diff --git a/.gitignore b/.gitignore index 3fa889bd..e3ebee38 100644 --- a/.gitignore +++ b/.gitignore @@ -121,10 +121,3 @@ docs/configuration-standardization.md # Rust target/ - -# Python -__pycache__/ -*.py[cod] -*.egg-info/ -.pytest_cache/ -.venv/ diff --git a/Cargo.lock b/Cargo.lock index 6899374a..11d01203 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -50,12 +50,6 @@ dependencies = [ "num-traits", ] -[[package]] -name = "array-const-fn-init" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8bcb85e548c05d407fa6faff46b750ba287714ef32afc0f5e15b4641ffd6affb" - [[package]] name = "arrayvec" version = "0.7.8" @@ -103,15 +97,6 @@ dependencies = [ "wyz", ] -[[package]] -name = "block-buffer" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" -dependencies = [ - "hybrid-array", -] - [[package]] name = "bson" version = "3.1.0" @@ -126,7 +111,6 @@ dependencies = [ "indexmap", "js-sys", "rand 0.9.5", - "serde", "serde_bytes", "simdutf8", "thiserror 2.0.21", @@ -170,17 +154,6 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" -[[package]] -name = "chacha20" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" -dependencies = [ - "cfg-if", - "cpufeatures", - "rand_core 0.10.1", -] - [[package]] name = "chrono" version = "0.4.45" @@ -195,28 +168,6 @@ dependencies = [ "windows-link", ] -[[package]] -name = "cmov" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" - -[[package]] -name = "combine" -version = "4.6.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" -dependencies = [ - "bytes", - "memchr", -] - -[[package]] -name = "const-oid" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" - [[package]] name = "const-random" version = "0.1.20" @@ -245,37 +196,12 @@ dependencies = [ "unicode-segmentation", ] -[[package]] -name = "core-foundation" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" -dependencies = [ - "core-foundation-sys", - "libc", -] - [[package]] name = "core-foundation-sys" version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" -[[package]] -name = "cpufeatures" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" -dependencies = [ - "libc", -] - -[[package]] -name = "critical-section" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" - [[package]] name = "crossbeam" version = "0.8.5" @@ -338,15 +264,6 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" -[[package]] -name = "crypto-common" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" -dependencies = [ - "hybrid-array", -] - [[package]] name = "ctor" version = "0.2.9" @@ -357,57 +274,12 @@ dependencies = [ "syn 2.0.119", ] -[[package]] -name = "ctutils" -version = "0.4.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" -dependencies = [ - "cmov", -] - [[package]] name = "curate-etl" version = "0.1.0" dependencies = [ "bson", - "mongodb", "parquet", - "rayon", -] - -[[package]] -name = "darling" -version = "0.24.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" -dependencies = [ - "darling_core", - "darling_macro", -] - -[[package]] -name = "darling_core" -version = "0.24.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" -dependencies = [ - "ident_case", - "proc-macro2", - "quote", - "strsim", - "syn 3.0.10", -] - -[[package]] -name = "darling_macro" -version = "0.24.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" -dependencies = [ - "darling_core", - "quote", - "syn 3.0.10", ] [[package]] @@ -423,69 +295,12 @@ dependencies = [ "parking_lot_core", ] -[[package]] -name = "data-encoding" -version = "2.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" - [[package]] name = "deranged" version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" -[[package]] -name = "derive-syn-parse" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d65d7ce8132b7c0e54497a4d9a55a1c2a0912a0d786cf894472ba818fba45762" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "derive-where" -version = "1.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e2b94854e8576378ccda7c8de8a66ed8b4e8acbd2c50ec3418ea6c8aaf4b567" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "digest" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" -dependencies = [ - "block-buffer", - "const-oid", - "crypto-common", - "ctutils", -] - -[[package]] -name = "displaydoc" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "either" -version = "1.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" - [[package]] name = "engine" version = "0.1.0" @@ -529,7 +344,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys", ] [[package]] @@ -538,59 +353,18 @@ version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" -[[package]] -name = "form_urlencoded" -version = "1.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" -dependencies = [ - "percent-encoding", -] - [[package]] name = "funty" version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" -[[package]] -name = "futures-channel" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" -dependencies = [ - "futures-core", -] - [[package]] name = "futures-core" version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" -[[package]] -name = "futures-io" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" - -[[package]] -name = "futures-macro" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "futures-sink" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" - [[package]] name = "futures-task" version = "0.3.34" @@ -604,10 +378,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ "futures-core", - "futures-io", - "futures-macro", "futures-task", - "memchr", "pin-project-lite", "slab", ] @@ -647,7 +418,6 @@ dependencies = [ "js-sys", "libc", "r-efi 6.0.0", - "rand_core 0.10.1", "wasm-bindgen", ] @@ -681,94 +451,6 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" -[[package]] -name = "hickory-net" -version = "0.26.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea9b43710d47761c90da994eeec7e1bee50095f2b4bcdfd42acd67ca5f814e47" -dependencies = [ - "async-trait", - "cfg-if", - "data-encoding", - "futures-channel", - "futures-io", - "futures-util", - "hickory-proto", - "idna", - "ipnet", - "jni", - "rand 0.10.4", - "thiserror 2.0.21", - "tinyvec", - "tokio", - "tracing", - "url", -] - -[[package]] -name = "hickory-proto" -version = "0.26.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "927c672dc4fd1e4b7cfcb7b751fe1d5766638080b8d243b78165ef660c2061e7" -dependencies = [ - "data-encoding", - "idna", - "ipnet", - "jni", - "once_cell", - "prefix-trie", - "rand 0.10.4", - "ring", - "thiserror 2.0.21", - "tinyvec", - "tracing", - "url", -] - -[[package]] -name = "hickory-resolver" -version = "0.26.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e847eb9a1b4e6bd038c2ff9400aff8ba02b450baa7f691bc56359c9af0418145" -dependencies = [ - "cfg-if", - "futures-util", - "hickory-net", - "hickory-proto", - "ipconfig", - "ipnet", - "jni", - "moka", - "ndk-context", - "once_cell", - "parking_lot", - "rand 0.10.4", - "resolv-conf", - "smallvec", - "system-configuration", - "thiserror 2.0.21", - "tokio", - "tracing", -] - -[[package]] -name = "hmac" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" -dependencies = [ - "digest", -] - -[[package]] -name = "hybrid-array" -version = "0.4.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" -dependencies = [ - "typenum", -] - [[package]] name = "iana-time-zone" version = "0.1.65" @@ -793,116 +475,6 @@ dependencies = [ "cc", ] -[[package]] -name = "icu_collections" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" -dependencies = [ - "displaydoc", - "potential_utf", - "utf8_iter", - "yoke", - "zerofrom", - "zerovec", -] - -[[package]] -name = "icu_locale_core" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" -dependencies = [ - "displaydoc", - "litemap", - "tinystr", - "writeable", - "zerovec", -] - -[[package]] -name = "icu_normalizer" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" -dependencies = [ - "icu_collections", - "icu_normalizer_data", - "icu_properties", - "icu_provider", - "smallvec", - "zerovec", -] - -[[package]] -name = "icu_normalizer_data" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" - -[[package]] -name = "icu_properties" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" -dependencies = [ - "displaydoc", - "icu_collections", - "icu_locale_core", - "icu_properties_data", - "icu_provider", - "zerotrie", - "zerovec", -] - -[[package]] -name = "icu_properties_data" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" - -[[package]] -name = "icu_provider" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" -dependencies = [ - "displaydoc", - "icu_locale_core", - "writeable", - "yoke", - "zerofrom", - "zerotrie", - "zerovec", -] - -[[package]] -name = "ident_case" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" - -[[package]] -name = "idna" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" -dependencies = [ - "idna_adapter", - "smallvec", - "utf8_iter", -] - -[[package]] -name = "idna_adapter" -version = "1.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" -dependencies = [ - "icu_normalizer", - "icu_properties", -] - [[package]] name = "indexmap" version = "2.14.2" @@ -913,83 +485,12 @@ dependencies = [ "hashbrown 0.17.2", ] -[[package]] -name = "ipconfig" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d40460c0ce33d6ce4b0630ad68ff63d6661961c48b6dba35e5a4d81cfb48222" -dependencies = [ - "socket2", - "widestring", - "windows-registry", - "windows-result", - "windows-sys 0.61.2", -] - -[[package]] -name = "ipnet" -version = "2.12.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "007d6e6b91097094791302ccc6cd0588e0700ddac5c6829035bcd71eff4dc433" -dependencies = [ - "serde", -] - [[package]] name = "itoa" version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" -[[package]] -name = "jni" -version = "0.22.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" -dependencies = [ - "cfg-if", - "combine", - "jni-macros", - "jni-sys", - "log", - "simd_cesu8", - "thiserror 2.0.21", - "walkdir", - "windows-link", -] - -[[package]] -name = "jni-macros" -version = "0.22.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" -dependencies = [ - "proc-macro2", - "quote", - "rustc_version", - "simd_cesu8", - "syn 2.0.119", -] - -[[package]] -name = "jni-sys" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" -dependencies = [ - "jni-sys-macros", -] - -[[package]] -name = "jni-sys-macros" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" -dependencies = [ - "quote", - "syn 2.0.119", -] - [[package]] name = "jobserver" version = "0.1.35" @@ -1039,12 +540,6 @@ version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" -[[package]] -name = "litemap" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" - [[package]] name = "lock_api" version = "0.4.14" @@ -1060,54 +555,6 @@ version = "0.4.35" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" -[[package]] -name = "macro_magic" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc33f9f0351468d26fbc53d9ce00a096c8522ecb42f19b50f34f2c422f76d21d" -dependencies = [ - "macro_magic_core", - "macro_magic_macros", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "macro_magic_core" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1687dc887e42f352865a393acae7cf79d98fab6351cde1f58e9e057da89bf150" -dependencies = [ - "const-random", - "derive-syn-parse", - "macro_magic_core_macros", - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "macro_magic_core_macros" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b02abfe41815b5bd98dbd4260173db2c116dda171dc0fe7838cb206333b83308" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "macro_magic_macros" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73ea28ee64b88876bf45277ed9a5817c1817df061a74f2b988971a12570e5869" -dependencies = [ - "macro_magic_core", - "quote", - "syn 2.0.119", -] - [[package]] name = "matrixmultiply" version = "0.3.11" @@ -1118,16 +565,6 @@ dependencies = [ "rawpointer", ] -[[package]] -name = "md-5" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98" -dependencies = [ - "cfg-if", - "digest", -] - [[package]] name = "memchr" version = "2.8.3" @@ -1142,99 +579,7 @@ checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" dependencies = [ "libc", "wasi", - "windows-sys 0.61.2", -] - -[[package]] -name = "moka" -version = "0.12.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4293f18e7567a1caf3c584855554377025c65e0aa445344d04171f5ad63d19b9" -dependencies = [ - "crossbeam-channel", - "crossbeam-epoch", - "crossbeam-utils", - "equivalent", - "parking_lot", - "portable-atomic", - "smallvec", - "tagptr", - "uuid", -] - -[[package]] -name = "mongocrypt" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8426a875ded61430d4a811dbfda7633b6b8af0225c547fc6c28b8b0aa7d79a13" -dependencies = [ - "bson", - "mongocrypt-sys", - "once_cell", - "serde", -] - -[[package]] -name = "mongocrypt-sys" -version = "0.1.6+1.18.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "851fac73f7fe22f6a3ab87f720ce509cae7c9fd08e7dd27866cc232dee07ccf4" - -[[package]] -name = "mongodb" -version = "3.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "526a3c2997c705268a415b470c16f97566dbe50ddf7e3bbe546d2f6f6b3782fc" -dependencies = [ - "base64", - "bitflags", - "bson", - "derive-where", - "futures-core", - "futures-io", - "futures-util", - "hex", - "hickory-net", - "hickory-proto", - "hickory-resolver", - "hmac", - "macro_magic", - "md-5", - "mongocrypt", - "mongodb-internal-macros", - "pbkdf2", - "percent-encoding", - "rand 0.9.5", - "rustc_version_runtime", - "rustls", - "serde", - "serde_bytes", - "serde_with", - "sha1", - "sha2", - "socket2", - "stringprep", - "strsim", - "take_mut", - "thiserror 2.0.21", - "tokio", - "tokio-rustls", - "tokio-util", - "typed-builder", - "uuid", - "webpki-roots", -] - -[[package]] -name = "mongodb-internal-macros" -version = "3.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c017252390a069993944881e7c411c2cc68a614cadb12a92a3da6f56b2f8da8" -dependencies = [ - "macro_magic", - "proc-macro2", - "quote", - "syn 2.0.119", + "windows-sys", ] [[package]] @@ -1354,19 +699,13 @@ dependencies = [ "libloading", ] -[[package]] -name = "ndk-context" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" - [[package]] name = "nu-ansi-term" version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.61.2", + "windows-sys", ] [[package]] @@ -1439,10 +778,6 @@ name = "once_cell" version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" -dependencies = [ - "critical-section", - "portable-atomic", -] [[package]] name = "parking_lot" @@ -1492,21 +827,6 @@ version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" -[[package]] -name = "pbkdf2" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "112d82ceb8c5bf524d9af484d4e4970c9fd5a0cc15ba14ad93dccd28873b0629" -dependencies = [ - "digest", -] - -[[package]] -name = "percent-encoding" -version = "2.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" - [[package]] name = "pin-project-lite" version = "0.2.18" @@ -1519,21 +839,6 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" -[[package]] -name = "portable-atomic" -version = "1.15.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" - -[[package]] -name = "potential_utf" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" -dependencies = [ - "zerovec", -] - [[package]] name = "powerfmt" version = "0.2.1" @@ -1549,19 +854,6 @@ dependencies = [ "zerocopy", ] -[[package]] -name = "prefix-trie" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77fe9ec8fb906114b52bc2e9aa142ac11817d0fcd33a32fb2feb94d823ad9a4d" -dependencies = [ - "array-const-fn-init", - "either", - "ipnet", - "num-traits", - "smallvec", -] - [[package]] name = "proc-macro2" version = "1.0.107" @@ -1619,17 +911,6 @@ dependencies = [ "rand_core 0.9.5", ] -[[package]] -name = "rand" -version = "0.10.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" -dependencies = [ - "chacha20", - "getrandom 0.4.3", - "rand_core 0.10.1", -] - [[package]] name = "rand_chacha" version = "0.3.1" @@ -1668,12 +949,6 @@ dependencies = [ "getrandom 0.3.4", ] -[[package]] -name = "rand_core" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" - [[package]] name = "rand_distr" version = "0.4.3" @@ -1690,26 +965,6 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3" -[[package]] -name = "rayon" -version = "1.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" -dependencies = [ - "either", - "rayon-core", -] - -[[package]] -name = "rayon-core" -version = "1.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" -dependencies = [ - "crossbeam-deque", - "crossbeam-utils", -] - [[package]] name = "redox_syscall" version = "0.5.18" @@ -1748,26 +1003,6 @@ version = "0.8.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" -[[package]] -name = "resolv-conf" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e061d1b48cb8d38042de4ae0a7a6401009d6143dc80d2e2d6f31f0bdd6470c7" - -[[package]] -name = "ring" -version = "0.17.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" -dependencies = [ - "cc", - "cfg-if", - "getrandom 0.2.17", - "libc", - "untrusted", - "windows-sys 0.52.0", -] - [[package]] name = "rust_decimal" version = "1.43.0" @@ -1778,60 +1013,6 @@ dependencies = [ "num-traits", ] -[[package]] -name = "rustc_version" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" -dependencies = [ - "semver", -] - -[[package]] -name = "rustc_version_runtime" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2dd18cd2bae1820af0b6ad5e54f4a51d0f3fcc53b05f845675074efcc7af071d" -dependencies = [ - "rustc_version", - "semver", -] - -[[package]] -name = "rustls" -version = "0.23.46" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" -dependencies = [ - "log", - "once_cell", - "ring", - "rustls-pki-types", - "rustls-webpki", - "subtle", - "zeroize", -] - -[[package]] -name = "rustls-pki-types" -version = "1.16.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" -dependencies = [ - "zeroize", -] - -[[package]] -name = "rustls-webpki" -version = "0.103.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" -dependencies = [ - "ring", - "rustls-pki-types", - "untrusted", -] - [[package]] name = "rustversion" version = "1.0.23" @@ -1847,15 +1028,6 @@ dependencies = [ "bytemuck", ] -[[package]] -name = "same-file" -version = "1.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" -dependencies = [ - "winapi-util", -] - [[package]] name = "scopeguard" version = "1.2.0" @@ -1927,50 +1099,6 @@ dependencies = [ "zmij", ] -[[package]] -name = "serde_with" -version = "3.25.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56cb1ca7c93ae63d6439b5250f6b6b040f7e121f32e5dd2f5d523dd4149b3204" -dependencies = [ - "serde_core", - "serde_with_macros", -] - -[[package]] -name = "serde_with_macros" -version = "3.25.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cff15a7c864bbec77d9586ca6822bc7c369bdf19e9243134a62b0b51ce26b31f" -dependencies = [ - "darling", - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "sha1" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214" -dependencies = [ - "cfg-if", - "cpufeatures", - "digest", -] - -[[package]] -name = "sha2" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b0e5c7d67bc53f435386b2130fdc900488c5703770f6d8a4633060e34288a27" -dependencies = [ - "cfg-if", - "cpufeatures", - "digest", -] - [[package]] name = "sharded-slab" version = "0.1.7" @@ -2022,16 +1150,6 @@ dependencies = [ "wide", ] -[[package]] -name = "simd_cesu8" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" -dependencies = [ - "rustc_version", - "simdutf8", -] - [[package]] name = "simdutf8" version = "0.1.5" @@ -2057,15 +1175,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys", ] -[[package]] -name = "stable_deref_trait" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" - [[package]] name = "statrs" version = "0.16.1" @@ -2079,29 +1191,6 @@ dependencies = [ "rand 0.8.8", ] -[[package]] -name = "stringprep" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1" -dependencies = [ - "unicode-bidi", - "unicode-normalization", - "unicode-properties", -] - -[[package]] -name = "strsim" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" - -[[package]] -name = "subtle" -version = "2.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" - [[package]] name = "syn" version = "1.0.109" @@ -2135,50 +1224,6 @@ dependencies = [ "unicode-ident", ] -[[package]] -name = "synstructure" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "system-configuration" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "501336eb7ba9e417300a6a0fa985721065467aa83a6dcf0422a8e43e4c0328fa" -dependencies = [ - "bitflags", - "core-foundation", - "system-configuration-sys", -] - -[[package]] -name = "system-configuration-sys" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" -dependencies = [ - "core-foundation-sys", - "libc", -] - -[[package]] -name = "tagptr" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b2093cf4c8eb1e67749a6762251bc9cd836b6fc171623bd0a9d324d37af2417" - -[[package]] -name = "take_mut" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f764005d11ee5f36500a149ace24e00e3da98b0158b3e2d53a7495660d3f4d60" - [[package]] name = "tap" version = "1.0.1" @@ -2273,22 +1318,6 @@ dependencies = [ "crunchy", ] -[[package]] -name = "tinystr" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" -dependencies = [ - "displaydoc", - "zerovec", -] - -[[package]] -name = "tinyvec" -version = "1.13.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" - [[package]] name = "tokio" version = "1.54.1" @@ -2303,7 +1332,7 @@ dependencies = [ "signal-hook-registry", "socket2", "tokio-macros", - "windows-sys 0.61.2", + "windows-sys", ] [[package]] @@ -2317,31 +1346,6 @@ dependencies = [ "syn 3.0.10", ] -[[package]] -name = "tokio-rustls" -version = "0.26.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" -dependencies = [ - "rustls", - "tokio", -] - -[[package]] -name = "tokio-util" -version = "0.7.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" -dependencies = [ - "bytes", - "futures-core", - "futures-io", - "futures-sink", - "futures-util", - "pin-project-lite", - "tokio", -] - [[package]] name = "tracing" version = "0.1.44" @@ -2405,98 +1409,24 @@ version = "2.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "86a801b3cea342a06d468c8710662aa29e5e05e4f5c0d62f00bbb7f2ad7941c2" -[[package]] -name = "typed-builder" -version = "0.22.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "398a3a3c918c96de527dc11e6e846cd549d4508030b8a33e1da12789c856b81a" -dependencies = [ - "typed-builder-macro", -] - -[[package]] -name = "typed-builder-macro" -version = "0.22.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e48cea23f68d1f78eb7bc092881b6bb88d3d6b5b7e6234f6f9c911da1ffb221" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "typenum" version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" -[[package]] -name = "unicode-bidi" -version = "0.3.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" - [[package]] name = "unicode-ident" version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" -[[package]] -name = "unicode-normalization" -version = "0.1.26" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" -dependencies = [ - "tinyvec", -] - -[[package]] -name = "unicode-properties" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "993ad287eb20e8ba755312801cfe1413e0f25d604075863acaddca10b04c1833" - [[package]] name = "unicode-segmentation" version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" -[[package]] -name = "untrusted" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" - -[[package]] -name = "url" -version = "2.5.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" -dependencies = [ - "form_urlencoded", - "idna", - "percent-encoding", - "serde", -] - -[[package]] -name = "utf8_iter" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" -dependencies = [ - "utf_types", -] - -[[package]] -name = "utf_types" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" - [[package]] name = "uuid" version = "1.18.1" @@ -2521,16 +1451,6 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" -[[package]] -name = "walkdir" -version = "2.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b42e295b7452c4604982280d8586001fcad9b8b201cac67bca9771e7a7475403" -dependencies = [ - "same-file", - "winapi-util", -] - [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" @@ -2590,15 +1510,6 @@ dependencies = [ "unicode-ident", ] -[[package]] -name = "webpki-roots" -version = "1.0.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" -dependencies = [ - "rustls-pki-types", -] - [[package]] name = "wide" version = "0.7.33" @@ -2609,21 +1520,6 @@ dependencies = [ "safe_arch", ] -[[package]] -name = "widestring" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72069c3113ab32ab29e5584db3c6ec55d416895e60715417b5b883a357c3e471" - -[[package]] -name = "winapi-util" -version = "0.1.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" -dependencies = [ - "windows-sys 0.61.2", -] - [[package]] name = "windows-core" version = "0.62.2" @@ -2665,17 +1561,6 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" -[[package]] -name = "windows-registry" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" -dependencies = [ - "windows-link", - "windows-result", - "windows-strings", -] - [[package]] name = "windows-result" version = "0.4.1" @@ -2694,15 +1579,6 @@ dependencies = [ "windows-link", ] -[[package]] -name = "windows-sys" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" -dependencies = [ - "windows-targets", -] - [[package]] name = "windows-sys" version = "0.61.2" @@ -2712,82 +1588,12 @@ dependencies = [ "windows-link", ] -[[package]] -name = "windows-targets" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" -dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_gnullvm", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", -] - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" - -[[package]] -name = "windows_i686_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" - -[[package]] -name = "windows_i686_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" - -[[package]] -name = "windows_i686_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" - [[package]] name = "wit-bindgen" version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" -[[package]] -name = "writeable" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" - [[package]] name = "wyz" version = "0.5.1" @@ -2797,29 +1603,6 @@ dependencies = [ "tap", ] -[[package]] -name = "yoke" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" -dependencies = [ - "stable_deref_trait", - "yoke-derive", - "zerofrom", -] - -[[package]] -name = "yoke-derive" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", - "synstructure", -] - [[package]] name = "zerocopy" version = "0.8.66" @@ -2840,66 +1623,6 @@ dependencies = [ "syn 2.0.119", ] -[[package]] -name = "zerofrom" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" -dependencies = [ - "zerofrom-derive", -] - -[[package]] -name = "zerofrom-derive" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", - "synstructure", -] - -[[package]] -name = "zeroize" -version = "1.9.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" - -[[package]] -name = "zerotrie" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" -dependencies = [ - "displaydoc", - "yoke", - "zerofrom", -] - -[[package]] -name = "zerovec" -version = "0.11.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" -dependencies = [ - "yoke", - "zerofrom", - "zerovec-derive", -] - -[[package]] -name = "zerovec-derive" -version = "0.11.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - [[package]] name = "zmij" version = "1.0.23" diff --git a/apps/stock/data-pipeline/README.md b/apps/stock/data-pipeline/README.md index bca66ac1..6664a2b0 100644 --- a/apps/stock/data-pipeline/README.md +++ b/apps/stock/data-pipeline/README.md @@ -206,128 +206,3 @@ All four files are deterministic and byte-identical for identical inputs (no wal - `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`). - -## Read-Only Source Field-Shape Probe (`source-field-shapes.ts`) -`apps/stock/data-pipeline/src/security-master/source-field-shapes.ts` and its CLI `probe-source-field-shapes.ts` sample raw MongoDB collections read-only to report exact field names, BSON/JS value types (`string`, `int`, `double`, `bool`, `date`, `null`, `objectId`, `array`, `object`, `other`), one-level nested `parent.child` keys, string pattern classes (`ymd`, `isoDatetime`, `numeric`, `emptyOrWhitespace`, `other`), and bounded sanitized examples (never emitted for `_id` / `_id.*`). - -- **Bounded read-only contract:** Initializes config with `mongoReadOnly: true`, connects via `MONGODB_READ_URI` (`studio_stock_bot_read@stock`), refuses non-read-only readers before issuing any query, and runs strictly `find({}, { limit, promoteValues: false, promoteLongs: false })` (default `limit = 1,000`, max `10,000`) over allowlisted collections (`ceoShorts`, `qmSplits`, `qmDividends`, `qmFilings`, `qmEarnings`, `qmPrices`, `eodPrices`, `teMarketData`) — no aggregations, no `$sample`, no writes, and no index operations. -- **Host live-run command (read-only QA MongoDB):** - -```bash -MONGODB_READ_URI="mongodb://studio_stock_bot_read:@localhost:27017/stock?authSource=stock" \ - bun run apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts \ - --out ./tmp/source-field-shapes.md \ - --limit 1000 -``` - -- **Local synthetic benchmark (zero MongoDB):** Run the fixed-seed 80,000-doc streaming benchmark (`8` collections × `10,000` limit) with: - -```bash -bun run apps/stock/data-pipeline/benchmarks/source-field-shapes-benchmark.ts -``` - -- **Recorded baselines (`2026-11-28`, local sandbox, in-memory async cursor fake reader):** - - Workload: `80,000` synthetic docs (`8` collections × `10,000` limit) with mixed BSON/JS types, one-level nested objects, and all five string pattern classes, including `renderFieldShapesMarkdown`. - - Initial implementation: `442,496 docs/s` (`180.8 ms` elapsed, `28.50 MiB` heap delta). - - After path-segment escaping, exact defensive sample cap, and GFM/HTML-safe cell formatting: `365,756 docs/s` (`218.7 ms` elapsed, `27.66 MiB` heap delta). - -## Read-Only Curate-ETL TSV Exporter (`export-curate-inputs.ts`) -`apps/stock/data-pipeline/src/security-master/export-curate-inputs.ts` and its CLI `run-export-curate-inputs.ts` read the PostgreSQL security-master tables strictly read-only inside a `REPEATABLE READ READ ONLY` transaction (bounded chunks `<= 5,000`, using a server-side `NO SCROLL` cursor for `provider_mapping`) and atomically publish each complete three-file set as an immutable generation under `/generations/` through a single atomic `/current` symlink commit point (`--chunk-size` is optional; default `5000`, max `5000`): - -```bash -NODE_ENV=development \ -POSTGRES_HOST=localhost \ -POSTGRES_PORT=5433 \ -POSTGRES_DATABASE=trading_bot_dev \ - bun run apps/stock/data-pipeline/src/security-master/run-export-curate-inputs.ts \ - --out-dir ./tmp/curate-inputs \ - --chunk-size 5000 -``` - -- **Immutable snapshot layout & consumer pinning:** - - Each export writes all three TSVs into `/generations//` and serializes top-level link setup, commit (`/current -> generations/`), and rollback behind `/.publish.lock`. Top-level symlinks (`/provider_mapping.tsv`, `/listing_currencies.tsv`, `/delistings.tsv`) point through `current/`. - - Multi-TSV Rust commands pin the active generation once before opening any TSV via `--curate-inputs ` (e.g. `curate-etl curate-corporate-actions --qm-splits qmSplits.bson --qm-dividends qmDividends.bson --curate-inputs ./tmp/curate-inputs --out ./out` and `curate-etl curate-bars-1d --eod-prices eodPrices.bson --qm-splits qmSplits.bson --curate-inputs ./tmp/curate-inputs --out ./out`), and TypeScript consumers can pin via `pinCurateInputSnapshot(outDir)` so concurrent refreshes never mix files from different PostgreSQL snapshots. -- **Output files:** - - `provider_mapping.tsv` — `source \t source_id \t valid_from \t valid_to(or empty) \t listing_id`, sorted in `COLLATE "C"` ASCII order, preserving non-blank values verbatim and failing closed on `\t`/`\n`/`\r`, duplicates, or overlapping inclusive ranges. - - `listing_currencies.tsv` — `listing_id \t currency`, sorted by ascending `listing_id`. - - `delistings.tsv` — Pass 6 delistings (`source_id \t delist_date \t from_listing_id \t successor_source_id(or empty) \t terminal_return(or empty)`), resolved against `qm` mappings (`valid_from <= effective_date` for outgoing OTC transfers, valid on `effective_date` for OTC successors, valid on `listed_to` for terminal delistings) and indexed by `from_listing_id` so OTC successors (e.g. `SIVBQ`) still emit their own terminal delisting. -- **Skip-reason accounting (`rowsIn === rowsOut + skippedTotal`):** - - `active`: active listings (no delisting row emitted; fails closed if an `active` listing has a continuity or `terminal_return`). - - `noOutcome`: non-active listings with neither an outgoing `otc_delist_transfer` nor a `terminal_return`. - - `missingListedTo`: terminal-return listings with `listed_to IS NULL`. - - `missingOutgoingQmMapping`: delisting/OTC candidates without a qualifying outgoing `qm` mapping. - - `missingSuccessorQmMapping`: OTC transfers whose successor listing has no `qm` mapping valid on `effective_date`. - - `nonOtcContinuity`: non-`otc_delist_transfer` continuities skipped in the pure `buildDelistingExportRows` builder. -- **Local synthetic benchmark (zero PostgreSQL):** Run the fixed-seed 500,000-mapping / 100,000-listing streaming benchmark with: - -```bash -bun run apps/stock/data-pipeline/benchmarks/export-curate-inputs-benchmark.ts -``` - -- **Recorded baseline (`2026-11-29`, local sandbox, in-memory cursor/keyset queryable, `chunkSize = 5000`):** - - Workload: `500,000` `provider_mapping` rows, `100,000` `listing` rows, `2,000` OTC continuities, terminal delistings, and skipped rows (`606,680` exported rows, `17,203,861` bytes written across all three TSVs). - - Observed throughput: `1,506,181 rows/s` (`402.8 ms` elapsed, `277.01 MiB` peak RSS). - -## Read-Only Raw-BSON Exporter (`export-raw-bson.ts`) -`apps/stock/data-pipeline/src/security-master/export-raw-bson.ts` and its CLI `run-export-raw-bson.ts` stream M1 allowlisted MongoDB collections directly to `/.bson` as untouched length-prefixed raw BSON bytes (`find(filter, { raw: true, batchSize })` — zero per-document JS decoding), validating every frame (`byteLength >= 5`, `<= 16 MiB + 16 KiB`, 4-byte LE length prefix `=== byteLength`, trailing `0x00`), coalescing writes through a fixed-size 8 MiB buffer with strict backpressure, computing an incremental SHA-256 digest, and publishing atomically via a same-directory temp file (`open('wx')` -> `write` -> `sync` -> `close` -> `rename`). - -- **Allowlisted collections (`RAW_BSON_EXPORT_COLLECTIONS`):** `eodPrices`, `qmSplits`, `qmDividends`, `qmPrices`, `teMarketData`, `ceoShorts`, `qmFilings`, `qmEarnings`. Any other collection (including M2 collections such as `eodIntraday1M`, `qmIntraday`, `qmFinancials`, `ceoPosts`) is rejected before any MongoDB call. -- **Flags:** - - `--out-dir ` *(required)* — destination directory for `.bson` files. - - `--collections ` *(optional)* — comma-separated subset of allowlisted collections (defaults to all 8). - - `--eod-symbol ` *(optional)* — exact `{ eodSearchCode: }` filter; only permitted when `--collections` is strictly `eodPrices` (for example `CAD.FOREX` for `curate-fx-1d`). Use a **separate `--out-dir`** so a filtered slice never overwrites the full `eodPrices.bson`. - - `--te-symbol ` *(optional)* — exact `{ teSymbol: }` filter; only permitted when `--collections` is strictly `teMarketData` (for example `USDCAD`). - - `--limit ` *(optional)* — positive integer document cap per collection for smoke runs. - - `--batch-size ` *(optional)* — MongoDB cursor `batchSize` (`1..100000`, default `4096`). - - `--help` — print usage and exit with zero config/Mongo/fs I/O. -- **Read-only safety:** Initializes config via `initializeStockConfig('dataPipeline', { mongoReadOnly: true })`, enforces `assertEnvironmentSafety()` via `assertExportRawBsonSafety()`, connects through `resolveReadOnlyMongoClientConfig()`, issues strictly `find(..., { raw: true })`, and always closes the MongoDB client in `finally`. Running against live QA MongoDB is a **separate manual host step** (never executed by automated tests or benchmarks). - -### Full M1 Step 2 Chain Order (Manual Host Run) -1. **Export PostgreSQL security-master TSVs (`run-export-curate-inputs.ts`):** -```bash -NODE_ENV=development \ -POSTGRES_HOST=localhost \ -POSTGRES_PORT=5433 \ -POSTGRES_DATABASE=trading_bot_dev \ - bun run apps/stock/data-pipeline/src/security-master/run-export-curate-inputs.ts \ - --out-dir ./tmp/curate-inputs -``` -2. **Export raw BSON collections from read-only QA MongoDB (`run-export-raw-bson.ts`):** -```bash -MONGODB_READ_URI="mongodb://studio_stock_bot_read:@localhost:27017/stock?authSource=stock" \ - bun run apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts \ - --out-dir ./tmp/raw-bson \ - --collections eodPrices,qmSplits,qmDividends,qmPrices,ceoShorts,qmFilings,qmEarnings - -# Export filtered FX inputs to a separate directory so full eodPrices.bson is not overwritten: -MONGODB_READ_URI="mongodb://studio_stock_bot_read:@localhost:27017/stock?authSource=stock" \ - bun run apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts \ - --out-dir ./tmp/raw-bson-fx \ - --collections eodPrices \ - --eod-symbol CAD.FOREX - -MONGODB_READ_URI="mongodb://studio_stock_bot_read:@localhost:27017/stock?authSource=stock" \ - bun run apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts \ - --out-dir ./tmp/raw-bson-fx \ - --collections teMarketData \ - --te-symbol USDCAD -``` -3. **Run `tools/curate-etl` commands (`curate-bars-1d` first, then the remaining datasets):** - - `curate-etl curate-bars-1d` (`--eod-prices ./tmp/raw-bson/eodPrices.bson`, `--qm-splits ./tmp/raw-bson/qmSplits.bson`, `--qm-prices ./tmp/raw-bson/qmPrices.bson`, `--curate-inputs ./tmp/curate-inputs`, `--out ./tmp/curated` — writes `./tmp/curated/bars_1d/year=YYYY/part.parquet` and prints read-only `qmPrices.sharevolume` cross-check stats) - - `curate-etl curate-adj-factors` (`--qm-splits ./tmp/raw-bson/qmSplits.bson`, `--qm-dividends ./tmp/raw-bson/qmDividends.bson`, `--provider-mapping ./tmp/curate-inputs/current/provider_mapping.tsv`, `--bars-1d ./tmp/curated/bars_1d`, `--out ./tmp/curated`) - - `curate-etl curate-corporate-actions` (`--qm-splits ./tmp/raw-bson/qmSplits.bson`, `--qm-dividends ./tmp/raw-bson/qmDividends.bson`, `--curate-inputs ./tmp/curate-inputs`, `--out ./tmp/curated`) - - `curate-etl curate-fx-1d` (`--eod-prices ./tmp/raw-bson-fx/eodPrices.bson`, `--te-market-data ./tmp/raw-bson-fx/teMarketData.bson`, `--out ./tmp/curated`) - - `curate-etl curate-shorts` (`--ceo-shorts ./tmp/raw-bson/ceoShorts.bson`, `--provider-mapping ./tmp/curate-inputs/current/provider_mapping.tsv`, `--out ./tmp/curated`, plus required `--shares-short-field `) - - `curate-etl curate-events` (`--qm-filings ./tmp/raw-bson/qmFilings.bson`, `--qm-earnings ./tmp/raw-bson/qmEarnings.bson`, `--provider-mapping ./tmp/curate-inputs/current/provider_mapping.tsv`, `--out ./tmp/curated`, plus required `--filings-form-type-field `) - -- **Local synthetic benchmark (zero MongoDB):** Run the fixed-seed 1,000,000-doc streaming benchmark with: - -```bash -bun run apps/stock/data-pipeline/benchmarks/export-raw-bson-benchmark.ts -``` - -- **Recorded baseline (`2026-11-29`, local sandbox, in-memory async cursor fake source, `writeBufferBytes = 8 MiB`):** - - Workload: `1,000,000` synthetic `eodPrices` raw BSON frames (`123.9 B` avg, `123,863,264` bytes written, deterministic `sha256=67f035eba7060d6312f3d5faecc9e6a6fa14f6239c0c4dc1859794b4cd895886`). - - Run 1 (`1,000,000` docs): `3,574,267 docs/s`, `422.21 MiB/s` (`279.8 ms` elapsed, `rss_before=97.00 MiB`, `rss_after=149.91 MiB`, `peak_rss=150.19 MiB`). - - Run 2 (`1,000,000` docs): `3,692,715 docs/s`, `436.20 MiB/s` (`270.8 ms` elapsed, `peak_rss=151.03 MiB`, identical `sha256`). - - Scaling check (`2,000,000` docs, `247,726,576` bytes): `3,833,075 docs/s`, `452.78 MiB/s` (`521.8 ms` elapsed, `peak_rss=146.88 MiB` — confirms peak RSS stays bounded independent of document count). diff --git a/apps/stock/data-pipeline/benchmarks/export-curate-inputs-benchmark.ts b/apps/stock/data-pipeline/benchmarks/export-curate-inputs-benchmark.ts deleted file mode 100644 index f23a8a02..00000000 --- a/apps/stock/data-pipeline/benchmarks/export-curate-inputs-benchmark.ts +++ /dev/null @@ -1,292 +0,0 @@ -/** - * Reproducible headless benchmark for `exportCurateInputs`. - * Streams 500,000 `provider_mapping` rows + 100,000 `listing` rows + 2,000 OTC continuities + - * terminal delistings + skipped rows through an in-memory keyset-paginated - * `SecurityMasterQueryable` into a temporary directory (cleaned up in `finally`), with zero - * database or network dependencies. - * - * Usage: - * bun run apps/stock/data-pipeline/benchmarks/export-curate-inputs-benchmark.ts - */ - -import { mkdtemp, rm } from 'node:fs/promises'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import { - DEFAULT_EXPORT_CHUNK_SIZE, - exportCurateInputs, - type SecurityMasterQueryable, - type SecurityMasterQueryResult, -} from '../src/security-master/export-curate-inputs'; - -const LISTING_COUNT = 100_000; -const PROVIDER_MAPPING_COUNT = 500_000; -const OTC_CONTINUITY_COUNT = 2_000; - -interface BenchContinuityRow { - from_listing_id: number; - to_listing_id: number; - effective_date: string; - kind: string; -} - -interface BenchListingRow { - listing_id: number; - currency: string; - listed_to: string | null; - delist_reason: string | null; - terminal_return: string | null; -} - -interface BenchMappingRow { - source: string; - source_id: string; - valid_from: string; - valid_to: string | null; - listing_id: number; -} - -/** - * Generates deterministic sorted synthetic rows (matching PostgreSQL ORDER BY): - * - 100,000 listings: - * - 1..2000: OTC outgoing listings (moved_to_otc -> successor listing_id + 2000) - * - 2001..4000: OTC successor listings (half bankruptcy_cancelled -1.0, half active) - * - 4001..8000: terminal delistings (-0.3; every 20th has listed_to = null -> missingListedTo) - * - 8001..10000: delisted with null outcome (noOutcome) - * - 10001..100000: active US/CA listings - * - 500,000 provider_mapping rows in strict ASCII COLLATE "C" order across 5 sources: - * ceo (100k), eod (100k), ib (100k), qm (100k), te (100k). - * For a small deterministic subset of listings, omit the `qm` mapping (assign to listing 10001) - * so missingOutgoingQmMapping and missingSuccessorQmMapping are exercised too. - */ -function buildSyntheticTables(): { - continuities: BenchContinuityRow[]; - listings: BenchListingRow[]; - mappings: BenchMappingRow[]; -} { - const continuities = new Array(OTC_CONTINUITY_COUNT); - for (let i = 0; i < OTC_CONTINUITY_COUNT; i++) { - const fromId = i + 1; - continuities[i] = { - from_listing_id: fromId, - to_listing_id: fromId + OTC_CONTINUITY_COUNT, - effective_date: '2023-03-28', - kind: 'otc_delist_transfer', - }; - } - - const listings = new Array(LISTING_COUNT); - for (let i = 0; i < LISTING_COUNT; i++) { - const id = i + 1; - const currency = id % 5 === 0 ? 'CAD' : 'USD'; - if (id <= OTC_CONTINUITY_COUNT) { - listings[i] = { - listing_id: id, - currency, - listed_to: '2023-03-10', - delist_reason: 'moved_to_otc', - terminal_return: null, - }; - } else if (id <= OTC_CONTINUITY_COUNT * 2) { - if (id % 2 === 0) { - listings[i] = { - listing_id: id, - currency, - listed_to: '2024-11-07', - delist_reason: 'bankruptcy_cancelled', - terminal_return: '-1.000000', - }; - } else { - listings[i] = { - listing_id: id, - currency, - listed_to: null, - delist_reason: 'active', - terminal_return: null, - }; - } - } else if (id <= 8_000) { - const missingDate = id % 20 === 0; - listings[i] = { - listing_id: id, - currency, - listed_to: missingDate ? null : '2023-06-15', - delist_reason: 'unknown_involuntary', - terminal_return: '-0.300000', - }; - } else if (id <= 10_000) { - listings[i] = { - listing_id: id, - currency, - listed_to: '2022-12-30', - delist_reason: null, - terminal_return: null, - }; - } else { - listings[i] = { - listing_id: id, - currency, - listed_to: null, - delist_reason: 'active', - terminal_return: null, - }; - } - } - - // 5 sources in strict ASCII order: ceo, eod, ib, qm, te (100,000 rows each = 500,000 total). - const sources = ['ceo', 'eod', 'ib', 'qm', 'te'] as const; - const mappings = new Array(PROVIDER_MAPPING_COUNT); - let idx = 0; - for (const source of sources) { - for (let i = 0; i < LISTING_COUNT; i++) { - const naturalListingId = i + 1; - const padded = String(naturalListingId).padStart(6, '0'); - let listingId = naturalListingId; - let validFrom = '2015-01-02'; - let validTo: string | null = null; - - if (naturalListingId <= OTC_CONTINUITY_COUNT) { - validTo = '2023-03-10'; - // Drop QM mapping for every 40th outgoing OTC listing (redirect to active listing 10001). - if (source === 'qm' && naturalListingId % 40 === 0) { - listingId = 10_001; - } - } else if (naturalListingId <= OTC_CONTINUITY_COUNT * 2) { - validFrom = '2023-03-28'; - validTo = naturalListingId % 2 === 0 ? '2024-11-07' : null; - // Drop QM mapping for every 50th successor OTC listing. - if (source === 'qm' && naturalListingId % 50 === 0) { - listingId = 10_002; - } - } else if (naturalListingId <= 8_000) { - validTo = '2023-06-15'; - } - - mappings[idx++] = { - source, - source_id: `SYM${padded}`, - valid_from: validFrom, - valid_to: validTo, - listing_id: listingId, - }; - } - } - - return { continuities, listings, mappings }; -} - -function createFastPaginatedQueryable(tables: { - continuities: BenchContinuityRow[]; - listings: BenchListingRow[]; - mappings: BenchMappingRow[]; -}): SecurityMasterQueryable { - let contOffset = 0; - let listingOffset = 0; - let mappingOffset = 0; - - return { - async query>( - text: string, - values?: readonly unknown[] - ): Promise> { - const normalized = text.replace(/\s+/g, ' ').trim(); - if (normalized.startsWith('BEGIN')) { - contOffset = 0; - listingOffset = 0; - mappingOffset = 0; - return { rows: [] }; - } - if (normalized === 'COMMIT' || normalized === 'ROLLBACK') { - return { rows: [] }; - } - if (normalized.startsWith('DECLARE ') && normalized.includes('FROM provider_mapping')) { - mappingOffset = 0; - return { rows: [] }; - } - const fetchMatch = /^FETCH FORWARD (\d+) FROM \S+$/i.exec(normalized); - if (fetchMatch) { - const fetchLimit = Number(fetchMatch[1]); - const slice = tables.mappings.slice(mappingOffset, mappingOffset + fetchLimit); - mappingOffset += slice.length; - return { rows: slice as unknown as Row[] }; - } - if (/^CLOSE \S+$/i.test(normalized)) { - return { rows: [] }; - } - - const limit = values ? (values[values.length - 1] as number) : DEFAULT_EXPORT_CHUNK_SIZE; - - if (normalized.includes('FROM corporate_action_continuity')) { - const slice = tables.continuities.slice(contOffset, contOffset + limit); - contOffset += slice.length; - return { rows: slice as unknown as Row[] }; - } - if (normalized.includes('FROM listing')) { - const slice = tables.listings.slice(listingOffset, listingOffset + limit); - listingOffset += slice.length; - return { rows: slice as unknown as Row[] }; - } - if (normalized.includes('FROM provider_mapping')) { - const slice = tables.mappings.slice(mappingOffset, mappingOffset + limit); - mappingOffset += slice.length; - return { rows: slice as unknown as Row[] }; - } - - throw new Error(`Unexpected SQL in benchmark queryable: ${normalized}`); - }, - release: () => {}, - }; -} - -async function main(): Promise { - const tables = buildSyntheticTables(); - const queryable = createFastPaginatedQueryable(tables); - const outDir = await mkdtemp(join(tmpdir(), 'curate-inputs-bench-')); - - try { - const startNs = Bun.nanoseconds(); - const result = await exportCurateInputs(queryable, { - outDir, - chunkSize: DEFAULT_EXPORT_CHUNK_SIZE, - }); - const elapsedMs = (Bun.nanoseconds() - startNs) / 1e6; - - const d = result.delistings.stats; - const skipSum = - d.skipped.active + - d.skipped.noOutcome + - d.skipped.missingListedTo + - d.skipped.missingOutgoingQmMapping + - d.skipped.missingSuccessorQmMapping + - d.skipped.nonOtcContinuity; - if (d.skippedTotal !== skipSum || d.rowsIn !== d.rowsOut + d.skippedTotal) { - throw new Error( - `Delisting stats reconciliation failed: rowsIn=${d.rowsIn} rowsOut=${d.rowsOut} skippedTotal=${d.skippedTotal} skipSum=${skipSum}` - ); - } - - const totalRowsExported = - result.providerMapping.rowsOut + result.listingCurrencies.rowsOut + result.delistings.rowsOut; - const rowsPerSec = totalRowsExported / (elapsedMs / 1000); - // process.resourceUsage().maxRSS is reported in KiB on Linux. - const peakRssMiB = process.resourceUsage().maxRSS / 1024; - - process.stdout.write('exportCurateInputs benchmark complete\n'); - process.stdout.write( - ` inputs: provider_mapping=${PROVIDER_MAPPING_COUNT} listings=${LISTING_COUNT} otc_continuities=${OTC_CONTINUITY_COUNT}\n` - ); - process.stdout.write( - ` exported: provider_mapping=${result.providerMapping.rowsOut} listing_currencies=${result.listingCurrencies.rowsOut} delistings=${result.delistings.rowsOut} (otc=${d.otcTransfersOut} terminal=${d.terminalDelistingsOut} skipped=${d.skippedTotal})\n` - ); - process.stdout.write( - ` total_rows_out=${totalRowsExported} bytes_written=${result.totalBytesWritten} elapsed_ms=${elapsedMs.toFixed(1)} throughput=${Math.round(rowsPerSec)} rows/s peak_rss=${peakRssMiB.toFixed(2)} MiB\n` - ); - } finally { - await rm(outDir, { recursive: true, force: true }); - } -} - -main().catch(error => { - process.stderr.write(`${error instanceof Error ? error.stack ?? error.message : String(error)}\n`); - process.exit(1); -}); diff --git a/apps/stock/data-pipeline/benchmarks/export-raw-bson-benchmark.ts b/apps/stock/data-pipeline/benchmarks/export-raw-bson-benchmark.ts deleted file mode 100644 index 7b3b86e6..00000000 --- a/apps/stock/data-pipeline/benchmarks/export-raw-bson-benchmark.ts +++ /dev/null @@ -1,140 +0,0 @@ -/** - * Reproducible headless benchmark for `exportRawBsonCollection`. - * Streams >= 1,000,000 fixed-seed synthetic ~100 B raw BSON `eodPrices` frames through - * `exportRawBsonCollection` into a temporary directory (cleaned up in `finally`), with zero - * MongoDB or network dependencies. - * - * Usage: - * bun run apps/stock/data-pipeline/benchmarks/export-raw-bson-benchmark.ts [docCount] - */ - -import { mkdtemp, rm } from 'node:fs/promises'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import { BSON } from 'mongodb'; -import { - DEFAULT_WRITE_BUFFER_BYTES, - exportRawBsonCollection, - type ReadOnlyRawBsonSource, -} from '../src/security-master/export-raw-bson'; - -const DEFAULT_DOC_COUNT = 1_000_000; -const POOL_SIZE = 1_024; - -function parseDocCount(): number { - const raw = process.argv[2]; - if (raw === undefined) { - return DEFAULT_DOC_COUNT; - } - if (!/^\d+$/.test(raw)) { - throw new Error(`Invalid docCount "${raw}": expected a positive integer`); - } - const parsed = Number(raw); - if (!Number.isSafeInteger(parsed) || parsed < 1) { - throw new Error(`Invalid docCount "${raw}": expected a positive integer`); - } - return parsed; -} - -/** - * Deterministic PRNG (Mulberry32) so the synthetic BSON pool is identical across runs. - */ -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) / 4294967296; - }; -} - -function buildSyntheticBsonPool(): Uint8Array[] { - const rng = createSeededRng(0x5eed117); - const pool = new Array(POOL_SIZE); - for (let i = 0; i < POOL_SIZE; i++) { - const base = 10 + Math.round(rng() * 20000) / 100; - const high = Math.round((base + rng() * 3) * 100) / 100; - const low = Math.max(0.01, Math.round((base - rng() * 3) * 100) / 100); - const close = Math.round((low + rng() * (high - low)) * 100) / 100; - const volume = Math.floor(1_000 + rng() * 5_000_000); - const month = String((i % 12) + 1).padStart(2, '0'); - const day = String((i % 28) + 1).padStart(2, '0'); - const doc = { - eodSearchCode: `SYM${String(i).padStart(4, '0')}.US`, - date: `2025-${month}-${day}`, - open: base, - high, - low, - close, - volume, - }; - pool[i] = Uint8Array.from(BSON.serialize(doc)); - } - return pool; -} - -function createSyntheticRawSource(pool: readonly Uint8Array[], totalDocs: number): ReadOnlyRawBsonSource { - const poolLen = pool.length; - return { - isReadOnly: () => true, - find() { - return { - async *[Symbol.asyncIterator]() { - for (let i = 0; i < totalDocs; i++) { - const frame = pool[i % poolLen]; - if (frame !== undefined) { - yield frame; - } - } - }, - }; - }, - }; -} - -async function main(): Promise { - const docCount = parseDocCount(); - const pool = buildSyntheticBsonPool(); - const avgDocBytes = - pool.reduce((acc, frame) => acc + frame.byteLength, 0) / pool.length; - const source = createSyntheticRawSource(pool, docCount); - const outDir = await mkdtemp(join(tmpdir(), 'export-raw-bson-bench-')); - - try { - const rssBeforeMiB = process.memoryUsage().rss / (1024 * 1024); - const startNs = Bun.nanoseconds(); - const result = await exportRawBsonCollection(source, { - collection: 'eodPrices', - outDir, - writeBufferBytes: DEFAULT_WRITE_BUFFER_BYTES, - }); - const elapsedMs = (Bun.nanoseconds() - startNs) / 1e6; - const rssAfterMiB = process.memoryUsage().rss / (1024 * 1024); - // process.resourceUsage().maxRSS is reported in KiB on Linux. - const peakRssMiB = process.resourceUsage().maxRSS / 1024; - - const elapsedSec = elapsedMs / 1000; - const docsPerSec = result.docsWritten / elapsedSec; - const mibPerSec = result.bytesWritten / (1024 * 1024) / elapsedSec; - - process.stdout.write('exportRawBsonCollection benchmark complete\n'); - process.stdout.write( - ` docs=${result.docsWritten} avg_doc_bytes=${avgDocBytes.toFixed(1)} bytes_written=${result.bytesWritten} write_buffer_bytes=${DEFAULT_WRITE_BUFFER_BYTES}\n` - ); - process.stdout.write( - ` elapsed_ms=${elapsedMs.toFixed(1)} throughput=${Math.round(docsPerSec)} docs/s rate=${mibPerSec.toFixed(2)} MiB/s\n` - ); - process.stdout.write( - ` rss_before=${rssBeforeMiB.toFixed(2)} MiB rss_after=${rssAfterMiB.toFixed(2)} MiB peak_rss=${peakRssMiB.toFixed(2)} MiB\n` - ); - process.stdout.write(` sha256=${result.sha256}\n`); - } finally { - await rm(outDir, { recursive: true, force: true }); - } -} - -main().catch(error => { - process.stderr.write(`${error instanceof Error ? error.stack ?? error.message : String(error)}\n`); - process.exit(1); -}); diff --git a/apps/stock/data-pipeline/benchmarks/source-field-shapes-benchmark.ts b/apps/stock/data-pipeline/benchmarks/source-field-shapes-benchmark.ts deleted file mode 100644 index ddb6ba75..00000000 --- a/apps/stock/data-pipeline/benchmarks/source-field-shapes-benchmark.ts +++ /dev/null @@ -1,167 +0,0 @@ -/** - * Reproducible headless benchmark for `readFieldShapes` + `renderFieldShapesMarkdown`. - * Streams 80,000 fixed-seed synthetic documents (8 allowlisted collections × 10,000 limit) - * with mixed BSON/JS types, one-level nested objects, and all 5 string pattern classes - * through an in-memory async-generator fake reader with zero MongoDB or network dependencies. - * - * Usage: - * bun run apps/stock/data-pipeline/benchmarks/source-field-shapes-benchmark.ts - */ - -import { - FIELD_SHAPE_PROBE_COLLECTIONS, - FIELD_VALUE_TYPES, - MAX_FIELD_SHAPE_LIMIT, - readFieldShapes, - renderFieldShapesMarkdown, - STRING_PATTERN_CLASSES, - type ReadOnlySourceSymbolCursor, - type ReadOnlySourceSymbolReader, - type SourceSymbolFindOptions, -} from '../src/security-master'; - -const DOCS_PER_COLLECTION = MAX_FIELD_SHAPE_LIMIT; - -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 makeSyntheticDoc(collectionIndex: number, docIndex: number, rng: () => number): Record { - const r = rng(); - const day = String((docIndex % 28) + 1).padStart(2, '0'); - const month = String(((docIndex + collectionIndex) % 12) + 1).padStart(2, '0'); - const dateStr = `2025-${month}-${day}`; - const isoStr = `${dateStr}T14:30:00Z`; - - const doc: Record = { - _id: { - _bsontype: 'ObjectId', - toString: () => - `${String(collectionIndex).padStart(2, '0')}${String(docIndex).padStart(22, '0')}`, - }, - symbol: `SYM${String(docIndex % 2000).padStart(4, '0')}`, - date: r < 0.85 ? dateStr : r < 0.95 ? isoStr : '', - value: - r < 0.5 - ? { _bsontype: 'Double', toString: () => (10 + (docIndex % 500) * 0.25).toFixed(2) } - : r < 0.8 - ? { _bsontype: 'Int32', toString: () => String(docIndex % 10000) } - : r < 0.92 - ? String((docIndex % 1000) / 10) - : null, - active: docIndex % 5 !== 0, - updatedAt: new Date(1735689600000 + (docIndex % 365) * 86_400_000), - meta: { - exchange: docIndex % 2 === 0 ? 'NYSE' : 'TSX', - version: { _bsontype: 'Int32', toString: () => '2' }, - }, - }; - - if (docIndex % 7 === 0) { - doc.tags = ['equity', 'na']; - } - return doc; -} - -function createSyntheticBenchmarkReader(): ReadOnlySourceSymbolReader { - return { - isReadOnly(): boolean { - return true; - }, - find = Record>( - collectionName: string, - _filter?: Record, - options?: SourceSymbolFindOptions - ): ReadOnlySourceSymbolCursor { - const colIdx = FIELD_SHAPE_PROBE_COLLECTIONS.indexOf( - collectionName as (typeof FIELD_SHAPE_PROBE_COLLECTIONS)[number] - ); - const count = Math.min(DOCS_PER_COLLECTION, options?.limit ?? DOCS_PER_COLLECTION); - const rng = mulberry32(0x5eed108 + (colIdx + 1) * 7919); - - return { - async *[Symbol.asyncIterator](): AsyncIterator { - for (let i = 0; i < count; i++) { - yield makeSyntheticDoc(colIdx, i, rng) as T; - } - }, - async close(): Promise { - // No-op for in-memory benchmark cursor. - }, - }; - }, - }; -} - -async function main(): Promise { - const reader = createSyntheticBenchmarkReader(); - - if (typeof Bun !== 'undefined' && typeof Bun.gc === 'function') { - Bun.gc(true); - } - const heapBefore = process.memoryUsage().heapUsed; - const startedAt = performance.now(); - - const result = await readFieldShapes(reader, { - limit: DOCS_PER_COLLECTION, - batchSize: 2_000, - }); - const markdown = renderFieldShapesMarkdown(result); - - const elapsedMs = performance.now() - startedAt; - const heapAfter = process.memoryUsage().heapUsed; - const heapDeltaMb = (heapAfter - heapBefore) / (1024 * 1024); - - const expectedTotal = FIELD_SHAPE_PROBE_COLLECTIONS.length * DOCS_PER_COLLECTION; - if (result.totalDocsSampled !== expectedTotal) { - throw new Error( - `Unexpected totalDocsSampled=${result.totalDocsSampled} (expected ${expectedTotal})` - ); - } - - for (const col of result.collections) { - for (const field of col.fields) { - if (field.presentCount + field.missingCount !== col.docCount) { - throw new Error(`Presence mismatch on ${col.collection}.${field.field}`); - } - let typeSum = 0; - for (const typeName of FIELD_VALUE_TYPES) { - typeSum += field.typeCounts[typeName]; - } - if (typeSum !== field.presentCount) { - throw new Error(`Type sum mismatch on ${col.collection}.${field.field}`); - } - if (field.stringStats !== null) { - let patternSum = 0; - for (const p of STRING_PATTERN_CLASSES) { - patternSum += field.stringStats.patterns[p]; - } - if (patternSum !== field.typeCounts.string) { - throw new Error(`Pattern sum mismatch on ${col.collection}.${field.field}`); - } - } - if ((field.field === '_id' || field.field.startsWith('_id.')) && field.examples.length > 0) { - throw new Error(`_id example leaked on ${col.collection}.${field.field}`); - } - } - } - - const docsPerSec = Math.round(result.totalDocsSampled / (elapsedMs / 1000)); - const lines = [ - 'Source field-shapes probe benchmark (in-memory async cursor, zero MongoDB)', - ` Workload: ${result.totalDocsSampled.toLocaleString('en-US')} docs (${FIELD_SHAPE_PROBE_COLLECTIONS.length} collections x ${DOCS_PER_COLLECTION.toLocaleString('en-US')} limit)`, - ` Markdown: ${markdown.length.toLocaleString('en-US')} chars`, - ` Elapsed: ${elapsedMs.toFixed(1)} ms`, - ` Throughput: ${docsPerSec.toLocaleString('en-US')} docs/s`, - ` Heap delta: ${heapDeltaMb.toFixed(2)} MiB`, - ]; - process.stdout.write(`${lines.join('\n')}\n`); -} - -await main(); diff --git a/apps/stock/data-pipeline/src/security-master/delisting-chains.ts b/apps/stock/data-pipeline/src/security-master/delisting-chains.ts index b6387b72..3da51d81 100644 --- a/apps/stock/data-pipeline/src/security-master/delisting-chains.ts +++ b/apps/stock/data-pipeline/src/security-master/delisting-chains.ts @@ -175,49 +175,6 @@ function parseExactIsoDateToUtcDay(value: unknown): number | null { return era * 146097 + dayOfEra - 719468; } -function formatUtcDayToIsoDate(daysSinceEpoch: number): string { - const shifted = daysSinceEpoch + 719468; - const era = Math.floor(shifted / 146097); - const doe = shifted - era * 146097; - const yoe = Math.floor( - (doe - Math.floor(doe / 1460) + Math.floor(doe / 36524) - Math.floor(doe / 146096)) / 365 - ); - const y = yoe + era * 400; - const doy = doe - (365 * yoe + Math.floor(yoe / 4) - Math.floor(yoe / 100)); - const mp = Math.floor((5 * doy + 2) / 153); - const day = doy - Math.floor((153 * mp + 2) / 5) + 1; - const month = mp + (mp < 10 ? 3 : -9); - const year = y + (month <= 2 ? 1 : 0); - const yStr = String(year).padStart(4, '0'); - const mStr = month < 10 ? `0${String(month)}` : String(month); - const dStr = day < 10 ? `0${String(day)}` : String(day); - return `${yStr}-${mStr}-${dStr}`; -} - -function isBackfilledOtcContinuation( - primary: EndedPrimaryRow, - otc: EligibleOtcRow, - overlapToleranceDays: number -): boolean { - // Provider backfills (notably EODHD on SIVB -> SIVBQ) copy the primary listing's entire - // pre-delist bar history onto the OTC ticker, so otc.listedFrom matches primary.listedFrom - // rather than starting near primary.listedTo. Require that OTC trading continued strictly - // past primary.listedTo and either shares the primary's IPO/start date or carries the - // canonical bankruptcy `Q` suffix. - if (otc.listedFromDay >= primary.listedToDay - overlapToleranceDays) { - return false; - } - if (otc.listedToDay !== null && otc.listedToDay <= primary.listedToDay) { - return false; - } - const sameBackfilledStart = - primary.listedFromDay !== null && - otc.listedFromDay <= primary.listedFromDay + overlapToleranceDays; - const isBankruptcyQSuffix = - otc.key.tickerRoot.toUpperCase() === `${primary.key.tickerRoot.toUpperCase()}Q`; - return sameBackfilledStart || isBankruptcyQSuffix; -} - function cloneListingKey(key: ListingNaturalKey): ListingNaturalKey { return { primaryIsin: key.primaryIsin, @@ -736,24 +693,13 @@ export function linkDelistingChains( otc.listedToDay === null || otc.listedToDay > maxWindowDay ? maxWindowDay : otc.listedToDay; - if (lowDay <= highDay) { - const startIdx = lowerBoundPrimaryByListedToDay(primaries, lowDay); - const endExclusive = upperBoundPrimaryByListedToDay(primaries, highDay); - if (startIdx < endExclusive) { - intervals.push({ startIdx, endIdx: endExclusive - 1, otcIdx: oIdx }); - continue; - } + if (lowDay > highDay) { + continue; } - // Fallback for EODHD-style backfilled OTC history (e.g. SIVB -> SIVBQ) where the OTC - // ticker carries pre-delist bars back to the primary listing's original start date. - for (let pIdx = 0; pIdx < primaries.length; pIdx++) { - const primary = primaries[pIdx]; - if ( - primary !== undefined && - isBackfilledOtcContinuation(primary, otc, overlapToleranceDays) - ) { - intervals.push({ startIdx: pIdx, endIdx: pIdx, otcIdx: oIdx }); - } + const startIdx = lowerBoundPrimaryByListedToDay(primaries, lowDay); + const endExclusive = upperBoundPrimaryByListedToDay(primaries, highDay); + if (startIdx < endExclusive) { + intervals.push({ startIdx, endIdx: endExclusive - 1, otcIdx: oIdx }); } } @@ -784,16 +730,13 @@ export function linkDelistingChains( const otc = oIdx !== undefined ? otcs[oIdx] : undefined; if (primary !== undefined && otc !== undefined) { linkedPrimaryIndices.add(primary.index); - // effectiveDate uses the OTC listing's first observed date (listedFrom) for clean - // transfers, or the day after primary.listedTo when the OTC ticker's pre-delist history - // was backfilled (so downstream curation never back-dates the transfer to the IPO date). - const effectiveDate = isBackfilledOtcContinuation(primary, otc, overlapToleranceDays) - ? formatUtcDayToIsoDate(primary.listedToDay + 1) - : otc.listedFrom; + // effectiveDate uses the OTC listing's first observed date (listedFrom) so + // downstream backtests and curation never back-date OTC availability before + // OTC trading/quoting actually began. continuities.push({ fromListingKey: cloneListingKey(primary.key), toListingKey: cloneListingKey(otc.key), - effectiveDate, + effectiveDate: otc.listedFrom, kind: CONTINUITY_KIND_OTC_DELIST_TRANSFER, }); } diff --git a/apps/stock/data-pipeline/src/security-master/exchange-pass1.ts b/apps/stock/data-pipeline/src/security-master/exchange-pass1.ts index b4ebb785..24ec1fab 100644 --- a/apps/stock/data-pipeline/src/security-master/exchange-pass1.ts +++ b/apps/stock/data-pipeline/src/security-master/exchange-pass1.ts @@ -71,7 +71,6 @@ export interface ExchangeClassificationResult { export interface ClassifySourceExchangesOptions { knownExchanges?: readonly ExchangeSeedRow[]; - reviewedRows?: readonly ExchangeSourceMapRow[]; } const VALID_EXCHANGE_SOURCE_SET: ReadonlySet = new Set(EXCHANGE_SOURCES); @@ -294,15 +293,9 @@ export const REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS: readonly ExchangeSourceMap { 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: 'NYSE NAT', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' }, - { source: 'eod' as const, sourceCode: 'NYSEARCA', role: 'primary_venue' as const, mic: 'ARCX', countryIso: 'US' }, - { source: 'eod' as const, sourceCode: 'NYSEMKT', 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: 'OTCBB', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' }, - { source: 'eod' as const, sourceCode: 'OTCCE', 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: 'OTCMTKS', 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' }, @@ -312,63 +305,19 @@ export const REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS: readonly ExchangeSourceMap { 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: 'BOX', role: 'ats_routing' as const, mic: null, countryIso: 'US' }, - { source: 'ib' as const, sourceCode: 'BYX', role: 'ats_routing' as const, mic: null, countryIso: 'US' }, - { source: 'ib' as const, sourceCode: 'CBOE', role: 'ats_routing' as const, mic: null, countryIso: 'US' }, - { source: 'ib' as const, sourceCode: 'CBOE2', role: 'ats_routing' as const, mic: null, countryIso: 'US' }, - { source: 'ib' as const, sourceCode: 'CBOT', role: 'ats_routing' as const, mic: null, countryIso: 'US' }, - { source: 'ib' as const, sourceCode: 'CDE', role: 'ats_routing' as const, mic: null, countryIso: 'CA' }, - { source: 'ib' as const, sourceCode: 'CFE', role: 'ats_routing' as const, mic: null, countryIso: 'US' }, - { source: 'ib' as const, sourceCode: 'CFETAS', role: 'ats_routing' as const, mic: null, countryIso: 'US' }, - { source: 'ib' as const, sourceCode: 'CHX', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' }, - { source: 'ib' as const, sourceCode: 'CME', role: 'ats_routing' as const, mic: null, countryIso: 'US' }, - { source: 'ib' as const, sourceCode: 'COMEX', role: 'ats_routing' as const, mic: null, countryIso: 'US' }, { source: 'ib' as const, sourceCode: 'EDGX', role: 'ats_routing' as const, mic: null, countryIso: 'US' }, - { source: 'ib' as const, sourceCode: 'EMERALD', role: 'ats_routing' as const, mic: null, countryIso: 'US' }, - { source: 'ib' as const, sourceCode: 'FORECASTX', role: 'ats_routing' as const, mic: null, countryIso: 'US' }, - { source: 'ib' as const, sourceCode: 'FUNDSERV', role: 'excluded_fund' as const, mic: null, countryIso: 'US' }, - { source: 'ib' as const, sourceCode: 'GEMINI', role: 'ats_routing' as const, mic: null, countryIso: 'US' }, - { source: 'ib' as const, sourceCode: 'IBCMDTY', role: 'ats_routing' as const, mic: null, countryIso: 'US' }, - { source: 'ib' as const, sourceCode: 'IBDESK', role: 'ats_routing' as const, mic: null, countryIso: 'US' }, - { source: 'ib' as const, sourceCode: 'IBFX', role: 'forex' as const, mic: null, countryIso: 'US' }, - { source: 'ib' as const, sourceCode: 'IBKRAM', role: 'ats_routing' as const, mic: null, countryIso: 'US' }, - { source: 'ib' as const, sourceCode: 'IBKRATS', role: 'ats_routing' as const, mic: null, countryIso: 'US' }, - { source: 'ib' as const, sourceCode: 'IBUSCFD', role: 'ats_routing' as const, mic: null, countryIso: 'US' }, - { source: 'ib' as const, sourceCode: 'ICEUS', role: 'ats_routing' as const, mic: null, countryIso: 'US' }, - { source: 'ib' as const, sourceCode: 'IDEALPRO', role: 'forex' as const, mic: null, countryIso: 'US' }, - { source: 'ib' as const, sourceCode: 'ISE', 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: 'LTSE', role: 'ats_routing' as const, mic: null, countryIso: 'US' }, - { source: 'ib' as const, sourceCode: 'MERCURY', role: 'ats_routing' as const, mic: null, countryIso: 'US' }, - { source: 'ib' as const, sourceCode: 'MIAX', role: 'ats_routing' as const, mic: null, countryIso: 'US' }, { source: 'ib' as const, sourceCode: 'NASDAQ', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' }, - { source: 'ib' as const, sourceCode: 'NASDAQBX', role: 'ats_routing' as const, mic: null, countryIso: 'US' }, - { source: 'ib' as const, sourceCode: 'NASDAQOM', role: 'ats_routing' as const, mic: null, countryIso: 'US' }, { source: 'ib' as const, sourceCode: 'NEO', role: 'primary_venue' as const, mic: 'NEOE', countryIso: 'CA' }, - { source: 'ib' as const, sourceCode: 'NYBOT', role: 'ats_routing' as const, mic: null, countryIso: 'US' }, - { source: 'ib' as const, sourceCode: 'NYMEX', role: 'ats_routing' as const, mic: null, countryIso: 'US' }, { source: 'ib' as const, sourceCode: 'NYSE', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' }, - { source: 'ib' as const, sourceCode: 'NYSEFLOOR', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' }, - { source: 'ib' as const, sourceCode: 'NYSELIFFE', role: 'ats_routing' as const, mic: null, countryIso: 'US' }, - { source: 'ib' as const, sourceCode: 'NYSENAT', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' }, - { source: 'ib' as const, sourceCode: 'OVERNIGHT', role: 'ats_routing' as const, mic: null, countryIso: 'US' }, - { source: 'ib' as const, sourceCode: 'PEARL', role: 'ats_routing' as const, mic: null, countryIso: 'US' }, - { source: 'ib' as const, sourceCode: 'PHLX', role: 'ats_routing' as const, mic: null, countryIso: 'US' }, { source: 'ib' as const, sourceCode: 'PINK', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' }, - { source: 'ib' as const, sourceCode: 'PSE', role: 'primary_venue' as const, mic: 'ARCX', countryIso: 'US' }, { source: 'ib' as const, sourceCode: 'PURE', role: 'primary_venue' as const, mic: 'XCNQ', countryIso: 'CA' }, - { source: 'ib' as const, sourceCode: 'SGXCME', role: 'ats_routing' as const, mic: null, countryIso: 'US' }, - { source: 'ib' as const, sourceCode: 'SMFE', role: 'ats_routing' as const, mic: null, countryIso: 'US' }, - { source: 'ib' as const, sourceCode: 'TRADEWEB', role: 'ats_routing' as const, mic: null, countryIso: 'US' }, { 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' }, - { source: 'ib' as const, sourceCode: 'ZEROHASH', role: 'ats_routing' as const, mic: null, countryIso: 'US' }, // 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: 'AMX', 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: 'AQLL', 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' }, @@ -383,23 +332,16 @@ export const REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS: readonly ExchangeSourceMap { 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: 'CVEM', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' }, { 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: 'EXPM', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' }, - { source: 'qm' as const, sourceCode: 'GREY', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' }, { source: 'qm' as const, sourceCode: 'IEX', role: 'primary_venue' as const, mic: 'IEXG', countryIso: 'US' }, - { source: 'qm' as const, sourceCode: 'MOE', role: 'ats_routing' as const, mic: null, countryIso: 'CA' }, { 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: 'NDD', 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: 'NMF', role: 'excluded_fund' as const, mic: null, countryIso: 'US' }, - { source: 'qm' as const, sourceCode: 'NSC', 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' }, @@ -415,7 +357,6 @@ export const REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS: readonly ExchangeSourceMap { 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: 'PINL', 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' }, @@ -423,9 +364,7 @@ export const REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS: readonly ExchangeSourceMap { 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: 'TSXC', role: 'composite' as const, mic: null, countryIso: 'CA' }, { source: 'qm' as const, sourceCode: 'TSXV', role: 'primary_venue' as const, mic: 'XTSX', countryIso: 'CA' }, - { source: 'qm' as const, sourceCode: 'TSXVC', role: 'composite' as const, mic: null, countryIso: 'CA' }, { source: 'qm' as const, sourceCode: 'VNX', role: 'primary_venue' as const, mic: 'XTSX', countryIso: 'CA' }, ].map(rule => ({ ...rule, @@ -484,12 +423,6 @@ export function classifySourceExchanges( const knownByMic = new Map( knownExchanges.map(exchange => [exchange.mic.trim().toUpperCase(), exchange]) ); - const reviewedByKey = new Map(); - if (options.reviewedRows) { - for (const row of options.reviewedRows) { - reviewedByKey.set(makeRuleKey(row.source, row.sourceCode.trim().toUpperCase()), row); - } - } const grouped = new Map(); const unresolved: UnresolvedExchangeRecord[] = []; @@ -562,20 +495,6 @@ export function classifySourceExchanges( continue; } - const reviewedRow = reviewedByKey.get(makeRuleKey(group.source, group.sourceCode)); - if (reviewedRow) { - mapped.push({ - source: reviewedRow.source, - sourceCode: reviewedRow.sourceCode.trim().toUpperCase(), - role: reviewedRow.role, - mic: reviewedRow.mic, - countryIso: reviewedRow.countryIso, - method: reviewedRow.method, - reviewedBy: reviewedRow.reviewedBy ?? null, - }); - continue; - } - // Sort group deterministically so duplicate collapse is independent of input order. const sortedRecords = [...group.records].sort(compareSourceRecordsDeterministically); const representative = sortedRecords[0]; diff --git a/apps/stock/data-pipeline/src/security-master/export-curate-inputs.ts b/apps/stock/data-pipeline/src/security-master/export-curate-inputs.ts deleted file mode 100644 index 299bac4d..00000000 --- a/apps/stock/data-pipeline/src/security-master/export-curate-inputs.ts +++ /dev/null @@ -1,2040 +0,0 @@ -import { randomUUID } from 'node:crypto'; -import { - access, - lstat, - mkdir, - open, - readlink, - realpath, - rename, - rm, - rmdir, - symlink, - unlink, - type FileHandle, -} from 'node:fs/promises'; -import { basename, join } from 'node:path'; -import { compareAscii } from './exchange-pass1'; -import type { SecurityMasterQueryable } from './persist'; - -export const CURATE_INPUT_FILES = Object.freeze({ - providerMapping: 'provider_mapping.tsv', - listingCurrencies: 'listing_currencies.tsv', - delistings: 'delistings.tsv', -} as const); - -export const CURATE_INPUT_GENERATIONS_DIR = 'generations'; -export const CURATE_INPUT_CURRENT_LINK = 'current'; -export const CURATE_INPUT_PUBLISH_LOCK = '.publish.lock'; -export const DEFAULT_EXPORT_CHUNK_SIZE = 5000; -export const MAX_EXPORT_CHUNK_SIZE = 5000; -export const DEFAULT_DELISTING_MAPPING_SOURCE = 'qm'; -export const DEFAULT_PUBLISH_LOCK_TIMEOUT_MS = 30_000; -const PUBLISH_LOCK_RETRY_MS = 5; -const PROVIDER_MAPPING_CURSOR_NAME = 'curate_export_pm_cursor'; - -const MAX_PG_INT4 = 2_147_483_647; -const EXACT_YMD_PATTERN = /^\d{4}-\d{2}-\d{2}$/; -const STRICT_DECIMAL_PATTERN = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/; -const DAYS_IN_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] as const; - -export type CurateInputExportErrorCode = - | 'INVALID_OPTION' - | 'INVALID_CLIENT' - | 'FORBIDDEN_CONTROL_CHAR' - | 'BLANK_FIELD' - | 'INVALID_LISTING_ID' - | 'INVALID_DATE' - | 'INVALID_DATE_RANGE' - | 'DUPLICATE_PROVIDER_MAPPING' - | 'OVERLAPPING_PROVIDER_MAPPING' - | 'UNSORTED_PROVIDER_MAPPING_STREAM' - | 'DUPLICATE_LISTING_CURRENCY' - | 'UNSORTED_LISTING_STREAM' - | 'INVALID_TERMINAL_RETURN' - | 'INVALID_DELISTING_OUTCOME' - | 'MISSING_FROM_LISTING_ID' - | 'ACTIVE_LISTING_WITH_OUTCOME' - | 'SELF_SUCCESSOR_CONTINUITY' - | 'DUPLICATE_OTC_CONTINUITY' - | 'OUT_OF_ORDER_CONTINUITY_STREAM' - | 'PUBLISH_LOCK_TIMEOUT' - | 'PUBLISH_ROLLBACK_FAILED'; - -export interface CurateInputExportErrorOptions { - readonly code: CurateInputExportErrorCode; - readonly table: string; - readonly key: string; - readonly field?: string; - readonly detail: string; - readonly cause?: unknown; -} - -export class CurateInputExportError extends Error { - readonly code: CurateInputExportErrorCode; - readonly table: string; - readonly key: string; - readonly field?: string; - - constructor(options: CurateInputExportErrorOptions) { - const fieldPart = options.field !== undefined ? ` field=${options.field}` : ''; - super( - `[${options.code}] ${options.table} (${options.key})${fieldPart}: ${options.detail}`, - options.cause !== undefined ? { cause: options.cause } : undefined - ); - this.name = 'CurateInputExportError'; - this.code = options.code; - this.table = options.table; - this.key = options.key; - if (options.field !== undefined) { - this.field = options.field; - } - } -} - -export interface ProviderMappingExportRow { - readonly source: string; - readonly sourceId: string; - readonly validFrom: string; - readonly validTo: string | null; - readonly listingId: number; -} - -export interface ListingCurrencyExportRow { - readonly listingId: number; - readonly currency: string; -} - -export interface DelistingExportRow { - readonly sourceId: string; - readonly delistDate: string; - readonly fromListingId: number | null; - readonly successorSourceId: string | null; - readonly terminalReturn: number | string | null; -} - -export interface ListingDelistingSourceRow { - readonly listingId: number; - readonly listedTo: string | null; - readonly delistReason: string | null; - readonly terminalReturn: number | string | null; -} - -export interface ContinuityExportSourceRow { - readonly fromListingId: number; - readonly toListingId: number; - readonly effectiveDate: string; - readonly kind: string; -} - -export interface BuildDelistingExportRowsOptions { - readonly mappingSource?: string; -} - -export interface DelistingExportSkippedByReason { - readonly active: number; - readonly noOutcome: number; - readonly missingListedTo: number; - readonly missingOutgoingQmMapping: number; - readonly missingSuccessorQmMapping: number; - readonly nonOtcContinuity: number; -} - -export interface DelistingExportStats { - readonly rowsIn: number; - readonly rowsOut: number; - readonly otcTransfersOut: number; - readonly terminalDelistingsOut: number; - readonly skippedTotal: number; - readonly skipped: DelistingExportSkippedByReason; -} - -export interface BuildDelistingExportRowsResult { - readonly rows: readonly DelistingExportRow[]; - readonly stats: DelistingExportStats; -} - -export interface ExportCurateInputsFsHooks { - readonly mkdir?: typeof mkdir; - readonly open?: typeof open; - readonly rename?: typeof rename; - readonly unlink?: typeof unlink; - readonly access?: typeof access; - readonly lstat?: typeof lstat; - readonly readlink?: typeof readlink; - readonly symlink?: typeof symlink; - readonly realpath?: typeof realpath; - readonly rm?: typeof rm; - readonly rmdir?: typeof rmdir; -} - -export interface ExportCurateInputsOptions { - readonly outDir: string; - readonly chunkSize?: number; - readonly delistingMappingSource?: string; - readonly publishLockTimeoutMs?: number; - readonly fs?: ExportCurateInputsFsHooks; -} - -export interface ExportCurateInputsFileStats { - readonly path: string; - readonly rowsIn: number; - readonly rowsOut: number; - readonly bytesWritten: number; -} - -export interface PinnedCurateInputSnapshot { - readonly outDir: string; - readonly generationId: string; - readonly generationDir: string; - readonly providerMapping: string; - readonly listingCurrencies: string; - readonly delistings: string; -} - -export interface ExportCurateInputsResult { - readonly outDir: string; - readonly generationId: string; - readonly generationDir: string; - readonly currentLink: string; - readonly chunkSize: number; - readonly delistingMappingSource: string; - readonly providerMapping: ExportCurateInputsFileStats; - readonly listingCurrencies: ExportCurateInputsFileStats; - readonly delistings: ExportCurateInputsFileStats & { - readonly stats: DelistingExportStats; - }; - readonly totalBytesWritten: number; - readonly cleanupWarnings: readonly string[]; -} - -interface QmListingMappingRange { - readonly sourceId: string; - readonly validFrom: string; - readonly validTo: string | null; - readonly listingId: number; -} - -interface ValidatedDelistingRow { - readonly sourceId: string; - readonly delistDate: string; - readonly fromListingId: number | null; - readonly successorSourceId: string | null; - readonly formattedTerminalReturn: string; -} - -interface DbContinuityRow { - from_listing_id: number; - to_listing_id: number; - effective_date: string; - kind: string; -} - -interface DbListingRow { - listing_id: number; - currency: string | null; - listed_to: string | null; - delist_reason: string | null; - terminal_return: string | null; -} - -interface DbProviderMappingRow { - source: string | null; - source_id: string | null; - valid_from: string | null; - valid_to: string | null; - listing_id: number; -} - -function isLeapYear(year: number): boolean { - return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; -} - -export function isValidStrictYmd(value: string): boolean { - if (!EXACT_YMD_PATTERN.test(value)) { - return false; - } - const year = - (value.charCodeAt(0) - 48) * 1000 + - (value.charCodeAt(1) - 48) * 100 + - (value.charCodeAt(2) - 48) * 10 + - (value.charCodeAt(3) - 48); - const month = (value.charCodeAt(5) - 48) * 10 + (value.charCodeAt(6) - 48); - const day = (value.charCodeAt(8) - 48) * 10 + (value.charCodeAt(9) - 48); - if (year < 1 || year > 9999 || month < 1 || month > 12) { - return false; - } - const maxDay = month === 2 && isLeapYear(year) ? 29 : (DAYS_IN_MONTH[month] ?? 0); - return day >= 1 && day <= maxDay; -} - -function assertNoTsvControlChars( - value: string, - table: string, - key: string, - field: string -): void { - if (value.includes('\t') || value.includes('\n') || value.includes('\r')) { - throw new CurateInputExportError({ - code: 'FORBIDDEN_CONTROL_CHAR', - table, - key, - field, - detail: `${field} must not contain tab, newline, or carriage return characters`, - }); - } -} - -function assertNonBlankVerbatim( - value: unknown, - table: string, - key: string, - field: string -): string { - if (typeof value !== 'string') { - throw new CurateInputExportError({ - code: 'BLANK_FIELD', - table, - key, - field, - detail: `${field} must be a non-blank string`, - }); - } - assertNoTsvControlChars(value, table, key, field); - if (value.trim().length === 0) { - throw new CurateInputExportError({ - code: 'BLANK_FIELD', - table, - key, - field, - detail: `${field} must not be empty or whitespace-only`, - }); - } - return value; -} - -function assertStrictYmd(value: unknown, table: string, key: string, field: string): string { - if (typeof value !== 'string') { - throw new CurateInputExportError({ - code: 'INVALID_DATE', - table, - key, - field, - detail: `${field} must be a strict Gregorian YYYY-MM-DD string`, - }); - } - assertNoTsvControlChars(value, table, key, field); - if (!isValidStrictYmd(value)) { - throw new CurateInputExportError({ - code: 'INVALID_DATE', - table, - key, - field, - detail: `invalid ${field} "${value}" (expected strict Gregorian YYYY-MM-DD)`, - }); - } - return value; -} - -function assertPositiveI32(value: unknown, table: string, key: string, field: string): number { - if ( - typeof value !== 'number' || - !Number.isInteger(value) || - value < 1 || - value > MAX_PG_INT4 - ) { - throw new CurateInputExportError({ - code: 'INVALID_LISTING_ID', - table, - key, - field, - detail: `invalid ${field} "${String(value)}" (expected integer in 1..=${MAX_PG_INT4})`, - }); - } - return value; -} - -/** - * Formats a finite JS number as a plain base-10 decimal string without scientific notation. - * Normalizes `-0` to `"0"`. - */ -export function formatPlainDecimal(value: number): string { - if (value === 0) { - return '0'; - } - const raw = String(value); - const expIdx = raw.search(/[eE]/); - if (expIdx === -1) { - return raw; - } - - const sign = raw.startsWith('-') ? '-' : ''; - const unsigned = sign.length > 0 ? raw.slice(1, expIdx) : raw.slice(0, expIdx); - const exponent = Number(raw.slice(expIdx + 1)); - const dotIdx = unsigned.indexOf('.'); - const digits = dotIdx === -1 ? unsigned : unsigned.slice(0, dotIdx) + unsigned.slice(dotIdx + 1); - const integerLen = dotIdx === -1 ? unsigned.length : dotIdx; - const decimalPos = integerLen + exponent; - - if (decimalPos <= 0) { - return `${sign}0.${'0'.repeat(-decimalPos)}${digits}`; - } - if (decimalPos >= digits.length) { - return `${sign}${digits}${'0'.repeat(decimalPos - digits.length)}`; - } - return `${sign}${digits.slice(0, decimalPos)}.${digits.slice(decimalPos)}`; -} - -function normalizeAndFormatTerminalReturn( - value: number | string, - table: string, - key: string, - field: string -): string { - let num: number; - if (typeof value === 'string') { - assertNoTsvControlChars(value, table, key, field); - if (value.length === 0 || value.trim() !== value || !STRICT_DECIMAL_PATTERN.test(value)) { - throw new CurateInputExportError({ - code: 'INVALID_TERMINAL_RETURN', - table, - key, - field, - detail: `invalid ${field} "${value}" (expected finite decimal in [-1, 0])`, - }); - } - num = Number(value); - } else if (typeof value === 'number') { - num = value; - } else { - throw new CurateInputExportError({ - code: 'INVALID_TERMINAL_RETURN', - table, - key, - field, - detail: `invalid ${field} "${String(value)}" (expected finite decimal in [-1, 0])`, - }); - } - - if (!Number.isFinite(num) || num < -1 || num > 0) { - throw new CurateInputExportError({ - code: 'INVALID_TERMINAL_RETURN', - table, - key, - field, - detail: `invalid ${field} "${String(value)}" (must be finite and in [-1, 0])`, - }); - } - - const normalized = num === 0 ? 0 : num; - return formatPlainDecimal(normalized); -} - -function compareNullableAscii(a: string | null, b: string | null): number { - if (a === b) { - return 0; - } - if (a === null) { - return 1; - } - if (b === null) { - return -1; - } - return compareAscii(a, b); -} - -function joinLinesInChunks(lines: readonly string[], chunkSize = DEFAULT_EXPORT_CHUNK_SIZE): string { - if (lines.length === 0) { - return ''; - } - if (lines.length <= chunkSize) { - return `${lines.join('\n')}\n`; - } - const chunks: string[] = []; - for (let offset = 0; offset < lines.length; offset += chunkSize) { - chunks.push(lines.slice(offset, offset + chunkSize).join('\n')); - } - return `${chunks.join('\n')}\n`; -} - -function validateProviderMappingRow( - row: ProviderMappingExportRow, - index: number -): ProviderMappingExportRow { - const fallbackKey = `row#${index}`; - const source = assertNonBlankVerbatim(row.source, 'provider_mapping', fallbackKey, 'source'); - const sourceId = assertNonBlankVerbatim( - row.sourceId, - 'provider_mapping', - `${source}:${fallbackKey}`, - 'source_id' - ); - const key = `${source}:${sourceId}:${String(row.validFrom)}`; - const validFrom = assertStrictYmd(row.validFrom, 'provider_mapping', key, 'valid_from'); - let validTo: string | null = null; - if (row.validTo !== null && row.validTo !== undefined) { - validTo = assertStrictYmd(row.validTo, 'provider_mapping', key, 'valid_to'); - if (validTo < validFrom) { - throw new CurateInputExportError({ - code: 'INVALID_DATE_RANGE', - table: 'provider_mapping', - key: `${source}:${sourceId}:${validFrom}`, - field: 'valid_to', - detail: `valid_to "${validTo}" precedes valid_from "${validFrom}"`, - }); - } - } - const listingId = assertPositiveI32( - row.listingId, - 'provider_mapping', - `${source}:${sourceId}:${validFrom}`, - 'listing_id' - ); - return { source, sourceId, validFrom, validTo, listingId }; -} - -/** - * Validates, deterministically ASCII-sorts, overlap-checks, and formats `provider_mapping.tsv`. - * Headerless 5-column TSV: `source\tsource_id\tvalid_from\tvalid_to\tlisting_id`. - */ -export function formatProviderMappingTsv(rows: readonly ProviderMappingExportRow[]): string { - if (rows.length === 0) { - return ''; - } - - const validated: ProviderMappingExportRow[] = []; - for (let i = 0; i < rows.length; i++) { - const row = rows[i]; - if (row === undefined) { - continue; - } - validated.push(validateProviderMappingRow(row, i)); - } - - validated.sort( - (a, b) => - compareAscii(a.source, b.source) || - compareAscii(a.sourceId, b.sourceId) || - compareAscii(a.validFrom, b.validFrom) || - compareNullableAscii(a.validTo, b.validTo) || - a.listingId - b.listingId - ); - - const lines: string[] = []; - let prev: ProviderMappingExportRow | undefined; - for (const curr of validated) { - if (prev !== undefined && prev.source === curr.source && prev.sourceId === curr.sourceId) { - if (prev.validFrom === curr.validFrom) { - throw new CurateInputExportError({ - code: 'DUPLICATE_PROVIDER_MAPPING', - table: 'provider_mapping', - key: `${curr.source}:${curr.sourceId}:${curr.validFrom}`, - detail: 'duplicate (source, source_id, valid_from) primary key', - }); - } - if (prev.validTo === null || prev.validTo >= curr.validFrom) { - throw new CurateInputExportError({ - code: 'OVERLAPPING_PROVIDER_MAPPING', - table: 'provider_mapping', - key: `${curr.source}:${curr.sourceId}:${curr.validFrom}`, - detail: `inclusive range [${prev.validFrom}, ${prev.validTo ?? '+inf'}] overlaps [${curr.validFrom}, ${curr.validTo ?? '+inf'}]`, - }); - } - } - lines.push( - `${curr.source}\t${curr.sourceId}\t${curr.validFrom}\t${curr.validTo ?? ''}\t${curr.listingId}` - ); - prev = curr; - } - - return joinLinesInChunks(lines); -} - -/** - * Validates, sorts by ascending `listing_id`, rejects duplicate `listing_id`s, and formats - * `listing_currencies.tsv`. Headerless 2-column TSV: `listing_id\tcurrency`. - */ -export function formatListingCurrenciesTsv(rows: readonly ListingCurrencyExportRow[]): string { - if (rows.length === 0) { - return ''; - } - - const validated: ListingCurrencyExportRow[] = []; - for (let i = 0; i < rows.length; i++) { - const row = rows[i]; - if (row === undefined) { - continue; - } - const listingId = assertPositiveI32(row.listingId, 'listing', `row#${i}`, 'listing_id'); - const currency = assertNonBlankVerbatim( - row.currency, - 'listing', - `listing_id=${listingId}`, - 'currency' - ); - validated.push({ listingId, currency }); - } - - validated.sort((a, b) => a.listingId - b.listingId); - - const lines: string[] = []; - let prevListingId: number | undefined; - for (const curr of validated) { - if (prevListingId === curr.listingId) { - throw new CurateInputExportError({ - code: 'DUPLICATE_LISTING_CURRENCY', - table: 'listing', - key: `listing_id=${curr.listingId}`, - field: 'listing_id', - detail: `duplicate listing_id ${curr.listingId} in listing_currencies`, - }); - } - lines.push(`${curr.listingId}\t${curr.currency}`); - prevListingId = curr.listingId; - } - - return joinLinesInChunks(lines); -} - -function validateDelistingExportRow(row: DelistingExportRow, index: number): ValidatedDelistingRow { - const fallbackKey = `row#${index}`; - const sourceId = assertNonBlankVerbatim(row.sourceId, 'delistings', fallbackKey, 'source_id'); - const rowKey = `${sourceId}:${String(row.delistDate)}`; - const delistDate = assertStrictYmd(row.delistDate, 'delistings', rowKey, 'delist_date'); - const fromListingId = - row.fromListingId === null || row.fromListingId === undefined - ? null - : assertPositiveI32(row.fromListingId, 'delistings', rowKey, 'from_listing_id'); - const successorSourceId = - row.successorSourceId === null || row.successorSourceId === undefined - ? null - : assertNonBlankVerbatim( - row.successorSourceId, - 'delistings', - rowKey, - 'successor_source_id' - ); - const formattedTerminalReturn = - row.terminalReturn === null || row.terminalReturn === undefined - ? '' - : normalizeAndFormatTerminalReturn(row.terminalReturn, 'delistings', rowKey, 'terminal_return'); - - const hasSuccessor = successorSourceId !== null; - const hasTerminalReturn = formattedTerminalReturn.length > 0; - if (hasSuccessor && hasTerminalReturn) { - throw new CurateInputExportError({ - code: 'INVALID_DELISTING_OUTCOME', - table: 'delistings', - key: rowKey, - detail: 'delisting row must set exactly one of successor_source_id or terminal_return (got both)', - }); - } - if (!hasSuccessor && !hasTerminalReturn) { - throw new CurateInputExportError({ - code: 'INVALID_DELISTING_OUTCOME', - table: 'delistings', - key: rowKey, - detail: - 'delisting row must set exactly one of successor_source_id or terminal_return (got neither)', - }); - } - if (hasSuccessor && fromListingId === null) { - throw new CurateInputExportError({ - code: 'MISSING_FROM_LISTING_ID', - table: 'delistings', - key: rowKey, - field: 'from_listing_id', - detail: 'OTC delisting transfer row with successor_source_id requires from_listing_id', - }); - } - - return { - sourceId, - delistDate, - fromListingId, - successorSourceId, - formattedTerminalReturn, - }; -} - -function compareValidatedDelistingRows(a: ValidatedDelistingRow, b: ValidatedDelistingRow): number { - return ( - compareAscii(a.sourceId, b.sourceId) || - compareAscii(a.delistDate, b.delistDate) || - (a.fromListingId ?? 0) - (b.fromListingId ?? 0) || - compareAscii(a.successorSourceId ?? '', b.successorSourceId ?? '') || - compareAscii(a.formattedTerminalReturn, b.formattedTerminalReturn) - ); -} - -/** - * Validates, deterministically sorts, and formats Pass 6 `delistings.tsv`. - * Headerless 5-column TSV: - * `source_id\tdelist_date\tfrom_listing_id\tsuccessor_source_id\tterminal_return`. - */ -export function formatDelistingsTsv(rows: readonly DelistingExportRow[]): string { - if (rows.length === 0) { - return ''; - } - - const validated: ValidatedDelistingRow[] = []; - for (let i = 0; i < rows.length; i++) { - const row = rows[i]; - if (row === undefined) { - continue; - } - validated.push(validateDelistingExportRow(row, i)); - } - - validated.sort(compareValidatedDelistingRows); - - const lines: string[] = []; - for (const row of validated) { - lines.push( - `${row.sourceId}\t${row.delistDate}\t${row.fromListingId === null ? '' : String(row.fromListingId)}\t${row.successorSourceId ?? ''}\t${row.formattedTerminalReturn}` - ); - } - - return joinLinesInChunks(lines); -} - -/** - * Deterministic tie-breaker when multiple `qm` mappings qualify for the same `listing_id`: - * 1. `validFrom DESC` (most recently started mapping) - * 2. `validTo DESC NULLS FIRST` (open-ended active mapping beats closed, then latest end date) - * 3. `sourceId ASC` (ASCII) - */ -function compareQualifyingQmMappings(a: QmListingMappingRange, b: QmListingMappingRange): number { - const fromCmp = compareAscii(b.validFrom, a.validFrom); - if (fromCmp !== 0) { - return fromCmp; - } - if (a.validTo !== b.validTo) { - if (a.validTo === null) { - return -1; - } - if (b.validTo === null) { - return 1; - } - const toCmp = compareAscii(b.validTo, a.validTo); - if (toCmp !== 0) { - return toCmp; - } - } - return compareAscii(a.sourceId, b.sourceId); -} - -function selectQmMappingOnOrBefore( - ranges: readonly QmListingMappingRange[] | undefined, - date: string -): QmListingMappingRange | null { - if (!ranges || ranges.length === 0) { - return null; - } - let best: QmListingMappingRange | null = null; - for (const candidate of ranges) { - if (candidate.validFrom <= date) { - if (best === null || compareQualifyingQmMappings(candidate, best) < 0) { - best = candidate; - } - } - } - return best; -} - -function selectQmMappingOnDate( - ranges: readonly QmListingMappingRange[] | undefined, - date: string -): QmListingMappingRange | null { - if (!ranges || ranges.length === 0) { - return null; - } - let best: QmListingMappingRange | null = null; - for (const candidate of ranges) { - if (candidate.validFrom <= date && (candidate.validTo === null || candidate.validTo >= date)) { - if (best === null || compareQualifyingQmMappings(candidate, best) < 0) { - best = candidate; - } - } - } - return best; -} - -/** - * Pure Pass 6 delistings builder turning `listing`, `corporate_action_continuity`, and - * `provider_mapping` rows into `DelistingExportRow[]` plus exact skip-reason stats - * (`rowsIn === rowsOut + skippedTotal`). - * - * Indexes `otc_delist_transfer` continuities strictly by `fromListingId` so OTC successor listings - * (e.g. `SIVBQ`) still emit their own subsequent terminal delisting (e.g. bankruptcy `-1`). - */ -export function buildDelistingExportRows( - listings: readonly ListingDelistingSourceRow[], - continuities: readonly ContinuityExportSourceRow[], - providerMappings: readonly ProviderMappingExportRow[], - options: BuildDelistingExportRowsOptions = {} -): BuildDelistingExportRowsResult { - const mappingSource = assertNonBlankVerbatim( - options.mappingSource ?? DEFAULT_DELISTING_MAPPING_SOURCE, - 'options', - 'mappingSource', - 'mappingSource' - ); - - let nonOtcContinuity = 0; - const otcByFromListingId = new Map(); - for (let i = 0; i < continuities.length; i++) { - const raw = continuities[i]; - if (raw === undefined) { - continue; - } - if (raw.kind !== 'otc_delist_transfer') { - nonOtcContinuity += 1; - continue; - } - const fromListingId = assertPositiveI32( - raw.fromListingId, - 'corporate_action_continuity', - `row#${i}`, - 'from_listing_id' - ); - const toListingId = assertPositiveI32( - raw.toListingId, - 'corporate_action_continuity', - `from_listing_id=${fromListingId}`, - 'to_listing_id' - ); - const effectiveDate = assertStrictYmd( - raw.effectiveDate, - 'corporate_action_continuity', - `from_listing_id=${fromListingId}`, - 'effective_date' - ); - if (fromListingId === toListingId) { - throw new CurateInputExportError({ - code: 'SELF_SUCCESSOR_CONTINUITY', - table: 'corporate_action_continuity', - key: `from_listing_id=${fromListingId}@${effectiveDate}`, - field: 'to_listing_id', - detail: `otc_delist_transfer continuity cannot link listing ${fromListingId} to itself`, - }); - } - if (otcByFromListingId.has(fromListingId)) { - throw new CurateInputExportError({ - code: 'DUPLICATE_OTC_CONTINUITY', - table: 'corporate_action_continuity', - key: `from_listing_id=${fromListingId}`, - detail: `multiple otc_delist_transfer continuities found for from_listing_id=${fromListingId}`, - }); - } - otcByFromListingId.set(fromListingId, { - fromListingId, - toListingId, - effectiveDate, - kind: raw.kind, - }); - } - - const qmMappingsByListingId = new Map(); - for (let i = 0; i < providerMappings.length; i++) { - const rawMapping = providerMappings[i]; - if (rawMapping === undefined) { - continue; - } - const validated = validateProviderMappingRow(rawMapping, i); - if (validated.source !== mappingSource) { - continue; - } - let list = qmMappingsByListingId.get(validated.listingId); - if (list === undefined) { - list = []; - qmMappingsByListingId.set(validated.listingId, list); - } - list.push({ - sourceId: validated.sourceId, - validFrom: validated.validFrom, - validTo: validated.validTo, - listingId: validated.listingId, - }); - } - - let active = 0; - let noOutcome = 0; - let missingListedTo = 0; - let missingOutgoingQmMapping = 0; - let missingSuccessorQmMapping = 0; - let otcTransfersOut = 0; - let terminalDelistingsOut = 0; - - const seenListingIds = new Set(); - const rows: DelistingExportRow[] = []; - - for (let i = 0; i < listings.length; i++) { - const listing = listings[i]; - if (listing === undefined) { - continue; - } - const listingId = assertPositiveI32(listing.listingId, 'listing', `row#${i}`, 'listing_id'); - const listingKey = `listing_id=${listingId}`; - if (seenListingIds.has(listingId)) { - throw new CurateInputExportError({ - code: 'DUPLICATE_LISTING_CURRENCY', - table: 'listing', - key: listingKey, - field: 'listing_id', - detail: `duplicate listing_id ${listingId} in listings input`, - }); - } - seenListingIds.add(listingId); - - const otc = otcByFromListingId.get(listingId); - const hasTerminalReturn = - listing.terminalReturn !== null && listing.terminalReturn !== undefined; - - if (listing.delistReason === 'active') { - if (otc !== undefined || hasTerminalReturn) { - throw new CurateInputExportError({ - code: 'ACTIVE_LISTING_WITH_OUTCOME', - table: 'listing', - key: listingKey, - field: 'delist_reason', - detail: 'listing marked active cannot have an OTC continuity or terminal_return', - }); - } - active += 1; - continue; - } - - if (otc !== undefined && hasTerminalReturn) { - throw new CurateInputExportError({ - code: 'INVALID_DELISTING_OUTCOME', - table: 'listing', - key: listingKey, - detail: 'listing cannot have both an outgoing otc_delist_transfer and a terminal_return', - }); - } - - if (otc !== undefined) { - const outgoing = selectQmMappingOnOrBefore( - qmMappingsByListingId.get(listingId), - otc.effectiveDate - ); - if (outgoing === null) { - missingOutgoingQmMapping += 1; - continue; - } - const successor = selectQmMappingOnDate( - qmMappingsByListingId.get(otc.toListingId), - otc.effectiveDate - ); - if (successor === null) { - missingSuccessorQmMapping += 1; - continue; - } - rows.push({ - sourceId: outgoing.sourceId, - delistDate: otc.effectiveDate, - fromListingId: listingId, - successorSourceId: successor.sourceId, - terminalReturn: null, - }); - otcTransfersOut += 1; - continue; - } - - if (hasTerminalReturn) { - const formattedReturn = normalizeAndFormatTerminalReturn( - listing.terminalReturn as number | string, - 'listing', - listingKey, - 'terminal_return' - ); - if (listing.listedTo === null || listing.listedTo === undefined) { - missingListedTo += 1; - continue; - } - const listedTo = assertStrictYmd(listing.listedTo, 'listing', listingKey, 'listed_to'); - const outgoing = selectQmMappingOnDate(qmMappingsByListingId.get(listingId), listedTo); - if (outgoing === null) { - missingOutgoingQmMapping += 1; - continue; - } - rows.push({ - sourceId: outgoing.sourceId, - delistDate: listedTo, - fromListingId: listingId, - successorSourceId: null, - terminalReturn: formattedReturn, - }); - terminalDelistingsOut += 1; - continue; - } - - noOutcome += 1; - } - - // Handle any OTC continuity whose fromListingId was absent from `listings` (pure caller input). - const orphanOtcIds = Array.from(otcByFromListingId.keys()) - .filter(id => !seenListingIds.has(id)) - .sort((a, b) => a - b); - for (const fromListingId of orphanOtcIds) { - const otc = otcByFromListingId.get(fromListingId); - if (otc === undefined) { - continue; - } - const outgoing = selectQmMappingOnOrBefore( - qmMappingsByListingId.get(fromListingId), - otc.effectiveDate - ); - if (outgoing === null) { - missingOutgoingQmMapping += 1; - continue; - } - const successor = selectQmMappingOnDate( - qmMappingsByListingId.get(otc.toListingId), - otc.effectiveDate - ); - if (successor === null) { - missingSuccessorQmMapping += 1; - continue; - } - rows.push({ - sourceId: outgoing.sourceId, - delistDate: otc.effectiveDate, - fromListingId, - successorSourceId: successor.sourceId, - terminalReturn: null, - }); - otcTransfersOut += 1; - } - - rows.sort((a, b) => - compareValidatedDelistingRows( - { - sourceId: a.sourceId, - delistDate: a.delistDate, - fromListingId: a.fromListingId, - successorSourceId: a.successorSourceId, - formattedTerminalReturn: a.terminalReturn === null ? '' : String(a.terminalReturn), - }, - { - sourceId: b.sourceId, - delistDate: b.delistDate, - fromListingId: b.fromListingId, - successorSourceId: b.successorSourceId, - formattedTerminalReturn: b.terminalReturn === null ? '' : String(b.terminalReturn), - } - ) - ); - - const rowsOut = otcTransfersOut + terminalDelistingsOut; - const skippedTotal = - active + - noOutcome + - missingListedTo + - missingOutgoingQmMapping + - missingSuccessorQmMapping + - nonOtcContinuity; - const rowsIn = rowsOut + skippedTotal; - - return { - rows, - stats: { - rowsIn, - rowsOut, - otcTransfersOut, - terminalDelistingsOut, - skippedTotal, - skipped: { - active, - noOutcome, - missingListedTo, - missingOutgoingQmMapping, - missingSuccessorQmMapping, - nonOtcContinuity, - }, - }, - }; -} - -function assertDedicatedQueryable(client: SecurityMasterQueryable): void { - if (client === null || client === undefined || typeof client !== 'object') { - throw new CurateInputExportError({ - code: 'INVALID_CLIENT', - table: 'connection', - key: 'client', - detail: 'exportCurateInputs requires a dedicated SecurityMasterQueryable client', - }); - } - if (typeof client.query !== 'function') { - throw new CurateInputExportError({ - code: 'INVALID_CLIENT', - table: 'connection', - key: 'client', - detail: 'exportCurateInputs client must expose a query() method', - }); - } - const maybePool = client as unknown as { connect?: unknown; release?: unknown }; - if (typeof maybePool.connect === 'function' && typeof maybePool.release !== 'function') { - throw new CurateInputExportError({ - code: 'INVALID_CLIENT', - table: 'connection', - key: 'client', - detail: - 'exportCurateInputs requires a dedicated single-session client (e.g. pg.PoolClient), not a Pool', - }); - } -} - -function validateChunkSize(chunkSize: number | undefined): number { - const resolved = chunkSize ?? DEFAULT_EXPORT_CHUNK_SIZE; - if ( - typeof resolved !== 'number' || - !Number.isSafeInteger(resolved) || - resolved < 1 || - resolved > MAX_EXPORT_CHUNK_SIZE - ) { - throw new CurateInputExportError({ - code: 'INVALID_OPTION', - table: 'options', - key: 'chunkSize', - field: 'chunkSize', - detail: `chunkSize must be an integer in 1..=${MAX_EXPORT_CHUNK_SIZE} (got ${String(resolved)})`, - }); - } - return resolved; -} - -async function safeUnlink(unlinkFn: typeof unlink, filePath: string): Promise { - try { - await unlinkFn(filePath); - } catch (error) { - if ((error as NodeJS.ErrnoException | undefined)?.code !== 'ENOENT') { - throw error; - } - } -} - -async function safeRmdirIfEmpty(rmdirFn: typeof rmdir, dirPath: string): Promise { - try { - await rmdirFn(dirPath); - } catch (error) { - const code = (error as NodeJS.ErrnoException | undefined)?.code; - if (code !== 'ENOENT' && code !== 'ENOTEMPTY' && code !== 'EEXIST') { - throw error; - } - } -} - -async function writeAll(handle: FileHandle, buf: Buffer): Promise { - let offset = 0; - while (offset < buf.byteLength) { - const { bytesWritten } = await handle.write(buf, offset, buf.byteLength - offset); - if (bytesWritten <= 0) { - throw new Error('Short write (0 bytes written) while streaming TSV chunk'); - } - offset += bytesWritten; - } -} - -async function acquirePublishLock( - lockPath: string, - outDir: string, - runTag: string, - timeoutMs: number, - fsOpen: typeof open, - fsUnlink: typeof unlink -): Promise { - const deadline = Date.now() + timeoutMs; - const payload = Buffer.from( - `${JSON.stringify({ pid: process.pid, runTag, acquiredAtMs: Date.now() })}\n`, - 'utf8' - ); - for (;;) { - let handle: FileHandle | null = null; - let created = false; - try { - handle = await fsOpen(lockPath, 'wx'); - created = true; - await writeAll(handle, payload); - const toClose = handle; - handle = null; - await toClose.close(); - return; - } catch (error) { - if (handle !== null) { - await handle.close().catch(() => {}); - } - if (created) { - await safeUnlink(fsUnlink, lockPath).catch(() => {}); - throw error; - } - const code = (error as NodeJS.ErrnoException | undefined)?.code; - if (code !== 'EEXIST') { - throw error; - } - if (Date.now() >= deadline) { - throw new CurateInputExportError({ - code: 'PUBLISH_LOCK_TIMEOUT', - table: 'publish', - key: outDir, - detail: `timed out after ${timeoutMs}ms waiting for publish lock ${lockPath}`, - cause: error, - }); - } - await new Promise(resolve => setTimeout(resolve, PUBLISH_LOCK_RETRY_MS)); - } - } -} - -/** - * Resolves and pins the currently active immutable generation directory via `/current` - * before a consumer opens any TSV file. All three returned paths belong to the same atomic - * PostgreSQL snapshot and remain immutable even if a concurrent export refreshes `/current`. - */ -export async function pinCurateInputSnapshot( - outDir: string, - fsHooks?: Pick -): Promise { - if (typeof outDir !== 'string' || outDir.trim().length === 0) { - throw new CurateInputExportError({ - code: 'INVALID_OPTION', - table: 'options', - key: 'outDir', - field: 'outDir', - detail: 'outDir must be a non-empty string', - }); - } - const normalizedOutDir = outDir.trim(); - const fsRealpath = fsHooks?.realpath ?? realpath; - const currentLink = join(normalizedOutDir, CURATE_INPUT_CURRENT_LINK); - const generationDir = await fsRealpath(currentLink); - const generationId = basename(generationDir); - return { - outDir: normalizedOutDir, - generationId, - generationDir, - providerMapping: join(generationDir, CURATE_INPUT_FILES.providerMapping), - listingCurrencies: join(generationDir, CURATE_INPUT_FILES.listingCurrencies), - delistings: join(generationDir, CURATE_INPUT_FILES.delistings), - }; -} - -/** - * Reads security-master tables strictly read-only inside a `REPEATABLE READ READ ONLY` - * transaction in bounded chunks (`chunkSize <= 5000`), streams formatted chunks to an immutable - * generation directory under `/generations/`, and atomically commits - * `/current` (plus top-level symlinks `provider_mapping.tsv`, `listing_currencies.tsv`, - * and `delistings.tsv` pointing through `current/`). - */ -export async function exportCurateInputs( - queryable: SecurityMasterQueryable, - options: ExportCurateInputsOptions -): Promise { - assertDedicatedQueryable(queryable); - - if ( - options === null || - options === undefined || - typeof options !== 'object' || - typeof options.outDir !== 'string' || - options.outDir.trim().length === 0 - ) { - throw new CurateInputExportError({ - code: 'INVALID_OPTION', - table: 'options', - key: 'outDir', - field: 'outDir', - detail: 'outDir must be a non-empty string', - }); - } - - const outDir = options.outDir.trim(); - const chunkSize = validateChunkSize(options.chunkSize); - const publishLockTimeoutMs = options.publishLockTimeoutMs ?? DEFAULT_PUBLISH_LOCK_TIMEOUT_MS; - if ( - typeof publishLockTimeoutMs !== 'number' || - !Number.isFinite(publishLockTimeoutMs) || - publishLockTimeoutMs < 0 - ) { - throw new CurateInputExportError({ - code: 'INVALID_OPTION', - table: 'options', - key: 'publishLockTimeoutMs', - field: 'publishLockTimeoutMs', - detail: `publishLockTimeoutMs must be a non-negative finite number (got ${String(publishLockTimeoutMs)})`, - }); - } - const delistingMappingSource = assertNonBlankVerbatim( - options.delistingMappingSource ?? DEFAULT_DELISTING_MAPPING_SOURCE, - 'options', - 'delistingMappingSource', - 'delistingMappingSource' - ); - - const fsMkdir = options.fs?.mkdir ?? mkdir; - const fsOpen = options.fs?.open ?? open; - const fsRename = options.fs?.rename ?? rename; - const fsUnlink = options.fs?.unlink ?? unlink; - const fsLstat = options.fs?.lstat ?? lstat; - const fsReadlink = options.fs?.readlink ?? readlink; - const fsSymlink = options.fs?.symlink ?? symlink; - const fsRm = options.fs?.rm ?? rm; - const fsRmdir = options.fs?.rmdir ?? rmdir; - - await fsMkdir(outDir, { recursive: true }); - - const uniqueSuffix = randomUUID().slice(0, 8); - const timestamp = Date.now(); - const runTag = `${process.pid}-${timestamp}-${uniqueSuffix}`; - const generationId = `gen-${timestamp}-${process.pid}-${uniqueSuffix}`; - const generationsRoot = join(outDir, CURATE_INPUT_GENERATIONS_DIR); - const stagingDir = join(outDir, `.staging-${runTag}`); - const generationDir = join(generationsRoot, generationId); - const relativeGenerationTarget = join(CURATE_INPUT_GENERATIONS_DIR, generationId); - const currentLink = join(outDir, CURATE_INPUT_CURRENT_LINK); - const currentTempLink = join(outDir, `.${CURATE_INPUT_CURRENT_LINK}.${runTag}.tmp`); - const publishLockPath = join(outDir, CURATE_INPUT_PUBLISH_LOCK); - - const targets = { - providerMapping: join(outDir, CURATE_INPUT_FILES.providerMapping), - listingCurrencies: join(outDir, CURATE_INPUT_FILES.listingCurrencies), - delistings: join(outDir, CURATE_INPUT_FILES.delistings), - }; - const stagedFiles = { - providerMapping: join(stagingDir, CURATE_INPUT_FILES.providerMapping), - listingCurrencies: join(stagingDir, CURATE_INPUT_FILES.listingCurrencies), - delistings: join(stagingDir, CURATE_INPUT_FILES.delistings), - }; - const generationFiles = { - providerMapping: join(generationDir, CURATE_INPUT_FILES.providerMapping), - listingCurrencies: join(generationDir, CURATE_INPUT_FILES.listingCurrencies), - delistings: join(generationDir, CURATE_INPUT_FILES.delistings), - }; - const backups = { - providerMapping: `${targets.providerMapping}.${runTag}.bak`, - listingCurrencies: `${targets.listingCurrencies}.${runTag}.bak`, - delistings: `${targets.delistings}.${runTag}.bak`, - }; - const linkTemps = { - providerMapping: `${targets.providerMapping}.${runTag}.link.tmp`, - listingCurrencies: `${targets.listingCurrencies}.${runTag}.link.tmp`, - delistings: `${targets.delistings}.${runTag}.link.tmp`, - }; - - let providerMappingHandle: FileHandle | null = null; - let listingCurrenciesHandle: FileHandle | null = null; - let delistingsHandle: FileHandle | null = null; - - let providerMappingRowsIn = 0; - let providerMappingRowsOut = 0; - let providerMappingBytes = 0; - - let listingCurrenciesRowsIn = 0; - let listingCurrenciesRowsOut = 0; - let listingCurrenciesBytes = 0; - - let delistingsBytes = 0; - let delistingsStats!: DelistingExportStats; - - type PublishKey = 'providerMapping' | 'listingCurrencies' | 'delistings'; - const publishOrder: PublishKey[] = ['providerMapping', 'listingCurrencies', 'delistings']; - - let stagingCreated = false; - let publishLockAcquired = false; - let generationMoved = false; - let currentTempCreated = false; - const backedUp = new Set(); - const createdLinks = new Set(); - - try { - await fsMkdir(stagingDir, { recursive: false }); - stagingCreated = true; - - providerMappingHandle = await fsOpen(stagedFiles.providerMapping, 'wx'); - listingCurrenciesHandle = await fsOpen(stagedFiles.listingCurrencies, 'wx'); - delistingsHandle = await fsOpen(stagedFiles.delistings, 'wx'); - - const otcByFromListingId = new Map(); - const relevantDelistingListingIds = new Set(); - const otcCandidates: Array<{ listingId: number; otc: ContinuityExportSourceRow }> = []; - const terminalCandidates: Array<{ - listingId: number; - listedTo: string; - formattedTerminalReturn: string; - }> = []; - const qmMappingsByListingId = new Map(); - - let skippedActive = 0; - let skippedNoOutcome = 0; - let skippedMissingListedTo = 0; - - await queryable.query('BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY'); - try { - // 1. Keyset-paginated read of corporate_action_continuity (kind = 'otc_delist_transfer'). - let lastContFromId: number | null = null; - let lastContEffDate: string | null = null; - for (;;) { - const res = - lastContFromId === null - ? await queryable.query( - `SELECT - from_listing_id, - to_listing_id, - to_char(effective_date, 'YYYY-MM-DD') AS effective_date, - kind - FROM corporate_action_continuity - WHERE kind = 'otc_delist_transfer' - ORDER BY from_listing_id ASC, effective_date ASC - LIMIT $1`, - [chunkSize] - ) - : await queryable.query( - `SELECT - from_listing_id, - to_listing_id, - to_char(effective_date, 'YYYY-MM-DD') AS effective_date, - kind - FROM corporate_action_continuity - WHERE kind = 'otc_delist_transfer' - AND ( - from_listing_id > $1 - OR (from_listing_id = $1 AND effective_date > $2::date) - ) - ORDER BY from_listing_id ASC, effective_date ASC - LIMIT $3`, - [lastContFromId, lastContEffDate, chunkSize] - ); - - if (res.rows.length === 0) { - break; - } - - for (const row of res.rows) { - const fromListingId = assertPositiveI32( - row.from_listing_id, - 'corporate_action_continuity', - `from_listing_id=${String(row.from_listing_id)}`, - 'from_listing_id' - ); - const toListingId = assertPositiveI32( - row.to_listing_id, - 'corporate_action_continuity', - `from_listing_id=${fromListingId}`, - 'to_listing_id' - ); - const effectiveDate = assertStrictYmd( - row.effective_date, - 'corporate_action_continuity', - `from_listing_id=${fromListingId}`, - 'effective_date' - ); - - if (lastContFromId !== null && lastContEffDate !== null) { - if ( - fromListingId < lastContFromId || - (fromListingId === lastContFromId && effectiveDate <= lastContEffDate) - ) { - throw new CurateInputExportError({ - code: 'OUT_OF_ORDER_CONTINUITY_STREAM', - table: 'corporate_action_continuity', - key: `from_listing_id=${fromListingId}@${effectiveDate}`, - detail: 'corporate_action_continuity stream was not strictly ordered by (from_listing_id, effective_date)', - }); - } - } - - if (fromListingId === toListingId) { - throw new CurateInputExportError({ - code: 'SELF_SUCCESSOR_CONTINUITY', - table: 'corporate_action_continuity', - key: `from_listing_id=${fromListingId}@${effectiveDate}`, - field: 'to_listing_id', - detail: `otc_delist_transfer continuity cannot link listing ${fromListingId} to itself`, - }); - } - - if (otcByFromListingId.has(fromListingId)) { - throw new CurateInputExportError({ - code: 'DUPLICATE_OTC_CONTINUITY', - table: 'corporate_action_continuity', - key: `from_listing_id=${fromListingId}`, - detail: `multiple otc_delist_transfer continuities found for from_listing_id=${fromListingId}`, - }); - } - - otcByFromListingId.set(fromListingId, { - fromListingId, - toListingId, - effectiveDate, - kind: row.kind, - }); - relevantDelistingListingIds.add(fromListingId); - relevantDelistingListingIds.add(toListingId); - - lastContFromId = fromListingId; - lastContEffDate = effectiveDate; - } - - if (res.rows.length < chunkSize) { - break; - } - } - - // 2. Keyset-paginated read of listing -> stream listing_currencies.tsv directly. - let lastListingId: number | null = null; - for (;;) { - const res = - lastListingId === null - ? await queryable.query( - `SELECT - listing_id, - btrim(currency) AS currency, - to_char(listed_to, 'YYYY-MM-DD') AS listed_to, - delist_reason, - terminal_return::text AS terminal_return - FROM listing - ORDER BY listing_id ASC - LIMIT $1`, - [chunkSize] - ) - : await queryable.query( - `SELECT - listing_id, - btrim(currency) AS currency, - to_char(listed_to, 'YYYY-MM-DD') AS listed_to, - delist_reason, - terminal_return::text AS terminal_return - FROM listing - WHERE listing_id > $1 - ORDER BY listing_id ASC - LIMIT $2`, - [lastListingId, chunkSize] - ); - - if (res.rows.length === 0) { - break; - } - - const chunkLines: string[] = []; - for (const row of res.rows) { - const listingId = assertPositiveI32( - row.listing_id, - 'listing', - `listing_id=${String(row.listing_id)}`, - 'listing_id' - ); - const listingKey = `listing_id=${listingId}`; - - if (lastListingId !== null) { - if (listingId === lastListingId) { - throw new CurateInputExportError({ - code: 'DUPLICATE_LISTING_CURRENCY', - table: 'listing', - key: listingKey, - field: 'listing_id', - detail: `duplicate listing_id ${listingId} in listing stream`, - }); - } - if (listingId < lastListingId) { - throw new CurateInputExportError({ - code: 'UNSORTED_LISTING_STREAM', - table: 'listing', - key: listingKey, - field: 'listing_id', - detail: `listing stream out of ascending listing_id order (${listingId} after ${lastListingId})`, - }); - } - } - - const currency = assertNonBlankVerbatim(row.currency, 'listing', listingKey, 'currency'); - chunkLines.push(`${listingId}\t${currency}`); - listingCurrenciesRowsIn += 1; - listingCurrenciesRowsOut += 1; - - const otc = otcByFromListingId.get(listingId); - const hasTerminalReturn = - row.terminal_return !== null && row.terminal_return !== undefined; - - if (row.delist_reason === 'active') { - if (otc !== undefined || hasTerminalReturn) { - throw new CurateInputExportError({ - code: 'ACTIVE_LISTING_WITH_OUTCOME', - table: 'listing', - key: listingKey, - field: 'delist_reason', - detail: 'listing marked active cannot have an OTC continuity or terminal_return', - }); - } - skippedActive += 1; - } else if (otc !== undefined && hasTerminalReturn) { - throw new CurateInputExportError({ - code: 'INVALID_DELISTING_OUTCOME', - table: 'listing', - key: listingKey, - detail: - 'listing cannot have both an outgoing otc_delist_transfer and a terminal_return', - }); - } else if (otc !== undefined) { - otcCandidates.push({ listingId, otc }); - } else if (hasTerminalReturn) { - const formattedTerminalReturn = normalizeAndFormatTerminalReturn( - row.terminal_return as string, - 'listing', - listingKey, - 'terminal_return' - ); - if (row.listed_to === null || row.listed_to === undefined) { - skippedMissingListedTo += 1; - } else { - const listedTo = assertStrictYmd(row.listed_to, 'listing', listingKey, 'listed_to'); - relevantDelistingListingIds.add(listingId); - terminalCandidates.push({ - listingId, - listedTo, - formattedTerminalReturn, - }); - } - } else { - skippedNoOutcome += 1; - } - - lastListingId = listingId; - } - - const chunkText = `${chunkLines.join('\n')}\n`; - const buf = Buffer.from(chunkText, 'utf8'); - await writeAll(listingCurrenciesHandle, buf); - listingCurrenciesBytes += buf.byteLength; - - if (res.rows.length < chunkSize) { - break; - } - } - - // 3. Server-side NO SCROLL cursor read of provider_mapping -> stream provider_mapping.tsv - // directly in bounded chunks without repeated per-page sorts on non-C DB collations. - let lastSource: string | null = null; - let lastSourceId: string | null = null; - let lastValidFrom: string | null = null; - let lastValidTo: string | null = null; - - await queryable.query( - `DECLARE ${PROVIDER_MAPPING_CURSOR_NAME} NO SCROLL CURSOR FOR - 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 - FROM provider_mapping - ORDER BY source COLLATE "C" ASC, source_id COLLATE "C" ASC, valid_from ASC` - ); - - for (;;) { - const res = await queryable.query( - `FETCH FORWARD ${chunkSize} FROM ${PROVIDER_MAPPING_CURSOR_NAME}` - ); - - if (res.rows.length === 0) { - break; - } - - const chunkLines: string[] = []; - for (const row of res.rows) { - const fallbackKey = `row#${providerMappingRowsIn}`; - const source = assertNonBlankVerbatim(row.source, 'provider_mapping', fallbackKey, 'source'); - const sourceId = assertNonBlankVerbatim( - row.source_id, - 'provider_mapping', - `${source}:${fallbackKey}`, - 'source_id' - ); - const key = `${source}:${sourceId}:${String(row.valid_from)}`; - const validFrom = assertStrictYmd(row.valid_from, 'provider_mapping', key, 'valid_from'); - let validTo: string | null = null; - if (row.valid_to !== null && row.valid_to !== undefined) { - validTo = assertStrictYmd(row.valid_to, 'provider_mapping', key, 'valid_to'); - if (validTo < validFrom) { - throw new CurateInputExportError({ - code: 'INVALID_DATE_RANGE', - table: 'provider_mapping', - key: `${source}:${sourceId}:${validFrom}`, - field: 'valid_to', - detail: `valid_to "${validTo}" precedes valid_from "${validFrom}"`, - }); - } - } - const listingId = assertPositiveI32( - row.listing_id, - 'provider_mapping', - `${source}:${sourceId}:${validFrom}`, - 'listing_id' - ); - - if (lastSource !== null && lastSourceId !== null && lastValidFrom !== null) { - const pairCmp = - compareAscii(source, lastSource) || compareAscii(sourceId, lastSourceId); - if (pairCmp < 0) { - throw new CurateInputExportError({ - code: 'UNSORTED_PROVIDER_MAPPING_STREAM', - table: 'provider_mapping', - key: `${source}:${sourceId}:${validFrom}`, - detail: `provider_mapping stream out of COLLATE "C" order ("${source}:${sourceId}" after "${lastSource}:${lastSourceId}")`, - }); - } - if (pairCmp === 0) { - const fromCmp = compareAscii(validFrom, lastValidFrom); - if (fromCmp < 0) { - throw new CurateInputExportError({ - code: 'UNSORTED_PROVIDER_MAPPING_STREAM', - table: 'provider_mapping', - key: `${source}:${sourceId}:${validFrom}`, - detail: `provider_mapping stream out of valid_from order ("${validFrom}" after "${lastValidFrom}")`, - }); - } - if (fromCmp === 0) { - throw new CurateInputExportError({ - code: 'DUPLICATE_PROVIDER_MAPPING', - table: 'provider_mapping', - key: `${source}:${sourceId}:${validFrom}`, - detail: 'duplicate (source, source_id, valid_from) primary key', - }); - } - if (lastValidTo === null || lastValidTo >= validFrom) { - throw new CurateInputExportError({ - code: 'OVERLAPPING_PROVIDER_MAPPING', - table: 'provider_mapping', - key: `${source}:${sourceId}:${validFrom}`, - detail: `inclusive range [${lastValidFrom}, ${lastValidTo ?? '+inf'}] overlaps [${validFrom}, ${validTo ?? '+inf'}]`, - }); - } - } - } - - if (source === delistingMappingSource && relevantDelistingListingIds.has(listingId)) { - let list = qmMappingsByListingId.get(listingId); - if (list === undefined) { - list = []; - qmMappingsByListingId.set(listingId, list); - } - list.push({ sourceId, validFrom, validTo, listingId }); - } - - chunkLines.push( - `${source}\t${sourceId}\t${validFrom}\t${validTo ?? ''}\t${listingId}` - ); - providerMappingRowsIn += 1; - providerMappingRowsOut += 1; - - lastSource = source; - lastSourceId = sourceId; - lastValidFrom = validFrom; - lastValidTo = validTo; - } - - const chunkText = `${chunkLines.join('\n')}\n`; - const buf = Buffer.from(chunkText, 'utf8'); - await writeAll(providerMappingHandle, buf); - providerMappingBytes += buf.byteLength; - - if (res.rows.length < chunkSize) { - break; - } - } - - await queryable.query(`CLOSE ${PROVIDER_MAPPING_CURSOR_NAME}`); - await queryable.query('COMMIT'); - } catch (error) { - try { - await queryable.query('ROLLBACK'); - } catch { - // Preserve original error if ROLLBACK fails on a broken session. - } - throw error; - } - - // 4. Assemble and chunk-write delistings.tsv. - let skippedMissingOutgoingQmMapping = 0; - let skippedMissingSuccessorQmMapping = 0; - let otcTransfersOut = 0; - let terminalDelistingsOut = 0; - const delistingRows: ValidatedDelistingRow[] = []; - - for (const { listingId, otc } of otcCandidates) { - const outgoing = selectQmMappingOnOrBefore( - qmMappingsByListingId.get(listingId), - otc.effectiveDate - ); - if (outgoing === null) { - skippedMissingOutgoingQmMapping += 1; - continue; - } - const successor = selectQmMappingOnDate( - qmMappingsByListingId.get(otc.toListingId), - otc.effectiveDate - ); - if (successor === null) { - skippedMissingSuccessorQmMapping += 1; - continue; - } - delistingRows.push({ - sourceId: outgoing.sourceId, - delistDate: otc.effectiveDate, - fromListingId: listingId, - successorSourceId: successor.sourceId, - formattedTerminalReturn: '', - }); - otcTransfersOut += 1; - } - - for (const { listingId, listedTo, formattedTerminalReturn } of terminalCandidates) { - const outgoing = selectQmMappingOnDate(qmMappingsByListingId.get(listingId), listedTo); - if (outgoing === null) { - skippedMissingOutgoingQmMapping += 1; - continue; - } - delistingRows.push({ - sourceId: outgoing.sourceId, - delistDate: listedTo, - fromListingId: listingId, - successorSourceId: null, - formattedTerminalReturn, - }); - terminalDelistingsOut += 1; - } - - delistingRows.sort(compareValidatedDelistingRows); - - for (let offset = 0; offset < delistingRows.length; offset += chunkSize) { - const slice = delistingRows.slice(offset, offset + chunkSize); - const chunkLines: string[] = []; - for (const row of slice) { - chunkLines.push( - `${row.sourceId}\t${row.delistDate}\t${row.fromListingId === null ? '' : String(row.fromListingId)}\t${row.successorSourceId ?? ''}\t${row.formattedTerminalReturn}` - ); - } - const buf = Buffer.from(`${chunkLines.join('\n')}\n`, 'utf8'); - await writeAll(delistingsHandle, buf); - delistingsBytes += buf.byteLength; - } - - const delistingsRowsOut = otcTransfersOut + terminalDelistingsOut; - const delistingsSkippedTotal = - skippedActive + - skippedNoOutcome + - skippedMissingListedTo + - skippedMissingOutgoingQmMapping + - skippedMissingSuccessorQmMapping; - delistingsStats = { - rowsIn: delistingsRowsOut + delistingsSkippedTotal, - rowsOut: delistingsRowsOut, - otcTransfersOut, - terminalDelistingsOut, - skippedTotal: delistingsSkippedTotal, - skipped: { - active: skippedActive, - noOutcome: skippedNoOutcome, - missingListedTo: skippedMissingListedTo, - missingOutgoingQmMapping: skippedMissingOutgoingQmMapping, - missingSuccessorQmMapping: skippedMissingSuccessorQmMapping, - nonOtcContinuity: 0, - }, - }; - - // 5. Sync and close all three staged files before atomic generation publish. - await providerMappingHandle.sync(); - await providerMappingHandle.close(); - providerMappingHandle = null; - - await listingCurrenciesHandle.sync(); - await listingCurrenciesHandle.close(); - listingCurrenciesHandle = null; - - await delistingsHandle.sync(); - await delistingsHandle.close(); - delistingsHandle = null; - - // 6. Acquire cross-process publish lock before touching shared top-level links or `current`. - // The lock serializes link setup, backups, atomic `current` commit, and any rollback across - // concurrent exporters targeting the same `outDir`. - await acquirePublishLock( - publishLockPath, - outDir, - runTag, - publishLockTimeoutMs, - fsOpen, - fsUnlink - ); - publishLockAcquired = true; - - // Promote staging directory to an immutable generation and prepare top-level links. - // Keep every backup until the single atomic commit point (`rename(currentTempLink, currentLink)`). - await fsMkdir(generationsRoot, { recursive: true }); - await fsRename(stagingDir, generationDir); - generationMoved = true; - stagingCreated = false; - - await fsSymlink(relativeGenerationTarget, currentTempLink); - currentTempCreated = true; - - for (const key of publishOrder) { - const expectedLinkTarget = join(CURATE_INPUT_CURRENT_LINK, CURATE_INPUT_FILES[key]); - let existingStat: Awaited> | null = null; - try { - existingStat = await fsLstat(targets[key]); - } catch (statErr) { - if ((statErr as NodeJS.ErrnoException | undefined)?.code !== 'ENOENT') { - throw statErr; - } - } - - if (existingStat === null) { - await fsSymlink(expectedLinkTarget, linkTemps[key]); - await fsRename(linkTemps[key], targets[key]); - createdLinks.add(key); - continue; - } - - if (existingStat.isSymbolicLink()) { - const currentTarget = await fsReadlink(targets[key]); - if (currentTarget === expectedLinkTarget) { - continue; - } - } - - // Pre-existing regular file or non-standard symlink: back it up and keep backup until commit. - await fsRename(targets[key], backups[key]); - backedUp.add(key); - await fsSymlink(expectedLinkTarget, linkTemps[key]); - await fsRename(linkTemps[key], targets[key]); - } - - // 7. Single atomic commit point: atomically swap `/current` -> `generations/`. - await fsRename(currentTempLink, currentLink); - currentTempCreated = false; - } catch (error) { - // Close any still-open staged file handles. - for (const handle of [providerMappingHandle, listingCurrenciesHandle, delistingsHandle]) { - if (handle !== null) { - await handle.close().catch(() => {}); - } - } - - // Roll back any backed-up targets or newly created top-level links while still holding the publish lock. - // Never unlink backups here: if a restore fails, retain the backup on disk and report it. - const restoreFailures: Array<{ - key: PublishKey; - target: string; - backup: string; - message: string; - }> = []; - for (const key of [...publishOrder].reverse()) { - if (backedUp.has(key)) { - try { - await fsRename(backups[key], targets[key]); - } catch (restoreErr) { - restoreFailures.push({ - key, - target: targets[key], - backup: backups[key], - message: restoreErr instanceof Error ? restoreErr.message : String(restoreErr), - }); - } - } else if (createdLinks.has(key)) { - await safeUnlink(fsUnlink, targets[key]).catch(() => {}); - } - } - - // Clean up uncommitted temporary artifacts (never backups). - for (const key of publishOrder) { - await safeUnlink(fsUnlink, linkTemps[key]).catch(() => {}); - } - if (currentTempCreated) { - await safeUnlink(fsUnlink, currentTempLink).catch(() => {}); - } - if (stagingCreated) { - await fsRm(stagingDir, { recursive: true, force: true }).catch(() => {}); - } - if (generationMoved) { - await fsRm(generationDir, { recursive: true, force: true }).catch(() => {}); - } - - if (publishLockAcquired) { - await safeRmdirIfEmpty(fsRmdir, generationsRoot).catch(() => {}); - await safeUnlink(fsUnlink, publishLockPath).catch(() => {}); - publishLockAcquired = false; - } - - if (restoreFailures.length > 0) { - const originalMessage = error instanceof Error ? error.message : String(error); - const failureSummary = restoreFailures - .map(f => `${f.key} (retained backup: ${f.backup}, target: ${f.target}): ${f.message}`) - .join('; '); - throw new CurateInputExportError({ - code: 'PUBLISH_ROLLBACK_FAILED', - table: 'publish', - key: restoreFailures.map(f => f.key).join(','), - detail: `export failed (${originalMessage}) and backup restoration failed; retained backups: ${failureSummary}`, - cause: error, - }); - } - - throw error; - } - - // 8. Post-commit lock release & backup cleanup (outside rollback scope: publication is already committed). - const cleanupWarnings: string[] = []; - if (publishLockAcquired) { - try { - await safeUnlink(fsUnlink, publishLockPath); - publishLockAcquired = false; - } catch (lockCleanupErr) { - const msg = - lockCleanupErr instanceof Error ? lockCleanupErr.message : String(lockCleanupErr); - cleanupWarnings.push( - `Failed to remove post-commit publish lock ${publishLockPath} (publication committed): ${msg}` - ); - } - } - for (const key of backedUp) { - try { - await safeUnlink(fsUnlink, backups[key]); - } catch (cleanupErr) { - const msg = cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr); - cleanupWarnings.push( - `Failed to remove post-commit backup ${backups[key]} (publication committed): ${msg}` - ); - } - } - - return { - outDir, - generationId, - generationDir, - currentLink, - chunkSize, - delistingMappingSource, - providerMapping: { - path: generationFiles.providerMapping, - rowsIn: providerMappingRowsIn, - rowsOut: providerMappingRowsOut, - bytesWritten: providerMappingBytes, - }, - listingCurrencies: { - path: generationFiles.listingCurrencies, - rowsIn: listingCurrenciesRowsIn, - rowsOut: listingCurrenciesRowsOut, - bytesWritten: listingCurrenciesBytes, - }, - delistings: { - path: generationFiles.delistings, - rowsIn: delistingsStats.rowsIn, - rowsOut: delistingsStats.rowsOut, - bytesWritten: delistingsBytes, - stats: delistingsStats, - }, - totalBytesWritten: providerMappingBytes + listingCurrenciesBytes + delistingsBytes, - cleanupWarnings, - }; -} diff --git a/apps/stock/data-pipeline/src/security-master/export-raw-bson.ts b/apps/stock/data-pipeline/src/security-master/export-raw-bson.ts deleted file mode 100644 index 8ba7e632..00000000 --- a/apps/stock/data-pipeline/src/security-master/export-raw-bson.ts +++ /dev/null @@ -1,670 +0,0 @@ -import { createHash, randomUUID } from 'node:crypto'; -import { mkdir, open, rename, unlink } from 'node:fs/promises'; -import { join } from 'node:path'; -import type { MongoDBClient } from '@stock-bot/mongodb'; - -/** - * M1 allowlisted MongoDB collections whose concatenated raw BSON documents are consumed by - * `tools/curate-etl` (`curate-bars-1d`, `curate-adj-factors`, `curate-corporate-actions`, - * `curate-fx-1d`, `curate-shorts`, `curate-events`). - */ -export const RAW_BSON_EXPORT_COLLECTIONS = Object.freeze([ - 'eodPrices', - 'qmSplits', - 'qmDividends', - 'qmPrices', - 'teMarketData', - 'ceoShorts', - 'qmFilings', - 'qmEarnings', -] as const); - -export type RawBsonExportCollection = (typeof RAW_BSON_EXPORT_COLLECTIONS)[number]; - -const RAW_BSON_EXPORT_COLLECTION_SET: ReadonlySet = new Set(RAW_BSON_EXPORT_COLLECTIONS); - -export const MIN_RAW_BSON_DOC_BYTES = 5; -/** Matches `tools/curate-etl` `bson_stream` ceiling (16 MiB BSON max + 16 KiB wire headroom). */ -export const DEFAULT_MAX_RAW_BSON_DOC_BYTES = 16 * 1024 * 1024 + 16 * 1024; -export const DEFAULT_WRITE_BUFFER_BYTES = 8 * 1024 * 1024; -export const MIN_WRITE_BUFFER_BYTES = 64; -export const MAX_WRITE_BUFFER_BYTES = 64 * 1024 * 1024; -export const DEFAULT_RAW_BSON_BATCH_SIZE = 4_096; -export const MAX_RAW_BSON_BATCH_SIZE = 100_000; - -export function isRawBsonExportCollection(value: string): value is RawBsonExportCollection { - return RAW_BSON_EXPORT_COLLECTION_SET.has(value); -} - -export type RawBsonExportErrorCode = - | 'DISALLOWED_COLLECTION' - | 'INVALID_OPTION' - | 'INVALID_SOURCE' - | 'INVALID_BSON_FRAME'; - -export interface RawBsonExportErrorOptions { - readonly code: RawBsonExportErrorCode; - readonly collection: string; - readonly docOrdinal?: number; - readonly detail: string; - readonly cause?: unknown; -} - -export class RawBsonExportError extends Error { - readonly code: RawBsonExportErrorCode; - readonly collection: string; - readonly docOrdinal?: number; - - constructor(options: RawBsonExportErrorOptions) { - const ordinalPart = options.docOrdinal !== undefined ? ` doc#${options.docOrdinal}` : ''; - super( - `[${options.code}] ${options.collection}${ordinalPart}: ${options.detail}`, - options.cause !== undefined ? { cause: options.cause } : undefined - ); - this.name = 'RawBsonExportError'; - this.code = options.code; - this.collection = options.collection; - if (options.docOrdinal !== undefined) { - this.docOrdinal = options.docOrdinal; - } - } -} - -export interface RawBsonFindOptions { - readonly raw: true; - readonly batchSize?: number; - readonly limit?: number; -} - -export interface ReadOnlyRawBsonCursor extends AsyncIterable { - close?(): Promise; -} - -export interface ReadOnlyRawBsonCollection { - find(filter: Record, options: RawBsonFindOptions): ReadOnlyRawBsonCursor; -} - -export interface ReadOnlyMongoRawBsonClient { - isReadOnly(): boolean; - getCollection(name: string): ReadOnlyRawBsonCollection; -} - -export interface ReadOnlyRawBsonSource { - isReadOnly(): boolean; - find( - collectionName: string, - filter: Record, - options: RawBsonFindOptions - ): Promise> | AsyncIterable; -} - -// Compile-time structural compatibility check (type-only, erased at runtime): -// verifies the real `MongoDBClient` satisfies `ReadOnlyMongoRawBsonClient`. -type AssertAssignable = true; -export type MongoDBClientRawBsonSourceCheck = AssertAssignable< - ReadOnlyMongoRawBsonClient, - MongoDBClient ->; - -export interface ExportRawBsonFileHandle { - write( - buffer: Uint8Array, - offset?: number | null, - length?: number | null, - position?: number | null - ): Promise<{ bytesWritten: number }>; - sync(): Promise; - close(): Promise; -} - -export interface ExportRawBsonFsHooks { - readonly mkdir?: typeof mkdir; - readonly open?: (path: string, flags: string) => Promise; - readonly rename?: typeof rename; - readonly unlink?: typeof unlink; -} - -export interface ExportRawBsonCollectionOptions { - readonly collection: string; - readonly outDir: string; - readonly eodSymbol?: string; - readonly teSymbol?: string; - readonly limit?: number; - readonly batchSize?: number; - readonly writeBufferBytes?: number; - readonly maxDocBytes?: number; - readonly fs?: ExportRawBsonFsHooks; -} - -export interface ExportRawBsonCollectionResult { - readonly collection: RawBsonExportCollection; - readonly outPath: string; - readonly docsWritten: number; - readonly bytesWritten: number; - readonly elapsedMs: number; - readonly sha256: string; - readonly filter: Readonly>; -} - -function isAsyncIterable(value: unknown): value is AsyncIterable { - if (value === null || typeof value !== 'object' || Array.isArray(value)) { - return false; - } - return typeof (value as Partial>)[Symbol.asyncIterator] === 'function'; -} - -/** - * Adapts a read-only `MongoDBClient` into a streaming `ReadOnlyRawBsonSource`. - * Rejects non-read-only clients and buffered/non-AsyncIterable cursor results, and - * guarantees `cursor.close()` runs in `finally` on completion, early break, or error. - */ -export function createReadOnlyMongoRawBsonSource( - client: ReadOnlyMongoRawBsonClient -): ReadOnlyRawBsonSource { - if (!client || typeof client.isReadOnly !== 'function' || client.isReadOnly() !== true) { - throw new RawBsonExportError({ - code: 'INVALID_SOURCE', - collection: '*', - detail: 'MongoDB client must be configured in read-only mode (isReadOnly() === true)', - }); - } - - return { - isReadOnly(): boolean { - return client.isReadOnly() === true; - }, - find( - collectionName: string, - filter: Record, - options: RawBsonFindOptions - ): AsyncIterable { - if (client.isReadOnly() !== true) { - throw new RawBsonExportError({ - code: 'INVALID_SOURCE', - collection: collectionName, - detail: 'MongoDB client must remain in read-only mode (isReadOnly() === true)', - }); - } - if (!options || options.raw !== true) { - throw new RawBsonExportError({ - code: 'INVALID_OPTION', - collection: collectionName, - detail: 'Raw BSON export requires find option { raw: true }', - }); - } - - const cursor = client.getCollection(collectionName).find(filter, options); - if (!isAsyncIterable(cursor)) { - throw new RawBsonExportError({ - code: 'INVALID_SOURCE', - collection: collectionName, - detail: - 'Collection find() must return a streaming AsyncIterable cursor (buffered arrays are not allowed)', - }); - } - - return { - async *[Symbol.asyncIterator]() { - let hasPrimaryError = false; - try { - for await (const doc of cursor) { - yield doc; - } - } catch (error) { - hasPrimaryError = true; - throw error; - } finally { - if (typeof cursor.close === 'function') { - if (hasPrimaryError) { - try { - await cursor.close(); - } catch { - // Preserve primary iteration error when close also fails. - } - } else { - await cursor.close(); - } - } - } - }, - }; - }, - }; -} - -/** - * Validates that a single raw BSON document frame is a `Uint8Array` of length in - * `[5, maxDocBytes]` whose leading signed 32-bit little-endian length prefix equals - * `byteLength` and whose final byte is `0x00`. - */ -export function validateRawBsonFrame( - bytes: unknown, - collection: string, - docOrdinal: number, - maxDocBytes: number = DEFAULT_MAX_RAW_BSON_DOC_BYTES -): Uint8Array { - if (!(bytes instanceof Uint8Array)) { - throw new RawBsonExportError({ - code: 'INVALID_BSON_FRAME', - collection, - docOrdinal, - detail: `expected Uint8Array raw BSON frame, got ${bytes === null ? 'null' : typeof bytes}`, - }); - } - - const byteLength = bytes.byteLength; - if (byteLength < MIN_RAW_BSON_DOC_BYTES) { - throw new RawBsonExportError({ - code: 'INVALID_BSON_FRAME', - collection, - docOrdinal, - detail: `frame length ${byteLength} is below minimum BSON document size (${MIN_RAW_BSON_DOC_BYTES})`, - }); - } - - if (byteLength > maxDocBytes) { - throw new RawBsonExportError({ - code: 'INVALID_BSON_FRAME', - collection, - docOrdinal, - detail: `frame length ${byteLength} exceeds maxDocBytes (${maxDocBytes})`, - }); - } - - const b0 = bytes[0] ?? 0; - const b1 = bytes[1] ?? 0; - const b2 = bytes[2] ?? 0; - const b3 = bytes[3] ?? 0; - const declaredLen = (b0 | (b1 << 8) | (b2 << 16) | (b3 << 24)) | 0; - - if (declaredLen !== byteLength) { - throw new RawBsonExportError({ - code: 'INVALID_BSON_FRAME', - collection, - docOrdinal, - detail: `4-byte LE length prefix (${declaredLen}) disagrees with frame byteLength (${byteLength})`, - }); - } - - const lastByte = bytes[byteLength - 1]; - if (lastByte !== 0x00) { - throw new RawBsonExportError({ - code: 'INVALID_BSON_FRAME', - collection, - docOrdinal, - detail: `missing trailing 0x00 terminator (got 0x${(lastByte ?? 0).toString(16).padStart(2, '0')})`, - }); - } - - return bytes; -} - -/** - * Walks concatenated length-prefixed raw BSON documents using the exact framing rules - * implemented by `tools/curate-etl/src/bson_eod_prices.rs::iter_raw_bson_docs` - * (signed 32-bit LE length prefix `>= 5`, `<= maxDocBytes`, exact buffer bounds, trailing `0x00`). - */ -export function walkRawBsonFrames( - bytes: Uint8Array, - maxDocBytes: number = DEFAULT_MAX_RAW_BSON_DOC_BYTES, - collection: string = '' -): Uint8Array[] { - const frames: Uint8Array[] = []; - let offset = 0; - let docOrdinal = 0; - - while (offset < bytes.byteLength) { - const remaining = bytes.byteLength - offset; - if (remaining < 4) { - throw new RawBsonExportError({ - code: 'INVALID_BSON_FRAME', - collection, - docOrdinal, - detail: `truncated BSON length prefix at byte offset ${offset} (${remaining} bytes remaining)`, - }); - } - - const b0 = bytes[offset] ?? 0; - const b1 = bytes[offset + 1] ?? 0; - const b2 = bytes[offset + 2] ?? 0; - const b3 = bytes[offset + 3] ?? 0; - const declaredLen = (b0 | (b1 << 8) | (b2 << 16) | (b3 << 24)) | 0; - - if (declaredLen < MIN_RAW_BSON_DOC_BYTES) { - throw new RawBsonExportError({ - code: 'INVALID_BSON_FRAME', - collection, - docOrdinal, - detail: `corrupt BSON document length ${declaredLen} at byte offset ${offset}`, - }); - } - if (declaredLen > maxDocBytes) { - throw new RawBsonExportError({ - code: 'INVALID_BSON_FRAME', - collection, - docOrdinal, - detail: `BSON document length ${declaredLen} at byte offset ${offset} exceeds maxDocBytes (${maxDocBytes})`, - }); - } - if (declaredLen > remaining) { - throw new RawBsonExportError({ - code: 'INVALID_BSON_FRAME', - collection, - docOrdinal, - detail: `truncated BSON document at byte offset ${offset} (declared ${declaredLen}, remaining ${remaining})`, - }); - } - - const frame = bytes.subarray(offset, offset + declaredLen); - const lastByte = frame[declaredLen - 1]; - if (lastByte !== 0x00) { - throw new RawBsonExportError({ - code: 'INVALID_BSON_FRAME', - collection, - docOrdinal, - detail: `missing trailing 0x00 terminator at byte offset ${offset}`, - }); - } - - frames.push(frame); - offset += declaredLen; - docOrdinal += 1; - } - - return frames; -} - -interface ValidatedExportOptions { - readonly collection: RawBsonExportCollection; - readonly outDir: string; - readonly filter: Readonly>; - readonly limit?: number; - readonly batchSize: number; - readonly writeBufferBytes: number; - readonly maxDocBytes: number; -} - -function validateExportOptions(options: ExportRawBsonCollectionOptions): ValidatedExportOptions { - const collectionName = typeof options?.collection === 'string' ? options.collection : ''; - if (!isRawBsonExportCollection(collectionName)) { - throw new RawBsonExportError({ - code: 'DISALLOWED_COLLECTION', - collection: collectionName || '', - detail: `collection "${collectionName}" is not in the M1 allowlist (${RAW_BSON_EXPORT_COLLECTIONS.join(', ')})`, - }); - } - - if (typeof options.outDir !== 'string' || options.outDir.trim().length === 0) { - throw new RawBsonExportError({ - code: 'INVALID_OPTION', - collection: collectionName, - detail: 'outDir must be a non-empty string', - }); - } - - const writeBufferBytes = options.writeBufferBytes ?? DEFAULT_WRITE_BUFFER_BYTES; - if ( - !Number.isSafeInteger(writeBufferBytes) || - writeBufferBytes < MIN_WRITE_BUFFER_BYTES || - writeBufferBytes > MAX_WRITE_BUFFER_BYTES - ) { - throw new RawBsonExportError({ - code: 'INVALID_OPTION', - collection: collectionName, - detail: `writeBufferBytes must be an integer in [${MIN_WRITE_BUFFER_BYTES}, ${MAX_WRITE_BUFFER_BYTES}] (got ${String(writeBufferBytes)})`, - }); - } - - const maxDocBytes = options.maxDocBytes ?? DEFAULT_MAX_RAW_BSON_DOC_BYTES; - if ( - !Number.isSafeInteger(maxDocBytes) || - maxDocBytes < MIN_RAW_BSON_DOC_BYTES || - maxDocBytes > MAX_WRITE_BUFFER_BYTES - ) { - throw new RawBsonExportError({ - code: 'INVALID_OPTION', - collection: collectionName, - detail: `maxDocBytes must be an integer in [${MIN_RAW_BSON_DOC_BYTES}, ${MAX_WRITE_BUFFER_BYTES}] (got ${String(maxDocBytes)})`, - }); - } - - const batchSize = options.batchSize ?? DEFAULT_RAW_BSON_BATCH_SIZE; - if (!Number.isSafeInteger(batchSize) || batchSize < 1 || batchSize > MAX_RAW_BSON_BATCH_SIZE) { - throw new RawBsonExportError({ - code: 'INVALID_OPTION', - collection: collectionName, - detail: `batchSize must be an integer in [1, ${MAX_RAW_BSON_BATCH_SIZE}] (got ${String(batchSize)})`, - }); - } - - let limit: number | undefined; - if (options.limit !== undefined) { - if (!Number.isSafeInteger(options.limit) || options.limit < 1) { - throw new RawBsonExportError({ - code: 'INVALID_OPTION', - collection: collectionName, - detail: `limit must be a positive safe integer (got ${String(options.limit)})`, - }); - } - limit = options.limit; - } - - let filter: Record = {}; - if (options.eodSymbol !== undefined) { - if (collectionName !== 'eodPrices') { - throw new RawBsonExportError({ - code: 'INVALID_OPTION', - collection: collectionName, - detail: '--eod-symbol filter is only permitted for collection "eodPrices"', - }); - } - if (typeof options.eodSymbol !== 'string' || options.eodSymbol.trim().length === 0) { - throw new RawBsonExportError({ - code: 'INVALID_OPTION', - collection: collectionName, - detail: 'eodSymbol must be a non-empty string', - }); - } - filter = { eodSearchCode: options.eodSymbol }; - } - - if (options.teSymbol !== undefined) { - if (collectionName !== 'teMarketData') { - throw new RawBsonExportError({ - code: 'INVALID_OPTION', - collection: collectionName, - detail: '--te-symbol filter is only permitted for collection "teMarketData"', - }); - } - if (typeof options.teSymbol !== 'string' || options.teSymbol.trim().length === 0) { - throw new RawBsonExportError({ - code: 'INVALID_OPTION', - collection: collectionName, - detail: 'teSymbol must be a non-empty string', - }); - } - filter = { teSymbol: options.teSymbol }; - } - - return { - collection: collectionName, - outDir: options.outDir.trim(), - filter: Object.freeze(filter), - ...(limit !== undefined ? { limit } : {}), - batchSize, - writeBufferBytes, - maxDocBytes, - }; -} - -async function writeAll( - handle: ExportRawBsonFileHandle, - buffer: Uint8Array, - length: number, - collection: string, - tempPath: string -): Promise { - let offset = 0; - while (offset < length) { - const remaining = length - offset; - const result = await handle.write(buffer, offset, remaining); - if ( - !result || - typeof result.bytesWritten !== 'number' || - !Number.isInteger(result.bytesWritten) || - result.bytesWritten <= 0 - ) { - throw new Error( - `Short write (bytesWritten=${String(result?.bytesWritten)}) while exporting "${collection}" to ${tempPath}` - ); - } - if (result.bytesWritten > remaining) { - throw new Error( - `Write hook reported bytesWritten=${result.bytesWritten} exceeding requested length=${remaining} while exporting "${collection}" to ${tempPath}` - ); - } - offset += result.bytesWritten; - } -} - -/** - * Streams an allowlisted MongoDB collection as untouched raw BSON frames into - * `/.bson` using a fixed-size write buffer, incremental SHA-256 hashing, - * and atomic same-directory temp-file publish (`open('wx')` -> `write` -> `sync` -> `close` -> `rename`). - */ -export async function exportRawBsonCollection( - source: ReadOnlyRawBsonSource, - options: ExportRawBsonCollectionOptions -): Promise { - const validated = validateExportOptions(options); - - if ( - !source || - typeof source.isReadOnly !== 'function' || - source.isReadOnly() !== true || - typeof source.find !== 'function' - ) { - throw new RawBsonExportError({ - code: 'INVALID_SOURCE', - collection: validated.collection, - detail: 'Raw BSON exporter requires a read-only source (isReadOnly() === true)', - }); - } - - const mkdirFn = options.fs?.mkdir ?? mkdir; - const openFn: (path: string, flags: string) => Promise = - options.fs?.open ?? ((filePath: string, flags: string) => open(filePath, flags)); - const renameFn = options.fs?.rename ?? rename; - const unlinkFn = options.fs?.unlink ?? unlink; - - const startMs = performance.now(); - - await mkdirFn(validated.outDir, { recursive: true }); - - const outPath = join(validated.outDir, `${validated.collection}.bson`); - const tempPath = join( - validated.outDir, - `.${validated.collection}.bson.${process.pid}.${randomUUID()}.tmp` - ); - - const handle = await openFn(tempPath, 'wx'); - let handleClosed = false; - let renamed = false; - - const writeBuffer = new Uint8Array(validated.writeBufferBytes); - let buffered = 0; - const hash = createHash('sha256'); - let docsWritten = 0; - let bytesWritten = 0; - - const flushBuffer = async (): Promise => { - if (buffered > 0) { - await writeAll(handle, writeBuffer, buffered, validated.collection, tempPath); - buffered = 0; - } - }; - - try { - const findOptions: RawBsonFindOptions = { - raw: true, - batchSize: validated.batchSize, - ...(validated.limit !== undefined ? { limit: validated.limit } : {}), - }; - - const iterable = await source.find( - validated.collection, - { ...validated.filter }, - findOptions - ); - - if (!isAsyncIterable(iterable)) { - throw new RawBsonExportError({ - code: 'INVALID_SOURCE', - collection: validated.collection, - detail: - 'Source find() must return a streaming AsyncIterable (buffered arrays are not allowed)', - }); - } - - for await (const rawDoc of iterable) { - if (validated.limit !== undefined && docsWritten >= validated.limit) { - break; - } - - const frame = validateRawBsonFrame( - rawDoc, - validated.collection, - docsWritten, - validated.maxDocBytes - ); - const frameLen = frame.byteLength; - hash.update(frame); - - if (frameLen > validated.writeBufferBytes) { - await flushBuffer(); - await writeAll(handle, frame, frameLen, validated.collection, tempPath); - } else { - if (buffered + frameLen > validated.writeBufferBytes) { - await flushBuffer(); - } - writeBuffer.set(frame, buffered); - buffered += frameLen; - } - - docsWritten += 1; - bytesWritten += frameLen; - - if (validated.limit !== undefined && docsWritten >= validated.limit) { - break; - } - } - - await flushBuffer(); - await handle.sync(); - await handle.close(); - handleClosed = true; - - await renameFn(tempPath, outPath); - renamed = true; - } catch (error) { - if (!handleClosed) { - await handle.close().catch(() => {}); - } - if (!renamed) { - await unlinkFn(tempPath).catch(() => {}); - } - throw error; - } - - const elapsedMs = Math.max(0, performance.now() - startMs); - - return { - collection: validated.collection, - outPath, - docsWritten, - bytesWritten, - elapsedMs, - sha256: hash.digest('hex'), - filter: validated.filter, - }; -} diff --git a/apps/stock/data-pipeline/src/security-master/index.ts b/apps/stock/data-pipeline/src/security-master/index.ts index 85707ca8..7dbcd44c 100644 --- a/apps/stock/data-pipeline/src/security-master/index.ts +++ b/apps/stock/data-pipeline/src/security-master/index.ts @@ -47,100 +47,6 @@ export { type UnresolvedExchangeRecord, } from './exchange-pass1'; -export { - buildDelistingExportRows, - CURATE_INPUT_CURRENT_LINK, - CURATE_INPUT_FILES, - CURATE_INPUT_GENERATIONS_DIR, - CURATE_INPUT_PUBLISH_LOCK, - CurateInputExportError, - DEFAULT_DELISTING_MAPPING_SOURCE, - DEFAULT_EXPORT_CHUNK_SIZE, - DEFAULT_PUBLISH_LOCK_TIMEOUT_MS, - exportCurateInputs, - formatDelistingsTsv, - formatListingCurrenciesTsv, - formatPlainDecimal, - formatProviderMappingTsv, - isValidStrictYmd, - MAX_EXPORT_CHUNK_SIZE, - pinCurateInputSnapshot, - type BuildDelistingExportRowsOptions, - type BuildDelistingExportRowsResult, - type ContinuityExportSourceRow, - type CurateInputExportErrorCode, - type CurateInputExportErrorOptions, - type DelistingExportRow, - type DelistingExportSkippedByReason, - type DelistingExportStats, - type ExportCurateInputsFileStats, - type ExportCurateInputsFsHooks, - type ExportCurateInputsOptions, - type ExportCurateInputsResult, - type ListingCurrencyExportRow, - type ListingDelistingSourceRow, - type PinnedCurateInputSnapshot, - type ProviderMappingExportRow, -} from './export-curate-inputs'; - -export { - assertExportCurateInputsSafety, - EXPORT_CURATE_INPUTS_USAGE, - formatExportCurateInputsSummary, - parseExportCurateInputsArgs, - runCli as runExportCurateInputsCli, - runExportCurateInputs, - type ParsedExportCurateInputsArgs, - type RunExportCurateInputsDeps, - type RunExportCurateInputsOptions, - type RunExportCurateInputsOutput, -} from './run-export-curate-inputs'; - -export { - createReadOnlyMongoRawBsonSource, - DEFAULT_MAX_RAW_BSON_DOC_BYTES, - DEFAULT_RAW_BSON_BATCH_SIZE, - DEFAULT_WRITE_BUFFER_BYTES, - exportRawBsonCollection, - isRawBsonExportCollection, - MAX_RAW_BSON_BATCH_SIZE, - MAX_WRITE_BUFFER_BYTES, - MIN_RAW_BSON_DOC_BYTES, - MIN_WRITE_BUFFER_BYTES, - RAW_BSON_EXPORT_COLLECTIONS, - RawBsonExportError, - validateRawBsonFrame, - walkRawBsonFrames, - type ExportRawBsonCollectionOptions, - type ExportRawBsonCollectionResult, - type ExportRawBsonFileHandle, - type ExportRawBsonFsHooks, - type MongoDBClientRawBsonSourceCheck, - type RawBsonExportCollection, - type RawBsonExportErrorCode, - type RawBsonExportErrorOptions, - type RawBsonFindOptions, - type ReadOnlyMongoRawBsonClient, - type ReadOnlyRawBsonCollection, - type ReadOnlyRawBsonCursor, - type ReadOnlyRawBsonSource, -} from './export-raw-bson'; - -export { - assertExportRawBsonSafety, - EXPORT_RAW_BSON_USAGE, - formatExportRawBsonSummary, - parseExportRawBsonArgs, - runCli as runExportRawBsonCli, - runExportRawBson, - type ParsedExportRawBsonArgs, - type RawBsonMongoHandle, - type RunExportRawBsonCliOverrides, - type RunExportRawBsonDeps, - type RunExportRawBsonOptions, - type RunExportRawBsonOutput, -} from './run-export-raw-bson'; - export { escapeSqlLiteral, generateExchangeSeedSql, @@ -359,47 +265,6 @@ export { type UnknownSecurityTypeCount, } from './security-type'; -export { - parseProbeSourceFieldShapesArgs, - PROBE_SOURCE_FIELD_SHAPES_USAGE, - runCli as runProbeSourceFieldShapesCli, - runSourceFieldShapesProbe, - type ParsedProbeSourceFieldShapesArgs, - type RunSourceFieldShapesProbeDeps, - type RunSourceFieldShapesProbeOptions, - type RunSourceFieldShapesProbeOutput, -} from './probe-source-field-shapes'; - -export { - DEFAULT_FIELD_SHAPE_LIMIT, - DEFAULT_MAX_EXAMPLE_LENGTH, - DEFAULT_MAX_EXAMPLES, - FIELD_SHAPE_PROBE_COLLECTIONS, - FIELD_VALUE_TYPES, - isFieldShapeProbeCollection, - MAX_EXAMPLE_LENGTH_CAP, - MAX_EXAMPLES_CAP, - MAX_FIELD_SHAPE_LIMIT, - normalizeProbeCollections, - readFieldShapes, - renderFieldShapesMarkdown, - STRING_PATTERN_CLASSES, - summarizeFieldShapes, - UnknownProbeCollectionError, - type CollectionFieldShapesProbeResult, - type CollectionFieldShapesSummary, - type FieldShapeProbeCollection, - type FieldShapeSummary, - type FieldStringStats, - type FieldValueType, - type FieldValueTypeCounts, - type ReadFieldShapesOptions, - type ReadFieldShapesResult, - type StringPatternClass, - type StringPatternCounts, - type SummarizeFieldShapesOptions, -} from './source-field-shapes'; - export { adaptCeoSymbolDoc, adaptEodSymbolChangeDoc, diff --git a/apps/stock/data-pipeline/src/security-master/instrument-stage-a.ts b/apps/stock/data-pipeline/src/security-master/instrument-stage-a.ts index 5a0acb60..f840113e 100644 --- a/apps/stock/data-pipeline/src/security-master/instrument-stage-a.ts +++ b/apps/stock/data-pipeline/src/security-master/instrument-stage-a.ts @@ -9,15 +9,9 @@ import { compareAscii } from './exchange-pass1'; export const STAGE_A_SOURCES = ['ib', 'eod'] as const; -export const SYNTHETIC_EOD_ISIN_PREFIX = 'SYN:EOD:' as const; - -export function isSyntheticInstrumentKey(value: string): boolean { - return value.startsWith(SYNTHETIC_EOD_ISIN_PREFIX); -} - export type StageASource = (typeof STAGE_A_SOURCES)[number]; -export type StageAMatchMethod = 'tier1_isin' | 'tier2_cusip' | 'tier3_ticker_span'; +export type StageAMatchMethod = 'tier1_isin' | 'tier2_cusip'; export type StageAConflictKind = 'isin_cusip_mismatch' | 'duplicate_source_id'; @@ -70,7 +64,6 @@ export interface StageASourceStats { total: number; tier1Isin: number; tier2Cusip: number; - tier3Synthetic?: number; unresolved: number; conflict: number; } @@ -83,7 +76,6 @@ export interface StageAStats { export interface MatchInstrumentsStageAOptions { readonly nameSourcePrecedence?: readonly StageASource[]; - readonly allowIdentifierlessEod?: boolean; } export interface StageAMatchResult { @@ -101,7 +93,6 @@ interface BestSourceName { interface InstrumentAccumulator { members: StageAInstrumentMember[]; bestNameBySource: Record; - fallbackCountry: string | null; } export function isStageASource(value: unknown): value is StageASource { @@ -239,45 +230,6 @@ export function matchInstrumentsStageA( const resolved = resolveIsin(record); if (resolved.isin === null) { - if (options.allowIdentifierlessEod === true && source === 'eod') { - const syntheticKey = `${SYNTHETIC_EOD_ISIN_PREFIX}${sourceId.trim().toUpperCase()}`; - const normalizedCountry = normalizeCode(record.country); - const fallbackCountry = - normalizedCountry !== null && /^[A-Z]{2}$/.test(normalizedCountry) - ? normalizedCountry - : sourceId.endsWith('.TO') || - sourceId.endsWith('.V') || - sourceId.endsWith('.NEO') || - sourceId.endsWith('.CN') - ? 'CA' - : 'US'; - const currency = normalizeCode(record.currency); - const name = normalizeName(record.name); - let acc = instrumentsByIsin.get(syntheticKey); - if (acc === undefined) { - acc = { - members: [], - bestNameBySource: { ib: null, eod: null }, - fallbackCountry, - }; - instrumentsByIsin.set(syntheticKey, acc); - } - acc.members.push({ - source, - sourceId, - currency, - method: 'tier3_ticker_span', - }); - if (name !== null) { - const existingBest = acc.bestNameBySource[source]; - if (existingBest === null || compareAscii(sourceId, existingBest.sourceId) < 0) { - acc.bestNameBySource[source] = { sourceId, name }; - } - } - sourceStats.tier3Synthetic = (sourceStats.tier3Synthetic ?? 0) + 1; - continue; - } - unresolved.push({ source, sourceId, @@ -334,7 +286,6 @@ export function matchInstrumentsStageA( ib: null, eod: null, }, - fallbackCountry: null, }; instrumentsByIsin.set(resolved.isin, acc); } @@ -362,13 +313,10 @@ export function matchInstrumentsStageA( const instruments: StageAInstrumentCandidate[] = []; for (const [primaryIsin, acc] of instrumentsByIsin.entries()) { - const isSynthetic = isSyntheticInstrumentKey(primaryIsin); - const issuerCountry = isSynthetic ? (acc.fallbackCountry ?? 'US') : primaryIsin.slice(0, 2); - const embeddedCusip = isSynthetic ? '' : primaryIsin.slice(2, 11); + const issuerCountry = primaryIsin.slice(0, 2); + const embeddedCusip = primaryIsin.slice(2, 11); const primaryCusip = - !isSynthetic && isNorthAmericaCountry(issuerCountry) && isValidCusip(embeddedCusip) - ? embeddedCusip - : null; + isNorthAmericaCountry(issuerCountry) && isValidCusip(embeddedCusip) ? embeddedCusip : null; let canonicalName: string | null = null; for (const source of nameSourcePrecedence) { diff --git a/apps/stock/data-pipeline/src/security-master/listing-stage-b.ts b/apps/stock/data-pipeline/src/security-master/listing-stage-b.ts index 1d3fdec2..69a816e5 100644 --- a/apps/stock/data-pipeline/src/security-master/listing-stage-b.ts +++ b/apps/stock/data-pipeline/src/security-master/listing-stage-b.ts @@ -6,11 +6,10 @@ import { } from '../normalization/bar-spans'; import { parseTickerDetailed } from '../normalization/ticker'; import { compareAscii, type ExchangeRole } from './exchange-pass1'; -import { - isSyntheticInstrumentKey, - type StageAInstrumentCandidate, - type StageAMatchMethod, - type StageASource, +import type { + StageAInstrumentCandidate, + StageAMatchMethod, + StageASource, } from './instrument-stage-a'; export const MAX_TICKER_ROOT_LENGTH = 24; @@ -45,9 +44,6 @@ export interface StageBIbContractInput { conid: number; currency?: string | null; primaryExchange: string | null; - ticker?: string | null; - name?: string | null; - exchangeId?: string | null; } export interface StageBTickerSourceInput { @@ -58,7 +54,6 @@ export interface StageBTickerSourceInput { role: ExchangeRole | null; currency?: string | null; span: SpanDateRange | null; - name?: string | null; } export interface StageBSymbolChangeInput { @@ -82,8 +77,6 @@ export interface StageBInput { export interface MatchListingsStageBOptions { readonly spanOverlapToleranceDays?: number; - readonly enableIbTickerDisambiguation?: boolean; - readonly allowUniqueTickerFallbackForCrawlOnlyCeo?: boolean; } export interface StageBListingCandidate extends ListingNaturalKey { @@ -208,7 +201,7 @@ interface StagedIbCandidate { currency: string; conid: number; primaryExchange: string | null; - method: StageBMatchMethod; + method: StageAMatchMethod; } const ISO_MIC_PATTERN = /^[A-Z0-9]{4}$/; @@ -223,15 +216,8 @@ function isStageASourceValue(value: unknown): value is StageASource { return value === 'ib' || value === 'eod'; } -function isStageAMatchMethodValue( - value: unknown, - allowSyntheticTier3 = false -): value is StageAMatchMethod { - return ( - value === 'tier1_isin' || - value === 'tier2_cusip' || - (allowSyntheticTier3 && value === 'tier3_ticker_span') - ); +function isStageAMatchMethodValue(value: unknown): value is StageAMatchMethod { + return value === 'tier1_isin' || value === 'tier2_cusip'; } function isStageBTickerSourceValue(value: unknown): value is StageBTickerSource { @@ -672,8 +658,7 @@ export function matchListingsStageB( `Invalid empty or non-string sourceId at instruments[${i}].members[${j}]` ); } - const isSyntheticInst = isSyntheticInstrumentKey(inst.primaryIsin); - if (!isStageAMatchMethodValue(member.method, isSyntheticInst)) { + if (!isStageAMatchMethodValue(member.method)) { throw new Error( `Unknown Stage A member method "${String(member.method)}" at instruments[${i}].members[${j}]` ); @@ -880,11 +865,7 @@ export function matchListingsStageB( const listingsByNaturalKey = new Map(); const listingsByInstrumentCurrency = new Map>(); const listingsByTickerKey = new Map(); - const listingsByCurrencyTickerKey = new Map(); const listingByEodSourceId = new Map(); - const enableIbTickerDisambiguation = options.enableIbTickerDisambiguation === true; - const allowUniqueTickerFallbackForCrawlOnlyCeo = - options.allowUniqueTickerFallbackForCrawlOnlyCeo === true; const providerMappings: StageBProviderMappingCandidate[] = []; const unresolved: StageBUnresolvedRecord[] = []; @@ -1025,14 +1006,6 @@ export function matchListingsStageB( listingsByTickerKey.set(tickerKey, tickerList); } tickerList.push({ acc, aliasBounds: null }); - - const currTickerKey = `${currency}\u0000${ticker.tickerRoot}\u0000${ticker.classSuffix}`; - let currTickerList = listingsByCurrencyTickerKey.get(currTickerKey); - if (currTickerList === undefined) { - currTickerList = []; - listingsByCurrencyTickerKey.set(currTickerKey, currTickerList); - } - currTickerList.push(acc); } else if (validSpan !== null) { // Associative & commutative min/max widening ensures shuffle invariance. if (acc.listedFrom === null || validSpan.firstBarDate < acc.listedFrom) { @@ -1170,84 +1143,7 @@ export function matchListingsStageB( } const primaryExchange = normalizeOptionalExchangeLabel(contract.primaryExchange); - let candidates = listingsByInstrumentCurrency.get(inst.primaryIsin)?.get(currency); - let matchMethod: StageBMatchMethod = member.method; - - const isActiveCandidate = (acc: ListingAccumulator): boolean => - acc.listedTo === null || acc.listedTo >= '2025-01-01'; - - const narrowIbCandidates = ( - pool: readonly ListingAccumulator[], - parsedTicker: { readonly tickerRoot: string; readonly classSuffix: string } | null - ): ListingAccumulator[] => { - let current = [...pool]; - if (current.length > 1 && parsedTicker !== null) { - const exactTicker = current.filter( - acc => - acc.key.tickerRoot === parsedTicker.tickerRoot && - acc.key.classSuffix === parsedTicker.classSuffix - ); - if (exactTicker.length > 0) { - current = exactTicker; - } - } - if (current.length > 1) { - const activeOnly = current.filter(isActiveCandidate); - if (activeOnly.length > 0) { - current = activeOnly; - } - } - if (current.length > 1) { - const primaryOnly = current.filter(acc => acc.key.mic !== 'OTCM'); - if (primaryOnly.length > 0) { - current = primaryOnly; - } - } - return current; - }; - - const parsedIbTicker = - enableIbTickerDisambiguation && typeof contract.ticker === 'string' - ? (() => { - const parsed = classifyTicker(contract.ticker, 'ib'); - return parsed.ok - ? { tickerRoot: parsed.tickerRoot, classSuffix: parsed.classSuffix } - : null; - })() - : null; - - if (enableIbTickerDisambiguation && candidates !== undefined && candidates.length > 1) { - candidates = narrowIbCandidates(candidates, parsedIbTicker); - } - - if ( - enableIbTickerDisambiguation && - (candidates === undefined || candidates.length === 0) && - parsedIbTicker !== null - ) { - const currTickerKey = `${currency}\u0000${parsedIbTicker.tickerRoot}\u0000${parsedIbTicker.classSuffix}`; - const tickerPool = listingsByCurrencyTickerKey.get(currTickerKey); - if (tickerPool !== undefined && tickerPool.length > 0) { - const ibIssuerPrefix = !isSyntheticInstrumentKey(inst.primaryIsin) - ? inst.primaryIsin.slice(0, 8) - : null; - const eligibleFallback = tickerPool.filter( - acc => - isSyntheticInstrumentKey(acc.key.primaryIsin) || - (ibIssuerPrefix !== null && - !isSyntheticInstrumentKey(acc.key.primaryIsin) && - acc.key.primaryIsin.slice(0, 8) === ibIssuerPrefix) || - isActiveCandidate(acc) - ); - if (eligibleFallback.length > 0) { - const narrowed = narrowIbCandidates(eligibleFallback, parsedIbTicker); - if (narrowed.length === 1) { - candidates = narrowed; - matchMethod = 'tier3_ticker_span'; - } - } - } - } + const candidates = listingsByInstrumentCurrency.get(inst.primaryIsin)?.get(currency); if (candidates === undefined || candidates.length === 0) { unresolved.push({ @@ -1294,7 +1190,7 @@ export function matchListingsStageB( currency, conid: contract.conid, primaryExchange, - method: matchMethod, + method: member.method, }); } } @@ -1587,29 +1483,6 @@ export function matchListingsStageB( primaryIsin: null, }); sourceStats.unresolved += 1; - } else if ( - allowUniqueTickerFallbackForCrawlOnlyCeo && - source === 'ceo' && - spanCheck.span.firstBarDate === spanCheck.span.lastBarDate && - candidates.length === 1 && - candidates[0] !== undefined && - candidates[0].aliasBounds === null && - candidates[0].acc.listedFrom !== null && - candidates[0].acc.listedTo !== null - ) { - // CEO symbols without ceoShorts history carry only a single-day crawl `lastSeen` date; - // when there is a single unique EOD listing for `(mic, currency, ticker)` with zero ticker - // reuse, attach cleanly using that listing's observed span. - const uniqueListing = candidates[0].acc; - providerMappings.push({ - source, - sourceId: record.sourceId, - listingKey: uniqueListing.key, - method: 'tier3_ticker_span', - validFrom: uniqueListing.listedFrom, - validTo: uniqueListing.listedTo, - }); - sourceStats.matched += 1; } else { unresolved.push({ source, diff --git a/apps/stock/data-pipeline/src/security-master/match-report.ts b/apps/stock/data-pipeline/src/security-master/match-report.ts index 7163a077..3e9ab06a 100644 --- a/apps/stock/data-pipeline/src/security-master/match-report.ts +++ b/apps/stock/data-pipeline/src/security-master/match-report.ts @@ -36,13 +36,6 @@ export type ExcludedByDesignStageBReason = (typeof EXCLUDED_BY_DESIGN_STAGE_B_RE export type SourceCountryLookup = ReadonlyMap | Readonly>; -export type GateOutOfScopeReason = - | 'zero_bar_catalog_ghost' - | 'uncovered_venue' - | 'non_equity_instrument'; - -export type GateOutOfScopeLookup = ReadonlyMap; - export interface MatchReportInput { readonly exchanges?: ExchangeClassificationResult; readonly stageA: StageAMatchResult; @@ -50,13 +43,10 @@ export interface MatchReportInput { readonly priceCrossCheck?: PriceCrossCheckResult; readonly delistingChains?: DelistingChainResult; readonly sourceCountries?: SourceCountryLookup; - readonly gateOutOfScope?: GateOutOfScopeLookup; - readonly gateDenominatorNote?: string; } export interface BuildMatchReportOptions { readonly minResolvedPct?: number; - readonly applyUsCaEquityGateDenominator?: boolean; } export interface ExchangeCoverageSummary { @@ -83,7 +73,6 @@ export interface SourceResolutionSummary { unresolved: number; conflict: number; excludedByDesign: number; - outOfGateScope?: number; eligibleTotal: number; resolvedPct: number | null; eligibleResolvedPct: number | null; @@ -152,8 +141,6 @@ export interface MatchReport { resolutionBySource: SourceResolutionSummary[]; resolutionByCountry: CountryResolutionSummary[]; unresolvedByReason: UnresolvedBreakdown; - outOfGateScopeByReason?: UnresolvedBreakdownRow[]; - gateDenominatorNote?: string; conflicts: UnifiedConflictRow[]; conflictsByPassKind: ConflictCountRow[]; priceCrossCheck: PriceCrossCheckSummary | null; @@ -517,62 +504,16 @@ export function buildMatchReport( qm: 0, ceo: 0, }; - const outOfGateScopeBySource: Record = { - eod: 0, - ib: 0, - qm: 0, - ceo: 0, - }; - const outOfGateScopeCounts = new Map(); - const hasGateOutOfScope = input.gateOutOfScope !== undefined && input.gateOutOfScope.size > 0; - for (const record of input.stageB.unresolved) { if (EXCLUDED_BY_DESIGN_SET.has(record.reason)) { excludedBySource[record.source] += 1; - } else if (hasGateOutOfScope) { - const gateReason = input.gateOutOfScope?.get(sourceCountryKey(record.source, record.sourceId)); - if (gateReason !== undefined) { - outOfGateScopeBySource[record.source] += 1; - const k = `${record.source}\u0000${gateReason}`; - outOfGateScopeCounts.set(k, (outOfGateScopeCounts.get(k) ?? 0) + 1); - } } } - if (hasGateOutOfScope) { - const countedConflictKeys = new Set(); - for (const conflict of input.stageB.conflicts) { - const key = sourceCountryKey(conflict.source, conflict.sourceId); - if (countedConflictKeys.has(key)) { - continue; - } - countedConflictKeys.add(key); - const gateReason = input.gateOutOfScope?.get(key); - if (gateReason !== undefined) { - outOfGateScopeBySource[conflict.source] += 1; - const k = `${conflict.source}\u0000${gateReason}`; - outOfGateScopeCounts.set(k, (outOfGateScopeCounts.get(k) ?? 0) + 1); - } - } - } - - const outOfGateScopeByReason: UnresolvedBreakdownRow[] = Array.from( - outOfGateScopeCounts.entries() - ) - .map(([key, count]) => { - const sep = key.indexOf('\u0000'); - return { - source: key.slice(0, sep), - reason: key.slice(sep + 1), - count, - }; - }) - .sort((a, b) => compareAscii(a.source, b.source) || compareAscii(a.reason, b.reason)); const resolutionBySource: SourceResolutionSummary[] = STAGE_B_SOURCES.map(source => { const stats = input.stageB.stats.bySource[source]; const excludedByDesign = excludedBySource[source]; - const outOfGateScope = outOfGateScopeBySource[source]; - const eligibleTotal = Math.max(0, stats.total - excludedByDesign - outOfGateScope); + const eligibleTotal = Math.max(0, stats.total - excludedByDesign); return { source, total: stats.total, @@ -580,7 +521,6 @@ export function buildMatchReport( unresolved: stats.unresolved, conflict: stats.conflict, excludedByDesign, - ...(hasGateOutOfScope ? { outOfGateScope } : {}), eligibleTotal, resolvedPct: stats.total > 0 ? stats.matched / stats.total : null, eligibleResolvedPct: eligibleTotal > 0 ? stats.matched / eligibleTotal : null, @@ -675,10 +615,6 @@ export function buildMatchReport( resolutionBySource, resolutionByCountry, unresolvedByReason, - ...(hasGateOutOfScope ? { outOfGateScopeByReason } : {}), - ...(input.gateDenominatorNote !== undefined - ? { gateDenominatorNote: input.gateDenominatorNote } - : {}), conflicts, conflictsByPassKind, priceCrossCheck, @@ -733,48 +669,18 @@ export function renderMatchReportMarkdown( lines.push('| 0 | 0 | 0 | N/A |'); } - if (report.gateDenominatorNote !== undefined && report.gateDenominatorNote.trim().length > 0) { - lines.push('', '## Gate Denominator Definition', '', report.gateDenominatorNote); - } - - const showGateScopeColumn = report.outOfGateScopeByReason !== undefined; lines.push( '', '## Per-Source Resolution', '', - showGateScopeColumn - ? '| Source | Total | Matched | Unresolved | Conflict | Excluded by Design | Out of Gate Scope | Eligible Total | Resolved % | Eligible Resolved % |' - : '| Source | Total | Matched | Unresolved | Conflict | Excluded by Design | Eligible Total | Resolved % | Eligible Resolved % |', - showGateScopeColumn - ? '| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |' - : '| --- | --- | --- | --- | --- | --- | --- | --- | --- |' + '| Source | Total | Matched | Unresolved | Conflict | Excluded by Design | Eligible Total | Resolved % | Eligible Resolved % |', + '| --- | --- | --- | --- | --- | --- | --- | --- | --- |' ); for (const row of report.resolutionBySource) { - if (showGateScopeColumn) { - lines.push( - `| ${escapeMarkdownCell(row.source)} | ${row.total} | ${row.matched} | ${row.unresolved} | ${row.conflict} | ${row.excludedByDesign} | ${row.outOfGateScope ?? 0} | ${row.eligibleTotal} | ${formatPct(row.resolvedPct)} | ${formatPct(row.eligibleResolvedPct)} |` - ); - } else { - lines.push( - `| ${escapeMarkdownCell(row.source)} | ${row.total} | ${row.matched} | ${row.unresolved} | ${row.conflict} | ${row.excludedByDesign} | ${row.eligibleTotal} | ${formatPct(row.resolvedPct)} | ${formatPct(row.eligibleResolvedPct)} |` - ); - } - } - - if (report.outOfGateScopeByReason !== undefined && report.outOfGateScopeByReason.length > 0) { lines.push( - '', - '## Out-of-Gate-Scope Breakdown', - '', - '| Source | Reason | Count |', - '| --- | --- | --- |' + `| ${escapeMarkdownCell(row.source)} | ${row.total} | ${row.matched} | ${row.unresolved} | ${row.conflict} | ${row.excludedByDesign} | ${row.eligibleTotal} | ${formatPct(row.resolvedPct)} | ${formatPct(row.eligibleResolvedPct)} |` ); - for (const row of report.outOfGateScopeByReason) { - lines.push( - `| ${escapeMarkdownCell(row.source)} | ${escapeMarkdownCell(row.reason)} | ${row.count} |` - ); - } } if (report.resolutionByCountry.length > 0) { diff --git a/apps/stock/data-pipeline/src/security-master/persist.ts b/apps/stock/data-pipeline/src/security-master/persist.ts index 88c80003..5fbce262 100644 --- a/apps/stock/data-pipeline/src/security-master/persist.ts +++ b/apps/stock/data-pipeline/src/security-master/persist.ts @@ -16,13 +16,11 @@ import type { Pass6DelistReason, } from './delisting-chains'; import { compareAscii } from './exchange-pass1'; -import { - isSyntheticInstrumentKey, - SYNTHETIC_EOD_ISIN_PREFIX, - type StageAInstrumentCandidate, - type StageAInstrumentMember, - type StageAMatchResult, - type StageASource, +import type { + StageAInstrumentCandidate, + StageAInstrumentMember, + StageAMatchResult, + StageASource, } from './instrument-stage-a'; import type { ListingNaturalKey, @@ -245,8 +243,6 @@ interface ExistingPass4ConflictRow { interface PreparedInstrument { readonly primaryIsin: string; - readonly isSynthetic: boolean; - readonly syntheticSourceId: string | null; readonly primaryCusip: string | null; readonly canonicalName: string; readonly securityType: SecurityType; @@ -664,16 +660,9 @@ async function persistWithinTransaction( skippedInstrumentIsins.add(candidate.primaryIsin); continue; } - const isSynthetic = isSyntheticInstrumentKey(candidate.primaryIsin); - const syntheticSourceId = isSynthetic - ? (candidate.members.find(m => m.source === 'eod')?.sourceId ?? - candidate.primaryIsin.slice(SYNTHETIC_EOD_ISIN_PREFIX.length)) - : null; preparedInstruments.push({ primaryIsin: candidate.primaryIsin, - isSynthetic, - syntheticSourceId, - primaryCusip: isSynthetic ? null : candidate.primaryCusip, + primaryCusip: candidate.primaryCusip, canonicalName: trimmedName, securityType, issuerCountry: candidate.issuerCountry, @@ -683,11 +672,8 @@ async function persistWithinTransaction( if (preparedInstruments.length > 0) { const existingByIsin = new Map(); - const realInstruments = preparedInstruments.filter(item => !item.isSynthetic); - const syntheticInstruments = preparedInstruments.filter(item => item.isSynthetic); - - for (let offset = 0; offset < realInstruments.length; offset += chunkSize) { - const slice = realInstruments.slice(offset, offset + chunkSize); + for (let offset = 0; offset < preparedInstruments.length; offset += chunkSize) { + const slice = preparedInstruments.slice(offset, offset + chunkSize); const isins = slice.map(item => item.primaryIsin); const res = await client.query( `SELECT @@ -706,70 +692,13 @@ async function persistWithinTransaction( } } - for (let offset = 0; offset < syntheticInstruments.length; offset += chunkSize) { - const slice = syntheticInstruments.slice(offset, offset + chunkSize); - const sourceIdToKey = new Map(); - const sourceIds: string[] = []; - for (const item of slice) { - if (item.syntheticSourceId !== null) { - sourceIdToKey.set(item.syntheticSourceId, item.primaryIsin); - sourceIds.push(item.syntheticSourceId); - } - } - if (sourceIds.length === 0) { - continue; - } - const res = await client.query<{ - source_id: string; - instrument_id: number; - primary_cusip: string | null; - canonical_name: string; - security_type: string; - issuer_country: string | null; - }>( - `SELECT DISTINCT ON (pm.source_id) - pm.source_id, - i.instrument_id, - btrim(i.primary_cusip) AS primary_cusip, - i.canonical_name, - i.security_type, - btrim(i.issuer_country) AS issuer_country - FROM provider_mapping pm - JOIN listing l ON l.listing_id = pm.listing_id - JOIN instrument i ON i.instrument_id = l.instrument_id - WHERE pm.source = 'eod' - AND pm.source_id = ANY($1::text[]) - AND i.primary_isin IS NULL - ORDER BY pm.source_id, pm.valid_from ASC`, - [sourceIds] - ); - for (const row of res.rows) { - const key = sourceIdToKey.get(row.source_id); - if (key !== undefined) { - existingByIsin.set(key, { - instrument_id: row.instrument_id, - primary_isin: key, - primary_cusip: row.primary_cusip, - canonical_name: row.canonical_name, - security_type: row.security_type, - issuer_country: row.issuer_country, - }); - } - } - } - - const toInsertReal: PreparedInstrument[] = []; - const toInsertSynthetic: PreparedInstrument[] = []; + const toInsert: PreparedInstrument[] = []; const toUpdate: Array<{ instrumentId: number; item: PreparedInstrument }> = []; for (const item of preparedInstruments) { const existing = existingByIsin.get(item.primaryIsin); if (existing === undefined) { - if (item.isSynthetic) { - toInsertSynthetic.push(item); - } else { - toInsertReal.push(item); - } + toInsert.push(item); continue; } instrumentIdByIsin.set(item.primaryIsin, existing.instrument_id); @@ -785,8 +714,8 @@ async function persistWithinTransaction( } } - for (let offset = 0; offset < toInsertReal.length; offset += chunkSize) { - const slice = toInsertReal.slice(offset, offset + chunkSize); + for (let offset = 0; offset < toInsert.length; offset += chunkSize) { + const slice = toInsert.slice(offset, offset + chunkSize); const res = await client.query( `INSERT INTO instrument ( primary_isin, @@ -818,39 +747,6 @@ async function persistWithinTransaction( instrumentsInserted += res.rows.length; } - for (let offset = 0; offset < toInsertSynthetic.length; offset += chunkSize) { - const slice = toInsertSynthetic.slice(offset, offset + chunkSize); - const res = await client.query<{ instrument_id: number }>( - `INSERT INTO instrument ( - primary_isin, - primary_cusip, - canonical_name, - security_type, - issuer_country - ) - SELECT NULL, NULL, u.canonical_name, u.security_type, u.issuer_country - FROM UNNEST( - $1::text[], - $2::varchar[], - $3::bpchar[] - ) AS u(canonical_name, security_type, issuer_country) - RETURNING instrument_id`, - [ - slice.map(item => item.canonicalName), - slice.map(item => item.securityType), - slice.map(item => item.issuerCountry), - ] - ); - for (let i = 0; i < res.rows.length; i++) { - const item = slice[i]; - const row = res.rows[i]; - if (item !== undefined && row !== undefined) { - instrumentIdByIsin.set(item.primaryIsin, row.instrument_id); - } - } - instrumentsInserted += res.rows.length; - } - for (let offset = 0; offset < toUpdate.length; offset += chunkSize) { const slice = toUpdate.slice(offset, offset + chunkSize); await client.query( @@ -888,9 +784,6 @@ async function persistWithinTransaction( source: StageASource; }> = []; for (const item of preparedInstruments) { - if (item.isSynthetic) { - continue; - } const instrumentId = instrumentIdByIsin.get(item.primaryIsin); if (instrumentId === undefined) { continue; diff --git a/apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts b/apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts deleted file mode 100644 index b3fbcfca..00000000 --- a/apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts +++ /dev/null @@ -1,291 +0,0 @@ -import { mkdir, writeFile } from 'node:fs/promises'; -import { dirname } from 'node:path'; -import { getLogger } from '@stock-bot/logger'; -import { MongoDBClient } from '@stock-bot/mongodb'; -import { initializeStockConfig } from '@stock-bot/stock-config'; -import { resolveReadOnlyMongoClientConfig } from './generate-exchange-seed'; -import { - DEFAULT_FIELD_SHAPE_LIMIT, - FIELD_SHAPE_PROBE_COLLECTIONS, - MAX_FIELD_SHAPE_LIMIT, - normalizeProbeCollections, - readFieldShapes, - renderFieldShapesMarkdown, - type FieldShapeProbeCollection, - type ReadFieldShapesResult, -} from './source-field-shapes'; -import { - createReadOnlyMongoSourceSymbolReader, - type ReadOnlyMongoCollectionClient, -} from './source-symbol-readers'; - -export const PROBE_SOURCE_FIELD_SHAPES_USAGE = [ - 'Usage: bun run apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts --out [--limit ] [--collections ] [--help]', - '', - 'Options:', - ' --out Required. Output Markdown report file path.', - ` --limit Optional. Max documents sampled per collection (1..${MAX_FIELD_SHAPE_LIMIT}, default: ${DEFAULT_FIELD_SHAPE_LIMIT}).`, - ` --collections Optional. Comma-separated allowlisted collections (default: ${FIELD_SHAPE_PROBE_COLLECTIONS.join(',')}).`, - ' --help Show this help message and exit.', -].join('\n'); - -export type ParsedProbeSourceFieldShapesArgs = - | { readonly help: true } - | { - readonly help: false; - readonly outPath: string; - readonly limit: number; - readonly collections: readonly FieldShapeProbeCollection[]; - }; - -export interface RunSourceFieldShapesProbeDeps { - readonly mongoCollectionClient: ReadOnlyMongoCollectionClient; - readonly closeMongo?: () => Promise | void; - readonly writeFile?: (filePath: string, content: string) => Promise | void; - readonly writeStdout?: (text: string) => void; -} - -export interface RunSourceFieldShapesProbeOptions { - readonly outPath: string; - readonly limit?: number; - readonly collections?: readonly string[]; - readonly maxExamples?: number; - readonly maxExampleLength?: number; - readonly batchSize?: number; -} - -export interface RunSourceFieldShapesProbeOutput { - readonly outPath: string; - readonly result: ReadFieldShapesResult; - readonly markdown: string; - readonly summary: string; -} - -const STRICT_INT_PATTERN = /^-?\d+$/; - -function usageError(message: string): Error { - return new Error(`${message}\n\n${PROBE_SOURCE_FIELD_SHAPES_USAGE}`); -} - -function parseLimitArg(raw: string): number { - if (!STRICT_INT_PATTERN.test(raw)) { - throw usageError( - `Invalid --limit value "${raw}": expected an integer between 1 and ${MAX_FIELD_SHAPE_LIMIT}` - ); - } - const parsed = Number(raw); - if (!Number.isSafeInteger(parsed) || parsed < 1 || parsed > MAX_FIELD_SHAPE_LIMIT) { - throw usageError( - `Invalid --limit value "${raw}": expected an integer between 1 and ${MAX_FIELD_SHAPE_LIMIT}` - ); - } - return parsed; -} - -function parseCollectionsArg(raw: string): FieldShapeProbeCollection[] { - const parts = raw - .split(',') - .map(part => part.trim()) - .filter(part => part.length > 0); - if (parts.length === 0) { - throw usageError('Missing value for --collections'); - } - return normalizeProbeCollections(parts); -} - -export function parseProbeSourceFieldShapesArgs( - argv: readonly string[] -): ParsedProbeSourceFieldShapesArgs { - let help = false; - let outPath: string | undefined; - let limit = DEFAULT_FIELD_SHAPE_LIMIT; - let collectionsRaw: string[] | undefined; - - for (let i = 0; i < argv.length; i++) { - const arg = argv[i]; - if (arg === '--help') { - help = true; - continue; - } - if (arg === '--out') { - const value = argv[i + 1]; - if (!value || value.trim().length === 0 || value.startsWith('--')) { - throw usageError('Missing value for --out'); - } - outPath = value.trim(); - i += 1; - continue; - } - if (arg?.startsWith('--out=')) { - const value = arg.slice('--out='.length).trim(); - if (value.length === 0) { - throw usageError('Missing value for --out'); - } - outPath = value; - continue; - } - if (arg === '--limit') { - const value = argv[i + 1]; - if (!value || value.trim().length === 0 || value.startsWith('--')) { - throw usageError('Missing value for --limit'); - } - limit = parseLimitArg(value.trim()); - i += 1; - continue; - } - if (arg?.startsWith('--limit=')) { - const value = arg.slice('--limit='.length).trim(); - if (value.length === 0) { - throw usageError('Missing value for --limit'); - } - limit = parseLimitArg(value); - continue; - } - if (arg === '--collections') { - const value = argv[i + 1]; - if (!value || value.trim().length === 0 || value.startsWith('--')) { - throw usageError('Missing value for --collections'); - } - const parsed = parseCollectionsArg(value); - collectionsRaw = collectionsRaw ? [...collectionsRaw, ...parsed] : parsed; - i += 1; - continue; - } - if (arg?.startsWith('--collections=')) { - const value = arg.slice('--collections='.length).trim(); - if (value.length === 0) { - throw usageError('Missing value for --collections'); - } - const parsed = parseCollectionsArg(value); - collectionsRaw = collectionsRaw ? [...collectionsRaw, ...parsed] : parsed; - continue; - } - throw usageError(`Unknown argument: ${String(arg)}`); - } - - if (help) { - return { help: true }; - } - - if (outPath === undefined || outPath.trim().length === 0) { - throw usageError('Missing required argument: --out '); - } - - const collections = normalizeProbeCollections(collectionsRaw); - return { - help: false, - outPath, - limit, - collections, - }; -} - -async function defaultWriteFile(filePath: string, content: string): Promise { - await mkdir(dirname(filePath), { recursive: true }); - await writeFile(filePath, content, 'utf8'); -} - -export async function runSourceFieldShapesProbe( - deps: RunSourceFieldShapesProbeDeps, - options: RunSourceFieldShapesProbeOptions -): Promise { - let primaryError: unknown = undefined; - let hasPrimaryError = false; - let output: RunSourceFieldShapesProbeOutput | undefined; - - try { - if (typeof options.outPath !== 'string' || options.outPath.trim().length === 0) { - throw new Error('outPath must be a non-empty string'); - } - - const reader = createReadOnlyMongoSourceSymbolReader(deps.mongoCollectionClient); - const result = await readFieldShapes(reader, { - limit: options.limit, - collections: options.collections, - maxExamples: options.maxExamples, - maxExampleLength: options.maxExampleLength, - batchSize: options.batchSize, - }); - - const markdown = renderFieldShapesMarkdown(result); - const writer = deps.writeFile ?? defaultWriteFile; - await writer(options.outPath, markdown); - - const summary = [ - `Source field-shape probe complete (limit=${result.limit})`, - ` Collections: ${result.collections.length} | Documents sampled: ${result.totalDocsSampled}`, - ` Report written: ${options.outPath}`, - ].join('\n'); - - output = { - outPath: options.outPath, - result, - markdown, - summary: `${summary}\n`, - }; - } catch (error) { - primaryError = error; - hasPrimaryError = true; - } finally { - if (deps.closeMongo) { - try { - await deps.closeMongo(); - } catch (closeError) { - if (!hasPrimaryError) { - primaryError = closeError; - hasPrimaryError = true; - } - } - } - } - - if (hasPrimaryError) { - throw primaryError; - } - if (output === undefined) { - throw new Error('Source field-shape probe completed without producing output'); - } - - const writeStdout = - deps.writeStdout ?? - ((text: string) => { - process.stdout.write(text); - }); - writeStdout(output.summary); - - return output; -} - -export async function runCli(argv: readonly string[] = process.argv.slice(2)): Promise { - const parsed = parseProbeSourceFieldShapesArgs(argv); - if (parsed.help) { - process.stdout.write(`${PROBE_SOURCE_FIELD_SHAPES_USAGE}\n`); - return; - } - - const logger = getLogger('source-field-shapes-probe'); - const config = initializeStockConfig('dataPipeline', { mongoReadOnly: true }); - const mongoConfig = resolveReadOnlyMongoClientConfig(config); - const mongo = new MongoDBClient(mongoConfig, logger); - - await mongo.connect(); - await runSourceFieldShapesProbe( - { - mongoCollectionClient: mongo, - closeMongo: () => mongo.disconnect(), - }, - { - outPath: parsed.outPath, - limit: parsed.limit, - collections: parsed.collections, - } - ); -} - -if (import.meta.main) { - runCli().catch(error => { - const message = error instanceof Error ? error.message : String(error); - process.stderr.write(`Error: ${message}\n`); - process.exit(1); - }); -} diff --git a/apps/stock/data-pipeline/src/security-master/run-export-curate-inputs.ts b/apps/stock/data-pipeline/src/security-master/run-export-curate-inputs.ts deleted file mode 100644 index 38d15920..00000000 --- a/apps/stock/data-pipeline/src/security-master/run-export-curate-inputs.ts +++ /dev/null @@ -1,345 +0,0 @@ -import { getLogger } from '@stock-bot/logger'; -import { PostgreSQLClient } from '@stock-bot/postgres'; -import { - assertEnvironmentSafety, - initializeStockConfig, - type StockAppConfig, -} from '@stock-bot/stock-config'; -import { - CURATE_INPUT_FILES, - DEFAULT_DELISTING_MAPPING_SOURCE, - DEFAULT_EXPORT_CHUNK_SIZE, - exportCurateInputs, - MAX_EXPORT_CHUNK_SIZE, - type ExportCurateInputsFsHooks, - type ExportCurateInputsResult, -} from './export-curate-inputs'; -import type { SecurityMasterQueryable, SecurityMasterQueryResult } from './persist'; -import type { SecurityMasterPostgresHandle } from './run-security-master'; - -export const EXPORT_CURATE_INPUTS_USAGE = [ - 'Usage: bun run apps/stock/data-pipeline/src/security-master/run-export-curate-inputs.ts --out-dir [--chunk-size ] [--help]', - '', - 'Options:', - ` --out-dir Required. Output directory for ${CURATE_INPUT_FILES.providerMapping}, ${CURATE_INPUT_FILES.listingCurrencies}, and ${CURATE_INPUT_FILES.delistings}.`, - ` --chunk-size Optional. Keyset pagination chunk size (1..${MAX_EXPORT_CHUNK_SIZE}, default: ${DEFAULT_EXPORT_CHUNK_SIZE}).`, - ' --help Show this help message and exit.', -].join('\n'); - -export type ParsedExportCurateInputsArgs = - | { readonly help: true } - | { - readonly help: false; - readonly outDir: string; - readonly chunkSize: number; - }; - -export interface RunExportCurateInputsDeps { - readonly assertSafety?: () => void; - readonly createPostgresClient: () => - | Promise - | SecurityMasterPostgresHandle; - readonly exportFn?: typeof exportCurateInputs; - readonly writeStdout?: (text: string) => void; -} - -export interface RunExportCurateInputsOptions { - readonly outDir: string; - readonly chunkSize?: number; - readonly delistingMappingSource?: string; - readonly fs?: ExportCurateInputsFsHooks; -} - -export interface RunExportCurateInputsOutput { - readonly result: ExportCurateInputsResult; - readonly summary: string; -} - -const STRICT_INT_PATTERN = /^-?\d+$/; - -function usageError(message: string): Error { - return new Error(`${message}\n\n${EXPORT_CURATE_INPUTS_USAGE}`); -} - -function parseChunkSizeArg(raw: string): number { - if (!STRICT_INT_PATTERN.test(raw)) { - throw usageError( - `Invalid --chunk-size value "${raw}": expected an integer between 1 and ${MAX_EXPORT_CHUNK_SIZE}` - ); - } - const parsed = Number(raw); - if (!Number.isSafeInteger(parsed) || parsed < 1 || parsed > MAX_EXPORT_CHUNK_SIZE) { - throw usageError( - `Invalid --chunk-size value "${raw}": expected an integer between 1 and ${MAX_EXPORT_CHUNK_SIZE}` - ); - } - return parsed; -} - -export function parseExportCurateInputsArgs( - argv: readonly string[] -): ParsedExportCurateInputsArgs { - let help = false; - let outDir: string | undefined; - let chunkSize = DEFAULT_EXPORT_CHUNK_SIZE; - - for (let i = 0; i < argv.length; i++) { - const arg = argv[i]; - if (arg === '--help') { - help = true; - 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.trim(); - i += 1; - continue; - } - if (arg?.startsWith('--out-dir=')) { - const value = arg.slice('--out-dir='.length).trim(); - if (value.length === 0) { - throw usageError('Missing value for --out-dir'); - } - outDir = value; - continue; - } - if (arg === '--chunk-size') { - const value = argv[i + 1]; - if (!value || value.trim().length === 0 || value.startsWith('--')) { - throw usageError('Missing value for --chunk-size'); - } - chunkSize = parseChunkSizeArg(value.trim()); - i += 1; - continue; - } - if (arg?.startsWith('--chunk-size=')) { - const value = arg.slice('--chunk-size='.length).trim(); - if (value.length === 0) { - throw usageError('Missing value for --chunk-size'); - } - chunkSize = parseChunkSizeArg(value); - continue; - } - throw usageError(`Unknown argument: ${String(arg)}`); - } - - if (help) { - return { help: true }; - } - - if (outDir === undefined || outDir.trim().length === 0) { - throw usageError('Missing required argument: --out-dir '); - } - - return { - help: false, - outDir, - chunkSize, - }; -} - -export function assertExportCurateInputsSafety( - config: StockAppConfig, - env: Record = process.env -): void { - const pg = config.database.postgres; - if (!pg.enabled) { - throw new Error('PostgreSQL is disabled in configuration; cannot export curate-etl inputs'); - } - - const { STOCK_BOT_ALLOW_DEV_ON_QA_DB: _stripped, ...safeEnv } = env; - const pgOnlyConfig: StockAppConfig = { - ...config, - database: { - ...config.database, - mongodb: { - ...config.database.mongodb, - enabled: false, - }, - }, - }; - assertEnvironmentSafety(pgOnlyConfig, 'dataPipeline', safeEnv); -} - -export function formatExportCurateInputsSummary(result: ExportCurateInputsResult): string { - const d = result.delistings.stats; - const s = d.skipped; - const lines = [ - `Curate-ETL TSV export complete (${result.outDir}, generation=${result.generationId}, snapshot_dir=${result.generationDir})`, - ` ${CURATE_INPUT_FILES.providerMapping}: rows_in=${result.providerMapping.rowsIn} rows_out=${result.providerMapping.rowsOut} bytes=${result.providerMapping.bytesWritten}`, - ` ${CURATE_INPUT_FILES.listingCurrencies}: rows_in=${result.listingCurrencies.rowsIn} rows_out=${result.listingCurrencies.rowsOut} bytes=${result.listingCurrencies.bytesWritten}`, - ` ${CURATE_INPUT_FILES.delistings}: rows_in=${d.rowsIn} rows_out=${d.rowsOut} (otc=${d.otcTransfersOut} terminal=${d.terminalDelistingsOut}) skipped=${d.skippedTotal} [active=${s.active} no_outcome=${s.noOutcome} missing_listed_to=${s.missingListedTo} missing_outgoing_qm=${s.missingOutgoingQmMapping} missing_successor_qm=${s.missingSuccessorQmMapping} non_otc_continuity=${s.nonOtcContinuity}] bytes=${result.delistings.bytesWritten}`, - ` chunk_size=${result.chunkSize} mapping_source=${result.delistingMappingSource} total_bytes=${result.totalBytesWritten}`, - ]; - for (const warning of result.cleanupWarnings) { - lines.push(` warning: ${warning}`); - } - return `${lines.join('\n')}\n`; -} - -export async function runExportCurateInputs( - deps: RunExportCurateInputsDeps, - options: RunExportCurateInputsOptions -): Promise { - if (deps.assertSafety) { - deps.assertSafety(); - } - - const pgHandle = await deps.createPostgresClient(); - let result: ExportCurateInputsResult; - let closeError: unknown = null; - try { - const exportFn = deps.exportFn ?? exportCurateInputs; - result = await exportFn(pgHandle.queryable, { - outDir: options.outDir, - chunkSize: options.chunkSize, - delistingMappingSource: options.delistingMappingSource ?? DEFAULT_DELISTING_MAPPING_SOURCE, - fs: options.fs, - }); - } finally { - try { - await pgHandle.close(); - } catch (error) { - closeError = error; - } - } - - if (closeError !== null) { - throw closeError; - } - - const summary = formatExportCurateInputsSummary(result); - const writeStdout = - deps.writeStdout ?? - ((text: string) => { - process.stdout.write(text); - }); - writeStdout(summary); - - return { result, summary }; -} - -export async function runCli( - argv: readonly string[] = process.argv.slice(2), - overrides?: Partial -): Promise { - const parsed = parseExportCurateInputsArgs(argv); - if (parsed.help) { - const writeStdout = - overrides?.writeStdout ?? - ((text: string) => { - process.stdout.write(text); - }); - writeStdout(`${EXPORT_CURATE_INPUTS_USAGE}\n`); - return; - } - - const logger = getLogger('security-master-export-curate-inputs-cli'); - const config = initializeStockConfig('dataPipeline', { postgresOnly: true }); - - const assertSafety = (): void => { - assertExportCurateInputsSafety(config, process.env); - }; - - const createPostgresClient = async (): Promise => { - const pg = config.database.postgres; - const pgClient = new PostgreSQLClient( - { - host: pg.host, - port: pg.port, - database: pg.database, - username: pg.user, - password: pg.password, - poolSettings: { - min: 1, - max: Math.max(1, pg.poolSize), - idleTimeoutMillis: pg.idleTimeout, - }, - ssl: { - enabled: pg.ssl, - rejectUnauthorized: true, - }, - timeouts: { - connection: pg.connectionTimeout, - }, - }, - logger - ); - - await pgClient.connect(); - try { - const pool = pgClient.connectionPool; - if (!pool) { - throw new Error('PostgreSQL connection pool was not initialized after connect()'); - } - const poolClient = await pool.connect(); - const queryable: SecurityMasterQueryable = { - query>( - text: string, - values?: readonly unknown[] - ): Promise> { - return poolClient.query( - text, - values === undefined ? undefined : [...values] - ) as unknown as Promise>; - }, - release: () => { - poolClient.release(); - }, - }; - let closed = false; - return { - queryable, - async close(): Promise { - if (closed) { - return; - } - closed = true; - let releaseError: unknown = null; - try { - poolClient.release(); - } catch (error) { - releaseError = error; - } - try { - await pgClient.disconnect(); - } catch (disconnectError) { - if (releaseError === null) { - throw disconnectError; - } - } - if (releaseError !== null) { - throw releaseError; - } - }, - }; - } catch (error) { - await pgClient.disconnect().catch(() => {}); - throw error; - } - }; - - await runExportCurateInputs( - { - assertSafety: overrides?.assertSafety ?? assertSafety, - createPostgresClient: overrides?.createPostgresClient ?? createPostgresClient, - exportFn: overrides?.exportFn, - writeStdout: overrides?.writeStdout, - }, - { - outDir: parsed.outDir, - chunkSize: parsed.chunkSize, - } - ); -} - -if (import.meta.main) { - runCli().catch(error => { - const message = error instanceof Error ? error.message : String(error); - process.stderr.write(`Error: ${message}\n`); - process.exit(1); - }); -} diff --git a/apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts b/apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts deleted file mode 100644 index 17ba87cf..00000000 --- a/apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts +++ /dev/null @@ -1,477 +0,0 @@ -import { getLogger } from '@stock-bot/logger'; -import { MongoDBClient } from '@stock-bot/mongodb'; -import { - assertEnvironmentSafety, - initializeStockConfig, - type StockAppConfig, -} from '@stock-bot/stock-config'; -import { - createReadOnlyMongoRawBsonSource, - DEFAULT_RAW_BSON_BATCH_SIZE, - exportRawBsonCollection, - isRawBsonExportCollection, - MAX_RAW_BSON_BATCH_SIZE, - RAW_BSON_EXPORT_COLLECTIONS, - RawBsonExportError, - type ExportRawBsonCollectionResult, - type ExportRawBsonFsHooks, - type RawBsonExportCollection, - type ReadOnlyMongoRawBsonClient, -} from './export-raw-bson'; -import { resolveReadOnlyMongoClientConfig } from './generate-exchange-seed'; - -export const EXPORT_RAW_BSON_USAGE = [ - 'Usage: bun run apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts --out-dir [--collections ] [--eod-symbol ] [--te-symbol ] [--limit ] [--batch-size ] [--help]', - '', - 'Options:', - ' --out-dir Required. Output directory for .bson files.', - ` --collections Optional. Comma-separated allowlisted collections (default: ${RAW_BSON_EXPORT_COLLECTIONS.join(',')}).`, - ' --eod-symbol Optional. Exact eodSearchCode filter (only valid when --collections is strictly eodPrices).', - ' --te-symbol Optional. Exact teSymbol filter (only valid when --collections is strictly teMarketData).', - ' --limit Optional. Max documents to export per collection (positive integer, for smoke runs).', - ` --batch-size Optional. MongoDB cursor batchSize (1..${MAX_RAW_BSON_BATCH_SIZE}, default: ${DEFAULT_RAW_BSON_BATCH_SIZE}).`, - ' --help Show this help message and exit.', -].join('\n'); - -export type ParsedExportRawBsonArgs = - | { readonly help: true } - | { - readonly help: false; - readonly outDir: string; - readonly collections: readonly RawBsonExportCollection[]; - readonly eodSymbol?: string; - readonly teSymbol?: string; - readonly limit?: number; - readonly batchSize: number; - }; - -export interface RawBsonMongoHandle { - readonly client: ReadOnlyMongoRawBsonClient; - readonly close: () => Promise | void; -} - -export interface RunExportRawBsonDeps { - readonly assertSafety?: () => void; - readonly createMongoClient: () => Promise | RawBsonMongoHandle; - readonly exportFn?: typeof exportRawBsonCollection; - readonly writeStdout?: (text: string) => void; -} - -export interface RunExportRawBsonCliOverrides extends Partial { - readonly initializeConfig?: typeof initializeStockConfig; -} - -export interface RunExportRawBsonOptions { - readonly outDir: string; - readonly collections: readonly RawBsonExportCollection[]; - readonly eodSymbol?: string; - readonly teSymbol?: string; - readonly limit?: number; - readonly batchSize?: number; - readonly writeBufferBytes?: number; - readonly maxDocBytes?: number; - readonly fs?: ExportRawBsonFsHooks; -} - -export interface RunExportRawBsonOutput { - readonly results: readonly ExportRawBsonCollectionResult[]; - readonly summary: string; -} - -const STRICT_INT_PATTERN = /^-?\d+$/; - -function usageError(message: string): Error { - return new Error(`${message}\n\n${EXPORT_RAW_BSON_USAGE}`); -} - -function parsePositiveIntArg(flag: string, raw: string, max?: number): number { - if (!STRICT_INT_PATTERN.test(raw)) { - throw usageError( - max !== undefined - ? `Invalid ${flag} value "${raw}": expected an integer between 1 and ${max}` - : `Invalid ${flag} value "${raw}": expected a positive integer` - ); - } - const parsed = Number(raw); - if ( - !Number.isSafeInteger(parsed) || - parsed < 1 || - (max !== undefined && parsed > max) - ) { - throw usageError( - max !== undefined - ? `Invalid ${flag} value "${raw}": expected an integer between 1 and ${max}` - : `Invalid ${flag} value "${raw}": expected a positive integer` - ); - } - return parsed; -} - -function parseCollectionsList(raw: string): RawBsonExportCollection[] { - const segments = raw.split(','); - const result: RawBsonExportCollection[] = []; - const seen = new Set(); - - for (const segment of segments) { - const trimmed = segment.trim(); - if (trimmed.length === 0) { - throw usageError(`Malformed --collections value "${raw}": empty collection entry`); - } - if (!isRawBsonExportCollection(trimmed)) { - throw new RawBsonExportError({ - code: 'DISALLOWED_COLLECTION', - collection: trimmed, - detail: `collection "${trimmed}" is not in the M1 allowlist (${RAW_BSON_EXPORT_COLLECTIONS.join(', ')})`, - }); - } - if (seen.has(trimmed)) { - throw usageError(`Duplicate collection "${trimmed}" in --collections`); - } - seen.add(trimmed); - result.push(trimmed); - } - - if (result.length === 0) { - throw usageError('Missing value for --collections'); - } - return result; -} - -function readFlagValue( - argv: readonly string[], - index: number, - flag: string -): { value: string; nextIndex: number } { - const arg = argv[index] ?? ''; - const eqPrefix = `${flag}=`; - if (arg.startsWith(eqPrefix)) { - const value = arg.slice(eqPrefix.length).trim(); - if (value.length === 0) { - throw usageError(`Missing value for ${flag}`); - } - if (value.startsWith('--')) { - throw usageError(`Invalid value for ${flag}: "${value}" must not start with "--"`); - } - return { value, nextIndex: index }; - } - - const next = argv[index + 1]; - const trimmedNext = next?.trim() ?? ''; - if (trimmedNext.length === 0 || trimmedNext.startsWith('--')) { - throw usageError(`Missing value for ${flag}`); - } - return { value: trimmedNext, nextIndex: index + 1 }; -} - -export function parseExportRawBsonArgs(argv: readonly string[]): ParsedExportRawBsonArgs { - let help = false; - let outDir: string | undefined; - let collections: RawBsonExportCollection[] | undefined; - let eodSymbol: string | undefined; - let teSymbol: string | undefined; - let limit: number | undefined; - let batchSize = DEFAULT_RAW_BSON_BATCH_SIZE; - - const seenFlags = new Set(); - - const markSeen = (flag: string): void => { - if (seenFlags.has(flag)) { - throw usageError(`Duplicate flag: ${flag}`); - } - seenFlags.add(flag); - }; - - for (let i = 0; i < argv.length; i++) { - const arg = argv[i]; - if (arg === '--help') { - markSeen('--help'); - help = true; - continue; - } - if (arg === '--out-dir' || arg?.startsWith('--out-dir=')) { - markSeen('--out-dir'); - const { value, nextIndex } = readFlagValue(argv, i, '--out-dir'); - outDir = value; - i = nextIndex; - continue; - } - if (arg === '--collections' || arg?.startsWith('--collections=')) { - markSeen('--collections'); - const { value, nextIndex } = readFlagValue(argv, i, '--collections'); - collections = parseCollectionsList(value); - i = nextIndex; - continue; - } - if (arg === '--eod-symbol' || arg?.startsWith('--eod-symbol=')) { - markSeen('--eod-symbol'); - const { value, nextIndex } = readFlagValue(argv, i, '--eod-symbol'); - eodSymbol = value; - i = nextIndex; - continue; - } - if (arg === '--te-symbol' || arg?.startsWith('--te-symbol=')) { - markSeen('--te-symbol'); - const { value, nextIndex } = readFlagValue(argv, i, '--te-symbol'); - teSymbol = value; - i = nextIndex; - continue; - } - if (arg === '--limit' || arg?.startsWith('--limit=')) { - markSeen('--limit'); - const { value, nextIndex } = readFlagValue(argv, i, '--limit'); - limit = parsePositiveIntArg('--limit', value); - i = nextIndex; - continue; - } - if (arg === '--batch-size' || arg?.startsWith('--batch-size=')) { - markSeen('--batch-size'); - const { value, nextIndex } = readFlagValue(argv, i, '--batch-size'); - batchSize = parsePositiveIntArg('--batch-size', value, MAX_RAW_BSON_BATCH_SIZE); - i = nextIndex; - continue; - } - throw usageError(`Unknown argument: ${String(arg)}`); - } - - if (help) { - return { help: true }; - } - - if (outDir === undefined || outDir.trim().length === 0) { - throw usageError('Missing required argument: --out-dir '); - } - - const resolvedCollections: readonly RawBsonExportCollection[] = - collections ?? [...RAW_BSON_EXPORT_COLLECTIONS]; - - if (eodSymbol !== undefined) { - if (resolvedCollections.length !== 1 || resolvedCollections[0] !== 'eodPrices') { - throw usageError( - '--eod-symbol is only permitted when --collections is strictly "eodPrices"' - ); - } - } - - if (teSymbol !== undefined) { - if (resolvedCollections.length !== 1 || resolvedCollections[0] !== 'teMarketData') { - throw usageError( - '--te-symbol is only permitted when --collections is strictly "teMarketData"' - ); - } - } - - return { - help: false, - outDir, - collections: resolvedCollections, - ...(eodSymbol !== undefined ? { eodSymbol } : {}), - ...(teSymbol !== undefined ? { teSymbol } : {}), - ...(limit !== undefined ? { limit } : {}), - batchSize, - }; -} - -export function assertExportRawBsonSafety( - config: StockAppConfig, - env: Record = process.env -): void { - const mongo = config.database.mongodb; - if (!mongo.enabled) { - throw new Error('MongoDB is disabled in configuration; cannot export raw BSON collections'); - } - if (mongo.readOnly !== true) { - throw new Error( - 'Raw BSON exporter requires read-only MongoDB configuration (database.mongodb.readOnly === true)' - ); - } - - const { STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: _stripped, ...safeEnv } = env; - const mongoOnlyConfig: StockAppConfig = { - ...config, - database: { - ...config.database, - postgres: { - ...config.database.postgres, - enabled: false, - }, - }, - }; - assertEnvironmentSafety(mongoOnlyConfig, 'dataPipeline', safeEnv); -} - -export function formatExportRawBsonSummary( - results: readonly ExportRawBsonCollectionResult[] -): string { - const lines = [`Raw BSON export complete (${results.length} collection(s))`]; - for (const r of results) { - lines.push( - ` ${r.collection}: docs=${r.docsWritten} bytes=${r.bytesWritten} elapsed_ms=${r.elapsedMs.toFixed(1)} sha256=${r.sha256} out=${r.outPath}` - ); - } - return `${lines.join('\n')}\n`; -} - -export async function runExportRawBson( - deps: RunExportRawBsonDeps, - options: RunExportRawBsonOptions -): Promise { - if (options.collections.length === 0) { - throw new RawBsonExportError({ - code: 'INVALID_OPTION', - collection: '*', - detail: 'At least one allowlisted collection must be specified', - }); - } - for (const collection of options.collections) { - if (!isRawBsonExportCollection(collection)) { - throw new RawBsonExportError({ - code: 'DISALLOWED_COLLECTION', - collection: String(collection), - detail: `collection "${String(collection)}" is not in the M1 allowlist`, - }); - } - } - if ( - options.eodSymbol !== undefined && - (options.collections.length !== 1 || options.collections[0] !== 'eodPrices') - ) { - throw new RawBsonExportError({ - code: 'INVALID_OPTION', - collection: options.collections.join(','), - detail: '--eod-symbol is only permitted when exporting strictly "eodPrices"', - }); - } - if ( - options.teSymbol !== undefined && - (options.collections.length !== 1 || options.collections[0] !== 'teMarketData') - ) { - throw new RawBsonExportError({ - code: 'INVALID_OPTION', - collection: options.collections.join(','), - detail: '--te-symbol is only permitted when exporting strictly "teMarketData"', - }); - } - - if (deps.assertSafety) { - deps.assertSafety(); - } - - const mongoHandle = await deps.createMongoClient(); - const results: ExportRawBsonCollectionResult[] = []; - let primaryError: unknown = undefined; - let hasPrimaryError = false; - - try { - const source = createReadOnlyMongoRawBsonSource(mongoHandle.client); - const exportFn = deps.exportFn ?? exportRawBsonCollection; - - for (const collection of options.collections) { - const result = await exportFn(source, { - collection, - outDir: options.outDir, - ...(options.eodSymbol !== undefined ? { eodSymbol: options.eodSymbol } : {}), - ...(options.teSymbol !== undefined ? { teSymbol: options.teSymbol } : {}), - ...(options.limit !== undefined ? { limit: options.limit } : {}), - ...(options.batchSize !== undefined ? { batchSize: options.batchSize } : {}), - ...(options.writeBufferBytes !== undefined - ? { writeBufferBytes: options.writeBufferBytes } - : {}), - ...(options.maxDocBytes !== undefined ? { maxDocBytes: options.maxDocBytes } : {}), - ...(options.fs !== undefined ? { fs: options.fs } : {}), - }); - results.push(result); - } - } catch (error) { - primaryError = error; - hasPrimaryError = true; - } finally { - try { - await mongoHandle.close(); - } catch (closeError) { - if (!hasPrimaryError) { - primaryError = closeError; - hasPrimaryError = true; - } - } - } - - if (hasPrimaryError) { - throw primaryError; - } - - const summary = formatExportRawBsonSummary(results); - const writeStdout = - deps.writeStdout ?? - ((text: string) => { - process.stdout.write(text); - }); - writeStdout(summary); - - return { results, summary }; -} - -export async function runCli( - argv: readonly string[] = process.argv.slice(2), - overrides?: RunExportRawBsonCliOverrides -): Promise { - const parsed = parseExportRawBsonArgs(argv); - if (parsed.help) { - const writeStdout = - overrides?.writeStdout ?? - ((text: string) => { - process.stdout.write(text); - }); - writeStdout(`${EXPORT_RAW_BSON_USAGE}\n`); - return; - } - - const logger = getLogger('security-master-export-raw-bson-cli'); - const initConfig = overrides?.initializeConfig ?? initializeStockConfig; - const config = initConfig('dataPipeline', { mongoReadOnly: true }); - - const assertSafety = (): void => { - assertExportRawBsonSafety(config, process.env); - }; - - const createMongoClient = async (): Promise => { - const mongoConfig = resolveReadOnlyMongoClientConfig(config); - const mongo = new MongoDBClient(mongoConfig, logger); - await mongo.connect(); - let closed = false; - return { - client: mongo, - async close(): Promise { - if (closed) { - return; - } - closed = true; - await mongo.disconnect(); - }, - }; - }; - - await runExportRawBson( - { - assertSafety: overrides?.assertSafety ?? assertSafety, - createMongoClient: overrides?.createMongoClient ?? createMongoClient, - exportFn: overrides?.exportFn, - writeStdout: overrides?.writeStdout, - }, - { - outDir: parsed.outDir, - collections: parsed.collections, - ...(parsed.eodSymbol !== undefined ? { eodSymbol: parsed.eodSymbol } : {}), - ...(parsed.teSymbol !== undefined ? { teSymbol: parsed.teSymbol } : {}), - ...(parsed.limit !== undefined ? { limit: parsed.limit } : {}), - batchSize: parsed.batchSize, - } - ); -} - -if (import.meta.main) { - runCli().catch(error => { - const message = error instanceof Error ? error.message : String(error); - process.stderr.write(`Error: ${message}\n`); - process.exit(1); - }); -} diff --git a/apps/stock/data-pipeline/src/security-master/run-security-master.ts b/apps/stock/data-pipeline/src/security-master/run-security-master.ts index 82c220fb..ce107fa7 100644 --- a/apps/stock/data-pipeline/src/security-master/run-security-master.ts +++ b/apps/stock/data-pipeline/src/security-master/run-security-master.ts @@ -21,7 +21,6 @@ import { EXCHANGE_SOURCES, ISO_EXCHANGE_SEEDS, normalizeRawExchangeDoc, - REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS, type ExchangeClassificationResult, type ExchangeSource, type SourceExchangeRecord, @@ -52,8 +51,6 @@ import { import { createExchangeSourceLookup, createReadOnlyMongoSourceSymbolReader, - DEFAULT_SOURCE_COUNTRIES, - normalizeCountryIso2, readSecurityMasterSources, type ExchangeSourceLookup, type ReadOnlyMongoCollectionClient, @@ -75,9 +72,7 @@ export const RUN_SECURITY_MASTER_USAGE = [ ' --out-dir Required. Output directory for match-report.md, conflicts.csv, override-template.sql, and run-stats.json.', ' --persist Optional. Persist security-master rows to isolated dev PostgreSQL after running safety guards (default: off).', ' --skip-price-cross-check Optional. Skip Pass 4 sample-close reads and price cross-checks (default: enabled).', - ' --sample-dates Optional. Number of stratified sample dates for Pass 4 (1..64, default: 25).', - ' --reviewed-us-ca-exchanges Optional. Scope Pass 1 exchange classification to configured US/CA countries with reviewed US/CA venue rules.', - ' --allow-identifierless-eod Optional. Admit US/CA EOD primary-venue listings lacking ISIN/CUSIP (stored with primary_isin = NULL).', + ` --sample-dates Optional. Number of stratified sample dates for Pass 4 (1..${MAX_SAMPLE_DATES}, default: ${DEFAULT_SAMPLE_DATE_COUNT}).`, ' --help Show this help message and exit.', ].join('\n'); @@ -90,8 +85,6 @@ export type ParsedRunSecurityMasterArgs = readonly persist: boolean; readonly skipPriceCrossCheck: boolean; readonly sampleDateCount: number; - readonly useReviewedUsCaExchanges?: boolean; - readonly allowIdentifierlessEod?: boolean; }; export interface RunSecurityMasterPass4Options { @@ -141,8 +134,6 @@ export interface RunSecurityMasterOptions { readonly batchSize?: number; readonly barSpans?: Omit; readonly pass4?: RunSecurityMasterPass4Options; - readonly useReviewedUsCaExchanges?: boolean; - readonly allowIdentifierlessEod?: boolean; } export interface RunSecurityMasterOutput { @@ -360,8 +351,6 @@ export function parseRunSecurityMasterArgs(argv: readonly string[]): ParsedRunSe let persist = false; let skipPriceCrossCheck = false; let sampleDateCount = DEFAULT_SAMPLE_DATE_COUNT; - let useReviewedUsCaExchanges = false; - let allowIdentifierlessEod = false; for (let i = 0; i < argv.length; i++) { const arg = argv[i]; @@ -377,14 +366,6 @@ export function parseRunSecurityMasterArgs(argv: readonly string[]): ParsedRunSe skipPriceCrossCheck = true; continue; } - if (arg === '--reviewed-us-ca-exchanges') { - useReviewedUsCaExchanges = true; - continue; - } - if (arg === '--allow-identifierless-eod') { - allowIdentifierlessEod = true; - continue; - } if (arg === '--sample-dates') { const value = argv[i + 1]; if (!value || value.trim().length === 0 || value.startsWith('--')) { @@ -462,8 +443,6 @@ export function parseRunSecurityMasterArgs(argv: readonly string[]): ParsedRunSe persist, skipPriceCrossCheck, sampleDateCount, - ...(useReviewedUsCaExchanges ? { useReviewedUsCaExchanges: true } : {}), - ...(allowIdentifierlessEod ? { allowIdentifierlessEod: true } : {}), }; } @@ -648,31 +627,8 @@ export async function runSecurityMaster( } exchangeCountsByCollection[source] = count; } - let recordsToClassify = normalizedRecords; - if (options.useReviewedUsCaExchanges === true && options.countries !== null) { - const allowedCountries = new Set( - (options.countries ?? DEFAULT_SOURCE_COUNTRIES) - .map(c => normalizeCountryIso2(c) ?? c.trim().toUpperCase()) - .filter(c => c.length > 0) - ); - recordsToClassify = normalizedRecords.filter(rec => { - const codeUpper = rec.code.trim().toUpperCase(); - if (rec.source === 'eod' && codeUpper === 'FOREX') { - return true; - } - const iso = normalizeCountryIso2(rec.country); - return ( - rec.country === null || - rec.country === undefined || - (iso !== null && allowedCountries.has(iso)) - ); - }); - } - exchanges = classifySourceExchanges(recordsToClassify, { + exchanges = classifySourceExchanges(normalizedRecords, { knownExchanges: ISO_EXCHANGE_SEEDS, - ...(options.useReviewedUsCaExchanges === true - ? { reviewedRows: REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS } - : {}), }); } @@ -688,7 +644,6 @@ export async function runSecurityMaster( exchangeLookup, countries: options.countries, batchSize: options.batchSize, - ...(options.allowIdentifierlessEod === true ? { includeExtendedMetadata: true } : {}), }); } catch (error) { throw wrapStepError('read-sources', error); @@ -718,41 +673,6 @@ export async function runSecurityMaster( } // Step 5: Compose Stage A -> Stage B -> Pass 6 -> candidate Pass 4 pairs. - const composeOptions = - options.allowIdentifierlessEod === true - ? { - asOfDate: options.asOfDate, - stageA: { allowIdentifierlessEod: true }, - stageB: { - enableIbTickerDisambiguation: true, - allowUniqueTickerFallbackForCrawlOnlyCeo: true, - }, - report: { - applyUsCaEquityGateDenominator: true, - }, - } - : { - asOfDate: options.asOfDate, - }; - - // Preserve verified pre-2024 FB -> META ticker history (2012-05-18 .. 2022-06-08) when - // META.US is present and eodSymbolChange only covers recent years, so historical FB bars - // map to Meta while the 2025 ProShares FB ETF (FB.US) retains a distinct listing_id. - if ( - options.allowIdentifierlessEod === true && - sources.stageBInput.eodListings.some(e => e.sourceId === 'META.US') && - !sources.stageBInput.symbolChanges.some( - sc => sc.eodSourceId === 'META.US' && sc.oldTicker === 'FB' - ) - ) { - sources.stageBInput.symbolChanges.push({ - eodSourceId: 'META.US', - oldTicker: 'FB', - effectiveDate: '2022-06-09', - validFrom: '2012-05-18', - }); - } - const composeFn = deps.composeFn ?? composeSecurityMasterRun; let composed: ComposeSecurityMasterRunResult; try { @@ -762,7 +682,9 @@ export async function runSecurityMaster( barSpans, exchanges, }, - composeOptions + { + asOfDate: options.asOfDate, + } ); } catch (error) { throw wrapStepError('compose', error); @@ -836,7 +758,9 @@ export async function runSecurityMaster( sampleCloses: sampleCloses.closes, fxRates: sampleCloses.fxRates, }, - composeOptions + { + asOfDate: options.asOfDate, + } ); } catch (error) { throw wrapStepError('compose', error); @@ -1101,8 +1025,6 @@ export async function runCli(argv: readonly string[] = process.argv.slice(2)): P asOfDate: parsed.asOfDate, outDir: parsed.outDir, persist: parsed.persist, - ...(parsed.useReviewedUsCaExchanges ? { useReviewedUsCaExchanges: true } : {}), - ...(parsed.allowIdentifierlessEod ? { allowIdentifierlessEod: true } : {}), pass4: { enabled: !parsed.skipPriceCrossCheck, sampleDateCount: parsed.sampleDateCount, diff --git a/apps/stock/data-pipeline/src/security-master/run.ts b/apps/stock/data-pipeline/src/security-master/run.ts index 6087833e..182ca474 100644 --- a/apps/stock/data-pipeline/src/security-master/run.ts +++ b/apps/stock/data-pipeline/src/security-master/run.ts @@ -22,12 +22,10 @@ import { isStageASource, matchInstrumentsStageA, STAGE_A_SOURCES, - SYNTHETIC_EOD_ISIN_PREFIX, type MatchInstrumentsStageAOptions, type StageAMatchResult, type StageASourceRecord, } from './instrument-stage-a'; -import { classifyEodSecurityType } from './security-type'; import { matchListingsStageB, MAX_TICKER_ROOT_LENGTH, @@ -48,8 +46,6 @@ import { sourceCountryKey, type BuildMatchReportOptions, type CountryResolutionSummary, - type GateOutOfScopeLookup, - type GateOutOfScopeReason, type MatchReport, type RenderMatchReportMarkdownOptions, type SourceCountryLookup, @@ -937,8 +933,7 @@ function applyEndToEndStageACoverage( const unresolved = row.unresolved + d.unresolved; const conflict = row.conflict + d.conflict; const excludedByDesign = row.excludedByDesign + d.excludedByDesign; - const outOfGateScope = row.outOfGateScope ?? 0; - const eligibleTotal = Math.max(0, total - excludedByDesign - outOfGateScope); + const eligibleTotal = Math.max(0, total - excludedByDesign); return { source: row.source, total, @@ -946,7 +941,6 @@ function applyEndToEndStageACoverage( unresolved, conflict, excludedByDesign, - ...(row.outOfGateScope !== undefined ? { outOfGateScope } : {}), eligibleTotal, resolvedPct: total > 0 ? row.matched / total : null, eligibleResolvedPct: eligibleTotal > 0 ? row.matched / eligibleTotal : null, @@ -1181,143 +1175,6 @@ export function composeSecurityMasterRun( const sourceCountries = input.sourceCountries ?? deriveSourceCountries(sanitizedStageARecords, attached.stageBInput, stageB); -const NON_EQUITY_CLASS_SUFFIX_RE = - /^(WT|WS|DB|RT|R|U|UN|H|P|PR|PF|PA|PB|PC|PD|PE|PG|PH|PI|PJ|PK|PL|PM|PN|PO|PP|PQ|PS|PT|PU|PV|PW|PX|PY|PZ|PR[A-Z]|PF[A-Z])(\..+)?$/; -const TEST_SYMBOL_RE = /^(NTEST|ZXYZ|ZVZZT|ZWZZT|ZXZZT)/i; -const NON_EQUITY_NAME_RE = - /\b(WARRANTS?|DEBENTURES?|PREFERRED|PFD|RIGHTS?|SUBSCRIPTION\s+RECEIPTS?|UNITS?|TEST\s+SYMBOL)\b/i; - -const US_CA_EQUITY_GATE_DENOMINATOR_NOTE = [ - 'The M1 `>= 95.00%` equity resolution gate evaluates **gate-eligible US/CA common equities & ETFs on EODHD-covered exchanges** (`XNYS`, `XNAS`, `ARCX`, `XASE`, `BATS`, `OTCM`, `XTSE`, `XTSX`, `NEOE`).', - 'All raw catalog rows remain visible in `Total` and `Resolved %`; non-matched records outside the gate denominator are transparently itemized under `Excluded by Design` (`excluded_fund`, `composite_venue`, `ats_routing_venue`, `forex_venue`) and `Out of Gate Scope`:', - '- `zero_bar_catalog_ghost`: secondary ticker-only rows (`qm`) with `missing_span` (zero price bars in `qmPrices`, intentionally refused by Stage B Tier 3/4 temporal-overlap safety to prevent ticker-reuse corruption such as `FB`).', - '- `uncovered_venue`: listings on venues absent from the EODHD bar master (`XCNQ` Canadian Securities Exchange across `qm`/`ceo`/`ib:AEQLIT`, and `ceo:NEOE` where EODHD carries only 19 of 587 listings).', - '- `non_equity_instrument`: non-common-equity instruments & test tickers (warrants `.WT`/`.WS`, convertible debentures `.DB`, subscription receipts/rights `.R`/`.RT`, SPAC/REIT units `.U`/`.UN`, preferred shares `.PR*`/`-P*`, TSXV NEX shells `.H`, TSXV CPCs `.P`, and exchange test symbols).', -].join('\n'); - -function isNonEquityRecord( - source: 'ib' | 'qm' | 'ceo', - ticker: string | null | undefined, - name: string | null | undefined -): boolean { - if (typeof name === 'string' && NON_EQUITY_NAME_RE.test(name)) { - return true; - } - if (typeof ticker !== 'string' || ticker.trim().length === 0) { - return false; - } - const trimmed = ticker.trim(); - if (TEST_SYMBOL_RE.test(trimmed)) { - return true; - } - if (source === 'ceo' && /\.(CN|NEO)$/i.test(trimmed)) { - return false; - } - const parsed = parseTickerDetailed(trimmed, source); - if (!parsed.ok) { - return false; - } - return ( - parsed.classSuffix.length > 0 && - NON_EQUITY_CLASS_SUFFIX_RE.test(parsed.classSuffix.toUpperCase()) - ); -} - -function buildUsCaEquityGateOutOfScope( - stageBInput: SecurityMasterStageBSourceInput, - stageB: StageBMatchResult -): GateOutOfScopeLookup { - const out = new Map(); - - const ibById = new Map(); - for (const contract of stageBInput.ibContracts) { - if (contract !== undefined) { - ibById.set(contract.sourceId, contract); - } - } - const tickerByKey = new Map(); - for (const entry of stageBInput.tickerSources) { - if (entry !== undefined) { - tickerByKey.set(sourceCountryKey(entry.source, entry.sourceId), entry); - } - } - - for (const rec of stageB.unresolved) { - const key = sourceCountryKey(rec.source, rec.sourceId); - if (rec.source === 'qm') { - if (rec.reason === 'missing_span') { - out.set(key, 'zero_bar_catalog_ghost'); - continue; - } - const meta = tickerByKey.get(key); - if (meta !== undefined) { - if (meta.mic === 'XCNQ') { - out.set(key, 'uncovered_venue'); - continue; - } - if (isNonEquityRecord('qm', meta.ticker, meta.name)) { - out.set(key, 'non_equity_instrument'); - } - } - } else if (rec.source === 'ceo') { - const meta = tickerByKey.get(key); - if (meta !== undefined) { - if ( - meta.mic === 'XCNQ' || - meta.mic === 'NEOE' || - (typeof meta.ticker === 'string' && /\.(CN|NEO)$/i.test(meta.ticker.trim())) - ) { - out.set(key, 'uncovered_venue'); - continue; - } - if (isNonEquityRecord('ceo', meta.ticker, meta.name)) { - out.set(key, 'non_equity_instrument'); - } - } - } else if (rec.source === 'ib') { - const meta = ibById.get(rec.sourceId); - if (meta !== undefined) { - if (isNonEquityRecord('ib', meta.ticker, meta.name)) { - out.set(key, 'non_equity_instrument'); - continue; - } - if (meta.exchangeId === 'AEQLIT' && meta.currency === 'CAD') { - out.set(key, 'uncovered_venue'); - } - } - } - } - - for (const conflict of stageB.conflicts) { - const key = sourceCountryKey(conflict.source, conflict.sourceId); - if (out.has(key)) { - continue; - } - if (conflict.source === 'ib') { - const meta = ibById.get(conflict.sourceId); - if (meta !== undefined && isNonEquityRecord('ib', meta.ticker, meta.name)) { - out.set(key, 'non_equity_instrument'); - } - } else if (conflict.source === 'qm' || conflict.source === 'ceo') { - const meta = tickerByKey.get(key); - if (meta !== undefined) { - if (meta.mic === 'XCNQ' || (conflict.source === 'ceo' && meta.mic === 'NEOE')) { - out.set(key, 'uncovered_venue'); - } else if (isNonEquityRecord(conflict.source, meta.ticker, meta.name)) { - out.set(key, 'non_equity_instrument'); - } - } - } - } - - return out; -} - - const gateOutOfScope = - options.report?.applyUsCaEquityGateDenominator === true - ? buildUsCaEquityGateOutOfScope(attached.stageBInput, stageB) - : undefined; - const baseReport = buildMatchReport( { ...(input.exchanges !== undefined ? { exchanges: input.exchanges } : {}), @@ -1326,12 +1183,6 @@ function buildUsCaEquityGateOutOfScope( ...(pass4 !== null ? { priceCrossCheck: pass4 } : {}), delistingChains: pass6, sourceCountries, - ...(gateOutOfScope !== undefined - ? { - gateOutOfScope, - gateDenominatorNote: US_CA_EQUITY_GATE_DENOMINATOR_NOTE, - } - : {}), }, options.report ); @@ -1357,29 +1208,6 @@ function buildUsCaEquityGateOutOfScope( sortedSecurityTypeByIsin.set(entry[0], entry[1]); } } - if ( - options.stageA?.allowIdentifierlessEod === true && - Array.isArray(input.sources.securityTypeRecords) - ) { - const syntheticEntries: Array<[string, SecurityType]> = []; - for (const rec of input.sources.securityTypeRecords) { - if (rec !== undefined && rec.isin === null && typeof rec.sourceId === 'string') { - const mapped = classifyEodSecurityType(rec.rawType); - if (mapped !== null) { - syntheticEntries.push([ - `${SYNTHETIC_EOD_ISIN_PREFIX}${rec.sourceId.trim().toUpperCase()}`, - mapped, - ]); - } - } - } - syntheticEntries.sort((a, b) => compareAscii(a[0], b[0])); - for (const [k, v] of syntheticEntries) { - if (!sortedSecurityTypeByIsin.has(k)) { - sortedSecurityTypeByIsin.set(k, v); - } - } - } const persistInput: PersistSecurityMasterInput = { stageA, @@ -1394,7 +1222,7 @@ function buildUsCaEquityGateOutOfScope( let stageAUnresolved = 0; for (const source of STAGE_A_SOURCES) { const s = stageA.stats.bySource[source]; - stageAResolved += s.tier1Isin + s.tier2Cusip + (s.tier3Synthetic ?? 0); + stageAResolved += s.tier1Isin + s.tier2Cusip; stageAUnresolved += s.unresolved + s.conflict; } const stageAStepStats: StageAComposeStepStats = { diff --git a/apps/stock/data-pipeline/src/security-master/source-field-shapes.ts b/apps/stock/data-pipeline/src/security-master/source-field-shapes.ts deleted file mode 100644 index da009d68..00000000 --- a/apps/stock/data-pipeline/src/security-master/source-field-shapes.ts +++ /dev/null @@ -1,915 +0,0 @@ -import { compareAscii } from './exchange-pass1'; -import type { - ReadOnlySourceSymbolCursor, - ReadOnlySourceSymbolReader, - SourceSymbolFindOptions, -} from './source-symbol-readers'; - -export const FIELD_SHAPE_PROBE_COLLECTIONS = Object.freeze([ - 'ceoShorts', - 'qmSplits', - 'qmDividends', - 'qmFilings', - 'qmEarnings', - 'qmPrices', - 'eodPrices', - 'teMarketData', -] as const); - -export type FieldShapeProbeCollection = (typeof FIELD_SHAPE_PROBE_COLLECTIONS)[number]; - -export const FIELD_VALUE_TYPES = Object.freeze([ - 'string', - 'int', - 'double', - 'bool', - 'date', - 'null', - 'objectId', - 'array', - 'object', - 'other', -] as const); - -export type FieldValueType = (typeof FIELD_VALUE_TYPES)[number]; - -export const STRING_PATTERN_CLASSES = Object.freeze([ - 'ymd', - 'isoDatetime', - 'numeric', - 'emptyOrWhitespace', - 'other', -] as const); - -export type StringPatternClass = (typeof STRING_PATTERN_CLASSES)[number]; - -export const DEFAULT_FIELD_SHAPE_LIMIT = 1_000; -export const MAX_FIELD_SHAPE_LIMIT = 10_000; -export const DEFAULT_MAX_EXAMPLES = 3; -export const MAX_EXAMPLES_CAP = 10; -export const DEFAULT_MAX_EXAMPLE_LENGTH = 48; -export const MAX_EXAMPLE_LENGTH_CAP = 120; - -const ALLOWED_PROBE_COLLECTION_SET: ReadonlySet = new Set( - FIELD_SHAPE_PROBE_COLLECTIONS -); - -export class UnknownProbeCollectionError extends Error { - readonly collectionName: string; - readonly allowedCollections: readonly FieldShapeProbeCollection[]; - - constructor(collectionName: string) { - super( - `Unknown probe collection "${collectionName}". Allowed collections: ${FIELD_SHAPE_PROBE_COLLECTIONS.join(', ')}` - ); - this.name = 'UnknownProbeCollectionError'; - this.collectionName = collectionName; - this.allowedCollections = FIELD_SHAPE_PROBE_COLLECTIONS; - Object.setPrototypeOf(this, new.target.prototype); - } -} - -export type FieldValueTypeCounts = Record; -export type StringPatternCounts = Record; - -export interface FieldStringStats { - minLength: number; - maxLength: number; - patterns: StringPatternCounts; -} - -export interface FieldShapeSummary { - field: string; - presentCount: number; - missingCount: number; - typeCounts: FieldValueTypeCounts; - stringStats: FieldStringStats | null; - examples: string[]; -} - -export interface SummarizeFieldShapesOptions { - readonly maxExamples?: number; - readonly maxExampleLength?: number; -} - -export interface CollectionFieldShapesSummary { - docCount: number; - fields: FieldShapeSummary[]; -} - -export interface ReadFieldShapesOptions extends SummarizeFieldShapesOptions { - readonly collections?: readonly string[]; - readonly limit?: number; - readonly batchSize?: number; -} - -export interface CollectionFieldShapesProbeResult extends CollectionFieldShapesSummary { - collection: FieldShapeProbeCollection; -} - -export interface ReadFieldShapesResult { - limit: number; - maxExamples: number; - maxExampleLength: number; - totalDocsSampled: number; - collections: CollectionFieldShapesProbeResult[]; -} - -const EXACT_YMD_PATTERN = /^\d{4}-\d{2}-\d{2}$/; -const STRICT_ISO_DATETIME_PATTERN = - /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(?:Z|([+-])(\d{2}):?(\d{2}))?$/; -const NUMERIC_STRING_PATTERN = /^[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?$/; -const DAYS_IN_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] as const; - -function isLeapYear(year: number): boolean { - return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; -} - -function isValidCalendarDate(year: number, month: number, day: number): boolean { - if (year < 1 || year > 9999 || month < 1 || month > 12) { - return false; - } - const maxDay = month === 2 && isLeapYear(year) ? 29 : (DAYS_IN_MONTH[month] ?? 0); - return day >= 1 && day <= maxDay; -} - -function isValidYmd(value: string): boolean { - if (!EXACT_YMD_PATTERN.test(value)) { - return false; - } - const year = - (value.charCodeAt(0) - 48) * 1000 + - (value.charCodeAt(1) - 48) * 100 + - (value.charCodeAt(2) - 48) * 10 + - (value.charCodeAt(3) - 48); - const month = (value.charCodeAt(5) - 48) * 10 + (value.charCodeAt(6) - 48); - const day = (value.charCodeAt(8) - 48) * 10 + (value.charCodeAt(9) - 48); - return isValidCalendarDate(year, month, day); -} - -function isValidIsoDatetime(value: string): boolean { - const match = STRICT_ISO_DATETIME_PATTERN.exec(value); - if (match === null) { - return false; - } - const year = Number(match[1]); - const month = Number(match[2]); - const day = Number(match[3]); - const hour = Number(match[4]); - const minute = Number(match[5]); - const second = Number(match[6]); - - if (!isValidCalendarDate(year, month, day)) { - return false; - } - if (hour > 23 || minute > 59 || second > 59) { - return false; - } - if (match[7] !== undefined) { - const tzHour = Number(match[8]); - const tzMinute = Number(match[9]); - if (tzHour > 23 || tzMinute > 59) { - return false; - } - } - return true; -} - -function classifyStringPattern(value: string): StringPatternClass { - if (value.length === 0 || value.trim().length === 0) { - return 'emptyOrWhitespace'; - } - if (value.length === 10 && isValidYmd(value)) { - return 'ymd'; - } - if (value.length >= 19 && value.charCodeAt(10) === 84 && isValidIsoDatetime(value)) { - return 'isoDatetime'; - } - if (NUMERIC_STRING_PATTERN.test(value)) { - return 'numeric'; - } - return 'other'; -} - -function createEmptyTypeCounts(): FieldValueTypeCounts { - return { - string: 0, - int: 0, - double: 0, - bool: 0, - date: 0, - null: 0, - objectId: 0, - array: 0, - object: 0, - other: 0, - }; -} - -function createEmptyStringPatternCounts(): StringPatternCounts { - return { - ymd: 0, - isoDatetime: 0, - numeric: 0, - emptyOrWhitespace: 0, - other: 0, - }; -} - -function isNonPlainBuiltInObject(value: object): boolean { - return ( - value instanceof Date || - Array.isArray(value) || - ArrayBuffer.isView(value) || - value instanceof ArrayBuffer || - value instanceof RegExp || - value instanceof Map || - value instanceof Set - ); -} - -function getBsonTypeTag(value: object): string | null { - const tag = (value as { _bsontype?: unknown })._bsontype; - return typeof tag === 'string' && tag.length > 0 ? tag : null; -} - -function isPlainNestedObject(value: unknown): value is Record { - if (value === null || typeof value !== 'object') { - return false; - } - if (isNonPlainBuiltInObject(value)) { - return false; - } - if (getBsonTypeTag(value) !== null) { - return false; - } - return true; -} - -function classifyValueType(value: unknown): FieldValueType { - if (value === null) { - return 'null'; - } - const primitiveType = typeof value; - if (primitiveType === 'string') { - return 'string'; - } - if (primitiveType === 'boolean') { - return 'bool'; - } - if (primitiveType === 'number') { - return Number.isInteger(value) ? 'int' : 'double'; - } - if (primitiveType === 'bigint') { - return 'int'; - } - if (primitiveType !== 'object') { - return 'other'; - } - - const obj = value as object; - if (obj instanceof Date) { - return 'date'; - } - if (Array.isArray(obj)) { - return 'array'; - } - - const bsonTag = getBsonTypeTag(obj); - if (bsonTag !== null) { - if (bsonTag === 'Int32' || bsonTag === 'Long') { - return 'int'; - } - if (bsonTag === 'Double') { - return 'double'; - } - if (bsonTag === 'ObjectId' || bsonTag === 'ObjectID') { - return 'objectId'; - } - return 'other'; - } - - if (isNonPlainBuiltInObject(obj)) { - return 'other'; - } - - return 'object'; -} - -function escapeFieldSegment(segment: string): string { - if (!segment.includes('.') && !segment.includes('\\')) { - return segment; - } - return segment.replace(/\\/g, '\\\\').replace(/\./g, '\\.'); -} - -function formatFieldPath(parentKey: string, childKey?: string): string { - const escapedParent = escapeFieldSegment(parentKey); - return childKey === undefined ? escapedParent : `${escapedParent}.${escapeFieldSegment(childKey)}`; -} - -function sanitizeAndTruncateExample(raw: string, maxLength: number): string { - let cleaned = ''; - for (let i = 0; i < raw.length; i++) { - const code = raw.charCodeAt(i); - if (code === 9 || code === 10 || code === 13) { - cleaned += ' '; - } else if (code >= 32 && code !== 127) { - cleaned += raw[i]; - } - } - if (cleaned.length <= maxLength) { - return cleaned; - } - if (maxLength <= 3) { - return cleaned.slice(0, maxLength); - } - return `${cleaned.slice(0, maxLength - 3)}...`; -} - -function extractScalarExample( - value: unknown, - valueType: FieldValueType, - maxExampleLength: number -): string | null { - if (valueType === 'null' || valueType === 'array' || valueType === 'object') { - return null; - } - - let raw: string | null = null; - if (valueType === 'string') { - raw = value as string; - } else if (valueType === 'bool') { - raw = (value as boolean) ? 'true' : 'false'; - } else if (valueType === 'int' || valueType === 'double') { - if (typeof value === 'number' || typeof value === 'bigint') { - raw = String(value); - } else if (value !== null && typeof value === 'object') { - raw = String(value); - } - } else if (valueType === 'date' && value instanceof Date) { - raw = Number.isNaN(value.getTime()) ? 'Invalid Date' : value.toISOString(); - } else if (valueType === 'objectId') { - raw = String(value); - } else if (valueType === 'other' && value !== null && typeof value === 'object') { - const bsonTag = getBsonTypeTag(value); - if (bsonTag === 'Decimal128' || bsonTag === 'UUID') { - raw = String(value); - } - } - - if (raw === null) { - return null; - } - return sanitizeAndTruncateExample(raw, maxExampleLength); -} - -function validateBoundedInt(value: unknown, name: string, min: number, max: number): number { - if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < min || value > max) { - throw new RangeError(`${name} must be an integer between ${min} and ${max}, received ${String(value)}`); - } - return value; -} - -function validatePositiveSafeInt(value: unknown, name: string): number { - if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) { - throw new RangeError(`${name} must be a positive safe integer, received ${String(value)}`); - } - return value; -} - -function resolveSummarizeOptions(options?: SummarizeFieldShapesOptions): { - maxExamples: number; - maxExampleLength: number; -} { - if (options !== undefined && (options === null || typeof options !== 'object')) { - throw new TypeError('options must be an object'); - } - const maxExamples = - options?.maxExamples !== undefined - ? validateBoundedInt(options.maxExamples, 'options.maxExamples', 0, MAX_EXAMPLES_CAP) - : DEFAULT_MAX_EXAMPLES; - const maxExampleLength = - options?.maxExampleLength !== undefined - ? validateBoundedInt( - options.maxExampleLength, - 'options.maxExampleLength', - 1, - MAX_EXAMPLE_LENGTH_CAP - ) - : DEFAULT_MAX_EXAMPLE_LENGTH; - return { maxExamples, maxExampleLength }; -} - -interface MutableFieldAccumulator { - presentCount: number; - typeCounts: FieldValueTypeCounts; - stringStats: FieldStringStats | null; - examples: string[]; -} - -/** - * Streaming, order-independent field-shape accumulator shared by `summarizeFieldShapes` - * and `readFieldShapes`. Keeps O(`maxExamples`) distinct ASCII-smallest examples per field. - */ -class FieldShapeAccumulator { - private readonly maxExamples: number; - private readonly maxExampleLength: number; - private readonly fields = new Map(); - private docCount = 0; - - constructor(maxExamples: number, maxExampleLength: number) { - this.maxExamples = maxExamples; - this.maxExampleLength = maxExampleLength; - } - - addDocument(doc: unknown): void { - this.docCount += 1; - if (!isPlainNestedObject(doc)) { - return; - } - - const keys = Object.keys(doc); - for (let i = 0; i < keys.length; i++) { - const key = keys[i]; - if (key === undefined) { - continue; - } - const value = doc[key]; - if (value === undefined) { - continue; - } - - const suppressExamples = key === '_id'; - const valueType = this.recordFieldValue(formatFieldPath(key), value, suppressExamples); - if (valueType === 'object' && isPlainNestedObject(value)) { - const childKeys = Object.keys(value); - for (let j = 0; j < childKeys.length; j++) { - const childKey = childKeys[j]; - if (childKey === undefined) { - continue; - } - const childValue = value[childKey]; - if (childValue === undefined) { - continue; - } - this.recordFieldValue(formatFieldPath(key, childKey), childValue, suppressExamples); - } - } - } - } - - finalize(): CollectionFieldShapesSummary { - const sortedNames = Array.from(this.fields.keys()).sort(compareAscii); - const summaries: FieldShapeSummary[] = []; - for (let i = 0; i < sortedNames.length; i++) { - const fieldName = sortedNames[i]; - if (fieldName === undefined) { - continue; - } - const acc = this.fields.get(fieldName); - if (acc === undefined) { - continue; - } - summaries.push({ - field: fieldName, - presentCount: acc.presentCount, - missingCount: this.docCount - acc.presentCount, - typeCounts: { ...acc.typeCounts }, - stringStats: - acc.stringStats === null - ? null - : { - minLength: acc.stringStats.minLength, - maxLength: acc.stringStats.maxLength, - patterns: { ...acc.stringStats.patterns }, - }, - examples: [...acc.examples], - }); - } - - return { - docCount: this.docCount, - fields: summaries, - }; - } - - private recordFieldValue( - fieldPath: string, - value: unknown, - suppressExamples: boolean - ): FieldValueType { - let acc = this.fields.get(fieldPath); - if (acc === undefined) { - acc = { - presentCount: 0, - typeCounts: createEmptyTypeCounts(), - stringStats: null, - examples: [], - }; - this.fields.set(fieldPath, acc); - } - - const valueType = classifyValueType(value); - acc.presentCount += 1; - acc.typeCounts[valueType] += 1; - - if (valueType === 'string') { - const str = value as string; - const len = str.length; - if (acc.stringStats === null) { - acc.stringStats = { - minLength: len, - maxLength: len, - patterns: createEmptyStringPatternCounts(), - }; - } else { - if (len < acc.stringStats.minLength) { - acc.stringStats.minLength = len; - } - if (len > acc.stringStats.maxLength) { - acc.stringStats.maxLength = len; - } - } - acc.stringStats.patterns[classifyStringPattern(str)] += 1; - } - - if (this.maxExamples > 0 && !suppressExamples) { - const example = extractScalarExample(value, valueType, this.maxExampleLength); - if (example !== null) { - this.insertExample(acc.examples, example); - } - } - - return valueType; - } - - private insertExample(examples: string[], candidate: string): void { - const len = examples.length; - const last = len > 0 ? examples[len - 1] : undefined; - if (len === this.maxExamples && last !== undefined && compareAscii(candidate, last) >= 0) { - return; - } - - let insertAt = len; - for (let i = 0; i < len; i++) { - const existing = examples[i]; - if (existing === undefined) { - continue; - } - const cmp = compareAscii(candidate, existing); - if (cmp === 0) { - return; - } - if (cmp < 0) { - insertAt = i; - break; - } - } - - examples.splice(insertAt, 0, candidate); - if (examples.length > this.maxExamples) { - examples.pop(); - } - } -} - -/** - * Pure, deterministic summarizer for field names, BSON/JS value types, string patterns, - * and bounded sanitized examples across an iterable of documents from one collection. - */ -export function summarizeFieldShapes( - docs: Iterable>, - options?: SummarizeFieldShapesOptions -): CollectionFieldShapesSummary { - if ( - docs === null || - docs === undefined || - typeof (docs as unknown as Record)[Symbol.iterator] !== 'function' - ) { - throw new TypeError('docs must be an Iterable of document objects'); - } - const { maxExamples, maxExampleLength } = resolveSummarizeOptions(options); - const accumulator = new FieldShapeAccumulator(maxExamples, maxExampleLength); - for (const doc of docs) { - accumulator.addDocument(doc); - } - return accumulator.finalize(); -} - -export function isFieldShapeProbeCollection(value: string): value is FieldShapeProbeCollection { - return ALLOWED_PROBE_COLLECTION_SET.has(value); -} - -export function normalizeProbeCollections( - collections?: readonly string[] -): FieldShapeProbeCollection[] { - const source = collections === undefined ? FIELD_SHAPE_PROBE_COLLECTIONS : collections; - if (!Array.isArray(source) || source.length === 0) { - throw new RangeError('collections must be a non-empty array of allowed probe collection names'); - } - const unique = new Set(); - for (let i = 0; i < source.length; i++) { - const name = source[i]; - if (typeof name !== 'string' || !isFieldShapeProbeCollection(name)) { - throw new UnknownProbeCollectionError(String(name)); - } - unique.add(name); - } - return Array.from(unique).sort(compareAscii); -} - -function assertReadOnlyReader(reader: ReadOnlySourceSymbolReader): void { - if ( - reader === null || - reader === undefined || - typeof reader !== 'object' || - typeof reader.isReadOnly !== 'function' || - typeof reader.find !== 'function' || - reader.isReadOnly() !== true - ) { - throw new Error( - 'Source field-shape probe requires a read-only MongoDB reader (isReadOnly() must be true)' - ); - } -} - -function isAsyncIterable(value: unknown): value is AsyncIterable { - return ( - value !== null && - (typeof value === 'object' || typeof value === 'function') && - typeof (value as Record)[Symbol.asyncIterator] === 'function' - ); -} - -function wrapCollectionReadError(collectionName: string, error: unknown): Error { - const detail = error instanceof Error ? error.message : String(error); - const message = detail.includes(collectionName) - ? detail - : `Failed reading collection "${collectionName}": ${detail}`; - return new Error(message, { cause: error }); -} - -async function streamBoundedCollectionIntoAccumulator( - reader: ReadOnlySourceSymbolReader, - collectionName: FieldShapeProbeCollection, - limit: number, - findOptions: SourceSymbolFindOptions, - accumulator: FieldShapeAccumulator -): Promise { - assertReadOnlyReader(reader); - let closableHandle: Pick>, 'close'> | null = - null; - let primaryError: unknown = undefined; - let hasPrimaryError = false; - let isInvalidCursorError = false; - - try { - const rawCursor = await reader.find>(collectionName, {}, findOptions); - if ( - rawCursor !== null && - (typeof rawCursor === 'object' || typeof rawCursor === 'function') - ) { - closableHandle = rawCursor as Pick< - ReadOnlySourceSymbolCursor>, - 'close' - >; - } - if (Array.isArray(rawCursor) || !isAsyncIterable>(rawCursor)) { - isInvalidCursorError = true; - throw new TypeError( - `Reader for collection "${collectionName}" must return an incremental AsyncIterable cursor (got buffered or non-async result)` - ); - } - - let seen = 0; - if (limit > 0) { - for await (const doc of rawCursor) { - accumulator.addDocument(doc); - seen += 1; - if (seen >= limit) { - break; - } - } - } - } catch (error) { - primaryError = error; - hasPrimaryError = true; - } finally { - if (closableHandle !== null && typeof closableHandle.close === 'function') { - try { - await closableHandle.close(); - } catch (closeError) { - if (!hasPrimaryError) { - primaryError = closeError; - hasPrimaryError = true; - } - } - } - } - - if (hasPrimaryError) { - if (isInvalidCursorError) { - throw primaryError; - } - throw wrapCollectionReadError(collectionName, primaryError); - } -} - -/** - * Bounded, read-only MongoDB field-shape probe over allowlisted source collections. - * Issues strictly `find({}, { limit, promoteValues: false, promoteLongs: false })` - * with zero aggregations, `$sample`, writes, or index operations. - */ -export async function readFieldShapes( - reader: ReadOnlySourceSymbolReader, - options?: ReadFieldShapesOptions -): Promise { - assertReadOnlyReader(reader); - - if (options !== undefined && (options === null || typeof options !== 'object')) { - throw new TypeError('options must be an object'); - } - - const limit = - options?.limit !== undefined - ? validateBoundedInt(options.limit, 'options.limit', 1, MAX_FIELD_SHAPE_LIMIT) - : DEFAULT_FIELD_SHAPE_LIMIT; - const { maxExamples, maxExampleLength } = resolveSummarizeOptions(options); - const batchSize = - options?.batchSize !== undefined - ? validatePositiveSafeInt(options.batchSize, 'options.batchSize') - : undefined; - const collections = normalizeProbeCollections(options?.collections); - - const findOptions: SourceSymbolFindOptions = { - limit, - promoteValues: false, - promoteLongs: false, - ...(batchSize !== undefined ? { batchSize } : {}), - }; - - const results: CollectionFieldShapesProbeResult[] = []; - let totalDocsSampled = 0; - - for (const collection of collections) { - const accumulator = new FieldShapeAccumulator(maxExamples, maxExampleLength); - await streamBoundedCollectionIntoAccumulator( - reader, - collection, - limit, - findOptions, - accumulator - ); - const summary = accumulator.finalize(); - totalDocsSampled += summary.docCount; - results.push({ - collection, - docCount: summary.docCount, - fields: summary.fields, - }); - } - - return { - limit, - maxExamples, - maxExampleLength, - totalDocsSampled, - collections: results, - }; -} - -function formatHtmlCodeElement(value: string): string { - const escaped = value.replace(/[&<>|\\`*_~[\]!]/g, ch => { - switch (ch) { - case '&': - return '&'; - case '<': - return '<'; - case '>': - return '>'; - case '|': - return '|'; - default: - return `&#${ch.charCodeAt(0)};`; - } - }); - return `${escaped}`; -} - -function formatMarkdownCodeCell(value: string): string { - const normalized = value.replace(/\r\n|\r|\n/g, ' '); - // Empty spans cannot be written with backtick fences; values containing `\|` - // would become `\\|` under pipe escaping, which GFM/micromark parses as an - // escaped backslash followed by a cell-splitting pipe. Use an HTML - // element with entity-encoded pipes and Markdown metacharacters instead. - if (normalized.length === 0 || normalized.includes('\\|')) { - return formatHtmlCodeElement(normalized); - } - const tableSafe = normalized.replace(/\|/g, '\\|'); - let maxBacktickRun = 0; - let currentRun = 0; - for (let i = 0; i < tableSafe.length; i++) { - if (tableSafe.charCodeAt(i) === 96) { - currentRun += 1; - if (currentRun > maxBacktickRun) { - maxBacktickRun = currentRun; - } - } else { - currentRun = 0; - } - } - const fence = '`'.repeat(maxBacktickRun + 1); - const startsWithBacktick = tableSafe.charCodeAt(0) === 96; - const endsWithBacktick = tableSafe.charCodeAt(tableSafe.length - 1) === 96; - const startsAndEndsWithSpace = - tableSafe.charCodeAt(0) === 32 && - tableSafe.charCodeAt(tableSafe.length - 1) === 32 && - tableSafe.trim().length > 0; - const needsPadding = startsWithBacktick || endsWithBacktick || startsAndEndsWithSpace; - return needsPadding ? `${fence} ${tableSafe} ${fence}` : `${fence}${tableSafe}${fence}`; -} - -function formatTypeCountsCell(typeCounts: FieldValueTypeCounts): string { - const parts: string[] = []; - for (const typeName of FIELD_VALUE_TYPES) { - const count = typeCounts[typeName]; - if (count > 0) { - parts.push(`${typeName}: ${count}`); - } - } - return parts.length > 0 ? parts.join(', ') : '—'; -} - -function formatStringStatsCell(stringStats: FieldStringStats | null): string { - if (stringStats === null) { - return '—'; - } - const parts: string[] = []; - for (const pattern of STRING_PATTERN_CLASSES) { - const count = stringStats.patterns[pattern]; - if (count > 0) { - parts.push(`${pattern}: ${count}`); - } - } - const patternText = parts.length > 0 ? parts.join(', ') : 'none'; - return `${patternText} (len ${stringStats.minLength}..${stringStats.maxLength})`; -} - -function formatExamplesCell(examples: readonly string[]): string { - if (examples.length === 0) { - return '—'; - } - return examples.map(formatMarkdownCodeCell).join(', '); -} - -/** - * Renders a deterministic Markdown field-shape report (zero wall-clock timestamps or - * filesystem paths). Identical results always produce byte-identical Markdown. - */ -export function renderFieldShapesMarkdown(result: ReadFieldShapesResult): string { - const sortedCollections = [...result.collections].sort((a, b) => - compareAscii(a.collection, b.collection) - ); - - const lines: string[] = [ - '# Source Field Shapes Report', - '', - '- **Scope:** bounded sample, not a full scan (head sample via `find().limit()`, no aggregation or `$sample`)', - `- **Sample limit per collection:** ${result.limit}`, - `- **Collections probed:** ${sortedCollections.length}`, - `- **Total documents sampled:** ${result.totalDocsSampled}`, - ]; - - for (const col of sortedCollections) { - lines.push('', `## \`${col.collection}\` (${col.docCount} docs sampled)`, ''); - - if (col.docCount === 0) { - lines.push('_No documents sampled._'); - continue; - } - - const sortedFields = [...col.fields].sort((a, b) => compareAscii(a.field, b.field)); - if (sortedFields.length === 0) { - lines.push('_No fields observed._'); - continue; - } - - lines.push('| Field | Presence | Types | String Patterns | Examples |'); - lines.push('| --- | --- | --- | --- | --- |'); - - for (const field of sortedFields) { - const pct = ((field.presentCount / col.docCount) * 100).toFixed(1); - const fieldCell = formatMarkdownCodeCell(field.field); - const presenceCell = `${pct}% (${field.presentCount}/${col.docCount})`; - const typesCell = formatTypeCountsCell(field.typeCounts); - const patternsCell = formatStringStatsCell(field.stringStats); - const examplesCell = formatExamplesCell(field.examples); - lines.push( - `| ${fieldCell} | ${presenceCell} | ${typesCell} | ${patternsCell} | ${examplesCell} |` - ); - } - } - - return `${lines.join('\n')}\n`; -} diff --git a/apps/stock/data-pipeline/src/security-master/source-symbol-readers.ts b/apps/stock/data-pipeline/src/security-master/source-symbol-readers.ts index 4397339e..58b7ea6a 100644 --- a/apps/stock/data-pipeline/src/security-master/source-symbol-readers.ts +++ b/apps/stock/data-pipeline/src/security-master/source-symbol-readers.ts @@ -53,9 +53,6 @@ export const DEFAULT_SOURCE_COUNTRIES: readonly string[] = Object.freeze(['US', export interface SourceSymbolFindOptions { projection?: Record; batchSize?: number; - limit?: number; - promoteValues?: boolean; - promoteLongs?: boolean; } /** @@ -164,7 +161,6 @@ export interface ReadSourceCollectionOptions { readonly knownExchanges?: readonly ExchangeSeedRow[]; readonly batchSize?: number; readonly maxSecurityTypeConflicts?: number; - readonly includeExtendedMetadata?: boolean; } export type ReadSecurityMasterSourcesOptions = ReadSourceCollectionOptions; @@ -179,7 +175,6 @@ export interface AdaptEodSymbolContext { export interface AdaptIbSymbolContext { readonly exchangeLookup: ExchangeSourceLookup; readonly allowedCountries: ReadonlySet | null; - readonly includeExtendedMetadata?: boolean; } export interface AdaptQmSymbolContext { @@ -187,7 +182,6 @@ export interface AdaptQmSymbolContext { readonly barSpans?: Pick | null; readonly allowedCountries: ReadonlySet | null; readonly micCurrencyMap: ReadonlyMap; - readonly includeExtendedMetadata?: boolean; } export interface AdaptCeoSymbolContext { @@ -195,7 +189,6 @@ export interface AdaptCeoSymbolContext { readonly ceoSpans?: ReadonlyMap | null; readonly allowedCountries: ReadonlySet | null; readonly micCurrencyMap: ReadonlyMap; - readonly includeExtendedMetadata?: boolean; } export interface AdaptEodSymbolChangeContext { @@ -446,9 +439,7 @@ export const CEO_SYMBOLS_PROJECTION: Readonly> = Object.fr export const EOD_SYMBOL_CHANGE_PROJECTION: Readonly> = Object.freeze({ _id: 0, oldSymbol: 1, - old_symbol: 1, newSymbol: 1, - new_symbol: 1, exchange: 1, eodExchange: 1, eodSearchCode: 1, @@ -1362,13 +1353,6 @@ export function adaptIbSymbolDoc( conid: rawConid, currency, primaryExchange, - ...(context.includeExtendedMetadata === true - ? { - ticker: symbolField.value, - name, - exchangeId: exchangeIdField.value !== null ? exchangeIdField.value.toUpperCase() : null, - } - : {}), }, invalidIdentifiersNulled, }; @@ -1449,11 +1433,6 @@ export function adaptQmSymbolDoc( : countryFallbackCurrency(effectiveCountry); const span = toSpanDateRange(context.barSpans?.get('qm', sourceId)); - const qmNameResult = - context.includeExtendedMetadata === true - ? readFirstOptionalString(doc, ['name', 'companyName']) - : null; - const qmName = qmNameResult !== null && qmNameResult.ok ? qmNameResult.value : null; return { ok: true, @@ -1465,7 +1444,6 @@ export function adaptQmSymbolDoc( role: exchangeEntry.role, currency, span, - ...(context.includeExtendedMetadata === true ? { name: qmName } : {}), }, }; } @@ -1558,10 +1536,6 @@ export function adaptCeoSymbolDoc( } } - const ceoNameResult = - context.includeExtendedMetadata === true ? readOptionalString(doc, 'name') : null; - const ceoName = ceoNameResult !== null && ceoNameResult.ok ? ceoNameResult.value : null; - return { ok: true, tickerSource: { @@ -1572,7 +1546,6 @@ export function adaptCeoSymbolDoc( role: exchangeEntry.role, currency, span, - ...(context.includeExtendedMetadata === true ? { name: ceoName } : {}), }, }; } @@ -1589,8 +1562,8 @@ export function adaptEodSymbolChangeDoc( return { ok: false, skipReason: 'invalidFieldType' }; } - const oldSymbolField = readFirstOptionalString(doc, ['oldSymbol', 'old_symbol']); - const newSymbolField = readFirstOptionalString(doc, ['newSymbol', 'new_symbol']); + const oldSymbolField = readOptionalString(doc, 'oldSymbol'); + const newSymbolField = readOptionalString(doc, 'newSymbol'); const exchangeField = readOptionalString(doc, 'exchange'); const eodExchangeField = readOptionalString(doc, 'eodExchange'); const eodSearchCodeField = readOptionalString(doc, 'eodSearchCode'); @@ -1790,7 +1763,6 @@ export async function readIbSymbols( const context: AdaptIbSymbolContext = { exchangeLookup: options.exchangeLookup, allowedCountries, - includeExtendedMetadata: options.includeExtendedMetadata, }; const stageARecords: StageASourceRecord[] = []; @@ -1839,7 +1811,6 @@ export async function readQmSymbols( barSpans: options.barSpans, allowedCountries, micCurrencyMap, - includeExtendedMetadata: options.includeExtendedMetadata, }; const tickerSources: StageBTickerSourceInput[] = []; @@ -1872,26 +1843,6 @@ export async function readQmSymbols( return { tickerSources, stats }; } -function expectedMicFromCeoSymbolSuffix(rawSymbol: unknown): string | null { - if (typeof rawSymbol !== 'string') { - return null; - } - const upper = rawSymbol.trim().toUpperCase(); - if (upper.endsWith('.TO')) { - return 'XTSE'; - } - if (upper.endsWith('.V')) { - return 'XTSX'; - } - if (upper.endsWith('.CN')) { - return 'XCNQ'; - } - if (upper.endsWith('.NEO') || upper.endsWith('.NE')) { - return 'NEOE'; - } - return null; -} - /** Streams and adapts `ceoSymbols` from a read-only MongoDB reader. */ export async function readCeoSymbols( reader: ReadOnlySourceSymbolReader, @@ -1904,15 +1855,9 @@ export async function readCeoSymbols( ceoSpans: options.ceoSpans, allowedCountries, micCurrencyMap, - includeExtendedMetadata: options.includeExtendedMetadata, }; const tickerSources: StageBTickerSourceInput[] = []; - const rawEntries: Array<{ - readonly tickerSource: StageBTickerSourceInput; - readonly rawSymbolKey: string | null; - readonly matchesSuffixMic: boolean; - }> = []; const stats = createCollectionStats(SOURCE_SYMBOL_COLLECTIONS.ceo); const findOptions: SourceSymbolFindOptions = { @@ -1932,59 +1877,11 @@ export async function readCeoSymbols( stats.skips[adapted.skipReason] += 1; return; } - const rawSymbol = - isPlainRecord(doc) && typeof doc.symbol === 'string' - ? doc.symbol.trim().toUpperCase() - : null; - const expectedMic = expectedMicFromCeoSymbolSuffix(rawSymbol); - rawEntries.push({ - tickerSource: adapted.tickerSource, - rawSymbolKey: rawSymbol !== null && rawSymbol.length > 0 ? rawSymbol : null, - matchesSuffixMic: expectedMic !== null && adapted.tickerSource.mic === expectedMic, - }); + tickerSources.push(adapted.tickerSource); + stats.emitted += 1; } ); - // Deduplicate crawl artifacts where the exact same (ceoId, symbol) was ingested under - // multiple Canadian exchange lists (e.g. ACB.TO under both TSX and CNQ). Prefer the row - // whose mapped MIC matches the symbol's own Canadian venue suffix (.TO/.V/.CN/.NEO). - // Distinct symbols sharing a ceoId are preserved so Stage B still flags true collisions. - const groupedByIdAndSymbol = new Map(); - for (const entry of rawEntries) { - if (entry.rawSymbolKey === null) { - tickerSources.push(entry.tickerSource); - stats.emitted += 1; - continue; - } - const key = `${entry.tickerSource.sourceId}\u0000${entry.rawSymbolKey}`; - const existing = groupedByIdAndSymbol.get(key); - if (existing !== undefined) { - existing.push(entry); - } else { - groupedByIdAndSymbol.set(key, [entry]); - } - } - - for (const entries of groupedByIdAndSymbol.values()) { - const first = entries[0]; - if (first === undefined) { - continue; - } - if (entries.length === 1) { - tickerSources.push(first.tickerSource); - stats.emitted += 1; - continue; - } - const suffixMatched = entries.filter(e => e.matchesSuffixMic); - const chosen = - suffixMatched.length === 1 && suffixMatched[0] !== undefined - ? suffixMatched[0] - : ([...entries].sort((a, b) => compareTickerSources(a.tickerSource, b.tickerSource))[0] ?? - first); - tickerSources.push(chosen.tickerSource); - stats.emitted += 1; - } - tickerSources.sort(compareTickerSources); return { tickerSources, stats }; diff --git a/apps/stock/data-pipeline/test/export-raw-bson-qa.test.ts b/apps/stock/data-pipeline/test/export-raw-bson-qa.test.ts deleted file mode 100644 index ce74b95f..00000000 --- a/apps/stock/data-pipeline/test/export-raw-bson-qa.test.ts +++ /dev/null @@ -1,293 +0,0 @@ -import { describe, expect, mock, test } from 'bun:test'; -import { createHash } from 'node:crypto'; -import { mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import { BSON } from 'mongodb'; -import { - createReadOnlyMongoRawBsonSource, - exportRawBsonCollection, - RawBsonExportError, - validateRawBsonFrame, - walkRawBsonFrames, - type ExportRawBsonFsHooks, - type ReadOnlyMongoRawBsonClient, - type ReadOnlyRawBsonSource, -} from '../src/security-master/export-raw-bson'; -import { runExportRawBson } from '../src/security-master/run-export-raw-bson'; - -function sha256Hex(bytes: Uint8Array): string { - return createHash('sha256').update(bytes).digest('hex'); -} - -function concatBytes(chunks: readonly Uint8Array[]): Uint8Array { - const out = new Uint8Array(chunks.reduce((acc, c) => acc + c.byteLength, 0)); - let offset = 0; - for (const chunk of chunks) { - out.set(chunk, offset); - offset += chunk.byteLength; - } - return out; -} - -function sourceOf(docs: readonly unknown[], onYield?: () => void): ReadOnlyRawBsonSource { - return { - isReadOnly: () => true, - find: () => ({ - async *[Symbol.asyncIterator]() { - for (const doc of docs) { - onYield?.(); - yield doc; - } - }, - }), - }; -} - -async function withTempDir(fn: (dir: string) => Promise): Promise { - const dir = await mkdtemp(join(tmpdir(), 'export-raw-bson-qa-')); - try { - return await fn(dir); - } finally { - await rm(dir, { recursive: true, force: true }); - } -} - -/** - * The mongodb 6.x driver returns `raw: true` documents as `subarray` views into the shared - * wire-reply buffer (`OnDemandDocument.toBytes`), so frames have non-zero `byteOffset` and - * neighbouring bytes belong to other documents / reply headers. - */ -function packAsReplyViews(docs: readonly Uint8Array[]): Uint8Array[] { - const junk = new Uint8Array([0xde, 0xad, 0xbe, 0xef, 0x07]); - const reply = concatBytes(docs.flatMap(d => [junk, d]).concat([junk])); - const views: Uint8Array[] = []; - let offset = 0; - for (const doc of docs) { - offset += junk.byteLength; - views.push(Buffer.from(reply.buffer, reply.byteOffset + offset, doc.byteLength)); - offset += doc.byteLength; - } - return views; -} - -describe('exportRawBsonCollection (QA edge cases)', () => { - test('writes only the frame bytes when raw documents are offset views into a shared reply buffer (buffered and direct-write paths, real fs)', async () => { - const small = Array.from({ length: 40 }, (_, i) => - Uint8Array.from(BSON.serialize({ eodSearchCode: `S${i}.US`, close: i + 0.5 })) - ); - const large = Uint8Array.from(BSON.serialize({ eodSearchCode: 'BIG.US', pad: 'z'.repeat(300) })); - const originals = [...small.slice(0, 20), large, ...small.slice(20)]; - const views = packAsReplyViews(originals); - expect(views.every(v => v.byteOffset > 0)).toBe(true); - const expected = concatBytes(originals); - - await withTempDir(async outDir => { - const result = await exportRawBsonCollection(sourceOf(views), { - collection: 'eodPrices', - outDir, - writeBufferBytes: 128, - }); - - const fileBytes = Uint8Array.from(await readFile(result.outPath)); - expect(fileBytes).toEqual(expected); - expect(result.sha256).toBe(sha256Hex(expected)); - expect(result.docsWritten).toBe(originals.length); - expect(walkRawBsonFrames(fileBytes).map(f => BSON.deserialize(f))).toEqual( - originals.map(o => BSON.deserialize(o)) - ); - }); - }); - - test('flushes correctly when frames exactly fill the write buffer', async () => { - const doc = Uint8Array.from(BSON.serialize({ k: 'v' })); - const writeBufferBytes = Math.max(64, doc.byteLength * 4); - const perBuffer = Math.floor(writeBufferBytes / doc.byteLength); - const docs = Array.from({ length: perBuffer * 3 }, () => doc); - const writes: number[] = []; - - await withTempDir(async outDir => { - const fsHooks: ExportRawBsonFsHooks = { - open: async () => ({ - write: async (_b, _o, len) => { - writes.push(len ?? 0); - return { bytesWritten: len ?? 0 }; - }, - sync: async () => {}, - close: async () => {}, - }), - rename: async () => {}, - unlink: async () => {}, - }; - const result = await exportRawBsonCollection(sourceOf(docs), { - collection: 'qmEarnings', - outDir, - writeBufferBytes, - fs: fsHooks, - }); - expect(result.bytesWritten).toBe(doc.byteLength * docs.length); - expect(writes.reduce((a, b) => a + b, 0)).toBe(result.bytesWritten); - expect(writes.every(w => w <= writeBufferBytes)).toBe(true); - expect(writes).toHaveLength(3); - }); - }); - - test('completes partial writes by continuing from the reported offset', async () => { - const docs = Array.from({ length: 10 }, (_, i) => Uint8Array.from(BSON.serialize({ i }))); - const expected = concatBytes(docs); - const received: Uint8Array[] = []; - - await withTempDir(async outDir => { - const fsHooks: ExportRawBsonFsHooks = { - open: async () => ({ - write: async (buf, off, len) => { - const start = off ?? 0; - const n = Math.min(len ?? 0, 7); - received.push(Uint8Array.from(buf.subarray(start, start + n))); - return { bytesWritten: n }; - }, - sync: async () => {}, - close: async () => {}, - }), - rename: async () => {}, - unlink: async () => {}, - }; - const result = await exportRawBsonCollection(sourceOf(docs), { - collection: 'qmSplits', - outDir, - writeBufferBytes: 64, - fs: fsHooks, - }); - expect(concatBytes(received)).toEqual(expected); - expect(result.sha256).toBe(sha256Hex(expected)); - }); - }); - - test('stops pulling from the source once limit is reached', async () => { - const docs = Array.from({ length: 50 }, (_, i) => Uint8Array.from(BSON.serialize({ i }))); - let pulled = 0; - await withTempDir(async outDir => { - const result = await exportRawBsonCollection( - sourceOf(docs, () => { - pulled += 1; - }), - { collection: 'eodPrices', outDir, limit: 3 } - ); - expect(result.docsWritten).toBe(3); - expect(pulled).toBe(3); - expect(Uint8Array.from(await readFile(result.outPath))).toEqual(concatBytes(docs.slice(0, 3))); - }); - }); - - test('creates a missing nested out-dir and leaves no temp files after success', async () => { - await withTempDir(async root => { - const outDir = join(root, 'a', 'b'); - const doc = Uint8Array.from(BSON.serialize({ x: 1 })); - const result = await exportRawBsonCollection(sourceOf([doc]), { collection: 'qmFilings', outDir }); - expect(await readdir(outDir)).toEqual(['qmFilings.bson']); - expect(result.outPath).toBe(join(outDir, 'qmFilings.bson')); - }); - }); - - test('rejects frames whose length prefix has the sign bit set (negative int32)', () => { - const frame = new Uint8Array([0xff, 0xff, 0xff, 0xff, 0x00]); - expect(() => validateRawBsonFrame(frame, 'eodPrices', 7)).toThrow(RawBsonExportError); - expect(() => walkRawBsonFrames(frame)).toThrow(/corrupt BSON document length -1/); - }); - - test('walkRawBsonFrames rejects truncated trailing bytes like curate-etl iter_raw_bson_docs', () => { - const doc = Uint8Array.from(BSON.serialize({ a: 1 })); - expect(() => walkRawBsonFrames(concatBytes([doc, new Uint8Array([1, 2])]))).toThrow( - /truncated BSON length prefix/ - ); - expect(() => walkRawBsonFrames(concatBytes([doc, doc.subarray(0, doc.byteLength - 1)]))).toThrow( - /truncated BSON document/ - ); - expect(walkRawBsonFrames(new Uint8Array())).toEqual([]); - }); - - test('rejects out-of-range writeBufferBytes, batchSize and limit before any fs or source call', async () => { - const openMock = mock(async () => { - throw new Error('open must not be called'); - }); - const findMock = mock(() => { - throw new Error('find must not be called'); - }); - const source: ReadOnlyRawBsonSource = { isReadOnly: () => true, find: findMock }; - const bad = [ - { writeBufferBytes: 63 }, - { writeBufferBytes: 64 * 1024 * 1024 + 1 }, - { writeBufferBytes: 100.5 }, - { batchSize: 0 }, - { batchSize: 100_001 }, - { limit: 0 }, - { limit: -1 }, - { maxDocBytes: 4 }, - { eodSymbol: ' ' }, - ]; - for (const opts of bad) { - await expect( - exportRawBsonCollection(source, { collection: 'eodPrices', outDir: '/tmp/unused', fs: { open: openMock }, ...opts }) - ).rejects.toMatchObject({ code: 'INVALID_OPTION' }); - } - await expect( - exportRawBsonCollection(source, { collection: 'eodPrices', outDir: ' ', fs: { open: openMock } }) - ).rejects.toMatchObject({ code: 'INVALID_OPTION' }); - expect(openMock).not.toHaveBeenCalled(); - expect(findMock).not.toHaveBeenCalled(); - }); -}); - -describe('runExportRawBson multi-collection (QA edge cases)', () => { - test('a failure in a later collection keeps earlier published files, preserves that collection\'s previous output, and closes the client once', async () => { - await withTempDir(async outDir => { - const splitsDoc = Uint8Array.from(BSON.serialize({ split: '2:1' })); - const previousDividends = Uint8Array.from(BSON.serialize({ previous: true })); - await writeFile(join(outDir, 'qmDividends.bson'), previousDividends); - const closeMongo = mock(async () => {}); - const findCalls: string[] = []; - - const client: ReadOnlyMongoRawBsonClient = { - isReadOnly: () => true, - getCollection: name => ({ - find: () => { - findCalls.push(name); - return { - async *[Symbol.asyncIterator]() { - if (name === 'qmSplits') { - yield splitsDoc; - return; - } - yield new Uint8Array([9, 0, 0, 0, 0]); - }, - }; - }, - }), - }; - - await expect( - runExportRawBson( - { createMongoClient: () => ({ client, close: closeMongo }), writeStdout: () => {} }, - { outDir, collections: ['qmSplits', 'qmDividends', 'qmEarnings'] } - ) - ).rejects.toMatchObject({ code: 'INVALID_BSON_FRAME', collection: 'qmDividends', docOrdinal: 0 }); - - expect(findCalls).toEqual(['qmSplits', 'qmDividends']); - expect(closeMongo).toHaveBeenCalledTimes(1); - expect((await readdir(outDir)).sort()).toEqual(['qmDividends.bson', 'qmSplits.bson']); - expect(Uint8Array.from(await readFile(join(outDir, 'qmSplits.bson')))).toEqual(splitsDoc); - expect(Uint8Array.from(await readFile(join(outDir, 'qmDividends.bson')))).toEqual(previousDividends); - }); - }); - - test('createReadOnlyMongoRawBsonSource re-checks read-only mode at find time', () => { - let readOnly = true; - const getCollection = mock(() => ({ - find: () => ({ async *[Symbol.asyncIterator]() {} }), - })); - const source = createReadOnlyMongoRawBsonSource({ isReadOnly: () => readOnly, getCollection }); - readOnly = false; - expect(() => source.find('eodPrices', {}, { raw: true })).toThrow(RawBsonExportError); - expect(getCollection).not.toHaveBeenCalled(); - }); -}); diff --git a/apps/stock/data-pipeline/test/export-raw-bson.test.ts b/apps/stock/data-pipeline/test/export-raw-bson.test.ts deleted file mode 100644 index e1fc3b59..00000000 --- a/apps/stock/data-pipeline/test/export-raw-bson.test.ts +++ /dev/null @@ -1,667 +0,0 @@ -import { describe, expect, mock, test } from 'bun:test'; -import { createHash } from 'node:crypto'; -import { mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import { BSON } from 'mongodb'; -import { - createReadOnlyMongoRawBsonSource, - exportRawBsonCollection, - RAW_BSON_EXPORT_COLLECTIONS, - RawBsonExportError, - validateRawBsonFrame, - walkRawBsonFrames, - type ExportRawBsonFileHandle, - type ExportRawBsonFsHooks, - type RawBsonFindOptions, - type ReadOnlyMongoRawBsonClient, - type ReadOnlyRawBsonSource, -} from '../src/security-master/export-raw-bson'; - -const EMPTY_SHA256 = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'; - -function sha256Hex(bytes: Uint8Array): string { - return createHash('sha256').update(bytes).digest('hex'); -} - -function concatBytes(chunks: readonly Uint8Array[]): Uint8Array { - const total = chunks.reduce((acc, c) => acc + c.byteLength, 0); - const out = new Uint8Array(total); - let offset = 0; - for (const chunk of chunks) { - out.set(chunk, offset); - offset += chunk.byteLength; - } - return out; -} - -function createFakeSource( - docs: readonly unknown[], - options: { - readOnly?: boolean; - errorAfter?: number; - error?: Error; - onFind?: (collection: string, filter: Record, findOpts: RawBsonFindOptions) => void; - onCursorClose?: () => void; - } = {} -): ReadOnlyRawBsonSource { - const readOnly = options.readOnly ?? true; - return { - isReadOnly: () => readOnly, - find(collection, filter, findOpts) { - options.onFind?.(collection, filter, findOpts); - return { - async *[Symbol.asyncIterator]() { - let index = 0; - try { - for (const doc of docs) { - if (options.errorAfter !== undefined && index === options.errorAfter) { - throw options.error ?? new Error('Simulated mid-stream cursor failure'); - } - yield doc; - index += 1; - } - } finally { - options.onCursorClose?.(); - } - }, - }; - }, - }; -} - -async function withTempDir(fn: (dir: string) => Promise): Promise { - const dir = await mkdtemp(join(tmpdir(), 'export-raw-bson-test-')); - try { - return await fn(dir); - } finally { - await rm(dir, { recursive: true, force: true }); - } -} - -describe('exportRawBsonCollection', () => { - test('streams raw BSON frames verbatim, matches concatenation, round-trips via 4-byte LE framing, and is deterministic', async () => { - const originalDocs = [ - { - eodSearchCode: 'AAPL.US', - date: '2025-01-02', - open: 248.93, - high: 249.1, - low: 241.82, - close: 243.85, - volume: 55740731, - ts: new Date('2025-01-02T21:00:00.000Z'), - meta: { exchange: 'US', adjusted: false }, - }, - { - eodSearchCode: 'RY.TO', - date: '2025-01-02', - open: 173.4, - high: 175.0, - low: 172.8, - close: 174.65, - volume: 2150000, - tags: ['CA', 'TSX'], - }, - { - eodSearchCode: 'NVDA.US', - date: '2024-06-10', - open: 120.37, - high: 123.1, - low: 117.01, - close: 121.79, - volume: 314162700, - }, - ]; - const serialized = originalDocs.map(doc => Uint8Array.from(BSON.serialize(doc))); - const expectedBytes = concatBytes(serialized); - const expectedSha = sha256Hex(expectedBytes); - - await withTempDir(async outDir => { - const findCalls: Array<{ - collection: string; - filter: Record; - options: RawBsonFindOptions; - }> = []; - const source = createFakeSource(serialized, { - onFind: (collection, filter, options) => { - findCalls.push({ collection, filter, options }); - }, - }); - - const run1 = await exportRawBsonCollection(source, { - collection: 'eodPrices', - outDir, - }); - - expect(run1.collection).toBe('eodPrices'); - expect(run1.outPath).toBe(join(outDir, 'eodPrices.bson')); - expect(run1.docsWritten).toBe(originalDocs.length); - expect(run1.bytesWritten).toBe(expectedBytes.byteLength); - expect(run1.elapsedMs).toBeGreaterThanOrEqual(0); - expect(run1.sha256).toBe(expectedSha); - expect(run1.filter).toEqual({}); - expect(findCalls).toEqual([ - { - collection: 'eodPrices', - filter: {}, - options: { raw: true, batchSize: 4096 }, - }, - ]); - - const fileBytes = Uint8Array.from(await readFile(run1.outPath)); - expect(fileBytes).toEqual(expectedBytes); - - // Cross-language framing parity: walk output by 4-byte LE length prefix - const walked = walkRawBsonFrames(fileBytes); - expect(walked).toHaveLength(originalDocs.length); - for (let i = 0; i < originalDocs.length; i++) { - const frame = walked[i]; - expect(frame).toEqual(serialized[i]); - expect(BSON.deserialize(frame!)).toEqual(originalDocs[i]); - } - - // Determinism / replay invariant: running twice yields byte-identical output and sha256 - const run2 = await exportRawBsonCollection(source, { - collection: 'eodPrices', - outDir, - }); - const fileBytes2 = Uint8Array.from(await readFile(run2.outPath)); - expect(run2.sha256).toBe(run1.sha256); - expect(run2.bytesWritten).toBe(run1.bytesWritten); - expect(fileBytes2).toEqual(fileBytes); - expect(await readdir(outDir)).toEqual(['eodPrices.bson']); - }); - }); - - test('publishes a 0-byte file with docsWritten === 0 and empty SHA-256 for an empty collection', async () => { - await withTempDir(async outDir => { - const source = createFakeSource([]); - const result = await exportRawBsonCollection(source, { - collection: 'ceoShorts', - outDir, - }); - - expect(result.collection).toBe('ceoShorts'); - expect(result.docsWritten).toBe(0); - expect(result.bytesWritten).toBe(0); - expect(result.sha256).toBe(EMPTY_SHA256); - - const fileBytes = await readFile(result.outPath); - expect(fileBytes.byteLength).toBe(0); - expect(await readdir(outDir)).toEqual(['ceoShorts.bson']); - }); - }); - - test('rejects invalid BSON frames with typed error naming collection and ordinal, cleans temp file, and preserves existing output', async () => { - const validDoc = Uint8Array.from(BSON.serialize({ a: 1 })); - const shortFrame = new Uint8Array([4, 0, 0, 0]); - const tooSmallPrefix = Uint8Array.from(validDoc); - tooSmallPrefix[0] = (tooSmallPrefix[0] ?? 0) - 1; - const tooLargePrefix = Uint8Array.from(validDoc); - tooLargePrefix[0] = (tooLargePrefix[0] ?? 0) + 1; - const missingTerminator = Uint8Array.from(validDoc); - missingTerminator[missingTerminator.byteLength - 1] = 0x01; - const oversizedDoc = Uint8Array.from(BSON.serialize({ payload: 'x'.repeat(200) })); - - const cases: Array<{ - name: string; - docs: unknown[]; - expectedOrdinal: number; - maxDocBytes?: number; - }> = [ - { name: 'shorter than 5 bytes', docs: [validDoc, shortFrame], expectedOrdinal: 1 }, - { name: 'LE prefix smaller than byteLength', docs: [validDoc, tooSmallPrefix], expectedOrdinal: 1 }, - { name: 'LE prefix larger than byteLength', docs: [tooLargePrefix], expectedOrdinal: 0 }, - { name: 'missing trailing 0x00', docs: [validDoc, validDoc, missingTerminator], expectedOrdinal: 2 }, - { name: 'non-Uint8Array chunk', docs: [validDoc, { plain: 'object' }], expectedOrdinal: 1 }, - { - name: 'exceeds maxDocBytes', - docs: [validDoc, oversizedDoc], - expectedOrdinal: 1, - maxDocBytes: 64, - }, - ]; - - for (const c of cases) { - await withTempDir(async outDir => { - const existingPath = join(outDir, 'qmSplits.bson'); - const sentinel = Uint8Array.from(BSON.serialize({ sentinel: c.name })); - await writeFile(existingPath, sentinel); - - const source = createFakeSource(c.docs); - let caught: unknown; - try { - await exportRawBsonCollection(source, { - collection: 'qmSplits', - outDir, - maxDocBytes: c.maxDocBytes, - }); - } catch (err) { - caught = err; - } - - expect(caught).toBeInstanceOf(RawBsonExportError); - const typed = caught as RawBsonExportError; - expect(typed.code).toBe('INVALID_BSON_FRAME'); - expect(typed.collection).toBe('qmSplits'); - expect(typed.docOrdinal).toBe(c.expectedOrdinal); - expect(typed.message).toContain('qmSplits'); - expect(typed.message).toContain(`doc#${c.expectedOrdinal}`); - - // No temp file left behind and pre-existing output is byte-identical - expect(await readdir(outDir)).toEqual(['qmSplits.bson']); - expect(Uint8Array.from(await readFile(existingPath))).toEqual(sentinel); - }); - } - }); - - test('cleans up temp file, closes cursor/handle, and preserves existing output on mid-stream cursor, write, short-write, fsync, and rename errors', async () => { - const docs = [ - Uint8Array.from(BSON.serialize({ seq: 0 })), - Uint8Array.from(BSON.serialize({ seq: 1 })), - Uint8Array.from(BSON.serialize({ seq: 2 })), - ]; - - // 1. Mid-stream cursor error - await withTempDir(async outDir => { - const existingPath = join(outDir, 'qmDividends.bson'); - const sentinel = Uint8Array.from(BSON.serialize({ sentinel: 'cursor-err' })); - await writeFile(existingPath, sentinel); - - let cursorClosed = false; - const source = createFakeSource(docs, { - errorAfter: 2, - error: new Error('Cursor network reset'), - onCursorClose: () => { - cursorClosed = true; - }, - }); - - await expect( - exportRawBsonCollection(source, { collection: 'qmDividends', outDir }) - ).rejects.toThrow('Cursor network reset'); - - expect(cursorClosed).toBe(true); - expect(await readdir(outDir)).toEqual(['qmDividends.bson']); - expect(Uint8Array.from(await readFile(existingPath))).toEqual(sentinel); - }); - - // 2. Write, short-write, fsync, and rename errors - const failureModes = ['write', 'shortWrite', 'sync', 'rename'] as const; - for (const mode of failureModes) { - await withTempDir(async outDir => { - const existingPath = join(outDir, 'qmPrices.bson'); - const sentinel = Uint8Array.from(BSON.serialize({ sentinel: mode })); - await writeFile(existingPath, sentinel); - - let handleClosed = false; - let tempFileCreated: string | null = null; - let unlinkedPath: string | null = null; - - const fsHooks: ExportRawBsonFsHooks = { - open: async (filePath: string) => { - tempFileCreated = filePath; - await writeFile(filePath, new Uint8Array()); - const handle: ExportRawBsonFileHandle = { - write: async (_buf, _off, len) => { - if (mode === 'write') { - throw new Error('ENOSPC simulated write failure'); - } - if (mode === 'shortWrite') { - return { bytesWritten: 0 }; - } - return { bytesWritten: len ?? 0 }; - }, - sync: async () => { - if (mode === 'sync') { - throw new Error('EIO simulated fsync failure'); - } - }, - close: async () => { - handleClosed = true; - }, - }; - return handle; - }, - rename: async () => { - if (mode === 'rename') { - throw new Error('EXDEV simulated rename failure'); - } - }, - unlink: async filePath => { - unlinkedPath = String(filePath); - await rm(filePath, { force: true }); - }, - }; - - const source = createFakeSource(docs); - await expect( - exportRawBsonCollection(source, { - collection: 'qmPrices', - outDir, - fs: fsHooks, - }) - ).rejects.toThrow(); - - expect(handleClosed).toBe(true); - expect(tempFileCreated).not.toBeNull(); - expect(unlinkedPath).toBe(tempFileCreated); - expect(await readdir(outDir)).toEqual(['qmPrices.bson']); - expect(Uint8Array.from(await readFile(existingPath))).toEqual(sentinel); - }); - } - }); - - test('enforces bounded write buffer size, handles oversized single docs, and strictly awaits write backpressure', async () => { - const smallDocs = Array.from({ length: 120 }, (_, i) => - Uint8Array.from( - BSON.serialize({ - eodSearchCode: `SYM${String(i).padStart(4, '0')}.US`, - date: '2025-01-02', - open: 10 + i, - close: 11 + i, - volume: 1000 + i, - }) - ) - ); - const largeDoc = Uint8Array.from( - BSON.serialize({ - eodSearchCode: 'LARGE.US', - payload: 'A'.repeat(350), - }) - ); - const allDocs = [...smallDocs.slice(0, 60), largeDoc, ...smallDocs.slice(60)]; - const expectedConcat = concatBytes(allDocs); - const writeBufferBytes = 256; - - expect(largeDoc.byteLength).toBeGreaterThan(writeBufferBytes); - - const writeLengths: number[] = []; - const writtenChunks: Uint8Array[] = []; - let inFlight = 0; - let maxInFlight = 0; - - await withTempDir(async outDir => { - const fsHooks: ExportRawBsonFsHooks = { - open: async () => ({ - write: async (buf, offset, length) => { - inFlight += 1; - if (inFlight > maxInFlight) { - maxInFlight = inFlight; - } - const start = offset ?? 0; - const len = length ?? buf.byteLength - start; - writeLengths.push(len); - // Copy slice immediately to simulate kernel read of buffer before async completion - const copy = Uint8Array.from(buf.subarray(start, start + len)); - await new Promise(resolve => setTimeout(resolve, 0)); - writtenChunks.push(copy); - inFlight -= 1; - return { bytesWritten: len }; - }, - sync: async () => {}, - close: async () => {}, - }), - rename: async () => {}, - unlink: async () => {}, - }; - - const source = createFakeSource(allDocs); - const result = await exportRawBsonCollection(source, { - collection: 'eodPrices', - outDir, - writeBufferBytes, - fs: fsHooks, - }); - - expect(maxInFlight).toBe(1); - expect(writeLengths.length).toBeGreaterThan(10); - - // Every write must be <= writeBufferBytes except the single oversized document write - const oversizedWrites = writeLengths.filter(len => len > writeBufferBytes); - expect(oversizedWrites).toEqual([largeDoc.byteLength]); - for (const len of writeLengths) { - expect(len).toBeLessThanOrEqual(Math.max(writeBufferBytes, largeDoc.byteLength)); - } - - const assembled = concatBytes(writtenChunks); - expect(assembled).toEqual(expectedConcat); - expect(result.docsWritten).toBe(allDocs.length); - expect(result.bytesWritten).toBe(expectedConcat.byteLength); - expect(result.sha256).toBe(sha256Hex(expectedConcat)); - }); - }); - - test('rejects disallowed collections, invalid filters, and non-read-only sources before any source or fs call', async () => { - const findMock = mock(() => { - throw new Error('source.find should never be called'); - }); - const openMock = mock(async () => { - throw new Error('fs.open should never be called'); - }); - const source: ReadOnlyRawBsonSource = { - isReadOnly: () => true, - find: findMock, - }; - const fsHooks: ExportRawBsonFsHooks = { open: openMock }; - - for (const disallowed of ['eodIntraday1M', 'qmIntraday', 'qmFinancials', 'ceoPosts', 'symbols']) { - await expect( - exportRawBsonCollection(source, { collection: disallowed, outDir: '/tmp/unused', fs: fsHooks }) - ).rejects.toMatchObject({ code: 'DISALLOWED_COLLECTION', collection: disallowed }); - } - - await expect( - exportRawBsonCollection(source, { - collection: 'teMarketData', - outDir: '/tmp/unused', - eodSymbol: 'CAD.FOREX', - fs: fsHooks, - }) - ).rejects.toMatchObject({ code: 'INVALID_OPTION' }); - - await expect( - exportRawBsonCollection(source, { - collection: 'eodPrices', - outDir: '/tmp/unused', - teSymbol: 'USDCAD', - fs: fsHooks, - }) - ).rejects.toMatchObject({ code: 'INVALID_OPTION' }); - - const writableSource: ReadOnlyRawBsonSource = { - isReadOnly: () => false, - find: findMock, - }; - await expect( - exportRawBsonCollection(writableSource, { - collection: 'eodPrices', - outDir: '/tmp/unused', - fs: fsHooks, - }) - ).rejects.toMatchObject({ code: 'INVALID_SOURCE' }); - - expect(findMock).not.toHaveBeenCalled(); - expect(openMock).not.toHaveBeenCalled(); - }); - - test('applies eodSymbol, teSymbol, and limit filters and defensively caps output at limit', async () => { - const docs = Array.from({ length: 5 }, (_, i) => - Uint8Array.from(BSON.serialize({ seq: i })) - ); - - await withTempDir(async outDir => { - const calls: Array<{ collection: string; filter: Record; options: RawBsonFindOptions }> = []; - const source = createFakeSource(docs, { - onFind: (collection, filter, options) => { - calls.push({ collection, filter, options }); - }, - }); - - const eodRes = await exportRawBsonCollection(source, { - collection: 'eodPrices', - outDir, - eodSymbol: 'CAD.FOREX', - limit: 2, - batchSize: 64, - }); - - expect(eodRes.docsWritten).toBe(2); - expect(eodRes.filter).toEqual({ eodSearchCode: 'CAD.FOREX' }); - expect(calls[0]).toEqual({ - collection: 'eodPrices', - filter: { eodSearchCode: 'CAD.FOREX' }, - options: { raw: true, batchSize: 64, limit: 2 }, - }); - - const teRes = await exportRawBsonCollection(source, { - collection: 'teMarketData', - outDir, - teSymbol: 'USDCAD', - limit: 3, - }); - - expect(teRes.docsWritten).toBe(3); - expect(teRes.filter).toEqual({ teSymbol: 'USDCAD' }); - expect(calls[1]).toEqual({ - collection: 'teMarketData', - filter: { teSymbol: 'USDCAD' }, - options: { raw: true, batchSize: 4096, limit: 3 }, - }); - }); - }); - - test('createReadOnlyMongoRawBsonSource enforces read-only, rejects buffered arrays, and always closes cursors', async () => { - const writableClient: ReadOnlyMongoRawBsonClient = { - isReadOnly: () => false, - getCollection: () => { - throw new Error('should not be called'); - }, - }; - expect(() => createReadOnlyMongoRawBsonSource(writableClient)).toThrow(RawBsonExportError); - - const bufferedArrayClient: ReadOnlyMongoRawBsonClient = { - isReadOnly: () => true, - getCollection: () => ({ - find: () => [] as unknown as ReturnType extends { - find: (...args: never[]) => infer R; - } - ? R - : never, - }), - }; - const badSource = createReadOnlyMongoRawBsonSource(bufferedArrayClient); - expect(() => badSource.find('eodPrices', {}, { raw: true })).toThrow(RawBsonExportError); - - // Cursor close is called on normal exhaustion and early break - const closeMock = mock(async () => {}); - const docs = [ - Uint8Array.from(BSON.serialize({ a: 1 })), - Uint8Array.from(BSON.serialize({ a: 2 })), - Uint8Array.from(BSON.serialize({ a: 3 })), - ]; - const goodClient: ReadOnlyMongoRawBsonClient = { - isReadOnly: () => true, - getCollection: () => ({ - find: () => ({ - close: closeMock, - async *[Symbol.asyncIterator]() { - for (const d of docs) { - yield d; - } - }, - }), - }), - }; - const source = createReadOnlyMongoRawBsonSource(goodClient); - - await withTempDir(async outDir => { - const res = await exportRawBsonCollection(source, { - collection: 'qmFilings', - outDir, - limit: 1, - }); - expect(res.docsWritten).toBe(1); - expect(closeMock).toHaveBeenCalledTimes(1); - }); - - // Limited export with rejecting cursor.close() must surface the close error, - // clean up the temp file, and leave any pre-existing output file byte-identical. - const rejectingCloseClient: ReadOnlyMongoRawBsonClient = { - isReadOnly: () => true, - getCollection: () => ({ - find: () => ({ - close: async () => { - throw new Error('Cursor close rejected after limit break'); - }, - async *[Symbol.asyncIterator]() { - for (const d of docs) { - yield d; - } - }, - }), - }), - }; - const rejectingSource = createReadOnlyMongoRawBsonSource(rejectingCloseClient); - - await withTempDir(async outDir => { - const existingPath = join(outDir, 'qmFilings.bson'); - const sentinel = Uint8Array.from(BSON.serialize({ sentinel: 'preserve-on-close-error' })); - await writeFile(existingPath, sentinel); - - await expect( - exportRawBsonCollection(rejectingSource, { - collection: 'qmFilings', - outDir, - limit: 1, - }) - ).rejects.toThrow('Cursor close rejected after limit break'); - - expect(await readdir(outDir)).toEqual(['qmFilings.bson']); - expect(Uint8Array.from(await readFile(existingPath))).toEqual(sentinel); - }); - - // When iteration itself fails AND cursor.close() rejects, the primary iteration error wins. - const dualFailureClient: ReadOnlyMongoRawBsonClient = { - isReadOnly: () => true, - getCollection: () => ({ - find: () => ({ - close: async () => { - throw new Error('Secondary cursor close failure'); - }, - async *[Symbol.asyncIterator]() { - yield docs[0]; - throw new Error('Primary cursor iteration failure'); - }, - }), - }), - }; - const dualFailureSource = createReadOnlyMongoRawBsonSource(dualFailureClient); - - await withTempDir(async outDir => { - await expect( - exportRawBsonCollection(dualFailureSource, { - collection: 'qmFilings', - outDir, - }) - ).rejects.toThrow('Primary cursor iteration failure'); - expect(await readdir(outDir)).toEqual([]); - }); - }); - - test('exports exact M1 allowlist of 8 collections and validateRawBsonFrame accepts minimal 5-byte empty BSON doc', () => { - expect([...RAW_BSON_EXPORT_COLLECTIONS]).toEqual([ - 'eodPrices', - 'qmSplits', - 'qmDividends', - 'qmPrices', - 'teMarketData', - 'ceoShorts', - 'qmFilings', - 'qmEarnings', - ]); - const emptyBson = new Uint8Array([5, 0, 0, 0, 0]); - expect(validateRawBsonFrame(emptyBson, 'eodPrices', 0)).toBe(emptyBson); - }); -}); diff --git a/apps/stock/data-pipeline/test/run-export-raw-bson.test.ts b/apps/stock/data-pipeline/test/run-export-raw-bson.test.ts deleted file mode 100644 index a0c6ab21..00000000 --- a/apps/stock/data-pipeline/test/run-export-raw-bson.test.ts +++ /dev/null @@ -1,399 +0,0 @@ -import { describe, expect, mock, test } from 'bun:test'; -import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import type { StockAppConfig } from '@stock-bot/stock-config'; -import { BSON } from 'mongodb'; -import { - DEFAULT_RAW_BSON_BATCH_SIZE, - RAW_BSON_EXPORT_COLLECTIONS, - RawBsonExportError, - type ReadOnlyMongoRawBsonClient, -} from '../src/security-master/export-raw-bson'; -import { - assertExportRawBsonSafety, - EXPORT_RAW_BSON_USAGE, - parseExportRawBsonArgs, - runCli, - runExportRawBson, -} from '../src/security-master/run-export-raw-bson'; - -function createBaseConfig(overrides: Partial = {}): StockAppConfig { - return { - environment: 'development', - database: { - postgres: { - enabled: true, - host: 'localhost', - port: 5432, - database: 'trading_bot', - user: 'trading_user', - password: 'pw', - ssl: false, - poolSize: 5, - idleTimeout: 10000, - connectionTimeout: 5000, - }, - mongodb: { - enabled: true, - uri: 'mongodb://studio_stock_bot_read:pw@localhost:27017/stock?authSource=stock', - readUri: 'mongodb://studio_stock_bot_read:pw@localhost:27017/stock?authSource=stock', - readOnly: true, - host: 'localhost', - port: 27017, - database: 'stock', - poolSize: 5, - ...overrides, - }, - dragonfly: { - enabled: false, - host: 'localhost', - port: 6380, - }, - questdb: { - enabled: false, - host: 'localhost', - port: 9100, - }, - }, - } as unknown as StockAppConfig; -} - -describe('parseExportRawBsonArgs', () => { - test('parses valid flags in both space-separated and equals forms', () => { - const parsed1 = parseExportRawBsonArgs([ - '--out-dir', - './tmp/bson', - '--collections', - 'eodPrices', - '--eod-symbol', - 'CAD.FOREX', - '--limit', - '100', - '--batch-size', - '512', - ]); - expect(parsed1).toEqual({ - help: false, - outDir: './tmp/bson', - collections: ['eodPrices'], - eodSymbol: 'CAD.FOREX', - limit: 100, - batchSize: 512, - }); - - const parsed2 = parseExportRawBsonArgs([ - '--out-dir=./tmp/te', - '--collections=teMarketData', - '--te-symbol=USDCAD', - ]); - expect(parsed2).toEqual({ - help: false, - outDir: './tmp/te', - collections: ['teMarketData'], - teSymbol: 'USDCAD', - batchSize: DEFAULT_RAW_BSON_BATCH_SIZE, - }); - - const parsedDefault = parseExportRawBsonArgs(['--out-dir', './tmp/all']); - expect(parsedDefault).toEqual({ - help: false, - outDir: './tmp/all', - collections: [...RAW_BSON_EXPORT_COLLECTIONS], - batchSize: DEFAULT_RAW_BSON_BATCH_SIZE, - }); - - expect(parseExportRawBsonArgs(['--help'])).toEqual({ help: true }); - }); - - test('rejects unknown, duplicate, missing-value, positional, and malformed flags', () => { - expect(() => parseExportRawBsonArgs([])).toThrow(/Missing required argument: --out-dir/); - expect(() => parseExportRawBsonArgs(['--out-dir', './tmp', '--bogus'])).toThrow(/Unknown argument/); - expect(() => parseExportRawBsonArgs(['--out-dir', './tmp', 'positional'])).toThrow(/Unknown argument/); - expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--out-dir', './b'])).toThrow(/Duplicate flag/); - expect(() => - parseExportRawBsonArgs(['--out-dir', './a', '--limit', '10', '--limit=20']) - ).toThrow(/Duplicate flag/); - expect(() => parseExportRawBsonArgs(['--out-dir', '--collections', 'eodPrices'])).toThrow( - /Missing value for --out-dir/ - ); - expect(() => parseExportRawBsonArgs(['--out-dir='])).toThrow(/Missing value for --out-dir/); - expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--limit', '0'])).toThrow(/Invalid --limit/); - expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--limit', '-5'])).toThrow(/Invalid --limit/); - expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--limit', '1.5'])).toThrow(/Invalid --limit/); - expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--batch-size', '0'])).toThrow( - /Invalid --batch-size/ - ); - expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--batch-size', '999999'])).toThrow( - /Invalid --batch-size/ - ); - expect(() => - parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'eodPrices,']) - ).toThrow(/Malformed --collections/); - expect(() => - parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'eodPrices,eodPrices']) - ).toThrow(/Duplicate collection/); - expect(() => parseExportRawBsonArgs(['--help', '--help'])).toThrow(/Duplicate flag: --help/); - expect(() => - parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'eodPrices', '--eod-symbol=--help']) - ).toThrow(/Invalid value for --eod-symbol/); - expect(() => - parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'eodPrices', '--eod-symbol', '--help']) - ).toThrow(/Missing value for --eod-symbol/); - expect(() => - parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'teMarketData', '--te-symbol=--limit']) - ).toThrow(/Invalid value for --te-symbol/); - expect(() => - parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'teMarketData', '--te-symbol', '--limit']) - ).toThrow(/Missing value for --te-symbol/); - }); - - test('rejects disallowed collections and mismatched --eod-symbol / --te-symbol filters', () => { - expect(() => - parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'eodIntraday1M']) - ).toThrow(RawBsonExportError); - expect(() => - parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'symbols']) - ).toThrow(RawBsonExportError); - expect(() => - parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'teMarketData', '--eod-symbol', 'CAD.FOREX']) - ).toThrow(/--eod-symbol is only permitted/); - expect(() => - parseExportRawBsonArgs([ - '--out-dir', - './a', - '--collections', - 'eodPrices,qmSplits', - '--eod-symbol', - 'CAD.FOREX', - ]) - ).toThrow(/--eod-symbol is only permitted/); - expect(() => - parseExportRawBsonArgs(['--out-dir', './a', '--eod-symbol', 'CAD.FOREX']) - ).toThrow(/--eod-symbol is only permitted/); - expect(() => - parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'eodPrices', '--te-symbol', 'USDCAD']) - ).toThrow(/--te-symbol is only permitted/); - }); -}); - -describe('assertExportRawBsonSafety', () => { - test('allows read-only dev MongoDB even if Postgres config points to QA, and rejects disabled/writable/admin MongoDB', () => { - expect(() => assertExportRawBsonSafety(createBaseConfig(), {})).not.toThrow(); - - expect(() => assertExportRawBsonSafety(createBaseConfig({ enabled: false }), {})).toThrow( - /MongoDB is disabled/ - ); - expect(() => assertExportRawBsonSafety(createBaseConfig({ readOnly: false }), {})).toThrow( - /read-only MongoDB configuration/ - ); - expect(() => - assertExportRawBsonSafety( - createBaseConfig({ - readUri: 'mongodb://trading_admin:pw@localhost:27017/stock?authSource=admin', - readOnly: true, - }), - {} - ) - ).toThrow(/Safety guard/); - }); -}); - -describe('runExportRawBson & runCli', () => { - test('--help prints usage and performs zero config, Mongo, or fs I/O', async () => { - const stdout: string[] = []; - const initConfigMock = mock(() => { - throw new Error('initializeConfig must not be called on --help'); - }); - const createClientMock = mock(() => { - throw new Error('createMongoClient must not be called on --help'); - }); - - await runCli(['--help'], { - initializeConfig: initConfigMock as never, - createMongoClient: createClientMock, - writeStdout: text => stdout.push(text), - }); - - expect(stdout.join('')).toBe(`${EXPORT_RAW_BSON_USAGE}\n`); - expect(initConfigMock).not.toHaveBeenCalled(); - expect(createClientMock).not.toHaveBeenCalled(); - }); - - test('runCli initializes config with mongoReadOnly: true, issues strictly raw find(), calls zero write methods, and closes client', async () => { - const outDir = await mkdtemp(join(tmpdir(), 'run-export-raw-bson-cli-')); - try { - const sampleBytes = Uint8Array.from( - BSON.serialize({ eodSearchCode: 'CAD.FOREX', date: '2025-01-02', close: 1.44 }) - ); - const findCalls: Array<{ collection: string; filter: unknown; options: unknown }> = []; - const forbiddenWrite = mock(() => { - throw new Error('Write/DDL method must never be called'); - }); - const closeMongoMock = mock(async () => {}); - const closeCursorMock = mock(async () => {}); - - const fakeClient: ReadOnlyMongoRawBsonClient & Record = { - isReadOnly: () => true, - insertOne: forbiddenWrite, - updateOne: forbiddenWrite, - deleteMany: forbiddenWrite, - createIndex: forbiddenWrite, - dropCollection: forbiddenWrite, - getCollection: (name: string) => ({ - find: (filter, options) => { - findCalls.push({ collection: name, filter, options }); - return { - close: closeCursorMock, - async *[Symbol.asyncIterator]() { - yield sampleBytes; - }, - }; - }, - }), - }; - - const initCalls: Array<{ service: string; opts: unknown }> = []; - const stdout: string[] = []; - - await runCli( - [ - '--out-dir', - outDir, - '--collections', - 'eodPrices', - '--eod-symbol', - 'CAD.FOREX', - '--batch-size', - '256', - ], - { - initializeConfig: ((service: string, opts?: unknown) => { - initCalls.push({ service, opts }); - return createBaseConfig(); - }) as never, - createMongoClient: async () => ({ - client: fakeClient, - close: closeMongoMock, - }), - writeStdout: text => stdout.push(text), - } - ); - - expect(initCalls).toEqual([{ service: 'dataPipeline', opts: { mongoReadOnly: true } }]); - expect(findCalls).toEqual([ - { - collection: 'eodPrices', - filter: { eodSearchCode: 'CAD.FOREX' }, - options: { raw: true, batchSize: 256 }, - }, - ]); - expect(forbiddenWrite).not.toHaveBeenCalled(); - expect(closeCursorMock).toHaveBeenCalledTimes(1); - expect(closeMongoMock).toHaveBeenCalledTimes(1); - - const written = Uint8Array.from(await readFile(join(outDir, 'eodPrices.bson'))); - expect(written).toEqual(sampleBytes); - expect(stdout.join('')).toContain('eodPrices: docs=1'); - expect(stdout.join('')).toContain('sha256='); - } finally { - await rm(outDir, { recursive: true, force: true }); - } - }); - - test('runExportRawBson closes Mongo client on mid-stream export failure and preserves primary error', async () => { - const outDir = await mkdtemp(join(tmpdir(), 'run-export-raw-bson-fail-')); - try { - const closeMongoMock = mock(async () => {}); - const fakeClient: ReadOnlyMongoRawBsonClient = { - isReadOnly: () => true, - getCollection: () => ({ - find: () => ({ - async *[Symbol.asyncIterator]() { - yield Uint8Array.from(BSON.serialize({ ok: 1 })); - throw new Error('Mid-stream Mongo failure'); - }, - }), - }), - }; - - await expect( - runExportRawBson( - { - createMongoClient: () => ({ client: fakeClient, close: closeMongoMock }), - writeStdout: () => {}, - }, - { - outDir, - collections: ['qmSplits'], - } - ) - ).rejects.toThrow('Mid-stream Mongo failure'); - - expect(closeMongoMock).toHaveBeenCalledTimes(1); - } finally { - await rm(outDir, { recursive: true, force: true }); - } - }); - - test('runExportRawBson rejects disallowed collections before calling assertSafety or createMongoClient', async () => { - const assertSafetyMock = mock(() => {}); - const createClientMock = mock(() => { - throw new Error('createMongoClient must not be called'); - }); - - await expect( - runExportRawBson( - { - assertSafety: assertSafetyMock, - createMongoClient: createClientMock, - }, - { - outDir: '/tmp/unused', - collections: ['eodIntraday1M' as never], - } - ) - ).rejects.toMatchObject({ code: 'DISALLOWED_COLLECTION' }); - - expect(assertSafetyMock).not.toHaveBeenCalled(); - expect(createClientMock).not.toHaveBeenCalled(); - }); - - test('runCli rejects flag-shaped --eod-symbol and --te-symbol values before config or MongoDB access and preserves existing output', async () => { - const outDir = await mkdtemp(join(tmpdir(), 'run-export-raw-bson-flag-val-')); - try { - const existingEodPath = join(outDir, 'eodPrices.bson'); - const sentinel = Uint8Array.from(BSON.serialize({ eodSearchCode: 'CAD.FOREX', close: 1.44 })); - await writeFile(existingEodPath, sentinel); - - const initConfigMock = mock(() => { - throw new Error('initializeConfig must not be called on malformed filter'); - }); - const createClientMock = mock(() => { - throw new Error('createMongoClient must not be called on malformed filter'); - }); - - const invalidInvocations: string[][] = [ - ['--out-dir', outDir, '--collections', 'eodPrices', '--eod-symbol=--help'], - ['--out-dir', outDir, '--collections', 'eodPrices', '--eod-symbol', '--help'], - ['--out-dir', outDir, '--collections', 'teMarketData', '--te-symbol=--help'], - ['--out-dir', outDir, '--collections', 'teMarketData', '--te-symbol', '--help'], - ]; - - for (const argv of invalidInvocations) { - await expect( - runCli(argv, { - initializeConfig: initConfigMock as never, - createMongoClient: createClientMock, - }) - ).rejects.toThrow(/(?:Invalid|Missing) value for --(?:eod|te)-symbol/); - } - - expect(initConfigMock).not.toHaveBeenCalled(); - expect(createClientMock).not.toHaveBeenCalled(); - expect(Uint8Array.from(await readFile(existingEodPath))).toEqual(sentinel); - } finally { - await rm(outDir, { recursive: true, force: true }); - } - }); -}); diff --git a/apps/stock/data-pipeline/test/source-field-shapes-qa.test.ts b/apps/stock/data-pipeline/test/source-field-shapes-qa.test.ts deleted file mode 100644 index a035b01f..00000000 --- a/apps/stock/data-pipeline/test/source-field-shapes-qa.test.ts +++ /dev/null @@ -1,364 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { BSON } from 'mongodb'; -import { - createReadOnlyMongoSourceSymbolReader, - MAX_EXAMPLES_CAP, - parseProbeSourceFieldShapesArgs, - readFieldShapes, - renderFieldShapesMarkdown, - runSourceFieldShapesProbe, - summarizeFieldShapes, - type ReadOnlyMongoCollectionClient, - type ReadOnlySourceSymbolCursor, - type ReadOnlySourceSymbolReader, - type SourceSymbolFindOptions, -} from '../src/security-master'; - -// QA coverage for T-108 beyond the programmer's suite: real BSON wire decoding, -// option pass-through via the production read-only adapter, fail-fast safety, -// and CLI/runner failure paths. No MongoDB connection is opened anywhere here. - -const OBJECT_ID_HEX = '507f1f77bcf86cd799439011'; - -function serializeRealBsonDoc(): Uint8Array { - return BSON.serialize({ - _id: new BSON.ObjectId(OBJECT_ID_HEX), - i32: new BSON.Int32(7), - dbl: new BSON.Double(1.0), - lng: BSON.Long.fromString('9007199254740993'), - dec: BSON.Decimal128.fromString('12.34'), - flag: true, - text: '2025-01-02', - when: new Date('2025-01-02T00:00:00.000Z'), - nothing: null, - list: [1, 2], - nested: { px: new BSON.Double(2.5), qty: new BSON.Int32(3) }, - bin: new BSON.Binary(new Uint8Array([1, 2, 3])), - ts: new BSON.Timestamp({ t: 1, i: 1 }), - min: new BSON.MinKey(), - }); -} - -function nonZeroTypes(counts: Record): Record { - return Object.fromEntries(Object.entries(counts).filter(([, count]) => count > 0)); -} - -function asyncCursor( - docs: readonly T[], - onClose?: () => void -): { [Symbol.asyncIterator](): AsyncIterator; close(): Promise } { - return { - async *[Symbol.asyncIterator]() { - for (const doc of docs) { - yield doc; - } - }, - async close() { - onClose?.(); - }, - }; -} - -describe('summarizeFieldShapes with real BSON wire documents', () => { - test('promoteValues:false decoding keeps int/double/long/objectId distinct and maps other BSON types to other', () => { - const doc = BSON.deserialize(serializeRealBsonDoc(), { - promoteValues: false, - promoteLongs: false, - }); - - const summary = summarizeFieldShapes([doc]); - const types = Object.fromEntries(summary.fields.map(f => [f.field, nonZeroTypes(f.typeCounts)])); - - expect(types).toEqual({ - _id: { objectId: 1 }, - bin: { other: 1 }, - dbl: { double: 1 }, - dec: { other: 1 }, - flag: { bool: 1 }, - i32: { int: 1 }, - list: { array: 1 }, - lng: { int: 1 }, - min: { other: 1 }, - nested: { object: 1 }, - 'nested.px': { double: 1 }, - 'nested.qty': { int: 1 }, - nothing: { null: 1 }, - text: { string: 1 }, - ts: { other: 1 }, - when: { date: 1 }, - }); - - const examples = Object.fromEntries(summary.fields.map(f => [f.field, f.examples])); - expect(examples._id).toEqual([]); - expect(examples.dbl).toEqual(['1']); - expect(examples.lng).toEqual(['9007199254740993']); - expect(examples.dec).toEqual(['12.34']); - expect(examples.when).toEqual(['2025-01-02T00:00:00.000Z']); - expect(examples.bin).toEqual([]); - }); - - test('default driver promotion collapses Double(1.0) into int, which is why the probe disables promotion', () => { - const promoted = BSON.deserialize(serializeRealBsonDoc()); - const summary = summarizeFieldShapes([promoted]); - const dbl = summary.fields.find(f => f.field === 'dbl')!; - expect(nonZeroTypes(dbl.typeCounts)).toEqual({ int: 1 }); - }); -}); - -describe('readFieldShapes through the production read-only Mongo adapter', () => { - test('forwards limit/promoteValues/promoteLongs verbatim to collection.find and classifies decoded BSON', async () => { - const findCalls: Array<{ name: string; filter: unknown; options: unknown }> = []; - const closed: string[] = []; - const wireDoc = BSON.deserialize(serializeRealBsonDoc(), { - promoteValues: false, - promoteLongs: false, - }); - - const client: ReadOnlyMongoCollectionClient = { - isReadOnly: () => true, - getCollection(name: string) { - return { - find(filter?: Record, options?: SourceSymbolFindOptions) { - findCalls.push({ name, filter, options }); - return asyncCursor(name === 'qmDividends' ? [wireDoc] : [], () => closed.push(name)); - }, - }; - }, - }; - - const reader = createReadOnlyMongoSourceSymbolReader(client); - const result = await readFieldShapes(reader, { - collections: ['qmDividends', 'qmSplits'], - limit: 25, - }); - - expect(findCalls).toEqual([ - { - name: 'qmDividends', - filter: {}, - options: { limit: 25, promoteValues: false, promoteLongs: false }, - }, - { - name: 'qmSplits', - filter: {}, - options: { limit: 25, promoteValues: false, promoteLongs: false }, - }, - ]); - expect(closed).toEqual(['qmDividends', 'qmSplits']); - expect(result.totalDocsSampled).toBe(1); - const dbl = result.collections[0]!.fields.find(f => f.field === 'dbl')!; - expect(dbl.typeCounts.double).toBe(1); - }); - - test('re-checks read-only before every collection and stops if the reader stops being read-only', async () => { - let readOnly = true; - const findCalls: string[] = []; - const reader: ReadOnlySourceSymbolReader = { - isReadOnly: () => readOnly, - find>(name: string): ReadOnlySourceSymbolCursor { - findCalls.push(name); - readOnly = false; // simulate a reader that flips after its first query - return asyncCursor([]) as unknown as ReadOnlySourceSymbolCursor; - }, - }; - - await expect( - readFieldShapes(reader, { collections: ['ceoShorts', 'qmSplits'] }) - ).rejects.toThrow(/read-only/i); - expect(findCalls).toEqual(['ceoShorts']); - }); - - test('fails fast: an error on one collection prevents queries on later collections', async () => { - const findCalls: string[] = []; - const reader: ReadOnlySourceSymbolReader = { - isReadOnly: () => true, - find>(name: string): ReadOnlySourceSymbolCursor { - findCalls.push(name); - if (name === 'eodPrices') { - throw new Error('not authorized on stock'); - } - return asyncCursor([]) as unknown as ReadOnlySourceSymbolCursor; - }, - }; - - let caught: unknown; - try { - await readFieldShapes(reader, { collections: ['qmSplits', 'eodPrices', 'ceoShorts'] }); - } catch (error) { - caught = error; - } - // Collections are ASCII-sorted: ceoShorts, eodPrices, qmSplits. - expect(findCalls).toEqual(['ceoShorts', 'eodPrices']); - expect((caught as Error).message).toContain('eodPrices'); - expect((caught as Error).message).toContain('not authorized on stock'); - expect(((caught as Error).cause as Error).message).toBe('not authorized on stock'); - }); - - test('rejects non-integer limit and invalid batchSize before any query', async () => { - let findCalls = 0; - const reader: ReadOnlySourceSymbolReader = { - isReadOnly: () => true, - find>(): ReadOnlySourceSymbolCursor { - findCalls += 1; - return asyncCursor([]) as unknown as ReadOnlySourceSymbolCursor; - }, - }; - - await expect(readFieldShapes(reader, { limit: 1.5 })).rejects.toThrow(RangeError); - await expect(readFieldShapes(reader, { limit: Number.NaN })).rejects.toThrow(RangeError); - await expect(readFieldShapes(reader, { batchSize: 0 })).rejects.toThrow(RangeError); - await expect(readFieldShapes(reader, { collections: [] })).rejects.toThrow(RangeError); - expect(findCalls).toBe(0); - }); -}); - -describe('summarizeFieldShapes edge cases', () => { - test('non-object documents count toward docCount and keep presence invariants', () => { - const docs = [{ a: 1 }, null, 'oops', { a: 'x' }] as unknown as Record[]; - const summary = summarizeFieldShapes(docs); - expect(summary.docCount).toBe(4); - const a = summary.fields.find(f => f.field === 'a')!; - expect(a.presentCount).toBe(2); - expect(a.missingCount).toBe(2); - }); - - test('undefined values are treated as missing, not as a present type', () => { - const summary = summarizeFieldShapes([{ a: undefined }, { a: 1 }]); - const a = summary.fields.find(f => f.field === 'a')!; - expect(a.presentCount).toBe(1); - expect(a.missingCount).toBe(1); - }); - - test('rejects near-miss dates and times as ymd/isoDatetime', () => { - const values = [ - '2024-13-01', // month 13 - '2024-04-31', // April has 30 days - '2025-01-01T24:00:00Z', // hour 24 - '2025-01-01T10:60:00Z', // minute 60 - '2025-01-01 10:00:00', // space separator - '20250101', // compact date is numeric, not ymd - ]; - const summary = summarizeFieldShapes(values.map(s => ({ s }))); - const s = summary.fields.find(f => f.field === 's')!; - expect(s.stringStats!.patterns).toEqual({ - ymd: 0, - isoDatetime: 0, - numeric: 1, - emptyOrWhitespace: 0, - other: 5, - }); - }); - - test('examples are distinct, strip control characters, and honour maxExamples 0 and the cap', () => { - const docs = [{ s: 'dup' }, { s: 'dup' }, { s: '\u0000\u001bbell\u0007' }]; - - expect(summarizeFieldShapes(docs).fields[0]!.examples).toEqual(['bell', 'dup']); - expect(summarizeFieldShapes(docs, { maxExamples: 0 }).fields[0]!.examples).toEqual([]); - - const many = Array.from({ length: 50 }, (_, i) => ({ s: `v${String(i).padStart(2, '0')}` })); - const capped = summarizeFieldShapes(many, { maxExamples: MAX_EXAMPLES_CAP }).fields[0]!; - expect(capped.examples.length).toBe(MAX_EXAMPLES_CAP); - expect(capped.examples[0]).toBe('v00'); - }); -}); - -describe('renderFieldShapesMarkdown privacy and header', () => { - test('never renders _id values and states the bounded sample in the header', async () => { - const reader: ReadOnlySourceSymbolReader = { - isReadOnly: () => true, - find>(): ReadOnlySourceSymbolCursor { - return asyncCursor([ - { _id: new BSON.ObjectId(OBJECT_ID_HEX), symbol: 'ABC' }, - { _id: { ticker: 'SECRET-COMPOSITE' }, symbol: 'DEF' }, - ] as unknown as T[]) as unknown as ReadOnlySourceSymbolCursor; - }, - }; - - const result = await readFieldShapes(reader, { collections: ['ceoShorts'], limit: 7 }); - const markdown = renderFieldShapesMarkdown(result); - - expect(markdown).not.toContain(OBJECT_ID_HEX); - expect(markdown).not.toContain('SECRET-COMPOSITE'); - expect(markdown).toContain('bounded sample, not a full scan'); - expect(markdown).toContain('**Sample limit per collection:** 7'); - expect(markdown).toContain('**Total documents sampled:** 2'); - expect(markdown).toContain('| `_id.ticker` | 50.0% (1/2) |'); - expect(markdown).not.toMatch(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/); // no wall-clock stamp - }); -}); - -describe('probe CLI parsing and runner failure paths', () => { - test('rejects a flag in place of a value and empty inline values', () => { - expect(() => parseProbeSourceFieldShapesArgs(['--out', '--limit', '5'])).toThrow(/--out/); - expect(() => parseProbeSourceFieldShapesArgs(['--out=x.md', '--limit'])).toThrow(/--limit/); - expect(() => parseProbeSourceFieldShapesArgs(['--out=x.md', '--collections='])).toThrow( - /--collections/ - ); - expect(() => parseProbeSourceFieldShapesArgs(['--out=x.md', '--collections', ' , '])).toThrow( - /--collections/ - ); - expect(() => parseProbeSourceFieldShapesArgs(['--out=x.md', '--limit=1e3'])).toThrow(/--limit/); - }); - - test('merges repeated --collections, accepts boundary limits, and lets --help win', () => { - expect( - parseProbeSourceFieldShapesArgs([ - '--out=x.md', - '--collections=qmSplits', - '--collections', - 'ceoShorts,qmSplits', - '--limit=10000', - ]) - ).toEqual({ help: false, outPath: 'x.md', limit: 10_000, collections: ['ceoShorts', 'qmSplits'] }); - expect(parseProbeSourceFieldShapesArgs(['--out=x.md', '--limit=1'])).toMatchObject({ limit: 1 }); - expect(parseProbeSourceFieldShapesArgs(['--out=x.md', '--help'])).toEqual({ help: true }); - }); - - test('closes Mongo and surfaces the write error when the report cannot be written', async () => { - let closeCalls = 0; - const stdout: string[] = []; - const client: ReadOnlyMongoCollectionClient = { - isReadOnly: () => true, - getCollection() { - return { find: () => asyncCursor([{ a: 1 }]) }; - }, - }; - - await expect( - runSourceFieldShapesProbe( - { - mongoCollectionClient: client, - closeMongo: () => { - closeCalls += 1; - }, - writeFile: () => { - throw new Error('EACCES: permission denied'); - }, - writeStdout: text => stdout.push(text), - }, - { outPath: './tmp/out.md', collections: ['qmSplits'] } - ) - ).rejects.toThrow('EACCES'); - expect(closeCalls).toBe(1); - expect(stdout).toEqual([]); - }); - - test('blank outPath is rejected before any collection is opened', async () => { - let getCollectionCalls = 0; - const client: ReadOnlyMongoCollectionClient = { - isReadOnly: () => true, - getCollection() { - getCollectionCalls += 1; - return { find: () => asyncCursor([]) }; - }, - }; - - await expect( - runSourceFieldShapesProbe( - { mongoCollectionClient: client, writeFile: () => {}, writeStdout: () => {} }, - { outPath: ' ' } - ) - ).rejects.toThrow(/outPath/); - expect(getCollectionCalls).toBe(0); - }); -}); diff --git a/apps/stock/data-pipeline/test/source-field-shapes.test.ts b/apps/stock/data-pipeline/test/source-field-shapes.test.ts deleted file mode 100644 index 47e150e9..00000000 --- a/apps/stock/data-pipeline/test/source-field-shapes.test.ts +++ /dev/null @@ -1,812 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { readFileSync } from 'node:fs'; -import { resolve } from 'node:path'; -import type { ParserOptions } from 'prettier'; -import * as markdownPlugin from 'prettier/plugins/markdown'; -import { - DEFAULT_FIELD_SHAPE_LIMIT, - DEFAULT_MAX_EXAMPLE_LENGTH, - DEFAULT_MAX_EXAMPLES, - FIELD_SHAPE_PROBE_COLLECTIONS, - FIELD_VALUE_TYPES, - MAX_EXAMPLE_LENGTH_CAP, - MAX_EXAMPLES_CAP, - MAX_FIELD_SHAPE_LIMIT, - parseProbeSourceFieldShapesArgs, - readFieldShapes, - renderFieldShapesMarkdown, - runSourceFieldShapesProbe, - STRING_PATTERN_CLASSES, - summarizeFieldShapes, - UnknownProbeCollectionError, - type FieldShapeSummary, - type ReadOnlyMongoCollectionClient, - type ReadOnlySourceSymbolCursor, - type ReadOnlySourceSymbolReader, - type SourceSymbolFindOptions, -} from '../src/security-master'; - -interface RecordedFindCall { - collectionName: string; - filter: Record | undefined; - options: SourceSymbolFindOptions | undefined; -} - -interface FakeBsonWrapper { - _bsontype: string; - valueOf?: () => unknown; - toString: () => string; -} - -function fakeInt32(value: number): FakeBsonWrapper { - return { - _bsontype: 'Int32', - valueOf: () => value, - toString: () => String(value), - }; -} - -function fakeDouble(value: number): FakeBsonWrapper { - return { - _bsontype: 'Double', - valueOf: () => value, - toString: () => String(value), - }; -} - -function fakeLong(value: string): FakeBsonWrapper { - return { - _bsontype: 'Long', - toString: () => value, - }; -} - -function fakeObjectId(hex: string): FakeBsonWrapper { - return { - _bsontype: 'ObjectId', - toString: () => hex, - }; -} - -function fakeDecimal128(value: string): FakeBsonWrapper { - return { - _bsontype: 'Decimal128', - toString: () => value, - }; -} - -function sumTypeCounts(summary: FieldShapeSummary): number { - let total = 0; - for (const typeName of FIELD_VALUE_TYPES) { - total += summary.typeCounts[typeName]; - } - return total; -} - -function sumPatternCounts(summary: FieldShapeSummary): number { - if (summary.stringStats === null) { - return 0; - } - let total = 0; - for (const pattern of STRING_PATTERN_CLASSES) { - total += summary.stringStats.patterns[pattern]; - } - return total; -} - -function createFakeReader( - docsByCollection: Record[]>, - opts?: { - readOnly?: boolean; - failFindOnCollection?: string; - failIterOnCollection?: string; - failIterAtIndex?: number; - failCloseOnCollection?: string; - returnBufferedArrayOnCollection?: string; - ignoreLimit?: boolean; - } -): { - reader: ReadOnlySourceSymbolReader; - calls: RecordedFindCall[]; - closedCollections: string[]; - pullsByCollection: Record; -} { - const calls: RecordedFindCall[] = []; - const closedCollections: string[] = []; - const pullsByCollection: Record = {}; - const readOnly = opts?.readOnly ?? true; - - const reader: ReadOnlySourceSymbolReader = { - isReadOnly(): boolean { - return readOnly; - }, - find = Record>( - collectionName: string, - filter?: Record, - options?: SourceSymbolFindOptions - ): ReadOnlySourceSymbolCursor { - calls.push({ collectionName, filter, options }); - - if (opts?.failFindOnCollection === collectionName) { - throw new Error('simulated find failure'); - } - if (opts?.returnBufferedArrayOnCollection === collectionName) { - return [...(docsByCollection[collectionName] ?? [])] as unknown as ReadOnlySourceSymbolCursor; - } - - const sourceDocs = docsByCollection[collectionName] ?? []; - const maxToYield = - opts?.ignoreLimit === true || options?.limit === undefined - ? sourceDocs.length - : Math.min(sourceDocs.length, options.limit); - const failAt = opts?.failIterAtIndex ?? 1; - - return { - async *[Symbol.asyncIterator](): AsyncIterator { - for (let i = 0; i < maxToYield; i++) { - pullsByCollection[collectionName] = (pullsByCollection[collectionName] ?? 0) + 1; - if (opts?.failIterOnCollection === collectionName && i === failAt) { - throw new Error('simulated cursor iteration failure'); - } - yield sourceDocs[i] as T; - } - }, - async close(): Promise { - closedCollections.push(collectionName); - if (opts?.failCloseOnCollection === collectionName) { - throw new Error('simulated cursor close failure'); - } - }, - }; - }, - }; - - return { reader, calls, closedCollections, pullsByCollection }; -} - -describe('source-field-shapes static purity', () => { - test('source-field-shapes.ts has zero runtime DB, FS, or network imports', () => { - const filePath = resolve(import.meta.dir, '../src/security-master/source-field-shapes.ts'); - const source = readFileSync(filePath, 'utf8'); - const runtimeImportLines = source - .split('\n') - .filter(line => /^\s*import\s+(?!type\b)/.test(line)); - - for (const line of runtimeImportLines) { - expect(line).not.toMatch(/mongodb|postgres|node:fs|node:http|node:https|node:net|fetch/i); - } - expect(source).not.toMatch(/\bDate\.now\s*\(|\bnew Date\s*\(\s*\)/); - }); -}); - -describe('summarizeFieldShapes', () => { - test('classifies mixed JS and BSON value types on one field and reconciles counts', () => { - const docs: Record[] = [ - { mixed: 'hello' }, - { mixed: 42 }, - { mixed: 3.14 }, - { mixed: fakeInt32(7) }, - { mixed: fakeLong('9007199254740993') }, - { mixed: fakeDouble(1.0) }, - { mixed: true }, - { mixed: new Date('2025-01-15T12:00:00.000Z') }, - { mixed: null }, - { mixed: fakeObjectId('507f1f77bcf86cd799439011') }, - { mixed: [1, 2, 3] }, - { mixed: { nested: 'a' } }, - { mixed: fakeDecimal128('12.34') }, - { mixed: new Uint8Array([1, 2]) }, - {}, // missing - ]; - - const summary = summarizeFieldShapes(docs); - expect(summary.docCount).toBe(docs.length); - - const mixed = summary.fields.find(f => f.field === 'mixed'); - expect(mixed).toBeDefined(); - expect(mixed!.presentCount).toBe(14); - expect(mixed!.missingCount).toBe(1); - expect(mixed!.presentCount + mixed!.missingCount).toBe(summary.docCount); - expect(sumTypeCounts(mixed!)).toBe(mixed!.presentCount); - - expect(mixed!.typeCounts).toEqual({ - string: 1, - int: 3, // 42, Int32(7), Long(...) - double: 2, // 3.14, Double(1.0) - bool: 1, - date: 1, - null: 1, - objectId: 1, - array: 1, - object: 1, - other: 2, // Decimal128, Uint8Array - }); - }); - - test('tracks one level of nested parent.child keys and stops at depth 1', () => { - const docs: Record[] = [ - { - meta: { - exchange: 'TSX', - deep: { level2: 'ignored' }, - recordedAt: new Date('2025-02-01T00:00:00Z'), - }, - arr: [{ insideArray: 1 }], - bsonObj: fakeObjectId('507f1f77bcf86cd799439012'), - }, - { - meta: { - exchange: 'NYSE', - }, - }, - ]; - - const summary = summarizeFieldShapes(docs); - const fieldNames = summary.fields.map(f => f.field); - - expect(fieldNames).toEqual([ - 'arr', - 'bsonObj', - 'meta', - 'meta.deep', - 'meta.exchange', - 'meta.recordedAt', - ]); - expect(fieldNames).not.toContain('meta.deep.level2'); - expect(fieldNames).not.toContain('bsonObj._bsontype'); - - const metaExchange = summary.fields.find(f => f.field === 'meta.exchange')!; - expect(metaExchange.presentCount).toBe(2); - expect(metaExchange.missingCount).toBe(0); - expect(metaExchange.typeCounts.string).toBe(2); - - const metaDeep = summary.fields.find(f => f.field === 'meta.deep')!; - expect(metaDeep.presentCount).toBe(1); - expect(metaDeep.missingCount).toBe(1); - expect(metaDeep.typeCounts.object).toBe(1); - }); - - test('keeps literal dotted top-level keys distinct from nested parent.child keys', () => { - const docs: Record[] = [ - { - 'meta.exchange': 'LITERAL_EXCHANGE', - meta: { - exchange: 42, - }, - }, - ]; - - const summary = summarizeFieldShapes(docs); - expect(summary.docCount).toBe(1); - - const literalField = summary.fields.find(f => f.field === 'meta\\.exchange'); - const nestedField = summary.fields.find(f => f.field === 'meta.exchange'); - expect(literalField).toBeDefined(); - expect(nestedField).toBeDefined(); - - expect(literalField!.presentCount).toBe(1); - expect(literalField!.missingCount).toBe(0); - expect(literalField!.typeCounts.string).toBe(1); - expect(literalField!.typeCounts.int).toBe(0); - expect(literalField!.examples).toEqual(['LITERAL_EXCHANGE']); - - expect(nestedField!.presentCount).toBe(1); - expect(nestedField!.missingCount).toBe(0); - expect(nestedField!.typeCounts.int).toBe(1); - expect(nestedField!.typeCounts.string).toBe(0); - expect(nestedField!.examples).toEqual(['42']); - }); - - test('classifies all five string pattern classes and tracks min/max string length', () => { - const docs: Record[] = [ - { s: '2024-02-29' }, // valid leap-year ymd (len 10) - { s: '2023-02-29' }, // invalid calendar date -> other (len 10) - { s: '2025-05-01T14:30:00Z' }, // isoDatetime (len 20) - { s: '2025-05-01T14:30:00.123-04:00' }, // isoDatetime (len 29) - { s: '-123.45' }, // numeric (len 7) - { s: '1.5e-4' }, // numeric (len 6) - { s: '' }, // emptyOrWhitespace (len 0) - { s: ' \t ' }, // emptyOrWhitespace (len 5) - { s: 'AAPL.US' }, // other (len 7) - ]; - - const summary = summarizeFieldShapes(docs); - const field = summary.fields.find(f => f.field === 's')!; - - expect(field.typeCounts.string).toBe(9); - expect(field.stringStats).toEqual({ - minLength: 0, - maxLength: 29, - patterns: { - ymd: 1, - isoDatetime: 2, - numeric: 2, - emptyOrWhitespace: 2, - other: 2, - }, - }); - expect(sumPatternCounts(field)).toBe(field.typeCounts.string); - }); - - test('truncates and caps examples, suppresses _id and _id.* examples, and validates bounds', () => { - const docs: Record[] = [ - { - _id: fakeObjectId('507f1f77bcf86cd799439011'), - symbol: 'ZZZZ', - note: 'line1\nline2\twith a very long description that must be truncated', - }, - { - _id: { key: 'secret-composite-id' }, - symbol: 'AAAA', - note: 'short', - }, - { - _id: 'string-id-should-never-appear', - symbol: 'MMMM', - }, - { - symbol: 'BBBB', - }, - ]; - - const summary = summarizeFieldShapes(docs, { maxExamples: 2, maxExampleLength: 16 }); - const idField = summary.fields.find(f => f.field === '_id')!; - const idChildField = summary.fields.find(f => f.field === '_id.key')!; - const symbolField = summary.fields.find(f => f.field === 'symbol')!; - const noteField = summary.fields.find(f => f.field === 'note')!; - - expect(idField.examples).toEqual([]); - expect(idChildField.examples).toEqual([]); - expect(symbolField.examples).toEqual(['AAAA', 'BBBB']); - expect(noteField.examples.length).toBe(2); - expect(noteField.examples[0]).toBe('line1 line2 w...'); - expect(noteField.examples[0]!.length).toBeLessThanOrEqual(16); - expect(noteField.examples[1]).toBe('short'); - - expect(() => summarizeFieldShapes(docs, { maxExamples: -1 })).toThrow(RangeError); - expect(() => summarizeFieldShapes(docs, { maxExamples: MAX_EXAMPLES_CAP + 1 })).toThrow( - RangeError - ); - expect(() => summarizeFieldShapes(docs, { maxExampleLength: 0 })).toThrow(RangeError); - expect(() => - summarizeFieldShapes(docs, { maxExampleLength: MAX_EXAMPLE_LENGTH_CAP + 1 }) - ).toThrow(RangeError); - }); - - test('produces deep-equal output for shuffled input order and handles empty iterable', () => { - expect(summarizeFieldShapes([])).toEqual({ docCount: 0, fields: [] }); - - const original: Record[] = [ - { _id: fakeObjectId('000000000000000000000001'), z: 'delta', a: 10, meta: { k: 'v3' } }, - { _id: fakeObjectId('000000000000000000000002'), z: 'alpha', a: 2.5, meta: { k: 'v1' } }, - { _id: fakeObjectId('000000000000000000000003'), z: 'charlie', b: true, meta: { k: 'v4' } }, - { _id: fakeObjectId('000000000000000000000004'), z: 'bravo', a: null, meta: { k: 'v2' } }, - ]; - const shuffled = [original[2]!, original[0]!, original[3]!, original[1]!]; - - const a = summarizeFieldShapes(original, { maxExamples: 2 }); - const b = summarizeFieldShapes(shuffled, { maxExamples: 2 }); - - expect(b).toEqual(a); - expect(a.fields.map(f => f.field)).toEqual(['_id', 'a', 'b', 'meta', 'meta.k', 'z']); - }); -}); - -describe('readFieldShapes', () => { - test('calls only find() with limit and promoteValues/promoteLongs false, closes cursors, and enforces client limit', async () => { - const docsByCollection: Record[]> = { - qmDividends: [ - { _id: fakeObjectId('507f1f77bcf86cd799439011'), amount: fakeDouble(0.25), currency: 'USD' }, - { _id: fakeObjectId('507f1f77bcf86cd799439012'), amount: fakeDouble(0.5), currency: 'CAD' }, - { _id: fakeObjectId('507f1f77bcf86cd799439013'), amount: fakeDouble(1.0), currency: 'USD' }, - ], - ceoShorts: [ - { _id: fakeObjectId('507f1f77bcf86cd799439014'), symbol: 'ABC', shares: fakeInt32(1000) }, - ], - }; - - const { reader, calls, closedCollections, pullsByCollection } = createFakeReader( - docsByCollection, - { - ignoreLimit: true, - failIterOnCollection: 'qmDividends', - failIterAtIndex: 2, - } - ); - - const result = await readFieldShapes(reader, { - collections: ['qmDividends', 'ceoShorts', 'qmDividends'], - limit: 2, - batchSize: 500, - }); - - expect(calls.length).toBe(2); - expect(calls.map(c => c.collectionName)).toEqual(['ceoShorts', 'qmDividends']); - for (const call of calls) { - expect(call.filter).toEqual({}); - expect(call.options).toEqual({ - limit: 2, - promoteValues: false, - promoteLongs: false, - batchSize: 500, - }); - } - expect(closedCollections).toEqual(['ceoShorts', 'qmDividends']); - // Breaks immediately after recording the limit-th doc without pulling a 3rd item - expect(pullsByCollection).toEqual({ ceoShorts: 1, qmDividends: 2 }); - - // Defensively capped at limit=2 even though fake reader ignored limit - expect(result.limit).toBe(2); - expect(result.totalDocsSampled).toBe(3); - const qmDiv = result.collections.find(c => c.collection === 'qmDividends')!; - expect(qmDiv.docCount).toBe(2); - const amountField = qmDiv.fields.find(f => f.field === 'amount')!; - expect(amountField.typeCounts.double).toBe(2); - }); - - test('defaults to all allowlisted collections and DEFAULT_FIELD_SHAPE_LIMIT', async () => { - const { reader, calls } = createFakeReader({}); - const result = await readFieldShapes(reader); - - expect(result.limit).toBe(DEFAULT_FIELD_SHAPE_LIMIT); - expect(result.maxExamples).toBe(DEFAULT_MAX_EXAMPLES); - expect(result.maxExampleLength).toBe(DEFAULT_MAX_EXAMPLE_LENGTH); - expect(calls.length).toBe(FIELD_SHAPE_PROBE_COLLECTIONS.length); - for (const call of calls) { - expect(call.options).toEqual({ - limit: DEFAULT_FIELD_SHAPE_LIMIT, - promoteValues: false, - promoteLongs: false, - }); - } - }); - - test('rejects invalid limit, unknown collection, and non-read-only reader before any query', async () => { - const nonRo = createFakeReader({}, { readOnly: false }); - await expect(readFieldShapes(nonRo.reader)).rejects.toThrow(/read-only/i); - expect(nonRo.calls.length).toBe(0); - - const badLimitHigh = createFakeReader({}); - await expect( - readFieldShapes(badLimitHigh.reader, { limit: MAX_FIELD_SHAPE_LIMIT + 1 }) - ).rejects.toThrow(RangeError); - expect(badLimitHigh.calls.length).toBe(0); - - const badLimitZero = createFakeReader({}); - await expect(readFieldShapes(badLimitZero.reader, { limit: 0 })).rejects.toThrow(RangeError); - expect(badLimitZero.calls.length).toBe(0); - - const unknownCol = createFakeReader({}); - let caught: unknown; - try { - await readFieldShapes(unknownCol.reader, { collections: ['eodPrices', 'notACollection'] }); - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(UnknownProbeCollectionError); - expect((caught as UnknownProbeCollectionError).collectionName).toBe('notACollection'); - expect(unknownCol.calls.length).toBe(0); - }); - - test('rejects buffered array cursor with TypeError and surfaces per-collection errors with cause', async () => { - const buffered = createFakeReader( - { eodPrices: [{ date: '2025-01-02' }] }, - { returnBufferedArrayOnCollection: 'eodPrices' } - ); - await expect( - readFieldShapes(buffered.reader, { collections: ['eodPrices'] }) - ).rejects.toThrow(TypeError); - - const findErr = createFakeReader({}, { failFindOnCollection: 'qmFilings' }); - let caughtFind: unknown; - try { - await readFieldShapes(findErr.reader, { collections: ['eodPrices', 'qmFilings'] }); - } catch (err) { - caughtFind = err; - } - expect(caughtFind).toBeInstanceOf(Error); - expect((caughtFind as Error).message).toContain('qmFilings'); - expect((caughtFind as Error).cause).toBeInstanceOf(Error); - - const iterErr = createFakeReader( - { qmEarnings: [{ a: 1 }, { a: 2 }] }, - { failIterOnCollection: 'qmEarnings' } - ); - let caughtIter: unknown; - try { - await readFieldShapes(iterErr.reader, { collections: ['qmEarnings'] }); - } catch (err) { - caughtIter = err; - } - expect(caughtIter).toBeInstanceOf(Error); - expect((caughtIter as Error).message).toContain('qmEarnings'); - expect((caughtIter as Error).cause).toBeInstanceOf(Error); - expect(iterErr.closedCollections).toEqual(['qmEarnings']); - - const closeErr = createFakeReader( - { teMarketData: [{ country: 'US' }] }, - { failCloseOnCollection: 'teMarketData' } - ); - let caughtClose: unknown; - try { - await readFieldShapes(closeErr.reader, { collections: ['teMarketData'] }); - } catch (err) { - caughtClose = err; - } - expect(caughtClose).toBeInstanceOf(Error); - expect((caughtClose as Error).message).toContain('teMarketData'); - expect((caughtClose as Error).cause).toBeInstanceOf(Error); - }); -}); - -interface MdastNode { - type: string; - value?: string; - children?: MdastNode[]; -} - -function decodeHtmlEntities(text: string): string { - return text.replace(/&(amp|lt|gt|#(\d+));/g, (_, entity: string, code?: string) => { - if (code !== undefined) { - return String.fromCharCode(Number(code)); - } - switch (entity) { - case 'amp': - return '&'; - case 'lt': - return '<'; - case 'gt': - return '>'; - default: - return `&${entity};`; - } - }); -} - -function parseGfmTables(markdown: string): MdastNode[][] { - const ast = markdownPlugin.parsers.markdown.parse( - markdown, - {} as ParserOptions - ) as unknown as MdastNode; - const rows: MdastNode[][] = []; - for (const node of ast.children ?? []) { - if (node.type !== 'table') { - continue; - } - const tableRows = node.children ?? []; - for (let rowIndex = 1; rowIndex < tableRows.length; rowIndex++) { - rows.push(tableRows[rowIndex]?.children ?? []); - } - } - return rows; -} - -function extractGfmCodeCellValues(cell: MdastNode): string[] { - const nodes = cell.children ?? []; - if (nodes.length === 1 && nodes[0]?.type === 'text' && nodes[0].value === '—') { - return []; - } - - const values: string[] = []; - let i = 0; - while (i < nodes.length) { - const node = nodes[i]!; - if (node.type === 'inlineCode') { - values.push(node.value ?? ''); - i += 1; - } else if (node.type === 'html' && node.value === '') { - let inner = ''; - i += 1; - let closed = false; - while (i < nodes.length) { - const innerNode = nodes[i]!; - if (innerNode.type === 'html' && innerNode.value === '') { - closed = true; - i += 1; - break; - } - if (innerNode.type !== 'text') { - throw new Error( - `Unexpected Markdown node "${innerNode.type}" inside element: ${JSON.stringify(innerNode)}` - ); - } - inner += decodeHtmlEntities(innerNode.value ?? ''); - i += 1; - } - if (!closed) { - throw new Error('Unclosed HTML element in GFM table cell'); - } - values.push(inner); - } else if (node.type === 'text' && node.value === ', ') { - i += 1; - } else { - throw new Error(`Unexpected node in GFM code cell: ${JSON.stringify(node)}`); - } - } - return values; -} - -describe('renderFieldShapesMarkdown', () => { - test('renders byte-identical Markdown with bounded-sample header, valid GFM code spans, and empty collection notice', async () => { - const docsA = [ - { - _id: fakeObjectId('000000000000000000000001'), - 'pipe|col': 'val|with`ticks\\slash', - 'slash\\|field': 'slash\\|pipe*em*_u_&', - 'tick`field\nname': '`leading`', - edge: 'double``ticks', - dt: '2025-01-02', - }, - { - _id: fakeObjectId('000000000000000000000002'), - 'pipe|col': 'slash\\|pipe', - 'slash\\|field': 'slash\\\\|pipe', - 'tick`field\nname': ' spaced ', - edge: '', - dt: '2025-01-03', - }, - ]; - const docsB = [docsA[1]!, docsA[0]!]; - - const run1 = await readFieldShapes( - createFakeReader({ eodPrices: docsA, qmSplits: [] }).reader, - { collections: ['eodPrices', 'qmSplits'], limit: 500 } - ); - const run2 = await readFieldShapes( - createFakeReader({ eodPrices: docsB, qmSplits: [] }).reader, - { collections: ['qmSplits', 'eodPrices'], limit: 500 } - ); - - const md1 = renderFieldShapesMarkdown(run1); - const md2 = renderFieldShapesMarkdown(run2); - - expect(md1).toBe(md2); - expect(md1).toContain('bounded sample'); - expect(md1).toContain('Sample limit per collection:** 500'); - expect(md1).toContain('Total documents sampled:** 2'); - expect(md1).toContain('_No documents sampled._'); - - const tableRows = parseGfmTables(md1); - expect(tableRows.length).toBe(6); - - const visibleByField = new Map(); - for (const cells of tableRows) { - expect(cells.length).toBe(5); - const parsedField = extractGfmCodeCellValues(cells[0]!); - expect(parsedField.length).toBe(1); - const parsedExamples = extractGfmCodeCellValues(cells[4]!); - visibleByField.set(parsedField[0]!, parsedExamples); - } - - expect(visibleByField.get('pipe|col')).toEqual(['slash\\|pipe', 'val|with`ticks\\slash']); - expect(visibleByField.get('slash\\\\|field')).toEqual([ - 'slash\\\\|pipe', - 'slash\\|pipe*em*_u_&', - ]); - expect(visibleByField.get('tick`field name')).toEqual([' spaced ', '`leading`']); - expect(visibleByField.get('edge')).toEqual(['', 'double``ticks']); - expect(visibleByField.get('_id')).toEqual([]); - }); -}); - -describe('CLI arg parsing and headless probe runner', () => { - test('parseProbeSourceFieldShapesArgs validates flags without opening any DB connection', () => { - expect(parseProbeSourceFieldShapesArgs(['--help'])).toEqual({ help: true }); - expect(() => parseProbeSourceFieldShapesArgs([])).toThrow(/--out/); - expect(() => parseProbeSourceFieldShapesArgs(['--out', ' '])).toThrow(/--out/); - expect(() => parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--limit=0'])).toThrow( - /--limit/ - ); - expect(() => parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--limit', '-1'])).toThrow( - /--limit/ - ); - expect(() => - parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--limit', String(MAX_FIELD_SHAPE_LIMIT + 1)]) - ).toThrow(/--limit/); - expect(() => parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--limit=abc'])).toThrow( - /--limit/ - ); - expect(() => parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--limit=1.5'])).toThrow( - /--limit/ - ); - expect(() => parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--bogus'])).toThrow( - /Unknown argument/ - ); - expect(() => - parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--collections=eodPrices,bogusCol']) - ).toThrow(UnknownProbeCollectionError); - - const parsed = parseProbeSourceFieldShapesArgs([ - '--out', - './tmp/report.md', - '--limit', - '250', - '--collections', - 'qmDividends,ceoShorts,qmDividends', - ]); - expect(parsed).toEqual({ - help: false, - outPath: './tmp/report.md', - limit: 250, - collections: ['ceoShorts', 'qmDividends'], - }); - }); - - test('runSourceFieldShapesProbe rejects non-read-only client before any query and writes report headlessly', async () => { - let getCollectionCalls = 0; - let closeCalls = 0; - - const writableClient: ReadOnlyMongoCollectionClient = { - isReadOnly: () => false, - getCollection() { - getCollectionCalls += 1; - throw new Error('should never be called'); - }, - }; - - await expect( - runSourceFieldShapesProbe( - { - mongoCollectionClient: writableClient, - closeMongo: () => { - closeCalls += 1; - }, - writeFile: () => {}, - writeStdout: () => {}, - }, - { outPath: './tmp/should-not-write.md' } - ) - ).rejects.toThrow(/read-only/i); - expect(getCollectionCalls).toBe(0); - expect(closeCalls).toBe(1); - - const writtenFiles: Array<{ filePath: string; content: string }> = []; - const stdoutChunks: string[] = []; - let roCloseCalls = 0; - - const roClient: ReadOnlyMongoCollectionClient = { - isReadOnly: () => true, - getCollection(name: string) { - return { - find() { - const docs = name === 'ceoShorts' ? [{ symbol: 'XYZ', shares: 100 }] : []; - return { - async *[Symbol.asyncIterator]() { - for (const doc of docs) { - yield doc; - } - }, - async close() {}, - }; - }, - }; - }, - }; - - const output = await runSourceFieldShapesProbe( - { - mongoCollectionClient: roClient, - closeMongo: () => { - roCloseCalls += 1; - }, - writeFile: (filePath, content) => { - writtenFiles.push({ filePath, content }); - }, - writeStdout: text => { - stdoutChunks.push(text); - }, - }, - { - outPath: './tmp/field-shapes.md', - limit: 10, - collections: ['ceoShorts'], - } - ); - - expect(roCloseCalls).toBe(1); - expect(writtenFiles.length).toBe(1); - expect(writtenFiles[0]!.filePath).toBe('./tmp/field-shapes.md'); - expect(writtenFiles[0]!.content).toBe(output.markdown); - expect(stdoutChunks.join('')).toContain('Documents sampled: 1'); - }); -}); diff --git a/bun.lock b/bun.lock index 9a537c0b..b91d5c52 100644 --- a/bun.lock +++ b/bun.lock @@ -355,17 +355,6 @@ "typescript": "^5.3.0", }, }, - "libs/data/duckdb": { - "name": "@stock-bot/duckdb", - "version": "1.0.0", - "dependencies": { - "@duckdb/node-api": "^1.4.4-r.1", - "@stock-bot/research": "workspace:*", - }, - "devDependencies": { - "@types/node": "^20.11.0", - }, - }, "libs/data/mongodb": { "name": "@stock-bot/mongodb", "version": "1.0.0", @@ -551,22 +540,6 @@ "@balena/dockerignore": ["@balena/dockerignore@1.0.2", "", {}, "sha512-wMue2Sy4GAVTk6Ic4tJVcnfdau+gx2EnG7S+uAEe+TWJFqE4YoWN4/H8MSLj4eYJKxGg26lZwboEniNiNwZQ6Q=="], - "@duckdb/node-api": ["@duckdb/node-api@1.4.4-r.4", "", { "dependencies": { "@duckdb/node-bindings": "1.4.4-r.4" } }, "sha512-yUotG8wPSmmEFxAODt07rXJZgV2fhvzhnZX3wrMspQNEaNVwXArzakgKyfakZkYL9me7SK9eDnXYv/XbdifWEg=="], - - "@duckdb/node-bindings": ["@duckdb/node-bindings@1.4.4-r.4", "", { "optionalDependencies": { "@duckdb/node-bindings-darwin-arm64": "1.4.4-r.4", "@duckdb/node-bindings-darwin-x64": "1.4.4-r.4", "@duckdb/node-bindings-linux-arm64": "1.4.4-r.4", "@duckdb/node-bindings-linux-x64": "1.4.4-r.4", "@duckdb/node-bindings-win32-arm64": "1.4.4-r.4", "@duckdb/node-bindings-win32-x64": "1.4.4-r.4" } }, "sha512-JYjCaZmqvqrjFBjT3Q6jnb3OFz26lAUTFXUka/HQRxWRy23ZiURZwPYMLkyFBLHa696hNlC85M/EWXDRFnDIfg=="], - - "@duckdb/node-bindings-darwin-arm64": ["@duckdb/node-bindings-darwin-arm64@1.4.4-r.4", "", { "os": "darwin", "cpu": "arm64" }, "sha512-ozQbuBlV+01WzyXcqXjEV3TbN+qQ8UcelwPmQaqBn86pdXQHuYGuS8K9a5yATsg+JvivqHQSb95OBHdP7FYDkA=="], - - "@duckdb/node-bindings-darwin-x64": ["@duckdb/node-bindings-darwin-x64@1.4.4-r.4", "", { "os": "darwin", "cpu": "x64" }, "sha512-quoPmg26/fpLM80UNMXYSYKGnXJUiqKTSlDIgONQiMVYXJqPc2yz9qwcTuZgaQx7JhD2m1D/cc+h/4d8yVD79Q=="], - - "@duckdb/node-bindings-linux-arm64": ["@duckdb/node-bindings-linux-arm64@1.4.4-r.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-Ve+kJ9+IqF5VBNWDzlUeg1xxKGHGqT9MJPxjRTSULgCpguL9ok13Klhw7WJQOs5ycB+osQe/40t5hOZk3cK82g=="], - - "@duckdb/node-bindings-linux-x64": ["@duckdb/node-bindings-linux-x64@1.4.4-r.4", "", { "os": "linux", "cpu": "x64" }, "sha512-jBTL/WvfwxLToFa/pVHfT6elMtltJGnc3wSuxZD9OfMltit9YUdVFS37vBFQzXMT1Z8OWjtSjMh+zPKxOwHLHA=="], - - "@duckdb/node-bindings-win32-arm64": ["@duckdb/node-bindings-win32-arm64@1.4.4-r.4", "", { "os": "win32", "cpu": "arm64" }, "sha512-4tqE7r1c4wCqgm1iBfW/rP6B67nkHK1Pyj6dT8T3aqupKk2eV0QgKPBYtGOqOlE+jdhj4El9WKye7eTJ59yjZQ=="], - - "@duckdb/node-bindings-win32-x64": ["@duckdb/node-bindings-win32-x64@1.4.4-r.4", "", { "os": "win32", "cpu": "x64" }, "sha512-lclo7ZibsYuCHd0ru5j9sw9x+wfXWOiNWIOjW3rcX9675xD7j4CB3RlWfZkBgdajLuXtRuo5FFfQZY249a7IlA=="], - "@esbuild/android-arm": ["@esbuild/android-arm@0.18.20", "", { "os": "android", "cpu": "arm" }, "sha512-fyi7TDI/ijKKNZTUJAQqiG5T7YjJXgnzkURqmGj13C6dCqckZBLdl4h7bkhHt/t0WP+zO9/zwroDvANaOqO5Sw=="], "@esbuild/android-arm64": ["@esbuild/android-arm64@0.18.20", "", { "os": "android", "cpu": "arm64" }, "sha512-Nz4rJcchGDtENV0eMKUNa6L12zz2zBDXuhj/Vjh18zGqB44Bi7MBMSXjgunJgjRhCmKOjnPuZp4Mb6OKqtMHLQ=="], @@ -731,8 +704,6 @@ "@stock-bot/di": ["@stock-bot/di@workspace:libs/core/di"], - "@stock-bot/duckdb": ["@stock-bot/duckdb@workspace:libs/data/duckdb"], - "@stock-bot/engine": ["@stock-bot/engine@workspace:apps/stock/engine"], "@stock-bot/handler-registry": ["@stock-bot/handler-registry@workspace:libs/core/handler-registry"], diff --git a/database/postgres/init/37-research-findings.sql b/database/postgres/init/37-research-findings.sql deleted file mode 100644 index b4c800ac..00000000 --- a/database/postgres/init/37-research-findings.sql +++ /dev/null @@ -1,99 +0,0 @@ --- Research findings & provider caveats schema (M2.1i) --- Research track migration: creates append-only findings and provider_caveats tables, --- lookup/idempotency indexes, and immutability triggers reusing --- reject_research_evidence_mutation() from 17-research-retention.sql. - -CREATE OR REPLACE FUNCTION research_trim_ecmascript(value TEXT) -RETURNS TEXT -LANGUAGE SQL -IMMUTABLE -STRICT -AS $$ - -- Explicit ECMAScript WhiteSpace + LineTerminator set so nonblank checks and - -- trimmed length caps match String.prototype.trim() regardless of DB collation. - SELECT btrim( - value, - U&'\0009\000A\000B\000C\000D\0020\00A0\1680\2000\2001\2002\2003\2004\2005\2006\2007\2008\2009\200A\2028\2029\202F\205F\3000\FEFF' - ); -$$; - -CREATE OR REPLACE FUNCTION research_finding_refs_valid(refs TEXT[], max_len INTEGER) -RETURNS BOOLEAN -LANGUAGE SQL -IMMUTABLE -STRICT -AS $$ - SELECT COALESCE(array_ndims(refs), 1) = 1 - AND NOT EXISTS ( - SELECT 1 - FROM unnest(refs) AS r - WHERE r IS NULL - OR char_length(r) > max_len - ); -$$; - -CREATE TABLE IF NOT EXISTS findings ( - id TEXT PRIMARY KEY - CHECK (research_trim_ecmascript(id) <> ''), - kind TEXT NOT NULL - CHECK (kind IN ('finding', 'dead_end')), - title TEXT NOT NULL - CHECK (char_length(research_trim_ecmascript(title)) BETWEEN 1 AND 256), - summary TEXT NOT NULL - CHECK (char_length(research_trim_ecmascript(summary)) BETWEEN 1 AND 4096), - status TEXT NOT NULL DEFAULT 'pending_review' - CHECK (research_trim_ecmascript(status) <> ''), - created_at TIMESTAMPTZ NOT NULL, - trial_refs TEXT[] NOT NULL - CHECK (cardinality(trial_refs) <= 32) - CHECK (COALESCE(array_ndims(trial_refs), 1) = 1) - CHECK (research_finding_refs_valid(trial_refs, 256)), - evidence_refs TEXT[] NOT NULL - CHECK (cardinality(evidence_refs) <= 32) - CHECK (COALESCE(array_ndims(evidence_refs), 1) = 1) - CHECK (research_finding_refs_valid(evidence_refs, 256)), - idempotency_key TEXT - CHECK (idempotency_key IS NULL OR (research_trim_ecmascript(idempotency_key) <> '' AND char_length(idempotency_key) BETWEEN 1 AND 128)) -); - -CREATE UNIQUE INDEX IF NOT EXISTS idx_findings_idempotency_key - ON findings (idempotency_key) - WHERE idempotency_key IS NOT NULL; - -CREATE INDEX IF NOT EXISTS idx_findings_created_at - ON findings (created_at); - -CREATE TABLE IF NOT EXISTS provider_caveats ( - id TEXT PRIMARY KEY - CHECK (research_trim_ecmascript(id) <> ''), - provider TEXT NOT NULL - CHECK (research_trim_ecmascript(provider) <> ''), - dataset TEXT NOT NULL - CHECK (research_trim_ecmascript(dataset) <> ''), - caveat TEXT NOT NULL - CHECK (research_trim_ecmascript(caveat) <> ''), - created_at TIMESTAMPTZ NOT NULL DEFAULT now() -); - -CREATE INDEX IF NOT EXISTS idx_provider_caveats_lower_provider - ON provider_caveats (lower(provider)); - -DROP TRIGGER IF EXISTS findings_retained ON findings; -CREATE TRIGGER findings_retained - BEFORE UPDATE OR DELETE ON findings - FOR EACH ROW EXECUTE FUNCTION reject_research_evidence_mutation(); - -DROP TRIGGER IF EXISTS findings_no_truncate ON findings; -CREATE TRIGGER findings_no_truncate - BEFORE TRUNCATE ON findings - FOR EACH STATEMENT EXECUTE FUNCTION reject_research_evidence_mutation(); - -DROP TRIGGER IF EXISTS provider_caveats_retained ON provider_caveats; -CREATE TRIGGER provider_caveats_retained - BEFORE UPDATE OR DELETE ON provider_caveats - FOR EACH ROW EXECUTE FUNCTION reject_research_evidence_mutation(); - -DROP TRIGGER IF EXISTS provider_caveats_no_truncate ON provider_caveats; -CREATE TRIGGER provider_caveats_no_truncate - BEFORE TRUNCATE ON provider_caveats - FOR EACH STATEMENT EXECUTE FUNCTION reject_research_evidence_mutation(); diff --git a/design/DATA-CONTRACTS.md b/design/DATA-CONTRACTS.md index 837da47a..bec7f246 100644 --- a/design/DATA-CONTRACTS.md +++ b/design/DATA-CONTRACTS.md @@ -22,7 +22,7 @@ Authoritative specification for `data-pipeline`, PostgreSQL reference schemas, D | `eodFinancialsOLD` (`2.98M`), `eodFundamentalsOLD` (`106.6k`) | `eodFinancialsOLD` sets `filingDate == reportDate` on **`99.26%`** of rows. `eodFundamentalsOLD` has `filing_date: null`, unversioned current valuation ratios, and mislabels USD figures as `"CAD"` on NEO CDRs (`AAPL` CDR `$335B` assets). | **Quarantine `eodFundamentalsOLD` `Highlights`/`Valuation` from all backtests.** Use `eodFinancialsOLD` only for pre-QM historical backfill with mandatory statutory lag (ignoring its `filingDate`). | | `qmFilings` (`30.52M`) | Has exact second-level `timefiled` (`"2025-01-31T06:01:27 EST"`) for both US EDGAR (`10-Q`, `10-K`, `8-K`, `4`, `144`) and **Canadian SEDAR+** (`Interim financial statements/report`, `Annual financial statements`, `MD&A`, `52-109`, `NI 43-101`, `45-106F1`). Metadata + external download URLs only (no parsed Form 4 share counts). | Primary `known_at` clock for `qmFinancials` and `qmEarnings`, plus standalone filing-arrival/form-type event stream. Convert `EST`/`EDT` strings cleanly using `America/New_York` rules. | | `qmEarnings` (`444.9k`) | `66.94%` (`297,779`) have `announceTime="N/A"` (`80,481` `AMC`, `66,605` `BTO`); `consensusEps` is overwritten post-hoc. | Link to same-day `qmFilings` `8-K` / `News release` `timefiled`; if still unknown, set `known_at = reportDate 16:05 ET` (tradable `T+1` open). | -| `qmDividends` (`495.9k`), `qmSplits` (`18.8k`), `eodSymbolChange` (`230`) | `qmDividends`: `82.3%` have `declared < date`, bogus `usdFxRate: 1` on CAD rows. `qmSplits`: `30.1%` have `declared`, `258` have `splitratio == 1`; empirically across `16,892/16,892` rows with numeric `forfactor`/`tofactor` (`100%`), QuoteMedia stores `splitratio = forfactor / tofactor = old_shares / new_shares` (e.g. `NVDA 2024-06-10`: `forfactor=1, tofactor=10, splitratio=0.1`; `GE 2021-08-02`: `forfactor=8, tofactor=1, splitratio=8`). `eodSymbolChange`: only `230` US rows (`2024-08..2025-07`). | Filter `splitratio == 1`; ignore `usdFxRate`; invert QuoteMedia `qmSplits` to canonical `new_shares / old_shares` via `tofactor / forfactor` when both are positive numbers (avoiding 6-decimal truncation like `0.142857` for 7:1) else `1 / splitratio`; never rely on `eodSymbolChange` for multi-year ticker history. | +| `qmDividends` (`495.9k`), `qmSplits` (`18.8k`), `eodSymbolChange` (`230`) | `qmDividends`: `82.3%` have `declared < date`, bogus `usdFxRate: 1` on CAD rows. `qmSplits`: `30.1%` have `declared`, `258` have `splitratio == 1`. `eodSymbolChange`: only `230` US rows (`2024-08..2025-07`). | Filter `splitratio == 1`; ignore `usdFxRate`; never rely on `eodSymbolChange` for multi-year ticker history. | | `teData` (`14.8k`), `teMarketData` (`435`), `CAD.FOREX` | `teData` has `{d, v}` final-revised values only (no release dates/vintages). `CAD.FOREX` (`eodPrices` `12,109` 1d, `eodIntraday1M` `5.20M` 1m) + `teMarketData.USDCAD` (`2,865` 1d through Apr 2026) already provide complete USD/CAD history. | Lag `teData` (`+1d` central-bank rates, `+35d` monthly CPI/NFP, `+65d/+90d` GDP) for coarse regime filters only. Curate `CAD.FOREX` + `teMarketData.USDCAD` directly into `fx_1d` and `fx_1m`. | --- @@ -184,75 +184,6 @@ CREATE INDEX IF NOT EXISTS idx_instrument_identifier_history_instrument_id `override` is keyed by `(source, source_id, valid_from)` and applied last with precedence `1.000`. The minimal definitions for `resolution_conflict`, `override`, and `golden_field_audit` above are open to revision as M1 Passes 1–6 are built. -### M1 `>= 95%` US/CA Equity Resolution Gate Denominator - -The M1 exit gate evaluates **gate-eligible US/CA common equities & ETFs on EODHD-covered venues** (`XNYS`, `XNAS`, `ARCX`, `XASE`, `BATS`, `OTCM`, `XTSE`, `XTSX`, `NEOE`). Every match report preserves raw catalog totals (`Total`, `Resolved %`) alongside explicit itemized exclusions: - -- **`Excluded by Design`:** `excluded_fund` (`NMFQS`, `NMF`), `composite_venue` (`US`, `TSXC`, `TSXVC`), `ats_routing_venue` (`EDGX`), and `forex_venue` (`FOREX`). -- **`Out of Gate Scope`:** - 1. `zero_bar_catalog_ghost` — secondary ticker-only rows (`qm`) with `missing_span` (`0` bars in `qmPrices`), which Stage B intentionally refuses to match to prevent ticker-reuse corruption (`FB`). - 2. `uncovered_venue` — listings on exchanges absent from the EODHD bar master (`XCNQ` Canadian Securities Exchange across `qm`, `ceo`, and `ib:AEQLIT`, plus `ceo:NEOE` where EODHD carries only 19 of 587 listings). - 3. `non_equity_instrument` — non-common-equity instruments & test tickers (warrants `.WT`/`.WS`, convertible debentures `.DB`, subscription receipts/rights `.R`/`.RT`, SPAC/REIT units `.U`/`.UN`, preferred shares `.PR*`/`-P*`, TSXV NEX inactive shells `.H`, TSXV CPCs `.P`, and exchange test symbols). - -### Research Knowledge & Findings Schema (PostgreSQL, Append-Only) - -Applied via `@stock-bot/postgres` (`research` migration track, `database/postgres/init/37-research-findings.sql`, immediately after `36-trial-ledger.sql`). Owned by Stock Bot research alongside `trial_ledger` and `vault_evaluations` (see [`design/VALIDATION-AND-RIGOR.md`](VALIDATION-AND-RIGOR.md) §2A and §3 for those tables). - -- **Research-visible boundary:** `findings` and `provider_caveats` store research-visible empirical evidence only. Callers and MCP adapters (`file_finding`, `read_knowledge`) are responsible for verifying that every `trial_ref` belongs to the research-visible `trial_ledger` and for excluding Vault holdout observations or Vault-only evidence from stored text and opaque `evidence_refs`. -- **Append-only enforcement:** Both tables reuse `reject_research_evidence_mutation()` from `17-research-retention.sql` via row-level `BEFORE UPDATE OR DELETE` (`findings_retained`, `provider_caveats_retained`) and statement-level `BEFORE TRUNCATE` (`findings_no_truncate`, `provider_caveats_no_truncate`) triggers, raising SQLSTATE `23514` on any mutation attempt. -- **Character-length & whitespace convention:** SQL `CHECK` constraints enforce PostgreSQL `char_length(...)` (Unicode code points) matching the MCP tool caps (`title` trimmed `1..256`, `summary` trimmed `1..4096`, each ref `<= 256`, `idempotency_key` `1..128`). Nonblank and trimmed-length checks use `research_trim_ecmascript(...)`, which strips the explicit 25-character ECMAScript `WhiteSpace` + `LineTerminator` set (`U+0009`..`U+000D`, `U+0020`, `U+00A0`, `U+1680`, `U+2000`..`U+200A`, `U+2028`, `U+2029`, `U+202F`, `U+205F`, `U+3000`, `U+FEFF`) regardless of database collation. JavaScript/Zod validation counts UTF-16 code units, which can reach the same numeric limit sooner for supplementary Unicode characters. - -```sql -CREATE TABLE IF NOT EXISTS findings ( - id TEXT PRIMARY KEY - CHECK (research_trim_ecmascript(id) <> ''), - kind TEXT NOT NULL - CHECK (kind IN ('finding', 'dead_end')), - title TEXT NOT NULL - CHECK (char_length(research_trim_ecmascript(title)) BETWEEN 1 AND 256), - summary TEXT NOT NULL - CHECK (char_length(research_trim_ecmascript(summary)) BETWEEN 1 AND 4096), - status TEXT NOT NULL DEFAULT 'pending_review' - CHECK (research_trim_ecmascript(status) <> ''), - created_at TIMESTAMPTZ NOT NULL, - trial_refs TEXT[] NOT NULL - CHECK (cardinality(trial_refs) <= 32) - CHECK (COALESCE(array_ndims(trial_refs), 1) = 1) - CHECK (research_finding_refs_valid(trial_refs, 256)), - evidence_refs TEXT[] NOT NULL - CHECK (cardinality(evidence_refs) <= 32) - CHECK (COALESCE(array_ndims(evidence_refs), 1) = 1) - CHECK (research_finding_refs_valid(evidence_refs, 256)), - idempotency_key TEXT - CHECK (idempotency_key IS NULL OR (research_trim_ecmascript(idempotency_key) <> '' AND char_length(idempotency_key) BETWEEN 1 AND 128)) -); - -CREATE UNIQUE INDEX IF NOT EXISTS idx_findings_idempotency_key - ON findings (idempotency_key) - WHERE idempotency_key IS NOT NULL; - -CREATE INDEX IF NOT EXISTS idx_findings_created_at - ON findings (created_at); - -CREATE TABLE IF NOT EXISTS provider_caveats ( - id TEXT PRIMARY KEY - CHECK (research_trim_ecmascript(id) <> ''), - provider TEXT NOT NULL - CHECK (research_trim_ecmascript(provider) <> ''), - dataset TEXT NOT NULL - CHECK (research_trim_ecmascript(dataset) <> ''), - caveat TEXT NOT NULL - CHECK (research_trim_ecmascript(caveat) <> ''), - created_at TIMESTAMPTZ NOT NULL DEFAULT now() -); - -CREATE INDEX IF NOT EXISTS idx_provider_caveats_lower_provider - ON provider_caveats (lower(provider)); -``` - -- **Reference arrays (`trial_refs`, `evidence_refs`):** Stored as opaque 1-dimensional `TEXT[]` arrays (empty arrays permitted via `COALESCE(array_ndims(...), 1) = 1`, max 32 entries each, no `NULL` elements, max 256 chars per entry enforced via `research_finding_refs_valid`). Reference normalization, deduplication, minimum `trial_refs` count, and research-visibility checks remain in the MCP tool/adapter layer. -- **Indexes:** `idx_findings_idempotency_key` (partial unique `WHERE idempotency_key IS NOT NULL`) supports atomic compare-and-append idempotency while allowing multiple `NULL` keys; `idx_findings_created_at` supports chronological listing; `idx_provider_caveats_lower_provider` supports case-insensitive provider filtering in `read_knowledge`. - --- ## 3. Curated Storage Schemas @@ -276,9 +207,9 @@ Schemas: - **`adj_factors/part.parquet`**: `(listing_id INT32, ex_date DATE, split_factor DOUBLE, div_cash DOUBLE, div_currency VARCHAR, cum_split_factor DOUBLE, cum_total_factor DOUBLE, known_at TIMESTAMPTZ)`. - **`corporate_actions/part.parquet`**: `(listing_id INT32, ex_date DATE, declared_date DATE, kind VARCHAR, ratio DOUBLE, cash_amount DOUBLE, currency VARCHAR, successor_listing_id INT32, terminal_return DOUBLE, known_at TIMESTAMPTZ, known_at_source VARCHAR)`. - **`fundamentals_bitemporal/part.parquet`**: `(listing_id INT32, period_end DATE, fiscal_period VARCHAR, currency VARCHAR, known_at TIMESTAMPTZ, known_at_source VARCHAR, )`. -- **`fundamentals_pit/year=YYYY/part.parquet`**: Pre-resolved point-in-time snapshots partitioned by the UTC year of `effective_known_at`, sorted and unique by `(listing_id, effective_known_at)`: `(listing_id INT32 NOT NULL, effective_known_at TIMESTAMPTZ NOT NULL, known_at_source VARCHAR NOT NULL, has_estimated_lag BOOLEAN NOT NULL, period_end DATE NOT NULL, fiscal_period VARCHAR NOT NULL, currency VARCHAR NOT NULL, period_known_at TIMESTAMPTZ NOT NULL, revenue DOUBLE, net_income DOUBLE, operating_cash_flow DOUBLE, total_assets DOUBLE, total_equity DOUBLE, shares_outstanding DOUBLE, ttm_period_end DATE, ttm_currency VARCHAR, ttm_revenue DOUBLE, ttm_net_income DOUBLE, ttm_operating_cash_flow DOUBLE, ttm_has_estimated_lag BOOLEAN)` (all `ttm_*` columns are `NULL` when 4 consecutive standalone quarters in one currency are unavailable). Each snapshot computes: +- **`fundamentals_pit/year=YYYY/part.parquet`**: Wide pre-resolved point-in-time snapshots keyed by `(listing_id INT32, effective_known_at TIMESTAMPTZ)` where each row computes: $$\text{latest } k \text{ periods by } \texttt{period\_end} \text{ of } \left(\arg\max_{\texttt{known\_at} \le \texttt{effective\_known\_at}} \text{ per } (\texttt{listing\_id}, \texttt{period\_end})\right)$$ - forward-filling un-restated fields and precomputing 4-quarter TTM sums so a restatement of Q1 never overwrites Q2; the physical Parquet row flattens the latest visible resolved period (`periods[0]`) alongside the precomputed `ttm_*` columns (lagged slots `periods[1..]` are omitted). + forward-filling un-restated fields and precomputing 4-quarter TTM sums so a restatement of Q1 never overwrites Q2. - **`events/year=YYYY/part.parquet`**: `(listing_id INT32, ts TIMESTAMPTZ, known_at TIMESTAMPTZ, known_at_source VARCHAR, kind VARCHAR, subtype VARCHAR, payload_json VARCHAR)`. - **`shorts/part.parquet`**: `(listing_id INT32, report_date DATE, known_at TIMESTAMPTZ, shares_short DOUBLE, net_change DOUBLE, pct_float DOUBLE, source VARCHAR)`. - **`macro/part.parquet`**: `(country_iso VARCHAR, indicator VARCHAR, period_date DATE, known_at TIMESTAMPTZ, known_at_source VARCHAR, value DOUBLE)`. diff --git a/design/README.md b/design/README.md index c7dfa150..0157ab05 100644 --- a/design/README.md +++ b/design/README.md @@ -13,9 +13,6 @@ Start here. Every document below has a single responsibility; historical sprint | **[DATA-CONTRACTS.md](DATA-CONTRACTS.md)** | Raw MongoDB provider quirks, PostgreSQL security-master DDL, split/volume un-adjustment rules, `known_at` derivation, DuckDB/Parquet & QuestDB `10.2.0` schemas, and `MarketDataStore` API | Before touching `data-pipeline`, `data-ingestion`, SQL migrations, or `MarketDataStore` | | **[VALIDATION-AND-RIGOR.md](VALIDATION-AND-RIGOR.md)** | Canonical metric definitions, `trial_ledger` schema, effective-trials DSR ($\hat{N}$), CSCV PBO, Purged CPCV/Walk-Forward, rolling 6-month Vault + Post-2023 Recency Gate, lifecycle gates, and Dual Live Drift + IB/TSX execution rules | Before touching `libs/calculations`, `libs/research`, validation workflows, or paper/live execution | | **[servers.md](servers.md)** | Host roles (`quant` `12900K` research/data server, `9900K` isolated IB live/paper host, `TrueNAS` cold storage, dev workstation) and port/storage layout | Infrastructure, deployment, and worker sizing | -| **[data-pipeline/rust-migration-evaluation.md](data-pipeline/rust-migration-evaluation.md)** | Evidence-based evaluation of keeping `apps/stock/data-pipeline` in TypeScript vs. moving bulk MongoDB streaming or the full pipeline into Rust (`tools/curate-etl`) | Before `M2` adds PIT fundamentals, `ceoPosts`, or `bars_1m` QuestDB ingestion | -| **[m2-completion-audit.md](m2-completion-audit.md)** | Historical read-only Milestone `M2` completion audit prior to `T-205`–`T-207` (`T-204`; superseded by `m2-master-audit.md`) | Historical reference for pre-`T-205` M2 state | -| **[m2-master-audit.md](m2-master-audit.md)** | Current read-only Milestone `M2` audit against `master` (post-`T-205`/`T-206`/`T-207`), Done/Partial/Missing matrix, director trade-offs, and 7-task M2 closure backlog (`T-208`) | Before closing `M2`, queuing remaining `M2` tasks, or starting `M3` | --- diff --git a/design/data-pipeline/m1-ca-study-result.json b/design/data-pipeline/m1-ca-study-result.json deleted file mode 100644 index 1817e036..00000000 --- a/design/data-pipeline/m1-ca-study-result.json +++ /dev/null @@ -1,78 +0,0 @@ -{ - "summary": { - "adjustment": "total", - "ca_bars_rows": 8446226, - "ca_shorts_rows": 459930, - "ca_filings_rows": 725435, - "shorts_panel_rows": 4541173, - "vault_bar_leaks": 0 - }, - "shorts_trial": { - "trial_id": 1, - "created_at": "2026-11-30T15:16:14.251727+00:00", - "expression_hash": "b8d63783a3803087c922ce7fe332340264db340f8d7de1b78cfaab097c17e938", - "n_obs": 1983, - "sharpe_unann": 0.10055685659710986, - "skewness": -0.1559440430924711, - "kurtosis": 15.987384989738644 - }, - "shorts_dsr": { - "trial_id": 1, - "cluster_size": 1, - "effective_trials": 1.0, - "mean_correlation": null, - "pairs_used": 0, - "pairs_skipped": 0, - "sr0": 0.0, - "standard_error": 0.023055762683025283, - "dsr": 0.9999935402185955, - "passes_gate": true - }, - "shorts_mean_rank_ic": 0.00694633488509233, - "shorts_rank_ic_nw_t": 2.7256714674429414, - "shorts_mean_spread": 0.010679776876364164, - "shorts_turnover": 0.40718536083796214, - "shorts_recency": { - "pass": true, - "reason": "passed", - "pre_n": 1456, - "post_n": 527, - "pre_mean": 0.006950115972062361, - "post_mean": 0.006935888466442682, - "ratio": 0.9979529110482659 - }, - "filings_trial": { - "trial_id": 2, - "created_at": "2026-11-30T15:16:17.977209+00:00", - "expression_hash": "c642ca87d95bb8436045ba34a231096d74df559f0e3baf91962ba0adbe3151da", - "n_obs": 885, - "sharpe_unann": -0.08030767099801248, - "skewness": -9.933468390420595, - "kurtosis": 115.43676350904063 - }, - "filings_dsr": { - "trial_id": 2, - "cluster_size": 2, - "effective_trials": 2.0, - "mean_correlation": null, - "pairs_used": 0, - "pairs_skipped": 1, - "sr0": 0.06647178849749248, - "standard_error": 0.02091720841503682, - "dsr": 1.1320926489926893e-12, - "passes_gate": false - }, - "filings_events_used": 101522, - "filings_n_dates": 885, - "filings_car_mean": -0.022160113638103773, - "filings_car_nw_t": -1.1695875860209246, - "filings_recency": { - "pass": false, - "reason": "sign_flipped", - "pre_n": 615, - "post_n": 270, - "pre_mean": 0.002165839268979803, - "post_mean": -0.07756922859312747, - "ratio": -35.81485925761503 - } -} diff --git a/design/data-pipeline/m1-quant-benchmark-result.json b/design/data-pipeline/m1-quant-benchmark-result.json deleted file mode 100644 index 06059bc2..00000000 --- a/design/data-pipeline/m1-quant-benchmark-result.json +++ /dev/null @@ -1,117 +0,0 @@ -{ - "host": "quant", - "curated_root": "/mnt/data/stockbot/m1-isolated/curated", - "duckdb_version": "1.5.6", - "polars_version": "1.44.2", - "duckdb_budget": { - "memory_limit": "6GB", - "threads": 4, - "temp_directory": "/mnt/data/stockbot/m1-isolated/tmp/duckdb" - }, - "cache_state_note": "run1_fresh_conn runs on a brand-new DuckDB process/connection with no prior queries; run2_warm_conn reuses the warm DuckDB connection. Unprivileged execution does not drop Linux kernel OS page cache (/proc/sys/vm/drop_caches requires root).", - "vault_cutoff_date": "2025-02-13", - "vault_rows_on_disk": 3363755, - "total_rows_in_scan": 78588295, - "distinct_listings_in_scan": 59096, - "scan_date_min": "2005-01-03", - "scan_date_max": "2025-02-12", - "nvda_pre_split_check": { - "listing_id": 20815, - "pre_split_2024_06_07": { - "close": 1208.88, - "raw_volume": 41238577.6, - "dollar_volume": 49852491689.088005, - "currency": "USD" - }, - "post_split_2024_06_10": { - "close": 121.79, - "raw_volume": 314162688.0, - "dollar_volume": 38261873771.520004, - "currency": "USD" - }, - "qm_pre_split_dollar_volume": 49852494590.4, - "rel_diff": 5.81979301196025e-08, - "within_1pct": true - }, - "parquet_scan_vault_audit": { - "explain_analyze_latency_secs": 4.2861, - "total_files_read": 21, - "parquet_scan_rows_emitted": 78592209, - "pushed_filters": [ - "session_date>='2005-01-01'::DATE AND session_date<'2025-02-13'::DATE", - "ts<'2025-02-13 00:00:00+00'::TIMESTAMP WITH TIME ZONE", - "known_at<'2025-02-13 00:00:00+00'::TIMESTAMP WITH TIME ZONE", - "optional: currency IN ('USD', 'CAD')", - "close>0.0", - "volume>0.0" - ], - "vault_session_date_pushed": true, - "vault_ts_pushed": true, - "vault_known_at_pushed": true - }, - "poisoned_vault_canary": { - "overlay_files_on_disk": 22, - "overlay_files_read_by_parquet_scan": 21, - "year_2026_partition_pruned": true, - "poisoned_vault_rows_on_disk": 3373755, - "canary_parquet_scan_rows_emitted": 78592209, - "scan_cardinality_identical": true, - "signal_metrics_bit_identical": true, - "pass": true - }, - "run1_fresh_conn": { - "wall_secs": 4.4122, - "sql_secs": 4.4088, - "post_secs": 0.0033, - "under_5s": true, - "min_date": "2005-02-01", - "max_date": "2025-02-05", - "vault_cutoff_date": "2025-02-13", - "n_sessions_evaluated": 5129, - "mean_ic": 0.018401, - "mean_q5_q1_spread": 0.001329, - "mean_q5_turnover": 0.23419, - "recency_gate": { - "pass": true, - "reason": "passed", - "pre_n": 4592, - "post_n": 537, - "pre_mean": 0.018166680678707872, - "post_mean": 0.020400683140664375, - "ratio": 1.1229725177354413 - }, - "sharpe_unann": 0.05117, - "sharpe_ann": 0.8123, - "newey_west_t_stat": 2.0292, - "newey_west_p_value": 0.042434, - "dsr": 0.999927 - }, - "run2_warm_conn": { - "wall_secs": 4.3086, - "sql_secs": 4.3071, - "post_secs": 0.0015, - "under_5s": true, - "min_date": "2005-02-01", - "max_date": "2025-02-05", - "vault_cutoff_date": "2025-02-13", - "n_sessions_evaluated": 5129, - "mean_ic": 0.018401, - "mean_q5_q1_spread": 0.001329, - "mean_q5_turnover": 0.23419, - "recency_gate": { - "pass": true, - "reason": "passed", - "pre_n": 4592, - "post_n": 537, - "pre_mean": 0.018166680678707872, - "post_mean": 0.02040068314066438, - "ratio": 1.1229725177354415 - }, - "sharpe_unann": 0.05117, - "sharpe_ann": 0.8123, - "newey_west_t_stat": 2.0292, - "newey_west_p_value": 0.042434, - "dsr": 0.999927 - }, - "both_runs_under_5s": true -} diff --git a/design/data-pipeline/m1-source-field-shapes.md b/design/data-pipeline/m1-source-field-shapes.md deleted file mode 100644 index 429b3236..00000000 --- a/design/data-pipeline/m1-source-field-shapes.md +++ /dev/null @@ -1,167 +0,0 @@ -# Source Field Shapes Report - -- **Scope:** bounded sample, not a full scan (head sample via `find().limit()`, no aggregation or `$sample`) -- **Sample limit per collection:** 1000 -- **Collections probed:** 8 -- **Total documents sampled:** 7435 - -## `ceoShorts` (1000 docs sampled) - -| Field | Presence | Types | String Patterns | Examples | -| --- | --- | --- | --- | --- | -| `_id` | 100.0% (1000/1000) | objectId: 1000 | — | — | -| `created_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-06-23T03:58:26.303Z`, `2025-06-23T03:58:27.035Z`, `2025-06-23T03:58:27.655Z` | -| `id` | 100.0% (1000/1000) | int: 1000 | — | `101986246`, `101986286`, `101986333` | -| `issue_name` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 18..37) | `AAJ CAPITAL 3 CORP.`, `ABERDEEN INTERNATIONAL INC. J`, `ADDED CAPITAL INC.` | -| `market` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 1..2) | `TO`, `V` | -| `net_change` | 100.0% (1000/1000) | int: 1000 | — | `-10`, `-100`, `-1000` | -| `number_of_shares` | 100.0% (1000/1000) | int: 1000 | — | `0`, `1`, `10` | -| `symbol` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 3..12) | `A.V`, `AA.V`, `AAA-P.V` | -| `timestamp` | 100.0% (1000/1000) | double: 1000 | — | `1492239600000`, `1493535600000`, `1494831600000` | -| `updated_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-06-26T19:28:57.102Z`, `2025-06-26T19:28:57.127Z`, `2025-06-26T19:28:57.129Z` | - -## `eodPrices` (1000 docs sampled) - -| Field | Presence | Types | String Patterns | Examples | -| --- | --- | --- | --- | --- | -| `_id` | 100.0% (1000/1000) | objectId: 1000 | — | — | -| `adjustedClose` | 100.0% (1000/1000) | double: 1000 | — | `0.000001999999995`, `0.0000030000001061`, `0.0000039999999899` | -| `close` | 100.0% (1000/1000) | double: 1000 | — | `0.000001999999995`, `0.0000030000001061`, `0.0000039999999899` | -| `created_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-07-11T02:13:56.412Z`, `2025-07-11T02:13:56.492Z`, `2025-07-11T02:13:56.694Z` | -| `date` | 100.0% (1000/1000) | string: 1000 | ymd: 1000 (len 10..10) | `2020-12-19`, `2020-12-20`, `2020-12-21` | -| `eodSearchCode` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 11..14) | `$ADS-USD.CC`, `$AFLOKI-USD.CC`, `$ANRX-USD.CC` | -| `exchange` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 2..2) | `CC` | -| `high` | 100.0% (1000/1000) | double: 1000 | — | `0.000001999999995`, `0.0000030000001061`, `0.0000039999999899` | -| `low` | 100.0% (1000/1000) | double: 1000 | — | `0.000001999999995`, `0.0000030000001061`, `0.0000039999999899` | -| `open` | 100.0% (1000/1000) | double: 1000 | — | `0.000001999999995`, `0.0000030000001061`, `0.0000039999999899` | -| `symbol` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 8..11) | `$ADS-USD`, `$AFLOKI-USD`, `$ANRX-USD` | -| `updated_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-08-13T14:09:20.036Z`, `2025-08-13T14:09:20.106Z`, `2025-08-13T14:09:20.135Z` | -| `volume` | 100.0% (1000/1000) | int: 1000 | — | `0`, `1000242`, `1006139` | - -## `qmDividends` (1000 docs sampled) - -| Field | Presence | Types | String Patterns | Examples | -| --- | --- | --- | --- | --- | -| `_id` | 100.0% (1000/1000) | objectId: 1000 | — | — | -| `amount` | 100.0% (1000/1000) | int: 10, double: 990 | — | `0`, `0.01`, `0.01167` | -| `created_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-06-29T22:22:20.799Z`, `2025-06-29T22:25:29.068Z`, `2025-06-29T22:25:29.069Z` | -| `currency` | 92.8% (928/1000) | string: 928 | other: 928 (len 3..3) | `CAD`, `USD` | -| `date` | 100.0% (1000/1000) | string: 1000 | ymd: 1000 (len 10..10) | `1987-03-31`, `1987-06-01`, `1987-06-25` | -| `declared` | 96.5% (965/1000) | string: 965 | ymd: 965 (len 10..10) | `1987-03-25`, `1987-05-21`, `1987-05-27` | -| `divflag` | 6.2% (62/1000) | string: 62 | other: 62 (len 2..2) | `EX`, `FI`, `SP` | -| `divtype` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 1..1) | `D`, `S` | -| `exchange` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 3..3) | `NGS`, `NSC`, `NSD` | -| `frequency` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 1..1) | `A`, `I`, `M` | -| `indicatedrate` | 66.0% (660/1000) | double: 660 | — | `0.01`, `0.01167`, `0.0125` | -| `payable` | 99.7% (997/1000) | string: 997 | ymd: 997 (len 10..10) | `1987-04-20`, `1987-07-01`, `1987-07-20` | -| `qmSearchCode` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 2..9) | `DBM:CA`, `DCM:CA`, `DHT.U:CA` | -| `qualified` | 22.6% (226/1000) | string: 226 | other: 226 (len 1..1) | `N`, `Q` | -| `record` | 99.6% (996/1000) | string: 996 | ymd: 996 (len 10..10) | `1987-04-06`, `1987-06-05`, `1987-07-01` | -| `reportDate` | 100.0% (1000/1000) | date: 1000 | — | `1987-03-31T00:00:00.000Z`, `1987-06-01T00:00:00.000Z`, `1987-06-25T00:00:00.000Z` | -| `symbol` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 1..8) | `DBM`, `DCM`, `DHT.U` | -| `updated_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-06-29T22:25:29.080Z`, `2025-06-29T22:25:29.146Z`, `2025-06-29T22:25:29.148Z` | -| `usdFxRate` | 25.6% (256/1000) | int: 253, double: 3 | — | `0.05`, `1`, `1.39556` | - -## `qmEarnings` (1000 docs sampled) - -| Field | Presence | Types | String Patterns | Examples | -| --- | --- | --- | --- | --- | -| `_id` | 100.0% (1000/1000) | objectId: 1000 | — | — | -| `actualEps` | 100.0% (1000/1000) | string: 73, int: 34, double: 893 | other: 73 (len 3..3) | `-0.01`, `-0.02`, `-0.03` | -| `announceTime` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 3..3) | `AMC`, `BTO`, `N/A` | -| `consensusEps` | 100.0% (1000/1000) | string: 347, int: 12, double: 641 | other: 347 (len 3..3) | `-0.02`, `-0.03`, `-0.04` | -| `created_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-06-29T22:22:20.864Z`, `2025-06-29T22:25:29.073Z`, `2025-06-29T22:25:29.087Z` | -| `epsSurpriseDollar` | 100.0% (1000/1000) | string: 359, int: 66, double: 575 | other: 359 (len 3..3) | `-0.0033`, `-0.005`, `-0.01` | -| `epsSurprisePercent` | 100.0% (1000/1000) | string: 366, int: 147, double: 487 | other: 366 (len 3..3) | `-0.6944`, `-0.7123`, `-0.8065` | -| `estimatedEps` | 100.0% (1000/1000) | string: 347, int: 12, double: 641 | other: 347 (len 3..3) | `-0.02`, `-0.03`, `-0.04` | -| `exchange` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 3..3) | `CDX`, `NGS`, `NSC` | -| `numOfEstimates` | 100.0% (1000/1000) | string: 42, int: 958 | other: 42 (len 3..3) | `0`, `1`, `10` | -| `period` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 3..7) | `N/A`, `Q1 1995`, `Q1 1996` | -| `qmSearchCode` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 3..8) | `DLCG:CA`, `DPM:CA`, `DSV:CA` | -| `quarterEnd` | 100.0% (1000/1000) | string: 1000 | ymd: 1000 (len 10..10) | `1994-09-30`, `1994-12-31`, `1995-03-31` | -| `reportDate` | 100.0% (1000/1000) | date: 1000 | — | `1994-10-26T00:00:00.000Z`, `1994-10-27T00:00:00.000Z`, `1994-11-02T00:00:00.000Z` | -| `symbol` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 1..5) | `DLCG`, `DPM`, `DSV` | -| `updated_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-06-29T22:25:29.073Z`, `2025-06-29T22:25:29.087Z`, `2025-06-29T22:25:29.167Z` | - -## `qmFilings` (1000 docs sampled) - -| Field | Presence | Types | String Patterns | Examples | -| --- | --- | --- | --- | --- | -| `_id` | 100.0% (1000/1000) | objectId: 1000 | — | — | -| `acc` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 36..151) | `01521843-00000001-00002586-s@#91#91761#SEDAR#...`, `01521972-00000001-00002586-s@#91#91761#SEDAR#...`, `01523099-00000001-00002586-s@#93#93810#SEDAR#...` | -| `datefiled` | 100.0% (1000/1000) | string: 1000 | ymd: 1000 (len 10..10) | `2010-01-06`, `2010-01-07`, `2010-01-12` | -| `exchange` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 3..3) | `CDX` | -| `filingDate` | 100.0% (1000/1000) | string: 1000 | ymd: 1000 (len 10..10) | `2010-01-06`, `2010-01-07`, `2010-01-12` | -| `filingId` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 24..24) | `5e6b93561f348f7b9159eb20`, `5e6b94221f348f7b9159fa0b`, `5e6b94221f348f7b9159fa0c` | -| `formdescription` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 4..72) | `52-109F2R - Certification of refiled interim ...`, `52-109FV1 - Certification of annual filings -...`, `52-109FV2 - Certification of interim filings ...` | -| `formgroup` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 19..38) | `Continuous Disclosure`, `Continuous disclosure`, `Exempt Market Offerings and Disclosure` | -| `formtype` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 21..21) | `002-001-001012-000052`, `002-001-001012-000054`, `002-001-001012-001002` | -| `htmllink` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 225..312) | `https://app.quotemedia.com/datatool/downloadF...` | -| `pages` | 100.0% (1000/1000) | int: 1000 | — | `1`, `10`, `11` | -| `pdflink` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 224..311) | `https://app.quotemedia.com/datatool/downloadF...` | -| `size` | 100.0% (1000/1000) | null: 1000 | — | — | -| `source` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 2..2) | `QM` | -| `symbol` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 2..6) | `AAC.P`, `ACAP.P`, `ACOP` | -| `timefiled` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 23..23) | `2010-01-06T03:00:00 EST`, `2010-01-07T03:00:00 EST`, `2010-01-12T03:00:00 EST` | - -## `qmPrices` (1000 docs sampled) - -| Field | Presence | Types | String Patterns | Examples | -| --- | --- | --- | --- | --- | -| `_id` | 100.0% (1000/1000) | objectId: 1000 | — | — | -| `change` | 100.0% (1000/1000) | int: 8, double: 992 | — | `-0.001851`, `-0.001877`, `-0.003661` | -| `changepercent` | 100.0% (1000/1000) | int: 8, double: 992 | — | `-0.007`, `-0.008`, `-0.014` | -| `created_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-06-29T18:05:12.787Z` | -| `date` | 100.0% (1000/1000) | string: 1000 | ymd: 1000 (len 10..10) | `2021-07-06`, `2021-07-07`, `2021-07-08` | -| `dateTime` | 100.0% (1000/1000) | date: 1000 | — | `2021-07-06T00:00:00.000Z`, `2021-07-07T00:00:00.000Z`, `2021-07-08T00:00:00.000Z` | -| `exchange` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 3..3) | `TSX` | -| `qmSearchCode` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 4..4) | `X:CA` | -| `sharevolume` | 100.0% (1000/1000) | int: 1000 | — | `100159`, `100168`, `100494` | -| `symbol` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 1..1) | `X` | -| `unadjustedclose` | 100.0% (1000/1000) | int: 29, double: 971 | — | `122.8`, `123.04`, `123.11` | -| `unadjustedhigh` | 100.0% (1000/1000) | int: 30, double: 970 | — | `123.85`, `124.4`, `124.76` | -| `unadjustedlow` | 100.0% (1000/1000) | int: 29, double: 971 | — | `121.42`, `121.9`, `122.24` | -| `unadjustedopen` | 100.0% (1000/1000) | int: 38, double: 962 | — | `122.02`, `122.24`, `122.7` | -| `unadjustedvwap` | 100.0% (1000/1000) | double: 1000 | — | `122.6259`, `123.1946`, `123.6024` | -| `updated_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-06-29T18:59:43.948Z` | - -## `qmSplits` (1000 docs sampled) - -| Field | Presence | Types | String Patterns | Examples | -| --- | --- | --- | --- | --- | -| `_id` | 100.0% (1000/1000) | objectId: 1000 | — | — | -| `created_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-06-29T22:22:20.834Z`, `2025-06-29T22:25:29.068Z`, `2025-06-29T22:25:29.085Z` | -| `date` | 100.0% (1000/1000) | string: 1000 | ymd: 1000 (len 10..10) | `1972-06-21`, `1973-04-23`, `1976-07-26` | -| `declared` | 40.8% (408/1000) | string: 408 | ymd: 408 (len 10..10) | `1978-11-29`, `1979-03-02`, `1979-04-16` | -| `exchange` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 3..5) | `CDX`, `CNQ`, `EXPM` | -| `forfactor` | 100.0% (1000/1000) | string: 114, int: 867, double: 19 | emptyOrWhitespace: 114 (len 0..0) | , `1`, `1.024549` | -| `payment` | 38.2% (382/1000) | string: 382 | ymd: 382 (len 10..10) | `1969-12-31`, `1979-01-05`, `1979-04-06` | -| `qmSearchCode` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 1..12) | `A`, `AAUC:CA`, `ABRA:CA` | -| `record` | 38.1% (381/1000) | string: 381 | ymd: 381 (len 10..10) | `1969-12-31`, `1978-12-12`, `1979-03-15` | -| `reportDate` | 100.0% (1000/1000) | date: 1000 | — | `1972-06-21T00:00:00.000Z`, `1973-04-23T00:00:00.000Z`, `1976-07-26T00:00:00.000Z` | -| `splitratio` | 100.0% (1000/1000) | int: 305, double: 695 | — | `0.005`, `0.01`, `0.029129` | -| `symbol` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 1..9) | `A`, `AAUC`, `ABRA` | -| `tofactor` | 100.0% (1000/1000) | string: 114, int: 745, double: 141 | emptyOrWhitespace: 114 (len 0..0) | , `0.067967`, `0.3333` | -| `updated_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-06-29T22:25:29.068Z`, `2025-06-29T22:25:29.085Z`, `2025-06-29T22:25:29.147Z` | - -## `teMarketData` (435 docs sampled) - -| Field | Presence | Types | String Patterns | Examples | -| --- | --- | --- | --- | --- | -| `_id` | 100.0% (435/435) | objectId: 435 | — | — | -| `category` | 100.0% (435/435) | string: 435 | other: 435 (len 4..9) | `bond`, `commodity`, `currency` | -| `createdAt` | 100.0% (435/435) | date: 435 | — | `2026-04-02T03:56:52.369Z`, `2026-04-02T03:56:52.418Z`, `2026-04-02T03:56:52.526Z` | -| `daily` | 100.0% (435/435) | array: 435 | — | — | -| `frequency` | 100.0% (435/435) | string: 435 | other: 435 (len 5..8) | `daily`, `intraday` | -| `fullName` | 100.0% (435/435) | string: 435 | other: 435 (len 3..48) | `Abu Dhabi General`, `Aluminum`, `Amman Stock Exchange General Index` | -| `industry` | 100.0% (435/435) | null: 435 | — | — | -| `lastUpdated` | 100.0% (435/435) | date: 435 | — | `2026-04-02T03:56:52.369Z`, `2026-04-02T03:56:52.418Z`, `2026-04-02T03:56:52.526Z` | -| `monthly` | 100.0% (435/435) | array: 435 | — | — | -| `name` | 100.0% (435/435) | string: 435 | other: 435 (len 2..28) | `ADX General`, `ASE`, `ASPI` | -| `sector` | 100.0% (435/435) | null: 435 | — | — | -| `symbolType` | 100.0% (435/435) | string: 435 | other: 435 (len 3..3) | `com`, `cur`, `gov` | -| `teSymbol` | 100.0% (435/435) | string: 435 | other: 435 (len 2..11) | `ADSMI`, `AEX`, `AS51` | -| `ticker` | 100.0% (435/435) | null: 435 | — | — | -| `type` | 100.0% (435/435) | string: 435 | other: 435 (len 4..9) | `bond`, `commodity`, `currency` | -| `unit` | 100.0% (435/435) | string: 293, null: 142 | other: 293 (len 3..19) | `AUD/100Kg`, `BRL/Kgs`, `CNY/KG` | -| `updated_at` | 100.0% (435/435) | date: 435 | — | `2026-04-02T03:56:52.369Z`, `2026-04-02T03:56:52.418Z`, `2026-04-02T03:56:52.526Z` | diff --git a/design/data-pipeline/m1-us-ca-match-report.md b/design/data-pipeline/m1-us-ca-match-report.md deleted file mode 100644 index c92ce767..00000000 --- a/design/data-pipeline/m1-us-ca-match-report.md +++ /dev/null @@ -1,332 +0,0 @@ -# Security Master Match & Conflict Report - -## Exit Thresholds - -| Criterion | Status | Target | -| --- | --- | --- | -| Exchanges Mapped | PASS | 100.00% | -| Equities Resolved (Eligible) | PASS | >= 95.00% | - -## Exchange Coverage - -| Mapped | Unresolved | Total | Mapped % | -| --- | --- | --- | --- | -| 95 | 0 | 95 | 100.00% | - -## Gate Denominator Definition - -The M1 `>= 95.00%` equity resolution gate evaluates **gate-eligible US/CA common equities & ETFs on EODHD-covered exchanges** (`XNYS`, `XNAS`, `ARCX`, `XASE`, `BATS`, `OTCM`, `XTSE`, `XTSX`, `NEOE`). -All raw catalog rows remain visible in `Total` and `Resolved %`; non-matched records outside the gate denominator are transparently itemized under `Excluded by Design` (`excluded_fund`, `composite_venue`, `ats_routing_venue`, `forex_venue`) and `Out of Gate Scope`: -- `zero_bar_catalog_ghost`: secondary ticker-only rows (`qm`) with `missing_span` (zero price bars in `qmPrices`, intentionally refused by Stage B Tier 3/4 temporal-overlap safety to prevent ticker-reuse corruption such as `FB`). -- `uncovered_venue`: listings on venues absent from the EODHD bar master (`XCNQ` Canadian Securities Exchange across `qm`/`ceo`/`ib:AEQLIT`, and `ceo:NEOE` where EODHD carries only 19 of 587 listings). -- `non_equity_instrument`: non-common-equity instruments & test tickers (warrants `.WT`/`.WS`, convertible debentures `.DB`, subscription receipts/rights `.R`/`.RT`, SPAC/REIT units `.U`/`.UN`, preferred shares `.PR*`/`-P*`, TSXV NEX shells `.H`, TSXV CPCs `.P`, and exchange test symbols). - -## Per-Source Resolution - -| Source | Total | Matched | Unresolved | Conflict | Excluded by Design | Out of Gate Scope | Eligible Total | Resolved % | Eligible Resolved % | -| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | -| eod | 66258 | 65970 | 288 | 0 | 288 | 0 | 65970 | 99.57% | 100.00% | -| ib | 18402 | 16882 | 1449 | 71 | 0 | 1165 | 17237 | 91.74% | 97.94% | -| qm | 47140 | 23394 | 23724 | 22 | 11259 | 11790 | 24091 | 49.63% | 97.11% | -| ceo | 9072 | 4904 | 4158 | 10 | 0 | 3951 | 5121 | 54.06% | 95.76% | - -## Out-of-Gate-Scope Breakdown - -| Source | Reason | Count | -| --- | --- | --- | -| ceo | non_equity_instrument | 1950 | -| ceo | uncovered_venue | 2001 | -| ib | non_equity_instrument | 437 | -| ib | uncovered_venue | 728 | -| qm | non_equity_instrument | 851 | -| qm | uncovered_venue | 718 | -| qm | zero_bar_catalog_ghost | 10221 | - -## Per-Country Resolution - -| Country | Total | Matched | Unresolved | Conflict | Excluded by Design | Eligible Total | Resolved % | Eligible Resolved % | -| --- | --- | --- | --- | --- | --- | --- | --- | --- | -| AU | 3 | 0 | 3 | 0 | 0 | 3 | 0.00% | 0.00% | -| BM | 13 | 0 | 13 | 0 | 0 | 13 | 0.00% | 0.00% | -| CA | 25221 | 18044 | 7148 | 29 | 0 | 25221 | 71.54% | 71.54% | -| IE | 2 | 0 | 1 | 1 | 0 | 2 | 0.00% | 0.00% | -| IL | 4 | 0 | 4 | 0 | 0 | 4 | 0.00% | 0.00% | -| JE | 1 | 0 | 1 | 0 | 0 | 1 | 0.00% | 0.00% | -| JP | 1 | 0 | 1 | 0 | 0 | 1 | 0.00% | 0.00% | -| KY | 51 | 0 | 34 | 17 | 0 | 51 | 0.00% | 0.00% | -| MH | 6 | 0 | 5 | 1 | 0 | 6 | 0.00% | 0.00% | -| NL | 2 | 0 | 2 | 0 | 0 | 2 | 0.00% | 0.00% | -| SG | 1 | 0 | 0 | 1 | 0 | 1 | 0.00% | 0.00% | -| US | 104021 | 93106 | 10861 | 54 | 6 | 104015 | 89.51% | 89.51% | -| VI | 1 | 0 | 1 | 0 | 0 | 1 | 0.00% | 0.00% | - -## Unresolved by Reason - -### Stage A - -| Source | Reason | Count | -| --- | --- | --- | -| ib | missing_identifiers | 4 | - -### Stage B - -| Source | Reason | Count | -| --- | --- | --- | -| ceo | invalid_ticker | 17 | -| ceo | no_matching_listing | 4141 | -| eod | composite_venue | 288 | -| ib | invalid_currency | 24 | -| ib | no_listing_for_currency | 1421 | -| qm | ats_routing_venue | 8283 | -| qm | composite_venue | 2976 | -| qm | invalid_ticker | 1 | -| qm | missing_span | 10221 | -| qm | no_matching_listing | 2204 | -| qm | no_span_overlap | 39 | - -## Conflicts by Pass & Kind - -| Pass | Conflict Kind | Count | -| --- | --- | --- | -| pass4 | price_low_correlation | 197 | -| pass4 | price_ratio_mismatch | 312 | -| stage_a | isin_cusip_mismatch | 1 | -| stage_b | ambiguous_ib_listing | 30 | -| stage_b | ambiguous_ticker_span | 22 | -| stage_b | competing_ib_conid | 40 | -| stage_b | duplicate_source_id | 10 | - -## Pass 4 Price Cross-Check Verdicts - -- Pairs In: 65231 -- Invalid Pairs: 0 -- Conflicts Emitted: 509 - -| Verdict | Count | -| --- | --- | -| unsupported_currency_pair | 0 | -| insufficient_data | 60599 | -| ratio_mismatch | 312 | -| low_correlation | 197 | -| confirmed | 4123 | - -## Pass 6 Delisting Chain Outcomes - -- Total Input Listings: 65970 -- Processed Listings: 65970 -- Continuities Created: 95 -- Conflicts Detected: 0 - -| Outcome | Count | -| --- | --- | -| active | 25956 | -| moved_to_otc | 95 | -| bankruptcy_cancelled | 590 | -| unknown_involuntary | 39329 | - -## Conflict Sample - -| Pass | Source | Source ID | Conflict Kind | Detail | -| --- | --- | --- | --- | --- | -| pass4 | eod | AAPL.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"AAPL.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.4923,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"AAPL"},"usableDates":17,"verdict":"low_correlation"} | -| pass4 | eod | ABLT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ABLT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.9623,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ABLT"},"usableDates":6,"verdict":"low_correlation"} | -| pass4 | eod | ABM.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ABM.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.2871,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ABM"},"usableDates":15,"verdict":"low_correlation"} | -| pass4 | eod | ABR.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ABR.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6267,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ABR"},"usableDates":7,"verdict":"low_correlation"} | -| pass4 | eod | ABT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ABT.US"},"medianRatio":1.0000009402030838,"minCorrelation":0.9,"priceCorr":0.653,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ABT"},"usableDates":16,"verdict":"low_correlation"} | -| pass4 | eod | ACD.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"ACD.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.768,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"ACD:CA"},"usableDates":5,"verdict":"low_correlation"} | -| pass4 | eod | ADM.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ADM.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8875,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ADM"},"usableDates":16,"verdict":"low_correlation"} | -| pass4 | eod | ADX.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ADX.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6527,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ADX"},"usableDates":17,"verdict":"low_correlation"} | -| pass4 | eod | AFG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"AFG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8974,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"AFG"},"usableDates":16,"verdict":"low_correlation"} | -| pass4 | eod | AG.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"AG.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8279,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"AG:CA"},"usableDates":10,"verdict":"low_correlation"} | -| pass4 | eod | AGFXF.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"AGFXF.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.3573,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"AGFXF"},"usableDates":5,"verdict":"low_correlation"} | -| pass4 | eod | ALXN.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ALXN.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.4186,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ALXN"},"usableDates":10,"verdict":"low_correlation"} | -| pass4 | eod | AMAT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"AMAT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6599,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"AMAT"},"usableDates":15,"verdict":"low_correlation"} | -| pass4 | eod | AMGN.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"AMGN.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8658,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"AMGN"},"usableDates":12,"verdict":"low_correlation"} | -| pass4 | eod | APD.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"APD.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7669,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"APD"},"usableDates":16,"verdict":"low_correlation"} | -| pass4 | eod | ARX.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"ARX.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8297,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"ARX:CA"},"usableDates":10,"verdict":"low_correlation"} | -| pass4 | eod | ASG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ASG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8475,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ASG"},"usableDates":14,"verdict":"low_correlation"} | -| pass4 | eod | AUQ.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"AUQ.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5609,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"AUQ:CA"},"usableDates":6,"verdict":"low_correlation"} | -| pass4 | eod | AVU.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"AVU.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.415,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"AVU:CA"},"usableDates":5,"verdict":"low_correlation"} | -| pass4 | eod | AVY.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"AVY.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.888,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"AVY"},"usableDates":15,"verdict":"low_correlation"} | -| pass4 | eod | B.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"B.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8517,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"B"},"usableDates":15,"verdict":"low_correlation"} | -| pass4 | eod | BCE.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"BCE.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.2712,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"BCE:CA"},"usableDates":10,"verdict":"low_correlation"} | -| pass4 | eod | BEN.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"BEN.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8754,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"BEN"},"usableDates":15,"verdict":"low_correlation"} | -| pass4 | eod | BKH.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"BKH.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.829,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"BKH"},"usableDates":15,"verdict":"low_correlation"} | -| pass4 | eod | BKT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"BKT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5579,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"BKT"},"usableDates":14,"verdict":"low_correlation"} | -| pass4 | eod | BKTI.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"BKTI.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8971,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"BKTI"},"usableDates":15,"verdict":"low_correlation"} | -| pass4 | eod | BLM.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"BLM.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8388,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"BLM:CA"},"usableDates":6,"verdict":"low_correlation"} | -| pass4 | eod | BMGP.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"BMGP.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.737,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"BMGP"},"usableDates":5,"verdict":"low_correlation"} | -| pass4 | eod | BN.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"BN.TO"},"medianRatio":0.9924867905232657,"minCorrelation":0.9,"priceCorr":0.7976,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"BN:CA"},"usableDates":9,"verdict":"low_correlation"} | -| pass4 | eod | BN.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"BN.US"},"medianRatio":0.9930629800660156,"minCorrelation":0.9,"priceCorr":0.8718,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"BN"},"usableDates":14,"verdict":"low_correlation"} | -| pass4 | eod | BNSOF.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"BNSOF.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6784,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"BNSOF"},"usableDates":11,"verdict":"low_correlation"} | -| pass4 | eod | BOH.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"BOH.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8681,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"BOH"},"usableDates":15,"verdict":"low_correlation"} | -| pass4 | eod | BTO.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"BTO.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7832,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"BTO"},"usableDates":7,"verdict":"low_correlation"} | -| pass4 | eod | BYDDY.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"BYDDY.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8275,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"BYDDY"},"usableDates":6,"verdict":"low_correlation"} | -| pass4 | eod | CAT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"CAT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8615,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"CAT"},"usableDates":17,"verdict":"low_correlation"} | -| pass4 | eod | CCK.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"CCK.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8453,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"CCK"},"usableDates":15,"verdict":"low_correlation"} | -| pass4 | eod | CFW.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"CFW.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7823,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"CFW:CA"},"usableDates":10,"verdict":"low_correlation"} | -| pass4 | eod | CGNX.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"CGNX.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8472,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"CGNX"},"usableDates":13,"verdict":"low_correlation"} | -| pass4 | eod | CINF.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"CINF.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5966,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"CINF"},"usableDates":13,"verdict":"low_correlation"} | -| pass4 | eod | CIX.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"CIX.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7309,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"CIX:CA"},"usableDates":11,"verdict":"low_correlation"} | -| pass4 | eod | CL.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"CL.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7174,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"CL"},"usableDates":17,"verdict":"low_correlation"} | -| pass4 | eod | CMT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"CMT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8188,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"CMT"},"usableDates":7,"verdict":"low_correlation"} | -| pass4 | eod | COV.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"COV.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.2511,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"COV:CA"},"usableDates":6,"verdict":"low_correlation"} | -| pass4 | eod | CRRX.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"CRRX.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7485,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"CRRX:CA"},"usableDates":8,"verdict":"low_correlation"} | -| pass4 | eod | CSCO.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"CSCO.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5838,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"CSCO"},"usableDates":13,"verdict":"low_correlation"} | -| pass4 | eod | CTAS.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"CTAS.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.833,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"CTAS"},"usableDates":13,"verdict":"low_correlation"} | -| pass4 | eod | DF.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"DF.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8822,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"DF:CA"},"usableDates":6,"verdict":"low_correlation"} | -| pass4 | eod | DGICB.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"DGICB.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7254,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"DGICB"},"usableDates":5,"verdict":"low_correlation"} | -| pass4 | eod | DHR.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"DHR.US"},"medianRatio":1.0000008038585209,"minCorrelation":0.9,"priceCorr":0.7251,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"DHR"},"usableDates":14,"verdict":"low_correlation"} | -| pass4 | eod | DIS.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"DIS.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6493,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"DIS"},"usableDates":23,"verdict":"low_correlation"} | -| pass4 | eod | DMI.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"DMI.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7968,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"DMI:CA"},"usableDates":6,"verdict":"low_correlation"} | -| pass4 | eod | DOC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"DOC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5946,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"DOC"},"usableDates":14,"verdict":"low_correlation"} | -| pass4 | eod | DS.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"DS.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.4049,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"DS:CA"},"usableDates":5,"verdict":"low_correlation"} | -| pass4 | eod | DTE.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"DTE.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7957,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"DTE"},"usableDates":20,"verdict":"low_correlation"} | -| pass4 | eod | DTRK.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"DTRK.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7845,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"DTRK"},"usableDates":9,"verdict":"low_correlation"} | -| pass4 | eod | EA.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"EA.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8582,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"EA"},"usableDates":13,"verdict":"low_correlation"} | -| pass4 | eod | EAPH.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"EAPH.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.0978,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"EAPH"},"usableDates":6,"verdict":"low_correlation"} | -| pass4 | eod | EBIXQ.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"EBIXQ.US"},"medianRatio":0.9984378853901176,"minCorrelation":0.9,"priceCorr":0.8049,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"EBIXQ"},"usableDates":10,"verdict":"low_correlation"} | -| pass4 | eod | EEA.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"EEA.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8994,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"EEA"},"usableDates":14,"verdict":"low_correlation"} | -| pass4 | eod | EIT-UN.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"EIT-UN.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.2739,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"EIT.UN:CA"},"usableDates":10,"verdict":"low_correlation"} | -| pass4 | eod | EIX.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"EIX.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8568,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"EIX"},"usableDates":19,"verdict":"low_correlation"} | -| pass4 | eod | EKG.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"EKG.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8466,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"EKG:CA"},"usableDates":8,"verdict":"low_correlation"} | -| pass4 | eod | EMR.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"EMR.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8167,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"EMR"},"usableDates":16,"verdict":"low_correlation"} | -| pass4 | eod | ENS.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ENS.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.2394,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ENS"},"usableDates":7,"verdict":"low_correlation"} | -| pass4 | eod | ERIC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ERIC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8581,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ERIC"},"usableDates":13,"verdict":"low_correlation"} | -| pass4 | eod | ETR.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ETR.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8864,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ETR"},"usableDates":16,"verdict":"low_correlation"} | -| pass4 | eod | EXC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"EXC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6761,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"EXC"},"usableDates":17,"verdict":"low_correlation"} | -| pass4 | eod | EXG.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"EXG.V"},"medianRatio":1.0128205128205128,"minCorrelation":0.9,"priceCorr":0.8849,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"EXG:CA"},"usableDates":6,"verdict":"low_correlation"} | -| pass4 | eod | FAST.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"FAST.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7978,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"FAST"},"usableDates":13,"verdict":"low_correlation"} | -| pass4 | eod | FE.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"FE.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.638,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"FE"},"usableDates":10,"verdict":"low_correlation"} | -| pass4 | eod | FI.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"FI.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5734,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"FI"},"usableDates":13,"verdict":"low_correlation"} | -| pass4 | eod | FLO.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"FLO.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6659,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"FLO"},"usableDates":14,"verdict":"low_correlation"} | -| pass4 | eod | FTFT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"FTFT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8561,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"FTFT"},"usableDates":5,"verdict":"low_correlation"} | -| pass4 | eod | FTU.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"FTU.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.7131,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"FTU:CA"},"usableDates":7,"verdict":"low_correlation"} | -| pass4 | eod | GAB.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"GAB.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7851,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"GAB"},"usableDates":14,"verdict":"low_correlation"} | -| pass4 | eod | GLW.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"GLW.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5909,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"GLW"},"usableDates":16,"verdict":"low_correlation"} | -| pass4 | eod | GMGI.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"GMGI.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.1581,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"GMGI"},"usableDates":5,"verdict":"low_correlation"} | -| pass4 | eod | GPC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"GPC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.893,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"GPC"},"usableDates":16,"verdict":"low_correlation"} | -| pass4 | eod | GR.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"GR.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.0751,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"GR:CA"},"usableDates":6,"verdict":"low_correlation"} | -| pass4 | eod | GSY.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"GSY.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.821,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"GSY:CA"},"usableDates":10,"verdict":"low_correlation"} | -| pass4 | eod | GWO.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"GWO.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.4038,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"GWO:CA"},"usableDates":11,"verdict":"low_correlation"} | -| pass4 | eod | GWW.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"GWW.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8347,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"GWW"},"usableDates":15,"verdict":"low_correlation"} | -| pass4 | eod | HD.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"HD.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.3437,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"HD"},"usableDates":15,"verdict":"low_correlation"} | -| pass4 | eod | HE.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"HE.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8973,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"HE"},"usableDates":14,"verdict":"low_correlation"} | -| pass4 | eod | HERC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"HERC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.9709,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"HERC"},"usableDates":5,"verdict":"low_correlation"} | -| pass4 | eod | HMSY.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"HMSY.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8013,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"HMSY"},"usableDates":11,"verdict":"low_correlation"} | -| pass4 | eod | HON.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"HON.US"},"medianRatio":0.9985665897393179,"minCorrelation":0.9,"priceCorr":0.7848,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"HON"},"usableDates":10,"verdict":"low_correlation"} | -| pass4 | eod | HRB.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"HRB.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7753,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"HRB"},"usableDates":14,"verdict":"low_correlation"} | -| pass4 | eod | IAF.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"IAF.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8914,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"IAF"},"usableDates":14,"verdict":"low_correlation"} | -| pass4 | eod | IBM.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"IBM.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8969,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"IBM"},"usableDates":23,"verdict":"low_correlation"} | -| pass4 | eod | IDXX.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"IDXX.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7758,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"IDXX"},"usableDates":12,"verdict":"low_correlation"} | -| pass4 | eod | INVI.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"INVI.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8356,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"INVI"},"usableDates":7,"verdict":"low_correlation"} | -| pass4 | eod | INX.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"INX.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.1372,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"INX:CA"},"usableDates":5,"verdict":"low_correlation"} | -| pass4 | eod | IP.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"IP.US"},"medianRatio":1.0000015837820717,"minCorrelation":0.9,"priceCorr":0.8714,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"IP"},"usableDates":20,"verdict":"low_correlation"} | -| pass4 | eod | IPG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"IPG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8854,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"IPG"},"usableDates":14,"verdict":"low_correlation"} | -| pass4 | eod | J.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"J.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8972,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"J"},"usableDates":13,"verdict":"low_correlation"} | -| pass4 | eod | JHI.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"JHI.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.2883,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"JHI"},"usableDates":17,"verdict":"low_correlation"} | -| pass4 | eod | JHS.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"JHS.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5039,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"JHS"},"usableDates":17,"verdict":"low_correlation"} | -| pass4 | eod | JNJ.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"JNJ.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.4784,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"JNJ"},"usableDates":20,"verdict":"low_correlation"} | -| pass4 | eod | JPM.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"JPM.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6225,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"JPM"},"usableDates":15,"verdict":"low_correlation"} | -| pass4 | eod | K.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"K.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7446,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"K"},"usableDates":15,"verdict":"low_correlation"} | -| pass4 | eod | KNX.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"KNX.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.3071,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"KNX"},"usableDates":5,"verdict":"low_correlation"} | -| pass4 | eod | KO.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"KO.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7972,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"KO"},"usableDates":23,"verdict":"low_correlation"} | -| pass4 | eod | KTN.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"KTN.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.1622,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"KTN:CA"},"usableDates":7,"verdict":"low_correlation"} | -| pass4 | eod | LB.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"LB.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7835,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"LB:CA"},"usableDates":11,"verdict":"low_correlation"} | -| pass4 | eod | LIN.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"LIN.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8716,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"LIN"},"usableDates":12,"verdict":"low_correlation"} | -| pass4 | eod | LOW.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"LOW.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.692,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"LOW"},"usableDates":15,"verdict":"low_correlation"} | -| pass4 | eod | LTTC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"LTTC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7122,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"LTTC"},"usableDates":9,"verdict":"low_correlation"} | -| pass4 | eod | MAG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MAG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5247,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MAG"},"usableDates":7,"verdict":"low_correlation"} | -| pass4 | eod | MAH.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"MAH.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8872,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"MAH:CA"},"usableDates":5,"verdict":"low_correlation"} | -| pass4 | eod | MAKOF.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MAKOF.US"},"medianRatio":1.0010373443983402,"minCorrelation":0.9,"priceCorr":-0.3094,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MAKOF"},"usableDates":5,"verdict":"low_correlation"} | -| pass4 | eod | MAR.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MAR.US"},"medianRatio":1.0000850013709899,"minCorrelation":0.9,"priceCorr":0.878,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MAR"},"usableDates":11,"verdict":"low_correlation"} | -| pass4 | eod | MAT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MAT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8638,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MAT"},"usableDates":16,"verdict":"low_correlation"} | -| pass4 | eod | MCD.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MCD.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8111,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MCD"},"usableDates":17,"verdict":"low_correlation"} | -| pass4 | eod | MCHP.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MCHP.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7736,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MCHP"},"usableDates":12,"verdict":"low_correlation"} | -| pass4 | eod | MG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8326,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MG"},"usableDates":5,"verdict":"low_correlation"} | -| pass4 | eod | MGF.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MGF.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.3548,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MGF"},"usableDates":14,"verdict":"low_correlation"} | -| pass4 | eod | MGRC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MGRC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8632,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MGRC"},"usableDates":13,"verdict":"low_correlation"} | -| pass4 | eod | MIN.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MIN.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.2315,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MIN"},"usableDates":14,"verdict":"low_correlation"} | -| pass4 | eod | MMT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MMT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.0508,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MMT"},"usableDates":14,"verdict":"low_correlation"} | -| pass4 | eod | MRNJ.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MRNJ.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.4307,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MRNJ"},"usableDates":6,"verdict":"low_correlation"} | -| pass4 | eod | MU.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MU.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.887,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MU"},"usableDates":13,"verdict":"low_correlation"} | -| pass4 | eod | NCA.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"NCA.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6143,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"NCA"},"usableDates":14,"verdict":"low_correlation"} | -| pass4 | eod | NDSN.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"NDSN.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8823,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"NDSN"},"usableDates":13,"verdict":"low_correlation"} | -| pass4 | eod | NEV.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"NEV.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.4241,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"NEV:CA"},"usableDates":5,"verdict":"low_correlation"} | -| pass4 | eod | NEWH.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"NEWH.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.3492,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"NEWH"},"usableDates":6,"verdict":"low_correlation"} | -| pass4 | eod | NGG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"NGG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7031,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"NGG"},"usableDates":9,"verdict":"low_correlation"} | -| pass4 | eod | NHC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"NHC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7198,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"NHC"},"usableDates":13,"verdict":"low_correlation"} | -| pass4 | eod | NJR.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"NJR.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7038,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"NJR"},"usableDates":14,"verdict":"low_correlation"} | -| pass4 | eod | NSC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"NSC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8787,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"NSC"},"usableDates":16,"verdict":"low_correlation"} | -| pass4 | eod | NTRS.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"NTRS.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8915,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"NTRS"},"usableDates":13,"verdict":"low_correlation"} | -| pass4 | eod | NUV.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"NUV.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6387,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"NUV"},"usableDates":14,"verdict":"low_correlation"} | -| pass4 | eod | NVO.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"NVO.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8002,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"NVO"},"usableDates":13,"verdict":"low_correlation"} | -| pass4 | eod | NWX.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"NWX.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8847,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"NWX:CA"},"usableDates":7,"verdict":"low_correlation"} | -| pass4 | eod | NZP.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"NZP.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8469,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"NZP:CA"},"usableDates":5,"verdict":"low_correlation"} | -| pass4 | eod | ODX-H.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"ODX-H.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7014,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"ODX.H:CA"},"usableDates":7,"verdict":"low_correlation"} | -| pass4 | eod | OMVKY.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"OMVKY.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7275,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"OMVKY"},"usableDates":7,"verdict":"low_correlation"} | -| pass4 | eod | ORCL.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ORCL.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8616,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ORCL"},"usableDates":14,"verdict":"low_correlation"} | -| pass4 | eod | ORI.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ORI.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8524,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ORI"},"usableDates":13,"verdict":"low_correlation"} | -| pass4 | eod | ORN.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ORN.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.0519,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ORN"},"usableDates":5,"verdict":"low_correlation"} | -| pass4 | eod | PAYX.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PAYX.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8645,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PAYX"},"usableDates":13,"verdict":"low_correlation"} | -| pass4 | eod | PBI.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PBI.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8444,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PBI"},"usableDates":13,"verdict":"low_correlation"} | -| pass4 | eod | PCF.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PCF.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5439,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PCF"},"usableDates":14,"verdict":"low_correlation"} | -| pass4 | eod | PCH.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PCH.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8737,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PCH"},"usableDates":15,"verdict":"low_correlation"} | -| pass4 | eod | PDLI.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PDLI.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.851,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PDLI"},"usableDates":11,"verdict":"low_correlation"} | -| pass4 | eod | PDV.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"PDV.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.7666,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"PDV:CA"},"usableDates":7,"verdict":"low_correlation"} | -| pass4 | eod | PEG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PEG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.852,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PEG"},"usableDates":17,"verdict":"low_correlation"} | -| pass4 | eod | PEO.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PEO.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8323,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PEO"},"usableDates":14,"verdict":"low_correlation"} | -| pass4 | eod | PFE.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PFE.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8302,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PFE"},"usableDates":13,"verdict":"low_correlation"} | -| pass4 | eod | PG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.841,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PG"},"usableDates":13,"verdict":"low_correlation"} | -| pass4 | eod | PGR.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PGR.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7961,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PGR"},"usableDates":14,"verdict":"low_correlation"} | -| pass4 | eod | PIM.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PIM.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.4549,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PIM"},"usableDates":14,"verdict":"low_correlation"} | -| pass4 | eod | PNC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PNC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7715,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PNC"},"usableDates":13,"verdict":"low_correlation"} | -| pass4 | eod | PPG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PPG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8466,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PPG"},"usableDates":14,"verdict":"low_correlation"} | -| pass4 | eod | PPL.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"PPL.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6331,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"PPL:CA"},"usableDates":10,"verdict":"low_correlation"} | -| pass4 | eod | PPL.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PPL.US"},"medianRatio":0.9962860635696822,"minCorrelation":0.9,"priceCorr":0.7763,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PPL"},"usableDates":13,"verdict":"low_correlation"} | -| pass4 | eod | PPT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PPT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5062,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PPT"},"usableDates":14,"verdict":"low_correlation"} | -| pass4 | eod | PSHG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PSHG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.897,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PSHG"},"usableDates":5,"verdict":"low_correlation"} | -| pass4 | eod | PSYC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PSYC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.0099,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PSYC"},"usableDates":5,"verdict":"low_correlation"} | -| pass4 | eod | PTE.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"PTE.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7833,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"PTE:CA"},"usableDates":7,"verdict":"low_correlation"} | -| pass4 | eod | PTVCB.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PTVCB.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.4213,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PTVCB"},"usableDates":11,"verdict":"low_correlation"} | -| pass4 | eod | QNC.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"QNC.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.2666,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"QNC:CA"},"usableDates":5,"verdict":"low_correlation"} | -| pass4 | eod | RDI.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"RDI.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8088,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"RDI"},"usableDates":8,"verdict":"low_correlation"} | -| pass4 | eod | RJF.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"RJF.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.4954,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"RJF"},"usableDates":14,"verdict":"low_correlation"} | -| pass4 | eod | ROG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ROG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8908,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ROG"},"usableDates":12,"verdict":"low_correlation"} | -| pass4 | eod | SABA.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SABA.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5922,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SABA"},"usableDates":14,"verdict":"low_correlation"} | -| pass4 | eod | SBR.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SBR.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.4564,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SBR"},"usableDates":14,"verdict":"low_correlation"} | -| pass4 | eod | SCL.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SCL.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6328,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SCL"},"usableDates":12,"verdict":"low_correlation"} | -| pass4 | eod | SDR.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"SDR.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8406,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"SDR:CA"},"usableDates":6,"verdict":"low_correlation"} | -| pass4 | eod | SGC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SGC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5532,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SGC"},"usableDates":12,"verdict":"low_correlation"} | -| pass4 | eod | SHW.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SHW.US"},"medianRatio":1.0000010134792743,"minCorrelation":0.9,"priceCorr":0.7152,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SHW"},"usableDates":15,"verdict":"low_correlation"} | -| pass4 | eod | SIM.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SIM.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5561,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SIM"},"usableDates":9,"verdict":"low_correlation"} | -| pass4 | eod | SKT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SKT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8894,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SKT"},"usableDates":12,"verdict":"low_correlation"} | -| pass4 | eod | SO.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SO.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7559,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SO"},"usableDates":16,"verdict":"low_correlation"} | -| pass4 | eod | SPH.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SPH.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.0746,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SPH"},"usableDates":11,"verdict":"low_correlation"} | -| pass4 | eod | SR.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SR.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5368,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SR"},"usableDates":13,"verdict":"low_correlation"} | -| pass4 | eod | SR.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"SR.V"},"medianRatio":1.0121951219512195,"minCorrelation":0.9,"priceCorr":0.4701,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"SR:CA"},"usableDates":6,"verdict":"low_correlation"} | -| pass4 | eod | SRC.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"SRC.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.1692,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"SRC:CA"},"usableDates":5,"verdict":"low_correlation"} | -| pass4 | eod | SRG.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"SRG.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7455,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"SRG:CA"},"usableDates":5,"verdict":"low_correlation"} | -| pass4 | eod | SSV.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"SSV.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6213,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"SSV:CA"},"usableDates":7,"verdict":"low_correlation"} | -| pass4 | eod | SWZ.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SWZ.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7802,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SWZ"},"usableDates":14,"verdict":"low_correlation"} | -| pass4 | eod | SYY.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SYY.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.446,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SYY"},"usableDates":14,"verdict":"low_correlation"} | -| pass4 | eod | T.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"T.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7822,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"T"},"usableDates":13,"verdict":"low_correlation"} | -| pass4 | eod | TCF.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"TCF.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.836,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"TCF"},"usableDates":10,"verdict":"low_correlation"} | -| pass4 | eod | TCI.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"TCI.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.2847,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"TCI"},"usableDates":11,"verdict":"low_correlation"} | -| pass4 | eod | TFX.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"TFX.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8388,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"TFX"},"usableDates":14,"verdict":"low_correlation"} | -| pass4 | eod | TIGO.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"TIGO.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.3913,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"TIGO"},"usableDates":11,"verdict":"low_correlation"} | -| pass4 | eod | TJX.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"TJX.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8876,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"TJX"},"usableDates":14,"verdict":"low_correlation"} | -| pass4 | eod | TLGPY.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"TLGPY.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6001,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"TLGPY"},"usableDates":10,"verdict":"low_correlation"} | -| pass4 | eod | TMBXF.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"TMBXF.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7082,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"TMBXF"},"usableDates":5,"verdict":"low_correlation"} | -| pass4 | eod | UHT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"UHT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8031,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"UHT"},"usableDates":14,"verdict":"low_correlation"} | -| pass4 | eod | UNM.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"UNM.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8065,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"UNM"},"usableDates":14,"verdict":"low_correlation"} | -| pass4 | eod | UNP.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"UNP.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7949,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"UNP"},"usableDates":17,"verdict":"low_correlation"} | -| pass4 | eod | URE.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"URE.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8376,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"URE:CA"},"usableDates":7,"verdict":"low_correlation"} | -| pass4 | eod | UVV.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"UVV.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8327,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"UVV"},"usableDates":14,"verdict":"low_correlation"} | -| pass4 | eod | VQS.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"VQS.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7545,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"VQS:CA"},"usableDates":7,"verdict":"low_correlation"} | -| pass4 | eod | WAFD.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"WAFD.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8958,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"WAFD"},"usableDates":13,"verdict":"low_correlation"} | -| pass4 | eod | ABBNY.US | price_ratio_mismatch | {"left":{"currency":"USD","source":"eod","sourceId":"ABBNY.US"},"medianRatio":0.9512875068194219,"minCorrelation":0.9,"priceCorr":0.9996,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ABBNY"},"usableDates":9,"verdict":"ratio_mismatch"} | -| pass4 | eod | ACORQ.US | price_ratio_mismatch | {"left":{"currency":"USD","source":"eod","sourceId":"ACORQ.US"},"medianRatio":120,"minCorrelation":0.9,"priceCorr":0.5059,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ACORQ"},"usableDates":7,"verdict":"ratio_mismatch"} | -| pass4 | eod | AFCC-H.V | price_ratio_mismatch | {"left":{"currency":"CAD","source":"eod","sourceId":"AFCC-H.V"},"medianRatio":0.06666666666666667,"minCorrelation":0.9,"priceCorr":0.8612,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"AFCC.H:CA"},"usableDates":7,"verdict":"ratio_mismatch"} | - -Showing 200 of 612 conflicts (412 more in CSV). diff --git a/design/data-pipeline/rust-migration-evaluation.md b/design/data-pipeline/rust-migration-evaluation.md deleted file mode 100644 index 2039d470..00000000 --- a/design/data-pipeline/rust-migration-evaluation.md +++ /dev/null @@ -1,294 +0,0 @@ -# Evaluation: Moving `apps/stock/data-pipeline` into Rust - -**Date:** 2026-11-29 -**Status:** Decision brief for the director (docs-only spike; no code, crate, config, or milestone changes enacted) -**Scope:** Evaluate the second half of the settled Rust ETL decision — whether to keep `apps/stock/data-pipeline` in TypeScript, move bulk MongoDB streaming into `tools/curate-etl` (Rust), or port all of `apps/stock/data-pipeline` to Rust before Milestone `M2` adds PIT fundamentals, `ceoPosts`, and `bars_1m` intraday QuestDB ingestion. - -## Bottom Line (Recommendation) - -**Adopt Option B: keep `apps/stock/data-pipeline` in TypeScript for security-master resolution, TSV export, probes, and BullMQ/HTTP orchestration, and add direct read-only MongoDB `RawDocumentBuf` streaming (with Rust-side read-only safety guards) to `tools/curate-etl` for bulk curation.** - -- **Why not full port (Option C):** 88.1% of `apps/stock/data-pipeline/src/` (`17,924` of `20,349` LOC, backed by `40` test files / `32,435` test LOC) is logic- and review-bound security-master code operating on `319` exchanges and `396k` symbol catalog rows that already runs in sub-second synthetic benchmarks (`479.6 ms` for `100k` records in `run.ts`, `402.8 ms` for `500k` TSV mappings in `export-curate-inputs.ts`). Porting it adds weeks of parity risk, requires re-implementing BullMQ/PostgreSQL/env-safety adapters, and reopens settled decision `D5` / §4 layer boundaries for negligible wall-time gain. -- **Why not keep the JS raw-BSON file bridge forever (Option A):** While `export-raw-bson.ts` avoids JS object decoding (`3.57M–3.83M docs/s` synthetic), staging `845.7M` `eodPrices` and `3.40B` `eodIntraday1M` + `173.3M` `qmIntraday` rows through intermediate `.bson` files forces an unnecessary full NVMe write + read of hundreds of GiB (synthetic estimate: ~127–225 GiB peak file capacity / ~255–450 GiB total write+read I/O for `eodPrices`; ~499–832 GiB peak capacity / ~998–1,664 GiB total write+read I/O for the two intraday collections) before Rust even begins curating. Streaming directly from read-only MongoDB cursors in `tools/curate-etl` eliminates that scratch hop without touching the TypeScript security master. -- **Decision ownership:** The final choice among Options A, B, and C belongs to the director. None of the follow-up tasks in Section 6 are queued or enacted by this document. - ---- - -## 1. Current `apps/stock/data-pipeline` Inventory - -Measured directly from the repository working tree (no database connections). Every production file under `apps/stock/data-pipeline/src/` is `.ts` (zero non-`.ts` files). - -| Area under `apps/stock/data-pipeline/src/` | Prod Files | Non-Test LOC | Dedicated Test Files | Test LOC | Primary I/O & Role | -| --- | ---: | ---: | ---: | ---: | --- | -| `security-master/` | 21 | 17,924 | 40 | 32,435 | Pure in-memory Passes 1–6 + read-only MongoDB readers (`eodSymbols`, `ibSymbols`, `qmSymbols`, `ceoSymbols`, `eodSymbolChange`, `eodPrices`, `qmPrices`, exchanges, raw BSON, field-shape probe) + PostgreSQL master read/write (`persist.ts`, `export-curate-inputs.ts`) + local file output | -| `normalization/` | 4 | 1,318 | 6 | 2,468 | Pure in-memory (`identifiers.ts`, `provider-symbol.ts`, `ticker.ts`) + read-only MongoDB aggregation reader (`bar-spans.ts`: `$match`/`$group`/`$project`/`$sort` only, `$out`/`$merge` forbidden) | -| `handlers/` | 12 | 809 | 1* | 290* | BullMQ job handlers (`{data-pipeline_exchanges}`, `{data-pipeline_symbols}` queues via `getFullQueueName`), read-only MongoDB reads, PostgreSQL master reads/writes via `PipelineSyncRepository` | -| `repositories/` | 1 | 166 | (shared)* | (shared)* | PostgreSQL transactional sync/reset (`PipelineSyncRepository`, `pg_advisory_xact_lock(1937007472, 1)`) using `@stock-bot/types` `parseReferenceDataResetRequest` | -| `routes/` | 2 | 23 | 0 | 0 | HTTP `GET /health` via Hono (`create-routes.ts`, `health.routes.ts`) | -| `types/` | 1 | 21 | 0 | 0 | Pure in-memory TypeScript interfaces (`job-payloads.ts`: `JobPayload`, `SyncResult`, `SyncStatus`) | -| `index.ts` | 1 | 88 | 0 | 0 | Service bootstrap (`ServiceApplication`, `initializeStockConfig('dataPipeline', { mongoReadOnly: true })`, port `2002`, BullMQ + HTTP + Postgres + read-only Mongo) | -| **Total (`src/`)** | **42** | **20,349** | **47** | **35,193** | — | - -*\*`test/postgres/pipeline-safety.test.ts` (1 file, 290 lines) exercises both `handlers/` operations and `PipelineSyncRepository`; it is counted once in the total. `routes/`, `types/`, and `index.ts` have no dedicated unit test files and are covered indirectly by `test/unit/environment-safety*.test.ts` and `test/unit/mongodb-read-only.test.ts`.* - -Separately from production LOC, `apps/stock/data-pipeline/benchmarks/` holds **5 files / 1,144 LOC** of local synthetic benchmark scripts (`export-curate-inputs-benchmark.ts`, `export-raw-bson-benchmark.ts`, `run-security-master-pass4-benchmark.ts`, `sample-closes-benchmark.ts`, `source-field-shapes-benchmark.ts`). - -### Key CLI & Exporter Subsystems Inside `security-master/` - -- **`run-security-master.ts` (T-89 / T-105, `1,042` LOC) + `run.ts` (`1,345` LOC):** Runs the full read-only MongoDB security-master pipeline (`read-exchanges` → `read-sources` → `compute-bar-spans` → Pass 4 `readSampleCloses` + `crossCheckPrices` → `composeSecurityMasterRun`) and writes deterministic `match-report.md`, `conflicts.csv`, `override-template.sql`, and `run-stats.json`, with opt-in `--persist` to isolated dev PostgreSQL guarded by `assertSecurityMasterPersistSafety()`. **Source note:** Pass 4 is **wired and enabled by default** in `run-security-master.ts` (`--skip-price-cross-check`, `--sample-dates `), even though `apps/stock/data-pipeline/README.md` line 201 still states it is not yet wired. -- **TSV Exporter (T-116, `export-curate-inputs.ts` `2,040` LOC + `run-export-curate-inputs.ts` `345` LOC = `2,385` LOC):** Reads PostgreSQL security-master tables inside a `REPEATABLE READ READ ONLY` transaction (server-side `NO SCROLL` cursor, chunk size `<= 5,000`) and atomically publishes `provider_mapping.tsv`, `listing_currencies.tsv`, and Pass 6 `delistings.tsv` into `/generations/` behind `/.publish.lock` and a single `/current` symlink. -- **Raw-BSON Exporter (T-117, `export-raw-bson.ts` `670` LOC + `run-export-raw-bson.ts` `477` LOC = `1,147` LOC):** Streams 8 allowlisted M1 MongoDB collections (`eodPrices`, `qmSplits`, `qmDividends`, `qmPrices`, `teMarketData`, `ceoShorts`, `qmFilings`, `qmEarnings`) via `find(filter, { raw: true, batchSize })` with zero per-document JS decoding, validating BSON frame lengths, coalescing through an `8 MiB` write buffer, computing SHA-256, and publishing `.bson` atomically. -- **Field-Shape Probe (`source-field-shapes.ts` `915` LOC + `probe-source-field-shapes.ts` `291` LOC = `1,206` LOC):** Bounded read-only `find({}, { limit <= 10_000, promoteValues: false, promoteLongs: false })` probe over the 8 M1 collections to confirm live BSON field names and types before curation runs. - -### Cross-App Coupling & Safety Guards - -- **Zero direct package imports:** No other app or library imports `@stock-bot/data-pipeline`. -- **`web-api` runtime contract:** `apps/stock/web-api/src/services/pipeline.service.ts` enqueues BullMQ jobs onto `{data-pipeline_exchanges}` and `{data-pipeline_symbols}` via `getFullQueueName` (`libs/core/queue/src/service-utils.ts`, re-exported by `@stock-bot/queue`; using shared `@stock-bot/types` `parseReferenceDataResetRequest` / `ReferenceDataResetScope` for reset confirmation), and `apps/stock/web-api/src/services/monitoring.service.ts` monitors those two queues and polls `GET /health` on port `2002`. -- **Safety guard stack:** Every service and CLI entrypoint calls `initializeStockConfig('dataPipeline', { mongoReadOnly: true })` and `assertEnvironmentSafety()` (`apps/stock/config/src/env-safety.ts`, `706` LOC), which resolves loopback/LAN/numeric IPv4 aliases and throws if `development` targets QA PostgreSQL (`localhost:5432/trading_bot`) or opens QA MongoDB (`localhost:27017`) without `mongoReadOnly: true` or with `trading_admin`. At the driver layer, `MongoDBClient` (`libs/data/mongodb/src/client.ts`) wraps databases, collections, and cursors in read-only proxies that reject all write, index, and collection-mutation operations. - -### Reproducible Inventory Commands - -Re-running these POSIX commands from the repository root at the same commit reproduces every count in the table above: - -```bash -# 1. Production source file counts & non-test LOC per area -for area in security-master normalization handlers repositories routes types; do - files=$(find "apps/stock/data-pipeline/src/$area" -type f -name '*.ts' | sort) - count=$(printf '%s\n' "$files" | grep -c .) - lines=$(printf '%s\n' "$files" | xargs wc -l | tail -n 1 | awk '{print $1}') - printf '%-18s files=%2d loc=%5d\n' "$area/" "$count" "$lines" -done -printf '%-18s files=%2d loc=%5d\n' "index.ts" 1 "$(wc -l < apps/stock/data-pipeline/src/index.ts)" -total_files=$(find apps/stock/data-pipeline/src -type f -name '*.ts' | wc -l) -total_lines=$(find apps/stock/data-pipeline/src -type f -name '*.ts' | sort | xargs wc -l | tail -n 1 | awk '{print $1}') -printf '%-18s files=%2d loc=%5d\n' "TOTAL" "$total_files" "$total_lines" - -# 2. Dedicated test files & benchmark scripts -printf 'data-pipeline/test: %2d files %5d lines\n' \ - "$(find apps/stock/data-pipeline/test -type f -name '*.test.ts' | wc -l)" \ - "$(find apps/stock/data-pipeline/test -type f -name '*.test.ts' | sort | xargs wc -l | tail -n 1 | awk '{print $1}')" -printf 'unit security-master: %2d files %5d lines\n' \ - "$(find test/unit -type f -name 'security-master-*.test.ts' | wc -l)" \ - "$(find test/unit -type f -name 'security-master-*.test.ts' | sort | xargs wc -l | tail -n 1 | awk '{print $1}')" -printf 'postgres security-master: %2d files %5d lines\n' \ - "$(find test/postgres -type f -name 'security-master-*.test.ts' | wc -l)" \ - "$(find test/postgres -type f -name 'security-master-*.test.ts' | sort | xargs wc -l | tail -n 1 | awk '{print $1}')" -printf 'unit normalization: %2d files %5d lines\n' \ - "$(find test/unit -type f -name 'normalization-*.test.ts' | wc -l)" \ - "$(find test/unit -type f -name 'normalization-*.test.ts' | sort | xargs wc -l | tail -n 1 | awk '{print $1}')" -printf 'integration provider-symbol: %2d files %5d lines\n' \ - 1 "$(wc -l < test/integration/provider-symbol.test.ts)" -printf 'postgres pipeline-safety: %2d files %5d lines\n' \ - 1 "$(wc -l < test/postgres/pipeline-safety.test.ts)" -printf 'benchmarks (separate): %2d files %5d lines\n' \ - "$(find apps/stock/data-pipeline/benchmarks -type f -name '*.ts' | wc -l)" \ - "$(find apps/stock/data-pipeline/benchmarks -type f -name '*.ts' | sort | xargs wc -l | tail -n 1 | awk '{print $1}')" -``` - ---- - -## 2. What Already Lives in Rust (`tools/curate-etl`) - -`tools/curate-etl` is a standalone Cargo workspace member with **three exact-pinned dependencies** (`bson = "=3.1.0"` with `compat-3-0-0`, `parquet = "=60.2.0"` Zstd-only, `rayon = "=1.12.0"`), **zero async runtime**, and **zero database clients**. - -| Module Group under `tools/curate-etl/src/` | Files | LOC | Contents | -| --- | ---: | ---: | --- | -| Domain builders | 9 | 8,170 | `adj.rs`, `bars.rs`, `corporate_actions.rs`, `events.rs`, `fx.rs`, `provider_mapping.rs`, `session_close.rs`, `shorts.rs`, `split.rs` | -| Zero-copy BSON decoders & framing | 7 | 5,594 | `bson_ceo_shorts.rs`, `bson_eod_prices.rs`, `bson_qm_actions.rs`, `bson_qm_events.rs`, `bson_qm_prices.rs`, `bson_stream.rs`, `bson_te_market_data.rs` | -| Zstd Parquet writers & atomic publish | 7 | 9,841 | `parquet_adj.rs`, `parquet_bars.rs`, `parquet_corporate_actions.rs`, `parquet_events.rs`, `parquet_fx.rs`, `parquet_publish.rs`, `parquet_shorts.rs` | -| Curation stages | 6 | 3,726 | `curate_adj.rs`, `curate_bars.rs`, `curate_corporate_actions.rs`, `curate_events.rs`, `curate_fx.rs`, `curate_shorts.rs` | -| Runnable `curate-*` CLI runners | 6 | 5,202 | `run_curate_adj.rs`, `run_curate_bars.rs`, `run_curate_corporate_actions.rs`, `run_curate_events.rs`, `run_curate_fx.rs`, `run_curate_shorts.rs` | -| CLI, benchmarks, entrypoints | 4 | 16,884 | `bench.rs`, `cli.rs`, `lib.rs`, `main.rs` | -| Dedicated test modules (`*_tests.rs`) | 26 | 27,215 | Unit, property, parity, and TSV/BSON fixture tests | -| **Total (`tools/curate-etl/src/`)** | **65** | **76,632** | **39 non-test files (49,417 LOC) + 26 test files (27,215 LOC)** | - -Reproducible command: - -```bash -find tools/curate-etl/src -type f -name '*.rs' ! -name '*_tests.rs' | wc -l -find tools/curate-etl/src -type f -name '*.rs' ! -name '*_tests.rs' | sort | xargs wc -l | tail -n 1 -find tools/curate-etl/src -type f -name '*_tests.rs' | wc -l -find tools/curate-etl/src -type f -name '*_tests.rs' | sort | xargs wc -l | tail -n 1 -``` - -The binary already implements all **six M1 curation commands** (`curate-bars-1d`, `curate-adj-factors`, `curate-corporate-actions`, `curate-fx-1d`, `curate-shorts`, `curate-events`) reading local TSVs + concatenated raw-BSON files and atomically publishing Hive-partitioned Zstd Parquet. - -### Measured Local Baselines (Synthetic / Offline — Zero Live QA MongoDB or `quant` Runs) - -| Benchmark | Source & Date | Command | Workload & Measured Result | -| --- | --- | --- | --- | -| `curate-bars-1d` (1-thread baseline) | `tools/curate-etl/README.md` (`2026-11-29`) | `cargo run -p curate-etl --release --offline -- bench-curate-bars-cmd 1000000` | `1,000,000` EOD + `227,439` QM + `2,040` splits: `decode 234.63 ms` (`4.26M rows/s`), `curate 208.07 ms`, `write 456.39 ms` (`2.06M rows/s`), **total `899.09 ms` (`1.11M rows/s`, `193.78 MB/s`)** | -| `curate-bars-1d` (`rayon` parallel write, **local re-run**) | Local sandbox re-run (`2026-11-29`, 32-thread host, synthetic) | `CARGO_BUILD_JOBS=2 cargo run --release -p curate-etl --offline -- bench-curate-bars-cmd 1000000` | Same `1,000,000`-row synthetic input: `decode 233.19 ms` (`4.29M rows/s`), `curate 207.45 ms`, `write_1 (threads=1) 445.79 ms` (`2.10M rows/s`) vs **`write (threads=32) 94.42 ms` (`9.93M rows/s`, `259.56 MB/s`, `4.72x` speedup)**, **total `535.06 ms` (`1.87M rows/s`, `325.63 MB/s`)** | -| `curate-bars-1d` (5M rows, 1-thread) | `tools/curate-etl/README.md` (`2026-11-29`) | `cargo run -p curate-etl --release --offline -- bench-curate-bars-cmd 5000000` | `5,000,000` EOD + `1.14M` QM + `4,080` splits: **total `3,525.02 ms` (`1.42M rows/s`, `247.01 MB/s`)** | -| `curate-adj-factors` | `tools/curate-etl/README.md` (`2026-11-29`) | `cargo run -p curate-etl --release --offline -- bench-curate-adj-cmd` | `500,000` events + `62,720` `bars_1d`: **total `436.90–500.88 ms` (`998k–1.14M events/s`)** across 2 runs | -| `curate-corporate-actions` | `tools/curate-etl/README.md` (`2026-11-29`) | `cargo run -p curate-etl --release --offline -- bench-curate-corporate-actions-cmd 1000000` | `1,000,000` events (`39,186` splits, `950,896` divs, `9,918` delistings): **total `752.71–775.67 ms` (`1.29M–1.33M events/s`)** | -| `curate-fx-1d` | `tools/curate-etl/README.md` (`2026-11-29`) | `cargo run -p curate-etl --release --offline -- bench-curate-fx-cmd` | `20,000` FX rows (`CAD.FOREX` + `USDCAD`): **total `20.19–29.97 ms` (`667k–990k rows/s`)** | -| `curate-shorts` | `tools/curate-etl/README.md` (`2026-11-29`) | `cargo run -p curate-etl --release --offline -- bench-curate-shorts-command` | `700,000` `ceoShorts` docs (`64.78 MiB`): **total `365.73–369.48 ms` (`1.89M–1.91M rows/s`)**, `peak_chunk_bytes = 8 MiB` | -| `curate-events` | `tools/curate-etl/README.md` (`2026-11-29`) | `cargo run -p curate-etl --release --offline -- bench-curate-events-cmd` | `500,000` rows (`492.5k` filings, `7.5k` earnings): **total `838.71–861.10 ms` (`581k–596k rows/s`)**; linear synthetic extrapolation to `30.96M` rows: `51.9–53.3 s` single-core | -| `bson_eod_prices` decode-only | `tools/curate-etl/README.md` (`2026-11-28`) | `cargo run --release -p curate-etl --offline -- bench-bson-eod-prices` | `1,000,000` docs (`272.4 MiB`): **`217.38–221.82 ms` (`4.51M–4.60M rows/s`, `1.23–1.25 GB/s`)** | -| `bson_stream` short-read | `tools/curate-etl/README.md` (`2026-11-28`) | `cargo run --release -p curate-etl --offline -- bench-bson-stream` | `2,000,000` docs (`544.8 MiB`): **`544.59 ms` (`3.67M rows/s`, `1.00 GiB/s`, `0.963x` vs in-memory buffer, `8 MiB` peak buffer)** | -| `parquet_bars` write-only | `tools/curate-etl/README.md` (`2026-11-28`) | `cargo run --release -p curate-etl --offline -- bench-parquet-bars` | `5,000,000` rows, 20 year files: **`1,422.27 ms` (`3.52M rows/s`, `155.11 MB/s`, `1.82x` Zstd)** | -| `split` builder | `tools/curate-etl/README.md` (date omitted in README) | `cargo run --release -p curate-etl --offline -- bench-split` | `10,000,000` synthetic rows: **`367.40 ms` (`27.22M rows/s`)** | -| `bars` builder | `tools/curate-etl/README.md` (date omitted in README) | `cargo run --release -p curate-etl --offline -- bench-bars` | `10,000,000` synthetic rows: **`842.38 ms` (`11.87M rows/s`)** | -| `provider_mapping` lookup | `tools/curate-etl/README.md` (date omitted in README) | `cargo run --release -p curate-etl --offline -- bench-provider-mapping` | `10,000,000` synthetic lookups: **`447.14 ms` (`22.36M lookups/s`)** | -| TS `export-raw-bson` | `apps/stock/data-pipeline/README.md` (`2026-11-29`) | `bun run apps/stock/data-pipeline/benchmarks/export-raw-bson-benchmark.ts` | `1,000,000` synthetic `eodPrices` frames (`123.9 B` avg): **`270.8–279.8 ms` (`3.57M–3.69M docs/s`, `422–436 MiB/s`, `peak_rss 150–151 MiB`)**; `2M` docs: `3.83M docs/s`, `peak_rss 146.88 MiB` | -| TS `export-curate-inputs` | `apps/stock/data-pipeline/README.md` (`2026-11-29`) | `bun run apps/stock/data-pipeline/benchmarks/export-curate-inputs-benchmark.ts` | `500k` mappings + `100k` listings + `2k` OTC (`606,680` TSV rows, `17.2 MB`): **`402.8 ms` (`1.51M rows/s`, `277.01 MiB` peak RSS)** | -| TS `sample-closes` (Pass 4a) | `apps/stock/data-pipeline/README.md` (`2026-11-28`) | `bun run apps/stock/data-pipeline/benchmarks/sample-closes-benchmark.ts` | `500,025` synthetic docs (25 dates × 20k IDs + FX): **`190.3 ms` (`2.63M docs/s`)** | -| TS `source-symbol-readers` | `apps/stock/data-pipeline/README.md` (`2026-11-28`) | `bun test test/unit/security-master-source-symbol-readers.test.ts` | `368,000` synthetic symbol docs: **`488.0 ms` (`754k docs/s`)** | -| TS `security-type` classifier | `apps/stock/data-pipeline/README.md` (`2026-11-28`) | `bun test test/unit/security-master-security-type.test.ts` | `300,000` synthetic EOD records (`100k` distinct ISIN buckets, `20` conflicting ISINs): **`70.1 ms` (`4.28M records/s`, floor `>= 100k records/s`)** | -| TS `run.ts` composer (Passes 3–6) | `apps/stock/data-pipeline/README.md` (`2026-11-28`) | `bun test test/unit/security-master-run.test.ts` | `100,000` synthetic source records end-to-end: **`479.6 ms` (`208.5k records/s`)** | -| TS `persistSecurityMaster` | `apps/stock/data-pipeline/README.md` (`2026-11-28`, host Postgres safety schema) | `bun --env-file=/home/boki/.studio/test-env/stock-bot.env test test/postgres/security-master-persist.test.ts` | `20k` instruments + `20k` listings + `60k` mappings (`140k` total rows): **`2.36 s` full test wall time (`>= 59.3k total rows/s`)** | -| TS `source-field-shapes` probe | `apps/stock/data-pipeline/README.md` (`2026-11-28`) | `bun run apps/stock/data-pipeline/benchmarks/source-field-shapes-benchmark.ts` | `80,000` synthetic docs (8 collections × 10k): **`218.7 ms` (`365.8k docs/s`)** | - ---- - -## 3. Workload Classification by Area - -Row volumes come from the measured 2026-11-26 QA MongoDB inventory in `design/data-pipeline/phase1-investigation.md` and `design/DATA-CONTRACTS.md` §1. - -| Area / Pipeline Stage | Raw / Target Volume | Bottleneck Class | Run Cadence | Rust Value-Add | -| --- | --- | --- | --- | --- | -| Pass 1 Exchanges (`exchange-pass1.ts`, `generate-exchange-seed.ts`) | `319` rows (`eodExchanges` 76, `ibExchanges` 214, `qmExchanges` 25, `ceoExchanges` 4) | **Logic / human-review-bound** | Rare (initial seed + schema override migrations) | **None** | -| Pass 2–3–5–6 Security Master (`source-symbol-readers.ts`, `instrument-stage-a.ts`, `listing-stage-b.ts`, `delisting-chains.ts`, `match-report.ts`, `run.ts`, `persist.ts`) | `396,041` symbol docs (`eodSymbols` 317.8k, `qmSymbols` 47.2k, `ibSymbols` 18.4k, `ceoSymbols` 12.6k) + `230` `eodSymbolChange` | **Logic / edge-case / review-bound** (ISIN Luhn + CUSIP rescue, IB ATS venues, ticker-reuse spans, OTC delisting chains, override precedence) | Infrequent (initial US+CA build, then periodic delta refreshes) | **Negligible** (TS already does `100k` records in `0.48 s` and `140k` PG rows in `2.36 s`) | -| Pass 2 `bar-spans.ts` & Pass 4 `sample-closes.ts` | Server-side Mongo `$group` on `eodPrices`/`qmPrices` + 25-date `$in` slice (~500k docs) | **MongoDB index/server I/O-bound** | Same as security master | **Negligible** (MongoDB server does the scan; TS client processes 500k closes in `0.19 s`) | -| TSV Export (`export-curate-inputs.ts`) | ~100k–500k PostgreSQL rows (~17 MB) | **Small Postgres read** | Before each curation batch | **Negligible** (`0.40 s` synthetic; ~17 MB on disk) | -| Field-Shape Probe (`source-field-shapes.ts`) | `<= 80,000` sampled docs (`8 × 10k`) | **Diagnostic / interactive** | Occasional schema check | **None** | -| Service Control Plane (`handlers/`, `repositories/`, `routes/`, `index.ts`) | Legacy BullMQ sync jobs + `GET /health` | **Control-plane / queue glue** | Always-on daemon (low QPS) | **Negative** (BullMQ/DI/Hono already in TS) | -| **M1 Bulk Raw-BSON Export → Parquet (`eodPrices`, `qmPrices`, `qmFilings`, `qmDividends`, `qmSplits`, `ceoShorts`, `qmEarnings`, `teMarketData`)** | **`845.7M` `eodPrices` + `51.5M` `qmPrices` + `30.5M` `qmFilings` + `1.65M` others** | **CPU + NVMe-scratch / throughput-bound** | Full backfill + nightly/weekly incremental | **High — already in Rust for curation; JS file hop adds huge NVMe scratch write+read** | -| **M2 Bulk Raw-BSON → Parquet / QuestDB ILP v2 (`eodIntraday1M`, `qmIntraday`, `ceoPosts`, `qmFinancials`)** | **`3.40B` `eodIntraday1M` + `173.3M` `qmIntraday` + `14.8M` `ceoPosts` + `2.77M` `qmFinancials`/`-old`** | **CPU + NVMe-scratch + network/ILP throughput-bound** | Multi-billion-row backfill + incremental | **Critical — staging `3.57B` intraday docs through local `.bson` files is an estimated ~499–832 GiB peak capacity (~998–1,664 GiB total write+read I/O) NVMe bottleneck** | - -### Why the Intermediate `.bson` File Hop Hurts at M1/M2 Scale - -Even though `export-raw-bson.ts` avoids JS object deserialization (`3.57M–3.83M docs/s` synthetic), it writes every raw document to `.bson` on NVMe before `curate-etl` reads the file back (so total NVMe bytes moved is **2×** the peak file size, using binary `1 GiB = 2^30` bytes throughout): - -- **M1 `eodPrices` (`845.7M` docs):** Under the synthetic average frame-size assumption of `161.7–285.6 B/doc` (`bench-curate-bars-cmd` / `bench-bson-eod-prices`), staging `eodPrices.bson` requires roughly **~127–225 GiB peak scratch file capacity** and **~255–450 GiB total NVMe I/O (write + read-back)** before `qmPrices` (`51.5M`) and `qmFilings` (`30.5M`). -- **M2 intraday (`3.40B` `eodIntraday1M` + `173.3M` `qmIntraday` = `3.57B` docs):** Under an assumed synthetic `150–250 B/doc` average frame size, staging both intraday collections to `.bson` files requires roughly **~499–832 GiB peak scratch file capacity** and **~998–1,664 GiB total NVMe I/O (write + read-back)** on `quant`'s 4 TB SN850X NVMe (which also holds the `~638 GB` MongoDB corpus, PostgreSQL, QuestDB, and curated Parquet). Eliminating that intermediate file via direct Rust `RawDocumentBuf` cursors saves that entire scratch file footprint and extra NVMe write+read pass. *(All byte-size figures are extrapolated from synthetic documents; actual live BSON document sizes are unverified — see Section 7.)* - ---- - -## 4. Options Comparison - -| Dimension | Option A: Keep Current TS + File-Bridge Rust Split | Option B: Direct Read-Only MongoDB Streaming in `tools/curate-etl` (Recommended) | Option C: Full Port of `apps/stock/data-pipeline` to Rust | -| --- | --- | --- | --- | -| **Architecture** | Status quo (`PLATFORM-PLAN.md` §4): TS owns security master, TSV export, raw-BSON export, probes, BullMQ/HTTP; Rust `curate-etl` reads local TSV + `.bson` files | TS keeps security master (Passes 1–6), TSV export (`export-curate-inputs.ts`), probes, BullMQ/HTTP. Rust `curate-etl` gains a read-only MongoDB cursor adapter (`--mongo-uri` / `MONGODB_READ_URI`) feeding the existing `RawDocumentBuf` decoders directly, while **retaining** file-based CLI mode for offline/reproducible tests | Rewrite all 42 TS files (`20,349` LOC) + 47 test files (`35,193` LOC) in Rust (security master, Postgres persistence, TSV/direct PG read, probes, BullMQ worker, HTTP `/health`, plus direct Mongo cursors) | -| **Estimated Effort** | **0 new files/LOC** for M1 bridge; in M2 must extend `RAW_BSON_EXPORT_COLLECTIONS` and add scratch-space management / chunked export for `3.40B` `eodIntraday1M` | **Two-stage effort:**
1. **Cursor-only swap (~4–6 new `.rs` files, ~1,200–1,800 LOC + ~1,000–1,500 test LOC):** Rust `env-safety` URI/host/user read-only guard, sealed `mongodb` read-only `RawDocumentBuf` cursor adapter, and `--mongo-uri` / `--collection` CLI wiring alongside existing file mode.
2. **Bounded-memory partitioning & overlapped I/O (additional ~3–5 `.rs` files / runner refactors, ~1,500–2,500 LOC + ~1,500–2,000 test LOC):** Date/year or key-range partitioned streaming in `run_curate_bars.rs` and `run_curate_events.rs` (which currently accumulate all decoded rows in RAM before sorting/curation) plus bounded channel pipelining between MongoDB cursor reads and `rayon` Parquet / ILP writes.
**Combined:** ~7–11 files, ~2,700–4,300 LOC + ~2,500–3,500 test LOC | **Very large (~40+ `.rs` files, ~15,000–22,000 LOC + ~25,000–35,000 test LOC):** Re-implement Passes 1–6, `persist.ts`, `bar-spans.ts`, `sample-closes.ts`, `source-field-shapes.ts`, `PipelineSyncRepository`, BullMQ Redis protocol, Hono `/health`, and re-verify all 47 test suites (plus Option B's Stage 1+2 work) | -| **New Rust Crates Required** | None (`bson =3.1.0`, `parquet =60.2.0`, `rayon =1.12.0` stay unchanged) | `mongodb` (with `bson-3` feature matching `bson =3.1.0`), `tokio` (minimal `rt-multi-thread`/`net`/`time` for async driver), `url` (or strict custom URI parser for safety guard). *Note: keeps zero Postgres/HTTP/Redis crates in `curate-etl`.* | Everything in Option B **plus** `tokio-postgres` / `sqlx`, `axum` / `hyper` (HTTP `/health`), `redis` + custom BullMQ Lua/stream worker compatibility (no official Rust BullMQ crate), `serde` / `serde_json`, `chrono` / `time` | -| **Expected Runtime & NVMe Gain (Evidence-Backed)** | Baseline: TS `export-raw-bson` (`3.57M–3.83M docs/s` synthetic) + Rust `curate-bars-1d` (`1.87M rows/s` with `rayon` write). Pays full NVMe scratch footprint (~127–225 GiB peak / ~255–450 GiB write+read for M1 `eodPrices`; ~499–832 GiB peak / ~998–1,664 GiB write+read for M2 intraday, synthetic estimates) | **Stage 1 (cursor-only):** Eliminates intermediate `.bson` scratch files (~100% of bulk scratch NVMe capacity and the extra write+read pass) and removes the TS process hop, **without** reducing decoded-row RAM or overlapping curation/Parquet writes (since `run_curate_bars.rs` and `run_curate_events.rs` still buffer decoded rows before sorting).
**Stage 2 (partitioned streaming + pipelining):** Adds bounded-memory execution (needed for global `845.7M` `eodPrices` on `quant`'s `125 GiB` RAM) and overlaps MongoDB wire reads with Rust decode/Parquet/ILP writes.
**End-to-end wall-time speedup is unmeasured** (see Section 7). Zero change to sub-second security-master runs | Same bulk gain as Option B; **< 1–3 seconds saved** on security master (`run.ts` is already `479.6 ms` / `100k` records; `persist.ts` is `2.36 s` / `140k` rows, bound by Postgres `UNNEST` I/O; `export-curate-inputs.ts` is `402.8 ms` / `500k` rows) | -| **Key Risks** | 1. NVMe capacity/wear spike on `quant` when exporting `3.57B` intraday docs to `.bson` files.
2. Two-step manual/scripted orchestration per bulk collection | 1. **Safety-guard parity:** Bypassing TS `assertEnvironmentSafety()` and `MongoDBClient` `mongoReadOnly: true` requires a battle-tested Rust read-only guard (blocking `trading_admin`, loopback/LAN IPv4 variants, and any write command).
2. **Memory scope:** A cursor swap alone does not bound RAM on global `845.7M` `eodPrices` until Stage 2 partitioning lands.
3. **Crate/async footprint:** Adds `mongodb` + `tokio` to Cargo workspace (requires crates.io fetch and offline cache refresh). | 1. **Pass 1–6 parity risk:** Re-verifying 17,924 LOC of subtle ISIN/CUSIP/ATS/ticker-reuse/delisting-chain rules against 40 test suites.
2. **Shared TS contract loss:** Loses `@stock-bot/types` (`ReferenceDataResetRequest`), `@stock-bot/stock-config`, `@stock-bot/postgres` migrations, and BullMQ `{data-pipeline_exchanges}`/`{data-pipeline_symbols}` queue parity with `web-api`.
3. **Safety-guard duplication** for both MongoDB and PostgreSQL.
4. **Multi-week M2 delay** with no user-visible research value | -| **Impact on M2 Work Items** | Slows M2 `bars_1m` (`3.40B` `eodIntraday1M` + `173.3M` `qmIntraday` → QuestDB ILP v2) because raw `.bson` staging doesn't scale cleanly to multi-billion-row streams; `ceoPosts` (`14.8M`) and `qmFinancials` (`2.77M`) remain workable | **Directly accelerates M2:** `tools/curate-etl` streams `eodIntraday1M` (`3.40B`, **split-unadjusting** retroactively adjusted OHLCV via `qmSplits`) and `qmIntraday` (`173.3M`, taking **already-raw** `open..close` and `sharevolume` directly — **no** split un-adjustment) into multi-socket QuestDB ILP v2 (`bars_1m`, `DEDUP UPSERT KEYS(ts, listing_id)`) with zero `.bson` scratch files, verified by the M2 split-boundary comparison (`NEXM.V` `1:20` and `NVDA.US` `10:1` `bars_1m` session closes within `0.5%` of raw `bars_1d` closes); same cursor adapter serves `ceoPosts` (`14.8M`) and `qmFinancials` | **Blocks M2** for weeks while porting already-working M1 security-master code instead of building MCP, PIT fundamentals, QuestDB `10.2.0` `bars_1m`, and Feature Library | - -*Why Option B keeps `export-curate-inputs.ts` in TypeScript:* Exporting `500k` security-master mappings + `100k` listings takes `402.8 ms` (`17.2 MB`) synthetically and already ships with atomic `/current` generation pinning consumed by `curate-etl --curate-inputs`. Keeping it in TypeScript avoids pulling a PostgreSQL driver and `assertSecurityMasterPersistSafety()` duplication into `tools/curate-etl`. - ---- - -## 5. Compliance Check (`D1`–`D12` & QA Database Safety Rules) - -### Locked Decisions `D1`–`D12` (`design/PLATFORM-PLAN.md` §3) - -| Decision | Option A | Option B (Recommended) | Option C | -| --- | --- | --- | --- | -| **D1** (Parquet+DuckDB daily/PIT; QuestDB `10.2.0` intraday) | Compliant | Compliant (directly enables M2 `3.40B` ILP v2 streaming to QuestDB) | Compliant | -| **D2** (Desktop copilot MCP; isolated campaign containers) | Compliant | Compliant | Compliant | -| **D3** (US+CA priority + FX; `ttFutures` out of scope) | Compliant | Compliant | Compliant | -| **D4** (Incremental `web-app` evolution; no rewrite) | Compliant | Compliant | Risk of `web-api` / `PipelinePage` BullMQ contract drift | -| **D5** (Cross-source entity resolution in `data-pipeline`) | Compliant | Compliant — matches `PLATFORM-PLAN.md` §4 (`data-pipeline` TS + `curate-etl` Rust) and `DATA-CONTRACTS.md` §3A (`mongodb::bson::RawDocumentBuf` cursors) | **Reopens §4 layer table** (moves TS entity resolution & orchestration out of TS `data-pipeline` into Rust; requires director sign-off to amend `PLATFORM-PLAN.md`) | -| **D6** (IB Margin `USD`/`CAD` on isolated `9900K`) | Compliant (no paper/live touch) | Compliant (no paper/live touch) | Compliant (no paper/live touch) | -| **D7** (Multi-strategy scope; no macro surprises / Form 4 $) | Compliant | Compliant | Compliant | -| **D8** (Incremental Research Playground) | Compliant | Compliant | Compliant (delays M2 timeline) | -| **D9** (`marimo` Python labs) | Compliant | Compliant | Compliant | -| **D10** (Rolling 6-month Air-Gapped Vault + Post-2023 Recency) | Compliant | Compliant | Compliant | -| **D11** (Materialized batch feature jobs; no Python→TS rewrites) | Compliant | Compliant | Compliant | -| **D12** (Read-only Studio `library.yml` + Postgres findings) | Compliant | Compliant | Compliant | - -### QA Database Safety Rules (`AGENTS.md`) - -| Safety Rule | Option A | Option B (Recommended) | Option C | -| --- | --- | --- | --- | -| **Never drop/reset/write QA MongoDB (`localhost:27017/stock`) from `dev` or tests** | Enforced by `assertEnvironmentSafety()` + `MongoDBClient` `mongoReadOnly: true` + `studio_stock_bot_read` | **Must implement Rust read-only guard parity** before enabling `--mongo-uri`: (1) connect strictly via `MONGODB_READ_URI` with server-side `read@stock` user (`studio_stock_bot_read`); (2) reject `trading_admin` and any non-read-only URI targeting loopback/local-LAN port `27017` (matching `env-safety.ts` IPv4/octal/hex/loopback rules); (3) expose **only** `find` / `RawDocumentBuf` cursor reads in a sealed Rust module with no `insert`/`update`/`delete`/`drop`/`create_index`/`run_command` surface; (4) unit-test all rejected URIs offline | Requires Option B's Rust Mongo guard **plus** full Rust parity for PostgreSQL dev-isolation guards (`assertSecurityMasterPersistSafety`, `NODE_ENV=development` blocking `localhost:5432/trading_bot`, `pg_advisory_xact_lock`, and `rejectDestructiveSync`) | -| **Tests never mutate QA Postgres (`trading_bot`) or QA Mongo (`stock`)** | Compliant (`stock_bot_safety*` + in-memory fakes) | Compliant — retain file-based CLI mode so all `cargo test --workspace --lib --offline` tests run with zero DB connections | Compliant only if every ported Postgres test preserves isolated `stock_bot_safety*` schema creation/teardown | -| **No `data-ingestion` or `9900K` live/paper side effects** | Compliant | Compliant | Compliant | - ---- - -## 6. Recommendation, Implied Follow-Up Tasks & What Not to Port - -### Recommendation - -**Select Option B.** It captures virtually 100% of the real throughput and NVMe-storage benefit of Rust where the data is actually large (`845.7M` `eodPrices`, `51.5M` `qmPrices`, `30.5M` `qmFilings`, and M2's `3.40B` `eodIntraday1M` + `173.3M` `qmIntraday` + `14.8M` `ceoPosts`), aligns word-for-word with `design/PLATFORM-PLAN.md` §4 and `design/DATA-CONTRACTS.md` §3A, requires no reopened locked decisions, and avoids risking or delaying M2 to rewrite 20k LOC of already-fast, heavily-tested TypeScript security-master logic. - -### Implied Follow-Up Tasks (Director-Gated — Not Yet Queued or Enacted) - -If the director approves Option B, the concrete follow-up sequence is: - -1. **Add Rust read-only MongoDB safety guard (`tools/curate-etl/src/mongo_safety.rs`):** Port the URI/host/loopback/IPv4-normalization and `trading_admin`-blocking rules from `apps/stock/config/src/env-safety.ts` with offline unit tests mirroring `test/unit/environment-safety*.test.ts`. -2. **Add sealed read-only MongoDB `RawDocumentBuf` cursor adapter (`tools/curate-etl/src/mongo_stream.rs`):** Add exact-pinned `mongodb` (`bson-3`) + minimal `tokio` to `tools/curate-etl/Cargo.toml`, exposing only allowlisted read-only `find` streams feeding the existing `bson_*` decoders (zero write/admin methods exposed). -3. **Wire `--mongo-uri` / `MONGODB_READ_URI` cursor mode into `curate-bars-1d` and `curate-events` (Stage 1 — cursor swap + adoption parity & provenance checks):** Allow bulk M1 commands to stream directly from read-only QA MongoDB without intermediate `.bson` files while preserving `--eod-prices ` file mode for offline fixture replay. **Adoption gate:** assert byte-identical file-versus-cursor output parity on pinned fixtures, and emit a per-run provenance manifest recording the source snapshot or retained input identifier, exact query bounds (`filter`/date bounds and run timestamp), and the pinned `curate-inputs` security-master `generationId` (so production datasets remain traceable even if a provider later corrects a bar or filing). -4. **Add partitioned bounded-memory streaming & overlapped read/write pipelining to `curate-bars-1d` and `curate-events` (Stage 2 — global-backfill RAM & I/O):** Partition MongoDB queries by calendar year or listing-key range and pipeline async cursor reads with `rayon` Parquet writes so global `845.7M` `eodPrices` and `30.5M` `qmFilings` runs fit comfortably inside `quant`'s `125 GiB` RAM instead of buffering all decoded rows in memory. -5. **Reuse the Rust cursor adapter for M2 `curate-bars-1m` (QuestDB `10.2.0` ILP v2) and `curate-ceo-posts`:** Stream `eodIntraday1M` (`3.40B`, **un-adjusting** retroactively split-adjusted OHLCV via `qmSplits`), `qmIntraday` (`173.3M`, ingesting **already-raw** `open..close` and `sharevolume` directly without split un-adjustment), `CAD.FOREX` `1m` (`5.2M`), and `ceoPosts` (`14.8M`) directly from read-only MongoDB with zero `.bson` scratch files; enforce the M2 exit-criterion split-boundary comparison on `NEXM.V` (`1:20`) and `NVDA.US` (`10:1`) confirming `bars_1m` session closes match raw `bars_1d` closes within `0.5%`. -6. **Keep `run-export-raw-bson.ts` as a diagnostic/fixture tool (optional deprecation later):** Retain T-117 for bounded `--limit` fixture captures and offline debugging; remove it from the bulk production path once Step 3 (and Step 4 for global backfills) is verified on `quant`. - -### What Should NOT Be Ported to Rust - -- **Pass 1–6 Security Master (`apps/stock/data-pipeline/src/security-master/` — 17,924 LOC, 40 test files):** Logic- and review-bound, runs in sub-second synthetic time, and has complex domain heuristics (ISIN/CUSIP rescue, IB ATS routing, ticker-reuse spans, OTC delisting chains, override precedence) that are faster to inspect and iterate in TypeScript. -- **PostgreSQL Security-Master Persistence (`persist.ts`) & TSV Exporter (`export-curate-inputs.ts`):** Already batched via `UNNEST` / server-side `NO SCROLL` cursor (`2.36 s` / `140k` rows; `0.40 s` / `500k` mappings) and tightly integrated with `@stock-bot/postgres` migrations and `assertSecurityMasterPersistSafety()`. -- **Field-Shape Probe (`source-field-shapes.ts` / `probe-source-field-shapes.ts`):** Bounded `<= 10k`-doc diagnostic utility. -- **Service Control Plane (`handlers/`, `repositories/`, `routes/`, `index.ts`):** BullMQ `{data-pipeline_exchanges}`/`{data-pipeline_symbols}` queue consumers (`getFullQueueName` in `libs/core/queue/src/service-utils.ts`), `PipelineSyncRepository`, and Hono `GET /health` tightly integrated with `@stock-bot/di`, `@stock-bot/queue`, `@stock-bot/types`, and `web-api`. - ---- - -## 7. Not Verified - -The following items were **not measured** in this docs-only spike and can only be verified on the `quant` host (`10.0.0.51`) or against live read-only QA MongoDB / dev PostgreSQL: - -1. **Live MongoDB cursor throughput, WiredTiger contention, and end-to-end Option B wall-time speedup:** All `export-raw-bson.ts` (`3.57M–3.83M docs/s`) and `curate-etl` (`1.87M rows/s` with `rayon` write) numbers are local synthetic benchmarks. Actual `quant` wall time and the net end-to-end speedup of Option B (both Stage 1 cursor-only and Stage 2 overlapped I/O) are **unmeasured** and depend on WiredTiger disk reads (`--wiredTigerCacheSizeGB 16`), localhost TCP framing, BSON wire overhead on `stock` (`~638 GB`), and NVMe contention. -2. **Real BSON document sizes & NVMe scratch footprint:** The intermediate `.bson` size estimates — **~127–225 GiB peak file capacity (~255–450 GiB total write+read I/O)** for `845.7M` `eodPrices` at synthetic `161.7–285.6 B/doc`, and **~499–832 GiB peak file capacity (~998–1,664 GiB total write+read I/O)** for `3.40B` `eodIntraday1M` + `173.3M` `qmIntraday` at assumed `150–250 B/doc` (binary `1 GiB = 2^30` bytes) — extrapolate from synthetic document byte sizes; actual uncompressed BSON sizes in QA MongoDB are unmeasured. -3. **`quant` 24-thread `rayon` scaling and peak RAM:** The `4.72x` parallel Parquet write speedup (`94.42 ms` vs `445.79 ms`) was measured locally on a 32-thread host on `1,000,000` synthetic rows. Peak RAM and scaling on `quant` (`12900K`, 24 threads, `125 GiB` RAM) for the US+CA subset (~100–150M `eodPrices` rows, estimated `20–30 GiB` peak RAM) vs. full `845.7M` global rows (`> 160 GiB` unsharded, requiring date/key sharding or `--threads 1`) remain unverified. -4. **Live `bar-spans.ts` and Pass 4 `sample-closes.ts` wall time:** MongoDB `$group` aggregation time on `845.7M` `eodPrices` and `51.5M` `qmPrices`, plus live 25-date `{ date: { $in: sampleDates } }` index selectivity, have not been timed against live QA MongoDB. -5. **Unverified live provider field shapes:** Exact field names and BSON types on live QA MongoDB for `ceoShorts` (`--shares-short-field`, `timestamp` unit), `qmFilings` (`--filings-form-type-field`, `symbol` vs `qmSearchCode`), `qmEarnings` optional fields, `qmDividends` (`amount`/`currency`), `teMarketData` (`t` epoch unit), and `qmPrices.date` string vs `DateTime` format remain pending the first host run of `probe-source-field-shapes.ts`. -6. **QuestDB `10.2.0` ILP v2 throughput (M2):** Multi-socket Rust ILP v2 ingestion rate into `bars_1m` (`PARTITION BY MONTH`, `DEDUP UPSERT KEYS(ts, listing_id)`) on `quant` has not been benchmarked. -7. **Rust `mongodb` crate compile time and transitive crate count:** Exact transitive dependency footprint and offline build time for `mongodb` (`bson-3`) + `tokio` inside this workspace have not been measured because this spike adds no crates. - ---- - -## Addendum: M1 Live Verification & Final Option B Record (`2026-11-30`) - -During Milestone `M1` closure on branch `m1-close-evidence`, the Option B Rust MongoDB driver and CLI wiring (`tools/curate-etl`) were implemented, compiled offline, unit/integration-tested, and executed end-to-end against live read-only QA MongoDB (`studio_stock_bot_read@stock`) on `quant` (`10.0.0.51`) into isolated output directory `/mnt/data/stockbot/m1-isolated/curated`. Every Section 7 unknown applicable to `M1` is now resolved empirically (item 6 — QuestDB `10.2.0` ILP v2 — remains scoped strictly to `M2`): - -### A.1 Dependency Footprint & Offline Build/Test Verification (Resolves §7.7) - -- **Driver pin (`tools/curate-etl/Cargo.toml`):** `mongodb = "=3.10.2"` (`default-features = false`, features `compat-3-3-0`, `bson-3`, `sync`, `rustls-tls`, `dns-resolver`). -- **Transitive crate delta:** `123` transitive crates added to `Cargo.lock` (all vendored/cached for `--offline` builds; zero OpenSSL system dependency). -- **Offline build & tests:** - - `CARGO_BUILD_JOBS=2 cargo build --release -p curate-etl --offline`: **PASSED** (`1m 00s` incremental, `0` compiler warnings, `13 MB` static-TLS release binary). - - `CARGO_BUILD_JOBS=2 bun run test:native`: **PASSED** (`150` `apps/stock/engine` lib tests + `582` `curate-etl` unit tests + all `45` `curate-etl` integration/contract suites including `mongo_driver_cli_contract.rs`, `0` failures). -- **Read-only safety parity:** `tools/curate-etl/src/mongo_safety.rs` and `tools/curate-etl/src/mongo_stream.rs` enforce `MONGODB_READ_URI`, reject `trading_admin` and writable loopback/LAN URIs, and expose a sealed `ReadOnlyMongoClient` with read-only raw-BSON cursors only (zero write/admin/drop/index methods). - -### A.2 Live Provider Field Shapes & Empirical Findings (Resolves §7.5) - -Measured by `apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts` (`7,435` docs across all `8` M1 collections in `0.7 s`, recorded in `design/data-pipeline/m1-source-field-shapes.md`) plus live curation verification: - -- **`qmSplits` sign convention (critical empirical catch):** Across all `16,892 / 16,892` (`100.00%`) `qmSplits` documents with numeric `forfactor`/`tofactor` (out of `18,751` total), QuoteMedia stores `splitratio = forfactor / tofactor = old_shares / new_shares` (e.g., `NVDA 2024-06-10`: `forfactor=1, tofactor=10, splitratio=0.1`; `GE 2021-08-02`: `forfactor=8, tofactor=1, splitratio=8`). `tools/curate-etl/src/bson_qm_actions.rs` now converts to canonical `new_shares / old_shares` via exact `tofactor / forfactor` (avoiding 6-decimal truncation like `0.142857` for 7:1) or `1.0 / splitratio` when `forfactor`/`tofactor` are blank. -- **`ceoShorts` mapping key:** `ceoShorts.symbol` uses exchange-suffixed tickers (`"A.V"`, `"ACB.TO"`) matching `provider_mapping(source='eod')`, with fields `number_of_shares` and `net_change`. -- **`qmFilings` Canadian keys:** `qmFilings` omits `:CA` on Canadian `symbol` rows (`symbol: "RY", exchange: "TSX"`); `bson_qm_events.rs` qualifies Canadian exchanges to `"{symbol}:CA"` during `provider_mapping(source='qm')` resolution. -- **`qmDividends`:** Confirmed `amount` (`100%` numeric) and `currency` (`92.8%` present; missing-currency rows cleanly counted as decode rejects). - -### A.3 Live `quant` Curation & Security-Master Timings (Resolves §7.1–§7.4) - -| Pipeline Stage | Runtime / Host | Input Streamed (Read-Only QA Mongo) | Curated Output (Isolated Path) | Wall Time | -| --- | --- | --- | --- | ---: | -| Security-Master Passes 1–6 + dev Postgres persist (`apps/stock/data-pipeline`, TS) | Workstation -> `localhost:5433/trading_bot_dev` | `317.8k` `eodSymbols`, `18.4k` `ibSymbols`, `47.2k` `qmSymbols`, `12.6k` `ceoSymbols`, `230` `eodSymbolChange` + bar-span aggregations + 25-date Pass 4 closes | `63,703` instruments, `64,804` listings, `109,194` mappings, `93` OTC continuities (`eod=100.0%`, `ib=97.9%`, `qm=97.1%`, `ceo=95.8%` gate-eligible) | `7m 23s` total (`2.86 s` idempotent Postgres persist) | -| `curate-fx-1d --from-mongo` | `quant` (`10.0.0.51`, Rust) | `CAD.FOREX` + `teMarketData.USDCAD` | `fx_1d/part.parquet`: `12,273` rows (`356 KB`, `2,701/2,701` overlap checks passed, max diff `0.386%`) | **`0.055 s`** | -| `curate-corporate-actions --from-mongo` | `quant` (Rust) | `18,751` `qmSplits` + `495,942` `qmDividends` + `1,573` delistings | `corporate_actions/part.parquet`: `355,718` rows (`13,877` listings, `2.47 MB`) | **`0.702 s`** | -| `curate-shorts --from-mongo` | `quant` (Rust) | `692,904` `ceoShorts` | `shorts/part.parquet`: `502,610` rows (`5,184` Canadian listings, `3.58 MB`) | **`0.831 s`** | -| `curate-adj-factors --from-mongo` (`point_in_time_fenced`, `--vault-cutoff 2025-02-13`, `--date-gte 1976-01-01`) | `quant` (Rust) | `18,738` `qmSplits` + `464,850` `qmDividends` + `103.38M` `bars_1d` `prev_close` index | `adj_factors/part.parquet`: `343,746` rows (`12,512` listings, `3.90 MB`; `443` splits + `9,817` divs fenced) | **`5.976 s`** | -| `curate-events --from-mongo --date-gte 2017-01-01` | `quant` (Rust) | `16,829,977` `qmFilings` (`27.06 GB` raw BSON, string `timefiled`) + `218,815` `qmEarnings` (`75.80 MB`, BSON `DateTime` `reportDate`; `8 MB` peak chunk) | `events/year=2017..2025/part.parquet`: `2,771,888` total events (`2,569,808` filings across `11,072` listings + `202,080` earnings across `8,348` listings; `17,284` linked to same-day filings + `201,531` lagged `16:05 ET`; `86.08 MB`) | **`76.466 s`** | -| `curate-bars-1d --from-mongo --with-qm-prices --date-gte 2005-01-01 --threads 8` | `quant` (Rust, indexed 250-key `$in` chunks) | `104,009,957` `eodPrices` (`24.63 GB`) + `40,052,628` `qmPrices` (`12.97 GB`) + `18,751` `qmSplits` | `bars_1d/year=2005..2025/part.parquet`: `103,381,236` rows (`60,848` listings, `21` files, `1.106 GB`; `33.50M/38.28M` QM volume checks within 1%; `NVDA 2024-06-07` rel diff `5.82e-8`) | **`492.550 s` (`8m 12s`)** | - -*Index-selectivity finding:* Querying `eodPrices` with a bare `{ date: { $gte: "2005-01-01" } }` selects `date_1_eodSearchCode_1` and causes random WiredTiger seeks (~100 min). Streaming mapped US/CA `eodSearchCode`s in 250-key `$in` chunks (`ChunkedMongoRawDocumentSource`) hits `{"eodSearchCode": 1}` sequentially and streams `37.6 GB` of raw BSON (`144.06M` docs) + writes `1.106 GB` of Zstd Parquet with **zero intermediate `.bson` scratch files** in `8m 12s`. - -### A.4 Final Recommendation (Confirmed) - -**Do NOT move `apps/stock/data-pipeline` itself to Rust. Lock Option B permanently:** -1. **Keep `apps/stock/data-pipeline` in TypeScript** for security-master Passes 1–6 (`17.9k` LOC, `40` test files, complex issuer/ATS/delisting heuristics), PostgreSQL persistence, TSV generation (`export-curate-inputs.ts`), field probes, and BullMQ/Hono orchestration. -2. **Keep bulk curation in Rust (`tools/curate-etl` with `--from-mongo` raw-BSON cursors)** — now proven end-to-end on `quant` at `103.38M` daily bars (`8m 12s`, `0` scratch `.bson` bytes) and `16.83M` filings + `218.8k` earnings (`76.5 s`). -3. **Keep `M2` intraday QuestDB `10.2.0` ILP v2 ingestion (`3.40B` `eodIntraday1M` + `173.3M` `qmIntraday` + `14.8M` `ceoPosts`) scoped to `M2`** inside `tools/curate-etl`, reusing the verified `ReadOnlyMongoClient` + `ChunkedMongoRawDocumentSource` infrastructure built in `M1`. diff --git a/design/m2-baseline-report.md b/design/m2-baseline-report.md deleted file mode 100644 index 4bbefde1..00000000 --- a/design/m2-baseline-report.md +++ /dev/null @@ -1,175 +0,0 @@ -# Milestone M2 Baseline Verification Report (T-128 / M2.0) - -**Verdict:** **GREEN — Baseline verified for M2 start (0 real failures).** All 7 sandbox-runnable gates passed on `master` (`56b73b7e663d293079ab7bac264950dfa7a68b00`), all 40 sandbox `bun test` failures are verified sandbox-boundary errors (38 worktree `.git` metadata + 2 `stock_bot_safety*` PostgreSQL env), and Studio's authoritative unsandboxed runs — **Build `#1027`** (`bun run build`) and **Test `#1028`** (`bun --env-file=/home/boki/.studio/test-env/stock-bot.env test && CARGO_BUILD_JOBS=2 cargo test --workspace --lib --offline`) — passed (exit `0`) on reviewed commit `904def37e2e9cff5dce538c3d1f61ffca3594e9d`. - ---- - -## 1. Repository Provenance & Revision Mapping - -### Revisions Checked - -| Role | Full SHA | Notes | -| --- | --- | --- | -| Accepted M1 commit | `d52aa20bff3f5c259fb6e2bcfc2d3a78ad5224b1` | Director-accepted M1 baseline | -| `master` baseline | `56b73b7e663d293079ab7bac264950dfa7a68b00` | Base revision where all sandbox gates and full sandbox `bun test` ran | -| Reviewed report commit (`feat/m2-baseline-gates`) | `904def37e2e9cff5dce538c3d1f61ffca3594e9d` | Adds only `design/m2-baseline-report.md` on top of `56b73b7e663d293079ab7bac264950dfa7a68b00`; revision tested by Studio Build `#1027` and Test `#1028` | - -### Unsandboxed Ancestry Checks (Confirmed) - -| Check | Target Revision | Exit Code | Confirmed By | -| --- | --- | --- | --- | -| `git merge-base --is-ancestor d52aa20bff3f5c259fb6e2bcfc2d3a78ad5224b1 56b73b7e663d293079ab7bac264950dfa7a68b00` | `master` (`56b73b7e663d293079ab7bac264950dfa7a68b00`) | `0` | Producer (plan worktree) and Reviewer | -| `git merge-base --is-ancestor d52aa20bff3f5c259fb6e2bcfc2d3a78ad5224b1 904def37e2e9cff5dce538c3d1f61ffca3594e9d` | Reviewed HEAD (`904def37e2e9cff5dce538c3d1f61ffca3594e9d`) | `0` | Reviewer | - -### Sandbox `git` Boundary Errors (Preserved Verbatim) - -Worktree `.git` file content: -```text -gitdir: /home/boki/repos/stock-bot/.git/worktrees/slot-1 -``` - -Because `/home/boki/repos/stock-bot/.git/worktrees/slot-1` lies outside the agent sandbox boundary, `git` commands inside the sandbox exit `128` as expected (no exit `0` was fabricated inside the sandbox): - -| Command (inside sandbox) | Exit Code | Output (verbatim) | -| --- | --- | --- | -| `git rev-parse HEAD` | `128` | `fatal: gitfile does not point to a valid repository: /home/boki/.studio/worktrees/stock-bot/slot-1/.git` | -| `git merge-base --is-ancestor d52aa20bff3f5c259fb6e2bcfc2d3a78ad5224b1 HEAD` | `128` | `fatal: gitfile does not point to a valid repository: /home/boki/.studio/worktrees/stock-bot/slot-1/.git` | - -### Which Checks Ran on Which Revision - -| Verification Run | Revision | Environment | Outcome | -| --- | --- | --- | --- | -| 7 sequential sandbox-runnable gates (§2) | `56b73b7e663d293079ab7bac264950dfa7a68b00` | Agent sandbox | PASS (7/7 exit `0`) | -| Full unfiltered `bun test` triage (§3) | `56b73b7e663d293079ab7bac264950dfa7a68b00` | Agent sandbox | 3,498 pass, 125 skip, 40 fail (all sandbox-only), 0 real failures | -| Studio Build `#1027` (`bun run build`) (§4) | `904def37e2e9cff5dce538c3d1f61ffca3594e9d` | Studio unsandboxed | PASS (exit `0`) | -| Studio Test `#1028` (`bun --env-file=... test && cargo test ...`) (§4) | `904def37e2e9cff5dce538c3d1f61ffca3594e9d` | Studio unsandboxed | PASS (exit `0`) | -| Targeted 10-file sandbox re-run for individual failure names (§3) | `904def37e2e9cff5dce538c3d1f61ffca3594e9d` | Agent sandbox | Confirmed exact same 40 failures across the 10 files | - ---- - -## 2. Sandbox-Runnable Gates (Sequential — Revision `56b73b7e663d293079ab7bac264950dfa7a68b00`) - -All seven sandbox-runnable gates exited `0` with zero failures and zero warnings: - -| Gate Command | Exit Code | Result / Counts | -| --- | --- | --- | -| `bun run typecheck` (`tsc --project tsconfig.check.json --noEmit`) | `0` | PASS (0 errors) | -| `bun run test:contracts` (`tsc --project tsconfig.contracts.json --noEmit`) | `0` | PASS (0 errors) | -| `bun run lint:check` (`eslint apps/stock libs tools test --ext .ts,.tsx --max-warnings 0`) | `0` | PASS (0 errors, 0 warnings) | -| `bun run test:utils` (`bun test libs/utils/test/ libs/core/handlers/test/base-handler-http.test.ts`) | `0` | PASS — 32 pass, 0 fail (59 `expect()` calls, 3 files) | -| `bun run test:calculations` (`bun test libs/calculations/test/`) | `0` | PASS — 144 pass, 0 fail (76,602 `expect()` calls, 12 files) | -| `CARGO_BUILD_JOBS=2 bun run test:native` (`cargo test -p engine --lib --offline && cargo test -p curate-etl --offline`) | `0` | PASS — 1,078 passed, 0 failed, 4 ignored across 49 test binaries/suites | -| `CARGO_BUILD_JOBS=2 cargo test --workspace --lib --offline` | `0` | PASS — 732 passed, 0 failed, 4 ignored across 2 lib suites | - ---- - -## 3. Full Unfiltered Sandbox `bun test` Triage (Revision `56b73b7e663d293079ab7bac264950dfa7a68b00`) - -- **Command:** `bun test` (complete unfiltered stdout/stderr captured and inspected from start to finish) -- **Exit Code:** `1` -- **Totals:** `3,498 pass`, `125 skip`, `40 fail`, `3 errors`, `885,783 expect() calls` across `282 files` (`57.36s`) -- **Skips note:** The `125 skip` count was reported by Bun from pre-existing conditional skips in the repository (e.g., suites that self-skip when PostgreSQL / service environment variables are absent in the sandbox). This task introduced **zero** test skips, mocks, or deletions. -- **Real failures:** **`0`** (all `40` failures and `3` `beforeAll` unhandled errors are expected sandbox-boundary failures). - -### Failure Classification Summary (10 files, 40 failures, 3 unhandled `beforeAll` errors) - -| Test File | Fails (+ Unhandled Errors) | Exact Error Text | Classification | -| --- | --- | --- | --- | -| `test/integration/retained-strategy-worker.test.ts` | 15 (+1 `beforeAll` error) | `error: Cannot read packaging source identity: git rev-parse failed` (`scripts/package-builtin-strategies.ts:42:11`) | **(a) Expected sandbox-only** — worktree `.git` metadata outside sandbox | -| `test/integration/chronological-validation-native.test.ts` | 2 | `error: Cannot read packaging source identity: git rev-parse failed` (`scripts/package-builtin-strategies.ts:42:11`) | **(a) Expected sandbox-only** — worktree `.git` metadata outside sandbox | -| `test/integration/reproduction-comparison.test.ts` | 4 (+1 `beforeAll` error) | `error: Cannot read packaging source identity: git rev-parse failed` (`scripts/package-builtin-strategies.ts:42:11`) | **(a) Expected sandbox-only** — worktree `.git` metadata outside sandbox | -| `test/postgres/security-master-run.test.ts` | 1 | `error: Dedicated stock_bot_safety database required` (`test/postgres/security-master-run.test.ts:37:11`) | **(a) Expected sandbox-only** — requires `PIPELINE_TEST_DATABASE_URL` (`/home/boki/.studio/test-env/stock-bot.env`) & host PostgreSQL `127.0.0.1:5432` | -| `test/postgres/security-master-export-curate-inputs.test.ts` | 1 | `error: Dedicated stock_bot_safety database required` (`test/postgres/security-master-export-curate-inputs.test.ts:35:11`) | **(a) Expected sandbox-only** — requires `PIPELINE_TEST_DATABASE_URL` (`/home/boki/.studio/test-env/stock-bot.env`) & host PostgreSQL `127.0.0.1:5432` | -| `scripts/test/strategy-packaging.test.ts` | 10 (+1 `beforeAll` error) | `error: Cannot read packaging source identity: git rev-parse failed` (`scripts/package-builtin-strategies.ts:42:11`) | **(a) Expected sandbox-only** — worktree `.git` metadata outside sandbox | -| `scripts/test/benchmark-sma.test.ts` | 1 | Child process exit `1`: `git failed: fatal: gitfile does not point to a valid repository: /home/boki/.studio/worktrees/stock-bot/slot-1/.git` | **(a) Expected sandbox-only** — worktree `.git` metadata outside sandbox | -| `scripts/test/benchmark-replay.test.ts` | 2 | Child process exit `1`: `git failed: fatal: gitfile does not point to a valid repository: /home/boki/.studio/worktrees/stock-bot/slot-1/.git` | **(a) Expected sandbox-only** — worktree `.git` metadata outside sandbox | -| `scripts/test/benchmark-research.test.ts` | 1 | Child process exit `1`: `git failed: fatal: gitfile does not point to a valid repository: /home/boki/.studio/worktrees/stock-bot/slot-1/.git` | **(a) Expected sandbox-only** — worktree `.git` metadata outside sandbox | -| `scripts/test/audit-secrets-repo.test.ts` | 3 | Child process exit `1`: `Cannot inspect tracked files for the secret audit` (`git ls-files` blocked by worktree `.git` outside sandbox) | **(a) Expected sandbox-only** — worktree `.git` metadata outside sandbox | - -### Individual Failing Test Names (All 40 Accounted For) - -1. **`test/integration/retained-strategy-worker.test.ts`** (15 fails; `beforeAll` failed on `git rev-parse`): - - `retained canonical strategy worker > sma_crossover exact packaged bytes match the native report and repeat identically` - - `retained canonical strategy worker > mean_reversion exact packaged bytes match the native report and repeat identically` - - `retained canonical strategy worker > a retained version executes its own bytes when the current constructor differs` - - `retained canonical strategy worker > build and retained hashes are checked before module or factory side effects` - - `retained canonical strategy worker > eligible exact single-series data and ownership are required before bundle import` - - `retained canonical strategy worker > factory identity, missing exports, thrown decisions and no-result exits fail closed` - - `retained canonical strategy worker > capture detaches all admitted inputs before the caller can mutate them` - - `retained canonical strategy worker > result parser rejects false identity, policy and statistical claims` - - `retained canonical strategy worker > typed worker rejects a malformed completed envelope: result.artifactHash = "f".repeat(64)` - - `retained canonical strategy worker > typed worker rejects a malformed completed envelope: result.build.workerSha256 = "f".repeat(64)` - - `retained canonical strategy worker > typed worker rejects a malformed completed envelope: result.financial.policy.matching.risk.feeRate = "0"` - - `retained canonical strategy worker > typed worker rejects a malformed completed envelope: result.analytics.metrics.exposureTime = null` - - `retained canonical strategy worker > typed retained results wait for successful child exit` - - `retained canonical strategy worker > alternate and source workers cannot claim the bundled worker identity` - - `retained canonical strategy worker > hard cancellation discards retained execution and the worker can be reused` - -2. **`test/integration/chronological-validation-native.test.ts`** (2 fails; `git rev-parse` in strategy packaging): - - `chronological preflight slices on the authoritative native engine > each phase independently starts with initial cash, empty positions and fresh state; warmup cannot trade` - - `chronological preflight slices on the authoritative native engine > changing only the test suffix cannot change training or validation inputs, native economics or decisions` - -3. **`test/integration/reproduction-comparison.test.ts`** (4 fails; `beforeAll` failed on `git rev-parse`): - - `economic_hash_parity: two actual replays ignore only admission identities and wall-clock metadata` - - `economic hash retains fees, ordered fills, decision ownership, risk, nulls and statistical facts` - - `economic hash preserves actual market-session identities and execution policy` - - `economic hash rejects mixed result/request/session identities rather than hiding them` - -4. **`test/postgres/security-master-run.test.ts`** (1 fail; requires `PIPELINE_TEST_DATABASE_URL` pointing to `stock_bot_safety*`): - - `composeSecurityMasterRun -> persistSecurityMaster PostgreSQL integration > persists FB vs FB-ETF distinct listing_ids, SIVB -> SIVBQ continuity, Pass 4 conflicts (including shared left endpoint), and is idempotent on re-run` - -5. **`test/postgres/security-master-export-curate-inputs.test.ts`** (1 fail; requires `PIPELINE_TEST_DATABASE_URL` pointing to `stock_bot_safety*`): - - `exportCurateInputs PostgreSQL integration (isolated stock_bot_safety_*) > exports exact TSV bytes read-only and matches across chunkSize=1 and chunkSize=5000` - -6. **`scripts/test/strategy-packaging.test.ts`** (10 fails; `beforeAll` failed on `git rev-parse`): - - `offline reviewed strategy packaging > repeat packaging retains byte-identical self-contained bundles and lock bytes` - - `offline reviewed strategy packaging > source revision, dirty state, compiler and public descriptor identity are truthful` - - `offline reviewed strategy packaging > isolated bundles require no workspace, installed packages, native engine or service runtime` - - `offline reviewed strategy packaging > residual imports and require references reject instead of retaining incomplete bundles` - - `offline reviewed strategy packaging > packaging inspects generated text without importing or executing it` - - `offline reviewed strategy packaging > a bundle missing its declared factory cannot be published as a valid built-in package` - - `offline reviewed strategy packaging > sma_crossover: source and packaged decisions/checkpoints agree through entry, exit and restore` - - `offline reviewed strategy packaging > mean_reversion: source and packaged decisions/checkpoints agree through entry, exit and restore` - - `offline reviewed strategy packaging > packaged factories retain strict parameter validation and canonical aliases` - - `offline reviewed strategy packaging > CLI writes the retained package envelope and rejects unsupported options` - -7. **`scripts/test/benchmark-sma.test.ts`** (1 fail; child `git` blocked by worktree `.git`): - - `sma_recorded_decision_parity verifies six shapes and actual financial/diagnostic identities` - -8. **`scripts/test/benchmark-replay.test.ts`** (2 fails; child `git` blocked by worktree `.git`): - - `all tiny replay profiles pin financial expectations and distinct strategy identities` - - `canonical self-test measures real sessions and verifies repeated full-result hashes` - -9. **`scripts/test/benchmark-research.test.ts`** (1 fail; child `git` blocked by worktree `.git`): - - `existing-path research benchmark > tiny native self-test records honest phases and pinned identities without timing thresholds` - -10. **`scripts/test/audit-secrets-repo.test.ts`** (3 fails; `git ls-files` blocked by worktree `.git`): - - `audit:secrets passes on the real repository` - - `real-repository audit ignores inherited GIT_DIR, GIT_WORK_TREE and GIT_INDEX_FILE` - - `audit:secrets passes on the real repository when run from scripts subdirectory` - ---- - -## 4. Authoritative Unsandboxed Gate (Studio Runner — Revision `904def37e2e9cff5dce538c3d1f61ffca3594e9d`) - -Per `studio.config.json`, Studio executed both authoritative unsandboxed commands against reviewed commit `904def37e2e9cff5dce538c3d1f61ffca3594e9d` (which has identical code and tests to `master` `56b73b7e663d293079ab7bac264950dfa7a68b00`, differing only by adding `design/m2-baseline-report.md`): - -| Studio Run | Revision | Exact Command | Exit Code | Result / Counts | -| --- | --- | --- | --- | --- | -| **Build `#1027`** | `904def37e2e9cff5dce538c3d1f61ffca3594e9d` | `bun run build` | `0` | **PASS** (reported passed by Studio; per-package counts not exposed in the Studio run summary) | -| **Test `#1028`** | `904def37e2e9cff5dce538c3d1f61ffca3594e9d` | `bun --env-file=/home/boki/.studio/test-env/stock-bot.env test && CARGO_BUILD_JOBS=2 cargo test --workspace --lib --offline` | `0` | **PASS** (reported passed by Studio, exercising all 38 `.git`-dependent tests, the 2 `stock_bot_safety*` PostgreSQL tests, and the Rust workspace lib tests; per-test Bun counts are not exposed in the Studio run summary, while the Rust half verified `732 passed, 0 failed, 4 ignored` on the same tree) | - -This closes the authoritative gate for T-128: every failure observed in the sandbox (`40/40`) passed in Studio's unsandboxed test run `#1028`, and `bun run build` passed in Studio build `#1027`. Updating this report triggers a fresh Studio build and test run on the updated doc-only commit. - ---- - -## 5. Read-Only M2 Planning Facts (No Config or Code Changes Made) - -1. **`@modelcontextprotocol/sdk` availability and agent network allowlist:** - - `@modelcontextprotocol/sdk` is **not present** in `bun.lock` or any `package.json` (`package.json`, `apps/`, `libs/`, `tools/`). - - `studio.config.json` (`agentExecution.programmer.networkDomains` and `agentExecution.qa.networkDomains`, lines 3–19) allows only `crates.io`, `index.crates.io`, and `static.crates.io` (no npm registry access in agent sessions). Any M2 MCP server task that needs `@modelcontextprotocol/sdk` will either need a lightweight dependency-free JSON-RPC 2.0 / MCP stdio+SSE implementation or an explicit dependency install / networkDomain decision before implementation. -2. **Python test suite (`python/tests/test_stockbot_sdk.py`) coverage:** - - `python/tests/test_stockbot_sdk.py` exists under `python/tests/`, but **is not invoked** by any script in `package.json`, `scripts/check.ts`, or `studio.config.json` (`test.command`). -3. **`studio.config.json` `docs.*` path mismatch (left untouched):** - - `docs/` does not exist at the repository root. - - `studio.config.json` lines 43–55 still point `docs.index`, `docs.plan`, `docs.milestones`, `docs.dataContracts`, `docs.validation`, `docs.dataPipeline`, and `docs.servers` at `docs/...` paths, whereas the actual milestone and architecture documents live under `design/` (e.g., `design/MILESTONES.md` lines 83–103 contain the M2 checklist and exit criteria). `studio.config.json` was intentionally left untouched in this task. diff --git a/design/m2-completion-audit.md b/design/m2-completion-audit.md deleted file mode 100644 index 19e06e5d..00000000 --- a/design/m2-completion-audit.md +++ /dev/null @@ -1,122 +0,0 @@ -# Milestone M2 Completion Audit & M3 Readiness Report (T-204) - -**Verdict:** **HOLD M3 — M2 is ~70% complete on the audited `feat/audit-m2-completion-status-m3` checkout (branched from `master`; exact `master` commit SHA pending host-side `git` verification), with 7 concrete wiring/contract gaps remaining before M2 closure.** - -All sandbox-runnable TypeScript, ESLint, contract, and Rust native gates passed in the programmer's sandboxed run on the review checkout (`0` errors, `0` warnings), and Studio's unsandboxed review-branch runs (`#1597` build and `#1598` test suite) passed. Core M2 building blocks — `send-ilp` (`T-190`), the 6-tool MCP copilot server, file-mode PIT fundamentals/`ceoPosts`/`teData` curaters, QuestDB `10.2.0` schemas, and the TypeScript Feature Library — are landed and tested. However, desktop Claude Code cannot launch the MCP server end-to-end (`T-196` entrypoint is absent from the checkout), `ceoPosts` writes `"post"` instead of `"ceo_post"`, `MarketDataStore` rejects `crossSection`/`macroAsOf`/`fx('1m')`, `curate-qm-bars-1m` has no CLI subcommand, Python `stockbot` lacks `register_signal` and M2 store methods, and the live `quant` QuestDB `10.2.0` preflight, observed split-boundary check, and latency gates remain unverified. - -> **Scope & Provenance Notes** -> - **Audit-only:** Zero production code, build config, or CI changes (project CI is off). -> - **Audited checkout & `master` relationship:** Audited in the task worktree on branch `feat/audit-m2-completion-status-m3` (branched from `master` for `T-204`). Because worktree `.git` metadata lives outside the agent sandbox, the exact `master` commit SHA and `studio/auto-*` branch history could not be read here and remain **PENDING** host-side verification. Every deliverable below was verified directly from source files, exports, CLI parsers, and test execution in this checkout. -> - **Documentation path drift:** Milestone and contract docs moved from `docs/` to `design/`, while `AGENTS.md` (lines 43–48), `CLAUDE.md` (lines 3, 7–11), `README.md` (lines 7, 9, 11–13, 142, 264, 435), and `studio.config.json` still reference `docs/*.md`. -> - **Prior M1 deferral:** Per settled director decision (`d52aa20`), M1 equity eligibility classification and cutoff-separated Parquet benchmarking stay deferred in the backlog and do not block M2. - ---- - -## 1. Verification Gate Results & Pending Host Checks - -### 1.1 Programmer Sandbox Runs (Review Worktree `feat/audit-m2-completion-status-m3`) - -Executed inside the agent sandbox (network disabled; zero contact with QA MongoDB `27017/stock` or QA PostgreSQL `5432/trading_bot`; counts below are attributed to the programmer's sandbox execution without retained log files on disk): - -| Gate / Suite | Command | Exit | Programmer-Observed Outcome & Counts | -| --- | --- | :---: | --- | -| Typecheck | `bun run typecheck` | `0` | **PASS** — `0` errors (`tsc --project tsconfig.check.json --noEmit`) | -| Contracts | `bun run test:contracts` | `0` | **PASS** — `0` errors (`tsc --project tsconfig.contracts.json --noEmit`) | -| Lint | `bun run lint:check` | `0` | **PASS** — `0` errors, `0` warnings (`--max-warnings 0`) | -| Utils | `bun run test:utils` | `0` | **PASS** — `32` pass, `0` fail (`59` expects, `3` files) | -| Calculations | `bun run test:calculations` | `0` | **PASS** — `144` pass, `0` fail (`76,602` expects, `12` files) | -| Native Rust | `CARGO_BUILD_JOBS=2 bun run test:native` | `0` | **PASS** — `1,548` passed, `0` failed, `4` ignored across `57` suites (`engine` + `curate-etl`, incl. `tcp_sends_separate_shards_and_half_closes`, `restatement_of_q1_after_q2_updates_q1_and_ttm_without_overwriting_q2`, and the synthetic `split_boundary_nvda_and_nexm_match_raw_bars_1d_closes` fixture) | -| M2 Research, DuckDB, QuestDB & Scripts | `bun test libs/research/ libs/data/duckdb/ libs/data/questdb/ scripts/test/security.test.ts scripts/test/workspace.test.ts` | `0` | **PASS** — `1,032` pass, `0` fail (`80,869` expects, `63` files; includes real-DuckDB `fundamentalsAsOf` restatement fixture and MCP Vault-fence suite) | -| Postgres Copilot Executor & Unit Suites | `bun test libs/data/postgres/test/research-copilot-executor.test.ts libs/data/postgres/test/research-copilot-executor-edge.test.ts test/unit/` | `0` | **PASS** — `640` pass, `0` fail (`734,988` expects, `44` files) | -| Python SDK (`python/tests/`) | `python3 -m pytest` | N/A | **SKIPPED (env)** — `pytest` / `python/.venv` not installed in the sandbox | - -### 1.2 Studio Unsandboxed Runs & Remaining Host Verification - -| Verification | Scope / Command | Status | Notes | -| --- | --- | :---: | --- | -| **Studio Build `#1597`** | `bun run build` on review branch `feat/audit-m2-completion-status-m3` | **PASS** | Reported green by Studio on the review branch. | -| **Studio Test Run `#1598`** | `bun --env-file=/home/boki/.studio/test-env/stock-bot.env test && CARGO_BUILD_JOBS=2 cargo test --workspace --lib --offline` on review branch `feat/audit-m2-completion-status-m3` | **PASS** | Reported green by Studio on the review branch (covers Bun test suites including isolated `stock_bot_safety*` PostgreSQL tests, plus Rust workspace `--lib` tests). | -| **Full Host Check & `master` Provenance** | Record `master` SHA, inspect `studio/auto-*` branches, and run `CARGO_BUILD_JOBS=2 bun run check` (incl. `audit:secrets`, `test:tooling`, `test:integration`, `lint:check`) + `bun --env-file=/home/boki/.studio/test-env/stock-bot.env test test/postgres/` with retained logs | **PENDING** | Not covered by Studio runs `#1597`/`#1598`; must be executed on the host against the confirmed `master` revision before M2 closure (see `design/m2-gap-audit.md:118-122`). | - -**Research & Financial Invariants Verified Across Passing Suites** -- **Economic ownership & durable inputs:** Quant data curation owns immutable Zstd Parquet partitions (`bars_1d`, `adj_factors`, `events`, `shorts`, `fx_1d`, `fundamentals_pit`, `macro`) and QuestDB ILP v2 shards; PostgreSQL owns append-only `trial_ledger`, `findings`, and `provider_caveats` (`database/postgres/init/37-research-findings.sql:81-99`). -- **Holdout Vault fence:** `createQueryDataTool` (`libs/research/src/mcp/tools/query-data.ts`) and `openResearchCopilotStore` (`libs/data/duckdb/src/research-copilot-store.ts:40`) hardcode `vaultOperatorAuthorized: false`, reject `scope`/`vault_evaluation_only` keys, clamp bounds strictly below `vaultCutoffTs`, and drop post-cutoff rows (`libs/research/test/mcp-query-data.test.ts`). -- **PIT & synthetic split conservation:** Both Rust (`tools/curate-etl/src/fundamentals_tests.rs:104`) and real-DuckDB TypeScript (`libs/data/duckdb/test/duckdb-market-data-store.test.ts:251,601-626`) prove `known_at <= asOf` and Q1-after-Q2 restatement non-overwrite. **Synthetic** Rust fixtures (`tools/curate-etl/src/bars_1m_tests.rs:107,220` and `tools/curate-etl/src/run_curate_bars_1m_tests.rs:377-402`) prove `NEXM.V` (`1:20`) and `NVDA.US` (`10:1`) split arithmetic and ex-date boundary handling within `0.5%`, while observed-data comparison against retained raw `bars_1d` closes remains open (`run_curate_bars_1m_tests.rs:396-400`). -- **Database & execution safety:** Read-only MongoDB/Postgres adapters verified; zero paper/live execution write access in research/MCP surfaces. - ---- - -## 2. M2 Deliverables & Exit Criteria Matrix - -### 2.1 Deliverables (`design/MILESTONES.md` lines 87–98) - -| Area | Status | Landed in Checkout (Exact Evidence) | Concrete Gaps Remaining | -| --- | :---: | --- | --- | -| **M2.1** Research Copilot MCP & Notebook Snapshots | **PARTIAL** | All 6 tools wired in `createResearchCopilotMcpServer` (`libs/research/src/mcp/copilot-server.ts:13-20,48`); stdio host (`libs/research/src/mcp/host/stdio-host.ts`); Postgres adapters (`libs/research/src/mcp/adapters/postgres-copilot.ts`, `postgres-trial-ref.ts`, `library-cards.ts`, `exchange-calendars.ts`, `bar-session-dates.ts`); `openResearchCopilotExecutor` (`libs/data/postgres/src/research-copilot-executor.ts`); `openResearchCopilotStore` (`libs/data/duckdb/src/research-copilot-store.ts:33`); SQL schema (`database/postgres/init/37-research-findings.sql`); `exportNotebookSnapshot` (`libs/research/src/notebook-snapshot.ts:594`, `notebook-snapshot-node.ts:67`). | **(1)** `T-196` desktop entrypoint `scripts/research-copilot-mcp.ts` and `"mcp:research-copilot"` in `package.json` are missing; `apps/stock/web-api/src/` has no optional SSE wrapper. **(2)** `openResearchCopilotStore` (`libs/data/duckdb/src/research-copilot-store.ts:37`) opens daily DuckDB only instead of composing `createRoutedMarketDataStore` + `createQuestDbIntradayBarsReader` for `1m` queries. **(3)** `analyze_signal` (`libs/research/src/mcp/tools/analyze-signal.ts:121-123`) restricts `signal.source` to `'shorts' \| 'fundamentals'` (no `ceoPosts`, `macro`, or materialized `features`). **(4)** `exportNotebookSnapshot` has no CLI or MCP entrypoint and no end-to-end MCP study + `marimo check`-clean HTML + `file_finding` verification test. | -| **M2.2** PIT Fundamentals, `ceoPosts` & Lagged `teData` | **PARTIAL** | File-mode CLIs `curate-fundamentals`, `curate-posts`, and `curate-macro` wired in `tools/curate-etl/src/cli.rs:99-101,1295,1573,1684` and `main.rs:228,238,250`; Rust Q1-after-Q2 restatement test (`tools/curate-etl/src/fundamentals_tests.rs:104`); real-DuckDB TS `fundamentalsAsOf` implementation & restatement test (`libs/research/src/market-data-store-duckdb.ts:2287`, `libs/data/duckdb/test/duckdb-market-data-store.test.ts:251`). | **(1)** `EVENT_KIND_POST = "post"` (`tools/curate-etl/src/parquet_posts.rs:22`) mismatches `'ceo_post'` required by `libs/research/src/market-data-store-duckdb.ts:108`, `libs/research/src/event-panel.ts:63`, and `python/stockbot/data.py:21`, and `run_curate_posts` fails closed (`EventsDatasetExists`, `tools/curate-etl/src/run_curate_posts.rs:133,389`) if `/events` already exists from `curate-events`; both TS (`market-data-store-duckdb.ts:1448`) and Python (`python/stockbot/data.py:71`) only glob `events/year=*/part.parquet`. **(2)** `createDuckDbMarketDataStore().macroAsOf` (`libs/research/src/market-data-store-duckdb.ts:2294-2296`) throws `MarketDataStoreNotImplementedError`, blocking read-back of `macro/part.parquet` (note: per `design/DATA-CONTRACTS.md:26`, `teData` holds final-revised values only and must remain restricted to coarse lagged regime filters, not historical release signals without vintage data). **(3)** `SourceCollection` (`tools/curate-etl/src/mongo_stream.rs:53-62`) allowlists only the 8 M1 collections — no `--from-mongo` streaming for `qmFinancials`, `qmFinancials-old`, `ceoPosts`, or `teData`, and `curate-fundamentals` lacks `--qm-financials-old` merging. **(4)** Python `stockbot.data.MarketDataStore` (`python/stockbot/data.py`) lacks `fundamentals_as_of` and `macro_as_of`. | -| **M2.3** QuestDB `10.2.0` Intraday & `send-ilp` (`T-190`) | **PARTIAL** | `T-190` `send-ilp` CLI landed (`tools/curate-etl/src/cli.rs:102,2290`, `main.rs:260`, `ilp_send.rs`, `ilp_send_tests.rs` loopback `TcpListener` tests); `curate-bars-1m` and `curate-fx-1m` CLIs wired (`cli.rs:97-98`, `main.rs:208,218`); `M2_INTRADAY_SCHEMAS` (`libs/data/questdb/src/schema.ts:13-63`) with `PARTITION BY MONTH`, `WAL`, `SYMBOL CAPACITY 65536 NOCACHE`, `DEDUP UPSERT KEYS`; `docker-compose.quant.yml:35-39,52-53` (`nofile: 1048576`, `QDB_RAM_USAGE_LIMIT_BYTES=21474836480`); synthetic `NEXM.V` (`1:20`) and `NVDA.US` (`10:1`) split fixtures (`bars_1m_tests.rs:107,220`, `run_curate_bars_1m_tests.rs:377-402`). | **(1)** `run_curate_qm_bars_1m` (`tools/curate-etl/src/run_curate_qm_bars_1m.rs`, `T-185`) is not wired into `cli.rs`/`main.rs` (no `curate-qm-bars-1m` subcommand). **(2)** `MarketDataStore.fx({ timeframe: '1m' })` throws `MarketDataStoreNotImplementedError` in TS (`libs/research/src/market-data-store-duckdb.ts:1529-1530`, delegated unchanged by `createRoutedMarketDataStore` at `libs/research/src/market-data-store-routed.ts:184-186`) and `NotImplementedError` in Python (`python/stockbot/data.py:259`). **(3)** No `--from-mongo` streaming for `eodIntraday1M` (`3.40B` docs) or `qmIntraday` (`173.3M` docs). **(4)** Live `quant` preflight (`vm.max_map_count >= 1048576`, effective container `nofile = 1048576`, WAL DDL), binary-double (`0x10`) TCP ILP v2 acceptance (`tools/curate-etl/src/ilp_send.rs:15-21`), observed `NEXM.V`/`NVDA.US` comparison against retained raw `bars_1d`, and pinned PGWire 1-year `1m` read benchmark (`< 250 ms` warm / `< 1 s` cold) are all unverified. | -| **M2.4** Versioned Feature Library (`D04` / `D11`) | **PARTIAL** | TS `registerSignal`, `runFeatureBatch`, and Zstd Parquet writer landed (`libs/research/src/feature-library.ts`); built-in `RET_1D_V1` (`feature-library.ts:2166`). | **(1)** `createDuckDbMarketDataStore().crossSection` (`libs/research/src/market-data-store-duckdb.ts:2283-2285`) throws `MarketDataStoreNotImplementedError`, blocking read-back of materialized `features//v/` Parquet. **(2)** `FEATURE_INPUT_DATASETS` (`libs/research/src/feature-library.ts:61-68`) omits `'macro'` (coarse regime filters only per `DATA-CONTRACTS.md:26`) and `'corporate_actions'`, and registers only `'RET_1D_V1'`. **(3)** Python `stockbot` (`python/stockbot/__init__.py`, `data.py`, `signals.py`) lacks `cross_section` and `register_signal` (`D04`/`D11`). | - -### 2.2 Exit Criteria (`design/MILESTONES.md` lines 100–103) - -| Exit Criterion | Status | Evidence & Remaining Blocker | -| --- | :---: | --- | -| **EC-1:** Desktop Claude Code via MCP runs a fundamental + alt-data signal study and event study end-to-end, exports a `marimo check`-clean static HTML snapshot, and files a finding. | **OPEN** | All 6 MCP tools and `exportNotebookSnapshot` exist as libraries, but `scripts/research-copilot-mcp.ts` / `"mcp:research-copilot"` (`T-196`) is missing, `ceoPosts` cannot be read via `event_study` (`"post"` vs `"ceo_post"`), and no end-to-end MCP → HTML snapshot → `file_finding` verification exists. | -| **EC-2:** Restatement fixture test proves a restated Q1 (`known_at > Q2`) never overwrites Q2 in `fundamentalsAsOf`. | **SATISFIED (Offline Fixture)** | Proven in both Rust (`tools/curate-etl/src/fundamentals_tests.rs:104`) and real-DuckDB TypeScript (`libs/data/duckdb/test/duckdb-market-data-store.test.ts:251,601-626`), both passing in sandbox and Studio test run `#1598`. | -| **EC-3:** Split-boundary test on `NEXM.V` (`1:20`) and `NVDA.US` (`10:1`) confirms `bars_1m` session closes match raw `bars_1d` closes within `0.5%`, and 1y of `1m` bars loads in `< 250 ms` warm / `< 1 s` cold. | **OPEN (Synthetic Only)** | **Synthetic** Rust fixtures (`tools/curate-etl/src/bars_1m_tests.rs:107,220`, `run_curate_bars_1m_tests.rs:377-402`) pass for split arithmetic only and explicitly leave observed comparison against retained raw `bars_1d` open (`run_curate_bars_1m_tests.rs:396-400`). Still open on `quant`: (1) effective `vm.max_map_count >= 1048576` & container `nofile = 1048576` preflight before bulk load; (2) live QuestDB `10.2.0` binary-double (`0x10`) TCP ILP v2 acceptance; (3) observed `NEXM.V` + `NVDA.US` `bars_1m` vs. retained raw `bars_1d` close check (`<= 0.5%`); and (4) pinned 1-year single-listing PGWire benchmark (`QuestDBClient.query` → `createQuestDbIntradayBarsReader`) recording listing ID, date range, cache conditions, and expected vs. actual row counts against `< 250 ms` warm / `< 1 s` cold. | - ---- - -## 3. Candidate Causes: Why M2 Auto Mode May Have Parked 3 Consecutive Tasks - -No parked task receipts or Auto Mode run logs are available inside the sandbox, so **none of the four items below can be attributed to a specific parked task yet**. Separating what is directly observed in the checkout from what remains inferred pending host history/log inspection: - -1. **Missing `T-196` desktop MCP entrypoint *(observed in checkout; branch-reset cause inferred/unverified)*:** `scripts/research-copilot-mcp.ts` and `"mcp:research-copilot"` in `package.json` are absent from the checkout, whereas `T-190` (`send-ilp`) and `curate-macro` are present. Any Auto Mode task expecting a runnable desktop MCP entrypoint would hit an immediate blocker. Whether `T-196` was dropped during a `studio/auto-*` branch reset remains **unverified** until host-side branch history is inspected (`design/m2-gap-audit.md:119`). -2. **`docs/*` → `design/*` path drift *(observed in checkout; park attribution unverified)*:** `AGENTS.md` (L43–48), `CLAUDE.md` (L3, L7–11), `README.md` (L7, L9, L11–13, L142, L264, L435), `studio.config.json`, and older task prompts still point to `docs/*.md`, which can cause agents to fail path checks against the renamed `design/` directory. -3. **Sandbox boundary friction for `.git`, PostgreSQL, and `quant` *(observed environment constraint; park attribution unverified)*:** Running `bun run check`, `audit:secrets`, worktree-git tests (`scripts/test/`), `PIPELINE_TEST_DATABASE_URL` (`127.0.0.1:5432`) suites, or live `quant` QuestDB checks inside the agent sandbox fails by design; tasks without explicit host/sandbox separation can park on those expected errors. -4. **Unqueued Option B `--from-mongo` extension for M2 collections *(observed in checkout; park attribution unverified)*:** The `2026-11-30` addendum in `design/data-pipeline/rust-migration-evaluation.md` (lines 253–294) locked Option B (`tools/curate-etl --from-mongo`) for M1 and scoped M2's 6 collections (`qmFinancials`, `qmFinancials-old`, `ceoPosts`, `teData`, `eodIntraday1M`, `qmIntraday`) to M2, but `SourceCollection` (`tools/curate-etl/src/mongo_stream.rs:53-62`) still allowlists only the 8 M1 collections. - ---- - -## 4. Concrete Blockers Needing Director Decisions - -1. **Option B `--from-mongo` for M2 collections vs. `.bson` staging:** Should we extend `tools/curate-etl` `SourceCollection` with `--from-mongo` streaming for the 6 M2 collections (`qmFinancials`, `qmFinancials-old`, `ceoPosts`, `teData`, `eodIntraday1M`, `qmIntraday`), or close M2 in file-mode `.bson` staging? - - *Recommended:* Extend `--from-mongo` to the 6 M2 collections (reusing the M1 `ReadOnlyMongoClient` + `ChunkedMongoRawDocumentSource` pattern) so `3.40B` `eodIntraday1M` docs never require `~500–832 GiB` of intermediate `.bson` scratch files. -2. **Canonical `ceoPosts` event `kind` & `/events` co-publishing:** Should `tools/curate-etl/src/parquet_posts.rs` switch `EVENT_KIND_POST` from `"post"` to `"ceo_post"` and co-publish alongside `curate-events` under `/events/year=YYYY/` (either by writing `part-posts.parquet` **and updating both readers** — `libs/research/src/market-data-store-duckdb.ts:1448` and `python/stockbot/data.py:71` — from `events/year=*/part.parquet` to `events/year=*/*.parquet`, or by merging posts into yearly `part.parquet`), or keep posts in a separate curated root? - - *Recommended:* Change `EVENT_KIND_POST` to `"ceo_post"`, write `events/year=YYYY/part-posts.parquet`, **and update both TS (`market-data-store-duckdb.ts:1448`) and Python (`python/stockbot/data.py:71`) readers to glob `events/year=*/*.parquet`** (verified by a combined read-back fixture with filings, earnings, and an edited CEO post in the same curated root) so `curate-events` and `curate-posts` remain independently re-runnable without hiding posts from either reader. -3. **Live `quant` QuestDB `10.2.0` preflight, observed split check & latency gate for M2 closure:** Should M2 closure require an operator-run `quant` QuestDB `10.2.0` verification covering host/container limits (`vm.max_map_count`, `nofile`), binary-double (`0x10`) TCP ILP v2 acceptance, observed `NEXM.V` + `NVDA.US` `bars_1m` vs. retained raw `bars_1d` closes (`<= 0.5%`), and a pinned 1-year single-listing PGWire latency benchmark (`< 250 ms` warm / `< 1 s` cold), or accept synthetic-fixture closure and defer all live `quant` checks to an ops follow-up (matching the M1 `d52aa20` precedent)? - - *Recommended:* Require a small-slice (`NEXM.V` + `NVDA.US`, 1 year) operator verification on `quant` covering all four checks above before closing M2, while deferring full `3.40B`-row backfill to an ops runbook. - ---- - -## 5. M3 Readiness Mapping & Recommended Task Order - -**Verdict: Do not start M3 yet.** M2 must close first, and M3's core engine, screener, and validation deliverables are unstarted on this checkout. - -### 5.1 M3 Deliverables & Exit Criteria Readiness Map (`design/MILESTONES.md` lines 111–128) - -| M3 Item | Status | Target Files & Current Checkout Evidence | -| --- | :---: | --- | -| **Tier 1 Columnar Screener** (`MILESTONES.md:112-113`) | **NOT STARTED** | Append-only `trial_ledger` SQL exists (`database/postgres/init/36-trial-ledger.sql`), and `libs/calculations/src/index.ts` exports `deflatedSharpeRatio`, `effectiveIndependentTrials`, `analyzeSignalPanel`, `eventStudy`, `evaluateRecencyGate`. No Polars/DuckDB portfolio sweep, $M_{T \times N}$ writer, or CSCV `PBO` ($S = 16$) yet. | -| **Tier 2 Rust `financial/` Multi-Asset Upgrades** (`MILESTONES.md:114-119`) | **NOT STARTED** | `apps/stock/engine/Cargo.toml` has no `parquet`/`arrow-rs` crates yet; `apps/stock/orchestrator/src/backtest/{native-worker,candidate-sandbox}.ts` still use the single-series JSON/IPC path. Task 1 (retire `backtest_datasets` JSONB/IPC/N-API bar path), atomic timestamp-slice marks (`F06`), simultaneous `Target` sell-netting, feature side-channel, and `USD`/`CAD` Margin + corporate actions/delisting in `apps/stock/engine/src/financial/*` are all unstarted. | -| **Validation Suite & Engine Consolidation** (`MILESTONES.md:120-123`) | **PARTIAL (SQL only)** | `vault_evaluations` table with `<= 10/year` cap & append-only triggers exists (`database/postgres/init/36-trial-ledger.sql:44-138`), and `apps/stock/analytics` / `SimulationExecution` are already absent from the repo. Purged Walk-Forward/CPCV, stability surface, ADV capacity, US/CA factor exposure, human Vault Holdout Gate workflow, and retirement of legacy `f64` `BacktestEngine` (`apps/stock/engine/src/backtest/engine.rs:17`, `apps/stock/engine/src/api/backtest.rs:13`) remain **NOT STARTED**. | -| **M3 EC-1:** Rust unit + differential accounting fixtures (`MILESTONES.md:126`) | **OPEN** | Atomic hedged mark neutrality, 100%-invested `Sell A + Buy B` target rotation, split + dividend 8-decimal conservation, USD/CAD margin interest, TSX board-lot sizing, and `SIVB` delisting liquidation fixtures are not yet implemented. | -| **M3 EC-2:** 20y US+CA daily backtest (`~5,000+` listings) in `< 30 s` on `quant` (`MILESTONES.md:127`) | **OPEN** | Blocked on Tier 2 Parquet/Arrow-rs path + multi-asset engine upgrades. | -| **M3 EC-3:** Real M2 signal via `register_signal` end-to-end (`MILESTONES.md:128`) | **OPEN** | Blocked on M2 Python `register_signal` + `crossSection` read-back and M3 Tier 1/Tier 2/CPCV/Vault gate. | - -### 5.2 Ordered Task List to Finish M2 (8 Tasks) - -1. **Restore `T-196` desktop MCP entrypoint & wire routed intraday store:** Add `scripts/research-copilot-mcp.ts` + `"mcp:research-copilot"` in `package.json`, and update `openResearchCopilotStore` (`libs/data/duckdb/src/research-copilot-store.ts`) to compose `createRoutedMarketDataStore` + `createQuestDbIntradayBarsReader` when QuestDB config is present. -2. **Fix `ceoPosts` `kind = 'ceo_post'`, `/events` co-publishing & reader globs:** Change `EVENT_KIND_POST` in `tools/curate-etl/src/parquet_posts.rs` to `"ceo_post"`, co-publish `ceoPosts` under `/events/year=YYYY/` (either writing `part-posts.parquet` and updating both `libs/research/src/market-data-store-duckdb.ts:1448` and `python/stockbot/data.py:71` to glob `events/year=*/*.parquet`, or merging into yearly `part.parquet`), and add a combined read-back fixture containing filings, earnings, and an edited CEO post in the same curated root. -3. **Implement `MarketDataStore.macroAsOf`, `crossSection`, and `fx('1m')`:** Implement DuckDB read-back for `macro/part.parquet` (`macroAsOf`, enforcing/documenting the `design/DATA-CONTRACTS.md:26` coarse lagged regime-filter-only limit since `teData` lacks release vintages) and versioned `features//v/` (`crossSection`) in `libs/research/src/market-data-store-duckdb.ts`, and route `fx({ timeframe: '1m' })` to QuestDB `fx_1m` in `libs/research/src/market-data-store-routed.ts`. -4. **Wire `curate-qm-bars-1m` CLI & expand Feature Library inputs:** Expose `curate-qm-bars-1m` in `tools/curate-etl/src/{cli,main}.rs`, add `'macro'` (restricted to lagged regime filters per `DATA-CONTRACTS.md:26` until vintage data exists) and `'corporate_actions'` to `FEATURE_INPUT_DATASETS` in `libs/research/src/feature-library.ts`, and extend MCP `analyze_signal` to support materialized `features` (and `ceoPosts` / regime-only `macro` as needed). -5. **Add Python `stockbot` M2 parity & `register_signal` (`D04`/`D11`):** Expose `fundamentals_as_of`, `macro_as_of` (regime-only), `cross_section`, `fx(..., timeframe='1m')`, and `register_signal(...)` in `python/stockbot/` with offline `pytest` coverage. -6. **Extend `curate-etl --from-mongo` to the 6 M2 collections (subject to Director Decision 1):** Add `qmFinancials`, `qmFinancials-old` (with `--qm-financials-old` merge), `ceoPosts`, `teData`, `eodIntraday1M`, and `qmIntraday` to `SourceCollection` in `tools/curate-etl/src/mongo_stream.rs`. -7. **Add M2 Exit Criterion 1 end-to-end verification & doc path cleanup:** Add a CLI/MCP wrapper + end-to-end test covering MCP study → `marimo check`-clean HTML snapshot (`exportNotebookSnapshot`) → `file_finding`, and update stale `docs/` links in `AGENTS.md`, `CLAUDE.md`, `README.md`, and `studio.config.json` to `design/`. -8. **Operator `quant` QuestDB `10.2.0` preflight, observed split check & latency benchmark (Exit Criterion 3):** Before bulk load, verify on `quant` effective `vm.max_map_count >= 1048576`, container `ulimits.nofile = 1048576`, memory limits, and `getM2IntradayDDL()` WAL tables; run `send-ilp` on a small `NEXM.V` + `NVDA.US` 1-year slice to verify `0x10` binary-double acceptance and `wal_tables()` health via PGWire; compare observed `NEXM.V` (`1:20`) and `NVDA.US` (`10:1`) `bars_1m` session closes against retained raw `bars_1d` closes (`<= 0.5%`); and run a pinned 1-year single-listing `1m` benchmark through `QuestDBClient.query` → `createQuestDbIntradayBarsReader` (re-verifying via `createRoutedMarketDataStore` once wired) recording listing ID, date range, cache conditions, and expected vs. actual row counts against `< 250 ms` warm / `< 1 s` cold. - -### 5.3 Initial M3 Prerequisite Sequence (Once M2 Closes) - -1. **Retire JSON-over-Postgres/IPC/N-API bar path (M3 Task 1):** Add `parquet`/`arrow-rs` to `apps/stock/engine/Cargo.toml`, store `(hash, manifest, parquet_paths)` in `backtest_datasets`, and lift single-series TS gates in `native-worker.ts`. -2. **Tier 1 Columnar Screener & CSCV PBO (`S = 16`):** Implement CSCV `PBO` and Purged Walk-Forward/CPCV in `libs/calculations`, plus vectorized Polars/DuckDB portfolio sweeps logging $M_{T \times N}$ matrices to `trial_ledger`. -3. **Tier 2 Rust `financial/` multi-asset upgrades & legacy retirement:** Implement atomic timestamp-slice marks (`F06`), simultaneous `Target` sell-netting, feature side-channel, `USD`/`CAD` Margin + corporate-action/delisting accounting (with all 6 M3 EC-1 fixtures), human Vault Holdout Gate workflow, and retirement of legacy `f64` `BacktestEngine`. diff --git a/design/m2-gap-audit.md b/design/m2-gap-audit.md deleted file mode 100644 index 2f39185f..00000000 --- a/design/m2-gap-audit.md +++ /dev/null @@ -1,133 +0,0 @@ -# Milestone M2 Gap Audit Report (T-203) - -**Verdict:** **OPEN — M2 is not ready for closure.** Core M2 libraries (`curate-macro`, `send-ilp`, MCP server/adapters with Vault-fenced `query_data`, `fundamentalsAsOf`, QuestDB `10.2.0` primitives, and TS Feature Library) are present in the checked-out worktree and are programmer-reported green in the provisioned sandbox, but six concrete code/wiring gaps remain (including the missing desktop MCP entry point, unwired equity `1m` QuestDB consumer routing, and a `ceo_post` vs `post` event-kind mismatch). Traceable gate verification (with confirmed checkout SHA and retained logs) and all host-only `master` / `quant` / desktop closure gates remain **PENDING**. - -> **Scope & Provenance Notes:** -> - Milestone and contract documents live under `design/` (`design/MILESTONES.md`, `design/DATA-CONTRACTS.md`, `design/PLATFORM-PLAN.md`), not `docs/`. -> - **Revision status:** Worktree `.git` metadata lives outside the sandbox boundary, so the exact base `master` SHA and `studio/auto-*` branches could not be inspected inside the sandbox. All local checks below ran against the checked-out worktree on branch `feat/m2-gap-audit` (`/home/boki/.studio/worktrees/stock-bot/slot-1`); authoritative `master` verification remains **PENDING** until the host confirms the `master` SHA. -> - Per settled director decision, **T-127** (M1 equity eligibility / Vault file isolation) stays deferred in the backlog and does not block M2. -> - Project CI is off; no CI workflows were planned, added, or modified. - ---- - -## 1. Verification History & Worktree Gate Results - -### 1.1 Earlier Planning-Phase Setup Failures (Recorded in Approved Plan) - -During the initial read-only planning pass (unprovisioned environment before worktree dependencies and writable Cargo target were available), all four requested local gates and supplemental tests failed during setup: - -| Gate / Suite | Command | Exit Code | Planning-Phase Outcome | -| --- | --- | --- | --- | -| Typecheck | `bun run typecheck` | `2` | **FAIL** — `TS2688` missing `bun-types` | -| Contracts | `bun run test:contracts` | `2` | **FAIL** — `TS2688` missing `bun-types` | -| Lint | `bun run lint:check` | `127` | **FAIL** — `eslint: command not found` | -| Native Rust | `CARGO_BUILD_JOBS=2 bun run test:native` | `101` | **FAIL** — `Read-only file system (os error 30)` creating Cargo target path | -| Supplemental M2 `bun test` | copilot server, stdio, snapshot exporter, DuckDB store, ILP writer | `1` | **FAIL** — missing `zod` and `@stock-bot/logger` during import setup | - -### 1.2 Programmer-Reported Worktree Sandbox Runs (Verification Pending) - -Executed interactively in the provisioned worktree `/home/boki/.studio/worktrees/stock-bot/slot-1` (branch `feat/m2-gap-audit`, Linux sandbox, network disabled). - -- **Tested checkout revision:** **Unavailable in sandbox** (worktree `.git` metadata lives outside the sandbox boundary). -- **Retained command log / run reference:** **None** (ephemeral sandbox terminal output only). -- **Verification status:** **PENDING.** Because neither a confirmed checkout SHA nor retained command logs/run IDs are available for these four gates and supplemental suites, the rows below are **programmer-reported** only and do not constitute verified passes on `master` or the audited revision. - -| Gate / Suite | Command | Exit Code | Status (Programmer-Reported) | -| --- | --- | --- | --- | -| Typecheck | `bun run typecheck` | `0` | **PROGRAMMER-REPORTED (pending)** — 0 errors reported | -| Contracts | `bun run test:contracts` | `0` | **PROGRAMMER-REPORTED (pending)** — 0 errors reported | -| Lint | `bun run lint:check` | `0` | **PROGRAMMER-REPORTED (pending)** — 0 errors, 0 warnings reported | -| Native Rust | `CARGO_BUILD_JOBS=2 bun run test:native` | `0` | **PROGRAMMER-REPORTED (pending)** — `1,548` passed, `0` failed, `4` ignored across `57` suites | -| MCP `query_data` Vault Fence | `bun test libs/research/test/mcp-query-data.test.ts` | `0` | **PROGRAMMER-REPORTED (pending)** — `13` pass, `0` fail | -| Real-DuckDB M2 Fixtures | `bun test libs/data/duckdb/test/` | `0` | **PROGRAMMER-REPORTED (pending)** — `25` pass, `0` fail across `4` files; includes Exit 2 restatement fixture & `openResearchCopilotStore` | -| Research + QuestDB + Copilot Executor | `bun test libs/research/test/ libs/data/questdb/test/ libs/data/postgres/test/research-copilot-executor.test.ts libs/data/postgres/test/research-copilot-executor-edge.test.ts` | `0` | **PROGRAMMER-REPORTED (pending)** — `999` pass, `0` fail across `59` files | -| Exit 3 Split-Boundary Fixture | `CARGO_BUILD_JOBS=2 cargo test -p curate-etl --offline split_boundary_nvda_and_nexm_match_raw_bars_1d_closes` | `0` | **PROGRAMMER-REPORTED (pending)** — `1` passed, `0` failed | -| Utils | `bun run test:utils` | `0` | **PROGRAMMER-REPORTED (pending)** — `32` pass, `0` fail across `3` files | -| Calculations | `bun run test:calculations` | `0` | **PROGRAMMER-REPORTED (pending)** — `144` pass, `0` fail across `12` files | - -- **Prior Studio unsandboxed runs (review branch `feat/m2-gap-audit`):** Studio `build` (`#1589`, `#1591`) and `test` (`#1590`, `#1592`) passed on the review branch. These runs cover separate Studio `build` and `test` commands on the review branch—not the four individual requested gates (`typecheck`, `test:contracts`, `lint:check`, `test:native`)—and do not confirm the audited `master` revision. -- **Verification status:** **PENDING** host confirmation of the exact `master` SHA, retained logs for `CARGO_BUILD_JOBS=2 bun run check`, and the separate `test/postgres/` run (see Section 4.1). - ---- - -## 2. Verified on `master` *(Source Inspection; Traceable Runtime Verification & Host `master` SHA Pending)* - -- **PRESENT · MCP Copilot Libraries, Vault-Fenced `query_data` & Snapshot Exporter.** - - `libs/research/src/mcp/copilot-server.ts` exposes all six M2 tools (`search_symbols`, `query_data`, `analyze_signal`, `event_study`, `file_finding`, `read_knowledge`). - - `createQueryDataTool` (`libs/research/src/mcp/tools/query-data.ts`) enforces strict Vault fencing: its Zod schema omits `scope` and `vault_evaluation_only` (`.strict()` rejects them with zero store calls), calls `fenceVaultQueryBounds` before any `store.universe` or `store.bars` call (clamping `to`/`asOf` strictly below `vaultCutoffTs` and rejecting ranges starting at/after `vaultCutoffTs` with `VaultHoldoutFenceError`), always passes `scope: 'vault_fenced'`, and applies defense-in-depth row filtering dropping any row where `row.ts >= vaultCutoffTs || row.knownAt >= vaultCutoffTs` (lines 203–210). - - Boundary cases in `libs/research/test/mcp-query-data.test.ts` — rejecting `scope`/`vault_evaluation_only`/unknown keys (L303), rejecting ranges starting at/after `vaultCutoffTs` with `VaultHoldoutFenceError` (L342), clamping straddling `to`/`asOf` below cutoff (L359), dropping leaky post-cutoff `ts`/`knownAt` rows (L386), clamping universe date via `min(to, asOf)` (L508), and DuckDB microsecond-bound + `adj_factors` snapshot checks (L576) — are **programmer-reported passing** in the worktree (`13` pass, `0` fail; traceable verification & host `master` SHA pending). - - `libs/research/src/mcp/adapters/postgres-copilot.ts` (`createPostgresResearchCopilotServer`) wires the read-only Studio library reader, PostgreSQL findings/caveats, trial lookup, and exchange calendars. - - `openResearchCopilotStore` (`libs/data/duckdb/src/research-copilot-store.ts`, T-184) and `openResearchCopilotExecutor` (`libs/data/postgres/src/research-copilot-executor.ts`, T-189/T-200) are exported and programmer-reported passing in worktree unit tests (verification pending). - - `exportNotebookSnapshot` (`libs/research/src/notebook-snapshot.ts`) and its Node/Bun adapters (`libs/research/src/notebook-snapshot-node.ts`) implement the `marimo check` → static HTML export sequence. -- **PRESENT · `tools/curate-etl` CLI Subcommands.** - - `tools/curate-etl/src/cli.rs` and `tools/curate-etl/src/main.rs` wire `curate-bars-1d`, `curate-adj-factors`, `curate-corporate-actions`, `curate-fx-1d`, `curate-shorts`, `curate-events`, `curate-bars-1m`, `curate-fx-1m`, `curate-posts`, `curate-fundamentals`, `curate-macro`, and `send-ilp`. - - `curate-macro` (T-194/T-202) connects `run_curate_macro` to `curate_and_write_macro`; `send-ilp` (T-190) connects `run_send_ilp` to shard discovery and one TCP connection per shard. Both are programmer-reported passing in offline native tests in the worktree (verification pending). -- **PRESENT · Exit 2 (PIT Restatement) & Exit 3 (Split-Boundary) Fixtures.** - - `tools/curate-etl/src/fundamentals.rs` builds deduplicated 2D PIT snapshots and 4-quarter TTM with venue lag provenance. - - `libs/data/duckdb/test/duckdb-market-data-store.test.ts` contains the real-DuckDB `fundamentalsAsOf` restatement fixture proving a restated Q1 (`known_at > Q2`) never overwrites Q2 (programmer-reported passing in worktree; verification pending). - - `tools/curate-etl/src/run_curate_bars_1m_tests.rs` contains `split_boundary_nvda_and_nexm_match_raw_bars_1d_closes` with the `0.5%` threshold and negative controls (programmer-reported passing in worktree; verification pending). -- **PRESENT · QuestDB `10.2.0` Primitives & TS Feature Library.** - - `docker-compose.yml`, `docker-compose.dev.yml`, and `docker-compose.prod.yml` pin `questdb/questdb:10.2.0`. - - `libs/data/questdb/src/{schema,client,query-builder,ilp-v2-writer}.ts` provide monthly WAL DDL (`M2_INTRADAY_SCHEMAS`, `getM2IntradayDDL`), parameterized PGWire (`QuestDBClient.query`), `LATEST ON`, and the ILP v2 binary batch writer. - - `libs/research/src/feature-library.ts` implements `registerSignal`, `runFeatureBatch`, and Zstd Parquet writing for versioned DuckDB SQL features. - ---- - -## 3. Remaining M2 Code Gaps - -1. **FAIL · Desktop MCP Entry Point & Exit 1 Wiring** - - T-196 target `scripts/research-copilot-mcp.ts` and root `package.json` script `mcp:research-copilot` are absent. - - `runResearchCopilotStdioHost` (`libs/research/src/mcp/host/stdio-host.ts`) still requires caller-injected store/executor factories rather than a runnable default entrypoint. - - `apps/stock/web-api/src/` has no MCP/SSE route. - - Impact: Desktop Claude Code cannot yet launch the copilot end-to-end to satisfy M2 Exit Criterion 1. - -2. **FAIL · `ceoPosts` Event-Kind & Output-Root Interoperability** - - `tools/curate-etl/src/parquet_posts.rs` emits `EVENT_KIND_POST = "post"`, whereas `libs/research/src/market-data-store.ts` (`EventKind`), `libs/research/src/market-data-store-duckdb.ts` (`EVENT_KINDS`), `libs/research/src/mcp/tools/event-study.ts`, and `python/stockbot/data.py` (`EventKind`) all expect `"ceo_post"`. - - `tools/curate-etl/src/run_curate_posts.rs` writes `/events/year=YYYY/part.parquet` and fails closed (`RunCuratePostsError::EventsDatasetExists`) if `/events` already has `year=*` partitions from `curate-events`, while the copilot store takes a single curated root. - - Impact: Published `ceoPosts` cannot be queried alongside filings and earnings through the DuckDB store or MCP `event_study` as shipped. - -3. **PARTIAL · Fundamentals & Macro Contract Gaps** - - `build_fundamentals_rows` (`tools/curate-etl/src/fundamentals.rs`) links filings using listing/fiscal-class plus report-date or filing-window heuristics because sampled filings lack statement period, whereas `design/DATA-CONTRACTS.md` specifies a direct period-end join. - - `run_curate_fundamentals` (`tools/curate-etl/src/run_curate_fundamentals.rs`) takes one caller-prepared financials BSON dump and requires `listing_venues.tsv`, which `exportCurateInputs` (`apps/stock/data-pipeline/src/security-master/export-curate-inputs.ts`) does not emit. No physical `fundamentals_bitemporal` writer or `eodFinancialsOLD` backfill path exists. - - `createDuckDbMarketDataStore().macroAsOf` (`libs/research/src/market-data-store-duckdb.ts:2294`) still rejects with `MarketDataStoreNotImplementedError`, so curated `teData` Parquet (`macro/part.parquet`) has no DuckDB reader. - -4. **PARTIAL · Intraday Operating Path** - - `run_curate_qm_bars_1m` (`tools/curate-etl/src/run_curate_qm_bars_1m.rs`) is implemented as a library function but has no binary subcommand dispatch in `tools/curate-etl/src/{cli,main}.rs`. - - `curate-bars-1m` and `curate-fx-1m` operate in file-mode BSON only (no `--from-mongo` streaming). - - `tools/curate-etl/src/bars_1m.rs` applies fixed Eastern session tags (venue/date overrides exist in close validation, not curation), and loaders stamp caller-supplied `--known-at-micros` whose historical availability semantics must be defined before as-of studies. - -5. **FAIL / PARTIAL · QuestDB Startup Wiring & Intraday Read Path (Equity `1m` + FX `1m`)** - - **Unwired equity `1m` consumer path:** No application entry point constructs `createRoutedMarketDataStore` (`libs/research/src/market-data-store-routed.ts`) with `createQuestDbIntradayBarsReader` (`libs/research/src/market-data-store-questdb.ts`). The documented copilot factory `openResearchCopilotStore` (`libs/data/duckdb/src/research-copilot-store.ts`) opens DuckDB alone (`openDuckDbMarketDataStore`), which rejects `timeframe: '1m'` queries with `MarketDataStoreNotImplementedError` before reaching QuestDB. - - **Unwired FX `1m` route:** Even when `createRoutedMarketDataStore` is constructed, `fx()` delegates to the daily store rather than QuestDB `fx_1m`. - - **Startup DDL & legacy writer:** `getM2IntradayDDL` (`libs/data/questdb/src/schema.ts:139`) is opt-in with no checked-in startup caller applying it, and `QuestDBClient` (`libs/data/questdb/src/client.ts:232`) still instantiates legacy `QuestDBInfluxWriter` (`libs/data/questdb/src/influx-writer.ts`). - - **Schema wording drift:** `M2_INTRADAY_SCHEMAS.fx_1m` matches `design/DATA-CONTRACTS.md` (`DEDUP UPSERT KEYS(ts, pair)`), while `design/MILESTONES.md:96` wording can be read as `(ts, listing_id)` for both `bars_1m` and `fx_1m`. - -6. **PARTIAL · Feature Library & Documentation Drift** - - `python/stockbot/__init__.py` and `python/stockbot/signals.py` do not expose `register_signal(...)` (only TS `libs/research/src/feature-library.ts` has `registerSignal`). - - `createDuckDbMarketDataStore().crossSection` (`libs/research/src/market-data-store-duckdb.ts:2283`) still rejects with `MarketDataStoreNotImplementedError`. - - `tools/curate-etl/README.md` still describes landed `curate-fundamentals` and `curate-macro` CLI wiring as deferred/follow-up in older stage sections (e.g., lines 1697, 1744, 1752, 1836, 1859). - - `AGENTS.md` and `studio.config.json` still reference `docs/` paths instead of `design/`. - - `design/MILESTONES.md:97` labels the Feature Library `D04` reopened, whereas `design/PLATFORM-PLAN.md` assigns the `register_signal` promotion bridge to `D11`. - ---- - -## 4. Manual Host-Only Closure Gates - -These checks cannot run inside the sandbox and must be executed on the host / `quant` before closing M2: - -1. **Host Git Revision, Unmerged Branches, Full Check Gate & PostgreSQL Safety Suite** - - Record the exact audited `master` SHA and inspect `studio/auto-*` branches for any unmerged M2 commits (in particular T-196 desktop MCP wiring). - - Run `CARGO_BUILD_JOBS=2 bun run check` outside the sandbox on the confirmed `master` revision (covers `audit:secrets`, `build`, `typecheck`, `test:contracts`, `test:tooling`, `test:utils`, `test:calculations`, `test:integration`, `test:native`, and `lint:check`) and retain the command output/log alongside the `master` SHA. - - Because `scripts/check.ts` (`bun run check`) does **not** invoke `test:postgres` or discover `test/postgres/`, run the fixture-backed PostgreSQL safety suite separately using `bun --env-file=/home/boki/.studio/test-env/stock-bot.env test test/postgres/` (against isolated `stock_bot_safety*`) and record its result and log alongside `bun run check`. - - Never mutate QA MongoDB (`localhost:27017/stock`) or QA PostgreSQL (`localhost:5432/trading_bot`). - -2. **Desktop Claude Code End-to-End Verification (Exit 1)** - - After runnable MCP entry-point wiring lands, connect desktop Claude Code against the read-only Studio library (`~/repos/studio/catalog/quant/library/library.yml`) and isolated PostgreSQL. - - Exercise all six MCP tools: run a PIT fundamentals + alt-data signal study and an event study, verify actual `marimo check`-clean static HTML export, and retrieve the filed finding with its trial and artifact references. - -3. **Live `quant` QuestDB `10.2.0` Preflight, Load & Latency Verification (Exit 3)** - - **Host & schema precheck:** Verify on `quant`: QuestDB `10.2.0` image, `vm.max_map_count >= 1048576`, container `ulimits.nofile = 1048576`, memory limits, and pre-created `PARTITION BY MONTH` WAL tables with documented dedup keys (`(ts, listing_id)` for `bars_1m`, `(ts, pair)` for `fx_1m`). - - **Small live preflight per shard type (before bulk load):** Because `tools/curate-etl/src/cli.rs:175` documents that ILP v2 binary double encoding over TCP on QuestDB `10.2.0` is still unverified live, send one small sample shard for each shard type (`bars_1m`, `bars_1m_qm`, `fx_1m`) via `send-ilp` first. Confirm committed row counts, decoded OHLCV/FX numeric values and timestamps, and healthy WAL state (`wal_tables()`) through PGWire before starting the bulk load. - - **Full bulk load & reconciliation:** Run `send-ilp` for `bars_1m`, `bars_1m_qm`, and `fx_1m`; reconcile source counts vs. QuestDB PGWire row counts and WAL state (TCP `send-ilp` success confirms socket delivery only, not committed rows), and verify overlapping EOD/QM bar dedup and repeat-load idempotency. - - **Split-boundary verification:** Compare `NEXM.V` (`1:20`) and `NVDA.US` (`10:1`) split-boundary `bars_1m` session closes against independently sourced raw `bars_1d` closes (`<= 0.5%`). - - **Read latency benchmark & explicit scope:** Benchmark a pinned 1-year single-listing `1m` read (`adjustment: 'raw'`) at **`< 250 ms` warm / `< 1 s` cold** using the real PGWire-backed reader path: `QuestDBClient.query(sql, params)` (`libs/data/questdb/src/client.ts`) injected as `QuestDbQueryExecutor` into `createQuestDbIntradayBarsReader` (`libs/research/src/market-data-store-questdb.ts`), optionally composed via `createRoutedMarketDataStore({ daily, intraday })`. Record listing ID, date range, row count, elapsed times, and cache conditions. **Scope note:** Until equity `1m` routing is wired into `openResearchCopilotStore` and the desktop MCP entrypoint (Section 3, item 5), this benchmark measures the **standalone PGWire-backed reader path**, not a running copilot application; re-verify through the running application once consumer wiring lands. diff --git a/design/m2-master-audit.md b/design/m2-master-audit.md deleted file mode 100644 index 8ec2b0c4..00000000 --- a/design/m2-master-audit.md +++ /dev/null @@ -1,127 +0,0 @@ -# Milestone M2 Master Audit & Closure Plan (T-208) - -**Bottom Line:** **HOLD M2 CLOSURE / HOLD M3 — Core M2 infrastructure is ~80% landed on current `master` (including `T-190` `send-ilp`, `T-205` `mcp:research-copilot`, `T-206` `curate-qm-bars-1m`, and `T-207` `curate-macro`), with 6 concrete code/wiring gaps and 1 host/`quant` verification gate remaining before M2 can close.** - -All sandbox-runnable TypeScript, ESLint, contract, and Rust native gates passed on local fixtures (including loopback TCP, with zero external network or QA DB contact; `0` errors, `0` warnings; `1,563` Rust tests across `58` suites and `1,050` targeted M2 Bun tests across `65` files). Exit Criterion 2 (2D PIT Q1-after-Q2 restatement non-overwrite) is **Done** in both Rust and real-DuckDB TypeScript fixtures; Exit Criteria 1 and 3 remain **Partial** pending event-kind/glob alignment, `MarketDataStore` read-path completions (`macroAsOf`, `crossSection`, `fx('1m')`), Python `stockbot` M2 parity, `notebook:snapshot` CLI + E2E test, and operator-run host/`quant` QuestDB `10.2.0` verification. - -> **Scope, Provenance & Constraints** -> - **Read-only, docs-only audit:** Only `design/m2-master-audit.md` and `design/README.md` are modified. Zero production code, schema, test, build config, or CI changes (project CI is off; zero CI workflows proposed). -> - **Audited `master` baseline vs. review branch:** Audited against `master` and `dev` at verified commit `d45014a1f6dfc5ba5a73bcc0d6e57e486c2c7c52` (with accepted M1 `d52aa20bff3f5c259fb6e2bcfc2d3a78ad5224b1` confirmed as an ancestor). The review branch is `feat/m2-audit` (prior review HEAD `efd73bda3b9937274be6a47663ac20010922cfbd`, superseded by this revision). When checking the audited baseline outside the sandbox, run `git rev-parse master` — not `git rev-parse HEAD` (which returns the `feat/m2-audit` documentation commit). -> - **Supersedes prior T-203/T-204 snapshots:** Unlike `design/m2-completion-audit.md` (T-204), current `master` (`d45014a1`) now includes `T-190` (`send-ilp`), `T-205` (`scripts/research-copilot-mcp.ts` + `"mcp:research-copilot"`), `T-206` (`curate-qm-bars-1m` CLI), and `T-207` (`curate-macro` CLI). Every status below was re-verified from current source files and test runs. -> - **Documentation path drift:** Canonical specs reside under `design/*.md`, while `AGENTS.md` (lines 43–48), `CLAUDE.md` (lines 3, 7–11), `README.md` (lines 7, 9, 11–13, 142, 264, 435), and `studio.config.json` (lines 46–54) still reference `docs/*.md`. Cleanup is queued in `m2-ec1-snapshot-cli-and-doc-paths`. -> - **Strict database safety:** Zero connections to QA MongoDB (`27017/stock`) or QA PostgreSQL (`5432/trading_bot`). - ---- - -## 1. Baseline Verification: M1 (`d52aa20`), `T-127` & Option B Rust Architecture - -| Baseline Item | Verified State on `master` | Impact on M2 | -| --- | --- | --- | -| **Accepted M1 (`d52aa20bff3f5c259fb6e2bcfc2d3a78ad5224b1`)** | Landed and intact: security-master & research SQL schemas (`database/postgres/init/34-security-master.sql`, `35-security-master-exchange-seed.sql`, `36-trial-ledger.sql`, `37-research-findings.sql`), Rust Option B `--from-mongo` runners for all 6 M1 commands (`tools/curate-etl/src/run_mongo.rs:1-100`, `mongo_stream.rs`, `mongo_safety.rs`), and Python `stockbot` M1 SDK (`python/stockbot/{__init__,calculations,data,ledger,signals,vault}.py`). | Solid foundation; M2 builds directly on these schemas, adapters, and `ReadOnlyMongoClient`. | -| **`T-127` (Deferred M1 Equity Eligibility & Vault File Isolation)** | Explicitly accepted as deferred in backlog per settled director decision (`d52aa20`). | **Non-blocking for M2.** Does not block EC-1, EC-2, or EC-3. | -| **Settled Rust ETL / `data-pipeline` Decision (Option B)** | Confirmed in `design/data-pipeline/rust-migration-evaluation.md` (including `2026-11-30` Addendum §§A.1–A.4): keep `apps/stock/data-pipeline` in TypeScript (`42` files, `20,349` LOC) for security master Passes 1–6, TSV export, probes, and BullMQ/Hono; keep bulk curation in Rust `tools/curate-etl` (`mongodb = "=3.10.2"` sync `RawDocumentBuf` cursors). | M2's 6 collections (`qmFinancials`, `qmFinancials-old`, `ceoPosts`, `teData`, `eodIntraday1M`, `qmIntraday`) still lack `--from-mongo` wiring in `tools/curate-etl/src/mongo_stream.rs:53-62` (currently 8 M1 collections only). | -| **Post-T-204 Merges (`T-190`, `T-205`, `T-206`, `T-207`)** | All four verified landed: `T-190` `send-ilp` (`tools/curate-etl/src/{ilp_send,cli,main}.rs`), `T-205` desktop MCP stdio entrypoint (`scripts/research-copilot-mcp.ts`, `package.json:56`, `scripts/test/research-copilot-mcp.test.ts`), `T-206` `curate-qm-bars-1m` (`tools/curate-etl/src/{run_curate_qm_bars_1m,cli,main}.rs`), and `T-207` `curate-macro` (`tools/curate-etl/src/{run_curate_macro,cli,main}.rs`). | Removes the T-204 desktop-launch and `curate-qm-bars-1m` CLI blockers. | - ---- - -## 2. Verification Gate Evidence & Research Governance - -### 2.1 Sandbox Local Fixture Runs (Programmer-Reported on `feat/m2-audit`, Including Loopback TCP — Zero External Network or QA DB Contact) - -| Gate / Suite | Command | Exit | Observed Outcome & Counts | -| --- | --- | :---: | --- | -| **Typecheck** | `bun run typecheck` | `0` | **PASS** — `0` errors (`tsc --project tsconfig.check.json --noEmit`) | -| **Contracts** | `bun run test:contracts` | `0` | **PASS** — `0` errors (`tsc --project tsconfig.contracts.json --noEmit`) | -| **Lint** | `bun run lint:check` | `0` | **PASS** — `0` errors, `0` warnings (`--max-warnings 0`) | -| **Utils** | `bun run test:utils` | `0` | **PASS** — `32` pass, `0` fail (`59` expects, `3` files) | -| **Calculations** | `bun run test:calculations` | `0` | **PASS** — `144` pass, `0` fail (`76,602` expects, `12` files) | -| **Native Rust** | `CARGO_BUILD_JOBS=2 bun run test:native` | `0` | **PASS** — `1,563` passed, `0` failed, `4` ignored across `58` suites (`engine` `150` passed + `curate-etl` unit & integration suites using local fixtures, including loopback TCP in `tools/curate-etl/tests/cli.rs:1787` for `send-ilp`, plus binary tests in `curate_qm_bars_1m.rs` and `curate_macro.rs`, `fundamentals_tests.rs`, `parquet_fundamentals_tests.rs`, and `run_curate_bars_1m_tests.rs`) | -| **Targeted M2 Suites** | `bun test scripts/test/research-copilot-mcp.test.ts scripts/test/security.test.ts libs/research/test/ libs/data/duckdb/test/ libs/data/questdb/test/ libs/data/postgres/test/research-copilot-executor.test.ts libs/data/postgres/test/research-copilot-executor-edge.test.ts` | `0` | **PASS** — `1,050` pass, `0` fail (`80,699` expects, `65` files; includes `7/7` pass in `scripts/test/research-copilot-mcp.test.ts`, real-DuckDB `fundamentalsAsOf` restatement suite, and MCP Vault-fence suite) | -| **Python SDK** | `python3 -m pytest python/tests` | `1` | **SKIPPED (env)** — `/usr/bin/python3: No module named pytest` in sandbox | - -### 2.2 Audited Baseline, Studio Unsandboxed & Host-Only Verification Boundary - -| Verification Layer | Command / Scope | Status | Notes | -| --- | --- | :---: | --- | -| **Audited `master` Baseline Check** | `git rev-parse master` / `git rev-parse dev` | **Verified (`d45014a1`)** | Reviewer verified `master` and `dev` both at `d45014a1f6dfc5ba5a73bcc0d6e57e486c2c7c52` with accepted M1 (`d52aa20bff3f5c259fb6e2bcfc2d3a78ad5224b1`) as an ancestor; `feat/m2-audit` review HEAD is tracked separately. | -| **Studio Unsandboxed Runner (Audit Revision)** | `bun run build` and `bun --env-file=/home/boki/.studio/test-env/stock-bot.env test && CARGO_BUILD_JOBS=2 cargo test --workspace --lib --offline` | **Authoritative post-handoff** | Prior revision passed Studio build `#1621` and test run `#1622`; Studio re-runs authoritatively on this revision covering workspace build, `audit:secrets`, worktree-git tooling tests (`scripts/test/`), integration tests, and isolated `stock_bot_safety*` PostgreSQL suites unreachable inside the sandbox. | -| **Future Host M2 Closure Revision** | `git rev-parse master` (at M2 closure), `CARGO_BUILD_JOBS=2 bun run check`, `bun --env-file=/home/boki/.studio/test-env/stock-bot.env test test/postgres/` | **PENDING (host closure)** | Future closure commit after M2 code tasks merge; required with retained logs in `design/m2-close-evidence.md` before M2 closure. | -| **`quant` (`10.0.0.51`) & Workstation Live Gates** | Read-only QA Mongo M2 field-shape probe, Quant Research-approved `curate-macro` `--series-map`, QuestDB `10.2.0` preflight (`vm.max_map_count`, `nofile`), bulk 3-feed intraday load + read-back reconciliation (`eodIntraday1M`, `qmIntraday`, `CAD.FOREX`), `0x10` TCP ILP v2 commit, observed `NEXM.V`/`NVDA.US` split check, 1y `1m` PGWire latency, and desktop Claude Code + real `marimo` EC-1 receipt | **PENDING (host/`quant`)** | Tracked in `m2-host-quant-verification-and-closure` (with director replan flag in §4–§5). | - -### 2.3 Research Governance & Replay / Financial Invariants Verified - -- **Economic owner & durable inputs:** Quant data curation owns immutable Zstd Parquet partitions (`bars_1d`, `adj_factors`, `corporate_actions`, `events`, `shorts`, `fx_1d`, `fundamentals_pit`, `macro`, `features//v`) and published QuestDB ILP v2 shard files; Quant Research owns the `curate-macro` `--series-map` series and lag-class selections (the approved TSV and its identifier must be retained with macro curation evidence); PostgreSQL owns append-only `trial_ledger`, `vault_evaluations`, `findings`, and `provider_caveats` (`database/postgres/init/36-trial-ledger.sql`, `37-research-findings.sql`, protected by `reject_research_evidence_mutation()`). -- **Holdout Vault & `known_at` boundaries:** Verified by `libs/research/test/mcp-query-data.test.ts` (rejects `scope`/`vault_evaluation_only`, clamps bounds strictly `< vaultCutoffTs`, drops leaky post-cutoff rows) and `openResearchCopilotStore` (`libs/data/duckdb/src/research-copilot-store.ts:40`, hardcoding `vaultOperatorAuthorized: false`). **Open FX `1m` availability gap:** `tools/curate-etl/src/run_curate_fx_1m.rs:24-26` preserves bar-start `ts` and `libs/data/questdb/src/schema.ts:33-47` defines `fx_1m` without `known_at`, so filtering on `ts` alone can leak an unclosed bar's close across a cutoff (director confirmation required in §4). -- **Baselines & single-source metrics:** `@stock-bot/calculations` (`144/144` tests passing) remains the sole authority for Sharpe/Sortino/IC/Newey-West/DSR/event-study/recency math; `RET_1D_V1` in `libs/research/src/feature-library.ts:29` documents its zero-return comparison baseline and zero-cost assumption. -- **2D PIT restatement & synthetic split-boundary conservation:** - - Q1 restated after Q2 never overwrites Q2 and updates TTM: verified in Rust (`tools/curate-etl/src/fundamentals_tests.rs:104` `restatement_of_q1_after_q2_updates_q1_and_ttm_without_overwriting_q2`, `parquet_fundamentals_tests.rs:1107` `restatement_of_q1_after_q2_preserves_q2_on_disk_and_updates_ttm`) and real-DuckDB TypeScript (`libs/data/duckdb/test/duckdb-market-data-store.test.ts:251`). - - `NVDA.US` (`10:1`) and `NEXM.V` (`1:20`) split-unadjustment conservation within `0.5%`: verified on **synthetic** fixtures (`tools/curate-etl/src/run_curate_bars_1m_tests.rs:402` `split_boundary_nvda_and_nexm_match_raw_bars_1d_closes`); observed comparison against retained raw `bars_1d` closes remains open on `quant`. -- **Database safety & execution boundary:** Read-only MongoDB/PostgreSQL guards (`assertEnvironmentSafety()`, `MongoDBClient` `mongoReadOnly: true`, Rust `mongo_safety.rs` + sealed `ReadOnlyMongoClient`) remain intact. **Paper and live execution write access is strictly absent from all M2 MCP/research surfaces and remains out of scope until M5.** - ---- - -## 3. Milestone M2 Deliverables & Exit Criteria Matrix - -### 3.1 Deliverables (`design/MILESTONES.md` lines 87–98) - -| Deliverable | Status | Landed on `master` (Exact Paths, Symbols & Tests) | Missing / Remaining Gaps | -| --- | :---: | --- | --- | -| **M2.1** MCP Server & Notebook Snapshots | **Partial** | - **T-205 landed:** Runnable stdio entrypoint `runResearchCopilotMcp` in `scripts/research-copilot-mcp.ts:77`, `"mcp:research-copilot"` in `package.json:56`, `7/7` tests in `scripts/test/research-copilot-mcp.test.ts`.
- All 6 MCP tools (`search_symbols`, `query_data`, `analyze_signal`, `event_study`, `file_finding`, `read_knowledge`) in `libs/research/src/mcp/tools/` + `createResearchCopilotMcpServer` (`libs/research/src/mcp/copilot-server.ts`) + `parseResearchCopilotHostConfig` / `runResearchCopilotStdioHost` (`libs/research/src/mcp/host/stdio-host.ts`).
- Real Postgres executor (`openResearchCopilotExecutor` in `libs/data/postgres/src/research-copilot-executor.ts`) + real DuckDB store (`openResearchCopilotStore` in `libs/data/duckdb/src/research-copilot-store.ts:33`) + read-only `library.yml` card reader (`libs/research/src/mcp/adapters/library-cards.ts`) + `database/postgres/init/37-research-findings.sql`.
- `exportNotebookSnapshot` & Node subprocess adapter (`libs/research/src/notebook-snapshot.ts`, `libs/research/src/notebook-snapshot-node.ts:67`, `libs/research/test/notebook-snapshot*.test.ts`). | 1. `openResearchCopilotStore` (`libs/data/duckdb/src/research-copilot-store.ts:37`) and `stdio-host.ts:49-79` open DuckDB-only; optional `RESEARCH_MCP_QUESTDB_*` config + `createRoutedMarketDataStore` composition is missing.
2. `analyze_signal` (`libs/research/src/mcp/tools/analyze-signal.ts:121-123`) supports only `source: 'shorts' \| 'fundamentals'` (no `source: 'feature'` for versioned Feature Library signals).
3. No runnable `scripts/export-notebook-snapshot.ts` / `"notebook:snapshot"` CLI wrapping `@stock-bot/research/notebook-snapshot-node`.
4. No automated E2E stdio test covering `search_symbols` → `query_data` → `analyze_signal` → `event_study` (with `ceo_post`) → `exportNotebookSnapshot` → `file_finding` → `read_knowledge`.
5. No `apps/stock/web-api` SSE wrapper (recommended deferred to M4; see §4). | -| **M2.2** PIT Fundamentals, `ceoPosts` & Lagged `teData` | **Partial** | - File-mode Rust CLIs wired in `tools/curate-etl/src/cli.rs` & `main.rs`: `curate-fundamentals` (`cli.rs:102,1636`, `run_curate_fundamentals.rs`), `curate-posts` (`cli.rs:101,1317`, `run_curate_posts.rs`), and **T-207** `curate-macro` (`cli.rs:103,1689`, `run_curate_macro.rs`; binary tests in `tools/curate-etl/tests/curate_macro.rs:178` `cli_publishes_runner_equivalent_macro_parquet_with_pit_lag_and_no_forecast_leakage`, `:471` `cli_publishes_runner_equivalent_macro_parquet_and_excludes_forecast_sentinel`, `:709` `cli_rerun_on_same_inputs_is_byte_deterministic`).
- Real-DuckDB `fundamentalsAsOf` (`libs/research/src/market-data-store-duckdb.ts:2287`, `libs/data/duckdb/test/duckdb-market-data-store.test.ts:251`).
- 2D PIT restatement tests (`fundamentals_tests.rs:104`, `parquet_fundamentals_tests.rs:1107`). | 1. **`ceoPosts` event-kind & partition mismatch:** `EVENT_KIND_POST = "post"` (`tools/curate-etl/src/parquet_posts.rs:22`) mismatches `'ceo_post'` expected by `market-data-store-duckdb.ts` and `python/stockbot/data.py:21`; `run_curate_posts.rs:133` fails with `EventsDatasetExists` when `/events` exists from `curate-events`; both `market-data-store-duckdb.ts:1448` and `python/stockbot/data.py:71` glob only `events/year=*/part.parquet` instead of `events/year=*/*.parquet`.
2. `MarketDataStore.macroAsOf` throws `MarketDataStoreNotImplementedError` (`libs/research/src/market-data-store-duckdb.ts:2294-2296`).
3. `CurateFundamentalsArgs` (`tools/curate-etl/src/run_curate_fundamentals.rs:113-118`) accepts only a single `--qm-financials` path (no `--qm-financials-old` merge or `--curate-inputs` resolution).
4. `export-curate-inputs.ts:20-24` does not emit `listing_venues.tsv` (`us_tsx` / `tsxv_cse`).
5. `SourceCollection` (`mongo_stream.rs:53-62`), `RAW_BSON_EXPORT_COLLECTIONS` (`export-raw-bson.ts:11-20`), and `FIELD_SHAPE_PROBE_COLLECTIONS` (`source-field-shapes.ts:8-17`) allowlist only the 8 M1 collections (missing `qmFinancials`, `qmFinancials-old`, `ceoPosts`, `teData`).
6. `python/stockbot/data.py` lacks `fundamentals_as_of` and `macro_as_of`. | -| **M2.3** QuestDB `10.2.0` Intraday & `send-ilp` | **Partial** | - **T-190 landed:** `send-ilp` multi-socket TCP sender (`tools/curate-etl/src/ilp_send.rs`, `cli.rs:104,2461`, `main.rs:22`, `ilp_send_tests.rs`; binary tests in `tools/curate-etl/tests/cli.rs:1747` `send_ilp_cli_help_missing_flag_success_and_partial_error_routing`, `:1877` `send_ilp_cli_shard_gap_exits_without_partial_report_or_connect_and_bad_prefix_prints_usage`, `:1939` `send_ilp_cli_ignores_questdb_env_vars_and_requires_explicit_addr`).
- **T-206 landed:** `curate-qm-bars-1m` CLI (`tools/curate-etl/src/run_curate_qm_bars_1m.rs`, `cli.rs:99,2277`, `main.rs:39`; binary tests in `tools/curate-etl/tests/curate_qm_bars_1m.rs:336` `curate_qm_bars_1m_binary_matches_direct_runner_bytes_report_and_invariants`, `:527` `curate_qm_bars_1m_binary_refuses_overwrite_and_coexists_with_eod_bars_1m_shards`, `:622` `curate_qm_bars_1m_binary_applies_date_effective_mapping_and_reports_dropped_unmapped`) alongside `curate-bars-1m` (`cli.rs:98,2110`) and `curate-fx-1m` (`cli.rs:100,2381`).
- QuestDB `10.2.0` query layer, ILP v2 writer, and opt-in `M2_INTRADAY_SCHEMAS` / `getM2IntradayDDL()` (`libs/data/questdb/src/schema.ts:13-63,139`, `libs/data/questdb/test/`).
- Vault-fenced QuestDB `bars('1m')` reader (`libs/research/src/market-data-store-questdb.ts`) + `createRoutedMarketDataStore` (`libs/research/src/market-data-store-routed.ts`).
- `docker-compose.quant.yml:30-45` (`nofile: 1048576`, `QDB_RAM_USAGE_LIMIT_BYTES=21474836480`, `mem_limit: 28g`). | 1. `fx({ timeframe: '1m' })` throws `MarketDataStoreNotImplementedError` in TS (`libs/research/src/market-data-store-duckdb.ts:1529-1534`, delegated unchanged by `market-data-store-routed.ts:184-186`) and `NotImplementedError` in Python (`python/stockbot/data.py:258-259`); `market-data-store-questdb.ts` reads `bars_1m` only (no `fx_1m` reader). Moreover, `run_curate_fx_1m.rs:24-26` preserves bar-start `ts` and `fx_1m` (`schema.ts:33-47`) has no `known_at` column, so Vault fencing for both FX adapters requires a confirmed bar-close availability rule (see §4).
2. `getM2IntradayDDL()` (`libs/data/questdb/src/schema.ts:139`) is pure/opt-in with no runnable initializer script/helper wired to apply it.
3. No `--from-mongo` streaming in `mongo_stream.rs` / `run_mongo.rs` (and no allowlist entries in `export-raw-bson.ts` / `source-field-shapes.ts`) for `eodIntraday1M` (`3.40B`) or `qmIntraday` (`173.3M`).
4. Live `quant` preflight (`vm.max_map_count`, `nofile`), `0x10` binary-double TCP ILP acceptance (`ilp_send.rs:15-21`), bulk load & PGWire read-back reconciliation of all three approved feeds (`eodIntraday1M` US 2003–2025, `qmIntraday` CA/US 2024–2025, `CAD.FOREX` `1m` ~5.2M bars, including EOD/QM `(ts, listing_id)` overlap reconciliation), observed `NEXM.V`/`NVDA.US` split check, and 1y `1m` PGWire latency benchmark are unverified. | -| **M2.4** Versioned Feature Library (`D04` / `D11`) | **Partial** | - Declarative DuckDB SQL feature definitions, immutable `registerSignal`, Vault-fenced yearly Zstd Parquet `runFeatureBatch`, and built-in `RET_1D_V1` in `libs/research/src/feature-library.ts` (`libs/research/test/feature-library.test.ts`). | 1. `MarketDataStore.crossSection` throws `MarketDataStoreNotImplementedError` (`libs/research/src/market-data-store-duckdb.ts:2283-2285`), blocking read-back of `features//v/year=*/part.parquet`.
2. `FEATURE_INPUT_DATASETS` (`libs/research/src/feature-library.ts:61-68`) omits `'macro'` and `'corporate_actions'`.
3. Python `stockbot` (`python/stockbot/{__init__,data,signals}.py`) lacks `register_signal(...)`, batch feature materialization, and `cross_section(...)`. | - -### 3.2 Exit Criteria (`design/MILESTONES.md` lines 100–103) - -| Exit Criterion | Status | Verified Evidence & Remaining Work | -| --- | :---: | --- | -| **EC-1:** Desktop Claude Code via MCP executes a fundamental + alt-data signal study and event study end-to-end, exports a `marimo check`-clean static HTML snapshot, and files a finding. | **Partial** | **Landed:** `scripts/research-copilot-mcp.ts` (`mcp:research-copilot`) + all 6 MCP tools + `exportNotebookSnapshot`.
**Missing:** `ceo_post` event compatibility (`m2-ceo-posts-events-compat`), `notebook:snapshot` CLI + automated E2E stdio test (`m2-ec1-snapshot-cli-and-doc-paths`), and desktop Claude Code + real `marimo` session receipt (`m2-host-quant-verification-and-closure`). | -| **EC-2:** Restatement fixture test proves a restated Q1 (`known_at > Q2`) never overwrites Q2 in `fundamentalsAsOf`. | **Done (Offline Rust + Real-DuckDB)** | Proven offline in `tools/curate-etl/src/fundamentals_tests.rs:104`, `tools/curate-etl/src/parquet_fundamentals_tests.rs:1107`, and real-DuckDB `libs/data/duckdb/test/duckdb-market-data-store.test.ts:251`. Python `fundamentals_as_of` parity is tracked in `m2-python-sdk-m2-parity`. | -| **EC-3:** Split-boundary test on `NEXM.V` (`1:20`) and `NVDA.US` (`10:1`) confirms `bars_1m` session closes match raw `bars_1d` closes within `0.5%`, and 1y of `1m` bars for one listing loads in `< 250 ms` warm / `< 1 s` cold. | **Partial (Synthetic Done; Live `quant` Missing)** | **Done (synthetic):** `tools/curate-etl/src/run_curate_bars_1m_tests.rs:402` (`split_boundary_nvda_and_nexm_match_raw_bars_1d_closes`).
**Missing (live `quant`):** Host/container `vm.max_map_count`/`nofile` preflight, `getM2IntradayDDL()` execution, QuestDB `10.2.0` `0x10` TCP ILP v2 commit check, bulk 3-feed load & PGWire read-back reconciliation (`eodIntraday1M`, `qmIntraday`, `CAD.FOREX` + EOD/QM `(ts, listing_id)` overlap rule), observed `NEXM.V` + `NVDA.US` `bars_1m` vs. retained raw `bars_1d` close check (`<= 0.5%`), and pinned 1-year single-listing PGWire latency benchmark (`< 250 ms` warm / `< 1 s` cold). | - ---- - -## 4. Concrete Blockers, Director Trade-Offs & Backlog Replan Flags - -Confirm these seven items (4 design trade-offs + 3 operational/environment prerequisites) and the **three backlog replan adjustments** below before coding/closing M2: - -### 4.1 Design Trade-Offs Requiring Director Confirmation - -1. **Option B `--from-mongo` for the 6 M2 collections vs. `.bson` staging:** Extend `tools/curate-etl` `SourceCollection` + `run_mongo.rs` with direct read-only MongoDB streaming for `qmFinancials`, `qmFinancials-old`, `ceoPosts`, `teData`, `eodIntraday1M`, and `qmIntraday`, or stay on `.bson` staging files for M2? - - *Recommended:* Extend Option B `--from-mongo` to all 6 M2 collections (`m2-curate-etl-mongo-and-financials-old`) so `3.40B` `eodIntraday1M` rows never require `~500–832 GiB` of NVMe scratch space, while keeping file mode for offline tests. -2. **MCP stdio-only for M2 vs. `web-api` SSE wrapper:** Close M2 with the landed desktop stdio server (`bun run mcp:research-copilot`), or also add an HTTP/SSE wrapper inside `apps/stock/web-api` now? - - *Recommended:* Keep M2 stdio-only for desktop Claude Code (EC-1) and defer the network-isolated HTTP/SSE MCP endpoint to M4 containerized campaigns. -3. **`fundamentals_pit`-only vs. physical `fundamentals_bitemporal/part.parquet`:** Keep `curate-fundamentals` writing pre-resolved 2D PIT snapshots (`fundamentals_pit/year=YYYY/part.parquet`), or also materialize a separate raw `fundamentals_bitemporal/part.parquet` table in M2? - - *Recommended:* Keep `fundamentals_pit`-only for M2 (`DATA-CONTRACTS.md` §3A and EC-2 both target `fundamentalsAsOf` over `fundamentals_pit`), and materialize `fundamentals_bitemporal` only if a downstream M3/M4 use case requires unflattened multi-period history. -4. **`fx_1m` bar-close availability & Vault fencing rule *(Unresolved — blocks both TS & Python FX adapters)*:** `tools/curate-etl/src/run_curate_fx_1m.rs:24-26` preserves EODHD bar-start `ts` and `libs/data/questdb/src/schema.ts:33-47` defines `fx_1m` without a `known_at` column. Filtering on `ts` alone can return a bar whose start is before `vaultCutoffTs` (or `asOf`) while its close is at or after the cutoff, leaking an unobservable FX close. - - *Recommended:* Enforce bar-close availability in both TypeScript (`m2-store-macro-cross-section-fx1m`) and Python (`m2-python-sdk-m2-parity`) FX adapters (`bar_close = ts + 60s` strictly `< vaultCutoffTs` and `<= asOf`), backed by a boundary fixture proving a bar spanning or ending at `vaultCutoffTs` is excluded — keeping the `fx_1m` schema unchanged. (Alternative: add a `known_at` `TIMESTAMP` column to `fx_1m` DDL + ILP writer set to `ts + 60s`.) - -### 4.2 Operational & Environment Prerequisites - -5. **Live read-only QA MongoDB M2 field-shape probe & `curate-macro` `--series-map` ownership:** Run `probe-source-field-shapes.ts` read-only (`studio_stock_bot_read@stock`) once `m2-data-pipeline-m2-inputs-and-probes` allowlists the 6 M2 collections, to confirm live `ceoPosts` numeric timestamp unit (`Seconds` vs `Millis`), `qmFinancials`/`qmFinancials-old` metric paths, and `teData` labels before production curation. **Quant Research** owns the `teData` series selection and lag-class choices in the caller-supplied `--series-map` TSV; retain the approved mapping TSV and its version/hash identifier alongside the macro curation evidence in `design/m2-close-evidence.md`. -6. **`quant` (`10.0.0.51`) QuestDB `10.2.0` operator access:** Required for sysctl (`vm.max_map_count >= 1048576`) & container `nofile = 1048576` preflight, applying `getM2IntradayDDL()`, verifying `0x10` binary-double TCP ILP v2 commits via PGWire `wal_tables()`, loading and reconciling all three approved intraday feeds (`eodIntraday1M`, `qmIntraday`, `CAD.FOREX`), running the observed `NEXM.V`/`NVDA.US` split check, and timing the 1-year `1m` PGWire latency gate. -7. **Workstation `marimo` + desktop Claude Code setup:** Required on the operator workstation with `bun run mcp:research-copilot`, Studio `library.yml`, real `marimo`, and isolated PostgreSQL to record the EC-1 sign-off receipt. - -### 4.3 Substantive Backlog Replan Flags for Director (Before Merging Follow-Ups) - -The approved 7-key implementation backlog has three gaps discovered during audit review that should be replanned within the existing keys before scheduling: - -- **`m2-store-macro-cross-section-fx1m` & `m2-python-sdk-m2-parity` (FX `1m` availability boundary):** Add the confirmed `fx_1m` bar-close availability rule (item 4 above) and a boundary fixture in both TS and Python tests verifying bar-close observability and Vault exclusion for a minute bar spanning or ending at `vaultCutoffTs`. -- **`m2-ec1-snapshot-cli-and-doc-paths` (missing prerequisite):** Add `m2-ceo-posts-events-compat` to `dependsOn` (currently only `m2-store-macro-cross-section-fx1m`). Without it, the EC-1 integration task can start before `curate-posts` emits `'ceo_post'` and co-publishes alongside `curate-events`; require the E2E stdio test to consume co-published `curate-events` + `curate-posts` fixture output so `event_study` proves it reaches the curated CEO post. -- **`m2-host-quant-verification-and-closure` (bulk 3-feed intraday coverage & reconciliation):** Add acceptance requiring retained bulk load and PGWire read-back evidence in QuestDB for all three approved feeds from `design/MILESTONES.md:96` — `eodIntraday1M` (US equity 2003–2025), `qmIntraday` (CA/US equity 2024–2025), and `CAD.FOREX` `1m` (~5.2M bars) — recording source/date coverage, row counts, skipped/dropped counts, and the explicit reconciliation/precedence rule where EOD and QM share a `(ts, listing_id)` dedup key in `bars_1m`. - ---- - -## 5. Ordered M2 Closure Backlog (7 Tasks) - -Aligned 1-to-1 with the approved implementation backlog keys (with the three director replan flags marked inline): - -| Order | Key | Task | Depends On | Primary Acceptance | -| :---: | --- | --- | --- | --- | -| **1** | `m2-ceo-posts-events-compat` | **M2.2u** — Fix `ceoPosts` event kind (`'ceo_post'`) and co-publish under `/events` | *(none)* | `EVENT_KIND_POST = "ceo_post"`; non-clobbering `events/year=YYYY/part-posts.parquet`; TS (`market-data-store-duckdb.ts`) & Python (`data.py`) glob `events/year=*/*.parquet` verified in real-DuckDB combined filing/earnings/`ceo_post` test. | -| **2** | `m2-store-macro-cross-section-fx1m` | **M2.3s** — Implement `MarketDataStore.macroAsOf`, `crossSection`, QuestDB `fx('1m')`, and copilot `1m` routing | *(none)* | Vault-fenced DuckDB `macroAsOf` & `crossSection` tests; QuestDB `fx_1m` reader + `createRoutedMarketDataStore` `fx('1m')` routing + `getM2IntradayDDL()` initializer; optional `RESEARCH_MCP_QUESTDB_*` in `stdio-host.ts`/`openResearchCopilotStore`; `analyze_signal` `source: 'feature'` + `FEATURE_INPUT_DATASETS` (`'macro'`, `'corporate_actions'`). **[Director replan §4.3: confirm `fx_1m` bar-close availability rule + add cutoff-spanning/ending boundary fixture.]** | -| **3** | `m2-data-pipeline-m2-inputs-and-probes` | **M2.2v** — Export `listing_venues.tsv` and extend field-shape probe & BSON fixture exporter for M2 collections | *(none)* | Atomic `listing_venues.tsv` (`us_tsx` / `tsxv_cse`) in `export-curate-inputs.ts`; all 14 M1+M2 collections allowlisted in `source-field-shapes.ts` & `export-raw-bson.ts` with `mongoReadOnly: true`. | -| **4** | `m2-curate-etl-mongo-and-financials-old` | **M2.3t** — Add `--qm-financials-old` merge and Option B `--from-mongo` streaming for M2 collections in `curate-etl` | `m2-ceo-posts-events-compat`, `m2-data-pipeline-m2-inputs-and-probes` | `curate-fundamentals` `--qm-financials-old` + `--curate-inputs`; sealed read-only `--from-mongo` streaming for all 6 M2 collections with byte-identical offline parity tests and zero new crates. | -| **5** | `m2-python-sdk-m2-parity` | **M2.4b** — Add Python `stockbot` `register_signal`, batch feature runner, and M2 `MarketDataStore` methods | `m2-ceo-posts-events-compat`, `m2-store-macro-cross-section-fx1m` | Vault-fenced `fundamentals_as_of`, `macro_as_of`, `cross_section`, optional QuestDB `1m` `bars`/`fx`, and `register_signal(...)` writing contract Zstd Parquet readable identically by TS and Python. **[Director replan §4.3: enforce confirmed `fx_1m` bar-close availability rule + cutoff-spanning/ending boundary fixture.]** | -| **6** | `m2-ec1-snapshot-cli-and-doc-paths` | **M2.1w** — Add notebook snapshot CLI, MCP E2E study+snapshot+finding test, and fix `docs/` → `design/` path drift | `m2-store-macro-cross-section-fx1m`, **`m2-ceo-posts-events-compat` *(replan §4.3)*** | Fail-closed `scripts/export-notebook-snapshot.ts` (`"notebook:snapshot"`); E2E stdio MCP test (`search_symbols` → `file_finding` + snapshot) consuming **co-published `curate-events` + `curate-posts` fixture output** so `event_study` reaches the curated `ceo_post`; `docs/*.md` → `design/*.md` updated in `AGENTS.md`, `CLAUDE.md`, `README.md`, `studio.config.json`, `tools/curate-etl/README.md`. | -| **7** | `m2-host-quant-verification-and-closure` | **M2.5** — Execute host/`quant` M2 preflight, bulk 3-feed intraday load, observed split-boundary & latency checks, and desktop Claude Code EC-1 sign-off | `m2-curate-etl-mongo-and-financials-old`, `m2-python-sdk-m2-parity`, `m2-ec1-snapshot-cli-and-doc-paths` | Retained host `git rev-parse master`, `CARGO_BUILD_JOBS=2 bun run check` + `test/postgres/` + live read-only M2 probe + Quant Research-approved `curate-macro` `--series-map` TSV/ID + `quant` QuestDB `10.2.0` preflight/`0x10` ILP/observed `NEXM.V` & `NVDA.US` split/latency checks + desktop Claude Code EC-1 receipt in `design/m2-close-evidence.md`, marking M2 closed in `design/MILESTONES.md`. **[Director replan §4.3: require retained bulk load + PGWire read-back reconciliation for EOD equity, QM equity, and `CAD.FOREX` FX — source/date coverage, row counts, skips, and EOD/QM `(ts, listing_id)` overlap precedence rule.]** | diff --git a/libs/data/duckdb/package.json b/libs/data/duckdb/package.json deleted file mode 100644 index 7636fd30..00000000 --- a/libs/data/duckdb/package.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "@stock-bot/duckdb", - "version": "1.0.0", - "private": true, - "type": "module", - "description": "Server-side DuckDB executor and MarketDataStore wiring for curated Hive Parquet datasets", - "main": "./src/index.ts", - "types": "./src/index.ts", - "exports": { - ".": "./src/index.ts" - }, - "scripts": { - "build": "tsc", - "test": "bun test" - }, - "dependencies": { - "@duckdb/node-api": "^1.4.4-r.1", - "@stock-bot/research": "workspace:*" - }, - "devDependencies": { - "@types/node": "^20.11.0" - } -} diff --git a/libs/data/duckdb/src/index.ts b/libs/data/duckdb/src/index.ts deleted file mode 100644 index 4eace5b6..00000000 --- a/libs/data/duckdb/src/index.ts +++ /dev/null @@ -1,276 +0,0 @@ -/** - * Concrete server-side DuckDB executor and `MarketDataStore` wiring over - * curated Hive-partitioned Parquet datasets (`design/DATA-CONTRACTS.md` §3.A & §4). - * - * Uses `@duckdb/node-api` (native N-API bindings, works in both Bun and Node) - * while keeping `@stock-bot/research` browser-safe and dependency-free. - */ - -import { copyFile, link, mkdir, mkdtemp, open, rm, type FileHandle } from 'node:fs/promises'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import { DuckDBInstance, type DuckDBConnection, type DuckDBValue } from '@duckdb/node-api'; -import type { MarketDataStore, TableCell, TableRow } from '@stock-bot/research/market-data-store'; -import { - createDuckDbMarketDataStore, - type AdjFactorsArtifactPinner, - type DuckDbExecutor, - type DuckDbMarketDataStoreOptions, - type DuckDbParam, - type PinnedAdjFactorsArtifact, -} from '@stock-bot/research/market-data-store-duckdb'; - -const UTF8_DECODER = new TextDecoder('utf-8', { fatal: false }); -const MS_PER_DAY = 86_400_000; - -export interface CreateNodeDuckDbExecutorOptions { - /** Optional DuckDB file path; defaults to `':memory:'` for read-only Parquet scans. */ - readonly databasePath?: string; -} - -export interface ClosableDuckDbExecutor extends DuckDbExecutor { - close(): Promise; -} - -export interface OpenDuckDbMarketDataStoreOptions - extends Omit { - /** Optional DuckDB database path; defaults to `':memory:'`. */ - readonly databasePath?: string; -} - -export interface OpenedDuckDbMarketDataStore { - readonly store: MarketDataStore; - readonly executor: ClosableDuckDbExecutor; - close(): Promise; -} - -function formatEpochDaysIso(days: number): string { - const date = new Date(days * MS_PER_DAY); - const y = String(date.getUTCFullYear()).padStart(4, '0'); - const m = String(date.getUTCMonth() + 1).padStart(2, '0'); - const d = String(date.getUTCDate()).padStart(2, '0'); - return `${y}-${m}-${d}`; -} - -function isRecord(value: unknown): value is Record { - return value !== null && typeof value === 'object'; -} - -/** - * Normalizes a `@duckdb/node-api` cell value into `@stock-bot/research`'s - * strict `TableCell` (`string | number | boolean | null`) contract. - */ -export function normalizeDuckDbCell(value: unknown): TableCell { - if (value === null || value === undefined) { - return null; - } - if (typeof value === 'string' || typeof value === 'boolean') { - return value; - } - if (typeof value === 'number') { - return Object.is(value, -0) ? 0 : value; - } - if (typeof value === 'bigint') { - const asNumber = Number(value); - if (!Number.isSafeInteger(asNumber)) { - throw new RangeError( - `DuckDB BIGINT value ${value.toString()} exceeds JavaScript safe integer range.` - ); - } - return asNumber; - } - if (value instanceof Uint8Array) { - return UTF8_DECODER.decode(value); - } - if (value instanceof Date) { - return value.getTime(); - } - if (isRecord(value)) { - // DuckDBBlobValue / DuckDBBitValue expose `{ bytes: Uint8Array }` (e.g. parquet_kv_metadata) - if (value.bytes instanceof Uint8Array) { - return UTF8_DECODER.decode(value.bytes); - } - // DuckDBDateValue exposes `{ days: number }` - if (typeof value.days === 'number' && Number.isFinite(value.days)) { - return formatEpochDaysIso(value.days); - } - // DuckDBTimestampValue / DuckDBTimestampTZValue expose `{ micros: bigint }` - if (typeof value.micros === 'bigint') { - const ms = Number(value.micros / 1000n); - if (!Number.isSafeInteger(ms)) { - throw new RangeError( - `DuckDB timestamp micros ${value.micros.toString()} exceeds safe millisecond range.` - ); - } - return ms; - } - // DuckDBDecimalValue exposes `{ value: bigint, scale: number }` - if (typeof value.value === 'bigint' && typeof value.scale === 'number') { - return Number(value.value) / 10 ** value.scale; - } - } - return String(value); -} - -/** - * Opens an in-process `@duckdb/node-api` connection and adapts it to - * {@link DuckDbExecutor}. - */ -export async function createNodeDuckDbExecutor( - options: CreateNodeDuckDbExecutorOptions = {} -): Promise { - const databasePath = options.databasePath ?? ':memory:'; - const instance = await DuckDBInstance.create(databasePath); - let connection: DuckDBConnection; - try { - connection = await instance.connect(); - } catch (err) { - instance.closeSync(); - throw err; - } - let closed = false; - - const assertOpen = (): void => { - if (closed) { - throw new Error('DuckDbExecutor connection has already been closed.'); - } - }; - - return { - async run(sql: string): Promise { - assertOpen(); - await connection.run(sql); - }, - - async query(sql: string, params: readonly DuckDbParam[]): Promise { - assertOpen(); - const values: DuckDBValue[] = params.map(param => param as DuckDBValue); - const reader = - values.length > 0 - ? await connection.runAndReadAll(sql, values) - : await connection.runAndReadAll(sql); - const rawRows = reader.getRowObjects(); - const rows: TableRow[] = new Array(rawRows.length); - for (let i = 0; i < rawRows.length; i += 1) { - const raw = rawRows[i]; - const clean: Record = {}; - if (raw !== undefined) { - for (const [col, cell] of Object.entries(raw)) { - clean[col] = normalizeDuckDbCell(cell); - } - } - rows[i] = clean; - } - return rows; - }, - - async close(): Promise { - if (closed) { - return; - } - closed = true; - connection.closeSync(); - instance.closeSync(); - }, - }; -} - -/** - * Pins a mutable `/adj_factors/part.parquet` path to a single - * inode/snapshot across footer verification and factor scan so concurrent - * atomic replacements by `curate-etl` cannot introduce TOCTOU drift. - * - * On Linux, opens a read-only file descriptor and exposes `/proc/self/fd/`. - * On platforms without `/proc/self/fd`, falls back to a private hardlink (or - * copy across filesystems) inside a temporary directory cleaned up in `release()`. - */ -export function createFsAdjFactorsPinner(): AdjFactorsArtifactPinner { - return async (sourcePath: string): Promise => { - if (process.platform === 'linux') { - const handle: FileHandle = await open(sourcePath, 'r'); - let released = false; - return { - pinnedPath: `/proc/self/fd/${handle.fd}`, - async release(): Promise { - if (released) { - return; - } - released = true; - await handle.close(); - }, - }; - } - - const tempDir = await mkdtemp(join(tmpdir(), 'stockbot-adj-pin-')); - const pinnedPath = join(tempDir, 'adj_factors.parquet'); - try { - await link(sourcePath, pinnedPath); - } catch { - await copyFile(sourcePath, pinnedPath); - } - let released = false; - return { - pinnedPath, - async release(): Promise { - if (released) { - return; - } - released = true; - await rm(tempDir, { recursive: true, force: true }); - }, - }; - }; -} - -/** - * Opens a ready-to-use DuckDB-backed {@link MarketDataStore} wired with - * `@duckdb/node-api` and a filesystem `adj_factors` artifact pinner. - */ -export async function openDuckDbMarketDataStore( - options: OpenDuckDbMarketDataStoreOptions -): Promise { - const tempDir = options.env?.STOCK_BOT_DUCKDB_TEMP_DIR; - if (typeof tempDir === 'string' && tempDir.trim().length > 0) { - await mkdir(tempDir, { recursive: true }); - } - - const executor = await createNodeDuckDbExecutor({ - databasePath: options.databasePath, - }); - - const pinAdjFactorsArtifact = - options.pinAdjFactorsArtifact ?? - (options.immutableAdjFactorsPath === undefined ? createFsAdjFactorsPinner() : undefined); - - try { - const store = createDuckDbMarketDataStore({ - ...options, - executor, - ...(pinAdjFactorsArtifact !== undefined ? { pinAdjFactorsArtifact } : {}), - }); - - return { - store, - executor, - async close(): Promise { - await executor.close(); - }, - }; - } catch (err) { - await executor.close(); - throw err; - } -} - -export { - createDuckDbMarketDataStore, - type AdjFactorsArtifactPinner, - type DuckDbExecutor, - type DuckDbMarketDataStoreOptions, - type DuckDbParam, - type PinnedAdjFactorsArtifact, -}; -export { - openResearchCopilotStore, - type OpenResearchCopilotStoreOptions, -} from './research-copilot-store'; diff --git a/libs/data/duckdb/src/research-copilot-store.ts b/libs/data/duckdb/src/research-copilot-store.ts deleted file mode 100644 index 941c2c53..00000000 --- a/libs/data/duckdb/src/research-copilot-store.ts +++ /dev/null @@ -1,49 +0,0 @@ -/** - * Real DuckDB `MarketDataStore` factory for the MCP research copilot stdio host - * (`runResearchCopilotStdioHost` in `@stock-bot/research/mcp`). - * - * - Uses `config.vaultCutoffTs` as the single authoritative Vault cutoff shared - * between the host and the underlying DuckDB store, and hardcodes - * `vaultOperatorAuthorized: false` so every query remains strictly - * `'vault_fenced'`. - * - Returns a {@link ManagedMarketDataStore} (`{ store, close }`) whose - * `close()` releases the underlying DuckDB connection and instance. - * - Any failure during open (native connection creation or store validation) - * releases already-acquired DuckDB resources before rejecting. - */ - -import type { - ManagedMarketDataStore, - ResearchCopilotHostConfig, - ResearchCopilotStdioHostDeps, -} from '@stock-bot/research/mcp'; -import { openDuckDbMarketDataStore } from './index'; - -export interface OpenResearchCopilotStoreOptions { - /** Optional DuckDB database path; defaults to `':memory:'`. */ - readonly databasePath?: string; - /** Optional environment overrides for DuckDB connection budget (`STOCKBOT_DUCKDB_*`). */ - readonly env?: Readonly>; -} - -/** - * Opens a Vault-fenced DuckDB-backed {@link ManagedMarketDataStore} from a - * validated {@link ResearchCopilotHostConfig} for `ResearchCopilotStdioHostDeps.openStore`. - */ -export const openResearchCopilotStore = (async ( - config: ResearchCopilotHostConfig, - options?: OpenResearchCopilotStoreOptions -): Promise => { - const opened = await openDuckDbMarketDataStore({ - curatedRoot: config.curatedRoot, - vaultCutoffTs: config.vaultCutoffTs, - vaultOperatorAuthorized: false, - ...(options?.databasePath !== undefined ? { databasePath: options.databasePath } : {}), - ...(options?.env !== undefined ? { env: options.env } : {}), - }); - - return { - store: opened.store, - close: opened.close, - }; -}) satisfies ResearchCopilotStdioHostDeps['openStore']; diff --git a/libs/data/duckdb/test/analyze-signal-fundamentals-real-duckdb.test.ts b/libs/data/duckdb/test/analyze-signal-fundamentals-real-duckdb.test.ts deleted file mode 100644 index 9cff62f1..00000000 --- a/libs/data/duckdb/test/analyze-signal-fundamentals-real-duckdb.test.ts +++ /dev/null @@ -1,522 +0,0 @@ -import { afterEach, describe, expect, test } from 'bun:test'; -import { mkdir, mkdtemp, rm } from 'node:fs/promises'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import type { MarketDataStore } from '@stock-bot/research/market-data-store'; -import type { FundamentalsAsOfQuery } from '@stock-bot/research/market-data-store-duckdb'; -import { createAnalyzeSignalTool, createMcpServer } from '@stock-bot/research/mcp'; -import { type SignalObservation, buildForwardReturnPanel, collectBars } from '@stock-bot/research/signal-panel'; -import { analyzeSignal } from '@stock-bot/research/signal-study'; -import type { TrialLedgerExecutor } from '@stock-bot/research/trial-ledger'; -import { createNodeDuckDbExecutor, openDuckDbMarketDataStore } from '../src/index'; - -// QA end-to-end evidence for T-149: MCP `analyze_signal` (source = fundamentals) -// driven against the REAL DuckDB `fundamentalsAsOf` over Hive Parquet files. -// - Dataset ID: `synthetic:qa-analyze-signal-fundamentals-real-duckdb:seed-20261206:v1` -// - Tool version: `mcp:analyze_signal:v1`; adjustment `raw`; horizon 3 sessions; modeled costs 0 -// - Pre-Vault window 2023-03-01..2023-05-12; Vault cutoff 2023-05-15T00:00:00.000Z -// - Bars: 6 listings (101..106), 20:00 UTC closes; 5 post-cutoff bars must be fenced out. -// - Fundamentals (ttm_revenue), all 13:00 UTC: -// 2023-03-10 verified (101..105), 2023-04-05 verified Q2 (all), -// 2023-04-18 same-month restatement (101..103, verified), -// 2023-04-18 estimated-lag update (104) -> omitted by DuckDB under default lag, -// 2023-04-20 verified row with NULL ttm_revenue (105) -> must not displace 2023-04-05. -// - Baseline: direct `buildForwardReturnPanel` + `analyzeSignal` over independently listed -// expected observations. - -const VAULT_CUTOFF_TS = Date.UTC(2023, 4, 15); -const VAULT_CUTOFF_DATE = '2023-05-15'; -const PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555'; -const LISTING_IDS = [101, 102, 103, 104, 105, 106] as const; -const HORIZON = 3; -// Listing with bars but no fundamentals rows at all (sparse coverage probe). -const UNCOVERED_LISTING_ID = 107; -const BAR_LISTING_IDS = [...LISTING_IDS, UNCOVERED_LISTING_ID] as const; - -const tempDirs: string[] = []; - -afterEach(async () => { - while (tempDirs.length > 0) { - const dir = tempDirs.pop(); - if (dir !== undefined) { - await rm(dir, { recursive: true, force: true }); - } - } -}); - -function createSeededRng(seed: number): () => number { - let s = seed >>> 0; - return () => { - s = (s + 0x6d2b79f5) >>> 0; - let t = s; - t = Math.imul(t ^ (t >>> 15), t | 1); - t ^= t + Math.imul(t ^ (t >>> 7), t | 61); - return ((t ^ (t >>> 14)) >>> 0) / 4294967296; - }; -} - -function businessDates(start: string, count: number): string[] { - const out: string[] = []; - const d = new Date(`${start}T00:00:00Z`); - while (out.length < count) { - const dow = d.getUTCDay(); - if (dow !== 0 && dow !== 6) { - out.push(d.toISOString().slice(0, 10)); - } - d.setUTCDate(d.getUTCDate() + 1); - } - return out; -} - -function ms(date: string, hour: number): number { - return Date.parse(`${date}T${String(hour).padStart(2, '0')}:00:00.000Z`); -} - -interface PitRow { - readonly listingId: number; - readonly knownAt: string; // YYYY-MM-DD - readonly hour?: number; // UTC hour, default 13 - readonly ttm: number | null; - readonly estimated?: boolean; -} - -const BASE_PIT_ROWS: readonly PitRow[] = [ - ...[101, 102, 103, 104, 105].map((lid, l) => ({ - listingId: lid, - knownAt: '2023-03-10', - ttm: 200 + ((l * 3) % 5) * 25, - })), - ...LISTING_IDS.map((lid, l) => ({ listingId: lid, knownAt: '2023-04-05', ttm: 100 + l * 40 })), - ...[101, 102, 103].map((lid, l) => ({ listingId: lid, knownAt: '2023-04-18', ttm: 400 - l * 90 })), - { listingId: 104, knownAt: '2023-04-18', ttm: 999, estimated: true }, - { listingId: 105, knownAt: '2023-04-20', ttm: null }, -]; - -function pitRowSql(r: PitRow): string { - const est = r.estimated === true ? 'TRUE' : 'FALSE'; - const ttm = r.ttm === null ? 'NULL::DOUBLE' : `${r.ttm}::DOUBLE`; - const ttmMeta = - r.ttm === null ? 'NULL::DATE, NULL::VARCHAR' : `DATE '2023-03-31', 'USD'::VARCHAR`; - const ts = `${r.knownAt} ${String(r.hour ?? 13).padStart(2, '0')}:00:00+00`; - return `(${r.listingId}::INTEGER, TIMESTAMPTZ '${ts}', 'filing_date'::VARCHAR, ${est}::BOOLEAN, - DATE '2023-03-31', 'Q1'::VARCHAR, 'USD'::VARCHAR, TIMESTAMPTZ '${ts}', - 1.0::DOUBLE, NULL::DOUBLE, NULL::DOUBLE, NULL::DOUBLE, NULL::DOUBLE, NULL::DOUBLE, - ${ttmMeta}, ${ttm}, NULL::DOUBLE, NULL::DOUBLE, ${est}::BOOLEAN)`; -} - -async function writeCurated( - curatedRoot: string, - pitPartitions: Readonly> -): Promise { - const rand = createSeededRng(20261206); - const dates = businessDates('2023-03-01', 58); // 53 pre-cutoff + 5 Vault sessions - const prices = BAR_LISTING_IDS.map(() => 40); - const barValues: string[] = []; - for (const date of dates) { - for (let l = 0; l < BAR_LISTING_IDS.length; l += 1) { - const ret = (l - 2.5) * 0.002 + (rand() * 2 - 1) * 0.009; - prices[l] = Math.max(1, prices[l]! * (1 + ret)); - const close = Number(prices[l]!.toFixed(6)); - const ts = `TIMESTAMPTZ '${date} 20:00:00+00'`; - barValues.push( - `(${BAR_LISTING_IDS[l]}::INTEGER, DATE '${date}', ${ts}, ${close}::DOUBLE, ${close}::DOUBLE, ${close}::DOUBLE, ${close}::DOUBLE, 50000.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, ${ts})` - ); - } - } - - await mkdir(join(curatedRoot, 'bars_1d', 'year=2023'), { recursive: true }); - const writer = await createNodeDuckDbExecutor(); - try { - await writer.run(` - COPY ( - SELECT * FROM (VALUES ${barValues.join(', ')}) - AS t(listing_id, session_date, ts, open, high, low, close, volume, vwap, currency, known_at) - ) TO '${join(curatedRoot, 'bars_1d', 'year=2023', 'part.parquet')}' (FORMAT PARQUET) - `); - for (const [year, rows] of Object.entries(pitPartitions)) { - const dir = join(curatedRoot, 'fundamentals_pit', `year=${year}`); - await mkdir(dir, { recursive: true }); - await writer.run(` - COPY ( - SELECT * FROM (VALUES ${rows.map(pitRowSql).join(', ')}) AS t( - listing_id, effective_known_at, known_at_source, has_estimated_lag, - period_end, fiscal_period, currency, period_known_at, - revenue, net_income, operating_cash_flow, total_assets, total_equity, shares_outstanding, - ttm_period_end, ttm_currency, ttm_revenue, ttm_net_income, ttm_operating_cash_flow, ttm_has_estimated_lag - ) - ) TO '${join(dir, 'part.parquet')}' (FORMAT PARQUET) - `); - } - } finally { - await writer.close(); - } -} - -interface LedgerRow { - readonly trial_id: string; - readonly created_at: Date; - readonly principal_id: string; - readonly campaign_id: string | null; - readonly stage: string; - readonly universe_market: string; - readonly horizon_bucket: string; - readonly hypothesis_id: string | null; - readonly expression_hash: string; - readonly sample_start: string; - readonly sample_end: string; - readonly n_obs: number; - readonly sharpe_unann: number; - readonly skewness: number; - readonly kurtosis: number; - readonly daily_series: number[]; -} - -// Deterministic in-memory trial_ledger port (fixed created_at, sequential ids). -function createLedger(): { executor: TrialLedgerExecutor; rows: LedgerRow[] } { - const rows: LedgerRow[] = []; - let nextId = 1; - const executor: TrialLedgerExecutor = { - async query>(text: string, params?: readonly unknown[]) { - const p = params ?? []; - const trimmed = text.trimStart(); - if (trimmed.startsWith('INSERT INTO trial_ledger')) { - const id = nextId++; - const row: LedgerRow = { - trial_id: String(id), - created_at: new Date(Date.UTC(2024, 0, 1, 0, 0, id)), - principal_id: p[0] as string, - campaign_id: (p[1] as string | null) ?? null, - stage: p[2] as string, - universe_market: p[3] as string, - horizon_bucket: p[4] as string, - hypothesis_id: (p[5] as string | null) ?? null, - expression_hash: p[6] as string, - sample_start: p[7] as string, - sample_end: p[8] as string, - n_obs: p[9] as number, - sharpe_unann: p[10] as number, - skewness: p[11] as number, - kurtosis: p[12] as number, - daily_series: (p[13] as readonly number[]).map(v => Math.fround(v)), - }; - rows.push(row); - return { - rows: [{ trial_id: row.trial_id, created_at: row.created_at } as unknown as Row], - rowCount: 1, - }; - } - if (trimmed.startsWith('SELECT')) { - if (text.includes('WHERE trial_id = $1::bigint')) { - const matched = rows.filter(r => r.trial_id === String(p[0])); - return { rows: matched as unknown as Row[], rowCount: matched.length }; - } - if (text.includes('WHERE universe_market = $1')) { - const matched = rows.filter( - r => r.universe_market === p[0] && r.horizon_bucket === p[1] - ); - return { rows: matched as unknown as Row[], rowCount: matched.length }; - } - } - return { rows: [], rowCount: 0 }; - }, - }; - return { executor, rows }; -} - -async function openStore( - pitPartitions: Readonly> -): Promise<{ - store: MarketDataStore; - calls: FundamentalsAsOfQuery[]; - close: () => Promise; -}> { - const root = await mkdtemp(join(tmpdir(), 'stockbot-qa-as-fnd-')); - tempDirs.push(root); - const curatedRoot = join(root, 'curated'); - const duckTempDir = join(root, 'duckdb-tmp'); - await mkdir(duckTempDir, { recursive: true }); - await writeCurated(curatedRoot, pitPartitions); - const opened = await openDuckDbMarketDataStore({ - curatedRoot, - vaultCutoffTs: VAULT_CUTOFF_TS, - env: { - STOCK_BOT_DUCKDB_MEMORY_LIMIT: '1GB', - STOCK_BOT_DUCKDB_THREADS: '2', - STOCK_BOT_DUCKDB_TEMP_DIR: duckTempDir, - }, - }); - const calls: FundamentalsAsOfQuery[] = []; - const inner = opened.store; - const store: MarketDataStore = { - ...inner, - bars: q => inner.bars(q), - shortsAsOf: q => inner.shortsAsOf(q), - universe: q => inner.universe(q), - fundamentalsAsOf: q => { - calls.push(q); - return inner.fundamentalsAsOf(q); - }, - }; - return { store, calls, close: () => opened.close() }; -} - -async function runTool( - store: MarketDataStore, - ledger: TrialLedgerExecutor, - allowEstimatedLag?: boolean, - listingIds: readonly number[] = LISTING_IDS -): Promise<{ isError: boolean; text: string }> { - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createAnalyzeSignalTool({ - store, - ledger, - vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, - principalId: PRINCIPAL, - }), - ], - }); - const raw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 'qa-1', - method: 'tools/call', - params: { - name: 'analyze_signal', - arguments: { - listingIds: [...listingIds], - from: '2023-03-01', - to: '2023-05-19', // straddles the Vault cutoff; must be clamped - signal: { - source: 'fundamentals', - field: 'ttm_revenue', - ...(allowEstimatedLag === undefined ? {} : { allowEstimatedLag }), - }, - horizonSessions: HORIZON, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }, - }, - }) - ); - const parsed = JSON.parse(raw as string) as { - result: { isError?: boolean; content: { text: string }[] }; - }; - return { isError: parsed.result.isError === true, text: parsed.result.content[0]?.text ?? '' }; -} - -function expectedObservations( - includeEstimated: boolean, - rows: readonly PitRow[] = BASE_PIT_ROWS -): SignalObservation[] { - const out: SignalObservation[] = []; - for (const r of rows) { - if (r.ttm === null || (r.estimated === true && !includeEstimated)) { - continue; - } - out.push({ listingId: r.listingId, knownAt: ms(r.knownAt, r.hour ?? 13), value: r.ttm }); - } - return out; -} - -async function directBaseline( - store: MarketDataStore, - signals: SignalObservation[], - listingIds: readonly number[] = LISTING_IDS -): Promise<{ rankIc: unknown; series: number[]; sampleStart: string; sampleEnd: string }> { - const bars = await collectBars(store.bars({ - listingIds: [...listingIds], - from: '2023-03-01', - to: '2023-05-12', - timeframe: '1d', - adjustment: 'raw', - })); - const built = buildForwardReturnPanel({ - bars, - signals, - horizonSessions: HORIZON, - vaultCutoffDate: VAULT_CUTOFF_DATE, - }); - const ledger = createLedger(); - const study = await analyzeSignal(ledger.executor, { - principalId: PRINCIPAL, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - expression: { - expression: 'qa_direct_baseline', - params: { field: 'ttm_revenue' }, - universe: [...listingIds], - horizon: `${HORIZON}d`, - }, - panel: built.panel, - vaultCutoffDate: VAULT_CUTOFF_DATE, - }); - if (study.status !== 'ok') { - throw new Error(`baseline study not ok: ${study.status}`); - } - return { - rankIc: study.analysis.rankIc, - series: ledger.rows[0]!.daily_series, - sampleStart: study.trial.sampleStart, - sampleEnd: study.trial.sampleEnd, - }; -} - -interface OkPayload { - status: 'ok'; - signal: unknown; - analysis: { rankIc: unknown }; - trial: { sampleStart: string; sampleEnd: string; expressionHash: string }; -} - -describe('analyze_signal fundamentals over real DuckDB fundamentalsAsOf (QA)', () => { - test('default lag: same-month restatement, estimated-lag omission and null-field rows replay exactly like the verified-only baseline', async () => { - const s = await openStore({ '2023': BASE_PIT_ROWS }); - try { - const ledger = createLedger(); - const res = await runTool(s.store, ledger.executor); - expect(res.isError).toBe(false); - const payload = JSON.parse(res.text) as OkPayload; - expect(payload.status).toBe('ok'); - expect(payload.signal).toEqual({ - source: 'fundamentals', - field: 'ttm_revenue', - allowEstimatedLag: false, - }); - - const baseline = await directBaseline(s.store, expectedObservations(false)); - expect(payload.analysis.rankIc).toEqual(baseline.rankIc); - expect(ledger.rows).toHaveLength(1); - expect(ledger.rows[0]!.daily_series).toEqual(baseline.series); - expect(payload.trial.sampleStart).toBe(baseline.sampleStart); - expect(payload.trial.sampleEnd).toBe(baseline.sampleEnd); - expect(payload.trial.sampleEnd < VAULT_CUTOFF_DATE).toBe(true); - - // Every real-store read is strictly pre-Vault and forwards the lag flag verbatim. - expect(s.calls.length).toBeGreaterThan(0); - for (const call of s.calls) { - expect(Date.parse(call.asOf)).toBeLessThan(VAULT_CUTOFF_TS); - expect(call.allowEstimatedLag).toBe(false); - expect(call.fields).toEqual(['ttm_revenue']); - } - // Fan-out bound: month-end snapshots (3) + at most one probe per eligible session (53). - expect(s.calls.length).toBeLessThanOrEqual(3 + 53); - } finally { - await s.close(); - } - }); - - test('allowEstimatedLag true includes the estimated update and matches its own baseline', async () => { - const s = await openStore({ '2023': BASE_PIT_ROWS }); - try { - const ledger = createLedger(); - const res = await runTool(s.store, ledger.executor, true); - const payload = JSON.parse(res.text) as OkPayload; - expect(payload.status).toBe('ok'); - const baseline = await directBaseline(s.store, expectedObservations(true)); - expect(payload.analysis.rankIc).toEqual(baseline.rankIc); - expect(ledger.rows[0]!.daily_series).toEqual(baseline.series); - expect(s.calls.every(c => c.allowEstimatedLag === true)).toBe(true); - - const defaultLedger = createLedger(); - const defaultRes = await runTool(s.store, defaultLedger.executor); - const defaultPayload = JSON.parse(defaultRes.text) as OkPayload; - expect(defaultPayload.trial.expressionHash).not.toBe(payload.trial.expressionHash); - expect(defaultLedger.rows[0]!.daily_series).not.toEqual(ledger.rows[0]!.daily_series); - } finally { - await s.close(); - } - }); - - test('appending Vault-window and post-cutoff revisions in another Parquet partition leaves payload and ledger rows byte-identical', async () => { - const clean = await openStore({ '2023': BASE_PIT_ROWS }); - const poisoned = await openStore({ - '2023': BASE_PIT_ROWS, - '2099': [ - // Exactly at the Vault cutoff, inside the Vault, and long after. - ...LISTING_IDS.map(lid => ({ listingId: lid, knownAt: '2023-05-15', ttm: 5_000 + lid })), - ...LISTING_IDS.map(lid => ({ listingId: lid, knownAt: '2023-05-17', ttm: 7_000 - lid })), - ...LISTING_IDS.map(lid => ({ listingId: lid, knownAt: '2024-01-02', ttm: 9_000 + lid })), - ], - }); - try { - const cleanLedger = createLedger(); - const poisonedLedger = createLedger(); - const cleanRes = await runTool(clean.store, cleanLedger.executor); - const poisonedRes = await runTool(poisoned.store, poisonedLedger.executor); - expect(cleanRes.isError).toBe(false); - expect(poisonedRes.text).toBe(cleanRes.text); - expect(poisonedLedger.rows).toEqual(cleanLedger.rows); - expect(poisoned.calls.map(c => c.asOf)).toEqual(clean.calls.map(c => c.asOf)); - } finally { - await clean.close(); - await poisoned.close(); - } - }); - - test('a release stamped exactly at a bar close and superseded next morning is replayed at that close', async () => { - // 106 files at 2023-04-12 20:00:00Z (== bar close ts) and restates at 2023-04-13 13:00Z. - // A month-end-only read would only see the 04-13 vintage; the 04-12 close must use 50. - const rows: readonly PitRow[] = [ - ...BASE_PIT_ROWS, - { listingId: 106, knownAt: '2023-04-12', hour: 20, ttm: 50 }, - { listingId: 106, knownAt: '2023-04-13', ttm: 900 }, - ]; - const s = await openStore({ '2023': rows }); - try { - const ledger = createLedger(); - const res = await runTool(s.store, ledger.executor); - const payload = JSON.parse(res.text) as OkPayload; - expect(payload.status).toBe('ok'); - const baseline = await directBaseline(s.store, expectedObservations(false, rows)); - expect(payload.analysis.rankIc).toEqual(baseline.rankIc); - expect(ledger.rows[0]!.daily_series).toEqual(baseline.series); - // Probe at the exact close timestamp is issued (store compares effective_known_at <= asOf). - expect(s.calls.some(c => Date.parse(c.asOf) === ms('2023-04-12', 20))).toBe(true); - } finally { - await s.close(); - } - }); - - test('sparse coverage: a listing with bars but no fundamentals stays bounded and does not change the study', async () => { - // Measurement for the reviewer's non-blocking fan-out note. The uncovered listing is - // probed at each eligible session, so calls grow with sessions, not with listings. - const covered = await openStore({ '2023': BASE_PIT_ROWS }); - const sparse = await openStore({ '2023': BASE_PIT_ROWS }); - try { - const coveredLedger = createLedger(); - const sparseLedger = createLedger(); - const coveredRes = await runTool(covered.store, coveredLedger.executor); - const sparseRes = await runTool(sparse.store, sparseLedger.executor, undefined, [ - ...LISTING_IDS, - UNCOVERED_LISTING_ID, - ]); - const coveredPayload = JSON.parse(coveredRes.text) as OkPayload; - const sparsePayload = JSON.parse(sparseRes.text) as OkPayload; - expect(coveredPayload.status).toBe('ok'); - expect(sparsePayload.status).toBe('ok'); - - // No signal for 107 -> same cross-sectional series as the covered-only study. - const baseline = await directBaseline(sparse.store, expectedObservations(false), [ - ...LISTING_IDS, - UNCOVERED_LISTING_ID, - ]); - expect(sparseLedger.rows[0]!.daily_series).toEqual(baseline.series); - - // 53 eligible sessions over 3 UTC months: <= 3 month-end snapshots + 53 probes. - expect(sparse.calls.length).toBeLessThanOrEqual(3 + 53); - expect(sparse.calls.length).toBeGreaterThan(covered.calls.length); - // Each session timestamp is probed at most once. - const asOfs = sparse.calls.map(c => c.asOf); - expect(new Set(asOfs).size).toBe(asOfs.length); - for (const call of sparse.calls) { - expect(Date.parse(call.asOf)).toBeLessThan(VAULT_CUTOFF_TS); - } - } finally { - await covered.close(); - await sparse.close(); - } - }); -}); diff --git a/libs/data/duckdb/test/duckdb-market-data-store.test.ts b/libs/data/duckdb/test/duckdb-market-data-store.test.ts deleted file mode 100644 index dfe3259c..00000000 --- a/libs/data/duckdb/test/duckdb-market-data-store.test.ts +++ /dev/null @@ -1,931 +0,0 @@ -import { afterEach, describe, expect, test } from 'bun:test'; -import { mkdir, mkdtemp, rm } from 'node:fs/promises'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import { - computeVaultCutoffTs, - VaultHoldoutFenceError, - type BarRecord, -} from '@stock-bot/research/market-data-store'; -import { - createNodeDuckDbExecutor, - openDuckDbMarketDataStore, -} from '../src/index'; - -const tempDirs: string[] = []; - -afterEach(async () => { - while (tempDirs.length > 0) { - const dir = tempDirs.pop(); - if (dir !== undefined) { - await rm(dir, { recursive: true, force: true }); - } - } -}); - -async function buildCuratedFixture(): Promise<{ - curatedRoot: string; - duckTempDir: string; - vaultCutoffTs: number; -}> { - const root = await mkdtemp(join(tmpdir(), 'stockbot-duckdb-mds-')); - tempDirs.push(root); - const curatedRoot = join(root, 'curated'); - const duckTempDir = join(root, 'duckdb-tmp'); - - await mkdir(join(curatedRoot, 'bars_1d', 'year=2024'), { recursive: true }); - await mkdir(join(curatedRoot, 'bars_1d', 'year=2025'), { recursive: true }); - await mkdir(join(curatedRoot, 'adj_factors'), { recursive: true }); - await mkdir(join(curatedRoot, 'events', 'year=2024'), { recursive: true }); - await mkdir(join(curatedRoot, 'shorts'), { recursive: true }); - await mkdir(join(curatedRoot, 'fx_1d'), { recursive: true }); - await mkdir(duckTempDir, { recursive: true }); - - // Max ingested = 2025-08-13 -> Vault cutoff = 2025-02-13T00:00:00.000Z - const vaultCutoffTs = computeVaultCutoffTs('2025-08-13'); - const vaultCutoffMicros = vaultCutoffTs * 1000; - const asOfMicros = vaultCutoffMicros - 1; - - const writer = await createNodeDuckDbExecutor(); - try { - // 2024 bars (pre-Vault): listing 101 (USD, NVDA 10:1 split on 2024-06-10) + listing 202 (CAD) - await writer.run(` - COPY ( - SELECT * FROM (VALUES - (101::INTEGER, DATE '2024-06-07', TIMESTAMPTZ '2024-06-07 20:00:00+00', 1200.0::DOUBLE, 1220.0::DOUBLE, 1190.0::DOUBLE, 1208.88::DOUBLE, 41238600.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2024-06-07 20:00:00+00'), - (101::INTEGER, DATE '2024-06-10', TIMESTAMPTZ '2024-06-10 20:00:00+00', 120.37::DOUBLE, 123.10::DOUBLE, 117.01::DOUBLE, 121.79::DOUBLE, 314162700.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2024-06-10 20:00:00+00'), - (202::INTEGER, DATE '2024-06-10', TIMESTAMPTZ '2024-06-10 20:00:00+00', 140.0::DOUBLE, 142.0::DOUBLE, 139.0::DOUBLE, 141.5::DOUBLE, 1200000.0::DOUBLE, NULL::DOUBLE, 'CAD'::VARCHAR, TIMESTAMPTZ '2024-06-10 20:00:00+00') - ) AS t(listing_id, session_date, ts, open, high, low, close, volume, vwap, currency, known_at) - ) TO '${join(curatedRoot, 'bars_1d', 'year=2024', 'part.parquet')}' (FORMAT PARQUET) - `); - - // 2025 bars: one pre-Vault bar (2025-02-12) and one Vault bar (2025-02-14) - await writer.run(` - COPY ( - SELECT * FROM (VALUES - (101::INTEGER, DATE '2025-02-12', TIMESTAMPTZ '2025-02-12 20:00:00+00', 130.0::DOUBLE, 132.0::DOUBLE, 129.0::DOUBLE, 131.0::DOUBLE, 200000000.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-02-12 20:00:00+00'), - (101::INTEGER, DATE '2025-02-14', TIMESTAMPTZ '2025-02-14 20:00:00+00', 999.0::DOUBLE, 999.0::DOUBLE, 999.0::DOUBLE, 999.0::DOUBLE, 1.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-02-14 20:00:00+00') - ) AS t(listing_id, session_date, ts, open, high, low, close, volume, vwap, currency, known_at) - ) TO '${join(curatedRoot, 'bars_1d', 'year=2025', 'part.parquet')}' (FORMAT PARQUET) - `); - - // Point-in-time fenced adj_factors snapshot (10:1 split on 2024-06-10) - await writer.run(` - COPY ( - SELECT * FROM (VALUES - (101::INTEGER, DATE '2024-06-10', 10.0::DOUBLE, 10.05::DOUBLE, TIMESTAMPTZ '2024-06-10 00:00:00+00') - ) AS t(listing_id, ex_date, cum_split_factor, cum_total_factor, known_at) - ) TO '${join(curatedRoot, 'adj_factors', 'part.parquet')}' ( - FORMAT PARQUET, - KV_METADATA { - 'stock_bot.adj_factors.format_version': '1', - 'stock_bot.adj_factors.snapshot_kind': 'point_in_time_fenced', - 'stock_bot.adj_factors.as_of_micros': '${asOfMicros}', - 'stock_bot.adj_factors.vault_cutoff_micros': '${vaultCutoffMicros}', - 'stock_bot.adj_factors.rows_written': '1', - 'stock_bot.adj_factors.snapshot_checksum': '0x0123456789abcdef' - } - ) - `); - - // Events (2024 filing) - await writer.run(` - COPY ( - SELECT * FROM (VALUES - (202::INTEGER, TIMESTAMPTZ '2024-06-05 14:30:00+00', TIMESTAMPTZ '2024-06-05 14:30:00+00', 'filing_timestamp'::VARCHAR, 'filing'::VARCHAR, 'MD&A'::VARCHAR, '{"filing_id":"f1"}'::VARCHAR) - ) AS t(listing_id, ts, known_at, known_at_source, kind, subtype, payload_json) - ) TO '${join(curatedRoot, 'events', 'year=2024', 'part.parquet')}' (FORMAT PARQUET) - `); - - // Canadian shorts (+4 biz day known_at) - await writer.run(` - COPY ( - SELECT * FROM (VALUES - (202::INTEGER, DATE '2024-06-15', TIMESTAMPTZ '2024-06-21 21:00:00+00', 500000.0::DOUBLE, 25000.0::DOUBLE, NULL::DOUBLE, 'ceo_shorts'::VARCHAR) - ) AS t(listing_id, report_date, known_at, shares_short, net_change, pct_float, source) - ) TO '${join(curatedRoot, 'shorts', 'part.parquet')}' (FORMAT PARQUET) - `); - - // FX 1d (USDCAD) - await writer.run(` - COPY ( - SELECT * FROM (VALUES - ('USDCAD'::VARCHAR, DATE '2024-06-10', TIMESTAMPTZ '2024-06-10 23:59:59.999999+00', 1.375::DOUBLE, 1.378::DOUBLE, 1.372::DOUBLE, 1.376::DOUBLE, 'eod_forex'::VARCHAR, TIMESTAMPTZ '2024-06-10 23:59:59.999999+00') - ) AS t(pair, session_date, ts, open, high, low, close, source, known_at) - ) TO '${join(curatedRoot, 'fx_1d', 'part.parquet')}' (FORMAT PARQUET) - `); - } finally { - await writer.close(); - } - - return { curatedRoot, duckTempDir, vaultCutoffTs }; -} - -describe('openDuckDbMarketDataStore (@duckdb/node-api)', () => { - test('reads real Parquet bars (raw, split, total), events, shorts, fx, universe and enforces Vault fence', async () => { - const { curatedRoot, duckTempDir, vaultCutoffTs } = await buildCuratedFixture(); - const opened = await openDuckDbMarketDataStore({ - curatedRoot, - vaultCutoffTs, - env: { - STOCK_BOT_DUCKDB_MEMORY_LIMIT: '2GB', - STOCK_BOT_DUCKDB_THREADS: '2', - STOCK_BOT_DUCKDB_TEMP_DIR: duckTempDir, - }, - }); - - try { - // 1. Raw bars: request through 2025-12-31 must clamp before Vault cutoff (2025-02-13) and never return 2025-02-14! - const rawBars: BarRecord[] = []; - for await (const batch of opened.store.bars({ - listingIds: [101], - timeframe: '1d', - from: '2024-06-01', - to: '2025-12-31', - adjustment: 'raw', - })) { - rawBars.push(...batch.rows); - } - expect(rawBars.length).toBe(3); - expect(rawBars.every(r => r.ts < vaultCutoffTs)).toBe(true); - expect(rawBars[0]!.close).toBeCloseTo(1208.88, 6); - expect(rawBars[0]!.volume).toBeCloseTo(41_238_600, 1); - - // 2. Vault rejection when from >= vaultCutoffTs - let rejected = false; - try { - for await (const _batch of opened.store.bars({ - listingIds: [101], - timeframe: '1d', - from: '2025-02-13', - to: '2025-08-01', - adjustment: 'raw', - })) { - // should not yield - } - } catch (err) { - rejected = err instanceof VaultHoldoutFenceError; - } - expect(rejected).toBe(true); - - // 3. Split-adjusted bars via pinned point_in_time_fenced adj_factors snapshot - const splitBars: BarRecord[] = []; - for await (const batch of opened.store.bars({ - listingIds: [101], - timeframe: '1d', - from: '2024-06-01', - to: '2024-06-15', - adjustment: 'split', - })) { - splitBars.push(...batch.rows); - } - expect(splitBars.length).toBe(2); - expect(splitBars[0]!.close).toBeCloseTo(120.888, 6); - expect(splitBars[0]!.volume).toBeCloseTo(412_386_000, 1); - expect(splitBars[1]!.close).toBeCloseTo(121.79, 6); - - // 4. Total-return-adjusted bars (price divided by cum_total_factor, volume scaled by cum_split_factor) - const totalBars: BarRecord[] = []; - for await (const batch of opened.store.bars({ - listingIds: [101], - timeframe: '1d', - from: '2024-06-01', - to: '2024-06-15', - adjustment: 'total', - })) { - totalBars.push(...batch.rows); - } - expect(totalBars.length).toBe(2); - expect(totalBars[0]!.close).toBeCloseTo(1208.88 / 10.05, 6); - expect(totalBars[0]!.volume).toBeCloseTo(412_386_000, 1); - - // 5. Events - const events = await opened.store.events({ - kinds: ['filing'], - listingIds: [202], - from: '2024-06-01', - to: '2024-06-30', - }); - expect(events.rows.length).toBe(1); - expect(events.rows[0]!.subtype).toBe('MD&A'); - - // 6. Shorts (known_at fence) - const shortsBeforeKnown = await opened.store.shortsAsOf({ - listingIds: [202], - from: '2024-06-01', - to: '2024-06-30', - asOf: '2024-06-18', - }); - expect(shortsBeforeKnown.rows.length).toBe(0); - - const shortsAfterKnown = await opened.store.shortsAsOf({ - listingIds: [202], - from: '2024-06-01', - to: '2024-06-30', - asOf: '2024-06-25', - }); - expect(shortsAfterKnown.rows.length).toBe(1); - expect(shortsAfterKnown.rows[0]!.shares_short).toBe(500_000); - - // 7. FX - const fx = await opened.store.fx({ - pair: 'USD.CAD', - timeframe: '1d', - from: '2024-06-01', - to: '2024-06-30', - }); - expect(fx.rows.length).toBe(1); - expect(fx.rows[0]!.close).toBeCloseTo(1.376, 6); - - // 8. Universe - expect(await opened.store.universe({ ref: 'US_EQ', date: '2024-06-10' })).toEqual([101]); - expect(await opened.store.universe({ ref: 'CA_EQ', date: '2024-06-10' })).toEqual([202]); - expect(await opened.store.universe({ ref: 'US_CA_EQ', date: '2024-06-10' })).toEqual([ - 101, 202, - ]); - } finally { - await opened.close(); - } - }); - - test('fundamentalsAsOf enforces restatement non-overwrite, multi-year Hive glob, Vault microsecond fence, and allowEstimatedLag semantics', async () => { - const root = await mkdtemp(join(tmpdir(), 'stockbot-duckdb-fnd-')); - tempDirs.push(root); - const curatedRoot = join(root, 'curated'); - const duckTempDir = join(root, 'duckdb-tmp'); - - await mkdir(join(curatedRoot, 'fundamentals_pit', 'year=2023'), { recursive: true }); - await mkdir(join(curatedRoot, 'fundamentals_pit', 'year=2024'), { recursive: true }); - await mkdir(join(curatedRoot, 'fundamentals_pit', 'year=2025'), { recursive: true }); - await mkdir(duckTempDir, { recursive: true }); - - // Vault cutoff = 2025-02-13T00:00:00.000Z - const vaultCutoffTs = computeVaultCutoffTs('2025-08-13'); - const s1KnownMs = Date.UTC(2024, 4, 1, 20, 0, 0, 0); // 2024-05-01T20:00:00Z - const s2KnownMs = Date.UTC(2024, 7, 1, 20, 0, 0, 0); // 2024-08-01T20:00:00Z - const s3KnownMs = Date.UTC(2024, 8, 15, 20, 0, 0, 0); // 2024-09-15T20:00:00Z - - const writer = await createNodeDuckDbExecutor(); - try { - // year=2023 partition: listing 50 (only exists in 2023 partition) - await writer.run(` - COPY ( - SELECT * FROM (VALUES - ( - 50::INTEGER, - TIMESTAMPTZ '2023-11-05 20:00:00+00', - 'filing_date'::VARCHAR, - FALSE::BOOLEAN, - DATE '2023-09-30', - 'Q3'::VARCHAR, - 'USD'::VARCHAR, - TIMESTAMPTZ '2023-11-05 20:00:00+00', - 80.0::DOUBLE, - 8.0::DOUBLE, - 12.0::DOUBLE, - 500.0::DOUBLE, - 250.0::DOUBLE, - 10.0::DOUBLE, - DATE '2023-09-30', - 'USD'::VARCHAR, - 310.0::DOUBLE, - 31.0::DOUBLE, - 46.0::DOUBLE, - FALSE::BOOLEAN - ) - ) AS t( - listing_id, effective_known_at, known_at_source, has_estimated_lag, - period_end, fiscal_period, currency, period_known_at, - revenue, net_income, operating_cash_flow, total_assets, total_equity, shares_outstanding, - ttm_period_end, ttm_currency, ttm_revenue, ttm_net_income, ttm_operating_cash_flow, ttm_has_estimated_lag - ) - ) TO '${join(curatedRoot, 'fundamentals_pit', 'year=2023', 'part.parquet')}' (FORMAT PARQUET) - `); - - // year=2024 partition: - // - listing 101: S1 (Q1), S2 (Q2), S3 (Q1 restatement known after Q2 -> latest period stays Q2, TTM changes) - // - listing 201: older verified snapshot + newer estimated-lag snapshot (strict mode must omit without fallback) - // - listing 202: verified snapshot with estimated-lag TTM only (strict mode keeps row, nulls ttm_* + ttm_period_end + ttm_currency, preserves ttm_has_estimated_lag) - await writer.run(` - COPY ( - SELECT * FROM (VALUES - ( - 101::INTEGER, - TIMESTAMPTZ '2024-05-01 20:00:00+00', - 'filing_date'::VARCHAR, - FALSE::BOOLEAN, - DATE '2024-03-31', - 'Q1'::VARCHAR, - 'USD'::VARCHAR, - TIMESTAMPTZ '2024-05-01 20:00:00+00', - 100.0::DOUBLE, - 10.0::DOUBLE, - 15.0::DOUBLE, - 1000.0::DOUBLE, - 500.0::DOUBLE, - 50.0::DOUBLE, - DATE '2024-03-31', - 'USD'::VARCHAR, - 380.0::DOUBLE, - 38.0::DOUBLE, - 55.0::DOUBLE, - FALSE::BOOLEAN - ), - ( - 101::INTEGER, - TIMESTAMPTZ '2024-08-01 20:00:00+00', - 'filing_date'::VARCHAR, - FALSE::BOOLEAN, - DATE '2024-06-30', - 'Q2'::VARCHAR, - 'USD'::VARCHAR, - TIMESTAMPTZ '2024-08-01 20:00:00+00', - 120.0::DOUBLE, - 14.0::DOUBLE, - 20.0::DOUBLE, - 1050.0::DOUBLE, - 520.0::DOUBLE, - 50.0::DOUBLE, - DATE '2024-06-30', - 'USD'::VARCHAR, - 420.0::DOUBLE, - 44.0::DOUBLE, - 65.0::DOUBLE, - FALSE::BOOLEAN - ), - ( - 101::INTEGER, - TIMESTAMPTZ '2024-09-15 20:00:00+00', - 'filing_date'::VARCHAR, - FALSE::BOOLEAN, - DATE '2024-06-30', - 'Q2'::VARCHAR, - 'USD'::VARCHAR, - TIMESTAMPTZ '2024-08-01 20:00:00+00', - 120.0::DOUBLE, - 14.0::DOUBLE, - 20.0::DOUBLE, - 1050.0::DOUBLE, - 520.0::DOUBLE, - 50.0::DOUBLE, - DATE '2024-06-30', - 'USD'::VARCHAR, - 415.0::DOUBLE, - 42.0::DOUBLE, - 63.0::DOUBLE, - FALSE::BOOLEAN - ), - ( - 201::INTEGER, - TIMESTAMPTZ '2024-05-01 20:00:00+00', - 'filing_date'::VARCHAR, - FALSE::BOOLEAN, - DATE '2024-03-31', - 'Q1'::VARCHAR, - 'USD'::VARCHAR, - TIMESTAMPTZ '2024-05-01 20:00:00+00', - 50.0::DOUBLE, - 5.0::DOUBLE, - 7.0::DOUBLE, - 400.0::DOUBLE, - 200.0::DOUBLE, - 20.0::DOUBLE, - DATE '2024-03-31', - 'USD'::VARCHAR, - 190.0::DOUBLE, - 19.0::DOUBLE, - 27.0::DOUBLE, - FALSE::BOOLEAN - ), - ( - 201::INTEGER, - TIMESTAMPTZ '2024-08-01 20:00:00+00', - 'estimated_lag'::VARCHAR, - TRUE::BOOLEAN, - DATE '2024-06-30', - 'Q2'::VARCHAR, - 'USD'::VARCHAR, - TIMESTAMPTZ '2024-08-01 20:00:00+00', - 60.0::DOUBLE, - 6.0::DOUBLE, - 8.0::DOUBLE, - 420.0::DOUBLE, - 210.0::DOUBLE, - 20.0::DOUBLE, - DATE '2024-06-30', - 'USD'::VARCHAR, - 210.0::DOUBLE, - 21.0::DOUBLE, - 30.0::DOUBLE, - TRUE::BOOLEAN - ), - ( - 202::INTEGER, - TIMESTAMPTZ '2024-08-01 20:00:00+00', - 'filing_date'::VARCHAR, - FALSE::BOOLEAN, - DATE '2024-06-30', - 'Q2'::VARCHAR, - 'CAD'::VARCHAR, - TIMESTAMPTZ '2024-08-01 20:00:00+00', - 75.0::DOUBLE, - 9.0::DOUBLE, - 11.0::DOUBLE, - 600.0::DOUBLE, - 300.0::DOUBLE, - 30.0::DOUBLE, - DATE '2024-06-30', - 'CAD'::VARCHAR, - 300.0::DOUBLE, - 30.0::DOUBLE, - 45.0::DOUBLE, - TRUE::BOOLEAN - ) - ) AS t( - listing_id, effective_known_at, known_at_source, has_estimated_lag, - period_end, fiscal_period, currency, period_known_at, - revenue, net_income, operating_cash_flow, total_assets, total_equity, shares_outstanding, - ttm_period_end, ttm_currency, ttm_revenue, ttm_net_income, ttm_operating_cash_flow, ttm_has_estimated_lag - ) - ) TO '${join(curatedRoot, 'fundamentals_pit', 'year=2024', 'part.parquet')}' (FORMAT PARQUET) - `); - - // year=2025 partition: Vault microsecond boundary rows - // - listing 102: 1 microsecond before cutoff (eligible), exact cutoff (excluded), post-cutoff (excluded) - // - listing 103: exact cutoff only (must return 0 rows) - await writer.run(` - COPY ( - SELECT * FROM (VALUES - ( - 102::INTEGER, - TIMESTAMPTZ '2025-02-12 23:59:59.999999+00', - 'filing_date'::VARCHAR, - FALSE::BOOLEAN, - DATE '2024-12-31', - 'Q4'::VARCHAR, - 'USD'::VARCHAR, - TIMESTAMPTZ '2025-02-12 23:59:59.999999+00', - 210.0::DOUBLE, - 21.0::DOUBLE, - 31.0::DOUBLE, - 1500.0::DOUBLE, - 750.0::DOUBLE, - 60.0::DOUBLE, - DATE '2024-12-31', - 'USD'::VARCHAR, - 800.0::DOUBLE, - 80.0::DOUBLE, - 120.0::DOUBLE, - FALSE::BOOLEAN - ), - ( - 102::INTEGER, - TIMESTAMPTZ '2025-02-13 00:00:00.000000+00', - 'filing_date'::VARCHAR, - FALSE::BOOLEAN, - DATE '2024-12-31', - 'Q4'::VARCHAR, - 'USD'::VARCHAR, - TIMESTAMPTZ '2025-02-13 00:00:00.000000+00', - 999.0::DOUBLE, - 99.0::DOUBLE, - 99.0::DOUBLE, - 9999.0::DOUBLE, - 4999.0::DOUBLE, - 60.0::DOUBLE, - DATE '2024-12-31', - 'USD'::VARCHAR, - 9999.0::DOUBLE, - 999.0::DOUBLE, - 999.0::DOUBLE, - FALSE::BOOLEAN - ), - ( - 102::INTEGER, - TIMESTAMPTZ '2025-02-14 12:00:00.000000+00', - 'filing_date'::VARCHAR, - FALSE::BOOLEAN, - DATE '2025-03-31', - 'Q1'::VARCHAR, - 'USD'::VARCHAR, - TIMESTAMPTZ '2025-02-14 12:00:00.000000+00', - 1111.0::DOUBLE, - 111.0::DOUBLE, - 111.0::DOUBLE, - 11111.0::DOUBLE, - 5555.0::DOUBLE, - 60.0::DOUBLE, - DATE '2025-03-31', - 'USD'::VARCHAR, - 11111.0::DOUBLE, - 1111.0::DOUBLE, - 1111.0::DOUBLE, - FALSE::BOOLEAN - ), - ( - 103::INTEGER, - TIMESTAMPTZ '2025-02-13 00:00:00.000000+00', - 'filing_date'::VARCHAR, - FALSE::BOOLEAN, - DATE '2024-12-31', - 'Q4'::VARCHAR, - 'USD'::VARCHAR, - TIMESTAMPTZ '2025-02-13 00:00:00.000000+00', - 777.0::DOUBLE, - 77.0::DOUBLE, - 77.0::DOUBLE, - 7777.0::DOUBLE, - 3333.0::DOUBLE, - 40.0::DOUBLE, - DATE '2024-12-31', - 'USD'::VARCHAR, - 7777.0::DOUBLE, - 777.0::DOUBLE, - 777.0::DOUBLE, - FALSE::BOOLEAN - ) - ) AS t( - listing_id, effective_known_at, known_at_source, has_estimated_lag, - period_end, fiscal_period, currency, period_known_at, - revenue, net_income, operating_cash_flow, total_assets, total_equity, shares_outstanding, - ttm_period_end, ttm_currency, ttm_revenue, ttm_net_income, ttm_operating_cash_flow, ttm_has_estimated_lag - ) - ) TO '${join(curatedRoot, 'fundamentals_pit', 'year=2025', 'part.parquet')}' (FORMAT PARQUET) - `); - } finally { - await writer.close(); - } - - const opened = await openDuckDbMarketDataStore({ - curatedRoot, - vaultCutoffTs, - env: { - STOCK_BOT_DUCKDB_MEMORY_LIMIT: '2GB', - STOCK_BOT_DUCKDB_THREADS: '2', - STOCK_BOT_DUCKDB_TEMP_DIR: duckTempDir, - }, - }); - - try { - // 1. Before S1: no row for listing 101 - const beforeS1 = await opened.store.fundamentalsAsOf({ - listingIds: [101], - fields: ['revenue', 'ttm_revenue'], - asOf: '2024-04-30T23:59:59Z', - }); - expect(beforeS1.rows).toEqual([]); - - // 2. Between S1 and S2: Q1 row (revenue 100, ttm_revenue 380) - const betweenS1S2 = await opened.store.fundamentalsAsOf({ - listingIds: [101], - fields: ['revenue', 'ttm_revenue'], - asOf: '2024-06-15', - }); - expect(betweenS1S2.rows).toHaveLength(1); - expect(betweenS1S2.rows[0]).toEqual({ - listing_id: 101, - effective_known_at: s1KnownMs, - known_at_source: 'filing_date', - has_estimated_lag: false, - period_end: '2024-03-31', - fiscal_period: 'Q1', - currency: 'USD', - period_known_at: s1KnownMs, - revenue: 100, - ttm_revenue: 380, - ttm_period_end: '2024-03-31', - ttm_currency: 'USD', - ttm_has_estimated_lag: false, - }); - - // 3. Between S2 and S3: Q2 baseline (revenue 120, period_known_at = S2, pre-restatement TTM 420) - const betweenS2S3 = await opened.store.fundamentalsAsOf({ - listingIds: [101], - fields: ['revenue', 'ttm_revenue'], - asOf: '2024-08-15', - }); - expect(betweenS2S3.rows).toHaveLength(1); - expect(betweenS2S3.rows[0]).toEqual({ - listing_id: 101, - effective_known_at: s2KnownMs, - known_at_source: 'filing_date', - has_estimated_lag: false, - period_end: '2024-06-30', - fiscal_period: 'Q2', - currency: 'USD', - period_known_at: s2KnownMs, - revenue: 120, - ttm_revenue: 420, - ttm_period_end: '2024-06-30', - ttm_currency: 'USD', - ttm_has_estimated_lag: false, - }); - - // 4. At and after S3 (Q1 restatement with known_at > Q2): Q2 period_end, revenue, and period_known_at stay fixed while ttm_revenue updates to 415 - for (const asOf of ['2024-09-15T20:00:00Z', '2024-10-01']) { - const afterS3 = await opened.store.fundamentalsAsOf({ - listingIds: [101], - fields: ['revenue', 'ttm_revenue'], - asOf, - }); - expect(afterS3.rows).toHaveLength(1); - expect(afterS3.rows[0]).toEqual({ - listing_id: 101, - effective_known_at: s3KnownMs, - known_at_source: 'filing_date', - has_estimated_lag: false, - period_end: '2024-06-30', - fiscal_period: 'Q2', - currency: 'USD', - period_known_at: s2KnownMs, - revenue: 120, - ttm_revenue: 415, - ttm_period_end: '2024-06-30', - ttm_currency: 'USD', - ttm_has_estimated_lag: false, - }); - } - - // 5. Multi-partition glob (year=2023 + year=2024) sorted by listing_id ASC, with non-TTM projection omitting TTM metadata columns - const multiYear = await opened.store.fundamentalsAsOf({ - listingIds: [101, 50], - fields: ['revenue'], - asOf: '2024-10-01', - }); - expect(multiYear.columns).toEqual([ - 'listing_id', - 'effective_known_at', - 'known_at_source', - 'has_estimated_lag', - 'period_end', - 'fiscal_period', - 'currency', - 'period_known_at', - 'revenue', - ]); - expect(multiYear.rows.map(r => r.listing_id)).toEqual([50, 101]); - expect(multiYear.rows[0]!.period_end).toBe('2023-09-30'); - expect(multiYear.rows[0]!.revenue).toBe(80); - expect(multiYear.rows[1]!.revenue).toBe(120); - - // 6. Vault microsecond fence: last pre-cutoff microsecond is eligible; exact cutoff and post-cutoff are excluded - for (const asOf of ['2025-02-13T00:00:00.000Z', '2025-06-01']) { - const fenced = await opened.store.fundamentalsAsOf({ - listingIds: [103, 102], - fields: ['revenue'], - asOf, - }); - expect(fenced.rows).toHaveLength(1); - expect(fenced.rows[0]!.listing_id).toBe(102); - expect(fenced.rows[0]!.revenue).toBe(210); - expect(fenced.rows[0]!.period_end).toBe('2024-12-31'); - } - - // 7. allowEstimatedLag default (true) vs strict (false): - // - listing 201 (has_estimated_lag = true on latest snapshot) returned by default, omitted in strict mode without falling back to older verified Q1 row - // - listing 202 (has_estimated_lag = false, ttm_has_estimated_lag = true) kept in strict mode with all ttm_* values + ttm_period_end + ttm_currency nulled and ttm_has_estimated_lag preserved - const lagAllowed = await opened.store.fundamentalsAsOf({ - listingIds: [202, 201], - fields: ['revenue', 'ttm_revenue', 'ttm_net_income', 'ttm_operating_cash_flow'], - asOf: '2024-09-01', - }); - expect(lagAllowed.rows.map(r => r.listing_id)).toEqual([201, 202]); - expect(lagAllowed.rows[0]!.revenue).toBe(60); - expect(lagAllowed.rows[0]!.has_estimated_lag).toBe(true); - expect(lagAllowed.rows[1]!.revenue).toBe(75); - expect(lagAllowed.rows[1]!.ttm_revenue).toBe(300); - expect(lagAllowed.rows[1]!.ttm_net_income).toBe(30); - expect(lagAllowed.rows[1]!.ttm_operating_cash_flow).toBe(45); - expect(lagAllowed.rows[1]!.ttm_period_end).toBe('2024-06-30'); - expect(lagAllowed.rows[1]!.ttm_currency).toBe('CAD'); - expect(lagAllowed.rows[1]!.ttm_has_estimated_lag).toBe(true); - - const lagStrict = await opened.store.fundamentalsAsOf({ - listingIds: [202, 201], - fields: ['revenue', 'ttm_revenue', 'ttm_net_income', 'ttm_operating_cash_flow'], - asOf: '2024-09-01', - allowEstimatedLag: false, - }); - expect(lagStrict.rows).toHaveLength(1); - expect(lagStrict.rows[0]).toEqual({ - listing_id: 202, - effective_known_at: s2KnownMs, - known_at_source: 'filing_date', - has_estimated_lag: false, - period_end: '2024-06-30', - fiscal_period: 'Q2', - currency: 'CAD', - period_known_at: s2KnownMs, - revenue: 75, - ttm_revenue: null, - ttm_net_income: null, - ttm_operating_cash_flow: null, - ttm_period_end: null, - ttm_currency: null, - ttm_has_estimated_lag: true, - }); - } finally { - await opened.close(); - } - }); -}); - -interface FundamentalsFixtureRow { - readonly listingId: number; - readonly effectiveKnownAt: string; - readonly hasEstimatedLag?: boolean; - readonly periodEnd: string; - readonly fiscalPeriod: string; - readonly periodKnownAt?: string; - readonly revenue: number | null; - readonly ttmRevenue: number | null; - readonly ttmHasEstimatedLag: boolean | null; -} - -function fundamentalsRowSql(r: FundamentalsFixtureRow): string { - const num = (v: number | null): string => (v === null ? 'NULL::DOUBLE' : `${v}::DOUBLE`); - const bool = (v: boolean | null): string => (v === null ? 'NULL::BOOLEAN' : `${v ? 'TRUE' : 'FALSE'}::BOOLEAN`); - const ttmMissing = r.ttmRevenue === null; - return `( - ${r.listingId}::INTEGER, TIMESTAMPTZ '${r.effectiveKnownAt}', 'filing_date'::VARCHAR, ${bool(r.hasEstimatedLag ?? false)}, - DATE '${r.periodEnd}', '${r.fiscalPeriod}'::VARCHAR, 'USD'::VARCHAR, TIMESTAMPTZ '${r.periodKnownAt ?? r.effectiveKnownAt}', - ${num(r.revenue)}, NULL::DOUBLE, NULL::DOUBLE, NULL::DOUBLE, NULL::DOUBLE, NULL::DOUBLE, - ${ttmMissing ? 'NULL::DATE' : `DATE '${r.periodEnd}'`}, ${ttmMissing ? 'NULL::VARCHAR' : `'USD'::VARCHAR`}, - ${num(r.ttmRevenue)}, NULL::DOUBLE, NULL::DOUBLE, ${bool(r.ttmHasEstimatedLag)} - )`; -} - -async function writeFundamentalsPartition( - curatedRoot: string, - year: number, - rows: readonly FundamentalsFixtureRow[] -): Promise { - const dir = join(curatedRoot, 'fundamentals_pit', `year=${year}`); - await mkdir(dir, { recursive: true }); - const writer = await createNodeDuckDbExecutor(); - try { - await writer.run(` - COPY ( - SELECT * FROM (VALUES ${rows.map(fundamentalsRowSql).join(', ')}) AS t( - listing_id, effective_known_at, known_at_source, has_estimated_lag, - period_end, fiscal_period, currency, period_known_at, - revenue, net_income, operating_cash_flow, total_assets, total_equity, shares_outstanding, - ttm_period_end, ttm_currency, ttm_revenue, ttm_net_income, ttm_operating_cash_flow, ttm_has_estimated_lag - ) - ) TO '${join(dir, 'part.parquet')}' (FORMAT PARQUET) - `); - } finally { - await writer.close(); - } -} - -describe('openDuckDbMarketDataStore fundamentalsAsOf edge cases (@duckdb/node-api)', () => { - async function openFundamentalsStore(): Promise>> { - const root = await mkdtemp(join(tmpdir(), 'stockbot-duckdb-fnd-edge-')); - tempDirs.push(root); - const curatedRoot = join(root, 'curated'); - const duckTempDir = join(root, 'duckdb-tmp'); - await mkdir(duckTempDir, { recursive: true }); - - // Partition directory does not drive ranking: listing 7's newest snapshot sits in - // year=2023 while its older one sits in year=2024; listing 8 is the reverse. - await writeFundamentalsPartition(curatedRoot, 2023, [ - { listingId: 7, effectiveKnownAt: '2024-05-01 12:00:00+00', periodEnd: '2024-03-31', fiscalPeriod: 'Q1', revenue: 70, ttmRevenue: 270, ttmHasEstimatedLag: false }, - { listingId: 8, effectiveKnownAt: '2023-11-01 12:00:00+00', periodEnd: '2023-09-30', fiscalPeriod: 'Q3', revenue: 80, ttmRevenue: 300, ttmHasEstimatedLag: false }, - ]); - await writeFundamentalsPartition(curatedRoot, 2024, [ - { listingId: 7, effectiveKnownAt: '2024-02-15 12:00:00+00', periodEnd: '2023-12-31', fiscalPeriod: 'Q4', revenue: 65, ttmRevenue: 260, ttmHasEstimatedLag: false }, - { listingId: 8, effectiveKnownAt: '2024-02-15 12:00:00+00', periodEnd: '2023-12-31', fiscalPeriod: 'Q4', revenue: 85, ttmRevenue: 310, ttmHasEstimatedLag: false }, - // Sub-millisecond neighbours: only the microsecond distinguishes them. - { listingId: 9, effectiveKnownAt: '2024-03-01 12:00:00.000500+00', periodEnd: '2023-12-31', fiscalPeriod: 'Q4', revenue: 90, ttmRevenue: 360, ttmHasEstimatedLag: false }, - { listingId: 9, effectiveKnownAt: '2024-03-01 12:00:00.000501+00', periodEnd: '2023-12-31', fiscalPeriod: 'Q4', revenue: 91, ttmRevenue: 361, ttmHasEstimatedLag: false }, - // Verified Q1, then estimated Q2. - { listingId: 10, effectiveKnownAt: '2024-05-01 12:00:00+00', periodEnd: '2024-03-31', fiscalPeriod: 'Q1', revenue: 100, ttmRevenue: 400, ttmHasEstimatedLag: false }, - { listingId: 10, effectiveKnownAt: '2024-08-01 12:00:00+00', hasEstimatedLag: true, periodEnd: '2024-06-30', fiscalPeriod: 'Q2', revenue: 110, ttmRevenue: 410, ttmHasEstimatedLag: true }, - // TTM-only estimated lag. - { listingId: 11, effectiveKnownAt: '2024-05-01 12:00:00+00', periodEnd: '2024-03-31', fiscalPeriod: 'Q1', revenue: 111, ttmRevenue: 444, ttmHasEstimatedLag: true }, - // No TTM yet (fewer than four quarters): TTM values and flag are NULL. - { listingId: 12, effectiveKnownAt: '2024-05-01 12:00:00+00', periodEnd: '2024-03-31', fiscalPeriod: 'Q1', revenue: 12, ttmRevenue: null, ttmHasEstimatedLag: null }, - ]); - - return openDuckDbMarketDataStore({ - curatedRoot, - vaultCutoffTs: computeVaultCutoffTs('2025-08-13'), - env: { - STOCK_BOT_DUCKDB_MEMORY_LIMIT: '2GB', - STOCK_BOT_DUCKDB_THREADS: '2', - STOCK_BOT_DUCKDB_TEMP_DIR: duckTempDir, - }, - }); - } - - test('selects the latest effective_known_at across Hive partitions regardless of partition directory', async () => { - const opened = await openFundamentalsStore(); - try { - const result = await opened.store.fundamentalsAsOf({ - listingIds: [8, 7], - fields: ['revenue'], - asOf: '2024-06-01', - }); - expect(result.rows.map(r => [r.listing_id, r.fiscal_period, r.revenue])).toEqual([ - [7, 'Q1', 70], - [8, 'Q4', 85], - ]); - - const earlier = await opened.store.fundamentalsAsOf({ - listingIds: [7, 8], - fields: ['revenue'], - asOf: '2024-01-01', - }); - expect(earlier.rows.map(r => [r.listing_id, r.fiscal_period])).toEqual([[8, 'Q3']]); - } finally { - await opened.close(); - } - }); - - test('binds explicit sub-millisecond asOf so microsecond-adjacent snapshots are separated', async () => { - const opened = await openFundamentalsStore(); - try { - const at = async (asOf: string): Promise => - (await opened.store.fundamentalsAsOf({ listingIds: [9], fields: ['revenue'], asOf })).rows.map( - r => r.revenue - ); - expect(await at('2024-03-01T12:00:00.000499Z')).toEqual([]); - expect(await at('2024-03-01T12:00:00.000500Z')).toEqual([90]); - expect(await at('2024-03-01T14:00:00.000500+02:00')).toEqual([90]); - expect(await at('2024-03-01T12:00:00.000501Z')).toEqual([91]); - } finally { - await opened.close(); - } - }); - - test('strict allowEstimatedLag returns the verified snapshot that was latest at an earlier asOf, and omits the listing once an estimated snapshot is latest', async () => { - const opened = await openFundamentalsStore(); - try { - const beforeEstimate = await opened.store.fundamentalsAsOf({ - listingIds: [10], - fields: ['revenue'], - asOf: '2024-07-31', - allowEstimatedLag: false, - }); - expect(beforeEstimate.rows.map(r => [r.fiscal_period, r.revenue])).toEqual([['Q1', 100]]); - - const afterEstimate = await opened.store.fundamentalsAsOf({ - listingIds: [10], - fields: ['revenue'], - asOf: '2024-08-02', - allowEstimatedLag: false, - }); - expect(afterEstimate.rows).toEqual([]); - } finally { - await opened.close(); - } - }); - - test('strict mode keeps TTM-estimated rows without TTM columns when no ttm_* field is requested, and passes through NULL TTM flags', async () => { - const opened = await openFundamentalsStore(); - try { - const noTtm = await opened.store.fundamentalsAsOf({ - listingIds: [11], - fields: ['revenue'], - asOf: '2024-06-01', - allowEstimatedLag: false, - }); - expect(noTtm.columns).not.toContain('ttm_has_estimated_lag'); - expect(noTtm.rows).toEqual([ - expect.objectContaining({ listing_id: 11, revenue: 111, has_estimated_lag: false }), - ]); - expect(Object.keys(noTtm.rows[0]!)).toEqual(noTtm.columns as string[]); - - const nullTtm = await opened.store.fundamentalsAsOf({ - listingIds: [12, 11], - fields: ['ttm_revenue'], - asOf: '2024-06-01', - allowEstimatedLag: false, - }); - expect(nullTtm.rows.map(r => [r.listing_id, r.ttm_revenue, r.ttm_period_end, r.ttm_currency, r.ttm_has_estimated_lag])).toEqual([ - [11, null, null, null, true], - [12, null, null, null, null], - ]); - } finally { - await opened.close(); - } - }); - - test('returns only requested listings and is reproducible across repeated identical queries', async () => { - const opened = await openFundamentalsStore(); - try { - const q = { - listingIds: [12, 999, 7], - fields: ['ttm_revenue', 'revenue'], - asOf: '2024-09-01T00:00:00.000001Z', - }; - const first = await opened.store.fundamentalsAsOf(q); - const second = await opened.store.fundamentalsAsOf(q); - expect(first.rows.map(r => r.listing_id)).toEqual([7, 12]); - expect(second).toEqual(first); - } finally { - await opened.close(); - } - }); -}); diff --git a/libs/data/duckdb/test/research-copilot-store-qa.test.ts b/libs/data/duckdb/test/research-copilot-store-qa.test.ts deleted file mode 100644 index fc564f4b..00000000 --- a/libs/data/duckdb/test/research-copilot-store-qa.test.ts +++ /dev/null @@ -1,394 +0,0 @@ -import { afterEach, describe, expect, spyOn, test } from 'bun:test'; -import { existsSync } from 'node:fs'; -import { mkdir, mkdtemp, rm } from 'node:fs/promises'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import { DuckDBConnection, DuckDBInstance } from '@duckdb/node-api'; -import { createNodeDuckDbExecutor, openResearchCopilotStore } from '@stock-bot/duckdb'; -import { - MarketDataStoreValidationError, - VaultHoldoutFenceError, - type BarRecord, -} from '@stock-bot/research/market-data-store'; -import { - runResearchCopilotStdioHost, - type PostgresResearchCopilotExecutor, - type QueryDataResultPayload, - type ResearchCopilotHostConfig, - type StdioInput, - type StdioOutput, -} from '@stock-bot/research/mcp'; - -// QA coverage for T-184 beyond the implementation tests: -// - budget env (`STOCKBOT_DUCKDB_*`) is forwarded and reaches DuckDB; -// - invalid budget env fails closed without leaking native handles or the Postgres URL; -// - `openStore: openResearchCopilotStore` works unwrapped (default env resolution); -// - the Vault cutoff comes from `config.vaultCutoffTs` (not a constant); -// - `databasePath` is forwarded. -// Fixture: listing 202, rows at 2025-03-10/11/12 20:00Z (known_at == ts). - -const LISTING_ID = 202; -const DAY1_MS = Date.UTC(2025, 2, 10, 20, 0, 0, 0); -const DAY2_MS = Date.UTC(2025, 2, 11, 20, 0, 0, 0); -const DAY3_MS = Date.UTC(2025, 2, 12, 20, 0, 0, 0); -const FIXED_NOW_MS = Date.UTC(2025, 2, 11, 12, 0, 0, 0); -const PG_SECRET = 'qa_only_fake_pw_7c1e'; -const FAKE_POSTGRES_URL = `postgresql://research_ro:${PG_SECRET}@127.0.0.1:5433/trading_bot_dev`; -const AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555'; - -const tempDirs: string[] = []; -const spies: Array<{ mockRestore(): void }> = []; - -afterEach(async () => { - while (spies.length > 0) { - spies.pop()?.mockRestore(); - } - while (tempDirs.length > 0) { - const dir = tempDirs.pop(); - if (dir !== undefined) { - await rm(dir, { recursive: true, force: true }); - } - } -}); - -function track(spy: T): T { - spies.push(spy); - return spy; -} - -function bar(ts: number, base: number): BarRecord { - return { - listingId: LISTING_ID, - ts, - open: base, - high: base + 1, - low: base - 1, - close: base + 0.5, - volume: 1000 * base, - vwap: base + 0.25, - knownAt: ts, - }; -} - -const BAR1 = bar(DAY1_MS, 10); -const BAR2 = bar(DAY2_MS, 20); -const BAR3 = bar(DAY3_MS, 30); - -function config(curatedRoot: string, vaultCutoffTs: number): ResearchCopilotHostConfig { - return { - postgresUrl: FAKE_POSTGRES_URL, - curatedRoot, - vaultCutoffTs, - principalId: AGENT_PRINCIPAL, - libraryRoot: '/tmp/unused-library-root', - referenceListingIds: { XNYS: [LISTING_ID] }, - }; -} - -async function makeRoot(): Promise { - const root = await mkdtemp(join(tmpdir(), 'stockbot-t184-qa-')); - tempDirs.push(root); - return root; -} - -function utcTs(ms: number): string { - return `${new Date(ms).toISOString().slice(0, 19).replace('T', ' ')}+00`; -} - -function utcDate(ms: number): string { - return new Date(ms).toISOString().slice(0, 10); -} - -async function writeFixture(root: string): Promise { - const curatedRoot = join(root, 'curated'); - await mkdir(join(curatedRoot, 'bars_1d', 'year=2025'), { recursive: true }); - const rows = [BAR1, BAR2, BAR3] - .map( - b => - // Explicit UTC literals: casting naive timestamps to TIMESTAMPTZ would use the host TimeZone. - `(${LISTING_ID}::INTEGER, DATE '${utcDate(b.ts)}', TIMESTAMPTZ '${utcTs(b.ts)}', ${b.open}::DOUBLE, ${b.high}::DOUBLE, ${b.low}::DOUBLE, ${b.close}::DOUBLE, ${b.volume}::DOUBLE, ${b.vwap}::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '${utcTs(b.knownAt)}')` - ) - .join(',\n'); - const writer = await createNodeDuckDbExecutor(); - try { - await writer.run(` - COPY ( - SELECT * FROM (VALUES ${rows}) - AS t(listing_id, session_date, ts, open, high, low, close, volume, vwap, currency, known_at) - ) TO '${join(curatedRoot, 'bars_1d', 'year=2025', 'part.parquet')}' (FORMAT PARQUET) - `); - } finally { - await writer.close(); - } - return curatedRoot; -} - -async function collect( - iterable: AsyncIterable<{ readonly rows: readonly BarRecord[] }> -): Promise { - const out: BarRecord[] = []; - for await (const batch of iterable) { - out.push(...batch.rows); - } - return out; -} - -async function captureError(fn: () => Promise): Promise { - try { - await fn(); - } catch (err) { - return err; - } - return undefined; -} - -function fullRangeQuery() { - return { - listingIds: [LISTING_ID], - timeframe: '1d' as const, - from: '2025-03-01', - to: '2025-03-31', - asOf: '2025-03-31', - adjustment: 'raw' as const, - }; -} - -function memoryStdio(messages: readonly unknown[]): { - readonly input: StdioInput; - readonly output: StdioOutput; - raw(): string; -} { - const chunks: string[] = []; - return { - input: { - async *[Symbol.asyncIterator]() { - for (const m of messages) { - yield `${JSON.stringify(m)}\n`; - } - }, - }, - output: { - write(chunk: string): boolean { - chunks.push(chunk); - return true; - }, - }, - raw: () => chunks.join(''), - }; -} - -function fakePg(): { executor: PostgresResearchCopilotExecutor; calls: number } { - const state = { - calls: 0, - executor: { - async query>(): Promise<{ readonly rows: readonly Row[] }> { - state.calls += 1; - return { rows: [] }; - }, - } as PostgresResearchCopilotExecutor, - }; - return state; -} - -function hostMessages(): unknown[] { - return [ - { - jsonrpc: '2.0', - id: 1, - method: 'initialize', - params: { - protocolVersion: '2024-11-05', - capabilities: {}, - clientInfo: { name: 't184-qa', version: '1.0.0' }, - }, - }, - { jsonrpc: '2.0', method: 'notifications/initialized' }, - { - jsonrpc: '2.0', - id: 2, - method: 'tools/call', - params: { - name: 'query_data', - arguments: { - listingIds: [LISTING_ID], - from: '2025-03-01', - to: '2025-03-31', - asOf: '2025-03-31', - }, - }, - }, - ]; -} - -describe('openResearchCopilotStore QA (T-184)', () => { - test('uses config.vaultCutoffTs as the only cutoff: moving the cutoff moves the visible rows', async () => { - const curatedRoot = await writeFixture(await makeRoot()); - - // Cutoff exactly at DAY2 ts: DAY2 (ts == cutoff) is excluded, only DAY1 visible. - const atDay2 = await openResearchCopilotStore(config(curatedRoot, DAY2_MS)); - try { - expect(await collect(atDay2.store.bars(fullRangeQuery()))).toEqual([BAR1]); - } finally { - await atDay2.close(); - } - - // Cutoff 1ms after DAY2: DAY1 + DAY2 visible, DAY3 still fenced. - const afterDay2 = await openResearchCopilotStore(config(curatedRoot, DAY2_MS + 1)); - try { - expect(await collect(afterDay2.store.bars(fullRangeQuery()))).toEqual([BAR1, BAR2]); - const err = await captureError(() => - collect(afterDay2.store.bars({ ...fullRangeQuery(), from: '2025-03-12' })) - ); - expect(err).toBeInstanceOf(VaultHoldoutFenceError); - } finally { - await afterDay2.close(); - } - - // Cutoff after all rows: everything visible (proves no hidden constant cutoff). - const late = await openResearchCopilotStore(config(curatedRoot, Date.UTC(2025, 5, 1))); - try { - expect(await collect(late.store.bars(fullRangeQuery()))).toEqual([BAR1, BAR2, BAR3]); - } finally { - await late.close(); - } - }); - - test('forwards STOCKBOT_DUCKDB_* budget env so DuckDB receives the configured spill directory, threads and memory limit', async () => { - const root = await makeRoot(); - const curatedRoot = await writeFixture(root); - const spillDir = join(root, 'spill'); - await mkdir(spillDir, { recursive: true }); - - const runSpy = track(spyOn(DuckDBConnection.prototype, 'run')); - const handle = await openResearchCopilotStore(config(curatedRoot, DAY2_MS), { - env: { - STOCKBOT_DUCKDB_MEMORY_LIMIT: '512MB', - STOCKBOT_DUCKDB_THREADS: '1', - STOCKBOT_DUCKDB_TEMP_DIRECTORY: spillDir, - }, - }); - try { - expect(await collect(handle.store.bars(fullRangeQuery()))).toEqual([BAR1]); - } finally { - await handle.close(); - } - - const statements = runSpy.mock.calls.map(call => String(call[0])); - expect(statements).toContain(`SET temp_directory = '${spillDir}';`); - expect(statements).toContain('SET threads = 1;'); - expect(statements).toContain("SET memory_limit = '512MB';"); - }); - - test('invalid budget env fails closed: open rejects, native connection and instance closed once, no Postgres URL in the error', async () => { - const curatedRoot = await writeFixture(await makeRoot()); - const connClose = track(spyOn(DuckDBConnection.prototype, 'closeSync')); - const instClose = track(spyOn(DuckDBInstance.prototype, 'closeSync')); - - const err = await captureError(() => - openResearchCopilotStore(config(curatedRoot, DAY2_MS), { - env: { STOCKBOT_DUCKDB_THREADS: 'not-a-number' }, - }) - ); - - expect(err).toBeInstanceOf(MarketDataStoreValidationError); - expect(connClose).toHaveBeenCalledTimes(1); - expect(instClose).toHaveBeenCalledTimes(1); - const text = `${(err as Error).message} ${(err as Error).stack ?? ''}`; - expect(text).not.toContain(PG_SECRET); - expect(text).not.toContain('postgresql://'); - }); - - test('forwards databasePath: a file-backed DuckDB database is created at the given path', async () => { - const root = await makeRoot(); - const curatedRoot = await writeFixture(root); - const dbPath = join(root, 'copilot.duckdb'); - expect(existsSync(dbPath)).toBe(false); - - const handle = await openResearchCopilotStore(config(curatedRoot, DAY2_MS), { - databasePath: dbPath, - }); - try { - expect(existsSync(dbPath)).toBe(true); - expect(await collect(handle.store.bars(fullRangeQuery()))).toEqual([BAR1]); - } finally { - await handle.close(); - } - }); - - test('host wired with openStore: openResearchCopilotStore (unwrapped, default env) serves query_data fenced at config cutoff and closes DuckDB once', async () => { - const curatedRoot = await writeFixture(await makeRoot()); - const pg = fakePg(); - const io = memoryStdio(hostMessages()); - const connClose = track(spyOn(DuckDBConnection.prototype, 'closeSync')); - const instClose = track(spyOn(DuckDBInstance.prototype, 'closeSync')); - - await runResearchCopilotStdioHost({ - config: config(curatedRoot, DAY2_MS + 1), - openExecutor: async () => ({ executor: pg.executor, close: async () => {} }), - openStore: openResearchCopilotStore, - createLibraryCardReader: async () => ({ listLibraryCards: async () => [] }), - newId: () => 'qa-id', - now: () => FIXED_NOW_MS, - stdio: { input: io.input, output: io.output }, - }); - - const lines = io - .raw() - .trimEnd() - .split('\n') - .map(l => JSON.parse(l) as { id: number; result: Record }); - expect(lines.map(l => l.id)).toEqual([1, 2]); - const envelope = lines[1]!.result as { - isError?: boolean; - content: Array<{ text: string }>; - }; - expect(envelope.isError).toBeUndefined(); - const payload = JSON.parse(envelope.content[0]!.text) as QueryDataResultPayload; - expect(payload.vaultCutoffTs).toBe(DAY2_MS + 1); - expect(payload.toMs).toBe(DAY2_MS); - expect(payload.rows).toEqual([BAR1, BAR2]); - expect(io.raw()).not.toContain(PG_SECRET); - expect(pg.calls).toBe(0); - expect(connClose).toHaveBeenCalledTimes(1); - expect(instClose).toHaveBeenCalledTimes(1); - }); - - test('host with empty curatedRoot: query_data fails without hanging, leaks no Postgres URL, and DuckDB still closes once at EOF', async () => { - const root = await makeRoot(); - const emptyRoot = join(root, 'curated'); - await mkdir(emptyRoot, { recursive: true }); - const io = memoryStdio(hostMessages()); - const connClose = track(spyOn(DuckDBConnection.prototype, 'closeSync')); - const instClose = track(spyOn(DuckDBInstance.prototype, 'closeSync')); - - await runResearchCopilotStdioHost({ - config: config(emptyRoot, DAY2_MS), - openExecutor: async () => ({ executor: fakePg().executor, close: async () => {} }), - openStore: openResearchCopilotStore, - createLibraryCardReader: async () => ({ listLibraryCards: async () => [] }), - newId: () => 'qa-id', - now: () => FIXED_NOW_MS, - stdio: { input: io.input, output: io.output }, - }); - - const lines = io - .raw() - .trimEnd() - .split('\n') - .map( - l => - JSON.parse(l) as { - id: number; - result?: { isError?: boolean; content?: Array<{ text: string }> }; - error?: unknown; - } - ); - const toolResponse = lines.find(l => l.id === 2); - expect(toolResponse).toBeDefined(); - const failed = toolResponse!.error !== undefined || toolResponse!.result?.isError === true; - expect(failed).toBe(true); - expect(io.raw()).not.toContain(PG_SECRET); - expect(connClose).toHaveBeenCalledTimes(1); - expect(instClose).toHaveBeenCalledTimes(1); - }); -}); diff --git a/libs/data/duckdb/test/research-copilot-store.test.ts b/libs/data/duckdb/test/research-copilot-store.test.ts deleted file mode 100644 index 2c1acc40..00000000 --- a/libs/data/duckdb/test/research-copilot-store.test.ts +++ /dev/null @@ -1,530 +0,0 @@ -import { afterEach, describe, expect, spyOn, test } from 'bun:test'; -import { readFileSync } from 'node:fs'; -import { mkdir, mkdtemp, rm } from 'node:fs/promises'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import { DuckDBConnection, DuckDBInstance } from '@duckdb/node-api'; -import { - createNodeDuckDbExecutor, - openResearchCopilotStore, -} from '@stock-bot/duckdb'; -import { - MarketDataStoreValidationError, - VaultHoldoutFenceError, - VaultScopeNotAuthorizedError, - type BarRecord, -} from '@stock-bot/research/market-data-store'; -import { - RESEARCH_COPILOT_HOST_NAME, - RESEARCH_COPILOT_HOST_VERSION, - runResearchCopilotStdioHost, - type PostgresResearchCopilotExecutor, - type QueryDataResultPayload, - type ResearchCopilotHostConfig, - type ResearchCopilotStdioHostDeps, - type StdioInput, - type StdioOutput, -} from '@stock-bot/research/mcp'; - -// Pinned synthetic fixture for T-184 (real-DuckDB store factory & stdio host wiring): -// - Listing 101 (USD), Vault cutoff 2025-06-01T00:00:00.000Z -// - Baseline visible row: 2025-05-30 20:00:00Z (known_at 2025-05-30 20:00:00Z) -// - Excluded rows: -// * at-cutoff ts: 2025-06-01 00:00:00Z (known_at 2025-05-30 20:00:00Z) -// * post-cutoff ts: 2025-06-02 20:00:00Z (known_at 2025-06-02 20:00:00Z) -// * late-known pre-cutoff ts: 2025-05-29 20:00:00Z (known_at 2025-06-01 00:00:00Z) - -const LISTING_ID = 101; -const VAULT_CUTOFF_MS = Date.UTC(2025, 5, 1, 0, 0, 0, 0); -const FIXED_NOW_MS = Date.UTC(2025, 4, 31, 12, 0, 0, 0); -const FAKE_POSTGRES_URL = - 'postgresql://research_ro:test_only_not_a_real_secret@127.0.0.1:5433/trading_bot_dev?sslmode=disable'; -const VALID_AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555'; - -const EXPECTED_VISIBLE_BAR: BarRecord = { - listingId: LISTING_ID, - ts: Date.UTC(2025, 4, 30, 20, 0, 0, 0), - open: 100.5, - high: 102.25, - low: 99.75, - close: 101.5, - volume: 123_456, - vwap: 101.1, - knownAt: Date.UTC(2025, 4, 30, 20, 0, 0, 0), -}; - -const tempDirs: string[] = []; -const activeSpies: Array<{ mockRestore(): void }> = []; - -function trackSpy(spy: T): T { - activeSpies.push(spy); - return spy; -} - -afterEach(async () => { - while (activeSpies.length > 0) { - activeSpies.pop()?.mockRestore(); - } - while (tempDirs.length > 0) { - const dir = tempDirs.pop(); - if (dir !== undefined) { - await rm(dir, { recursive: true, force: true }); - } - } -}); - -function buildHostConfig( - curatedRoot: string, - overrides: Partial = {} -): ResearchCopilotHostConfig { - return { - postgresUrl: FAKE_POSTGRES_URL, - curatedRoot, - vaultCutoffTs: VAULT_CUTOFF_MS, - principalId: VALID_AGENT_PRINCIPAL, - libraryRoot: '/tmp/unused-library-root', - referenceListingIds: { XNYS: [LISTING_ID] }, - ...overrides, - }; -} - -function buildDuckDbBudgetEnv(duckTempDir: string): Readonly> { - return { - STOCKBOT_DUCKDB_MEMORY_LIMIT: '2GB', - STOCKBOT_DUCKDB_THREADS: '2', - STOCKBOT_DUCKDB_TEMP_DIRECTORY: duckTempDir, - }; -} - -async function buildBarsFixture(): Promise<{ - readonly curatedRoot: string; - readonly duckTempDir: string; -}> { - const root = await mkdtemp(join(tmpdir(), 'stockbot-mcp-duckdb-')); - tempDirs.push(root); - const curatedRoot = join(root, 'curated'); - const duckTempDir = join(root, 'duckdb-tmp'); - - await mkdir(join(curatedRoot, 'bars_1d', 'year=2025'), { recursive: true }); - await mkdir(duckTempDir, { recursive: true }); - - const writer = await createNodeDuckDbExecutor(); - try { - await writer.run(` - COPY ( - SELECT * FROM (VALUES - (${LISTING_ID}::INTEGER, DATE '2025-05-29', TIMESTAMPTZ '2025-05-29 20:00:00+00', 94.0::DOUBLE, 96.0::DOUBLE, 93.5::DOUBLE, 95.0::DOUBLE, 80000.0::DOUBLE, 94.8::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-06-01 00:00:00+00'), - (${LISTING_ID}::INTEGER, DATE '2025-05-30', TIMESTAMPTZ '2025-05-30 20:00:00+00', 100.5::DOUBLE, 102.25::DOUBLE, 99.75::DOUBLE, 101.5::DOUBLE, 123456.0::DOUBLE, 101.1::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-05-30 20:00:00+00'), - (${LISTING_ID}::INTEGER, DATE '2025-06-01', TIMESTAMPTZ '2025-06-01 00:00:00+00', 199.0::DOUBLE, 201.0::DOUBLE, 198.0::DOUBLE, 200.0::DOUBLE, 200000.0::DOUBLE, 199.5::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-05-30 20:00:00+00'), - (${LISTING_ID}::INTEGER, DATE '2025-06-02', TIMESTAMPTZ '2025-06-02 20:00:00+00', 299.0::DOUBLE, 301.0::DOUBLE, 298.0::DOUBLE, 300.0::DOUBLE, 300000.0::DOUBLE, 299.5::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-06-02 20:00:00+00') - ) AS t(listing_id, session_date, ts, open, high, low, close, volume, vwap, currency, known_at) - ) TO '${join(curatedRoot, 'bars_1d', 'year=2025', 'part.parquet')}' (FORMAT PARQUET) - `); - } finally { - await writer.close(); - } - - return { curatedRoot, duckTempDir }; -} - -function createMemoryOutput(): { - readonly output: StdioOutput; - jsonLines(): unknown[]; -} { - const chunks: string[] = []; - const output: StdioOutput = { - write(chunk: string): boolean { - chunks.push(chunk); - return true; - }, - }; - return { - output, - jsonLines: () => { - const raw = chunks.join(''); - if (raw.length === 0) { - return []; - } - return raw - .trimEnd() - .split('\n') - .map(line => JSON.parse(line) as unknown); - }, - }; -} - -function createMemoryInput(messages: readonly unknown[]): StdioInput { - return { - async *[Symbol.asyncIterator]() { - for (const msg of messages) { - yield `${JSON.stringify(msg)}\n`; - } - }, - }; -} - -function createFakePostgresExecutor(): { - readonly executor: PostgresResearchCopilotExecutor; - readonly calls: Array<{ readonly text: string; readonly params: readonly unknown[] | undefined }>; -} { - const calls: Array<{ readonly text: string; readonly params: readonly unknown[] | undefined }> = []; - const executor: PostgresResearchCopilotExecutor = { - async query>( - text: string, - params?: readonly unknown[] - ): Promise<{ readonly rows: readonly Row[] }> { - calls.push({ text, params }); - return { rows: [] }; - }, - }; - return { executor, calls }; -} - -async function collectBars( - iterable: AsyncIterable<{ readonly rows: readonly BarRecord[] }> -): Promise { - const rows: BarRecord[] = []; - for await (const batch of iterable) { - rows.push(...batch.rows); - } - return rows; -} - -describe('openResearchCopilotStore (@duckdb/node-api)', () => { - test('source invariants: no pg import, no process.env read, no console logging, always vault-fenced', () => { - const sourcePath = join(import.meta.dir, '..', 'src', 'research-copilot-store.ts'); - const source = readFileSync(sourcePath, 'utf8'); - - expect(source).not.toMatch(/from\s+['"]pg['"]/); - expect(source).not.toMatch(/require\(\s*['"]pg['"]\s*\)/); - expect(source).not.toContain('process.env'); - expect(source).not.toMatch(/\bprocess\b/); - expect(source).not.toContain('console.'); - expect(source).toContain('vaultOperatorAuthorized: false'); - - // Verify typed assignability to ResearchCopilotStdioHostDeps['openStore'] without casts. - const directFactory: ResearchCopilotStdioHostDeps['openStore'] = openResearchCopilotStore; - const wrappedFactory: ResearchCopilotStdioHostDeps['openStore'] = cfg => - openResearchCopilotStore(cfg); - expect(typeof directFactory).toBe('function'); - expect(typeof wrappedFactory).toBe('function'); - }); - - test('enforces single Vault cutoff directly on store.bars(), replays identically, and blocks vault_evaluation_only even for operator principal', async () => { - const { curatedRoot, duckTempDir } = await buildBarsFixture(); - const config = buildHostConfig(curatedRoot, { principalId: 'operator' }); - - const handle = await openResearchCopilotStore(config, { - env: buildDuckDbBudgetEnv(duckTempDir), - }); - - try { - expect(Object.keys(handle).sort()).toEqual(['close', 'store']); - - // Straddling query: to and asOf exceed cutoff -> only visible pre-cutoff row returned. - const firstRun = await collectBars( - handle.store.bars({ - listingIds: [LISTING_ID], - timeframe: '1d', - from: '2025-05-28', - to: '2025-06-05', - asOf: '2025-06-05', - adjustment: 'raw', - }) - ); - expect(firstRun).toEqual([EXPECTED_VISIBLE_BAR]); - - // Replay produces identical results. - const replayRun = await collectBars( - handle.store.bars({ - listingIds: [LISTING_ID], - timeframe: '1d', - from: '2025-05-28', - to: '2025-06-05', - asOf: '2025-06-05', - adjustment: 'raw', - }) - ); - expect(replayRun).toEqual(firstRun); - - // Query starting at cutoff throws VaultHoldoutFenceError. - let atCutoffErr: unknown; - try { - await collectBars( - handle.store.bars({ - listingIds: [LISTING_ID], - timeframe: '1d', - from: '2025-06-01', - to: '2025-06-05', - adjustment: 'raw', - }) - ); - } catch (err) { - atCutoffErr = err; - } - expect(atCutoffErr).toBeInstanceOf(VaultHoldoutFenceError); - - // Query starting after cutoff throws VaultHoldoutFenceError. - let afterCutoffErr: unknown; - try { - await collectBars( - handle.store.bars({ - listingIds: [LISTING_ID], - timeframe: '1d', - from: '2025-06-02', - to: '2025-06-05', - adjustment: 'raw', - }) - ); - } catch (err) { - afterCutoffErr = err; - } - expect(afterCutoffErr).toBeInstanceOf(VaultHoldoutFenceError); - - // vault_evaluation_only is always rejected even when config.principalId is 'operator'. - let scopeErr: unknown; - try { - await collectBars( - handle.store.bars({ - listingIds: [LISTING_ID], - timeframe: '1d', - from: '2025-05-28', - to: '2025-06-05', - adjustment: 'raw', - scope: 'vault_evaluation_only', - }) - ); - } catch (err) { - scopeErr = err; - } - expect(scopeErr).toBeInstanceOf(VaultScopeNotAuthorizedError); - } finally { - await handle.close(); - } - }); - - test('wires into runResearchCopilotStdioHost end-to-end, serves initialize + query_data, and closes DuckDB exactly once at EOF', async () => { - const { curatedRoot, duckTempDir } = await buildBarsFixture(); - const config = buildHostConfig(curatedRoot); - const fakePg = createFakePostgresExecutor(); - const sink = createMemoryOutput(); - const input = createMemoryInput([ - { - jsonrpc: '2.0', - id: 1, - method: 'initialize', - params: { - protocolVersion: '2024-11-05', - capabilities: {}, - clientInfo: { name: 'duckdb-host-test', version: '1.0.0' }, - }, - }, - { - jsonrpc: '2.0', - method: 'notifications/initialized', - }, - { - jsonrpc: '2.0', - id: 2, - method: 'tools/call', - params: { - name: 'query_data', - arguments: { - listingIds: [LISTING_ID], - from: '2025-05-28', - to: '2025-06-05', - asOf: '2025-06-05', - }, - }, - }, - ]); - - // Install call-through spies after fixture writer is closed so counts reflect only the host store. - const connCloseSpy = trackSpy(spyOn(DuckDBConnection.prototype, 'closeSync')); - const instCloseSpy = trackSpy(spyOn(DuckDBInstance.prototype, 'closeSync')); - - let capturedStore: Awaited>['store'] | undefined; - - await runResearchCopilotStdioHost({ - config, - openExecutor: async () => ({ - executor: fakePg.executor, - close: async () => {}, - }), - openStore: async cfg => { - const opened = await openResearchCopilotStore(cfg, { - env: buildDuckDbBudgetEnv(duckTempDir), - }); - capturedStore = opened.store; - return opened; - }, - createLibraryCardReader: async () => ({ - listLibraryCards: async () => [], - }), - newId: () => 'id-1', - now: () => FIXED_NOW_MS, - stdio: { input, output: sink.output }, - }); - - const responses = sink.jsonLines() as Array<{ - readonly id: number; - readonly result: Record; - }>; - expect(responses).toHaveLength(2); - - expect(responses[0]!.id).toBe(1); - expect(responses[0]!.result.serverInfo).toEqual({ - name: RESEARCH_COPILOT_HOST_NAME, - version: RESEARCH_COPILOT_HOST_VERSION, - }); - - expect(responses[1]!.id).toBe(2); - const toolEnvelope = responses[1]!.result as { - readonly isError?: boolean; - readonly content: ReadonlyArray<{ readonly type: 'text'; readonly text: string }>; - }; - expect(toolEnvelope.isError).toBeUndefined(); - - const payload = JSON.parse(toolEnvelope.content[0]!.text) as QueryDataResultPayload; - expect(payload.vaultCutoffTs).toBe(VAULT_CUTOFF_MS); - expect(payload.clampedTo).toBe(true); - expect(payload.clampedAsOf).toBe(true); - expect(payload.toMs).toBe(VAULT_CUTOFF_MS - 1); - expect(payload.asOfMs).toBe(VAULT_CUTOFF_MS - 1); - expect(payload.rows).toEqual([EXPECTED_VISIBLE_BAR]); - - expect(fakePg.calls).toHaveLength(0); - expect(connCloseSpy).toHaveBeenCalledTimes(1); - expect(instCloseSpy).toHaveBeenCalledTimes(1); - - // Confirm the host-opened store rejects subsequent queries after EOF cleanup. - expect(capturedStore).toBeDefined(); - let postCloseErr: unknown; - try { - await collectBars( - capturedStore!.bars({ - listingIds: [LISTING_ID], - timeframe: '1d', - from: '2025-05-28', - to: '2025-05-31', - adjustment: 'raw', - }) - ); - } catch (err) { - postCloseErr = err; - } - expect(postCloseErr).toBeInstanceOf(Error); - expect((postCloseErr as Error).message).toContain('closed'); - }); - - test('directly opened handle resolves close() and rejects subsequent valid bars() queries', async () => { - const { curatedRoot, duckTempDir } = await buildBarsFixture(); - const config = buildHostConfig(curatedRoot); - - const connCloseSpy = trackSpy(spyOn(DuckDBConnection.prototype, 'closeSync')); - const instCloseSpy = trackSpy(spyOn(DuckDBInstance.prototype, 'closeSync')); - - const handle = await openResearchCopilotStore(config, { - env: buildDuckDbBudgetEnv(duckTempDir), - }); - - await handle.close(); - await handle.close(); - - expect(connCloseSpy).toHaveBeenCalledTimes(1); - expect(instCloseSpy).toHaveBeenCalledTimes(1); - - let postCloseErr: unknown; - try { - await collectBars( - handle.store.bars({ - listingIds: [LISTING_ID], - timeframe: '1d', - from: '2025-05-28', - to: '2025-05-31', - adjustment: 'raw', - }) - ); - } catch (err) { - postCloseErr = err; - } - expect(postCloseErr).toBeInstanceOf(Error); - expect((postCloseErr as Error).message).toContain('closed'); - }); - - test('fail-closed: empty curatedRoot rejects on first bars() read and closes cleanly in finally', async () => { - const root = await mkdtemp(join(tmpdir(), 'stockbot-mcp-empty-')); - tempDirs.push(root); - const emptyCuratedRoot = join(root, 'curated'); - const duckTempDir = join(root, 'duckdb-tmp'); - await mkdir(emptyCuratedRoot, { recursive: true }); - await mkdir(duckTempDir, { recursive: true }); - - const connCloseSpy = trackSpy(spyOn(DuckDBConnection.prototype, 'closeSync')); - const instCloseSpy = trackSpy(spyOn(DuckDBInstance.prototype, 'closeSync')); - - const handle = await openResearchCopilotStore(buildHostConfig(emptyCuratedRoot), { - env: buildDuckDbBudgetEnv(duckTempDir), - }); - - let readErr: unknown; - try { - await collectBars( - handle.store.bars({ - listingIds: [LISTING_ID], - timeframe: '1d', - from: '2025-05-28', - to: '2025-05-31', - adjustment: 'raw', - }) - ); - } catch (err) { - readErr = err; - } finally { - await handle.close(); - } - - expect(readErr).toBeInstanceOf(Error); - expect(connCloseSpy).toHaveBeenCalledTimes(1); - expect(instCloseSpy).toHaveBeenCalledTimes(1); - }); - - test('fail-closed: invalid relative curatedRoot closes acquired connection and instance before rejecting', async () => { - const connCloseSpy = trackSpy(spyOn(DuckDBConnection.prototype, 'closeSync')); - const instCloseSpy = trackSpy(spyOn(DuckDBInstance.prototype, 'closeSync')); - - let openErr: unknown; - try { - await openResearchCopilotStore(buildHostConfig('relative/curated/root')); - } catch (err) { - openErr = err; - } - - expect(openErr).toBeInstanceOf(MarketDataStoreValidationError); - expect(connCloseSpy).toHaveBeenCalledTimes(1); - expect(instCloseSpy).toHaveBeenCalledTimes(1); - }); - - test('fail-closed: rejected native instance.connect() closes allocated DuckDBInstance before propagating error', async () => { - const connectFailure = new Error('simulated native connect failure'); - const connCloseSpy = trackSpy(spyOn(DuckDBConnection.prototype, 'closeSync')); - const instCloseSpy = trackSpy(spyOn(DuckDBInstance.prototype, 'closeSync')); - const connectSpy = trackSpy( - spyOn(DuckDBInstance.prototype, 'connect').mockImplementationOnce(async () => { - throw connectFailure; - }) - ); - - let openErr: unknown; - try { - await openResearchCopilotStore(buildHostConfig('/tmp/unused-curated-root')); - } catch (err) { - openErr = err; - } - - expect(openErr).toBe(connectFailure); - expect(connectSpy).toHaveBeenCalledTimes(1); - expect(connCloseSpy).toHaveBeenCalledTimes(0); - expect(instCloseSpy).toHaveBeenCalledTimes(1); - }); -}); diff --git a/libs/data/duckdb/tsconfig.json b/libs/data/duckdb/tsconfig.json deleted file mode 100644 index 49cb7b59..00000000 --- a/libs/data/duckdb/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "extends": "../../../tsconfig.json", - "compilerOptions": { - "outDir": "./dist", - "rootDir": "./src", - "composite": true - }, - "include": ["src/**/*"], - "references": [ - { - "path": "../../research" - } - ] -} diff --git a/libs/data/postgres/src/index.ts b/libs/data/postgres/src/index.ts index de560c90..eadd1545 100644 --- a/libs/data/postgres/src/index.ts +++ b/libs/data/postgres/src/index.ts @@ -1,21 +1,6 @@ export { PostgreSQLClient } from './client'; export { PostgreSQLTransactionManager } from './transactions'; export { runPostgresMigrations, type MigrationTrack } from './migrations'; -export { - RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS, - RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS, - RESEARCH_COPILOT_PG_POOL_MAX, - RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS, - RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS, - ResearchCopilotExecutorError, - openResearchCopilotExecutor, - type ManagedResearchCopilotExecutor, - type ResearchCopilotExecutor, - type ResearchCopilotExecutorConfig, - type ResearchCopilotExecutorDeps, - type ResearchCopilotExecutorErrorCode, - type ResearchCopilotExecutorPool, -} from './research-copilot-executor'; export type { ConnectionEvents, PoolMetrics, diff --git a/libs/data/postgres/src/migrations.ts b/libs/data/postgres/src/migrations.ts index 1fa68e3c..1f05331a 100644 --- a/libs/data/postgres/src/migrations.ts +++ b/libs/data/postgres/src/migrations.ts @@ -45,7 +45,6 @@ const RESEARCH_FILES = new Set([ '32-candidate-parameter-defaults.sql', '33-candidate-decimal-normalization.sql', '36-trial-ledger.sql', - '37-research-findings.sql', ]); function locateMigrationsDir(): string { diff --git a/libs/data/postgres/src/research-copilot-executor.ts b/libs/data/postgres/src/research-copilot-executor.ts deleted file mode 100644 index cd55c3b7..00000000 --- a/libs/data/postgres/src/research-copilot-executor.ts +++ /dev/null @@ -1,379 +0,0 @@ -/** - * Real PostgreSQL executor factory for the MCP research copilot stdio host. - * - * Opens a bounded `pg.Pool` (`max: 4`, 5 s connect timeout, 10 s statement - * timeout, 15 s driver query timeout, 2 s lock timeout), verifies connectivity - * with a single `SELECT 1` probe, attaches an idle-client `'error'` listener, - * and returns a managed `{ executor, close }` handle structurally assignable - * to `ManagedPostgresExecutor` in `@stock-bot/research/mcp` without importing - * `@stock-bot/research` at runtime. - * - * All errors thrown by this module are {@link ResearchCopilotExecutorError} - * instances with fixed, sanitized messages and no `cause`, so connection - * strings, credentials, hostnames, and raw `pg` error text never leak. - * PostgreSQL unique-violation SQLSTATE `'23505'` is preserved on sanitized - * query errors for `createPostgresFindingWritePort` idempotent retries. - */ - -import { Pool, type PoolConfig } from 'pg'; - -/** Maximum number of PostgreSQL connections in the copilot executor pool. */ -export const RESEARCH_COPILOT_PG_POOL_MAX = 4; - -/** TCP/startup connection timeout in milliseconds. */ -export const RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS = 5_000; - -/** Server-side PostgreSQL `statement_timeout` in milliseconds. */ -export const RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS = 10_000; - -/** Driver-side `pg` `query_timeout` in milliseconds. */ -export const RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS = 15_000; - -/** Server-side PostgreSQL `lock_timeout` in milliseconds. */ -export const RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS = 2_000; - -/** Typed error codes emitted by {@link ResearchCopilotExecutorError}. */ -export type ResearchCopilotExecutorErrorCode = - | 'INVALID_CONFIG' - | 'OPEN_FAILED' - | 'QUERY_FAILED' - | 'EXECUTOR_CLOSED' - | 'CLOSE_FAILED' - | '23505'; - -const ERROR_MESSAGES: Readonly> = { - INVALID_CONFIG: - 'Invalid PostgreSQL configuration: expected a postgres:// or postgresql:// URL with an explicit host and database.', - OPEN_FAILED: 'Failed to open PostgreSQL executor for research copilot.', - QUERY_FAILED: 'PostgreSQL query failed in research copilot executor.', - EXECUTOR_CLOSED: 'Research copilot PostgreSQL executor is closed.', - CLOSE_FAILED: 'Failed to close PostgreSQL executor for research copilot.', - '23505': 'PostgreSQL unique constraint violation in research copilot executor.', -}; - -const STRIPPED_TIMEOUT_PARAMS: ReadonlySet = new Set([ - 'statement_timeout', - 'lock_timeout', - 'query_timeout', - 'connect_timeout', - 'connectiontimeoutmillis', -]); - -const POSTGRES_URL_PREFIX_RE = /^postgres(?:ql)?:\/\//i; -const PORT_DIGITS_RE = /^\d+$/; -const CONTROL_CHAR_RE = /[\r\n\0]/; - -/** - * Sanitized error thrown by {@link openResearchCopilotExecutor} and the - * managed executor it returns. Never attaches a raw `cause` or embeds DSNs, - * credentials, hostnames, or raw driver messages. - */ -export class ResearchCopilotExecutorError extends Error { - readonly code: ResearchCopilotExecutorErrorCode; - - constructor(code: ResearchCopilotExecutorErrorCode, message: string) { - super(message); - this.name = 'ResearchCopilotExecutorError'; - this.code = code; - Object.setPrototypeOf(this, new.target.prototype); - } -} - -/** Configuration accepted by {@link openResearchCopilotExecutor}. */ -export interface ResearchCopilotExecutorConfig { - readonly postgresUrl: string; -} - -/** Minimal `pg.Pool` surface required by {@link openResearchCopilotExecutor}. */ -export interface ResearchCopilotExecutorPool { - query(text: string, values?: unknown[]): Promise<{ readonly rows: readonly unknown[] }>; - end(): Promise; - on(event: 'error', listener: (error: Error) => void): unknown; -} - -/** Optional dependency injection hooks for {@link openResearchCopilotExecutor}. */ -export interface ResearchCopilotExecutorDeps { - readonly createPool?: (poolConfig: PoolConfig) => ResearchCopilotExecutorPool; -} - -/** Structural query executor compatible with MCP research copilot PostgreSQL adapters. */ -export interface ResearchCopilotExecutor { - query>( - text: string, - params?: readonly unknown[] - ): Promise<{ readonly rows: readonly Row[] }>; -} - -/** Managed executor handle structurally assignable to `ManagedPostgresExecutor`. */ -export interface ManagedResearchCopilotExecutor { - readonly executor: ResearchCopilotExecutor; - close(): Promise; -} - -function invalidConfigError(): ResearchCopilotExecutorError { - return new ResearchCopilotExecutorError('INVALID_CONFIG', ERROR_MESSAGES.INVALID_CONFIG); -} - -function assertValidPort(rawPort: string): void { - if (!PORT_DIGITS_RE.test(rawPort)) { - throw invalidConfigError(); - } - const portNum = Number(rawPort); - if (!Number.isInteger(portNum) || portNum < 1 || portNum > 65535) { - throw invalidConfigError(); - } -} - -function parseAndNormalizePoolConfig(config: ResearchCopilotExecutorConfig): PoolConfig { - if (typeof config !== 'object' || config === null || typeof config.postgresUrl !== 'string') { - throw invalidConfigError(); - } - - const rawUrl = config.postgresUrl; - if ( - rawUrl.length === 0 || - rawUrl !== rawUrl.trim() || - CONTROL_CHAR_RE.test(rawUrl) || - !POSTGRES_URL_PREFIX_RE.test(rawUrl) - ) { - throw invalidConfigError(); - } - - let parsed: URL; - try { - parsed = new URL(rawUrl); - } catch { - throw invalidConfigError(); - } - - if (parsed.protocol !== 'postgres:' && parsed.protocol !== 'postgresql:') { - throw invalidConfigError(); - } - - const hostQueryParams = parsed.searchParams.getAll('host'); - if (hostQueryParams.length > 1) { - throw invalidConfigError(); - } - const queryHost = hostQueryParams.length === 1 ? (hostQueryParams[0] as string).trim() : ''; - if (hostQueryParams.length === 1 && queryHost.length === 0) { - throw invalidConfigError(); - } - - const hasAuthorityHost = parsed.hostname.length > 0; - if (hasAuthorityHost) { - let decodedHost: string; - try { - decodedHost = decodeURIComponent(parsed.hostname); - } catch { - throw invalidConfigError(); - } - if (decodedHost.trim().length === 0) { - throw invalidConfigError(); - } - } - - if (!hasAuthorityHost && queryHost.length === 0) { - throw invalidConfigError(); - } - - if (parsed.port.length > 0) { - assertValidPort(parsed.port); - } - - const portQueryParams = parsed.searchParams.getAll('port'); - if (portQueryParams.length > 1) { - throw invalidConfigError(); - } - if (portQueryParams.length === 1) { - assertValidPort((portQueryParams[0] as string).trim()); - } - - if (!parsed.pathname.startsWith('/') || parsed.pathname.length <= 1) { - throw invalidConfigError(); - } - const rawDatabase = parsed.pathname.slice(1); - if (rawDatabase.includes('/')) { - throw invalidConfigError(); - } - let decodedDatabase: string; - try { - decodedDatabase = decodeURIComponent(rawDatabase); - } catch { - throw invalidConfigError(); - } - if (decodedDatabase.trim().length === 0) { - throw invalidConfigError(); - } - - try { - if (parsed.username.length > 0) { - decodeURIComponent(parsed.username); - } - if (parsed.password.length > 0) { - decodeURIComponent(parsed.password); - } - } catch { - throw invalidConfigError(); - } - - const existingOptions: string[] = []; - const keysToDelete: string[] = []; - for (const [key, value] of parsed.searchParams.entries()) { - const lower = key.toLowerCase(); - if (lower === 'options') { - const trimmed = value.trim(); - if (trimmed.length > 0) { - existingOptions.push(trimmed); - } - keysToDelete.push(key); - } else if (STRIPPED_TIMEOUT_PARAMS.has(lower)) { - keysToDelete.push(key); - } - } - for (let i = 0; i < keysToDelete.length; i += 1) { - parsed.searchParams.delete(keysToDelete[i] as string); - } - - const envOptions = typeof process.env.PGOPTIONS === 'string' ? process.env.PGOPTIONS.trim() : ''; - const baseOptions = existingOptions.length > 0 ? existingOptions.join(' ') : envOptions; - - const poolConfig: PoolConfig = { - connectionString: parsed.toString(), - max: RESEARCH_COPILOT_PG_POOL_MAX, - connectionTimeoutMillis: RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS, - statement_timeout: RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS, - query_timeout: RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS, - lock_timeout: RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS, - }; - - if (baseOptions.length > 0) { - poolConfig.options = `${baseOptions} -c statement_timeout=${RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS} -c lock_timeout=${RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS}`; - } - - return poolConfig; -} - -function resolveCreatePool( - deps?: ResearchCopilotExecutorDeps -): (poolConfig: PoolConfig) => ResearchCopilotExecutorPool { - if (deps === undefined) { - return poolConfig => new Pool(poolConfig); - } - if (typeof deps !== 'object' || deps === null) { - throw invalidConfigError(); - } - if (deps.createPool === undefined) { - return poolConfig => new Pool(poolConfig); - } - if (typeof deps.createPool !== 'function') { - throw invalidConfigError(); - } - return deps.createPool; -} - -function getPostgresErrorCode(error: unknown): string | undefined { - if (typeof error === 'object' && error !== null) { - const code = (error as { readonly code?: unknown }).code; - if (typeof code === 'string') { - return code; - } - } - return undefined; -} - -async function safeEndPool(pool: ResearchCopilotExecutorPool): Promise { - try { - await pool.end(); - } catch { - // Best-effort cleanup during failed startup; preserve primary OPEN_FAILED error. - } -} - -/** - * Opens a bounded, probed PostgreSQL executor for the MCP research copilot - * stdio host. - */ -export async function openResearchCopilotExecutor( - config: ResearchCopilotExecutorConfig, - deps?: ResearchCopilotExecutorDeps -): Promise { - const poolConfig = parseAndNormalizePoolConfig(config); - const createPool = resolveCreatePool(deps); - - let pool: ResearchCopilotExecutorPool; - try { - pool = createPool(poolConfig); - } catch { - throw new ResearchCopilotExecutorError('OPEN_FAILED', ERROR_MESSAGES.OPEN_FAILED); - } - - if ( - typeof pool !== 'object' || - pool === null || - typeof pool.query !== 'function' || - typeof pool.end !== 'function' || - typeof pool.on !== 'function' - ) { - throw new ResearchCopilotExecutorError('OPEN_FAILED', ERROR_MESSAGES.OPEN_FAILED); - } - - try { - // Keep idle-client disconnects from becoming unhandled EventEmitter errors. - pool.on('error', () => { - // Intentionally absorbed; subsequent queries surface sanitized QUERY_FAILED errors. - }); - await pool.query('SELECT 1'); - } catch { - await safeEndPool(pool); - throw new ResearchCopilotExecutorError('OPEN_FAILED', ERROR_MESSAGES.OPEN_FAILED); - } - - let closed = false; - let closePromise: Promise | null = null; - - const executor: ResearchCopilotExecutor = { - async query>( - text: string, - params?: readonly unknown[] - ): Promise<{ readonly rows: readonly Row[] }> { - if (closed) { - throw new ResearchCopilotExecutorError('EXECUTOR_CLOSED', ERROR_MESSAGES.EXECUTOR_CLOSED); - } - - let rawResult: { readonly rows: readonly unknown[] }; - try { - rawResult = - params === undefined ? await pool.query(text) : await pool.query(text, [...params]); - } catch (error) { - if (getPostgresErrorCode(error) === '23505') { - throw new ResearchCopilotExecutorError('23505', ERROR_MESSAGES['23505']); - } - throw new ResearchCopilotExecutorError('QUERY_FAILED', ERROR_MESSAGES.QUERY_FAILED); - } - - if ( - typeof rawResult !== 'object' || - rawResult === null || - !Array.isArray(rawResult.rows) - ) { - throw new ResearchCopilotExecutorError('QUERY_FAILED', ERROR_MESSAGES.QUERY_FAILED); - } - - return { rows: rawResult.rows as readonly Row[] }; - }, - }; - - const close = (): Promise => { - closed = true; - if (closePromise === null) { - closePromise = Promise.resolve() - .then(() => pool.end()) - .catch(() => { - throw new ResearchCopilotExecutorError('CLOSE_FAILED', ERROR_MESSAGES.CLOSE_FAILED); - }); - } - return closePromise; - }; - - return { executor, close }; -} diff --git a/libs/data/postgres/test/research-copilot-executor-edge.test.ts b/libs/data/postgres/test/research-copilot-executor-edge.test.ts deleted file mode 100644 index f126bd50..00000000 --- a/libs/data/postgres/test/research-copilot-executor-edge.test.ts +++ /dev/null @@ -1,428 +0,0 @@ -import { readFileSync } from 'node:fs'; -import { createServer, type AddressInfo, type Socket } from 'node:net'; -import { fileURLToPath } from 'node:url'; -import { afterEach, describe, expect, test } from 'bun:test'; -import { Client, Pool, type PoolConfig } from 'pg'; -import { - RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS, - RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS, - RESEARCH_COPILOT_PG_POOL_MAX, - RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS, - RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS, - ResearchCopilotExecutorError, - type ResearchCopilotExecutorPool, - openResearchCopilotExecutor, -} from '../src/index'; - -const cleanup: Array<() => Promise | void> = []; -afterEach(async () => { - for (const fn of cleanup.splice(0).reverse()) { - await fn(); - } -}); - -describe('openResearchCopilotExecutor edge cases', () => { - test('strips URL timeout overrides while preserving search_path and enforcing executor timeouts', async () => { - const capturedConfigs: PoolConfig[] = []; - const fakePool: ResearchCopilotExecutorPool = { - async query() { - return { rows: [{ '?column?': 1 }] }; - }, - async end() {}, - on() { - return fakePool; - }, - }; - - const hostileUrl = - 'postgres://u:p@127.0.0.1:5432/research_db' + - '?sslmode=disable' + - '&application_name=copilot_edge' + - '&statement_timeout=99999' + - '&LOCK_TIMEOUT=88888' + - '&query_timeout=77777' + - '&connect_timeout=66' + - '&connectionTimeoutMillis=55555' + - '&options=-c%20search_path%3Disolated_schema%20-c%20statement_timeout%3D60000%20-c%20lock_timeout%3D60000'; - - const handle = await openResearchCopilotExecutor( - { postgresUrl: hostileUrl }, - { - createPool(poolConfig) { - capturedConfigs.push(poolConfig); - return fakePool; - }, - } - ); - - expect(capturedConfigs).toHaveLength(1); - const poolConfig = capturedConfigs[0]!; - const normalizedUrl = new URL(poolConfig.connectionString!); - expect(normalizedUrl.searchParams.get('sslmode')).toBe('disable'); - expect(normalizedUrl.searchParams.get('application_name')).toBe('copilot_edge'); - expect(normalizedUrl.searchParams.has('statement_timeout')).toBe(false); - expect(normalizedUrl.searchParams.has('LOCK_TIMEOUT')).toBe(false); - expect(normalizedUrl.searchParams.has('query_timeout')).toBe(false); - expect(normalizedUrl.searchParams.has('connect_timeout')).toBe(false); - expect(normalizedUrl.searchParams.has('connectionTimeoutMillis')).toBe(false); - expect(normalizedUrl.searchParams.has('options')).toBe(false); - - expect(poolConfig.options).toBe( - `-c search_path=isolated_schema -c statement_timeout=60000 -c lock_timeout=60000 ` + - `-c statement_timeout=${RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS} -c lock_timeout=${RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS}` - ); - - // Verify pg's own ConnectionParameters parser resolves the enforced timeouts. - const client = new Client(poolConfig); - const params = ( - client as unknown as { - connectionParameters: { - statement_timeout?: unknown; - lock_timeout?: unknown; - query_timeout?: unknown; - connect_timeout?: unknown; - options?: string; - application_name?: string; - }; - } - ).connectionParameters; - - expect(params.statement_timeout).toBe(RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS); - expect(params.lock_timeout).toBe(RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS); - expect(params.query_timeout).toBe(RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS); - expect(params.connect_timeout).toBe(RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS / 1000); - expect(params.application_name).toBe('copilot_edge'); - expect(params.options).toBe(poolConfig.options); - - await handle.close(); - }); - - test('accepts Unix-domain socket host query parameter and resolves domain-socket parameters in pg', async () => { - const capturedConfigs: PoolConfig[] = []; - const fakePool: ResearchCopilotExecutorPool = { - async query() { - return { rows: [{ '?column?': 1 }] }; - }, - async end() {}, - on() { - return fakePool; - }, - }; - - const handle = await openResearchCopilotExecutor( - { - postgresUrl: - 'postgres:///research_db?host=/var/run/postgresql&statement_timeout=99999&lock_timeout=88888', - }, - { - createPool(poolConfig) { - capturedConfigs.push(poolConfig); - return fakePool; - }, - } - ); - - expect(capturedConfigs).toHaveLength(1); - const client = new Client(capturedConfigs[0]); - const params = ( - client as unknown as { - connectionParameters: { - host?: string; - database?: string; - isDomainSocket?: boolean; - statement_timeout?: unknown; - lock_timeout?: unknown; - query_timeout?: unknown; - }; - } - ).connectionParameters; - - expect(params.host).toBe('/var/run/postgresql'); - expect(params.database).toBe('research_db'); - expect(params.isDomainSocket).toBe(true); - expect(params.statement_timeout).toBe(RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS); - expect(params.lock_timeout).toBe(RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS); - expect(params.query_timeout).toBe(RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS); - - await handle.close(); - }); - - test('rejects URLs missing host or database even when PGHOST and PGDATABASE are set', async () => { - const previousPgHost = process.env.PGHOST; - const previousPgDatabase = process.env.PGDATABASE; - process.env.PGHOST = '127.0.0.1'; - process.env.PGDATABASE = 'fallback_db'; - cleanup.push(() => { - if (previousPgHost === undefined) { - delete process.env.PGHOST; - } else { - process.env.PGHOST = previousPgHost; - } - if (previousPgDatabase === undefined) { - delete process.env.PGDATABASE; - } else { - process.env.PGDATABASE = previousPgDatabase; - } - }); - - let createPoolCalls = 0; - for (const postgresUrl of [ - 'postgres:///research_db', - 'postgres://127.0.0.1:5432/', - 'postgres://127.0.0.1:5432', - ]) { - await expect( - openResearchCopilotExecutor( - { postgresUrl }, - { - createPool() { - createPoolCalls += 1; - return { - async query() { - return { rows: [] }; - }, - async end() {}, - on() { - return undefined; - }, - }; - }, - } - ) - ).rejects.toMatchObject({ - name: 'ResearchCopilotExecutorError', - code: 'INVALID_CONFIG', - }); - } - expect(createPoolCalls).toBe(0); - }); - - test('preserves PGOPTIONS startup precedence while enforcing executor timeouts', async () => { - const previousPgOptions = process.env.PGOPTIONS; - cleanup.push(() => { - if (previousPgOptions === undefined) { - delete process.env.PGOPTIONS; - } else { - process.env.PGOPTIONS = previousPgOptions; - } - }); - - const fakePool: ResearchCopilotExecutorPool = { - async query() { - return { rows: [{ '?column?': 1 }] }; - }, - async end() {}, - on() { - return fakePool; - }, - }; - - // 1. No URL options and no PGOPTIONS -> PoolConfig.options omitted. - delete process.env.PGOPTIONS; - let captured: PoolConfig | undefined; - const h1 = await openResearchCopilotExecutor( - { postgresUrl: 'postgres://127.0.0.1:5432/research_db' }, - { - createPool(poolConfig) { - captured = poolConfig; - return fakePool; - }, - } - ); - expect(captured?.options).toBeUndefined(); - const c1 = new Client(captured); - const p1 = ( - c1 as unknown as { - connectionParameters: { - options?: string; - statement_timeout?: unknown; - lock_timeout?: unknown; - }; - } - ).connectionParameters; - expect(p1.options).toBeUndefined(); - expect(p1.statement_timeout).toBe(RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS); - expect(p1.lock_timeout).toBe(RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS); - await h1.close(); - - // 2. PGOPTIONS set with no URL options -> PGOPTIONS preserved + executor timeouts appended. - process.env.PGOPTIONS = '-c search_path=research -c statement_timeout=99999 -c lock_timeout=88888'; - captured = undefined; - const h2 = await openResearchCopilotExecutor( - { postgresUrl: 'postgres://127.0.0.1:5432/research_db' }, - { - createPool(poolConfig) { - captured = poolConfig; - return fakePool; - }, - } - ); - expect(captured?.options).toBe( - `-c search_path=research -c statement_timeout=99999 -c lock_timeout=88888 ` + - `-c statement_timeout=${RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS} -c lock_timeout=${RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS}` - ); - const c2 = new Client(captured); - const p2 = ( - c2 as unknown as { connectionParameters: { options?: string } } - ).connectionParameters; - expect(p2.options).toBe(captured?.options); - await h2.close(); - - // 3. Both URL options and PGOPTIONS set -> URL options wins over PGOPTIONS, timeouts still appended. - process.env.PGOPTIONS = '-c search_path=env_schema'; - captured = undefined; - const h3 = await openResearchCopilotExecutor( - { - postgresUrl: - 'postgres://127.0.0.1:5432/research_db?options=-c%20search_path%3Durl_schema', - }, - { - createPool(poolConfig) { - captured = poolConfig; - return fakePool; - }, - } - ); - expect(captured?.options).toBe( - `-c search_path=url_schema ` + - `-c statement_timeout=${RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS} -c lock_timeout=${RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS}` - ); - await h3.close(); - }); - - test('absorbs idle-client pool error events without crashing the process', async () => { - const errorListeners: Array<(error: Error) => void> = []; - const fakePool: ResearchCopilotExecutorPool = { - async query(text) { - return { rows: [{ sql: text }] }; - }, - async end() {}, - on(event, listener) { - if (event === 'error') { - errorListeners.push(listener); - } - return fakePool; - }, - }; - - const handle = await openResearchCopilotExecutor( - { postgresUrl: 'postgres://127.0.0.1:5432/research_db' }, - { createPool: () => fakePool } - ); - - expect(errorListeners).toHaveLength(1); - expect(() => errorListeners[0]!(new Error('idle client disconnected'))).not.toThrow(); - - const res = await handle.executor.query<{ sql: string }>('SELECT 2'); - expect(res.rows).toEqual([{ sql: 'SELECT 2' }]); - await handle.close(); - }); - - test('deduplicates concurrent close() calls and rejects queries started during shutdown', async () => { - let resolveEnd!: () => void; - let endCalls = 0; - let queryCalls = 0; - - const fakePool: ResearchCopilotExecutorPool = { - async query() { - queryCalls += 1; - return { rows: [] }; - }, - end() { - endCalls += 1; - return new Promise(resolve => { - resolveEnd = resolve; - }); - }, - on() { - return fakePool; - }, - }; - - const handle = await openResearchCopilotExecutor( - { postgresUrl: 'postgres://127.0.0.1:5432/research_db' }, - { createPool: () => fakePool } - ); - expect(queryCalls).toBe(1); - - const closeA = handle.close(); - const closeB = handle.close(); - - // Even while pool.end() is still in flight, new queries must reject immediately. - await expect(handle.executor.query('SELECT 2')).rejects.toMatchObject({ - name: 'ResearchCopilotExecutorError', - code: 'EXECUTOR_CLOSED', - }); - expect(queryCalls).toBe(1); - expect(endCalls).toBe(1); - - resolveEnd(); - await Promise.all([closeA, closeB]); - expect(endCalls).toBe(1); - }); - - test('rejects with sanitized OPEN_FAILED when a real pg.Pool times out against a silent loopback listener', async () => { - const sockets = new Set(); - const server = createServer(socket => { - sockets.add(socket); - socket.on('close', () => sockets.delete(socket)); - // Intentionally accept and never reply so pg hits its connection timeout. - }); - - await new Promise((resolve, reject) => { - server.once('error', reject); - server.listen(0, '127.0.0.1', () => resolve()); - }); - cleanup.push(async () => { - for (const socket of sockets) { - socket.destroy(); - } - await new Promise(resolve => server.close(() => resolve())); - }); - - const { port } = server.address() as AddressInfo; - const secretPass = 'LoopbackSecretPass99'; - const loopbackUrl = `postgres://loopback_user:${secretPass}@127.0.0.1:${port}/research_db`; - - let observedConfig: PoolConfig | undefined; - let caught: unknown; - try { - await openResearchCopilotExecutor( - { postgresUrl: loopbackUrl }, - { - createPool(poolConfig) { - observedConfig = poolConfig; - // Keep the default config assertions intact, but tighten connect timeout for fast local test execution. - return new Pool({ - ...poolConfig, - connectionTimeoutMillis: 150, - }); - }, - } - ); - } catch (err) { - caught = err; - } - - expect(observedConfig?.max).toBe(RESEARCH_COPILOT_PG_POOL_MAX); - expect(observedConfig?.connectionTimeoutMillis).toBe(RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS); - expect(observedConfig?.query_timeout).toBe(RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS); - expect(caught).toBeInstanceOf(ResearchCopilotExecutorError); - const typed = caught as ResearchCopilotExecutorError; - expect(typed.code).toBe('OPEN_FAILED'); - expect((typed as { cause?: unknown }).cause).toBeUndefined(); - expect(typed.message).not.toContain('loopback_user'); - expect(typed.message).not.toContain(secretPass); - expect(typed.message).not.toContain('127.0.0.1'); - expect(typed.message).not.toContain(String(port)); - }); - - test('has no runtime import of @stock-bot/research', () => { - const sourcePath = fileURLToPath( - new URL('../src/research-copilot-executor.ts', import.meta.url) - ); - const source = readFileSync(sourcePath, 'utf8'); - expect(source).not.toMatch(/from\s+['"]@stock-bot\/research/); - expect(source).not.toMatch(/require\(\s*['"]@stock-bot\/research/); - }); -}); diff --git a/libs/data/postgres/test/research-copilot-executor.test.ts b/libs/data/postgres/test/research-copilot-executor.test.ts deleted file mode 100644 index c014d210..00000000 --- a/libs/data/postgres/test/research-copilot-executor.test.ts +++ /dev/null @@ -1,423 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import type { PoolConfig } from 'pg'; -import { - RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS, - RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS, - RESEARCH_COPILOT_PG_POOL_MAX, - RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS, - RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS, - ResearchCopilotExecutorError, - type ResearchCopilotExecutorPool, - openResearchCopilotExecutor, -} from '../src/index'; - -const SECRET_USER = 'copilot_secret_user'; -const SECRET_PASS = 'Sup3rS3cretP@ssw0rd!'; -const SECRET_HOST = 'pg-internal-secret.example.test'; -const VALID_URL = `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db`; - -interface FakePoolState { - readonly queries: Array<{ readonly text: string; readonly values?: unknown[] }>; - readonly errorListeners: Array<(error: Error) => void>; - endCalls: number; - readonly pool: ResearchCopilotExecutorPool; -} - -function createFakePool(options?: { - onQuery?: (text: string, values?: unknown[]) => Promise<{ readonly rows: readonly unknown[] }>; - onEnd?: () => Promise; -}): FakePoolState { - const queries: Array<{ readonly text: string; readonly values?: unknown[] }> = []; - const errorListeners: Array<(error: Error) => void> = []; - const state: FakePoolState = { - queries, - errorListeners, - endCalls: 0, - pool: { - async query(text: string, values?: unknown[]) { - queries.push(values === undefined ? { text } : { text, values }); - if (options?.onQuery) { - return options.onQuery(text, values); - } - return { rows: [] }; - }, - async end() { - state.endCalls += 1; - if (options?.onEnd) { - return options.onEnd(); - } - }, - on(event: 'error', listener: (error: Error) => void) { - if (event === 'error') { - errorListeners.push(listener); - } - return state.pool; - }, - }, - }; - return state; -} - -function assertNoSecretsLeaked(error: unknown): void { - expect(error).toBeInstanceOf(ResearchCopilotExecutorError); - const typed = error as ResearchCopilotExecutorError; - expect((typed as { cause?: unknown }).cause).toBeUndefined(); - expect('cause' in typed).toBe(false); - expect('detail' in typed).toBe(false); - expect('extraDiag' in typed).toBe(false); - const message = typed.message; - for (const needle of [ - VALID_URL, - SECRET_USER, - SECRET_PASS, - encodeURIComponent(SECRET_PASS), - SECRET_HOST, - 'raw-pg-secret', - ]) { - expect(message).not.toContain(needle); - } -} - -describe('openResearchCopilotExecutor', () => { - test('opens a bounded pg pool, probes once with SELECT 1, and attaches an error listener', async () => { - const previousPgOptions = process.env.PGOPTIONS; - delete process.env.PGOPTIONS; - try { - const capturedConfigs: PoolConfig[] = []; - const fake = createFakePool({ - async onQuery(text) { - if (text === 'SELECT 1') { - return { rows: [{ '?column?': 1 }] }; - } - return { rows: [{ id: 42 }] }; - }, - }); - - const handle = await openResearchCopilotExecutor( - { postgresUrl: VALID_URL }, - { - createPool(poolConfig) { - capturedConfigs.push(poolConfig); - return fake.pool; - }, - } - ); - - expect(capturedConfigs).toHaveLength(1); - expect(capturedConfigs[0]).toEqual({ - connectionString: VALID_URL, - max: RESEARCH_COPILOT_PG_POOL_MAX, - connectionTimeoutMillis: RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS, - statement_timeout: RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS, - query_timeout: RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS, - lock_timeout: RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS, - }); - expect(capturedConfigs[0]?.options).toBeUndefined(); - expect(RESEARCH_COPILOT_PG_POOL_MAX).toBe(4); - expect(RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS).toBe(5_000); - expect(RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS).toBe(10_000); - expect(RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS).toBe(15_000); - expect(RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS).toBe(2_000); - - expect(fake.errorListeners).toHaveLength(1); - expect(fake.queries).toEqual([{ text: 'SELECT 1' }]); - - const res = await handle.executor.query<{ id: number }>('SELECT $1::int AS id', [42]); - expect(res.rows).toEqual([{ id: 42 }]); - expect(fake.queries).toEqual([ - { text: 'SELECT 1' }, - { text: 'SELECT $1::int AS id', values: [42] }, - ]); - - await handle.close(); - expect(fake.endCalls).toBe(1); - } finally { - if (previousPgOptions === undefined) { - delete process.env.PGOPTIONS; - } else { - process.env.PGOPTIONS = previousPgOptions; - } - } - }); - - test('accepts postgresql:// scheme and Unix-domain socket host query parameters', async () => { - for (const postgresUrl of [ - 'postgresql://127.0.0.1:5432/research_db', - 'postgres:///research_db?host=/var/run/postgresql', - 'postgresql:///research_db?host=/var/run/postgresql', - ]) { - const fake = createFakePool(); - const handle = await openResearchCopilotExecutor( - { postgresUrl }, - { createPool: () => fake.pool } - ); - expect(fake.queries).toEqual([{ text: 'SELECT 1' }]); - await handle.close(); - } - }); - - test('rejects invalid URLs with INVALID_CONFIG before constructing a pool', async () => { - const invalidUrls = [ - '', - ' ', - ` ${VALID_URL} `, - `${VALID_URL}\n`, - 'not-a-url', - `http://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db`, - `mysql://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:3306/research_db`, - 'postgres:/research_db?host=%2Ftmp', - 'postgresql:/research_db?host=%2Ftmp', - 'postgres:///research_db', - 'postgres:///research_db?host=', - 'postgres:///research_db?host=%20%20', - 'postgres:///research_db?host=/var/run/postgresql&host=/tmp', - 'postgres:///research_db?HOST=/var/run/postgresql', - 'postgres://copilot@db.example/?dbname=research', - `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?host=`, - `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?host=/a&host=/b`, - `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?port=0`, - `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?port=70000`, - `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?port=abc`, - `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?port=`, - `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?port=5432&port=5433`, - `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432`, - `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/`, - `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/%20%20`, - `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/db/extra`, - `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:0/research_db`, - `postgres://%ZZ:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db`, - `postgres://${SECRET_USER}:%ZZ@${SECRET_HOST}:5432/research_db`, - `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/%ZZ`, - ]; - - let createPoolCalls = 0; - for (const postgresUrl of invalidUrls) { - let caught: unknown; - try { - await openResearchCopilotExecutor( - { postgresUrl }, - { - createPool() { - createPoolCalls += 1; - return createFakePool().pool; - }, - } - ); - } catch (err) { - caught = err; - } - assertNoSecretsLeaked(caught); - expect((caught as ResearchCopilotExecutorError).code).toBe('INVALID_CONFIG'); - } - expect(createPoolCalls).toBe(0); - }); - - test('rejects malformed config or deps with INVALID_CONFIG', async () => { - await expect( - openResearchCopilotExecutor(null as unknown as { postgresUrl: string }) - ).rejects.toMatchObject({ - name: 'ResearchCopilotExecutorError', - code: 'INVALID_CONFIG', - }); - - await expect( - openResearchCopilotExecutor( - { postgresUrl: VALID_URL }, - { createPool: 'not-a-fn' as unknown as () => ResearchCopilotExecutorPool } - ) - ).rejects.toMatchObject({ - name: 'ResearchCopilotExecutorError', - code: 'INVALID_CONFIG', - }); - }); - - test('ends pool and throws sanitized OPEN_FAILED when startup probe fails', async () => { - const fake = createFakePool({ - async onQuery() { - throw new Error(`password authentication failed for ${SECRET_USER} at ${SECRET_HOST} raw-pg-secret`); - }, - }); - - let caught: unknown; - try { - await openResearchCopilotExecutor({ postgresUrl: VALID_URL }, { createPool: () => fake.pool }); - } catch (err) { - caught = err; - } - - assertNoSecretsLeaked(caught); - expect((caught as ResearchCopilotExecutorError).code).toBe('OPEN_FAILED'); - expect(fake.endCalls).toBe(1); - }); - - test('still throws OPEN_FAILED when both probe and cleanup end() fail', async () => { - const fake = createFakePool({ - async onQuery() { - throw new Error(`connect ECONNREFUSED ${SECRET_HOST} raw-pg-secret`); - }, - async onEnd() { - throw new Error(`pool end failed ${VALID_URL}`); - }, - }); - - let caught: unknown; - try { - await openResearchCopilotExecutor({ postgresUrl: VALID_URL }, { createPool: () => fake.pool }); - } catch (err) { - caught = err; - } - - assertNoSecretsLeaked(caught); - expect((caught as ResearchCopilotExecutorError).code).toBe('OPEN_FAILED'); - expect(fake.endCalls).toBe(1); - }); - - test('forwards parameters defensively without mutating caller arrays', async () => { - const fake = createFakePool({ - async onQuery(text, values) { - if (values) { - values.push('mutated-by-driver'); - } - return { rows: [{ text }] }; - }, - }); - - const handle = await openResearchCopilotExecutor( - { postgresUrl: VALID_URL }, - { createPool: () => fake.pool } - ); - - const callerParams = Object.freeze(['alpha', 7]); - const res = await handle.executor.query('SELECT $1, $2', callerParams); - expect(res.rows).toEqual([{ text: 'SELECT $1, $2' }]); - expect(callerParams).toEqual(['alpha', 7]); - - await handle.executor.query('SELECT 2'); - expect(fake.queries[2]).toEqual({ text: 'SELECT 2' }); - expect('values' in fake.queries[2]!).toBe(false); - - await handle.close(); - }); - - test('preserves SQLSTATE 23505 on sanitized unique-violation query errors without leaking cause or driver fields', async () => { - let callCount = 0; - const rawCause = new Error(`nested pgpass secret ${SECRET_PASS}`); - const fake = createFakePool({ - async onQuery() { - callCount += 1; - if (callCount === 1) { - return { rows: [{ '?column?': 1 }] }; - } - const pgErr = Object.assign( - new Error(`duplicate key value violates unique constraint on ${SECRET_HOST} raw-pg-secret`, { - cause: rawCause, - }), - { - code: '23505', - detail: `Key (id)=(dup-1) already exists (${SECRET_PASS})`, - extraDiag: 'sensitive-driver-field', - } - ); - throw pgErr; - }, - }); - - const handle = await openResearchCopilotExecutor( - { postgresUrl: VALID_URL }, - { createPool: () => fake.pool } - ); - - let caught: unknown; - try { - await handle.executor.query('INSERT INTO findings (id) VALUES ($1)', ['dup-1']); - } catch (err) { - caught = err; - } - - assertNoSecretsLeaked(caught); - expect((caught as ResearchCopilotExecutorError).code).toBe('23505'); - await handle.close(); - }); - - test('sanitizes generic query errors to QUERY_FAILED with no cause, extra fields, or raw text', async () => { - let callCount = 0; - const rawCause = new Error(`nested env PGPASSWORD=${SECRET_PASS}`); - const fake = createFakePool({ - async onQuery() { - callCount += 1; - if (callCount === 1) { - return { rows: [{ '?column?': 1 }] }; - } - throw Object.assign( - new Error(`relation "missing" does not exist on ${VALID_URL} raw-pg-secret`, { - cause: rawCause, - }), - { code: '42P01', detail: 'driver-detail', extraDiag: 'sensitive-driver-field' } - ); - }, - }); - - const handle = await openResearchCopilotExecutor( - { postgresUrl: VALID_URL }, - { createPool: () => fake.pool } - ); - - let caught: unknown; - try { - await handle.executor.query('SELECT * FROM missing'); - } catch (err) { - caught = err; - } - - assertNoSecretsLeaked(caught); - expect((caught as ResearchCopilotExecutorError).code).toBe('QUERY_FAILED'); - await handle.close(); - }); - - test('close() is idempotent and subsequent queries fail with EXECUTOR_CLOSED', async () => { - const fake = createFakePool(); - const handle = await openResearchCopilotExecutor( - { postgresUrl: VALID_URL }, - { createPool: () => fake.pool } - ); - - await handle.close(); - await handle.close(); - expect(fake.endCalls).toBe(1); - - let caught: unknown; - try { - await handle.executor.query('SELECT 1'); - } catch (err) { - caught = err; - } - - assertNoSecretsLeaked(caught); - expect((caught as ResearchCopilotExecutorError).code).toBe('EXECUTOR_CLOSED'); - expect(fake.queries).toHaveLength(1); // Only the initial SELECT 1 probe ran. - }); - - test('sanitizes pool.end() failures to CLOSE_FAILED with no cause or secret leakage', async () => { - const fake = createFakePool({ - async onEnd() { - throw new Error(`failed closing pool for ${VALID_URL} raw-pg-secret`); - }, - }); - - const handle = await openResearchCopilotExecutor( - { postgresUrl: VALID_URL }, - { createPool: () => fake.pool } - ); - - let caught: unknown; - try { - await handle.close(); - } catch (err) { - caught = err; - } - - assertNoSecretsLeaked(caught); - expect((caught as ResearchCopilotExecutorError).code).toBe('CLOSE_FAILED'); - expect(fake.endCalls).toBe(1); - }); -}); diff --git a/libs/data/postgres/test/research-copilot-executor.type-test.ts b/libs/data/postgres/test/research-copilot-executor.type-test.ts deleted file mode 100644 index b022aa18..00000000 --- a/libs/data/postgres/test/research-copilot-executor.type-test.ts +++ /dev/null @@ -1,50 +0,0 @@ -import type { Pool } from 'pg'; -import type { - ManagedPostgresExecutor, - PostgresResearchCopilotExecutor, - ResearchCopilotHostConfig, - ResearchCopilotStdioHostDeps, -} from '@stock-bot/research/mcp'; -import { - type ManagedResearchCopilotExecutor, - type ResearchCopilotExecutor, - type ResearchCopilotExecutorConfig, - type ResearchCopilotExecutorDeps, - type ResearchCopilotExecutorError, - type ResearchCopilotExecutorErrorCode, - type ResearchCopilotExecutorPool, - openResearchCopilotExecutor, -} from '../src/index'; - -// The factory must plug directly into ResearchCopilotStdioHostDeps.openExecutor. -openResearchCopilotExecutor satisfies ResearchCopilotStdioHostDeps['openExecutor']; - -// Full host config is structurally assignable to the minimal executor config. -declare const hostConfig: ResearchCopilotHostConfig; -hostConfig satisfies ResearchCopilotExecutorConfig; - -// Returned handle and executor are structurally assignable to the MCP host ports. -declare const managedHandle: ManagedResearchCopilotExecutor; -managedHandle satisfies ManagedPostgresExecutor; - -declare const executor: ResearchCopilotExecutor; -executor satisfies PostgresResearchCopilotExecutor; - -// Real pg.Pool satisfies the injected pool contract. -declare const pgPool: Pool; -pgPool satisfies ResearchCopilotExecutorPool; - -// Optional deps contract accepts createPool returning pg.Pool. -const validDeps: ResearchCopilotExecutorDeps = { - createPool: () => pgPool, -}; -void validDeps; - -// Error code union includes all sanitized lifecycle codes plus SQLSTATE 23505. -declare const errorInstance: ResearchCopilotExecutorError; -const errorCode: ResearchCopilotExecutorErrorCode = errorInstance.code; -void errorCode; - -// Negative checks: missing postgresUrl must fail typechecking. -// @ts-expect-error postgresUrl is required. -void openResearchCopilotExecutor({}); diff --git a/libs/data/questdb/README.md b/libs/data/questdb/README.md index 55476969..469ab8be 100644 --- a/libs/data/questdb/README.md +++ b/libs/data/questdb/README.md @@ -1,115 +1,102 @@ -# QuestDB Client Library - -A QuestDB 10.2.0 client library for the Stock Bot trading platform, optimized for time-series data, parameterized PGWire queries, and intraday bar storage. - -## Features - -- **Time-Series Optimized**: Built for QuestDB 10.2.0 (`LATEST ON`, `SAMPLE BY`, `ASOF JOIN`) -- **Parameterized PGWire Queries**: All value filters bind `$1..$n` placeholders; structured identifiers and intervals are strictly validated -- **Contract DDL**: Offline DDL generator for M2 intraday tables (`bars_1m`, `fx_1m`, `bar_revisions`) with `SYMBOL CAPACITY ... [NO]CACHE`, `PARTITION BY MONTH WAL`, and `DEDUP UPSERT KEYS` -- **Typed `bars_1m` Range Reader**: `readBars1m()` binds `listing_id` as canonical decimal string, returns `INT32` `listing_id` values, and projects `ts` and `known_at` as lossless UTC epoch microseconds (`bigint`) -- **InfluxDB Line Protocol**: Batch ingestion writer -- **Health Monitoring**: Connection health monitoring and metrics - -## Usage - -### Parameterized Queries & `LATEST ON` - -```typescript -import { QuestDBClient, QuestDBQueryBuilder } from '@stock-bot/questdb'; - -const questClient = new QuestDBClient({ - host: 'localhost', - httpPort: 9000, - pgPort: 8812, - influxPort: 9009, - database: 'qdb', -}); -await questClient.connect(); - -// Parameterized PGWire query via query builder -const { sql, params } = QuestDBQueryBuilder.create(questClient) - .select('listing_id', 'ts', 'close', 'volume') - .from('bars_1m') - .where('listing_id = $1', ['1042']) - .latestOn('ts', 'listing_id') - .buildParameterized(); -// sql: -// SELECT listing_id, ts, close, volume FROM bars_1m WHERE listing_id = $1 LATEST ON ts PARTITION BY listing_id -// params: ['1042'] - -// Execute directly (forwards both SQL and bound params) -const latestBars = await questClient.latestBy('bars_1m', ['listing_id', 'ts', 'close'], 'listing_id', { - where: 'session = $1', - params: ['RTH'], -}); - -// Override the designated timestamp column explicitly -const latestRevisions = await questClient.latestBy( - 'bar_revisions', - ['listing_id', 'revised_at', 'new_close'], - 'listing_id', - { timestampColumn: 'revised_at' } -); - -// Time-series aggregations with bound filters -const hourlyStats = await questClient - .aggregate('ohlcv_data') - .selectAgg({ avg_close: 'avg(close)' }) - .whereSymbol('AAPL') - .whereLastHours(24) - .groupBy('symbol') - .sampleBy('1h') - .execute(); -``` - -### Reading `bars_1m` Ranges - -```typescript -import { readBars1m } from '@stock-bot/questdb'; - -// Queries `[from, to)` ordered by `ts ASC`, binding listingId as decimal string SYMBOL -// and converting returned `listing_id` back to signed INT32. -const bars = await readBars1m( - questClient, - 1042, - new Date('2024-01-02T14:30:00.000Z'), - new Date('2024-01-02T21:00:00.000Z') -); -``` - -> **Storage-layer read semantics**: `readBars1m` returns all stored bars in `[from, to)` with `ts` and `known_at` projected via `CAST(... AS LONG)` as UTC epoch microseconds (`bigint`, preserving all 6 fractional digits independent of host timezone) without applying replay cutoffs. Research callers (`MarketDataStore`) remain responsible for as-of availability filtering and Vault fencing. - -### M2 Intraday Contract DDL (Offline) - -```typescript -import { getM2IntradayDDL } from '@stock-bot/questdb'; - -const ddl = getM2IntradayDDL(); -// ddl.bars_1m -> CREATE TABLE IF NOT EXISTS bars_1m (...) TIMESTAMP(ts) PARTITION BY MONTH WAL DEDUP UPSERT KEYS(ts, listing_id) -// ddl.fx_1m -> CREATE TABLE IF NOT EXISTS fx_1m (...) TIMESTAMP(ts) PARTITION BY MONTH WAL DEDUP UPSERT KEYS(ts, pair) -// ddl.bar_revisions -> CREATE TABLE IF NOT EXISTS bar_revisions (...) TIMESTAMP(revised_at) PARTITION BY MONTH WAL -``` - -M2 intraday tables are opt-in and are not auto-created during `QuestDBClient.connect()`. - -## Configuration - -Configure using environment variables: - -```env -QUESTDB_HOST=localhost -QUESTDB_HTTP_PORT=9000 -QUESTDB_PG_PORT=8812 -QUESTDB_INFLUX_PORT=9009 -``` - -## Time-Series Features - -QuestDB 10.2.0 supports: - -- **High-frequency data**: Millions of data points per second -- **Time-based partitioning**: Monthly WAL partitions for intraday tables -- **ASOF JOINs**: Time-series specific joins -- **SAMPLE BY**: Time-based aggregations -- **LATEST ON**: Get latest values per partition key (`LATEST ON PARTITION BY `) +# QuestDB Client Library + +A comprehensive QuestDB client library for the Stock Bot trading platform, optimized for time-series data, market analytics, and high-performance queries. + +## Features + +- **Time-Series Optimized**: Built specifically for time-series data patterns +- **Dual Protocol Support**: HTTP REST API and PostgreSQL wire protocol +- **InfluxDB Line Protocol**: High-performance data ingestion +- **SQL Analytics**: Full SQL support for complex analytics +- **Schema Management**: Automatic table creation and partitioning +- **Performance Monitoring**: Query performance tracking and optimization +- **Health Monitoring**: Connection health monitoring and metrics + +## Usage + +```typescript +import { QuestDBClient } from '@stock-bot/questdb'; + +// Initialize client +const questClient = new QuestDBClient(); +await questClient.connect(); + +// Insert market data using InfluxDB Line Protocol +await questClient.insert('ohlcv', { + symbol: 'AAPL', + open: 150.00, + high: 152.00, + low: 149.50, + close: 151.50, + volume: 1000000, + timestamp: new Date() +}); + +// Query with SQL +const prices = await questClient.query(` + SELECT symbol, close, timestamp + FROM ohlcv + WHERE symbol = 'AAPL' + AND timestamp > dateadd('d', -1, now()) + ORDER BY timestamp DESC +`); + +// Time-series aggregations +const dailyStats = await questClient.aggregate('ohlcv') + .select(['symbol', 'avg(close) as avg_price']) + .where('symbol = ?', ['AAPL']) + .groupBy('symbol') + .sampleBy('1d', 'timestamp') + .execute(); +``` + +## Data Types + +The client provides typed access to the following time-series data: + +- **ohlcv**: OHLCV candlestick data +- **trades**: Individual trade executions +- **quotes**: Bid/ask quote data +- **indicators**: Technical indicator values +- **performance**: Portfolio performance metrics +- **risk_metrics**: Risk calculation results + +## Configuration + +Configure using environment variables: + +```env +QUESTDB_HOST=localhost +QUESTDB_HTTP_PORT=9000 +QUESTDB_PG_PORT=8812 +QUESTDB_INFLUX_PORT=9009 +``` + +## Time-Series Features + +QuestDB excels at: + +- **High-frequency data**: Millions of data points per second +- **Time-based partitioning**: Automatic partitioning by time +- **ASOF JOINs**: Time-series specific joins +- **SAMPLE BY**: Time-based aggregations +- **LATEST BY**: Get latest values by key + +## Performance + +The client includes performance optimizations: + +- Connection pooling for HTTP and PostgreSQL protocols +- Batch insertions for high throughput +- Compressed data transfer +- Query result caching +- Automatic schema optimization + +## Health Monitoring + +Built-in health monitoring: + +```typescript +const health = await questClient.getHealth(); +console.log(health.status); // 'healthy' | 'degraded' | 'unhealthy' +``` diff --git a/libs/data/questdb/src/client.ts b/libs/data/questdb/src/client.ts index 84e63f43..d4cba976 100644 --- a/libs/data/questdb/src/client.ts +++ b/libs/data/questdb/src/client.ts @@ -3,193 +3,15 @@ import { Pool } from 'pg'; import type { LoggerLike } from '@stock-bot/logger'; import { QuestDBHealthMonitor } from './health'; import { QuestDBInfluxWriter } from './influx-writer'; -import { - assertIdentifier, - assertSampleInterval, - assertSelectColumn, - QuestDBQueryBuilder, - rebaseWhereCondition, -} from './query-builder'; +import { QuestDBQueryBuilder } from './query-builder'; import { QuestDBSchemaManager } from './schema'; import type { - Bar1mRow, - LatestByOptions, QueryResult, QuestDBClientConfig, QuestDBConnectionOptions, - QuestDBQueryable, TableNames, } from './types'; -const INT32_MIN = -2147483648; -const INT32_MAX = 2147483647; -const CANONICAL_INT_RE = /^-?(?:0|[1-9]\d*)$/; -const ISO_UTC_OR_OFFSET_RE = - /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?(Z|([+-])(\d{2}):(\d{2}))$/; -const ALLOWED_PARTITIONS = new Set(['NONE', 'HOUR', 'DAY', 'MONTH', 'YEAR']); - -function formatInt32ListingId(listingId: number): string { - if (!Number.isInteger(listingId) || listingId < INT32_MIN || listingId > INT32_MAX) { - throw new RangeError( - `Invalid listingId: expected signed INT32 integer, received ${String(listingId)}` - ); - } - return String(listingId === 0 ? 0 : listingId); -} - -function parseInt32ListingSymbol(raw: unknown): number { - if (typeof raw !== 'string' || !CANONICAL_INT_RE.test(raw)) { - throw new Error(`Malformed bars_1m listing_id SYMBOL value: "${String(raw)}"`); - } - const parsed = Number(raw); - if (!Number.isInteger(parsed) || parsed < INT32_MIN || parsed > INT32_MAX) { - throw new RangeError(`Out-of-range bars_1m listing_id SYMBOL value: "${raw}"`); - } - return parsed; -} - -function toUtcIsoString(value: Date | string, label: string): string { - if (value instanceof Date) { - if (Number.isNaN(value.getTime())) { - throw new Error(`Invalid ${label} timestamp: Date is NaN`); - } - return value.toISOString(); - } - if (typeof value === 'string') { - const trimmed = value.trim(); - const match = ISO_UTC_OR_OFFSET_RE.exec(trimmed); - if (!match) { - throw new Error( - `Invalid ${label} timestamp: expected ISO-8601 string with explicit UTC or offset timezone, received "${value}"` - ); - } - - const year = Number(match[1]); - const month = Number(match[2]); - const day = Number(match[3]); - const hour = Number(match[4]); - const minute = Number(match[5]); - const second = Number(match[6]); - const frac = match[7]; - const tz = match[8]; - - const baseUtcMs = Date.UTC(year, month - 1, day, hour, minute, second); - const check = new Date(baseUtcMs); - if ( - check.getUTCFullYear() !== year || - check.getUTCMonth() !== month - 1 || - check.getUTCDate() !== day || - check.getUTCHours() !== hour || - check.getUTCMinutes() !== minute || - check.getUTCSeconds() !== second - ) { - throw new Error(`Invalid ${label} timestamp calendar date/time: "${value}"`); - } - - if (tz === 'Z') { - return trimmed; - } - - const sign = match[9] === '+' ? 1 : -1; - const offsetHours = Number(match[10]); - const offsetMinutes = Number(match[11]); - if (offsetHours > 23 || offsetMinutes > 59) { - throw new Error(`Invalid ${label} timestamp timezone offset: "${value}"`); - } - - const adjustedUtcMs = baseUtcMs - sign * (offsetHours * 60 + offsetMinutes) * 60_000; - const utcDate = new Date(adjustedUtcMs); - const isoSeconds = utcDate.toISOString().slice(0, 19); - return frac ? `${isoSeconds}.${frac}Z` : `${isoSeconds}Z`; - } - throw new Error(`Invalid ${label} timestamp: "${String(value)}"`); -} - -function parseUtcEpochMicros(raw: unknown, field: string): bigint { - if (typeof raw === 'bigint') { - return raw; - } - if (typeof raw === 'string' && CANONICAL_INT_RE.test(raw)) { - return BigInt(raw); - } - if (typeof raw === 'number' && Number.isSafeInteger(raw)) { - return BigInt(raw); - } - throw new Error(`Invalid bars_1m ${field} UTC epoch microseconds: "${String(raw)}"`); -} - -function parseRequiredFiniteNumber(raw: unknown, field: string): number { - const value = - typeof raw === 'number' - ? raw - : typeof raw === 'string' && raw.trim().length > 0 - ? Number(raw) - : Number.NaN; - if (!Number.isFinite(value)) { - throw new Error(`Invalid bars_1m ${field} value: "${String(raw)}"`); - } - return value; -} - -function parseNullableFiniteNumber(raw: unknown, field: string): number | null { - if (raw === null || raw === undefined) { - return null; - } - return parseRequiredFiniteNumber(raw, field); -} - -function parseNullableString(raw: unknown, field: string): string | null { - if (raw === null || raw === undefined) { - return null; - } - if (typeof raw === 'string') { - return raw; - } - throw new Error(`Invalid bars_1m ${field} value: expected string or null`); -} - -/** - * Read 1-minute bars for a single listing over `[from, to)` ordered by `ts ASC` from `bars_1m`. - * - * Binds `listingId` as its canonical decimal string (`SYMBOL`) and converts returned `listing_id` - * values back to signed `INT32` numbers at the boundary (`design/DATA-CONTRACTS.md` §3.B). - * - * Storage-layer read: preserves `known_at` on each row without applying replay cutoffs. - * Research callers (`MarketDataStore`) remain responsible for as-of availability and Vault fencing. - */ -export async function readBars1m( - client: QuestDBQueryable, - listingId: number, - from: Date | string, - to: Date | string -): Promise { - const listingIdParam = formatInt32ListingId(listingId); - const fromIso = toUtcIsoString(from, 'from'); - const toIso = toUtcIsoString(to, 'to'); - - const sql = - 'SELECT listing_id, open, high, low, close, volume, vwap, session, source, CAST(known_at AS LONG) AS known_at_us, CAST(ts AS LONG) AS ts_us ' + - 'FROM bars_1m ' + - 'WHERE listing_id = $1 AND ts >= $2 AND ts < $3 ' + - 'ORDER BY ts ASC'; - - const result = await client.query>(sql, [listingIdParam, fromIso, toIso]); - - return result.rows.map(row => ({ - listing_id: parseInt32ListingSymbol(row.listing_id), - open: parseRequiredFiniteNumber(row.open, 'open'), - high: parseRequiredFiniteNumber(row.high, 'high'), - low: parseRequiredFiniteNumber(row.low, 'low'), - close: parseRequiredFiniteNumber(row.close, 'close'), - volume: parseRequiredFiniteNumber(row.volume, 'volume'), - vwap: parseNullableFiniteNumber(row.vwap, 'vwap'), - session: parseNullableString(row.session, 'session'), - source: parseNullableString(row.source, 'source'), - known_at: parseUtcEpochMicros(row.known_at_us, 'known_at'), - ts: parseUtcEpochMicros(row.ts_us, 'ts'), - })); -} - /** * QuestDB Client for Stock Bot * @@ -409,125 +231,72 @@ export class QuestDBClient { } /** - * Execute a time-series specific query with SAMPLE BY. - * `where` is treated as a trusted SQL fragment with `$1..$n` placeholders bound via `params`. + * Execute a time-series specific query with SAMPLE BY */ async sampleBy( - table: TableNames | string, + table: TableNames, columns: string[], interval: string, - timeColumn: string = 'timestamp', + _timeColumn: string = 'timestamp', where?: string, params?: unknown[] ): Promise> { - const validTable = assertIdentifier(table, 'table name'); - if (columns.length === 0) { - throw new Error('SELECT columns cannot be empty'); - } - const validColumns = columns.map(col => assertSelectColumn(col)); - const validInterval = assertSampleInterval(interval); - assertIdentifier(timeColumn, 'timestamp column'); + const columnsStr = columns.join(', '); + const whereClause = where ? `WHERE ${where}` : ''; - let whereClause = ''; - const boundParams = params ? [...params] : []; - if (where !== undefined) { - const validatedWhere = rebaseWhereCondition(where, boundParams, 0); - whereClause = `WHERE ${validatedWhere}`; - } else if (boundParams.length > 0) { - throw new Error('params provided to sampleBy without a where clause'); - } + const sql = ` + SELECT ${columnsStr} + FROM ${table} + ${whereClause} + SAMPLE BY ${interval} + ALIGN TO CALENDAR + `; - const sql = [ - `SELECT ${validColumns.join(', ')}`, - `FROM ${validTable}`, - whereClause, - `SAMPLE BY ${validInterval}`, - 'ALIGN TO CALENDAR', - ] - .filter(Boolean) - .join(' '); - - return await this.query(sql, boundParams.length > 0 ? boundParams : undefined); + return await this.query(sql, params); } /** - * Get latest rows per partition key using QuestDB 10.2.0 `LATEST ON`. - * Defaults to `ts` for `bars_1m`/`fx_1m`, `revised_at` for `bar_revisions`, and `timestamp` otherwise. - * `options.where` is treated as a trusted SQL fragment with `$1..$n` placeholders bound via `options.params`. + * Get latest values by symbol using LATEST BY */ async latestBy( - table: TableNames | string, + table: TableNames, columns: string | string[] = '*', - keyColumns: string | string[] = 'symbol', - options?: LatestByOptions + keyColumns: string | string[] = 'symbol' ): Promise> { - const cols = Array.isArray(columns) ? columns : [columns]; - if (cols.length === 0) { - throw new Error('SELECT columns cannot be empty'); - } - const keys = Array.isArray(keyColumns) ? keyColumns : [keyColumns]; + const columnsStr = Array.isArray(columns) ? columns.join(', ') : columns; + const keyColumnsStr = Array.isArray(keyColumns) ? keyColumns.join(', ') : keyColumns; - const builder = this.queryBuilder().select(...cols).from(table); + const sql = ` + SELECT ${columnsStr} + FROM ${table} + LATEST BY ${keyColumnsStr} + `; - if (options?.where !== undefined) { - builder.where(options.where, options.params); - } else if (options?.params && options.params.length > 0) { - throw new Error('params provided to latestBy without a where clause'); - } - - if (options?.timestampColumn !== undefined) { - builder.latestOn(options.timestampColumn, ...keys); - } else { - builder.latestBy(...keys); - } - - return await builder.execute(); + return await this.query(sql); } /** - * Execute ASOF JOIN for time-series correlation. - * `joinCondition` and `where` are treated as trusted SQL fragments. + * Execute ASOF JOIN for time-series correlation */ async asofJoin( - leftTable: TableNames | string, - rightTable: TableNames | string, + leftTable: TableNames, + rightTable: TableNames, joinCondition: string, columns?: string[], where?: string, params?: unknown[] ): Promise> { - const validLeft = assertIdentifier(leftTable, 'left table name'); - const validRight = assertIdentifier(rightTable, 'right table name'); - if (typeof joinCondition !== 'string' || joinCondition.trim().length === 0) { - throw new Error('ASOF JOIN condition must be a non-empty SQL fragment'); - } - let columnsStr = '*'; - if (columns !== undefined) { - if (columns.length === 0) { - throw new Error('SELECT columns cannot be empty'); - } - columnsStr = columns.map(col => assertSelectColumn(col)).join(', '); - } + const columnsStr = columns ? columns.join(', ') : '*'; + const whereClause = where ? `WHERE ${where}` : ''; - let whereClause = ''; - const boundParams = params ? [...params] : []; - if (where !== undefined) { - const validatedWhere = rebaseWhereCondition(where, boundParams, 0); - whereClause = `WHERE ${validatedWhere}`; - } else if (boundParams.length > 0) { - throw new Error('params provided to asofJoin without a where clause'); - } + const sql = ` + SELECT ${columnsStr} + FROM ${leftTable} + ASOF JOIN ${rightTable} ON ${joinCondition} + ${whereClause} + `; - const sql = [ - `SELECT ${columnsStr}`, - `FROM ${validLeft}`, - `ASOF JOIN ${validRight} ON ${joinCondition}`, - whereClause, - ] - .filter(Boolean) - .join(' '); - - return await this.query(sql, boundParams.length > 0 ? boundParams : undefined); + return await this.query(sql, params); } /** @@ -551,7 +320,9 @@ export class QuestDBClient { * Get table information */ async getTableInfo(tableName: string): Promise { - const result = await this.query('SELECT * FROM table_columns($1)', [tableName]); + const result = await this.query(`SELECT * FROM table_columns WHERE table_name = ?`, [ + tableName, + ]); return result.rows; } @@ -603,9 +374,8 @@ export class QuestDBClient { * Optimize table by rebuilding partitions */ async optimizeTable(tableName: string): Promise { - const validTable = assertIdentifier(tableName, 'table name'); - await this.query(`VACUUM TABLE ${validTable}`); - this.logger.debug(`Optimized table: ${validTable}`); + await this.query(`VACUUM TABLE ${tableName}`); + this.logger.debug(`Optimized table: ${tableName}`); } /** @@ -617,19 +387,14 @@ export class QuestDBClient { partitionBy: string = 'DAY', timestampColumn: string = 'timestamp' ): Promise { - const validTable = assertIdentifier(tableName, 'table name'); - const validTimestamp = assertIdentifier(timestampColumn, 'timestamp column'); - if (!ALLOWED_PARTITIONS.has(partitionBy)) { - throw new Error(`Invalid PARTITION BY value: "${String(partitionBy)}"`); - } const sql = ` - CREATE TABLE IF NOT EXISTS ${validTable} ( + CREATE TABLE IF NOT EXISTS ${tableName} ( ${columns} - ) TIMESTAMP(${validTimestamp}) PARTITION BY ${partitionBy} + ) TIMESTAMP(${timestampColumn}) PARTITION BY ${partitionBy} `; await this.query(sql); - this.logger.info(`Created table: ${validTable}`); + this.logger.info(`Created table: ${tableName}`); } /** diff --git a/libs/data/questdb/src/ilp-v2-writer.ts b/libs/data/questdb/src/ilp-v2-writer.ts deleted file mode 100644 index 6917f5b7..00000000 --- a/libs/data/questdb/src/ilp-v2-writer.ts +++ /dev/null @@ -1,550 +0,0 @@ -import type { Bar1mRow } from './types'; - -/** QuestDB ILP v2 binary `DOUBLE` type byte (`16` / `0x10`). */ -export const ILP_V2_DOUBLE_TYPE = 0x10; - -/** Default maximum buffered bytes before flushing a batch (1 MiB). */ -export const DEFAULT_ILP_MAX_BATCH_BYTES = 1_048_576; - -/** Default maximum buffered rows before flushing a batch. */ -export const DEFAULT_ILP_MAX_BATCH_ROWS = 10_000; - -const TABLE_BARS_1M = 'bars_1m'; -const TABLE_FX_1M = 'fx_1m'; - -const INT32_MIN = -2_147_483_648; -const INT32_MAX = 2_147_483_647; -const INT64_MIN = -(2n ** 63n); -const INT64_MAX = 2n ** 63n - 1n; - -const BYTE_SPACE = 0x20; -const BYTE_COMMA = 0x2c; -const BYTE_EQUALS = 0x3d; -const BYTE_LF = 0x0a; -const BYTE_CR = 0x0d; -const BYTE_BACKSLASH = 0x5c; - -const textEncoder = new TextEncoder(); - -const BARS_1M_OPEN_PREFIX = textEncoder.encode(' open=='); -const HIGH_PREFIX = textEncoder.encode(',high=='); -const LOW_PREFIX = textEncoder.encode(',low=='); -const CLOSE_PREFIX = textEncoder.encode(',close=='); -const VOLUME_PREFIX = textEncoder.encode(',volume=='); -const FX_1M_PREFIX = textEncoder.encode(`${TABLE_FX_1M},pair=`); -const FX_1M_SOURCE_PREFIX = textEncoder.encode(',source='); - -/** Valid intraday trading session tags for `bars_1m`. */ -export type Bar1mSession = 'PRE' | 'RTH' | 'POST'; - -/** - * Curated `bars_1m` row input for QuestDB ILP v2 encoding. - * - * Derived from read-side `Bar1mRow` with `vwap` omitted (left NULL in QuestDB) and - * `session` / `source` narrowed to required non-null write values matching `M2_INTRADAY_SCHEMAS.bars_1m`. - */ -export type Bar1mIlpV2Row = Omit & { - session: Bar1mSession; - source: string; -}; - -/** - * Curated `fx_1m` row input for QuestDB ILP v2 encoding. - * - * Matches `M2_INTRADAY_SCHEMAS.fx_1m`: symbols `pair`, `source`; binary doubles - * `open`, `high`, `low`, `close`; designated timestamp `ts` (UTC epoch microseconds). - */ -export interface Fx1mIlpV2Row { - pair: string; - source: string; - open: number; - high: number; - low: number; - close: number; - ts: bigint; -} - -/** Discriminated error kinds for `IlpV2EncodeError`. */ -export type IlpV2EncodeErrorKind = - | 'empty-symbol' - | 'invalid-session' - | 'invalid-listing-id' - | 'non-finite-double' - | 'negative-timestamp' - | 'timestamp-out-of-range'; - -/** - * Typed validation error thrown by `encodeBar1mIlpV2` and `encodeFx1mIlpV2`. - * - * Validation runs atomically before any bytes are encoded or buffered. - */ -export class IlpV2EncodeError extends Error { - public readonly kind: IlpV2EncodeErrorKind; - public readonly field: string; - public readonly value?: number | bigint | string; - - constructor( - kind: IlpV2EncodeErrorKind, - field: string, - message: string, - value?: number | bigint | string - ) { - super(message); - this.name = 'IlpV2EncodeError'; - this.kind = kind; - this.field = field; - if (value !== undefined) { - this.value = value; - } - Object.setPrototypeOf(this, new.target.prototype); - } -} - -/** Injected output port for `createIlpV2BatchWriter`. */ -export interface IlpV2BatchSink { - write(batch: Uint8Array): Promise; -} - -/** Configuration options for `createIlpV2BatchWriter`. */ -export interface IlpV2BatchWriterOptions { - sink: IlpV2BatchSink; - maxBatchBytes?: number; - maxBatchRows?: number; -} - -/** Write summary returned by `IlpV2BatchWriter.finish()`. */ -export interface IlpV2BatchWriterStats { - rows: number; - batches: number; - bytes: number; -} - -/** Pure, sink-injected QuestDB ILP v2 batch writer for `bars_1m` and `fx_1m`. */ -export interface IlpV2BatchWriter { - writeBar1m(row: Bar1mIlpV2Row): Promise; - writeFx1m(row: Fx1mIlpV2Row): Promise; - flush(): Promise; - finish(): Promise; -} - -function validateNonEmptySymbol(field: string, value: string): void { - if (typeof value !== 'string' || value.length === 0) { - throw new IlpV2EncodeError('empty-symbol', field, `empty ILP symbol field '${field}'`); - } -} - -function validateSession(value: Bar1mSession): void { - if (typeof value !== 'string' || value.length === 0) { - throw new IlpV2EncodeError('empty-symbol', 'session', "empty ILP symbol field 'session'"); - } - if (value !== 'PRE' && value !== 'RTH' && value !== 'POST') { - throw new IlpV2EncodeError( - 'invalid-session', - 'session', - `invalid ILP session '${String(value)}' (expected PRE, RTH, or POST)`, - String(value) - ); - } -} - -function validateListingId(value: number): void { - if ( - typeof value !== 'number' || - !Number.isInteger(value) || - value < INT32_MIN || - value > INT32_MAX - ) { - throw new IlpV2EncodeError( - 'invalid-listing-id', - 'listing_id', - `invalid ILP listing_id '${String(value)}' (expected signed 32-bit integer)`, - value - ); - } -} - -function validateFiniteDouble(field: string, value: number): void { - if (typeof value !== 'number' || !Number.isFinite(value)) { - throw new IlpV2EncodeError( - 'non-finite-double', - field, - `non-finite ILP double field '${field}': ${String(value)}`, - value - ); - } -} - -function validateInt64Timestamp(field: string, value: bigint): void { - if (typeof value !== 'bigint' || value < INT64_MIN || value > INT64_MAX) { - throw new IlpV2EncodeError( - 'timestamp-out-of-range', - field, - `ILP timestamp '${field}' out of signed 64-bit range: ${String(value)}`, - typeof value === 'bigint' ? value : undefined - ); - } -} - -function validateDesignatedTimestamp(field: string, value: bigint): void { - validateInt64Timestamp(field, value); - if (value < 0n) { - throw new IlpV2EncodeError( - 'negative-timestamp', - field, - `negative ILP designated timestamp '${field}': ${value.toString(10)} (must be >= 0)`, - value - ); - } -} - -function needsSymbolEscape(byte: number): boolean { - return ( - byte === BYTE_SPACE || - byte === BYTE_COMMA || - byte === BYTE_EQUALS || - byte === BYTE_LF || - byte === BYTE_CR || - byte === BYTE_BACKSLASH - ); -} - -/** - * Escapes an ILP tag/symbol value by prefixing space, `,`, `=`, `\n`, `\r`, and `\` with `\`. - */ -function encodeEscapedSymbol(value: string): Uint8Array { - const raw = textEncoder.encode(value); - let extra = 0; - for (const b of raw) { - if (needsSymbolEscape(b)) { - extra += 1; - } - } - if (extra === 0) { - return raw; - } - - const escaped = new Uint8Array(raw.length + extra); - let out = 0; - for (const b of raw) { - if (needsSymbolEscape(b)) { - escaped[out++] = BYTE_BACKSLASH; - } - escaped[out++] = b; - } - return escaped; -} - -function writeBinaryDoubleField( - out: Uint8Array, - view: DataView, - offset: number, - prefix: Uint8Array, - value: number -): number { - out.set(prefix, offset); - const typeOffset = offset + prefix.byteLength; - out[typeOffset] = ILP_V2_DOUBLE_TYPE; - view.setFloat64(typeOffset + 1, value, true); - return typeOffset + 9; -} - -/** - * Encodes one curated `bars_1m` row in QuestDB ILP v2 format. - * - * Wire contract (byte-for-byte parity with `tools/curate-etl/src/ilp.rs::encode_bar_1m`): - * - Table `bars_1m` - * - Symbols `listing_id` (decimal), `session` (`PRE`/`RTH`/`POST`), `source` (escaped) - * - Binary IEEE-754 little-endian doubles `open`, `high`, `low`, `close`, `volume` (`vwap` omitted) - * - Timestamp column `known_at=t` (signed 64-bit integer preserved as supplied) - * - Designated timestamp ` t\n` (non-negative signed 64-bit integer) - */ -export function encodeBar1mIlpV2(row: Bar1mIlpV2Row): Uint8Array { - validateListingId(row.listing_id); - validateSession(row.session); - validateNonEmptySymbol('source', row.source); - validateFiniteDouble('open', row.open); - validateFiniteDouble('high', row.high); - validateFiniteDouble('low', row.low); - validateFiniteDouble('close', row.close); - validateFiniteDouble('volume', row.volume); - validateInt64Timestamp('known_at', row.known_at); - validateDesignatedTimestamp('ts', row.ts); - - const listingIdDecimal = row.listing_id === 0 ? '0' : String(row.listing_id); - const prefixBytes = textEncoder.encode( - `${TABLE_BARS_1M},listing_id=${listingIdDecimal},session=${row.session},source=` - ); - const escapedSourceBytes = encodeEscapedSymbol(row.source); - const suffixBytes = textEncoder.encode( - `,known_at=${row.known_at.toString(10)}t ${row.ts.toString(10)}t\n` - ); - - // Binary doubles section: ' open==\x10<8>,high==\x10<8>,low==\x10<8>,close==\x10<8>,volume==\x10<8>' - const binaryFieldsLen = - BARS_1M_OPEN_PREFIX.byteLength + - 9 + - HIGH_PREFIX.byteLength + - 9 + - LOW_PREFIX.byteLength + - 9 + - CLOSE_PREFIX.byteLength + - 9 + - VOLUME_PREFIX.byteLength + - 9; - - const out = new Uint8Array( - prefixBytes.byteLength + escapedSourceBytes.byteLength + binaryFieldsLen + suffixBytes.byteLength - ); - const view = new DataView(out.buffer, out.byteOffset, out.byteLength); - - let offset = 0; - out.set(prefixBytes, offset); - offset += prefixBytes.byteLength; - out.set(escapedSourceBytes, offset); - offset += escapedSourceBytes.byteLength; - - offset = writeBinaryDoubleField(out, view, offset, BARS_1M_OPEN_PREFIX, row.open); - offset = writeBinaryDoubleField(out, view, offset, HIGH_PREFIX, row.high); - offset = writeBinaryDoubleField(out, view, offset, LOW_PREFIX, row.low); - offset = writeBinaryDoubleField(out, view, offset, CLOSE_PREFIX, row.close); - offset = writeBinaryDoubleField(out, view, offset, VOLUME_PREFIX, row.volume); - - out.set(suffixBytes, offset); - return out; -} - -/** - * Encodes one `fx_1m` row in QuestDB ILP v2 format. - * - * Wire contract (byte-for-byte parity with `tools/curate-etl/src/ilp.rs::encode_fx_1m`): - * - Table `fx_1m` - * - Symbols `pair` (escaped), `source` (escaped) - * - Binary IEEE-754 little-endian doubles `open`, `high`, `low`, `close` - * - Designated timestamp ` t\n` (non-negative signed 64-bit integer) - */ -export function encodeFx1mIlpV2(row: Fx1mIlpV2Row): Uint8Array { - validateNonEmptySymbol('pair', row.pair); - validateNonEmptySymbol('source', row.source); - validateFiniteDouble('open', row.open); - validateFiniteDouble('high', row.high); - validateFiniteDouble('low', row.low); - validateFiniteDouble('close', row.close); - validateDesignatedTimestamp('ts', row.ts); - - const escapedPairBytes = encodeEscapedSymbol(row.pair); - const escapedSourceBytes = encodeEscapedSymbol(row.source); - const suffixBytes = textEncoder.encode(` ${row.ts.toString(10)}t\n`); - - const binaryFieldsLen = - BARS_1M_OPEN_PREFIX.byteLength + - 9 + - HIGH_PREFIX.byteLength + - 9 + - LOW_PREFIX.byteLength + - 9 + - CLOSE_PREFIX.byteLength + - 9; - - const out = new Uint8Array( - FX_1M_PREFIX.byteLength + - escapedPairBytes.byteLength + - FX_1M_SOURCE_PREFIX.byteLength + - escapedSourceBytes.byteLength + - binaryFieldsLen + - suffixBytes.byteLength - ); - const view = new DataView(out.buffer, out.byteOffset, out.byteLength); - - let offset = 0; - out.set(FX_1M_PREFIX, offset); - offset += FX_1M_PREFIX.byteLength; - out.set(escapedPairBytes, offset); - offset += escapedPairBytes.byteLength; - out.set(FX_1M_SOURCE_PREFIX, offset); - offset += FX_1M_SOURCE_PREFIX.byteLength; - out.set(escapedSourceBytes, offset); - offset += escapedSourceBytes.byteLength; - - offset = writeBinaryDoubleField(out, view, offset, BARS_1M_OPEN_PREFIX, row.open); - offset = writeBinaryDoubleField(out, view, offset, HIGH_PREFIX, row.high); - offset = writeBinaryDoubleField(out, view, offset, LOW_PREFIX, row.low); - offset = writeBinaryDoubleField(out, view, offset, CLOSE_PREFIX, row.close); - - out.set(suffixBytes, offset); - return out; -} - -function assertPositiveIntegerOption(name: string, value: number): void { - if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1) { - throw new RangeError(`ILP v2 batch writer option '${name}' must be a positive integer`); - } -} - -/** - * Creates a pure, sink-injected QuestDB ILP v2 batch writer for `bars_1m` and `fx_1m`. - * - * Operations are serialized in call order so overlapping calls never reorder rows or overlap - * sink writes. Batches always end on whole-row boundaries, fail closed on sink errors, and - * reject writes after `finish()`. - */ -export function createIlpV2BatchWriter(options: IlpV2BatchWriterOptions): IlpV2BatchWriter { - if (!options || !options.sink || typeof options.sink.write !== 'function') { - throw new TypeError('ILP v2 batch writer requires a sink with a write(batch) method'); - } - - const maxBatchBytes = options.maxBatchBytes ?? DEFAULT_ILP_MAX_BATCH_BYTES; - const maxBatchRows = options.maxBatchRows ?? DEFAULT_ILP_MAX_BATCH_ROWS; - assertPositiveIntegerOption('maxBatchBytes', maxBatchBytes); - assertPositiveIntegerOption('maxBatchRows', maxBatchRows); - - const { sink } = options; - - const pendingChunks: Uint8Array[] = []; - let pendingBytes = 0; - let pendingRows = 0; - - let writtenRows = 0; - let writtenBatches = 0; - let writtenBytes = 0; - - let finished = false; - let hasSinkFailure = false; - let sinkFailure: unknown = null; - - let queueTail: Promise = Promise.resolve(); - - function enqueue(operation: () => Promise): Promise { - const result = queueTail.then(operation, operation); - queueTail = result.then( - () => undefined, - () => undefined - ); - return result; - } - - function assertHealthyForMutation(action: string): void { - if (hasSinkFailure) { - throw new Error(`ILP v2 batch writer is closed after a sink write failure (${action})`, { - cause: sinkFailure, - }); - } - if (finished) { - throw new Error(`ILP v2 batch writer is already finished (${action})`); - } - } - - async function flushPending(): Promise { - if (pendingChunks.length === 0) { - return; - } - - const batch = new Uint8Array(pendingBytes); - let offset = 0; - for (const chunk of pendingChunks) { - batch.set(chunk, offset); - offset += chunk.byteLength; - } - - const rowCount = pendingRows; - const byteCount = pendingBytes; - - try { - await sink.write(batch); - } catch (error) { - hasSinkFailure = true; - sinkFailure = error; - pendingChunks.length = 0; - pendingBytes = 0; - pendingRows = 0; - throw error; - } - - pendingChunks.length = 0; - pendingBytes = 0; - pendingRows = 0; - writtenRows += rowCount; - writtenBatches += 1; - writtenBytes += byteCount; - } - - async function enqueueEncodedRow(encoded: Uint8Array): Promise { - if (pendingChunks.length > 0 && pendingBytes + encoded.byteLength > maxBatchBytes) { - await flushPending(); - } - - pendingChunks.push(encoded); - pendingBytes += encoded.byteLength; - pendingRows += 1; - - if (pendingRows >= maxBatchRows || pendingBytes >= maxBatchBytes) { - await flushPending(); - } - } - - function snapshotBar1mRow(row: Bar1mIlpV2Row): Bar1mIlpV2Row { - return { - listing_id: row.listing_id, - ts: row.ts, - known_at: row.known_at, - open: row.open, - high: row.high, - low: row.low, - close: row.close, - volume: row.volume, - session: row.session, - source: row.source, - }; - } - - function snapshotFx1mRow(row: Fx1mIlpV2Row): Fx1mIlpV2Row { - return { - pair: row.pair, - source: row.source, - open: row.open, - high: row.high, - low: row.low, - close: row.close, - ts: row.ts, - }; - } - - return { - writeBar1m(row: Bar1mIlpV2Row): Promise { - const snapshot = snapshotBar1mRow(row); - return enqueue(async () => { - assertHealthyForMutation('writeBar1m'); - const encoded = encodeBar1mIlpV2(snapshot); - await enqueueEncodedRow(encoded); - }); - }, - - writeFx1m(row: Fx1mIlpV2Row): Promise { - const snapshot = snapshotFx1mRow(row); - return enqueue(async () => { - assertHealthyForMutation('writeFx1m'); - const encoded = encodeFx1mIlpV2(snapshot); - await enqueueEncodedRow(encoded); - }); - }, - - flush(): Promise { - return enqueue(async () => { - assertHealthyForMutation('flush'); - await flushPending(); - }); - }, - - finish(): Promise { - return enqueue(async () => { - assertHealthyForMutation('finish'); - await flushPending(); - finished = true; - return { - rows: writtenRows, - batches: writtenBatches, - bytes: writtenBytes, - }; - }); - }, - }; -} diff --git a/libs/data/questdb/src/index.ts b/libs/data/questdb/src/index.ts index 6036ae94..46ab3687 100644 --- a/libs/data/questdb/src/index.ts +++ b/libs/data/questdb/src/index.ts @@ -5,56 +5,27 @@ * InfluxDB Line Protocol, SQL queries, and PostgreSQL wire protocol. */ -export { QuestDBClient, readBars1m } from './client'; +export { QuestDBClient } from './client'; export { QuestDBHealthMonitor } from './health'; export { QuestDBQueryBuilder } from './query-builder'; export { QuestDBInfluxWriter } from './influx-writer'; -export { - createIlpV2BatchWriter, - DEFAULT_ILP_MAX_BATCH_BYTES, - DEFAULT_ILP_MAX_BATCH_ROWS, - encodeBar1mIlpV2, - encodeFx1mIlpV2, - ILP_V2_DOUBLE_TYPE, - IlpV2EncodeError, - type Bar1mIlpV2Row, - type Bar1mSession, - type Fx1mIlpV2Row, - type IlpV2BatchSink, - type IlpV2BatchWriter, - type IlpV2BatchWriterOptions, - type IlpV2BatchWriterStats, - type IlpV2EncodeErrorKind, -} from './ilp-v2-writer'; -export { - formatCreateTableSQL, - getM2IntradayDDL, - M2_INTRADAY_SCHEMAS, - QuestDBSchemaManager, - type M2IntradayTableName, -} from './schema'; +export { QuestDBSchemaManager } from './schema'; // Types export type { - Bar1mRow, - ColumnSchema, - InsertResult, - LatestByOptions, - OHLCVData, - ParameterizedQuery, - PerformanceData, - QueryResult, QuestDBClientConfig, QuestDBConnectionOptions, QuestDBHealthStatus, QuestDBMetrics, - QuestDBQueryable, - QuoteData, - RiskMetrics, TableNames, - TableSchema, + OHLCVData, TradeData, + QuoteData, IndicatorData, + PerformanceData, + RiskMetrics, + QueryResult, + InsertResult, } from './types'; // Note: Factory functions removed - instantiate directly with new QuestDBClient() diff --git a/libs/data/questdb/src/influx-writer.ts b/libs/data/questdb/src/influx-writer.ts index 6f48aae7..90e6145b 100644 --- a/libs/data/questdb/src/influx-writer.ts +++ b/libs/data/questdb/src/influx-writer.ts @@ -11,9 +11,6 @@ interface QuestDBClientInterface { * * Provides high-performance data ingestion using InfluxDB Line Protocol * which QuestDB supports natively for optimal time-series data insertion. - * - * @deprecated Legacy text-ILP writer. Use `createIlpV2BatchWriter` (from `./ilp-v2-writer`) - * for QuestDB ILP v2 binary-double ingestion into `bars_1m` and `fx_1m`. */ export class QuestDBInfluxWriter { private readonly logger: ReturnType; diff --git a/libs/data/questdb/src/query-builder.ts b/libs/data/questdb/src/query-builder.ts index 652c75a3..7ebb56f1 100644 --- a/libs/data/questdb/src/query-builder.ts +++ b/libs/data/questdb/src/query-builder.ts @@ -1,272 +1,32 @@ import type { QueryResultRow } from 'pg'; import { getLogger } from '@stock-bot/logger'; -import type { - ParameterizedQuery, - QueryResult, - QuestDBQueryable, - TableNames, - TimeRange, -} from './types'; +import type { QueryResult, TableNames, TimeRange } from './types'; -const IDENTIFIER_RE = /^[A-Za-z_][A-Za-z0-9_]*$/; -const SAMPLE_INTERVAL_RE = /^\d+[UTsmhdwMy]$/; - -/** - * Validate a SQL identifier (table, column, alias, or timestamp column). - */ -export function assertIdentifier(value: string, label: string): string { - if (typeof value !== 'string' || !IDENTIFIER_RE.test(value)) { - throw new Error(`Invalid ${label}: "${String(value)}"`); - } - return value; -} - -/** - * Validate a projection column (literal `*` or strict SQL identifier). - */ -export function assertSelectColumn(value: string): string { - if (value === '*') { - return value; - } - return assertIdentifier(value, 'SELECT column'); -} - -/** - * Validate a QuestDB SAMPLE BY interval (e.g. `1m`, `5m`, `1h`, `1d`). - */ -export function assertSampleInterval(value: string): string { - if (typeof value !== 'string' || !SAMPLE_INTERVAL_RE.test(value)) { - throw new Error(`Invalid SAMPLE BY interval: "${String(value)}"`); - } - return value; -} - -/** - * Validate a SQL sort direction. - */ -export function assertSortDirection(value: string): 'ASC' | 'DESC' { - if (value !== 'ASC' && value !== 'DESC') { - throw new Error(`Invalid ORDER BY direction: "${String(value)}"`); - } - return value; -} - -/** - * Resolve the default designated timestamp column for a QuestDB table. - */ -export function defaultTimestampColumnForTable(table: string): string { - switch (table) { - case 'bars_1m': - case 'fx_1m': - return 'ts'; - case 'bar_revisions': - return 'revised_at'; - default: - return 'timestamp'; - } -} - -/** - * Offset fragment-local `$1..$k` placeholders in a trusted SQL WHERE fragment by `offset`. - * Preserves repeated references and ignores `$n` inside single/double quotes and SQL comments. - * Rejects `$0`, out-of-range placeholders, and unused parameters. - */ -export function rebaseWhereCondition( - condition: string, - params: readonly unknown[] = [], - offset: number = 0 -): string { - if (typeof condition !== 'string' || condition.trim().length === 0) { - throw new Error('WHERE condition must be a non-empty SQL string'); - } - - const usedIndices = new Set(); - let out = ''; - let i = 0; - - while (i < condition.length) { - const ch = condition.charAt(i); - const next = condition.charAt(i + 1); - - // Single-quoted string literal ('...' with '' escape) - if (ch === "'") { - out += ch; - i += 1; - let closed = false; - while (i < condition.length) { - const cur = condition.charAt(i); - out += cur; - i += 1; - if (cur === "'") { - if (condition.charAt(i) === "'") { - out += "'"; - i += 1; - } else { - closed = true; - break; - } - } - } - if (!closed) { - throw new Error('Unterminated string literal in WHERE condition'); - } - continue; - } - - // Double-quoted identifier ("..." with "" escape) - if (ch === '"') { - out += ch; - i += 1; - let closed = false; - while (i < condition.length) { - const cur = condition.charAt(i); - out += cur; - i += 1; - if (cur === '"') { - if (condition.charAt(i) === '"') { - out += '"'; - i += 1; - } else { - closed = true; - break; - } - } - } - if (!closed) { - throw new Error('Unterminated quoted identifier in WHERE condition'); - } - continue; - } - - // Line comment (-- ... \n); terminate at EOF so subsequent clauses are never swallowed - if (ch === '-' && next === '-') { - out += '--'; - i += 2; - let sawNewline = false; - while (i < condition.length) { - const cur = condition.charAt(i); - out += cur; - i += 1; - if (cur === '\n') { - sawNewline = true; - break; - } - } - if (!sawNewline) { - out += '\n'; - } - continue; - } - - // Block comment (/* ... */) - if (ch === '/' && next === '*') { - out += '/*'; - i += 2; - let closed = false; - while (i < condition.length) { - if (condition.charAt(i) === '*' && condition.charAt(i + 1) === '/') { - out += '*/'; - i += 2; - closed = true; - break; - } - out += condition.charAt(i); - i += 1; - } - if (!closed) { - throw new Error('Unterminated block comment in WHERE condition'); - } - continue; - } - - // Parameter placeholder ($1, $2, ..., $10, ...) - if (ch === '$' && next >= '0' && next <= '9') { - const prev = i > 0 ? condition.charAt(i - 1) : ''; - const isPartOfIdentifier = /[A-Za-z0-9_]/.test(prev); - if (!isPartOfIdentifier) { - let j = i + 1; - while (j < condition.length) { - const digit = condition.charAt(j); - if (digit < '0' || digit > '9') { - break; - } - j += 1; - } - const digits = condition.slice(i + 1, j); - const index = Number(digits); - if (!Number.isSafeInteger(index) || index < 1) { - throw new Error(`Invalid parameter placeholder $${digits}: placeholders are 1-based`); - } - if (index > params.length) { - throw new Error( - `Parameter placeholder $${index} is out of range for ${params.length} provided parameter(s)` - ); - } - usedIndices.add(index); - out += `$${offset + index}`; - i = j; - continue; - } - } - - out += ch; - i += 1; - } - - for (let idx = 1; idx <= params.length; idx += 1) { - if (!usedIndices.has(idx)) { - throw new Error(`Unused parameter at index ${idx} in WHERE condition`); - } - } - - return out; -} - -interface WherePredicate { - sql: string; - params: unknown[]; -} - -interface LatestOnClause { - timestampColumn?: string; - partitionBy: string[]; -} - -function assertValidDate(value: Date, label: string): Date { - if (!(value instanceof Date) || Number.isNaN(value.getTime())) { - throw new Error(`Invalid ${label}: expected a valid Date`); - } - return value; -} - -function assertPositiveInteger(value: number, label: string): number { - if (!Number.isInteger(value) || value <= 0) { - throw new Error(`Invalid ${label}: expected a positive integer, received ${String(value)}`); - } - return value; +// Interface to avoid circular dependency +interface QuestDBClientInterface { + query(sql: string, params?: unknown[]): Promise>; } /** * QuestDB Query Builder * - * Provides a fluent interface for building parameterized PGWire time-series queries - * with support for QuestDB 10.2.0 SQL clauses (`LATEST ON`, `SAMPLE BY`). + * Provides a fluent interface for building optimized time-series queries + * with support for QuestDB-specific functions and optimizations. */ export class QuestDBQueryBuilder { private readonly logger: ReturnType; private query!: { select: string[]; from: string; - where: WherePredicate[]; + where: string[]; groupBy: string[]; orderBy: string[]; limit?: number; sampleBy?: string; - latestOn?: LatestOnClause; + latestBy?: string[]; timeRange?: TimeRange; }; - - constructor(private readonly client: QuestDBQueryable) { + constructor(private readonly client: QuestDBClientInterface) { this.logger = getLogger('questdb-query-builder'); this.reset(); } @@ -281,263 +41,193 @@ export class QuestDBQueryBuilder { where: [], groupBy: [], orderBy: [], - limit: undefined, sampleBy: undefined, - latestOn: undefined, + latestBy: undefined, timeRange: undefined, }; return this; } - /** * Start a new query */ - public static create(client: QuestDBQueryable): QuestDBQueryBuilder { + public static create(client: QuestDBClientInterface): QuestDBQueryBuilder { return new QuestDBQueryBuilder(client); } /** - * Select columns (`*` or validated SQL identifiers) + * Select columns */ public select(...columns: string[]): QuestDBQueryBuilder { - const validated = columns.map(col => assertSelectColumn(col)); - this.query.select.push(...validated); + this.query.select.push(...columns); return this; } /** - * Select with aggregation functions. - * Aliases are validated as SQL identifiers; aggregation expressions are treated as trusted SQL fragments. + * Select with aggregation functions */ public selectAgg(aggregations: Record): QuestDBQueryBuilder { - const validatedEntries = Object.entries(aggregations).map(([alias, expression]) => { - const validAlias = assertIdentifier(alias, 'aggregation alias'); - if (typeof expression !== 'string' || expression.trim().length === 0) { - throw new Error(`Invalid aggregation expression for alias "${validAlias}"`); - } - return `${expression} as ${validAlias}`; + Object.entries(aggregations).forEach(([alias, expression]) => { + this.query.select.push(`${expression} as ${alias}`); }); - this.query.select.push(...validatedEntries); return this; } /** - * From table (validated SQL identifier) + * From table */ public from(table: TableNames | string): QuestDBQueryBuilder { - this.query.from = assertIdentifier(table, 'table name'); + this.query.from = table; return this; } /** - * Raw WHERE predicate (trusted SQL fragment escape hatch). - * Supports fragment-local `$1..$n` placeholders, which are renumbered automatically during build. + * Where condition */ - public where(condition: string, params?: unknown[]): QuestDBQueryBuilder { - const boundParams = params ? [...params] : []; - // Validate fragment syntax and parameter indices eagerly before mutating builder state. - rebaseWhereCondition(condition, boundParams, 0); - this.query.where.push({ sql: condition, params: boundParams }); + public where(condition: string): QuestDBQueryBuilder { + this.query.where.push(condition); return this; } /** - * Where symbol equals (bound parameter) + * Where symbol equals */ public whereSymbol(symbol: string): QuestDBQueryBuilder { - this.query.where.push({ sql: 'symbol = $1', params: [symbol] }); + this.query.where.push(`symbol = '${symbol}'`); return this; } /** - * Where symbols in list (one bound parameter per element; rejects empty lists) + * Where symbols in list */ public whereSymbolIn(symbols: string[]): QuestDBQueryBuilder { - if (symbols.length === 0) { - throw new Error('whereSymbolIn requires at least one symbol'); - } - const placeholders = symbols.map((_, index) => `$${index + 1}`).join(', '); - this.query.where.push({ - sql: `symbol IN (${placeholders})`, - params: [...symbols], - }); + const symbolList = symbols.map(s => `'${s}'`).join(', '); + this.query.where.push(`symbol IN (${symbolList})`); return this; } /** - * Where exchange equals (bound parameter) + * Where exchange equals */ public whereExchange(exchange: string): QuestDBQueryBuilder { - this.query.where.push({ sql: 'exchange = $1', params: [exchange] }); + this.query.where.push(`exchange = '${exchange}'`); return this; } /** - * Time range filter with inclusive bounds (bound UTC ISO-8601 parameters) + * Time range filter */ public whereTimeRange(startTime: Date, endTime: Date): QuestDBQueryBuilder { - const validStart = assertValidDate(startTime, 'startTime'); - const validEnd = assertValidDate(endTime, 'endTime'); - this.query.timeRange = { startTime: validStart, endTime: validEnd }; - this.query.where.push({ - sql: 'timestamp >= $1 AND timestamp <= $2', - params: [validStart.toISOString(), validEnd.toISOString()], - }); + this.query.timeRange = { startTime, endTime }; + this.query.where.push( + `timestamp >= '${startTime.toISOString()}' AND timestamp <= '${endTime.toISOString()}'` + ); return this; } /** - * Last N hours (bound negative hour offset) + * Last N hours */ public whereLastHours(hours: number): QuestDBQueryBuilder { - const validHours = assertPositiveInteger(hours, 'hours'); - this.query.where.push({ - sql: "timestamp > dateadd('h', $1, now())", - params: [-validHours], - }); + this.query.where.push(`timestamp > dateadd('h', -${hours}, now())`); return this; } /** - * Last N days (bound negative day offset) + * Last N days */ public whereLastDays(days: number): QuestDBQueryBuilder { - const validDays = assertPositiveInteger(days, 'days'); - this.query.where.push({ - sql: "timestamp > dateadd('d', $1, now())", - params: [-validDays], - }); + this.query.where.push(`timestamp > dateadd('d', -${days}, now())`); return this; } /** - * Group by columns (validated SQL identifiers) + * Group by columns */ public groupBy(...columns: string[]): QuestDBQueryBuilder { - const validated = columns.map(col => assertIdentifier(col, 'GROUP BY column')); - this.query.groupBy.push(...validated); + this.query.groupBy.push(...columns); return this; } /** - * Order by column (validated identifier and direction) + * Order by column */ public orderBy(column: string, direction: 'ASC' | 'DESC' = 'ASC'): QuestDBQueryBuilder { - const validColumn = assertIdentifier(column, 'ORDER BY column'); - const validDirection = assertSortDirection(direction); - this.query.orderBy.push(`${validColumn} ${validDirection}`); + this.query.orderBy.push(`${column} ${direction}`); return this; } /** * Order by timestamp descending (most recent first) */ - public orderByTimeDesc(timestampColumn: string = 'timestamp'): QuestDBQueryBuilder { - const validColumn = assertIdentifier(timestampColumn, 'ORDER BY column'); - this.query.orderBy.push(`${validColumn} DESC`); + public orderByTimeDesc(): QuestDBQueryBuilder { + this.query.orderBy.push('timestamp DESC'); return this; } /** - * Limit results (bound non-negative integer parameter) + * Limit results */ public limit(count: number): QuestDBQueryBuilder { - if (!Number.isInteger(count) || count < 0) { - throw new Error(`Invalid LIMIT count: expected a non-negative integer, received ${String(count)}`); - } this.query.limit = count; return this; } /** - * Sample by time interval (QuestDB specific, validated interval) + * Sample by time interval (QuestDB specific) */ public sampleBy(interval: string): QuestDBQueryBuilder { - this.query.sampleBy = assertSampleInterval(interval); + this.query.sampleBy = interval; return this; } /** - * QuestDB 10.2.0 `LATEST ON PARTITION BY ` with explicit timestamp column. + * Latest by columns (QuestDB specific) */ - public latestOn(timestampColumn: string, ...partitionByColumns: string[]): QuestDBQueryBuilder { - const validTs = assertIdentifier(timestampColumn, 'LATEST ON timestamp column'); - if (partitionByColumns.length === 0) { - throw new Error('latestOn requires at least one partition column'); - } - const validKeys = partitionByColumns.map(col => - assertIdentifier(col, 'LATEST ON partition column') - ); - this.query.latestOn = { - timestampColumn: validTs, - partitionBy: validKeys, - }; + public latestBy(...columns: string[]): QuestDBQueryBuilder { + this.query.latestBy = columns; return this; } /** - * Convenience wrapper emitting `LATEST ON PARTITION BY `. - * Uses `ts` for `bars_1m`/`fx_1m`, `revised_at` for `bar_revisions`, and `timestamp` for legacy tables. - */ - public latestBy(...partitionByColumns: string[]): QuestDBQueryBuilder { - if (partitionByColumns.length === 0) { - throw new Error('latestBy requires at least one partition column'); - } - const validKeys = partitionByColumns.map(col => - assertIdentifier(col, 'LATEST ON partition column') - ); - this.query.latestOn = { - timestampColumn: undefined, - partitionBy: validKeys, - }; - return this; - } - - /** - * Build and execute the parameterized query + * Build and execute the query */ public async execute(): Promise> { - let built: ParameterizedQuery | undefined; + const sql = this.build(); + this.logger.debug('Executing query', { sql }); + try { - built = this.buildParameterized(); - this.logger.debug('Executing query', { sql: built.sql, paramCount: built.params.length }); - return await this.client.query(built.sql, built.params); + const result = await this.client.query(sql); + this.reset(); // Reset for next query + return result; } catch (error) { - this.logger.error('Query execution failed', { sql: built?.sql, error }); + this.logger.error('Query execution failed', { sql, error }); + this.reset(); // Reset even on error throw error; - } finally { - this.reset(); } } /** - * Build the parameterized SQL query and ordered parameter list (`$1..$n`). + * Build the SQL query string */ - public buildParameterized(): ParameterizedQuery { + public build(): string { if (!this.query.from) { throw new Error('FROM clause is required'); } - const selectColumns = this.query.select.length > 0 ? this.query.select : ['*']; - const params: unknown[] = []; - - let sql = `SELECT ${selectColumns.join(', ')} FROM ${this.query.from}`; - - // Add WHERE clause with consecutively renumbered $1..$n placeholders - if (this.query.where.length > 0) { - const renderedPredicates = this.query.where.map(predicate => { - const rebased = rebaseWhereCondition(predicate.sql, predicate.params, params.length); - params.push(...predicate.params); - return rebased; - }); - sql += ` WHERE ${renderedPredicates.join(' AND ')}`; + if (this.query.select.length === 0) { + this.query.select.push('*'); } - // Add LATEST ON (QuestDB 10.2.0 - placed after WHERE, before SAMPLE BY / GROUP BY) - if (this.query.latestOn && this.query.latestOn.partitionBy.length > 0) { - const tsColumn = - this.query.latestOn.timestampColumn ?? defaultTimestampColumnForTable(this.query.from); - sql += ` LATEST ON ${tsColumn} PARTITION BY ${this.query.latestOn.partitionBy.join(', ')}`; + let sql = `SELECT ${this.query.select.join(', ')} FROM ${this.query.from}`; + + // Add WHERE clause + if (this.query.where.length > 0) { + sql += ` WHERE ${this.query.where.join(' AND ')}`; + } + + // Add LATEST BY (QuestDB specific - must come before GROUP BY) + if (this.query.latestBy && this.query.latestBy.length > 0) { + sql += ` LATEST BY ${this.query.latestBy.join(', ')}`; } // Add SAMPLE BY (QuestDB specific) @@ -555,36 +245,27 @@ export class QuestDBQueryBuilder { sql += ` ORDER BY ${this.query.orderBy.join(', ')}`; } - // Add LIMIT (bound parameter) - if (this.query.limit !== undefined) { - params.push(this.query.limit); - sql += ` LIMIT $${params.length}`; + // Add LIMIT + if (this.query.limit) { + sql += ` LIMIT ${this.query.limit}`; } - return { sql, params }; + return sql; } /** - * Build the SQL query string (placeholder view of `buildParameterized().sql`) - */ - public build(): string { - return this.buildParameterized().sql; - } - - /** - * Get the built query string without executing + * Get the built query without executing */ public toSQL(): string { return this.build(); } // Predefined query methods for common use cases - /** * Get latest OHLCV data for symbols */ public static latestOHLCV( - client: QuestDBQueryable, + client: QuestDBClientInterface, symbols: string[], exchange?: string ): QuestDBQueryBuilder { @@ -601,12 +282,11 @@ export class QuestDBQueryBuilder { return builder; } - /** * Get OHLCV data with time sampling */ public static ohlcvTimeSeries( - client: QuestDBQueryable, + client: QuestDBClientInterface, symbol: string, interval: string, hours: number = 24 @@ -625,12 +305,11 @@ export class QuestDBQueryBuilder { .sampleBy(interval) .orderByTimeDesc(); } - /** * Get market analytics data */ public static marketAnalytics( - client: QuestDBQueryable, + client: QuestDBClientInterface, symbols: string[], hours: number = 1 ): QuestDBQueryBuilder { @@ -650,12 +329,11 @@ export class QuestDBQueryBuilder { .orderBy('symbol') .orderByTimeDesc(); } - /** * Get performance metrics for a time range */ public static performanceMetrics( - client: QuestDBQueryable, + client: QuestDBClientInterface, startTime: Date, endTime: Date ): QuestDBQueryBuilder { @@ -670,12 +348,11 @@ export class QuestDBQueryBuilder { .whereTimeRange(startTime, endTime) .sampleBy('1m'); } - /** * Get trade execution data */ public static tradeExecutions( - client: QuestDBQueryable, + client: QuestDBClientInterface, symbol?: string, hours: number = 24 ): QuestDBQueryBuilder { diff --git a/libs/data/questdb/src/schema.ts b/libs/data/questdb/src/schema.ts index 6e8458d2..55ca7e81 100644 --- a/libs/data/questdb/src/schema.ts +++ b/libs/data/questdb/src/schema.ts @@ -1,147 +1,11 @@ import type { QueryResultRow } from 'pg'; import { at } from '@stock-bot/invariants'; import { getLogger } from '@stock-bot/logger'; -import { assertIdentifier } from './query-builder'; -import type { ColumnSchema, QuestDBQueryable, TableSchema } from './types'; +import type { QueryResult, TableSchema } from './types'; -export type M2IntradayTableName = 'bars_1m' | 'fx_1m' | 'bar_revisions'; - -/** - * Contract schemas for M2 QuestDB 10.2.0 intraday tables (`design/DATA-CONTRACTS.md` §3.B). - * Kept opt-in (outside `QuestDBSchemaManager.initializeDatabase()`). - */ -export const M2_INTRADAY_SCHEMAS: Readonly> = { - bars_1m: { - tableName: 'bars_1m', - columns: [ - { name: 'listing_id', type: 'SYMBOL', capacity: 65536, cache: false }, - { name: 'open', type: 'DOUBLE' }, - { name: 'high', type: 'DOUBLE' }, - { name: 'low', type: 'DOUBLE' }, - { name: 'close', type: 'DOUBLE' }, - { name: 'volume', type: 'DOUBLE' }, - { name: 'vwap', type: 'DOUBLE' }, - { name: 'session', type: 'SYMBOL', capacity: 8, cache: true }, - { name: 'source', type: 'SYMBOL', capacity: 8, cache: true }, - { name: 'known_at', type: 'TIMESTAMP' }, - { name: 'ts', type: 'TIMESTAMP', designated: true }, - ], - partitionBy: 'MONTH', - wal: true, - dedupUpsertKeys: ['ts', 'listing_id'], - }, - fx_1m: { - tableName: 'fx_1m', - columns: [ - { name: 'pair', type: 'SYMBOL', capacity: 32, cache: true }, - { name: 'open', type: 'DOUBLE' }, - { name: 'high', type: 'DOUBLE' }, - { name: 'low', type: 'DOUBLE' }, - { name: 'close', type: 'DOUBLE' }, - { name: 'source', type: 'SYMBOL', capacity: 8, cache: true }, - { name: 'ts', type: 'TIMESTAMP', designated: true }, - ], - partitionBy: 'MONTH', - wal: true, - dedupUpsertKeys: ['ts', 'pair'], - }, - bar_revisions: { - tableName: 'bar_revisions', - columns: [ - { name: 'listing_id', type: 'SYMBOL', capacity: 65536, cache: false }, - { name: 'timeframe', type: 'SYMBOL', capacity: 8, cache: true }, - { name: 'bar_ts', type: 'TIMESTAMP' }, - { name: 'prev_close', type: 'DOUBLE' }, - { name: 'new_close', type: 'DOUBLE' }, - { name: 'prev_volume', type: 'DOUBLE' }, - { name: 'new_volume', type: 'DOUBLE' }, - { name: 'revised_at', type: 'TIMESTAMP', designated: true }, - ], - partitionBy: 'MONTH', - wal: true, - }, -}; - -function formatColumnDDL(col: ColumnSchema): string { - const name = assertIdentifier(col.name, 'column name'); - let def = `${name} ${col.type}`; - - if (col.type === 'SYMBOL') { - if (col.capacity !== undefined) { - if (!Number.isInteger(col.capacity) || col.capacity <= 0) { - throw new Error( - `Invalid SYMBOL capacity for column "${name}": expected positive integer, received ${String(col.capacity)}` - ); - } - def += ` CAPACITY ${col.capacity}`; - } - if (col.cache === true) { - def += ' CACHE'; - } else if (col.cache === false) { - def += ' NOCACHE'; - } - } - - return def; -} - -/** - * Pure QuestDB CREATE TABLE DDL formatter shared by legacy schemas and M2 contract tables. - */ -export function formatCreateTableSQL(schema: TableSchema): string { - const tableName = assertIdentifier(schema.tableName, 'table name'); - if (!schema.columns || schema.columns.length === 0) { - throw new Error('At least one column is required'); - } - - const columnNames = new Set(schema.columns.map(col => assertIdentifier(col.name, 'column name'))); - // QuestDB's column grammar has no PostgreSQL-style NOT NULL constraint. - // nullable remains descriptive metadata; the designated timestamp is declared below. - const columns = schema.columns.map(formatColumnDDL).join(', '); - - let sql = `CREATE TABLE IF NOT EXISTS ${tableName} (${columns})`; - - const timestampColumns = schema.columns.filter(col => col.designated); - if (timestampColumns.length > 1) { - throw new Error('Only one designated timestamp column is allowed'); - } - const timestampColumn = timestampColumns[0]; - if (timestampColumn) { - sql += ` TIMESTAMP(${assertIdentifier(timestampColumn.name, 'designated timestamp column')})`; - } - - if (schema.partitionBy) { - sql += ` PARTITION BY ${schema.partitionBy}`; - } - - if (schema.wal) { - sql += ' WAL'; - } - - if (schema.dedupUpsertKeys && schema.dedupUpsertKeys.length > 0) { - const keys = schema.dedupUpsertKeys.map(key => { - const validKey = assertIdentifier(key, 'DEDUP UPSERT key'); - if (!columnNames.has(validKey)) { - throw new Error(`DEDUP UPSERT key "${validKey}" does not exist on table "${tableName}"`); - } - return validKey; - }); - sql += ` DEDUP UPSERT KEYS(${keys.join(', ')})`; - } - - return sql; -} - -/** - * Return the QuestDB 10.2.0 DDL statements for `bars_1m`, `fx_1m`, and `bar_revisions`. - * Pure offline helper; requires no database connection. - */ -export function getM2IntradayDDL(): Record { - return { - bars_1m: formatCreateTableSQL(M2_INTRADAY_SCHEMAS.bars_1m), - fx_1m: formatCreateTableSQL(M2_INTRADAY_SCHEMAS.fx_1m), - bar_revisions: formatCreateTableSQL(M2_INTRADAY_SCHEMAS.bar_revisions), - }; +// Interface to avoid circular dependency +interface QuestDBClientInterface { + query(sql: string, params?: unknown[]): Promise>; } /** @@ -153,7 +17,7 @@ export function getM2IntradayDDL(): Record { export class QuestDBSchemaManager { private readonly logger: ReturnType; private readonly schemas: Map = new Map(); - constructor(private readonly client: QuestDBQueryable) { + constructor(private readonly client: QuestDBClientInterface) { this.logger = getLogger('questdb-schema-manager'); this.initializeSchemas(); } @@ -331,14 +195,13 @@ export class QuestDBSchemaManager { * Drop a table */ public async dropTable(tableName: string): Promise { - const validTable = assertIdentifier(tableName, 'table name'); - const sql = `DROP TABLE IF EXISTS ${validTable}`; + const sql = `DROP TABLE IF EXISTS ${tableName}`; try { await this.client.query(sql); - this.logger.warn(`Table ${validTable} dropped`); + this.logger.warn(`Table ${tableName} dropped`); } catch (error) { - this.logger.error(`Failed to drop table ${validTable}`, error); + this.logger.error(`Failed to drop table ${tableName}`, error); throw error; } } @@ -348,12 +211,13 @@ export class QuestDBSchemaManager { */ public async tableExists(tableName: string): Promise { try { - const result = await this.client.query<{ count: number | string }>( - 'SELECT COUNT(*) as count FROM tables() WHERE table_name = $1', - [tableName] - ); + const result = await this.client.query(` + SELECT COUNT(*) as count + FROM information_schema.tables + WHERE table_name = '${tableName}' + `); - return result.rows.length > 0 && Number(at(result.rows, 0).count) > 0; + return result.rows.length > 0 && at(result.rows, 0).count > 0; } catch (error) { this.logger.error(`Error checking if table exists: ${tableName}`, error); return false; @@ -405,19 +269,18 @@ export class QuestDBSchemaManager { * Get table statistics */ public async getTableStats(tableName: string): Promise { - const validTable = assertIdentifier(tableName, 'table name'); try { const result = await this.client.query(` SELECT COUNT(*) as row_count, MIN(timestamp) as min_timestamp, MAX(timestamp) as max_timestamp - FROM ${validTable} + FROM ${tableName} `); return result.rows[0] || {}; } catch (error) { - this.logger.error(`Failed to get table stats for ${validTable}`, error); + this.logger.error(`Failed to get table stats for ${tableName}`, error); throw error; } } @@ -426,12 +289,11 @@ export class QuestDBSchemaManager { * Truncate table (remove all data but keep structure) */ public async truncateTable(tableName: string): Promise { - const validTable = assertIdentifier(tableName, 'table name'); try { - await this.client.query(`TRUNCATE TABLE ${validTable}`); - this.logger.warn(`Table ${validTable} truncated`); + await this.client.query(`TRUNCATE TABLE ${tableName}`); + this.logger.warn(`Table ${tableName} truncated`); } catch (error) { - this.logger.error(`Failed to truncate table ${validTable}`, error); + this.logger.error(`Failed to truncate table ${tableName}`, error); throw error; } } @@ -449,7 +311,27 @@ export class QuestDBSchemaManager { * Build CREATE TABLE SQL statement */ private buildCreateTableSQL(schema: TableSchema): string { - return formatCreateTableSQL(schema); + // QuestDB's column grammar has no PostgreSQL-style NOT NULL constraint. + // nullable remains descriptive metadata; the designated timestamp is declared + // below. See https://questdb.com/docs/query/sql/create-table/. + const columns = schema.columns + .map(col => `${col.name} ${col.type}`) + .join(', '); + + let sql = `CREATE TABLE IF NOT EXISTS ${schema.tableName} (${columns})`; + + // Add designated timestamp + const timestampColumn = schema.columns.find(col => col.designated); + if (timestampColumn) { + sql += ` TIMESTAMP(${timestampColumn.name})`; + } + + // Add partition by + if (schema.partitionBy) { + sql += ` PARTITION BY ${schema.partitionBy}`; + } + + return sql; } /** diff --git a/libs/data/questdb/src/types.ts b/libs/data/questdb/src/types.ts index f52d6192..5aec03c7 100644 --- a/libs/data/questdb/src/types.ts +++ b/libs/data/questdb/src/types.ts @@ -62,54 +62,7 @@ export type TableNames = | 'risk_metrics' | 'market_events' | 'strategy_signals' - | 'portfolio_snapshots' - | 'bars_1m' - | 'fx_1m' - | 'bar_revisions'; - -/** - * Shared minimal query executor interface for QuestDB helpers. - */ -export interface QuestDBQueryable { - query(sql: string, params?: unknown[]): Promise>; -} - -/** - * Parameterized PGWire SQL query and ordered bound parameters ($1..$n). - */ -export interface ParameterizedQuery { - sql: string; - params: unknown[]; -} - -/** - * Options for QuestDBClient.latestBy(). - */ -export interface LatestByOptions { - timestampColumn?: string; - where?: string; - params?: unknown[]; -} - -/** - * Typed 1-minute bar row returned from QuestDB `bars_1m`. - * - `listing_id` is stored as decimal string SYMBOL in QuestDB and converted to INT32 at read boundary. - * - `known_at` and `ts` are lossless UTC epoch microseconds (`bigint`) projected via `CAST(... AS LONG)` - * to preserve all 6 fractional digits and avoid PGWire local-timezone `Date` coercion. - */ -export interface Bar1mRow { - listing_id: number; - open: number; - high: number; - low: number; - close: number; - volume: number; - vwap: number | null; - session: string | null; - source: string | null; - known_at: bigint; - ts: bigint; -} + | 'portfolio_snapshots'; /** * Time-Series Data Types @@ -261,14 +214,12 @@ export interface TableSchema { tableName: string; columns: ColumnSchema[]; partitionBy?: 'NONE' | 'HOUR' | 'DAY' | 'MONTH' | 'YEAR'; - wal?: boolean; - dedupUpsertKeys?: string[]; orderBy?: string[]; indices?: IndexDefinition[]; dedup?: boolean; } -export interface ColumnSchema { +interface ColumnSchema { name: string; type: | 'SYMBOL' @@ -284,7 +235,6 @@ export interface ColumnSchema { nullable?: boolean; designated?: boolean; // For designated timestamp column capacity?: number; // For SYMBOL type - cache?: boolean; // For SYMBOL type: true -> CACHE, false -> NOCACHE indexed?: boolean; } diff --git a/libs/data/questdb/test/ilp-v2-writer-edges.test.ts b/libs/data/questdb/test/ilp-v2-writer-edges.test.ts deleted file mode 100644 index d43bd8ae..00000000 --- a/libs/data/questdb/test/ilp-v2-writer-edges.test.ts +++ /dev/null @@ -1,426 +0,0 @@ -import { describe, expect, it } from 'bun:test'; -import { - createIlpV2BatchWriter, - DEFAULT_ILP_MAX_BATCH_BYTES, - DEFAULT_ILP_MAX_BATCH_ROWS, - encodeBar1mIlpV2, - encodeFx1mIlpV2, - IlpV2EncodeError, - type Bar1mIlpV2Row, - type Bar1mSession, - type Fx1mIlpV2Row, - type IlpV2BatchSink, -} from '../src/index'; - -const encoder = new TextEncoder(); - -function asciiBytes(text: string): number[] { - return Array.from(encoder.encode(text)); -} - -function concatBytes(chunks: readonly Uint8Array[]): Uint8Array { - const total = chunks.reduce((sum, c) => sum + c.byteLength, 0); - const out = new Uint8Array(total); - let offset = 0; - for (const chunk of chunks) { - out.set(chunk, offset); - offset += chunk.byteLength; - } - return out; -} - -function sampleBar(overrides: Partial = {}): Bar1mIlpV2Row { - return { - listing_id: 42, - ts: 1_736_951_400_000_000n, - known_at: 1_736_951_460_000_000n, - open: 123.45, - high: 125.75, - low: 122.125, - close: 124.5, - volume: 98_765.0, - session: 'RTH', - source: 'eod_unadj', - ...overrides, - }; -} - -function sampleFx(overrides: Partial = {}): Fx1mIlpV2Row { - return { - pair: 'USD.CAD', - source: 'eod', - open: 1.3625, - high: 1.365, - low: 1.36125, - close: 1.364375, - ts: 1_736_951_400_000_000n, - ...overrides, - }; -} - -function expectEncodeError(fn: () => unknown, kind: IlpV2EncodeError['kind'], field: string) { - let caught: unknown; - try { - fn(); - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(IlpV2EncodeError); - expect((caught as IlpV2EncodeError).kind).toBe(kind); - expect((caught as IlpV2EncodeError).field).toBe(field); -} - -describe('ILP v2 encoder edge cases', () => { - it('matches golden_bytes_literal_ieee754_little_endian_without_to_le_bytes with hand-written bytes', () => { - // Mirrors `golden_bytes_literal_ieee754_little_endian_without_to_le_bytes` - // in `tools/curate-etl/src/ilp_tests.rs` (key 7, source eod_unadj). - const actual = encodeBar1mIlpV2({ - listing_id: 7, - ts: 1_700_000_000_000_000n, - known_at: 1_700_000_060_000_000n, - open: 1.0, - high: 2.0, - low: 0.5, - close: 1.5, - volume: 0.0, - session: 'RTH', - source: 'eod_unadj', - }); - - const expected = new Uint8Array([ - ...asciiBytes('bars_1m,listing_id=7,session=RTH,source=eod_unadj '), - ...asciiBytes('open=='), - 0x10, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0xf0, - 0x3f, - ...asciiBytes(',high=='), - 0x10, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x40, - ...asciiBytes(',low=='), - 0x10, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0xe0, - 0x3f, - ...asciiBytes(',close=='), - 0x10, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0xf8, - 0x3f, - ...asciiBytes(',volume=='), - 0x10, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - ...asciiBytes(',known_at=1700000060000000t 1700000000000000t\n'), - ]); - - expect(actual).toEqual(expected); - }); - - it('preserves the negative-zero sign bit like Rust f64::to_le_bytes and emits -0 listing_id as 0', () => { - const bytes = encodeBar1mIlpV2(sampleBar({ listing_id: -0, volume: -0 })); - - expect(Array.from(bytes.slice(0, 22))).toEqual(asciiBytes('bars_1m,listing_id=0,s')); - const volumePrefix = encoder.encode(',volume=='); - const suffix = encoder.encode(',known_at=1736951460000000t 1736951400000000t\n'); - const volStart = bytes.byteLength - suffix.byteLength - 9 - volumePrefix.byteLength; - expect(bytes.slice(volStart, volStart + volumePrefix.byteLength)).toEqual(volumePrefix); - expect( - Array.from( - bytes.slice(volStart + volumePrefix.byteLength, volStart + volumePrefix.byteLength + 9) - ) - ).toEqual([0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80]); - }); - - it('encodes extreme finite doubles (MAX_VALUE, MIN_VALUE subnormal, negative) without rejection', () => { - const bytes = encodeFx1mIlpV2( - sampleFx({ open: Number.MAX_VALUE, high: Number.MIN_VALUE, low: -1.5, close: 0 }) - ); - const head = encoder.encode('fx_1m,pair=USD.CAD,source=eod open=='); - expect(bytes.slice(0, head.byteLength)).toEqual(head); - let o = head.byteLength; - // MAX_VALUE = 0x7fefffffffffffff - expect(Array.from(bytes.slice(o, o + 9))).toEqual([ - 0x10, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xef, 0x7f, - ]); - o += 9 + ',high=='.length; - // MIN_VALUE = 0x0000000000000001 - expect(Array.from(bytes.slice(o, o + 9))).toEqual([ - 0x10, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - ]); - o += 9 + ',low=='.length; - // -1.5 = 0xbff8000000000000 - expect(Array.from(bytes.slice(o, o + 9))).toEqual([ - 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xbf, - ]); - }); - - it('returns a fresh buffer per call so mutating one encoding cannot corrupt another', () => { - const row = sampleFx(); - const a = encodeFx1mIlpV2(row); - const b = encodeFx1mIlpV2(row); - a.fill(0); - expect(b).toEqual(encodeFx1mIlpV2(row)); - expect(b[0]).toBe(0x66); // 'f' - }); - - it('escapes a symbol consisting only of special characters', () => { - const bytes = encodeFx1mIlpV2(sampleFx({ pair: ' ,=\\\n\r' })); - const expected = encoder.encode('fx_1m,pair=\\ \\,\\=\\\\\\\n\\\r,source=eod open=='); - expect(bytes.slice(0, expected.byteLength)).toEqual(expected); - }); - - it('rejects invalid or empty session tags with a typed error', () => { - expectEncodeError( - () => encodeBar1mIlpV2(sampleBar({ session: 'rth' as Bar1mSession })), - 'invalid-session', - 'session' - ); - expectEncodeError( - () => encodeBar1mIlpV2(sampleBar({ session: 'RTH ' as Bar1mSession })), - 'invalid-session', - 'session' - ); - expectEncodeError( - () => encodeBar1mIlpV2(sampleBar({ session: '' as Bar1mSession })), - 'empty-symbol', - 'session' - ); - }); - - it('rejects non-bigint timestamps (JS number) instead of silently encoding them', () => { - expectEncodeError( - () => encodeBar1mIlpV2(sampleBar({ ts: 1_700_000_000_000_000 as unknown as bigint })), - 'timestamp-out-of-range', - 'ts' - ); - expectEncodeError( - () => encodeBar1mIlpV2(sampleBar({ known_at: 5 as unknown as bigint })), - 'timestamp-out-of-range', - 'known_at' - ); - expectEncodeError( - () => encodeFx1mIlpV2(sampleFx({ ts: 0 as unknown as bigint })), - 'timestamp-out-of-range', - 'ts' - ); - }); - - it('accepts the fx_1m designated timestamp at INT64_MAX', () => { - const max = 2n ** 63n - 1n; - const bytes = encodeFx1mIlpV2(sampleFx({ ts: max })); - const suffix = encoder.encode(` ${max.toString(10)}t\n`); - expect(bytes.slice(bytes.byteLength - suffix.byteLength)).toEqual(suffix); - }); -}); - -describe('createIlpV2BatchWriter edge cases', () => { - it('rejects construction without a usable sink and rejects unsafe-integer limits', () => { - expect(() => createIlpV2BatchWriter(undefined as never)).toThrow(TypeError); - expect(() => createIlpV2BatchWriter({} as never)).toThrow(TypeError); - expect(() => createIlpV2BatchWriter({ sink: {} as IlpV2BatchSink })).toThrow(TypeError); - const sink: IlpV2BatchSink = { write: async () => {} }; - expect(() => createIlpV2BatchWriter({ sink, maxBatchBytes: 2 ** 53 })).toThrow(RangeError); - expect(() => createIlpV2BatchWriter({ sink, maxBatchRows: '5' as unknown as number })).toThrow( - RangeError - ); - expect(() => createIlpV2BatchWriter({ sink, maxBatchBytes: 1, maxBatchRows: 1 })).not.toThrow(); - }); - - it('flushes at DEFAULT_ILP_MAX_BATCH_ROWS when no limits are supplied', async () => { - const batches: Uint8Array[] = []; - const writer = createIlpV2BatchWriter({ sink: { write: async b => void batches.push(b) } }); - const row = sampleFx({ ts: 0n }); - const rowLen = encodeFx1mIlpV2(row).byteLength; - // Row size keeps 10_000 rows well below the 1 MiB default, so only the row limit triggers. - expect(rowLen * DEFAULT_ILP_MAX_BATCH_ROWS).toBeLessThan(DEFAULT_ILP_MAX_BATCH_BYTES); - - for (let i = 0; i < DEFAULT_ILP_MAX_BATCH_ROWS - 1; i++) { - await writer.writeFx1m(row); - } - expect(batches).toHaveLength(0); - await writer.writeFx1m(row); - expect(batches).toHaveLength(1); - expect(batches[0]!.byteLength).toBe(rowLen * DEFAULT_ILP_MAX_BATCH_ROWS); - - await writer.writeFx1m(row); - const stats = await writer.finish(); - expect(stats).toEqual({ - rows: DEFAULT_ILP_MAX_BATCH_ROWS + 1, - batches: 2, - bytes: rowLen * (DEFAULT_ILP_MAX_BATCH_ROWS + 1), - }); - }); - - it('hands the sink a fresh batch buffer per flush so retained batches are never overwritten', async () => { - const retained: Uint8Array[] = []; - const writer = createIlpV2BatchWriter({ - sink: { write: async b => void retained.push(b) }, - maxBatchRows: 1, - }); - const r1 = sampleBar({ listing_id: 1 }); - const r2 = sampleBar({ listing_id: 2 }); - await writer.writeBar1m(r1); - await writer.writeBar1m(r2); - await writer.finish(); - expect(retained[0]).not.toBe(retained[1]); - expect(retained[0]!.buffer).not.toBe(retained[1]!.buffer); - expect(retained).toEqual([encodeBar1mIlpV2(r1), encodeBar1mIlpV2(r2)]); - }); - - it('a rejected row in the middle of overlapping writes does not block or reorder later queued rows', async () => { - const batches: Uint8Array[] = []; - const writer = createIlpV2BatchWriter({ - sink: { write: async b => void batches.push(b.slice()) }, - maxBatchRows: 2, - maxBatchBytes: 100_000, - }); - const a = sampleBar({ listing_id: 1 }); - const c = sampleFx({ pair: 'EUR.USD' }); - const d = sampleBar({ listing_id: 4 }); - - const pa = writer.writeBar1m(a); - const pb = writer.writeBar1m(sampleBar({ high: Number.NaN })); - const pc = writer.writeFx1m(c); - const pd = writer.writeBar1m(d); - const pFinish = writer.finish(); - - await pa; - await expect(pb).rejects.toBeInstanceOf(IlpV2EncodeError); - await pc; - await pd; - const stats = await pFinish; - - const expected = [encodeBar1mIlpV2(a), encodeFx1mIlpV2(c), encodeBar1mIlpV2(d)]; - expect(batches).toEqual([concatBytes(expected.slice(0, 2)), expected[2]!]); - expect(stats).toEqual({ - rows: 3, - batches: 2, - bytes: expected.reduce((s, e) => s + e.byteLength, 0), - }); - }); - - it('treats a synchronously throwing sink like a rejected write and fails closed', async () => { - const boom = new Error('sync sink failure'); - let calls = 0; - const sink: IlpV2BatchSink = { - write(): Promise { - calls += 1; - throw boom; - }, - }; - const writer = createIlpV2BatchWriter({ sink, maxBatchRows: 1 }); - - await expect(writer.writeBar1m(sampleBar())).rejects.toBe(boom); - await expect(writer.writeBar1m(sampleBar())).rejects.toThrow(/sink write failure/i); - await expect(writer.flush()).rejects.toThrow(/sink write failure/i); - expect(calls).toBe(1); - }); - - it('propagates a sink failure on the finish() tail flush, excludes it from stats, and stays closed', async () => { - const boom = new Error('tail failure'); - let calls = 0; - const sink: IlpV2BatchSink = { - async write(): Promise { - calls += 1; - if (calls === 2) { - throw boom; - } - }, - }; - const writer = createIlpV2BatchWriter({ sink, maxBatchRows: 2, maxBatchBytes: 100_000 }); - await writer.writeBar1m(sampleBar({ listing_id: 1 })); - await writer.writeBar1m(sampleBar({ listing_id: 2 })); // batch 1 OK - await writer.writeBar1m(sampleBar({ listing_id: 3 })); // pending tail - - await expect(writer.finish()).rejects.toBe(boom); - expect(calls).toBe(2); - - const err = await writer.finish().then( - () => null, - (e: unknown) => e as Error - ); - expect(err).toBeInstanceOf(Error); - expect(err!.message).toMatch(/sink write failure/i); - // The original sink error is preserved as the cause for diagnostics. - expect(err!.cause).toBe(boom); - expect(calls).toBe(2); - }); - - it('flush() on an explicit call propagates sink failure and blocks the tail on finish()', async () => { - const boom = new Error('flush failure'); - let calls = 0; - const writer = createIlpV2BatchWriter({ - sink: { - async write(): Promise { - calls += 1; - throw boom; - }, - }, - }); - await writer.writeFx1m(sampleFx()); - await expect(writer.flush()).rejects.toBe(boom); - await expect(writer.writeFx1m(sampleFx())).rejects.toThrow(/sink write failure/i); - await expect(writer.finish()).rejects.toThrow(/sink write failure/i); - expect(calls).toBe(1); - }); - - it('serializes an overlapping explicit flush() behind in-flight writes', async () => { - const order: string[] = []; - let release: (() => void) | null = null; - const writer = createIlpV2BatchWriter({ - sink: { - write(b: Uint8Array): Promise { - order.push(`write:${b.byteLength}`); - if (release === null) { - return new Promise(resolve => { - release = resolve; - }); - } - return Promise.resolve(); - }, - }, - maxBatchRows: 1, - }); - const row = sampleFx(); - const len = encodeFx1mIlpV2(row).byteLength; - - const p1 = writer.writeFx1m(row); - const pFlush = writer.flush().then(() => order.push('flushed')); - const p2 = writer.writeFx1m(row); - - await Promise.resolve(); - expect(order).toEqual([`write:${len}`]); - release!(); - await Promise.all([p1, pFlush, p2]); - expect(order).toEqual([`write:${len}`, 'flushed', `write:${len}`]); - }); -}); diff --git a/libs/data/questdb/test/ilp-v2-writer.test.ts b/libs/data/questdb/test/ilp-v2-writer.test.ts deleted file mode 100644 index c7d4c6ca..00000000 --- a/libs/data/questdb/test/ilp-v2-writer.test.ts +++ /dev/null @@ -1,820 +0,0 @@ -import { describe, expect, it } from 'bun:test'; -import { - createIlpV2BatchWriter, - DEFAULT_ILP_MAX_BATCH_BYTES, - DEFAULT_ILP_MAX_BATCH_ROWS, - encodeBar1mIlpV2, - encodeFx1mIlpV2, - ILP_V2_DOUBLE_TYPE, - IlpV2EncodeError, - type Bar1mIlpV2Row, - type Fx1mIlpV2Row, - type IlpV2BatchSink, -} from '../src/index'; - -const encoder = new TextEncoder(); - -function asciiBytes(text: string): number[] { - return Array.from(encoder.encode(text)); -} - -function concatBytes(chunks: readonly Uint8Array[]): Uint8Array { - const total = chunks.reduce((sum, c) => sum + c.byteLength, 0); - const out = new Uint8Array(total); - let offset = 0; - for (const chunk of chunks) { - out.set(chunk, offset); - offset += chunk.byteLength; - } - return out; -} - -function indexOfSubarray(haystack: Uint8Array, needle: Uint8Array): number { - outer: for (let i = 0; i <= haystack.length - needle.length; i++) { - for (let j = 0; j < needle.length; j++) { - if (haystack[i + j] !== needle[j]) { - continue outer; - } - } - return i; - } - return -1; -} - -function sampleBar(overrides: Partial = {}): Bar1mIlpV2Row { - return { - listing_id: 42, - ts: 1_736_951_400_000_000n, - known_at: 1_736_951_460_000_000n, - open: 123.45, - high: 125.75, - low: 122.125, - close: 124.5, - volume: 98_765.0, - session: 'RTH', - source: 'eod_unadj', - ...overrides, - }; -} - -function sampleFx(overrides: Partial = {}): Fx1mIlpV2Row { - return { - pair: 'USD.CAD', - source: 'eod', - open: 1.3625, - high: 1.365, - low: 1.36125, - close: 1.364375, - ts: 1_736_951_400_000_000n, - ...overrides, - }; -} - -function createMemorySink(): { sink: IlpV2BatchSink; batches: Uint8Array[] } { - const batches: Uint8Array[] = []; - const sink: IlpV2BatchSink = { - async write(batch: Uint8Array): Promise { - batches.push(batch.slice()); - }, - }; - return { sink, batches }; -} - -describe('ILP v2 writer constants', () => { - it('matches Rust tools/curate-etl/src/ilp.rs constants', () => { - expect(ILP_V2_DOUBLE_TYPE).toBe(0x10); - expect(DEFAULT_ILP_MAX_BATCH_BYTES).toBe(1_048_576); - expect(DEFAULT_ILP_MAX_BATCH_ROWS).toBe(10_000); - }); -}); - -describe('ILP v2 byte-parity with tools/curate-etl/src/ilp_tests.rs', () => { - it('matches golden_bytes_encode_bar_1m_matches_ilp_v2_wire_contract byte-for-byte', () => { - // Mirrors `golden_bytes_encode_bar_1m_matches_ilp_v2_wire_contract` - // in `tools/curate-etl/src/ilp_tests.rs`. - const row: Bar1mIlpV2Row = { - listing_id: 42, - ts: 1_736_951_400_000_000n, - known_at: 1_736_951_460_123_456n, - open: 150.25, - high: 151.75, - low: 149.5, - close: 151.125, - volume: 12_345.0, - session: 'RTH', - source: 'eod_unadj', - }; - - const actual = encodeBar1mIlpV2(row); - - // Expected wire bytes written out literally (little-endian IEEE-754 doubles): - // 150.25 -> 0x4062c80000000000 -> [0x00, 0x00, 0x00, 0x00, 0x00, 0xc8, 0x62, 0x40] - // 151.75 -> 0x4062f80000000000 -> [0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x62, 0x40] - // 149.5 -> 0x4062b00000000000 -> [0x00, 0x00, 0x00, 0x00, 0x00, 0xb0, 0x62, 0x40] - // 151.125 -> 0x4062e40000000000 -> [0x00, 0x00, 0x00, 0x00, 0x00, 0xe4, 0x62, 0x40] - // 12345.0 -> 0x40c81c8000000000 -> [0x00, 0x00, 0x00, 0x00, 0x80, 0x1c, 0xc8, 0x40] - const expected = new Uint8Array([ - ...asciiBytes('bars_1m,listing_id=42,session=RTH,source=eod_unadj open=='), - 0x10, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0xc8, - 0x62, - 0x40, - ...asciiBytes(',high=='), - 0x10, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0xf8, - 0x62, - 0x40, - ...asciiBytes(',low=='), - 0x10, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0xb0, - 0x62, - 0x40, - ...asciiBytes(',close=='), - 0x10, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0xe4, - 0x62, - 0x40, - ...asciiBytes(',volume=='), - 0x10, - 0x00, - 0x00, - 0x00, - 0x00, - 0x80, - 0x1c, - 0xc8, - 0x40, - ...asciiBytes(',known_at=1736951460123456t 1736951400000000t\n'), - ]); - - expect(actual).toEqual(expected); - expect(indexOfSubarray(actual, encoder.encode('vwap'))).toBe(-1); - - // Verify PRE and POST session tags as in the Rust golden test. - const preBytes = encodeBar1mIlpV2({ ...row, session: 'PRE' }); - expect( - indexOfSubarray(preBytes, encoder.encode('bars_1m,listing_id=42,session=PRE,source=eod_unadj ')) - ).toBe(0); - - const postBytes = encodeBar1mIlpV2({ ...row, session: 'POST' }); - expect( - indexOfSubarray( - postBytes, - encoder.encode('bars_1m,listing_id=42,session=POST,source=eod_unadj ') - ) - ).toBe(0); - }); - - it('matches golden_bytes_encode_fx_1m_matches_ilp_v2_wire_contract byte-for-byte', () => { - // Mirrors `golden_bytes_encode_fx_1m_matches_ilp_v2_wire_contract` - // in `tools/curate-etl/src/ilp_tests.rs`. - const row: Fx1mIlpV2Row = { - pair: 'USD.CAD', - ts: 1_736_951_400_000_000n, - open: 1.3625, - high: 1.365, - low: 1.36125, - close: 1.364375, - source: 'eod', - }; - - const actual = encodeFx1mIlpV2(row); - - // Expected wire bytes written out literally (little-endian IEEE-754 doubles): - // 1.3625 -> 0x3ff5cccccccccccc -> [0xcd, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xf5, 0x3f] - // 1.365 -> 0x3ff5d70a3d70a3d7 -> [0xd7, 0xa3, 0x70, 0x3d, 0x0a, 0xd7, 0xf5, 0x3f] - // 1.36125 -> 0x3ff5c7ae147ae148 -> [0x48, 0xe1, 0x7a, 0x14, 0xae, 0xc7, 0xf5, 0x3f] - // 1.364375 -> 0x3ff5d47ae147ae14 -> [0x14, 0xae, 0x47, 0xe1, 0x7a, 0xd4, 0xf5, 0x3f] - const expected = new Uint8Array([ - ...asciiBytes('fx_1m,pair=USD.CAD,source=eod open=='), - 0x10, - 0xcd, - 0xcc, - 0xcc, - 0xcc, - 0xcc, - 0xcc, - 0xf5, - 0x3f, - ...asciiBytes(',high=='), - 0x10, - 0xd7, - 0xa3, - 0x70, - 0x3d, - 0x0a, - 0xd7, - 0xf5, - 0x3f, - ...asciiBytes(',low=='), - 0x10, - 0x48, - 0xe1, - 0x7a, - 0x14, - 0xae, - 0xc7, - 0xf5, - 0x3f, - ...asciiBytes(',close=='), - 0x10, - 0x14, - 0xae, - 0x47, - 0xe1, - 0x7a, - 0xd4, - 0xf5, - 0x3f, - ...asciiBytes(' 1736951400000000t\n'), - ]); - - expect(actual).toEqual(expected); - expect(indexOfSubarray(actual, encoder.encode('known_at'))).toBe(-1); - expect(indexOfSubarray(actual, encoder.encode('volume'))).toBe(-1); - expect(indexOfSubarray(actual, encoder.encode('vwap'))).toBe(-1); - }); -}); - -describe('ILP v2 escaping, timestamps, and atomic rejection', () => { - it('escapes all six ILP symbol characters and preserves UTF-8 and signed known_at', () => { - // Mirrors `symbol_escaping_and_non_finite_or_negative_ts_atomic_rejection` - // in `tools/curate-etl/src/ilp_tests.rs`. - const rawSym = 'a b,c=d\\e\nf\rg caf\u00e9'; - const expectedEscaped = new Uint8Array([ - ...asciiBytes('a\\ b\\,c\\=d\\\\e\\\nf\\\rg\\ caf'), - 0xc3, - 0xa9, - ]); - - // Rust `encode_bar_1m` writes signed `known_at` via `write_i64_decimal` without rejecting < 0. - const barBytes = encodeBar1mIlpV2( - sampleBar({ - listing_id: 7, - ts: 0n, - known_at: -1n, - source: rawSym, - }) - ); - const expectedBarPrefix = concatBytes([ - encoder.encode('bars_1m,listing_id=7,session=RTH,source='), - expectedEscaped, - encoder.encode(' '), - ]); - expect(barBytes.slice(0, expectedBarPrefix.byteLength)).toEqual(expectedBarPrefix); - const expectedBarSuffix = encoder.encode(',known_at=-1t 0t\n'); - expect(barBytes.slice(barBytes.byteLength - expectedBarSuffix.byteLength)).toEqual( - expectedBarSuffix - ); - - // Also check signed 64-bit timestamp endpoints and INT32 listing_id endpoints. - const int64Min = -(2n ** 63n); - const int64Max = 2n ** 63n - 1n; - const endpointBar = encodeBar1mIlpV2( - sampleBar({ - listing_id: -2_147_483_648, - known_at: int64Min, - ts: int64Max, - }) - ); - expect( - indexOfSubarray(endpointBar, encoder.encode('bars_1m,listing_id=-2147483648,session=RTH,')) - ).toBe(0); - const endpointSuffix = encoder.encode( - `,known_at=${int64Min.toString(10)}t ${int64Max.toString(10)}t\n` - ); - expect(endpointBar.slice(endpointBar.byteLength - endpointSuffix.byteLength)).toEqual( - endpointSuffix - ); - - const maxListingBar = encodeBar1mIlpV2( - sampleBar({ - listing_id: 2_147_483_647, - known_at: int64Max, - ts: 0n, - }) - ); - expect( - indexOfSubarray(maxListingBar, encoder.encode('bars_1m,listing_id=2147483647,session=RTH,')) - ).toBe(0); - - // FX pair and source escaping. - const fxBytes = encodeFx1mIlpV2( - sampleFx({ - pair: rawSym, - source: 'src=1,2 3\\4\n\r', - ts: 123n, - }) - ); - const expectedFxPrefix = concatBytes([ - encoder.encode('fx_1m,pair='), - expectedEscaped, - encoder.encode(',source=src\\=1\\,2\\ 3\\\\4\\\n\\\r '), - ]); - expect(fxBytes.slice(0, expectedFxPrefix.byteLength)).toEqual(expectedFxPrefix); - const expectedFxSuffix = encoder.encode(' 123t\n'); - expect(fxBytes.slice(fxBytes.byteLength - expectedFxSuffix.byteLength)).toEqual( - expectedFxSuffix - ); - }); - - it('throws typed IlpV2EncodeError for negative ts, int64 overflow, non-finite doubles, empty symbols, and non-int32 listing_id', () => { - const expectEncodeError = ( - fn: () => unknown, - kind: IlpV2EncodeError['kind'], - field: string - ) => { - try { - fn(); - throw new Error('Expected IlpV2EncodeError to be thrown'); - } catch (err) { - expect(err).toBeInstanceOf(IlpV2EncodeError); - const encodeErr = err as IlpV2EncodeError; - expect(encodeErr.kind).toBe(kind); - expect(encodeErr.field).toBe(field); - } - }; - - // Negative designated timestamps. - expectEncodeError(() => encodeBar1mIlpV2(sampleBar({ ts: -1n })), 'negative-timestamp', 'ts'); - expectEncodeError(() => encodeFx1mIlpV2(sampleFx({ ts: -42n })), 'negative-timestamp', 'ts'); - - // Signed 64-bit timestamp overflow / underflow. - const overInt64 = 2n ** 63n; - const underInt64 = -(2n ** 63n) - 1n; - expectEncodeError( - () => encodeBar1mIlpV2(sampleBar({ ts: overInt64 })), - 'timestamp-out-of-range', - 'ts' - ); - expectEncodeError( - () => encodeBar1mIlpV2(sampleBar({ ts: underInt64 })), - 'timestamp-out-of-range', - 'ts' - ); - expectEncodeError( - () => encodeBar1mIlpV2(sampleBar({ known_at: overInt64 })), - 'timestamp-out-of-range', - 'known_at' - ); - expectEncodeError( - () => encodeBar1mIlpV2(sampleBar({ known_at: underInt64 })), - 'timestamp-out-of-range', - 'known_at' - ); - expectEncodeError( - () => encodeFx1mIlpV2(sampleFx({ ts: overInt64 })), - 'timestamp-out-of-range', - 'ts' - ); - - // Non-finite doubles across every double column. - for (const badVal of [Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY]) { - for (const field of ['open', 'high', 'low', 'close', 'volume'] as const) { - expectEncodeError( - () => encodeBar1mIlpV2(sampleBar({ [field]: badVal })), - 'non-finite-double', - field - ); - } - for (const field of ['open', 'high', 'low', 'close'] as const) { - expectEncodeError( - () => encodeFx1mIlpV2(sampleFx({ [field]: badVal })), - 'non-finite-double', - field - ); - } - } - - // Empty symbols. - expectEncodeError(() => encodeBar1mIlpV2(sampleBar({ source: '' })), 'empty-symbol', 'source'); - expectEncodeError(() => encodeFx1mIlpV2(sampleFx({ pair: '' })), 'empty-symbol', 'pair'); - expectEncodeError(() => encodeFx1mIlpV2(sampleFx({ source: '' })), 'empty-symbol', 'source'); - - // Non-INT32 listing_id. - for (const badId of [ - 1.5, - -0.25, - 2_147_483_648, - -2_147_483_649, - Number.NaN, - Number.POSITIVE_INFINITY, - ]) { - expectEncodeError( - () => encodeBar1mIlpV2(sampleBar({ listing_id: badId })), - 'invalid-listing-id', - 'listing_id' - ); - } - }); - - it('rejects invalid rows at a batch boundary without calling sink and preserves pending rows', async () => { - const validRow = sampleBar({ listing_id: 101 }); - const validBytes = encodeBar1mIlpV2(validRow); - const { sink, batches } = createMemorySink(); - - // Limit allows 1 row to sit pending right at the byte boundary so a second valid row would flush. - const writer = createIlpV2BatchWriter({ - sink, - maxBatchBytes: validBytes.byteLength + 1, - maxBatchRows: 2, - }); - - await writer.writeBar1m(validRow); - expect(batches).toHaveLength(0); - - // Rejected bar and FX rows must not flush the pending row or write anything to sink. - await expect(writer.writeBar1m(sampleBar({ ts: -1n }))).rejects.toBeInstanceOf( - IlpV2EncodeError - ); - await expect(writer.writeBar1m(sampleBar({ volume: Number.NaN }))).rejects.toBeInstanceOf( - IlpV2EncodeError - ); - await expect(writer.writeBar1m(sampleBar({ source: '' }))).rejects.toBeInstanceOf( - IlpV2EncodeError - ); - await expect(writer.writeBar1m(sampleBar({ listing_id: 3.14 }))).rejects.toBeInstanceOf( - IlpV2EncodeError - ); - await expect(writer.writeFx1m(sampleFx({ pair: '' }))).rejects.toBeInstanceOf(IlpV2EncodeError); - await expect(writer.writeFx1m(sampleFx({ ts: -5n }))).rejects.toBeInstanceOf(IlpV2EncodeError); - expect(batches).toHaveLength(0); - - // Pending valid row is still intact and flushes cleanly on finish(). - const stats = await writer.finish(); - expect(stats).toEqual({ rows: 1, batches: 1, bytes: validBytes.byteLength }); - expect(batches).toEqual([validBytes]); - }); -}); - -describe('createIlpV2BatchWriter batching, boundaries, and option validation', () => { - it('validates maxBatchBytes and maxBatchRows at construction', () => { - const { sink } = createMemorySink(); - for (const invalid of [0, -1, -100, 1.5, Number.NaN, Number.POSITIVE_INFINITY]) { - expect(() => createIlpV2BatchWriter({ sink, maxBatchBytes: invalid })).toThrow(RangeError); - expect(() => createIlpV2BatchWriter({ sink, maxBatchRows: invalid })).toThrow(RangeError); - } - }); - - it('flushes on exact maxBatchRows, exact maxBatchBytes, pre-overflow, oversized singleton, and explicit/empty flush', async () => { - // Include a finite double whose IEEE-754 LE payload contains 0x0a (LF) and a symbol with LF. - const lfDoubleBuf = new Uint8Array([0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x24, 0x40]); - const doubleWithLf = new DataView(lfDoubleBuf.buffer).getFloat64(0, true); - expect(Number.isFinite(doubleWithLf)).toBe(true); - - const row = sampleBar({ open: doubleWithLf, source: 'eod\nwith_lf' }); - const oneLine = encodeBar1mIlpV2(row); - const rowLen = oneLine.byteLength; - - // 1. Exact row limit (maxBatchRows = 3) + 1 remainder row. - { - const { sink, batches } = createMemorySink(); - const writer = createIlpV2BatchWriter({ - sink, - maxBatchBytes: 100_000, - maxBatchRows: 3, - }); - for (let i = 0; i < 7; i++) { - await writer.writeBar1m(row); - } - const stats = await writer.finish(); - expect(stats).toEqual({ rows: 7, batches: 3, bytes: 7 * rowLen }); - expect(batches).toHaveLength(3); - expect(batches[0]).toEqual(concatBytes([oneLine, oneLine, oneLine])); - expect(batches[1]).toEqual(concatBytes([oneLine, oneLine, oneLine])); - expect(batches[2]).toEqual(oneLine); - expect(batches.every(b => b[b.byteLength - 1] === 0x0a)).toBe(true); - } - - // 2. Exact byte limit (2 * rowLen): flushes immediately when the 2nd and 4th rows hit the limit. - { - const { sink, batches } = createMemorySink(); - const writer = createIlpV2BatchWriter({ - sink, - maxBatchBytes: 2 * rowLen, - maxBatchRows: 100, - }); - await writer.writeBar1m(row); - expect(batches).toHaveLength(0); - await writer.writeBar1m(row); - expect(batches).toHaveLength(1); - expect(batches[0]).toEqual(concatBytes([oneLine, oneLine])); - await writer.writeBar1m(row); - expect(batches).toHaveLength(1); - await writer.writeBar1m(row); - expect(batches).toHaveLength(2); - expect(batches[1]).toEqual(concatBytes([oneLine, oneLine])); - await writer.writeBar1m(row); - expect(batches).toHaveLength(2); - const stats = await writer.finish(); - expect(stats).toEqual({ rows: 5, batches: 3, bytes: 5 * rowLen }); - expect(batches).toHaveLength(3); - expect(batches[2]).toEqual(oneLine); - } - - // 3. Row would exceed remaining capacity (2 * rowLen - 1): pre-flushes before appending. - { - const { sink, batches } = createMemorySink(); - const writer = createIlpV2BatchWriter({ - sink, - maxBatchBytes: 2 * rowLen - 1, - maxBatchRows: 100, - }); - for (let i = 0; i < 3; i++) { - await writer.writeBar1m(row); - } - const stats = await writer.finish(); - expect(stats).toEqual({ rows: 3, batches: 3, bytes: 3 * rowLen }); - expect(batches).toEqual([oneLine, oneLine, oneLine]); - } - - // 4. Individually oversized row (maxBatchBytes = 16 < rowLen): sent alone, never split. - { - const { sink, batches } = createMemorySink(); - const writer = createIlpV2BatchWriter({ - sink, - maxBatchBytes: 16, - maxBatchRows: 100, - }); - await writer.writeBar1m(row); - await writer.writeBar1m(row); - const stats = await writer.finish(); - expect(stats).toEqual({ rows: 2, batches: 2, bytes: 2 * rowLen }); - expect(batches).toEqual([oneLine, oneLine]); - } - - // 5. Empty flush, explicit flush, and zero-row finish. - { - const { sink, batches } = createMemorySink(); - const writer = createIlpV2BatchWriter({ sink, maxBatchBytes: 100_000, maxBatchRows: 10 }); - await writer.flush(); - expect(batches).toHaveLength(0); - await writer.writeBar1m(row); - await writer.flush(); - expect(batches).toEqual([oneLine]); - await writer.flush(); - expect(batches).toHaveLength(1); - const stats = await writer.finish(); - expect(stats).toEqual({ rows: 1, batches: 1, bytes: rowLen }); - } - - { - const { sink, batches } = createMemorySink(); - const writer = createIlpV2BatchWriter({ sink }); - const stats = await writer.finish(); - expect(stats).toEqual({ rows: 0, batches: 0, bytes: 0 }); - expect(batches).toHaveLength(0); - } - }); - - it('preserves mixed bars_1m and fx_1m input order and rejects writes after finish()', async () => { - const bar1 = sampleBar({ listing_id: 1, ts: 1_700_000_000_000_000n }); - const fx1 = sampleFx({ pair: 'USD.CAD', ts: 1_700_000_060_000_000n }); - const bar2 = sampleBar({ listing_id: 2, ts: 1_700_000_120_000_000n }); - const fx2 = sampleFx({ pair: 'EUR.USD', ts: 1_700_000_180_000_000n }); - - const expectedAll = concatBytes([ - encodeBar1mIlpV2(bar1), - encodeFx1mIlpV2(fx1), - encodeBar1mIlpV2(bar2), - encodeFx1mIlpV2(fx2), - ]); - - const { sink, batches } = createMemorySink(); - const writer = createIlpV2BatchWriter({ sink, maxBatchRows: 2, maxBatchBytes: 100_000 }); - - await writer.writeBar1m(bar1); - await writer.writeFx1m(fx1); - await writer.writeBar1m(bar2); - await writer.writeFx1m(fx2); - - const stats = await writer.finish(); - expect(stats).toEqual({ rows: 4, batches: 2, bytes: expectedAll.byteLength }); - expect(concatBytes(batches)).toEqual(expectedAll); - expect(batches.every(b => b[b.byteLength - 1] === 0x0a)).toBe(true); - - // Writes, flush, and finish after finish() throw without calling sink. - await expect(writer.writeBar1m(bar1)).rejects.toThrow(/already finished/i); - await expect(writer.writeFx1m(fx1)).rejects.toThrow(/already finished/i); - await expect(writer.flush()).rejects.toThrow(/already finished/i); - await expect(writer.finish()).rejects.toThrow(/already finished/i); - expect(batches).toHaveLength(2); - }); -}); - -describe('createIlpV2BatchWriter serialization and fail-closed sink errors', () => { - it('serializes overlapping writes and finish() without overlapping sink calls', async () => { - let inFlight = 0; - let maxInFlight = 0; - const batches: Uint8Array[] = []; - const resolvers: Array<() => void> = []; - - const sink: IlpV2BatchSink = { - write(batch: Uint8Array): Promise { - inFlight += 1; - maxInFlight = Math.max(maxInFlight, inFlight); - batches.push(batch.slice()); - return new Promise(resolve => { - resolvers.push(() => { - inFlight -= 1; - resolve(); - }); - }); - }, - }; - - const row1 = sampleBar({ listing_id: 1, ts: 1_700_000_000_000_000n }); - const row2 = sampleFx({ pair: 'USD.CAD', ts: 1_700_000_060_000_000n }); - const row3 = sampleBar({ listing_id: 3, ts: 1_700_000_120_000_000n }); - - const writer = createIlpV2BatchWriter({ sink, maxBatchRows: 1, maxBatchBytes: 100_000 }); - - // Launch overlapping operations without awaiting between calls. - const p1 = writer.writeBar1m(row1); - const p2 = writer.writeFx1m(row2); - const p3 = writer.writeBar1m(row3); - const pFinish = writer.finish(); - - // Drain queued manual resolutions one by one as each sink.write starts. - await Promise.resolve(); - expect(resolvers).toHaveLength(1); - expect(inFlight).toBe(1); - resolvers[0]!(); - await p1; - - await Promise.resolve(); - expect(resolvers).toHaveLength(2); - expect(inFlight).toBe(1); - resolvers[1]!(); - await p2; - - await Promise.resolve(); - expect(resolvers).toHaveLength(3); - expect(inFlight).toBe(1); - resolvers[2]!(); - await p3; - - const stats = await pFinish; - expect(maxInFlight).toBe(1); - expect(stats).toEqual({ - rows: 3, - batches: 3, - bytes: - encodeBar1mIlpV2(row1).byteLength + - encodeFx1mIlpV2(row2).byteLength + - encodeBar1mIlpV2(row3).byteLength, - }); - expect(batches).toEqual([ - encodeBar1mIlpV2(row1), - encodeFx1mIlpV2(row2), - encodeBar1mIlpV2(row3), - ]); - }); - - it('snapshots row field values at submission when a caller reuses mutable row objects across overlapping writes', async () => { - const { sink, batches } = createMemorySink(); - const writer = createIlpV2BatchWriter({ sink, maxBatchRows: 1, maxBatchBytes: 100_000 }); - - const mutableBar = sampleBar({ - listing_id: 10, - ts: 1_700_000_000_000_000n, - known_at: 1_700_000_060_000_000n, - open: 100.0, - high: 101.0, - low: 99.5, - close: 100.5, - volume: 1_000, - session: 'PRE', - source: 'bar_one', - }); - const expectedBar1 = encodeBar1mIlpV2(mutableBar); - - const mutableFx = sampleFx({ - pair: 'USD.CAD', - source: 'fx_one', - open: 1.35, - high: 1.36, - low: 1.34, - close: 1.355, - ts: 1_700_000_000_000_000n, - }); - const expectedFx1 = encodeFx1mIlpV2(mutableFx); - - // Submit first bar and FX row without awaiting, then mutate both objects in place. - const pBar1 = writer.writeBar1m(mutableBar); - const pFx1 = writer.writeFx1m(mutableFx); - - mutableBar.listing_id = 11; - mutableBar.ts = 1_700_000_060_000_000n; - mutableBar.known_at = 1_700_000_120_000_000n; - mutableBar.open = 200.0; - mutableBar.high = 202.0; - mutableBar.low = 199.0; - mutableBar.close = 201.5; - mutableBar.volume = 2_000; - mutableBar.session = 'RTH'; - mutableBar.source = 'bar_two'; - const expectedBar2 = encodeBar1mIlpV2(mutableBar); - - mutableFx.pair = 'EUR.USD'; - mutableFx.source = 'fx_two'; - mutableFx.open = 1.08; - mutableFx.high = 1.09; - mutableFx.low = 1.07; - mutableFx.close = 1.085; - mutableFx.ts = 1_700_000_060_000_000n; - const expectedFx2 = encodeFx1mIlpV2(mutableFx); - - const pBar2 = writer.writeBar1m(mutableBar); - const pFx2 = writer.writeFx1m(mutableFx); - - await Promise.all([pBar1, pFx1, pBar2, pFx2]); - const stats = await writer.finish(); - - expect(stats).toEqual({ - rows: 4, - batches: 4, - bytes: - expectedBar1.byteLength + - expectedFx1.byteLength + - expectedBar2.byteLength + - expectedFx2.byteLength, - }); - expect(batches).toEqual([expectedBar1, expectedFx1, expectedBar2, expectedFx2]); - }); - - it('propagates sink rejection and fails closed for queued and subsequent calls with zero extra sink writes', async () => { - const boom = new Error('simulated sink EPIPE'); - let sinkCalls = 0; - const acceptedBatches: Uint8Array[] = []; - let rejectSecondWrite: ((err: Error) => void) | null = null; - - const sink: IlpV2BatchSink = { - write(batch: Uint8Array): Promise { - sinkCalls += 1; - if (sinkCalls === 1) { - acceptedBatches.push(batch.slice()); - return Promise.resolve(); - } - return new Promise((_resolve, reject) => { - rejectSecondWrite = reject; - }); - }, - }; - - const row1 = sampleBar({ listing_id: 1 }); - const row2 = sampleBar({ listing_id: 2 }); - const row3 = sampleBar({ listing_id: 3 }); - - const writer = createIlpV2BatchWriter({ sink, maxBatchRows: 1, maxBatchBytes: 100_000 }); - - // First batch succeeds. - await writer.writeBar1m(row1); - expect(sinkCalls).toBe(1); - expect(acceptedBatches).toEqual([encodeBar1mIlpV2(row1)]); - - // Trigger second batch (in-flight) and queue a third write + finish behind it. - const failingWrite = writer.writeBar1m(row2); - const queuedWrite = writer.writeBar1m(row3); - const queuedFinish = writer.finish(); - - await Promise.resolve(); - expect(sinkCalls).toBe(2); - expect(rejectSecondWrite).not.toBeNull(); - rejectSecondWrite!(boom); - - // Triggering call receives the exact original error. - await expect(failingWrite).rejects.toBe(boom); - // Queued operations fail closed without invoking sink.write again. - await expect(queuedWrite).rejects.toThrow(/sink write failure/i); - await expect(queuedFinish).rejects.toThrow(/sink write failure/i); - - // Later calls also fail closed without invoking sink.write. - await expect(writer.writeBar1m(row3)).rejects.toThrow(/sink write failure/i); - await expect(writer.writeFx1m(sampleFx())).rejects.toThrow(/sink write failure/i); - await expect(writer.flush()).rejects.toThrow(/sink write failure/i); - await expect(writer.finish()).rejects.toThrow(/sink write failure/i); - - expect(sinkCalls).toBe(2); - }); -}); diff --git a/libs/data/questdb/test/questdb-query-layer-edges.test.ts b/libs/data/questdb/test/questdb-query-layer-edges.test.ts deleted file mode 100644 index e8089acd..00000000 --- a/libs/data/questdb/test/questdb-query-layer-edges.test.ts +++ /dev/null @@ -1,305 +0,0 @@ -import { describe, expect, it } from 'bun:test'; -import type { QueryResultRow } from 'pg'; -import { - formatCreateTableSQL, - QuestDBClient, - QuestDBQueryBuilder, - QuestDBSchemaManager, - readBars1m, - type QueryResult, - type QuestDBQueryable, -} from '../src'; - -interface RecordedQuery { - sql: string; - params: unknown[] | undefined; -} - -class RecordingClient implements QuestDBQueryable { - public readonly calls: RecordedQuery[] = []; - - public async query( - sql: string, - params?: unknown[] - ): Promise> { - this.calls.push({ sql, params }); - return { rows: [] as T[], rowCount: 0, executionTime: 0 }; - } -} - -function clientRoutedTo(fake: RecordingClient): QuestDBClient { - const client = new QuestDBClient( - { host: 'questdb.test.local', httpPort: 9000, pgPort: 8812, influxPort: 9009, database: 'qdb' }, - { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} } - ); - (client as unknown as { query: QuestDBQueryable['query'] }).query = fake.query.bind(fake); - return client; -} - -describe('QuestDB query layer edge cases (QA)', () => { - describe('predefined builders', () => { - it('latestOHLCV binds symbols and exchange and emits LATEST ON timestamp after WHERE', () => { - const fake = new RecordingClient(); - const hostile = "AAPL' OR '1'='1"; - - const { sql, params } = QuestDBQueryBuilder.latestOHLCV( - fake, - [hostile, 'MSFT'], - 'NASDAQ' - ).buildParameterized(); - - expect(sql).toBe( - 'SELECT symbol, timestamp, open, high, low, close, volume FROM ohlcv_data ' + - 'WHERE symbol IN ($1, $2) AND exchange = $3 ' + - 'LATEST ON timestamp PARTITION BY symbol ORDER BY timestamp DESC' - ); - expect(params).toEqual([hostile, 'MSFT', 'NASDAQ']); - expect(sql).not.toContain(hostile); - }); - - it('ohlcvTimeSeries and tradeExecutions bind values in placeholder order', () => { - const fake = new RecordingClient(); - - const series = QuestDBQueryBuilder.ohlcvTimeSeries(fake, 'AAPL', '5m', 12).buildParameterized(); - expect(series.sql).toBe( - 'SELECT first(open) as first_open, max(high) as max_high, min(low) as min_low, ' + - 'last(close) as last_close, sum(volume) as sum_volume FROM ohlcv_data ' + - "WHERE symbol = $1 AND timestamp > dateadd('h', $2, now()) SAMPLE BY 5m ORDER BY timestamp DESC" - ); - expect(series.params).toEqual(['AAPL', -12]); - - const trades = QuestDBQueryBuilder.tradeExecutions(fake, 'AAPL', 3).buildParameterized(); - expect(trades.sql).toBe( - 'SELECT symbol, timestamp, side, quantity, price, execution_time FROM trade_executions ' + - "WHERE timestamp > dateadd('h', $1, now()) AND symbol = $2 ORDER BY timestamp DESC" - ); - expect(trades.params).toEqual([-3, 'AAPL']); - }); - - it('ohlcvTimeSeries rejects a hostile SAMPLE BY interval at build time', () => { - const fake = new RecordingClient(); - expect(() => QuestDBQueryBuilder.ohlcvTimeSeries(fake, 'AAPL', '1h; DROP TABLE x')).toThrow( - /Invalid SAMPLE BY interval/ - ); - expect(fake.calls).toHaveLength(0); - }); - }); - - describe('builder input validation', () => { - it('binds LIMIT 0 instead of silently dropping it and rejects negative or fractional limits', () => { - const fake = new RecordingClient(); - expect(QuestDBQueryBuilder.create(fake).from('t').limit(0).buildParameterized()).toEqual({ - sql: 'SELECT * FROM t LIMIT $1', - params: [0], - }); - expect(() => QuestDBQueryBuilder.create(fake).limit(-1)).toThrow(/LIMIT/); - expect(() => QuestDBQueryBuilder.create(fake).limit(1.5)).toThrow(/LIMIT/); - }); - - it('rejects non-positive relative windows and invalid dates', () => { - const fake = new RecordingClient(); - expect(() => QuestDBQueryBuilder.create(fake).whereLastHours(0)).toThrow(/hours/); - expect(() => QuestDBQueryBuilder.create(fake).whereLastDays(-2)).toThrow(/days/); - expect(() => - QuestDBQueryBuilder.create(fake).whereTimeRange(new Date('nope'), new Date()) - ).toThrow(/startTime/); - }); - - it('rejects unterminated quotes and block comments in raw where() before mutating state', () => { - const fake = new RecordingClient(); - const builder = QuestDBQueryBuilder.create(fake).from('bars_1m'); - - expect(() => builder.where("session = 'RTH", [])).toThrow(/Unterminated string/); - expect(() => builder.where('"session = $1', ['RTH'])).toThrow(/Unterminated quoted/); - expect(() => builder.where('session = $1 /* open', ['RTH'])).toThrow(/Unterminated block/); - - // Rejected fragments must not leak into the next build. - expect(builder.where('session = $1', ['RTH']).buildParameterized()).toEqual({ - sql: 'SELECT * FROM bars_1m WHERE session = $1', - params: ['RTH'], - }); - }); - - it('keeps doubled quotes inside literals and still rebases the following placeholder', () => { - const fake = new RecordingClient(); - const { sql, params } = QuestDBQueryBuilder.create(fake) - .from('bars_1m') - .whereSymbol('X') - .where("note = 'it''s $1' AND close > $1", [10]) - .buildParameterized(); - - expect(sql).toBe("SELECT * FROM bars_1m WHERE symbol = $1 AND note = 'it''s $1' AND close > $2"); - expect(params).toEqual(['X', 10]); - }); - }); - - describe('QuestDBClient helpers', () => { - it('reject params without a where fragment before sending a query', async () => { - const fake = new RecordingClient(); - const client = clientRoutedTo(fake); - - await expect( - client.sampleBy('bars_1m', ['ts', 'close'], '1h', 'ts', undefined, ['RTH']) - ).rejects.toThrow(/without a where/); - await expect( - client.asofJoin('bars_1m', 'fx_1m', 'bars_1m.ts = fx_1m.ts', undefined, undefined, [1]) - ).rejects.toThrow(/without a where/); - await expect( - client.latestBy('bars_1m', '*', 'listing_id', { params: ['RTH'] }) - ).rejects.toThrow(/without a where/); - await expect(client.sampleBy('bars_1m', ['ts'], '1h', 'ts; --')).rejects.toThrow( - /Invalid timestamp column/ - ); - await expect( - client.createTable('bars_1m', 'ts TIMESTAMP', 'DAY; DROP TABLE x', 'ts') - ).rejects.toThrow(/PARTITION BY/); - await expect(client.optimizeTable('bars_1m; DROP TABLE x')).rejects.toThrow( - /Invalid table name/ - ); - - expect(fake.calls).toHaveLength(0); - }); - - it('asofJoin binds where params and keeps SQL on validated identifiers', async () => { - const fake = new RecordingClient(); - const client = clientRoutedTo(fake); - - await client.asofJoin( - 'bars_1m', - 'fx_1m', - 'bars_1m.ts = fx_1m.ts', - ['close'], - 'listing_id = $1 AND pair = $2', - ['1042', 'USDCAD'] - ); - - expect(fake.calls).toEqual([ - { - sql: - 'SELECT close FROM bars_1m ASOF JOIN fx_1m ON bars_1m.ts = fx_1m.ts ' + - 'WHERE listing_id = $1 AND pair = $2', - params: ['1042', 'USDCAD'], - }, - ]); - }); - }); - - describe('schema DDL', () => { - it('leaves legacy startup DDL unchanged (no CAPACITY, CACHE, WAL or DEDUP)', async () => { - const fake = new RecordingClient(); - await new QuestDBSchemaManager(fake).createAllTables(); - - const ddl = fake.calls.map(call => call.sql); - expect(ddl).toHaveLength(6); - expect(ddl[0]).toBe( - 'CREATE TABLE IF NOT EXISTS ohlcv_data (symbol SYMBOL, exchange SYMBOL, timestamp TIMESTAMP, ' + - 'open DOUBLE, high DOUBLE, low DOUBLE, close DOUBLE, volume LONG, data_source SYMBOL) ' + - 'TIMESTAMP(timestamp) PARTITION BY DAY' - ); - for (const statement of ddl) { - expect(statement).not.toMatch(/CAPACITY|CACHE|WAL|DEDUP|bars_1m|fx_1m|bar_revisions/); - } - }); - - it('formatCreateTableSQL rejects hostile identifiers, bad capacities and multiple designated timestamps', () => { - expect(() => - formatCreateTableSQL({ - tableName: 'bars_1m; DROP TABLE x', - columns: [{ name: 'ts', type: 'TIMESTAMP', designated: true }], - }) - ).toThrow(/Invalid table name/); - expect(() => - formatCreateTableSQL({ - tableName: 't', - columns: [{ name: 'ts TIMESTAMP); --', type: 'TIMESTAMP' }], - }) - ).toThrow(/Invalid column name/); - expect(() => - formatCreateTableSQL({ - tableName: 't', - columns: [{ name: 's', type: 'SYMBOL', capacity: 0 }], - }) - ).toThrow(/capacity/); - expect(() => - formatCreateTableSQL({ - tableName: 't', - columns: [ - { name: 'a', type: 'TIMESTAMP', designated: true }, - { name: 'b', type: 'TIMESTAMP', designated: true }, - ], - }) - ).toThrow(/Only one designated/); - }); - }); - - describe('readBars1m bound normalisation', () => { - it('converts offset bounds to UTC with fractional digits intact, across a day boundary', async () => { - const fake = new RecordingClient(); - - await readBars1m(fake, -0, '2024-01-01T23:30:00.5-05:00', '2024-01-02T09:30:00.000123+05:30'); - - expect(fake.calls).toHaveLength(1); - expect(fake.calls[0]?.params).toEqual([ - '0', - '2024-01-02T04:30:00.5Z', - '2024-01-02T04:00:00.000123Z', - ]); - }); - - it('binds negative INT32 listing ids and parses negative SYMBOL values back', async () => { - const fake = new RecordingClient(); - (fake as unknown as { query: QuestDBQueryable['query'] }).query = async ( - sql: string, - params?: unknown[] - ) => { - fake.calls.push({ sql, params }); - return { - rows: [ - { - listing_id: '-2147483648', - open: 1, - high: 1, - low: 1, - close: 1, - volume: 1, - vwap: null, - session: null, - source: null, - known_at_us: '1704205800000000', - ts_us: '1704205800000000', - }, - ] as T[], - rowCount: 1, - executionTime: 0, - }; - }; - - const rows = await readBars1m( - fake, - -2147483648, - '2024-01-02T14:30:00Z', - '2024-01-02T14:31:00Z' - ); - - expect(fake.calls[0]?.params?.[0]).toBe('-2147483648'); - expect(rows[0]?.listing_id).toBe(-2147483648); - expect(rows[0]?.vwap).toBeNull(); - }); - - it('rejects impossible calendar dates, out-of-range offsets and NaN dates before querying', async () => { - const fake = new RecordingClient(); - const to = '2024-03-01T00:00:00Z'; - - await expect(readBars1m(fake, 1, '2024-02-30T00:00:00Z', to)).rejects.toThrow(/calendar/); - await expect(readBars1m(fake, 1, '2024-02-01T00:00:00+24:00', to)).rejects.toThrow( - /offset/ - ); - await expect(readBars1m(fake, 1, new Date('nope'), to)).rejects.toThrow(/NaN/); - await expect(readBars1m(fake, 1, '2024-02-01T00:00:00.1234567Z', to)).rejects.toThrow( - /timezone/ - ); - - expect(fake.calls).toHaveLength(0); - }); - }); -}); diff --git a/libs/data/questdb/test/questdb-query-layer.test.ts b/libs/data/questdb/test/questdb-query-layer.test.ts deleted file mode 100644 index ce587670..00000000 --- a/libs/data/questdb/test/questdb-query-layer.test.ts +++ /dev/null @@ -1,658 +0,0 @@ -import { describe, expect, it } from 'bun:test'; -import { readFileSync } from 'node:fs'; -import { resolve } from 'node:path'; -import type { QueryResultRow } from 'pg'; -import { - formatCreateTableSQL, - getM2IntradayDDL, - QuestDBClient, - QuestDBQueryBuilder, - QuestDBSchemaManager, - readBars1m, - type QueryResult, - type QuestDBQueryable, -} from '../src'; - -interface RecordedQuery { - sql: string; - params: unknown[] | undefined; -} - -class FakeQuestDBClient implements QuestDBQueryable { - public readonly calls: RecordedQuery[] = []; - private nextRows: unknown[] = []; - private nextError: Error | null = null; - - public setRows(rows: unknown[]): void { - this.nextRows = rows; - } - - public failNext(error: Error): void { - this.nextError = error; - } - - public async query( - sql: string, - params?: unknown[] - ): Promise> { - this.calls.push({ sql, params }); - if (this.nextError) { - const err = this.nextError; - this.nextError = null; - throw err; - } - return { - rows: this.nextRows as T[], - rowCount: this.nextRows.length, - executionTime: 1, - }; - } -} - -function createClientWithFakeQuery(fake: FakeQuestDBClient): QuestDBClient { - const client = new QuestDBClient( - { - host: 'questdb.test.local', - httpPort: 9000, - pgPort: 8812, - influxPort: 9009, - database: 'qdb', - }, - { - info: () => {}, - warn: () => {}, - error: () => {}, - debug: () => {}, - } - ); - // Route PGWire query execution to the recording fake without opening a network socket. - (client as unknown as { query: QuestDBQueryable['query'] }).query = fake.query.bind(fake); - return client; -} - -function normalizeSql(sql: string): string { - return sql - .replace(/--[^\n]*/g, '') - .replace(/;/g, '') - .replace(/\s+/g, ' ') - .replace(/\(\s+/g, '(') - .replace(/\s+\)/g, ')') - .replace(/\s+,/g, ',') - .trim(); -} - -describe('QuestDB 10.2.0 query layer', () => { - describe('LATEST ON clause generation', () => { - it('emits LATEST ON after WHERE with explicit timestamp and partition key', async () => { - const fake = new FakeQuestDBClient(); - const builder = QuestDBQueryBuilder.create(fake) - .select('listing_id', 'ts', 'close') - .from('bars_1m') - .where('listing_id = $1', ['1042']) - .latestOn('ts', 'listing_id'); - - const built = builder.buildParameterized(); - expect(built.sql).toBe( - 'SELECT listing_id, ts, close FROM bars_1m WHERE listing_id = $1 LATEST ON ts PARTITION BY listing_id' - ); - expect(built.params).toEqual(['1042']); - expect(builder.build()).toBe(built.sql); - expect(builder.toSQL()).toBe(built.sql); - - await builder.execute(); - expect(fake.calls).toHaveLength(1); - expect(fake.calls[0]).toEqual({ - sql: built.sql, - params: ['1042'], - }); - }); - - it('preserves multi-key PARTITION BY ordering', () => { - const fake = new FakeQuestDBClient(); - const sql = QuestDBQueryBuilder.create(fake) - .select('listing_id', 'session', 'ts', 'close') - .from('bars_1m') - .latestOn('ts', 'listing_id', 'session') - .build(); - - expect(sql).toBe( - 'SELECT listing_id, session, ts, close FROM bars_1m LATEST ON ts PARTITION BY listing_id, session' - ); - }); - - it('resolves table-appropriate default timestamps for latestBy()', () => { - const fake = new FakeQuestDBClient(); - - expect(QuestDBQueryBuilder.create(fake).from('bars_1m').latestBy('listing_id').build()).toBe( - 'SELECT * FROM bars_1m LATEST ON ts PARTITION BY listing_id' - ); - expect(QuestDBQueryBuilder.create(fake).from('fx_1m').latestBy('pair').build()).toBe( - 'SELECT * FROM fx_1m LATEST ON ts PARTITION BY pair' - ); - expect( - QuestDBQueryBuilder.create(fake).from('bar_revisions').latestBy('listing_id').build() - ).toBe('SELECT * FROM bar_revisions LATEST ON revised_at PARTITION BY listing_id'); - expect(QuestDBQueryBuilder.create(fake).from('ohlcv_data').latestBy('symbol').build()).toBe( - 'SELECT * FROM ohlcv_data LATEST ON timestamp PARTITION BY symbol' - ); - }); - - it('routes QuestDBClient.latestBy() through the builder with timestamp override and bound filters', async () => { - const fake = new FakeQuestDBClient(); - const client = createClientWithFakeQuery(fake); - - await client.latestBy('bars_1m', ['listing_id', 'ts', 'close'], 'listing_id', { - where: 'session = $1', - params: ['RTH'], - }); - await client.latestBy('bar_revisions', '*', ['listing_id', 'timeframe']); - await client.latestBy('bars_1m', 'close', 'listing_id', { - timestampColumn: 'known_at', - }); - - expect(fake.calls).toEqual([ - { - sql: 'SELECT listing_id, ts, close FROM bars_1m WHERE session = $1 LATEST ON ts PARTITION BY listing_id', - params: ['RTH'], - }, - { - sql: 'SELECT * FROM bar_revisions LATEST ON revised_at PARTITION BY listing_id, timeframe', - params: [], - }, - { - sql: 'SELECT close FROM bars_1m LATEST ON known_at PARTITION BY listing_id', - params: [], - }, - ]); - }); - }); - - describe('parameterized predicates and placeholder renumbering', () => { - it('binds all filter values and keeps hostile input out of SQL', () => { - const fake = new FakeQuestDBClient(); - const hostile = "x' OR '1'='1"; - const start = new Date('2024-01-02T14:30:00.000Z'); - const end = new Date('2024-01-02T15:30:00.000Z'); - - const { sql, params } = QuestDBQueryBuilder.create(fake) - .select('symbol', 'exchange', 'timestamp', 'close') - .from('ohlcv_data') - .whereSymbol(hostile) - .whereSymbolIn(['AAPL', 'MSFT']) - .whereExchange('NASDAQ') - .whereTimeRange(start, end) - .whereLastHours(6) - .whereLastDays(2) - .limit(25) - .buildParameterized(); - - expect(sql).toBe( - 'SELECT symbol, exchange, timestamp, close FROM ohlcv_data ' + - "WHERE symbol = $1 AND symbol IN ($2, $3) AND exchange = $4 AND timestamp >= $5 AND timestamp <= $6 AND timestamp > dateadd('h', $7, now()) AND timestamp > dateadd('d', $8, now()) " + - 'LIMIT $9' - ); - expect(sql).not.toContain(hostile); - expect(sql).not.toContain('AAPL'); - expect(sql).not.toContain('NASDAQ'); - expect(params).toEqual([ - hostile, - 'AAPL', - 'MSFT', - 'NASDAQ', - '2024-01-02T14:30:00.000Z', - '2024-01-02T15:30:00.000Z', - -6, - -2, - 25, - ]); - }); - - it('renumbers raw where() fragments consecutively across repeated, multi-digit, quoted, and commented placeholders', () => { - const fake = new FakeQuestDBClient(); - const tenParams = ['p1', 'p2', 'p3', 'p4', 'p5', 'p6', 'p7', 'p8', 'p9', 'p10']; - const tenPred = - 'c1=$1 AND c2=$2 AND c3=$3 AND c4=$4 AND c5=$5 AND c6=$6 AND c7=$7 AND c8=$8 AND c9=$9 AND c10=$10'; - - const { sql, params } = QuestDBQueryBuilder.create(fake) - .from('ohlcv_data') - .limit(10) - .whereSymbol('SPY') - .where( - "note = '$1' AND \"col_$2\" = $1 AND close >= $1 -- ignore $3\n/* ignore $4 */ AND volume > $2", - [100.5, 5000] - ) - .where(tenPred, tenParams) - .buildParameterized(); - - expect(sql).toBe( - 'SELECT * FROM ohlcv_data WHERE symbol = $1 ' + - 'AND note = \'$1\' AND "col_$2" = $2 AND close >= $2 -- ignore $3\n/* ignore $4 */ AND volume > $3 ' + - 'AND c1=$4 AND c2=$5 AND c3=$6 AND c4=$7 AND c5=$8 AND c6=$9 AND c7=$10 AND c8=$11 AND c9=$12 AND c10=$13 ' + - 'LIMIT $14' - ); - expect(params).toHaveLength(14); - expect(params).toEqual(['SPY', 100.5, 5000, ...tenParams, 10]); - }); - - it('rejects empty IN lists and malformed/mismatched where() placeholders before querying', () => { - const fake = new FakeQuestDBClient(); - - expect(() => QuestDBQueryBuilder.create(fake).whereSymbolIn([])).toThrow( - /at least one symbol/i - ); - expect(() => QuestDBQueryBuilder.create(fake).where('close > $0', [1])).toThrow(/1-based/i); - expect(() => QuestDBQueryBuilder.create(fake).where('close > $2', [1])).toThrow( - /out of range/i - ); - expect(() => QuestDBQueryBuilder.create(fake).where('close > $1', [1, 2])).toThrow( - /Unused parameter/i - ); - expect(() => QuestDBQueryBuilder.create(fake).where('close > 10', [1])).toThrow( - /Unused parameter/i - ); - expect(() => QuestDBQueryBuilder.create(fake).where(' ')).toThrow(/non-empty/i); - - expect(fake.calls).toHaveLength(0); - }); - - it('resets builder cleanly for reuse after execution and after rejection', async () => { - const fake = new FakeQuestDBClient(); - const builder = QuestDBQueryBuilder.create(fake); - - fake.failNext(new Error('simulated wire failure')); - await expect(builder.from('ohlcv_data').whereSymbol('AAPL').execute()).rejects.toThrow( - 'simulated wire failure' - ); - - // Builder must be reset after failed execute() - const nextBuilt = builder.select('close').from('bars_1m').where('listing_id = $1', ['7']).buildParameterized(); - expect(nextBuilt).toEqual({ - sql: 'SELECT close FROM bars_1m WHERE listing_id = $1', - params: ['7'], - }); - - await builder.execute(); - expect(fake.calls).toHaveLength(2); - expect(fake.calls[1]).toEqual(nextBuilt); - // Builder is reset again after successful execute() - expect(() => builder.build()).toThrow('FROM clause is required'); - }); - - it('terminates trailing line comments with a newline before subsequent predicates, LATEST ON, and SAMPLE BY', async () => { - const fake = new FakeQuestDBClient(); - const client = createClientWithFakeQuery(fake); - - const builderResult = QuestDBQueryBuilder.create(fake) - .select('listing_id', 'ts', 'close') - .from('bars_1m') - .where('session = $1 -- regular session', ['RTH']) - .where('close > $1 -- minimum price', [100]) - .latestOn('ts', 'listing_id') - .buildParameterized(); - - expect(builderResult.sql).toBe( - 'SELECT listing_id, ts, close FROM bars_1m ' + - 'WHERE session = $1 -- regular session\n ' + - 'AND close > $2 -- minimum price\n ' + - 'LATEST ON ts PARTITION BY listing_id' - ); - expect(builderResult.params).toEqual(['RTH', 100]); - - await client.latestBy('bars_1m', ['listing_id', 'ts', 'close'], 'listing_id', { - where: 'session = $1 -- regular session', - params: ['RTH'], - }); - await client.sampleBy( - 'bars_1m', - ['ts', 'close'], - '1h', - 'ts', - 'session = $1 -- regular session', - ['RTH'] - ); - - expect(fake.calls).toEqual([ - { - sql: - 'SELECT listing_id, ts, close FROM bars_1m ' + - 'WHERE session = $1 -- regular session\n ' + - 'LATEST ON ts PARTITION BY listing_id', - params: ['RTH'], - }, - { - sql: - 'SELECT ts, close FROM bars_1m ' + - 'WHERE session = $1 -- regular session\n ' + - 'SAMPLE BY 1h ALIGN TO CALENDAR', - params: ['RTH'], - }, - ]); - }); - }); - - describe('identifier and interval validation', () => { - it('rejects hostile table, column, alias, latestOn, sort, and sampleBy inputs before querying', async () => { - const fake = new FakeQuestDBClient(); - const client = createClientWithFakeQuery(fake); - - expect(() => QuestDBQueryBuilder.create(fake).from('bars_1m; DROP TABLE x')).toThrow( - /Invalid table name/i - ); - expect(() => QuestDBQueryBuilder.create(fake).select('close; --')).toThrow( - /Invalid SELECT column/i - ); - expect(() => - QuestDBQueryBuilder.create(fake).selectAgg({ 'bad alias': 'avg(close)' }) - ).toThrow(/Invalid aggregation alias/i); - expect(() => QuestDBQueryBuilder.create(fake).latestOn('ts; --', 'listing_id')).toThrow( - /Invalid LATEST ON timestamp column/i - ); - expect(() => QuestDBQueryBuilder.create(fake).latestOn('ts', 'listing_id; DROP')).toThrow( - /Invalid LATEST ON partition column/i - ); - expect(() => QuestDBQueryBuilder.create(fake).orderBy('ts', 'UP' as 'ASC')).toThrow( - /Invalid ORDER BY direction/i - ); - expect(() => QuestDBQueryBuilder.create(fake).sampleBy('1h; DROP TABLE x')).toThrow( - /Invalid SAMPLE BY interval/i - ); - expect(() => QuestDBQueryBuilder.create(fake).sampleBy('1x')).toThrow( - /Invalid SAMPLE BY interval/i - ); - - await expect( - client.sampleBy('bars_1m', ['ts', 'close'], 'bad_interval') - ).rejects.toThrow(/Invalid SAMPLE BY interval/i); - await expect( - client.latestBy('bars_1m; DROP TABLE x', '*', 'listing_id') - ).rejects.toThrow(/Invalid table name/i); - await expect( - client.asofJoin('bars_1m', 'fx_1m; DROP', 'bars_1m.ts = fx_1m.ts') - ).rejects.toThrow(/Invalid right table name/i); - - expect(fake.calls).toHaveLength(0); - }); - - it('binds table name in QuestDBSchemaManager.tableExists() via tables()', async () => { - const fake = new FakeQuestDBClient(); - fake.setRows([{ count: 1 }]); - const manager = new QuestDBSchemaManager(fake); - - const hostileTable = "bars_1m' OR '1'='1"; - const exists = await manager.tableExists(hostileTable); - - expect(exists).toBe(true); - expect(fake.calls).toHaveLength(1); - expect(fake.calls[0]).toEqual({ - sql: 'SELECT COUNT(*) as count FROM tables() WHERE table_name = $1', - params: [hostileTable], - }); - }); - - it('binds table name in QuestDBClient.getTableInfo() via table_columns($1)', async () => { - const fake = new FakeQuestDBClient(); - const client = createClientWithFakeQuery(fake); - fake.setRows([{ column: 'ts', type: 'TIMESTAMP' }]); - - const rows = await client.getTableInfo('bars_1m'); - - expect(rows).toEqual([{ column: 'ts', type: 'TIMESTAMP' }]); - expect(fake.calls).toEqual([ - { - sql: 'SELECT * FROM table_columns($1)', - params: ['bars_1m'], - }, - ]); - }); - }); - - describe('M2 intraday contract DDL', () => { - it('matches design/DATA-CONTRACTS.md §3.B exactly after whitespace and comment normalization', () => { - const contractPath = resolve(import.meta.dir, '../../../../design/DATA-CONTRACTS.md'); - const contractDoc = readFileSync(contractPath, 'utf8'); - const sectionMatch = contractDoc.match( - /### B\. QuestDB `10\.2\.0`[\s\S]*?```sql\n([\s\S]*?)```/ - ); - expect(sectionMatch).not.toBeNull(); - - const contractStatements = sectionMatch![1]! - .split(';') - .map(normalizeSql) - .filter(Boolean); - expect(contractStatements).toHaveLength(3); - - const generated = getM2IntradayDDL(); - expect(normalizeSql(generated.bars_1m)).toBe(contractStatements[0]!); - expect(normalizeSql(generated.fx_1m)).toBe(contractStatements[1]!); - expect(normalizeSql(generated.bar_revisions)).toBe(contractStatements[2]!); - - expect(generated.bars_1m).toContain('listing_id SYMBOL CAPACITY 65536 NOCACHE'); - expect(generated.bars_1m).toContain('session SYMBOL CAPACITY 8 CACHE'); - expect(generated.bars_1m).toContain('source SYMBOL CAPACITY 8 CACHE'); - expect(generated.bars_1m).toContain('TIMESTAMP(ts) PARTITION BY MONTH WAL'); - expect(generated.bars_1m).toContain('DEDUP UPSERT KEYS(ts, listing_id)'); - - expect(generated.fx_1m).toContain('pair SYMBOL CAPACITY 32 CACHE'); - expect(generated.fx_1m).toContain('TIMESTAMP(ts) PARTITION BY MONTH WAL'); - expect(generated.fx_1m).toContain('DEDUP UPSERT KEYS(ts, pair)'); - - expect(generated.bar_revisions).toContain('listing_id SYMBOL CAPACITY 65536 NOCACHE'); - expect(generated.bar_revisions).toContain('TIMESTAMP(revised_at) PARTITION BY MONTH WAL'); - expect(generated.bar_revisions).not.toContain('DEDUP'); - }); - - it('keeps M2 intraday tables opt-in outside legacy startup initialization', () => { - const fake = new FakeQuestDBClient(); - const manager = new QuestDBSchemaManager(fake); - const startupNames = manager.getSchemaNames(); - - expect(startupNames).not.toContain('bars_1m'); - expect(startupNames).not.toContain('fx_1m'); - expect(startupNames).not.toContain('bar_revisions'); - - // Shared formatter also validates dedup keys exist on the table - expect(() => - formatCreateTableSQL({ - tableName: 'bad_table', - columns: [{ name: 'ts', type: 'TIMESTAMP', designated: true }], - dedupUpsertKeys: ['ts', 'missing_col'], - }) - ).toThrow(/does not exist/i); - }); - }); - - describe('readBars1m storage reader', () => { - it('sends one parameterized [from, to) query with UTC epoch-microsecond projection and converts listing_id to INT32', async () => { - const fake = new FakeQuestDBClient(); - // 2024-01-02T14:30:00.000000Z = 1704205800000000 us - // 2024-01-02T14:31:00.000700Z = 1704205860000700 us (6 fractional digits preserved) - // 2024-01-02T14:31:00.000000Z = 1704205860000000 us - // 2024-01-02T14:32:00.123456Z = 1704205920123456 us - const fixtureRows = [ - { - listing_id: '1042', - open: 185.1, - high: 185.5, - low: 184.9, - close: 185.4, - volume: 12500, - vwap: 185.28, - session: 'RTH', - source: 'eod_unadj', - known_at_us: '1704205860000700', - ts_us: '1704205800000000', - }, - { - listing_id: '1042', - open: 185.4, - high: 185.6, - low: 185.3, - close: 185.55, - volume: 0, - vwap: null, - session: 'RTH', - source: 'ib_live', - known_at_us: 1704205920123456n, - ts_us: 1704205860000000, - }, - ]; - fake.setRows(fixtureRows); - - const from = new Date('2024-01-02T14:30:00.000Z'); - const to = new Date('2024-01-02T14:32:00.000Z'); - - const firstRead = await readBars1m(fake, 1042, from, to); - const secondRead = await readBars1m(fake, 1042, from, to); - - expect(fake.calls).toHaveLength(2); - expect(fake.calls[0]).toEqual({ - sql: - 'SELECT listing_id, open, high, low, close, volume, vwap, session, source, CAST(known_at AS LONG) AS known_at_us, CAST(ts AS LONG) AS ts_us ' + - 'FROM bars_1m ' + - 'WHERE listing_id = $1 AND ts >= $2 AND ts < $3 ' + - 'ORDER BY ts ASC', - params: ['1042', '2024-01-02T14:30:00.000Z', '2024-01-02T14:32:00.000Z'], - }); - - expect(firstRead).toEqual(secondRead); - expect(firstRead).toEqual([ - { - listing_id: 1042, - open: 185.1, - high: 185.5, - low: 184.9, - close: 185.4, - volume: 12500, - vwap: 185.28, - session: 'RTH', - source: 'eod_unadj', - known_at: 1704205860000700n, - ts: 1704205800000000n, - }, - { - listing_id: 1042, - open: 185.4, - high: 185.6, - low: 185.3, - close: 185.55, - volume: 0, - vwap: null, - session: 'RTH', - source: 'ib_live', - known_at: 1704205920123456n, - ts: 1704205860000000n, - }, - ]); - expect(typeof firstRead[0]!.listing_id).toBe('number'); - // Verify sub-millisecond ordering is preserved (14:31:00.000700Z > 14:31:00.000000Z) - expect(firstRead[0]!.known_at > 1704205860000000n).toBe(true); - }); - - it('preserves 6-digit microsecond bounds and produces identical results under non-UTC TZ', async () => { - const fake = new FakeQuestDBClient(); - fake.setRows([ - { - listing_id: '1042', - open: 185.1, - high: 185.5, - low: 184.9, - close: 185.4, - volume: 12500, - vwap: 185.28, - session: 'RTH', - source: 'eod_unadj', - known_at_us: '1704205860000700', - ts_us: '1704205800000000', - }, - ]); - - const previousTz = process.env.TZ; - try { - process.env.TZ = 'UTC'; - const utcRows = await readBars1m( - fake, - 1042, - '2024-01-02T14:30:00.000000Z', - '2024-01-02T14:31:00.000700Z' - ); - - process.env.TZ = 'America/Toronto'; - const torontoRows = await readBars1m( - fake, - 1042, - '2024-01-02T14:30:00.000000Z', - '2024-01-02T14:31:00.000700Z' - ); - - expect(torontoRows).toEqual(utcRows); - expect(torontoRows[0]!.known_at).toBe(1704205860000700n); - expect(torontoRows[0]!.ts).toBe(1704205800000000n); - expect(fake.calls[0]?.params).toEqual([ - '1042', - '2024-01-02T14:30:00.000000Z', - '2024-01-02T14:31:00.000700Z', - ]); - expect(fake.calls[1]?.params).toEqual(fake.calls[0]?.params); - } finally { - if (previousTz === undefined) { - delete process.env.TZ; - } else { - process.env.TZ = previousTz; - } - } - - // Reject timezone-naive string bounds that would depend on host local timezone - await expect( - readBars1m(fake, 1042, '2024-01-02T14:30:00', '2024-01-02T14:35:00Z') - ).rejects.toThrow(/timezone/i); - }); - - it('returns empty array when no bars exist in range', async () => { - const fake = new FakeQuestDBClient(); - fake.setRows([]); - - const rows = await readBars1m( - fake, - 0, - '2024-01-02T14:30:00.000Z', - '2024-01-02T14:35:00.000Z' - ); - - expect(rows).toEqual([]); - expect(fake.calls[0]?.params).toEqual([ - '0', - '2024-01-02T14:30:00.000Z', - '2024-01-02T14:35:00.000Z', - ]); - }); - - it('rejects invalid input listingIds and malformed returned SYMBOL listing_id values', async () => { - const fake = new FakeQuestDBClient(); - const from = new Date('2024-01-02T14:30:00.000Z'); - const to = new Date('2024-01-02T14:35:00.000Z'); - - await expect(readBars1m(fake, 1.5, from, to)).rejects.toThrow(/INT32/i); - await expect(readBars1m(fake, 2147483648, from, to)).rejects.toThrow(/INT32/i); - expect(fake.calls).toHaveLength(0); - - for (const badSymbol of ['abc', '007', '12.5', '2147483648', null]) { - fake.setRows([ - { - listing_id: badSymbol, - open: 1, - high: 2, - low: 1, - close: 2, - volume: 10, - vwap: 1.5, - session: 'RTH', - source: 'eod_unadj', - known_at_us: '1704205800000000', - ts_us: '1704205800000000', - }, - ]); - await expect(readBars1m(fake, 42, from, to)).rejects.toThrow(/listing_id SYMBOL/i); - } - }); - }); -}); diff --git a/libs/data/questdb/test/questdb.test.ts b/libs/data/questdb/test/questdb.test.ts index 80a682f3..09c5377d 100644 --- a/libs/data/questdb/test/questdb.test.ts +++ b/libs/data/questdb/test/questdb.test.ts @@ -252,20 +252,19 @@ describe('QuestDB', () => { const builder = new QuestDBQueryBuilder(mockClient); - const { sql, params } = builder + const query = builder .select('symbol', 'close', 'volume') .from('ohlcv_data') .whereSymbol('AAPL') .orderBy('timestamp', 'DESC') .limit(100) - .buildParameterized(); + .build(); - expect(sql).toContain('SELECT symbol, close, volume'); - expect(sql).toContain('FROM ohlcv_data'); - expect(sql).toContain('symbol = $1'); - expect(sql).toContain('ORDER BY timestamp DESC'); - expect(sql).toContain('LIMIT $2'); - expect(params).toEqual(['AAPL', 100]); + expect(query).toContain('SELECT symbol, close, volume'); + expect(query).toContain('FROM ohlcv_data'); + expect(query).toContain("symbol = 'AAPL'"); + expect(query).toContain('ORDER BY timestamp DESC'); + expect(query).toContain('LIMIT 100'); }); it('should build query with time range', () => { diff --git a/libs/research/README.md b/libs/research/README.md index d4eac9a3..8f0d6452 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -74,303 +74,3 @@ Fixed-seed (`20260402`) end-to-end `analyzeSignal` benchmark covering `5,040` bu - **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`) - -## DuckDB Curated Parquet Query Planner & `MarketDataStore` Adapter - -Exported from both `@stock-bot/research` and `@stock-bot/research/market-data-store-duckdb` (`libs/research/src/market-data-store-duckdb.ts`). The module is dependency-free and browser-safe; DuckDB execution is injected via `DuckDbExecutor` (`{ run(sql), query(sql, params) }`) so parameter values are always bound separately from SQL text. - -### API - -- **`planBars1dQuery(q, ctx)`** — Plans a fenced query over `/bars_1d/year=*/part.parquet` (`hive_partitioning = true`) for `timeframe: '1d'` and `adjustment: 'raw' | 'split' | 'total'`. Rejects `'1m' | '5m' | '1h'` with `MarketDataStoreNotImplementedError`. For `'split'` and `'total'`, requires a verified `point_in_time_fenced` `ctx.adjFactorsSnapshot` matching the query's effective `asOf` and Vault fence, and binds `read_parquet(...)` directly to `ctx.adjFactorsSnapshot.path`. -- **`planAdjFactorsMetadataQuery(adjPath)`** / **`parseAdjFactorsSnapshotMetadata(adjPath, kvRows)`** — Plans the `parquet_kv_metadata('')` query for `stock_bot.adj_factors.*` footer keys and strictly parses/validates them (mirroring `tools/curate-etl/src/curate_adj.rs`). -- **`planEventsQuery(q, ctx)`** — Plans a `'vault_fenced'` query over `/events/year=*/part.parquet` (`hive_partitioning = true`) filtered by allow-listed `kinds` and optional `listingIds`, preserving the Parquet writer's total sort order `(listing_id, ts, kind, subtype, payload_json, known_at, known_at_source)`. -- **`planShortsAsOfQuery(q, ctx)`** — Plans a `'vault_fenced'` query over `/shorts/part.parquet`, binding UTC `YYYY-MM-DD` `report_date` bounds and microsecond UTC ISO-8601 `known_at <= ?`. -- **`planFundamentalsAsOfQuery(q, ctx)`** — Plans a `'vault_fenced'` point-in-time query over `/fundamentals_pit/year=*/part.parquet` (`hive_partitioning = true`) selecting at most one latest snapshot (`effective_known_at <= asOf`, clamped strictly below `vaultCutoffTs`) per requested `listing_id` across allow-listed `FUNDAMENTALS_PIT_VALUE_FIELDS`, with `allowEstimatedLag` (default `true`) failing closed on snapshot-level `has_estimated_lag` without fallback and masking `ttm_*` values/date/currency when `ttm_has_estimated_lag` is `true`. -- **`planFx1dQuery(q, ctx)`** — Plans a `'vault_fenced'` query (with default `asOf = vaultCutoffTs * 1000 - 1` µs) over `/fx_1d/part.parquet` for `timeframe: '1d'`, mapping `'USD.CAD'` to the stored bound parameter `'USDCAD'`. Rejects `'1m'` with `MarketDataStoreNotImplementedError`. -- **`planUniverseQuery(q, ctx)`** — Plans a `'vault_fenced'`, survivorship-free query over `/bars_1d/year=*/part.parquet` (`hive_partitioning = true`) returning `SELECT DISTINCT b.listing_id ... ORDER BY b.listing_id ASC` for supported `UNIVERSE_REFS` (`'US_EQ'`, `'CA_EQ'`, `'US_CA_EQ'`) within `[date - lookbackDays, date]` (default `DEFAULT_UNIVERSE_LOOKBACK_DAYS = 7`, configurable via `ctx.universeLookbackDays`). -- **`createDuckDbMarketDataStore({ executor, curatedRoot, vaultCutoffTs, vaultOperatorAuthorized?, universeLookbackDays?, adjFactorsPath?, pinAdjFactorsArtifact?, immutableAdjFactorsPath?, env?, barBatchSize? })`** — Returns a `MarketDataStore` adapter that eagerly validates options and `resolveDuckDbConnectionBudget(env)`, lazily executes the three budget `SET` statements sequentially and at most once before the first `executor.query(...)` (including under concurrent first calls, with clean retry if initialization fails), pins a single `adj_factors` artifact version across both `parquet_kv_metadata` footer verification and the `read_parquet` factor scan (via `pinAdjFactorsArtifact` handle pinning or an explicit write-once `immutableAdjFactorsPath` distinct from the mutable `/adj_factors/part.parquet`, failing closed with `AdjFactorsSnapshotError('unpinned_mutable_path')` if unpinned), validates per-column scalar types and nullability when mapping rows into `BarBatch` / `Table` / strictly ascending INT32 `universe` `number[]`, and rejects out-of-slice methods (`bars` `1m`/`5m`/`1h`, `fx` `1m`, `crossSection`, `macroAsOf`) with `MarketDataStoreNotImplementedError` and zero executor calls. - -### Mandatory Vault, PIT, Microsecond & Boundary Validation Rules - -- Every planner delegates unconditionally to `applyVaultFence`, binding `ts`/`report_date` bounds and `known_at <= ?` in UTC (`TZ`-invariant). Under `'vault_fenced'`, `from >= vaultCutoffTs` throws `VaultHoldoutFenceError` and `to`/`asOf` clamp strictly below `vaultCutoffTs`; `'vault_evaluation_only'` requires `vaultOperatorAuthorized === true` (only on `bars`; `events`, `shortsAsOf`, and `fx` are always `'vault_fenced'`). -- **Microsecond upper-bound precision:** Curated Parquet `ts` and `known_at` columns store UTC microseconds (`curate_fx_1d` stamps `23:59:59.999999Z`). Date-only `YYYY-MM-DD` upper bounds (`to`, `asOf`) and default or clamped Vault upper bounds expand to the last included Parquet microsecond (`.999999Z` / `vaultCutoffTs * 1000 - 1`), while explicit time-of-day bounds preserve their caller-specified precision. Under `'vault_fenced'`, every planned upper bound remains strictly `< vaultCutoffTs`. -- `curatedRoot` (and optional `adjFactorsPath`) are the only values embedded in SQL text and must be absolute POSIX paths free of control characters (`<= 0x1f`, `0x7f`), `'`, `;`, and glob metacharacters (`*`, `?`, `[`, `]`). -- All caller values (`listingIds` as `INT32` safe integers, allow-listed `kinds`, `'USD.CAD' -> 'USDCAD'`, and UTC date/timestamp bounds) are validated upfront and passed strictly as bound `?` parameters. - -### `bars` 1d Adjustment Formulas & Verified Fenced `adj_factors` Requirement - -`bars_1d` stores raw OHLC, optional `vwap`, and split-unadjusted raw share `volume`. Because `adj_factors` stores right-to-left cumulative suffix products (`cum_split_factor`, `cum_total_factor`), slicing a retrospective `adj_factors` file with `known_at <= asOf` would still embed future or held-out Vault splits/dividends into earlier cumulative factors. - -- **`'raw'`**: OHLC, `vwap`, and `volume` are returned unadjusted (`adj_factors` is not read). -- **`'split'` / `'total'`**: Require a verified `point_in_time_fenced` `adj_factors` Parquet artifact (published by `curate_and_write_adj_factors_as_of` with `stock_bot.adj_factors.*` footer metadata) whose effective inclusive microsecond fence matches the query's effective `asOf` and Vault cutoff. Retrospective, unverified, or mismatched-fence files are rejected with `AdjFactorsSnapshotError` before any `bars` query runs. To prevent TOCTOU races when `curate-etl` atomically replaces `/adj_factors/part.parquet` between footer verification and the factor scan, `createDuckDbMarketDataStore` requires either `pinAdjFactorsArtifact` (binding a stable handle such as `/proc/self/fd/`, `/dev/fd/`, or a private hardlink/copy for both queries and releasing it in `finally`) or an explicit write-once `immutableAdjFactorsPath` distinct from the mutable published path; unpinned mutable paths fail closed with `AdjFactorsSnapshotError('unpinned_mutable_path')`. -- Against the verified `adj_factors` file, `bars_1d` is joined via `ASOF LEFT JOIN` (filtered to `listing_id IN (...) AND known_at <= ?`) on `b.listing_id = a.listing_id AND b.session_date < a.ex_date` (matching the first `adj_factors` row with `ex_date > session_date` per `tools/curate-etl/README.md`): - - **`'split'`**: `open`, `high`, `low`, `close`, and `vwap` are divided by `COALESCE(a.cum_split_factor, 1.0)`; `volume` is multiplied by `COALESCE(a.cum_split_factor, 1.0)`. - - **`'total'`**: `open`, `high`, `low`, `close`, and `vwap` are divided by `COALESCE(a.cum_total_factor, 1.0)`; `volume` is multiplied by `COALESCE(a.cum_split_factor, 1.0)`. - -### `universe` - -`planUniverseQuery` and `createDuckDbMarketDataStore().universe({ ref, date })` resolve the survivorship-free set of active `INT32` `listing_id`s on a UTC calendar `date` (`YYYY-MM-DD`) directly from curated `bars_1d` Parquet (`hive_partitioning = true`): - -- **Provisional M1 bar-currency membership rule:** Supported `UNIVERSE_REFS` (`'US_EQ'`, `'CA_EQ'`, `'US_CA_EQ'`, matching `trial_ledger.universe_market`) filter `bars_1d.currency` using bound `?` parameters (`'USD'`, `'CAD'`, or `IN ('USD', 'CAD')`). Because membership is provisionally determined by bar quote currency before security-master MIC joins are added, USD-quoted TSX listings land in `'US_EQ'`. `'FX'` and any other ref throw `MarketDataStoreValidationError` (`field: 'ref'`) with zero executor calls. -- **Active-listing lookback window:** A listing is active on `date` when it has at least one `bars_1d` row with `session_date` in `[date - lookbackDays, date]` (calendar days; default `DEFAULT_UNIVERSE_LOOKBACK_DAYS = 7`, optional positive-integer `universeLookbackDays` on context/store options). No row after `date` is ever read, so delisted listings appear only while they traded. -- **Mandatory Vault & PIT fence:** `date` is always routed through `applyVaultFence` under `'vault_fenced'` scope (`date >= vaultCutoffTs` throws `VaultHoldoutFenceError` with zero executor calls, even when `vaultOperatorAuthorized: true`), and every planned query binds both `b.ts <= ?` and `b.known_at <= ?` strictly below `vaultCutoffTs`. - -### Local Query-Planner Benchmark - -Fixed-seed (`20261129`) local benchmark planning `120,000` mixed queries across `bars` 1d (`raw`/`split`/`total`), `events` (with and without `listingIds`), `shortsAsOf`, and `fx` 1d, plus a fixed-seed (`20261129`) `universe` case exercising `createDuckDbMarketDataStore().universe()` (plan + adapter mapping) over `200` calls × `15,000` listing IDs (`3,000,000` mapped IDs) via an in-memory executor (checksums verified outside the timed sections): - -- **Command:** `bun run libs/research/scripts/benchmark-market-data-store-duckdb.ts` -- **Observed (Bun 1.2.16):** - - **Mixed planners (`120,000` queries):** `elapsedMs = 225.79 ms`, `queriesPerSec = 531,470 queries/s` (`758,061` bound params, pinned checksum `8606c98c`) - - **`universe` plan + adapter mapping (`200` calls × `15,000` listings):** `elapsedMs = 23.44 ms`, `callsPerSec = 8,534 calls/s`, `rowsPerSec = 128,011,137 rows/s` (`3,000,000` mapped IDs, pinned checksum `ef5f1136`) - -## Routed `MarketDataStore` (DuckDB Daily + QuestDB `1m` Intraday) - -Exported from `@stock-bot/research` and `@stock-bot/research/market-data-store-routed` (`libs/research/src/market-data-store-routed.ts`). The QuestDB intraday reader is also exported from `@stock-bot/research/market-data-store-questdb`. Both modules are pure, dependency-free, and browser-safe. - -- **`createRoutedMarketDataStore({ daily, intraday })`** — Composes a full daily `MarketDataStore` (e.g. `createDuckDbMarketDataStore`) with an intraday `bars` reader (`Pick`, e.g. `createQuestDbIntradayBarsReader`). - - `bars(q)` with `timeframe: '1m'` delegates directly to `intraday.bars(q)` (preserving lazy iteration, receiver, query identity, and error propagation). Note that `createQuestDbIntradayBarsReader` supports split-unadjusted raw (`adjustment: 'raw'`) `1m` bars. - - `bars(q)` with any other timeframe (`'1d'`, `'5m'`, `'1h'`, or malformed inputs) and all other `MarketDataStore` methods (`crossSection`, `fundamentalsAsOf`, `events`, `shortsAsOf`, `macroAsOf`, `fx`, `universe`) delegate directly to `daily`. - - **Shared Vault fence requirement:** The router adds no Vault logic of its own; each delegate enforces its own fence. Always construct `daily` and `intraday` with the exact same `vaultCutoffTs` and `vaultOperatorAuthorized`, and pass that same `vaultCutoffTs` to `createQueryDataTool` (which is always Vault-fenced and accepts only `{ vaultCutoffTs }`): - -```ts -const vaultCutoffTs = Date.UTC(2025, 6, 1, 0, 0, 0, 0); -const vaultOperatorAuthorized = false; - -const daily = createDuckDbMarketDataStore({ - executor: duckDbExecutor, - curatedRoot: '/mnt/data/stockbot/curated', - vaultCutoffTs, - vaultOperatorAuthorized, -}); -const intraday = createQuestDbIntradayBarsReader({ - executor: questDbExecutor, - vaultCutoffTs, - vaultOperatorAuthorized, -}); -const store = createRoutedMarketDataStore({ daily, intraday }); -const queryDataTool = createQueryDataTool({ - store, - vaultContext: { vaultCutoffTs }, -}); -``` - -## Signal Panel Builder - -Exported from both `@stock-bot/research` and `@stock-bot/research/signal-panel` (`libs/research/src/signal-panel.ts`). The module is pure, synchronous (except `collectBars`), dependency-free, and browser-safe (zero `node:*` imports, zero bare `process` access, no database drivers). - -### API - -- **`buildForwardReturnPanel({ bars, signals, horizonSessions, vaultCutoffDate, maxSignalAgeSessions? })`** — Joins daily `BarRecord[]` (caller-supplied `'total'`-adjusted closes in any order) with point-in-time `SignalObservation[]` (`{ listingId, knownAt, value }`) into Vault-safe `SignalCrossSection[]` slices ready for `analyzeSignal`. Returns `{ panel, sessionDates, diagnostics }` with strictly ascending `date`s, `ids: Int32Array` sorted ascending by `listingId`, and `signal` / `forwardReturn` as `Float64Array`, deterministic under any input permutation and without mutating caller inputs. -- **`shortsTableToSignalRows(table, field)`** — Maps a `MarketDataStore.shortsAsOf` `Table` into `SignalObservation[]` for `field: 'shares_short' | 'net_change' | 'pct_float'`, skipping `null` cells, normalizing `-0` to `0`, and rejecting missing columns or malformed rows with `SignalPanelError`. -- **`collectBars(iterable)`** — Drains `AsyncIterable` (such as `MarketDataStore.bars`) into a flat `BarRecord[]` using indexed loops without mutating yielded batches. - -### UTC Session Calendar, PIT Alignment & Vault Rules - -- **UTC session calendar:** Daily curated bars (`bars_1d.ts`) are stamped at `16:00 ET` (`20:00` or `21:00 UTC`), so the integer UTC day key `Math.floor(bar.ts / 86_400_000)` maps 1:1 to the exchange session date `YYYY-MM-DD`. -- **Strict point-in-time (`knownAt <= bar.ts`):** For each listing and session `d`, the active signal is the latest row with `knownAt <= bar.ts` (ties on identical `(listingId, knownAt)` break deterministically by `value ASC` so the highest value wins regardless of input order). A signal known after the close (e.g. `17:00 ET`) is never applied on `d` and first takes effect on `d + 1`. -- **Signal staleness (`maxSignalAgeSessions`):** When set (`>= 0`), age is measured in calendar sessions elapsed since the first actionable session where `sessionMaxTs[s] >= knownAt` (so a `17:00 ET` after-close signal has age `0` on the next trading day). Expired observations are dropped and counted in `diagnostics.droppedStaleSignal`. -- **Exact horizon alignment & close validation:** `forwardReturn = close[d + h] / close[d] - 1` uses the listing's own bar exactly `horizonSessions` calendar sessions ahead; missing forward bars are dropped (`diagnostics.droppedMissingForwardBar`) and never shifted to `d + h + 1`. Non-positive or non-finite closes (`<= 0`, `NaN`, `±Infinity`) drop cleanly into `diagnostics.droppedNonPositiveClose` without throwing. Exact pre-cutoff duplicate bars (`ts` and `close` identical) are deduplicated into `diagnostics.duplicateBars`; conflicting duplicates on the same `(listingId, date)` throw `SignalPanelError('duplicate_bar')`. -- **Vault holdout fence:** `sessionDates` contains only dates strictly `< vaultCutoffDate`. No cross-section is emitted when either `d` or its forward session `d + horizonSessions` reaches or exceeds `vaultCutoffDate` (counted in `diagnostics.vaultExcludedDates`), and `bar.close` is never accessed for any bar on or after `vaultCutoffDate`. - -### `SignalPanelError` Codes - -| Code | Meaning | -| --- | --- | -| `'invalid_input'` | Non-object input envelope, non-array `bars`/`signals`, invalid `AsyncIterable`, invalid shorts field, or missing required table columns | -| `'invalid_horizon'` | `horizonSessions` is not a safe integer `>= 1` | -| `'invalid_option'` | `maxSignalAgeSessions` is defined and not a safe integer `>= 0` | -| `'invalid_date'` | `vaultCutoffDate` is not a valid strict calendar `YYYY-MM-DD` date | -| `'invalid_bar'` | Malformed bar record, invalid `INT32` `listingId`, invalid epoch-ms `ts`/`knownAt`, non-number pre-cutoff `close`, or malformed `BarBatch` | -| `'invalid_signal'` | Malformed signal or shorts table row, invalid `listingId`/`knownAt`, or non-finite non-null signal value | -| `'duplicate_bar'` | Two pre-cutoff bars for the same `(listingId, date)` disagree on `ts` or `close` | - -### Local In-Memory Benchmark (`buildForwardReturnPanel`) - -Fixed-seed (`20261129`) local benchmark covering `5,040` business sessions × `3,000` listings (`15,120,000` input bars, `720,000` monthly-ish `17:00 ET` signal rows, `horizonSessions = 5`, `vaultCutoffDate = '2025-03-31'`): - -- **Command:** `bun run libs/research/scripts/benchmark-signal-panel.ts` -- **Observed (Bun 1.2.16):** `elapsedMs = 817.24 ms`, `rowsPerSec = 18,501,301 rows/s` (`5,014` emitted panel dates, `15,042,000` emitted observations, `25` Vault-excluded dates, pinned checksum `f0f28bdf`) - -## Event Study Panel Builder - -Exported from both `@stock-bot/research` and `@stock-bot/research/event-panel` (`libs/research/src/event-panel.ts`). The module is pure, synchronous, dependency-free, and browser-safe (zero `node:*` imports, zero bare `process` access, no database drivers). - -### API - -- **`eventsTableToEventRows(table, filter?)`** — Maps a `MarketDataStore.events` `Table` into point-in-time `EventObservation[]` (`{ listingId, knownAt, kind, subtype }`), validating every row upfront (before applying optional exact-match `filter.kinds` / `filter.subtypes` allow-lists), normalizing `-0` to `0`, and rejecting missing columns, empty filter arrays, or malformed rows with `EventPanelError`. -- **`buildEventStudyInput({ bars, events, vaultCutoffDate, exchangeCalendars, benchmark? })`** — Transforms daily `BarRecord[]` (caller-supplied `'total'`-adjusted closes in any order) and `EventObservation[]` rows into a Vault-safe `EventStudyInput` (`{ sessionDates, entityReturns, benchmarkReturns?, events }`) plus `EventPanelDiagnostics` ready for `runEventStudy` / `eventStudy`. Output is deterministic under any input permutation (entities inserted in ascending `listingId` order; events sorted by `(dayIndex ASC, entityId ASC)`) without mutating caller inputs. - - `exchangeCalendars: { calendars, listingCalendarId }` (**required**): caller-supplied exchange close calendars (`{ date, closeTs }[]` per calendar ID, plus `listingId -> calendarId` mapping). Every pre-Vault listing in `bars` must be mapped to a calendar that covers all of its pre-Vault bar dates (coverage gaps or missing mappings throw `EventPanelError('invalid_option')`). Each listing's events are anchored against its exchange's actual pre-Vault session close timestamps (e.g. `13:00 ET` on NYSE half-days vs `16:00 ET` on TSX) rather than curated `bars_1d.ts` (`16:00 ET`), and the eligible session date is then mapped onto the shared `sessionDates` index. - - `benchmark?: 'equal_weight' | 'none'` (default `'none'` when omitted/`undefined`; `null` or any other value throws `EventPanelError('invalid_option')`): `'none'` omits `benchmarkReturns`; `'equal_weight'` sets `benchmarkReturns[d]` to the mean of finite `entityReturns` on session `d` (`NaN` when none). - -### UTC Session Calendar, PIT Anchoring, `NaN` Returns & Vault Rules - -- **UTC session calendar:** Daily curated bars (`bars_1d.ts`) are stamped at `16:00 ET` (`20:00` or `21:00 UTC`), so the integer UTC day key `Math.floor(bar.ts / 86_400_000)` maps 1:1 to the exchange session date `YYYY-MM-DD`. -- **Consecutive-session returns & `NaN` contract (`eventStudy`):** For each listing, `entityReturns` is a `Float64Array` aligned to `sessionDates`. Simple close-to-close return `close[d] / close[d - 1] - 1` is computed strictly when the listing has bars on consecutive exchange-calendar sessions (`currCalIdx === prevCalIdx + 1`) and both closes are finite and `> 0` with a finite ratio. Session `0`, missing-bar sessions (including an open exchange session missing for all listings), the first resumption session after a gap, and non-positive/non-finite/overflowing transitions (counted in `diagnostics.nonPositiveCloseReturns`) are written as `NaN` (never `±Infinity`), matching `eventStudy`'s contract in `libs/calculations/src/analytics/event-study.ts` (which rejects `±Infinity` with `NON_FINITE_RETURN` and cleanly drops events with any `NaN` in `[-preDays, +postDays]`). -- **Duplicate-bar policy:** Exact pre-cutoff duplicate bars (`ts` and `close` identical, including `NaN === NaN`) are deduplicated into `diagnostics.duplicateBars`; conflicting duplicates on the same `(listingId, date)` throw `EventPanelError('duplicate_bar')`. -- **Strict PIT event anchoring & drop precedence:** Each event is classified in strict order: (1) `knownAt >= vaultCutoffDate (00:00:00.000Z)` → `diagnostics.vaultExcludedEvents`; (2) listing has no pre-Vault bars → `diagnostics.droppedUnknownListing`; (3) `knownAt` is after the listing's last pre-Vault exchange close (or its eligible calendar date exceeds the last pre-Vault bar date) → `diagnostics.droppedAfterLastSession`; (4) eligible pre-Vault exchange session dates absent from `sessionDates` → `diagnostics.droppedMissingCalendarSession`; (5) lower-bound binary search over the listing's exchange close timestamps, matching `eventDayIndex` semantics so after-close and post-half-day-close filings always anchor to the next trading session. Exact duplicate `(listingId, dayIndex)` events collapse to one (`diagnostics.duplicateEvents`), preserving `events.length === emitted + vaultExcludedEvents + droppedUnknownListing + droppedAfterLastSession + droppedMissingCalendarSession + duplicateEvents`. -- **Vault holdout fence:** `sessionDates` contains only dates strictly `< vaultCutoffDate` (post-cutoff dates are counted in `diagnostics.vaultExcludedDates`), and `bar.close` is never accessed for any bar on or after `vaultCutoffDate`. - -### `EventPanelError` Codes - -| Code | Meaning | -| --- | --- | -| `'invalid_input'` | Non-object input envelope, non-array `bars`/`events`, malformed `Table`, or missing required columns (`listing_id`, `known_at`, `kind`, `subtype`) | -| `'invalid_date'` | `vaultCutoffDate` or an `exchangeCalendars` session `date` is not a valid strict calendar `YYYY-MM-DD` date | -| `'invalid_bar'` | Malformed bar record, invalid `INT32` `listingId`, invalid epoch-ms `ts`/`knownAt`, or non-number pre-cutoff `close` | -| `'invalid_event'` | Malformed event or table row, invalid `listingId`/`knownAt`, `kind` outside `EVENT_KINDS`, or non-string/non-null `subtype` | -| `'invalid_option'` | Invalid `benchmark` mode, missing/malformed/incomplete `exchangeCalendars` (including pre-Vault bar coverage gaps), or invalid/empty `eventsTableToEventRows` filter (`kinds`/`subtypes`) | -| `'duplicate_bar'` | Two pre-cutoff bars for the same `(listingId, date)` disagree on `ts` or `close` | - -### Local In-Memory Benchmark (`buildEventStudyInput`) - -Fixed-seed (`20261129`) local benchmark covering `5,040` business sessions × `3,000` listings (`15,120,000` input bars, `240,000` after-close `17:00 ET` filing events at stride `63`, `vaultCutoffDate = '2025-03-31'`, `benchmark: 'equal_weight'`, `XNYS`/`XTSE` exchange calendars): - -- **Command:** `bun run libs/research/scripts/benchmark-event-panel.ts` -- **Observed (Bun 1.2.16):** `elapsedMs = 731.06 ms`, `barsPerSec = 20,682,279 bars/s`, `eventsPerSec = 328,290 events/s` (`5,020` pre-Vault sessions, `240,000` anchored events, `20` Vault-excluded dates, pinned checksum `01b356d3`) - -## MCP Copilot Core - -Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported via the `@stock-bot/research/mcp` subpath (`libs/research/src/mcp/index.ts`). It is intentionally **not** re-exported from the browser-safe `@stock-bot/research` default entrypoint. - -### Registering Tools & Running Stdio Framing - -- **`defineMcpTool({ name, description, inputSchema, jsonSchema?, handler })`** — Registers a strict Zod-validated tool, converts `inputSchema` into a strict JSON Schema (`additionalProperties: false`, or uses an explicit `jsonSchema` override), returns `isError: true` on invalid arguments without calling the handler, and sanitizes thrown handler errors so stack traces never leak. -- **`createMcpServer({ name, version, tools })`** — Transport-agnostic JSON-RPC 2.0 dispatcher implementing `initialize`, `notifications/initialized`, `ping`, `tools/list`, and `tools/call` via `handleMessage(raw: string): Promise`. Rejects duplicate tool names at creation time. -- **`runStdioServer(server, { input?, output?, maxLineBytes? })`** — Newline-delimited JSON-RPC stdio transport over injectable streams (defaulting to `process.stdin` / `process.stdout`), with streaming UTF-8 decoding across arbitrary chunk boundaries, strict sequential dispatch in arrival order, `maxLineBytes` frame-size protection (default `4 MiB`), and zero non-protocol bytes on `output`. - -### `query_data` Tool (Vault-Fenced) - -- **`createQueryDataTool({ store, vaultContext })`** — Wraps an injected `MarketDataStore` for explicit `listingIds` (max `QUERY_DATA_MAX_LISTING_IDS = 500`) or a survivorship-free `universe` ref, with bounded output rows (`QUERY_DATA_DEFAULT_LIMIT = 500`, hard max `QUERY_DATA_MAX_LIMIT = 5_000`). -- Always enforces `scope: 'vault_fenced'` via `applyVaultFence` before any store call, omits `scope` / `vault_evaluation_only` from the strict schema (rejecting unknown keys with zero store calls), drops any post-cutoff row (`ts >= vaultCutoffTs` or `knownAt >= vaultCutoffTs`) as defense in depth, and maps `VaultHoldoutFenceError`, `VaultScopeNotAuthorizedError`, `MarketDataStoreValidationError`, `MarketDataStoreNotImplementedError`, and `AdjFactorsSnapshotError` to `isError: true` responses naming the error class. - -### `event_study` Tool (Vault-Fenced) - -- **`createEventStudyTool({ store, ledger, vaultContext, principalId, resolveExchangeCalendars })`** — Runs a Vault-fenced event study over daily bars and point-in-time `events` (`filing`, `earnings`, `ceo_post`, `corporate_action`, with optional exact `subtypes` filter capped at `EVENT_STUDY_MAX_SUBTYPES = 100` entries and `EVENT_STUDY_MAX_SUBTYPE_LENGTH = 128` chars each) for explicit `listingIds` (max `EVENT_STUDY_MAX_LISTING_IDS = 500`) or a survivorship-free `universe` ref matching `universeMarket`, across `[-preDays, +postDays]` (`0–60` sessions each; `horizonBucket` must match `postDays <= 10 ? 'swing_1_10d' : 'position_10d_plus'`). -- **Injected exchange calendars:** `resolveExchangeCalendars({ listingIds, fromDate, toDate })` supplies actual exchange session close timestamps (including half-days) for `buildEventStudyInput` so events are anchored without synthesizing calendars from bars. -- **Returns, benchmark & Vault fence:** Models daily close-to-close returns with no execution or transaction costs (`adjustment` defaults to `'raw'`; `benchmark` defaults to `'equal_weight'` using available eligible listing returns, or `'none'` for unbenchmarked returns). Enforces `scope: 'vault_fenced'`, clamps `to`/`asOf` strictly below `vaultCutoffTs`, resolves named universes strictly pre-start, defensively excludes any bar or event on or after the Vault cutoff date (or with `known_at > asOf`), and writes eligible trials exclusively to the injected `trial_ledger` (`stage = 'event_study'`) under the server-injected `principalId`. - -### `file_finding` Tool (Append-Only) - -- **`createFileFindingTool({ port, trialLookup, newId, now })`** — Files an append-only empirical `finding` or `dead_end` record linked to 1–32 research-visible `trial_ledger` references (`trialRefs`, capped at 256 chars each) and 0–32 optional opaque snapshot identifiers (`evidenceRefs`, never dereferenced by the tool). Trims and enforces hard limits (`title` ≤ 256, `summary` ≤ 4,096, `idempotencyKey` ≤ 128), applies array bounds before case-sensitive deduplication and sorting, and rejects unknown fields with a fixed message. -- **Review status & Vault safety:** Server-controlled metadata (`id`, UTC ISO `createdAt`, and initial `status: 'pending_review'`) cannot be supplied by callers; director approval occurs out-of-band. Every unique `trialRef` is verified via the injected read-only `trialLookup.hasResearchVisibleTrial(ref)` before generating metadata or writing (treating unknown and Vault-only refs identically). Callers must describe research-visible evidence only in `title` and `summary` and keep Vault holdout observations out of filing text. -- **Idempotency & receipts:** `FindingWritePort` exposes only `appendFinding(record, idempotencyKey?)` with atomic `created` / `replayed` / `conflict` semantics comparing normalized `kind`, `title`, `summary`, `trialRefs`, and `evidenceRefs`. Retries with the same key and normalized payload return the original `{ id, createdAt, created: false }` without appending; key reuse with a different payload returns a fixed `isError: true` conflict error with zero writes; unkeyed calls are independent. Filed records extend `FindingRecord` and can be read back by receipt ID via `read_knowledge`. - -### PostgreSQL Symbol Search Adapter - -- **`createPostgresSymbolSearchPort({ executor, schema? })`** (exported from `@stock-bot/research/mcp` alongside `SymbolSearchExecutor` and `PostgresSymbolSearchError`) implements `SymbolSearchPort` over the M1 PostgreSQL security master (`listing`, `instrument`, `exchange`, `listing_symbol_history`) in one read-only parameterized `SELECT` with zero runtime `pg` dependency. -- **Inputs & schema:** Validates that `executor` exposes a callable `query(text, params?)` method (`INVALID_EXECUTOR`), validates optional `schema` against `^[a-z_][a-z0-9_]*$` before quoting table identifiers (`INVALID_SCHEMA`; defaults to the executor's `search_path`), validates `q.vaultCutoffTs` (epoch milliseconds) and converts it to a UTC calendar date (`YYYY-MM-DD`), escapes `%`, `_`, and `\` before building the `ILIKE` pattern, and rejects malformed/non-integer IDs or invalid/impossible `YYYY-MM-DD` dates returned by the executor (`INVALID_ROW`). -- **As-of ticker resolution & root suppression:** Excludes listings with `listed_from > cutoff` (retaining `listed_from IS NULL`). Defines `root_is_future` per listing when `listing_symbol_history` has at least one row with `upper(ticker) = upper(listing.ticker_root)` and none with `valid_from <= cutoff`. Resolves one ticker per listing (breaking same-`valid_from` ties by `ticker ASC`) in strict order: (1) latest history row valid at cutoff (`valid_from <= cutoff AND (valid_to IS NULL OR valid_to >= cutoff)`), (2) `listing.ticker_root` when `NOT root_is_future`, (3) latest history row with `valid_from <= cutoff` even if its `valid_to < cutoff`, (4) otherwise excludes the listing so future tickers never leak via fallback or name/ISIN lookup. -- **`delistedAt` derivation:** Projects `delistedAt` as `listing.listed_to` (`YYYY-MM-DD`) when `delist_reason IS NOT NULL AND delist_reason <> 'active'`, else `null`. When `q.includeDelisted === false`, rows with non-null `delistedAt <= cutoff` are filtered out while future delistings (`delistedAt > cutoff`) remain eligible as of the cutoff. -- **Port matching vs. MCP ranking:** The adapter matches on resolved as-of ticker (`ILIKE`), `listing.ticker_root` (`ILIKE`, gated by `NOT root_is_future`), `instrument.canonical_name` (`ILIKE`), or case-insensitive exact `instrument.primary_isin`, ignores `q.limit`, and returns all candidates ordered by `listing_id ASC`. When composed with `createSearchSymbolsTool`, the MCP tool applies Vault clamping/masking, ranks by exact ticker > ticker prefix > company name substring (tie-breaking by `listingId ASC`), and truncates to `limit` — so callers needing ticker-substring, root-only, or exact-ISIN lookups should call the port directly, while MCP tool callers should query by ticker or company name. - -### PostgreSQL Findings & Provider Caveats Adapter - -- **`createPostgresFindingWritePort({ executor, schema? })`** and **`createPostgresKnowledgeReaders({ executor, schema? })`** (exported from `@stock-bot/research/mcp` alongside `PostgresFindingsExecutor`, `PostgresFindingsOptions`, `PostgresKnowledgeReaders`, `PostgresFindingsError`, and `PostgresFindingsErrorCode`) back `file_finding` (`FindingWritePort`) and the `findings` / `provider_caveats` halves of `read_knowledge` (`Pick`) over `37-research-findings.sql` with zero runtime `pg` dependency. -- **Inputs, schema & row validation:** Validates `executor.query` (`INVALID_EXECUTOR`) and optional `schema` against `^[a-z_][a-z0-9_]*$` (`INVALID_SCHEMA`; defaults to the executor's `search_path`), binds every caller value via `$n` parameters, issues zero `UPDATE`/`DELETE` statements, and fails closed (`INVALID_ROW`) on malformed result envelopes, non-1D/non-string ref arrays, unknown `kind`, or invalid timestamps (converting PostgreSQL `Date` values or strictly parsed timezone-qualified ISO-8601 strings to UTC ISO-8601 output). -- **Atomic idempotency & autocommit requirement:** Unkeyed appends execute a plain `INSERT ... RETURNING id, created_at`. Keyed appends use `INSERT ... ON CONFLICT (idempotency_key) WHERE idempotency_key IS NOT NULL DO NOTHING RETURNING id, created_at` followed by a separate keyed `SELECT` on zero rows (and on same-ID `23505` primary-key retries), comparing normalized `kind`, `title`, `summary`, `trialRefs`, and `evidenceRefs` via `areFiledFindingPayloadsEqual`. Pass an autocommit, fresh-snapshot `READ COMMITTED` executor (such as a `pg.Pool`, not a `REPEATABLE READ`/`SERIALIZABLE` or explicit `BEGIN` transaction unless the executor rolls back a `SAVEPOINT` before rethrowing errors) so concurrent callers observe the committed winner and `23505` retry lookups do not hit `25P02`. -- **Reader filtering & research-visible corpus boundary:** `listFindings` and `listProviderCaveats` push down case-sensitive exact `id` (taking precedence over `query`), escaped `ILIKE` substring matching (`%`, `_`, `\`) for ASCII queries, and `lower(provider) = lower($n::text)` (matching `idx_provider_caveats_lower_provider`) for ASCII provider filters while retaining non-ASCII stored rows as candidates (and omitting SQL casing filters for non-ASCII selectors), then applying JavaScript `.toLowerCase()` matching after row validation so PostgreSQL libc/C collation casing (e.g., Greek final sigma or `BİST` / `K`) never drops `read_knowledge` matches. All eligible rows are returned ordered by `id ASC` with no `LIMIT` so `createReadKnowledgeTool` owns ranking and global limits. Because `findings` and `provider_caveats` carry no Vault visibility column, callers must bind the adapter to a research-visible corpus and keep `createFileFindingTool` responsible for verifying `trialRefs` via `trialLookup` before writing. - -### Exchange Calendar Resolver - -- **`createPostgresListingCalendarPort({ executor, schema? })`** and **`createExchangeCalendarResolver({ listingCalendars, sessionDates, earlyCloses? })`** (exported from `@stock-bot/research/mcp` alongside `ListingCalendarPort`, `SessionDatesPort`, `EarlyCloseOverrides`, `PostgresListingCalendarError`, and `ExchangeCalendarResolverError`) implement `EventStudyExchangeCalendarResolver` for `createEventStudyTool` with zero `node:*` imports and zero runtime `pg` dependency. -- **Injected ports & fail-closed validation:** `createPostgresListingCalendarPort` issues one read-only parameterized `SELECT` joining `listing.mic` to `exchange.mic` (`WHERE l.listing_id = ANY($1::integer[])`), validating `executor.query` (`INVALID_EXECUTOR`), optional `schema` (`^[a-z_][a-z0-9_]*$`, `INVALID_SCHEMA`), and returned rows (`INVALID_ROW`). `SessionDatesPort.listSessionDates({ calendarCode, fromDate, toDate })` is called once per distinct calendar code in sorted order; the resolver fails closed with no partial result on missing, unrequested, or conflicting listing mappings or on malformed, duplicate, unsorted, or out-of-window session dates. Empty `listingIds` returns empty `{ calendars, listingCalendarId }` with zero port calls. -- **Supported DST range & default half-day close:** Session close timestamps convert Eastern Time (`America/New_York` / `America/Toronto`) to UTC epoch milliseconds across `1976-01-01` through `2030-12-31` inclusive (matching `tools/curate-etl/src/session_close.rs` across the `1976–1986`, `1987–2006`, and `2007–2030` DST eras) and throw `ExchangeCalendarResolverError('UNSUPPORTED_DATE')` outside that range. Optional `earlyCloses` (`{ [calendarCode]: { [YYYY-MM-DD]: minuteOfDayEastern } }`, integer minutes in `1..=960`, e.g. `780` for `13:00 ET`) overrides the close on listed dates; when `earlyCloses` is omitted, every session closes at `16:00 ET` and exchange half-days are treated as full `16:00 ET` trading days. -- **Bar-derived `SessionDatesPort` (`createBarSessionDatesPort({ store, referenceListingIds })`):** Exported from `@stock-bot/research/mcp` alongside `BarSessionDatesPortOptions` and `BarSessionDatesError`. Keys in `referenceListingIds` are exact `exchange.calendar_code` strings (e.g. `XNYS`, `XTSE`) mapped to non-empty, duplicate-free arrays of positive INT32 reference listing IDs whose daily bars define that exchange's session dates; the caller owns reference-listing coverage so gaps do not omit real sessions. Each `listSessionDates` call queries `store.bars({ listingIds, timeframe: '1d', from, to, adjustment: 'raw' })` once with `scope` and `asOf` omitted so the store's default `'vault_fenced'` scope applies (`'vault_evaluation_only'` is never passed), propagates store errors (including `VaultHoldoutFenceError`) unchanged, derives UTC session dates from `BarRecord.ts` (`Math.floor(ts / MS_PER_DAY)`), and fails closed on unknown calendars, malformed queries, or invalid bars. - -### Filesystem Library Cards Adapter - -- **`createLibraryCardReader({ root, fs })`** (exported from `@stock-bot/research/mcp` alongside `createNodeLibraryCardFs`, `LibraryCardFs`, `LibraryCardDirHandle`, `LibraryCardDirEntry`, `LibraryCardReaderOptions`, `LibraryCardReader`, `LibraryCardError`, and `LibraryCardErrorCode`) implements `Pick` over a configured read-only library root (`/library.yml` and `/cards//.md`) with zero new dependencies. -- **Read-only boundary, fresh reads & symlink safety:** Resolves `root` once at construction, reads `library.yml` and eligible cards fresh on every call (no cache), requires anchored directory operations (`LibraryCardFs.openDir`, backed by `/proc/self/fd/` in `createNodeLibraryCardFs()`) with no pathname fallback, enforces `O_NOFOLLOW` on every component below the configured root with `fstat` regular-file/directory verification, and fails closed if the adapter or runtime cannot enforce that boundary. -- **Exact-ID narrowing & unverified-card assumption:** Returns all eligible cards in manifest section order and code-unit slug order without pre-slicing or truncating text, narrowing only on exact case-sensitive `q.id` (malformed or unknown IDs return an empty frozen array without opening card files) so `createReadKnowledgeTool` owns `query`/`tags` filtering, ranking, truncation, and `limit`. All eligible cards are returned regardless of `verified` status, and callers must bind `root` to a research-visible corpus free of holdout or Vault-only observations. - -### Copilot Server - -- **`createResearchCopilotMcpServer(options)`** (exported from `@stock-bot/research/mcp` alongside `ResearchCopilotMcpServerOptions` and the frozen `RESEARCH_COPILOT_TOOL_NAMES` tuple) composes all six research tools into one transport-agnostic `McpServer` in the fixed registration order `search_symbols`, `query_data`, `analyze_signal`, `event_study`, `file_finding`, `read_knowledge`. It accepts `name` and `version`, shared authoritative `store`, `vaultContext`, `ledger`, and `principalId`, plus the per-tool injected ports (`searchSymbols`, `eventStudy.resolveExchangeCalendars`, `fileFinding`, `readKnowledge`), fails closed on duplicate, missing, unexpected, or out-of-order tool names, and pairs directly with `runStdioServer(server, ...)` for headless newline-delimited JSON-RPC sessions. -- **`createPostgresResearchCopilotServer(options)`** (exported from `@stock-bot/research/mcp` alongside `PostgresResearchCopilotServerOptions` and `PostgresResearchCopilotExecutor`) wires one shared PostgreSQL executor into `createPostgresSymbolSearchPort`, `createPostgresTrialRefPort`, `createPostgresFindingWritePort`, `createPostgresKnowledgeReaders`, `createPostgresListingCalendarPort` + `createExchangeCalendarResolver`, and `trial_ledger`, while keeping `store`, `listLibraryCards`, `sessionDates` (with optional `earlyCloses`), `newId`, and `now` caller-supplied. `vaultContext.vaultCutoffTs` is the single authoritative Vault cutoff for all Vault-fenced tools and `trial_ledger` visibility lookups. When `schema` is supplied, the schema-aware adapters qualify their tables with `"".`, while `trial_ledger` writes and cluster DSR reads resolve through the executor's `search_path`. - -### Stdio Host Composition - -- **`parseResearchCopilotHostConfig(env)`** and **`runResearchCopilotStdioHost(deps)`** (exported from `@stock-bot/research/mcp` alongside `ResearchCopilotHostConfig`, `ResearchCopilotHostConfigError`, `ResearchCopilotStdioHostDeps`, `RESEARCH_COPILOT_HOST_NAME`, and `RESEARCH_COPILOT_HOST_VERSION`) provide a pure, dependency-free stdio host layer (`libs/research/src/mcp/host/stdio-host.ts`) with no `pg`, DuckDB, `node:*`, or bare `process` references. -- **Environment variables (`RESEARCH_MCP_*`):** Unrelated keys are ignored; unknown `RESEARCH_MCP_*` keys, missing required variables, blank values, and malformed fields throw `ResearchCopilotHostConfigError` naming the variable without exposing raw values or credentials. - -| Variable | Required | Format | -| --- | --- | --- | -| `RESEARCH_MCP_POSTGRES_URL` | Yes | `postgres://` or `postgresql://` URL with non-empty host (never echoed in errors) | -| `RESEARCH_MCP_POSTGRES_SCHEMA` | No | PostgreSQL identifier `^[a-z_][a-z0-9_]*$` | -| `RESEARCH_MCP_CURATED_ROOT` | Yes | Non-blank path string for curated Parquet datasets (validated by the store factory) | -| `RESEARCH_MCP_VAULT_CUTOFF_TS` | Yes | Strict ISO-8601 UTC instant with seconds and `Z` suffix, optional ms (e.g. `2025-06-01T00:00:00Z`) | -| `RESEARCH_MCP_PRINCIPAL_ID` | Yes | `operator` or `agent:` (UUID v1–8, RFC variant) | -| `RESEARCH_MCP_LIBRARY_ROOT` | Yes | Non-blank directory path containing `library.yml` (validated by the reader factory) | -| `RESEARCH_MCP_SESSION_REFERENCE_LISTINGS` | Yes | JSON object `{ "": [, ...] }` (non-empty, distinct IDs), e.g. `{"XNYS":[101,102],"XTSE":[201]}` | -| `RESEARCH_MCP_EARLY_CLOSES` | No | JSON object `{ "": { "": <1..960 ET min> } }` within `1976-01-01..=2030-12-31`, e.g. `{"XNYS":{"2024-11-29":780}}` | - -- **Usage, single Vault cutoff & cleanup ownership:** Pass the parsed `config` to `runResearchCopilotStdioHost({ config, openExecutor, openStore, createLibraryCardReader, newId, now, stdio? })`. The host acquires `openExecutor` → `openStore` → `createLibraryCardReader`, builds `createBarSessionDatesPort` and `createPostgresResearchCopilotServer` (`stock-bot-research-copilot` / `0.1.0`) with `vaultContext: { vaultCutoffTs: config.vaultCutoffTs }`, and starts `runStdioServer` only after all setup succeeds. Callers' `openStore(config)` factory must configure its `MarketDataStore` with the same `config.vaultCutoffTs` so store queries and session-date derivation share one cutoff. Each factory owns internal cleanup on its own failed startup; once a handle is returned, the host awaits `close()` on every acquired handle exactly once in reverse acquisition order on EOF or error, preserving safe primary errors and replacing credential-bearing or uninspectable failures with fixed stage-specific errors. Keep all startup and runtime diagnostics off `stdout` (use `stderr` or structured logs outside stdio) so `stdout` carries only newline-delimited JSON-RPC frames. - -### Remaining M2 MCP Items (Later Tasks) - -- SSE/HTTP transport wrapper in `apps/stock/web-api`. -- Runnable CLI binary wired to real DuckDB/Parquet and PostgreSQL adapters. - -## Versioned Feature Library - -Exported from both `@stock-bot/research` and `@stock-bot/research/feature-library` (`libs/research/src/feature-library.ts`). The module is pure, dependency-free, and browser-safe (zero `node:*` imports, zero DuckDB driver dependency); SQL execution is injected via `DuckDbExecutor` (`{ run(sql), query(sql, params) }`). - -### API & Immutability - -- **`validateFeatureDefinition(def)`** — Fail-closed validator for declarative `duckdb_sql` feature definitions using a single quote-aware tokenizer shared with hashing and placeholder expansion. Accepts a single `SELECT` or non-recursive `WITH ... SELECT` statement projecting exactly `(listing_id, ts, known_at, value)` in contract order. Rejects `WITH RECURSIVE`, semicolons, comments, caller bind markers (`?`, `$1`, `:name`), prohibited DDL/DML/admin keywords (`COPY`, `ATTACH`, `INSERT`, `CREATE`, `PRAGMA`, `SET`, etc.), external readers (`read_parquet`, `read_csv`, `glob`, etc.), quoted file paths/URIs, catalog relations, table functions, and non-allow-listed functions. Relation sources are restricted to declared `{{input:}}` placeholders (`bars_1d`, `adj_factors`, `events`, `shorts`, `fx_1d`, `fundamentals_pit`), in-scope non-recursive CTEs, and validated subqueries; every declared input must be used and every placeholder must be declared. -- **`featureRef(def)` / `parseFeatureRef(ref)`** — Formats and parses canonical `@v` refs (`^[a-z][a-z0-9_]{0,62}$` and positive safe integer version; rejects non-canonical forms such as `ret_1d@v01`). -- **`featureDefinitionHash(def)`** — Deterministic 64-char SHA-256 hex digest over `{ name, version, kind, sql (canonical tokens), inputs (sorted), warmupBars, knownAtRule }`. Invariant across inter-token whitespace, object key order, and input array order; preserves whitespace inside string literals. `family` and `description` are stored as metadata from the first registration. -- **`createFeatureRegistry()`** — In-memory registry exposing `registerSignal(def)` (D11), `get(ref)`, and `list()`. Re-registering an identical hash is idempotent; re-registering `@v` with a different hash throws `FeatureLibraryError('FEATURE_VERSION_IMMUTABLE')`. Defensive copies isolate stored definitions from caller mutation. -- **`planFeatureBatch(def, { curatedRoot, fromYear, toYear, vaultCutoffDate })`** — Validates `curatedRoot`, four-digit ordered years, and strict UTC `YYYY-MM-DD` `vaultCutoffDate` via `applyVaultFence`. Plans one yearly ZSTD Parquet write to `/features//v/year=YYYY/part.parquet` through the last year with any pre-cutoff time (a January 1 cutoff excludes that calendar year; an entirely post-cutoff range throws `VAULT_RANGE_VIOLATION`). Expands `{{input:}}` scans with bound upper availability predicates (`ts <= ? AND known_at <= ?`, `known_at <= ?`, or `effective_known_at <= ?` for `fundamentals_pit`) strictly `< vaultCutoffDate` (last included microsecond `.999999Z`) before authored SQL runs, preserving earlier history for SQL-owned warm-up. -- **`runFeatureBatch(def, opts, executor)`** — Validates and plans upfront (0 executor calls on invalid inputs), awaits `executor.query(sql, params)` sequentially in year order, and returns `{ ref, definitionHash, knownAtRule, warmupBars, inputs, writes }`. On write failure, stops immediately and throws `FeatureLibraryError('BATCH_WRITE_FAILED')` exposing `cause`, `failedYear`, `completedYears`, and `completedWrites` (earlier completed files may remain on disk for operator inspection before retry). -- **`RET_1D_V1`** — Built-in `ret_1d@v1` example computing 1-day listing-partitioned raw-close return `(close / LAG(close)) - 1.0` with `known_at = ts` and `warmupBars: 1` (omitting rows without a positive prior close). - -### Operational & Research Governance Notes - -- **Executor & directory requirements:** Callers running plans against DuckDB must configure the executor session timezone to UTC (`TZ=UTC`) and ensure output parent directories (`/features//v/year=YYYY/`) exist before executing `COPY`. -- **Point-in-time & `adj_factors` snapshots:** Feature definitions own per-observation availability (`knownAtRule` and projected `known_at`). Because `adj_factors` stores cumulative suffix products, features referencing `{{input:adj_factors}}` require a caller-verified, immutable point-in-time snapshot compatible with `vaultCutoffDate`. -- **Economic ownership & evidence:** The Quant research role owns each feature's economic specification. `RET_1D_V1` uses a zero-return comparison baseline with no execution or transaction cost model. Any future research claim built on materialized features must retain the feature `ref` and `definitionHash`, immutable dataset identifier, sample window, `vaultCutoffDate`, baseline, and execution assumptions. - -## `marimo check`-Gated Notebook Snapshot Exporter - -Exported from `@stock-bot/research` (`libs/research/src/notebook-snapshot.ts`). Subprocess execution and filesystem access are injected via `NotebookCommandRunner` and `NotebookSnapshotFs`, and `node:crypto` is loaded lazily at call time so the shared package barrel remains browser-bundleable. Command flags and JSON report validation are confirmed against **marimo `0.26.0`** (pinned in `python/uv.lock`). - -### API & Ports - -- **`exportNotebookSnapshot(options)`** — Validates options and paths, confirms `notebookPath` is an existing regular `.py` file, gates on `marimo check --format=json `, and only on a clean check reserves a unique sibling `.html` temp file via `fs.createExclusive` and runs `marimo export html -o --force` before computing byte length and lowercase SHA-256 and atomically publishing via `fs.rename(tempPath, outputPath)`. -- **Frozen receipt (`NotebookSnapshotReceipt`)** — Returns `Object.freeze({ notebookPath, outputPath, bytes, sha256, checkDiagnostics })`, where `checkDiagnostics` is the deep-frozen marimo JSON report (or `null` when `marimo check` exits `0` with empty stdout). -- **`NotebookCommandRunner`** — Must execute `command` directly with `args` as an argv array (never a shell string). On timeout (default `120_000` ms per command), implementations must terminate the subprocess and reject with `code: 'ETIMEDOUT'` **only after the process has exited and stopped writing** so cleanup cannot race with late writes. -- **`NotebookSnapshotFs`** — Minimal port requiring `stat`, `createExclusive` (must throw `code: 'EEXIST'` on collision), `readBytes`, `rename`, and idempotent `remove`. On any export, read, or publish failure, only the owned temp file is removed and any pre-existing `outputPath` keeps its original bytes. -- **Fail-closed error codes (`NotebookSnapshotError`)** — `INVALID_OPTION`, `INVALID_PATH`, `NOTEBOOK_NOT_FOUND`, `CHECK_FAILED` (nonzero check exit, `summary.errored === true`, `type: 'error'`, or `severity: 'breaking'`), `CHECK_OUTPUT_INVALID` (non-JSON stdout on exit `0` or malformed `{ issues, summary }` / `summary.total_files !== 1`), `EXPORT_FAILED`, `EXPORT_EMPTY`, and `TIMEOUT`. Formatting and runtime advisories may accompany a clean check. -- **Lexical roots & execution notice:** `allowedNotebookRoot` and `allowedOutputRoot` enforce lexical POSIX path-component containment (blocking `..` traversal and same-prefix sibling escapes); callers must supply trusted directories and keep the notebook file stable between check and export. Note that `marimo export html` **executes notebook cells**. - -### Node/Bun Adapters (`@stock-bot/research/notebook-snapshot-node`) - -Server-only adapters backed by `node:child_process` and `node:fs/promises` are exported exclusively from the `@stock-bot/research/notebook-snapshot-node` subpath (`libs/research/src/notebook-snapshot-node.ts`) so the default `@stock-bot/research` entrypoint remains browser-bundleable: - -- **`createNodeNotebookCommandRunner(options?)`** — Implements `NotebookCommandRunner` via `spawn(command, [...args], { cwd, shell: false, stdio: ['ignore', 'pipe', 'pipe'] })`. Captures stdout and stderr independently up to `NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES` (`16 MiB` by default, configurable via `options.maxOutputBytes`), kills with `SIGKILL` on timeout (`ETIMEDOUT`) or overflow (`EOUTPUTLIMIT`), and settles only after `close`. -- **`createNodeNotebookSnapshotFs()`** — Implements `NotebookSnapshotFs` over `node:fs/promises` (`stat` mapping only `ENOENT` to `null`, `open(..., 'wx')` exclusive create, binary `readFile`, atomic `rename`, and non-recursive `rm(..., { force: true })`). - -```ts -import { exportNotebookSnapshot } from '@stock-bot/research'; -import { - createNodeNotebookCommandRunner, - createNodeNotebookSnapshotFs, -} from '@stock-bot/research/notebook-snapshot-node'; - -const receipt = await exportNotebookSnapshot({ - notebookPath: '/abs/path/to/study.py', - outputPath: '/abs/path/to/study.html', - runner: createNodeNotebookCommandRunner(), - fs: createNodeNotebookSnapshotFs(), -}); -``` - -### Manual Host Smoke Check (Director / Host Only) - -Automated tests use fakes and never spawn `marimo`. On a host with the pinned `python/` `uv` environment (`marimo 0.26.0`): - -1. Ensure `STOCK_BOT_TRIAL_LEDGER_DSN` is **unset** so the smoke check does not append trial rows to `trial_ledger`. -2. Target `research/notebooks/ca_shorts_filings_study.py` against a fixed Vault-fenced dataset and run `exportNotebookSnapshot` (or the two commands it issues: `uv run --project python marimo check --format=json research/notebooks/ca_shorts_filings_study.py` followed by `uv run --project python marimo export html research/notebooks/ca_shorts_filings_study.py -o --force`). -3. Record the pinned inputs, whether `marimo check` reported 0 errors, and whether the exported HTML opens cleanly. Quant owns any research claims (including notebook revision, dataset ID, sample window, Vault cutoff, baseline, and cost assumptions); any paper or live write access requires a separate scope decision. diff --git a/libs/research/package.json b/libs/research/package.json index 7add3b09..dd8dd698 100644 --- a/libs/research/package.json +++ b/libs/research/package.json @@ -10,16 +10,8 @@ ".": "./src/index.ts", "./dataset-contracts": "./src/dataset-contracts.ts", "./datasets": "./src/datasets.ts", - "./event-panel": "./src/event-panel.ts", - "./feature-library": "./src/feature-library.ts", "./market-data-store": "./src/market-data-store.ts", - "./market-data-store-duckdb": "./src/market-data-store-duckdb.ts", - "./market-data-store-questdb": "./src/market-data-store-questdb.ts", - "./market-data-store-routed": "./src/market-data-store-routed.ts", - "./mcp": "./src/mcp/index.ts", - "./notebook-snapshot-node": "./src/notebook-snapshot-node.ts", "./results": "./src/results.ts", - "./signal-panel": "./src/signal-panel.ts", "./signal-study": "./src/signal-study.ts", "./strategy-api": "./src/strategy-api.ts", "./trial-ledger": "./src/trial-ledger.ts" diff --git a/libs/research/scripts/benchmark-event-panel.ts b/libs/research/scripts/benchmark-event-panel.ts deleted file mode 100644 index de8e2c60..00000000 --- a/libs/research/scripts/benchmark-event-panel.ts +++ /dev/null @@ -1,230 +0,0 @@ -import { - type EventObservation, - type EventStudyExchangeCalendars, - buildEventStudyInput, -} from '../src/event-panel'; -import type { BarRecord } from '../src/market-data-store'; - -const SEED = 20261129; -const SESSIONS = 5_040; -const LISTINGS = 3_000; -const EVENT_STRIDE_SESSIONS = 63; // 5040 / 63 = 80 filings/listing -> 240,000 total events -const PRE_CUTOFF_SESSIONS = 5_020; - -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) / 4_294_967_296; - }; -} - -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 generateBusinessCalendar(count: number, startYear: number): { - dates: string[]; - closeTs: Float64Array; - afterCloseTs: Float64Array; -} { - const dates: string[] = new Array(count); - const closeTs = new Float64Array(count); - const afterCloseTs = new Float64Array(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}`; - closeTs[produced] = Date.UTC(year, month - 1, day, 21, 0, 0, 0); // 16:00 ET - afterCloseTs[produced] = Date.UTC(year, month - 1, day, 22, 0, 0, 0); // 17:00 ET - produced += 1; - } - - dow = (dow + 1) % 7; - day += 1; - const baseDays = DAYS_IN_MONTH[month] ?? 31; - const maxDay = month === 2 && isLeapYear(year) ? 29 : baseDays; - if (day > maxDay) { - day = 1; - month += 1; - if (month > 12) { - month = 1; - year += 1; - } - } - } - - return { dates, closeTs, afterCloseTs }; -} - -function fnv1aByte(hash: number, byte: number): number { - return Math.imul((hash ^ (byte & 0xff)) >>> 0, 0x01000193) >>> 0; -} - -function fnv1aUint32(hash: number, value: number): number { - const v = value >>> 0; - let h = fnv1aByte(hash, v & 0xff); - h = fnv1aByte(h, (v >>> 8) & 0xff); - h = fnv1aByte(h, (v >>> 16) & 0xff); - h = fnv1aByte(h, (v >>> 24) & 0xff); - return h; -} - -function fnv1aBytes(hash: number, bytes: Uint8Array): number { - let h = hash >>> 0; - for (let i = 0; i < bytes.length; i += 1) { - h = Math.imul((h ^ (bytes[i] as number)) >>> 0, 0x01000193) >>> 0; - } - return h; -} - -const rng = createMulberry32(SEED); -const calendar = generateBusinessCalendar(SESSIONS, 2006); -const vaultCutoffDate = calendar.dates[PRE_CUTOFF_SESSIONS] as string; - -const totalBars = SESSIONS * LISTINGS; -const bars: BarRecord[] = new Array(totalBars); -const eventsPerListing = Math.ceil(SESSIONS / EVENT_STRIDE_SESSIONS); -const totalEvents = LISTINGS * eventsPerListing; -const events: EventObservation[] = new Array(totalEvents); - -let barIdx = 0; -let evIdx = 0; - -for (let l = 0; l < LISTINGS; l += 1) { - const listingId = l + 1; - const subtype = l % 2 === 0 ? '10-q' : 'interim_financial_statements'; - let price = 10 + (l % 200) * 0.5; - for (let t = 0; t < SESSIONS; t += 1) { - const ts = calendar.closeTs[t] as number; - price = Math.max(1, price * (1 + (rng() - 0.4995) * 0.02)); - bars[barIdx++] = { - listingId, - ts, - open: price, - high: price, - low: price, - close: price, - volume: 10_000, - vwap: price, - knownAt: ts, - }; - if (t % EVENT_STRIDE_SESSIONS === 0) { - events[evIdx++] = { - listingId, - knownAt: calendar.afterCloseTs[t] as number, - kind: 'filing', - subtype, - }; - } - } -} - -const sessionCloses = calendar.dates.map((date, idx) => ({ - date, - closeTs: calendar.closeTs[idx] as number, -})); -const listingCalendarId = new Map(); -for (let l = 0; l < LISTINGS; l += 1) { - listingCalendarId.set(l + 1, l % 2 === 0 ? 'XNYS' : 'XTSE'); -} -const exchangeCalendars: EventStudyExchangeCalendars = { - calendars: new Map([ - ['XNYS', sessionCloses], - ['XTSE', sessionCloses], - ]), - listingCalendarId, -}; - -// Timed section: pure buildEventStudyInput execution (no fixture generation or checksum). -const started = performance.now(); -const result = buildEventStudyInput({ - bars, - events, - vaultCutoffDate, - benchmark: 'equal_weight', - exchangeCalendars, -}); -const elapsedMs = performance.now() - started; - -// Untimed verification pass: FNV-1a 32-bit checksum over lengths, diagnostics, returns, and events. -let checksum = 0x811c9dc5; -checksum = fnv1aUint32(checksum, result.input.sessionDates.length); -checksum = fnv1aUint32(checksum, result.input.entityReturns.size); -checksum = fnv1aUint32(checksum, result.input.events.length); -checksum = fnv1aUint32(checksum, result.diagnostics.vaultExcludedDates); -checksum = fnv1aUint32(checksum, result.diagnostics.vaultExcludedEvents); -checksum = fnv1aUint32(checksum, result.diagnostics.droppedUnknownListing); -checksum = fnv1aUint32(checksum, result.diagnostics.droppedAfterLastSession); -checksum = fnv1aUint32(checksum, result.diagnostics.droppedMissingCalendarSession); -checksum = fnv1aUint32(checksum, result.diagnostics.duplicateEvents); -checksum = fnv1aUint32(checksum, result.diagnostics.duplicateBars); -checksum = fnv1aUint32(checksum, result.diagnostics.nonPositiveCloseReturns); - -if (result.input.benchmarkReturns !== undefined) { - const bench = result.input.benchmarkReturns as Float64Array; - checksum = fnv1aBytes(checksum, new Uint8Array(bench.buffer, bench.byteOffset, bench.byteLength)); -} - -for (const [entityId, series] of result.input.entityReturns) { - checksum = fnv1aUint32(checksum, Number(entityId)); - const arr = series as Float64Array; - checksum = fnv1aBytes(checksum, new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength)); -} - -for (let i = 0; i < result.input.events.length; i += 1) { - const ev = result.input.events[i]; - if (ev === undefined) { - continue; - } - checksum = fnv1aUint32(checksum, ev.dayIndex); - checksum = fnv1aUint32(checksum, Number(ev.entityId)); -} - -const checksumHex = checksum.toString(16).padStart(8, '0'); - -const EXPECTED_CHECKSUM = '01b356d3'; -if (checksumHex !== EXPECTED_CHECKSUM) { - throw new Error( - `Benchmark checksum mismatch: expected ${EXPECTED_CHECKSUM}, got ${checksumHex}.` - ); -} - -const elapsedSec = elapsedMs / 1000; -const barsPerSec = Math.round(totalBars / elapsedSec); -const eventsPerSec = Math.round(totalEvents / elapsedSec); - -console.log( - JSON.stringify( - { - seed: SEED, - sessions: SESSIONS, - listings: LISTINGS, - vaultCutoffDate, - inputBars: totalBars, - inputEvents: totalEvents, - sessionDates: result.input.sessionDates.length, - anchoredEvents: result.input.events.length, - elapsedMs: Number(elapsedMs.toFixed(2)), - barsPerSec, - eventsPerSec, - diagnostics: result.diagnostics, - checksum: checksumHex, - }, - null, - 2 - ) -); diff --git a/libs/research/scripts/benchmark-market-data-store-duckdb.ts b/libs/research/scripts/benchmark-market-data-store-duckdb.ts deleted file mode 100644 index 172f91b6..00000000 --- a/libs/research/scripts/benchmark-market-data-store-duckdb.ts +++ /dev/null @@ -1,352 +0,0 @@ -import { - type AdjFactorsSnapshotMetadata, - BARS_ADJUSTMENTS, - type BarsQuery, - type DuckDbExecutor, - type DuckDbParam, - type DuckDbPlanContext, - EVENT_KINDS, - type EventsQuery, - type FxQuery, - type PlannedDuckDbQuery, - type ShortsAsOfQuery, - UNIVERSE_REFS, - type UniverseQuery, - createDuckDbMarketDataStore, - planBars1dQuery, - planEventsQuery, - planFx1dQuery, - planShortsAsOfQuery, -} from '../src/market-data-store-duckdb'; -import { type TableRow, applyVaultFence } from '../src/market-data-store'; - -const SEED = 20261129; -const QUERY_COUNT = 120_000; -const CURATED_ROOT = '/mnt/data/stockbot/curated'; -const ADJ_PATH = `${CURATED_ROOT}/adj_factors/part.parquet`; -const VAULT_CUTOFF_TS = Date.UTC(2026, 4, 28, 0, 0, 0, 0); -const VAULT_CUTOFF_MICROS = VAULT_CUTOFF_TS * 1000; -const DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/; - -const BASE_CTX: DuckDbPlanContext = { - curatedRoot: CURATED_ROOT, - vaultCutoffTs: VAULT_CUTOFF_TS, -}; - -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) / 4_294_967_296; - }; -} - -type WorkloadItem = - | { readonly kind: 'bars'; readonly q: BarsQuery; readonly ctx: DuckDbPlanContext } - | { readonly kind: 'events'; readonly q: EventsQuery } - | { readonly kind: 'shorts'; readonly q: ShortsAsOfQuery } - | { readonly kind: 'fx'; readonly q: FxQuery }; - -const rng = createMulberry32(SEED); -const startBaseMs = Date.UTC(2016, 0, 1, 0, 0, 0, 0); -const preCutoffSpanMs = VAULT_CUTOFF_TS - startBaseMs - 86_400_000; -const postCutoffSpanMs = 180 * 86_400_000; - -function randomDateOrIso(epochMs: number): string { - const iso = new Date(epochMs).toISOString(); - return rng() < 0.5 ? iso.slice(0, 10) : iso; -} - -function randomListingIds(): number[] { - const count = 1 + Math.floor(rng() * 4); - const ids: number[] = new Array(count); - for (let i = 0; i < count; i += 1) { - ids[i] = 1 + Math.floor(rng() * 50_000); - } - return ids; -} - -function buildVerifiedSnapshotForBarsQuery( - from: string, - to: string, - asOf: string | undefined -): AdjFactorsSnapshotMetadata { - const fenced = applyVaultFence( - { from, to, asOf, scope: 'vault_fenced' }, - { vaultCutoffTs: VAULT_CUTOFF_TS } - ); - const subMs = fenced.clampedAsOf || asOf === undefined || DATE_ONLY_RE.test(asOf) ? 999 : 0; - const effectiveAsOfMicros = fenced.asOfMs * 1000 + subMs; - return { - path: ADJ_PATH, - formatVersion: 1, - snapshotKind: 'point_in_time_fenced', - fence: { - asOfMicros: effectiveAsOfMicros, - vaultCutoffMicros: VAULT_CUTOFF_MICROS, - }, - rowsWritten: 1000, - snapshotChecksum: '0x024ec73a1afe7e6b', - }; -} - -const workload: WorkloadItem[] = new Array(QUERY_COUNT); -for (let i = 0; i < QUERY_COUNT; i += 1) { - const fromMs = startBaseMs + Math.floor(rng() * preCutoffSpanMs); - const toMs = fromMs + Math.floor(rng() * (VAULT_CUTOFF_TS - fromMs + postCutoffSpanMs)); - const asOfMs = - rng() < 0.35 - ? undefined - : startBaseMs + Math.floor(rng() * (VAULT_CUTOFF_TS - startBaseMs + postCutoffSpanMs)); - - const from = randomDateOrIso(fromMs); - const to = randomDateOrIso(toMs); - const asOf = asOfMs === undefined ? undefined : randomDateOrIso(asOfMs); - - const slot = i % 7; - if (slot < 3) { - const adjustment = BARS_ADJUSTMENTS[slot] ?? 'raw'; - const ctx: DuckDbPlanContext = - adjustment === 'raw' - ? BASE_CTX - : { - ...BASE_CTX, - adjFactorsSnapshot: buildVerifiedSnapshotForBarsQuery(from, to, asOf), - }; - workload[i] = { - kind: 'bars', - q: { - listingIds: randomListingIds(), - timeframe: '1d', - from, - to, - adjustment, - asOf, - }, - ctx, - }; - } else if (slot === 3 || slot === 4) { - const kindA = EVENT_KINDS[Math.floor(rng() * EVENT_KINDS.length)] ?? 'filing'; - const kindB = EVENT_KINDS[Math.floor(rng() * EVENT_KINDS.length)] ?? 'earnings'; - workload[i] = { - kind: 'events', - q: { - kinds: slot === 3 ? [kindA] : [kindA, kindB], - listingIds: slot === 3 ? randomListingIds() : undefined, - from, - to, - asOf, - }, - }; - } else if (slot === 5) { - workload[i] = { - kind: 'shorts', - q: { - listingIds: randomListingIds(), - from, - to, - asOf, - }, - }; - } else { - workload[i] = { - kind: 'fx', - q: { - pair: 'USD.CAD', - timeframe: '1d', - from, - to, - }, - }; - } -} - -function planWorkloadItem(item: WorkloadItem): PlannedDuckDbQuery { - switch (item.kind) { - case 'bars': - return planBars1dQuery(item.q, item.ctx); - case 'events': - return planEventsQuery(item.q, BASE_CTX); - case 'shorts': - return planShortsAsOfQuery(item.q, BASE_CTX); - case 'fx': - return planFx1dQuery(item.q, BASE_CTX); - } -} - -function fnv1aByte(hash: number, byte: number): number { - return Math.imul((hash ^ (byte & 0xff)) >>> 0, 0x01000193) >>> 0; -} - -function fnv1aString(hash: number, str: string): number { - let h = fnv1aByte(hash, str.length & 0xff); - h = fnv1aByte(h, (str.length >>> 8) & 0xff); - for (let i = 0; i < str.length; i += 1) { - const code = str.charCodeAt(i); - h = fnv1aByte(h, code & 0xff); - if (code > 0xff) { - h = fnv1aByte(h, (code >>> 8) & 0xff); - } - } - return h; -} - -function fnv1aParam(hash: number, param: DuckDbParam): number { - if (param === null) { - return fnv1aByte(hash, 0x00); - } - if (typeof param === 'string') { - return fnv1aString(fnv1aByte(hash, 0x01), param); - } - if (typeof param === 'number') { - return fnv1aString(fnv1aByte(hash, 0x02), String(param)); - } - return fnv1aByte(fnv1aByte(hash, 0x03), param ? 1 : 0); -} - -// Timed section: pure query planning only (no checksum hashing overhead). -let totalParams = 0; -const started = performance.now(); -for (const item of workload) { - const planned = planWorkloadItem(item); - totalParams += planned.params.length; -} -const elapsedMs = performance.now() - started; -const queriesPerSec = Math.round(QUERY_COUNT / (elapsedMs / 1000)); - -// Untimed verification pass: hash full SQL text and ordered parameter values for all queries. -let checksum = 0x811c9dc5; -for (const item of workload) { - const planned = planWorkloadItem(item); - checksum = fnv1aString(checksum, planned.sql); - checksum = fnv1aByte(checksum, planned.params.length); - for (const param of planned.params) { - checksum = fnv1aParam(checksum, param); - } -} -const checksumHex = checksum.toString(16).padStart(8, '0'); - -const EXPECTED_CHECKSUM = '8606c98c'; -if (checksumHex !== EXPECTED_CHECKSUM) { - throw new Error( - `Benchmark checksum mismatch: expected ${EXPECTED_CHECKSUM}, got ${checksumHex}.` - ); -} - -// Fixed-seed universe benchmark: plan + adapter mapping for 15,000 listing IDs via in-memory executor. -const UNIVERSE_LISTING_COUNT = 15_000; -const UNIVERSE_CALL_COUNT = 200; - -async function runUniverseBenchmark() { - const universeRng = createMulberry32(SEED); - const listingRows: TableRow[] = new Array(UNIVERSE_LISTING_COUNT); - let nextListingId = 1; - for (let i = 0; i < UNIVERSE_LISTING_COUNT; i += 1) { - listingRows[i] = { listing_id: nextListingId }; - nextListingId += 1 + Math.floor(universeRng() * 5); - } - - const universeQueries: UniverseQuery[] = new Array(UNIVERSE_CALL_COUNT); - for (let i = 0; i < UNIVERSE_CALL_COUNT; i += 1) { - const ref = UNIVERSE_REFS[i % UNIVERSE_REFS.length] ?? 'US_EQ'; - const dateMs = startBaseMs + Math.floor(universeRng() * preCutoffSpanMs); - const date = new Date(dateMs).toISOString().slice(0, 10); - universeQueries[i] = { ref, date }; - } - - const timedExecutor: DuckDbExecutor = { - async run(): Promise {}, - async query(): Promise { - return listingRows; - }, - }; - const timedStore = createDuckDbMarketDataStore({ - executor: timedExecutor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - - // Timed section: universe query planning + adapter row validation/mapping. - let totalListingsMapped = 0; - const uStarted = performance.now(); - for (const q of universeQueries) { - const ids = await timedStore.universe(q); - totalListingsMapped += ids.length; - } - const uElapsedMs = performance.now() - uStarted; - const uCallsPerSec = Math.round(UNIVERSE_CALL_COUNT / (uElapsedMs / 1000)); - const uRowsPerSec = Math.round(totalListingsMapped / (uElapsedMs / 1000)); - - // Untimed verification pass: hash SQL, ordered params, and mapped listing IDs. - let uChecksum = 0x811c9dc5; - const verifyExecutor: DuckDbExecutor = { - async run(): Promise {}, - async query(sql: string, params: readonly DuckDbParam[]): Promise { - uChecksum = fnv1aString(uChecksum, sql); - uChecksum = fnv1aByte(uChecksum, params.length); - for (const param of params) { - uChecksum = fnv1aParam(uChecksum, param); - } - return listingRows; - }, - }; - const verifyStore = createDuckDbMarketDataStore({ - executor: verifyExecutor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - - for (const q of universeQueries) { - const ids = await verifyStore.universe(q); - for (let i = 0; i < ids.length; i += 1) { - const id = ids[i] ?? 0; - uChecksum = fnv1aByte(uChecksum, id & 0xff); - uChecksum = fnv1aByte(uChecksum, (id >>> 8) & 0xff); - uChecksum = fnv1aByte(uChecksum, (id >>> 16) & 0xff); - uChecksum = fnv1aByte(uChecksum, (id >>> 24) & 0xff); - } - } - const uChecksumHex = uChecksum.toString(16).padStart(8, '0'); - const EXPECTED_UNIVERSE_CHECKSUM = 'ef5f1136'; - if (uChecksumHex !== EXPECTED_UNIVERSE_CHECKSUM) { - throw new Error( - `Universe benchmark checksum mismatch: expected ${EXPECTED_UNIVERSE_CHECKSUM}, got ${uChecksumHex}.` - ); - } - - return { - seed: SEED, - calls: UNIVERSE_CALL_COUNT, - listingsPerCall: UNIVERSE_LISTING_COUNT, - totalListingsMapped, - elapsedMs: Number(uElapsedMs.toFixed(2)), - callsPerSec: uCallsPerSec, - rowsPerSec: uRowsPerSec, - checksum: uChecksumHex, - }; -} - -runUniverseBenchmark() - .then((universe) => { - console.log( - JSON.stringify( - { - seed: SEED, - queries: QUERY_COUNT, - totalParams, - elapsedMs: Number(elapsedMs.toFixed(2)), - queriesPerSec, - checksum: checksumHex, - universe, - }, - null, - 2 - ) - ); - }) - .catch((err: unknown) => { - console.error(err); - process.exitCode = 1; - }); diff --git a/libs/research/scripts/benchmark-signal-panel.ts b/libs/research/scripts/benchmark-signal-panel.ts deleted file mode 100644 index b6b41fb4..00000000 --- a/libs/research/scripts/benchmark-signal-panel.ts +++ /dev/null @@ -1,196 +0,0 @@ -import type { BarRecord } from '../src/market-data-store'; -import { type SignalObservation, buildForwardReturnPanel } from '../src/signal-panel'; - -const SEED = 20261129; -const SESSIONS = 5_040; -const LISTINGS = 3_000; -const SIGNAL_STRIDE_SESSIONS = 21; -const HORIZON_SESSIONS = 5; -const PRE_CUTOFF_SESSIONS = 5_020; - -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) / 4_294_967_296; - }; -} - -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 generateBusinessCalendar(count: number, startYear: number): { - dates: string[]; - closeTs: Float64Array; - afterCloseTs: Float64Array; -} { - const dates: string[] = new Array(count); - const closeTs = new Float64Array(count); - const afterCloseTs = new Float64Array(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}`; - closeTs[produced] = Date.UTC(year, month - 1, day, 21, 0, 0, 0); // 16:00 ET - afterCloseTs[produced] = Date.UTC(year, month - 1, day, 22, 0, 0, 0); // 17:00 ET - produced += 1; - } - - dow = (dow + 1) % 7; - day += 1; - const baseDays = DAYS_IN_MONTH[month] ?? 31; - const maxDay = month === 2 && isLeapYear(year) ? 29 : baseDays; - if (day > maxDay) { - day = 1; - month += 1; - if (month > 12) { - month = 1; - year += 1; - } - } - } - - return { dates, closeTs, afterCloseTs }; -} - -function fnv1aByte(hash: number, byte: number): number { - return Math.imul((hash ^ (byte & 0xff)) >>> 0, 0x01000193) >>> 0; -} - -function fnv1aUint32(hash: number, value: number): number { - const v = value >>> 0; - let h = fnv1aByte(hash, v & 0xff); - h = fnv1aByte(h, (v >>> 8) & 0xff); - h = fnv1aByte(h, (v >>> 16) & 0xff); - h = fnv1aByte(h, (v >>> 24) & 0xff); - return h; -} - -function fnv1aBytes(hash: number, bytes: Uint8Array): number { - let h = hash >>> 0; - for (let i = 0; i < bytes.length; i += 1) { - h = Math.imul((h ^ (bytes[i] as number)) >>> 0, 0x01000193) >>> 0; - } - return h; -} - -const rng = createMulberry32(SEED); -const calendar = generateBusinessCalendar(SESSIONS, 2006); -const vaultCutoffDate = calendar.dates[PRE_CUTOFF_SESSIONS] as string; - -const totalBars = SESSIONS * LISTINGS; -const bars: BarRecord[] = new Array(totalBars); -const signalsPerListing = Math.ceil(SESSIONS / SIGNAL_STRIDE_SESSIONS); -const signals: SignalObservation[] = new Array(LISTINGS * signalsPerListing); - -let barIdx = 0; -let sigIdx = 0; - -for (let l = 0; l < LISTINGS; l += 1) { - const listingId = l + 1; - let price = 10 + (l % 200) * 0.5; - for (let t = 0; t < SESSIONS; t += 1) { - const ts = calendar.closeTs[t] as number; - price = Math.max(1, price * (1 + (rng() - 0.4995) * 0.02)); - bars[barIdx++] = { - listingId, - ts, - open: price, - high: price, - low: price, - close: price, - volume: 10_000, - vwap: price, - knownAt: ts, - }; - if (t % SIGNAL_STRIDE_SESSIONS === 0) { - signals[sigIdx++] = { - listingId, - knownAt: calendar.afterCloseTs[t] as number, - value: rng() * 2 - 1, - }; - } - } -} - -// Timed section: pure buildForwardReturnPanel execution (no fixture generation or checksum). -const started = performance.now(); -const result = buildForwardReturnPanel({ - bars, - signals, - horizonSessions: HORIZON_SESSIONS, - vaultCutoffDate, -}); -const elapsedMs = performance.now() - started; - -// Untimed verification pass: FNV-1a 32-bit checksum over lengths, diagnostics, and typed-array bytes. -let checksum = 0x811c9dc5; -checksum = fnv1aUint32(checksum, result.panel.length); -checksum = fnv1aUint32(checksum, result.sessionDates.length); -checksum = fnv1aUint32(checksum, result.diagnostics.vaultExcludedDates); -checksum = fnv1aUint32(checksum, result.diagnostics.droppedNoSignal); -checksum = fnv1aUint32(checksum, result.diagnostics.droppedStaleSignal); -checksum = fnv1aUint32(checksum, result.diagnostics.droppedMissingForwardBar); -checksum = fnv1aUint32(checksum, result.diagnostics.droppedNonPositiveClose); -checksum = fnv1aUint32(checksum, result.diagnostics.duplicateBars); - -let emittedObservations = 0; -for (let i = 0; i < result.panel.length; i += 1) { - const slice = result.panel[i]; - if (slice === undefined) { - continue; - } - const ids = slice.ids as Int32Array; - const sig = slice.signal as Float64Array; - const ret = slice.forwardReturn as Float64Array; - emittedObservations += ids.length; - checksum = fnv1aBytes(checksum, new Uint8Array(ids.buffer, ids.byteOffset, ids.byteLength)); - checksum = fnv1aBytes(checksum, new Uint8Array(sig.buffer, sig.byteOffset, sig.byteLength)); - checksum = fnv1aBytes(checksum, new Uint8Array(ret.buffer, ret.byteOffset, ret.byteLength)); -} -const checksumHex = checksum.toString(16).padStart(8, '0'); - -const EXPECTED_CHECKSUM = 'f0f28bdf'; -if (checksumHex !== EXPECTED_CHECKSUM) { - throw new Error( - `Benchmark checksum mismatch: expected ${EXPECTED_CHECKSUM}, got ${checksumHex}.` - ); -} - -const rowsPerSec = Math.round(totalBars / (elapsedMs / 1000)); - -console.log( - JSON.stringify( - { - seed: SEED, - sessions: SESSIONS, - listings: LISTINGS, - horizonSessions: HORIZON_SESSIONS, - vaultCutoffDate, - inputBars: totalBars, - inputSignals: signals.length, - panelDates: result.panel.length, - emittedObservations, - elapsedMs: Number(elapsedMs.toFixed(2)), - rowsPerSec, - diagnostics: result.diagnostics, - checksum: checksumHex, - }, - null, - 2 - ) -); diff --git a/libs/research/src/event-panel.ts b/libs/research/src/event-panel.ts deleted file mode 100644 index 53928a35..00000000 --- a/libs/research/src/event-panel.ts +++ /dev/null @@ -1,1069 +0,0 @@ -/** - * Pure, dependency-free event-study panel builder that transforms `MarketDataStore` - * daily bars and point-in-time `events` rows into Vault-safe `EventStudyInput` - * panels for `runEventStudy` / `eventStudy` (`design/MILESTONES.md` M1). - * - * Browser-safe and dependency-free: zero `node:*` imports, zero bare `process` - * access, and no database drivers. - * - * UTC session-calendar derivation: - * - Curated daily bars (`bars_1d.ts`) are stamped at `16:00 ET` (`20:00` or - * `21:00 UTC`), so the UTC calendar date `Math.floor(bar.ts / 86_400_000)` - * matches the exchange session date without timezone drift. - * - * Return-series & `NaN` contract (matching `eventStudy` in - * `libs/calculations/src/analytics/event-study.ts`): - * - `entityReturns` maps each pre-cutoff `listingId` (inserted in ascending order) - * to a `Float64Array` aligned 1:1 with `sessionDates`. - * - Simple close-to-close return `close[d] / close[d - 1] - 1` is computed - * strictly across consecutive exchange-calendar sessions for that listing - * (`currCalIdx === prevCalIdx + 1`) where both closes are finite and `> 0` and - * the resulting return is finite. If an open exchange session is missing for a - * listing (or for all listings), the subsequent session's return is `NaN`. - * - `NaN` is written at session `0`, on any missing-bar session, on the first - * resumption session after a gap, and on any non-positive/non-finite close or - * overflowing ratio (`eventStudy` rejects `±Infinity` with `NON_FINITE_RETURN` - * and cleanly drops events whose `[-preDays, +postDays]` window contains `NaN`). - * - * Point-in-time (PIT) & Vault rules: - * - `sessionDates` holds only calendar dates strictly `< vaultCutoffDate`, and - * `bar.close` is never accessed for any bar on or after `vaultCutoffDate`. - * - Events with `knownAt >= vaultCutoffDate (00:00:00.000Z)` are excluded and - * counted in `diagnostics.vaultExcludedEvents`. - * - Caller-supplied `exchangeCalendars` is required and must cover every pre-Vault - * bar date of every mapped listing. Each listing's events are anchored against - * its exchange's actual pre-Vault session close timestamps (e.g. `13:00 ET` on - * NYSE half-days vs `16:00 ET` on TSX) rather than curated `bars_1d.ts` (which - * is always stamped at `16:00 ET`), and the eligible session date is then mapped - * onto the shared `sessionDates` index. An after-close or post-half-day-close - * event always anchors to the next trading session, never the same day. - */ - -import { - type EventStudyEvent, - type EventStudyInput, - type NumericSeries, - eventDayIndex, -} from '@stock-bot/calculations'; -import type { BarRecord, EventKind, Table } from './market-data-store'; -import { EVENT_KINDS } from './market-data-store-duckdb'; -import { - type BarSortScratch, - MAX_DIRECT_DAY_SPAN, - MS_PER_DAY, - formatDayKeyUtc, - isPlainRecord, - isValidEpochMs, - isValidInt32, - normalizeZero, - parseCalendarDayKey, - sortBarSliceBySession, -} from './panel-shared'; - -const EVENT_KIND_SET: ReadonlySet = new Set(EVENT_KINDS); - -export type EventPanelErrorCode = - | 'invalid_input' - | 'invalid_date' - | 'invalid_bar' - | 'invalid_event' - | 'invalid_option' - | 'duplicate_bar'; - -export interface EventPanelErrorOptions { - readonly cause?: unknown; -} - -/** Typed validation and data-integrity error thrown by the event-panel builder helpers. */ -export class EventPanelError extends Error { - override readonly name = 'EventPanelError'; - readonly code: EventPanelErrorCode; - override readonly cause?: unknown; - - constructor(code: EventPanelErrorCode, message: string, options?: EventPanelErrorOptions) { - super(message, options?.cause !== undefined ? { cause: options.cause } : undefined); - this.code = code; - if (options?.cause !== undefined) { - this.cause = options.cause; - } - Object.setPrototypeOf(this, new.target.prototype); - } -} - -/** Point-in-time event observation aligned to a listing ID and UTC epoch-ms `knownAt`. */ -export interface EventObservation { - readonly listingId: number; - readonly knownAt: number; - readonly kind: EventKind; - readonly subtype: string | null; -} - -/** Optional exact-match allow-list filter for {@link eventsTableToEventRows}. */ -export interface EventsTableFilter { - readonly kinds?: readonly EventKind[]; - readonly subtypes?: readonly string[]; -} - -/** Benchmark return construction mode for {@link buildEventStudyInput}. */ -export type EventStudyBenchmarkMode = 'equal_weight' | 'none'; - -/** Single exchange trading session close entry (`YYYY-MM-DD` date + actual close UTC epoch ms). */ -export interface ExchangeSessionClose { - readonly date: string; - readonly closeTs: number; -} - -/** - * Caller-supplied exchange close calendars for point-in-time event anchoring. - * - * Curated `bars_1d.ts` is stamped at `16:00 ET` even on exchange half-days (e.g. - * `13:00 ET` on NYSE Black Friday). Passing `exchangeCalendars` anchors each - * listing's events against its exchange's actual session close timestamps and - * maps the resulting eligible session date onto the shared `sessionDates` index. - */ -export interface EventStudyExchangeCalendars { - readonly calendars: - | ReadonlyMap - | Readonly>; - readonly listingCalendarId: - | ReadonlyMap - | Readonly>; -} - -/** Input contract for {@link buildEventStudyInput}. */ -export interface BuildEventStudyInputParams { - readonly bars: readonly BarRecord[]; - readonly events: readonly EventObservation[]; - readonly vaultCutoffDate: string; - readonly benchmark?: EventStudyBenchmarkMode; - readonly exchangeCalendars: EventStudyExchangeCalendars; -} - -/** Per-run diagnostic counters reported by {@link buildEventStudyInput}. */ -export interface EventPanelDiagnostics { - readonly vaultExcludedDates: number; - readonly vaultExcludedEvents: number; - readonly droppedUnknownListing: number; - readonly droppedAfterLastSession: number; - readonly droppedMissingCalendarSession: number; - readonly duplicateEvents: number; - readonly duplicateBars: number; - readonly nonPositiveCloseReturns: number; -} - -/** Output contract returned by {@link buildEventStudyInput}. */ -export interface BuildEventStudyInputResult { - readonly input: EventStudyInput; - readonly diagnostics: EventPanelDiagnostics; -} - -const STRICT_INT_KEY_RE = /^(?:0|-?[1-9]\d*)$/; - -interface ParsedExchangeCalendar { - readonly id: string; - readonly dayKeys: Int32Array; - readonly closeTs: Float64Array; - readonly minDayKey: number; - readonly maxDayKey: number; - readonly dayKeyToIdxArr: Int32Array | null; - readonly dayKeyToIdxMap: Map | null; -} - -function lookupCalendarDayIdx(cal: ParsedExchangeCalendar, dayKey: number): number { - if (cal.dayKeys.length === 0 || dayKey < cal.minDayKey || dayKey > cal.maxDayKey) { - return -1; - } - if (cal.dayKeyToIdxArr !== null) { - return cal.dayKeyToIdxArr[dayKey - cal.minDayKey] as number; - } - return (cal.dayKeyToIdxMap as Map).get(dayKey) ?? -1; -} - -function parseStrictCalendarDayKey(value: unknown, field: string): number { - return parseCalendarDayKey(value, field, (message, cause) => - new EventPanelError('invalid_date', message, cause !== undefined ? { cause } : undefined) - ); -} - -function parseExchangeCalendars( - raw: unknown, - vaultCutoffDayKey: number -): Map { - if (!isPlainRecord(raw)) { - throw new EventPanelError( - 'invalid_option', - 'exchangeCalendars must be a non-null plain object.' - ); - } - - const rawCalendars = raw.calendars; - let calendarEntries: Array<[unknown, unknown]>; - if (rawCalendars instanceof Map) { - calendarEntries = Array.from(rawCalendars.entries()); - } else if (isPlainRecord(rawCalendars)) { - calendarEntries = Object.entries(rawCalendars); - } else { - throw new EventPanelError( - 'invalid_option', - 'exchangeCalendars.calendars must be a Map or plain object.' - ); - } - - const parsedByCalId = new Map(); - for (let c = 0; c < calendarEntries.length; c += 1) { - const [calId, rawSessions] = calendarEntries[c] as [unknown, unknown]; - if (typeof calId !== 'string' || calId.length === 0) { - throw new EventPanelError( - 'invalid_option', - `Invalid exchange calendar ID "${String(calId)}": expected a non-empty string.` - ); - } - if (!Array.isArray(rawSessions)) { - throw new EventPanelError( - 'invalid_option', - `exchangeCalendars.calendars["${calId}"] must be an array of { date, closeTs }.` - ); - } - - const n = rawSessions.length; - const allDayKeys = new Int32Array(n); - const allCloseTs = new Float64Array(n); - const order = new Int32Array(n); - for (let i = 0; i < n; i += 1) { - const entry: unknown = rawSessions[i]; - if (!isPlainRecord(entry)) { - throw new EventPanelError( - 'invalid_option', - `exchangeCalendars.calendars["${calId}"][${i}] must be a plain object.` - ); - } - const dk = parseStrictCalendarDayKey( - entry.date, - `exchangeCalendars.calendars["${calId}"][${i}].date` - ); - const closeTs = entry.closeTs; - if (!isValidEpochMs(closeTs)) { - throw new EventPanelError( - 'invalid_option', - `Invalid closeTs in exchangeCalendars.calendars["${calId}"][${i}]: ${String(closeTs)}.` - ); - } - allDayKeys[i] = dk; - allCloseTs[i] = normalizeZero(closeTs); - order[i] = i; - } - - if (n > 1) { - order.sort((a, b) => (allDayKeys[a] as number) - (allDayKeys[b] as number)); - } - - let preCount = 0; - for (let i = 0; i < n; i += 1) { - const currIdx = order[i] as number; - const dk = allDayKeys[currIdx] as number; - const ct = allCloseTs[currIdx] as number; - if (i > 0) { - const prevIdx = order[i - 1] as number; - const prevDk = allDayKeys[prevIdx] as number; - const prevCt = allCloseTs[prevIdx] as number; - if (dk === prevDk) { - throw new EventPanelError( - 'invalid_option', - `Duplicate session date "${formatDayKeyUtc(dk)}" in exchange calendar "${calId}".` - ); - } - if (ct <= prevCt) { - throw new EventPanelError( - 'invalid_option', - `Non-ascending closeTs in exchange calendar "${calId}" at session "${formatDayKeyUtc(dk)}".` - ); - } - } - if (dk < vaultCutoffDayKey) { - preCount += 1; - } - } - - const dayKeys = new Int32Array(preCount); - const closeTs = new Float64Array(preCount); - let outIdx = 0; - for (let i = 0; i < n; i += 1) { - const idx = order[i] as number; - const dk = allDayKeys[idx] as number; - if (dk < vaultCutoffDayKey) { - dayKeys[outIdx] = dk; - closeTs[outIdx] = allCloseTs[idx] as number; - outIdx += 1; - } - } - - let minDayKey = 0; - let maxDayKey = -1; - let dayKeyToIdxArr: Int32Array | null = null; - let dayKeyToIdxMap: Map | null = null; - if (preCount > 0) { - eventDayIndex(closeTs, closeTs[0] as number); - minDayKey = dayKeys[0] as number; - maxDayKey = dayKeys[preCount - 1] as number; - const calSpan = maxDayKey - minDayKey + 1; - if (calSpan <= MAX_DIRECT_DAY_SPAN) { - dayKeyToIdxArr = new Int32Array(calSpan); - dayKeyToIdxArr.fill(-1); - for (let i = 0; i < preCount; i += 1) { - dayKeyToIdxArr[(dayKeys[i] as number) - minDayKey] = i; - } - } else { - dayKeyToIdxMap = new Map(); - for (let i = 0; i < preCount; i += 1) { - dayKeyToIdxMap.set(dayKeys[i] as number, i); - } - } - } - - parsedByCalId.set(calId, { - id: calId, - dayKeys, - closeTs, - minDayKey, - maxDayKey, - dayKeyToIdxArr, - dayKeyToIdxMap, - }); - } - - const rawMapping = raw.listingCalendarId; - const listingCalendars = new Map(); - if (rawMapping instanceof Map) { - for (const [rawLid, calId] of rawMapping.entries()) { - if (!isValidInt32(rawLid)) { - throw new EventPanelError( - 'invalid_option', - `Invalid listingId in exchangeCalendars.listingCalendarId: ${String(rawLid)}.` - ); - } - if (typeof calId !== 'string' || !parsedByCalId.has(calId)) { - throw new EventPanelError( - 'invalid_option', - `Unknown exchange calendar "${String(calId)}" for listingId ${rawLid}.` - ); - } - listingCalendars.set(normalizeZero(rawLid), parsedByCalId.get(calId) as ParsedExchangeCalendar); - } - } else if (isPlainRecord(rawMapping)) { - for (const [key, calId] of Object.entries(rawMapping)) { - if (!STRICT_INT_KEY_RE.test(key)) { - throw new EventPanelError( - 'invalid_option', - `Invalid listingId key "${key}" in exchangeCalendars.listingCalendarId.` - ); - } - const lid = Number(key); - if (!isValidInt32(lid)) { - throw new EventPanelError( - 'invalid_option', - `Invalid INT32 listingId key "${key}" in exchangeCalendars.listingCalendarId.` - ); - } - if (typeof calId !== 'string' || !parsedByCalId.has(calId)) { - throw new EventPanelError( - 'invalid_option', - `Unknown exchange calendar "${String(calId)}" for listingId ${lid}.` - ); - } - listingCalendars.set(normalizeZero(lid), parsedByCalId.get(calId) as ParsedExchangeCalendar); - } - } else { - throw new EventPanelError( - 'invalid_option', - 'exchangeCalendars.listingCalendarId must be a Map or plain object.' - ); - } - - return listingCalendars; -} - -/** - * Maps a `MarketDataStore.events` `Table` into point-in-time {@link EventObservation} - * rows, validating every row upfront (before applying optional exact-match allow-lists) - * and rejecting malformed inputs with {@link EventPanelError}. - */ -export function eventsTableToEventRows( - table: Table, - filter?: EventsTableFilter -): EventObservation[] { - if (!isPlainRecord(table) || !Array.isArray(table.columns) || !Array.isArray(table.rows)) { - throw new EventPanelError( - 'invalid_input', - 'Expected a Table object with array columns and rows.' - ); - } - - let hasListingIdCol = false; - let hasKnownAtCol = false; - let hasKindCol = false; - let hasSubtypeCol = false; - for (let i = 0; i < table.columns.length; i += 1) { - const col: unknown = table.columns[i]; - if (col === 'listing_id') { - hasListingIdCol = true; - } else if (col === 'known_at') { - hasKnownAtCol = true; - } else if (col === 'kind') { - hasKindCol = true; - } else if (col === 'subtype') { - hasSubtypeCol = true; - } - } - if (!hasListingIdCol || !hasKnownAtCol || !hasKindCol || !hasSubtypeCol) { - throw new EventPanelError( - 'invalid_input', - 'Events table is missing required column(s): expected "listing_id", "known_at", "kind", and "subtype".' - ); - } - - let kindFilterSet: Set | null = null; - let subtypeFilterSet: Set | null = null; - if (filter !== undefined) { - if (!isPlainRecord(filter)) { - throw new EventPanelError('invalid_option', 'filter must be a non-null plain object.'); - } - if (filter.kinds !== undefined) { - if (!Array.isArray(filter.kinds) || filter.kinds.length === 0) { - throw new EventPanelError( - 'invalid_option', - 'filter.kinds must be a non-empty array of valid EventKind values.' - ); - } - kindFilterSet = new Set(); - for (let i = 0; i < filter.kinds.length; i += 1) { - const k: unknown = filter.kinds[i]; - if (typeof k !== 'string' || !EVENT_KIND_SET.has(k)) { - throw new EventPanelError( - 'invalid_option', - `Invalid filter.kinds[${i}] "${String(k)}": expected one of ${EVENT_KINDS.join(', ')}.` - ); - } - kindFilterSet.add(k); - } - } - if (filter.subtypes !== undefined) { - if (!Array.isArray(filter.subtypes) || filter.subtypes.length === 0) { - throw new EventPanelError( - 'invalid_option', - 'filter.subtypes must be a non-empty array of strings.' - ); - } - subtypeFilterSet = new Set(); - for (let i = 0; i < filter.subtypes.length; i += 1) { - const s: unknown = filter.subtypes[i]; - if (typeof s !== 'string') { - throw new EventPanelError( - 'invalid_option', - `Invalid filter.subtypes[${i}]: expected a string, got ${typeof s}.` - ); - } - subtypeFilterSet.add(s); - } - } - } - - const out: EventObservation[] = []; - const rows = table.rows; - for (let i = 0; i < rows.length; i += 1) { - const row: unknown = rows[i]; - if (!isPlainRecord(row)) { - throw new EventPanelError('invalid_event', `Events table row[${i}] must be a plain object.`); - } - if ( - !Object.prototype.hasOwnProperty.call(row, 'listing_id') || - !Object.prototype.hasOwnProperty.call(row, 'known_at') || - !Object.prototype.hasOwnProperty.call(row, 'kind') || - !Object.prototype.hasOwnProperty.call(row, 'subtype') - ) { - throw new EventPanelError( - 'invalid_event', - `Events table row[${i}] is missing required key "listing_id", "known_at", "kind", or "subtype".` - ); - } - - const listingId = row.listing_id; - if (!isValidInt32(listingId)) { - throw new EventPanelError( - 'invalid_event', - `Invalid listing_id in events table row[${i}]: ${String(listingId)}.` - ); - } - - const knownAt = row.known_at; - if (!isValidEpochMs(knownAt)) { - throw new EventPanelError( - 'invalid_event', - `Invalid known_at in events table row[${i}]: ${String(knownAt)}.` - ); - } - - const kind = row.kind; - if (typeof kind !== 'string' || !EVENT_KIND_SET.has(kind)) { - throw new EventPanelError( - 'invalid_event', - `Invalid kind in events table row[${i}]: "${String(kind)}".` - ); - } - - const subtype = row.subtype; - if (subtype !== null && typeof subtype !== 'string') { - throw new EventPanelError( - 'invalid_event', - `Invalid subtype in events table row[${i}]: expected string or null, got ${typeof subtype}.` - ); - } - - if (kindFilterSet !== null && !kindFilterSet.has(kind)) { - continue; - } - if (subtypeFilterSet !== null && (subtype === null || !subtypeFilterSet.has(subtype))) { - continue; - } - - out.push({ - listingId: normalizeZero(listingId), - knownAt: normalizeZero(knownAt), - kind: kind as EventKind, - subtype, - }); - } - - return out; -} - -/** - * Pure, synchronous event-study panel builder. - * - * Transforms daily bars (caller-supplied `'total'`-adjusted closes in any order) - * and point-in-time {@link EventObservation} rows into a Vault-safe - * `EventStudyInput` ready for `runEventStudy` / `eventStudy`, without mutating - * caller inputs or ever reading `bar.close` on or after `vaultCutoffDate`. - */ -export function buildEventStudyInput( - params: BuildEventStudyInputParams -): BuildEventStudyInputResult { - if (!isPlainRecord(params)) { - throw new EventPanelError('invalid_input', 'Input must be a non-null plain object.'); - } - - const vaultCutoffDayKey = parseStrictCalendarDayKey(params.vaultCutoffDate, 'vaultCutoffDate'); - const vaultCutoffMs = vaultCutoffDayKey * MS_PER_DAY; - - const rawBenchmark: unknown = params.benchmark; - const benchmark: EventStudyBenchmarkMode = - rawBenchmark === undefined ? 'none' : (rawBenchmark as EventStudyBenchmarkMode); - if (benchmark !== 'none' && benchmark !== 'equal_weight') { - throw new EventPanelError( - 'invalid_option', - `Invalid benchmark "${String(benchmark)}": expected "none" or "equal_weight".` - ); - } - - const listingCalendars = parseExchangeCalendars(params.exchangeCalendars, vaultCutoffDayKey); - - if (!Array.isArray(params.bars)) { - throw new EventPanelError('invalid_input', 'params.bars must be an array of BarRecord.'); - } - if (!Array.isArray(params.events)) { - throw new EventPanelError( - 'invalid_input', - 'params.events must be an array of EventObservation.' - ); - } - - const bars = params.bars; - const events = params.events; - - // Pass 1 over bars: validate structure, build pre-cutoff calendar, count bars per listing. - // Never access `bar.close` when the bar's UTC dayKey reaches or exceeds `vaultCutoffDayKey`. - const postCutoffDays = new Set(); - const preCutoffDays = new Set(); - const listingBarCounts = new Map(); - let preCutoffBarTotal = 0; - - for (let i = 0; i < bars.length; i += 1) { - const rawBar: unknown = bars[i]; - if (!isPlainRecord(rawBar)) { - throw new EventPanelError('invalid_bar', `bars[${i}] must be a non-null plain object.`); - } - - const listingId = rawBar.listingId; - if (!isValidInt32(listingId)) { - throw new EventPanelError( - 'invalid_bar', - `Invalid listingId at bars[${i}]: ${String(listingId)}.` - ); - } - - const ts = rawBar.ts; - if (!isValidEpochMs(ts)) { - throw new EventPanelError('invalid_bar', `Invalid ts at bars[${i}]: ${String(ts)}.`); - } - - const knownAt = rawBar.knownAt; - if (!isValidEpochMs(knownAt)) { - throw new EventPanelError( - 'invalid_bar', - `Invalid knownAt at bars[${i}]: ${String(knownAt)}.` - ); - } - - const dayKey = Math.floor(ts / MS_PER_DAY); - if (dayKey >= vaultCutoffDayKey) { - postCutoffDays.add(dayKey); - continue; - } - - const close = rawBar.close; - if (typeof close !== 'number') { - throw new EventPanelError('invalid_bar', `Invalid close at bars[${i}]: expected a number.`); - } - - preCutoffDays.add(dayKey); - - const normListingId = normalizeZero(listingId); - listingBarCounts.set(normListingId, (listingBarCounts.get(normListingId) ?? 0) + 1); - preCutoffBarTotal += 1; - } - - // Validate all events upfront (even if bars is empty). - for (let i = 0; i < events.length; i += 1) { - const rawEv: unknown = events[i]; - if (!isPlainRecord(rawEv)) { - throw new EventPanelError('invalid_event', `events[${i}] must be a non-null plain object.`); - } - if (!isValidInt32(rawEv.listingId)) { - throw new EventPanelError( - 'invalid_event', - `Invalid listingId at events[${i}]: ${String(rawEv.listingId)}.` - ); - } - if (!isValidEpochMs(rawEv.knownAt)) { - throw new EventPanelError( - 'invalid_event', - `Invalid knownAt at events[${i}]: ${String(rawEv.knownAt)}.` - ); - } - if (typeof rawEv.kind !== 'string' || !EVENT_KIND_SET.has(rawEv.kind)) { - throw new EventPanelError( - 'invalid_event', - `Invalid kind at events[${i}]: "${String(rawEv.kind)}".` - ); - } - if (rawEv.subtype !== null && typeof rawEv.subtype !== 'string') { - throw new EventPanelError( - 'invalid_event', - `Invalid subtype at events[${i}]: expected string or null, got ${typeof rawEv.subtype}.` - ); - } - } - - const vaultExcludedDates = postCutoffDays.size; - - if (preCutoffBarTotal === 0) { - let vaultExcludedEvents = 0; - let droppedUnknownListing = 0; - for (let i = 0; i < events.length; i += 1) { - const ev = events[i] as EventObservation; - if (ev.knownAt >= vaultCutoffMs) { - vaultExcludedEvents += 1; - } else { - droppedUnknownListing += 1; - } - } - - const emptyInput: EventStudyInput = - benchmark === 'equal_weight' - ? { - sessionDates: [], - entityReturns: new Map(), - benchmarkReturns: new Float64Array(0), - events: [], - } - : { - sessionDates: [], - entityReturns: new Map(), - events: [], - }; - - return { - input: emptyInput, - diagnostics: { - vaultExcludedDates, - vaultExcludedEvents, - droppedUnknownListing, - droppedAfterLastSession: 0, - droppedMissingCalendarSession: 0, - duplicateEvents: 0, - duplicateBars: 0, - nonPositiveCloseReturns: 0, - }, - }; - } - - // Build strictly ascending pre-cutoff session calendar. - const preCount = preCutoffDays.size; - const preDayKeys = new Int32Array(preCount); - { - let idx = 0; - for (const dayKey of preCutoffDays) { - preDayKeys[idx] = dayKey; - idx += 1; - } - preDayKeys.sort(); - } - - const sessionDates: string[] = new Array(preCount); - for (let i = 0; i < preCount; i += 1) { - sessionDates[i] = formatDayKeyUtc(preDayKeys[i] as number); - } - - // Sort unique listingIds ascending for deterministic entityReturns Map insertion order. - const listingCount = listingBarCounts.size; - const sortedListingIds = new Int32Array(listingCount); - { - let idx = 0; - for (const lid of listingBarCounts.keys()) { - sortedListingIds[idx] = lid; - idx += 1; - } - sortedListingIds.sort(); - } - - const listingIdToIdx = new Map(); - const barOffsets = new Int32Array(listingCount + 1); - for (let l = 0; l < listingCount; l += 1) { - const lid = sortedListingIds[l] as number; - listingIdToIdx.set(lid, l); - barOffsets[l + 1] = (barOffsets[l] as number) + (listingBarCounts.get(lid) as number); - } - - // Build O(1) dayKey -> sessionIdx lookup (direct Int32Array when span <= 200_000, else Map). - const minDayKey = preDayKeys[0] as number; - const maxDayKey = preDayKeys[preCount - 1] as number; - const daySpan = maxDayKey - minDayKey + 1; - let dayKeyToIdxArr: Int32Array | null = null; - let dayKeyToIdxMap: Map | null = null; - if (daySpan <= MAX_DIRECT_DAY_SPAN) { - dayKeyToIdxArr = new Int32Array(daySpan); - dayKeyToIdxArr.fill(-1); - for (let i = 0; i < preCount; i += 1) { - dayKeyToIdxArr[(preDayKeys[i] as number) - minDayKey] = i; - } - } else { - dayKeyToIdxMap = new Map(); - for (let i = 0; i < preCount; i += 1) { - dayKeyToIdxMap.set(preDayKeys[i] as number, i); - } - } - - // Scatter pre-cutoff bars into CSR typed arrays grouped by listing index. - const barSessionIdx = new Int32Array(preCutoffBarTotal); - const barTs = new Float64Array(preCutoffBarTotal); - const barClose = new Float64Array(preCutoffBarTotal); - const barCursor = new Int32Array(listingCount); - for (let l = 0; l < listingCount; l += 1) { - barCursor[l] = barOffsets[l] as number; - } - - for (let i = 0; i < bars.length; i += 1) { - const bar = bars[i] as BarRecord; - const dayKey = Math.floor(bar.ts / MS_PER_DAY); - if (dayKey >= vaultCutoffDayKey) { - continue; - } - const l = listingIdToIdx.get(normalizeZero(bar.listingId)) as number; - const pos = barCursor[l] as number; - barCursor[l] = pos + 1; - - const sIdx = - dayKeyToIdxArr !== null - ? (dayKeyToIdxArr[dayKey - minDayKey] as number) - : ((dayKeyToIdxMap as Map).get(dayKey) as number); - barSessionIdx[pos] = sIdx; - barTs[pos] = normalizeZero(bar.ts); - barClose[pos] = bar.close; - } - - const barScratch: BarSortScratch = { - sessionIdx: new Int32Array(0), - ts: new Float64Array(0), - close: new Float64Array(0), - }; - - const entityReturns = new Map(); - const computeBench = benchmark === 'equal_weight'; - const benchSum = computeBench ? new Float64Array(preCount) : null; - const benchCount = computeBench ? new Int32Array(preCount) : null; - - let duplicateBars = 0; - let nonPositiveCloseReturns = 0; - - for (let l = 0; l < listingCount; l += 1) { - const listingId = sortedListingIds[l] as number; - const cal = listingCalendars.get(listingId); - if (cal === undefined) { - throw new EventPanelError( - 'invalid_option', - `Missing exchange calendar mapping for listingId ${listingId}.` - ); - } - - const bStart = barOffsets[l] as number; - const bEnd = barOffsets[l + 1] as number; - - sortBarSliceBySession(barSessionIdx, barTs, barClose, bStart, bEnd, barScratch); - - // Compact exact duplicates in place; reject conflicting duplicates on the same (listingId, date). - let write = bStart; - for (let i = bStart + 1; i < bEnd; i += 1) { - if (barSessionIdx[i] === barSessionIdx[write]) { - const prevTs = barTs[write] as number; - const currTs = barTs[i] as number; - const prevClose = barClose[write] as number; - const currClose = barClose[i] as number; - const sameClose = - prevClose === currClose || (Number.isNaN(prevClose) && Number.isNaN(currClose)); - if (currTs === prevTs && sameClose) { - duplicateBars += 1; - continue; - } - const conflictDate = sessionDates[barSessionIdx[i] as number] as string; - throw new EventPanelError( - 'duplicate_bar', - `Conflicting duplicate bars for listingId ${listingId} on session ${conflictDate}.` - ); - } - write += 1; - if (write !== i) { - barSessionIdx[write] = barSessionIdx[i] as number; - barTs[write] = barTs[i] as number; - barClose[write] = barClose[i] as number; - } - } - const uniqueEnd = write + 1; - - // Verify that the listing's mapped exchange calendar covers every pre-Vault bar date, - // and compute close-to-close returns strictly across consecutive exchange sessions. - const firstSIdx = barSessionIdx[bStart] as number; - let prevCalIdx = lookupCalendarDayIdx(cal, preDayKeys[firstSIdx] as number); - if (prevCalIdx < 0) { - throw new EventPanelError( - 'invalid_option', - `Exchange calendar "${cal.id}" for listingId ${listingId} does not cover pre-Vault bar session ${sessionDates[firstSIdx]}.` - ); - } - - const returns = new Float64Array(preCount); - returns.fill(Number.NaN); - - for (let i = bStart + 1; i < uniqueEnd; i += 1) { - const currSIdx = barSessionIdx[i] as number; - const currCalIdx = lookupCalendarDayIdx(cal, preDayKeys[currSIdx] as number); - if (currCalIdx < 0) { - throw new EventPanelError( - 'invalid_option', - `Exchange calendar "${cal.id}" for listingId ${listingId} does not cover pre-Vault bar session ${sessionDates[currSIdx]}.` - ); - } - const isConsecutiveSession = currCalIdx === prevCalIdx + 1; - prevCalIdx = currCalIdx; - if (!isConsecutiveSession) { - continue; - } - const prevClose = barClose[i - 1] as number; - const currClose = barClose[i] as number; - if (!Number.isFinite(prevClose) || prevClose <= 0 || !Number.isFinite(currClose) || currClose <= 0) { - nonPositiveCloseReturns += 1; - continue; - } - const ret = currClose / prevClose - 1; - if (!Number.isFinite(ret)) { - nonPositiveCloseReturns += 1; - continue; - } - const normRet = normalizeZero(ret); - returns[currSIdx] = normRet; - if (benchSum !== null && benchCount !== null) { - benchSum[currSIdx] = (benchSum[currSIdx] as number) + normRet; - benchCount[currSIdx] = (benchCount[currSIdx] as number) + 1; - } - } - - entityReturns.set(listingId, returns); - } - - let benchmarkReturns: Float64Array | undefined; - if (benchSum !== null && benchCount !== null) { - benchmarkReturns = new Float64Array(preCount); - benchmarkReturns.fill(Number.NaN); - for (let t = 0; t < preCount; t += 1) { - const count = benchCount[t] as number; - if (count > 0) { - const mean = (benchSum[t] as number) / count; - if (Number.isFinite(mean)) { - benchmarkReturns[t] = normalizeZero(mean); - } - } - } - } - - // Classify and anchor events in strict precedence order: - // (1) vaultExcludedEvents -> (2) droppedUnknownListing -> (3) droppedAfterLastSession - // -> (4) droppedMissingCalendarSession -> (5) anchor via the listing's exchange calendar. - const candDay = new Int32Array(events.length); - const candListing = new Int32Array(events.length); - let candCount = 0; - let vaultExcludedEvents = 0; - let droppedUnknownListing = 0; - let droppedAfterLastSession = 0; - let droppedMissingCalendarSession = 0; - - for (let i = 0; i < events.length; i += 1) { - const ev = events[i] as EventObservation; - const knownAt = normalizeZero(ev.knownAt); - if (knownAt >= vaultCutoffMs) { - vaultExcludedEvents += 1; - continue; - } - - const normListingId = normalizeZero(ev.listingId); - const l = listingIdToIdx.get(normListingId); - if (l === undefined) { - droppedUnknownListing += 1; - continue; - } - - const cal = listingCalendars.get(normListingId) as ParsedExchangeCalendar; - const calLen = cal.closeTs.length; - if (calLen === 0 || knownAt > (cal.closeTs[calLen - 1] as number)) { - droppedAfterLastSession += 1; - continue; - } - - // Lower-bound binary search over the listing's actual exchange close timestamps. - let lo = 0; - let hi = calLen - 1; - while (lo < hi) { - const mid = (lo + hi) >>> 1; - if ((cal.closeTs[mid] as number) < knownAt) { - lo = mid + 1; - } else { - hi = mid; - } - } - - const eligibleDayKey = cal.dayKeys[lo] as number; - if (eligibleDayKey > maxDayKey) { - droppedAfterLastSession += 1; - continue; - } - - const mappedIdx = - eligibleDayKey < minDayKey - ? -1 - : dayKeyToIdxArr !== null - ? (dayKeyToIdxArr[eligibleDayKey - minDayKey] as number) - : ((dayKeyToIdxMap as Map).get(eligibleDayKey) ?? -1); - if (mappedIdx < 0) { - droppedMissingCalendarSession += 1; - continue; - } - - candDay[candCount] = mappedIdx; - candListing[candCount] = l; - candCount += 1; - } - - // Canonical 2-pass counting sort into (dayIndex ASC, listingIdx ASC). - if (candCount > 1) { - const tmpDay = new Int32Array(candCount); - const tmpListing = new Int32Array(candCount); - - const listingCounts = new Int32Array(listingCount + 1); - for (let i = 0; i < candCount; i += 1) { - const idx = (candListing[i] as number) + 1; - listingCounts[idx] = (listingCounts[idx] as number) + 1; - } - for (let l = 1; l <= listingCount; l += 1) { - listingCounts[l] = (listingCounts[l] as number) + (listingCounts[l - 1] as number); - } - for (let i = 0; i < candCount; i += 1) { - const l = candListing[i] as number; - const pos = listingCounts[l] as number; - listingCounts[l] = pos + 1; - tmpDay[pos] = candDay[i] as number; - tmpListing[pos] = l; - } - - const dayCounts = new Int32Array(preCount + 1); - for (let i = 0; i < candCount; i += 1) { - const idx = (tmpDay[i] as number) + 1; - dayCounts[idx] = (dayCounts[idx] as number) + 1; - } - for (let d = 1; d <= preCount; d += 1) { - dayCounts[d] = (dayCounts[d] as number) + (dayCounts[d - 1] as number); - } - for (let i = 0; i < candCount; i += 1) { - const d = tmpDay[i] as number; - const pos = dayCounts[d] as number; - dayCounts[d] = pos + 1; - candDay[pos] = d; - candListing[pos] = tmpListing[i] as number; - } - } - - // Collapse exact duplicate (listingId, dayIndex) events (keep one). - const anchoredEvents: EventStudyEvent[] = []; - let duplicateEvents = 0; - let prevDay = -1; - let prevListing = -1; - - for (let i = 0; i < candCount; i += 1) { - const d = candDay[i] as number; - const l = candListing[i] as number; - if (d === prevDay && l === prevListing) { - duplicateEvents += 1; - continue; - } - prevDay = d; - prevListing = l; - anchoredEvents.push({ - entityId: sortedListingIds[l] as number, - dayIndex: d, - }); - } - - const input: EventStudyInput = - benchmarkReturns !== undefined - ? { - sessionDates, - entityReturns, - benchmarkReturns, - events: anchoredEvents, - } - : { - sessionDates, - entityReturns, - events: anchoredEvents, - }; - - return { - input, - diagnostics: { - vaultExcludedDates, - vaultExcludedEvents, - droppedUnknownListing, - droppedAfterLastSession, - droppedMissingCalendarSession, - duplicateEvents, - duplicateBars, - nonPositiveCloseReturns, - }, - }; -} diff --git a/libs/research/src/feature-library.ts b/libs/research/src/feature-library.ts deleted file mode 100644 index 680a3bf1..00000000 --- a/libs/research/src/feature-library.ts +++ /dev/null @@ -1,2193 +0,0 @@ -/** - * Versioned Feature Library core: declarative DuckDB SQL feature definitions, - * immutable `registerSignal` registry, and Vault-fenced yearly Parquet - * batch-plan runner (`design/PLATFORM-PLAN.md` §8 & D11, - * `design/DATA-CONTRACTS.md` §3.A). - * - * Pure, dependency-free, and browser-safe: zero `node:*` imports, zero DuckDB - * driver dependency, zero bare `process` access. SQL execution is injected via - * {@link DuckDbExecutor} from `./market-data-store-duckdb`. - * - * Output Parquet contract (`design/DATA-CONTRACTS.md` §3.A): - * - `/features//v/year=YYYY/part.parquet` - * - Columns: `(listing_id INT32, ts TIMESTAMPTZ, known_at TIMESTAMPTZ, value DOUBLE)` - * - Compression: `ZSTD`, ordered by `(listing_id, ts)`. - * - * Point-in-time & `adj_factors` note: - * - Each expanded `{{input:}}` scan binds upper availability - * predicates strictly below `vaultCutoffDate` before authored SQL executes, - * while preserving earlier history for SQL-owned warm-up windows. - * - Feature definitions own per-observation availability (`knownAtRule` and - * projected `known_at`). Because `adj_factors` stores cumulative suffix - * products, any feature consuming `{{input:adj_factors}}` requires a - * caller-verified, immutable point-in-time snapshot compatible with the job - * cutoff. - * - * Economic ownership & research evidence: - * - The Quant research role owns the economic specification of each feature - * definition. - * - {@link RET_1D_V1} is a built-in 1-session raw-close return example using a - * zero-return comparison baseline and no execution or transaction cost model. - * - Any future research result claim built on materialized features must retain - * the feature ref and `definitionHash`, immutable dataset identifier, sample - * window, Vault cutoff, baseline, and execution assumptions. - */ - -import { - MarketDataStoreValidationError, - VaultHoldoutFenceError, - applyVaultFence, -} from './market-data-store'; -import { - type DuckDbExecutor, - type DuckDbParam, - validateCuratedRoot, -} from './market-data-store-duckdb'; -import { sha256HexUtf8 } from './sha256'; - -export const FEATURE_FAMILIES = [ - 'technical', - 'cross_sectional', - 'fundamental', - 'event', - 'fx', - 'regime', -] as const; -export type FeatureFamily = (typeof FEATURE_FAMILIES)[number]; - -export const FEATURE_KINDS = ['duckdb_sql'] as const; -export type FeatureKind = (typeof FEATURE_KINDS)[number]; - -export const FEATURE_INPUT_DATASETS = [ - 'bars_1d', - 'adj_factors', - 'events', - 'shorts', - 'fx_1d', - 'fundamentals_pit', -] as const; -export type FeatureInputDataset = (typeof FEATURE_INPUT_DATASETS)[number]; - -export const FEATURE_KNOWN_AT_RULES = [ - 'bar_close', - 'source_known_at', - 'max_input_known_at', -] as const; -export type FeatureKnownAtRule = (typeof FEATURE_KNOWN_AT_RULES)[number]; - -export const FEATURE_OUTPUT_COLUMNS = ['listing_id', 'ts', 'known_at', 'value'] as const; - -const FEATURE_FAMILY_SET: ReadonlySet = new Set(FEATURE_FAMILIES); -const FEATURE_INPUT_SET: ReadonlySet = new Set(FEATURE_INPUT_DATASETS); -const FEATURE_KNOWN_AT_RULE_SET: ReadonlySet = new Set(FEATURE_KNOWN_AT_RULES); - -const FEATURE_NAME_RE = /^[a-z][a-z0-9_]{0,62}$/; -const FEATURE_REF_RE = /^([a-z][a-z0-9_]{0,62})@v([1-9]\d*)$/; -const PLACEHOLDER_INNER_RE = /^input:([a-z][a-z0-9_]*)$/; -const DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/; - -const MIN_FOUR_DIGIT_YEAR = 1000; -const MAX_FOUR_DIGIT_YEAR = 9999; - -export type FeatureLibraryErrorCode = - | 'INVALID_DEFINITION' - | 'INVALID_NAME' - | 'INVALID_VERSION' - | 'INVALID_FAMILY' - | 'INVALID_KIND' - | 'INVALID_WARMUP_BARS' - | 'INVALID_KNOWN_AT_RULE' - | 'INVALID_FEATURE_REF' - | 'INVALID_SQL_STATEMENT' - | 'PROHIBITED_SQL_OPERATION' - | 'EXTERNAL_DATA_ACCESS' - | 'INVALID_SQL_PROJECTION' - | 'UNSUPPORTED_INPUT_DATASET' - | 'UNDECLARED_INPUT' - | 'UNUSED_INPUT' - | 'FEATURE_VERSION_IMMUTABLE' - | 'INVALID_BATCH_OPTIONS' - | 'VAULT_RANGE_VIOLATION' - | 'BATCH_WRITE_FAILED'; - -export interface FeatureBatchWriteReceipt { - readonly year: number; - readonly outputPath: string; -} - -export interface FeatureLibraryErrorDetails { - readonly cause?: unknown; - readonly failedYear?: number; - readonly completedYears?: readonly number[]; - readonly completedWrites?: readonly FeatureBatchWriteReceipt[]; - readonly ref?: string; -} - -/** Typed fail-closed error thrown by the Feature Library SDK. */ -export class FeatureLibraryError extends Error { - override readonly name = 'FeatureLibraryError'; - readonly code: FeatureLibraryErrorCode; - readonly failedYear?: number; - readonly completedYears?: readonly number[]; - readonly completedWrites?: readonly FeatureBatchWriteReceipt[]; - readonly ref?: string; - - constructor( - code: FeatureLibraryErrorCode, - message: string, - details?: FeatureLibraryErrorDetails - ) { - super(message, details?.cause !== undefined ? { cause: details.cause } : undefined); - this.code = code; - this.failedYear = details?.failedYear; - this.completedYears = - details?.completedYears !== undefined - ? Object.freeze([...details.completedYears]) - : undefined; - this.completedWrites = - details?.completedWrites !== undefined - ? Object.freeze(details.completedWrites.map(w => Object.freeze({ ...w }))) - : undefined; - this.ref = details?.ref; - Object.setPrototypeOf(this, new.target.prototype); - } -} - -export interface FeatureDefinition { - readonly name: string; - readonly version: number; - readonly family: FeatureFamily; - readonly kind: FeatureKind; - readonly sql: string; - readonly inputs: readonly FeatureInputDataset[]; - readonly warmupBars: number; - readonly knownAtRule: FeatureKnownAtRule; - readonly description?: string; -} - -export interface FeatureRefParts { - readonly name: string; - readonly version: number; -} - -export interface RegisteredFeature { - readonly ref: string; - readonly definitionHash: string; - readonly definition: FeatureDefinition; -} - -export interface FeatureRegistry { - registerSignal(def: FeatureDefinition): RegisteredFeature; - get(ref: string): FeatureDefinition | undefined; - list(): readonly string[]; -} - -export interface PlanFeatureBatchOptions { - readonly curatedRoot: string; - readonly fromYear: number; - readonly toYear: number; - readonly vaultCutoffDate: string; -} - -export interface PlannedFeatureWrite { - readonly year: number; - readonly outputPath: string; - readonly sql: string; - readonly params: readonly DuckDbParam[]; -} - -export interface FeatureBatchManifest { - readonly ref: string; - readonly definitionHash: string; - readonly knownAtRule: FeatureKnownAtRule; - readonly warmupBars: number; - readonly inputs: readonly FeatureInputDataset[]; - readonly writes: readonly FeatureBatchWriteReceipt[]; -} - -const PROHIBITED_SQL_KEYWORDS: ReadonlySet = new Set([ - 'ALTER', - 'ANALYZE', - 'ATTACH', - 'BEGIN', - 'CALL', - 'CHECKPOINT', - 'COMMIT', - 'COPY', - 'CREATE', - 'DEALLOCATE', - 'DELETE', - 'DESCRIBE', - 'DETACH', - 'DROP', - 'EXECUTE', - 'EXPLAIN', - 'EXPORT', - 'GRANT', - 'IMPORT', - 'INSERT', - 'INSTALL', - 'LOAD', - 'MERGE', - 'PIVOT', - 'PRAGMA', - 'PREPARE', - 'RESET', - 'REVOKE', - 'ROLLBACK', - 'SET', - 'SHOW', - 'SUMMARIZE', - 'TRUNCATE', - 'UNPIVOT', - 'UPDATE', - 'UPSERT', - 'USE', - 'VACUUM', -]); - -const EXTERNAL_READER_IDENTIFIERS: ReadonlySet = new Set([ - 'CURRENT_SETTING', - 'DELTA_SCAN', - 'DUCKDB_COLUMNS', - 'DUCKDB_CONSTRAINTS', - 'DUCKDB_DATABASES', - 'DUCKDB_DEPENDENCIES', - 'DUCKDB_EXTENSIONS', - 'DUCKDB_FUNCTIONS', - 'DUCKDB_INDEXES', - 'DUCKDB_KEYWORDS', - 'DUCKDB_MEMORY', - 'DUCKDB_OPTIMIZERS', - 'DUCKDB_SCHEMAS', - 'DUCKDB_SECRETS', - 'DUCKDB_SEQUENCES', - 'DUCKDB_SETTINGS', - 'DUCKDB_TABLES', - 'DUCKDB_TEMPORARY_FILES', - 'DUCKDB_TYPES', - 'DUCKDB_VIEWS', - 'GETENV', - 'GLOB', - 'HTTP_GET', - 'ICEBERG_SCAN', - 'MYSQL_SCAN', - 'PARQUET_FILE_METADATA', - 'PARQUET_KV_METADATA', - 'PARQUET_METADATA', - 'PARQUET_SCAN', - 'PARQUET_SCHEMA', - 'POSTGRES_SCAN', - 'PRAGMA_DATABASE_LIST', - 'PRAGMA_STORAGE_INFO', - 'PRAGMA_TABLE_INFO', - 'READ_BLOB', - 'READ_CSV', - 'READ_CSV_AUTO', - 'READ_EXCEL', - 'READ_JSON', - 'READ_JSON_AUTO', - 'READ_NDJSON', - 'READ_NDJSON_AUTO', - 'READ_PARQUET', - 'READ_STAT', - 'READ_TEXT', - 'SQLITE_SCAN', - 'ST_READ', -]); - -/** - * Pure built-in scalar, aggregate, window, date/time, string, and type-cast - * functions permitted in declarative feature SQL. Excludes all file, network, - * catalog, secret, and system-inspection functions. - */ -const ALLOWED_SQL_FUNCTIONS: ReadonlySet = new Set([ - // Casting & type constructors - 'BIT', - 'CAST', - 'CHAR', - 'CHARACTER', - 'DECIMAL', - 'INTERVAL', - 'NUMERIC', - 'TIME', - 'TIMESTAMP', - 'TIMESTAMPTZ', - 'TRY_CAST', - 'TYPEOF', - 'VARCHAR', - // Null / conditional - 'COALESCE', - 'GREATEST', - 'IF', - 'IFNULL', - 'ISFINITE', - 'ISINF', - 'ISNAN', - 'LEAST', - 'NULLIF', - // Math - 'ABS', - 'ACOS', - 'ASIN', - 'ATAN', - 'ATAN2', - 'CBRT', - 'CEIL', - 'CEILING', - 'COS', - 'COT', - 'DEGREES', - 'EXP', - 'FLOOR', - 'LN', - 'LOG', - 'LOG10', - 'LOG2', - 'MOD', - 'PI', - 'POW', - 'POWER', - 'RADIANS', - 'ROUND', - 'SIGN', - 'SIN', - 'SQRT', - 'TAN', - 'TRUNC', - // Aggregate - 'ANY_VALUE', - 'ARG_MAX', - 'ARG_MIN', - 'AVG', - 'CORR', - 'COUNT', - 'COVAR_POP', - 'COVAR_SAMP', - 'FIRST', - 'GEOMEAN', - 'KURTOSIS', - 'LAST', - 'MAD', - 'MAX', - 'MEDIAN', - 'MIN', - 'MODE', - 'PERCENTILE_CONT', - 'PERCENTILE_DISC', - 'PRODUCT', - 'QUANTILE', - 'QUANTILE_CONT', - 'QUANTILE_DISC', - 'REGR_INTERCEPT', - 'REGR_R2', - 'REGR_SLOPE', - 'SKEWNESS', - 'STDDEV', - 'STDDEV_POP', - 'STDDEV_SAMP', - 'SUM', - 'VAR_POP', - 'VAR_SAMP', - 'VARIANCE', - // Window - 'CUME_DIST', - 'DENSE_RANK', - 'FIRST_VALUE', - 'LAG', - 'LAST_VALUE', - 'LEAD', - 'NTH_VALUE', - 'NTILE', - 'PERCENT_RANK', - 'RANK', - 'ROW_NUMBER', - // Date / time - 'DATE_ADD', - 'DATE_DIFF', - 'DATE_PART', - 'DATE_SUB', - 'DATE_TRUNC', - 'DATEDIFF', - 'DAY', - 'DAYOFWEEK', - 'DAYOFYEAR', - 'EPOCH', - 'EPOCH_MS', - 'EPOCH_NS', - 'EPOCH_US', - 'EXTRACT', - 'HOUR', - 'LAST_DAY', - 'MAKE_DATE', - 'MAKE_TIMESTAMP', - 'MINUTE', - 'MONTH', - 'QUARTER', - 'SECOND', - 'STRFTIME', - 'STRPTIME', - 'TIME_BUCKET', - 'WEEK', - 'YEAR', - // String & pure JSON - 'CONCAT', - 'CONCAT_WS', - 'CONTAINS', - 'ENDS_WITH', - 'JSON_EXTRACT', - 'JSON_EXTRACT_PATH', - 'JSON_EXTRACT_PATH_TEXT', - 'JSON_EXTRACT_STRING', - 'LEFT', - 'LENGTH', - 'LOWER', - 'LTRIM', - 'POSITION', - 'RIGHT', - 'RTRIM', - 'SPLIT_PART', - 'STARTS_WITH', - 'STRLEN', - 'STRPOS', - 'SUBSTR', - 'SUBSTRING', - 'TRIM', - 'UPPER', -]); - -/** SQL keywords that can syntactically precede `(` without being a function call. */ -const KEYWORD_BEFORE_LPAREN: ReadonlySet = new Set([ - 'ALL', - 'AND', - 'ANY', - 'AS', - 'ASC', - 'BETWEEN', - 'BY', - 'CASE', - 'DESC', - 'DISTINCT', - 'ELSE', - 'EXISTS', - 'FILTER', - 'FIRST', - 'FROM', - 'HAVING', - 'IN', - 'IS', - 'JOIN', - 'LAST', - 'NOT', - 'NULLS', - 'ON', - 'OR', - 'ORDER', - 'OVER', - 'PARTITION', - 'QUALIFY', - 'SELECT', - 'SOME', - 'THEN', - 'USING', - 'VALUES', - 'WHEN', - 'WHERE', - 'WITHIN', -]); - -const CLAUSE_TERMINATOR_KEYWORDS: ReadonlySet = new Set([ - 'EXCEPT', - 'FETCH', - 'FROM', - 'GROUP', - 'HAVING', - 'INTERSECT', - 'LIMIT', - 'OFFSET', - 'ORDER', - 'QUALIFY', - 'UNION', - 'WHERE', - 'WINDOW', -]); - -const JOIN_MODIFIER_KEYWORDS: ReadonlySet = new Set([ - 'ANTI', - 'ASOF', - 'CROSS', - 'FULL', - 'INNER', - 'JOIN', - 'LEFT', - 'NATURAL', - 'OUTER', - 'POSITIONAL', - 'RIGHT', - 'SEMI', -]); - -const NON_ALIAS_KEYWORDS: ReadonlySet = new Set([ - ...CLAUSE_TERMINATOR_KEYWORDS, - ...JOIN_MODIFIER_KEYWORDS, - 'ON', - 'USING', -]); - -const PATH_OR_URI_PREFIX_RE = /^(?:\/|\.\/|\.\.\/|~\/|(?:s3|gs|http|https|file|hf|az|r2):\/\/)/i; -const PATH_EXTENSION_RE = /\.(?:parquet|csv|tsv|json|jsonl|ndjson|duckdb|db|sqlite|txt|gz|zst)$/i; -const PATH_GLOB_OR_TRAVERSAL_RE = /(?:^|\/)\.\.(?:\/|$)|\/\*|\*\./; - -type SqlToken = - | { readonly kind: 'word'; readonly value: string; readonly upper: string; readonly raw: string } - | { readonly kind: 'quoted_ident'; readonly value: string; readonly raw: string } - | { readonly kind: 'string'; readonly value: string; readonly raw: string } - | { readonly kind: 'number'; readonly raw: string } - | { readonly kind: 'placeholder'; readonly dataset: string; readonly raw: string } - | { readonly kind: 'lparen'; readonly raw: '(' } - | { readonly kind: 'rparen'; readonly raw: ')' } - | { readonly kind: 'comma'; readonly raw: ',' } - | { readonly kind: 'dot'; readonly raw: '.' } - | { readonly kind: 'op'; readonly raw: string }; - -interface DatasetScanSpec { - readonly relativePath: string; - readonly hivePartitioning: boolean; - readonly predicateKind: 'ts_and_known_at' | 'known_at' | 'effective_known_at'; -} - -const DATASET_SCAN_SPECS: Readonly> = { - bars_1d: { - relativePath: 'bars_1d/year=*/part.parquet', - hivePartitioning: true, - predicateKind: 'ts_and_known_at', - }, - adj_factors: { - relativePath: 'adj_factors/part.parquet', - hivePartitioning: false, - predicateKind: 'known_at', - }, - events: { - relativePath: 'events/year=*/part.parquet', - hivePartitioning: true, - predicateKind: 'ts_and_known_at', - }, - shorts: { - relativePath: 'shorts/part.parquet', - hivePartitioning: false, - predicateKind: 'known_at', - }, - fx_1d: { - relativePath: 'fx_1d/part.parquet', - hivePartitioning: false, - predicateKind: 'ts_and_known_at', - }, - fundamentals_pit: { - relativePath: 'fundamentals_pit/year=*/part.parquet', - hivePartitioning: true, - predicateKind: 'effective_known_at', - }, -}; - -function isPlainRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value); -} - -function compareAscii(a: string, b: string): number { - return a < b ? -1 : a > b ? 1 : 0; -} - -function isAsciiWhitespace(code: number): boolean { - return code === 0x20 || code === 0x09 || code === 0x0a || code === 0x0d || code === 0x0c; -} - -function isIdentStart(code: number): boolean { - return ( - (code >= 0x41 && code <= 0x5a) || // A-Z - (code >= 0x61 && code <= 0x7a) || // a-z - code === 0x5f // _ - ); -} - -function isIdentContinue(code: number): boolean { - return isIdentStart(code) || (code >= 0x30 && code <= 0x39); -} - -function isDigit(code: number): boolean { - return code >= 0x30 && code <= 0x39; -} - -function looksLikeExternalPath(value: string): boolean { - return ( - PATH_OR_URI_PREFIX_RE.test(value) || - PATH_EXTENSION_RE.test(value) || - PATH_GLOB_OR_TRAVERSAL_RE.test(value) - ); -} - -/** - * Quote-aware SQL tokenizer shared by validation, canonical hashing, and - * `{{input:}}` placeholder expansion. - */ -function tokenizeFeatureSql(sql: string): SqlToken[] { - const tokens: SqlToken[] = []; - const len = sql.length; - let i = 0; - - while (i < len) { - const code = sql.charCodeAt(i); - if (isAsciiWhitespace(code)) { - i += 1; - continue; - } - - // Reject SQL comments (-- or /* ... */). - if (code === 0x2d && i + 1 < len && sql.charCodeAt(i + 1) === 0x2d) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'SQL line comments ("--") are not permitted in feature definitions.' - ); - } - if (code === 0x2f && i + 1 < len && sql.charCodeAt(i + 1) === 0x2a) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'SQL block comments ("/* ... */") are not permitted in feature definitions.' - ); - } - if (code === 0x2a && i + 1 < len && sql.charCodeAt(i + 1) === 0x2f) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'Unexpected SQL block comment terminator ("*/") in feature definition.' - ); - } - - // Reject statement separators (;). - if (code === 0x3b) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'Multiple SQL statements or semicolons (";") are not permitted in feature definitions.' - ); - } - - // Reject caller-supplied bind markers (?, $1, $name, :name). - if (code === 0x3f) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'Caller-supplied bind markers ("?") are not permitted in feature definitions.' - ); - } - if (code === 0x24) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'Dollar-prefixed parameters or dollar-quoted strings ("$") are not permitted in feature definitions.' - ); - } - - // Placeholder: {{input:}} - if (code === 0x7b && i + 1 < len && sql.charCodeAt(i + 1) === 0x7b) { - const closeIdx = sql.indexOf('}}', i + 2); - if (closeIdx === -1) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'Unterminated placeholder "{{" in feature SQL.' - ); - } - const inner = sql.slice(i + 2, closeIdx); - const match = PLACEHOLDER_INNER_RE.exec(inner); - if (match === null) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - `Malformed input placeholder "{{${inner}}}". Expected "{{input:}}".` - ); - } - const dataset = match[1] as string; - const raw = sql.slice(i, closeIdx + 2); - tokens.push({ kind: 'placeholder', dataset, raw }); - i = closeIdx + 2; - continue; - } - - // Single-quoted string literal ('...'). - if (code === 0x27) { - const start = i; - i += 1; - let value = ''; - let closed = false; - while (i < len) { - const c = sql.charCodeAt(i); - if (c === 0x27) { - if (i + 1 < len && sql.charCodeAt(i + 1) === 0x27) { - value += "'"; - i += 2; - continue; - } - i += 1; - closed = true; - break; - } - value += sql[i] as string; - i += 1; - } - if (!closed) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'Unterminated single-quoted string literal in feature SQL.' - ); - } - tokens.push({ kind: 'string', value, raw: sql.slice(start, i) }); - continue; - } - - // Double-quoted identifier ("..."). - if (code === 0x22) { - const start = i; - i += 1; - let value = ''; - let closed = false; - while (i < len) { - const c = sql.charCodeAt(i); - if (c === 0x22) { - if (i + 1 < len && sql.charCodeAt(i + 1) === 0x22) { - value += '"'; - i += 2; - continue; - } - i += 1; - closed = true; - break; - } - value += sql[i] as string; - i += 1; - } - if (!closed || value.length === 0) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'Unterminated or empty double-quoted identifier in feature SQL.' - ); - } - tokens.push({ kind: 'quoted_ident', value, raw: sql.slice(start, i) }); - continue; - } - - // Unquoted word (keyword or identifier). - if (isIdentStart(code)) { - const start = i; - i += 1; - while (i < len && isIdentContinue(sql.charCodeAt(i))) { - i += 1; - } - const value = sql.slice(start, i); - tokens.push({ kind: 'word', value, upper: value.toUpperCase(), raw: value }); - continue; - } - - // Numeric literal (digits or .digits). - if (isDigit(code) || (code === 0x2e && i + 1 < len && isDigit(sql.charCodeAt(i + 1)))) { - const start = i; - let hasDot = false; - if (code === 0x2e) { - hasDot = true; - i += 1; - } - while (i < len && isDigit(sql.charCodeAt(i))) { - i += 1; - } - if (!hasDot && i < len && sql.charCodeAt(i) === 0x2e) { - i += 1; - while (i < len && isDigit(sql.charCodeAt(i))) { - i += 1; - } - } - if (i < len && (sql.charCodeAt(i) === 0x65 || sql.charCodeAt(i) === 0x45)) { - const expPos = i; - i += 1; - if (i < len && (sql.charCodeAt(i) === 0x2b || sql.charCodeAt(i) === 0x2d)) { - i += 1; - } - if (i >= len || !isDigit(sql.charCodeAt(i))) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - `Malformed numeric exponent at offset ${expPos} in feature SQL.` - ); - } - while (i < len && isDigit(sql.charCodeAt(i))) { - i += 1; - } - } - tokens.push({ kind: 'number', raw: sql.slice(start, i) }); - continue; - } - - // Punctuation. - if (code === 0x28) { - tokens.push({ kind: 'lparen', raw: '(' }); - i += 1; - continue; - } - if (code === 0x29) { - tokens.push({ kind: 'rparen', raw: ')' }); - i += 1; - continue; - } - if (code === 0x2c) { - tokens.push({ kind: 'comma', raw: ',' }); - i += 1; - continue; - } - if (code === 0x2e) { - tokens.push({ kind: 'dot', raw: '.' }); - i += 1; - continue; - } - - // Two-character operators. - if (i + 1 < len) { - const two = sql.slice(i, i + 2); - if ( - two === '<>' || - two === '!=' || - two === '<=' || - two === '>=' || - two === '||' || - two === '::' - ) { - tokens.push({ kind: 'op', raw: two }); - i += 2; - continue; - } - } - - // Reject single ':' (named bind marker). - if (code === 0x3a) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'Colon-prefixed bind markers (":name") are not permitted in feature definitions.' - ); - } - - // Single-character operators. - if ( - code === 0x2b || // + - code === 0x2d || // - - code === 0x2a || // * - code === 0x2f || // / - code === 0x25 || // % - code === 0x3d || // = - code === 0x3c || // < - code === 0x3e // > - ) { - tokens.push({ kind: 'op', raw: sql[i] as string }); - i += 1; - continue; - } - - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - `Unsupported token character "${sql[i] as string}" at offset ${i} in feature SQL.` - ); - } - - return tokens; -} - -function findMatchingParen(tokens: readonly SqlToken[], openIndex: number, end: number): number { - let depth = 0; - for (let i = openIndex; i < end; i += 1) { - const tok = tokens[i] as SqlToken; - if (tok.kind === 'lparen') { - depth += 1; - } else if (tok.kind === 'rparen') { - depth -= 1; - if (depth === 0) { - return i; - } - } - } - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'Unbalanced parentheses in feature SQL.' - ); -} - -function assertBalancedParens(tokens: readonly SqlToken[]): void { - let depth = 0; - for (let i = 0; i < tokens.length; i += 1) { - const tok = tokens[i] as SqlToken; - if (tok.kind === 'lparen') { - depth += 1; - } else if (tok.kind === 'rparen') { - depth -= 1; - if (depth < 0) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'Unbalanced closing parenthesis ")" in feature SQL.' - ); - } - } - } - if (depth !== 0) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'Unbalanced opening parenthesis "(" in feature SQL.' - ); - } -} - -function extractIdentifierText(tok: SqlToken | undefined): string | null { - if (tok === undefined) { - return null; - } - if (tok.kind === 'word') { - return tok.value.toLowerCase(); - } - if (tok.kind === 'quoted_ident') { - return tok.value; - } - return null; -} - -function extractProjectionOutputName(tokens: readonly SqlToken[], start: number, end: number): string { - if (start >= end) { - throw new FeatureLibraryError( - 'INVALID_SQL_PROJECTION', - 'Empty projection expression in final SELECT list.' - ); - } - - // Reject wildcard projections (* or alias.*) at top level of the projection item. - let depth = 0; - for (let i = start; i < end; i += 1) { - const tok = tokens[i] as SqlToken; - if (tok.kind === 'lparen') { - depth += 1; - } else if (tok.kind === 'rparen') { - depth -= 1; - } else if (depth === 0 && tok.kind === 'op' && tok.raw === '*') { - const prev = i > start ? tokens[i - 1] : undefined; - if (prev === undefined || prev.kind === 'dot') { - throw new FeatureLibraryError( - 'INVALID_SQL_PROJECTION', - 'Wildcard projections ("*" / "alias.*") are not permitted; final SELECT must explicitly project listing_id, ts, known_at, value.' - ); - } - } - } - - // Case 1: explicit `... AS ` at top level. - if (end - start >= 3) { - const asTok = tokens[end - 2]; - const aliasTok = tokens[end - 1]; - if (asTok?.kind === 'word' && asTok.upper === 'AS') { - const alias = extractIdentifierText(aliasTok); - if (alias === null) { - throw new FeatureLibraryError( - 'INVALID_SQL_PROJECTION', - 'Expected an output column identifier after AS in final SELECT projection.' - ); - } - return alias; - } - } - - // Case 2: simple column reference `` or `.`. - if (end - start === 1) { - const name = extractIdentifierText(tokens[start]); - if (name !== null) { - return name; - } - } - if (end - start === 3 && tokens[start + 1]?.kind === 'dot') { - const qual = extractIdentifierText(tokens[start]); - const col = extractIdentifierText(tokens[start + 2]); - if (qual !== null && col !== null) { - return col; - } - } - - throw new FeatureLibraryError( - 'INVALID_SQL_PROJECTION', - 'Every expression in the final SELECT list must be a direct column reference or use an explicit AS alias matching (listing_id, ts, known_at, value).' - ); -} - -function hasTopLevelSetOperator(tokens: readonly SqlToken[], start: number, end: number): boolean { - let depth = 0; - for (let i = start; i < end; i += 1) { - const tok = tokens[i] as SqlToken; - if (tok.kind === 'lparen') { - depth += 1; - } else if (tok.kind === 'rparen') { - depth -= 1; - } else if ( - depth === 0 && - tok.kind === 'word' && - (tok.upper === 'UNION' || tok.upper === 'INTERSECT' || tok.upper === 'EXCEPT') - ) { - return true; - } - } - return false; -} - -function validateExpressionSlice( - tokens: readonly SqlToken[], - start: number, - end: number, - inScopeCtes: ReadonlySet -): void { - let i = start; - while (i < end) { - const tok = tokens[i] as SqlToken; - - // Nested subquery: (SELECT ...), (WITH ...), or compound subquery ((SELECT ...) UNION ...); - // reject DuckDB FROM-first / TABLE subqueries. - if (tok.kind === 'lparen') { - const closeIdx = findMatchingParen(tokens, i, end); - const innerFirst = tokens[i + 1]; - if ( - (innerFirst?.kind === 'word' && - (innerFirst.upper === 'SELECT' || innerFirst.upper === 'WITH')) || - hasTopLevelSetOperator(tokens, i + 1, closeIdx) - ) { - validateQuerySlice(tokens, i + 1, closeIdx, inScopeCtes, false); - i = closeIdx + 1; - continue; - } - if ( - innerFirst?.kind === 'word' && - (innerFirst.upper === 'FROM' || innerFirst.upper === 'TABLE') - ) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - `Unsupported subquery form "(${innerFirst.upper} ...)" in feature SQL; subqueries must begin with SELECT or WITH.` - ); - } - i += 1; - continue; - } - - // Fail closed if an unparsed JOIN token appears inside an expression or clause tail. - if (tok.kind === 'word' && tok.upper === 'JOIN') { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'Unexpected JOIN outside a parsed FROM/JOIN clause in feature SQL.' - ); - } - - // Callable function check: followed by '('. - if ( - (tok.kind === 'word' || tok.kind === 'quoted_ident') && - i + 1 < end && - tokens[i + 1]?.kind === 'lparen' - ) { - const upper = tok.kind === 'word' ? tok.upper : tok.value.toUpperCase(); - if (tok.kind === 'word' && KEYWORD_BEFORE_LPAREN.has(upper)) { - i += 1; - continue; - } - // Reject schema-qualified function calls (e.g. main.read_parquet(...)). - if (i > start && tokens[i - 1]?.kind === 'dot') { - throw new FeatureLibraryError( - 'EXTERNAL_DATA_ACCESS', - `Schema-qualified function call ".${tok.raw}(...)" is not permitted in feature SQL.` - ); - } - if (!ALLOWED_SQL_FUNCTIONS.has(upper)) { - throw new FeatureLibraryError( - 'EXTERNAL_DATA_ACCESS', - `Unsupported or prohibited SQL function "${tok.raw}(...)" in feature SQL.` - ); - } - } - - i += 1; - } -} - -// DuckDB folds identifier case for ASCII letters only; mirror that exact rule for CTE scope. -function foldAsciiIdentifier(identifier: string): string { - return identifier.replace(/[A-Z]/g, (ch) => String.fromCharCode(ch.charCodeAt(0) + 32)); -} - -function parseTableReference( - tokens: readonly SqlToken[], - start: number, - end: number, - inScopeCtes: ReadonlySet -): number { - if (start >= end) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'Expected a relation source after FROM or JOIN in feature SQL.' - ); - } - - let pos = start; - const tok = tokens[pos] as SqlToken; - - if (tok.kind === 'placeholder') { - pos += 1; - } else if (tok.kind === 'lparen') { - const closeIdx = findMatchingParen(tokens, pos, end); - const innerFirst = tokens[pos + 1]; - if ( - innerFirst === undefined || - innerFirst.kind !== 'word' || - (innerFirst.upper !== 'SELECT' && innerFirst.upper !== 'WITH') - ) { - throw new FeatureLibraryError( - 'EXTERNAL_DATA_ACCESS', - 'Parenthesized relation source must be a SELECT or WITH subquery.' - ); - } - validateQuerySlice(tokens, pos + 1, closeIdx, inScopeCtes, false); - pos = closeIdx + 1; - } else if (tok.kind === 'word' || tok.kind === 'quoted_ident') { - // Reject table functions (`fn(...)`) and qualified catalog relations (`schema.table`). - const next = pos + 1 < end ? tokens[pos + 1] : undefined; - if (next?.kind === 'lparen') { - throw new FeatureLibraryError( - 'EXTERNAL_DATA_ACCESS', - `Table function "${tok.raw}(...)" is not permitted as a relation source in feature SQL.` - ); - } - if (next?.kind === 'dot') { - throw new FeatureLibraryError( - 'EXTERNAL_DATA_ACCESS', - `Catalog or schema-qualified relation "${tok.raw}...." is not permitted; use {{input:}} placeholders.` - ); - } - const cteName = foldAsciiIdentifier(tok.value); - if (!inScopeCtes.has(cteName)) { - throw new FeatureLibraryError( - 'EXTERNAL_DATA_ACCESS', - `Direct table reference "${tok.raw}" is not an in-scope CTE; use {{input:}} placeholders.` - ); - } - pos += 1; - } else { - throw new FeatureLibraryError( - 'EXTERNAL_DATA_ACCESS', - `Unsupported relation source "${tok.raw}" in feature SQL; use {{input:}}, an in-scope CTE, or a subquery.` - ); - } - - // Optional table alias: `[AS] [(col1, col2, ...)]`. - if (pos < end) { - const maybeAs = tokens[pos] as SqlToken; - if (maybeAs.kind === 'word' && maybeAs.upper === 'AS') { - pos += 1; - if (pos >= end || (tokens[pos]?.kind !== 'word' && tokens[pos]?.kind !== 'quoted_ident')) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'Expected table alias identifier after AS.' - ); - } - pos += 1; - } else if ( - (maybeAs.kind === 'word' && !NON_ALIAS_KEYWORDS.has(maybeAs.upper)) || - maybeAs.kind === 'quoted_ident' - ) { - pos += 1; - } - - // Optional column alias list `(c1, c2)`. - if (pos < end && tokens[pos]?.kind === 'lparen') { - const closeIdx = findMatchingParen(tokens, pos, end); - pos = closeIdx + 1; - } - } - - return pos; -} - -function isJoinClauseStart(tokens: readonly SqlToken[], start: number, end: number): boolean { - let pos = start; - while (pos < end) { - const tok = tokens[pos] as SqlToken; - if (tok.kind !== 'word' || !JOIN_MODIFIER_KEYWORDS.has(tok.upper)) { - return false; - } - if (tok.upper === 'JOIN') { - return true; - } - pos += 1; - } - return false; -} - -function validateSelectBranch( - tokens: readonly SqlToken[], - start: number, - end: number, - inScopeCtes: ReadonlySet, - requireContractProjection: boolean -): void { - if (start >= end) { - throw new FeatureLibraryError('INVALID_SQL_STATEMENT', 'Empty SELECT branch in feature SQL.'); - } - - // Parenthesized SELECT branch: `(SELECT ...)` - if (tokens[start]?.kind === 'lparen') { - const closeIdx = findMatchingParen(tokens, start, end); - if (closeIdx === end - 1) { - validateQuerySlice(tokens, start + 1, closeIdx, inScopeCtes, requireContractProjection); - return; - } - } - - const first = tokens[start]; - if (first?.kind !== 'word' || first.upper !== 'SELECT') { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - `Expected SELECT statement, got "${first?.raw ?? ''}".` - ); - } - - let pos = start + 1; - if ( - pos < end && - tokens[pos]?.kind === 'word' && - ((tokens[pos] as { upper: string }).upper === 'DISTINCT' || - (tokens[pos] as { upper: string }).upper === 'ALL') - ) { - pos += 1; - } - - // Find end of SELECT projection list (first top-level FROM or other clause terminator). - let depth = 0; - let projEnd = end; - for (let i = pos; i < end; i += 1) { - const tok = tokens[i] as SqlToken; - if (tok.kind === 'lparen') { - depth += 1; - } else if (tok.kind === 'rparen') { - depth -= 1; - } else if (depth === 0 && tok.kind === 'word' && CLAUSE_TERMINATOR_KEYWORDS.has(tok.upper)) { - projEnd = i; - break; - } - } - - if (projEnd === pos) { - throw new FeatureLibraryError( - 'INVALID_SQL_PROJECTION', - 'SELECT clause has an empty projection list.' - ); - } - - // Validate expressions inside projection list. - validateExpressionSlice(tokens, pos, projEnd, inScopeCtes); - - if (requireContractProjection) { - const itemBounds: Array<{ start: number; end: number }> = []; - let itemStart = pos; - depth = 0; - for (let i = pos; i < projEnd; i += 1) { - const tok = tokens[i] as SqlToken; - if (tok.kind === 'lparen') { - depth += 1; - } else if (tok.kind === 'rparen') { - depth -= 1; - } else if (depth === 0 && tok.kind === 'comma') { - itemBounds.push({ start: itemStart, end: i }); - itemStart = i + 1; - } - } - itemBounds.push({ start: itemStart, end: projEnd }); - - if (itemBounds.length !== FEATURE_OUTPUT_COLUMNS.length) { - throw new FeatureLibraryError( - 'INVALID_SQL_PROJECTION', - `Final SELECT must project exactly ${FEATURE_OUTPUT_COLUMNS.length} columns (${FEATURE_OUTPUT_COLUMNS.join(', ')}), got ${itemBounds.length}.` - ); - } - - for (let idx = 0; idx < FEATURE_OUTPUT_COLUMNS.length; idx += 1) { - const bound = itemBounds[idx] as { start: number; end: number }; - const actualName = extractProjectionOutputName(tokens, bound.start, bound.end); - const expectedName = FEATURE_OUTPUT_COLUMNS[idx] as string; - if (actualName !== expectedName) { - throw new FeatureLibraryError( - 'INVALID_SQL_PROJECTION', - `Final SELECT column #${idx + 1} must be named "${expectedName}", got "${actualName}".` - ); - } - } - } - - // Scan FROM / JOIN clauses and remaining clauses at paren depth 0. - pos = projEnd; - while (pos < end) { - const tok = tokens[pos] as SqlToken; - - if (tok.kind === 'word' && tok.upper === 'FROM') { - pos += 1; - // Parse one or more comma-separated table references, plus any chained JOINs. - pos = parseTableReference(tokens, pos, end, inScopeCtes); - while (pos < end) { - const nextTok = tokens[pos] as SqlToken; - if (nextTok.kind === 'comma') { - pos += 1; - pos = parseTableReference(tokens, pos, end, inScopeCtes); - continue; - } - if (nextTok.kind === 'word' && JOIN_MODIFIER_KEYWORDS.has(nextTok.upper)) { - // Consume join modifiers up to and including JOIN. - let foundJoin = false; - while (pos < end) { - const jTok = tokens[pos] as SqlToken; - if (jTok.kind === 'word' && JOIN_MODIFIER_KEYWORDS.has(jTok.upper)) { - pos += 1; - if (jTok.upper === 'JOIN') { - foundJoin = true; - break; - } - } else { - break; - } - } - if (!foundJoin) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'Malformed JOIN clause in feature SQL.' - ); - } - pos = parseTableReference(tokens, pos, end, inScopeCtes); - - // Optional ON or USING (...) before next JOIN or clause terminator. - if (pos < end && tokens[pos]?.kind === 'word') { - const condKw = (tokens[pos] as { upper: string }).upper; - if (condKw === 'ON' || condKw === 'USING') { - const condStart = pos + 1; - let condEnd = end; - let cDepth = 0; - for (let k = condStart; k < end; k += 1) { - const ct = tokens[k] as SqlToken; - if (ct.kind === 'lparen') { - cDepth += 1; - } else if (ct.kind === 'rparen') { - cDepth -= 1; - } else if ( - cDepth === 0 && - (ct.kind === 'comma' || - (ct.kind === 'word' && - (CLAUSE_TERMINATOR_KEYWORDS.has(ct.upper) || - isJoinClauseStart(tokens, k, end)))) - ) { - condEnd = k; - break; - } - } - validateExpressionSlice(tokens, condStart, condEnd, inScopeCtes); - pos = condEnd; - } - } - continue; - } - break; - } - if (pos < end) { - const afterFrom = tokens[pos] as SqlToken; - if ( - afterFrom.kind !== 'word' || - !CLAUSE_TERMINATOR_KEYWORDS.has(afterFrom.upper) || - afterFrom.upper === 'FROM' - ) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - `Unexpected token "${afterFrom.raw}" after FROM/JOIN clause in feature SQL.` - ); - } - } - continue; - } - - // Remaining clause expressions (WHERE, GROUP BY, HAVING, WINDOW, QUALIFY, ORDER BY, LIMIT, OFFSET). - const exprStart = pos; - let exprEnd = end; - let eDepth = 0; - for (let k = exprStart + 1; k < end; k += 1) { - const et = tokens[k] as SqlToken; - if (et.kind === 'lparen') { - eDepth += 1; - } else if (et.kind === 'rparen') { - eDepth -= 1; - } else if (eDepth === 0 && et.kind === 'word' && et.upper === 'FROM') { - exprEnd = k; - break; - } - } - validateExpressionSlice(tokens, exprStart, exprEnd, inScopeCtes); - pos = exprEnd; - } -} - -function validateQuerySlice( - tokens: readonly SqlToken[], - start: number, - end: number, - outerCtes: ReadonlySet, - requireContractProjection: boolean -): void { - if (start >= end) { - throw new FeatureLibraryError('INVALID_SQL_STATEMENT', 'Empty SQL query in feature definition.'); - } - - const inScopeCtes = new Set(outerCtes); - let pos = start; - - // Optional leading WITH clause (non-recursive CTEs only). - if (tokens[pos]?.kind === 'word' && (tokens[pos] as { upper: string }).upper === 'WITH') { - pos += 1; - if (pos < end && tokens[pos]?.kind === 'word' && (tokens[pos] as { upper: string }).upper === 'RECURSIVE') { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'WITH RECURSIVE CTEs are not permitted in feature SQL; use non-recursive CTEs.' - ); - } - - while (pos < end) { - const nameTok = tokens[pos]; - if (nameTok === undefined || (nameTok.kind !== 'word' && nameTok.kind !== 'quoted_ident')) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'Expected CTE name identifier after WITH in feature SQL.' - ); - } - const cteName = foldAsciiIdentifier(nameTok.value); - pos += 1; - - // Optional CTE column list `(col1, col2)`. - if (pos < end && tokens[pos]?.kind === 'lparen') { - pos = findMatchingParen(tokens, pos, end) + 1; - } - - if (pos >= end || tokens[pos]?.kind !== 'word' || (tokens[pos] as { upper: string }).upper !== 'AS') { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - `Expected AS after CTE name "${nameTok.raw}" in feature SQL.` - ); - } - pos += 1; - - // Optional `[NOT] MATERIALIZED`. - if (pos < end && tokens[pos]?.kind === 'word' && (tokens[pos] as { upper: string }).upper === 'NOT') { - pos += 1; - } - if ( - pos < end && - tokens[pos]?.kind === 'word' && - (tokens[pos] as { upper: string }).upper === 'MATERIALIZED' - ) { - pos += 1; - } - - if (pos >= end || tokens[pos]?.kind !== 'lparen') { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - `Expected "(" opening CTE body for "${nameTok.raw}" in feature SQL.` - ); - } - const bodyClose = findMatchingParen(tokens, pos, end); - validateQuerySlice(tokens, pos + 1, bodyClose, inScopeCtes, false); - inScopeCtes.add(cteName); - pos = bodyClose + 1; - - if (pos < end && tokens[pos]?.kind === 'comma') { - pos += 1; - continue; - } - break; - } - } - - // Split remaining query by top-level set operators (UNION [ALL|DISTINCT], INTERSECT, EXCEPT). - const branches: Array<{ start: number; end: number }> = []; - let branchStart = pos; - let depth = 0; - for (let i = pos; i < end; i += 1) { - const tok = tokens[i] as SqlToken; - if (tok.kind === 'lparen') { - depth += 1; - } else if (tok.kind === 'rparen') { - depth -= 1; - } else if ( - depth === 0 && - tok.kind === 'word' && - (tok.upper === 'UNION' || tok.upper === 'INTERSECT' || tok.upper === 'EXCEPT') - ) { - branches.push({ start: branchStart, end: i }); - let nextPos = i + 1; - if ( - nextPos < end && - tokens[nextPos]?.kind === 'word' && - ((tokens[nextPos] as { upper: string }).upper === 'ALL' || - (tokens[nextPos] as { upper: string }).upper === 'DISTINCT') - ) { - nextPos += 1; - } - branchStart = nextPos; - i = nextPos - 1; - } - } - branches.push({ start: branchStart, end }); - - for (let b = 0; b < branches.length; b += 1) { - const branch = branches[b] as { start: number; end: number }; - validateSelectBranch(tokens, branch.start, branch.end, inScopeCtes, requireContractProjection); - } -} - -interface ValidatedFeatureInternal { - readonly def: FeatureDefinition; - readonly tokens: readonly SqlToken[]; - readonly normalizedInputs: readonly FeatureInputDataset[]; -} - -function validateName(name: unknown): string { - if (typeof name !== 'string' || !FEATURE_NAME_RE.test(name)) { - throw new FeatureLibraryError( - 'INVALID_NAME', - `Invalid feature name "${String(name)}". Expected ^[a-z][a-z0-9_]{0,62}$.` - ); - } - return name; -} - -function validateVersion(version: unknown): number { - if (typeof version !== 'number' || !Number.isSafeInteger(version) || version < 1) { - throw new FeatureLibraryError( - 'INVALID_VERSION', - `Invalid feature version "${String(version)}". Expected a positive safe integer.` - ); - } - return version; -} - -function validateFeatureDefinitionInternal(def: FeatureDefinition): ValidatedFeatureInternal { - if (!isPlainRecord(def)) { - throw new FeatureLibraryError( - 'INVALID_DEFINITION', - 'Feature definition must be a plain object.' - ); - } - - validateName(def.name); - validateVersion(def.version); - - if (typeof def.family !== 'string' || !FEATURE_FAMILY_SET.has(def.family)) { - throw new FeatureLibraryError( - 'INVALID_FAMILY', - `Invalid feature family "${String(def.family)}". Expected one of: ${FEATURE_FAMILIES.join(', ')}.` - ); - } - - if (def.kind !== 'duckdb_sql') { - throw new FeatureLibraryError( - 'INVALID_KIND', - `Invalid feature kind "${String(def.kind)}". Expected 'duckdb_sql'.` - ); - } - - if (typeof def.warmupBars !== 'number' || !Number.isSafeInteger(def.warmupBars) || def.warmupBars < 0) { - throw new FeatureLibraryError( - 'INVALID_WARMUP_BARS', - `Invalid warmupBars "${String(def.warmupBars)}". Expected a non-negative safe integer.` - ); - } - - if (typeof def.knownAtRule !== 'string' || !FEATURE_KNOWN_AT_RULE_SET.has(def.knownAtRule)) { - throw new FeatureLibraryError( - 'INVALID_KNOWN_AT_RULE', - `Invalid knownAtRule "${String(def.knownAtRule)}". Expected one of: ${FEATURE_KNOWN_AT_RULES.join(', ')}.` - ); - } - - if (def.description !== undefined && typeof def.description !== 'string') { - throw new FeatureLibraryError( - 'INVALID_DEFINITION', - 'Feature description must be a string when provided.' - ); - } - - if (!Array.isArray(def.inputs) || def.inputs.length === 0) { - throw new FeatureLibraryError( - 'INVALID_DEFINITION', - 'Feature definition must declare a non-empty inputs array.' - ); - } - - const declaredSet = new Set(); - const normalizedInputs: FeatureInputDataset[] = []; - for (let i = 0; i < def.inputs.length; i += 1) { - const rawInput: unknown = def.inputs[i]; - if (typeof rawInput !== 'string' || !FEATURE_INPUT_SET.has(rawInput)) { - throw new FeatureLibraryError( - 'UNSUPPORTED_INPUT_DATASET', - `Unsupported input dataset "${String(rawInput)}". Allowed datasets: ${FEATURE_INPUT_DATASETS.join(', ')}.` - ); - } - const ds = rawInput as FeatureInputDataset; - if (!declaredSet.has(ds)) { - declaredSet.add(ds); - normalizedInputs.push(ds); - } - } - - if (typeof def.sql !== 'string' || def.sql.trim().length === 0) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'Feature SQL must be a non-empty string.' - ); - } - - const tokens = tokenizeFeatureSql(def.sql); - if (tokens.length === 0) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'Feature SQL must contain a SELECT or WITH statement.' - ); - } - - // Pass 1: check prohibited statement/operation keywords. - for (let i = 0; i < tokens.length; i += 1) { - const tok = tokens[i] as SqlToken; - if (tok.kind === 'word' && PROHIBITED_SQL_KEYWORDS.has(tok.upper)) { - throw new FeatureLibraryError( - 'PROHIBITED_SQL_OPERATION', - `Prohibited SQL operation "${tok.raw}" is not permitted in feature definitions.` - ); - } - } - - // Pass 2: check external readers and quoted file paths/URIs. - for (let i = 0; i < tokens.length; i += 1) { - const tok = tokens[i] as SqlToken; - if (tok.kind === 'word' && EXTERNAL_READER_IDENTIFIERS.has(tok.upper)) { - throw new FeatureLibraryError( - 'EXTERNAL_DATA_ACCESS', - `Direct external reader "${tok.raw}" is not permitted; reference datasets via {{input:}}.` - ); - } - if (tok.kind === 'quoted_ident' && EXTERNAL_READER_IDENTIFIERS.has(tok.value.toUpperCase())) { - throw new FeatureLibraryError( - 'EXTERNAL_DATA_ACCESS', - `Direct external reader ${tok.raw} is not permitted; reference datasets via {{input:}}.` - ); - } - if ((tok.kind === 'string' || tok.kind === 'quoted_ident') && looksLikeExternalPath(tok.value)) { - throw new FeatureLibraryError( - 'EXTERNAL_DATA_ACCESS', - `Quoted file path or URI ${tok.raw} is not permitted in feature SQL; reference datasets via {{input:}}.` - ); - } - } - - // Pass 3: check leading statement keyword and balanced parentheses. - const firstTok = tokens[0] as SqlToken; - if (firstTok.kind !== 'word' || (firstTok.upper !== 'SELECT' && firstTok.upper !== 'WITH')) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - `Feature SQL must begin with SELECT or WITH, got "${firstTok.raw}".` - ); - } - assertBalancedParens(tokens); - - // Pass 4: structural validation of CTEs, FROM/JOIN sources, functions, and final projection. - validateQuerySlice(tokens, 0, tokens.length, new Set(), true); - - // Pass 5: verify placeholder declarations and usage. - const usedInputs = new Set(); - for (let i = 0; i < tokens.length; i += 1) { - const tok = tokens[i] as SqlToken; - if (tok.kind !== 'placeholder') { - continue; - } - if (!declaredSet.has(tok.dataset as FeatureInputDataset)) { - throw new FeatureLibraryError( - 'UNDECLARED_INPUT', - `SQL placeholder "{{input:${tok.dataset}}}" is not declared in definition.inputs.` - ); - } - usedInputs.add(tok.dataset as FeatureInputDataset); - } - - for (let i = 0; i < normalizedInputs.length; i += 1) { - const declared = normalizedInputs[i] as FeatureInputDataset; - if (!usedInputs.has(declared)) { - throw new FeatureLibraryError( - 'UNUSED_INPUT', - `Declared input dataset "${declared}" is not referenced via "{{input:${declared}}}" in feature SQL.` - ); - } - } - - return { def, tokens, normalizedInputs }; -} - -/** - * Validates a declarative feature definition and throws a typed - * {@link FeatureLibraryError} on any contract, SQL safety, projection, or - * input-declaration violation. - */ -export function validateFeatureDefinition(def: FeatureDefinition): void { - validateFeatureDefinitionInternal(def); -} - -/** - * Formats the canonical versioned feature reference `'@v'`. - */ -export function featureRef(def: Pick): string { - if (!isPlainRecord(def)) { - throw new FeatureLibraryError( - 'INVALID_DEFINITION', - 'Expected an object with name and version for featureRef.' - ); - } - const name = validateName(def.name); - const version = validateVersion(def.version); - return `${name}@v${version}`; -} - -/** - * Parses a canonical versioned feature reference `'@v'`, - * rejecting non-canonical forms such as `'ret_1d@v01'` or `'RSI-14@v1'`. - */ -export function parseFeatureRef(ref: string): FeatureRefParts { - if (typeof ref !== 'string') { - throw new FeatureLibraryError( - 'INVALID_FEATURE_REF', - `Invalid feature ref "${String(ref)}". Expected "@v".` - ); - } - const match = FEATURE_REF_RE.exec(ref); - if (match === null) { - throw new FeatureLibraryError( - 'INVALID_FEATURE_REF', - `Invalid feature ref "${ref}". Expected "@v" with lowercase name and canonical positive integer version.` - ); - } - const name = match[1] as string; - const version = Number(match[2]); - if (!Number.isSafeInteger(version) || version < 1) { - throw new FeatureLibraryError( - 'INVALID_FEATURE_REF', - `Invalid feature version in ref "${ref}". Expected a positive safe integer.` - ); - } - return Object.freeze({ name, version }); -} - -function canonicalizeSqlTokens(tokens: readonly SqlToken[]): string { - const parts = new Array(tokens.length); - for (let i = 0; i < tokens.length; i += 1) { - parts[i] = (tokens[i] as SqlToken).raw; - } - return parts.join(' '); -} - -/** - * Computes a deterministic 64-character lowercase SHA-256 hex digest over the - * semantic specification of a validated feature definition (name, version, - * kind, canonicalized SQL tokens, sorted inputs, `warmupBars`, and - * `knownAtRule`). Inter-token whitespace, object key order, and input array - * order do not affect the hash; literal whitespace and semantic changes do. - */ -export function featureDefinitionHash(def: FeatureDefinition): string { - const validated = validateFeatureDefinitionInternal(def); - const sortedInputs = [...validated.normalizedInputs].sort(compareAscii); - const canonicalPayload = JSON.stringify({ - name: def.name, - version: def.version, - kind: def.kind, - sql: canonicalizeSqlTokens(validated.tokens), - inputs: sortedInputs, - warmupBars: def.warmupBars, - knownAtRule: def.knownAtRule, - }); - return sha256HexUtf8(canonicalPayload); -} - -function cloneFeatureDefinition(def: FeatureDefinition): FeatureDefinition { - const copy: FeatureDefinition = { - name: def.name, - version: def.version, - family: def.family, - kind: def.kind, - sql: def.sql, - inputs: Object.freeze([...def.inputs]), - warmupBars: def.warmupBars, - knownAtRule: def.knownAtRule, - ...(def.description !== undefined ? { description: def.description } : {}), - }; - return Object.freeze(copy); -} - -/** - * Creates an in-memory immutable versioned feature registry (`registerSignal` - * SDK entrypoint, D11). Re-registering an identical definition hash is - * idempotent; re-registering the same `@v` with a different - * semantic hash throws `FeatureLibraryError('FEATURE_VERSION_IMMUTABLE')`. - */ -export function createFeatureRegistry(): FeatureRegistry { - const entries = new Map(); - - return { - registerSignal(def: FeatureDefinition): RegisteredFeature { - validateFeatureDefinitionInternal(def); - const ref = featureRef(def); - const definitionHash = featureDefinitionHash(def); - const existing = entries.get(ref); - if (existing !== undefined) { - if (existing.definitionHash === definitionHash) { - return Object.freeze({ - ref: existing.ref, - definitionHash: existing.definitionHash, - definition: cloneFeatureDefinition(existing.definition), - }); - } - throw new FeatureLibraryError( - 'FEATURE_VERSION_IMMUTABLE', - `Feature "${ref}" is already registered with hash ${existing.definitionHash}; cannot overwrite with ${definitionHash}. Bump version to register a changed definition.`, - { ref } - ); - } - - const stored: RegisteredFeature = Object.freeze({ - ref, - definitionHash, - definition: cloneFeatureDefinition(def), - }); - entries.set(ref, stored); - return Object.freeze({ - ref: stored.ref, - definitionHash: stored.definitionHash, - definition: cloneFeatureDefinition(stored.definition), - }); - }, - - get(ref: string): FeatureDefinition | undefined { - if (typeof ref !== 'string') { - return undefined; - } - const existing = entries.get(ref); - return existing !== undefined ? cloneFeatureDefinition(existing.definition) : undefined; - }, - - list(): readonly string[] { - return Array.from(entries.keys()); - }, - }; -} - -function joinCuratedPath(normalizedRoot: string, relativePath: string): string { - return normalizedRoot === '/' ? `/${relativePath}` : `${normalizedRoot}/${relativePath}`; -} - -function formatUtcIsoWithMicros(epochMs: number, subMsMicros: number): string { - const isoMs = new Date(epochMs).toISOString(); - if (subMsMicros === 0) { - return isoMs; - } - const extra = String(subMsMicros).padStart(3, '0'); - return `${isoMs.slice(0, -1)}${extra}Z`; -} - -function validateFourDigitYear(value: unknown, field: string): number { - if ( - typeof value !== 'number' || - !Number.isSafeInteger(value) || - value < MIN_FOUR_DIGIT_YEAR || - value > MAX_FOUR_DIGIT_YEAR - ) { - throw new FeatureLibraryError( - 'INVALID_BATCH_OPTIONS', - `Invalid "${field}": "${String(value)}". Expected a four-digit integer year (${MIN_FOUR_DIGIT_YEAR}..${MAX_FOUR_DIGIT_YEAR}).` - ); - } - return value; -} - -function parseVaultCutoffDateMs(raw: unknown): number { - if (typeof raw !== 'string' || !DATE_ONLY_RE.test(raw)) { - throw new FeatureLibraryError( - 'INVALID_BATCH_OPTIONS', - `Invalid "vaultCutoffDate": "${String(raw)}". Expected strict UTC YYYY-MM-DD date string.` - ); - } - try { - const parsed = applyVaultFence( - { from: raw, to: raw, scope: 'vault_evaluation_only' }, - { vaultCutoffTs: 0, vaultOperatorAuthorized: true } - ); - return parsed.fromMs; - } catch (error) { - if (error instanceof MarketDataStoreValidationError) { - throw new FeatureLibraryError( - 'INVALID_BATCH_OPTIONS', - `Invalid "vaultCutoffDate": ${error.message}`, - { cause: error } - ); - } - throw error; - } -} - -function expandSqlForYear( - tokens: readonly SqlToken[], - curatedRoot: string, - tsUpperIso: string, - knownAtUpperIso: string -): { sql: string; scanParams: DuckDbParam[] } { - const scanParams: DuckDbParam[] = []; - const parts: string[] = []; - - for (let i = 0; i < tokens.length; i += 1) { - const tok = tokens[i] as SqlToken; - if (tok.kind === 'placeholder') { - const ds = tok.dataset as FeatureInputDataset; - const spec = DATASET_SCAN_SPECS[ds]; - const fullPath = joinCuratedPath(curatedRoot, spec.relativePath); - const readCall = spec.hivePartitioning - ? `read_parquet('${fullPath}', hive_partitioning = true)` - : `read_parquet('${fullPath}')`; - - if (spec.predicateKind === 'ts_and_known_at') { - parts.push(`(SELECT * FROM ${readCall} WHERE ts <= ? AND known_at <= ?)`); - scanParams.push(tsUpperIso, knownAtUpperIso); - } else if (spec.predicateKind === 'effective_known_at') { - parts.push(`(SELECT * FROM ${readCall} WHERE effective_known_at <= ?)`); - scanParams.push(knownAtUpperIso); - } else { - parts.push(`(SELECT * FROM ${readCall} WHERE known_at <= ?)`); - scanParams.push(knownAtUpperIso); - } - continue; - } - - parts.push(tok.raw); - } - - return { - sql: parts.join(' '), - scanParams, - }; -} - -/** - * Plans ordered yearly Vault-fenced DuckDB `COPY ... TO ... (FORMAT PARQUET, - * COMPRESSION ZSTD)` statements for a validated feature definition. - */ -export function planFeatureBatch( - def: FeatureDefinition, - options: PlanFeatureBatchOptions -): readonly PlannedFeatureWrite[] { - const validated = validateFeatureDefinitionInternal(def); - - if (!isPlainRecord(options)) { - throw new FeatureLibraryError( - 'INVALID_BATCH_OPTIONS', - 'Feature batch options must be a plain object.' - ); - } - - let curatedRoot: string; - try { - curatedRoot = validateCuratedRoot(options.curatedRoot); - } catch (error) { - if (error instanceof MarketDataStoreValidationError) { - throw new FeatureLibraryError('INVALID_BATCH_OPTIONS', error.message, { cause: error }); - } - throw error; - } - - const fromYear = validateFourDigitYear(options.fromYear, 'fromYear'); - const toYear = validateFourDigitYear(options.toYear, 'toYear'); - if (fromYear > toYear) { - throw new FeatureLibraryError( - 'INVALID_BATCH_OPTIONS', - `Invalid year range: fromYear (${fromYear}) must not exceed toYear (${toYear}).` - ); - } - - const cutoffMs = parseVaultCutoffDateMs(options.vaultCutoffDate); - const rangeFrom = `${String(fromYear).padStart(4, '0')}-01-01`; - const rangeTo = `${String(toYear).padStart(4, '0')}-12-31`; - - let fenced; - try { - fenced = applyVaultFence( - { from: rangeFrom, to: rangeTo, scope: 'vault_fenced' }, - { vaultCutoffTs: cutoffMs } - ); - } catch (error) { - if (error instanceof VaultHoldoutFenceError) { - throw new FeatureLibraryError( - 'VAULT_RANGE_VIOLATION', - `Requested year range [${fromYear}, ${toYear}] falls on or after vaultCutoffDate "${options.vaultCutoffDate}".`, - { cause: error } - ); - } - if (error instanceof MarketDataStoreValidationError) { - throw new FeatureLibraryError('INVALID_BATCH_OPTIONS', error.message, { cause: error }); - } - throw error; - } - - const lastPlannedYear = Math.min(toYear, new Date(fenced.toMs).getUTCFullYear()); - if (lastPlannedYear < fromYear) { - throw new FeatureLibraryError( - 'VAULT_RANGE_VIOLATION', - `No pre-cutoff years remain in [${fromYear}, ${toYear}] for vaultCutoffDate "${options.vaultCutoffDate}".` - ); - } - - // Last included Parquet microsecond strictly before vaultCutoffDate (00:00:00.000Z). - const vaultCeilingMs = cutoffMs - 1; - const knownAtUpperIso = formatUtcIsoWithMicros(vaultCeilingMs, 999); - - const writes: PlannedFeatureWrite[] = []; - for (let year = fromYear; year <= lastPlannedYear; year += 1) { - const yearEndMs = Date.UTC(year, 11, 31, 23, 59, 59, 999); - const effectiveTsEndMs = Math.min(yearEndMs, vaultCeilingMs); - const tsUpperIso = formatUtcIsoWithMicros(effectiveTsEndMs, 999); - - const { sql: expandedSql, scanParams } = expandSqlForYear( - validated.tokens, - curatedRoot, - tsUpperIso, - knownAtUpperIso - ); - - const outputPath = joinCuratedPath( - curatedRoot, - `features/${def.name}/v${def.version}/year=${year}/part.parquet` - ); - - const sql = - 'COPY (SELECT listing_id, ts, known_at, value ' + - 'FROM (SELECT CAST(listing_id AS INTEGER) AS listing_id, CAST(ts AS TIMESTAMPTZ) AS ts, CAST(known_at AS TIMESTAMPTZ) AS known_at, CAST(value AS DOUBLE) AS value ' + - `FROM (${expandedSql}) AS __feature_source) AS __feature_typed ` + - 'WHERE year(ts) = ? AND ts <= ? AND known_at <= ? ' + - `ORDER BY listing_id, ts) TO '${outputPath}' (FORMAT PARQUET, COMPRESSION ZSTD)`; - - const params: DuckDbParam[] = [...scanParams, year, tsUpperIso, knownAtUpperIso]; - - writes.push( - Object.freeze({ - year, - outputPath, - sql, - params: Object.freeze(params), - }) - ); - } - - return Object.freeze(writes); -} - -/** - * Validates and plans a feature batch upfront, executes each yearly Parquet - * `COPY` sequentially via `executor.query(sql, params)`, and returns a - * manifest. Stops on the first executor failure and throws - * `FeatureLibraryError('BATCH_WRITE_FAILED')` exposing `cause`, `failedYear`, - * `completedYears`, and `completedWrites`. - */ -export async function runFeatureBatch( - def: FeatureDefinition, - options: PlanFeatureBatchOptions, - executor: DuckDbExecutor -): Promise { - if ( - typeof executor !== 'object' || - executor === null || - typeof (executor as { query?: unknown }).query !== 'function' - ) { - throw new FeatureLibraryError( - 'INVALID_BATCH_OPTIONS', - 'Expected a DuckDbExecutor object with a query(sql, params) method.' - ); - } - - validateFeatureDefinitionInternal(def); - const snapshot = cloneFeatureDefinition(def); - const plannedWrites = planFeatureBatch(snapshot, options); - const ref = featureRef(snapshot); - const definitionHash = featureDefinitionHash(snapshot); - const sortedInputs = [...new Set(snapshot.inputs)].sort(compareAscii); - const { knownAtRule, warmupBars } = snapshot; - - const completedWrites: FeatureBatchWriteReceipt[] = []; - for (let i = 0; i < plannedWrites.length; i += 1) { - const write = plannedWrites[i] as PlannedFeatureWrite; - try { - await executor.query(write.sql, write.params); - } catch (cause) { - const completedYears = completedWrites.map(w => w.year); - throw new FeatureLibraryError( - 'BATCH_WRITE_FAILED', - `Feature batch write failed for "${ref}" on year ${write.year} (completed years: ${completedYears.length > 0 ? completedYears.join(', ') : 'none'}).`, - { - cause, - failedYear: write.year, - completedYears, - completedWrites, - ref, - } - ); - } - completedWrites.push( - Object.freeze({ - year: write.year, - outputPath: write.outputPath, - }) - ); - } - - return Object.freeze({ - ref, - definitionHash, - knownAtRule, - warmupBars, - inputs: Object.freeze(sortedInputs), - writes: Object.freeze(completedWrites), - }); -} - -/** - * Built-in example feature definition (`ret_1d@v1`): 1-day simple raw-close - * return per listing with bar-close availability (`known_at = ts`) and 1-bar - * warm-up. Omits rows without a usable positive prior close. - * - * Comparison baseline: zero return (`0.0`); no execution or transaction cost - * model is included. - */ -export const RET_1D_V1: FeatureDefinition = Object.freeze({ - name: 'ret_1d', - version: 1, - family: 'technical', - kind: 'duckdb_sql', - inputs: Object.freeze(['bars_1d'] as const), - warmupBars: 1, - knownAtRule: 'bar_close', - description: - '1-day simple raw-close return per listing with bar-close availability; comparison baseline is 0 return with no execution or cost model.', - sql: [ - 'WITH lagged AS (', - ' SELECT', - ' listing_id,', - ' ts,', - ' close,', - ' LAG(close) OVER (PARTITION BY listing_id ORDER BY ts ASC) AS prev_close', - ' FROM {{input:bars_1d}}', - ')', - 'SELECT', - ' listing_id,', - ' ts,', - ' ts AS known_at,', - ' (close / prev_close) - 1.0 AS value', - 'FROM lagged', - 'WHERE prev_close IS NOT NULL AND prev_close > 0 AND close > 0', - ].join('\n'), -}); diff --git a/libs/research/src/index.ts b/libs/research/src/index.ts index b2e95446..fd3691a2 100644 --- a/libs/research/src/index.ts +++ b/libs/research/src/index.ts @@ -1,12 +1,5 @@ // The default entrypoint is browser safe; server validation is an explicit subpath. export * from './dataset-contracts'; -export * from './event-panel'; -export * from './feature-library'; export * from './market-data-store'; -export * from './market-data-store-duckdb'; -export * from './market-data-store-questdb'; -export * from './market-data-store-routed'; -export * from './notebook-snapshot'; -export * from './signal-panel'; export * from './signal-study'; export * from './trial-ledger'; diff --git a/libs/research/src/market-data-store-duckdb.ts b/libs/research/src/market-data-store-duckdb.ts deleted file mode 100644 index fd6dd8ae..00000000 --- a/libs/research/src/market-data-store-duckdb.ts +++ /dev/null @@ -1,2305 +0,0 @@ -/** - * Pure, dependency-free DuckDB SQL query planner and injected-executor - * `MarketDataStore` adapter for curated daily Parquet datasets - * (`design/DATA-CONTRACTS.md` §3.A & §4). - * - * Browser-safe and dependency-free: zero `node:*` imports, zero DuckDB driver - * dependency, zero bare `process` access. SQL execution is injected via - * {@link DuckDbExecutor}, mirroring `TrialLedgerExecutor` in `./trial-ledger`. - * - * Curated Parquet layout under `curatedRoot` (`design/DATA-CONTRACTS.md` §3.A): - * - `/bars_1d/year=*\/part.parquet` (`hive_partitioning = true`) - * - `/adj_factors/part.parquet` (point-in-time fenced snapshot with - * `stock_bot.adj_factors.*` Parquet footer metadata) - * - `/events/year=*\/part.parquet` (`hive_partitioning = true`) - * - `/shorts/part.parquet` - * - `/fx_1d/part.parquet` - * - `/fundamentals_pit/year=*\/part.parquet` (`hive_partitioning = true`) - * - * `bars` (`timeframe: '1d'`) adjustment formulas (`tools/curate-etl/README.md`): - * - `bars_1d` stores raw OHLC, optional `vwap`, and split-unadjusted raw share - * `volume`. - * - `adj_factors` stores per-`(listing_id, ex_date)` cumulative back-adjustment - * divisors (`cum_split_factor`, `cum_total_factor`) and `known_at`. - * - For `'raw'`, `open`, `high`, `low`, `close`, `volume`, and `vwap` are - * projected directly from `bars_1d`. - * - For `'split'` and `'total'`, because `cum_split_factor` and - * `cum_total_factor` are right-to-left suffix products, slicing a - * retrospective `adj_factors` file with `known_at <= asOf` would still leak - * future or held-out Vault splits/dividends into earlier cumulative factors. - * Therefore, `'split'` and `'total'` queries REQUIRE a verified - * `point_in_time_fenced` `adj_factors` snapshot artifact (parsed from - * Parquet footer `stock_bot.adj_factors.*` metadata) whose effective - * inclusive fence matches the query's effective `asOf` and Vault cutoff. - * To prevent TOCTOU races when `curate-etl` atomically replaces the mutable - * `/adj_factors/part.parquet` path between footer verification - * and the factor scan, {@link createDuckDbMarketDataStore} pins a single - * artifact version via {@link DuckDbMarketDataStoreOptions.pinAdjFactorsArtifact} - * (stable handle such as `/proc/self/fd/`, `/dev/fd/`, or private - * hardlink/copy) or requires an explicit write-once - * {@link DuckDbMarketDataStoreOptions.immutableAdjFactorsPath} distinct from - * the mutable published path; unpinned mutable paths fail closed with - * {@link AdjFactorsSnapshotError}. - * - Against the verified `adj_factors` file, `bars_1d` is joined via - * `ASOF LEFT JOIN` filtered to `listing_id IN (...) AND known_at <= ?` on - * `b.listing_id = a.listing_id AND b.session_date < a.ex_date` (selecting the - * first `adj_factors` row with `ex_date > session_date`): - * - `'split'`: - * - `price_adj = price_raw / COALESCE(a.cum_split_factor, 1.0)` for - * `open`, `high`, `low`, `close`, and `vwap` (preserving `NULL` `vwap`). - * - `volume_adj = volume_raw * COALESCE(a.cum_split_factor, 1.0)`. - * - `'total'`: - * - `price_adj = price_raw / COALESCE(a.cum_total_factor, 1.0)` for - * `open`, `high`, `low`, `close`, and `vwap` (preserving `NULL` `vwap`). - * - `volume_adj = volume_raw * COALESCE(a.cum_split_factor, 1.0)` (share - * volume scales only by splits, not cash dividends). - * - * Microsecond upper-bound semantics: - * - Curated Parquet `ts` and `known_at` columns are stored as - * `TIMESTAMP(MICROS, isAdjustedToUTC=true)` (for example, `curate_fx_1d` - * stamps `ts = known_at = 23:59:59.999999Z`). - * - Date-only `YYYY-MM-DD` upper bounds (`to`, `asOf`) and default or clamped - * Vault upper bounds expand to the last included Parquet microsecond - * (`.999999Z` / `vaultCutoffTs * 1000 - 1`), while explicit time-of-day - * bounds preserve their caller-specified precision. Under `'vault_fenced'`, - * every planned upper bound remains strictly `< vaultCutoffTs`. - */ - -import { - type BarBatch, - type BarRecord, - type EventKind, - type FencedTimeRange, - type MarketDataStore, - MarketDataStoreValidationError, - type Table, - type TableCell, - type TableRow, - VaultHoldoutFenceError, - applyVaultFence, - resolveDuckDbConnectionBudget, -} from './market-data-store'; - -const INT32_MIN = -2_147_483_648; -const INT32_MAX = 2_147_483_647; -const MAX_ECMASCRIPT_EPOCH_MS = 8_640_000_000_000_000; -const MS_PER_DAY = 86_400_000; -// 0000-01-01T00:00:00.000Z: earliest epoch ms that formats as unsigned YYYY-MM-DD. -const MIN_ISO_DATE_EPOCH_MS = -62_167_219_200_000; -// 9999-12-31T00:00:00.000Z: latest UTC midnight representable as YYYY-MM-DD. -const MAX_ISO_DATE_MIDNIGHT_MS = 253_402_214_400_000; -const DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/; -const ISO_FRACTIONAL_RE = /\.(\d+)(?:Z|[+-]\d{2}:\d{2})$/; -const STRICT_INT_RE = /^-?\d+$/; -const STRICT_UINT_RE = /^\d+$/; -const SNAPSHOT_CHECKSUM_RE = /^0x[0-9a-f]{16}$/; -const FD_HANDLE_PATH_RE = /^\/(?:proc\/self|dev)\/fd\/[1-9]\d*$/; - -export const ADJ_SNAPSHOT_FORMAT_VERSION = 1; -export const ADJ_SNAPSHOT_KV_PREFIX = 'stock_bot.adj_factors.'; - -const KV_FORMAT_VERSION = `${ADJ_SNAPSHOT_KV_PREFIX}format_version`; -const KV_SNAPSHOT_KIND = `${ADJ_SNAPSHOT_KV_PREFIX}snapshot_kind`; -const KV_AS_OF_MICROS = `${ADJ_SNAPSHOT_KV_PREFIX}as_of_micros`; -const KV_VAULT_CUTOFF_MICROS = `${ADJ_SNAPSHOT_KV_PREFIX}vault_cutoff_micros`; -const KV_ROWS_WRITTEN = `${ADJ_SNAPSHOT_KV_PREFIX}rows_written`; -const KV_SNAPSHOT_CHECKSUM = `${ADJ_SNAPSHOT_KV_PREFIX}snapshot_checksum`; - -export const EVENT_KINDS = ['filing', 'earnings', 'ceo_post', 'corporate_action'] as const; -const EVENT_KIND_SET: ReadonlySet = new Set(EVENT_KINDS); - -export const FX_PAIR_MAP = { - 'USD.CAD': 'USDCAD', -} as const; - -export const BARS_ADJUSTMENTS = ['raw', 'split', 'total'] as const; -const BARS_ADJUSTMENT_SET: ReadonlySet = new Set(BARS_ADJUSTMENTS); - -export const UNIVERSE_REFS = ['US_EQ', 'CA_EQ', 'US_CA_EQ'] as const; -export type SupportedUniverseRef = (typeof UNIVERSE_REFS)[number]; -export const DEFAULT_UNIVERSE_LOOKBACK_DAYS = 7; - -const UNIVERSE_CURRENCY_MAP: Readonly> = { - US_EQ: ['USD'], - CA_EQ: ['CAD'], - US_CA_EQ: ['USD', 'CAD'], -}; - -export const EVENTS_COLUMNS = [ - 'listing_id', - 'ts', - 'known_at', - 'known_at_source', - 'kind', - 'subtype', - 'payload_json', -] as const; - -export const SHORTS_COLUMNS = [ - 'listing_id', - 'report_date', - 'known_at', - 'shares_short', - 'net_change', - 'pct_float', - 'source', -] as const; - -export const FX_1D_COLUMNS = [ - 'pair', - 'session_date', - 'ts', - 'open', - 'high', - 'low', - 'close', - 'source', - 'known_at', -] as const; - -export const FUNDAMENTALS_PIT_VALUE_FIELDS = [ - 'revenue', - 'net_income', - 'operating_cash_flow', - 'total_assets', - 'total_equity', - 'shares_outstanding', - 'ttm_revenue', - 'ttm_net_income', - 'ttm_operating_cash_flow', -] as const; -export type FundamentalsPitValueField = (typeof FUNDAMENTALS_PIT_VALUE_FIELDS)[number]; - -const FUNDAMENTALS_PIT_VALUE_FIELD_MAP: ReadonlyMap = new Map( - FUNDAMENTALS_PIT_VALUE_FIELDS.map(field => [field, field]) -); -const FUNDAMENTALS_TTM_VALUE_FIELD_SET: ReadonlySet = new Set([ - 'ttm_revenue', - 'ttm_net_income', - 'ttm_operating_cash_flow', -]); - -type ColumnScalarKind = 'int32' | 'safe_int' | 'number' | 'string' | 'boolean'; - -interface TableColumnSpec { - readonly name: string; - readonly kind: ColumnScalarKind; - readonly nullable: boolean; -} - -const EVENTS_SCHEMA: readonly TableColumnSpec[] = [ - { name: 'listing_id', kind: 'int32', nullable: false }, - { name: 'ts', kind: 'safe_int', nullable: false }, - { name: 'known_at', kind: 'safe_int', nullable: false }, - { name: 'known_at_source', kind: 'string', nullable: false }, - { name: 'kind', kind: 'string', nullable: false }, - { name: 'subtype', kind: 'string', nullable: false }, - { name: 'payload_json', kind: 'string', nullable: false }, -]; - -const SHORTS_SCHEMA: readonly TableColumnSpec[] = [ - { name: 'listing_id', kind: 'int32', nullable: false }, - { name: 'report_date', kind: 'string', nullable: false }, - { name: 'known_at', kind: 'safe_int', nullable: false }, - { name: 'shares_short', kind: 'number', nullable: false }, - { name: 'net_change', kind: 'number', nullable: true }, - { name: 'pct_float', kind: 'number', nullable: true }, - { name: 'source', kind: 'string', nullable: false }, -]; - -const FX_1D_SCHEMA: readonly TableColumnSpec[] = [ - { name: 'pair', kind: 'string', nullable: false }, - { name: 'session_date', kind: 'string', nullable: false }, - { name: 'ts', kind: 'safe_int', nullable: false }, - { name: 'open', kind: 'number', nullable: false }, - { name: 'high', kind: 'number', nullable: false }, - { name: 'low', kind: 'number', nullable: false }, - { name: 'close', kind: 'number', nullable: false }, - { name: 'source', kind: 'string', nullable: false }, - { name: 'known_at', kind: 'safe_int', nullable: false }, -]; - -const FUNDAMENTALS_BASE_SCHEMA: readonly TableColumnSpec[] = [ - { name: 'listing_id', kind: 'int32', nullable: false }, - { name: 'effective_known_at', kind: 'safe_int', nullable: false }, - { name: 'known_at_source', kind: 'string', nullable: false }, - { name: 'has_estimated_lag', kind: 'boolean', nullable: false }, - { name: 'period_end', kind: 'string', nullable: false }, - { name: 'fiscal_period', kind: 'string', nullable: false }, - { name: 'currency', kind: 'string', nullable: false }, - { name: 'period_known_at', kind: 'safe_int', nullable: false }, -]; - -const FUNDAMENTALS_TTM_META_SCHEMA: readonly TableColumnSpec[] = [ - { name: 'ttm_period_end', kind: 'string', nullable: true }, - { name: 'ttm_currency', kind: 'string', nullable: true }, - { name: 'ttm_has_estimated_lag', kind: 'boolean', nullable: true }, -]; - -/** Scalar parameter value bound separately from SQL text. */ -export type DuckDbParam = string | number | boolean | null; - -/** - * Injected DuckDB SQL executor interface. Parameter values are always passed - * separately from SQL text via `params`. - */ -export interface DuckDbExecutor { - run(sql: string): Promise; - query(sql: string, params: readonly DuckDbParam[]): Promise; -} - -/** Pure output of a DuckDB query planner. */ -export interface PlannedDuckDbQuery { - readonly sql: string; - readonly params: readonly DuckDbParam[]; - readonly fenced: FencedTimeRange; -} - -/** Snapshot classification written by `tools/curate-etl` into `adj_factors/part.parquet`. */ -export type AdjFactorsSnapshotKind = 'retrospective' | 'point_in_time_fenced'; - -/** Point-in-time and Vault fence embedded in `adj_factors/part.parquet` footer metadata. */ -export interface AdjFactorsPointInTimeFence { - readonly asOfMicros: number | null; - readonly vaultCutoffMicros: number | null; -} - -/** - * Verified `adj_factors` Parquet footer metadata parsed via - * {@link parseAdjFactorsSnapshotMetadata}, bound to a concrete `.parquet` file - * path. - */ -export interface AdjFactorsSnapshotMetadata { - readonly path: string; - readonly formatVersion: number; - readonly snapshotKind: AdjFactorsSnapshotKind; - readonly fence: AdjFactorsPointInTimeFence; - readonly rowsWritten: number; - readonly snapshotChecksum: string; -} - -/** Pure output of {@link planAdjFactorsMetadataQuery}. */ -export interface PlannedAdjFactorsMetadataQuery { - readonly path: string; - readonly sql: string; - readonly params: readonly DuckDbParam[]; -} - -export type AdjFactorsSnapshotErrorCode = - | 'missing_snapshot' - | 'missing_metadata' - | 'invalid_metadata' - | 'unsupported_version' - | 'retrospective_rejected' - | 'incompatible_fence' - | 'path_mismatch' - | 'unpinned_mutable_path'; - -/** - * Thrown when an adjusted `bars` (`'split'` or `'total'`) query lacks a - * verified `point_in_time_fenced` `adj_factors` snapshot artifact matching the - * query's effective `asOf` and Vault fence, or when Parquet footer metadata is - * missing, retrospective, malformed, or mismatched. - */ -export class AdjFactorsSnapshotError extends Error { - override readonly name = 'AdjFactorsSnapshotError'; - readonly code: AdjFactorsSnapshotErrorCode; - readonly path?: string; - - constructor(code: AdjFactorsSnapshotErrorCode, message: string, path?: string) { - super(message); - this.code = code; - this.path = path; - Object.setPrototypeOf(this, new.target.prototype); - } -} - -/** Context required to plan fenced DuckDB queries against curated Parquet. */ -export interface DuckDbPlanContext { - readonly curatedRoot: string; - readonly vaultCutoffTs: number; - readonly vaultOperatorAuthorized?: boolean; - /** - * Optional calendar-day lookback window for {@link planUniverseQuery} - * (`[date - universeLookbackDays, date]`). Defaults to - * {@link DEFAULT_UNIVERSE_LOOKBACK_DAYS} (`7`). - */ - readonly universeLookbackDays?: number; - /** - * Verified `adj_factors` snapshot metadata bound to the `.parquet` file to - * be read. Required for `'split'` and `'total'` `bars` queries; rejected if - * retrospective or mismatched for the query's effective `asOf` / Vault fence. - */ - readonly adjFactorsSnapshot?: AdjFactorsSnapshotMetadata; -} - -/** - * Handle returned by {@link AdjFactorsArtifactPinner} pinning a single - * `adj_factors` Parquet artifact version (e.g. an open `/proc/self/fd/`, - * `/dev/fd/`, a private hardlink, or a staged copy) across both footer - * verification (`parquet_kv_metadata`) and the `bars` factor scan - * (`read_parquet`). - */ -export interface PinnedAdjFactorsArtifact { - /** - * Stable path referencing the single pinned artifact version (an absolute - * POSIX `.parquet` path distinct from the mutable published path, or a - * `/proc/self/fd/` / `/dev/fd/` handle path). - */ - readonly pinnedPath: string; - /** - * Releases the pinned handle or temporary link/copy once the query finishes - * or fails. Always invoked in a `finally` block. - */ - release(): Promise | void; -} - -/** - * Pins a mutable `adj_factors` Parquet source path to a stable file handle or - * immutable copy before footer verification so concurrent ETL atomic renames - * cannot swap the file between `parquet_kv_metadata(...)` and - * `read_parquet(...)`. - */ -export type AdjFactorsArtifactPinner = ( - sourcePath: string -) => Promise | PinnedAdjFactorsArtifact; - -/** Configuration for {@link createDuckDbMarketDataStore}. */ -export interface DuckDbMarketDataStoreOptions - extends Omit { - readonly executor: DuckDbExecutor; - readonly env?: Readonly>; - readonly barBatchSize?: number; - /** - * Optional absolute POSIX `.parquet` source path for `adj_factors` reads when - * using {@link pinAdjFactorsArtifact}. Defaults to - * `/adj_factors/part.parquet`. Mutually exclusive with - * {@link immutableAdjFactorsPath}. - */ - readonly adjFactorsPath?: string; - /** - * Optional pinning hook that binds the mutable `adj_factors` source path to a - * stable file handle (`/proc/self/fd/`, `/dev/fd/`) or private - * hardlink/copy `.parquet` path distinct from the mutable path across both - * footer verification and the factor scan. - */ - readonly pinAdjFactorsArtifact?: AdjFactorsArtifactPinner; - /** - * Optional absolute POSIX `.parquet` path to a write-once immutable - * `adj_factors` snapshot artifact (must NOT be the mutable published - * `/adj_factors/part.parquet` path). Mutually exclusive with - * {@link adjFactorsPath}. - */ - readonly immutableAdjFactorsPath?: string; -} - -export type BarsQuery = Parameters[0]; -export type EventsQuery = Parameters[0]; -export type ShortsAsOfQuery = Parameters[0]; -export type FxQuery = Parameters[0]; -export type UniverseQuery = Parameters[0]; -export type FundamentalsAsOfQuery = Parameters[0]; - -/** - * Thrown when a `MarketDataStore` method or timeframe is outside the curated - * daily DuckDB Parquet adapter slice. - */ -export class MarketDataStoreNotImplementedError extends Error { - override readonly name = 'MarketDataStoreNotImplementedError'; - readonly method: keyof MarketDataStore; - readonly detail?: string; - - constructor(method: keyof MarketDataStore, detail?: string) { - super( - detail !== undefined - ? `MarketDataStore.${method} is not implemented by the DuckDB daily Parquet adapter: ${detail}` - : `MarketDataStore.${method} is not implemented by the DuckDB daily Parquet adapter.` - ); - this.method = method; - this.detail = detail; - Object.setPrototypeOf(this, new.target.prototype); - } -} - -function isPlainRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value); -} - -function hasForbiddenCuratedRootChar(value: string): boolean { - for (let i = 0; i < value.length; i += 1) { - const code = value.charCodeAt(i); - // Reject ASCII control chars (0x00..0x1f, 0x7f), SQL quote/separator (', ;), - // and DuckDB read_parquet glob metacharacters (*, ?, [, ]). - if ( - code <= 0x1f || - code === 0x7f || - code === 0x27 || - code === 0x3b || - code === 0x2a || - code === 0x3f || - code === 0x5b || - code === 0x5d - ) { - return true; - } - } - return false; -} - -/** - * Strictly validates `curatedRoot` as an absolute POSIX path with no control - * characters, single quotes, semicolons, or glob metacharacters, normalizing - * trailing slashes (except `'/'`). - */ -export function validateCuratedRoot(raw: string): string { - if ( - typeof raw !== 'string' || - raw.length === 0 || - !raw.startsWith('/') || - hasForbiddenCuratedRootChar(raw) - ) { - throw new MarketDataStoreValidationError( - `Invalid curatedRoot "${String(raw)}". Expected a non-empty absolute POSIX path without quotes, semicolons, control characters, or glob characters (*, ?, [, ]).`, - 'curatedRoot' - ); - } - - let end = raw.length; - while (end > 1 && raw.charCodeAt(end - 1) === 0x2f) { - end -= 1; - } - return end === raw.length ? raw : raw.slice(0, end); -} - -/** - * Strictly validates a concrete Parquet file path (absolute POSIX `.parquet` - * path with no control characters, quotes, semicolons, or glob metacharacters). - */ -export function validateParquetFilePath(raw: string, field = 'adjFactorsPath'): string { - if ( - typeof raw !== 'string' || - raw.length === 0 || - !raw.startsWith('/') || - !raw.endsWith('.parquet') || - hasForbiddenCuratedRootChar(raw) - ) { - throw new MarketDataStoreValidationError( - `Invalid Parquet file path "${String(raw)}" for "${field}". Expected an absolute POSIX .parquet path without quotes, semicolons, control characters, or glob characters (*, ?, [, ]).`, - field - ); - } - return raw; -} - -/** - * Strictly validates an `adj_factors` artifact path accepted by DuckDB - * `parquet_kv_metadata(...)` and `read_parquet(...)`: either an absolute POSIX - * `.parquet` path or a pinned file-descriptor handle path - * (`/proc/self/fd/` or `/dev/fd/`). - */ -export function validateAdjFactorsArtifactPath(raw: string, field = 'adjFactorsPath'): string { - if ( - typeof raw !== 'string' || - raw.length === 0 || - !raw.startsWith('/') || - hasForbiddenCuratedRootChar(raw) || - (!raw.endsWith('.parquet') && !FD_HANDLE_PATH_RE.test(raw)) - ) { - throw new MarketDataStoreValidationError( - `Invalid adj_factors artifact path "${String(raw)}" for "${field}". Expected an absolute POSIX .parquet path or pinned /proc/self/fd/ (/dev/fd/) handle without quotes, semicolons, control characters, or glob characters (*, ?, [, ]).`, - field - ); - } - return raw; -} - -function canonicalizePosixPath(path: string): string { - const parts = path.split('/'); - const stack: string[] = []; - for (let i = 0; i < parts.length; i += 1) { - const part = parts[i]; - if (part === undefined || part === '' || part === '.') { - continue; - } - if (part === '..') { - stack.pop(); - continue; - } - stack.push(part); - } - return `/${stack.join('/')}`; -} - -function joinCuratedPath(normalizedRoot: string, relativePath: string): string { - return normalizedRoot === '/' ? `/${relativePath}` : `${normalizedRoot}/${relativePath}`; -} - -function validateListingIds(raw: readonly number[], field = 'listingIds'): number[] { - if (!Array.isArray(raw) || raw.length === 0) { - throw new MarketDataStoreValidationError( - `Expected a non-empty array of INT32 listing IDs for "${field}".`, - field - ); - } - - if (raw.length === 1) { - const id = raw[0]; - if ( - typeof id !== 'number' || - !Number.isSafeInteger(id) || - id < INT32_MIN || - id > INT32_MAX - ) { - throw new MarketDataStoreValidationError( - `Invalid INT32 listing ID at ${field}[0]: ${String(id)}.`, - field - ); - } - return [id === 0 ? 0 : id]; - } - - const seen = new Set(); - const normalized: number[] = []; - for (let i = 0; i < raw.length; i += 1) { - const id = raw[i]; - if ( - typeof id !== 'number' || - !Number.isSafeInteger(id) || - id < INT32_MIN || - id > INT32_MAX - ) { - throw new MarketDataStoreValidationError( - `Invalid INT32 listing ID at ${field}[${i}]: ${String(id)}.`, - field - ); - } - const clean = id === 0 ? 0 : id; - if (!seen.has(clean)) { - seen.add(clean); - normalized.push(clean); - } - } - return normalized; -} - -function validateEventKinds(raw: readonly EventKind[], field = 'kinds'): EventKind[] { - if (!Array.isArray(raw) || raw.length === 0) { - throw new MarketDataStoreValidationError( - `Expected a non-empty array of EventKind values for "${field}".`, - field - ); - } - - if (raw.length === 1) { - const kind = raw[0]; - if (typeof kind !== 'string' || !EVENT_KIND_SET.has(kind)) { - throw new MarketDataStoreValidationError( - `Unknown EventKind "${String(kind)}". Expected one of: ${EVENT_KINDS.join(', ')}.`, - field - ); - } - return [kind as EventKind]; - } - - const seen = new Set(); - const normalized: EventKind[] = []; - for (let i = 0; i < raw.length; i += 1) { - const kind = raw[i]; - if (typeof kind !== 'string' || !EVENT_KIND_SET.has(kind)) { - throw new MarketDataStoreValidationError( - `Unknown EventKind "${String(kind)}". Expected one of: ${EVENT_KINDS.join(', ')}.`, - field - ); - } - if (!seen.has(kind)) { - seen.add(kind); - normalized.push(kind as EventKind); - } - } - return normalized; -} - -function validateFundamentalsFields( - raw: readonly string[], - field = 'fields' -): FundamentalsPitValueField[] { - if (!Array.isArray(raw) || raw.length === 0) { - throw new MarketDataStoreValidationError( - `Expected a non-empty array of fundamentals value fields for "${field}".`, - field - ); - } - - const seen = new Set(); - const normalized: FundamentalsPitValueField[] = []; - for (let i = 0; i < raw.length; i += 1) { - const name: unknown = raw[i]; - const canonical = - typeof name === 'string' ? FUNDAMENTALS_PIT_VALUE_FIELD_MAP.get(name) : undefined; - if (canonical === undefined) { - throw new MarketDataStoreValidationError( - `Unknown fundamentals field "${String(name)}". Expected one of: ${FUNDAMENTALS_PIT_VALUE_FIELDS.join(', ')}.`, - field - ); - } - if (!seen.has(canonical)) { - seen.add(canonical); - normalized.push(canonical); - } - } - return normalized; -} - -function validateAllowEstimatedLag(raw: unknown): boolean { - if (raw === undefined) { - return true; - } - if (typeof raw !== 'boolean') { - throw new MarketDataStoreValidationError( - `Invalid allowEstimatedLag "${String(raw)}". Expected a boolean.`, - 'allowEstimatedLag' - ); - } - return raw; -} - -function validateAdjustment(raw: unknown): (typeof BARS_ADJUSTMENTS)[number] { - if (typeof raw !== 'string' || !BARS_ADJUSTMENT_SET.has(raw)) { - throw new MarketDataStoreValidationError( - `Invalid adjustment "${String(raw)}". Expected one of: ${BARS_ADJUSTMENTS.join(', ')}.`, - 'adjustment' - ); - } - return raw as (typeof BARS_ADJUSTMENTS)[number]; -} - -function validateFxPair(raw: unknown): (typeof FX_PAIR_MAP)[keyof typeof FX_PAIR_MAP] { - if (typeof raw === 'string' && Object.prototype.hasOwnProperty.call(FX_PAIR_MAP, raw)) { - return FX_PAIR_MAP[raw as keyof typeof FX_PAIR_MAP]; - } - throw new MarketDataStoreValidationError( - `Unsupported FX pair "${String(raw)}". Expected 'USD.CAD'.`, - 'pair' - ); -} - -function validateUniverseRef(raw: unknown): readonly string[] { - if (typeof raw === 'string' && Object.prototype.hasOwnProperty.call(UNIVERSE_CURRENCY_MAP, raw)) { - return UNIVERSE_CURRENCY_MAP[raw as SupportedUniverseRef]; - } - throw new MarketDataStoreValidationError( - `Unsupported universe ref "${String(raw)}". Expected one of: ${UNIVERSE_REFS.join(', ')}.`, - 'ref' - ); -} - -function validateUniverseLookbackDays(raw: unknown, vaultCutoffTs?: number): number { - const days = raw === undefined ? DEFAULT_UNIVERSE_LOOKBACK_DAYS : raw; - if (typeof days !== 'number' || !Number.isSafeInteger(days) || days < 1) { - throw new MarketDataStoreValidationError( - `Invalid universeLookbackDays "${String(raw)}". Expected a positive safe integer.`, - 'universeLookbackDays' - ); - } - - const lookbackMs = days * MS_PER_DAY; - if ( - !Number.isSafeInteger(lookbackMs) || - MAX_ISO_DATE_MIDNIGHT_MS - lookbackMs < MIN_ISO_DATE_EPOCH_MS - ) { - throw new MarketDataStoreValidationError( - `Invalid universeLookbackDays "${days}". Lookback window exceeds supported YYYY-MM-DD UTC date range.`, - 'universeLookbackDays' - ); - } - - if (vaultCutoffTs !== undefined) { - const latestPermittedDateMs = - Math.floor(Math.min(vaultCutoffTs - 1, MAX_ISO_DATE_MIDNIGHT_MS) / MS_PER_DAY) * MS_PER_DAY; - const latestLookbackStartMs = latestPermittedDateMs - lookbackMs; - if ( - !Number.isSafeInteger(latestLookbackStartMs) || - latestLookbackStartMs < MIN_ISO_DATE_EPOCH_MS - ) { - throw new MarketDataStoreValidationError( - `Invalid universeLookbackDays "${days}". Lookback window exceeds supported YYYY-MM-DD UTC date range for vaultCutoffTs.`, - 'universeLookbackDays' - ); - } - } - - return days; -} - -function validateContext(ctx: DuckDbPlanContext): string { - if (!isPlainRecord(ctx)) { - throw new MarketDataStoreValidationError('Expected a DuckDbPlanContext object.', 'context'); - } - return validateCuratedRoot(ctx.curatedRoot); -} - -function buildPlaceholders(count: number): string { - if (count === 1) { - return '?'; - } - if (count === 2) { - return '?, ?'; - } - if (count === 3) { - return '?, ?, ?'; - } - let out = '?'; - for (let i = 1; i < count; i += 1) { - out += ', ?'; - } - return out; -} - -function extractExplicitSubMsMicros(raw: string): number { - const match = ISO_FRACTIONAL_RE.exec(raw); - if (match === null) { - return 0; - } - const frac = match[1] ?? ''; - if (frac.length <= 3) { - return 0; - } - const microDigits = frac.slice(3, 6).padEnd(3, '0'); - return Number(microDigits); -} - -function resolveFromSubMsMicros(rawFrom: string): number { - if (DATE_ONLY_RE.test(rawFrom)) { - return 0; - } - return extractExplicitSubMsMicros(rawFrom); -} - -function resolveToSubMsMicros(rawTo: string, fenced: FencedTimeRange): number { - if (fenced.clampedTo || DATE_ONLY_RE.test(rawTo)) { - return 999; - } - return extractExplicitSubMsMicros(rawTo); -} - -function resolveAsOfSubMsMicros( - rawAsOf: string | undefined, - rawTo: string, - fenced: FencedTimeRange -): number { - if (fenced.clampedAsOf) { - return 999; - } - if (rawAsOf === undefined) { - if (fenced.scope === 'vault_fenced') { - return 999; - } - return resolveToSubMsMicros(rawTo, fenced); - } - if (DATE_ONLY_RE.test(rawAsOf)) { - return 999; - } - return extractExplicitSubMsMicros(rawAsOf); -} - -function formatUtcIsoWithMicros(epochMs: number, subMsMicros: number): string { - const isoMs = new Date(epochMs).toISOString(); - if (subMsMicros === 0) { - return isoMs; - } - const extra = String(subMsMicros).padStart(3, '0'); - return `${isoMs.slice(0, -1)}${extra}Z`; -} - -function formatUtcDate(epochMs: number): string { - return new Date(epochMs).toISOString().slice(0, 10); -} - -function toEpochMicros(epochMs: number, subMsMicros: number, field: string): number { - const micros = epochMs * 1000 + subMsMicros; - if (!Number.isSafeInteger(micros)) { - throw new MarketDataStoreValidationError( - `Timestamp for "${field}" exceeds safe microsecond integer precision.`, - field - ); - } - return micros === 0 ? 0 : micros; -} - -function parseOptionalMicrosKv(value: string, key: string, path: string): number | null { - if (value === 'none') { - return null; - } - if (!STRICT_INT_RE.test(value)) { - throw new AdjFactorsSnapshotError( - 'invalid_metadata', - `Invalid microsecond integer value "${value}" for "${key}" in "${path}".`, - path - ); - } - const parsed = Number(value); - if (!Number.isSafeInteger(parsed)) { - throw new AdjFactorsSnapshotError( - 'invalid_metadata', - `Out-of-range microsecond integer value "${value}" for "${key}" in "${path}".`, - path - ); - } - return parsed === 0 ? 0 : parsed; -} - -/** - * Plans the DuckDB `parquet_kv_metadata` query that reads - * `stock_bot.adj_factors.*` footer metadata from a concrete `adj_factors` - * Parquet file. - */ -export function planAdjFactorsMetadataQuery(adjPath: string): PlannedAdjFactorsMetadataQuery { - const validPath = validateAdjFactorsArtifactPath(adjPath, 'adjFactorsPath'); - const sql = - 'SELECT decode(key) AS key, decode(value) AS value ' + - `FROM parquet_kv_metadata('${validPath}') ` + - 'WHERE decode(key) LIKE ?'; - return { - path: validPath, - sql, - params: [`${ADJ_SNAPSHOT_KV_PREFIX}%`], - }; -} - -/** - * Parses and strictly validates `stock_bot.adj_factors.*` Parquet footer - * key-value metadata rows (matching `tools/curate-etl/src/curate_adj.rs`) - * and binds the resulting metadata object to `adjPath`. - */ -export function parseAdjFactorsSnapshotMetadata( - adjPath: string, - kvRows: readonly TableRow[] -): AdjFactorsSnapshotMetadata { - const validPath = validateAdjFactorsArtifactPath(adjPath, 'adjFactorsPath'); - if (!Array.isArray(kvRows)) { - throw new AdjFactorsSnapshotError( - 'invalid_metadata', - `Expected an array of Parquet metadata rows for "${validPath}".`, - validPath - ); - } - - let foundAny = false; - let formatVersion: number | undefined; - let snapshotKindStr: string | undefined; - let asOfMicros: number | null | undefined; - let vaultCutoffMicros: number | null | undefined; - let rowsWritten: number | undefined; - let snapshotChecksum: string | undefined; - - for (let i = 0; i < kvRows.length; i += 1) { - const row = kvRows[i]; - if (!isPlainRecord(row) || typeof row.key !== 'string') { - throw new AdjFactorsSnapshotError( - 'invalid_metadata', - `Malformed Parquet metadata row at index ${i} for "${validPath}".`, - validPath - ); - } - const key = row.key; - if (!key.startsWith(ADJ_SNAPSHOT_KV_PREFIX)) { - continue; - } - foundAny = true; - const rawVal = row.value; - if (typeof rawVal !== 'string') { - throw new AdjFactorsSnapshotError( - 'invalid_metadata', - `Missing or non-string value for metadata key "${key}" in "${validPath}".`, - validPath - ); - } - - switch (key) { - case KV_FORMAT_VERSION: { - if (formatVersion !== undefined) { - throw new AdjFactorsSnapshotError( - 'invalid_metadata', - `Duplicate metadata key "${KV_FORMAT_VERSION}" in "${validPath}".`, - validPath - ); - } - if (!STRICT_UINT_RE.test(rawVal)) { - throw new AdjFactorsSnapshotError( - 'invalid_metadata', - `Invalid "${KV_FORMAT_VERSION}" value "${rawVal}" in "${validPath}".`, - validPath - ); - } - const parsed = Number(rawVal); - if (!Number.isSafeInteger(parsed)) { - throw new AdjFactorsSnapshotError( - 'invalid_metadata', - `Out-of-range "${KV_FORMAT_VERSION}" value "${rawVal}" in "${validPath}".`, - validPath - ); - } - formatVersion = parsed; - break; - } - case KV_SNAPSHOT_KIND: { - if (snapshotKindStr !== undefined) { - throw new AdjFactorsSnapshotError( - 'invalid_metadata', - `Duplicate metadata key "${KV_SNAPSHOT_KIND}" in "${validPath}".`, - validPath - ); - } - snapshotKindStr = rawVal; - break; - } - case KV_AS_OF_MICROS: { - if (asOfMicros !== undefined) { - throw new AdjFactorsSnapshotError( - 'invalid_metadata', - `Duplicate metadata key "${KV_AS_OF_MICROS}" in "${validPath}".`, - validPath - ); - } - asOfMicros = parseOptionalMicrosKv(rawVal, KV_AS_OF_MICROS, validPath); - break; - } - case KV_VAULT_CUTOFF_MICROS: { - if (vaultCutoffMicros !== undefined) { - throw new AdjFactorsSnapshotError( - 'invalid_metadata', - `Duplicate metadata key "${KV_VAULT_CUTOFF_MICROS}" in "${validPath}".`, - validPath - ); - } - vaultCutoffMicros = parseOptionalMicrosKv(rawVal, KV_VAULT_CUTOFF_MICROS, validPath); - break; - } - case KV_ROWS_WRITTEN: { - if (rowsWritten !== undefined) { - throw new AdjFactorsSnapshotError( - 'invalid_metadata', - `Duplicate metadata key "${KV_ROWS_WRITTEN}" in "${validPath}".`, - validPath - ); - } - if (!STRICT_UINT_RE.test(rawVal)) { - throw new AdjFactorsSnapshotError( - 'invalid_metadata', - `Invalid "${KV_ROWS_WRITTEN}" value "${rawVal}" in "${validPath}".`, - validPath - ); - } - const parsed = Number(rawVal); - if (!Number.isSafeInteger(parsed)) { - throw new AdjFactorsSnapshotError( - 'invalid_metadata', - `Out-of-range "${KV_ROWS_WRITTEN}" value "${rawVal}" in "${validPath}".`, - validPath - ); - } - rowsWritten = parsed; - break; - } - case KV_SNAPSHOT_CHECKSUM: { - if (snapshotChecksum !== undefined) { - throw new AdjFactorsSnapshotError( - 'invalid_metadata', - `Duplicate metadata key "${KV_SNAPSHOT_CHECKSUM}" in "${validPath}".`, - validPath - ); - } - if (!SNAPSHOT_CHECKSUM_RE.test(rawVal)) { - throw new AdjFactorsSnapshotError( - 'invalid_metadata', - `Invalid "${KV_SNAPSHOT_CHECKSUM}" value "${rawVal}" in "${validPath}". Expected 0x followed by 16 lowercase hex digits.`, - validPath - ); - } - snapshotChecksum = rawVal; - break; - } - default: - throw new AdjFactorsSnapshotError( - 'invalid_metadata', - `Unknown metadata key "${key}" in "${validPath}".`, - validPath - ); - } - } - - if (!foundAny) { - throw new AdjFactorsSnapshotError( - 'missing_metadata', - `Missing "${ADJ_SNAPSHOT_KV_PREFIX}*" metadata in Parquet footer at "${validPath}" (refusing to read unverified adj_factors Parquet).`, - validPath - ); - } - - if (formatVersion === undefined) { - throw new AdjFactorsSnapshotError( - 'invalid_metadata', - `Missing "${KV_FORMAT_VERSION}" in "${validPath}".`, - validPath - ); - } - if (formatVersion !== ADJ_SNAPSHOT_FORMAT_VERSION) { - throw new AdjFactorsSnapshotError( - 'unsupported_version', - `Unsupported adj_factors snapshot metadata version ${formatVersion} at "${validPath}" (supported: ${ADJ_SNAPSHOT_FORMAT_VERSION}).`, - validPath - ); - } - if (snapshotKindStr === undefined) { - throw new AdjFactorsSnapshotError( - 'invalid_metadata', - `Missing "${KV_SNAPSHOT_KIND}" in "${validPath}".`, - validPath - ); - } - if (asOfMicros === undefined) { - throw new AdjFactorsSnapshotError( - 'invalid_metadata', - `Missing "${KV_AS_OF_MICROS}" in "${validPath}".`, - validPath - ); - } - if (vaultCutoffMicros === undefined) { - throw new AdjFactorsSnapshotError( - 'invalid_metadata', - `Missing "${KV_VAULT_CUTOFF_MICROS}" in "${validPath}".`, - validPath - ); - } - if (rowsWritten === undefined) { - throw new AdjFactorsSnapshotError( - 'invalid_metadata', - `Missing "${KV_ROWS_WRITTEN}" in "${validPath}".`, - validPath - ); - } - if (snapshotChecksum === undefined) { - throw new AdjFactorsSnapshotError( - 'invalid_metadata', - `Missing "${KV_SNAPSHOT_CHECKSUM}" in "${validPath}".`, - validPath - ); - } - - let snapshotKind: AdjFactorsSnapshotKind; - if (snapshotKindStr === 'retrospective') { - if (asOfMicros !== null || vaultCutoffMicros !== null) { - throw new AdjFactorsSnapshotError( - 'invalid_metadata', - `Retrospective adj_factors snapshot at "${validPath}" must have 'none' for as_of_micros and vault_cutoff_micros.`, - validPath - ); - } - snapshotKind = 'retrospective'; - } else if (snapshotKindStr === 'point_in_time_fenced') { - if (asOfMicros === null && vaultCutoffMicros === null) { - throw new AdjFactorsSnapshotError( - 'invalid_metadata', - `Fenced adj_factors snapshot at "${validPath}" must specify at least one of as_of_micros or vault_cutoff_micros.`, - validPath - ); - } - snapshotKind = 'point_in_time_fenced'; - } else { - throw new AdjFactorsSnapshotError( - 'invalid_metadata', - `Unknown "${KV_SNAPSHOT_KIND}" value "${snapshotKindStr}" in "${validPath}".`, - validPath - ); - } - - return { - path: validPath, - formatVersion, - snapshotKind, - fence: { - asOfMicros, - vaultCutoffMicros, - }, - rowsWritten, - snapshotChecksum, - }; -} - -function effectiveSnapshotCeilingMicros(fence: AdjFactorsPointInTimeFence): number { - const asOfCeiling = fence.asOfMicros; - const vaultCeiling = fence.vaultCutoffMicros !== null ? fence.vaultCutoffMicros - 1 : null; - if (asOfCeiling !== null && vaultCeiling !== null) { - return Math.min(asOfCeiling, vaultCeiling); - } - if (asOfCeiling !== null) { - return asOfCeiling; - } - if (vaultCeiling !== null) { - return vaultCeiling; - } - throw new AdjFactorsSnapshotError( - 'invalid_metadata', - 'Fenced adj_factors snapshot must carry at least one non-null fence bound.' - ); -} - -/** - * Verifies that `snapshot` is a well-formed, `point_in_time_fenced` - * `adj_factors` artifact whose effective inclusive microsecond ceiling matches - * the query's effective `asOf` and Vault fence, returning its validated - * `.parquet` path so the SQL planner binds `read_parquet(...)` directly to the - * verified file. - */ -function verifyAdjFactorsSnapshotForQuery( - snapshot: AdjFactorsSnapshotMetadata | undefined, - requiredAsOfMicros: number, - requiredVaultCutoffMicros: number | null -): string { - if (snapshot === undefined) { - throw new AdjFactorsSnapshotError( - 'missing_snapshot', - 'Adjusted bars queries ("split" / "total") require a verified point_in_time_fenced adj_factors snapshot matching the query asOf and Vault fence.' - ); - } - if (!isPlainRecord(snapshot)) { - throw new AdjFactorsSnapshotError( - 'invalid_metadata', - 'Expected an AdjFactorsSnapshotMetadata object for adjFactorsSnapshot.' - ); - } - - const validPath = validateAdjFactorsArtifactPath(snapshot.path, 'adjFactorsSnapshot.path'); - - if ( - typeof snapshot.formatVersion !== 'number' || - !Number.isSafeInteger(snapshot.formatVersion) - ) { - throw new AdjFactorsSnapshotError( - 'invalid_metadata', - `Invalid adj_factors snapshot formatVersion "${String(snapshot.formatVersion)}" at "${validPath}".`, - validPath - ); - } - if (snapshot.formatVersion !== ADJ_SNAPSHOT_FORMAT_VERSION) { - throw new AdjFactorsSnapshotError( - 'unsupported_version', - `Unsupported adj_factors snapshot version ${snapshot.formatVersion} at "${validPath}" (supported: ${ADJ_SNAPSHOT_FORMAT_VERSION}).`, - validPath - ); - } - if ( - typeof snapshot.rowsWritten !== 'number' || - !Number.isSafeInteger(snapshot.rowsWritten) || - snapshot.rowsWritten < 0 - ) { - throw new AdjFactorsSnapshotError( - 'invalid_metadata', - `Invalid adj_factors snapshot rowsWritten "${String(snapshot.rowsWritten)}" at "${validPath}".`, - validPath - ); - } - if ( - typeof snapshot.snapshotChecksum !== 'string' || - !SNAPSHOT_CHECKSUM_RE.test(snapshot.snapshotChecksum) - ) { - throw new AdjFactorsSnapshotError( - 'invalid_metadata', - `Invalid adj_factors snapshotChecksum "${String(snapshot.snapshotChecksum)}" at "${validPath}".`, - validPath - ); - } - - if (snapshot.snapshotKind === 'retrospective') { - throw new AdjFactorsSnapshotError( - 'retrospective_rejected', - `Refusing retrospective adj_factors snapshot at "${validPath}" for point-in-time adjusted bars query (cumulative factors may embed post-asOf or held-out Vault actions).`, - validPath - ); - } - if (snapshot.snapshotKind !== 'point_in_time_fenced') { - throw new AdjFactorsSnapshotError( - 'invalid_metadata', - `Unknown adj_factors snapshotKind "${String(snapshot.snapshotKind)}" at "${validPath}".`, - validPath - ); - } - - if (!isPlainRecord(snapshot.fence)) { - throw new AdjFactorsSnapshotError( - 'invalid_metadata', - `Missing fence object in adj_factors snapshot metadata at "${validPath}".`, - validPath - ); - } - const { asOfMicros, vaultCutoffMicros } = snapshot.fence; - if ( - (asOfMicros !== null && (typeof asOfMicros !== 'number' || !Number.isSafeInteger(asOfMicros))) || - (vaultCutoffMicros !== null && - (typeof vaultCutoffMicros !== 'number' || !Number.isSafeInteger(vaultCutoffMicros))) - ) { - throw new AdjFactorsSnapshotError( - 'invalid_metadata', - `Invalid microsecond fence bounds in adj_factors snapshot metadata at "${validPath}".`, - validPath - ); - } - if (asOfMicros === null && vaultCutoffMicros === null) { - throw new AdjFactorsSnapshotError( - 'invalid_metadata', - `Fenced adj_factors snapshot at "${validPath}" has no non-null fence bounds.`, - validPath - ); - } - - const actualCeiling = effectiveSnapshotCeilingMicros(snapshot.fence); - if ( - requiredVaultCutoffMicros !== null && - actualCeiling >= requiredVaultCutoffMicros - ) { - throw new AdjFactorsSnapshotError( - 'incompatible_fence', - `adj_factors snapshot at "${validPath}" admits actions at or past Vault cutoff (${actualCeiling} >= ${requiredVaultCutoffMicros}).`, - validPath - ); - } - if (actualCeiling !== requiredAsOfMicros) { - throw new AdjFactorsSnapshotError( - 'incompatible_fence', - `adj_factors snapshot at "${validPath}" has effective fence ceiling ${actualCeiling} µs, which does not match query effective asOf ${requiredAsOfMicros} µs.`, - validPath - ); - } - - return validPath; -} - -interface ValidatedBarsInputs { - readonly curatedRoot: string; - readonly adjustment: (typeof BARS_ADJUSTMENTS)[number]; - readonly listingIds: number[]; - readonly fenced: FencedTimeRange; - readonly fromSubMs: number; - readonly toSubMs: number; - readonly asOfSubMs: number; -} - -function validateBarsQueryInputs(q: BarsQuery, ctx: DuckDbPlanContext): ValidatedBarsInputs { - const curatedRoot = validateContext(ctx); - if (!isPlainRecord(q)) { - throw new MarketDataStoreValidationError('Expected a bars query object.', 'query'); - } - - const timeframe: unknown = q.timeframe; - if (timeframe === '1m' || timeframe === '5m' || timeframe === '1h') { - throw new MarketDataStoreNotImplementedError( - 'bars', - `Timeframe '${timeframe}' is outside the daily Parquet slice.` - ); - } - if (timeframe !== '1d') { - throw new MarketDataStoreValidationError( - `Invalid bars timeframe "${String(timeframe)}". Expected '1d'.`, - 'timeframe' - ); - } - - const adjustment = validateAdjustment(q.adjustment); - const listingIds = validateListingIds(q.listingIds); - const fenced = applyVaultFence( - { - from: q.from, - to: q.to, - asOf: q.asOf, - scope: q.scope, - }, - { - vaultCutoffTs: ctx.vaultCutoffTs, - vaultOperatorAuthorized: ctx.vaultOperatorAuthorized, - } - ); - - const fromSubMs = resolveFromSubMsMicros(q.from); - const toSubMs = resolveToSubMsMicros(q.to, fenced); - const asOfSubMs = resolveAsOfSubMsMicros(q.asOf, q.to, fenced); - if (fenced.fromMs === fenced.toMs && fromSubMs > toSubMs) { - throw new MarketDataStoreValidationError( - `Query start "${q.from}" must not be after end "${q.to}".`, - 'from' - ); - } - - return { - curatedRoot, - adjustment, - listingIds, - fenced, - fromSubMs, - toSubMs, - asOfSubMs, - }; -} - -/** - * Plans a fenced DuckDB SQL query for daily curated OHLCV bars (`bars_1d`) with - * optional point-in-time `adj_factors` split or total-return adjustment. - * - * For `'split'` and `'total'`, `ctx.adjFactorsSnapshot` must supply verified - * `point_in_time_fenced` Parquet footer metadata matching the query's effective - * `asOf` and Vault fence; `read_parquet(...)` is bound directly to - * `ctx.adjFactorsSnapshot.path`. - */ -export function planBars1dQuery(q: BarsQuery, ctx: DuckDbPlanContext): PlannedDuckDbQuery { - const { curatedRoot, adjustment, listingIds, fenced, fromSubMs, toSubMs, asOfSubMs } = - validateBarsQueryInputs(q, ctx); - - const fromIso = formatUtcIsoWithMicros(fenced.fromMs, fromSubMs); - const toIso = formatUtcIsoWithMicros(fenced.toMs, toSubMs); - const asOfIso = formatUtcIsoWithMicros(fenced.asOfMs, asOfSubMs); - const barsPath = joinCuratedPath(curatedRoot, 'bars_1d/year=*/part.parquet'); - const listingPlaceholders = buildPlaceholders(listingIds.length); - - if (adjustment === 'raw') { - const sql = - 'SELECT b.listing_id, epoch_ms(b.ts) AS ts, b.open, b.high, b.low, b.close, b.volume, b.vwap, epoch_ms(b.known_at) AS known_at ' + - `FROM read_parquet('${barsPath}', hive_partitioning = true) AS b ` + - `WHERE b.listing_id IN (${listingPlaceholders}) AND b.ts >= ? AND b.ts <= ? AND b.known_at <= ? ` + - 'ORDER BY b.listing_id ASC, b.ts ASC'; - const params: DuckDbParam[] = [...listingIds, fromIso, toIso, asOfIso]; - return { sql, params, fenced }; - } - - const requiredAsOfMicros = toEpochMicros(fenced.asOfMs, asOfSubMs, 'asOf'); - const requiredVaultCutoffMicros = - fenced.scope === 'vault_fenced' ? toEpochMicros(ctx.vaultCutoffTs, 0, 'vaultCutoffTs') : null; - const verifiedAdjPath = verifyAdjFactorsSnapshotForQuery( - ctx.adjFactorsSnapshot, - requiredAsOfMicros, - requiredVaultCutoffMicros - ); - - const priceDivisor = - adjustment === 'split' - ? 'COALESCE(a.cum_split_factor, 1.0)' - : 'COALESCE(a.cum_total_factor, 1.0)'; - const adjSelectCols = - adjustment === 'split' - ? 'listing_id, ex_date, cum_split_factor' - : 'listing_id, ex_date, cum_split_factor, cum_total_factor'; - - const sql = - 'SELECT b.listing_id, epoch_ms(b.ts) AS ts, ' + - `b.open / ${priceDivisor} AS open, ` + - `b.high / ${priceDivisor} AS high, ` + - `b.low / ${priceDivisor} AS low, ` + - `b.close / ${priceDivisor} AS close, ` + - 'b.volume * COALESCE(a.cum_split_factor, 1.0) AS volume, ' + - `b.vwap / ${priceDivisor} AS vwap, ` + - 'epoch_ms(b.known_at) AS known_at ' + - `FROM read_parquet('${barsPath}', hive_partitioning = true) AS b ` + - `ASOF LEFT JOIN (SELECT ${adjSelectCols} FROM read_parquet('${verifiedAdjPath}') WHERE listing_id IN (${listingPlaceholders}) AND known_at <= ?) AS a ` + - 'ON b.listing_id = a.listing_id AND b.session_date < a.ex_date ' + - `WHERE b.listing_id IN (${listingPlaceholders}) AND b.ts >= ? AND b.ts <= ? AND b.known_at <= ? ` + - 'ORDER BY b.listing_id ASC, b.ts ASC'; - - const params: DuckDbParam[] = [...listingIds, asOfIso, ...listingIds, fromIso, toIso, asOfIso]; - return { sql, params, fenced }; -} - -/** - * Plans a fenced DuckDB SQL query for point-in-time curated events (`events`). - * Preserves the Parquet writer's total sort order: - * `(listing_id, ts, kind, subtype, payload_json, known_at, known_at_source)`. - */ -export function planEventsQuery(q: EventsQuery, ctx: DuckDbPlanContext): PlannedDuckDbQuery { - const curatedRoot = validateContext(ctx); - if (!isPlainRecord(q)) { - throw new MarketDataStoreValidationError('Expected an events query object.', 'query'); - } - - const kinds = validateEventKinds(q.kinds); - const listingIds = - q.listingIds !== undefined ? validateListingIds(q.listingIds) : undefined; - const fenced = applyVaultFence( - { - from: q.from, - to: q.to, - asOf: q.asOf, - scope: 'vault_fenced', - }, - { - vaultCutoffTs: ctx.vaultCutoffTs, - } - ); - - const fromSubMs = resolveFromSubMsMicros(q.from); - const toSubMs = resolveToSubMsMicros(q.to, fenced); - const asOfSubMs = resolveAsOfSubMsMicros(q.asOf, q.to, fenced); - if (fenced.fromMs === fenced.toMs && fromSubMs > toSubMs) { - throw new MarketDataStoreValidationError( - `Query start "${q.from}" must not be after end "${q.to}".`, - 'from' - ); - } - - const fromIso = formatUtcIsoWithMicros(fenced.fromMs, fromSubMs); - const toIso = formatUtcIsoWithMicros(fenced.toMs, toSubMs); - const asOfIso = formatUtcIsoWithMicros(fenced.asOfMs, asOfSubMs); - const eventsPath = joinCuratedPath(curatedRoot, 'events/year=*/part.parquet'); - const kindPlaceholders = buildPlaceholders(kinds.length); - const orderBy = - 'ORDER BY e.listing_id ASC, e.ts ASC, e.kind ASC, e.subtype ASC, e.payload_json ASC, e.known_at ASC, e.known_at_source ASC'; - - if (listingIds !== undefined) { - const listingPlaceholders = buildPlaceholders(listingIds.length); - const sql = - 'SELECT e.listing_id, epoch_ms(e.ts) AS ts, epoch_ms(e.known_at) AS known_at, e.known_at_source, e.kind, e.subtype, e.payload_json ' + - `FROM read_parquet('${eventsPath}', hive_partitioning = true) AS e ` + - `WHERE e.kind IN (${kindPlaceholders}) AND e.listing_id IN (${listingPlaceholders}) AND e.ts >= ? AND e.ts <= ? AND e.known_at <= ? ` + - orderBy; - const params: DuckDbParam[] = [...kinds, ...listingIds, fromIso, toIso, asOfIso]; - return { sql, params, fenced }; - } - - const sql = - 'SELECT e.listing_id, epoch_ms(e.ts) AS ts, epoch_ms(e.known_at) AS known_at, e.known_at_source, e.kind, e.subtype, e.payload_json ' + - `FROM read_parquet('${eventsPath}', hive_partitioning = true) AS e ` + - `WHERE e.kind IN (${kindPlaceholders}) AND e.ts >= ? AND e.ts <= ? AND e.known_at <= ? ` + - orderBy; - const params: DuckDbParam[] = [...kinds, fromIso, toIso, asOfIso]; - return { sql, params, fenced }; -} - -/** - * Plans a fenced DuckDB SQL query for point-in-time curated short interest (`shorts`). - */ -export function planShortsAsOfQuery( - q: ShortsAsOfQuery, - ctx: DuckDbPlanContext -): PlannedDuckDbQuery { - const curatedRoot = validateContext(ctx); - if (!isPlainRecord(q)) { - throw new MarketDataStoreValidationError('Expected a shortsAsOf query object.', 'query'); - } - - const listingIds = validateListingIds(q.listingIds); - const fenced = applyVaultFence( - { - from: q.from, - to: q.to, - asOf: q.asOf, - scope: 'vault_fenced', - }, - { - vaultCutoffTs: ctx.vaultCutoffTs, - } - ); - - const asOfSubMs = resolveAsOfSubMsMicros(q.asOf, q.to, fenced); - const fromDate = formatUtcDate(fenced.fromMs); - const toDate = formatUtcDate(fenced.toMs); - const asOfIso = formatUtcIsoWithMicros(fenced.asOfMs, asOfSubMs); - const shortsPath = joinCuratedPath(curatedRoot, 'shorts/part.parquet'); - const listingPlaceholders = buildPlaceholders(listingIds.length); - - const sql = - 'SELECT s.listing_id, CAST(s.report_date AS VARCHAR) AS report_date, epoch_ms(s.known_at) AS known_at, s.shares_short, s.net_change, s.pct_float, s.source ' + - `FROM read_parquet('${shortsPath}') AS s ` + - `WHERE s.listing_id IN (${listingPlaceholders}) AND s.report_date >= ? AND s.report_date <= ? AND s.known_at <= ? ` + - 'ORDER BY s.listing_id ASC, s.report_date ASC'; - const params: DuckDbParam[] = [...listingIds, fromDate, toDate, asOfIso]; - return { sql, params, fenced }; -} - -/** - * Plans a fenced DuckDB SQL query for daily curated FX bars (`fx_1d`). - * `fx` has no `asOf`/`scope` in `MarketDataStore`, so it is always planned - * under `'vault_fenced'` with default `asOf = vaultCutoffTs * 1000 - 1` µs. - * Date-only `to` and clamped/default Vault upper bounds expand to the last - * included Parquet microsecond (`23:59:59.999999Z`), matching `curate_fx_1d`'s - * `23:59:59.999999Z` session timestamps. - */ -export function planFx1dQuery(q: FxQuery, ctx: DuckDbPlanContext): PlannedDuckDbQuery { - const curatedRoot = validateContext(ctx); - if (!isPlainRecord(q)) { - throw new MarketDataStoreValidationError('Expected an fx query object.', 'query'); - } - - const timeframe: unknown = q.timeframe; - if (timeframe === '1m') { - throw new MarketDataStoreNotImplementedError( - 'fx', - "Timeframe '1m' is outside the daily Parquet slice." - ); - } - if (timeframe !== '1d') { - throw new MarketDataStoreValidationError( - `Invalid fx timeframe "${String(timeframe)}". Expected '1d'.`, - 'timeframe' - ); - } - - const storedPair = validateFxPair(q.pair); - const fenced = applyVaultFence( - { - from: q.from, - to: q.to, - scope: 'vault_fenced', - }, - { - vaultCutoffTs: ctx.vaultCutoffTs, - } - ); - - const fromSubMs = resolveFromSubMsMicros(q.from); - const toSubMs = resolveToSubMsMicros(q.to, fenced); - const asOfSubMs = resolveAsOfSubMsMicros(undefined, q.to, fenced); - if (fenced.fromMs === fenced.toMs && fromSubMs > toSubMs) { - throw new MarketDataStoreValidationError( - `Query start "${q.from}" must not be after end "${q.to}".`, - 'from' - ); - } - - const fromIso = formatUtcIsoWithMicros(fenced.fromMs, fromSubMs); - const toIso = formatUtcIsoWithMicros(fenced.toMs, toSubMs); - const asOfIso = formatUtcIsoWithMicros(fenced.asOfMs, asOfSubMs); - const fxPath = joinCuratedPath(curatedRoot, 'fx_1d/part.parquet'); - - const sql = - 'SELECT f.pair, CAST(f.session_date AS VARCHAR) AS session_date, epoch_ms(f.ts) AS ts, f.open, f.high, f.low, f.close, f.source, epoch_ms(f.known_at) AS known_at ' + - `FROM read_parquet('${fxPath}') AS f ` + - 'WHERE f.pair = ? AND f.ts >= ? AND f.ts <= ? AND f.known_at <= ? ' + - 'ORDER BY f.session_date ASC'; - const params: DuckDbParam[] = [storedPair, fromIso, toIso, asOfIso]; - return { sql, params, fenced }; -} - -/** - * Plans a Vault-fenced, survivorship-free DuckDB SQL query resolving active - * listing IDs on `q.date` from curated `bars_1d` Parquet (`US_EQ`, `CA_EQ`, - * `US_CA_EQ`). - * - * A listing is considered active on `q.date` when it has at least one `bars_1d` - * row with `session_date` in `[date - lookbackDays, date]` (default `7` - * calendar days), bounded by `b.ts <= ?` and `b.known_at <= ?` under - * `'vault_fenced'` scope so no post-date or Vault rows can ever be read. - */ -export function planUniverseQuery(q: UniverseQuery, ctx: DuckDbPlanContext): PlannedDuckDbQuery { - const curatedRoot = validateContext(ctx); - const lookbackDays = validateUniverseLookbackDays(ctx.universeLookbackDays); - if (!isPlainRecord(q)) { - throw new MarketDataStoreValidationError('Expected a universe query object.', 'query'); - } - - const currencies = validateUniverseRef(q.ref); - if (typeof q.date !== 'string' || !DATE_ONLY_RE.test(q.date)) { - throw new MarketDataStoreValidationError( - `Invalid universe date "${String(q.date)}". Expected a UTC calendar date in YYYY-MM-DD format.`, - 'date' - ); - } - - let fencedDate: FencedTimeRange; - try { - fencedDate = applyVaultFence( - { - from: q.date, - to: q.date, - asOf: q.date, - scope: 'vault_fenced', - }, - { - vaultCutoffTs: ctx.vaultCutoffTs, - } - ); - } catch (err: unknown) { - if ( - err instanceof MarketDataStoreValidationError && - (err.field === 'from' || err.field === 'to' || err.field === 'asOf') - ) { - throw new MarketDataStoreValidationError(err.message, 'date'); - } - throw err; - } - - const lookbackStartMs = fencedDate.fromMs - lookbackDays * MS_PER_DAY; - if (!Number.isSafeInteger(lookbackStartMs) || lookbackStartMs < MIN_ISO_DATE_EPOCH_MS) { - throw new MarketDataStoreValidationError( - `Invalid universeLookbackDays "${lookbackDays}". Lookback start precedes supported YYYY-MM-DD UTC date range.`, - 'universeLookbackDays' - ); - } - - const lookbackStartDate = formatUtcDate(lookbackStartMs); - const endDate = formatUtcDate(fencedDate.toMs); - const toIso = formatUtcIsoWithMicros(fencedDate.toMs, resolveToSubMsMicros(q.date, fencedDate)); - const asOfIso = formatUtcIsoWithMicros( - fencedDate.asOfMs, - resolveAsOfSubMsMicros(q.date, q.date, fencedDate) - ); - const barsPath = joinCuratedPath(curatedRoot, 'bars_1d/year=*/part.parquet'); - const currencyPredicate = - currencies.length === 1 - ? 'b.currency = ?' - : `b.currency IN (${buildPlaceholders(currencies.length)})`; - - const sql = - 'SELECT DISTINCT b.listing_id ' + - `FROM read_parquet('${barsPath}', hive_partitioning = true) AS b ` + - `WHERE ${currencyPredicate} AND b.session_date >= ? AND b.session_date <= ? AND b.ts <= ? AND b.known_at <= ? ` + - 'ORDER BY b.listing_id ASC'; - const params: DuckDbParam[] = [...currencies, lookbackStartDate, endDate, toIso, asOfIso]; - - return { - sql, - params, - fenced: { - ...fencedDate, - fromMs: lookbackStartMs, - }, - }; -} - -interface PlannedFundamentalsAsOfInternal { - readonly planned: PlannedDuckDbQuery; - readonly columns: readonly string[]; - readonly schema: readonly TableColumnSpec[]; -} - -function planFundamentalsAsOfInternal( - q: FundamentalsAsOfQuery, - ctx: DuckDbPlanContext -): PlannedFundamentalsAsOfInternal { - const curatedRoot = validateContext(ctx); - if (!isPlainRecord(q)) { - throw new MarketDataStoreValidationError( - 'Expected a fundamentalsAsOf query object.', - 'query' - ); - } - - const listingIds = validateListingIds(q.listingIds); - const fields = validateFundamentalsFields(q.fields); - const allowEstimatedLag = validateAllowEstimatedLag(q.allowEstimatedLag); - - let fenced: FencedTimeRange; - try { - fenced = applyVaultFence( - { - from: q.asOf, - to: q.asOf, - asOf: q.asOf, - scope: 'vault_fenced', - }, - { - vaultCutoffTs: ctx.vaultCutoffTs, - } - ); - } catch (err: unknown) { - if (err instanceof VaultHoldoutFenceError) { - const maxAllowedMs = ctx.vaultCutoffTs - 1; - fenced = { - fromMs: maxAllowedMs, - toMs: maxAllowedMs, - asOfMs: maxAllowedMs, - scope: 'vault_fenced', - clampedTo: true, - clampedAsOf: true, - }; - } else if ( - err instanceof MarketDataStoreValidationError && - (err.field === 'from' || err.field === 'to') - ) { - throw new MarketDataStoreValidationError(err.message, 'asOf'); - } else { - throw err; - } - } - - const asOfSubMs = resolveAsOfSubMsMicros(q.asOf, q.asOf, fenced); - const asOfIso = formatUtcIsoWithMicros(fenced.asOfMs, asOfSubMs); - const fundamentalsPath = joinCuratedPath(curatedRoot, 'fundamentals_pit/year=*/part.parquet'); - const listingPlaceholders = buildPlaceholders(listingIds.length); - - let hasTtmField = false; - for (const field of fields) { - if (FUNDAMENTALS_TTM_VALUE_FIELD_SET.has(field)) { - hasTtmField = true; - break; - } - } - - const innerCols: string[] = [ - 'f.listing_id', - 'f.effective_known_at', - 'f.known_at_source', - 'f.has_estimated_lag', - 'f.period_end', - 'f.fiscal_period', - 'f.currency', - 'f.period_known_at', - ]; - const outerCols: string[] = [ - 's.listing_id', - 'epoch_ms(s.effective_known_at) AS effective_known_at', - 's.known_at_source', - 's.has_estimated_lag', - 'CAST(s.period_end AS VARCHAR) AS period_end', - 's.fiscal_period', - 's.currency', - 'epoch_ms(s.period_known_at) AS period_known_at', - ]; - const schema: TableColumnSpec[] = [...FUNDAMENTALS_BASE_SCHEMA]; - - for (const field of fields) { - innerCols.push(`f.${field}`); - if (FUNDAMENTALS_TTM_VALUE_FIELD_SET.has(field)) { - outerCols.push( - `CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN s.${field} ELSE NULL END AS ${field}` - ); - } else { - outerCols.push(`s.${field}`); - } - schema.push({ name: field, kind: 'number', nullable: true }); - } - - if (hasTtmField) { - innerCols.push('f.ttm_period_end', 'f.ttm_currency', 'f.ttm_has_estimated_lag'); - outerCols.push( - 'CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN CAST(s.ttm_period_end AS VARCHAR) ELSE NULL END AS ttm_period_end', - 'CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN s.ttm_currency ELSE NULL END AS ttm_currency', - 's.ttm_has_estimated_lag' - ); - schema.push(...FUNDAMENTALS_TTM_META_SCHEMA); - } - - const columns = schema.map(spec => spec.name); - const sql = - `WITH latest AS (SELECT ${innerCols.join(', ')} ` + - 'FROM read_parquet(?, hive_partitioning = true) AS f ' + - `WHERE f.listing_id IN (${listingPlaceholders}) AND f.effective_known_at <= CAST(? AS TIMESTAMPTZ) ` + - 'QUALIFY ROW_NUMBER() OVER (PARTITION BY f.listing_id ORDER BY f.effective_known_at DESC) = 1) ' + - `SELECT ${outerCols.join(', ')} ` + - 'FROM latest AS s ' + - 'CROSS JOIN (SELECT CAST(? AS BOOLEAN) AS allow_estimated_lag) AS opts ' + - 'WHERE (opts.allow_estimated_lag OR NOT s.has_estimated_lag) ' + - 'ORDER BY s.listing_id ASC'; - const params: DuckDbParam[] = [fundamentalsPath, ...listingIds, asOfIso, allowEstimatedLag]; - - return { - planned: { sql, params, fenced }, - columns, - schema, - }; -} - -/** - * Plans a Vault-fenced point-in-time DuckDB SQL query over curated - * `fundamentals_pit/year=*\/part.parquet` snapshots. - * - * Selects at most one snapshot per requested `listing_id` — the latest with - * `effective_known_at <= asOf` (clamped strictly below `vaultCutoffTs`). When - * `allowEstimatedLag` is `false`, listings whose selected snapshot has - * `has_estimated_lag = true` are omitted without falling back to an older - * snapshot, and requested `ttm_*` value fields plus `ttm_period_end` / - * `ttm_currency` are masked to `NULL` when `ttm_has_estimated_lag` is `true` - * while preserving `ttm_has_estimated_lag`. - */ -export function planFundamentalsAsOfQuery( - q: FundamentalsAsOfQuery, - ctx: DuckDbPlanContext -): PlannedDuckDbQuery { - return planFundamentalsAsOfInternal(q, ctx).planned; -} - -function readRequiredInt32(row: Record, key: string, rowIndex: number): number { - const val = row[key]; - if (typeof val !== 'number' || !Number.isSafeInteger(val) || val < INT32_MIN || val > INT32_MAX) { - throw new MarketDataStoreValidationError( - `Invalid INT32 column "${key}" in result row ${rowIndex}: ${String(val)}.`, - key - ); - } - return val === 0 ? 0 : val; -} - -function readRequiredSafeInt(row: Record, key: string, rowIndex: number): number { - const val = row[key]; - if (typeof val !== 'number' || !Number.isSafeInteger(val)) { - throw new MarketDataStoreValidationError( - `Invalid integer timestamp column "${key}" in result row ${rowIndex}: ${String(val)}.`, - key - ); - } - return val === 0 ? 0 : val; -} - -function readRequiredFiniteNumber( - row: Record, - key: string, - rowIndex: number -): number { - const val = row[key]; - if (typeof val !== 'number' || !Number.isFinite(val)) { - throw new MarketDataStoreValidationError( - `Invalid numeric column "${key}" in result row ${rowIndex}: ${String(val)}.`, - key - ); - } - return val === 0 ? 0 : val; -} - -function readNullableFiniteNumber( - row: Record, - key: string, - rowIndex: number -): number | null { - const val = row[key]; - if (val === null || val === undefined) { - return null; - } - if (typeof val !== 'number' || !Number.isFinite(val)) { - throw new MarketDataStoreValidationError( - `Invalid nullable numeric column "${key}" in result row ${rowIndex}: ${String(val)}.`, - key - ); - } - return val === 0 ? 0 : val; -} - -function mapBarRows(rows: readonly TableRow[]): BarRecord[] { - if (!Array.isArray(rows)) { - throw new MarketDataStoreValidationError('Executor returned a non-array bars result.', 'rows'); - } - const out: BarRecord[] = new Array(rows.length); - for (let i = 0; i < rows.length; i += 1) { - const raw = rows[i]; - if (!isPlainRecord(raw)) { - throw new MarketDataStoreValidationError( - `Executor returned a non-object bar row at index ${i}.`, - 'rows' - ); - } - out[i] = { - listingId: readRequiredInt32(raw, 'listing_id', i), - ts: readRequiredSafeInt(raw, 'ts', i), - open: readRequiredFiniteNumber(raw, 'open', i), - high: readRequiredFiniteNumber(raw, 'high', i), - low: readRequiredFiniteNumber(raw, 'low', i), - close: readRequiredFiniteNumber(raw, 'close', i), - volume: readRequiredFiniteNumber(raw, 'volume', i), - vwap: readNullableFiniteNumber(raw, 'vwap', i), - knownAt: readRequiredSafeInt(raw, 'known_at', i), - }; - } - return out; -} - -function readValidatedTableCell( - row: Record, - spec: TableColumnSpec, - rowIndex: number -): TableCell { - const val = row[spec.name]; - if (val === null) { - if (spec.nullable) { - return null; - } - throw new MarketDataStoreValidationError( - `Unexpected null for non-nullable column "${spec.name}" in result row ${rowIndex}.`, - spec.name - ); - } - - switch (spec.kind) { - case 'int32': - if ( - typeof val !== 'number' || - !Number.isSafeInteger(val) || - val < INT32_MIN || - val > INT32_MAX - ) { - throw new MarketDataStoreValidationError( - `Expected INT32 for column "${spec.name}" in result row ${rowIndex}, got ${typeof val} (${String(val)}).`, - spec.name - ); - } - return val === 0 ? 0 : val; - case 'safe_int': - if (typeof val !== 'number' || !Number.isSafeInteger(val)) { - throw new MarketDataStoreValidationError( - `Expected integer timestamp for column "${spec.name}" in result row ${rowIndex}, got ${typeof val} (${String(val)}).`, - spec.name - ); - } - return val === 0 ? 0 : val; - case 'number': - if (typeof val !== 'number' || !Number.isFinite(val)) { - throw new MarketDataStoreValidationError( - `Expected finite number for column "${spec.name}" in result row ${rowIndex}, got ${typeof val} (${String(val)}).`, - spec.name - ); - } - return val === 0 ? 0 : val; - case 'string': - if (typeof val !== 'string') { - throw new MarketDataStoreValidationError( - `Expected string for column "${spec.name}" in result row ${rowIndex}, got ${typeof val} (${String(val)}).`, - spec.name - ); - } - return val; - case 'boolean': - if (typeof val !== 'boolean') { - throw new MarketDataStoreValidationError( - `Expected boolean for column "${spec.name}" in result row ${rowIndex}, got ${typeof val} (${String(val)}).`, - spec.name - ); - } - return val; - } -} - -function mapTableRows( - columns: readonly string[], - schema: readonly TableColumnSpec[], - rows: readonly TableRow[] -): Table { - if (!Array.isArray(rows)) { - throw new MarketDataStoreValidationError('Executor returned a non-array table result.', 'rows'); - } - const mappedRows: TableRow[] = new Array(rows.length); - for (let i = 0; i < rows.length; i += 1) { - const raw = rows[i]; - if (!isPlainRecord(raw)) { - throw new MarketDataStoreValidationError( - `Executor returned a non-object table row at index ${i}.`, - 'rows' - ); - } - const cleanRow: Record = {}; - for (const spec of schema) { - if (!Object.prototype.hasOwnProperty.call(raw, spec.name)) { - throw new MarketDataStoreValidationError( - `Missing expected column "${spec.name}" in result row ${i}.`, - spec.name - ); - } - cleanRow[spec.name] = readValidatedTableCell(raw, spec, i); - } - mappedRows[i] = cleanRow; - } - return { - columns: [...columns], - rows: mappedRows, - }; -} - -function mapUniverseRows(rows: readonly TableRow[]): number[] { - if (!Array.isArray(rows)) { - throw new MarketDataStoreValidationError( - 'Executor returned a non-array universe result.', - 'rows' - ); - } - const out: number[] = new Array(rows.length); - let prev: number | undefined; - for (let i = 0; i < rows.length; i += 1) { - const raw = rows[i]; - if (!isPlainRecord(raw)) { - throw new MarketDataStoreValidationError( - `Executor returned a non-object universe row at index ${i}.`, - 'rows' - ); - } - if (!Object.prototype.hasOwnProperty.call(raw, 'listing_id')) { - throw new MarketDataStoreValidationError( - `Missing expected column "listing_id" in universe result row ${i}.`, - 'listing_id' - ); - } - const id = readRequiredInt32(raw, 'listing_id', i); - if (prev !== undefined) { - if (id === prev) { - throw new MarketDataStoreValidationError( - `Duplicate listing_id ${id} in universe result row ${i}.`, - 'listing_id' - ); - } - if (id < prev) { - throw new MarketDataStoreValidationError( - `Unsorted listing_id ${id} after ${prev} in universe result row ${i}. Expected strictly ascending order.`, - 'listing_id' - ); - } - } - prev = id; - out[i] = id; - } - return out; -} - -/** - * Creates a `MarketDataStore` backed by an injected {@link DuckDbExecutor} - * over curated daily Parquet files. - * - * The three `resolveDuckDbConnectionBudget(env).statements` are executed - * sequentially, at most once, strictly after the first query validates cleanly - * and strictly before the first `executor.query(...)` call. - * - * For `'split'` and `'total'` `bars` queries, the adapter pins a single - * `adj_factors` artifact version across both `parquet_kv_metadata(...)` footer - * verification and the `read_parquet(...)` factor scan — either via - * {@link DuckDbMarketDataStoreOptions.pinAdjFactorsArtifact} (releasing the - * handle in `finally`) or via an explicit write-once - * {@link DuckDbMarketDataStoreOptions.immutableAdjFactorsPath} distinct from - * the mutable `/adj_factors/part.parquet` path. Unpinned reads of - * a mutable path fail closed with {@link AdjFactorsSnapshotError} - * (`code: 'unpinned_mutable_path'`) and zero executor calls. - */ -export function createDuckDbMarketDataStore(options: DuckDbMarketDataStoreOptions): MarketDataStore { - if (!isPlainRecord(options)) { - throw new MarketDataStoreValidationError( - 'Expected a DuckDbMarketDataStoreOptions object.', - 'options' - ); - } - - const executor: unknown = options.executor; - if ( - !isPlainRecord(executor) || - typeof executor.run !== 'function' || - typeof executor.query !== 'function' - ) { - throw new MarketDataStoreValidationError( - 'Expected `executor` with `run(sql)` and `query(sql, params)` methods.', - 'executor' - ); - } - const typedExecutor = executor as unknown as DuckDbExecutor; - - const curatedRoot = validateCuratedRoot(options.curatedRoot); - const defaultMutableAdjPath = joinCuratedPath(curatedRoot, 'adj_factors/part.parquet'); - const canonicalDefaultMutableAdjPath = canonicalizePosixPath(defaultMutableAdjPath); - - if (options.adjFactorsPath !== undefined && options.immutableAdjFactorsPath !== undefined) { - throw new MarketDataStoreValidationError( - 'Options `adjFactorsPath` and `immutableAdjFactorsPath` are mutually exclusive.', - 'immutableAdjFactorsPath' - ); - } - - const adjFactorsSourcePath = - options.adjFactorsPath !== undefined - ? validateParquetFilePath(options.adjFactorsPath, 'adjFactorsPath') - : defaultMutableAdjPath; - const canonicalSourceAdjPath = canonicalizePosixPath(adjFactorsSourcePath); - - let immutableAdjFactorsPath: string | undefined; - if (options.immutableAdjFactorsPath !== undefined) { - const validatedImmutable = validateParquetFilePath( - options.immutableAdjFactorsPath, - 'immutableAdjFactorsPath' - ); - if (canonicalizePosixPath(validatedImmutable) === canonicalDefaultMutableAdjPath) { - throw new MarketDataStoreValidationError( - `Option \`immutableAdjFactorsPath\` must not point to the mutable published path "${defaultMutableAdjPath}". Use \`pinAdjFactorsArtifact\` to pin the mutable path or provide a write-once snapshot path.`, - 'immutableAdjFactorsPath' - ); - } - immutableAdjFactorsPath = validatedImmutable; - } - - const pinAdjFactorsArtifact = options.pinAdjFactorsArtifact; - if (pinAdjFactorsArtifact !== undefined && typeof pinAdjFactorsArtifact !== 'function') { - throw new MarketDataStoreValidationError( - 'Expected `pinAdjFactorsArtifact` to be a function returning a PinnedAdjFactorsArtifact handle.', - 'pinAdjFactorsArtifact' - ); - } - - const vaultCutoffTs = options.vaultCutoffTs; - if ( - typeof vaultCutoffTs !== 'number' || - !Number.isSafeInteger(vaultCutoffTs) || - Math.abs(vaultCutoffTs) > MAX_ECMASCRIPT_EPOCH_MS || - vaultCutoffTs <= -MAX_ECMASCRIPT_EPOCH_MS - ) { - throw new MarketDataStoreValidationError( - `Invalid epoch millisecond timestamp for "vaultCutoffTs": ${String(vaultCutoffTs)}.`, - 'vaultCutoffTs' - ); - } - - const barBatchSize = options.barBatchSize; - if ( - barBatchSize !== undefined && - (typeof barBatchSize !== 'number' || !Number.isSafeInteger(barBatchSize) || barBatchSize < 1) - ) { - throw new MarketDataStoreValidationError( - `Invalid barBatchSize "${String(barBatchSize)}". Expected a positive safe integer.`, - 'barBatchSize' - ); - } - - const universeLookbackDays = validateUniverseLookbackDays( - options.universeLookbackDays, - vaultCutoffTs - ); - - const budget = resolveDuckDbConnectionBudget(options.env); - const planCtx: DuckDbPlanContext = { - curatedRoot, - vaultCutoffTs: vaultCutoffTs === 0 ? 0 : vaultCutoffTs, - vaultOperatorAuthorized: options.vaultOperatorAuthorized, - universeLookbackDays, - }; - - let budgetInitialized = false; - let budgetInitPromise: Promise | null = null; - - function ensureBudgetInitialized(): Promise { - if (budgetInitialized) { - return Promise.resolve(); - } - if (budgetInitPromise === null) { - budgetInitPromise = (async () => { - for (const statement of budget.statements) { - await typedExecutor.run(statement); - } - budgetInitialized = true; - })().catch((err: unknown) => { - budgetInitPromise = null; - throw err; - }); - } - return budgetInitPromise; - } - - async function executeAdjustedBarsQuery( - q: BarsQuery, - artifactPath: string - ): Promise { - const metaQuery = planAdjFactorsMetadataQuery(artifactPath); - const kvRows = await typedExecutor.query(metaQuery.sql, metaQuery.params); - const adjFactorsSnapshot = parseAdjFactorsSnapshotMetadata(artifactPath, kvRows); - const planned = planBars1dQuery(q, { ...planCtx, adjFactorsSnapshot }); - return typedExecutor.query(planned.sql, planned.params); - } - - return { - async *bars(q: BarsQuery): AsyncIterable { - if (!isPlainRecord(q)) { - throw new MarketDataStoreValidationError('Expected a bars query object.', 'query'); - } - - let rawRows: readonly TableRow[]; - if (q.adjustment === 'split' || q.adjustment === 'total') { - // Validate timeframe, listingIds, adjustment, and Vault fence before any executor/pinner call. - validateBarsQueryInputs(q, planCtx); - - if (pinAdjFactorsArtifact !== undefined) { - await ensureBudgetInitialized(); - const sourceToPin = immutableAdjFactorsPath ?? adjFactorsSourcePath; - const rawPin: unknown = await pinAdjFactorsArtifact(sourceToPin); - if (!isPlainRecord(rawPin) || typeof rawPin.release !== 'function') { - throw new MarketDataStoreValidationError( - 'Expected `pinAdjFactorsArtifact` to return `{ pinnedPath, release() }`.', - 'pinAdjFactorsArtifact' - ); - } - const pin = rawPin as unknown as PinnedAdjFactorsArtifact; - try { - const pinnedPath = validateAdjFactorsArtifactPath( - pin.pinnedPath, - 'pinnedPath' - ); - const canonicalPinned = canonicalizePosixPath(pinnedPath); - if ( - canonicalPinned === canonicalSourceAdjPath || - canonicalPinned === canonicalDefaultMutableAdjPath - ) { - throw new AdjFactorsSnapshotError( - 'unpinned_mutable_path', - `\`pinAdjFactorsArtifact\` returned the mutable path "${pinnedPath}" without pinning a distinct handle or immutable snapshot copy.`, - pinnedPath - ); - } - rawRows = await executeAdjustedBarsQuery(q, pinnedPath); - } finally { - await pin.release(); - } - } else if (immutableAdjFactorsPath !== undefined) { - await ensureBudgetInitialized(); - rawRows = await executeAdjustedBarsQuery(q, immutableAdjFactorsPath); - } else { - throw new AdjFactorsSnapshotError( - 'unpinned_mutable_path', - `Refusing to read mutable adj_factors path "${adjFactorsSourcePath}" across separate footer verification and factor scan queries without pinning. Provide \`pinAdjFactorsArtifact\` or \`immutableAdjFactorsPath\`.`, - adjFactorsSourcePath - ); - } - } else { - const planned = planBars1dQuery(q, planCtx); - await ensureBudgetInitialized(); - rawRows = await typedExecutor.query(planned.sql, planned.params); - } - - const mapped = mapBarRows(rawRows); - if (mapped.length === 0) { - return; - } - if (barBatchSize === undefined || mapped.length <= barBatchSize) { - yield { rows: mapped }; - return; - } - for (let offset = 0; offset < mapped.length; offset += barBatchSize) { - yield { rows: mapped.slice(offset, offset + barBatchSize) }; - } - }, - - async events(q: EventsQuery): Promise
{ - const planned = planEventsQuery(q, planCtx); - await ensureBudgetInitialized(); - const rawRows = await typedExecutor.query(planned.sql, planned.params); - return mapTableRows(EVENTS_COLUMNS, EVENTS_SCHEMA, rawRows); - }, - - async shortsAsOf(q: ShortsAsOfQuery): Promise
{ - const planned = planShortsAsOfQuery(q, planCtx); - await ensureBudgetInitialized(); - const rawRows = await typedExecutor.query(planned.sql, planned.params); - return mapTableRows(SHORTS_COLUMNS, SHORTS_SCHEMA, rawRows); - }, - - async fx(q: FxQuery): Promise
{ - const planned = planFx1dQuery(q, planCtx); - await ensureBudgetInitialized(); - const rawRows = await typedExecutor.query(planned.sql, planned.params); - return mapTableRows(FX_1D_COLUMNS, FX_1D_SCHEMA, rawRows); - }, - - crossSection(): Promise
{ - return Promise.reject(new MarketDataStoreNotImplementedError('crossSection')); - }, - - async fundamentalsAsOf(q: FundamentalsAsOfQuery): Promise
{ - const { planned, columns, schema } = planFundamentalsAsOfInternal(q, planCtx); - await ensureBudgetInitialized(); - const rawRows = await typedExecutor.query(planned.sql, planned.params); - return mapTableRows(columns, schema, rawRows); - }, - - macroAsOf(): Promise
{ - return Promise.reject(new MarketDataStoreNotImplementedError('macroAsOf')); - }, - - async universe(q: UniverseQuery): Promise { - const planned = planUniverseQuery(q, planCtx); - await ensureBudgetInitialized(); - const rawRows = await typedExecutor.query(planned.sql, planned.params); - return mapUniverseRows(rawRows); - }, - }; -} diff --git a/libs/research/src/market-data-store-questdb.ts b/libs/research/src/market-data-store-questdb.ts deleted file mode 100644 index c6da320c..00000000 --- a/libs/research/src/market-data-store-questdb.ts +++ /dev/null @@ -1,462 +0,0 @@ -/** - * Pure, dependency-free QuestDB `bars_1m` query planner and injected-executor - * intraday reader for `MarketDataStore.bars` (`timeframe: '1m'`, - * `design/DATA-CONTRACTS.md` §3.B & §4). - * - * Browser-safe and dependency-free: zero `node:*` imports, zero `pg` or - * `@stock-bot/questdb` dependency, zero bare `process` access. SQL execution - * is injected via {@link QuestDbQueryExecutor}, which is structurally - * compatible with `QuestDBClient.query(sql, params)`. - * - * Storage and point-in-time semantics: - * - `bars_1m` stores split-unadjusted raw 1-minute OHLCV, nullable `vwap`, - * `listing_id` (`SYMBOL`, canonical positive decimal string), `known_at` - * (`TIMESTAMP`), and designated timestamp `ts` (`TIMESTAMP`, - * `PARTITION BY MONTH`). - * - Only `adjustment: 'raw'` is supported; `'split'` and `'total'` throw - * {@link MarketDataStoreNotImplementedError}. - * - Query bounds are Vault-fenced via {@link applyVaultFence} before SQL - * planning. Every user-supplied value is bound via `$1..$n` placeholders; - * only ordinal placeholder tokens are generated in SQL text. - * - `ts` and `known_at` are projected as `CAST(... AS LONG)` (UTC epoch - * microseconds) and verified in exact microseconds against the fenced bounds - * before converting to epoch milliseconds or yielding any batch. - */ - -import { - type BarBatch, - type BarRecord, - type FencedTimeRange, - type MarketDataStore, - MarketDataStoreValidationError, - type VaultFenceContext, - applyVaultFence, -} from './market-data-store'; -import { MarketDataStoreNotImplementedError } from './market-data-store-duckdb'; - -const INT32_MAX = 2_147_483_647; -const MAX_ECMASCRIPT_EPOCH_MS = 8_640_000_000_000_000; -const CANONICAL_POSITIVE_INT_RE = /^[1-9]\d*$/; -const CANONICAL_SIGNED_INT_RE = /^-?(?:0|[1-9]\d*)$/; - -/** Default maximum number of `BarRecord` rows yielded per `BarBatch`. */ -export const DEFAULT_QUESTDB_BARS_BATCH_SIZE = 50_000; - -/** Input query type derived from `MarketDataStore['bars']`. */ -export type QuestDbBars1mQuery = Parameters[0]; - -/** - * Injected PGWire SQL executor port, structurally compatible with - * `QuestDBClient.query(sql, params)` in `libs/data/questdb/src/client.ts`. - */ -export interface QuestDbQueryExecutor { - query( - sql: string, - params: readonly unknown[] - ): Promise<{ readonly rows: readonly Record[] }>; -} - -/** Pure output of {@link planBars1mQuery}. */ -export interface PlannedQuestDbBars1mQuery { - readonly sql: string; - readonly params: readonly string[]; - readonly fence: FencedTimeRange; -} - -/** Configuration for {@link createQuestDbIntradayBarsReader}. */ -export interface QuestDbIntradayBarsReaderOptions extends VaultFenceContext { - readonly executor: QuestDbQueryExecutor; - /** Maximum number of bars per yielded `BarBatch`. Defaults to `50_000`. */ - readonly batchSize?: number; -} - -interface InternalPlannedBars1mQuery { - readonly planned: PlannedQuestDbBars1mQuery; - readonly requestedListingIds: ReadonlySet; -} - -function isPlainRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value); -} - -function validateVaultCutoffTs(vaultCutoffTs: unknown): number { - if ( - typeof vaultCutoffTs !== 'number' || - !Number.isSafeInteger(vaultCutoffTs) || - Math.abs(vaultCutoffTs) > MAX_ECMASCRIPT_EPOCH_MS || - vaultCutoffTs <= -MAX_ECMASCRIPT_EPOCH_MS - ) { - throw new MarketDataStoreValidationError( - `Invalid epoch millisecond timestamp for "vaultCutoffTs": ${String(vaultCutoffTs)}.`, - 'vaultCutoffTs' - ); - } - return vaultCutoffTs === 0 ? 0 : vaultCutoffTs; -} - -function validatePositiveInt32ListingIds(raw: unknown): number[] { - if (!Array.isArray(raw) || raw.length === 0) { - throw new MarketDataStoreValidationError( - 'Expected a non-empty array of positive INT32 listing IDs for "listingIds".', - 'listingIds' - ); - } - - const seen = new Set(); - const normalized: number[] = []; - for (let i = 0; i < raw.length; i += 1) { - const id: unknown = raw[i]; - if ( - typeof id !== 'number' || - !Number.isSafeInteger(id) || - id < 1 || - id > INT32_MAX - ) { - throw new MarketDataStoreValidationError( - `Invalid positive INT32 listing ID at listingIds[${i}]: ${String(id)}.`, - 'listingIds' - ); - } - if (!seen.has(id)) { - seen.add(id); - normalized.push(id); - } - } - - normalized.sort((a, b) => a - b); - return normalized; -} - -function formatUtcIsoMs(epochMs: number): string { - return new Date(epochMs).toISOString(); -} - -function planBars1mQueryInternal( - q: QuestDbBars1mQuery, - ctx: VaultFenceContext -): InternalPlannedBars1mQuery { - if (!isPlainRecord(ctx)) { - throw new MarketDataStoreValidationError('Expected a VaultFenceContext object.', 'ctx'); - } - if (!isPlainRecord(q)) { - throw new MarketDataStoreValidationError('Expected a bars query object.', 'query'); - } - - const timeframe: unknown = q.timeframe; - if (timeframe !== '1m') { - throw new MarketDataStoreValidationError( - `Invalid bars timeframe "${String(timeframe)}". Expected '1m'.`, - 'timeframe' - ); - } - - const adjustment: unknown = q.adjustment; - if (adjustment === 'split' || adjustment === 'total') { - throw new MarketDataStoreNotImplementedError( - 'bars', - `Adjustment '${adjustment}' is not supported for intraday '1m' bars; bars_1m stores raw split-unadjusted values.` - ); - } - if (adjustment !== 'raw') { - throw new MarketDataStoreValidationError( - `Invalid bars adjustment "${String(adjustment)}". Expected 'raw'.`, - 'adjustment' - ); - } - - const sortedListingIds = validatePositiveInt32ListingIds(q.listingIds); - - const fence = applyVaultFence( - { - from: q.from, - to: q.to, - asOf: q.asOf, - scope: q.scope, - }, - { - vaultCutoffTs: ctx.vaultCutoffTs, - vaultOperatorAuthorized: ctx.vaultOperatorAuthorized === true, - } - ); - - const listingPlaceholders = sortedListingIds.map((_, index) => `$${index + 3}`).join(', '); - const asOfPlaceholder = `$${sortedListingIds.length + 3}`; - - const sql = - 'SELECT listing_id, CAST(ts AS LONG) AS ts_us, open, high, low, close, volume, vwap, CAST(known_at AS LONG) AS known_at_us ' + - 'FROM bars_1m ' + - `WHERE ts >= $1 AND ts <= $2 AND listing_id IN (${listingPlaceholders}) AND known_at <= ${asOfPlaceholder} ` + - 'ORDER BY ts, listing_id'; - - const params: string[] = [ - formatUtcIsoMs(fence.fromMs), - formatUtcIsoMs(fence.toMs), - ...sortedListingIds.map(id => String(id)), - formatUtcIsoMs(fence.asOfMs), - ]; - - return { - planned: { sql, params, fence }, - requestedListingIds: new Set(sortedListingIds), - }; -} - -/** - * Pure, Vault-fenced, parameterized SQL planner for QuestDB `bars_1m`. - * - * Binds `from`, `to`, and `asOf` as exact millisecond UTC ISO-8601 strings and - * deduplicated, numerically sorted positive INT32 `listingIds` as canonical - * decimal `SYMBOL` strings. - */ -export function planBars1mQuery( - q: QuestDbBars1mQuery, - ctx: VaultFenceContext -): PlannedQuestDbBars1mQuery { - return planBars1mQueryInternal(q, ctx).planned; -} - -function parseListingIdSymbol( - row: Record, - rowIndex: number, - requestedListingIds: ReadonlySet -): number { - const raw = row.listing_id; - if (typeof raw !== 'string' || !CANONICAL_POSITIVE_INT_RE.test(raw)) { - throw new MarketDataStoreValidationError( - `Invalid bars_1m listing_id SYMBOL in result row ${rowIndex}: ${String(raw)}.`, - 'listing_id' - ); - } - const parsed = Number(raw); - if (!Number.isSafeInteger(parsed) || parsed < 1 || parsed > INT32_MAX) { - throw new MarketDataStoreValidationError( - `Out-of-range bars_1m listing_id SYMBOL in result row ${rowIndex}: "${raw}".`, - 'listing_id' - ); - } - if (!requestedListingIds.has(parsed)) { - throw new MarketDataStoreValidationError( - `Unexpected unrequested listing_id ${parsed} in bars_1m result row ${rowIndex}.`, - 'listing_id' - ); - } - return parsed; -} - -function parseTimestampMicros( - row: Record, - column: 'ts_us' | 'known_at_us', - field: 'ts' | 'known_at', - rowIndex: number -): bigint { - const raw = row[column]; - if (typeof raw === 'bigint') { - return raw; - } - if (typeof raw === 'string' && CANONICAL_SIGNED_INT_RE.test(raw)) { - return BigInt(raw); - } - if (typeof raw === 'number' && Number.isSafeInteger(raw)) { - return BigInt(raw); - } - throw new MarketDataStoreValidationError( - `Invalid bars_1m timestamp column "${column}" in result row ${rowIndex}: ${String(raw)}.`, - field - ); -} - -function microsToEpochMs( - us: bigint, - field: 'ts' | 'known_at', - rowIndex: number, - rounding: 'floor' | 'ceil' -): number { - const quotient = us / 1000n; - const remainder = us % 1000n; - const msBigInt = - rounding === 'ceil' - ? remainder > 0n - ? quotient + 1n - : quotient - : remainder < 0n - ? quotient - 1n - : quotient; - const ms = Number(msBigInt); - if (!Number.isSafeInteger(ms) || Math.abs(ms) > MAX_ECMASCRIPT_EPOCH_MS) { - throw new MarketDataStoreValidationError( - `Out-of-range bars_1m timestamp "${field}" (${us.toString()} us) in result row ${rowIndex}.`, - field - ); - } - return ms === 0 ? 0 : ms; -} - -function readRequiredFiniteNumber( - row: Record, - key: 'open' | 'high' | 'low' | 'close' | 'volume', - rowIndex: number -): number { - const val = row[key]; - if (typeof val !== 'number' || !Number.isFinite(val)) { - throw new MarketDataStoreValidationError( - `Invalid numeric column "${key}" in bars_1m result row ${rowIndex}: ${String(val)}.`, - key - ); - } - return val === 0 ? 0 : val; -} - -function readNullableFiniteNumber( - row: Record, - key: 'vwap', - rowIndex: number -): number | null { - const val = row[key]; - if (val === null || val === undefined) { - return null; - } - if (typeof val !== 'number' || !Number.isFinite(val)) { - throw new MarketDataStoreValidationError( - `Invalid nullable numeric column "${key}" in bars_1m result row ${rowIndex}: ${String(val)}.`, - key - ); - } - return val === 0 ? 0 : val; -} - -function mapBars1mRows( - rows: readonly Record[], - fence: FencedTimeRange, - requestedListingIds: ReadonlySet -): BarRecord[] { - const fromUs = BigInt(fence.fromMs) * 1000n; - const toUs = BigInt(fence.toMs) * 1000n; - const asOfUs = BigInt(fence.asOfMs) * 1000n; - - const out: BarRecord[] = new Array(rows.length); - for (let i = 0; i < rows.length; i += 1) { - const raw = rows[i]; - if (!isPlainRecord(raw)) { - throw new MarketDataStoreValidationError( - `Executor returned a non-object bar row at index ${i}.`, - 'rows' - ); - } - - const listingId = parseListingIdSymbol(raw, i, requestedListingIds); - const tsUs = parseTimestampMicros(raw, 'ts_us', 'ts', i); - if (tsUs < fromUs || tsUs > toUs) { - throw new MarketDataStoreValidationError( - `Row ${i} timestamp ts (${tsUs.toString()} us) is outside fenced range [${fromUs.toString()}, ${toUs.toString()}] us.`, - 'ts' - ); - } - - const knownAtUs = parseTimestampMicros(raw, 'known_at_us', 'known_at', i); - if (knownAtUs > asOfUs) { - throw new MarketDataStoreValidationError( - `Row ${i} availability timestamp known_at (${knownAtUs.toString()} us) exceeds fenced asOf (${asOfUs.toString()} us).`, - 'known_at' - ); - } - - out[i] = { - listingId, - ts: microsToEpochMs(tsUs, 'ts', i, 'floor'), - open: readRequiredFiniteNumber(raw, 'open', i), - high: readRequiredFiniteNumber(raw, 'high', i), - low: readRequiredFiniteNumber(raw, 'low', i), - close: readRequiredFiniteNumber(raw, 'close', i), - volume: readRequiredFiniteNumber(raw, 'volume', i), - vwap: readNullableFiniteNumber(raw, 'vwap', i), - // Round sub-millisecond availability up so replay never treats a bar as known before arrival. - knownAt: microsToEpochMs(knownAtUs, 'known_at', i, 'ceil'), - }; - } - - return out; -} - -/** - * Creates a read-only intraday `bars` reader backed by an injected - * {@link QuestDbQueryExecutor} over QuestDB `bars_1m`. - * - * Validates all inputs and applies the Vault fence before invoking - * `executor.query(...)`. Validates and maps all returned rows (including - * exact-microsecond defence-in-depth checks against `fence`) before yielding - * batches of at most `batchSize` rows (default `50_000`). - */ -export function createQuestDbIntradayBarsReader( - options: QuestDbIntradayBarsReaderOptions -): Pick { - if (!isPlainRecord(options)) { - throw new MarketDataStoreValidationError( - 'Expected a QuestDbIntradayBarsReaderOptions object.', - 'options' - ); - } - - const executor: unknown = options.executor; - if (!isPlainRecord(executor) || typeof executor.query !== 'function') { - throw new MarketDataStoreValidationError( - 'Expected `executor` with a `query(sql, params)` method.', - 'executor' - ); - } - const typedExecutor = executor as unknown as QuestDbQueryExecutor; - - const vaultCutoffTs = validateVaultCutoffTs(options.vaultCutoffTs); - - if ( - options.vaultOperatorAuthorized !== undefined && - typeof options.vaultOperatorAuthorized !== 'boolean' - ) { - throw new MarketDataStoreValidationError( - `Invalid vaultOperatorAuthorized "${String(options.vaultOperatorAuthorized)}". Expected a boolean.`, - 'vaultOperatorAuthorized' - ); - } - - const batchSize = - options.batchSize === undefined ? DEFAULT_QUESTDB_BARS_BATCH_SIZE : options.batchSize; - if (typeof batchSize !== 'number' || !Number.isSafeInteger(batchSize) || batchSize < 1) { - throw new MarketDataStoreValidationError( - `Invalid batchSize "${String(options.batchSize)}". Expected a positive safe integer.`, - 'batchSize' - ); - } - - const planCtx: VaultFenceContext = { - vaultCutoffTs, - vaultOperatorAuthorized: options.vaultOperatorAuthorized === true, - }; - - return { - async *bars(q: QuestDbBars1mQuery): AsyncIterable { - const { planned, requestedListingIds } = planBars1mQueryInternal(q, planCtx); - const result: unknown = await typedExecutor.query(planned.sql, [...planned.params]); - if (!isPlainRecord(result) || !Array.isArray(result.rows)) { - throw new MarketDataStoreValidationError( - 'Executor returned a malformed result; expected `{ rows: Record[] }`.', - 'rows' - ); - } - - const mapped = mapBars1mRows( - result.rows as readonly Record[], - planned.fence, - requestedListingIds - ); - if (mapped.length === 0) { - return; - } - if (mapped.length <= batchSize) { - yield { rows: mapped }; - return; - } - for (let offset = 0; offset < mapped.length; offset += batchSize) { - yield { rows: mapped.slice(offset, offset + batchSize) }; - } - }, - }; -} diff --git a/libs/research/src/market-data-store-routed.ts b/libs/research/src/market-data-store-routed.ts deleted file mode 100644 index a7b52608..00000000 --- a/libs/research/src/market-data-store-routed.ts +++ /dev/null @@ -1,192 +0,0 @@ -/** - * Pure, dependency-free `MarketDataStore` router that dispatches intraday - * `bars` queries (`timeframe: '1m'`) to an injected intraday reader (such as - * {@link createQuestDbIntradayBarsReader}) and routes every other `bars` - * timeframe and all other `MarketDataStore` methods to the injected daily - * store (such as {@link createDuckDbMarketDataStore}). - * - * Browser-safe and dependency-free: zero `node:*` imports, zero bare `process` - * access, and no database or filesystem I/O. - * - * Vault & point-in-time semantics: - * - This router adds no Vault logic of its own; each delegate continues to - * enforce its own Vault holdout fence and point-in-time predicates. - * - Callers MUST construct both `daily` and `intraday` with the exact same - * `vaultCutoffTs` and `vaultOperatorAuthorized` values (and pass the same - * `vaultCutoffTs` to MCP tools such as `createQueryDataTool`, which is - * always Vault-fenced) so the holdout boundary is identical across - * timeframes. - * - The QuestDB intraday reader (`createQuestDbIntradayBarsReader`) supports - * split-unadjusted `adjustment: 'raw'` `1m` bars; non-`'raw'` `1m` requests - * and unsupported timeframes (`'5m'`, `'1h'`) are handled by the respective - * delegate without modification. - */ - -import { type MarketDataStore, MarketDataStoreValidationError } from './market-data-store'; - -/** Configuration for {@link createRoutedMarketDataStore}. */ -export interface RoutedMarketDataStoreOptions { - /** Backing store for daily (`'1d'`) and non-`'1m'` bars plus all other `MarketDataStore` methods. */ - readonly daily: MarketDataStore; - /** Backing intraday reader for `bars` queries with `timeframe: '1m'`. */ - readonly intraday: Pick; -} - -const REQUIRED_DAILY_METHODS = [ - 'bars', - 'crossSection', - 'fundamentalsAsOf', - 'events', - 'shortsAsOf', - 'macroAsOf', - 'fx', - 'universe', -] as const satisfies readonly (keyof MarketDataStore)[]; - -function isPlainObject(value: unknown): value is Record { - if (typeof value !== 'object' || value === null) { - return false; - } - const proto: unknown = Object.getPrototypeOf(value); - return proto === Object.prototype || proto === null; -} - -function isDelegateObject(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value); -} - -function isIntraday1mBarsQuery(q: unknown): boolean { - return ( - typeof q === 'object' && - q !== null && - !Array.isArray(q) && - (q as { readonly timeframe?: unknown }).timeframe === '1m' - ); -} - -/** - * Composes a daily `MarketDataStore` and an intraday `bars` reader into a - * single read-only `MarketDataStore`. - * - * Routing rules: - * - `bars(q)` with `q.timeframe === '1m'` delegates directly to - * `options.intraday.bars(q)` and returns its `AsyncIterable` - * unchanged (preserving receiver, query identity, lazy iteration, and error - * timing). - * - `bars(q)` with any other timeframe (`'1d'`, `'5m'`, `'1h'`, or malformed - * runtime inputs) delegates directly to `options.daily.bars(q)`. - * - All other `MarketDataStore` methods (`crossSection`, `fundamentalsAsOf`, - * `events`, `shortsAsOf`, `macroAsOf`, `fx`, `universe`) delegate directly - * to `options.daily` and return its original promise. - * - * Vault fence note: - * Both `daily` and `intraday` MUST be constructed with the exact same - * `vaultCutoffTs` and `vaultOperatorAuthorized` settings. The QuestDB intraday - * reader serves raw (`adjustment: 'raw'`) `1m` bars. - * - * @example - * ```ts - * const vaultCutoffTs = Date.UTC(2025, 6, 1, 0, 0, 0, 0); - * const vaultOperatorAuthorized = false; - * - * const daily = createDuckDbMarketDataStore({ - * executor: duckDbExecutor, - * curatedRoot: '/mnt/data/stockbot/curated', - * vaultCutoffTs, - * vaultOperatorAuthorized, - * }); - * const intraday = createQuestDbIntradayBarsReader({ - * executor: questDbExecutor, - * vaultCutoffTs, - * vaultOperatorAuthorized, - * }); - * const store = createRoutedMarketDataStore({ daily, intraday }); - * // `createQueryDataTool` is always Vault-fenced and accepts only `vaultCutoffTs`. - * const queryDataTool = createQueryDataTool({ - * store, - * vaultContext: { vaultCutoffTs }, - * }); - * ``` - */ -export function createRoutedMarketDataStore( - options: RoutedMarketDataStoreOptions -): MarketDataStore { - if (!isPlainObject(options)) { - throw new MarketDataStoreValidationError( - 'Expected a plain RoutedMarketDataStoreOptions object.', - 'options' - ); - } - - const rawDaily: unknown = options.daily; - if (!isDelegateObject(rawDaily)) { - throw new MarketDataStoreValidationError( - 'Expected `daily` to be a MarketDataStore object.', - 'daily' - ); - } - - for (const method of REQUIRED_DAILY_METHODS) { - if (typeof rawDaily[method] !== 'function') { - throw new MarketDataStoreValidationError( - `Expected \`daily.${method}\` to be a function.`, - `daily.${method}` - ); - } - } - - const rawIntraday: unknown = options.intraday; - if (!isDelegateObject(rawIntraday)) { - throw new MarketDataStoreValidationError( - 'Expected `intraday` to be an object with a `bars` method.', - 'intraday' - ); - } - - if (typeof rawIntraday.bars !== 'function') { - throw new MarketDataStoreValidationError( - 'Expected `intraday.bars` to be a function.', - 'intraday.bars' - ); - } - - const daily = options.daily; - const intraday = options.intraday; - - return { - bars(q) { - if (isIntraday1mBarsQuery(q)) { - return intraday.bars(q); - } - return daily.bars(q); - }, - - crossSection(q) { - return daily.crossSection(q); - }, - - fundamentalsAsOf(q) { - return daily.fundamentalsAsOf(q); - }, - - events(q) { - return daily.events(q); - }, - - shortsAsOf(q) { - return daily.shortsAsOf(q); - }, - - macroAsOf(q) { - return daily.macroAsOf(q); - }, - - fx(q) { - return daily.fx(q); - }, - - universe(q) { - return daily.universe(q); - }, - }; -} diff --git a/libs/research/src/mcp/adapters/bar-session-dates.ts b/libs/research/src/mcp/adapters/bar-session-dates.ts deleted file mode 100644 index d87b1219..00000000 --- a/libs/research/src/mcp/adapters/bar-session-dates.ts +++ /dev/null @@ -1,278 +0,0 @@ -/** - * Bar-derived {@link SessionDatesPort} adapter for the MCP copilot `event_study` - * exchange-calendar resolver (`createExchangeCalendarResolver`). - * - * Pure, dependency-free, and browser-safe: zero `node:*` imports, zero bare - * `process` access, no `pg` dependency, and no DuckDB driver import. - * - * Daily bar timestamp convention: - * - In `libs/research/src/market-data-store-duckdb.ts`, `planBars1dQuery` - * projects `epoch_ms(b.ts) AS ts` and `mapBarRows` validates it as an integer - * UTC epoch millisecond value on `BarRecord.ts`. - * - In `tools/curate-etl/src/curate_bars.rs`, curated daily bars are stamped at - * `16:00:00 America/New_York` (`16:00 ET`), which converts to `20:00:00Z` - * (EDT) or `21:00:00Z` (EST) on the same UTC calendar date. - * - Therefore, `Math.floor(bar.ts / MS_PER_DAY)` yields the session's integer - * UTC day key (`formatDayKeyUtc`). Close timestamps and optional early-close - * overrides remain owned by `createExchangeCalendarResolver`. - * - * Vault fence behavior: - * - Queries `store.bars` with `timeframe: '1d'` and `adjustment: 'raw'`, - * omitting `scope` and `asOf` so the injected store applies its default - * `'vault_fenced'` scope. Never passes `'vault_evaluation_only'`. - * - Errors thrown by the store (including `VaultHoldoutFenceError`) propagate - * unchanged. - */ - -import type { MarketDataStore } from '../../market-data-store'; -import { - MS_PER_DAY, - formatDayKeyUtc, - isPlainRecord, - isValidEpochMs, - isValidInt32, - parseCalendarDayKey, -} from '../../panel-shared'; -import type { SessionDatesPort, SessionDatesQuery } from './exchange-calendars'; - -/** Error codes thrown by {@link BarSessionDatesError}. */ -export type BarSessionDatesErrorCode = - | 'invalid_options' - | 'unknown_calendar' - | 'invalid_query' - | 'invalid_bar'; - -/** Optional error constructor metadata for {@link BarSessionDatesError}. */ -export interface BarSessionDatesErrorOptions { - readonly cause?: unknown; -} - -/** Typed fail-closed error thrown by {@link createBarSessionDatesPort}. */ -export class BarSessionDatesError extends RangeError { - readonly code: BarSessionDatesErrorCode; - override readonly cause?: unknown; - - constructor( - code: BarSessionDatesErrorCode, - message: string, - options?: BarSessionDatesErrorOptions - ) { - super(message, options?.cause !== undefined ? { cause: options.cause } : undefined); - this.name = 'BarSessionDatesError'; - this.code = code; - if (options?.cause !== undefined) { - this.cause = options.cause; - } - Object.setPrototypeOf(this, new.target.prototype); - } -} - -/** Factory options for {@link createBarSessionDatesPort}. */ -export interface BarSessionDatesPortOptions { - readonly store: Pick; - /** - * Caller-configured reference listing IDs per `exchange.calendar_code` - * (e.g. `XNYS`, `XTSE`). The union of their daily bars defines the exchange's - * session dates. - */ - readonly referenceListingIds: Readonly>; -} - -interface CalendarReferenceConfig { - readonly listingIds: readonly number[]; - readonly listingIdSet: ReadonlySet; -} - -function isPlainObjectRecord(value: unknown): value is Record { - if (typeof value !== 'object' || value === null) { - return false; - } - const proto: unknown = Object.getPrototypeOf(value); - return proto === Object.prototype || proto === null; -} - -function parseQueryDayKey(value: unknown, field: string): number { - return parseCalendarDayKey(value, field, (message, cause) => - new BarSessionDatesError( - 'invalid_query', - message, - cause !== undefined ? { cause } : undefined - ) - ); -} - -function validateOptions(options: BarSessionDatesPortOptions): { - readonly store: Pick; - readonly calendars: ReadonlyMap; -} { - if (!isPlainRecord(options)) { - throw new BarSessionDatesError( - 'invalid_options', - 'Invalid options: expected an object with store and referenceListingIds.' - ); - } - - const { store, referenceListingIds } = options; - if (typeof store !== 'object' || store === null || typeof store.bars !== 'function') { - throw new BarSessionDatesError( - 'invalid_options', - 'Invalid "store": expected an object with a callable bars(query) method.' - ); - } - - if (!isPlainObjectRecord(referenceListingIds)) { - throw new BarSessionDatesError( - 'invalid_options', - 'Invalid "referenceListingIds": expected a plain object mapping calendar codes to positive INT32 listing ID arrays.' - ); - } - - const calendars = new Map(); - const entries = Object.entries(referenceListingIds); - - for (let i = 0; i < entries.length; i += 1) { - const [calendarCode, rawIds] = entries[i] as [string, unknown]; - if (calendarCode.trim().length === 0 || calendarCode !== calendarCode.trim()) { - throw new BarSessionDatesError( - 'invalid_options', - `Invalid "referenceListingIds" calendar code "${calendarCode}": expected a non-empty trimmed string.` - ); - } - - if (!Array.isArray(rawIds) || rawIds.length === 0) { - throw new BarSessionDatesError( - 'invalid_options', - `Invalid "referenceListingIds.${calendarCode}": expected a non-empty array of positive 32-bit integer listing IDs.` - ); - } - - const copiedIds: number[] = []; - const idSet = new Set(); - - for (let j = 0; j < rawIds.length; j += 1) { - const id: unknown = rawIds[j]; - if (!isValidInt32(id) || id <= 0) { - throw new BarSessionDatesError( - 'invalid_options', - `Invalid "referenceListingIds.${calendarCode}[${j}]": expected a positive 32-bit integer, got ${String(id)}.` - ); - } - if (idSet.has(id)) { - throw new BarSessionDatesError( - 'invalid_options', - `Duplicate listing ID ${id} in "referenceListingIds.${calendarCode}".` - ); - } - idSet.add(id); - copiedIds.push(id); - } - - calendars.set(calendarCode, { - listingIds: copiedIds, - listingIdSet: idSet, - }); - } - - return { store, calendars }; -} - -/** - * Creates a {@link SessionDatesPort} backed by Vault-fenced daily bars - * (`timeframe: '1d'`, `adjustment: 'raw'`) for caller-configured reference - * listings per `exchange.calendar_code`. - */ -export function createBarSessionDatesPort( - options: BarSessionDatesPortOptions -): SessionDatesPort { - const { store, calendars } = validateOptions(options); - - return { - async listSessionDates(query: SessionDatesQuery): Promise { - if (!isPlainRecord(query)) { - throw new BarSessionDatesError( - 'invalid_query', - 'Invalid query: expected an object with calendarCode, fromDate, and toDate.' - ); - } - - if (typeof query.calendarCode !== 'string') { - throw new BarSessionDatesError( - 'invalid_query', - 'Invalid "calendarCode": expected a string.' - ); - } - - const config = calendars.get(query.calendarCode); - if (config === undefined) { - throw new BarSessionDatesError( - 'unknown_calendar', - `No reference listings configured for calendarCode "${query.calendarCode}".` - ); - } - - const fromDayKey = parseQueryDayKey(query.fromDate, 'fromDate'); - const toDayKey = parseQueryDayKey(query.toDate, 'toDate'); - if (fromDayKey > toDayKey) { - throw new BarSessionDatesError( - 'invalid_query', - `Invalid date window: fromDate "${query.fromDate}" is after toDate "${query.toDate}".` - ); - } - - const dayKeys = new Set(); - const stream = store.bars({ - listingIds: config.listingIds.slice(), - timeframe: '1d', - from: query.fromDate, - to: query.toDate, - adjustment: 'raw', - }); - - for await (const batch of stream) { - if (!isPlainRecord(batch) || !Array.isArray(batch.rows)) { - throw new BarSessionDatesError( - 'invalid_bar', - 'Invalid bar batch: expected an object with a rows array.' - ); - } - - const rows = batch.rows; - for (let i = 0; i < rows.length; i += 1) { - const bar: unknown = rows[i]; - if (!isPlainRecord(bar)) { - throw new BarSessionDatesError( - 'invalid_bar', - `Invalid bar row at index ${i}: expected a plain object.` - ); - } - - if (!isValidEpochMs(bar.ts)) { - throw new BarSessionDatesError( - 'invalid_bar', - `Invalid bar timestamp at index ${i}: expected a finite integer epoch ms, got ${String(bar.ts)}.` - ); - } - - if (!isValidInt32(bar.listingId) || !config.listingIdSet.has(bar.listingId)) { - throw new BarSessionDatesError( - 'invalid_bar', - `Unexpected bar listingId ${String(bar.listingId)} for calendarCode "${query.calendarCode}".` - ); - } - - const dayKey = Math.floor(bar.ts / MS_PER_DAY); - if (dayKey >= fromDayKey && dayKey <= toDayKey) { - dayKeys.add(dayKey); - } - } - } - - if (dayKeys.size === 0) { - return []; - } - - const sortedDayKeys = Array.from(dayKeys).sort((a, b) => a - b); - return sortedDayKeys.map(formatDayKeyUtc); - }, - }; -} diff --git a/libs/research/src/mcp/adapters/exchange-calendars.ts b/libs/research/src/mcp/adapters/exchange-calendars.ts deleted file mode 100644 index 801230f6..00000000 --- a/libs/research/src/mcp/adapters/exchange-calendars.ts +++ /dev/null @@ -1,749 +0,0 @@ -/** - * Exchange-calendar resolver and read-only PostgreSQL listing-calendar adapter - * for the MCP copilot `event_study` tool (`EventStudyExchangeCalendarResolver`). - * - * Pure, dependency-free, and browser-safe: zero `node:*` imports, zero bare - * `process` access, and no runtime `pg` dependency. - * - * Eastern Time DST schedule (`1976-01-01..=2030-12-31`, matching - * `tools/curate-etl/src/session_close.rs` for `America/New_York` / - * `America/Toronto`): - * - `1976..=1986`: last Sunday of April -> last Sunday of October. - * - `1987..=2006`: first Sunday of April -> last Sunday of October. - * - `2007..=2030`: second Sunday of March -> first Sunday of November. - * - * Using the session-date convention (inclusive spring boundary, exclusive fall - * boundary), EDT is `UTC-4` and EST is `UTC-5`. - */ - -import type { - EventStudyExchangeCalendars, - ExchangeSessionClose, -} from '../../event-panel'; -import { - MS_PER_DAY, - isPlainRecord, - isValidInt32, - parseCalendarDayKey, -} from '../../panel-shared'; -import type { - EventStudyExchangeCalendarQuery, - EventStudyExchangeCalendarResolver, -} from '../tools/event-study'; - -const SCHEMA_IDENT_RE = /^[a-z_][a-z0-9_]*$/; -const MS_PER_MINUTE = 60_000; -const EDT_UTC_OFFSET_MINUTES = 4 * 60; -const EST_UTC_OFFSET_MINUTES = 5 * 60; - -/** First Gregorian year supported by the Eastern Time DST schedule. */ -export const EXCHANGE_CALENDAR_MIN_SUPPORTED_YEAR = 1976; - -/** Last Gregorian year supported by the Eastern Time DST schedule. */ -export const EXCHANGE_CALENDAR_MAX_SUPPORTED_YEAR = 2030; - -/** Inclusive lower bound (`YYYY-MM-DD`) of the supported Eastern Time DST schedule. */ -export const EXCHANGE_CALENDAR_MIN_SUPPORTED_DATE = '1976-01-01'; - -/** Inclusive upper bound (`YYYY-MM-DD`) of the supported Eastern Time DST schedule. */ -export const EXCHANGE_CALENDAR_MAX_SUPPORTED_DATE = '2030-12-31'; - -/** Default Eastern Time close minute of day (`16:00 ET` = `960`). */ -export const EXCHANGE_CALENDAR_DEFAULT_CLOSE_MINUTE_ET = 16 * 60; - -/** Minimum allowed Eastern Time early-close override minute of day (`00:01 ET`). */ -export const EXCHANGE_CALENDAR_MIN_CLOSE_MINUTE_ET = 1; - -/** Maximum allowed Eastern Time close minute of day (`16:00 ET`). */ -export const EXCHANGE_CALENDAR_MAX_CLOSE_MINUTE_ET = 16 * 60; - -/** Epoch day for `1976-01-01` (`Date.UTC(1976, 0, 1) / MS_PER_DAY`). */ -const MIN_SUPPORTED_DAY_KEY = 2_191; - -/** Epoch day for `2030-12-31` (`Date.UTC(2030, 11, 31) / MS_PER_DAY`). */ -const MAX_SUPPORTED_DAY_KEY = 22_279; - -const SUPPORTED_YEAR_COUNT = - EXCHANGE_CALENDAR_MAX_SUPPORTED_YEAR - EXCHANGE_CALENDAR_MIN_SUPPORTED_YEAR + 1; - -/** Error codes thrown by {@link PostgresListingCalendarError}. */ -export type PostgresListingCalendarErrorCode = - | 'INVALID_EXECUTOR' - | 'INVALID_SCHEMA' - | 'INVALID_ROW'; - -/** Typed validation error thrown by the PostgreSQL listing-calendar adapter. */ -export class PostgresListingCalendarError extends RangeError { - readonly code: PostgresListingCalendarErrorCode; - - constructor(code: PostgresListingCalendarErrorCode, message: string) { - super(message); - this.name = 'PostgresListingCalendarError'; - this.code = code; - Object.setPrototypeOf(this, new.target.prototype); - } -} - -/** Error codes thrown by {@link ExchangeCalendarResolverError}. */ -export type ExchangeCalendarResolverErrorCode = - | 'INVALID_OPTION' - | 'INVALID_QUERY' - | 'UNSUPPORTED_DATE' - | 'INVALID_LISTING_CALENDAR_ROW' - | 'MISSING_LISTING_CALENDAR' - | 'UNEXPECTED_LISTING_CALENDAR' - | 'CONFLICTING_LISTING_CALENDAR' - | 'INVALID_SESSION_DATES'; - -/** Optional error constructor metadata for {@link ExchangeCalendarResolverError}. */ -export interface ExchangeCalendarResolverErrorOptions { - readonly cause?: unknown; -} - -/** Typed validation and fail-closed integrity error thrown by {@link createExchangeCalendarResolver}. */ -export class ExchangeCalendarResolverError extends RangeError { - readonly code: ExchangeCalendarResolverErrorCode; - override readonly cause?: unknown; - - constructor( - code: ExchangeCalendarResolverErrorCode, - message: string, - options?: ExchangeCalendarResolverErrorOptions - ) { - super(message, options?.cause !== undefined ? { cause: options.cause } : undefined); - this.name = 'ExchangeCalendarResolverError'; - this.code = code; - if (options?.cause !== undefined) { - this.cause = options.cause; - } - Object.setPrototypeOf(this, new.target.prototype); - } -} - -/** - * Structural `pg.Pool` / `pg.PoolClient`-compatible query interface so this module - * has no runtime dependency on `pg` and is unit-testable with a fake executor. - */ -export interface ListingCalendarExecutor { - query>( - text: string, - params?: readonly unknown[] - ): Promise<{ readonly rows: readonly Row[] }>; -} - -/** Factory options for {@link createPostgresListingCalendarPort}. */ -export interface PostgresListingCalendarPortOptions { - readonly executor: ListingCalendarExecutor; - /** Optional PostgreSQL schema name (`^[a-z_][a-z0-9_]*$`); defaults to the executor's `search_path`. */ - readonly schema?: string; -} - -/** One listing-to-exchange-calendar mapping row returned by {@link ListingCalendarPort}. */ -export interface ListingCalendarRow { - readonly listingId: number; - readonly calendarCode: string; -} - -/** Injected port resolving `listingId` -> `exchange.calendar_code`. */ -export interface ListingCalendarPort { - getListingCalendars( - listingIds: readonly number[] - ): Promise | readonly ListingCalendarRow[]; -} - -/** Query passed to {@link SessionDatesPort.listSessionDates}. */ -export interface SessionDatesQuery { - readonly calendarCode: string; - readonly fromDate: string; - readonly toDate: string; -} - -/** - * Injected port supplying strictly ascending, unique `YYYY-MM-DD` exchange session - * dates inside `[fromDate, toDate]` for one exchange calendar code. - */ -export interface SessionDatesPort { - listSessionDates(query: SessionDatesQuery): Promise | readonly string[]; -} - -/** - * Optional caller-supplied early-close overrides keyed by - * `{ [calendarCode]: { [YYYY-MM-DD]: minuteOfDayEastern } }`, where - * `minuteOfDayEastern` is an integer in `(0, 960]` (e.g. `780` = `13:00 ET`). - */ -export type EarlyCloseOverrides = Readonly>>>; - -/** Factory options for {@link createExchangeCalendarResolver}. */ -export interface ExchangeCalendarResolverOptions { - readonly listingCalendars: ListingCalendarPort; - readonly sessionDates: SessionDatesPort; - readonly earlyCloses?: EarlyCloseOverrides; -} - -interface RawListingCalendarRow { - readonly listing_id: unknown; - readonly calendar_code: unknown; -} - -interface DstBoundsTable { - readonly startDay: Int32Array; - readonly endDay: Int32Array; -} - -let cachedDstBounds: DstBoundsTable | null = null; - -/** ISO-8601 weekday for an epoch day: `1 = Monday`, ..., `7 = Sunday`. */ -function isoWeekday(epochDay: number): number { - // 1970-01-01 (epochDay === 0) was Thursday (ISO 4). - return (((epochDay + 3) % 7) + 7) % 7 + 1; -} - -function ymdToEpochDay(year: number, month: number, day: number): number { - return Date.UTC(year, month - 1, day) / MS_PER_DAY; -} - -function nthSundayOfMonth(year: number, month: number, nth: number): number { - const first = ymdToEpochDay(year, month, 1); - const firstWd = isoWeekday(first); - const delta = (7 - firstWd) % 7; - return first + delta + (nth - 1) * 7; -} - -function lastSundayOfMonth(year: number, month: number): number { - const nextYear = month === 12 ? year + 1 : year; - const nextMonth = month === 12 ? 1 : month + 1; - const last = ymdToEpochDay(nextYear, nextMonth, 1) - 1; - const lastWd = isoWeekday(last); - return last - (lastWd % 7); -} - -function getDstBoundsTable(): DstBoundsTable { - if (cachedDstBounds !== null) { - return cachedDstBounds; - } - - const startDay = new Int32Array(SUPPORTED_YEAR_COUNT); - const endDay = new Int32Array(SUPPORTED_YEAR_COUNT); - - for ( - let year = EXCHANGE_CALENDAR_MIN_SUPPORTED_YEAR; - year <= EXCHANGE_CALENDAR_MAX_SUPPORTED_YEAR; - year += 1 - ) { - let dstStart: number; - let dstEnd: number; - if (year <= 1986) { - dstStart = lastSundayOfMonth(year, 4); - dstEnd = lastSundayOfMonth(year, 10); - } else if (year <= 2006) { - dstStart = nthSundayOfMonth(year, 4, 1); - dstEnd = lastSundayOfMonth(year, 10); - } else { - dstStart = nthSundayOfMonth(year, 3, 2); - dstEnd = nthSundayOfMonth(year, 11, 1); - } - const idx = year - EXCHANGE_CALENDAR_MIN_SUPPORTED_YEAR; - startDay[idx] = dstStart; - endDay[idx] = dstEnd; - } - - cachedDstBounds = { startDay, endDay }; - return cachedDstBounds; -} - -function assertSupportedDayKey(dayKey: number, dateStr: string, field: string): void { - if (dayKey < MIN_SUPPORTED_DAY_KEY || dayKey > MAX_SUPPORTED_DAY_KEY) { - throw new ExchangeCalendarResolverError( - 'UNSUPPORTED_DATE', - `Unsupported "${field}" date "${dateStr}": must fall within ${EXCHANGE_CALENDAR_MIN_SUPPORTED_DATE}..=${EXCHANGE_CALENDAR_MAX_SUPPORTED_DATE}.` - ); - } -} - -function easternSessionCloseUtcMs(dayKey: number, closeMinuteEt: number): number { - const year = new Date(dayKey * MS_PER_DAY).getUTCFullYear(); - const table = getDstBoundsTable(); - const idx = year - EXCHANGE_CALENDAR_MIN_SUPPORTED_YEAR; - const isEdt = - dayKey >= (table.startDay[idx] as number) && dayKey < (table.endDay[idx] as number); - const utcOffsetMinutes = isEdt ? EDT_UTC_OFFSET_MINUTES : EST_UTC_OFFSET_MINUTES; - return dayKey * MS_PER_DAY + (closeMinuteEt + utcOffsetMinutes) * MS_PER_MINUTE; -} - -function defineDataProperty(target: Record, key: string, value: T): void { - Object.defineProperty(target, key, { - value, - enumerable: true, - writable: true, - configurable: true, - }); -} - -function buildListingCalendarSql(schemaPrefix: string): string { - const listingTable = `${schemaPrefix}listing`; - const exchangeTable = `${schemaPrefix}exchange`; - - return [ - 'SELECT', - ' l.listing_id AS listing_id,', - ' e.calendar_code AS calendar_code', - `FROM ${listingTable} l`, - `INNER JOIN ${exchangeTable} e ON e.mic = l.mic`, - 'WHERE l.listing_id = ANY($1::integer[])', - 'ORDER BY l.listing_id ASC', - ].join('\n'); -} - -function validatePostgresFactoryOptions(options: PostgresListingCalendarPortOptions): { - readonly executor: ListingCalendarExecutor; - readonly schemaPrefix: string; -} { - if (typeof options !== 'object' || options === null) { - throw new PostgresListingCalendarError( - 'INVALID_EXECUTOR', - 'Invalid options: expected an object with a ListingCalendarExecutor.' - ); - } - - const { executor, schema } = options; - if (typeof executor !== 'object' || executor === null || typeof executor.query !== 'function') { - throw new PostgresListingCalendarError( - 'INVALID_EXECUTOR', - 'Invalid executor: expected an object with a callable query(text, params?) method.' - ); - } - - if (schema === undefined) { - return { executor, schemaPrefix: '' }; - } - - if (typeof schema !== 'string' || !SCHEMA_IDENT_RE.test(schema)) { - throw new PostgresListingCalendarError( - 'INVALID_SCHEMA', - 'Invalid schema: expected an identifier matching ^[a-z_][a-z0-9_]*$.' - ); - } - - return { executor, schemaPrefix: `"${schema}".` }; -} - -function mapRawListingCalendarRow(raw: unknown): ListingCalendarRow { - if (!isPlainRecord(raw)) { - throw new PostgresListingCalendarError( - 'INVALID_ROW', - 'Invalid security-master row: expected a non-null plain object.' - ); - } - - const row = raw as unknown as RawListingCalendarRow; - if (!isValidInt32(row.listing_id)) { - throw new PostgresListingCalendarError( - 'INVALID_ROW', - 'Invalid security-master row: "listing_id" must be a safe 32-bit integer.' - ); - } - - if (typeof row.calendar_code !== 'string' || row.calendar_code.trim().length === 0) { - throw new PostgresListingCalendarError( - 'INVALID_ROW', - 'Invalid security-master row: "calendar_code" must be a non-empty string.' - ); - } - - return { - listingId: row.listing_id, - calendarCode: row.calendar_code.trim(), - }; -} - -/** - * Creates a read-only PostgreSQL {@link ListingCalendarPort} backed by the M1 - * security master (`listing` joined to `exchange` on `mic`), binding listing IDs - * as a single `$1::integer[]` parameter. - */ -export function createPostgresListingCalendarPort( - options: PostgresListingCalendarPortOptions -): ListingCalendarPort { - const { executor, schemaPrefix } = validatePostgresFactoryOptions(options); - const sql = buildListingCalendarSql(schemaPrefix); - - return { - async getListingCalendars( - listingIds: readonly number[] - ): Promise { - if (!Array.isArray(listingIds)) { - throw new PostgresListingCalendarError( - 'INVALID_ROW', - 'Invalid listingIds: expected an array of 32-bit integers.' - ); - } - - const boundIds: number[] = []; - for (let i = 0; i < listingIds.length; i += 1) { - const id = listingIds[i]; - if (!isValidInt32(id)) { - throw new PostgresListingCalendarError( - 'INVALID_ROW', - `Invalid listingIds[${i}]: expected a safe 32-bit integer.` - ); - } - boundIds.push(id); - } - - if (boundIds.length === 0) { - return []; - } - - const result = await executor.query(sql, [boundIds]); - if (typeof result !== 'object' || result === null || !Array.isArray(result.rows)) { - throw new PostgresListingCalendarError( - 'INVALID_ROW', - 'Invalid executor response: expected an object with a rows array.' - ); - } - - const mapped: ListingCalendarRow[] = []; - for (let i = 0; i < result.rows.length; i += 1) { - mapped.push(mapRawListingCalendarRow(result.rows[i])); - } - return mapped; - }, - }; -} - -function parseResolverDayKey( - value: unknown, - field: string, - code: 'INVALID_OPTION' | 'INVALID_QUERY' | 'INVALID_SESSION_DATES' -): number { - return parseCalendarDayKey(value, field, (message, cause) => - new ExchangeCalendarResolverError( - code, - message, - cause !== undefined ? { cause } : undefined - ) - ); -} - -function isPlainObjectRecord(value: unknown): value is Record { - if (typeof value !== 'object' || value === null) { - return false; - } - const proto: unknown = Object.getPrototypeOf(value); - return proto === Object.prototype || proto === null; -} - -function parseEarlyCloses( - raw: unknown -): Map> { - const result = new Map>(); - if (raw === undefined) { - return result; - } - if (!isPlainObjectRecord(raw)) { - throw new ExchangeCalendarResolverError( - 'INVALID_OPTION', - 'Invalid "earlyCloses": expected a plain object mapping calendarCode to { [YYYY-MM-DD]: minuteOfDay }.' - ); - } - - const calendarEntries = Object.entries(raw); - for (let i = 0; i < calendarEntries.length; i += 1) { - const [calendarCode, rawDates] = calendarEntries[i] as [string, unknown]; - if (calendarCode.trim().length === 0 || calendarCode !== calendarCode.trim()) { - throw new ExchangeCalendarResolverError( - 'INVALID_OPTION', - `Invalid "earlyCloses" calendar code "${calendarCode}": expected a non-blank trimmed string.` - ); - } - if (!isPlainObjectRecord(rawDates)) { - throw new ExchangeCalendarResolverError( - 'INVALID_OPTION', - `Invalid "earlyCloses.${calendarCode}": expected a plain object mapping YYYY-MM-DD dates to Eastern close minutes.` - ); - } - - const dateOverrides = new Map(); - const dateEntries = Object.entries(rawDates); - for (let j = 0; j < dateEntries.length; j += 1) { - const [dateStr, minute] = dateEntries[j] as [string, unknown]; - const field = `earlyCloses.${calendarCode}["${dateStr}"]`; - const dayKey = parseResolverDayKey(dateStr, field, 'INVALID_OPTION'); - assertSupportedDayKey(dayKey, dateStr, field); - - if ( - typeof minute !== 'number' || - !Number.isSafeInteger(minute) || - minute < EXCHANGE_CALENDAR_MIN_CLOSE_MINUTE_ET || - minute > EXCHANGE_CALENDAR_MAX_CLOSE_MINUTE_ET - ) { - throw new ExchangeCalendarResolverError( - 'INVALID_OPTION', - `Invalid "${field}": expected an integer Eastern minute in (${EXCHANGE_CALENDAR_MIN_CLOSE_MINUTE_ET - 1}, ${EXCHANGE_CALENDAR_MAX_CLOSE_MINUTE_ET}], got ${String(minute)}.` - ); - } - - dateOverrides.set(dateStr, minute); - } - result.set(calendarCode, dateOverrides); - } - - return result; -} - -function validateResolverOptions(options: ExchangeCalendarResolverOptions): { - readonly listingCalendars: ListingCalendarPort; - readonly sessionDates: SessionDatesPort; - readonly earlyCloseMap: Map>; -} { - if (!isPlainRecord(options)) { - throw new ExchangeCalendarResolverError( - 'INVALID_OPTION', - 'Invalid options: expected an object with listingCalendars and sessionDates ports.' - ); - } - - const { listingCalendars, sessionDates, earlyCloses } = options; - if ( - typeof listingCalendars !== 'object' || - listingCalendars === null || - typeof listingCalendars.getListingCalendars !== 'function' - ) { - throw new ExchangeCalendarResolverError( - 'INVALID_OPTION', - 'Invalid "listingCalendars": expected an object with a callable getListingCalendars(listingIds) method.' - ); - } - - if ( - typeof sessionDates !== 'object' || - sessionDates === null || - typeof sessionDates.listSessionDates !== 'function' - ) { - throw new ExchangeCalendarResolverError( - 'INVALID_OPTION', - 'Invalid "sessionDates": expected an object with a callable listSessionDates({ calendarCode, fromDate, toDate }) method.' - ); - } - - const earlyCloseMap = parseEarlyCloses(earlyCloses); - return { listingCalendars, sessionDates, earlyCloseMap }; -} - -function compareAscii(a: string, b: string): number { - return a < b ? -1 : a > b ? 1 : 0; -} - -/** - * Creates an {@link EventStudyExchangeCalendarResolver} over injected - * {@link ListingCalendarPort} and {@link SessionDatesPort} implementations, - * converting each validated exchange session date into its UTC epoch-ms close - * timestamp (`16:00 ET` by default, or caller-supplied `earlyCloses` override). - */ -export function createExchangeCalendarResolver( - options: ExchangeCalendarResolverOptions -): EventStudyExchangeCalendarResolver { - const { listingCalendars, sessionDates, earlyCloseMap } = validateResolverOptions(options); - - return async function resolveExchangeCalendars( - query: EventStudyExchangeCalendarQuery - ): Promise { - if (!isPlainRecord(query)) { - throw new ExchangeCalendarResolverError( - 'INVALID_QUERY', - 'Invalid query: expected a plain object with listingIds, fromDate, and toDate.' - ); - } - - if (!Array.isArray(query.listingIds)) { - throw new ExchangeCalendarResolverError( - 'INVALID_QUERY', - 'Invalid "listingIds": expected an array of 32-bit integer listing IDs.' - ); - } - - if (query.listingIds.length === 0) { - return { - calendars: {}, - listingCalendarId: {}, - }; - } - - const fromDayKey = parseResolverDayKey(query.fromDate, 'fromDate', 'INVALID_QUERY'); - const toDayKey = parseResolverDayKey(query.toDate, 'toDate', 'INVALID_QUERY'); - if (fromDayKey > toDayKey) { - throw new ExchangeCalendarResolverError( - 'INVALID_QUERY', - `Invalid date window: fromDate "${query.fromDate}" is after toDate "${query.toDate}".` - ); - } - assertSupportedDayKey(fromDayKey, query.fromDate, 'fromDate'); - assertSupportedDayKey(toDayKey, query.toDate, 'toDate'); - - const requestedSet = new Set(); - for (let i = 0; i < query.listingIds.length; i += 1) { - const id: unknown = query.listingIds[i]; - if (!isValidInt32(id)) { - throw new ExchangeCalendarResolverError( - 'INVALID_QUERY', - `Invalid "listingIds[${i}]": expected a safe 32-bit integer.` - ); - } - requestedSet.add(id); - } - - const sortedListingIds = Array.from(requestedSet).sort((a, b) => a - b); - const rawMappings = await listingCalendars.getListingCalendars(sortedListingIds); - if (!Array.isArray(rawMappings)) { - throw new ExchangeCalendarResolverError( - 'INVALID_LISTING_CALENDAR_ROW', - 'Invalid listingCalendars response: expected an array of { listingId, calendarCode } rows.' - ); - } - - const listingToCalendar = new Map(); - for (let i = 0; i < rawMappings.length; i += 1) { - const row: unknown = rawMappings[i]; - if (!isPlainRecord(row)) { - throw new ExchangeCalendarResolverError( - 'INVALID_LISTING_CALENDAR_ROW', - `Invalid listingCalendars[${i}]: expected a plain object.` - ); - } - - const listingId = row.listingId; - const calendarCode = row.calendarCode; - if (!isValidInt32(listingId)) { - throw new ExchangeCalendarResolverError( - 'INVALID_LISTING_CALENDAR_ROW', - `Invalid listingCalendars[${i}].listingId: expected a safe 32-bit integer.` - ); - } - if ( - typeof calendarCode !== 'string' || - calendarCode.trim().length === 0 || - calendarCode !== calendarCode.trim() - ) { - throw new ExchangeCalendarResolverError( - 'INVALID_LISTING_CALENDAR_ROW', - `Invalid listingCalendars[${i}].calendarCode: expected a non-blank trimmed string.` - ); - } - - if (!requestedSet.has(listingId)) { - throw new ExchangeCalendarResolverError( - 'UNEXPECTED_LISTING_CALENDAR', - `Listing calendar port returned unrequested listingId ${listingId}.` - ); - } - - const existing = listingToCalendar.get(listingId); - if (existing !== undefined && existing !== calendarCode) { - throw new ExchangeCalendarResolverError( - 'CONFLICTING_LISTING_CALENDAR', - `Conflicting calendar codes for listingId ${listingId}: "${existing}" vs "${calendarCode}".` - ); - } - listingToCalendar.set(listingId, calendarCode); - } - - const missingIds: number[] = []; - for (let i = 0; i < sortedListingIds.length; i += 1) { - const id = sortedListingIds[i] as number; - if (!listingToCalendar.has(id)) { - missingIds.push(id); - } - } - if (missingIds.length > 0) { - throw new ExchangeCalendarResolverError( - 'MISSING_LISTING_CALENDAR', - `Missing exchange calendar mapping for listingId(s): ${missingIds.join(', ')}.` - ); - } - - const distinctCalendars = Array.from(new Set(listingToCalendar.values())).sort(compareAscii); - const sessionsByCalendar = new Map(); - - for (let c = 0; c < distinctCalendars.length; c += 1) { - const calendarCode = distinctCalendars[c] as string; - const rawDates = await sessionDates.listSessionDates({ - calendarCode, - fromDate: query.fromDate, - toDate: query.toDate, - }); - - if (!Array.isArray(rawDates)) { - throw new ExchangeCalendarResolverError( - 'INVALID_SESSION_DATES', - `Invalid session dates for "${calendarCode}": expected an array of YYYY-MM-DD strings.` - ); - } - - const overrides = earlyCloseMap.get(calendarCode); - const sessions: ExchangeSessionClose[] = []; - let prevDayKey = Number.NEGATIVE_INFINITY; - - for (let i = 0; i < rawDates.length; i += 1) { - const dateStr: unknown = rawDates[i]; - const field = `sessionDates["${calendarCode}"][${i}]`; - const dayKey = parseResolverDayKey(dateStr, field, 'INVALID_SESSION_DATES'); - const validDate = dateStr as string; - assertSupportedDayKey(dayKey, validDate, field); - - if (dayKey < fromDayKey || dayKey > toDayKey) { - throw new ExchangeCalendarResolverError( - 'INVALID_SESSION_DATES', - `Session date "${validDate}" for "${calendarCode}" is outside requested window [${query.fromDate}, ${query.toDate}].` - ); - } - if (dayKey === prevDayKey) { - throw new ExchangeCalendarResolverError( - 'INVALID_SESSION_DATES', - `Duplicate session date "${validDate}" for "${calendarCode}".` - ); - } - if (dayKey < prevDayKey) { - throw new ExchangeCalendarResolverError( - 'INVALID_SESSION_DATES', - `Session dates for "${calendarCode}" must be strictly ascending (saw "${validDate}" out of order).` - ); - } - - prevDayKey = dayKey; - const closeMinuteEt = - overrides?.get(validDate) ?? EXCHANGE_CALENDAR_DEFAULT_CLOSE_MINUTE_ET; - sessions.push({ - date: validDate, - closeTs: easternSessionCloseUtcMs(dayKey, closeMinuteEt), - }); - } - - sessionsByCalendar.set(calendarCode, sessions); - } - - const calendars: Record = {}; - for (let c = 0; c < distinctCalendars.length; c += 1) { - const calendarCode = distinctCalendars[c] as string; - defineDataProperty( - calendars, - calendarCode, - sessionsByCalendar.get(calendarCode) as readonly ExchangeSessionClose[] - ); - } - - const listingCalendarId: Record = {}; - for (let i = 0; i < sortedListingIds.length; i += 1) { - const id = sortedListingIds[i] as number; - defineDataProperty( - listingCalendarId as unknown as Record, - String(id), - listingToCalendar.get(id) as string - ); - } - - return { - calendars, - listingCalendarId, - }; - }; -} diff --git a/libs/research/src/mcp/adapters/library-cards.ts b/libs/research/src/mcp/adapters/library-cards.ts deleted file mode 100644 index 92935689..00000000 --- a/libs/research/src/mcp/adapters/library-cards.ts +++ /dev/null @@ -1,883 +0,0 @@ -/** - * Read-only filesystem adapter for the MCP copilot `read_knowledge` tool, - * implementing {@link KnowledgePort.listLibraryCards} over `/library.yml` - * and `/cards//.md`. - * - * Filesystem access is injected via {@link LibraryCardFs} for hermetic testing, - * with {@link createNodeLibraryCardFs} provided for Node/Bun composition. - */ - -import { constants as fsConstants } from 'node:fs'; -import { type FileHandle, open, readdir, stat } from 'node:fs/promises'; -import path from 'node:path'; -import type { KnowledgePort, LibraryCardQuery, LibraryCardRecord } from '../tools/read-knowledge'; - -const SAFE_IDENT_RE = /^[a-z0-9][a-z0-9-]*$/; -const LIBRARY_ID_RE = /^[a-z0-9][a-z0-9_-]*$/; -const PLAIN_YAML_KEY_RE = /^[^?:,[\]{}#&*!|>'"%@`\s](?:(?:[^,[\]{}#\s]| )*[^,[\]{}#\s])?$/; -const BLOCK_SCALAR_RE = /^[|>][+-]?$/; - -/** Error codes thrown by {@link LibraryCardError}. */ -export type LibraryCardErrorCode = - | 'INVALID_FS' - | 'INVALID_ROOT' - | 'INVALID_LIBRARY' - | 'INVALID_CARD'; - -/** Typed validation and I/O error thrown by the library card filesystem adapter. */ -export class LibraryCardError extends RangeError { - readonly code: LibraryCardErrorCode; - - constructor(code: LibraryCardErrorCode, message: string) { - super(message); - this.name = 'LibraryCardError'; - this.code = code; - Object.setPrototypeOf(this, new.target.prototype); - } -} - -/** Directory entry metadata returned by {@link LibraryCardFs.listDir}. */ -export interface LibraryCardDirEntry { - readonly name: string; - readonly isFile: boolean; - readonly isDirectory: boolean; -} - -/** Anchored read-only directory handle for symlink-safe traversal below a configured root. */ -export interface LibraryCardDirHandle { - listDir(): Promise; - openSubdir(name: string): Promise; - readTextFile(name: string): Promise; - close(): Promise; -} - -/** Minimal read-only filesystem port injected into {@link createLibraryCardReader}. */ -export interface LibraryCardFs { - readTextFile(filePath: string): Promise; - listDir(dirPath: string): Promise; - openDir(dirPath: string): Promise; -} - -/** Factory options for {@link createLibraryCardReader}. */ -export interface LibraryCardReaderOptions { - readonly root: string; - readonly fs: LibraryCardFs; -} - -/** Library-card subset of {@link KnowledgePort}. */ -export type LibraryCardReader = Pick; - -interface ParsedLibraryManifest { - readonly id: string; - readonly sections: readonly string[]; -} - -type FrontMatterValue = string | readonly string[]; - -function compareCodeUnits(a: string, b: string): number { - if (a < b) { - return -1; - } - if (a > b) { - return 1; - } - return 0; -} - -function isEnoentError(err: unknown): boolean { - return ( - typeof err === 'object' && - err !== null && - (err as { readonly code?: unknown }).code === 'ENOENT' - ); -} - -function invalidLibrary(reason: string): LibraryCardError { - return new LibraryCardError('INVALID_LIBRARY', `Invalid library.yml: ${reason}`); -} - -function invalidCard(relPath: string, reason: string): LibraryCardError { - return new LibraryCardError('INVALID_CARD', `Invalid card "${relPath}": ${reason}`); -} - -function validateFactoryOptions(options: LibraryCardReaderOptions): { - readonly resolvedRoot: string; - readonly fs: LibraryCardFs; -} { - if (typeof options !== 'object' || options === null) { - throw new LibraryCardError( - 'INVALID_ROOT', - 'Invalid options: expected an object with root and fs.' - ); - } - - const { root, fs } = options; - if (typeof root !== 'string' || root.trim().length === 0 || root.includes('\0')) { - throw new LibraryCardError( - 'INVALID_ROOT', - 'Invalid root: expected a non-empty filesystem path without null bytes.' - ); - } - - if ( - typeof fs !== 'object' || - fs === null || - typeof fs.readTextFile !== 'function' || - typeof fs.listDir !== 'function' || - typeof fs.openDir !== 'function' - ) { - throw new LibraryCardError( - 'INVALID_FS', - 'Invalid fs: expected a LibraryCardFs implementing readTextFile, listDir, and openDir.' - ); - } - - return { - resolvedRoot: path.resolve(root), - fs, - }; -} - -function parseLibraryScalar(rawValue: string): string { - if (rawValue.length === 0 || rawValue.startsWith('#')) { - throw invalidLibrary('"id" must not be empty.'); - } - if (rawValue.startsWith("'")) { - throw invalidLibrary('single-quoted "id" values are not supported.'); - } - if (rawValue.startsWith('"')) { - let parsed: unknown; - try { - parsed = JSON.parse(rawValue); - } catch { - throw invalidLibrary('invalid double-quoted "id" value.'); - } - if (typeof parsed !== 'string') { - throw invalidLibrary('invalid double-quoted "id" value.'); - } - return parsed; - } - if (rawValue.startsWith('[') || rawValue.startsWith('{') || BLOCK_SCALAR_RE.test(rawValue)) { - throw invalidLibrary('"id" must be a scalar string.'); - } - return rawValue; -} - -function parseLibraryManifest(content: string): ParsedLibraryManifest { - const lines = content.split(/\r?\n/); - - let libraryId: string | undefined; - let sawSections = false; - let sectionsIndent: number | null = null; - let currentTopLevelKey: string | null = null; - const seenSectionKeys = new Set(); - const validSections: string[] = []; - - for (let i = 0; i < lines.length; i += 1) { - const line = lines[i] as string; - const trimmed = line.trim(); - if (trimmed.length === 0 || trimmed.startsWith('#')) { - continue; - } - - let indent = 0; - while (indent < line.length && line[indent] === ' ') { - indent += 1; - } - if (line[indent] === '\t') { - throw invalidLibrary('tab indentation is not supported.'); - } - - if (indent === 0) { - const colonIdx = line.indexOf(':'); - if (colonIdx <= 0) { - throw invalidLibrary('malformed top-level entry.'); - } - const key = line.slice(0, colonIdx).trim(); - const rawValue = line.slice(colonIdx + 1).trim(); - if (key.length === 0 || /\s/.test(key)) { - throw invalidLibrary('invalid top-level key.'); - } - - currentTopLevelKey = key; - - if (key === 'id') { - if (libraryId !== undefined) { - throw invalidLibrary('duplicate "id" declaration.'); - } - const parsedId = parseLibraryScalar(rawValue); - if (!LIBRARY_ID_RE.test(parsedId)) { - throw invalidLibrary('"id" must match ^[a-z0-9][a-z0-9_-]*$.'); - } - libraryId = parsedId; - } else if (key === 'sections') { - if (sawSections) { - throw invalidLibrary('duplicate "sections" declaration.'); - } - if (rawValue.length > 0) { - throw invalidLibrary('"sections" must be an indented map.'); - } - sawSections = true; - sectionsIndent = null; - } - continue; - } - - if (currentTopLevelKey === null) { - throw invalidLibrary('indented entry before any top-level declaration.'); - } - if (currentTopLevelKey === 'id') { - throw invalidLibrary('"id" must be a single-line scalar.'); - } - if (currentTopLevelKey !== 'sections') { - continue; - } - - if (sectionsIndent === null) { - sectionsIndent = indent; - } else if (indent !== sectionsIndent) { - throw invalidLibrary('inconsistent indentation inside "sections" map.'); - } - - const body = line.slice(indent); - if (body === '-' || body.startsWith('- ') || body.startsWith('-\t')) { - throw invalidLibrary('sequence entries are not supported inside "sections" map.'); - } - const colonIdx = body.indexOf(':'); - if (colonIdx <= 0) { - throw invalidLibrary('malformed entry inside "sections" map.'); - } - const rawKey = body.slice(0, colonIdx); - const sectionKey = rawKey.trim(); - const afterColon = body.slice(colonIdx + 1); - if ( - rawKey !== sectionKey || - !PLAIN_YAML_KEY_RE.test(sectionKey) || - (afterColon.length > 0 && afterColon[0] !== ' ' && afterColon[0] !== '\t') - ) { - throw invalidLibrary('malformed entry inside "sections" map.'); - } - const sectionTitle = afterColon.trim(); - if (sectionTitle.length === 0 || sectionTitle.startsWith('#')) { - throw invalidLibrary('empty key or title inside "sections" map.'); - } - if (seenSectionKeys.has(sectionKey)) { - throw invalidLibrary('duplicate key inside "sections" map.'); - } - seenSectionKeys.add(sectionKey); - - if (SAFE_IDENT_RE.test(sectionKey)) { - validSections.push(sectionKey); - } - } - - if (libraryId === undefined) { - throw invalidLibrary('missing "id" declaration.'); - } - if (!sawSections || seenSectionKeys.size === 0) { - throw invalidLibrary('missing or empty "sections" map.'); - } - - return { - id: libraryId, - sections: validSections, - }; -} - -function parseFrontMatterValue(rawValue: string, relPath: string): FrontMatterValue { - if (rawValue.length === 0 || rawValue.startsWith('#')) { - throw invalidCard(relPath, 'empty or multiline front-matter value.'); - } - if (BLOCK_SCALAR_RE.test(rawValue)) { - throw invalidCard(relPath, 'multiline front-matter values are not supported.'); - } - if (rawValue.startsWith("'")) { - throw invalidCard(relPath, 'single-quoted front-matter values are not supported.'); - } - if (rawValue.startsWith('{')) { - throw invalidCard(relPath, 'object front-matter values are not supported.'); - } - - if (rawValue.startsWith('"')) { - let parsed: unknown; - try { - parsed = JSON.parse(rawValue); - } catch { - throw invalidCard(relPath, 'invalid double-quoted front-matter string.'); - } - if (typeof parsed !== 'string') { - throw invalidCard(relPath, 'invalid double-quoted front-matter string.'); - } - return parsed; - } - - if (rawValue.startsWith('[')) { - let parsed: unknown; - try { - parsed = JSON.parse(rawValue); - } catch { - throw invalidCard(relPath, 'invalid front-matter array.'); - } - if (!Array.isArray(parsed)) { - throw invalidCard(relPath, 'invalid front-matter array.'); - } - const items: string[] = []; - for (let i = 0; i < parsed.length; i += 1) { - const entry: unknown = parsed[i]; - if (typeof entry !== 'string') { - throw invalidCard(relPath, 'front-matter array entries must be strings.'); - } - items.push(entry); - } - return items; - } - - return rawValue; -} - -function parseCardDocument( - content: string, - libraryId: string, - sectionId: string, - slug: string -): LibraryCardRecord { - const relPath = `cards/${sectionId}/${slug}.md`; - const lines = content.split(/\r?\n/); - - if (lines[0] !== '---') { - throw invalidCard(relPath, 'missing opening front-matter delimiter.'); - } - - let closingIndex = -1; - for (let i = 1; i < lines.length; i += 1) { - if (lines[i] === '---') { - closingIndex = i; - break; - } - } - if (closingIndex === -1) { - throw invalidCard(relPath, 'missing closing front-matter delimiter.'); - } - - const fields = new Map(); - for (let i = 1; i < closingIndex; i += 1) { - const line = lines[i] as string; - const trimmed = line.trim(); - if (trimmed.length === 0 || trimmed.startsWith('#')) { - continue; - } - if (line[0] === ' ' || line[0] === '\t') { - throw invalidCard(relPath, 'multiline or indented front-matter values are not supported.'); - } - - const colonIdx = line.indexOf(':'); - if (colonIdx <= 0) { - throw invalidCard(relPath, 'malformed front-matter entry.'); - } - const key = line.slice(0, colonIdx).trim(); - if (key.length === 0 || /\s/.test(key)) { - throw invalidCard(relPath, 'invalid front-matter key.'); - } - if (fields.has(key)) { - throw invalidCard(relPath, 'duplicate front-matter key.'); - } - - const rawValue = line.slice(colonIdx + 1).trim(); - fields.set(key, parseFrontMatterValue(rawValue, relPath)); - } - - const rawTitle = fields.get('title'); - if (typeof rawTitle !== 'string' || rawTitle.trim().length === 0) { - throw invalidCard(relPath, 'missing or empty "title".'); - } - - const rawSummary = fields.get('summary'); - if (typeof rawSummary !== 'string' || rawSummary.trim().length === 0) { - throw invalidCard(relPath, 'missing or empty "summary".'); - } - - const rawMatches = fields.get('matches'); - if (rawMatches !== undefined && !Array.isArray(rawMatches)) { - throw invalidCard(relPath, '"matches" must be an array of strings.'); - } - - const tags: string[] = []; - const seenTags = new Set(); - const addTag = (raw: string): void => { - const normalized = raw.trim().toLowerCase(); - if (normalized.length > 0 && !seenTags.has(normalized)) { - seenTags.add(normalized); - tags.push(normalized); - } - }; - - addTag(sectionId); - if (rawMatches !== undefined) { - for (let i = 0; i < rawMatches.length; i += 1) { - addTag(rawMatches[i] as string); - } - } - - const body = lines - .slice(closingIndex + 1) - .join('\n') - .trim(); - - return Object.freeze({ - id: `${libraryId}:${sectionId}/${slug}`, - title: rawTitle, - tags: Object.freeze(tags), - summary: rawSummary, - body, - }); -} - -function parseExactCardId( - id: string, - libraryId: string, - declaredSections: ReadonlySet -): { readonly sectionId: string; readonly slug: string } | null { - const prefix = `${libraryId}:`; - if (!id.startsWith(prefix)) { - return null; - } - const rest = id.slice(prefix.length); - const slashIdx = rest.indexOf('/'); - if (slashIdx <= 0 || rest.indexOf('/', slashIdx + 1) !== -1) { - return null; - } - const sectionId = rest.slice(0, slashIdx); - const slug = rest.slice(slashIdx + 1); - if (!SAFE_IDENT_RE.test(sectionId) || !SAFE_IDENT_RE.test(slug)) { - return null; - } - if (!declaredSections.has(sectionId)) { - return null; - } - return { sectionId, slug }; -} - -function assertSafeChildName(name: string): void { - if ( - name.length === 0 || - name === '.' || - name === '..' || - name.includes('/') || - name.includes('\\') || - name.includes('\0') - ) { - throw new Error('Invalid directory child entry name.'); - } -} - -function isValidDirHandle(value: unknown): value is LibraryCardDirHandle { - return ( - typeof value === 'object' && - value !== null && - typeof (value as { readonly listDir?: unknown }).listDir === 'function' && - typeof (value as { readonly openSubdir?: unknown }).openSubdir === 'function' && - typeof (value as { readonly readTextFile?: unknown }).readTextFile === 'function' && - typeof (value as { readonly close?: unknown }).close === 'function' - ); -} - -async function safeOpenRootDir( - fs: LibraryCardFs, - resolvedRoot: string -): Promise { - let handle: unknown; - try { - handle = await fs.openDir(resolvedRoot); - } catch { - throw new LibraryCardError( - 'INVALID_LIBRARY', - 'Invalid library.yml: failed to open library root directory.' - ); - } - if (!isValidDirHandle(handle)) { - throw new LibraryCardError( - 'INVALID_LIBRARY', - 'Invalid library.yml: failed to open library root directory.' - ); - } - return handle; -} - -async function safeOpenSubdir( - parent: LibraryCardDirHandle, - name: string, - errorMessage: string, - allowMissing: boolean -): Promise { - let handle: unknown; - try { - handle = await parent.openSubdir(name); - } catch (err) { - if (allowMissing && isEnoentError(err)) { - return null; - } - throw new LibraryCardError('INVALID_LIBRARY', errorMessage); - } - if (!isValidDirHandle(handle)) { - throw new LibraryCardError('INVALID_LIBRARY', errorMessage); - } - return handle; -} - -async function safeReadTextFileFromDir( - dir: LibraryCardDirHandle, - name: string, - errorCode: 'INVALID_LIBRARY' | 'INVALID_CARD', - errorMessage: string -): Promise { - let content: unknown; - try { - content = await dir.readTextFile(name); - } catch { - throw new LibraryCardError(errorCode, errorMessage); - } - if (typeof content !== 'string') { - throw new LibraryCardError(errorCode, errorMessage); - } - return content; -} - -async function safeListDirHandle( - dir: LibraryCardDirHandle, - errorMessage: string, - allowMissing: boolean -): Promise { - let rawEntries: unknown; - try { - rawEntries = await dir.listDir(); - } catch (err) { - if (allowMissing && isEnoentError(err)) { - return []; - } - throw new LibraryCardError('INVALID_LIBRARY', errorMessage); - } - - if (!Array.isArray(rawEntries)) { - throw new LibraryCardError('INVALID_LIBRARY', errorMessage); - } - - const entries: LibraryCardDirEntry[] = []; - for (let i = 0; i < rawEntries.length; i += 1) { - const entry: unknown = rawEntries[i]; - if ( - typeof entry !== 'object' || - entry === null || - typeof (entry as { readonly name?: unknown }).name !== 'string' || - typeof (entry as { readonly isFile?: unknown }).isFile !== 'boolean' || - typeof (entry as { readonly isDirectory?: unknown }).isDirectory !== 'boolean' - ) { - throw new LibraryCardError('INVALID_LIBRARY', errorMessage); - } - entries.push(entry as LibraryCardDirEntry); - } - - return entries; -} - -interface AnchoredOpenFlags { - readonly dirOpenFlags: number; - readonly subdirOpenFlags: number; - readonly fileOpenFlags: number; -} - -function getAnchoredOpenFlags(): AnchoredOpenFlags { - if ( - process.platform !== 'linux' || - typeof fsConstants.O_NOFOLLOW !== 'number' || - typeof fsConstants.O_DIRECTORY !== 'number' - ) { - throw new Error('Anchored no-follow directory operations are not supported on this platform.'); - } - return { - dirOpenFlags: fsConstants.O_RDONLY | fsConstants.O_DIRECTORY, - subdirOpenFlags: fsConstants.O_RDONLY | fsConstants.O_DIRECTORY | fsConstants.O_NOFOLLOW, - fileOpenFlags: fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW, - }; -} - -function createAnchoredNodeDirHandle( - handle: FileHandle, - flags: AnchoredOpenFlags -): LibraryCardDirHandle { - let closed = false; - - const getFdBase = (): string => { - if (closed) { - throw new Error('Directory handle is closed.'); - } - return `/proc/self/fd/${handle.fd}`; - }; - - return { - async listDir(): Promise { - const dirents = await readdir(getFdBase(), { withFileTypes: true }); - const entries: LibraryCardDirEntry[] = []; - for (let i = 0; i < dirents.length; i += 1) { - const dirent = dirents[i]; - if (dirent !== undefined) { - entries.push({ - name: dirent.name, - isFile: dirent.isFile(), - isDirectory: dirent.isDirectory(), - }); - } - } - return entries; - }, - - async openSubdir(name: string): Promise { - assertSafeChildName(name); - const childHandle = await open(`${getFdBase()}/${name}`, flags.subdirOpenFlags); - try { - const stats = await childHandle.stat(); - if (!stats.isDirectory()) { - throw new Error('Target path is not a directory.'); - } - } catch (err) { - await childHandle.close(); - throw err; - } - return createAnchoredNodeDirHandle(childHandle, flags); - }, - - async readTextFile(name: string): Promise { - assertSafeChildName(name); - const fileHandle = await open(`${getFdBase()}/${name}`, flags.fileOpenFlags); - try { - const stats = await fileHandle.stat(); - if (!stats.isFile()) { - throw new Error('Target path is not a regular file.'); - } - return await fileHandle.readFile({ encoding: 'utf8' }); - } finally { - await fileHandle.close(); - } - }, - - async close(): Promise { - if (closed) { - return; - } - closed = true; - await handle.close(); - }, - }; -} - -/** - * Creates a read-only {@link LibraryCardFs} backed by `node:fs/promises`. - * - * Anchors directory listings and file reads to opened directory file descriptors - * via `/proc/self/fd/`, enforces `O_NOFOLLOW` on every component below the - * configured root, verifies regular-file/directory types via `fstat`, and fails - * closed on platforms that cannot enforce this boundary. - */ -export function createNodeLibraryCardFs(): LibraryCardFs { - return { - async readTextFile(filePath: string): Promise { - const flags = getAnchoredOpenFlags(); - const handle = await open(filePath, flags.fileOpenFlags); - try { - const stats = await handle.stat(); - if (!stats.isFile()) { - throw new Error('Target path is not a regular file.'); - } - return await handle.readFile({ encoding: 'utf8' }); - } finally { - await handle.close(); - } - }, - - async listDir(dirPath: string): Promise { - const flags = getAnchoredOpenFlags(); - const handle = await open(dirPath, flags.subdirOpenFlags); - try { - const stats = await handle.stat(); - if (!stats.isDirectory()) { - throw new Error('Target path is not a directory.'); - } - const anchored = createAnchoredNodeDirHandle(handle, flags); - return await anchored.listDir(); - } finally { - await handle.close(); - } - }, - - async openDir(dirPath: string): Promise { - const flags = getAnchoredOpenFlags(); - const handle = await open(dirPath, flags.dirOpenFlags); - try { - const stats = await handle.stat(); - if (!stats.isDirectory()) { - throw new Error('Target path is not a directory.'); - } - const procStats = await stat(`/proc/self/fd/${handle.fd}`); - if (!procStats.isDirectory()) { - throw new Error('Anchored directory descriptor is not accessible.'); - } - } catch (err) { - await handle.close(); - throw err; - } - return createAnchoredNodeDirHandle(handle, flags); - }, - }; -} - -/** - * Creates a read-only filesystem reader implementing - * {@link KnowledgePort.listLibraryCards} over `/library.yml` and - * `/cards//.md`. - * - * Reads fresh from the injected {@link LibraryCardFs} on every call, narrows - * only by exact case-sensitive `q.id` (leaving `q.query`, `q.tags`, ranking, - * truncation, and `limit` to `createReadKnowledgeTool`), and returns all - * eligible cards regardless of `verified` status. - */ -export function createLibraryCardReader(options: LibraryCardReaderOptions): LibraryCardReader { - const { resolvedRoot, fs } = validateFactoryOptions(options); - - return { - async listLibraryCards(q: LibraryCardQuery): Promise { - const rootDir = await safeOpenRootDir(fs, resolvedRoot); - try { - const manifestText = await safeReadTextFileFromDir( - rootDir, - 'library.yml', - 'INVALID_LIBRARY', - 'Invalid library.yml: failed to read manifest.' - ); - const manifest = parseLibraryManifest(manifestText); - const declaredSections = new Set(manifest.sections); - - let target: { readonly sectionId: string; readonly slug: string } | null = null; - if (q.id !== undefined) { - target = parseExactCardId(q.id, manifest.id, declaredSections); - if (target === null) { - return Object.freeze([]); - } - } - - const rootEntries = await safeListDirHandle( - rootDir, - 'Invalid library.yml: failed to list library root directory.', - false - ); - const hasCardsDir = rootEntries.some( - entry => entry.name === 'cards' && entry.isDirectory && !entry.isFile - ); - if (!hasCardsDir) { - return Object.freeze([]); - } - - const cardsDir = await safeOpenSubdir( - rootDir, - 'cards', - 'Invalid library.yml: failed to open library cards directory.', - true - ); - if (cardsDir === null) { - return Object.freeze([]); - } - - try { - const cardDirEntries = await safeListDirHandle( - cardsDir, - 'Invalid library.yml: failed to list library cards directory.', - true - ); - const presentSectionDirs = new Set(); - for (let i = 0; i < cardDirEntries.length; i += 1) { - const entry = cardDirEntries[i] as LibraryCardDirEntry; - if (entry.isDirectory && !entry.isFile && SAFE_IDENT_RE.test(entry.name)) { - presentSectionDirs.add(entry.name); - } - } - - const sectionsToScan = target !== null ? [target.sectionId] : manifest.sections; - const cards: LibraryCardRecord[] = []; - const seenIds = new Set(); - - for (let s = 0; s < sectionsToScan.length; s += 1) { - const sectionId = sectionsToScan[s] as string; - if (!presentSectionDirs.has(sectionId)) { - continue; - } - - const sectionDir = await safeOpenSubdir( - cardsDir, - sectionId, - `Invalid library.yml: failed to open section directory "cards/${sectionId}".`, - true - ); - if (sectionDir === null) { - continue; - } - - try { - const sectionEntries = await safeListDirHandle( - sectionDir, - `Invalid library.yml: failed to list section directory "cards/${sectionId}".`, - true - ); - - const slugs: string[] = []; - const seenSectionSlugs = new Set(); - for (let i = 0; i < sectionEntries.length; i += 1) { - const entry = sectionEntries[i] as LibraryCardDirEntry; - if (!entry.isFile || entry.isDirectory || !entry.name.endsWith('.md')) { - continue; - } - const slug = entry.name.slice(0, -3); - if (!SAFE_IDENT_RE.test(slug)) { - continue; - } - if (target !== null && slug !== target.slug) { - continue; - } - if (seenSectionSlugs.has(slug)) { - throw invalidCard(`cards/${sectionId}/${slug}.md`, 'duplicate card id.'); - } - seenSectionSlugs.add(slug); - slugs.push(slug); - } - - slugs.sort(compareCodeUnits); - - for (let i = 0; i < slugs.length; i += 1) { - const slug = slugs[i] as string; - const relPath = `cards/${sectionId}/${slug}.md`; - const canonicalId = `${manifest.id}:${sectionId}/${slug}`; - if (seenIds.has(canonicalId)) { - throw invalidCard(relPath, 'duplicate card id.'); - } - seenIds.add(canonicalId); - - const cardText = await safeReadTextFileFromDir( - sectionDir, - `${slug}.md`, - 'INVALID_CARD', - `Invalid card "${relPath}": failed to read card file.` - ); - cards.push(parseCardDocument(cardText, manifest.id, sectionId, slug)); - } - } finally { - await sectionDir.close(); - } - } - - return Object.freeze(cards); - } finally { - await cardsDir.close(); - } - } finally { - await rootDir.close(); - } - }, - }; -} diff --git a/libs/research/src/mcp/adapters/postgres-copilot.ts b/libs/research/src/mcp/adapters/postgres-copilot.ts deleted file mode 100644 index ca571894..00000000 --- a/libs/research/src/mcp/adapters/postgres-copilot.ts +++ /dev/null @@ -1,173 +0,0 @@ -/** - * PostgreSQL composition root for the MCP research copilot server. - * - * Wires a single injected {@link PostgresResearchCopilotExecutor} into all - * PostgreSQL-backed MCP adapters (`search_symbols`, `file_finding`, - * `read_knowledge`, `event_study` listing calendars, and `trial_ledger`) with - * one authoritative Vault cutoff (`vaultContext.vaultCutoffTs`). - * - * Dependency-free (no `pg`, no `node:*`, no bare `process`): SQL execution, - * market data store, library-card reader, session-date port, ID generator, and - * clock are all injected by the caller. - */ - -import { - type ResearchCopilotMcpServerOptions, - createResearchCopilotMcpServer, -} from '../copilot-server'; -import type { McpServer } from '../server'; -import type { KnowledgePort } from '../tools/read-knowledge'; -import { - type EarlyCloseOverrides, - type SessionDatesPort, - createExchangeCalendarResolver, - createPostgresListingCalendarPort, -} from './exchange-calendars'; -import { - createPostgresFindingWritePort, - createPostgresKnowledgeReaders, -} from './postgres-findings'; -import { createPostgresSymbolSearchPort } from './postgres-symbol-search'; -import { createPostgresTrialRefPort } from './postgres-trial-ref'; - -/** - * Structural `pg.Pool` / `pg.PoolClient`-compatible query interface shared by - * all PostgreSQL-backed MCP copilot adapters and `trial_ledger`. - * - * Assignable without casts to `SymbolSearchExecutor`, `TrialRefExecutor`, - * `PostgresFindingsExecutor`, `ListingCalendarExecutor`, and - * `TrialLedgerExecutor`. - */ -export interface PostgresResearchCopilotExecutor { - query>( - text: string, - params?: readonly unknown[] - ): Promise<{ readonly rows: readonly Row[] }>; -} - -/** - * Composition options for {@link createPostgresResearchCopilotServer}. - * - * Uses `vaultContext.vaultCutoffTs` as the single authoritative Vault cutoff - * across all Vault-fenced tools and `trial_ledger` visibility lookups. - */ -export interface PostgresResearchCopilotServerOptions - extends Pick< - ResearchCopilotMcpServerOptions, - 'name' | 'version' | 'store' | 'vaultContext' | 'principalId' - > { - readonly executor: PostgresResearchCopilotExecutor; - /** Optional PostgreSQL schema name (`^[a-z_][a-z0-9_]*$`); defaults to the executor's `search_path`. */ - readonly schema?: string; - readonly listLibraryCards: KnowledgePort['listLibraryCards']; - readonly sessionDates: SessionDatesPort; - readonly earlyCloses?: EarlyCloseOverrides; - readonly newId: () => string; - readonly now: () => Date | number; -} - -function validateOptions(options: PostgresResearchCopilotServerOptions): void { - if (typeof options !== 'object' || options === null) { - throw new Error( - 'Invalid `options`: expected a PostgresResearchCopilotServerOptions object.' - ); - } - if ( - typeof options.executor !== 'object' || - options.executor === null || - typeof options.executor.query !== 'function' - ) { - throw new Error( - 'Invalid `executor`: expected an object with a callable query(text, params?) method.' - ); - } - if (typeof options.vaultContext !== 'object' || options.vaultContext === null) { - throw new Error('Invalid `vaultContext`: expected a VaultFenceContext object.'); - } - if (typeof options.listLibraryCards !== 'function') { - throw new Error('Invalid `listLibraryCards`: expected a callable function.'); - } - if ( - typeof options.sessionDates !== 'object' || - options.sessionDates === null || - typeof options.sessionDates.listSessionDates !== 'function' - ) { - throw new Error( - 'Invalid `sessionDates`: expected an object with a callable listSessionDates(query) method.' - ); - } - if (typeof options.newId !== 'function') { - throw new Error('Invalid `newId`: expected a callable function.'); - } - if (typeof options.now !== 'function') { - throw new Error('Invalid `now`: expected a callable function.'); - } -} - -/** - * Composes all six research copilot MCP tools into a single {@link McpServer} - * backed by one shared PostgreSQL executor and one authoritative Vault cutoff. - * - * Schema-aware adapters (`search_symbols`, `trial_ledger` visibility lookup, - * `findings`, `provider_caveats`, and listing-to-exchange calendars) qualify - * their tables with `options.schema` when supplied; `trial_ledger` writes and - * cluster DSR reads resolve through the executor's `search_path`. - */ -export function createPostgresResearchCopilotServer( - options: PostgresResearchCopilotServerOptions -): McpServer { - validateOptions(options); - - const pgAdapterOptions = - options.schema === undefined - ? { executor: options.executor } - : { executor: options.executor, schema: options.schema }; - - const symbolSearchPort = createPostgresSymbolSearchPort(pgAdapterOptions); - const trialRefPort = createPostgresTrialRefPort({ - ...pgAdapterOptions, - vaultCutoffTs: options.vaultContext.vaultCutoffTs, - }); - const findingWritePort = createPostgresFindingWritePort(pgAdapterOptions); - const knowledgeReaders = createPostgresKnowledgeReaders(pgAdapterOptions); - const listingCalendars = createPostgresListingCalendarPort(pgAdapterOptions); - - const resolveExchangeCalendars = createExchangeCalendarResolver( - options.earlyCloses === undefined - ? { listingCalendars, sessionDates: options.sessionDates } - : { - listingCalendars, - sessionDates: options.sessionDates, - earlyCloses: options.earlyCloses, - } - ); - - const knowledgePort: KnowledgePort = { - listLibraryCards: options.listLibraryCards, - ...knowledgeReaders, - }; - - return createResearchCopilotMcpServer({ - name: options.name, - version: options.version, - store: options.store, - vaultContext: options.vaultContext, - ledger: options.executor, - principalId: options.principalId, - searchSymbols: { - port: symbolSearchPort, - }, - eventStudy: { - resolveExchangeCalendars, - }, - fileFinding: { - port: findingWritePort, - trialLookup: trialRefPort, - newId: options.newId, - now: options.now, - }, - readKnowledge: { - port: knowledgePort, - }, - }); -} diff --git a/libs/research/src/mcp/adapters/postgres-findings.ts b/libs/research/src/mcp/adapters/postgres-findings.ts deleted file mode 100644 index 388aa8f3..00000000 --- a/libs/research/src/mcp/adapters/postgres-findings.ts +++ /dev/null @@ -1,722 +0,0 @@ -/** - * PostgreSQL adapter for the MCP copilot findings and provider caveats tables - * (`37-research-findings.sql`), implementing {@link FindingWritePort} for - * `file_finding` and the `listFindings` / `listProviderCaveats` readers of - * {@link KnowledgePort} for `read_knowledge`. - * - * Dependency-free (no `pg`, no `node:*`, no bare `process`): SQL execution is - * injected via {@link PostgresFindingsExecutor}. - */ - -import { - type AppendFindingResult, - FILE_FINDING_KINDS, - type FileFindingKind, - type FiledFindingComparablePayload, - type FiledFindingRecord, - type FindingWritePort, - areFiledFindingPayloadsEqual, -} from '../tools/file-finding'; -import type { - FindingQuery, - FindingRecord, - KnowledgePort, - ProviderCaveatQuery, - ProviderCaveatRecord, -} from '../tools/read-knowledge'; -import { MAX_ECMASCRIPT_EPOCH_MS } from '../tools/vault-fenced-input'; - -const SCHEMA_IDENT_RE = /^[a-z_][a-z0-9_]*$/; -const ISO_INSTANT_RE = - /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(Z|([+-])(\d{2}):(\d{2}))$/; -const DAYS_IN_MONTH: readonly number[] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; -const FILE_FINDING_KIND_SET: ReadonlySet = new Set(FILE_FINDING_KINDS); - -/** Error codes thrown by {@link PostgresFindingsError}. */ -export type PostgresFindingsErrorCode = 'INVALID_EXECUTOR' | 'INVALID_SCHEMA' | 'INVALID_ROW'; - -/** Typed validation error thrown by the PostgreSQL findings adapter. */ -export class PostgresFindingsError extends RangeError { - readonly code: PostgresFindingsErrorCode; - - constructor(code: PostgresFindingsErrorCode, message: string) { - super(message); - this.name = 'PostgresFindingsError'; - this.code = code; - Object.setPrototypeOf(this, new.target.prototype); - } -} - -/** - * Structural `pg.Pool` / `pg.PoolClient`-compatible query interface so this module - * has no runtime dependency on `pg` and is unit-testable with a fake executor. - * - * For {@link createPostgresFindingWritePort}, the executor must run each `query()` - * call in autocommit mode on a fresh `READ COMMITTED` snapshot (such as a `pg.Pool`) - * rather than inside a `REPEATABLE READ` / `SERIALIZABLE` or explicit `BEGIN` - * transaction (unless the executor wraps each statement in a `SAVEPOINT` and rolls - * it back before rethrowing errors). Autocommit ensures that `ON CONFLICT ... DO - * NOTHING` winner lookups observe the committed winner and that same-ID `23505` - * primary-key retry lookups do not fail with `25P02` (aborted transaction). - */ -export interface PostgresFindingsExecutor { - query>( - text: string, - params?: readonly unknown[] - ): Promise<{ readonly rows: readonly Row[] }>; -} - -/** Factory options for {@link createPostgresFindingWritePort} and {@link createPostgresKnowledgeReaders}. */ -export interface PostgresFindingsOptions { - readonly executor: PostgresFindingsExecutor; - /** Optional PostgreSQL schema name (`^[a-z_][a-z0-9_]*$`); defaults to the executor's `search_path`. */ - readonly schema?: string; -} - -/** PostgreSQL-backed subset of {@link KnowledgePort} (`findings` and `provider_caveats`). */ -export type PostgresKnowledgeReaders = Pick; - -interface RawFindingReceiptRow { - readonly id: unknown; - readonly created_at: unknown; -} - -interface RawStoredFindingForReplayRow { - readonly id: unknown; - readonly kind: unknown; - readonly title: unknown; - readonly summary: unknown; - readonly created_at: unknown; - readonly trial_refs: unknown; - readonly evidence_refs: unknown; -} - -interface RawFindingRow { - readonly id: unknown; - readonly title: unknown; - readonly status: unknown; - readonly created_at: unknown; - readonly summary: unknown; - readonly trial_refs: unknown; - readonly evidence_refs: unknown; -} - -interface RawProviderCaveatRow { - readonly id: unknown; - readonly provider: unknown; - readonly dataset: unknown; - readonly caveat: unknown; - readonly created_at: unknown; -} - -function isLeapYear(year: number): boolean { - return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; -} - -function daysInUtcMonth(year: number, monthIndex: number): number { - if (monthIndex === 1 && isLeapYear(year)) { - return 29; - } - return DAYS_IN_MONTH[monthIndex] ?? 0; -} - -function utcDateMs( - year: number, - monthIndex: number, - day: number, - hours: number, - minutes: number, - seconds: number, - ms: number -): number { - const date = new Date(0); - date.setUTCFullYear(year, monthIndex, day); - date.setUTCHours(hours, minutes, seconds, ms); - return date.getTime(); -} - -function escapeLikePattern(value: string): string { - return value.replace(/[\\%_]/g, '\\$&'); -} - -/** - * PostgreSQL POSIX regex matching any non-ASCII character (`> 0x7F`). - * - * Used alongside ASCII SQL pushdown (`ILIKE` / `lower()`) so rows containing - * non-ASCII stored text (e.g. `BİST` under `C` collation or `K` U+212A) are - * kept as candidates and evaluated with JavaScript's `.toLowerCase()` rules. - */ -const PG_NON_ASCII_REGEX = "'[^\\x01-\\x7f]'"; - -/** - * Returns `true` when every UTF-16 code unit in `value` is ASCII (`<= 0x7F`). - * - * PostgreSQL `ILIKE` / `lower()` agrees with JavaScript `.toLowerCase()` only - * when both the selector and the stored text are pure ASCII. Non-ASCII - * selectors omit SQL casing filters, and ASCII selectors retain non-ASCII - * stored rows as candidates; all returned rows are then filtered with - * JavaScript's `.toLowerCase()` rules after validation. - */ -function isAsciiOnly(value: string): boolean { - for (let i = 0; i < value.length; i += 1) { - if (value.charCodeAt(i) > 0x7f) { - return false; - } - } - return true; -} - -function quoteTable(schemaPrefix: string, table: string): string { - return `${schemaPrefix}${table}`; -} - -function validateFactoryOptions(options: PostgresFindingsOptions): { - readonly executor: PostgresFindingsExecutor; - readonly schemaPrefix: string; -} { - if (typeof options !== 'object' || options === null) { - throw new PostgresFindingsError( - 'INVALID_EXECUTOR', - 'Invalid options: expected an object with a PostgresFindingsExecutor.' - ); - } - - const { executor, schema } = options; - if (typeof executor !== 'object' || executor === null || typeof executor.query !== 'function') { - throw new PostgresFindingsError( - 'INVALID_EXECUTOR', - 'Invalid executor: expected an object with a callable query(text, params?) method.' - ); - } - - if (schema === undefined) { - return { executor, schemaPrefix: '' }; - } - - if (typeof schema !== 'string' || !SCHEMA_IDENT_RE.test(schema)) { - throw new PostgresFindingsError( - 'INVALID_SCHEMA', - 'Invalid schema: expected an identifier matching ^[a-z_][a-z0-9_]*$.' - ); - } - - return { executor, schemaPrefix: `"${schema}".` }; -} - -function extractRows(result: unknown): readonly Row[] { - if ( - typeof result !== 'object' || - result === null || - !Array.isArray((result as { readonly rows?: unknown }).rows) - ) { - throw new PostgresFindingsError( - 'INVALID_ROW', - 'Invalid executor response: expected an object with a rows array.' - ); - } - return (result as { readonly rows: readonly Row[] }).rows; -} - -function parseNonEmptyString(value: unknown, field: string): string { - if (typeof value !== 'string' || value.trim().length === 0) { - throw new PostgresFindingsError( - 'INVALID_ROW', - `Invalid findings row: "${field}" must be a non-empty string.` - ); - } - return value; -} - -function parseFindingKind(value: unknown): FileFindingKind { - if (typeof value !== 'string' || !FILE_FINDING_KIND_SET.has(value)) { - throw new PostgresFindingsError( - 'INVALID_ROW', - 'Invalid findings row: "kind" must be "finding" or "dead_end".' - ); - } - return value as FileFindingKind; -} - -function parseStringArray(value: unknown, field: string): readonly string[] { - if (!Array.isArray(value)) { - throw new PostgresFindingsError( - 'INVALID_ROW', - `Invalid findings row: "${field}" must be a one-dimensional string array.` - ); - } - const result: string[] = []; - for (let i = 0; i < value.length; i += 1) { - const entry: unknown = value[i]; - if (typeof entry !== 'string') { - throw new PostgresFindingsError( - 'INVALID_ROW', - `Invalid findings row: "${field}[${i}]" must be a string.` - ); - } - result.push(entry); - } - return result; -} - -function parseTimestampIso(value: unknown, field: string): string { - if (value instanceof Date) { - const ms = value.getTime(); - if (!Number.isFinite(ms) || Math.abs(ms) >= MAX_ECMASCRIPT_EPOCH_MS) { - throw new PostgresFindingsError( - 'INVALID_ROW', - `Invalid findings row: "${field}" must be a finite Date.` - ); - } - return new Date(ms).toISOString(); - } - - if (typeof value !== 'string') { - throw new PostgresFindingsError( - 'INVALID_ROW', - `Invalid findings row: "${field}" must be a Date or timezone-qualified ISO-8601 timestamp string.` - ); - } - - const match = ISO_INSTANT_RE.exec(value); - if (match === null) { - throw new PostgresFindingsError( - 'INVALID_ROW', - `Invalid findings row: "${field}" must be a timezone-qualified ISO-8601 timestamp string.` - ); - } - - const year = Number(match[1]); - const month = Number(match[2]); - const day = Number(match[3]); - const hours = Number(match[4]); - const minutes = Number(match[5]); - const seconds = Number(match[6]); - const fractional = match[7]; - const tzToken = match[8]; - const tzSign = match[9]; - const tzHoursRaw = match[10]; - const tzMinutesRaw = match[11]; - - if (month < 1 || month > 12) { - throw new PostgresFindingsError( - 'INVALID_ROW', - `Invalid findings row: "${field}" has an out-of-range calendar month.` - ); - } - const maxDay = daysInUtcMonth(year, month - 1); - if (day < 1 || day > maxDay) { - throw new PostgresFindingsError( - 'INVALID_ROW', - `Invalid findings row: "${field}" has an out-of-range calendar day.` - ); - } - if (hours > 23 || minutes > 59 || seconds > 59) { - throw new PostgresFindingsError( - 'INVALID_ROW', - `Invalid findings row: "${field}" has an out-of-range time of day.` - ); - } - - let ms = 0; - if (fractional !== undefined) { - ms = Number(fractional.slice(0, 3).padEnd(3, '0')); - } - - let offsetMs = 0; - if (tzToken !== 'Z') { - const offsetHours = Number(tzHoursRaw); - const offsetMinutes = Number(tzMinutesRaw); - if (offsetHours > 23 || offsetMinutes > 59) { - throw new PostgresFindingsError( - 'INVALID_ROW', - `Invalid findings row: "${field}" has an out-of-range timezone offset.` - ); - } - const sign = tzSign === '+' ? 1 : -1; - offsetMs = sign * (offsetHours * 60 + offsetMinutes) * 60_000; - } - - const epochMs = utcDateMs(year, month - 1, day, hours, minutes, seconds, ms) - offsetMs; - if (!Number.isFinite(epochMs) || Math.abs(epochMs) >= MAX_ECMASCRIPT_EPOCH_MS) { - throw new PostgresFindingsError( - 'INVALID_ROW', - `Invalid findings row: "${field}" is outside the valid ECMAScript timestamp range.` - ); - } - - return new Date(epochMs).toISOString(); -} - -function parseReceiptRow(raw: unknown): { readonly id: string; readonly createdAt: string } { - if (typeof raw !== 'object' || raw === null) { - throw new PostgresFindingsError( - 'INVALID_ROW', - 'Invalid findings receipt row: expected a non-null object.' - ); - } - const row = raw as RawFindingReceiptRow; - return { - id: parseNonEmptyString(row.id, 'id'), - createdAt: parseTimestampIso(row.created_at, 'created_at'), - }; -} - -function parseStoredFindingForReplayRow(raw: unknown): { - readonly id: string; - readonly createdAt: string; - readonly payload: FiledFindingComparablePayload; -} { - if (typeof raw !== 'object' || raw === null) { - throw new PostgresFindingsError( - 'INVALID_ROW', - 'Invalid findings replay row: expected a non-null object.' - ); - } - const row = raw as RawStoredFindingForReplayRow; - const id = parseNonEmptyString(row.id, 'id'); - const kind = parseFindingKind(row.kind); - const title = parseNonEmptyString(row.title, 'title'); - const summary = parseNonEmptyString(row.summary, 'summary'); - const createdAt = parseTimestampIso(row.created_at, 'created_at'); - const trialRefs = parseStringArray(row.trial_refs, 'trial_refs'); - const evidenceRefs = parseStringArray(row.evidence_refs, 'evidence_refs'); - - return { - id, - createdAt, - payload: { - kind, - title, - summary, - trialRefs, - evidenceRefs, - }, - }; -} - -function parseFindingRow(raw: unknown): FindingRecord { - if (typeof raw !== 'object' || raw === null) { - throw new PostgresFindingsError( - 'INVALID_ROW', - 'Invalid findings row: expected a non-null object.' - ); - } - const row = raw as RawFindingRow; - return { - id: parseNonEmptyString(row.id, 'id'), - title: parseNonEmptyString(row.title, 'title'), - status: parseNonEmptyString(row.status, 'status'), - createdAt: parseTimestampIso(row.created_at, 'created_at'), - summary: parseNonEmptyString(row.summary, 'summary'), - trialRefs: parseStringArray(row.trial_refs, 'trial_refs'), - evidenceRefs: parseStringArray(row.evidence_refs, 'evidence_refs'), - }; -} - -function parseProviderCaveatRow(raw: unknown): ProviderCaveatRecord { - if (typeof raw !== 'object' || raw === null) { - throw new PostgresFindingsError( - 'INVALID_ROW', - 'Invalid provider_caveats row: expected a non-null object.' - ); - } - const row = raw as RawProviderCaveatRow; - return { - id: parseNonEmptyString(row.id, 'id'), - provider: parseNonEmptyString(row.provider, 'provider'), - dataset: parseNonEmptyString(row.dataset, 'dataset'), - caveat: parseNonEmptyString(row.caveat, 'caveat'), - createdAt: parseTimestampIso(row.created_at, 'created_at'), - }; -} - -function isPostgresUniqueViolation(err: unknown): boolean { - return ( - typeof err === 'object' && - err !== null && - (err as { readonly code?: unknown }).code === '23505' - ); -} - -function buildInsertFindingSql(schemaPrefix: string, keyed: boolean): string { - const findingsTable = quoteTable(schemaPrefix, 'findings'); - const lines = [ - `INSERT INTO ${findingsTable} (`, - ' id,', - ' kind,', - ' title,', - ' summary,', - ' status,', - ' created_at,', - ' trial_refs,', - ' evidence_refs,', - ' idempotency_key', - ')', - 'VALUES ($1, $2, $3, $4, $5, $6::timestamptz, $7::text[], $8::text[], $9)', - ]; - if (keyed) { - lines.push('ON CONFLICT (idempotency_key) WHERE idempotency_key IS NOT NULL DO NOTHING'); - } - lines.push('RETURNING id, created_at'); - return lines.join('\n'); -} - -function buildSelectByIdempotencyKeySql(schemaPrefix: string): string { - const findingsTable = quoteTable(schemaPrefix, 'findings'); - return [ - 'SELECT', - ' id,', - ' kind,', - ' title,', - ' summary,', - ' created_at,', - ' trial_refs,', - ' evidence_refs', - `FROM ${findingsTable}`, - 'WHERE idempotency_key = $1::text', - ].join('\n'); -} - -/** - * Creates an append-only PostgreSQL {@link FindingWritePort} backed by the - * `findings` table (`37-research-findings.sql`). - */ -export function createPostgresFindingWritePort(options: PostgresFindingsOptions): FindingWritePort { - const { executor, schemaPrefix } = validateFactoryOptions(options); - const unkeyedInsertSql = buildInsertFindingSql(schemaPrefix, false); - const keyedInsertSql = buildInsertFindingSql(schemaPrefix, true); - const selectByKeySql = buildSelectByIdempotencyKeySql(schemaPrefix); - - return { - async appendFinding( - record: FiledFindingRecord, - idempotencyKey?: string - ): Promise { - const insertParams: readonly unknown[] = [ - record.id, - record.kind, - record.title, - record.summary, - record.status, - record.createdAt, - [...record.trialRefs], - [...record.evidenceRefs], - idempotencyKey ?? null, - ]; - - if (idempotencyKey === undefined) { - const result = await executor.query(unkeyedInsertSql, insertParams); - const rows = extractRows(result); - if (rows.length !== 1) { - throw new PostgresFindingsError( - 'INVALID_ROW', - `Expected 1 inserted findings row, received ${rows.length}.` - ); - } - const receipt = parseReceiptRow(rows[0]); - return { - status: 'created', - id: receipt.id, - createdAt: receipt.createdAt, - }; - } - - let insertRows: readonly RawFindingReceiptRow[]; - try { - const result = await executor.query(keyedInsertSql, insertParams); - insertRows = extractRows(result); - } catch (err) { - if (!isPostgresUniqueViolation(err)) { - throw err; - } - // A concurrent same-ID retry can collide on the primary key before the - // partial idempotency_key index; resolve only if the stored row for this - // key has the exact same ID, otherwise propagate the primary-key error. - const lookupResult = await executor.query(selectByKeySql, [ - idempotencyKey, - ]); - const lookupRows = extractRows(lookupResult); - if (lookupRows.length === 0) { - throw err; - } - if (lookupRows.length > 1) { - throw new PostgresFindingsError( - 'INVALID_ROW', - `Expected at most 1 stored finding for idempotency_key, received ${lookupRows.length}.` - ); - } - const stored = parseStoredFindingForReplayRow(lookupRows[0]); - if (stored.id !== record.id) { - throw err; - } - return areFiledFindingPayloadsEqual(stored.payload, record) - ? { status: 'replayed', id: stored.id, createdAt: stored.createdAt } - : { status: 'conflict' }; - } - - if (insertRows.length === 1) { - const receipt = parseReceiptRow(insertRows[0]); - return { - status: 'created', - id: receipt.id, - createdAt: receipt.createdAt, - }; - } - - if (insertRows.length > 1) { - throw new PostgresFindingsError( - 'INVALID_ROW', - `Expected 0 or 1 inserted findings rows, received ${insertRows.length}.` - ); - } - - // Separate SELECT on a fresh READ COMMITTED snapshot so a concurrent winner - // committed during ON CONFLICT DO NOTHING is visible. - const winnerResult = await executor.query(selectByKeySql, [ - idempotencyKey, - ]); - const winnerRows = extractRows(winnerResult); - if (winnerRows.length !== 1) { - throw new PostgresFindingsError( - 'INVALID_ROW', - `Expected 1 stored finding for idempotency_key after conflict, received ${winnerRows.length}.` - ); - } - - const stored = parseStoredFindingForReplayRow(winnerRows[0]); - return areFiledFindingPayloadsEqual(stored.payload, record) - ? { status: 'replayed', id: stored.id, createdAt: stored.createdAt } - : { status: 'conflict' }; - }, - }; -} - -/** - * Creates read-only PostgreSQL readers (`listFindings` and `listProviderCaveats`) - * for composing {@link KnowledgePort} in `read_knowledge`. - */ -export function createPostgresKnowledgeReaders( - options: PostgresFindingsOptions -): PostgresKnowledgeReaders { - const { executor, schemaPrefix } = validateFactoryOptions(options); - const findingsTable = quoteTable(schemaPrefix, 'findings'); - const caveatsTable = quoteTable(schemaPrefix, 'provider_caveats'); - - return { - async listFindings(q: FindingQuery): Promise { - const lines = [ - 'SELECT', - ' id,', - ' title,', - ' status,', - ' created_at,', - ' summary,', - ' trial_refs,', - ' evidence_refs', - `FROM ${findingsTable}`, - ]; - const params: unknown[] = []; - let normalizedQuery: string | null = null; - - if (q.id !== undefined) { - params.push(q.id); - lines.push('WHERE id = $1::text'); - } else if (q.query !== undefined) { - normalizedQuery = q.query.toLowerCase(); - if (isAsciiOnly(q.query)) { - params.push(`%${escapeLikePattern(q.query)}%`); - lines.push( - `WHERE title ILIKE $1::text ESCAPE '\\' OR summary ILIKE $1::text ESCAPE '\\' OR title ~ ${PG_NON_ASCII_REGEX} OR summary ~ ${PG_NON_ASCII_REGEX}` - ); - } - } - - lines.push('ORDER BY id ASC'); - - const result = await executor.query(lines.join('\n'), params); - const rows = extractRows(result); - const mapped: FindingRecord[] = []; - for (let i = 0; i < rows.length; i += 1) { - const finding = parseFindingRow(rows[i]); - if ( - normalizedQuery !== null && - !finding.title.toLowerCase().includes(normalizedQuery) && - !finding.summary.toLowerCase().includes(normalizedQuery) - ) { - continue; - } - mapped.push(finding); - } - return mapped; - }, - - async listProviderCaveats(q: ProviderCaveatQuery): Promise { - const lines = [ - 'SELECT', - ' id,', - ' provider,', - ' dataset,', - ' caveat,', - ' created_at', - `FROM ${caveatsTable}`, - ]; - const conditions: string[] = []; - const params: unknown[] = []; - let normalizedProvider: string | null = null; - let normalizedQuery: string | null = null; - - if (q.provider !== undefined) { - normalizedProvider = q.provider.toLowerCase(); - if (isAsciiOnly(q.provider)) { - params.push(q.provider); - conditions.push( - `(lower(provider) = lower($${params.length}::text) OR provider ~ ${PG_NON_ASCII_REGEX})` - ); - } - } - - if (q.id !== undefined) { - params.push(q.id); - conditions.push(`id = $${params.length}::text`); - } else if (q.query !== undefined) { - normalizedQuery = q.query.toLowerCase(); - if (isAsciiOnly(q.query)) { - params.push(`%${escapeLikePattern(q.query)}%`); - const idx = params.length; - conditions.push( - `(provider ILIKE $${idx}::text ESCAPE '\\' OR dataset ILIKE $${idx}::text ESCAPE '\\' OR caveat ILIKE $${idx}::text ESCAPE '\\' OR provider ~ ${PG_NON_ASCII_REGEX} OR dataset ~ ${PG_NON_ASCII_REGEX} OR caveat ~ ${PG_NON_ASCII_REGEX})` - ); - } - } - - if (conditions.length > 0) { - lines.push(`WHERE ${conditions.join(' AND ')}`); - } - - lines.push('ORDER BY id ASC'); - - const result = await executor.query(lines.join('\n'), params); - const rows = extractRows(result); - const mapped: ProviderCaveatRecord[] = []; - for (let i = 0; i < rows.length; i += 1) { - const caveat = parseProviderCaveatRow(rows[i]); - if ( - normalizedProvider !== null && - caveat.provider.toLowerCase() !== normalizedProvider - ) { - continue; - } - if ( - normalizedQuery !== null && - !caveat.provider.toLowerCase().includes(normalizedQuery) && - !caveat.dataset.toLowerCase().includes(normalizedQuery) && - !caveat.caveat.toLowerCase().includes(normalizedQuery) - ) { - continue; - } - mapped.push(caveat); - } - return mapped; - }, - }; -} diff --git a/libs/research/src/mcp/adapters/postgres-symbol-search.ts b/libs/research/src/mcp/adapters/postgres-symbol-search.ts deleted file mode 100644 index c2e7b9ae..00000000 --- a/libs/research/src/mcp/adapters/postgres-symbol-search.ts +++ /dev/null @@ -1,355 +0,0 @@ -/** - * Read-only PostgreSQL security-master adapter implementing {@link SymbolSearchPort} - * for the MCP copilot `search_symbols` tool. - * - * Dependency-free (no `pg`, no `node:*`, no bare `process`): SQL execution is - * injected via {@link SymbolSearchExecutor}. - */ - -import type { SymbolSearchPort, SymbolSearchQuery, SymbolSearchRow } from '../tools/search-symbols'; -import { utcDateOf, validateVaultCutoffTs } from '../tools/vault-fenced-input'; - -const SCHEMA_IDENT_RE = /^[a-z_][a-z0-9_]*$/; -const CALENDAR_DATE_RE = /^(\d{4})-(\d{2})-(\d{2})$/; -const DAYS_IN_MONTH: readonly number[] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; - -/** Error codes thrown by {@link PostgresSymbolSearchError}. */ -export type PostgresSymbolSearchErrorCode = - | 'INVALID_EXECUTOR' - | 'INVALID_SCHEMA' - | 'INVALID_ROW'; - -/** Typed validation error thrown by the PostgreSQL symbol-search adapter. */ -export class PostgresSymbolSearchError extends RangeError { - readonly code: PostgresSymbolSearchErrorCode; - - constructor(code: PostgresSymbolSearchErrorCode, message: string) { - super(message); - this.name = 'PostgresSymbolSearchError'; - this.code = code; - Object.setPrototypeOf(this, new.target.prototype); - } -} - -/** - * Structural `pg.Pool` / `pg.PoolClient`-compatible query interface so this module - * has no runtime dependency on `pg` and is unit-testable with a fake executor. - */ -export interface SymbolSearchExecutor { - query>( - text: string, - params?: readonly unknown[] - ): Promise<{ readonly rows: readonly Row[] }>; -} - -/** Factory options for {@link createPostgresSymbolSearchPort}. */ -export interface PostgresSymbolSearchPortOptions { - readonly executor: SymbolSearchExecutor; - /** Optional PostgreSQL schema name (`^[a-z_][a-z0-9_]*$`); defaults to the executor's `search_path`. */ - readonly schema?: string; -} - -interface RawSymbolSearchRow { - readonly listing_id: unknown; - readonly instrument_id: unknown; - readonly ticker: unknown; - readonly class_suffix: unknown; - readonly name: unknown; - readonly mic: unknown; - readonly currency: unknown; - readonly isin: unknown; - readonly first_bar_date: unknown; - readonly last_bar_date: unknown; - readonly delisted_at: unknown; -} - -function isLeapYear(year: number): boolean { - return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; -} - -function daysInUtcMonth(year: number, monthIndex: number): number { - if (monthIndex === 1 && isLeapYear(year)) { - return 29; - } - return DAYS_IN_MONTH[monthIndex] ?? 0; -} - -function isValidCalendarDate(value: unknown): value is string { - if (typeof value !== 'string') { - return false; - } - const match = CALENDAR_DATE_RE.exec(value); - if (match === null) { - return false; - } - const year = Number(match[1]); - const month = Number(match[2]); - const day = Number(match[3]); - if (month < 1 || month > 12) { - return false; - } - return day >= 1 && day <= daysInUtcMonth(year, month - 1); -} - -function escapeLikePattern(value: string): string { - return value.replace(/[\\%_]/g, '\\$&'); -} - -function quoteTable(schemaPrefix: string, table: string): string { - return `${schemaPrefix}${table}`; -} - -function buildSearchSymbolsSql(schemaPrefix: string): string { - const listingTable = quoteTable(schemaPrefix, 'listing'); - const instrumentTable = quoteTable(schemaPrefix, 'instrument'); - const exchangeTable = quoteTable(schemaPrefix, 'exchange'); - const historyTable = quoteTable(schemaPrefix, 'listing_symbol_history'); - - return [ - 'SELECT', - ' l.listing_id AS listing_id,', - ' l.instrument_id AS instrument_id,', - ' resolved.ticker AS ticker,', - " NULLIF(l.class_suffix, '') AS class_suffix,", - ' i.canonical_name AS name,', - ' l.mic AS mic,', - ' btrim(l.currency) AS currency,', - " NULLIF(btrim(i.primary_isin), '') AS isin,", - " to_char(l.listed_from, 'YYYY-MM-DD') AS first_bar_date,", - " to_char(l.listed_to, 'YYYY-MM-DD') AS last_bar_date,", - " to_char(delisted.delisted_at, 'YYYY-MM-DD') AS delisted_at", - `FROM ${listingTable} l`, - `INNER JOIN ${instrumentTable} i ON i.instrument_id = l.instrument_id`, - `INNER JOIN ${exchangeTable} e ON e.mic = l.mic`, - 'CROSS JOIN LATERAL (', - ' SELECT (', - ' EXISTS (', - ' SELECT 1', - ` FROM ${historyTable} h_any`, - ' WHERE h_any.listing_id = l.listing_id', - ' AND upper(h_any.ticker) = upper(l.ticker_root)', - ' )', - ' AND NOT EXISTS (', - ' SELECT 1', - ` FROM ${historyTable} h_past`, - ' WHERE h_past.listing_id = l.listing_id', - ' AND upper(h_past.ticker) = upper(l.ticker_root)', - ' AND h_past.valid_from <= $1::date', - ' )', - ' ) AS is_future', - ') root_state', - 'LEFT JOIN LATERAL (', - ' SELECT h.ticker', - ` FROM ${historyTable} h`, - ' WHERE h.listing_id = l.listing_id', - ' AND h.valid_from <= $1::date', - ' AND (h.valid_to IS NULL OR h.valid_to >= $1::date)', - ' ORDER BY h.valid_from DESC, h.ticker ASC', - ' LIMIT 1', - ') hist_active ON TRUE', - 'LEFT JOIN LATERAL (', - ' SELECT h.ticker', - ` FROM ${historyTable} h`, - ' WHERE h.listing_id = l.listing_id', - ' AND h.valid_from <= $1::date', - ' ORDER BY h.valid_from DESC, h.ticker ASC', - ' LIMIT 1', - ') hist_prior ON TRUE', - 'CROSS JOIN LATERAL (', - ' SELECT CASE', - ' WHEN hist_active.ticker IS NOT NULL THEN hist_active.ticker', - ' WHEN NOT root_state.is_future THEN l.ticker_root', - ' ELSE hist_prior.ticker', - ' END AS ticker', - ') resolved', - 'CROSS JOIN LATERAL (', - ' SELECT CASE', - " WHEN l.delist_reason IS NOT NULL AND l.delist_reason <> 'active' THEN l.listed_to", - ' ELSE NULL', - ' END AS delisted_at', - ') delisted', - 'WHERE (l.listed_from IS NULL OR l.listed_from <= $1::date)', - ' AND resolved.ticker IS NOT NULL', - " AND resolved.ticker <> ''", - ' AND ($4::text IS NULL OR btrim(e.country_iso) = $4::text)', - ' AND ($5::boolean OR delisted.delisted_at IS NULL OR delisted.delisted_at > $1::date)', - ' AND (', - " resolved.ticker ILIKE $2::text ESCAPE '\\'", - " OR (NOT root_state.is_future AND l.ticker_root ILIKE $2::text ESCAPE '\\')", - " OR i.canonical_name ILIKE $2::text ESCAPE '\\'", - ' OR (i.primary_isin IS NOT NULL AND upper(btrim(i.primary_isin)) = upper($3::text))', - ' )', - 'ORDER BY l.listing_id ASC', - ].join('\n'); -} - -function parseSafeInt(value: unknown, field: string): number { - if (typeof value !== 'number' || !Number.isSafeInteger(value)) { - throw new PostgresSymbolSearchError( - 'INVALID_ROW', - `Invalid security-master row: "${field}" must be a safe integer.` - ); - } - return value; -} - -function parseNonEmptyString(value: unknown, field: string): string { - if (typeof value !== 'string' || value.trim().length === 0) { - throw new PostgresSymbolSearchError( - 'INVALID_ROW', - `Invalid security-master row: "${field}" must be a non-empty string.` - ); - } - return value; -} - -function parseNullableClassSuffix(value: unknown): string | null { - if (value === null) { - return null; - } - if (typeof value !== 'string') { - throw new PostgresSymbolSearchError( - 'INVALID_ROW', - 'Invalid security-master row: "class_suffix" must be a string or null.' - ); - } - return value === '' ? null : value; -} - -function parseNullableIsin(value: unknown): string | null { - if (value === null) { - return null; - } - if (typeof value !== 'string') { - throw new PostgresSymbolSearchError( - 'INVALID_ROW', - 'Invalid security-master row: "isin" must be a string or null.' - ); - } - const trimmed = value.trim(); - return trimmed === '' ? null : trimmed; -} - -function parseNullableDate(value: unknown, field: string): string | null { - if (value === null) { - return null; - } - if (!isValidCalendarDate(value)) { - throw new PostgresSymbolSearchError( - 'INVALID_ROW', - `Invalid security-master row: "${field}" must be a valid YYYY-MM-DD calendar date or null.` - ); - } - return value; -} - -function mapRawRow(raw: unknown): SymbolSearchRow { - if (typeof raw !== 'object' || raw === null) { - throw new PostgresSymbolSearchError( - 'INVALID_ROW', - 'Invalid security-master row: expected a non-null object.' - ); - } - - const row = raw as RawSymbolSearchRow; - const listingId = parseSafeInt(row.listing_id, 'listing_id'); - const instrumentId = parseSafeInt(row.instrument_id, 'instrument_id'); - const ticker = parseNonEmptyString(row.ticker, 'ticker'); - const classSuffix = parseNullableClassSuffix(row.class_suffix); - const name = parseNonEmptyString(row.name, 'name'); - const mic = parseNonEmptyString(row.mic, 'mic'); - const currency = parseNonEmptyString(row.currency, 'currency').trim(); - const isin = parseNullableIsin(row.isin); - const firstBarDate = parseNullableDate(row.first_bar_date, 'first_bar_date'); - const lastBarDate = parseNullableDate(row.last_bar_date, 'last_bar_date'); - const delistedAt = parseNullableDate(row.delisted_at, 'delisted_at'); - - return { - listingId, - instrumentId, - ticker, - classSuffix, - name, - mic, - currency, - isin, - firstBarDate, - lastBarDate, - delistedAt, - }; -} - -function validateFactoryOptions(options: PostgresSymbolSearchPortOptions): { - readonly executor: SymbolSearchExecutor; - readonly schemaPrefix: string; -} { - if (typeof options !== 'object' || options === null) { - throw new PostgresSymbolSearchError( - 'INVALID_EXECUTOR', - 'Invalid options: expected an object with a SymbolSearchExecutor.' - ); - } - - const { executor, schema } = options; - if (typeof executor !== 'object' || executor === null || typeof executor.query !== 'function') { - throw new PostgresSymbolSearchError( - 'INVALID_EXECUTOR', - 'Invalid executor: expected an object with a callable query(text, params?) method.' - ); - } - - if (schema === undefined) { - return { executor, schemaPrefix: '' }; - } - - if (typeof schema !== 'string' || !SCHEMA_IDENT_RE.test(schema)) { - throw new PostgresSymbolSearchError( - 'INVALID_SCHEMA', - 'Invalid schema: expected an identifier matching ^[a-z_][a-z0-9_]*$.' - ); - } - - return { executor, schemaPrefix: `"${schema}".` }; -} - -/** - * Creates a read-only PostgreSQL {@link SymbolSearchPort} backed by the M1 - * security master (`listing`, `instrument`, `exchange`, `listing_symbol_history`). - */ -export function createPostgresSymbolSearchPort( - options: PostgresSymbolSearchPortOptions -): SymbolSearchPort { - const { executor, schemaPrefix } = validateFactoryOptions(options); - const sql = buildSearchSymbolsSql(schemaPrefix); - - return { - async searchSymbols(q: SymbolSearchQuery): Promise { - const cutoffTs = validateVaultCutoffTs(q.vaultCutoffTs); - const cutoffDate = utcDateOf(cutoffTs); - const ilikePattern = `%${escapeLikePattern(q.query)}%`; - const country = q.country ?? null; - const includeDelisted = q.includeDelisted; - - const result = await executor.query(sql, [ - cutoffDate, - ilikePattern, - q.query, - country, - includeDelisted, - ]); - - if (typeof result !== 'object' || result === null || !Array.isArray(result.rows)) { - throw new PostgresSymbolSearchError( - 'INVALID_ROW', - 'Invalid executor response: expected an object with a rows array.' - ); - } - - const mapped: SymbolSearchRow[] = []; - for (let i = 0; i < result.rows.length; i += 1) { - mapped.push(mapRawRow(result.rows[i])); - } - return mapped; - }, - }; -} diff --git a/libs/research/src/mcp/adapters/postgres-trial-ref.ts b/libs/research/src/mcp/adapters/postgres-trial-ref.ts deleted file mode 100644 index bc6ac3f7..00000000 --- a/libs/research/src/mcp/adapters/postgres-trial-ref.ts +++ /dev/null @@ -1,181 +0,0 @@ -/** - * Read-only PostgreSQL `trial_ledger` adapter implementing {@link TrialRefLookupPort} - * for the MCP copilot `file_finding` tool. - * - * Dependency-free (no `pg`, no `node:*`, no bare `process`): SQL execution is - * injected via {@link TrialRefExecutor}. - */ - -import type { TrialRefLookupPort } from '../tools/file-finding'; -import { utcDateOf, validateVaultCutoffTs } from '../tools/vault-fenced-input'; - -const SCHEMA_IDENT_RE = /^[a-z_][a-z0-9_]*$/; -const FOUR_DIGIT_DATE_RE = /^\d{4}-\d{2}-\d{2}$/; -const CANONICAL_POSITIVE_BIGINT_RE = /^[1-9][0-9]{0,18}$/; -const MAX_SIGNED_BIGINT_STR = '9223372036854775807'; - -/** Error codes thrown by {@link PostgresTrialRefError}. */ -export type PostgresTrialRefErrorCode = - | 'INVALID_EXECUTOR' - | 'INVALID_SCHEMA' - | 'INVALID_VAULT_CUTOFF' - | 'INVALID_ROW'; - -/** Typed validation error thrown by the PostgreSQL trial-ref lookup adapter. */ -export class PostgresTrialRefError extends RangeError { - readonly code: PostgresTrialRefErrorCode; - - constructor(code: PostgresTrialRefErrorCode, message: string) { - super(message); - this.name = 'PostgresTrialRefError'; - this.code = code; - Object.setPrototypeOf(this, new.target.prototype); - } -} - -/** - * Structural `pg.Pool` / `pg.PoolClient`-compatible query interface so this module - * has no runtime dependency on `pg` and is unit-testable with a fake executor. - */ -export interface TrialRefExecutor { - query>( - text: string, - params?: readonly unknown[] - ): Promise<{ readonly rows: readonly Row[] }>; -} - -/** Factory options for {@link createPostgresTrialRefLookupPort} / {@link createPostgresTrialRefPort}. */ -export interface PostgresTrialRefLookupPortOptions { - readonly executor: TrialRefExecutor; - /** Authoritative UTC epoch-ms Vault cutoff; trials with `sample_end < cutoffDate` are research-visible. */ - readonly vaultCutoffTs: number; - /** Optional PostgreSQL schema name (`^[a-z_][a-z0-9_]*$`); defaults to the executor's `search_path`. */ - readonly schema?: string; -} - -/** Alias for {@link PostgresTrialRefLookupPortOptions}. */ -export type PostgresTrialRefPortOptions = PostgresTrialRefLookupPortOptions; - -interface RawTrialRefVisibilityRow { - readonly visible?: unknown; -} - -function isCanonicalPositiveBigInt(value: unknown): value is string { - if (typeof value !== 'string' || !CANONICAL_POSITIVE_BIGINT_RE.test(value)) { - return false; - } - if (value.length === MAX_SIGNED_BIGINT_STR.length && value > MAX_SIGNED_BIGINT_STR) { - return false; - } - return true; -} - -function buildTrialVisibilitySql(schemaPrefix: string): string { - return `SELECT 1 AS visible FROM ${schemaPrefix}trial_ledger WHERE trial_id = $1::bigint AND sample_end < $2::date LIMIT 1`; -} - -function validateFactoryOptions(options: PostgresTrialRefLookupPortOptions): { - readonly executor: TrialRefExecutor; - readonly cutoffDate: string; - readonly schemaPrefix: string; -} { - if (typeof options !== 'object' || options === null) { - throw new PostgresTrialRefError( - 'INVALID_EXECUTOR', - 'Invalid options: expected an object with a TrialRefExecutor.' - ); - } - - const { executor, vaultCutoffTs, schema } = options; - if (typeof executor !== 'object' || executor === null || typeof executor.query !== 'function') { - throw new PostgresTrialRefError( - 'INVALID_EXECUTOR', - 'Invalid executor: expected an object with a callable query(text, params?) method.' - ); - } - - let schemaPrefix = ''; - if (schema !== undefined) { - if (typeof schema !== 'string' || !SCHEMA_IDENT_RE.test(schema)) { - throw new PostgresTrialRefError( - 'INVALID_SCHEMA', - 'Invalid schema: expected an identifier matching ^[a-z_][a-z0-9_]*$.' - ); - } - schemaPrefix = `"${schema}".`; - } - - let validatedCutoffTs: number; - try { - validatedCutoffTs = validateVaultCutoffTs(vaultCutoffTs); - } catch { - throw new PostgresTrialRefError( - 'INVALID_VAULT_CUTOFF', - 'Invalid vaultCutoffTs: expected a finite safe-integer epoch-ms timestamp within ECMAScript Date bounds.' - ); - } - - const cutoffDate = utcDateOf(validatedCutoffTs); - if (!FOUR_DIGIT_DATE_RE.test(cutoffDate) || cutoffDate.startsWith('0000-')) { - throw new PostgresTrialRefError( - 'INVALID_VAULT_CUTOFF', - 'Invalid vaultCutoffTs: resolved UTC date must be a four-digit PostgreSQL calendar date (0001-01-01 through 9999-12-31).' - ); - } - - return { executor, cutoffDate, schemaPrefix }; -} - -/** - * Creates a read-only PostgreSQL {@link TrialRefLookupPort} backed by `trial_ledger` - * (`36-trial-ledger.sql`). - * - * Only trials with `sample_end < cutoffDate` (exclusive UTC Vault cutoff date) are - * research-visible. Unknown, malformed, and Vault-only references all return `false`. - */ -export function createPostgresTrialRefLookupPort( - options: PostgresTrialRefLookupPortOptions -): TrialRefLookupPort { - const { executor, cutoffDate, schemaPrefix } = validateFactoryOptions(options); - const sql = buildTrialVisibilitySql(schemaPrefix); - - return { - async hasResearchVisibleTrial(trialRef: string): Promise { - if (!isCanonicalPositiveBigInt(trialRef)) { - return false; - } - - const result = await executor.query(sql, [trialRef, cutoffDate]); - if (typeof result !== 'object' || result === null || !Array.isArray(result.rows)) { - throw new PostgresTrialRefError( - 'INVALID_ROW', - 'Invalid executor response: expected an object with a rows array.' - ); - } - - if (result.rows.length === 0) { - return false; - } - - if (result.rows.length !== 1) { - throw new PostgresTrialRefError( - 'INVALID_ROW', - `Invalid executor response: expected at most 1 trial_ledger row, received ${result.rows.length}.` - ); - } - - const raw = result.rows[0]; - if (typeof raw !== 'object' || raw === null || raw.visible !== 1) { - throw new PostgresTrialRefError( - 'INVALID_ROW', - 'Invalid trial_ledger visibility row: expected an object with visible === 1.' - ); - } - - return true; - }, - }; -} - -/** Alias for {@link createPostgresTrialRefLookupPort}. */ -export const createPostgresTrialRefPort = createPostgresTrialRefLookupPort; diff --git a/libs/research/src/mcp/copilot-server.ts b/libs/research/src/mcp/copilot-server.ts deleted file mode 100644 index 98b412ee..00000000 --- a/libs/research/src/mcp/copilot-server.ts +++ /dev/null @@ -1,110 +0,0 @@ -import { type McpServer, type McpServerOptions, createMcpServer } from './server'; -import { type AnalyzeSignalToolOptions, createAnalyzeSignalTool } from './tools/analyze-signal'; -import { type EventStudyToolOptions, createEventStudyTool } from './tools/event-study'; -import { type FileFindingToolOptions, createFileFindingTool } from './tools/file-finding'; -import { type QueryDataToolOptions, createQueryDataTool } from './tools/query-data'; -import { type ReadKnowledgeToolOptions, createReadKnowledgeTool } from './tools/read-knowledge'; -import { type SearchSymbolsToolOptions, createSearchSymbolsTool } from './tools/search-symbols'; - -/** - * Fixed, documented registration order of the six MCP tools exposed by - * {@link createResearchCopilotMcpServer}. - */ -export const RESEARCH_COPILOT_TOOL_NAMES = Object.freeze([ - 'search_symbols', - 'query_data', - 'analyze_signal', - 'event_study', - 'file_finding', - 'read_knowledge', -] as const); - -/** - * Composed server options for {@link createResearchCopilotMcpServer}. - * - * Shares the common Vault-fenced `MarketDataStore`, `vaultContext`, - * `TrialLedgerExecutor`, and `principalId` across the tools that consume them - * while passing each tool's remaining injected ports unchanged. - */ -export interface ResearchCopilotMcpServerOptions - extends Pick, - Pick, - Pick { - readonly searchSymbols: Omit; - readonly eventStudy: Pick; - readonly fileFinding: FileFindingToolOptions; - readonly readKnowledge: ReadKnowledgeToolOptions; -} - -/** - * Composes all six research MCP tools (`search_symbols`, `query_data`, - * `analyze_signal`, `event_study`, `file_finding`, `read_knowledge`) into a - * single transport-agnostic {@link McpServer}. - * - * Keeps the shared `store`, `vaultContext`, `ledger`, and `principalId` - * authoritative across tools and fails closed if any tool is duplicated, - * missing, unexpected, or out of order. - */ -export function createResearchCopilotMcpServer( - options: ResearchCopilotMcpServerOptions -): McpServer { - if (typeof options !== 'object' || options === null) { - throw new Error('Invalid `options`: expected a ResearchCopilotMcpServerOptions object.'); - } - if (typeof options.searchSymbols !== 'object' || options.searchSymbols === null) { - throw new Error('Invalid `searchSymbols`: expected a SearchSymbolsToolOptions object.'); - } - if (typeof options.eventStudy !== 'object' || options.eventStudy === null) { - throw new Error('Invalid `eventStudy`: expected an EventStudyToolOptions object.'); - } - - const tools = [ - createSearchSymbolsTool({ - ...options.searchSymbols, - vaultContext: options.vaultContext, - }), - createQueryDataTool({ - store: options.store, - vaultContext: options.vaultContext, - }), - createAnalyzeSignalTool({ - store: options.store, - ledger: options.ledger, - vaultContext: options.vaultContext, - principalId: options.principalId, - }), - createEventStudyTool({ - store: options.store, - ledger: options.ledger, - vaultContext: options.vaultContext, - principalId: options.principalId, - resolveExchangeCalendars: options.eventStudy.resolveExchangeCalendars, - }), - createFileFindingTool(options.fileFinding), - createReadKnowledgeTool(options.readKnowledge), - ]; - - const server = createMcpServer({ - name: options.name, - version: options.version, - tools, - }); - - const registered = server.listTools(); - if (registered.length !== RESEARCH_COPILOT_TOOL_NAMES.length) { - throw new Error( - `Research copilot MCP server expected ${RESEARCH_COPILOT_TOOL_NAMES.length} tools, got ${registered.length}.` - ); - } - for (let i = 0; i < RESEARCH_COPILOT_TOOL_NAMES.length; i += 1) { - const expectedName = RESEARCH_COPILOT_TOOL_NAMES[i]; - const actualName = registered[i]?.name; - if (actualName !== expectedName) { - throw new Error( - `Research copilot MCP server tool mismatch at index ${i}: expected "${expectedName}", got "${String(actualName)}".` - ); - } - } - - return server; -} diff --git a/libs/research/src/mcp/host/stdio-host.ts b/libs/research/src/mcp/host/stdio-host.ts deleted file mode 100644 index b7ff3c3a..00000000 --- a/libs/research/src/mcp/host/stdio-host.ts +++ /dev/null @@ -1,835 +0,0 @@ -/** - * Dependency-free stdio host composition for the MCP research copilot. - * - * Parses `RESEARCH_MCP_*` environment variables into a strict typed - * {@link ResearchCopilotHostConfig} and composes injected PostgreSQL executor, - * market data store, and library-card reader factories with - * {@link createBarSessionDatesPort}, {@link createPostgresResearchCopilotServer}, - * and {@link runStdioServer}. - * - * Pure and dependency-free: zero `node:*` imports, zero bare `process` access, - * no `pg` dependency, and no DuckDB driver import. - */ - -import { z } from 'zod'; -import type { MarketDataStore } from '../../market-data-store'; -import { - MAX_ECMASCRIPT_EPOCH_MS, - isValidInt32, - parseCalendarDayKey, -} from '../../panel-shared'; -import { - type BarSessionDatesPortOptions, - createBarSessionDatesPort, -} from '../adapters/bar-session-dates'; -import { - EXCHANGE_CALENDAR_MAX_CLOSE_MINUTE_ET, - EXCHANGE_CALENDAR_MAX_SUPPORTED_DATE, - EXCHANGE_CALENDAR_MIN_CLOSE_MINUTE_ET, - EXCHANGE_CALENDAR_MIN_SUPPORTED_DATE, - type EarlyCloseOverrides, -} from '../adapters/exchange-calendars'; -import { - type PostgresResearchCopilotExecutor, - createPostgresResearchCopilotServer, -} from '../adapters/postgres-copilot'; -import type { McpServer } from '../server'; -import { type StdioServerOptions, runStdioServer } from '../stdio'; -import type { KnowledgePort } from '../tools/read-knowledge'; - -/** Environment variable prefix owned by {@link parseResearchCopilotHostConfig}. */ -export const RESEARCH_MCP_ENV_PREFIX = 'RESEARCH_MCP_'; - -/** Headless MCP server name announced during `initialize`. */ -export const RESEARCH_COPILOT_HOST_NAME = 'stock-bot-research-copilot'; - -/** Headless MCP server version announced during `initialize`. */ -export const RESEARCH_COPILOT_HOST_VERSION = '0.1.0'; - -const ENV_POSTGRES_URL = 'RESEARCH_MCP_POSTGRES_URL'; -const ENV_POSTGRES_SCHEMA = 'RESEARCH_MCP_POSTGRES_SCHEMA'; -const ENV_CURATED_ROOT = 'RESEARCH_MCP_CURATED_ROOT'; -const ENV_VAULT_CUTOFF_TS = 'RESEARCH_MCP_VAULT_CUTOFF_TS'; -const ENV_PRINCIPAL_ID = 'RESEARCH_MCP_PRINCIPAL_ID'; -const ENV_LIBRARY_ROOT = 'RESEARCH_MCP_LIBRARY_ROOT'; -const ENV_SESSION_REFERENCE_LISTINGS = 'RESEARCH_MCP_SESSION_REFERENCE_LISTINGS'; -const ENV_EARLY_CLOSES = 'RESEARCH_MCP_EARLY_CLOSES'; - -const SCHEMA_IDENT_RE = /^[a-z_][a-z0-9_]*$/; -const AGENT_PRINCIPAL_RE = - /^agent:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; -const STRICT_UTC_INSTANT_RE = - /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?Z$/; - -const nonBlankEnvString = z.string().refine(value => value.trim().length > 0, { - message: 'blank', -}); - -const rawHostEnvSchema = z - .object({ - [ENV_POSTGRES_URL]: nonBlankEnvString, - [ENV_POSTGRES_SCHEMA]: nonBlankEnvString.optional(), - [ENV_CURATED_ROOT]: nonBlankEnvString, - [ENV_VAULT_CUTOFF_TS]: nonBlankEnvString, - [ENV_PRINCIPAL_ID]: nonBlankEnvString, - [ENV_LIBRARY_ROOT]: nonBlankEnvString, - [ENV_SESSION_REFERENCE_LISTINGS]: nonBlankEnvString, - [ENV_EARLY_CLOSES]: nonBlankEnvString.optional(), - }) - .strict(); - -/** Validated configuration parsed from `RESEARCH_MCP_*` environment variables. */ -export interface ResearchCopilotHostConfig { - readonly postgresUrl: string; - readonly postgresSchema?: string; - readonly curatedRoot: string; - readonly vaultCutoffTs: number; - readonly principalId: string; - readonly libraryRoot: string; - readonly referenceListingIds: BarSessionDatesPortOptions['referenceListingIds']; - readonly earlyCloses?: EarlyCloseOverrides; -} - -/** - * Typed configuration error thrown by {@link parseResearchCopilotHostConfig}. - * - * Always names the offending `RESEARCH_MCP_*` variable with a fixed reason and - * never embeds raw environment values, DSNs, JSON parser output, or Zod dumps. - */ -export class ResearchCopilotHostConfigError extends RangeError { - readonly variable: string; - - constructor(variable: string, message: string) { - super(message); - this.name = 'ResearchCopilotHostConfigError'; - this.variable = variable; - Object.setPrototypeOf(this, new.target.prototype); - } -} - -/** Managed PostgreSQL executor handle returned by `deps.openExecutor`. */ -export interface ManagedPostgresExecutor { - readonly executor: PostgresResearchCopilotExecutor; - close(): Promise | void; -} - -/** Managed market data store handle returned by `deps.openStore`. */ -export interface ManagedMarketDataStore { - readonly store: MarketDataStore; - close(): Promise | void; -} - -/** Library-card reader handle returned by `deps.createLibraryCardReader`. */ -export interface LibraryCardReaderHandle { - readonly listLibraryCards: KnowledgePort['listLibraryCards']; -} - -/** Injected dependencies for {@link runResearchCopilotStdioHost}. */ -export interface ResearchCopilotStdioHostDeps { - readonly config: ResearchCopilotHostConfig; - readonly openExecutor: ( - config: ResearchCopilotHostConfig - ) => Promise | ManagedPostgresExecutor; - readonly openStore: ( - config: ResearchCopilotHostConfig - ) => Promise | ManagedMarketDataStore; - readonly createLibraryCardReader: ( - config: ResearchCopilotHostConfig - ) => Promise | LibraryCardReaderHandle; - readonly newId: () => string; - readonly now: () => Date | number; - readonly stdio?: StdioServerOptions; -} - -type HostStage = - | 'executor_open' - | 'store_open' - | 'library_reader' - | 'server_init' - | 'stdio_serve' - | 'cleanup'; - -const STAGE_ERROR_MESSAGES: Readonly> = { - executor_open: 'Research copilot stdio host failed while opening the PostgreSQL executor.', - store_open: 'Research copilot stdio host failed while opening the market data store.', - library_reader: 'Research copilot stdio host failed while creating the library card reader.', - server_init: 'Research copilot stdio host failed while initializing the MCP server.', - stdio_serve: 'Research copilot stdio host failed while serving MCP stdio.', - cleanup: 'Research copilot stdio host failed while closing host resources.', -}; - -function isPlainObjectRecord(value: unknown): value is Record { - if (typeof value !== 'object' || value === null) { - return false; - } - const proto: unknown = Object.getPrototypeOf(value); - return proto === Object.prototype || proto === null; -} - -function defineDataProperty(target: Record, key: string, value: T): void { - Object.defineProperty(target, key, { - value, - enumerable: true, - writable: true, - configurable: true, - }); -} - -function parsePostgresUrl(raw: string): string { - if (raw !== raw.trim()) { - throw new ResearchCopilotHostConfigError( - ENV_POSTGRES_URL, - `Invalid configuration variable "${ENV_POSTGRES_URL}": expected a valid postgres:// or postgresql:// URL without surrounding whitespace.` - ); - } - let parsed: URL; - try { - parsed = new URL(raw); - } catch { - throw new ResearchCopilotHostConfigError( - ENV_POSTGRES_URL, - `Invalid configuration variable "${ENV_POSTGRES_URL}": expected a valid postgres:// or postgresql:// URL.` - ); - } - if ( - (parsed.protocol !== 'postgres:' && parsed.protocol !== 'postgresql:') || - parsed.hostname.length === 0 - ) { - throw new ResearchCopilotHostConfigError( - ENV_POSTGRES_URL, - `Invalid configuration variable "${ENV_POSTGRES_URL}": expected a postgres:// or postgresql:// URL with a non-empty host.` - ); - } - try { - if (parsed.username.length > 0) { - decodeURIComponent(parsed.username); - } - if (parsed.password.length > 0) { - decodeURIComponent(parsed.password); - } - } catch { - throw new ResearchCopilotHostConfigError( - ENV_POSTGRES_URL, - `Invalid configuration variable "${ENV_POSTGRES_URL}": URL credentials contain invalid percent-encoding.` - ); - } - return raw; -} - -function parsePostgresSchema(raw: string): string { - if (!SCHEMA_IDENT_RE.test(raw)) { - throw new ResearchCopilotHostConfigError( - ENV_POSTGRES_SCHEMA, - `Invalid configuration variable "${ENV_POSTGRES_SCHEMA}": expected a PostgreSQL identifier matching ^[a-z_][a-z0-9_]*$.` - ); - } - return raw; -} - -function parsePrincipalId(raw: string): string { - if (raw !== 'operator' && !AGENT_PRINCIPAL_RE.test(raw)) { - throw new ResearchCopilotHostConfigError( - ENV_PRINCIPAL_ID, - `Invalid configuration variable "${ENV_PRINCIPAL_ID}": expected "operator" or "agent:".` - ); - } - return raw; -} - -function parseVaultCutoffTs(raw: string): number { - const match = STRICT_UTC_INSTANT_RE.exec(raw); - if (match === null) { - throw new ResearchCopilotHostConfigError( - ENV_VAULT_CUTOFF_TS, - `Invalid configuration variable "${ENV_VAULT_CUTOFF_TS}": expected a strict ISO-8601 UTC instant ending in Z.` - ); - } - - const year = Number(match[1]); - const month = Number(match[2]); - const day = Number(match[3]); - const hour = Number(match[4]); - const minute = Number(match[5]); - const second = Number(match[6]); - const fracRaw = match[7]; - const millis = fracRaw === undefined ? 0 : Number(fracRaw.padEnd(3, '0')); - - if ( - month < 1 || - month > 12 || - day < 1 || - day > 31 || - hour > 23 || - minute > 59 || - second > 59 - ) { - throw new ResearchCopilotHostConfigError( - ENV_VAULT_CUTOFF_TS, - `Invalid configuration variable "${ENV_VAULT_CUTOFF_TS}": timestamp is not a valid UTC calendar instant.` - ); - } - - const epochMs = Date.UTC(year, month - 1, day, hour, minute, second, millis); - if (!Number.isSafeInteger(epochMs) || Math.abs(epochMs) >= MAX_ECMASCRIPT_EPOCH_MS) { - throw new ResearchCopilotHostConfigError( - ENV_VAULT_CUTOFF_TS, - `Invalid configuration variable "${ENV_VAULT_CUTOFF_TS}": timestamp is out of supported epoch range.` - ); - } - - const check = new Date(epochMs); - if ( - check.getUTCFullYear() !== year || - check.getUTCMonth() !== month - 1 || - check.getUTCDate() !== day || - check.getUTCHours() !== hour || - check.getUTCMinutes() !== minute || - check.getUTCSeconds() !== second || - check.getUTCMilliseconds() !== millis - ) { - throw new ResearchCopilotHostConfigError( - ENV_VAULT_CUTOFF_TS, - `Invalid configuration variable "${ENV_VAULT_CUTOFF_TS}": timestamp is not a valid UTC calendar instant.` - ); - } - - return epochMs; -} - -function parseReferenceListingIds( - raw: string -): BarSessionDatesPortOptions['referenceListingIds'] { - let parsed: unknown; - try { - parsed = JSON.parse(raw); - } catch { - throw new ResearchCopilotHostConfigError( - ENV_SESSION_REFERENCE_LISTINGS, - `Invalid configuration variable "${ENV_SESSION_REFERENCE_LISTINGS}": expected valid JSON.` - ); - } - - if (!isPlainObjectRecord(parsed)) { - throw new ResearchCopilotHostConfigError( - ENV_SESSION_REFERENCE_LISTINGS, - `Invalid configuration variable "${ENV_SESSION_REFERENCE_LISTINGS}": expected a JSON object mapping calendar codes to listing ID arrays.` - ); - } - - const result: Record = {}; - const entries = Object.entries(parsed); - - for (let i = 0; i < entries.length; i += 1) { - const [calendarCode, rawIds] = entries[i] as [string, unknown]; - if (calendarCode.trim().length === 0 || calendarCode !== calendarCode.trim()) { - throw new ResearchCopilotHostConfigError( - ENV_SESSION_REFERENCE_LISTINGS, - `Invalid configuration variable "${ENV_SESSION_REFERENCE_LISTINGS}": calendar codes must be non-empty trimmed strings.` - ); - } - - if (!Array.isArray(rawIds) || rawIds.length === 0) { - throw new ResearchCopilotHostConfigError( - ENV_SESSION_REFERENCE_LISTINGS, - `Invalid configuration variable "${ENV_SESSION_REFERENCE_LISTINGS}": each calendar must map to a non-empty array of positive INT32 listing IDs.` - ); - } - - const copiedIds: number[] = []; - const seen = new Set(); - - for (let j = 0; j < rawIds.length; j += 1) { - const id: unknown = rawIds[j]; - if (!isValidInt32(id) || id <= 0) { - throw new ResearchCopilotHostConfigError( - ENV_SESSION_REFERENCE_LISTINGS, - `Invalid configuration variable "${ENV_SESSION_REFERENCE_LISTINGS}": listing IDs must be positive 32-bit integers.` - ); - } - if (seen.has(id)) { - throw new ResearchCopilotHostConfigError( - ENV_SESSION_REFERENCE_LISTINGS, - `Invalid configuration variable "${ENV_SESSION_REFERENCE_LISTINGS}": listing IDs within a calendar must be distinct.` - ); - } - seen.add(id); - copiedIds.push(id); - } - - defineDataProperty(result, calendarCode, copiedIds); - } - - return result; -} - -function parseEarlyClosesEnv(raw: string): EarlyCloseOverrides { - let parsed: unknown; - try { - parsed = JSON.parse(raw); - } catch { - throw new ResearchCopilotHostConfigError( - ENV_EARLY_CLOSES, - `Invalid configuration variable "${ENV_EARLY_CLOSES}": expected valid JSON.` - ); - } - - if (!isPlainObjectRecord(parsed)) { - throw new ResearchCopilotHostConfigError( - ENV_EARLY_CLOSES, - `Invalid configuration variable "${ENV_EARLY_CLOSES}": expected a JSON object mapping calendar codes to date/minute overrides.` - ); - } - - const result: Record>> = {}; - const calendarEntries = Object.entries(parsed); - - for (let i = 0; i < calendarEntries.length; i += 1) { - const [calendarCode, rawDates] = calendarEntries[i] as [string, unknown]; - if (calendarCode.trim().length === 0 || calendarCode !== calendarCode.trim()) { - throw new ResearchCopilotHostConfigError( - ENV_EARLY_CLOSES, - `Invalid configuration variable "${ENV_EARLY_CLOSES}": calendar codes must be non-empty trimmed strings.` - ); - } - - if (!isPlainObjectRecord(rawDates)) { - throw new ResearchCopilotHostConfigError( - ENV_EARLY_CLOSES, - `Invalid configuration variable "${ENV_EARLY_CLOSES}": each calendar must map to an object of YYYY-MM-DD dates and Eastern close minutes.` - ); - } - - const dates: Record = {}; - const dateEntries = Object.entries(rawDates); - - for (let j = 0; j < dateEntries.length; j += 1) { - const [dateStr, minute] = dateEntries[j] as [string, unknown]; - parseCalendarDayKey(dateStr, ENV_EARLY_CLOSES, () => - new ResearchCopilotHostConfigError( - ENV_EARLY_CLOSES, - `Invalid configuration variable "${ENV_EARLY_CLOSES}": override dates must be valid YYYY-MM-DD calendar dates.` - ) - ); - - if ( - dateStr < EXCHANGE_CALENDAR_MIN_SUPPORTED_DATE || - dateStr > EXCHANGE_CALENDAR_MAX_SUPPORTED_DATE - ) { - throw new ResearchCopilotHostConfigError( - ENV_EARLY_CLOSES, - `Invalid configuration variable "${ENV_EARLY_CLOSES}": override dates must fall within ${EXCHANGE_CALENDAR_MIN_SUPPORTED_DATE}..=${EXCHANGE_CALENDAR_MAX_SUPPORTED_DATE}.` - ); - } - - if ( - typeof minute !== 'number' || - !Number.isSafeInteger(minute) || - minute < EXCHANGE_CALENDAR_MIN_CLOSE_MINUTE_ET || - minute > EXCHANGE_CALENDAR_MAX_CLOSE_MINUTE_ET - ) { - throw new ResearchCopilotHostConfigError( - ENV_EARLY_CLOSES, - `Invalid configuration variable "${ENV_EARLY_CLOSES}": close minutes must be integers from ${EXCHANGE_CALENDAR_MIN_CLOSE_MINUTE_ET} through ${EXCHANGE_CALENDAR_MAX_CLOSE_MINUTE_ET}.` - ); - } - - defineDataProperty(dates, dateStr, minute); - } - - defineDataProperty(result, calendarCode, dates); - } - - return result; -} - -/** - * Purely parses and validates `RESEARCH_MCP_*` environment variables into a - * typed {@link ResearchCopilotHostConfig}. - * - * Unrelated environment keys are ignored. Unknown `RESEARCH_MCP_*` keys, - * missing required variables, blank values, and malformed fields fail closed - * with {@link ResearchCopilotHostConfigError} naming the variable without - * exposing raw values or credentials. - */ -export function parseResearchCopilotHostConfig( - env: Readonly> -): ResearchCopilotHostConfig { - if (typeof env !== 'object' || env === null) { - throw new ResearchCopilotHostConfigError( - RESEARCH_MCP_ENV_PREFIX, - 'Invalid environment object: expected a key-value record.' - ); - } - - const scopedEnv: Record = {}; - const entries = Object.entries(env); - for (let i = 0; i < entries.length; i += 1) { - const [key, value] = entries[i] as [string, unknown]; - if (key.startsWith(RESEARCH_MCP_ENV_PREFIX) && value !== undefined) { - defineDataProperty(scopedEnv, key, value); - } - } - - const parsedEnv = rawHostEnvSchema.safeParse(scopedEnv); - if (!parsedEnv.success) { - const firstIssue = parsedEnv.error.issues[0]; - if (firstIssue !== undefined) { - if (firstIssue.code === 'unrecognized_keys') { - const unknownKey = firstIssue.keys[0] ?? RESEARCH_MCP_ENV_PREFIX; - throw new ResearchCopilotHostConfigError( - unknownKey, - `Unknown configuration variable "${unknownKey}".` - ); - } - - const variable = - typeof firstIssue.path[0] === 'string' ? firstIssue.path[0] : RESEARCH_MCP_ENV_PREFIX; - - if (firstIssue.code === 'invalid_type' && firstIssue.received === 'undefined') { - throw new ResearchCopilotHostConfigError( - variable, - `Missing required configuration variable "${variable}".` - ); - } - - if (firstIssue.code === 'custom') { - throw new ResearchCopilotHostConfigError( - variable, - `Invalid configuration variable "${variable}": value must not be empty or whitespace.` - ); - } - - throw new ResearchCopilotHostConfigError( - variable, - `Invalid configuration variable "${variable}": expected a non-empty string.` - ); - } - - throw new ResearchCopilotHostConfigError( - RESEARCH_MCP_ENV_PREFIX, - 'Invalid research copilot host configuration.' - ); - } - - const data = parsedEnv.data; - const postgresUrl = parsePostgresUrl(data[ENV_POSTGRES_URL]); - const postgresSchema = - data[ENV_POSTGRES_SCHEMA] !== undefined - ? parsePostgresSchema(data[ENV_POSTGRES_SCHEMA]) - : undefined; - const curatedRoot = data[ENV_CURATED_ROOT].trim(); - const vaultCutoffTs = parseVaultCutoffTs(data[ENV_VAULT_CUTOFF_TS]); - const principalId = parsePrincipalId(data[ENV_PRINCIPAL_ID]); - const libraryRoot = data[ENV_LIBRARY_ROOT].trim(); - const referenceListingIds = parseReferenceListingIds(data[ENV_SESSION_REFERENCE_LISTINGS]); - const earlyCloses = - data[ENV_EARLY_CLOSES] !== undefined - ? parseEarlyClosesEnv(data[ENV_EARLY_CLOSES]) - : undefined; - - return { - postgresUrl, - ...(postgresSchema !== undefined ? { postgresSchema } : {}), - curatedRoot, - vaultCutoffTs, - principalId, - libraryRoot, - referenceListingIds, - ...(earlyCloses !== undefined ? { earlyCloses } : {}), - }; -} - -function addRawAndDecodedNeedle(needles: Set, raw: string): void { - if (raw.length === 0) { - return; - } - needles.add(raw); - try { - const decoded = decodeURIComponent(raw); - if (decoded.length > 0) { - needles.add(decoded); - } - } catch { - // Malformed percent-encoding: raw needle is already registered. - } -} - -function collectSecretNeedles(postgresUrl: string): readonly string[] { - const needles = new Set(); - if (postgresUrl.length > 0) { - needles.add(postgresUrl); - } - try { - const parsed = new URL(postgresUrl); - if (parsed.href.length > 0) { - needles.add(parsed.href); - } - addRawAndDecodedNeedle(needles, parsed.password); - for (const [key, value] of parsed.searchParams.entries()) { - if (key.toLowerCase() === 'password' && value.length > 0) { - needles.add(value); - } - } - if (parsed.search.length > 1) { - const pairs = parsed.search.slice(1).split('&'); - for (let i = 0; i < pairs.length; i += 1) { - const pair = pairs[i] as string; - const eqIdx = pair.indexOf('='); - if (eqIdx <= 0) { - continue; - } - const rawKey = pair.slice(0, eqIdx); - let decodedKey = rawKey; - try { - decodedKey = decodeURIComponent(rawKey); - } catch { - // Keep rawKey if percent-decoding fails. - } - if (decodedKey.toLowerCase() === 'password') { - addRawAndDecodedNeedle(needles, pair.slice(eqIdx + 1)); - } - } - } - } catch { - // Non-URL postgresUrl passed directly to runResearchCopilotStdioHost: raw string is covered. - } - return Array.from(needles); -} - -function containsAnyNeedle(text: string, needles: readonly string[]): boolean { - for (let i = 0; i < needles.length; i += 1) { - if (text.includes(needles[i] as string)) { - return true; - } - } - return false; -} - -function isErrorSafeToSurface( - error: unknown, - needles: readonly string[], - visited: Set = new Set(), - depth = 0 -): error is Error { - if (!(error instanceof Error) || depth > 8) { - return false; - } - if (visited.has(error)) { - return true; - } - visited.add(error); - - try { - const message = error.message; - if (typeof message !== 'string' || containsAnyNeedle(message, needles)) { - return false; - } - const stack = error.stack; - if (typeof stack === 'string' && containsAnyNeedle(stack, needles)) { - return false; - } - const cause = (error as { readonly cause?: unknown }).cause; - if (cause !== undefined && !isErrorSafeToSurface(cause, needles, visited, depth + 1)) { - return false; - } - if (error instanceof AggregateError || 'errors' in error) { - const nested = (error as { readonly errors?: unknown }).errors; - if (nested !== undefined) { - if (!Array.isArray(nested)) { - return false; - } - for (let i = 0; i < nested.length; i += 1) { - if (!isErrorSafeToSurface(nested[i], needles, visited, depth + 1)) { - return false; - } - } - } - } - return true; - } catch { - return false; - } -} - -function sanitizeHostError( - error: unknown, - stage: HostStage, - needles: readonly string[] -): Error { - if (isErrorSafeToSurface(error, needles)) { - return error; - } - return new Error(STAGE_ERROR_MESSAGES[stage]); -} - -function validateHostDeps(deps: ResearchCopilotStdioHostDeps): void { - if (typeof deps !== 'object' || deps === null) { - throw new Error('Invalid `deps`: expected a ResearchCopilotStdioHostDeps object.'); - } - if (typeof deps.config !== 'object' || deps.config === null) { - throw new Error('Invalid `deps.config`: expected a ResearchCopilotHostConfig object.'); - } - if (typeof deps.openExecutor !== 'function') { - throw new Error('Invalid `deps.openExecutor`: expected a callable factory function.'); - } - if (typeof deps.openStore !== 'function') { - throw new Error('Invalid `deps.openStore`: expected a callable factory function.'); - } - if (typeof deps.createLibraryCardReader !== 'function') { - throw new Error( - 'Invalid `deps.createLibraryCardReader`: expected a callable factory function.' - ); - } - if (typeof deps.newId !== 'function') { - throw new Error('Invalid `deps.newId`: expected a callable ID generator function.'); - } - if (typeof deps.now !== 'function') { - throw new Error('Invalid `deps.now`: expected a callable clock function.'); - } -} - -/** - * Composes and runs the headless MCP research copilot over stdio using - * caller-injected resource factories. - * - * - Acquires resources sequentially (`openExecutor` -> `openStore` -> - * `createLibraryCardReader`) before serving any stdio input. - * - Uses `config.vaultCutoffTs` as the single authoritative Vault cutoff; the - * caller's `openStore` factory must configure the store with that same cutoff. - * - Always closes every acquired resource exactly once in reverse acquisition - * order on EOF or error, preserving the primary failure when safe and - * replacing credential-bearing or uninspectable errors with a fixed - * stage-specific error without a raw `cause`. - */ -export async function runResearchCopilotStdioHost( - deps: ResearchCopilotStdioHostDeps -): Promise { - validateHostDeps(deps); - - const { config } = deps; - const secretNeedles = collectSecretNeedles( - typeof config.postgresUrl === 'string' ? config.postgresUrl : '' - ); - - const closers: Array<() => Promise | void> = []; - let primaryError: { readonly error: unknown; readonly stage: HostStage } | null = null; - - try { - let executorHandle: ManagedPostgresExecutor; - try { - executorHandle = await deps.openExecutor(config); - } catch (error) { - primaryError = { error, stage: 'executor_open' }; - throw error; - } - - if ( - typeof executorHandle !== 'object' || - executorHandle === null || - typeof executorHandle.close !== 'function' - ) { - const error = new Error( - 'Invalid executor handle: expected an object with executor and close().' - ); - primaryError = { error, stage: 'executor_open' }; - throw error; - } - closers.push(() => executorHandle.close()); - - let storeHandle: ManagedMarketDataStore; - try { - storeHandle = await deps.openStore(config); - } catch (error) { - primaryError = { error, stage: 'store_open' }; - throw error; - } - - if ( - typeof storeHandle !== 'object' || - storeHandle === null || - typeof storeHandle.close !== 'function' - ) { - const error = new Error( - 'Invalid store handle: expected an object with store and close().' - ); - primaryError = { error, stage: 'store_open' }; - throw error; - } - closers.push(() => storeHandle.close()); - - let libraryReader: LibraryCardReaderHandle; - try { - libraryReader = await deps.createLibraryCardReader(config); - } catch (error) { - primaryError = { error, stage: 'library_reader' }; - throw error; - } - - if ( - typeof libraryReader !== 'object' || - libraryReader === null || - typeof libraryReader.listLibraryCards !== 'function' - ) { - const error = new Error( - 'Invalid library card reader: expected an object with listLibraryCards().' - ); - primaryError = { error, stage: 'library_reader' }; - throw error; - } - - let server: McpServer; - try { - const sessionDates = createBarSessionDatesPort({ - store: storeHandle.store, - referenceListingIds: config.referenceListingIds, - }); - - server = createPostgresResearchCopilotServer({ - name: RESEARCH_COPILOT_HOST_NAME, - version: RESEARCH_COPILOT_HOST_VERSION, - executor: executorHandle.executor, - ...(config.postgresSchema !== undefined ? { schema: config.postgresSchema } : {}), - store: storeHandle.store, - vaultContext: { vaultCutoffTs: config.vaultCutoffTs }, - principalId: config.principalId, - listLibraryCards: query => libraryReader.listLibraryCards(query), - sessionDates, - ...(config.earlyCloses !== undefined ? { earlyCloses: config.earlyCloses } : {}), - newId: deps.newId, - now: deps.now, - }); - } catch (error) { - primaryError = { error, stage: 'server_init' }; - throw error; - } - - try { - await runStdioServer(server, deps.stdio); - } catch (error) { - primaryError = { error, stage: 'stdio_serve' }; - throw error; - } - } catch (error) { - if (primaryError === null) { - primaryError = { error, stage: 'server_init' }; - } - } - - let firstCloseError: { readonly error: unknown } | null = null; - for (let i = closers.length - 1; i >= 0; i -= 1) { - try { - await closers[i]?.(); - } catch (closeErr) { - if (firstCloseError === null) { - firstCloseError = { error: closeErr }; - } - } - } - - if (primaryError !== null) { - throw sanitizeHostError(primaryError.error, primaryError.stage, secretNeedles); - } - if (firstCloseError !== null) { - throw sanitizeHostError(firstCloseError.error, 'cleanup', secretNeedles); - } -} diff --git a/libs/research/src/mcp/index.ts b/libs/research/src/mcp/index.ts deleted file mode 100644 index 9ffe9a0a..00000000 --- a/libs/research/src/mcp/index.ts +++ /dev/null @@ -1,18 +0,0 @@ -export * from './adapters/library-cards'; -export * from './adapters/postgres-findings'; -export * from './adapters/postgres-symbol-search'; -export * from './adapters/postgres-trial-ref'; -export * from './adapters/exchange-calendars'; -export * from './copilot-server'; -export * from './protocol'; -export * from './server'; -export * from './stdio'; -export * from './tools/analyze-signal'; -export * from './tools/event-study'; -export * from './tools/file-finding'; -export * from './tools/query-data'; -export * from './tools/read-knowledge'; -export * from './tools/search-symbols'; -export * from './adapters/postgres-copilot'; -export * from './adapters/bar-session-dates'; -export * from './host/stdio-host'; diff --git a/libs/research/src/mcp/protocol.ts b/libs/research/src/mcp/protocol.ts deleted file mode 100644 index fe7efcd6..00000000 --- a/libs/research/src/mcp/protocol.ts +++ /dev/null @@ -1,274 +0,0 @@ -import { z } from 'zod'; - -/** Supported Model Context Protocol revision. */ -export const MCP_PROTOCOL_VERSION = '2025-03-26'; - -/** Standard JSON-RPC 2.0 error codes. */ -export const JSON_RPC_ERROR_CODES = { - PARSE_ERROR: -32700, - INVALID_REQUEST: -32600, - METHOD_NOT_FOUND: -32601, - INVALID_PARAMS: -32602, - INTERNAL_ERROR: -32603, -} as const; - -export type JsonRpcErrorCode = (typeof JSON_RPC_ERROR_CODES)[keyof typeof JSON_RPC_ERROR_CODES]; - -/** Valid JSON-RPC 2.0 request identifier (string or finite number). */ -export const jsonRpcIdSchema = z.union([z.string(), z.number().finite()]); -export type JsonRpcId = z.infer; - -/** Strict JSON-RPC 2.0 request envelope (must carry a valid `id`). */ -export const jsonRpcRequestSchema = z - .object({ - jsonrpc: z.literal('2.0'), - id: jsonRpcIdSchema, - method: z.string().min(1), - params: z.unknown().optional(), - }) - .strict(); - -export type JsonRpcRequest = z.infer; - -/** Strict JSON-RPC 2.0 notification envelope (must NOT carry an `id`). */ -export const jsonRpcNotificationSchema = z - .object({ - jsonrpc: z.literal('2.0'), - method: z.string().min(1), - params: z.unknown().optional(), - }) - .strict(); - -export type JsonRpcNotification = z.infer; - -export type JsonRpcMessage = JsonRpcRequest | JsonRpcNotification; - -export interface JsonRpcSuccessResponse { - readonly jsonrpc: '2.0'; - readonly id: JsonRpcId; - readonly result: unknown; -} - -export interface JsonRpcErrorObject { - readonly code: number; - readonly message: string; - readonly data?: unknown; -} - -export interface JsonRpcErrorResponse { - readonly jsonrpc: '2.0'; - readonly id: JsonRpcId | null; - readonly error: JsonRpcErrorObject; -} - -export type JsonRpcResponse = JsonRpcSuccessResponse | JsonRpcErrorResponse; - -/** MCP text content block returned inside `tools/call` results. */ -export interface McpTextContent { - readonly type: 'text'; - readonly text: string; -} - -/** MCP `tools/call` result envelope. */ -export interface McpToolCallResult { - readonly content: readonly McpTextContent[]; - readonly isError?: boolean; -} - -/** Minimal JSON Schema Draft 7/2020-12 property definition for MCP tool inputs. */ -export interface JsonSchemaProperty { - readonly type?: 'string' | 'number' | 'integer' | 'boolean' | 'array' | 'object' | 'null'; - readonly description?: string; - readonly enum?: readonly (string | number | boolean | null)[]; - readonly const?: string | number | boolean | null; - readonly minimum?: number; - readonly maximum?: number; - readonly exclusiveMinimum?: number; - readonly exclusiveMaximum?: number; - readonly minLength?: number; - readonly maxLength?: number; - readonly minItems?: number; - readonly maxItems?: number; - readonly items?: JsonSchemaProperty; - readonly properties?: Readonly>; - readonly required?: readonly string[]; - readonly additionalProperties?: boolean; - readonly anyOf?: readonly JsonSchemaProperty[]; - readonly default?: unknown; -} - -/** Strict top-level JSON Schema object emitted by `tools/list`. */ -export interface JsonSchemaObject { - readonly type: 'object'; - readonly properties: Readonly>; - readonly required?: readonly string[]; - readonly additionalProperties: false; - readonly description?: string; -} - -/** Tool metadata returned in `tools/list`. */ -export interface McpToolDescriptor { - readonly name: string; - readonly description: string; - readonly inputSchema: JsonSchemaObject; -} - -/** Valid MCP progress token (`string | finite number`). */ -export const mcpProgressTokenSchema = z.union([z.string(), z.number().finite()]); -export type McpProgressToken = z.infer; - -/** Standard optional MCP `_meta` request/notification metadata bag. */ -export const mcpRequestMetaSchema = z - .object({ - progressToken: mcpProgressTokenSchema.optional(), - }) - .passthrough(); -export type McpRequestMeta = z.infer; - -const jsonObjectSchema = z.custom>( - (value): value is Record => - typeof value === 'object' && value !== null && !Array.isArray(value), - { message: 'Expected a JSON object.' } -); - -/** Strict MCP `initialize` params schema. */ -export const mcpInitializeParamsSchema = z - .object({ - protocolVersion: z.string().min(1).optional(), - capabilities: z.record(z.unknown()).optional(), - clientInfo: z - .object({ - name: z.string().min(1), - version: z.string().min(1), - }) - .strict() - .optional(), - _meta: mcpRequestMetaSchema.optional(), - }) - .strict(); - -/** Strict MCP `notifications/initialized` params schema. */ -export const mcpInitializedNotificationParamsSchema = z - .object({ - _meta: mcpRequestMetaSchema.optional(), - }) - .strict(); - -/** Strict MCP `ping` params schema. */ -export const mcpPingParamsSchema = z - .object({ - _meta: mcpRequestMetaSchema.optional(), - }) - .strict(); - -/** Strict MCP `tools/list` params schema. */ -export const mcpToolsListParamsSchema = z - .object({ - cursor: z.string().min(1).optional(), - _meta: mcpRequestMetaSchema.optional(), - }) - .strict(); - -/** Strict MCP `tools/call` params schema (preserves own keys on `arguments`). */ -export const mcpToolsCallParamsSchema = z - .object({ - name: z.string().min(1), - arguments: jsonObjectSchema.optional(), - _meta: mcpRequestMetaSchema.optional(), - }) - .strict(); - -export type ParsedJsonRpcMessage = - | { readonly ok: true; readonly kind: 'request'; readonly message: JsonRpcRequest } - | { readonly ok: true; readonly kind: 'notification'; readonly message: JsonRpcNotification } - | { - readonly ok: false; - readonly errorCode: JsonRpcErrorCode; - readonly message: string; - }; - -/** - * Parses a raw JSON-RPC 2.0 message string. - * - * - Malformed JSON returns `PARSE_ERROR` (-32700). - * - Non-object payloads or invalid envelopes (including an explicit invalid `id` - * such as `id: null` or `id: true`) return `INVALID_REQUEST` (-32600). - * - Objects without an `id` property are parsed as notifications. - */ -export function parseJsonRpcMessage(raw: string): ParsedJsonRpcMessage { - let parsed: unknown; - try { - parsed = JSON.parse(raw); - } catch { - return { - ok: false, - errorCode: JSON_RPC_ERROR_CODES.PARSE_ERROR, - message: 'Parse error: invalid JSON.', - }; - } - - if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) { - return { - ok: false, - errorCode: JSON_RPC_ERROR_CODES.INVALID_REQUEST, - message: 'Invalid Request: expected a JSON-RPC 2.0 object.', - }; - } - - const hasId = Object.prototype.hasOwnProperty.call(parsed, 'id'); - if (hasId) { - const requestResult = jsonRpcRequestSchema.safeParse(parsed); - if (!requestResult.success) { - return { - ok: false, - errorCode: JSON_RPC_ERROR_CODES.INVALID_REQUEST, - message: 'Invalid Request: malformed JSON-RPC 2.0 request envelope.', - }; - } - return { - ok: true, - kind: 'request', - message: requestResult.data, - }; - } - - const notificationResult = jsonRpcNotificationSchema.safeParse(parsed); - if (!notificationResult.success) { - return { - ok: false, - errorCode: JSON_RPC_ERROR_CODES.INVALID_REQUEST, - message: 'Invalid Request: malformed JSON-RPC 2.0 notification envelope.', - }; - } - - return { - ok: true, - kind: 'notification', - message: notificationResult.data, - }; -} - -/** Builds a JSON-RPC 2.0 success response object. */ -export function jsonRpcSuccess(id: JsonRpcId, result: unknown): JsonRpcSuccessResponse { - return { - jsonrpc: '2.0', - id, - result, - }; -} - -/** Builds a JSON-RPC 2.0 error response object. */ -export function jsonRpcError( - id: JsonRpcId | null, - code: number, - message: string, - data?: unknown -): JsonRpcErrorResponse { - const error: JsonRpcErrorObject = - data !== undefined ? { code, message, data } : { code, message }; - return { - jsonrpc: '2.0', - id, - error, - }; -} diff --git a/libs/research/src/mcp/server.ts b/libs/research/src/mcp/server.ts deleted file mode 100644 index dec43185..00000000 --- a/libs/research/src/mcp/server.ts +++ /dev/null @@ -1,536 +0,0 @@ -import { z } from 'zod'; -import { - JSON_RPC_ERROR_CODES, - type JsonSchemaObject, - type JsonSchemaProperty, - MCP_PROTOCOL_VERSION, - type McpToolCallResult, - type McpToolDescriptor, - jsonRpcError, - jsonRpcSuccess, - mcpInitializeParamsSchema, - mcpPingParamsSchema, - mcpToolsCallParamsSchema, - mcpToolsListParamsSchema, - parseJsonRpcMessage, -} from './protocol'; - -/** Configuration for defining a strongly typed MCP tool. */ -export interface McpToolDefinition { - readonly name: string; - readonly description: string; - readonly inputSchema: z.ZodType; - readonly jsonSchema?: JsonSchemaObject; - readonly handler: (input: TInput) => Promise | McpToolCallResult; -} - -/** Type-erased tool entry registered on an {@link McpServer}. */ -export interface McpToolEntry { - readonly name: string; - readonly description: string; - readonly inputSchema: JsonSchemaObject; - readonly execute: (rawArguments: Record) => Promise; -} - -/** Options for {@link createMcpServer}. */ -export interface McpServerOptions { - readonly name: string; - readonly version: string; - readonly tools?: readonly McpToolEntry[]; -} - -/** Transport-agnostic MCP JSON-RPC 2.0 server interface. */ -export interface McpServer { - readonly name: string; - readonly version: string; - listTools(): readonly McpToolDescriptor[]; - handleMessage(raw: string): Promise; -} - -function isOptionalSchema(schema: z.ZodTypeAny): boolean { - if (schema instanceof z.ZodOptional || schema instanceof z.ZodDefault) { - return true; - } - if (schema instanceof z.ZodEffects) { - return isOptionalSchema(schema._def.schema); - } - return false; -} - -function withDescription( - prop: JsonSchemaProperty, - description: string | undefined -): JsonSchemaProperty { - if (description !== undefined && prop.description === undefined) { - return { ...prop, description }; - } - return prop; -} - -function convertZodType(schema: z.ZodTypeAny): JsonSchemaProperty { - const outerDescription = schema.description; - - if (schema instanceof z.ZodEffects) { - return withDescription(convertZodType(schema._def.schema), outerDescription); - } - - if (schema instanceof z.ZodOptional) { - return withDescription(convertZodType(schema.unwrap()), outerDescription); - } - - if (schema instanceof z.ZodDefault) { - const inner = convertZodType(schema._def.innerType); - const defaultValue: unknown = schema._def.defaultValue(); - return withDescription({ ...inner, default: defaultValue }, outerDescription); - } - - if (schema instanceof z.ZodNullable) { - const inner = convertZodType(schema.unwrap()); - return withDescription({ anyOf: [inner, { type: 'null' }] }, outerDescription); - } - - if (schema instanceof z.ZodString) { - let minLength: number | undefined; - let maxLength: number | undefined; - for (const check of schema._def.checks) { - if (check.kind === 'min') { - minLength = check.value; - } else if (check.kind === 'max') { - maxLength = check.value; - } else if (check.kind === 'length') { - minLength = check.value; - maxLength = check.value; - } - } - const result: { - type: 'string'; - description?: string; - minLength?: number; - maxLength?: number; - } = { type: 'string' }; - if (outerDescription !== undefined) { - result.description = outerDescription; - } - if (minLength !== undefined) { - result.minLength = minLength; - } - if (maxLength !== undefined) { - result.maxLength = maxLength; - } - return result; - } - - if (schema instanceof z.ZodNumber) { - let isInt = false; - let minimum: number | undefined; - let maximum: number | undefined; - let exclusiveMinimum: number | undefined; - let exclusiveMaximum: number | undefined; - for (const check of schema._def.checks) { - if (check.kind === 'int') { - isInt = true; - } else if (check.kind === 'min') { - if (check.inclusive) { - minimum = check.value; - } else { - exclusiveMinimum = check.value; - } - } else if (check.kind === 'max') { - if (check.inclusive) { - maximum = check.value; - } else { - exclusiveMaximum = check.value; - } - } - } - const result: { - type: 'integer' | 'number'; - description?: string; - minimum?: number; - maximum?: number; - exclusiveMinimum?: number; - exclusiveMaximum?: number; - } = { type: isInt ? 'integer' : 'number' }; - if (outerDescription !== undefined) { - result.description = outerDescription; - } - if (minimum !== undefined) { - result.minimum = minimum; - } - if (maximum !== undefined) { - result.maximum = maximum; - } - if (exclusiveMinimum !== undefined) { - result.exclusiveMinimum = exclusiveMinimum; - } - if (exclusiveMaximum !== undefined) { - result.exclusiveMaximum = exclusiveMaximum; - } - return result; - } - - if (schema instanceof z.ZodBoolean) { - return outerDescription !== undefined - ? { type: 'boolean', description: outerDescription } - : { type: 'boolean' }; - } - - if (schema instanceof z.ZodEnum) { - const values = [...schema._def.values] as readonly string[]; - return outerDescription !== undefined - ? { type: 'string', enum: values, description: outerDescription } - : { type: 'string', enum: values }; - } - - if (schema instanceof z.ZodLiteral) { - const literalValue: unknown = schema._def.value; - if ( - typeof literalValue === 'string' || - typeof literalValue === 'number' || - typeof literalValue === 'boolean' || - literalValue === null - ) { - const literalType: JsonSchemaProperty['type'] = - literalValue === null - ? 'null' - : typeof literalValue === 'string' - ? 'string' - : typeof literalValue === 'number' - ? 'number' - : 'boolean'; - return outerDescription !== undefined - ? { type: literalType, const: literalValue, description: outerDescription } - : { type: literalType, const: literalValue }; - } - throw new Error('Unsupported ZodLiteral value type in MCP tool input schema.'); - } - - if (schema instanceof z.ZodArray) { - const items = convertZodType(schema._def.type); - const result: { - type: 'array'; - items: JsonSchemaProperty; - description?: string; - minItems?: number; - maxItems?: number; - } = { type: 'array', items }; - if (outerDescription !== undefined) { - result.description = outerDescription; - } - if (schema._def.minLength !== null) { - result.minItems = schema._def.minLength.value; - } - if (schema._def.maxLength !== null) { - result.maxItems = schema._def.maxLength.value; - } - if (schema._def.exactLength !== null) { - result.minItems = schema._def.exactLength.value; - result.maxItems = schema._def.exactLength.value; - } - return result; - } - - if (schema instanceof z.ZodUnion) { - const options = (schema._def.options as readonly z.ZodTypeAny[]).map(option => - convertZodType(option) - ); - return outerDescription !== undefined - ? { anyOf: options, description: outerDescription } - : { anyOf: options }; - } - - if (schema instanceof z.ZodObject) { - return convertZodObject(schema, outerDescription); - } - - const typeName = - typeof (schema._def as { typeName?: unknown }).typeName === 'string' - ? (schema._def as { typeName: string }).typeName - : 'unknown'; - throw new Error(`Unsupported Zod schema type "${typeName}" in MCP tool input schema.`); -} - -function convertZodObject( - schema: z.ZodObject, - outerDescription: string | undefined -): JsonSchemaObject { - const shape = schema.shape; - const properties: Record = {}; - const required: string[] = []; - - for (const [key, fieldSchema] of Object.entries(shape)) { - properties[key] = convertZodType(fieldSchema); - if (!isOptionalSchema(fieldSchema)) { - required.push(key); - } - } - - const description = outerDescription ?? schema.description; - const result: { - type: 'object'; - properties: Record; - required?: string[]; - additionalProperties: false; - description?: string; - } = { - type: 'object', - properties, - additionalProperties: false, - }; - - if (required.length > 0) { - result.required = required; - } - if (description !== undefined) { - result.description = description; - } - return result; -} - -/** - * Converts a Zod v3 object schema (including `.refine()` / `.superRefine()` - * `ZodEffects` wrappers) into a strict {@link JsonSchemaObject}. - * - * Fails fast on unsupported Zod schema types so misconfigured tools are caught - * at registration time rather than at `tools/list` time. - */ -export function zodObjectToJsonSchema(schema: z.ZodTypeAny): JsonSchemaObject { - let current: z.ZodTypeAny = schema; - let description = schema.description; - - while (current instanceof z.ZodEffects) { - current = current._def.schema; - if (description === undefined && current.description !== undefined) { - description = current.description; - } - } - - if (!(current instanceof z.ZodObject)) { - throw new Error('MCP tool inputSchema must be a ZodObject (optionally wrapped in ZodEffects).'); - } - - return convertZodObject(current, description); -} - -function formatZodIssues(error: z.ZodError): string { - const parts = error.issues.map(issue => { - const path = issue.path.length > 0 ? `${issue.path.join('.')}: ` : ''; - return `${path}${issue.message}`; - }); - return parts.join('; '); -} - -const SAFE_ERROR_NAME_RE = /^[A-Za-z][A-Za-z0-9_]{0,63}$/; - -function sanitizeToolError(err: unknown): string { - if (err instanceof Error) { - const rawName = typeof err.name === 'string' ? err.name.trim() : ''; - const safeName = SAFE_ERROR_NAME_RE.test(rawName) ? rawName : 'Error'; - return `${safeName}: Tool execution failed.`; - } - return 'Error: Tool execution failed.'; -} - -/** - * Defines a type-erased MCP tool entry with eager JSON Schema generation, - * strict argument validation, and sanitized error handling. - */ -export function defineMcpTool(definition: McpToolDefinition): McpToolEntry { - if (typeof definition.name !== 'string' || definition.name.trim().length === 0) { - throw new Error('MCP tool name must be a non-empty string.'); - } - if (typeof definition.description !== 'string' || definition.description.trim().length === 0) { - throw new Error(`MCP tool "${definition.name}" description must be a non-empty string.`); - } - - const resolvedSchema: JsonSchemaObject = - definition.jsonSchema ?? zodObjectToJsonSchema(definition.inputSchema); - - return { - name: definition.name, - description: definition.description, - inputSchema: resolvedSchema, - async execute(rawArguments: Record): Promise { - const parsed = definition.inputSchema.safeParse(rawArguments); - if (!parsed.success) { - return { - content: [ - { - type: 'text', - text: `Invalid arguments for tool "${definition.name}": ${formatZodIssues(parsed.error)}`, - }, - ], - isError: true, - }; - } - - try { - return await definition.handler(parsed.data); - } catch (err: unknown) { - return { - content: [ - { - type: 'text', - text: sanitizeToolError(err), - }, - ], - isError: true, - }; - } - }, - }; -} - -/** - * Creates a transport-agnostic MCP JSON-RPC 2.0 server with a validated tool - * registry. - */ -export function createMcpServer(options: McpServerOptions): McpServer { - if (typeof options.name !== 'string' || options.name.trim().length === 0) { - throw new Error('MCP server name must be a non-empty string.'); - } - if (typeof options.version !== 'string' || options.version.trim().length === 0) { - throw new Error('MCP server version must be a non-empty string.'); - } - - const toolMap = new Map(); - const toolDescriptors: McpToolDescriptor[] = []; - - for (const tool of options.tools ?? []) { - if (toolMap.has(tool.name)) { - throw new Error(`Duplicate MCP tool name: "${tool.name}".`); - } - toolMap.set(tool.name, tool); - toolDescriptors.push({ - name: tool.name, - description: tool.description, - inputSchema: tool.inputSchema, - }); - } - - const frozenDescriptors: readonly McpToolDescriptor[] = Object.freeze([...toolDescriptors]); - - return { - name: options.name, - version: options.version, - - listTools(): readonly McpToolDescriptor[] { - return frozenDescriptors; - }, - - async handleMessage(raw: string): Promise { - const parsed = parseJsonRpcMessage(raw); - if (!parsed.ok) { - return JSON.stringify(jsonRpcError(null, parsed.errorCode, parsed.message)); - } - - if (parsed.kind === 'notification') { - return null; - } - - const { id, method, params } = parsed.message; - - switch (method) { - case 'initialize': { - if (params !== undefined) { - const initParams = mcpInitializeParamsSchema.safeParse(params); - if (!initParams.success) { - return JSON.stringify( - jsonRpcError( - id, - JSON_RPC_ERROR_CODES.INVALID_PARAMS, - `Invalid params for initialize: ${formatZodIssues(initParams.error)}` - ) - ); - } - } - return JSON.stringify( - jsonRpcSuccess(id, { - protocolVersion: MCP_PROTOCOL_VERSION, - capabilities: { - tools: {}, - }, - serverInfo: { - name: options.name, - version: options.version, - }, - }) - ); - } - - case 'ping': { - if (params !== undefined) { - const pingParams = mcpPingParamsSchema.safeParse(params); - if (!pingParams.success) { - return JSON.stringify( - jsonRpcError( - id, - JSON_RPC_ERROR_CODES.INVALID_PARAMS, - `Invalid params for ping: ${formatZodIssues(pingParams.error)}` - ) - ); - } - } - return JSON.stringify(jsonRpcSuccess(id, {})); - } - - case 'tools/list': { - if (params !== undefined) { - const listParams = mcpToolsListParamsSchema.safeParse(params); - if (!listParams.success) { - return JSON.stringify( - jsonRpcError( - id, - JSON_RPC_ERROR_CODES.INVALID_PARAMS, - `Invalid params for tools/list: ${formatZodIssues(listParams.error)}` - ) - ); - } - } - return JSON.stringify( - jsonRpcSuccess(id, { - tools: frozenDescriptors, - }) - ); - } - - case 'tools/call': { - const callParams = mcpToolsCallParamsSchema.safeParse(params); - if (!callParams.success) { - return JSON.stringify( - jsonRpcError( - id, - JSON_RPC_ERROR_CODES.INVALID_PARAMS, - `Invalid params for tools/call: ${formatZodIssues(callParams.error)}` - ) - ); - } - - const tool = toolMap.get(callParams.data.name); - if (tool === undefined) { - return JSON.stringify( - jsonRpcError( - id, - JSON_RPC_ERROR_CODES.INVALID_PARAMS, - `Unknown tool: "${callParams.data.name}".` - ) - ); - } - - const result = await tool.execute(callParams.data.arguments ?? {}); - return JSON.stringify(jsonRpcSuccess(id, result)); - } - - default: { - return JSON.stringify( - jsonRpcError( - id, - JSON_RPC_ERROR_CODES.METHOD_NOT_FOUND, - `Method not found: "${method}".` - ) - ); - } - } - }, - }; -} diff --git a/libs/research/src/mcp/stdio.ts b/libs/research/src/mcp/stdio.ts deleted file mode 100644 index 580c3b6e..00000000 --- a/libs/research/src/mcp/stdio.ts +++ /dev/null @@ -1,147 +0,0 @@ -import { JSON_RPC_ERROR_CODES, jsonRpcError } from './protocol'; -import type { McpServer } from './server'; - -/** Default maximum allowed line frame size in UTF-8 bytes (4 MiB). */ -export const DEFAULT_STDIO_MAX_LINE_BYTES = 4 * 1024 * 1024; - -/** Readable byte/string stream accepted by {@link runStdioServer}. */ -export type StdioInput = AsyncIterable; - -/** Minimal writable stream interface accepted by {@link runStdioServer}. */ -export interface StdioOutput { - write(chunk: string): boolean; - once?(event: 'drain', listener: () => void): unknown; -} - -/** Options for {@link runStdioServer}. */ -export interface StdioServerOptions { - readonly input?: StdioInput; - readonly output?: StdioOutput; - readonly maxLineBytes?: number; -} - -async function writeLine(output: StdioOutput, line: string): Promise { - const ok = output.write(`${line}\n`); - if (!ok && typeof output.once === 'function') { - await new Promise(resolve => { - output.once?.('drain', () => { - resolve(); - }); - }); - } -} - -/** - * Runs a newline-delimited JSON-RPC 2.0 stdio transport loop for an - * {@link McpServer}. - * - * - Decodes binary chunks with streaming UTF-8 (`TextDecoder`) so multi-byte - * characters split across chunk boundaries are never corrupted. - * - Dispatches lines strictly sequentially in arrival order. - * - Writes only compact newline-terminated JSON-RPC responses to `output` - * (skipping `null` notification results and blank lines). - * - Guards against oversized unterminated frames via `maxLineBytes`. - */ -export async function runStdioServer( - server: McpServer, - options?: StdioServerOptions -): Promise { - const input: StdioInput = options?.input ?? process.stdin; - const output: StdioOutput = options?.output ?? process.stdout; - const maxLineBytes = options?.maxLineBytes ?? DEFAULT_STDIO_MAX_LINE_BYTES; - - if (!Number.isSafeInteger(maxLineBytes) || maxLineBytes < 1) { - throw new Error(`Invalid maxLineBytes (${String(maxLineBytes)}): expected a positive integer.`); - } - - const decoder = new TextDecoder('utf-8'); - const encoder = new TextEncoder(); - let buffer = ''; - let droppingOversizedLine = false; - - const processLine = async (rawLine: string): Promise => { - const trimmed = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine; - if (trimmed.trim().length === 0) { - return; - } - const response = await server.handleMessage(trimmed); - if (response !== null) { - await writeLine(output, response); - } - }; - - const emitOversizedError = async (): Promise => { - const errorPayload = JSON.stringify( - jsonRpcError( - null, - JSON_RPC_ERROR_CODES.PARSE_ERROR, - `Parse error: message exceeds maximum frame size of ${maxLineBytes} bytes.` - ) - ); - await writeLine(output, errorPayload); - }; - - const drainBuffer = async (): Promise => { - while (true) { - const newlineIdx = buffer.indexOf('\n'); - if (newlineIdx === -1) { - if (!droppingOversizedLine && encoder.encode(buffer).byteLength > maxLineBytes) { - droppingOversizedLine = true; - buffer = ''; - await emitOversizedError(); - } - return; - } - - const rawLine = buffer.slice(0, newlineIdx); - buffer = buffer.slice(newlineIdx + 1); - - if (droppingOversizedLine) { - droppingOversizedLine = false; - continue; - } - - if (encoder.encode(rawLine).byteLength > maxLineBytes) { - await emitOversizedError(); - continue; - } - - await processLine(rawLine); - } - }; - - for await (const chunk of input) { - const text = typeof chunk === 'string' ? chunk : decoder.decode(chunk, { stream: true }); - if (text.length === 0) { - continue; - } - - if (droppingOversizedLine) { - const newlineIdx = text.indexOf('\n'); - if (newlineIdx === -1) { - continue; - } - droppingOversizedLine = false; - buffer = text.slice(newlineIdx + 1); - } else { - buffer += text; - } - - await drainBuffer(); - } - - const tail = decoder.decode(); - if (tail.length > 0 && !droppingOversizedLine) { - buffer += tail; - } - - await drainBuffer(); - - if (!droppingOversizedLine && buffer.length > 0) { - if (encoder.encode(buffer).byteLength > maxLineBytes) { - await emitOversizedError(); - } else { - await processLine(buffer); - } - } -} diff --git a/libs/research/src/mcp/tools/analyze-signal.ts b/libs/research/src/mcp/tools/analyze-signal.ts deleted file mode 100644 index 0103f10a..00000000 --- a/libs/research/src/mcp/tools/analyze-signal.ts +++ /dev/null @@ -1,1201 +0,0 @@ -import { - type IcSummary, - type RecencySplitResult, - type SignalPanelAnalysis, - type SignalPanelDiagnostics as CalcSignalPanelDiagnostics, - analyzeSignalPanel, -} from '@stock-bot/calculations'; -import { z } from 'zod'; -import { - type BarRecord, - type MarketDataStore, - MarketDataStoreValidationError, - type Table, - type TableRow, - type VaultFenceContext, -} from '../../market-data-store'; -import { - FUNDAMENTALS_PIT_VALUE_FIELDS, - type FundamentalsPitValueField, - UNIVERSE_REFS, -} from '../../market-data-store-duckdb'; -import { - SHORTS_SIGNAL_FIELDS, - type SignalObservation, - type SignalPanelDiagnostics, - SignalPanelError, - type SignalPanelErrorCode, - buildForwardReturnPanel, - collectBars, - shortsTableToSignalRows, -} from '../../signal-panel'; -import { - type AnalyzeSignalInsufficientDataReason, - type SignalLedgerSeries, - SignalStudyError, - type SignalStudyErrorCode, - type SignalStudyExpression, - type StudyTrialSummary, - analyzeSignal, -} from '../../signal-study'; -import { - type ClusterDeflatedSharpeResult, - HORIZON_BUCKETS, - type HorizonBucket, - TrialLedgerError, - type TrialLedgerErrorCode, - type TrialLedgerExecutor, - UNIVERSE_MARKETS, - type UniverseMarket, -} from '../../trial-ledger'; -import type { JsonSchemaObject, JsonSchemaProperty, McpToolCallResult } from '../protocol'; -import { type McpToolEntry, defineMcpTool, zodObjectToJsonSchema } from '../server'; -import { - EXCLUSIVE_LISTING_SELECTOR_MESSAGE, - MCP_MAX_LISTING_IDS, - createListingIdsFieldSchema, - createUniverseFieldSchema, - fenceVaultQueryBounds, - formatMappedStoreError, - formatUtcIsoWithMicros, - hasExclusiveListingSelector, - isValidUtcBoundString, - resolvePreStartUniverseDate, - utcDateOf, - validateVaultCutoffTs, -} from './vault-fenced-input'; - -/** Hard maximum number of explicit `listingIds` accepted by `analyze_signal`. */ -export const ANALYZE_SIGNAL_MAX_LISTING_IDS = MCP_MAX_LISTING_IDS; - -/** Hard maximum forward-return horizon in trading sessions. */ -export const ANALYZE_SIGNAL_MAX_HORIZON_SESSIONS = 252; - -/** Maximum number of latest dated observations exposed in the tool response preview. */ -export const ANALYZE_SIGNAL_MAX_SERIES_POINTS = 100; - -/** Hard maximum number of UTC month-end fundamentals snapshots queried in a single study. */ -export const ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS = 120; - -const LEDGER_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; -const AGENT_PRINCIPAL_RE = - /^agent:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; -const UTC_BOUND_ERROR_MESSAGE = - 'Expected YYYY-MM-DD calendar date or UTC ISO-8601 timestamp with timezone offset.'; -const SUPPORTED_UNIVERSE_REF_SET: ReadonlySet = new Set(UNIVERSE_REFS); - -function canonicalDailyHorizonBucket(horizonSessions: number): HorizonBucket { - return horizonSessions <= 10 ? 'swing_1_10d' : 'position_10d_plus'; -} - -const utcBoundStringSchema = z.string().min(1).refine(isValidUtcBoundString, UTC_BOUND_ERROR_MESSAGE); - -const shortsSignalSpecSchema = z - .object({ - source: z.literal('shorts').describe('Signal data source ("shorts").'), - field: z - .enum(SHORTS_SIGNAL_FIELDS) - .describe('Short-interest field to evaluate (shares_short, net_change, or pct_float).'), - }) - .strict() - .describe('Short-interest signal specification.'); - -const fundamentalsSignalSpecSchema = z - .object({ - source: z.literal('fundamentals').describe('Signal data source ("fundamentals").'), - field: z - .enum(FUNDAMENTALS_PIT_VALUE_FIELDS) - .describe( - 'Point-in-time fundamentals value field to evaluate (revenue, net_income, operating_cash_flow, total_assets, total_equity, shares_outstanding, ttm_revenue, ttm_net_income, or ttm_operating_cash_flow).' - ), - allowEstimatedLag: z - .boolean() - .default(false) - .describe( - 'Whether to include fundamentals snapshots with estimated publication lag (default false).' - ), - }) - .strict() - .describe('Point-in-time fundamentals signal specification.'); - -const signalSpecSchema = z - .discriminatedUnion('source', [shortsSignalSpecSchema, fundamentalsSignalSpecSchema]) - .describe('Discriminated signal source and field specification ("shorts" or "fundamentals").'); - -const analyzeSignalSharedFieldsSchema = z - .object({ - listingIds: createListingIdsFieldSchema( - 'Explicit INT32 listing IDs to study (mutually exclusive with universe).' - ), - universe: createUniverseFieldSchema( - 'Survivorship-free universe identifier such as US_EQ, CA_EQ, or US_CA_EQ (mutually exclusive with listingIds).' - ), - from: utcBoundStringSchema.describe( - 'Inclusive study start date (YYYY-MM-DD) or UTC ISO-8601 timestamp.' - ), - to: utcBoundStringSchema.describe( - 'Inclusive study end date (YYYY-MM-DD) or UTC ISO-8601 timestamp; clamped below Vault cutoff.' - ), - asOf: utcBoundStringSchema - .optional() - .describe( - 'Optional point-in-time knowledge cutoff (YYYY-MM-DD or UTC ISO-8601); clamped below Vault cutoff.' - ), - horizonSessions: z - .number() - .int() - .min(1) - .max(ANALYZE_SIGNAL_MAX_HORIZON_SESSIONS) - .describe( - `Forward-return horizon in trading sessions (1–${ANALYZE_SIGNAL_MAX_HORIZON_SESSIONS}).` - ), - maxSignalAgeSessions: z - .number() - .int() - .min(0) - .max(Number.MAX_SAFE_INTEGER) - .optional() - .describe('Optional maximum signal age in trading sessions before a signal is treated as stale.'), - universeMarket: z - .enum(UNIVERSE_MARKETS) - .describe('Relatedness-cluster market bucket recorded in trial_ledger.'), - horizonBucket: z - .enum(HORIZON_BUCKETS) - .describe('Relatedness-cluster horizon bucket recorded in trial_ledger.'), - ledgerSeries: z - .enum(['rank_ic', 'quantile_spread']) - .default('rank_ic') - .describe('Daily series recorded to trial_ledger and evaluated for DSR (default rank_ic).'), - campaignId: z - .string() - .regex(LEDGER_UUID_RE, 'Expected a UUID string.') - .optional() - .describe('Optional research campaign UUID recorded in trial_ledger.'), - hypothesisId: z - .string() - .regex(LEDGER_UUID_RE, 'Expected a UUID string.') - .optional() - .describe('Optional research hypothesis UUID recorded in trial_ledger.'), - adjustment: z - .enum(['raw', 'split', 'total']) - .default('raw') - .describe('Bar price adjustment mode (default raw).'), - }) - .strict(); - -/** - * Strict Zod input schema for the `analyze_signal` MCP tool. - * - * Intentionally omits `scope`, `vault_evaluation_only`, `principalId`, and - * `vaultCutoffDate`; `.strict()` rejects any caller attempt to supply them - * or any other unknown top-level or nested key. - */ -export const analyzeSignalInputSchema = analyzeSignalSharedFieldsSchema - .extend({ - signal: signalSpecSchema, - }) - .strict() - .superRefine((data, ctx) => { - if (!hasExclusiveListingSelector(data)) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: EXCLUSIVE_LISTING_SELECTOR_MESSAGE, - }); - } - - const expectedBucket = canonicalDailyHorizonBucket(data.horizonSessions); - if (data.horizonBucket !== expectedBucket) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - path: ['horizonBucket'], - message: `Daily horizonSessions=${data.horizonSessions} requires horizonBucket "${expectedBucket}".`, - }); - } - - if (data.universe !== undefined && SUPPORTED_UNIVERSE_REF_SET.has(data.universe)) { - if (data.universeMarket !== data.universe) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - path: ['universeMarket'], - message: `Named universe "${data.universe}" requires universeMarket "${data.universe}".`, - }); - } - } else if (data.universeMarket === 'FX') { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - path: ['universeMarket'], - message: - data.signal.source === 'shorts' - ? 'Short-interest signal studies require an equity universeMarket (US_EQ, CA_EQ, or US_CA_EQ).' - : 'Fundamentals signal studies require an equity universeMarket (US_EQ, CA_EQ, or US_CA_EQ).', - }); - } - }); - -export type AnalyzeSignalInput = z.infer; - -function buildAnalyzeSignalJsonSchema(): JsonSchemaObject { - const sharedSchema = zodObjectToJsonSchema(analyzeSignalSharedFieldsSchema); - const shortsBranch = zodObjectToJsonSchema(shortsSignalSpecSchema); - const fundamentalsBranch = zodObjectToJsonSchema(fundamentalsSignalSpecSchema); - const allowEstimatedLagProp = fundamentalsBranch.properties.allowEstimatedLag ?? { - type: 'boolean' as const, - default: false, - }; - const signalProperty: JsonSchemaProperty = { - type: 'object', - description: signalSpecSchema.description, - properties: { - source: { - type: 'string', - enum: ['shorts', 'fundamentals'], - description: 'Signal data source ("shorts" or "fundamentals").', - }, - field: { - type: 'string', - enum: [...SHORTS_SIGNAL_FIELDS, ...FUNDAMENTALS_PIT_VALUE_FIELDS], - description: 'Signal field name valid for the chosen source.', - }, - allowEstimatedLag: allowEstimatedLagProp, - }, - required: ['source', 'field'], - additionalProperties: false, - anyOf: [shortsBranch, fundamentalsBranch], - }; - - return { - type: 'object', - properties: { - ...sharedSchema.properties, - signal: signalProperty, - }, - required: [...(sharedSchema.required ?? []), 'signal'], - additionalProperties: false, - }; -} - -const ANALYZE_SIGNAL_JSON_SCHEMA: JsonSchemaObject = buildAnalyzeSignalJsonSchema(); - -/** Server-side injected configuration for {@link createAnalyzeSignalTool}. */ -export interface AnalyzeSignalToolOptions { - readonly store: MarketDataStore; - readonly ledger: TrialLedgerExecutor; - readonly vaultContext: Pick; - readonly principalId: string; -} - -/** Single dated observation in the bounded series preview. */ -export interface AnalyzeSignalSeriesPoint { - readonly date: string; - readonly value: number; -} - -/** Bounded preview of the selected ledger series (latest 100 observations). */ -export interface AnalyzeSignalSeriesPreview { - readonly series: SignalLedgerSeries; - readonly totalCount: number; - readonly truncated: boolean; - readonly points: readonly AnalyzeSignalSeriesPoint[]; -} - -/** Projected quantile-spread summary without raw per-bucket typed arrays. */ -export interface AnalyzeSignalQuantilesSummary { - readonly quantiles: number; - readonly validDates: number; - readonly skippedDates: number; - readonly bucketMeanReturns: readonly (number | null)[]; - readonly spreadSummary: IcSummary; -} - -/** Projected top/bottom quantile membership turnover summary. */ -export interface AnalyzeSignalTurnoverSummary { - readonly count: number; - readonly meanTopTurnover: number | null; - readonly meanBottomTurnover: number | null; -} - -/** Bounded summary projection of {@link SignalPanelAnalysis}. */ -export interface AnalyzeSignalAnalysisSummary { - readonly pearsonIc: IcSummary; - readonly rankIc: IcSummary; - readonly quantiles: AnalyzeSignalQuantilesSummary; - readonly turnover: AnalyzeSignalTurnoverSummary; - readonly recency: RecencySplitResult; - readonly diagnostics: CalcSignalPanelDiagnostics; - readonly ledgerSeries: AnalyzeSignalSeriesPreview; -} - -interface AnalyzeSignalResultBase { - readonly scope: 'vault_fenced'; - readonly vaultCutoffTs: number; - readonly vaultCutoffDate: string; - readonly signal: AnalyzeSignalInput['signal']; - readonly horizonSessions: number; - readonly adjustment: 'raw' | 'split' | 'total'; - readonly universeMarket: UniverseMarket; - readonly horizonBucket: HorizonBucket; - readonly fromMs: number; - readonly toMs: number; - readonly asOfMs: number; - readonly effectiveFrom: string; - readonly effectiveTo: string; - readonly effectiveAsOf: string; - readonly clampedTo: boolean; - readonly clampedAsOf: boolean; - readonly listingCount: number; - readonly panelDiagnostics: SignalPanelDiagnostics; - readonly analysis: AnalyzeSignalAnalysisSummary; -} - -/** Structured JSON payload serialized into the `analyze_signal` MCP text result. */ -export type AnalyzeSignalResultPayload = - | (AnalyzeSignalResultBase & { - readonly status: 'ok'; - readonly trial: StudyTrialSummary; - readonly deflatedSharpe: ClusterDeflatedSharpeResult; - }) - | (AnalyzeSignalResultBase & { - readonly status: 'insufficient_data'; - readonly reason: AnalyzeSignalInsufficientDataReason; - }); - -const ZERO_PANEL_DIAGNOSTICS: SignalPanelDiagnostics = { - vaultExcludedDates: 0, - droppedNoSignal: 0, - droppedStaleSignal: 0, - droppedMissingForwardBar: 0, - droppedNonPositiveClose: 0, - duplicateBars: 0, -}; - -const SIGNAL_PANEL_ERROR_MESSAGES: Readonly> = { - invalid_input: 'Invalid signal panel input.', - invalid_horizon: 'Invalid forward-return horizon.', - invalid_option: 'Invalid signal panel option.', - invalid_date: 'Invalid signal panel date.', - invalid_bar: 'Market bar data failed panel validation.', - invalid_signal: 'Signal table data failed panel validation.', - duplicate_bar: 'Conflicting duplicate daily bars detected.', -}; - -const SIGNAL_STUDY_ERROR_MESSAGES: Readonly> = { - invalid_request: 'Invalid signal study request.', - empty_panel: 'Signal panel is empty.', - invalid_date: 'Invalid signal study date.', - unsorted_dates: 'Signal panel dates are not strictly ascending.', - duplicate_date: 'Duplicate date detected in signal panel.', - invalid_panel: 'Signal panel failed validation.', - invalid_option: 'Invalid signal study option.', - dsr_read_failed: 'Trial was recorded, but cluster deflated Sharpe evaluation failed.', -}; - -const TRIAL_LEDGER_ERROR_MESSAGES: Readonly>> = { - VAULT_FENCE_VIOLATION: 'Sample window violates the Vault holdout cutoff.', - INVALID_PRINCIPAL: 'Invalid trial ledger principal.', - INVALID_UUID: 'Invalid trial ledger UUID.', - INVALID_SAMPLE_WINDOW: 'Invalid trial ledger sample window.', - INVALID_DATE: 'Invalid trial ledger date.', - SERIES_TOO_SHORT: 'Observation series is too short for trial ledger recording.', - ZERO_VARIANCE_SERIES: 'Observation series has zero variance.', - TRIAL_NOT_FOUND: 'Recorded trial could not be found in trial ledger.', -}; - -function sortAndDedupeListingIds(ids: readonly number[]): number[] { - return [...new Set(ids)].sort((a, b) => a - b); -} - -function projectAnalysisSummary( - analysis: SignalPanelAnalysis, - selectedSeries: SignalLedgerSeries -): AnalyzeSignalAnalysisSummary { - const rawDates = selectedSeries === 'rank_ic' ? analysis.dates : analysis.quantiles.dates; - const rawValues = - selectedSeries === 'rank_ic' ? analysis.rankIcSeries : analysis.quantiles.spreadSeries; - const totalCount = Math.min(rawDates.length, rawValues.length); - const truncated = totalCount > ANALYZE_SIGNAL_MAX_SERIES_POINTS; - const startIdx = truncated ? totalCount - ANALYZE_SIGNAL_MAX_SERIES_POINTS : 0; - const points: AnalyzeSignalSeriesPoint[] = []; - - for (let i = startIdx; i < totalCount; i += 1) { - points.push({ - date: rawDates[i] as string, - value: rawValues[i] as number, - }); - } - - return { - pearsonIc: analysis.pearsonIc, - rankIc: analysis.rankIc, - quantiles: { - quantiles: analysis.quantiles.quantiles, - validDates: analysis.quantiles.validDates, - skippedDates: analysis.quantiles.skippedDates, - bucketMeanReturns: [...analysis.quantiles.bucketMeanReturns], - spreadSummary: analysis.quantiles.spreadSummary, - }, - turnover: { - count: analysis.turnover.count, - meanTopTurnover: analysis.turnover.meanTopTurnover, - meanBottomTurnover: analysis.turnover.meanBottomTurnover, - }, - recency: analysis.recency, - diagnostics: analysis.diagnostics, - ledgerSeries: { - series: selectedSeries, - totalCount, - truncated, - points, - }, - }; -} - -function filterEligibleBars( - bars: readonly BarRecord[], - listingIdSet: ReadonlySet, - fromMs: number, - toMs: number, - asOfMs: number, - vaultCutoffTs: number, - vaultCutoffDate: string -): BarRecord[] { - const eligible: BarRecord[] = []; - for (let i = 0; i < bars.length; i += 1) { - const row = bars[i]; - if (typeof row !== 'object' || row === null) { - eligible.push(row as unknown as BarRecord); - continue; - } - if (typeof row.ts === 'number' && Number.isFinite(row.ts)) { - if ( - row.ts < fromMs || - row.ts > toMs || - row.ts > asOfMs || - row.ts >= vaultCutoffTs || - utcDateOf(row.ts) >= vaultCutoffDate - ) { - continue; - } - } - if (typeof row.knownAt === 'number' && Number.isFinite(row.knownAt)) { - if (row.knownAt > asOfMs || row.knownAt >= vaultCutoffTs) { - continue; - } - } - if (typeof row.listingId === 'number' && !listingIdSet.has(row.listingId)) { - continue; - } - eligible.push(row); - } - return eligible; -} - -function filterEligibleShortsTable( - table: Table, - listingIdSet: ReadonlySet, - fromUtcDate: string, - toUtcDate: string, - asOfMs: number, - vaultCutoffTs: number, - vaultCutoffDate: string -): Table { - if ( - typeof table !== 'object' || - table === null || - !Array.isArray(table.columns) || - !Array.isArray(table.rows) - ) { - return table; - } - - const eligibleRows: TableRow[] = []; - for (let i = 0; i < table.rows.length; i += 1) { - const row = table.rows[i]; - if (typeof row !== 'object' || row === null) { - eligibleRows.push(row as TableRow); - continue; - } - const knownAt = row.known_at; - if (typeof knownAt === 'number' && Number.isFinite(knownAt)) { - if (knownAt > asOfMs || knownAt >= vaultCutoffTs) { - continue; - } - } - const reportDate = row.report_date; - if (typeof reportDate === 'string') { - if (reportDate < fromUtcDate || reportDate > toUtcDate || reportDate >= vaultCutoffDate) { - continue; - } - } - const listingId = row.listing_id; - if (typeof listingId === 'number' && !listingIdSet.has(listingId)) { - continue; - } - eligibleRows.push(row); - } - - return { - columns: table.columns, - rows: eligibleRows, - }; -} - -function deriveMonthlySnapshotDates(bars: readonly BarRecord[]): string[] { - const latestByMonth = new Map(); - for (let i = 0; i < bars.length; i += 1) { - const bar = bars[i]; - if ( - typeof bar !== 'object' || - bar === null || - typeof bar.ts !== 'number' || - !Number.isFinite(bar.ts) - ) { - continue; - } - const sessionDate = utcDateOf(bar.ts); - const monthKey = sessionDate.slice(0, 7); - const prev = latestByMonth.get(monthKey); - if (prev === undefined || sessionDate > prev) { - latestByMonth.set(monthKey, sessionDate); - } - } - return [...latestByMonth.values()].sort(); -} - -function resolveSnapshotAsOf( - snapshotDate: string, - fencedAsOfMs: number, - canonicalAsOf: string -): { readonly asOf: string; readonly asOfMs: number } { - const snapshotDayEndMs = Date.parse(`${snapshotDate}T23:59:59.999Z`); - if (fencedAsOfMs <= snapshotDayEndMs) { - return { - asOf: canonicalAsOf, - asOfMs: fencedAsOfMs, - }; - } - return { - asOf: formatUtcIsoWithMicros(snapshotDayEndMs, 999), - asOfMs: snapshotDayEndMs, - }; -} - -function buildBarTimestampsByListing(bars: readonly BarRecord[]): Map { - const byListing = new Map(); - for (let i = 0; i < bars.length; i += 1) { - const bar = bars[i]; - if ( - typeof bar !== 'object' || - bar === null || - typeof bar.listingId !== 'number' || - !Number.isSafeInteger(bar.listingId) || - typeof bar.ts !== 'number' || - !Number.isFinite(bar.ts) - ) { - continue; - } - let list = byListing.get(bar.listingId); - if (list === undefined) { - list = []; - byListing.set(bar.listingId, list); - } - list.push(bar.ts); - } - for (const [lid, list] of byListing) { - list.sort((a, b) => a - b); - let write = 0; - for (let i = 0; i < list.length; i += 1) { - const ts = list[i] as number; - if (write === 0 || list[write - 1] !== ts) { - list[write] = ts; - write += 1; - } - } - list.length = write; - byListing.set(lid, list); - } - return byListing; -} - -function findLatestBarBefore( - sortedTs: readonly number[] | undefined, - upperExclusiveMs: number, - lowerExclusiveMs: number -): number | null { - if (sortedTs === undefined || sortedTs.length === 0) { - return null; - } - let lo = 0; - let hi = sortedTs.length; - while (lo < hi) { - const mid = (lo + hi) >>> 1; - if ((sortedTs[mid] as number) < upperExclusiveMs) { - lo = mid + 1; - } else { - hi = mid; - } - } - const idx = lo - 1; - if (idx < 0) { - return null; - } - const candidate = sortedTs[idx] as number; - return candidate > lowerExclusiveMs ? candidate : null; -} - -function appendEligibleFundamentalsObservations(params: { - readonly table: Table; - readonly field: FundamentalsPitValueField; - readonly listingIdSet: ReadonlySet; - readonly snapshotAsOfMs: number; - readonly fencedAsOfMs: number; - readonly vaultCutoffTs: number; - readonly seenKeys: Set; - readonly out: SignalObservation[]; -}): Map { - const { - table, - field, - listingIdSet, - snapshotAsOfMs, - fencedAsOfMs, - vaultCutoffTs, - seenKeys, - out, - } = params; - - if ( - typeof table !== 'object' || - table === null || - !Array.isArray(table.columns) || - !Array.isArray(table.rows) - ) { - throw new SignalPanelError( - 'invalid_input', - 'Expected a fundamentals Table object with array columns and rows.' - ); - } - - const latestKnownAtByListing = new Map(); - - for (let i = 0; i < table.rows.length; i += 1) { - const row = table.rows[i]; - if (typeof row !== 'object' || row === null) { - continue; - } - - const listingId = row.listing_id; - if ( - typeof listingId !== 'number' || - !Number.isSafeInteger(listingId) || - !listingIdSet.has(listingId) - ) { - continue; - } - - const knownAt = row.effective_known_at; - if ( - typeof knownAt !== 'number' || - !Number.isFinite(knownAt) || - !Number.isSafeInteger(knownAt) - ) { - continue; - } - if (knownAt > snapshotAsOfMs || knownAt > fencedAsOfMs || knownAt >= vaultCutoffTs) { - continue; - } - - const rawValue = row[field]; - if (typeof rawValue !== 'number' || !Number.isFinite(rawValue)) { - continue; - } - - const normalizedListingId = listingId === 0 ? 0 : listingId; - const normalizedKnownAt = knownAt === 0 ? 0 : knownAt; - const prevLatest = latestKnownAtByListing.get(normalizedListingId); - if (prevLatest === undefined || normalizedKnownAt > prevLatest) { - latestKnownAtByListing.set(normalizedListingId, normalizedKnownAt); - } - - const normalizedValue = rawValue === 0 ? 0 : rawValue; - const dedupeKey = `${normalizedListingId}:${normalizedKnownAt}`; - if (seenKeys.has(dedupeKey)) { - continue; - } - seenKeys.add(dedupeKey); - out.push({ - listingId: normalizedListingId, - knownAt: normalizedKnownAt, - value: normalizedValue, - }); - } - - return latestKnownAtByListing; -} - -function buildCanonicalStudyExpression(params: { - readonly input: AnalyzeSignalInput; - readonly listingIds: readonly number[]; - readonly universeSnapshotDate: string | null; - readonly effectiveFrom: string; - readonly effectiveTo: string; - readonly effectiveAsOf: string; -}): SignalStudyExpression { - const { input, listingIds, universeSnapshotDate, effectiveFrom, effectiveTo, effectiveAsOf } = - params; - return { - expression: `mcp:analyze_signal:v1:${input.signal.source}:${input.signal.field}`, - params: { - version: 1, - signalSource: input.signal.source, - signalField: input.signal.field, - ...(input.signal.source === 'fundamentals' - ? { allowEstimatedLag: input.signal.allowEstimatedLag } - : {}), - horizonSessions: input.horizonSessions, - maxSignalAgeSessions: input.maxSignalAgeSessions ?? null, - adjustment: input.adjustment, - ledgerSeries: input.ledgerSeries, - effectiveFrom, - effectiveTo, - effectiveAsOf, - }, - universe: - input.universe !== undefined - ? { - kind: 'universe', - ref: input.universe, - snapshotDate: universeSnapshotDate, - listingIds, - } - : { - kind: 'listingIds', - listingIds, - }, - horizon: `${input.horizonSessions}d`, - }; -} - -function formatMappedAnalyzeSignalError(err: unknown): McpToolCallResult { - const storeMapped = formatMappedStoreError(err); - if (storeMapped !== null) { - return storeMapped; - } - - if (err instanceof SignalPanelError) { - const detail = Object.prototype.hasOwnProperty.call(SIGNAL_PANEL_ERROR_MESSAGES, err.code) - ? SIGNAL_PANEL_ERROR_MESSAGES[err.code] - : 'Signal panel construction failed.'; - return { - content: [{ type: 'text', text: `SignalPanelError: ${detail}` }], - isError: true, - }; - } - - if (err instanceof SignalStudyError) { - const detail = Object.prototype.hasOwnProperty.call(SIGNAL_STUDY_ERROR_MESSAGES, err.code) - ? SIGNAL_STUDY_ERROR_MESSAGES[err.code] - : 'Signal study execution failed.'; - return { - content: [{ type: 'text', text: `SignalStudyError: ${detail}` }], - isError: true, - }; - } - - if (err instanceof TrialLedgerError) { - const detail = - Object.prototype.hasOwnProperty.call(TRIAL_LEDGER_ERROR_MESSAGES, err.code) && - TRIAL_LEDGER_ERROR_MESSAGES[err.code] !== undefined - ? TRIAL_LEDGER_ERROR_MESSAGES[err.code] - : 'Trial ledger operation failed.'; - return { - content: [{ type: 'text', text: `TrialLedgerError: ${detail}` }], - isError: true, - }; - } - - return { - content: [{ type: 'text', text: 'Error: Tool execution failed.' }], - isError: true, - }; -} - -function validateFactoryOptions(options: AnalyzeSignalToolOptions): number { - if ( - typeof options.store !== 'object' || - options.store === null || - typeof options.store.bars !== 'function' || - typeof options.store.shortsAsOf !== 'function' || - typeof options.store.fundamentalsAsOf !== 'function' || - typeof options.store.universe !== 'function' - ) { - throw new MarketDataStoreValidationError( - 'Invalid `store`: expected a MarketDataStore implementing `bars`, `shortsAsOf`, `fundamentalsAsOf`, and `universe`.', - 'store' - ); - } - - if ( - typeof options.ledger !== 'object' || - options.ledger === null || - typeof options.ledger.query !== 'function' - ) { - throw new SignalStudyError( - 'invalid_request', - 'Invalid `ledger`: expected a TrialLedgerExecutor implementing `query`.' - ); - } - - if ( - typeof options.principalId !== 'string' || - (options.principalId !== 'operator' && !AGENT_PRINCIPAL_RE.test(options.principalId)) - ) { - throw new TrialLedgerError( - 'INVALID_PRINCIPAL', - `Invalid \`principalId\`: "${String(options.principalId)}".` - ); - } - - return validateVaultCutoffTs(options.vaultContext?.vaultCutoffTs); -} - -/** - * Creates the Vault-fenced `analyze_signal` MCP tool backed by an injected - * {@link MarketDataStore} and {@link TrialLedgerExecutor}. - * - * Enforces `scope: 'vault_fenced'`, fences bounds before any store call, - * resolves named universes strictly prior to the study start date, filters - * bars and shorts defensively against the effective window and Vault cutoff, - * builds the forward-return panel, runs `analyzeSignal` with the injected - * research principal, and returns a bounded summary payload. - */ -export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpToolEntry { - const vaultCutoffTs = validateFactoryOptions(options); - const { store, ledger, principalId } = options; - - return defineMcpTool({ - name: 'analyze_signal', - description: - 'Run a Vault-fenced cross-sectional short-interest or point-in-time fundamentals signal study and record eligible trials to trial_ledger.', - inputSchema: analyzeSignalInputSchema, - jsonSchema: ANALYZE_SIGNAL_JSON_SCHEMA, - async handler(input: AnalyzeSignalInput): Promise { - try { - const fenced = fenceVaultQueryBounds( - { - from: input.from, - to: input.to, - asOf: input.asOf, - }, - vaultCutoffTs - ); - - let listingIds: number[]; - let universeSnapshotDate: string | null = null; - - if (input.universe !== undefined) { - universeSnapshotDate = resolvePreStartUniverseDate( - fenced.fromMs, - fenced.asOfMs, - fenced.asOfSubMs - ); - const resolved = await store.universe({ - ref: input.universe, - date: universeSnapshotDate, - }); - listingIds = sortAndDedupeListingIds(resolved); - } else { - listingIds = sortAndDedupeListingIds(input.listingIds ?? []); - } - - const signalEcho: AnalyzeSignalInput['signal'] = - input.signal.source === 'shorts' - ? { - source: 'shorts', - field: input.signal.field, - } - : { - source: 'fundamentals', - field: input.signal.field, - allowEstimatedLag: input.signal.allowEstimatedLag, - }; - - const basePayloadFields = { - scope: 'vault_fenced' as const, - vaultCutoffTs, - vaultCutoffDate: fenced.vaultCutoffDate, - signal: signalEcho, - horizonSessions: input.horizonSessions, - adjustment: input.adjustment, - universeMarket: input.universeMarket, - horizonBucket: input.horizonBucket, - fromMs: fenced.fromMs, - toMs: fenced.toMs, - asOfMs: fenced.asOfMs, - effectiveFrom: fenced.canonicalFrom, - effectiveTo: fenced.canonicalTo, - effectiveAsOf: fenced.canonicalAsOf, - clampedTo: fenced.clampedTo, - clampedAsOf: fenced.clampedAsOf, - listingCount: listingIds.length, - }; - - if (listingIds.length === 0) { - const emptyAnalysis = analyzeSignalPanel([], { - vaultCutoffDate: fenced.vaultCutoffDate, - }); - const payload: AnalyzeSignalResultPayload = { - ...basePayloadFields, - status: 'insufficient_data', - reason: 'too_few_observations', - panelDiagnostics: ZERO_PANEL_DIAGNOSTICS, - analysis: projectAnalysisSummary(emptyAnalysis, input.ledgerSeries), - }; - return { - content: [{ type: 'text', text: JSON.stringify(payload) }], - }; - } - - const rawBars = await collectBars( - store.bars({ - listingIds, - timeframe: '1d', - from: fenced.canonicalFrom, - to: fenced.canonicalTo, - adjustment: input.adjustment, - asOf: fenced.canonicalAsOf, - scope: 'vault_fenced', - }) - ); - - const listingIdSet = new Set(listingIds); - const eligibleBars = filterEligibleBars( - rawBars, - listingIdSet, - fenced.fromMs, - fenced.toMs, - fenced.asOfMs, - vaultCutoffTs, - fenced.vaultCutoffDate - ); - - let signals: SignalObservation[]; - if (input.signal.source === 'shorts') { - const rawShortsTable = await store.shortsAsOf({ - listingIds, - from: fenced.canonicalFrom, - to: fenced.canonicalTo, - asOf: fenced.canonicalAsOf, - }); - const eligibleShortsTable = filterEligibleShortsTable( - rawShortsTable, - listingIdSet, - utcDateOf(fenced.fromMs), - utcDateOf(fenced.toMs), - fenced.asOfMs, - vaultCutoffTs, - fenced.vaultCutoffDate - ); - signals = shortsTableToSignalRows(eligibleShortsTable, input.signal.field); - } else { - const { field: fundamentalsField, allowEstimatedLag } = input.signal; - const snapshotDates = deriveMonthlySnapshotDates(eligibleBars); - if (snapshotDates.length > ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS) { - return { - content: [ - { - type: 'text', - text: `Invalid arguments for tool "analyze_signal": Fundamentals study exceeds maximum of ${ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS} month-end snapshots.`, - }, - ], - isError: true, - }; - } - - signals = []; - const seenKeys = new Set(); - const barTimestampsByListing = buildBarTimestampsByListing(eligibleBars); - let windowFloorMs = Number.NEGATIVE_INFINITY; - - for (const snapshotDate of snapshotDates) { - const snapshot = resolveSnapshotAsOf( - snapshotDate, - fenced.asOfMs, - fenced.canonicalAsOf - ); - const rawTable = await store.fundamentalsAsOf({ - listingIds, - fields: [fundamentalsField], - asOf: snapshot.asOf, - allowEstimatedLag, - }); - const latestKnownByListing = appendEligibleFundamentalsObservations({ - table: rawTable, - field: fundamentalsField, - listingIdSet, - snapshotAsOfMs: snapshot.asOfMs, - fencedAsOfMs: fenced.asOfMs, - vaultCutoffTs, - seenKeys, - out: signals, - }); - - // Backfill vintages superseded earlier within this month (or prior - // to the first eligible bar for the initial month) by stepping to - // the latest uncovered eligible bar strictly before each returned - // vintage. Under either lag setting, a requested listing with no - // valid observation (omitted by DuckDB or carrying a null/non-finite - // field) is treated as an unresolved interval so earlier eligible - // closes within the month are probed. Listings sharing a target bar - // timestamp are batched. - const pendingByBarTs = new Map(); - const enqueueBackfill = ( - queriedListingIds: readonly number[], - knownByListing: ReadonlyMap, - upperBoundExclusiveMs: number - ): void => { - for (const lid of queriedListingIds) { - const knownAt = knownByListing.get(lid); - const upperExclusive = - knownAt !== undefined - ? Math.min(knownAt, upperBoundExclusiveMs) - : upperBoundExclusiveMs; - const prevBarTs = findLatestBarBefore( - barTimestampsByListing.get(lid), - upperExclusive, - windowFloorMs - ); - if (prevBarTs !== null) { - let bucket = pendingByBarTs.get(prevBarTs); - if (bucket === undefined) { - bucket = []; - pendingByBarTs.set(prevBarTs, bucket); - } - bucket.push(lid); - } - } - }; - - enqueueBackfill(listingIds, latestKnownByListing, snapshot.asOfMs); - - while (pendingByBarTs.size > 0) { - // Pop the highest bar timestamp first so earlier buckets merge - // newly discovered listings landing on the same session. - let nextBarTs = Number.NEGATIVE_INFINITY; - for (const ts of pendingByBarTs.keys()) { - if (ts > nextBarTs) { - nextBarTs = ts; - } - } - const batchListingIds = sortAndDedupeListingIds(pendingByBarTs.get(nextBarTs) ?? []); - pendingByBarTs.delete(nextBarTs); - if (batchListingIds.length === 0) { - continue; - } - - const batchAsOfMs = Math.min(nextBarTs, fenced.asOfMs); - const batchAsOf = - batchAsOfMs === fenced.asOfMs - ? fenced.canonicalAsOf - : formatUtcIsoWithMicros(batchAsOfMs, 0); - const batchListingIdSet = new Set(batchListingIds); - - const backfillTable = await store.fundamentalsAsOf({ - listingIds: batchListingIds, - fields: [fundamentalsField], - asOf: batchAsOf, - allowEstimatedLag, - }); - const backfillKnownByListing = appendEligibleFundamentalsObservations({ - table: backfillTable, - field: fundamentalsField, - listingIdSet: batchListingIdSet, - snapshotAsOfMs: batchAsOfMs, - fencedAsOfMs: fenced.asOfMs, - vaultCutoffTs, - seenKeys, - out: signals, - }); - - enqueueBackfill(batchListingIds, backfillKnownByListing, nextBarTs); - } - - windowFloorMs = snapshot.asOfMs; - } - } - - const built = buildForwardReturnPanel({ - bars: eligibleBars, - signals, - horizonSessions: input.horizonSessions, - vaultCutoffDate: fenced.vaultCutoffDate, - ...(input.maxSignalAgeSessions !== undefined - ? { maxSignalAgeSessions: input.maxSignalAgeSessions } - : {}), - }); - - if (built.panel.length === 0) { - const emptyAnalysis = analyzeSignalPanel([], { - vaultCutoffDate: fenced.vaultCutoffDate, - }); - const payload: AnalyzeSignalResultPayload = { - ...basePayloadFields, - status: 'insufficient_data', - reason: 'too_few_observations', - panelDiagnostics: built.diagnostics, - analysis: projectAnalysisSummary(emptyAnalysis, input.ledgerSeries), - }; - return { - content: [{ type: 'text', text: JSON.stringify(payload) }], - }; - } - - const expression = buildCanonicalStudyExpression({ - input, - listingIds, - universeSnapshotDate, - effectiveFrom: fenced.canonicalFrom, - effectiveTo: fenced.canonicalTo, - effectiveAsOf: fenced.canonicalAsOf, - }); - - const studyResult = await analyzeSignal(ledger, { - principalId, - ...(input.campaignId !== undefined ? { campaignId: input.campaignId } : {}), - ...(input.hypothesisId !== undefined ? { hypothesisId: input.hypothesisId } : {}), - universeMarket: input.universeMarket, - horizonBucket: input.horizonBucket, - expression, - panel: built.panel, - vaultCutoffDate: fenced.vaultCutoffDate, - ledgerSeries: input.ledgerSeries, - }); - - const analysisSummary = projectAnalysisSummary(studyResult.analysis, input.ledgerSeries); - - const payload: AnalyzeSignalResultPayload = - studyResult.status === 'ok' - ? { - ...basePayloadFields, - status: 'ok', - panelDiagnostics: built.diagnostics, - analysis: analysisSummary, - trial: studyResult.trial, - deflatedSharpe: studyResult.deflatedSharpe, - } - : { - ...basePayloadFields, - status: 'insufficient_data', - reason: studyResult.reason, - panelDiagnostics: built.diagnostics, - analysis: analysisSummary, - }; - - return { - content: [{ type: 'text', text: JSON.stringify(payload) }], - }; - } catch (err: unknown) { - return formatMappedAnalyzeSignalError(err); - } - }, - }); -} diff --git a/libs/research/src/mcp/tools/event-study.ts b/libs/research/src/mcp/tools/event-study.ts deleted file mode 100644 index 68e5266e..00000000 --- a/libs/research/src/mcp/tools/event-study.ts +++ /dev/null @@ -1,1032 +0,0 @@ -import type { - EventStudyDiagnostics, - EventStudyRecencyResult, - EventStudyResult, - NeweyWestResult, -} from '@stock-bot/calculations'; -import { z } from 'zod'; -import { - type EventPanelDiagnostics, - EventPanelError, - type EventPanelErrorCode, - type EventStudyBenchmarkMode, - type EventStudyExchangeCalendars, - buildEventStudyInput, - eventsTableToEventRows, -} from '../../event-panel'; -import { - type BarRecord, - type EventKind, - type MarketDataStore, - MarketDataStoreValidationError, - type Table, - type TableRow, - type VaultFenceContext, -} from '../../market-data-store'; -import { EVENT_KINDS } from '../../market-data-store-duckdb'; -import { collectBars } from '../../signal-panel'; -import { - type RunEventStudyInsufficientDataReason, - SignalStudyError, - type SignalStudyErrorCode, - type SignalStudyExpression, - type StudyTrialSummary, - runEventStudy, -} from '../../signal-study'; -import { - type ClusterDeflatedSharpeResult, - HORIZON_BUCKETS, - type HorizonBucket, - TrialLedgerError, - type TrialLedgerErrorCode, - type TrialLedgerExecutor, - UNIVERSE_MARKETS, - type UniverseMarket, -} from '../../trial-ledger'; -import type { McpToolCallResult } from '../protocol'; -import { type McpToolEntry, defineMcpTool } from '../server'; -import { - EXCLUSIVE_LISTING_SELECTOR_MESSAGE, - MAX_ECMASCRIPT_EPOCH_MS, - MCP_MAX_LISTING_IDS, - MS_PER_DAY, - createListingIdsFieldSchema, - createUniverseFieldSchema, - fenceVaultQueryBounds, - formatMappedStoreError, - hasExclusiveListingSelector, - isValidUtcBoundString, - resolvePreStartUniverseDate, - utcDateOf, - validateVaultCutoffTs, -} from './vault-fenced-input'; - -/** Hard maximum number of explicit `listingIds` accepted by `event_study`. */ -export const EVENT_STUDY_MAX_LISTING_IDS = MCP_MAX_LISTING_IDS; - -/** Hard maximum pre-event window length in trading sessions. */ -export const EVENT_STUDY_MAX_PRE_DAYS = 60; - -/** Hard maximum post-event window length in trading sessions. */ -export const EVENT_STUDY_MAX_POST_DAYS = 60; - -/** Hard maximum number of event subtype entries accepted in `event.subtypes`. */ -export const EVENT_STUDY_MAX_SUBTYPES = 100; - -/** Hard maximum character length of each event subtype string in `event.subtypes`. */ -export const EVENT_STUDY_MAX_SUBTYPE_LENGTH = 128; - -const LEDGER_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; -const AGENT_PRINCIPAL_RE = - /^agent:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; -const UTC_BOUND_ERROR_MESSAGE = - 'Expected YYYY-MM-DD calendar date or UTC ISO-8601 timestamp with timezone offset.'; -const EVENT_KIND_SET: ReadonlySet = new Set(EVENT_KINDS); - -function canonicalDailyHorizonBucket(postDays: number): HorizonBucket { - return postDays <= 10 ? 'swing_1_10d' : 'position_10d_plus'; -} - -function isValidEpochMs(value: unknown): value is number { - return ( - typeof value === 'number' && - Number.isFinite(value) && - Number.isSafeInteger(value) && - Math.abs(value) < MAX_ECMASCRIPT_EPOCH_MS - ); -} - -const utcBoundStringSchema = z.string().min(1).refine(isValidUtcBoundString, UTC_BOUND_ERROR_MESSAGE); - -const eventFilterSpecSchema = z - .object({ - kinds: z - .array(z.enum(EVENT_KINDS)) - .min(1) - .describe( - 'Non-empty list of event kinds to include (filing, earnings, ceo_post, or corporate_action).' - ), - subtypes: z - .array(z.string().min(1).max(EVENT_STUDY_MAX_SUBTYPE_LENGTH)) - .min(1) - .max(EVENT_STUDY_MAX_SUBTYPES) - .optional() - .describe( - `Optional non-empty exact-match allow-list of event subtypes (max ${EVENT_STUDY_MAX_SUBTYPES} entries, ${EVENT_STUDY_MAX_SUBTYPE_LENGTH} chars each).` - ), - }) - .strict() - .describe('Event kind and optional subtype filter specification.'); - -/** - * Strict Zod input schema for the `event_study` MCP tool. - * - * Intentionally omits `scope`, `vault_evaluation_only`, `principalId`, and - * `vaultCutoffDate`; `.strict()` rejects any caller attempt to supply them - * or any other unknown top-level or nested key. - */ -export const eventStudyInputSchema = z - .object({ - listingIds: createListingIdsFieldSchema( - 'Explicit INT32 listing IDs to study (mutually exclusive with universe).' - ), - universe: createUniverseFieldSchema( - 'Survivorship-free universe identifier such as US_EQ, CA_EQ, or US_CA_EQ (mutually exclusive with listingIds).' - ), - from: utcBoundStringSchema.describe( - 'Inclusive study start date (YYYY-MM-DD) or UTC ISO-8601 timestamp.' - ), - to: utcBoundStringSchema.describe( - 'Inclusive study end date (YYYY-MM-DD) or UTC ISO-8601 timestamp; clamped below Vault cutoff.' - ), - asOf: utcBoundStringSchema - .optional() - .describe( - 'Optional point-in-time knowledge cutoff (YYYY-MM-DD or UTC ISO-8601); clamped below Vault cutoff.' - ), - event: eventFilterSpecSchema, - preDays: z - .number() - .int() - .min(0) - .max(EVENT_STUDY_MAX_PRE_DAYS) - .describe( - `Pre-event window in trading sessions (0–${EVENT_STUDY_MAX_PRE_DAYS}).` - ), - postDays: z - .number() - .int() - .min(0) - .max(EVENT_STUDY_MAX_POST_DAYS) - .describe( - `Post-event window in trading sessions (0–${EVENT_STUDY_MAX_POST_DAYS}).` - ), - benchmark: z - .enum(['equal_weight', 'none']) - .default('equal_weight') - .describe( - 'Benchmark return mode: equal_weight (cross-sectional mean of eligible listing returns) or none (default equal_weight).' - ), - adjustment: z - .enum(['raw', 'split', 'total']) - .default('raw') - .describe('Bar price adjustment mode (default raw).'), - universeMarket: z - .enum(UNIVERSE_MARKETS) - .describe('Relatedness-cluster market bucket recorded in trial_ledger.'), - horizonBucket: z - .enum(HORIZON_BUCKETS) - .describe('Relatedness-cluster horizon bucket recorded in trial_ledger.'), - campaignId: z - .string() - .regex(LEDGER_UUID_RE, 'Expected a UUID string.') - .optional() - .describe('Optional research campaign UUID recorded in trial_ledger.'), - hypothesisId: z - .string() - .regex(LEDGER_UUID_RE, 'Expected a UUID string.') - .optional() - .describe('Optional research hypothesis UUID recorded in trial_ledger.'), - }) - .strict() - .superRefine((data, ctx) => { - if (!hasExclusiveListingSelector(data)) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: EXCLUSIVE_LISTING_SELECTOR_MESSAGE, - }); - } - - const expectedBucket = canonicalDailyHorizonBucket(data.postDays); - if (data.horizonBucket !== expectedBucket) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - path: ['horizonBucket'], - message: `Daily postDays=${data.postDays} requires horizonBucket "${expectedBucket}".`, - }); - } - - if (data.universe !== undefined && data.universeMarket !== data.universe) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - path: ['universeMarket'], - message: `Named universe "${data.universe}" requires universeMarket "${data.universe}".`, - }); - } - }); - -export type EventStudyToolInput = z.infer; - -/** Query passed to the server-injected exchange-calendar resolver. */ -export interface EventStudyExchangeCalendarQuery { - readonly listingIds: readonly number[]; - readonly fromDate: string; - readonly toDate: string; -} - -/** Server-injected exchange-calendar resolver returning actual session close calendars. */ -export type EventStudyExchangeCalendarResolver = ( - query: EventStudyExchangeCalendarQuery -) => Promise | EventStudyExchangeCalendars; - -/** Server-side injected configuration for {@link createEventStudyTool}. */ -export interface EventStudyToolOptions { - readonly store: MarketDataStore; - readonly ledger: TrialLedgerExecutor; - readonly vaultContext: Pick; - readonly principalId: string; - readonly resolveExchangeCalendars: EventStudyExchangeCalendarResolver; -} - -/** Projected CAR/AAR summary for one relative offset in `[-preDays, +postDays]`. */ -export interface EventStudyOffsetSummary { - readonly offset: number; - readonly n: number; - readonly aar: number; - readonly caar: number; - readonly caarFromZero: number | null; -} - -/** Bounded date-clustered CAR summary without raw per-date typed arrays. */ -export interface EventStudyClusteredSummary { - readonly nDates: number; - readonly carMean: number; - readonly neweyWest: NeweyWestResult; -} - -/** Bounded summary projection of {@link EventStudyResult}. */ -export interface EventStudySummary { - readonly preDays: number; - readonly postDays: number; - readonly hasBenchmark: boolean; - readonly offsets: readonly EventStudyOffsetSummary[]; - readonly clustered: EventStudyClusteredSummary | null; - readonly recency: EventStudyRecencyResult | null; - readonly diagnostics: EventStudyDiagnostics; -} - -interface EventStudyResultBase { - readonly scope: 'vault_fenced'; - readonly vaultCutoffTs: number; - readonly vaultCutoffDate: string; - readonly event: { - readonly kinds: readonly EventKind[]; - readonly subtypes: readonly string[] | null; - }; - readonly preDays: number; - readonly postDays: number; - readonly benchmark: EventStudyBenchmarkMode; - readonly adjustment: 'raw' | 'split' | 'total'; - readonly universeMarket: UniverseMarket; - readonly horizonBucket: HorizonBucket; - readonly fromMs: number; - readonly toMs: number; - readonly asOfMs: number; - readonly effectiveFrom: string; - readonly effectiveTo: string; - readonly effectiveAsOf: string; - readonly clampedTo: boolean; - readonly clampedAsOf: boolean; - readonly listingCount: number; - readonly eventCount: number; - readonly vaultExcludedEvents: number; - readonly panelDiagnostics: EventPanelDiagnostics; - readonly study: EventStudySummary; -} - -/** Structured JSON payload serialized into the `event_study` MCP text result. */ -export type EventStudyResultPayload = - | (EventStudyResultBase & { - readonly status: 'ok'; - readonly trial: StudyTrialSummary; - readonly deflatedSharpe: ClusterDeflatedSharpeResult; - }) - | (EventStudyResultBase & { - readonly status: 'insufficient_data'; - readonly reason: RunEventStudyInsufficientDataReason; - }); - -class ExchangeCalendarResolverError extends Error { - override readonly name = 'ExchangeCalendarResolverError'; - override readonly cause?: unknown; - - constructor(cause: unknown) { - super('Exchange calendar resolution failed.', { cause }); - this.cause = cause; - Object.setPrototypeOf(this, new.target.prototype); - } -} - -const ZERO_EVENT_PANEL_DIAGNOSTICS: EventPanelDiagnostics = { - vaultExcludedDates: 0, - vaultExcludedEvents: 0, - droppedUnknownListing: 0, - droppedAfterLastSession: 0, - droppedMissingCalendarSession: 0, - duplicateEvents: 0, - duplicateBars: 0, - nonPositiveCloseReturns: 0, -}; - -const ZERO_EVENT_STUDY_DIAGNOSTICS: EventStudyDiagnostics = { - eventsIn: 0, - eventsUsed: 0, - droppedUnknownEntity: 0, - droppedWindowOutOfRange: 0, - droppedMissingReturns: 0, - duplicateEventsCollapsed: 0, -}; - -const EVENT_PANEL_ERROR_MESSAGES: Readonly> = { - invalid_input: 'Invalid event panel input.', - invalid_date: 'Invalid event panel date.', - invalid_bar: 'Market bar data failed event panel validation.', - invalid_event: 'Event table data failed event panel validation.', - invalid_option: 'Invalid event panel option.', - duplicate_bar: 'Conflicting duplicate daily bars detected.', -}; - -const SIGNAL_STUDY_ERROR_MESSAGES: Readonly> = { - invalid_request: 'Invalid event study request.', - empty_panel: 'Event study session grid is empty.', - invalid_date: 'Invalid event study date.', - unsorted_dates: 'Event study session dates are not strictly ascending.', - duplicate_date: 'Duplicate date detected in event study session grid.', - invalid_panel: 'Event study panel failed validation.', - invalid_option: 'Invalid event study option.', - dsr_read_failed: 'Trial was recorded, but cluster deflated Sharpe evaluation failed.', -}; - -const TRIAL_LEDGER_ERROR_MESSAGES: Readonly>> = { - VAULT_FENCE_VIOLATION: 'Sample window violates the Vault holdout cutoff.', - INVALID_PRINCIPAL: 'Invalid trial ledger principal.', - INVALID_UUID: 'Invalid trial ledger UUID.', - INVALID_SAMPLE_WINDOW: 'Invalid trial ledger sample window.', - INVALID_DATE: 'Invalid trial ledger date.', - SERIES_TOO_SHORT: 'Observation series is too short for trial ledger recording.', - ZERO_VARIANCE_SERIES: 'Observation series has zero variance.', - TRIAL_NOT_FOUND: 'Recorded trial could not be found in trial ledger.', -}; - -function sortAndDedupeListingIds(ids: readonly number[]): number[] { - return [...new Set(ids)].sort((a, b) => a - b); -} - -function sortAndDedupeStrings(items: readonly T[]): T[] { - return [...new Set(items)].sort() as T[]; -} - -function makeEmptyStudySummary( - preDays: number, - postDays: number, - hasBenchmark: boolean -): EventStudySummary { - return { - preDays, - postDays, - hasBenchmark, - offsets: [], - clustered: null, - recency: null, - diagnostics: ZERO_EVENT_STUDY_DIAGNOSTICS, - }; -} - -function projectStudySummary(study: EventStudyResult): EventStudySummary { - if (study.status === 'insufficient_data') { - return { - preDays: study.preDays, - postDays: study.postDays, - hasBenchmark: study.hasBenchmark, - offsets: [], - clustered: null, - recency: null, - diagnostics: study.diagnostics, - }; - } - - return { - preDays: study.preDays, - postDays: study.postDays, - hasBenchmark: study.hasBenchmark, - offsets: study.offsets.map(o => ({ - offset: o.offset, - n: o.n, - aar: o.aar, - caar: o.caar, - caarFromZero: o.caarFromZero, - })), - clustered: { - nDates: study.clustered.nDates, - carMean: study.clustered.carMean, - neweyWest: study.clustered.neweyWest, - }, - recency: study.recency, - diagnostics: study.diagnostics, - }; -} - -function filterEligibleBars( - bars: readonly BarRecord[], - listingIdSet: ReadonlySet, - fromMs: number, - fromSubMs: number, - toMs: number, - asOfMs: number, - vaultCutoffTs: number, - vaultCutoffDate: string -): { readonly bars: BarRecord[]; readonly prePanelVaultExcludedDates: number } { - const eligible: BarRecord[] = []; - const vaultExcludedDates = new Set(); - const minTsMs = fromSubMs > 0 ? fromMs + 1 : fromMs; - - for (let i = 0; i < bars.length; i += 1) { - const row = bars[i]; - if (typeof row !== 'object' || row === null) { - eligible.push(row as unknown as BarRecord); - continue; - } - if (typeof row.listingId === 'number' && !listingIdSet.has(row.listingId)) { - continue; - } - - const tsValid = isValidEpochMs(row.ts); - const tsDate = tsValid ? utcDateOf(row.ts) : null; - const tsInVault = tsValid && (row.ts >= vaultCutoffTs || (tsDate as string) >= vaultCutoffDate); - if (tsInVault) { - vaultExcludedDates.add(tsDate as string); - continue; - } - - if (tsValid) { - if (row.ts < minTsMs || row.ts > toMs || row.ts > asOfMs) { - continue; - } - } - - if (isValidEpochMs(row.knownAt)) { - if ( - row.knownAt > asOfMs || - row.knownAt >= vaultCutoffTs || - utcDateOf(row.knownAt) >= vaultCutoffDate - ) { - continue; - } - } - - eligible.push(row); - } - - return { - bars: eligible, - prePanelVaultExcludedDates: vaultExcludedDates.size, - }; -} - -function filterEligibleEventsTable(params: { - readonly table: Table; - readonly listingIdSet: ReadonlySet; - readonly kindSet: ReadonlySet; - readonly subtypeSet: ReadonlySet | null; - readonly fromMs: number; - readonly fromSubMs: number; - readonly toMs: number; - readonly asOfMs: number; - readonly vaultCutoffTs: number; - readonly vaultCutoffDate: string; -}): { readonly table: Table; readonly prePanelVaultExcludedEvents: number } { - const { - table, - listingIdSet, - kindSet, - subtypeSet, - fromMs, - fromSubMs, - toMs, - asOfMs, - vaultCutoffTs, - vaultCutoffDate, - } = params; - - if ( - typeof table !== 'object' || - table === null || - !Array.isArray(table.columns) || - !Array.isArray(table.rows) - ) { - return { table, prePanelVaultExcludedEvents: 0 }; - } - - const eligibleRows: TableRow[] = []; - let prePanelVaultExcludedEvents = 0; - // TableRow timestamps carry integer epoch-ms precision. When the effective start - // has non-zero microseconds (fromSubMs > 0), any row stamped at `fromMs` is either - // strictly earlier (e.g. `.123Z < .123456Z`) or ambiguous at the boundary ms, so - // require `ts >= fromMs + 1` conservatively. - const minTsMs = fromSubMs > 0 ? fromMs + 1 : fromMs; - - for (let i = 0; i < table.rows.length; i += 1) { - const row = table.rows[i]; - if (typeof row !== 'object' || row === null || Array.isArray(row)) { - eligibleRows.push(row as TableRow); - continue; - } - - const listingId = row.listing_id; - if (typeof listingId === 'number' && !listingIdSet.has(listingId)) { - continue; - } - - // Drop valid but unrequested kinds/subtypes without counting them as Vault exclusions. - // Malformed kind/subtype values fall through so eventsTableToEventRows rejects them. - const kind = row.kind; - if (typeof kind === 'string' && EVENT_KIND_SET.has(kind) && !kindSet.has(kind)) { - continue; - } - if (subtypeSet !== null) { - const subtype = row.subtype; - if (subtype === null || (typeof subtype === 'string' && !subtypeSet.has(subtype))) { - continue; - } - } - - const knownAt = row.known_at; - const knownAtInVault = - isValidEpochMs(knownAt) && - (knownAt >= vaultCutoffTs || utcDateOf(knownAt) >= vaultCutoffDate); - - const ts = row.ts; - const tsInVault = - isValidEpochMs(ts) && - (ts >= vaultCutoffTs || utcDateOf(ts) >= vaultCutoffDate); - - if (knownAtInVault || tsInVault) { - prePanelVaultExcludedEvents += 1; - continue; - } - - if (isValidEpochMs(knownAt) && knownAt > asOfMs) { - continue; - } - - if (isValidEpochMs(ts)) { - if (ts < minTsMs || ts > toMs) { - continue; - } - } else { - throw new EventPanelError( - 'invalid_event', - `Invalid ts in events table row[${i}]: ${String(ts)}.` - ); - } - - eligibleRows.push(row); - } - - return { - table: { - columns: table.columns, - rows: eligibleRows, - }, - prePanelVaultExcludedEvents, - }; -} - -function buildCanonicalEventStudyExpression(params: { - readonly input: EventStudyToolInput; - readonly canonicalKinds: readonly EventKind[]; - readonly canonicalSubtypes: readonly string[] | undefined; - readonly listingIds: readonly number[]; - readonly universeSnapshotDate: string | null; - readonly effectiveFrom: string; - readonly effectiveTo: string; - readonly effectiveAsOf: string; -}): SignalStudyExpression { - const { - input, - canonicalKinds, - canonicalSubtypes, - listingIds, - universeSnapshotDate, - effectiveFrom, - effectiveTo, - effectiveAsOf, - } = params; - - return { - expression: `mcp:event_study:v1:${canonicalKinds.join(',')}`, - params: { - version: 1, - kinds: canonicalKinds, - subtypes: canonicalSubtypes ?? null, - preDays: input.preDays, - postDays: input.postDays, - benchmark: input.benchmark, - adjustment: input.adjustment, - effectiveFrom, - effectiveTo, - effectiveAsOf, - }, - universe: - input.universe !== undefined - ? { - kind: 'universe', - ref: input.universe, - snapshotDate: universeSnapshotDate, - listingIds, - } - : { - kind: 'listingIds', - listingIds, - }, - horizon: `${input.postDays}d`, - }; -} - -function formatMappedEventStudyError(err: unknown): McpToolCallResult { - const storeMapped = formatMappedStoreError(err); - if (storeMapped !== null) { - return storeMapped; - } - - if (err instanceof ExchangeCalendarResolverError) { - return { - content: [{ type: 'text', text: 'Error: Exchange calendar resolution failed.' }], - isError: true, - }; - } - - if (err instanceof EventPanelError) { - const detail = Object.prototype.hasOwnProperty.call(EVENT_PANEL_ERROR_MESSAGES, err.code) - ? EVENT_PANEL_ERROR_MESSAGES[err.code] - : 'Event panel construction failed.'; - return { - content: [{ type: 'text', text: `EventPanelError: ${detail}` }], - isError: true, - }; - } - - if (err instanceof SignalStudyError) { - const detail = Object.prototype.hasOwnProperty.call(SIGNAL_STUDY_ERROR_MESSAGES, err.code) - ? SIGNAL_STUDY_ERROR_MESSAGES[err.code] - : 'Event study execution failed.'; - return { - content: [{ type: 'text', text: `SignalStudyError: ${detail}` }], - isError: true, - }; - } - - if (err instanceof TrialLedgerError) { - const detail = - Object.prototype.hasOwnProperty.call(TRIAL_LEDGER_ERROR_MESSAGES, err.code) && - TRIAL_LEDGER_ERROR_MESSAGES[err.code] !== undefined - ? TRIAL_LEDGER_ERROR_MESSAGES[err.code] - : 'Trial ledger operation failed.'; - return { - content: [{ type: 'text', text: `TrialLedgerError: ${detail}` }], - isError: true, - }; - } - - return { - content: [{ type: 'text', text: 'Error: Tool execution failed.' }], - isError: true, - }; -} - -function validateFactoryOptions(options: EventStudyToolOptions): number { - if (typeof options !== 'object' || options === null) { - throw new MarketDataStoreValidationError( - 'Invalid `options`: expected an EventStudyToolOptions object.', - 'options' - ); - } - - if ( - typeof options.store !== 'object' || - options.store === null || - typeof options.store.bars !== 'function' || - typeof options.store.events !== 'function' || - typeof options.store.universe !== 'function' - ) { - throw new MarketDataStoreValidationError( - 'Invalid `store`: expected a MarketDataStore implementing `bars`, `events`, and `universe`.', - 'store' - ); - } - - if ( - typeof options.ledger !== 'object' || - options.ledger === null || - typeof options.ledger.query !== 'function' - ) { - throw new SignalStudyError( - 'invalid_request', - 'Invalid `ledger`: expected a TrialLedgerExecutor implementing `query`.' - ); - } - - if (typeof options.resolveExchangeCalendars !== 'function') { - throw new EventPanelError( - 'invalid_option', - 'Invalid `resolveExchangeCalendars`: expected a function.' - ); - } - - if ( - typeof options.principalId !== 'string' || - (options.principalId !== 'operator' && !AGENT_PRINCIPAL_RE.test(options.principalId)) - ) { - throw new TrialLedgerError( - 'INVALID_PRINCIPAL', - `Invalid \`principalId\`: "${String(options.principalId)}".` - ); - } - - return validateVaultCutoffTs(options.vaultContext?.vaultCutoffTs); -} - -/** - * Creates the Vault-fenced `event_study` MCP tool backed by an injected - * {@link MarketDataStore}, {@link TrialLedgerExecutor}, and exchange-calendar - * resolver. - * - * Enforces `scope: 'vault_fenced'`, fences bounds before any dependency call, - * resolves named universes strictly prior to the study start date, filters - * bars and events defensively against the effective window and Vault cutoff, - * anchors events using actual exchange close calendars, runs `runEventStudy` - * under the injected research principal, and returns a bounded summary payload. - */ -export function createEventStudyTool(options: EventStudyToolOptions): McpToolEntry { - const vaultCutoffTs = validateFactoryOptions(options); - const { store, ledger, principalId, resolveExchangeCalendars } = options; - - return defineMcpTool({ - name: 'event_study', - description: - 'Run a Vault-fenced event study over daily bars and point-in-time events and record eligible trials to trial_ledger.', - inputSchema: eventStudyInputSchema, - async handler(input: EventStudyToolInput): Promise { - try { - const fenced = fenceVaultQueryBounds( - { - from: input.from, - to: input.to, - asOf: input.asOf, - }, - vaultCutoffTs - ); - - const canonicalKinds = sortAndDedupeStrings(input.event.kinds); - const canonicalSubtypes = - input.event.subtypes !== undefined - ? sortAndDedupeStrings(input.event.subtypes) - : undefined; - - let listingIds: number[]; - let universeSnapshotDate: string | null = null; - - if (input.universe !== undefined) { - universeSnapshotDate = resolvePreStartUniverseDate( - fenced.fromMs, - fenced.asOfMs, - fenced.asOfSubMs - ); - const resolved = await store.universe({ - ref: input.universe, - date: universeSnapshotDate, - }); - listingIds = sortAndDedupeListingIds(resolved); - } else { - listingIds = sortAndDedupeListingIds(input.listingIds ?? []); - } - - const hasBenchmark = input.benchmark === 'equal_weight'; - const basePayloadFields = { - scope: 'vault_fenced' as const, - vaultCutoffTs, - vaultCutoffDate: fenced.vaultCutoffDate, - event: { - kinds: canonicalKinds, - subtypes: canonicalSubtypes ?? null, - }, - preDays: input.preDays, - postDays: input.postDays, - benchmark: input.benchmark, - adjustment: input.adjustment, - universeMarket: input.universeMarket, - horizonBucket: input.horizonBucket, - fromMs: fenced.fromMs, - toMs: fenced.toMs, - asOfMs: fenced.asOfMs, - effectiveFrom: fenced.canonicalFrom, - effectiveTo: fenced.canonicalTo, - effectiveAsOf: fenced.canonicalAsOf, - clampedTo: fenced.clampedTo, - clampedAsOf: fenced.clampedAsOf, - listingCount: listingIds.length, - }; - - if (listingIds.length === 0) { - const payload: EventStudyResultPayload = { - ...basePayloadFields, - status: 'insufficient_data', - reason: 'below_min_events', - eventCount: 0, - vaultExcludedEvents: 0, - panelDiagnostics: ZERO_EVENT_PANEL_DIAGNOSTICS, - study: makeEmptyStudySummary(input.preDays, input.postDays, hasBenchmark), - }; - return { - content: [{ type: 'text', text: JSON.stringify(payload) }], - }; - } - - const rawBars = await collectBars( - store.bars({ - listingIds, - timeframe: '1d', - from: fenced.canonicalFrom, - to: fenced.canonicalTo, - adjustment: input.adjustment, - asOf: fenced.canonicalAsOf, - scope: 'vault_fenced', - }) - ); - - const rawEventsTable = await store.events({ - kinds: canonicalKinds, - listingIds, - from: fenced.canonicalFrom, - to: fenced.canonicalTo, - asOf: fenced.canonicalAsOf, - }); - - const listingIdSet = new Set(listingIds); - const kindSet = new Set(canonicalKinds); - const subtypeSet = canonicalSubtypes !== undefined ? new Set(canonicalSubtypes) : null; - - const { bars: eligibleBars, prePanelVaultExcludedDates } = filterEligibleBars( - rawBars, - listingIdSet, - fenced.fromMs, - fenced.fromSubMs, - fenced.toMs, - fenced.asOfMs, - vaultCutoffTs, - fenced.vaultCutoffDate - ); - - const { table: eligibleEventsTable, prePanelVaultExcludedEvents } = - filterEligibleEventsTable({ - table: rawEventsTable, - listingIdSet, - kindSet, - subtypeSet, - fromMs: fenced.fromMs, - fromSubMs: fenced.fromSubMs, - toMs: fenced.toMs, - asOfMs: fenced.asOfMs, - vaultCutoffTs, - vaultCutoffDate: fenced.vaultCutoffDate, - }); - - const events = eventsTableToEventRows(eligibleEventsTable, { - kinds: canonicalKinds, - ...(canonicalSubtypes !== undefined ? { subtypes: canonicalSubtypes } : {}), - }); - - const fromDate = utcDateOf(fenced.fromMs); - const toDate = utcDateOf(fenced.toMs); - const asOfDate = utcDateOf(fenced.asOfMs); - const vaultCutoffDayStartMs = Math.floor(vaultCutoffTs / MS_PER_DAY) * MS_PER_DAY; - const lastPreVaultDate = utcDateOf(vaultCutoffDayStartMs - MS_PER_DAY); - const calendarToDate = [toDate, asOfDate, lastPreVaultDate].reduce((a, b) => - a < b ? a : b - ); - - if (fromDate > calendarToDate) { - const panelDiagnostics: EventPanelDiagnostics = { - ...ZERO_EVENT_PANEL_DIAGNOSTICS, - vaultExcludedDates: prePanelVaultExcludedDates, - vaultExcludedEvents: prePanelVaultExcludedEvents, - droppedUnknownListing: events.length, - }; - const payload: EventStudyResultPayload = { - ...basePayloadFields, - status: 'insufficient_data', - reason: 'below_min_events', - eventCount: 0, - vaultExcludedEvents: prePanelVaultExcludedEvents, - panelDiagnostics, - study: makeEmptyStudySummary(input.preDays, input.postDays, hasBenchmark), - }; - return { - content: [{ type: 'text', text: JSON.stringify(payload) }], - }; - } - - let exchangeCalendars: EventStudyExchangeCalendars; - try { - exchangeCalendars = await resolveExchangeCalendars({ - listingIds, - fromDate, - toDate: calendarToDate, - }); - } catch (err: unknown) { - if (err instanceof EventPanelError) { - throw err; - } - throw new ExchangeCalendarResolverError(err); - } - - const built = buildEventStudyInput({ - bars: eligibleBars, - events, - vaultCutoffDate: fenced.vaultCutoffDate, - benchmark: input.benchmark, - exchangeCalendars, - }); - - const combinedPanelDiagnostics: EventPanelDiagnostics = { - ...built.diagnostics, - vaultExcludedDates: prePanelVaultExcludedDates + built.diagnostics.vaultExcludedDates, - vaultExcludedEvents: prePanelVaultExcludedEvents + built.diagnostics.vaultExcludedEvents, - }; - - if (built.input.sessionDates.length === 0) { - const payload: EventStudyResultPayload = { - ...basePayloadFields, - status: 'insufficient_data', - reason: 'below_min_events', - eventCount: 0, - vaultExcludedEvents: combinedPanelDiagnostics.vaultExcludedEvents, - panelDiagnostics: combinedPanelDiagnostics, - study: makeEmptyStudySummary(input.preDays, input.postDays, hasBenchmark), - }; - return { - content: [{ type: 'text', text: JSON.stringify(payload) }], - }; - } - - const expression = buildCanonicalEventStudyExpression({ - input, - canonicalKinds, - canonicalSubtypes, - listingIds, - universeSnapshotDate, - effectiveFrom: fenced.canonicalFrom, - effectiveTo: fenced.canonicalTo, - effectiveAsOf: fenced.canonicalAsOf, - }); - - const studyResult = await runEventStudy(ledger, { - principalId, - ...(input.campaignId !== undefined ? { campaignId: input.campaignId } : {}), - ...(input.hypothesisId !== undefined ? { hypothesisId: input.hypothesisId } : {}), - universeMarket: input.universeMarket, - horizonBucket: input.horizonBucket, - expression, - input: built.input, - vaultCutoffDate: fenced.vaultCutoffDate, - options: { - preDays: input.preDays, - postDays: input.postDays, - }, - }); - - const totalVaultExcludedEvents = - combinedPanelDiagnostics.vaultExcludedEvents + studyResult.vaultExcludedEvents; - const studySummary = projectStudySummary(studyResult.study); - - const payload: EventStudyResultPayload = - studyResult.status === 'ok' - ? { - ...basePayloadFields, - status: 'ok', - eventCount: built.input.events.length, - vaultExcludedEvents: totalVaultExcludedEvents, - panelDiagnostics: combinedPanelDiagnostics, - study: studySummary, - trial: studyResult.trial, - deflatedSharpe: studyResult.deflatedSharpe, - } - : { - ...basePayloadFields, - status: 'insufficient_data', - reason: studyResult.reason, - eventCount: built.input.events.length, - vaultExcludedEvents: totalVaultExcludedEvents, - panelDiagnostics: combinedPanelDiagnostics, - study: studySummary, - }; - - return { - content: [{ type: 'text', text: JSON.stringify(payload) }], - }; - } catch (err: unknown) { - return formatMappedEventStudyError(err); - } - }, - }); -} diff --git a/libs/research/src/mcp/tools/file-finding.ts b/libs/research/src/mcp/tools/file-finding.ts deleted file mode 100644 index 97fb8d3f..00000000 --- a/libs/research/src/mcp/tools/file-finding.ts +++ /dev/null @@ -1,416 +0,0 @@ -import { z } from 'zod'; -import type { McpToolCallResult } from '../protocol'; -import { type McpToolEntry, defineMcpTool } from '../server'; -import { type FindingRecord, READ_KNOWLEDGE_MAX_TEXT_LENGTH } from './read-knowledge'; -import { MAX_ECMASCRIPT_EPOCH_MS } from './vault-fenced-input'; - -/** Supported filing kinds for `file_finding` (per D12 in `design/PLATFORM-PLAN.md`). */ -export const FILE_FINDING_KINDS = ['finding', 'dead_end'] as const; - -export type FileFindingKind = (typeof FILE_FINDING_KINDS)[number]; - -/** Initial server-assigned review status for every newly filed finding or dead end. */ -export const FILE_FINDING_INITIAL_STATUS = 'pending_review' as const; - -export type FileFindingInitialStatus = typeof FILE_FINDING_INITIAL_STATUS; - -/** Hard maximum character length of a trimmed `file_finding` title. */ -export const FILE_FINDING_MAX_TITLE_LENGTH = 256; - -/** Hard maximum character length of a trimmed `file_finding` summary. */ -export const FILE_FINDING_MAX_SUMMARY_LENGTH = READ_KNOWLEDGE_MAX_TEXT_LENGTH; - -/** Hard maximum character length of a trimmed trial or evidence reference string. */ -export const FILE_FINDING_MAX_REF_LENGTH = 256; - -/** Hard maximum number of raw `trialRefs` accepted before deduplication. */ -export const FILE_FINDING_MAX_TRIAL_REFS = 32; - -/** Hard maximum number of raw `evidenceRefs` accepted before deduplication. */ -export const FILE_FINDING_MAX_EVIDENCE_REFS = 32; - -/** Hard maximum character length of a trimmed `idempotencyKey`. */ -export const FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH = 128; - -/** Fixed validation message used when unknown keys are supplied (never echoes caller keys). */ -export const FILE_FINDING_ERROR_UNKNOWN_KEYS = 'Unrecognized field(s) are not allowed.'; - -/** Fixed tool error message when one or more trial refs are unknown or Vault-only. */ -export const FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF = - 'One or more referenced trials are unavailable in the research-visible trial ledger.'; - -/** Fixed tool error message when an idempotency key is reused with a different payload. */ -export const FILE_FINDING_ERROR_IDEMPOTENCY_CONFLICT = - 'Idempotency key conflict: the provided idempotency key was already used with a different finding payload.'; - -/** Fixed tool error message when trial lookup, metadata generation, or append fails. */ -export const FILE_FINDING_ERROR_FILING_FAILED = - 'Failed to file finding due to a storage or lookup error.'; - -/** - * Append-only finding or dead-end record passed to {@link FindingWritePort.appendFinding}. - * - * Extends {@link FindingRecord} with `kind` and fixes `status` to `'pending_review'` - * so filed records are directly readable via `read_knowledge` while director approval - * happens out-of-band. - */ -export interface FiledFindingRecord extends FindingRecord { - readonly kind: FileFindingKind; - readonly status: FileFindingInitialStatus; -} - -/** Normalized caller-supplied fields compared for idempotency equality. */ -export type FiledFindingComparablePayload = Pick< - FiledFindingRecord, - 'kind' | 'title' | 'summary' | 'trialRefs' | 'evidenceRefs' ->; - -/** - * Discriminated outcome returned by {@link FindingWritePort.appendFinding}. - * - * - `'created'`: A new record was appended. - * - `'replayed'`: An existing record with the same `idempotencyKey` and - * identical normalized payload (`kind`, `title`, `summary`, `trialRefs`, - * `evidenceRefs`) was found; zero rows were appended and the stored `id` - * and `createdAt` are returned. - * - `'conflict'`: An existing record with the same `idempotencyKey` has a - * different normalized payload; zero rows were appended. - */ -export type AppendFindingResult = - | { - readonly status: 'created'; - readonly id: string; - readonly createdAt: string; - } - | { - readonly status: 'replayed'; - readonly id: string; - readonly createdAt: string; - } - | { - readonly status: 'conflict'; - }; - -/** - * Append-only write port injected into {@link createFileFindingTool}. - * - * Port contract: - * - Append-only by construction: exposes only {@link appendFinding} (no update - * or delete methods). - * - When `idempotencyKey` is supplied, the port must atomically compare and - * append within its configured key namespace: - * - Compare normalized `kind`, `title`, `summary`, `trialRefs`, and - * `evidenceRefs` (excluding server-generated `id`, `createdAt`, and `status`). - * - On an identical payload match, return `{ status: 'replayed', id, createdAt }` - * with the originally stored `id` and `createdAt` without appending a new row. - * - On a payload mismatch, return `{ status: 'conflict' }` and append zero rows. - * - When `idempotencyKey` is omitted (`undefined`), each call is independent and - * appends a new row, returning `{ status: 'created', id, createdAt }`. - */ -export interface FindingWritePort { - appendFinding( - record: FiledFindingRecord, - idempotencyKey?: string - ): Promise; -} - -/** - * Read-only trial visibility lookup port injected into {@link createFileFindingTool}. - * - * Bound at composition to the caller's research-visible `trial_ledger` and active - * Vault boundary. Accepts opaque string refs (for example, decimal `trialId` strings - * from `trial_ledger` receipts without numeric coercion) and returns `true` only when - * the trial exists and is research-visible. Unknown and Vault-only refs both return - * `false`. - */ -export interface TrialRefLookupPort { - hasResearchVisibleTrial(trialRef: string): Promise | boolean; -} - -/** Server-side injected configuration for {@link createFileFindingTool}. */ -export interface FileFindingToolOptions { - readonly port: FindingWritePort; - readonly trialLookup: TrialRefLookupPort; - readonly newId: () => string; - readonly now: () => Date | number; -} - -/** Structured JSON receipt serialized into the `file_finding` MCP text result. */ -export interface FileFindingResultPayload { - readonly id: string; - readonly createdAt: string; - readonly created: boolean; -} - -function compareStrings(a: string, b: string): number { - if (a < b) { - return -1; - } - if (a > b) { - return 1; - } - return 0; -} - -function normalizeRefSet(refs: readonly string[]): readonly string[] { - const unique = Array.from(new Set(refs)); - unique.sort(compareStrings); - return unique; -} - -function areStringArraysEqual(a: readonly string[], b: readonly string[]): boolean { - if (a.length !== b.length) { - return false; - } - for (let i = 0; i < a.length; i += 1) { - if (a[i] !== b[i]) { - return false; - } - } - return true; -} - -/** - * Compares two normalized filing payloads for idempotency equality across - * `kind`, `title`, `summary`, `trialRefs`, and `evidenceRefs` (excluding - * server-generated `id`, `createdAt`, and `status`). - */ -export function areFiledFindingPayloadsEqual( - a: FiledFindingComparablePayload, - b: FiledFindingComparablePayload -): boolean { - return ( - a.kind === b.kind && - a.title === b.title && - a.summary === b.summary && - areStringArraysEqual(a.trialRefs, b.trialRefs) && - areStringArraysEqual(a.evidenceRefs, b.evidenceRefs) - ); -} - -const refStringSchema = z.string().trim().min(1).max(FILE_FINDING_MAX_REF_LENGTH); - -/** - * Strict Zod input schema for the `file_finding` MCP tool. - * - * Intentionally omits server-controlled fields (`id`, `status`, `createdAt`) and - * Vault/holdout fields (`scope`, `vault_evaluation_only`, `vaultCutoffTs`). - * `.strict(FILE_FINDING_ERROR_UNKNOWN_KEYS)` rejects any unknown keys with a fixed - * message so caller-supplied key names are never echoed. - * - * `title` and `summary` must describe research-visible evidence only; `evidenceRefs` - * are opaque snapshot identifiers that the tool stores without dereferencing. - */ -export const fileFindingInputSchema = z - .object({ - kind: z - .enum(FILE_FINDING_KINDS, { - errorMap: () => ({ message: "Expected 'finding' or 'dead_end'." }), - }) - .describe("Filing classification: 'finding' or 'dead_end'."), - title: z - .string() - .trim() - .min(1) - .max(FILE_FINDING_MAX_TITLE_LENGTH) - .describe( - `Short title describing research-visible evidence (trimmed, 1–${FILE_FINDING_MAX_TITLE_LENGTH} characters).` - ), - summary: z - .string() - .trim() - .min(1) - .max(FILE_FINDING_MAX_SUMMARY_LENGTH) - .describe( - `Concise summary of research-visible evidence only; never include Vault holdout observations (trimmed, 1–${FILE_FINDING_MAX_SUMMARY_LENGTH} characters).` - ), - trialRefs: z - .array(refStringSchema) - .min(1) - .max(FILE_FINDING_MAX_TRIAL_REFS) - .transform(normalizeRefSet) - .describe( - `Opaque research-visible trial_ledger references (1–${FILE_FINDING_MAX_TRIAL_REFS} raw entries, each 1–${FILE_FINDING_MAX_REF_LENGTH} characters; deduplicated case-sensitively and sorted).` - ), - evidenceRefs: z - .array(refStringSchema) - .max(FILE_FINDING_MAX_EVIDENCE_REFS) - .default([]) - .transform(normalizeRefSet) - .describe( - `Optional opaque snapshot or artifact identifiers never dereferenced by the tool (0–${FILE_FINDING_MAX_EVIDENCE_REFS} raw entries, each 1–${FILE_FINDING_MAX_REF_LENGTH} characters; defaults to empty list, deduplicated case-sensitively and sorted).` - ), - idempotencyKey: z - .string() - .trim() - .min(1) - .max(FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH) - .optional() - .describe( - `Optional retry idempotency key (trimmed, 1–${FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH} characters).` - ), - }) - .strict(FILE_FINDING_ERROR_UNKNOWN_KEYS); - -export type FileFindingInput = z.infer; - -function toolError(message: string): McpToolCallResult { - return { - content: [{ type: 'text', text: message }], - isError: true, - }; -} - -function validateNonEmptyString(value: unknown): string | null { - if (typeof value !== 'string' || value.trim().length === 0) { - return null; - } - return value; -} - -function formatUtcIsoTimestamp(raw: Date | number): string | null { - const epochMs = raw instanceof Date ? raw.getTime() : raw; - if ( - typeof epochMs !== 'number' || - !Number.isFinite(epochMs) || - Math.abs(epochMs) >= MAX_ECMASCRIPT_EPOCH_MS - ) { - return null; - } - return new Date(epochMs).toISOString(); -} - -function validateFactoryOptions(options: FileFindingToolOptions): FileFindingToolOptions { - if (typeof options !== 'object' || options === null) { - throw new Error('Invalid `options`: expected a FileFindingToolOptions object.'); - } - - if ( - typeof options.port !== 'object' || - options.port === null || - typeof options.port.appendFinding !== 'function' - ) { - throw new Error( - 'Invalid `port`: expected a FindingWritePort implementing `appendFinding`.' - ); - } - - if ( - typeof options.trialLookup !== 'object' || - options.trialLookup === null || - typeof options.trialLookup.hasResearchVisibleTrial !== 'function' - ) { - throw new Error( - 'Invalid `trialLookup`: expected a TrialRefLookupPort implementing `hasResearchVisibleTrial`.' - ); - } - - if (typeof options.newId !== 'function') { - throw new Error('Invalid `newId`: expected a function returning a non-empty finding ID.'); - } - - if (typeof options.now !== 'function') { - throw new Error('Invalid `now`: expected a clock function returning a Date or epoch ms.'); - } - - return options; -} - -/** - * Creates the append-only `file_finding` MCP tool backed by an injected - * {@link FindingWritePort} and read-only {@link TrialRefLookupPort}. - * - * Verifies every unique `trialRef` against the research-visible trial ledger - * before generating server-controlled metadata (`id`, `createdAt`, - * `status: 'pending_review'`) or calling `appendFinding`. Returns only the - * explicitly projected `{ id, createdAt, created }` receipt on success and fixed - * sanitized `isError` messages on failure. - */ -export function createFileFindingTool(options: FileFindingToolOptions): McpToolEntry { - const validated = validateFactoryOptions(options); - const { port, trialLookup, newId, now } = validated; - - return defineMcpTool({ - name: 'file_finding', - description: - 'File an append-only empirical finding or dead end linked to research-visible trial ledger references for director review.', - inputSchema: fileFindingInputSchema, - async handler(input: FileFindingInput): Promise { - // Verify every unique research-visible trial ref before generating metadata or writing. - for (let i = 0; i < input.trialRefs.length; i += 1) { - const trialRef = input.trialRefs[i] as string; - let visible: unknown; - try { - visible = await trialLookup.hasResearchVisibleTrial(trialRef); - } catch { - return toolError(FILE_FINDING_ERROR_FILING_FAILED); - } - if (typeof visible !== 'boolean') { - return toolError(FILE_FINDING_ERROR_FILING_FAILED); - } - if (!visible) { - return toolError(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF); - } - } - - let id: string | null; - let createdAt: string | null; - try { - id = validateNonEmptyString(newId()); - createdAt = formatUtcIsoTimestamp(now()); - } catch { - return toolError(FILE_FINDING_ERROR_FILING_FAILED); - } - - if (id === null || createdAt === null) { - return toolError(FILE_FINDING_ERROR_FILING_FAILED); - } - - const record: FiledFindingRecord = { - id, - kind: input.kind, - title: input.title, - status: FILE_FINDING_INITIAL_STATUS, - createdAt, - summary: input.summary, - trialRefs: [...input.trialRefs], - evidenceRefs: [...input.evidenceRefs], - }; - - let outcome: AppendFindingResult; - try { - outcome = await port.appendFinding(record, input.idempotencyKey); - } catch { - return toolError(FILE_FINDING_ERROR_FILING_FAILED); - } - - if (typeof outcome !== 'object' || outcome === null) { - return toolError(FILE_FINDING_ERROR_FILING_FAILED); - } - - if (outcome.status === 'conflict') { - return toolError(FILE_FINDING_ERROR_IDEMPOTENCY_CONFLICT); - } - - if (outcome.status !== 'created' && outcome.status !== 'replayed') { - return toolError(FILE_FINDING_ERROR_FILING_FAILED); - } - - const receiptId = validateNonEmptyString(outcome.id); - const receiptCreatedAt = validateNonEmptyString(outcome.createdAt); - if (receiptId === null || receiptCreatedAt === null) { - return toolError(FILE_FINDING_ERROR_FILING_FAILED); - } - - const payload: FileFindingResultPayload = { - id: receiptId, - createdAt: receiptCreatedAt, - created: outcome.status === 'created', - }; - - return { - content: [{ type: 'text', text: JSON.stringify(payload) }], - }; - }, - }); -} diff --git a/libs/research/src/mcp/tools/query-data.ts b/libs/research/src/mcp/tools/query-data.ts deleted file mode 100644 index b65fff46..00000000 --- a/libs/research/src/mcp/tools/query-data.ts +++ /dev/null @@ -1,249 +0,0 @@ -import { z } from 'zod'; -import { - type BarRecord, - type MarketDataStore, - MarketDataStoreValidationError, - type VaultFenceContext, -} from '../../market-data-store'; -import type { McpToolCallResult } from '../protocol'; -import { type McpToolEntry, defineMcpTool } from '../server'; -import { - EXCLUSIVE_LISTING_SELECTOR_MESSAGE, - MCP_MAX_LISTING_IDS, - createListingIdsFieldSchema, - createUniverseFieldSchema, - fenceVaultQueryBounds, - formatMappedStoreError, - hasExclusiveListingSelector, - resolveUniverseDate, - validateVaultCutoffTs, -} from './vault-fenced-input'; - -/** Default maximum number of bar rows returned by `query_data`. */ -export const QUERY_DATA_DEFAULT_LIMIT = 500; - -/** Hard maximum number of bar rows returned by `query_data`. */ -export const QUERY_DATA_MAX_LIMIT = 5_000; - -/** Hard maximum number of explicit `listingIds` accepted by `query_data`. */ -export const QUERY_DATA_MAX_LISTING_IDS = MCP_MAX_LISTING_IDS; - -/** - * Strict Zod input schema for the `query_data` MCP tool. - * - * Intentionally omits `scope` and `vault_evaluation_only`; `.strict()` rejects - * any caller attempt to supply them or any other unknown key. - */ -export const queryDataInputSchema = z - .object({ - listingIds: createListingIdsFieldSchema( - 'Explicit INT32 listing IDs to query (mutually exclusive with universe).' - ), - universe: createUniverseFieldSchema( - 'Universe identifier such as US_EQ, CA_EQ, or US_CA_EQ (mutually exclusive with listingIds).' - ), - from: z - .string() - .min(1) - .describe('Inclusive start date (YYYY-MM-DD) or UTC ISO-8601 timestamp.'), - to: z - .string() - .min(1) - .describe('Inclusive end date (YYYY-MM-DD) or UTC ISO-8601 timestamp; clamped below Vault cutoff.'), - timeframe: z - .enum(['1m', '5m', '1h', '1d']) - .default('1d') - .describe('Bar timeframe (default 1d).'), - adjustment: z - .enum(['raw', 'split', 'total']) - .default('raw') - .describe('Price/volume adjustment mode (default raw).'), - asOf: z - .string() - .min(1) - .optional() - .describe('Optional point-in-time knowledge cutoff (YYYY-MM-DD or UTC ISO-8601); clamped below Vault cutoff.'), - limit: z - .number() - .int() - .min(1) - .max(QUERY_DATA_MAX_LIMIT) - .default(QUERY_DATA_DEFAULT_LIMIT) - .describe( - `Maximum number of bar rows to return (default ${QUERY_DATA_DEFAULT_LIMIT}, max ${QUERY_DATA_MAX_LIMIT}).` - ), - }) - .strict() - .refine(hasExclusiveListingSelector, EXCLUSIVE_LISTING_SELECTOR_MESSAGE); - -export type QueryDataInput = z.infer; - -/** Configuration for {@link createQueryDataTool}. */ -export interface QueryDataToolOptions { - readonly store: MarketDataStore; - readonly vaultContext: Pick; -} - -/** Structured JSON payload serialized into the `query_data` MCP text result. */ -export interface QueryDataResultPayload { - readonly scope: 'vault_fenced'; - readonly vaultCutoffTs: number; - readonly timeframe: '1m' | '5m' | '1h' | '1d'; - readonly adjustment: 'raw' | 'split' | 'total'; - readonly fromMs: number; - readonly toMs: number; - readonly asOfMs: number; - readonly clampedTo: boolean; - readonly clampedAsOf: boolean; - readonly limit: number; - readonly rowCount: number; - readonly truncated: boolean; - readonly rows: readonly BarRecord[]; -} - -function validateFactoryOptions(options: QueryDataToolOptions): number { - if ( - typeof options.store !== 'object' || - options.store === null || - typeof options.store.bars !== 'function' || - typeof options.store.universe !== 'function' - ) { - throw new MarketDataStoreValidationError( - 'Invalid `store`: expected a MarketDataStore implementing `bars` and `universe`.', - 'store' - ); - } - - return validateVaultCutoffTs(options.vaultContext?.vaultCutoffTs); -} - -/** - * Creates the Vault-fenced `query_data` MCP tool backed by an injected - * {@link MarketDataStore}. - * - * Always enforces `scope: 'vault_fenced'`, runs {@link applyVaultFence} before - * any store call, drops any post-cutoff row yielded by a store as defense in - * depth, and bounds output rows by `limit` (default {@link QUERY_DATA_DEFAULT_LIMIT}, - * hard max {@link QUERY_DATA_MAX_LIMIT}). - */ -export function createQueryDataTool(options: QueryDataToolOptions): McpToolEntry { - const vaultCutoffTs = validateFactoryOptions(options); - const { store } = options; - - return defineMcpTool({ - name: 'query_data', - description: - 'Query Vault-fenced OHLCV market bars for explicit listing IDs or a survivorship-free universe.', - inputSchema: queryDataInputSchema, - async handler(input: QueryDataInput): Promise { - try { - const fenced = fenceVaultQueryBounds( - { - from: input.from, - to: input.to, - asOf: input.asOf, - }, - vaultCutoffTs - ); - - const effectiveLimit = input.limit; - let listingIds: number[]; - - if (input.universe !== undefined) { - const universeDate = resolveUniverseDate( - fenced.toMs, - fenced.toSubMs, - fenced.asOfMs, - fenced.asOfSubMs - ); - const resolved = await store.universe({ - ref: input.universe, - date: universeDate, - }); - if (resolved.length === 0) { - const emptyPayload: QueryDataResultPayload = { - scope: 'vault_fenced', - vaultCutoffTs, - timeframe: input.timeframe, - adjustment: input.adjustment, - fromMs: fenced.fromMs, - toMs: fenced.toMs, - asOfMs: fenced.asOfMs, - clampedTo: fenced.clampedTo, - clampedAsOf: fenced.clampedAsOf, - limit: effectiveLimit, - rowCount: 0, - truncated: false, - rows: [], - }; - return { - content: [{ type: 'text', text: JSON.stringify(emptyPayload) }], - }; - } - listingIds = [...resolved]; - } else { - listingIds = [...(input.listingIds ?? [])]; - } - - const stream = store.bars({ - listingIds, - timeframe: input.timeframe, - from: input.from, - to: fenced.effectiveFencedTo, - adjustment: input.adjustment, - asOf: fenced.effectiveFencedAsOf, - scope: 'vault_fenced', - }); - - const rows: BarRecord[] = []; - let truncated = false; - - outer: for await (const batch of stream) { - for (const row of batch.rows) { - if ( - !Number.isFinite(row.ts) || - !Number.isFinite(row.knownAt) || - row.ts >= vaultCutoffTs || - row.knownAt >= vaultCutoffTs - ) { - continue; - } - - if (rows.length >= effectiveLimit) { - truncated = true; - break outer; - } - - rows.push(row); - } - } - - const payload: QueryDataResultPayload = { - scope: 'vault_fenced', - vaultCutoffTs, - timeframe: input.timeframe, - adjustment: input.adjustment, - fromMs: fenced.fromMs, - toMs: fenced.toMs, - asOfMs: fenced.asOfMs, - clampedTo: fenced.clampedTo, - clampedAsOf: fenced.clampedAsOf, - limit: effectiveLimit, - rowCount: rows.length, - truncated, - rows, - }; - - return { - content: [{ type: 'text', text: JSON.stringify(payload) }], - }; - } catch (err: unknown) { - const mapped = formatMappedStoreError(err); - if (mapped !== null) { - return mapped; - } - throw err; - } - }, - }); -} diff --git a/libs/research/src/mcp/tools/read-knowledge.ts b/libs/research/src/mcp/tools/read-knowledge.ts deleted file mode 100644 index 929b398f..00000000 --- a/libs/research/src/mcp/tools/read-knowledge.ts +++ /dev/null @@ -1,588 +0,0 @@ -import { z } from 'zod'; -import type { McpToolCallResult } from '../protocol'; -import { type McpToolEntry, defineMcpTool } from '../server'; - -/** Concrete knowledge sources returned in `read_knowledge` rows and source counts. */ -export const READ_KNOWLEDGE_RECORD_SOURCES = ['library', 'findings', 'provider_caveats'] as const; - -export type ReadKnowledgeRecordSource = (typeof READ_KNOWLEDGE_RECORD_SOURCES)[number]; - -/** Supported `source` selector values for `read_knowledge`. */ -export const READ_KNOWLEDGE_SOURCES = [...READ_KNOWLEDGE_RECORD_SOURCES, 'all'] as const; - -export type ReadKnowledgeSource = (typeof READ_KNOWLEDGE_SOURCES)[number]; - -/** Default maximum number of matching records returned by `read_knowledge`. */ -export const READ_KNOWLEDGE_DEFAULT_LIMIT = 20; - -/** Hard maximum number of matching records returned by `read_knowledge`. */ -export const READ_KNOWLEDGE_MAX_LIMIT = 100; - -/** Hard maximum character length of a trimmed `read_knowledge` query string. */ -export const READ_KNOWLEDGE_MAX_QUERY_LENGTH = 64; - -/** Hard maximum character length per projected text field (`body`, `summary`, `caveat`). */ -export const READ_KNOWLEDGE_MAX_TEXT_LENGTH = 4096; - -/** Methodology or literature card record returned by {@link KnowledgePort.listLibraryCards}. */ -export interface LibraryCardRecord { - readonly id: string; - readonly title: string; - readonly tags: readonly string[]; - readonly summary: string; - readonly body: string; -} - -/** Empirical Stock Bot finding record returned by {@link KnowledgePort.listFindings}. */ -export interface FindingRecord { - readonly id: string; - readonly title: string; - readonly status: string; - readonly createdAt: string; - readonly summary: string; - readonly trialRefs: readonly string[]; - readonly evidenceRefs: readonly string[]; -} - -/** Provider dataset caveat record returned by {@link KnowledgePort.listProviderCaveats}. */ -export interface ProviderCaveatRecord { - readonly id: string; - readonly provider: string; - readonly dataset: string; - readonly caveat: string; - readonly createdAt: string; -} - -/** Applicable parsed selectors passed to {@link KnowledgePort.listLibraryCards}. */ -export interface LibraryCardQuery { - readonly id?: string; - readonly query?: string; - readonly tags?: readonly string[]; -} - -/** Applicable parsed selectors passed to {@link KnowledgePort.listFindings}. */ -export interface FindingQuery { - readonly id?: string; - readonly query?: string; -} - -/** Applicable parsed selectors passed to {@link KnowledgePort.listProviderCaveats}. */ -export interface ProviderCaveatQuery { - readonly id?: string; - readonly query?: string; - readonly provider?: string; -} - -/** - * Read-only knowledge lookup port injected into {@link createReadKnowledgeTool}. - * - * Port contract: - * - Read-only by construction: exposes only lookup methods and never mutates backing stores. - * - Callers and concrete adapters must supply research-visible records and references only; - * holdout observations and vault-only evidence must be excluded from the research corpus. - * - Return all eligible candidates (with IDs unique within each source) without pre-slicing - * so the tool controls deterministic global ranking and the global `limit`. - */ -export interface KnowledgePort { - listLibraryCards(q: LibraryCardQuery): Promise; - listFindings(q: FindingQuery): Promise; - listProviderCaveats(q: ProviderCaveatQuery): Promise; -} - -/** - * Strict Zod input schema for the `read_knowledge` MCP tool. - * - * Intentionally omits `scope`, `vault_evaluation_only`, and `vaultCutoffTs`; - * `.strict()` rejects any unknown keys. - */ -export const readKnowledgeInputSchema = z - .object({ - source: z - .enum(READ_KNOWLEDGE_SOURCES) - .default('all') - .describe( - 'Knowledge source to query: library, findings, provider_caveats, or all (default all).' - ), - query: z - .string() - .trim() - .min(1) - .max(READ_KNOWLEDGE_MAX_QUERY_LENGTH) - .optional() - .describe( - `Optional case-insensitive substring query (trimmed, 1–${READ_KNOWLEDGE_MAX_QUERY_LENGTH} characters). Ignored when id is supplied.` - ), - id: z - .string() - .trim() - .min(1) - .optional() - .describe( - 'Optional exact case-sensitive card or record ID selector. Takes precedence over query when supplied.' - ), - tags: z - .array(z.string().trim().min(1)) - .min(1) - .optional() - .describe( - 'Optional tag filter applied only to library cards (case-insensitive all-tag match; findings and provider_caveats are unaffected when source is all).' - ), - provider: z - .string() - .trim() - .min(1) - .optional() - .describe( - 'Optional provider filter applied only to provider_caveats (case-insensitive exact match; library and findings are unaffected when source is all).' - ), - limit: z - .number() - .int() - .min(1) - .max(READ_KNOWLEDGE_MAX_LIMIT) - .default(READ_KNOWLEDGE_DEFAULT_LIMIT) - .describe( - `Maximum number of ranked records to return (default ${READ_KNOWLEDGE_DEFAULT_LIMIT}, max ${READ_KNOWLEDGE_MAX_LIMIT}).` - ), - }) - .strict(); - -export type ReadKnowledgeInput = z.infer; - -/** Server-side injected configuration for {@link createReadKnowledgeTool}. */ -export interface ReadKnowledgeToolOptions { - readonly port: KnowledgePort; -} - -/** Source-labeled library card row emitted by `read_knowledge`. */ -export interface ReadKnowledgeLibraryRow { - readonly source: 'library'; - readonly id: string; - readonly title: string; - readonly tags: readonly string[]; - readonly summary: string; - readonly body: string; - readonly truncated: boolean; -} - -/** Source-labeled empirical finding row emitted by `read_knowledge`. */ -export interface ReadKnowledgeFindingRow { - readonly source: 'findings'; - readonly id: string; - readonly title: string; - readonly status: string; - readonly createdAt: string; - readonly summary: string; - readonly trialRefs: readonly string[]; - readonly evidenceRefs: readonly string[]; - readonly truncated: boolean; -} - -/** Source-labeled provider caveat row emitted by `read_knowledge`. */ -export interface ReadKnowledgeProviderCaveatRow { - readonly source: 'provider_caveats'; - readonly id: string; - readonly provider: string; - readonly dataset: string; - readonly caveat: string; - readonly createdAt: string; - readonly truncated: boolean; -} - -/** Discriminated union of rows emitted by `read_knowledge`. */ -export type ReadKnowledgeRow = - | ReadKnowledgeLibraryRow - | ReadKnowledgeFindingRow - | ReadKnowledgeProviderCaveatRow; - -/** Per-source counts of returned rows after applying the global `limit`. */ -export interface ReadKnowledgeSourceCounts { - readonly library: number; - readonly findings: number; - readonly provider_caveats: number; -} - -/** Structured JSON payload serialized into the `read_knowledge` MCP text result. */ -export interface ReadKnowledgeResultPayload { - readonly rowCount: number; - readonly sources: ReadKnowledgeSourceCounts; - readonly rows: readonly ReadKnowledgeRow[]; -} - -const SOURCE_ORDER: Readonly> = { - library: 0, - findings: 1, - provider_caveats: 2, -}; - -function compareStrings(a: string, b: string): number { - if (a < b) { - return -1; - } - if (a > b) { - return 1; - } - return 0; -} - -function validateRequiredString(value: unknown, field: string): string { - if (typeof value !== 'string') { - throw new Error(`Invalid port string for "${field}".`); - } - return value; -} - -function validateStringArray(value: unknown, field: string): readonly string[] { - if (!Array.isArray(value)) { - throw new Error(`Invalid port string array for "${field}".`); - } - const result: string[] = []; - for (let i = 0; i < value.length; i += 1) { - const entry: unknown = value[i]; - if (typeof entry !== 'string') { - throw new Error(`Invalid port string array entry for "${field}".`); - } - result.push(entry); - } - return result; -} - -function truncateText(value: string): { readonly text: string; readonly truncated: boolean } { - if (value.length <= READ_KNOWLEDGE_MAX_TEXT_LENGTH) { - return { text: value, truncated: false }; - } - return { - text: value.slice(0, READ_KNOWLEDGE_MAX_TEXT_LENGTH), - truncated: true, - }; -} - -function validateLibraryCard(raw: LibraryCardRecord): LibraryCardRecord { - if (typeof raw !== 'object' || raw === null) { - throw new Error('Invalid library card record returned by port.'); - } - return { - id: validateRequiredString(raw.id, 'id'), - title: validateRequiredString(raw.title, 'title'), - tags: validateStringArray(raw.tags, 'tags'), - summary: validateRequiredString(raw.summary, 'summary'), - body: validateRequiredString(raw.body, 'body'), - }; -} - -function validateFinding(raw: FindingRecord): FindingRecord { - if (typeof raw !== 'object' || raw === null) { - throw new Error('Invalid finding record returned by port.'); - } - return { - id: validateRequiredString(raw.id, 'id'), - title: validateRequiredString(raw.title, 'title'), - status: validateRequiredString(raw.status, 'status'), - createdAt: validateRequiredString(raw.createdAt, 'createdAt'), - summary: validateRequiredString(raw.summary, 'summary'), - trialRefs: validateStringArray(raw.trialRefs, 'trialRefs'), - evidenceRefs: validateStringArray(raw.evidenceRefs, 'evidenceRefs'), - }; -} - -function validateProviderCaveat(raw: ProviderCaveatRecord): ProviderCaveatRecord { - if (typeof raw !== 'object' || raw === null) { - throw new Error('Invalid provider caveat record returned by port.'); - } - return { - id: validateRequiredString(raw.id, 'id'), - provider: validateRequiredString(raw.provider, 'provider'), - dataset: validateRequiredString(raw.dataset, 'dataset'), - caveat: validateRequiredString(raw.caveat, 'caveat'), - createdAt: validateRequiredString(raw.createdAt, 'createdAt'), - }; -} - -function matchesAllTags( - cardTags: readonly string[], - requiredLowerTags: readonly string[] -): boolean { - const cardLowerTags = new Set(cardTags.map(tag => tag.toLowerCase())); - for (let i = 0; i < requiredLowerTags.length; i += 1) { - if (!cardLowerTags.has(requiredLowerTags[i] as string)) { - return false; - } - } - return true; -} - -function rankLibraryCard( - card: LibraryCardRecord, - exactId: string | undefined, - normalizedQuery: string | null, - requiredLowerTags: readonly string[] | null -): number | null { - if (requiredLowerTags !== null && !matchesAllTags(card.tags, requiredLowerTags)) { - return null; - } - if (exactId !== undefined) { - return card.id === exactId ? 0 : null; - } - if (normalizedQuery === null) { - return 2; - } - const titleMatches = card.title.toLowerCase().includes(normalizedQuery); - const tagMatches = card.tags.some(tag => tag.toLowerCase().includes(normalizedQuery)); - const summaryMatches = card.summary.toLowerCase().includes(normalizedQuery); - if (!titleMatches && !tagMatches && !summaryMatches) { - return null; - } - return titleMatches ? 1 : 2; -} - -function rankFinding( - finding: FindingRecord, - exactId: string | undefined, - normalizedQuery: string | null -): number | null { - if (exactId !== undefined) { - return finding.id === exactId ? 0 : null; - } - if (normalizedQuery === null) { - return 2; - } - const titleMatches = finding.title.toLowerCase().includes(normalizedQuery); - const summaryMatches = finding.summary.toLowerCase().includes(normalizedQuery); - if (!titleMatches && !summaryMatches) { - return null; - } - return titleMatches ? 1 : 2; -} - -function rankProviderCaveat( - caveat: ProviderCaveatRecord, - exactId: string | undefined, - normalizedQuery: string | null, - normalizedProvider: string | null -): number | null { - if (normalizedProvider !== null && caveat.provider.toLowerCase() !== normalizedProvider) { - return null; - } - if (exactId !== undefined) { - return caveat.id === exactId ? 0 : null; - } - if (normalizedQuery === null) { - return 2; - } - const datasetMatches = caveat.dataset.toLowerCase().includes(normalizedQuery); - const providerMatches = caveat.provider.toLowerCase().includes(normalizedQuery); - const caveatMatches = caveat.caveat.toLowerCase().includes(normalizedQuery); - if (!datasetMatches && !providerMatches && !caveatMatches) { - return null; - } - return datasetMatches ? 1 : 2; -} - -function projectLibraryCard(card: LibraryCardRecord): ReadKnowledgeLibraryRow { - const summary = truncateText(card.summary); - const body = truncateText(card.body); - return { - source: 'library', - id: card.id, - title: card.title, - tags: [...card.tags], - summary: summary.text, - body: body.text, - truncated: summary.truncated || body.truncated, - }; -} - -function projectFinding(finding: FindingRecord): ReadKnowledgeFindingRow { - const summary = truncateText(finding.summary); - return { - source: 'findings', - id: finding.id, - title: finding.title, - status: finding.status, - createdAt: finding.createdAt, - summary: summary.text, - trialRefs: [...finding.trialRefs], - evidenceRefs: [...finding.evidenceRefs], - truncated: summary.truncated, - }; -} - -function projectProviderCaveat(caveat: ProviderCaveatRecord): ReadKnowledgeProviderCaveatRow { - const caveatText = truncateText(caveat.caveat); - return { - source: 'provider_caveats', - id: caveat.id, - provider: caveat.provider, - dataset: caveat.dataset, - caveat: caveatText.text, - createdAt: caveat.createdAt, - truncated: caveatText.truncated, - }; -} - -function validateFactoryOptions(options: ReadKnowledgeToolOptions): KnowledgePort { - if (typeof options !== 'object' || options === null) { - throw new Error('Invalid `options`: expected a ReadKnowledgeToolOptions object.'); - } - - const { port } = options; - if ( - typeof port !== 'object' || - port === null || - typeof port.listLibraryCards !== 'function' || - typeof port.listFindings !== 'function' || - typeof port.listProviderCaveats !== 'function' - ) { - throw new Error( - 'Invalid `port`: expected a KnowledgePort implementing `listLibraryCards`, `listFindings`, and `listProviderCaveats`.' - ); - } - - return port; -} - -interface RankedCandidate { - readonly rank: number; - readonly row: ReadKnowledgeRow; -} - -/** - * Creates the read-only `read_knowledge` MCP tool backed by an injected - * {@link KnowledgePort}. - * - * Queries only the selected source(s), applies exact-ID or case-insensitive - * text matching and source-specific filters (`tags` for library cards, - * `provider` for provider caveats), ranks deterministically (exact ID > title - * match > ascending ID, breaking cross-source ties in `library`, `findings`, - * `provider_caveats` order), applies `limit` after ranking, and caps long text - * fields independently with `truncated: true`. - */ -export function createReadKnowledgeTool(options: ReadKnowledgeToolOptions): McpToolEntry { - const port = validateFactoryOptions(options); - - return defineMcpTool({ - name: 'read_knowledge', - description: - 'Read-only lookup across methodology library cards, empirical findings, and provider dataset caveats.', - inputSchema: readKnowledgeInputSchema, - async handler(input: ReadKnowledgeInput): Promise { - const wantLibrary = input.source === 'all' || input.source === 'library'; - const wantFindings = input.source === 'all' || input.source === 'findings'; - const wantCaveats = input.source === 'all' || input.source === 'provider_caveats'; - - const baseQuery: FindingQuery = - input.id !== undefined - ? { id: input.id } - : input.query !== undefined - ? { query: input.query } - : {}; - - const libraryQuery: LibraryCardQuery = { - ...baseQuery, - ...(input.tags !== undefined ? { tags: input.tags } : {}), - }; - const findingQuery: FindingQuery = baseQuery; - const caveatQuery: ProviderCaveatQuery = { - ...baseQuery, - ...(input.provider !== undefined ? { provider: input.provider } : {}), - }; - - const [rawLibrary, rawFindings, rawCaveats] = await Promise.all([ - (async () => (wantLibrary ? port.listLibraryCards(libraryQuery) : null))(), - (async () => (wantFindings ? port.listFindings(findingQuery) : null))(), - (async () => (wantCaveats ? port.listProviderCaveats(caveatQuery) : null))(), - ]); - - const normalizedQuery = - input.id === undefined && input.query !== undefined ? input.query.toLowerCase() : null; - const requiredLowerTags = - input.tags !== undefined ? input.tags.map(tag => tag.toLowerCase()) : null; - const normalizedProvider = - input.provider !== undefined ? input.provider.toLowerCase() : null; - - const eligible: RankedCandidate[] = []; - - if (rawLibrary !== null) { - if (!Array.isArray(rawLibrary)) { - throw new Error('Invalid library cards response returned by port.'); - } - for (let i = 0; i < rawLibrary.length; i += 1) { - const card = validateLibraryCard(rawLibrary[i] as LibraryCardRecord); - const rank = rankLibraryCard(card, input.id, normalizedQuery, requiredLowerTags); - if (rank !== null) { - eligible.push({ rank, row: projectLibraryCard(card) }); - } - } - } - - if (rawFindings !== null) { - if (!Array.isArray(rawFindings)) { - throw new Error('Invalid findings response returned by port.'); - } - for (let i = 0; i < rawFindings.length; i += 1) { - const finding = validateFinding(rawFindings[i] as FindingRecord); - const rank = rankFinding(finding, input.id, normalizedQuery); - if (rank !== null) { - eligible.push({ rank, row: projectFinding(finding) }); - } - } - } - - if (rawCaveats !== null) { - if (!Array.isArray(rawCaveats)) { - throw new Error('Invalid provider caveats response returned by port.'); - } - for (let i = 0; i < rawCaveats.length; i += 1) { - const caveat = validateProviderCaveat(rawCaveats[i] as ProviderCaveatRecord); - const rank = rankProviderCaveat(caveat, input.id, normalizedQuery, normalizedProvider); - if (rank !== null) { - eligible.push({ rank, row: projectProviderCaveat(caveat) }); - } - } - } - - eligible.sort((a, b) => { - if (a.rank !== b.rank) { - return a.rank - b.rank; - } - const idCmp = compareStrings(a.row.id, b.row.id); - if (idCmp !== 0) { - return idCmp; - } - return SOURCE_ORDER[a.row.source] - SOURCE_ORDER[b.row.source]; - }); - - const limitCount = Math.min(eligible.length, input.limit); - const rows: ReadKnowledgeRow[] = []; - let libraryCount = 0; - let findingsCount = 0; - let providerCaveatsCount = 0; - - for (let i = 0; i < limitCount; i += 1) { - const row = (eligible[i] as RankedCandidate).row; - rows.push(row); - if (row.source === 'library') { - libraryCount += 1; - } else if (row.source === 'findings') { - findingsCount += 1; - } else { - providerCaveatsCount += 1; - } - } - - const payload: ReadKnowledgeResultPayload = { - rowCount: rows.length, - sources: { - library: libraryCount, - findings: findingsCount, - provider_caveats: providerCaveatsCount, - }, - rows, - }; - - return { - content: [{ type: 'text', text: JSON.stringify(payload) }], - }; - }, - }); -} diff --git a/libs/research/src/mcp/tools/search-symbols.ts b/libs/research/src/mcp/tools/search-symbols.ts deleted file mode 100644 index a5bd5882..00000000 --- a/libs/research/src/mcp/tools/search-symbols.ts +++ /dev/null @@ -1,359 +0,0 @@ -import { z } from 'zod'; -import { MarketDataStoreValidationError, type VaultFenceContext } from '../../market-data-store'; -import type { McpToolCallResult } from '../protocol'; -import { type McpToolEntry, defineMcpTool } from '../server'; -import { utcDateOf, validateVaultCutoffTs } from './vault-fenced-input'; - -/** Default maximum number of matching listings returned by `search_symbols`. */ -export const SEARCH_SYMBOLS_DEFAULT_LIMIT = 20; - -/** Hard maximum number of matching listings returned by `search_symbols`. */ -export const SEARCH_SYMBOLS_MAX_LIMIT = 100; - -/** Hard maximum character length of a trimmed `search_symbols` query string. */ -export const SEARCH_SYMBOLS_MAX_QUERY_LENGTH = 64; - -/** Supported exchange country filters for `search_symbols`. */ -export const SEARCH_SYMBOLS_COUNTRIES = ['US', 'CA'] as const; - -export type SymbolSearchCountry = (typeof SEARCH_SYMBOLS_COUNTRIES)[number]; - -const CALENDAR_DATE_RE = /^(\d{4})-(\d{2})-(\d{2})$/; -const DAYS_IN_MONTH: readonly number[] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; - -/** - * Security-master projection returned by {@link SymbolSearchPort} and emitted - * (after Vault fencing) by the `search_symbols` MCP tool. - * - * Field provenance (M1 security master DDL / `design/DATA-CONTRACTS.md`): - * - `listingId`: `listing.listing_id` (`INT32`) - * - `instrumentId`: `listing.instrument_id` / `instrument.instrument_id` (`INT32`) - * - `ticker`: `listing_symbol_history.ticker` valid as of the Vault cutoff - * - `classSuffix`: nullable `listing.class_suffix` - * - `name`: `instrument.canonical_name` - * - `mic`: `listing.mic` - * - `currency`: `listing.currency` - * - `isin`: nullable `instrument.primary_isin` - * - `firstBarDate`: nullable `YYYY-MM-DD` observed bar span start (`listing.listed_from`) - * - `lastBarDate`: nullable `YYYY-MM-DD` observed bar span end (`listing.listed_to`) - * - `delistedAt`: nullable `YYYY-MM-DD` confirmed delisting date (distinct from `lastBarDate`) - */ -export interface SymbolSearchRow { - readonly listingId: number; - readonly instrumentId: number; - readonly ticker: string; - readonly classSuffix: string | null; - readonly name: string; - readonly mic: string; - readonly currency: string; - readonly isin: string | null; - readonly firstBarDate: string | null; - readonly lastBarDate: string | null; - readonly delistedAt: string | null; -} - -/** - * Query passed to {@link SymbolSearchPort.searchSymbols}. - * - * Port contract: - * - Return all matching candidates for tool-side ranking and Vault fencing; - * treat `limit` as a hint only (never truncate ahead of exact-ticker matches). - * - Resolve symbol identities and matches as of `vaultCutoffTs` so future - * renames or delistings do not leak into research queries. - * - Include listings whose `firstBarDate` is unknown (`null`). - * - The tool always passes `includeDelisted: true` to the port so current - * delisting status cannot drop a candidate before Vault cutoff masking. - */ -export interface SymbolSearchQuery { - readonly query: string; - readonly limit: number; - readonly country?: SymbolSearchCountry; - readonly includeDelisted: boolean; - readonly vaultCutoffTs: number; -} - -/** Read-only security-master symbol lookup port injected into `createSearchSymbolsTool`. */ -export interface SymbolSearchPort { - searchSymbols(q: SymbolSearchQuery): Promise; -} - -/** - * Strict Zod input schema for the `search_symbols` MCP tool. - * - * Intentionally omits `scope`, `vault_evaluation_only`, and `vaultCutoffTs`; - * `.strict()` rejects any unknown keys. - */ -export const searchSymbolsInputSchema = z - .object({ - query: z - .string() - .trim() - .min(1) - .max(SEARCH_SYMBOLS_MAX_QUERY_LENGTH) - .describe( - `Ticker symbol or company name search query (trimmed, 1–${SEARCH_SYMBOLS_MAX_QUERY_LENGTH} characters).` - ), - limit: z - .number() - .int() - .min(1) - .max(SEARCH_SYMBOLS_MAX_LIMIT) - .default(SEARCH_SYMBOLS_DEFAULT_LIMIT) - .describe( - `Maximum number of matching listings to return (default ${SEARCH_SYMBOLS_DEFAULT_LIMIT}, max ${SEARCH_SYMBOLS_MAX_LIMIT}).` - ), - country: z - .enum(SEARCH_SYMBOLS_COUNTRIES) - .optional() - .describe('Optional exchange country filter (US or CA).'), - includeDelisted: z - .boolean() - .default(true) - .describe('Include delisted listings as of the Vault cutoff (default true).'), - }) - .strict(); - -export type SearchSymbolsInput = z.infer; - -/** Server-side injected configuration for {@link createSearchSymbolsTool}. */ -export interface SearchSymbolsToolOptions { - readonly port: SymbolSearchPort; - readonly vaultContext: Pick; -} - -/** Structured JSON payload serialized into the `search_symbols` MCP text result. */ -export interface SearchSymbolsResultPayload { - readonly scope: 'vault_fenced'; - readonly vaultCutoffTs: number; - readonly rowCount: number; - readonly truncated: boolean; - readonly rows: readonly SymbolSearchRow[]; -} - -function isLeapYear(year: number): boolean { - return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; -} - -function daysInUtcMonth(year: number, monthIndex: number): number { - if (monthIndex === 1 && isLeapYear(year)) { - return 29; - } - return DAYS_IN_MONTH[monthIndex] ?? 0; -} - -function isValidCalendarDate(value: unknown): value is string { - if (typeof value !== 'string') { - return false; - } - const match = CALENDAR_DATE_RE.exec(value); - if (match === null) { - return false; - } - const year = Number(match[1]); - const month = Number(match[2]); - const day = Number(match[3]); - if (month < 1 || month > 12) { - return false; - } - return day >= 1 && day <= daysInUtcMonth(year, month - 1); -} - -function validateNullableDate(value: unknown, field: string): string | null { - if (value === null) { - return null; - } - if (!isValidCalendarDate(value)) { - throw new Error(`Invalid port date for "${field}".`); - } - return value; -} - -function validateNullableString(value: unknown, field: string): string | null { - if (value === null) { - return null; - } - if (typeof value !== 'string') { - throw new Error(`Invalid port string for "${field}".`); - } - return value; -} - -function validateRequiredString(value: unknown, field: string): string { - if (typeof value !== 'string') { - throw new Error(`Invalid port string for "${field}".`); - } - return value; -} - -function validateSafeInteger(value: unknown, field: string): number { - if (typeof value !== 'number' || !Number.isSafeInteger(value)) { - throw new Error(`Invalid port integer for "${field}".`); - } - return value; -} - -function fenceAndProjectRow( - raw: SymbolSearchRow, - vaultCutoffDate: string, - includeDelisted: boolean -): SymbolSearchRow | null { - if (typeof raw !== 'object' || raw === null) { - throw new Error('Invalid symbol search row returned by port.'); - } - - const listingId = validateSafeInteger(raw.listingId, 'listingId'); - const instrumentId = validateSafeInteger(raw.instrumentId, 'instrumentId'); - const ticker = validateRequiredString(raw.ticker, 'ticker'); - const classSuffix = validateNullableString(raw.classSuffix, 'classSuffix'); - const name = validateRequiredString(raw.name, 'name'); - const mic = validateRequiredString(raw.mic, 'mic'); - const currency = validateRequiredString(raw.currency, 'currency'); - const isin = validateNullableString(raw.isin, 'isin'); - const firstBarDate = validateNullableDate(raw.firstBarDate, 'firstBarDate'); - const rawLastBarDate = validateNullableDate(raw.lastBarDate, 'lastBarDate'); - const rawDelistedAt = validateNullableDate(raw.delistedAt, 'delistedAt'); - - if (firstBarDate !== null && firstBarDate > vaultCutoffDate) { - return null; - } - - const lastBarDate = - rawLastBarDate !== null && rawLastBarDate > vaultCutoffDate ? vaultCutoffDate : rawLastBarDate; - - const delistedAt = - rawDelistedAt !== null && rawDelistedAt > vaultCutoffDate ? null : rawDelistedAt; - - if (!includeDelisted && delistedAt !== null) { - return null; - } - - return { - listingId, - instrumentId, - ticker, - classSuffix, - name, - mic, - currency, - isin, - firstBarDate, - lastBarDate, - delistedAt, - }; -} - -function matchRank(row: SymbolSearchRow, normalizedQuery: string): number | null { - const normalizedTicker = row.ticker.toLowerCase(); - if (normalizedTicker === normalizedQuery) { - return 0; - } - if (normalizedTicker.startsWith(normalizedQuery)) { - return 1; - } - if (row.name.toLowerCase().includes(normalizedQuery)) { - return 2; - } - return null; -} - -function validateFactoryOptions(options: SearchSymbolsToolOptions): number { - if (typeof options !== 'object' || options === null) { - throw new MarketDataStoreValidationError( - 'Invalid `options`: expected a SearchSymbolsToolOptions object.', - 'options' - ); - } - - if ( - typeof options.port !== 'object' || - options.port === null || - typeof options.port.searchSymbols !== 'function' - ) { - throw new MarketDataStoreValidationError( - 'Invalid `port`: expected a SymbolSearchPort implementing `searchSymbols`.', - 'port' - ); - } - - return validateVaultCutoffTs(options.vaultContext?.vaultCutoffTs); -} - -/** - * Creates the Vault-fenced `search_symbols` MCP tool backed by an injected - * read-only {@link SymbolSearchPort}. - * - * Enforces `scope: 'vault_fenced'`, requests candidates with - * `includeDelisted: true` so current delisting status cannot hide listings that - * were active as of the Vault cutoff, drops post-cutoff listings, clamps - * `lastBarDate` and masks future `delistedAt` against the cutoff UTC calendar - * date, ranks deterministically (exact ticker > ticker prefix > company name, - * breaking ties by ascending `listingId`), and caps results at `limit`. - */ -export function createSearchSymbolsTool(options: SearchSymbolsToolOptions): McpToolEntry { - const vaultCutoffTs = validateFactoryOptions(options); - const vaultCutoffDate = utcDateOf(vaultCutoffTs); - const { port } = options; - - return defineMcpTool({ - name: 'search_symbols', - description: - 'Search Vault-fenced security-master listings by ticker symbol or company name and return numeric listing IDs.', - inputSchema: searchSymbolsInputSchema, - async handler(input: SearchSymbolsInput): Promise { - const candidates = await port.searchSymbols({ - query: input.query, - limit: input.limit, - ...(input.country !== undefined ? { country: input.country } : {}), - includeDelisted: true, - vaultCutoffTs, - }); - - if (!Array.isArray(candidates)) { - throw new Error('Invalid symbol search response returned by port.'); - } - - const normalizedQuery = input.query.toLowerCase(); - const eligible: { readonly row: SymbolSearchRow; readonly rank: number }[] = []; - - for (let i = 0; i < candidates.length; i += 1) { - const fenced = fenceAndProjectRow( - candidates[i] as SymbolSearchRow, - vaultCutoffDate, - input.includeDelisted - ); - if (fenced !== null) { - const rank = matchRank(fenced, normalizedQuery); - if (rank !== null) { - eligible.push({ row: fenced, rank }); - } - } - } - - eligible.sort((a, b) => { - if (a.rank !== b.rank) { - return a.rank - b.rank; - } - return a.row.listingId - b.row.listingId; - }); - - const truncated = eligible.length > input.limit; - const limitCount = truncated ? input.limit : eligible.length; - const rows: SymbolSearchRow[] = []; - for (let i = 0; i < limitCount; i += 1) { - rows.push((eligible[i] as { readonly row: SymbolSearchRow }).row); - } - - const payload: SearchSymbolsResultPayload = { - scope: 'vault_fenced', - vaultCutoffTs, - rowCount: rows.length, - truncated, - rows, - }; - - return { - content: [{ type: 'text', text: JSON.stringify(payload) }], - }; - }, - }); -} diff --git a/libs/research/src/mcp/tools/vault-fenced-input.ts b/libs/research/src/mcp/tools/vault-fenced-input.ts deleted file mode 100644 index 3eaa97c7..00000000 --- a/libs/research/src/mcp/tools/vault-fenced-input.ts +++ /dev/null @@ -1,341 +0,0 @@ -import { z } from 'zod'; -import { - type FencedTimeRange, - MarketDataStoreValidationError, - VaultHoldoutFenceError, - VaultScopeNotAuthorizedError, - applyVaultFence, -} from '../../market-data-store'; -import { - AdjFactorsSnapshotError, - type AdjFactorsSnapshotErrorCode, - MarketDataStoreNotImplementedError, -} from '../../market-data-store-duckdb'; -import type { McpToolCallResult } from '../protocol'; - -export const INT32_MIN = -2_147_483_648; -export const INT32_MAX = 2_147_483_647; -export const MAX_ECMASCRIPT_EPOCH_MS = 8_640_000_000_000_000; -export const MS_PER_DAY = 86_400_000; - -/** Hard maximum number of explicit `listingIds` accepted by Vault-fenced MCP tools. */ -export const MCP_MAX_LISTING_IDS = 500; - -const DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/; -const ISO_FRACTIONAL_RE = /\.(\d+)(?:Z|[+-]\d{2}:\d{2})$/; - -export const EXCLUSIVE_LISTING_SELECTOR_MESSAGE = - 'Exactly one of "listingIds" or "universe" must be provided.'; - -/** Returns true when exactly one of `listingIds` or `universe` is supplied. */ -export function hasExclusiveListingSelector(data: { - readonly listingIds?: readonly number[]; - readonly universe?: string; -}): boolean { - return (data.listingIds !== undefined) !== (data.universe !== undefined); -} - -/** Shared Zod field schema for explicit INT32 `listingIds` (1–500). */ -export function createListingIdsFieldSchema(description: string) { - return z - .array(z.number().int().min(INT32_MIN).max(INT32_MAX)) - .min(1) - .max(MCP_MAX_LISTING_IDS) - .optional() - .describe(description); -} - -/** Shared Zod field schema for a named `universe` reference. */ -export function createUniverseFieldSchema(description: string) { - return z.string().min(1).optional().describe(description); -} - -/** - * Validates that a raw string is a valid calendar date (`YYYY-MM-DD`) or - * UTC ISO-8601 timestamp with an explicit timezone offset (`Z` or `±HH:MM`). - */ -export function isValidUtcBoundString(raw: string): boolean { - try { - applyVaultFence( - { from: raw, to: raw, scope: 'vault_evaluation_only' }, - { vaultCutoffTs: 0, vaultOperatorAuthorized: true } - ); - return true; - } catch { - return false; - } -} - -/** Validates an injected server-side `vaultCutoffTs` epoch-ms boundary. */ -export function validateVaultCutoffTs(cutoffTs: unknown): number { - if ( - typeof cutoffTs !== 'number' || - !Number.isFinite(cutoffTs) || - !Number.isSafeInteger(cutoffTs) || - Math.abs(cutoffTs) >= MAX_ECMASCRIPT_EPOCH_MS - ) { - throw new MarketDataStoreValidationError( - `Invalid \`vaultContext.vaultCutoffTs\`: ${String(cutoffTs)}.`, - 'vaultCutoffTs' - ); - } - return cutoffTs; -} - -/** Returns the UTC calendar date (`YYYY-MM-DD`) for an epoch-ms timestamp. */ -export function utcDateOf(epochMs: number): string { - return new Date(epochMs).toISOString().slice(0, 10); -} - -export function extractExplicitSubMsMicros(raw: string): number { - const match = ISO_FRACTIONAL_RE.exec(raw); - if (match === null) { - return 0; - } - const frac = match[1] ?? ''; - if (frac.length <= 3) { - return 0; - } - const microDigits = frac.slice(3, 6).padEnd(3, '0'); - return Number(microDigits); -} - -export function resolveFromSubMsMicros(rawFrom: string): number { - if (DATE_ONLY_RE.test(rawFrom)) { - return 0; - } - return extractExplicitSubMsMicros(rawFrom); -} - -export function resolveToSubMsMicros(rawTo: string, clampedTo: boolean): number { - if (clampedTo || DATE_ONLY_RE.test(rawTo)) { - return 999; - } - return extractExplicitSubMsMicros(rawTo); -} - -export function resolveAsOfSubMsMicros(rawAsOf: string | undefined, clampedAsOf: boolean): number { - if (clampedAsOf || rawAsOf === undefined || DATE_ONLY_RE.test(rawAsOf)) { - return 999; - } - return extractExplicitSubMsMicros(rawAsOf); -} - -export function formatUtcIsoWithMicros(epochMs: number, subMsMicros: number): string { - const isoMs = new Date(epochMs).toISOString(); - if (subMsMicros === 0) { - return isoMs; - } - const extra = String(subMsMicros).padStart(3, '0'); - return `${isoMs.slice(0, -1)}${extra}Z`; -} - -/** - * Resolves the latest completed UTC calendar date at or before `(epochMs, subMsMicros)`. - * A full day is completed only at `23:59:59.999999Z`; any earlier instant resolves - * to the preceding UTC calendar date. - */ -export function resolveCompletedUtcDate(epochMs: number, subMsMicros: number): string { - const dayStartMs = Math.floor(epochMs / MS_PER_DAY) * MS_PER_DAY; - const dayEndMs = dayStartMs + MS_PER_DAY - 1; - if (epochMs === dayEndMs && subMsMicros === 999) { - return utcDateOf(dayStartMs); - } - return utcDateOf(dayStartMs - MS_PER_DAY); -} - -/** - * Resolves the completed UTC date at `min(effectiveTo, effectiveAsOf)` for point-in-time - * universe resolution in `query_data`. - */ -export function resolveUniverseDate( - toMs: number, - toSubMs: number, - asOfMs: number, - asOfSubMs: number -): string { - if (asOfMs < toMs || (asOfMs === toMs && asOfSubMs < toSubMs)) { - return resolveCompletedUtcDate(asOfMs, asOfSubMs); - } - return resolveCompletedUtcDate(toMs, toSubMs); -} - -/** - * Resolves a fixed pre-study cohort date: the latest completed UTC date strictly - * before the study start (`fromMs`) and no later than effective `asOf`. - */ -export function resolvePreStartUniverseDate( - fromMs: number, - asOfMs: number, - asOfSubMs: number -): string { - const fromDayStartMs = Math.floor(fromMs / MS_PER_DAY) * MS_PER_DAY; - const preStartDate = utcDateOf(fromDayStartMs - MS_PER_DAY); - const asOfCompletedDate = resolveCompletedUtcDate(asOfMs, asOfSubMs); - return asOfCompletedDate < preStartDate ? asOfCompletedDate : preStartDate; -} - -/** Result of fencing MCP query bounds against the server-injected Vault cutoff. */ -export interface VaultFencedBounds extends FencedTimeRange { - readonly vaultCutoffDate: string; - readonly fromSubMs: number; - readonly toSubMs: number; - readonly asOfSubMs: number; - readonly canonicalFrom: string; - readonly canonicalTo: string; - readonly canonicalAsOf: string; - readonly effectiveFencedTo: string; - readonly effectiveFencedAsOf: string; -} - -/** - * Runs {@link applyVaultFence} under `scope: 'vault_fenced'` with - * `vaultOperatorAuthorized: false` and computes microsecond-preserving effective - * `to` / `asOf` query strings. - */ -export function fenceVaultQueryBounds( - input: { readonly from: string; readonly to: string; readonly asOf?: string }, - vaultCutoffTs: number -): VaultFencedBounds { - const fenced = applyVaultFence( - { - from: input.from, - to: input.to, - asOf: input.asOf, - scope: 'vault_fenced', - }, - { - vaultCutoffTs, - vaultOperatorAuthorized: false, - } - ); - - const fromSubMs = resolveFromSubMsMicros(input.from); - const toSubMs = resolveToSubMsMicros(input.to, fenced.clampedTo); - const asOfSubMs = resolveAsOfSubMsMicros(input.asOf, fenced.clampedAsOf); - const canonicalFrom = formatUtcIsoWithMicros(fenced.fromMs, fromSubMs); - const canonicalTo = formatUtcIsoWithMicros(fenced.toMs, toSubMs); - const canonicalAsOf = formatUtcIsoWithMicros(fenced.asOfMs, asOfSubMs); - const effectiveFencedTo = fenced.clampedTo - ? formatUtcIsoWithMicros(fenced.toMs, 999) - : input.to; - const effectiveFencedAsOf = - fenced.clampedAsOf || input.asOf === undefined - ? formatUtcIsoWithMicros(fenced.asOfMs, 999) - : input.asOf; - - return { - ...fenced, - vaultCutoffDate: utcDateOf(vaultCutoffTs), - fromSubMs, - toSubMs, - asOfSubMs, - canonicalFrom, - canonicalTo, - canonicalAsOf, - effectiveFencedTo, - effectiveFencedAsOf, - }; -} - -const SAFE_VALIDATION_FIELDS: ReadonlySet = new Set([ - 'from', - 'to', - 'asOf', - 'date', - 'ref', - 'listingIds', - 'timeframe', - 'adjustment', - 'scope', - 'limit', -]); - -const SAFE_STORE_METHODS: ReadonlySet = new Set([ - 'bars', - 'crossSection', - 'fundamentalsAsOf', - 'events', - 'shortsAsOf', - 'macroAsOf', - 'fx', - 'universe', -]); - -const ADJ_SNAPSHOT_ERROR_MESSAGES: Readonly> = { - missing_snapshot: - 'Adjusted bars require a verified point-in-time fenced adj_factors snapshot.', - missing_metadata: 'Required adj_factors snapshot metadata is missing.', - invalid_metadata: 'adj_factors snapshot metadata is invalid.', - unsupported_version: 'adj_factors snapshot metadata version is unsupported.', - retrospective_rejected: - 'Retrospective adj_factors snapshots are rejected for point-in-time queries.', - incompatible_fence: - 'adj_factors snapshot fence does not match the query asOf or Vault cutoff.', - path_mismatch: 'adj_factors snapshot metadata does not match the configured artifact.', - unpinned_mutable_path: - 'Adjusted bars require a pinned or immutable adj_factors snapshot artifact.', -}; - -/** - * Maps known `MarketDataStore` / Vault domain errors to fixed, sanitized - * `isError: true` MCP tool results without leaking SQL, file paths, or URIs. - */ -export function formatMappedStoreError(err: unknown): McpToolCallResult | null { - if (err instanceof VaultHoldoutFenceError) { - return { - content: [ - { - type: 'text', - text: 'VaultHoldoutFenceError: Requested range reaches or exceeds the Vault holdout cutoff.', - }, - ], - isError: true, - }; - } - - if (err instanceof VaultScopeNotAuthorizedError) { - return { - content: [ - { - type: 'text', - text: "VaultScopeNotAuthorizedError: Data scope 'vault_evaluation_only' is not permitted through MCP.", - }, - ], - isError: true, - }; - } - - if (err instanceof MarketDataStoreValidationError) { - const text = - err.field !== undefined && SAFE_VALIDATION_FIELDS.has(err.field) - ? `MarketDataStoreValidationError: Invalid query parameter "${err.field}".` - : 'MarketDataStoreValidationError: Query parameters failed store validation.'; - return { - content: [{ type: 'text', text }], - isError: true, - }; - } - - if (err instanceof MarketDataStoreNotImplementedError) { - const text = SAFE_STORE_METHODS.has(err.method) - ? `MarketDataStoreNotImplementedError: Store operation "${err.method}" is not supported for this query.` - : 'MarketDataStoreNotImplementedError: Requested store operation is not supported.'; - return { - content: [{ type: 'text', text }], - isError: true, - }; - } - - if (err instanceof AdjFactorsSnapshotError) { - const detail = Object.prototype.hasOwnProperty.call(ADJ_SNAPSHOT_ERROR_MESSAGES, err.code) - ? ADJ_SNAPSHOT_ERROR_MESSAGES[err.code] - : 'Adjusted bars snapshot verification failed.'; - return { - content: [{ type: 'text', text: `AdjFactorsSnapshotError: ${detail}` }], - isError: true, - }; - } - - return null; -} diff --git a/libs/research/src/notebook-snapshot-node.ts b/libs/research/src/notebook-snapshot-node.ts deleted file mode 100644 index d6ebd9bc..00000000 --- a/libs/research/src/notebook-snapshot-node.ts +++ /dev/null @@ -1,293 +0,0 @@ -/** - * Node/Bun subprocess and filesystem adapters for {@link exportNotebookSnapshot}. - * - * Intentionally exposed only via the `@stock-bot/research/notebook-snapshot-node` - * subpath (never re-exported from `@stock-bot/research`) so the root package - * stays browser-bundleable. - */ - -import { spawn } from 'node:child_process'; -import { rename as fsRename, stat as fsStat, open, readFile, rm } from 'node:fs/promises'; -import { basename } from 'node:path'; -import type { - NotebookCommandResult, - NotebookCommandRunner, - NotebookCommandRunOptions, - NotebookSnapshotFileStat, - NotebookSnapshotFs, -} from './notebook-snapshot'; - -/** Default per-stream (stdout / stderr) capture cap in bytes (16 MiB). */ -export const NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES = 16 * 1024 * 1024; - -/** Maximum single-call delay supported by Node/Bun `setTimeout` (2^31 - 1 ms). */ -const MAX_TIMER_DELAY_MS = 2_147_483_647; - -export interface NodeNotebookCommandRunnerOptions { - /** Maximum captured bytes per stream (stdout and stderr independently). */ - readonly maxOutputBytes?: number; -} - -interface CodedError extends Error { - code: string; -} - -function createCodedError(code: string, message: string): CodedError { - const err = new Error(message) as CodedError; - err.code = code; - return err; -} - -function getErrorCode(err: unknown): string | undefined { - if (typeof err === 'object' && err !== null && 'code' in err) { - const code = (err as { code?: unknown }).code; - if (typeof code === 'string') { - return code; - } - } - return undefined; -} - -function assertPositiveSafeInteger(value: unknown, label: string): number { - if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) { - throw new RangeError(`${label} must be a positive finite integer.`); - } - return value; -} - -/** - * Creates a real {@link NotebookCommandRunner} backed by `node:child_process.spawn`. - * - * - Always invokes `command` directly with `args` as argv (`shell: false`). - * - Resolves any numeric exit code on `close`; rejects on spawn errors, signal - * termination, timeout (`ETIMEDOUT`), or per-stream output overflow (`EOUTPUTLIMIT`). - * - On timeout or output overflow, sends `SIGKILL` once and rejects only after - * the child's `close` event has fired. - */ -export function createNodeNotebookCommandRunner( - runnerOptions?: NodeNotebookCommandRunnerOptions -): NotebookCommandRunner { - const maxOutputBytes = - runnerOptions?.maxOutputBytes === undefined - ? NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES - : assertPositiveSafeInteger(runnerOptions.maxOutputBytes, 'maxOutputBytes'); - - return { - run( - command: string, - args: readonly string[], - options: NotebookCommandRunOptions - ): Promise { - let timeoutMs: number; - try { - timeoutMs = assertPositiveSafeInteger(options.timeoutMs, 'timeoutMs'); - } catch (err) { - return Promise.reject(err); - } - - const commandName = basename(command) || command; - - return new Promise((resolve, reject) => { - let settled = false; - let terminalFailure: CodedError | null = null; - let killSent = false; - let timeoutHandle: ReturnType | undefined; - - const stdoutChunks: Buffer[] = []; - let stdoutBytes = 0; - const stderrChunks: Buffer[] = []; - let stderrBytes = 0; - - const clearTimeoutHandle = (): void => { - if (timeoutHandle !== undefined) { - clearTimeout(timeoutHandle); - timeoutHandle = undefined; - } - }; - - let child: ReturnType; - try { - child = spawn(command, [...args], { - ...(options.cwd !== undefined ? { cwd: options.cwd } : {}), - shell: false, - stdio: ['ignore', 'pipe', 'pipe'], - }); - } catch (err) { - settled = true; - reject(err); - return; - } - - const triggerTerminalFailure = (err: CodedError): void => { - if (settled || terminalFailure !== null) { - return; - } - terminalFailure = err; - clearTimeoutHandle(); - stdoutChunks.length = 0; - stderrChunks.length = 0; - if (!killSent) { - killSent = true; - try { - child.kill('SIGKILL'); - } catch { - // Child may have already exited before kill was delivered. - } - } - // Tear down our read ends of stdout/stderr so a descendant that - // inherited either pipe cannot prevent `child`'s `close` event from - // firing once the direct child exits. - child.stdout?.destroy(); - child.stderr?.destroy(); - }; - - const attachStreamCollector = ( - stream: NodeJS.ReadableStream | null, - streamName: 'stdout' | 'stderr', - chunks: Buffer[], - getBytes: () => number, - setBytes: (next: number) => void - ): void => { - if (!stream) { - return; - } - stream.on('error', () => { - // Drain/ignore pipe errors once the child is terminating. - }); - stream.on('data', (chunk: Buffer | string) => { - if (terminalFailure !== null || settled) { - // Keep draining so a killed/exiting child never blocks on a full pipe. - return; - } - const buf = typeof chunk === 'string' ? Buffer.from(chunk, 'utf8') : chunk; - const nextBytes = getBytes() + buf.byteLength; - if (nextBytes > maxOutputBytes) { - triggerTerminalFailure( - createCodedError( - 'EOUTPUTLIMIT', - `Command '${commandName}' exceeded ${streamName} output limit of ${maxOutputBytes} bytes.` - ) - ); - return; - } - setBytes(nextBytes); - chunks.push(buf); - }); - }; - - attachStreamCollector( - child.stdout, - 'stdout', - stdoutChunks, - () => stdoutBytes, - next => { - stdoutBytes = next; - } - ); - attachStreamCollector( - child.stderr, - 'stderr', - stderrChunks, - () => stderrBytes, - next => { - stderrBytes = next; - } - ); - - const deadlineMs = performance.now() + timeoutMs; - const scheduleTimeout = (): void => { - if (settled || terminalFailure !== null) { - return; - } - const remainingMs = deadlineMs - performance.now(); - if (remainingMs <= 0) { - triggerTerminalFailure( - createCodedError( - 'ETIMEDOUT', - `Command '${commandName}' timed out after ${timeoutMs}ms.` - ) - ); - return; - } - const delayMs = Math.min(Math.ceil(remainingMs), MAX_TIMER_DELAY_MS); - timeoutHandle = setTimeout(scheduleTimeout, delayMs); - }; - scheduleTimeout(); - - child.once('error', err => { - clearTimeoutHandle(); - if (settled) { - return; - } - settled = true; - reject(err); - }); - - child.once('close', (code, signal) => { - clearTimeoutHandle(); - if (settled) { - return; - } - settled = true; - - if (terminalFailure !== null) { - reject(terminalFailure); - return; - } - - if (code === null) { - reject( - new Error( - signal - ? `Command '${commandName}' terminated by signal ${signal}.` - : `Command '${commandName}' terminated without an exit code.` - ) - ); - return; - } - - const stdout = Buffer.concat(stdoutChunks, stdoutBytes).toString('utf8'); - const stderr = Buffer.concat(stderrChunks, stderrBytes).toString('utf8'); - resolve({ exitCode: code, stdout, stderr }); - }); - }); - }, - }; -} - -/** - * Creates a real {@link NotebookSnapshotFs} backed by `node:fs/promises`. - */ -export function createNodeNotebookSnapshotFs(): NotebookSnapshotFs { - return { - async stat(path: string): Promise { - try { - const info = await fsStat(path); - return { isFile: info.isFile(), size: info.size }; - } catch (err) { - if (getErrorCode(err) === 'ENOENT') { - return null; - } - throw err; - } - }, - - async createExclusive(path: string): Promise { - const handle = await open(path, 'wx'); - await handle.close(); - }, - - async readBytes(path: string): Promise { - const data = await readFile(path); - return new Uint8Array(data.buffer, data.byteOffset, data.byteLength); - }, - - async rename(sourcePath: string, destinationPath: string): Promise { - await fsRename(sourcePath, destinationPath); - }, - - async remove(path: string): Promise { - await rm(path, { force: true }); - }, - }; -} diff --git a/libs/research/src/notebook-snapshot.ts b/libs/research/src/notebook-snapshot.ts deleted file mode 100644 index f6af2521..00000000 --- a/libs/research/src/notebook-snapshot.ts +++ /dev/null @@ -1,804 +0,0 @@ -/** - * `marimo check`-gated static HTML snapshot exporter for research notebooks. - * - * Enforces the D9 rule (`design/PLATFORM-PLAN.md`): a notebook must pass - * `marimo check --format=json` with zero errors before `marimo export html` - * runs, and exported HTML is published atomically via a sibling temp file. - * - * All subprocess execution and filesystem access are injected via ports - * (`NotebookCommandRunner`, `NotebookSnapshotFs`). `node:crypto` is loaded - * lazily at call time so `@stock-bot/research` remains browser-bundleable. - * - * Command flags and JSON diagnostic shape are confirmed against marimo 0.26.0 - * (pinned in `python/uv.lock`). - */ - -export const DEFAULT_MARIMO_COMMAND = 'marimo'; -export const DEFAULT_NOTEBOOK_SNAPSHOT_TIMEOUT_MS = 120_000; - -const MAX_TEMP_RESERVATION_ATTEMPTS = 16; -let tempSequence = 0; - -/** Stable machine-readable error codes thrown by {@link NotebookSnapshotError}. */ -export type NotebookSnapshotErrorCode = - | 'INVALID_OPTION' - | 'INVALID_PATH' - | 'NOTEBOOK_NOT_FOUND' - | 'CHECK_FAILED' - | 'CHECK_OUTPUT_INVALID' - | 'EXPORT_FAILED' - | 'EXPORT_EMPTY' - | 'TIMEOUT'; - -export interface NotebookSnapshotErrorOptions { - readonly details?: unknown; - readonly cause?: unknown; -} - -/** Typed fail-closed error thrown by {@link exportNotebookSnapshot}. */ -export class NotebookSnapshotError extends Error { - readonly code: NotebookSnapshotErrorCode; - readonly details?: unknown; - override readonly cause?: unknown; - - constructor( - code: NotebookSnapshotErrorCode, - message: string, - options?: NotebookSnapshotErrorOptions - ) { - super(message); - this.name = 'NotebookSnapshotError'; - this.code = code; - if (options && 'details' in options) { - this.details = options.details; - } - if (options && 'cause' in options) { - this.cause = options.cause; - } - Object.setPrototypeOf(this, new.target.prototype); - } -} - -export interface NotebookCommandRunOptions { - readonly cwd?: string; - readonly timeoutMs: number; -} - -export interface NotebookCommandResult { - readonly exitCode: number; - readonly stdout: string; - readonly stderr: string; -} - -/** - * Injected command-runner port. - * - * Implementations MUST execute `command` directly with `args` as an argv array - * (never via a shell string or shell interpolation). - * - * Timeout contract: on timeout, implementations MUST terminate the subprocess - * and settle (rejecting with an error carrying `code: 'ETIMEDOUT'`) only after - * the process has exited and stopped writing to disk. - */ -export interface NotebookCommandRunner { - run( - command: string, - args: readonly string[], - options: NotebookCommandRunOptions - ): Promise; -} - -export interface NotebookSnapshotFileStat { - readonly isFile: boolean; - readonly size: number; -} - -/** - * Minimal injected filesystem port for {@link exportNotebookSnapshot}. - */ -export interface NotebookSnapshotFs { - /** Returns file metadata for `path`, or `null` when `path` does not exist. */ - stat(path: string): Promise; - /** - * Exclusively creates an empty file at `path` (`O_CREAT | O_EXCL`). - * MUST throw an error carrying `code: 'EEXIST'` if `path` already exists. - */ - createExclusive(path: string): Promise; - /** Reads the complete byte contents of `path`. */ - readBytes(path: string): Promise; - /** Atomically replaces `destinationPath` with `sourcePath`. */ - rename(sourcePath: string, destinationPath: string): Promise; - /** Idempotently removes `path` (succeeds as a no-op if already absent). */ - remove(path: string): Promise; -} - -/** Parsed marimo 0.26.0 `marimo check --format=json` summary object. */ -export interface MarimoCheckSummary { - readonly errored: boolean; - readonly total_files: number; - readonly [key: string]: unknown; -} - -/** Parsed marimo 0.26.0 `marimo check --format=json` report object. */ -export interface MarimoCheckReport { - readonly issues: readonly Readonly>[]; - readonly summary: MarimoCheckSummary; - readonly [key: string]: unknown; -} - -export interface ExportNotebookSnapshotOptions { - readonly notebookPath: string; - readonly outputPath: string; - readonly runner: NotebookCommandRunner; - readonly fs: NotebookSnapshotFs; - /** Executable name or path for marimo (default `'marimo'`). */ - readonly marimoCommand?: string; - /** Per-command timeout in milliseconds (default `120_000`). */ - readonly timeoutMs?: number; - /** Optional working directory passed to `runner.run`. */ - readonly cwd?: string; - /** Optional absolute root directory that `notebookPath` must lexically reside within. */ - readonly allowedNotebookRoot?: string; - /** Optional absolute root directory that `outputPath` must lexically reside within. */ - readonly allowedOutputRoot?: string; -} - -/** Frozen receipt returned when a notebook snapshot is cleanly checked and published. */ -export interface NotebookSnapshotReceipt { - readonly notebookPath: string; - readonly outputPath: string; - readonly bytes: number; - readonly sha256: string; - readonly checkDiagnostics: MarimoCheckReport | null; -} - -function isPlainObject(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value); -} - -function getErrorCode(err: unknown): string | undefined { - if (typeof err === 'object' && err !== null && 'code' in err) { - const code = (err as { code?: unknown }).code; - if (typeof code === 'string') { - return code; - } - } - return undefined; -} - -function normalizePosixAbsolutePath(rawPath: string): string { - const segments = rawPath.split('/'); - const stack: string[] = []; - for (let i = 0; i < segments.length; i += 1) { - const seg = segments[i]; - if (seg === undefined || seg === '' || seg === '.') { - continue; - } - if (seg === '..') { - if (stack.length > 0) { - stack.pop(); - } - continue; - } - stack.push(seg); - } - return `/${stack.join('/')}`; -} - -function validateAbsolutePath( - rawPath: unknown, - label: string, - options?: { readonly requiredExtension?: string } -): string { - if (typeof rawPath !== 'string' || rawPath.length === 0) { - throw new NotebookSnapshotError( - 'INVALID_PATH', - `Invalid ${label}: expected a non-empty string.` - ); - } - if (rawPath.includes('\0')) { - throw new NotebookSnapshotError('INVALID_PATH', `Invalid ${label}: NUL bytes are not allowed.`); - } - if (rawPath.startsWith('-')) { - throw new NotebookSnapshotError( - 'INVALID_PATH', - `Invalid ${label}: path must not start with '-'.` - ); - } - if (!rawPath.startsWith('/')) { - throw new NotebookSnapshotError( - 'INVALID_PATH', - `Invalid ${label}: path must be an absolute POSIX path.` - ); - } - - if (options?.requiredExtension !== undefined) { - if (rawPath.endsWith('/')) { - throw new NotebookSnapshotError( - 'INVALID_PATH', - `Invalid ${label}: path must reference a ${options.requiredExtension} file, not a directory.` - ); - } - } - - const normalized = normalizePosixAbsolutePath(rawPath); - - if (options?.requiredExtension !== undefined) { - const ext = options.requiredExtension; - if (!normalized.endsWith(ext) || normalized === `/${ext}` || normalized.endsWith(`/${ext}`)) { - throw new NotebookSnapshotError( - 'INVALID_PATH', - `Invalid ${label}: path must end with '${ext}'.` - ); - } - } - - return normalized; -} - -function assertWithinRoot( - normalizedPath: string, - rawRoot: unknown, - pathLabel: string, - rootLabel: string -): void { - const normalizedRoot = validateAbsolutePath(rawRoot, rootLabel); - if (normalizedRoot === '/') { - return; - } - const requiredPrefix = `${normalizedRoot}/`; - if (!normalizedPath.startsWith(requiredPrefix)) { - throw new NotebookSnapshotError( - 'INVALID_PATH', - `Invalid ${pathLabel}: resolved path '${normalizedPath}' escapes ${rootLabel} '${normalizedRoot}'.` - ); - } -} - -function dirnamePosix(normalizedFilePath: string): string { - const lastSlash = normalizedFilePath.lastIndexOf('/'); - return lastSlash <= 0 ? '/' : normalizedFilePath.slice(0, lastSlash); -} - -function validatePortsAndOptions(options: ExportNotebookSnapshotOptions): { - readonly notebookPath: string; - readonly outputPath: string; - readonly runner: NotebookCommandRunner; - readonly fs: NotebookSnapshotFs; - readonly marimoCommand: string; - readonly timeoutMs: number; - readonly cwd?: string; -} { - if (!isPlainObject(options)) { - throw new NotebookSnapshotError('INVALID_OPTION', 'Invalid options: expected an object.'); - } - - const { runner, fs } = options; - if (!isPlainObject(runner) || typeof runner.run !== 'function') { - throw new NotebookSnapshotError( - 'INVALID_OPTION', - 'Invalid runner: expected an object with a callable run(command, args, options) method.' - ); - } - if ( - !isPlainObject(fs) || - typeof fs.stat !== 'function' || - typeof fs.createExclusive !== 'function' || - typeof fs.readBytes !== 'function' || - typeof fs.rename !== 'function' || - typeof fs.remove !== 'function' - ) { - throw new NotebookSnapshotError( - 'INVALID_OPTION', - 'Invalid fs: expected an object implementing stat, createExclusive, readBytes, rename, and remove.' - ); - } - - const marimoCommand = - options.marimoCommand === undefined ? DEFAULT_MARIMO_COMMAND : options.marimoCommand; - if ( - typeof marimoCommand !== 'string' || - marimoCommand.trim().length === 0 || - marimoCommand.includes('\0') || - marimoCommand.startsWith('-') - ) { - throw new NotebookSnapshotError( - 'INVALID_OPTION', - 'Invalid marimoCommand: expected a non-empty command name or path without NUL bytes or leading "-".' - ); - } - - const timeoutMs = - options.timeoutMs === undefined ? DEFAULT_NOTEBOOK_SNAPSHOT_TIMEOUT_MS : options.timeoutMs; - if (typeof timeoutMs !== 'number' || !Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) { - throw new NotebookSnapshotError( - 'INVALID_OPTION', - 'Invalid timeoutMs: expected a positive safe integer.' - ); - } - - const notebookPath = validateAbsolutePath(options.notebookPath, 'notebookPath', { - requiredExtension: '.py', - }); - const outputPath = validateAbsolutePath(options.outputPath, 'outputPath', { - requiredExtension: '.html', - }); - - if (options.allowedNotebookRoot !== undefined) { - assertWithinRoot( - notebookPath, - options.allowedNotebookRoot, - 'notebookPath', - 'allowedNotebookRoot' - ); - } - if (options.allowedOutputRoot !== undefined) { - assertWithinRoot(outputPath, options.allowedOutputRoot, 'outputPath', 'allowedOutputRoot'); - } - - let cwd: string | undefined; - if (options.cwd !== undefined) { - cwd = validateAbsolutePath(options.cwd, 'cwd'); - } - - return { - notebookPath, - outputPath, - runner, - fs, - marimoCommand, - timeoutMs, - ...(cwd !== undefined ? { cwd } : {}), - }; -} - -function validateCommandResult(result: unknown, phase: 'check' | 'export'): NotebookCommandResult { - if ( - !isPlainObject(result) || - typeof result.exitCode !== 'number' || - !Number.isSafeInteger(result.exitCode) || - typeof result.stdout !== 'string' || - typeof result.stderr !== 'string' - ) { - throw new NotebookSnapshotError( - phase === 'check' ? 'CHECK_FAILED' : 'EXPORT_FAILED', - `Invalid runner result for marimo ${phase}: expected { exitCode, stdout, stderr }.` - ); - } - return { - exitCode: result.exitCode, - stdout: result.stdout, - stderr: result.stderr, - }; -} - -function issueHasBlockingError(issue: Record): boolean { - if (issue.type === 'error' || issue.severity === 'breaking') { - return true; - } - const nested = issue.diagnostics; - if (Array.isArray(nested)) { - for (let i = 0; i < nested.length; i += 1) { - const diag = nested[i]; - if (isPlainObject(diag) && (diag.type === 'error' || diag.severity === 'breaking')) { - return true; - } - } - } - return false; -} - -function parseAndValidateCheckReport(parsed: unknown): { - readonly report: MarimoCheckReport; - readonly hasBlockingError: boolean; -} { - if (!isPlainObject(parsed)) { - throw new NotebookSnapshotError( - 'CHECK_OUTPUT_INVALID', - 'marimo check JSON output must be an object with { issues, summary }.' - ); - } - - const { issues, summary } = parsed; - if (!Array.isArray(issues) || !isPlainObject(summary)) { - throw new NotebookSnapshotError( - 'CHECK_OUTPUT_INVALID', - 'marimo check JSON output must contain an issues array and a summary object.' - ); - } - - if ( - typeof summary.errored !== 'boolean' || - typeof summary.total_files !== 'number' || - !Number.isSafeInteger(summary.total_files) - ) { - throw new NotebookSnapshotError( - 'CHECK_OUTPUT_INVALID', - 'marimo check summary must include boolean errored and integer total_files.' - ); - } - - if (summary.total_files !== 1) { - throw new NotebookSnapshotError( - 'CHECK_OUTPUT_INVALID', - `marimo check reported summary.total_files=${summary.total_files}; expected exactly 1 checked file.`, - { details: { diagnostics: parsed } } - ); - } - - let hasBlockingError = summary.errored; - - for (let i = 0; i < issues.length; i += 1) { - const issue = issues[i]; - if (!isPlainObject(issue)) { - throw new NotebookSnapshotError( - 'CHECK_OUTPUT_INVALID', - `marimo check issues[${i}] must be an object.`, - { details: { diagnostics: parsed } } - ); - } - if (issue.type !== undefined && typeof issue.type !== 'string') { - throw new NotebookSnapshotError( - 'CHECK_OUTPUT_INVALID', - `marimo check issues[${i}].type must be a string when present.`, - { details: { diagnostics: parsed } } - ); - } - if (issue.severity !== undefined && typeof issue.severity !== 'string') { - throw new NotebookSnapshotError( - 'CHECK_OUTPUT_INVALID', - `marimo check issues[${i}].severity must be a string when present.`, - { details: { diagnostics: parsed } } - ); - } - if (issue.diagnostics !== undefined) { - if (!Array.isArray(issue.diagnostics)) { - throw new NotebookSnapshotError( - 'CHECK_OUTPUT_INVALID', - `marimo check issues[${i}].diagnostics must be an array when present.`, - { details: { diagnostics: parsed } } - ); - } - for (let j = 0; j < issue.diagnostics.length; j += 1) { - const diag = issue.diagnostics[j]; - if (!isPlainObject(diag)) { - throw new NotebookSnapshotError( - 'CHECK_OUTPUT_INVALID', - `marimo check issues[${i}].diagnostics[${j}] must be an object.`, - { details: { diagnostics: parsed } } - ); - } - if (diag.type !== undefined && typeof diag.type !== 'string') { - throw new NotebookSnapshotError( - 'CHECK_OUTPUT_INVALID', - `marimo check issues[${i}].diagnostics[${j}].type must be a string when present.`, - { details: { diagnostics: parsed } } - ); - } - if (diag.severity !== undefined && typeof diag.severity !== 'string') { - throw new NotebookSnapshotError( - 'CHECK_OUTPUT_INVALID', - `marimo check issues[${i}].diagnostics[${j}].severity must be a string when present.`, - { details: { diagnostics: parsed } } - ); - } - } - } - - if (issueHasBlockingError(issue)) { - hasBlockingError = true; - } - } - - return { - report: parsed as MarimoCheckReport, - hasBlockingError, - }; -} - -function deepFreeze(value: T): T { - if (typeof value !== 'object' || value === null || Object.isFrozen(value)) { - return value; - } - if (Array.isArray(value)) { - for (let i = 0; i < value.length; i += 1) { - deepFreeze(value[i]); - } - return Object.freeze(value); - } - const record = value as Record; - const keys = Object.keys(record); - for (let i = 0; i < keys.length; i += 1) { - const key = keys[i] as string; - deepFreeze(record[key]); - } - return Object.freeze(value); -} - -function generateTempToken(): string { - tempSequence += 1; - const randomPart = - typeof globalThis.crypto !== 'undefined' && typeof globalThis.crypto.randomUUID === 'function' - ? globalThis.crypto.randomUUID().replace(/-/g, '') - : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`; - return `${tempSequence}-${randomPart}`; -} - -async function reserveSiblingTempHtml(fs: NotebookSnapshotFs, outputPath: string): Promise { - const dir = dirnamePosix(outputPath); - const dirPrefix = dir === '/' ? '' : dir; - - for (let attempt = 0; attempt < MAX_TEMP_RESERVATION_ATTEMPTS; attempt += 1) { - const candidate = `${dirPrefix}/.marimo-snapshot-${generateTempToken()}.tmp.html`; - try { - await fs.createExclusive(candidate); - return candidate; - } catch (err) { - if (getErrorCode(err) === 'EEXIST') { - continue; - } - throw new NotebookSnapshotError( - 'EXPORT_FAILED', - `Failed to reserve temporary HTML sibling for '${outputPath}'.`, - { cause: err } - ); - } - } - - throw new NotebookSnapshotError( - 'EXPORT_FAILED', - `Failed to reserve a unique temporary HTML sibling for '${outputPath}' after ${MAX_TEMP_RESERVATION_ATTEMPTS} attempts.` - ); -} - -async function sha256HexNodeCrypto(bytes: Uint8Array): Promise { - // Keep the Node built-in specifier non-literal so browser bundlers do not try - // to statically resolve `node:crypto` when bundling `@stock-bot/research`. - const cryptoSpecifier = 'node:crypto'; - const nodeCrypto = (await import(cryptoSpecifier)) as typeof import('node:crypto'); - return nodeCrypto.createHash('sha256').update(bytes).digest('hex'); -} - -async function runPhaseCommand( - runner: NotebookCommandRunner, - command: string, - args: readonly string[], - runOptions: NotebookCommandRunOptions, - phase: 'check' | 'export' -): Promise { - let rawResult: unknown; - try { - rawResult = await runner.run(command, args, runOptions); - } catch (err) { - if (getErrorCode(err) === 'ETIMEDOUT') { - throw new NotebookSnapshotError( - 'TIMEOUT', - `marimo ${phase} timed out after ${runOptions.timeoutMs}ms.`, - { cause: err, details: { phase, timeoutMs: runOptions.timeoutMs } } - ); - } - throw new NotebookSnapshotError( - phase === 'check' ? 'CHECK_FAILED' : 'EXPORT_FAILED', - `marimo ${phase} command failed to execute.`, - { cause: err, details: { phase } } - ); - } - return validateCommandResult(rawResult, phase); -} - -/** - * Validates a marimo notebook with `marimo check --format=json` and, only when - * the check is clean, exports a static HTML snapshot via `marimo export html` - * and publishes it atomically via sibling temp-file rename. - */ -export async function exportNotebookSnapshot( - options: ExportNotebookSnapshotOptions -): Promise { - const { notebookPath, outputPath, runner, fs, marimoCommand, timeoutMs, cwd } = - validatePortsAndOptions(options); - - let notebookStat: NotebookSnapshotFileStat | null; - try { - notebookStat = await fs.stat(notebookPath); - } catch (err) { - if (getErrorCode(err) === 'ENOENT') { - notebookStat = null; - } else { - throw new NotebookSnapshotError( - 'NOTEBOOK_NOT_FOUND', - `Unable to stat notebook '${notebookPath}'.`, - { cause: err } - ); - } - } - - if (notebookStat === null || !notebookStat.isFile) { - throw new NotebookSnapshotError( - 'NOTEBOOK_NOT_FOUND', - `Notebook file not found or is not a regular file: '${notebookPath}'.` - ); - } - - const runOptions: NotebookCommandRunOptions = - cwd !== undefined ? { cwd, timeoutMs } : { timeoutMs }; - - // Step 1: Gate on `marimo check --format=json `. - const checkResult = await runPhaseCommand( - runner, - marimoCommand, - ['check', '--format=json', notebookPath], - runOptions, - 'check' - ); - - const hasCheckStdout = checkResult.stdout.length > 0; - let parsedCheckJson: unknown = undefined; - let checkJsonParseError: unknown = undefined; - if (hasCheckStdout) { - try { - parsedCheckJson = JSON.parse(checkResult.stdout); - } catch (err) { - checkJsonParseError = err; - } - } - - if (checkResult.exitCode !== 0) { - throw new NotebookSnapshotError( - 'CHECK_FAILED', - `marimo check exited with code ${checkResult.exitCode}.`, - { - details: { - exitCode: checkResult.exitCode, - stderr: checkResult.stderr, - stdout: checkResult.stdout, - ...(checkJsonParseError === undefined && parsedCheckJson !== undefined - ? { diagnostics: parsedCheckJson } - : {}), - }, - } - ); - } - - let checkDiagnostics: MarimoCheckReport | null = null; - if (hasCheckStdout) { - if (checkJsonParseError !== undefined) { - throw new NotebookSnapshotError( - 'CHECK_OUTPUT_INVALID', - 'marimo check exited 0 but emitted non-JSON stdout.', - { - cause: checkJsonParseError, - details: { stdout: checkResult.stdout, stderr: checkResult.stderr }, - } - ); - } - - const { report, hasBlockingError } = parseAndValidateCheckReport(parsedCheckJson); - if (hasBlockingError) { - throw new NotebookSnapshotError( - 'CHECK_FAILED', - 'marimo check reported blocking errors in diagnostics.', - { - details: { - exitCode: checkResult.exitCode, - stderr: checkResult.stderr, - diagnostics: report, - }, - } - ); - } - checkDiagnostics = deepFreeze(report); - } - - // Step 2: Reserve an exclusive sibling `.html` temp file and run `marimo export html`. - const tempPath = await reserveSiblingTempHtml(fs, outputPath); - let tempOwned = true; - - try { - const exportResult = await runPhaseCommand( - runner, - marimoCommand, - ['export', 'html', notebookPath, '-o', tempPath, '--force'], - runOptions, - 'export' - ); - - if (exportResult.exitCode !== 0) { - throw new NotebookSnapshotError( - 'EXPORT_FAILED', - `marimo export html exited with code ${exportResult.exitCode}.`, - { - details: { - exitCode: exportResult.exitCode, - stderr: exportResult.stderr, - stdout: exportResult.stdout, - }, - } - ); - } - - let tempStat: NotebookSnapshotFileStat | null; - try { - tempStat = await fs.stat(tempPath); - } catch (err) { - if (getErrorCode(err) === 'ENOENT') { - tempStat = null; - } else { - throw new NotebookSnapshotError( - 'EXPORT_FAILED', - `Failed to stat exported snapshot temp file '${tempPath}'.`, - { cause: err } - ); - } - } - - if (tempStat === null || !tempStat.isFile || tempStat.size <= 0) { - throw new NotebookSnapshotError( - 'EXPORT_EMPTY', - `marimo export html produced missing or empty output at '${tempPath}'.` - ); - } - - let exportedBytes: Uint8Array; - try { - exportedBytes = await fs.readBytes(tempPath); - } catch (err) { - if (getErrorCode(err) === 'ENOENT') { - throw new NotebookSnapshotError( - 'EXPORT_EMPTY', - `Exported snapshot temp file '${tempPath}' disappeared before read.`, - { cause: err } - ); - } - throw new NotebookSnapshotError( - 'EXPORT_FAILED', - `Failed to read exported snapshot temp file '${tempPath}'.`, - { cause: err } - ); - } - - if (!(exportedBytes instanceof Uint8Array) || exportedBytes.byteLength === 0) { - throw new NotebookSnapshotError( - 'EXPORT_EMPTY', - `marimo export html produced zero bytes at '${tempPath}'.` - ); - } - - const sha256 = await sha256HexNodeCrypto(exportedBytes); - const receipt: NotebookSnapshotReceipt = Object.freeze({ - notebookPath, - outputPath, - bytes: exportedBytes.byteLength, - sha256, - checkDiagnostics, - }); - - try { - await fs.rename(tempPath, outputPath); - tempOwned = false; - } catch (err) { - throw new NotebookSnapshotError( - 'EXPORT_FAILED', - `Failed to atomically publish snapshot from '${tempPath}' to '${outputPath}'.`, - { cause: err } - ); - } - - return receipt; - } catch (err) { - if (tempOwned) { - try { - await fs.remove(tempPath); - } catch { - // Preserve the primary error if temp cleanup also fails. - } - } - if (err instanceof NotebookSnapshotError) { - throw err; - } - throw new NotebookSnapshotError( - 'EXPORT_FAILED', - 'Unexpected failure during notebook snapshot export.', - { cause: err } - ); - } -} diff --git a/libs/research/src/panel-shared.ts b/libs/research/src/panel-shared.ts deleted file mode 100644 index 8e540224..00000000 --- a/libs/research/src/panel-shared.ts +++ /dev/null @@ -1,172 +0,0 @@ -/** - * Internal, browser-safe helpers shared by `signal-panel.ts` and `event-panel.ts`. - * - * Pure, synchronous, and dependency-free: zero `node:*` imports and zero bare - * `process` access. Not exported from the package root. - */ - -import { MarketDataStoreValidationError, applyVaultFence } from './market-data-store'; - -export const INT32_MIN = -2_147_483_648; -export const INT32_MAX = 2_147_483_647; -export const MAX_ECMASCRIPT_EPOCH_MS = 8_640_000_000_000_000; -export const MS_PER_DAY = 86_400_000; -export const MAX_DIRECT_DAY_SPAN = 200_000; -const DATE_ONLY_PATTERN = /^\d{4}-\d{2}-\d{2}$/; - -export function isPlainRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value); -} - -export function normalizeZero(value: number): number { - return value === 0 ? 0 : value; -} - -export function isValidInt32(value: unknown): value is number { - return ( - typeof value === 'number' && - Number.isSafeInteger(value) && - value >= INT32_MIN && - value <= INT32_MAX - ); -} - -export function isValidEpochMs(value: unknown): value is number { - return ( - typeof value === 'number' && - Number.isSafeInteger(value) && - Math.abs(value) <= MAX_ECMASCRIPT_EPOCH_MS - ); -} - -/** - * Parses a strict `YYYY-MM-DD` calendar date string into an integer UTC day key - * (`Math.floor(epochMs / MS_PER_DAY)`), delegating calendar validation to - * `applyVaultFence`. - */ -export function parseCalendarDayKey( - value: unknown, - field: string, - createError: (message: string, cause?: unknown) => Error -): number { - if (typeof value !== 'string' || !DATE_ONLY_PATTERN.test(value)) { - throw createError( - `Invalid "${field}": expected strict YYYY-MM-DD date string, got "${String(value)}".` - ); - } - try { - const fenced = applyVaultFence( - { from: value, to: value, scope: 'vault_evaluation_only' }, - { vaultCutoffTs: 0, vaultOperatorAuthorized: true } - ); - return fenced.fromMs / MS_PER_DAY; - } catch (error) { - if (error instanceof MarketDataStoreValidationError) { - throw createError(`Invalid "${field}": ${error.message}`, error); - } - throw error; - } -} - -export function formatDayKeyUtc(dayKey: number): string { - const date = new Date(dayKey * MS_PER_DAY); - const year = String(date.getUTCFullYear()).padStart(4, '0'); - const month = String(date.getUTCMonth() + 1).padStart(2, '0'); - const day = String(date.getUTCDate()).padStart(2, '0'); - return `${year}-${month}-${day}`; -} - -export interface BarSortScratch { - sessionIdx: Int32Array; - ts: Float64Array; - close: Float64Array; -} - -function ensureBarScratch(scratch: BarSortScratch, len: number): void { - if (scratch.sessionIdx.length < len) { - scratch.sessionIdx = new Int32Array(len); - scratch.ts = new Float64Array(len); - scratch.close = new Float64Array(len); - } -} - -/** - * Iterative bottom-up mergesort for a listing's bar slice `[start, end)` ordered - * by `sessionIdx ASC`. Skips sorting when already non-decreasing. - */ -export function sortBarSliceBySession( - sessionIdx: Int32Array, - ts: Float64Array, - close: Float64Array, - start: number, - end: number, - scratch: BarSortScratch -): void { - const len = end - start; - if (len <= 1) { - return; - } - - let sorted = true; - for (let i = start + 1; i < end; i += 1) { - if ((sessionIdx[i] as number) < (sessionIdx[i - 1] as number)) { - sorted = false; - break; - } - } - if (sorted) { - return; - } - - ensureBarScratch(scratch, len); - const tmpSession = scratch.sessionIdx; - const tmpTs = scratch.ts; - const tmpClose = scratch.close; - - for (let width = 1; width < len; width *= 2) { - for (let left = 0; left < len; left += 2 * width) { - const mid = Math.min(left + width, len); - const right = Math.min(left + 2 * width, len); - let i = left; - let j = mid; - let k = left; - - while (i < mid && j < right) { - const si = sessionIdx[start + i] as number; - const sj = sessionIdx[start + j] as number; - if (si <= sj) { - tmpSession[k] = si; - tmpTs[k] = ts[start + i] as number; - tmpClose[k] = close[start + i] as number; - i += 1; - } else { - tmpSession[k] = sj; - tmpTs[k] = ts[start + j] as number; - tmpClose[k] = close[start + j] as number; - j += 1; - } - k += 1; - } - while (i < mid) { - tmpSession[k] = sessionIdx[start + i] as number; - tmpTs[k] = ts[start + i] as number; - tmpClose[k] = close[start + i] as number; - i += 1; - k += 1; - } - while (j < right) { - tmpSession[k] = sessionIdx[start + j] as number; - tmpTs[k] = ts[start + j] as number; - tmpClose[k] = close[start + j] as number; - j += 1; - k += 1; - } - } - - for (let k = 0; k < len; k += 1) { - sessionIdx[start + k] = tmpSession[k] as number; - ts[start + k] = tmpTs[k] as number; - close[start + k] = tmpClose[k] as number; - } - } -} diff --git a/libs/research/src/sha256.ts b/libs/research/src/sha256.ts deleted file mode 100644 index d4c6febc..00000000 --- a/libs/research/src/sha256.ts +++ /dev/null @@ -1,105 +0,0 @@ -/** - * Browser-safe, dependency-free FIPS 180-4 SHA-256 hex digest helper. - * - * Internal module shared by `trial-ledger.ts` and `feature-library.ts`. - */ - -// FIPS 180-4 SHA-256 round constants. -const SHA256_K = new Uint32Array([ - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, -]); - -const UTF8_ENCODER = new TextEncoder(); - -export function sha256HexUtf8(text: string): string { - const bytes = UTF8_ENCODER.encode(text); - const byteLen = bytes.length; - const paddedLen = (((byteLen + 9 + 63) >> 6) << 6) >>> 0; - const buffer = new Uint8Array(paddedLen); - buffer.set(bytes); - buffer[byteLen] = 0x80; - - const view = new DataView(buffer.buffer); - const bitLenHigh = Math.floor((byteLen * 8) / 0x1_0000_0000); - const bitLenLow = (byteLen * 8) >>> 0; - view.setUint32(paddedLen - 8, bitLenHigh, false); - view.setUint32(paddedLen - 4, bitLenLow, false); - - let h0 = 0x6a09e667; - let h1 = 0xbb67ae85; - let h2 = 0x3c6ef372; - let h3 = 0xa54ff53a; - let h4 = 0x510e527f; - let h5 = 0x9b05688c; - let h6 = 0x1f83d9ab; - let h7 = 0x5be0cd19; - - const w = new Uint32Array(64); - - for (let offset = 0; offset < paddedLen; offset += 64) { - for (let i = 0; i < 16; i += 1) { - w[i] = view.getUint32(offset + i * 4, false); - } - for (let i = 16; i < 64; i += 1) { - const w15 = w[i - 15] as number; - const w2 = w[i - 2] as number; - const s0 = ((w15 >>> 7) | (w15 << 25)) ^ ((w15 >>> 18) | (w15 << 14)) ^ (w15 >>> 3); - const s1 = ((w2 >>> 17) | (w2 << 15)) ^ ((w2 >>> 19) | (w2 << 13)) ^ (w2 >>> 10); - w[i] = (((w[i - 16] as number) + s0 + (w[i - 7] as number) + s1) | 0) >>> 0; - } - - let a = h0; - let b = h1; - let c = h2; - let d = h3; - let e = h4; - let f = h5; - let g = h6; - let h = h7; - - for (let i = 0; i < 64; i += 1) { - const s1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7)); - const ch = (e & f) ^ (~e & g); - const temp1 = (h + s1 + ch + (SHA256_K[i] as number) + (w[i] as number)) | 0; - const s0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10)); - const maj = (a & b) ^ (a & c) ^ (b & c); - const temp2 = (s0 + maj) | 0; - - h = g; - g = f; - f = e; - e = (d + temp1) | 0; - d = c; - c = b; - b = a; - a = (temp1 + temp2) | 0; - } - - h0 = (h0 + a) >>> 0; - h1 = (h1 + b) >>> 0; - h2 = (h2 + c) >>> 0; - h3 = (h3 + d) >>> 0; - h4 = (h4 + e) >>> 0; - h5 = (h5 + f) >>> 0; - h6 = (h6 + g) >>> 0; - h7 = (h7 + h) >>> 0; - } - - return ( - h0.toString(16).padStart(8, '0') + - h1.toString(16).padStart(8, '0') + - h2.toString(16).padStart(8, '0') + - h3.toString(16).padStart(8, '0') + - h4.toString(16).padStart(8, '0') + - h5.toString(16).padStart(8, '0') + - h6.toString(16).padStart(8, '0') + - h7.toString(16).padStart(8, '0') - ); -} diff --git a/libs/research/src/signal-panel.ts b/libs/research/src/signal-panel.ts deleted file mode 100644 index 60d5f82a..00000000 --- a/libs/research/src/signal-panel.ts +++ /dev/null @@ -1,825 +0,0 @@ -/** - * Pure, dependency-free signal-panel builder that transforms `MarketDataStore` - * daily bars and point-in-time signal observations into Vault-safe - * `SignalCrossSection[]` panels for `analyzeSignal` (`design/MILESTONES.md` M1). - * - * Browser-safe and dependency-free: zero `node:*` imports, zero bare `process` - * access, and no database drivers. - * - * UTC session-calendar derivation: - * - Curated daily bars (`bars_1d.ts`) are stamped at `16:00 ET` (`20:00` or - * `21:00 UTC`), so the UTC calendar date `Math.floor(bar.ts / 86_400_000)` - * matches the exchange session date without timezone drift. - * - * Point-in-time (PIT) & Vault rules: - * - For each listing and session `d`, only signal rows with - * `knownAt <= bar.ts` are eligible; a signal known after the close takes - * effect on the next trading session. - * - No cross-section is emitted when either `d` or its forward session - * `d + horizonSessions` reaches or exceeds `vaultCutoffDate`, and `bar.close` - * is never accessed for any bar on or after `vaultCutoffDate`. - */ - -import type { SignalCrossSection } from '@stock-bot/calculations'; -import type { BarBatch, BarRecord, Table } from './market-data-store'; -import { - type BarSortScratch, - MAX_DIRECT_DAY_SPAN, - MS_PER_DAY, - formatDayKeyUtc, - isPlainRecord, - isValidEpochMs, - isValidInt32, - normalizeZero, - parseCalendarDayKey, - sortBarSliceBySession, -} from './panel-shared'; - -export type SignalPanelErrorCode = - | 'invalid_input' - | 'invalid_horizon' - | 'invalid_option' - | 'invalid_date' - | 'invalid_bar' - | 'invalid_signal' - | 'duplicate_bar'; - -export interface SignalPanelErrorOptions { - readonly cause?: unknown; -} - -/** Typed validation and data-integrity error thrown by the signal-panel builder helpers. */ -export class SignalPanelError extends Error { - override readonly name = 'SignalPanelError'; - readonly code: SignalPanelErrorCode; - override readonly cause?: unknown; - - constructor(code: SignalPanelErrorCode, message: string, options?: SignalPanelErrorOptions) { - super(message, options?.cause !== undefined ? { cause: options.cause } : undefined); - this.code = code; - if (options?.cause !== undefined) { - this.cause = options.cause; - } - Object.setPrototypeOf(this, new.target.prototype); - } -} - -export const SHORTS_SIGNAL_FIELDS = ['shares_short', 'net_change', 'pct_float'] as const; -const SHORTS_SIGNAL_FIELD_SET: ReadonlySet = new Set(SHORTS_SIGNAL_FIELDS); - -export type ShortsSignalField = (typeof SHORTS_SIGNAL_FIELDS)[number]; - -/** Point-in-time signal observation aligned to a listing ID and UTC epoch-ms `knownAt`. */ -export interface SignalObservation { - readonly listingId: number; - readonly knownAt: number; - readonly value: number; -} - -/** Input contract for {@link buildForwardReturnPanel}. */ -export interface BuildForwardReturnPanelInput { - readonly bars: readonly BarRecord[]; - readonly signals: readonly SignalObservation[]; - readonly horizonSessions: number; - readonly vaultCutoffDate: string; - readonly maxSignalAgeSessions?: number; -} - -/** Per-run diagnostic counters reported by {@link buildForwardReturnPanel}. */ -export interface SignalPanelDiagnostics { - readonly vaultExcludedDates: number; - readonly droppedNoSignal: number; - readonly droppedStaleSignal: number; - readonly droppedMissingForwardBar: number; - readonly droppedNonPositiveClose: number; - readonly duplicateBars: number; -} - -/** Output contract returned by {@link buildForwardReturnPanel}. */ -export interface BuildForwardReturnPanelResult { - readonly panel: SignalCrossSection[]; - readonly sessionDates: string[]; - readonly diagnostics: SignalPanelDiagnostics; -} - -function parseStrictCalendarDayKey(value: unknown, field: string): number { - return parseCalendarDayKey(value, field, (message, cause) => - new SignalPanelError('invalid_date', message, cause !== undefined ? { cause } : undefined) - ); -} - -/** - * Drains an `AsyncIterable` (such as `MarketDataStore.bars`) into a - * flat `BarRecord[]` without mutating any yielded batch or overflowing the call - * stack on large batches. - */ -export async function collectBars(iterable: AsyncIterable): Promise { - if ( - iterable === null || - (typeof iterable !== 'object' && typeof iterable !== 'function') || - typeof (iterable as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] !== 'function' - ) { - throw new SignalPanelError( - 'invalid_input', - 'Expected an AsyncIterable with a [Symbol.asyncIterator] method.' - ); - } - - const out: BarRecord[] = []; - let batchIndex = 0; - for await (const batch of iterable) { - if (!isPlainRecord(batch) || !Array.isArray(batch.rows)) { - throw new SignalPanelError( - 'invalid_bar', - `Expected batch[${batchIndex}] to be an object with a rows array.` - ); - } - const rows = batch.rows; - for (let i = 0; i < rows.length; i += 1) { - out.push(rows[i] as BarRecord); - } - batchIndex += 1; - } - return out; -} - -/** - * Maps a `MarketDataStore.shortsAsOf` `Table` into point-in-time - * {@link SignalObservation} rows for the chosen field, skipping `null` cells - * and rejecting malformed rows with {@link SignalPanelError}. - */ -export function shortsTableToSignalRows( - table: Table, - field: ShortsSignalField -): SignalObservation[] { - if (typeof field !== 'string' || !SHORTS_SIGNAL_FIELD_SET.has(field)) { - throw new SignalPanelError( - 'invalid_input', - `Invalid shorts signal field "${String(field)}": expected one of ${SHORTS_SIGNAL_FIELDS.join(', ')}.` - ); - } - if (!isPlainRecord(table) || !Array.isArray(table.columns) || !Array.isArray(table.rows)) { - throw new SignalPanelError( - 'invalid_input', - 'Expected a Table object with array columns and rows.' - ); - } - - let hasListingIdCol = false; - let hasKnownAtCol = false; - let hasFieldCol = false; - for (let i = 0; i < table.columns.length; i += 1) { - const col: unknown = table.columns[i]; - if (col === 'listing_id') { - hasListingIdCol = true; - } else if (col === 'known_at') { - hasKnownAtCol = true; - } else if (col === field) { - hasFieldCol = true; - } - } - if (!hasListingIdCol || !hasKnownAtCol || !hasFieldCol) { - throw new SignalPanelError( - 'invalid_input', - `Shorts table is missing required column(s): expected "listing_id", "known_at", and "${field}".` - ); - } - - const out: SignalObservation[] = []; - const rows = table.rows; - for (let i = 0; i < rows.length; i += 1) { - const row: unknown = rows[i]; - if (!isPlainRecord(row)) { - throw new SignalPanelError('invalid_signal', `Shorts table row[${i}] must be a plain object.`); - } - if ( - !Object.prototype.hasOwnProperty.call(row, 'listing_id') || - !Object.prototype.hasOwnProperty.call(row, 'known_at') || - !Object.prototype.hasOwnProperty.call(row, field) - ) { - throw new SignalPanelError( - 'invalid_signal', - `Shorts table row[${i}] is missing required key "listing_id", "known_at", or "${field}".` - ); - } - - const listingId = row.listing_id; - if (!isValidInt32(listingId)) { - throw new SignalPanelError( - 'invalid_signal', - `Invalid listing_id in shorts table row[${i}]: ${String(listingId)}.` - ); - } - - const knownAt = row.known_at; - if (!isValidEpochMs(knownAt)) { - throw new SignalPanelError( - 'invalid_signal', - `Invalid known_at in shorts table row[${i}]: ${String(knownAt)}.` - ); - } - - const rawValue = row[field]; - if (rawValue === null) { - continue; - } - if (typeof rawValue !== 'number' || !Number.isFinite(rawValue)) { - throw new SignalPanelError( - 'invalid_signal', - `Invalid "${field}" value in shorts table row[${i}]: ${String(rawValue)}.` - ); - } - - out.push({ - listingId: normalizeZero(listingId), - knownAt: normalizeZero(knownAt), - value: normalizeZero(rawValue), - }); - } - - return out; -} - -interface SignalSortScratch { - knownAt: Float64Array; - value: Float64Array; -} - -function ensureSignalScratch(scratch: SignalSortScratch, len: number): void { - if (scratch.knownAt.length < len) { - scratch.knownAt = new Float64Array(len); - scratch.value = new Float64Array(len); - } -} - -/** - * Iterative bottom-up mergesort for a listing's signal slice `[start, end)` - * ordered by `(knownAt ASC, value ASC)` for deterministic tie-breaking. - * Skips sorting when already sorted. - */ -function sortSignalSlice( - knownAt: Float64Array, - value: Float64Array, - start: number, - end: number, - scratch: SignalSortScratch -): void { - const len = end - start; - if (len <= 1) { - return; - } - - let sorted = true; - for (let i = start + 1; i < end; i += 1) { - const ka = knownAt[i] as number; - const prevKa = knownAt[i - 1] as number; - if (ka < prevKa || (ka === prevKa && (value[i] as number) < (value[i - 1] as number))) { - sorted = false; - break; - } - } - if (sorted) { - return; - } - - ensureSignalScratch(scratch, len); - const tmpKnownAt = scratch.knownAt; - const tmpValue = scratch.value; - - for (let width = 1; width < len; width *= 2) { - for (let left = 0; left < len; left += 2 * width) { - const mid = Math.min(left + width, len); - const right = Math.min(left + 2 * width, len); - let i = left; - let j = mid; - let k = left; - - while (i < mid && j < right) { - const ki = knownAt[start + i] as number; - const kj = knownAt[start + j] as number; - const vi = value[start + i] as number; - const vj = value[start + j] as number; - if (ki < kj || (ki === kj && vi <= vj)) { - tmpKnownAt[k] = ki; - tmpValue[k] = vi; - i += 1; - } else { - tmpKnownAt[k] = kj; - tmpValue[k] = vj; - j += 1; - } - k += 1; - } - while (i < mid) { - tmpKnownAt[k] = knownAt[start + i] as number; - tmpValue[k] = value[start + i] as number; - i += 1; - k += 1; - } - while (j < right) { - tmpKnownAt[k] = knownAt[start + j] as number; - tmpValue[k] = value[start + j] as number; - j += 1; - k += 1; - } - } - - for (let k = 0; k < len; k += 1) { - knownAt[start + k] = tmpKnownAt[k] as number; - value[start + k] = tmpValue[k] as number; - } - } -} - -/** - * Pure, synchronous forward-return signal-panel builder. - * - * Joins daily bars (caller-supplied `'total'`-adjusted closes in any order) - * with point-in-time signal observations (`knownAt <= bar.ts`), enforces the - * exclusive `vaultCutoffDate` fence across both the signal date `d` and the - * forward session `d + horizonSessions` without ever reading post-cutoff - * closes, and emits deterministic `SignalCrossSection[]` slices ready for - * `analyzeSignal`. - */ -export function buildForwardReturnPanel( - input: BuildForwardReturnPanelInput -): BuildForwardReturnPanelResult { - if (!isPlainRecord(input)) { - throw new SignalPanelError('invalid_input', 'Input must be a non-null plain object.'); - } - - const horizonSessions = input.horizonSessions; - if ( - typeof horizonSessions !== 'number' || - !Number.isSafeInteger(horizonSessions) || - horizonSessions < 1 - ) { - throw new SignalPanelError( - 'invalid_horizon', - `Invalid horizonSessions "${String(horizonSessions)}": expected a safe integer >= 1.` - ); - } - - const vaultCutoffDayKey = parseStrictCalendarDayKey(input.vaultCutoffDate, 'vaultCutoffDate'); - - const maxSignalAgeSessions = input.maxSignalAgeSessions; - if ( - maxSignalAgeSessions !== undefined && - (typeof maxSignalAgeSessions !== 'number' || - !Number.isSafeInteger(maxSignalAgeSessions) || - maxSignalAgeSessions < 0) - ) { - throw new SignalPanelError( - 'invalid_option', - `Invalid maxSignalAgeSessions "${String(maxSignalAgeSessions)}": expected a safe integer >= 0.` - ); - } - - if (!Array.isArray(input.bars)) { - throw new SignalPanelError('invalid_input', 'input.bars must be an array of BarRecord.'); - } - if (!Array.isArray(input.signals)) { - throw new SignalPanelError( - 'invalid_input', - 'input.signals must be an array of SignalObservation.' - ); - } - - const bars = input.bars; - const signals = input.signals; - - // Pass 1 over bars: validate structure, build pre-cutoff calendar, count bars per listing. - // Never access `bar.close` when the bar's UTC dayKey reaches or exceeds `vaultCutoffDayKey`. - const postCutoffDays = new Set(); - const preCutoffDayMaxTs = new Map(); - const listingBarCounts = new Map(); - let preCutoffBarTotal = 0; - - for (let i = 0; i < bars.length; i += 1) { - const rawBar: unknown = bars[i]; - if (!isPlainRecord(rawBar)) { - throw new SignalPanelError('invalid_bar', `bars[${i}] must be a non-null plain object.`); - } - - const listingId = rawBar.listingId; - if (!isValidInt32(listingId)) { - throw new SignalPanelError( - 'invalid_bar', - `Invalid listingId at bars[${i}]: ${String(listingId)}.` - ); - } - - const ts = rawBar.ts; - if (!isValidEpochMs(ts)) { - throw new SignalPanelError('invalid_bar', `Invalid ts at bars[${i}]: ${String(ts)}.`); - } - - const knownAt = rawBar.knownAt; - if (!isValidEpochMs(knownAt)) { - throw new SignalPanelError( - 'invalid_bar', - `Invalid knownAt at bars[${i}]: ${String(knownAt)}.` - ); - } - - const dayKey = Math.floor(ts / MS_PER_DAY); - if (dayKey >= vaultCutoffDayKey) { - postCutoffDays.add(dayKey); - continue; - } - - const close = rawBar.close; - if (typeof close !== 'number') { - throw new SignalPanelError('invalid_bar', `Invalid close at bars[${i}]: expected a number.`); - } - - const prevMaxTs = preCutoffDayMaxTs.get(dayKey); - if (prevMaxTs === undefined || ts > prevMaxTs) { - preCutoffDayMaxTs.set(dayKey, ts); - } - - const normListingId = normalizeZero(listingId); - listingBarCounts.set(normListingId, (listingBarCounts.get(normListingId) ?? 0) + 1); - preCutoffBarTotal += 1; - } - - // Build strictly ascending pre-cutoff session calendar. - const preCount = preCutoffDayMaxTs.size; - const preDayKeys = new Int32Array(preCount); - { - let idx = 0; - for (const dayKey of preCutoffDayMaxTs.keys()) { - preDayKeys[idx] = dayKey; - idx += 1; - } - preDayKeys.sort(); - } - - const sessionMaxTs = new Float64Array(preCount); - const sessionDates: string[] = new Array(preCount); - for (let i = 0; i < preCount; i += 1) { - const dk = preDayKeys[i] as number; - sessionMaxTs[i] = preCutoffDayMaxTs.get(dk) as number; - sessionDates[i] = formatDayKeyUtc(dk); - } - - const emittableDateLimit = Math.max(0, preCount - horizonSessions); - const hasPostCutoff = postCutoffDays.size > 0; - const vaultExcludedDates = hasPostCutoff - ? preCount - emittableDateLimit + postCutoffDays.size - : 0; - - // Sort unique listingIds ascending so output cross-section `ids` are strictly ascending - // with zero per-date sorting. - const listingCount = listingBarCounts.size; - const sortedListingIds = new Int32Array(listingCount); - { - let idx = 0; - for (const lid of listingBarCounts.keys()) { - sortedListingIds[idx] = lid; - idx += 1; - } - sortedListingIds.sort(); - } - - const listingIdToIdx = new Map(); - const barOffsets = new Int32Array(listingCount + 1); - for (let l = 0; l < listingCount; l += 1) { - const lid = sortedListingIds[l] as number; - listingIdToIdx.set(lid, l); - barOffsets[l + 1] = (barOffsets[l] as number) + (listingBarCounts.get(lid) as number); - } - - // Validate all signals upfront (even if bars is empty) and count signals per known listing. - const sigCounts = new Int32Array(listingCount); - let matchedSignalTotal = 0; - for (let i = 0; i < signals.length; i += 1) { - const rawSig: unknown = signals[i]; - if (!isPlainRecord(rawSig)) { - throw new SignalPanelError( - 'invalid_signal', - `signals[${i}] must be a non-null plain object.` - ); - } - - const listingId = rawSig.listingId; - if (!isValidInt32(listingId)) { - throw new SignalPanelError( - 'invalid_signal', - `Invalid listingId at signals[${i}]: ${String(listingId)}.` - ); - } - - const knownAt = rawSig.knownAt; - if (!isValidEpochMs(knownAt)) { - throw new SignalPanelError( - 'invalid_signal', - `Invalid knownAt at signals[${i}]: ${String(knownAt)}.` - ); - } - - const value = rawSig.value; - if (typeof value !== 'number' || !Number.isFinite(value)) { - throw new SignalPanelError( - 'invalid_signal', - `Invalid signal value at signals[${i}]: ${String(value)}.` - ); - } - - const l = listingIdToIdx.get(normalizeZero(listingId)); - if (l !== undefined) { - sigCounts[l] = (sigCounts[l] as number) + 1; - matchedSignalTotal += 1; - } - } - - if (preCutoffBarTotal === 0) { - return { - panel: [], - sessionDates, - diagnostics: { - vaultExcludedDates, - droppedNoSignal: 0, - droppedStaleSignal: 0, - droppedMissingForwardBar: 0, - droppedNonPositiveClose: 0, - duplicateBars: 0, - }, - }; - } - - // Build O(1) dayKey -> sessionIdx lookup (direct Int32Array when span <= 200_000, else Map). - const minDayKey = preDayKeys[0] as number; - const maxDayKey = preDayKeys[preCount - 1] as number; - const daySpan = maxDayKey - minDayKey + 1; - let dayKeyToIdxArr: Int32Array | null = null; - let dayKeyToIdxMap: Map | null = null; - if (daySpan <= MAX_DIRECT_DAY_SPAN) { - dayKeyToIdxArr = new Int32Array(daySpan); - dayKeyToIdxArr.fill(-1); - for (let i = 0; i < preCount; i += 1) { - dayKeyToIdxArr[(preDayKeys[i] as number) - minDayKey] = i; - } - } else { - dayKeyToIdxMap = new Map(); - for (let i = 0; i < preCount; i += 1) { - dayKeyToIdxMap.set(preDayKeys[i] as number, i); - } - } - - // Scatter pre-cutoff bars into CSR typed arrays grouped by listing index. - const barSessionIdx = new Int32Array(preCutoffBarTotal); - const barTs = new Float64Array(preCutoffBarTotal); - const barClose = new Float64Array(preCutoffBarTotal); - const barCursor = new Int32Array(listingCount); - for (let l = 0; l < listingCount; l += 1) { - barCursor[l] = barOffsets[l] as number; - } - - for (let i = 0; i < bars.length; i += 1) { - const bar = bars[i] as BarRecord; - const dayKey = Math.floor(bar.ts / MS_PER_DAY); - if (dayKey >= vaultCutoffDayKey) { - continue; - } - const l = listingIdToIdx.get(normalizeZero(bar.listingId)) as number; - const pos = barCursor[l] as number; - barCursor[l] = pos + 1; - - const sIdx = - dayKeyToIdxArr !== null - ? (dayKeyToIdxArr[dayKey - minDayKey] as number) - : ((dayKeyToIdxMap as Map).get(dayKey) as number); - barSessionIdx[pos] = sIdx; - barTs[pos] = normalizeZero(bar.ts); - barClose[pos] = bar.close; - } - - // Scatter matched signals into CSR typed arrays grouped by listing index. - const sigOffsets = new Int32Array(listingCount + 1); - const sigCursor = new Int32Array(listingCount); - for (let l = 0; l < listingCount; l += 1) { - sigOffsets[l + 1] = (sigOffsets[l] as number) + (sigCounts[l] as number); - sigCursor[l] = sigOffsets[l] as number; - } - - const sigKnownAt = new Float64Array(matchedSignalTotal); - const sigValue = new Float64Array(matchedSignalTotal); - if (matchedSignalTotal > 0) { - for (let i = 0; i < signals.length; i += 1) { - const sig = signals[i] as SignalObservation; - const l = listingIdToIdx.get(normalizeZero(sig.listingId)); - if (l === undefined) { - continue; - } - const pos = sigCursor[l] as number; - sigCursor[l] = pos + 1; - sigKnownAt[pos] = normalizeZero(sig.knownAt); - sigValue[pos] = normalizeZero(sig.value); - } - } - - // Per-date growable typed-array buckets for emitted observations. - const initialBucketCap = Math.max( - 8, - Math.min(listingCount, Math.ceil(preCutoffBarTotal / Math.max(1, preCount))) - ); - const bucketLengths = new Int32Array(emittableDateLimit); - const bucketIds: (Int32Array | null)[] = new Array(emittableDateLimit).fill( - null - ); - const bucketSignals: (Float64Array | null)[] = new Array( - emittableDateLimit - ).fill(null); - const bucketReturns: (Float64Array | null)[] = new Array( - emittableDateLimit - ).fill(null); - - const barScratch: BarSortScratch = { - sessionIdx: new Int32Array(0), - ts: new Float64Array(0), - close: new Float64Array(0), - }; - const sigScratch: SignalSortScratch = { - knownAt: new Float64Array(0), - value: new Float64Array(0), - }; - - let droppedNoSignal = 0; - let droppedStaleSignal = 0; - let droppedMissingForwardBar = 0; - let droppedNonPositiveClose = 0; - let duplicateBars = 0; - - // One linear merge pass per listing in ascending listingId order. - for (let l = 0; l < listingCount; l += 1) { - const listingId = sortedListingIds[l] as number; - const bStart = barOffsets[l] as number; - const bEnd = barOffsets[l + 1] as number; - if (bStart >= bEnd) { - continue; - } - - sortBarSliceBySession(barSessionIdx, barTs, barClose, bStart, bEnd, barScratch); - - // Compact exact duplicates in place; reject conflicting duplicates on the same (listingId, date). - let write = bStart; - for (let i = bStart + 1; i < bEnd; i += 1) { - if (barSessionIdx[i] === barSessionIdx[write]) { - const prevTs = barTs[write] as number; - const currTs = barTs[i] as number; - const prevClose = barClose[write] as number; - const currClose = barClose[i] as number; - const sameClose = - prevClose === currClose || (Number.isNaN(prevClose) && Number.isNaN(currClose)); - if (currTs === prevTs && sameClose) { - duplicateBars += 1; - continue; - } - const conflictDate = sessionDates[barSessionIdx[i] as number] as string; - throw new SignalPanelError( - 'duplicate_bar', - `Conflicting duplicate bars for listingId ${listingId} on session ${conflictDate}.` - ); - } - write += 1; - if (write !== i) { - barSessionIdx[write] = barSessionIdx[i] as number; - barTs[write] = barTs[i] as number; - barClose[write] = barClose[i] as number; - } - } - const uniqueEnd = write + 1; - - const sStart = sigOffsets[l] as number; - const sEnd = sigOffsets[l + 1] as number; - sortSignalSlice(sigKnownAt, sigValue, sStart, sEnd, sigScratch); - - let sigPtr = sStart - 1; - let fwdPtr = bStart; - let ageCalPtr = 0; - let firstActionableSessionIdx = -1; - - for (let i = bStart; i < uniqueEnd; i += 1) { - const t = barSessionIdx[i] as number; - if (hasPostCutoff && t >= emittableDateLimit) { - break; - } - - const ts = barTs[i] as number; - const prevSigPtr = sigPtr; - while (sigPtr + 1 < sEnd && (sigKnownAt[sigPtr + 1] as number) <= ts) { - sigPtr += 1; - } - - if (sigPtr < sStart) { - droppedNoSignal += 1; - continue; - } - - if (maxSignalAgeSessions !== undefined) { - if (sigPtr !== prevSigPtr) { - const activeKnownAt = sigKnownAt[sigPtr] as number; - while (ageCalPtr < preCount && (sessionMaxTs[ageCalPtr] as number) < activeKnownAt) { - ageCalPtr += 1; - } - firstActionableSessionIdx = ageCalPtr; - } - if (t - firstActionableSessionIdx > maxSignalAgeSessions) { - droppedStaleSignal += 1; - continue; - } - } - - const targetSession = t + horizonSessions; - if (targetSession >= preCount) { - droppedMissingForwardBar += 1; - continue; - } - - while (fwdPtr < uniqueEnd && (barSessionIdx[fwdPtr] as number) < targetSession) { - fwdPtr += 1; - } - if (fwdPtr >= uniqueEnd || (barSessionIdx[fwdPtr] as number) !== targetSession) { - droppedMissingForwardBar += 1; - continue; - } - - const close0 = barClose[i] as number; - const close1 = barClose[fwdPtr] as number; - if (!Number.isFinite(close0) || close0 <= 0 || !Number.isFinite(close1) || close1 <= 0) { - droppedNonPositiveClose += 1; - continue; - } - - const fwdRet = close1 / close0 - 1; - if (!Number.isFinite(fwdRet)) { - droppedNonPositiveClose += 1; - continue; - } - - // Append to bucket `t`. - const len = bucketLengths[t] as number; - let ids = bucketIds[t] ?? null; - let sigs = bucketSignals[t] ?? null; - let rets = bucketReturns[t] ?? null; - if (ids === null || sigs === null || rets === null) { - ids = new Int32Array(initialBucketCap); - sigs = new Float64Array(initialBucketCap); - rets = new Float64Array(initialBucketCap); - bucketIds[t] = ids; - bucketSignals[t] = sigs; - bucketReturns[t] = rets; - } else if (len === ids.length) { - const nextCap = Math.min(listingCount, ids.length * 2); - const nextIds = new Int32Array(nextCap); - const nextSigs = new Float64Array(nextCap); - const nextRets = new Float64Array(nextCap); - nextIds.set(ids); - nextSigs.set(sigs); - nextRets.set(rets); - ids = nextIds; - sigs = nextSigs; - rets = nextRets; - bucketIds[t] = ids; - bucketSignals[t] = sigs; - bucketReturns[t] = rets; - } - - ids[len] = listingId; - sigs[len] = normalizeZero(sigValue[sigPtr] as number); - rets[len] = normalizeZero(fwdRet); - bucketLengths[t] = len + 1; - } - } - - const panel: SignalCrossSection[] = []; - for (let t = 0; t < emittableDateLimit; t += 1) { - const len = bucketLengths[t] as number; - if (len === 0) { - continue; - } - const ids = bucketIds[t] as Int32Array; - const sigs = bucketSignals[t] as Float64Array; - const rets = bucketReturns[t] as Float64Array; - panel.push({ - date: sessionDates[t] as string, - ids: len === ids.length ? ids : ids.slice(0, len), - signal: len === sigs.length ? sigs : sigs.slice(0, len), - forwardReturn: len === rets.length ? rets : rets.slice(0, len), - }); - } - - return { - panel, - sessionDates, - diagnostics: { - vaultExcludedDates, - droppedNoSignal, - droppedStaleSignal, - droppedMissingForwardBar, - droppedNonPositiveClose, - duplicateBars, - }, - }; -} diff --git a/libs/research/src/trial-ledger.ts b/libs/research/src/trial-ledger.ts index fedddfbc..bc89a636 100644 --- a/libs/research/src/trial-ledger.ts +++ b/libs/research/src/trial-ledger.ts @@ -18,7 +18,6 @@ import { VaultHoldoutFenceError, applyVaultFence, } from './market-data-store'; -import { sha256HexUtf8 } from './sha256'; export const TRIAL_STAGES = ['signal_ic', 'event_study', 'screen', 'engine_backtest'] as const; export type TrialStage = (typeof TRIAL_STAGES)[number]; @@ -223,6 +222,106 @@ const SELECT_TRIAL_COLUMNS = ` kurtosis, daily_series`; +// FIPS 180-4 SHA-256 round constants. +const SHA256_K = new Uint32Array([ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, +]); + +const UTF8_ENCODER = new TextEncoder(); + +function sha256HexUtf8(text: string): string { + const bytes = UTF8_ENCODER.encode(text); + const byteLen = bytes.length; + const paddedLen = (((byteLen + 9 + 63) >> 6) << 6) >>> 0; + const buffer = new Uint8Array(paddedLen); + buffer.set(bytes); + buffer[byteLen] = 0x80; + + const view = new DataView(buffer.buffer); + const bitLenHigh = Math.floor((byteLen * 8) / 0x1_0000_0000); + const bitLenLow = (byteLen * 8) >>> 0; + view.setUint32(paddedLen - 8, bitLenHigh, false); + view.setUint32(paddedLen - 4, bitLenLow, false); + + let h0 = 0x6a09e667; + let h1 = 0xbb67ae85; + let h2 = 0x3c6ef372; + let h3 = 0xa54ff53a; + let h4 = 0x510e527f; + let h5 = 0x9b05688c; + let h6 = 0x1f83d9ab; + let h7 = 0x5be0cd19; + + const w = new Uint32Array(64); + + for (let offset = 0; offset < paddedLen; offset += 64) { + for (let i = 0; i < 16; i += 1) { + w[i] = view.getUint32(offset + i * 4, false); + } + for (let i = 16; i < 64; i += 1) { + const w15 = w[i - 15] as number; + const w2 = w[i - 2] as number; + const s0 = ((w15 >>> 7) | (w15 << 25)) ^ ((w15 >>> 18) | (w15 << 14)) ^ (w15 >>> 3); + const s1 = ((w2 >>> 17) | (w2 << 15)) ^ ((w2 >>> 19) | (w2 << 13)) ^ (w2 >>> 10); + w[i] = (((w[i - 16] as number) + s0 + (w[i - 7] as number) + s1) | 0) >>> 0; + } + + let a = h0; + let b = h1; + let c = h2; + let d = h3; + let e = h4; + let f = h5; + let g = h6; + let h = h7; + + for (let i = 0; i < 64; i += 1) { + const s1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7)); + const ch = (e & f) ^ (~e & g); + const temp1 = (h + s1 + ch + (SHA256_K[i] as number) + (w[i] as number)) | 0; + const s0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10)); + const maj = (a & b) ^ (a & c) ^ (b & c); + const temp2 = (s0 + maj) | 0; + + h = g; + g = f; + f = e; + e = (d + temp1) | 0; + d = c; + c = b; + b = a; + a = (temp1 + temp2) | 0; + } + + h0 = (h0 + a) >>> 0; + h1 = (h1 + b) >>> 0; + h2 = (h2 + c) >>> 0; + h3 = (h3 + d) >>> 0; + h4 = (h4 + e) >>> 0; + h5 = (h5 + f) >>> 0; + h6 = (h6 + g) >>> 0; + h7 = (h7 + h) >>> 0; + } + + return ( + h0.toString(16).padStart(8, '0') + + h1.toString(16).padStart(8, '0') + + h2.toString(16).padStart(8, '0') + + h3.toString(16).padStart(8, '0') + + h4.toString(16).padStart(8, '0') + + h5.toString(16).padStart(8, '0') + + h6.toString(16).padStart(8, '0') + + h7.toString(16).padStart(8, '0') + ); +} + function compareAscii(a: string, b: string): number { return a < b ? -1 : a > b ? 1 : 0; } diff --git a/libs/research/test/event-panel-e2e.test.ts b/libs/research/test/event-panel-e2e.test.ts deleted file mode 100644 index 4ac07daa..00000000 --- a/libs/research/test/event-panel-e2e.test.ts +++ /dev/null @@ -1,729 +0,0 @@ -import { describe, expect, it } from 'bun:test'; -import { - buildEventStudyInput, - collectBars, - createDuckDbMarketDataStore, - eventsTableToEventRows, - runEventStudy, - type DuckDbExecutor, - type DuckDbParam, - type EventStudyExchangeCalendars, - type TableRow, - type TrialLedgerExecutor, -} from '@stock-bot/research'; - -const CURATED_ROOT = '/mnt/data/stockbot/curated'; -const IMMUTABLE_ADJ_PATH = `${CURATED_ROOT}/adj_factors/snapshots/qmfilings_e2e_fenced.parquet`; -const SEED = 20261129; - -function createSeededRng(seed: number): () => number { - let state = seed >>> 0; - return () => { - state = (state + 0x6d2b79f5) >>> 0; - let t = Math.imul(state ^ (state >>> 15), 1 | state); - t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; - return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296; - }; -} - -function makeBusinessDates(startDate: string, count: number): string[] { - const out: string[] = new Array(count); - const current = new Date(`${startDate}T00:00:00.000Z`); - let written = 0; - while (written < count) { - const day = current.getUTCDay(); - if (day !== 0 && day !== 6) { - out[written] = current.toISOString().slice(0, 10); - written += 1; - } - current.setUTCDate(current.getUTCDate() + 1); - } - return out; -} - -function makeUtcMs(date: string, hourUtc: number): number { - const [y, m, d] = date.split('-').map(Number); - return Date.UTC(y!, m! - 1, d!, hourUtc, 0, 0, 0); -} - -interface StoredTrialRow { - readonly trial_id: string; - readonly created_at: Date; - readonly principal_id: string; - readonly campaign_id: string | null; - readonly stage: string; - readonly universe_market: string; - readonly horizon_bucket: string; - readonly hypothesis_id: string | null; - readonly expression_hash: string; - readonly sample_start: string; - readonly sample_end: string; - readonly n_obs: number; - readonly sharpe_unann: number; - readonly skewness: number; - readonly kurtosis: number; - readonly daily_series: readonly number[]; -} - -function createInMemoryTrialExecutor(): { - executor: TrialLedgerExecutor; - rows: StoredTrialRow[]; -} { - const rows: StoredTrialRow[] = []; - let nextTrialId = 1; - - const executor: TrialLedgerExecutor = { - async query>(text: string, params?: readonly unknown[]) { - const trimmed = text.trimStart(); - if (trimmed.startsWith('INSERT INTO trial_ledger')) { - const p = params ?? []; - const trialId = nextTrialId++; - const createdAt = new Date(Date.UTC(2024, 5, 1, 12, 0, trialId)); - const dailySeries = (p[13] as readonly number[]).map(v => Math.fround(v)); - const stored: StoredTrialRow = { - trial_id: String(trialId), - created_at: createdAt, - principal_id: p[0] as string, - campaign_id: (p[1] as string | null) ?? null, - stage: p[2] as string, - universe_market: p[3] as string, - horizon_bucket: p[4] as string, - hypothesis_id: (p[5] as string | null) ?? null, - expression_hash: p[6] as string, - sample_start: p[7] as string, - sample_end: p[8] as string, - n_obs: p[9] as number, - sharpe_unann: p[10] as number, - skewness: p[11] as number, - kurtosis: p[12] as number, - daily_series: dailySeries, - }; - rows.push(stored); - return { - rows: [{ trial_id: stored.trial_id, created_at: stored.created_at } as unknown as Row], - rowCount: 1, - }; - } - - if (trimmed.startsWith('SELECT')) { - if (text.includes('WHERE trial_id = $1::bigint')) { - const targetId = String(params?.[0]); - const matched = rows.filter(r => r.trial_id === targetId); - return { rows: matched as unknown as Row[], rowCount: matched.length }; - } - if (text.includes('WHERE universe_market = $1')) { - const market = params?.[0] as string; - const bucket = params?.[1] as string; - const matched = rows.filter( - r => r.universe_market === market && r.horizon_bucket === bucket - ); - return { rows: matched as unknown as Row[], rowCount: matched.length }; - } - } - - return { rows: [], rowCount: 0 }; - }, - }; - - return { executor, rows }; -} - -interface AdjFactorRow { - readonly listing_id: number; - readonly ex_date: string; - readonly cum_split_factor: number; - readonly cum_total_factor: number; - readonly known_at: number; -} - -interface QmFilingsFixture { - readonly listingIds: number[]; - readonly usListingIds: ReadonlySet; - readonly caListingIds: ReadonlySet; - readonly allDates: string[]; - readonly vaultCutoffDate: string; - readonly vaultCutoffTs: number; - readonly barRows: TableRow[]; - readonly adjFactorRows: AdjFactorRow[]; - readonly eventRows: TableRow[]; - readonly exchangeCalendars: EventStudyExchangeCalendars; - readonly dividendCase: { - readonly listingId: number; - readonly exDate: string; - readonly exDayIdx: number; - readonly expectedTotalReturn: number; - readonly rawDropReturn: number; - }; - readonly halfDayCase: { - readonly usListingId: number; - readonly caListingId: number; - readonly halfDayDate: string; - readonly halfDayIdx: number; - readonly nextSessionDate: string; - readonly nextSessionIdx: number; - readonly usHalfDayReturn: number; - readonly usNextSessionReturn: number; - }; -} - -function makeFencedAdjKvRows(vaultCutoffTs: number, rowsWritten: number): TableRow[] { - return [ - { key: 'stock_bot.adj_factors.format_version', value: '1' }, - { key: 'stock_bot.adj_factors.snapshot_kind', value: 'point_in_time_fenced' }, - { key: 'stock_bot.adj_factors.as_of_micros', value: 'none' }, - { key: 'stock_bot.adj_factors.vault_cutoff_micros', value: String(vaultCutoffTs * 1000) }, - { key: 'stock_bot.adj_factors.rows_written', value: String(rowsWritten) }, - { key: 'stock_bot.adj_factors.snapshot_checksum', value: '0x024ec73a1afe7e6b' }, - ]; -} - -function buildQmFilingsFixture(poisonPostCutoff: boolean): QmFilingsFixture { - const rand = createSeededRng(SEED); - const listingCount = 24; // 12 US ('10-q') + 12 CA ('interim_financial_statements') - const preCutoffSessions = 160; // spans late 2022 through spring 2023 (pre-2023 & post-2023) - const postCutoffSessions = 10; - const allDates = makeBusinessDates('2022-09-01', preCutoffSessions + postCutoffSessions); - const vaultCutoffDate = allDates[preCutoffSessions]!; - const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0); - - const listingIds = Array.from({ length: listingCount }, (_, i) => - i < 12 ? 10_001 + i : 50_001 + (i - 12) - ); - const usListingIds = new Set(listingIds.slice(0, 12)); - const caListingIds = new Set(listingIds.slice(12)); - const barRows: TableRow[] = []; - const adjFactorRows: AdjFactorRow[] = []; - const eventRows: TableRow[] = []; - - // Black Friday 2022-11-25: NYSE closes early at 13:00 ET (18:00 UTC) while TSX closes at - // 16:00 ET (21:00 UTC), even though curated bars_1d.ts stamps both at 16:00 ET (21:00 UTC). - const halfDayDate = '2022-11-25'; - const halfDayIdx = allDates.indexOf(halfDayDate); - if (halfDayIdx < 1 || halfDayIdx + 1 >= preCutoffSessions) { - throw new Error(`Expected half-day ${halfDayDate} inside pre-cutoff range.`); - } - const nextSessionIdx = halfDayIdx + 1; - const nextSessionDate = allDates[nextSessionIdx]!; - const halfDayUsIdx = 0; // listingId 10_001 (XNYS) - const halfDayCaIdx = 12; // listingId 50_001 (XTSE) - const halfDayUsListingId = listingIds[halfDayUsIdx]!; - const halfDayCaListingId = listingIds[halfDayCaIdx]!; - let usHalfDayReturn = 0; - let usNextSessionReturn = 0; - - const nyseCalendar = allDates.map(date => ({ - date, - closeTs: makeUtcMs(date, date === halfDayDate ? 18 : 21), // 13:00 ET on Black Friday, else 16:00 ET - })); - const tsxCalendar = allDates.map(date => ({ - date, - closeTs: makeUtcMs(date, 21), // 16:00 ET on all sessions including Black Friday - })); - const listingCalendarId = new Map(); - for (let l = 0; l < listingCount; l += 1) { - listingCalendarId.set(listingIds[l]!, l < 12 ? 'XNYS' : 'XTSE'); - } - const exchangeCalendars: EventStudyExchangeCalendars = { - calendars: new Map([ - ['XNYS', nyseCalendar], - ['XTSE', tsxCalendar], - ]), - listingCalendarId, - }; - - // Plant a 10% cash dividend inside a filing window for listing 0 (US, 10-q): - // On t = 12, listing l = ((12/4)*2 + 0) % 24 = 6 files after close; choose listing 6 - // and ex-date t = 15 (day +2 inside its [0..+5] filing window). - const divListingIdx = 6; - const divListingId = listingIds[divListingIdx]!; - const divExIdx = 15; - const divExDate = allDates[divExIdx]!; - const divYield = 0.1; // 10% cash dividend -> cum_total_factor = 1 / (1 - 0.1) = 10/9 - let divExpectedTotalReturn = 0; - let divRawDropReturn = 0; - - // Track active post-filing drift per listing: zero look-ahead because a filing stamped - // after close on session `t` (`22:00 UTC` / `17:00 ET`) only boosts returns starting on - // session `t + 1` (the event's anchored `dayIndex`) for 5 sessions. - const remainingBoostSessions = new Int32Array(listingCount); - const rawPrices = new Float64Array(listingCount); - for (let l = 0; l < listingCount; l += 1) { - rawPrices[l] = 15 + l * 1.25; - } - - for (let t = 0; t < allDates.length; t += 1) { - const date = allDates[t]!; - const closeTs = makeUtcMs(date, 21); // 16:00 ET - const afterCloseTs = makeUtcMs(date, 22); // 17:00 ET - const isPostCutoff = date >= vaultCutoffDate; - - // Emit daily bars using ONLY boosts already active before today's close. - for (let l = 0; l < listingCount; l += 1) { - const boost = remainingBoostSessions[l]! > 0 ? 0.008 : 0; - if (remainingBoostSessions[l]! > 0) { - remainingBoostSessions[l] = remainingBoostSessions[l]! - 1; - } - const dailyRet = boost + (rand() * 2 - 1) * 0.006; - - if (l === divListingIdx && t === divExIdx) { - const prevRaw = rawPrices[l]!; - const exRawBase = prevRaw * (1 - divYield); - const nextRaw = exRawBase * (1 + dailyRet); - const cumTotalFactor = prevRaw / exRawBase; // 1 / (1 - divYield) - adjFactorRows.push({ - listing_id: divListingId, - ex_date: divExDate, - cum_split_factor: 1.0, - cum_total_factor: cumTotalFactor, - known_at: makeUtcMs(allDates[divExIdx - 1]!, 21), - }); - divExpectedTotalReturn = nextRaw / (prevRaw / cumTotalFactor) - 1; - divRawDropReturn = nextRaw / prevRaw - 1; - rawPrices[l] = nextRaw; - } else { - const prevRaw = rawPrices[l]!; - const nextRaw = Math.max(0.5, prevRaw * (1 + dailyRet)); - if (l === halfDayUsIdx && t === halfDayIdx) { - usHalfDayReturn = nextRaw / prevRaw - 1; - } else if (l === halfDayUsIdx && t === nextSessionIdx) { - usNextSessionReturn = nextRaw / prevRaw - 1; - } - rawPrices[l] = nextRaw; - } - - const closeVal = poisonPostCutoff && isPostCutoff ? 999_999 : rawPrices[l]!; - barRows.push({ - listing_id: listingIds[l]!, - session_date: date, - ts: closeTs, - open: closeVal, - high: closeVal, - low: closeVal, - close: closeVal, - volume: 75_000, - vwap: closeVal, - known_at: closeTs, - }); - } - - // Schedule staggered after-close filing events across pre-2023 and post-2023 sessions - // (plus post-cutoff filings to verify Vault isolation) using exact curator subtypes. - if (t >= 12 && (t - 12) % 4 === 0) { - for (let k = 0; k < 2; k += 1) { - const l = ((t / 4) * 2 + k) % listingCount; - const isUs = l < 12; - const subtype = isUs ? '10-q' : 'interim_financial_statements'; - eventRows.push({ - listing_id: listingIds[l]!, - ts: afterCloseTs, - known_at: afterCloseTs, - known_at_source: 'exact', - kind: 'filing', - subtype: poisonPostCutoff && isPostCutoff ? 'poison_filing' : subtype, - payload_json: JSON.stringify({ market: isUs ? 'US' : 'CA', form: subtype }), - }); - // Activate drift starting on session `t + 1`. - remainingBoostSessions[l] = 5; - } - - // Also emit a non-matching curated subtype filing on another listing to verify subtype filtering. - const otherL = (t + 7) % listingCount; - eventRows.push({ - listing_id: listingIds[otherL]!, - ts: afterCloseTs, - known_at: afterCloseTs, - known_at_source: 'exact', - kind: 'filing', - subtype: 'other', - payload_json: '{}', - }); - } - - // Emit half-day filings at 14:00 ET (19:00 UTC) on Black Friday 2022-11-25: - // - NYSE already closed at 13:00 ET (18:00 UTC) -> anchors to Monday 2022-11-28. - // - TSX closes at 16:00 ET (21:00 UTC) -> anchors to Friday 2022-11-25. - if (t === halfDayIdx) { - const halfDay14EtTs = makeUtcMs(date, 19); - eventRows.push({ - listing_id: halfDayUsListingId, - ts: halfDay14EtTs, - known_at: halfDay14EtTs, - known_at_source: 'exact', - kind: 'filing', - subtype: '10-q', - payload_json: JSON.stringify({ market: 'US', form: '10-q', halfDay: true }), - }); - eventRows.push({ - listing_id: halfDayCaListingId, - ts: halfDay14EtTs, - known_at: halfDay14EtTs, - known_at_source: 'exact', - kind: 'filing', - subtype: 'interim_financial_statements', - payload_json: JSON.stringify({ - market: 'CA', - form: 'interim_financial_statements', - halfDay: true, - }), - }); - remainingBoostSessions[halfDayUsIdx] = 5; - remainingBoostSessions[halfDayCaIdx] = 5; - } - } - - return { - listingIds, - usListingIds, - caListingIds, - allDates, - vaultCutoffDate, - vaultCutoffTs, - barRows, - adjFactorRows, - eventRows, - exchangeCalendars, - dividendCase: { - listingId: divListingId, - exDate: divExDate, - exDayIdx: divExIdx, - expectedTotalReturn: divExpectedTotalReturn, - rawDropReturn: divRawDropReturn, - }, - halfDayCase: { - usListingId: halfDayUsListingId, - caListingId: halfDayCaListingId, - halfDayDate, - halfDayIdx, - nextSessionDate, - nextSessionIdx, - usHalfDayReturn, - usNextSessionReturn, - }, - }; -} - -interface RecordedQuery { - readonly sql: string; - readonly params: readonly DuckDbParam[]; -} - -function createFakeDuckDbExecutor(fixture: QmFilingsFixture): { - executor: DuckDbExecutor; - runStatements: string[]; - queries: RecordedQuery[]; -} { - const runStatements: string[] = []; - const queries: RecordedQuery[] = []; - - const executor: DuckDbExecutor = { - async run(sql: string) { - runStatements.push(sql); - }, - async query(sql: string, params: readonly DuckDbParam[]): Promise { - queries.push({ sql, params: [...params] }); - - if (sql.includes('parquet_kv_metadata')) { - return makeFencedAdjKvRows(fixture.vaultCutoffTs, fixture.adjFactorRows.length); - } - - if (sql.includes('bars_1d/year=*/part.parquet')) { - const nIds = fixture.listingIds.length; - const isAdjusted = sql.includes('ASOF LEFT JOIN'); - let idSet: Set; - let fromMs: number; - let toMs: number; - let asOfMs: number; - let adjAsOfMs: number | null = null; - - if (isAdjusted) { - // Bound params: [...listingIds, adjAsOfIso, ...listingIds, fromIso, toIso, asOfIso] - adjAsOfMs = Date.parse(params[nIds] as string); - idSet = new Set(params.slice(nIds + 1, 2 * nIds + 1) as number[]); - fromMs = Date.parse(params[2 * nIds + 1] as string); - toMs = Date.parse(params[2 * nIds + 2] as string); - asOfMs = Date.parse(params[2 * nIds + 3] as string); - } else { - // Bound params: [...listingIds, fromIso, toIso, asOfIso] - idSet = new Set(params.slice(0, nIds) as number[]); - fromMs = Date.parse(params[nIds] as string); - toMs = Date.parse(params[nIds + 1] as string); - asOfMs = Date.parse(params[nIds + 2] as string); - } - - const out: TableRow[] = []; - for (const row of fixture.barRows) { - const lid = row.listing_id as number; - const ts = row.ts as number; - const knownAt = row.known_at as number; - if (!idSet.has(lid) || ts < fromMs || ts > toMs || knownAt > asOfMs) { - continue; - } - - let priceDivisor = 1.0; - let splitFactor = 1.0; - if (isAdjusted && adjAsOfMs !== null) { - const sessionDate = row.session_date as string; - // ASOF LEFT JOIN: first adj_factors row with ex_date > session_date and known_at <= adjAsOfMs - let bestAdj: AdjFactorRow | null = null; - for (const adj of fixture.adjFactorRows) { - if ( - adj.listing_id === lid && - adj.known_at <= adjAsOfMs && - sessionDate < adj.ex_date && - (bestAdj === null || adj.ex_date < bestAdj.ex_date) - ) { - bestAdj = adj; - } - } - if (bestAdj !== null) { - priceDivisor = sql.includes('cum_total_factor') - ? bestAdj.cum_total_factor - : bestAdj.cum_split_factor; - splitFactor = bestAdj.cum_split_factor; - } - } - - out.push({ - listing_id: lid, - ts, - open: (row.open as number) / priceDivisor, - high: (row.high as number) / priceDivisor, - low: (row.low as number) / priceDivisor, - close: (row.close as number) / priceDivisor, - volume: (row.volume as number) * splitFactor, - vwap: (row.vwap as number) / priceDivisor, - known_at: knownAt, - }); - } - return out; - } - - if (sql.includes('events/year=*/part.parquet')) { - // Bound params: [...kinds, ...listingIds, fromIso, toIso, asOfIso] - const nIds = fixture.listingIds.length; - const nKinds = params.length - nIds - 3; - const kindSet = new Set(params.slice(0, nKinds) as string[]); - const idSet = new Set(params.slice(nKinds, nKinds + nIds) as number[]); - const fromMs = Date.parse(params[nKinds + nIds] as string); - const toMs = Date.parse(params[nKinds + nIds + 1] as string); - const asOfMs = Date.parse(params[nKinds + nIds + 2] as string); - return fixture.eventRows.filter(row => { - const kind = row.kind as string; - const lid = row.listing_id as number; - const ts = row.ts as number; - const knownAt = row.known_at as number; - return ( - kindSet.has(kind) && - idSet.has(lid) && - ts >= fromMs && - ts <= toMs && - knownAt <= asOfMs - ); - }); - } - - throw new Error(`Unexpected SQL in fake DuckDbExecutor: ${sql}`); - }, - }; - - return { executor, runStatements, queries }; -} - -describe('qmFilings end-to-end event study (headless, no database)', () => { - async function runQmFilingsStudy(poisonPostCutoff: boolean) { - const fixture = buildQmFilingsFixture(poisonPostCutoff); - const duck = createFakeDuckDbExecutor(fixture); - const ledger = createInMemoryTrialExecutor(); - - const store = createDuckDbMarketDataStore({ - executor: duck.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: fixture.vaultCutoffTs, - immutableAdjFactorsPath: IMMUTABLE_ADJ_PATH, - barBatchSize: 256, - }); - - const from = fixture.allDates[0]!; - const to = fixture.allDates[fixture.allDates.length - 1]!; - - const bars = await collectBars( - store.bars({ - listingIds: fixture.listingIds, - timeframe: '1d', - from, - to, - adjustment: 'total', - }) - ); - const eventsTable = await store.events({ - kinds: ['filing'], - listingIds: fixture.listingIds, - from, - to, - }); - - const events = eventsTableToEventRows(eventsTable, { - kinds: ['filing'], - subtypes: ['10-q', 'interim_financial_statements'], - }); - const built = buildEventStudyInput({ - bars, - events, - vaultCutoffDate: fixture.vaultCutoffDate, - benchmark: 'equal_weight', - exchangeCalendars: fixture.exchangeCalendars, - }); - - const studyResult = await runEventStudy(ledger.executor, { - principalId: 'operator', - universeMarket: 'US_CA_EQ', - horizonBucket: 'swing_1_10d', - expression: { - expression: 'qmfilings_interim_10q_sedar_event_study', - params: { - kinds: ['filing'], - subtypes: ['10-q', 'interim_financial_statements'], - preDays: 5, - postDays: 5, - }, - universe: 'US_CA_EQ_FIXTURE', - horizon: '5d', - }, - input: built.input, - options: { preDays: 5, postDays: 5, minEvents: 10 }, - vaultCutoffDate: fixture.vaultCutoffDate, - }); - - return { fixture, duck, ledger, events, built, studyResult }; - } - - it('flows DuckDbMarketDataStore (total-adjusted) -> buildEventStudyInput -> runEventStudy -> trial_ledger + DSR', async () => { - const clean = await runQmFilingsStudy(false); - - // DuckDB connection budget SET statements ran once; 3 queries ran (adj_factors kv metadata + bars + events). - expect(clean.duck.runStatements).toHaveLength(3); - expect(clean.duck.runStatements[0]).toContain('SET memory_limit'); - expect(clean.duck.runStatements[1]).toContain('SET threads'); - expect(clean.duck.runStatements[2]).toContain('SET temp_directory'); - expect(clean.duck.queries).toHaveLength(3); - expect(clean.duck.queries[0]!.sql).toContain('parquet_kv_metadata'); - expect(clean.duck.queries[1]!.sql).toContain('cum_total_factor'); - expect(clean.duck.queries[2]!.sql).toContain('events/year=*/part.parquet'); - - // Every bound timestamp parameter (`asOfIso`, `fromIso`, `toIso`) in every data query - // is strictly `< vaultCutoffTs`. - const isoRe = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/; - let checkedTimestamps = 0; - for (const q of clean.duck.queries) { - for (const param of q.params) { - if (typeof param === 'string' && isoRe.test(param)) { - const parsedMs = Date.parse(param); - expect(Number.isFinite(parsedMs)).toBe(true); - expect(parsedMs).toBeLessThan(clean.fixture.vaultCutoffTs); - checkedTimestamps += 1; - } - } - } - // bars_1d total-adjusted binds 4 timestamps (adjAsOfIso, fromIso, toIso, barsAsOfIso) + events binds 3. - expect(checkedTimestamps).toBe(7); - - // Both curated filing groups ('10-q' for US and 'interim_financial_statements' for CA) contribute events. - const usFilteredCount = clean.events.filter(e => e.subtype === '10-q').length; - const caFilteredCount = clean.events.filter( - e => e.subtype === 'interim_financial_statements' - ).length; - expect(usFilteredCount).toBeGreaterThan(0); - expect(caFilteredCount).toBeGreaterThan(0); - expect(usFilteredCount + caFilteredCount).toBe(clean.events.length); - - // Total-return adjustment eliminates the raw -10% dividend drop inside the filing window. - const divCase = clean.fixture.dividendCase; - expect(divCase.rawDropReturn).toBeLessThan(-0.08); - expect(divCase.expectedTotalReturn).toBeGreaterThan(-0.02); - const divSeries = clean.built.input.entityReturns.get(divCase.listingId)!; - expect(divSeries[divCase.exDayIdx]!).toBeCloseTo(divCase.expectedTotalReturn, 10); - - // Half-day anchoring: a US ('10-q') filing published at 14:00 ET on Black Friday 2022-11-25 - // (after NYSE's 13:00 ET close, even though curated bars_1d.ts stamps 16:00 ET) MUST anchor - // to Monday 2022-11-28 (not Friday), while the CA ('interim_financial_statements') filing at - // 14:00 ET anchors to Friday 2022-11-25 (before TSX's 16:00 ET close). - const halfDay = clean.fixture.halfDayCase; - expect( - clean.built.input.events.some( - e => e.entityId === halfDay.usListingId && e.dayIndex === halfDay.halfDayIdx - ) - ).toBe(false); - expect( - clean.built.input.events.some( - e => e.entityId === halfDay.usListingId && e.dayIndex === halfDay.nextSessionIdx - ) - ).toBe(true); - expect( - clean.built.input.events.some( - e => e.entityId === halfDay.caListingId && e.dayIndex === halfDay.halfDayIdx - ) - ).toBe(true); - const usHalfDaySeries = clean.built.input.entityReturns.get(halfDay.usListingId)!; - expect(clean.built.input.sessionDates[halfDay.nextSessionIdx]).toBe(halfDay.nextSessionDate); - expect(usHalfDaySeries[halfDay.nextSessionIdx]!).toBeCloseTo(halfDay.usNextSessionReturn, 12); - expect(halfDay.usNextSessionReturn).not.toBeCloseTo(halfDay.usHalfDayReturn, 6); - - // Event study succeeded and appended exactly one `event_study` row to trial_ledger. - expect(clean.studyResult.status).toBe('ok'); - if (clean.studyResult.status !== 'ok') { - return; - } - - // Both US ('10-q') and CA ('interim_financial_statements') listings contributed usable events to the study. - const usedIds = clean.studyResult.study.eventCars.entityIds; - const usUsedCount = usedIds.filter(id => clean.fixture.usListingIds.has(Number(id))).length; - const caUsedCount = usedIds.filter(id => clean.fixture.caListingIds.has(Number(id))).length; - expect(usUsedCount).toBeGreaterThan(0); - expect(caUsedCount).toBeGreaterThan(0); - - expect(clean.ledger.rows).toHaveLength(1); - const stored = clean.ledger.rows[0]!; - expect(stored.stage).toBe('event_study'); - expect(stored.universe_market).toBe('US_CA_EQ'); - expect(stored.horizon_bucket).toBe('swing_1_10d'); - expect(stored.sample_end < clean.fixture.vaultCutoffDate).toBe(true); - expect(clean.studyResult.trial.sampleEnd < clean.fixture.vaultCutoffDate).toBe(true); - - // Stored daily_series matches study.clustered.meanCars at float32 precision. - const expectedMeanCars = Array.from(clean.studyResult.study.clustered.meanCars, v => - Math.fround(v) - ); - expect(stored.daily_series).toEqual(expectedMeanCars); - - // Finite cluster-deflated Sharpe with effectiveTrials >= 1. - expect(clean.studyResult.deflatedSharpe.dsr).not.toBeNull(); - expect(Number.isFinite(clean.studyResult.deflatedSharpe.dsr!)).toBe(true); - expect(clean.studyResult.deflatedSharpe.effectiveTrials).toBeGreaterThanOrEqual(1); - - // Planted positive post-filing abnormal return produces positive clustered CAR mean. - expect(clean.studyResult.study.clustered.carMean).toBeGreaterThan(0); - - // Poisoning post-cutoff bars & events leaves built input, study result, and ledger byte-identical. - const poisoned = await runQmFilingsStudy(true); - expect(poisoned.built.diagnostics).toEqual(clean.built.diagnostics); - expect(poisoned.built.input.sessionDates).toEqual(clean.built.input.sessionDates); - expect(poisoned.built.input.events).toEqual(clean.built.input.events); - expect(Array.from(poisoned.built.input.entityReturns.keys())).toEqual( - Array.from(clean.built.input.entityReturns.keys()) - ); - for (const [id, cleanSeries] of clean.built.input.entityReturns) { - const a = poisoned.built.input.entityReturns.get(id) as Float64Array; - const b = cleanSeries as Float64Array; - expect(new Uint8Array(a.buffer, a.byteOffset, a.byteLength)).toEqual( - new Uint8Array(b.buffer, b.byteOffset, b.byteLength) - ); - } - const cleanBench = clean.built.input.benchmarkReturns as Float64Array; - const poisonedBench = poisoned.built.input.benchmarkReturns as Float64Array; - expect( - new Uint8Array(poisonedBench.buffer, poisonedBench.byteOffset, poisonedBench.byteLength) - ).toEqual(new Uint8Array(cleanBench.buffer, cleanBench.byteOffset, cleanBench.byteLength)); - expect(poisoned.studyResult).toEqual(clean.studyResult); - expect(poisoned.ledger.rows).toEqual(clean.ledger.rows); - }); -}); diff --git a/libs/research/test/event-panel-qa.test.ts b/libs/research/test/event-panel-qa.test.ts deleted file mode 100644 index 23ef342a..00000000 --- a/libs/research/test/event-panel-qa.test.ts +++ /dev/null @@ -1,672 +0,0 @@ -import { describe, expect, it } from 'bun:test'; -import { - type BarRecord, - type BuildEventStudyInputResult, - type EventObservation, - type EventStudyExchangeCalendars, - type ExchangeSessionClose, - type TrialLedgerExecutor, - buildEventStudyInput, - runEventStudy, -} from '@stock-bot/research'; - -// QA suite for T-123: compares `buildEventStudyInput` against a deliberately naive reference -// model on seeded random panels (two exchange calendars with different holidays and an NYSE -// half-day, EDT/EST close stamps, gaps, bad closes, exact duplicate bars, late-listing / -// early-delisting, events at/around exact close timestamps, weekends, pre-history and -// post-cutoff), plus truncation (prefix-stability) and an end-to-end half-day CAR probe. - -const MS_PER_DAY = 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 makeUtcMs(date: string, hourUtc: number, minuteUtc = 0, ms = 0): number { - const [y, m, d] = date.split('-').map(Number); - return Date.UTC(y!, m! - 1, d!, hourUtc, minuteUtc, 0, ms); -} - -function makeBusinessDates(startDate: string, count: number): string[] { - const out: string[] = []; - const current = new Date(`${startDate}T00:00:00.000Z`); - while (out.length < count) { - const day = current.getUTCDay(); - if (day !== 0 && day !== 6) { - out.push(current.toISOString().slice(0, 10)); - } - current.setUTCDate(current.getUTCDate() + 1); - } - return out; -} - -// 16:00 ET in UTC: 20:00 during EDT (before 2022-11-06 / from 2023-03-12), 21:00 during EST. -function regularCloseHourUtc(date: string): number { - return date < '2022-11-06' || date >= '2023-03-12' ? 20 : 21; -} - -function makeBar(listingId: number, ts: number, close: number): BarRecord { - return { - listingId, - ts, - open: close, - high: close, - low: close, - close, - volume: 1_000, - vwap: close, - knownAt: ts, - }; -} - -function makeTrappedBar(listingId: number, ts: number): BarRecord { - const bar = { ...makeBar(listingId, ts, 1) } as Record; - Object.defineProperty(bar, 'close', { - enumerable: true, - get() { - throw new Error(`Vault breach: close read for listing ${listingId} at ${ts}`); - }, - }); - return bar as unknown as BarRecord; -} - -function shuffle(items: readonly T[], seed: number): T[] { - const copy = [...items]; - const rand = createSeededRng(seed); - for (let i = copy.length - 1; i > 0; i -= 1) { - const j = Math.floor(rand() * (i + 1)); - [copy[i], copy[j]] = [copy[j]!, copy[i]!]; - } - return copy; -} - -const US_HOLIDAYS = new Set(['2022-11-24', '2022-12-26', '2023-01-02', '2023-01-16', '2023-02-20']); -const CA_HOLIDAYS = new Set(['2022-10-10', '2022-12-26', '2022-12-27', '2023-01-02', '2023-02-20']); -const NYSE_HALF_DAYS = new Set(['2022-11-25']); - -function buildCalendars(dates: readonly string[]): { - xnys: ExchangeSessionClose[]; - xtse: ExchangeSessionClose[]; -} { - const xnys: ExchangeSessionClose[] = []; - const xtse: ExchangeSessionClose[] = []; - for (const date of dates) { - const regular = regularCloseHourUtc(date); - if (!US_HOLIDAYS.has(date)) { - xnys.push({ date, closeTs: makeUtcMs(date, NYSE_HALF_DAYS.has(date) ? regular - 3 : regular) }); - } - if (!CA_HOLIDAYS.has(date)) { - xtse.push({ date, closeTs: makeUtcMs(date, regular) }); - } - } - return { xnys, xtse }; -} - -interface RandomPanel { - readonly bars: BarRecord[]; - readonly events: EventObservation[]; - readonly calendars: EventStudyExchangeCalendars; - readonly calendarByListing: Map; - readonly dates: string[]; -} - -/** - * Builds a seeded random panel. Bars dated on/after `trapFromDate` get a throwing `close` - * getter so any Vault breach fails the test. - */ -function buildRandomPanel(seed: number, trapFromDate: string | null): RandomPanel { - const rand = createSeededRng(seed); - const dates = makeBusinessDates('2022-10-03', 110); - const { xnys, xtse } = buildCalendars(dates); - const listingCount = 12; - const listingIds = Array.from({ length: listingCount }, (_, i) => 100 + i * 7); - const calendarByListing = new Map(); - const listingCalendarId = new Map(); - const bars: BarRecord[] = []; - - for (let l = 0; l < listingCount; l += 1) { - const listingId = listingIds[l]!; - const isUs = l % 2 === 0; - const cal = isUs ? xnys : xtse; - calendarByListing.set(listingId, cal); - listingCalendarId.set(listingId, isUs ? 'XNYS' : 'XTSE'); - - const startIdx = l % 4 === 3 ? 20 + Math.floor(rand() * 20) : 0; - const endIdx = l % 5 === 4 ? cal.length - 30 - Math.floor(rand() * 10) : cal.length; - let price = 20 + l; - for (let s = startIdx; s < endIdx; s += 1) { - const session = cal[s]!; - if (rand() < 0.08) { - continue; // gap - } - price *= 1 + (rand() * 2 - 1) * 0.02; - const ts = makeUtcMs(session.date, regularCloseHourUtc(session.date)); // curated 16:00 ET - const trapped = trapFromDate !== null && session.date >= trapFromDate; - if (trapped) { - bars.push(makeTrappedBar(listingId, ts)); - continue; - } - const u = rand(); - const close = u < 0.01 ? 0 : u < 0.02 ? -1 : u < 0.025 ? Number.NaN : u < 0.03 ? Number.POSITIVE_INFINITY : price; - bars.push(makeBar(listingId, ts, close)); - if (rand() < 0.03) { - bars.push(makeBar(listingId, ts, close)); // exact duplicate - } - } - } - - const events: EventObservation[] = []; - const eventCount = 160; - for (let i = 0; i < eventCount; i += 1) { - const unknown = rand() < 0.05; - const listingId = unknown ? 9_999 : listingIds[Math.floor(rand() * listingCount)]!; - const cal = calendarByListing.get(listingId) ?? xnys; - const anchorSession = cal[Math.floor(rand() * cal.length)]!; - const mode = Math.floor(rand() * 7); - let knownAt: number; - if (mode === 0) { - knownAt = anchorSession.closeTs; // exactly at close -> same session - } else if (mode === 1) { - knownAt = anchorSession.closeTs + 1; // 1 ms after close -> next session - } else if (mode === 2) { - knownAt = anchorSession.closeTs - 1; - } else if (mode === 3) { - knownAt = makeUtcMs(anchorSession.date, 19); // 14:00/15:00 ET intraday (after half-day close) - } else if (mode === 4) { - knownAt = makeUtcMs(anchorSession.date, 22, 30); // after close - } else if (mode === 5) { - knownAt = makeUtcMs(anchorSession.date, 12) + 2 * MS_PER_DAY; // may land on weekend - } else { - knownAt = makeUtcMs('2022-09-15', 15) + Math.floor(rand() * 200) * MS_PER_DAY; // pre-history .. post-cutoff - } - events.push({ listingId, knownAt, kind: 'filing', subtype: rand() < 0.5 ? '10-q' : 'interim_financial_statements' }); - if (rand() < 0.05) { - events.push({ listingId, knownAt, kind: 'filing', subtype: 'other' }); // duplicate anchor - } - } - // Explicit NYSE half-day probe: 14:00 ET on Black Friday for a US and a CA listing. - events.push({ listingId: listingIds[0]!, knownAt: makeUtcMs('2022-11-25', 19), kind: 'filing', subtype: '10-q' }); - events.push({ listingId: listingIds[1]!, knownAt: makeUtcMs('2022-11-25', 19), kind: 'filing', subtype: null }); - - return { - bars, - events, - calendars: { - calendars: new Map([ - ['XNYS', xnys], - ['XTSE', xtse], - ]), - listingCalendarId, - }, - calendarByListing, - dates, - }; -} - -interface ReferenceResult { - sessionDates: string[]; - entityIds: number[]; - returns: Map; - benchmark: number[]; - events: { entityId: number; dayIndex: number }[]; - diagnostics: Record; -} - -/** Naive O(n^2) reference model of the documented contract. */ -function referenceBuild(panel: RandomPanel, vaultCutoffDate: string): ReferenceResult { - const cutoffMs = makeUtcMs(vaultCutoffDate, 0); - const dateOf = (ts: number) => new Date(Math.floor(ts / MS_PER_DAY) * MS_PER_DAY).toISOString().slice(0, 10); - const postDates = new Set(); - const perListing = new Map>(); - let duplicateBars = 0; - for (const bar of panel.bars) { - const date = dateOf(bar.ts); - if (date >= vaultCutoffDate) { - postDates.add(date); - continue; - } - const m = perListing.get(bar.listingId) ?? new Map(); - perListing.set(bar.listingId, m); - if (m.has(date)) { - duplicateBars += 1; - continue; - } - m.set(date, bar.close); - } - const sessionDates = [...new Set([...perListing.values()].flatMap(m => [...m.keys()]))].sort(); - const entityIds = [...perListing.keys()].sort((a, b) => a - b); - const returns = new Map(); - const benchSum = new Array(sessionDates.length).fill(0); - const benchCount = new Array(sessionDates.length).fill(0); - let nonPositiveCloseReturns = 0; - for (const id of entityIds) { - const closes = perListing.get(id)!; - const calDates = panel.calendarByListing.get(id)!.map(s => s.date); - const series = sessionDates.map((date, d) => { - if (!closes.has(date)) { - return Number.NaN; - } - const c = calDates.indexOf(date); - if (c <= 0 || !closes.has(calDates[c - 1]!)) { - return Number.NaN; - } - const prev = closes.get(calDates[c - 1]!)!; - const curr = closes.get(date)!; - const ret = curr / prev - 1; - if (!(prev > 0 && curr > 0 && Number.isFinite(prev) && Number.isFinite(curr) && Number.isFinite(ret))) { - nonPositiveCloseReturns += 1; - return Number.NaN; - } - benchSum[d] += ret; - benchCount[d] += 1; - return ret; - }); - returns.set(id, series); - } - const benchmark = benchSum.map((s, d) => (benchCount[d]! > 0 ? s / benchCount[d]! : Number.NaN)); - - let vaultExcludedEvents = 0; - let droppedUnknownListing = 0; - let droppedAfterLastSession = 0; - let droppedMissingCalendarSession = 0; - const cands: { entityId: number; dayIndex: number }[] = []; - for (const ev of panel.events) { - if (ev.knownAt >= cutoffMs) { - vaultExcludedEvents += 1; - continue; - } - if (!perListing.has(ev.listingId)) { - droppedUnknownListing += 1; - continue; - } - const preCal = panel.calendarByListing.get(ev.listingId)!.filter(s => s.date < vaultCutoffDate); - const eligible = preCal.find(s => s.closeTs >= ev.knownAt); - if (eligible === undefined || eligible.date > sessionDates[sessionDates.length - 1]!) { - droppedAfterLastSession += 1; - continue; - } - const dayIndex = sessionDates.indexOf(eligible.date); - if (dayIndex < 0) { - droppedMissingCalendarSession += 1; - continue; - } - cands.push({ entityId: ev.listingId, dayIndex }); - } - cands.sort((a, b) => a.dayIndex - b.dayIndex || a.entityId - b.entityId); - const events = cands.filter( - (c, i) => i === 0 || c.dayIndex !== cands[i - 1]!.dayIndex || c.entityId !== cands[i - 1]!.entityId - ); - - return { - sessionDates, - entityIds, - returns, - benchmark, - events, - diagnostics: { - vaultExcludedDates: postDates.size, - vaultExcludedEvents, - droppedUnknownListing, - droppedAfterLastSession, - droppedMissingCalendarSession, - duplicateEvents: cands.length - events.length, - duplicateBars, - nonPositiveCloseReturns, - }, - }; -} - -function nanSafe(values: ArrayLike): (number | string)[] { - return Array.from(values, v => (Number.isNaN(v) ? 'NaN' : v)); -} - -function expectSameAsReference(actual: BuildEventStudyInputResult, ref: ReferenceResult): void { - expect(actual.input.sessionDates).toEqual(ref.sessionDates); - expect(Array.from(actual.input.entityReturns.keys())).toEqual(ref.entityIds); - for (const id of ref.entityIds) { - expect(nanSafe(actual.input.entityReturns.get(id)!)).toEqual(nanSafe(ref.returns.get(id)!)); - } - expect(nanSafe(actual.input.benchmarkReturns!)).toEqual(nanSafe(ref.benchmark)); - expect(actual.input.events.map(e => ({ entityId: e.entityId, dayIndex: e.dayIndex }))).toEqual(ref.events); - expect({ ...actual.diagnostics }).toEqual(ref.diagnostics); -} - -describe('buildEventStudyInput QA — seeded reference-model comparison', () => { - const VAULT_CUTOFF = '2023-02-01'; - - for (const seed of [20261129, 7, 424242, 99]) { - it(`matches the naive reference model exactly and never reads vaulted closes (seed ${seed})`, () => { - const panel = buildRandomPanel(seed, VAULT_CUTOFF); - const ref = referenceBuild(panel, VAULT_CUTOFF); - - const actual = buildEventStudyInput({ - bars: panel.bars, - events: panel.events, - vaultCutoffDate: VAULT_CUTOFF, - benchmark: 'equal_weight', - exchangeCalendars: panel.calendars, - }); - - expectSameAsReference(actual, ref); - // Conservation identity. - const d = actual.diagnostics; - expect( - actual.input.events.length + - d.vaultExcludedEvents + - d.droppedUnknownListing + - d.droppedAfterLastSession + - d.droppedMissingCalendarSession + - d.duplicateEvents - ).toBe(panel.events.length); - // No session date reaches the Vault and no event anchors onto a Vault session. - expect(actual.input.sessionDates.every(date => date < VAULT_CUTOFF)).toBe(true); - // Fixture actually exercises the interesting branches. - expect(d.vaultExcludedEvents).toBeGreaterThan(0); - expect(d.droppedUnknownListing).toBeGreaterThan(0); - expect(d.vaultExcludedDates).toBeGreaterThan(0); - expect(d.nonPositiveCloseReturns).toBeGreaterThan(0); - - // Shuffled inputs give the identical result. - const shuffled = buildEventStudyInput({ - bars: shuffle(panel.bars, seed + 1), - events: shuffle(panel.events, seed + 2), - vaultCutoffDate: VAULT_CUTOFF, - benchmark: 'equal_weight', - exchangeCalendars: panel.calendars, - }); - expectSameAsReference(shuffled, ref); - }); - } - - it('anchors the NYSE Black Friday 14:00 ET filing to Monday and the TSX one to Friday', () => { - const panel = buildRandomPanel(20261129, VAULT_CUTOFF); - const actual = buildEventStudyInput({ - bars: panel.bars, - events: panel.events, - vaultCutoffDate: VAULT_CUTOFF, - exchangeCalendars: panel.calendars, - }); - const usId = 100; - const caId = 107; - const dates = actual.input.sessionDates; - const usDates = actual.input.events.filter(e => e.entityId === usId).map(e => dates[e.dayIndex]); - const caDates = actual.input.events.filter(e => e.entityId === caId).map(e => dates[e.dayIndex]); - expect(usDates).toContain('2022-11-28'); - expect(caDates).toContain('2022-11-25'); - }); -}); - -describe('buildEventStudyInput QA — truncation (prefix stability) across Vault cutoffs', () => { - it('earlier-cutoff output is an exact prefix of later-cutoff output (no future-dependent values)', () => { - const panel = buildRandomPanel(31337, null); - const cutoffs = ['2022-11-25', '2022-12-27', '2023-01-17', '2023-02-21']; - const results = cutoffs.map(vaultCutoffDate => - buildEventStudyInput({ - bars: panel.bars, - events: panel.events, - vaultCutoffDate, - benchmark: 'equal_weight', - exchangeCalendars: panel.calendars, - }) - ); - - for (let i = 0; i + 1 < results.length; i += 1) { - const early = results[i]!.input; - const late = results[i + 1]!.input; - const n = early.sessionDates.length; - expect(n).toBeGreaterThan(0); - expect(late.sessionDates.slice(0, n)).toEqual([...early.sessionDates]); - for (const [id, series] of early.entityReturns) { - const lateSeries = late.entityReturns.get(id)!; - expect(nanSafe(Array.from(lateSeries).slice(0, n))).toEqual(nanSafe(series)); - } - expect(nanSafe(Array.from(late.benchmarkReturns!).slice(0, n))).toEqual( - nanSafe(early.benchmarkReturns!) - ); - const lateKeys = new Set(late.events.map(e => `${e.entityId}@${e.dayIndex}`)); - for (const ev of early.events) { - expect(lateKeys.has(`${ev.entityId}@${ev.dayIndex}`)).toBe(true); - } - } - }); - - it('a poisoned future (absurd closes, extra filings, calendar tail) leaves pre-cutoff output byte-identical', () => { - const cutoff = '2023-01-17'; - const panel = buildRandomPanel(555, null); - const base = buildEventStudyInput({ - bars: panel.bars, - events: panel.events, - vaultCutoffDate: cutoff, - benchmark: 'equal_weight', - exchangeCalendars: panel.calendars, - }); - - const cutoffMs = makeUtcMs(cutoff, 0); - const poisonedBars = panel.bars.map(b => - b.ts >= cutoffMs ? makeBar(b.listingId, b.ts, b.close * 1_000_000) : b - ); - const poisonedEvents: EventObservation[] = [ - ...panel.events, - ...[100, 107, 114].map(listingId => ({ - listingId, - knownAt: cutoffMs, - kind: 'filing' as const, - subtype: 'poison', - })), - ]; - const result = buildEventStudyInput({ - bars: poisonedBars, - events: poisonedEvents, - vaultCutoffDate: cutoff, - benchmark: 'equal_weight', - exchangeCalendars: panel.calendars, - }); - - expect(result.input.sessionDates).toEqual(base.input.sessionDates); - expect(result.input.events).toEqual(base.input.events); - for (const [id, series] of base.input.entityReturns) { - expect(nanSafe(result.input.entityReturns.get(id)!)).toEqual(nanSafe(series)); - } - expect(nanSafe(result.input.benchmarkReturns!)).toEqual(nanSafe(base.input.benchmarkReturns!)); - expect(result.diagnostics.vaultExcludedEvents).toBe(base.diagnostics.vaultExcludedEvents + 3); - }); -}); - -describe('buildEventStudyInput QA — calendar input forms and exact-close boundaries', () => { - it('treats plain-object calendars/mappings identically to Maps', () => { - const panel = buildRandomPanel(8080, null); - const cutoff = '2023-02-01'; - const cals = panel.calendars.calendars as ReadonlyMap; - const mapping = panel.calendars.listingCalendarId as ReadonlyMap; - const asMaps = buildEventStudyInput({ - bars: panel.bars, - events: panel.events, - vaultCutoffDate: cutoff, - benchmark: 'equal_weight', - exchangeCalendars: panel.calendars, - }); - const asRecords = buildEventStudyInput({ - bars: panel.bars, - events: panel.events, - vaultCutoffDate: cutoff, - benchmark: 'equal_weight', - exchangeCalendars: { - calendars: Object.fromEntries(cals), - listingCalendarId: Object.fromEntries(mapping), - }, - }); - expect(asRecords.input.events).toEqual(asMaps.input.events); - expect(asRecords.diagnostics).toEqual(asMaps.diagnostics); - for (const [id, series] of asMaps.input.entityReturns) { - expect(nanSafe(asRecords.input.entityReturns.get(id)!)).toEqual(nanSafe(series)); - } - }); - - it('anchors knownAt == close to that session and close + 1 ms to the next (half-day close included)', () => { - const dates = ['2022-11-22', '2022-11-23', '2022-11-25', '2022-11-28']; - const xnys = dates.map(date => ({ - date, - closeTs: makeUtcMs(date, NYSE_HALF_DAYS.has(date) ? 18 : 21), - })); - const bars = dates.map((date, i) => makeBar(1, makeUtcMs(date, 21), 10 + i)); - const halfClose = makeUtcMs('2022-11-25', 18); - const result = buildEventStudyInput({ - bars, - events: [ - { listingId: 1, knownAt: halfClose, kind: 'filing', subtype: '10-q' }, - { listingId: 1, knownAt: halfClose + 1, kind: 'filing', subtype: '10-q' }, - // Thanksgiving (NYSE closed) intraday -> Friday half-day session. - { listingId: 1, knownAt: makeUtcMs('2022-11-24', 15), kind: 'filing', subtype: '10-q' }, - ], - vaultCutoffDate: '2022-12-01', - exchangeCalendars: { calendars: { XNYS: xnys }, listingCalendarId: { 1: 'XNYS' } }, - }); - expect(result.input.events).toEqual([ - { entityId: 1, dayIndex: 2 }, - { entityId: 1, dayIndex: 3 }, - ]); - expect(result.diagnostics.duplicateEvents).toBe(1); - // Wed -> Fri is consecutive on the NYSE calendar (Thanksgiving closed), so Friday's return is valid. - expect(result.input.entityReturns.get(1)![2]).toBeCloseTo(12 / 11 - 1, 15); - }); -}); - -function createInMemoryTrialExecutor(): { executor: TrialLedgerExecutor; rows: Record[] } { - const rows: Record[] = []; - let nextTrialId = 1; - const executor: TrialLedgerExecutor = { - async query>(text: string, params?: readonly unknown[]) { - const trimmed = text.trimStart(); - const p = params ?? []; - if (trimmed.startsWith('INSERT INTO trial_ledger')) { - const trialId = String(nextTrialId++); - const createdAt = new Date(Date.UTC(2024, 5, 1, 12, 0, Number(trialId))); - const stored = { - trial_id: trialId, - created_at: createdAt, - principal_id: p[0], - campaign_id: p[1] ?? null, - stage: p[2], - universe_market: p[3], - horizon_bucket: p[4], - hypothesis_id: p[5] ?? null, - expression_hash: p[6], - sample_start: p[7], - sample_end: p[8], - n_obs: p[9], - sharpe_unann: p[10], - skewness: p[11], - kurtosis: p[12], - daily_series: (p[13] as readonly number[]).map(v => Math.fround(v)), - }; - rows.push(stored); - return { rows: [{ trial_id: trialId, created_at: createdAt } as unknown as Row], rowCount: 1 }; - } - if (trimmed.startsWith('SELECT')) { - if (text.includes('WHERE trial_id = $1::bigint')) { - const matched = rows.filter(r => r.trial_id === String(p[0])); - return { rows: matched as unknown as Row[], rowCount: matched.length }; - } - if (text.includes('WHERE universe_market = $1')) { - const matched = rows.filter(r => r.universe_market === p[0] && r.horizon_bucket === p[1]); - return { rows: matched as unknown as Row[], rowCount: matched.length }; - } - } - return { rows: [], rowCount: 0 }; - }, - }; - return { executor, rows }; -} - -describe('buildEventStudyInput QA — half-day filing reaches runEventStudy eventCars on Monday', () => { - it('keeps the NYSE Black Friday filing in study.eventCars dated Monday with the expected benchmark-adjusted CAR', async () => { - const rand = createSeededRng(20261129); - const dates = makeBusinessDates('2022-10-03', 90); - const { xnys, xtse } = buildCalendars(dates); - const vaultCutoffDate = dates[80]!; - const usIds = [11, 12, 13, 14]; - const caIds = [21, 22, 23, 24]; - const bars: BarRecord[] = []; - const listingCalendarId = new Map(); - for (const [ids, cal, calId] of [ - [usIds, xnys, 'XNYS'], - [caIds, xtse, 'XTSE'], - ] as const) { - for (const id of ids) { - listingCalendarId.set(id, calId); - let price = 30 + id; - for (const s of cal) { - price *= 1 + (rand() * 2 - 1) * 0.015; - bars.push(makeBar(id, makeUtcMs(s.date, regularCloseHourUtc(s.date)), price)); - } - } - } - - // Regular after-close filings every 5 sessions in windows that avoid cross-border holidays, - // plus the 14:00 ET Black Friday filing for listing 11 (after NYSE's 13:00 ET close). - const events: EventObservation[] = []; - for (let t = 3; t < 75; t += 5) { - const date = dates[t]!; - for (const id of [...usIds, ...caIds]) { - if ((t + id) % 3 === 0) { - events.push({ listingId: id, knownAt: makeUtcMs(date, 23), kind: 'filing', subtype: '10-q' }); - } - } - } - events.push({ listingId: 11, knownAt: makeUtcMs('2022-11-25', 19), kind: 'filing', subtype: '10-q' }); - - const built = buildEventStudyInput({ - bars, - events, - vaultCutoffDate, - benchmark: 'equal_weight', - exchangeCalendars: { calendars: { XNYS: xnys, XTSE: xtse }, listingCalendarId }, - }); - - const postDays = 3; - const ledger = createInMemoryTrialExecutor(); - const result = await runEventStudy(ledger.executor, { - principalId: 'operator', - universeMarket: 'US_CA_EQ', - horizonBucket: 'swing_1_10d', - expression: { - expression: 'qa_half_day_filing_event_study', - params: { preDays: 0, postDays }, - universe: 'US_CA_EQ_QA', - horizon: '3d', - }, - input: built.input, - options: { preDays: 0, postDays, minEvents: 5 }, - vaultCutoffDate, - }); - - expect(result.status).toBe('ok'); - if (result.status !== 'ok') { - return; - } - expect(ledger.rows).toHaveLength(1); - - const cars = result.study.eventCars; - const usHalfDayIdx = cars.entityIds.findIndex((id, i) => id === 11 && cars.dates[i] === '2022-11-28'); - expect(usHalfDayIdx).toBeGreaterThanOrEqual(0); - expect(cars.entityIds.some((id, i) => id === 11 && cars.dates[i] === '2022-11-25')).toBe(false); - - const sessionDates = built.input.sessionDates; - const d = sessionDates.indexOf('2022-11-28'); - expect(cars.dayIndices[usHalfDayIdx]).toBe(d); - const r = built.input.entityReturns.get(11)!; - const b = built.input.benchmarkReturns!; - let expectedCar = 0; - for (let k = 0; k <= postDays; k += 1) { - expectedCar += (r[d + k] as number) - (b[d + k] as number); - } - expect(cars.cars[usHalfDayIdx]!).toBeCloseTo(expectedCar, 12); - expect(Number.isFinite(result.deflatedSharpe.dsr ?? Number.NaN)).toBe(true); - }); -}); diff --git a/libs/research/test/event-panel.test.ts b/libs/research/test/event-panel.test.ts deleted file mode 100644 index a5979670..00000000 --- a/libs/research/test/event-panel.test.ts +++ /dev/null @@ -1,1181 +0,0 @@ -import { describe, expect, it } from 'bun:test'; -import { readFileSync } from 'node:fs'; -import { eventDayIndex, eventStudy } from '@stock-bot/calculations'; -import { - EventPanelError, - buildEventStudyInput, - eventsTableToEventRows, - type BarRecord, - type EventObservation, - type EventPanelErrorCode, - type EventStudyExchangeCalendars, - type Table, -} from '@stock-bot/research'; -import { - EventPanelError as SubpathEventPanelError, - buildEventStudyInput as subpathBuildEventStudyInput, - eventsTableToEventRows as subpathEventsTableToEventRows, -} from '@stock-bot/research/event-panel'; - -function makeUtcMs(date: string, hourUtc = 21, minuteUtc = 0, secondUtc = 0, ms = 0): number { - const [y, m, d] = date.split('-').map(Number); - return Date.UTC(y!, m! - 1, d!, hourUtc, minuteUtc, secondUtc, ms); -} - -function makeBusinessDates(startDate: string, count: number): string[] { - const out: string[] = new Array(count); - const current = new Date(`${startDate}T00:00:00.000Z`); - let written = 0; - while (written < count) { - const day = current.getUTCDay(); - if (day !== 0 && day !== 6) { - out[written] = current.toISOString().slice(0, 10); - written += 1; - } - current.setUTCDate(current.getUTCDate() + 1); - } - return out; -} - -function makeBar(listingId: number, date: string, close: number, hourUtc = 21): BarRecord { - const ts = makeUtcMs(date, hourUtc, 0, 0, 0); - return { - listingId, - ts, - open: close, - high: close, - low: close, - close, - volume: 1_000, - vwap: close, - knownAt: ts, - }; -} - -function makeExchangeCalendars( - listingIds: readonly number[], - dates: readonly string[], - hourUtc = 21 -): EventStudyExchangeCalendars { - const sessions = dates.map(date => ({ date, closeTs: makeUtcMs(date, hourUtc) })); - const listingCalendarId = new Map(); - for (const id of listingIds) { - listingCalendarId.set(id, 'XNYS'); - } - return { - calendars: new Map([['XNYS', sessions]]), - listingCalendarId, - }; -} - -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 shuffle(items: readonly T[], seed: number): T[] { - const copy = [...items]; - const rand = createSeededRng(seed); - for (let i = copy.length - 1; i > 0; i -= 1) { - const j = Math.floor(rand() * (i + 1)); - const tmp = copy[i]!; - copy[i] = copy[j]!; - copy[j] = tmp; - } - return copy; -} - -function expectEventPanelError(fn: () => unknown, code: EventPanelErrorCode): EventPanelError { - try { - fn(); - } catch (err) { - expect(err).toBeInstanceOf(EventPanelError); - const typed = err as EventPanelError; - expect(typed.code).toBe(code); - return typed; - } - throw new Error(`Expected EventPanelError(${code}), but function did not throw.`); -} - -function expectBitIdenticalFloat64(actual: Float64Array, expected: Float64Array): void { - expect(actual.length).toBe(expected.length); - const aBytes = new Uint8Array(actual.buffer, actual.byteOffset, actual.byteLength); - const eBytes = new Uint8Array(expected.buffer, expected.byteOffset, expected.byteLength); - expect(aBytes).toEqual(eBytes); -} - -function expectBitIdenticalEventStudyInput( - actual: ReturnType['input'], - expected: ReturnType['input'] -): void { - expect(actual.sessionDates).toEqual(expected.sessionDates); - expect(actual.events).toEqual(expected.events); - expect(Array.from(actual.entityReturns.keys())).toEqual(Array.from(expected.entityReturns.keys())); - for (const [id, expectedSeries] of expected.entityReturns) { - const actualSeries = actual.entityReturns.get(id); - expect(actualSeries).toBeInstanceOf(Float64Array); - expectBitIdenticalFloat64(actualSeries as Float64Array, expectedSeries as Float64Array); - } - if (expected.benchmarkReturns === undefined) { - expect(actual.benchmarkReturns).toBeUndefined(); - } else { - expect(actual.benchmarkReturns).toBeInstanceOf(Float64Array); - expectBitIdenticalFloat64( - actual.benchmarkReturns as Float64Array, - expected.benchmarkReturns as Float64Array - ); - } -} - -describe('@stock-bot/research event-panel exports and browser safety', () => { - it('exposes identical symbols from root and ./event-panel subpath', () => { - expect(buildEventStudyInput).toBe(subpathBuildEventStudyInput); - expect(eventsTableToEventRows).toBe(subpathEventsTableToEventRows); - expect(EventPanelError).toBe(SubpathEventPanelError); - }); - - it('has zero node:* imports, zero bare process access, and unchanged package dependencies', () => { - for (const relPath of ['../src/event-panel.ts', '../src/panel-shared.ts']) { - const src = readFileSync(new URL(relPath, import.meta.url), 'utf8'); - expect(src).not.toMatch(/from\s+['"]node:/); - expect(src).not.toMatch(/require\s*\(\s*['"]node:/); - expect(src).not.toMatch(/\bprocess\./); - } - - const pkg = JSON.parse( - readFileSync(new URL('../package.json', import.meta.url), 'utf8') - ) as { dependencies?: Record; exports?: Record }; - expect(pkg.exports?.['./event-panel']).toBe('./src/event-panel.ts'); - expect(Object.keys(pkg.dependencies ?? {}).sort()).toEqual([ - '@stock-bot/calculations', - '@stock-bot/stock-config', - '@stock-bot/types', - 'zod', - ]); - }); -}); - -describe('eventsTableToEventRows', () => { - const baseColumns = [ - 'listing_id', - 'ts', - 'known_at', - 'known_at_source', - 'kind', - 'subtype', - 'payload_json', - ]; - - it('maps valid rows, normalizes -0, and preserves null/string subtypes', () => { - const table: Table = { - columns: baseColumns, - rows: [ - { - listing_id: -0, - ts: makeUtcMs('2024-01-05', 22), - known_at: -0, - known_at_source: 'exact', - kind: 'filing', - subtype: '10-Q', - payload_json: '{}', - }, - { - listing_id: 42, - ts: makeUtcMs('2024-01-08', 22), - known_at: makeUtcMs('2024-01-08', 22), - known_at_source: 'exact', - kind: 'earnings', - subtype: null, - payload_json: '{}', - }, - ], - }; - - const rows = eventsTableToEventRows(table); - expect(rows).toEqual([ - { listingId: 0, knownAt: 0, kind: 'filing', subtype: '10-Q' }, - { listingId: 42, knownAt: makeUtcMs('2024-01-08', 22), kind: 'earnings', subtype: null }, - ]); - expect(Object.is(rows[0]!.listingId, 0)).toBe(true); - expect(Object.is(rows[0]!.knownAt, 0)).toBe(true); - }); - - it('applies exact-match kinds and subtypes allow-lists', () => { - const table: Table = { - columns: ['listing_id', 'known_at', 'kind', 'subtype'], - rows: [ - { listing_id: 1, known_at: 1000, kind: 'filing', subtype: '10-Q' }, - { listing_id: 2, known_at: 2000, kind: 'filing', subtype: '10-K' }, - { listing_id: 3, known_at: 3000, kind: 'filing', subtype: null }, - { listing_id: 4, known_at: 4000, kind: 'earnings', subtype: '10-Q' }, - ], - }; - - expect(eventsTableToEventRows(table, { kinds: ['filing'] })).toHaveLength(3); - expect(eventsTableToEventRows(table, { subtypes: ['10-Q'] })).toEqual([ - { listingId: 1, knownAt: 1000, kind: 'filing', subtype: '10-Q' }, - { listingId: 4, knownAt: 4000, kind: 'earnings', subtype: '10-Q' }, - ]); - expect( - eventsTableToEventRows(table, { kinds: ['filing'], subtypes: ['10-Q', '10-K'] }) - ).toEqual([ - { listingId: 1, knownAt: 1000, kind: 'filing', subtype: '10-Q' }, - { listingId: 2, knownAt: 2000, kind: 'filing', subtype: '10-K' }, - ]); - }); - - it('validates all rows upfront even when they would be filtered out', () => { - const table: Table = { - columns: ['listing_id', 'known_at', 'kind', 'subtype'], - rows: [ - { listing_id: 1, known_at: 1000, kind: 'filing', subtype: '10-Q' }, - { listing_id: 2, known_at: Number.NaN, kind: 'earnings', subtype: 'Q1' }, - ], - }; - - expectEventPanelError( - () => eventsTableToEventRows(table, { kinds: ['filing'] }), - 'invalid_event' - ); - }); - - it('rejects malformed table, missing columns, invalid filter options, and malformed rows', () => { - expectEventPanelError( - () => eventsTableToEventRows(null as unknown as Table), - 'invalid_input' - ); - expectEventPanelError( - () => eventsTableToEventRows({ columns: ['listing_id', 'known_at', 'kind'], rows: [] }), - 'invalid_input' - ); - - const validEmptyTable: Table = { - columns: ['listing_id', 'known_at', 'kind', 'subtype'], - rows: [], - }; - expectEventPanelError( - () => eventsTableToEventRows(validEmptyTable, { kinds: [] }), - 'invalid_option' - ); - expectEventPanelError( - () => eventsTableToEventRows(validEmptyTable, { subtypes: [] }), - 'invalid_option' - ); - expectEventPanelError( - () => - eventsTableToEventRows(validEmptyTable, { - kinds: ['unknown_kind' as unknown as 'filing'], - }), - 'invalid_option' - ); - expectEventPanelError( - () => - eventsTableToEventRows(validEmptyTable, { - subtypes: [123 as unknown as string], - }), - 'invalid_option' - ); - expectEventPanelError( - () => eventsTableToEventRows(validEmptyTable, [] as unknown as Record), - 'invalid_option' - ); - - const badRows: unknown[] = [ - null, - { listing_id: 1, known_at: 1000, kind: 'filing' }, // missing subtype - { listing_id: 1.5, known_at: 1000, kind: 'filing', subtype: '10-Q' }, - { listing_id: 2_147_483_648, known_at: 1000, kind: 'filing', subtype: '10-Q' }, - { listing_id: 1, known_at: Number.POSITIVE_INFINITY, kind: 'filing', subtype: '10-Q' }, - { listing_id: 1, known_at: 1000, kind: 'bad_kind', subtype: '10-Q' }, - { listing_id: 1, known_at: 1000, kind: 'filing', subtype: 99 }, - ]; - for (const badRow of badRows) { - expectEventPanelError( - () => - eventsTableToEventRows({ - columns: ['listing_id', 'known_at', 'kind', 'subtype'], - rows: [badRow as Table['rows'][number]], - }), - 'invalid_event' - ); - } - }); -}); - -describe('buildEventStudyInput — returns, PIT anchoring, Vault fence, and invariants', () => { - it('computes consecutive-session simple returns, sets NaN on gaps/resumption, and handles equal_weight benchmark', () => { - const dates = makeBusinessDates('2024-01-02', 5); // 5 sessions: d0..d4 - const bars: BarRecord[] = [ - // Listing 10: present on all 5 sessions - makeBar(10, dates[0]!, 100), - makeBar(10, dates[1]!, 110), // +10% - makeBar(10, dates[2]!, 99), // -10% - makeBar(10, dates[3]!, 99), // 0% - makeBar(10, dates[4]!, 108.9), // +10% - // Listing 20: missing on d2 -> d2 is NaN AND d3 (resumption) is NaN; d4 is 120/100 - 1 = +20% - makeBar(20, dates[0]!, 50), - makeBar(20, dates[1]!, 60), // +20% - makeBar(20, dates[3]!, 100), - makeBar(20, dates[4]!, 120), // +20% - ]; - - const events: EventObservation[] = [ - { listingId: 10, knownAt: makeUtcMs(dates[1]!, 21), kind: 'filing', subtype: '10-Q' }, - ]; - - const exchangeCalendars = makeExchangeCalendars([10, 20], dates); - - const resNone = buildEventStudyInput({ - bars, - events, - vaultCutoffDate: '2024-02-01', - exchangeCalendars, - }); - - expect(resNone.input.sessionDates).toEqual(dates); - expect('benchmarkReturns' in resNone.input).toBe(false); - expect(Array.from(resNone.input.entityReturns.keys())).toEqual([10, 20]); - - const r10 = resNone.input.entityReturns.get(10)!; - const r20 = resNone.input.entityReturns.get(20)!; - expect(Number.isNaN(r10[0]!)).toBe(true); - expect(r10[1]!).toBeCloseTo(0.1, 12); - expect(r10[2]!).toBeCloseTo(-0.1, 12); - expect(r10[3]!).toBe(0); - expect(r10[4]!).toBeCloseTo(0.1, 12); - - expect(Number.isNaN(r20[0]!)).toBe(true); - expect(r20[1]!).toBeCloseTo(0.2, 12); - expect(Number.isNaN(r20[2]!)).toBe(true); - expect(Number.isNaN(r20[3]!)).toBe(true); - expect(r20[4]!).toBeCloseTo(0.2, 12); - - const resEq = buildEventStudyInput({ - bars, - events, - vaultCutoffDate: '2024-02-01', - benchmark: 'equal_weight', - exchangeCalendars, - }); - expect(resEq.input.benchmarkReturns).toBeInstanceOf(Float64Array); - const b = resEq.input.benchmarkReturns!; - expect(Number.isNaN(b[0]!)).toBe(true); - expect(b[1]!).toBeCloseTo(0.15, 12); // (0.1 + 0.2) / 2 - expect(b[2]!).toBeCloseTo(-0.1, 12); // only listing 10 finite - expect(b[3]!).toBe(0); // only listing 10 finite - expect(b[4]!).toBeCloseTo(0.15, 12); // (0.1 + 0.2) / 2 - }); - - it('writes NaN (never Infinity) for non-positive, non-finite, or overflowing closes and passes eventStudy', () => { - const dates = makeBusinessDates('2024-01-02', 6); - const bars: BarRecord[] = [ - makeBar(1, dates[0]!, 10), - makeBar(1, dates[1]!, 0), // non-positive - makeBar(1, dates[2]!, -5), // non-positive - makeBar(1, dates[3]!, Number.NaN), // non-finite - makeBar(1, dates[4]!, 1e-308), - makeBar(1, dates[5]!, 1e308), // close[5]/close[4] overflows to +Infinity - ]; - - const res = buildEventStudyInput({ - bars, - events: [], - vaultCutoffDate: '2024-02-01', - benchmark: 'equal_weight', - exchangeCalendars: makeExchangeCalendars([1], dates), - }); - - const series = res.input.entityReturns.get(1)!; - for (let t = 0; t < dates.length; t += 1) { - expect(Number.isNaN(series[t]!)).toBe(true); - expect(Number.isNaN(res.input.benchmarkReturns![t]!)).toBe(true); - } - expect(res.diagnostics.nonPositiveCloseReturns).toBe(5); - - // Must not throw NON_FINITE_RETURN in eventStudy. - const study = eventStudy(res.input, { preDays: 1, postDays: 1, minEvents: 1 }); - expect(study.status).toBe('insufficient_data'); - }); - - it('anchors after-close, weekend, and holiday events to the next session and matches eventDayIndex exactly', () => { - // Include a Friday -> Monday weekend and a Wednesday holiday (skip 2024-01-10). - const dates = ['2024-01-05', '2024-01-08', '2024-01-09', '2024-01-11', '2024-01-12']; - const bars: BarRecord[] = []; - for (const d of dates) { - bars.push(makeBar(1, d, 100, 21)); // 16:00 ET = 21:00 UTC - bars.push(makeBar(2, d, 50, 21)); - } - - const sessionMaxTs = Float64Array.from(dates.map(d => makeUtcMs(d, 21))); - const probeTimestamps: Array<{ listingId: number; knownAt: number; expectedIdx: number | null }> = [ - // Pre-market on first session -> day 0 - { listingId: 1, knownAt: makeUtcMs('2024-01-05', 13), expectedIdx: 0 }, - // Exact close on Friday -> day 0 - { listingId: 2, knownAt: makeUtcMs('2024-01-05', 21), expectedIdx: 0 }, - // After-close Friday 17:00 ET (22:00 UTC) -> Monday (day 1) - { listingId: 1, knownAt: makeUtcMs('2024-01-05', 22), expectedIdx: 1 }, - // Saturday morning -> Monday (day 1) - { listingId: 2, knownAt: makeUtcMs('2024-01-06', 14), expectedIdx: 1 }, - // After-close Tuesday 21:00:00.001 UTC -> Thursday (day 3, skipping Wednesday holiday) - { listingId: 1, knownAt: makeUtcMs('2024-01-09', 21, 0, 0, 1), expectedIdx: 3 }, - // Holiday Wednesday -> Thursday (day 3) - { listingId: 2, knownAt: makeUtcMs('2024-01-10', 15), expectedIdx: 3 }, - // After-close Friday last session (22:00 UTC < Saturday cutoff 00:00Z) -> droppedAfterLastSession - { listingId: 1, knownAt: makeUtcMs('2024-01-12', 22), expectedIdx: null }, - ]; - - // Verify exact equivalence with eventDayIndex from @stock-bot/calculations. - for (const p of probeTimestamps) { - const ref = eventDayIndex(sessionMaxTs, p.knownAt); - if (p.expectedIdx === null) { - expect(ref).toEqual({ status: 'no_session', reason: 'after_last_session' }); - } else { - expect(ref).toEqual({ status: 'ok', dayIndex: p.expectedIdx }); - } - } - - const events: EventObservation[] = probeTimestamps.map(p => ({ - listingId: p.listingId, - knownAt: p.knownAt, - kind: 'filing', - subtype: '10-Q', - })); - - const res = buildEventStudyInput({ - bars, - events, - vaultCutoffDate: '2024-01-13', - exchangeCalendars: makeExchangeCalendars([1, 2], dates), - }); - - expect(res.input.events).toEqual([ - { entityId: 1, dayIndex: 0 }, - { entityId: 2, dayIndex: 0 }, - { entityId: 1, dayIndex: 1 }, - { entityId: 2, dayIndex: 1 }, - { entityId: 1, dayIndex: 3 }, - { entityId: 2, dayIndex: 3 }, - ]); - expect(res.diagnostics.droppedAfterLastSession).toBe(1); - expect(res.diagnostics.vaultExcludedEvents).toBe(0); - expect(res.diagnostics.droppedUnknownListing).toBe(0); - expect(res.diagnostics.duplicateEvents).toBe(0); - }); - - it('deduplicates exact duplicate bars and rejects conflicting duplicates', () => { - const dates = makeBusinessDates('2024-01-02', 3); - const b0 = makeBar(1, dates[0]!, 10); - const b1 = makeBar(1, dates[1]!, 12); - const b2 = makeBar(1, dates[2]!, Number.NaN); - - const exchangeCalendars = makeExchangeCalendars([1], dates); - - const exactDup = buildEventStudyInput({ - bars: [b0, { ...b0 }, b1, b2, { ...b2 }], - events: [], - vaultCutoffDate: '2024-02-01', - exchangeCalendars, - }); - expect(exactDup.diagnostics.duplicateBars).toBe(2); - expect(exactDup.input.entityReturns.get(1)![1]).toBeCloseTo(0.2, 12); - - // Conflicting close - expectEventPanelError( - () => - buildEventStudyInput({ - bars: [b0, { ...b0, close: 10.01 }, b1], - events: [], - vaultCutoffDate: '2024-02-01', - exchangeCalendars, - }), - 'duplicate_bar' - ); - - // Conflicting timestamp on same UTC date - expectEventPanelError( - () => - buildEventStudyInput({ - bars: [b0, { ...b0, ts: b0.ts + 1_000 }, b1], - events: [], - vaultCutoffDate: '2024-02-01', - exchangeCalendars, - }), - 'duplicate_bar' - ); - }); - - it('enforces Vault exclusion without ever reading post-cutoff bar.close and obeys event conservation', () => { - const dates = makeBusinessDates('2024-01-02', 6); // d0..d3 pre-cutoff, d4..d5 post-cutoff - const vaultCutoffDate = dates[4]!; - let postCutoffCloseReads = 0; - - const makeTrappedPostCutoffBar = (listingId: number, date: string): BarRecord => { - const ts = makeUtcMs(date, 21); - const bar = { - listingId, - ts, - open: 999, - high: 999, - low: 999, - volume: 100, - vwap: 999, - knownAt: ts, - }; - Object.defineProperty(bar, 'close', { - enumerable: true, - get() { - postCutoffCloseReads += 1; - throw new Error('Vault violation: post-cutoff bar.close was accessed!'); - }, - }); - return bar as unknown as BarRecord; - }; - - const preBars: BarRecord[] = []; - for (let t = 0; t < 4; t += 1) { - preBars.push(makeBar(10, dates[t]!, 100 + t * 5)); - } - const postBars: BarRecord[] = [ - makeTrappedPostCutoffBar(10, dates[4]!), - makeTrappedPostCutoffBar(10, dates[5]!), - makeTrappedPostCutoffBar(99, dates[4]!), // listing only exists post-cutoff - ]; - - const events: EventObservation[] = [ - // Valid event -> day 1 - { listingId: 10, knownAt: makeUtcMs(dates[0]!, 22), kind: 'filing', subtype: '10-Q' }, - // Duplicate event anchoring to day 1 (different timestamp on same pre-market morning) - { listingId: 10, knownAt: makeUtcMs(dates[1]!, 14), kind: 'filing', subtype: '10-Q' }, - // Unknown listing (pre-cutoff) -> droppedUnknownListing - { listingId: 99, knownAt: makeUtcMs(dates[1]!, 14), kind: 'filing', subtype: '10-Q' }, - // After last pre-cutoff session close, but still < vaultCutoffMs -> droppedAfterLastSession - { listingId: 10, knownAt: makeUtcMs(dates[3]!, 22), kind: 'filing', subtype: '10-Q' }, - // Exact vaultCutoffDate 00:00:00.000Z (even for unknown listing) -> vaultExcludedEvents - { listingId: 99, knownAt: makeUtcMs(vaultCutoffDate, 0), kind: 'filing', subtype: '10-Q' }, - // After vaultCutoffDate -> vaultExcludedEvents - { listingId: 10, knownAt: makeUtcMs(dates[5]!, 22), kind: 'filing', subtype: '10-Q' }, - ]; - - const exchangeCalendars = makeExchangeCalendars([10], dates); - - const trappedResult = buildEventStudyInput({ - bars: [...preBars, ...postBars], - events, - vaultCutoffDate, - benchmark: 'equal_weight', - exchangeCalendars, - }); - - expect(postCutoffCloseReads).toBe(0); - expect(trappedResult.input.sessionDates).toEqual(dates.slice(0, 4)); - expect(trappedResult.input.events).toEqual([{ entityId: 10, dayIndex: 1 }]); - expect(trappedResult.diagnostics).toEqual({ - vaultExcludedDates: 2, - vaultExcludedEvents: 2, - droppedUnknownListing: 1, - droppedAfterLastSession: 1, - droppedMissingCalendarSession: 0, - duplicateEvents: 1, - duplicateBars: 0, - nonPositiveCloseReturns: 0, - }); - - // Event conservation identity - const d = trappedResult.diagnostics; - expect( - trappedResult.input.events.length + - d.vaultExcludedEvents + - d.droppedUnknownListing + - d.droppedAfterLastSession + - d.droppedMissingCalendarSession + - d.duplicateEvents - ).toBe(events.length); - - // Poisoned post-cutoff bars/events leave pre-cutoff input byte-identical - const poisonedResult = buildEventStudyInput({ - bars: [ - ...preBars, - makeBar(10, dates[4]!, 999_999), - makeBar(10, dates[5]!, Number.NaN), - ], - events: [ - ...events.slice(0, 4), - { listingId: 10, knownAt: makeUtcMs(dates[4]!, 22), kind: 'filing', subtype: '10-K' }, - ], - vaultCutoffDate, - benchmark: 'equal_weight', - exchangeCalendars, - }); - expectBitIdenticalEventStudyInput(poisonedResult.input, trappedResult.input); - }); - - it('is bit-identical under arbitrary permutations and never mutates frozen inputs', () => { - const dates = makeBusinessDates('2024-01-02', 8); - const bars: BarRecord[] = []; - const events: EventObservation[] = []; - for (const lid of [30, 10, 20]) { - for (let t = 0; t < dates.length; t += 1) { - if (lid === 20 && t === 3) { - continue; // gap - } - bars.push(makeBar(lid, dates[t]!, 20 + lid + t * 0.75)); - } - events.push({ - listingId: lid, - knownAt: makeUtcMs(dates[1]!, 22), - kind: 'filing', - subtype: '10-Q', - }); - events.push({ - listingId: lid, - knownAt: makeUtcMs(dates[4]!, 15), - kind: 'filing', - subtype: '8-K', - }); - } - - const exchangeCalendars = makeExchangeCalendars([10, 20, 30], dates); - const frozenBars = Object.freeze(bars.map(b => Object.freeze({ ...b }))); - const frozenEvents = Object.freeze(events.map(e => Object.freeze({ ...e }))); - const frozenParams = Object.freeze({ - bars: frozenBars, - events: frozenEvents, - vaultCutoffDate: dates[6]!, - benchmark: 'equal_weight' as const, - exchangeCalendars, - }); - - const baseline = buildEventStudyInput(frozenParams); - for (const seed of [1, 42, 999, 20261129]) { - const permuted = buildEventStudyInput({ - bars: shuffle(bars, seed), - events: shuffle(events, seed + 17), - vaultCutoffDate: dates[6]!, - benchmark: 'equal_weight', - exchangeCalendars, - }); - expectBitIdenticalEventStudyInput(permuted.input, baseline.input); - expect(permuted.diagnostics).toEqual(baseline.diagnostics); - expect(Array.from(permuted.input.entityReturns.keys())).toEqual([10, 20, 30]); - } - }); - - it('handles empty and post-cutoff-only inputs cleanly', () => { - const emptyCalendars: EventStudyExchangeCalendars = { calendars: {}, listingCalendarId: {} }; - const emptyRes = buildEventStudyInput({ - bars: [], - events: [ - { listingId: 1, knownAt: makeUtcMs('2024-01-05', 22), kind: 'filing', subtype: '10-Q' }, - { listingId: 1, knownAt: makeUtcMs('2024-02-01', 0), kind: 'filing', subtype: '10-Q' }, - ], - vaultCutoffDate: '2024-02-01', - exchangeCalendars: emptyCalendars, - }); - expect(emptyRes.input.sessionDates).toEqual([]); - expect(emptyRes.input.entityReturns.size).toBe(0); - expect(emptyRes.input.events).toEqual([]); - expect('benchmarkReturns' in emptyRes.input).toBe(false); - expect(emptyRes.diagnostics).toEqual({ - vaultExcludedDates: 0, - vaultExcludedEvents: 1, - droppedUnknownListing: 1, - droppedAfterLastSession: 0, - droppedMissingCalendarSession: 0, - duplicateEvents: 0, - duplicateBars: 0, - nonPositiveCloseReturns: 0, - }); - - const postOnlyRes = buildEventStudyInput({ - bars: [makeBar(1, '2024-02-01', 100), makeBar(1, '2024-02-02', 105)], - events: [], - vaultCutoffDate: '2024-02-01', - benchmark: 'equal_weight', - exchangeCalendars: emptyCalendars, - }); - expect(postOnlyRes.input.sessionDates).toEqual([]); - expect(postOnlyRes.input.benchmarkReturns).toEqual(new Float64Array(0)); - expect(postOnlyRes.diagnostics.vaultExcludedDates).toBe(2); - }); - - it('throws typed EventPanelError for every remaining validation error code', () => { - const emptyCalendars: EventStudyExchangeCalendars = { calendars: {}, listingCalendarId: {} }; - expectEventPanelError( - () => buildEventStudyInput(null as unknown as Parameters[0]), - 'invalid_input' - ); - expectEventPanelError( - () => - buildEventStudyInput({ - bars: 'not-array' as unknown as BarRecord[], - events: [], - vaultCutoffDate: '2024-02-01', - exchangeCalendars: emptyCalendars, - }), - 'invalid_input' - ); - expectEventPanelError( - () => - buildEventStudyInput({ - bars: [], - events: 'not-array' as unknown as EventObservation[], - vaultCutoffDate: '2024-02-01', - exchangeCalendars: emptyCalendars, - }), - 'invalid_input' - ); - - expectEventPanelError( - () => - buildEventStudyInput({ - bars: [], - events: [], - vaultCutoffDate: '2024-02-30', - exchangeCalendars: emptyCalendars, - }), - 'invalid_date' - ); - expectEventPanelError( - () => - buildEventStudyInput({ - bars: [], - events: [], - vaultCutoffDate: '2024/02/01', - exchangeCalendars: emptyCalendars, - }), - 'invalid_date' - ); - - expectEventPanelError( - () => - buildEventStudyInput({ - bars: [], - events: [], - vaultCutoffDate: '2024-02-01', - benchmark: 'cap_weight' as unknown as 'none', - exchangeCalendars: emptyCalendars, - }), - 'invalid_option' - ); - expectEventPanelError( - () => - buildEventStudyInput({ - bars: [], - events: [], - vaultCutoffDate: '2024-02-01', - benchmark: null as unknown as 'none', - exchangeCalendars: emptyCalendars, - }), - 'invalid_option' - ); - expectEventPanelError( - () => - buildEventStudyInput({ - bars: [], - events: [], - vaultCutoffDate: '2024-02-01', - exchangeCalendars: undefined as unknown as EventStudyExchangeCalendars, - }), - 'invalid_option' - ); - - const goodBar = makeBar(1, '2024-01-05', 10); - for (const badBar of [ - null, - { ...goodBar, listingId: 1.5 }, - { ...goodBar, ts: Number.NaN }, - { ...goodBar, knownAt: Number.POSITIVE_INFINITY }, - { ...goodBar, close: '10' }, - ]) { - expectEventPanelError( - () => - buildEventStudyInput({ - bars: [badBar as BarRecord], - events: [], - vaultCutoffDate: '2024-02-01', - exchangeCalendars: emptyCalendars, - }), - 'invalid_bar' - ); - } - - const goodEv: EventObservation = { - listingId: 1, - knownAt: makeUtcMs('2024-01-05', 22), - kind: 'filing', - subtype: '10-Q', - }; - for (const badEv of [ - null, - { ...goodEv, listingId: 2_147_483_648 }, - { ...goodEv, knownAt: Number.NaN }, - { ...goodEv, kind: 'not_a_kind' }, - { ...goodEv, subtype: 42 }, - ]) { - expectEventPanelError( - () => - buildEventStudyInput({ - bars: [], - events: [badEv as EventObservation], - vaultCutoffDate: '2024-02-01', - exchangeCalendars: emptyCalendars, - }), - 'invalid_event' - ); - } - }); - - it('uses caller-supplied exchangeCalendars for half-day US vs CA close times and cross-border holidays', () => { - // Black Friday 2024-11-29: curated bars_1d.ts stamps BOTH NYSE and TSX at 16:00 ET (21:00 UTC), - // even though NYSE closes early at 13:00 ET (18:00 UTC) while TSX closes at 16:00 ET (21:00 UTC). - // Also include US Thanksgiving 2024-11-28 (TSX open, NYSE closed). - const sharedDates = ['2024-11-27', '2024-11-28', '2024-11-29', '2024-12-02', '2024-12-03']; - const nyseId = 10_001; - const tsxId = 50_001; - - const bars: BarRecord[] = [ - // NYSE bars (closed 2024-11-28; half-day 2024-11-29 still stamped 21:00 UTC by curator) - makeBar(nyseId, '2024-11-27', 100, 21), - makeBar(nyseId, '2024-11-29', 102, 21), - makeBar(nyseId, '2024-12-02', 105, 21), - makeBar(nyseId, '2024-12-03', 106, 21), - // TSX bars (open all 5 days, stamped 21:00 UTC) - makeBar(tsxId, '2024-11-27', 50, 21), - makeBar(tsxId, '2024-11-28', 50.5, 21), - makeBar(tsxId, '2024-11-29', 51, 21), - makeBar(tsxId, '2024-12-02', 52, 21), - makeBar(tsxId, '2024-12-03', 52.5, 21), - ]; - - const nyseCalendar = [ - { date: '2024-11-27', closeTs: makeUtcMs('2024-11-27', 21) }, // 16:00 ET - { date: '2024-11-29', closeTs: makeUtcMs('2024-11-29', 18) }, // 13:00 ET early close - { date: '2024-12-02', closeTs: makeUtcMs('2024-12-02', 21) }, // 16:00 ET - { date: '2024-12-03', closeTs: makeUtcMs('2024-12-03', 21) }, // 16:00 ET - ]; - const tsxCalendar = [ - { date: '2024-11-27', closeTs: makeUtcMs('2024-11-27', 21) }, // 16:00 ET - { date: '2024-11-28', closeTs: makeUtcMs('2024-11-28', 21) }, // 16:00 ET (US holiday) - { date: '2024-11-29', closeTs: makeUtcMs('2024-11-29', 21) }, // 16:00 ET (normal close) - { date: '2024-12-02', closeTs: makeUtcMs('2024-12-02', 21) }, // 16:00 ET - { date: '2024-12-03', closeTs: makeUtcMs('2024-12-03', 21) }, // 16:00 ET - ]; - - // Filing published at 14:00 ET (19:00 UTC) on Friday 2024-11-29: - // - NYSE already closed at 13:00 ET (18:00 UTC) -> MUST anchor to Monday 2024-12-02 (index 3). - // - TSX closes at 16:00 ET (21:00 UTC) -> anchors to Friday 2024-11-29 (index 2). - // Filing published at 12:30 ET (17:30 UTC) on Friday 2024-11-29 for NYSE -> anchors to Friday 2024-11-29 (index 2). - // Filing published on US Thanksgiving 2024-11-28 at 10:00 ET (15:00 UTC): - // - NYSE closed -> anchors to Friday 2024-11-29 (index 2, collapses with 12:30 ET NYSE event). - // - TSX open -> anchors to Thursday 2024-11-28 (index 1). - const events: EventObservation[] = [ - { listingId: nyseId, knownAt: makeUtcMs('2024-11-29', 19), kind: 'filing', subtype: '10-q' }, - { listingId: tsxId, knownAt: makeUtcMs('2024-11-29', 19), kind: 'filing', subtype: 'interim_financial_statements' }, - { listingId: nyseId, knownAt: makeUtcMs('2024-11-29', 17, 30), kind: 'filing', subtype: '10-q' }, - { listingId: nyseId, knownAt: makeUtcMs('2024-11-28', 15), kind: 'filing', subtype: '10-q' }, - { listingId: tsxId, knownAt: makeUtcMs('2024-11-28', 15), kind: 'filing', subtype: 'interim_financial_statements' }, - ]; - - const mapResult = buildEventStudyInput({ - bars, - events, - vaultCutoffDate: '2024-12-04', - exchangeCalendars: { - calendars: new Map([ - ['XNYS', nyseCalendar], - ['XTSE', tsxCalendar], - ]), - listingCalendarId: new Map([ - [nyseId, 'XNYS'], - [tsxId, 'XTSE'], - ]), - }, - }); - - expect(mapResult.input.sessionDates).toEqual(sharedDates); - expect(mapResult.input.events).toEqual([ - { entityId: tsxId, dayIndex: 1 }, // 2024-11-28 - { entityId: nyseId, dayIndex: 2 }, // 2024-11-29 (12:30 ET & Thanksgiving deduped) - { entityId: tsxId, dayIndex: 2 }, // 2024-11-29 (14:00 ET still before TSX 16:00 ET close) - { entityId: nyseId, dayIndex: 3 }, // 2024-12-02 (14:00 ET after NYSE 13:00 ET close) - ]); - // Cross-border holiday: NYSE was closed on Thanksgiving 2024-11-28, so its Friday - // 2024-11-29 return (index 2) is a valid 1-session NYSE return (102 / 100 - 1 = 0.02). - const nyseRets = mapResult.input.entityReturns.get(nyseId)!; - expect(Number.isNaN(nyseRets[1]!)).toBe(true); - expect(nyseRets[2]!).toBeCloseTo(0.02, 12); - expect(nyseRets[3]!).toBeCloseTo(105 / 102 - 1, 12); - expect(mapResult.diagnostics.duplicateEvents).toBe(1); - expect(mapResult.diagnostics.droppedAfterLastSession).toBe(0); - expect(mapResult.diagnostics.droppedMissingCalendarSession).toBe(0); - - // Record-based calendars with shuffled sessions/bars/events produce bit-identical output. - const recordResult = buildEventStudyInput({ - bars: shuffle(bars, 7), - events: shuffle(events, 11), - vaultCutoffDate: '2024-12-04', - exchangeCalendars: { - calendars: { - XNYS: shuffle(nyseCalendar, 13), - XTSE: shuffle(tsxCalendar, 17), - }, - listingCalendarId: { - [nyseId]: 'XNYS', - [tsxId]: 'XTSE', - }, - }, - }); - expectBitIdenticalEventStudyInput(recordResult.input, mapResult.input); - expect(recordResult.diagnostics).toEqual(mapResult.diagnostics); - - // NYSE-only study: filing at 14:00 ET on 2024-11-29 anchors to Monday 2024-12-02 (index 2 in NYSE-only dates), - // even though curated bars_1d.ts for 2024-11-29 is stamped at 16:00 ET (21:00 UTC). - const nyseOnly = buildEventStudyInput({ - bars: bars.filter(b => b.listingId === nyseId), - events: [ - { listingId: nyseId, knownAt: makeUtcMs('2024-11-29', 19), kind: 'filing', subtype: '10-q' }, - ], - vaultCutoffDate: '2024-12-04', - exchangeCalendars: { - calendars: { XNYS: nyseCalendar }, - listingCalendarId: { [nyseId]: 'XNYS' }, - }, - }); - expect(nyseOnly.input.sessionDates).toEqual(['2024-11-27', '2024-11-29', '2024-12-02', '2024-12-03']); - expect(nyseOnly.input.events).toEqual([{ entityId: nyseId, dayIndex: 2 }]); // 2024-12-02 - }); - - it('enforces Vault fencing, drop counters, and strict validation on exchangeCalendars', () => { - const nyseId = 10_001; - const bars = [ - makeBar(nyseId, '2024-11-27', 100, 21), - makeBar(nyseId, '2024-11-29', 102, 21), - ]; - const nyseCalendar = [ - { date: '2024-11-26', closeTs: makeUtcMs('2024-11-26', 21) }, // before first bar -> droppedMissingCalendarSession - { date: '2024-11-27', closeTs: makeUtcMs('2024-11-27', 21) }, - { date: '2024-11-29', closeTs: makeUtcMs('2024-11-29', 18) }, // 13:00 ET half-day - { date: '2024-12-02', closeTs: makeUtcMs('2024-12-02', 21) }, // post-cutoff (excluded from calendar) - ]; - - const res = buildEventStudyInput({ - bars, - events: [ - // Anchors to 2024-11-26 which has no bar in sessionDates -> droppedMissingCalendarSession - { listingId: nyseId, knownAt: makeUtcMs('2024-11-26', 15), kind: 'filing', subtype: '10-q' }, - // 14:00 ET on 2024-11-29 is after 13:00 ET close; 2024-12-02 is Vault-excluded -> droppedAfterLastSession - { listingId: nyseId, knownAt: makeUtcMs('2024-11-29', 19), kind: 'filing', subtype: '10-q' }, - ], - vaultCutoffDate: '2024-12-02', - exchangeCalendars: { - calendars: { XNYS: nyseCalendar }, - listingCalendarId: { [nyseId]: 'XNYS' }, - }, - }); - - expect(res.input.events).toEqual([]); - expect(res.diagnostics.droppedMissingCalendarSession).toBe(1); - expect(res.diagnostics.droppedAfterLastSession).toBe(1); - expect(res.diagnostics.vaultExcludedEvents).toBe(0); - - // Invalid exchangeCalendars shapes and values - expectEventPanelError( - () => - buildEventStudyInput({ - bars, - events: [], - vaultCutoffDate: '2024-12-02', - exchangeCalendars: null as unknown as NonNullable< - Parameters[0]['exchangeCalendars'] - >, - }), - 'invalid_option' - ); - expectEventPanelError( - () => - buildEventStudyInput({ - bars, - events: [], - vaultCutoffDate: '2024-12-02', - exchangeCalendars: { - calendars: { - XNYS: [{ date: '2024-02-30', closeTs: makeUtcMs('2024-02-28', 21) }], - }, - listingCalendarId: { [nyseId]: 'XNYS' }, - }, - }), - 'invalid_date' - ); - expectEventPanelError( - () => - buildEventStudyInput({ - bars, - events: [], - vaultCutoffDate: '2024-12-02', - exchangeCalendars: { - calendars: { - XNYS: [ - { date: '2024-11-27', closeTs: makeUtcMs('2024-11-27', 21) }, - { date: '2024-11-27', closeTs: makeUtcMs('2024-11-27', 21) }, - ], - }, - listingCalendarId: { [nyseId]: 'XNYS' }, - }, - }), - 'invalid_option' - ); - expectEventPanelError( - () => - buildEventStudyInput({ - bars, - events: [], - vaultCutoffDate: '2024-12-02', - exchangeCalendars: { - calendars: { - XNYS: [ - { date: '2024-11-27', closeTs: makeUtcMs('2024-11-29', 21) }, - { date: '2024-11-29', closeTs: makeUtcMs('2024-11-27', 21) }, - ], - }, - listingCalendarId: { [nyseId]: 'XNYS' }, - }, - }), - 'invalid_option' - ); - expectEventPanelError( - () => - buildEventStudyInput({ - bars, - events: [], - vaultCutoffDate: '2024-12-02', - exchangeCalendars: { - calendars: { XNYS: nyseCalendar }, - listingCalendarId: { [nyseId]: 'UNKNOWN_CAL' }, - }, - }), - 'invalid_option' - ); - expectEventPanelError( - () => - buildEventStudyInput({ - bars, - events: [], - vaultCutoffDate: '2024-12-02', - exchangeCalendars: { - calendars: { XNYS: nyseCalendar }, - listingCalendarId: {}, - }, - }), - 'invalid_option' - ); - }); - - it('rejects incomplete exchange calendar coverage when a calendar starts after or omits pre-Vault bar dates', () => { - const nyseId = 10_001; - const dec2023AndJan2024Bars: BarRecord[] = [ - makeBar(nyseId, '2023-12-28', 100, 21), - makeBar(nyseId, '2023-12-29', 101, 21), - makeBar(nyseId, '2024-01-02', 103, 21), - makeBar(nyseId, '2024-01-03', 104, 21), - ]; - - // Calendar starts on Jan 2, 2024 while bars include December 2023 -> must throw invalid_option. - expectEventPanelError( - () => - buildEventStudyInput({ - bars: dec2023AndJan2024Bars, - events: [ - { - listingId: nyseId, - knownAt: makeUtcMs('2023-12-29', 19), // 14:00 ET on Dec 29 - kind: 'filing', - subtype: '10-q', - }, - ], - vaultCutoffDate: '2024-02-01', - exchangeCalendars: { - calendars: { - XNYS: [ - { date: '2024-01-02', closeTs: makeUtcMs('2024-01-02', 21) }, - { date: '2024-01-03', closeTs: makeUtcMs('2024-01-03', 21) }, - ], - }, - listingCalendarId: { [nyseId]: 'XNYS' }, - }, - }), - 'invalid_option' - ); - - // Calendar omits a mid-history bar session (2023-12-29) -> must throw invalid_option. - expectEventPanelError( - () => - buildEventStudyInput({ - bars: dec2023AndJan2024Bars, - events: [], - vaultCutoffDate: '2024-02-01', - exchangeCalendars: { - calendars: { - XNYS: [ - { date: '2023-12-28', closeTs: makeUtcMs('2023-12-28', 21) }, - { date: '2024-01-02', closeTs: makeUtcMs('2024-01-02', 21) }, - { date: '2024-01-03', closeTs: makeUtcMs('2024-01-03', 21) }, - ], - }, - listingCalendarId: { [nyseId]: 'XNYS' }, - }, - }), - 'invalid_option' - ); - }); - - it('uses exchange-calendar adjacency so a missing open session for all listings yields NaN on the next bar', () => { - // Exchange is open Mon, Tue, Wed, Thu, but bars exist only on Mon, Wed, Thu (Tue missing for ALL listings). - const mon = '2024-01-08'; - const tue = '2024-01-09'; - const wed = '2024-01-10'; - const thu = '2024-01-11'; - const bars: BarRecord[] = [ - makeBar(10, mon, 100), - makeBar(10, wed, 110), - makeBar(10, thu, 121), - makeBar(20, mon, 50), - makeBar(20, wed, 55), - makeBar(20, thu, 60.5), - ]; - - const res = buildEventStudyInput({ - bars, - events: [], - vaultCutoffDate: '2024-02-01', - benchmark: 'equal_weight', - exchangeCalendars: makeExchangeCalendars([10, 20], [mon, tue, wed, thu]), - }); - - // sessionDates contains only observed bar dates [Mon, Wed, Thu]. - expect(res.input.sessionDates).toEqual([mon, wed, thu]); - - const r10 = res.input.entityReturns.get(10)!; - const r20 = res.input.entityReturns.get(20)!; - const bench = res.input.benchmarkReturns!; - - // Mon (index 0): NaN (first bar) - expect(Number.isNaN(r10[0]!)).toBe(true); - expect(Number.isNaN(r20[0]!)).toBe(true); - expect(Number.isNaN(bench[0]!)).toBe(true); - - // Wed (index 1): MUST be NaN because Tue was an open exchange session (not consecutive). - expect(Number.isNaN(r10[1]!)).toBe(true); - expect(Number.isNaN(r20[1]!)).toBe(true); - expect(Number.isNaN(bench[1]!)).toBe(true); - - // Thu (index 2): consecutive with Wed -> valid +10% return. - expect(r10[2]!).toBeCloseTo(0.1, 12); - expect(r20[2]!).toBeCloseTo(0.1, 12); - expect(bench[2]!).toBeCloseTo(0.1, 12); - }); -}); diff --git a/libs/research/test/feature-library.test.ts b/libs/research/test/feature-library.test.ts deleted file mode 100644 index 9315471d..00000000 --- a/libs/research/test/feature-library.test.ts +++ /dev/null @@ -1,1616 +0,0 @@ -import { describe, expect, it } from 'bun:test'; -import { - type DuckDbExecutor, - type DuckDbParam, - FEATURE_FAMILIES, - FEATURE_INPUT_DATASETS, - FEATURE_KINDS, - FEATURE_KNOWN_AT_RULES, - FEATURE_OUTPUT_COLUMNS, - type FeatureDefinition, - FeatureLibraryError, - type FeatureLibraryErrorCode, - RET_1D_V1, - type TableRow, - createFeatureRegistry, - featureDefinitionHash, - featureRef, - parseFeatureRef, - planFeatureBatch, - runFeatureBatch, - validateFeatureDefinition, -} from '@stock-bot/research'; -import { - FEATURE_FAMILIES as subpathFeatureFamilies, - FEATURE_INPUT_DATASETS as subpathFeatureInputDatasets, - FEATURE_KINDS as subpathFeatureKinds, - FEATURE_KNOWN_AT_RULES as subpathFeatureKnownAtRules, - FEATURE_OUTPUT_COLUMNS as subpathFeatureOutputColumns, - FeatureLibraryError as SubpathFeatureLibraryError, - RET_1D_V1 as subpathRet1dV1, - createFeatureRegistry as subpathCreateFeatureRegistry, - featureDefinitionHash as subpathFeatureDefinitionHash, - featureRef as subpathFeatureRef, - parseFeatureRef as subpathParseFeatureRef, - planFeatureBatch as subpathPlanFeatureBatch, - runFeatureBatch as subpathRunFeatureBatch, - validateFeatureDefinition as subpathValidateFeatureDefinition, -} from '@stock-bot/research/feature-library'; - -interface RecordedQuery { - readonly sql: string; - readonly params: readonly DuckDbParam[]; -} - -interface RecordingFakeExecutor { - readonly executor: DuckDbExecutor; - readonly calls: RecordedQuery[]; - readonly runCalls: string[]; -} - -function createRecordingFakeExecutor(opts?: { - onQuery?: (sql: string, params: readonly DuckDbParam[], callIndex: number) => Promise | void; -}): RecordingFakeExecutor { - const calls: RecordedQuery[] = []; - const runCalls: string[] = []; - - const executor: DuckDbExecutor = { - async run(sql: string): Promise { - runCalls.push(sql); - }, - async query(sql: string, params: readonly DuckDbParam[]): Promise { - const idx = calls.length; - calls.push({ sql, params: [...params] }); - if (opts?.onQuery !== undefined) { - await opts.onQuery(sql, params, idx); - } - return []; - }, - }; - - return { executor, calls, runCalls }; -} - -function expectFeatureErrorCode(fn: () => unknown, expectedCode: FeatureLibraryErrorCode): FeatureLibraryError { - try { - fn(); - } catch (error) { - expect(error).toBeInstanceOf(FeatureLibraryError); - const typed = error as FeatureLibraryError; - expect(typed.code).toBe(expectedCode); - return typed; - } - throw new Error(`Expected FeatureLibraryError(${expectedCode}) to be thrown, but succeeded.`); -} - -function makeSimpleDef(overrides: Partial = {}): FeatureDefinition { - return { - name: 'close_raw', - version: 1, - family: 'technical', - kind: 'duckdb_sql', - inputs: ['bars_1d'], - warmupBars: 0, - knownAtRule: 'bar_close', - sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}}', - ...overrides, - }; -} - -describe('feature-library barrel and subpath exports', () => { - it('exposes identical symbols from @stock-bot/research and @stock-bot/research/feature-library', () => { - expect(FEATURE_FAMILIES).toBe(subpathFeatureFamilies); - expect(FEATURE_INPUT_DATASETS).toBe(subpathFeatureInputDatasets); - expect(FEATURE_KINDS).toBe(subpathFeatureKinds); - expect(FEATURE_KNOWN_AT_RULES).toBe(subpathFeatureKnownAtRules); - expect(FEATURE_OUTPUT_COLUMNS).toBe(subpathFeatureOutputColumns); - expect(FeatureLibraryError).toBe(SubpathFeatureLibraryError); - expect(RET_1D_V1).toBe(subpathRet1dV1); - expect(createFeatureRegistry).toBe(subpathCreateFeatureRegistry); - expect(featureDefinitionHash).toBe(subpathFeatureDefinitionHash); - expect(featureRef).toBe(subpathFeatureRef); - expect(parseFeatureRef).toBe(subpathParseFeatureRef); - expect(planFeatureBatch).toBe(subpathPlanFeatureBatch); - expect(runFeatureBatch).toBe(subpathRunFeatureBatch); - expect(validateFeatureDefinition).toBe(subpathValidateFeatureDefinition); - }); -}); - -describe('featureRef and parseFeatureRef', () => { - it('round-trips canonical refs such as ret_1d@v1', () => { - const ref = featureRef(RET_1D_V1); - expect(ref).toBe('ret_1d@v1'); - expect(parseFeatureRef(ref)).toEqual({ name: 'ret_1d', version: 1 }); - expect(parseFeatureRef('rsi_14@v12')).toEqual({ name: 'rsi_14', version: 12 }); - }); - - it('rejects malformed, non-canonical, and unsafe refs', () => { - const invalidRefs = [ - '', - 'ret_1d', - 'ret_1d@1', - 'ret_1d@v0', - 'ret_1d@v01', - 'ret_1d@v-1', - 'ret_1d@v1.5', - 'RSI-14@v1', - '1abc@v1', - `${'a'.repeat(64)}@v1`, - 'ret_1d@v9007199254740992', - ]; - for (const bad of invalidRefs) { - expectFeatureErrorCode(() => parseFeatureRef(bad), 'INVALID_FEATURE_REF'); - } - expectFeatureErrorCode(() => parseFeatureRef(null as unknown as string), 'INVALID_FEATURE_REF'); - expectFeatureErrorCode(() => featureRef({ name: 'RSI-14', version: 1 }), 'INVALID_NAME'); - expectFeatureErrorCode(() => featureRef({ name: 'ret_1d', version: 0 }), 'INVALID_VERSION'); - expectFeatureErrorCode(() => featureRef({ name: 'ret_1d', version: 1.5 }), 'INVALID_VERSION'); - expectFeatureErrorCode( - () => featureRef({ name: 'ret_1d', version: Number.MAX_SAFE_INTEGER + 1 }), - 'INVALID_VERSION' - ); - }); -}); - -describe('validateFeatureDefinition', () => { - it('accepts RET_1D_V1, CTE + window expressions, subqueries, and multi-input joins', () => { - expect(() => validateFeatureDefinition(RET_1D_V1)).not.toThrow(); - - const joinedDef: FeatureDefinition = { - name: 'cad_scaled_close', - version: 1, - family: 'fx', - kind: 'duckdb_sql', - inputs: ['bars_1d', 'fx_1d'], - warmupBars: 0, - knownAtRule: 'max_input_known_at', - sql: ` - WITH base AS ( - SELECT b.listing_id, b.ts, b.session_date, b.close, b.known_at - FROM {{input:bars_1d}} AS b - ) - SELECT - base.listing_id, - base.ts, - GREATEST(base.known_at, f.known_at) AS known_at, - base.close / f.close AS value - FROM base - INNER JOIN ( - SELECT session_date, close, known_at - FROM {{input:fx_1d}} - WHERE pair = 'USDCAD' - ) AS f ON base.session_date = f.session_date - `, - }; - expect(() => validateFeatureDefinition(joinedDef)).not.toThrow(); - - // Two-input join using LEFT(...) and RIGHT(...) string functions in the ON predicate, - // followed immediately by a real LEFT JOIN to verify join-boundary detection. - const leftInJoinOnDef: FeatureDefinition = { - name: 'fx_base_ccy_close', - version: 1, - family: 'fx', - kind: 'duckdb_sql', - inputs: ['bars_1d', 'fx_1d'], - warmupBars: 0, - knownAtRule: 'max_input_known_at', - sql: ` - SELECT - b.listing_id, - b.ts, - GREATEST(b.known_at, f.known_at) AS known_at, - b.close / COALESCE(f2.close, f.close) AS value - FROM {{input:bars_1d}} AS b - INNER JOIN {{input:fx_1d}} AS f - ON b.session_date = f.session_date - AND b.currency = LEFT(f.pair, 3) - AND RIGHT(f.pair, 3) = 'USD' - LEFT JOIN {{input:fx_1d}} AS f2 - ON b.session_date = f2.session_date - AND f2.pair = 'USDCAD' - WHERE f.close > 0 - `, - }; - expect(() => validateFeatureDefinition(leftInJoinOnDef)).not.toThrow(); - - // Valid compound subquery with parenthesized branches referencing declared inputs, - // and scalar subquery inside parenthesized arithmetic. - const compoundExistsDef: FeatureDefinition = { - name: 'eligible_close', - version: 1, - family: 'event', - kind: 'duckdb_sql', - inputs: ['bars_1d', 'events'], - warmupBars: 0, - knownAtRule: 'max_input_known_at', - sql: ` - SELECT - b.listing_id, - b.ts, - b.known_at, - b.close AS value - FROM {{input:bars_1d}} AS b - WHERE EXISTS ( - (SELECT 1 FROM {{input:bars_1d}} AS b2 WHERE b2.listing_id = b.listing_id) - UNION ALL - (SELECT 1 FROM {{input:events}} AS e WHERE e.listing_id = b.listing_id) - ) - AND ((SELECT MAX(close) FROM {{input:bars_1d}}) + 1) > b.close - `, - }; - expect(() => validateFeatureDefinition(compoundExistsDef)).not.toThrow(); - }); - - it('rejects invalid names, versions, families, kinds, warmupBars, and knownAtRule', () => { - expectFeatureErrorCode(() => validateFeatureDefinition(makeSimpleDef({ name: 'RSI-14' })), 'INVALID_NAME'); - expectFeatureErrorCode(() => validateFeatureDefinition(makeSimpleDef({ name: '' })), 'INVALID_NAME'); - expectFeatureErrorCode(() => validateFeatureDefinition(makeSimpleDef({ name: '1ret' })), 'INVALID_NAME'); - expectFeatureErrorCode( - () => validateFeatureDefinition(makeSimpleDef({ name: 'a'.repeat(64) })), - 'INVALID_NAME' - ); - - expectFeatureErrorCode(() => validateFeatureDefinition(makeSimpleDef({ version: 0 })), 'INVALID_VERSION'); - expectFeatureErrorCode(() => validateFeatureDefinition(makeSimpleDef({ version: -2 })), 'INVALID_VERSION'); - expectFeatureErrorCode(() => validateFeatureDefinition(makeSimpleDef({ version: 1.5 })), 'INVALID_VERSION'); - expectFeatureErrorCode( - () => validateFeatureDefinition(makeSimpleDef({ version: Number.NaN })), - 'INVALID_VERSION' - ); - - expectFeatureErrorCode( - () => validateFeatureDefinition(makeSimpleDef({ family: 'macro' as FeatureDefinition['family'] })), - 'INVALID_FAMILY' - ); - expectFeatureErrorCode( - () => validateFeatureDefinition(makeSimpleDef({ kind: 'polars' as FeatureDefinition['kind'] })), - 'INVALID_KIND' - ); - expectFeatureErrorCode( - () => validateFeatureDefinition(makeSimpleDef({ warmupBars: -1 })), - 'INVALID_WARMUP_BARS' - ); - expectFeatureErrorCode( - () => validateFeatureDefinition(makeSimpleDef({ warmupBars: 0.5 })), - 'INVALID_WARMUP_BARS' - ); - expectFeatureErrorCode( - () => - validateFeatureDefinition( - makeSimpleDef({ knownAtRule: 'end_of_month' as FeatureDefinition['knownAtRule'] }) - ), - 'INVALID_KNOWN_AT_RULE' - ); - }); - - it('rejects empty SQL, semicolons/multi-statement SQL, comments, bind markers, and malformed placeholders', () => { - expectFeatureErrorCode(() => validateFeatureDefinition(makeSimpleDef({ sql: ' ' })), 'INVALID_SQL_STATEMENT'); - expectFeatureErrorCode( - () => - validateFeatureDefinition( - makeSimpleDef({ - sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}}; SELECT 1', - }) - ), - 'INVALID_SQL_STATEMENT' - ); - expectFeatureErrorCode( - () => - validateFeatureDefinition( - makeSimpleDef({ - sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} -- comment', - }) - ), - 'INVALID_SQL_STATEMENT' - ); - expectFeatureErrorCode( - () => - validateFeatureDefinition( - makeSimpleDef({ - sql: '/* block */ SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}}', - }) - ), - 'INVALID_SQL_STATEMENT' - ); - expectFeatureErrorCode( - () => - validateFeatureDefinition( - makeSimpleDef({ - sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE close > ?', - }) - ), - 'INVALID_SQL_STATEMENT' - ); - expectFeatureErrorCode( - () => - validateFeatureDefinition( - makeSimpleDef({ - sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE close > $1', - }) - ), - 'INVALID_SQL_STATEMENT' - ); - expectFeatureErrorCode( - () => - validateFeatureDefinition( - makeSimpleDef({ - sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE close > :min_close', - }) - ), - 'INVALID_SQL_STATEMENT' - ); - expectFeatureErrorCode( - () => - validateFeatureDefinition( - makeSimpleDef({ - sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{bad:bars_1d}}', - }) - ), - 'INVALID_SQL_STATEMENT' - ); - }); - - it('rejects prohibited DDL/DML/admin SQL commands with PROHIBITED_SQL_OPERATION', () => { - const prohibitedSqls = [ - "COPY (SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}}) TO '/tmp/out.parquet'", - "ATTACH '/tmp/evil.db' AS evil", - 'INSERT INTO t VALUES (1)', - 'CREATE TABLE t (x INT)', - 'PRAGMA database_list', - "SET memory_limit = '100GB'", - 'INSTALL httpfs', - 'LOAD httpfs', - 'DROP TABLE bars_1d', - 'DELETE FROM bars_1d', - 'UPDATE bars_1d SET close = 0', - ]; - for (const sql of prohibitedSqls) { - expectFeatureErrorCode( - () => validateFeatureDefinition(makeSimpleDef({ sql })), - 'PROHIBITED_SQL_OPERATION' - ); - } - }); - - it('rejects direct/mixed-case readers, quoted paths, catalog relations, table functions, and disallowed functions', () => { - const externalSqls = [ - "SELECT listing_id, ts, ts AS known_at, close AS value FROM read_parquet('/etc/x')", - "SELECT listing_id, ts, ts AS known_at, close AS value FROM ReAd_PaRqUeT('/etc/x.parquet')", - "SELECT listing_id, ts, ts AS known_at, close AS value FROM read_csv('/tmp/a.csv')", - "SELECT listing_id, ts, ts AS known_at, close AS value FROM glob('/mnt/*')", - "SELECT listing_id, ts, ts AS known_at, close AS value FROM '/etc/x.parquet'", - "SELECT listing_id, ts, ts AS known_at, '/etc/passwd' AS value FROM {{input:bars_1d}}", - 'SELECT listing_id, ts, ts AS known_at, close AS value FROM information_schema.tables', - 'SELECT listing_id, ts, ts AS known_at, close AS value FROM pg_catalog.pg_tables', - 'SELECT listing_id, ts, ts AS known_at, close AS value FROM raw_table_not_a_cte', - "SELECT listing_id, ts, ts AS known_at, getenv('HOME') AS value FROM {{input:bars_1d}}", - 'SELECT listing_id, ts, ts AS known_at, custom_evil_fn(close) AS value FROM {{input:bars_1d}}', - ]; - for (const sql of externalSqls) { - expectFeatureErrorCode( - () => validateFeatureDefinition(makeSimpleDef({ sql })), - 'EXTERNAL_DATA_ACCESS' - ); - } - - // Reject DuckDB FROM-first and TABLE subqueries inside expressions so catalog tables cannot bypass allow-list checks. - const unsupportedSubqueries = [ - 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE EXISTS (FROM secret_table)', - 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE EXISTS ((FROM secret_table))', - 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE listing_id IN (FROM secret_table SELECT listing_id)', - 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE EXISTS (TABLE secret_table)', - 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE EXISTS ((SELECT 1 FROM {{input:bars_1d}}) UNION ALL FROM staging_eligibility)', - ]; - for (const sql of unsupportedSubqueries) { - expectFeatureErrorCode( - () => validateFeatureDefinition(makeSimpleDef({ sql })), - 'INVALID_SQL_STATEMENT' - ); - } - - // Reject compound subqueries with a parenthesized first branch when any later branch references an unauthorized relation. - const compoundBypassSubqueries = [ - 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE EXISTS ((SELECT 1 FROM {{input:bars_1d}}) UNION ALL SELECT 1 FROM staging_eligibility)', - 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE EXISTS ((SELECT 1 FROM {{input:bars_1d}}) UNION ALL (SELECT 1 FROM staging_eligibility))', - 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE EXISTS ((SELECT 1 FROM {{input:bars_1d}}) INTERSECT SELECT 1 FROM staging_eligibility)', - 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE EXISTS ((SELECT 1 FROM {{input:bars_1d}}) EXCEPT SELECT 1 FROM staging_eligibility)', - 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE EXISTS (((SELECT 1 FROM {{input:bars_1d}}) UNION ALL SELECT 1 FROM staging_eligibility))', - ]; - for (const sql of compoundBypassSubqueries) { - expectFeatureErrorCode( - () => validateFeatureDefinition(makeSimpleDef({ sql })), - 'EXTERNAL_DATA_ACCESS' - ); - } - }); - - it('rejects incorrect final projections with INVALID_SQL_PROJECTION', () => { - const badProjections = [ - 'SELECT * FROM {{input:bars_1d}}', - 'SELECT listing_id, ts, close AS value FROM {{input:bars_1d}}', - 'SELECT listing_id, ts, ts AS known_at, close AS value, volume AS extra FROM {{input:bars_1d}}', - 'SELECT ts, listing_id, ts AS known_at, close AS value FROM {{input:bars_1d}}', - 'SELECT listing_id, ts, ts AS known_at, close AS ret FROM {{input:bars_1d}}', - 'SELECT listing_id, ts, ts AS known_at, close + 1 FROM {{input:bars_1d}}', - ]; - for (const sql of badProjections) { - expectFeatureErrorCode( - () => validateFeatureDefinition(makeSimpleDef({ sql })), - 'INVALID_SQL_PROJECTION' - ); - } - }); - - it('rejects unsupported, undeclared, and unused input datasets with distinct codes', () => { - expectFeatureErrorCode( - () => - validateFeatureDefinition( - makeSimpleDef({ - inputs: ['macro' as FeatureDefinition['inputs'][number]], - sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:macro}}', - }) - ), - 'UNSUPPORTED_INPUT_DATASET' - ); - - expectFeatureErrorCode( - () => - validateFeatureDefinition( - makeSimpleDef({ - inputs: ['bars_1d'], - sql: 'SELECT b.listing_id, b.ts, b.ts AS known_at, b.close AS value FROM {{input:bars_1d}} AS b INNER JOIN {{input:events}} AS e ON b.listing_id = e.listing_id', - }) - ), - 'UNDECLARED_INPUT' - ); - - expectFeatureErrorCode( - () => - validateFeatureDefinition( - makeSimpleDef({ - inputs: ['bars_1d', 'fx_1d'], - sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}}', - }) - ), - 'UNUSED_INPUT' - ); - }); -}); - -describe('featureDefinitionHash', () => { - it('is stable across inter-token whitespace, object key order, input order, and metadata', () => { - const defA: FeatureDefinition = { - name: 'fx_ratio', - version: 1, - family: 'fx', - kind: 'duckdb_sql', - inputs: ['fx_1d', 'bars_1d'], - warmupBars: 2, - knownAtRule: 'max_input_known_at', - description: 'First description', - sql: "SELECT b.listing_id, b.ts, GREATEST(b.known_at, f.known_at) AS known_at, b.close / f.close AS value FROM {{input:bars_1d}} AS b INNER JOIN {{input:fx_1d}} AS f ON b.session_date = f.session_date WHERE f.pair = 'USD CAD'", - }; - - const defB: FeatureDefinition = { - sql: [ - 'SELECT', - ' b.listing_id,', - ' b.ts,', - ' GREATEST(b.known_at, f.known_at) AS known_at,', - ' b.close / f.close AS value', - 'FROM {{input:bars_1d}} AS b', - 'INNER JOIN {{input:fx_1d}} AS f', - ' ON b.session_date = f.session_date', - "WHERE f.pair = 'USD CAD'", - ].join('\n\t'), - knownAtRule: 'max_input_known_at', - warmupBars: 2, - inputs: ['bars_1d', 'fx_1d'], - kind: 'duckdb_sql', - family: 'technical', - version: 1, - name: 'fx_ratio', - description: 'Different metadata description', - }; - - const hashA = featureDefinitionHash(defA); - const hashB = featureDefinitionHash(defB); - expect(hashA).toMatch(/^[0-9a-f]{64}$/); - expect(hashA).toBe(hashB); - }); - - it('changes when string literal whitespace, SQL semantics, inputs, warmupBars, or knownAtRule change', () => { - const base = makeSimpleDef({ - sql: "SELECT listing_id, ts, ts AS known_at, CASE WHEN currency = 'US D' THEN close ELSE 0.0 END AS value FROM {{input:bars_1d}}", - }); - const baseHash = featureDefinitionHash(base); - - // Whitespace inside string literal changes hash. - const changedLiteral = makeSimpleDef({ - sql: "SELECT listing_id, ts, ts AS known_at, CASE WHEN currency = 'US D' THEN close ELSE 0.0 END AS value FROM {{input:bars_1d}}", - }); - expect(featureDefinitionHash(changedLiteral)).not.toBe(baseHash); - - // Substantive SQL change. - const changedSql = makeSimpleDef({ - sql: 'SELECT listing_id, ts, ts AS known_at, open AS value FROM {{input:bars_1d}}', - }); - expect(featureDefinitionHash(changedSql)).not.toBe(baseHash); - - // Valid input dataset change. - const changedInput = makeSimpleDef({ - inputs: ['events'], - sql: 'SELECT listing_id, ts, known_at, 1.0 AS value FROM {{input:events}}', - }); - expect(featureDefinitionHash(changedInput)).not.toBe(baseHash); - - // warmupBars change. - expect(featureDefinitionHash({ ...base, warmupBars: 5 })).not.toBe(baseHash); - - // knownAtRule change. - expect(featureDefinitionHash({ ...base, knownAtRule: 'source_known_at' })).not.toBe(baseHash); - }); -}); - -describe('createFeatureRegistry', () => { - it('supports idempotent re-registration, enforces FEATURE_VERSION_IMMUTABLE, allows version bumps, and isolates mutations', () => { - const registry = createFeatureRegistry(); - const mutableInputs: FeatureDefinition['inputs'][number][] = ['bars_1d']; - const initial: FeatureDefinition = { - ...RET_1D_V1, - inputs: mutableInputs, - }; - - const first = registry.registerSignal(initial); - expect(first.ref).toBe('ret_1d@v1'); - expect(first.definitionHash).toBe(featureDefinitionHash(RET_1D_V1)); - - // Mutate caller input after registration; stored definition must be unaffected. - mutableInputs.push('fx_1d'); - expect(registry.get('ret_1d@v1')?.inputs).toEqual(['bars_1d']); - - // Idempotent re-registration with whitespace-only SQL difference. - const sameSemantic: FeatureDefinition = { - ...RET_1D_V1, - sql: RET_1D_V1.sql.replace(/\n/g, ' '), - description: 'Updated description ignored for hash', - }; - const second = registry.registerSignal(sameSemantic); - expect(second.definitionHash).toBe(first.definitionHash); - expect(registry.list()).toEqual(['ret_1d@v1']); - - // Semantic changes at v1 must throw FEATURE_VERSION_IMMUTABLE. - const changedSql: FeatureDefinition = { - ...RET_1D_V1, - sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}}', - }; - const errSql = expectFeatureErrorCode( - () => registry.registerSignal(changedSql), - 'FEATURE_VERSION_IMMUTABLE' - ); - expect(errSql.ref).toBe('ret_1d@v1'); - - const changedInputs: FeatureDefinition = { - ...RET_1D_V1, - inputs: ['bars_1d', 'fx_1d'], - sql: 'SELECT b.listing_id, b.ts, GREATEST(b.known_at, f.known_at) AS known_at, b.close / f.close AS value FROM {{input:bars_1d}} AS b INNER JOIN {{input:fx_1d}} AS f ON b.session_date = f.session_date', - }; - expectFeatureErrorCode( - () => registry.registerSignal(changedInputs), - 'FEATURE_VERSION_IMMUTABLE' - ); - - expectFeatureErrorCode( - () => registry.registerSignal({ ...RET_1D_V1, warmupBars: 2 }), - 'FEATURE_VERSION_IMMUTABLE' - ); - - expectFeatureErrorCode( - () => registry.registerSignal({ ...RET_1D_V1, knownAtRule: 'source_known_at' }), - 'FEATURE_VERSION_IMMUTABLE' - ); - - // Same change under version 2 succeeds and both refs are listed. - const v2 = registry.registerSignal({ ...changedSql, version: 2 }); - expect(v2.ref).toBe('ret_1d@v2'); - expect(registry.list()).toEqual(['ret_1d@v1', 'ret_1d@v2']); - expect(registry.get('ret_1d@v2')?.version).toBe(2); - expect(registry.get('missing@v1')).toBeUndefined(); - - // Mutating returned list array does not affect registry. - const listed = registry.list() as string[]; - listed.push('evil@v99'); - expect(registry.list()).toEqual(['ret_1d@v1', 'ret_1d@v2']); - }); -}); - -describe('planFeatureBatch', () => { - it('plans 3 yearly Parquet COPY statements for RET_1D_V1 across 2020–2022', () => { - const writes = planFeatureBatch(RET_1D_V1, { - curatedRoot: '/c', - fromYear: 2020, - toYear: 2022, - vaultCutoffDate: '2025-06-01', - }); - - expect(writes).toHaveLength(3); - expect(writes.map(w => w.year)).toEqual([2020, 2021, 2022]); - expect(writes.map(w => w.outputPath)).toEqual([ - '/c/features/ret_1d/v1/year=2020/part.parquet', - '/c/features/ret_1d/v1/year=2021/part.parquet', - '/c/features/ret_1d/v1/year=2022/part.parquet', - ]); - - for (const write of writes) { - expect(write.sql).toStartWith( - 'COPY (SELECT listing_id, ts, known_at, value ' + - 'FROM (SELECT CAST(listing_id AS INTEGER) AS listing_id, CAST(ts AS TIMESTAMPTZ) AS ts, CAST(known_at AS TIMESTAMPTZ) AS known_at, CAST(value AS DOUBLE) AS value FROM (' - ); - expect(write.sql).toContain( - "read_parquet('/c/bars_1d/year=*/part.parquet', hive_partitioning = true) WHERE ts <= ? AND known_at <= ?" - ); - expect(write.sql).toContain( - ') AS __feature_source) AS __feature_typed WHERE year(ts) = ? AND ts <= ? AND known_at <= ? ORDER BY listing_id, ts)' - ); - expect(write.sql).toEndWith( - `TO '${write.outputPath}' (FORMAT PARQUET, COMPRESSION ZSTD)` - ); - const expectedTsEnd = `${write.year}-12-31T23:59:59.999999Z`; - const expectedKnownAtCeiling = '2025-05-31T23:59:59.999999Z'; - expect(write.params).toEqual([ - expectedTsEnd, - expectedKnownAtCeiling, - write.year, - expectedTsEnd, - expectedKnownAtCeiling, - ]); - - // Verify scan predicate is embedded inside the FROM subquery of the lagged CTE - // (evaluated before LAG), timestamp casts precede the outer year/Vault filter, - // and outer year(ts) filter follows the authored query. - const castTsIdx = write.sql.indexOf('CAST(ts AS TIMESTAMPTZ) AS ts'); - const castKnownAtIdx = write.sql.indexOf('CAST(known_at AS TIMESTAMPTZ) AS known_at'); - const lagIdx = write.sql.indexOf('LAG ( close )'); - const scanIdx = write.sql.indexOf( - "FROM (SELECT * FROM read_parquet('/c/bars_1d/year=*/part.parquet', hive_partitioning = true) WHERE ts <= ? AND known_at <= ?)" - ); - const outerYearIdx = write.sql.indexOf('WHERE year(ts) = ?'); - expect(castTsIdx).toBeGreaterThan(-1); - expect(castKnownAtIdx).toBeGreaterThan(castTsIdx); - expect(lagIdx).toBeGreaterThan(castKnownAtIdx); - expect(scanIdx).toBeGreaterThan(lagIdx); - expect(outerYearIdx).toBeGreaterThan(scanIdx); - } - - // Daily short-interest fixture projecting DATE report_date as ts still normalizes ts & known_at to TIMESTAMPTZ. - const shortsDateDef: FeatureDefinition = { - name: 'short_interest_raw', - version: 1, - family: 'event', - kind: 'duckdb_sql', - inputs: ['shorts'], - warmupBars: 0, - knownAtRule: 'source_known_at', - sql: 'SELECT listing_id, report_date AS ts, known_at, shares_short AS value FROM {{input:shorts}}', - }; - const [shortsWrite] = planFeatureBatch(shortsDateDef, { - curatedRoot: '/c', - fromYear: 2021, - toYear: 2021, - vaultCutoffDate: '2025-01-01', - }); - expect(shortsWrite?.sql).toContain( - 'SELECT CAST(listing_id AS INTEGER) AS listing_id, CAST(ts AS TIMESTAMPTZ) AS ts, CAST(known_at AS TIMESTAMPTZ) AS known_at, CAST(value AS DOUBLE) AS value FROM (' - ); - expect(shortsWrite?.sql).toContain( - ') AS __feature_source) AS __feature_typed WHERE year(ts) = ? AND ts <= ? AND known_at <= ?' - ); - }); - - it('expands all six allow-listed dataset path shapes and predicates, normalizes roots, and rejects unsafe roots', () => { - const allSixDef: FeatureDefinition = { - name: 'all_six_check', - version: 1, - family: 'fundamental', - kind: 'duckdb_sql', - inputs: ['bars_1d', 'adj_factors', 'events', 'shorts', 'fx_1d', 'fundamentals_pit'], - warmupBars: 0, - knownAtRule: 'max_input_known_at', - sql: ` - SELECT - b.listing_id, - b.ts, - GREATEST(b.known_at, a.known_at, e.known_at, s.known_at, f.known_at, p.effective_known_at) AS known_at, - b.close AS value - FROM {{input:bars_1d}} AS b - INNER JOIN {{input:adj_factors}} AS a ON b.listing_id = a.listing_id - INNER JOIN {{input:events}} AS e ON b.listing_id = e.listing_id - INNER JOIN {{input:shorts}} AS s ON b.listing_id = s.listing_id - INNER JOIN {{input:fx_1d}} AS f ON b.session_date = f.session_date - INNER JOIN {{input:fundamentals_pit}} AS p ON b.listing_id = p.listing_id - `, - }; - - const [write] = planFeatureBatch(allSixDef, { - curatedRoot: '/data///', - fromYear: 2021, - toYear: 2021, - vaultCutoffDate: '2024-01-01', - }); - expect(write).toBeDefined(); - expect(write?.outputPath).toBe('/data/features/all_six_check/v1/year=2021/part.parquet'); - expect(write?.sql).toContain( - "read_parquet('/data/bars_1d/year=*/part.parquet', hive_partitioning = true) WHERE ts <= ? AND known_at <= ?" - ); - expect(write?.sql).toContain( - "read_parquet('/data/adj_factors/part.parquet') WHERE known_at <= ?" - ); - expect(write?.sql).toContain( - "read_parquet('/data/events/year=*/part.parquet', hive_partitioning = true) WHERE ts <= ? AND known_at <= ?" - ); - expect(write?.sql).toContain( - "read_parquet('/data/shorts/part.parquet') WHERE known_at <= ?" - ); - expect(write?.sql).toContain( - "read_parquet('/data/fx_1d/part.parquet') WHERE ts <= ? AND known_at <= ?" - ); - expect(write?.sql).toContain( - "read_parquet('/data/fundamentals_pit/year=*/part.parquet', hive_partitioning = true) WHERE effective_known_at <= ?" - ); - - const ts2021 = '2021-12-31T23:59:59.999999Z'; - const vaultCeiling = '2023-12-31T23:59:59.999999Z'; - expect(write?.params).toEqual([ - ts2021, - vaultCeiling, // bars_1d - vaultCeiling, // adj_factors - ts2021, - vaultCeiling, // events - vaultCeiling, // shorts - ts2021, - vaultCeiling, // fx_1d - vaultCeiling, // fundamentals_pit - 2021, - ts2021, - vaultCeiling, // outer filter - ]); - - // Root '/' normalization (no double leading slash). - const [rootWrite] = planFeatureBatch(RET_1D_V1, { - curatedRoot: '/', - fromYear: 2020, - toYear: 2020, - vaultCutoffDate: '2025-01-01', - }); - expect(rootWrite?.outputPath).toBe('/features/ret_1d/v1/year=2020/part.parquet'); - expect(rootWrite?.sql).toContain("read_parquet('/bars_1d/year=*/part.parquet', hive_partitioning = true)"); - - // Unsafe curated roots rejected. - for (const badRoot of ['', 'relative/path', "/tmp/o'reilly", '/tmp/a;b', '/tmp/a*b', '/tmp/\n']) { - expectFeatureErrorCode( - () => - planFeatureBatch(RET_1D_V1, { - curatedRoot: badRoot, - fromYear: 2020, - toYear: 2020, - vaultCutoffDate: '2025-01-01', - }), - 'INVALID_BATCH_OPTIONS' - ); - } - }); - - it('enforces Vault fence for midyear cutoff, January 1 cutoff, entirely post-cutoff ranges, and invalid options', () => { - // Midyear cutoff: 2022-06-15 -> plans 2020, 2021, 2022; clamps 2022 ts and all known_at to 2022-06-14T23:59:59.999999Z. - const midyear = planFeatureBatch(RET_1D_V1, { - curatedRoot: '/c', - fromYear: 2020, - toYear: 2024, - vaultCutoffDate: '2022-06-15', - }); - expect(midyear.map(w => w.year)).toEqual([2020, 2021, 2022]); - expect(midyear[2]?.params).toEqual([ - '2022-06-14T23:59:59.999999Z', - '2022-06-14T23:59:59.999999Z', - 2022, - '2022-06-14T23:59:59.999999Z', - '2022-06-14T23:59:59.999999Z', - ]); - - // January 1 cutoff: 2022-01-01 -> excludes 2022 completely. - const jan1 = planFeatureBatch(RET_1D_V1, { - curatedRoot: '/c', - fromYear: 2020, - toYear: 2023, - vaultCutoffDate: '2022-01-01', - }); - expect(jan1.map(w => w.year)).toEqual([2020, 2021]); - expect(jan1[1]?.params).toEqual([ - '2021-12-31T23:59:59.999999Z', - '2021-12-31T23:59:59.999999Z', - 2021, - '2021-12-31T23:59:59.999999Z', - '2021-12-31T23:59:59.999999Z', - ]); - - // Entirely held-out ranges throw VAULT_RANGE_VIOLATION. - expectFeatureErrorCode( - () => - planFeatureBatch(RET_1D_V1, { - curatedRoot: '/c', - fromYear: 2023, - toYear: 2025, - vaultCutoffDate: '2022-06-15', - }), - 'VAULT_RANGE_VIOLATION' - ); - expectFeatureErrorCode( - () => - planFeatureBatch(RET_1D_V1, { - curatedRoot: '/c', - fromYear: 2022, - toYear: 2022, - vaultCutoffDate: '2022-01-01', - }), - 'VAULT_RANGE_VIOLATION' - ); - - // Invalid calendar dates and year ranges throw INVALID_BATCH_OPTIONS. - for (const badDate of ['2025-02-29', '2025-13-01', '2025-04-31', '2025-06-01T00:00:00Z', 'not-a-date']) { - expectFeatureErrorCode( - () => - planFeatureBatch(RET_1D_V1, { - curatedRoot: '/c', - fromYear: 2020, - toYear: 2021, - vaultCutoffDate: badDate, - }), - 'INVALID_BATCH_OPTIONS' - ); - } - - expectFeatureErrorCode( - () => - planFeatureBatch(RET_1D_V1, { - curatedRoot: '/c', - fromYear: 2022, - toYear: 2020, - vaultCutoffDate: '2025-01-01', - }), - 'INVALID_BATCH_OPTIONS' - ); - expectFeatureErrorCode( - () => - planFeatureBatch(RET_1D_V1, { - curatedRoot: '/c', - fromYear: 999, - toYear: 2020, - vaultCutoffDate: '2025-01-01', - }), - 'INVALID_BATCH_OPTIONS' - ); - expectFeatureErrorCode( - () => - planFeatureBatch(RET_1D_V1, { - curatedRoot: '/c', - fromYear: 2020.5, - toYear: 2021, - vaultCutoffDate: '2025-01-01', - }), - 'INVALID_BATCH_OPTIONS' - ); - }); -}); - -describe('runFeatureBatch', () => { - it('executes deterministically in sequential year order and returns a complete manifest', async () => { - const opts = { - curatedRoot: '/c', - fromYear: 2020, - toYear: 2022, - vaultCutoffDate: '2025-06-01', - }; - - const orderLog: string[] = []; - const fakeA = createRecordingFakeExecutor({ - async onQuery(_sql, params) { - const year = params[2]; - orderLog.push(`start:${String(year)}`); - await Promise.resolve(); - orderLog.push(`end:${String(year)}`); - }, - }); - const fakeB = createRecordingFakeExecutor(); - - const manifestA = await runFeatureBatch(RET_1D_V1, opts, fakeA.executor); - const manifestB = await runFeatureBatch(RET_1D_V1, opts, fakeB.executor); - - expect(orderLog).toEqual([ - 'start:2020', - 'end:2020', - 'start:2021', - 'end:2021', - 'start:2022', - 'end:2022', - ]); - expect(fakeA.runCalls).toHaveLength(0); - expect(fakeA.calls).toEqual(fakeB.calls); - expect(manifestA).toEqual(manifestB); - expect(manifestA).toEqual({ - ref: 'ret_1d@v1', - definitionHash: featureDefinitionHash(RET_1D_V1), - knownAtRule: 'bar_close', - warmupBars: 1, - inputs: ['bars_1d'], - writes: [ - { year: 2020, outputPath: '/c/features/ret_1d/v1/year=2020/part.parquet' }, - { year: 2021, outputPath: '/c/features/ret_1d/v1/year=2021/part.parquet' }, - { year: 2022, outputPath: '/c/features/ret_1d/v1/year=2022/part.parquet' }, - ], - }); - }); - - it('stops on second-year executor error, preserves cause, and reports only first year as completed', async () => { - const rootCause = new Error('disk full on year 2021'); - const fake = createRecordingFakeExecutor({ - onQuery(_sql, _params, callIndex) { - if (callIndex === 1) { - throw rootCause; - } - }, - }); - - let caught: unknown; - try { - await runFeatureBatch( - RET_1D_V1, - { - curatedRoot: '/c', - fromYear: 2020, - toYear: 2022, - vaultCutoffDate: '2025-06-01', - }, - fake.executor - ); - } catch (error) { - caught = error; - } - - expect(caught).toBeInstanceOf(FeatureLibraryError); - const typed = caught as FeatureLibraryError; - expect(typed.code).toBe('BATCH_WRITE_FAILED'); - expect(typed.cause).toBe(rootCause); - expect(typed.failedYear).toBe(2021); - expect(typed.completedYears).toEqual([2020]); - expect(typed.completedWrites).toEqual([ - { year: 2020, outputPath: '/c/features/ret_1d/v1/year=2020/part.parquet' }, - ]); - expect(fake.calls).toHaveLength(2); - }); - - it('issues zero executor calls when definition or batch options are invalid', async () => { - const fake = createRecordingFakeExecutor(); - let caught: unknown; - try { - await runFeatureBatch( - RET_1D_V1, - { - curatedRoot: '/c', - fromYear: 2025, - toYear: 2026, - vaultCutoffDate: '2025-01-01', - }, - fake.executor - ); - } catch (error) { - caught = error; - } - - expect(caught).toBeInstanceOf(FeatureLibraryError); - expect((caught as FeatureLibraryError).code).toBe('VAULT_RANGE_VIOLATION'); - expect(fake.calls).toHaveLength(0); - expect(fake.runCalls).toHaveLength(0); - }); - - it('snapshots definition metadata before awaiting writes so mid-run caller mutations cannot skew the manifest', async () => { - const mutableDef: { - name: string; - version: number; - family: FeatureDefinition['family']; - kind: FeatureDefinition['kind']; - inputs: FeatureDefinition['inputs'][number][]; - warmupBars: number; - knownAtRule: FeatureDefinition['knownAtRule']; - sql: string; - } = { - name: 'mutable_close', - version: 1, - family: 'technical', - kind: 'duckdb_sql', - inputs: ['bars_1d'], - warmupBars: 2, - knownAtRule: 'bar_close', - sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}}', - }; - const expectedHash = featureDefinitionHash(mutableDef); - - const fake = createRecordingFakeExecutor({ - onQuery() { - mutableDef.warmupBars = 999; - mutableDef.knownAtRule = 'source_known_at'; - mutableDef.inputs.push('fx_1d'); - }, - }); - - const manifest = await runFeatureBatch( - mutableDef, - { - curatedRoot: '/c', - fromYear: 2020, - toYear: 2021, - vaultCutoffDate: '2025-01-01', - }, - fake.executor - ); - - expect(manifest.definitionHash).toBe(expectedHash); - expect(manifest.warmupBars).toBe(2); - expect(manifest.knownAtRule).toBe('bar_close'); - expect(manifest.inputs).toEqual(['bars_1d']); - expect(manifest.writes).toHaveLength(2); - }); -}); - -describe('RET_1D_V1 economic reference check (planned SQL + hand-calculated fixture, no Parquet execution)', () => { - it('matches listing-partitioned LAG raw-close return semantics across prior-year warm-up and raw split discontinuity', () => { - // Verify SQL structure enforces listing-partitioned LAG, bar-close known_at, and positive prior close guard. - expect(RET_1D_V1.sql).toContain('LAG(close) OVER (PARTITION BY listing_id ORDER BY ts ASC) AS prev_close'); - expect(RET_1D_V1.sql).toContain('ts AS known_at'); - expect(RET_1D_V1.sql).toContain('(close / prev_close) - 1.0 AS value'); - expect(RET_1D_V1.sql).toContain('WHERE prev_close IS NOT NULL AND prev_close > 0 AND close > 0'); - - // Hand-calculated reference fixture (does not evaluate DuckDB Parquet): - // Listing 101: 2019-12-31 close 100 -> 2020-01-02 close 110 (+10%) -> 2020-01-03 2-for-1 raw split close 55 (-50% raw). - // Listing 202: 2020-01-02 close 50 (no prior close -> omitted) -> 2020-01-03 close 52 (+4%). - const bars = [ - { listing_id: 101, ts: '2019-12-31T21:00:00Z', close: 100 }, - { listing_id: 101, ts: '2020-01-02T21:00:00Z', close: 110 }, - { listing_id: 101, ts: '2020-01-03T21:00:00Z', close: 55 }, - { listing_id: 202, ts: '2020-01-02T21:00:00Z', close: 50 }, - { listing_id: 202, ts: '2020-01-03T21:00:00Z', close: 52 }, - ]; - - const lastCloseByListing = new Map(); - const targetYearRows: Array<{ listing_id: number; ts: string; known_at: string; value: number }> = []; - for (const bar of bars) { - const prevClose = lastCloseByListing.get(bar.listing_id); - lastCloseByListing.set(bar.listing_id, bar.close); - if (prevClose === undefined || prevClose <= 0 || bar.close <= 0) { - continue; - } - if (bar.ts.startsWith('2020-')) { - targetYearRows.push({ - listing_id: bar.listing_id, - ts: bar.ts, - known_at: bar.ts, - value: bar.close / prevClose - 1.0, - }); - } - } - - expect(targetYearRows).toHaveLength(3); - expect(targetYearRows[0]).toEqual({ - listing_id: 101, - ts: '2020-01-02T21:00:00Z', - known_at: '2020-01-02T21:00:00Z', - value: 0.10000000000000009, - }); - expect(targetYearRows[1]).toEqual({ - listing_id: 101, - ts: '2020-01-03T21:00:00Z', - known_at: '2020-01-03T21:00:00Z', - value: -0.5, - }); - expect(targetYearRows[2]?.listing_id).toBe(202); - expect(targetYearRows[2]?.value).toBeCloseTo(0.04, 12); - }); -}); - -describe('QA: relation-source allow-list and Vault boundary edge cases', () => { - const positionalBypassSqls = [ - // Explicit alias, then DuckDB POSITIONAL JOIN to an undeclared catalog table. - 'SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b POSITIONAL JOIN staging_tbl AS s', - // Bare alias form. - 'SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} b POSITIONAL JOIN staging_tbl s', - // Inside a CTE body. - 'WITH x AS (SELECT b.listing_id, b.ts, s.v FROM {{input:bars_1d}} AS b POSITIONAL JOIN staging_tbl AS s) SELECT listing_id, ts, ts AS known_at, v AS value FROM x', - ]; - - it('rejects POSITIONAL JOIN to an undeclared relation after an aliased input (registry and runner never execute it)', async () => { - for (const sql of positionalBypassSqls) { - const def = makeSimpleDef({ name: 'positional_leak', sql }); - let thrown: unknown; - try { - validateFeatureDefinition(def); - } catch (error) { - thrown = error; - } - expect(thrown).toBeInstanceOf(FeatureLibraryError); - expect(['EXTERNAL_DATA_ACCESS', 'INVALID_SQL_STATEMENT']).toContain( - (thrown as FeatureLibraryError).code - ); - - expect(() => createFeatureRegistry().registerSignal(def)).toThrow(FeatureLibraryError); - - const fake = createRecordingFakeExecutor(); - await expect( - runFeatureBatch( - def, - { curatedRoot: '/c', fromYear: 2021, toYear: 2021, vaultCutoffDate: '2022-06-30' }, - fake.executor - ) - ).rejects.toBeInstanceOf(FeatureLibraryError); - expect(fake.calls).toHaveLength(0); - } - }); - - it('still rejects a POSITIONAL JOIN to an undeclared relation chained after an ON predicate', () => { - expectFeatureErrorCode( - () => - validateFeatureDefinition( - makeSimpleDef({ - sql: 'SELECT b.listing_id, b.ts, b.ts AS known_at, b.close AS value FROM {{input:bars_1d}} AS b JOIN {{input:bars_1d}} AS c ON b.ts = c.ts POSITIONAL JOIN staging_tbl', - }) - ), - 'EXTERNAL_DATA_ACCESS' - ); - }); - - it('allows POSITIONAL JOIN between declared inputs and fails closed on unknown join modifiers or unparsed JOIN tokens', () => { - expect(() => - validateFeatureDefinition( - makeSimpleDef({ - inputs: ['bars_1d', 'fx_1d'], - sql: 'SELECT b.listing_id, b.ts, b.ts AS known_at, b.close / f.close AS value FROM {{input:bars_1d}} AS b POSITIONAL JOIN {{input:fx_1d}} AS f', - }) - ) - ).not.toThrow(); - - expect(() => - validateFeatureDefinition( - makeSimpleDef({ - inputs: ['bars_1d', 'fx_1d'], - sql: 'WITH fx AS (SELECT close AS fx_close FROM {{input:fx_1d}}) SELECT listing_id, ts, ts AS known_at, close / fx_close AS value FROM {{input:bars_1d}} POSITIONAL JOIN fx', - }) - ) - ).not.toThrow(); - - // Unknown modifier immediately after FROM/alias must fail closed (never fall through to expression scan). - expectFeatureErrorCode( - () => - validateFeatureDefinition( - makeSimpleDef({ - sql: 'SELECT b.listing_id, b.ts, b.ts AS known_at, b.close AS value FROM {{input:bars_1d}} AS b LATERAL_UNKNOWN JOIN staging_tbl AS s', - }) - ), - 'INVALID_SQL_STATEMENT' - ); - - // Chained JOIN after an ON predicate with an unknown modifier still hits relation allow-list validation. - expectFeatureErrorCode( - () => - validateFeatureDefinition( - makeSimpleDef({ - sql: 'SELECT b.listing_id, b.ts, b.ts AS known_at, b.close AS value FROM {{input:bars_1d}} AS b JOIN {{input:bars_1d}} AS c ON b.ts = c.ts UNKNOWN_MOD JOIN staging_tbl AS s', - }) - ), - 'EXTERNAL_DATA_ACCESS' - ); - - // Unparsed JOIN keyword inside a WHERE expression tail must fail closed. - expectFeatureErrorCode( - () => - validateFeatureDefinition( - makeSimpleDef({ - sql: 'SELECT b.listing_id, b.ts, b.ts AS known_at, b.close AS value FROM {{input:bars_1d}} AS b WHERE b.close > 0 JOIN staging_tbl AS s', - }) - ), - 'INVALID_SQL_STATEMENT' - ); - }); - - it('accepts a leap-day cutoff and clamps the cutoff year to the last microsecond of the prior day', () => { - const writes = planFeatureBatch(RET_1D_V1, { - curatedRoot: '/c', - fromYear: 2023, - toYear: 2025, - vaultCutoffDate: '2024-02-29', - }); - expect(writes.map(w => w.year)).toEqual([2023, 2024]); - const ceiling = '2024-02-28T23:59:59.999999Z'; - expect(writes[1]?.params).toEqual([ceiling, ceiling, 2024, ceiling, ceiling]); - expect(writes[0]?.params).toEqual([ - '2023-12-31T23:59:59.999999Z', - ceiling, - 2023, - '2023-12-31T23:59:59.999999Z', - ceiling, - ]); - }); - - it('plans the cutoff year when only its first day precedes a January 2 cutoff', () => { - const writes = planFeatureBatch(RET_1D_V1, { - curatedRoot: '/c', - fromYear: 2022, - toYear: 2022, - vaultCutoffDate: '2022-01-02', - }); - expect(writes.map(w => w.year)).toEqual([2022]); - const ceiling = '2022-01-01T23:59:59.999999Z'; - expect(writes[0]?.params).toEqual([ceiling, ceiling, 2022, ceiling, ceiling]); - for (const param of writes[0]?.params ?? []) { - if (typeof param === 'string') { - expect(param < '2022-01-02').toBe(true); - } - } - }); -}); - -describe('QA round 2: undeclared-relation probes rejected before any executor call', () => { - // Each probe was also checked in a scratch in-memory DuckDB 1.4.4 session holding a - // `staging_tbl` relation; every form here is valid DuckDB that would read that table. - const undeclaredRelationProbes: ReadonlyArray<{ sql: string; code: FeatureLibraryErrorCode }> = [ - { - sql: 'SELECT b.listing_id, b.ts, b.known_at, s.v AS value FROM {{input:bars_1d}} b NATURAL JOIN staging_tbl s', - code: 'EXTERNAL_DATA_ACCESS', - }, - { - sql: 'SELECT b.listing_id, b.ts, b.known_at, b.close AS value FROM {{input:bars_1d}} b ANTI JOIN staging_tbl s ON s.listing_id = b.listing_id', - code: 'EXTERNAL_DATA_ACCESS', - }, - { - sql: 'SELECT b.listing_id, b.ts, b.known_at, b.close AS value FROM {{input:bars_1d}} b SEMI JOIN staging_tbl USING (listing_id)', - code: 'EXTERNAL_DATA_ACCESS', - }, - { - sql: 'SELECT b.listing_id, b.ts, b.known_at, b.close AS value FROM {{input:bars_1d}} AS b(listing_id) ASOF JOIN staging_tbl s ON s.listing_id <= b.listing_id', - code: 'EXTERNAL_DATA_ACCESS', - }, - { - sql: 'SELECT b.listing_id, b.ts, b.known_at, b.close AS value FROM {{input:bars_1d}} b, LATERAL (SELECT v FROM staging_tbl) s', - code: 'EXTERNAL_DATA_ACCESS', - }, - { - sql: 'SELECT b.listing_id, b.ts, b.known_at, (SELECT v FROM staging_tbl) AS value FROM {{input:bars_1d}} b', - code: 'EXTERNAL_DATA_ACCESS', - }, - { - sql: 'SELECT b.listing_id, b.ts, b.known_at, b.close AS value FROM {{input:bars_1d}} b WHERE EXISTS ((FROM staging_tbl))', - code: 'INVALID_SQL_STATEMENT', - }, - { - sql: 'WITH x AS (SELECT * FROM {{input:bars_1d}}) SELECT x.listing_id, x.ts, x.known_at, x.close AS value FROM x WHERE x.listing_id IN (TABLE staging_tbl)', - code: 'INVALID_SQL_STATEMENT', - }, - { - sql: 'SELECT b.listing_id, b.ts, b.known_at, b.close AS value FROM {{input:bars_1d}} b WHERE b.listing_id = ANY (SELECT listing_id FROM "staging_tbl")', - code: 'EXTERNAL_DATA_ACCESS', - }, - { - sql: 'SELECT b.listing_id, b.ts, b.known_at, b.close AS value FROM {{input:bars_1d}} b QUALIFY b.close IN (SELECT v FROM staging_tbl)', - code: 'EXTERNAL_DATA_ACCESS', - }, - { - sql: 'SELECT b.listing_id, b.ts, b.known_at, b.close AS value FROM {{input:bars_1d}} b WINDOW w AS (ORDER BY (SELECT 1 FROM staging_tbl))', - code: 'EXTERNAL_DATA_ACCESS', - }, - { - // An unused CTE over a catalog table still counts as an undeclared relation source. - sql: 'WITH x AS (SELECT * FROM staging_tbl) SELECT b.listing_id, b.ts, b.known_at, b.close AS value FROM {{input:bars_1d}} b', - code: 'EXTERNAL_DATA_ACCESS', - }, - { - // DuckDB method-call syntax resolves to the table function query_table(). - sql: 'SELECT b.listing_id, b.ts, b.known_at, b.close.query_table() AS value FROM {{input:bars_1d}} b', - code: 'EXTERNAL_DATA_ACCESS', - }, - { - sql: 'SELECT listing_id, ts, known_at, close AS value FROM {{input:bars_1d}} UNION ALL BY NAME SELECT listing_id, ts, ts AS known_at, v AS value FROM staging_tbl', - code: 'INVALID_SQL_STATEMENT', - }, - { - // DuckDB E-strings treat \' as an escaped quote; the tokenizer must not be - // desynchronised into hiding a subquery inside what it believes is a literal. - sql: "SELECT b.listing_id, b.ts, b.known_at, E'\\' ' || (SELECT max(v) FROM staging_tbl) || ' ' AS value FROM {{input:bars_1d}} b", - code: 'INVALID_SQL_STATEMENT', - }, - ]; - - it('rejects each undeclared-relation form with a specific code from validate, registerSignal and runFeatureBatch', async () => { - for (const probe of undeclaredRelationProbes) { - const def = makeSimpleDef({ name: 'probe_leak', sql: probe.sql }); - - expectFeatureErrorCode(() => validateFeatureDefinition(def), probe.code); - expectFeatureErrorCode(() => createFeatureRegistry().registerSignal(def), probe.code); - - const fake = createRecordingFakeExecutor(); - let thrown: unknown; - try { - await runFeatureBatch( - def, - { curatedRoot: '/c', fromYear: 2021, toYear: 2021, vaultCutoffDate: '2022-06-30' }, - fake.executor - ); - } catch (error) { - thrown = error; - } - expect((thrown as FeatureLibraryError).code).toBe(probe.code); - expect(fake.calls).toHaveLength(0); - } - }); - - it('plans contract-schema definitions for every input dataset with inner availability predicates bound before the outer filters', () => { - const cutoff = '2022-06-30'; - const ceiling = '2022-06-29T23:59:59.999999Z'; - const yearEnd = '2021-12-31T23:59:59.999999Z'; - const base = { version: 1, warmupBars: 0, knownAtRule: 'source_known_at' as const }; - const cases: ReadonlyArray<{ def: FeatureDefinition; scanParams: DuckDbParam[] }> = [ - { - def: makeSimpleDef({ - ...base, - name: 'fx_close', - family: 'fx', - inputs: ['bars_1d', 'fx_1d'], - sql: 'SELECT b.listing_id, b.ts, GREATEST(b.known_at, f.known_at) AS known_at, b.close * f.close AS value FROM {{input:bars_1d}} AS b JOIN {{input:fx_1d}} AS f ON f.session_date = b.session_date AND LEFT(f.pair, 3) = b.currency', - }), - scanParams: [yearEnd, ceiling, yearEnd, ceiling], - }, - { - def: makeSimpleDef({ - ...base, - name: 'short_int', - inputs: ['shorts'], - sql: 'SELECT listing_id, report_date AS ts, known_at, shares_short AS value FROM {{input:shorts}}', - }), - scanParams: [ceiling], - }, - { - def: makeSimpleDef({ - ...base, - name: 'evt', - family: 'event', - inputs: ['events'], - sql: 'SELECT listing_id, ts, known_at, 1.0 AS value FROM {{input:events}}', - }), - scanParams: [yearEnd, ceiling], - }, - { - def: makeSimpleDef({ - ...base, - name: 'adj', - inputs: ['adj_factors'], - sql: 'SELECT listing_id, ex_date AS ts, known_at, cum_split_factor AS value FROM {{input:adj_factors}}', - }), - scanParams: [ceiling], - }, - { - def: makeSimpleDef({ - ...base, - name: 'fund', - family: 'fundamental', - inputs: ['fundamentals_pit'], - sql: 'SELECT listing_id, effective_known_at AS ts, effective_known_at AS known_at, revenue_ttm AS value FROM {{input:fundamentals_pit}}', - }), - scanParams: [ceiling], - }, - ]; - - for (const { def, scanParams } of cases) { - const writes = planFeatureBatch(def, { - curatedRoot: '/c', - fromYear: 2021, - toYear: 2021, - vaultCutoffDate: cutoff, - }); - expect(writes).toHaveLength(1); - const write = writes[0] as (typeof writes)[number]; - expect(write.outputPath).toBe(`/c/features/${def.name}/v1/year=2021/part.parquet`); - expect(write.params).toEqual([...scanParams, 2021, yearEnd, ceiling]); - // Bind markers in SQL match the parameter count exactly. - expect(write.sql.split('?').length - 1).toBe(write.params.length); - // Every inner scan predicate appears before the outer year/Vault filter. - const outerFilter = write.sql.indexOf('WHERE year(ts) = ?'); - expect(outerFilter).toBeGreaterThan(0); - let lastScan = -1; - for (let at = write.sql.indexOf('read_parquet('); at !== -1; at = write.sql.indexOf('read_parquet(', at + 1)) { - lastScan = at; - } - expect(lastScan).toBeGreaterThan(-1); - expect(lastScan).toBeLessThan(outerFilter); - expect(write.sql).toContain('CAST(ts AS TIMESTAMPTZ) AS ts'); - expect(write.sql).toContain('CAST(known_at AS TIMESTAMPTZ) AS known_at'); - for (const param of write.params) { - if (typeof param === 'string') { - expect(param < cutoff).toBe(true); - } - } - } - }); -}); - -describe('QA round 3: WITH RECURSIVE cannot shadow an undeclared catalog relation', () => { - // Reproduced in a scratch in-memory DuckDB 1.4.4 session holding `staging_tbl(v = 42.0)`: - // DuckDB treats a RECURSIVE CTE body without a recursive UNION term (or the anchor term of - // one that has it) as a non-recursive scope, so `FROM staging_tbl` inside the body binds to - // the catalog table. runFeatureBatch then wrote 42.0 into - // features/leak/v1/year=2021/part.parquet while the manifest reported inputs ['bars_1d']. - const recursiveShadowProbes: readonly string[] = [ - 'WITH RECURSIVE staging_tbl AS (SELECT * FROM staging_tbl) SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, staging_tbl AS s', - 'WITH RECURSIVE staging_tbl AS (SELECT * FROM staging_tbl UNION ALL SELECT * FROM staging_tbl WHERE 1 = 0) SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, staging_tbl AS s', - 'SELECT b.listing_id, b.ts, b.ts AS known_at, b.close AS value FROM (WITH RECURSIVE staging_tbl AS (SELECT * FROM staging_tbl) SELECT b.listing_id, b.ts, b.close FROM {{input:bars_1d}} AS b, staging_tbl AS s) AS b', - 'SELECT b.listing_id, b.ts, b.ts AS known_at, b.close AS value FROM {{input:bars_1d}} AS b WHERE EXISTS (WITH RECURSIVE staging_tbl AS (SELECT * FROM staging_tbl) SELECT 1 FROM staging_tbl)', - ]; - - it('rejects top-level and nested WITH RECURSIVE CTEs with INVALID_SQL_STATEMENT and zero executor calls', async () => { - for (const sql of recursiveShadowProbes) { - const def = makeSimpleDef({ name: 'leak', sql }); - - expectFeatureErrorCode(() => validateFeatureDefinition(def), 'INVALID_SQL_STATEMENT'); - expectFeatureErrorCode(() => createFeatureRegistry().registerSignal(def), 'INVALID_SQL_STATEMENT'); - - const fake = createRecordingFakeExecutor(); - let execError: unknown; - try { - await runFeatureBatch( - def, - { curatedRoot: '/c', fromYear: 2021, toYear: 2021, vaultCutoffDate: '2022-01-01' }, - fake.executor - ); - } catch (error) { - execError = error; - } - expect(execError).toBeInstanceOf(FeatureLibraryError); - expect((execError as FeatureLibraryError).code).toBe('INVALID_SQL_STATEMENT'); - expect(fake.calls).toHaveLength(0); - } - }); -}); - -describe('QA round 4: CTE scope must match DuckDB identifier folding (ASCII-only)', () => { - // Reproduced in a scratch in-memory DuckDB 1.4.4 session (`SET TimeZone='UTC'`) holding catalog - // tables `kv(v = 42.0)` and `"ä"(v = 43.0)` plus one bars_1d row (listing 1, 2021-03-01). DuckDB - // folds identifier case for ASCII only, so `"Kv"` (KELVIN SIGN) is not the same name as `kv` - // and `"Ä"` is not `"ä"`; the validator's `toLowerCase()` treated them as the same in-scope CTE. - // runFeatureBatch then wrote 42.0 / 43.0 into features/leak_*/v1/year=2021/part.parquet while the - // manifest reported inputs ['bars_1d']. - const unicodeFoldProbes: readonly string[] = [ - 'WITH "Kv" AS (SELECT 1.0 AS v) SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, kv AS s', - 'WITH "Ä" AS (SELECT 1.0 AS v) SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, "ä" AS s', - 'SELECT b.listing_id, b.ts, b.ts AS known_at, b.close AS value FROM {{input:bars_1d}} AS b WHERE EXISTS (WITH "Kv" AS (SELECT 1 AS v) SELECT 1 FROM kv)', - ]; - - it('rejects a reference that only matches a CTE under Unicode case folding, with zero executor calls', async () => { - for (const sql of unicodeFoldProbes) { - const def = makeSimpleDef({ name: 'leak', sql }); - - expectFeatureErrorCode(() => validateFeatureDefinition(def), 'EXTERNAL_DATA_ACCESS'); - expectFeatureErrorCode(() => createFeatureRegistry().registerSignal(def), 'EXTERNAL_DATA_ACCESS'); - - const fake = createRecordingFakeExecutor(); - let execError: unknown; - try { - await runFeatureBatch( - def, - { curatedRoot: '/c', fromYear: 2021, toYear: 2021, vaultCutoffDate: '2022-01-01' }, - fake.executor - ); - } catch (error) { - execError = error; - } - expect(execError).toBeInstanceOf(FeatureLibraryError); - expect((execError as FeatureLibraryError).code).toBe('EXTERNAL_DATA_ACCESS'); - expect(fake.calls).toHaveLength(0); - } - }); - - it('still accepts an ASCII case-insensitive quoted CTE reference, which DuckDB binds to the CTE', () => { - // Verified in DuckDB 1.4.4: `WITH "STAGING" AS (SELECT 1.0 AS v) SELECT v FROM staging` returns 1.0 - // even when a catalog table `staging(v = 42.0)` exists. - const def = makeSimpleDef({ - sql: 'WITH "BARS" AS (SELECT listing_id, ts, close FROM {{input:bars_1d}}) SELECT listing_id, ts, ts AS known_at, close AS value FROM bars', - }); - expect(() => validateFeatureDefinition(def)).not.toThrow(); - }); - - it('accepts an exact non-ASCII quoted CTE name match', () => { - const def = makeSimpleDef({ - sql: 'WITH "Ä" AS (SELECT listing_id, ts, close FROM {{input:bars_1d}}) SELECT listing_id, ts, ts AS known_at, close AS value FROM "Ä"', - }); - expect(() => validateFeatureDefinition(def)).not.toThrow(); - }); -}); - -describe('QA round 5: CTE scope parity with DuckDB across nesting and UNION branches', () => { - // Each case was run in a scratch in-memory DuckDB 1.4.4 session (`SET TimeZone='UTC'`) holding a - // catalog table `kv(v = 42.0)`, with {{input:bars_1d}} replaced by a one-row bars subquery. - // Leak cases returned 42.0 (catalog) in DuckDB; accepted cases returned the CTE value 1.0. - const leakCases: ReadonlyArray<{ label: string; sql: string }> = [ - { - label: 'CTE declared inside a CTE body is not visible to the outer query', - sql: 'WITH a AS (WITH kv AS (SELECT 1.0 AS v) SELECT v FROM kv) SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, kv AS s', - }, - { - label: 'CTE declared in an earlier parenthesized UNION branch is not visible to a later branch', - sql: 'SELECT b.listing_id, b.ts, b.ts AS known_at, 1.0 AS value FROM {{input:bars_1d}} AS b UNION ALL (WITH kv AS (SELECT 1.0 AS v) SELECT b.listing_id, b.ts, b.ts AS known_at, 1.0 AS value FROM {{input:bars_1d}} AS b) UNION ALL SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, kv AS s', - }, - { - label: 'CTE declared in a derived table is not visible to a sibling FROM item', - sql: 'SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, (WITH kv AS (SELECT 1.0 AS v) SELECT v FROM kv) AS x, kv AS s', - }, - ]; - - it('rejects references that DuckDB binds to the catalog table, with zero executor calls', async () => { - for (const { label, sql } of leakCases) { - const def = makeSimpleDef({ name: 'leak', sql }); - let validateError: unknown; - try { - validateFeatureDefinition(def); - } catch (error) { - validateError = error; - } - expect(validateError, label).toBeInstanceOf(FeatureLibraryError); - expect((validateError as FeatureLibraryError).code, label).toBe('EXTERNAL_DATA_ACCESS'); - - const fake = createRecordingFakeExecutor(); - let execError: unknown; - try { - await runFeatureBatch( - def, - { curatedRoot: '/c', fromYear: 2021, toYear: 2021, vaultCutoffDate: '2022-01-01' }, - fake.executor - ); - } catch (error) { - execError = error; - } - expect(execError, label).toBeInstanceOf(FeatureLibraryError); - expect((execError as FeatureLibraryError).code, label).toBe('EXTERNAL_DATA_ACCESS'); - expect(fake.calls).toHaveLength(0); - } - }); - - it('rejects a CTE name that differs only by Unicode normalization or an invisible character', () => { - // DuckDB matches these names byte-for-byte after ASCII folding, so neither is the CTE. - for (const sql of [ - 'WITH "Ä" AS (SELECT 1.0 AS v) SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, "Ä" AS s', - 'WITH "kv​" AS (SELECT 1.0 AS v) SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, "kv" AS s', - ]) { - expectFeatureErrorCode( - () => validateFeatureDefinition(makeSimpleDef({ name: 'leak', sql })), - 'EXTERNAL_DATA_ACCESS' - ); - } - }); - - it('rejects a non-ASCII space outside quotes instead of treating it as whitespace', () => { - expectFeatureErrorCode( - () => - validateFeatureDefinition( - makeSimpleDef({ - sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}}', - }) - ), - 'INVALID_SQL_STATEMENT' - ); - }); - - it('accepts CTE references DuckDB binds to the CTE: outer CTE shadowing, top-level WITH over UNION, column lists, MATERIALIZED', () => { - for (const sql of [ - 'WITH kv AS (SELECT 1.0 AS v) SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, (WITH kv AS (SELECT v FROM kv) SELECT v FROM kv) AS s', - 'WITH kv AS (SELECT 1.0 AS v) SELECT b.listing_id, b.ts, b.ts AS known_at, 1.0 AS value FROM {{input:bars_1d}} AS b UNION ALL SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, kv AS s', - 'WITH kv(v) AS (SELECT 1.0) SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, kv AS s', - 'WITH kv AS MATERIALIZED (SELECT 1.0 AS v) SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, kv AS s', - ]) { - expect(() => validateFeatureDefinition(makeSimpleDef({ sql }))).not.toThrow(); - } - }); -}); diff --git a/libs/research/test/market-data-store-duckdb-universe.qa.test.ts b/libs/research/test/market-data-store-duckdb-universe.qa.test.ts deleted file mode 100644 index c98578fb..00000000 --- a/libs/research/test/market-data-store-duckdb-universe.qa.test.ts +++ /dev/null @@ -1,420 +0,0 @@ -import { describe, expect, it } from 'bun:test'; -import { - createDuckDbMarketDataStore, - MarketDataStoreValidationError, - planBars1dQuery, - planUniverseQuery, - resolveDuckDbConnectionBudget, - UNIVERSE_REFS, - VaultHoldoutFenceError, - type DuckDbExecutor, - type DuckDbParam, - type DuckDbPlanContext, - type TableRow, -} from '@stock-bot/research'; - -// QA edge cases for T-122 (`universe` planner + adapter) not pinned by the primary suite. - -const ROOT = '/data/curated'; -const CUTOFF_MS = Date.UTC(2026, 4, 28); // 2026-05-28T00:00:00.000Z -const CTX: DuckDbPlanContext = { curatedRoot: ROOT, vaultCutoffTs: CUTOFF_MS }; -const DAY_MS = 86_400_000; - -interface Recorder { - readonly executor: DuckDbExecutor; - readonly log: Array<{ kind: 'run' | 'query'; sql: string; params?: readonly DuckDbParam[] }>; -} - -function recorder( - onQuery: ( - sql: string, - params: readonly DuckDbParam[] - ) => Promise | readonly TableRow[] = () => [], - onRun: (sql: string) => Promise | void = () => {} -): Recorder { - const log: Recorder['log'] = []; - return { - log, - executor: { - async run(sql) { - log.push({ kind: 'run', sql }); - await onRun(sql); - }, - async query(sql, params) { - log.push({ kind: 'query', sql, params: [...params] }); - return onQuery(sql, params); - }, - }, - }; -} - -function mulberry32(seed: number): () => number { - let a = seed >>> 0; - return () => { - a = (a + 0x6d2b79f5) >>> 0; - let t = a; - t = Math.imul(t ^ (t >>> 15), t | 1); - t ^= t + Math.imul(t ^ (t >>> 7), t | 61); - return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296; - }; -} - -function isoDate(ms: number): string { - return new Date(ms).toISOString().slice(0, 10); -} - -interface FixtureBar { - readonly listing_id: number; - readonly currency: 'USD' | 'CAD'; - readonly session_date: string; - readonly ts: string; // microsecond UTC ISO, same format the planner binds - readonly known_at: string; -} - -function bar( - listingId: number, - currency: 'USD' | 'CAD', - sessionDate: string, - knownAt?: string -): FixtureBar { - return { - listing_id: listingId, - currency, - session_date: sessionDate, - ts: `${sessionDate}T20:00:00.000000Z`, - known_at: knownAt ?? `${sessionDate}T22:00:00.000000Z`, - }; -} - -/** - * In-memory evaluator for the planned universe SQL: applies the bound predicates - * positionally (currency list, session_date bounds, ts bound, known_at bound) to a - * fixture `bars_1d` table and returns DISTINCT listing_id ASC, the way DuckDB would. - * Fixed-width ISO strings compare chronologically, matching DuckDB's typed compare. - */ -function evaluatingExecutor(bars: readonly FixtureBar[]): Recorder { - return recorder((sql, params) => { - const inMatch = /b\.currency IN \(([?, ]+)\)/.exec(sql); - const currencyCount = inMatch === null ? 1 : (inMatch[1] ?? '').split('?').length - 1; - expect(sql).toContain( - currencyCount === 1 && inMatch === null ? 'b.currency = ?' : 'b.currency IN (' - ); - const currencies = params.slice(0, currencyCount) as string[]; - const [lo, hi, tsMax, knownMax] = params.slice(currencyCount) as string[]; - expect(params).toHaveLength(currencyCount + 4); - const ids = new Set(); - for (const b of bars) { - if ( - currencies.includes(b.currency) && - b.session_date >= (lo as string) && - b.session_date <= (hi as string) && - b.ts <= (tsMax as string) && - b.known_at <= (knownMax as string) - ) { - ids.add(b.listing_id); - } - } - return [...ids].sort((a, b) => a - b).map(listing_id => ({ listing_id })); - }); -} - -describe('T-122 QA: survivorship-free, no-look-ahead semantics over a fixture bars_1d table', () => { - const BARS: FixtureBar[] = [ - // 101: US listing delisted after 2025-03-10. - bar(101, 'USD', '2025-03-03'), - bar(101, 'USD', '2025-03-10'), - // 102: US IPO on 2025-03-14 (future relative to 2025-03-12). - bar(102, 'USD', '2025-03-14'), - bar(102, 'USD', '2025-03-17'), - // 201: CAD TSX line trading throughout. - bar(201, 'CAD', '2025-03-05'), - bar(201, 'CAD', '2025-03-12'), - bar(201, 'CAD', '2025-03-19'), - // 202: USD-quoted TSX line (provisional rule -> US_EQ). - bar(202, 'USD', '2025-03-11'), - // 301: only bar on 2025-03-12 was published (known_at) the next morning. - bar(301, 'USD', '2025-03-12', '2025-03-13T09:30:00.000000Z'), - // 302: bar known exactly at the last microsecond of 2025-03-12 -> included. - bar(302, 'CAD', '2025-03-12', '2025-03-12T23:59:59.999999Z'), - // 401: last bar exactly 7 days before 2025-03-12 (inclusive lower bound). - bar(401, 'USD', '2025-03-05'), - // 402: last bar 8 days before 2025-03-12 (outside default window). - bar(402, 'CAD', '2025-03-04'), - ]; - - it('includes a delisted listing only while it traded and never includes a not-yet-listed IPO', async () => { - const fx = evaluatingExecutor(BARS); - const store = createDuckDbMarketDataStore({ - executor: fx.executor, - curatedRoot: ROOT, - vaultCutoffTs: CUTOFF_MS, - }); - - expect(await store.universe({ ref: 'US_EQ', date: '2025-03-12' })).toEqual([101, 202, 401]); - // 101 last traded 2025-03-10; window for 2025-03-17 is [03-10, 03-17] -> still included on the edge. - expect(await store.universe({ ref: 'US_EQ', date: '2025-03-17' })).toEqual([ - 101, 102, 202, 301, - ]); - // One day later 101 drops out (delisted), 102 remains. - expect(await store.universe({ ref: 'US_EQ', date: '2025-03-18' })).toEqual([102, 202, 301]); - }); - - it('excludes bars published after the end of date (known_at fence) and includes the last-microsecond publication', async () => { - const fx = evaluatingExecutor(BARS); - const store = createDuckDbMarketDataStore({ - executor: fx.executor, - curatedRoot: ROOT, - vaultCutoffTs: CUTOFF_MS, - }); - - const us = await store.universe({ ref: 'US_EQ', date: '2025-03-12' }); - expect(us).not.toContain(301); - // Next day the restated bar is known -> 301 is active. - expect(await store.universe({ ref: 'US_EQ', date: '2025-03-13' })).toContain(301); - - expect(await store.universe({ ref: 'CA_EQ', date: '2025-03-12' })).toEqual([201, 302]); - }); - - it('applies the provisional bar-currency membership rule and an inclusive 7-day lower bound', async () => { - const fx = evaluatingExecutor(BARS); - const store = createDuckDbMarketDataStore({ - executor: fx.executor, - curatedRoot: ROOT, - vaultCutoffTs: CUTOFF_MS, - }); - - const ca = await store.universe({ ref: 'CA_EQ', date: '2025-03-12' }); - const us = await store.universe({ ref: 'US_EQ', date: '2025-03-12' }); - const both = await store.universe({ ref: 'US_CA_EQ', date: '2025-03-12' }); - - expect(us).toContain(202); // USD-quoted TSX line lands in US_EQ - expect(ca).not.toContain(202); - expect(us).toContain(401); // exactly date - 7 days - expect(ca).not.toContain(402); // date - 8 days - expect(both).toEqual([...new Set([...us, ...ca])].sort((a, b) => a - b)); - - // A wider custom lookback picks up the 8-day-old listing and nothing else changes. - const wide = createDuckDbMarketDataStore({ - executor: evaluatingExecutor(BARS).executor, - curatedRoot: ROOT, - vaultCutoffTs: CUTOFF_MS, - universeLookbackDays: 8, - }); - expect(await wide.universe({ ref: 'CA_EQ', date: '2025-03-12' })).toEqual([201, 302, 402]); - }); -}); - -describe('T-122 QA: store/planner parity and adapter error paths', () => { - it('sends exactly the planUniverseQuery SQL and params for default and custom store lookbacks', async () => { - for (const lookback of [undefined, 1, 30]) { - const rec = recorder(); - const store = createDuckDbMarketDataStore({ - executor: rec.executor, - curatedRoot: ROOT, - vaultCutoffTs: CUTOFF_MS, - ...(lookback === undefined ? {} : { universeLookbackDays: lookback }), - }); - for (const ref of UNIVERSE_REFS) { - await store.universe({ ref, date: '2025-11-03' }); - const expected = planUniverseQuery( - { ref, date: '2025-11-03' }, - lookback === undefined ? CTX : { ...CTX, universeLookbackDays: lookback } - ); - const last = rec.log[rec.log.length - 1]; - expect(last?.kind).toBe('query'); - expect(last?.sql).toBe(expected.sql); - expect(last?.params).toEqual(expected.params); - } - } - }); - - it('runs the budget SET statements once and before any query under concurrent first universe calls', async () => { - const env = { STOCKBOT_DUCKDB_THREADS: '3', STOCKBOT_DUCKDB_MEMORY_LIMIT: '2GB' }; - const rec = recorder( - () => [{ listing_id: 1 }], - () => new Promise(resolve => setTimeout(resolve, 0)) - ); - const store = createDuckDbMarketDataStore({ - executor: rec.executor, - curatedRoot: ROOT, - vaultCutoffTs: CUTOFF_MS, - env, - }); - - const results = await Promise.all([ - store.universe({ ref: 'US_EQ', date: '2025-06-02' }), - store.universe({ ref: 'CA_EQ', date: '2025-06-02' }), - store.universe({ ref: 'US_CA_EQ', date: '2025-06-02' }), - ]); - - expect(results).toEqual([[1], [1], [1]]); - expect(rec.log.map(e => e.kind)).toEqual(['run', 'run', 'run', 'query', 'query', 'query']); - expect(rec.log.slice(0, 3).map(e => e.sql)).toEqual([ - ...resolveDuckDbConnectionBudget(env).statements, - ]); - }); - - it('propagates executor query errors unchanged and retries budget init after a failed SET', async () => { - const boom = new Error('duckdb io error'); - const failingQuery = recorder(() => Promise.reject(boom)); - const s1 = createDuckDbMarketDataStore({ - executor: failingQuery.executor, - curatedRoot: ROOT, - vaultCutoffTs: CUTOFF_MS, - }); - await expect(s1.universe({ ref: 'US_EQ', date: '2025-06-02' })).rejects.toBe(boom); - - let failFirstRun = true; - const flakyRun = recorder( - () => [{ listing_id: 7 }], - () => { - if (failFirstRun) { - failFirstRun = false; - throw new Error('SET failed'); - } - } - ); - const s2 = createDuckDbMarketDataStore({ - executor: flakyRun.executor, - curatedRoot: ROOT, - vaultCutoffTs: CUTOFF_MS, - }); - await expect(s2.universe({ ref: 'US_EQ', date: '2025-06-02' })).rejects.toThrow('SET failed'); - expect(flakyRun.log.some(e => e.kind === 'query')).toBe(false); - expect(await s2.universe({ ref: 'US_EQ', date: '2025-06-02' })).toEqual([7]); - }); - - it('returns a fresh array per call and does not mutate the caller query object', async () => { - const rows: TableRow[] = [{ listing_id: 3 }, { listing_id: 9 }]; - const rec = recorder(() => rows); - const store = createDuckDbMarketDataStore({ - executor: rec.executor, - curatedRoot: ROOT, - vaultCutoffTs: CUTOFF_MS, - }); - const q = Object.freeze({ ref: 'US_CA_EQ', date: '2025-06-02' }); - - const first = await store.universe(q); - first.push(99); - const second = await store.universe(q); - - expect(second).toEqual([3, 9]); - expect(q).toEqual({ ref: 'US_CA_EQ', date: '2025-06-02' }); - expect(rows).toEqual([{ listing_id: 3 }, { listing_id: 9 }]); - }); - - it('rejects a store-level universeLookbackDays at construction without touching the executor', () => { - const rec = recorder(); - expect(() => - createDuckDbMarketDataStore({ - executor: rec.executor, - curatedRoot: ROOT, - vaultCutoffTs: CUTOFF_MS, - universeLookbackDays: -7, - }) - ).toThrow(MarketDataStoreValidationError); - expect(rec.log).toHaveLength(0); - }); -}); - -describe('T-122 QA: seeded fence and lookback invariants', () => { - it('holds lookback arithmetic and Vault bounds across 600 seeded (date, lookback, ref, cutoff) cases', async () => { - const rng = mulberry32(20261129); - const baseMs = Date.UTC(2004, 0, 1); - let fencedCount = 0; - let plannedCount = 0; - - for (let i = 0; i < 600; i += 1) { - // Cutoff anywhere in 2020..2027, sometimes mid-day. - const cutoffDayMs = Date.UTC(2020, 0, 1) + Math.floor(rng() * 8 * 365) * DAY_MS; - const cutoffMs = rng() < 0.5 ? cutoffDayMs : cutoffDayMs + Math.floor(rng() * DAY_MS); - const dateMs = baseMs + Math.floor(rng() * 24 * 365) * DAY_MS; - const date = isoDate(dateMs); - const lookback = 1 + Math.floor(rng() * 400); - const ref = UNIVERSE_REFS[Math.floor(rng() * UNIVERSE_REFS.length)] ?? 'US_EQ'; - const ctx: DuckDbPlanContext = { - curatedRoot: ROOT, - vaultCutoffTs: cutoffMs, - universeLookbackDays: lookback, - }; - - if (dateMs >= cutoffMs) { - fencedCount += 1; - expect(() => planUniverseQuery({ ref, date }, ctx)).toThrow(VaultHoldoutFenceError); - // Same class bars uses for a vault_fenced range starting on that date. - expect(() => - planBars1dQuery( - { listingIds: [1], timeframe: '1d', from: date, to: date, adjustment: 'raw' }, - ctx - ) - ).toThrow(VaultHoldoutFenceError); - const rec = recorder(); - const store = createDuckDbMarketDataStore({ - executor: rec.executor, - curatedRoot: ROOT, - vaultCutoffTs: cutoffMs, - }); - await expect(store.universe({ ref, date })).rejects.toBeInstanceOf(VaultHoldoutFenceError); - expect(rec.log).toHaveLength(0); - continue; - } - - plannedCount += 1; - const planned = planUniverseQuery({ ref, date }, ctx); - const n = ref === 'US_CA_EQ' ? 2 : 1; - expect(planned.params).toHaveLength(n + 4); - const [lo, hi, tsMax, knownMax] = planned.params.slice(n) as string[]; - expect(lo).toBe(isoDate(dateMs - lookback * DAY_MS)); - expect(hi).toBe(date); - const endOfDateMs = dateMs + DAY_MS - 1; - const expectedUpperMs = Math.min(endOfDateMs, cutoffMs - 1); - expect(Date.parse(tsMax as string)).toBe(expectedUpperMs); - expect(tsMax).toBe(knownMax); - expect(Date.parse(tsMax as string)).toBeLessThan(cutoffMs); - // Never reads past the end of `date`. - expect((tsMax as string).slice(0, 10)).toBe(date); - expect(planned.fenced.clampedTo).toBe(endOfDateMs >= cutoffMs); - expect(planned.sql).not.toContain(date); - expect(planned.sql).not.toContain(lo as string); - } - - // Both branches must actually be exercised by the seed. - expect(fencedCount).toBeGreaterThan(50); - expect(plannedCount).toBeGreaterThan(50); - }); - - it('clamps to the first microsecond window when the cutoff is 1 ms after midnight of date', () => { - const cutoff = Date.UTC(2025, 2, 12, 0, 0, 0, 1); - const planned = planUniverseQuery( - { ref: 'US_EQ', date: '2025-03-12' }, - { curatedRoot: ROOT, vaultCutoffTs: cutoff } - ); - expect(planned.params).toEqual([ - 'USD', - '2025-03-05', - '2025-03-12', - '2025-03-12T00:00:00.000999Z', - '2025-03-12T00:00:00.000999Z', - ]); - expect(planned.fenced.clampedTo).toBe(true); - expect(planned.fenced.clampedAsOf).toBe(true); - }); - - it('produces identical SQL and params under TZ=UTC and TZ=America/Toronto', () => { - const prev = process.env.TZ; - try { - process.env.TZ = 'UTC'; - const a = planUniverseQuery({ ref: 'US_CA_EQ', date: '2025-03-09' }, CTX); // DST switch in Toronto - process.env.TZ = 'America/Toronto'; - const b = planUniverseQuery({ ref: 'US_CA_EQ', date: '2025-03-09' }, CTX); - expect(b).toEqual(a); - expect(a.params[2]).toBe('2025-03-02'); - } finally { - if (prev === undefined) { - delete process.env.TZ; - } else { - process.env.TZ = prev; - } - } - }); -}); diff --git a/libs/research/test/market-data-store-duckdb.qa.test.ts b/libs/research/test/market-data-store-duckdb.qa.test.ts deleted file mode 100644 index ed8ba65a..00000000 --- a/libs/research/test/market-data-store-duckdb.qa.test.ts +++ /dev/null @@ -1,318 +0,0 @@ -import { describe, expect, it } from 'bun:test'; -import { - AdjFactorsSnapshotError, - type BarBatch, - type DuckDbExecutor, - type DuckDbParam, - type DuckDbPlanContext, - MarketDataStoreValidationError, - type TableRow, - VaultHoldoutFenceError, - createDuckDbMarketDataStore, - planBars1dQuery, - planEventsQuery, - planFx1dQuery, - planShortsAsOfQuery, - resolveDuckDbConnectionBudget, -} from '@stock-bot/research'; - -// QA edge cases for T-119 that the primary suite does not pin down. - -const ROOT = '/data/curated'; -const CUTOFF_MS = Date.UTC(2026, 4, 28); // 2026-05-28T00:00:00.000Z -const CTX: DuckDbPlanContext = { curatedRoot: ROOT, vaultCutoffTs: CUTOFF_MS }; -const BUDGET_ENV = { STOCKBOT_DUCKDB_THREADS: '3', STOCKBOT_DUCKDB_MEMORY_LIMIT: '2GB' }; - -interface Recorder { - readonly executor: DuckDbExecutor; - readonly log: Array<{ kind: 'run' | 'query'; sql: string; params?: readonly DuckDbParam[] }>; -} - -function recorder( - onQuery: (sql: string, params: readonly DuckDbParam[]) => readonly TableRow[] = () => [] -): Recorder { - const log: Recorder['log'] = []; - return { - log, - executor: { - async run(sql) { - log.push({ kind: 'run', sql }); - }, - async query(sql, params) { - log.push({ kind: 'query', sql, params: [...params] }); - return onQuery(sql, params); - }, - }, - }; -} - -function fencedKv(asOfMicros: number | null, vaultCutoffMicros: number | null): TableRow[] { - return [ - { key: 'stock_bot.adj_factors.format_version', value: '1' }, - { key: 'stock_bot.adj_factors.snapshot_kind', value: 'point_in_time_fenced' }, - { key: 'stock_bot.adj_factors.as_of_micros', value: asOfMicros === null ? 'none' : String(asOfMicros) }, - { - key: 'stock_bot.adj_factors.vault_cutoff_micros', - value: vaultCutoffMicros === null ? 'none' : String(vaultCutoffMicros), - }, - { key: 'stock_bot.adj_factors.rows_written', value: '2' }, - { key: 'stock_bot.adj_factors.snapshot_checksum', value: '0x0123456789abcdef' }, - ]; -} - -async function drain(it: AsyncIterable): Promise { - const out: BarBatch[] = []; - for await (const b of it) { - out.push(b); - } - return out; -} - -describe('T-119 QA: listingIds boundaries and caller-input immutability', () => { - it('accepts exact INT32 bounds and binds them as numbers, never in SQL text', () => { - const planned = planBars1dQuery( - { - listingIds: [-2_147_483_648, 2_147_483_647], - timeframe: '1d', - from: '2025-01-02', - to: '2025-01-03', - adjustment: 'raw', - }, - CTX - ); - - expect(planned.params.slice(0, 2)).toEqual([-2_147_483_648, 2_147_483_647]); - expect(planned.sql).not.toContain('2147483647'); - expect(planned.sql).not.toContain('2147483648'); - expect(planned.sql).toContain('b.listing_id IN (?, ?)'); - }); - - it('deduplicates frozen listingIds and kinds (including -0 vs 0) without mutating caller arrays', () => { - const listingIds = Object.freeze([7, 0, -0, 7, 9]); - const kinds = Object.freeze(['filing', 'earnings', 'filing'] as const); - - const planned = planEventsQuery( - { kinds: [...kinds], listingIds: listingIds as number[], from: '2025-01-02', to: '2025-01-03' }, - CTX - ); - - expect(listingIds).toEqual([7, 0, -0, 7, 9]); - expect(planned.sql).toContain('e.kind IN (?, ?) AND e.listing_id IN (?, ?, ?)'); - expect(planned.params.slice(0, 5)).toEqual(['filing', 'earnings', 7, 0, 9]); - expect(Object.is(planned.params[3], 0)).toBe(true); - }); -}); - -describe('T-119 QA: timestamp precision and offsets', () => { - it('preserves explicit microsecond from/to/asOf digits and normalises offsets to UTC', () => { - const planned = planBars1dQuery( - { - listingIds: [1], - timeframe: '1d', - from: '2025-01-02T09:30:00.123456-05:00', - to: '2025-01-03T16:00:00.654321-05:00', - asOf: '2025-01-03T21:00:00.000001Z', - adjustment: 'raw', - }, - CTX - ); - - expect(planned.params).toEqual([ - 1, - '2025-01-02T14:30:00.123456Z', - '2025-01-03T21:00:00.654321Z', - '2025-01-03T21:00:00.000001Z', - ]); - }); - - it('binds a single-millisecond window with explicit micros ordered correctly and rejects inverted micros', () => { - const ok = planEventsQuery( - { - kinds: ['filing'], - from: '2025-01-02T10:00:00.000100Z', - to: '2025-01-02T10:00:00.000900Z', - }, - CTX - ); - expect(ok.params.slice(1, 3)).toEqual(['2025-01-02T10:00:00.000100Z', '2025-01-02T10:00:00.000900Z']); - - expect(() => - planEventsQuery( - { kinds: ['filing'], from: '2025-01-02T10:00:00.000900Z', to: '2025-01-02T10:00:00.000100Z' }, - CTX - ) - ).toThrow(MarketDataStoreValidationError); - }); -}); - -describe('T-119 QA: Vault bounds under a non-midnight cutoff', () => { - // computeVaultCutoffTs preserves the time-of-day of the max ingested ts, so cutoffs need not be midnight. - const cutoff = Date.UTC(2026, 4, 28, 14, 30, 0, 0); - const ctx: DuckDbPlanContext = { curatedRoot: ROOT, vaultCutoffTs: cutoff }; - const cutoffMinusOneMicroIso = '2026-05-28T14:29:59.999999Z'; - - it('clamps bars/events/fx upper ts and known_at bounds to cutoff - 1µs', () => { - const bars = planBars1dQuery( - { listingIds: [1], timeframe: '1d', from: '2026-05-01', to: '2026-12-31', asOf: '2027-01-01', adjustment: 'raw' }, - ctx - ); - expect(bars.params.slice(-2)).toEqual([cutoffMinusOneMicroIso, cutoffMinusOneMicroIso]); - - const events = planEventsQuery({ kinds: ['ceo_post'], from: '2026-05-01', to: '2026-05-28' }, ctx); - expect(events.params.slice(-2)).toEqual([cutoffMinusOneMicroIso, cutoffMinusOneMicroIso]); - - const fx = planFx1dQuery({ pair: 'USD.CAD', timeframe: '1d', from: '2026-05-01', to: '2026-06-30' }, ctx); - expect(fx.params).toEqual(['USDCAD', '2026-05-01T00:00:00.000Z', cutoffMinusOneMicroIso, cutoffMinusOneMicroIso]); - }); - - it('keeps shortsAsOf known_at strictly before the cutoff even when the report_date bound lands on the cutoff day', () => { - const shorts = planShortsAsOfQuery({ listingIds: [5], from: '2026-05-01', to: '2026-09-01' }, ctx); - - expect(shorts.params).toEqual([5, '2026-05-01', '2026-05-28', cutoffMinusOneMicroIso]); - expect(shorts.fenced.toMs).toBe(cutoff - 1); - expect(shorts.fenced.asOfMs).toBe(cutoff - 1); - }); - - it('rejects from exactly at a non-midnight cutoff but accepts from one millisecond earlier', () => { - expect(() => - planShortsAsOfQuery({ listingIds: [5], from: '2026-05-28T14:30:00Z', to: '2026-06-01' }, ctx) - ).toThrow(VaultHoldoutFenceError); - const planned = planShortsAsOfQuery( - { listingIds: [5], from: '2026-05-28T14:29:59.999Z', to: '2026-06-01' }, - ctx - ); - expect(planned.params.slice(1, 3)).toEqual(['2026-05-28', '2026-05-28']); - }); -}); - -describe('T-119 QA: adapter immutable-path flow and budget ordering', () => { - const IMMUTABLE = '/data/snapshots/adj_factors_2026-05-27.parquet'; - - it('runs env-derived budget SETs, then the footer query, then the bars query bound to the immutable path', async () => { - const asOfMicros = CUTOFF_MS * 1000 - 1; - const rec = recorder((sql) => { - if (sql.includes('parquet_kv_metadata')) { - return fencedKv(asOfMicros, CUTOFF_MS * 1000); - } - return [ - { listing_id: 42, ts: Date.UTC(2025, 0, 2, 21), open: 50, high: 51, low: 49, close: 50, volume: 2000, vwap: null, known_at: Date.UTC(2025, 0, 2, 22) }, - ]; - }); - const store = createDuckDbMarketDataStore({ - executor: rec.executor, - curatedRoot: ROOT, - vaultCutoffTs: CUTOFF_MS, - immutableAdjFactorsPath: IMMUTABLE, - env: BUDGET_ENV, - }); - - const batches = await drain( - store.bars({ listingIds: [42], timeframe: '1d', from: '2025-01-01', to: '2025-01-31', adjustment: 'split' }) - ); - - const budget = resolveDuckDbConnectionBudget(BUDGET_ENV).statements; - expect(rec.log.map((c) => c.kind)).toEqual(['run', 'run', 'run', 'query', 'query']); - expect(rec.log.slice(0, 3).map((c) => c.sql)).toEqual([...budget]); - expect(rec.log[3]?.sql).toContain(`parquet_kv_metadata('${IMMUTABLE}')`); - expect(rec.log[4]?.sql).toContain(`read_parquet('${IMMUTABLE}')`); - expect(rec.log[4]?.sql).not.toContain(`${ROOT}/adj_factors/part.parquet`); - expect(batches).toEqual([ - { - rows: [ - { listingId: 42, ts: Date.UTC(2025, 0, 2, 21), open: 50, high: 51, low: 49, close: 50, volume: 2000, vwap: null, knownAt: Date.UTC(2025, 0, 2, 22) }, - ], - }, - ]); - }); - - it('fails closed with incompatible_fence when the immutable snapshot fence differs from the query asOf, issuing no bars scan', async () => { - const rec = recorder((sql) => - sql.includes('parquet_kv_metadata') ? fencedKv(Date.UTC(2025, 5, 30) * 1000, CUTOFF_MS * 1000) : [] - ); - const store = createDuckDbMarketDataStore({ - executor: rec.executor, - curatedRoot: ROOT, - vaultCutoffTs: CUTOFF_MS, - immutableAdjFactorsPath: IMMUTABLE, - env: BUDGET_ENV, - }); - - const err = await drain( - store.bars({ listingIds: [42], timeframe: '1d', from: '2025-01-01', to: '2025-01-31', adjustment: 'total' }) - ).catch((e: unknown) => e); - - expect(err).toBeInstanceOf(AdjFactorsSnapshotError); - expect((err as AdjFactorsSnapshotError).code).toBe('incompatible_fence'); - expect(rec.log.filter((c) => c.kind === 'query')).toHaveLength(1); - expect(rec.log.some((c) => c.sql.includes('bars_1d'))).toBe(false); - }); - - it('does not run budget SETs when the first call fails validation, then runs them once on the next valid call', async () => { - const rec = recorder(); - const store = createDuckDbMarketDataStore({ - executor: rec.executor, - curatedRoot: ROOT, - vaultCutoffTs: CUTOFF_MS, - env: BUDGET_ENV, - }); - - await expect( - store.events({ kinds: ['filing'], listingIds: [1.5], from: '2025-01-01', to: '2025-01-02' }) - ).rejects.toBeInstanceOf(MarketDataStoreValidationError); - expect(rec.log).toHaveLength(0); - - await store.events({ kinds: ['filing'], from: '2025-01-01', to: '2025-01-02' }); - await store.fx({ pair: 'USD.CAD', timeframe: '1d', from: '2025-01-01', to: '2025-01-02' }); - expect(rec.log.map((c) => c.kind)).toEqual(['run', 'run', 'run', 'query', 'query']); - }); -}); - -describe('T-119 QA: pinned-artifact release failures', () => { - it('propagates a release() failure after a successful scan and still releases exactly once', async () => { - const asOfMicros = CUTOFF_MS * 1000 - 1; - const rec = recorder((sql) => (sql.includes('parquet_kv_metadata') ? fencedKv(asOfMicros, CUTOFF_MS * 1000) : [])); - let releases = 0; - const store = createDuckDbMarketDataStore({ - executor: rec.executor, - curatedRoot: ROOT, - vaultCutoffTs: CUTOFF_MS, - env: BUDGET_ENV, - pinAdjFactorsArtifact: () => ({ - pinnedPath: '/proc/self/fd/17', - release() { - releases += 1; - throw new Error('close failed'); - }, - }), - }); - - const err = await drain( - store.bars({ listingIds: [42], timeframe: '1d', from: '2025-01-01', to: '2025-01-31', adjustment: 'split' }) - ).catch((e: unknown) => e); - - expect((err as Error).message).toBe('close failed'); - expect(releases).toBe(1); - expect(rec.log.filter((c) => c.kind === 'query').map((c) => c.sql.includes('/proc/self/fd/17'))).toEqual([true, true]); - }); - - it('never calls the pinner for an adjusted query that fails the Vault fence', async () => { - const rec = recorder(); - let pins = 0; - const store = createDuckDbMarketDataStore({ - executor: rec.executor, - curatedRoot: ROOT, - vaultCutoffTs: CUTOFF_MS, - env: BUDGET_ENV, - pinAdjFactorsArtifact: () => { - pins += 1; - return { pinnedPath: '/proc/self/fd/17', release() {} }; - }, - }); - - await expect( - drain(store.bars({ listingIds: [42], timeframe: '1d', from: '2026-05-28', to: '2026-06-30', adjustment: 'split' })) - ).rejects.toBeInstanceOf(VaultHoldoutFenceError); - expect(pins).toBe(0); - expect(rec.log).toHaveLength(0); - }); -}); diff --git a/libs/research/test/market-data-store-duckdb.test.ts b/libs/research/test/market-data-store-duckdb.test.ts deleted file mode 100644 index 599edece..00000000 --- a/libs/research/test/market-data-store-duckdb.test.ts +++ /dev/null @@ -1,3279 +0,0 @@ -import { describe, expect, it } from 'bun:test'; -import { - ADJ_SNAPSHOT_FORMAT_VERSION, - ADJ_SNAPSHOT_KV_PREFIX, - type AdjFactorsArtifactPinner, - AdjFactorsSnapshotError, - type AdjFactorsSnapshotMetadata, - BARS_ADJUSTMENTS, - type BarBatch, - DEFAULT_UNIVERSE_LOOKBACK_DAYS, - type DuckDbExecutor, - type DuckDbParam, - type DuckDbPlanContext, - EVENT_KINDS, - EVENTS_COLUMNS, - FUNDAMENTALS_PIT_VALUE_FIELDS, - FX_1D_COLUMNS, - FX_PAIR_MAP, - MarketDataStoreNotImplementedError, - MarketDataStoreValidationError, - type PinnedAdjFactorsArtifact, - SHORTS_COLUMNS, - type TableRow, - UNIVERSE_REFS, - VaultHoldoutFenceError, - VaultScopeNotAuthorizedError, - createDuckDbMarketDataStore, - parseAdjFactorsSnapshotMetadata, - planAdjFactorsMetadataQuery, - planBars1dQuery, - planEventsQuery, - planFundamentalsAsOfQuery, - planFx1dQuery, - planShortsAsOfQuery, - planUniverseQuery, - resolveDuckDbConnectionBudget, - validateAdjFactorsArtifactPath, - validateCuratedRoot, - validateParquetFilePath, -} from '@stock-bot/research'; -import { - ADJ_SNAPSHOT_FORMAT_VERSION as subpathAdjSnapshotFormatVersion, - ADJ_SNAPSHOT_KV_PREFIX as subpathAdjSnapshotKvPrefix, - AdjFactorsSnapshotError as SubpathAdjFactorsSnapshotError, - BARS_ADJUSTMENTS as subpathBarsAdjustments, - DEFAULT_UNIVERSE_LOOKBACK_DAYS as subpathDefaultUniverseLookbackDays, - EVENT_KINDS as subpathEventKinds, - EVENTS_COLUMNS as subpathEventsColumns, - FUNDAMENTALS_PIT_VALUE_FIELDS as subpathFundamentalsPitValueFields, - FX_1D_COLUMNS as subpathFx1dColumns, - FX_PAIR_MAP as subpathFxPairMap, - MarketDataStoreNotImplementedError as SubpathNotImplementedError, - SHORTS_COLUMNS as subpathShortsColumns, - UNIVERSE_REFS as subpathUniverseRefs, - createDuckDbMarketDataStore as subpathCreateDuckDbMarketDataStore, - parseAdjFactorsSnapshotMetadata as subpathParseAdjFactorsSnapshotMetadata, - planAdjFactorsMetadataQuery as subpathPlanAdjFactorsMetadataQuery, - planBars1dQuery as subpathPlanBars1dQuery, - planEventsQuery as subpathPlanEventsQuery, - planFundamentalsAsOfQuery as subpathPlanFundamentalsAsOfQuery, - planFx1dQuery as subpathPlanFx1dQuery, - planShortsAsOfQuery as subpathPlanShortsAsOfQuery, - planUniverseQuery as subpathPlanUniverseQuery, - validateAdjFactorsArtifactPath as subpathValidateAdjFactorsArtifactPath, - validateCuratedRoot as subpathValidateCuratedRoot, - validateParquetFilePath as subpathValidateParquetFilePath, -} from '@stock-bot/research/market-data-store-duckdb'; - -const CURATED_ROOT = '/mnt/data/stockbot/curated'; -const DEFAULT_ADJ_PATH = `${CURATED_ROOT}/adj_factors/part.parquet`; -const CUTOFF_MS = Date.UTC(2026, 4, 28, 0, 0, 0, 0); // 2026-05-28T00:00:00.000Z -const CUTOFF_MICROS = CUTOFF_MS * 1000; -const MAX_ALLOWED_ISO_MICROS = '2026-05-27T23:59:59.999999Z'; -const MAX_ALLOWED_DATE = '2026-05-27'; - -const DEFAULT_CTX: DuckDbPlanContext = { - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, -}; - -function makeFencedKvRows(opts: { - snapshotKind?: string; - asOfMicros?: number | null; - vaultCutoffMicros?: number | null; - rowsWritten?: number; - checksum?: string; - formatVersion?: string; -}): TableRow[] { - return [ - { key: 'stock_bot.adj_factors.format_version', value: opts.formatVersion ?? '1' }, - { key: 'stock_bot.adj_factors.snapshot_kind', value: opts.snapshotKind ?? 'point_in_time_fenced' }, - { - key: 'stock_bot.adj_factors.as_of_micros', - value: opts.asOfMicros === undefined || opts.asOfMicros === null ? 'none' : String(opts.asOfMicros), - }, - { - key: 'stock_bot.adj_factors.vault_cutoff_micros', - value: - opts.vaultCutoffMicros === undefined || opts.vaultCutoffMicros === null - ? 'none' - : String(opts.vaultCutoffMicros), - }, - { key: 'stock_bot.adj_factors.rows_written', value: String(opts.rowsWritten ?? 1) }, - { - key: 'stock_bot.adj_factors.snapshot_checksum', - value: opts.checksum ?? '0x024ec73a1afe7e6b', - }, - ]; -} - -function makeFencedSnapshot(opts: { - path?: string; - asOfMicros?: number | null; - vaultCutoffMicros?: number | null; - rowsWritten?: number; -}): AdjFactorsSnapshotMetadata { - return parseAdjFactorsSnapshotMetadata( - opts.path ?? DEFAULT_ADJ_PATH, - makeFencedKvRows({ - asOfMicros: opts.asOfMicros, - vaultCutoffMicros: opts.vaultCutoffMicros, - rowsWritten: opts.rowsWritten, - }) - ); -} - -/** Parses a UTC ISO-8601 timestamp with optional up-to-microsecond fractional digits into epoch µs. */ -function parseIsoToMicros(iso: string): number { - const m = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?Z$/.exec(iso); - if (m === null) { - throw new Error(`Unexpected UTC ISO timestamp: ${iso}`); - } - const frac = (m[7] ?? '').padEnd(6, '0').slice(0, 6); - const ms = Number(frac.slice(0, 3)); - const subMs = Number(frac.slice(3, 6)); - const epochMs = Date.UTC( - Number(m[1]), - Number(m[2]) - 1, - Number(m[3]), - Number(m[4]), - Number(m[5]), - Number(m[6]), - ms - ); - return epochMs * 1000 + subMs; -} - -interface RecordedCall { - readonly kind: 'run' | 'query'; - readonly sql: string; - readonly params?: readonly DuckDbParam[]; -} - -interface RecordingFakeExecutor { - readonly executor: DuckDbExecutor; - readonly calls: RecordedCall[]; - readonly runCalls: string[]; - readonly queryCalls: Array<{ sql: string; params: readonly DuckDbParam[] }>; -} - -function createRecordingExecutor(options?: { - onRun?: (sql: string, callIndex: number) => Promise | void; - onQuery?: ( - sql: string, - params: readonly DuckDbParam[], - callIndex: number - ) => Promise | readonly TableRow[]; -}): RecordingFakeExecutor { - const calls: RecordedCall[] = []; - const runCalls: string[] = []; - const queryCalls: Array<{ sql: string; params: readonly DuckDbParam[] }> = []; - - const executor: DuckDbExecutor = { - async run(sql: string): Promise { - const idx = runCalls.length; - calls.push({ kind: 'run', sql }); - runCalls.push(sql); - if (options?.onRun !== undefined) { - await options.onRun(sql, idx); - } - }, - async query(sql: string, params: readonly DuckDbParam[]): Promise { - const idx = queryCalls.length; - const snapshot = [...params]; - calls.push({ kind: 'query', sql, params: snapshot }); - queryCalls.push({ sql, params: snapshot }); - if (options?.onQuery !== undefined) { - return await options.onQuery(sql, snapshot, idx); - } - return []; - }, - }; - - return { executor, calls, runCalls, queryCalls }; -} - -async function collectBars(iterable: AsyncIterable): Promise { - const batches: BarBatch[] = []; - for await (const batch of iterable) { - batches.push(batch); - } - return batches; -} - -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) / 4_294_967_296; - }; -} - -describe('market-data-store-duckdb exports', () => { - it('exposes identical runtime symbols from package root and subpath', () => { - expect(planBars1dQuery).toBe(subpathPlanBars1dQuery); - expect(planEventsQuery).toBe(subpathPlanEventsQuery); - expect(planShortsAsOfQuery).toBe(subpathPlanShortsAsOfQuery); - expect(planFx1dQuery).toBe(subpathPlanFx1dQuery); - expect(planUniverseQuery).toBe(subpathPlanUniverseQuery); - expect(planFundamentalsAsOfQuery).toBe(subpathPlanFundamentalsAsOfQuery); - expect(FUNDAMENTALS_PIT_VALUE_FIELDS).toBe(subpathFundamentalsPitValueFields); - expect(planAdjFactorsMetadataQuery).toBe(subpathPlanAdjFactorsMetadataQuery); - expect(parseAdjFactorsSnapshotMetadata).toBe(subpathParseAdjFactorsSnapshotMetadata); - expect(createDuckDbMarketDataStore).toBe(subpathCreateDuckDbMarketDataStore); - expect(validateCuratedRoot).toBe(subpathValidateCuratedRoot); - expect(validateParquetFilePath).toBe(subpathValidateParquetFilePath); - expect(validateAdjFactorsArtifactPath).toBe(subpathValidateAdjFactorsArtifactPath); - expect(MarketDataStoreNotImplementedError).toBe(SubpathNotImplementedError); - expect(AdjFactorsSnapshotError).toBe(SubpathAdjFactorsSnapshotError); - expect(ADJ_SNAPSHOT_FORMAT_VERSION).toBe(subpathAdjSnapshotFormatVersion); - expect(ADJ_SNAPSHOT_KV_PREFIX).toBe(subpathAdjSnapshotKvPrefix); - expect(EVENT_KINDS).toBe(subpathEventKinds); - expect(FX_PAIR_MAP).toBe(subpathFxPairMap); - expect(BARS_ADJUSTMENTS).toBe(subpathBarsAdjustments); - expect(UNIVERSE_REFS).toBe(subpathUniverseRefs); - expect(DEFAULT_UNIVERSE_LOOKBACK_DAYS).toBe(subpathDefaultUniverseLookbackDays); - expect(EVENTS_COLUMNS).toBe(subpathEventsColumns); - expect(SHORTS_COLUMNS).toBe(subpathShortsColumns); - expect(FX_1D_COLUMNS).toBe(subpathFx1dColumns); - }); -}); - -describe('pure DuckDB query planners — exact SQL and bound parameters', () => { - it('plans bars 1d raw query with hive_partitioning, bound listingIds, and PIT/Vault predicates', () => { - const inputListingIds = [101, 202, 101, -0]; - const planned = planBars1dQuery( - { - listingIds: inputListingIds, - timeframe: '1d', - from: '2024-01-02', - to: '2025-12-31', - adjustment: 'raw', - asOf: '2026-01-15T12:00:00Z', - }, - { curatedRoot: `${CURATED_ROOT}///`, vaultCutoffTs: CUTOFF_MS } - ); - - // Caller array must not be mutated - expect(inputListingIds).toEqual([101, 202, 101, -0]); - expect(Object.is(planned.params[2], 0)).toBe(true); - - expect(planned.sql).toBe( - 'SELECT b.listing_id, epoch_ms(b.ts) AS ts, b.open, b.high, b.low, b.close, b.volume, b.vwap, epoch_ms(b.known_at) AS known_at ' + - `FROM read_parquet('${CURATED_ROOT}/bars_1d/year=*/part.parquet', hive_partitioning = true) AS b ` + - 'WHERE b.listing_id IN (?, ?, ?) AND b.ts >= ? AND b.ts <= ? AND b.known_at <= ? ' + - 'ORDER BY b.listing_id ASC, b.ts ASC' - ); - expect(planned.params).toEqual([ - 101, - 202, - 0, - '2024-01-02T00:00:00.000Z', - '2025-12-31T23:59:59.999999Z', - '2026-01-15T12:00:00.000Z', - ]); - expect(planned.fenced.scope).toBe('vault_fenced'); - expect(planned.fenced.clampedTo).toBe(false); - expect(planned.fenced.clampedAsOf).toBe(false); - }); - - it('plans bars 1d split query with verified fenced adj_factors snapshot bound to read_parquet', () => { - const asOfMicros = parseIsoToMicros('2025-07-01T23:59:59.999999Z'); - const snapshot = makeFencedSnapshot({ - path: DEFAULT_ADJ_PATH, - asOfMicros, - vaultCutoffMicros: CUTOFF_MICROS, - }); - const planned = planBars1dQuery( - { - listingIds: [42, 77], - timeframe: '1d', - from: '2023-01-01', - to: '2025-06-30', - adjustment: 'split', - asOf: '2025-07-01', - }, - { ...DEFAULT_CTX, adjFactorsSnapshot: snapshot } - ); - - expect(planned.sql).toBe( - 'SELECT b.listing_id, epoch_ms(b.ts) AS ts, ' + - 'b.open / COALESCE(a.cum_split_factor, 1.0) AS open, ' + - 'b.high / COALESCE(a.cum_split_factor, 1.0) AS high, ' + - 'b.low / COALESCE(a.cum_split_factor, 1.0) AS low, ' + - 'b.close / COALESCE(a.cum_split_factor, 1.0) AS close, ' + - 'b.volume * COALESCE(a.cum_split_factor, 1.0) AS volume, ' + - 'b.vwap / COALESCE(a.cum_split_factor, 1.0) AS vwap, ' + - 'epoch_ms(b.known_at) AS known_at ' + - `FROM read_parquet('${CURATED_ROOT}/bars_1d/year=*/part.parquet', hive_partitioning = true) AS b ` + - `ASOF LEFT JOIN (SELECT listing_id, ex_date, cum_split_factor FROM read_parquet('${DEFAULT_ADJ_PATH}') WHERE listing_id IN (?, ?) AND known_at <= ?) AS a ` + - 'ON b.listing_id = a.listing_id AND b.session_date < a.ex_date ' + - 'WHERE b.listing_id IN (?, ?) AND b.ts >= ? AND b.ts <= ? AND b.known_at <= ? ' + - 'ORDER BY b.listing_id ASC, b.ts ASC' - ); - expect(planned.params).toEqual([ - 42, - 77, - '2025-07-01T23:59:59.999999Z', - 42, - 77, - '2023-01-01T00:00:00.000Z', - '2025-06-30T23:59:59.999999Z', - '2025-07-01T23:59:59.999999Z', - ]); - }); - - it('plans bars 1d total query dividing prices by cum_total_factor and multiplying volume by cum_split_factor', () => { - const snapshot = makeFencedSnapshot({ - path: '/adj_factors/part.parquet', - asOfMicros: null, - vaultCutoffMicros: CUTOFF_MICROS, - }); - const planned = planBars1dQuery( - { - listingIds: [7], - timeframe: '1d', - from: '2020-01-01', - to: '2025-01-01', - adjustment: 'total', - }, - { curatedRoot: '/', vaultCutoffTs: CUTOFF_MS, adjFactorsSnapshot: snapshot } - ); - - expect(planned.sql).toBe( - 'SELECT b.listing_id, epoch_ms(b.ts) AS ts, ' + - 'b.open / COALESCE(a.cum_total_factor, 1.0) AS open, ' + - 'b.high / COALESCE(a.cum_total_factor, 1.0) AS high, ' + - 'b.low / COALESCE(a.cum_total_factor, 1.0) AS low, ' + - 'b.close / COALESCE(a.cum_total_factor, 1.0) AS close, ' + - 'b.volume * COALESCE(a.cum_split_factor, 1.0) AS volume, ' + - 'b.vwap / COALESCE(a.cum_total_factor, 1.0) AS vwap, ' + - 'epoch_ms(b.known_at) AS known_at ' + - "FROM read_parquet('/bars_1d/year=*/part.parquet', hive_partitioning = true) AS b " + - "ASOF LEFT JOIN (SELECT listing_id, ex_date, cum_split_factor, cum_total_factor FROM read_parquet('/adj_factors/part.parquet') WHERE listing_id IN (?) AND known_at <= ?) AS a " + - 'ON b.listing_id = a.listing_id AND b.session_date < a.ex_date ' + - 'WHERE b.listing_id IN (?) AND b.ts >= ? AND b.ts <= ? AND b.known_at <= ? ' + - 'ORDER BY b.listing_id ASC, b.ts ASC' - ); - expect(planned.params).toEqual([ - 7, - MAX_ALLOWED_ISO_MICROS, - 7, - '2020-01-01T00:00:00.000Z', - '2025-01-01T23:59:59.999999Z', - MAX_ALLOWED_ISO_MICROS, - ]); - }); - - it('plans events query with and without listingIds using complete Parquet writer tie-breaker ordering', () => { - const kinds: Array<'filing' | 'earnings'> = ['filing', 'earnings', 'filing']; - const withListings = planEventsQuery( - { - kinds, - listingIds: [10, 20], - from: '2025-01-01', - to: '2025-03-31', - asOf: '2025-04-01T00:00:00Z', - }, - DEFAULT_CTX - ); - - expect(kinds).toEqual(['filing', 'earnings', 'filing']); - expect(withListings.sql).toBe( - 'SELECT e.listing_id, epoch_ms(e.ts) AS ts, epoch_ms(e.known_at) AS known_at, e.known_at_source, e.kind, e.subtype, e.payload_json ' + - `FROM read_parquet('${CURATED_ROOT}/events/year=*/part.parquet', hive_partitioning = true) AS e ` + - 'WHERE e.kind IN (?, ?) AND e.listing_id IN (?, ?) AND e.ts >= ? AND e.ts <= ? AND e.known_at <= ? ' + - 'ORDER BY e.listing_id ASC, e.ts ASC, e.kind ASC, e.subtype ASC, e.payload_json ASC, e.known_at ASC, e.known_at_source ASC' - ); - expect(withListings.params).toEqual([ - 'filing', - 'earnings', - 10, - 20, - '2025-01-01T00:00:00.000Z', - '2025-03-31T23:59:59.999999Z', - '2025-04-01T00:00:00.000Z', - ]); - - const withoutListings = planEventsQuery( - { - kinds: ['corporate_action'], - from: '2025-01-01', - to: '2025-03-31', - }, - DEFAULT_CTX - ); - expect(withoutListings.sql).toBe( - 'SELECT e.listing_id, epoch_ms(e.ts) AS ts, epoch_ms(e.known_at) AS known_at, e.known_at_source, e.kind, e.subtype, e.payload_json ' + - `FROM read_parquet('${CURATED_ROOT}/events/year=*/part.parquet', hive_partitioning = true) AS e ` + - 'WHERE e.kind IN (?) AND e.ts >= ? AND e.ts <= ? AND e.known_at <= ? ' + - 'ORDER BY e.listing_id ASC, e.ts ASC, e.kind ASC, e.subtype ASC, e.payload_json ASC, e.known_at ASC, e.known_at_source ASC' - ); - expect(withoutListings.params).toEqual([ - 'corporate_action', - '2025-01-01T00:00:00.000Z', - '2025-03-31T23:59:59.999999Z', - MAX_ALLOWED_ISO_MICROS, - ]); - }); - - it('orders two distinct filings sharing (listing_id, ts, kind, subtype) deterministically via payload_json tie-breaker', async () => { - const sameSecondMs = Date.UTC(2025, 2, 10, 21, 5, 0); - const filingA: TableRow = { - listing_id: 10, - ts: sameSecondMs, - known_at: sameSecondMs, - known_at_source: 'filing_timestamp', - kind: 'filing', - subtype: '8-k', - payload_json: '{"accession":"0001","item":"2.02"}', - }; - const filingB: TableRow = { - listing_id: 10, - ts: sameSecondMs, - known_at: sameSecondMs, - known_at_source: 'filing_timestamp', - kind: 'filing', - subtype: '8-k', - payload_json: '{"accession":"0002","item":"7.01"}', - }; - - const fake = createRecordingExecutor({ - onQuery: (sql) => { - // Confirm the SQL query requests the complete writer tie-breaker order. - expect(sql).toContain( - 'ORDER BY e.listing_id ASC, e.ts ASC, e.kind ASC, e.subtype ASC, e.payload_json ASC, e.known_at ASC, e.known_at_source ASC' - ); - // Simulate DuckDB sorting rows by the exact ORDER BY key. - return [filingB, filingA].sort((a, b) => - String(a.payload_json).localeCompare(String(b.payload_json)) - ); - }, - }); - - const store = createDuckDbMarketDataStore({ - executor: fake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - env: {}, - }); - - const result = await store.events({ - kinds: ['filing'], - listingIds: [10], - from: '2025-03-10', - to: '2025-03-10', - }); - expect(result.rows).toEqual([filingA, filingB]); - }); - - it('plans shortsAsOf query binding UTC YYYY-MM-DD report_date bounds and microsecond ISO known_at bound', () => { - const planned = planShortsAsOfQuery( - { - listingIds: [500, 600], - from: '2024-06-01', - to: '2026-08-01', // clamped to 2026-05-27T23:59:59.999999Z - asOf: '2026-09-01', // clamped to 2026-05-27T23:59:59.999999Z - }, - DEFAULT_CTX - ); - - expect(planned.sql).toBe( - 'SELECT s.listing_id, CAST(s.report_date AS VARCHAR) AS report_date, epoch_ms(s.known_at) AS known_at, s.shares_short, s.net_change, s.pct_float, s.source ' + - `FROM read_parquet('${CURATED_ROOT}/shorts/part.parquet') AS s ` + - 'WHERE s.listing_id IN (?, ?) AND s.report_date >= ? AND s.report_date <= ? AND s.known_at <= ? ' + - 'ORDER BY s.listing_id ASC, s.report_date ASC' - ); - expect(planned.params).toEqual([ - 500, - 600, - '2024-06-01', - MAX_ALLOWED_DATE, - MAX_ALLOWED_ISO_MICROS, - ]); - expect(planned.fenced.clampedTo).toBe(true); - expect(planned.fenced.clampedAsOf).toBe(true); - }); - - it('plans fx 1d query mapping USD.CAD to bound USDCAD and enforcing vault_fenced microsecond default asOf', () => { - const planned = planFx1dQuery( - { - pair: 'USD.CAD', - timeframe: '1d', - from: '2022-01-01', - to: '2026-10-01', // clamped - }, - DEFAULT_CTX - ); - - expect(planned.sql).toBe( - 'SELECT f.pair, CAST(f.session_date AS VARCHAR) AS session_date, epoch_ms(f.ts) AS ts, f.open, f.high, f.low, f.close, f.source, epoch_ms(f.known_at) AS known_at ' + - `FROM read_parquet('${CURATED_ROOT}/fx_1d/part.parquet') AS f ` + - 'WHERE f.pair = ? AND f.ts >= ? AND f.ts <= ? AND f.known_at <= ? ' + - 'ORDER BY f.session_date ASC' - ); - expect(planned.params).toEqual([ - 'USDCAD', - '2022-01-01T00:00:00.000Z', - MAX_ALLOWED_ISO_MICROS, - MAX_ALLOWED_ISO_MICROS, - ]); - expect(planned.fenced.scope).toBe('vault_fenced'); - expect(planned.fenced.clampedTo).toBe(true); - expect(planned.fenced.asOfMs).toBe(CUTOFF_MS - 1); - }); -}); - -describe('FX 1d microsecond bounds (curate_fx_1d 23:59:59.999999Z compatibility)', () => { - it('includes a single-day FX session stamped at 23:59:59.999999Z for date-only from=to', () => { - const planned = planFx1dQuery( - { - pair: 'USD.CAD', - timeframe: '1d', - from: '2025-01-15', - to: '2025-01-15', - }, - DEFAULT_CTX - ); - - expect(planned.params).toEqual([ - 'USDCAD', - '2025-01-15T00:00:00.000Z', - '2025-01-15T23:59:59.999999Z', - MAX_ALLOWED_ISO_MICROS, - ]); - - const writerTsMicros = parseIsoToMicros('2025-01-15T23:59:59.999999Z'); - const boundFromMicros = parseIsoToMicros(planned.params[1] as string); - const boundToMicros = parseIsoToMicros(planned.params[2] as string); - const boundAsOfMicros = parseIsoToMicros(planned.params[3] as string); - - expect(writerTsMicros).toBeGreaterThanOrEqual(boundFromMicros); - expect(writerTsMicros).toBeLessThanOrEqual(boundToMicros); - expect(writerTsMicros).toBeLessThanOrEqual(boundAsOfMicros); - expect(boundToMicros).toBeLessThan(CUTOFF_MICROS); - expect(boundAsOfMicros).toBeLessThan(CUTOFF_MICROS); - }); - - it('includes the last pre-Vault FX session (2026-05-27T23:59:59.999999Z) while excluding the Vault cutoff day', () => { - const planned = planFx1dQuery( - { - pair: 'USD.CAD', - timeframe: '1d', - from: '2026-05-27', - to: '2026-05-27', - }, - DEFAULT_CTX - ); - - expect(planned.params).toEqual([ - 'USDCAD', - '2026-05-27T00:00:00.000Z', - '2026-05-27T23:59:59.999999Z', - '2026-05-27T23:59:59.999999Z', - ]); - - const lastPreVaultMicros = parseIsoToMicros('2026-05-27T23:59:59.999999Z'); - const firstVaultMicros = parseIsoToMicros('2026-05-28T00:00:00.000000Z'); - const boundToMicros = parseIsoToMicros(planned.params[2] as string); - const boundAsOfMicros = parseIsoToMicros(planned.params[3] as string); - - expect(lastPreVaultMicros).toBeLessThanOrEqual(boundToMicros); - expect(lastPreVaultMicros).toBeLessThanOrEqual(boundAsOfMicros); - expect(boundToMicros).toBeLessThan(firstVaultMicros); - expect(boundAsOfMicros).toBeLessThan(firstVaultMicros); - }); - - it('preserves explicit time-of-day upper bounds without expanding to .999999Z', () => { - const explicitSec = planFx1dQuery( - { - pair: 'USD.CAD', - timeframe: '1d', - from: '2025-01-15T00:00:00Z', - to: '2025-01-15T16:00:00Z', - }, - DEFAULT_CTX - ); - expect(explicitSec.params[2]).toBe('2025-01-15T16:00:00.000Z'); - - const explicitMs = planFx1dQuery( - { - pair: 'USD.CAD', - timeframe: '1d', - from: '2025-01-15T00:00:00Z', - to: '2025-01-15T23:59:59.999Z', - }, - DEFAULT_CTX - ); - expect(explicitMs.params[2]).toBe('2025-01-15T23:59:59.999Z'); - // Writer's 23:59:59.999999Z is excluded when caller explicitly asks for <= 23:59:59.999Z. - expect(parseIsoToMicros('2025-01-15T23:59:59.999999Z')).toBeGreaterThan( - parseIsoToMicros(explicitMs.params[2] as string) - ); - }); - - it('keeps clamped/default upper bounds strictly before non-midnight Vault cutoffs', () => { - const nonMidnightCutoffMs = Date.UTC(2026, 4, 28, 12, 30, 0, 500); - const planned = planFx1dQuery( - { - pair: 'USD.CAD', - timeframe: '1d', - from: '2026-05-01', - to: '2026-06-01', - }, - { curatedRoot: CURATED_ROOT, vaultCutoffTs: nonMidnightCutoffMs } - ); - expect(planned.params[2]).toBe('2026-05-28T12:30:00.499999Z'); - expect(planned.params[3]).toBe('2026-05-28T12:30:00.499999Z'); - expect(parseIsoToMicros(planned.params[2] as string)).toBe(nonMidnightCutoffMs * 1000 - 1); - }); -}); - -describe('adj_factors snapshot verification & Vault future-split leakage prevention', () => { - it('plans parquet_kv_metadata query bound to the exact adj_factors file path', () => { - const metaQuery = planAdjFactorsMetadataQuery(DEFAULT_ADJ_PATH); - expect(metaQuery).toEqual({ - path: DEFAULT_ADJ_PATH, - sql: - 'SELECT decode(key) AS key, decode(value) AS value ' + - `FROM parquet_kv_metadata('${DEFAULT_ADJ_PATH}') ` + - 'WHERE decode(key) LIKE ?', - params: ['stock_bot.adj_factors.%'], - }); - - expect(() => planAdjFactorsMetadataQuery("'/evil.parquet")).toThrow( - MarketDataStoreValidationError - ); - expect(() => planAdjFactorsMetadataQuery('/data/adj_factors/part.csv')).toThrow( - MarketDataStoreValidationError - ); - }); - - it('parses valid curate-etl footer metadata and rejects missing, malformed, or unsupported metadata', () => { - const asOfMicros = Date.UTC(2018, 2, 14, 12, 0, 0) * 1000; - const parsed = parseAdjFactorsSnapshotMetadata( - DEFAULT_ADJ_PATH, - makeFencedKvRows({ asOfMicros, vaultCutoffMicros: null, rowsWritten: 42 }) - ); - expect(parsed).toEqual({ - path: DEFAULT_ADJ_PATH, - formatVersion: 1, - snapshotKind: 'point_in_time_fenced', - fence: { asOfMicros, vaultCutoffMicros: null }, - rowsWritten: 42, - snapshotChecksum: '0x024ec73a1afe7e6b', - }); - - // Missing metadata - expect(() => parseAdjFactorsSnapshotMetadata(DEFAULT_ADJ_PATH, [])).toThrow( - AdjFactorsSnapshotError - ); - try { - parseAdjFactorsSnapshotMetadata(DEFAULT_ADJ_PATH, []); - } catch (err) { - expect((err as AdjFactorsSnapshotError).code).toBe('missing_metadata'); - } - - // Unsupported version - try { - parseAdjFactorsSnapshotMetadata( - DEFAULT_ADJ_PATH, - makeFencedKvRows({ formatVersion: '2', asOfMicros }) - ); - expect.unreachable('should throw unsupported_version'); - } catch (err) { - expect(err).toBeInstanceOf(AdjFactorsSnapshotError); - expect((err as AdjFactorsSnapshotError).code).toBe('unsupported_version'); - } - - // Duplicate key - expect(() => - parseAdjFactorsSnapshotMetadata(DEFAULT_ADJ_PATH, [ - ...makeFencedKvRows({ asOfMicros }), - { key: 'stock_bot.adj_factors.format_version', value: '1' }, - ]) - ).toThrow(AdjFactorsSnapshotError); - - // Unknown stock_bot.adj_factors.* key - expect(() => - parseAdjFactorsSnapshotMetadata(DEFAULT_ADJ_PATH, [ - ...makeFencedKvRows({ asOfMicros }), - { key: 'stock_bot.adj_factors.extra', value: '1' }, - ]) - ).toThrow(AdjFactorsSnapshotError); - - // Invalid checksum - expect(() => - parseAdjFactorsSnapshotMetadata( - DEFAULT_ADJ_PATH, - makeFencedKvRows({ asOfMicros, checksum: 'deadbeef' }) - ) - ).toThrow(AdjFactorsSnapshotError); - - // Retrospective with non-none fence - expect(() => - parseAdjFactorsSnapshotMetadata( - DEFAULT_ADJ_PATH, - makeFencedKvRows({ snapshotKind: 'retrospective', asOfMicros }) - ) - ).toThrow(AdjFactorsSnapshotError); - - // Fenced with both bounds none - expect(() => - parseAdjFactorsSnapshotMetadata( - DEFAULT_ADJ_PATH, - makeFencedKvRows({ - snapshotKind: 'point_in_time_fenced', - asOfMicros: null, - vaultCutoffMicros: null, - }) - ) - ).toThrow(AdjFactorsSnapshotError); - }); - - it('rejects retrospective and mismatched-fence snapshots and prevents Vault future-split leakage', async () => { - // Fixture mirroring tools/curate-etl/tests/curate_adj_qa_contract.rs: - // - Listing 42 has a visible 2-for-1 split on 2024-06-10 (pre-Vault) - // - Listing 42 has a held-out 2-for-1 split on 2026-07-15 (inside Vault, after CUTOFF_MS) - // - Raw close on 2024-06-07 (immediately before visible split) is 100.0. - // - Retrospective snapshot has cum_split_factor = 4.0 -> 100 / 4 = 25.0 (LEAK!). - // - Fenced snapshot (vault_cutoff = CUTOFF_MICROS) excludes the 2026-07-15 split before - // compounding, so cum_split_factor = 2.0 -> 100 / 2 = 50.0 (CLEAN!). - const rawPreSplitClose = 100.0; - - // 1. Planner rejects missing adjFactorsSnapshot for split/total - try { - planBars1dQuery( - { - listingIds: [42], - timeframe: '1d', - from: '2024-06-01', - to: '2024-06-15', - adjustment: 'split', - }, - DEFAULT_CTX - ); - expect.unreachable('should throw missing_snapshot'); - } catch (err) { - expect(err).toBeInstanceOf(AdjFactorsSnapshotError); - expect((err as AdjFactorsSnapshotError).code).toBe('missing_snapshot'); - } - - // 2. Adapter rejects retrospective adj_factors snapshot without executing bars query - const retroPath = `${CURATED_ROOT}/adj_factors/snapshots/retro.parquet`; - const retroFake = createRecordingExecutor({ - onQuery: (sql) => { - if (sql.includes('parquet_kv_metadata')) { - return makeFencedKvRows({ - snapshotKind: 'retrospective', - asOfMicros: null, - vaultCutoffMicros: null, - rowsWritten: 2, - }); - } - throw new Error('bars query must never run against retrospective adj_factors'); - }, - }); - const retroStore = createDuckDbMarketDataStore({ - executor: retroFake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - immutableAdjFactorsPath: retroPath, - env: {}, - }); - - try { - await collectBars( - retroStore.bars({ - listingIds: [42], - timeframe: '1d', - from: '2024-06-01', - to: '2024-06-15', - adjustment: 'split', - }) - ); - expect.unreachable('should reject retrospective snapshot'); - } catch (err) { - expect(err).toBeInstanceOf(AdjFactorsSnapshotError); - expect((err as AdjFactorsSnapshotError).code).toBe('retrospective_rejected'); - } - expect(retroFake.queryCalls).toHaveLength(1); - expect(retroFake.queryCalls[0]!.sql).toContain('parquet_kv_metadata'); - - // 3. Adapter rejects neighbouring fence 1 microsecond off (curate_adj_qa_contract.rs:282) - // and rejects a snapshot fenced past the Vault cutoff (which would embed the 2026-07-15 split). - const laterCutoffMicros = Date.UTC(2026, 7, 1, 0, 0, 0) * 1000; - const badPath = `${CURATED_ROOT}/adj_factors/snapshots/mismatched.parquet`; - for (const badFence of [ - { asOfMicros: CUTOFF_MICROS - 2, vaultCutoffMicros: CUTOFF_MICROS }, // 1 µs too early - { asOfMicros: null, vaultCutoffMicros: CUTOFF_MICROS + 1 }, // 1 µs past cutoff - { asOfMicros: null, vaultCutoffMicros: laterCutoffMicros }, // includes Vault split - ]) { - const badFake = createRecordingExecutor({ - onQuery: (sql) => { - if (sql.includes('parquet_kv_metadata')) { - return makeFencedKvRows({ ...badFence, rowsWritten: 2 }); - } - throw new Error('bars query must never run against mismatched fence'); - }, - }); - const badStore = createDuckDbMarketDataStore({ - executor: badFake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - immutableAdjFactorsPath: badPath, - env: {}, - }); - - try { - await collectBars( - badStore.bars({ - listingIds: [42], - timeframe: '1d', - from: '2024-06-01', - to: '2024-06-15', - adjustment: 'split', - }) - ); - expect.unreachable('should reject incompatible fence'); - } catch (err) { - expect(err).toBeInstanceOf(AdjFactorsSnapshotError); - expect((err as AdjFactorsSnapshotError).code).toBe('incompatible_fence'); - } - expect(badFake.queryCalls).toHaveLength(1); - } - - // 4. Adapter accepts exact fenced snapshot (vault_cutoff wins over later as_of, matching - // curate_adj_qa_contract.rs:303) bound to immutableAdjFactorsPath, and adjusts close by 2.0 (not 4.0). - const fencedAdjPath = `${CURATED_ROOT}/adj_factors/vault_2026_05_28/part.parquet`; - const fencedFake = createRecordingExecutor({ - onQuery: (sql) => { - if (sql.includes('parquet_kv_metadata')) { - expect(sql).toContain(`parquet_kv_metadata('${fencedAdjPath}')`); - return makeFencedKvRows({ - asOfMicros: Date.UTC(2026, 9, 1, 0, 0, 0) * 1000, // later as_of; vault_cutoff wins - vaultCutoffMicros: CUTOFF_MICROS, - rowsWritten: 1, // only the visible 2024-06-10 split - }); - } - // Verification is bound to the exact file read in the bars SQL. - expect(sql).toContain(`read_parquet('${fencedAdjPath}')`); - const fencedCumSplitFactor = 2.0; // Vault 2026-07-15 split excluded before compounding - return [ - { - listing_id: 42, - ts: Date.UTC(2024, 5, 7, 20, 0, 0), - open: rawPreSplitClose / fencedCumSplitFactor, - high: rawPreSplitClose / fencedCumSplitFactor, - low: rawPreSplitClose / fencedCumSplitFactor, - close: rawPreSplitClose / fencedCumSplitFactor, - volume: 1000 * fencedCumSplitFactor, - vwap: null, - known_at: Date.UTC(2024, 5, 7, 20, 0, 0), - }, - ]; - }, - }); - const fencedStore = createDuckDbMarketDataStore({ - executor: fencedFake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - immutableAdjFactorsPath: fencedAdjPath, - env: {}, - }); - - const batches = await collectBars( - fencedStore.bars({ - listingIds: [42], - timeframe: '1d', - from: '2024-06-01', - to: '2024-06-15', - adjustment: 'split', - }) - ); - expect(batches).toHaveLength(1); - expect(batches[0]!.rows[0]!.close).toBe(50.0); - expect(batches[0]!.rows[0]!.volume).toBe(2000); - expect(fencedFake.runCalls).toHaveLength(3); - expect(fencedFake.queryCalls).toHaveLength(2); - expect(fencedFake.calls.slice(0, 3).map(c => c.kind)).toEqual(['run', 'run', 'run']); - }); - - it('pins a single artifact version across footer check and factor scan when ETL atomically replaces part.parquet', async () => { - // Regression for TOCTOU between parquet_kv_metadata and read_parquet: - // Fixture mirrors tools/curate-etl/tests/curate_adj_qa_contract.rs: - // - Listing 42: visible 2-for-1 split (2024-06-10) + held-out Vault 2-for-1 split (2026-07-15) - // - Raw close on 2024-06-07: 100.0 - // - Inode 1 (fenced, vault_cutoff = CUTOFF_MICROS): cum_split_factor = 2.0 -> close = 50.0 - // - Inode 2 (retrospective replacement): cum_split_factor = 4.0 -> close = 25.0 (LEAK!) - interface VirtualAdjInode { - readonly id: number; - readonly kvRows: TableRow[]; - readonly cumSplitFactor: number; - } - - const fencedInode: VirtualAdjInode = { - id: 1, - kvRows: makeFencedKvRows({ - asOfMicros: null, - vaultCutoffMicros: CUTOFF_MICROS, - rowsWritten: 1, - checksum: '0x024ec73a1afe7e6b', - }), - cumSplitFactor: 2.0, - }; - const retrospectiveInode: VirtualAdjInode = { - id: 2, - kvRows: makeFencedKvRows({ - snapshotKind: 'retrospective', - asOfMicros: null, - vaultCutoffMicros: null, - rowsWritten: 2, - checksum: '0x9999999999999999', - }), - cumSplitFactor: 4.0, - }; - - // Simulated POSIX directory entry + open file-descriptor table - const dirEntries = new Map([[DEFAULT_ADJ_PATH, fencedInode]]); - const openFds = new Map(); - let nextFd = 42; - const releasedFds: string[] = []; - - const pinAdjFactorsArtifact: AdjFactorsArtifactPinner = (sourcePath) => { - const inode = dirEntries.get(sourcePath); - if (inode === undefined) { - throw new Error(`ENOENT: ${sourcePath}`); - } - const fdPath = `/proc/self/fd/${nextFd}`; - nextFd += 1; - openFds.set(fdPath, inode); - return { - pinnedPath: fdPath, - release() { - openFds.delete(fdPath); - releasedFds.push(fdPath); - }, - }; - }; - - const resolvePath = (path: string): VirtualAdjInode => { - const inode = openFds.get(path) ?? dirEntries.get(path); - if (inode === undefined) { - throw new Error(`ENOENT: ${path}`); - } - return inode; - }; - - const rawPreSplitClose = 100.0; - let swapped = false; - const fake = createRecordingExecutor({ - onQuery: (sql) => { - const metaMatch = /parquet_kv_metadata\('([^']+)'\)/.exec(sql); - if (metaMatch !== null) { - const path = metaMatch[1]!; - const inode = resolvePath(path); - // Simulate ETL atomically replacing the published path RIGHT BETWEEN - // footer verification and the bars factor scan. - if (!swapped) { - swapped = true; - dirEntries.set(DEFAULT_ADJ_PATH, retrospectiveInode); - } - return inode.kvRows; - } - const readMatches = [...sql.matchAll(/read_parquet\('([^']+)'\)/g)]; - expect(readMatches).toHaveLength(1); - const adjPath = readMatches[0]![1]!; - const inode = resolvePath(adjPath); - return [ - { - listing_id: 42, - ts: Date.UTC(2024, 5, 7, 20, 0, 0), - open: rawPreSplitClose / inode.cumSplitFactor, - high: rawPreSplitClose / inode.cumSplitFactor, - low: rawPreSplitClose / inode.cumSplitFactor, - close: rawPreSplitClose / inode.cumSplitFactor, - volume: 1000 * inode.cumSplitFactor, - vwap: null, - known_at: Date.UTC(2024, 5, 7, 20, 0, 0), - }, - ]; - }, - }); - - const store = createDuckDbMarketDataStore({ - executor: fake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - pinAdjFactorsArtifact, - env: {}, - }); - - // 1. In-flight query pinned Inode 1 before ETL replaced DEFAULT_ADJ_PATH with Inode 2. - // Both parquet_kv_metadata and read_parquet read /proc/self/fd/42 -> Inode 1 -> close = 50.0. - const batches = await collectBars( - store.bars({ - listingIds: [42], - timeframe: '1d', - from: '2024-06-01', - to: '2024-06-15', - adjustment: 'split', - }) - ); - expect(swapped).toBe(true); - expect(batches).toHaveLength(1); - expect(batches[0]!.rows[0]!.close).toBe(50.0); - expect(batches[0]!.rows[0]!.volume).toBe(2000); - expect(fake.queryCalls).toHaveLength(2); - expect(fake.queryCalls[0]!.sql).toContain("parquet_kv_metadata('/proc/self/fd/42')"); - expect(fake.queryCalls[1]!.sql).toContain("read_parquet('/proc/self/fd/42')"); - expect(releasedFds).toEqual(['/proc/self/fd/42']); - expect(openFds.size).toBe(0); - - // 2. Next query opens the newly published retrospective Inode 2 via /proc/self/fd/43, - // fails closed on footer verification without scanning bars, and still releases the fd. - try { - await collectBars( - store.bars({ - listingIds: [42], - timeframe: '1d', - from: '2024-06-01', - to: '2024-06-15', - adjustment: 'split', - }) - ); - expect.unreachable('should fail closed on retrospective replacement'); - } catch (err) { - expect(err).toBeInstanceOf(AdjFactorsSnapshotError); - expect((err as AdjFactorsSnapshotError).code).toBe('retrospective_rejected'); - } - expect(fake.queryCalls).toHaveLength(3); - expect(fake.queryCalls[2]!.sql).toContain("parquet_kv_metadata('/proc/self/fd/43')"); - expect(releasedFds).toEqual(['/proc/self/fd/42', '/proc/self/fd/43']); - expect(openFds.size).toBe(0); - }); - - it('preserves the `this` receiver when calling pinned artifact `release()` after successful and failed scans', async () => { - class HandlePinnedArtifact implements PinnedAdjFactorsArtifact { - readonly pinnedPath: string; - released = false; - releaseCount = 0; - readonly fileHandle: { closed: boolean; close: () => Promise }; - - constructor(pinnedPath: string) { - this.pinnedPath = pinnedPath; - this.fileHandle = { - closed: false, - close: () => { - this.fileHandle.closed = true; - return Promise.resolve(); - }, - }; - } - - async release(): Promise { - if (!(this instanceof HandlePinnedArtifact)) { - throw new TypeError('release() was invoked without its PinnedAdjFactorsArtifact receiver'); - } - await this.fileHandle.close(); - this.released = true; - this.releaseCount += 1; - } - } - - const createdPins: HandlePinnedArtifact[] = []; - let nextFd = 100; - const pinAdjFactorsArtifact: AdjFactorsArtifactPinner = () => { - const pin = new HandlePinnedArtifact(`/proc/self/fd/${nextFd}`); - nextFd += 1; - createdPins.push(pin); - return pin; - }; - - let shouldFailScan = false; - const fake = createRecordingExecutor({ - onQuery: (sql) => { - if (sql.includes('parquet_kv_metadata')) { - return makeFencedKvRows({ - asOfMicros: null, - vaultCutoffMicros: CUTOFF_MICROS, - rowsWritten: 1, - }); - } - if (shouldFailScan) { - throw new Error('simulated DuckDB bars scan failure'); - } - return [ - { - listing_id: 42, - ts: Date.UTC(2024, 5, 7, 20, 0, 0), - open: 50.0, - high: 51.0, - low: 49.5, - close: 50.0, - volume: 2000, - vwap: 50.25, - known_at: Date.UTC(2024, 5, 7, 20, 0, 0), - }, - ]; - }, - }); - - const store = createDuckDbMarketDataStore({ - executor: fake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - pinAdjFactorsArtifact, - env: {}, - }); - - // 1. Successful split-adjusted scan: returns rows and invokes pin.release() with `this` intact. - const batches = await collectBars( - store.bars({ - listingIds: [42], - timeframe: '1d', - from: '2024-06-01', - to: '2024-06-15', - adjustment: 'split', - }) - ); - expect(batches).toHaveLength(1); - expect(batches[0]!.rows[0]!.close).toBe(50.0); - expect(createdPins).toHaveLength(1); - expect(createdPins[0]!.released).toBe(true); - expect(createdPins[0]!.fileHandle.closed).toBe(true); - expect(createdPins[0]!.releaseCount).toBe(1); - - // 2. Failed scan (executor error): propagates error and still invokes pin.release() with `this` intact. - shouldFailScan = true; - await expect( - collectBars( - store.bars({ - listingIds: [42], - timeframe: '1d', - from: '2024-06-01', - to: '2024-06-15', - adjustment: 'split', - }) - ) - ).rejects.toThrow('simulated DuckDB bars scan failure'); - expect(createdPins).toHaveLength(2); - expect(createdPins[1]!.released).toBe(true); - expect(createdPins[1]!.fileHandle.closed).toBe(true); - expect(createdPins[1]!.releaseCount).toBe(1); - }); - - it('fails closed on unpinned mutable adj_factors paths and buggy no-op pinners', async () => { - // 1. Default mutable path with neither pinAdjFactorsArtifact nor immutableAdjFactorsPath - const unpinnedFake = createRecordingExecutor(); - const unpinnedStore = createDuckDbMarketDataStore({ - executor: unpinnedFake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - env: {}, - }); - - try { - await collectBars( - unpinnedStore.bars({ - listingIds: [42], - timeframe: '1d', - from: '2024-06-01', - to: '2024-06-15', - adjustment: 'split', - }) - ); - expect.unreachable('should fail closed on unpinned mutable path'); - } catch (err) { - expect(err).toBeInstanceOf(AdjFactorsSnapshotError); - expect((err as AdjFactorsSnapshotError).code).toBe('unpinned_mutable_path'); - } - expect(unpinnedFake.calls).toHaveLength(0); - - // 2. Buggy no-op pinner returning the mutable path itself fails closed and still releases - let released = false; - const noopFake = createRecordingExecutor(); - const noopStore = createDuckDbMarketDataStore({ - executor: noopFake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - pinAdjFactorsArtifact: (sourcePath) => ({ - pinnedPath: sourcePath, - release() { - released = true; - }, - }), - env: {}, - }); - - try { - await collectBars( - noopStore.bars({ - listingIds: [42], - timeframe: '1d', - from: '2024-06-01', - to: '2024-06-15', - adjustment: 'total', - }) - ); - expect.unreachable('should reject no-op pinner returning mutable path'); - } catch (err) { - expect(err).toBeInstanceOf(AdjFactorsSnapshotError); - expect((err as AdjFactorsSnapshotError).code).toBe('unpinned_mutable_path'); - } - expect(released).toBe(true); - expect(noopFake.queryCalls).toHaveLength(0); - - // 3. Pinner returning malformed handle or invalid path rejects cleanly and releases when possible - const badHandleStore = createDuckDbMarketDataStore({ - executor: noopFake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - pinAdjFactorsArtifact: (() => null) as unknown as AdjFactorsArtifactPinner, - env: {}, - }); - await expect( - collectBars( - badHandleStore.bars({ - listingIds: [42], - timeframe: '1d', - from: '2024-06-01', - to: '2024-06-15', - adjustment: 'split', - }) - ) - ).rejects.toThrow(MarketDataStoreValidationError); - - let badPathReleased = false; - const badPathStore = createDuckDbMarketDataStore({ - executor: noopFake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - pinAdjFactorsArtifact: () => - ({ - pinnedPath: '/proc/self/fd/0', - release() { - badPathReleased = true; - }, - }) as PinnedAdjFactorsArtifact, - env: {}, - }); - await expect( - collectBars( - badPathStore.bars({ - listingIds: [42], - timeframe: '1d', - from: '2024-06-01', - to: '2024-06-15', - adjustment: 'split', - }) - ) - ).rejects.toThrow(MarketDataStoreValidationError); - expect(badPathReleased).toBe(true); - }); - - it('validates pinned fd handles and .parquet paths strictly in validateAdjFactorsArtifactPath', () => { - expect(validateAdjFactorsArtifactPath('/proc/self/fd/12')).toBe('/proc/self/fd/12'); - expect(validateAdjFactorsArtifactPath('/dev/fd/5')).toBe('/dev/fd/5'); - expect(validateAdjFactorsArtifactPath(DEFAULT_ADJ_PATH)).toBe(DEFAULT_ADJ_PATH); - - for (const bad of [ - '', - 'relative.parquet', - '/data/adj_factors/part.csv', - '/proc/self/fd/0', - '/proc/self/fd/-1', - '/proc/self/fd/abc', - "/proc/self/fd/12'; DROP TABLE x", - '/tmp/pin-*.parquet', - ]) { - expect(() => validateAdjFactorsArtifactPath(bad)).toThrow(MarketDataStoreValidationError); - } - }); - - it('rejects retrospective snapshot even under authorized vault_evaluation_only', () => { - const retroSnapshot = parseAdjFactorsSnapshotMetadata( - DEFAULT_ADJ_PATH, - makeFencedKvRows({ snapshotKind: 'retrospective', asOfMicros: null, vaultCutoffMicros: null }) - ); - - try { - planBars1dQuery( - { - listingIds: [42], - timeframe: '1d', - from: '2026-06-01', - to: '2026-07-01', - adjustment: 'split', - scope: 'vault_evaluation_only', - }, - { - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - vaultOperatorAuthorized: true, - adjFactorsSnapshot: retroSnapshot, - } - ); - expect.unreachable('should reject retrospective snapshot under vault_evaluation_only'); - } catch (err) { - expect(err).toBeInstanceOf(AdjFactorsSnapshotError); - expect((err as AdjFactorsSnapshotError).code).toBe('retrospective_rejected'); - } - }); -}); - -describe('mandatory Vault & PIT invariants + TZ invariance', () => { - it('enforces bound known_at <= ? and upper bounds < vaultCutoffTs across 400 seeded mixed queries', () => { - const rng = createMulberry32(20261129); - const baseMs = Date.UTC(2015, 0, 1, 0, 0, 0, 0); - const preCutoffSpanMs = CUTOFF_MS - baseMs - 86_400_000; - const postCutoffSpanMs = 365 * 86_400_000; - - for (let i = 0; i < 400; i += 1) { - const fromMs = baseMs + Math.floor(rng() * preCutoffSpanMs); - const toMs = fromMs + Math.floor(rng() * (CUTOFF_MS - fromMs + postCutoffSpanMs)); - const asOfMs = - rng() < 0.35 - ? undefined - : baseMs + Math.floor(rng() * (CUTOFF_MS - baseMs + postCutoffSpanMs)); - - const fromStr = - rng() < 0.5 ? new Date(fromMs).toISOString().slice(0, 10) : new Date(fromMs).toISOString(); - const toStr = - rng() < 0.5 ? new Date(toMs).toISOString().slice(0, 10) : new Date(toMs).toISOString(); - const asOfStr = - asOfMs === undefined - ? undefined - : rng() < 0.5 - ? new Date(asOfMs).toISOString().slice(0, 10) - : new Date(asOfMs).toISOString(); - - const kindIdx = i % 4; - let planned; - if (kindIdx === 0) { - const adj = BARS_ADJUSTMENTS[i % 3]!; - // Compute matching fenced snapshot for split/total - const rawPlan = planBars1dQuery( - { - listingIds: [1], - timeframe: '1d', - from: fromStr, - to: toStr, - adjustment: 'raw', - asOf: asOfStr, - }, - DEFAULT_CTX - ); - const effAsOfMicros = parseIsoToMicros(rawPlan.params[rawPlan.params.length - 1] as string); - const snapshot = makeFencedSnapshot({ - asOfMicros: effAsOfMicros, - vaultCutoffMicros: CUTOFF_MICROS, - }); - planned = planBars1dQuery( - { - listingIds: [1 + Math.floor(rng() * 100_000)], - timeframe: '1d', - from: fromStr, - to: toStr, - adjustment: adj, - asOf: asOfStr, - }, - adj === 'raw' ? DEFAULT_CTX : { ...DEFAULT_CTX, adjFactorsSnapshot: snapshot } - ); - expect(planned.sql).toContain('known_at <= ?'); - expect(planned.sql).toContain('b.ts <= ?'); - const boundTo = planned.params[planned.params.length - 2] as string; - const boundAsOf = planned.params[planned.params.length - 1] as string; - expect(parseIsoToMicros(boundTo)).toBeLessThan(CUTOFF_MICROS); - expect(parseIsoToMicros(boundAsOf)).toBeLessThan(CUTOFF_MICROS); - if (adj !== 'raw') { - const adjAsOf = planned.params[1] as string; - expect(parseIsoToMicros(adjAsOf)).toBeLessThan(CUTOFF_MICROS); - } - } else if (kindIdx === 1) { - planned = planEventsQuery( - { - kinds: [EVENT_KINDS[i % EVENT_KINDS.length]!], - listingIds: rng() < 0.5 ? [1 + Math.floor(rng() * 100_000)] : undefined, - from: fromStr, - to: toStr, - asOf: asOfStr, - }, - DEFAULT_CTX - ); - expect(planned.sql).toContain('e.known_at <= ?'); - expect(planned.sql).toContain('e.ts <= ?'); - const boundTo = planned.params[planned.params.length - 2] as string; - const boundAsOf = planned.params[planned.params.length - 1] as string; - expect(parseIsoToMicros(boundTo)).toBeLessThan(CUTOFF_MICROS); - expect(parseIsoToMicros(boundAsOf)).toBeLessThan(CUTOFF_MICROS); - } else if (kindIdx === 2) { - planned = planShortsAsOfQuery( - { - listingIds: [1 + Math.floor(rng() * 100_000)], - from: fromStr, - to: toStr, - asOf: asOfStr, - }, - DEFAULT_CTX - ); - expect(planned.sql).toContain('s.known_at <= ?'); - expect(planned.sql).toContain('s.report_date <= ?'); - const boundToDate = planned.params[planned.params.length - 2] as string; - const boundAsOf = planned.params[planned.params.length - 1] as string; - expect(Date.parse(`${boundToDate}T00:00:00.000Z`)).toBeLessThan(CUTOFF_MS); - expect(parseIsoToMicros(boundAsOf)).toBeLessThan(CUTOFF_MICROS); - } else { - planned = planFx1dQuery( - { - pair: 'USD.CAD', - timeframe: '1d', - from: fromStr, - to: toStr, - }, - DEFAULT_CTX - ); - expect(planned.sql).toContain('f.known_at <= ?'); - expect(planned.sql).toContain('f.ts <= ?'); - const boundTo = planned.params[planned.params.length - 2] as string; - const boundAsOf = planned.params[planned.params.length - 1] as string; - expect(parseIsoToMicros(boundTo)).toBeLessThan(CUTOFF_MICROS); - expect(parseIsoToMicros(boundAsOf)).toBeLessThan(CUTOFF_MICROS); - } - expect(planned.fenced.toMs).toBeLessThan(CUTOFF_MS); - expect(planned.fenced.asOfMs).toBeLessThan(CUTOFF_MS); - } - }); - - it('produces identical SQL and bound params under TZ=UTC and TZ=America/Toronto', () => { - const previousTz = process.env.TZ; - const asOfMicros = Date.UTC(2025, 10, 3, 6, 30, 0) * 1000; // 2025-11-03T01:30:00-05:00 - const snapshot = makeFencedSnapshot({ asOfMicros, vaultCutoffMicros: CUTOFF_MICROS }); - try { - const runAll = () => ({ - bars: planBars1dQuery( - { - listingIds: [101], - timeframe: '1d', - from: '2025-03-08', - to: '2025-11-02', - adjustment: 'total', - asOf: '2025-11-03T01:30:00-05:00', - }, - { ...DEFAULT_CTX, adjFactorsSnapshot: snapshot } - ), - events: planEventsQuery( - { - kinds: ['filing', 'earnings'], - from: '2025-03-08', - to: '2025-11-02', - }, - DEFAULT_CTX - ), - shorts: planShortsAsOfQuery( - { - listingIds: [101], - from: '2025-03-08', - to: '2025-11-02', - }, - DEFAULT_CTX - ), - fx: planFx1dQuery( - { - pair: 'USD.CAD', - timeframe: '1d', - from: '2025-03-08', - to: '2025-11-02', - }, - DEFAULT_CTX - ), - }); - - process.env.TZ = 'UTC'; - const utcResult = runAll(); - process.env.TZ = 'America/Toronto'; - const torontoResult = runAll(); - - expect(torontoResult).toEqual(utcResult); - } finally { - if (previousTz === undefined) { - delete process.env.TZ; - } else { - process.env.TZ = previousTz; - } - } - }); -}); - -describe('Vault fence enforcement with zero executor calls', () => { - it('throws VaultHoldoutFenceError when from >= vaultCutoffTs across all 4 endpoints (incl. split bars) with 0 executor calls', async () => { - const fake = createRecordingExecutor(); - const store = createDuckDbMarketDataStore({ - executor: fake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - }); - - await expect( - collectBars( - store.bars({ - listingIds: [1], - timeframe: '1d', - from: '2026-05-28', - to: '2026-06-01', - adjustment: 'raw', - }) - ) - ).rejects.toThrow(VaultHoldoutFenceError); - - await expect( - collectBars( - store.bars({ - listingIds: [1], - timeframe: '1d', - from: '2026-05-28', - to: '2026-06-01', - adjustment: 'split', - }) - ) - ).rejects.toThrow(VaultHoldoutFenceError); - - await expect( - store.events({ - kinds: ['filing'], - from: '2026-05-28T00:00:00Z', - to: '2026-06-01', - }) - ).rejects.toThrow(VaultHoldoutFenceError); - - await expect( - store.shortsAsOf({ - listingIds: [1], - from: '2026-05-29', - to: '2026-06-01', - }) - ).rejects.toThrow(VaultHoldoutFenceError); - - await expect( - store.fx({ - pair: 'USD.CAD', - timeframe: '1d', - from: '2026-05-28', - to: '2026-06-01', - }) - ).rejects.toThrow(VaultHoldoutFenceError); - - expect(fake.calls).toHaveLength(0); - }); - - it('throws VaultScopeNotAuthorizedError for unauthorized vault_evaluation_only with 0 executor calls', async () => { - const fake = createRecordingExecutor(); - const store = createDuckDbMarketDataStore({ - executor: fake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - }); - - await expect( - collectBars( - store.bars({ - listingIds: [1], - timeframe: '1d', - from: '2026-06-01', - to: '2026-07-01', - adjustment: 'split', - scope: 'vault_evaluation_only', - }) - ) - ).rejects.toThrow(VaultScopeNotAuthorizedError); - - expect(fake.calls).toHaveLength(0); - }); - - it('permits unclamped bars query when vault_evaluation_only is explicitly authorized', () => { - const planned = planBars1dQuery( - { - listingIds: [1], - timeframe: '1d', - from: '2026-06-01', - to: '2026-07-01', - adjustment: 'raw', - scope: 'vault_evaluation_only', - }, - { - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - vaultOperatorAuthorized: true, - } - ); - - expect(planned.fenced.scope).toBe('vault_evaluation_only'); - expect(planned.fenced.clampedTo).toBe(false); - expect(planned.params).toEqual([ - 1, - '2026-06-01T00:00:00.000Z', - '2026-07-01T23:59:59.999999Z', - '2026-07-01T23:59:59.999999Z', - ]); - }); - - it('keeps events, shortsAsOf, and fx vault_fenced even when vaultOperatorAuthorized is true', () => { - const authCtx: DuckDbPlanContext = { - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - vaultOperatorAuthorized: true, - }; - - expect(() => - planEventsQuery({ kinds: ['filing'], from: '2026-06-01', to: '2026-07-01' }, authCtx) - ).toThrow(VaultHoldoutFenceError); - expect(() => - planShortsAsOfQuery({ listingIds: [1], from: '2026-06-01', to: '2026-07-01' }, authCtx) - ).toThrow(VaultHoldoutFenceError); - expect(() => - planFx1dQuery({ pair: 'USD.CAD', timeframe: '1d', from: '2026-06-01', to: '2026-07-01' }, authCtx) - ).toThrow(VaultHoldoutFenceError); - }); -}); - -describe('SQL injection & strict boundary validation', () => { - it('rejects malicious or malformed curatedRoot values with MarketDataStoreValidationError', () => { - const badRoots = [ - '', - 'relative/path', - '/data/curated; DROP TABLE x', - "/data/curated' OR '1'='1", - '/data/curated\n/evil', - '/data/curated\r/evil', - '/data/curated\0/evil', - '/data/curated\x7f/evil', - '/data/curated/*', - '/data/curated/?', - '/data/curated/[a-z]', - '/data/curated/]', - ]; - - for (const root of badRoots) { - expect(() => validateCuratedRoot(root)).toThrow(MarketDataStoreValidationError); - expect(() => - planFx1dQuery( - { pair: 'USD.CAD', timeframe: '1d', from: '2025-01-01', to: '2025-02-01' }, - { curatedRoot: root, vaultCutoffTs: CUTOFF_MS } - ) - ).toThrow(MarketDataStoreValidationError); - } - }); - - it('rejects non-INT32, non-integer, non-number, or empty listingIds with zero executor calls', async () => { - const fake = createRecordingExecutor(); - const store = createDuckDbMarketDataStore({ - executor: fake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - }); - - const badListingIdInputs: unknown[] = [ - [], - [1.5], - [Number.NaN], - [Number.POSITIVE_INFINITY], - [Number.NEGATIVE_INFINITY], - [2_147_483_648], - [-2_147_483_649], - ['101' as unknown as number], - ]; - - for (const badIds of badListingIdInputs) { - await expect( - collectBars( - store.bars({ - listingIds: badIds as number[], - timeframe: '1d', - from: '2025-01-01', - to: '2025-02-01', - adjustment: 'raw', - }) - ) - ).rejects.toThrow(MarketDataStoreValidationError); - - await expect( - store.shortsAsOf({ - listingIds: badIds as number[], - from: '2025-01-01', - to: '2025-02-01', - }) - ).rejects.toThrow(MarketDataStoreValidationError); - } - - expect(fake.calls).toHaveLength(0); - }); - - it('rejects unknown/empty kinds, unsupported pair, invalid adjustment, and unknown timeframe with zero executor calls', async () => { - const fake = createRecordingExecutor(); - const store = createDuckDbMarketDataStore({ - executor: fake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - }); - - await expect( - store.events({ - kinds: [], - from: '2025-01-01', - to: '2025-02-01', - }) - ).rejects.toThrow(MarketDataStoreValidationError); - - await expect( - store.events({ - kinds: ["filing' OR '1'='1" as unknown as 'filing'], - from: '2025-01-01', - to: '2025-02-01', - }) - ).rejects.toThrow(MarketDataStoreValidationError); - - await expect( - store.fx({ - pair: 'EUR.USD' as unknown as 'USD.CAD', - timeframe: '1d', - from: '2025-01-01', - to: '2025-02-01', - }) - ).rejects.toThrow(MarketDataStoreValidationError); - - await expect( - store.fx({ - pair: 'USD.CAD', - timeframe: '2d' as unknown as '1d', - from: '2025-01-01', - to: '2025-02-01', - }) - ).rejects.toThrow(MarketDataStoreValidationError); - - await expect( - collectBars( - store.bars({ - listingIds: [1], - timeframe: '1d', - from: '2025-01-01', - to: '2025-02-01', - adjustment: 'dividend' as unknown as 'raw', - }) - ) - ).rejects.toThrow(MarketDataStoreValidationError); - - await expect( - collectBars( - store.bars({ - listingIds: [1], - timeframe: '2d' as unknown as '1d', - from: '2025-01-01', - to: '2025-02-01', - adjustment: 'raw', - }) - ) - ).rejects.toThrow(MarketDataStoreValidationError); - - expect(fake.calls).toHaveLength(0); - }); - - it('never embeds caller-supplied values other than validated curatedRoot/adjPath in SQL text', () => { - const sentinelId = 987654321; - const asOfMicros = Date.UTC(2025, 9, 5, 15, 45, 0) * 1000; - const snapshot = makeFencedSnapshot({ asOfMicros, vaultCutoffMicros: CUTOFF_MICROS }); - const barsPlan = planBars1dQuery( - { - listingIds: [sentinelId], - timeframe: '1d', - from: '2024-03-14', - to: '2025-09-22', - adjustment: 'total', - asOf: '2025-10-05T15:45:00Z', - }, - { ...DEFAULT_CTX, adjFactorsSnapshot: snapshot } - ); - expect(barsPlan.sql).not.toContain(String(sentinelId)); - expect(barsPlan.sql).not.toContain('2024-03-14'); - expect(barsPlan.sql).not.toContain('2025-09-22'); - expect(barsPlan.sql).not.toContain('2025-10-05'); - - const eventsPlan = planEventsQuery( - { - kinds: ['ceo_post'], - listingIds: [sentinelId], - from: '2024-03-14', - to: '2025-09-22', - }, - DEFAULT_CTX - ); - expect(eventsPlan.sql).not.toContain('ceo_post'); - expect(eventsPlan.sql).not.toContain(String(sentinelId)); - expect(eventsPlan.sql).not.toContain('2024-03-14'); - - const fxPlan = planFx1dQuery( - { - pair: 'USD.CAD', - timeframe: '1d', - from: '2024-03-14', - to: '2025-09-22', - }, - DEFAULT_CTX - ); - expect(fxPlan.sql).not.toContain('USD.CAD'); - expect(fxPlan.sql).not.toContain('USDCAD'); - expect(fxPlan.sql).not.toContain('2024-03-14'); - }); -}); - -describe('createDuckDbMarketDataStore adapter behavior', () => { - it('validates options eagerly at construction', () => { - const fake = createRecordingExecutor(); - - expect(() => - createDuckDbMarketDataStore({ - executor: {} as unknown as DuckDbExecutor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - }) - ).toThrow(MarketDataStoreValidationError); - - expect(() => - createDuckDbMarketDataStore({ - executor: fake.executor, - curatedRoot: 'relative', - vaultCutoffTs: CUTOFF_MS, - }) - ).toThrow(MarketDataStoreValidationError); - - expect(() => - createDuckDbMarketDataStore({ - executor: fake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - adjFactorsPath: "/evil'; DROP TABLE x;.parquet", - }) - ).toThrow(MarketDataStoreValidationError); - - expect(() => - createDuckDbMarketDataStore({ - executor: fake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - immutableAdjFactorsPath: DEFAULT_ADJ_PATH, - }) - ).toThrow(MarketDataStoreValidationError); - - expect(() => - createDuckDbMarketDataStore({ - executor: fake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - immutableAdjFactorsPath: `${CURATED_ROOT}//adj_factors/./sub/../part.parquet`, - }) - ).toThrow(MarketDataStoreValidationError); - - expect(() => - createDuckDbMarketDataStore({ - executor: fake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - adjFactorsPath: DEFAULT_ADJ_PATH, - immutableAdjFactorsPath: `${CURATED_ROOT}/adj_factors/snapshots/s1.parquet`, - }) - ).toThrow(MarketDataStoreValidationError); - - expect(() => - createDuckDbMarketDataStore({ - executor: fake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - pinAdjFactorsArtifact: 'not-a-fn' as unknown as AdjFactorsArtifactPinner, - }) - ).toThrow(MarketDataStoreValidationError); - - expect(() => - createDuckDbMarketDataStore({ - executor: fake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: Number.NaN, - }) - ).toThrow(MarketDataStoreValidationError); - - expect(() => - createDuckDbMarketDataStore({ - executor: fake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - barBatchSize: 0, - }) - ).toThrow(MarketDataStoreValidationError); - - expect(() => - createDuckDbMarketDataStore({ - executor: fake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - env: { STOCKBOT_DUCKDB_THREADS: '0' }, - }) - ).toThrow(MarketDataStoreValidationError); - - expect(fake.calls).toHaveLength(0); - }); - - it('runs the three budget SET statements sequentially, once, and strictly before the first query (including concurrent first calls)', async () => { - const env = { - STOCKBOT_DUCKDB_MEMORY_LIMIT: '4GB', - STOCKBOT_DUCKDB_THREADS: '2', - STOCKBOT_DUCKDB_TEMP_DIRECTORY: '/tmp/duckdb-test', - }; - const expectedStatements = resolveDuckDbConnectionBudget(env).statements; - - const fake = createRecordingExecutor({ - async onRun() { - await Promise.resolve(); - }, - async onQuery() { - return []; - }, - }); - - const store = createDuckDbMarketDataStore({ - executor: fake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - env, - }); - - // Zero calls before first query - expect(fake.calls).toHaveLength(0); - - await Promise.all([ - collectBars( - store.bars({ - listingIds: [1], - timeframe: '1d', - from: '2025-01-01', - to: '2025-02-01', - adjustment: 'raw', - }) - ), - store.events({ - kinds: ['filing'], - from: '2025-01-01', - to: '2025-02-01', - }), - store.shortsAsOf({ - listingIds: [1], - from: '2025-01-01', - to: '2025-02-01', - }), - store.fx({ - pair: 'USD.CAD', - timeframe: '1d', - from: '2025-01-01', - to: '2025-02-01', - }), - ]); - - expect(fake.runCalls).toEqual(expectedStatements); - expect(fake.queryCalls).toHaveLength(4); - expect(fake.calls.slice(0, 3).map(c => c.kind)).toEqual(['run', 'run', 'run']); - expect(fake.calls.slice(3).map(c => c.kind)).toEqual(['query', 'query', 'query', 'query']); - - // Subsequent call does not re-run SET statements - await store.fx({ - pair: 'USD.CAD', - timeframe: '1d', - from: '2025-01-01', - to: '2025-02-01', - }); - expect(fake.runCalls).toHaveLength(3); - expect(fake.queryCalls).toHaveLength(5); - }); - - it('retries budget initialization cleanly if an initial executor.run call rejects', async () => { - let failOnce = true; - const fake = createRecordingExecutor({ - async onRun(_sql, callIndex) { - if (failOnce && callIndex === 1) { - failOnce = false; - throw new Error('transient DuckDB SET failure'); - } - }, - onQuery: () => [], - }); - - const store = createDuckDbMarketDataStore({ - executor: fake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - env: {}, - }); - - await expect( - store.fx({ - pair: 'USD.CAD', - timeframe: '1d', - from: '2025-01-01', - to: '2025-02-01', - }) - ).rejects.toThrow('transient DuckDB SET failure'); - expect(fake.queryCalls).toHaveLength(0); - - // Second attempt retries all 3 SET statements and executes the query - const table = await store.fx({ - pair: 'USD.CAD', - timeframe: '1d', - from: '2025-01-01', - to: '2025-02-01', - }); - expect(table).toEqual({ columns: [...FX_1D_COLUMNS], rows: [] }); - expect(fake.runCalls).toHaveLength(5); // 2 from failed attempt + 3 from retry - expect(fake.queryCalls).toHaveLength(1); - }); - - it('maps BarBatch rows with nullable vwap, empty results, and barBatchSize chunking', async () => { - const sampleRows: TableRow[] = [ - { - listing_id: 101, - ts: Date.UTC(2025, 0, 2, 21, 0, 0), - open: 10, - high: 12, - low: 9.5, - close: 11.25, - volume: 1000, - vwap: 10.8, - known_at: Date.UTC(2025, 0, 2, 22, 0, 0), - }, - { - listing_id: 101, - ts: Date.UTC(2025, 0, 3, 21, 0, 0), - open: 11.25, - high: 11.5, - low: 10.9, - close: 11.1, - volume: 0, - vwap: null, - known_at: Date.UTC(2025, 0, 3, 22, 0, 0), - }, - { - listing_id: 202, - ts: Date.UTC(2025, 0, 2, 21, 0, 0), - open: 50, - high: 52, - low: 49, - close: 51, - volume: 500, - vwap: null, - known_at: Date.UTC(2025, 0, 2, 22, 0, 0), - }, - ]; - - const fake = createRecordingExecutor({ - onQuery: (_sql, _params, idx) => (idx === 0 ? sampleRows : []), - }); - - const store = createDuckDbMarketDataStore({ - executor: fake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - env: {}, - barBatchSize: 2, - }); - - const batches = await collectBars( - store.bars({ - listingIds: [101, 202], - timeframe: '1d', - from: '2025-01-01', - to: '2025-01-10', - adjustment: 'raw', - }) - ); - expect(batches).toHaveLength(2); - expect(batches[0]!.rows).toEqual([ - { - listingId: 101, - ts: Date.UTC(2025, 0, 2, 21, 0, 0), - open: 10, - high: 12, - low: 9.5, - close: 11.25, - volume: 1000, - vwap: 10.8, - knownAt: Date.UTC(2025, 0, 2, 22, 0, 0), - }, - { - listingId: 101, - ts: Date.UTC(2025, 0, 3, 21, 0, 0), - open: 11.25, - high: 11.5, - low: 10.9, - close: 11.1, - volume: 0, - vwap: null, - knownAt: Date.UTC(2025, 0, 3, 22, 0, 0), - }, - ]); - expect(batches[1]!.rows).toHaveLength(1); - expect(batches[1]!.rows[0]!.listingId).toBe(202); - - // Empty result yields 0 batches - const emptyBatches = await collectBars( - store.bars({ - listingIds: [101], - timeframe: '1d', - from: '2025-01-01', - to: '2025-01-10', - adjustment: 'raw', - }) - ); - expect(emptyBatches).toEqual([]); - }); - - it('maps Table rows for events, shortsAsOf, and fx and strips unexpected extra columns', async () => { - const fake = createRecordingExecutor({ - onQuery: (sql) => { - if (sql.includes('/events/')) { - return [ - { - listing_id: 10, - ts: 1_700_000_000_000, - known_at: 1_700_000_000_000, - known_at_source: 'filing_timestamp', - kind: 'filing', - subtype: '10-k', - payload_json: '{"form":"10-K"}', - extra_ignored: 'should-not-appear', - }, - ]; - } - if (sql.includes('/shorts/')) { - return [ - { - listing_id: 10, - report_date: '2025-01-15', - known_at: 1_737_500_000_000, - shares_short: 125_000, - net_change: null, - pct_float: null, - source: 'ceo_shorts', - }, - ]; - } - return [ - { - pair: 'USDCAD', - session_date: '2025-01-15', - ts: 1_736_985_599_999, - open: 1.43, - high: 1.44, - low: 1.425, - close: 1.435, - source: 'eod_cad_forex', - known_at: 1_736_985_599_999, - }, - ]; - }, - }); - - const store = createDuckDbMarketDataStore({ - executor: fake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - env: {}, - }); - - const events = await store.events({ - kinds: ['filing'], - from: '2023-01-01', - to: '2025-02-01', - }); - expect(events.columns).toEqual([...EVENTS_COLUMNS]); - expect(events.rows).toEqual([ - { - listing_id: 10, - ts: 1_700_000_000_000, - known_at: 1_700_000_000_000, - known_at_source: 'filing_timestamp', - kind: 'filing', - subtype: '10-k', - payload_json: '{"form":"10-K"}', - }, - ]); - - const shorts = await store.shortsAsOf({ - listingIds: [10], - from: '2025-01-01', - to: '2025-02-01', - }); - expect(shorts.columns).toEqual([...SHORTS_COLUMNS]); - expect(shorts.rows[0]!.net_change).toBeNull(); - expect(shorts.rows[0]!.pct_float).toBeNull(); - - const fx = await store.fx({ - pair: 'USD.CAD', - timeframe: '1d', - from: '2025-01-01', - to: '2025-02-01', - }); - expect(fx.columns).toEqual([...FX_1D_COLUMNS]); - expect(fx.rows[0]!.pair).toBe('USDCAD'); - }); - - it('validates per-column scalar types and nullability even when all expected columns are present', async () => { - const cases: Array<{ - label: string; - row: TableRow; - run: (store: ReturnType) => Promise; - }> = [ - { - label: 'fx stringified ts', - row: { - pair: 'USDCAD', - session_date: '2025-01-15', - ts: '2025-01-15T23:59:59.999999Z', // wrong scalar type (string instead of safe_int) - open: 1.43, - high: 1.44, - low: 1.425, - close: 1.435, - source: 'eod_cad_forex', - known_at: 1_736_985_599_999, - }, - run: (s) => s.fx({ pair: 'USD.CAD', timeframe: '1d', from: '2025-01-15', to: '2025-01-15' }), - }, - { - label: 'fx null close', - row: { - pair: 'USDCAD', - session_date: '2025-01-15', - ts: 1_736_985_599_999, - open: 1.43, - high: 1.44, - low: 1.425, - close: null, // forbidden null - source: 'eod_cad_forex', - known_at: 1_736_985_599_999, - }, - run: (s) => s.fx({ pair: 'USD.CAD', timeframe: '1d', from: '2025-01-15', to: '2025-01-15' }), - }, - { - label: 'events stringified listing_id', - row: { - listing_id: '10', // wrong scalar type (string instead of int32) - ts: 1_700_000_000_000, - known_at: 1_700_000_000_000, - known_at_source: 'filing_timestamp', - kind: 'filing', - subtype: '10-k', - payload_json: '{}', - }, - run: (s) => s.events({ kinds: ['filing'], from: '2023-01-01', to: '2025-02-01' }), - }, - { - label: 'shorts null required shares_short', - row: { - listing_id: 10, - report_date: '2025-01-15', - known_at: 1_737_500_000_000, - shares_short: null, // forbidden null - net_change: null, - pct_float: null, - source: 'ceo_shorts', - }, - run: (s) => s.shortsAsOf({ listingIds: [10], from: '2025-01-01', to: '2025-02-01' }), - }, - ]; - - for (const c of cases) { - const fake = createRecordingExecutor({ onQuery: () => [c.row] }); - const store = createDuckDbMarketDataStore({ - executor: fake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - env: {}, - }); - await expect(c.run(store)).rejects.toThrow(MarketDataStoreValidationError); - } - }); - - it('rejects malformed driver rows with MarketDataStoreValidationError and propagates executor errors', async () => { - const malformedFake = createRecordingExecutor({ - onQuery: (sql) => { - if (sql.includes('/bars_1d/')) { - return [{ listing_id: 101, ts: 1000, open: Number.NaN, high: 1, low: 1, close: 1, volume: 1, vwap: null, known_at: 1000 }]; - } - return [{ pair: 'USDCAD' }]; // missing columns - }, - }); - - const malformedStore = createDuckDbMarketDataStore({ - executor: malformedFake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - env: {}, - }); - - await expect( - collectBars( - malformedStore.bars({ - listingIds: [101], - timeframe: '1d', - from: '2025-01-01', - to: '2025-02-01', - adjustment: 'raw', - }) - ) - ).rejects.toThrow(MarketDataStoreValidationError); - - await expect( - malformedStore.fx({ - pair: 'USD.CAD', - timeframe: '1d', - from: '2025-01-01', - to: '2025-02-01', - }) - ).rejects.toThrow(MarketDataStoreValidationError); - - const failingFake = createRecordingExecutor({ - onQuery: async () => { - throw new Error('parquet file missing'); - }, - }); - const failingStore = createDuckDbMarketDataStore({ - executor: failingFake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - env: {}, - }); - - await expect( - failingStore.events({ - kinds: ['filing'], - from: '2025-01-01', - to: '2025-02-01', - }) - ).rejects.toThrow('parquet file missing'); - }); - - it('rejects all out-of-slice methods and timeframes with MarketDataStoreNotImplementedError and 0 executor calls', async () => { - const fake = createRecordingExecutor(); - const store = createDuckDbMarketDataStore({ - executor: fake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - env: {}, - }); - - const cases: Array<{ method: string; run: () => Promise }> = [ - { - method: 'bars', - run: () => - collectBars( - store.bars({ - listingIds: [1], - timeframe: '1m', - from: '2025-01-01', - to: '2025-02-01', - adjustment: 'raw', - }) - ), - }, - { - method: 'bars', - run: () => - collectBars( - store.bars({ - listingIds: [1], - timeframe: '5m', - from: '2025-01-01', - to: '2025-02-01', - adjustment: 'split', - }) - ), - }, - { - method: 'bars', - run: () => - collectBars( - store.bars({ - listingIds: [1], - timeframe: '1h', - from: '2025-01-01', - to: '2025-02-01', - adjustment: 'total', - }) - ), - }, - { - method: 'fx', - run: () => - store.fx({ - pair: 'USD.CAD', - timeframe: '1m', - from: '2025-01-01', - to: '2025-02-01', - }), - }, - { - method: 'crossSection', - run: () => - store.crossSection({ - features: ['ret_20d'], - date: '2025-01-15', - universe: 'US_EQ', - }), - }, - { - method: 'macroAsOf', - run: () => - store.macroAsOf({ - countries: ['US'], - indicators: ['CPI'], - from: '2025-01-01', - to: '2025-02-01', - }), - }, - ]; - - for (const c of cases) { - let caught: unknown; - try { - await c.run(); - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(MarketDataStoreNotImplementedError); - expect((caught as MarketDataStoreNotImplementedError).method).toBe(c.method); - } - - expect(fake.calls).toHaveLength(0); - }); -}); - -describe('planUniverseQuery & createDuckDbMarketDataStore().universe()', () => { - it('plans exact SQL and ordered bound parameters for US_EQ, CA_EQ, and US_CA_EQ without interpolation', () => { - expect(UNIVERSE_REFS).toEqual(['US_EQ', 'CA_EQ', 'US_CA_EQ']); - expect(DEFAULT_UNIVERSE_LOOKBACK_DAYS).toBe(7); - - const expectedSingleCurrencySql = - 'SELECT DISTINCT b.listing_id ' + - `FROM read_parquet('${CURATED_ROOT}/bars_1d/year=*/part.parquet', hive_partitioning = true) AS b ` + - 'WHERE b.currency = ? AND b.session_date >= ? AND b.session_date <= ? AND b.ts <= ? AND b.known_at <= ? ' + - 'ORDER BY b.listing_id ASC'; - const expectedDualCurrencySql = - 'SELECT DISTINCT b.listing_id ' + - `FROM read_parquet('${CURATED_ROOT}/bars_1d/year=*/part.parquet', hive_partitioning = true) AS b ` + - 'WHERE b.currency IN (?, ?) AND b.session_date >= ? AND b.session_date <= ? AND b.ts <= ? AND b.known_at <= ? ' + - 'ORDER BY b.listing_id ASC'; - - const us = planUniverseQuery({ ref: 'US_EQ', date: '2025-06-15' }, DEFAULT_CTX); - expect(us.sql).toBe(expectedSingleCurrencySql); - expect(us.params).toEqual([ - 'USD', - '2025-06-08', - '2025-06-15', - '2025-06-15T23:59:59.999999Z', - '2025-06-15T23:59:59.999999Z', - ]); - expect(us.fenced).toEqual({ - fromMs: Date.UTC(2025, 5, 8, 0, 0, 0, 0), - toMs: Date.UTC(2025, 5, 15, 23, 59, 59, 999), - asOfMs: Date.UTC(2025, 5, 15, 23, 59, 59, 999), - scope: 'vault_fenced', - clampedTo: false, - clampedAsOf: false, - }); - - const ca = planUniverseQuery({ ref: 'CA_EQ', date: '2025-06-15' }, DEFAULT_CTX); - expect(ca.sql).toBe(expectedSingleCurrencySql); - expect(ca.params).toEqual([ - 'CAD', - '2025-06-08', - '2025-06-15', - '2025-06-15T23:59:59.999999Z', - '2025-06-15T23:59:59.999999Z', - ]); - - const usCa = planUniverseQuery({ ref: 'US_CA_EQ', date: '2025-06-15' }, DEFAULT_CTX); - expect(usCa.sql).toBe(expectedDualCurrencySql); - expect(usCa.params).toEqual([ - 'USD', - 'CAD', - '2025-06-08', - '2025-06-15', - '2025-06-15T23:59:59.999999Z', - '2025-06-15T23:59:59.999999Z', - ]); - - // Verify no query values are interpolated into SQL text. - for (const planned of [us, ca, usCa]) { - expect(planned.sql).not.toContain('USD'); - expect(planned.sql).not.toContain('CAD'); - expect(planned.sql).not.toContain('2025-06-15'); - expect(planned.sql).not.toContain('2025-06-08'); - expect(planned.sql).not.toContain('23:59:59'); - } - }); - - it('enforces Vault holdout fence identically to bars under vault_fenced scope with zero executor calls', async () => { - const fake = createRecordingExecutor(); - const store = createDuckDbMarketDataStore({ - executor: fake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - vaultOperatorAuthorized: true, - }); - - // On and after midnight cutoff must throw VaultHoldoutFenceError even when vaultOperatorAuthorized is true. - for (const blockedDate of ['2026-05-28', '2026-05-29', '2026-10-01']) { - expect(() => - planUniverseQuery( - { ref: 'US_CA_EQ', date: blockedDate }, - { ...DEFAULT_CTX, vaultOperatorAuthorized: true } - ) - ).toThrow(VaultHoldoutFenceError); - - await expect(store.universe({ ref: 'US_CA_EQ', date: blockedDate })).rejects.toBeInstanceOf( - VaultHoldoutFenceError - ); - } - expect(fake.calls).toHaveLength(0); - - // Day before midnight cutoff succeeds with upper bounds strictly < vaultCutoffTs. - const dayBefore = planUniverseQuery({ ref: 'US_EQ', date: MAX_ALLOWED_DATE }, DEFAULT_CTX); - expect(dayBefore.params).toEqual([ - 'USD', - '2026-05-20', - MAX_ALLOWED_DATE, - MAX_ALLOWED_ISO_MICROS, - MAX_ALLOWED_ISO_MICROS, - ]); - expect(parseIsoToMicros(dayBefore.params[3] as string)).toBe(CUTOFF_MICROS - 1); - expect(parseIsoToMicros(dayBefore.params[4] as string)).toBe(CUTOFF_MICROS - 1); - expect(dayBefore.fenced.clampedTo).toBe(false); - expect(dayBefore.fenced.clampedAsOf).toBe(false); - - // Mid-day Vault cutoff on date clamps both ts and known_at to vaultCutoffTs * 1000 - 1 µs. - const midDayCutoffMs = Date.UTC(2026, 4, 27, 12, 0, 0, 0); - const midDayCutoffMicros = midDayCutoffMs * 1000; - const clamped = planUniverseQuery( - { ref: 'CA_EQ', date: '2026-05-27' }, - { curatedRoot: CURATED_ROOT, vaultCutoffTs: midDayCutoffMs } - ); - expect(clamped.params).toEqual([ - 'CAD', - '2026-05-20', - '2026-05-27', - '2026-05-27T11:59:59.999999Z', - '2026-05-27T11:59:59.999999Z', - ]); - expect(parseIsoToMicros(clamped.params[3] as string)).toBe(midDayCutoffMicros - 1); - expect(parseIsoToMicros(clamped.params[4] as string)).toBe(midDayCutoffMicros - 1); - expect(clamped.fenced.clampedTo).toBe(true); - expect(clamped.fenced.clampedAsOf).toBe(true); - }); - - it('computes calendar-day lookback across month, year, leap-day, and custom universeLookbackDays boundaries', () => { - // Month boundary: 2025-05-03 - 7d = 2025-04-26 - const monthBoundary = planUniverseQuery({ ref: 'US_EQ', date: '2025-05-03' }, DEFAULT_CTX); - expect(monthBoundary.params[1]).toBe('2025-04-26'); - expect(monthBoundary.params[2]).toBe('2025-05-03'); - - // Year boundary: 2025-01-03 - 7d = 2024-12-27 - const yearBoundary = planUniverseQuery({ ref: 'US_EQ', date: '2025-01-03' }, DEFAULT_CTX); - expect(yearBoundary.params[1]).toBe('2024-12-27'); - expect(yearBoundary.params[2]).toBe('2025-01-03'); - - // Leap year vs non-leap year - const leapYear = planUniverseQuery({ ref: 'US_EQ', date: '2024-03-04' }, DEFAULT_CTX); - expect(leapYear.params[1]).toBe('2024-02-26'); - const nonLeapYear = planUniverseQuery({ ref: 'US_EQ', date: '2023-03-04' }, DEFAULT_CTX); - expect(nonLeapYear.params[1]).toBe('2023-02-25'); - - // 1-day lookback across leap day: 2024-03-01 - 1d = 2024-02-29 - const leapDayOne = planUniverseQuery( - { ref: 'US_EQ', date: '2024-03-01' }, - { ...DEFAULT_CTX, universeLookbackDays: 1 } - ); - expect(leapDayOne.params[1]).toBe('2024-02-29'); - - // Custom universeLookbackDays changes ONLY the lower session_date bound param. - const defaultPlan = planUniverseQuery({ ref: 'US_CA_EQ', date: '2025-05-15' }, DEFAULT_CTX); - const customPlan = planUniverseQuery( - { ref: 'US_CA_EQ', date: '2025-05-15' }, - { ...DEFAULT_CTX, universeLookbackDays: 14 } - ); - expect(customPlan.sql).toBe(defaultPlan.sql); - expect(customPlan.params[0]).toBe(defaultPlan.params[0]); - expect(customPlan.params[1]).toBe(defaultPlan.params[1]); - expect(customPlan.params[2]).toBe('2025-05-01'); - expect(defaultPlan.params[2]).toBe('2025-05-08'); - expect(customPlan.params.slice(3)).toEqual(defaultPlan.params.slice(3)); - }); - - it('rejects invalid ref, date, query, and universeLookbackDays upfront with zero executor calls', async () => { - const fake = createRecordingExecutor(); - const store = createDuckDbMarketDataStore({ - executor: fake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - }); - - const badRefs: unknown[] = ['FX', '', 'us_eq', 'toString', '__proto__', 123, null, undefined]; - for (const ref of badRefs) { - let caught: unknown; - try { - planUniverseQuery({ ref: ref as string, date: '2025-01-15' }, DEFAULT_CTX); - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(MarketDataStoreValidationError); - expect((caught as MarketDataStoreValidationError).field).toBe('ref'); - - await expect(store.universe({ ref: ref as string, date: '2025-01-15' })).rejects.toBeInstanceOf( - MarketDataStoreValidationError - ); - } - - const badDates: unknown[] = [ - '', - '2025-01-15T12:00:00Z', - '2025/01/15', - '2025-02-29', - '2025-04-31', - '2025-13-01', - null, - undefined, - ]; - for (const date of badDates) { - let caught: unknown; - try { - planUniverseQuery({ ref: 'US_EQ', date: date as string }, DEFAULT_CTX); - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(MarketDataStoreValidationError); - expect((caught as MarketDataStoreValidationError).field).toBe('date'); - - await expect(store.universe({ ref: 'US_EQ', date: date as string })).rejects.toBeInstanceOf( - MarketDataStoreValidationError - ); - } - - const badQueries: unknown[] = [null, [], 'US_EQ', undefined]; - for (const q of badQueries) { - let caught: unknown; - try { - planUniverseQuery(q as { ref: string; date: string }, DEFAULT_CTX); - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(MarketDataStoreValidationError); - expect((caught as MarketDataStoreValidationError).field).toBe('query'); - - await expect(store.universe(q as { ref: string; date: string })).rejects.toBeInstanceOf( - MarketDataStoreValidationError - ); - } - - const badLookbacks: unknown[] = [0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY, '7', null]; - for (const lookback of badLookbacks) { - let caughtPlan: unknown; - try { - planUniverseQuery( - { ref: 'US_EQ', date: '2025-01-15' }, - { ...DEFAULT_CTX, universeLookbackDays: lookback as number } - ); - } catch (err) { - caughtPlan = err; - } - expect(caughtPlan).toBeInstanceOf(MarketDataStoreValidationError); - expect((caughtPlan as MarketDataStoreValidationError).field).toBe('universeLookbackDays'); - - let caughtStore: unknown; - try { - createDuckDbMarketDataStore({ - executor: fake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - universeLookbackDays: lookback as number, - }); - } catch (err) { - caughtStore = err; - } - expect(caughtStore).toBeInstanceOf(MarketDataStoreValidationError); - expect((caughtStore as MarketDataStoreValidationError).field).toBe('universeLookbackDays'); - } - - // Safe-integer overflow, epoch-underflow, and cutoff-impossible lookbacks must fail - // upfront at both planUniverseQuery and createDuckDbMarketDataStore with zero executor calls. - for (const impossibleLookback of [ - Number.MAX_SAFE_INTEGER, - 100_000_000_000, - 604_800_000, // 7 days accidentally passed in milliseconds - 100_100_000, // fits in safe ms (8.64864e15) but underflows supported date range - 740_129, // 1 day beyond 2026-05-27 -> 0000-01-01 at the 2026 fixture cutoff - ]) { - let caughtPlan: unknown; - try { - planUniverseQuery( - { ref: 'US_EQ', date: '2025-01-15' }, - { ...DEFAULT_CTX, universeLookbackDays: impossibleLookback } - ); - } catch (err) { - caughtPlan = err; - } - expect(caughtPlan).toBeInstanceOf(MarketDataStoreValidationError); - expect((caughtPlan as MarketDataStoreValidationError).field).toBe('universeLookbackDays'); - - let caughtStore: unknown; - try { - createDuckDbMarketDataStore({ - executor: fake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - universeLookbackDays: impossibleLookback, - }); - } catch (err) { - caughtStore = err; - } - expect(caughtStore).toBeInstanceOf(MarketDataStoreValidationError); - expect((caughtStore as MarketDataStoreValidationError).field).toBe('universeLookbackDays'); - } - - // Crossing before year 0000 (while still inside JS Date epoch range) must reject - // cleanly in both planUniverseQuery and store.universe with zero executor calls - // rather than truncating an extended signed ISO year (`-000001-...`). - let caughtYearZeroPlan: unknown; - try { - planUniverseQuery({ ref: 'US_EQ', date: '0000-01-05' }, DEFAULT_CTX); - } catch (err) { - caughtYearZeroPlan = err; - } - expect(caughtYearZeroPlan).toBeInstanceOf(MarketDataStoreValidationError); - expect((caughtYearZeroPlan as MarketDataStoreValidationError).field).toBe( - 'universeLookbackDays' - ); - - await expect(store.universe({ ref: 'US_EQ', date: '0000-01-05' })).rejects.toMatchObject({ - name: 'MarketDataStoreValidationError', - field: 'universeLookbackDays', - }); - - // Exact 0000-01-01 boundary succeeds with a valid YYYY-MM-DD lower bound. - const exactYearZero = planUniverseQuery({ ref: 'US_EQ', date: '0000-01-08' }, DEFAULT_CTX); - expect(exactYearZero.params[1]).toBe('0000-01-01'); - - // A lookback valid on the latest permitted date (2026-05-27 -> 0000-01-01) is accepted - // at store creation, but still rejected on earlier query dates with zero executor calls. - const boundaryStore = createDuckDbMarketDataStore({ - executor: fake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - universeLookbackDays: 740_128, - }); - const maxBoundaryPlan = planUniverseQuery( - { ref: 'US_EQ', date: MAX_ALLOWED_DATE }, - { ...DEFAULT_CTX, universeLookbackDays: 740_128 } - ); - expect(maxBoundaryPlan.params[1]).toBe('0000-01-01'); - - await expect( - boundaryStore.universe({ ref: 'US_EQ', date: '2026-05-26' }) - ).rejects.toMatchObject({ - name: 'MarketDataStoreValidationError', - field: 'universeLookbackDays', - }); - - expect(fake.calls).toHaveLength(0); - }); - - it('runs budget SET statements once before first store.universe query, maps strictly ascending IDs, normalizes -0, and handles empty results', async () => { - let callCount = 0; - const fake = createRecordingExecutor({ - onQuery: () => { - callCount += 1; - if (callCount === 1) { - return [{ listing_id: -2_147_483_648 }, { listing_id: -0 }, { listing_id: 42 }, { listing_id: 2_147_483_647 }]; - } - return []; - }, - }); - const store = createDuckDbMarketDataStore({ - executor: fake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - universeLookbackDays: 10, - }); - const expectedBudget = resolveDuckDbConnectionBudget().statements; - - const ids = await store.universe({ ref: 'US_CA_EQ', date: '2025-06-15' }); - expect(ids).toEqual([-2_147_483_648, 0, 42, 2_147_483_647]); - expect(Object.is(ids[1], 0)).toBe(true); - - expect(fake.runCalls).toEqual(expectedBudget); - expect(fake.calls.slice(0, 3).map((c) => c.kind)).toEqual(['run', 'run', 'run']); - expect(fake.calls[3]?.kind).toBe('query'); - expect(fake.queryCalls[0]?.params).toEqual([ - 'USD', - 'CAD', - '2025-06-05', - '2025-06-15', - '2025-06-15T23:59:59.999999Z', - '2025-06-15T23:59:59.999999Z', - ]); - - // Second call must not re-run budget SET statements and returns [] on empty result. - const empty = await store.universe({ ref: 'US_EQ', date: '2025-06-15' }); - expect(empty).toEqual([]); - expect(fake.runCalls).toHaveLength(3); - expect(fake.queryCalls).toHaveLength(2); - }); - - it('throws MarketDataStoreValidationError on malformed, out-of-INT32, duplicate, or unsorted executor rows', async () => { - const badResults: unknown[] = [ - 'not-an-array', - [null], - [{}], - [{ listing_id: 1.5 }], - [{ listing_id: Number.NaN }], - [{ listing_id: '10' }], - [{ listing_id: null }], - [{ listing_id: -2_147_483_649 }], - [{ listing_id: 2_147_483_648 }], - [{ listing_id: 10 }, { listing_id: 10 }], - [{ listing_id: 20 }, { listing_id: 10 }], - ]; - - for (const rawResult of badResults) { - const fake = createRecordingExecutor({ - onQuery: () => rawResult as readonly TableRow[], - }); - const store = createDuckDbMarketDataStore({ - executor: fake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - }); - - await expect(store.universe({ ref: 'US_EQ', date: '2025-06-15' })).rejects.toBeInstanceOf( - MarketDataStoreValidationError - ); - } - }); -}); - -describe('planFundamentalsAsOfQuery & createDuckDbMarketDataStore().fundamentalsAsOf()', () => { - const EXPECTED_GLOB = `${CURATED_ROOT}/fundamentals_pit/year=*/part.parquet`; - - it('exports the exact 9 allow-listed FUNDAMENTALS_PIT_VALUE_FIELDS and plans parameterized Hive Parquet SQL', () => { - expect(FUNDAMENTALS_PIT_VALUE_FIELDS).toEqual([ - 'revenue', - 'net_income', - 'operating_cash_flow', - 'total_assets', - 'total_equity', - 'shares_outstanding', - 'ttm_revenue', - 'ttm_net_income', - 'ttm_operating_cash_flow', - ]); - - const nonTtm = planFundamentalsAsOfQuery( - { - listingIds: [202, 101, 202], - fields: ['net_income', 'revenue', 'net_income'], - asOf: '2025-06-15', - }, - DEFAULT_CTX - ); - - expect(nonTtm.sql).toBe( - 'WITH latest AS (SELECT f.listing_id, f.effective_known_at, f.known_at_source, f.has_estimated_lag, f.period_end, f.fiscal_period, f.currency, f.period_known_at, f.net_income, f.revenue ' + - 'FROM read_parquet(?, hive_partitioning = true) AS f ' + - 'WHERE f.listing_id IN (?, ?) AND f.effective_known_at <= CAST(? AS TIMESTAMPTZ) ' + - 'QUALIFY ROW_NUMBER() OVER (PARTITION BY f.listing_id ORDER BY f.effective_known_at DESC) = 1) ' + - 'SELECT s.listing_id, epoch_ms(s.effective_known_at) AS effective_known_at, s.known_at_source, s.has_estimated_lag, CAST(s.period_end AS VARCHAR) AS period_end, s.fiscal_period, s.currency, epoch_ms(s.period_known_at) AS period_known_at, s.net_income, s.revenue ' + - 'FROM latest AS s ' + - 'CROSS JOIN (SELECT CAST(? AS BOOLEAN) AS allow_estimated_lag) AS opts ' + - 'WHERE (opts.allow_estimated_lag OR NOT s.has_estimated_lag) ' + - 'ORDER BY s.listing_id ASC' - ); - expect(nonTtm.params).toEqual([ - EXPECTED_GLOB, - 202, - 101, - '2025-06-15T23:59:59.999999Z', - true, - ]); - expect(nonTtm.fenced).toEqual({ - fromMs: Date.UTC(2025, 5, 15, 0, 0, 0, 0), - toMs: Date.UTC(2025, 5, 15, 23, 59, 59, 999), - asOfMs: Date.UTC(2025, 5, 15, 23, 59, 59, 999), - scope: 'vault_fenced', - clampedTo: false, - clampedAsOf: false, - }); - expect(nonTtm.sql).not.toContain(CURATED_ROOT); - expect(nonTtm.sql).not.toContain('2025-06-15'); - expect(nonTtm.sql).not.toContain('ttm_period_end'); - expect(nonTtm.sql).not.toContain('ttm_currency'); - expect(nonTtm.sql).not.toContain('ttm_has_estimated_lag'); - - const withTtm = planFundamentalsAsOfQuery( - { - listingIds: [101], - fields: ['revenue', 'ttm_revenue', 'ttm_operating_cash_flow', 'revenue', 'ttm_revenue'], - asOf: '2025-06-15T14:30:00.123456+02:00', - allowEstimatedLag: false, - }, - DEFAULT_CTX - ); - - expect(withTtm.sql).toBe( - 'WITH latest AS (SELECT f.listing_id, f.effective_known_at, f.known_at_source, f.has_estimated_lag, f.period_end, f.fiscal_period, f.currency, f.period_known_at, f.revenue, f.ttm_revenue, f.ttm_operating_cash_flow, f.ttm_period_end, f.ttm_currency, f.ttm_has_estimated_lag ' + - 'FROM read_parquet(?, hive_partitioning = true) AS f ' + - 'WHERE f.listing_id IN (?) AND f.effective_known_at <= CAST(? AS TIMESTAMPTZ) ' + - 'QUALIFY ROW_NUMBER() OVER (PARTITION BY f.listing_id ORDER BY f.effective_known_at DESC) = 1) ' + - 'SELECT s.listing_id, epoch_ms(s.effective_known_at) AS effective_known_at, s.known_at_source, s.has_estimated_lag, CAST(s.period_end AS VARCHAR) AS period_end, s.fiscal_period, s.currency, epoch_ms(s.period_known_at) AS period_known_at, s.revenue, ' + - 'CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN s.ttm_revenue ELSE NULL END AS ttm_revenue, ' + - 'CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN s.ttm_operating_cash_flow ELSE NULL END AS ttm_operating_cash_flow, ' + - 'CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN CAST(s.ttm_period_end AS VARCHAR) ELSE NULL END AS ttm_period_end, ' + - 'CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN s.ttm_currency ELSE NULL END AS ttm_currency, ' + - 's.ttm_has_estimated_lag ' + - 'FROM latest AS s ' + - 'CROSS JOIN (SELECT CAST(? AS BOOLEAN) AS allow_estimated_lag) AS opts ' + - 'WHERE (opts.allow_estimated_lag OR NOT s.has_estimated_lag) ' + - 'ORDER BY s.listing_id ASC' - ); - expect(withTtm.params).toEqual([ - EXPECTED_GLOB, - 101, - '2025-06-15T12:30:00.123456Z', - false, - ]); - expect(withTtm.fenced.asOfMs).toBe(Date.UTC(2025, 5, 15, 12, 30, 0, 123)); - expect(withTtm.fenced.clampedAsOf).toBe(false); - }); - - it('clamps asOf at or after vaultCutoffTs to vaultCutoffTs * 1000 - 1 micros even when vaultOperatorAuthorized is true', () => { - const authorizedCtx: DuckDbPlanContext = { - ...DEFAULT_CTX, - vaultOperatorAuthorized: true, - }; - - for (const clampedAsOf of [ - '2026-05-28', - '2026-05-28T00:00:00.000Z', - '2026-05-28T00:00:00.000001Z', - '2026-09-01T15:00:00Z', - ]) { - const planned = planFundamentalsAsOfQuery( - { listingIds: [1], fields: ['revenue'], asOf: clampedAsOf }, - authorizedCtx - ); - expect(planned.params).toEqual([EXPECTED_GLOB, 1, MAX_ALLOWED_ISO_MICROS, true]); - expect(planned.fenced).toEqual({ - fromMs: CUTOFF_MS - 1, - toMs: CUTOFF_MS - 1, - asOfMs: CUTOFF_MS - 1, - scope: 'vault_fenced', - clampedTo: true, - clampedAsOf: true, - }); - } - - // Mid-day cutoff with a date-only asOf on the cutoff date clamps cleanly to 1 microsecond before cutoff. - const midDayCutoffMs = Date.UTC(2026, 4, 28, 12, 0, 0, 0); - const midDayClamped = planFundamentalsAsOfQuery( - { listingIds: [1], fields: ['revenue'], asOf: '2026-05-28' }, - { curatedRoot: CURATED_ROOT, vaultCutoffTs: midDayCutoffMs } - ); - expect(midDayClamped.params).toEqual([EXPECTED_GLOB, 1, '2026-05-28T11:59:59.999999Z', true]); - expect(midDayClamped.fenced.clampedAsOf).toBe(true); - expect(midDayClamped.fenced.clampedTo).toBe(true); - expect(midDayClamped.fenced.asOfMs).toBe(midDayCutoffMs - 1); - - // One microsecond before cutoff stays unclamped and preserves exact micros. - const preCutoffMicros = planFundamentalsAsOfQuery( - { listingIds: [1], fields: ['revenue'], asOf: MAX_ALLOWED_ISO_MICROS }, - DEFAULT_CTX - ); - expect(preCutoffMicros.params).toEqual([EXPECTED_GLOB, 1, MAX_ALLOWED_ISO_MICROS, true]); - expect(preCutoffMicros.fenced.clampedAsOf).toBe(false); - }); - - it('validates fields allow-list, allowEstimatedLag, listingIds, and asOf with zero executor calls on invalid input', async () => { - const fake = createRecordingExecutor(); - const store = createDuckDbMarketDataStore({ - executor: fake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - }); - - const invalidFieldsCases: unknown[] = [ - [], - 'revenue', - null, - undefined, - ['unknown_field'], - ['revenue', 'period_end'], - ['toString'], - ['revenue; DROP TABLE x'], - [123], - ]; - for (const badFields of invalidFieldsCases) { - let caught: unknown; - try { - await store.fundamentalsAsOf({ - listingIds: [1], - fields: badFields as string[], - asOf: '2025-06-15', - }); - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(MarketDataStoreValidationError); - expect((caught as MarketDataStoreValidationError).field).toBe('fields'); - } - - const invalidLagCases: unknown[] = [null, 1, 0, 'true', 'false', {}]; - for (const badLag of invalidLagCases) { - let caught: unknown; - try { - await store.fundamentalsAsOf({ - listingIds: [1], - fields: ['revenue'], - asOf: '2025-06-15', - allowEstimatedLag: badLag as boolean, - }); - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(MarketDataStoreValidationError); - expect((caught as MarketDataStoreValidationError).field).toBe('allowEstimatedLag'); - } - - const invalidAsOfCases: unknown[] = ['', 'not-a-date', '2024-02-30', '2025-06-15T12:00:00', null, undefined]; - for (const badAsOf of invalidAsOfCases) { - let caught: unknown; - try { - await store.fundamentalsAsOf({ - listingIds: [1], - fields: ['revenue'], - asOf: badAsOf as string, - }); - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(MarketDataStoreValidationError); - expect((caught as MarketDataStoreValidationError).field).toBe('asOf'); - } - - await expect( - store.fundamentalsAsOf({ listingIds: [], fields: ['revenue'], asOf: '2025-06-15' }) - ).rejects.toBeInstanceOf(MarketDataStoreValidationError); - await expect( - store.fundamentalsAsOf(null as unknown as Parameters[0]) - ).rejects.toBeInstanceOf(MarketDataStoreValidationError); - - expect(fake.calls).toHaveLength(0); - }); - - it('initializes DuckDB budget once and maps fundamentalsAsOf columns in exact projection order with strict scalar validation', async () => { - const t1 = Date.UTC(2024, 7, 1, 20, 0, 0, 0); - const t2 = Date.UTC(2024, 7, 15, 20, 0, 0, 0); - let callIndex = 0; - const fake = createRecordingExecutor({ - onQuery: () => { - callIndex += 1; - if (callIndex === 1) { - return [ - { - listing_id: 101, - effective_known_at: t1, - known_at_source: 'filing_date', - has_estimated_lag: false, - period_end: '2024-06-30', - fiscal_period: 'Q2', - currency: 'USD', - period_known_at: t1, - total_assets: null, - revenue: 120.5, - }, - ]; - } - return [ - { - listing_id: 101, - effective_known_at: t2, - known_at_source: 'filing_date', - has_estimated_lag: false, - period_end: '2024-06-30', - fiscal_period: 'Q2', - currency: 'USD', - period_known_at: t1, - revenue: 120.5, - ttm_revenue: 450.25, - ttm_period_end: '2024-06-30', - ttm_currency: 'USD', - ttm_has_estimated_lag: false, - }, - ]; - }, - }); - - const store = createDuckDbMarketDataStore({ - executor: fake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - }); - const expectedBudget = resolveDuckDbConnectionBudget().statements; - - const first = await store.fundamentalsAsOf({ - listingIds: [101], - fields: ['total_assets', 'revenue', 'total_assets'], - asOf: '2024-08-05', - }); - expect(first.columns).toEqual([ - 'listing_id', - 'effective_known_at', - 'known_at_source', - 'has_estimated_lag', - 'period_end', - 'fiscal_period', - 'currency', - 'period_known_at', - 'total_assets', - 'revenue', - ]); - expect(first.rows).toEqual([ - { - listing_id: 101, - effective_known_at: t1, - known_at_source: 'filing_date', - has_estimated_lag: false, - period_end: '2024-06-30', - fiscal_period: 'Q2', - currency: 'USD', - period_known_at: t1, - total_assets: null, - revenue: 120.5, - }, - ]); - expect(fake.runCalls).toEqual(expectedBudget); - - const second = await store.fundamentalsAsOf({ - listingIds: [101], - fields: ['revenue', 'ttm_revenue'], - asOf: '2024-08-20', - allowEstimatedLag: false, - }); - expect(second.columns).toEqual([ - 'listing_id', - 'effective_known_at', - 'known_at_source', - 'has_estimated_lag', - 'period_end', - 'fiscal_period', - 'currency', - 'period_known_at', - 'revenue', - 'ttm_revenue', - 'ttm_period_end', - 'ttm_currency', - 'ttm_has_estimated_lag', - ]); - expect(second.rows).toHaveLength(1); - expect(second.rows[0]?.ttm_revenue).toBe(450.25); - expect(second.rows[0]?.ttm_has_estimated_lag).toBe(false); - // Budget SET statements must not re-run on second query. - expect(fake.runCalls).toHaveLength(3); - expect(fake.queryCalls).toHaveLength(2); - - // Rejects non-boolean has_estimated_lag from a misbehaving executor. - const badBoolFake = createRecordingExecutor({ - onQuery: () => [ - { - listing_id: 101, - effective_known_at: t1, - known_at_source: 'filing_date', - has_estimated_lag: 'false' as unknown as boolean, - period_end: '2024-06-30', - fiscal_period: 'Q2', - currency: 'USD', - period_known_at: t1, - revenue: 120.5, - }, - ], - }); - const badStore = createDuckDbMarketDataStore({ - executor: badBoolFake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - }); - await expect( - badStore.fundamentalsAsOf({ listingIds: [101], fields: ['revenue'], asOf: '2024-08-05' }) - ).rejects.toBeInstanceOf(MarketDataStoreValidationError); - }); -}); - -describe('fundamentalsAsOf hostile request inputs', () => { - it('fails closed with zero executor calls for JSON-decoded object, symbol, and sparse field entries', async () => { - const fake = createRecordingExecutor(); - const store = createDuckDbMarketDataStore({ - executor: fake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - }); - - const hostileFields: unknown[] = [ - JSON.parse('[{"toString": 1}]'), - [Object.create(null)], - [Symbol('revenue')], - // eslint-disable-next-line no-sparse-arrays - [, 'revenue'], - ['REVENUE'], - [' revenue'], - ]; - for (const fields of hostileFields) { - await expect( - store.fundamentalsAsOf({ listingIds: [1], fields: fields as string[], asOf: '2025-06-15' }) - ).rejects.toThrow(); - } - - const hostileLag = JSON.parse('{"toString": 1}'); - await expect( - store.fundamentalsAsOf({ - listingIds: [1], - fields: ['revenue'], - asOf: '2025-06-15', - allowEstimatedLag: hostileLag as boolean, - }) - ).rejects.toThrow(); - - expect(fake.calls).toHaveLength(0); - expect(fake.runCalls).toHaveLength(0); - }); - - it('plans a request asOf with an offset that crosses the cutoff as a clamped bound', () => { - // 2026-05-28T01:00:00+02:00 === 2026-05-27T23:00:00Z, i.e. before the cutoff: not clamped. - const beforeCutoff = planFundamentalsAsOfQuery( - { listingIds: [1], fields: ['revenue'], asOf: '2026-05-28T01:00:00+02:00' }, - DEFAULT_CTX - ); - expect(Date.parse(beforeCutoff.params[2] as string)).toBe(Date.UTC(2026, 4, 27, 23, 0, 0, 0)); - expect(beforeCutoff.fenced.clampedAsOf).toBe(false); - - // 2026-05-27T23:00:00-02:00 === 2026-05-28T01:00:00Z, i.e. after the cutoff: clamped. - const afterCutoff = planFundamentalsAsOfQuery( - { listingIds: [1], fields: ['revenue'], asOf: '2026-05-27T23:00:00-02:00' }, - DEFAULT_CTX - ); - expect(afterCutoff.params[2]).toBe(MAX_ALLOWED_ISO_MICROS); - expect(afterCutoff.fenced.clampedAsOf).toBe(true); - }); -}); diff --git a/libs/research/test/market-data-store-questdb.qa.test.ts b/libs/research/test/market-data-store-questdb.qa.test.ts deleted file mode 100644 index bbe68fb6..00000000 --- a/libs/research/test/market-data-store-questdb.qa.test.ts +++ /dev/null @@ -1,346 +0,0 @@ -import { describe, expect, it } from 'bun:test'; -import { - createQuestDbIntradayBarsReader, - MarketDataStoreValidationError, - planBars1mQuery, - VaultScopeNotAuthorizedError, - type BarBatch, - type QuestDbBars1mQuery, - type QuestDbQueryExecutor, -} from '@stock-bot/research'; - -// QA edge cases for T-146 (QuestDB `bars_1m` reader) beyond the programmer suite. - -const VAULT_CUTOFF_TS = Date.UTC(2025, 6, 1, 0, 0, 0, 0); - -type QueryResult = { readonly rows: readonly Record[] }; - -class ScriptedExecutor implements QuestDbQueryExecutor { - readonly calls: Array<{ sql: string; params: unknown[] }> = []; - constructor(private readonly respond: () => Promise) {} - async query(sql: string, params: readonly unknown[]): Promise { - this.calls.push({ sql, params: [...params] }); - return this.respond(); - } -} - -function executorReturning(result: unknown): ScriptedExecutor { - return new ScriptedExecutor(async () => result as QueryResult); -} - -async function collect(iterable: AsyncIterable): Promise { - const out: BarBatch[] = []; - for await (const batch of iterable) { - out.push(batch); - } - return out; -} - -function us(ms: number, extraMicros = 0n): string { - return (BigInt(ms) * 1000n + extraMicros).toString(); -} - -function row(overrides: Record): Record { - return { - listing_id: '7', - open: 10, - high: 11, - low: 9, - close: 10.5, - volume: 100, - vwap: 10.2, - ...overrides, - }; -} - -const sessionQuery: QuestDbBars1mQuery = { - listingIds: [7], - timeframe: '1m', - from: '2024-03-01T14:30:00Z', - to: '2024-03-01T21:00:00Z', - asOf: '2024-03-01T21:00:00Z', - adjustment: 'raw', -}; - -describe('QuestDB bars_1m reader QA: planner purity and param binding', () => { - it('is deterministic and binds INT32_MAX as a decimal SYMBOL string only in params', () => { - const q: QuestDbBars1mQuery = { ...sessionQuery, listingIds: [2_147_483_647, 1] }; - const a = planBars1mQuery(q, { vaultCutoffTs: VAULT_CUTOFF_TS }); - const b = planBars1mQuery(q, { vaultCutoffTs: VAULT_CUTOFF_TS }); - - expect(a).toEqual(b); - expect(a.params).toEqual([ - '2024-03-01T14:30:00.000Z', - '2024-03-01T21:00:00.000Z', - '1', - '2147483647', - '2024-03-01T21:00:00.000Z', - ]); - expect(a.sql).not.toContain('2147483647'); - expect(a.sql).toContain('listing_id IN ($3, $4) AND known_at <= $5'); - // Only ordinal placeholders and fixed identifiers: no quotes or digits outside `$n` tokens. - expect(a.sql.replace(/\$\d+/g, '').replace('bars_1m', '')).not.toMatch(/[0-9'";]/); - }); - - it('normalizes offset timestamps to UTC ISO-8601 params', () => { - const planned = planBars1mQuery( - { - ...sessionQuery, - from: '2024-03-01T09:30:00-05:00', - to: '2024-03-01T16:00:00.250-05:00', - asOf: '2024-03-01T17:00:00-05:00', - }, - { vaultCutoffTs: VAULT_CUTOFF_TS } - ); - expect(planned.params).toEqual([ - '2024-03-01T14:30:00.000Z', - '2024-03-01T21:00:00.250Z', - '7', - '2024-03-01T22:00:00.000Z', - ]); - }); - - it('passes the executor a copy of params so executor mutation cannot alter later plans', async () => { - const executor = new ScriptedExecutor(async () => ({ rows: [] })); - const mutating: QuestDbQueryExecutor = { - async query(sql, params) { - (params as unknown[]).splice(0, params.length, 'tampered'); - return executor.query(sql, params); - }, - }; - const reader = createQuestDbIntradayBarsReader({ - executor: mutating, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - await collect(reader.bars(sessionQuery)); - await collect(reader.bars(sessionQuery)); - - expect(executor.calls).toHaveLength(2); - expect(executor.calls[1]?.params).toEqual(['tampered']); - expect(planBars1mQuery(sessionQuery, { vaultCutoffTs: VAULT_CUTOFF_TS }).params).toHaveLength( - 4 - ); - }); - - it('rejects numeric-looking string listing IDs and non-array listingIds before querying', async () => { - const executor = executorReturning({ rows: [] }); - const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS }); - const bad: unknown[] = [ - { ...sessionQuery, listingIds: ['7'] }, - { ...sessionQuery, listingIds: [7n] }, - { ...sessionQuery, listingIds: 7 }, - { ...sessionQuery, listingIds: undefined }, - { ...sessionQuery, listingIds: [7, Number.POSITIVE_INFINITY] }, - null, - ]; - for (const q of bad) { - await expect(collect(reader.bars(q as QuestDbBars1mQuery))).rejects.toThrow( - MarketDataStoreValidationError - ); - } - expect(executor.calls).toHaveLength(0); - }); -}); - -describe('QuestDB bars_1m reader QA: Vault and trusted context', () => { - it('planner ignores a vaultOperatorAuthorized flag smuggled on the query object', () => { - const spoofed = { - ...sessionQuery, - from: '2025-07-02', - to: '2025-07-03', - asOf: undefined, - scope: 'vault_evaluation_only', - vaultOperatorAuthorized: true, - } as unknown as QuestDbBars1mQuery; - expect(() => planBars1mQuery(spoofed, { vaultCutoffTs: VAULT_CUTOFF_TS })).toThrow( - VaultScopeNotAuthorizedError - ); - }); - - it('rejects non-boolean truthy vaultOperatorAuthorized in factory options', () => { - for (const flag of ['true', 1, {}]) { - expect(() => - createQuestDbIntradayBarsReader({ - executor: executorReturning({ rows: [] }), - vaultCutoffTs: VAULT_CUTOFF_TS, - vaultOperatorAuthorized: flag as unknown as boolean, - }) - ).toThrow(MarketDataStoreValidationError); - } - }); - - it('rejects a non-object planner context', () => { - expect(() => - planBars1mQuery(sessionQuery, null as unknown as { vaultCutoffTs: number }) - ).toThrow(MarketDataStoreValidationError); - }); - - it('rejects unknown scope values before querying', async () => { - const executor = executorReturning({ rows: [] }); - const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS }); - await expect( - collect(reader.bars({ ...sessionQuery, scope: 'all' } as unknown as QuestDbBars1mQuery)) - ).rejects.toThrow(MarketDataStoreValidationError); - expect(executor.calls).toHaveLength(0); - }); - - it('a row known one microsecond before a clamped asOf maps to knownAt exactly at the fence, never past it', async () => { - const executor = executorReturning({ - rows: [ - row({ - ts_us: us(VAULT_CUTOFF_TS - 60_000), - known_at_us: us(VAULT_CUTOFF_TS - 1, -1n), - }), - ], - }); - const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS }); - const rows = ( - await collect( - reader.bars({ - ...sessionQuery, - from: '2025-06-30T23:00:00Z', - to: '2025-12-31', - asOf: '2025-12-31', - }) - ) - ).flatMap(b => b.rows); - expect(rows).toHaveLength(1); - expect(rows[0]?.knownAt).toBe(VAULT_CUTOFF_TS - 1); - expect(rows[0]!.knownAt).toBeLessThan(VAULT_CUTOFF_TS); - }); -}); - -describe('QuestDB bars_1m reader QA: executor result and row defence-in-depth', () => { - it('rejects malformed executor results with a validation error', async () => { - for (const result of [ - null, - undefined, - {}, - { rows: null }, - { rows: 'x' }, - [], - { rows: [null] }, - { rows: [[1]] }, - ]) { - const reader = createQuestDbIntradayBarsReader({ - executor: executorReturning(result), - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - await expect(collect(reader.bars(sessionQuery))).rejects.toThrow( - MarketDataStoreValidationError - ); - } - }); - - it('propagates executor failures unchanged and yields nothing', async () => { - const boom = new Error('pgwire connection reset'); - const reader = createQuestDbIntradayBarsReader({ - executor: new ScriptedExecutor(async () => { - throw boom; - }), - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - await expect(collect(reader.bars(sessionQuery))).rejects.toBe(boom); - }); - - it('does not call the executor until iteration starts (lazy plan + query)', async () => { - const executor = executorReturning({ rows: [] }); - const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS }); - const iterable = reader.bars(sessionQuery); - expect(executor.calls).toHaveLength(0); - await collect(iterable); - expect(executor.calls).toHaveLength(1); - }); - - it('maps multi-listing rows, undefined vwap to null, and -0 to 0', async () => { - const t0 = Date.UTC(2024, 2, 1, 14, 30); - const executor = executorReturning({ - rows: [ - row({ listing_id: '3', ts_us: us(t0), known_at_us: us(t0 + 60_000), vwap: undefined }), - row({ listing_id: '7', ts_us: us(t0), known_at_us: us(t0 + 60_000), volume: -0, vwap: 0 }), - ], - }); - const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS }); - const rows = (await collect(reader.bars({ ...sessionQuery, listingIds: [7, 3] }))).flatMap( - b => b.rows - ); - expect(rows.map(r => r.listingId)).toEqual([3, 7]); - expect(rows[0]?.vwap).toBeNull(); - expect(Object.is(rows[1]?.volume, 0)).toBe(true); - expect(rows[1]?.vwap).toBe(0); - expect(executor.calls[0]?.params.slice(2, 4)).toEqual(['3', '7']); - }); - - it('rejects timestamp wire values that are unsafe numbers, padded strings, or missing', async () => { - const t0 = Date.UTC(2024, 2, 1, 14, 30); - const bad: Record[] = [ - row({ ts_us: Number.MAX_SAFE_INTEGER + 2, known_at_us: us(t0) }), - row({ ts_us: ` ${us(t0)}`, known_at_us: us(t0) }), - row({ ts_us: `+${us(t0)}`, known_at_us: us(t0) }), - row({ ts_us: us(t0) }), - row({ ts_us: new Date(t0), known_at_us: us(t0) }), - ]; - for (const r of bad) { - const reader = createQuestDbIntradayBarsReader({ - executor: executorReturning({ rows: [r] }), - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - await expect(collect(reader.bars(sessionQuery))).rejects.toThrow( - MarketDataStoreValidationError - ); - } - }); - - it('floors sub-millisecond ts and ceils sub-millisecond known_at for pre-1970 instants', async () => { - // ts = -1.5 ms -> floor -2 ms; known_at = -1.5 ms -> ceil -1 ms. - const executor = executorReturning({ - rows: [row({ ts_us: '-1500', known_at_us: -1500n })], - }); - const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS }); - const rows = ( - await collect( - reader.bars({ - ...sessionQuery, - from: '1969-12-31T23:59:59.000Z', - to: '1970-01-01T00:00:00.000Z', - asOf: '1970-01-01T00:00:00.000Z', - }) - ) - ).flatMap(b => b.rows); - expect(rows).toEqual([ - { - listingId: 7, - ts: -2, - open: 10, - high: 11, - low: 9, - close: 10.5, - volume: 100, - vwap: 10.2, - knownAt: -1, - }, - ]); - }); - - it('batch size equal to row count yields one batch; batch size 1 yields one row per batch in order', async () => { - const t0 = Date.UTC(2024, 2, 1, 14, 30); - const rows = Array.from({ length: 4 }, (_, i) => - row({ ts_us: us(t0 + i * 60_000), known_at_us: us(t0 + (i + 1) * 60_000), open: 10 + i }) - ); - const exact = createQuestDbIntradayBarsReader({ - executor: executorReturning({ rows }), - vaultCutoffTs: VAULT_CUTOFF_TS, - batchSize: 4, - }); - expect((await collect(exact.bars(sessionQuery))).map(b => b.rows.length)).toEqual([4]); - - const single = createQuestDbIntradayBarsReader({ - executor: executorReturning({ rows }), - vaultCutoffTs: VAULT_CUTOFF_TS, - batchSize: 1, - }); - const batches = await collect(single.bars(sessionQuery)); - expect(batches.map(b => b.rows.length)).toEqual([1, 1, 1, 1]); - expect(batches.map(b => b.rows[0]?.open)).toEqual([10, 11, 12, 13]); - }); -}); diff --git a/libs/research/test/market-data-store-questdb.test.ts b/libs/research/test/market-data-store-questdb.test.ts deleted file mode 100644 index b17e06a2..00000000 --- a/libs/research/test/market-data-store-questdb.test.ts +++ /dev/null @@ -1,768 +0,0 @@ -import { describe, expect, it } from 'bun:test'; -import { - type BarBatch, - type BarRecord, - DEFAULT_QUESTDB_BARS_BATCH_SIZE, - MarketDataStoreNotImplementedError, - MarketDataStoreValidationError, - type QuestDbBars1mQuery, - type QuestDbQueryExecutor, - VaultHoldoutFenceError, - VaultScopeNotAuthorizedError, - createQuestDbIntradayBarsReader, - planBars1mQuery, -} from '@stock-bot/research'; - -interface RecordedCall { - readonly sql: string; - readonly params: readonly unknown[]; -} - -class RecordingQuestDbExecutor implements QuestDbQueryExecutor { - readonly calls: RecordedCall[] = []; - private nextResult: { readonly rows: readonly Record[] } = { rows: [] }; - - setRows(rows: readonly Record[]): void { - this.nextResult = { rows }; - } - - setRawResult(result: unknown): void { - this.nextResult = result as { readonly rows: readonly Record[] }; - } - - async query( - sql: string, - params: readonly unknown[] - ): Promise<{ readonly rows: readonly Record[] }> { - this.calls.push({ sql, params: [...params] }); - return this.nextResult; - } -} - -async function collectBatches(iterable: AsyncIterable): Promise { - const batches: BarBatch[] = []; - for await (const batch of iterable) { - batches.push(batch); - } - return batches; -} - -const VAULT_CUTOFF_TS = Date.UTC(2025, 6, 1, 0, 0, 0, 0); // 2025-07-01T00:00:00.000Z - -describe('planBars1mQuery', () => { - it('snapshots exact parameterized SQL and bound params for a 1-listing, 1-year query', () => { - const query: QuestDbBars1mQuery = { - listingIds: [42], - timeframe: '1m', - from: '2024-01-02', - to: '2024-12-31', - adjustment: 'raw', - asOf: '2025-01-01T00:00:00Z', - }; - - const planned = planBars1mQuery(query, { vaultCutoffTs: VAULT_CUTOFF_TS }); - - expect(planned.sql).toBe( - 'SELECT listing_id, CAST(ts AS LONG) AS ts_us, open, high, low, close, volume, vwap, CAST(known_at AS LONG) AS known_at_us ' + - 'FROM bars_1m ' + - 'WHERE ts >= $1 AND ts <= $2 AND listing_id IN ($3) AND known_at <= $4 ' + - 'ORDER BY ts, listing_id' - ); - expect(planned.params).toEqual([ - '2024-01-02T00:00:00.000Z', - '2024-12-31T23:59:59.999Z', - '42', - '2025-01-01T00:00:00.000Z', - ]); - expect(planned.fence).toEqual({ - fromMs: Date.UTC(2024, 0, 2, 0, 0, 0, 0), - toMs: Date.UTC(2024, 11, 31, 23, 59, 59, 999), - asOfMs: Date.UTC(2025, 0, 1, 0, 0, 0, 0), - scope: 'vault_fenced', - clampedTo: false, - clampedAsOf: false, - }); - - // No caller-supplied values appear in SQL text. - for (const boundValue of planned.params) { - expect(planned.sql).not.toContain(boundValue); - } - expect(planned.sql).not.toContain('42'); - expect(planned.sql).not.toContain('2024'); - expect(planned.sql).not.toContain('2025'); - }); - - it('deduplicates and sorts multi-listing IDs numerically without mutating caller input', () => { - const callerListingIds = [100, 2, 10, 2, 1]; - const snapshotBefore = [...callerListingIds]; - - const planned = planBars1mQuery( - { - listingIds: callerListingIds, - timeframe: '1m', - from: '2024-06-03T13:30:00Z', - to: '2024-06-03T20:00:00Z', - adjustment: 'raw', - asOf: '2024-06-04T00:00:00Z', - }, - { vaultCutoffTs: VAULT_CUTOFF_TS } - ); - - expect(callerListingIds).toEqual(snapshotBefore); - expect(planned.sql).toBe( - 'SELECT listing_id, CAST(ts AS LONG) AS ts_us, open, high, low, close, volume, vwap, CAST(known_at AS LONG) AS known_at_us ' + - 'FROM bars_1m ' + - 'WHERE ts >= $1 AND ts <= $2 AND listing_id IN ($3, $4, $5, $6) AND known_at <= $7 ' + - 'ORDER BY ts, listing_id' - ); - expect(planned.params).toEqual([ - '2024-06-03T13:30:00.000Z', - '2024-06-03T20:00:00.000Z', - '1', - '2', - '10', - '100', - '2024-06-04T00:00:00.000Z', - ]); - }); - - it('port is structurally compatible with QuestDBClient.query generic signature', async () => { - class QuestDbClientLike { - readonly calls: RecordedCall[] = []; - async query>( - sql: string, - params?: unknown[] - ): Promise<{ - rows: T[]; - rowCount: number; - executionTime: number; - }> { - this.calls.push({ sql, params: params ? [...params] : [] }); - return { rows: [], rowCount: 0, executionTime: 1 }; - } - } - - const clientLike = new QuestDbClientLike(); - const executorPort: QuestDbQueryExecutor = clientLike; - const reader = createQuestDbIntradayBarsReader({ - executor: executorPort, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - - const batches = await collectBatches( - reader.bars({ - listingIds: [7], - timeframe: '1m', - from: '2024-05-01T13:30:00Z', - to: '2024-05-01T13:35:00Z', - adjustment: 'raw', - }) - ); - - expect(batches).toEqual([]); - expect(clientLike.calls).toHaveLength(1); - }); -}); - -describe('Vault fence enforcement', () => { - it('rejects from at or past cutoff with VaultHoldoutFenceError and zero executor calls', async () => { - const executor = new RecordingQuestDbExecutor(); - const reader = createQuestDbIntradayBarsReader({ - executor, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - - await expect( - collectBatches( - reader.bars({ - listingIds: [1], - timeframe: '1m', - from: '2025-07-01T00:00:00.000Z', - to: '2025-07-02T00:00:00.000Z', - adjustment: 'raw', - }) - ) - ).rejects.toThrow(VaultHoldoutFenceError); - - await expect( - collectBatches( - reader.bars({ - listingIds: [1], - timeframe: '1m', - from: '2025-07-15', - to: '2025-08-01', - adjustment: 'raw', - }) - ) - ).rejects.toThrow(VaultHoldoutFenceError); - - expect(executor.calls).toHaveLength(0); - }); - - it('clamps to and asOf past cutoff and defaults omitted asOf to cutoff - 1ms', () => { - const clampedPlan = planBars1mQuery( - { - listingIds: [9], - timeframe: '1m', - from: '2025-06-01', - to: '2025-09-01', - asOf: '2025-09-02', - adjustment: 'raw', - }, - { vaultCutoffTs: VAULT_CUTOFF_TS } - ); - - expect(clampedPlan.fence.clampedTo).toBe(true); - expect(clampedPlan.fence.clampedAsOf).toBe(true); - expect(clampedPlan.fence.toMs).toBe(VAULT_CUTOFF_TS - 1); - expect(clampedPlan.fence.asOfMs).toBe(VAULT_CUTOFF_TS - 1); - expect(clampedPlan.params).toEqual([ - '2025-06-01T00:00:00.000Z', - '2025-06-30T23:59:59.999Z', - '9', - '2025-06-30T23:59:59.999Z', - ]); - - const omittedAsOfPlan = planBars1mQuery( - { - listingIds: [9], - timeframe: '1m', - from: '2025-06-01', - to: '2025-06-15', - adjustment: 'raw', - }, - { vaultCutoffTs: VAULT_CUTOFF_TS } - ); - - expect(omittedAsOfPlan.fence.clampedTo).toBe(false); - expect(omittedAsOfPlan.fence.clampedAsOf).toBe(false); - expect(omittedAsOfPlan.fence.asOfMs).toBe(VAULT_CUTOFF_TS - 1); - expect(omittedAsOfPlan.params[3]).toBe('2025-06-30T23:59:59.999Z'); - }); - - it('rejects unauthorized vault_evaluation_only even if caller attaches authorization flag on query', async () => { - const executor = new RecordingQuestDbExecutor(); - const reader = createQuestDbIntradayBarsReader({ - executor, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - - const spoofedQuery = { - listingIds: [1], - timeframe: '1m', - from: '2025-07-01', - to: '2025-07-10', - adjustment: 'raw', - scope: 'vault_evaluation_only', - vaultOperatorAuthorized: true, - } as unknown as QuestDbBars1mQuery; - - await expect(collectBatches(reader.bars(spoofedQuery))).rejects.toThrow( - VaultScopeNotAuthorizedError - ); - expect(executor.calls).toHaveLength(0); - }); - - it('permits vault_evaluation_only when trusted factory context is operator-authorized', async () => { - const executor = new RecordingQuestDbExecutor(); - const reader = createQuestDbIntradayBarsReader({ - executor, - vaultCutoffTs: VAULT_CUTOFF_TS, - vaultOperatorAuthorized: true, - }); - - const batches = await collectBatches( - reader.bars({ - listingIds: [5], - timeframe: '1m', - from: '2025-07-02T13:30:00Z', - to: '2025-07-02T13:31:00Z', - adjustment: 'raw', - scope: 'vault_evaluation_only', - }) - ); - - expect(batches).toEqual([]); - expect(executor.calls).toHaveLength(1); - expect(executor.calls[0]?.params).toEqual([ - '2025-07-02T13:30:00.000Z', - '2025-07-02T13:31:00.000Z', - '5', - '2025-07-02T13:31:00.000Z', - ]); - }); -}); - -describe('Input validation and injection rejection', () => { - it('rejects split and total adjustments with MarketDataStoreNotImplementedError and zero executor calls', async () => { - const executor = new RecordingQuestDbExecutor(); - const reader = createQuestDbIntradayBarsReader({ - executor, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - - for (const adjustment of ['split', 'total'] as const) { - await expect( - collectBatches( - reader.bars({ - listingIds: [1], - timeframe: '1m', - from: '2024-01-02', - to: '2024-01-03', - adjustment, - }) - ) - ).rejects.toThrow(MarketDataStoreNotImplementedError); - } - - expect(executor.calls).toHaveLength(0); - }); - - it('rejects invalid timeframe, adjustment, dates, listingIds, and SQL injection before any executor call', async () => { - const executor = new RecordingQuestDbExecutor(); - const reader = createQuestDbIntradayBarsReader({ - executor, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - - const invalidQueries: unknown[] = [ - // Wrong timeframes - { listingIds: [1], timeframe: '1d', from: '2024-01-02', to: '2024-01-03', adjustment: 'raw' }, - { listingIds: [1], timeframe: '5m', from: '2024-01-02', to: '2024-01-03', adjustment: 'raw' }, - { listingIds: [1], timeframe: '1h', from: '2024-01-02', to: '2024-01-03', adjustment: 'raw' }, - // Invalid adjustment - { - listingIds: [1], - timeframe: '1m', - from: '2024-01-02', - to: '2024-01-03', - adjustment: 'dividend', - }, - // Reversed or invalid dates - { listingIds: [1], timeframe: '1m', from: '2024-02-01', to: '2024-01-01', adjustment: 'raw' }, - { - listingIds: [1], - timeframe: '1m', - from: '2024-01-02T13:30:00', - to: '2024-01-03T13:30:00Z', - adjustment: 'raw', - }, - { listingIds: [1], timeframe: '1m', from: 'not-a-date', to: '2024-01-03', adjustment: 'raw' }, - // Invalid listingIds - { listingIds: [], timeframe: '1m', from: '2024-01-02', to: '2024-01-03', adjustment: 'raw' }, - { listingIds: [0], timeframe: '1m', from: '2024-01-02', to: '2024-01-03', adjustment: 'raw' }, - { - listingIds: [-5], - timeframe: '1m', - from: '2024-01-02', - to: '2024-01-03', - adjustment: 'raw', - }, - { - listingIds: [2_147_483_648], - timeframe: '1m', - from: '2024-01-02', - to: '2024-01-03', - adjustment: 'raw', - }, - { - listingIds: [1.5], - timeframe: '1m', - from: '2024-01-02', - to: '2024-01-03', - adjustment: 'raw', - }, - { - listingIds: [Number.NaN], - timeframe: '1m', - from: '2024-01-02', - to: '2024-01-03', - adjustment: 'raw', - }, - // SQL injection attempt cast through unknown - { - listingIds: ['1; DROP TABLE bars_1m'], - timeframe: '1m', - from: '2024-01-02', - to: '2024-01-03', - adjustment: 'raw', - }, - ]; - - for (const badQuery of invalidQueries) { - await expect(collectBatches(reader.bars(badQuery as QuestDbBars1mQuery))).rejects.toThrow( - MarketDataStoreValidationError - ); - } - - expect(executor.calls).toHaveLength(0); - }); - - it('rejects invalid factory options (executor, vaultCutoffTs, batchSize)', () => { - const executor = new RecordingQuestDbExecutor(); - - expect(() => - createQuestDbIntradayBarsReader({ - executor: {} as unknown as QuestDbQueryExecutor, - vaultCutoffTs: VAULT_CUTOFF_TS, - }) - ).toThrow(MarketDataStoreValidationError); - - expect(() => - createQuestDbIntradayBarsReader({ - executor, - vaultCutoffTs: Number.NaN, - }) - ).toThrow(MarketDataStoreValidationError); - - for (const badBatchSize of [0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY, null]) { - expect(() => - createQuestDbIntradayBarsReader({ - executor, - vaultCutoffTs: VAULT_CUTOFF_TS, - batchSize: badBatchSize as unknown as number, - }) - ).toThrow(MarketDataStoreValidationError); - } - }); -}); - -describe('1-year single-listing replay, row mapping, and batching', () => { - it('streams 98,280 synthetic 1m rows (252 sessions x 390 min) in exact order across default 50k batches', async () => { - expect(DEFAULT_QUESTDB_BARS_BATCH_SIZE).toBe(50_000); - - const sessions = 252; - const minutesPerSession = 390; - const totalRows = sessions * minutesPerSession; // 98,280 - const listingId = 101; - const listingIdSymbol = String(listingId); - const baseSessionStartMs = Date.UTC(2024, 0, 2, 14, 30, 0, 0); - const msPerDay = 86_400_000; - const msPerMinute = 60_000; - - const rawRows: Record[] = new Array(totalRows); - const expected: BarRecord[] = new Array(totalRows); - - let idx = 0; - for (let s = 0; s < sessions; s += 1) { - const sessionStartMs = baseSessionStartMs + s * msPerDay; - for (let m = 0; m < minutesPerSession; m += 1) { - const tsMs = sessionStartMs + m * msPerMinute; - const knownAtMs = tsMs + msPerMinute; - const tsUs = BigInt(tsMs) * 1000n; - const knownAtUs = BigInt(knownAtMs) * 1000n; - - const open = 100 + s * 0.25 + m * 0.01; - const high = open + 0.15; - const low = open - 0.1; - const close = open + 0.05; - const volume = 1_000 + ((s * 390 + m) % 500); - const vwap = m % 10 === 0 ? null : open + 0.02; - - // Exercise all three supported LONG wire representations: decimal string, bigint, safe int. - const tsWire: unknown = - idx % 3 === 0 ? tsUs.toString() : idx % 3 === 1 ? tsUs : Number(tsUs); - const knownAtWire: unknown = - idx % 3 === 0 ? knownAtUs.toString() : idx % 3 === 1 ? knownAtUs : Number(knownAtUs); - - rawRows[idx] = { - listing_id: listingIdSymbol, - ts_us: tsWire, - open, - high, - low, - close, - volume, - vwap, - known_at_us: knownAtWire, - }; - expected[idx] = { - listingId, - ts: tsMs, - open, - high, - low, - close, - volume, - vwap, - knownAt: knownAtMs, - }; - idx += 1; - } - } - - const executor = new RecordingQuestDbExecutor(); - executor.setRows(rawRows); - const reader = createQuestDbIntradayBarsReader({ - executor, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - - const query: QuestDbBars1mQuery = { - listingIds: [listingId], - timeframe: '1m', - from: '2024-01-02', - to: '2024-12-31', - asOf: '2025-01-01T00:00:00Z', - adjustment: 'raw', - }; - - const run1Batches = await collectBatches(reader.bars(query)); - const run2Batches = await collectBatches(reader.bars(query)); - - expect(executor.calls).toHaveLength(2); - expect(run1Batches.map(b => b.rows.length)).toEqual([50_000, 48_280]); - expect(run2Batches.map(b => b.rows.length)).toEqual([50_000, 48_280]); - - const flat1 = run1Batches.flatMap(b => b.rows); - const flat2 = run2Batches.flatMap(b => b.rows); - expect(flat1).toHaveLength(totalRows); - expect(flat1).toEqual(expected); - expect(flat2).toEqual(flat1); - }); - - it('supports custom small batch sizes and yields zero batches for empty results', async () => { - const executor = new RecordingQuestDbExecutor(); - const reader = createQuestDbIntradayBarsReader({ - executor, - vaultCutoffTs: VAULT_CUTOFF_TS, - batchSize: 3, - }); - - const query: QuestDbBars1mQuery = { - listingIds: [12], - timeframe: '1m', - from: '2024-03-01T14:30:00Z', - to: '2024-03-01T14:40:00Z', - asOf: '2024-03-01T15:00:00Z', - adjustment: 'raw', - }; - - executor.setRows([]); - expect(await collectBatches(reader.bars(query))).toEqual([]); - expect(executor.calls).toHaveLength(1); - - const startMs = Date.UTC(2024, 2, 1, 14, 30, 0, 0); - const rows = Array.from({ length: 7 }, (_, i) => { - const tsMs = startMs + i * 60_000; - return { - listing_id: '12', - ts_us: (BigInt(tsMs) * 1000n).toString(), - open: 10 + i, - high: 11 + i, - low: 9 + i, - close: 10.5 + i, - volume: 100 + i, - vwap: i % 2 === 0 ? null : 10.25 + i, - known_at_us: (BigInt(tsMs + 60_000) * 1000n).toString(), - }; - }); - - executor.setRows(rows); - const batches = await collectBatches(reader.bars(query)); - expect(batches.map(b => b.rows.length)).toEqual([3, 3, 1]); - expect(executor.calls).toHaveLength(2); - expect(batches[0]?.rows[0]?.vwap).toBeNull(); - expect(batches[0]?.rows[1]?.vwap).toBe(11.25); - }); -}); - -describe('Malformed and out-of-fence row defence-in-depth', () => { - const baseQuery: QuestDbBars1mQuery = { - listingIds: [101], - timeframe: '1m', - from: '2025-06-30T23:58:00.000Z', - to: '2025-07-05T00:00:00.000Z', // clamped to VAULT_CUTOFF_TS - 1 (2025-06-30T23:59:59.999Z) - asOf: '2025-07-05T00:00:00.000Z', // clamped to VAULT_CUTOFF_TS - 1 - adjustment: 'raw', - }; - - const fromUs = BigInt(Date.UTC(2025, 5, 30, 23, 58, 0, 0)) * 1000n; - const clampedToUs = BigInt(VAULT_CUTOFF_TS - 1) * 1000n; - const clampedAsOfUs = BigInt(VAULT_CUTOFF_TS - 1) * 1000n; - - function makeValidRow(overrides: Record = {}): Record { - return { - listing_id: '101', - ts_us: fromUs.toString(), - open: 150, - high: 151, - low: 149.5, - close: 150.25, - volume: 2500, - vwap: 150.1, - known_at_us: clampedAsOfUs.toString(), - ...overrides, - }; - } - - it('accepts rows at exact fenced microsecond endpoints', async () => { - const executor = new RecordingQuestDbExecutor(); - executor.setRows([ - makeValidRow({ ts_us: fromUs.toString(), known_at_us: clampedAsOfUs.toString() }), - makeValidRow({ ts_us: clampedToUs.toString(), known_at_us: clampedAsOfUs.toString() }), - ]); - - const reader = createQuestDbIntradayBarsReader({ - executor, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - - const batches = await collectBatches(reader.bars(baseQuery)); - expect(batches).toHaveLength(1); - expect(batches[0]?.rows).toHaveLength(2); - expect(batches[0]?.rows[0]?.ts).toBe(Date.UTC(2025, 5, 30, 23, 58, 0, 0)); - expect(batches[0]?.rows[1]?.ts).toBe(VAULT_CUTOFF_TS - 1); - }); - - it('rejects rows 1 microsecond before from, 1 microsecond after clamped to, or 1 microsecond after fenced asOf', async () => { - const executor = new RecordingQuestDbExecutor(); - const reader = createQuestDbIntradayBarsReader({ - executor, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - - const outOfFenceRows: Array<{ label: string; row: Record }> = [ - { label: 'ts 1us before from', row: makeValidRow({ ts_us: (fromUs - 1n).toString() }) }, - { label: 'ts 1us after clamped to', row: makeValidRow({ ts_us: (clampedToUs + 1n).toString() }) }, - { - label: 'known_at 1us after clamped asOf', - row: makeValidRow({ known_at_us: (clampedAsOfUs + 1n).toString() }), - }, - ]; - - for (const testCase of outOfFenceRows) { - executor.setRows([testCase.row]); - await expect(collectBatches(reader.bars(baseQuery))).rejects.toThrow( - MarketDataStoreValidationError - ); - } - }); - - it('rejects invalid SYMBOLs, unrequested listings, non-finite OHLCV/vwap, and invalid timestamps', async () => { - const executor = new RecordingQuestDbExecutor(); - const reader = createQuestDbIntradayBarsReader({ - executor, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - - const malformedRows: Record[] = [ - makeValidRow({ listing_id: '0101' }), - makeValidRow({ listing_id: '-101' }), - makeValidRow({ listing_id: '0' }), - makeValidRow({ listing_id: '2147483648' }), - makeValidRow({ listing_id: 101 }), - makeValidRow({ listing_id: '102' }), // valid INT32 SYMBOL, but unrequested - makeValidRow({ open: Number.NaN }), - makeValidRow({ high: Number.POSITIVE_INFINITY }), - makeValidRow({ low: Number.NEGATIVE_INFINITY }), - makeValidRow({ close: '150.25' }), - makeValidRow({ volume: Number.NaN }), - makeValidRow({ vwap: Number.NaN }), - makeValidRow({ vwap: Number.POSITIVE_INFINITY }), - makeValidRow({ ts_us: 'not-a-timestamp' }), - makeValidRow({ ts_us: 1.5 }), - makeValidRow({ known_at_us: null }), - ]; - - for (const badRow of malformedRows) { - executor.setRows([badRow]); - await expect(collectBatches(reader.bars(baseQuery))).rejects.toThrow( - MarketDataStoreValidationError - ); - } - }); - - it('fails before yielding any batch when a malformed row appears beyond the first batch boundary', async () => { - const executor = new RecordingQuestDbExecutor(); - executor.setRows([ - makeValidRow(), - makeValidRow(), - makeValidRow({ close: Number.NaN }), // row index 2 is past batchSize: 2 - ]); - - const reader = createQuestDbIntradayBarsReader({ - executor, - vaultCutoffTs: VAULT_CUTOFF_TS, - batchSize: 2, - }); - - const yielded: BarBatch[] = []; - let caught: unknown; - try { - for await (const batch of reader.bars(baseQuery)) { - yielded.push(batch); - } - } catch (err) { - caught = err; - } - - expect(caught).toBeInstanceOf(MarketDataStoreValidationError); - expect(yielded).toHaveLength(0); - }); - - it('rounds sub-millisecond known_at up so wider-window replay never exposes a bar before arrival', async () => { - // Matches the QuestDB storage fixture: - // ts = 2024-01-02T14:30:00.000000Z (1704205800000000 us) - // known_at = 2024-01-02T14:31:00.000700Z (1704205860000700 us) - const executor = new RecordingQuestDbExecutor(); - executor.setRows([ - { - listing_id: '1042', - ts_us: '1704205800000000', - open: 185.1, - high: 185.5, - low: 184.9, - close: 185.4, - volume: 12500, - vwap: 185.28, - known_at_us: '1704205860000700', - }, - { - listing_id: '1042', - ts_us: '1704205860000000', - open: 185.4, - high: 185.6, - low: 185.3, - close: 185.55, - volume: 8200, - vwap: null, - known_at_us: '1704205920000000', // exact millisecond: 2024-01-02T14:32:00.000000Z - }, - ]); - - const reader = createQuestDbIntradayBarsReader({ - executor, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - - const query: QuestDbBars1mQuery = { - listingIds: [1042], - timeframe: '1m', - from: '2024-01-02T14:30:00.000Z', - to: '2024-01-02T21:00:00.000Z', - asOf: '2024-01-02T21:00:00.000Z', - adjustment: 'raw', - }; - - const run1 = (await collectBatches(reader.bars(query))).flatMap(b => b.rows); - const run2 = (await collectBatches(reader.bars(query))).flatMap(b => b.rows); - expect(run1).toEqual(run2); - expect(run1).toHaveLength(2); - - const decisionAt143100000 = Date.UTC(2024, 0, 2, 14, 31, 0, 0); - const decisionAt143100001 = Date.UTC(2024, 0, 2, 14, 31, 0, 1); - const exactKnownAt143200000 = Date.UTC(2024, 0, 2, 14, 32, 0, 0); - - const subMsBar = run1[0]!; - expect(subMsBar.knownAt).toBe(decisionAt143100001); - // Ineligible at 14:31:00.000 UTC, eligible at 14:31:00.001 UTC. - expect(subMsBar.knownAt <= decisionAt143100000).toBe(false); - expect(subMsBar.knownAt <= decisionAt143100001).toBe(true); - - // Exact whole-millisecond known_at is not pushed forward. - const exactMsBar = run1[1]!; - expect(exactMsBar.knownAt).toBe(exactKnownAt143200000); - expect(exactMsBar.knownAt <= exactKnownAt143200000).toBe(true); - }); -}); diff --git a/libs/research/test/market-data-store-routed.test.ts b/libs/research/test/market-data-store-routed.test.ts deleted file mode 100644 index 81b38fb6..00000000 --- a/libs/research/test/market-data-store-routed.test.ts +++ /dev/null @@ -1,1098 +0,0 @@ -import { describe, expect, it } from 'bun:test'; -import { - type BarBatch, - type BarRecord, - type DuckDbExecutor, - type DuckDbParam, - type MarketDataStore, - MarketDataStoreNotImplementedError, - MarketDataStoreValidationError, - type QuestDbQueryExecutor, - type RoutedMarketDataStoreOptions, - type Table, - type TableRow, - createDuckDbMarketDataStore, - createQuestDbIntradayBarsReader, - createRoutedMarketDataStore, -} from '@stock-bot/research'; -import { createQuestDbIntradayBarsReader as subpathCreateQuestDbIntradayBarsReader } from '@stock-bot/research/market-data-store-questdb'; -import { createRoutedMarketDataStore as subpathCreateRoutedMarketDataStore } from '@stock-bot/research/market-data-store-routed'; -import { - type QueryDataResultPayload, - createMcpServer, - createQueryDataTool, -} from '../src/mcp/index'; - -type BarsQuery = Parameters[0]; -type CrossSectionQuery = Parameters[0]; -type FundamentalsQuery = Parameters[0]; -type EventsQuery = Parameters[0]; -type ShortsQuery = Parameters[0]; -type MacroQuery = Parameters[0]; -type FxQuery = Parameters[0]; -type UniverseQuery = Parameters[0]; - -const LISTING_ID = 42; -const VAULT_CUTOFF_TS = Date.UTC(2025, 6, 1, 0, 0, 0, 0); // 2025-07-01T00:00:00.000Z -const VAULT_CUTOFF_US = VAULT_CUTOFF_TS * 1000; -const CLAMPED_END_ISO = '2025-06-30T23:59:59.999Z'; -const CURATED_ROOT = '/mnt/data/stockbot/curated'; - -function makeBar(listingId: number, ts: number, close: number, knownAt = ts): BarRecord { - return { - listingId, - ts, - open: close - 0.5, - high: close + 0.5, - low: close - 1, - close, - volume: 1_000, - vwap: close, - knownAt, - }; -} - -async function collectBatches(iterable: AsyncIterable): Promise { - const batches: BarBatch[] = []; - for await (const batch of iterable) { - batches.push(batch); - } - return batches; -} - -class PrototypeDailyStore implements MarketDataStore { - readonly calls: { method: keyof MarketDataStore; arg: unknown }[] = []; - readonly returnedPromises = new Map>(); - readonly barsBatches: BarBatch[]; - - constructor(barsBatches: BarBatch[] = []) { - this.barsBatches = barsBatches; - } - - private assertReceiver(): void { - if (!(this instanceof PrototypeDailyStore)) { - throw new Error('Lost daily receiver (`this`).'); - } - } - - bars(q: BarsQuery): AsyncIterable { - this.assertReceiver(); - this.calls.push({ method: 'bars', arg: q }); - const batches = this.barsBatches; - return { - async *[Symbol.asyncIterator]() { - for (const batch of batches) { - yield batch; - } - }, - }; - } - - crossSection(q: CrossSectionQuery): Promise
{ - this.assertReceiver(); - this.calls.push({ method: 'crossSection', arg: q }); - const p = Promise.resolve
({ columns: ['listing_id'], rows: [{ listing_id: 42 }] }); - this.returnedPromises.set('crossSection', p); - return p; - } - - fundamentalsAsOf(q: FundamentalsQuery): Promise
{ - this.assertReceiver(); - this.calls.push({ method: 'fundamentalsAsOf', arg: q }); - const p = Promise.resolve
({ columns: ['listing_id', 'revenue'], rows: [] }); - this.returnedPromises.set('fundamentalsAsOf', p); - return p; - } - - events(q: EventsQuery): Promise
{ - this.assertReceiver(); - this.calls.push({ method: 'events', arg: q }); - const p = Promise.resolve
({ columns: ['listing_id', 'kind'], rows: [] }); - this.returnedPromises.set('events', p); - return p; - } - - shortsAsOf(q: ShortsQuery): Promise
{ - this.assertReceiver(); - this.calls.push({ method: 'shortsAsOf', arg: q }); - const p = Promise.resolve
({ columns: ['listing_id', 'shares_short'], rows: [] }); - this.returnedPromises.set('shortsAsOf', p); - return p; - } - - macroAsOf(q: MacroQuery): Promise
{ - this.assertReceiver(); - this.calls.push({ method: 'macroAsOf', arg: q }); - const p = Promise.resolve
({ columns: ['country', 'value'], rows: [] }); - this.returnedPromises.set('macroAsOf', p); - return p; - } - - fx(q: FxQuery): Promise
{ - this.assertReceiver(); - this.calls.push({ method: 'fx', arg: q }); - const p = Promise.resolve
({ columns: ['pair', 'close'], rows: [] }); - this.returnedPromises.set('fx', p); - return p; - } - - universe(q: UniverseQuery): Promise { - this.assertReceiver(); - this.calls.push({ method: 'universe', arg: q }); - const p = Promise.resolve([42, 101]); - this.returnedPromises.set('universe', p); - return p; - } -} - -class PrototypeIntradayReader implements Pick { - readonly calls: BarsQuery[] = []; - readonly barsBatches: BarBatch[]; - - constructor(barsBatches: BarBatch[] = []) { - this.barsBatches = barsBatches; - } - - bars(q: BarsQuery): AsyncIterable { - if (!(this instanceof PrototypeIntradayReader)) { - throw new Error('Lost intraday receiver (`this`).'); - } - this.calls.push(q); - const batches = this.barsBatches; - return { - async *[Symbol.asyncIterator]() { - for (const batch of batches) { - yield batch; - } - }, - }; - } -} - -interface QuestDbFixtureRow { - readonly listing_id: string; - readonly ts_us: number; - readonly open: number; - readonly high: number; - readonly low: number; - readonly close: number; - readonly volume: number; - readonly vwap: number | null; - readonly known_at_us: number; -} - -class PredicateAwareQuestDbExecutor implements QuestDbQueryExecutor { - readonly calls: { readonly sql: string; readonly params: readonly unknown[] }[] = []; - private readonly rows: readonly QuestDbFixtureRow[]; - private readonly leaky: boolean; - - constructor(rows: readonly QuestDbFixtureRow[], options?: { leaky?: boolean }) { - this.rows = rows; - this.leaky = options?.leaky === true; - } - - async query( - sql: string, - params: readonly unknown[] - ): Promise<{ readonly rows: readonly Record[] }> { - this.calls.push({ sql, params: [...params] }); - if (this.leaky) { - return { rows: this.rows as unknown as readonly Record[] }; - } - const fromUs = Date.parse(String(params[0])) * 1000; - const toUs = Date.parse(String(params[1])) * 1000; - const asOfUs = Date.parse(String(params[params.length - 1])) * 1000; - const listingIds = new Set(params.slice(2, params.length - 1).map(String)); - - const filtered = this.rows.filter( - row => - row.ts_us >= fromUs && - row.ts_us <= toUs && - row.known_at_us <= asOfUs && - listingIds.has(row.listing_id) - ); - return { rows: filtered as unknown as readonly Record[] }; - } -} - -class RecordingDuckDbExecutor implements DuckDbExecutor { - readonly runCalls: string[] = []; - readonly queryCalls: { readonly sql: string; readonly params: readonly DuckDbParam[] }[] = []; - private readonly rows: readonly TableRow[]; - - constructor(rows: readonly TableRow[] = []) { - this.rows = rows; - } - - async run(sql: string): Promise { - this.runCalls.push(sql); - } - - async query(sql: string, params: readonly DuckDbParam[]): Promise { - this.queryCalls.push({ sql, params: [...params] }); - return this.rows; - } -} - -describe('package exports', () => { - it('re-exports createRoutedMarketDataStore and createQuestDbIntradayBarsReader from root and subpaths', () => { - expect(createRoutedMarketDataStore).toBe(subpathCreateRoutedMarketDataStore); - expect(createQuestDbIntradayBarsReader).toBe(subpathCreateQuestDbIntradayBarsReader); - }); -}); - -describe('createRoutedMarketDataStore', () => { - describe('constructor validation', () => { - it('rejects null, primitives, arrays, and class instances for options', () => { - const invalidOptions: unknown[] = [ - null, - undefined, - 42, - 'options', - true, - [], - new Date(), - new (class OptionsClass { - daily = new PrototypeDailyStore(); - intraday = new PrototypeIntradayReader(); - })(), - ]; - - for (const bad of invalidOptions) { - let caught: unknown; - try { - createRoutedMarketDataStore(bad as RoutedMarketDataStoreOptions); - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(MarketDataStoreValidationError); - expect((caught as MarketDataStoreValidationError).field).toBe('options'); - } - }); - - it('accepts a null-prototype options object and prototype-backed delegates', () => { - const options = Object.create(null) as { - daily: MarketDataStore; - intraday: Pick; - }; - options.daily = new PrototypeDailyStore(); - options.intraday = new PrototypeIntradayReader(); - - const store = createRoutedMarketDataStore(options); - expect(typeof store.bars).toBe('function'); - }); - - it('rejects missing or malformed daily delegate and each missing daily method', () => { - const intraday = new PrototypeIntradayReader(); - - for (const badDaily of [null, undefined, 'daily', 123, []]) { - let caught: unknown; - try { - createRoutedMarketDataStore({ - daily: badDaily as unknown as MarketDataStore, - intraday, - }); - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(MarketDataStoreValidationError); - expect((caught as MarketDataStoreValidationError).field).toBe('daily'); - } - - const requiredMethods: (keyof MarketDataStore)[] = [ - 'bars', - 'crossSection', - 'fundamentalsAsOf', - 'events', - 'shortsAsOf', - 'macroAsOf', - 'fx', - 'universe', - ]; - - for (const missingMethod of requiredMethods) { - const base = new PrototypeDailyStore(); - const incomplete: Record = { - bars: base.bars.bind(base), - crossSection: base.crossSection.bind(base), - fundamentalsAsOf: base.fundamentalsAsOf.bind(base), - events: base.events.bind(base), - shortsAsOf: base.shortsAsOf.bind(base), - macroAsOf: base.macroAsOf.bind(base), - fx: base.fx.bind(base), - universe: base.universe.bind(base), - }; - delete incomplete[missingMethod]; - - let caughtMissing: unknown; - try { - createRoutedMarketDataStore({ - daily: incomplete as unknown as MarketDataStore, - intraday, - }); - } catch (err) { - caughtMissing = err; - } - expect(caughtMissing).toBeInstanceOf(MarketDataStoreValidationError); - expect((caughtMissing as MarketDataStoreValidationError).field).toBe( - `daily.${missingMethod}` - ); - - incomplete[missingMethod] = 'not-a-function'; - let caughtNonFn: unknown; - try { - createRoutedMarketDataStore({ - daily: incomplete as unknown as MarketDataStore, - intraday, - }); - } catch (err) { - caughtNonFn = err; - } - expect(caughtNonFn).toBeInstanceOf(MarketDataStoreValidationError); - expect((caughtNonFn as MarketDataStoreValidationError).field).toBe( - `daily.${missingMethod}` - ); - } - }); - - it('rejects missing or non-callable intraday delegate and intraday.bars', () => { - const daily = new PrototypeDailyStore(); - - for (const badIntraday of [null, undefined, 'intraday', 99, []]) { - let caught: unknown; - try { - createRoutedMarketDataStore({ - daily, - intraday: badIntraday as unknown as Pick, - }); - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(MarketDataStoreValidationError); - expect((caught as MarketDataStoreValidationError).field).toBe('intraday'); - } - - for (const badBars of [undefined, null, 'bars', 42, {}]) { - let caught: unknown; - try { - createRoutedMarketDataStore({ - daily, - intraday: { bars: badBars } as unknown as Pick, - }); - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(MarketDataStoreValidationError); - expect((caught as MarketDataStoreValidationError).field).toBe('intraday.bars'); - } - }); - }); - - describe('routing and delegation', () => { - it('routes 1m bars exclusively to intraday and 1d bars exclusively to daily with exact query identity', async () => { - const intradayBatch: BarBatch = { - rows: [makeBar(LISTING_ID, Date.UTC(2025, 5, 30, 13, 30, 0), 101.25)], - }; - const dailyBatch: BarBatch = { - rows: [makeBar(LISTING_ID, Date.UTC(2025, 5, 30, 20, 0, 0), 102.5)], - }; - const daily = new PrototypeDailyStore([dailyBatch]); - const intraday = new PrototypeIntradayReader([intradayBatch]); - const store = createRoutedMarketDataStore({ daily, intraday }); - - const q1m: BarsQuery = { - listingIds: [LISTING_ID], - timeframe: '1m', - from: '2025-06-30', - to: '2025-06-30', - adjustment: 'raw', - }; - const q1d: BarsQuery = { - listingIds: [LISTING_ID], - timeframe: '1d', - from: '2025-06-01', - to: '2025-06-30', - adjustment: 'raw', - }; - - const intradayOut = await collectBatches(store.bars(q1m)); - expect(intraday.calls).toHaveLength(1); - expect(intraday.calls[0]).toBe(q1m); - expect(daily.calls).toHaveLength(0); - expect(intradayOut).toHaveLength(1); - expect(intradayOut[0]).toBe(intradayBatch); - - const dailyOut = await collectBatches(store.bars(q1d)); - expect(daily.calls).toHaveLength(1); - expect(daily.calls[0]?.method).toBe('bars'); - expect(daily.calls[0]?.arg).toBe(q1d); - expect(intraday.calls).toHaveLength(1); - expect(dailyOut).toHaveLength(1); - expect(dailyOut[0]).toBe(dailyBatch); - }); - - it('forwards invalid timeframe values and non-object inputs to daily unchanged', async () => { - const daily = new PrototypeDailyStore(); - const intraday = new PrototypeIntradayReader(); - const store = createRoutedMarketDataStore({ daily, intraday }); - - const arrayWithTimeframe = Object.assign(['1m'], { timeframe: '1m' }); - const malformedInputs: unknown[] = [ - null, - undefined, - '1m', - 42, - ['1m'], - arrayWithTimeframe, - { listingIds: [42], timeframe: '2m', from: '2025-06-01', to: '2025-06-30', adjustment: 'raw' }, - { listingIds: [42], timeframe: '', from: '2025-06-01', to: '2025-06-30', adjustment: 'raw' }, - ]; - - for (const badInput of malformedInputs) { - await collectBatches(store.bars(badInput as BarsQuery)); - } - - expect(intraday.calls).toHaveLength(0); - expect(daily.calls).toHaveLength(malformedInputs.length); - for (let i = 0; i < malformedInputs.length; i += 1) { - expect(daily.calls[i]?.method).toBe('bars'); - expect(daily.calls[i]?.arg).toBe(malformedInputs[i]); - } - }); - - it('preserves DuckDB MarketDataStoreNotImplementedError for 5m and 1h with zero executor or intraday calls', async () => { - const duckExecutor = new RecordingDuckDbExecutor(); - const daily = createDuckDbMarketDataStore({ - executor: duckExecutor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - const intraday = new PrototypeIntradayReader(); - const store = createRoutedMarketDataStore({ daily, intraday }); - - for (const timeframe of ['5m', '1h'] as const) { - let caught: unknown; - try { - for await (const _batch of store.bars({ - listingIds: [LISTING_ID], - timeframe, - from: '2025-06-01', - to: '2025-06-30', - adjustment: 'raw', - })) { - // unreachable - } - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(MarketDataStoreNotImplementedError); - } - - expect(duckExecutor.runCalls).toHaveLength(0); - expect(duckExecutor.queryCalls).toHaveLength(0); - expect(intraday.calls).toHaveLength(0); - }); - - it('delegates all seven non-bars methods (including fx 1m) to daily with argument, receiver, and promise identity', async () => { - const daily = new PrototypeDailyStore(); - const intraday = new PrototypeIntradayReader(); - const store = createRoutedMarketDataStore({ daily, intraday }); - - const crossSectionArg: CrossSectionQuery = { - features: ['ret_1d@v1'], - date: '2025-06-30', - universe: 'US_EQ', - }; - const fundamentalsArg: FundamentalsQuery = { - listingIds: [LISTING_ID], - fields: ['revenue'], - asOf: '2025-06-30', - }; - const eventsArg: EventsQuery = { - kinds: ['filing'], - listingIds: [LISTING_ID], - from: '2025-06-01', - to: '2025-06-30', - }; - const shortsArg: ShortsQuery = { - listingIds: [LISTING_ID], - from: '2025-06-01', - to: '2025-06-30', - }; - const macroArg: MacroQuery = { - countries: ['US'], - indicators: ['CPI'], - from: '2025-06-01', - to: '2025-06-30', - }; - const fxArg: FxQuery = { - pair: 'USD.CAD', - timeframe: '1m', - from: '2025-06-01', - to: '2025-06-30', - }; - const universeArg: UniverseQuery = { - ref: 'US_EQ', - date: '2025-06-30', - }; - - const pCrossSection = store.crossSection(crossSectionArg); - const pFundamentals = store.fundamentalsAsOf(fundamentalsArg); - const pEvents = store.events(eventsArg); - const pShorts = store.shortsAsOf(shortsArg); - const pMacro = store.macroAsOf(macroArg); - const pFx = store.fx(fxArg); - const pUniverse = store.universe(universeArg); - - expect(pCrossSection).toBe(daily.returnedPromises.get('crossSection') as Promise
); - expect(pFundamentals).toBe(daily.returnedPromises.get('fundamentalsAsOf') as Promise
); - expect(pEvents).toBe(daily.returnedPromises.get('events') as Promise
); - expect(pShorts).toBe(daily.returnedPromises.get('shortsAsOf') as Promise
); - expect(pMacro).toBe(daily.returnedPromises.get('macroAsOf') as Promise
); - expect(pFx).toBe(daily.returnedPromises.get('fx') as Promise
); - expect(pUniverse).toBe(daily.returnedPromises.get('universe') as Promise); - - await Promise.all([ - pCrossSection, - pFundamentals, - pEvents, - pShorts, - pMacro, - pFx, - pUniverse, - ]); - - expect(intraday.calls).toHaveLength(0); - expect(daily.calls).toHaveLength(7); - expect(daily.calls[0]).toEqual({ method: 'crossSection', arg: crossSectionArg }); - expect(daily.calls[0]?.arg).toBe(crossSectionArg); - expect(daily.calls[1]).toEqual({ method: 'fundamentalsAsOf', arg: fundamentalsArg }); - expect(daily.calls[1]?.arg).toBe(fundamentalsArg); - expect(daily.calls[2]).toEqual({ method: 'events', arg: eventsArg }); - expect(daily.calls[2]?.arg).toBe(eventsArg); - expect(daily.calls[3]).toEqual({ method: 'shortsAsOf', arg: shortsArg }); - expect(daily.calls[3]?.arg).toBe(shortsArg); - expect(daily.calls[4]).toEqual({ method: 'macroAsOf', arg: macroArg }); - expect(daily.calls[4]?.arg).toBe(macroArg); - expect(daily.calls[5]).toEqual({ method: 'fx', arg: fxArg }); - expect(daily.calls[5]?.arg).toBe(fxArg); - expect(daily.calls[6]).toEqual({ method: 'universe', arg: universeArg }); - expect(daily.calls[6]?.arg).toBe(universeArg); - }); - }); - - describe('error propagation and lazy iteration', () => { - it('propagates exact error instances for sync throws, promise rejections, and mid-iteration failures', async () => { - const syncIntradayErr = new Error('sync intraday boom'); - const syncDailyErr = new Error('sync daily boom'); - const rejectedUniverseErr = new Error('async universe boom'); - const iterErr = new Error('mid-iteration boom'); - - const baseDaily = new PrototypeDailyStore(); - const firstBatch: BarBatch = { - rows: [makeBar(LISTING_ID, Date.UTC(2025, 5, 30, 13, 30, 0), 100)], - }; - - const dailySyncStore = createRoutedMarketDataStore({ - daily: { - bars: () => { - throw syncDailyErr; - }, - crossSection: baseDaily.crossSection.bind(baseDaily), - fundamentalsAsOf: baseDaily.fundamentalsAsOf.bind(baseDaily), - events: baseDaily.events.bind(baseDaily), - shortsAsOf: baseDaily.shortsAsOf.bind(baseDaily), - macroAsOf: baseDaily.macroAsOf.bind(baseDaily), - fx: baseDaily.fx.bind(baseDaily), - universe: () => Promise.reject(rejectedUniverseErr), - }, - intraday: { - bars: () => { - throw syncIntradayErr; - }, - }, - }); - - let caughtSyncIntraday: unknown; - try { - dailySyncStore.bars({ - listingIds: [LISTING_ID], - timeframe: '1m', - from: '2025-06-30', - to: '2025-06-30', - adjustment: 'raw', - }); - } catch (err) { - caughtSyncIntraday = err; - } - expect(caughtSyncIntraday).toBe(syncIntradayErr); - - let caughtSyncDaily: unknown; - try { - dailySyncStore.bars({ - listingIds: [LISTING_ID], - timeframe: '1d', - from: '2025-06-30', - to: '2025-06-30', - adjustment: 'raw', - }); - } catch (err) { - caughtSyncDaily = err; - } - expect(caughtSyncDaily).toBe(syncDailyErr); - - let caughtRejected: unknown; - try { - await dailySyncStore.universe({ ref: 'US_EQ', date: '2025-06-30' }); - } catch (err) { - caughtRejected = err; - } - expect(caughtRejected).toBe(rejectedUniverseErr); - - const iterFailStore = createRoutedMarketDataStore({ - daily: baseDaily, - intraday: { - bars() { - return { - async *[Symbol.asyncIterator]() { - yield firstBatch; - throw iterErr; - }, - }; - }, - }, - }); - - const received: BarBatch[] = []; - let caughtIter: unknown; - try { - for await (const batch of iterFailStore.bars({ - listingIds: [LISTING_ID], - timeframe: '1m', - from: '2025-06-30', - to: '2025-06-30', - adjustment: 'raw', - })) { - received.push(batch); - } - } catch (err) { - caughtIter = err; - } - expect(received).toHaveLength(1); - expect(received[0]).toBe(firstBatch); - expect(caughtIter).toBe(iterErr); - }); - - it('preserves lazy iteration and closes the delegate iterator on early exit', async () => { - const batch1: BarBatch = { - rows: [makeBar(LISTING_ID, Date.UTC(2025, 5, 30, 13, 30, 0), 100)], - }; - const batch2: BarBatch = { - rows: [makeBar(LISTING_ID, Date.UTC(2025, 5, 30, 13, 31, 0), 101)], - }; - let nextCalls = 0; - let returnCalls = 0; - - const store = createRoutedMarketDataStore({ - daily: new PrototypeDailyStore(), - intraday: { - bars() { - return { - [Symbol.asyncIterator]() { - const batches = [batch1, batch2]; - return { - async next() { - const idx = nextCalls; - nextCalls += 1; - const value = batches[idx]; - if (value === undefined) { - return { done: true as const, value: undefined }; - } - return { done: false as const, value }; - }, - async return() { - returnCalls += 1; - return { done: true as const, value: undefined }; - }, - }; - }, - }; - }, - }, - }); - - const consumed: BarBatch[] = []; - for await (const batch of store.bars({ - listingIds: [LISTING_ID], - timeframe: '1m', - from: '2025-06-30', - to: '2025-06-30', - adjustment: 'raw', - })) { - consumed.push(batch); - break; - } - - expect(consumed).toHaveLength(1); - expect(consumed[0]).toBe(batch1); - expect(nextCalls).toBe(1); - expect(returnCalls).toBe(1); - }); - }); - - describe('QuestDB intraday reader integration and Vault fence', () => { - const preCutoffTs1Us = Date.UTC(2025, 5, 30, 13, 30, 0, 0) * 1000; - const preCutoffTs2Us = Date.UTC(2025, 5, 30, 13, 31, 0, 0) * 1000; - const fixtureRows: readonly QuestDbFixtureRow[] = [ - { - listing_id: String(LISTING_ID), - ts_us: preCutoffTs1Us, - open: 100.0, - high: 101.0, - low: 99.5, - close: 100.5, - volume: 500, - vwap: 100.25, - known_at_us: preCutoffTs1Us + 60_000_000, - }, - { - listing_id: String(LISTING_ID), - ts_us: preCutoffTs2Us, - open: 100.5, - high: 101.5, - low: 100.25, - close: 101.25, - volume: 750, - vwap: 101.0, - known_at_us: preCutoffTs2Us + 60_000_000, - }, - // Row with ts exactly at Vault cutoff (must be excluded by fence) - { - listing_id: String(LISTING_ID), - ts_us: VAULT_CUTOFF_US, - open: 102.0, - high: 103.0, - low: 101.5, - close: 102.5, - volume: 900, - vwap: 102.25, - known_at_us: preCutoffTs2Us + 60_000_000, - }, - // Row with known_at exactly at Vault cutoff (must be excluded by fence) - { - listing_id: String(LISTING_ID), - ts_us: preCutoffTs2Us + 60_000_000, - open: 101.25, - high: 102.0, - low: 101.0, - close: 101.75, - volume: 600, - vwap: 101.5, - known_at_us: VAULT_CUTOFF_US, - }, - ]; - - const straddlingQuery: BarsQuery = { - listingIds: [LISTING_ID], - timeframe: '1m', - from: '2025-06-30T13:30:00Z', - to: '2025-07-05T20:00:00Z', - adjustment: 'raw', - asOf: '2025-07-10T00:00:00Z', - }; - - it('streams batches unchanged from createQuestDbIntradayBarsReader and clamps to/asOf strictly below vaultCutoffTs', async () => { - const directExecutor = new PredicateAwareQuestDbExecutor(fixtureRows); - const directReader = createQuestDbIntradayBarsReader({ - executor: directExecutor, - vaultCutoffTs: VAULT_CUTOFF_TS, - vaultOperatorAuthorized: false, - batchSize: 1, - }); - - const routedExecutor = new PredicateAwareQuestDbExecutor(fixtureRows); - const underlyingIntraday = createQuestDbIntradayBarsReader({ - executor: routedExecutor, - vaultCutoffTs: VAULT_CUTOFF_TS, - vaultOperatorAuthorized: false, - batchSize: 1, - }); - - const yieldedByIntraday: BarBatch[] = []; - const recordingIntraday: Pick = { - bars(q) { - const inner = underlyingIntraday.bars(q); - return { - async *[Symbol.asyncIterator]() { - for await (const batch of inner) { - yieldedByIntraday.push(batch); - yield batch; - } - }, - }; - }, - }; - - const daily = new PrototypeDailyStore(); - const store = createRoutedMarketDataStore({ daily, intraday: recordingIntraday }); - - const directBatches = await collectBatches(directReader.bars(straddlingQuery)); - const routedBatches = await collectBatches(store.bars(straddlingQuery)); - - expect(daily.calls).toHaveLength(0); - expect(routedExecutor.calls).toHaveLength(1); - expect(routedExecutor.calls[0]?.params[1]).toBe(CLAMPED_END_ISO); - expect(routedExecutor.calls[0]?.params[3]).toBe(CLAMPED_END_ISO); - - expect(routedBatches).toEqual(directBatches); - expect(routedBatches).toHaveLength(2); - expect(routedBatches[0]).toBe(yieldedByIntraday[0]); - expect(routedBatches[1]).toBe(yieldedByIntraday[1]); - - for (const batch of routedBatches) { - for (const row of batch.rows) { - expect(row.ts).toBeLessThan(VAULT_CUTOFF_TS); - expect(row.knownAt).toBeLessThan(VAULT_CUTOFF_TS); - } - } - }); - - it('rejects a leaky QuestDB executor returning a row with ts or known_at at vaultCutoffTs before yielding any batch', async () => { - const tsCutoffRow = fixtureRows[2] as QuestDbFixtureRow; - const knownAtCutoffRow = fixtureRows[3] as QuestDbFixtureRow; - const preCutoffRow = fixtureRows[0] as QuestDbFixtureRow; - - for (const leakyRows of [ - [preCutoffRow, tsCutoffRow], - [preCutoffRow, knownAtCutoffRow], - ]) { - const leakyExecutor = new PredicateAwareQuestDbExecutor(leakyRows, { leaky: true }); - const intraday = createQuestDbIntradayBarsReader({ - executor: leakyExecutor, - vaultCutoffTs: VAULT_CUTOFF_TS, - vaultOperatorAuthorized: false, - batchSize: 1, - }); - const store = createRoutedMarketDataStore({ - daily: new PrototypeDailyStore(), - intraday, - }); - - const yielded: BarBatch[] = []; - let caught: unknown; - try { - for await (const batch of store.bars(straddlingQuery)) { - yielded.push(batch); - } - } catch (err) { - caught = err; - } - - expect(caught).toBeInstanceOf(MarketDataStoreValidationError); - expect(yielded).toHaveLength(0); - } - }); - }); - - describe('MCP query_data end-to-end over routed store', () => { - it('routes 1m calls to fake QuestDB and 1d calls to fake DuckDB, enforcing the Vault cutoff deterministically', async () => { - const intradayTs1Us = Date.UTC(2025, 5, 30, 13, 30, 0, 0) * 1000; - const intradayTs2Us = Date.UTC(2025, 5, 30, 13, 31, 0, 0) * 1000; - const questDbRows: readonly QuestDbFixtureRow[] = [ - { - listing_id: String(LISTING_ID), - ts_us: intradayTs1Us, - open: 100.0, - high: 100.75, - low: 99.5, - close: 100.5, - volume: 1_200, - vwap: 100.2, - known_at_us: intradayTs1Us + 60_000_000, - }, - { - listing_id: String(LISTING_ID), - ts_us: intradayTs2Us, - open: 100.5, - high: 101.25, - low: 100.25, - close: 101.0, - volume: 1_500, - vwap: 100.8, - known_at_us: intradayTs2Us + 60_000_000, - }, - // Out-of-fence rows at exact cutoff (filtered by predicate-aware executor) - { - listing_id: String(LISTING_ID), - ts_us: VAULT_CUTOFF_US, - open: 105.0, - high: 106.0, - low: 104.0, - close: 105.5, - volume: 2_000, - vwap: 105.2, - known_at_us: intradayTs2Us + 60_000_000, - }, - { - listing_id: String(LISTING_ID), - ts_us: intradayTs2Us + 60_000_000, - open: 101.0, - high: 101.5, - low: 100.75, - close: 101.25, - volume: 1_100, - vwap: 101.1, - known_at_us: VAULT_CUTOFF_US, - }, - ]; - - const dailyBarTs = Date.UTC(2025, 5, 30, 20, 0, 0, 0); - const duckDbRows: readonly TableRow[] = [ - { - listing_id: LISTING_ID, - ts: dailyBarTs, - open: 99.0, - high: 102.0, - low: 98.5, - close: 101.5, - volume: 250_000, - vwap: 100.75, - known_at: dailyBarTs, - }, - ]; - - const questExecutor = new PredicateAwareQuestDbExecutor(questDbRows); - const duckExecutor = new RecordingDuckDbExecutor(duckDbRows); - - const daily = createDuckDbMarketDataStore({ - executor: duckExecutor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: VAULT_CUTOFF_TS, - vaultOperatorAuthorized: false, - }); - const intraday = createQuestDbIntradayBarsReader({ - executor: questExecutor, - vaultCutoffTs: VAULT_CUTOFF_TS, - vaultOperatorAuthorized: false, - }); - const routedStore = createRoutedMarketDataStore({ daily, intraday }); - - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createQueryDataTool({ - store: routedStore, - vaultContext: { - vaultCutoffTs: VAULT_CUTOFF_TS, - }, - }), - ], - }); - - const direct1mBatches = await collectBatches( - createQuestDbIntradayBarsReader({ - executor: new PredicateAwareQuestDbExecutor(questDbRows), - vaultCutoffTs: VAULT_CUTOFF_TS, - vaultOperatorAuthorized: false, - }).bars({ - listingIds: [LISTING_ID], - timeframe: '1m', - from: '2025-06-30', - to: '2025-07-05', - adjustment: 'raw', - }) - ); - const expected1mRows = direct1mBatches.flatMap(b => b.rows); - - const req1m = JSON.stringify({ - jsonrpc: '2.0', - id: 'mcp-1m', - method: 'tools/call', - params: { - name: 'query_data', - arguments: { - listingIds: [LISTING_ID], - from: '2025-06-30', - to: '2025-07-05', - timeframe: '1m', - adjustment: 'raw', - }, - }, - }); - - const raw1mFirst = await server.handleMessage(req1m); - const raw1mSecond = await server.handleMessage(req1m); - expect(raw1mFirst).not.toBeNull(); - expect(raw1mSecond).toBe(raw1mFirst); - - expect(questExecutor.calls).toHaveLength(2); - expect(duckExecutor.queryCalls).toHaveLength(0); - expect(duckExecutor.runCalls).toHaveLength(0); - - const resp1m = JSON.parse(raw1mFirst as string) as { - result: { isError?: boolean; content: { type: string; text: string }[] }; - }; - expect(resp1m.result.isError).toBeUndefined(); - const payload1m = JSON.parse(resp1m.result.content[0]?.text ?? '') as QueryDataResultPayload; - expect(payload1m.rows).toEqual(expected1mRows); - expect(payload1m.rows).toHaveLength(2); - for (const row of payload1m.rows) { - expect(row.ts).toBeLessThan(VAULT_CUTOFF_TS); - expect(row.knownAt).toBeLessThan(VAULT_CUTOFF_TS); - } - - const direct1dBatches = await collectBatches( - createDuckDbMarketDataStore({ - executor: new RecordingDuckDbExecutor(duckDbRows), - curatedRoot: CURATED_ROOT, - vaultCutoffTs: VAULT_CUTOFF_TS, - vaultOperatorAuthorized: false, - }).bars({ - listingIds: [LISTING_ID], - timeframe: '1d', - from: '2025-06-25', - to: '2025-07-05', - adjustment: 'raw', - }) - ); - const expected1dRows = direct1dBatches.flatMap(b => b.rows); - - const req1d = JSON.stringify({ - jsonrpc: '2.0', - id: 'mcp-1d', - method: 'tools/call', - params: { - name: 'query_data', - arguments: { - listingIds: [LISTING_ID], - from: '2025-06-25', - to: '2025-07-05', - timeframe: '1d', - adjustment: 'raw', - }, - }, - }); - - const raw1dFirst = await server.handleMessage(req1d); - const raw1dSecond = await server.handleMessage(req1d); - expect(raw1dFirst).not.toBeNull(); - expect(raw1dSecond).toBe(raw1dFirst); - - expect(questExecutor.calls).toHaveLength(2); - expect(duckExecutor.queryCalls).toHaveLength(2); - - const resp1d = JSON.parse(raw1dFirst as string) as { - result: { isError?: boolean; content: { type: string; text: string }[] }; - }; - expect(resp1d.result.isError).toBeUndefined(); - const payload1d = JSON.parse(resp1d.result.content[0]?.text ?? '') as QueryDataResultPayload; - expect(payload1d.rows).toEqual(expected1dRows); - expect(payload1d.rows).toHaveLength(1); - for (const row of payload1d.rows) { - expect(row.ts).toBeLessThan(VAULT_CUTOFF_TS); - expect(row.knownAt).toBeLessThan(VAULT_CUTOFF_TS); - } - }); - }); -}); diff --git a/libs/research/test/mcp-analyze-signal-qa.test.ts b/libs/research/test/mcp-analyze-signal-qa.test.ts deleted file mode 100644 index 78f010c8..00000000 --- a/libs/research/test/mcp-analyze-signal-qa.test.ts +++ /dev/null @@ -1,820 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { - type BarBatch, - type BarRecord, - type MarketDataStore, - MarketDataStoreValidationError, - type Table, - type TableRow, -} from '../src/market-data-store'; -import { - type BarsQuery, - MarketDataStoreNotImplementedError, - type ShortsAsOfQuery, - type UniverseQuery, -} from '../src/market-data-store-duckdb'; -import { - type AnalyzeSignalResultPayload, - createAnalyzeSignalTool, - createMcpServer, -} from '../src/mcp/index'; -import { - SignalPanelError, - buildForwardReturnPanel, - shortsTableToSignalRows, -} from '../src/signal-panel'; -import { TrialLedgerError, type TrialLedgerExecutor } from '../src/trial-ledger'; - -// QA fixture: seeded synthetic short-interest panel (SEED below), 12 listings, -// 140 pre-cutoff + 10 post-cutoff business sessions from 2022-09-01, shorts -// every 10 sessions published T+4 at 22:00 UTC, gross close-to-close returns, -// raw adjustment, no fills or fees. -const SEED = 4_242_026; -const AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555'; -const POISON = 'POISON' as unknown as number; -const SHORTS_COLUMNS = [ - 'listing_id', - 'report_date', - 'known_at', - 'shares_short', - 'net_change', - 'pct_float', - 'source', -] as const; - -function createSeededRng(seed: number): () => number { - let state = seed >>> 0; - return () => { - state = (state + 0x6d2b79f5) >>> 0; - let t = Math.imul(state ^ (state >>> 15), 1 | state); - t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; - return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296; - }; -} - -function makeBusinessDates(startDate: string, count: number): string[] { - const out: string[] = []; - const current = new Date(`${startDate}T00:00:00.000Z`); - while (out.length < count) { - const day = current.getUTCDay(); - if (day !== 0 && day !== 6) { - out.push(current.toISOString().slice(0, 10)); - } - current.setUTCDate(current.getUTCDate() + 1); - } - return out; -} - -function utcMs(date: string, hour: number, minute = 0): number { - return Date.parse(`${date}T00:00:00.000Z`) + hour * 3_600_000 + minute * 60_000; -} - -interface Fixture { - readonly listingIds: number[]; - readonly allDates: string[]; - readonly cutoffDate: string; - readonly cutoffTs: number; - readonly bars: BarRecord[]; - readonly shorts: Table; -} - -function buildFixture(): Fixture { - const rand = createSeededRng(SEED); - const listingCount = 12; - const pre = 140; - const allDates = makeBusinessDates('2022-09-01', pre + 10); - const cutoffDate = allDates[pre]!; - const listingIds = Array.from({ length: listingCount }, (_, i) => 70_001 + i); - const bars: BarRecord[] = []; - const shortsRows: TableRow[] = []; - const active = new Float64Array(listingCount); - const pending = new Map(); - const prices = Array.from({ length: listingCount }, (_, l) => 20 + l); - - for (let t = 0; t < allDates.length; t += 1) { - const date = allDates[t]!; - const released = pending.get(t - 1); - if (released !== undefined) { - for (let l = 0; l < listingCount; l += 1) { - active[l] = released[l]! / 20_000; - } - } - if (t % 10 === 0 && t + 4 < allDates.length) { - const knownAt = utcMs(allDates[t + 4]!, 22); - const values: number[] = []; - for (let l = 0; l < listingCount; l += 1) { - const netChange = Math.round((rand() * 2 - 1) * 20_000); - values.push(netChange); - shortsRows.push({ - listing_id: listingIds[l]!, - report_date: date, - known_at: knownAt, - shares_short: 100_000 + Math.round(rand() * 10_000), - net_change: netChange, - pct_float: Number((0.02 + rand() * 0.08).toFixed(4)), - source: 'ceoShorts', - }); - } - pending.set(t + 4, values); - } - for (let l = 0; l < listingCount; l += 1) { - prices[l] = Math.max(0.5, prices[l]! * (1 - 0.004 * active[l]! + (rand() * 2 - 1) * 0.008)); - const close = Number(prices[l]!.toFixed(6)); - const ts = utcMs(date, 21); - bars.push({ - listingId: listingIds[l]!, - ts, - open: close, - high: close, - low: close, - close, - volume: 10_000, - knownAt: ts, - }); - } - } - - return { - listingIds, - allDates, - cutoffDate, - cutoffTs: utcMs(cutoffDate, 0), - bars, - shorts: { columns: SHORTS_COLUMNS, rows: shortsRows }, - }; -} - -function parseBound(raw: string, endOfDay: boolean): number { - if (raw.length === 10) { - return Date.parse(`${raw}T${endOfDay ? '23:59:59.999' : '00:00:00.000'}Z`); - } - return Date.parse(raw); -} - -interface FakeStore { - readonly store: MarketDataStore; - readonly barsCalls: BarsQuery[]; - readonly shortsCalls: ShortsAsOfQuery[]; - readonly universeCalls: UniverseQuery[]; -} - -/** - * Correctly filtering store; `extraBars` / `extraShorts` are appended - * unconditionally to simulate an adapter that leaks rows past its filters. - */ -function createStore( - fixture: Fixture, - options?: { - extraBars?: readonly BarRecord[]; - extraShorts?: readonly TableRow[]; - universe?: (q: UniverseQuery) => number[]; - barsThrow?: unknown; - shortsThrow?: unknown; - } -): FakeStore { - const barsCalls: BarsQuery[] = []; - const shortsCalls: ShortsAsOfQuery[] = []; - const universeCalls: UniverseQuery[] = []; - const store: MarketDataStore = { - bars(q: BarsQuery): AsyncIterable { - barsCalls.push(q); - const ids = new Set(q.listingIds); - const fromMs = parseBound(q.from, false); - const toMs = parseBound(q.to, true); - const asOfMs = q.asOf === undefined ? Number.POSITIVE_INFINITY : parseBound(q.asOf, true); - const rows = fixture.bars.filter( - b => - ids.has(b.listingId) && - b.ts >= fromMs && - b.ts <= toMs && - b.ts <= asOfMs && - b.knownAt <= asOfMs - ); - const thrown = options?.barsThrow; - return { - async *[Symbol.asyncIterator]() { - if (thrown !== undefined) { - throw thrown; - } - yield { rows: [...rows, ...(options?.extraBars ?? [])] }; - }, - }; - }, - async shortsAsOf(q: ShortsAsOfQuery): Promise
{ - shortsCalls.push(q); - if (options?.shortsThrow !== undefined) { - throw options.shortsThrow; - } - const ids = new Set(q.listingIds); - const fromDate = q.from.slice(0, 10); - const toDate = q.to.slice(0, 10); - const asOfMs = q.asOf === undefined ? Number.POSITIVE_INFINITY : parseBound(q.asOf, true); - const rows = fixture.shorts.rows.filter( - r => - ids.has(r.listing_id as number) && - (r.report_date as string) >= fromDate && - (r.report_date as string) <= toDate && - (r.known_at as number) <= asOfMs - ); - return { columns: fixture.shorts.columns, rows: [...rows, ...(options?.extraShorts ?? [])] }; - }, - async universe(q: UniverseQuery): Promise { - universeCalls.push(q); - return options?.universe?.(q) ?? []; - }, - crossSection() { - throw new MarketDataStoreNotImplementedError('crossSection'); - }, - fundamentalsAsOf() { - throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); - }, - events() { - throw new MarketDataStoreNotImplementedError('events'); - }, - macroAsOf() { - throw new MarketDataStoreNotImplementedError('macroAsOf'); - }, - fx() { - throw new MarketDataStoreNotImplementedError('fx'); - }, - }; - return { store, barsCalls, shortsCalls, universeCalls }; -} - -interface LedgerRow { - readonly trial_id: string; - readonly created_at: Date; - readonly principal_id: string; - readonly campaign_id: string | null; - readonly stage: string; - readonly universe_market: string; - readonly horizon_bucket: string; - readonly hypothesis_id: string | null; - readonly expression_hash: string; - readonly sample_start: string; - readonly sample_end: string; - readonly n_obs: number; - readonly sharpe_unann: number; - readonly skewness: number; - readonly kurtosis: number; - readonly daily_series: readonly number[]; -} - -function createLedger(options?: { insertThrow?: unknown }): { - executor: TrialLedgerExecutor; - rows: LedgerRow[]; -} { - const rows: LedgerRow[] = []; - const executor: TrialLedgerExecutor = { - async query>(text: string, params?: readonly unknown[]) { - const sql = text.trimStart(); - if (sql.startsWith('INSERT INTO trial_ledger')) { - if (options?.insertThrow !== undefined) { - throw options.insertThrow; - } - const p = params ?? []; - const id = rows.length + 1; - const row: LedgerRow = { - trial_id: String(id), - created_at: new Date(Date.UTC(2024, 0, 1, 0, 0, id)), - principal_id: p[0] as string, - campaign_id: (p[1] as string | null) ?? null, - stage: p[2] as string, - universe_market: p[3] as string, - horizon_bucket: p[4] as string, - hypothesis_id: (p[5] as string | null) ?? null, - expression_hash: p[6] as string, - sample_start: p[7] as string, - sample_end: p[8] as string, - n_obs: p[9] as number, - sharpe_unann: p[10] as number, - skewness: p[11] as number, - kurtosis: p[12] as number, - daily_series: (p[13] as readonly number[]).map(v => Math.fround(v)), - }; - rows.push(row); - return { - rows: [{ trial_id: row.trial_id, created_at: row.created_at } as unknown as Row], - rowCount: 1, - }; - } - if (sql.startsWith('SELECT')) { - if (text.includes('WHERE trial_id = $1::bigint')) { - const m = rows.filter(r => r.trial_id === String(params?.[0])); - return { rows: m as unknown as Row[], rowCount: m.length }; - } - if (text.includes('WHERE universe_market = $1')) { - const m = rows.filter( - r => r.universe_market === params?.[0] && r.horizon_bucket === params?.[1] - ); - return { rows: m as unknown as Row[], rowCount: m.length }; - } - } - return { rows: [], rowCount: 0 }; - }, - }; - return { executor, rows }; -} - -async function call(params: { - store: MarketDataStore; - ledger: TrialLedgerExecutor; - cutoffTs: number; - args: Record; - principalId?: string; -}): Promise<{ raw: string; isError: boolean; text: string }> { - const server = createMcpServer({ - name: 'qa', - version: '0.0.0', - tools: [ - createAnalyzeSignalTool({ - store: params.store, - ledger: params.ledger, - vaultContext: { vaultCutoffTs: params.cutoffTs }, - principalId: params.principalId ?? AGENT_PRINCIPAL, - }), - ], - }); - const raw = (await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 1, - method: 'tools/call', - params: { name: 'analyze_signal', arguments: params.args }, - }) - )) as string; - const parsed = JSON.parse(raw) as { - result: { isError?: boolean; content: { text: string }[] }; - }; - return { - raw, - isError: parsed.result.isError === true, - text: parsed.result.content[0]?.text ?? '', - }; -} - -function baseArgs(fixture: Fixture): Record { - return { - listingIds: fixture.listingIds, - from: fixture.allDates[0]!, - to: fixture.allDates[fixture.allDates.length - 1]!, - signal: { source: 'shorts', field: 'net_change' }, - horizonSessions: 5, - universeMarket: 'CA_EQ', - horizonBucket: 'swing_1_10d', - }; -} - -function poisonBar(listingId: number, ts: number, knownAt: number): BarRecord { - return { - listingId, - ts, - open: POISON, - high: POISON, - low: POISON, - close: POISON, - volume: 1, - knownAt, - }; -} - -function poisonShort(listingId: number, reportDate: string, knownAt: number): TableRow { - return { - listing_id: listingId, - report_date: reportDate, - known_at: knownAt, - shares_short: POISON, - net_change: POISON, - pct_float: POISON, - source: 'poison', - }; -} - -describe('analyze_signal QA: sentinel rows that would fail panel validation if forwarded', () => { - test('positive control: a poison bar or poison shorts row inside the window reaches the panel and maps to a fixed SignalPanelError', async () => { - const fixture = buildFixture(); - const inWindowTs = utcMs(fixture.allDates[50]!, 21); - - expect(() => - shortsTableToSignalRows( - { columns: SHORTS_COLUMNS, rows: [poisonShort(fixture.listingIds[0]!, '2022-10-03', 1)] }, - 'net_change' - ) - ).toThrow(SignalPanelError); - - const leakedBar = await call({ - store: createStore(fixture, { - extraBars: [poisonBar(fixture.listingIds[0]!, inWindowTs + 60_000, inWindowTs + 60_000)], - }).store, - ledger: createLedger().executor, - cutoffTs: fixture.cutoffTs, - args: baseArgs(fixture), - }); - expect(leakedBar.isError).toBe(true); - expect(leakedBar.text).toBe('SignalPanelError: Market bar data failed panel validation.'); - expect(leakedBar.raw).not.toContain('POISON'); - - const ledger = createLedger(); - const leakedShort = await call({ - store: createStore(fixture, { - extraShorts: [poisonShort(fixture.listingIds[0]!, fixture.allDates[50]!, inWindowTs)], - }).store, - ledger: ledger.executor, - cutoffTs: fixture.cutoffTs, - args: baseArgs(fixture), - }); - expect(leakedShort.isError).toBe(true); - expect(leakedShort.text).toBe('SignalPanelError: Signal table data failed panel validation.'); - expect(leakedShort.raw).not.toContain('POISON'); - expect(ledger.rows).toHaveLength(0); - }); - - test('midnight Vault clamp: sentinels at/after the cutoff, before from, or for foreign listings never reach the panel; result equals clean replay', async () => { - const fixture = buildFixture(); - const lid = fixture.listingIds[3]!; - const extraBars = [ - poisonBar(lid, fixture.cutoffTs, fixture.cutoffTs - 1), // exact cutoff ts, backdated knownAt - poisonBar(lid, utcMs(fixture.allDates[100]!, 21), fixture.cutoffTs), // knownAt at cutoff - poisonBar(99_999, utcMs(fixture.allDates[100]!, 15), utcMs(fixture.allDates[100]!, 15)), - poisonBar(lid, utcMs('2022-08-15', 21), utcMs('2022-08-15', 21)), // before from - ]; - const extraShorts = [ - poisonShort(lid, fixture.cutoffDate, fixture.cutoffTs - 1), // cutoff-day report, backdated - poisonShort(lid, fixture.allDates[100]!, fixture.cutoffTs), // known exactly at cutoff - poisonShort(99_999, fixture.allDates[100]!, utcMs(fixture.allDates[105]!, 22)), - poisonShort(lid, '2022-08-15', utcMs('2022-08-19', 22)), // report before from - ]; - - const cleanLedger = createLedger(); - const clean = await call({ - store: createStore(fixture).store, - ledger: cleanLedger.executor, - cutoffTs: fixture.cutoffTs, - args: baseArgs(fixture), - }); - const poisonedLedger = createLedger(); - const poisoned = await call({ - store: createStore(fixture, { extraBars, extraShorts }).store, - ledger: poisonedLedger.executor, - cutoffTs: fixture.cutoffTs, - args: baseArgs(fixture), - }); - - expect(clean.isError).toBe(false); - expect(poisoned.isError).toBe(false); - const payload = JSON.parse(poisoned.text) as AnalyzeSignalResultPayload; - expect(payload.status).toBe('ok'); - expect(payload.clampedTo).toBe(true); - // Omitted asOf defaults to the already-clamped `to`, so only `to` reports a clamp. - expect(payload.clampedAsOf).toBe(false); - expect(payload.asOfMs).toBe(fixture.cutoffTs - 1); - if (payload.status === 'ok') { - expect(payload.trial.sampleEnd < fixture.cutoffDate).toBe(true); - } - expect(JSON.parse(poisoned.text)).toEqual(JSON.parse(clean.text)); - expect(poisonedLedger.rows).toEqual(cleanLedger.rows); - }); - - test('intraday Vault cutoff: cutoff-date bars before the cutoff instant and cutoff-date shorts are excluded; result equals clean replay', async () => { - const fixture = buildFixture(); - const cutoffTs = utcMs(fixture.cutoffDate, 15); - const lid = fixture.listingIds[5]!; - const earlyCutoffDay = utcMs(fixture.cutoffDate, 14); - const extraBars = [ - poisonBar(lid, earlyCutoffDay, earlyCutoffDay), // before cutoff instant, same UTC date - poisonBar(lid, cutoffTs, earlyCutoffDay), // exactly at cutoff - ]; - const extraShorts = [ - poisonShort(lid, fixture.cutoffDate, utcMs(fixture.cutoffDate, 10)), // known before cutoff instant - ]; - - const cleanLedger = createLedger(); - const clean = await call({ - store: createStore(fixture).store, - ledger: cleanLedger.executor, - cutoffTs, - args: { ...baseArgs(fixture), asOf: fixture.allDates[fixture.allDates.length - 1]! }, - }); - const poisonedLedger = createLedger(); - const poisoned = await call({ - store: createStore(fixture, { extraBars, extraShorts }).store, - ledger: poisonedLedger.executor, - cutoffTs, - args: { ...baseArgs(fixture), asOf: fixture.allDates[fixture.allDates.length - 1]! }, - }); - - expect(poisoned.isError).toBe(false); - const payload = JSON.parse(poisoned.text) as AnalyzeSignalResultPayload; - expect(payload.clampedTo).toBe(true); - expect(payload.clampedAsOf).toBe(true); - expect(payload.effectiveTo).toBe(`${fixture.cutoffDate}T14:59:59.999999Z`); - expect(payload.status).toBe('ok'); - expect(JSON.parse(poisoned.text)).toEqual(JSON.parse(clean.text)); - expect(poisonedLedger.rows).toEqual(cleanLedger.rows); - }); - - test('earlier explicit asOf: shorts known after asOf and bars stamped or known after asOf are excluded; result equals clean replay', async () => { - const fixture = buildFixture(); - const asOfDate = fixture.allDates[120]!; - const asOf = `${asOfDate}T18:00:00.000Z`; - const asOfMs = Date.parse(asOf); - const lid = fixture.listingIds[7]!; - const extraBars = [ - poisonBar(lid, utcMs(asOfDate, 21), utcMs(asOfDate, 0)), // close after asOf, backdated knownAt - poisonBar(lid, utcMs(fixture.allDates[119]!, 22), asOfMs + 1), // known 1ms after asOf - ]; - const extraShorts = [poisonShort(lid, fixture.allDates[100]!, asOfMs + 1)]; - const args = { ...baseArgs(fixture), asOf }; - - const cleanLedger = createLedger(); - const clean = await call({ - store: createStore(fixture).store, - ledger: cleanLedger.executor, - cutoffTs: fixture.cutoffTs, - args, - }); - const poisonedLedger = createLedger(); - const poisoned = await call({ - store: createStore(fixture, { extraBars, extraShorts }).store, - ledger: poisonedLedger.executor, - cutoffTs: fixture.cutoffTs, - args, - }); - - expect(poisoned.isError).toBe(false); - const payload = JSON.parse(poisoned.text) as AnalyzeSignalResultPayload; - expect(payload.status).toBe('ok'); - expect(payload.clampedAsOf).toBe(false); - expect(payload.effectiveAsOf).toBe(asOf); - if (payload.status === 'ok') { - expect(payload.trial.sampleEnd < asOfDate).toBe(true); - } - expect(JSON.parse(poisoned.text)).toEqual(JSON.parse(clean.text)); - expect(poisonedLedger.rows).toEqual(cleanLedger.rows); - }); -}); - -describe('analyze_signal QA: store arguments, universe and ledger behaviour', () => { - test('bars and shorts receive identical fenced bounds, 1d timeframe, vault_fenced scope and requested adjustment', async () => { - const fixture = buildFixture(); - const fake = createStore(fixture); - await call({ - store: fake.store, - ledger: createLedger().executor, - cutoffTs: fixture.cutoffTs, - args: { ...baseArgs(fixture), adjustment: 'split' }, - }); - - expect(fake.barsCalls).toHaveLength(1); - expect(fake.shortsCalls).toHaveLength(1); - const bars = fake.barsCalls[0]!; - const shorts = fake.shortsCalls[0]!; - expect(bars.timeframe).toBe('1d'); - expect(bars.scope).toBe('vault_fenced'); - expect(bars.adjustment).toBe('split'); - expect(bars.from).toBe(shorts.from); - expect(bars.to).toBe(shorts.to); - expect(bars.asOf).toBe(shorts.asOf); - expect(bars.listingIds).toEqual(shorts.listingIds); - const lastAllowed = new Date(fixture.cutoffTs - 1).toISOString().replace('Z', '999Z'); - expect(bars.to).toBe(lastAllowed); - expect(bars.asOf).toBe(lastAllowed); - - const defaulted = createStore(fixture); - await call({ - store: defaulted.store, - ledger: createLedger().executor, - cutoffTs: fixture.cutoffTs, - args: baseArgs(fixture), - }); - expect(defaulted.barsCalls[0]?.adjustment).toBe('raw'); - }); - - test('named universe: one snapshot lookup before from; resolved IDs are sorted and deduplicated before the store query', async () => { - const fixture = buildFixture(); - const shuffled = [...fixture.listingIds].reverse(); - const fake = createStore(fixture, { - universe: () => [...shuffled, fixture.listingIds[0]!, fixture.listingIds[1]!], - }); - const ledger = createLedger(); - const args = { ...baseArgs(fixture), universe: 'CA_EQ' } as Record; - delete args.listingIds; - - const res = await call({ store: fake.store, ledger: ledger.executor, cutoffTs: fixture.cutoffTs, args }); - expect(res.isError).toBe(false); - expect(fake.universeCalls).toEqual([{ ref: 'CA_EQ', date: '2022-08-31' }]); - expect(fake.barsCalls[0]?.listingIds).toEqual(fixture.listingIds); - expect(fake.shortsCalls[0]?.listingIds).toEqual(fixture.listingIds); - const payload = JSON.parse(res.text) as AnalyzeSignalResultPayload; - expect(payload.listingCount).toBe(fixture.listingIds.length); - }); - - test('named-universe expression hash differs from the same IDs selected explicitly', async () => { - const fixture = buildFixture(); - const explicitLedger = createLedger(); - await call({ - store: createStore(fixture).store, - ledger: explicitLedger.executor, - cutoffTs: fixture.cutoffTs, - args: baseArgs(fixture), - }); - const universeLedger = createLedger(); - const args = { ...baseArgs(fixture), universe: 'CA_EQ' } as Record; - delete args.listingIds; - await call({ - store: createStore(fixture, { universe: () => fixture.listingIds }).store, - ledger: universeLedger.executor, - cutoffTs: fixture.cutoffTs, - args, - }); - expect(explicitLedger.rows).toHaveLength(1); - expect(universeLedger.rows).toHaveLength(1); - expect(universeLedger.rows[0]!.expression_hash).not.toBe(explicitLedger.rows[0]!.expression_hash); - expect(universeLedger.rows[0]!.daily_series).toEqual(explicitLedger.rows[0]!.daily_series); - }); - - test('maxSignalAgeSessions is applied to the panel and changes the expression hash', async () => { - const fixture = buildFixture(); - const run = async (extra: Record) => { - const ledger = createLedger(); - const res = await call({ - store: createStore(fixture).store, - ledger: ledger.executor, - cutoffTs: fixture.cutoffTs, - args: { ...baseArgs(fixture), ...extra }, - }); - return { payload: JSON.parse(res.text) as AnalyzeSignalResultPayload, ledger }; - }; - const unbounded = await run({}); - const capped = await run({ maxSignalAgeSessions: 3 }); - - expect(unbounded.payload.panelDiagnostics.droppedStaleSignal).toBe(0); - expect(capped.payload.panelDiagnostics.droppedStaleSignal).toBeGreaterThan(0); - expect(capped.payload.status).toBe('ok'); - expect(capped.ledger.rows[0]!.expression_hash).not.toBe(unbounded.ledger.rows[0]!.expression_hash); - }); - - test('replaying the same request on one ledger appends a second row with the same hash and grows the DSR cluster', async () => { - const fixture = buildFixture(); - const ledger = createLedger(); - const first = await call({ - store: createStore(fixture).store, - ledger: ledger.executor, - cutoffTs: fixture.cutoffTs, - args: baseArgs(fixture), - }); - const second = await call({ - store: createStore(fixture).store, - ledger: ledger.executor, - cutoffTs: fixture.cutoffTs, - args: baseArgs(fixture), - }); - const p1 = JSON.parse(first.text) as AnalyzeSignalResultPayload; - const p2 = JSON.parse(second.text) as AnalyzeSignalResultPayload; - if (p1.status !== 'ok' || p2.status !== 'ok') { - throw new Error('expected ok'); - } - expect(ledger.rows).toHaveLength(2); - expect(p2.trial.expressionHash).toBe(p1.trial.expressionHash); - expect(p2.trial.trialId).not.toBe(p1.trial.trialId); - expect(p1.deflatedSharpe.clusterSize).toBe(1); - expect(p2.deflatedSharpe.clusterSize).toBe(2); - }); - - test('operator principal is accepted and recorded; caller cannot change it', async () => { - const fixture = buildFixture(); - const ledger = createLedger(); - const res = await call({ - store: createStore(fixture).store, - ledger: ledger.executor, - cutoffTs: fixture.cutoffTs, - principalId: 'operator', - args: baseArgs(fixture), - }); - expect(res.isError).toBe(false); - expect(ledger.rows.map(r => r.principal_id)).toEqual(['operator']); - }); - - test('unsupported universe refs accept equity market labels but reject FX before any store call', async () => { - const fixture = buildFixture(); - const args = { ...baseArgs(fixture), universe: 'TSX_COMPOSITE' } as Record; - delete args.listingIds; - - const okStore = createStore(fixture, { universe: () => fixture.listingIds }); - const ok = await call({ store: okStore.store, ledger: createLedger().executor, cutoffTs: fixture.cutoffTs, args }); - expect(ok.isError).toBe(false); - expect(okStore.universeCalls[0]?.ref).toBe('TSX_COMPOSITE'); - - const fxStore = createStore(fixture); - const fxLedger = createLedger(); - const fx = await call({ - store: fxStore.store, - ledger: fxLedger.executor, - cutoffTs: fixture.cutoffTs, - args: { ...args, universeMarket: 'FX' }, - }); - expect(JSON.parse(fx.raw).error ?? JSON.parse(fx.raw).result?.isError).toBeTruthy(); - expect(fxStore.universeCalls).toHaveLength(0); - expect(fxStore.barsCalls).toHaveLength(0); - expect(fxLedger.rows).toHaveLength(0); - }); -}); - -describe('analyze_signal QA: factory validation and error sanitisation', () => { - test('factory rejects invalid principal, ledger, store and cutoff without touching the store', () => { - const fixture = buildFixture(); - const fake = createStore(fixture); - const ledger = createLedger().executor; - const vaultContext = { vaultCutoffTs: fixture.cutoffTs }; - - expect(() => - createAnalyzeSignalTool({ store: fake.store, ledger, vaultContext, principalId: 'agent:not-a-uuid' }) - ).toThrow(TrialLedgerError); - expect(() => - createAnalyzeSignalTool({ - store: fake.store, - ledger: {} as TrialLedgerExecutor, - vaultContext, - principalId: AGENT_PRINCIPAL, - }) - ).toThrow(); - expect(() => - createAnalyzeSignalTool({ - store: { bars: fake.store.bars } as unknown as MarketDataStore, - ledger, - vaultContext, - principalId: AGENT_PRINCIPAL, - }) - ).toThrow(MarketDataStoreValidationError); - for (const bad of [Number.NaN, 1.5, Number.POSITIVE_INFINITY, undefined]) { - expect(() => - createAnalyzeSignalTool({ - store: fake.store, - ledger, - vaultContext: { vaultCutoffTs: bad as number }, - principalId: AGENT_PRINCIPAL, - }) - ).toThrow(MarketDataStoreValidationError); - } - expect(fake.barsCalls).toHaveLength(0); - expect(fake.universeCalls).toHaveLength(0); - }); - - test('unknown errors, non-Error throws and unsafe validation fields return fixed generic text with no secrets', async () => { - const fixture = buildFixture(); - const secret = - 'SELECT * FROM bars_1d WHERE x; /srv/data/parquet/bars.parquet postgres://user:pass@host:5432/db'; - const cases: readonly [string, Parameters[1], { insertThrow?: unknown } | undefined, string][] = [ - ['plain Error from bars stream', { barsThrow: new Error(secret) }, undefined, 'Error: Tool execution failed.'], - ['string thrown from shortsAsOf', { shortsThrow: secret }, undefined, 'Error: Tool execution failed.'], - [ - 'validation error with unsafe field name', - { shortsThrow: new MarketDataStoreValidationError(secret, secret) }, - undefined, - 'MarketDataStoreValidationError: Query parameters failed store validation.', - ], - [ - 'not-implemented error for unknown method', - { barsThrow: new MarketDataStoreNotImplementedError(secret as never) }, - undefined, - 'MarketDataStoreNotImplementedError: Requested store operation is not supported.', - ], - ['plain Error from ledger insert', undefined, { insertThrow: new Error(secret) }, 'Error: Tool execution failed.'], - [ - 'unmapped TrialLedgerError code', - undefined, - { insertThrow: new TrialLedgerError('INVALID_ROW', secret) }, - 'TrialLedgerError: Trial ledger operation failed.', - ], - ]; - - for (const [label, storeOpts, ledgerOpts, expected] of cases) { - const ledger = createLedger(ledgerOpts); - const res = await call({ - store: createStore(fixture, storeOpts).store, - ledger: ledger.executor, - cutoffTs: fixture.cutoffTs, - args: baseArgs(fixture), - }); - expect(res.isError, label).toBe(true); - expect(res.text, label).toBe(expected); - for (const fragment of ['SELECT', 'bars_1d', '/srv/data', 'postgres://', 'user:pass', 'stack']) { - expect(res.raw.includes(fragment), `${label}: ${fragment}`).toBe(false); - } - expect(ledger.rows, label).toHaveLength(0); - } - }); - - test('a poison bar forwarded to the panel builder directly throws, proving the sentinel is meaningful', () => { - const fixture = buildFixture(); - const ts = utcMs(fixture.allDates[10]!, 21); - expect(() => - buildForwardReturnPanel({ - bars: [...fixture.bars.filter(b => b.ts < fixture.cutoffTs), poisonBar(fixture.listingIds[0]!, ts + 1, ts + 1)], - signals: [], - horizonSessions: 5, - vaultCutoffDate: fixture.cutoffDate, - }) - ).toThrow(SignalPanelError); - }); -}); diff --git a/libs/research/test/mcp-analyze-signal.test.ts b/libs/research/test/mcp-analyze-signal.test.ts deleted file mode 100644 index e871fdeb..00000000 --- a/libs/research/test/mcp-analyze-signal.test.ts +++ /dev/null @@ -1,3403 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { - type BarBatch, - type BarRecord, - type MarketDataStore, - MarketDataStoreValidationError, - type Table, - type TableRow, - VaultScopeNotAuthorizedError, -} from '../src/market-data-store'; -import { - type BarsQuery, - FUNDAMENTALS_PIT_VALUE_FIELDS, - type FundamentalsAsOfQuery, - MarketDataStoreNotImplementedError, - type ShortsAsOfQuery, - type UniverseQuery, -} from '../src/market-data-store-duckdb'; -import { - ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS, - ANALYZE_SIGNAL_MAX_HORIZON_SESSIONS, - ANALYZE_SIGNAL_MAX_LISTING_IDS, - ANALYZE_SIGNAL_MAX_SERIES_POINTS, - type AnalyzeSignalResultPayload, - createAnalyzeSignalTool, - createMcpServer, - createQueryDataTool, -} from '../src/mcp/index'; -import { - type SignalObservation, - buildForwardReturnPanel, - shortsTableToSignalRows, -} from '../src/signal-panel'; -import { analyzeSignal } from '../src/signal-study'; -import { type TrialLedgerExecutor, canonicalExpressionHash } from '../src/trial-ledger'; - -const SEED = 20261129; -const AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555'; -const CAMPAIGN_UUID = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee'; -const HYPOTHESIS_UUID = '12345678-1234-4123-8123-123456789abc'; - -function createSeededRng(seed: number): () => number { - let state = seed >>> 0; - return () => { - state = (state + 0x6d2b79f5) >>> 0; - let t = Math.imul(state ^ (state >>> 15), 1 | state); - t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; - return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296; - }; -} - -function makeBusinessDates(startDate: string, count: number): string[] { - const out: string[] = new Array(count); - const current = new Date(`${startDate}T00:00:00.000Z`); - let written = 0; - while (written < count) { - const day = current.getUTCDay(); - if (day !== 0 && day !== 6) { - out[written] = current.toISOString().slice(0, 10); - written += 1; - } - current.setUTCDate(current.getUTCDate() + 1); - } - return out; -} - -function makeUtcMs(date: string, hourUtc: number): number { - const [y, m, d] = date.split('-').map(Number); - return Date.UTC(y!, m! - 1, d!, hourUtc, 0, 0, 0); -} - -interface StoredTrialRow { - readonly trial_id: string; - readonly created_at: Date; - readonly principal_id: string; - readonly campaign_id: string | null; - readonly stage: string; - readonly universe_market: string; - readonly horizon_bucket: string; - readonly hypothesis_id: string | null; - readonly expression_hash: string; - readonly sample_start: string; - readonly sample_end: string; - readonly n_obs: number; - readonly sharpe_unann: number; - readonly skewness: number; - readonly kurtosis: number; - readonly daily_series: readonly number[]; -} - -function createFakeTrialLedger(options?: { - insertError?: Error; - dsrReadError?: Error; -}): { - executor: TrialLedgerExecutor; - rows: StoredTrialRow[]; - insertCalls: number; - selectCalls: number; -} { - const rows: StoredTrialRow[] = []; - let nextTrialId = 1; - const state = { - rows, - insertCalls: 0, - selectCalls: 0, - executor: null as unknown as TrialLedgerExecutor, - }; - - state.executor = { - async query>(text: string, params?: readonly unknown[]) { - const trimmed = text.trimStart(); - if (trimmed.startsWith('INSERT INTO trial_ledger')) { - state.insertCalls += 1; - if (options?.insertError !== undefined) { - throw options.insertError; - } - const p = params ?? []; - const trialId = nextTrialId++; - const createdAt = new Date(Date.UTC(2024, 5, 1, 12, 0, trialId)); - const dailySeries = (p[13] as readonly number[]).map(v => Math.fround(v)); - const stored: StoredTrialRow = { - trial_id: String(trialId), - created_at: createdAt, - principal_id: p[0] as string, - campaign_id: (p[1] as string | null) ?? null, - stage: p[2] as string, - universe_market: p[3] as string, - horizon_bucket: p[4] as string, - hypothesis_id: (p[5] as string | null) ?? null, - expression_hash: p[6] as string, - sample_start: p[7] as string, - sample_end: p[8] as string, - n_obs: p[9] as number, - sharpe_unann: p[10] as number, - skewness: p[11] as number, - kurtosis: p[12] as number, - daily_series: dailySeries, - }; - rows.push(stored); - return { - rows: [{ trial_id: stored.trial_id, created_at: stored.created_at } as unknown as Row], - rowCount: 1, - }; - } - - if (trimmed.startsWith('SELECT')) { - state.selectCalls += 1; - if (options?.dsrReadError !== undefined) { - throw options.dsrReadError; - } - if (text.includes('WHERE trial_id = $1::bigint')) { - const targetId = String(params?.[0]); - const matched = rows.filter(r => r.trial_id === targetId); - return { rows: matched as unknown as Row[], rowCount: matched.length }; - } - if (text.includes('WHERE universe_market = $1')) { - const market = params?.[0] as string; - const bucket = params?.[1] as string; - const matched = rows.filter( - r => r.universe_market === market && r.horizon_bucket === bucket - ); - return { rows: matched as unknown as Row[], rowCount: matched.length }; - } - } - - return { rows: [], rowCount: 0 }; - }, - }; - - return state; -} - -interface CeoShortsFixture { - readonly listingIds: number[]; - readonly allDates: string[]; - readonly vaultCutoffDate: string; - readonly vaultCutoffTs: number; - readonly bars: BarRecord[]; - readonly shortsTable: Table; -} - -const SHORTS_COLUMNS = [ - 'listing_id', - 'report_date', - 'known_at', - 'shares_short', - 'net_change', - 'pct_float', - 'source', -] as const; - -function buildCeoShortsFixture(options?: { - preCutoffSessions?: number; - postCutoffSessions?: number; - listingCount?: number; - poisonPostCutoff?: boolean; -}): CeoShortsFixture { - const rand = createSeededRng(SEED); - const listingCount = options?.listingCount ?? 28; - const preCutoffSessions = options?.preCutoffSessions ?? 140; - const postCutoffSessions = options?.postCutoffSessions ?? 10; - const poisonPostCutoff = options?.poisonPostCutoff ?? false; - - const allDates = makeBusinessDates('2022-09-01', preCutoffSessions + postCutoffSessions); - const vaultCutoffDate = allDates[preCutoffSessions]!; - const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0); - - const listingIds = Array.from({ length: listingCount }, (_, i) => 50_001 + i); - const bars: BarRecord[] = []; - const shortsRows: TableRow[] = []; - - const PUBLICATION_LAG_SESSIONS = 4; - const activeNetChange = new Float64Array(listingCount); - const pendingByPublishIdx = new Map(); - const prices = new Float64Array(listingCount); - for (let l = 0; l < listingCount; l += 1) { - prices[l] = 10 + l * 1.5; - } - - for (let t = 0; t < allDates.length; t += 1) { - const date = allDates[t]!; - const closeTs = makeUtcMs(date, 21); // 16:00 ET close - - const released = pendingByPublishIdx.get(t - 1); - if (released !== undefined) { - for (let l = 0; l < listingCount; l += 1) { - const v = released[l]; - if (v !== null && v !== undefined) { - activeNetChange[l] = v / 20_000; - } - } - } - - const publishIdx = t + PUBLICATION_LAG_SESSIONS; - if (t % 10 === 0 && publishIdx < allDates.length) { - const reportKnownAt = makeUtcMs(allDates[publishIdx]!, 22); // 17:00 ET on T+4 - const pending: (number | null)[] = []; - for (let l = 0; l < listingCount; l += 1) { - const isNullCell = t > 0 && (t + l) % 19 === 0; - const netChange = isNullCell ? null : Math.round((rand() * 2 - 1) * 20_000); - pending.push(netChange); - shortsRows.push({ - listing_id: listingIds[l]!, - report_date: date, - known_at: reportKnownAt, - shares_short: 100_000 + l * 5_000 + Math.round(rand() * 10_000), - net_change: netChange, - pct_float: isNullCell ? null : Number((0.02 + rand() * 0.08).toFixed(4)), - source: 'ceoShorts', - }); - } - pendingByPublishIdx.set(publishIdx, pending); - } - - for (let l = 0; l < listingCount; l += 1) { - const dailyRet = -0.004 * activeNetChange[l]! + (rand() * 2 - 1) * 0.008; - prices[l] = Math.max(0.5, prices[l]! * (1 + dailyRet)); - const isPostCutoff = date >= vaultCutoffDate; - const closeVal = poisonPostCutoff && isPostCutoff ? 999_999 : Number(prices[l]!.toFixed(6)); - bars.push({ - listingId: listingIds[l]!, - ts: closeTs, - open: closeVal, - high: closeVal, - low: closeVal, - close: closeVal, - volume: 50_000, - vwap: closeVal, - knownAt: closeTs, - }); - } - } - - return { - listingIds, - allDates, - vaultCutoffDate, - vaultCutoffTs, - bars, - shortsTable: { - columns: SHORTS_COLUMNS, - rows: shortsRows, - }, - }; -} - -interface FakeStoreState { - readonly barsCalls: BarsQuery[]; - readonly shortsCalls: ShortsAsOfQuery[]; - readonly fundamentalsCalls: FundamentalsAsOfQuery[]; - readonly universeCalls: UniverseQuery[]; - readonly store: MarketDataStore; -} - -function createFakeStore(options?: { - bars?: readonly BarRecord[]; - shortsTable?: Table; - fundamentalsResolver?: (q: FundamentalsAsOfQuery) => Table | Promise
; - universeIds?: readonly number[]; - universeResolver?: (q: UniverseQuery) => number[]; - leaky?: boolean; - barsError?: Error; - shortsError?: Error; - fundamentalsError?: Error; - universeError?: Error; -}): FakeStoreState { - const barsCalls: BarsQuery[] = []; - const shortsCalls: ShortsAsOfQuery[] = []; - const fundamentalsCalls: FundamentalsAsOfQuery[] = []; - const universeCalls: UniverseQuery[] = []; - - const allBars = options?.bars ?? []; - const allShorts = options?.shortsTable ?? { columns: SHORTS_COLUMNS, rows: [] }; - const leaky = options?.leaky ?? false; - - const store: MarketDataStore = { - bars(q: BarsQuery): AsyncIterable { - barsCalls.push(q); - if (options?.barsError !== undefined) { - const err = options.barsError; - return { - [Symbol.asyncIterator]() { - return { - next() { - return Promise.reject(err); - }, - }; - }, - }; - } - - const idSet = new Set(q.listingIds); - const fromMs = Date.parse(q.from.length === 10 ? `${q.from}T00:00:00.000Z` : q.from); - const toMs = Date.parse(q.to.length === 10 ? `${q.to}T23:59:59.999Z` : q.to); - const asOfMs = - q.asOf !== undefined - ? Date.parse(q.asOf.length === 10 ? `${q.asOf}T23:59:59.999Z` : q.asOf) - : Number.POSITIVE_INFINITY; - - const filtered = leaky - ? [...allBars] - : allBars.filter( - row => - idSet.has(row.listingId) && - row.ts >= fromMs && - row.ts <= toMs && - row.ts <= asOfMs && - row.knownAt <= asOfMs - ); - - return { - async *[Symbol.asyncIterator]() { - yield { rows: filtered }; - }, - }; - }, - - async shortsAsOf(q: ShortsAsOfQuery): Promise
{ - shortsCalls.push(q); - if (options?.shortsError !== undefined) { - throw options.shortsError; - } - - if (leaky) { - return { - columns: allShorts.columns, - rows: [...allShorts.rows], - }; - } - - const idSet = new Set(q.listingIds); - const fromDate = q.from.slice(0, 10); - const toDate = q.to.slice(0, 10); - const asOfMs = - q.asOf !== undefined - ? Date.parse(q.asOf.length === 10 ? `${q.asOf}T23:59:59.999Z` : q.asOf) - : Number.POSITIVE_INFINITY; - - const rows = allShorts.rows.filter(row => { - const lid = row.listing_id as number; - const reportDate = row.report_date as string | undefined; - const knownAt = row.known_at as number; - const inDateRange = - reportDate === undefined || (reportDate >= fromDate && reportDate <= toDate); - return idSet.has(lid) && inDateRange && knownAt <= asOfMs; - }); - - return { - columns: allShorts.columns, - rows, - }; - }, - - async universe(q: UniverseQuery): Promise { - universeCalls.push(q); - if (options?.universeError !== undefined) { - throw options.universeError; - } - if (options?.universeResolver !== undefined) { - return options.universeResolver(q); - } - return [...(options?.universeIds ?? [])]; - }, - - crossSection() { - throw new MarketDataStoreNotImplementedError('crossSection'); - }, - async fundamentalsAsOf(q: FundamentalsAsOfQuery): Promise
{ - fundamentalsCalls.push(q); - if (options?.fundamentalsError !== undefined) { - throw options.fundamentalsError; - } - if (options?.fundamentalsResolver !== undefined) { - return options.fundamentalsResolver(q); - } - throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); - }, - events() { - throw new MarketDataStoreNotImplementedError('events'); - }, - macroAsOf() { - throw new MarketDataStoreNotImplementedError('macroAsOf'); - }, - fx() { - throw new MarketDataStoreNotImplementedError('fx'); - }, - }; - - return { barsCalls, shortsCalls, fundamentalsCalls, universeCalls, store }; -} - -async function callAnalyzeSignal(params: { - store: MarketDataStore; - ledger: TrialLedgerExecutor; - vaultCutoffTs: number; - principalId?: string; - args: Record; -}): Promise<{ - rawResponse: string; - isError: boolean; - text: string; -}> { - const tool = createAnalyzeSignalTool({ - store: params.store, - ledger: params.ledger, - vaultContext: { vaultCutoffTs: params.vaultCutoffTs }, - principalId: params.principalId ?? AGENT_PRINCIPAL, - }); - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [tool], - }); - - const rawResponse = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 'as-1', - method: 'tools/call', - params: { - name: 'analyze_signal', - arguments: params.args, - }, - }) - ); - - expect(rawResponse).not.toBeNull(); - const parsed = JSON.parse(rawResponse as string) as { - result: { - isError?: boolean; - content: { type: string; text: string }[]; - }; - }; - return { - rawResponse: rawResponse as string, - isError: parsed.result.isError === true, - text: parsed.result.content[0]?.text ?? '', - }; -} - -describe('MCP analyze_signal tool', () => { - test('tools/list advertises query_data and analyze_signal and omits server-controlled fields from analyze_signal schema', async () => { - const fixture = buildCeoShortsFixture({ preCutoffSessions: 20, postCutoffSessions: 5, listingCount: 6 }); - const fakeStore = createFakeStore({ bars: fixture.bars, shortsTable: fixture.shortsTable }); - const fakeLedger = createFakeTrialLedger(); - - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createQueryDataTool({ - store: fakeStore.store, - vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, - }), - createAnalyzeSignalTool({ - store: fakeStore.store, - ledger: fakeLedger.executor, - vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - }), - ], - }); - - const raw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 'list-1', - method: 'tools/list', - }) - ); - - const parsed = JSON.parse(raw as string) as { - result: { - tools: { - name: string; - description: string; - inputSchema: { - type: string; - properties: Record }>; - required?: string[]; - additionalProperties: boolean; - }; - }[]; - }; - }; - - const names = parsed.result.tools.map(t => t.name); - expect(names).toEqual(['query_data', 'analyze_signal']); - - const analyzeTool = parsed.result.tools.find(t => t.name === 'analyze_signal'); - expect(analyzeTool).toBeDefined(); - expect(analyzeTool?.inputSchema.type).toBe('object'); - expect(analyzeTool?.inputSchema.additionalProperties).toBe(false); - expect(analyzeTool?.inputSchema.properties.signal?.additionalProperties).toBe(false); - - const propKeys = Object.keys(analyzeTool?.inputSchema.properties ?? {}); - expect(propKeys).toContain('listingIds'); - expect(propKeys).toContain('universe'); - expect(propKeys).toContain('from'); - expect(propKeys).toContain('to'); - expect(propKeys).toContain('signal'); - expect(propKeys).toContain('horizonSessions'); - expect(propKeys).toContain('universeMarket'); - expect(propKeys).toContain('horizonBucket'); - - for (const forbidden of ['scope', 'vault_evaluation_only', 'principalId', 'vaultCutoffDate']) { - expect(propKeys).not.toContain(forbidden); - expect(analyzeTool?.inputSchema.required ?? []).not.toContain(forbidden); - } - }); - - test('executes seeded ceoShorts fixture with parity to direct analyzeSignal and writes exactly one trial row under injected principal', async () => { - const fixture = buildCeoShortsFixture(); - const fakeStore = createFakeStore({ - bars: fixture.bars, - shortsTable: fixture.shortsTable, - }); - const mcpLedger = createFakeTrialLedger(); - - const from = fixture.allDates[0]!; - const to = fixture.allDates[fixture.allDates.length - 1]!; - - const res = await callAnalyzeSignal({ - store: fakeStore.store, - ledger: mcpLedger.executor, - vaultCutoffTs: fixture.vaultCutoffTs, - principalId: AGENT_PRINCIPAL, - args: { - listingIds: fixture.listingIds, - from, - to, - signal: { source: 'shorts', field: 'net_change' }, - horizonSessions: 5, - universeMarket: 'CA_EQ', - horizonBucket: 'swing_1_10d', - campaignId: CAMPAIGN_UUID, - hypothesisId: HYPOTHESIS_UUID, - }, - }); - - expect(res.isError).toBe(false); - const payload = JSON.parse(res.text) as AnalyzeSignalResultPayload; - expect(payload.status).toBe('ok'); - if (payload.status !== 'ok') { - return; - } - - // Run direct research pipeline on the same pre-cutoff bars/shorts with a fresh isolated ledger - const directLedger = createFakeTrialLedger(); - const preCutoffBars = fixture.bars.filter(b => b.ts < fixture.vaultCutoffTs); - const preCutoffShorts: Table = { - columns: fixture.shortsTable.columns, - rows: fixture.shortsTable.rows.filter( - r => (r.report_date as string) < fixture.vaultCutoffDate && (r.known_at as number) < fixture.vaultCutoffTs - ), - }; - const directSignals = shortsTableToSignalRows(preCutoffShorts, 'net_change'); - const directBuilt = buildForwardReturnPanel({ - bars: preCutoffBars, - signals: directSignals, - horizonSessions: 5, - vaultCutoffDate: fixture.vaultCutoffDate, - }); - const directStudy = await analyzeSignal(directLedger.executor, { - principalId: AGENT_PRINCIPAL, - campaignId: CAMPAIGN_UUID, - hypothesisId: HYPOTHESIS_UUID, - universeMarket: 'CA_EQ', - horizonBucket: 'swing_1_10d', - expression: { - expression: 'direct_reference', - params: { field: 'net_change', horizonSessions: 5 }, - universe: fixture.listingIds, - horizon: '5d', - }, - panel: directBuilt.panel, - vaultCutoffDate: fixture.vaultCutoffDate, - }); - - expect(directStudy.status).toBe('ok'); - if (directStudy.status !== 'ok') { - return; - } - - // Parity between MCP payload and direct research pipeline - expect(payload.scope).toBe('vault_fenced'); - expect(payload.vaultCutoffTs).toBe(fixture.vaultCutoffTs); - expect(payload.vaultCutoffDate).toBe(fixture.vaultCutoffDate); - expect(payload.panelDiagnostics).toEqual(directBuilt.diagnostics); - expect(payload.analysis.rankIc).toEqual(directStudy.analysis.rankIc); - expect(payload.analysis.pearsonIc).toEqual(directStudy.analysis.pearsonIc); - expect(payload.analysis.quantiles.spreadSummary).toEqual( - directStudy.analysis.quantiles.spreadSummary - ); - expect(payload.analysis.turnover.meanTopTurnover).toBe( - directStudy.analysis.turnover.meanTopTurnover - ); - expect(payload.analysis.recency).toEqual(directStudy.analysis.recency); - expect(payload.analysis.diagnostics).toEqual(directStudy.analysis.diagnostics); - expect(payload.trial.sampleStart).toBe(directStudy.trial.sampleStart); - expect(payload.trial.sampleEnd).toBe(directStudy.trial.sampleEnd); - expect(payload.trial.sampleEnd < fixture.vaultCutoffDate).toBe(true); - expect(payload.trial.nObs).toBe(directStudy.trial.nObs); - expect(payload.trial.expressionHash).toMatch(/^[0-9a-f]{64}$/); - expect(payload.deflatedSharpe).toEqual(directStudy.deflatedSharpe); - - // Bounded series preview: >100 observations truncated to latest 100 while study & ledger keep full sample - expect(payload.analysis.ledgerSeries.series).toBe('rank_ic'); - expect(payload.analysis.ledgerSeries.totalCount).toBe(directStudy.trial.nObs); - expect(payload.analysis.ledgerSeries.totalCount).toBeGreaterThan(ANALYZE_SIGNAL_MAX_SERIES_POINTS); - expect(payload.analysis.ledgerSeries.truncated).toBe(true); - expect(payload.analysis.ledgerSeries.points).toHaveLength(ANALYZE_SIGNAL_MAX_SERIES_POINTS); - const lastPoint = payload.analysis.ledgerSeries.points[ANALYZE_SIGNAL_MAX_SERIES_POINTS - 1]; - expect(lastPoint?.date).toBe(directStudy.trial.sampleEnd); - - // Exactly one trial_ledger row written with injected principalId and full daily_series - expect(mcpLedger.rows).toHaveLength(1); - const stored = mcpLedger.rows[0]!; - expect(stored.stage).toBe('signal_ic'); - expect(stored.principal_id).toBe(AGENT_PRINCIPAL); - expect(stored.campaign_id).toBe(CAMPAIGN_UUID); - expect(stored.hypothesis_id).toBe(HYPOTHESIS_UUID); - expect(stored.universe_market).toBe('CA_EQ'); - expect(stored.horizon_bucket).toBe('swing_1_10d'); - expect(stored.n_obs).toBe(directStudy.trial.nObs); - expect(stored.daily_series).toHaveLength(directStudy.trial.nObs); - }); - - test('identical requests and reordered/duplicate listingIds produce the same expressionHash; changing field, horizon, or ledgerSeries changes it', async () => { - const fixture = buildCeoShortsFixture(); - const from = fixture.allDates[0]!; - const to = fixture.allDates[fixture.allDates.length - 1]!; - - async function runWithArgs(args: Record) { - const store = createFakeStore({ bars: fixture.bars, shortsTable: fixture.shortsTable }); - const ledger = createFakeTrialLedger(); - const res = await callAnalyzeSignal({ - store: store.store, - ledger: ledger.executor, - vaultCutoffTs: fixture.vaultCutoffTs, - args, - }); - expect(res.isError).toBe(false); - const payload = JSON.parse(res.text) as AnalyzeSignalResultPayload; - expect(payload.status).toBe('ok'); - if (payload.status !== 'ok') { - throw new Error('Expected ok status'); - } - return { payload, ledger }; - } - - const baseArgs = { - listingIds: fixture.listingIds, - from, - to, - signal: { source: 'shorts', field: 'net_change' }, - horizonSessions: 5, - universeMarket: 'CA_EQ', - horizonBucket: 'swing_1_10d', - }; - - const run1 = await runWithArgs(baseArgs); - const run2 = await runWithArgs(baseArgs); - expect(run1.payload.trial.expressionHash).toBe(run2.payload.trial.expressionHash); - - // Reordered and duplicated listingIds canonicalize to the exact same expressionHash - const reorderedIds = [...fixture.listingIds].reverse(); - reorderedIds.push(fixture.listingIds[0]!, fixture.listingIds[3]!); - const runReordered = await runWithArgs({ ...baseArgs, listingIds: reorderedIds }); - expect(runReordered.payload.trial.expressionHash).toBe(run1.payload.trial.expressionHash); - - // Different signal.field -> different expressionHash - const runOtherField = await runWithArgs({ - ...baseArgs, - signal: { source: 'shorts', field: 'pct_float' }, - }); - expect(runOtherField.payload.trial.expressionHash).not.toBe(run1.payload.trial.expressionHash); - - // Different horizonSessions -> different expressionHash (including position_10d_plus bucket for 11d) - const runOtherHorizon = await runWithArgs({ - ...baseArgs, - horizonSessions: 11, - horizonBucket: 'position_10d_plus', - }); - expect(runOtherHorizon.payload.trial.expressionHash).not.toBe(run1.payload.trial.expressionHash); - expect(runOtherHorizon.ledger.rows[0]?.horizon_bucket).toBe('position_10d_plus'); - - // Equivalent date/timestamp/offset forms canonicalize to identical effective microsecond bounds & expressionHash - const midDate = fixture.allDates[120]!; - const runDateForm = await runWithArgs({ - ...baseArgs, - from, - to: midDate, - asOf: midDate, - }); - const runIsoMicrosForm = await runWithArgs({ - ...baseArgs, - from: `${from}T00:00:00.000000Z`, - to: `${midDate}T23:59:59.999999Z`, - asOf: `${midDate}T23:59:59.999999Z`, - }); - const runOffsetForm = await runWithArgs({ - ...baseArgs, - from: '2022-08-31T19:00:00.000000-05:00', - to: `${midDate}T18:59:59.999999-05:00`, - asOf: `${midDate}T18:59:59.999999-05:00`, - }); - expect(runDateForm.payload.effectiveFrom).toBe(`${from}T00:00:00.000Z`); - expect(runDateForm.payload.effectiveTo).toBe(`${midDate}T23:59:59.999999Z`); - expect(runDateForm.payload.effectiveAsOf).toBe(`${midDate}T23:59:59.999999Z`); - expect(runIsoMicrosForm.payload.effectiveFrom).toBe(runDateForm.payload.effectiveFrom); - expect(runIsoMicrosForm.payload.effectiveTo).toBe(runDateForm.payload.effectiveTo); - expect(runIsoMicrosForm.payload.effectiveAsOf).toBe(runDateForm.payload.effectiveAsOf); - expect(runIsoMicrosForm.payload.trial.expressionHash).toBe( - runDateForm.payload.trial.expressionHash - ); - expect(runOffsetForm.payload.trial.expressionHash).toBe( - runDateForm.payload.trial.expressionHash - ); - - // Distinct sub-millisecond effective bounds produce different expressionHash even with identical sampleStart/sampleEnd - const runAsOfZeroMicros = await runWithArgs({ - ...baseArgs, - from, - to: midDate, - asOf: `${midDate}T23:59:59.999000Z`, - }); - expect(runAsOfZeroMicros.payload.effectiveAsOf).toBe(`${midDate}T23:59:59.999Z`); - expect(runAsOfZeroMicros.payload.trial.sampleStart).toBe(runDateForm.payload.trial.sampleStart); - expect(runAsOfZeroMicros.payload.trial.sampleEnd).toBe(runDateForm.payload.trial.sampleEnd); - expect(runAsOfZeroMicros.payload.trial.expressionHash).not.toBe( - runDateForm.payload.trial.expressionHash - ); - - const runToZeroMicros = await runWithArgs({ - ...baseArgs, - from, - to: `${midDate}T23:59:59.999000Z`, - asOf: midDate, - }); - expect(runToZeroMicros.payload.effectiveTo).toBe(`${midDate}T23:59:59.999Z`); - expect(runToZeroMicros.payload.trial.expressionHash).not.toBe( - runDateForm.payload.trial.expressionHash - ); - - const runFromOneMicro = await runWithArgs({ - ...baseArgs, - from: `${from}T00:00:00.000001Z`, - to: midDate, - asOf: midDate, - }); - expect(runFromOneMicro.payload.effectiveFrom).toBe(`${from}T00:00:00.000001Z`); - expect(runFromOneMicro.payload.trial.expressionHash).not.toBe( - runDateForm.payload.trial.expressionHash - ); - - // quantile_spread ledgerSeries works, truncates preview to 100 while preserving full count, and hashes distinctly - const runSpread = await runWithArgs({ ...baseArgs, ledgerSeries: 'quantile_spread' }); - expect(runSpread.payload.analysis.ledgerSeries.series).toBe('quantile_spread'); - expect(runSpread.payload.analysis.ledgerSeries.totalCount).toBe(runSpread.payload.trial.nObs); - expect(runSpread.payload.analysis.ledgerSeries.truncated).toBe(true); - expect(runSpread.payload.analysis.ledgerSeries.points).toHaveLength( - ANALYZE_SIGNAL_MAX_SERIES_POINTS - ); - expect(runSpread.ledger.rows[0]?.daily_series).toHaveLength(runSpread.payload.trial.nObs); - expect(runSpread.payload.trial.expressionHash).not.toBe(run1.payload.trial.expressionHash); - }); - - test('clamps to/asOf strictly below midnight and intraday Vault cutoffs and blocks cutoff-day leakage from a leaky store', async () => { - const cleanFixture = buildCeoShortsFixture({ poisonPostCutoff: false }); - const poisonedFixture = buildCeoShortsFixture({ poisonPostCutoff: true }); - const from = cleanFixture.allDates[0]!; - const postCutoffDate = cleanFixture.allDates[cleanFixture.allDates.length - 1]!; - const horizonSessions = 5; - - // 1. Clamping test with to and asOf after Vault cutoff (midnight cutoff) - const clampLedger = createFakeTrialLedger(); - const clampStore = createFakeStore({ - bars: cleanFixture.bars, - shortsTable: cleanFixture.shortsTable, - }); - const clampRes = await callAnalyzeSignal({ - store: clampStore.store, - ledger: clampLedger.executor, - vaultCutoffTs: cleanFixture.vaultCutoffTs, - args: { - listingIds: cleanFixture.listingIds, - from, - to: postCutoffDate, - asOf: postCutoffDate, - signal: { source: 'shorts', field: 'net_change' }, - horizonSessions, - universeMarket: 'CA_EQ', - horizonBucket: 'swing_1_10d', - }, - }); - - expect(clampRes.isError).toBe(false); - const clampPayload = JSON.parse(clampRes.text) as AnalyzeSignalResultPayload; - expect(clampPayload.status).toBe('ok'); - expect(clampPayload.clampedTo).toBe(true); - expect(clampPayload.clampedAsOf).toBe(true); - expect(clampPayload.toMs).toBe(cleanFixture.vaultCutoffTs - 1); - expect(clampPayload.asOfMs).toBe(cleanFixture.vaultCutoffTs - 1); - - // Store received fenced to and asOf strictly below vaultCutoffTs - expect(clampStore.barsCalls).toHaveLength(1); - expect(clampStore.barsCalls[0]?.scope).toBe('vault_fenced'); - expect(Date.parse(clampStore.barsCalls[0]?.to ?? '')).toBe(cleanFixture.vaultCutoffTs - 1); - expect(Date.parse(clampStore.barsCalls[0]?.asOf ?? '')).toBe(cleanFixture.vaultCutoffTs - 1); - expect(clampStore.shortsCalls).toHaveLength(1); - expect(Date.parse(clampStore.shortsCalls[0]?.to ?? '')).toBe(cleanFixture.vaultCutoffTs - 1); - expect(Date.parse(clampStore.shortsCalls[0]?.asOf ?? '')).toBe(cleanFixture.vaultCutoffTs - 1); - if (clampPayload.status === 'ok') { - expect(clampPayload.trial.sampleEnd < cleanFixture.vaultCutoffDate).toBe(true); - const endIdx = cleanFixture.allDates.indexOf(clampPayload.trial.sampleEnd); - const lastForwardEndpoint = cleanFixture.allDates[endIdx + horizonSessions]!; - expect(lastForwardEndpoint < cleanFixture.vaultCutoffDate).toBe(true); - } - - // 2. Intraday Vault cutoff (12:00 UTC on vaultCutoffDate) with asOf beyond cutoff and leaky store - // injecting rows on vaultCutoffDate before cutoff, at exact cutoff timestamp, and after cutoff. - const intradayCutoffTs = makeUtcMs(cleanFixture.vaultCutoffDate, 12); - const cleanPreCutoffBars = cleanFixture.bars.filter( - b => new Date(b.ts).toISOString().slice(0, 10) < cleanFixture.vaultCutoffDate - ); - const cleanPreCutoffShorts: Table = { - columns: cleanFixture.shortsTable.columns, - rows: cleanFixture.shortsTable.rows.filter( - r => - (r.report_date as string) < cleanFixture.vaultCutoffDate && - (r.known_at as number) < intradayCutoffTs - ), - }; - const cleanIntradayStore = createFakeStore({ - bars: cleanPreCutoffBars, - shortsTable: cleanPreCutoffShorts, - leaky: false, - }); - const leakyIntradayStore = createFakeStore({ - bars: [ - ...poisonedFixture.bars, - // Cutoff-day bars BEFORE intradayCutoffTs (10:00 UTC) for every listing - ...poisonedFixture.listingIds.map(listingId => ({ - listingId, - ts: makeUtcMs(poisonedFixture.vaultCutoffDate, 10), - open: 888_888, - high: 888_888, - low: 888_888, - close: 888_888, - volume: 100, - vwap: 888_888, - knownAt: makeUtcMs(poisonedFixture.vaultCutoffDate, 10), - })), - // Bar at EXACT intradayCutoffTs (12:00 UTC) - { - listingId: poisonedFixture.listingIds[0]!, - ts: intradayCutoffTs, - open: 777_777, - high: 777_777, - low: 777_777, - close: 777_777, - volume: 100, - vwap: 777_777, - knownAt: intradayCutoffTs, - }, - ], - shortsTable: { - columns: poisonedFixture.shortsTable.columns, - rows: [ - ...poisonedFixture.shortsTable.rows, - // Shorts row on vaultCutoffDate with known_at before intradayCutoffTs - { - listing_id: poisonedFixture.listingIds[0]!, - report_date: poisonedFixture.vaultCutoffDate, - known_at: makeUtcMs(poisonedFixture.vaultCutoffDate, 9), - shares_short: 9_999_999, - net_change: 9_999_999, - pct_float: 0.99, - source: 'ceoShorts', - }, - // Shorts row with report_date before cutoff but known_at at exact intradayCutoffTs - { - listing_id: poisonedFixture.listingIds[1]!, - report_date: cleanFixture.allDates[100]!, - known_at: intradayCutoffTs, - shares_short: 8_888_888, - net_change: 8_888_888, - pct_float: 0.88, - source: 'ceoShorts', - }, - ], - }, - leaky: true, - }); - - const cleanIntradayLedger = createFakeTrialLedger(); - const leakyIntradayLedger = createFakeTrialLedger(); - const intradayArgs = { - listingIds: cleanFixture.listingIds, - from, - to: postCutoffDate, - asOf: postCutoffDate, - signal: { source: 'shorts', field: 'net_change' }, - horizonSessions, - universeMarket: 'CA_EQ', - horizonBucket: 'swing_1_10d', - }; - - const cleanIntradayRes = await callAnalyzeSignal({ - store: cleanIntradayStore.store, - ledger: cleanIntradayLedger.executor, - vaultCutoffTs: intradayCutoffTs, - args: intradayArgs, - }); - const leakyIntradayRes = await callAnalyzeSignal({ - store: leakyIntradayStore.store, - ledger: leakyIntradayLedger.executor, - vaultCutoffTs: intradayCutoffTs, - args: intradayArgs, - }); - - expect(cleanIntradayRes.isError).toBe(false); - expect(leakyIntradayRes.isError).toBe(false); - expect(leakyIntradayRes.text).toBe(cleanIntradayRes.text); - expect(leakyIntradayLedger.rows).toEqual(cleanIntradayLedger.rows); - - const intradayPayload = JSON.parse(leakyIntradayRes.text) as AnalyzeSignalResultPayload; - expect(intradayPayload.status).toBe('ok'); - expect(intradayPayload.clampedTo).toBe(true); - expect(intradayPayload.clampedAsOf).toBe(true); - expect(intradayPayload.toMs).toBe(intradayCutoffTs - 1); - expect(intradayPayload.asOfMs).toBe(intradayCutoffTs - 1); - if (intradayPayload.status === 'ok') { - expect(intradayPayload.trial.sampleEnd < cleanFixture.vaultCutoffDate).toBe(true); - const endIdx = cleanFixture.allDates.indexOf(intradayPayload.trial.sampleEnd); - const lastForwardEndpoint = cleanFixture.allDates[endIdx + horizonSessions]!; - expect(lastForwardEndpoint < cleanFixture.vaultCutoffDate).toBe(true); - } - }); - - test('earlier explicit asOf excludes bars with ts > asOf or knownAt > asOf independently from a leaky store and matches clean replay', async () => { - const cleanFixture = buildCeoShortsFixture({ poisonPostCutoff: false }); - const from = cleanFixture.allDates[0]!; - const postCutoffDate = cleanFixture.allDates[cleanFixture.allDates.length - 1]!; - const horizonSessions = 5; - - // Set asOf to noon UTC on session 100 while `to` extends past cutoff - const asOfSessionIdx = 100; - const asOfDate = cleanFixture.allDates[asOfSessionIdx]!; - const asOfIso = `${asOfDate}T12:00:00.000Z`; - const asOfMs = makeUtcMs(asOfDate, 12); - - // Clean replay store filters strictly by ts <= asOfMs && knownAt <= asOfMs - const cleanStore = createFakeStore({ - bars: cleanFixture.bars, - shortsTable: cleanFixture.shortsTable, - leaky: false, - }); - - // Leaky store injects two independent bar leaks + a delayed shorts row: - // (a) Closing bars on `asOfDate` stamped at 21:00 UTC (> noon asOf) with knownAt at 00:00 UTC (<= noon asOf) and poisoned close - // (b) Delayed bars on session 95 (ts <= noon asOf) with knownAt at 15:00 UTC on `asOfDate` (> noon asOf) and poisoned close - const delayedBarDate = cleanFixture.allDates[95]!; - const leakyBars: BarRecord[] = cleanFixture.bars.map(bar => { - if (bar.ts === makeUtcMs(asOfDate, 21)) { - return { - ...bar, - open: 666_666, - high: 666_666, - low: 666_666, - close: 666_666, - vwap: 666_666, - knownAt: makeUtcMs(asOfDate, 0), // earlier than noon asOf, while ts (21:00 UTC) > noon asOf - }; - } - return bar; - }); - // Also inject a bar with ts <= asOfMs but knownAt > asOfMs for listing 0 on session 95 (replace clean bar? No, add extra listing or poisoned bar on a date not in clean? Better: inject on a date after clean or with a listing that has a delayed knownAt!) - // Specifically: take a clean bar on session 95 for listing 0 and verify a delayed-knownAt poison bar on session 100-1 (where ts <= asOfMs and knownAt > asOfMs) is dropped. - // Even stronger: add a synthetic bar on `delayedBarDate` at 10:00 UTC (ts <= asOfMs) with knownAt = 15:00 UTC on `asOfDate` (> asOfMs) and poisoned close 555_555. - // If knownAt filter regresses, buildForwardReturnPanel will throw duplicate_bar (conflicting close on delayedBarDate)! - leakyBars.push({ - listingId: cleanFixture.listingIds[0]!, - ts: makeUtcMs(delayedBarDate, 10), - open: 555_555, - high: 555_555, - low: 555_555, - close: 555_555, - volume: 100, - vwap: 555_555, - knownAt: makeUtcMs(asOfDate, 15), // > noon asOf, while ts <= noon asOf - }); - - const leakyStore = createFakeStore({ - bars: leakyBars, - shortsTable: { - columns: cleanFixture.shortsTable.columns, - rows: [ - ...cleanFixture.shortsTable.rows, - { - listing_id: cleanFixture.listingIds[1]!, - report_date: cleanFixture.allDates[50]!, - known_at: makeUtcMs(asOfDate, 15), // > noon asOf - shares_short: 7_777_777, - net_change: 7_777_777, - pct_float: 0.77, - source: 'ceoShorts', - }, - ], - }, - leaky: true, - }); - - const cleanLedger = createFakeTrialLedger(); - const leakyLedger = createFakeTrialLedger(); - const args = { - listingIds: cleanFixture.listingIds, - from, - to: postCutoffDate, - asOf: asOfIso, - signal: { source: 'shorts', field: 'net_change' }, - horizonSessions, - universeMarket: 'CA_EQ', - horizonBucket: 'swing_1_10d', - }; - - const cleanRes = await callAnalyzeSignal({ - store: cleanStore.store, - ledger: cleanLedger.executor, - vaultCutoffTs: cleanFixture.vaultCutoffTs, - args, - }); - const leakyRes = await callAnalyzeSignal({ - store: leakyStore.store, - ledger: leakyLedger.executor, - vaultCutoffTs: cleanFixture.vaultCutoffTs, - args, - }); - - expect(cleanRes.isError).toBe(false); - expect(leakyRes.isError).toBe(false); - expect(leakyRes.text).toBe(cleanRes.text); - expect(leakyLedger.rows).toEqual(cleanLedger.rows); - - const payload = JSON.parse(leakyRes.text) as AnalyzeSignalResultPayload; - expect(payload.status).toBe('ok'); - expect(payload.clampedAsOf).toBe(false); - expect(payload.asOfMs).toBe(asOfMs); - if (payload.status === 'ok') { - const endIdx = cleanFixture.allDates.indexOf(payload.trial.sampleEnd); - const lastForwardEndpoint = cleanFixture.allDates[endIdx + horizonSessions]!; - // Closing bar on asOfDate (21:00 UTC) was excluded by ts > asOfMs, so last forward endpoint must precede asOfDate - expect(lastForwardEndpoint < asOfDate).toBe(true); - } - }); - - test('request wholly inside Vault holdout returns fixed VaultHoldoutFenceError with zero store and ledger calls', async () => { - const fixture = buildCeoShortsFixture(); - const fakeStore = createFakeStore({ - bars: fixture.bars, - shortsTable: fixture.shortsTable, - }); - const fakeLedger = createFakeTrialLedger(); - - const res = await callAnalyzeSignal({ - store: fakeStore.store, - ledger: fakeLedger.executor, - vaultCutoffTs: fixture.vaultCutoffTs, - args: { - listingIds: fixture.listingIds, - from: fixture.vaultCutoffDate, - to: fixture.allDates[fixture.allDates.length - 1]!, - signal: { source: 'shorts', field: 'net_change' }, - horizonSessions: 5, - universeMarket: 'CA_EQ', - horizonBucket: 'swing_1_10d', - }, - }); - - expect(res.isError).toBe(true); - expect(res.text).toBe( - 'VaultHoldoutFenceError: Requested range reaches or exceeds the Vault holdout cutoff.' - ); - expect(fakeStore.barsCalls).toHaveLength(0); - expect(fakeStore.shortsCalls).toHaveLength(0); - expect(fakeStore.universeCalls).toHaveLength(0); - expect(fakeLedger.insertCalls).toBe(0); - expect(fakeLedger.rows).toHaveLength(0); - }); - - test('named universe resolves strictly before study start and respects earlier/intraday asOf', async () => { - const fixture = buildCeoShortsFixture(); - const from = fixture.allDates[0]!; // 2022-09-01 - const to = fixture.allDates[fixture.allDates.length - 1]!; - - const fakeStore = createFakeStore({ - bars: fixture.bars, - shortsTable: fixture.shortsTable, - universeIds: [...fixture.listingIds].reverse(), - }); - const fakeLedger = createFakeTrialLedger(); - - const res = await callAnalyzeSignal({ - store: fakeStore.store, - ledger: fakeLedger.executor, - vaultCutoffTs: fixture.vaultCutoffTs, - args: { - universe: 'CA_EQ', - from, - to, - signal: { source: 'shorts', field: 'net_change' }, - horizonSessions: 5, - universeMarket: 'CA_EQ', - horizonBucket: 'swing_1_10d', - }, - }); - - expect(res.isError).toBe(false); - // Study starts 2022-09-01 -> universe must be resolved on 2022-08-31 (strictly before study start) - expect(fakeStore.universeCalls).toEqual([{ ref: 'CA_EQ', date: '2022-08-31' }]); - // Sorted listingIds passed to bars and shortsAsOf - expect(fakeStore.barsCalls[0]?.listingIds).toEqual(fixture.listingIds); - expect(fakeStore.shortsCalls[0]?.listingIds).toEqual(fixture.listingIds); - - // Earlier intraday asOf (2022-08-15T12:00:00Z) -> universe resolved on completed UTC date 2022-08-14 - const earlyStore = createFakeStore({ - bars: fixture.bars, - shortsTable: fixture.shortsTable, - universeIds: fixture.listingIds, - }); - const earlyLedger = createFakeTrialLedger(); - await callAnalyzeSignal({ - store: earlyStore.store, - ledger: earlyLedger.executor, - vaultCutoffTs: fixture.vaultCutoffTs, - args: { - universe: 'CA_EQ', - from, - to, - asOf: '2022-08-15T12:00:00Z', - signal: { source: 'shorts', field: 'net_change' }, - horizonSessions: 5, - universeMarket: 'CA_EQ', - horizonBucket: 'swing_1_10d', - }, - }); - expect(earlyStore.universeCalls).toEqual([{ ref: 'CA_EQ', date: '2022-08-14' }]); - }); - - test('insufficient-data cases (empty universe, empty panel, undersized panel, zero-variance series) return reason with zero ledger writes', async () => { - const cutoffDate = '2025-03-31'; - const cutoffTs = makeUtcMs(cutoffDate, 0); - - // 1. Empty resolved universe -> zero bars/shorts calls, zero ledger rows - const emptyUniStore = createFakeStore({ universeIds: [] }); - const emptyUniLedger = createFakeTrialLedger(); - const emptyUniRes = await callAnalyzeSignal({ - store: emptyUniStore.store, - ledger: emptyUniLedger.executor, - vaultCutoffTs: cutoffTs, - args: { - universe: 'CA_EQ', - from: '2025-01-01', - to: '2025-03-20', - signal: { source: 'shorts', field: 'net_change' }, - horizonSessions: 1, - universeMarket: 'CA_EQ', - horizonBucket: 'swing_1_10d', - }, - }); - expect(emptyUniRes.isError).toBe(false); - const emptyUniPayload = JSON.parse(emptyUniRes.text) as AnalyzeSignalResultPayload; - expect(emptyUniPayload.status).toBe('insufficient_data'); - if (emptyUniPayload.status === 'insufficient_data') { - expect(emptyUniPayload.reason).toBe('too_few_observations'); - } - expect(emptyUniStore.barsCalls).toHaveLength(0); - expect(emptyUniStore.shortsCalls).toHaveLength(0); - expect(emptyUniLedger.rows).toHaveLength(0); - - // 2. Empty panel (bars exist but no shorts signals) - const dates = makeBusinessDates('2025-01-02', 6); - const barsForSixDays: BarRecord[] = []; - for (let d = 0; d < dates.length; d += 1) { - const ts = makeUtcMs(dates[d]!, 21); - for (let id = 1; id <= 6; id += 1) { - barsForSixDays.push({ - listingId: id, - ts, - open: 100 + d, - high: 101 + d, - low: 99 + d, - close: 100 + d + id * 0.1, - volume: 1000, - vwap: 100 + d, - knownAt: ts, - }); - } - } - const emptyPanelStore = createFakeStore({ - bars: barsForSixDays, - shortsTable: { columns: SHORTS_COLUMNS, rows: [] }, - }); - const emptyPanelLedger = createFakeTrialLedger(); - const emptyPanelRes = await callAnalyzeSignal({ - store: emptyPanelStore.store, - ledger: emptyPanelLedger.executor, - vaultCutoffTs: cutoffTs, - args: { - listingIds: [1, 2, 3, 4, 5, 6], - from: dates[0]!, - to: dates[dates.length - 1]!, - signal: { source: 'shorts', field: 'net_change' }, - horizonSessions: 1, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }, - }); - expect(emptyPanelRes.isError).toBe(false); - const emptyPanelPayload = JSON.parse(emptyPanelRes.text) as AnalyzeSignalResultPayload; - expect(emptyPanelPayload.status).toBe('insufficient_data'); - if (emptyPanelPayload.status === 'insufficient_data') { - expect(emptyPanelPayload.reason).toBe('too_few_observations'); - } - expect(emptyPanelLedger.rows).toHaveLength(0); - - // 3. Undersized non-empty panel (only 1 date with forward return -> too_few_observations) - const twoDayBars = barsForSixDays.filter(b => b.ts <= makeUtcMs(dates[1]!, 21)); - const singleSignalRows: TableRow[] = [1, 2, 3, 4, 5, 6].map(id => ({ - listing_id: id, - report_date: dates[0]!, - known_at: makeUtcMs(dates[0]!, 10), - shares_short: 1000 * id, - net_change: 100 * id, - pct_float: 0.01 * id, - source: 'ceoShorts', - })); - const undersizedStore = createFakeStore({ - bars: twoDayBars, - shortsTable: { columns: SHORTS_COLUMNS, rows: singleSignalRows }, - }); - const undersizedLedger = createFakeTrialLedger(); - const undersizedRes = await callAnalyzeSignal({ - store: undersizedStore.store, - ledger: undersizedLedger.executor, - vaultCutoffTs: cutoffTs, - args: { - listingIds: [1, 2, 3, 4, 5, 6], - from: dates[0]!, - to: dates[1]!, - signal: { source: 'shorts', field: 'net_change' }, - horizonSessions: 1, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }, - }); - expect(undersizedRes.isError).toBe(false); - const undersizedPayload = JSON.parse(undersizedRes.text) as AnalyzeSignalResultPayload; - expect(undersizedPayload.status).toBe('insufficient_data'); - if (undersizedPayload.status === 'insufficient_data') { - expect(undersizedPayload.reason).toBe('too_few_observations'); - } - expect(undersizedLedger.rows).toHaveLength(0); - - // 4. Zero-variance rank_ic series (identical strictly monotone rank ordering every day -> rank_ic = 1.0 on every date) - const monotoneBars: BarRecord[] = []; - for (let d = 0; d < dates.length; d += 1) { - const ts = makeUtcMs(dates[d]!, 21); - for (let id = 1; id <= 6; id += 1) { - const close = 100 * Math.pow(1 + 0.01 * id, d); - monotoneBars.push({ - listingId: id, - ts, - open: close, - high: close, - low: close, - close, - volume: 1000, - vwap: close, - knownAt: ts, - }); - } - } - const zeroVarStore = createFakeStore({ - bars: monotoneBars, - shortsTable: { columns: SHORTS_COLUMNS, rows: singleSignalRows }, - }); - const zeroVarLedger = createFakeTrialLedger(); - const zeroVarRes = await callAnalyzeSignal({ - store: zeroVarStore.store, - ledger: zeroVarLedger.executor, - vaultCutoffTs: cutoffTs, - args: { - listingIds: [1, 2, 3, 4, 5, 6], - from: dates[0]!, - to: dates[dates.length - 1]!, - signal: { source: 'shorts', field: 'net_change' }, - horizonSessions: 1, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }, - }); - expect(zeroVarRes.isError).toBe(false); - const zeroVarPayload = JSON.parse(zeroVarRes.text) as AnalyzeSignalResultPayload; - expect(zeroVarPayload.status).toBe('insufficient_data'); - if (zeroVarPayload.status === 'insufficient_data') { - expect(zeroVarPayload.reason).toBe('zero_variance_series'); - } - expect(zeroVarLedger.rows).toHaveLength(0); - }); - - test('strict schema rejects forbidden keys, unknown keys, bad selectors, invalid dates/UUIDs, INT32/limit/horizon violations with zero store or ledger calls', async () => { - const cutoffTs = makeUtcMs('2025-03-31', 0); - const validBase = { - listingIds: [101, 102], - from: '2025-01-02', - to: '2025-03-20', - signal: { source: 'shorts', field: 'net_change' }, - horizonSessions: 5, - universeMarket: 'CA_EQ', - horizonBucket: 'swing_1_10d', - }; - - const invalidCases: readonly [string, Record][] = [ - ['scope vault_evaluation_only', { ...validBase, scope: 'vault_evaluation_only' }], - ['scope vault_fenced', { ...validBase, scope: 'vault_fenced' }], - ['vault_evaluation_only flag', { ...validBase, vault_evaluation_only: true }], - ['principalId override', { ...validBase, principalId: 'operator' }], - ['vaultCutoffDate override', { ...validBase, vaultCutoffDate: '2026-01-01' }], - ['unknown top-level key', { ...validBase, extraFlag: true }], - [ - 'unknown nested signal key', - { ...validBase, signal: { source: 'shorts', field: 'net_change', extra: 1 } }, - ], - ['both listingIds and universe', { ...validBase, universe: 'CA_EQ' }], - [ - 'neither listingIds nor universe', - { - from: validBase.from, - to: validBase.to, - signal: validBase.signal, - horizonSessions: 5, - universeMarket: 'CA_EQ', - horizonBucket: 'swing_1_10d', - }, - ], - ['unknown signal.source', { ...validBase, signal: { source: 'fundamentals', field: 'net_change' } }], - ['unknown signal.field', { ...validBase, signal: { source: 'shorts', field: 'unknown_col' } }], - ['invalid calendar date from', { ...validBase, from: '2025-02-30' }], - ['invalid string date to', { ...validBase, to: 'not-a-date' }], - ['naive timestamp without offset in asOf', { ...validBase, asOf: '2025-02-01T12:00:00' }], - ['invalid campaignId UUID', { ...validBase, campaignId: 'not-a-uuid' }], - ['invalid hypothesisId UUID', { ...validBase, hypothesisId: '12345' }], - ['INT32 overflow listingId', { ...validBase, listingIds: [2_147_483_648] }], - ['INT32 underflow listingId', { ...validBase, listingIds: [-2_147_483_649] }], - ['non-integer listingId', { ...validBase, listingIds: [101.5] }], - ['empty listingIds', { ...validBase, listingIds: [] }], - [ - 'more than 500 explicit listingIds', - { - ...validBase, - listingIds: Array.from({ length: ANALYZE_SIGNAL_MAX_LISTING_IDS + 1 }, (_, i) => i + 1), - }, - ], - ['horizonSessions 0', { ...validBase, horizonSessions: 0 }], - ['horizonSessions negative', { ...validBase, horizonSessions: -3 }], - [ - 'horizonSessions above max', - { ...validBase, horizonSessions: ANALYZE_SIGNAL_MAX_HORIZON_SESSIONS + 1 }, - ], - ['horizonSessions float', { ...validBase, horizonSessions: 2.5 }], - ['negative maxSignalAgeSessions', { ...validBase, maxSignalAgeSessions: -1 }], - ['mismatched horizonBucket intraday for 5d daily horizon', { ...validBase, horizonSessions: 5, horizonBucket: 'intraday' }], - [ - 'mismatched horizonBucket position_10d_plus for 5d daily horizon', - { ...validBase, horizonSessions: 5, horizonBucket: 'position_10d_plus' }, - ], - [ - 'mismatched horizonBucket swing_1_10d for 11d daily horizon', - { ...validBase, horizonSessions: 11, horizonBucket: 'swing_1_10d' }, - ], - [ - 'mismatched horizonBucket intraday for 15d daily horizon', - { ...validBase, horizonSessions: 15, horizonBucket: 'intraday' }, - ], - [ - 'named universe CA_EQ with mismatched universeMarket FX', - { - from: validBase.from, - to: validBase.to, - signal: validBase.signal, - horizonSessions: 5, - universe: 'CA_EQ', - universeMarket: 'FX', - horizonBucket: 'swing_1_10d', - }, - ], - [ - 'named universe CA_EQ with mismatched universeMarket US_EQ', - { - from: validBase.from, - to: validBase.to, - signal: validBase.signal, - horizonSessions: 5, - universe: 'CA_EQ', - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }, - ], - [ - 'named universe US_CA_EQ with mismatched universeMarket US_EQ', - { - from: validBase.from, - to: validBase.to, - signal: validBase.signal, - horizonSessions: 5, - universe: 'US_CA_EQ', - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }, - ], - ['shorts study with FX universeMarket and listingIds', { ...validBase, universeMarket: 'FX' }], - ]; - - for (const [_label, args] of invalidCases) { - const fakeStore = createFakeStore(); - const fakeLedger = createFakeTrialLedger(); - const res = await callAnalyzeSignal({ - store: fakeStore.store, - ledger: fakeLedger.executor, - vaultCutoffTs: cutoffTs, - args, - }); - - expect(res.isError).toBe(true); - expect(res.text).toContain('Invalid arguments for tool "analyze_signal":'); - expect(fakeStore.barsCalls).toHaveLength(0); - expect(fakeStore.shortsCalls).toHaveLength(0); - expect(fakeStore.universeCalls).toHaveLength(0); - expect(fakeLedger.insertCalls).toBe(0); - } - - // Raw JSON own __proto__ key rejected with zero store or ledger calls - const protoStore = createFakeStore(); - const protoLedger = createFakeTrialLedger(); - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createAnalyzeSignalTool({ - store: protoStore.store, - ledger: protoLedger.executor, - vaultContext: { vaultCutoffTs: cutoffTs }, - principalId: AGENT_PRINCIPAL, - }), - ], - }); - const rawProto = - '{"jsonrpc":"2.0","id":"proto-1","method":"tools/call","params":{"name":"analyze_signal","arguments":{"listingIds":[101],"from":"2025-01-02","to":"2025-03-20","signal":{"source":"shorts","field":"net_change"},"horizonSessions":5,"universeMarket":"CA_EQ","horizonBucket":"swing_1_10d","__proto__":{"principalId":"operator"}}}}'; - const protoResp = JSON.parse((await server.handleMessage(rawProto)) as string) as { - result: { isError?: boolean; content: { type: string; text: string }[] }; - }; - expect(protoResp.result.isError).toBe(true); - expect(protoStore.barsCalls).toHaveLength(0); - expect(protoLedger.insertCalls).toBe(0); - }); - - test('sanitizes store, panel, ledger insert, and DSR read failures without leaking SQL, paths, or connection URIs', async () => { - const fixture = buildCeoShortsFixture(); - const from = fixture.allDates[0]!; - const to = fixture.allDates[fixture.allDates.length - 1]!; - const validArgs = { - listingIds: fixture.listingIds, - from, - to, - signal: { source: 'shorts', field: 'net_change' }, - horizonSessions: 5, - universeMarket: 'CA_EQ', - horizonBucket: 'swing_1_10d', - }; - - const sensitiveDetail = - 'SELECT * FROM trial_ledger WHERE secret=1 at /mnt/data/stockbot/curated/shorts/part.parquet via postgres://user:pass@host:5432/trading_bot'; - - function assertNoLeak(rawResponse: string): void { - expect(rawResponse).not.toContain('SELECT * FROM trial_ledger'); - expect(rawResponse).not.toContain('/mnt/data/stockbot'); - expect(rawResponse).not.toContain('part.parquet'); - expect(rawResponse).not.toContain('postgres://user:pass@host'); - } - - // 1. Store domain & unexpected errors - const storeErrors: readonly [Error, string][] = [ - [new VaultScopeNotAuthorizedError(sensitiveDetail), 'VaultScopeNotAuthorizedError'], - [new MarketDataStoreValidationError(sensitiveDetail, 'curatedRoot'), 'MarketDataStoreValidationError'], - [new MarketDataStoreNotImplementedError('shortsAsOf', sensitiveDetail), 'MarketDataStoreNotImplementedError'], - [new Error(sensitiveDetail), 'Error: Tool execution failed.'], - ]; - for (const [err, expectedSnippet] of storeErrors) { - const store = createFakeStore({ shortsError: err, bars: fixture.bars }); - const ledger = createFakeTrialLedger(); - const res = await callAnalyzeSignal({ - store: store.store, - ledger: ledger.executor, - vaultCutoffTs: fixture.vaultCutoffTs, - args: validArgs, - }); - expect(res.isError).toBe(true); - expect(res.text).toContain(expectedSnippet); - assertNoLeak(res.rawResponse); - expect(ledger.rows).toHaveLength(0); - } - - // 2. Malformed shorts table -> SignalPanelError mapped cleanly - const badTableStore = createFakeStore({ - bars: fixture.bars, - shortsTable: { columns: ['listing_id'], rows: [] }, - }); - const badTableLedger = createFakeTrialLedger(); - const badTableRes = await callAnalyzeSignal({ - store: badTableStore.store, - ledger: badTableLedger.executor, - vaultCutoffTs: fixture.vaultCutoffTs, - args: validArgs, - }); - expect(badTableRes.isError).toBe(true); - expect(badTableRes.text).toContain('SignalPanelError:'); - expect(badTableLedger.rows).toHaveLength(0); - - // 3. Ledger INSERT failure -> isError: true, no leak, zero trial rows written - const insertFailStore = createFakeStore({ - bars: fixture.bars, - shortsTable: fixture.shortsTable, - }); - const insertFailLedger = createFakeTrialLedger({ - insertError: new Error(sensitiveDetail), - }); - const insertFailRes = await callAnalyzeSignal({ - store: insertFailStore.store, - ledger: insertFailLedger.executor, - vaultCutoffTs: fixture.vaultCutoffTs, - args: validArgs, - }); - expect(insertFailRes.isError).toBe(true); - expect(insertFailRes.text).toBe('Error: Tool execution failed.'); - assertNoLeak(insertFailRes.rawResponse); - expect(insertFailLedger.insertCalls).toBe(1); - expect(insertFailLedger.rows).toHaveLength(0); - - // 4. DSR read failure after INSERT -> isError: true, fixed SignalStudyError, no leak, exactly 1 insert (never retried) - const dsrFailStore = createFakeStore({ - bars: fixture.bars, - shortsTable: fixture.shortsTable, - }); - const dsrFailLedger = createFakeTrialLedger({ - dsrReadError: new Error(sensitiveDetail), - }); - const dsrFailRes = await callAnalyzeSignal({ - store: dsrFailStore.store, - ledger: dsrFailLedger.executor, - vaultCutoffTs: fixture.vaultCutoffTs, - args: validArgs, - }); - expect(dsrFailRes.isError).toBe(true); - expect(dsrFailRes.text).toBe( - 'SignalStudyError: Trial was recorded, but cluster deflated Sharpe evaluation failed.' - ); - assertNoLeak(dsrFailRes.rawResponse); - expect(dsrFailLedger.insertCalls).toBe(1); - expect(dsrFailLedger.rows).toHaveLength(1); - }); -}); - -interface FundamentalsPitFixtureRow { - readonly listing_id: number; - readonly effective_known_at: number; - readonly known_at_source: string; - readonly has_estimated_lag: boolean; - readonly period_end: string; - readonly fiscal_period: string; - readonly currency: string; - readonly period_known_at: number; - readonly revenue: number | null; - readonly net_income: number | null; - readonly operating_cash_flow: number | null; - readonly total_assets: number | null; - readonly total_equity: number | null; - readonly shares_outstanding: number | null; - readonly ttm_revenue: number | null; - readonly ttm_net_income: number | null; - readonly ttm_operating_cash_flow: number | null; - readonly ttm_period_end: string | null; - readonly ttm_currency: string | null; - readonly ttm_has_estimated_lag: boolean; -} - -const FUNDAMENTALS_TTM_FIELDS = new Set([ - 'ttm_revenue', - 'ttm_net_income', - 'ttm_operating_cash_flow', -]); - -function queryFundamentalsFixtureRows( - rows: readonly FundamentalsPitFixtureRow[], - q: FundamentalsAsOfQuery -): Table { - const idSet = new Set(q.listingIds); - const asOfMs = Date.parse(q.asOf.length === 10 ? `${q.asOf}T23:59:59.999Z` : q.asOf); - const allowEstimatedLag = q.allowEstimatedLag ?? false; - - const latestByListing = new Map(); - for (const row of rows) { - if (!idSet.has(row.listing_id) || row.effective_known_at > asOfMs) { - continue; - } - const prev = latestByListing.get(row.listing_id); - if (prev === undefined || row.effective_known_at > prev.effective_known_at) { - latestByListing.set(row.listing_id, row); - } - } - - const hasTtm = q.fields.some(f => FUNDAMENTALS_TTM_FIELDS.has(f)); - const columns: string[] = [ - 'listing_id', - 'effective_known_at', - 'known_at_source', - 'has_estimated_lag', - 'period_end', - 'fiscal_period', - 'currency', - 'period_known_at', - ...q.fields, - ...(hasTtm ? ['ttm_period_end', 'ttm_currency', 'ttm_has_estimated_lag'] : []), - ]; - - const outRows: TableRow[] = []; - const sortedIds = [...latestByListing.keys()].sort((a, b) => a - b); - for (const lid of sortedIds) { - const selected = latestByListing.get(lid)!; - if (!allowEstimatedLag && selected.has_estimated_lag) { - continue; - } - const projected: Record = { - listing_id: selected.listing_id, - effective_known_at: selected.effective_known_at, - known_at_source: selected.known_at_source, - has_estimated_lag: selected.has_estimated_lag, - period_end: selected.period_end, - fiscal_period: selected.fiscal_period, - currency: selected.currency, - period_known_at: selected.period_known_at, - }; - for (const field of q.fields) { - const val = selected[field as keyof FundamentalsPitFixtureRow] as number | null; - if (FUNDAMENTALS_TTM_FIELDS.has(field)) { - projected[field] = allowEstimatedLag || !selected.ttm_has_estimated_lag ? val : null; - } else { - projected[field] = val; - } - } - if (hasTtm) { - projected.ttm_period_end = - allowEstimatedLag || !selected.ttm_has_estimated_lag ? selected.ttm_period_end : null; - projected.ttm_currency = - allowEstimatedLag || !selected.ttm_has_estimated_lag ? selected.ttm_currency : null; - projected.ttm_has_estimated_lag = selected.ttm_has_estimated_lag; - } - outRows.push(projected); - } - - return { columns, rows: outRows }; -} - -function makeFundamentalsRow(params: { - listingId: number; - effectiveKnownAt: number; - periodEnd: string; - fiscalPeriod: string; - revenue: number; - ttmRevenue: number; - hasEstimatedLag?: boolean; - ttmHasEstimatedLag?: boolean; -}): FundamentalsPitFixtureRow { - const hasEstimatedLag = params.hasEstimatedLag ?? false; - const ttmHasEstimatedLag = params.ttmHasEstimatedLag ?? false; - return { - listing_id: params.listingId, - effective_known_at: params.effectiveKnownAt, - known_at_source: hasEstimatedLag ? 'estimated_lag' : 'sec_edgar_filing', - has_estimated_lag: hasEstimatedLag, - period_end: params.periodEnd, - fiscal_period: params.fiscalPeriod, - currency: 'USD', - period_known_at: params.effectiveKnownAt, - revenue: params.revenue, - net_income: Number((params.revenue * 0.15).toFixed(2)), - operating_cash_flow: Number((params.revenue * 0.2).toFixed(2)), - total_assets: Number((params.revenue * 4.0).toFixed(2)), - total_equity: Number((params.revenue * 1.8).toFixed(2)), - shares_outstanding: 10_000_000, - ttm_revenue: params.ttmRevenue, - ttm_net_income: Number((params.ttmRevenue * 0.15).toFixed(2)), - ttm_operating_cash_flow: Number((params.ttmRevenue * 0.2).toFixed(2)), - ttm_period_end: params.periodEnd, - ttm_currency: 'USD', - ttm_has_estimated_lag: ttmHasEstimatedLag, - }; -} - -// Seeded fundamentals study fixture metadata (pinned for reproducibility): -// - Dataset ID: `synthetic:mcp-analyze-signal-fundamentals:seed-20261202:v1` -// - Tool version: `mcp:analyze_signal:v1` -// - Seed: `20261202` (Mulberry32 PRNG) -// - Universe: 12 synthetic US equity listings (`70001..70012`, USD, 21:00 UTC close) -// - Pre-Vault window: 2023-01-02..2023-06-30 (130 business sessions), Vault cutoff: 2023-07-03T00:00:00.000Z -// - Adjustment: `raw`, horizon: `5` sessions, modeled execution/transaction costs: `0` -// - Ownership: Quant research owns evidence; Director owns adoption. -const FUNDAMENTALS_FIXTURE_SEED = 20261202; - -function buildFundamentalsStudyFixture(): { - readonly listingIds: number[]; - readonly allDates: string[]; - readonly preCutoffSessions: number; - readonly vaultCutoffDate: string; - readonly vaultCutoffTs: number; - readonly bars: BarRecord[]; - readonly fundamentalsRows: FundamentalsPitFixtureRow[]; -} { - const rand = createSeededRng(FUNDAMENTALS_FIXTURE_SEED); - const listingCount = 12; - const preCutoffSessions = 130; - const postCutoffSessions = 10; - const allDates = makeBusinessDates('2023-01-02', preCutoffSessions + postCutoffSessions); - const vaultCutoffDate = allDates[preCutoffSessions]!; - const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0); - const listingIds = Array.from({ length: listingCount }, (_, i) => 70_001 + i); - - const fundamentalsRows: FundamentalsPitFixtureRow[] = []; - // Monthly PIT releases across 6 pre-cutoff months + 1 post-cutoff release - const releaseDates = [ - { date: '2023-01-10', periodEnd: '2022-12-31', fiscalPeriod: 'Q4' }, - { date: '2023-02-15', periodEnd: '2022-12-31', fiscalPeriod: 'Q4' }, - { date: '2023-04-18', periodEnd: '2023-03-31', fiscalPeriod: 'Q1' }, - { date: '2023-05-18', periodEnd: '2023-03-31', fiscalPeriod: 'Q1' }, - { date: vaultCutoffDate, periodEnd: '2023-06-30', fiscalPeriod: 'Q2' }, - ]; - - const activeScore = new Float64Array(listingCount); - for (let rIdx = 0; rIdx < releaseDates.length; rIdx += 1) { - const rel = releaseDates[rIdx]!; - const knownAt = makeUtcMs(rel.date, 13); // 08:00 ET pre-close - for (let l = 0; l < listingCount; l += 1) { - const rev = 100 + l * 25 + rIdx * 10 + Math.round((rand() * 2 - 1) * 40); - const ttm = rev * 4 + (l % 3) * 15; - fundamentalsRows.push( - makeFundamentalsRow({ - listingId: listingIds[l]!, - effectiveKnownAt: knownAt, - periodEnd: rel.periodEnd, - fiscalPeriod: rel.fiscalPeriod, - revenue: rev, - ttmRevenue: ttm, - }) - ); - } - } - - const prices = new Float64Array(listingCount); - for (let l = 0; l < listingCount; l += 1) { - prices[l] = 20 + l * 3; - } - - const bars: BarRecord[] = []; - for (let t = 0; t < allDates.length; t += 1) { - const date = allDates[t]!; - const closeTs = makeUtcMs(date, 21); - for (let l = 0; l < listingCount; l += 1) { - activeScore[l] = (l - listingCount / 2) / listingCount; - const dailyRet = 0.002 * activeScore[l]! + (rand() * 2 - 1) * 0.01; - prices[l] = Math.max(1.0, prices[l]! * (1 + dailyRet)); - const close = Number(prices[l]!.toFixed(6)); - bars.push({ - listingId: listingIds[l]!, - ts: closeTs, - open: close, - high: close, - low: close, - close, - volume: 80_000, - vwap: close, - knownAt: closeTs, - }); - } - } - - return { - listingIds, - allDates, - preCutoffSessions, - vaultCutoffDate, - vaultCutoffTs, - bars, - fundamentalsRows, - }; -} - -describe('MCP analyze_signal tool — fundamentals source', () => { - test('tools/list advertises strict signal discriminated branches and rejects invalid fundamentals inputs with zero store/ledger calls', async () => { - const cutoffTs = makeUtcMs('2025-03-31', 0); - const fakeStore = createFakeStore(); - const fakeLedger = createFakeTrialLedger(); - - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createAnalyzeSignalTool({ - store: fakeStore.store, - ledger: fakeLedger.executor, - vaultContext: { vaultCutoffTs: cutoffTs }, - principalId: AGENT_PRINCIPAL, - }), - ], - }); - - const listRaw = await server.handleMessage( - JSON.stringify({ jsonrpc: '2.0', id: 'list-fund', method: 'tools/list' }) - ); - const listParsed = JSON.parse(listRaw as string) as { - result: { - tools: { - name: string; - description: string; - inputSchema: { - properties: { - signal: { - type: string; - additionalProperties: boolean; - properties: Record; - anyOf: { - additionalProperties: boolean; - properties: Record; - }[]; - }; - }; - }; - }[]; - }; - }; - - const tool = listParsed.result.tools[0]!; - expect(tool.description).toContain('fundamentals'); - expect(tool.description).toContain('short-interest'); - - const signalSchema = tool.inputSchema.properties.signal; - expect(signalSchema.type).toBe('object'); - expect(signalSchema.additionalProperties).toBe(false); - expect(Object.keys(signalSchema.properties).sort()).toEqual([ - 'allowEstimatedLag', - 'field', - 'source', - ]); - expect(signalSchema.anyOf).toHaveLength(2); - expect(signalSchema.anyOf[0]?.additionalProperties).toBe(false); - expect(signalSchema.anyOf[0]?.properties.source?.const).toBe('shorts'); - expect(signalSchema.anyOf[1]?.additionalProperties).toBe(false); - expect(signalSchema.anyOf[1]?.properties.source?.const).toBe('fundamentals'); - expect(signalSchema.anyOf[1]?.properties.field?.enum).toEqual([...FUNDAMENTALS_PIT_VALUE_FIELDS]); - expect(signalSchema.anyOf[1]?.properties.allowEstimatedLag?.default).toBe(false); - - const validBase = { - listingIds: [70_001, 70_002], - from: '2023-01-02', - to: '2023-06-30', - signal: { source: 'fundamentals', field: 'ttm_revenue' }, - horizonSessions: 5, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }; - - const invalidCases: readonly [string, Record][] = [ - ['unknown fundamentals field', { ...validBase, signal: { source: 'fundamentals', field: 'ebitda_fake' } }], - ['shorts field on fundamentals source', { ...validBase, signal: { source: 'fundamentals', field: 'net_change' } }], - ['fundamentals field on shorts source', { ...validBase, signal: { source: 'shorts', field: 'ttm_revenue' } }], - ['unknown signal.source', { ...validBase, signal: { source: 'macro', field: 'ttm_revenue' } }], - [ - 'unknown nested key in fundamentals signal', - { ...validBase, signal: { source: 'fundamentals', field: 'ttm_revenue', extraKey: true } }, - ], - [ - 'allowEstimatedLag on shorts source', - { ...validBase, signal: { source: 'shorts', field: 'net_change', allowEstimatedLag: false } }, - ], - [ - 'non-boolean allowEstimatedLag string', - { ...validBase, signal: { source: 'fundamentals', field: 'ttm_revenue', allowEstimatedLag: 'true' } }, - ], - [ - 'non-boolean allowEstimatedLag number', - { ...validBase, signal: { source: 'fundamentals', field: 'ttm_revenue', allowEstimatedLag: 1 } }, - ], - ['fundamentals study with FX universeMarket', { ...validBase, universeMarket: 'FX' }], - ]; - - for (const [_label, args] of invalidCases) { - const store = createFakeStore(); - const ledger = createFakeTrialLedger(); - const res = await callAnalyzeSignal({ - store: store.store, - ledger: ledger.executor, - vaultCutoffTs: cutoffTs, - args, - }); - expect(res.isError).toBe(true); - expect(res.text).toContain('Invalid arguments for tool "analyze_signal":'); - expect(store.barsCalls).toHaveLength(0); - expect(store.shortsCalls).toHaveLength(0); - expect(store.fundamentalsCalls).toHaveLength(0); - expect(store.universeCalls).toHaveLength(0); - expect(ledger.insertCalls).toBe(0); - } - }); - - test('executes fundamentals study, records canonical fundamentals expressionHash, forwards allowEstimatedLag verbatim, and preserves identity on append-only retry', async () => { - const fixture = buildFundamentalsStudyFixture(); - const from = fixture.allDates[0]!; - const to = fixture.allDates[fixture.preCutoffSessions - 1]!; - - const store = createFakeStore({ - bars: fixture.bars, - fundamentalsResolver: q => queryFundamentalsFixtureRows(fixture.fundamentalsRows, q), - }); - const sharedLedger = createFakeTrialLedger(); - - const baseArgs = { - listingIds: fixture.listingIds, - from, - to, - signal: { source: 'fundamentals', field: 'ttm_revenue' }, - horizonSessions: 5, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - campaignId: CAMPAIGN_UUID, - hypothesisId: HYPOTHESIS_UUID, - }; - - const res1 = await callAnalyzeSignal({ - store: store.store, - ledger: sharedLedger.executor, - vaultCutoffTs: fixture.vaultCutoffTs, - principalId: AGENT_PRINCIPAL, - args: baseArgs, - }); - expect(res1.isError).toBe(false); - const payload1 = JSON.parse(res1.text) as AnalyzeSignalResultPayload; - expect(payload1.status).toBe('ok'); - if (payload1.status !== 'ok') { - return; - } - - expect(payload1.signal).toEqual({ - source: 'fundamentals', - field: 'ttm_revenue', - allowEstimatedLag: false, - }); - expect(sharedLedger.rows).toHaveLength(1); - expect(sharedLedger.rows[0]?.stage).toBe('signal_ic'); - expect(sharedLedger.rows[0]?.principal_id).toBe(AGENT_PRINCIPAL); - - // Verify canonical expression prefix `mcp:analyze_signal:v1:fundamentals:` via canonicalExpressionHash - const expectedHash = canonicalExpressionHash({ - expression: 'mcp:analyze_signal:v1:fundamentals:ttm_revenue', - params: { - version: 1, - signalSource: 'fundamentals', - signalField: 'ttm_revenue', - allowEstimatedLag: false, - horizonSessions: 5, - maxSignalAgeSessions: null, - adjustment: 'raw', - ledgerSeries: 'rank_ic', - effectiveFrom: payload1.effectiveFrom, - effectiveTo: payload1.effectiveTo, - effectiveAsOf: payload1.effectiveAsOf, - }, - universe: { - kind: 'listingIds', - listingIds: fixture.listingIds, - }, - horizon: '5d', - sampleStart: payload1.trial.sampleStart, - sampleEnd: payload1.trial.sampleEnd, - }); - expect(payload1.trial.expressionHash).toBe(expectedHash); - expect(sharedLedger.rows[0]?.expression_hash).toBe(expectedHash); - - // Default allowEstimatedLag === false forwarded verbatim to every fundamentalsAsOf call - expect(store.fundamentalsCalls.length).toBeGreaterThan(0); - expect(store.shortsCalls).toHaveLength(0); - for (const call of store.fundamentalsCalls) { - expect(call.fields).toEqual(['ttm_revenue']); - expect(call.allowEstimatedLag).toBe(false); - } - - // Re-running identical request against the SAME ledger appends under append-only rules with one distinct expression_hash - const res2 = await callAnalyzeSignal({ - store: store.store, - ledger: sharedLedger.executor, - vaultCutoffTs: fixture.vaultCutoffTs, - principalId: AGENT_PRINCIPAL, - args: baseArgs, - }); - expect(res2.isError).toBe(false); - const payload2 = JSON.parse(res2.text) as AnalyzeSignalResultPayload; - expect(payload2.status).toBe('ok'); - if (payload2.status !== 'ok') { - return; - } - expect(payload2.trial.expressionHash).toBe(payload1.trial.expressionHash); - expect(new Set(sharedLedger.rows.map(r => r.expression_hash)).size).toBe(1); - - // Explicit allowEstimatedLag: false and reordered/duplicated listingIds preserve identity - const explicitFalseStore = createFakeStore({ - bars: fixture.bars, - fundamentalsResolver: q => queryFundamentalsFixtureRows(fixture.fundamentalsRows, q), - }); - const explicitFalseLedger = createFakeTrialLedger(); - const reorderedIds = [...fixture.listingIds].reverse(); - reorderedIds.push(fixture.listingIds[0]!, fixture.listingIds[2]!); - const resExplicitFalse = await callAnalyzeSignal({ - store: explicitFalseStore.store, - ledger: explicitFalseLedger.executor, - vaultCutoffTs: fixture.vaultCutoffTs, - args: { - ...baseArgs, - listingIds: reorderedIds, - signal: { source: 'fundamentals', field: 'ttm_revenue', allowEstimatedLag: false }, - }, - }); - const payloadExplicitFalse = JSON.parse(resExplicitFalse.text) as AnalyzeSignalResultPayload; - expect(payloadExplicitFalse.status).toBe('ok'); - if (payloadExplicitFalse.status === 'ok') { - expect(payloadExplicitFalse.trial.expressionHash).toBe(payload1.trial.expressionHash); - } - expect(explicitFalseStore.fundamentalsCalls.every(c => c.allowEstimatedLag === false)).toBe(true); - - // allowEstimatedLag: true forwards true verbatim and changes expressionHash - const lagTrueStore = createFakeStore({ - bars: fixture.bars, - fundamentalsResolver: q => queryFundamentalsFixtureRows(fixture.fundamentalsRows, q), - }); - const lagTrueLedger = createFakeTrialLedger(); - const resLagTrue = await callAnalyzeSignal({ - store: lagTrueStore.store, - ledger: lagTrueLedger.executor, - vaultCutoffTs: fixture.vaultCutoffTs, - args: { - ...baseArgs, - signal: { source: 'fundamentals', field: 'ttm_revenue', allowEstimatedLag: true }, - }, - }); - const payloadLagTrue = JSON.parse(resLagTrue.text) as AnalyzeSignalResultPayload; - expect(payloadLagTrue.status).toBe('ok'); - if (payloadLagTrue.status === 'ok') { - expect(payloadLagTrue.signal).toEqual({ - source: 'fundamentals', - field: 'ttm_revenue', - allowEstimatedLag: true, - }); - expect(payloadLagTrue.trial.expressionHash).not.toBe(payload1.trial.expressionHash); - } - expect(lagTrueStore.fundamentalsCalls.every(c => c.allowEstimatedLag === true)).toBe(true); - - // Different field changes expressionHash - const otherFieldStore = createFakeStore({ - bars: fixture.bars, - fundamentalsResolver: q => queryFundamentalsFixtureRows(fixture.fundamentalsRows, q), - }); - const otherFieldLedger = createFakeTrialLedger(); - const resOtherField = await callAnalyzeSignal({ - store: otherFieldStore.store, - ledger: otherFieldLedger.executor, - vaultCutoffTs: fixture.vaultCutoffTs, - args: { - ...baseArgs, - signal: { source: 'fundamentals', field: 'revenue' }, - }, - }); - const payloadOtherField = JSON.parse(resOtherField.text) as AnalyzeSignalResultPayload; - expect(payloadOtherField.status).toBe('ok'); - if (payloadOtherField.status === 'ok') { - expect(payloadOtherField.trial.expressionHash).not.toBe(payload1.trial.expressionHash); - } - - // Shorts study over the same window/listings produces a distinct expressionHash - const shortsRows: TableRow[] = fixture.listingIds.map((lid, i) => ({ - listing_id: lid, - report_date: from, - known_at: makeUtcMs(from, 12), - shares_short: 100_000 + i * 5_000, - net_change: (i - 5) * 1_000, - pct_float: 0.03 + i * 0.005, - source: 'ceoShorts', - })); - const shortsStore = createFakeStore({ - bars: fixture.bars, - shortsTable: { columns: SHORTS_COLUMNS, rows: shortsRows }, - }); - const shortsLedger = createFakeTrialLedger(); - const resShorts = await callAnalyzeSignal({ - store: shortsStore.store, - ledger: shortsLedger.executor, - vaultCutoffTs: fixture.vaultCutoffTs, - args: { - ...baseArgs, - signal: { source: 'shorts', field: 'net_change' }, - }, - }); - const payloadShorts = JSON.parse(resShorts.text) as AnalyzeSignalResultPayload; - expect(payloadShorts.status).toBe('ok'); - if (payloadShorts.status === 'ok') { - expect(payloadShorts.trial.expressionHash).not.toBe(payload1.trial.expressionHash); - } - }); - - test('queries month-end snapshots in ascending order from unsorted bars, preserves earlier explicit asOf, enforces 120-snapshot cap, and handles empty bars', async () => { - // 1. Unsorted bars spanning 3 UTC months (2 full + 1 partial final month) with earlier intraday asOf - const janDates = ['2023-01-10', '2023-01-31']; - const febDates = ['2023-02-14', '2023-02-28']; - const marDates = ['2023-03-08', '2023-03-15']; - const unsortedDates = [...marDates, ...janDates, ...febDates].reverse(); - const bars: BarRecord[] = []; - for (const date of unsortedDates) { - const ts = makeUtcMs(date, 21); - for (const lid of [101, 102]) { - bars.push({ - listingId: lid, - ts, - open: 10, - high: 10, - low: 10, - close: 10, - volume: 100, - vwap: 10, - knownAt: ts, - }); - } - } - - const cutoffTs = makeUtcMs('2023-04-01', 0); - const preWindowKnownAt = makeUtcMs('2022-12-15', 13); - const storeOrder = createFakeStore({ - bars, - fundamentalsResolver: q => ({ - columns: ['listing_id', 'effective_known_at', 'revenue'], - rows: q.listingIds.map(lid => ({ - listing_id: lid, - effective_known_at: preWindowKnownAt, - revenue: 100, - })), - }), - }); - const ledgerOrder = createFakeTrialLedger(); - - // Earlier explicit asOf on 2023-03-15T22:30:00.123456Z (after 21:00 bar close, before day end) - const explicitAsOf = '2023-03-15T22:30:00.123456Z'; - const orderRes = await callAnalyzeSignal({ - store: storeOrder.store, - ledger: ledgerOrder.executor, - vaultCutoffTs: cutoffTs, - args: { - listingIds: [102, 101], - from: '2023-01-01', - to: '2023-03-31', - asOf: explicitAsOf, - signal: { source: 'fundamentals', field: 'revenue' }, - horizonSessions: 1, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }, - }); - expect(orderRes.isError).toBe(false); - expect(storeOrder.fundamentalsCalls.map(c => c.asOf)).toEqual([ - '2023-01-31T23:59:59.999999Z', - '2023-02-28T23:59:59.999999Z', - explicitAsOf, - ]); - expect(storeOrder.fundamentalsCalls.every(c => c.listingIds[0] === 101 && c.listingIds[1] === 102)).toBe(true); - - // 2. Empty eligible bar sample -> 0 fundamentalsAsOf calls, insufficient_data, 0 ledger writes - const emptyBarsStore = createFakeStore({ - bars: [], - fundamentalsResolver: () => ({ columns: ['listing_id', 'effective_known_at', 'revenue'], rows: [] }), - }); - const emptyBarsLedger = createFakeTrialLedger(); - const emptyRes = await callAnalyzeSignal({ - store: emptyBarsStore.store, - ledger: emptyBarsLedger.executor, - vaultCutoffTs: cutoffTs, - args: { - listingIds: [101, 102], - from: '2023-01-01', - to: '2023-03-31', - signal: { source: 'fundamentals', field: 'revenue' }, - horizonSessions: 1, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }, - }); - expect(emptyRes.isError).toBe(false); - const emptyPayload = JSON.parse(emptyRes.text) as AnalyzeSignalResultPayload; - expect(emptyPayload.status).toBe('insufficient_data'); - if (emptyPayload.status === 'insufficient_data') { - expect(emptyPayload.reason).toBe('too_few_observations'); - } - expect(emptyBarsStore.fundamentalsCalls).toHaveLength(0); - expect(emptyBarsLedger.rows).toHaveLength(0); - - // 3. Exactly 120 eligible UTC months is accepted; 121 is rejected with 0 fundamentals calls and 0 ledger inserts - function makeMonthlyBars(monthCount: number): BarRecord[] { - const out: BarRecord[] = []; - for (let m = 0; m < monthCount; m += 1) { - const year = 2010 + Math.floor(m / 12); - const month = (m % 12) + 1; - const date = `${year}-${String(month).padStart(2, '0')}-15`; - const ts = makeUtcMs(date, 21); - out.push({ - listingId: 101, - ts, - open: 10, - high: 10, - low: 10, - close: 10, - volume: 100, - vwap: 10, - knownAt: ts, - }); - } - return out; - } - - const capCutoffTs = makeUtcMs('2025-01-01', 0); - const capPreWindowKnownAt = makeUtcMs('2009-12-15', 13); - const exactCapStore = createFakeStore({ - bars: makeMonthlyBars(ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS), - fundamentalsResolver: q => ({ - columns: ['listing_id', 'effective_known_at', 'revenue'], - rows: q.listingIds.map(lid => ({ - listing_id: lid, - effective_known_at: capPreWindowKnownAt, - revenue: 100, - })), - }), - }); - const exactCapLedger = createFakeTrialLedger(); - const exactCapRes = await callAnalyzeSignal({ - store: exactCapStore.store, - ledger: exactCapLedger.executor, - vaultCutoffTs: capCutoffTs, - args: { - listingIds: [101], - from: '2010-01-01', - to: '2024-12-31', - signal: { source: 'fundamentals', field: 'revenue' }, - horizonSessions: 1, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }, - }); - expect(exactCapRes.isError).toBe(false); - expect(exactCapStore.fundamentalsCalls).toHaveLength(ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS); - - const overCapStore = createFakeStore({ - bars: makeMonthlyBars(ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS + 1), - fundamentalsResolver: () => ({ columns: ['listing_id', 'effective_known_at', 'revenue'], rows: [] }), - }); - const overCapLedger = createFakeTrialLedger(); - const overCapRes = await callAnalyzeSignal({ - store: overCapStore.store, - ledger: overCapLedger.executor, - vaultCutoffTs: capCutoffTs, - args: { - listingIds: [101], - from: '2010-01-01', - to: '2024-12-31', - signal: { source: 'fundamentals', field: 'revenue' }, - horizonSessions: 1, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }, - }); - expect(overCapRes.isError).toBe(true); - expect(overCapRes.text).toBe( - `Invalid arguments for tool "analyze_signal": Fundamentals study exceeds maximum of ${ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS} month-end snapshots.` - ); - expect(overCapStore.fundamentalsCalls).toHaveLength(0); - expect(overCapLedger.insertCalls).toBe(0); - expect(overCapLedger.rows).toHaveLength(0); - }); - - test('restatement replay prevents look-ahead: dates before Q1 restatement use originally known values and appending a future revision leaves prior output unchanged', async () => { - // Explicit deterministic restatement fixture: - // - 6 listings across 2023-01-02..2023-05-31 (108 sessions), Vault cutoff 2023-06-01T00:00:00Z - // - Original Q1 known 2023-01-12T13:00Z (period_end 2022-12-31) - // - Original Q2 known 2023-02-15T13:00Z (period_end 2023-01-31) - // - Q1 restatement known 2023-04-12T13:00Z (AFTER Q2!): period_end stays 2023-01-31 (Q2), - // while ttm_revenue flips cross-sectional ordering for listings 0..5. - // - Unchanged months (March, May) re-emit identical (listing_id, effective_known_at) -> deduped cleanly. - const listingIds = [80_001, 80_002, 80_003, 80_004, 80_005, 80_006]; - const allDates = makeBusinessDates('2023-01-02', 112); - const preCutoffDates = allDates.filter(d => d < '2023-06-01'); - const vaultCutoffDate = '2023-06-01'; - const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0); - - const q1KnownAt = makeUtcMs('2023-01-12', 13); - const q2KnownAt = makeUtcMs('2023-02-15', 13); - const q1RestatedKnownAt = makeUtcMs('2023-04-12', 13); - const futureRevisionKnownAt = makeUtcMs('2023-06-15', 13); // post-cutoff - - const rand = createSeededRng(20261203); - const bars: BarRecord[] = []; - const prices = new Float64Array(listingIds.length).fill(50); - for (let t = 0; t < preCutoffDates.length; t += 1) { - const date = preCutoffDates[t]!; - const closeTs = makeUtcMs(date, 21); - for (let l = 0; l < listingIds.length; l += 1) { - const ret = (l - 2.5) * 0.0015 + (rand() * 2 - 1) * 0.008; - prices[l] = Math.max(1, prices[l]! * (1 + ret)); - const close = Number(prices[l]!.toFixed(6)); - bars.push({ - listingId: listingIds[l]!, - ts: closeTs, - open: close, - high: close, - low: close, - close, - volume: 25_000, - vwap: close, - knownAt: closeTs, - }); - } - } - - const basePitRows: FundamentalsPitFixtureRow[] = []; - const expectedDirectObs: SignalObservation[] = []; - - for (let l = 0; l < listingIds.length; l += 1) { - const lid = listingIds[l]!; - const q1Val = 100 + l * 20; - const q2Val = 120 + l * 25; - // Restatement reverses cross-sectional rank ordering after 2023-04-12 - const restatedVal = 300 - l * 30; - - basePitRows.push( - makeFundamentalsRow({ - listingId: lid, - effectiveKnownAt: q1KnownAt, - periodEnd: '2022-12-31', - fiscalPeriod: 'Q1', - revenue: q1Val / 4, - ttmRevenue: q1Val, - }), - makeFundamentalsRow({ - listingId: lid, - effectiveKnownAt: q2KnownAt, - periodEnd: '2023-01-31', - fiscalPeriod: 'Q2', - revenue: q2Val / 4, - ttmRevenue: q2Val, - }), - makeFundamentalsRow({ - listingId: lid, - effectiveKnownAt: q1RestatedKnownAt, - periodEnd: '2023-01-31', - fiscalPeriod: 'Q2', - revenue: q2Val / 4, - ttmRevenue: restatedVal, - }) - ); - - expectedDirectObs.push( - { listingId: lid, knownAt: q1KnownAt, value: q1Val }, - { listingId: lid, knownAt: q2KnownAt, value: q2Val }, - { listingId: lid, knownAt: q1RestatedKnownAt, value: restatedVal } - ); - } - - // 1. Direct baseline using independently specified eligible observations - const directLedger = createFakeTrialLedger(); - const directBuilt = buildForwardReturnPanel({ - bars, - signals: expectedDirectObs, - horizonSessions: 5, - vaultCutoffDate, - }); - const directStudy = await analyzeSignal(directLedger.executor, { - principalId: AGENT_PRINCIPAL, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - expression: { - expression: 'direct_restatement_baseline', - params: { field: 'ttm_revenue', horizonSessions: 5 }, - universe: listingIds, - horizon: '5d', - }, - panel: directBuilt.panel, - vaultCutoffDate, - }); - expect(directStudy.status).toBe('ok'); - if (directStudy.status !== 'ok') { - return; - } - - // 2. MCP handler run on base rows (before future revision is appended) - const args = { - listingIds, - from: preCutoffDates[0]!, - to: preCutoffDates[preCutoffDates.length - 1]!, - signal: { source: 'fundamentals', field: 'ttm_revenue' }, - horizonSessions: 5, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }; - - const mcpStore = createFakeStore({ - bars, - fundamentalsResolver: q => queryFundamentalsFixtureRows(basePitRows, q), - }); - const mcpLedger = createFakeTrialLedger(); - const mcpRes = await callAnalyzeSignal({ - store: mcpStore.store, - ledger: mcpLedger.executor, - vaultCutoffTs, - args, - }); - expect(mcpRes.isError).toBe(false); - const mcpPayload = JSON.parse(mcpRes.text) as AnalyzeSignalResultPayload; - expect(mcpPayload.status).toBe('ok'); - if (mcpPayload.status !== 'ok') { - return; - } - - // Exact parity between MCP handler and direct baseline (dates, rankIc, ledger daily_series) - expect(mcpPayload.analysis.rankIc).toEqual(directStudy.analysis.rankIc); - expect(mcpPayload.analysis.pearsonIc).toEqual(directStudy.analysis.pearsonIc); - expect(mcpLedger.rows[0]?.daily_series).toEqual(directLedger.rows[0]?.daily_series); - expect(mcpPayload.trial.sampleStart).toBe(directStudy.trial.sampleStart); - expect(mcpPayload.trial.sampleEnd).toBe(directStudy.trial.sampleEnd); - // Forward return endpoint remains strictly before vaultCutoffDate - const sampleEndIdx = preCutoffDates.indexOf(mcpPayload.trial.sampleEnd); - expect(sampleEndIdx).toBeGreaterThanOrEqual(0); - expect(sampleEndIdx + 5).toBeLessThan(preCutoffDates.length); - expect(preCutoffDates[sampleEndIdx + 5]! < vaultCutoffDate).toBe(true); - - // Confirm pre-restatement dates (between 2023-02-15 and 2023-04-11) actually differ from a look-ahead study - // that wrongly substitutes the restated values onto Q2's earlier known_at! - const lookAheadObs = expectedDirectObs.map(o => - o.knownAt === q2KnownAt - ? { ...o, value: 300 - (o.listingId - 80_001) * 30 } - : o - ); - const lookAheadBuilt = buildForwardReturnPanel({ - bars, - signals: lookAheadObs, - horizonSessions: 5, - vaultCutoffDate, - }); - const lookAheadLedger = createFakeTrialLedger(); - const lookAheadStudy = await analyzeSignal(lookAheadLedger.executor, { - principalId: AGENT_PRINCIPAL, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - expression: { - expression: 'look_ahead_counterfactual', - params: { field: 'ttm_revenue', horizonSessions: 5 }, - universe: listingIds, - horizon: '5d', - }, - panel: lookAheadBuilt.panel, - vaultCutoffDate, - }); - expect(lookAheadStudy.status).toBe('ok'); - expect(mcpLedger.rows[0]?.daily_series).not.toEqual(lookAheadLedger.rows[0]?.daily_series); - - // 3. Append a future revision (post-cutoff) and verify all prior dated outputs & ledger rows remain bit-identical - const rowsWithFutureRevision: FundamentalsPitFixtureRow[] = [ - ...basePitRows, - ...listingIds.map((lid, l) => - makeFundamentalsRow({ - listingId: lid, - effectiveKnownAt: futureRevisionKnownAt, - periodEnd: '2023-01-31', - fiscalPeriod: 'Q2', - revenue: 999, - ttmRevenue: 9_999 + l, - }) - ), - ]; - const futureStore = createFakeStore({ - bars, - fundamentalsResolver: q => queryFundamentalsFixtureRows(rowsWithFutureRevision, q), - }); - const futureLedger = createFakeTrialLedger(); - const futureRes = await callAnalyzeSignal({ - store: futureStore.store, - ledger: futureLedger.executor, - vaultCutoffTs, - args, - }); - expect(futureRes.isError).toBe(false); - expect(futureRes.text).toBe(mcpRes.text); - expect(futureLedger.rows).toEqual(mcpLedger.rows); - }); - - test('same-month restatement replay retains earlier intra-month vintage through the day before the amendment', async () => { - // Regression fixture for intra-month superseded vintages: - // - Dataset ID: `synthetic:mcp-analyze-signal-same-month-restatement:seed-20261204:v1` - // - 6 listings across 2023-03-01..2023-05-12 (53 sessions), Vault cutoff 2023-05-15T00:00:00Z - // - March 10: initial Q1 release (listings 0..4 only; listing 5 has NO prior release before April 5) - // - April 5: Q2 release for all 6 listings (strictly ascending ttm_revenue across listings) - // - April 18: Q1 restatement (SAME month as Q2!) keeping Q2 as latest period while reversing - // ttm_revenue cross-sectional ordering. - // Under latest-only month-end reads, the April 30 snapshot returns only the April 18 vintage - // and erases April 5 from April 5..17 (falling back to March for listings 0..4 and dropping - // listing 5 completely). With intra-month backfill, April 5..17 uses the original April 5 Q2 - // values and April 18+ uses the restated values. - const listingIds = [81_001, 81_002, 81_003, 81_004, 81_005, 81_006]; - const allDates = makeBusinessDates('2023-03-01', 53); - const vaultCutoffDate = '2023-05-15'; - const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0); - - const marKnownAt = makeUtcMs('2023-03-10', 13); - const aprQ2KnownAt = makeUtcMs('2023-04-05', 13); - const aprRestatedKnownAt = makeUtcMs('2023-04-18', 13); - - const rand = createSeededRng(20261204); - const bars: BarRecord[] = []; - const prices = new Float64Array(listingIds.length).fill(40); - for (let t = 0; t < allDates.length; t += 1) { - const date = allDates[t]!; - const closeTs = makeUtcMs(date, 21); - for (let l = 0; l < listingIds.length; l += 1) { - const ret = (l - 2.5) * 0.002 + (rand() * 2 - 1) * 0.009; - prices[l] = Math.max(1, prices[l]! * (1 + ret)); - const close = Number(prices[l]!.toFixed(6)); - bars.push({ - listingId: listingIds[l]!, - ts: closeTs, - open: close, - high: close, - low: close, - close, - volume: 30_000, - vwap: close, - knownAt: closeTs, - }); - } - } - - const pitRows: FundamentalsPitFixtureRow[] = []; - const expectedAllVintagesObs: SignalObservation[] = []; - const brokenMonthEndOnlyObs: SignalObservation[] = []; - - for (let l = 0; l < listingIds.length; l += 1) { - const lid = listingIds[l]!; - // March ordering: alternating/scrambled; April 5 Q2: strictly ascending; April 18 restated: strictly descending - const marVal = 200 + ((l * 3) % listingIds.length) * 25; - const aprQ2Val = 100 + l * 40; - const aprRestatedVal = 400 - l * 45; - - if (l < 5) { - pitRows.push( - makeFundamentalsRow({ - listingId: lid, - effectiveKnownAt: marKnownAt, - periodEnd: '2022-12-31', - fiscalPeriod: 'Q1', - revenue: marVal / 4, - ttmRevenue: marVal, - }) - ); - expectedAllVintagesObs.push({ listingId: lid, knownAt: marKnownAt, value: marVal }); - brokenMonthEndOnlyObs.push({ listingId: lid, knownAt: marKnownAt, value: marVal }); - } - - pitRows.push( - makeFundamentalsRow({ - listingId: lid, - effectiveKnownAt: aprQ2KnownAt, - periodEnd: '2023-03-31', - fiscalPeriod: 'Q2', - revenue: aprQ2Val / 4, - ttmRevenue: aprQ2Val, - }), - makeFundamentalsRow({ - listingId: lid, - effectiveKnownAt: aprRestatedKnownAt, - periodEnd: '2023-03-31', - fiscalPeriod: 'Q2', - revenue: aprQ2Val / 4, - ttmRevenue: aprRestatedVal, - }) - ); - - expectedAllVintagesObs.push( - { listingId: lid, knownAt: aprQ2KnownAt, value: aprQ2Val }, - { listingId: lid, knownAt: aprRestatedKnownAt, value: aprRestatedVal } - ); - // Month-end-only baseline misses the April 5 vintage completely - brokenMonthEndOnlyObs.push({ listingId: lid, knownAt: aprRestatedKnownAt, value: aprRestatedVal }); - } - - // 1. Direct baseline with all eligible vintages (including April 5 Q2) - const directBuilt = buildForwardReturnPanel({ - bars, - signals: expectedAllVintagesObs, - horizonSessions: 3, - vaultCutoffDate, - }); - const directLedger = createFakeTrialLedger(); - const directStudy = await analyzeSignal(directLedger.executor, { - principalId: AGENT_PRINCIPAL, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - expression: { - expression: 'direct_same_month_baseline', - params: { field: 'ttm_revenue', horizonSessions: 3 }, - universe: listingIds, - horizon: '3d', - }, - panel: directBuilt.panel, - vaultCutoffDate, - }); - expect(directStudy.status).toBe('ok'); - if (directStudy.status !== 'ok') { - return; - } - - // 2. Broken month-end-only counterfactual (omits April 5 Q2) - const brokenBuilt = buildForwardReturnPanel({ - bars, - signals: brokenMonthEndOnlyObs, - horizonSessions: 3, - vaultCutoffDate, - }); - const brokenLedger = createFakeTrialLedger(); - const brokenStudy = await analyzeSignal(brokenLedger.executor, { - principalId: AGENT_PRINCIPAL, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - expression: { - expression: 'broken_month_end_only_counterfactual', - params: { field: 'ttm_revenue', horizonSessions: 3 }, - universe: listingIds, - horizon: '3d', - }, - panel: brokenBuilt.panel, - vaultCutoffDate, - }); - expect(brokenStudy.status).toBe('ok'); - - // 3. MCP handler over multi-month window (March..May) - const mcpStore = createFakeStore({ - bars, - fundamentalsResolver: q => queryFundamentalsFixtureRows(pitRows, q), - }); - const mcpLedger = createFakeTrialLedger(); - const mcpRes = await callAnalyzeSignal({ - store: mcpStore.store, - ledger: mcpLedger.executor, - vaultCutoffTs, - args: { - listingIds, - from: allDates[0]!, - to: allDates[allDates.length - 1]!, - signal: { source: 'fundamentals', field: 'ttm_revenue' }, - horizonSessions: 3, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }, - }); - expect(mcpRes.isError).toBe(false); - const mcpPayload = JSON.parse(mcpRes.text) as AnalyzeSignalResultPayload; - expect(mcpPayload.status).toBe('ok'); - if (mcpPayload.status !== 'ok') { - return; - } - - // Exact parity with the full-vintage direct baseline across all dates (including April 5..17) - expect(mcpPayload.analysis.rankIc).toEqual(directStudy.analysis.rankIc); - expect(mcpPayload.analysis.pearsonIc).toEqual(directStudy.analysis.pearsonIc); - expect(mcpLedger.rows[0]?.daily_series).toEqual(directLedger.rows[0]?.daily_series); - - // Specifically verify April 5..17 dated points match direct baseline and differ from month-end-only - const aprilPreAmendmentDates = mcpPayload.analysis.ledgerSeries.points - .filter(p => p.date >= '2023-04-05' && p.date <= '2023-04-17') - .map(p => p.date); - expect(aprilPreAmendmentDates.length).toBeGreaterThan(0); - expect(aprilPreAmendmentDates[0]).toBe('2023-04-05'); - expect(aprilPreAmendmentDates[aprilPreAmendmentDates.length - 1]).toBe('2023-04-17'); - - const mcpByDate = new Map(mcpPayload.analysis.ledgerSeries.points.map(p => [p.date, p.value])); - const brokenByDate = new Map( - brokenStudy.analysis.dates.map((d, idx) => [d, brokenStudy.analysis.rankIcSeries[idx]!]) - ); - let aprilDiffCount = 0; - for (const d of aprilPreAmendmentDates) { - if (mcpByDate.get(d) !== brokenByDate.get(d)) { - aprilDiffCount += 1; - } - } - expect(aprilDiffCount).toBeGreaterThan(0); - - // Every fundamentalsAsOf call (month-end + backfill) stays strictly below Vault cutoff and forwards allowEstimatedLag - for (const call of mcpStore.fundamentalsCalls) { - expect(Date.parse(call.asOf)).toBeLessThan(vaultCutoffTs); - expect(call.allowEstimatedLag).toBe(false); - } - - // 4. Single-month window starting in April (2023-04-03..2023-04-28): - // must retain March prior (for Apr 3..4), April 5 Q2 (for Apr 5..17), and April 18 restatement (Apr 18..28). - const aprilOnlyBars = bars.filter(b => b.ts >= makeUtcMs('2023-04-03', 0) && b.ts <= makeUtcMs('2023-04-28', 23)); - const aprilDirectBuilt = buildForwardReturnPanel({ - bars: aprilOnlyBars, - signals: expectedAllVintagesObs, - horizonSessions: 3, - vaultCutoffDate, - }); - const aprilDirectLedger = createFakeTrialLedger(); - const aprilDirectStudy = await analyzeSignal(aprilDirectLedger.executor, { - principalId: AGENT_PRINCIPAL, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - expression: { - expression: 'direct_april_only_baseline', - params: { field: 'ttm_revenue', horizonSessions: 3 }, - universe: listingIds, - horizon: '3d', - }, - panel: aprilDirectBuilt.panel, - vaultCutoffDate, - }); - expect(aprilDirectStudy.status).toBe('ok'); - - const aprilMcpStore = createFakeStore({ - bars: aprilOnlyBars, - fundamentalsResolver: q => queryFundamentalsFixtureRows(pitRows, q), - }); - const aprilMcpLedger = createFakeTrialLedger(); - const aprilMcpRes = await callAnalyzeSignal({ - store: aprilMcpStore.store, - ledger: aprilMcpLedger.executor, - vaultCutoffTs, - args: { - listingIds, - from: '2023-04-03', - to: '2023-04-28', - signal: { source: 'fundamentals', field: 'ttm_revenue' }, - horizonSessions: 3, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }, - }); - expect(aprilMcpRes.isError).toBe(false); - const aprilMcpPayload = JSON.parse(aprilMcpRes.text) as AnalyzeSignalResultPayload; - expect(aprilMcpPayload.status).toBe('ok'); - if (aprilMcpPayload.status === 'ok' && aprilDirectStudy.status === 'ok') { - expect(aprilMcpPayload.analysis.rankIc).toEqual(aprilDirectStudy.analysis.rankIc); - expect(aprilMcpLedger.rows[0]?.daily_series).toEqual(aprilDirectLedger.rows[0]?.daily_series); - expect(aprilMcpPayload.trial.sampleStart).toBe('2023-04-03'); - } - }); - - test('estimated-lag omission backfill recovers earlier verified intra-month vintages when allowEstimatedLag is false', async () => { - // Regression fixture for DuckDB estimated-lag omission under allowEstimatedLag: false: - // - Dataset ID: `synthetic:mcp-analyze-signal-estimated-lag-omission:seed-20261205:v1` - // - 6 listings across 2023-03-01..2023-05-12 (53 sessions), Vault cutoff 2023-05-15T00:00:00Z - // - March 10: verified Q1 release (listings 0..4 only; listing 5 has no March prior) - // - April 5: verified Q2 release (`has_estimated_lag: false`) for all 6 listings - // - April 18: estimated-lag update (`has_estimated_lag: true`) for all 6 listings, so - // DuckDB's `fundamentalsAsOf(..., allowEstimatedLag: false)` omits listings 1..5 - // at April month-end and omits listing 0 at intermediate backfill probes. - // - April 25: verified update (`has_estimated_lag: false`) for listing 0 only (exercises - // sandwiched omission during backfill after a later verified release). - const listingIds = [82_001, 82_002, 82_003, 82_004, 82_005, 82_006]; - const allDates = makeBusinessDates('2023-03-01', 53); - const vaultCutoffDate = '2023-05-15'; - const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0); - - const marKnownAt = makeUtcMs('2023-03-10', 13); - const aprVerifiedKnownAt = makeUtcMs('2023-04-05', 13); - const aprEstimatedLagKnownAt = makeUtcMs('2023-04-18', 13); - const aprLateVerifiedKnownAt = makeUtcMs('2023-04-25', 13); - - const rand = createSeededRng(20261205); - const bars: BarRecord[] = []; - const prices = new Float64Array(listingIds.length).fill(45); - for (let t = 0; t < allDates.length; t += 1) { - const date = allDates[t]!; - const closeTs = makeUtcMs(date, 21); - for (let l = 0; l < listingIds.length; l += 1) { - const ret = (l - 2.5) * 0.002 + (rand() * 2 - 1) * 0.009; - prices[l] = Math.max(1, prices[l]! * (1 + ret)); - const close = Number(prices[l]!.toFixed(6)); - bars.push({ - listingId: listingIds[l]!, - ts: closeTs, - open: close, - high: close, - low: close, - close, - volume: 30_000, - vwap: close, - knownAt: closeTs, - }); - } - } - - const pitRows: FundamentalsPitFixtureRow[] = []; - const expectedVerifiedObs: SignalObservation[] = []; - const expectedAllowLagObs: SignalObservation[] = []; - const brokenOmittedAprilObs: SignalObservation[] = []; - - for (let l = 0; l < listingIds.length; l += 1) { - const lid = listingIds[l]!; - const marVal = 200 + ((l * 3) % listingIds.length) * 25; - const aprVerifiedVal = 100 + l * 40; - const aprEstimatedVal = 400 - l * 45; - const aprLateVerifiedVal = 150; - - if (l < 5) { - pitRows.push( - makeFundamentalsRow({ - listingId: lid, - effectiveKnownAt: marKnownAt, - periodEnd: '2022-12-31', - fiscalPeriod: 'Q1', - revenue: marVal / 4, - ttmRevenue: marVal, - hasEstimatedLag: false, - }) - ); - expectedVerifiedObs.push({ listingId: lid, knownAt: marKnownAt, value: marVal }); - expectedAllowLagObs.push({ listingId: lid, knownAt: marKnownAt, value: marVal }); - brokenOmittedAprilObs.push({ listingId: lid, knownAt: marKnownAt, value: marVal }); - } - - pitRows.push( - makeFundamentalsRow({ - listingId: lid, - effectiveKnownAt: aprVerifiedKnownAt, - periodEnd: '2023-03-31', - fiscalPeriod: 'Q2', - revenue: aprVerifiedVal / 4, - ttmRevenue: aprVerifiedVal, - hasEstimatedLag: false, - }), - makeFundamentalsRow({ - listingId: lid, - effectiveKnownAt: aprEstimatedLagKnownAt, - periodEnd: '2023-03-31', - fiscalPeriod: 'Q2', - revenue: aprEstimatedVal / 4, - ttmRevenue: aprEstimatedVal, - hasEstimatedLag: true, - }) - ); - - expectedVerifiedObs.push({ - listingId: lid, - knownAt: aprVerifiedKnownAt, - value: aprVerifiedVal, - }); - expectedAllowLagObs.push( - { listingId: lid, knownAt: aprVerifiedKnownAt, value: aprVerifiedVal }, - { listingId: lid, knownAt: aprEstimatedLagKnownAt, value: aprEstimatedVal } - ); - - if (l === 0) { - pitRows.push( - makeFundamentalsRow({ - listingId: lid, - effectiveKnownAt: aprLateVerifiedKnownAt, - periodEnd: '2023-03-31', - fiscalPeriod: 'Q2', - revenue: aprLateVerifiedVal / 4, - ttmRevenue: aprLateVerifiedVal, - hasEstimatedLag: false, - }) - ); - expectedVerifiedObs.push({ - listingId: lid, - knownAt: aprLateVerifiedKnownAt, - value: aprLateVerifiedVal, - }); - expectedAllowLagObs.push({ - listingId: lid, - knownAt: aprLateVerifiedKnownAt, - value: aprLateVerifiedVal, - }); - brokenOmittedAprilObs.push({ - listingId: lid, - knownAt: aprLateVerifiedKnownAt, - value: aprLateVerifiedVal, - }); - } - } - - // 1. Direct verified-only baseline (includes April 5 verified release; excludes April 18 estimated lag) - const directVerifiedBuilt = buildForwardReturnPanel({ - bars, - signals: expectedVerifiedObs, - horizonSessions: 3, - vaultCutoffDate, - }); - const directVerifiedLedger = createFakeTrialLedger(); - const directVerifiedStudy = await analyzeSignal(directVerifiedLedger.executor, { - principalId: AGENT_PRINCIPAL, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - expression: { - expression: 'direct_estimated_lag_omission_verified_baseline', - params: { field: 'ttm_revenue', horizonSessions: 3, allowEstimatedLag: false }, - universe: listingIds, - horizon: '3d', - }, - panel: directVerifiedBuilt.panel, - vaultCutoffDate, - }); - expect(directVerifiedStudy.status).toBe('ok'); - if (directVerifiedStudy.status !== 'ok') { - return; - } - - // 2. Broken counterfactual without omission backfill (loses April 5 for all omitted listings) - const brokenBuilt = buildForwardReturnPanel({ - bars, - signals: brokenOmittedAprilObs, - horizonSessions: 3, - vaultCutoffDate, - }); - const brokenLedger = createFakeTrialLedger(); - const brokenStudy = await analyzeSignal(brokenLedger.executor, { - principalId: AGENT_PRINCIPAL, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - expression: { - expression: 'broken_estimated_lag_omission_counterfactual', - params: { field: 'ttm_revenue', horizonSessions: 3, allowEstimatedLag: false }, - universe: listingIds, - horizon: '3d', - }, - panel: brokenBuilt.panel, - vaultCutoffDate, - }); - expect(brokenStudy.status).toBe('ok'); - - // 3. MCP handler with allowEstimatedLag: false (default) over March..May - const mcpStore = createFakeStore({ - bars, - fundamentalsResolver: q => queryFundamentalsFixtureRows(pitRows, q), - }); - const mcpLedger = createFakeTrialLedger(); - const mcpRes = await callAnalyzeSignal({ - store: mcpStore.store, - ledger: mcpLedger.executor, - vaultCutoffTs, - args: { - listingIds, - from: allDates[0]!, - to: allDates[allDates.length - 1]!, - signal: { source: 'fundamentals', field: 'ttm_revenue' }, - horizonSessions: 3, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }, - }); - expect(mcpRes.isError).toBe(false); - const mcpPayload = JSON.parse(mcpRes.text) as AnalyzeSignalResultPayload; - expect(mcpPayload.status).toBe('ok'); - if (mcpPayload.status !== 'ok') { - return; - } - - // Exact parity with the verified-only direct baseline across all dates (including April 5..17) - expect(mcpPayload.analysis.rankIc).toEqual(directVerifiedStudy.analysis.rankIc); - expect(mcpPayload.analysis.pearsonIc).toEqual(directVerifiedStudy.analysis.pearsonIc); - expect(mcpLedger.rows[0]?.daily_series).toEqual(directVerifiedLedger.rows[0]?.daily_series); - - const aprilPreEstimatedDates = mcpPayload.analysis.ledgerSeries.points - .filter(p => p.date >= '2023-04-05' && p.date <= '2023-04-17') - .map(p => p.date); - expect(aprilPreEstimatedDates[0]).toBe('2023-04-05'); - expect(aprilPreEstimatedDates[aprilPreEstimatedDates.length - 1]).toBe('2023-04-17'); - - const mcpByDate = new Map(mcpPayload.analysis.ledgerSeries.points.map(p => [p.date, p.value])); - const brokenByDate = new Map( - brokenStudy.analysis.dates.map((d, idx) => [d, brokenStudy.analysis.rankIcSeries[idx]!]) - ); - let aprilDiffCount = 0; - for (const d of aprilPreEstimatedDates) { - if (mcpByDate.get(d) !== brokenByDate.get(d)) { - aprilDiffCount += 1; - } - } - expect(aprilDiffCount).toBeGreaterThan(0); - - // Every fundamentalsAsOf call stays strictly below Vault cutoff and forwards allowEstimatedLag: false - for (const call of mcpStore.fundamentalsCalls) { - expect(Date.parse(call.asOf)).toBeLessThan(vaultCutoffTs); - expect(call.allowEstimatedLag).toBe(false); - } - - // 4. Single-month April-only window (2023-04-03..2023-04-28) with allowEstimatedLag: false - const aprilOnlyBars = bars.filter( - b => b.ts >= makeUtcMs('2023-04-03', 0) && b.ts <= makeUtcMs('2023-04-28', 23) - ); - const aprilDirectBuilt = buildForwardReturnPanel({ - bars: aprilOnlyBars, - signals: expectedVerifiedObs, - horizonSessions: 3, - vaultCutoffDate, - }); - const aprilDirectLedger = createFakeTrialLedger(); - const aprilDirectStudy = await analyzeSignal(aprilDirectLedger.executor, { - principalId: AGENT_PRINCIPAL, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - expression: { - expression: 'direct_estimated_lag_april_only_baseline', - params: { field: 'ttm_revenue', horizonSessions: 3, allowEstimatedLag: false }, - universe: listingIds, - horizon: '3d', - }, - panel: aprilDirectBuilt.panel, - vaultCutoffDate, - }); - expect(aprilDirectStudy.status).toBe('ok'); - - const aprilMcpStore = createFakeStore({ - bars: aprilOnlyBars, - fundamentalsResolver: q => queryFundamentalsFixtureRows(pitRows, q), - }); - const aprilMcpLedger = createFakeTrialLedger(); - const aprilMcpRes = await callAnalyzeSignal({ - store: aprilMcpStore.store, - ledger: aprilMcpLedger.executor, - vaultCutoffTs, - args: { - listingIds, - from: '2023-04-03', - to: '2023-04-28', - signal: { source: 'fundamentals', field: 'ttm_revenue' }, - horizonSessions: 3, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }, - }); - expect(aprilMcpRes.isError).toBe(false); - const aprilMcpPayload = JSON.parse(aprilMcpRes.text) as AnalyzeSignalResultPayload; - expect(aprilMcpPayload.status).toBe('ok'); - if (aprilMcpPayload.status === 'ok' && aprilDirectStudy.status === 'ok') { - expect(aprilMcpPayload.analysis.rankIc).toEqual(aprilDirectStudy.analysis.rankIc); - expect(aprilMcpLedger.rows[0]?.daily_series).toEqual(aprilDirectLedger.rows[0]?.daily_series); - } - - // 5. With allowEstimatedLag: true, April 18 estimated-lag update is included alongside April 5 - const allowLagDirectBuilt = buildForwardReturnPanel({ - bars, - signals: expectedAllowLagObs, - horizonSessions: 3, - vaultCutoffDate, - }); - const allowLagDirectLedger = createFakeTrialLedger(); - const allowLagDirectStudy = await analyzeSignal(allowLagDirectLedger.executor, { - principalId: AGENT_PRINCIPAL, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - expression: { - expression: 'direct_estimated_lag_allowed_baseline', - params: { field: 'ttm_revenue', horizonSessions: 3, allowEstimatedLag: true }, - universe: listingIds, - horizon: '3d', - }, - panel: allowLagDirectBuilt.panel, - vaultCutoffDate, - }); - expect(allowLagDirectStudy.status).toBe('ok'); - - const allowLagStore = createFakeStore({ - bars, - fundamentalsResolver: q => queryFundamentalsFixtureRows(pitRows, q), - }); - const allowLagLedger = createFakeTrialLedger(); - const allowLagRes = await callAnalyzeSignal({ - store: allowLagStore.store, - ledger: allowLagLedger.executor, - vaultCutoffTs, - args: { - listingIds, - from: allDates[0]!, - to: allDates[allDates.length - 1]!, - signal: { source: 'fundamentals', field: 'ttm_revenue', allowEstimatedLag: true }, - horizonSessions: 3, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }, - }); - expect(allowLagRes.isError).toBe(false); - const allowLagPayload = JSON.parse(allowLagRes.text) as AnalyzeSignalResultPayload; - expect(allowLagPayload.status).toBe('ok'); - if (allowLagPayload.status === 'ok' && allowLagDirectStudy.status === 'ok') { - expect(allowLagPayload.analysis.rankIc).toEqual(allowLagDirectStudy.analysis.rankIc); - expect(allowLagLedger.rows[0]?.daily_series).toEqual( - allowLagDirectLedger.rows[0]?.daily_series - ); - expect(allowLagLedger.rows[0]?.daily_series).not.toEqual(mcpLedger.rows[0]?.daily_series); - } - expect(allowLagStore.fundamentalsCalls.every(c => c.allowEstimatedLag === true)).toBe(true); - - // 6. Stale March null row for an omitted listing must not suppress April omission backfill; - // exact payload and ledger rows must match the clean run. - const staleNullKnownAt = makeUtcMs('2023-03-20', 13); - const staleNullStore = createFakeStore({ - bars, - fundamentalsResolver: q => { - const cleanTable = queryFundamentalsFixtureRows(pitRows, q); - const returnedIds = new Set(cleanTable.rows.map(r => r.listing_id)); - const injected: TableRow[] = []; - for (const omittedTarget of [listingIds[1]!, listingIds[5]!]) { - if (q.listingIds.includes(omittedTarget) && !returnedIds.has(omittedTarget)) { - injected.push({ - listing_id: omittedTarget, - effective_known_at: staleNullKnownAt, - known_at_source: 'sec_edgar_filing', - has_estimated_lag: false, - period_end: '2022-12-31', - fiscal_period: 'Q1', - currency: 'USD', - period_known_at: staleNullKnownAt, - ttm_revenue: null, - ttm_period_end: null, - ttm_currency: null, - ttm_has_estimated_lag: false, - }); - } - } - return { - columns: cleanTable.columns, - rows: [...cleanTable.rows, ...injected], - }; - }, - }); - const staleNullLedger = createFakeTrialLedger(); - const staleNullRes = await callAnalyzeSignal({ - store: staleNullStore.store, - ledger: staleNullLedger.executor, - vaultCutoffTs, - args: { - listingIds, - from: allDates[0]!, - to: allDates[allDates.length - 1]!, - signal: { source: 'fundamentals', field: 'ttm_revenue' }, - horizonSessions: 3, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }, - }); - expect(staleNullRes.isError).toBe(false); - expect(staleNullRes.text).toBe(mcpRes.text); - expect(staleNullLedger.rows).toEqual(mcpLedger.rows); - for (const call of staleNullStore.fundamentalsCalls) { - expect(Date.parse(call.asOf)).toBeLessThan(vaultCutoffTs); - expect(call.allowEstimatedLag).toBe(false); - } - - // 7. Genuinely null latest field with allowEstimatedLag: true must still probe earlier - // eligible closes and recover the valid April 5 release. - const nullLatestPitRows: FundamentalsPitFixtureRow[] = pitRows.map(row => - row.effective_known_at === aprEstimatedLagKnownAt ? { ...row, ttm_revenue: null } : row - ); - const nullLatestAllowLagStore = createFakeStore({ - bars, - fundamentalsResolver: q => queryFundamentalsFixtureRows(nullLatestPitRows, q), - }); - const nullLatestAllowLagLedger = createFakeTrialLedger(); - const nullLatestAllowLagRes = await callAnalyzeSignal({ - store: nullLatestAllowLagStore.store, - ledger: nullLatestAllowLagLedger.executor, - vaultCutoffTs, - args: { - listingIds, - from: allDates[0]!, - to: allDates[allDates.length - 1]!, - signal: { source: 'fundamentals', field: 'ttm_revenue', allowEstimatedLag: true }, - horizonSessions: 3, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }, - }); - expect(nullLatestAllowLagRes.isError).toBe(false); - const nullLatestAllowLagPayload = JSON.parse( - nullLatestAllowLagRes.text - ) as AnalyzeSignalResultPayload; - expect(nullLatestAllowLagPayload.status).toBe('ok'); - if (nullLatestAllowLagPayload.status === 'ok') { - expect(nullLatestAllowLagPayload.analysis.rankIc).toEqual( - directVerifiedStudy.analysis.rankIc - ); - expect(nullLatestAllowLagPayload.analysis.pearsonIc).toEqual( - directVerifiedStudy.analysis.pearsonIc - ); - expect(nullLatestAllowLagLedger.rows[0]?.daily_series).toEqual( - directVerifiedLedger.rows[0]?.daily_series - ); - const recoveredByDate = new Map( - nullLatestAllowLagPayload.analysis.ledgerSeries.points.map(p => [p.date, p.value]) - ); - let recoveredAprilDiffCount = 0; - for (const d of aprilPreEstimatedDates) { - if (recoveredByDate.get(d) !== brokenByDate.get(d)) { - recoveredAprilDiffCount += 1; - } - } - expect(recoveredAprilDiffCount).toBeGreaterThan(0); - } - expect(nullLatestAllowLagStore.fundamentalsCalls.length).toBeGreaterThan(0); - for (const call of nullLatestAllowLagStore.fundamentalsCalls) { - expect(Date.parse(call.asOf)).toBeLessThan(vaultCutoffTs); - expect(call.allowEstimatedLag).toBe(true); - } - }); - - test('Vault fence and defensive filtering: clean vs deliberately leaky fundamentals store produce identical payloads and ledger rows', async () => { - const fixture = buildFundamentalsStudyFixture(); - const from = fixture.allDates[0]!; - const postCutoffDate = fixture.allDates[fixture.allDates.length - 1]!; - - const cleanStore = createFakeStore({ - bars: fixture.bars, - fundamentalsResolver: q => queryFundamentalsFixtureRows(fixture.fundamentalsRows, q), - }); - const leakyStore = createFakeStore({ - bars: fixture.bars, - leaky: true, - fundamentalsResolver: q => { - const cleanTable = queryFundamentalsFixtureRows(fixture.fundamentalsRows, q); - const snapAsOfMs = Date.parse(q.asOf); - const poisonedRows: TableRow[] = [ - // 1. effective_known_at strictly after individual snapshot asOf (but before vaultCutoffTs) - { - listing_id: fixture.listingIds[0]!, - effective_known_at: snapAsOfMs + 60_000, - ttm_revenue: 999_999, - }, - // 2. effective_known_at at exact vaultCutoffTs - { - listing_id: fixture.listingIds[1]!, - effective_known_at: fixture.vaultCutoffTs, - ttm_revenue: 888_888, - }, - // 3. effective_known_at after vaultCutoffTs - { - listing_id: fixture.listingIds[2]!, - effective_known_at: fixture.vaultCutoffTs + 86_400_000, - ttm_revenue: 777_777, - }, - // 4. unrequested listing_id - { - listing_id: 999_999, - effective_known_at: makeUtcMs(from, 12), - ttm_revenue: 666_666, - }, - // 5. non-safe-integer effective_known_at (float & NaN) - { - listing_id: fixture.listingIds[3]!, - effective_known_at: makeUtcMs(from, 12) + 0.5, - ttm_revenue: 555_555, - }, - { - listing_id: fixture.listingIds[3]!, - effective_known_at: Number.NaN, - ttm_revenue: 555_555, - }, - // 6. null, NaN, and Infinity field values - { - listing_id: fixture.listingIds[4]!, - effective_known_at: makeUtcMs(from, 12), - ttm_revenue: null, - }, - { - listing_id: fixture.listingIds[4]!, - effective_known_at: makeUtcMs(from, 12) + 1_000, - ttm_revenue: Number.NaN, - }, - { - listing_id: fixture.listingIds[4]!, - effective_known_at: makeUtcMs(from, 12) + 2_000, - ttm_revenue: Number.POSITIVE_INFINITY, - }, - ]; - return { - columns: cleanTable.columns, - rows: [...cleanTable.rows, ...poisonedRows], - }; - }, - }); - - const cleanLedger = createFakeTrialLedger(); - const leakyLedger = createFakeTrialLedger(); - const args = { - listingIds: fixture.listingIds, - from, - to: postCutoffDate, - asOf: postCutoffDate, - signal: { source: 'fundamentals', field: 'ttm_revenue' }, - horizonSessions: 5, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }; - - const cleanRes = await callAnalyzeSignal({ - store: cleanStore.store, - ledger: cleanLedger.executor, - vaultCutoffTs: fixture.vaultCutoffTs, - args, - }); - const leakyRes = await callAnalyzeSignal({ - store: leakyStore.store, - ledger: leakyLedger.executor, - vaultCutoffTs: fixture.vaultCutoffTs, - args, - }); - - expect(cleanRes.isError).toBe(false); - expect(leakyRes.isError).toBe(false); - expect(leakyRes.text).toBe(cleanRes.text); - expect(leakyLedger.rows).toEqual(cleanLedger.rows); - - // Every fundamentalsAsOf call's asOf is strictly before vaultCutoffTs - expect(cleanStore.fundamentalsCalls.length).toBeGreaterThan(0); - for (const call of [...cleanStore.fundamentalsCalls, ...leakyStore.fundamentalsCalls]) { - expect(Date.parse(call.asOf)).toBeLessThan(fixture.vaultCutoffTs); - } - - // Malformed fundamentals table -> sanitized SignalPanelError with zero ledger writes - const badTableStore = createFakeStore({ - bars: fixture.bars, - fundamentalsResolver: () => ({ columns: null, rows: null } as unknown as Table), - }); - const badTableLedger = createFakeTrialLedger(); - const badTableRes = await callAnalyzeSignal({ - store: badTableStore.store, - ledger: badTableLedger.executor, - vaultCutoffTs: fixture.vaultCutoffTs, - args, - }); - expect(badTableRes.isError).toBe(true); - expect(badTableRes.text).toBe('SignalPanelError: Invalid signal panel input.'); - expect(badTableLedger.rows).toHaveLength(0); - }); -}); diff --git a/libs/research/test/mcp-bar-session-dates-qa.test.ts b/libs/research/test/mcp-bar-session-dates-qa.test.ts deleted file mode 100644 index 1685e47f..00000000 --- a/libs/research/test/mcp-bar-session-dates-qa.test.ts +++ /dev/null @@ -1,249 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { VaultHoldoutFenceError } from '../src/market-data-store'; -import { - type DuckDbExecutor, - type DuckDbParam, - createDuckDbMarketDataStore, -} from '../src/market-data-store-duckdb'; -import { - type ListingCalendarPort, - createBarSessionDatesPort, - createExchangeCalendarResolver, -} from '@stock-bot/research/mcp'; - -/** - * QA: the bar-derived SessionDatesPort composed with the real DuckDB store - * planner (`planBars1dQuery` + `mapBarRows`) over a recording fake executor that - * emulates the raw 1d SQL predicate (`listing_id IN (...) AND ts >= ? AND ts <= ? - * AND known_at <= ?` ordered by `listing_id, ts`) on a pinned in-memory dataset. - */ - -const CURATED_ROOT = '/mnt/data/stockbot/curated'; -const CUTOFF_MS = Date.UTC(2026, 4, 28, 0, 0, 0, 0); // 2026-05-28T00:00:00.000Z -const MAX_ALLOWED_ISO_MICROS = '2026-05-27T23:59:59.999999Z'; - -interface FixtureBar { - readonly listingId: number; - readonly ts: number; - readonly knownAt: number; -} - -function utcMs(dateStr: string, hour: number, minute = 0): number { - const [y, m, d] = dateStr.split('-').map(Number) as [number, number, number]; - return Date.UTC(y, m - 1, d, hour, minute, 0, 0); -} - -/** 16:00 ET daily stamp (curate_bars.rs convention): 20:00Z in EDT. Known shortly after close. */ -function edtBar(listingId: number, date: string, knownAt?: number): FixtureBar { - const ts = utcMs(date, 20); - return { listingId, ts, knownAt: knownAt ?? ts + 60_000 }; -} - -/** Parses `YYYY-MM-DDTHH:MM:SS(.ffffff)?Z` to fractional epoch ms (µs precision kept). */ -function isoToMs(iso: string): number { - const m = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?Z$/.exec(iso); - if (m === null) { - throw new Error(`Unexpected ISO bound: ${iso}`); - } - const frac = Number(`0.${(m[7] ?? '0').padEnd(6, '0').slice(0, 6)}`); - return ( - Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]), Number(m[4]), Number(m[5]), Number(m[6])) + - frac * 1000 - ); -} - -function createFixtureExecutor(dataset: readonly FixtureBar[]): { - readonly executor: DuckDbExecutor; - readonly queries: Array<{ sql: string; params: readonly DuckDbParam[] }>; -} { - const queries: Array<{ sql: string; params: readonly DuckDbParam[] }> = []; - const executor: DuckDbExecutor = { - async run(): Promise {}, - async query(sql: string, params: readonly DuckDbParam[]) { - queries.push({ sql, params: [...params] }); - const listingIds = new Set(params.slice(0, -3) as number[]); - const [fromIso, toIso, asOfIso] = params.slice(-3) as [string, string, string]; - const fromMs = isoToMs(fromIso); - const toMs = isoToMs(toIso); - const asOfMs = isoToMs(asOfIso); - return dataset - .filter( - (b) => - listingIds.has(b.listingId) && b.ts >= fromMs && b.ts <= toMs && b.knownAt <= asOfMs - ) - .sort((a, b) => a.listingId - b.listingId || a.ts - b.ts) - .map((b) => ({ - listing_id: b.listingId, - ts: b.ts, - open: 10, - high: 11, - low: 9, - close: 10.5, - volume: 1000, - vwap: null, - known_at: b.knownAt, - })); - }, - }; - return { executor, queries }; -} - -const DATASET: readonly FixtureBar[] = [ - // XNYS reference listings 11 and 12 (overlapping + one-sided dates). - edtBar(11, '2026-05-21'), - edtBar(12, '2026-05-22'), - edtBar(11, '2026-05-26'), - edtBar(12, '2026-05-26'), - edtBar(12, '2026-05-27'), - // Held-out Vault sessions at and after the cutoff date. - edtBar(11, '2026-05-28'), - edtBar(12, '2026-05-29'), - edtBar(11, '2026-06-01'), - // XTSE reference listing 21. - edtBar(21, '2026-05-25'), // Victoria Day: XTSE closed in reality, but present here to prove per-calendar isolation. - edtBar(21, '2026-05-26'), - // Pre-cutoff session whose bar only became known after the cutoff: must stay hidden. - edtBar(21, '2026-05-27', CUTOFF_MS + 3_600_000), - edtBar(21, '2026-05-28'), -]; - -function makeStore(barBatchSize?: number) { - const fake = createFixtureExecutor(DATASET); - const store = createDuckDbMarketDataStore({ - executor: fake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - env: {}, - ...(barBatchSize !== undefined ? { barBatchSize } : {}), - }); - return { store, queries: fake.queries }; -} - -describe('bar-session-dates QA — DuckDB store planner at the Vault cutoff', () => { - test('window straddling the cutoff returns only pre-cutoff sessions with a raw bars_1d plan clamped to cutoff - 1µs', async () => { - const { store, queries } = makeStore(); - const port = createBarSessionDatesPort({ - store, - referenceListingIds: { XNYS: [12, 11], XTSE: [21] }, - }); - - const dates = await port.listSessionDates({ - calendarCode: 'XNYS', - fromDate: '2026-05-22', - toDate: '2026-06-02', - }); - - expect(dates).toEqual(['2026-05-22', '2026-05-26', '2026-05-27']); - expect(queries).toHaveLength(1); - const q = queries[0]!; - expect(q.sql).toContain(`read_parquet('${CURATED_ROOT}/bars_1d/year=*/part.parquet'`); - expect(q.sql).not.toContain('adj_factors'); - expect(q.params).toEqual([ - 12, - 11, - '2026-05-22T00:00:00.000Z', - MAX_ALLOWED_ISO_MICROS, - MAX_ALLOWED_ISO_MICROS, - ]); - }); - - test('pre-cutoff bar first known after the cutoff is excluded via the default known_at fence', async () => { - const { store } = makeStore(); - const port = createBarSessionDatesPort({ - store, - referenceListingIds: { XNYS: [11, 12], XTSE: [21] }, - }); - - expect( - await port.listSessionDates({ - calendarCode: 'XTSE', - fromDate: '2026-05-25', - toDate: '2026-05-31', - }) - ).toEqual(['2026-05-25', '2026-05-26']); - }); - - test('fromDate on or after the cutoff date rejects with VaultHoldoutFenceError before any executor query', async () => { - const { store, queries } = makeStore(); - const port = createBarSessionDatesPort({ - store, - referenceListingIds: { XNYS: [11, 12] }, - }); - - for (const fromDate of ['2026-05-28', '2026-06-01']) { - let caught: unknown; - try { - await port.listSessionDates({ calendarCode: 'XNYS', fromDate, toDate: '2026-06-02' }); - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(VaultHoldoutFenceError); - } - expect(queries).toHaveLength(0); - }); - - test('last pre-cutoff day as a single-day window is included, and output is identical across barBatchSize settings', async () => { - const results: string[][] = []; - for (const batchSize of [undefined, 1, 2]) { - const { store } = makeStore(batchSize); - const port = createBarSessionDatesPort({ - store, - referenceListingIds: { XNYS: [11, 12] }, - }); - results.push([ - ...(await port.listSessionDates({ - calendarCode: 'XNYS', - fromDate: '2026-05-21', - toDate: '2026-05-27', - })), - ]); - expect( - await port.listSessionDates({ - calendarCode: 'XNYS', - fromDate: '2026-05-27', - toDate: '2026-05-27', - }) - ).toEqual(['2026-05-27']); - } - const expected = ['2026-05-21', '2026-05-22', '2026-05-26', '2026-05-27']; - expect(results).toEqual([expected, expected, expected]); - }); - - test('resolver composed over the DuckDB-backed port yields no post-cutoff session closes', async () => { - const { store, queries } = makeStore(); - const sessionDates = createBarSessionDatesPort({ - store, - referenceListingIds: { XNYS: [11, 12], XTSE: [21] }, - }); - const listingCalendars: ListingCalendarPort = { - getListingCalendars(listingIds) { - return listingIds.map((listingId) => ({ - listingId, - calendarCode: listingId === 901 ? 'XNYS' : 'XTSE', - })); - }, - }; - const resolve = createExchangeCalendarResolver({ listingCalendars, sessionDates }); - - const resolved = await resolve({ - listingIds: [901, 902], - fromDate: '2026-05-26', - toDate: '2026-06-02', - }); - - expect(resolved.listingCalendarId).toEqual({ 901: 'XNYS', 902: 'XTSE' }); - expect(resolved.calendars).toEqual({ - XNYS: [ - { date: '2026-05-26', closeTs: utcMs('2026-05-26', 20) }, - { date: '2026-05-27', closeTs: utcMs('2026-05-27', 20) }, - ], - XTSE: [{ date: '2026-05-26', closeTs: utcMs('2026-05-26', 20) }], - }); - for (const closes of Object.values(resolved.calendars)) { - for (const c of closes) { - expect(c.closeTs).toBeLessThan(CUTOFF_MS); - } - } - expect(queries).toHaveLength(2); - }); -}); diff --git a/libs/research/test/mcp-bar-session-dates.test.ts b/libs/research/test/mcp-bar-session-dates.test.ts deleted file mode 100644 index f5a1ebca..00000000 --- a/libs/research/test/mcp-bar-session-dates.test.ts +++ /dev/null @@ -1,527 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { - type BarBatch, - type BarRecord, - type MarketDataStore, - VaultHoldoutFenceError, -} from '../src/market-data-store'; -import { - BarSessionDatesError, - type BarSessionDatesPortOptions, - type ListingCalendarPort, - type PostgresResearchCopilotServerOptions, - type SessionDatesPort, - createBarSessionDatesPort, - createExchangeCalendarResolver, -} from '@stock-bot/research/mcp'; - -type BarsQueryArg = Parameters[0]; - -function utcMs( - year: number, - month: number, - day: number, - hour = 0, - minute = 0, - second = 0 -): number { - return Date.UTC(year, month - 1, day, hour, minute, second, 0); -} - -function makeBar(listingId: number, dateStr: string, closeHourUtc = 21): BarRecord { - const [y, m, d] = dateStr.split('-').map(Number) as [number, number, number]; - const ts = utcMs(y, m, d, closeHourUtc, 0, 0); - return { - listingId, - ts, - open: 100, - high: 101, - low: 99, - close: 100.5, - volume: 100_000, - knownAt: ts, - }; -} - -function makeRecordingStore( - handler: (q: BarsQueryArg) => AsyncIterable -): { - readonly store: Pick; - readonly calls: BarsQueryArg[]; -} { - const calls: BarsQueryArg[] = []; - const store: Pick = { - bars(q: BarsQueryArg): AsyncIterable { - calls.push(q); - return handler(q); - }, - }; - return { store, calls }; -} - -async function* yieldBatches(batches: readonly BarBatch[]): AsyncGenerator { - for (const batch of batches) { - yield batch; - } -} - -describe('createBarSessionDatesPort — exports, types, and query contract', () => { - test('returned port is assignable to SessionDatesPort and PostgresResearchCopilotServerOptions["sessionDates"] without casts', async () => { - const { store } = makeRecordingStore(() => yieldBatches([])); - const options: BarSessionDatesPortOptions = { - store, - referenceListingIds: { - XNYS: [101], - }, - }; - - const port = createBarSessionDatesPort(options); - const asSessionDatesPort: SessionDatesPort = port; - const asCopilotSessionDates: PostgresResearchCopilotServerOptions['sessionDates'] = port; - - expect(asSessionDatesPort).toBe(port); - expect(asCopilotSessionDates).toBe(port); - expect( - await asCopilotSessionDates.listSessionDates({ - calendarCode: 'XNYS', - fromDate: '2024-11-25', - toDate: '2024-11-29', - }) - ).toEqual([]); - }); - - test('calls store.bars once per query with exact Vault-default keys and configured ID order', async () => { - const { store, calls } = makeRecordingStore(() => - yieldBatches([{ rows: [makeBar(202, '2024-11-26', 21)] }]) - ); - - const port = createBarSessionDatesPort({ - store, - referenceListingIds: { - XNYS: [202, 101], - XTSE: [303], - }, - }); - - const dates = await port.listSessionDates({ - calendarCode: 'XNYS', - fromDate: '2024-11-25', - toDate: '2024-11-29', - }); - - expect(dates).toEqual(['2024-11-26']); - expect(calls).toHaveLength(1); - - const req = calls[0] as BarsQueryArg; - expect(req.listingIds).toEqual([202, 101]); - expect(req.timeframe).toBe('1d'); - expect(req.adjustment).toBe('raw'); - expect(req.from).toBe('2024-11-25'); - expect(req.to).toBe('2024-11-29'); - expect(Object.keys(req).sort()).toEqual(['adjustment', 'from', 'listingIds', 'timeframe', 'to']); - expect('scope' in req).toBe(false); - expect('asOf' in req).toBe(false); - }); -}); - -describe('createBarSessionDatesPort — union, bounds, determinism, and empty streams', () => { - test('returns strictly ascending de-duplicated union across multiple out-of-order batches inside [fromDate, toDate]', async () => { - const batches: readonly BarBatch[] = [ - { - rows: [ - // Valid bars outside the requested window must be excluded. - makeBar(101, '2024-11-22', 21), - makeBar(102, '2024-12-02', 21), - // Out-of-order bars inside window, including upper inclusive bound. - makeBar(102, '2024-11-29', 21), - makeBar(101, '2024-11-27', 21), - ], - }, - { - rows: [ - // Overlapping date (2024-11-27), single-listing date (2024-11-26), lower inclusive bound (2024-11-25). - makeBar(102, '2024-11-27', 21), - makeBar(101, '2024-11-25', 21), - makeBar(102, '2024-11-26', 21), - ], - }, - ]; - - const { store, calls } = makeRecordingStore(() => yieldBatches(batches)); - const port = createBarSessionDatesPort({ - store, - referenceListingIds: { - XNYS: [101, 102], - }, - }); - - const first = await port.listSessionDates({ - calendarCode: 'XNYS', - fromDate: '2024-11-25', - toDate: '2024-11-29', - }); - const second = await port.listSessionDates({ - calendarCode: 'XNYS', - fromDate: '2024-11-25', - toDate: '2024-11-29', - }); - - const expected = ['2024-11-25', '2024-11-26', '2024-11-27', '2024-11-29']; - expect(first).toEqual(expected); - expect(second).toEqual(expected); - expect(calls).toHaveLength(2); - }); - - test('supports single-day inclusive window and returns [] for empty streams or empty batches', async () => { - const { store: singleDayStore } = makeRecordingStore(() => - yieldBatches([ - { - rows: [ - makeBar(101, '2024-07-01', 20), - makeBar(101, '2024-07-02', 20), - makeBar(101, '2024-07-03', 20), - ], - }, - ]) - ); - - const singleDayPort = createBarSessionDatesPort({ - store: singleDayStore, - referenceListingIds: { XNYS: [101] }, - }); - - expect( - await singleDayPort.listSessionDates({ - calendarCode: 'XNYS', - fromDate: '2024-07-02', - toDate: '2024-07-02', - }) - ).toEqual(['2024-07-02']); - - const { store: emptyBatchStore } = makeRecordingStore(() => - yieldBatches([{ rows: [] }, { rows: [] }]) - ); - const emptyPort = createBarSessionDatesPort({ - store: emptyBatchStore, - referenceListingIds: { XNYS: [101] }, - }); - - expect( - await emptyPort.listSessionDates({ - calendarCode: 'XNYS', - fromDate: '2024-07-02', - toDate: '2024-07-02', - }) - ).toEqual([]); - }); -}); - -describe('createBarSessionDatesPort — fail-closed query, store error, and bar validation', () => { - test('throws unknown_calendar and invalid_query with zero store calls', async () => { - const { store, calls } = makeRecordingStore(() => yieldBatches([])); - const port = createBarSessionDatesPort({ - store, - referenceListingIds: { - XNYS: [101], - }, - }); - - const expectError = async ( - query: unknown, - expectedCode: BarSessionDatesError['code'] - ): Promise => { - let caught: unknown; - try { - await port.listSessionDates(query as never); - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(BarSessionDatesError); - expect((caught as BarSessionDatesError).code).toBe(expectedCode); - }; - - await expectError( - { calendarCode: 'XTSE', fromDate: '2024-11-25', toDate: '2024-11-29' }, - 'unknown_calendar' - ); - await expectError( - { calendarCode: '', fromDate: '2024-11-25', toDate: '2024-11-29' }, - 'unknown_calendar' - ); - await expectError( - { calendarCode: 'XNYS', fromDate: '2024/11/25', toDate: '2024-11-29' }, - 'invalid_query' - ); - await expectError( - { calendarCode: 'XNYS', fromDate: '2024-11-25T00:00:00Z', toDate: '2024-11-29' }, - 'invalid_query' - ); - await expectError( - { calendarCode: 'XNYS', fromDate: '2024-02-30', toDate: '2024-03-01' }, - 'invalid_query' - ); - await expectError( - { calendarCode: 'XNYS', fromDate: '2024-11-25', toDate: '2023-02-29' }, - 'invalid_query' - ); - await expectError( - { calendarCode: 'XNYS', fromDate: '2024-11-29', toDate: '2024-11-25' }, - 'invalid_query' - ); - await expectError(null, 'invalid_query'); - - expect(calls).toHaveLength(0); - }); - - test('propagates VaultHoldoutFenceError from the async iterator unchanged with no partial result', async () => { - const vaultError = new VaultHoldoutFenceError( - '2025-01-02', - utcMs(2025, 1, 2, 0, 0, 0), - utcMs(2025, 1, 1, 0, 0, 0) - ); - - const { store } = makeRecordingStore(() => - (async function* (): AsyncGenerator { - yield { rows: [makeBar(101, '2024-12-31', 21)] }; - throw vaultError; - })() - ); - - const port = createBarSessionDatesPort({ - store, - referenceListingIds: { XNYS: [101] }, - }); - - let caught: unknown; - try { - await port.listSessionDates({ - calendarCode: 'XNYS', - fromDate: '2024-12-30', - toDate: '2025-01-02', - }); - } catch (err) { - caught = err; - } - - expect(caught).toBe(vaultError); - }); - - test('throws invalid_bar for NaN, Infinity, fractional ts, or unconfigured listingId', async () => { - const badBars: readonly BarRecord[] = [ - { ...makeBar(101, '2024-11-25', 21), ts: Number.NaN }, - { ...makeBar(101, '2024-11-25', 21), ts: Number.POSITIVE_INFINITY }, - { ...makeBar(101, '2024-11-25', 21), ts: Number.NEGATIVE_INFINITY }, - { ...makeBar(101, '2024-11-25', 21), ts: utcMs(2024, 11, 25, 21, 0, 0) + 0.5 }, - // Listing ID configured only on XTSE, not XNYS. - makeBar(202, '2024-11-25', 21), - // Listing ID not configured on any calendar, even when outside the date window. - makeBar(999, '2024-01-02', 21), - ]; - - for (const badBar of badBars) { - const { store } = makeRecordingStore(() => yieldBatches([{ rows: [badBar] }])); - const port = createBarSessionDatesPort({ - store, - referenceListingIds: { - XNYS: [101], - XTSE: [202], - }, - }); - - let caught: unknown; - try { - await port.listSessionDates({ - calendarCode: 'XNYS', - fromDate: '2024-11-25', - toDate: '2024-11-29', - }); - } catch (err) { - caught = err; - } - - expect(caught).toBeInstanceOf(BarSessionDatesError); - expect((caught as BarSessionDatesError).code).toBe('invalid_bar'); - } - }); -}); - -describe('createBarSessionDatesPort — options validation and defensive copy', () => { - test('rejects malformed options, empty keys, non-positive/non-INT32 IDs, and duplicates with invalid_options', () => { - const { store } = makeRecordingStore(() => yieldBatches([])); - - const invalidInputs: readonly unknown[] = [ - null, - undefined, - {}, - { store: null, referenceListingIds: { XNYS: [1] } }, - { store: {}, referenceListingIds: { XNYS: [1] } }, - { store: { bars: 'nope' }, referenceListingIds: { XNYS: [1] } }, - { store, referenceListingIds: null }, - { store, referenceListingIds: [] }, - { store, referenceListingIds: { '': [1] } }, - { store, referenceListingIds: { ' ': [1] } }, - { store, referenceListingIds: { ' XNYS': [1] } }, - { store, referenceListingIds: { XNYS: null } }, - { store, referenceListingIds: { XNYS: [] } }, - { store, referenceListingIds: { XNYS: [0] } }, - { store, referenceListingIds: { XNYS: [-5] } }, - { store, referenceListingIds: { XNYS: [1.5] } }, - { store, referenceListingIds: { XNYS: [2_147_483_648] } }, - { store, referenceListingIds: { XNYS: [Number.NaN] } }, - { store, referenceListingIds: { XNYS: [101, 202, 101] } }, - ]; - - for (const input of invalidInputs) { - let caught: unknown; - try { - createBarSessionDatesPort(input as never); - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(BarSessionDatesError); - expect((caught as BarSessionDatesError).code).toBe('invalid_options'); - } - }); - - test('defensively copies caller config and isolates per-call listingIds arrays', async () => { - const xnysIds = [101, 102]; - const referenceListingIds: Record = { - XNYS: xnysIds, - }; - - const observedIds: number[][] = []; - const store: Pick = { - bars(q: BarsQueryArg): AsyncIterable { - observedIds.push([...q.listingIds]); - // Mutate caller-passed query array to confirm port passes a fresh copy each time. - q.listingIds.push(999); - return yieldBatches([{ rows: [makeBar(101, '2024-11-25', 21)] }]); - }, - }; - - const port = createBarSessionDatesPort({ store, referenceListingIds }); - - // Mutate caller config after construction. - xnysIds.push(303); - xnysIds[0] = 404; - referenceListingIds.XNYS = [505]; - referenceListingIds.XTSE = [606]; - - expect( - await port.listSessionDates({ - calendarCode: 'XNYS', - fromDate: '2024-11-25', - toDate: '2024-11-25', - }) - ).toEqual(['2024-11-25']); - expect( - await port.listSessionDates({ - calendarCode: 'XNYS', - fromDate: '2024-11-25', - toDate: '2024-11-25', - }) - ).toEqual(['2024-11-25']); - - expect(observedIds).toEqual([ - [101, 102], - [101, 102], - ]); - - let caught: unknown; - try { - await port.listSessionDates({ - calendarCode: 'XTSE', - fromDate: '2024-11-25', - toDate: '2024-11-25', - }); - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(BarSessionDatesError); - expect((caught as BarSessionDatesError).code).toBe('unknown_calendar'); - }); -}); - -describe('createBarSessionDatesPort — composition with createExchangeCalendarResolver', () => { - test('resolves XNYS and XTSE session closes including summer EDT, Thanksgiving divergence, and early-close override', async () => { - const xnysBars: readonly BarRecord[] = [ - // Summer EDT session (16:00 ET = 20:00Z) - makeBar(1001, '2024-07-02', 20), - // Winter EST sessions (US closed 2024-11-28 Thanksgiving; open 2024-11-29) - makeBar(1001, '2024-11-27', 21), - makeBar(1002, '2024-11-29', 21), - ]; - - const xtseBars: readonly BarRecord[] = [ - // Summer EDT session (16:00 ET = 20:00Z) - makeBar(2001, '2024-07-02', 20), - // Winter EST sessions (TSX open on US Thanksgiving 2024-11-28 and regular close on 2024-11-29) - makeBar(2001, '2024-11-27', 21), - makeBar(2001, '2024-11-28', 21), - makeBar(2002, '2024-11-29', 21), - ]; - - const { store, calls } = makeRecordingStore((q) => { - const requested = new Set(q.listingIds); - const rows = [...xnysBars, ...xtseBars].filter((bar) => requested.has(bar.listingId)); - return yieldBatches([{ rows }]); - }); - - const sessionDates = createBarSessionDatesPort({ - store, - referenceListingIds: { - XNYS: [1001, 1002], - XTSE: [2001, 2002], - }, - }); - - const listingCalendars: ListingCalendarPort = { - getListingCalendars(listingIds) { - return listingIds.map((listingId) => ({ - listingId, - calendarCode: listingId === 501 ? 'XNYS' : 'XTSE', - })); - }, - }; - - const resolveExchangeCalendars = createExchangeCalendarResolver({ - listingCalendars, - sessionDates, - earlyCloses: { - XNYS: { - '2024-11-29': 13 * 60, // 13:00 ET -> 18:00Z (EST) - }, - }, - }); - - const resolved = await resolveExchangeCalendars({ - listingIds: [501, 602], - fromDate: '2024-07-02', - toDate: '2024-11-29', - }); - - expect(resolved.listingCalendarId).toEqual({ - 501: 'XNYS', - 602: 'XTSE', - }); - - expect(resolved.calendars).toEqual({ - XNYS: [ - { date: '2024-07-02', closeTs: utcMs(2024, 7, 2, 20, 0, 0) }, - { date: '2024-11-27', closeTs: utcMs(2024, 11, 27, 21, 0, 0) }, - { date: '2024-11-29', closeTs: utcMs(2024, 11, 29, 18, 0, 0) }, - ], - XTSE: [ - { date: '2024-07-02', closeTs: utcMs(2024, 7, 2, 20, 0, 0) }, - { date: '2024-11-27', closeTs: utcMs(2024, 11, 27, 21, 0, 0) }, - { date: '2024-11-28', closeTs: utcMs(2024, 11, 28, 21, 0, 0) }, - { date: '2024-11-29', closeTs: utcMs(2024, 11, 29, 21, 0, 0) }, - ], - }); - - // One store.bars call per distinct calendar code (XNYS, XTSE). - expect(calls).toHaveLength(2); - expect(calls[0]?.listingIds).toEqual([1001, 1002]); - expect(calls[1]?.listingIds).toEqual([2001, 2002]); - }); -}); diff --git a/libs/research/test/mcp-copilot-server-qa.test.ts b/libs/research/test/mcp-copilot-server-qa.test.ts deleted file mode 100644 index 893c62ec..00000000 --- a/libs/research/test/mcp-copilot-server-qa.test.ts +++ /dev/null @@ -1,740 +0,0 @@ -import { describe, expect, spyOn, test } from 'bun:test'; -import type { EventStudyExchangeCalendars } from '../src/event-panel'; -import type { - BarBatch, - BarRecord, - BarsQuery, - EventsQuery, - MarketDataStore, - ShortsAsOfQuery, - Table, - TableRow, -} from '../src/market-data-store'; -import { EVENTS_COLUMNS, MarketDataStoreNotImplementedError } from '../src/market-data-store-duckdb'; -import { - type AnalyzeSignalResultPayload, - type EventStudyResultPayload, - type FileFindingResultPayload, - type FiledFindingRecord, - type FindingWritePort, - type KnowledgePort, - type McpServer, - RESEARCH_COPILOT_TOOL_NAMES, - type ReadKnowledgeResultPayload, - type ResearchCopilotMcpServerOptions, - type SearchSymbolsResultPayload, - type StdioOutput, - areFiledFindingPayloadsEqual, - createResearchCopilotMcpServer, - runStdioServer, -} from '../src/mcp/index'; -import * as analyzeSignalToolModule from '../src/mcp/tools/analyze-signal'; -import * as queryDataToolModule from '../src/mcp/tools/query-data'; -import type { TrialLedgerExecutor } from '../src/trial-ledger'; - -// QA fixture for T-144 (composed research copilot MCP server), pinned for reproducibility: -// - Dataset ID: `synthetic:mcp-copilot-qa:seed-424242:v1` (Mulberry32 seed 424242) -// - Universe: 12 synthetic XNYS listings (`60001..60012`), daily bars at 21:00 UTC -// - Sessions: 60 pre-cutoff + 6 post-cutoff weekdays starting 2023-01-02; -// vault cutoff = 00:00 UTC on session index 60 -// - Shorts reported every 5 sessions (indices 0,5,...), known_at = 22:00 UTC on report+3, -// so the first actionable signal session is index 4 (first close strictly after known_at) -// - Study assumptions: raw close-to-close returns, zero modeled costs, 5-session horizon, -// event_study equal-weight benchmark on 8-K filings -const FIXTURE_DATASET_ID = 'synthetic:mcp-copilot-qa:seed-424242:v1'; -const SEED = 424242; -const LISTING_COUNT = 12; -const PRE_CUTOFF_SESSIONS = 60; -const POST_CUTOFF_SESSIONS = 6; -const HORIZON = 5; -const AGENT_PRINCIPAL = 'agent:aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee'; -const FIXED_NOW_MS = Date.parse('2024-07-01T09:00:00.000Z'); - -function createSeededRng(seed: number): () => number { - let state = seed >>> 0; - return () => { - state = (state + 0x6d2b79f5) >>> 0; - let t = Math.imul(state ^ (state >>> 15), 1 | state); - t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; - return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296; - }; -} - -function makeBusinessDates(startDate: string, count: number): string[] { - const out: string[] = []; - const current = new Date(`${startDate}T00:00:00.000Z`); - while (out.length < count) { - const day = current.getUTCDay(); - if (day !== 0 && day !== 6) { - out.push(current.toISOString().slice(0, 10)); - } - current.setUTCDate(current.getUTCDate() + 1); - } - return out; -} - -function utcMs(date: string, hour: number): number { - return Date.parse(`${date}T${String(hour).padStart(2, '0')}:00:00.000Z`); -} - -/** Parses store bound strings (date-only, ms or µs ISO) to epoch ms, truncating sub-ms digits. */ -function boundMs(raw: string, endOfDay: boolean): number { - if (raw.length === 10) { - return Date.parse(`${raw}T${endOfDay ? '23:59:59.999' : '00:00:00.000'}Z`); - } - const m = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,9}))?Z$/.exec(raw); - if (m === null) { - throw new Error(`Unparseable bound: ${raw}`); - } - const frac = (m[2] ?? '').padEnd(3, '0').slice(0, 3); - return Date.parse(`${m[1]}.${frac}Z`); -} - -interface Fixture { - readonly listingIds: readonly number[]; - readonly dates: readonly string[]; - readonly cutoffDate: string; - readonly cutoffTs: number; - readonly lastPreDate: string; - readonly lastDate: string; - readonly bars: readonly BarRecord[]; - readonly shorts: Table; - readonly events: Table; - readonly calendars: EventStudyExchangeCalendars; -} - -function buildFixture(): Fixture { - const rand = createSeededRng(SEED); - const dates = makeBusinessDates('2023-01-02', PRE_CUTOFF_SESSIONS + POST_CUTOFF_SESSIONS); - const listingIds = Array.from({ length: LISTING_COUNT }, (_, i) => 60_001 + i); - const cutoffDate = dates[PRE_CUTOFF_SESSIONS]!; - const bars: BarRecord[] = []; - const shortsRows: TableRow[] = []; - const eventRows: TableRow[] = []; - - const eventDays = [10, 18, 26, 34, 42, 50, 62]; - const eventKey = new Set(); - eventDays.forEach((t, e) => { - const ts = utcMs(dates[t]!, 14); - for (let k = 0; k < 2; k += 1) { - const l = (e * 2 + k) % LISTING_COUNT; - eventKey.add(`${t}:${l}`); - eventRows.push({ - listing_id: listingIds[l]!, - ts, - known_at: ts, - known_at_source: 'exact', - kind: 'filing', - subtype: '8-K', - payload_json: '{}', - }); - } - }); - - const prices = listingIds.map((_, l) => 20 + l * 3); - for (let t = 0; t < dates.length; t += 1) { - const date = dates[t]!; - if (t % 5 === 0 && t + 3 < dates.length) { - for (let l = 0; l < LISTING_COUNT; l += 1) { - shortsRows.push({ - listing_id: listingIds[l]!, - report_date: date, - known_at: utcMs(dates[t + 3]!, 22), - shares_short: 200_000 + l * 1_000 + Math.round(rand() * 5_000), - net_change: Math.round((rand() * 2 - 1) * 15_000), - pct_float: Number((0.01 + rand() * 0.05).toFixed(4)), - source: 'ceoShorts', - }); - } - } - const closeTs = utcMs(date, 21); - for (let l = 0; l < LISTING_COUNT; l += 1) { - const drift = eventKey.has(`${t}:${l}`) || eventKey.has(`${t - 1}:${l}`) ? 0.008 : 0; - prices[l] = Math.max(1, prices[l]! * (1 + drift + (rand() * 2 - 1) * 0.01)); - const close = Number(prices[l]!.toFixed(4)); - bars.push({ - listingId: listingIds[l]!, - ts: closeTs, - open: close, - high: close, - low: close, - close, - volume: 10_000 + t, - vwap: close, - knownAt: closeTs, - }); - } - } - - return { - listingIds, - dates, - cutoffDate, - cutoffTs: utcMs(cutoffDate, 0), - lastPreDate: dates[PRE_CUTOFF_SESSIONS - 1]!, - lastDate: dates[dates.length - 1]!, - bars, - shorts: { - columns: [ - 'listing_id', - 'report_date', - 'known_at', - 'shares_short', - 'net_change', - 'pct_float', - 'source', - ], - rows: shortsRows, - }, - events: { columns: [...EVENTS_COLUMNS], rows: eventRows }, - calendars: { - calendars: { XNYS: dates.map(date => ({ date, closeTs: utcMs(date, 21) })) }, - listingCalendarId: new Map(listingIds.map(id => [id, 'XNYS'])), - }, - }; -} - -interface RecordingStore { - readonly store: MarketDataStore; - readonly barsQueries: BarsQuery[]; - readonly shortsQueries: ShortsAsOfQuery[]; - readonly eventsQueries: EventsQuery[]; -} - -/** Honest in-memory store that records every query it receives. */ -function createRecordingStore(fx: Fixture): RecordingStore { - const barsQueries: BarsQuery[] = []; - const shortsQueries: ShortsAsOfQuery[] = []; - const eventsQueries: EventsQuery[] = []; - const store: MarketDataStore = { - bars(q): AsyncIterable { - barsQueries.push(q); - const ids = new Set(q.listingIds); - const from = boundMs(q.from, false); - const to = boundMs(q.to, true); - const asOf = q.asOf !== undefined ? boundMs(q.asOf, true) : Number.POSITIVE_INFINITY; - const rows = fx.bars.filter( - r => ids.has(r.listingId) && r.ts >= from && r.ts <= to && r.knownAt <= asOf - ); - return { - async *[Symbol.asyncIterator]() { - yield { rows }; - }, - }; - }, - async universe() { - return [...fx.listingIds]; - }, - async shortsAsOf(q) { - shortsQueries.push(q); - const ids = new Set(q.listingIds); - const asOf = q.asOf !== undefined ? boundMs(q.asOf, true) : Number.POSITIVE_INFINITY; - const from = q.from.slice(0, 10); - const to = q.to.slice(0, 10); - return { - columns: fx.shorts.columns, - rows: fx.shorts.rows.filter( - r => - ids.has(r.listing_id as number) && - (r.report_date as string) >= from && - (r.report_date as string) <= to && - (r.known_at as number) <= asOf - ), - }; - }, - async events(q) { - eventsQueries.push(q); - const ids = q.listingIds !== undefined ? new Set(q.listingIds) : null; - const from = boundMs(q.from, false); - const to = boundMs(q.to, true); - const asOf = q.asOf !== undefined ? boundMs(q.asOf, true) : Number.POSITIVE_INFINITY; - return { - columns: fx.events.columns, - rows: fx.events.rows.filter( - r => - (ids === null || ids.has(r.listing_id as number)) && - q.kinds.includes(r.kind as never) && - (r.ts as number) >= from && - (r.ts as number) <= to && - (r.known_at as number) <= asOf - ), - }; - }, - async crossSection() { - throw new MarketDataStoreNotImplementedError('crossSection'); - }, - async fundamentalsAsOf() { - throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); - }, - async macroAsOf() { - throw new MarketDataStoreNotImplementedError('macroAsOf'); - }, - async fx() { - throw new MarketDataStoreNotImplementedError('fx'); - }, - }; - return { store, barsQueries, shortsQueries, eventsQueries }; -} - -interface LedgerRow { - readonly trial_id: string; - readonly created_at: Date; - readonly principal_id: string; - readonly campaign_id: string | null; - readonly stage: string; - readonly universe_market: string; - readonly horizon_bucket: string; - readonly hypothesis_id: string | null; - readonly expression_hash: string; - readonly sample_start: string; - readonly sample_end: string; - readonly n_obs: number; - readonly sharpe_unann: number; - readonly skewness: number; - readonly kurtosis: number; - readonly daily_series: readonly number[]; -} - -function createLedger(): { readonly executor: TrialLedgerExecutor; readonly rows: LedgerRow[] } { - const rows: LedgerRow[] = []; - const executor: TrialLedgerExecutor = { - async query>(text: string, params?: readonly unknown[]) { - const p = params ?? []; - if (text.trimStart().startsWith('INSERT INTO trial_ledger')) { - const id = rows.length + 1; - const row: LedgerRow = { - trial_id: String(id), - created_at: new Date(Date.UTC(2024, 6, 1, 0, 0, id)), - principal_id: p[0] as string, - campaign_id: (p[1] as string | null) ?? null, - stage: p[2] as string, - universe_market: p[3] as string, - horizon_bucket: p[4] as string, - hypothesis_id: (p[5] as string | null) ?? null, - expression_hash: p[6] as string, - sample_start: p[7] as string, - sample_end: p[8] as string, - n_obs: p[9] as number, - sharpe_unann: p[10] as number, - skewness: p[11] as number, - kurtosis: p[12] as number, - daily_series: (p[13] as readonly number[]).map(v => Math.fround(v)), - }; - rows.push(row); - return { - rows: [{ trial_id: row.trial_id, created_at: row.created_at } as unknown as Row], - rowCount: 1, - }; - } - if (text.includes('WHERE trial_id = $1::bigint')) { - const m = rows.filter(r => r.trial_id === String(p[0])); - return { rows: m as unknown as Row[], rowCount: m.length }; - } - if (text.includes('WHERE universe_market = $1')) { - const m = rows.filter(r => r.universe_market === p[0] && r.horizon_bucket === p[1]); - return { rows: m as unknown as Row[], rowCount: m.length }; - } - return { rows: [], rowCount: 0 }; - }, - }; - return { executor, rows }; -} - -interface Harness { - readonly options: ResearchCopilotMcpServerOptions; - readonly store: RecordingStore; - readonly ledger: ReturnType; - readonly stored: FiledFindingRecord[]; - readonly appendCalls: () => number; -} - -function buildHarness(fx: Fixture): Harness { - const store = createRecordingStore(fx); - const ledger = createLedger(); - const stored: FiledFindingRecord[] = []; - const byKey = new Map(); - let appends = 0; - let nextFinding = 1; - - const writePort: FindingWritePort = { - async appendFinding(record, key) { - appends += 1; - if (key !== undefined) { - const prior = byKey.get(key); - if (prior !== undefined) { - return areFiledFindingPayloadsEqual(prior, record) - ? { status: 'replayed', id: prior.id, createdAt: prior.createdAt } - : { status: 'conflict' }; - } - } - const copy = { ...record, trialRefs: [...record.trialRefs], evidenceRefs: [...record.evidenceRefs] }; - stored.push(copy); - if (key !== undefined) { - byKey.set(key, copy); - } - return { status: 'created', id: copy.id, createdAt: copy.createdAt }; - }, - }; - - const knowledge: KnowledgePort = { - async listLibraryCards() { - return []; - }, - async listFindings() { - return stored; - }, - async listProviderCaveats() { - return []; - }, - }; - - const options: ResearchCopilotMcpServerOptions = { - name: 'copilot-qa', - version: '0.0.1', - store: store.store, - vaultContext: { vaultCutoffTs: fx.cutoffTs }, - ledger: ledger.executor, - principalId: AGENT_PRINCIPAL, - searchSymbols: { - port: { - async searchSymbols() { - return fx.listingIds.map((listingId, i) => ({ - listingId, - instrumentId: 90_000 + i, - ticker: i === 0 ? 'QAQA' : `QA${i}`, - classSuffix: null, - name: `QA Equity ${i}`, - mic: 'XNYS', - currency: 'USD', - isin: null, - firstBarDate: fx.dates[0]!, - lastBarDate: fx.lastDate, - delistedAt: null, - })); - }, - }, - }, - eventStudy: { resolveExchangeCalendars: () => fx.calendars }, - fileFinding: { - port: writePort, - trialLookup: { - hasResearchVisibleTrial: ref => - ledger.rows.some(r => r.trial_id === ref && r.sample_end < fx.cutoffDate), - }, - newId: () => `finding-qa-${nextFinding++}`, - now: () => FIXED_NOW_MS, - }, - readKnowledge: { port: knowledge }, - }; - - return { options, store, ledger, stored, appendCalls: () => appends }; -} - -interface ToolEnvelope { - readonly content: readonly { readonly text: string }[]; - readonly isError?: boolean; -} - -async function callTool( - server: McpServer, - name: string, - args: Record -): Promise { - const raw = await server.handleMessage( - JSON.stringify({ jsonrpc: '2.0', id: name, method: 'tools/call', params: { name, arguments: args } }) - ); - const parsed = JSON.parse(raw!) as { result?: ToolEnvelope; error?: unknown }; - expect(parsed.error).toBeUndefined(); - return parsed.result!; -} - -function okJson(env: ToolEnvelope): T { - expect(env.isError).not.toBe(true); - return JSON.parse(env.content[0]!.text) as T; -} - -function signalArgs(fx: Fixture, overrides: Record = {}): Record { - return { - listingIds: [...fx.listingIds], - from: fx.dates[0]!, - to: fx.lastPreDate, - signal: { source: 'shorts', field: 'net_change' }, - horizonSessions: HORIZON, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - adjustment: 'raw', - ...overrides, - }; -} - -function eventArgs(fx: Fixture, overrides: Record = {}): Record { - return { - listingIds: [...fx.listingIds], - from: fx.dates[0]!, - to: fx.lastPreDate, - event: { kinds: ['filing'], subtypes: ['8-K'] }, - preDays: 2, - postDays: 5, - benchmark: 'equal_weight', - adjustment: 'raw', - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - ...overrides, - }; -} - -describe('createResearchCopilotMcpServer QA', () => { - test('straddling query_data, analyze_signal and event_study send only clamped pre-cutoff bounds to the store', async () => { - const fx = buildFixture(); - const h = buildHarness(fx); - const server = createResearchCopilotMcpServer(h.options); - - await callTool(server, 'query_data', { - listingIds: [fx.listingIds[0]!], - from: fx.dates[0]!, - to: fx.lastDate, - asOf: fx.lastDate, - timeframe: '1d', - adjustment: 'raw', - }); - const sig = okJson( - await callTool(server, 'analyze_signal', signalArgs(fx, { to: fx.lastDate, asOf: fx.lastDate })) - ); - const ev = okJson( - await callTool(server, 'event_study', eventArgs(fx, { to: fx.lastDate, asOf: fx.lastDate })) - ); - - expect(sig.status).toBe('ok'); - expect(ev.status).toBe('ok'); - expect(ev.clampedTo).toBe(true); - expect(ev.toMs).toBe(fx.cutoffTs - 1); - - // query_data + analyze_signal + event_study each read bars once. - expect(h.store.barsQueries).toHaveLength(3); - expect(h.store.shortsQueries).toHaveLength(1); - expect(h.store.eventsQueries).toHaveLength(1); - const all: { readonly to: string; readonly asOf?: string }[] = [ - ...h.store.barsQueries, - ...h.store.shortsQueries, - ...h.store.eventsQueries, - ]; - for (const q of all) { - expect(q.to.startsWith(new Date(fx.cutoffTs - 1).toISOString().slice(0, 19))).toBe(true); - expect(boundMs(q.to, true)).toBe(fx.cutoffTs - 1); - expect(q.asOf).toBeDefined(); - expect(boundMs(q.asOf!, true)).toBe(fx.cutoffTs - 1); - } - for (const q of h.store.barsQueries) { - expect(q.scope).toBe('vault_fenced'); - } - // Event-study trial stays pre-cutoff too. - expect(h.ledger.rows.map(r => r.stage)).toEqual(['signal_ic', 'event_study']); - for (const row of h.ledger.rows) { - expect(row.sample_end < fx.cutoffDate).toBe(true); - } - }); - - test('analyze_signal trial covers the exact pinned formation window (first actionable session through cutoff minus horizon)', async () => { - const fx = buildFixture(); - const h = buildHarness(fx); - const server = createResearchCopilotMcpServer(h.options); - - const sig = okJson( - await callTool(server, 'analyze_signal', signalArgs(fx, { to: fx.lastDate })) - ); - expect(sig.status).toBe('ok'); - if (sig.status !== 'ok') { - throw new Error('expected ok'); - } - - // First report (index 0) becomes known 22:00 UTC on index 3, after that day's 21:00 close, - // so the first eligible formation session is index 4. The last formation session whose - // 5-session forward endpoint is still pre-cutoff is index 59 - 5 = 54. - const expectedStart = fx.dates[4]!; - const expectedEnd = fx.dates[PRE_CUTOFF_SESSIONS - 1 - HORIZON]!; - expect(fx.dates[PRE_CUTOFF_SESSIONS - 1 - HORIZON + HORIZON]).toBe(fx.lastPreDate); - - expect(h.ledger.rows).toHaveLength(1); - const row = h.ledger.rows[0]!; - expect(row.trial_id).toBe(String(sig.trial.trialId)); - expect(row.principal_id).toBe(AGENT_PRINCIPAL); - expect(row.sample_start).toBe(expectedStart); - expect(row.sample_end).toBe(expectedEnd); - // One daily IC observation per formation session, none dropped. - expect(row.daily_series).toHaveLength(PRE_CUTOFF_SESSIONS - HORIZON - 4); - expect(row.n_obs).toBe(row.daily_series.length); - }); - - test('a replay on fresh servers with the same inputs produces an identical stdio transcript and ledger', async () => { - const fx = buildFixture(); - - async function runSession(): Promise<{ readonly lines: string[]; readonly ledger: LedgerRow[] }> { - const h = buildHarness(fx); - const server = createResearchCopilotMcpServer(h.options); - const lines: string[] = []; - let buf = ''; - const output: StdioOutput = { - write(chunk: string) { - buf += chunk; - let i = buf.indexOf('\n'); - while (i !== -1) { - lines.push(buf.slice(0, i)); - buf = buf.slice(i + 1); - i = buf.indexOf('\n'); - } - return true; - }, - }; - async function* input(): AsyncGenerator { - const calls: [string, Record][] = [ - ['analyze_signal', signalArgs(fx)], - ['event_study', eventArgs(fx)], - ]; - let id = 1; - for (const [name, args] of calls) { - yield `${JSON.stringify({ jsonrpc: '2.0', id: id++, method: 'tools/call', params: { name, arguments: args } })}\n`; - } - yield `${JSON.stringify({ - jsonrpc: '2.0', - id: id++, - method: 'tools/call', - params: { - name: 'file_finding', - arguments: { - kind: 'finding', - title: 'Replay finding', - summary: `Dataset ${FIXTURE_DATASET_ID}, pre-Vault only.`, - trialRefs: ['1'], - evidenceRefs: [FIXTURE_DATASET_ID], - }, - }, - })}\n`; - } - await runStdioServer(server, { input: input(), output }); - return { lines, ledger: h.ledger.rows }; - } - - const a = await runSession(); - const b = await runSession(); - expect(a.lines).toHaveLength(3); - expect(b.lines).toEqual(a.lines); - expect(b.ledger).toEqual(a.ledger); - expect(JSON.parse(a.lines[2]!).result.isError).not.toBe(true); - }); - - test('file_finding through the composed server rejects unknown trial refs, replays idempotent retries, and read_knowledge reads the filed record back', async () => { - const fx = buildFixture(); - const h = buildHarness(fx); - const server = createResearchCopilotMcpServer(h.options); - - const unknown = await callTool(server, 'file_finding', { - kind: 'finding', - title: 'No trial yet', - summary: 'Should be rejected.', - trialRefs: ['999'], - }); - expect(unknown.isError).toBe(true); - expect(h.appendCalls()).toBe(0); - - const sig = okJson(await callTool(server, 'analyze_signal', signalArgs(fx))); - if (sig.status !== 'ok') { - throw new Error('expected ok'); - } - const args = { - kind: 'finding', - title: 'Shorts net_change IC', - summary: `Dataset ${FIXTURE_DATASET_ID}.`, - trialRefs: [String(sig.trial.trialId)], - evidenceRefs: [FIXTURE_DATASET_ID], - idempotencyKey: 'qa-key-1', - }; - const first = okJson(await callTool(server, 'file_finding', args)); - const retry = okJson(await callTool(server, 'file_finding', args)); - expect(first.created).toBe(true); - expect(retry).toEqual({ id: first.id, createdAt: first.createdAt, created: false }); - expect(h.stored).toHaveLength(1); - - const conflict = await callTool(server, 'file_finding', { ...args, title: 'Different title' }); - expect(conflict.isError).toBe(true); - expect(h.stored).toHaveLength(1); - - const read = okJson( - await callTool(server, 'read_knowledge', { source: 'findings', id: first.id }) - ); - expect(read.rowCount).toBe(1); - expect(read.rows[0]?.id).toBe(first.id); - }); - - test('shared vaultContext and store stay authoritative over stray per-tool overrides', async () => { - const fx = buildFixture(); - const h = buildHarness(fx); - const throwingStore = new Proxy( - {}, - { - get() { - throw new Error('per-tool store override must not be used'); - }, - } - ); - const options = { - ...h.options, - // Runtime callers can bypass the Omit/Pick types; the composed server must ignore these. - searchSymbols: { - ...h.options.searchSymbols, - vaultContext: { vaultCutoffTs: utcMs(fx.lastDate, 23) + 86_400_000 }, - }, - eventStudy: { ...h.options.eventStudy, store: throwingStore, vaultContext: { vaultCutoffTs: 8.64e15 } }, - } as unknown as ResearchCopilotMcpServerOptions; - const server = createResearchCopilotMcpServer(options); - - const search = okJson( - await callTool(server, 'search_symbols', { query: 'QAQA', limit: 5 }) - ); - expect(search.rows[0]?.lastBarDate).toBe(fx.cutoffDate); - - const ev = okJson( - await callTool(server, 'event_study', eventArgs(fx, { to: fx.lastDate })) - ); - expect(ev.status).toBe('ok'); - expect(ev.toMs).toBe(fx.cutoffTs - 1); - expect(h.store.eventsQueries).toHaveLength(1); - }); - - test('rejects invalid option objects and out-of-order tool registration', () => { - const fx = buildFixture(); - const h = buildHarness(fx); - - expect(() => createResearchCopilotMcpServer(null as never)).toThrow(/Invalid `options`/); - expect(() => - createResearchCopilotMcpServer({ ...h.options, searchSymbols: null } as never) - ).toThrow(/Invalid `searchSymbols`/); - expect(() => - createResearchCopilotMcpServer({ ...h.options, eventStudy: undefined } as never) - ).toThrow(/Invalid `eventStudy`/); - - const realQuery = queryDataToolModule.createQueryDataTool(h.options); - const realSignal = analyzeSignalToolModule.createAnalyzeSignalTool(h.options); - const qSpy = spyOn(queryDataToolModule, 'createQueryDataTool').mockImplementation(() => realSignal); - const sSpy = spyOn(analyzeSignalToolModule, 'createAnalyzeSignalTool').mockImplementation( - () => realQuery - ); - try { - expect(() => createResearchCopilotMcpServer(h.options)).toThrow( - /index 1: expected "query_data", got "analyze_signal"/ - ); - } finally { - qSpy.mockRestore(); - sSpy.mockRestore(); - } - - // Restored spies: composition succeeds again with the fixed order. - const server = createResearchCopilotMcpServer(h.options); - expect(server.listTools().map(t => t.name)).toEqual([...RESEARCH_COPILOT_TOOL_NAMES]); - }); - - test('is importable through the @stock-bot/research/mcp package subpath', async () => { - const mod = await import('@stock-bot/research/mcp'); - expect(mod.createResearchCopilotMcpServer).toBe(createResearchCopilotMcpServer); - expect(mod.RESEARCH_COPILOT_TOOL_NAMES).toBe(RESEARCH_COPILOT_TOOL_NAMES); - }); -}); diff --git a/libs/research/test/mcp-copilot-server.test.ts b/libs/research/test/mcp-copilot-server.test.ts deleted file mode 100644 index 8bd18a11..00000000 --- a/libs/research/test/mcp-copilot-server.test.ts +++ /dev/null @@ -1,1354 +0,0 @@ -import { describe, expect, spyOn, test } from 'bun:test'; -import type { EventStudyExchangeCalendars } from '../src/event-panel'; -import { - type BarBatch, - type BarRecord, - type EventKind, - type MarketDataStore, - type Table, - type TableRow, -} from '../src/market-data-store'; -import { - EVENTS_COLUMNS, - MarketDataStoreNotImplementedError, -} from '../src/market-data-store-duckdb'; -import { - type AnalyzeSignalResultPayload, - type AppendFindingResult, - type EventStudyResultPayload, - type FileFindingResultPayload, - type FiledFindingRecord, - type FindingWritePort, - JSON_RPC_ERROR_CODES, - type KnowledgePort, - type McpToolDescriptor, - type QueryDataResultPayload, - RESEARCH_COPILOT_TOOL_NAMES, - type ReadKnowledgeResultPayload, - type ResearchCopilotMcpServerOptions, - type SearchSymbolsResultPayload, - type StdioOutput, - type SymbolSearchPort, - type SymbolSearchRow, - areFiledFindingPayloadsEqual, - createResearchCopilotMcpServer, - runStdioServer, -} from '../src/mcp/index'; -import * as queryDataToolModule from '../src/mcp/tools/query-data'; -import * as readKnowledgeToolModule from '../src/mcp/tools/read-knowledge'; -import type { TrialLedgerExecutor } from '../src/trial-ledger'; - -// Synthetic headless-study fixture metadata (pinned for reproducibility): -// - Dataset ID: `synthetic:mcp-copilot-e2e:seed-20261201:v1` -// - Seed: `20261201` (Mulberry32 PRNG) -// - Universe: 16 synthetic US equity listings (`50001..50016`, XNYS, USD, 21:00 UTC close) -// - Sessions: 80 pre-cutoff + 8 post-cutoff business sessions starting `2022-11-01` -// - Cutoff: `vaultCutoffDate` = `allDates[80]` (`vaultCutoffTs = Date.UTC(..., 0, 0, 0)`) -// - Economic assumptions: daily raw close-to-close returns, zero modeled execution/transaction -// costs; `event_study` uses `benchmark: 'equal_weight'` over eligible listing returns. -// - Ownership: Quant research role owns the economic specification; `AGENT_PRINCIPAL` owns -// the recorded `trial_ledger` rows. -const FIXTURE_DATASET_ID = 'synthetic:mcp-copilot-e2e:seed-20261201:v1'; -const SEED = 20261201; -const SERVER_NAME = 'stock-bot-research-copilot'; -const SERVER_VERSION = '0.1.0'; -const AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555'; -const FIXED_FINDING_ID = 'finding-copilot-e2e-001'; -const FIXED_NOW_ISO = '2024-06-01T15:30:00.000Z'; -const FIXED_NOW_MS = Date.parse(FIXED_NOW_ISO); - -const EXPECTED_TOOL_NAMES = [ - 'search_symbols', - 'query_data', - 'analyze_signal', - 'event_study', - 'file_finding', - 'read_knowledge', -] as const; - -const SHORTS_COLUMNS = [ - 'listing_id', - 'report_date', - 'known_at', - 'shares_short', - 'net_change', - 'pct_float', - 'source', -] as const; - -function createSeededRng(seed: number): () => number { - let state = seed >>> 0; - return () => { - state = (state + 0x6d2b79f5) >>> 0; - let t = Math.imul(state ^ (state >>> 15), 1 | state); - t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; - return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296; - }; -} - -function makeBusinessDates(startDate: string, count: number): string[] { - const out: string[] = new Array(count); - const current = new Date(`${startDate}T00:00:00.000Z`); - let written = 0; - while (written < count) { - const day = current.getUTCDay(); - if (day !== 0 && day !== 6) { - out[written] = current.toISOString().slice(0, 10); - written += 1; - } - current.setUTCDate(current.getUTCDate() + 1); - } - return out; -} - -function makeUtcMs(date: string, hourUtc: number, minuteUtc = 0): number { - const [y, m, d] = date.split('-').map(Number); - return Date.UTC(y!, m! - 1, d!, hourUtc, minuteUtc, 0, 0); -} - -function parseBoundMs(raw: string, endOfDay: boolean): number { - if (raw.length === 10) { - return Date.parse(`${raw}T${endOfDay ? '23:59:59.999' : '00:00:00.000'}Z`); - } - return Date.parse(raw); -} - -interface StoredTrialRow { - readonly trial_id: string; - readonly created_at: Date; - readonly principal_id: string; - readonly campaign_id: string | null; - readonly stage: string; - readonly universe_market: string; - readonly horizon_bucket: string; - readonly hypothesis_id: string | null; - readonly expression_hash: string; - readonly sample_start: string; - readonly sample_end: string; - readonly n_obs: number; - readonly sharpe_unann: number; - readonly skewness: number; - readonly kurtosis: number; - readonly daily_series: readonly number[]; -} - -function createFakeTrialLedger(): { - readonly executor: TrialLedgerExecutor; - readonly rows: StoredTrialRow[]; - readonly getInsertCalls: () => number; - readonly getSelectCalls: () => number; -} { - const rows: StoredTrialRow[] = []; - let nextTrialId = 1; - let insertCalls = 0; - let selectCalls = 0; - - const executor: TrialLedgerExecutor = { - async query>(text: string, params?: readonly unknown[]) { - const trimmed = text.trimStart(); - if (trimmed.startsWith('INSERT INTO trial_ledger')) { - insertCalls += 1; - const p = params ?? []; - const trialId = nextTrialId++; - const createdAt = new Date(Date.UTC(2024, 5, 1, 12, 0, trialId)); - const dailySeries = (p[13] as readonly number[]).map(v => Math.fround(v)); - const stored: StoredTrialRow = { - trial_id: String(trialId), - created_at: createdAt, - principal_id: p[0] as string, - campaign_id: (p[1] as string | null) ?? null, - stage: p[2] as string, - universe_market: p[3] as string, - horizon_bucket: p[4] as string, - hypothesis_id: (p[5] as string | null) ?? null, - expression_hash: p[6] as string, - sample_start: p[7] as string, - sample_end: p[8] as string, - n_obs: p[9] as number, - sharpe_unann: p[10] as number, - skewness: p[11] as number, - kurtosis: p[12] as number, - daily_series: dailySeries, - }; - rows.push(stored); - return { - rows: [{ trial_id: stored.trial_id, created_at: stored.created_at } as unknown as Row], - rowCount: 1, - }; - } - - if (trimmed.startsWith('SELECT')) { - selectCalls += 1; - if (text.includes('WHERE trial_id = $1::bigint')) { - const targetId = String(params?.[0]); - const matched = rows.filter(r => r.trial_id === targetId); - return { rows: matched as unknown as Row[], rowCount: matched.length }; - } - if (text.includes('WHERE universe_market = $1')) { - const market = params?.[0] as string; - const bucket = params?.[1] as string; - const matched = rows.filter( - r => r.universe_market === market && r.horizon_bucket === bucket - ); - return { rows: matched as unknown as Row[], rowCount: matched.length }; - } - } - - return { rows: [], rowCount: 0 }; - }, - }; - - return { - executor, - rows, - getInsertCalls: () => insertCalls, - getSelectCalls: () => selectCalls, - }; -} - -interface CopilotStudyFixture { - readonly listingIds: readonly number[]; - readonly allDates: readonly string[]; - readonly preCutoffSessions: number; - readonly firstDate: string; - readonly lastPreCutoffDate: string; - readonly vaultCutoffDate: string; - readonly vaultCutoffTs: number; - readonly postCutoffDate: string; - readonly bars: readonly BarRecord[]; - readonly shortsTable: Table; - readonly fundamentalsRows: readonly TableRow[]; - readonly eventsTable: Table; - readonly symbols: readonly SymbolSearchRow[]; - readonly exchangeCalendars: EventStudyExchangeCalendars; -} - -function buildCopilotStudyFixture(): CopilotStudyFixture { - const rand = createSeededRng(SEED); - const listingCount = 16; - const preCutoffSessions = 80; - const postCutoffSessions = 8; - - const allDates = makeBusinessDates('2022-11-01', preCutoffSessions + postCutoffSessions); - const firstDate = allDates[0]!; - const lastPreCutoffDate = allDates[preCutoffSessions - 1]!; - const vaultCutoffDate = allDates[preCutoffSessions]!; - const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0); - const postCutoffDate = allDates[allDates.length - 1]!; - - const listingIds = Array.from({ length: listingCount }, (_, i) => 50_001 + i); - const bars: BarRecord[] = []; - const shortsRows: TableRow[] = []; - const fundamentalsRows: TableRow[] = []; - const eventRows: TableRow[] = []; - - const fundamentalReleaseIndices = [0, 22, 44, 64]; - for (let rIdx = 0; rIdx < fundamentalReleaseIndices.length; rIdx += 1) { - const t = fundamentalReleaseIndices[rIdx]!; - const relDate = allDates[t]!; - const effectiveKnownAt = makeUtcMs(relDate, 13); // 08:00 ET pre-close - for (let l = 0; l < listingCount; l += 1) { - const revenue = 250 + ((l * 7 + rIdx * 5) % listingCount) * 40 + rIdx * 15; - const ttmRevenue = revenue * 4 + ((l + rIdx) % 4) * 25; - fundamentalsRows.push({ - listing_id: listingIds[l]!, - effective_known_at: effectiveKnownAt, - known_at_source: 'sec_edgar_filing', - has_estimated_lag: false, - period_end: relDate, - fiscal_period: `Q${(rIdx % 4) + 1}`, - currency: 'USD', - period_known_at: effectiveKnownAt, - revenue, - net_income: Number((revenue * 0.14).toFixed(2)), - operating_cash_flow: Number((revenue * 0.19).toFixed(2)), - total_assets: Number((revenue * 3.8).toFixed(2)), - total_equity: Number((revenue * 1.7).toFixed(2)), - shares_outstanding: 10_000_000, - ttm_revenue: ttmRevenue, - ttm_net_income: Number((ttmRevenue * 0.14).toFixed(2)), - ttm_operating_cash_flow: Number((ttmRevenue * 0.19).toFixed(2)), - ttm_period_end: relDate, - ttm_currency: 'USD', - ttm_has_estimated_lag: false, - }); - } - } - - const eventDayIndices = [12, 20, 28, 38, 48, 58]; - const eventSet = new Set(); - for (let eIdx = 0; eIdx < eventDayIndices.length; eIdx += 1) { - const t = eventDayIndices[eIdx]!; - const date = allDates[t]!; - const ts = makeUtcMs(date, 14); // 09:00 ET intraday filing -> anchors on same session - for (let k = 0; k < 2; k += 1) { - const l = (eIdx * 2 + k) % listingCount; - eventSet.add(`${t}:${l}`); - const kind: EventKind = 'filing'; - eventRows.push({ - listing_id: listingIds[l]!, - ts, - known_at: ts, - known_at_source: 'exact', - kind, - subtype: '8-K', - payload_json: '{}', - }); - } - } - - const publicationLagSessions = 3; - const activeSignal = new Float64Array(listingCount); - const pendingByPublishIdx = new Map(); - const prices = new Float64Array(listingCount); - for (let l = 0; l < listingCount; l += 1) { - prices[l] = 15 + l * 2.5; - } - - for (let t = 0; t < allDates.length; t += 1) { - const date = allDates[t]!; - const closeTs = makeUtcMs(date, 21); // 16:00 ET close - - const released = pendingByPublishIdx.get(t - 1); - if (released !== undefined) { - for (let l = 0; l < listingCount; l += 1) { - activeSignal[l] = (released[l] ?? 0) / 20_000; - } - } - - const publishIdx = t + publicationLagSessions; - if (t % 5 === 0 && publishIdx < allDates.length) { - const reportKnownAt = makeUtcMs(allDates[publishIdx]!, 22); // 17:00 ET on T+3 - const pending: number[] = []; - for (let l = 0; l < listingCount; l += 1) { - const netChange = Math.round((rand() * 2 - 1) * 20_000); - pending.push(netChange); - shortsRows.push({ - listing_id: listingIds[l]!, - report_date: date, - known_at: reportKnownAt, - shares_short: 100_000 + l * 4_000 + Math.round(rand() * 10_000), - net_change: netChange, - pct_float: Number((0.02 + rand() * 0.08).toFixed(4)), - source: 'ceoShorts', - }); - } - pendingByPublishIdx.set(publishIdx, pending); - } - - for (let l = 0; l < listingCount; l += 1) { - let eventDrift = 0; - for (let offset = 0; offset <= 3; offset += 1) { - if (eventSet.has(`${t - offset}:${l}`)) { - eventDrift += 0.006 * (1 + ((l + t) % 3) * 0.25); - } - } - const dailyRet = -0.004 * activeSignal[l]! + eventDrift + (rand() * 2 - 1) * 0.009; - prices[l] = Math.max(1.0, prices[l]! * (1 + dailyRet)); - const close = Number(prices[l]!.toFixed(4)); - bars.push({ - listingId: listingIds[l]!, - ts: closeTs, - open: Number((close * 0.995).toFixed(4)), - high: Number((close * 1.01).toFixed(4)), - low: Number((close * 0.99).toFixed(4)), - close, - volume: 50_000 + l * 1_500 + t * 100, - vwap: close, - knownAt: closeTs, - }); - } - } - - const symbols: SymbolSearchRow[] = listingIds.map((listingId, idx) => ({ - listingId, - instrumentId: 80_001 + idx, - ticker: idx === 0 ? 'ACME' : `SYN${idx}`, - classSuffix: null, - name: idx === 0 ? 'Acme Synthetic Corp' : `Synthetic Equity ${idx}`, - mic: 'XNYS', - currency: 'USD', - isin: `US000000${String(idx).padStart(4, '0')}`, - firstBarDate: firstDate, - lastBarDate: postCutoffDate, - delistedAt: null, - })); - - const xnysSessions = allDates.map(date => ({ - date, - closeTs: makeUtcMs(date, 21), - })); - const listingCalendarId = new Map(); - for (const id of listingIds) { - listingCalendarId.set(id, 'XNYS'); - } - - return { - listingIds, - allDates, - preCutoffSessions, - firstDate, - lastPreCutoffDate, - vaultCutoffDate, - vaultCutoffTs, - postCutoffDate, - bars, - shortsTable: { - columns: [...SHORTS_COLUMNS], - rows: shortsRows, - }, - fundamentalsRows, - eventsTable: { - columns: [...EVENTS_COLUMNS], - rows: eventRows, - }, - symbols, - exchangeCalendars: { - calendars: { XNYS: xnysSessions }, - listingCalendarId, - }, - }; -} - -interface FakeMarketDataStoreHandle { - readonly store: MarketDataStore; - readonly getBarsCalls: () => number; - readonly getShortsCalls: () => number; - readonly getFundamentalsCalls: () => number; - readonly getEventsCalls: () => number; - readonly getUniverseCalls: () => number; -} - -function createFakeMarketDataStore( - fixture: CopilotStudyFixture, - options?: { - readonly leakyVaultRows?: boolean; - } -): FakeMarketDataStoreHandle { - const leaky = options?.leakyVaultRows ?? false; - let barsCalls = 0; - let shortsCalls = 0; - let fundamentalsCalls = 0; - let eventsCalls = 0; - let universeCalls = 0; - - // Deliberately leaky rows: - // 1) Bar at exact vaultCutoffTs and after vaultCutoffTs (by ts) - // 2) Bar with pre-cutoff ts (early observation) but late knownAt >= vaultCutoffTs - // 3) Short row with pre-cutoff report_date but late known_at >= vaultCutoffTs - const leakyBars: BarRecord[] = [ - { - listingId: fixture.listingIds[0]!, - ts: fixture.vaultCutoffTs, - open: 999, - high: 999, - low: 999, - close: 999, - volume: 1000, - vwap: 999, - knownAt: fixture.vaultCutoffTs, - }, - { - listingId: fixture.listingIds[1]!, - ts: makeUtcMs(fixture.postCutoffDate, 21), - open: 888, - high: 888, - low: 888, - close: 888, - volume: 1000, - vwap: 888, - knownAt: makeUtcMs(fixture.postCutoffDate, 21), - }, - { - listingId: fixture.listingIds[0]!, - ts: makeUtcMs(fixture.lastPreCutoffDate, 21), - open: 777, - high: 777, - low: 777, - close: 777, - volume: 1000, - vwap: 777, - knownAt: fixture.vaultCutoffTs + 60_000, - }, - ]; - - const leakyShortsRows: TableRow[] = [ - { - listing_id: fixture.listingIds[0]!, - report_date: fixture.lastPreCutoffDate, - known_at: fixture.vaultCutoffTs + 120_000, - shares_short: 999_999, - net_change: 500_000, - pct_float: 0.99, - source: 'ceoShorts', - }, - { - listing_id: fixture.listingIds[1]!, - report_date: fixture.vaultCutoffDate, - known_at: fixture.vaultCutoffTs, - shares_short: 888_888, - net_change: -500_000, - pct_float: 0.88, - source: 'ceoShorts', - }, - ]; - - const store: MarketDataStore = { - bars(q): AsyncIterable { - barsCalls += 1; - const idSet = new Set(q.listingIds); - const fromMs = parseBoundMs(q.from, false); - const toMs = parseBoundMs(q.to, true); - const asOfMs = q.asOf !== undefined ? parseBoundMs(q.asOf, true) : Number.POSITIVE_INFINITY; - - const filtered = fixture.bars.filter( - row => - idSet.has(row.listingId) && - row.ts >= fromMs && - row.ts <= toMs && - row.knownAt <= asOfMs - ); - const out = leaky ? [...filtered, ...leakyBars] : filtered; - - return { - async *[Symbol.asyncIterator]() { - yield { rows: out }; - }, - }; - }, - - async universe() { - universeCalls += 1; - return [...fixture.listingIds]; - }, - - async shortsAsOf(q): Promise
{ - shortsCalls += 1; - const idSet = new Set(q.listingIds); - const fromDate = q.from.slice(0, 10); - const toDate = q.to.slice(0, 10); - const asOfMs = q.asOf !== undefined ? parseBoundMs(q.asOf, true) : Number.POSITIVE_INFINITY; - - const filtered = fixture.shortsTable.rows.filter(row => { - const listingId = row.listing_id as number; - const reportDate = row.report_date as string; - const knownAt = row.known_at as number; - return ( - idSet.has(listingId) && - reportDate >= fromDate && - reportDate <= toDate && - knownAt <= asOfMs - ); - }); - - return { - columns: fixture.shortsTable.columns, - rows: leaky ? [...filtered, ...leakyShortsRows] : filtered, - }; - }, - - async events(q): Promise
{ - eventsCalls += 1; - const idSet = q.listingIds !== undefined ? new Set(q.listingIds) : null; - const kindSet = new Set(q.kinds); - const fromMs = parseBoundMs(q.from, false); - const toMs = parseBoundMs(q.to, true); - const asOfMs = q.asOf !== undefined ? parseBoundMs(q.asOf, true) : Number.POSITIVE_INFINITY; - - const filtered = fixture.eventsTable.rows.filter(row => { - const listingId = row.listing_id as number; - const kind = row.kind as EventKind; - const ts = row.ts as number; - const knownAt = row.known_at as number; - if (idSet !== null && !idSet.has(listingId)) { - return false; - } - return kindSet.has(kind) && ts >= fromMs && ts <= toMs && knownAt <= asOfMs; - }); - - return { - columns: fixture.eventsTable.columns, - rows: filtered, - }; - }, - - async crossSection() { - throw new MarketDataStoreNotImplementedError('crossSection'); - }, - async fundamentalsAsOf(q): Promise
{ - fundamentalsCalls += 1; - const idSet = new Set(q.listingIds); - const asOfMs = parseBoundMs(q.asOf, true); - const allowEstimatedLag = q.allowEstimatedLag ?? false; - const latestByListing = new Map(); - - for (const row of fixture.fundamentalsRows) { - const listingId = row.listing_id as number; - const knownAt = row.effective_known_at as number; - if (!idSet.has(listingId) || knownAt > asOfMs) { - continue; - } - const prev = latestByListing.get(listingId); - if (prev === undefined || knownAt > (prev.effective_known_at as number)) { - latestByListing.set(listingId, row); - } - } - - const rows: TableRow[] = []; - for (const lid of [...latestByListing.keys()].sort((a, b) => a - b)) { - const row = latestByListing.get(lid)!; - if (!allowEstimatedLag && row.has_estimated_lag === true) { - continue; - } - rows.push(row); - } - - if (leaky) { - rows.push({ - listing_id: fixture.listingIds[0]!, - effective_known_at: fixture.vaultCutoffTs, - known_at_source: 'sec_edgar_filing', - has_estimated_lag: false, - period_end: fixture.vaultCutoffDate, - fiscal_period: 'Q4', - currency: 'USD', - period_known_at: fixture.vaultCutoffTs, - revenue: 999_999, - ttm_revenue: 999_999, - }); - } - - return { - columns: [ - 'listing_id', - 'effective_known_at', - 'known_at_source', - 'has_estimated_lag', - 'period_end', - 'fiscal_period', - 'currency', - 'period_known_at', - ...q.fields, - ], - rows, - }; - }, - async macroAsOf() { - throw new MarketDataStoreNotImplementedError('macroAsOf'); - }, - async fx() { - throw new MarketDataStoreNotImplementedError('fx'); - }, - }; - - return { - store, - getBarsCalls: () => barsCalls, - getShortsCalls: () => shortsCalls, - getFundamentalsCalls: () => fundamentalsCalls, - getEventsCalls: () => eventsCalls, - getUniverseCalls: () => universeCalls, - }; -} - -interface FakeFindingStore { - readonly stored: FiledFindingRecord[]; - readonly appendCalls: { - readonly record: FiledFindingRecord; - readonly idempotencyKey?: string; - }[]; - readonly writePort: FindingWritePort; -} - -function createFakeFindingStore(): FakeFindingStore { - const stored: FiledFindingRecord[] = []; - const byIdempotencyKey = new Map(); - const appendCalls: { readonly record: FiledFindingRecord; readonly idempotencyKey?: string }[] = - []; - - const writePort: FindingWritePort = { - async appendFinding( - record: FiledFindingRecord, - idempotencyKey?: string - ): Promise { - appendCalls.push({ record, idempotencyKey }); - if (idempotencyKey !== undefined) { - const existing = byIdempotencyKey.get(idempotencyKey); - if (existing !== undefined) { - if (areFiledFindingPayloadsEqual(existing, record)) { - return { status: 'replayed', id: existing.id, createdAt: existing.createdAt }; - } - return { status: 'conflict' }; - } - } - const copy: FiledFindingRecord = { - ...record, - trialRefs: [...record.trialRefs], - evidenceRefs: [...record.evidenceRefs], - }; - stored.push(copy); - if (idempotencyKey !== undefined) { - byIdempotencyKey.set(idempotencyKey, copy); - } - return { status: 'created', id: copy.id, createdAt: copy.createdAt }; - }, - }; - - return { stored, appendCalls, writePort }; -} - -function createMemoryOutput(): { - readonly output: StdioOutput; - readonly lines: string[]; - readonly text: () => string; -} { - const chunks: string[] = []; - const lines: string[] = []; - let pending = ''; - - const output: StdioOutput = { - write(chunk: string): boolean { - chunks.push(chunk); - pending += chunk; - while (true) { - const idx = pending.indexOf('\n'); - if (idx === -1) { - break; - } - lines.push(pending.slice(0, idx)); - pending = pending.slice(idx + 1); - } - return true; - }, - }; - - return { - output, - lines, - text: () => chunks.join(''), - }; -} - -interface JsonRpcResponseEnvelope { - readonly jsonrpc: '2.0'; - readonly id: number | string | null; - readonly result?: unknown; - readonly error?: { - readonly code: number; - readonly message: string; - }; -} - -interface ToolCallEnvelope { - readonly content: readonly { readonly type: 'text'; readonly text: string }[]; - readonly isError?: boolean; -} - -function buildComposedServerOptions( - fixture: CopilotStudyFixture, - options?: { readonly leakyVaultRows?: boolean } -): { - readonly serverOptions: ResearchCopilotMcpServerOptions; - readonly storeHandle: FakeMarketDataStoreHandle; - readonly ledger: ReturnType; - readonly findings: FakeFindingStore; -} { - const storeHandle = createFakeMarketDataStore(fixture, { - leakyVaultRows: options?.leakyVaultRows, - }); - const ledger = createFakeTrialLedger(); - const findings = createFakeFindingStore(); - - const symbolSearchPort: SymbolSearchPort = { - async searchSymbols() { - return fixture.symbols; - }, - }; - - const knowledgePort: KnowledgePort = { - async listLibraryCards() { - return [ - { - id: 'card-dsr-01', - title: 'Deflated Sharpe & Effective Trials', - tags: ['dsr', 'rigor'], - summary: 'Adjust Sharpe ratios for multiple testing across relatedness clusters.', - body: 'Use clusterDeflatedSharpe with pre-Vault series and record every trial.', - }, - ]; - }, - async listFindings() { - return findings.stored; - }, - async listProviderCaveats() { - return [ - { - id: 'caveat-shorts-01', - provider: 'ceoShorts', - dataset: 'shorts', - caveat: 'Short-interest reports carry a multi-session publication lag.', - createdAt: '2024-01-15T00:00:00.000Z', - }, - ]; - }, - }; - - const serverOptions: ResearchCopilotMcpServerOptions = { - name: SERVER_NAME, - version: SERVER_VERSION, - store: storeHandle.store, - vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, - ledger: ledger.executor, - principalId: AGENT_PRINCIPAL, - searchSymbols: { port: symbolSearchPort }, - eventStudy: { - resolveExchangeCalendars: () => fixture.exchangeCalendars, - }, - fileFinding: { - port: findings.writePort, - trialLookup: { - hasResearchVisibleTrial(ref: string): boolean { - return ledger.rows.some( - row => row.trial_id === ref && row.sample_end < fixture.vaultCutoffDate - ); - }, - }, - newId: () => FIXED_FINDING_ID, - now: () => FIXED_NOW_MS, - }, - readKnowledge: { port: knowledgePort }, - }; - - return { serverOptions, storeHandle, ledger, findings }; -} - -function decodeToolJson(response: JsonRpcResponseEnvelope): T { - expect(response.error).toBeUndefined(); - const result = response.result as ToolCallEnvelope; - expect(result.isError).not.toBe(true); - expect(result.content).toHaveLength(1); - return JSON.parse(result.content[0]!.text) as T; -} - -describe('createResearchCopilotMcpServer', () => { - test('tools/list returns the six literal expected tool names in fixed order with object inputSchemas', async () => { - const fixture = buildCopilotStudyFixture(); - const { serverOptions } = buildComposedServerOptions(fixture); - const server = createResearchCopilotMcpServer(serverOptions); - - expect(Object.isFrozen(RESEARCH_COPILOT_TOOL_NAMES)).toBe(true); - expect([...RESEARCH_COPILOT_TOOL_NAMES]).toEqual([...EXPECTED_TOOL_NAMES]); - - const rawResponse = await server.handleMessage( - JSON.stringify({ jsonrpc: '2.0', id: 'list-1', method: 'tools/list' }) - ); - expect(rawResponse).not.toBeNull(); - const parsed = JSON.parse(rawResponse!) as JsonRpcResponseEnvelope; - expect(parsed.error).toBeUndefined(); - const tools = (parsed.result as { tools: readonly McpToolDescriptor[] }).tools; - - expect(tools.map(t => t.name)).toEqual([...EXPECTED_TOOL_NAMES]); - expect(tools.map(t => t.name)).toEqual([...RESEARCH_COPILOT_TOOL_NAMES]); - - for (const tool of tools) { - expect(tool.inputSchema.type).toBe('object'); - expect(typeof tool.inputSchema.properties).toBe('object'); - expect(tool.inputSchema.properties).not.toBeNull(); - } - }); - - test('runs initialize -> tools/list -> search_symbols -> query_data -> analyze_signal (shorts + fundamentals) -> event_study -> read_knowledge -> file_finding in one stdio session', async () => { - const fixture = buildCopilotStudyFixture(); - const { serverOptions, storeHandle, ledger, findings } = buildComposedServerOptions(fixture); - const server = createResearchCopilotMcpServer(serverOptions); - const sink = createMemoryOutput(); - - let shortsTrialRef = ''; - let fundamentalsTrialRef = ''; - - async function* requestStream(): AsyncGenerator { - yield `${JSON.stringify({ - jsonrpc: '2.0', - id: 1, - method: 'initialize', - params: { - protocolVersion: '2024-11-05', - capabilities: {}, - clientInfo: { name: 'headless-copilot-test', version: '1.0.0' }, - }, - })}\n`; - - yield `${JSON.stringify({ - jsonrpc: '2.0', - id: 2, - method: 'tools/list', - })}\n`; - - yield `${JSON.stringify({ - jsonrpc: '2.0', - id: 3, - method: 'tools/call', - params: { - name: 'search_symbols', - arguments: { query: 'ACME', country: 'US', limit: 5 }, - }, - })}\n`; - - yield `${JSON.stringify({ - jsonrpc: '2.0', - id: 4, - method: 'tools/call', - params: { - name: 'query_data', - arguments: { - listingIds: [fixture.listingIds[0]!], - from: fixture.firstDate, - to: fixture.lastPreCutoffDate, - timeframe: '1d', - adjustment: 'raw', - limit: 10, - }, - }, - })}\n`; - - yield `${JSON.stringify({ - jsonrpc: '2.0', - id: 5, - method: 'tools/call', - params: { - name: 'analyze_signal', - arguments: { - listingIds: [...fixture.listingIds], - from: fixture.firstDate, - to: fixture.lastPreCutoffDate, - signal: { source: 'shorts', field: 'net_change' }, - horizonSessions: 5, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - adjustment: 'raw', - }, - }, - })}\n`; - - yield `${JSON.stringify({ - jsonrpc: '2.0', - id: 6, - method: 'tools/call', - params: { - name: 'analyze_signal', - arguments: { - listingIds: [...fixture.listingIds], - from: fixture.firstDate, - to: fixture.lastPreCutoffDate, - signal: { source: 'fundamentals', field: 'ttm_revenue' }, - horizonSessions: 5, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - adjustment: 'raw', - }, - }, - })}\n`; - - yield `${JSON.stringify({ - jsonrpc: '2.0', - id: 7, - method: 'tools/call', - params: { - name: 'event_study', - arguments: { - listingIds: [...fixture.listingIds], - from: fixture.firstDate, - to: fixture.lastPreCutoffDate, - event: { kinds: ['filing'], subtypes: ['8-K'] }, - preDays: 2, - postDays: 5, - benchmark: 'equal_weight', - adjustment: 'raw', - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }, - }, - })}\n`; - - yield `${JSON.stringify({ - jsonrpc: '2.0', - id: 8, - method: 'tools/call', - params: { - name: 'read_knowledge', - arguments: { source: 'all', query: 'sharpe', limit: 5 }, - }, - })}\n`; - - // Decode both earlier analyze_signal responses written by runStdioServer before - // constructing the file_finding call so both trialRefs are dynamically linked. - expect(sink.lines.length).toBeGreaterThanOrEqual(6); - const shortsResp = JSON.parse(sink.lines[4]!) as JsonRpcResponseEnvelope; - const shortsPayload = decodeToolJson(shortsResp); - expect(shortsPayload.status).toBe('ok'); - if (shortsPayload.status !== 'ok') { - throw new Error('Expected shorts analyze_signal status to be ok.'); - } - shortsTrialRef = String(shortsPayload.trial.trialId); - - const fundamentalsResp = JSON.parse(sink.lines[5]!) as JsonRpcResponseEnvelope; - const fundamentalsPayload = decodeToolJson(fundamentalsResp); - expect(fundamentalsPayload.status).toBe('ok'); - if (fundamentalsPayload.status !== 'ok') { - throw new Error('Expected fundamentals analyze_signal status to be ok.'); - } - fundamentalsTrialRef = String(fundamentalsPayload.trial.trialId); - - yield `${JSON.stringify({ - jsonrpc: '2.0', - id: 9, - method: 'tools/call', - params: { - name: 'file_finding', - arguments: { - kind: 'finding', - title: 'Short-interest and fundamentals signal studies on synthetic US_EQ panel', - summary: `Dataset ${FIXTURE_DATASET_ID}, raw close-to-close returns, zero modeled costs, pre-Vault window ${fixture.firstDate}..${fixture.lastPreCutoffDate}.`, - trialRefs: [shortsTrialRef, fundamentalsTrialRef], - evidenceRefs: [FIXTURE_DATASET_ID], - idempotencyKey: 'copilot-e2e-finding-1', - }, - }, - })}\n`; - } - - await runStdioServer(server, { input: requestStream(), output: sink.output }); - - const rawOut = sink.text(); - expect(rawOut.endsWith('\n')).toBe(true); - expect(sink.lines).toHaveLength(9); - - const responses = sink.lines.map(line => JSON.parse(line) as JsonRpcResponseEnvelope); - expect(responses.map(r => r.id)).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9]); - for (const resp of responses) { - expect(resp.error).toBeUndefined(); - } - - // 1. initialize - const initResult = responses[0]!.result as { - serverInfo: { name: string; version: string }; - capabilities: { tools: Record }; - }; - expect(initResult.serverInfo).toEqual({ name: SERVER_NAME, version: SERVER_VERSION }); - expect(initResult.capabilities.tools).toEqual({}); - - // 2. tools/list - const listResult = responses[1]!.result as { tools: readonly McpToolDescriptor[] }; - expect(listResult.tools.map(t => t.name)).toEqual([...EXPECTED_TOOL_NAMES]); - - // 3. search_symbols - const searchPayload = decodeToolJson(responses[2]!); - expect(searchPayload.scope).toBe('vault_fenced'); - expect(searchPayload.rowCount).toBe(1); - expect(searchPayload.rows[0]?.ticker).toBe('ACME'); - expect(searchPayload.rows[0]?.listingId).toBe(fixture.listingIds[0]); - - // 4. query_data - const queryPayload = decodeToolJson(responses[3]!); - expect(queryPayload.scope).toBe('vault_fenced'); - expect(queryPayload.rowCount).toBe(10); - expect(queryPayload.truncated).toBe(true); - expect(queryPayload.rows.every(r => r.ts < fixture.vaultCutoffTs)).toBe(true); - - // 5. analyze_signal (shorts) - const shortsSignalPayload = decodeToolJson(responses[4]!); - expect(shortsSignalPayload.status).toBe('ok'); - if (shortsSignalPayload.status !== 'ok') { - throw new Error('Expected shorts analyze_signal status to be ok.'); - } - expect(shortsSignalPayload.signal).toEqual({ source: 'shorts', field: 'net_change' }); - expect(String(shortsSignalPayload.trial.trialId)).toBe(shortsTrialRef); - - // 6. analyze_signal (fundamentals) - const fundamentalsSignalPayload = decodeToolJson(responses[5]!); - expect(fundamentalsSignalPayload.status).toBe('ok'); - if (fundamentalsSignalPayload.status !== 'ok') { - throw new Error('Expected fundamentals analyze_signal status to be ok.'); - } - expect(fundamentalsSignalPayload.signal).toEqual({ - source: 'fundamentals', - field: 'ttm_revenue', - allowEstimatedLag: false, - }); - expect(String(fundamentalsSignalPayload.trial.trialId)).toBe(fundamentalsTrialRef); - expect(fundamentalsSignalPayload.trial.expressionHash).not.toBe( - shortsSignalPayload.trial.expressionHash - ); - expect(storeHandle.getFundamentalsCalls()).toBeGreaterThan(0); - - // 7. event_study - const eventPayload = decodeToolJson(responses[6]!); - expect(eventPayload.status).toBe('ok'); - if (eventPayload.status !== 'ok') { - throw new Error('Expected event_study status to be ok.'); - } - expect(eventPayload.benchmark).toBe('equal_weight'); - expect(eventPayload.study.hasBenchmark).toBe(true); - - // 8. read_knowledge - const knowledgePayload = decodeToolJson(responses[7]!); - expect(knowledgePayload.rowCount).toBe(1); - expect(knowledgePayload.rows[0]?.id).toBe('card-dsr-01'); - - // 9. file_finding - const findingPayload = decodeToolJson(responses[8]!); - expect(findingPayload).toEqual({ - id: FIXED_FINDING_ID, - createdAt: FIXED_NOW_ISO, - created: true, - }); - - // Verify trial_ledger recorded both signal_ic trials (distinct hashes) and event_study under AGENT_PRINCIPAL. - expect(ledger.rows).toHaveLength(3); - expect(ledger.rows.map(r => r.stage)).toEqual(['signal_ic', 'signal_ic', 'event_study']); - expect(ledger.rows.every(r => r.principal_id === AGENT_PRINCIPAL)).toBe(true); - expect(ledger.rows[0]?.trial_id).toBe(String(shortsSignalPayload.trial.trialId)); - expect(ledger.rows[1]?.trial_id).toBe(String(fundamentalsSignalPayload.trial.trialId)); - expect(ledger.rows[2]?.trial_id).toBe(String(eventPayload.trial.trialId)); - expect(ledger.rows[0]?.expression_hash).not.toBe(ledger.rows[1]?.expression_hash); - - // Verify FindingWritePort recorded exactly one pending_review finding referencing both signal trials. - expect(findings.appendCalls).toHaveLength(1); - expect(findings.stored).toHaveLength(1); - expect(findings.stored[0]).toMatchObject({ - id: findingPayload.id, - createdAt: findingPayload.createdAt, - kind: 'finding', - status: 'pending_review', - trialRefs: [shortsTrialRef, fundamentalsTrialRef], - evidenceRefs: [FIXTURE_DATASET_ID], - }); - }); - - test('enforces the Vault fence on straddling and post-cutoff query_data and analyze_signal calls (clean vs leaky store)', async () => { - const fixture = buildCopilotStudyFixture(); - const clean = buildComposedServerOptions(fixture, { leakyVaultRows: false }); - const leaky = buildComposedServerOptions(fixture, { leakyVaultRows: true }); - - const cleanServer = createResearchCopilotMcpServer(clean.serverOptions); - const leakyServer = createResearchCopilotMcpServer(leaky.serverOptions); - - // Straddling query_data: ends after vaultCutoffDate with explicit post-cutoff asOf - const straddlingQueryReq = JSON.stringify({ - jsonrpc: '2.0', - id: 'q-straddle', - method: 'tools/call', - params: { - name: 'query_data', - arguments: { - listingIds: [fixture.listingIds[0]!, fixture.listingIds[1]!], - from: fixture.firstDate, - to: fixture.postCutoffDate, - asOf: fixture.postCutoffDate, - timeframe: '1d', - adjustment: 'raw', - limit: 500, - }, - }, - }); - - const cleanQueryPayload = decodeToolJson( - JSON.parse((await cleanServer.handleMessage(straddlingQueryReq))!) as JsonRpcResponseEnvelope - ); - const leakyQueryPayload = decodeToolJson( - JSON.parse((await leakyServer.handleMessage(straddlingQueryReq))!) as JsonRpcResponseEnvelope - ); - - for (const payload of [cleanQueryPayload, leakyQueryPayload]) { - expect(payload.scope).toBe('vault_fenced'); - expect(payload.clampedTo).toBe(true); - expect(payload.clampedAsOf).toBe(true); - expect(payload.toMs).toBe(fixture.vaultCutoffTs - 1); - expect(payload.asOfMs).toBe(fixture.vaultCutoffTs - 1); - expect(payload.rows.every(r => r.ts < fixture.vaultCutoffTs && r.knownAt < fixture.vaultCutoffTs)).toBe( - true - ); - } - expect(leakyQueryPayload.rows).toEqual(cleanQueryPayload.rows); - - // Straddling analyze_signal: clean vs deliberately leaky store must produce identical payload & trial row - const straddlingSignalReq = JSON.stringify({ - jsonrpc: '2.0', - id: 'sig-straddle', - method: 'tools/call', - params: { - name: 'analyze_signal', - arguments: { - listingIds: [...fixture.listingIds], - from: fixture.firstDate, - to: fixture.postCutoffDate, - asOf: fixture.postCutoffDate, - signal: { source: 'shorts', field: 'net_change' }, - horizonSessions: 5, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - adjustment: 'raw', - }, - }, - }); - - const cleanSignalPayload = decodeToolJson( - JSON.parse((await cleanServer.handleMessage(straddlingSignalReq))!) as JsonRpcResponseEnvelope - ); - const leakySignalPayload = decodeToolJson( - JSON.parse((await leakyServer.handleMessage(straddlingSignalReq))!) as JsonRpcResponseEnvelope - ); - - expect(cleanSignalPayload.status).toBe('ok'); - expect(leakySignalPayload.status).toBe('ok'); - expect(leakySignalPayload).toEqual(cleanSignalPayload); - expect(leakySignalPayload.scope).toBe('vault_fenced'); - expect(leakySignalPayload.clampedTo).toBe(true); - expect(leakySignalPayload.clampedAsOf).toBe(true); - expect(leakySignalPayload.toMs).toBe(fixture.vaultCutoffTs - 1); - expect(leakySignalPayload.asOfMs).toBe(fixture.vaultCutoffTs - 1); - - expect(clean.ledger.rows).toHaveLength(1); - expect(leaky.ledger.rows).toHaveLength(1); - expect(leaky.ledger.rows[0]).toEqual(clean.ledger.rows[0]); - - // Last forward-return endpoint must remain strictly before vaultCutoffDate. - const lastSampleEnd = leaky.ledger.rows[0]!.sample_end; - const lastSampleIdx = fixture.allDates.indexOf(lastSampleEnd); - expect(lastSampleIdx).toBeGreaterThanOrEqual(0); - expect(lastSampleIdx + 5).toBeLessThan(fixture.preCutoffSessions); - expect(fixture.allDates[lastSampleIdx + 5]! < fixture.vaultCutoffDate).toBe(true); - - // Wholly post-cutoff range must return VaultHoldoutFenceError with zero store reads and zero ledger writes. - const postCutoffCheck = buildComposedServerOptions(fixture); - const postCutoffServer = createResearchCopilotMcpServer(postCutoffCheck.serverOptions); - - const postQueryResp = JSON.parse( - (await postCutoffServer.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 'q-post', - method: 'tools/call', - params: { - name: 'query_data', - arguments: { - listingIds: [fixture.listingIds[0]!], - from: fixture.vaultCutoffDate, - to: fixture.postCutoffDate, - timeframe: '1d', - adjustment: 'raw', - }, - }, - }) - ))! - ) as JsonRpcResponseEnvelope; - const postQueryTool = postQueryResp.result as ToolCallEnvelope; - expect(postQueryTool.isError).toBe(true); - expect(postQueryTool.content[0]?.text).toContain('VaultHoldoutFenceError'); - - const postSignalResp = JSON.parse( - (await postCutoffServer.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 'sig-post', - method: 'tools/call', - params: { - name: 'analyze_signal', - arguments: { - listingIds: [...fixture.listingIds], - from: fixture.vaultCutoffDate, - to: fixture.postCutoffDate, - signal: { source: 'shorts', field: 'net_change' }, - horizonSessions: 5, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - adjustment: 'raw', - }, - }, - }) - ))! - ) as JsonRpcResponseEnvelope; - const postSignalTool = postSignalResp.result as ToolCallEnvelope; - expect(postSignalTool.isError).toBe(true); - expect(postSignalTool.content[0]?.text).toContain('VaultHoldoutFenceError'); - - expect(postCutoffCheck.storeHandle.getBarsCalls()).toBe(0); - expect(postCutoffCheck.storeHandle.getShortsCalls()).toBe(0); - expect(postCutoffCheck.storeHandle.getUniverseCalls()).toBe(0); - expect(postCutoffCheck.ledger.getInsertCalls()).toBe(0); - }); - - test('returns INVALID_PARAMS for unknown tool in stdio session and continues processing ping', async () => { - const fixture = buildCopilotStudyFixture(); - const { serverOptions } = buildComposedServerOptions(fixture); - const server = createResearchCopilotMcpServer(serverOptions); - const sink = createMemoryOutput(); - - async function* input(): AsyncGenerator { - yield `${JSON.stringify({ - jsonrpc: '2.0', - id: 'bad-tool', - method: 'tools/call', - params: { name: 'nonexistent_tool', arguments: {} }, - })}\n`; - yield `${JSON.stringify({ - jsonrpc: '2.0', - id: 'keep-alive', - method: 'ping', - })}\n`; - } - - await runStdioServer(server, { input: input(), output: sink.output }); - - expect(sink.lines).toHaveLength(2); - const errResp = JSON.parse(sink.lines[0]!) as JsonRpcResponseEnvelope; - const pingResp = JSON.parse(sink.lines[1]!) as JsonRpcResponseEnvelope; - - expect(errResp.id).toBe('bad-tool'); - expect(errResp.error?.code).toBe(JSON_RPC_ERROR_CODES.INVALID_PARAMS); - expect(errResp.error?.message).toBe('Unknown tool: "nonexistent_tool".'); - - expect(pingResp.id).toBe('keep-alive'); - expect(pingResp.error).toBeUndefined(); - expect(pingResp.result).toEqual({}); - }); - - test('throws on duplicate or missing/unexpected tool name during server composition', () => { - const fixture = buildCopilotStudyFixture(); - const { serverOptions } = buildComposedServerOptions(fixture); - - const dupSpy = spyOn(queryDataToolModule, 'createQueryDataTool').mockImplementation(() => ({ - name: 'search_symbols', - description: 'Duplicate name entry', - inputSchema: { type: 'object', properties: {}, additionalProperties: false }, - async execute() { - return { content: [{ type: 'text', text: '{}' }] }; - }, - })); - try { - expect(() => createResearchCopilotMcpServer(serverOptions)).toThrow( - /Duplicate MCP tool name/ - ); - } finally { - dupSpy.mockRestore(); - } - - const missingSpy = spyOn(readKnowledgeToolModule, 'createReadKnowledgeTool').mockImplementation( - () => ({ - name: 'unexpected_tool', - description: 'Unexpected name entry leaving read_knowledge missing', - inputSchema: { type: 'object', properties: {}, additionalProperties: false }, - async execute() { - return { content: [{ type: 'text', text: '{}' }] }; - }, - }) - ); - try { - expect(() => createResearchCopilotMcpServer(serverOptions)).toThrow( - /expected "read_knowledge", got "unexpected_tool"/ - ); - } finally { - missingSpy.mockRestore(); - } - }); -}); diff --git a/libs/research/test/mcp-edge-cases.test.ts b/libs/research/test/mcp-edge-cases.test.ts deleted file mode 100644 index c20ec3c5..00000000 --- a/libs/research/test/mcp-edge-cases.test.ts +++ /dev/null @@ -1,595 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { z } from 'zod'; -import { - type BarBatch, - type BarRecord, - type MarketDataStore, - VaultHoldoutFenceError, -} from '../src/market-data-store'; -import { - type BarsQuery, - MarketDataStoreNotImplementedError, - type UniverseQuery, -} from '../src/market-data-store-duckdb'; -import { - JSON_RPC_ERROR_CODES, - type JsonSchemaObject, - QUERY_DATA_MAX_LISTING_IDS, - type QueryDataResultPayload, - type StdioOutput, - createMcpServer, - createQueryDataTool, - defineMcpTool, - runStdioServer, - zodObjectToJsonSchema, -} from '../src/mcp/index'; - -// QA edge cases for T-129 (M2.1a MCP core) not covered by the programmer's suites. - -const VAULT_CUTOFF_TS = Date.UTC(2025, 2, 31, 0, 0, 0, 0); - -interface ToolResult { - isError?: boolean; - content: { type: string; text: string }[]; -} - -interface RpcResponse { - id: string | number | null; - result?: unknown; - error?: { code: number; message: string }; -} - -function rpc(id: string | number, method: string, params?: unknown): string { - return JSON.stringify( - params === undefined ? { jsonrpc: '2.0', id, method } : { jsonrpc: '2.0', id, method, params } - ); -} - -function parse(raw: string | null): RpcResponse { - expect(raw).not.toBeNull(); - return JSON.parse(raw as string) as RpcResponse; -} - -function makeBar(listingId: number, ts: number, close: number, knownAt = ts): BarRecord { - return { - listingId, - ts, - open: close, - high: close, - low: close, - close, - volume: 1, - vwap: close, - knownAt, - }; -} - -interface RecordingStore { - readonly store: MarketDataStore; - readonly barsCalls: BarsQuery[]; - readonly universeCalls: UniverseQuery[]; - readonly iteratorClosed: () => boolean; -} - -function createRecordingStore(options: { - batches?: readonly BarBatch[]; - universeIds?: readonly number[]; - universeError?: Error; -}): RecordingStore { - const barsCalls: BarsQuery[] = []; - const universeCalls: UniverseQuery[] = []; - let closed = false; - const store: MarketDataStore = { - bars(q: BarsQuery): AsyncIterable { - barsCalls.push(q); - const batches = options.batches ?? []; - return { - async *[Symbol.asyncIterator]() { - try { - for (const batch of batches) { - yield batch; - } - } finally { - closed = true; - } - }, - }; - }, - async universe(q: UniverseQuery): Promise { - universeCalls.push(q); - if (options.universeError !== undefined) { - throw options.universeError; - } - return [...(options.universeIds ?? [])]; - }, - crossSection() { - throw new MarketDataStoreNotImplementedError('crossSection'); - }, - fundamentalsAsOf() { - throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); - }, - events() { - throw new MarketDataStoreNotImplementedError('events'); - }, - shortsAsOf() { - throw new MarketDataStoreNotImplementedError('shortsAsOf'); - }, - macroAsOf() { - throw new MarketDataStoreNotImplementedError('macroAsOf'); - }, - fx() { - throw new MarketDataStoreNotImplementedError('fx'); - }, - }; - return { store, barsCalls, universeCalls, iteratorClosed: () => closed }; -} - -async function callQueryData( - rec: RecordingStore, - args: Record, - vaultCutoffTs = VAULT_CUTOFF_TS -): Promise<{ isError: boolean; text: string }> { - const server = createMcpServer({ - name: 'qa', - version: '0.0.0', - tools: [createQueryDataTool({ store: rec.store, vaultContext: { vaultCutoffTs } })], - }); - const resp = parse( - await server.handleMessage(rpc('q', 'tools/call', { name: 'query_data', arguments: args })) - ); - expect(resp.error).toBeUndefined(); - const result = resp.result as ToolResult; - return { isError: result.isError === true, text: result.content[0]?.text ?? '' }; -} - -function memoryOutput(): { output: StdioOutput; chunks: string[] } { - const chunks: string[] = []; - return { - chunks, - output: { - write(chunk: string): boolean { - chunks.push(chunk); - return true; - }, - }, - }; -} - -async function* chunksOf(chunks: readonly (string | Uint8Array)[]): AsyncGenerator { - for (const c of chunks) { - yield c; - } -} - -describe('MCP server edge cases (QA)', () => { - test('tools/call sent as a notification returns null and never runs the handler', async () => { - let calls = 0; - const tool = defineMcpTool({ - name: 'side_effect', - description: 'Counts invocations.', - inputSchema: z.object({}).strict(), - handler() { - calls += 1; - return { content: [{ type: 'text', text: 'ran' }] }; - }, - }); - const server = createMcpServer({ name: 'qa', version: '0.0.0', tools: [tool] }); - - const raw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - method: 'tools/call', - params: { name: 'side_effect', arguments: {} }, - }) - ); - - expect(raw).toBeNull(); - expect(calls).toBe(0); - }); - - test('tools/call with missing or array params returns -32602 echoing the id', async () => { - const server = createMcpServer({ name: 'qa', version: '0.0.0' }); - for (const [id, params] of [ - [7, undefined], - ['arr', [{ name: 'x' }]], - [8, { arguments: {} }], - [9, { name: 'x', arguments: [1, 2] }], - ] as const) { - const resp = parse(await server.handleMessage(rpc(id, 'tools/call', params))); - expect(resp.id).toBe(id); - expect(resp.error?.code).toBe(JSON_RPC_ERROR_CODES.INVALID_PARAMS); - } - }); - - test('initialize with invalid params returns -32602 and does not crash', async () => { - const server = createMcpServer({ name: 'qa', version: '0.0.0' }); - const resp = parse( - await server.handleMessage(rpc('init', 'initialize', { clientInfo: { name: 5 } })) - ); - expect(resp.id).toBe('init'); - expect(resp.error?.code).toBe(JSON_RPC_ERROR_CODES.INVALID_PARAMS); - }); - - test('non-Error throws and errors with unsafe names are sanitized to a fixed message', async () => { - const throwString = defineMcpTool({ - name: 'throw_string', - description: 'Throws a string.', - inputSchema: z.object({}).strict(), - handler() { - throw '/srv/secret/path leaked'; - }, - }); - const throwBadName = defineMcpTool({ - name: 'throw_bad_name', - description: 'Throws an error whose name contains a path.', - inputSchema: z.object({}).strict(), - async handler() { - const err = new Error('boom /srv/secret/x.ts'); - err.name = '/srv/secret/x.ts'; - throw err; - }, - }); - const server = createMcpServer({ - name: 'qa', - version: '0.0.0', - tools: [throwString, throwBadName], - }); - - for (const [name, expected] of [ - ['throw_string', 'Error: Tool execution failed.'], - ['throw_bad_name', 'Error: Tool execution failed.'], - ] as const) { - const resp = parse(await server.handleMessage(rpc(name, 'tools/call', { name, arguments: {} }))); - const result = resp.result as ToolResult; - expect(result.isError).toBe(true); - expect(result.content[0]?.text).toBe(expected); - expect(result.content[0]?.text).not.toContain('/srv/secret'); - } - }); - - test('responses are single-line JSON even when tool text contains newlines', async () => { - const tool = defineMcpTool({ - name: 'multiline', - description: 'Returns multi-line text.', - inputSchema: z.object({}).strict(), - handler: () => ({ content: [{ type: 'text', text: 'line1\nline2\r\nline3' }] }), - }); - const server = createMcpServer({ name: 'qa', version: '0.0.0', tools: [tool] }); - const raw = await server.handleMessage( - rpc(1, 'tools/call', { name: 'multiline', arguments: {} }) - ); - expect(raw).not.toContain('\n'); - expect(raw).not.toContain('\r'); - expect((parse(raw).result as ToolResult).content[0]?.text).toBe('line1\nline2\r\nline3'); - }); - - test('explicit jsonSchema override is emitted verbatim by tools/list', async () => { - const override: JsonSchemaObject = { - type: 'object', - properties: { q: { type: 'string', description: 'custom' } }, - required: ['q'], - additionalProperties: false, - }; - const tool = defineMcpTool({ - name: 'with_override', - description: 'Has a hand-written schema.', - inputSchema: z.object({ q: z.string() }).strict(), - jsonSchema: override, - handler: () => ({ content: [{ type: 'text', text: 'ok' }] }), - }); - const server = createMcpServer({ name: 'qa', version: '0.0.0', tools: [tool] }); - const resp = parse(await server.handleMessage(rpc(1, 'tools/list'))); - const tools = (resp.result as { tools: { inputSchema: unknown }[] }).tools; - expect(tools[0]?.inputSchema).toEqual(override); - }); - - test('zod converter maps nullable, union, literal, exclusive bounds, defaults, arrays and refinements', () => { - const schema = z - .object({ - n: z.number().gt(0).lt(10).describe('open interval'), - s: z.string().length(3), - maybe: z.string().nullable(), - either: z.union([z.string(), z.number().int()]), - lit: z.literal('fixed'), - flag: z.boolean().default(false), - tags: z.array(z.string()).min(1).max(4).optional(), - }) - .strict() - .refine(() => true) - .describe('root'); - - const json = zodObjectToJsonSchema(schema); - - expect(json.type).toBe('object'); - expect(json.additionalProperties).toBe(false); - expect(json.description).toBe('root'); - expect(json.required).toEqual(['n', 's', 'maybe', 'either', 'lit']); - expect(json.properties.n).toEqual({ - type: 'number', - description: 'open interval', - exclusiveMinimum: 0, - exclusiveMaximum: 10, - }); - expect(json.properties.s).toEqual({ type: 'string', minLength: 3, maxLength: 3 }); - expect(json.properties.maybe).toEqual({ anyOf: [{ type: 'string' }, { type: 'null' }] }); - expect(json.properties.either).toEqual({ - anyOf: [{ type: 'string' }, { type: 'integer' }], - }); - expect(json.properties.lit).toEqual({ type: 'string', const: 'fixed' }); - expect(json.properties.flag).toEqual({ type: 'boolean', default: false }); - expect(json.properties.tags).toEqual({ - type: 'array', - items: { type: 'string' }, - minItems: 1, - maxItems: 4, - }); - - expect(() => zodObjectToJsonSchema(z.string())).toThrow(/must be a ZodObject/); - }); - - test('defineMcpTool and createMcpServer reject empty names/descriptions/versions', () => { - const base = { - inputSchema: z.object({}).strict(), - handler: () => ({ content: [{ type: 'text' as const, text: '' }] }), - }; - expect(() => defineMcpTool({ ...base, name: ' ', description: 'd' })).toThrow(); - expect(() => defineMcpTool({ ...base, name: 'n', description: '' })).toThrow(); - expect(() => createMcpServer({ name: '', version: '1' })).toThrow(); - expect(() => createMcpServer({ name: 'n', version: ' ' })).toThrow(); - }); -}); - -describe('MCP stdio edge cases (QA)', () => { - test('oversized frame spread across many chunks yields exactly one -32700 and recovers', async () => { - const server = createMcpServer({ name: 'qa', version: '0.0.0' }); - const pad = 'x'.repeat(100); - const sink = memoryOutput(); - - await runStdioServer(server, { - input: chunksOf([ - `{"jsonrpc":"2.0","id":1,"method":"ping","pad":"${pad}`, - pad, - pad, - `${pad}"}\n${rpc(2, 'ping')}\n`, - ]), - output: sink.output, - maxLineBytes: 64, - }); - - const lines = sink.chunks.join('').trimEnd().split('\n'); - expect(lines).toHaveLength(2); - const first = JSON.parse(lines[0] ?? '') as RpcResponse; - const second = JSON.parse(lines[1] ?? '') as RpcResponse; - expect(first.id).toBeNull(); - expect(first.error?.code).toBe(JSON_RPC_ERROR_CODES.PARSE_ERROR); - expect(second.id).toBe(2); - expect(second.result).toEqual({}); - }); - - test('oversized unterminated tail at EOF yields one -32700 and never dispatches it', async () => { - const server = createMcpServer({ name: 'qa', version: '0.0.0' }); - const sink = memoryOutput(); - await runStdioServer(server, { - input: chunksOf([`${rpc(1, 'ping')}\n`, `{"jsonrpc":"2.0","id":2,"method":"ping","p":"${'y'.repeat(200)}"}`]), - output: sink.output, - maxLineBytes: 128, - }); - const lines = sink.chunks.join('').trimEnd().split('\n'); - expect(lines).toHaveLength(2); - expect((JSON.parse(lines[0] ?? '') as RpcResponse).id).toBe(1); - const err = JSON.parse(lines[1] ?? '') as RpcResponse; - expect(err.id).toBeNull(); - expect(err.error?.code).toBe(JSON_RPC_ERROR_CODES.PARSE_ERROR); - }); - - test('malformed line between valid requests yields -32700 and processing continues in order', async () => { - const server = createMcpServer({ name: 'qa', version: '0.0.0' }); - const sink = memoryOutput(); - await runStdioServer(server, { - input: chunksOf([`${rpc('a', 'ping')}\n{oops\n${rpc('b', 'ping')}\n`]), - output: sink.output, - }); - const lines = sink.chunks.join('').trimEnd().split('\n').map(l => JSON.parse(l) as RpcResponse); - expect(lines.map(l => l.id)).toEqual(['a', null, 'b']); - expect(lines[1]?.error?.code).toBe(JSON_RPC_ERROR_CODES.PARSE_ERROR); - }); - - test('a stream of only notifications writes zero bytes', async () => { - const server = createMcpServer({ name: 'qa', version: '0.0.0' }); - const sink = memoryOutput(); - await runStdioServer(server, { - input: chunksOf([ - `${JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' })}\n`, - `${JSON.stringify({ jsonrpc: '2.0', method: 'notifications/cancelled', params: { requestId: 1 } })}\n`, - ]), - output: sink.output, - }); - expect(sink.chunks).toEqual([]); - }); - - test('waits for drain when output.write signals backpressure before writing the next response', async () => { - const server = createMcpServer({ name: 'qa', version: '0.0.0' }); - const events: string[] = []; - const output: StdioOutput = { - write(chunk: string): boolean { - events.push(`write:${(JSON.parse(chunk) as RpcResponse).id}`); - return false; - }, - once(_event: 'drain', listener: () => void) { - events.push('await-drain'); - queueMicrotask(() => { - events.push('drain'); - listener(); - }); - }, - }; - - await runStdioServer(server, { - input: chunksOf([`${rpc(1, 'ping')}\n${rpc(2, 'ping')}\n`]), - output, - }); - - expect(events).toEqual(['write:1', 'await-drain', 'drain', 'write:2', 'await-drain', 'drain']); - }); - - test('rejects non-positive or non-integer maxLineBytes', async () => { - const server = createMcpServer({ name: 'qa', version: '0.0.0' }); - for (const bad of [0, -1, 1.5, Number.NaN]) { - await expect( - runStdioServer(server, { input: chunksOf([]), output: memoryOutput().output, maxLineBytes: bad }) - ).rejects.toThrow(/maxLineBytes/); - } - }); -}); - -describe('MCP query_data edge cases (QA)', () => { - test('selector rules: both, neither, too many, or non-integer listingIds are rejected with zero store calls', async () => { - const tooMany = Array.from({ length: QUERY_DATA_MAX_LISTING_IDS + 1 }, (_, i) => i + 1); - const cases: Record[] = [ - { listingIds: [1], universe: 'US_EQ', from: '2025-03-01', to: '2025-03-10' }, - { from: '2025-03-01', to: '2025-03-10' }, - { listingIds: [], from: '2025-03-01', to: '2025-03-10' }, - { listingIds: tooMany, from: '2025-03-01', to: '2025-03-10' }, - { listingIds: [1.5], from: '2025-03-01', to: '2025-03-10' }, - { listingIds: [2_147_483_648], from: '2025-03-01', to: '2025-03-10' }, - { listingIds: [1], from: '2025-03-01', to: '2025-03-10', timeframe: '1w' }, - { listingIds: [1], from: '2025-03-01', to: '2025-03-10', limit: 2.5 }, - ]; - for (const args of cases) { - const rec = createRecordingStore({}); - const res = await callQueryData(rec, args); - expect(res.isError).toBe(true); - expect(res.text).toContain('Invalid arguments for tool "query_data"'); - expect(rec.barsCalls).toHaveLength(0); - expect(rec.universeCalls).toHaveLength(0); - } - - const okRec = createRecordingStore({}); - const ok = await callQueryData(okRec, { - listingIds: tooMany.slice(0, QUERY_DATA_MAX_LISTING_IDS), - from: '2025-03-01', - to: '2025-03-10', - }); - expect(ok.isError).toBe(false); - expect(okRec.barsCalls[0]?.listingIds).toHaveLength(QUERY_DATA_MAX_LISTING_IDS); - }); - - test('from after to maps to MarketDataStoreValidationError with zero store calls', async () => { - const rec = createRecordingStore({}); - const res = await callQueryData(rec, { listingIds: [1], from: '2025-03-10', to: '2025-03-01' }); - expect(res.isError).toBe(true); - expect(res.text).toBe('MarketDataStoreValidationError: Invalid query parameter "from".'); - expect(rec.barsCalls).toHaveLength(0); - }); - - test('exactly limit eligible rows across batches is not truncated; one more is truncated and closes the store stream', async () => { - const base = Date.UTC(2025, 0, 2); - const rowsA = [makeBar(1, base, 1), makeBar(1, base + 1, 2)]; - const rowsB = [makeBar(1, base + 2, 3)]; - - const exact = createRecordingStore({ batches: [{ rows: rowsA }, { rows: rowsB }] }); - const exactRes = await callQueryData(exact, { - listingIds: [1], - from: '2025-01-01', - to: '2025-03-01', - limit: 3, - }); - const exactPayload = JSON.parse(exactRes.text) as QueryDataResultPayload; - expect(exactPayload.rowCount).toBe(3); - expect(exactPayload.truncated).toBe(false); - - const more = createRecordingStore({ - batches: [{ rows: rowsA }, { rows: rowsB }, { rows: [makeBar(1, base + 3, 4)] }, { rows: [makeBar(1, base + 4, 5)] }], - }); - const moreRes = await callQueryData(more, { - listingIds: [1], - from: '2025-01-01', - to: '2025-03-01', - limit: 3, - }); - const morePayload = JSON.parse(moreRes.text) as QueryDataResultPayload; - expect(morePayload.rowCount).toBe(3); - expect(morePayload.truncated).toBe(true); - expect(morePayload.rows.map(r => r.close)).toEqual([1, 2, 3]); - expect(more.iteratorClosed()).toBe(true); - }); - - test('post-cutoff rows dropped by the fence do not count toward the limit or the truncated flag', async () => { - const pre = makeBar(1, Date.UTC(2025, 2, 10), 1); - const leaks = [ - makeBar(1, VAULT_CUTOFF_TS, 9), - makeBar(1, Date.UTC(2025, 2, 11), 9, VAULT_CUTOFF_TS + 5), - makeBar(1, Number.NaN, 9), - ]; - const rec = createRecordingStore({ batches: [{ rows: [pre, ...leaks] }] }); - const res = await callQueryData(rec, { listingIds: [1], from: '2025-03-01', to: '2025-04-30', limit: 1 }); - const payload = JSON.parse(res.text) as QueryDataResultPayload; - expect(payload.rows).toEqual([pre]); - expect(payload.truncated).toBe(false); - expect(res.text).not.toContain('"close":9'); - }); - - test('mid-day Vault cutoff: universe date is the last completed UTC day and bars bounds stay below the cutoff', async () => { - const midDayCutoff = Date.UTC(2025, 2, 31, 12, 0, 0, 0); - const rec = createRecordingStore({ - universeIds: [5], - batches: [{ rows: [makeBar(5, Date.UTC(2025, 2, 31, 11, 0), 1), makeBar(5, midDayCutoff, 2)] }], - }); - const res = await callQueryData( - rec, - { universe: 'US_EQ', from: '2025-03-01', to: '2025-04-30' }, - midDayCutoff - ); - expect(res.isError).toBe(false); - expect(rec.universeCalls).toEqual([{ ref: 'US_EQ', date: '2025-03-30' }]); - const q = rec.barsCalls[0]; - expect(q?.scope).toBe('vault_fenced'); - expect(q?.to).toBe('2025-03-31T11:59:59.999999Z'); - expect(q?.asOf).toBe('2025-03-31T11:59:59.999999Z'); - const payload = JSON.parse(res.text) as QueryDataResultPayload; - expect(payload.rows.every(r => r.ts < midDayCutoff && r.knownAt < midDayCutoff)).toBe(true); - expect(payload.rowCount).toBe(1); - }); - - test('in-fence date-only to with omitted asOf resolves universe on the to date', async () => { - const rec = createRecordingStore({ universeIds: [] }); - const res = await callQueryData(rec, { universe: 'CA_EQ', from: '2025-02-01', to: '2025-03-20' }); - expect(res.isError).toBe(false); - expect(rec.universeCalls).toEqual([{ ref: 'CA_EQ', date: '2025-03-20' }]); - expect(rec.barsCalls).toHaveLength(0); - }); - - test('errors thrown by store.universe are mapped or sanitized and bars is never called', async () => { - const fenceRec = createRecordingStore({ - universeError: new VaultHoldoutFenceError('2025-04-01', VAULT_CUTOFF_TS + 1, VAULT_CUTOFF_TS), - }); - const fenceRes = await callQueryData(fenceRec, { universe: 'US_EQ', from: '2025-03-01', to: '2025-03-20' }); - expect(fenceRes.isError).toBe(true); - expect(fenceRes.text).toContain('VaultHoldoutFenceError'); - expect(fenceRec.barsCalls).toHaveLength(0); - - const crashRec = createRecordingStore({ - universeError: new Error('connect ECONNREFUSED postgres://user:pw@10.0.0.51:5432/trading_bot'), - }); - const crashRes = await callQueryData(crashRec, { universe: 'US_EQ', from: '2025-03-01', to: '2025-03-20' }); - expect(crashRes.isError).toBe(true); - expect(crashRes.text).toBe('Error: Tool execution failed.'); - expect(crashRes.text).not.toContain('postgres://'); - expect(crashRec.barsCalls).toHaveLength(0); - }); - - test('factory rejects invalid store and vault cutoff values eagerly', () => { - const rec = createRecordingStore({}); - for (const bad of [Number.NaN, Number.POSITIVE_INFINITY, 1.5, 8_640_000_000_000_000]) { - expect(() => createQueryDataTool({ store: rec.store, vaultContext: { vaultCutoffTs: bad } })).toThrow( - /vaultCutoffTs/ - ); - } - expect(() => - createQueryDataTool({ - store: {} as MarketDataStore, - vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, - }) - ).toThrow(/store/); - }); -}); diff --git a/libs/research/test/mcp-event-study-qa.test.ts b/libs/research/test/mcp-event-study-qa.test.ts deleted file mode 100644 index fca76a34..00000000 --- a/libs/research/test/mcp-event-study-qa.test.ts +++ /dev/null @@ -1,1116 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import type { EventStudyExchangeCalendars } from '../src/event-panel'; -import type { - BarBatch, - BarRecord, - EventKind, - MarketDataStore, - Table, - TableRow, -} from '../src/market-data-store'; -import { - type BarsQuery, - EVENTS_COLUMNS, - type EventsQuery, - MarketDataStoreNotImplementedError, - type UniverseQuery, -} from '../src/market-data-store-duckdb'; -import { - type EventStudyExchangeCalendarQuery, - type EventStudyResultPayload, - createEventStudyTool, - createMcpServer, -} from '../src/mcp/index'; -import type { TrialLedgerExecutor } from '../src/trial-ledger'; - -// QA fixture: deterministic synthetic equity bars & events with explicit -// half-day closes, intraday Vault cutoffs, exact boundary timestamps, and -// malformed rows. Models gross daily close-to-close returns, raw adjustment, -// no fills or transaction costs. -const AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555'; - -function makeBusinessDates(startDate: string, count: number): string[] { - const out: string[] = []; - const current = new Date(`${startDate}T00:00:00.000Z`); - while (out.length < count) { - const day = current.getUTCDay(); - if (day !== 0 && day !== 6) { - out.push(current.toISOString().slice(0, 10)); - } - current.setUTCDate(current.getUTCDate() + 1); - } - return out; -} - -function utcMs(date: string, hour: number, minute = 0, second = 0, ms = 0): number { - const [y, m, d] = date.split('-').map(Number); - return Date.UTC(y!, m! - 1, d!, hour, minute, second, ms); -} - -function createFakeLedger(): { - executor: TrialLedgerExecutor; - insertCalls: number; - rows: Array<{ expression_hash: string; daily_series: number[] }>; -} { - const rows: Array<{ expression_hash: string; daily_series: number[] }> = []; - let nextId = 1; - const state = { - rows, - insertCalls: 0, - executor: null as unknown as TrialLedgerExecutor, - }; - - state.executor = { - async query>(text: string, params?: readonly unknown[]) { - const trimmed = text.trimStart(); - if (trimmed.startsWith('INSERT INTO trial_ledger')) { - state.insertCalls += 1; - const p = params ?? []; - const id = nextId++; - const dailySeries = (p[13] as readonly number[]).map(v => Math.fround(v)); - rows.push({ - expression_hash: p[6] as string, - daily_series: dailySeries, - }); - return { - rows: [ - { - trial_id: String(id), - created_at: new Date(Date.UTC(2024, 5, 1, 12, 0, id)), - } as unknown as Row, - ], - rowCount: 1, - }; - } - if (trimmed.startsWith('SELECT')) { - const storedRows = rows.map((r, idx) => ({ - trial_id: String(idx + 1), - created_at: new Date(Date.UTC(2024, 5, 1, 12, 0, idx + 1)), - principal_id: AGENT_PRINCIPAL, - campaign_id: null, - stage: 'event_study', - universe_market: 'US_EQ', - horizon_bucket: 'swing_1_10d', - hypothesis_id: null, - expression_hash: r.expression_hash, - sample_start: '2023-01-02', - sample_end: '2023-02-01', - n_obs: r.daily_series.length, - sharpe_unann: 0.5, - skewness: 0, - kurtosis: 3, - daily_series: r.daily_series, - })); - return { rows: storedRows as unknown as Row[], rowCount: storedRows.length }; - } - return { rows: [], rowCount: 0 }; - }, - }; - - return state; -} - -function createPassThroughStore(params: { - bars: readonly BarRecord[]; - eventsTable: Table; -}): MarketDataStore { - return { - bars(_q: BarsQuery): AsyncIterable { - return { - async *[Symbol.asyncIterator]() { - yield { rows: [...params.bars] }; - }, - }; - }, - async events(_q: EventsQuery): Promise
{ - return params.eventsTable; - }, - async universe(_q: UniverseQuery): Promise { - return []; - }, - crossSection() { - throw new MarketDataStoreNotImplementedError('crossSection'); - }, - fundamentalsAsOf() { - throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); - }, - shortsAsOf() { - throw new MarketDataStoreNotImplementedError('shortsAsOf'); - }, - macroAsOf() { - throw new MarketDataStoreNotImplementedError('macroAsOf'); - }, - fx() { - throw new MarketDataStoreNotImplementedError('fx'); - }, - }; -} - -async function invoke( - server: ReturnType, - args: Record -): Promise<{ - isError?: boolean; - text: string; - payload?: EventStudyResultPayload; -}> { - const raw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 1, - method: 'tools/call', - params: { name: 'event_study', arguments: args }, - }) - ); - const rpc = JSON.parse(raw!) as { - result: { content: Array<{ type: string; text: string }>; isError?: boolean }; - }; - const text = rpc.result.content[0]!.text; - return { - isError: rpc.result.isError, - text, - payload: rpc.result.isError ? undefined : (JSON.parse(text) as EventStudyResultPayload), - }; -} - -describe('MCP event_study QA edge cases', () => { - test('event released after a half-day close anchors to the next trading session, not the half-day', async () => { - const dates = makeBusinessDates('2023-05-01', 25); - const vaultCutoffDate = dates[24]!; - const vaultCutoffTs = utcMs(vaultCutoffDate, 0); - const listingIds = [101, 102, 103, 104, 105, 106]; - - // Make day index 8 a half-day (closes at 18:00 UTC = 13:00 ET instead of 21:00 UTC). - // Place 6 events across days 8 and 14, released at 19:00 UTC (after 18:00 UTC half-day close, - // before 21:00 UTC bar stamp). For half-day (index 8), events must anchor to index 9! - // Put a +10% jump on index 9 and +20% jump on index 15 (next day after 14, also half-day), - // and 0% return on index 8 and 14 so AAR at offset 0 proves next-session anchoring. - const halfDayIndices = new Set([8, 14]); - const jumpDayReturns = new Map([ - [9, 0.1], - [15, 0.2], - ]); - - const bars: BarRecord[] = []; - for (const id of listingIds) { - let price = 100; - for (let t = 0; t < 24; t += 1) { - const ret = jumpDayReturns.get(t) ?? 0; - price = Number((price * (1 + ret)).toFixed(6)); - const ts = utcMs(dates[t]!, 21); // bars_1d always stamped 16:00 ET (21:00 UTC) - bars.push({ - listingId: id, - ts, - open: price, - high: price, - low: price, - close: price, - volume: 10_000, - knownAt: ts, - }); - } - } - - const eventRows: TableRow[] = []; - for (let i = 0; i < 3; i += 1) { - // Released at 19:00 UTC on half-day index 8 -> anchors to index 9 (+10%) - eventRows.push({ - listing_id: listingIds[i]!, - ts: utcMs(dates[8]!, 19), - known_at: utcMs(dates[8]!, 19), - known_at_source: 'exact', - kind: 'filing' as EventKind, - subtype: '8-K', - payload_json: '{}', - }); - } - for (let i = 3; i < 6; i += 1) { - // Released at 19:00 UTC on half-day index 14 -> anchors to index 15 (+20%) - eventRows.push({ - listing_id: listingIds[i]!, - ts: utcMs(dates[14]!, 19), - known_at: utcMs(dates[14]!, 19), - known_at_source: 'exact', - kind: 'filing' as EventKind, - subtype: '8-K', - payload_json: '{}', - }); - } - - const store = createPassThroughStore({ - bars, - eventsTable: { columns: [...EVENTS_COLUMNS], rows: eventRows }, - }); - const ledger = createFakeLedger(); - - const resolveExchangeCalendars = async ( - q: EventStudyExchangeCalendarQuery - ): Promise => { - const sessions = dates - .filter(d => d >= q.fromDate && d <= q.toDate) - .map((date, _idx) => { - const globalIdx = dates.indexOf(date); - const closeHour = halfDayIndices.has(globalIdx) ? 18 : 21; - return { date, closeTs: utcMs(date, closeHour) }; - }); - const listingCalendarId = new Map(); - for (const id of q.listingIds) { - listingCalendarId.set(id, 'XNYS'); - } - return { - calendars: new Map([['XNYS', sessions]]), - listingCalendarId, - }; - }; - - const server = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store, - ledger: ledger.executor, - vaultContext: { vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars, - }), - ], - }); - - const res = await invoke(server, { - listingIds, - from: dates[0]!, - to: dates[23]!, - event: { kinds: ['filing'] }, - preDays: 1, - postDays: 1, - benchmark: 'none', - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }); - - expect(res.isError).toBeUndefined(); - expect(res.payload?.status).toBe('ok'); - if (res.payload?.status !== 'ok') { - throw new Error('Expected ok'); - } - - // Offset -1 is the half-day itself (0% return); Offset 0 is the next session (mean of +10% and +20% = +15%). - const offsetMinus1 = res.payload.study.offsets.find(o => o.offset === -1)!; - const offset0 = res.payload.study.offsets.find(o => o.offset === 0)!; - expect(offsetMinus1.aar).toBeCloseTo(0, 8); - expect(offset0.aar).toBeCloseTo(0.15, 8); - }); - - test('intraday Vault cutoff excludes rows on the cutoff UTC day and handles start-on-cutoff-day safely', async () => { - const dates = makeBusinessDates('2023-06-01', 25); - const cutoffDate = dates[20]!; - // Intraday Vault cutoff at 12:00 UTC on cutoffDate - const vaultCutoffTs = utcMs(cutoffDate, 12); - const listingIds = [201, 202, 203, 204, 205, 206]; - - const bars: BarRecord[] = []; - for (const id of listingIds) { - let price = 50; - for (let t = 0; t < 22; t += 1) { - price = Number((price * (1 + (t % 3 === 0 ? 0.02 : -0.005))).toFixed(6)); - const ts = t === 20 ? utcMs(dates[t]!, 10) : utcMs(dates[t]!, 21); // Bar on cutoff day at 10:00 UTC (< cutoffTs!) - bars.push({ - listingId: id, - ts, - open: price, - high: price, - low: price, - close: price, - volume: 5_000, - knownAt: ts, - }); - } - } - - const baseEvents: TableRow[] = [ - // 6 valid pre-cutoff events across 2 dates - ...listingIds.slice(0, 3).map(id => ({ - listing_id: id, - ts: utcMs(dates[6]!, 14), - known_at: utcMs(dates[6]!, 14), - known_at_source: 'exact', - kind: 'filing', - subtype: '8-K', - payload_json: '{}', - })), - ...listingIds.slice(3, 6).map(id => ({ - listing_id: id, - ts: utcMs(dates[12]!, 14), - known_at: utcMs(dates[12]!, 14), - known_at_source: 'exact', - kind: 'filing', - subtype: '8-K', - payload_json: '{}', - })), - ]; - - const intradayCutoffEvents: TableRow[] = [ - // Event on cutoff UTC day BEFORE intraday vaultCutoffTs (10:00 UTC < 12:00 UTC) -> MUST be excluded! - { - listing_id: listingIds[0]!, - ts: utcMs(cutoffDate, 10), - known_at: utcMs(cutoffDate, 10), - known_at_source: 'exact', - kind: 'filing', - subtype: '8-K', - payload_json: '{}', - }, - // Valid ts earlier, but known_at on cutoff UTC day at 09:00 UTC (< 12:00 UTC) -> MUST be excluded! - { - listing_id: listingIds[1]!, - ts: utcMs(dates[10]!, 14), - known_at: utcMs(cutoffDate, 9), - known_at_source: 'exact', - kind: 'filing', - subtype: '8-K', - payload_json: '{}', - }, - // Unrequested valid kind on cutoff day -> MUST NOT inflate vaultExcludedEvents - { - listing_id: listingIds[2]!, - ts: utcMs(cutoffDate, 10), - known_at: utcMs(cutoffDate, 10), - known_at_source: 'exact', - kind: 'ceo_post', - subtype: null, - payload_json: '{}', - }, - ]; - - const calendarCalls: EventStudyExchangeCalendarQuery[] = []; - const resolveExchangeCalendars = async ( - q: EventStudyExchangeCalendarQuery - ): Promise => { - calendarCalls.push(q); - const sessions = dates - .filter(d => d >= q.fromDate && d <= q.toDate) - .map(date => ({ date, closeTs: utcMs(date, 21) })); - const listingCalendarId = new Map(); - for (const id of q.listingIds) { - listingCalendarId.set(id, 'XNYS'); - } - return { calendars: new Map([['XNYS', sessions]]), listingCalendarId }; - }; - - const store = createPassThroughStore({ - bars, - eventsTable: { - columns: [...EVENTS_COLUMNS], - rows: [...baseEvents, ...intradayCutoffEvents], - }, - }); - const ledger = createFakeLedger(); - const server = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store, - ledger: ledger.executor, - vaultContext: { vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars, - }), - ], - }); - - const res = await invoke(server, { - listingIds, - from: dates[0]!, - to: dates[21]!, - event: { kinds: ['filing'] }, - preDays: 2, - postDays: 2, - benchmark: 'none', - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }); - - expect(res.payload?.status).toBe('ok'); - expect(res.payload?.vaultExcludedEvents).toBe(2); - expect(res.payload?.panelDiagnostics.vaultExcludedDates).toBe(2); - expect(res.payload?.eventCount).toBe(6); - expect(calendarCalls[0]!.toDate < cutoffDate).toBe(true); - - // Request starting on the intraday cutoff day before vaultCutoffTs: - // returns insufficient_data cleanly without calling calendar resolver with inverted dates. - calendarCalls.length = 0; - const ledger2 = createFakeLedger(); - const server2 = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store, - ledger: ledger2.executor, - vaultContext: { vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars, - }), - ], - }); - - const startOnCutoffRes = await invoke(server2, { - listingIds, - from: `${cutoffDate}T01:00:00.000Z`, - to: `${cutoffDate}T11:00:00.000Z`, - event: { kinds: ['filing'] }, - preDays: 1, - postDays: 1, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }); - - expect(startOnCutoffRes.isError).toBeUndefined(); - expect(startOnCutoffRes.payload?.status).toBe('insufficient_data'); - expect(calendarCalls).toHaveLength(0); - expect(ledger2.insertCalls).toBe(0); - }); - - test('exact boundary timestamps (fromMs, toMs, asOfMs) and malformed ts rejection', async () => { - const dates = makeBusinessDates('2023-07-03', 20); - const vaultCutoffDate = dates[19]!; - const vaultCutoffTs = utcMs(vaultCutoffDate, 0); - const listingIds = [301, 302, 303, 304, 305, 306]; - - const bars: BarRecord[] = []; - for (const id of listingIds) { - let price = 30; - for (let t = 0; t < 19; t += 1) { - price = Number((price * (1 + (t % 2 === 0 ? 0.015 : -0.005))).toFixed(6)); - const ts = utcMs(dates[t]!, 21); - bars.push({ - listingId: id, - ts, - open: price, - high: price, - low: price, - close: price, - volume: 1_000, - knownAt: ts, - }); - } - } - - const fromIso = `${dates[2]}T00:00:00.000Z`; - const toIso = `${dates[15]}T23:59:59.999Z`; - const asOfIso = `${dates[14]}T21:00:00.000Z`; - const fromMs = Date.parse(fromIso); - const toMs = Date.parse(toIso); - const asOfMs = Date.parse(asOfIso); - - const rows: TableRow[] = [ - // Exact fromMs -> included - { - listing_id: listingIds[0]!, - ts: fromMs, - known_at: fromMs, - known_at_source: 'exact', - kind: 'filing', - subtype: '8-K', - payload_json: '{}', - }, - // fromMs - 1 -> excluded - { - listing_id: listingIds[1]!, - ts: fromMs - 1, - known_at: fromMs - 1, - known_at_source: 'exact', - kind: 'filing', - subtype: '8-K', - payload_json: '{}', - }, - // Exact asOfMs -> included - { - listing_id: listingIds[2]!, - ts: utcMs(dates[10]!, 14), - known_at: asOfMs, - known_at_source: 'exact', - kind: 'filing', - subtype: '8-K', - payload_json: '{}', - }, - // asOfMs + 1 -> excluded - { - listing_id: listingIds[3]!, - ts: utcMs(dates[10]!, 14), - known_at: asOfMs + 1, - known_at_source: 'exact', - kind: 'filing', - subtype: '8-K', - payload_json: '{}', - }, - // toMs + 1 -> excluded - { - listing_id: listingIds[4]!, - ts: toMs + 1, - known_at: asOfMs, - known_at_source: 'exact', - kind: 'filing', - subtype: '8-K', - payload_json: '{}', - }, - ]; - - const resolveExchangeCalendars = async ( - q: EventStudyExchangeCalendarQuery - ): Promise => { - const sessions = dates - .filter(d => d >= q.fromDate && d <= q.toDate) - .map(date => ({ date, closeTs: utcMs(date, 21) })); - const listingCalendarId = new Map(); - for (const id of q.listingIds) { - listingCalendarId.set(id, 'XNYS'); - } - return { calendars: new Map([['XNYS', sessions]]), listingCalendarId }; - }; - - const store = createPassThroughStore({ - bars, - eventsTable: { columns: [...EVENTS_COLUMNS], rows }, - }); - const ledger = createFakeLedger(); - const server = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store, - ledger: ledger.executor, - vaultContext: { vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars, - }), - ], - }); - - const res = await invoke(server, { - listingIds, - from: fromIso, - to: toIso, - asOf: asOfIso, - event: { kinds: ['filing'] }, - preDays: 1, - postDays: 1, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }); - - // Only 2 events survived the exact boundaries (fromMs and asOfMs) -> insufficient_data (< 5) - expect(res.payload?.status).toBe('insufficient_data'); - expect(res.payload?.eventCount).toBe(2); - expect(ledger.insertCalls).toBe(0); - - // Malformed `ts` on an otherwise eligible event row must fail with sanitized EventPanelError - const malformedStore = createPassThroughStore({ - bars, - eventsTable: { - columns: [...EVENTS_COLUMNS], - rows: [ - { - listing_id: listingIds[0]!, - ts: 'not-a-timestamp' as unknown as number, - known_at: fromMs, - known_at_source: 'exact', - kind: 'filing', - subtype: '8-K', - payload_json: '{}', - }, - ], - }, - }); - const malformedLedger = createFakeLedger(); - const malformedServer = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store: malformedStore, - ledger: malformedLedger.executor, - vaultContext: { vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars, - }), - ], - }); - - const badRes = await invoke(malformedServer, { - listingIds, - from: fromIso, - to: toIso, - asOf: asOfIso, - event: { kinds: ['filing'] }, - preDays: 1, - postDays: 1, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }); - - expect(badRes.isError).toBe(true); - expect(badRes.text).toBe('EventPanelError: Event table data failed event panel validation.'); - expect(malformedLedger.insertCalls).toBe(0); - }); - - test('microsecond-precision from rejects leaked boundary-millisecond event and matches clean run', async () => { - const dates = makeBusinessDates('2023-07-03', 24); - const vaultCutoffDate = dates[23]!; - const vaultCutoffTs = utcMs(vaultCutoffDate, 0); - const listingIds = [401, 402, 403, 404, 405, 406]; - - const bars: BarRecord[] = []; - for (let l = 0; l < listingIds.length; l += 1) { - const id = listingIds[l]!; - let price = 40 + l * 2; - for (let t = 0; t < 23; t += 1) { - // Distinct per-listing returns on dates[3] so admitting listingIds[1] at .123Z - // measurably shifts eventCount, eventsUsed, CAR, and ledger daily_series. - const ret = - t === 3 - ? l === 1 - ? 0.25 - : 0.05 - : t === 9 - ? 0.03 + l * 0.004 - : t === 15 - ? -0.02 + l * 0.003 - : 0.002; - price = Number((price * (1 + ret)).toFixed(6)); - const ts = utcMs(dates[t]!, 21); - bars.push({ - listingId: id, - ts, - open: price, - high: price, - low: price, - close: price, - volume: 10_000, - knownAt: ts, - }); - } - } - - // Researcher sets microsecond-precision start on half-day dates[2] (18:00 UTC close, 21:00 UTC bar stamp): - // bars from dates[2]..dates[22] enter the panel, so dates[3] (session index 1) has finite close-to-close returns. - // A leaked filing at 19:00:00.123Z (< .123456Z) would anchor to dates[3] and shift CAR/daily_series if admitted. - // A valid filing at 19:00:00.124Z (> .123456Z) must be admitted and anchored to dates[3]. - const microFromIso = `${dates[2]}T19:00:00.123456Z`; - const leakedBoundaryMs = Date.parse(`${dates[2]}T19:00:00.123Z`); - const admittedNextMs = Date.parse(`${dates[2]}T19:00:00.124Z`); - - const validRows: TableRow[] = [ - // Admitted event at fromMs + 1 (.124Z) -> anchors to dates[3] (after dates[2] 18:00 UTC half-day close) - { - listing_id: listingIds[0]!, - ts: admittedNextMs, - known_at: admittedNextMs, - known_at_source: 'exact', - kind: 'filing', - subtype: '8-K', - payload_json: '{}', - }, - // 3 events on dates[9] - ...listingIds.slice(0, 3).map(id => ({ - listing_id: id, - ts: utcMs(dates[9]!, 14), - known_at: utcMs(dates[9]!, 14), - known_at_source: 'exact', - kind: 'filing' as EventKind, - subtype: '8-K', - payload_json: '{}', - })), - // 3 events on dates[15] - ...listingIds.slice(3, 6).map(id => ({ - listing_id: id, - ts: utcMs(dates[15]!, 14), - known_at: utcMs(dates[15]!, 14), - known_at_source: 'exact', - kind: 'filing' as EventKind, - subtype: '8-K', - payload_json: '{}', - })), - ]; - - // Leaked out-of-window filing at .123Z (strictly before .123456Z) on listingIds[1] (+25% on dates[3]). - const leakedRow: TableRow = { - listing_id: listingIds[1]!, - ts: leakedBoundaryMs, - known_at: leakedBoundaryMs, - known_at_source: 'exact', - kind: 'filing', - subtype: '8-K', - payload_json: '{}', - }; - - const resolveExchangeCalendars = async ( - q: EventStudyExchangeCalendarQuery - ): Promise => { - const sessions = dates - .filter(d => d >= q.fromDate && d <= q.toDate) - .map(date => ({ - date, - closeTs: utcMs(date, date === dates[2] ? 18 : 21), - })); - const listingCalendarId = new Map(); - for (const id of q.listingIds) { - listingCalendarId.set(id, 'XNYS'); - } - return { calendars: new Map([['XNYS', sessions]]), listingCalendarId }; - }; - - const runWithRows = async (rows: readonly TableRow[]) => { - const store = createPassThroughStore({ - bars, - eventsTable: { columns: [...EVENTS_COLUMNS], rows: [...rows] }, - }); - const ledger = createFakeLedger(); - const server = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store, - ledger: ledger.executor, - vaultContext: { vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars, - }), - ], - }); - const res = await invoke(server, { - listingIds, - from: microFromIso, - to: dates[22]!, - event: { kinds: ['filing'] }, - preDays: 0, - postDays: 1, - benchmark: 'none', - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }); - return { res, ledger }; - }; - - const leaky = await runWithRows([leakedRow, ...validRows]); - const clean = await runWithRows(validRows); - - expect(leaky.res.isError).toBeUndefined(); - expect(clean.res.isError).toBeUndefined(); - expect(leaky.res.payload?.status).toBe('ok'); - expect(clean.res.payload?.status).toBe('ok'); - if (leaky.res.payload?.status !== 'ok' || clean.res.payload?.status !== 'ok') { - throw new Error('Expected ok payloads'); - } - - // Leaked .123Z row must be excluded; admitted .124Z row + 6 later events = 7 anchored & used events. - expect(leaky.res.payload.eventCount).toBe(7); - expect(clean.res.payload.eventCount).toBe(7); - expect(leaky.res.payload.study.diagnostics.eventsUsed).toBe(7); - expect(clean.res.payload.study.diagnostics.eventsUsed).toBe(7); - expect(leaky.res.payload.study.offsets).toEqual(clean.res.payload.study.offsets); - expect(leaky.res.payload.trial.expressionHash).toBe(clean.res.payload.trial.expressionHash); - expect(leaky.ledger.rows[0]!.daily_series).toEqual(clean.ledger.rows[0]!.daily_series); - }); -}); - -// --------------------------------------------------------------------------- -// Quant QA additions (T-133): exact benchmark economics, late-revised bars, -// subtype-filter accounting, resolver contract edges, and microsecond upper bounds. -// Fixture "qa-t133-v1": 6 listings, weekday sessions, flat prices except -// explicit jump days; gross close-to-close returns, raw adjustment, no costs. -// --------------------------------------------------------------------------- - -const QA_LISTINGS = [701, 702, 703, 704, 705, 706]; - -function qaXnysResolver(dates: readonly string[]) { - const calls: EventStudyExchangeCalendarQuery[] = []; - const resolve = (q: EventStudyExchangeCalendarQuery): EventStudyExchangeCalendars => { - calls.push(q); - const sessions = dates - .filter(d => d >= q.fromDate && d <= q.toDate) - .map(date => ({ date, closeTs: utcMs(date, 21) })); - const listingCalendarId = new Map(); - for (const id of q.listingIds) { - listingCalendarId.set(id, 'XNYS'); - } - return { calendars: new Map([['XNYS', sessions]]), listingCalendarId }; - }; - return { calls, resolve }; -} - -/** Flat 100 prices; `jumps` maps `${listingIndex}:${dayIndex}` -> daily return. */ -function qaBars(dates: readonly string[], days: number, jumps: ReadonlyMap) { - const bars: BarRecord[] = []; - for (let l = 0; l < QA_LISTINGS.length; l += 1) { - let price = 100; - for (let t = 0; t < days; t += 1) { - price = Number((price * (1 + (jumps.get(`${l}:${t}`) ?? 0))).toFixed(6)); - const ts = utcMs(dates[t]!, 21); - bars.push({ - listingId: QA_LISTINGS[l]!, - ts, - open: price, - high: price, - low: price, - close: price, - volume: 1_000, - knownAt: ts, - }); - } - } - return bars; -} - -function qaEvent(l: number, ts: number, extra?: Partial): TableRow { - return { - listing_id: QA_LISTINGS[l]!, - ts, - known_at: ts, - known_at_source: 'exact', - kind: 'filing', - subtype: '8-K', - payload_json: '{}', - ...extra, - }; -} - -function qaServer(params: { - bars: readonly BarRecord[]; - rows: readonly TableRow[]; - vaultCutoffTs: number; - resolveExchangeCalendars: ( - q: EventStudyExchangeCalendarQuery - ) => EventStudyExchangeCalendars | Promise; -}) { - const ledger = createFakeLedger(); - const server = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store: createPassThroughStore({ - bars: params.bars, - eventsTable: { columns: [...EVENTS_COLUMNS], rows: [...params.rows] }, - }), - ledger: ledger.executor, - vaultContext: { vaultCutoffTs: params.vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars: params.resolveExchangeCalendars, - }), - ], - }); - return { server, ledger }; -} - -describe('MCP event_study QA additions', () => { - // Day 6: listings 0-2 get +10% with events; day 12: listings 3-5 get +20% with events. - // Other listings are flat, so the equal-weight benchmark on day 6 is 0.05 and on day 12 is 0.10. - const dates = makeBusinessDates('2023-03-01', 22); - const vaultCutoffTs = utcMs(dates[21]!, 0); - const jumps = new Map([ - ['0:6', 0.1], - ['1:6', 0.1], - ['2:6', 0.1], - ['3:12', 0.2], - ['4:12', 0.2], - ['5:12', 0.2], - ]); - const bars = qaBars(dates, 21, jumps); - const eventRows: TableRow[] = [ - ...[0, 1, 2].map(l => qaEvent(l, utcMs(dates[6]!, 14))), - ...[3, 4, 5].map(l => qaEvent(l, utcMs(dates[12]!, 14))), - ]; - const baseArgs = { - listingIds: QA_LISTINGS, - from: dates[0]!, - to: dates[20]!, - event: { kinds: ['filing'] }, - preDays: 1, - postDays: 1, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }; - - test('benchmark "none" reports raw event-day returns and "equal_weight" subtracts the cross-sectional mean', async () => { - const none = qaServer({ - bars, - rows: eventRows, - vaultCutoffTs, - resolveExchangeCalendars: qaXnysResolver(dates).resolve, - }); - const ew = qaServer({ - bars, - rows: eventRows, - vaultCutoffTs, - resolveExchangeCalendars: qaXnysResolver(dates).resolve, - }); - - const resNone = await invoke(none.server, { ...baseArgs, benchmark: 'none' }); - const resEw = await invoke(ew.server, { ...baseArgs, benchmark: 'equal_weight' }); - - if (resNone.payload?.status !== 'ok' || resEw.payload?.status !== 'ok') { - throw new Error(`Expected ok payloads: ${resNone.text} | ${resEw.text}`); - } - const at = (p: typeof resNone.payload, offset: number) => - p.study.offsets.find(o => o.offset === offset)!; - - // none: mean(+10% x3, +20% x3) = 0.15; flat neighbours. - expect(at(resNone.payload, 0).aar).toBeCloseTo(0.15, 10); - expect(at(resNone.payload, -1).aar).toBeCloseTo(0, 10); - expect(at(resNone.payload, 1).aar).toBeCloseTo(0, 10); - // equal_weight: mean(0.10-0.05 x3, 0.20-0.10 x3) = 0.075. - expect(at(resEw.payload, 0).aar).toBeCloseTo(0.075, 10); - expect(at(resEw.payload, 0).n).toBe(6); - expect(resNone.payload.study.hasBenchmark).toBe(false); - expect(resEw.payload.study.hasBenchmark).toBe(true); - expect(none.ledger.insertCalls).toBe(1); - expect(ew.ledger.insertCalls).toBe(1); - expect(resNone.payload.trial.expressionHash).not.toBe(resEw.payload.trial.expressionHash); - }); - - test('a late-revised bar (knownAt > asOf) leaked by the store is dropped before the panel', async () => { - const asOfIso = `${dates[18]!}T21:00:00.000Z`; - // Same (listing, ts) as an original bar but a different close and knownAt after asOf. - // If admitted, the panel would throw duplicate_bar or change returns. - const revised: BarRecord = { - ...bars.find(b => b.listingId === QA_LISTINGS[0] && b.ts === utcMs(dates[6]!, 21))!, - close: 999, - open: 999, - high: 999, - low: 999, - knownAt: utcMs(dates[19]!, 12), - }; - const clean = qaServer({ - bars, - rows: eventRows, - vaultCutoffTs, - resolveExchangeCalendars: qaXnysResolver(dates).resolve, - }); - const leaky = qaServer({ - bars: [...bars, revised], - rows: eventRows, - vaultCutoffTs, - resolveExchangeCalendars: qaXnysResolver(dates).resolve, - }); - - const resClean = await invoke(clean.server, { ...baseArgs, asOf: asOfIso, benchmark: 'none' }); - const resLeaky = await invoke(leaky.server, { ...baseArgs, asOf: asOfIso, benchmark: 'none' }); - - expect(resLeaky.isError).toBeUndefined(); - if (resLeaky.payload?.status !== 'ok' || resClean.payload?.status !== 'ok') { - throw new Error(`Expected ok payloads: ${resLeaky.text}`); - } - expect(resLeaky.payload.study.offsets).toEqual(resClean.payload.study.offsets); - expect(resLeaky.payload.panelDiagnostics).toEqual(resClean.payload.panelDiagnostics); - expect(leaky.ledger.rows[0]!.daily_series).toEqual(clean.ledger.rows[0]!.daily_series); - }); - - test('subtype filter drops null and non-matching subtypes (even in the Vault) without counting Vault exclusions', async () => { - const noise: TableRow[] = [ - qaEvent(0, utcMs(dates[9]!, 14), { subtype: null }), - qaEvent(1, utcMs(dates[9]!, 14), { subtype: '10-Q' }), - // Non-matching subtype on the cutoff day: filtered as unrequested, not as a Vault exclusion. - qaEvent(2, utcMs(dates[21]!, 14), { subtype: '10-K' }), - // Matching subtype on the cutoff day: a genuine Vault exclusion. - qaEvent(3, utcMs(dates[21]!, 14)), - ]; - const { server, ledger } = qaServer({ - bars, - rows: [...eventRows, ...noise], - vaultCutoffTs, - resolveExchangeCalendars: qaXnysResolver(dates).resolve, - }); - - const res = await invoke(server, { - ...baseArgs, - event: { kinds: ['filing'], subtypes: ['8-K'] }, - benchmark: 'none', - }); - - if (res.payload?.status !== 'ok') { - throw new Error(`Expected ok: ${res.text}`); - } - expect(res.payload.eventCount).toBe(6); - expect(res.payload.vaultExcludedEvents).toBe(1); - expect(res.payload.event.subtypes).toEqual(['8-K']); - expect(res.payload.study.offsets.find(o => o.offset === 0)!.aar).toBeCloseTo(0.15, 10); - expect(ledger.insertCalls).toBe(1); - }); - - test('synchronous calendar resolver is accepted and a non-Error throw maps to the fixed resolver message', async () => { - const sync = qaServer({ - bars, - rows: eventRows, - vaultCutoffTs, - resolveExchangeCalendars: qaXnysResolver(dates).resolve, - }); - const syncRes = await invoke(sync.server, { ...baseArgs, benchmark: 'none' }); - expect(syncRes.payload?.status).toBe('ok'); - - const SECRET = 'SECRET_CAL_DSN_55120'; - const failing = qaServer({ - bars, - rows: eventRows, - vaultCutoffTs, - resolveExchangeCalendars: () => { - throw `postgres://calendar:${SECRET}@db/cal`; - }, - }); - const failRes = await invoke(failing.server, { ...baseArgs, benchmark: 'none' }); - expect(failRes.isError).toBe(true); - expect(failRes.text).toBe('Error: Exchange calendar resolution failed.'); - expect(failRes.text).not.toContain(SECRET); - expect(failing.ledger.insertCalls).toBe(0); - - const rejecting = qaServer({ - bars, - rows: eventRows, - vaultCutoffTs, - resolveExchangeCalendars: () => Promise.reject(new TypeError(`/srv/cal/${SECRET}.parquet`)), - }); - const rejectRes = await invoke(rejecting.server, { ...baseArgs, benchmark: 'none' }); - expect(rejectRes.isError).toBe(true); - expect(rejectRes.text).toBe('Error: Exchange calendar resolution failed.'); - expect(rejectRes.text).not.toContain(SECRET); - }); - - test('microsecond-precision to/asOf keep rows at the boundary millisecond and drop the next millisecond', async () => { - // to/asOf at dates[14] 15:00:00.123456Z. Base events (days 6, 12) are inside the window. - const boundaryIso = `${dates[14]!}T15:00:00.123456Z`; - const boundaryMs = Date.parse(`${dates[14]!}T15:00:00.123Z`); - const extra: TableRow[] = [ - qaEvent(0, boundaryMs), // ts == toMs, known_at == asOfMs (.123 <= .123456) -> kept - qaEvent(1, boundaryMs + 1), // .124 > .123456 -> dropped - qaEvent(2, utcMs(dates[10]!, 14), { known_at: boundaryMs + 1 }), // known after asOf -> dropped - ]; - const { server } = qaServer({ - bars, - rows: [...eventRows, ...extra], - vaultCutoffTs, - resolveExchangeCalendars: qaXnysResolver(dates).resolve, - }); - - const res = await invoke(server, { - ...baseArgs, - to: boundaryIso, - asOf: boundaryIso, - benchmark: 'none', - }); - - expect(res.isError).toBeUndefined(); - expect(res.payload?.effectiveTo).toBe(boundaryIso); - expect(res.payload?.effectiveAsOf).toBe(boundaryIso); - // The boundary-ms event passes the defensive filter and reaches the panel, which drops it - // as after-last-session (its dates[14] close is after asOf). The .124 rows never reach the - // panel: if they did, droppedAfterLastSession would be > 1 or eventCount would change. - expect(res.payload?.panelDiagnostics.droppedAfterLastSession).toBe(1); - expect(res.payload?.eventCount).toBe(6); - expect(res.payload?.study.diagnostics.eventsUsed).toBe(6); - expect(res.payload?.vaultExcludedEvents).toBe(0); - }); -}); diff --git a/libs/research/test/mcp-event-study.test.ts b/libs/research/test/mcp-event-study.test.ts deleted file mode 100644 index 30729c3b..00000000 --- a/libs/research/test/mcp-event-study.test.ts +++ /dev/null @@ -1,1451 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { - EventPanelError, - type EventStudyExchangeCalendars, - buildEventStudyInput, - eventsTableToEventRows, -} from '../src/event-panel'; -import { - type BarBatch, - type BarRecord, - type EventKind, - type MarketDataStore, - MarketDataStoreValidationError, - type Table, - type TableRow, - VaultHoldoutFenceError, - VaultScopeNotAuthorizedError, -} from '../src/market-data-store'; -import { - AdjFactorsSnapshotError, - type BarsQuery, - EVENTS_COLUMNS, - type EventsQuery, - MarketDataStoreNotImplementedError, - type UniverseQuery, -} from '../src/market-data-store-duckdb'; -import { - EVENT_STUDY_MAX_LISTING_IDS, - EVENT_STUDY_MAX_POST_DAYS, - EVENT_STUDY_MAX_PRE_DAYS, - EVENT_STUDY_MAX_SUBTYPES, - EVENT_STUDY_MAX_SUBTYPE_LENGTH, - type EventStudyExchangeCalendarQuery, - type EventStudyResultPayload, - createEventStudyTool, - createMcpServer, -} from '../src/mcp/index'; -import { SignalStudyError, runEventStudy } from '../src/signal-study'; -import { TrialLedgerError, type TrialLedgerExecutor } from '../src/trial-ledger'; - -// Synthetic fixture: seeded (20261201) 8 listings, 60 pre-cutoff + 8 post-cutoff -// business sessions from 2022-11-01, daily close-to-close returns, raw adjustment, -// no fills or transaction costs, XNYS 21:00 UTC close calendar. -const SEED = 20261201; -const AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555'; -const CAMPAIGN_UUID = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee'; -const HYPOTHESIS_UUID = '12345678-1234-4123-8123-123456789abc'; - -function createSeededRng(seed: number): () => number { - let state = seed >>> 0; - return () => { - state = (state + 0x6d2b79f5) >>> 0; - let t = Math.imul(state ^ (state >>> 15), 1 | state); - t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; - return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296; - }; -} - -function makeBusinessDates(startDate: string, count: number): string[] { - const out: string[] = new Array(count); - const current = new Date(`${startDate}T00:00:00.000Z`); - let written = 0; - while (written < count) { - const day = current.getUTCDay(); - if (day !== 0 && day !== 6) { - out[written] = current.toISOString().slice(0, 10); - written += 1; - } - current.setUTCDate(current.getUTCDate() + 1); - } - return out; -} - -function makeUtcMs(date: string, hourUtc: number, minuteUtc = 0): number { - const [y, m, d] = date.split('-').map(Number); - return Date.UTC(y!, m! - 1, d!, hourUtc, minuteUtc, 0, 0); -} - -function parseBound(raw: string, endOfDay: boolean): number { - if (raw.length === 10) { - return Date.parse(`${raw}T${endOfDay ? '23:59:59.999' : '00:00:00.000'}Z`); - } - return Date.parse(raw); -} - -interface StoredTrialRow { - readonly trial_id: string; - readonly created_at: Date; - readonly principal_id: string; - readonly campaign_id: string | null; - readonly stage: string; - readonly universe_market: string; - readonly horizon_bucket: string; - readonly hypothesis_id: string | null; - readonly expression_hash: string; - readonly sample_start: string; - readonly sample_end: string; - readonly n_obs: number; - readonly sharpe_unann: number; - readonly skewness: number; - readonly kurtosis: number; - readonly daily_series: readonly number[]; -} - -function createFakeTrialLedger(options?: { - insertError?: Error; - dsrReadError?: Error; -}): { - executor: TrialLedgerExecutor; - rows: StoredTrialRow[]; - insertCalls: number; - selectCalls: number; -} { - const rows: StoredTrialRow[] = []; - let nextTrialId = 1; - const state = { - rows, - insertCalls: 0, - selectCalls: 0, - executor: null as unknown as TrialLedgerExecutor, - }; - - state.executor = { - async query>(text: string, params?: readonly unknown[]) { - const trimmed = text.trimStart(); - if (trimmed.startsWith('INSERT INTO trial_ledger')) { - state.insertCalls += 1; - if (options?.insertError !== undefined) { - throw options.insertError; - } - const p = params ?? []; - const trialId = nextTrialId++; - const createdAt = new Date(Date.UTC(2024, 5, 1, 12, 0, trialId)); - const dailySeries = (p[13] as readonly number[]).map(v => Math.fround(v)); - const stored: StoredTrialRow = { - trial_id: String(trialId), - created_at: createdAt, - principal_id: p[0] as string, - campaign_id: (p[1] as string | null) ?? null, - stage: p[2] as string, - universe_market: p[3] as string, - horizon_bucket: p[4] as string, - hypothesis_id: (p[5] as string | null) ?? null, - expression_hash: p[6] as string, - sample_start: p[7] as string, - sample_end: p[8] as string, - n_obs: p[9] as number, - sharpe_unann: p[10] as number, - skewness: p[11] as number, - kurtosis: p[12] as number, - daily_series: dailySeries, - }; - rows.push(stored); - return { - rows: [{ trial_id: stored.trial_id, created_at: stored.created_at } as unknown as Row], - rowCount: 1, - }; - } - - if (trimmed.startsWith('SELECT')) { - state.selectCalls += 1; - if (options?.dsrReadError !== undefined) { - throw options.dsrReadError; - } - if (text.includes('WHERE trial_id = $1::bigint')) { - const targetId = String(params?.[0]); - const matched = rows.filter(r => r.trial_id === targetId); - return { rows: matched as unknown as Row[], rowCount: matched.length }; - } - if (text.includes('WHERE universe_market = $1')) { - const market = params?.[0] as string; - const bucket = params?.[1] as string; - const matched = rows.filter( - r => r.universe_market === market && r.horizon_bucket === bucket - ); - return { rows: matched as unknown as Row[], rowCount: matched.length }; - } - } - - return { rows: [], rowCount: 0 }; - }, - }; - - return state; -} - -interface SyntheticEventFixture { - readonly listingIds: number[]; - readonly allDates: string[]; - readonly vaultCutoffDate: string; - readonly vaultCutoffTs: number; - readonly bars: BarRecord[]; - readonly eventsTable: Table; -} - -function buildSyntheticEventFixture(options?: { - preCutoffSessions?: number; - postCutoffSessions?: number; - listingCount?: number; - zeroVariance?: boolean; -}): SyntheticEventFixture { - const rand = createSeededRng(SEED); - const listingCount = options?.listingCount ?? 8; - const preCutoffSessions = options?.preCutoffSessions ?? 65; - const postCutoffSessions = options?.postCutoffSessions ?? 8; - const zeroVariance = options?.zeroVariance ?? false; - - const allDates = makeBusinessDates('2022-11-01', preCutoffSessions + postCutoffSessions); - const vaultCutoffDate = allDates[preCutoffSessions]!; - const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0); - const listingIds = Array.from({ length: listingCount }, (_, i) => 60_001 + i); - - const bars: BarRecord[] = []; - const eventRows: TableRow[] = []; - const prices = Array.from({ length: listingCount }, (_, i) => 20 + i * 3); - - // Place filings across multiple pre-cutoff dates (well inside window) and some post-cutoff. - const eventDayIndices = [12, 18, 26, 34, 42, 50]; - const eventSet = new Set(); - for (let eIdx = 0; eIdx < eventDayIndices.length; eIdx += 1) { - const t = eventDayIndices[eIdx]!; - if (t >= preCutoffSessions) { - continue; - } - // 2 listings per event date => 12 events across 6 distinct dates (spans pre and post 2023-01-01) - for (let k = 0; k < 2; k += 1) { - const l = (eIdx * 2 + k) % listingCount; - eventSet.add(`${t}:${l}`); - const date = allDates[t]!; - const ts = makeUtcMs(date, 14); // 09:00 ET intraday filing -> anchors on same session - const kind: EventKind = eIdx % 2 === 0 ? 'filing' : 'earnings'; - const subtype = kind === 'filing' ? '8-K' : 'Q4'; - eventRows.push({ - listing_id: listingIds[l]!, - ts, - known_at: ts, - known_at_source: 'exact', - kind, - subtype, - payload_json: '{}', - }); - } - } - - for (let t = 0; t < allDates.length; t += 1) { - const date = allDates[t]!; - const closeTs = makeUtcMs(date, 21); // 16:00 ET close - for (let l = 0; l < listingCount; l += 1) { - let close: number; - if (zeroVariance) { - close = 100; - } else { - const isEvent = eventSet.has(`${t}:${l}`); - const base = (rand() - 0.5) * 0.015; - const dailyRet = isEvent ? base + 0.025 + l * 0.002 : base; - prices[l] = Math.max(0.5, prices[l]! * (1 + dailyRet)); - close = Number(prices[l]!.toFixed(6)); - } - bars.push({ - listingId: listingIds[l]!, - ts: closeTs, - open: close, - high: close, - low: close, - close, - volume: 25_000, - vwap: close, - knownAt: closeTs, - }); - } - } - - return { - listingIds, - allDates, - vaultCutoffDate, - vaultCutoffTs, - bars, - eventsTable: { - columns: [...EVENTS_COLUMNS], - rows: eventRows, - }, - }; -} - -interface FakeStoreState { - readonly store: MarketDataStore; - readonly barsCalls: BarsQuery[]; - readonly eventsCalls: EventsQuery[]; - readonly universeCalls: UniverseQuery[]; -} - -function createFakeStore( - fixture: SyntheticEventFixture, - options?: { - extraBars?: readonly BarRecord[]; - extraEvents?: readonly TableRow[]; - universeResolver?: (q: UniverseQuery) => number[]; - barsError?: unknown; - eventsError?: unknown; - universeError?: unknown; - } -): FakeStoreState { - const barsCalls: BarsQuery[] = []; - const eventsCalls: EventsQuery[] = []; - const universeCalls: UniverseQuery[] = []; - - const store: MarketDataStore = { - bars(q: BarsQuery): AsyncIterable { - barsCalls.push(q); - const ids = new Set(q.listingIds); - const fromMs = parseBound(q.from, false); - const toMs = parseBound(q.to, true); - const asOfMs = q.asOf === undefined ? Number.POSITIVE_INFINITY : parseBound(q.asOf, true); - const rows = fixture.bars.filter( - b => - ids.has(b.listingId) && - b.ts >= fromMs && - b.ts <= toMs && - b.ts <= asOfMs && - b.knownAt <= asOfMs - ); - const thrown = options?.barsError; - return { - async *[Symbol.asyncIterator]() { - if (thrown !== undefined) { - throw thrown; - } - yield { rows: [...rows, ...(options?.extraBars ?? [])] }; - }, - }; - }, - async events(q: EventsQuery): Promise
{ - eventsCalls.push(q); - if (options?.eventsError !== undefined) { - throw options.eventsError; - } - const kinds = new Set(q.kinds); - const ids = q.listingIds !== undefined ? new Set(q.listingIds) : null; - const fromMs = parseBound(q.from, false); - const toMs = parseBound(q.to, true); - const asOfMs = q.asOf === undefined ? Number.POSITIVE_INFINITY : parseBound(q.asOf, true); - const rows = fixture.eventsTable.rows.filter(r => { - if (!kinds.has(r.kind as string)) { - return false; - } - if (ids !== null && !ids.has(r.listing_id as number)) { - return false; - } - const ts = r.ts as number; - const knownAt = r.known_at as number; - return ts >= fromMs && ts <= toMs && knownAt <= asOfMs; - }); - return { - columns: fixture.eventsTable.columns, - rows: [...rows, ...(options?.extraEvents ?? [])], - }; - }, - async universe(q: UniverseQuery): Promise { - universeCalls.push(q); - if (options?.universeError !== undefined) { - throw options.universeError; - } - return options?.universeResolver ? options.universeResolver(q) : fixture.listingIds; - }, - crossSection() { - throw new MarketDataStoreNotImplementedError('crossSection'); - }, - fundamentalsAsOf() { - throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); - }, - shortsAsOf() { - throw new MarketDataStoreNotImplementedError('shortsAsOf'); - }, - macroAsOf() { - throw new MarketDataStoreNotImplementedError('macroAsOf'); - }, - fx() { - throw new MarketDataStoreNotImplementedError('fx'); - }, - }; - - return { store, barsCalls, eventsCalls, universeCalls }; -} - -function createFakeCalendarResolver( - dates: readonly string[], - options?: { - hourUtc?: number; - error?: unknown; - } -): { - calls: EventStudyExchangeCalendarQuery[]; - resolveExchangeCalendars: ( - q: EventStudyExchangeCalendarQuery - ) => Promise; -} { - const calls: EventStudyExchangeCalendarQuery[] = []; - const hourUtc = options?.hourUtc ?? 21; - - return { - calls, - async resolveExchangeCalendars( - q: EventStudyExchangeCalendarQuery - ): Promise { - calls.push(q); - if (options?.error !== undefined) { - throw options.error; - } - const sessions = dates - .filter(d => d >= q.fromDate && d <= q.toDate) - .map(date => ({ date, closeTs: makeUtcMs(date, hourUtc) })); - const listingCalendarId = new Map(); - for (const id of q.listingIds) { - listingCalendarId.set(id, 'XNYS'); - } - return { - calendars: new Map([['XNYS', sessions]]), - listingCalendarId, - }; - }, - }; -} - -async function callEventStudy( - server: ReturnType, - args: Record, - id = 1 -): Promise<{ - rpc: Record; - result?: { content: Array<{ type: string; text: string }>; isError?: boolean }; - payload?: EventStudyResultPayload; -}> { - const raw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id, - method: 'tools/call', - params: { name: 'event_study', arguments: args }, - }) - ); - const rpc = JSON.parse(raw!) as Record; - const result = rpc.result as - | { content: Array<{ type: string; text: string }>; isError?: boolean } - | undefined; - let payload: EventStudyResultPayload | undefined; - if (result !== undefined && !result.isError && result.content[0]?.text) { - payload = JSON.parse(result.content[0].text) as EventStudyResultPayload; - } - return { rpc, result, payload }; -} - -describe('MCP event_study tool', () => { - test('tools/list advertises strict JSON schema and exported bounds constants', async () => { - const fixture = buildSyntheticEventFixture(); - const fakeStore = createFakeStore(fixture); - const ledger = createFakeTrialLedger(); - const cal = createFakeCalendarResolver(fixture.allDates); - - const server = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store: fakeStore.store, - ledger: ledger.executor, - vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars: cal.resolveExchangeCalendars, - }), - ], - }); - - expect(EVENT_STUDY_MAX_LISTING_IDS).toBe(500); - expect(EVENT_STUDY_MAX_PRE_DAYS).toBe(60); - expect(EVENT_STUDY_MAX_POST_DAYS).toBe(60); - expect(EVENT_STUDY_MAX_SUBTYPES).toBe(100); - expect(EVENT_STUDY_MAX_SUBTYPE_LENGTH).toBe(128); - - const raw = await server.handleMessage( - JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} }) - ); - const parsed = JSON.parse(raw!) as { - result: { - tools: Array<{ - name: string; - inputSchema: { - type: string; - additionalProperties: boolean; - properties: Record>; - }; - }>; - }; - }; - - expect(parsed.result.tools).toHaveLength(1); - const tool = parsed.result.tools[0]!; - expect(tool.name).toBe('event_study'); - expect(tool.inputSchema.type).toBe('object'); - expect(tool.inputSchema.additionalProperties).toBe(false); - - const props = tool.inputSchema.properties; - expect(props.scope).toBeUndefined(); - expect(props.principalId).toBeUndefined(); - expect(props.vaultCutoffDate).toBeUndefined(); - expect(props.vault_evaluation_only).toBeUndefined(); - - const eventSchema = props.event as { - additionalProperties?: boolean; - properties?: { - subtypes?: { - maxItems?: number; - items?: { maxLength?: number }; - }; - }; - }; - expect(eventSchema.additionalProperties).toBe(false); - expect(eventSchema.properties?.subtypes?.maxItems).toBe(EVENT_STUDY_MAX_SUBTYPES); - expect(eventSchema.properties?.subtypes?.items?.maxLength).toBe( - EVENT_STUDY_MAX_SUBTYPE_LENGTH - ); - }); - - test('happy path matches direct runEventStudy, writes one event_study trial, and omits raw series', async () => { - const fixture = buildSyntheticEventFixture(); - const fakeStore = createFakeStore(fixture); - const ledger = createFakeTrialLedger(); - const cal = createFakeCalendarResolver(fixture.allDates); - - const server = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store: fakeStore.store, - ledger: ledger.executor, - vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars: cal.resolveExchangeCalendars, - }), - ], - }); - - const from = fixture.allDates[0]!; - const to = fixture.allDates[64]!; - const preDays = 3; - const postDays = 5; - - const { result, payload } = await callEventStudy(server, { - listingIds: fixture.listingIds, - from, - to, - event: { kinds: ['filing', 'earnings'] }, - preDays, - postDays, - benchmark: 'equal_weight', - adjustment: 'raw', - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - campaignId: CAMPAIGN_UUID, - hypothesisId: HYPOTHESIS_UUID, - }); - - expect(result?.isError).toBeUndefined(); - expect(payload).toBeDefined(); - expect(payload?.status).toBe('ok'); - if (!payload || payload.status !== 'ok') { - throw new Error('Expected ok payload'); - } - - expect(payload.scope).toBe('vault_fenced'); - expect(payload.vaultCutoffTs).toBe(fixture.vaultCutoffTs); - expect(payload.vaultCutoffDate).toBe(fixture.vaultCutoffDate); - expect(payload.clampedTo).toBe(false); - expect(payload.clampedAsOf).toBe(false); - expect(payload.listingCount).toBe(fixture.listingIds.length); - expect(payload.eventCount).toBe(12); - expect(payload.vaultExcludedEvents).toBe(0); - expect(payload.study.offsets).toHaveLength(preDays + postDays + 1); - expect(payload.study.hasBenchmark).toBe(true); - expect(payload.study.diagnostics.eventsUsed).toBeGreaterThanOrEqual(5); - expect(payload.study.clustered).not.toBeNull(); - expect(payload.study.recency).not.toBeNull(); - - // Verify no raw arrays or typed series are exposed in the JSON payload. - const serialized = result!.content[0]!.text; - expect(serialized).not.toContain('entityReturns'); - expect(serialized).not.toContain('benchmarkReturns'); - expect(serialized).not.toContain('eventCars'); - expect(serialized).not.toContain('meanCars'); - expect(serialized).not.toContain('eventCounts'); - - // Verify trial_ledger write - expect(ledger.insertCalls).toBe(1); - expect(ledger.rows).toHaveLength(1); - const row = ledger.rows[0]!; - expect(row.stage).toBe('event_study'); - expect(row.principal_id).toBe(AGENT_PRINCIPAL); - expect(row.universe_market).toBe('US_EQ'); - expect(row.horizon_bucket).toBe('swing_1_10d'); - expect(row.campaign_id).toBe(CAMPAIGN_UUID); - expect(row.hypothesis_id).toBe(HYPOTHESIS_UUID); - expect(row.sample_end < fixture.vaultCutoffDate).toBe(true); - expect(payload.trial.trialId).toBe(1); - expect(payload.deflatedSharpe.trialId).toBe(1); - expect(payload.deflatedSharpe.clusterSize).toBe(1); - - // Direct parity check against buildEventStudyInput + runEventStudy - const directLedger = createFakeTrialLedger(); - const directEvents = eventsTableToEventRows(fixture.eventsTable, { - kinds: ['earnings', 'filing'], - }); - const directCal = await cal.resolveExchangeCalendars({ - listingIds: fixture.listingIds, - fromDate: from, - toDate: to, - }); - const directBuilt = buildEventStudyInput({ - bars: fixture.bars.filter(b => b.ts < fixture.vaultCutoffTs), - events: directEvents, - vaultCutoffDate: fixture.vaultCutoffDate, - benchmark: 'equal_weight', - exchangeCalendars: directCal, - }); - const directRun = await runEventStudy(directLedger.executor, { - principalId: AGENT_PRINCIPAL, - campaignId: CAMPAIGN_UUID, - hypothesisId: HYPOTHESIS_UUID, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - expression: { - expression: 'mcp:event_study:v1:earnings,filing', - params: { - version: 1, - kinds: ['earnings', 'filing'], - subtypes: null, - preDays, - postDays, - benchmark: 'equal_weight', - adjustment: 'raw', - effectiveFrom: payload.effectiveFrom, - effectiveTo: payload.effectiveTo, - effectiveAsOf: payload.effectiveAsOf, - }, - universe: { - kind: 'listingIds', - listingIds: fixture.listingIds, - }, - horizon: `${postDays}d`, - }, - input: directBuilt.input, - vaultCutoffDate: fixture.vaultCutoffDate, - options: { preDays, postDays }, - }); - - expect(directRun.status).toBe('ok'); - if (directRun.status !== 'ok') { - throw new Error('Expected direct ok'); - } - - expect(payload.trial.expressionHash).toBe(directRun.trial.expressionHash); - expect(row.daily_series).toEqual(directLedger.rows[0]!.daily_series); - expect(payload.study.offsets).toEqual( - directRun.study.offsets.map(o => ({ - offset: o.offset, - n: o.n, - aar: o.aar, - caar: o.caar, - caarFromZero: o.caarFromZero, - })) - ); - }); - - test('replay with reordered/duplicated IDs, kinds, and subtypes yields identical expressionHash and results; param change alters hash', async () => { - const fixture = buildSyntheticEventFixture(); - const from = fixture.allDates[0]!; - const to = fixture.allDates[64]!; - - const runWithArgs = async (args: Record) => { - const fakeStore = createFakeStore(fixture); - const ledger = createFakeTrialLedger(); - const cal = createFakeCalendarResolver(fixture.allDates); - const server = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store: fakeStore.store, - ledger: ledger.executor, - vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars: cal.resolveExchangeCalendars, - }), - ], - }); - const res = await callEventStudy(server, args); - expect(res.payload?.status).toBe('ok'); - return res.payload as Extract; - }; - - const p1 = await runWithArgs({ - listingIds: fixture.listingIds, - from, - to, - event: { kinds: ['filing', 'earnings'], subtypes: ['8-K', 'Q4'] }, - preDays: 2, - postDays: 4, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }); - - const p2 = await runWithArgs({ - listingIds: [...fixture.listingIds].reverse().concat(fixture.listingIds[0]!), - from, - to, - event: { kinds: ['earnings', 'filing', 'earnings'], subtypes: ['Q4', '8-K', 'Q4'] }, - preDays: 2, - postDays: 4, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }); - - expect(p2.trial.expressionHash).toBe(p1.trial.expressionHash); - expect(p2.study.offsets).toEqual(p1.study.offsets); - expect(p2.event.kinds).toEqual(['earnings', 'filing']); - expect(p2.event.subtypes).toEqual(['8-K', 'Q4']); - - // Changing benchmark changes the expressionHash - const p3 = await runWithArgs({ - listingIds: fixture.listingIds, - from, - to, - event: { kinds: ['filing', 'earnings'], subtypes: ['8-K', 'Q4'] }, - preDays: 2, - postDays: 4, - benchmark: 'none', - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }); - - expect(p3.trial.expressionHash).not.toBe(p1.trial.expressionHash); - expect(p3.study.hasBenchmark).toBe(false); - expect(p1.study.hasBenchmark).toBe(true); - // With equal_weight benchmark vs none, AAR values differ when cross-sectional mean return is non-zero - expect(p3.study.offsets[2]!.aar).not.toBeCloseTo(p1.study.offsets[2]!.aar, 8); - }); - - test('Vault fence clamps to/asOf, filters leaky store rows, and matches clean replay', async () => { - const fixture = buildSyntheticEventFixture(); - const from = fixture.allDates[0]!; - const postCutoffTo = fixture.allDates[fixture.allDates.length - 1]!; - const cutoffDate = fixture.vaultCutoffDate; - - const poisonedEvents: TableRow[] = [ - // Post-cutoff ts & known_at - { - listing_id: fixture.listingIds[0]!, - ts: makeUtcMs(cutoffDate, 14), - known_at: makeUtcMs(cutoffDate, 14), - known_at_source: 'exact', - kind: 'filing', - subtype: '8-K', - payload_json: '{}', - }, - // Valid ts in window, but known_at in Vault - { - listing_id: fixture.listingIds[1]!, - ts: makeUtcMs(fixture.allDates[20]!, 14), - known_at: makeUtcMs(cutoffDate, 15), - known_at_source: 'exact', - kind: 'filing', - subtype: '8-K', - payload_json: '{}', - }, - // Foreign listing - { - listing_id: 999_999, - ts: makeUtcMs(fixture.allDates[20]!, 14), - known_at: makeUtcMs(fixture.allDates[20]!, 14), - known_at_source: 'exact', - kind: 'filing', - subtype: '8-K', - payload_json: '{}', - }, - // Before study window - { - listing_id: fixture.listingIds[2]!, - ts: makeUtcMs('2022-01-05', 14), - known_at: makeUtcMs('2022-01-05', 14), - known_at_source: 'exact', - kind: 'filing', - subtype: '8-K', - payload_json: '{}', - }, - ]; - - const poisonedBars: BarRecord[] = [ - // Post-cutoff bar with NaN close (must never be read or affect returns) - { - listingId: fixture.listingIds[0]!, - ts: makeUtcMs(cutoffDate, 21), - open: Number.NaN, - high: Number.NaN, - low: Number.NaN, - close: Number.NaN, - volume: 100, - knownAt: makeUtcMs(cutoffDate, 21), - }, - // Foreign listing bar - { - listingId: 999_999, - ts: makeUtcMs(fixture.allDates[15]!, 21), - open: 50, - high: 50, - low: 50, - close: 50, - volume: 100, - knownAt: makeUtcMs(fixture.allDates[15]!, 21), - }, - ]; - - const leakyStore = createFakeStore(fixture, { - extraBars: poisonedBars, - extraEvents: poisonedEvents, - }); - const leakyLedger = createFakeTrialLedger(); - const leakyCal = createFakeCalendarResolver(fixture.allDates); - - const leakyServer = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store: leakyStore.store, - ledger: leakyLedger.executor, - vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars: leakyCal.resolveExchangeCalendars, - }), - ], - }); - - const leakyRes = await callEventStudy(leakyServer, { - listingIds: fixture.listingIds, - from, - to: postCutoffTo, - asOf: postCutoffTo, - event: { kinds: ['filing', 'earnings'] }, - preDays: 2, - postDays: 4, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }); - - expect(leakyRes.payload?.status).toBe('ok'); - const leakyPayload = leakyRes.payload as Extract; - expect(leakyPayload.clampedTo).toBe(true); - expect(leakyPayload.clampedAsOf).toBe(true); - expect(leakyPayload.toMs).toBeLessThan(fixture.vaultCutoffTs); - expect(leakyPayload.asOfMs).toBeLessThan(fixture.vaultCutoffTs); - expect(leakyPayload.vaultExcludedEvents).toBe(2); - expect(leakyPayload.panelDiagnostics.vaultExcludedDates).toBe(1); - expect(leakyPayload.eventCount).toBe(12); - - // Verify no store call received a bound >= vaultCutoffTs - expect(Date.parse(leakyStore.barsCalls[0]!.to)).toBeLessThan(fixture.vaultCutoffTs); - expect(Date.parse(leakyStore.barsCalls[0]!.asOf!)).toBeLessThan(fixture.vaultCutoffTs); - expect(Date.parse(leakyStore.eventsCalls[0]!.to)).toBeLessThan(fixture.vaultCutoffTs); - expect(Date.parse(leakyStore.eventsCalls[0]!.asOf!)).toBeLessThan(fixture.vaultCutoffTs); - expect(leakyCal.calls[0]!.toDate < fixture.vaultCutoffDate).toBe(true); - - // Compare against clean store with same arguments - const cleanStore = createFakeStore(fixture); - const cleanLedger = createFakeTrialLedger(); - const cleanCal = createFakeCalendarResolver(fixture.allDates); - const cleanServer = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store: cleanStore.store, - ledger: cleanLedger.executor, - vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars: cleanCal.resolveExchangeCalendars, - }), - ], - }); - - const cleanRes = await callEventStudy(cleanServer, { - listingIds: fixture.listingIds, - from, - to: postCutoffTo, - asOf: postCutoffTo, - event: { kinds: ['filing', 'earnings'] }, - preDays: 2, - postDays: 4, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }); - - const cleanPayload = cleanRes.payload as Extract; - expect(cleanPayload.panelDiagnostics.vaultExcludedDates).toBe(0); - expect(leakyPayload.study.offsets).toEqual(cleanPayload.study.offsets); - expect(leakyPayload.trial.expressionHash).toBe(cleanPayload.trial.expressionHash); - expect(leakyLedger.rows[0]!.daily_series).toEqual(cleanLedger.rows[0]!.daily_series); - }); - - test('named universe resolves strictly pre-start and earlier explicit asOf caps calendar & events', async () => { - const fixture = buildSyntheticEventFixture(); - const fakeStore = createFakeStore(fixture); - const ledger = createFakeTrialLedger(); - const cal = createFakeCalendarResolver(fixture.allDates); - - const server = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store: fakeStore.store, - ledger: ledger.executor, - vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, - principalId: 'operator', - resolveExchangeCalendars: cal.resolveExchangeCalendars, - }), - ], - }); - - const from = fixture.allDates[0]!; // 2022-11-01 - const to = fixture.allDates[64]!; - const earlierAsOf = fixture.allDates[40]!; // Excludes events at day 42 and 50 - - const res = await callEventStudy(server, { - universe: 'US_EQ', - from, - to, - asOf: earlierAsOf, - event: { kinds: ['filing', 'earnings'] }, - preDays: 2, - postDays: 4, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }); - - expect(fakeStore.universeCalls).toHaveLength(1); - expect(fakeStore.universeCalls[0]!.ref).toBe('US_EQ'); - expect(fakeStore.universeCalls[0]!.date).toBe('2022-10-31'); // Strictly before 2022-11-01 - expect(cal.calls[0]!.toDate).toBe(earlierAsOf); - expect(res.payload?.status).toBe('ok'); - expect(res.payload?.eventCount).toBe(8); // Only days 12, 18, 26, 34 (2 listings each) - expect(ledger.rows[0]!.principal_id).toBe('operator'); - }); - - test('strict input schema rejects invalid arguments with zero dependency calls and accepts boundary windows', async () => { - const fixture = buildSyntheticEventFixture(); - const fakeStore = createFakeStore(fixture); - const ledger = createFakeTrialLedger(); - const cal = createFakeCalendarResolver(fixture.allDates); - - const server = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store: fakeStore.store, - ledger: ledger.executor, - vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars: cal.resolveExchangeCalendars, - }), - ], - }); - - const validBase = { - listingIds: [60_001], - from: fixture.allDates[0]!, - to: fixture.allDates[64]!, - event: { kinds: ['filing'] }, - preDays: 2, - postDays: 5, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }; - - const invalidCases: Record[] = [ - { ...validBase, scope: 'vault_evaluation_only' }, - { ...validBase, principalId: 'operator' }, - { ...validBase, vaultCutoffDate: '2099-01-01' }, - { ...validBase, vault_evaluation_only: true }, - { ...validBase, extraKey: 123 }, - { ...validBase, event: { kinds: ['filing'], unknownNested: true } }, - { ...validBase, universe: 'US_EQ' }, // both listingIds and universe - { - from: fixture.allDates[0]!, - to: fixture.allDates[64]!, - event: { kinds: ['filing'] }, - preDays: 2, - postDays: 5, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }, // neither selector - { ...validBase, event: { kinds: [] } }, - { ...validBase, event: { kinds: ['unknown_kind'] } }, - { ...validBase, event: { kinds: ['filing'], subtypes: [] } }, - { - ...validBase, - event: { - kinds: ['filing'], - subtypes: Array.from({ length: EVENT_STUDY_MAX_SUBTYPES + 1 }, (_, i) => `SUB_${i}`), - }, - }, - { - ...validBase, - event: { - kinds: ['filing'], - subtypes: ['x'.repeat(EVENT_STUDY_MAX_SUBTYPE_LENGTH + 1)], - }, - }, - { ...validBase, preDays: -1 }, - { ...validBase, preDays: 61 }, - { ...validBase, preDays: 1.5 }, - { ...validBase, postDays: -1 }, - { ...validBase, postDays: 61 }, - { ...validBase, postDays: 2.5 }, - { ...validBase, postDays: 10, horizonBucket: 'position_10d_plus' }, - { ...validBase, postDays: 11, horizonBucket: 'swing_1_10d' }, - { ...validBase, campaignId: 'not-a-uuid' }, - { ...validBase, hypothesisId: 'not-a-uuid' }, - { - universe: 'US_EQ', - from: fixture.allDates[0]!, - to: fixture.allDates[64]!, - event: { kinds: ['filing'] }, - preDays: 2, - postDays: 5, - universeMarket: 'CA_EQ', - horizonBucket: 'swing_1_10d', - }, - ]; - - for (let i = 0; i < invalidCases.length; i += 1) { - const res = await callEventStudy(server, invalidCases[i]!, i + 1); - expect(res.result?.isError).toBe(true); - expect(res.result?.content[0]?.text).toContain('Invalid arguments for tool "event_study"'); - } - - expect(fakeStore.barsCalls).toHaveLength(0); - expect(fakeStore.eventsCalls).toHaveLength(0); - expect(fakeStore.universeCalls).toHaveLength(0); - expect(cal.calls).toHaveLength(0); - expect(ledger.insertCalls).toBe(0); - - // Valid boundary windows: 0, 10 (swing_1_10d), 11, 60 (position_10d_plus) - const boundaryWindows: Array<{ preDays: number; postDays: number; bucket: string }> = [ - { preDays: 0, postDays: 0, bucket: 'swing_1_10d' }, - { preDays: 0, postDays: 10, bucket: 'swing_1_10d' }, - { preDays: 11, postDays: 11, bucket: 'position_10d_plus' }, - { preDays: 60, postDays: 60, bucket: 'position_10d_plus' }, - ]; - for (const w of boundaryWindows) { - const res = await callEventStudy(server, { - ...validBase, - preDays: w.preDays, - postDays: w.postDays, - horizonBucket: w.bucket, - }); - expect(res.result?.isError).toBeUndefined(); - expect(res.payload).toBeDefined(); - } - }); - - test('insufficient_data paths (empty universe, empty grid, below_min_events, zero_variance_series) write zero ledger rows', async () => { - const fixture = buildSyntheticEventFixture(); - - // 1. Empty resolved universe -> zero bars/events/calendar/ledger calls - { - const fakeStore = createFakeStore(fixture, { universeResolver: () => [] }); - const ledger = createFakeTrialLedger(); - const cal = createFakeCalendarResolver(fixture.allDates); - const server = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store: fakeStore.store, - ledger: ledger.executor, - vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars: cal.resolveExchangeCalendars, - }), - ], - }); - const res = await callEventStudy(server, { - universe: 'US_EQ', - from: fixture.allDates[0]!, - to: fixture.allDates[64]!, - event: { kinds: ['filing'] }, - preDays: 2, - postDays: 4, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }); - expect(res.payload?.status).toBe('insufficient_data'); - if (res.payload?.status === 'insufficient_data') { - expect(res.payload.reason).toBe('below_min_events'); - } - expect(res.payload?.listingCount).toBe(0); - expect(fakeStore.barsCalls).toHaveLength(0); - expect(fakeStore.eventsCalls).toHaveLength(0); - expect(cal.calls).toHaveLength(0); - expect(ledger.insertCalls).toBe(0); - } - - // 2. Empty session grid (no bars in range) - { - const emptyBarsFixture: SyntheticEventFixture = { ...fixture, bars: [] }; - const fakeStore = createFakeStore(emptyBarsFixture); - const ledger = createFakeTrialLedger(); - const cal = createFakeCalendarResolver(fixture.allDates); - const server = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store: fakeStore.store, - ledger: ledger.executor, - vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars: cal.resolveExchangeCalendars, - }), - ], - }); - const res = await callEventStudy(server, { - listingIds: fixture.listingIds, - from: fixture.allDates[0]!, - to: fixture.allDates[64]!, - event: { kinds: ['filing'] }, - preDays: 2, - postDays: 4, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }); - expect(res.payload?.status).toBe('insufficient_data'); - expect(res.payload?.eventCount).toBe(0); - expect(ledger.insertCalls).toBe(0); - } - - // 3. Below minimum events (subtype with no matches) - { - const fakeStore = createFakeStore(fixture); - const ledger = createFakeTrialLedger(); - const cal = createFakeCalendarResolver(fixture.allDates); - const server = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store: fakeStore.store, - ledger: ledger.executor, - vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars: cal.resolveExchangeCalendars, - }), - ], - }); - const res = await callEventStudy(server, { - listingIds: fixture.listingIds, - from: fixture.allDates[0]!, - to: fixture.allDates[64]!, - event: { kinds: ['filing'], subtypes: ['NONEXISTENT_SUBTYPE'] }, - preDays: 2, - postDays: 4, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }); - expect(res.payload?.status).toBe('insufficient_data'); - if (res.payload?.status === 'insufficient_data') { - expect(res.payload.reason).toBe('below_min_events'); - } - expect(ledger.insertCalls).toBe(0); - } - - // 4. Zero-variance clustered CAR series - { - const flatFixture = buildSyntheticEventFixture({ zeroVariance: true }); - const fakeStore = createFakeStore(flatFixture); - const ledger = createFakeTrialLedger(); - const cal = createFakeCalendarResolver(flatFixture.allDates); - const server = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store: fakeStore.store, - ledger: ledger.executor, - vaultContext: { vaultCutoffTs: flatFixture.vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars: cal.resolveExchangeCalendars, - }), - ], - }); - const res = await callEventStudy(server, { - listingIds: flatFixture.listingIds, - from: flatFixture.allDates[0]!, - to: flatFixture.allDates[64]!, - event: { kinds: ['filing', 'earnings'] }, - preDays: 2, - postDays: 4, - benchmark: 'none', - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }); - expect(res.payload?.status).toBe('insufficient_data'); - if (res.payload?.status === 'insufficient_data') { - expect(res.payload.reason).toBe('zero_variance_series'); - } - // Offsets are still projected when study.status === 'ok' - expect(res.payload?.study.offsets).toHaveLength(7); - expect(ledger.insertCalls).toBe(0); - } - }); - - test('factory option validation, wholly-in-Vault request, and sanitized error mapping without secret leaks', async () => { - const fixture = buildSyntheticEventFixture(); - const fakeStore = createFakeStore(fixture); - const ledger = createFakeTrialLedger(); - const cal = createFakeCalendarResolver(fixture.allDates); - const SECRET = 'SECRET_MARKER_SQL_URI_88421'; - - // Factory option validation - expect(() => - createEventStudyTool({ - store: {} as MarketDataStore, - ledger: ledger.executor, - vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars: cal.resolveExchangeCalendars, - }) - ).toThrow(MarketDataStoreValidationError); - - expect(() => - createEventStudyTool({ - store: fakeStore.store, - ledger: {} as TrialLedgerExecutor, - vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars: cal.resolveExchangeCalendars, - }) - ).toThrow(SignalStudyError); - - expect(() => - createEventStudyTool({ - store: fakeStore.store, - ledger: ledger.executor, - vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars: null as unknown as typeof cal.resolveExchangeCalendars, - }) - ).toThrow(EventPanelError); - - expect(() => - createEventStudyTool({ - store: fakeStore.store, - ledger: ledger.executor, - vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, - principalId: 'invalid-principal', - resolveExchangeCalendars: cal.resolveExchangeCalendars, - }) - ).toThrow(TrialLedgerError); - - expect(() => - createEventStudyTool({ - store: fakeStore.store, - ledger: ledger.executor, - vaultContext: { vaultCutoffTs: Number.NaN }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars: cal.resolveExchangeCalendars, - }) - ).toThrow(MarketDataStoreValidationError); - - // Request wholly in Vault -> zero dependency calls - { - const s = createFakeStore(fixture); - const l = createFakeTrialLedger(); - const c = createFakeCalendarResolver(fixture.allDates); - const server = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store: s.store, - ledger: l.executor, - vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars: c.resolveExchangeCalendars, - }), - ], - }); - const res = await callEventStudy(server, { - listingIds: fixture.listingIds, - from: fixture.vaultCutoffDate, - to: fixture.allDates[fixture.allDates.length - 1]!, - event: { kinds: ['filing'] }, - preDays: 2, - postDays: 4, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }); - expect(res.result?.isError).toBe(true); - expect(res.result?.content[0]?.text).toContain('VaultHoldoutFenceError'); - expect(s.barsCalls).toHaveLength(0); - expect(s.eventsCalls).toHaveLength(0); - expect(c.calls).toHaveLength(0); - expect(l.insertCalls).toBe(0); - } - - const baseArgs = { - listingIds: fixture.listingIds, - from: fixture.allDates[0]!, - to: fixture.allDates[64]!, - event: { kinds: ['filing', 'earnings'] }, - preDays: 2, - postDays: 4, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }; - - const errorCases: Array<{ - name: string; - storeOpts?: Parameters[1]; - calError?: unknown; - ledgerOpts?: Parameters[0]; - expectedPrefix: string; - }> = [ - { - name: 'store VaultHoldoutFenceError', - storeOpts: { - barsError: new VaultHoldoutFenceError('2025-01-01', 1, 1, `leak ${SECRET}`), - }, - expectedPrefix: 'VaultHoldoutFenceError:', - }, - { - name: 'store VaultScopeNotAuthorizedError', - storeOpts: { barsError: new VaultScopeNotAuthorizedError(`leak ${SECRET}`) }, - expectedPrefix: 'VaultScopeNotAuthorizedError:', - }, - { - name: 'store MarketDataStoreValidationError', - storeOpts: { - eventsError: new MarketDataStoreValidationError(`leak ${SECRET}`, 'from'), - }, - expectedPrefix: 'MarketDataStoreValidationError:', - }, - { - name: 'store MarketDataStoreNotImplementedError', - storeOpts: { - eventsError: new MarketDataStoreNotImplementedError('events', `leak ${SECRET}`), - }, - expectedPrefix: 'MarketDataStoreNotImplementedError:', - }, - { - name: 'store AdjFactorsSnapshotError', - storeOpts: { - barsError: new AdjFactorsSnapshotError('missing_snapshot', `leak ${SECRET}`), - }, - expectedPrefix: 'AdjFactorsSnapshotError:', - }, - { - name: 'calendar resolver generic Error', - calError: new Error(`calendar db down ${SECRET}`), - expectedPrefix: 'Error: Exchange calendar resolution failed.', - }, - { - name: 'calendar resolver EventPanelError', - calError: new EventPanelError('invalid_option', `bad cal ${SECRET}`), - expectedPrefix: 'EventPanelError:', - }, - { - name: 'SignalStudyError from store/runner', - storeOpts: { - eventsError: new SignalStudyError('invalid_panel', `bad panel ${SECRET}`), - }, - expectedPrefix: 'SignalStudyError:', - }, - { - name: 'TrialLedgerError on INSERT', - ledgerOpts: { - insertError: new TrialLedgerError('VAULT_FENCE_VIOLATION', `pg detail ${SECRET}`), - }, - expectedPrefix: 'TrialLedgerError:', - }, - ]; - - for (const tc of errorCases) { - const s = createFakeStore(fixture, tc.storeOpts); - const l = createFakeTrialLedger(tc.ledgerOpts); - const c = createFakeCalendarResolver(fixture.allDates, { error: tc.calError }); - const server = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store: s.store, - ledger: l.executor, - vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars: c.resolveExchangeCalendars, - }), - ], - }); - - const res = await callEventStudy(server, baseArgs); - expect(res.result?.isError).toBe(true); - const text = res.result?.content[0]?.text ?? ''; - expect(text).toContain(tc.expectedPrefix); - expect(text).not.toContain(SECRET); - } - - // Post-insert DSR read failure: trial is recorded once (no retry) and sanitized message informs caller - { - const s = createFakeStore(fixture); - const l = createFakeTrialLedger({ - dsrReadError: new Error(`pg select timeout ${SECRET}`), - }); - const c = createFakeCalendarResolver(fixture.allDates); - const server = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store: s.store, - ledger: l.executor, - vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars: c.resolveExchangeCalendars, - }), - ], - }); - - const res = await callEventStudy(server, baseArgs); - expect(res.result?.isError).toBe(true); - const text = res.result?.content[0]?.text ?? ''; - expect(text).toBe( - 'SignalStudyError: Trial was recorded, but cluster deflated Sharpe evaluation failed.' - ); - expect(text).not.toContain(SECRET); - expect(l.insertCalls).toBe(1); - expect(l.rows).toHaveLength(1); - } - }); -}); diff --git a/libs/research/test/mcp-exchange-calendars-qa.test.ts b/libs/research/test/mcp-exchange-calendars-qa.test.ts deleted file mode 100644 index d35a216f..00000000 --- a/libs/research/test/mcp-exchange-calendars-qa.test.ts +++ /dev/null @@ -1,430 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { type EventObservation, buildEventStudyInput } from '../src/event-panel'; -import type { BarRecord } from '../src/market-data-store'; -import { - ExchangeCalendarResolverError, - type ListingCalendarExecutor, - type ListingCalendarRow, - PostgresListingCalendarError, - type SessionDatesQuery, - createExchangeCalendarResolver, - createPostgresListingCalendarPort, -} from '../src/mcp/index'; - -const MS_PER_DAY = 86_400_000; - -function utcMs(dateStr: string, hour: number, minute = 0): number { - const [y, m, d] = dateStr.split('-').map(Number) as [number, number, number]; - return Date.UTC(y, m - 1, d, hour, minute, 0, 0); -} - -function isoDate(epochMs: number): string { - return new Date(epochMs).toISOString().slice(0, 10); -} - -function allDatesInclusive(from: string, to: string): string[] { - const out: string[] = []; - for (let t = utcMs(from, 0); t <= utcMs(to, 0); t += MS_PER_DAY) { - out.push(isoDate(t)); - } - return out; -} - -/** Independent oracle: local wall-clock date/time of `epochMs` in an IANA zone (ICU tzdata). */ -function makeZoneFormatter(timeZone: string): (epochMs: number) => string { - const fmt = new Intl.DateTimeFormat('en-CA', { - timeZone, - year: 'numeric', - month: '2-digit', - day: '2-digit', - hour: '2-digit', - minute: '2-digit', - hourCycle: 'h23', - }); - return (epochMs) => { - const parts = Object.fromEntries(fmt.formatToParts(new Date(epochMs)).map((p) => [p.type, p.value])); - return `${parts.year}-${parts.month}-${parts.day} ${parts.hour}:${parts.minute}`; - }; -} - -async function captureError(fn: () => unknown): Promise { - try { - await fn(); - } catch (err) { - return err; - } - return undefined; -} - -function countingPorts( - rows: readonly ListingCalendarRow[] | (() => unknown), - sessions: (q: SessionDatesQuery) => unknown -) { - const counts = { listing: 0, session: 0 }; - const sessionCalls: SessionDatesQuery[] = []; - return { - counts, - sessionCalls, - listingCalendars: { - getListingCalendars: () => { - counts.listing += 1; - return (typeof rows === 'function' ? rows() : rows) as readonly ListingCalendarRow[]; - }, - }, - sessionDates: { - listSessionDates: (q: SessionDatesQuery) => { - counts.session += 1; - sessionCalls.push(q); - return sessions(q) as readonly string[]; - }, - }, - }; -} - -describe('QA: Eastern close timestamps vs ICU tzdata oracle', () => { - test('every day 1976-01-01..=2030-12-31 closes at exactly 16:00 local in America/New_York and America/Toronto', async () => { - const days = allDatesInclusive('1976-01-01', '2030-12-31'); - expect(days).toHaveLength(20_089); - - const ports = countingPorts( - [ - { listingId: 1, calendarCode: 'XNYS' }, - { listingId: 2, calendarCode: 'XTSE' }, - ], - () => days - ); - const resolver = createExchangeCalendarResolver(ports); - const result = await resolver({ listingIds: [1, 2], fromDate: days[0]!, toDate: days[days.length - 1]! }); - const calendars = result.calendars as Record; - - const ny = makeZoneFormatter('America/New_York'); - const to = makeZoneFormatter('America/Toronto'); - const mismatches: string[] = []; - for (const code of ['XNYS', 'XTSE'] as const) { - const sessions = calendars[code]!; - expect(sessions).toHaveLength(days.length); - for (let i = 0; i < days.length; i += 1) { - const s = sessions[i]!; - const expected = `${days[i]} 16:00`; - if (s.date !== days[i] || ny(s.closeTs) !== expected || to(s.closeTs) !== expected) { - mismatches.push(`${code} ${days[i]} -> ${new Date(s.closeTs).toISOString()}`); - } - } - } - expect(mismatches).toEqual([]); - expect(ports.counts).toEqual({ listing: 1, session: 2 }); - }); - - test('each supported year has exactly two offset flips, both on Sundays, and closes are only 20:00Z or 21:00Z', async () => { - const days = allDatesInclusive('1976-01-01', '2030-12-31'); - const resolver = createExchangeCalendarResolver( - countingPorts([{ listingId: 1, calendarCode: 'XNYS' }], () => days) - ); - const result = await resolver({ listingIds: [1], fromDate: days[0]!, toDate: days[days.length - 1]! }); - const sessions = (result.calendars as Record).XNYS!; - - const flipsByYear = new Map(); - let prevHour = -1; - for (const s of sessions) { - const hour = (s.closeTs - utcMs(s.date, 0)) / 3_600_000; - expect(hour === 20 || hour === 21).toBe(true); - if (prevHour !== -1 && hour !== prevHour) { - const year = Number(s.date.slice(0, 4)); - flipsByYear.set(year, [...(flipsByYear.get(year) ?? []), s.date]); - expect(new Date(utcMs(s.date, 0)).getUTCDay()).toBe(0); - } - prevHour = hour; - } - // 1976 starts in EST, so every year (1976..=2030) has exactly spring + fall flips. - expect(flipsByYear.size).toBe(55); - for (const [, flips] of flipsByYear) { - expect(flips).toHaveLength(2); - } - }); - - test('remaining session_close.rs known vectors (mid-season and 1986/2006 boundaries) match exactly', async () => { - const vectors: ReadonlyArray = [ - ['1980-01-15', 21], - ['1980-07-15', 20], - ['1986-04-26', 21], - ['1986-04-27', 20], - ['1999-01-15', 21], - ['1999-07-15', 20], - ['2006-04-01', 21], - ['2006-04-02', 20], - ['2006-10-28', 20], - ['2006-10-29', 21], - ['2024-01-15', 21], - ['2024-07-15', 20], - ]; - const resolver = createExchangeCalendarResolver( - countingPorts([{ listingId: 1, calendarCode: 'XNYS' }], () => vectors.map(([d]) => d)) - ); - const result = await resolver({ listingIds: [1], fromDate: '1980-01-15', toDate: '2024-07-15' }); - expect(result.calendars).toEqual({ - XNYS: vectors.map(([date, hour]) => ({ date, closeTs: utcMs(date, hour) })), - }); - }); -}); - -describe('QA: earlyCloses edge cases', () => { - test('override applies in EDT and EST, 960 equals default, and minute 1 is 00:01 ET', async () => { - const dates = ['2024-07-03', '2024-11-29', '2024-12-24', '2024-12-26']; - const resolver = createExchangeCalendarResolver({ - ...countingPorts([{ listingId: 1, calendarCode: 'XNYS' }], () => dates), - earlyCloses: { XNYS: { '2024-07-03': 780, '2024-11-29': 960, '2024-12-24': 1 } }, - }); - const result = await resolver({ listingIds: [1], fromDate: '2024-07-01', toDate: '2024-12-31' }); - expect(result.calendars).toEqual({ - XNYS: [ - { date: '2024-07-03', closeTs: utcMs('2024-07-03', 17) }, // 13:00 EDT - { date: '2024-11-29', closeTs: utcMs('2024-11-29', 21) }, // 16:00 EST (== default) - { date: '2024-12-24', closeTs: utcMs('2024-12-24', 5, 1) }, // 00:01 EST - { date: '2024-12-26', closeTs: utcMs('2024-12-26', 21) }, - ], - }); - }); - - test('overrides for unrequested calendars or non-session dates are ignored without error', async () => { - const ports = countingPorts([{ listingId: 1, calendarCode: 'XTSE' }], () => ['2024-11-29']); - const resolver = createExchangeCalendarResolver({ - ...ports, - earlyCloses: { XNYS: { '2024-11-29': 780 }, XTSE: { '2024-12-25': 780 } }, - }); - const result = await resolver({ listingIds: [1], fromDate: '2024-11-29', toDate: '2024-11-29' }); - expect(result.calendars).toEqual({ - XTSE: [{ date: '2024-11-29', closeTs: utcMs('2024-11-29', 21) }], - }); - }); - - test('calendar code matching for overrides is exact (case-sensitive)', async () => { - const resolver = createExchangeCalendarResolver({ - ...countingPorts([{ listingId: 1, calendarCode: 'XNYS' }], () => ['2024-11-29']), - earlyCloses: { xnys: { '2024-11-29': 780 } }, - }); - const result = await resolver({ listingIds: [1], fromDate: '2024-11-29', toDate: '2024-11-29' }); - expect(result.calendars).toEqual({ - XNYS: [{ date: '2024-11-29', closeTs: utcMs('2024-11-29', 21) }], - }); - }); - - test('earlyCloses parsed from JSON with a "__proto__" calendar key does not pollute Object.prototype', async () => { - const earlyCloses = JSON.parse('{"__proto__": {"2024-11-29": 780}, "XNYS": {"2024-11-29": 780}}'); - const resolver = createExchangeCalendarResolver({ - ...countingPorts([{ listingId: 1, calendarCode: 'XNYS' }], () => ['2024-11-29']), - earlyCloses, - }); - const result = await resolver({ listingIds: [1], fromDate: '2024-11-29', toDate: '2024-11-29' }); - expect(result.calendars).toEqual({ - XNYS: [{ date: '2024-11-29', closeTs: utcMs('2024-11-29', 18) }], - }); - expect(({} as Record)['2024-11-29']).toBeUndefined(); - }); -}); - -describe('QA: query validation and port failures fail closed', () => { - test('invalid queries throw INVALID_QUERY with zero port calls', async () => { - const bad: unknown[] = [ - null, - [], - { listingIds: 'x', fromDate: '2024-01-02', toDate: '2024-01-03' }, - { listingIds: [1], fromDate: '2024-01-03', toDate: '2024-01-02' }, - { listingIds: [1], fromDate: '2024-1-2', toDate: '2024-01-03' }, - { listingIds: [1], fromDate: '2024-01-02', toDate: undefined }, - { listingIds: [1.5], fromDate: '2024-01-02', toDate: '2024-01-03' }, - { listingIds: ['1'], fromDate: '2024-01-02', toDate: '2024-01-03' }, - { listingIds: [2_147_483_648], fromDate: '2024-01-02', toDate: '2024-01-03' }, - ]; - for (const q of bad) { - const ports = countingPorts([{ listingId: 1, calendarCode: 'XNYS' }], () => ['2024-01-02']); - const err = await captureError(() => createExchangeCalendarResolver(ports)(q as never)); - expect(err, JSON.stringify(q)).toBeInstanceOf(ExchangeCalendarResolverError); - expect((err as ExchangeCalendarResolverError).code, JSON.stringify(q)).toBe('INVALID_QUERY'); - expect(ports.counts, JSON.stringify(q)).toEqual({ listing: 0, session: 0 }); - } - }); - - test('malformed listing port responses throw INVALID_LISTING_CALENDAR_ROW before any session call', async () => { - const badResponses: unknown[] = [ - null, - { rows: [] }, - [null], - [{ listingId: '1', calendarCode: 'XNYS' }], - [{ listingId: 1, calendarCode: ' XNYS' }], - [{ listingId: 1, calendarCode: '' }], - [{ listingId: 1 }], - ]; - for (const resp of badResponses) { - const ports = countingPorts(() => resp, () => ['2024-01-02']); - const err = await captureError(() => - createExchangeCalendarResolver(ports)({ listingIds: [1], fromDate: '2024-01-02', toDate: '2024-01-02' }) - ); - expect(err, JSON.stringify(resp)).toBeInstanceOf(ExchangeCalendarResolverError); - expect((err as ExchangeCalendarResolverError).code).toBe('INVALID_LISTING_CALENDAR_ROW'); - expect(ports.counts.session).toBe(0); - } - }); - - test('port errors propagate unchanged and no partial result is returned', async () => { - const listingBoom = new Error('pg down'); - const ports1 = countingPorts(() => { - throw listingBoom; - }, () => []); - expect( - await captureError(() => - createExchangeCalendarResolver(ports1)({ listingIds: [1], fromDate: '2024-01-02', toDate: '2024-01-02' }) - ) - ).toBe(listingBoom); - expect(ports1.counts.session).toBe(0); - - const sessionBoom = new Error('sessions down'); - const ports2 = countingPorts( - [ - { listingId: 1, calendarCode: 'XNYS' }, - { listingId: 2, calendarCode: 'XTSE' }, - ], - (q) => (q.calendarCode === 'XTSE' ? Promise.reject(sessionBoom) : ['2024-01-02']) - ); - expect( - await captureError(() => - createExchangeCalendarResolver(ports2)({ listingIds: [2, 1], fromDate: '2024-01-02', toDate: '2024-01-02' }) - ) - ).toBe(sessionBoom); - expect(ports2.sessionCalls.map((q) => q.calendarCode)).toEqual(['XNYS', 'XTSE']); - }); - - test('session dates outside the supported DST range fail closed even when the window would allow them', async () => { - // Query window is in range; port returns a pre-1976 date which is also outside the window. - const ports = countingPorts([{ listingId: 1, calendarCode: 'XNYS' }], () => ['1975-12-31']); - const err = await captureError(() => - createExchangeCalendarResolver(ports)({ listingIds: [1], fromDate: '1976-01-01', toDate: '1976-01-05' }) - ); - expect(err).toBeInstanceOf(ExchangeCalendarResolverError); - expect((err as ExchangeCalendarResolverError).code).toBe('UNSUPPORTED_DATE'); - }); - - test('an empty session list for a calendar is returned as an empty array (not dropped)', async () => { - const resolver = createExchangeCalendarResolver( - countingPorts([{ listingId: 5, calendarCode: 'XTSE' }], () => []) - ); - const result = await resolver({ listingIds: [5], fromDate: '2024-01-01', toDate: '2024-01-01' }); - expect(result).toEqual({ calendars: { XTSE: [] }, listingCalendarId: { 5: 'XTSE' } }); - }); -}); - -describe('QA: output safety and isolation', () => { - test('a "__proto__" calendar code becomes an own property and does not pollute Object.prototype', async () => { - const resolver = createExchangeCalendarResolver( - countingPorts([{ listingId: 1, calendarCode: '__proto__' }], () => ['2024-01-02']) - ); - const result = await resolver({ listingIds: [1], fromDate: '2024-01-02', toDate: '2024-01-02' }); - expect(Object.keys(result.calendars)).toEqual(['__proto__']); - expect(Object.getPrototypeOf(result.calendars)).toBe(Object.prototype); - expect(Object.hasOwn(result.calendars, '__proto__')).toBe(true); - expect(({} as Record).date).toBeUndefined(); - }); - - test('repeated calls return fresh objects; mutating one result does not affect the next', async () => { - const resolver = createExchangeCalendarResolver( - countingPorts([{ listingId: 1, calendarCode: 'XNYS' }], () => ['2024-01-02']) - ); - const q = { listingIds: [1], fromDate: '2024-01-02', toDate: '2024-01-02' }; - const first = await resolver(q); - (first.calendars as Record).XNYS!.push({ - date: '2024-01-03', - closeTs: 0, - }); - (first.listingCalendarId as Record)[1] = 'XTSE'; - const second = await resolver(q); - expect(second).toEqual({ - calendars: { XNYS: [{ date: '2024-01-02', closeTs: utcMs('2024-01-02', 21) }] }, - listingCalendarId: { 1: 'XNYS' }, - }); - }); -}); - -describe('QA: Postgres port → resolver → buildEventStudyInput (fake executor)', () => { - test('rejects invalid listingIds with INVALID_ROW and zero queries; propagates executor rejection', async () => { - let queries = 0; - const executor: ListingCalendarExecutor = { - async query() { - queries += 1; - return { rows: [] }; - }, - }; - const port = createPostgresListingCalendarPort({ executor, schema: 'public' }); - for (const bad of ['1' as unknown, [1.5], ['1'], [Number.NaN], [-2_147_483_649]]) { - const err = await captureError(() => port.getListingCalendars(bad as never)); - expect(err).toBeInstanceOf(PostgresListingCalendarError); - expect((err as PostgresListingCalendarError).code).toBe('INVALID_ROW'); - } - expect(queries).toBe(0); - - const boom = new Error('connection reset'); - const failing = createPostgresListingCalendarPort({ - executor: { - async query() { - throw boom; - }, - }, - }); - expect(await captureError(() => failing.getListingCalendars([1]))).toBe(boom); - }); - - test('padded VARCHAR calendar_code is trimmed and the composed result feeds buildEventStudyInput', async () => { - const calls: Array<{ text: string; params: readonly unknown[] | undefined }> = []; - const executor: ListingCalendarExecutor = { - async query>(text: string, params?: readonly unknown[]) { - calls.push({ text, params }); - return { - rows: [ - { listing_id: 202, calendar_code: 'XTSE ' }, - { listing_id: 101, calendar_code: 'XNYS' }, - ] as unknown as readonly Row[], - }; - }, - }; - const sessions: Record = { - XNYS: ['2024-11-27', '2024-11-29', '2024-12-02'], - XTSE: ['2024-11-27', '2024-11-28', '2024-11-29', '2024-12-02'], - }; - const resolver = createExchangeCalendarResolver({ - listingCalendars: createPostgresListingCalendarPort({ executor, schema: 'public' }), - sessionDates: { listSessionDates: (q) => sessions[q.calendarCode] ?? [] }, - earlyCloses: { XNYS: { '2024-11-29': 780 } }, - }); - const cal = await resolver({ listingIds: [202, 101, 202], fromDate: '2024-11-27', toDate: '2024-12-02' }); - - expect(calls).toHaveLength(1); - expect(calls[0]!.params).toEqual([[101, 202]]); - expect(calls[0]!.text).toContain('FROM "public".listing l'); - expect(cal.listingCalendarId).toEqual({ 101: 'XNYS', 202: 'XTSE' }); - - const bar = (listingId: number, date: string, close: number): BarRecord => { - const ts = utcMs(date, 21); - return { listingId, ts, open: close, high: close, low: close, close, volume: 1_000, knownAt: ts }; - }; - const bars: BarRecord[] = [ - ...sessions.XNYS!.map((d, i) => bar(101, d, 100 + i)), - ...sessions.XTSE!.map((d, i) => bar(202, d, 50 + i)), - ]; - // 18:30Z on 2024-11-29: after XNYS 13:00 ET early close, before XTSE 16:00 ET close. - const knownAt = utcMs('2024-11-29', 18, 30); - const events: EventObservation[] = [ - { listingId: 101, knownAt, kind: 'filing', subtype: '8-K' }, - { listingId: 202, knownAt, kind: 'filing', subtype: '8-K' }, - ]; - const panel = buildEventStudyInput({ - bars, - events, - vaultCutoffDate: '2024-12-03', - benchmark: 'equal_weight', - exchangeCalendars: cal, - }); - expect(panel.input.sessionDates).toEqual(['2024-11-27', '2024-11-28', '2024-11-29', '2024-12-02']); - expect(panel.input.events).toEqual([ - { entityId: 202, dayIndex: 2 }, - { entityId: 101, dayIndex: 3 }, - ]); - }); -}); diff --git a/libs/research/test/mcp-exchange-calendars.test.ts b/libs/research/test/mcp-exchange-calendars.test.ts deleted file mode 100644 index cb85f02c..00000000 --- a/libs/research/test/mcp-exchange-calendars.test.ts +++ /dev/null @@ -1,789 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { type EventObservation, buildEventStudyInput } from '../src/event-panel'; -import type { BarRecord } from '../src/market-data-store'; -import { - EXCHANGE_CALENDAR_DEFAULT_CLOSE_MINUTE_ET, - EXCHANGE_CALENDAR_MAX_SUPPORTED_DATE, - EXCHANGE_CALENDAR_MIN_SUPPORTED_DATE, - ExchangeCalendarResolverError, - type ListingCalendarExecutor, - type ListingCalendarPort, - type ListingCalendarRow, - PostgresListingCalendarError, - type SessionDatesPort, - type SessionDatesQuery, - createExchangeCalendarResolver, - createPostgresListingCalendarPort, -} from '../src/mcp/index'; - -function utcMs( - year: number, - month: number, - day: number, - hour = 0, - minute = 0, - second = 0 -): number { - return Date.UTC(year, month - 1, day, hour, minute, second, 0); -} - -function makeBar(listingId: number, dateStr: string, close: number, closeHourUtc = 21): BarRecord { - const [y, m, d] = dateStr.split('-').map(Number) as [number, number, number]; - const ts = utcMs(y, m, d, closeHourUtc, 0, 0); - return { - listingId, - ts, - open: close, - high: close, - low: close, - close, - volume: 100_000, - knownAt: ts, - }; -} - -describe('createExchangeCalendarResolver — Eastern DST schedule & date bounds', () => { - test('computes exact UTC ms for EDT (2024-07-01 -> 20:00Z) and EST (2024-12-02 -> 21:00Z)', async () => { - const resolver = createExchangeCalendarResolver({ - listingCalendars: { - getListingCalendars: () => [{ listingId: 1, calendarCode: 'XNYS' }], - }, - sessionDates: { - listSessionDates: () => ['2024-07-01', '2024-12-02'], - }, - }); - - const result = await resolver({ - listingIds: [1], - fromDate: '2024-07-01', - toDate: '2024-12-02', - }); - - expect(result.calendars).toEqual({ - XNYS: [ - { date: '2024-07-01', closeTs: utcMs(2024, 7, 1, 20, 0, 0) }, - { date: '2024-12-02', closeTs: utcMs(2024, 12, 2, 21, 0, 0) }, - ], - }); - expect(result.listingCalendarId).toEqual({ 1: 'XNYS' }); - }); - - test('matches session_close.rs DST transition vectors across all three eras (1976, 1987, 2007)', async () => { - const vectors: readonly { - readonly date: string; - readonly expectedUtcHour: number; - }[] = [ - // Era 1 (1976..=1986): last Sunday of April -> last Sunday of October - { date: '1976-04-24', expectedUtcHour: 21 }, // Sat before spring-forward (EST) - { date: '1976-04-25', expectedUtcHour: 20 }, // Last Sun of April (EDT) - { date: '1976-10-30', expectedUtcHour: 20 }, // Sat before fall-back (EDT) - { date: '1976-10-31', expectedUtcHour: 21 }, // Last Sun of October (EST) - // Era 2 (1987..=2006): first Sunday of April -> last Sunday of October - { date: '1987-04-04', expectedUtcHour: 21 }, // Sat before spring-forward (EST) - { date: '1987-04-05', expectedUtcHour: 20 }, // First Sun of April (EDT) - { date: '1987-10-24', expectedUtcHour: 20 }, // Sat before fall-back (EDT) - { date: '1987-10-25', expectedUtcHour: 21 }, // Last Sun of October (EST) - // Era 3 (2007..=2030): second Sunday of March -> first Sunday of November - { date: '2007-03-10', expectedUtcHour: 21 }, // Sat before spring-forward (EST) - { date: '2007-03-11', expectedUtcHour: 20 }, // Second Sun of March (EDT) - { date: '2007-11-03', expectedUtcHour: 20 }, // Sat before fall-back (EDT) - { date: '2007-11-04', expectedUtcHour: 21 }, // First Sun of November (EST) - ]; - - const resolver = createExchangeCalendarResolver({ - listingCalendars: { - getListingCalendars: () => [{ listingId: 10, calendarCode: 'XNYS' }], - }, - sessionDates: { - listSessionDates: () => vectors.map((v) => v.date), - }, - }); - - const result = await resolver({ - listingIds: [10], - fromDate: '1976-04-24', - toDate: '2007-11-04', - }); - - const sessions = (result.calendars as Record) - .XNYS; - expect(sessions).toHaveLength(vectors.length); - - for (let i = 0; i < vectors.length; i += 1) { - const vec = vectors[i] as { date: string; expectedUtcHour: number }; - const [y, m, d] = vec.date.split('-').map(Number) as [number, number, number]; - expect(sessions?.[i]).toEqual({ - date: vec.date, - closeTs: utcMs(y, m, d, vec.expectedUtcHour, 0, 0), - }); - } - }); - - test('supports inclusive endpoints 1976-01-01 and 2030-12-31 and fails closed outside range', async () => { - let listingCalls = 0; - let sessionCalls = 0; - const resolver = createExchangeCalendarResolver({ - listingCalendars: { - getListingCalendars: () => { - listingCalls += 1; - return [{ listingId: 1, calendarCode: 'XNYS' }]; - }, - }, - sessionDates: { - listSessionDates: () => { - sessionCalls += 1; - return [EXCHANGE_CALENDAR_MIN_SUPPORTED_DATE, EXCHANGE_CALENDAR_MAX_SUPPORTED_DATE]; - }, - }, - }); - - const ok = await resolver({ - listingIds: [1], - fromDate: '1976-01-01', - toDate: '2030-12-31', - }); - expect(ok.calendars).toEqual({ - XNYS: [ - { date: '1976-01-01', closeTs: utcMs(1976, 1, 1, 21, 0, 0) }, - { date: '2030-12-31', closeTs: utcMs(2030, 12, 31, 21, 0, 0) }, - ], - }); - expect(listingCalls).toBe(1); - expect(sessionCalls).toBe(1); - - await expect( - resolver({ listingIds: [1], fromDate: '1975-12-31', toDate: '1976-01-02' }) - ).rejects.toThrow(ExchangeCalendarResolverError); - try { - await resolver({ listingIds: [1], fromDate: '1975-12-31', toDate: '1976-01-02' }); - } catch (err) { - expect(err).toBeInstanceOf(ExchangeCalendarResolverError); - expect((err as ExchangeCalendarResolverError).code).toBe('UNSUPPORTED_DATE'); - } - - try { - await resolver({ listingIds: [1], fromDate: '2030-12-30', toDate: '2031-01-01' }); - expect.unreachable('expected UNSUPPORTED_DATE for 2031-01-01'); - } catch (err) { - expect(err).toBeInstanceOf(ExchangeCalendarResolverError); - expect((err as ExchangeCalendarResolverError).code).toBe('UNSUPPORTED_DATE'); - } - - // Out-of-range query bounds fail before calling either port. - expect(listingCalls).toBe(1); - expect(sessionCalls).toBe(1); - }); -}); - -describe('createPostgresListingCalendarPort', () => { - test('issues one parameterized SELECT joining listing.mic to exchange.mic with no ID literals or writes', async () => { - const calls: Array<{ text: string; params: readonly unknown[] | undefined }> = []; - const executor: ListingCalendarExecutor = { - async query>(text: string, params?: readonly unknown[]) { - calls.push({ text, params }); - const rows = [ - { listing_id: 101, calendar_code: 'XNYS' }, - { listing_id: 202, calendar_code: 'XTSE' }, - ]; - return { rows: rows as unknown as readonly Row[] }; - }, - }; - - const port = createPostgresListingCalendarPort({ executor }); - const rows = await port.getListingCalendars([101, 202]); - - expect(rows).toEqual([ - { listingId: 101, calendarCode: 'XNYS' }, - { listingId: 202, calendarCode: 'XTSE' }, - ]); - expect(calls).toHaveLength(1); - - const call = calls[0] as { text: string; params: readonly unknown[] | undefined }; - expect(call.text).toContain('SELECT'); - expect(call.text).toContain('FROM listing l'); - expect(call.text).toContain('INNER JOIN exchange e ON e.mic = l.mic'); - expect(call.text).toContain('WHERE l.listing_id = ANY($1::integer[])'); - expect(call.text).not.toContain('101'); - expect(call.text).not.toContain('202'); - expect(call.text).not.toMatch(/\b(INSERT|UPDATE|DELETE|DROP|ALTER|CREATE|TRUNCATE)\b/i); - expect(call.params).toEqual([[101, 202]]); - }); - - test('supports optional validated schema qualification and short-circuits empty listingIds', async () => { - const calls: Array<{ text: string; params: readonly unknown[] | undefined }> = []; - const executor: ListingCalendarExecutor = { - async query>(text: string, params?: readonly unknown[]) { - calls.push({ text, params }); - return { rows: [{ listing_id: 7, calendar_code: 'XNYS' }] as unknown as readonly Row[] }; - }, - }; - - const port = createPostgresListingCalendarPort({ executor, schema: 'sec_master_v1' }); - expect(await port.getListingCalendars([])).toEqual([]); - expect(calls).toHaveLength(0); - - const rows = await port.getListingCalendars([7]); - expect(rows).toEqual([{ listingId: 7, calendarCode: 'XNYS' }]); - expect(calls).toHaveLength(1); - expect(calls[0]?.text).toContain('FROM "sec_master_v1".listing l'); - expect(calls[0]?.text).toContain('INNER JOIN "sec_master_v1".exchange e ON e.mic = l.mic'); - }); - - test('throws typed INVALID_EXECUTOR, INVALID_SCHEMA, and INVALID_ROW errors', async () => { - const badExecutors: unknown[] = [null, undefined, {}, { executor: null }, { executor: {} }]; - for (const bad of badExecutors) { - let caught: unknown; - try { - createPostgresListingCalendarPort(bad as never); - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(PostgresListingCalendarError); - expect((caught as PostgresListingCalendarError).code).toBe('INVALID_EXECUTOR'); - } - - const okExecutor: ListingCalendarExecutor = { - async query() { - return { rows: [] }; - }, - }; - for (const badSchema of ['', 'Public', '1bad', 'bad-schema', 'a; DROP TABLE listing;']) { - let caught: unknown; - try { - createPostgresListingCalendarPort({ executor: okExecutor, schema: badSchema }); - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(PostgresListingCalendarError); - expect((caught as PostgresListingCalendarError).code).toBe('INVALID_SCHEMA'); - } - - const badResponses: unknown[] = [ - null, - { rows: 'not-an-array' }, - { rows: [null] }, - { rows: [{ listing_id: '101', calendar_code: 'XNYS' }] }, - { rows: [{ listing_id: 2_147_483_648, calendar_code: 'XNYS' }] }, - { rows: [{ listing_id: 101, calendar_code: '' }] }, - { rows: [{ listing_id: 101, calendar_code: ' ' }] }, - { rows: [{ listing_id: 101, calendar_code: null }] }, - ]; - for (const badResp of badResponses) { - const port = createPostgresListingCalendarPort({ - executor: { - async query() { - return badResp as never; - }, - }, - }); - let caught: unknown; - try { - await port.getListingCalendars([101]); - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(PostgresListingCalendarError); - expect((caught as PostgresListingCalendarError).code).toBe('INVALID_ROW'); - } - }); -}); - -describe('createExchangeCalendarResolver — multi-calendar, earlyCloses, and buildEventStudyInput integration', () => { - const createMultiCalendarFixture = () => { - const xnysDates = ['2024-11-27', '2024-11-29', '2024-12-02', '2024-12-03'] as const; - const xtseDates = [ - '2024-11-27', - '2024-11-28', - '2024-11-29', - '2024-12-02', - '2024-12-03', - ] as const; - - const bars: BarRecord[] = [ - // Listing 101 (XNYS) — closed on US Thanksgiving 2024-11-28 - makeBar(101, '2024-11-27', 100), - makeBar(101, '2024-11-29', 110), - makeBar(101, '2024-12-02', 121), - makeBar(101, '2024-12-03', 121), - makeBar(101, '2024-12-04', 999), // post-Vault bar (must be excluded) - // Listing 102 (XNYS) - makeBar(102, '2024-11-27', 50), - makeBar(102, '2024-11-29', 55), - makeBar(102, '2024-12-02', 60.5), - makeBar(102, '2024-12-03', 60.5), - // Listing 201 (XTSE) — open on 2024-11-28 - makeBar(201, '2024-11-27', 200), - makeBar(201, '2024-11-28', 210), - makeBar(201, '2024-11-29', 220.5), - makeBar(201, '2024-12-02', 242.55), - makeBar(201, '2024-12-03', 242.55), - ]; - - // Event at 19:00:00Z on 2024-11-29 (14:00 EST): - // - After XNYS 13:00 EST early close (18:00Z), so with override it anchors to 2024-12-02. - // - Before XTSE 16:00 EST close (21:00Z), so it stays on 2024-11-29. - const eventTs = utcMs(2024, 11, 29, 19, 0, 0); - const events: EventObservation[] = [ - { listingId: 101, knownAt: eventTs, kind: 'filing', subtype: '8-K' }, - { listingId: 201, knownAt: eventTs, kind: 'filing', subtype: '8-K' }, - ]; - - return { - xnysDates, - xtseDates, - bars, - events, - fromDate: '2024-11-27', - toDate: '2024-12-03', - vaultCutoffDate: '2024-12-04', - }; - }; - - test('calls listSessionDates once per distinct calendar, anchors early-close vs 16:00 ET in buildEventStudyInput, and respects Vault cutoff', async () => { - const fixture = createMultiCalendarFixture(); - - const makePorts = () => { - const sessionCalls: SessionDatesQuery[] = []; - const listingPort: ListingCalendarPort = { - async getListingCalendars() { - return [ - { listingId: 101, calendarCode: 'XNYS' }, - { listingId: 102, calendarCode: 'XNYS' }, - { listingId: 201, calendarCode: 'XTSE' }, - ]; - }, - }; - const sessionPort: SessionDatesPort = { - async listSessionDates(q) { - sessionCalls.push(q); - return q.calendarCode === 'XNYS' ? fixture.xnysDates : fixture.xtseDates; - }, - }; - return { listingPort, sessionPort, sessionCalls }; - }; - - // 1) Baseline: no earlyCloses (all sessions close at 16:00 ET = 21:00Z in EST) - const baselinePorts = makePorts(); - const baselineResolver = createExchangeCalendarResolver({ - listingCalendars: baselinePorts.listingPort, - sessionDates: baselinePorts.sessionPort, - }); - const baselineCal = await baselineResolver({ - listingIds: [101, 102, 201], - fromDate: fixture.fromDate, - toDate: fixture.toDate, - }); - - expect(baselinePorts.sessionCalls).toEqual([ - { calendarCode: 'XNYS', fromDate: fixture.fromDate, toDate: fixture.toDate }, - { calendarCode: 'XTSE', fromDate: fixture.fromDate, toDate: fixture.toDate }, - ]); - expect(baselineCal.listingCalendarId).toEqual({ - 101: 'XNYS', - 102: 'XNYS', - 201: 'XTSE', - }); - - const baselinePanel = buildEventStudyInput({ - bars: fixture.bars, - events: fixture.events, - vaultCutoffDate: fixture.vaultCutoffDate, - benchmark: 'equal_weight', - exchangeCalendars: baselineCal, - }); - - expect(baselinePanel.diagnostics.vaultExcludedDates).toBe(1); - expect(baselinePanel.input.sessionDates).toEqual([ - '2024-11-27', - '2024-11-28', - '2024-11-29', - '2024-12-02', - '2024-12-03', - ]); - // Under 16:00 ET baseline, both listings anchor to 2024-11-29 (index 2). - expect(baselinePanel.input.events).toEqual([ - { entityId: 101, dayIndex: 2 }, - { entityId: 201, dayIndex: 2 }, - ]); - - // Consecutive-session returns: listing 101 has no 2024-11-28 session on XNYS, - // so 2024-11-27 -> 2024-11-29 is consecutive on XNYS (+10%), and 2024-11-28 is NaN. - const returns101 = baselinePanel.input.entityReturns.get(101) as Float64Array; - expect(Number.isNaN(returns101[0] as number)).toBe(true); - expect(Number.isNaN(returns101[1] as number)).toBe(true); - expect(returns101[2]).toBeCloseTo(0.1, 12); - expect(returns101[3]).toBeCloseTo(0.1, 12); - expect(returns101[4]).toBeCloseTo(0.0, 12); - - // 2) With XNYS-only early close override (780 = 13:00 ET -> 18:00Z on 2024-11-29) - const overridePorts = makePorts(); - const overrideConfig = { XNYS: { '2024-11-29': 780 } }; - const overrideResolver = createExchangeCalendarResolver({ - listingCalendars: overridePorts.listingPort, - sessionDates: overridePorts.sessionPort, - earlyCloses: overrideConfig, - }); - // Mutating caller's override object after construction must not affect resolver. - overrideConfig.XNYS['2024-11-29'] = EXCHANGE_CALENDAR_DEFAULT_CLOSE_MINUTE_ET; - - const overrideCal = await overrideResolver({ - listingIds: [101, 102, 201], - fromDate: fixture.fromDate, - toDate: fixture.toDate, - }); - - const xnysSessions = ( - overrideCal.calendars as Record - ).XNYS; - const xtseSessions = ( - overrideCal.calendars as Record - ).XTSE; - - expect(xnysSessions?.find((s) => s.date === '2024-11-29')?.closeTs).toBe( - utcMs(2024, 11, 29, 18, 0, 0) - ); - expect(xnysSessions?.find((s) => s.date === '2024-12-02')?.closeTs).toBe( - utcMs(2024, 12, 2, 21, 0, 0) - ); - expect(xtseSessions?.find((s) => s.date === '2024-11-29')?.closeTs).toBe( - utcMs(2024, 11, 29, 21, 0, 0) - ); - - const overridePanel = buildEventStudyInput({ - bars: fixture.bars, - events: fixture.events, - vaultCutoffDate: fixture.vaultCutoffDate, - benchmark: 'equal_weight', - exchangeCalendars: overrideCal, - }); - - // Listing 201 (XTSE) stays on 2024-11-29 (index 2); listing 101 (XNYS) shifts to 2024-12-02 (index 3). - expect(overridePanel.input.events).toEqual([ - { entityId: 201, dayIndex: 2 }, - { entityId: 101, dayIndex: 3 }, - ]); - }); - - test('is deterministic under permuted listingIds and reversed listing rows without mutating caller inputs', async () => { - const fixture = createMultiCalendarFixture(); - - const runWithOrder = async ( - listingIds: number[], - rows: readonly ListingCalendarRow[], - asyncSessionPort: boolean - ) => { - const snapshot = [...listingIds]; - const resolver = createExchangeCalendarResolver({ - listingCalendars: { - getListingCalendars: () => rows, - }, - sessionDates: { - listSessionDates: (q) => { - const dates = q.calendarCode === 'XNYS' ? fixture.xnysDates : fixture.xtseDates; - return asyncSessionPort ? Promise.resolve(dates) : dates; - }, - }, - earlyCloses: { XNYS: { '2024-11-29': 780 } }, - }); - - const resolved = await resolver({ - listingIds, - fromDate: fixture.fromDate, - toDate: fixture.toDate, - }); - expect(listingIds).toEqual(snapshot); - return resolved; - }; - - const forward = await runWithOrder( - [101, 102, 201], - [ - { listingId: 101, calendarCode: 'XNYS' }, - { listingId: 102, calendarCode: 'XNYS' }, - { listingId: 201, calendarCode: 'XTSE' }, - ], - false - ); - - // Permuted listingIds (including duplicate) + reversed listing rows (including identical duplicate) - const permuted = await runWithOrder( - [201, 102, 101, 102], - [ - { listingId: 201, calendarCode: 'XTSE' }, - { listingId: 102, calendarCode: 'XNYS' }, - { listingId: 102, calendarCode: 'XNYS' }, - { listingId: 101, calendarCode: 'XNYS' }, - ], - true - ); - - expect(permuted).toEqual(forward); - expect(Object.keys(permuted.calendars)).toEqual(Object.keys(forward.calendars)); - expect(Object.keys(permuted.listingCalendarId)).toEqual( - Object.keys(forward.listingCalendarId) - ); - - // Replay both resolved calendars through buildEventStudyInput on the same pinned bars, - // events, and Vault cutoff, and assert identical anchors, return series, and diagnostics. - const forwardPanel = buildEventStudyInput({ - bars: fixture.bars, - events: fixture.events, - vaultCutoffDate: fixture.vaultCutoffDate, - benchmark: 'equal_weight', - exchangeCalendars: forward, - }); - const permutedPanel = buildEventStudyInput({ - bars: fixture.bars, - events: fixture.events, - vaultCutoffDate: fixture.vaultCutoffDate, - benchmark: 'equal_weight', - exchangeCalendars: permuted, - }); - - expect(permutedPanel.input.sessionDates).toEqual(forwardPanel.input.sessionDates); - expect(permutedPanel.input.events).toEqual(forwardPanel.input.events); - expect(permutedPanel.input.events).toEqual([ - { entityId: 201, dayIndex: 2 }, - { entityId: 101, dayIndex: 3 }, - ]); - expect(Array.from(permutedPanel.input.entityReturns.keys())).toEqual( - Array.from(forwardPanel.input.entityReturns.keys()) - ); - for (const [entityId, forwardSeries] of forwardPanel.input.entityReturns.entries()) { - const permutedSeries = permutedPanel.input.entityReturns.get(entityId); - expect(permutedSeries).toBeDefined(); - expect(Array.from(permutedSeries as Float64Array)).toEqual(Array.from(forwardSeries)); - } - expect(Array.from(permutedPanel.input.benchmarkReturns)).toEqual( - Array.from(forwardPanel.input.benchmarkReturns) - ); - expect(permutedPanel.diagnostics).toEqual(forwardPanel.diagnostics); - expect(permutedPanel.diagnostics.vaultExcludedDates).toBe(1); - }); -}); - -describe('createExchangeCalendarResolver — fail-closed validation & edge cases', () => { - test('empty listingIds returns empty records with zero port calls', async () => { - let listingCalls = 0; - let sessionCalls = 0; - const resolver = createExchangeCalendarResolver({ - listingCalendars: { - getListingCalendars: () => { - listingCalls += 1; - return []; - }, - }, - sessionDates: { - listSessionDates: () => { - sessionCalls += 1; - return []; - }, - }, - }); - - const result = await resolver({ - listingIds: [], - fromDate: '2024-01-01', - toDate: '2024-12-31', - }); - - expect(result).toEqual({ calendars: {}, listingCalendarId: {} }); - expect(listingCalls).toBe(0); - expect(sessionCalls).toBe(0); - }); - - test('fails closed with zero sessionDates calls on missing, unrequested, or conflicting listing rows', async () => { - const cases: readonly { - readonly name: string; - readonly rows: readonly ListingCalendarRow[]; - readonly expectedCode: string; - }[] = [ - { - name: 'missing requested listing', - rows: [{ listingId: 101, calendarCode: 'XNYS' }], - expectedCode: 'MISSING_LISTING_CALENDAR', - }, - { - name: 'unrequested listing returned', - rows: [ - { listingId: 101, calendarCode: 'XNYS' }, - { listingId: 102, calendarCode: 'XNYS' }, - { listingId: 999, calendarCode: 'XTSE' }, - ], - expectedCode: 'UNEXPECTED_LISTING_CALENDAR', - }, - { - name: 'conflicting duplicate listing rows', - rows: [ - { listingId: 101, calendarCode: 'XNYS' }, - { listingId: 101, calendarCode: 'XTSE' }, - { listingId: 102, calendarCode: 'XNYS' }, - ], - expectedCode: 'CONFLICTING_LISTING_CALENDAR', - }, - ]; - - for (const tc of cases) { - let sessionCalls = 0; - const resolver = createExchangeCalendarResolver({ - listingCalendars: { getListingCalendars: () => tc.rows }, - sessionDates: { - listSessionDates: () => { - sessionCalls += 1; - return ['2024-12-02']; - }, - }, - }); - - let caught: unknown; - try { - await resolver({ - listingIds: [101, 102], - fromDate: '2024-12-02', - toDate: '2024-12-02', - }); - } catch (err) { - caught = err; - } - expect(caught, tc.name).toBeInstanceOf(ExchangeCalendarResolverError); - expect((caught as ExchangeCalendarResolverError).code, tc.name).toBe(tc.expectedCode); - expect(sessionCalls, tc.name).toBe(0); - } - }); - - test('fails closed with no partial result on unsorted, duplicate, malformed, or out-of-range session dates', async () => { - const badSessionLists: readonly { readonly name: string; readonly dates: unknown }[] = [ - { name: 'non-array response', dates: '2024-12-02' }, - { name: 'unsorted dates', dates: ['2024-12-03', '2024-12-02'] }, - { name: 'duplicate dates', dates: ['2024-12-02', '2024-12-02'] }, - { name: 'malformed date string', dates: ['2024-02-30'] }, - { name: 'non-string date', dates: [20241202] }, - { name: 'date before fromDate', dates: ['2024-12-01', '2024-12-02'] }, - { name: 'date after toDate', dates: ['2024-12-02', '2024-12-04'] }, - ]; - - for (const tc of badSessionLists) { - const resolver = createExchangeCalendarResolver({ - listingCalendars: { - getListingCalendars: () => [ - { listingId: 101, calendarCode: 'XNYS' }, - { listingId: 201, calendarCode: 'XTSE' }, - ], - }, - sessionDates: { - listSessionDates: (q) => - q.calendarCode === 'XNYS' ? ['2024-12-02', '2024-12-03'] : (tc.dates as never), - }, - }); - - let caught: unknown; - try { - await resolver({ - listingIds: [101, 201], - fromDate: '2024-12-02', - toDate: '2024-12-03', - }); - } catch (err) { - caught = err; - } - expect(caught, tc.name).toBeInstanceOf(ExchangeCalendarResolverError); - expect((caught as ExchangeCalendarResolverError).code, tc.name).toBe('INVALID_SESSION_DATES'); - } - }); - - test('rejects invalid earlyCloses minutes, dates, and shapes at construction with zero port calls', () => { - let listingCalls = 0; - let sessionCalls = 0; - const listingCalendars: ListingCalendarPort = { - getListingCalendars: () => { - listingCalls += 1; - return []; - }, - }; - const sessionDates: SessionDatesPort = { - listSessionDates: () => { - sessionCalls += 1; - return []; - }, - }; - - const invalidCases: readonly { readonly earlyCloses: unknown; readonly expectedCode: string }[] = - [ - { earlyCloses: null, expectedCode: 'INVALID_OPTION' }, - { earlyCloses: [], expectedCode: 'INVALID_OPTION' }, - { earlyCloses: 'XNYS', expectedCode: 'INVALID_OPTION' }, - { - earlyCloses: new Map([['XNYS', { '2024-11-29': 780 }]]), - expectedCode: 'INVALID_OPTION', - }, - { - earlyCloses: { XNYS: new Map([['2024-11-29', 780]]) }, - expectedCode: 'INVALID_OPTION', - }, - { earlyCloses: new Set(['XNYS']), expectedCode: 'INVALID_OPTION' }, - { earlyCloses: { XNYS: new Date('2024-11-29T00:00:00Z') }, expectedCode: 'INVALID_OPTION' }, - { earlyCloses: { '': { '2024-11-29': 780 } }, expectedCode: 'INVALID_OPTION' }, - { earlyCloses: { ' XNYS ': { '2024-11-29': 780 } }, expectedCode: 'INVALID_OPTION' }, - { earlyCloses: { XNYS: null }, expectedCode: 'INVALID_OPTION' }, - { earlyCloses: { XNYS: [] }, expectedCode: 'INVALID_OPTION' }, - { earlyCloses: { XNYS: { '2024-02-30': 780 } }, expectedCode: 'INVALID_OPTION' }, - { earlyCloses: { XNYS: { 'not-a-date': 780 } }, expectedCode: 'INVALID_OPTION' }, - { earlyCloses: { XNYS: { '1975-12-31': 780 } }, expectedCode: 'UNSUPPORTED_DATE' }, - { earlyCloses: { XNYS: { '2031-01-01': 780 } }, expectedCode: 'UNSUPPORTED_DATE' }, - { earlyCloses: { XNYS: { '2024-11-29': 0 } }, expectedCode: 'INVALID_OPTION' }, - { earlyCloses: { XNYS: { '2024-11-29': -1 } }, expectedCode: 'INVALID_OPTION' }, - { earlyCloses: { XNYS: { '2024-11-29': 961 } }, expectedCode: 'INVALID_OPTION' }, - { earlyCloses: { XNYS: { '2024-11-29': 780.5 } }, expectedCode: 'INVALID_OPTION' }, - { earlyCloses: { XNYS: { '2024-11-29': Number.NaN } }, expectedCode: 'INVALID_OPTION' }, - { earlyCloses: { XNYS: { '2024-11-29': '780' } }, expectedCode: 'INVALID_OPTION' }, - ]; - - for (const tc of invalidCases) { - let caught: unknown; - try { - createExchangeCalendarResolver({ - listingCalendars, - sessionDates, - earlyCloses: tc.earlyCloses as never, - }); - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(ExchangeCalendarResolverError); - expect((caught as ExchangeCalendarResolverError).code).toBe(tc.expectedCode); - } - - expect(listingCalls).toBe(0); - expect(sessionCalls).toBe(0); - }); - - test('accepts null-prototype records at both levels of earlyCloses', async () => { - const xnysOverrides = Object.create(null) as Record; - xnysOverrides['2024-11-29'] = 780; - const earlyCloses = Object.create(null) as Record>; - earlyCloses.XNYS = xnysOverrides; - - const resolver = createExchangeCalendarResolver({ - listingCalendars: { - getListingCalendars: () => [{ listingId: 101, calendarCode: 'XNYS' }], - }, - sessionDates: { - listSessionDates: () => ['2024-11-29', '2024-12-02'], - }, - earlyCloses, - }); - - const result = await resolver({ - listingIds: [101], - fromDate: '2024-11-29', - toDate: '2024-12-02', - }); - - expect(result.calendars).toEqual({ - XNYS: [ - { date: '2024-11-29', closeTs: utcMs(2024, 11, 29, 18, 0, 0) }, - { date: '2024-12-02', closeTs: utcMs(2024, 12, 2, 21, 0, 0) }, - ], - }); - }); -}); diff --git a/libs/research/test/mcp-file-finding-qa.test.ts b/libs/research/test/mcp-file-finding-qa.test.ts deleted file mode 100644 index 397637ba..00000000 --- a/libs/research/test/mcp-file-finding-qa.test.ts +++ /dev/null @@ -1,469 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { - type AppendFindingResult, - FILE_FINDING_ERROR_FILING_FAILED, - FILE_FINDING_ERROR_IDEMPOTENCY_CONFLICT, - FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF, - FILE_FINDING_MAX_EVIDENCE_REFS, - FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH, - FILE_FINDING_MAX_REF_LENGTH, - FILE_FINDING_MAX_SUMMARY_LENGTH, - FILE_FINDING_MAX_TITLE_LENGTH, - FILE_FINDING_MAX_TRIAL_REFS, - type FileFindingResultPayload, - type FiledFindingRecord, - type FindingWritePort, - type TrialRefLookupPort, - areFiledFindingPayloadsEqual, - createFileFindingTool, -} from '../src/mcp/index'; - -// Compile-time guard: the write port exposes exactly one append method (no update/delete). -type Equal = (() => T extends A ? 1 : 2) extends () => T extends B ? 1 : 2 - ? true - : false; -const writePortKeysAreAppendOnly: Equal = true; - -const FIXED_EPOCH_MS = Date.UTC(2025, 5, 2, 15, 30, 0); - -interface RecordingPort { - readonly calls: { record: FiledFindingRecord; idempotencyKey: string | undefined }[]; - readonly port: FindingWritePort; -} - -function recordingPort( - respond: (record: FiledFindingRecord, key: string | undefined) => unknown -): RecordingPort { - const calls: RecordingPort['calls'] = []; - return { - calls, - port: { - async appendFinding(record, idempotencyKey) { - calls.push({ record, idempotencyKey }); - return respond(record, idempotencyKey) as AppendFindingResult; - }, - }, - }; -} - -function createdEcho(record: FiledFindingRecord): AppendFindingResult { - return { status: 'created', id: record.id, createdAt: record.createdAt }; -} - -function lookupFrom( - answer: (ref: string) => unknown -): { readonly queried: string[]; readonly port: TrialRefLookupPort } { - const queried: string[] = []; - return { - queried, - port: { - hasResearchVisibleTrial(ref: string) { - queried.push(ref); - return answer(ref) as boolean; - }, - }, - }; -} - -function counter(fn: () => T): { calls: number; fn: () => T } { - const state = { - calls: 0, - fn: () => { - state.calls += 1; - return fn(); - }, - }; - return state; -} - -const validArgs = { - kind: 'finding', - title: 'QA filing', - summary: 'Research-visible summary.', - trialRefs: ['trial-1'], -}; - -function parseReceipt(text: string | undefined): FileFindingResultPayload { - return JSON.parse(text ?? '') as FileFindingResultPayload; -} - -describe('MCP file_finding QA edge cases', () => { - test('write port type exposes only appendFinding', () => { - expect(writePortKeysAreAppendOnly).toBe(true); - }); - - test('deduplicates trial refs before lookup, verifies in sorted order, and short-circuits on the first unavailable ref', async () => { - const rec = recordingPort(createdEcho); - const lookup = lookupFrom(ref => ref !== 'trial-b'); - const tool = createFileFindingTool({ - port: rec.port, - trialLookup: lookup.port, - newId: () => 'id-1', - now: () => FIXED_EPOCH_MS, - }); - - const res = await tool.execute({ - ...validArgs, - trialRefs: ['trial-c', 'trial-a', 'trial-b', 'trial-a', 'trial-c'], - }); - - expect(res.isError).toBe(true); - expect(res.content[0]?.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF); - expect(lookup.queried).toEqual(['trial-a', 'trial-b']); - expect(rec.calls).toHaveLength(0); - }); - - test('accepts a synchronous boolean lookup and queries each unique ref exactly once on success', async () => { - const rec = recordingPort(createdEcho); - const lookup = lookupFrom(() => true); - const tool = createFileFindingTool({ - port: rec.port, - trialLookup: lookup.port, - newId: () => 'id-sync', - now: () => FIXED_EPOCH_MS, - }); - - const res = await tool.execute({ ...validArgs, trialRefs: ['t2', 't1', 't2', 't1'] }); - - expect(res.isError).toBeUndefined(); - expect(lookup.queried).toEqual(['t1', 't2']); - expect(rec.calls).toHaveLength(1); - expect(rec.calls[0]?.record.trialRefs).toEqual(['t1', 't2']); - }); - - test('treats non-boolean lookup answers as a filing failure with zero writes and no metadata generation', async () => { - for (const answer of [1, 'true', null, undefined, {}]) { - const rec = recordingPort(createdEcho); - const ids = counter(() => 'never'); - const clock = counter(() => FIXED_EPOCH_MS); - const tool = createFileFindingTool({ - port: rec.port, - trialLookup: lookupFrom(() => answer).port, - newId: ids.fn, - now: clock.fn, - }); - - const res = await tool.execute(validArgs); - - expect(res.isError).toBe(true); - expect(res.content[0]?.text).toBe(FILE_FINDING_ERROR_FILING_FAILED); - expect(rec.calls).toHaveLength(0); - expect(ids.calls).toBe(0); - expect(clock.calls).toBe(0); - } - }); - - test('rejects unusable generated ids and clock values with a fixed error and zero writes', async () => { - const badSources: readonly { - readonly label: string; - readonly newId: () => string; - readonly now: () => Date | number; - }[] = [ - { label: 'empty id', newId: () => '', now: () => FIXED_EPOCH_MS }, - { label: 'blank id', newId: () => ' ', now: () => FIXED_EPOCH_MS }, - { label: 'non-string id', newId: () => 42 as unknown as string, now: () => FIXED_EPOCH_MS }, - { - label: 'throwing id source', - newId: () => { - throw new Error('postgres://u:p@db/x id sequence exhausted'); - }, - now: () => FIXED_EPOCH_MS, - }, - { label: 'NaN clock', newId: () => 'id-1', now: () => Number.NaN }, - { label: 'infinite clock', newId: () => 'id-1', now: () => Number.POSITIVE_INFINITY }, - { label: 'invalid Date', newId: () => 'id-1', now: () => new Date('not-a-date') }, - { label: 'out-of-range epoch', newId: () => 'id-1', now: () => 9e15 }, - { label: 'string clock', newId: () => 'id-1', now: () => '2025-01-01' as unknown as number }, - { - label: 'throwing clock', - newId: () => 'id-1', - now: () => { - throw new Error('clock unavailable at /srv/secret.ts:1:1'); - }, - }, - ]; - - for (const source of badSources) { - const rec = recordingPort(createdEcho); - const tool = createFileFindingTool({ - port: rec.port, - trialLookup: lookupFrom(() => true).port, - newId: source.newId, - now: source.now, - }); - - const res = await tool.execute(validArgs); - - expect({ label: source.label, isError: res.isError }).toEqual({ - label: source.label, - isError: true, - }); - expect(res.content[0]?.text).toBe(FILE_FINDING_ERROR_FILING_FAILED); - expect(rec.calls).toHaveLength(0); - } - }); - - test('stores Date and epoch clock values as identical UTC ISO timestamps', async () => { - const fromDate = recordingPort(createdEcho); - const fromEpoch = recordingPort(createdEcho); - const lookup = lookupFrom(() => true).port; - - await createFileFindingTool({ - port: fromDate.port, - trialLookup: lookup, - newId: () => 'id-d', - now: () => new Date(FIXED_EPOCH_MS), - }).execute(validArgs); - await createFileFindingTool({ - port: fromEpoch.port, - trialLookup: lookup, - newId: () => 'id-e', - now: () => FIXED_EPOCH_MS, - }).execute(validArgs); - - expect(fromDate.calls[0]?.record.createdAt).toBe('2025-06-02T15:30:00.000Z'); - expect(fromEpoch.calls[0]?.record.createdAt).toBe('2025-06-02T15:30:00.000Z'); - }); - - test('passes the trimmed idempotency key to the port and undefined when omitted', async () => { - const rec = recordingPort(createdEcho); - const tool = createFileFindingTool({ - port: rec.port, - trialLookup: lookupFrom(() => true).port, - newId: () => 'id-k', - now: () => FIXED_EPOCH_MS, - }); - - await tool.execute({ ...validArgs, idempotencyKey: '\t retry-key-7 \n' }); - await tool.execute(validArgs); - - expect(rec.calls.map(c => c.idempotencyKey)).toEqual(['retry-key-7', undefined]); - }); - - test('receipt reflects the port-stored id and timestamp on replay, not freshly generated metadata', async () => { - const rec = recordingPort(() => ({ - status: 'replayed', - id: 'stored-original', - createdAt: '2024-12-31T23:59:59.000Z', - })); - const tool = createFileFindingTool({ - port: rec.port, - trialLookup: lookupFrom(() => true).port, - newId: () => 'fresh-id', - now: () => FIXED_EPOCH_MS, - }); - - const res = await tool.execute({ ...validArgs, idempotencyKey: 'k' }); - - expect(res.isError).toBeUndefined(); - expect(parseReceipt(res.content[0]?.text)).toEqual({ - id: 'stored-original', - createdAt: '2024-12-31T23:59:59.000Z', - created: false, - }); - }); - - test('maps malformed port outcomes to the fixed filing error and conflict to the fixed conflict error', async () => { - const malformed: readonly unknown[] = [ - null, - undefined, - 'created', - {}, - { status: 'updated', id: 'x', createdAt: 'y' }, - { status: 'created', id: '', createdAt: '2025-01-01T00:00:00.000Z' }, - { status: 'created', id: 'x' }, - { status: 'replayed', id: 7, createdAt: '2025-01-01T00:00:00.000Z' }, - ]; - - for (const outcome of malformed) { - const tool = createFileFindingTool({ - port: recordingPort(() => outcome).port, - trialLookup: lookupFrom(() => true).port, - newId: () => 'id-m', - now: () => FIXED_EPOCH_MS, - }); - const res = await tool.execute(validArgs); - expect(res.isError).toBe(true); - expect(res.content[0]?.text).toBe(FILE_FINDING_ERROR_FILING_FAILED); - } - - const conflictTool = createFileFindingTool({ - port: recordingPort(() => ({ status: 'conflict' })).port, - trialLookup: lookupFrom(() => true).port, - newId: () => 'id-c', - now: () => FIXED_EPOCH_MS, - }); - const conflict = await conflictTool.execute({ ...validArgs, idempotencyKey: 'k' }); - expect(conflict.isError).toBe(true); - expect(conflict.content[0]?.text).toBe(FILE_FINDING_ERROR_IDEMPOTENCY_CONFLICT); - }); - - test('accepts every field exactly at its hard limit', async () => { - const rec = recordingPort(createdEcho); - const tool = createFileFindingTool({ - port: rec.port, - trialLookup: lookupFrom(() => true).port, - newId: () => 'id-limit', - now: () => FIXED_EPOCH_MS, - }); - const trialRefs = Array.from({ length: FILE_FINDING_MAX_TRIAL_REFS }, (_, i) => - `t${String(i).padStart(2, '0')}`.padEnd(FILE_FINDING_MAX_REF_LENGTH, 'x') - ); - const evidenceRefs = Array.from({ length: FILE_FINDING_MAX_EVIDENCE_REFS }, (_, i) => - `e${String(i).padStart(2, '0')}`.padEnd(FILE_FINDING_MAX_REF_LENGTH, 'y') - ); - - const res = await tool.execute({ - kind: 'dead_end', - title: 'T'.repeat(FILE_FINDING_MAX_TITLE_LENGTH), - summary: 'S'.repeat(FILE_FINDING_MAX_SUMMARY_LENGTH), - trialRefs, - evidenceRefs, - idempotencyKey: 'K'.repeat(FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH), - }); - - expect(res.isError).toBeUndefined(); - expect(rec.calls).toHaveLength(1); - expect(rec.calls[0]?.record.trialRefs).toHaveLength(FILE_FINDING_MAX_TRIAL_REFS); - expect(rec.calls[0]?.record.evidenceRefs).toHaveLength(FILE_FINDING_MAX_EVIDENCE_REFS); - }); - - test('measures limits after trimming, so padded at-limit text is accepted', async () => { - const rec = recordingPort(createdEcho); - const tool = createFileFindingTool({ - port: rec.port, - trialLookup: lookupFrom(() => true).port, - newId: () => 'id-trim', - now: () => FIXED_EPOCH_MS, - }); - - const res = await tool.execute({ - ...validArgs, - title: ` ${'T'.repeat(FILE_FINDING_MAX_TITLE_LENGTH)} `, - }); - - expect(res.isError).toBeUndefined(); - expect(rec.calls[0]?.record.title).toHaveLength(FILE_FINDING_MAX_TITLE_LENGTH); - }); - - test('validation errors never echo submitted text, refs, or keys', async () => { - const sentinel = 'HOLDOUT_OBSERVATION_SENTINEL_0x5f3'; - const rec = recordingPort(createdEcho); - const tool = createFileFindingTool({ - port: rec.port, - trialLookup: lookupFrom(() => true).port, - newId: () => 'id-v', - now: () => FIXED_EPOCH_MS, - }); - - const cases: readonly Record[] = [ - { ...validArgs, summary: `${sentinel} `.repeat(FILE_FINDING_MAX_SUMMARY_LENGTH) }, - { ...validArgs, title: sentinel.repeat(20) }, - { ...validArgs, trialRefs: [sentinel.repeat(10)] }, - { ...validArgs, evidenceRefs: [sentinel.repeat(10)] }, - { ...validArgs, idempotencyKey: sentinel.repeat(5) }, - { ...validArgs, kind: sentinel }, - { ...validArgs, [sentinel]: 1.2345 }, - { ...validArgs, observations: [{ date: '2025-09-01', value: sentinel }] }, - ]; - - for (const args of cases) { - const res = await tool.execute(args); - expect(res.isError).toBe(true); - expect(res.content[0]?.text).not.toContain(sentinel); - } - expect(rec.calls).toHaveLength(0); - }); - - test('concurrent same-key filings across two tool instances store one row (promise barrier, no timers)', async () => { - const stored: FiledFindingRecord[] = []; - const byKey = new Map(); - let releaseFirst: () => void = () => undefined; - const firstHeld = new Promise(resolve => { - releaseFirst = resolve; - }); - let secondArrived: () => void = () => undefined; - const secondReached = new Promise(resolve => { - secondArrived = resolve; - }); - let callIndex = 0; - - const port: FindingWritePort = { - async appendFinding(record, key) { - callIndex += 1; - const mine = callIndex; - // Atomic compare-and-append (no await between read and write). - let outcome: AppendFindingResult; - const existing = key === undefined ? undefined : byKey.get(key); - if (existing === undefined) { - stored.push(record); - if (key !== undefined) { - byKey.set(key, record); - } - outcome = { status: 'created', id: record.id, createdAt: record.createdAt }; - } else if (areFiledFindingPayloadsEqual(existing, record)) { - outcome = { status: 'replayed', id: existing.id, createdAt: existing.createdAt }; - } else { - outcome = { status: 'conflict' }; - } - if (mine === 1) { - await firstHeld; - } else { - secondArrived(); - } - return outcome; - }, - }; - const lookup = lookupFrom(() => true).port; - const toolA = createFileFindingTool({ - port, - trialLookup: lookup, - newId: () => 'inst-a', - now: () => FIXED_EPOCH_MS, - }); - const toolB = createFileFindingTool({ - port, - trialLookup: lookup, - newId: () => 'inst-b', - now: () => FIXED_EPOCH_MS + 1_000, - }); - const args = { ...validArgs, idempotencyKey: 'concurrent' }; - - const pendingA = toolA.execute(args); - const pendingB = toolB.execute(args); - await secondReached; - releaseFirst(); - const [resA, resB] = await Promise.all([pendingA, pendingB]); - - expect(stored).toHaveLength(1); - expect(parseReceipt(resA.content[0]?.text)).toEqual({ - id: 'inst-a', - createdAt: new Date(FIXED_EPOCH_MS).toISOString(), - created: true, - }); - expect(parseReceipt(resB.content[0]?.text)).toEqual({ - id: 'inst-a', - createdAt: new Date(FIXED_EPOCH_MS).toISOString(), - created: false, - }); - }); - - test('payload equality helper ignores server metadata and is order-sensitive on normalized refs', () => { - const base = { - kind: 'finding' as const, - title: 't', - summary: 's', - trialRefs: ['a', 'b'], - evidenceRefs: [], - }; - expect( - areFiledFindingPayloadsEqual( - { ...base, id: 'x', createdAt: '1', status: 'pending_review' } as FiledFindingRecord, - { ...base, id: 'y', createdAt: '2', status: 'pending_review' } as FiledFindingRecord - ) - ).toBe(true); - expect(areFiledFindingPayloadsEqual(base, { ...base, trialRefs: ['a'] })).toBe(false); - expect(areFiledFindingPayloadsEqual(base, { ...base, evidenceRefs: ['e'] })).toBe(false); - expect(areFiledFindingPayloadsEqual(base, { ...base, title: 'T' })).toBe(false); - }); -}); diff --git a/libs/research/test/mcp-file-finding.test.ts b/libs/research/test/mcp-file-finding.test.ts deleted file mode 100644 index ea47b644..00000000 --- a/libs/research/test/mcp-file-finding.test.ts +++ /dev/null @@ -1,1100 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import * as rootResearchExports from '../src/index'; -import { - type AppendFindingResult, - FILE_FINDING_ERROR_FILING_FAILED, - FILE_FINDING_ERROR_IDEMPOTENCY_CONFLICT, - FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF, - FILE_FINDING_ERROR_UNKNOWN_KEYS, - FILE_FINDING_INITIAL_STATUS, - FILE_FINDING_KINDS, - FILE_FINDING_MAX_EVIDENCE_REFS, - FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH, - FILE_FINDING_MAX_REF_LENGTH, - FILE_FINDING_MAX_SUMMARY_LENGTH, - FILE_FINDING_MAX_TITLE_LENGTH, - FILE_FINDING_MAX_TRIAL_REFS, - type FileFindingResultPayload, - type FiledFindingRecord, - type FindingQuery, - type FindingRecord, - type FindingWritePort, - type KnowledgePort, - type ReadKnowledgeResultPayload, - type TrialRefLookupPort, - areFiledFindingPayloadsEqual, - createFileFindingTool, - createMcpServer, - createReadKnowledgeTool, - fileFindingInputSchema, -} from '../src/mcp/index'; - -interface SharedFindingsFakeOptions { - readonly failNextAppendError?: unknown; - readonly alwaysAppendError?: unknown; - readonly delayFirstAppendMs?: number; - readonly attachExtraReceiptField?: boolean; -} - -interface SharedFindingsFake { - readonly stored: FiledFindingRecord[]; - readonly appendCalls: { - readonly record: FiledFindingRecord; - readonly idempotencyKey?: string; - }[]; - readonly writePort: FindingWritePort; - readonly knowledgePort: KnowledgePort; - readonly invokedWriteMethods: string[]; -} - -function createSharedFindingsFake(options?: SharedFindingsFakeOptions): SharedFindingsFake { - const stored: FiledFindingRecord[] = []; - const byIdempotencyKey = new Map(); - const appendCalls: { readonly record: FiledFindingRecord; readonly idempotencyKey?: string }[] = - []; - const invokedWriteMethods: string[] = []; - - let failOnceError: unknown = options?.failNextAppendError; - let firstCallSeen = false; - - const rawWritePort: FindingWritePort = { - async appendFinding( - record: FiledFindingRecord, - idempotencyKey?: string - ): Promise { - appendCalls.push({ record, idempotencyKey }); - - if (options?.alwaysAppendError !== undefined) { - throw options.alwaysAppendError; - } - - if (failOnceError !== undefined) { - const err = failOnceError; - failOnceError = undefined; - throw err; - } - - // Atomic compare-and-append before any async yield so concurrent calls with - // the same idempotencyKey cannot both insert. - let outcome: AppendFindingResult; - if (idempotencyKey !== undefined) { - const existing = byIdempotencyKey.get(idempotencyKey); - if (existing !== undefined) { - if (areFiledFindingPayloadsEqual(existing, record)) { - outcome = { - status: 'replayed', - id: existing.id, - createdAt: existing.createdAt, - }; - } else { - outcome = { status: 'conflict' }; - } - } else { - const copy: FiledFindingRecord = { - ...record, - trialRefs: [...record.trialRefs], - evidenceRefs: [...record.evidenceRefs], - }; - stored.push(copy); - byIdempotencyKey.set(idempotencyKey, copy); - outcome = { - status: 'created', - id: copy.id, - createdAt: copy.createdAt, - }; - } - } else { - const copy: FiledFindingRecord = { - ...record, - trialRefs: [...record.trialRefs], - evidenceRefs: [...record.evidenceRefs], - }; - stored.push(copy); - outcome = { - status: 'created', - id: copy.id, - createdAt: copy.createdAt, - }; - } - - if (!firstCallSeen && options?.delayFirstAppendMs !== undefined) { - firstCallSeen = true; - await new Promise(resolve => setTimeout(resolve, options.delayFirstAppendMs)); - } - - if (options?.attachExtraReceiptField === true && outcome.status !== 'conflict') { - return { - ...outcome, - internalDsn: 'postgres://leaked:pass@127.0.0.1:5432/trading_bot', - } as unknown as AppendFindingResult; - } - - return outcome; - }, - }; - - const writePort = new Proxy(rawWritePort, { - get(target, prop, receiver) { - const value: unknown = Reflect.get(target, prop, receiver); - if (typeof value === 'function' && typeof prop === 'string') { - return (...args: unknown[]) => { - invokedWriteMethods.push(prop); - return (value as (...a: unknown[]) => unknown).apply(target, args); - }; - } - return value; - }, - }); - - const knowledgePort: KnowledgePort = { - async listLibraryCards() { - return []; - }, - async listFindings(q: FindingQuery): Promise { - return stored.filter(item => { - if (q.id !== undefined && item.id !== q.id) { - return false; - } - if (q.query !== undefined) { - const needle = q.query.toLowerCase(); - return ( - item.title.toLowerCase().includes(needle) || item.summary.toLowerCase().includes(needle) - ); - } - return true; - }); - }, - async listProviderCaveats() { - return []; - }, - }; - - return { - stored, - appendCalls, - writePort, - knowledgePort, - invokedWriteMethods, - }; -} - -interface FakeTrialLookup { - readonly queriedRefs: string[]; - readonly port: TrialRefLookupPort; -} - -function createFakeTrialLookup(options?: { - readonly researchVisibleRefs?: readonly string[]; - readonly vaultOnlyRefs?: readonly string[]; - readonly throwError?: unknown; -}): FakeTrialLookup { - const visibleSet = new Set( - options?.researchVisibleRefs ?? ['trial-101', 'trial-102', '9007199254740993123'] - ); - const vaultOnlySet = new Set(options?.vaultOnlyRefs ?? ['trial-vault-999']); - const queriedRefs: string[] = []; - - const port: TrialRefLookupPort = { - async hasResearchVisibleTrial(trialRef: string): Promise { - queriedRefs.push(trialRef); - if (options?.throwError !== undefined) { - throw options.throwError; - } - if (vaultOnlySet.has(trialRef)) { - return false; - } - return visibleSet.has(trialRef); - }, - }; - - return { queriedRefs, port }; -} - -function createFixedClock(startIso = '2025-03-01T12:00:00.000Z', stepMs = 60_000) { - let current = Date.parse(startIso); - let calls = 0; - return { - get calls() { - return calls; - }, - now: () => { - calls += 1; - const value = current; - current += stepMs; - return value; - }, - }; -} - -function createFixedIdGenerator(prefix = 'find') { - let counter = 0; - return { - get calls() { - return counter; - }, - newId: () => { - counter += 1; - return `${prefix}-${String(counter).padStart(4, '0')}`; - }, - }; -} - -async function callTool( - server: ReturnType, - toolName: string, - args: Record, - id: string | number = 'req-1' -): Promise<{ - readonly isError: boolean; - readonly text: string; - readonly payload: TPayload | null; -}> { - const raw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id, - method: 'tools/call', - params: { - name: toolName, - arguments: args, - }, - }) - ); - - expect(raw).not.toBeNull(); - const parsed = JSON.parse(raw as string) as { - error?: unknown; - result: { - isError?: boolean; - content: { type: string; text: string }[]; - }; - }; - expect(parsed.error).toBeUndefined(); - const isError = parsed.result.isError === true; - const text = parsed.result.content[0]?.text ?? ''; - - return { - isError, - text, - payload: isError ? null : (JSON.parse(text) as TPayload), - }; -} - -describe('MCP file_finding tool', () => { - test('files both finding and dead_end with fixed server metadata, normalization, and explicit receipt projection', async () => { - const fake = createSharedFindingsFake({ attachExtraReceiptField: true }); - const trialLookup = createFakeTrialLookup(); - const clock = createFixedClock('2025-03-01T10:00:00.000Z', 60_000); - const idGen = createFixedIdGenerator('finding'); - - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createFileFindingTool({ - port: fake.writePort, - trialLookup: trialLookup.port, - newId: idGen.newId, - now: clock.now, - }), - ], - }); - - const findingRes = await callTool(server, 'file_finding', { - kind: 'finding', - title: ' Post-earnings drift decays after day 3 ', - summary: ' Cross-sectional CAR flattens after session +3 across 2015-2024. ', - trialRefs: [' trial-102 ', '9007199254740993123', 'trial-102', 'trial-101'], - evidenceRefs: [' snap-b ', 'snap-a', 'snap-b', 'Snap-A'], - }); - - expect(findingRes.isError).toBe(false); - expect(findingRes.payload).toEqual({ - id: 'finding-0001', - createdAt: '2025-03-01T10:00:00.000Z', - created: true, - }); - expect(Object.keys(findingRes.payload as unknown as Record).sort()).toEqual([ - 'created', - 'createdAt', - 'id', - ]); - - expect(fake.stored[0]).toEqual({ - id: 'finding-0001', - kind: 'finding', - title: 'Post-earnings drift decays after day 3', - status: FILE_FINDING_INITIAL_STATUS, - createdAt: '2025-03-01T10:00:00.000Z', - summary: 'Cross-sectional CAR flattens after session +3 across 2015-2024.', - trialRefs: ['9007199254740993123', 'trial-101', 'trial-102'], - evidenceRefs: ['Snap-A', 'snap-a', 'snap-b'], - }); - - const deadEndRes = await callTool(server, 'file_finding', { - kind: 'dead_end', - title: 'Short-interest 1d reversal', - summary: 'No net edge after realistic borrow and spread costs.', - trialRefs: ['trial-101'], - }); - - expect(deadEndRes.isError).toBe(false); - expect(deadEndRes.payload).toEqual({ - id: 'finding-0002', - createdAt: '2025-03-01T10:01:00.000Z', - created: true, - }); - expect(fake.stored[1]).toEqual({ - id: 'finding-0002', - kind: 'dead_end', - title: 'Short-interest 1d reversal', - status: 'pending_review', - createdAt: '2025-03-01T10:01:00.000Z', - summary: 'No net edge after realistic borrow and spread costs.', - trialRefs: ['trial-101'], - evidenceRefs: [], - }); - expect(fake.invokedWriteMethods).toEqual(['appendFinding', 'appendFinding']); - }); - - test('rejects invalid inputs, blank or over-length fields, raw array limits, unknown fields, and metadata overrides with zero writes', async () => { - const fake = createSharedFindingsFake(); - const trialLookup = createFakeTrialLookup(); - const clock = createFixedClock(); - const idGen = createFixedIdGenerator(); - - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createFileFindingTool({ - port: fake.writePort, - trialLookup: trialLookup.port, - newId: idGen.newId, - now: clock.now, - }), - ], - }); - - const validBase = { - kind: 'finding', - title: 'Valid title', - summary: 'Valid research-visible summary', - trialRefs: ['trial-101'], - }; - - const invalidCases: readonly { - readonly label: string; - readonly args: Record; - readonly forbiddenSubstring?: string; - }[] = [ - { label: 'missing trialRefs', args: { kind: 'finding', title: 'T', summary: 'S' } }, - { label: 'empty trialRefs', args: { ...validBase, trialRefs: [] } }, - { label: 'blank trialRef', args: { ...validBase, trialRefs: [' '] } }, - { label: 'blank evidenceRef', args: { ...validBase, evidenceRefs: [' '] } }, - { label: 'blank title', args: { ...validBase, title: ' ' } }, - { label: 'blank summary', args: { ...validBase, summary: '\t\n ' } }, - { label: 'blank idempotencyKey', args: { ...validBase, idempotencyKey: ' ' } }, - { - label: 'over-length title', - args: { ...validBase, title: 'a'.repeat(FILE_FINDING_MAX_TITLE_LENGTH + 1) }, - }, - { - label: 'over-length summary', - args: { ...validBase, summary: 's'.repeat(FILE_FINDING_MAX_SUMMARY_LENGTH + 1) }, - }, - { - label: 'over-length trialRef', - args: { ...validBase, trialRefs: ['r'.repeat(FILE_FINDING_MAX_REF_LENGTH + 1)] }, - }, - { - label: 'over-length evidenceRef', - args: { ...validBase, evidenceRefs: ['e'.repeat(FILE_FINDING_MAX_REF_LENGTH + 1)] }, - }, - { - label: 'over-length idempotencyKey', - args: { - ...validBase, - idempotencyKey: 'k'.repeat(FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH + 1), - }, - }, - { - label: 'raw trialRefs exceeds 32 even with duplicates', - args: { - ...validBase, - trialRefs: Array.from({ length: FILE_FINDING_MAX_TRIAL_REFS + 1 }, () => 'trial-101'), - }, - }, - { - label: 'raw evidenceRefs exceeds 32 even with duplicates', - args: { - ...validBase, - evidenceRefs: Array.from( - { length: FILE_FINDING_MAX_EVIDENCE_REFS + 1 }, - () => 'snap-01' - ), - }, - }, - { - label: 'invalid kind does not echo caller value', - args: { ...validBase, kind: 'vault_secret_kind_sentinel' }, - forbiddenSubstring: 'vault_secret_kind_sentinel', - }, - { label: 'invalid title type', args: { ...validBase, title: 123 } }, - { label: 'invalid trialRefs type', args: { ...validBase, trialRefs: 'trial-101' } }, - { - label: 'caller-supplied id rejected', - args: { ...validBase, id: 'attacker-id' }, - forbiddenSubstring: 'attacker-id', - }, - { - label: 'caller-supplied status rejected', - args: { ...validBase, status: 'confirmed' }, - forbiddenSubstring: 'confirmed', - }, - { - label: 'caller-supplied createdAt rejected', - args: { ...validBase, createdAt: '2020-01-01T00:00:00.000Z' }, - forbiddenSubstring: '2020-01-01', - }, - { - label: 'holdout scope rejected without echoing key', - args: { ...validBase, scope: 'vault_evaluation_only' }, - forbiddenSubstring: 'scope', - }, - { - label: 'holdout vault_evaluation_only rejected without echoing key', - args: { ...validBase, vault_evaluation_only: true }, - forbiddenSubstring: 'vault_evaluation_only', - }, - { - label: 'holdout vaultCutoffTs rejected without echoing key', - args: { ...validBase, vaultCutoffTs: 1_700_000_000_000 }, - forbiddenSubstring: 'vaultCutoffTs', - }, - { - label: 'unknown-key sentinel rejected without echoing sentinel', - args: { ...validBase, vaultHoldoutKeySentinel_XYZ: 'secret-value' }, - forbiddenSubstring: 'vaultHoldoutKeySentinel_XYZ', - }, - ]; - - for (const testCase of invalidCases) { - const res = await callTool(server, 'file_finding', testCase.args); - expect(res.isError).toBe(true); - if (testCase.forbiddenSubstring !== undefined) { - expect(res.text).not.toContain(testCase.forbiddenSubstring); - } - if ( - testCase.label.includes('unknown-key') || - testCase.label.includes('holdout') || - testCase.label.includes('caller-supplied') - ) { - expect(res.text).toContain(FILE_FINDING_ERROR_UNKNOWN_KEYS); - } - } - - expect(fake.stored).toHaveLength(0); - expect(fake.appendCalls).toHaveLength(0); - expect(trialLookup.queriedRefs).toHaveLength(0); - expect(idGen.calls).toBe(0); - expect(clock.calls).toBe(0); - - // Raw 32 duplicate entries are accepted (bounds applied before dedup). - const maxRawRes = await callTool(server, 'file_finding', { - ...validBase, - trialRefs: Array.from({ length: FILE_FINDING_MAX_TRIAL_REFS }, () => 'trial-101'), - evidenceRefs: Array.from({ length: FILE_FINDING_MAX_EVIDENCE_REFS }, () => 'snap-1'), - }); - expect(maxRawRes.isError).toBe(false); - expect(fake.stored).toHaveLength(1); - expect(fake.stored[0]?.trialRefs).toEqual(['trial-101']); - expect(fake.stored[0]?.evidenceRefs).toEqual(['snap-1']); - }); - - test('rejects unknown and Vault-only trial refs identically with zero writes and zero metadata generation', async () => { - const fake = createSharedFindingsFake(); - const trialLookup = createFakeTrialLookup({ - researchVisibleRefs: ['trial-101'], - vaultOnlyRefs: ['trial-vault-only-secret'], - }); - const clock = createFixedClock(); - const idGen = createFixedIdGenerator(); - - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createFileFindingTool({ - port: fake.writePort, - trialLookup: trialLookup.port, - newId: idGen.newId, - now: clock.now, - }), - ], - }); - - const unknownRes = await callTool(server, 'file_finding', { - kind: 'finding', - title: 'Mixed valid and unknown ref', - summary: 'Should fail before writing.', - trialRefs: ['trial-101', 'trial-unknown-secret-ref'], - }); - - const vaultRes = await callTool(server, 'file_finding', { - kind: 'finding', - title: 'Mixed valid and Vault-only ref', - summary: 'Should fail identically to unknown ref.', - trialRefs: ['trial-101', 'trial-vault-only-secret'], - }); - - expect(unknownRes.isError).toBe(true); - expect(vaultRes.isError).toBe(true); - expect(unknownRes.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF); - expect(vaultRes.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF); - expect(unknownRes.text).not.toContain('trial-unknown-secret-ref'); - expect(vaultRes.text).not.toContain('trial-vault-only-secret'); - expect(fake.stored).toHaveLength(0); - expect(fake.appendCalls).toHaveLength(0); - expect(idGen.calls).toBe(0); - expect(clock.calls).toBe(0); - }); - - test('sanitizes lookup and append exceptions so DSNs and stack markers never leak', async () => { - const fakeDsn = 'postgres://writer:supersecret@10.0.0.51:5432/trading_bot'; - const stackMarker = 'at internalPgPoolQuery (/srv/stock-bot/secret-adapter.ts:91:13)'; - - const lookupErr = new Error(`Lookup failed on ${fakeDsn}\n ${stackMarker}`); - lookupErr.name = 'PgConnectionError'; - - const lookupFake = createSharedFindingsFake(); - const failingLookup = createFakeTrialLookup({ throwError: lookupErr }); - const lookupServer = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createFileFindingTool({ - port: lookupFake.writePort, - trialLookup: failingLookup.port, - newId: createFixedIdGenerator().newId, - now: createFixedClock().now, - }), - ], - }); - - const lookupRes = await callTool(lookupServer, 'file_finding', { - kind: 'finding', - title: 'Lookup failure test', - summary: 'Summary text', - trialRefs: ['trial-101'], - }); - expect(lookupRes.isError).toBe(true); - expect(lookupRes.text).toBe(FILE_FINDING_ERROR_FILING_FAILED); - expect(lookupRes.text).not.toContain(fakeDsn); - expect(lookupRes.text).not.toContain(stackMarker); - expect(lookupRes.text).not.toContain('PgConnectionError'); - expect(lookupFake.appendCalls).toHaveLength(0); - - const appendErr = new Error(`INSERT failed on ${fakeDsn}\n ${stackMarker}`); - appendErr.name = 'DatabaseWriteError'; - const appendFake = createSharedFindingsFake({ alwaysAppendError: appendErr }); - const appendServer = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createFileFindingTool({ - port: appendFake.writePort, - trialLookup: createFakeTrialLookup().port, - newId: createFixedIdGenerator().newId, - now: createFixedClock().now, - }), - ], - }); - - const appendRes = await callTool(appendServer, 'file_finding', { - kind: 'finding', - title: 'Append failure test', - summary: 'Summary text', - trialRefs: ['trial-101'], - }); - expect(appendRes.isError).toBe(true); - expect(appendRes.text).toBe(FILE_FINDING_ERROR_FILING_FAILED); - expect(appendRes.text).not.toContain(fakeDsn); - expect(appendRes.text).not.toContain(stackMarker); - expect(appendRes.text).not.toContain('DatabaseWriteError'); - }); - - test('enforces idempotency replays, per-field conflicts, concurrent retries across instances, post-failure retry, and independent unkeyed calls', async () => { - const fake = createSharedFindingsFake(); - const trialLookup = createFakeTrialLookup(); - const clock = createFixedClock('2025-03-01T14:00:00.000Z', 60_000); - const idGen = createFixedIdGenerator('idem'); - - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createFileFindingTool({ - port: fake.writePort, - trialLookup: trialLookup.port, - newId: idGen.newId, - now: clock.now, - }), - ], - }); - - const first = await callTool(server, 'file_finding', { - kind: 'finding', - title: 'Momentum crowding signal', - summary: 'Observed IC decay during high volatility regimes.', - trialRefs: ['trial-102', 'trial-101'], - idempotencyKey: ' key-001 ', - }); - expect(first.isError).toBe(false); - expect(first.payload).toEqual({ - id: 'idem-0001', - createdAt: '2025-03-01T14:00:00.000Z', - created: true, - }); - expect(fake.stored).toHaveLength(1); - - // Replay with whitespace, duplicate/reordered refs, and explicit empty evidenceRefs. - const replay = await callTool(server, 'file_finding', { - kind: 'finding', - title: ' Momentum crowding signal ', - summary: ' Observed IC decay during high volatility regimes. ', - trialRefs: ['trial-101', ' trial-102 ', 'trial-101'], - evidenceRefs: [], - idempotencyKey: 'key-001', - }); - expect(replay.isError).toBe(false); - expect(replay.payload).toEqual({ - id: 'idem-0001', - createdAt: '2025-03-01T14:00:00.000Z', - created: false, - }); - expect(fake.stored).toHaveLength(1); - - // Changing each normalized payload field in turn causes a conflict with zero extra rows. - const conflictPayloads: readonly Record[] = [ - { - kind: 'dead_end', - title: 'Momentum crowding signal', - summary: 'Observed IC decay during high volatility regimes.', - trialRefs: ['trial-101', 'trial-102'], - evidenceRefs: [], - idempotencyKey: 'key-001', - }, - { - kind: 'finding', - title: 'Different title', - summary: 'Observed IC decay during high volatility regimes.', - trialRefs: ['trial-101', 'trial-102'], - evidenceRefs: [], - idempotencyKey: 'key-001', - }, - { - kind: 'finding', - title: 'Momentum crowding signal', - summary: 'Different summary', - trialRefs: ['trial-101', 'trial-102'], - evidenceRefs: [], - idempotencyKey: 'key-001', - }, - { - kind: 'finding', - title: 'Momentum crowding signal', - summary: 'Observed IC decay during high volatility regimes.', - trialRefs: ['trial-101'], - evidenceRefs: [], - idempotencyKey: 'key-001', - }, - { - kind: 'finding', - title: 'Momentum crowding signal', - summary: 'Observed IC decay during high volatility regimes.', - trialRefs: ['trial-101', 'trial-102'], - evidenceRefs: ['snap-extra'], - idempotencyKey: 'key-001', - }, - ]; - - for (const conflictArgs of conflictPayloads) { - const res = await callTool(server, 'file_finding', conflictArgs); - expect(res.isError).toBe(true); - expect(res.text).toBe(FILE_FINDING_ERROR_IDEMPOTENCY_CONFLICT); - } - expect(fake.stored).toHaveLength(1); - - // Concurrent same-key calls across two separate tool instances sharing one port. - const concurrentFake = createSharedFindingsFake({ delayFirstAppendMs: 10 }); - const toolA = createFileFindingTool({ - port: concurrentFake.writePort, - trialLookup: trialLookup.port, - newId: createFixedIdGenerator('instA').newId, - now: createFixedClock('2025-03-02T00:00:00.000Z').now, - }); - const toolB = createFileFindingTool({ - port: concurrentFake.writePort, - trialLookup: trialLookup.port, - newId: createFixedIdGenerator('instB').newId, - now: createFixedClock('2025-03-02T05:00:00.000Z').now, - }); - const concurrentArgs = { - kind: 'finding', - title: 'Concurrent filing', - summary: 'Submitted concurrently by two retries.', - trialRefs: ['trial-101'], - idempotencyKey: 'concurrent-key', - }; - - const [resA, resB] = await Promise.all([ - toolA.execute(concurrentArgs), - toolB.execute(concurrentArgs), - ]); - expect(resA.isError).toBeUndefined(); - expect(resB.isError).toBeUndefined(); - const payloadA = JSON.parse(resA.content[0]?.text ?? '') as FileFindingResultPayload; - const payloadB = JSON.parse(resB.content[0]?.text ?? '') as FileFindingResultPayload; - expect(concurrentFake.stored).toHaveLength(1); - expect(payloadA.id).toBe(payloadB.id); - expect(payloadA.createdAt).toBe(payloadB.createdAt); - expect([payloadA.created, payloadB.created].sort()).toEqual([false, true]); - - // Retry after an injected pre-commit failure succeeds cleanly. - const retryFake = createSharedFindingsFake({ - failNextAppendError: new Error('transient pre-commit timeout'), - }); - const retryServer = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createFileFindingTool({ - port: retryFake.writePort, - trialLookup: trialLookup.port, - newId: createFixedIdGenerator('retry').newId, - now: createFixedClock('2025-03-03T08:00:00.000Z').now, - }), - ], - }); - - const failedAttempt = await callTool(retryServer, 'file_finding', { - kind: 'dead_end', - title: 'Retry after failure', - summary: 'First attempt fails before commit.', - trialRefs: ['trial-101'], - idempotencyKey: 'retry-key', - }); - expect(failedAttempt.isError).toBe(true); - expect(failedAttempt.text).toBe(FILE_FINDING_ERROR_FILING_FAILED); - expect(retryFake.stored).toHaveLength(0); - - const retryAttempt = await callTool(retryServer, 'file_finding', { - kind: 'dead_end', - title: 'Retry after failure', - summary: 'First attempt fails before commit.', - trialRefs: ['trial-101'], - idempotencyKey: 'retry-key', - }); - expect(retryAttempt.isError).toBe(false); - expect(retryAttempt.payload).toEqual({ - id: 'retry-0002', - createdAt: '2025-03-03T08:01:00.000Z', - created: true, - }); - expect(retryFake.stored).toHaveLength(1); - - // Unkeyed calls with identical payloads are independent. - const unkeyed1 = await callTool(server, 'file_finding', { - kind: 'finding', - title: 'Unkeyed entry', - summary: 'Independent unkeyed filing.', - trialRefs: ['trial-101'], - }); - const unkeyed2 = await callTool(server, 'file_finding', { - kind: 'finding', - title: 'Unkeyed entry', - summary: 'Independent unkeyed filing.', - trialRefs: ['trial-101'], - }); - expect(unkeyed1.isError).toBe(false); - expect(unkeyed2.isError).toBe(false); - expect(unkeyed1.payload?.created).toBe(true); - expect(unkeyed2.payload?.created).toBe(true); - expect(unkeyed1.payload?.id).not.toBe(unkeyed2.payload?.id); - expect(fake.stored).toHaveLength(3); - }); - - test('advertises strict schema via tools/list and round-trips filed records through read_knowledge', async () => { - const fake = createSharedFindingsFake(); - const trialLookup = createFakeTrialLookup(); - const clock = createFixedClock('2025-03-04T09:30:00.000Z', 120_000); - const idGen = createFixedIdGenerator('kb'); - - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createFileFindingTool({ - port: fake.writePort, - trialLookup: trialLookup.port, - newId: idGen.newId, - now: clock.now, - }), - createReadKnowledgeTool({ - port: fake.knowledgePort, - }), - ], - }); - - const listRaw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 'list-1', - method: 'tools/list', - }) - ); - expect(listRaw).not.toBeNull(); - const listParsed = JSON.parse(listRaw as string) as { - result: { - tools: { - name: string; - description: string; - inputSchema: { - type: string; - properties: Record>; - required?: string[]; - additionalProperties: boolean; - }; - }[]; - }; - }; - - expect(listParsed.result.tools.map(t => t.name)).toEqual(['file_finding', 'read_knowledge']); - const tool = listParsed.result.tools.find(t => t.name === 'file_finding'); - expect(tool).toBeDefined(); - expect(tool?.inputSchema.type).toBe('object'); - expect(tool?.inputSchema.additionalProperties).toBe(false); - expect(tool?.inputSchema.required).toEqual(['kind', 'title', 'summary', 'trialRefs']); - expect(tool?.inputSchema.properties.kind).toMatchObject({ - type: 'string', - enum: [...FILE_FINDING_KINDS], - }); - expect(tool?.inputSchema.properties.title).toMatchObject({ - type: 'string', - minLength: 1, - maxLength: FILE_FINDING_MAX_TITLE_LENGTH, - }); - expect(tool?.inputSchema.properties.summary).toMatchObject({ - type: 'string', - minLength: 1, - maxLength: FILE_FINDING_MAX_SUMMARY_LENGTH, - }); - expect(tool?.inputSchema.properties.trialRefs).toMatchObject({ - type: 'array', - minItems: 1, - maxItems: FILE_FINDING_MAX_TRIAL_REFS, - items: { type: 'string', minLength: 1, maxLength: FILE_FINDING_MAX_REF_LENGTH }, - }); - expect(tool?.inputSchema.properties.evidenceRefs).toMatchObject({ - type: 'array', - maxItems: FILE_FINDING_MAX_EVIDENCE_REFS, - default: [], - items: { type: 'string', minLength: 1, maxLength: FILE_FINDING_MAX_REF_LENGTH }, - }); - expect(tool?.inputSchema.properties.idempotencyKey).toMatchObject({ - type: 'string', - minLength: 1, - maxLength: FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH, - }); - expect(tool?.inputSchema.properties.id).toBeUndefined(); - expect(tool?.inputSchema.properties.status).toBeUndefined(); - expect(tool?.inputSchema.properties.createdAt).toBeUndefined(); - expect(tool?.inputSchema.properties.scope).toBeUndefined(); - expect(tool?.inputSchema.properties.vault_evaluation_only).toBeUndefined(); - expect(tool?.inputSchema.properties.vaultCutoffTs).toBeUndefined(); - - // File both kinds via tools/call and read each back through read_knowledge. - const filedFinding = await callTool( - server, - 'file_finding', - { - kind: 'finding', - title: ' Event-study drift after SEC 8-K ', - summary: ' CAR peaks on session +2 and persists through +5. ', - trialRefs: ['trial-102', 'trial-101', 'trial-102'], - evidenceRefs: ['ev-html-2', 'ev-html-1'], - }, - 'call-f1' - ); - expect(filedFinding.isError).toBe(false); - const findingId = filedFinding.payload?.id as string; - - const filedDeadEnd = await callTool( - server, - 'file_finding', - { - kind: 'dead_end', - title: 'Intraday gap fade on microcaps', - summary: 'Edge disappears once 15 bps slippage is modeled.', - trialRefs: ['9007199254740993123'], - }, - 'call-f2' - ); - expect(filedDeadEnd.isError).toBe(false); - const deadEndId = filedDeadEnd.payload?.id as string; - - const readFinding = await callTool( - server, - 'read_knowledge', - { source: 'findings', id: findingId }, - 'call-r1' - ); - expect(readFinding.isError).toBe(false); - expect(readFinding.payload).toEqual({ - rowCount: 1, - sources: { library: 0, findings: 1, provider_caveats: 0 }, - rows: [ - { - source: 'findings', - id: findingId, - title: 'Event-study drift after SEC 8-K', - status: 'pending_review', - createdAt: '2025-03-04T09:30:00.000Z', - summary: 'CAR peaks on session +2 and persists through +5.', - trialRefs: ['trial-101', 'trial-102'], - evidenceRefs: ['ev-html-1', 'ev-html-2'], - truncated: false, - }, - ], - }); - expect(fake.stored.find(r => r.id === findingId)?.kind).toBe('finding'); - - const readDeadEnd = await callTool( - server, - 'read_knowledge', - { source: 'findings', id: deadEndId }, - 'call-r2' - ); - expect(readDeadEnd.isError).toBe(false); - expect(readDeadEnd.payload).toEqual({ - rowCount: 1, - sources: { library: 0, findings: 1, provider_caveats: 0 }, - rows: [ - { - source: 'findings', - id: deadEndId, - title: 'Intraday gap fade on microcaps', - status: 'pending_review', - createdAt: '2025-03-04T09:32:00.000Z', - summary: 'Edge disappears once 15 bps slippage is modeled.', - trialRefs: ['9007199254740993123'], - evidenceRefs: [], - truncated: false, - }, - ], - }); - expect(fake.stored.find(r => r.id === deadEndId)?.kind).toBe('dead_end'); - }); - - test('produces bit-identical receipts, stored records, and read-backs across deterministic replays', async () => { - async function runReplay() { - const fake = createSharedFindingsFake(); - const trialLookup = createFakeTrialLookup(); - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createFileFindingTool({ - port: fake.writePort, - trialLookup: trialLookup.port, - newId: createFixedIdGenerator('rep').newId, - now: createFixedClock('2025-03-05T00:00:00.000Z', 30_000).now, - }), - createReadKnowledgeTool({ port: fake.knowledgePort }), - ], - }); - - const r1 = await callTool(server, 'file_finding', { - kind: 'finding', - title: 'Replay finding', - summary: 'Deterministic summary.', - trialRefs: ['trial-102', 'trial-101'], - evidenceRefs: ['ev-b', 'ev-a'], - idempotencyKey: 'rep-key-1', - }); - const r2 = await callTool(server, 'file_finding', { - kind: 'finding', - title: 'Replay finding', - summary: 'Deterministic summary.', - trialRefs: ['trial-101', 'trial-102'], - evidenceRefs: ['ev-a', 'ev-b'], - idempotencyKey: 'rep-key-1', - }); - const r3 = await callTool(server, 'read_knowledge', { - source: 'findings', - }); - return { - receipts: [r1.payload, r2.payload], - stored: fake.stored, - knowledge: r3.payload, - }; - } - - const firstRun = await runReplay(); - const secondRun = await runReplay(); - expect(secondRun).toEqual(firstRun); - }); - - test('validates factory options eagerly and keeps MCP symbols out of browser-safe root export', () => { - const validPort = createSharedFindingsFake().writePort; - const validLookup = createFakeTrialLookup().port; - const validNewId = () => 'id-1'; - const validNow = () => Date.UTC(2025, 2, 1); - - expect(() => createFileFindingTool(null as never)).toThrow(/options/i); - expect(() => - createFileFindingTool({ - port: {} as never, - trialLookup: validLookup, - newId: validNewId, - now: validNow, - }) - ).toThrow(/port/i); - expect(() => - createFileFindingTool({ - port: validPort, - trialLookup: {} as never, - newId: validNewId, - now: validNow, - }) - ).toThrow(/trialLookup/i); - expect(() => - createFileFindingTool({ - port: validPort, - trialLookup: validLookup, - newId: 'not-a-fn' as never, - now: validNow, - }) - ).toThrow(/newId/i); - expect(() => - createFileFindingTool({ - port: validPort, - trialLookup: validLookup, - newId: validNewId, - now: 'not-a-fn' as never, - }) - ).toThrow(/now/i); - - expect( - fileFindingInputSchema.safeParse({ - kind: 'finding', - title: 'Schema export sanity check', - summary: 'Direct schema parse works.', - trialRefs: ['trial-101'], - }).success - ).toBe(true); - - expect(Object.keys(rootResearchExports)).not.toContain('createFileFindingTool'); - }); -}); diff --git a/libs/research/test/mcp-library-cards.test.ts b/libs/research/test/mcp-library-cards.test.ts deleted file mode 100644 index ac6a35eb..00000000 --- a/libs/research/test/mcp-library-cards.test.ts +++ /dev/null @@ -1,933 +0,0 @@ -import { afterEach, describe, expect, test } from 'bun:test'; -import { mkdir, mkdtemp, rename, rm, symlink, unlink, writeFile } from 'node:fs/promises'; -import os from 'node:os'; -import path from 'node:path'; -import { - type KnowledgePort, - type LibraryCardDirEntry, - type LibraryCardDirHandle, - LibraryCardError, - type LibraryCardFs, - READ_KNOWLEDGE_MAX_TEXT_LENGTH, - type ReadKnowledgeResultPayload, - createLibraryCardReader, - createMcpServer, - createNodeLibraryCardFs, - createReadKnowledgeTool, -} from '../src/mcp/index'; - -const VIRTUAL_ROOT = '/virtual/quant-library'; - -const PIOTROSKI_CARD = `--- -verified: false -checked: 2026-03-15 -title: "Piotroski F-Score: Value, Quality (1976–2000)" -summary: "Nine-signal accounting screen: profitability, leverage, and operating efficiency." -excerpt: "Separates winners from value traps among high book-to-market equities." -matches: [" Value ", "Fundamental", "alphas", "value", "Quality"] -related: ["quant:alphas/novy-marx-gross-profitability"] -sources: ["https://doi.org/10.2307/2672906", "https://example.com/papers/f-score?year=2000&mode=full"] -confidence: high -topic: fundamental-value ---- - -# Piotroski F-Score - -Nine binary fundamental signals evaluated strictly point-in-time. -`; - -const MOMENTUM_CARD = `--- -verified: true -checked: 2026-03-10 -title: "Cross-Sectional Momentum (12-1)" -summary: "Twelve-month return skipping the most recent month." ---- - -Skipping the last month mitigates short-term reversal. -`; - -const LIVE_OPS_CARD = `--- -verified: false -checked: 2026-03-12 -title: "IBKR Margin & FX Rebalance Checklist" -summary: "Pre-trade checks for USD/CAD margin accounts." -matches: ["execution", "IBKR"] ---- - -Verify buying power and currency conversion buffers before routing. -`; - -const STANDARD_MANIFEST = `# Quant methodology library -id: quant -name: "Quant Research Library" -shelves: - - id: core - title: "Core reading" - nested: - ignored: true -sections: - live-ops: Live operations & execution - alphas: Signal & alpha research -`; - -interface FakeFsState { - readonly files: Map; - readonly dirs: Map; - readonly readPaths: string[]; - readonly listPaths: string[]; - readonly readErrors: Map; - readonly listErrors: Map; - readonly fs: LibraryCardFs; -} - -function makeEnoent(targetPath: string): NodeJS.ErrnoException { - const err = new Error(`ENOENT: no such file or directory, open '${targetPath}'`) as NodeJS.ErrnoException; - err.code = 'ENOENT'; - return err; -} - -function createFakeLibraryFs(init?: { - readonly files?: Readonly>; - readonly dirs?: Readonly>; -}): FakeFsState { - const files = new Map(); - const dirs = new Map(); - const readPaths: string[] = []; - const listPaths: string[] = []; - const readErrors = new Map(); - const listErrors = new Map(); - - if (init?.files !== undefined) { - for (const [relOrAbs, text] of Object.entries(init.files)) { - const full = path.isAbsolute(relOrAbs) ? relOrAbs : path.join(VIRTUAL_ROOT, relOrAbs); - files.set(full, text); - } - } - if (init?.dirs !== undefined) { - for (const [relOrAbs, entries] of Object.entries(init.dirs)) { - const full = relOrAbs === '' ? VIRTUAL_ROOT : path.isAbsolute(relOrAbs) ? relOrAbs : path.join(VIRTUAL_ROOT, relOrAbs); - dirs.set(full, [...entries]); - } - } - - const readFileByPath = async (filePath: string): Promise => { - readPaths.push(filePath); - const forcedErr = readErrors.get(filePath); - if (forcedErr !== undefined) { - throw forcedErr; - } - const text = files.get(filePath); - if (text === undefined) { - throw makeEnoent(filePath); - } - return text; - }; - - const listDirByPath = async (dirPath: string): Promise => { - listPaths.push(dirPath); - const forcedErr = listErrors.get(dirPath); - if (forcedErr !== undefined) { - throw forcedErr; - } - const entries = dirs.get(dirPath); - if (entries === undefined) { - throw makeEnoent(dirPath); - } - return [...entries]; - }; - - const createAnchoredFakeDirHandle = (dirPath: string): LibraryCardDirHandle => { - let closed = false; - const assertOpen = (): void => { - if (closed) { - throw new Error(`Directory handle already closed: ${dirPath}`); - } - }; - const assertChildName = (name: string): void => { - if ( - name.length === 0 || - name === '.' || - name === '..' || - name.includes('/') || - name.includes('\\') || - name.includes('\0') - ) { - throw new Error(`Invalid child name: ${name}`); - } - }; - return { - async listDir(): Promise { - assertOpen(); - return listDirByPath(dirPath); - }, - async openSubdir(name: string): Promise { - assertOpen(); - assertChildName(name); - const childPath = path.join(dirPath, name); - if (!dirs.has(childPath)) { - throw makeEnoent(childPath); - } - return createAnchoredFakeDirHandle(childPath); - }, - async readTextFile(name: string): Promise { - assertOpen(); - assertChildName(name); - return readFileByPath(path.join(dirPath, name)); - }, - async close(): Promise { - closed = true; - }, - }; - }; - - const fs: LibraryCardFs = { - readTextFile: readFileByPath, - listDir: listDirByPath, - async openDir(dirPath: string): Promise { - if (dirPath !== VIRTUAL_ROOT && !dirs.has(dirPath)) { - throw makeEnoent(dirPath); - } - return createAnchoredFakeDirHandle(dirPath); - }, - }; - - return { files, dirs, readPaths, listPaths, readErrors, listErrors, fs }; -} - -function createStandardFakeFs(): FakeFsState { - return createFakeLibraryFs({ - files: { - 'library.yml': STANDARD_MANIFEST, - 'cards/live-ops/ibkr-margin.md': LIVE_OPS_CARD, - 'cards/alphas/piotroski-f-score.md': PIOTROSKI_CARD, - 'cards/alphas/a-momentum.md': MOMENTUM_CARD, - }, - dirs: { - '': [ - { name: 'library.yml', isFile: true, isDirectory: false }, - { name: '_topics.yml', isFile: true, isDirectory: false }, - { name: 'rules', isFile: false, isDirectory: true }, - { name: 'cards', isFile: false, isDirectory: true }, - ], - cards: [ - { name: 'alphas', isFile: false, isDirectory: true }, - { name: 'live-ops', isFile: false, isDirectory: true }, - ], - 'cards/live-ops': [{ name: 'ibkr-margin.md', isFile: true, isDirectory: false }], - // Deliberately unsorted listing to verify code-unit slug sorting. - 'cards/alphas': [ - { name: 'piotroski-f-score.md', isFile: true, isDirectory: false }, - { name: 'a-momentum.md', isFile: true, isDirectory: false }, - ], - }, - }); -} - -async function expectLibraryCardError( - fn: () => Promise | unknown, - expectedCode: LibraryCardError['code'] -): Promise { - try { - await fn(); - } catch (err) { - expect(err).toBeInstanceOf(RangeError); - expect(err).toBeInstanceOf(LibraryCardError); - const typed = err as LibraryCardError; - expect(typed.code).toBe(expectedCode); - return typed; - } - throw new Error(`Expected LibraryCardError(${expectedCode}) to be thrown.`); -} - -const tempDirs: string[] = []; - -afterEach(async () => { - while (tempDirs.length > 0) { - const dir = tempDirs.pop(); - if (dir !== undefined) { - await rm(dir, { recursive: true, force: true }); - } - } -}); - -describe('MCP library-cards filesystem adapter', () => { - test('reads sections in manifest order, sorts slugs by code unit, normalizes tags, and preserves punctuation/Unicode and unverified cards', async () => { - const fake = createStandardFakeFs(); - const reader = createLibraryCardReader({ root: VIRTUAL_ROOT, fs: fake.fs }); - - const cards = await reader.listLibraryCards({}); - - expect(cards.map(c => c.id)).toEqual([ - 'quant:live-ops/ibkr-margin', - 'quant:alphas/a-momentum', - 'quant:alphas/piotroski-f-score', - ]); - - expect(cards[0]).toEqual({ - id: 'quant:live-ops/ibkr-margin', - title: 'IBKR Margin & FX Rebalance Checklist', - tags: ['live-ops', 'execution', 'ibkr'], - summary: 'Pre-trade checks for USD/CAD margin accounts.', - body: 'Verify buying power and currency conversion buffers before routing.', - }); - - // Missing matches falls back to [sectionId]. - expect(cards[1]).toEqual({ - id: 'quant:alphas/a-momentum', - title: 'Cross-Sectional Momentum (12-1)', - tags: ['alphas'], - summary: 'Twelve-month return skipping the most recent month.', - body: 'Skipping the last month mitigates short-term reversal.', - }); - - // Quoted punctuation (:, ,, (), en-dash), URL array, deduplicated tags in first-seen order, verified: false included. - expect(cards[2]).toEqual({ - id: 'quant:alphas/piotroski-f-score', - title: 'Piotroski F-Score: Value, Quality (1976–2000)', - tags: ['alphas', 'value', 'fundamental', 'quality'], - summary: 'Nine-signal accounting screen: profitability, leverage, and operating efficiency.', - body: '# Piotroski F-Score\n\nNine binary fundamental signals evaluated strictly point-in-time.', - }); - }); - - test('supports exact case-sensitive q.id narrowing and blocks traversal/unknown IDs with zero card reads', async () => { - const fake = createStandardFakeFs(); - const reader = createLibraryCardReader({ root: VIRTUAL_ROOT, fs: fake.fs }); - const manifestPath = path.join(VIRTUAL_ROOT, 'library.yml'); - const piotroskiPath = path.join(VIRTUAL_ROOT, 'cards/alphas/piotroski-f-score.md'); - - // Exact hit reads library.yml and only the target card. - const hit = await reader.listLibraryCards({ id: 'quant:alphas/piotroski-f-score' }); - expect(hit).toHaveLength(1); - expect(hit[0]?.id).toBe('quant:alphas/piotroski-f-score'); - expect(fake.readPaths).toEqual([manifestPath, piotroskiPath]); - - // Misses and traversal attempts must return frozen [] and read no card files. - const missIds = [ - 'QUANT:alphas/piotroski-f-score', - 'quant:Alphas/piotroski-f-score', - 'quant:alphas/Piotroski-f-score', - 'quant:unknown-section/piotroski-f-score', - 'quant:alphas/does-not-exist', - 'quant:../x', - 'quant:alphas/../../library', - '/etc/passwd', - 'quant:alphas/sub/nested', - '', - ]; - - for (const id of missIds) { - fake.readPaths.length = 0; - const result = await reader.listLibraryCards({ id }); - expect(result).toEqual([]); - expect(Object.isFrozen(result)).toBe(true); - expect(fake.readPaths).toEqual([manifestPath]); - for (const readPath of fake.readPaths) { - expect(readPath === manifestPath || readPath.startsWith(`${VIRTUAL_ROOT}/cards/`)).toBe( - true - ); - } - } - }); - - test('skips dotfiles, non-.md files, nested dirs, symlinks, undeclared sections, invalid slugs, invalid section IDs, and missing section dirs', async () => { - const fake = createFakeLibraryFs({ - files: { - 'library.yml': `id: quant -sections: - alphas: Alphas - -draft: Draft notes - .archived: Archived notes - old signals: Archived signals - Bad_Section: Invalid section name - empty-section: Declared section with no directory -`, - 'cards/alphas/valid-card.md': MOMENTUM_CARD, - 'cards/alphas/.hidden.md': MOMENTUM_CARD, - 'cards/alphas/README.txt': 'ignored', - 'cards/alphas/UpperCase.md': MOMENTUM_CARD, - 'cards/alphas/symlink-card.md': MOMENTUM_CARD, - 'cards/undeclared/secret.md': MOMENTUM_CARD, - 'cards/-draft/valid-card.md': MOMENTUM_CARD, - 'cards/old signals/valid-card.md': MOMENTUM_CARD, - 'cards/Bad_Section/valid-card.md': MOMENTUM_CARD, - }, - dirs: { - '': [ - { name: 'library.yml', isFile: true, isDirectory: false }, - { name: 'cards', isFile: false, isDirectory: true }, - ], - cards: [ - { name: 'alphas', isFile: false, isDirectory: true }, - { name: 'undeclared', isFile: false, isDirectory: true }, - { name: '-draft', isFile: false, isDirectory: true }, - { name: 'old signals', isFile: false, isDirectory: true }, - { name: 'Bad_Section', isFile: false, isDirectory: true }, - { name: 'symlink-section', isFile: false, isDirectory: false }, - ], - 'cards/alphas': [ - { name: '.hidden.md', isFile: true, isDirectory: false }, - { name: 'README.txt', isFile: true, isDirectory: false }, - { name: 'nested.md', isFile: false, isDirectory: true }, - { name: 'symlink-card.md', isFile: false, isDirectory: false }, - { name: 'UpperCase.md', isFile: true, isDirectory: false }, - { name: 'valid-card.md', isFile: true, isDirectory: false }, - ], - 'cards/old signals': [{ name: 'valid-card.md', isFile: true, isDirectory: false }], - }, - }); - - const reader = createLibraryCardReader({ root: VIRTUAL_ROOT, fs: fake.fs }); - const cards = await reader.listLibraryCards({}); - - expect(cards.map(c => c.id)).toEqual(['quant:alphas/valid-card']); - expect(fake.readPaths).toEqual([ - path.join(VIRTUAL_ROOT, 'library.yml'), - path.join(VIRTUAL_ROOT, 'cards/alphas/valid-card.md'), - ]); - }); - - test('validates constructor options synchronously and fails closed on invalid manifest and I/O errors', async () => { - const fake = createStandardFakeFs(); - - await expectLibraryCardError( - () => createLibraryCardReader(null as unknown as { root: string; fs: LibraryCardFs }), - 'INVALID_ROOT' - ); - await expectLibraryCardError( - () => createLibraryCardReader({ root: ' ', fs: fake.fs }), - 'INVALID_ROOT' - ); - await expectLibraryCardError( - () => createLibraryCardReader({ root: '/tmp/bad\0path', fs: fake.fs }), - 'INVALID_ROOT' - ); - await expectLibraryCardError( - () => createLibraryCardReader({ root: VIRTUAL_ROOT, fs: null as unknown as LibraryCardFs }), - 'INVALID_FS' - ); - await expectLibraryCardError( - () => - createLibraryCardReader({ - root: VIRTUAL_ROOT, - fs: { readTextFile: fake.fs.readTextFile } as unknown as LibraryCardFs, - }), - 'INVALID_FS' - ); - // A two-method wrapper omitting anchored openDir must fail closed at construction. - const nodeFs = createNodeLibraryCardFs(); - await expectLibraryCardError( - () => - createLibraryCardReader({ - root: VIRTUAL_ROOT, - fs: { - readTextFile: p => nodeFs.readTextFile(p), - listDir: p => nodeFs.listDir(p), - } as unknown as LibraryCardFs, - }), - 'INVALID_FS' - ); - - // Zero I/O happened during invalid option checks. - expect(fake.readPaths).toHaveLength(0); - expect(fake.listPaths).toHaveLength(0); - - // Missing library.yml - const missingManifestFs = createFakeLibraryFs({}); - const missingReader = createLibraryCardReader({ root: VIRTUAL_ROOT, fs: missingManifestFs.fs }); - await expectLibraryCardError(() => missingReader.listLibraryCards({}), 'INVALID_LIBRARY'); - - // Malformed library.yml variants - const badManifests: readonly string[] = [ - 'sections:\n alphas: Alphas\n', // missing id - 'id:\nsections:\n alphas: Alphas\n', // empty id - 'id: quant\nname: Only name\n', // missing sections - 'id: quant\nsections:\n', // empty sections - 'id: quant\nid: quant2\nsections:\n alphas: Alphas\n', // duplicate id - 'id: quant\nsections:\n alphas: A\nsections:\n beta: B\n', // duplicate sections - 'id: quant\nsections:\n alphas: A\n alphas: B\n', // duplicate section key - 'id: quant\nsections: []\n', // non-map sections - 'id: quant\nsections:\n - alphas: Alphas\n', // YAML sequence under sections - 'id: quant\nsections:\n - alphas\n', // YAML bare sequence under sections - 'id: quant\nsections:\n alphas: # comment-only title\n', // comment-only title - 'id: quant\nsections:\n alphas:NoSpace\n', // missing space after colon - ]; - - for (const manifest of badManifests) { - const f = createFakeLibraryFs({ files: { 'library.yml': manifest } }); - const r = createLibraryCardReader({ root: VIRTUAL_ROOT, fs: f.fs }); - await expectLibraryCardError(() => r.listLibraryCards({}), 'INVALID_LIBRARY'); - } - - // Permission / generic I/O failure on listDir and card readTextFile - const ioFake = createStandardFakeFs(); - const eacces = Object.assign(new Error('EACCES: permission denied /secret/path'), { - code: 'EACCES', - }); - ioFake.listErrors.set(path.join(VIRTUAL_ROOT, 'cards/alphas'), eacces); - const ioReader = createLibraryCardReader({ root: VIRTUAL_ROOT, fs: ioFake.fs }); - const listErr = await expectLibraryCardError( - () => ioReader.listLibraryCards({}), - 'INVALID_LIBRARY' - ); - expect(listErr.message).not.toContain('/secret/path'); - - ioFake.listErrors.clear(); - ioFake.readErrors.set( - path.join(VIRTUAL_ROOT, 'cards/alphas/a-momentum.md'), - new Error('EIO: raw disk failure secret-bytes') - ); - const readErr = await expectLibraryCardError( - () => ioReader.listLibraryCards({}), - 'INVALID_CARD' - ); - expect(readErr.message).toContain('cards/alphas/a-momentum.md'); - expect(readErr.message).not.toContain('secret-bytes'); - }); - - test('fails closed on malformed cards and duplicate card IDs, naming relative path without leaking card content', async () => { - const SECRET_MARKER = 'CONFIDENTIAL_CARD_BODY_MARKER_99123'; - - const badCards: readonly { readonly label: string; readonly content: string }[] = [ - { - label: 'missing opening delimiter', - content: `title: "T"\nsummary: "S"\n---\n${SECRET_MARKER}`, - }, - { - label: 'missing closing delimiter', - content: `---\ntitle: "T"\nsummary: "S"\n${SECRET_MARKER}`, - }, - { - label: 'missing title', - content: `---\nsummary: "S"\n---\n${SECRET_MARKER}`, - }, - { - label: 'blank title', - content: `---\ntitle: " "\nsummary: "S"\n---\n${SECRET_MARKER}`, - }, - { - label: 'missing summary', - content: `---\ntitle: "T"\n---\n${SECRET_MARKER}`, - }, - { - label: 'blank summary', - content: `---\ntitle: "T"\nsummary: ""\n---\n${SECRET_MARKER}`, - }, - { - label: 'unterminated double quote', - content: `---\ntitle: "Unterminated ${SECRET_MARKER}\nsummary: "S"\n---\n${SECRET_MARKER}`, - }, - { - label: 'single-quoted value', - content: `---\ntitle: 'Single ${SECRET_MARKER}'\nsummary: "S"\n---\n${SECRET_MARKER}`, - }, - { - label: 'multiline block scalar', - content: `---\ntitle: "T"\nsummary: |\n ${SECRET_MARKER}\n---\n${SECRET_MARKER}`, - }, - { - label: 'indented continuation', - content: `---\ntitle: "T"\n ${SECRET_MARKER}\nsummary: "S"\n---\n${SECRET_MARKER}`, - }, - { - label: 'invalid matches non-array', - content: `---\ntitle: "T"\nsummary: "S"\nmatches: "${SECRET_MARKER}"\n---\n${SECRET_MARKER}`, - }, - { - label: 'invalid matches non-string item', - content: `---\ntitle: "T"\nsummary: "S"\nmatches: ["ok", 42]\n---\n${SECRET_MARKER}`, - }, - { - label: 'duplicate key', - content: `---\ntitle: "First"\ntitle: "Second ${SECRET_MARKER}"\nsummary: "S"\n---\n${SECRET_MARKER}`, - }, - { - label: 'comment-only summary', - content: `---\ntitle: "T"\nsummary: # Fill in after review ${SECRET_MARKER}\n---\n${SECRET_MARKER}`, - }, - { - label: 'comment-only title', - content: `---\ntitle: # Draft title ${SECRET_MARKER}\nsummary: "S"\n---\n${SECRET_MARKER}`, - }, - ]; - - for (const tc of badCards) { - const fake = createFakeLibraryFs({ - files: { - 'library.yml': STANDARD_MANIFEST, - 'cards/alphas/broken-card.md': tc.content, - }, - dirs: { - '': [{ name: 'cards', isFile: false, isDirectory: true }], - cards: [{ name: 'alphas', isFile: false, isDirectory: true }], - 'cards/alphas': [{ name: 'broken-card.md', isFile: true, isDirectory: false }], - }, - }); - const reader = createLibraryCardReader({ root: VIRTUAL_ROOT, fs: fake.fs }); - const err = await expectLibraryCardError(() => reader.listLibraryCards({}), 'INVALID_CARD'); - expect(err.message).toContain('cards/alphas/broken-card.md'); - expect(err.message).not.toContain(SECRET_MARKER); - } - - // Duplicate card ID via duplicate directory entries (both broad scan and exact ID lookup). - const dupFake = createFakeLibraryFs({ - files: { - 'library.yml': STANDARD_MANIFEST, - 'cards/alphas/dup-card.md': `---\ntitle: "Dup"\nsummary: "Summary"\n---\n${SECRET_MARKER}`, - }, - dirs: { - '': [{ name: 'cards', isFile: false, isDirectory: true }], - cards: [{ name: 'alphas', isFile: false, isDirectory: true }], - 'cards/alphas': [ - { name: 'dup-card.md', isFile: true, isDirectory: false }, - { name: 'dup-card.md', isFile: true, isDirectory: false }, - ], - }, - }); - const dupReader = createLibraryCardReader({ root: VIRTUAL_ROOT, fs: dupFake.fs }); - const broadDupErr = await expectLibraryCardError( - () => dupReader.listLibraryCards({}), - 'INVALID_CARD' - ); - expect(broadDupErr.message).toContain('cards/alphas/dup-card.md'); - expect(broadDupErr.message).not.toContain(SECRET_MARKER); - - const exactDupErr = await expectLibraryCardError( - () => dupReader.listLibraryCards({ id: 'quant:alphas/dup-card' }), - 'INVALID_CARD' - ); - expect(exactDupErr.message).toContain('cards/alphas/dup-card.md'); - expect(exactDupErr.message).not.toContain(SECRET_MARKER); - }); - - test('integrates end-to-end with createReadKnowledgeTool while adapter returns all candidates untruncated', async () => { - const longBody = 'A'.repeat(READ_KNOWLEDGE_MAX_TEXT_LENGTH + 250); - const fake = createStandardFakeFs(); - fake.files.set( - path.join(VIRTUAL_ROOT, 'cards/alphas/piotroski-f-score.md'), - `--- -verified: false -title: "Piotroski F-Score: Value, Quality (1976–2000)" -summary: "Nine-signal accounting screen: profitability, leverage, and operating efficiency." -matches: ["Value", "Quality"] ---- - -${longBody} -` - ); - - const libraryReader = createLibraryCardReader({ root: VIRTUAL_ROOT, fs: fake.fs }); - - // Adapter itself ignores query/tags and does not truncate body text. - const rawCandidates = await libraryReader.listLibraryCards({ - query: 'piotroski', - tags: ['VALUE'], - }); - expect(rawCandidates).toHaveLength(3); - const rawPiotroski = rawCandidates.find(c => c.id === 'quant:alphas/piotroski-f-score'); - expect(rawPiotroski?.body.length).toBe(READ_KNOWLEDGE_MAX_TEXT_LENGTH + 250); - - // Real read_knowledge tool filters by mixed-case tags + query and truncates long body. - const port: KnowledgePort = { - ...libraryReader, - async listFindings() { - return []; - }, - async listProviderCaveats() { - return []; - }, - }; - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [createReadKnowledgeTool({ port })], - }); - - const rawResponse = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 'lib-e2e-1', - method: 'tools/call', - params: { - name: 'read_knowledge', - arguments: { - source: 'library', - tags: ['VALUE', 'Alphas'], - query: 'piotroski', - }, - }, - }) - ); - - expect(rawResponse).not.toBeNull(); - const parsed = JSON.parse(rawResponse as string) as { - result: { isError?: boolean; content: { type: string; text: string }[] }; - }; - expect(parsed.result.isError).toBeUndefined(); - const payload = JSON.parse(parsed.result.content[0]?.text ?? '') as ReadKnowledgeResultPayload; - expect(payload.rowCount).toBe(1); - expect(payload.sources).toEqual({ library: 1, findings: 0, provider_caveats: 0 }); - expect(payload.rows[0]).toEqual({ - source: 'library', - id: 'quant:alphas/piotroski-f-score', - title: 'Piotroski F-Score: Value, Quality (1976–2000)', - tags: ['alphas', 'value', 'quality'], - summary: 'Nine-signal accounting screen: profitability, leverage, and operating efficiency.', - body: 'A'.repeat(READ_KNOWLEDGE_MAX_TEXT_LENGTH), - truncated: true, - }); - }); - - test('reads fresh on every call and returns frozen result arrays, records, and tag arrays', async () => { - const fake = createStandardFakeFs(); - const reader = createLibraryCardReader({ root: VIRTUAL_ROOT, fs: fake.fs }); - - const first = await reader.listLibraryCards({}); - expect(Object.isFrozen(first)).toBe(true); - for (const card of first) { - expect(Object.isFrozen(card)).toBe(true); - expect(Object.isFrozen(card.tags)).toBe(true); - } - expect(first.find(c => c.id === 'quant:alphas/a-momentum')?.title).toBe( - 'Cross-Sectional Momentum (12-1)' - ); - - // Mutate card and manifest in the fake between calls. - fake.files.set( - path.join(VIRTUAL_ROOT, 'cards/alphas/a-momentum.md'), - `--- -title: "Updated Momentum Title" -summary: "Updated summary." -matches: ["updated-tag"] ---- - -Updated body. -` - ); - fake.files.set( - path.join(VIRTUAL_ROOT, 'library.yml'), - `id: quant-v2 -sections: - alphas: Alphas only -` - ); - - const second = await reader.listLibraryCards({}); - expect(second.map(c => c.id)).toEqual([ - 'quant-v2:alphas/a-momentum', - 'quant-v2:alphas/piotroski-f-score', - ]); - expect(second[0]).toEqual({ - id: 'quant-v2:alphas/a-momentum', - title: 'Updated Momentum Title', - tags: ['alphas', 'updated-tag'], - summary: 'Updated summary.', - body: 'Updated body.', - }); - expect(Object.isFrozen(second)).toBe(true); - expect(Object.isFrozen(second[0])).toBe(true); - expect(Object.isFrozen(second[0]?.tags)).toBe(true); - }); - - test('createNodeLibraryCardFs reads real temp fixtures and never follows symlinked files, sections, or manifests', async () => { - const tempBase = await mkdtemp(path.join(os.tmpdir(), 'stock-bot-library-cards-')); - tempDirs.push(tempBase); - - const libRoot = path.join(tempBase, 'library'); - const siblingDir = path.join(tempBase, 'sibling-outside-library'); - const siblingFile = path.join(siblingDir, 'leaked.md'); - - await mkdir(path.join(libRoot, 'cards', 'alphas'), { recursive: true }); - await mkdir(siblingDir, { recursive: true }); - - await writeFile( - path.join(libRoot, 'library.yml'), - `id: quant -sections: - alphas: Signal & alpha research - linked-section: Symlinked section -`, - 'utf8' - ); - await writeFile(path.join(libRoot, 'cards', 'alphas', 'piotroski-f-score.md'), PIOTROSKI_CARD, 'utf8'); - await writeFile( - siblingFile, - `--- -title: "Leaked Sibling Card" -summary: "Must never be read via symlink." ---- - -LEAKED_SIBLING_CONTENT -`, - 'utf8' - ); - - // Create symlinked file inside cards/alphas and symlinked section directory inside cards/. - await symlink(siblingFile, path.join(libRoot, 'cards', 'alphas', 'linked-card.md')); - await symlink(siblingDir, path.join(libRoot, 'cards', 'linked-section')); - - const nodeFs = createNodeLibraryCardFs(); - const reader = createLibraryCardReader({ root: libRoot, fs: nodeFs }); - - const cards = await reader.listLibraryCards({}); - expect(cards).toHaveLength(1); - expect(cards[0]?.id).toBe('quant:alphas/piotroski-f-score'); - - // Exact-ID lookups targeting symlinked file or symlinked section return empty without reading. - expect(await reader.listLibraryCards({ id: 'quant:alphas/linked-card' })).toEqual([]); - expect(await reader.listLibraryCards({ id: 'quant:linked-section/leaked' })).toEqual([]); - - // Direct symlinked library.yml must fail closed via O_NOFOLLOW. - const symlinkManifestRoot = path.join(tempBase, 'symlink-manifest-lib'); - await mkdir(symlinkManifestRoot, { recursive: true }); - await symlink(path.join(libRoot, 'library.yml'), path.join(symlinkManifestRoot, 'library.yml')); - const symlinkManifestReader = createLibraryCardReader({ - root: symlinkManifestRoot, - fs: nodeFs, - }); - await expectLibraryCardError( - () => symlinkManifestReader.listLibraryCards({}), - 'INVALID_LIBRARY' - ); - }); - - test('anchors directory listings and reads to open handles to block directory-symlink TOCTOU races', async () => { - const tempBase = await mkdtemp(path.join(os.tmpdir(), 'stock-bot-library-toctou-')); - tempDirs.push(tempBase); - - const libRoot = path.join(tempBase, 'library'); - const alphasDir = path.join(libRoot, 'cards', 'alphas'); - const outsideDir = path.join(tempBase, 'outside-corpus'); - const LEAK_MARKER = 'OUTSIDE_CORPUS_TOCTOU_LEAK_7741'; - - await mkdir(alphasDir, { recursive: true }); - await mkdir(outsideDir, { recursive: true }); - - await writeFile( - path.join(libRoot, 'library.yml'), - `id: quant\nsections:\n alphas: Signal & alpha research\n`, - 'utf8' - ); - await writeFile(path.join(alphasDir, 'piotroski-f-score.md'), PIOTROSKI_CARD, 'utf8'); - await writeFile( - path.join(outsideDir, 'piotroski-f-score.md'), - `---\ntitle: "Leaked Card"\nsummary: "Leaked summary"\n---\n\n${LEAK_MARKER}\n`, - 'utf8' - ); - - const baseNodeFs = createNodeLibraryCardFs(); - expect(typeof baseNodeFs.openDir).toBe('function'); - - // Race A: cards/alphas is replaced with a symlink after cards/ is listed, before opening alphas. - let raceATriggered = false; - const raceAFs: LibraryCardFs = { - readTextFile: p => baseNodeFs.readTextFile(p), - listDir: p => baseNodeFs.listDir(p), - async openDir(dirPath: string): Promise { - const rootHandle = await baseNodeFs.openDir(dirPath); - return { - listDir: () => rootHandle.listDir(), - readTextFile: name => rootHandle.readTextFile(name), - close: () => rootHandle.close(), - async openSubdir(name: string): Promise { - const sub = await rootHandle.openSubdir(name); - if (name !== 'cards') { - return sub; - } - return { - async listDir(): Promise { - const entries = await sub.listDir(); - if (!raceATriggered) { - raceATriggered = true; - await rename(alphasDir, path.join(libRoot, 'cards', 'alphas-moved-a')); - await symlink(outsideDir, alphasDir); - } - return entries; - }, - openSubdir: child => sub.openSubdir(child), - readTextFile: child => sub.readTextFile(child), - close: () => sub.close(), - }; - }, - }; - }, - }; - - const raceAReader = createLibraryCardReader({ root: libRoot, fs: raceAFs }); - const raceAErr = await expectLibraryCardError( - () => raceAReader.listLibraryCards({}), - 'INVALID_LIBRARY' - ); - expect(raceATriggered).toBe(true); - expect(raceAErr.message).not.toContain(LEAK_MARKER); - - // Restore alphas directory for Race B. - await unlink(alphasDir); - await rename(path.join(libRoot, 'cards', 'alphas-moved-a'), alphasDir); - - // Race B: cards/alphas is replaced with a symlink after alphas is opened and listed, before reading the card. - let raceBTriggered = false; - const raceBFs: LibraryCardFs = { - readTextFile: p => baseNodeFs.readTextFile(p), - listDir: p => baseNodeFs.listDir(p), - async openDir(dirPath: string): Promise { - const rootHandle = await baseNodeFs.openDir(dirPath); - return { - listDir: () => rootHandle.listDir(), - readTextFile: name => rootHandle.readTextFile(name), - close: () => rootHandle.close(), - async openSubdir(name: string): Promise { - const cardsHandle = await rootHandle.openSubdir(name); - if (name !== 'cards') { - return cardsHandle; - } - return { - listDir: () => cardsHandle.listDir(), - readTextFile: child => cardsHandle.readTextFile(child), - close: () => cardsHandle.close(), - async openSubdir(sectionName: string): Promise { - const sectionHandle = await cardsHandle.openSubdir(sectionName); - return { - async listDir(): Promise { - const entries = await sectionHandle.listDir(); - if (!raceBTriggered && sectionName === 'alphas') { - raceBTriggered = true; - await rename(alphasDir, path.join(libRoot, 'cards', 'alphas-moved-b')); - await symlink(outsideDir, alphasDir); - } - return entries; - }, - openSubdir: child => sectionHandle.openSubdir(child), - readTextFile: child => sectionHandle.readTextFile(child), - close: () => sectionHandle.close(), - }; - }, - }; - }, - }; - }, - }; - - const raceBReader = createLibraryCardReader({ root: libRoot, fs: raceBFs }); - const anchoredCards = await raceBReader.listLibraryCards({}); - expect(raceBTriggered).toBe(true); - expect(anchoredCards).toHaveLength(1); - expect(anchoredCards[0]?.id).toBe('quant:alphas/piotroski-f-score'); - expect(anchoredCards[0]?.body).not.toContain(LEAK_MARKER); - expect(anchoredCards[0]?.body).toContain('Piotroski F-Score'); - - // Unsupported boundary enforcement on openDir fails closed with INVALID_LIBRARY. - const unsupportedFs: LibraryCardFs = { - readTextFile: p => baseNodeFs.readTextFile(p), - listDir: p => baseNodeFs.listDir(p), - async openDir(): Promise { - throw new Error('Anchored no-follow directory operations are not supported.'); - }, - }; - const unsupportedReader = createLibraryCardReader({ root: libRoot, fs: unsupportedFs }); - await expectLibraryCardError( - () => unsupportedReader.listLibraryCards({}), - 'INVALID_LIBRARY' - ); - }); -}); diff --git a/libs/research/test/mcp-postgres-copilot.test.ts b/libs/research/test/mcp-postgres-copilot.test.ts deleted file mode 100644 index cdb0d3d8..00000000 --- a/libs/research/test/mcp-postgres-copilot.test.ts +++ /dev/null @@ -1,1139 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { - type BarBatch, - type BarRecord, - type EventKind, - type MarketDataStore, - type Table, - type TableRow, -} from '../src/market-data-store'; -import { - EVENTS_COLUMNS, - MarketDataStoreNotImplementedError, -} from '../src/market-data-store-duckdb'; -import { - type EventStudyResultPayload, - type FileFindingResultPayload, - type KnowledgePort, - type LibraryCardQuery, - type LibraryCardRecord, - type ListingCalendarExecutor, - type McpServer, - type PostgresFindingsExecutor, - type PostgresResearchCopilotExecutor, - type PostgresResearchCopilotServerOptions, - RESEARCH_COPILOT_TOOL_NAMES, - type ReadKnowledgeResultPayload, - type SearchSymbolsResultPayload, - type SessionDatesPort, - type SessionDatesQuery, - type SymbolSearchExecutor, - type TrialRefExecutor, - createPostgresResearchCopilotServer, -} from '../src/mcp/index'; -import type { TrialLedgerExecutor } from '../src/trial-ledger'; - -// Synthetic PostgreSQL copilot composition fixture metadata (pinned for reproducibility): -// - Dataset ID: `synthetic:mcp-postgres-copilot:seed-20261202:v1` -// - Seed: `20261202` (Mulberry32 PRNG) -// - Universe: 8 synthetic US equity listings (`60001..60008`, XNYS, USD, 21:00 UTC close) -// - Sessions: 40 pre-cutoff + 5 post-cutoff business sessions starting `2023-01-03` -// - Cutoff: `vaultCutoffDate` = `allDates[40]` (`vaultCutoffTs = Date.UTC(..., 0, 0, 0)`) -// - Economic assumptions: daily raw close-to-close returns, equal-weight benchmark over -// eligible listing returns, zero modeled execution/transaction costs. -// - Ownership: Quant research role owns the study assumptions; `AGENT_PRINCIPAL` owns -// recorded `trial_ledger` rows. -const FIXTURE_DATASET_ID = 'synthetic:mcp-postgres-copilot:seed-20261202:v1'; -const SEED = 20261202; -const SERVER_NAME = 'stock-bot-pg-copilot'; -const SERVER_VERSION = '0.1.0'; -const AGENT_PRINCIPAL = 'agent:22222222-3333-4444-8555-666666666666'; -const FIXED_FINDING_ID = 'finding-pg-copilot-001'; -const FIXED_NOW_ISO = '2024-06-15T12:00:00.000Z'; -const FIXED_NOW_MS = Date.parse(FIXED_NOW_ISO); - -// Compile-time assertions: -// 1) PostgresResearchCopilotExecutor is assignable to all five existing executor interfaces without casts. -function _assertExecutorAssignability(executor: PostgresResearchCopilotExecutor) { - const asSymbolSearch: SymbolSearchExecutor = executor; - const asTrialRef: TrialRefExecutor = executor; - const asFindings: PostgresFindingsExecutor = executor; - const asListingCalendar: ListingCalendarExecutor = executor; - const asTrialLedger: TrialLedgerExecutor = executor; - return [asSymbolSearch, asTrialRef, asFindings, asListingCalendar, asTrialLedger] as const; -} -void _assertExecutorAssignability; - -// 2) PostgresResearchCopilotServerOptions has no separate `vaultCutoffTs` key. -type HasSeparateVaultCutoffTs = 'vaultCutoffTs' extends keyof PostgresResearchCopilotServerOptions - ? true - : false; -const _noSeparateVaultCutoffTs: HasSeparateVaultCutoffTs = false; -void _noSeparateVaultCutoffTs; - -interface RecordedSqlCall { - readonly text: string; - readonly params: readonly unknown[] | undefined; -} - -interface StoredTrialRow { - readonly trial_id: string; - readonly created_at: Date; - readonly principal_id: string; - readonly campaign_id: string | null; - readonly stage: string; - readonly universe_market: string; - readonly horizon_bucket: string; - readonly hypothesis_id: string | null; - readonly expression_hash: string; - readonly sample_start: string; - readonly sample_end: string; - readonly n_obs: number; - readonly sharpe_unann: number; - readonly skewness: number; - readonly kurtosis: number; - readonly daily_series: readonly number[]; -} - -interface JsonRpcResponseEnvelope { - readonly jsonrpc: '2.0'; - readonly id: number | string | null; - readonly result?: unknown; - readonly error?: { - readonly code: number; - readonly message: string; - }; -} - -interface ToolCallEnvelope { - readonly content: readonly { readonly type: 'text'; readonly text: string }[]; - readonly isError?: boolean; -} - -function createSeededRng(seed: number): () => number { - let state = seed >>> 0; - return () => { - state = (state + 0x6d2b79f5) >>> 0; - let t = Math.imul(state ^ (state >>> 15), 1 | state); - t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; - return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296; - }; -} - -function makeBusinessDates(startDate: string, count: number): string[] { - const out: string[] = new Array(count); - const current = new Date(`${startDate}T00:00:00.000Z`); - let written = 0; - while (written < count) { - const day = current.getUTCDay(); - if (day !== 0 && day !== 6) { - out[written] = current.toISOString().slice(0, 10); - written += 1; - } - current.setUTCDate(current.getUTCDate() + 1); - } - return out; -} - -function makeUtcMs(date: string, hourUtc: number, minuteUtc = 0): number { - const [y, m, d] = date.split('-').map(Number); - return Date.UTC(y!, m! - 1, d!, hourUtc, minuteUtc, 0, 0); -} - -function parseBoundMs(raw: string, endOfDay: boolean): number { - if (raw.length === 10) { - return Date.parse(`${raw}T${endOfDay ? '23:59:59.999' : '00:00:00.000'}Z`); - } - return Date.parse(raw); -} - -interface EventStudyFixture { - readonly listingIds: readonly number[]; - readonly allDates: readonly string[]; - readonly preCutoffDates: readonly string[]; - readonly firstDate: string; - readonly lastPreCutoffDate: string; - readonly vaultCutoffDate: string; - readonly vaultCutoffTs: number; - readonly bars: readonly BarRecord[]; - readonly eventsTable: Table; -} - -function buildEventStudyFixture(): EventStudyFixture { - const rand = createSeededRng(SEED); - const listingCount = 8; - const preCutoffSessions = 40; - const postCutoffSessions = 5; - - const allDates = makeBusinessDates('2023-01-03', preCutoffSessions + postCutoffSessions); - const preCutoffDates = allDates.slice(0, preCutoffSessions); - const firstDate = allDates[0]!; - const lastPreCutoffDate = allDates[preCutoffSessions - 1]!; - const vaultCutoffDate = allDates[preCutoffSessions]!; - const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0); - - const listingIds = Array.from({ length: listingCount }, (_, i) => 60_001 + i); - const bars: BarRecord[] = []; - const eventRows: TableRow[] = []; - - const eventDayIndices = [8, 14, 20, 26, 32]; - const eventSet = new Set(); - for (let eIdx = 0; eIdx < eventDayIndices.length; eIdx += 1) { - const t = eventDayIndices[eIdx]!; - const date = allDates[t]!; - const ts = makeUtcMs(date, 14); // 09:00 ET intraday filing - for (let k = 0; k < 2; k += 1) { - const l = (eIdx * 2 + k) % listingCount; - eventSet.add(`${t}:${l}`); - const kind: EventKind = 'filing'; - eventRows.push({ - listing_id: listingIds[l]!, - ts, - known_at: ts, - known_at_source: 'exact', - kind, - subtype: '8-K', - payload_json: '{}', - }); - } - } - - const prices = new Float64Array(listingCount); - for (let l = 0; l < listingCount; l += 1) { - prices[l] = 20 + l * 3; - } - - for (let t = 0; t < allDates.length; t += 1) { - const date = allDates[t]!; - const closeTs = makeUtcMs(date, 21); // 16:00 ET close - for (let l = 0; l < listingCount; l += 1) { - let drift = 0; - for (let offset = 0; offset <= 2; offset += 1) { - if (eventSet.has(`${t - offset}:${l}`)) { - drift += 0.008 * (1 + ((l + t) % 3) * 0.2); - } - } - const ret = drift + (rand() * 2 - 1) * 0.01; - prices[l] = Math.max(1.0, prices[l]! * (1 + ret)); - const close = Number(prices[l]!.toFixed(4)); - bars.push({ - listingId: listingIds[l]!, - ts: closeTs, - open: Number((close * 0.995).toFixed(4)), - high: Number((close * 1.01).toFixed(4)), - low: Number((close * 0.99).toFixed(4)), - close, - volume: 100_000 + l * 1_000 + t * 50, - vwap: close, - knownAt: closeTs, - }); - } - } - - return { - listingIds, - allDates, - preCutoffDates, - firstDate, - lastPreCutoffDate, - vaultCutoffDate, - vaultCutoffTs, - bars, - eventsTable: { - columns: [...EVENTS_COLUMNS], - rows: eventRows, - }, - }; -} - -function createFakeMarketDataStore(fixture: EventStudyFixture): MarketDataStore { - return { - bars(q): AsyncIterable { - const idSet = new Set(q.listingIds); - const fromMs = parseBoundMs(q.from, false); - const toMs = parseBoundMs(q.to, true); - const asOfMs = q.asOf !== undefined ? parseBoundMs(q.asOf, true) : Number.POSITIVE_INFINITY; - const filtered = fixture.bars.filter( - row => - idSet.has(row.listingId) && - row.ts >= fromMs && - row.ts <= toMs && - row.knownAt <= asOfMs - ); - return { - async *[Symbol.asyncIterator]() { - yield { rows: filtered }; - }, - }; - }, - async universe() { - return [...fixture.listingIds]; - }, - async events(q): Promise
{ - const idSet = q.listingIds !== undefined ? new Set(q.listingIds) : null; - const kindSet = new Set(q.kinds); - const fromMs = parseBoundMs(q.from, false); - const toMs = parseBoundMs(q.to, true); - const asOfMs = q.asOf !== undefined ? parseBoundMs(q.asOf, true) : Number.POSITIVE_INFINITY; - const filtered = fixture.eventsTable.rows.filter(row => { - const listingId = row.listing_id as number; - const kind = row.kind as EventKind; - const ts = row.ts as number; - const knownAt = row.known_at as number; - if (idSet !== null && !idSet.has(listingId)) { - return false; - } - return kindSet.has(kind) && ts >= fromMs && ts <= toMs && knownAt <= asOfMs; - }); - return { - columns: fixture.eventsTable.columns, - rows: filtered, - }; - }, - async shortsAsOf() { - throw new MarketDataStoreNotImplementedError('shortsAsOf'); - }, - async crossSection() { - throw new MarketDataStoreNotImplementedError('crossSection'); - }, - async fundamentalsAsOf() { - throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); - }, - async macroAsOf() { - throw new MarketDataStoreNotImplementedError('macroAsOf'); - }, - async fx() { - throw new MarketDataStoreNotImplementedError('fx'); - }, - }; -} - -class RecordingPostgresExecutor implements PostgresResearchCopilotExecutor { - readonly calls: RecordedSqlCall[] = []; - readonly ledgerRows: StoredTrialRow[] = []; - readonly visibleTrialsById: Map; - private nextTrialId = 100; - - constructor(options?: { readonly trials?: readonly { readonly id: string; readonly sampleEnd: string }[] }) { - this.visibleTrialsById = new Map(); - for (const trial of options?.trials ?? [{ id: '42', sampleEnd: '2024-05-01' }]) { - this.visibleTrialsById.set(trial.id, { sampleEnd: trial.sampleEnd }); - } - } - - async query>( - text: string, - params?: readonly unknown[] - ): Promise<{ readonly rows: readonly Row[] }> { - // Use `this` explicitly so receiver loss would immediately fail tests. - this.calls.push({ text, params }); - const normalized = text.trim(); - - // 1. Symbol search (`listing` + `instrument` + `exchange` + `listing_symbol_history`) - if (normalized.includes('listing_symbol_history') && normalized.includes('canonical_name')) { - return { - rows: [ - { - listing_id: 60_001, - instrument_id: 90_001, - ticker: 'ACME', - class_suffix: null, - name: 'Acme Holdings Inc', - mic: 'XNYS', - currency: 'USD', - isin: 'US0000000001', - first_bar_date: '2020-01-02', - last_bar_date: '2024-05-31', - delisted_at: null, - } as unknown as Row, - ], - }; - } - - // 2. Trial-ref visibility lookup (`SELECT 1 AS visible FROM ...trial_ledger`) - if (normalized.startsWith('SELECT 1 AS visible FROM')) { - const trialId = String(params?.[0] ?? ''); - const cutoffDate = String(params?.[1] ?? ''); - const trial = this.visibleTrialsById.get(trialId); - if (trial !== undefined && trial.sampleEnd < cutoffDate) { - return { rows: [{ visible: 1 } as unknown as Row] }; - } - return { rows: [] }; - } - - // 3. Findings insert (`INSERT INTO ...findings`) - if (normalized.startsWith('INSERT INTO') && normalized.includes('findings (')) { - const id = String(params?.[0] ?? ''); - const createdAt = String(params?.[5] ?? FIXED_NOW_ISO); - return { - rows: [{ id, created_at: createdAt } as unknown as Row], - }; - } - - // 4. Findings reader (`SELECT ... FROM ...findings`) - if (normalized.startsWith('SELECT') && normalized.includes('trial_refs') && normalized.includes('evidence_refs')) { - return { - rows: [ - { - id: 'finding-existing-01', - title: 'Short-interest drift finding', - status: 'approved', - created_at: '2024-05-10T10:00:00.000Z', - summary: 'Pre-Vault empirical finding on filing drift.', - trial_refs: ['42'], - evidence_refs: ['snap-01'], - } as unknown as Row, - ], - }; - } - - // 5. Provider caveats reader (`SELECT ... FROM ...provider_caveats`) - if (normalized.startsWith('SELECT') && normalized.includes('caveat') && normalized.includes('provider_caveats')) { - return { - rows: [ - { - id: 'caveat-eodhd-01', - provider: 'eodhd', - dataset: 'bars_1d', - caveat: 'Splits require un-adjustment before raw close storage.', - created_at: '2024-03-01T00:00:00.000Z', - } as unknown as Row, - ], - }; - } - - // 6. Listing calendar lookup (`SELECT ... e.calendar_code AS calendar_code`) - if (normalized.startsWith('SELECT') && normalized.includes('e.calendar_code AS calendar_code')) { - const requested = (params?.[0] as readonly number[] | undefined) ?? []; - return { - rows: requested.map( - listingId => - ({ - listing_id: listingId, - calendar_code: 'XNYS', - }) as unknown as Row - ), - }; - } - - // 7. Trial ledger insert (`INSERT INTO trial_ledger`) - if (normalized.startsWith('INSERT INTO trial_ledger')) { - const p = params ?? []; - const trialId = this.nextTrialId++; - const createdAt = new Date(Date.UTC(2024, 5, 1, 12, 0, trialId % 60)); - const dailySeries = (p[13] as readonly number[]).map(v => Math.fround(v)); - const stored: StoredTrialRow = { - trial_id: String(trialId), - created_at: createdAt, - principal_id: p[0] as string, - campaign_id: (p[1] as string | null) ?? null, - stage: p[2] as string, - universe_market: p[3] as string, - horizon_bucket: p[4] as string, - hypothesis_id: (p[5] as string | null) ?? null, - expression_hash: p[6] as string, - sample_start: p[7] as string, - sample_end: p[8] as string, - n_obs: p[9] as number, - sharpe_unann: p[10] as number, - skewness: p[11] as number, - kurtosis: p[12] as number, - daily_series: dailySeries, - }; - this.ledgerRows.push(stored); - return { - rows: [{ trial_id: stored.trial_id, created_at: stored.created_at } as unknown as Row], - }; - } - - // 8. Trial ledger cluster/target reads (`SELECT ... FROM trial_ledger`) - if (normalized.startsWith('SELECT') && normalized.includes('FROM trial_ledger')) { - if (normalized.includes('WHERE trial_id = $1::bigint')) { - const targetId = String(params?.[0]); - const matched = this.ledgerRows.filter(r => r.trial_id === targetId); - return { rows: matched as unknown as Row[] }; - } - if (normalized.includes('WHERE universe_market = $1')) { - const market = params?.[0] as string; - const bucket = params?.[1] as string; - const matched = this.ledgerRows.filter( - r => r.universe_market === market && r.horizon_bucket === bucket - ); - return { rows: matched as unknown as Row[] }; - } - } - - throw new Error(`Unexpected SQL statement in RecordingPostgresExecutor:\n${text}`); - } -} - -async function callMcpTool( - server: McpServer, - id: number, - name: string, - args: Record -): Promise<{ readonly envelope: ToolCallEnvelope; readonly parsed: T | null }> { - const raw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id, - method: 'tools/call', - params: { name, arguments: args }, - }) - ); - if (raw === null) { - throw new Error(`Expected JSON-RPC response for tool "${name}", got null.`); - } - const rpc = JSON.parse(raw) as JsonRpcResponseEnvelope; - expect(rpc.error).toBeUndefined(); - const envelope = rpc.result as ToolCallEnvelope; - const text = envelope.content[0]?.text ?? ''; - if (envelope.isError === true) { - return { envelope, parsed: null }; - } - return { envelope, parsed: JSON.parse(text) as T }; -} - -function makeDefaultLibraryCards(): readonly LibraryCardRecord[] { - return [ - { - id: 'card-dsr-01', - title: 'Deflated Sharpe Ratio', - tags: ['dsr', 'rigor'], - summary: 'Adjust Sharpe ratios for multiple testing.', - body: 'Always record trials before reading results.', - }, - ]; -} - -function buildValidOptions(overrides?: { - readonly executor?: RecordingPostgresExecutor; - readonly schema?: string; - readonly vaultCutoffTs?: number; - readonly fixture?: EventStudyFixture; - readonly listLibraryCards?: KnowledgePort['listLibraryCards']; - readonly sessionDates?: SessionDatesPort; -}): { - readonly options: PostgresResearchCopilotServerOptions; - readonly executor: RecordingPostgresExecutor; - readonly fixture: EventStudyFixture; - readonly sessionDateCalls: SessionDatesQuery[]; - readonly libraryCardCalls: LibraryCardQuery[]; -} { - const fixture = overrides?.fixture ?? buildEventStudyFixture(); - const executor = overrides?.executor ?? new RecordingPostgresExecutor(); - const sessionDateCalls: SessionDatesQuery[] = []; - const libraryCardCalls: LibraryCardQuery[] = []; - - const defaultSessionDates: SessionDatesPort = { - listSessionDates(query: SessionDatesQuery) { - sessionDateCalls.push(query); - return fixture.allDates.filter(d => d >= query.fromDate && d <= query.toDate); - }, - }; - - const defaultListLibraryCards: KnowledgePort['listLibraryCards'] = async ( - q: LibraryCardQuery - ) => { - libraryCardCalls.push(q); - return makeDefaultLibraryCards(); - }; - - const base: PostgresResearchCopilotServerOptions = { - name: SERVER_NAME, - version: SERVER_VERSION, - executor, - ...(overrides?.schema !== undefined ? { schema: overrides.schema } : {}), - store: createFakeMarketDataStore(fixture), - vaultContext: { vaultCutoffTs: overrides?.vaultCutoffTs ?? fixture.vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - listLibraryCards: overrides?.listLibraryCards ?? defaultListLibraryCards, - sessionDates: overrides?.sessionDates ?? defaultSessionDates, - newId: () => FIXED_FINDING_ID, - now: () => FIXED_NOW_MS, - }; - - return { - options: base, - executor, - fixture, - sessionDateCalls, - libraryCardCalls, - }; -} - -describe('createPostgresResearchCopilotServer', () => { - test('registers all six MCP tools in RESEARCH_COPILOT_TOOL_NAMES order with zero queries at construction', () => { - const { options, executor } = buildValidOptions(); - const server = createPostgresResearchCopilotServer(options); - - expect(server.listTools().map(t => t.name)).toEqual([...RESEARCH_COPILOT_TOOL_NAMES]); - expect(executor.calls).toHaveLength(0); - }); - - test('routes search_symbols, file_finding, and read_knowledge (findings + provider_caveats) through the same executor', async () => { - const cutoffTs = Date.UTC(2024, 6, 1, 0, 0, 0, 0); // 2024-07-01 - const { options, executor } = buildValidOptions({ vaultCutoffTs: cutoffTs }); - const server = createPostgresResearchCopilotServer(options); - - // 1) search_symbols - const beforeSearch = executor.calls.length; - const searchRes = await callMcpTool(server, 1, 'search_symbols', { - query: 'ACME', - country: 'US', - includeDelisted: false, - limit: 5, - }); - expect(searchRes.envelope.isError).toBeUndefined(); - expect(searchRes.parsed?.rows).toHaveLength(1); - expect(searchRes.parsed?.rows[0]?.ticker).toBe('ACME'); - const searchCalls = executor.calls.slice(beforeSearch); - expect(searchCalls).toHaveLength(1); - // createSearchSymbolsTool always queries the port with includeDelisted: true so - // post-cutoff delistings cannot hide listings that were active as of the cutoff. - expect(searchCalls[0]?.params).toEqual(['2024-07-01', '%ACME%', 'ACME', 'US', true]); - - // 2) file_finding with trial_ledger ref '42' - const beforeFile = executor.calls.length; - const fileRes = await callMcpTool(server, 2, 'file_finding', { - kind: 'finding', - title: 'Filing drift effect', - summary: 'Pre-Vault event study shows positive post-filing drift.', - trialRefs: ['42'], - evidenceRefs: [FIXTURE_DATASET_ID], - }); - expect(fileRes.envelope.isError).toBeUndefined(); - expect(fileRes.parsed).toEqual({ - id: FIXED_FINDING_ID, - createdAt: FIXED_NOW_ISO, - created: true, - }); - const fileCalls = executor.calls.slice(beforeFile); - expect(fileCalls).toHaveLength(2); - // Visibility lookup must run before finding insert - expect(fileCalls[0]?.text).toContain('SELECT 1 AS visible FROM trial_ledger'); - expect(fileCalls[0]?.params).toEqual(['42', '2024-07-01']); - expect(fileCalls[1]?.text).toContain('INSERT INTO findings'); - expect(fileCalls[1]?.params?.[0]).toBe(FIXED_FINDING_ID); - expect(fileCalls[1]?.params?.[5]).toBe(FIXED_NOW_ISO); - - // 3) read_knowledge (findings) - const beforeFindings = executor.calls.length; - const findingsRes = await callMcpTool(server, 3, 'read_knowledge', { - source: 'findings', - query: 'drift', - }); - expect(findingsRes.envelope.isError).toBeUndefined(); - expect(findingsRes.parsed?.rows).toHaveLength(1); - expect(findingsRes.parsed?.rows[0]?.id).toBe('finding-existing-01'); - const findingsCalls = executor.calls.slice(beforeFindings); - expect(findingsCalls).toHaveLength(1); - expect(findingsCalls[0]?.text).toContain('FROM findings'); - expect(findingsCalls[0]?.params).toEqual(['%drift%']); - - // 4) read_knowledge (provider_caveats) - const beforeCaveats = executor.calls.length; - const caveatsRes = await callMcpTool(server, 4, 'read_knowledge', { - source: 'provider_caveats', - provider: 'eodhd', - query: 'split', - }); - expect(caveatsRes.envelope.isError).toBeUndefined(); - expect(caveatsRes.parsed?.rows).toHaveLength(1); - expect(caveatsRes.parsed?.rows[0]?.id).toBe('caveat-eodhd-01'); - const caveatsCalls = executor.calls.slice(beforeCaveats); - expect(caveatsCalls).toHaveLength(1); - expect(caveatsCalls[0]?.text).toContain('FROM provider_caveats'); - expect(caveatsCalls[0]?.params).toEqual(['eodhd', '%split%']); - }); - - test('qualifies every schema-aware adapter table when schema is provided and leaves them unqualified when omitted', async () => { - const runAllSqlTools = async (schema?: string) => { - const fixture = buildEventStudyFixture(); - const executor = new RecordingPostgresExecutor({ - trials: [{ id: '42', sampleEnd: '2023-01-10' }], - }); - const { options } = buildValidOptions({ - executor, - fixture, - schema, - }); - const server = createPostgresResearchCopilotServer(options); - - const s1 = await callMcpTool(server, 1, 'search_symbols', { - query: 'ACME', - }); - expect(s1.envelope.isError).toBeUndefined(); - - const s2 = await callMcpTool(server, 2, 'file_finding', { - kind: 'finding', - title: 'Schema test finding', - summary: 'Verifies schema qualification across adapters.', - trialRefs: ['42'], - }); - expect(s2.envelope.isError).toBeUndefined(); - - const s3 = await callMcpTool(server, 3, 'read_knowledge', { - source: 'findings', - id: 'finding-existing-01', - }); - expect(s3.envelope.isError).toBeUndefined(); - - const s4 = await callMcpTool(server, 4, 'read_knowledge', { - source: 'provider_caveats', - provider: 'eodhd', - }); - expect(s4.envelope.isError).toBeUndefined(); - - const s5 = await callMcpTool(server, 5, 'event_study', { - listingIds: [...fixture.listingIds], - from: fixture.firstDate, - to: fixture.lastPreCutoffDate, - event: { kinds: ['filing'], subtypes: ['8-K'] }, - preDays: 2, - postDays: 3, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - benchmark: 'equal_weight', - }); - expect(s5.envelope.isError).toBeUndefined(); - - return executor.calls; - }; - - // With schema: 'research_x' - const qualifiedCalls = await runAllSqlTools('research_x'); - const symbolSql = qualifiedCalls.find(c => c.text.includes('listing_symbol_history'))?.text ?? ''; - expect(symbolSql).toContain('FROM "research_x".listing l'); - expect(symbolSql).toContain('INNER JOIN "research_x".instrument i'); - expect(symbolSql).toContain('INNER JOIN "research_x".exchange e'); - expect(symbolSql).toContain('FROM "research_x".listing_symbol_history h_any'); - expect(symbolSql).toContain('FROM "research_x".listing_symbol_history h_past'); - expect(symbolSql).toContain('FROM "research_x".listing_symbol_history h'); - - const trialLookupSql = - qualifiedCalls.find(c => c.text.startsWith('SELECT 1 AS visible'))?.text ?? ''; - expect(trialLookupSql).toContain('FROM "research_x".trial_ledger'); - - const findingInsertSql = - qualifiedCalls.find(c => c.text.startsWith('INSERT INTO') && c.text.includes('findings (')) - ?.text ?? ''; - expect(findingInsertSql).toContain('INSERT INTO "research_x".findings'); - - const findingsReadSql = - qualifiedCalls.find(c => c.text.startsWith('SELECT') && c.text.includes('trial_refs'))?.text ?? - ''; - expect(findingsReadSql).toContain('FROM "research_x".findings'); - - const caveatsReadSql = - qualifiedCalls.find(c => c.text.startsWith('SELECT') && c.text.includes('provider_caveats')) - ?.text ?? ''; - expect(caveatsReadSql).toContain('FROM "research_x".provider_caveats'); - - const calendarSql = - qualifiedCalls.find(c => c.text.includes('e.calendar_code AS calendar_code'))?.text ?? ''; - expect(calendarSql).toContain('FROM "research_x".listing l'); - expect(calendarSql).toContain('INNER JOIN "research_x".exchange e'); - - // Ledger SQL resolves via executor's search_path (unqualified even when schema is set) - const ledgerInsertSql = - qualifiedCalls.find(c => c.text.trim().startsWith('INSERT INTO trial_ledger'))?.text ?? ''; - expect(ledgerInsertSql).toContain('INSERT INTO trial_ledger'); - expect(ledgerInsertSql).not.toContain('"research_x".'); - - // With schema omitted - const unqualifiedCalls = await runAllSqlTools(undefined); - expect(unqualifiedCalls.length).toBeGreaterThanOrEqual(7); - for (const call of unqualifiedCalls) { - expect(call.text).not.toMatch(/"[a-z_][a-z0-9_]*"\./); - } - }); - - test('derives trial-ref visibility cutoff exclusively from vaultContext.vaultCutoffTs', async () => { - // Trial '42' ends on 2024-06-01: - // - Under cutoff 2024-06-01: sample_end < '2024-06-01' is false -> rejected with zero inserts. - // - Under cutoff 2024-07-01: sample_end < '2024-07-01' is true -> accepted and inserted. - const trialFixture = [{ id: '42', sampleEnd: '2024-06-01' }] as const; - - const blockedExecutor = new RecordingPostgresExecutor({ trials: trialFixture }); - const blockedSetup = buildValidOptions({ - executor: blockedExecutor, - vaultCutoffTs: Date.UTC(2024, 5, 1, 0, 0, 0, 0), // 2024-06-01 - }); - const blockedServer = createPostgresResearchCopilotServer(blockedSetup.options); - - const blockedRes = await callMcpTool(blockedServer, 1, 'file_finding', { - kind: 'finding', - title: 'Holdout-boundary trial', - summary: 'Must be rejected when sample_end equals cutoff.', - trialRefs: ['42'], - }); - expect(blockedRes.envelope.isError).toBe(true); - expect(blockedExecutor.calls).toHaveLength(1); - expect(blockedExecutor.calls[0]?.text).toContain('sample_end < $2::date'); - expect(blockedExecutor.calls[0]?.params).toEqual(['42', '2024-06-01']); - - const allowedExecutor = new RecordingPostgresExecutor({ trials: trialFixture }); - const allowedSetup = buildValidOptions({ - executor: allowedExecutor, - vaultCutoffTs: Date.UTC(2024, 6, 1, 0, 0, 0, 0), // 2024-07-01 - }); - const allowedServer = createPostgresResearchCopilotServer(allowedSetup.options); - - const allowedRes = await callMcpTool(allowedServer, 2, 'file_finding', { - kind: 'finding', - title: 'Pre-cutoff trial', - summary: 'Allowed once cutoff moves past sample_end.', - trialRefs: ['42'], - }); - expect(allowedRes.envelope.isError).toBeUndefined(); - expect(allowedRes.parsed?.created).toBe(true); - expect(allowedExecutor.calls).toHaveLength(2); - expect(allowedExecutor.calls[0]?.text).toContain('sample_end < $2::date'); - expect(allowedExecutor.calls[0]?.params).toEqual(['42', '2024-07-01']); - expect(allowedExecutor.calls[1]?.text).toContain('INSERT INTO findings'); - }); - - test('isolates library reads from PostgreSQL and prevents smuggling listFindings or listProviderCaveats', async () => { - const libraryCalls: LibraryCardQuery[] = []; - let smuggledFindingsCalled = false; - let smuggledCaveatsCalled = false; - - const baseLibraryFn: KnowledgePort['listLibraryCards'] = async (q: LibraryCardQuery) => { - libraryCalls.push(q); - return makeDefaultLibraryCards(); - }; - - const smuggledFn = Object.assign(baseLibraryFn, { - listFindings: async () => { - smuggledFindingsCalled = true; - throw new Error('Smuggled listFindings must never be called'); - }, - listProviderCaveats: async () => { - smuggledCaveatsCalled = true; - throw new Error('Smuggled listProviderCaveats must never be called'); - }, - }); - - const { options, executor } = buildValidOptions({ listLibraryCards: smuggledFn }); - const server = createPostgresResearchCopilotServer(options); - - // source: 'library' -> calls injected listLibraryCards and issues zero executor queries - const libRes = await callMcpTool(server, 1, 'read_knowledge', { - source: 'library', - query: 'Sharpe', - }); - expect(libRes.envelope.isError).toBeUndefined(); - expect(libRes.parsed?.rows).toHaveLength(1); - expect(libRes.parsed?.rows[0]?.id).toBe('card-dsr-01'); - expect(libraryCalls).toHaveLength(1); - expect(executor.calls).toHaveLength(0); - - // source: 'findings' -> uses PostgreSQL reader, never calls smuggled property - const findingsRes = await callMcpTool(server, 2, 'read_knowledge', { - source: 'findings', - }); - expect(findingsRes.envelope.isError).toBeUndefined(); - expect(findingsRes.parsed?.rows[0]?.id).toBe('finding-existing-01'); - expect(smuggledFindingsCalled).toBe(false); - - // source: 'provider_caveats' -> uses PostgreSQL reader, never calls smuggled property - const caveatsRes = await callMcpTool(server, 3, 'read_knowledge', { - source: 'provider_caveats', - }); - expect(caveatsRes.envelope.isError).toBeUndefined(); - expect(caveatsRes.parsed?.rows[0]?.id).toBe('caveat-eodhd-01'); - expect(smuggledCaveatsCalled).toBe(false); - expect(executor.calls).toHaveLength(2); - }); - - test('wires event_study calendar resolution through shared executor and injected sessionDates and records trial under principalId', async () => { - const fixture = buildEventStudyFixture(); - const { options, executor, sessionDateCalls } = buildValidOptions({ fixture }); - const server = createPostgresResearchCopilotServer({ - ...options, - earlyCloses: { XNYS: { [fixture.firstDate]: 780 } }, - }); - - // Pass `to` past vaultCutoffDate to verify Vault clamping reaches sessionDates. - const postCutoffTo = fixture.allDates[fixture.allDates.length - 1]!; - const res = await callMcpTool(server, 1, 'event_study', { - listingIds: [...fixture.listingIds], - from: fixture.firstDate, - to: postCutoffTo, - event: { kinds: ['filing'], subtypes: ['8-K'] }, - preDays: 2, - postDays: 3, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - benchmark: 'equal_weight', - }); - - expect(res.envelope.isError).toBeUndefined(); - expect(res.parsed?.status).toBe('ok'); - - // Listing-calendar query ran through the shared executor with bound listing IDs - const calendarCalls = executor.calls.filter(c => - c.text.includes('e.calendar_code AS calendar_code') - ); - expect(calendarCalls).toHaveLength(1); - expect(calendarCalls[0]?.params).toEqual([[...fixture.listingIds]]); - - // Injected sessionDates received XNYS and a Vault-clamped date range (< vaultCutoffDate) - expect(sessionDateCalls).toHaveLength(1); - expect(sessionDateCalls[0]?.calendarCode).toBe('XNYS'); - expect(sessionDateCalls[0]?.fromDate).toBe(fixture.firstDate); - expect(sessionDateCalls[0]!.toDate < fixture.vaultCutoffDate).toBe(true); - - // Trial ledger append ran through the same shared executor under AGENT_PRINCIPAL - expect(executor.ledgerRows).toHaveLength(1); - expect(executor.ledgerRows[0]?.principal_id).toBe(AGENT_PRINCIPAL); - expect(executor.ledgerRows[0]?.stage).toBe('event_study'); - expect(executor.ledgerRows[0]!.sample_end < fixture.vaultCutoffDate).toBe(true); - }); - - describe('fail-closed option validation', () => { - const invalidCases: readonly { - readonly label: string; - readonly field: string; - readonly mutate: (valid: PostgresResearchCopilotServerOptions) => unknown; - }[] = [ - { label: 'options is undefined', field: 'options', mutate: () => undefined }, - { label: 'options is null', field: 'options', mutate: () => null }, - { label: 'options is primitive', field: 'options', mutate: () => 'invalid' }, - { - label: 'executor is undefined', - field: 'executor', - mutate: valid => ({ ...valid, executor: undefined }), - }, - { - label: 'executor is null', - field: 'executor', - mutate: valid => ({ ...valid, executor: null }), - }, - { - label: 'executor missing query', - field: 'executor', - mutate: valid => ({ ...valid, executor: {} }), - }, - { - label: 'executor.query is not callable', - field: 'executor', - mutate: valid => ({ ...valid, executor: { query: 'not-a-function' } }), - }, - { - label: 'vaultContext is null', - field: 'vaultContext', - mutate: valid => ({ ...valid, vaultContext: null }), - }, - { - label: 'listLibraryCards is undefined', - field: 'listLibraryCards', - mutate: valid => ({ ...valid, listLibraryCards: undefined }), - }, - { - label: 'listLibraryCards is not callable', - field: 'listLibraryCards', - mutate: valid => ({ ...valid, listLibraryCards: {} }), - }, - { - label: 'sessionDates is undefined', - field: 'sessionDates', - mutate: valid => ({ ...valid, sessionDates: undefined }), - }, - { - label: 'sessionDates is null', - field: 'sessionDates', - mutate: valid => ({ ...valid, sessionDates: null }), - }, - { - label: 'sessionDates missing listSessionDates', - field: 'sessionDates', - mutate: valid => ({ ...valid, sessionDates: {} }), - }, - { - label: 'sessionDates.listSessionDates is not callable', - field: 'sessionDates', - mutate: valid => ({ ...valid, sessionDates: { listSessionDates: 123 } }), - }, - { - label: 'newId is undefined', - field: 'newId', - mutate: valid => ({ ...valid, newId: undefined }), - }, - { - label: 'newId is not callable', - field: 'newId', - mutate: valid => ({ ...valid, newId: 'id-1' }), - }, - { - label: 'now is undefined', - field: 'now', - mutate: valid => ({ ...valid, now: undefined }), - }, - { - label: 'now is not callable', - field: 'now', - mutate: valid => ({ ...valid, now: FIXED_NOW_MS }), - }, - ]; - - for (const testCase of invalidCases) { - test(`throws an Error naming "${testCase.field}" when ${testCase.label}`, () => { - const { options, executor } = buildValidOptions(); - const badInput = testCase.mutate(options) as PostgresResearchCopilotServerOptions; - - expect(() => createPostgresResearchCopilotServer(badInput)).toThrow( - new RegExp(testCase.field) - ); - expect(executor.calls).toHaveLength(0); - }); - } - }); -}); - -describe('createPostgresResearchCopilotServer (QA edge cases)', () => { - test('clamps event_study session-date request to exactly the last pre-cutoff session', async () => { - const fixture = buildEventStudyFixture(); - const { options, sessionDateCalls, executor } = buildValidOptions({ fixture }); - const server = createPostgresResearchCopilotServer(options); - - const res = await callMcpTool(server, 1, 'event_study', { - listingIds: [...fixture.listingIds], - from: fixture.firstDate, - to: fixture.allDates[fixture.allDates.length - 1]!, - event: { kinds: ['filing'], subtypes: ['8-K'] }, - preDays: 2, - postDays: 3, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - benchmark: 'equal_weight', - }); - - expect(res.parsed?.status).toBe('ok'); - expect(sessionDateCalls).toHaveLength(1); - const requested = sessionDateCalls[0]!; - // Fixture pins lastPreCutoffDate (2023-02-27) as the calendar day before the cutoff - // (2023-02-28), so an off-by-one clamp that drops the final session fails here. - expect(fixture.lastPreCutoffDate).toBe('2023-02-27'); - expect(fixture.vaultCutoffDate).toBe('2023-02-28'); - expect(requested.toDate).toBe(fixture.lastPreCutoffDate); - const served = fixture.allDates.filter( - d => d >= requested.fromDate && d <= requested.toDate - ); - expect(served[served.length - 1]).toBe(fixture.lastPreCutoffDate); - expect(executor.ledgerRows[0]!.sample_end <= fixture.lastPreCutoffDate).toBe(true); - }); - - test('binds the UTC calendar date of an intraday vaultCutoffTs to trial-ref and symbol-search queries', async () => { - const intradayCutoff = Date.UTC(2024, 6, 1, 15, 30, 0, 0); // 2024-07-01T15:30Z - const executor = new RecordingPostgresExecutor({ trials: [{ id: '42', sampleEnd: '2024-06-30' }] }); - const { options } = buildValidOptions({ executor, vaultCutoffTs: intradayCutoff }); - const server = createPostgresResearchCopilotServer(options); - - await callMcpTool(server, 1, 'search_symbols', { query: 'ACME' }); - const fileRes = await callMcpTool(server, 2, 'file_finding', { - kind: 'finding', - title: 'Intraday cutoff', - summary: 'Cutoff date derivation check.', - trialRefs: ['42'], - }); - - expect(fileRes.parsed?.created).toBe(true); - expect(executor.calls[0]?.params?.[0]).toBe('2024-07-01'); - expect(executor.calls[1]?.params).toEqual(['42', '2024-07-01']); - }); - - test('rejects unknown and non-canonical trial refs without inserting a finding', async () => { - const executor = new RecordingPostgresExecutor(); - const { options } = buildValidOptions({ - executor, - vaultCutoffTs: Date.UTC(2024, 6, 1, 0, 0, 0, 0), - }); - const server = createPostgresResearchCopilotServer(options); - - for (const [i, ref] of ['999', '042', '-1', 'abc'].entries()) { - const res = await callMcpTool(server, i + 1, 'file_finding', { - kind: 'finding', - title: 'Bad ref', - summary: 'Must not be filed.', - trialRefs: [ref], - }); - expect(res.envelope.isError).toBe(true); - } - expect(executor.calls.some(c => c.text.includes('INSERT INTO'))).toBe(false); - }); - - test('ignores pre-built ports and a stray vaultCutoffTs smuggled onto the options object', async () => { - const executor = new RecordingPostgresExecutor({ trials: [{ id: '42', sampleEnd: '2024-06-01' }] }); - const { options } = buildValidOptions({ - executor, - vaultCutoffTs: Date.UTC(2024, 5, 1, 0, 0, 0, 0), // 2024-06-01: trial 42 is Vault-only - }); - let smuggledUsed = false; - const smuggled = { - ...options, - vaultCutoffTs: Date.UTC(2030, 0, 1), - ledger: { query: async () => { smuggledUsed = true; return { rows: [] }; } }, - fileFinding: { - trialLookup: { hasResearchVisibleTrial: async () => { smuggledUsed = true; return true; } }, - }, - } as unknown as PostgresResearchCopilotServerOptions; - const server = createPostgresResearchCopilotServer(smuggled); - - const res = await callMcpTool(server, 1, 'file_finding', { - kind: 'finding', - title: 'Smuggle attempt', - summary: 'Holdout-backed trial must stay invisible.', - trialRefs: ['42'], - }); - - expect(res.envelope.isError).toBe(true); - expect(smuggledUsed).toBe(false); - expect(executor.calls).toHaveLength(1); - expect(executor.calls[0]?.params).toEqual(['42', '2024-06-01']); - }); - - test('keeps two servers isolated to their own executors', async () => { - const a = buildValidOptions(); - const b = buildValidOptions(); - const serverA = createPostgresResearchCopilotServer(a.options); - createPostgresResearchCopilotServer(b.options); - - await callMcpTool(serverA, 1, 'search_symbols', { query: 'ACME' }); - - expect(a.executor.calls).toHaveLength(1); - expect(b.executor.calls).toHaveLength(0); - }); - - test('lists tools over JSON-RPC tools/list in RESEARCH_COPILOT_TOOL_NAMES order', async () => { - const { options, executor } = buildValidOptions(); - const server = createPostgresResearchCopilotServer(options); - - const raw = await server.handleMessage( - JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' }) - ); - const rpc = JSON.parse(raw!) as { result: { tools: { name: string }[] } }; - - expect(rpc.result.tools.map(t => t.name)).toEqual([...RESEARCH_COPILOT_TOOL_NAMES]); - expect(executor.calls).toHaveLength(0); - }); - - test.each([ - ['uppercase schema', { schema: 'Research_X' }], - ['quoted schema injection', { schema: 'x"; DROP TABLE findings; --' }], - ['NaN vault cutoff', { vaultCutoffTs: Number.NaN }], - ] as const)('fails closed at construction with zero queries for %s', (_label, override) => { - const { options, executor } = buildValidOptions(); - const bad = { - ...options, - ...('schema' in override ? { schema: override.schema } : {}), - ...('vaultCutoffTs' in override - ? { vaultContext: { vaultCutoffTs: override.vaultCutoffTs } } - : {}), - }; - - expect(() => createPostgresResearchCopilotServer(bad)).toThrow(); - expect(executor.calls).toHaveLength(0); - }); -}); diff --git a/libs/research/test/mcp-postgres-findings-qa.test.ts b/libs/research/test/mcp-postgres-findings-qa.test.ts deleted file mode 100644 index 249816fd..00000000 --- a/libs/research/test/mcp-postgres-findings-qa.test.ts +++ /dev/null @@ -1,268 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { - type FiledFindingRecord, - type PostgresFindingsExecutor, - createPostgresFindingWritePort, - createPostgresKnowledgeReaders, -} from '../src/mcp/index'; - -// QA edge cases for the PostgreSQL findings adapter (T-161), complementing -// mcp-postgres-findings.test.ts. All randomness is seeded; no wall clock. - -interface RecordedCall { - readonly text: string; - readonly params: readonly unknown[] | undefined; -} - -function createRowsExecutor(rows: readonly Record[]): { - readonly calls: RecordedCall[]; - readonly executor: PostgresFindingsExecutor; -} { - const calls: RecordedCall[] = []; - return { - calls, - executor: { - async query>( - text: string, - params?: readonly unknown[] - ): Promise<{ readonly rows: readonly Row[] }> { - calls.push({ text, params }); - return { rows: rows as unknown as readonly Row[] }; - }, - }, - }; -} - -function mulberry32(seed: number): () => number { - let a = seed >>> 0; - return () => { - a = (a + 0x6d2b79f5) >>> 0; - let t = a; - t = Math.imul(t ^ (t >>> 15), t | 1); - t ^= t + Math.imul(t ^ (t >>> 7), t | 61); - return ((t ^ (t >>> 14)) >>> 0) / 4294967296; - }; -} - -// Mix of ASCII (incl. LIKE wildcards / escape) and casing-hostile Unicode. -const ALPHABET = ['a', 'B', 'i', 'I', 's', 'S', 'k', '%', '_', '\\', ' ', 'İ', 'ı', 'Σ', 'ς', 'K', 'é', 'ß']; - -function randomText(rand: () => number, min: number, max: number): string { - const len = min + Math.floor(rand() * (max - min + 1)); - let out = ''; - for (let i = 0; i < len; i += 1) { - out += ALPHABET[Math.floor(rand() * ALPHABET.length)]; - } - return out; -} - -function randomQuery(rand: () => number, corpus: readonly string[]): string { - if (rand() < 0.5) { - const source = corpus[Math.floor(rand() * corpus.length)]!; - const start = Math.floor(rand() * source.length); - const end = Math.min(source.length, start + 1 + Math.floor(rand() * 3)); - let q = ''; - for (const ch of source.slice(start, end)) { - q += rand() < 0.5 ? ch.toUpperCase() : ch.toLowerCase(); - } - return q.length > 0 ? q : 'a'; - } - return randomText(rand, 1, 2); -} - -const TS = '2026-01-15T12:34:56.789Z'; - -describe('PostgreSQL findings readers QA: JS post-filter agrees with read_knowledge matching', () => { - test('seeded fuzz: listFindings returns exactly the read_knowledge-matching rows in SQL order', async () => { - const rand = mulberry32(161); - const rows = Array.from({ length: 40 }, (_, i) => ({ - id: `f-${String(i).padStart(3, '0')}`, - title: `T${randomText(rand, 2, 6)}`, - summary: `S${randomText(rand, 2, 6)}`, - status: 'pending_review', - created_at: new Date(TS), - trial_refs: [], - evidence_refs: [], - })); - const corpus = rows.flatMap(r => [r.title, r.summary]); - const { executor } = createRowsExecutor(rows); - const readers = createPostgresKnowledgeReaders({ executor }); - - for (let n = 0; n < 200; n += 1) { - const query = randomQuery(rand, corpus); - const lower = query.toLowerCase(); - const expected = rows - .filter(r => r.title.toLowerCase().includes(lower) || r.summary.toLowerCase().includes(lower)) - .map(r => r.id); - const actual = (await readers.listFindings({ query })).map(r => r.id); - expect({ query, ids: actual }).toEqual({ query, ids: expected }); - } - }); - - test('seeded fuzz: listProviderCaveats applies provider equality and query substring like read_knowledge', async () => { - const rand = mulberry32(2026); - const providers = ['EODHD', 'eodhd', 'K', 'kelvin', 'İBK', 'ibk', 'ΣΙΣ', 'σις']; - const rows = Array.from({ length: 40 }, (_, i) => ({ - id: `c-${String(i).padStart(3, '0')}`, - provider: providers[Math.floor(rand() * providers.length)]!, - dataset: `D${randomText(rand, 2, 5)}`, - caveat: `C${randomText(rand, 2, 6)}`, - created_at: new Date(TS), - })); - const corpus = rows.flatMap(r => [r.provider, r.dataset, r.caveat]); - const { executor } = createRowsExecutor(rows); - const readers = createPostgresKnowledgeReaders({ executor }); - - for (let n = 0; n < 200; n += 1) { - const provider = - rand() < 0.6 ? providers[Math.floor(rand() * providers.length)]!.toUpperCase() : undefined; - const query = rand() < 0.7 ? randomQuery(rand, corpus) : undefined; - const lowerProvider = provider?.toLowerCase(); - const lowerQuery = query?.toLowerCase(); - const expected = rows - .filter(r => lowerProvider === undefined || r.provider.toLowerCase() === lowerProvider) - .filter( - r => - lowerQuery === undefined || - r.provider.toLowerCase().includes(lowerQuery) || - r.dataset.toLowerCase().includes(lowerQuery) || - r.caveat.toLowerCase().includes(lowerQuery) - ) - .map(r => r.id); - const actual = ( - await readers.listProviderCaveats({ - ...(provider !== undefined ? { provider } : {}), - ...(query !== undefined ? { query } : {}), - }) - ).map(r => r.id); - expect({ provider, query, ids: actual }).toEqual({ provider, query, ids: expected }); - } - }); - - test('non-ASCII Kelvin-sign query omits SQL casing and still matches ASCII stored text via JS lowering', async () => { - const { calls, executor } = createRowsExecutor([ - { id: 'f-1', title: 'kelvin bars', summary: 'x', status: 's', created_at: new Date(TS), trial_refs: [], evidence_refs: [] }, - { id: 'f-2', title: 'other', summary: 'y', status: 's', created_at: new Date(TS), trial_refs: [], evidence_refs: [] }, - ]); - const readers = createPostgresKnowledgeReaders({ executor }); - - const result = await readers.listFindings({ query: 'Kelvin' }); - - expect(result.map(r => r.id)).toEqual(['f-1']); - expect(calls[0]!.text).not.toContain('WHERE'); - expect(calls[0]!.params).toEqual([]); - }); - - test('exact id ignores a non-ASCII query in the JS post-filter too', async () => { - const { calls, executor } = createRowsExecutor([ - { id: 'f-1', title: 'plain', summary: 'plain', status: 's', created_at: new Date(TS), trial_refs: [], evidence_refs: [] }, - ]); - const readers = createPostgresKnowledgeReaders({ executor }); - - const result = await readers.listFindings({ id: 'f-1', query: 'ΚΟΣΜΟΣ' }); - - expect(result.map(r => r.id)).toEqual(['f-1']); - expect(calls[0]!.params).toEqual(['f-1']); - }); - - test('ASCII provider selector excludes ASCII-different and Unicode-different providers after JS check', async () => { - const { executor } = createRowsExecutor([ - { id: 'c-1', provider: 'EODHD', dataset: 'd', caveat: 'c', created_at: new Date(TS) }, - { id: 'c-2', provider: 'EODHD2', dataset: 'd', caveat: 'c', created_at: new Date(TS) }, - { id: 'c-3', provider: 'ЕODHD', dataset: 'd', caveat: 'c', created_at: new Date(TS) }, // Cyrillic Е - ]); - const readers = createPostgresKnowledgeReaders({ executor }); - - expect((await readers.listProviderCaveats({ provider: 'eodhd' })).map(r => r.id)).toEqual(['c-1']); - }); -}); - -describe('PostgreSQL findings adapter QA: timestamps and write params', () => { - function readerForCreatedAt(createdAt: unknown) { - return createPostgresKnowledgeReaders({ - executor: createRowsExecutor([ - { id: 'c-1', provider: 'p', dataset: 'd', caveat: 'c', created_at: createdAt }, - ]).executor, - }); - } - - test.each([ - ['2024-02-29T00:00:00Z', '2024-02-29T00:00:00.000Z'], - ['2000-02-29T23:59:59.5+00:00', '2000-02-29T23:59:59.500Z'], - ['2026-01-01T01:30:00+02:00', '2025-12-31T23:30:00.000Z'], - ['2025-12-31T23:00:00-05:30', '2026-01-01T04:30:00.000Z'], - ['2026-01-15T12:34:56.123999+00:00', '2026-01-15T12:34:56.123Z'], - ['0099-06-01T00:00:00Z', '0099-06-01T00:00:00.000Z'], - ])('accepts valid timezone-qualified instant %s as UTC %s', async (raw, expectedIso) => { - const rows = await readerForCreatedAt(raw).listProviderCaveats({}); - expect(rows[0]!.createdAt).toBe(expectedIso); - }); - - test.each(['2025-02-29T00:00:00Z', '1900-02-29T00:00:00Z', '2026-04-31T00:00:00Z', '2026-00-10T00:00:00Z', '2026-01-15T12:60:00Z', '2026-01-15T12:00:00+05:60', '2026-01-15 12:00:00Z'])( - 'rejects invalid instant %s with INVALID_ROW', - async raw => { - await expect(readerForCreatedAt(raw).listProviderCaveats({})).rejects.toMatchObject({ - name: 'PostgresFindingsError', - code: 'INVALID_ROW', - }); - } - ); - - test('appendFinding binds copies of ref arrays and does not mutate the caller record', async () => { - const { calls, executor } = createRowsExecutor([{ id: 'f-1', created_at: new Date(TS) }]); - const port = createPostgresFindingWritePort({ executor }); - const trialRefs = Object.freeze(['1', '2']); - const evidenceRefs = Object.freeze(['e']); - const record: FiledFindingRecord = Object.freeze({ - id: 'f-1', - kind: 'dead_end', - title: 't', - status: 'pending_review', - createdAt: TS, - summary: 's', - trialRefs, - evidenceRefs, - }); - - const outcome = await port.appendFinding(record, 'k-1'); - - expect(outcome).toEqual({ status: 'created', id: 'f-1', createdAt: TS }); - const params = calls[0]!.params!; - expect(params[6]).toEqual(['1', '2']); - expect(params[6]).not.toBe(trialRefs); - expect(params[7]).not.toBe(evidenceRefs); - expect(params[8]).toBe('k-1'); - }); - - test('replay with identical payload but different status/createdAt still replays the stored receipt', async () => { - let call = 0; - const executor: PostgresFindingsExecutor = { - async query>(): Promise<{ readonly rows: readonly Row[] }> { - call += 1; - const rows = - call === 1 - ? [] - : [ - { - id: 'f-orig', - kind: 'finding', - title: 't', - summary: 's', - created_at: '2026-01-01T00:00:00+01:00', - trial_refs: ['1'], - evidence_refs: [], - }, - ]; - return { rows: rows as unknown as readonly Row[] }; - }, - }; - const port = createPostgresFindingWritePort({ executor }); - - const outcome = await port.appendFinding( - { id: 'f-new', kind: 'finding', title: 't', summary: 's', status: 'other', createdAt: TS, trialRefs: ['1'], evidenceRefs: [] }, - 'k' - ); - - expect(outcome).toEqual({ status: 'replayed', id: 'f-orig', createdAt: '2025-12-31T23:00:00.000Z' }); - }); -}); diff --git a/libs/research/test/mcp-postgres-findings.test.ts b/libs/research/test/mcp-postgres-findings.test.ts deleted file mode 100644 index 6b5ddaf3..00000000 --- a/libs/research/test/mcp-postgres-findings.test.ts +++ /dev/null @@ -1,772 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { - type FiledFindingRecord, - type PostgresFindingsExecutor, - PostgresFindingsError, - createPostgresFindingWritePort, - createPostgresKnowledgeReaders, -} from '../src/mcp/index'; - -interface RecordedCall { - readonly text: string; - readonly params: readonly unknown[] | undefined; -} - -type QueryHandler = ( - text: string, - params: readonly unknown[] | undefined, - callIndex: number -) => Promise<{ readonly rows: readonly Record[] }> | { readonly rows: readonly Record[] }; - -function createSequenceExecutor(handler: QueryHandler): { - readonly calls: RecordedCall[]; - readonly executor: PostgresFindingsExecutor; -} { - const calls: RecordedCall[] = []; - const executor: PostgresFindingsExecutor = { - async query>( - text: string, - params?: readonly unknown[] - ): Promise<{ readonly rows: readonly Row[] }> { - const idx = calls.length; - calls.push({ text, params }); - const res = await handler(text, params, idx); - return res as unknown as { readonly rows: readonly Row[] }; - }, - }; - return { calls, executor }; -} - -function createFakeExecutor(rows: readonly Record[] = []): { - readonly calls: RecordedCall[]; - readonly executor: PostgresFindingsExecutor; -} { - return createSequenceExecutor(() => ({ rows })); -} - -const FIXED_TS = '2026-01-15T12:34:56.789Z'; - -function makeFiledRecord(overrides: Partial = {}): FiledFindingRecord { - return { - id: 'finding-001', - kind: 'finding', - title: 'Momentum decays after 5 sessions', - status: 'pending_review', - createdAt: FIXED_TS, - summary: 'Cross-sectional rank IC turns negative past day 5.', - trialRefs: ['101', '102'], - evidenceRefs: ['snap:2026-01-15:ic'], - ...overrides, - }; -} - -function makeRawFindingRow(overrides: Record = {}): Record { - return { - id: 'finding-001', - title: 'Momentum decays after 5 sessions', - status: 'pending_review', - created_at: new Date(FIXED_TS), - summary: 'Cross-sectional rank IC turns negative past day 5.', - trial_refs: ['101', '102'], - evidence_refs: ['snap:2026-01-15:ic'], - ...overrides, - }; -} - -function makeRawReplayRow(overrides: Record = {}): Record { - return { - id: 'finding-001', - kind: 'finding', - title: 'Momentum decays after 5 sessions', - summary: 'Cross-sectional rank IC turns negative past day 5.', - created_at: new Date(FIXED_TS), - trial_refs: ['101', '102'], - evidence_refs: ['snap:2026-01-15:ic'], - ...overrides, - }; -} - -function makeRawCaveatRow(overrides: Record = {}): Record { - return { - id: 'caveat-001', - provider: 'EODHD', - dataset: 'eodIntraday1M', - caveat: 'Intraday 1m OHLCV is retroactively split-adjusted.', - created_at: new Date(FIXED_TS), - ...overrides, - }; -} - -function assertNoMutationOrReaderLimitSql(calls: readonly RecordedCall[], checkNoLimit = false): void { - for (const call of calls) { - expect(call.text).not.toMatch(/\bUPDATE\b/i); - expect(call.text).not.toMatch(/\bDELETE\b/i); - expect(call.text).not.toMatch(/\bTRUNCATE\b/i); - if (checkNoLimit) { - expect(call.text).not.toMatch(/\bLIMIT\b/i); - } - } -} - -describe('createPostgresFindingWritePort (fake executor)', () => { - test('unkeyed append issues plain parameterized INSERT with NULL key and never interpolates values', async () => { - const injection = "'; DROP TABLE findings; --"; - const fake = createFakeExecutor([{ id: 'finding-inj', created_at: new Date(FIXED_TS) }]); - const port = createPostgresFindingWritePort({ executor: fake.executor }); - - const record = makeFiledRecord({ - id: 'finding-inj', - title: injection, - summary: `summary ${injection}`, - trialRefs: [injection], - evidenceRefs: [`ev:${injection}`], - }); - - const outcome = await port.appendFinding(record); - - expect(outcome).toEqual({ - status: 'created', - id: 'finding-inj', - createdAt: FIXED_TS, - }); - expect(fake.calls).toHaveLength(1); - const call = fake.calls[0]!; - expect(call.text).toContain('INSERT INTO findings'); - expect(call.text).not.toContain('ON CONFLICT'); - expect(call.text).toContain('RETURNING id, created_at'); - expect(call.text).not.toContain(injection); - expect(call.text).not.toContain(';'); - expect(call.params).toEqual([ - 'finding-inj', - 'finding', - injection, - `summary ${injection}`, - 'pending_review', - FIXED_TS, - [injection], - [`ev:${injection}`], - null, - ]); - assertNoMutationOrReaderLimitSql(fake.calls); - }); - - test('keyed append uses partial-index ON CONFLICT DO NOTHING and returns created on 1 returned row', async () => { - const fake = createFakeExecutor([ - { id: 'finding-001', created_at: '2026-01-15T14:34:56.789+02:00' }, - ]); - const port = createPostgresFindingWritePort({ executor: fake.executor }); - - const outcome = await port.appendFinding(makeFiledRecord(), 'idem-key-1'); - - expect(outcome).toEqual({ - status: 'created', - id: 'finding-001', - createdAt: FIXED_TS, - }); - expect(fake.calls).toHaveLength(1); - const call = fake.calls[0]!; - expect(call.text).toContain( - 'ON CONFLICT (idempotency_key) WHERE idempotency_key IS NOT NULL DO NOTHING' - ); - expect(call.text).not.toContain('idem-key-1'); - expect(call.params).toEqual([ - 'finding-001', - 'finding', - 'Momentum decays after 5 sessions', - 'Cross-sectional rank IC turns negative past day 5.', - 'pending_review', - FIXED_TS, - ['101', '102'], - ['snap:2026-01-15:ic'], - 'idem-key-1', - ]); - assertNoMutationOrReaderLimitSql(fake.calls); - }); - - test('keyed append reads winner in separate SELECT on 0 rows and returns replayed with stored metadata', async () => { - const fake = createSequenceExecutor((_text, _params, idx) => { - if (idx === 0) { - return { rows: [] }; - } - return { - rows: [ - makeRawReplayRow({ - id: 'finding-original', - created_at: '2026-01-15T07:34:56.789999-05:00', - }), - ], - }; - }); - const port = createPostgresFindingWritePort({ executor: fake.executor }); - - // Incoming call has a new id and createdAt, but identical comparable payload - const outcome = await port.appendFinding( - makeFiledRecord({ - id: 'finding-retry-new-id', - createdAt: '2026-01-16T00:00:00.000Z', - }), - 'idem-replay' - ); - - expect(outcome).toEqual({ - status: 'replayed', - id: 'finding-original', - createdAt: FIXED_TS, - }); - expect(fake.calls).toHaveLength(2); - expect(fake.calls[1]!.text).toContain('SELECT'); - expect(fake.calls[1]!.text).toContain('WHERE idempotency_key = $1::text'); - expect(fake.calls[1]!.params).toEqual(['idem-replay']); - assertNoMutationOrReaderLimitSql(fake.calls); - }); - - test('keyed append returns conflict when stored payload differs on any comparable field', async () => { - const diffs: readonly Partial[] = [ - { kind: 'dead_end' }, - { title: 'Different title' }, - { summary: 'Different summary' }, - { trialRefs: ['101'] }, - { trialRefs: ['102', '101'] }, - { evidenceRefs: [] }, - ]; - - for (const diff of diffs) { - const fake = createSequenceExecutor((_text, _params, idx) => - idx === 0 ? { rows: [] } : { rows: [makeRawReplayRow()] } - ); - const port = createPostgresFindingWritePort({ executor: fake.executor }); - - const outcome = await port.appendFinding(makeFiledRecord(diff), 'idem-conflict'); - expect(outcome).toEqual({ status: 'conflict' }); - expect(fake.calls).toHaveLength(2); - assertNoMutationOrReaderLimitSql(fake.calls); - } - }); - - test('keyed append resolves same-ID 23505 retry as replayed or conflict, and propagates unrelated 23505 or other errors', async () => { - const pkErr = Object.assign(new Error('duplicate key value violates unique constraint'), { - code: '23505', - }); - - // Same ID + identical payload -> replayed - const fakeReplay = createSequenceExecutor((_text, _params, idx) => { - if (idx === 0) { - throw pkErr; - } - return { rows: [makeRawReplayRow({ id: 'finding-001' })] }; - }); - const replayPort = createPostgresFindingWritePort({ executor: fakeReplay.executor }); - expect(await replayPort.appendFinding(makeFiledRecord(), 'idem-same-id')).toEqual({ - status: 'replayed', - id: 'finding-001', - createdAt: FIXED_TS, - }); - expect(fakeReplay.calls).toHaveLength(2); - - // Same ID + different payload -> conflict - const fakeConflict = createSequenceExecutor((_text, _params, idx) => { - if (idx === 0) { - throw pkErr; - } - return { rows: [makeRawReplayRow({ id: 'finding-001', title: 'Other title' })] }; - }); - const conflictPort = createPostgresFindingWritePort({ executor: fakeConflict.executor }); - expect(await conflictPort.appendFinding(makeFiledRecord(), 'idem-same-id')).toEqual({ - status: 'conflict', - }); - - // Unrelated PK collision: no stored row for idempotency_key -> propagate pkErr - const fakeMissing = createSequenceExecutor((_text, _params, idx) => { - if (idx === 0) { - throw pkErr; - } - return { rows: [] }; - }); - const missingPort = createPostgresFindingWritePort({ executor: fakeMissing.executor }); - await expect(missingPort.appendFinding(makeFiledRecord(), 'idem-unrelated')).rejects.toBe( - pkErr - ); - - // Unrelated PK collision: stored row for idempotency_key has different ID -> propagate pkErr - const fakeDifferentId = createSequenceExecutor((_text, _params, idx) => { - if (idx === 0) { - throw pkErr; - } - return { rows: [makeRawReplayRow({ id: 'finding-other' })] }; - }); - const diffIdPort = createPostgresFindingWritePort({ executor: fakeDifferentId.executor }); - await expect(diffIdPort.appendFinding(makeFiledRecord(), 'idem-other-id')).rejects.toBe(pkErr); - - // Non-23505 error -> propagates immediately without SELECT - const checkErr = Object.assign(new Error('check violation'), { code: '23514' }); - const fakeOther = createSequenceExecutor(() => { - throw checkErr; - }); - const otherPort = createPostgresFindingWritePort({ executor: fakeOther.executor }); - await expect(otherPort.appendFinding(makeFiledRecord(), 'idem-check')).rejects.toBe(checkErr); - expect(fakeOther.calls).toHaveLength(1); - - // Unkeyed 23505 -> propagates immediately without SELECT - const fakeUnkeyed = createSequenceExecutor(() => { - throw pkErr; - }); - const unkeyedPort = createPostgresFindingWritePort({ executor: fakeUnkeyed.executor }); - await expect(unkeyedPort.appendFinding(makeFiledRecord())).rejects.toBe(pkErr); - expect(fakeUnkeyed.calls).toHaveLength(1); - }); - - test('quotes explicit schema on INSERT and replay SELECT, and omits prefix when unset', async () => { - const fakeScoped = createSequenceExecutor((_text, _params, idx) => - idx === 0 ? { rows: [] } : { rows: [makeRawReplayRow()] } - ); - const scopedPort = createPostgresFindingWritePort({ - executor: fakeScoped.executor, - schema: 'custom_research_1', - }); - await scopedPort.appendFinding(makeFiledRecord(), 'idem-schema'); - - expect(fakeScoped.calls[0]!.text).toContain('INSERT INTO "custom_research_1".findings'); - expect(fakeScoped.calls[1]!.text).toContain('FROM "custom_research_1".findings'); - assertNoMutationOrReaderLimitSql(fakeScoped.calls); - }); -}); - -describe('createPostgresKnowledgeReaders (fake executor)', () => { - test('listFindings binds exact id (taking precedence over query), escaped ILIKE query, and unfiltered queries with ORDER BY id ASC and no LIMIT', async () => { - const injection = "'; DELETE FROM findings; --"; - const fake = createFakeExecutor([makeRawFindingRow()]); - const readers = createPostgresKnowledgeReaders({ executor: fake.executor }); - - // Unfiltered - const allRows = await readers.listFindings({}); - expect(allRows).toEqual([ - { - id: 'finding-001', - title: 'Momentum decays after 5 sessions', - status: 'pending_review', - createdAt: FIXED_TS, - summary: 'Cross-sectional rank IC turns negative past day 5.', - trialRefs: ['101', '102'], - evidenceRefs: ['snap:2026-01-15:ic'], - }, - ]); - expect(fake.calls[0]!.text).not.toContain('WHERE'); - expect(fake.calls[0]!.text.trimEnd().endsWith('ORDER BY id ASC')).toBe(true); - expect(fake.calls[0]!.params).toEqual([]); - - // Exact id takes precedence over query - await readers.listFindings({ id: injection, query: 'ignored' }); - expect(fake.calls[1]!.text).toContain('WHERE id = $1::text'); - expect(fake.calls[1]!.text).not.toContain('ILIKE'); - expect(fake.calls[1]!.text).not.toContain(injection); - expect(fake.calls[1]!.params).toEqual([injection]); - - // Escaped ILIKE query on title and summary (retaining non-ASCII stored rows as candidates) - await readers.listFindings({ query: '100% pure_wild\\path' }); - expect(fake.calls[2]!.text).toContain( - "WHERE title ILIKE $1::text ESCAPE '\\' OR summary ILIKE $1::text ESCAPE '\\' OR title ~ '[^\\x01-\\x7f]' OR summary ~ '[^\\x01-\\x7f]'" - ); - expect(fake.calls[2]!.params).toEqual(['%100\\% pure\\_wild\\\\path%']); - - assertNoMutationOrReaderLimitSql(fake.calls, true); - }); - - test('listProviderCaveats combines case-insensitive provider with id or escaped ILIKE query and no LIMIT', async () => { - const fake = createFakeExecutor([ - makeRawCaveatRow({ created_at: '2026-01-15T12:34:56.789Z' }), - ]); - const readers = createPostgresKnowledgeReaders({ - executor: fake.executor, - schema: 'custom_research_2', - }); - - // Unfiltered - const rows = await readers.listProviderCaveats({}); - expect(rows).toEqual([ - { - id: 'caveat-001', - provider: 'EODHD', - dataset: 'eodIntraday1M', - caveat: 'Intraday 1m OHLCV is retroactively split-adjusted.', - createdAt: FIXED_TS, - }, - ]); - expect(fake.calls[0]!.text).toContain('FROM "custom_research_2".provider_caveats'); - expect(fake.calls[0]!.text).not.toContain('WHERE'); - expect(fake.calls[0]!.params).toEqual([]); - - // Provider + exact id (id takes precedence over query) - await readers.listProviderCaveats({ - provider: 'eodhd', - id: 'caveat-001', - query: 'ignored', - }); - expect(fake.calls[1]!.text).toContain( - "WHERE (lower(provider) = lower($1::text) OR provider ~ '[^\\x01-\\x7f]') AND id = $2::text" - ); - expect(fake.calls[1]!.text).not.toContain('ILIKE'); - expect(fake.calls[1]!.params).toEqual(['eodhd', 'caveat-001']); - - // Provider + query with wildcards - await readers.listProviderCaveats({ - provider: 'QuoteMedia', - query: '50%_ratio\\inv', - }); - expect(fake.calls[2]!.text).toContain( - "WHERE (lower(provider) = lower($1::text) OR provider ~ '[^\\x01-\\x7f]') AND (provider ILIKE $2::text ESCAPE '\\' OR dataset ILIKE $2::text ESCAPE '\\' OR caveat ILIKE $2::text ESCAPE '\\' OR provider ~ '[^\\x01-\\x7f]' OR dataset ~ '[^\\x01-\\x7f]' OR caveat ~ '[^\\x01-\\x7f]')" - ); - expect(fake.calls[2]!.params).toEqual(['QuoteMedia', '%50\\%\\_ratio\\\\inv%']); - - // Query only - await readers.listProviderCaveats({ query: 'split' }); - expect(fake.calls[3]!.text).toContain( - "WHERE (provider ILIKE $1::text ESCAPE '\\' OR dataset ILIKE $1::text ESCAPE '\\' OR caveat ILIKE $1::text ESCAPE '\\' OR provider ~ '[^\\x01-\\x7f]' OR dataset ~ '[^\\x01-\\x7f]' OR caveat ~ '[^\\x01-\\x7f]')" - ); - expect(fake.calls[3]!.params).toEqual(['%split%']); - - assertNoMutationOrReaderLimitSql(fake.calls, true); - }); - - test('falls back to JS Unicode lowercasing for non-ASCII query/provider while preserving ASCII SQL pushdown and row validation', async () => { - // Findings: non-ASCII query (Greek final sigma) omits SQL ILIKE and filters with JS .toLowerCase() - const findingFake = createFakeExecutor([ - makeRawFindingRow({ id: 'f-1', title: 'Αλφα κοσμος', summary: 'Greek cosmos finding.' }), - makeRawFindingRow({ id: 'f-2', title: 'Unrelated', summary: 'Does not match.' }), - makeRawFindingRow({ id: 'f-3', title: 'Other', summary: 'Summary has κοσμος too.' }), - ]); - const findingReaders = createPostgresKnowledgeReaders({ executor: findingFake.executor }); - const findingMatches = await findingReaders.listFindings({ query: 'ΚΟΣΜΟΣ' }); - expect(findingMatches.map(r => r.id)).toEqual(['f-1', 'f-3']); - expect(findingFake.calls[0]!.text).not.toContain('ILIKE'); - expect(findingFake.calls[0]!.text).not.toContain('WHERE'); - expect(findingFake.calls[0]!.params).toEqual([]); - - // Provider caveats: ASCII provider still pushes down SQL lower(provider), non-ASCII query filters in JS - const caveatFake = createFakeExecutor([ - makeRawCaveatRow({ id: 'c-1', provider: 'EODHD', caveat: 'Note on κοσμος regime.' }), - makeRawCaveatRow({ id: 'c-2', provider: 'EODHD', caveat: 'Unrelated note.' }), - ]); - const caveatReaders = createPostgresKnowledgeReaders({ executor: caveatFake.executor }); - const caveatMatches = await caveatReaders.listProviderCaveats({ - provider: 'eodhd', - query: 'ΚΟΣΜΟΣ', - }); - expect(caveatMatches.map(r => r.id)).toEqual(['c-1']); - expect(caveatFake.calls[0]!.text).toContain( - "WHERE (lower(provider) = lower($1::text) OR provider ~ '[^\\x01-\\x7f]')" - ); - expect(caveatFake.calls[0]!.text).not.toContain('ILIKE'); - expect(caveatFake.calls[0]!.params).toEqual(['eodhd']); - - // Provider caveats: non-ASCII provider falls back to JS exact case-insensitive match - const nonAsciiProvFake = createFakeExecutor([ - makeRawCaveatRow({ id: 'c-1', provider: 'κοσμος', dataset: 'ds', caveat: 'c' }), - makeRawCaveatRow({ id: 'c-2', provider: 'EODHD', dataset: 'ds', caveat: 'c' }), - ]); - const nonAsciiProvReaders = createPostgresKnowledgeReaders({ - executor: nonAsciiProvFake.executor, - }); - const provMatches = await nonAsciiProvReaders.listProviderCaveats({ provider: 'ΚΟΣΜΟΣ' }); - expect(provMatches.map(r => r.id)).toEqual(['c-1']); - expect(nonAsciiProvFake.calls[0]!.text).not.toContain('WHERE'); - expect(nonAsciiProvFake.calls[0]!.params).toEqual([]); - - // ASCII query / ASCII provider against Unicode stored rows (e.g. BİST and K under C collation): - // SQL retains non-ASCII stored rows as candidates and JS .toLowerCase() filters out non-matches. - const asciiAgainstUnicodeFindingFake = createFakeExecutor([ - makeRawFindingRow({ - id: 'f-bist', - title: 'BİST exchange coverage', - summary: 'Turkish equities.', - }), - makeRawFindingRow({ - id: 'f-other-unicode', - title: 'κόσμος', - summary: 'Unrelated Greek finding.', - }), - ]); - const asciiFindingReaders = createPostgresKnowledgeReaders({ - executor: asciiAgainstUnicodeFindingFake.executor, - }); - expect((await asciiFindingReaders.listFindings({ query: 'bi' })).map(r => r.id)).toEqual([ - 'f-bist', - ]); - - const asciiAgainstUnicodeCaveatFake = createFakeExecutor([ - makeRawCaveatRow({ - id: 'c-kelvin', - provider: 'K', - dataset: 'ds', - caveat: 'BİST feed note.', - }), - makeRawCaveatRow({ - id: 'c-other-unicode', - provider: 'κόσμος', - dataset: 'ds', - caveat: 'Unrelated.', - }), - ]); - const asciiCaveatReaders = createPostgresKnowledgeReaders({ - executor: asciiAgainstUnicodeCaveatFake.executor, - }); - expect( - (await asciiCaveatReaders.listProviderCaveats({ provider: 'k', query: 'bi' })).map(r => r.id) - ).toEqual(['c-kelvin']); - - assertNoMutationOrReaderLimitSql( - [ - ...findingFake.calls, - ...caveatFake.calls, - ...nonAsciiProvFake.calls, - ...asciiAgainstUnicodeFindingFake.calls, - ...asciiAgainstUnicodeCaveatFake.calls, - ], - true - ); - }); -}); - -describe('PostgreSQL findings adapter validation (fake executor)', () => { - test('rejects invalid executors and options with INVALID_EXECUTOR before any query', () => { - const invalidOptions: unknown[] = [ - null, - undefined, - {}, - { executor: null }, - { executor: {} }, - { executor: { query: 'not-a-fn' } }, - ]; - - for (const opts of invalidOptions) { - for (const factory of [createPostgresFindingWritePort, createPostgresKnowledgeReaders]) { - let caught: unknown; - try { - factory(opts as Parameters[0]); - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(PostgresFindingsError); - expect((caught as PostgresFindingsError).code).toBe('INVALID_EXECUTOR'); - } - } - }); - - test('rejects invalid schema names with INVALID_SCHEMA before any query', () => { - const fake = createFakeExecutor([]); - const badSchemas: unknown[] = [ - '', - 'Public', - '1schema', - 'bad-name', - 'bad.name', - 'public"; DROP TABLE findings; --', - 'space name', - 123, - null, - ]; - - for (const schema of badSchemas) { - for (const factory of [createPostgresFindingWritePort, createPostgresKnowledgeReaders]) { - let caught: unknown; - try { - factory({ executor: fake.executor, schema: schema as string }); - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(PostgresFindingsError); - expect((caught as PostgresFindingsError).code).toBe('INVALID_SCHEMA'); - } - } - - expect(fake.calls).toHaveLength(0); - }); - - test('accepts prototype-method executors', async () => { - class ProtoExecutor { - async query>(): Promise<{ readonly rows: readonly Row[] }> { - return { rows: [makeRawFindingRow()] as unknown as readonly Row[] }; - } - } - const readers = createPostgresKnowledgeReaders({ executor: new ProtoExecutor() }); - const rows = await readers.listFindings({}); - expect(rows).toHaveLength(1); - expect(rows[0]!.id).toBe('finding-001'); - }); - - test('rejects invalid result envelopes and missing/duplicate receipt or winner rows with INVALID_ROW', async () => { - const badEnvelopeExecutor: PostgresFindingsExecutor = { - async query() { - return { rows: 'not-an-array' as unknown as readonly never[] }; - }, - }; - const badWritePort = createPostgresFindingWritePort({ executor: badEnvelopeExecutor }); - const badReaders = createPostgresKnowledgeReaders({ executor: badEnvelopeExecutor }); - - for (const op of [ - () => badWritePort.appendFinding(makeFiledRecord()), - () => badWritePort.appendFinding(makeFiledRecord(), 'k1'), - () => badReaders.listFindings({}), - () => badReaders.listProviderCaveats({}), - ]) { - let caught: unknown; - try { - await op(); - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(PostgresFindingsError); - expect((caught as PostgresFindingsError).code).toBe('INVALID_ROW'); - } - - // Unkeyed insert returning 0 rows or 2 rows - for (const rows of [[], [{ id: 'a', created_at: FIXED_TS }, { id: 'b', created_at: FIXED_TS }]]) { - const port = createPostgresFindingWritePort({ executor: createFakeExecutor(rows).executor }); - await expect(port.appendFinding(makeFiledRecord())).rejects.toMatchObject({ - name: 'PostgresFindingsError', - code: 'INVALID_ROW', - }); - } - - // Keyed insert returning 2 rows - const dupInsertPort = createPostgresFindingWritePort({ - executor: createFakeExecutor([ - { id: 'a', created_at: FIXED_TS }, - { id: 'b', created_at: FIXED_TS }, - ]).executor, - }); - await expect(dupInsertPort.appendFinding(makeFiledRecord(), 'k-dup')).rejects.toMatchObject({ - name: 'PostgresFindingsError', - code: 'INVALID_ROW', - }); - - // Keyed conflict lookup returning 0 rows or 2 rows - for (const lookupRows of [[], [makeRawReplayRow(), makeRawReplayRow({ id: 'finding-002' })]]) { - const fake = createSequenceExecutor((_t, _p, idx) => - idx === 0 ? { rows: [] } : { rows: lookupRows } - ); - const port = createPostgresFindingWritePort({ executor: fake.executor }); - await expect(port.appendFinding(makeFiledRecord(), 'k-missing-or-dup')).rejects.toMatchObject( - { - name: 'PostgresFindingsError', - code: 'INVALID_ROW', - } - ); - } - - // 23505 lookup returning 2 rows - const pkErr = Object.assign(new Error('dup'), { code: '23505' }); - const fakeDup23505 = createSequenceExecutor((_t, _p, idx) => { - if (idx === 0) { - throw pkErr; - } - return { rows: [makeRawReplayRow(), makeRawReplayRow({ id: 'finding-002' })] }; - }); - const dup23505Port = createPostgresFindingWritePort({ executor: fakeDup23505.executor }); - await expect(dup23505Port.appendFinding(makeFiledRecord(), 'k-dup-23505')).rejects.toMatchObject( - { - name: 'PostgresFindingsError', - code: 'INVALID_ROW', - } - ); - }); - - test('rejects malformed timestamps, invalid kinds on replay, and non-string or nested arrays with INVALID_ROW', async () => { - const badTimestamps: readonly unknown[] = [ - null, - 1700000000000, - new Date(Number.NaN), - '', - '2026-01-15', - '2026-01-15T12:34:56', - '2026-02-30T00:00:00Z', - '2026-01-15T24:00:00Z', - '2026-01-15T12:00:00+25:00', - 'not-a-timestamp', - ]; - - for (const badTs of badTimestamps) { - const findingReaders = createPostgresKnowledgeReaders({ - executor: createFakeExecutor([makeRawFindingRow({ created_at: badTs })]).executor, - }); - await expect(findingReaders.listFindings({})).rejects.toMatchObject({ - name: 'PostgresFindingsError', - code: 'INVALID_ROW', - }); - - const caveatReaders = createPostgresKnowledgeReaders({ - executor: createFakeExecutor([makeRawCaveatRow({ created_at: badTs })]).executor, - }); - await expect(caveatReaders.listProviderCaveats({})).rejects.toMatchObject({ - name: 'PostgresFindingsError', - code: 'INVALID_ROW', - }); - } - - // Invalid kind on replay - for (const badKind of ['hypothesis', 'FINDING', '', null, 42]) { - const fake = createSequenceExecutor((_t, _p, idx) => - idx === 0 ? { rows: [] } : { rows: [makeRawReplayRow({ kind: badKind })] } - ); - const port = createPostgresFindingWritePort({ executor: fake.executor }); - await expect(port.appendFinding(makeFiledRecord(), 'k-bad-kind')).rejects.toMatchObject({ - name: 'PostgresFindingsError', - code: 'INVALID_ROW', - }); - } - - // Invalid ref arrays (nested arrays, null elements, non-arrays) - const badArrays: readonly unknown[] = [null, '101', [101], ['101', null], [['101']]]; - for (const badArr of badArrays) { - const readers = createPostgresKnowledgeReaders({ - executor: createFakeExecutor([makeRawFindingRow({ trial_refs: badArr })]).executor, - }); - await expect(readers.listFindings({})).rejects.toMatchObject({ - name: 'PostgresFindingsError', - code: 'INVALID_ROW', - }); - - const readersEv = createPostgresKnowledgeReaders({ - executor: createFakeExecutor([makeRawFindingRow({ evidence_refs: badArr })]).executor, - }); - await expect(readersEv.listFindings({})).rejects.toMatchObject({ - name: 'PostgresFindingsError', - code: 'INVALID_ROW', - }); - } - - // Non-object rows & blank strings - const badFindingRows: readonly unknown[] = [ - null, - makeRawFindingRow({ id: ' ' }), - makeRawFindingRow({ title: '' }), - makeRawFindingRow({ status: null }), - makeRawFindingRow({ summary: '' }), - ]; - for (const badRow of badFindingRows) { - const readers = createPostgresKnowledgeReaders({ - executor: createFakeExecutor([badRow as Record]).executor, - }); - await expect(readers.listFindings({})).rejects.toMatchObject({ - name: 'PostgresFindingsError', - code: 'INVALID_ROW', - }); - } - - const badCaveatRows: readonly unknown[] = [ - null, - makeRawCaveatRow({ id: '' }), - makeRawCaveatRow({ provider: ' ' }), - makeRawCaveatRow({ dataset: '' }), - makeRawCaveatRow({ caveat: null }), - ]; - for (const badRow of badCaveatRows) { - const readers = createPostgresKnowledgeReaders({ - executor: createFakeExecutor([badRow as Record]).executor, - }); - await expect(readers.listProviderCaveats({})).rejects.toMatchObject({ - name: 'PostgresFindingsError', - code: 'INVALID_ROW', - }); - } - }); -}); diff --git a/libs/research/test/mcp-postgres-symbol-search.test.ts b/libs/research/test/mcp-postgres-symbol-search.test.ts deleted file mode 100644 index d4fb71c5..00000000 --- a/libs/research/test/mcp-postgres-symbol-search.test.ts +++ /dev/null @@ -1,489 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { MarketDataStoreValidationError } from '../src/market-data-store'; -import { - createPostgresSymbolSearchPort, - PostgresSymbolSearchError, - type SymbolSearchExecutor, - type SymbolSearchQuery, -} from '../src/mcp/index'; - -interface RecordedCall { - readonly text: string; - readonly params: readonly unknown[] | undefined; -} - -function createFakeExecutor(rows: readonly Record[] = []): { - readonly calls: RecordedCall[]; - readonly executor: SymbolSearchExecutor; -} { - const calls: RecordedCall[] = []; - const executor: SymbolSearchExecutor = { - async query>( - text: string, - params?: readonly unknown[] - ): Promise<{ readonly rows: readonly Row[] }> { - calls.push({ text, params }); - return { rows: rows as readonly Row[] }; - }, - }; - return { calls, executor }; -} - -function makeRawRow(overrides: Record = {}): Record { - return { - listing_id: 101, - instrument_id: 1001, - ticker: 'ACME', - class_suffix: '', - name: 'Acme Corporation', - mic: 'XNAS', - currency: 'USD', - isin: 'US0000001015', - first_bar_date: '2018-01-02', - last_bar_date: '2024-06-28', - delisted_at: null, - ...overrides, - }; -} - -const BASE_QUERY: SymbolSearchQuery = { - query: 'ACME', - limit: 20, - includeDelisted: true, - vaultCutoffTs: Date.UTC(2024, 5, 30, 0, 0, 0, 0), // 2024-06-30T00:00:00.000Z -}; - -describe('createPostgresSymbolSearchPort (fake executor)', () => { - test('issues a single parameterized SELECT and never interpolates injection-shaped queries', async () => { - const injection = "'; DROP TABLE listing; --"; - const fake = createFakeExecutor([makeRawRow()]); - const port = createPostgresSymbolSearchPort({ executor: fake.executor }); - - await port.searchSymbols({ - ...BASE_QUERY, - query: injection, - }); - - expect(fake.calls).toHaveLength(1); - const call = fake.calls[0]!; - expect(call.text.trimStart().startsWith('SELECT')).toBe(true); - expect(call.text).not.toContain(';'); - expect(call.text).not.toContain(injection); - expect(call.text).not.toContain('DROP TABLE'); - expect(call.params).toEqual(['2024-06-30', `%${injection}%`, injection, null, true]); - }); - - test('escapes %, _, and backslash literals in the ILIKE pattern while preserving raw query for ISIN', async () => { - const fake = createFakeExecutor([]); - const port = createPostgresSymbolSearchPort({ executor: fake.executor }); - - await port.searchSymbols({ - ...BASE_QUERY, - query: 'A%B_C\\D', - }); - - expect(fake.calls).toHaveLength(1); - const call = fake.calls[0]!; - expect(call.text).toContain("ESCAPE '\\'"); - expect(call.params).toEqual(['2024-06-30', '%A\\%B\\_C\\\\D%', 'A%B_C\\D', null, true]); - }); - - test('converts vaultCutoffTs epoch-ms to UTC calendar date across midnight boundaries', async () => { - const fake = createFakeExecutor([]); - const port = createPostgresSymbolSearchPort({ executor: fake.executor }); - - await port.searchSymbols({ - ...BASE_QUERY, - vaultCutoffTs: Date.UTC(2024, 5, 30, 23, 59, 59, 999), - }); - await port.searchSymbols({ - ...BASE_QUERY, - vaultCutoffTs: Date.UTC(2024, 6, 1, 0, 0, 0, 0), - }); - - expect(fake.calls).toHaveLength(2); - expect(fake.calls[0]!.params?.[0]).toBe('2024-06-30'); - expect(fake.calls[1]!.params?.[0]).toBe('2024-07-01'); - }); - - test('binds optional country filter and both includeDelisted flags', async () => { - const fake = createFakeExecutor([]); - const port = createPostgresSymbolSearchPort({ executor: fake.executor }); - - await port.searchSymbols({ - ...BASE_QUERY, - country: 'CA', - includeDelisted: false, - }); - await port.searchSymbols({ - ...BASE_QUERY, - country: 'US', - includeDelisted: true, - }); - - expect(fake.calls).toHaveLength(2); - expect(fake.calls[0]!.params?.[3]).toBe('CA'); - expect(fake.calls[0]!.params?.[4]).toBe(false); - expect(fake.calls[1]!.params?.[3]).toBe('US'); - expect(fake.calls[1]!.params?.[4]).toBe(true); - }); - - test('ignores q.limit in SQL and returns all candidates without truncation', async () => { - const rows = [ - makeRawRow({ listing_id: 1, instrument_id: 10, ticker: 'AA' }), - makeRawRow({ listing_id: 2, instrument_id: 20, ticker: 'AAB' }), - makeRawRow({ listing_id: 3, instrument_id: 30, ticker: 'AAC' }), - ]; - const fake = createFakeExecutor(rows); - const port = createPostgresSymbolSearchPort({ executor: fake.executor }); - - const r1 = await port.searchSymbols({ ...BASE_QUERY, limit: 1 }); - const r2 = await port.searchSymbols({ ...BASE_QUERY, limit: 100 }); - - expect(r1).toHaveLength(3); - expect(r2).toHaveLength(3); - expect(fake.calls[0]!.text).toBe(fake.calls[1]!.text); - expect(fake.calls[0]!.params).toEqual(fake.calls[1]!.params); - // Outer query has ORDER BY listing_id ASC with no outer LIMIT clause - expect(fake.calls[0]!.text.trimEnd().endsWith('ORDER BY l.listing_id ASC')).toBe(true); - }); - - test('gates ticker_root fallback and matching on cutoff-aware history suppression and derives delisted_at', async () => { - const fake = createFakeExecutor([]); - const port = createPostgresSymbolSearchPort({ executor: fake.executor }); - - await port.searchSymbols(BASE_QUERY); - - const sql = fake.calls[0]!.text; - // Root-suppression subquery checks upper(ticker) = upper(ticker_root) and cutoff $1::date - expect(sql).toContain('upper(h_any.ticker) = upper(l.ticker_root)'); - expect(sql).toContain('upper(h_past.ticker) = upper(l.ticker_root)'); - expect(sql).toContain('h_past.valid_from <= $1::date'); - // Both fallback resolution and root ILIKE predicate are gated by NOT root_state.is_future - expect(sql).toContain('WHEN NOT root_state.is_future THEN l.ticker_root'); - expect(sql).toContain( - "OR (NOT root_state.is_future AND l.ticker_root ILIKE $2::text ESCAPE '\\')" - ); - // delisted_at derivation and $5 filter - expect(sql).toContain( - "WHEN l.delist_reason IS NOT NULL AND l.delist_reason <> 'active' THEN l.listed_to" - ); - expect(sql).toContain( - '($5::boolean OR delisted.delisted_at IS NULL OR delisted.delisted_at > $1::date)' - ); - }); - - test('quotes optional validated schema on all security-master tables and omits prefix when unset', async () => { - const fakeDefault = createFakeExecutor([]); - const defaultPort = createPostgresSymbolSearchPort({ executor: fakeDefault.executor }); - await defaultPort.searchSymbols(BASE_QUERY); - expect(fakeDefault.calls[0]!.text).toContain('FROM listing l'); - expect(fakeDefault.calls[0]!.text).toContain('INNER JOIN instrument i'); - expect(fakeDefault.calls[0]!.text).toContain('INNER JOIN exchange e'); - expect(fakeDefault.calls[0]!.text).toContain('FROM listing_symbol_history'); - - const fakeScoped = createFakeExecutor([]); - const scopedPort = createPostgresSymbolSearchPort({ - executor: fakeScoped.executor, - schema: 'custom_master_1', - }); - await scopedPort.searchSymbols(BASE_QUERY); - expect(fakeScoped.calls[0]!.text).toContain('FROM "custom_master_1".listing l'); - expect(fakeScoped.calls[0]!.text).toContain('INNER JOIN "custom_master_1".instrument i'); - expect(fakeScoped.calls[0]!.text).toContain('INNER JOIN "custom_master_1".exchange e'); - expect(fakeScoped.calls[0]!.text).toContain('FROM "custom_master_1".listing_symbol_history'); - }); - - test('maps raw rows into SymbolSearchRow with classSuffix, ISIN trimming, nullable dates, and delistedAt', async () => { - const fake = createFakeExecutor([ - makeRawRow({ - listing_id: 101, - instrument_id: 501, - ticker: 'ACME', - class_suffix: '', - name: 'Acme Corp', - mic: 'XNAS', - currency: 'USD ', - isin: ' US0000001015 ', - first_bar_date: '2020-02-29', - last_bar_date: '2024-06-28', - delisted_at: null, - }), - makeRawRow({ - listing_id: 102, - instrument_id: 502, - ticker: 'BRK', - class_suffix: 'B', - name: 'Berkshire Example', - mic: 'XNYS', - currency: 'USD', - isin: ' ', - first_bar_date: null, - last_bar_date: '2023-12-15', - delisted_at: '2023-12-15', - }), - makeRawRow({ - listing_id: 103, - instrument_id: 503, - ticker: 'NULLY', - class_suffix: null, - name: 'Nullable Fields Co', - mic: 'XTSE', - currency: 'CAD', - isin: null, - first_bar_date: null, - last_bar_date: null, - delisted_at: null, - }), - ]); - - const port = createPostgresSymbolSearchPort({ executor: fake.executor }); - const rows = await port.searchSymbols(BASE_QUERY); - - expect(rows).toEqual([ - { - listingId: 101, - instrumentId: 501, - ticker: 'ACME', - classSuffix: null, - name: 'Acme Corp', - mic: 'XNAS', - currency: 'USD', - isin: 'US0000001015', - firstBarDate: '2020-02-29', - lastBarDate: '2024-06-28', - delistedAt: null, - }, - { - listingId: 102, - instrumentId: 502, - ticker: 'BRK', - classSuffix: 'B', - name: 'Berkshire Example', - mic: 'XNYS', - currency: 'USD', - isin: null, - firstBarDate: null, - lastBarDate: '2023-12-15', - delistedAt: '2023-12-15', - }, - { - listingId: 103, - instrumentId: 503, - ticker: 'NULLY', - classSuffix: null, - name: 'Nullable Fields Co', - mic: 'XTSE', - currency: 'CAD', - isin: null, - firstBarDate: null, - lastBarDate: null, - delistedAt: null, - }, - ]); - }); - - test('rejects invalid executors and options with INVALID_EXECUTOR before any query', () => { - const invalidOptions: unknown[] = [ - null, - undefined, - {}, - { executor: null }, - { executor: {} }, - { executor: { query: 'not-a-fn' } }, - ]; - - for (const opts of invalidOptions) { - let caught: unknown; - try { - createPostgresSymbolSearchPort( - opts as Parameters[0] - ); - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(PostgresSymbolSearchError); - expect((caught as PostgresSymbolSearchError).code).toBe('INVALID_EXECUTOR'); - } - }); - - test('rejects invalid schema names with INVALID_SCHEMA before any query', () => { - const fake = createFakeExecutor([]); - const badSchemas: unknown[] = [ - '', - 'Public', - '1schema', - 'bad-name', - 'bad.name', - 'public"; DROP TABLE listing; --', - 'space name', - 123, - null, - ]; - - for (const schema of badSchemas) { - let caught: unknown; - try { - createPostgresSymbolSearchPort({ - executor: fake.executor, - schema: schema as string, - }); - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(PostgresSymbolSearchError); - expect((caught as PostgresSymbolSearchError).code).toBe('INVALID_SCHEMA'); - } - - expect(fake.calls).toHaveLength(0); - }); - - test('rejects invalid vaultCutoffTs before executing any query', async () => { - const fake = createFakeExecutor([]); - const port = createPostgresSymbolSearchPort({ executor: fake.executor }); - - await expect( - port.searchSymbols({ ...BASE_QUERY, vaultCutoffTs: Number.NaN }) - ).rejects.toBeInstanceOf(MarketDataStoreValidationError); - expect(fake.calls).toHaveLength(0); - }); - - test('rejects malformed rows (fractional/unsafe IDs, malformed/impossible dates, invalid types) with INVALID_ROW', async () => { - const badRows: readonly Record[] = [ - makeRawRow({ listing_id: 1.5 }), - makeRawRow({ listing_id: Number.MAX_SAFE_INTEGER + 1 }), - makeRawRow({ listing_id: '101' }), - makeRawRow({ listing_id: Number.NaN }), - makeRawRow({ instrument_id: 2.25 }), - makeRawRow({ instrument_id: Number.POSITIVE_INFINITY }), - makeRawRow({ ticker: '' }), - makeRawRow({ ticker: null }), - makeRawRow({ name: '' }), - makeRawRow({ mic: null }), - makeRawRow({ currency: '' }), - makeRawRow({ class_suffix: 42 }), - makeRawRow({ isin: 12345 }), - makeRawRow({ first_bar_date: '2024-6-1' }), - makeRawRow({ first_bar_date: '2023-02-29' }), - makeRawRow({ last_bar_date: '2024-02-30' }), - makeRawRow({ last_bar_date: '2024-13-01' }), - makeRawRow({ delisted_at: '2024-06-30T00:00:00Z' }), - makeRawRow({ delisted_at: new Date('2024-06-30T00:00:00Z') }), - ]; - - for (const badRow of badRows) { - const fake = createFakeExecutor([badRow]); - const port = createPostgresSymbolSearchPort({ executor: fake.executor }); - - let caught: unknown; - try { - await port.searchSymbols(BASE_QUERY); - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(PostgresSymbolSearchError); - expect((caught as PostgresSymbolSearchError).code).toBe('INVALID_ROW'); - } - - // Non-object row / invalid result shape - const nullRowExecutor: SymbolSearchExecutor = { - async query>() { - return { rows: [null as unknown as Row] }; - }, - }; - const portNullRow = createPostgresSymbolSearchPort({ executor: nullRowExecutor }); - await expect(portNullRow.searchSymbols(BASE_QUERY)).rejects.toBeInstanceOf( - PostgresSymbolSearchError - ); - - const badResultExecutor: SymbolSearchExecutor = { - async query() { - return { rows: 'not-an-array' as unknown as readonly never[] }; - }, - }; - const portBadResult = createPostgresSymbolSearchPort({ executor: badResultExecutor }); - await expect(portBadResult.searchSymbols(BASE_QUERY)).rejects.toBeInstanceOf( - PostgresSymbolSearchError - ); - }); -}); - -describe('createPostgresSymbolSearchPort (QA edge cases)', () => { - test('accepts a pg.Pool-shaped executor whose query method lives on the prototype', async () => { - class PrototypeExecutor { - readonly calls: RecordedCall[] = []; - async query>( - text: string, - params?: readonly unknown[] - ): Promise<{ readonly rows: readonly Row[] }> { - this.calls.push({ text, params }); - return { rows: [makeRawRow()] as unknown as readonly Row[] }; - } - } - const executor = new PrototypeExecutor(); - const port = createPostgresSymbolSearchPort({ executor }); - - const rows = await port.searchSymbols(BASE_QUERY); - - expect(rows.map(r => r.listingId)).toEqual([101]); - expect(executor.calls).toHaveLength(1); - }); - - test('accepts minimal valid schema identifiers and quotes them', async () => { - for (const schema of ['_', 'a', 'stock_bot_safety_0abc']) { - const fake = createFakeExecutor([]); - const port = createPostgresSymbolSearchPort({ executor: fake.executor, schema }); - await port.searchSymbols(BASE_QUERY); - expect(fake.calls[0]!.text).toContain(`FROM "${schema}".listing l`); - } - }); - - test('propagates executor failures unchanged without retrying', async () => { - const failure = new Error('connection terminated'); - let attempts = 0; - const executor: SymbolSearchExecutor = { - async query() { - attempts += 1; - throw failure; - }, - }; - const port = createPostgresSymbolSearchPort({ executor }); - - await expect(port.searchSymbols(BASE_QUERY)).rejects.toBe(failure); - expect(attempts).toBe(1); - }); - - test('binds the UTC calendar date for an instant that is already the next day east of UTC', async () => { - const fake = createFakeExecutor([]); - const port = createPostgresSymbolSearchPort({ executor: fake.executor }); - - // 2024-02-29T23:30Z is 2024-03-01 in UTC+1 zones; the adapter must still bind the UTC date. - await port.searchSymbols({ ...BASE_QUERY, vaultCutoffTs: Date.UTC(2024, 1, 29, 23, 30) }); - - expect(fake.calls[0]!.params?.[0]).toBe('2024-02-29'); - }); - - test('returns an empty array (not null) when the executor returns no rows', async () => { - const fake = createFakeExecutor([]); - const port = createPostgresSymbolSearchPort({ executor: fake.executor }); - - expect(await port.searchSymbols(BASE_QUERY)).toEqual([]); - }); - - test('rejects the whole result when any row in a batch is malformed', async () => { - const fake = createFakeExecutor([ - makeRawRow(), - makeRawRow({ listing_id: 102, last_bar_date: '2024-04-31' }), - ]); - const port = createPostgresSymbolSearchPort({ executor: fake.executor }); - - let caught: unknown; - try { - await port.searchSymbols(BASE_QUERY); - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(PostgresSymbolSearchError); - expect((caught as PostgresSymbolSearchError).code).toBe('INVALID_ROW'); - }); -}); diff --git a/libs/research/test/mcp-postgres-trial-ref-qa.test.ts b/libs/research/test/mcp-postgres-trial-ref-qa.test.ts deleted file mode 100644 index f4cf1d66..00000000 --- a/libs/research/test/mcp-postgres-trial-ref-qa.test.ts +++ /dev/null @@ -1,263 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { - createFileFindingTool, - createPostgresTrialRefPort, - FILE_FINDING_ERROR_FILING_FAILED, - FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF, - PostgresTrialRefError, - type AppendFindingResult, - type FiledFindingRecord, - type FindingWritePort, - type PostgresTrialRefPortOptions, - type TrialRefExecutor, -} from '../src/mcp/index'; - -interface RecordedCall { - readonly text: string; - readonly params: readonly unknown[] | undefined; -} - -function scriptedExecutor(respond: (params: readonly unknown[] | undefined) => unknown): { - readonly calls: RecordedCall[]; - readonly executor: TrialRefExecutor; -} { - const calls: RecordedCall[] = []; - return { - calls, - executor: { - async query>( - text: string, - params?: readonly unknown[] - ): Promise<{ readonly rows: readonly Row[] }> { - calls.push({ text, params }); - return respond(params) as { readonly rows: readonly Row[] }; - }, - }, - }; -} - -function recordingWritePort(): { - readonly appended: FiledFindingRecord[]; - readonly port: FindingWritePort; -} { - const appended: FiledFindingRecord[] = []; - return { - appended, - port: { - async appendFinding(record): Promise { - appended.push(record); - return { status: 'created', id: record.id, createdAt: record.createdAt }; - }, - }, - }; -} - -const CUTOFF_TS = Date.UTC(2025, 5, 30, 15, 45, 30, 500); // 2025-06-30T15:45:30.500Z -const CUTOFF_DATE = '2025-06-30'; -const FIXED_EPOCH_MS = Date.UTC(2026, 0, 15, 12, 0, 0); - -describe('createPostgresTrialRefPort QA edge cases', () => { - test('snapshots executor, schema and cutoff at construction so later option mutation has no effect', async () => { - const original = scriptedExecutor(() => ({ rows: [] })); - const replacement = scriptedExecutor(() => ({ rows: [{ visible: 1 }] })); - const options: { - -readonly [K in keyof PostgresTrialRefPortOptions]: PostgresTrialRefPortOptions[K]; - } = { - executor: original.executor, - vaultCutoffTs: CUTOFF_TS, - schema: 'research_a', - }; - const port = createPostgresTrialRefPort(options); - - options.executor = replacement.executor; - options.vaultCutoffTs = Date.UTC(2030, 0, 1); - options.schema = 'research_b'; - - expect(await port.hasResearchVisibleTrial('5')).toBe(false); - expect(replacement.calls).toHaveLength(0); - expect(original.calls).toEqual([ - { - text: 'SELECT 1 AS visible FROM "research_a".trial_ledger WHERE trial_id = $1::bigint AND sample_end < $2::date LIMIT 1', - params: ['5', CUTOFF_DATE], - }, - ]); - }); - - test('binds UTC dates for epoch, pre-1970 and four-digit-year extreme cutoffs', async () => { - const cases: [number, string][] = [ - [0, '1970-01-01'], - [-1, '1969-12-31'], - [Date.UTC(2025, 5, 30, 0, 0, 0, 0), '2025-06-30'], - [Date.UTC(2025, 5, 30, 23, 59, 59, 999), '2025-06-30'], - [new Date('0001-01-01T00:00:00.000Z').getTime(), '0001-01-01'], - [new Date('9999-12-31T23:59:59.999Z').getTime(), '9999-12-31'], - ]; - - for (const [vaultCutoffTs, expectedDate] of cases) { - const fake = scriptedExecutor(() => ({ rows: [] })); - const port = createPostgresTrialRefPort({ executor: fake.executor, vaultCutoffTs }); - expect(await port.hasResearchVisibleTrial('1')).toBe(false); - expect(fake.calls[0]?.params).toEqual(['1', expectedDate]); - } - }); - - test('reports INVALID_EXECUTOR before schema or cutoff errors when several options are invalid', () => { - let caught: unknown; - try { - createPostgresTrialRefPort({ - executor: {} as TrialRefExecutor, - vaultCutoffTs: Number.NaN, - schema: 'Bad-Schema', - }); - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(PostgresTrialRefError); - expect(caught).toBeInstanceOf(RangeError); - expect((caught as PostgresTrialRefError).code).toBe('INVALID_EXECUTOR'); - expect((caught as PostgresTrialRefError).name).toBe('PostgresTrialRefError'); - }); - - test('queries every canonical id across the 1..19 digit range up to the PostgreSQL bigint max', async () => { - const fake = scriptedExecutor(() => ({ rows: [{ visible: 1 }] })); - const port = createPostgresTrialRefPort({ executor: fake.executor, vaultCutoffTs: CUTOFF_TS }); - const accepted = [ - '1', - '9', - '10', - '999999999999999999', - '1000000000000000000', - '9223372036854775799', - '9223372036854775806', - '9223372036854775807', - ]; - - for (const ref of accepted) { - expect(await port.hasResearchVisibleTrial(ref)).toBe(true); - } - expect(fake.calls.map(call => call.params?.[0])).toEqual(accepted); - }); - - test('returns false without querying for out-of-range, unicode-digit, control-char and boxed refs', async () => { - const fake = scriptedExecutor(() => ({ rows: [{ visible: 1 }] })); - const port = createPostgresTrialRefPort({ executor: fake.executor, vaultCutoffTs: CUTOFF_TS }); - const rejected: unknown[] = [ - '9223372036854775810', - '9300000000000000000', - '12345678901234567890', - '١', // Arabic-Indic digit one - '1', // full-width digit one - '1\u0000', - ' 1', - '1​', - new String('1'), - Number.MAX_SAFE_INTEGER, - ]; - - for (const ref of rejected) { - expect(await port.hasResearchVisibleTrial(ref as string)).toBe(false); - } - expect(fake.calls).toHaveLength(0); - }); - - test('concurrent lookups each issue their own query and keep their own answers', async () => { - const fake = scriptedExecutor(params => ({ - rows: params?.[0] === '2' ? [{ visible: 1 }] : [], - })); - const port = createPostgresTrialRefPort({ executor: fake.executor, vaultCutoffTs: CUTOFF_TS }); - - const results = await Promise.all( - ['1', '2', '3', '2'].map(ref => port.hasResearchVisibleTrial(ref)) - ); - - expect(results).toEqual([false, true, false, true]); - expect(fake.calls).toHaveLength(4); - for (const call of fake.calls) { - expect(call.text).toMatch(/^SELECT 1 AS visible FROM trial_ledger WHERE /); - expect(call.text).not.toMatch(/\b(INSERT|UPDATE|DELETE|DROP|ALTER|CREATE|TRUNCATE)\b/i); - expect(call.params?.[1]).toBe(CUTOFF_DATE); - } - }); - - test('exposes only the read-only hasResearchVisibleTrial method', () => { - const fake = scriptedExecutor(() => ({ rows: [] })); - const port = createPostgresTrialRefPort({ executor: fake.executor, vaultCutoffTs: CUTOFF_TS }); - expect(Object.keys(port)).toEqual(['hasResearchVisibleTrial']); - }); -}); - -describe('createPostgresTrialRefPort composed with file_finding (fake executor)', () => { - function composeTool(respond: (params: readonly unknown[] | undefined) => unknown) { - const fake = scriptedExecutor(respond); - const writes = recordingWritePort(); - const tool = createFileFindingTool({ - port: writes.port, - trialLookup: createPostgresTrialRefPort({ - executor: fake.executor, - vaultCutoffTs: CUTOFF_TS, - }), - newId: () => 'finding-qa-1', - now: () => FIXED_EPOCH_MS, - }); - return { fake, tool, writes }; - } - - const baseArgs = { kind: 'finding', title: 'QA filing', summary: 'Visible-only summary.' }; - - test('a visible ref files one finding with the original string ref', async () => { - const { fake, tool, writes } = composeTool(() => ({ rows: [{ visible: 1 }] })); - - const res = await tool.execute({ ...baseArgs, trialRefs: ['9223372036854775807'] }); - - expect(res.isError).toBeUndefined(); - expect(fake.calls).toHaveLength(1); - expect(writes.appended).toHaveLength(1); - expect(writes.appended[0]?.trialRefs).toEqual(['9223372036854775807']); - expect(writes.appended[0]?.status).toBe('pending_review'); - }); - - test('a non-canonical ref is reported unavailable without any query or append', async () => { - const { fake, tool, writes } = composeTool(() => ({ rows: [{ visible: 1 }] })); - - const res = await tool.execute({ ...baseArgs, trialRefs: ['1; DROP TABLE trial_ledger'] }); - - expect(res.isError).toBe(true); - expect(res.content[0]?.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF); - expect(fake.calls).toHaveLength(0); - expect(writes.appended).toHaveLength(0); - }); - - test('one Vault-only ref among visible refs rejects the whole filing with zero appends', async () => { - const { tool, writes } = composeTool(params => ({ - rows: params?.[0] === '20' ? [] : [{ visible: 1 }], - })); - - const res = await tool.execute({ ...baseArgs, trialRefs: ['10', '20', '30'] }); - - expect(res.isError).toBe(true); - expect(res.content[0]?.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF); - expect(writes.appended).toHaveLength(0); - }); - - test('a malformed multi-row response fails closed as filing_failed with zero appends', async () => { - const { tool, writes } = composeTool(() => ({ rows: [{ visible: 1 }, { visible: 1 }] })); - - const res = await tool.execute({ ...baseArgs, trialRefs: ['10'] }); - - expect(res.isError).toBe(true); - expect(res.content[0]?.text).toBe(FILE_FINDING_ERROR_FILING_FAILED); - expect(writes.appended).toHaveLength(0); - }); - - test('an executor failure fails closed as filing_failed with zero appends', async () => { - const { tool, writes } = composeTool(() => { - throw new Error('connection terminated'); - }); - - const res = await tool.execute({ ...baseArgs, trialRefs: ['10'] }); - - expect(res.isError).toBe(true); - expect(res.content[0]?.text).toBe(FILE_FINDING_ERROR_FILING_FAILED); - expect(writes.appended).toHaveLength(0); - }); -}); diff --git a/libs/research/test/mcp-postgres-trial-ref.test.ts b/libs/research/test/mcp-postgres-trial-ref.test.ts deleted file mode 100644 index f3f4186c..00000000 --- a/libs/research/test/mcp-postgres-trial-ref.test.ts +++ /dev/null @@ -1,565 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { - type AppendFindingResult, - FILE_FINDING_ERROR_FILING_FAILED, - FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF, - FILE_FINDING_INITIAL_STATUS, - type FileFindingResultPayload, - type FiledFindingRecord, - type FindingWritePort, - PostgresTrialRefError, - type TrialRefExecutor, - createFileFindingTool, - createMcpServer, - createPostgresTrialRefLookupPort, - createPostgresTrialRefPort, -} from '../src/mcp/index'; -import { utcDateOf } from '../src/mcp/tools/vault-fenced-input'; - -interface RecordedCall { - readonly text: string; - readonly params: readonly unknown[] | undefined; -} - -function createFakeExecutor(rows: readonly Record[] = []): { - readonly calls: RecordedCall[]; - readonly executor: TrialRefExecutor; -} { - const calls: RecordedCall[] = []; - const executor: TrialRefExecutor = { - async query>( - text: string, - params?: readonly unknown[] - ): Promise<{ readonly rows: readonly Row[] }> { - calls.push({ text, params }); - return { rows: rows as readonly Row[] }; - }, - }; - return { calls, executor }; -} - -function createFakeWritePort(): { - readonly appended: FiledFindingRecord[]; - readonly port: FindingWritePort; -} { - const appended: FiledFindingRecord[] = []; - const port: FindingWritePort = { - async appendFinding(record: FiledFindingRecord): Promise { - appended.push(record); - return { - status: 'created', - id: record.id, - createdAt: record.createdAt, - }; - }, - }; - return { appended, port }; -} - -const CUTOFF_MIDNIGHT_TS = Date.UTC(2025, 5, 30, 0, 0, 0, 0); // 2025-06-30T00:00:00.000Z - -describe('createPostgresTrialRefLookupPort', () => { - test('exposes createPostgresTrialRefPort as an alias', () => { - expect(createPostgresTrialRefPort).toBe(createPostgresTrialRefLookupPort); - }); - - test('rejects missing or non-callable executor with INVALID_EXECUTOR', () => { - const invalidOptions: unknown[] = [ - null, - undefined, - {}, - { executor: null, vaultCutoffTs: CUTOFF_MIDNIGHT_TS }, - { executor: {}, vaultCutoffTs: CUTOFF_MIDNIGHT_TS }, - { executor: { query: 'not-a-fn' }, vaultCutoffTs: CUTOFF_MIDNIGHT_TS }, - ]; - - for (const opts of invalidOptions) { - let caught: unknown; - try { - createPostgresTrialRefLookupPort( - opts as Parameters[0] - ); - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(PostgresTrialRefError); - expect(caught).toBeInstanceOf(RangeError); - expect((caught as PostgresTrialRefError).code).toBe('INVALID_EXECUTOR'); - } - }); - - test('rejects invalid schema names with INVALID_SCHEMA before any query', () => { - const fake = createFakeExecutor([]); - const badSchemas: unknown[] = [ - '', - 'Public', - 'Bad-Schema', - 'a;drop', - '1schema', - 'bad.name', - 'space name', - 'public"; DROP TABLE trial_ledger; --', - 123, - null, - ]; - - for (const schema of badSchemas) { - let caught: unknown; - try { - createPostgresTrialRefLookupPort({ - executor: fake.executor, - vaultCutoffTs: CUTOFF_MIDNIGHT_TS, - schema: schema as string, - }); - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(PostgresTrialRefError); - expect((caught as PostgresTrialRefError).code).toBe('INVALID_SCHEMA'); - } - - expect(fake.calls).toHaveLength(0); - }); - - test('rejects invalid or extended-year vaultCutoffTs with INVALID_VAULT_CUTOFF', () => { - const fake = createFakeExecutor([]); - const badCutoffs: unknown[] = [ - Number.NaN, - Number.POSITIVE_INFINITY, - Number.NEGATIVE_INFINITY, - '2025-06-30', - null, - undefined, - 123.45, - Number.MAX_SAFE_INTEGER + 1, - 8_640_000_000_000_000, - -8_640_000_000_000_000, - Date.parse('+010000-01-01T00:00:00.000Z'), - Date.parse('-000001-01-01T00:00:00.000Z'), - Date.parse('0000-01-01T00:00:00.000Z'), - ]; - - for (const vaultCutoffTs of badCutoffs) { - let caught: unknown; - try { - createPostgresTrialRefLookupPort({ - executor: fake.executor, - vaultCutoffTs: vaultCutoffTs as number, - }); - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(PostgresTrialRefError); - expect((caught as PostgresTrialRefError).code).toBe('INVALID_VAULT_CUTOFF'); - } - - expect(fake.calls).toHaveLength(0); - }); - - test('returns true for a visible trial with one parameterized read-only SELECT and exact params', async () => { - const fake = createFakeExecutor([{ visible: 1 }]); - const port = createPostgresTrialRefLookupPort({ - executor: fake.executor, - vaultCutoffTs: CUTOFF_MIDNIGHT_TS, - }); - - const visible = await port.hasResearchVisibleTrial('42'); - - expect(visible).toBe(true); - expect(fake.calls).toHaveLength(1); - const call = fake.calls[0]!; - expect(call.text.trimStart().startsWith('SELECT')).toBe(true); - expect(call.text).not.toContain(';'); - expect(call.text).not.toMatch(/\b(INSERT|UPDATE|DELETE|DROP|ALTER|CREATE|TRUNCATE)\b/i); - expect(call.text).toBe( - 'SELECT 1 AS visible FROM trial_ledger WHERE trial_id = $1::bigint AND sample_end < $2::date LIMIT 1' - ); - expect(call.params).toEqual(['42', '2025-06-30']); - expect(typeof call.params?.[0]).toBe('string'); - }); - - test('returns false when the executor returns empty rows (unknown or Vault-only trial)', async () => { - const fake = createFakeExecutor([]); - const port = createPostgresTrialRefLookupPort({ - executor: fake.executor, - vaultCutoffTs: CUTOFF_MIDNIGHT_TS, - }); - - const visible = await port.hasResearchVisibleTrial('42'); - - expect(visible).toBe(false); - expect(fake.calls).toHaveLength(1); - expect(fake.calls[0]!.params).toEqual(['42', '2025-06-30']); - }); - - test('maps midnight and non-midnight UTC vaultCutoffTs to the same UTC date as utcDateOf', async () => { - const nonMidnightTs = Date.UTC(2025, 5, 30, 23, 59, 59, 999); - const nextDayTs = Date.UTC(2025, 6, 1, 0, 0, 0, 0); - - const fakeSameDay = createFakeExecutor([{ visible: 1 }]); - const sameDayPort = createPostgresTrialRefLookupPort({ - executor: fakeSameDay.executor, - vaultCutoffTs: nonMidnightTs, - }); - await sameDayPort.hasResearchVisibleTrial('7'); - expect(fakeSameDay.calls[0]!.params).toEqual(['7', utcDateOf(nonMidnightTs)]); - expect(fakeSameDay.calls[0]!.params?.[1]).toBe('2025-06-30'); - - const fakeNextDay = createFakeExecutor([{ visible: 1 }]); - const nextDayPort = createPostgresTrialRefLookupPort({ - executor: fakeNextDay.executor, - vaultCutoffTs: nextDayTs, - }); - await nextDayPort.hasResearchVisibleTrial('7'); - expect(fakeNextDay.calls[0]!.params).toEqual(['7', '2025-07-01']); - }); - - test('returns false with zero executor calls for malformed, injection-shaped, overflowing, and non-string refs', async () => { - const fake = createFakeExecutor([{ visible: 1 }]); - const port = createPostgresTrialRefLookupPort({ - executor: fake.executor, - vaultCutoffTs: CUTOFF_MIDNIGHT_TS, - }); - - const invalidRefs: unknown[] = [ - '', - ' 42', - '42 ', - '042', - '0', - '-1', - '+1', - '1.0', - '1e3', - '0x10', - '1_000', - '42; DROP TABLE trial_ledger', - '9223372036854775808', - '10000000000000000000', - 42, - 42n, - null, - undefined, - {}, - [], - ]; - - for (const ref of invalidRefs) { - const result = await port.hasResearchVisibleTrial(ref as string); - expect(result).toBe(false); - } - - expect(fake.calls).toHaveLength(0); - }); - - test('queries the maximum signed 64-bit BIGINT verbatim as a string without numeric coercion', async () => { - const maxBigIntRef = '9223372036854775807'; - const fake = createFakeExecutor([{ visible: 1 }]); - const port = createPostgresTrialRefLookupPort({ - executor: fake.executor, - vaultCutoffTs: CUTOFF_MIDNIGHT_TS, - }); - - const visible = await port.hasResearchVisibleTrial(maxBigIntRef); - - expect(visible).toBe(true); - expect(fake.calls).toHaveLength(1); - expect(fake.calls[0]!.text).not.toContain(maxBigIntRef); - expect(fake.calls[0]!.params).toEqual([maxBigIntRef, '2025-06-30']); - }); - - test('quotes validated optional schema and leaves table unqualified when omitted', async () => { - const fakeDefault = createFakeExecutor([]); - const defaultPort = createPostgresTrialRefLookupPort({ - executor: fakeDefault.executor, - vaultCutoffTs: CUTOFF_MIDNIGHT_TS, - }); - await defaultPort.hasResearchVisibleTrial('1'); - expect(fakeDefault.calls[0]!.text).toContain('FROM trial_ledger '); - - for (const schema of ['_', 'a', 'research_x', 'stock_bot_safety_0abc']) { - const fakeScoped = createFakeExecutor([]); - const scopedPort = createPostgresTrialRefLookupPort({ - executor: fakeScoped.executor, - vaultCutoffTs: CUTOFF_MIDNIGHT_TS, - schema, - }); - await scopedPort.hasResearchVisibleTrial('1'); - expect(fakeScoped.calls[0]!.text).toContain(`FROM "${schema}".trial_ledger `); - } - }); - - test('throws INVALID_ROW for malformed envelopes, invalid singleton rows, and multiple rows (regression)', async () => { - const badResponses: unknown[] = [ - null, - undefined, - {}, - { rows: null }, - { rows: 'not-an-array' }, - { rows: {} }, - { rows: [null] }, - { rows: [undefined] }, - { rows: [1] }, - { rows: [{}] }, - { rows: [{ visible: '1' }] }, - { rows: [{ visible: true }] }, - { rows: [{ visible: 0 }] }, - { rows: [{ visible: 2 }] }, - { rows: [{ visible: null }] }, - // Regression: multiple rows must fail closed rather than returning true. - { rows: [{ visible: 1 }, { visible: 1 }] }, - ]; - - for (const response of badResponses) { - const executor: TrialRefExecutor = { - async query() { - return response as { readonly rows: readonly never[] }; - }, - }; - const port = createPostgresTrialRefLookupPort({ - executor, - vaultCutoffTs: CUTOFF_MIDNIGHT_TS, - }); - - let caught: unknown; - try { - await port.hasResearchVisibleTrial('101'); - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(PostgresTrialRefError); - expect((caught as PostgresTrialRefError).code).toBe('INVALID_ROW'); - } - }); - - test('propagates rejected and synchronously thrown executor errors unchanged without retrying', async () => { - const asyncFailure = new Error('postgres connection lost'); - let asyncAttempts = 0; - const asyncExecutor: TrialRefExecutor = { - async query() { - asyncAttempts += 1; - throw asyncFailure; - }, - }; - const asyncPort = createPostgresTrialRefLookupPort({ - executor: asyncExecutor, - vaultCutoffTs: CUTOFF_MIDNIGHT_TS, - }); - - await expect(asyncPort.hasResearchVisibleTrial('42')).rejects.toBe(asyncFailure); - expect(asyncAttempts).toBe(1); - - const syncFailure = new Error('pool exhausted'); - let syncAttempts = 0; - const syncExecutor = { - query() { - syncAttempts += 1; - throw syncFailure; - }, - } as unknown as TrialRefExecutor; - const syncPort = createPostgresTrialRefLookupPort({ - executor: syncExecutor, - vaultCutoffTs: CUTOFF_MIDNIGHT_TS, - }); - - await expect(syncPort.hasResearchVisibleTrial('42')).rejects.toBe(syncFailure); - expect(syncAttempts).toBe(1); - }); - - test('accepts a pg.Pool-shaped executor with query on its prototype', async () => { - class PoolLikeExecutor { - readonly calls: RecordedCall[] = []; - async query>( - text: string, - params?: readonly unknown[] - ): Promise<{ readonly rows: readonly Row[] }> { - this.calls.push({ text, params }); - return { rows: [{ visible: 1 }] as unknown as readonly Row[] }; - } - } - - const executor = new PoolLikeExecutor(); - const port = createPostgresTrialRefLookupPort({ - executor, - vaultCutoffTs: CUTOFF_MIDNIGHT_TS, - }); - - expect(await port.hasResearchVisibleTrial('99')).toBe(true); - expect(executor.calls).toHaveLength(1); - }); -}); - -describe('createPostgresTrialRefLookupPort wired into createFileFindingTool', () => { - async function callFileFinding( - executor: TrialRefExecutor, - trialRefs: readonly string[] - ): Promise<{ - readonly appended: FiledFindingRecord[]; - readonly result: { readonly content: readonly { type: string; text: string }[]; readonly isError?: boolean }; - }> { - const trialLookup = createPostgresTrialRefLookupPort({ - executor, - vaultCutoffTs: CUTOFF_MIDNIGHT_TS, - }); - const { appended, port } = createFakeWritePort(); - const tool = createFileFindingTool({ - port, - trialLookup, - newId: () => 'finding-0001', - now: () => Date.UTC(2025, 5, 29, 12, 0, 0, 0), - }); - const server = createMcpServer({ - name: 'test-copilot', - version: '0.1.0', - tools: [tool], - }); - - const rawResponse = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 1, - method: 'tools/call', - params: { - name: 'file_finding', - arguments: { - kind: 'finding', - title: 'Pre-vault momentum signal', - summary: 'Observed stable rank IC across US equities prior to cutoff.', - trialRefs, - }, - }, - }) - ); - - const parsed = JSON.parse(rawResponse!) as { - readonly result: { - readonly content: readonly { type: string; text: string }[]; - readonly isError?: boolean; - }; - }; - return { appended, result: parsed.result }; - } - - test('files a pending_review finding and returns a created receipt when the trial is visible', async () => { - const fake = createFakeExecutor([{ visible: 1 }]); - const { appended, result } = await callFileFinding(fake.executor, ['42']); - - expect(result.isError).toBeUndefined(); - const payload = JSON.parse(result.content[0]!.text) as FileFindingResultPayload; - expect(payload).toEqual({ - id: 'finding-0001', - createdAt: '2025-06-29T12:00:00.000Z', - created: true, - }); - expect(appended).toHaveLength(1); - expect(appended[0]).toEqual({ - id: 'finding-0001', - kind: 'finding', - title: 'Pre-vault momentum signal', - status: FILE_FINDING_INITIAL_STATUS, - createdAt: '2025-06-29T12:00:00.000Z', - summary: 'Observed stable rank IC across US equities prior to cutoff.', - trialRefs: ['42'], - evidenceRefs: [], - }); - expect(fake.calls).toHaveLength(1); - expect(fake.calls[0]!.params).toEqual(['42', '2025-06-30']); - }); - - test('returns FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF with zero appends when executor returns no rows', async () => { - const fake = createFakeExecutor([]); - const { appended, result } = await callFileFinding(fake.executor, ['42']); - - expect(result.isError).toBe(true); - expect(result.content[0]!.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF); - expect(appended).toHaveLength(0); - expect(fake.calls).toHaveLength(1); - }); - - test('returns FILE_FINDING_ERROR_FILING_FAILED with zero appends when executor rejects', async () => { - const executor: TrialRefExecutor = { - async query() { - throw new Error('database unavailable'); - }, - }; - const { appended, result } = await callFileFinding(executor, ['42']); - - expect(result.isError).toBe(true); - expect(result.content[0]!.text).toBe(FILE_FINDING_ERROR_FILING_FAILED); - expect(appended).toHaveLength(0); - }); -}); - -describe('createPostgresTrialRefLookupPort (QA edge cases)', () => { - test('queries in-range 19-digit refs and rejects 19-digit refs above the signed BIGINT max', async () => { - const fake = createFakeExecutor([{ visible: 1 }]); - const port = createPostgresTrialRefLookupPort({ - executor: fake.executor, - vaultCutoffTs: CUTOFF_MIDNIGHT_TS, - }); - - expect(await port.hasResearchVisibleTrial('1000000000000000000')).toBe(true); - expect(await port.hasResearchVisibleTrial('9223372036854775806')).toBe(true); - expect(await port.hasResearchVisibleTrial('9223372036854775900')).toBe(false); - expect(await port.hasResearchVisibleTrial('9999999999999999999')).toBe(false); - - expect(fake.calls.map(c => c.params?.[0])).toEqual([ - '1000000000000000000', - '9223372036854775806', - ]); - }); - - test('rejects trailing-newline, tab, fullwidth-digit, and boxed-String refs without querying', async () => { - const fake = createFakeExecutor([{ visible: 1 }]); - const port = createPostgresTrialRefLookupPort({ - executor: fake.executor, - vaultCutoffTs: CUTOFF_MIDNIGHT_TS, - }); - - for (const ref of ['42\n', '\n42', '4\t2', '42', '42\u0000', new String('42')] as unknown[]) { - expect(await port.hasResearchVisibleTrial(ref as string)).toBe(false); - } - expect(fake.calls).toHaveLength(0); - }); - - test('accepts the four-digit PostgreSQL calendar bounds 0001-01-01 and 9999-12-31 as cutoff dates', async () => { - const earliest = Date.parse('0001-01-01T00:00:00.000Z'); - const latest = Date.parse('9999-12-31T23:59:59.999Z'); - - for (const [ts, expected] of [ - [earliest, '0001-01-01'], - [latest, '9999-12-31'], - [Date.UTC(1969, 11, 31, 23, 59, 59, 999), '1969-12-31'], - ] as const) { - const fake = createFakeExecutor([]); - const port = createPostgresTrialRefLookupPort({ executor: fake.executor, vaultCutoffTs: ts }); - await port.hasResearchVisibleTrial('5'); - expect(fake.calls[0]!.params).toEqual(['5', expected]); - } - - let caught: unknown; - try { - createPostgresTrialRefLookupPort({ - executor: createFakeExecutor().executor, - vaultCutoffTs: latest + 1, - }); - } catch (err) { - caught = err; - } - expect((caught as PostgresTrialRefError).code).toBe('INVALID_VAULT_CUTOFF'); - }); - - test('freezes the cutoff date and SQL text at construction across repeated lookups', async () => { - const fake = createFakeExecutor([]); - const options = { executor: fake.executor, vaultCutoffTs: CUTOFF_MIDNIGHT_TS }; - const port = createPostgresTrialRefLookupPort(options); - - await port.hasResearchVisibleTrial('1'); - (options as { vaultCutoffTs: number }).vaultCutoffTs = Date.UTC(2030, 0, 1); - await port.hasResearchVisibleTrial('2'); - - expect(fake.calls).toHaveLength(2); - expect(fake.calls[0]!.text).toBe(fake.calls[1]!.text); - expect(fake.calls[1]!.params).toEqual(['2', '2025-06-30']); - }); -}); diff --git a/libs/research/test/mcp-protocol.test.ts b/libs/research/test/mcp-protocol.test.ts deleted file mode 100644 index 511a8f7e..00000000 --- a/libs/research/test/mcp-protocol.test.ts +++ /dev/null @@ -1,454 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { z } from 'zod'; -import * as rootResearchExports from '../src/index'; -import { - JSON_RPC_ERROR_CODES, - MCP_PROTOCOL_VERSION, - createMcpServer, - defineMcpTool, - zodObjectToJsonSchema, -} from '../src/mcp/index'; - -interface JsonRpcParsedResponse { - jsonrpc: string; - id: string | number | null; - result?: Record; - error?: { - code: number; - message: string; - data?: unknown; - }; -} - -function parseResponse(raw: string | null): JsonRpcParsedResponse { - expect(raw).not.toBeNull(); - return JSON.parse(raw as string) as JsonRpcParsedResponse; -} - -describe('MCP protocol & server core', () => { - test('initialize returns protocolVersion, serverInfo, and capabilities.tools', async () => { - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [], - }); - - const raw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 1, - method: 'initialize', - params: { - protocolVersion: MCP_PROTOCOL_VERSION, - capabilities: {}, - clientInfo: { name: 'test-client', version: '1.0.0' }, - }, - }) - ); - - const response = parseResponse(raw); - expect(response.jsonrpc).toBe('2.0'); - expect(response.id).toBe(1); - expect(response.error).toBeUndefined(); - expect(response.result).toEqual({ - protocolVersion: MCP_PROTOCOL_VERSION, - capabilities: { tools: {} }, - serverInfo: { - name: 'stock-bot-research', - version: '0.1.0', - }, - }); - }); - - test('notifications/initialized returns null (no response)', async () => { - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - }); - - const raw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - method: 'notifications/initialized', - }) - ); - - expect(raw).toBeNull(); - }); - - test('ping returns empty object result', async () => { - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - }); - - const raw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 'ping-1', - method: 'ping', - }) - ); - - const response = parseResponse(raw); - expect(response.id).toBe('ping-1'); - expect(response.result).toEqual({}); - }); - - test('echoes string and numeric request ids verbatim (including 0 and negative integers)', async () => { - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - }); - - const ids: readonly (string | number)[] = ['req-abc', '', 0, -42, 9007199254740991]; - for (const id of ids) { - const raw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id, - method: 'ping', - }) - ); - const response = parseResponse(raw); - expect(response.id).toBe(id); - } - }); - - test('malformed JSON returns -32700 with id: null', async () => { - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - }); - - const raw = await server.handleMessage('{not valid json'); - const response = parseResponse(raw); - expect(response.id).toBeNull(); - expect(response.error?.code).toBe(JSON_RPC_ERROR_CODES.PARSE_ERROR); - }); - - test('non-JSON-RPC objects and explicit invalid id return -32600', async () => { - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - }); - - const badPayloads = [ - '42', - '"hello"', - 'null', - '[]', - JSON.stringify({ foo: 'bar' }), - JSON.stringify({ jsonrpc: '1.0', id: 1, method: 'ping' }), - JSON.stringify({ jsonrpc: '2.0', id: null, method: 'ping' }), - JSON.stringify({ jsonrpc: '2.0', id: true, method: 'ping' }), - JSON.stringify({ jsonrpc: '2.0', id: { nested: 1 }, method: 'ping' }), - JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'ping', extra: true }), - ]; - - for (const payload of badPayloads) { - const raw = await server.handleMessage(payload); - const response = parseResponse(raw); - expect(response.id).toBeNull(); - expect(response.error?.code).toBe(JSON_RPC_ERROR_CODES.INVALID_REQUEST); - } - }); - - test('unknown method returns -32601 echoing request id', async () => { - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - }); - - const raw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 'unknown-1', - method: 'resources/list', - }) - ); - - const response = parseResponse(raw); - expect(response.id).toBe('unknown-1'); - expect(response.error?.code).toBe(JSON_RPC_ERROR_CODES.METHOD_NOT_FOUND); - }); - - test('tools/call rejects unknown tool name and malformed params with -32602', async () => { - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [], - }); - - const unknownToolRaw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 10, - method: 'tools/call', - params: { name: 'does_not_exist', arguments: {} }, - }) - ); - const unknownToolResp = parseResponse(unknownToolRaw); - expect(unknownToolResp.id).toBe(10); - expect(unknownToolResp.error?.code).toBe(JSON_RPC_ERROR_CODES.INVALID_PARAMS); - - const badParamsRaw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 11, - method: 'tools/call', - params: { name: 123, arguments: 'not-an-object' }, - }) - ); - const badParamsResp = parseResponse(badParamsRaw); - expect(badParamsResp.id).toBe(11); - expect(badParamsResp.error?.code).toBe(JSON_RPC_ERROR_CODES.INVALID_PARAMS); - }); - - test('invalid tool arguments return isError: true with readable message and zero handler calls', async () => { - let handlerCalls = 0; - const echoTool = defineMcpTool({ - name: 'echo_count', - description: 'Echoes a positive integer count.', - inputSchema: z.object({ count: z.number().int().min(1) }).strict(), - handler(input) { - handlerCalls += 1; - return { - content: [{ type: 'text', text: String(input.count) }], - }; - }, - }); - - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [echoTool], - }); - - const raw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 20, - method: 'tools/call', - params: { - name: 'echo_count', - arguments: { count: 0, unexpected: true }, - }, - }) - ); - - expect(handlerCalls).toBe(0); - const response = parseResponse(raw); - expect(response.id).toBe(20); - expect(response.error).toBeUndefined(); - const result = response.result as { - isError?: boolean; - content: { type: string; text: string }[]; - }; - expect(result.isError).toBe(true); - expect(result.content[0]?.type).toBe('text'); - expect(result.content[0]?.text).toContain('Invalid arguments for tool "echo_count"'); - }); - - test('throwing tool handler returns isError: true with sanitized error and zero stack trace or paths', async () => { - const boomTool = defineMcpTool({ - name: 'explode', - description: 'Always throws an error.', - inputSchema: z.object({}).strict(), - handler() { - const err = new Error( - 'Failed reading /mnt/data/stockbot/secret.parquet\n at secretInternal (/srv/app/secret.ts:42:9)' - ); - err.name = 'BackendFailureError'; - throw err; - }, - }); - - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [boomTool], - }); - - const raw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 30, - method: 'tools/call', - params: { name: 'explode', arguments: {} }, - }) - ); - - const response = parseResponse(raw); - expect(response.id).toBe(30); - expect(response.error).toBeUndefined(); - const result = response.result as { - isError?: boolean; - content: { type: string; text: string }[]; - }; - expect(result.isError).toBe(true); - const text = result.content[0]?.text ?? ''; - expect(text).toBe('BackendFailureError: Tool execution failed.'); - expect(text).not.toContain('/mnt/data/stockbot'); - expect(text).not.toContain('at '); - expect(text).not.toContain('/srv/app/secret.ts'); - expect(text).not.toContain('\n'); - }); - - test('accepts standard MCP _meta.progressToken on requests and rejects malformed _meta', async () => { - let calls = 0; - const echoTool = defineMcpTool({ - name: 'echo_msg', - description: 'Echoes a message.', - inputSchema: z.object({ msg: z.string() }).strict(), - handler(input) { - calls += 1; - return { content: [{ type: 'text', text: input.msg }] }; - }, - }); - - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [echoTool], - }); - - const initResp = parseResponse( - await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 'm1', - method: 'initialize', - params: { - protocolVersion: MCP_PROTOCOL_VERSION, - _meta: { progressToken: 'init-tok' }, - }, - }) - ) - ); - expect(initResp.error).toBeUndefined(); - - const pingResp = parseResponse( - await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 'm2', - method: 'ping', - params: { _meta: { progressToken: 42 } }, - }) - ) - ); - expect(pingResp.result).toEqual({}); - - const listResp = parseResponse( - await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 'm3', - method: 'tools/list', - params: { _meta: { progressToken: 'list-tok', customFlag: true } }, - }) - ) - ); - expect(listResp.error).toBeUndefined(); - - const callResp = parseResponse( - await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 'm4', - method: 'tools/call', - params: { - name: 'echo_msg', - arguments: { msg: 'hello' }, - _meta: { progressToken: 'call-tok-1' }, - }, - }) - ) - ); - expect(calls).toBe(1); - expect(callResp.error).toBeUndefined(); - const callResult = callResp.result as { - isError?: boolean; - content: { type: string; text: string }[]; - }; - expect(callResult.isError).toBeUndefined(); - expect(callResult.content[0]?.text).toBe('hello'); - - // Invalid progressToken type -> -32602 before handler runs - const badMetaResp = parseResponse( - await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 'm5', - method: 'tools/call', - params: { - name: 'echo_msg', - arguments: { msg: 'hello' }, - _meta: { progressToken: true }, - }, - }) - ) - ); - expect(calls).toBe(1); - expect(badMetaResp.error?.code).toBe(JSON_RPC_ERROR_CODES.INVALID_PARAMS); - }); - - test('raw JSON own __proto__ key in tools/call arguments is preserved and rejected by strict tool schema', async () => { - let calls = 0; - const strictTool = defineMcpTool({ - name: 'strict_tool', - description: 'Accepts only x.', - inputSchema: z.object({ x: z.number() }).strict(), - handler(input) { - calls += 1; - return { content: [{ type: 'text', text: String(input.x) }] }; - }, - }); - - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [strictTool], - }); - - const rawRequest = - '{"jsonrpc":"2.0","id":"proto-check","method":"tools/call","params":{"name":"strict_tool","arguments":{"x":1,"__proto__":{"injected":true}}}}'; - const response = parseResponse(await server.handleMessage(rawRequest)); - expect(calls).toBe(0); - expect(response.error).toBeUndefined(); - const result = response.result as { isError?: boolean; content: { type: string; text: string }[] }; - expect(result.isError).toBe(true); - expect(result.content[0]?.text).toContain('Invalid arguments for tool "strict_tool"'); - }); - - test('duplicate tool names throw at createMcpServer time and unsupported schemas fail fast', () => { - const makeTool = () => - defineMcpTool({ - name: 'dup_tool', - description: 'Duplicate tool test.', - inputSchema: z.object({ x: z.string() }).strict(), - handler: () => ({ content: [{ type: 'text', text: 'ok' }] }), - }); - - expect(() => - createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [makeTool(), makeTool()], - }) - ).toThrow(/Duplicate MCP tool name/i); - - expect(() => - zodObjectToJsonSchema(z.object({ bad: z.date() }).strict()) - ).toThrow(/Unsupported Zod schema type/i); - }); - - test('browser-safe root entrypoint does not re-export MCP symbols', () => { - const exportedKeys = Object.keys(rootResearchExports); - expect(exportedKeys).not.toContain('createMcpServer'); - expect(exportedKeys).not.toContain('defineMcpTool'); - expect(exportedKeys).not.toContain('runStdioServer'); - expect(exportedKeys).not.toContain('createQueryDataTool'); - }); -}); diff --git a/libs/research/test/mcp-query-data.test.ts b/libs/research/test/mcp-query-data.test.ts deleted file mode 100644 index 664e5c13..00000000 --- a/libs/research/test/mcp-query-data.test.ts +++ /dev/null @@ -1,783 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { - type BarBatch, - type BarRecord, - type MarketDataStore, - MarketDataStoreValidationError, - VaultScopeNotAuthorizedError, -} from '../src/market-data-store'; -import { - ADJ_SNAPSHOT_FORMAT_VERSION, - ADJ_SNAPSHOT_KV_PREFIX, - AdjFactorsSnapshotError, - type BarsQuery, - type DuckDbExecutor, - type DuckDbParam, - MarketDataStoreNotImplementedError, - type UniverseQuery, - createDuckDbMarketDataStore, -} from '../src/market-data-store-duckdb'; -import { - QUERY_DATA_DEFAULT_LIMIT, - QUERY_DATA_MAX_LIMIT, - type QueryDataResultPayload, - createMcpServer, - createQueryDataTool, -} from '../src/mcp/index'; - -const VAULT_CUTOFF_TS = Date.UTC(2025, 2, 31, 0, 0, 0, 0); // 2025-03-31T00:00:00.000Z - -function makeBar(listingId: number, ts: number, close: number, knownAt = ts): BarRecord { - return { - listingId, - ts, - open: close - 1, - high: close + 1, - low: close - 2, - close, - volume: 1_000, - vwap: close, - knownAt, - }; -} - -interface FakeStoreState { - readonly barsCalls: BarsQuery[]; - readonly universeCalls: UniverseQuery[]; - readonly store: MarketDataStore; -} - -function createFakeStore(options?: { - batches?: readonly BarBatch[]; - universeIds?: readonly number[]; - barsError?: Error; - universeError?: Error; -}): FakeStoreState { - const barsCalls: BarsQuery[] = []; - const universeCalls: UniverseQuery[] = []; - - const batches = options?.batches ?? []; - const universeIds = options?.universeIds ?? []; - - const store: MarketDataStore = { - bars(q: BarsQuery): AsyncIterable { - barsCalls.push(q); - if (options?.barsError !== undefined) { - const err = options.barsError; - return { - [Symbol.asyncIterator]() { - return { - next() { - return Promise.reject(err); - }, - }; - }, - }; - } - return { - async *[Symbol.asyncIterator]() { - for (const batch of batches) { - yield batch; - } - }, - }; - }, - async universe(q: UniverseQuery): Promise { - universeCalls.push(q); - if (options?.universeError !== undefined) { - throw options.universeError; - } - return [...universeIds]; - }, - crossSection() { - throw new MarketDataStoreNotImplementedError('crossSection'); - }, - fundamentalsAsOf() { - throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); - }, - events() { - throw new MarketDataStoreNotImplementedError('events'); - }, - shortsAsOf() { - throw new MarketDataStoreNotImplementedError('shortsAsOf'); - }, - macroAsOf() { - throw new MarketDataStoreNotImplementedError('macroAsOf'); - }, - fx() { - throw new MarketDataStoreNotImplementedError('fx'); - }, - }; - - return { barsCalls, universeCalls, store }; -} - -async function callQueryData( - fake: FakeStoreState, - args: Record -): Promise<{ - rawResponse: string; - isError: boolean; - text: string; -}> { - const tool = createQueryDataTool({ - store: fake.store, - vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, - }); - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [tool], - }); - - const rawResponse = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 'q1', - method: 'tools/call', - params: { - name: 'query_data', - arguments: args, - }, - }) - ); - - expect(rawResponse).not.toBeNull(); - const parsed = JSON.parse(rawResponse as string) as { - result: { - isError?: boolean; - content: { type: string; text: string }[]; - }; - }; - return { - rawResponse: rawResponse as string, - isError: parsed.result.isError === true, - text: parsed.result.content[0]?.text ?? '', - }; -} - -describe('MCP query_data tool', () => { - test('tools/list exposes query_data with strict inputSchema and omits scope / vault_evaluation_only', async () => { - const fake = createFakeStore(); - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createQueryDataTool({ - store: fake.store, - vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, - }), - ], - }); - - const raw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 1, - method: 'tools/list', - }) - ); - - const parsed = JSON.parse(raw as string) as { - result: { - tools: { - name: string; - description: string; - inputSchema: { - type: string; - properties: Record; - required?: string[]; - additionalProperties: boolean; - }; - }[]; - }; - }; - - expect(parsed.result.tools).toHaveLength(1); - const tool = parsed.result.tools[0]; - expect(tool?.name).toBe('query_data'); - expect(tool?.inputSchema.type).toBe('object'); - expect(tool?.inputSchema.additionalProperties).toBe(false); - expect(tool?.inputSchema.required).toEqual(['from', 'to']); - - const propKeys = Object.keys(tool?.inputSchema.properties ?? {}); - expect(propKeys).toContain('listingIds'); - expect(propKeys).toContain('universe'); - expect(propKeys).toContain('from'); - expect(propKeys).toContain('to'); - expect(propKeys).toContain('limit'); - expect(propKeys).not.toContain('scope'); - expect(propKeys).not.toContain('vault_evaluation_only'); - expect(tool?.inputSchema.required).not.toContain('scope'); - expect(tool?.inputSchema.required).not.toContain('vault_evaluation_only'); - }); - - test('returns pre-cutoff rows and records scope === vault_fenced on every bars() call', async () => { - const bar1 = makeBar(101, Date.UTC(2025, 2, 28, 20, 0, 0), 150.5); - const bar2 = makeBar(101, Date.UTC(2025, 2, 30, 20, 0, 0), 152.0); - const fake = createFakeStore({ - batches: [{ rows: [bar1, bar2] }], - }); - - const { isError, text } = await callQueryData(fake, { - listingIds: [101], - from: '2025-03-01', - to: '2025-03-30', - }); - - expect(isError).toBe(false); - expect(fake.barsCalls).toHaveLength(1); - expect(fake.barsCalls[0]?.scope).toBe('vault_fenced'); - - const payload = JSON.parse(text) as QueryDataResultPayload; - expect(payload.scope).toBe('vault_fenced'); - expect(payload.vaultCutoffTs).toBe(VAULT_CUTOFF_TS); - expect(payload.clampedTo).toBe(false); - expect(payload.rowCount).toBe(2); - expect(payload.truncated).toBe(false); - expect(payload.rows).toEqual([bar1, bar2]); - }); - - test('enforces default limit, explicit limit, max limit, and rejects out-of-bounds limits with zero store calls', async () => { - const totalRows = QUERY_DATA_MAX_LIMIT + 5; - const allRows: BarRecord[] = []; - for (let i = 0; i < totalRows; i += 1) { - allRows.push(makeBar(101, Date.UTC(2024, 0, 1, 0, 0, 0) + i * 60_000, 100 + i * 0.01)); - } - - // Omitted limit -> caps at QUERY_DATA_DEFAULT_LIMIT with truncated: true - const defaultFake = createFakeStore({ batches: [{ rows: allRows }] }); - const defaultRes = await callQueryData(defaultFake, { - listingIds: [101], - from: '2024-01-01', - to: '2025-03-01', - }); - expect(defaultRes.isError).toBe(false); - const defaultPayload = JSON.parse(defaultRes.text) as QueryDataResultPayload; - expect(defaultPayload.limit).toBe(QUERY_DATA_DEFAULT_LIMIT); - expect(defaultPayload.rowCount).toBe(QUERY_DATA_DEFAULT_LIMIT); - expect(defaultPayload.truncated).toBe(true); - - // Explicit limit -> caps at requested value - const explicitFake = createFakeStore({ batches: [{ rows: allRows }] }); - const explicitRes = await callQueryData(explicitFake, { - listingIds: [101], - from: '2024-01-01', - to: '2025-03-01', - limit: 3, - }); - expect(explicitRes.isError).toBe(false); - const explicitPayload = JSON.parse(explicitRes.text) as QueryDataResultPayload; - expect(explicitPayload.limit).toBe(3); - expect(explicitPayload.rowCount).toBe(3); - expect(explicitPayload.truncated).toBe(true); - - // Exact QUERY_DATA_MAX_LIMIT -> succeeds - const maxFake = createFakeStore({ batches: [{ rows: allRows }] }); - const maxRes = await callQueryData(maxFake, { - listingIds: [101], - from: '2024-01-01', - to: '2025-03-01', - limit: QUERY_DATA_MAX_LIMIT, - }); - expect(maxRes.isError).toBe(false); - const maxPayload = JSON.parse(maxRes.text) as QueryDataResultPayload; - expect(maxPayload.rowCount).toBe(QUERY_DATA_MAX_LIMIT); - expect(maxPayload.truncated).toBe(true); - - // limit > QUERY_DATA_MAX_LIMIT or <= 0 -> isError: true with zero store calls - for (const badLimit of [QUERY_DATA_MAX_LIMIT + 1, 0, -5]) { - const badFake = createFakeStore({ batches: [{ rows: allRows }] }); - const badRes = await callQueryData(badFake, { - listingIds: [101], - from: '2024-01-01', - to: '2025-03-01', - limit: badLimit, - }); - expect(badRes.isError).toBe(true); - expect(badFake.barsCalls).toHaveLength(0); - expect(badFake.universeCalls).toHaveLength(0); - } - }); - - test('rejects scope, vault_evaluation_only, or unknown keys with isError: true and zero store calls', async () => { - const injectedPayloads: Record[] = [ - { - listingIds: [101], - from: '2025-03-01', - to: '2025-03-30', - scope: 'vault_evaluation_only', - }, - { - listingIds: [101], - from: '2025-03-01', - to: '2025-03-30', - scope: 'vault_fenced', - }, - { - listingIds: [101], - from: '2025-03-01', - to: '2025-03-30', - vault_evaluation_only: true, - }, - { - listingIds: [101], - from: '2025-03-01', - to: '2025-03-30', - unknownFlag: 'x', - }, - ]; - - for (const args of injectedPayloads) { - const fake = createFakeStore({ - batches: [{ rows: [makeBar(101, Date.UTC(2025, 2, 20, 20, 0, 0), 100)] }], - }); - const res = await callQueryData(fake, args); - expect(res.isError).toBe(true); - expect(fake.barsCalls).toHaveLength(0); - expect(fake.universeCalls).toHaveLength(0); - } - }); - - test('range starting at or after vaultCutoffTs returns isError: true naming VaultHoldoutFenceError with zero store calls', async () => { - const fake = createFakeStore({ - batches: [{ rows: [makeBar(101, Date.UTC(2025, 3, 5, 20, 0, 0), 200)] }], - }); - - const res = await callQueryData(fake, { - listingIds: [101], - from: '2025-03-31', - to: '2025-04-15', - }); - - expect(res.isError).toBe(true); - expect(res.text).toContain('VaultHoldoutFenceError'); - expect(fake.barsCalls).toHaveLength(0); - expect(fake.universeCalls).toHaveLength(0); - }); - - test('range straddling vaultCutoffTs clamps to/asOf strictly below cutoff', async () => { - const preBar = makeBar(101, Date.UTC(2025, 2, 30, 20, 0, 0), 150); - const fake = createFakeStore({ - batches: [{ rows: [preBar] }], - }); - - const res = await callQueryData(fake, { - listingIds: [101], - from: '2025-03-01', - to: '2025-04-30', - asOf: '2025-05-01', - }); - - expect(res.isError).toBe(false); - expect(fake.barsCalls).toHaveLength(1); - expect(fake.barsCalls[0]?.scope).toBe('vault_fenced'); - expect(Date.parse(fake.barsCalls[0]?.to ?? '')).toBe(VAULT_CUTOFF_TS - 1); - expect(Date.parse(fake.barsCalls[0]?.asOf ?? '')).toBe(VAULT_CUTOFF_TS - 1); - - const payload = JSON.parse(res.text) as QueryDataResultPayload; - expect(payload.clampedTo).toBe(true); - expect(payload.clampedAsOf).toBe(true); - expect(payload.toMs).toBe(VAULT_CUTOFF_TS - 1); - expect(payload.asOfMs).toBe(VAULT_CUTOFF_TS - 1); - expect(payload.rows).toEqual([preBar]); - }); - - test('defense-in-depth drops post-cutoff rows (ts >= cutoff or knownAt >= cutoff) from a leaky store', async () => { - const preBar = makeBar(101, Date.UTC(2025, 2, 28, 20, 0, 0), 150); - const leakyTsBar = makeBar(101, VAULT_CUTOFF_TS, 999); - const leakyFutureTsBar = makeBar(101, Date.UTC(2025, 3, 2, 20, 0, 0), 1000); - const leakyKnownAtBar = makeBar( - 101, - Date.UTC(2025, 2, 25, 20, 0, 0), - 148, - VAULT_CUTOFF_TS - ); - - const fake = createFakeStore({ - batches: [{ rows: [preBar, leakyTsBar, leakyFutureTsBar, leakyKnownAtBar] }], - }); - - const res = await callQueryData(fake, { - listingIds: [101], - from: '2025-03-01', - to: '2025-04-15', - }); - - expect(res.isError).toBe(false); - const payload = JSON.parse(res.text) as QueryDataResultPayload; - expect(payload.rowCount).toBe(1); - expect(payload.rows).toEqual([preBar]); - }); - - test('universe path resolves strictly pre-cutoff date and handles empty universe cleanly', async () => { - const preBar = makeBar(202, Date.UTC(2025, 2, 28, 20, 0, 0), 50); - const populatedFake = createFakeStore({ - universeIds: [202], - batches: [{ rows: [preBar] }], - }); - - const res = await callQueryData(populatedFake, { - universe: 'US_EQ', - from: '2025-03-01', - to: '2025-04-30', - }); - - expect(res.isError).toBe(false); - expect(populatedFake.universeCalls).toEqual([{ ref: 'US_EQ', date: '2025-03-30' }]); - expect(populatedFake.barsCalls).toHaveLength(1); - expect(populatedFake.barsCalls[0]?.listingIds).toEqual([202]); - expect(populatedFake.barsCalls[0]?.scope).toBe('vault_fenced'); - - // Empty universe -> zero bars() calls - const emptyFake = createFakeStore({ universeIds: [] }); - const emptyRes = await callQueryData(emptyFake, { - universe: 'CA_EQ', - from: '2025-03-01', - to: '2025-03-30', - }); - expect(emptyRes.isError).toBe(false); - expect(emptyFake.universeCalls).toHaveLength(1); - expect(emptyFake.barsCalls).toHaveLength(0); - const emptyPayload = JSON.parse(emptyRes.text) as QueryDataResultPayload; - expect(emptyPayload.rowCount).toBe(0); - expect(emptyPayload.rows).toEqual([]); - }); - - test('maps store domain errors and unexpected errors without leaking paths or stack traces', async () => { - const domainErrors: readonly [Error, string][] = [ - [new VaultScopeNotAuthorizedError(), 'VaultScopeNotAuthorizedError'], - [ - new MarketDataStoreValidationError( - 'Invalid curatedRoot "/mnt/data/stockbot/curated"', - 'curatedRoot' - ), - 'MarketDataStoreValidationError', - ], - [ - new MarketDataStoreValidationError('Bad from timestamp "/etc/passwd"', 'from'), - 'MarketDataStoreValidationError', - ], - [ - new MarketDataStoreNotImplementedError('bars', '1m not supported at /srv/secret/bars.parquet'), - 'MarketDataStoreNotImplementedError', - ], - [ - new AdjFactorsSnapshotError( - 'unpinned_mutable_path', - 'Refusing unpinned mutable adj_factors path "/mnt/data/stockbot/curated/adj_factors/part.parquet"', - '/mnt/data/stockbot/curated/adj_factors/part.parquet' - ), - 'AdjFactorsSnapshotError', - ], - ]; - - for (const [err, expectedName] of domainErrors) { - const fake = createFakeStore({ barsError: err }); - const res = await callQueryData(fake, { - listingIds: [101], - from: '2025-03-01', - to: '2025-03-30', - }); - expect(res.isError).toBe(true); - expect(res.text).toContain(expectedName); - expect(res.text).not.toContain('/mnt/data/stockbot'); - expect(res.text).not.toContain('/srv/secret'); - expect(res.text).not.toContain('/etc/passwd'); - expect(res.text).not.toContain('part.parquet'); - expect(res.text).not.toContain('\n'); - expect(res.text).not.toContain('at '); - } - - // Unexpected non-domain error containing a filesystem path on the first line - const unexpectedErr = new Error( - 'EACCES: permission denied, open /mnt/data/stockbot/curated/bars_1d/year=2025/part.parquet\n at open (/srv/app/store.ts:12:3)' - ); - const unexpectedFake = createFakeStore({ barsError: unexpectedErr }); - const unexpectedRes = await callQueryData(unexpectedFake, { - listingIds: [101], - from: '2025-03-01', - to: '2025-03-30', - }); - expect(unexpectedRes.isError).toBe(true); - expect(unexpectedRes.text).toBe('Error: Tool execution failed.'); - expect(unexpectedRes.text).not.toContain('/mnt/data/stockbot'); - expect(unexpectedRes.text).not.toContain('/srv/app/store.ts'); - }); - - test('universe lookup uses min(to, asOf) and completed UTC date so later trading cannot leak into earlier asOf', async () => { - const janBar101 = makeBar(101, Date.UTC(2025, 0, 15, 20, 0, 0), 100); - const janBar202 = makeBar(202, Date.UTC(2025, 0, 15, 20, 0, 0), 50); - const allBarsByListing = new Map([ - [101, [janBar101]], - [202, [janBar202]], - ]); - - const universeDates: string[] = []; - const store: MarketDataStore = { - async universe(q: UniverseQuery): Promise { - universeDates.push(q.date); - // Listing 202 resumed trading on 2025-03-26, so it is NOT active on 2025-03-03 - return q.date >= '2025-03-26' ? [101, 202] : [101]; - }, - bars(q: BarsQuery): AsyncIterable { - const rows = q.listingIds.flatMap(id => [...(allBarsByListing.get(id) ?? [])]); - return { - async *[Symbol.asyncIterator]() { - yield { rows }; - }, - }; - }, - crossSection() { - throw new MarketDataStoreNotImplementedError('crossSection'); - }, - fundamentalsAsOf() { - throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); - }, - events() { - throw new MarketDataStoreNotImplementedError('events'); - }, - shortsAsOf() { - throw new MarketDataStoreNotImplementedError('shortsAsOf'); - }, - macroAsOf() { - throw new MarketDataStoreNotImplementedError('macroAsOf'); - }, - fx() { - throw new MarketDataStoreNotImplementedError('fx'); - }, - }; - - const fake: FakeStoreState = { barsCalls: [], universeCalls: [], store }; - - // Date-only asOf earlier than to -> universe queried on 2025-03-03, excluding listing 202 - const dateOnlyRes = await callQueryData(fake, { - universe: 'US_EQ', - from: '2025-01-01', - to: '2025-03-28', - asOf: '2025-03-03', - }); - expect(dateOnlyRes.isError).toBe(false); - expect(universeDates).toEqual(['2025-03-03']); - const payload = JSON.parse(dateOnlyRes.text) as QueryDataResultPayload; - expect(payload.rows).toEqual([janBar101]); - - // Intraday asOf on 2025-03-03 -> uses completed UTC date 2025-03-02 - const intradayRes = await callQueryData(fake, { - universe: 'US_EQ', - from: '2025-01-01', - to: '2025-03-28', - asOf: '2025-03-03T12:00:00Z', - }); - expect(intradayRes.isError).toBe(false); - expect(universeDates).toEqual(['2025-03-03', '2025-03-02']); - }); - - test('DuckDB planner integration preserves microsecond bounds, accepts matching fenced adj_factors snapshot, and sanitizes snapshot errors', async () => { - const recordedQueries: { sql: string; params: readonly DuckDbParam[] }[] = []; - const expectedVaultCeilingMicros = VAULT_CUTOFF_TS * 1000 - 1; - const barTs = Date.UTC(2025, 2, 20, 20, 0, 0); - - const executor: DuckDbExecutor = { - async run() { - // no-op in memory - }, - async query(sql, params) { - recordedQueries.push({ sql, params }); - if (sql.includes('parquet_kv_metadata')) { - return [ - { key: `${ADJ_SNAPSHOT_KV_PREFIX}format_version`, value: String(ADJ_SNAPSHOT_FORMAT_VERSION) }, - { key: `${ADJ_SNAPSHOT_KV_PREFIX}snapshot_kind`, value: 'point_in_time_fenced' }, - { key: `${ADJ_SNAPSHOT_KV_PREFIX}as_of_micros`, value: 'none' }, - { key: `${ADJ_SNAPSHOT_KV_PREFIX}vault_cutoff_micros`, value: String(VAULT_CUTOFF_TS * 1000) }, - { key: `${ADJ_SNAPSHOT_KV_PREFIX}rows_written`, value: '10' }, - { key: `${ADJ_SNAPSHOT_KV_PREFIX}snapshot_checksum`, value: '0x0123456789abcdef' }, - ]; - } - return [ - { - listing_id: 101, - ts: barTs, - open: 99, - high: 101, - low: 98, - close: 100, - volume: 2_000, - vwap: 100, - known_at: barTs, - }, - ]; - }, - }; - - const duckStore = createDuckDbMarketDataStore({ - curatedRoot: '/mnt/data/stockbot/curated', - vaultCutoffTs: VAULT_CUTOFF_TS, - immutableAdjFactorsPath: '/mnt/data/stockbot/curated/snapshots/adj_2025_03_30.parquet', - executor, - }); - - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createQueryDataTool({ - store: duckStore, - vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, - }), - ], - }); - - // 1. Split-adjusted bars with omitted asOf and clamped to -> forwards .999999Z matching snapshot ceiling - const splitRaw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 'duck-1', - method: 'tools/call', - params: { - name: 'query_data', - arguments: { - listingIds: [101], - from: '2025-03-01', - to: '2025-04-15', - adjustment: 'split', - }, - }, - }) - ); - const splitResp = JSON.parse(splitRaw as string) as { - result: { isError?: boolean; content: { type: string; text: string }[] }; - }; - expect(splitResp.result.isError).toBeUndefined(); - const splitPayload = JSON.parse(splitResp.result.content[0]?.text ?? '{}') as QueryDataResultPayload; - expect(splitPayload.rowCount).toBe(1); - expect(expectedVaultCeilingMicros).toBe(Date.UTC(2025, 2, 30, 23, 59, 59, 999) * 1000 + 999); - const barsQuery1 = recordedQueries.find(q => q.sql.includes('bars_1d')); - expect(barsQuery1).toBeDefined(); - expect(barsQuery1?.params).toEqual([ - 101, - '2025-03-30T23:59:59.999999Z', - 101, - '2025-03-01T00:00:00.000Z', - '2025-03-30T23:59:59.999999Z', - '2025-03-30T23:59:59.999999Z', - ]); - - // 2. Caller-supplied sub-millisecond bounds within the fence are preserved verbatim - recordedQueries.length = 0; - const preciseRaw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 'duck-2', - method: 'tools/call', - params: { - name: 'query_data', - arguments: { - listingIds: [101], - from: '2025-03-01T00:00:00.000123Z', - to: '2025-03-20T12:34:56.123456Z', - asOf: '2025-03-25T08:09:10.654321Z', - adjustment: 'raw', - }, - }, - }) - ); - const preciseResp = JSON.parse(preciseRaw as string) as { - result: { isError?: boolean; content: { type: string; text: string }[] }; - }; - expect(preciseResp.result.isError).toBeUndefined(); - const barsQuery2 = recordedQueries.find(q => q.sql.includes('bars_1d')); - expect(barsQuery2?.params).toEqual([ - 101, - '2025-03-01T00:00:00.000123Z', - '2025-03-20T12:34:56.123456Z', - '2025-03-25T08:09:10.654321Z', - ]); - - // 3. Unpinned mutable adj_factors path fails closed without leaking internal filesystem path - const unpinnedStore = createDuckDbMarketDataStore({ - curatedRoot: '/mnt/data/stockbot/curated', - vaultCutoffTs: VAULT_CUTOFF_TS, - executor, - }); - const unpinnedServer = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createQueryDataTool({ - store: unpinnedStore, - vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, - }), - ], - }); - const unpinnedRaw = await unpinnedServer.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 'duck-3', - method: 'tools/call', - params: { - name: 'query_data', - arguments: { - listingIds: [101], - from: '2025-03-01', - to: '2025-03-30', - adjustment: 'split', - }, - }, - }) - ); - const unpinnedResp = JSON.parse(unpinnedRaw as string) as { - result: { isError?: boolean; content: { type: string; text: string }[] }; - }; - expect(unpinnedResp.result.isError).toBe(true); - const unpinnedText = unpinnedResp.result.content[0]?.text ?? ''; - expect(unpinnedText).toContain('AdjFactorsSnapshotError'); - expect(unpinnedText).not.toContain('/mnt/data/stockbot'); - expect(unpinnedText).not.toContain('part.parquet'); - }); - - test('raw JSON own __proto__ key in query_data arguments returns isError: true with zero store calls', async () => { - const fake = createFakeStore({ - batches: [{ rows: [makeBar(101, Date.UTC(2025, 2, 20, 20, 0, 0), 100)] }], - }); - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createQueryDataTool({ - store: fake.store, - vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, - }), - ], - }); - - const rawRequest = - '{"jsonrpc":"2.0","id":"proto-q","method":"tools/call","params":{"name":"query_data","arguments":{"listingIds":[101],"from":"2025-03-01","to":"2025-03-30","__proto__":{"scope":"vault_evaluation_only"}}}}'; - const rawResponse = await server.handleMessage(rawRequest); - const parsed = JSON.parse(rawResponse as string) as { - result: { isError?: boolean; content: { type: string; text: string }[] }; - }; - expect(parsed.result.isError).toBe(true); - expect(fake.barsCalls).toHaveLength(0); - expect(fake.universeCalls).toHaveLength(0); - }); - - test('repeated identical calls produce byte-identical JSON output', async () => { - const bar = makeBar(101, Date.UTC(2025, 2, 28, 20, 0, 0), 150.25); - const fake1 = createFakeStore({ batches: [{ rows: [bar] }] }); - const fake2 = createFakeStore({ batches: [{ rows: [bar] }] }); - - const args = { - listingIds: [101], - from: '2025-03-01', - to: '2025-03-30', - timeframe: '1d', - adjustment: 'raw', - limit: 10, - }; - - const res1 = await callQueryData(fake1, args); - const res2 = await callQueryData(fake2, args); - expect(res1.rawResponse).toBe(res2.rawResponse); - }); -}); diff --git a/libs/research/test/mcp-read-knowledge-qa.test.ts b/libs/research/test/mcp-read-knowledge-qa.test.ts deleted file mode 100644 index b9d233c5..00000000 --- a/libs/research/test/mcp-read-knowledge-qa.test.ts +++ /dev/null @@ -1,581 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { - createMcpServer, - createReadKnowledgeTool, - type FindingQuery, - type FindingRecord, - type KnowledgePort, - type LibraryCardQuery, - type LibraryCardRecord, - type ProviderCaveatQuery, - type ProviderCaveatRecord, - READ_KNOWLEDGE_MAX_LIMIT, - READ_KNOWLEDGE_MAX_QUERY_LENGTH, - READ_KNOWLEDGE_MAX_TEXT_LENGTH, - type ReadKnowledgeResultPayload, -} from '../src/mcp/index'; - -// QA fixtures: deterministic in-memory KnowledgePort (no network, no Postgres, -// no filesystem). All timestamps are pinned ISO strings; shuffles use a seeded PRNG. - -const SECRET = 'postgres://admin:super-secret@10.0.0.51:5432/trading_bot'; - -function card(id: string, o: Partial = {}): LibraryCardRecord { - return { - id, - title: o.title ?? `Card ${id}`, - tags: o.tags ?? ['methodology'], - summary: o.summary ?? `Summary ${id}`, - body: o.body ?? `Body ${id}`, - }; -} - -function finding(id: string, o: Partial = {}): FindingRecord { - return { - id, - title: o.title ?? `Finding ${id}`, - status: o.status ?? 'confirmed', - createdAt: o.createdAt ?? '2025-01-15T12:00:00.000Z', - summary: o.summary ?? `Finding summary ${id}`, - trialRefs: o.trialRefs ?? [`trial-${id}`], - evidenceRefs: o.evidenceRefs ?? [`ev-${id}`], - }; -} - -function caveat(id: string, o: Partial = {}): ProviderCaveatRecord { - return { - id, - provider: o.provider ?? 'eodhd', - dataset: o.dataset ?? `dataset_${id}`, - caveat: o.caveat ?? `Caveat ${id}`, - createdAt: o.createdAt ?? '2025-01-20T08:30:00.000Z', - }; -} - -interface PortImpl { - readonly library?: (q: LibraryCardQuery) => unknown; - readonly findings?: (q: FindingQuery) => unknown; - readonly caveats?: (q: ProviderCaveatQuery) => unknown; -} - -function makePort(impl: PortImpl): { port: KnowledgePort; calls: string[] } { - const calls: string[] = []; - const port: KnowledgePort = { - listLibraryCards(q) { - calls.push('listLibraryCards'); - return (impl.library ?? (() => Promise.resolve([])))(q) as Promise< - readonly LibraryCardRecord[] - >; - }, - listFindings(q) { - calls.push('listFindings'); - return (impl.findings ?? (() => Promise.resolve([])))(q) as Promise< - readonly FindingRecord[] - >; - }, - listProviderCaveats(q) { - calls.push('listProviderCaveats'); - return (impl.caveats ?? (() => Promise.resolve([])))(q) as Promise< - readonly ProviderCaveatRecord[] - >; - }, - }; - return { port, calls }; -} - -function staticPort( - library: readonly LibraryCardRecord[], - findings: readonly FindingRecord[], - caveats: readonly ProviderCaveatRecord[] -): { port: KnowledgePort; calls: string[] } { - return makePort({ - library: async () => library, - findings: async () => findings, - caveats: async () => caveats, - }); -} - -async function call( - port: KnowledgePort, - args: Record | undefined -): Promise<{ isError: boolean; text: string; payload: ReadKnowledgeResultPayload | null }> { - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [createReadKnowledgeTool({ port })], - }); - const params: Record = { name: 'read_knowledge' }; - if (args !== undefined) { - params.arguments = args; - } - const raw = await server.handleMessage( - JSON.stringify({ jsonrpc: '2.0', id: 'qa', method: 'tools/call', params }) - ); - expect(raw).not.toBeNull(); - const parsed = JSON.parse(raw as string) as { - result: { isError?: boolean; content: { type: string; text: string }[] }; - }; - const isError = parsed.result.isError === true; - const text = parsed.result.content[0]?.text ?? ''; - return { isError, text, payload: isError ? null : (JSON.parse(text) as ReadKnowledgeResultPayload) }; -} - -function expectSanitized(res: { isError: boolean; text: string }): void { - expect(res.isError).toBe(true); - expect(res.text).toMatch(/^[A-Za-z][A-Za-z0-9_]*: Tool execution failed\.$/); - for (const leak of ['super-secret', '10.0.0.51', 'trading_bot', 'postgres://', 'db.ts', ' at ']) { - expect(res.text).not.toContain(leak); - } -} - -function deepFreeze(value: T): T { - if (typeof value === 'object' && value !== null) { - for (const v of Object.values(value)) { - deepFreeze(v); - } - Object.freeze(value); - } - return value; -} - -// mulberry32 — seeded PRNG for reproducible shuffles. -function seededShuffle(items: readonly T[], seed: number): T[] { - let s = seed >>> 0; - const rand = (): number => { - s = (s + 0x6d2b79f5) >>> 0; - let t = s; - t = Math.imul(t ^ (t >>> 15), t | 1); - t ^= t + Math.imul(t ^ (t >>> 7), t | 61); - return ((t ^ (t >>> 14)) >>> 0) / 4294967296; - }; - const out = [...items]; - for (let i = out.length - 1; i > 0; i -= 1) { - const j = Math.floor(rand() * (i + 1)); - [out[i], out[j]] = [out[j] as T, out[i] as T]; - } - return out; -} - -describe('read_knowledge QA: port failures and malformed port output', () => { - test('non-Error rejections and synchronous throws carrying connection strings are sanitized', async () => { - const cases: PortImpl[] = [ - { library: () => Promise.reject(SECRET) }, - { findings: () => Promise.reject({ message: SECRET, stack: 'at /srv/db.ts:1' }) }, - { - caveats: () => { - throw new Error(SECRET); - }, - }, - { - library: () => { - const err = new Error(SECRET); - err.name = SECRET; - throw err; - }, - }, - ]; - for (const impl of cases) { - const { port } = makePort(impl); - const res = await call(port, { query: 'alpha' }); - expectSanitized(res); - } - }); - - test('malformed port responses map to a sanitized isError without echoing record contents', async () => { - const badResponses: PortImpl[] = [ - { library: async () => SECRET }, - { library: async () => undefined }, - { library: async () => [null] }, - { library: async () => [{ ...card('c1'), id: 42 }] }, - { library: async () => [{ ...card('c1'), tags: [SECRET, 7] }] }, - { library: async () => [{ ...card('c1'), tags: SECRET }] }, - { findings: async () => [{ ...finding('f1'), trialRefs: undefined }] }, - { findings: async () => [{ ...finding('f1'), createdAt: 1_700_000_000_000 }] }, - { caveats: async () => [{ ...caveat('v1'), caveat: { text: SECRET } }] }, - { caveats: async () => ({ rows: [caveat('v1')] }) }, - ]; - for (const impl of badResponses) { - const { port } = makePort(impl); - const res = await call(port, {}); - expectSanitized(res); - } - }); - - // Regression: port calls were started eagerly inside the Promise.all array literal, so a - // synchronous throw from a later source abandoned an earlier source's rejected promise. - // Bun treats that unhandled rejection as fatal: the MCP stdio process exits 1 after replying - // and prints the raw error (including any connection string) to stderr. Bun's test runner - // also reports it as an error between tests, so the scenario runs in a child process. - test('earlier async rejection combined with a later synchronous throw does not crash the process', () => { - const indexPath = new URL('../src/mcp/index.ts', import.meta.url).pathname; - const script = ` - import { createMcpServer, createReadKnowledgeTool } from ${JSON.stringify(indexPath)}; - const secret = ${JSON.stringify(SECRET)}; - const combos = [ - { listLibraryCards: () => Promise.reject(new Error(secret)), listFindings: () => { throw new Error('sync'); }, listProviderCaveats: async () => [] }, - { listLibraryCards: () => Promise.reject(new Error(secret)), listFindings: async () => [], listProviderCaveats: () => { throw new Error('sync'); } }, - { listLibraryCards: async () => [], listFindings: () => Promise.reject(new Error(secret)), listProviderCaveats: () => { throw new Error('sync'); } }, - ]; - for (const port of combos) { - const server = createMcpServer({ name: 'qa', version: '0.0.0', tools: [createReadKnowledgeTool({ port })] }); - const raw = await server.handleMessage(JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'read_knowledge', arguments: {} } })); - console.log(JSON.parse(raw).result.content[0].text); - } - await new Promise(resolve => setTimeout(resolve, 20)); - console.log('DONE'); - `; - - const proc = Bun.spawnSync([process.execPath, '-e', script], { - stdout: 'pipe', - stderr: 'pipe', - timeout: 30_000, - }); - const stdout = proc.stdout.toString(); - const stderr = proc.stderr.toString(); - - expect(stdout.trim().split('\n')).toEqual([ - 'Error: Tool execution failed.', - 'Error: Tool execution failed.', - 'Error: Tool execution failed.', - 'DONE', - ]); - expect(stderr).not.toContain('super-secret'); - expect(proc.exitCode).toBe(0); - }); -}); - -describe('read_knowledge QA: read-only port usage', () => { - test('never calls write-like methods present on the injected object and calls each read method at most once', async () => { - const writes: string[] = []; - const base = staticPort([card('c1')], [finding('f1')], [caveat('v1')]); - const port = Object.assign(base.port, { - fileFinding: () => writes.push('fileFinding'), - upsertCard: () => writes.push('upsertCard'), - deleteCaveat: () => writes.push('deleteCaveat'), - }); - - for (const args of [{}, { source: 'library' }, { id: 'f1' }, { query: 'card', limit: 1 }]) { - base.calls.length = 0; - const res = await call(port, args); - expect(res.isError).toBe(false); - expect(new Set(base.calls).size).toBe(base.calls.length); - } - expect(writes).toEqual([]); - }); - - test('does not mutate deeply frozen port records and returns copies of array fields', async () => { - const lib = deepFreeze([card('c1', { tags: ['Alpha', 'beta'], body: 'b'.repeat(5000) })]); - const fin = deepFreeze([finding('f1', { title: 'Alpha finding' })]); - const cav = deepFreeze([caveat('v1', { dataset: 'alpha_ds', caveat: 'c'.repeat(5000) })]); - const snapshot = JSON.stringify([lib, fin, cav]); - const { port } = staticPort(lib, fin, cav); - - const res = await call(port, { query: 'alpha', tags: ['ALPHA'] }); - - expect(res.isError).toBe(false); - expect(res.payload?.rowCount).toBe(3); - expect(JSON.stringify([lib, fin, cav])).toBe(snapshot); - }); - - test('omitted tools/call arguments use defaults and call all three sources with an empty selector', async () => { - const seen: unknown[] = []; - const { port, calls } = makePort({ - library: async q => { - seen.push(q); - return [card('c1')]; - }, - findings: async q => { - seen.push(q); - return [finding('f1')]; - }, - caveats: async q => { - seen.push(q); - return [caveat('v1')]; - }, - }); - - const res = await call(port, undefined); - - expect(res.isError).toBe(false); - expect(calls.sort()).toEqual(['listFindings', 'listLibraryCards', 'listProviderCaveats']); - expect(seen).toEqual([{}, {}, {}]); - expect(res.payload?.sources).toEqual({ library: 1, findings: 1, provider_caveats: 1 }); - }); -}); - -describe('read_knowledge QA: input boundaries', () => { - test('accepts query at exactly the cap, including when surrounding whitespace is trimmed', async () => { - const atCap = 'q'.repeat(READ_KNOWLEDGE_MAX_QUERY_LENGTH); - const seen: (string | undefined)[] = []; - const { port } = makePort({ - library: async q => { - seen.push(q.query); - return [card('c1', { title: `x${atCap}x` })]; - }, - }); - - for (const query of [atCap, ` ${atCap}\t\n `]) { - const res = await call(port, { source: 'library', query }); - expect(res.isError).toBe(false); - expect(res.payload?.rows.map(r => r.id)).toEqual(['c1']); - } - expect(seen).toEqual([atCap, atCap]); - }); - - test('accepts limit 1 and limit max as boundary values', async () => { - const lib = Array.from({ length: READ_KNOWLEDGE_MAX_LIMIT + 5 }, (_, i) => - card(`c${String(i).padStart(3, '0')}`) - ); - const { port } = staticPort(lib, [], []); - - const one = await call(port, { limit: 1 }); - const max = await call(port, { limit: READ_KNOWLEDGE_MAX_LIMIT }); - - expect(one.payload?.rows.map(r => r.id)).toEqual(['c000']); - expect(max.payload?.rowCount).toBe(READ_KNOWLEDGE_MAX_LIMIT); - expect(max.payload?.rows.at(-1)?.id).toBe('c099'); - }); - - test('rejects null-valued optional selectors and non-array tags before calling the port', async () => { - for (const args of [ - { query: null }, - { id: null }, - { tags: 'alpha' }, - { tags: [1] }, - { provider: ['eodhd'] }, - { source: null }, - { limit: null }, - { limit: Number.POSITIVE_INFINITY }, - ]) { - const { port, calls } = staticPort([card('c1')], [], []); - const res = await call(port, args); - expect(res.isError).toBe(true); - expect(res.text).toContain('Invalid arguments for tool "read_knowledge"'); - expect(calls).toEqual([]); - } - }); -}); - -describe('read_knowledge QA: matching semantics', () => { - test('free-text query does not match on id, status, createdAt, or trial/evidence refs alone', async () => { - const { port } = staticPort( - [card('zeta-card', { title: 'A', tags: ['b'], summary: 'c', body: 'zeta in body only' })], - [ - finding('zeta-finding', { - title: 'A', - summary: 'c', - status: 'zeta', - createdAt: 'zeta', - trialRefs: ['zeta'], - evidenceRefs: ['zeta'], - }), - ], - [caveat('zeta-caveat', { provider: 'p', dataset: 'd', caveat: 'c', createdAt: 'zeta' })] - ); - - const res = await call(port, { query: 'zeta' }); - - expect(res.payload).toEqual({ - rowCount: 0, - sources: { library: 0, findings: 0, provider_caveats: 0 }, - rows: [], - }); - }); - - test('provider filter is exact (not substring) and tags filter requires whole-tag equality', async () => { - const { port } = staticPort( - [card('c-full', { tags: ['momentum'] }), card('c-partial', { tags: ['momentum-crash'] })], - [], - [caveat('v-eodhd', { provider: 'eodhd' }), caveat('v-eod', { provider: 'eod' })] - ); - - const byProvider = await call(port, { source: 'provider_caveats', provider: 'EOD' }); - const byTag = await call(port, { source: 'library', tags: ['Momentum'] }); - - expect(byProvider.payload?.rows.map(r => r.id)).toEqual(['v-eod']); - expect(byTag.payload?.rows.map(r => r.id)).toEqual(['c-full']); - }); - - test('provider matched in free text ranks below a dataset match for caveats', async () => { - const { port } = staticPort( - [], - [], - [ - caveat('a-provider', { provider: 'quantmedia', dataset: 'bars', caveat: 'x' }), - caveat('z-dataset', { provider: 'eodhd', dataset: 'quantmedia_filings', caveat: 'x' }), - ] - ); - - const res = await call(port, { query: 'QuantMedia' }); - - expect(res.payload?.rows.map(r => r.id)).toEqual(['z-dataset', 'a-provider']); - }); - - test('id lookup still honours source-specific filters: tag mismatch drops the card but keeps other sources under all', async () => { - const { port } = staticPort( - [card('shared', { tags: ['risk'] })], - [finding('shared')], - [caveat('shared', { provider: 'polygon' })] - ); - - const res = await call(port, { id: 'shared', tags: ['momentum'], provider: 'eodhd' }); - - expect(res.payload?.rows.map(r => `${r.source}:${r.id}`)).toEqual(['findings:shared']); - expect(res.payload?.sources).toEqual({ library: 0, findings: 1, provider_caveats: 0 }); - }); - - test('regex and wildcard metacharacters in query are matched literally', async () => { - const { port } = staticPort( - [card('c-literal', { title: 'Sharpe (annualised) * sqrt(252)' }), card('c-plain', { title: 'Sharpe annualised' })], - [finding('f-dot', { summary: 'a.b' }), finding('f-any', { summary: 'axb' })], - [caveat('v-pct', { caveat: '100% adjusted' }), caveat('v-none', { caveat: '100 adjusted' })] - ); - - const paren = await call(port, { query: '(annualised) *' }); - const dot = await call(port, { query: 'a.b' }); - const pct = await call(port, { query: '100%' }); - - expect(paren.payload?.rows.map(r => r.id)).toEqual(['c-literal']); - expect(dot.payload?.rows.map(r => r.id)).toEqual(['f-dot']); - expect(pct.payload?.rows.map(r => r.id)).toEqual(['v-pct']); - }); - - test('case-insensitive matching handles non-ASCII text', async () => { - const { port } = staticPort( - [card('c1', { title: 'Étude des rendements' })], - [finding('f1', { summary: 'ÜBERRENDITE nach Ankündigung' })], - [] - ); - - const res = await call(port, { query: 'étude' }); - const res2 = await call(port, { query: 'überrendite' }); - - expect(res.payload?.rows.map(r => r.id)).toEqual(['c1']); - expect(res2.payload?.rows.map(r => r.id)).toEqual(['f1']); - }); - - test('projects exactly the documented fields for findings and caveats, dropping extra port fields', async () => { - const extraFinding = { ...finding('f1'), holdoutPnl: 123, dsn: SECRET } as FindingRecord; - const extraCaveat = { ...caveat('v1'), internalNote: SECRET } as ProviderCaveatRecord; - const { port } = staticPort([], [extraFinding], [extraCaveat]); - - const res = await call(port, {}); - - expect(res.text).not.toContain('super-secret'); - expect(res.text).not.toContain('holdoutPnl'); - expect(res.payload?.rows).toEqual([ - { - source: 'findings', - id: 'f1', - title: 'Finding f1', - status: 'confirmed', - createdAt: '2025-01-15T12:00:00.000Z', - summary: 'Finding summary f1', - trialRefs: ['trial-f1'], - evidenceRefs: ['ev-f1'], - truncated: false, - }, - { - source: 'provider_caveats', - id: 'v1', - provider: 'eodhd', - dataset: 'dataset_v1', - caveat: 'Caveat v1', - createdAt: '2025-01-20T08:30:00.000Z', - truncated: false, - }, - ]); - }); -}); - -describe('read_knowledge QA: deterministic ranking and limit', () => { - test('seeded permutations of a mixed fixture replay to identical rows and counts at every limit', async () => { - const lib = [ - card('m-title', { title: 'Drift study', summary: 's' }), - card('a-tag', { title: 'x', tags: ['drift'] }), - card('Q-sum', { title: 'x', summary: 'post drift' }), - card('shared', { title: 'Drift shared', summary: 's' }), - ]; - const fin = [ - finding('shared', { title: 'Drift finding' }), - finding('b-sum', { title: 'x', summary: 'DRIFT' }), - finding('k-none', { title: 'x', summary: 'nothing' }), - ]; - const cav = [ - caveat('shared', { dataset: 'drift_ds' }), - caveat('c-cav', { dataset: 'bars', caveat: 'drift noted' }), - ]; - - for (const limit of [1, 2, 3, 5, 8, 20]) { - let baseline: ReadKnowledgeResultPayload | null = null; - for (let seed = 1; seed <= 12; seed += 1) { - const { port } = staticPort( - seededShuffle(lib, seed), - seededShuffle(fin, seed * 7), - seededShuffle(cav, seed * 13) - ); - const res = await call(port, { query: 'drift', limit }); - expect(res.isError).toBe(false); - if (baseline === null) { - baseline = res.payload; - } else { - expect(res.payload).toEqual(baseline); - } - } - const expectedOrder = [ - 'library:m-title', - 'library:shared', - 'findings:shared', - 'provider_caveats:shared', - 'library:Q-sum', - 'library:a-tag', - 'findings:b-sum', - 'provider_caveats:c-cav', - ].slice(0, limit); - expect(baseline?.rows.map(r => `${r.source}:${r.id}`)).toEqual(expectedOrder); - const counts = { library: 0, findings: 0, provider_caveats: 0 }; - for (const r of baseline?.rows ?? []) { - counts[r.source] += 1; - } - expect(baseline?.sources).toEqual(counts); - expect(baseline?.rowCount).toBe(expectedOrder.length); - } - }); - - test('truncation flag reflects only text fields over the cap; title, tags and refs are never truncated', async () => { - const longTitle = 'T'.repeat(READ_KNOWLEDGE_MAX_TEXT_LENGTH + 10); - const { port } = staticPort( - [card('c1', { title: longTitle, tags: ['t'.repeat(READ_KNOWLEDGE_MAX_TEXT_LENGTH + 1)] })], - [finding('f1', { title: longTitle })], - [] - ); - - const res = await call(port, {}); - - for (const row of res.payload?.rows ?? []) { - expect(row.truncated).toBe(false); - if (row.source !== 'provider_caveats') { - expect(row.title).toHaveLength(longTitle.length); - } - } - }); -}); - -describe('read_knowledge QA: limit cutting through a cross-source tie', () => { - test('limit inside a same-id tie keeps library > findings > provider_caveats and counts only returned rows', async () => { - const { port } = staticPort( - [card('dup', { title: 'Basis risk' })], - [finding('dup', { title: 'Basis risk' })], - [caveat('dup', { dataset: 'basis_ds' })] - ); - - const two = await call(port, { query: 'basis', limit: 2 }); - - expect(two.payload?.rows.map(r => `${r.source}:${r.id}`)).toEqual([ - 'library:dup', - 'findings:dup', - ]); - expect(two.payload?.sources).toEqual({ library: 1, findings: 1, provider_caveats: 0 }); - expect(two.payload?.rowCount).toBe(2); - }); -}); diff --git a/libs/research/test/mcp-read-knowledge.test.ts b/libs/research/test/mcp-read-knowledge.test.ts deleted file mode 100644 index ec32fe0e..00000000 --- a/libs/research/test/mcp-read-knowledge.test.ts +++ /dev/null @@ -1,1110 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import type { MarketDataStore } from '../src/market-data-store'; -import { MarketDataStoreNotImplementedError } from '../src/market-data-store-duckdb'; -import { - type FindingQuery, - type FindingRecord, - type KnowledgePort, - type LibraryCardQuery, - type LibraryCardRecord, - type ProviderCaveatQuery, - type ProviderCaveatRecord, - READ_KNOWLEDGE_DEFAULT_LIMIT, - READ_KNOWLEDGE_MAX_LIMIT, - READ_KNOWLEDGE_MAX_QUERY_LENGTH, - READ_KNOWLEDGE_MAX_TEXT_LENGTH, - READ_KNOWLEDGE_SOURCES, - type ReadKnowledgeResultPayload, - type SymbolSearchPort, - createAnalyzeSignalTool, - createEventStudyTool, - createMcpServer, - createQueryDataTool, - createReadKnowledgeTool, - createSearchSymbolsTool, - readKnowledgeInputSchema, -} from '../src/mcp/index'; -import type { TrialLedgerExecutor } from '../src/trial-ledger'; - -const VAULT_CUTOFF_TS = Date.UTC(2025, 2, 31, 0, 0, 0, 0); - -function makeLibraryCard( - overrides: Partial & { readonly id: string } -): LibraryCardRecord { - return { - id: overrides.id, - title: overrides.title ?? `Card ${overrides.id}`, - tags: overrides.tags ?? ['methodology'], - summary: overrides.summary ?? `Summary for ${overrides.id}`, - body: overrides.body ?? `Body for ${overrides.id}`, - }; -} - -function makeFinding(overrides: Partial & { readonly id: string }): FindingRecord { - return { - id: overrides.id, - title: overrides.title ?? `Finding ${overrides.id}`, - status: overrides.status ?? 'confirmed', - createdAt: overrides.createdAt ?? '2025-01-15T12:00:00.000Z', - summary: overrides.summary ?? `Finding summary for ${overrides.id}`, - trialRefs: overrides.trialRefs ?? [`trial-${overrides.id}`], - evidenceRefs: overrides.evidenceRefs ?? [`ev-${overrides.id}`], - }; -} - -function makeCaveat( - overrides: Partial & { readonly id: string } -): ProviderCaveatRecord { - return { - id: overrides.id, - provider: overrides.provider ?? 'eodhd', - dataset: overrides.dataset ?? `Dataset ${overrides.id}`, - caveat: overrides.caveat ?? `Caveat text for ${overrides.id}`, - createdAt: overrides.createdAt ?? '2025-01-20T08:30:00.000Z', - }; -} - -interface FakePortState { - readonly libraryCalls: LibraryCardQuery[]; - readonly findingsCalls: FindingQuery[]; - readonly caveatsCalls: ProviderCaveatQuery[]; - readonly invokedMethods: string[]; - readonly port: KnowledgePort; -} - -function createFakeKnowledgePort(options?: { - readonly libraryCards?: readonly LibraryCardRecord[]; - readonly findings?: readonly FindingRecord[]; - readonly providerCaveats?: readonly ProviderCaveatRecord[]; - readonly libraryError?: unknown; - readonly findingsError?: unknown; - readonly caveatsError?: unknown; - readonly applySelectors?: boolean; -}): FakePortState { - const libraryCalls: LibraryCardQuery[] = []; - const findingsCalls: FindingQuery[] = []; - const caveatsCalls: ProviderCaveatQuery[] = []; - const invokedMethods: string[] = []; - - const libraryCards = options?.libraryCards ?? []; - const findings = options?.findings ?? []; - const providerCaveats = options?.providerCaveats ?? []; - const applySelectors = options?.applySelectors === true; - - const rawPort: KnowledgePort = { - async listLibraryCards(q: LibraryCardQuery): Promise { - libraryCalls.push({ ...q }); - if (options?.libraryError !== undefined) { - throw options.libraryError; - } - if (!applySelectors) { - return [...libraryCards]; - } - return libraryCards.filter(card => { - if (q.id !== undefined && card.id !== q.id) { - return false; - } - if (q.tags !== undefined) { - const cardTags = new Set(card.tags.map(t => t.toLowerCase())); - if (!q.tags.every(t => cardTags.has(t.toLowerCase()))) { - return false; - } - } - if (q.query !== undefined) { - const needle = q.query.toLowerCase(); - const inText = - card.title.toLowerCase().includes(needle) || - card.summary.toLowerCase().includes(needle) || - card.tags.some(t => t.toLowerCase().includes(needle)); - if (!inText) { - return false; - } - } - return true; - }); - }, - async listFindings(q: FindingQuery): Promise { - findingsCalls.push({ ...q }); - if (options?.findingsError !== undefined) { - throw options.findingsError; - } - if (!applySelectors) { - return [...findings]; - } - return findings.filter(finding => { - if (q.id !== undefined && finding.id !== q.id) { - return false; - } - if (q.query !== undefined) { - const needle = q.query.toLowerCase(); - const inText = - finding.title.toLowerCase().includes(needle) || - finding.summary.toLowerCase().includes(needle); - if (!inText) { - return false; - } - } - return true; - }); - }, - async listProviderCaveats(q: ProviderCaveatQuery): Promise { - caveatsCalls.push({ ...q }); - if (options?.caveatsError !== undefined) { - throw options.caveatsError; - } - if (!applySelectors) { - return [...providerCaveats]; - } - return providerCaveats.filter(caveat => { - if (q.id !== undefined && caveat.id !== q.id) { - return false; - } - if (q.provider !== undefined && caveat.provider.toLowerCase() !== q.provider.toLowerCase()) { - return false; - } - if (q.query !== undefined) { - const needle = q.query.toLowerCase(); - const inText = - caveat.provider.toLowerCase().includes(needle) || - caveat.dataset.toLowerCase().includes(needle) || - caveat.caveat.toLowerCase().includes(needle); - if (!inText) { - return false; - } - } - return true; - }); - }, - }; - - const port = new Proxy(rawPort, { - get(target, prop, receiver) { - const value: unknown = Reflect.get(target, prop, receiver); - if (typeof value === 'function' && typeof prop === 'string') { - return (...args: unknown[]) => { - invokedMethods.push(prop); - return (value as (...a: unknown[]) => unknown).apply(target, args); - }; - } - return value; - }, - }); - - return { - libraryCalls, - findingsCalls, - caveatsCalls, - invokedMethods, - port, - }; -} - -function createMinimalStore(): MarketDataStore { - return { - bars() { - return { - async *[Symbol.asyncIterator]() { - // empty stream - }, - }; - }, - async universe() { - return []; - }, - crossSection() { - throw new MarketDataStoreNotImplementedError('crossSection'); - }, - fundamentalsAsOf() { - throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); - }, - events() { - throw new MarketDataStoreNotImplementedError('events'); - }, - shortsAsOf() { - throw new MarketDataStoreNotImplementedError('shortsAsOf'); - }, - macroAsOf() { - throw new MarketDataStoreNotImplementedError('macroAsOf'); - }, - fx() { - throw new MarketDataStoreNotImplementedError('fx'); - }, - }; -} - -function createMinimalLedger(): TrialLedgerExecutor { - return { - async query() { - return { rows: [] }; - }, - }; -} - -function createMinimalSymbolPort(): SymbolSearchPort { - return { - async searchSymbols() { - return []; - }, - }; -} - -async function callReadKnowledge( - fake: FakePortState, - args: Record -): Promise<{ - readonly isError: boolean; - readonly text: string; - readonly payload: ReadKnowledgeResultPayload | null; -}> { - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [createReadKnowledgeTool({ port: fake.port })], - }); - - const raw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 'rk-1', - method: 'tools/call', - params: { - name: 'read_knowledge', - arguments: args, - }, - }) - ); - - expect(raw).not.toBeNull(); - const parsed = JSON.parse(raw as string) as { - result: { - isError?: boolean; - content: { type: string; text: string }[]; - }; - }; - const isError = parsed.result.isError === true; - const text = parsed.result.content[0]?.text ?? ''; - - return { - isError, - text, - payload: isError ? null : (JSON.parse(text) as ReadKnowledgeResultPayload), - }; -} - -describe('MCP read_knowledge tool', () => { - test('registers alongside existing MCP tools, exposes strict schema via tools/list, and executes via tools/call', async () => { - const store = createMinimalStore(); - const ledger = createMinimalLedger(); - const fake = createFakeKnowledgePort({ - libraryCards: [ - makeLibraryCard({ - id: 'card-cpcv', - title: 'Combinatorial Purged Cross-Validation', - tags: ['validation', 'overfitting'], - summary: 'Purge and embargo overlapping labels across folds.', - body: 'Detailed CPCV methodology card body.', - }), - ], - findings: [ - makeFinding({ - id: 'find-01', - title: 'Earnings drift decay post-2023', - status: 'confirmed', - createdAt: '2025-02-01T10:00:00.000Z', - summary: 'Post-earnings drift attenuates within 3 sessions.', - trialRefs: ['trial-101'], - evidenceRefs: ['ev-202'], - }), - ], - providerCaveats: [ - makeCaveat({ - id: 'cav-01', - provider: 'eodhd', - dataset: 'eodPrices', - caveat: 'Backward split adjustments must be un-adjusted before research.', - createdAt: '2025-02-05T09:00:00.000Z', - }), - ], - }); - - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createQueryDataTool({ - store, - vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, - }), - createAnalyzeSignalTool({ - store, - ledger, - vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, - principalId: 'operator', - }), - createEventStudyTool({ - store, - ledger, - vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, - principalId: 'operator', - resolveExchangeCalendars: () => ({}), - }), - createSearchSymbolsTool({ - port: createMinimalSymbolPort(), - vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, - }), - createReadKnowledgeTool({ port: fake.port }), - ], - }); - - const listRaw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 1, - method: 'tools/list', - }) - ); - expect(listRaw).not.toBeNull(); - - const listParsed = JSON.parse(listRaw as string) as { - result: { - tools: { - name: string; - description: string; - inputSchema: { - type: string; - properties: Record>; - required?: string[]; - additionalProperties: boolean; - }; - }[]; - }; - }; - - expect(listParsed.result.tools.map(t => t.name)).toEqual([ - 'query_data', - 'analyze_signal', - 'event_study', - 'search_symbols', - 'read_knowledge', - ]); - - const tool = listParsed.result.tools.find(t => t.name === 'read_knowledge'); - expect(tool).toBeDefined(); - expect(tool?.inputSchema.type).toBe('object'); - expect(tool?.inputSchema.additionalProperties).toBe(false); - expect(tool?.inputSchema.required).toBeUndefined(); - expect(tool?.inputSchema.properties.source).toMatchObject({ - type: 'string', - enum: [...READ_KNOWLEDGE_SOURCES], - default: 'all', - }); - expect(tool?.inputSchema.properties.query).toMatchObject({ - type: 'string', - minLength: 1, - maxLength: READ_KNOWLEDGE_MAX_QUERY_LENGTH, - }); - expect(tool?.inputSchema.properties.id).toMatchObject({ - type: 'string', - minLength: 1, - }); - expect(tool?.inputSchema.properties.tags).toMatchObject({ - type: 'array', - minItems: 1, - items: { type: 'string', minLength: 1 }, - }); - expect(tool?.inputSchema.properties.provider).toMatchObject({ - type: 'string', - minLength: 1, - }); - expect(tool?.inputSchema.properties.limit).toMatchObject({ - type: 'integer', - minimum: 1, - maximum: READ_KNOWLEDGE_MAX_LIMIT, - default: READ_KNOWLEDGE_DEFAULT_LIMIT, - }); - expect(tool?.inputSchema.properties.scope).toBeUndefined(); - expect(tool?.inputSchema.properties.vault_evaluation_only).toBeUndefined(); - expect(tool?.inputSchema.properties.vaultCutoffTs).toBeUndefined(); - - // Execute tools/call end-to-end on the multi-tool server. - const callRaw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 2, - method: 'tools/call', - params: { - name: 'read_knowledge', - arguments: { id: 'card-cpcv' }, - }, - }) - ); - expect(callRaw).not.toBeNull(); - const callParsed = JSON.parse(callRaw as string) as { - result: { isError?: boolean; content: { type: string; text: string }[] }; - }; - expect(callParsed.result.isError).toBeUndefined(); - const payload = JSON.parse(callParsed.result.content[0]?.text ?? '') as ReadKnowledgeResultPayload; - expect(payload).toEqual({ - rowCount: 1, - sources: { - library: 1, - findings: 0, - provider_caveats: 0, - }, - rows: [ - { - source: 'library', - id: 'card-cpcv', - title: 'Combinatorial Purged Cross-Validation', - tags: ['validation', 'overfitting'], - summary: 'Purge and embargo overlapping labels across folds.', - body: 'Detailed CPCV methodology card body.', - truncated: false, - }, - ], - }); - expect(new Set(fake.invokedMethods)).toEqual( - new Set(['listLibraryCards', 'listFindings', 'listProviderCaveats']) - ); - }); - - test('invokes only the selected source port methods with applicable parsed selectors', async () => { - const libraryCard = makeLibraryCard({ id: 'lib-1', tags: ['alpha'] }); - const finding = makeFinding({ id: 'fin-1' }); - const caveat = makeCaveat({ id: 'cav-1', provider: 'eodhd' }); - - // source: 'library' - const libFake = createFakeKnowledgePort({ - libraryCards: [libraryCard], - findings: [finding], - providerCaveats: [caveat], - }); - const libRes = await callReadKnowledge(libFake, { - source: 'library', - query: ' lib-1 ', - tags: [' alpha '], - provider: 'eodhd', - }); - expect(libRes.isError).toBe(false); - expect(libFake.invokedMethods).toEqual(['listLibraryCards']); - expect(libFake.libraryCalls).toEqual([{ query: 'lib-1', tags: ['alpha'] }]); - expect(libFake.findingsCalls).toHaveLength(0); - expect(libFake.caveatsCalls).toHaveLength(0); - expect(libRes.payload?.sources).toEqual({ library: 1, findings: 0, provider_caveats: 0 }); - - // source: 'findings' - const finFake = createFakeKnowledgePort({ - libraryCards: [libraryCard], - findings: [finding], - providerCaveats: [caveat], - }); - const finRes = await callReadKnowledge(finFake, { - source: 'findings', - query: ' fin-1 ', - tags: ['alpha'], - provider: 'eodhd', - }); - expect(finRes.isError).toBe(false); - expect(finFake.invokedMethods).toEqual(['listFindings']); - expect(finFake.findingsCalls).toEqual([{ query: 'fin-1' }]); - expect(finFake.libraryCalls).toHaveLength(0); - expect(finFake.caveatsCalls).toHaveLength(0); - expect(finRes.payload?.sources).toEqual({ library: 0, findings: 1, provider_caveats: 0 }); - - // source: 'provider_caveats' - const cavFake = createFakeKnowledgePort({ - libraryCards: [libraryCard], - findings: [finding], - providerCaveats: [caveat], - }); - const cavRes = await callReadKnowledge(cavFake, { - source: 'provider_caveats', - query: ' cav-1 ', - tags: ['alpha'], - provider: ' EODHD ', - }); - expect(cavRes.isError).toBe(false); - expect(cavFake.invokedMethods).toEqual(['listProviderCaveats']); - expect(cavFake.caveatsCalls).toEqual([{ query: 'cav-1', provider: 'EODHD' }]); - expect(cavFake.libraryCalls).toHaveLength(0); - expect(cavFake.findingsCalls).toHaveLength(0); - expect(cavRes.payload?.sources).toEqual({ library: 0, findings: 0, provider_caveats: 1 }); - - // source: 'all' (explicit) and omitted source - for (const args of [ - { source: 'all', id: ' shared-id ', tags: [' beta '], provider: ' polygon ' }, - { id: ' shared-id ', tags: [' beta '], provider: ' polygon ' }, - ]) { - const allFake = createFakeKnowledgePort(); - const allRes = await callReadKnowledge(allFake, args); - expect(allRes.isError).toBe(false); - expect(allFake.libraryCalls).toEqual([{ id: 'shared-id', tags: ['beta'] }]); - expect(allFake.findingsCalls).toEqual([{ id: 'shared-id' }]); - expect(allFake.caveatsCalls).toEqual([{ id: 'shared-id', provider: 'polygon' }]); - expect(allFake.invokedMethods).toEqual([ - 'listLibraryCards', - 'listFindings', - 'listProviderCaveats', - ]); - } - }); - - test('supports exact case-sensitive id precedence over query, missing id, and explicit field projection', async () => { - const extraCard = { - ...makeLibraryCard({ - id: 'Exact-Id', - title: 'Unrelated Title', - summary: 'Unrelated summary', - }), - internalSecret: 'must-not-leak', - } as unknown as LibraryCardRecord; - - const fake = createFakeKnowledgePort({ - libraryCards: [extraCard, makeLibraryCard({ id: 'exact-id', title: 'Lowercase ID' })], - findings: [makeFinding({ id: 'Exact-Id', title: 'Matching Finding ID' })], - providerCaveats: [makeCaveat({ id: 'Exact-Id', dataset: 'Matching Caveat ID' })], - }); - - // id takes precedence over non-matching query and is case-sensitive - const exactRes = await callReadKnowledge(fake, { - id: ' Exact-Id ', - query: 'nonexistent-query-text', - }); - expect(exactRes.isError).toBe(false); - expect(exactRes.payload?.rowCount).toBe(3); - expect(exactRes.payload?.sources).toEqual({ library: 1, findings: 1, provider_caveats: 1 }); - expect(exactRes.payload?.rows.map(r => `${r.source}:${r.id}`)).toEqual([ - 'library:Exact-Id', - 'findings:Exact-Id', - 'provider_caveats:Exact-Id', - ]); - expect('internalSecret' in (exactRes.payload?.rows[0] ?? {})).toBe(false); - - // Missing id returns empty result with zero counts - const missingRes = await callReadKnowledge(fake, { id: 'does-not-exist' }); - expect(missingRes.isError).toBe(false); - expect(missingRes.payload).toEqual({ - rowCount: 0, - sources: { library: 0, findings: 0, provider_caveats: 0 }, - rows: [], - }); - }); - - test('omits query from port selectors when id is supplied so selector-filtering ports return exact matches', async () => { - const filteringFake = createFakeKnowledgePort({ - applySelectors: true, - libraryCards: [ - makeLibraryCard({ - id: 'card-cpcv', - title: 'Combinatorial Purged Cross-Validation', - tags: ['validation'], - summary: 'Purge and embargo overlapping labels across folds.', - }), - ], - findings: [ - makeFinding({ - id: 'card-cpcv', - title: 'CPCV split stability', - summary: 'No mention of unrelated factors.', - }), - ], - providerCaveats: [ - makeCaveat({ - id: 'card-cpcv', - provider: 'eodhd', - dataset: 'eodPrices', - caveat: 'Backward split adjustments only.', - }), - ], - }); - - const res = await callReadKnowledge(filteringFake, { - id: 'card-cpcv', - query: 'momentum', - tags: ['validation'], - provider: 'eodhd', - }); - - expect(res.isError).toBe(false); - expect(filteringFake.libraryCalls).toEqual([{ id: 'card-cpcv', tags: ['validation'] }]); - expect(filteringFake.findingsCalls).toEqual([{ id: 'card-cpcv' }]); - expect(filteringFake.caveatsCalls).toEqual([{ id: 'card-cpcv', provider: 'eodhd' }]); - expect(res.payload?.rowCount).toBe(3); - expect(res.payload?.sources).toEqual({ library: 1, findings: 1, provider_caveats: 1 }); - expect(res.payload?.rows.map(r => `${r.source}:${r.id}`)).toEqual([ - 'library:card-cpcv', - 'findings:card-cpcv', - 'provider_caveats:card-cpcv', - ]); - }); - - test('does not grant exact-ID priority to free-text query matches and stays invariant to query capitalization', async () => { - const fake = createFakeKnowledgePort({ - libraryCards: [ - makeLibraryCard({ - id: 'momentum', - title: 'Factor Crowding Notes', - tags: ['risk'], - summary: 'Discusses momentum drawdown regimes.', - }), - makeLibraryCard({ - id: 'z-card', - title: 'Momentum Basics', - tags: ['factor'], - summary: 'Introductory overview.', - }), - ], - findings: [ - makeFinding({ - id: 'momentum', - title: 'Regime Decay', - summary: 'Observed momentum turnover costs.', - }), - makeFinding({ - id: 'z-finding', - title: 'Momentum Persistence', - summary: 'Observed over 2015–2024.', - }), - ], - providerCaveats: [ - makeCaveat({ - id: 'momentum', - provider: 'eodhd', - dataset: 'eodPrices', - caveat: 'Affects momentum backtests.', - }), - makeCaveat({ - id: 'z-caveat', - provider: 'eodhd', - dataset: 'momentum_signals', - caveat: 'Adjusted series.', - }), - ], - }); - - for (const source of ['library', 'findings', 'provider_caveats'] as const) { - const lowerTop = await callReadKnowledge(fake, { source, query: 'momentum', limit: 1 }); - const upperTop = await callReadKnowledge(fake, { source, query: 'MOMENTUM', limit: 1 }); - - expect(lowerTop.isError).toBe(false); - expect(upperTop.isError).toBe(false); - expect(lowerTop.payload).toEqual(upperTop.payload); - - const expectedId = - source === 'library' ? 'z-card' : source === 'findings' ? 'z-finding' : 'z-caveat'; - expect(lowerTop.payload?.rows.map(r => r.id)).toEqual([expectedId]); - } - }); - - test('filters case-insensitively across titles, tags, summaries, caveats, and source-specific filters', async () => { - const fake = createFakeKnowledgePort({ - libraryCards: [ - makeLibraryCard({ - id: 'lib-tag', - title: 'Factor Neutrality', - tags: ['Momentum', 'Neutrality'], - summary: 'Dollar neutral weighting.', - }), - makeLibraryCard({ - id: 'lib-summary', - title: 'Execution Slippage', - tags: ['Microstructure'], - summary: 'Models MOMENTUM crowding impact.', - }), - makeLibraryCard({ - id: 'lib-only-one-tag', - title: 'Momentum Basics', - tags: ['Momentum'], - summary: 'Single tag card.', - }), - ], - findings: [ - makeFinding({ - id: 'fin-match', - title: 'Cross-sectional Momentum', - summary: 'Observed decay in 2024.', - }), - makeFinding({ - id: 'fin-other', - title: 'Value Spread', - summary: 'Unrelated finding.', - }), - ], - providerCaveats: [ - makeCaveat({ - id: 'cav-eodhd', - provider: 'EODHD', - dataset: 'eodPrices', - caveat: 'Momentum backtests need un-adjusted closes.', - }), - makeCaveat({ - id: 'cav-polygon', - provider: 'Polygon', - dataset: 'intraday1m', - caveat: 'Momentum bars omit odd lots.', - }), - ], - }); - - // With source: 'all', tags filters only library (all-tag match) and provider filters only caveats - const combinedRes = await callReadKnowledge(fake, { - query: ' momentum ', - tags: [' MOMENTUM ', 'neutrality'], - provider: ' eodhd ', - }); - expect(combinedRes.isError).toBe(false); - expect(combinedRes.payload?.rows.map(r => `${r.source}:${r.id}`)).toEqual([ - 'findings:fin-match', - 'provider_caveats:cav-eodhd', - 'library:lib-tag', - ]); - expect(combinedRes.payload?.sources).toEqual({ - library: 1, - findings: 1, - provider_caveats: 1, - }); - - // Empty result when query matches nothing - const emptyRes = await callReadKnowledge(fake, { query: 'zzz-no-match' }); - expect(emptyRes.isError).toBe(false); - expect(emptyRes.payload).toEqual({ - rowCount: 0, - sources: { library: 0, findings: 0, provider_caveats: 0 }, - rows: [], - }); - }); - - test('ranks deterministically across shuffled fixtures: exact id > title/dataset > other > ascending id > source order', async () => { - const libraryCards: LibraryCardRecord[] = [ - makeLibraryCard({ - id: 'tie-id', - title: 'Alpha title match', - tags: ['misc'], - summary: 'summary', - }), - makeLibraryCard({ - id: 'a-other', - title: 'Unrelated', - tags: ['alpha'], - summary: 'summary', - }), - makeLibraryCard({ - id: 'B-other', - title: 'Unrelated', - tags: ['misc'], - summary: 'Contains alpha in summary', - }), - ]; - const findings: FindingRecord[] = [ - makeFinding({ - id: 'tie-id', - title: 'Alpha finding title', - summary: 'summary', - }), - makeFinding({ - id: 'z-summary', - title: 'Unrelated finding', - summary: 'Mentions alpha here', - }), - ]; - const providerCaveats: ProviderCaveatRecord[] = [ - makeCaveat({ - id: 'tie-id', - provider: 'eodhd', - dataset: 'alpha_dataset', - caveat: 'caveat text', - }), - makeCaveat({ - id: 'c-provider', - provider: 'alpha-feed', - dataset: 'bars', - caveat: 'ordinary text', - }), - makeCaveat({ - id: 'd-caveat', - provider: 'other', - dataset: 'bars', - caveat: 'mentions alpha inside caveat', - }), - ]; - - const resA = await callReadKnowledge( - createFakeKnowledgePort({ libraryCards, findings, providerCaveats }), - { query: 'alpha' } - ); - const resB = await callReadKnowledge( - createFakeKnowledgePort({ - libraryCards: [...libraryCards].reverse(), - findings: [...findings].reverse(), - providerCaveats: [...providerCaveats].reverse(), - }), - { query: 'alpha' } - ); - - expect(resA.isError).toBe(false); - expect(resB.isError).toBe(false); - expect(resA.payload).toEqual(resB.payload); - - // Title/dataset matches first (all have id 'tie-id', broken by library -> findings -> provider_caveats), - // then other text matches ordered by ASCII/code-unit id ('B-other' < 'a-other' < 'c-provider' < 'd-caveat' < 'z-summary'). - expect(resA.payload?.rows.map(r => `${r.source}:${r.id}`)).toEqual([ - 'library:tie-id', - 'findings:tie-id', - 'provider_caveats:tie-id', - 'library:B-other', - 'library:a-other', - 'provider_caveats:c-provider', - 'provider_caveats:d-caveat', - 'findings:z-summary', - ]); - }); - - test('enforces default limit 20, hard max 100, late best match, and post-limit source counts', async () => { - // 25 eligible records (22 library + 3 findings) with default limit 20: - // Findings have title matches so they rank ahead of library summary matches, pushing 5 library rows out. - const lib22: LibraryCardRecord[] = []; - for (let i = 1; i <= 22; i += 1) { - lib22.push( - makeLibraryCard({ - id: `lib-${String(i).padStart(2, '0')}`, - title: 'Generic Card', - summary: 'Contains needle in summary', - }) - ); - } - const fin3: FindingRecord[] = [ - makeFinding({ id: 'fin-01', title: 'Needle Title 1', summary: 's' }), - makeFinding({ id: 'fin-02', title: 'Needle Title 2', summary: 's' }), - makeFinding({ id: 'fin-03', title: 'Needle Title 3', summary: 's' }), - ]; - - const defaultRes = await callReadKnowledge( - createFakeKnowledgePort({ libraryCards: lib22, findings: fin3 }), - { query: 'needle' } - ); - expect(defaultRes.isError).toBe(false); - expect(defaultRes.payload?.rowCount).toBe(20); - expect(defaultRes.payload?.rows).toHaveLength(20); - expect(defaultRes.payload?.sources).toEqual({ - library: 17, - findings: 3, - provider_caveats: 0, - }); - - // Hard max 100 with 115 eligible records and the best match placed last in the fixture - const lib115: LibraryCardRecord[] = []; - for (let i = 1; i <= 114; i += 1) { - lib115.push( - makeLibraryCard({ - id: `rec-${String(i).padStart(3, '0')}`, - title: 'Other', - summary: 'Contains signal in summary', - }) - ); - } - lib115.push( - makeLibraryCard({ - id: 'zzz-best-late', - title: 'Signal Title Match Placed Last', - summary: 'summary', - }) - ); - - const maxRes = await callReadKnowledge(createFakeKnowledgePort({ libraryCards: lib115 }), { - source: 'library', - query: 'signal', - limit: READ_KNOWLEDGE_MAX_LIMIT, - }); - expect(maxRes.isError).toBe(false); - expect(maxRes.payload?.rowCount).toBe(100); - expect(maxRes.payload?.rows).toHaveLength(100); - expect(maxRes.payload?.rows[0]?.id).toBe('zzz-best-late'); - expect(maxRes.payload?.sources).toEqual({ - library: 100, - findings: 0, - provider_caveats: 0, - }); - }); - - test('truncates body, summary, and caveat independently at 4096 chars after matching', async () => { - const exactCap = 'x'.repeat(READ_KNOWLEDGE_MAX_TEXT_LENGTH); - const overCapWithTailNeedle = `${'y'.repeat(READ_KNOWLEDGE_MAX_TEXT_LENGTH)}NEEDLE`; - const overCapOne = 'z'.repeat(READ_KNOWLEDGE_MAX_TEXT_LENGTH + 1); - - const fake = createFakeKnowledgePort({ - libraryCards: [ - makeLibraryCard({ - id: 'lib-exact', - title: 'Exact Cap Card', - summary: exactCap, - body: exactCap, - }), - makeLibraryCard({ - id: 'lib-over-body', - title: 'Over Cap Body', - summary: 'short summary', - body: overCapOne, - }), - makeLibraryCard({ - id: 'lib-over-summary-needle', - title: 'Late Match Summary', - summary: overCapWithTailNeedle, - body: 'short body', - }), - ], - findings: [ - makeFinding({ - id: 'fin-exact', - title: 'Exact Finding', - summary: exactCap, - }), - makeFinding({ - id: 'fin-over-needle', - title: 'Late Match Finding', - summary: overCapWithTailNeedle, - }), - ], - providerCaveats: [ - makeCaveat({ - id: 'cav-exact', - dataset: 'exact_ds', - caveat: exactCap, - }), - makeCaveat({ - id: 'cav-over-needle', - dataset: 'over_ds', - caveat: overCapWithTailNeedle, - }), - ], - }); - - // Exact cap rows are not truncated - for (const id of ['lib-exact', 'fin-exact', 'cav-exact']) { - const res = await callReadKnowledge(fake, { id }); - expect(res.isError).toBe(false); - expect(res.payload?.rows).toHaveLength(1); - const row = res.payload?.rows[0]; - expect(row?.truncated).toBe(false); - if (row?.source === 'library') { - expect(row.summary).toHaveLength(READ_KNOWLEDGE_MAX_TEXT_LENGTH); - expect(row.body).toHaveLength(READ_KNOWLEDGE_MAX_TEXT_LENGTH); - } else if (row?.source === 'findings') { - expect(row.summary).toHaveLength(READ_KNOWLEDGE_MAX_TEXT_LENGTH); - } else if (row?.source === 'provider_caveats') { - expect(row.caveat).toHaveLength(READ_KNOWLEDGE_MAX_TEXT_LENGTH); - } - } - - // Library body 1 char over cap is truncated independently while short summary is untouched - const overBodyRes = await callReadKnowledge(fake, { id: 'lib-over-body' }); - expect(overBodyRes.isError).toBe(false); - const bodyRow = overBodyRes.payload?.rows[0]; - expect(bodyRow?.source).toBe('library'); - if (bodyRow?.source === 'library') { - expect(bodyRow.truncated).toBe(true); - expect(bodyRow.summary).toBe('short summary'); - expect(bodyRow.body).toHaveLength(READ_KNOWLEDGE_MAX_TEXT_LENGTH); - } - - // Query matching text beyond char 4096 still matches, then caps output to 4096 with truncated: true - const needleRes = await callReadKnowledge(fake, { query: 'needle' }); - expect(needleRes.isError).toBe(false); - expect(needleRes.payload?.rows.map(r => `${r.source}:${r.id}`)).toEqual([ - 'provider_caveats:cav-over-needle', - 'findings:fin-over-needle', - 'library:lib-over-summary-needle', - ]); - for (const row of needleRes.payload?.rows ?? []) { - expect(row.truncated).toBe(true); - if (row.source === 'library') { - expect(row.summary).toHaveLength(READ_KNOWLEDGE_MAX_TEXT_LENGTH); - expect(row.body).toBe('short body'); - } else if (row.source === 'findings') { - expect(row.summary).toHaveLength(READ_KNOWLEDGE_MAX_TEXT_LENGTH); - } else { - expect(row.caveat).toHaveLength(READ_KNOWLEDGE_MAX_TEXT_LENGTH); - } - } - }); - - test('rejects strict input violations before invoking any port method', async () => { - const invalidInputs: Record[] = [ - { scope: 'vault_evaluation_only' }, - { vault_evaluation_only: true }, - { vaultCutoffTs: VAULT_CUTOFF_TS }, - { unexpectedKey: 'nope' }, - { query: 'A'.repeat(READ_KNOWLEDGE_MAX_QUERY_LENGTH + 1) }, - { query: '' }, - { query: ' \t\n ' }, - { id: '' }, - { id: ' ' }, - { provider: '' }, - { provider: ' ' }, - { tags: [] }, - { tags: ['valid', ' '] }, - { source: 'vault' }, - { source: 'LIBRARY' }, - { limit: 0 }, - { limit: -5 }, - { limit: READ_KNOWLEDGE_MAX_LIMIT + 1 }, - { limit: 1.5 }, - { limit: '10' }, - ]; - - for (const args of invalidInputs) { - expect(readKnowledgeInputSchema.safeParse(args).success).toBe(false); - const fake = createFakeKnowledgePort({ - libraryCards: [makeLibraryCard({ id: 'c1' })], - }); - const res = await callReadKnowledge(fake, args); - expect(res.isError).toBe(true); - expect(res.text).toContain('Invalid arguments for tool "read_knowledge"'); - expect(fake.invokedMethods).toHaveLength(0); - } - }); - - test('returns sanitized isError without leaking connection strings or stack traces when port rejects', async () => { - const secretError = new Error( - 'postgres://admin:super-secret@10.0.0.51:5432/trading_bot connection refused' - ); - secretError.stack = - 'Error: postgres://admin:super-secret@10.0.0.51:5432/trading_bot\n at internalQuery (/srv/secret/db.ts:42:9)'; - - // Single source failure - const singleFake = createFakeKnowledgePort({ libraryError: secretError }); - const singleRes = await callReadKnowledge(singleFake, { source: 'library', query: 'alpha' }); - expect(singleRes.isError).toBe(true); - expect(singleRes.text).toBe('Error: Tool execution failed.'); - expect(singleRes.text).not.toContain('super-secret'); - expect(singleRes.text).not.toContain('10.0.0.51'); - expect(singleRes.text).not.toContain('trading_bot'); - expect(singleRes.text).not.toContain('/srv/secret/db.ts'); - - // Partial failure under source: 'all' when other selected sources succeed - const partialFake = createFakeKnowledgePort({ - libraryCards: [makeLibraryCard({ id: 'ok-1', title: 'Alpha' })], - findingsError: secretError, - providerCaveats: [makeCaveat({ id: 'ok-2', dataset: 'Alpha' })], - }); - const partialRes = await callReadKnowledge(partialFake, { source: 'all', query: 'alpha' }); - expect(partialRes.isError).toBe(true); - expect(partialRes.text).toBe('Error: Tool execution failed.'); - expect(partialRes.text).not.toContain('super-secret'); - expect(partialRes.text).not.toContain('10.0.0.51'); - expect(partialRes.text).not.toContain('db.ts'); - }); - - test('factory throws on missing or invalid port options', () => { - expect(() => - createReadKnowledgeTool(null as unknown as Parameters[0]) - ).toThrow(); - - expect(() => - createReadKnowledgeTool({ port: null as unknown as KnowledgePort }) - ).toThrow(); - - expect(() => - createReadKnowledgeTool({ port: {} as unknown as KnowledgePort }) - ).toThrow(); - }); -}); diff --git a/libs/research/test/mcp-search-symbols-qa.test.ts b/libs/research/test/mcp-search-symbols-qa.test.ts deleted file mode 100644 index 44d15be2..00000000 --- a/libs/research/test/mcp-search-symbols-qa.test.ts +++ /dev/null @@ -1,354 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { - createMcpServer, - createSearchSymbolsTool, - SEARCH_SYMBOLS_MAX_QUERY_LENGTH, - type SearchSymbolsResultPayload, - type SymbolSearchPort, - type SymbolSearchQuery, - type SymbolSearchRow, -} from '../src/mcp/index'; - -// QA fixture: deterministic in-memory security-master port (no network, no -// Postgres, no MongoDB). Cutoffs are pinned epoch-ms values; no wall clock. -const MIDDAY_CUTOFF_TS = Date.UTC(2025, 2, 31, 15, 30, 0, 0); // 2025-03-31T15:30Z -const LAST_MS_CUTOFF_TS = Date.UTC(2025, 2, 31, 23, 59, 59, 999); // 2025-03-31T23:59:59.999Z -const CUTOFF_DATE = '2025-03-31'; - -function row( - overrides: Partial & { readonly listingId: number } -): SymbolSearchRow { - return { - instrumentId: overrides.listingId * 10, - ticker: `T${overrides.listingId}`, - classSuffix: null, - name: `Company ${overrides.listingId}`, - mic: 'XNAS', - currency: 'USD', - isin: null, - firstBarDate: '2020-01-02', - lastBarDate: '2025-03-28', - delistedAt: null, - ...overrides, - }; -} - -function fakePort(impl: (q: SymbolSearchQuery) => Promise | unknown): { - readonly calls: SymbolSearchQuery[]; - readonly port: SymbolSearchPort; -} { - const calls: SymbolSearchQuery[] = []; - return { - calls, - port: { - async searchSymbols(q) { - calls.push({ ...q }); - return (await impl(q)) as readonly SymbolSearchRow[]; - }, - }, - }; -} - -async function call( - port: SymbolSearchPort, - args: Record, - vaultCutoffTs: number -): Promise<{ isError: boolean; text: string; payload: SearchSymbolsResultPayload | null }> { - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [createSearchSymbolsTool({ port, vaultContext: { vaultCutoffTs } })], - }); - const raw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 7, - method: 'tools/call', - params: { name: 'search_symbols', arguments: args }, - }) - ); - const parsed = JSON.parse(raw as string) as { - result: { isError?: boolean; content: { text: string }[] }; - }; - const isError = parsed.result.isError === true; - const text = parsed.result.content[0]?.text ?? ''; - return { - isError, - text, - payload: isError ? null : (JSON.parse(text) as SearchSymbolsResultPayload), - }; -} - -describe('MCP search_symbols QA', () => { - test('intraday cutoff fences against the cutoff UTC calendar date (equal kept, next day dropped/clamped/masked)', async () => { - const rows = [ - row({ - listingId: 1, - ticker: 'QQ', - firstBarDate: CUTOFF_DATE, - lastBarDate: '2025-04-01', - delistedAt: '2025-04-01', - }), - row({ listingId: 2, ticker: 'QQ', firstBarDate: '2025-04-01', lastBarDate: '2025-04-02' }), - row({ listingId: 3, ticker: 'QQ', lastBarDate: CUTOFF_DATE, delistedAt: CUTOFF_DATE }), - ]; - for (const cutoff of [MIDDAY_CUTOFF_TS, LAST_MS_CUTOFF_TS]) { - const { port } = fakePort(() => rows); - const res = await call(port, { query: 'QQ' }, cutoff); - expect(res.isError).toBe(false); - expect(res.payload?.vaultCutoffTs).toBe(cutoff); - expect( - res.payload?.rows.map(r => [r.listingId, r.firstBarDate, r.lastBarDate, r.delistedAt]) - ).toEqual([ - [1, CUTOFF_DATE, CUTOFF_DATE, null], - [3, '2020-01-02', CUTOFF_DATE, CUTOFF_DATE], - ]); - } - }); - - test('cutoff one ms before midnight UTC uses the previous calendar date', async () => { - const cutoff = Date.UTC(2025, 2, 31, 0, 0, 0, 0) - 1; // 2025-03-30T23:59:59.999Z - const { port } = fakePort(() => [ - row({ listingId: 1, ticker: 'EDGE', firstBarDate: CUTOFF_DATE }), - row({ listingId: 2, ticker: 'EDGE', lastBarDate: CUTOFF_DATE, delistedAt: CUTOFF_DATE }), - ]); - const res = await call(port, { query: 'EDGE' }, cutoff); - expect(res.payload?.rows).toHaveLength(1); - expect(res.payload?.rows[0]).toMatchObject({ - listingId: 2, - lastBarDate: '2025-03-30', - delistedAt: null, - }); - }); - - test('a future delisting changes neither membership nor ranking relative to a never-delisted listing', async () => { - const base = [ - row({ listingId: 9, ticker: 'MSFT', name: 'Microsoft Corp' }), - row({ listingId: 4, ticker: 'MSFTX', name: 'Microsoft Tracker' }), - row({ listingId: 7, ticker: 'ZZZ', name: 'Old msft Holdings' }), - ]; - const withFutureDelisting = base.map(r => - r.listingId === 4 ? { ...r, delistedAt: '2026-01-15', lastBarDate: '2026-01-14' } : r - ); - for (const includeDelisted of [true, false]) { - const a = await call( - fakePort(() => base).port, - { query: 'msft', includeDelisted }, - MIDDAY_CUTOFF_TS - ); - const b = await call( - fakePort(() => withFutureDelisting).port, - { query: 'msft', includeDelisted }, - MIDDAY_CUTOFF_TS - ); - expect(a.payload?.rows.map(r => r.listingId)).toEqual([9, 4, 7]); - expect(b.payload?.rows.map(r => r.listingId)).toEqual([9, 4, 7]); - expect(b.payload?.rows[1]).toMatchObject({ delistedAt: null, lastBarDate: CUTOFF_DATE }); - } - }); - - test('truncation with includeDelisted: true ignores post-cutoff rows placed ahead of eligible matches', async () => { - const rows = [ - row({ listingId: 1, ticker: 'NEW', firstBarDate: '2025-06-01' }), - row({ listingId: 2, ticker: 'NEW', firstBarDate: '2025-04-01' }), - row({ listingId: 3, ticker: 'NEWA' }), - row({ listingId: 4, ticker: 'NEWB', delistedAt: '2021-05-05', lastBarDate: '2021-05-04' }), - ]; - const fit = await call(fakePort(() => rows).port, { query: 'new', limit: 2 }, MIDDAY_CUTOFF_TS); - expect(fit.payload).toMatchObject({ rowCount: 2, truncated: false }); - expect(fit.payload?.rows.map(r => r.listingId)).toEqual([3, 4]); - - const over = await call( - fakePort(() => rows).port, - { query: 'new', limit: 1 }, - MIDDAY_CUTOFF_TS - ); - expect(over.payload).toMatchObject({ rowCount: 1, truncated: true }); - expect(over.payload?.rows.map(r => r.listingId)).toEqual([3]); - }); - - test('a row matching both ticker prefix and name ranks by its best (ticker) match; name match is literal substring', async () => { - const rows = [ - row({ listingId: 1, ticker: 'ZED', name: 'A.B Industries' }), - row({ listingId: 2, ticker: 'A.BX', name: 'A.B Prefix Co' }), - row({ listingId: 3, ticker: 'AXB', name: 'Regex Bait AXB' }), - row({ listingId: 4, ticker: 'A.B', name: 'Exact Dot' }), - ]; - const res = await call(fakePort(() => rows).port, { query: 'a.b' }, MIDDAY_CUTOFF_TS); - // "a.b" must not behave like a regex: AXB (3) is not a match. - expect(res.payload?.rows.map(r => r.listingId)).toEqual([4, 2, 1]); - }); - - test('repeated calls on shuffled inputs give byte-identical payloads', async () => { - const rows = Array.from({ length: 30 }, (_, i) => - row({ listingId: 1000 - i * 7, ticker: i % 3 === 0 ? 'RY' : `RY${i}`, name: `Royal ${i}` }) - ); - // Deterministic Fisher-Yates with a fixed LCG seed. - let seed = 12345; - const shuffled = [...rows]; - for (let i = shuffled.length - 1; i > 0; i -= 1) { - seed = (seed * 1103515245 + 12345) % 2147483648; - const j = seed % (i + 1); - [shuffled[i], shuffled[j]] = [shuffled[j] as SymbolSearchRow, shuffled[i] as SymbolSearchRow]; - } - const a = await call(fakePort(() => rows).port, { query: 'RY', limit: 12 }, MIDDAY_CUTOFF_TS); - const b = await call( - fakePort(() => shuffled).port, - { query: 'RY', limit: 12 }, - MIDDAY_CUTOFF_TS - ); - expect(a.text).toBe(b.text); - const ids = a.payload?.rows.map(r => r.listingId) ?? []; - const exact = ids.slice(0, 10); - expect([...exact].sort((x, y) => x - y)).toEqual(exact); // 10 exact RY matches ascending - expect(a.payload?.truncated).toBe(true); - }); - - test('query of exactly 64 chars (and 64 chars after trimming) is accepted; whitespace is trimmed before the length check', async () => { - const q = 'B'.repeat(SEARCH_SYMBOLS_MAX_QUERY_LENGTH); - const fake = fakePort(() => []); - const exact = await call(fake.port, { query: q }, MIDDAY_CUTOFF_TS); - const padded = await call(fake.port, { query: ` ${q} ` }, MIDDAY_CUTOFF_TS); - expect(exact.isError).toBe(false); - expect(padded.isError).toBe(false); - expect(fake.calls.map(c => c.query)).toEqual([q, q]); - }); - - test('limit 1 and 100 accepted and forwarded as hints; non-number limit, null and non-boolean includeDelisted rejected without port call', async () => { - const fake = fakePort(() => []); - expect((await call(fake.port, { query: 'X', limit: 1 }, MIDDAY_CUTOFF_TS)).isError).toBe(false); - expect( - (await call(fake.port, { query: 'X', limit: 100, country: 'US' }, MIDDAY_CUTOFF_TS)).isError - ).toBe(false); - expect(fake.calls).toEqual([ - { query: 'X', limit: 1, includeDelisted: true, vaultCutoffTs: MIDDAY_CUTOFF_TS }, - { - query: 'X', - limit: 100, - country: 'US', - includeDelisted: true, - vaultCutoffTs: MIDDAY_CUTOFF_TS, - }, - ]); - - const bad = fakePort(() => []); - for (const args of [ - { query: 'X', limit: '20' }, - { query: 'X', limit: null }, - { query: 'X', limit: Number.NaN }, - { query: 42 }, - { query: 'X', country: null }, - { query: 'X', includeDelisted: 0 }, - { query: 'X', vaultCutoffTs: Date.UTC(2030, 0, 1) }, - ]) { - const res = await call(bad.port, args, MIDDAY_CUTOFF_TS); - expect(res.isError).toBe(true); - } - expect(bad.calls).toHaveLength(0); - }); - - test('malformed port responses yield a sanitized isError result', async () => { - const malformed: unknown[] = [ - null, - { rows: [] }, - 'not-an-array', - [null], - ['row'], - [{ ...row({ listingId: 1, ticker: 'M' }), listingId: '1' }], - [{ ...row({ listingId: 1, ticker: 'M' }), listingId: 1.5 }], - [{ ...row({ listingId: 1, ticker: 'M' }), instrumentId: undefined }], - [{ ...row({ listingId: 1, ticker: 'M' }), ticker: null }], - [{ ...row({ listingId: 1, ticker: 'M' }), name: undefined }], - [{ ...row({ listingId: 1, ticker: 'M' }), mic: 5 }], - [{ ...row({ listingId: 1, ticker: 'M' }), isin: 123 }], - [{ ...row({ listingId: 1, ticker: 'M' }), classSuffix: undefined }], - [{ ...row({ listingId: 1, ticker: 'M' }), firstBarDate: undefined }], - ]; - for (const response of malformed) { - const res = await call(fakePort(() => response).port, { query: 'M' }, MIDDAY_CUTOFF_TS); - expect(res.isError).toBe(true); - expect(res.text).toBe('Error: Tool execution failed.'); - } - }); - - test('non-Error port rejections are sanitized', async () => { - for (const thrown of ['password=hunter2', { secret: 'x' }, 42]) { - const res = await call( - fakePort(() => { - throw thrown; - }).port, - { query: 'AAPL' }, - MIDDAY_CUTOFF_TS - ); - expect(res.isError).toBe(true); - expect(res.text).toBe('Error: Tool execution failed.'); - expect(res.text).not.toContain('hunter2'); - } - }); - - test('returned rows are fresh projections: mutating port objects after the call does not alter output, and port input is not mutated', async () => { - const source = row({ listingId: 5, ticker: 'FRZ', lastBarDate: '2025-05-05' }); - const snapshot = JSON.stringify(source); - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createSearchSymbolsTool({ - port: { searchSymbols: async () => [source] }, - vaultContext: { vaultCutoffTs: MIDDAY_CUTOFF_TS }, - }), - ], - }); - const raw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 1, - method: 'tools/call', - params: { name: 'search_symbols', arguments: { query: 'FRZ' } }, - }) - ); - expect(JSON.stringify(source)).toBe(snapshot); // clamping did not write back to the port row - const payload = JSON.parse( - (JSON.parse(raw as string) as { result: { content: { text: string }[] } }).result.content[0] - ?.text ?? '' - ) as SearchSymbolsResultPayload; - expect(payload.rows[0]?.lastBarDate).toBe(CUTOFF_DATE); - }); - - test('concurrent calls are independent and each respects its own arguments', async () => { - const rows = [ - row({ listingId: 1, ticker: 'TD', mic: 'XTSE', currency: 'CAD' }), - row({ listingId: 2, ticker: 'TD', mic: 'XNYS' }), - row({ listingId: 3, ticker: 'TDX', delistedAt: '2022-02-02', lastBarDate: '2022-02-01' }), - ]; - const fake = fakePort(q => - q.country === undefined ? rows : rows.filter(r => (q.country === 'CA') === (r.mic === 'XTSE')) - ); - const [all, ca, active] = await Promise.all([ - call(fake.port, { query: 'TD' }, MIDDAY_CUTOFF_TS), - call(fake.port, { query: 'TD', country: 'CA' }, MIDDAY_CUTOFF_TS), - call(fake.port, { query: 'TD', includeDelisted: false, limit: 1 }, MIDDAY_CUTOFF_TS), - ]); - expect(all.payload?.rows.map(r => r.listingId)).toEqual([1, 2, 3]); - expect(ca.payload?.rows.map(r => r.listingId)).toEqual([1]); - expect(active.payload).toMatchObject({ rowCount: 1, truncated: true }); - expect(active.payload?.rows.map(r => r.listingId)).toEqual([1]); - }); - - test('pre-1970 cutoff fences correctly', async () => { - const cutoff = Date.UTC(1965, 5, 30, 12, 0, 0, 0); - const rows = [ - row({ - listingId: 1, - ticker: 'IBM', - firstBarDate: '1962-01-02', - lastBarDate: '2025-03-28', - delistedAt: null, - }), - row({ listingId: 2, ticker: 'IBM', firstBarDate: '1970-01-02' }), - ]; - const res = await call(fakePort(() => rows).port, { query: 'IBM' }, cutoff); - expect(res.payload?.rows).toHaveLength(1); - expect(res.payload?.rows[0]).toMatchObject({ listingId: 1, lastBarDate: '1965-06-30' }); - }); -}); diff --git a/libs/research/test/mcp-search-symbols.test.ts b/libs/research/test/mcp-search-symbols.test.ts deleted file mode 100644 index 1db83564..00000000 --- a/libs/research/test/mcp-search-symbols.test.ts +++ /dev/null @@ -1,711 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { - type MarketDataStore, - MarketDataStoreValidationError, -} from '../src/market-data-store'; -import { MarketDataStoreNotImplementedError } from '../src/market-data-store-duckdb'; -import { - SEARCH_SYMBOLS_DEFAULT_LIMIT, - SEARCH_SYMBOLS_MAX_LIMIT, - SEARCH_SYMBOLS_MAX_QUERY_LENGTH, - type SearchSymbolsResultPayload, - type SymbolSearchPort, - type SymbolSearchQuery, - type SymbolSearchRow, - createAnalyzeSignalTool, - createEventStudyTool, - createMcpServer, - createQueryDataTool, - createSearchSymbolsTool, -} from '../src/mcp/index'; -import type { TrialLedgerExecutor } from '../src/trial-ledger'; - -const VAULT_CUTOFF_TS = Date.UTC(2025, 2, 31, 0, 0, 0, 0); // 2025-03-31T00:00:00.000Z -const VAULT_CUTOFF_DATE = '2025-03-31'; - -interface FixtureRow extends SymbolSearchRow { - readonly country?: 'US' | 'CA'; -} - -function makeRow(overrides: Partial & { readonly listingId: number }): SymbolSearchRow { - return { - listingId: overrides.listingId, - instrumentId: overrides.instrumentId ?? overrides.listingId * 10, - ticker: overrides.ticker ?? `T${overrides.listingId}`, - classSuffix: overrides.classSuffix ?? null, - name: overrides.name ?? `Company ${overrides.listingId}`, - mic: overrides.mic ?? 'XNAS', - currency: overrides.currency ?? 'USD', - isin: overrides.isin ?? null, - firstBarDate: overrides.firstBarDate === undefined ? '2020-01-02' : overrides.firstBarDate, - lastBarDate: overrides.lastBarDate === undefined ? '2025-03-28' : overrides.lastBarDate, - delistedAt: overrides.delistedAt === undefined ? null : overrides.delistedAt, - }; -} - -interface FakePortState { - readonly calls: SymbolSearchQuery[]; - readonly port: SymbolSearchPort; -} - -function createFakePort(options?: { - readonly rows?: readonly FixtureRow[]; - readonly filterByCountry?: boolean; - readonly error?: unknown; - readonly rawReturn?: unknown; -}): FakePortState { - const calls: SymbolSearchQuery[] = []; - const rows = options?.rows ?? []; - - const port: SymbolSearchPort = { - async searchSymbols(q: SymbolSearchQuery): Promise { - calls.push({ ...q }); - if (options?.error !== undefined) { - throw options.error; - } - if (options?.rawReturn !== undefined) { - return options.rawReturn as readonly SymbolSearchRow[]; - } - if (options?.filterByCountry && q.country !== undefined) { - return rows.filter(row => row.country === q.country); - } - return [...rows]; - }, - }; - - return { calls, port }; -} - -function createMinimalStore(): MarketDataStore { - return { - bars() { - return { - async *[Symbol.asyncIterator]() { - // empty stream - }, - }; - }, - async universe() { - return []; - }, - crossSection() { - throw new MarketDataStoreNotImplementedError('crossSection'); - }, - fundamentalsAsOf() { - throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); - }, - events() { - throw new MarketDataStoreNotImplementedError('events'); - }, - shortsAsOf() { - throw new MarketDataStoreNotImplementedError('shortsAsOf'); - }, - macroAsOf() { - throw new MarketDataStoreNotImplementedError('macroAsOf'); - }, - fx() { - throw new MarketDataStoreNotImplementedError('fx'); - }, - }; -} - -function createMinimalLedger(): TrialLedgerExecutor { - return { - async query() { - return { rows: [] }; - }, - }; -} - -async function callSearchSymbols( - fake: FakePortState, - args: Record, - vaultCutoffTs = VAULT_CUTOFF_TS -): Promise<{ - readonly isError: boolean; - readonly text: string; - readonly payload: SearchSymbolsResultPayload | null; -}> { - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createSearchSymbolsTool({ - port: fake.port, - vaultContext: { vaultCutoffTs }, - }), - ], - }); - - const raw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 'ss-1', - method: 'tools/call', - params: { - name: 'search_symbols', - arguments: args, - }, - }) - ); - - expect(raw).not.toBeNull(); - const parsed = JSON.parse(raw as string) as { - result: { - isError?: boolean; - content: { type: string; text: string }[]; - }; - }; - const isError = parsed.result.isError === true; - const text = parsed.result.content[0]?.text ?? ''; - - return { - isError, - text, - payload: isError ? null : (JSON.parse(text) as SearchSymbolsResultPayload), - }; -} - -describe('MCP search_symbols tool', () => { - test('registers alongside query_data, analyze_signal, and event_study and exposes strict schema via tools/list', async () => { - const store = createMinimalStore(); - const ledger = createMinimalLedger(); - const fake = createFakePort({ - rows: [ - makeRow({ - listingId: 42, - instrumentId: 420, - ticker: 'AAPL', - classSuffix: null, - name: 'Apple Inc.', - mic: 'XNAS', - currency: 'USD', - isin: 'US0378331005', - firstBarDate: '1980-12-12', - lastBarDate: '2025-03-28', - delistedAt: null, - }), - ], - }); - - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createQueryDataTool({ - store, - vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, - }), - createAnalyzeSignalTool({ - store, - ledger, - vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, - principalId: 'operator', - }), - createEventStudyTool({ - store, - ledger, - vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, - principalId: 'operator', - resolveExchangeCalendars: () => ({}), - }), - createSearchSymbolsTool({ - port: fake.port, - vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, - }), - ], - }); - - const listRaw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 1, - method: 'tools/list', - }) - ); - expect(listRaw).not.toBeNull(); - - const listParsed = JSON.parse(listRaw as string) as { - result: { - tools: { - name: string; - description: string; - inputSchema: { - type: string; - properties: Record>; - required?: string[]; - additionalProperties: boolean; - }; - }[]; - }; - }; - - expect(listParsed.result.tools.map(t => t.name)).toEqual([ - 'query_data', - 'analyze_signal', - 'event_study', - 'search_symbols', - ]); - - const searchTool = listParsed.result.tools.find(t => t.name === 'search_symbols'); - expect(searchTool).toBeDefined(); - expect(searchTool?.inputSchema.type).toBe('object'); - expect(searchTool?.inputSchema.additionalProperties).toBe(false); - expect(searchTool?.inputSchema.required).toEqual(['query']); - expect(searchTool?.inputSchema.properties.query).toMatchObject({ - type: 'string', - minLength: 1, - maxLength: SEARCH_SYMBOLS_MAX_QUERY_LENGTH, - }); - expect(searchTool?.inputSchema.properties.limit).toMatchObject({ - type: 'integer', - minimum: 1, - maximum: SEARCH_SYMBOLS_MAX_LIMIT, - default: SEARCH_SYMBOLS_DEFAULT_LIMIT, - }); - expect(searchTool?.inputSchema.properties.country).toMatchObject({ - type: 'string', - enum: ['US', 'CA'], - }); - expect(searchTool?.inputSchema.properties.includeDelisted).toMatchObject({ - type: 'boolean', - default: true, - }); - expect(searchTool?.inputSchema.properties.scope).toBeUndefined(); - expect(searchTool?.inputSchema.properties.vault_evaluation_only).toBeUndefined(); - expect(searchTool?.inputSchema.properties.vaultCutoffTs).toBeUndefined(); - - // Exercise JSON-RPC tools/call end-to-end on the multi-tool server. - const callRaw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 2, - method: 'tools/call', - params: { - name: 'search_symbols', - arguments: { query: 'AAPL' }, - }, - }) - ); - expect(callRaw).not.toBeNull(); - const callParsed = JSON.parse(callRaw as string) as { - result: { isError?: boolean; content: { type: string; text: string }[] }; - }; - expect(callParsed.result.isError).toBeUndefined(); - const payload = JSON.parse(callParsed.result.content[0]?.text ?? '') as SearchSymbolsResultPayload; - expect(payload).toEqual({ - scope: 'vault_fenced', - vaultCutoffTs: VAULT_CUTOFF_TS, - rowCount: 1, - truncated: false, - rows: [ - { - listingId: 42, - instrumentId: 420, - ticker: 'AAPL', - classSuffix: null, - name: 'Apple Inc.', - mic: 'XNAS', - currency: 'USD', - isin: 'US0378331005', - firstBarDate: '1980-12-12', - lastBarDate: '2025-03-28', - delistedAt: null, - }, - ], - }); - }); - - test('ranks exact ticker > ticker prefix > company name case-insensitively with numeric listingId tie-break', async () => { - const fixture: SymbolSearchRow[] = [ - makeRow({ listingId: 100, ticker: 'XYZ', name: 'Apple Blossom Holdings' }), - makeRow({ listingId: 10, ticker: 'AAPL', name: 'Apple Inc. Secondary' }), - makeRow({ listingId: 25, ticker: 'AAPLE', name: 'Apple Energy Corp' }), - makeRow({ listingId: 2, ticker: 'aapl', name: 'Apple Inc.' }), - makeRow({ listingId: 5, ticker: 'AAPLX', name: 'Apple Extended ETF' }), - makeRow({ listingId: 15, ticker: 'ZZZ', name: 'aapl Partners LP' }), - makeRow({ listingId: 30, ticker: 'OTHER', name: 'Unrelated Name' }), - ]; - - const fakeA = createFakePort({ rows: fixture }); - const fakeB = createFakePort({ rows: [...fixture].reverse() }); - - const resA = await callSearchSymbols(fakeA, { query: ' AaPl ' }); - const resB = await callSearchSymbols(fakeB, { query: ' AaPl ' }); - - expect(resA.isError).toBe(false); - expect(resB.isError).toBe(false); - expect(resA.payload).toEqual(resB.payload); - - // Exact ticker (2, 10) -> prefix (5, 25) -> name substring (15); unrelated candidates (30, 100) are excluded - expect(resA.payload?.rows.map(r => r.listingId)).toEqual([2, 10, 5, 25, 15]); - expect(resA.payload?.rowCount).toBe(5); - expect(resA.payload?.truncated).toBe(false); - - // Unrelated candidates must not trigger truncation when all actual matches fit within limit. - const exactFitRes = await callSearchSymbols(createFakePort({ rows: fixture }), { - query: 'AAPL', - limit: 5, - }); - expect(exactFitRes.isError).toBe(false); - expect(exactFitRes.payload?.rows.map(r => r.listingId)).toEqual([2, 10, 5, 25, 15]); - expect(exactFitRes.payload?.rowCount).toBe(5); - expect(exactFitRes.payload?.truncated).toBe(false); - - // When none of the port's returned candidates match, return an empty, non-truncated payload. - const noMatchRes = await callSearchSymbols(createFakePort({ rows: fixture }), { - query: 'UNMATCHED', - limit: 2, - }); - expect(noMatchRes.isError).toBe(false); - expect(noMatchRes.payload).toEqual({ - scope: 'vault_fenced', - vaultCutoffTs: VAULT_CUTOFF_TS, - rowCount: 0, - truncated: false, - rows: [], - }); - - // Verify trimmed query, default limit, includeDelisted: true, and vaultCutoffTs were passed to port. - expect(fakeA.calls).toHaveLength(1); - expect(fakeA.calls[0]).toEqual({ - query: 'AaPl', - limit: SEARCH_SYMBOLS_DEFAULT_LIMIT, - includeDelisted: true, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - }); - - test('forwards country filter and returns empty payload when no listings match', async () => { - const fake = createFakePort({ - filterByCountry: true, - rows: [ - { ...makeRow({ listingId: 1, ticker: 'SHOP', mic: 'XNYS', currency: 'USD' }), country: 'US' }, - { ...makeRow({ listingId: 2, ticker: 'SHOP', mic: 'XTSE', currency: 'CAD' }), country: 'CA' }, - ], - }); - - const caRes = await callSearchSymbols(fake, { query: 'SHOP', country: 'CA' }); - expect(caRes.isError).toBe(false); - expect(caRes.payload?.rows.map(r => r.listingId)).toEqual([2]); - expect(fake.calls[0]?.country).toBe('CA'); - - const emptyFake = createFakePort({ rows: [] }); - const emptyRes = await callSearchSymbols(emptyFake, { query: 'NO_SUCH_SYMBOL', country: 'US' }); - expect(emptyRes.isError).toBe(false); - expect(emptyRes.payload).toEqual({ - scope: 'vault_fenced', - vaultCutoffTs: VAULT_CUTOFF_TS, - rowCount: 0, - truncated: false, - rows: [], - }); - expect(emptyFake.calls[0]?.country).toBe('US'); - }); - - test('enforces default limit 20, hard max 100, exact-fit, and over-returning port truncation', async () => { - // 25 eligible rows with default limit (20) -> truncated: true - const rows25: SymbolSearchRow[] = []; - for (let i = 1; i <= 25; i += 1) { - rows25.push(makeRow({ listingId: i, ticker: `SYM${i}`, name: `Symbol ${i}` })); - } - const defaultOver = await callSearchSymbols(createFakePort({ rows: rows25 }), { query: 'SYM' }); - expect(defaultOver.isError).toBe(false); - expect(defaultOver.payload?.rowCount).toBe(20); - expect(defaultOver.payload?.rows).toHaveLength(20); - expect(defaultOver.payload?.truncated).toBe(true); - - // Exact fit of 20 eligible rows -> truncated: false - const defaultExact = await callSearchSymbols(createFakePort({ rows: rows25.slice(0, 20) }), { - query: 'SYM', - }); - expect(defaultExact.isError).toBe(false); - expect(defaultExact.payload?.rowCount).toBe(20); - expect(defaultExact.payload?.truncated).toBe(false); - - // Hard max 100 accepted; port over-returns 115 rows with late exact match at end - const rows115: SymbolSearchRow[] = []; - for (let i = 1; i <= 114; i += 1) { - rows115.push(makeRow({ listingId: i + 10, ticker: `ABC${i}`, name: `ABC Corp ${i}` })); - } - rows115.push(makeRow({ listingId: 999, ticker: 'ABC', name: 'Exact Match Late In Array' })); - - const maxOver = await callSearchSymbols(createFakePort({ rows: rows115 }), { - query: 'ABC', - limit: 100, - }); - expect(maxOver.isError).toBe(false); - expect(maxOver.payload?.rowCount).toBe(100); - expect(maxOver.payload?.rows).toHaveLength(100); - expect(maxOver.payload?.truncated).toBe(true); - // Late exact ticker match must still rank #1 before slicing - expect(maxOver.payload?.rows[0]?.listingId).toBe(999); - - // Exact fit at max 100 -> truncated: false - const maxExact = await callSearchSymbols(createFakePort({ rows: rows115.slice(0, 100) }), { - query: 'ABC', - limit: 100, - }); - expect(maxExact.isError).toBe(false); - expect(maxExact.payload?.rowCount).toBe(100); - expect(maxExact.payload?.truncated).toBe(false); - }); - - test('rows removed by Vault fencing or includeDelisted: false do not count toward truncation', async () => { - const rows: SymbolSearchRow[] = [ - // Post-cutoff listings placed ahead of eligible matches - makeRow({ listingId: 1, ticker: 'ACME', firstBarDate: '2025-04-01' }), - makeRow({ listingId: 2, ticker: 'ACME2', firstBarDate: '2025-05-15' }), - // Historically delisted listings - makeRow({ listingId: 3, ticker: 'ACME3', delistedAt: '2024-06-30', lastBarDate: '2024-06-28' }), - makeRow({ listingId: 4, ticker: 'ACME4', delistedAt: '2025-03-31', lastBarDate: '2025-03-31' }), - // Active as of cutoff (one active forever, one delisted after cutoff) - makeRow({ listingId: 5, ticker: 'ACME5', delistedAt: null }), - makeRow({ listingId: 6, ticker: 'ACME6', delistedAt: '2025-04-15', lastBarDate: '2025-04-14' }), - ]; - - const res = await callSearchSymbols(createFakePort({ rows }), { - query: 'ACME', - limit: 2, - includeDelisted: false, - }); - - expect(res.isError).toBe(false); - expect(res.payload?.rows.map(r => r.listingId)).toEqual([5, 6]); - expect(res.payload?.rowCount).toBe(2); - expect(res.payload?.truncated).toBe(false); - }); - - test('enforces Vault fencing on firstBarDate, lastBarDate, delistedAt, UTC cutoff equality, and null dates', async () => { - const extraFieldRow = { - ...makeRow({ - listingId: 10, - ticker: 'VLT', - classSuffix: 'A', - isin: 'US0000000010', - firstBarDate: '2024-02-29', // valid leap-year date - lastBarDate: '2025-06-01', // after cutoff -> clamp to 2025-03-31 - delistedAt: '2025-05-01', // after cutoff -> mask to null - }), - internalSecretField: 'must-not-leak', - } as unknown as SymbolSearchRow; - - const rows: SymbolSearchRow[] = [ - extraFieldRow, - // firstBarDate strictly after cutoff -> dropped - makeRow({ - listingId: 11, - ticker: 'VLT', - firstBarDate: '2025-04-01', - lastBarDate: '2025-06-01', - delistedAt: null, - }), - // firstBarDate / lastBarDate / delistedAt equal to cutoff -> kept as-is - makeRow({ - listingId: 12, - ticker: 'VLT', - firstBarDate: VAULT_CUTOFF_DATE, - lastBarDate: VAULT_CUTOFF_DATE, - delistedAt: VAULT_CUTOFF_DATE, - }), - // Null dates preserved - makeRow({ - listingId: 13, - ticker: 'VLT', - firstBarDate: null, - lastBarDate: null, - delistedAt: null, - }), - // Historical delisting before cutoff -> preserved by default - makeRow({ - listingId: 14, - ticker: 'VLT', - firstBarDate: '2019-01-03', - lastBarDate: '2023-10-12', - delistedAt: '2023-10-15', - }), - ]; - - const fakeDefault = createFakePort({ rows }); - const resDefault = await callSearchSymbols(fakeDefault, { query: 'VLT' }); - expect(resDefault.isError).toBe(false); - expect(resDefault.payload?.rows).toEqual([ - { - listingId: 10, - instrumentId: 100, - ticker: 'VLT', - classSuffix: 'A', - name: 'Company 10', - mic: 'XNAS', - currency: 'USD', - isin: 'US0000000010', - firstBarDate: '2024-02-29', - lastBarDate: VAULT_CUTOFF_DATE, - delistedAt: null, - }, - { - listingId: 12, - instrumentId: 120, - ticker: 'VLT', - classSuffix: null, - name: 'Company 12', - mic: 'XNAS', - currency: 'USD', - isin: null, - firstBarDate: VAULT_CUTOFF_DATE, - lastBarDate: VAULT_CUTOFF_DATE, - delistedAt: VAULT_CUTOFF_DATE, - }, - { - listingId: 13, - instrumentId: 130, - ticker: 'VLT', - classSuffix: null, - name: 'Company 13', - mic: 'XNAS', - currency: 'USD', - isin: null, - firstBarDate: null, - lastBarDate: null, - delistedAt: null, - }, - { - listingId: 14, - instrumentId: 140, - ticker: 'VLT', - classSuffix: null, - name: 'Company 14', - mic: 'XNAS', - currency: 'USD', - isin: null, - firstBarDate: '2019-01-03', - lastBarDate: '2023-10-12', - delistedAt: '2023-10-15', - }, - ]); - // Extra port property must not be projected - expect('internalSecretField' in (resDefault.payload?.rows[0] ?? {})).toBe(false); - - // With includeDelisted: false, historical delistings (12, 14) are excluded, - // while future delisting (10) remains eligible with delistedAt: null. - const fakeNoDelisted = createFakePort({ rows }); - const resNoDelisted = await callSearchSymbols(fakeNoDelisted, { - query: 'VLT', - includeDelisted: false, - }); - expect(resNoDelisted.isError).toBe(false); - expect(resNoDelisted.payload?.rows.map(r => r.listingId)).toEqual([10, 13]); - expect(resNoDelisted.payload?.rows[0]?.delistedAt).toBeNull(); - // Port must still be called with includeDelisted: true - expect(fakeNoDelisted.calls[0]?.includeDelisted).toBe(true); - }); - - test('rejects invalid port date strings with sanitized isError result', async () => { - const invalidDateCases: Partial[] = [ - { firstBarDate: '2025-02-29' }, // non-leap year Feb 29 - { lastBarDate: '2025-04-31' }, // April has 30 days - { delistedAt: '2025-13-01' }, // invalid month - { firstBarDate: '2025-03-31T00:00:00Z' }, // timestamp instead of YYYY-MM-DD - { lastBarDate: 'not-a-date' }, - { delistedAt: '' }, - ]; - - for (const badFields of invalidDateCases) { - const fake = createFakePort({ - rows: [makeRow({ listingId: 1, ticker: 'BAD', ...badFields })], - }); - const res = await callSearchSymbols(fake, { query: 'BAD' }); - expect(res.isError).toBe(true); - expect(res.text).toBe('Error: Tool execution failed.'); - } - }); - - test('factory throws MarketDataStoreValidationError on missing or invalid port or vaultCutoffTs', () => { - const validPort = createFakePort().port; - - expect(() => - createSearchSymbolsTool(null as unknown as Parameters[0]) - ).toThrow(MarketDataStoreValidationError); - - expect(() => - createSearchSymbolsTool({ - port: null as unknown as SymbolSearchPort, - vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, - }) - ).toThrow(MarketDataStoreValidationError); - - expect(() => - createSearchSymbolsTool({ - port: {} as unknown as SymbolSearchPort, - vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, - }) - ).toThrow(MarketDataStoreValidationError); - - const invalidCutoffs: unknown[] = [ - undefined, - null, - '2025-03-31', - Number.NaN, - Number.POSITIVE_INFINITY, - Number.NEGATIVE_INFINITY, - 123.45, - 8_640_000_000_000_000, - ]; - - for (const badCutoff of invalidCutoffs) { - expect(() => - createSearchSymbolsTool({ - port: validPort, - vaultContext: { vaultCutoffTs: badCutoff as number }, - }) - ).toThrow(MarketDataStoreValidationError); - } - - expect(() => - createSearchSymbolsTool({ - port: validPort, - vaultContext: undefined as unknown as { vaultCutoffTs: number }, - }) - ).toThrow(MarketDataStoreValidationError); - }); - - test('returns structured isError without calling port on invalid arguments', async () => { - const invalidInputs: Record[] = [ - {}, - { query: '' }, - { query: ' \t\n ' }, - { query: 'A'.repeat(SEARCH_SYMBOLS_MAX_QUERY_LENGTH + 1) }, - { query: 'AAPL', limit: 0 }, - { query: 'AAPL', limit: -5 }, - { query: 'AAPL', limit: SEARCH_SYMBOLS_MAX_LIMIT + 1 }, - { query: 'AAPL', limit: 1.5 }, - { query: 'AAPL', country: 'UK' }, - { query: 'AAPL', country: 'us' }, - { query: 'AAPL', includeDelisted: 'true' }, - { query: 'AAPL', scope: 'vault_evaluation_only' }, - { query: 'AAPL', unknownField: 123 }, - ]; - - for (const args of invalidInputs) { - const fake = createFakePort({ rows: [makeRow({ listingId: 1, ticker: 'AAPL' })] }); - const res = await callSearchSymbols(fake, args); - expect(res.isError).toBe(true); - expect(res.text).toContain('Invalid arguments for tool "search_symbols"'); - expect(fake.calls).toHaveLength(0); - } - }); - - test('returns sanitized isError without leaking error message when port rejects', async () => { - const fake = createFakePort({ - error: new Error('postgres://admin:super-secret@10.0.0.51:5432/trading_bot failed'), - }); - - const res = await callSearchSymbols(fake, { query: 'AAPL' }); - expect(res.isError).toBe(true); - expect(res.text).toBe('Error: Tool execution failed.'); - expect(res.text).not.toContain('super-secret'); - expect(res.text).not.toContain('10.0.0.51'); - expect(res.text).not.toContain('trading_bot'); - expect(fake.calls).toHaveLength(1); - }); -}); diff --git a/libs/research/test/mcp-stdio-host-qa.test.ts b/libs/research/test/mcp-stdio-host-qa.test.ts deleted file mode 100644 index 5933b196..00000000 --- a/libs/research/test/mcp-stdio-host-qa.test.ts +++ /dev/null @@ -1,496 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import type { BarBatch, BarQuery, MarketDataStore, Table } from '../src/market-data-store'; -import { - EVENTS_COLUMNS, - MarketDataStoreNotImplementedError, -} from '../src/market-data-store-duckdb'; -import { - type PostgresResearchCopilotExecutor, - type ResearchCopilotStdioHostDeps, - ResearchCopilotHostConfigError, - type StdioInput, - type StdioOutput, - parseResearchCopilotHostConfig, - runResearchCopilotStdioHost, -} from '../src/mcp/index'; - -// QA fixtures: synthetic in-memory factories and stdio only. No Postgres, -// DuckDB, filesystem, or network. Protocol/wiring checks; no strategy claims. -const FAKE_DECODED_PASSWORD = 'qa+p@ss w0rd/=?'; -const FAKE_ENCODED_PASSWORD = encodeURIComponent(FAKE_DECODED_PASSWORD); -const FAKE_POSTGRES_URL = `postgresql://qa_ro:${FAKE_ENCODED_PASSWORD}@127.0.0.1:5433/trading_bot_dev`; -const CUTOFF_ISO = '2025-06-01T00:00:00Z'; -const CUTOFF_MS = Date.UTC(2025, 5, 1); -const FIXED_NOW_MS = Date.UTC(2025, 4, 15, 12); - -function buildEnv( - overrides: Readonly> = {} -): Record { - return { - RESEARCH_MCP_POSTGRES_URL: FAKE_POSTGRES_URL, - RESEARCH_MCP_CURATED_ROOT: '/qa/curated', - RESEARCH_MCP_VAULT_CUTOFF_TS: CUTOFF_ISO, - RESEARCH_MCP_PRINCIPAL_ID: 'operator', - RESEARCH_MCP_LIBRARY_ROOT: '/qa/library', - RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: JSON.stringify({ XNYS: [101, 102] }), - ...overrides, - }; -} - -function memoryOutput(): { readonly output: StdioOutput; readonly chunks: string[] } { - const chunks: string[] = []; - return { - chunks, - output: { - write(chunk: string): boolean { - chunks.push(chunk); - return true; - }, - }, - }; -} - -function trackingInput(messages: readonly unknown[]): { - readonly input: StdioInput; - readonly pulled: () => number; -} { - let count = 0; - return { - pulled: () => count, - input: { - async *[Symbol.asyncIterator]() { - for (const msg of messages) { - count += 1; - yield `${JSON.stringify(msg)}\n`; - } - }, - }, - }; -} - -function recordingStore(): { readonly store: MarketDataStore; readonly barQueries: BarQuery[] } { - const barQueries: BarQuery[] = []; - const emptyEvents: Table = { columns: [...EVENTS_COLUMNS], rows: [] }; - const store: MarketDataStore = { - async *bars(q: BarQuery): AsyncIterable { - barQueries.push(q); - yield { listingId: q.listingIds[0] ?? 0, timeframe: q.timeframe, rows: [] }; - }, - async events() { - return emptyEvents; - }, - async universe() { - return []; - }, - async crossSection() { - throw new MarketDataStoreNotImplementedError('crossSection'); - }, - async fundamentalsAsOf() { - throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); - }, - async shortsAsOf() { - throw new MarketDataStoreNotImplementedError('shortsAsOf'); - }, - async macroAsOf() { - throw new MarketDataStoreNotImplementedError('macroAsOf'); - }, - async fx() { - throw new MarketDataStoreNotImplementedError('fx'); - }, - }; - return { store, barQueries }; -} - -function calendarExecutor(): { - readonly executor: PostgresResearchCopilotExecutor; - readonly sql: string[]; -} { - const sql: string[] = []; - const executor: PostgresResearchCopilotExecutor = { - async query>( - text: string, - params?: readonly unknown[] - ): Promise<{ readonly rows: readonly Row[] }> { - sql.push(text); - if (text.includes('calendar_code AS calendar_code')) { - const ids = (params?.[0] as readonly number[] | undefined) ?? []; - return { - rows: ids.map(id => ({ listing_id: id, calendar_code: 'XNYS' }) as unknown as Row), - }; - } - return { rows: [] }; - }, - }; - return { executor, sql }; -} - -function baseDeps( - overrides: Partial = {} -): ResearchCopilotStdioHostDeps { - return { - config: parseResearchCopilotHostConfig(buildEnv()), - openExecutor: () => ({ executor: calendarExecutor().executor, close: () => {} }), - openStore: () => ({ store: recordingStore().store, close: () => {} }), - createLibraryCardReader: () => ({ listLibraryCards: async () => [] }), - newId: () => 'qa-id', - now: () => FIXED_NOW_MS, - stdio: { input: trackingInput([]).input, output: memoryOutput().output }, - ...overrides, - }; -} - -async function captureRejection(run: () => Promise): Promise { - try { - await run(); - } catch (err) { - return err; - } - throw new Error('expected rejection'); -} - -function expectNoSecret(error: unknown): void { - expect(error).toBeInstanceOf(Error); - const err = error as Error & { cause?: unknown }; - for (const text of [err.message, err.stack ?? '']) { - expect(text).not.toContain(FAKE_POSTGRES_URL); - expect(text).not.toContain(FAKE_ENCODED_PASSWORD); - expect(text).not.toContain(FAKE_DECODED_PASSWORD); - } - expect(err.cause).toBeUndefined(); -} - -describe('runResearchCopilotStdioHost QA: session-date wiring', () => { - test('event_study derives session dates from the configured reference listings on the opened store, clamped below the env cutoff', async () => { - const { store, barQueries } = recordingStore(); - const { executor } = calendarExecutor(); - const sink = memoryOutput(); - const { input } = trackingInput([ - { - jsonrpc: '2.0', - id: 1, - method: 'tools/call', - params: { - name: 'event_study', - arguments: { - listingIds: [555], - from: '2025-05-01', - to: '2025-06-20', - event: { kinds: ['filing'] }, - preDays: 2, - postDays: 3, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - benchmark: 'none', - }, - }, - }, - ]); - - await runResearchCopilotStdioHost( - baseDeps({ - openExecutor: () => ({ executor, close: () => {} }), - openStore: () => ({ store, close: () => {} }), - stdio: { input, output: sink.output }, - }) - ); - - expect(sink.chunks).toHaveLength(1); - const studyQuery = barQueries.find(q => q.listingIds.includes(555)); - expect(studyQuery?.scope).toBe('vault_fenced'); - - const sessionQueries = barQueries.filter(q => !q.listingIds.includes(555)); - expect(sessionQueries).toHaveLength(1); - const sessionQuery = sessionQueries[0]!; - expect([...sessionQuery.listingIds]).toEqual([101, 102]); - expect(sessionQuery.timeframe).toBe('1d'); - expect(sessionQuery.scope).not.toBe('vault_evaluation_only'); - expect(sessionQuery.to < '2025-06-01').toBe(true); - }); -}); - -describe('runResearchCopilotStdioHost QA: lifecycle edge cases', () => { - test('supports synchronous factories and synchronously throwing close(), closing in reverse order once each', async () => { - const events: string[] = []; - const err = await captureRejection(() => - runResearchCopilotStdioHost( - baseDeps({ - openExecutor: () => { - events.push('open:executor'); - return { - executor: calendarExecutor().executor, - close: () => { - events.push('close:executor'); - }, - }; - }, - openStore: () => { - events.push('open:store'); - return { - store: recordingStore().store, - close: () => { - events.push('close:store'); - throw new Error('sync store close failure'); - }, - }; - }, - }) - ) - ); - - expect((err as Error).message).toBe('sync store close failure'); - expect(events).toEqual(['open:executor', 'open:store', 'close:store', 'close:executor']); - }); - - test('synchronous throw from openStore is the rethrown original and the executor is still closed', async () => { - const storeError = new Error('sync store open failure'); - let execCloses = 0; - const sink = memoryOutput(); - const tracker = trackingInput([{ jsonrpc: '2.0', id: 1, method: 'ping' }]); - - const err = await captureRejection(() => - runResearchCopilotStdioHost( - baseDeps({ - openExecutor: () => ({ - executor: calendarExecutor().executor, - close: () => { - execCloses += 1; - }, - }), - openStore: () => { - throw storeError; - }, - stdio: { input: tracker.input, output: sink.output }, - }) - ) - ); - - expect(err).toBe(storeError); - expect(execCloses).toBe(1); - expect(sink.chunks).toEqual([]); - expect(tracker.pulled()).toBe(0); - }); - - test.each([ - ['null', null], - ['missing close()', { executor: {} }], - ] as const)('invalid executor handle (%s) fails closed with no store open and no stdio', async (_label, handle) => { - let storeOpened = false; - const sink = memoryOutput(); - const tracker = trackingInput([{ jsonrpc: '2.0', id: 1, method: 'ping' }]); - - const err = await captureRejection(() => - runResearchCopilotStdioHost( - baseDeps({ - openExecutor: () => handle as never, - openStore: () => { - storeOpened = true; - return { store: recordingStore().store, close: () => {} }; - }, - stdio: { input: tracker.input, output: sink.output }, - }) - ) - ); - - expect(err).toBeInstanceOf(Error); - expect(storeOpened).toBe(false); - expect(sink.chunks).toEqual([]); - expect(tracker.pulled()).toBe(0); - }); - - test('invalid store handle closes the executor and serves nothing', async () => { - let execCloses = 0; - const sink = memoryOutput(); - const tracker = trackingInput([{ jsonrpc: '2.0', id: 1, method: 'ping' }]); - - const err = await captureRejection(() => - runResearchCopilotStdioHost( - baseDeps({ - openExecutor: () => ({ - executor: calendarExecutor().executor, - close: () => { - execCloses += 1; - }, - }), - openStore: () => ({ store: recordingStore().store }) as never, - stdio: { input: tracker.input, output: sink.output }, - }) - ) - ); - - expect(err).toBeInstanceOf(Error); - expect(execCloses).toBe(1); - expect(sink.chunks).toEqual([]); - expect(tracker.pulled()).toBe(0); - }); - - test('library reader without listLibraryCards closes store then executor and serves nothing', async () => { - const closes: string[] = []; - const sink = memoryOutput(); - const tracker = trackingInput([{ jsonrpc: '2.0', id: 1, method: 'ping' }]); - - const err = await captureRejection(() => - runResearchCopilotStdioHost( - baseDeps({ - openExecutor: () => ({ - executor: calendarExecutor().executor, - close: () => { - closes.push('executor'); - }, - }), - openStore: () => ({ - store: recordingStore().store, - close: () => { - closes.push('store'); - }, - }), - createLibraryCardReader: () => ({}) as never, - stdio: { input: tracker.input, output: sink.output }, - }) - ) - ); - - expect(err).toBeInstanceOf(Error); - expect(closes).toEqual(['store', 'executor']); - expect(sink.chunks).toEqual([]); - expect(tracker.pulled()).toBe(0); - }); -}); - -describe('runResearchCopilotStdioHost QA: credential redaction', () => { - test('replaces a safe-message error whose cause chain carries the DSN', async () => { - const err = await captureRejection(() => - runResearchCopilotStdioHost( - baseDeps({ - openExecutor: () => { - throw new Error('connect failed', { - cause: new Error('inner', { cause: new Error(`dsn=${FAKE_POSTGRES_URL}`) }), - }); - }, - }) - ) - ); - expectNoSecret(err); - expect((err as Error).message).toContain('PostgreSQL executor'); - }); - - test('replaces an error carrying only the URL-encoded password', async () => { - const err = await captureRejection(() => - runResearchCopilotStdioHost( - baseDeps({ - createLibraryCardReader: () => { - throw new Error(`bad token ${FAKE_ENCODED_PASSWORD}`); - }, - }) - ) - ); - expectNoSecret(err); - expect((err as Error).message).toContain('library card reader'); - }); - - test('replaces an error whose message getter throws (uninspectable)', async () => { - const hostile = new Error('placeholder'); - Object.defineProperty(hostile, 'message', { - get() { - throw new Error(FAKE_DECODED_PASSWORD); - }, - }); - const err = await captureRejection(() => - runResearchCopilotStdioHost( - baseDeps({ - openStore: () => { - throw hostile; - }, - }) - ) - ); - expect(err).not.toBe(hostile); - expectNoSecret(err); - expect((err as Error).message).toContain('market data store'); - }); - - test('redacts a query-parameter password containing "+" in both decoded forms', async () => { - const config = parseResearchCopilotHostConfig( - buildEnv({ - RESEARCH_MCP_POSTGRES_URL: 'postgresql://qa_ro@127.0.0.1:5433/db?password=a+b%2Bc', - }) - ); - for (const leaked of ['a b+c', 'a+b+c', 'a+b%2Bc']) { - const err = await captureRejection(() => - runResearchCopilotStdioHost( - baseDeps({ - config, - openExecutor: () => { - throw new Error(`auth failed: ${leaked}`); - }, - }) - ) - ); - expect((err as Error).message).not.toContain(leaked); - } - }); -}); - -describe('parseResearchCopilotHostConfig QA: edge cases', () => { - test('keeps a "__proto__" calendar code as an own data property without prototype pollution', () => { - const config = parseResearchCopilotHostConfig( - buildEnv({ - RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: '{"__proto__":[7],"XNYS":[101]}', - }) - ); - - expect(Object.keys(config.referenceListingIds).sort()).toEqual(['XNYS', '__proto__']); - expect(Object.getOwnPropertyDescriptor(config.referenceListingIds, '__proto__')?.value).toEqual([7]); - expect(Object.getPrototypeOf(config.referenceListingIds)).toBe(Object.prototype); - }); - - test('ignores undefined prefixed keys and differently cased look-alike keys', () => { - const config = parseResearchCopilotHostConfig( - buildEnv({ - RESEARCH_MCP_NOT_SET: undefined, - research_mcp_extra: 'x', - Research_Mcp_Extra: 'y', - }) - ); - expect(config.principalId).toBe('operator'); - }); - - test('accepts boundary early-close values (minute 1/960, dates 1976-01-01 and 2030-12-31)', () => { - const config = parseResearchCopilotHostConfig( - buildEnv({ - RESEARCH_MCP_EARLY_CLOSES: JSON.stringify({ - XNYS: { '1976-01-01': 1, '2030-12-31': 960 }, - }), - }) - ); - expect(config.earlyCloses).toEqual({ XNYS: { '1976-01-01': 1, '2030-12-31': 960 } }); - }); - - test('accepts INT32 max listing id and rejects a two-digit-year cutoff that Date.UTC would remap', () => { - expect( - parseResearchCopilotHostConfig( - buildEnv({ RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: '{"XNYS":[2147483647]}' }) - ).referenceListingIds - ).toEqual({ XNYS: [2147483647] }); - - let caught: unknown; - try { - parseResearchCopilotHostConfig( - buildEnv({ RESEARCH_MCP_VAULT_CUTOFF_TS: '0050-01-01T00:00:00Z' }) - ); - } catch (err) { - caught = err; - } - // Must never silently become 1950-01-01 (a different, earlier cutoff). - expect(caught).toBeInstanceOf(ResearchCopilotHostConfigError); - expect((caught as ResearchCopilotHostConfigError).variable).toBe( - 'RESEARCH_MCP_VAULT_CUTOFF_TS' - ); - }); - - test('parses the cutoff once and repeated parses of the same env are deterministic', () => { - const a = parseResearchCopilotHostConfig(buildEnv()); - const b = parseResearchCopilotHostConfig(buildEnv()); - expect(a).toEqual(b); - expect(a.vaultCutoffTs).toBe(CUTOFF_MS); - }); -}); diff --git a/libs/research/test/mcp-stdio-host.test.ts b/libs/research/test/mcp-stdio-host.test.ts deleted file mode 100644 index 3dd7cdee..00000000 --- a/libs/research/test/mcp-stdio-host.test.ts +++ /dev/null @@ -1,1206 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { readFileSync } from 'node:fs'; -import type { - BarBatch, - BarQuery, - BarRecord, - MarketDataStore, -} from '../src/market-data-store'; -import { MarketDataStoreNotImplementedError } from '../src/market-data-store-duckdb'; -import { - type LibraryCardQuery, - type LibraryCardRecord, - type PostgresResearchCopilotExecutor, - RESEARCH_COPILOT_HOST_NAME, - RESEARCH_COPILOT_HOST_VERSION, - RESEARCH_COPILOT_TOOL_NAMES, - type QueryDataResultPayload, - type ReadKnowledgeResultPayload, - type ResearchCopilotHostConfig, - ResearchCopilotHostConfigError, - type StdioInput, - type StdioOutput, - parseResearchCopilotHostConfig, - runResearchCopilotStdioHost, -} from '../src/mcp/index'; - -const FAKE_DECODED_PASSWORD = 's3cr@t pass#99!'; -const FAKE_ENCODED_PASSWORD = encodeURIComponent(FAKE_DECODED_PASSWORD); -const FAKE_POSTGRES_URL = `postgresql://research_ro:${FAKE_ENCODED_PASSWORD}@127.0.0.1:5433/trading_bot_dev?sslmode=disable`; -const VALID_AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555'; -const VALID_CUTOFF_ISO = '2025-06-01T00:00:00Z'; -const VALID_CUTOFF_MS = Date.UTC(2025, 5, 1, 0, 0, 0, 0); -const FIXED_NOW_MS = Date.UTC(2025, 4, 15, 12, 0, 0, 0); - -function buildValidEnv( - overrides: Readonly> = {} -): Record { - return { - PATH: '/usr/local/bin:/usr/bin', - HOME: '/tmp/fake-home', - NODE_ENV: 'test', - RESEARCH_MCP_POSTGRES_URL: FAKE_POSTGRES_URL, - RESEARCH_MCP_POSTGRES_SCHEMA: 'research_ro', - RESEARCH_MCP_CURATED_ROOT: '/mnt/data/stockbot/curated', - RESEARCH_MCP_VAULT_CUTOFF_TS: VALID_CUTOFF_ISO, - RESEARCH_MCP_PRINCIPAL_ID: VALID_AGENT_PRINCIPAL, - RESEARCH_MCP_LIBRARY_ROOT: '/mnt/data/stockbot/library', - RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: JSON.stringify({ - XNYS: [101, 102], - XTSE: [201], - }), - RESEARCH_MCP_EARLY_CLOSES: JSON.stringify({ - XNYS: { - '2024-11-29': 780, - '2024-12-24': 780, - }, - }), - ...overrides, - }; -} - -function assertNoCredentialLeak(error: unknown, visited: Set = new Set()): void { - expect(error).toBeInstanceOf(Error); - if (visited.has(error)) { - return; - } - visited.add(error); - const err = error as Error & { cause?: unknown; errors?: unknown }; - expect(err.message).not.toContain(FAKE_POSTGRES_URL); - expect(err.message).not.toContain(FAKE_ENCODED_PASSWORD); - expect(err.message).not.toContain(FAKE_DECODED_PASSWORD); - if (err.cause !== undefined) { - assertNoCredentialLeak(err.cause, visited); - } - if (Array.isArray(err.errors)) { - for (const nested of err.errors) { - assertNoCredentialLeak(nested, visited); - } - } -} - -function createMemoryOutput(): { - readonly output: StdioOutput; - readonly chunks: string[]; - text(): string; - jsonLines(): unknown[]; -} { - const chunks: string[] = []; - const output: StdioOutput = { - write(chunk: string): boolean { - chunks.push(chunk); - return true; - }, - }; - return { - output, - chunks, - text: () => chunks.join(''), - jsonLines: () => { - const raw = chunks.join(''); - if (raw.length === 0) { - return []; - } - return raw - .trimEnd() - .split('\n') - .map(line => JSON.parse(line) as unknown); - }, - }; -} - -function createTrackingInput(messages: readonly unknown[]): { - readonly input: StdioInput; - readonly getPulledCount: () => number; -} { - let pulled = 0; - const input: StdioInput = { - async *[Symbol.asyncIterator]() { - for (const msg of messages) { - pulled += 1; - yield `${JSON.stringify(msg)}\n`; - } - }, - }; - return { - input, - getPulledCount: () => pulled, - }; -} - -function createFakeExecutor(): { - readonly executor: PostgresResearchCopilotExecutor; - readonly calls: Array<{ readonly text: string; readonly params: readonly unknown[] | undefined }>; -} { - const calls: Array<{ readonly text: string; readonly params: readonly unknown[] | undefined }> = []; - const executor: PostgresResearchCopilotExecutor = { - async query>( - text: string, - params?: readonly unknown[] - ): Promise<{ readonly rows: readonly Row[] }> { - calls.push({ text, params }); - return { rows: [] }; - }, - }; - return { executor, calls }; -} - -function createFakeStore( - rows: readonly BarRecord[] = [] -): { - readonly store: MarketDataStore; - readonly barQueries: BarQuery[]; -} { - const barQueries: BarQuery[] = []; - const store: MarketDataStore = { - async *bars(q: BarQuery): AsyncIterable { - barQueries.push(q); - yield { - listingId: q.listingIds[0] ?? 0, - timeframe: q.timeframe, - rows: [...rows], - }; - }, - async crossSection() { - throw new MarketDataStoreNotImplementedError('crossSection'); - }, - async fundamentalsAsOf() { - throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); - }, - async events() { - throw new MarketDataStoreNotImplementedError('events'); - }, - async shortsAsOf() { - throw new MarketDataStoreNotImplementedError('shortsAsOf'); - }, - async macroAsOf() { - throw new MarketDataStoreNotImplementedError('macroAsOf'); - }, - async fx() { - throw new MarketDataStoreNotImplementedError('fx'); - }, - async universe() { - return []; - }, - }; - return { store, barQueries }; -} - -describe('parseResearchCopilotHostConfig', () => { - test('parses a complete valid env with optionals and ignores unrelated env keys', () => { - const config = parseResearchCopilotHostConfig(buildValidEnv()); - - expect(config).toEqual({ - postgresUrl: FAKE_POSTGRES_URL, - postgresSchema: 'research_ro', - curatedRoot: '/mnt/data/stockbot/curated', - vaultCutoffTs: VALID_CUTOFF_MS, - principalId: VALID_AGENT_PRINCIPAL, - libraryRoot: '/mnt/data/stockbot/library', - referenceListingIds: { - XNYS: [101, 102], - XTSE: [201], - }, - earlyCloses: { - XNYS: { - '2024-11-29': 780, - '2024-12-24': 780, - }, - }, - }); - }); - - test('supports omitted optional variables, operator principal, postgres:// scheme, and millisecond UTC instants', () => { - const env = buildValidEnv({ - RESEARCH_MCP_POSTGRES_URL: 'postgres://user:pass@localhost:5432/db', - RESEARCH_MCP_POSTGRES_SCHEMA: undefined, - RESEARCH_MCP_VAULT_CUTOFF_TS: '2025-06-01T13:30:45.250Z', - RESEARCH_MCP_PRINCIPAL_ID: 'operator', - RESEARCH_MCP_EARLY_CLOSES: undefined, - }); - - const config = parseResearchCopilotHostConfig(env); - - expect(config.postgresUrl).toBe('postgres://user:pass@localhost:5432/db'); - expect(config.postgresSchema).toBeUndefined(); - expect('postgresSchema' in config).toBe(false); - expect(config.earlyCloses).toBeUndefined(); - expect('earlyCloses' in config).toBe(false); - expect(config.principalId).toBe('operator'); - expect(config.vaultCutoffTs).toBe(Date.UTC(2025, 5, 1, 13, 30, 45, 250)); - }); - - test.each([ - 'RESEARCH_MCP_POSTGRES_URL', - 'RESEARCH_MCP_CURATED_ROOT', - 'RESEARCH_MCP_VAULT_CUTOFF_TS', - 'RESEARCH_MCP_PRINCIPAL_ID', - 'RESEARCH_MCP_LIBRARY_ROOT', - 'RESEARCH_MCP_SESSION_REFERENCE_LISTINGS', - ] as const)('rejects missing required variable %s', variable => { - const env = buildValidEnv({ [variable]: undefined }); - let caught: unknown; - try { - parseResearchCopilotHostConfig(env); - } catch (err) { - caught = err; - } - - expect(caught).toBeInstanceOf(ResearchCopilotHostConfigError); - const err = caught as ResearchCopilotHostConfigError; - expect(err.variable).toBe(variable); - expect(err.message).toContain(variable); - assertNoCredentialLeak(err); - }); - - test.each([ - 'RESEARCH_MCP_POSTGRES_URL', - 'RESEARCH_MCP_POSTGRES_SCHEMA', - 'RESEARCH_MCP_CURATED_ROOT', - 'RESEARCH_MCP_VAULT_CUTOFF_TS', - 'RESEARCH_MCP_PRINCIPAL_ID', - 'RESEARCH_MCP_LIBRARY_ROOT', - 'RESEARCH_MCP_SESSION_REFERENCE_LISTINGS', - 'RESEARCH_MCP_EARLY_CLOSES', - ] as const)('rejects empty and whitespace-only values for %s', variable => { - for (const blank of ['', ' \t\n ']) { - const env = buildValidEnv({ [variable]: blank }); - let caught: unknown; - try { - parseResearchCopilotHostConfig(env); - } catch (err) { - caught = err; - } - - expect(caught).toBeInstanceOf(ResearchCopilotHostConfigError); - const err = caught as ResearchCopilotHostConfigError; - expect(err.variable).toBe(variable); - expect(err.message).toContain(variable); - assertNoCredentialLeak(err); - } - }); - - test.each([ - ['unknown prefixed key with value', 'RESEARCH_MCP_EXTRA', 'enabled'], - ['unknown prefixed key with empty string', 'RESEARCH_MCP_UNKNOWN_FLAG', ''], - ] as const)('rejects %s', (_label, key, value) => { - const env = buildValidEnv({ [key]: value }); - let caught: unknown; - try { - parseResearchCopilotHostConfig(env); - } catch (err) { - caught = err; - } - - expect(caught).toBeInstanceOf(ResearchCopilotHostConfigError); - const err = caught as ResearchCopilotHostConfigError; - expect(err.variable).toBe(key); - expect(err.message).toContain(key); - assertNoCredentialLeak(err); - }); - - test.each([ - ['non-postgres scheme', `http://user:${FAKE_ENCODED_PASSWORD}@localhost:5432/db`], - ['missing host', `postgresql://user:${FAKE_ENCODED_PASSWORD}@/db`], - ['malformed URL', `not-a-url-${FAKE_DECODED_PASSWORD}`], - ['surrounding whitespace', ` ${FAKE_POSTGRES_URL} `], - ['invalid percent-encoding in password', 'postgresql://research_ro:%FF@127.0.0.1:5433/db'], - ['invalid percent-encoding in username', 'postgresql://user%FF:pass@127.0.0.1:5433/db'], - ] as const)('rejects invalid POSTGRES_URL (%s) without leaking URL or password', (_label, badUrl) => { - const env = buildValidEnv({ RESEARCH_MCP_POSTGRES_URL: badUrl }); - let caught: unknown; - try { - parseResearchCopilotHostConfig(env); - } catch (err) { - caught = err; - } - - expect(caught).toBeInstanceOf(ResearchCopilotHostConfigError); - const err = caught as ResearchCopilotHostConfigError; - expect(err.variable).toBe('RESEARCH_MCP_POSTGRES_URL'); - expect(err.message).toContain('RESEARCH_MCP_POSTGRES_URL'); - expect(err.message).not.toContain(badUrl); - assertNoCredentialLeak(err); - }); - - test.each([ - ['uppercase', 'Research_RO'], - ['leading digit', '1schema'], - ['hyphen', 'research-ro'], - ['SQL injection', 'public"; DROP TABLE findings; --'], - ] as const)('rejects invalid POSTGRES_SCHEMA (%s)', (_label, badSchema) => { - const env = buildValidEnv({ RESEARCH_MCP_POSTGRES_SCHEMA: badSchema }); - let caught: unknown; - try { - parseResearchCopilotHostConfig(env); - } catch (err) { - caught = err; - } - - expect(caught).toBeInstanceOf(ResearchCopilotHostConfigError); - const err = caught as ResearchCopilotHostConfigError; - expect(err.variable).toBe('RESEARCH_MCP_POSTGRES_SCHEMA'); - expect(err.message).toContain('RESEARCH_MCP_POSTGRES_SCHEMA'); - expect(err.message).not.toContain(badSchema); - assertNoCredentialLeak(err); - }); - - test.each([ - ['bare uuid', '11111111-2222-4333-8444-555555555555'], - ['uppercase agent uuid', 'agent:11111111-2222-4333-8444-55555555555A'], - ['invalid uuid version 0', 'agent:11111111-2222-0333-8444-555555555555'], - ['invalid uuid version 9', 'agent:11111111-2222-9333-8444-555555555555'], - ['invalid RFC variant', 'agent:11111111-2222-4333-0444-555555555555'], - ['unknown role', 'admin'], - ] as const)('rejects invalid PRINCIPAL_ID (%s)', (_label, badPrincipal) => { - const env = buildValidEnv({ RESEARCH_MCP_PRINCIPAL_ID: badPrincipal }); - let caught: unknown; - try { - parseResearchCopilotHostConfig(env); - } catch (err) { - caught = err; - } - - expect(caught).toBeInstanceOf(ResearchCopilotHostConfigError); - const err = caught as ResearchCopilotHostConfigError; - expect(err.variable).toBe('RESEARCH_MCP_PRINCIPAL_ID'); - expect(err.message).toContain('RESEARCH_MCP_PRINCIPAL_ID'); - expect(err.message).not.toContain(badPrincipal); - assertNoCredentialLeak(err); - }); - - test.each([ - ['date-only string', '2025-06-01'], - ['missing seconds', '2025-06-01T00:00Z'], - ['non-UTC offset +00:00', '2025-06-01T00:00:00+00:00'], - ['non-UTC offset -05:00', '2025-06-01T00:00:00-05:00'], - ['lowercase z', '2025-06-01T00:00:00z'], - ['sub-millisecond precision', '2025-06-01T00:00:00.123456Z'], - ['impossible leap day', '2025-02-29T00:00:00Z'], - ['impossible April 31', '2025-04-31T00:00:00Z'], - ['hour 24', '2025-06-01T24:00:00Z'], - ['second 60', '2025-06-01T00:00:60Z'], - ] as const)('rejects invalid VAULT_CUTOFF_TS (%s)', (_label, badTs) => { - const env = buildValidEnv({ RESEARCH_MCP_VAULT_CUTOFF_TS: badTs }); - let caught: unknown; - try { - parseResearchCopilotHostConfig(env); - } catch (err) { - caught = err; - } - - expect(caught).toBeInstanceOf(ResearchCopilotHostConfigError); - const err = caught as ResearchCopilotHostConfigError; - expect(err.variable).toBe('RESEARCH_MCP_VAULT_CUTOFF_TS'); - expect(err.message).toContain('RESEARCH_MCP_VAULT_CUTOFF_TS'); - expect(err.message).not.toContain(badTs); - assertNoCredentialLeak(err); - }); - - test.each([ - ['malformed JSON', '{bad-json'], - ['JSON array root', '[101, 102]'], - ['JSON null root', 'null'], - ['scalar listing ID', '{"XNYS": 101}'], - ['empty listing ID array', '{"XNYS": []}'], - ['duplicate listing IDs', '{"XNYS": [101, 101]}'], - ['zero listing ID', '{"XNYS": [0]}'], - ['negative listing ID', '{"XNYS": [-5]}'], - ['float listing ID', '{"XNYS": [10.5]}'], - ['INT32 overflow', '{"XNYS": [2147483648]}'], - ['string listing ID', '{"XNYS": ["101"]}'], - ['untrimmed calendar code', '{" XNYS ": [101]}'], - ['blank calendar code', '{"": [101]}'], - ] as const)('rejects invalid SESSION_REFERENCE_LISTINGS (%s)', (_label, badJson) => { - const env = buildValidEnv({ RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: badJson }); - let caught: unknown; - try { - parseResearchCopilotHostConfig(env); - } catch (err) { - caught = err; - } - - expect(caught).toBeInstanceOf(ResearchCopilotHostConfigError); - const err = caught as ResearchCopilotHostConfigError; - expect(err.variable).toBe('RESEARCH_MCP_SESSION_REFERENCE_LISTINGS'); - expect(err.message).toContain('RESEARCH_MCP_SESSION_REFERENCE_LISTINGS'); - assertNoCredentialLeak(err); - }); - - test.each([ - ['malformed JSON', '{bad-json'], - ['JSON array root', '[]'], - ['JSON null root', 'null'], - ['non-object calendar entry', '{"XNYS": [780]}'], - ['untrimmed calendar code', '{" XNYS": {"2024-11-29": 780}}'], - ['impossible calendar date', '{"XNYS": {"2024-02-30": 780}}'], - ['date below supported range', '{"XNYS": {"1975-12-31": 780}}'], - ['date above supported range', '{"XNYS": {"2031-01-01": 780}}'], - ['minute 0 (below min 1)', '{"XNYS": {"2024-11-29": 0}}'], - ['negative minute', '{"XNYS": {"2024-11-29": -10}}'], - ['minute 961 (above max 960)', '{"XNYS": {"2024-11-29": 961}}'], - ['fractional minute', '{"XNYS": {"2024-11-29": 780.5}}'], - ['string minute', '{"XNYS": {"2024-11-29": "780"}}'], - ] as const)('rejects invalid EARLY_CLOSES (%s)', (_label, badJson) => { - const env = buildValidEnv({ RESEARCH_MCP_EARLY_CLOSES: badJson }); - let caught: unknown; - try { - parseResearchCopilotHostConfig(env); - } catch (err) { - caught = err; - } - - expect(caught).toBeInstanceOf(ResearchCopilotHostConfigError); - const err = caught as ResearchCopilotHostConfigError; - expect(err.variable).toBe('RESEARCH_MCP_EARLY_CLOSES'); - expect(err.message).toContain('RESEARCH_MCP_EARLY_CLOSES'); - assertNoCredentialLeak(err); - }); -}); - -describe('runResearchCopilotStdioHost', () => { - test('serves initialize, tools/list (exact 6 tools in order), and read_knowledge (library) with zero SQL calls', async () => { - const config = parseResearchCopilotHostConfig(buildValidEnv()); - const fakeExec = createFakeExecutor(); - const fakeStore = createFakeStore(); - const expectedCard: LibraryCardRecord = { - id: 'card-short-squeeze-01', - title: 'Canadian Short Interest Spike', - summary: 'Synthetic fixture card for stdio host wiring verification.', - body: 'Full body text for the synthetic short interest library card.', - tags: ['shorts', 'ca'], - }; - - class StatefulLibraryCardReader { - readonly queries: LibraryCardQuery[] = []; - private readonly cards: readonly LibraryCardRecord[]; - - constructor(cards: readonly LibraryCardRecord[]) { - this.cards = cards; - } - - async listLibraryCards(q: LibraryCardQuery): Promise { - this.queries.push(q); - return [...this.cards]; - } - } - - const reader = new StatefulLibraryCardReader([expectedCard]); - const sink = createMemoryOutput(); - const { input } = createTrackingInput([ - { - jsonrpc: '2.0', - id: 1, - method: 'initialize', - params: { - protocolVersion: '2024-11-05', - capabilities: {}, - clientInfo: { name: 'test-client', version: '1.0.0' }, - }, - }, - { - jsonrpc: '2.0', - method: 'notifications/initialized', - }, - { - jsonrpc: '2.0', - id: 2, - method: 'tools/list', - }, - { - jsonrpc: '2.0', - id: 3, - method: 'tools/call', - params: { - name: 'read_knowledge', - arguments: { - source: 'library', - query: 'short interest', - }, - }, - }, - ]); - - await runResearchCopilotStdioHost({ - config, - openExecutor: async () => ({ - executor: fakeExec.executor, - close: async () => {}, - }), - openStore: async () => ({ - store: fakeStore.store, - close: async () => {}, - }), - createLibraryCardReader: async () => reader, - newId: () => 'id-1', - now: () => FIXED_NOW_MS, - stdio: { input, output: sink.output }, - }); - - const responses = sink.jsonLines() as Array<{ - readonly id: number; - readonly result: Record; - }>; - expect(responses).toHaveLength(3); - - const initResp = responses[0]!; - expect(initResp.id).toBe(1); - expect(initResp.result.serverInfo).toEqual({ - name: RESEARCH_COPILOT_HOST_NAME, - version: RESEARCH_COPILOT_HOST_VERSION, - }); - - const listResp = responses[1]!; - expect(listResp.id).toBe(2); - const listedTools = listResp.result.tools as Array<{ readonly name: string }>; - expect(listedTools.map(t => t.name)).toEqual([...RESEARCH_COPILOT_TOOL_NAMES]); - - const callResp = responses[2]!; - expect(callResp.id).toBe(3); - const toolEnvelope = callResp.result as { - readonly isError?: boolean; - readonly content: ReadonlyArray<{ readonly type: 'text'; readonly text: string }>; - }; - expect(toolEnvelope.isError).toBeUndefined(); - const payload = JSON.parse(toolEnvelope.content[0]!.text) as ReadKnowledgeResultPayload; - expect(payload.rows).toHaveLength(1); - expect(payload.rows[0]?.source).toBe('library'); - expect(payload.rows[0]?.id).toBe(expectedCard.id); - expect(payload.rows[0]?.source === 'library' ? payload.rows[0].title : undefined).toBe( - expectedCard.title - ); - - expect(reader.queries).toHaveLength(1); - expect(fakeExec.calls).toHaveLength(0); - }); - - test('enforces the single RESEARCH_MCP_VAULT_CUTOFF_TS across query_data rejection, clamping, and row defense-in-depth', async () => { - // Pinned synthetic bar fixture (protocol check only, no strategy or return claim): - // - Cutoff from env: 2025-06-01T00:00:00Z - // - Listing 101: - // 1) Pre-cutoff bar (2025-05-30 20:00Z, knownAt 2025-05-30 20:00Z) -> included - // 2) Cutoff-ts bar (2025-06-01 00:00Z, knownAt 2025-05-30 20:00Z) -> excluded - // 3) Post-cutoff knownAt bar (2025-05-29 20:00Z, knownAt 2025-06-01 00:00Z) -> excluded - const config = parseResearchCopilotHostConfig(buildValidEnv()); - const preCutoffBar: BarRecord = { - listingId: 101, - ts: Date.UTC(2025, 4, 30, 20, 0, 0, 0), - open: 10, - high: 11, - low: 9.5, - close: 10.5, - volume: 10_000, - vwap: 10.25, - knownAt: Date.UTC(2025, 4, 30, 20, 0, 0, 0), - }; - const atCutoffTsBar: BarRecord = { - listingId: 101, - ts: VALID_CUTOFF_MS, - open: 10.5, - high: 11.5, - low: 10, - close: 11, - volume: 12_000, - vwap: 10.75, - knownAt: Date.UTC(2025, 4, 30, 20, 0, 0, 0), - }; - const atCutoffKnownAtBar: BarRecord = { - listingId: 101, - ts: Date.UTC(2025, 4, 29, 20, 0, 0, 0), - open: 9.5, - high: 10, - low: 9, - close: 9.8, - volume: 8_000, - vwap: 9.6, - knownAt: VALID_CUTOFF_MS, - }; - - const fakeExec = createFakeExecutor(); - const fakeStore = createFakeStore([preCutoffBar, atCutoffTsBar, atCutoffKnownAtBar]); - let storeFactoryConfig: ResearchCopilotHostConfig | undefined; - - const sink = createMemoryOutput(); - const { input } = createTrackingInput([ - { - jsonrpc: '2.0', - id: 1, - method: 'tools/call', - params: { - name: 'query_data', - arguments: { - listingIds: [101], - from: '2025-06-01', - to: '2025-06-05', - }, - }, - }, - { - jsonrpc: '2.0', - id: 2, - method: 'tools/call', - params: { - name: 'query_data', - arguments: { - listingIds: [101], - from: '2025-05-29', - to: '2025-06-05', - asOf: '2025-06-05', - }, - }, - }, - ]); - - await runResearchCopilotStdioHost({ - config, - openExecutor: async () => ({ - executor: fakeExec.executor, - close: async () => {}, - }), - openStore: async cfg => { - storeFactoryConfig = cfg; - return { - store: fakeStore.store, - close: async () => {}, - }; - }, - createLibraryCardReader: async () => ({ - listLibraryCards: async () => [], - }), - newId: () => 'id-1', - now: () => FIXED_NOW_MS, - stdio: { input, output: sink.output }, - }); - - expect(storeFactoryConfig).toBe(config); - expect(storeFactoryConfig?.vaultCutoffTs).toBe(VALID_CUTOFF_MS); - - const responses = sink.jsonLines() as Array<{ - readonly id: number; - readonly result: { - readonly isError?: boolean; - readonly content: ReadonlyArray<{ readonly type: 'text'; readonly text: string }>; - }; - }>; - expect(responses).toHaveLength(2); - - // Call 1: at/beyond cutoff -> VaultHoldoutFenceError with zero store calls. - expect(responses[0]?.result.isError).toBe(true); - expect(responses[0]?.result.content[0]?.text).toContain('VaultHoldoutFenceError'); - - // Call 2: straddling range -> clamped strictly below cutoff and post-cutoff rows dropped. - expect(fakeStore.barQueries).toHaveLength(1); - const barQuery = fakeStore.barQueries[0]!; - expect(barQuery.scope).toBe('vault_fenced'); - expect(barQuery.to).toBe('2025-05-31T23:59:59.999999Z'); - expect(barQuery.asOf).toBe('2025-05-31T23:59:59.999999Z'); - - expect(responses[1]?.result.isError).toBeUndefined(); - const payload = JSON.parse(responses[1]!.result.content[0]!.text) as QueryDataResultPayload; - expect(payload.vaultCutoffTs).toBe(VALID_CUTOFF_MS); - expect(payload.toMs).toBe(VALID_CUTOFF_MS - 1); - expect(payload.asOfMs).toBe(VALID_CUTOFF_MS - 1); - expect(payload.clampedTo).toBe(true); - expect(payload.clampedAsOf).toBe(true); - expect(payload.rows).toEqual([preCutoffBar]); - }); - - test('closes acquired resources exactly once in reverse order on normal EOF', async () => { - const config = parseResearchCopilotHostConfig(buildValidEnv()); - const fakeExec = createFakeExecutor(); - const fakeStore = createFakeStore(); - const events: string[] = []; - let execCloses = 0; - let storeCloses = 0; - - const sink = createMemoryOutput(); - const { input } = createTrackingInput([{ jsonrpc: '2.0', id: 1, method: 'ping' }]); - - await runResearchCopilotStdioHost({ - config, - openExecutor: async () => { - events.push('open:executor'); - return { - executor: fakeExec.executor, - close: async () => { - execCloses += 1; - events.push('close:executor'); - }, - }; - }, - openStore: async () => { - events.push('open:store'); - return { - store: fakeStore.store, - close: async () => { - storeCloses += 1; - events.push('close:store'); - }, - }; - }, - createLibraryCardReader: async () => { - events.push('open:library'); - return { - listLibraryCards: async () => [], - }; - }, - newId: () => 'id-1', - now: () => FIXED_NOW_MS, - stdio: { input, output: sink.output }, - }); - - expect(events).toEqual([ - 'open:executor', - 'open:store', - 'open:library', - 'close:store', - 'close:executor', - ]); - expect(storeCloses).toBe(1); - expect(execCloses).toBe(1); - expect(sink.jsonLines()).toHaveLength(1); - }); - - test('fails closed when openExecutor rejects with zero downstream calls, zero stdout, and zero input consumed', async () => { - const config = parseResearchCopilotHostConfig(buildValidEnv()); - const safeError = new Error('PostgreSQL host unreachable'); - let storeCalled = false; - let libraryCalled = false; - - const sink = createMemoryOutput(); - const tracker = createTrackingInput([{ jsonrpc: '2.0', id: 1, method: 'ping' }]); - - let caught: unknown; - try { - await runResearchCopilotStdioHost({ - config, - openExecutor: async () => { - throw safeError; - }, - openStore: async () => { - storeCalled = true; - return { store: createFakeStore().store, close: async () => {} }; - }, - createLibraryCardReader: async () => { - libraryCalled = true; - return { listLibraryCards: async () => [] }; - }, - newId: () => 'id-1', - now: () => FIXED_NOW_MS, - stdio: { input: tracker.input, output: sink.output }, - }); - } catch (err) { - caught = err; - } - - expect(caught).toBe(safeError); - expect(storeCalled).toBe(false); - expect(libraryCalled).toBe(false); - expect(sink.text()).toBe(''); - expect(tracker.getPulledCount()).toBe(0); - }); - - test('closes executor and preserves original error when openStore throws, even if executor.close throws', async () => { - const config = parseResearchCopilotHostConfig(buildValidEnv()); - const storeError = new Error('DuckDB catalog open failed'); - let execCloses = 0; - let libraryCalled = false; - - const sink = createMemoryOutput(); - const tracker = createTrackingInput([{ jsonrpc: '2.0', id: 1, method: 'ping' }]); - - let caught: unknown; - try { - await runResearchCopilotStdioHost({ - config, - openExecutor: async () => ({ - executor: createFakeExecutor().executor, - close: async () => { - execCloses += 1; - throw new Error('secondary executor close failure'); - }, - }), - openStore: async () => { - throw storeError; - }, - createLibraryCardReader: async () => { - libraryCalled = true; - return { listLibraryCards: async () => [] }; - }, - newId: () => 'id-1', - now: () => FIXED_NOW_MS, - stdio: { input: tracker.input, output: sink.output }, - }); - } catch (err) { - caught = err; - } - - expect(caught).toBe(storeError); - expect(execCloses).toBe(1); - expect(libraryCalled).toBe(false); - expect(sink.text()).toBe(''); - expect(tracker.getPulledCount()).toBe(0); - }); - - test('closes store then executor and preserves original error when createLibraryCardReader throws, even if both closes throw', async () => { - const config = parseResearchCopilotHostConfig(buildValidEnv()); - const libraryError = new Error('library.yml unreadable'); - const closeOrder: string[] = []; - - const sink = createMemoryOutput(); - const tracker = createTrackingInput([{ jsonrpc: '2.0', id: 1, method: 'ping' }]); - - let caught: unknown; - try { - await runResearchCopilotStdioHost({ - config, - openExecutor: async () => ({ - executor: createFakeExecutor().executor, - close: async () => { - closeOrder.push('executor'); - throw new Error('executor close failed'); - }, - }), - openStore: async () => ({ - store: createFakeStore().store, - close: async () => { - closeOrder.push('store'); - throw new Error('store close failed'); - }, - }), - createLibraryCardReader: async () => { - throw libraryError; - }, - newId: () => 'id-1', - now: () => FIXED_NOW_MS, - stdio: { input: tracker.input, output: sink.output }, - }); - } catch (err) { - caught = err; - } - - expect(caught).toBe(libraryError); - expect(closeOrder).toEqual(['store', 'executor']); - expect(sink.text()).toBe(''); - expect(tracker.getPulledCount()).toBe(0); - }); - - test('closes both resources in reverse order and preserves transport error when stdio input or output throws', async () => { - const config = parseResearchCopilotHostConfig(buildValidEnv()); - - // Case 1: throwing input stream - const inputError = new Error('stdin read reset'); - const inputCloseOrder: string[] = []; - const failingInput: StdioInput = { - async *[Symbol.asyncIterator]() { - yield `${JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'ping' })}\n`; - throw inputError; - }, - }; - - let caughtInput: unknown; - try { - await runResearchCopilotStdioHost({ - config, - openExecutor: async () => ({ - executor: createFakeExecutor().executor, - close: async () => { - inputCloseOrder.push('executor'); - }, - }), - openStore: async () => ({ - store: createFakeStore().store, - close: async () => { - inputCloseOrder.push('store'); - throw new Error('close error masked by primary'); - }, - }), - createLibraryCardReader: async () => ({ - listLibraryCards: async () => [], - }), - newId: () => 'id-1', - now: () => FIXED_NOW_MS, - stdio: { input: failingInput, output: createMemoryOutput().output }, - }); - } catch (err) { - caughtInput = err; - } - expect(caughtInput).toBe(inputError); - expect(inputCloseOrder).toEqual(['store', 'executor']); - - // Case 2: throwing output stream - const outputError = new Error('stdout broken pipe'); - const outputCloseOrder: string[] = []; - const failingOutput: StdioOutput = { - write() { - throw outputError; - }, - }; - - let caughtOutput: unknown; - try { - await runResearchCopilotStdioHost({ - config, - openExecutor: async () => ({ - executor: createFakeExecutor().executor, - close: async () => { - outputCloseOrder.push('executor'); - }, - }), - openStore: async () => ({ - store: createFakeStore().store, - close: async () => { - outputCloseOrder.push('store'); - }, - }), - createLibraryCardReader: async () => ({ - listLibraryCards: async () => [], - }), - newId: () => 'id-1', - now: () => FIXED_NOW_MS, - stdio: { - input: createTrackingInput([{ jsonrpc: '2.0', id: 1, method: 'ping' }]).input, - output: failingOutput, - }, - }); - } catch (err) { - caughtOutput = err; - } - expect(caughtOutput).toBe(outputError); - expect(outputCloseOrder).toEqual(['store', 'executor']); - }); - - test('attempts both closes after EOF and reports the first close failure when both fail', async () => { - const config = parseResearchCopilotHostConfig(buildValidEnv()); - const storeCloseError = new Error('store flush failed'); - const execCloseError = new Error('pool drain failed'); - const closeOrder: string[] = []; - - let caught: unknown; - try { - await runResearchCopilotStdioHost({ - config, - openExecutor: async () => ({ - executor: createFakeExecutor().executor, - close: async () => { - closeOrder.push('executor'); - throw execCloseError; - }, - }), - openStore: async () => ({ - store: createFakeStore().store, - close: async () => { - closeOrder.push('store'); - throw storeCloseError; - }, - }), - createLibraryCardReader: async () => ({ - listLibraryCards: async () => [], - }), - newId: () => 'id-1', - now: () => FIXED_NOW_MS, - stdio: { - input: createTrackingInput([]).input, - output: createMemoryOutput().output, - }, - }); - } catch (err) { - caught = err; - } - - expect(closeOrder).toEqual(['store', 'executor']); - expect(caught).toBe(storeCloseError); - }); - - test('replaces startup and cleanup errors containing the full URL, decoded password, or uninspectable values with fixed stage errors and no cause', async () => { - const config = parseResearchCopilotHostConfig(buildValidEnv()); - - // 1. Startup error containing full DSN - let caughtDsn: unknown; - try { - await runResearchCopilotStdioHost({ - config, - openExecutor: async () => { - throw new Error(`connect failed for ${FAKE_POSTGRES_URL}`); - }, - openStore: async () => ({ store: createFakeStore().store, close: async () => {} }), - createLibraryCardReader: async () => ({ listLibraryCards: async () => [] }), - newId: () => 'id-1', - now: () => FIXED_NOW_MS, - stdio: { input: createTrackingInput([]).input, output: createMemoryOutput().output }, - }); - } catch (err) { - caughtDsn = err; - } - assertNoCredentialLeak(caughtDsn); - expect((caughtDsn as Error & { cause?: unknown }).cause).toBeUndefined(); - expect((caughtDsn as Error).message).toContain('executor'); - - // 2. Startup error containing decoded password by itself - let caughtPass: unknown; - try { - await runResearchCopilotStdioHost({ - config, - openExecutor: async () => ({ - executor: createFakeExecutor().executor, - close: async () => {}, - }), - openStore: async () => { - throw new Error(`auth rejected password "${FAKE_DECODED_PASSWORD}"`); - }, - createLibraryCardReader: async () => ({ listLibraryCards: async () => [] }), - newId: () => 'id-1', - now: () => FIXED_NOW_MS, - stdio: { input: createTrackingInput([]).input, output: createMemoryOutput().output }, - }); - } catch (err) { - caughtPass = err; - } - assertNoCredentialLeak(caughtPass); - expect((caughtPass as Error & { cause?: unknown }).cause).toBeUndefined(); - expect((caughtPass as Error).message).toContain('market data store'); - - // 3. Cleanup error containing decoded password after EOF - let caughtClose: unknown; - try { - await runResearchCopilotStdioHost({ - config, - openExecutor: async () => ({ - executor: createFakeExecutor().executor, - close: async () => { - throw new Error(`disconnect error for ${FAKE_DECODED_PASSWORD}`); - }, - }), - openStore: async () => ({ store: createFakeStore().store, close: async () => {} }), - createLibraryCardReader: async () => ({ listLibraryCards: async () => [] }), - newId: () => 'id-1', - now: () => FIXED_NOW_MS, - stdio: { input: createTrackingInput([]).input, output: createMemoryOutput().output }, - }); - } catch (err) { - caughtClose = err; - } - assertNoCredentialLeak(caughtClose); - expect((caughtClose as Error & { cause?: unknown }).cause).toBeUndefined(); - expect((caughtClose as Error).message).toContain('closing host resources'); - - // 4. Uninspectable non-Error rejection containing raw secret - let caughtRaw: unknown; - try { - await runResearchCopilotStdioHost({ - config, - openExecutor: async () => { - throw `raw-string-${FAKE_DECODED_PASSWORD}`; - }, - openStore: async () => ({ store: createFakeStore().store, close: async () => {} }), - createLibraryCardReader: async () => ({ listLibraryCards: async () => [] }), - newId: () => 'id-1', - now: () => FIXED_NOW_MS, - stdio: { input: createTrackingInput([]).input, output: createMemoryOutput().output }, - }); - } catch (err) { - caughtRaw = err; - } - assertNoCredentialLeak(caughtRaw); - expect((caughtRaw as Error & { cause?: unknown }).cause).toBeUndefined(); - }); - - test('redacts decoded password supplied via DSN query parameter', async () => { - const queryPasswordDsn = `postgresql://research_ro@127.0.0.1:5433/trading_bot_dev?sslmode=disable&password=${FAKE_ENCODED_PASSWORD}`; - const config = parseResearchCopilotHostConfig( - buildValidEnv({ RESEARCH_MCP_POSTGRES_URL: queryPasswordDsn }) - ); - - let caught: unknown; - try { - await runResearchCopilotStdioHost({ - config, - openExecutor: async () => { - throw new Error(`password authentication failed for "${FAKE_DECODED_PASSWORD}"`); - }, - openStore: async () => ({ store: createFakeStore().store, close: async () => {} }), - createLibraryCardReader: async () => ({ listLibraryCards: async () => [] }), - newId: () => 'id-1', - now: () => FIXED_NOW_MS, - stdio: { input: createTrackingInput([]).input, output: createMemoryOutput().output }, - }); - } catch (err) { - caught = err; - } - - assertNoCredentialLeak(caught); - expect((caught as Error).message).not.toContain(queryPasswordDsn); - expect((caught as Error).message).toContain('executor'); - expect((caught as Error & { cause?: unknown }).cause).toBeUndefined(); - }); - - test('replaces AggregateError containing nested credentials while preserving safe AggregateError', async () => { - const config = parseResearchCopilotHostConfig(buildValidEnv()); - - // 1. Unsafe AggregateError with nested DSN - let caughtUnsafe: unknown; - try { - await runResearchCopilotStdioHost({ - config, - openExecutor: async () => { - throw new AggregateError( - [ - new Error('primary host timed out'), - new Error(`replica connect failed for ${FAKE_POSTGRES_URL}`), - ], - 'All database endpoints failed' - ); - }, - openStore: async () => ({ store: createFakeStore().store, close: async () => {} }), - createLibraryCardReader: async () => ({ listLibraryCards: async () => [] }), - newId: () => 'id-1', - now: () => FIXED_NOW_MS, - stdio: { input: createTrackingInput([]).input, output: createMemoryOutput().output }, - }); - } catch (err) { - caughtUnsafe = err; - } - - assertNoCredentialLeak(caughtUnsafe); - expect(caughtUnsafe).not.toBeInstanceOf(AggregateError); - expect((caughtUnsafe as Error).message).toContain('executor'); - expect((caughtUnsafe as Error & { cause?: unknown }).cause).toBeUndefined(); - - // 2. Safe AggregateError is preserved by identity - const safeAggregate = new AggregateError( - [new Error('primary host timed out'), new Error('replica refused connection')], - 'All database endpoints failed' - ); - let caughtSafe: unknown; - try { - await runResearchCopilotStdioHost({ - config, - openExecutor: async () => { - throw safeAggregate; - }, - openStore: async () => ({ store: createFakeStore().store, close: async () => {} }), - createLibraryCardReader: async () => ({ listLibraryCards: async () => [] }), - newId: () => 'id-1', - now: () => FIXED_NOW_MS, - stdio: { input: createTrackingInput([]).input, output: createMemoryOutput().output }, - }); - } catch (err) { - caughtSafe = err; - } - - expect(caughtSafe).toBe(safeAggregate); - }); -}); - -describe('stdio-host dependency-free source invariants', () => { - test('contains no bare process access and no pg, node:*, or DuckDB imports', () => { - const src = readFileSync(new URL('../src/mcp/host/stdio-host.ts', import.meta.url), 'utf8'); - expect(src).not.toMatch(/\bprocess\./); - expect(src).not.toMatch(/from\s+['"]node:/); - expect(src).not.toMatch(/require\s*\(\s*['"]node:/); - expect(src).not.toMatch(/from\s+['"]pg(?:\/|['"])/); - expect(src).not.toMatch(/require\s*\(\s*['"]pg(?:\/|['"])/); - expect(src).not.toMatch(/from\s+['"][^'"]*duckdb/i); - expect(src).not.toMatch(/require\s*\(\s*['"][^'"]*duckdb/i); - }); -}); diff --git a/libs/research/test/mcp-stdio.test.ts b/libs/research/test/mcp-stdio.test.ts deleted file mode 100644 index 08d38bd5..00000000 --- a/libs/research/test/mcp-stdio.test.ts +++ /dev/null @@ -1,195 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { z } from 'zod'; -import { - JSON_RPC_ERROR_CODES, - type StdioOutput, - createMcpServer, - defineMcpTool, - runStdioServer, -} from '../src/mcp/index'; - -function createMemoryOutput(): { output: StdioOutput; chunks: string[]; text: () => string } { - const chunks: string[] = []; - const output: StdioOutput = { - write(chunk: string): boolean { - chunks.push(chunk); - return true; - }, - }; - return { - output, - chunks, - text: () => chunks.join(''), - }; -} - -async function* yieldChunks(chunks: readonly (Uint8Array | string)[]): AsyncGenerator { - for (const chunk of chunks) { - yield chunk; - } -} - -describe('MCP stdio transport', () => { - test('processes 3 messages (1 notification + 1 chunk-split multi-byte UTF-8 request) into exactly 2 newline-terminated responses', async () => { - const echoTool = defineMcpTool({ - name: 'echo_label', - description: 'Echoes a UTF-8 label.', - inputSchema: z.object({ label: z.string() }).strict(), - handler(input) { - return { - content: [{ type: 'text', text: input.label }], - }; - }, - }); - - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [echoTool], - }); - - const encoder = new TextEncoder(); - const msg1 = `${JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'ping' })}\n`; - const msg2 = `${JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' })}\n`; - const msg3Bytes = encoder.encode( - `${JSON.stringify({ - jsonrpc: '2.0', - id: 'utf8-2', - method: 'tools/call', - params: { name: 'echo_label', arguments: { label: 'café-🚀-αβγ' } }, - })}\n` - ); - - // Split right in the middle of the multi-byte UTF-8 emoji sequence. - const rocketStart = msg3Bytes.indexOf(0xf0); - expect(rocketStart).toBeGreaterThan(0); - const splitPoint = rocketStart + 2; - - const input = yieldChunks([ - encoder.encode(msg1), - encoder.encode(msg2), - msg3Bytes.slice(0, splitPoint), - msg3Bytes.slice(splitPoint), - ]); - - const sink = createMemoryOutput(); - await runStdioServer(server, { input, output: sink.output }); - - const rawOut = sink.text(); - expect(rawOut.endsWith('\n')).toBe(true); - const lines = rawOut.slice(0, -1).split('\n'); - expect(lines).toHaveLength(2); - - const resp1 = JSON.parse(lines[0] ?? '') as { id: number; result: Record }; - const resp2 = JSON.parse(lines[1] ?? '') as { - id: string; - result: { content: { type: string; text: string }[] }; - }; - - expect(resp1.id).toBe(1); - expect(resp1.result).toEqual({}); - expect(resp2.id).toBe('utf8-2'); - expect(resp2.result.content[0]?.text).toBe('café-🚀-αβγ'); - }); - - test('preserves strict arrival order even when earlier async handler takes longer than later handler', async () => { - const delayedTool = defineMcpTool({ - name: 'delayed', - description: 'Resolves after deterministic microtask/timer delay.', - inputSchema: z.object({ tag: z.string(), delayMs: z.number().int().min(0) }).strict(), - async handler(input) { - await new Promise(resolve => { - setTimeout(resolve, input.delayMs); - }); - return { - content: [{ type: 'text', text: input.tag }], - }; - }, - }); - - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [delayedTool], - }); - - const payload = [ - JSON.stringify({ - jsonrpc: '2.0', - id: 'first-slow', - method: 'tools/call', - params: { name: 'delayed', arguments: { tag: 'first', delayMs: 25 } }, - }), - JSON.stringify({ - jsonrpc: '2.0', - id: 'second-fast', - method: 'tools/call', - params: { name: 'delayed', arguments: { tag: 'second', delayMs: 0 } }, - }), - ].join('\n'); - - const sink = createMemoryOutput(); - await runStdioServer(server, { - input: yieldChunks([`${payload}\n`]), - output: sink.output, - }); - - const lines = sink.text().trimEnd().split('\n'); - expect(lines).toHaveLength(2); - const first = JSON.parse(lines[0] ?? '') as { id: string }; - const second = JSON.parse(lines[1] ?? '') as { id: string }; - expect(first.id).toBe('first-slow'); - expect(second.id).toBe('second-fast'); - }); - - test('ignores blank lines, handles CRLF, and flushes a final non-newline-terminated line on EOF', async () => { - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - }); - - const input = yieldChunks([ - '\n \r\n', - `${JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'ping' })}\r\n`, - '\n', - JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'ping' }), - ]); - - const sink = createMemoryOutput(); - await runStdioServer(server, { input, output: sink.output }); - - const lines = sink.text().trimEnd().split('\n'); - expect(lines).toHaveLength(2); - expect((JSON.parse(lines[0] ?? '') as { id: number }).id).toBe(1); - expect((JSON.parse(lines[1] ?? '') as { id: number }).id).toBe(2); - }); - - test('rejects oversized frames exceeding maxLineBytes with -32700 and recovers on the next line', async () => { - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - }); - - const hugeLine = `{"jsonrpc":"2.0","id":1,"method":"ping","pad":"${'x'.repeat(300)}"}\n`; - const nextLine = `${JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'ping' })}\n`; - - const sink = createMemoryOutput(); - await runStdioServer(server, { - input: yieldChunks([hugeLine, nextLine]), - output: sink.output, - maxLineBytes: 128, - }); - - const lines = sink.text().trimEnd().split('\n'); - expect(lines).toHaveLength(2); - const errResp = JSON.parse(lines[0] ?? '') as { - id: null; - error: { code: number }; - }; - const okResp = JSON.parse(lines[1] ?? '') as { id: number; result: Record }; - expect(errResp.id).toBeNull(); - expect(errResp.error.code).toBe(JSON_RPC_ERROR_CODES.PARSE_ERROR); - expect(okResp.id).toBe(2); - expect(okResp.result).toEqual({}); - }); -}); diff --git a/libs/research/test/notebook-snapshot-node-qa.test.ts b/libs/research/test/notebook-snapshot-node-qa.test.ts deleted file mode 100644 index 9b1b317f..00000000 --- a/libs/research/test/notebook-snapshot-node-qa.test.ts +++ /dev/null @@ -1,521 +0,0 @@ -import { readFileSync } from 'node:fs'; -import { - chmod, - mkdir, - mkdtemp, - readdir, - readFile, - realpath, - rm, - symlink, - writeFile, -} from 'node:fs/promises'; -import { tmpdir } from 'node:os'; -import { join, resolve } from 'node:path'; -import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; -import { - createNodeNotebookCommandRunner, - createNodeNotebookSnapshotFs, -} from '@stock-bot/research/notebook-snapshot-node'; -import { exportNotebookSnapshot, NotebookSnapshotError } from '../src/notebook-snapshot'; - -// QA coverage for T-191 beyond the programmer's suite: kill-then-settle on the -// EOUTPUTLIMIT path (including a descendant holding inherited pipes), timer -// cleanup on every settlement path (a leaked timer keeps the host process -// alive), stdin isolation, spawn error-code preservation, error-message -// redaction on timeout/overflow, concurrent runner reuse, O_EXCL refusing to -// follow a planted symlink, and exporter failure paths with real adapters that -// must keep a previously published snapshot intact. No real marimo, network or -// database is used: all children are `process.execPath` running temp fixtures. - -const ADAPTER_MODULE_PATH = resolve(import.meta.dir, '../src/notebook-snapshot-node.ts'); - -function getErrorCode(err: unknown): string | undefined { - if (typeof err === 'object' && err !== null && 'code' in err) { - const code = (err as { code?: unknown }).code; - if (typeof code === 'string') { - return code; - } - } - return undefined; -} - -async function expectReject(promise: Promise): Promise { - try { - await promise; - } catch (err) { - return err; - } - throw new Error('Expected promise to reject, but it resolved.'); -} - -function probePid(pid: number): string | undefined { - try { - process.kill(pid, 0); - return undefined; - } catch (err) { - return getErrorCode(err); - } -} - -function readPid(path: string): number { - const pid = Number.parseInt(readFileSync(path, 'utf8').trim(), 10); - if (!Number.isInteger(pid) || pid <= 0) { - throw new Error(`Invalid pid in ${path}`); - } - return pid; -} - -describe('notebook-snapshot-node QA', () => { - let workDir = ''; - - beforeEach(async () => { - workDir = await realpath(await mkdtemp(join(tmpdir(), 'notebook-snapshot-node-qa-'))); - }); - - afterEach(async () => { - if (workDir) { - await rm(workDir, { recursive: true, force: true }); - workDir = ''; - } - }); - - describe('runner: kill-then-settle on output overflow', () => { - test('EOUTPUTLIMIT rejects only after the direct child is dead (ESRCH)', async () => { - const pidFile = join(workDir, 'flood.pid'); - const scriptPath = join(workDir, 'flood.js'); - // Writes its pid, then floods stdout forever; it never exits on its own. - await writeFile( - scriptPath, - [ - "import { writeFileSync } from 'node:fs';", - 'writeFileSync(process.argv[2], String(process.pid), "utf8");', - 'const chunk = Buffer.alloc(4096, 0x78);', - 'function pump() { while (process.stdout.write(chunk)) {} process.stdout.once("drain", pump); }', - 'pump();', - ].join('\n'), - 'utf8' - ); - - const runner = createNodeNotebookCommandRunner({ maxOutputBytes: 64 * 1024 }); - const err = await expectReject( - runner.run(process.execPath, [scriptPath, pidFile], { timeoutMs: 20_000 }) - ); - // No await between settlement and the liveness probe. - const probe = probePid(readPid(pidFile)); - - expect(getErrorCode(err)).toBe('EOUTPUTLIMIT'); - expect(probe).toBe('ESRCH'); - }); - - test('EOUTPUTLIMIT settles even when a descendant still holds inherited stdout/stderr', async () => { - const childPidFile = join(workDir, 'child.pid'); - const grandchildPidFile = join(workDir, 'grandchild.pid'); - const grandchildScript = join(workDir, 'grandchild.js'); - const parentScript = join(workDir, 'parent.js'); - - // Bounded lifetime (well beyond the runner timeout) so a regression cannot - // leak the fixture process indefinitely. - await writeFile(grandchildScript, 'setTimeout(() => process.exit(0), 30_000);\n', 'utf8'); - await writeFile( - parentScript, - [ - "import { spawn } from 'node:child_process';", - "import { writeFileSync } from 'node:fs';", - 'const gc = spawn(process.execPath, [process.argv[4]], { stdio: "inherit" });', - 'writeFileSync(process.argv[2], String(process.pid), "utf8");', - 'writeFileSync(process.argv[3], String(gc.pid), "utf8");', - 'process.stderr.write("x".repeat(4096));', - 'setInterval(() => {}, 10_000);', - ].join('\n'), - 'utf8' - ); - - let grandchildPid: number | undefined; - try { - const runner = createNodeNotebookCommandRunner({ maxOutputBytes: 1024 }); - const err = await expectReject( - runner.run( - process.execPath, - [parentScript, childPidFile, grandchildPidFile, grandchildScript], - // Far below the grandchild's 30s lifetime: if the runner waited on - // the inherited pipe it would report ETIMEDOUT instead. - { timeoutMs: 15_000 } - ) - ); - const childProbe = probePid(readPid(childPidFile)); - grandchildPid = readPid(grandchildPidFile); - const grandchildProbe = probePid(grandchildPid); - - expect(getErrorCode(err)).toBe('EOUTPUTLIMIT'); - expect(childProbe).toBe('ESRCH'); - expect(grandchildProbe).toBeUndefined(); - } finally { - try { - grandchildPid ??= readPid(grandchildPidFile); - process.kill(grandchildPid, 'SIGKILL'); - } catch { - // Never started or already exited. - } - } - }); - }); - - describe('runner: timer cleanup', () => { - // A timer left armed after settlement keeps the host event loop alive. Run - // the adapter inside a wrapper process with a 2-minute runner timeout; the - // wrapper must exit on its own long before the outer 10s guard kills it. - for (const scenario of ['success', 'nonzero', 'enoent', 'signal'] as const) { - test(`clears the timeout timer after ${scenario} so the host process can exit`, async () => { - const fastChild = join(workDir, 'fast-child.js'); - await writeFile( - fastChild, - [ - 'const mode = process.argv[2];', - 'if (mode === "nonzero") process.exit(3);', - 'if (mode === "signal") process.kill(process.pid, "SIGKILL");', - 'process.stdout.write("ok");', - ].join('\n'), - 'utf8' - ); - const wrapper = join(workDir, 'wrapper.ts'); - await writeFile( - wrapper, - [ - `import { createNodeNotebookCommandRunner } from ${JSON.stringify(ADAPTER_MODULE_PATH)};`, - 'const [childScript, mode, missing] = process.argv.slice(2);', - 'const runner = createNodeNotebookCommandRunner();', - 'const command = mode === "enoent" ? missing : process.execPath;', - 'try {', - ' const r = await runner.run(command, [childScript, mode], { timeoutMs: 120_000 });', - ' process.stdout.write(JSON.stringify({ resolved: r.exitCode }));', - '} catch (err) {', - ' process.stdout.write(JSON.stringify({ rejected: err.code ?? err.message }));', - '}', - ].join('\n'), - 'utf8' - ); - - const outer = createNodeNotebookCommandRunner(); - const result = await outer.run( - process.execPath, - [wrapper, fastChild, scenario, join(workDir, 'missing-binary')], - { timeoutMs: 10_000 } - ); - - expect(result.exitCode).toBe(0); - const outcome = JSON.parse(result.stdout) as { resolved?: number; rejected?: string }; - if (scenario === 'success') { - expect(outcome).toEqual({ resolved: 0 }); - } - if (scenario === 'nonzero') { - expect(outcome).toEqual({ resolved: 3 }); - } - if (scenario === 'enoent') { - expect(outcome).toEqual({ rejected: 'ENOENT' }); - } - if (scenario === 'signal') { - expect(outcome.rejected).toContain('SIGKILL'); - } - }, 30_000); - } - }); - - describe('runner: process isolation and error surface', () => { - test('child stdin is closed (ignored), so a stdin reader sees EOF instead of hanging', async () => { - const scriptPath = join(workDir, 'read-stdin.js'); - await writeFile( - scriptPath, - [ - 'let n = 0;', - 'process.stdin.on("data", c => { n += c.length; });', - 'process.stdin.on("end", () => process.stdout.write(String(n)));', - 'process.stdin.resume();', - ].join('\n'), - 'utf8' - ); - - const runner = createNodeNotebookCommandRunner(); - const result = await runner.run(process.execPath, [scriptPath], { timeoutMs: 10_000 }); - - expect(result.exitCode).toBe(0); - expect(result.stdout).toBe('0'); - }); - - test('preserves EACCES for a non-executable file and for a directory used as command', async () => { - const notExecutable = join(workDir, 'plain.txt'); - await writeFile(notExecutable, 'not a program\n', 'utf8'); - await chmod(notExecutable, 0o644); - const runner = createNodeNotebookCommandRunner(); - - const fileErr = await expectReject(runner.run(notExecutable, [], { timeoutMs: 10_000 })); - const dirErr = await expectReject(runner.run(workDir, [], { timeoutMs: 10_000 })); - - expect(getErrorCode(fileErr)).toBe('EACCES'); - expect(getErrorCode(dirErr)).toBe('EACCES'); - }); - - test('argv containing a NUL byte rejects asynchronously instead of throwing from run()', async () => { - const runner = createNodeNotebookCommandRunner(); - let returned: Promise | undefined; - expect(() => { - returned = runner.run(process.execPath, ['a\0b'], { timeoutMs: 10_000 }); - }).not.toThrow(); - - const err = await expectReject(returned as Promise); - expect(err).toBeInstanceOf(Error); - }); - - test('ETIMEDOUT and EOUTPUTLIMIT messages name only the command basename, not path, argv or output', async () => { - const secretArg = 'QA_SECRET_ARG_51f0c2'; - const secretOutput = 'QA_SECRET_OUTPUT_9a7d'; - const shimPath = join(workDir, 'leaky-tool'); - await writeFile( - shimPath, - [ - '#!/usr/bin/env bun', - 'const mode = process.argv[2];', - `process.stdout.write(${JSON.stringify(secretOutput)});`, - 'if (mode === "flood") process.stdout.write("y".repeat(4096));', - 'setInterval(() => {}, 10_000);', - ].join('\n'), - 'utf8' - ); - await chmod(shimPath, 0o755); - const runner = createNodeNotebookCommandRunner({ maxOutputBytes: 1024 }); - - const timeoutErr = await expectReject( - runner.run(shimPath, ['sleep', secretArg], { timeoutMs: 800 }) - ); - const overflowErr = await expectReject( - runner.run(shimPath, ['flood', secretArg], { timeoutMs: 15_000 }) - ); - - expect(getErrorCode(timeoutErr)).toBe('ETIMEDOUT'); - expect(getErrorCode(overflowErr)).toBe('EOUTPUTLIMIT'); - for (const err of [timeoutErr, overflowErr]) { - const message = (err as Error).message; - expect(message).toContain('leaky-tool'); - expect(message).not.toContain(workDir); - expect(message).not.toContain(secretArg); - expect(message).not.toContain(secretOutput); - } - }); - - test('one runner instance handles concurrent runs without mixing streams or exit codes', async () => { - const scriptPath = join(workDir, 'tagged.js'); - await writeFile( - scriptPath, - [ - 'const tag = process.argv[2];', - 'process.stdout.write("out-" + tag);', - 'process.stderr.write("err-" + tag);', - 'process.exit(Number(tag));', - ].join('\n'), - 'utf8' - ); - const runner = createNodeNotebookCommandRunner(); - const tags = [0, 1, 2, 3, 4, 5, 6, 7]; - - const results = await Promise.all( - tags.map(tag => - runner.run(process.execPath, [scriptPath, String(tag)], { timeoutMs: 15_000 }) - ) - ); - - expect(results).toEqual( - tags.map(tag => ({ exitCode: tag, stdout: `out-${tag}`, stderr: `err-${tag}` })) - ); - }); - }); - - describe('fs: failure propagation and symlink safety', () => { - test('createExclusive refuses to follow a planted (dangling) symlink and never creates its target', async () => { - const fs = createNodeNotebookSnapshotFs(); - const victim = join(workDir, 'victim.html'); - const link = join(workDir, '.marimo-snapshot-planted.tmp.html'); - await symlink(victim, link); - - const err = await expectReject(fs.createExclusive(link)); - - expect(getErrorCode(err)).toBe('EEXIST'); - expect(await fs.stat(victim)).toBeNull(); - }); - - test('remove on a symlink deletes the link only and leaves the target intact', async () => { - const fs = createNodeNotebookSnapshotFs(); - const target = join(workDir, 'target.html'); - const link = join(workDir, 'link.html'); - await writeFile(target, 'keep me', 'utf8'); - await symlink(target, link); - - await fs.remove(link); - - expect(await readdir(workDir)).toEqual(['target.html']); - expect(await readFile(target, 'utf8')).toBe('keep me'); - }); - - test('missing parents/sources propagate ENOENT from createExclusive, readBytes and rename', async () => { - const fs = createNodeNotebookSnapshotFs(); - const missingDir = join(workDir, 'no-such-dir'); - - const createErr = await expectReject(fs.createExclusive(join(missingDir, 'x.tmp'))); - const readErr = await expectReject(fs.readBytes(join(workDir, 'absent.bin'))); - const renameErr = await expectReject( - fs.rename(join(workDir, 'absent.bin'), join(workDir, 'dst.bin')) - ); - - expect(getErrorCode(createErr)).toBe('ENOENT'); - expect(getErrorCode(readErr)).toBe('ENOENT'); - expect(getErrorCode(renameErr)).toBe('ENOENT'); - expect(await readdir(workDir)).toEqual([]); - }); - - test('readBytes of an empty file returns a zero-length Uint8Array', async () => { - const fs = createNodeNotebookSnapshotFs(); - const target = join(workDir, 'empty.html'); - await writeFile(target, ''); - - const bytes = await fs.readBytes(target); - - expect(bytes).toBeInstanceOf(Uint8Array); - expect(bytes.byteLength).toBe(0); - }); - }); - - describe('exporter failure paths with real adapters keep the published snapshot intact', () => { - const PREVIOUS_SNAPSHOT = 'previous published snapshot\n'; - - async function writeShim(mode: 'export_nonzero' | 'export_empty' | 'export_flood') { - const shimPath = join(workDir, `fake-marimo-${mode}`); - const script = [ - '#!/usr/bin/env bun', - "import { writeFileSync } from 'node:fs';", - 'const args = process.argv.slice(2);', - `const mode = ${JSON.stringify(mode)};`, - 'if (args[0] === "check") {', - ' process.stdout.write(JSON.stringify({ issues: [], summary: { errored: false, total_files: 1 } }) + "\\n");', - ' process.exit(0);', - '}', - 'const outPath = args[4];', - 'if (mode === "export_nonzero") {', - ' writeFileSync(outPath, "half-written", "utf8");', - ' process.stderr.write("NameError in cell 3");', - ' process.exit(1);', - '}', - 'if (mode === "export_empty") process.exit(0);', - 'writeFileSync(outPath, "partial", "utf8");', - 'const chunk = Buffer.alloc(4096, 0x7a);', - 'function pump() { while (process.stdout.write(chunk)) {} process.stdout.once("drain", pump); }', - 'pump();', - ].join('\n'); - await writeFile(shimPath, `${script}\n`, 'utf8'); - await chmod(shimPath, 0o755); - return shimPath; - } - - async function runExport( - mode: 'export_nonzero' | 'export_empty' | 'export_flood' - ): Promise<{ err: unknown; outputDir: string; outputPath: string }> { - const notebookDir = join(workDir, 'notebooks'); - const outputDir = join(workDir, 'out'); - await mkdir(notebookDir); - await mkdir(outputDir); - const notebookPath = join(notebookDir, 'study.py'); - const outputPath = join(outputDir, 'study.html'); - await writeFile(notebookPath, '# fixture\n', 'utf8'); - await writeFile(outputPath, PREVIOUS_SNAPSHOT, 'utf8'); - const shimPath = await writeShim(mode); - - const err = await expectReject( - exportNotebookSnapshot({ - notebookPath, - outputPath, - runner: createNodeNotebookCommandRunner({ maxOutputBytes: 64 * 1024 }), - fs: createNodeNotebookSnapshotFs(), - marimoCommand: shimPath, - timeoutMs: 15_000, - }) - ); - return { err, outputDir, outputPath }; - } - - test('nonzero export exit → EXPORT_FAILED, half-written temp removed, previous snapshot untouched', async () => { - const { err, outputDir, outputPath } = await runExport('export_nonzero'); - - expect(err).toBeInstanceOf(NotebookSnapshotError); - expect((err as NotebookSnapshotError).code).toBe('EXPORT_FAILED'); - expect(await readdir(outputDir)).toEqual(['study.html']); - expect(await readFile(outputPath, 'utf8')).toBe(PREVIOUS_SNAPSHOT); - }); - - test('export exits 0 without writing → EXPORT_EMPTY, reserved temp removed, previous snapshot untouched', async () => { - const { err, outputDir, outputPath } = await runExport('export_empty'); - - expect(err).toBeInstanceOf(NotebookSnapshotError); - expect((err as NotebookSnapshotError).code).toBe('EXPORT_EMPTY'); - expect(await readdir(outputDir)).toEqual(['study.html']); - expect(await readFile(outputPath, 'utf8')).toBe(PREVIOUS_SNAPSHOT); - }); - - test('export output flood → EXPORT_FAILED via EOUTPUTLIMIT, temp removed, previous snapshot untouched', async () => { - const { err, outputDir, outputPath } = await runExport('export_flood'); - - expect(err).toBeInstanceOf(NotebookSnapshotError); - expect((err as NotebookSnapshotError).code).toBe('EXPORT_FAILED'); - expect(getErrorCode((err as Error).cause)).toBe('EOUTPUTLIMIT'); - expect(await readdir(outputDir)).toEqual(['study.html']); - expect(await readFile(outputPath, 'utf8')).toBe(PREVIOUS_SNAPSHOT); - }); - }); - - describe('packaging', () => { - test('root entrypoint does not reference the node adapter module', async () => { - const indexSource = await readFile(resolve(import.meta.dir, '../src/index.ts'), 'utf8'); - const pkg = JSON.parse( - await readFile(resolve(import.meta.dir, '../package.json'), 'utf8') - ) as { exports: Record }; - - expect(indexSource).not.toContain('notebook-snapshot-node'); - expect(pkg.exports['./notebook-snapshot-node']).toBe('./src/notebook-snapshot-node.ts'); - }); - - test('browser bundle of the root entrypoint contains no adapter code or child_process', () => { - const entry = resolve(import.meta.dir, '../src/index.ts'); - // Run Bun.build in a subprocess so Bun's in-process build/fd cache stays - // isolated from other bundling tests in the full workspace suite. - const child = Bun.spawnSync( - [ - process.execPath, - '--no-env-file', - '-e', - ` - const result = await Bun.build({ - entrypoints: [${JSON.stringify(entry)}], - target: 'browser', - }); - if (!result.success) { - console.error(result.logs); - process.exit(1); - } - const code = (await Promise.all(result.outputs.map(o => o.text()))).join('\\n'); - for (const forbidden of [ - 'createNodeNotebookCommandRunner', - 'createNodeNotebookSnapshotFs', - 'child_process', - ]) { - if (code.includes(forbidden)) { - console.error('Found forbidden symbol in browser bundle:', forbidden); - process.exit(2); - } - } - `, - ], - { env: { PATH: process.env.PATH } } - ); - - expect(new TextDecoder().decode(child.stderr)).toBe(''); - expect(child.exitCode).toBe(0); - }); - }); -}); diff --git a/libs/research/test/notebook-snapshot-node.test.ts b/libs/research/test/notebook-snapshot-node.test.ts deleted file mode 100644 index 32c32c5d..00000000 --- a/libs/research/test/notebook-snapshot-node.test.ts +++ /dev/null @@ -1,676 +0,0 @@ -import { createHash } from 'node:crypto'; -import { readFileSync } from 'node:fs'; -import { - chmod, - mkdir, - mkdtemp, - readdir, - readFile, - realpath, - rm, - writeFile, -} from 'node:fs/promises'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; -import { - createNodeNotebookCommandRunner, - createNodeNotebookSnapshotFs, - NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES, -} from '@stock-bot/research/notebook-snapshot-node'; -import { exportNotebookSnapshot, NotebookSnapshotError } from '../src/notebook-snapshot'; - -function getErrorCode(err: unknown): string | undefined { - if (typeof err === 'object' && err !== null && 'code' in err) { - const code = (err as { code?: unknown }).code; - if (typeof code === 'string') { - return code; - } - } - return undefined; -} - -async function expectReject(promise: Promise): Promise { - try { - await promise; - } catch (err) { - return err; - } - throw new Error('Expected promise to reject, but it resolved.'); -} - -describe('notebook-snapshot-node adapters', () => { - let workDir = ''; - - beforeEach(async () => { - const rawDir = await mkdtemp(join(tmpdir(), 'notebook-snapshot-node-')); - workDir = await realpath(rawDir); - }); - - afterEach(async () => { - if (workDir) { - await rm(workDir, { recursive: true, force: true }); - workDir = ''; - } - }); - - describe('createNodeNotebookCommandRunner', () => { - test('passes argv verbatim without shell interpretation (spaces, quotes, $(...), ;, *)', async () => { - const scriptPath = join(workDir, 'echo-argv.js'); - await writeFile( - scriptPath, - 'process.stdout.write(JSON.stringify(process.argv.slice(2)));\n', - 'utf8' - ); - - const runner = createNodeNotebookCommandRunner(); - const args = [ - scriptPath, - 'hello world', - `"double" and 'single' quotes`, - '$(echo pwned)', - 'a;b', - '*.ts', - ]; - const result = await runner.run(process.execPath, args, { timeoutMs: 10_000 }); - - expect(result.exitCode).toBe(0); - expect(result.stderr).toBe(''); - expect(JSON.parse(result.stdout)).toEqual(args.slice(1)); - }); - - test('honours cwd, separates stdout/stderr with split multi-byte UTF-8, and resolves non-zero exit codes', async () => { - const subDir = join(workDir, 'child-cwd'); - await mkdir(subDir); - - const scriptPath = join(workDir, 'streams-and-exit.js'); - await writeFile( - scriptPath, - [ - // Split a 3-byte UTF-8 character ('€' = E2 82 AC) and a 4-byte emoji ('🚀' = F0 9F 9A 80) across writes. - 'process.stdout.write(Buffer.from([0x63, 0x77, 0x64, 0x3d]));', - 'process.stdout.write(process.cwd() + "\\n");', - 'process.stdout.write(Buffer.from([0xe2, 0x82]));', - 'process.stdout.write(Buffer.from([0xac, 0x0a]));', - 'process.stderr.write(Buffer.from([0xf0, 0x9f]));', - 'process.stderr.write(Buffer.from([0x9a, 0x80]));', - 'process.exit(42);', - ].join('\n'), - 'utf8' - ); - - const runner = createNodeNotebookCommandRunner(); - const result = await runner.run(process.execPath, [scriptPath], { - cwd: subDir, - timeoutMs: 10_000, - }); - - expect(result.exitCode).toBe(42); - expect(result.stdout).toBe(`cwd=${subDir}\n€\n`); - expect(result.stderr).toBe('🚀'); - }); - - test('rejects with ENOENT when executable does not exist', async () => { - const runner = createNodeNotebookCommandRunner(); - const missingPath = join(workDir, 'does-not-exist-binary'); - - const err = await expectReject(runner.run(missingPath, ['--version'], { timeoutMs: 10_000 })); - expect(err).toBeInstanceOf(Error); - expect(getErrorCode(err)).toBe('ENOENT'); - }); - - test('rejects signal exit with only command basename (no full path, argv, or env values)', async () => { - const secretArg = 'SECRET_ARG_TOKEN_987654'; - const shimPath = join(workDir, 'signal-self.js'); - await writeFile( - shimPath, - [ - '#!/usr/bin/env bun', - "process.kill(process.pid, 'SIGKILL');", - 'setInterval(() => {}, 10_000);', - ].join('\n'), - 'utf8' - ); - await chmod(shimPath, 0o755); - - const runner = createNodeNotebookCommandRunner(); - const err = await expectReject(runner.run(shimPath, [secretArg], { timeoutMs: 10_000 })); - - expect(err).toBeInstanceOf(Error); - const message = (err as Error).message; - expect(message).toContain('signal-self.js'); - expect(message).toContain('SIGKILL'); - expect(message).not.toContain(workDir); - expect(message).not.toContain(secretArg); - expect(message).not.toContain(process.env.PATH ?? '__no_path__'); - }); - - test('kills timed-out child with SIGKILL and rejects ETIMEDOUT only after child is dead (ESRCH)', async () => { - const pidFile = join(workDir, 'sleeper.pid'); - const scriptPath = join(workDir, 'sleep-forever.js'); - await writeFile( - scriptPath, - [ - "import { writeFileSync } from 'node:fs';", - 'writeFileSync(process.argv[2], String(process.pid), "utf8");', - 'setInterval(() => {}, 10_000);', - ].join('\n'), - 'utf8' - ); - - const runner = createNodeNotebookCommandRunner(); - const err = await expectReject( - runner.run(process.execPath, [scriptPath, pidFile], { timeoutMs: 800 }) - ); - - // Read the PID synchronously with no intervening await so the liveness - // probe checks the process state immediately upon settlement. - const pidText = readFileSync(pidFile, 'utf8'); - const pid = Number.parseInt(pidText.trim(), 10); - let probeError: unknown; - try { - process.kill(pid, 0); - } catch (killErr) { - probeError = killErr; - } - - expect(err).toBeInstanceOf(Error); - expect(getErrorCode(err)).toBe('ETIMEDOUT'); - expect(Number.isInteger(pid) && pid > 0).toBe(true); - expect(getErrorCode(probeError)).toBe('ESRCH'); - }); - - test('settles ETIMEDOUT after direct child dies even when a descendant inherits stdout/stderr', async () => { - const childPidFile = join(workDir, 'parent.pid'); - const grandchildPidFile = join(workDir, 'grandchild.pid'); - const grandchildScript = join(workDir, 'grandchild-sleeper.js'); - const parentScript = join(workDir, 'spawn-grandchild.js'); - - // Bounded lifetime well beyond the runner's 800ms deadline so a regression - // cannot leak the fixture process indefinitely. - await writeFile(grandchildScript, 'setTimeout(() => process.exit(0), 30_000);\n', 'utf8'); - await writeFile( - parentScript, - [ - "import { spawn } from 'node:child_process';", - "import { writeFileSync } from 'node:fs';", - 'const grandchild = spawn(process.execPath, [process.argv[4]], { stdio: "inherit" });', - 'writeFileSync(process.argv[2], String(process.pid), "utf8");', - 'writeFileSync(process.argv[3], String(grandchild.pid), "utf8");', - 'setInterval(() => {}, 10_000);', - ].join('\n'), - 'utf8' - ); - - let grandchildPid: number | undefined; - try { - const runner = createNodeNotebookCommandRunner(); - const err = await expectReject( - runner.run( - process.execPath, - [parentScript, childPidFile, grandchildPidFile, grandchildScript], - { timeoutMs: 800 } - ) - ); - - const childPid = Number.parseInt(readFileSync(childPidFile, 'utf8').trim(), 10); - grandchildPid = Number.parseInt(readFileSync(grandchildPidFile, 'utf8').trim(), 10); - - let childProbeError: unknown; - try { - process.kill(childPid, 0); - } catch (killErr) { - childProbeError = killErr; - } - - // Grandchild still holds the inherited stdout/stderr pipes open while alive. - let grandchildAlive = true; - try { - process.kill(grandchildPid, 0); - } catch { - grandchildAlive = false; - } - - expect(err).toBeInstanceOf(Error); - expect(getErrorCode(err)).toBe('ETIMEDOUT'); - expect(Number.isInteger(childPid) && childPid > 0).toBe(true); - expect(Number.isInteger(grandchildPid) && grandchildPid > 0).toBe(true); - expect(getErrorCode(childProbeError)).toBe('ESRCH'); - expect(grandchildAlive).toBe(true); - } finally { - if (grandchildPid === undefined) { - try { - grandchildPid = Number.parseInt(readFileSync(grandchildPidFile, 'utf8').trim(), 10); - } catch { - // Grandchild never wrote its PID file. - } - } - if (grandchildPid !== undefined && Number.isInteger(grandchildPid) && grandchildPid > 0) { - try { - process.kill(grandchildPid, 'SIGKILL'); - } catch { - // Already exited. - } - } - } - }); - - test('handles timeoutMs beyond 32-bit setTimeout limit without firing immediately', async () => { - const scriptPath = join(workDir, 'fast-ok.js'); - await writeFile(scriptPath, 'process.stdout.write("ok");\n', 'utf8'); - - const runner = createNodeNotebookCommandRunner(); - const result = await runner.run(process.execPath, [scriptPath], { - timeoutMs: 3_000_000_000, - }); - - expect(result.exitCode).toBe(0); - expect(result.stdout).toBe('ok'); - expect(result.stderr).toBe(''); - }); - - test('enforces NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES independently on stdout and stderr', async () => { - const scriptPath = join(workDir, 'emit-bytes.js'); - await writeFile( - scriptPath, - [ - 'const streamName = process.argv[2];', - 'const totalBytes = Number.parseInt(process.argv[3], 10);', - 'const chunkSize = 65536;', - 'const chunk = Buffer.alloc(chunkSize, 0x61);', - 'const target = streamName === "stderr" ? process.stderr : process.stdout;', - 'let remaining = totalBytes;', - 'function pump() {', - ' while (remaining > 0) {', - ' const size = Math.min(remaining, chunkSize);', - ' remaining -= size;', - ' const ok = target.write(size === chunkSize ? chunk : chunk.subarray(0, size));', - ' if (!ok) {', - ' target.once("drain", pump);', - ' return;', - ' }', - ' }', - '}', - 'pump();', - ].join('\n'), - 'utf8' - ); - - const runner = createNodeNotebookCommandRunner(); - - // Exact cap on stdout succeeds. - const stdoutExact = await runner.run( - process.execPath, - [scriptPath, 'stdout', String(NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES)], - { timeoutMs: 30_000 } - ); - expect(stdoutExact.exitCode).toBe(0); - expect(stdoutExact.stdout.length).toBe(NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES); - expect(stdoutExact.stderr).toBe(''); - - // One byte over cap on stdout rejects with EOUTPUTLIMIT. - const stdoutOverflow = await expectReject( - runner.run( - process.execPath, - [scriptPath, 'stdout', String(NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES + 1)], - { timeoutMs: 30_000 } - ) - ); - expect(getErrorCode(stdoutOverflow)).toBe('EOUTPUTLIMIT'); - - // Exact cap on stderr succeeds. - const stderrExact = await runner.run( - process.execPath, - [scriptPath, 'stderr', String(NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES)], - { timeoutMs: 30_000 } - ); - expect(stderrExact.exitCode).toBe(0); - expect(stderrExact.stdout).toBe(''); - expect(stderrExact.stderr.length).toBe(NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES); - - // One byte over cap on stderr rejects with EOUTPUTLIMIT. - const stderrOverflow = await expectReject( - runner.run( - process.execPath, - [scriptPath, 'stderr', String(NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES + 1)], - { timeoutMs: 30_000 } - ) - ); - expect(getErrorCode(stderrOverflow)).toBe('EOUTPUTLIMIT'); - }); - - test('supports custom per-stream maxOutputBytes without sharing cap across streams', async () => { - const scriptPath = join(workDir, 'both-streams.js'); - await writeFile( - scriptPath, - [ - 'const n = Number.parseInt(process.argv[2], 10);', - 'process.stdout.write("a".repeat(n));', - 'process.stderr.write("b".repeat(n));', - ].join('\n'), - 'utf8' - ); - - const runner = createNodeNotebookCommandRunner({ maxOutputBytes: 128 }); - - const exactBoth = await runner.run(process.execPath, [scriptPath, '128'], { - timeoutMs: 10_000, - }); - expect(exactBoth.exitCode).toBe(0); - expect(exactBoth.stdout.length).toBe(128); - expect(exactBoth.stderr.length).toBe(128); - - const overCap = await expectReject( - runner.run(process.execPath, [scriptPath, '129'], { timeoutMs: 10_000 }) - ); - expect(getErrorCode(overCap)).toBe('EOUTPUTLIMIT'); - }); - - test('rejects invalid timeoutMs with RangeError before spawning and invalid maxOutputBytes on construction', async () => { - const runner = createNodeNotebookCommandRunner(); - const invalidTimeouts = [ - 0, - -1, - Number.NaN, - Number.POSITIVE_INFINITY, - Number.NEGATIVE_INFINITY, - 1.5, - ]; - - for (const timeoutMs of invalidTimeouts) { - const err = await expectReject( - runner.run(join(workDir, 'never-spawned'), [], { timeoutMs }) - ); - expect(err).toBeInstanceOf(RangeError); - } - - expect(() => createNodeNotebookCommandRunner({ maxOutputBytes: 0 })).toThrow(RangeError); - expect(() => createNodeNotebookCommandRunner({ maxOutputBytes: -5 })).toThrow(RangeError); - expect(() => createNodeNotebookCommandRunner({ maxOutputBytes: 1.5 })).toThrow(RangeError); - }); - }); - - describe('createNodeNotebookSnapshotFs', () => { - test('stat returns null for missing, { isFile, size } for file/dir, and propagates ENOTDIR', async () => { - const fs = createNodeNotebookSnapshotFs(); - const missingPath = join(workDir, 'missing.txt'); - const filePath = join(workDir, 'sample.bin'); - const dirPath = join(workDir, 'nested-dir'); - - await writeFile(filePath, new Uint8Array([1, 2, 3, 4, 5])); - await mkdir(dirPath); - - expect(await fs.stat(missingPath)).toBeNull(); - expect(await fs.stat(filePath)).toEqual({ isFile: true, size: 5 }); - - const dirStat = await fs.stat(dirPath); - expect(dirStat).not.toBeNull(); - expect(dirStat?.isFile).toBe(false); - - const enotdirErr = await expectReject(fs.stat(join(filePath, 'child'))); - expect(getErrorCode(enotdirErr)).toBe('ENOTDIR'); - }); - - test('createExclusive creates an empty file and rejects EEXIST on collision', async () => { - const fs = createNodeNotebookSnapshotFs(); - const target = join(workDir, 'exclusive.tmp'); - - await fs.createExclusive(target); - expect(await fs.stat(target)).toEqual({ isFile: true, size: 0 }); - - const err = await expectReject(fs.createExclusive(target)); - expect(getErrorCode(err)).toBe('EEXIST'); - }); - - test('readBytes round-trips arbitrary binary bytes including 0x00 and 0xff', async () => { - const fs = createNodeNotebookSnapshotFs(); - const target = join(workDir, 'binary.dat'); - const payload = new Uint8Array([0x00, 0x01, 0x7f, 0x80, 0xfe, 0xff, 0x00, 0x42]); - await writeFile(target, payload); - - const actual = await fs.readBytes(target); - expect(actual).toBeInstanceOf(Uint8Array); - expect(Array.from(actual)).toEqual(Array.from(payload)); - }); - - test('rename atomically replaces an existing destination file', async () => { - const fs = createNodeNotebookSnapshotFs(); - const src = join(workDir, 'new.html'); - const dst = join(workDir, 'published.html'); - - await writeFile(dst, 'old content', 'utf8'); - await writeFile(src, 'new content', 'utf8'); - - await fs.rename(src, dst); - - expect(await fs.stat(src)).toBeNull(); - expect(await readFile(dst, 'utf8')).toBe('new content'); - }); - - test('remove is a no-op when absent and rejects non-recursively on a non-empty directory', async () => { - const fs = createNodeNotebookSnapshotFs(); - - await fs.remove(join(workDir, 'absent.tmp')); - - const regularFile = join(workDir, 'deletable.tmp'); - await writeFile(regularFile, 'bye', 'utf8'); - await fs.remove(regularFile); - expect(await fs.stat(regularFile)).toBeNull(); - - const nonEmptyDir = join(workDir, 'keep-dir'); - const innerFile = join(nonEmptyDir, 'inside.txt'); - await mkdir(nonEmptyDir); - await writeFile(innerFile, 'precious', 'utf8'); - - const err = await expectReject(fs.remove(nonEmptyDir)); - expect(err).toBeInstanceOf(Error); - expect(await readFile(innerFile, 'utf8')).toBe('precious'); - }); - }); - - describe('end-to-end exportNotebookSnapshot with real adapters and fake marimo shim', () => { - async function writeFakeMarimoShim( - name: string, - mode: 'clean' | 'check_error' | 'hang_export', - logPath: string, - extra?: { readonly htmlContent?: string; readonly pidPath?: string } - ): Promise { - const shimPath = join(workDir, name); - const htmlContent = extra?.htmlContent ?? 'OK\n'; - const pidPath = extra?.pidPath ?? ''; - - const script = [ - '#!/usr/bin/env bun', - "import { appendFileSync, writeFileSync } from 'node:fs';", - 'const args = process.argv.slice(2);', - `const mode = ${JSON.stringify(mode)};`, - `const logPath = ${JSON.stringify(logPath)};`, - `const htmlContent = ${JSON.stringify(htmlContent)};`, - `const pidPath = ${JSON.stringify(pidPath)};`, - 'appendFileSync(logPath, JSON.stringify({ args, pid: process.pid }) + "\\n", "utf8");', - 'if (args[0] === "check") {', - ' if (args[1] !== "--format=json" || args.length !== 3) {', - ' process.stderr.write("unexpected check argv: " + JSON.stringify(args));', - ' process.exit(2);', - ' }', - ' if (mode === "check_error") {', - ' process.stdout.write(JSON.stringify({', - ' issues: [{ type: "error", severity: "breaking", message: "undefined name" }],', - ' summary: { errored: true, total_files: 1 },', - ' }));', - ' process.exit(0);', - ' }', - ' process.stdout.write(JSON.stringify({', - ' issues: [],', - ' summary: { errored: false, total_files: 1 },', - ' }));', - ' process.exit(0);', - '}', - 'if (args[0] === "export" && args[1] === "html") {', - ' if (args.length !== 6 || args[3] !== "-o" || args[5] !== "--force") {', - ' process.stderr.write("unexpected export argv: " + JSON.stringify(args));', - ' process.exit(2);', - ' }', - ' const outPath = args[4];', - ' if (mode === "hang_export") {', - ' writeFileSync(outPath, "partial", "utf8");', - ' if (pidPath) writeFileSync(pidPath, String(process.pid), "utf8");', - ' setInterval(() => {}, 10_000);', - ' } else {', - ' writeFileSync(outPath, htmlContent, "utf8");', - ' process.exit(0);', - ' }', - '} else {', - ' process.stderr.write("unknown command: " + JSON.stringify(args));', - ' process.exit(2);', - '}', - ].join('\n'); - - await writeFile(shimPath, `${script}\n`, 'utf8'); - await chmod(shimPath, 0o755); - return shimPath; - } - - test('clean check publishes HTML whose bytes and sha256 match the receipt with no leftover temp files', async () => { - const notebookDir = join(workDir, 'notebooks'); - const outputDir = join(workDir, 'out'); - await mkdir(notebookDir); - await mkdir(outputDir); - - const notebookPath = join(notebookDir, 'study.py'); - const outputPath = join(outputDir, 'study.html'); - const logPath = join(workDir, 'clean.log.jsonl'); - const expectedHtml = '

CA Shorts Study €

\n'; - const expectedBytes = Buffer.from(expectedHtml, 'utf8'); - const expectedSha256 = createHash('sha256').update(expectedBytes).digest('hex'); - - await writeFile(notebookPath, '# marimo notebook fixture\n', 'utf8'); - const shimPath = await writeFakeMarimoShim('fake-marimo-clean', 'clean', logPath, { - htmlContent: expectedHtml, - }); - - const receipt = await exportNotebookSnapshot({ - notebookPath, - outputPath, - runner: createNodeNotebookCommandRunner(), - fs: createNodeNotebookSnapshotFs(), - marimoCommand: shimPath, - timeoutMs: 10_000, - allowedNotebookRoot: notebookDir, - allowedOutputRoot: outputDir, - }); - - expect(receipt.notebookPath).toBe(notebookPath); - expect(receipt.outputPath).toBe(outputPath); - expect(receipt.bytes).toBe(expectedBytes.byteLength); - expect(receipt.sha256).toBe(expectedSha256); - expect(receipt.checkDiagnostics).toEqual({ - issues: [], - summary: { errored: false, total_files: 1 }, - }); - - const published = await readFile(outputPath); - expect(published.byteLength).toBe(receipt.bytes); - expect(createHash('sha256').update(published).digest('hex')).toBe(receipt.sha256); - expect(await readdir(outputDir)).toEqual(['study.html']); - - const invocations = (await readFile(logPath, 'utf8')) - .trim() - .split('\n') - .map(line => JSON.parse(line) as { args: string[] }); - expect(invocations).toHaveLength(2); - expect(invocations[0]?.args).toEqual(['check', '--format=json', notebookPath]); - expect(invocations[1]?.args[0]).toBe('export'); - expect(invocations[1]?.args[1]).toBe('html'); - expect(invocations[1]?.args[2]).toBe(notebookPath); - expect(invocations[1]?.args[3]).toBe('-o'); - expect(invocations[1]?.args[5]).toBe('--force'); - }); - - test('blocking check report on exit 0 rejects CHECK_FAILED, skips export, and writes no output or temp files', async () => { - const notebookDir = join(workDir, 'notebooks'); - const outputDir = join(workDir, 'out'); - await mkdir(notebookDir); - await mkdir(outputDir); - - const notebookPath = join(notebookDir, 'broken.py'); - const outputPath = join(outputDir, 'broken.html'); - const logPath = join(workDir, 'check-error.log.jsonl'); - - await writeFile(notebookPath, '# broken marimo notebook fixture\n', 'utf8'); - const shimPath = await writeFakeMarimoShim('fake-marimo-check-error', 'check_error', logPath); - - const err = await expectReject( - exportNotebookSnapshot({ - notebookPath, - outputPath, - runner: createNodeNotebookCommandRunner(), - fs: createNodeNotebookSnapshotFs(), - marimoCommand: shimPath, - timeoutMs: 10_000, - }) - ); - - expect(err).toBeInstanceOf(NotebookSnapshotError); - expect((err as NotebookSnapshotError).code).toBe('CHECK_FAILED'); - expect(await readdir(outputDir)).toEqual([]); - - const invocations = (await readFile(logPath, 'utf8')) - .trim() - .split('\n') - .map(line => JSON.parse(line) as { args: string[] }); - expect(invocations).toHaveLength(1); - expect(invocations[0]?.args).toEqual(['check', '--format=json', notebookPath]); - }); - - test('hanging export rejects TIMEOUT, kills export child, and leaves no output or partial temp file', async () => { - const notebookDir = join(workDir, 'notebooks'); - const outputDir = join(workDir, 'out'); - await mkdir(notebookDir); - await mkdir(outputDir); - - const notebookPath = join(notebookDir, 'hang.py'); - const outputPath = join(outputDir, 'hang.html'); - const logPath = join(workDir, 'hang.log.jsonl'); - const pidPath = join(workDir, 'hang-export.pid'); - - await writeFile(notebookPath, '# hanging export fixture\n', 'utf8'); - const shimPath = await writeFakeMarimoShim('fake-marimo-hang', 'hang_export', logPath, { - pidPath, - }); - - const err = await expectReject( - exportNotebookSnapshot({ - notebookPath, - outputPath, - runner: createNodeNotebookCommandRunner(), - fs: createNodeNotebookSnapshotFs(), - marimoCommand: shimPath, - timeoutMs: 800, - }) - ); - - const pid = Number.parseInt(readFileSync(pidPath, 'utf8').trim(), 10); - let probeError: unknown; - try { - process.kill(pid, 0); - } catch (killErr) { - probeError = killErr; - } - - expect(err).toBeInstanceOf(NotebookSnapshotError); - expect((err as NotebookSnapshotError).code).toBe('TIMEOUT'); - expect(Number.isInteger(pid) && pid > 0).toBe(true); - expect(getErrorCode(probeError)).toBe('ESRCH'); - expect(await readdir(outputDir)).toEqual([]); - - const invocations = (await readFile(logPath, 'utf8')) - .trim() - .split('\n') - .map(line => JSON.parse(line) as { args: string[]; pid: number }); - expect(invocations).toHaveLength(2); - expect(invocations[0]?.args[0]).toBe('check'); - expect(invocations[1]?.args[0]).toBe('export'); - }); - }); -}); diff --git a/libs/research/test/notebook-snapshot-qa.test.ts b/libs/research/test/notebook-snapshot-qa.test.ts deleted file mode 100644 index e9f01e18..00000000 --- a/libs/research/test/notebook-snapshot-qa.test.ts +++ /dev/null @@ -1,615 +0,0 @@ -import { createHash } from 'node:crypto'; -import { describe, expect, test } from 'bun:test'; -import { - exportNotebookSnapshot, - NotebookSnapshotError, - type ExportNotebookSnapshotOptions, - type NotebookCommandResult, - type NotebookCommandRunner, - type NotebookSnapshotFileStat, - type NotebookSnapshotFs, -} from '../src/notebook-snapshot'; - -// QA coverage for T-177 beyond the programmer's unit tests: fail-at-call-N fault -// injection across every port call, realistic marimo 0.26.0 report payloads -// (shapes taken from marimo/_lint/formatters/json.py, _lint/linter.py and -// _cli/cli.py `check`, which echoes JSON with a trailing newline), temp-name -// collisions, path normalization, and option validation. Fakes only; no real -// marimo process is ever spawned. - -const NOTEBOOK = '/work/notebooks/study.py'; -const OUTPUT = '/work/out/study.html'; -const ORIGINAL_SNAPSHOT = 'original-snapshot'; -const NEW_SNAPSHOT = 'new-snapshot — €'; -const TEMP_MARKER = '.marimo-snapshot-'; - -type PortOp = - | 'fs.stat' - | 'fs.createExclusive' - | 'fs.readBytes' - | 'fs.rename' - | 'fs.remove' - | 'runner.check' - | 'runner.export'; - -function errWithCode(code: string, message = code): Error & { code: string } { - const err = new Error(message) as Error & { code: string }; - err.code = code; - return err; -} - -/** - * In-memory fs + runner pair sharing one ordered port-call log. `failAt` makes - * the Nth port call throw EIO; `failPersistently` makes every later call throw too. - */ -class FaultyPorts { - readonly files = new Map(); - readonly ops: PortOp[] = []; - readonly runnerArgs: string[][] = []; - failAt = 0; - failPersistently = false; - checkStdout = ''; - exportBytes: Uint8Array = new TextEncoder().encode(NEW_SNAPSHOT); - createExclusiveHook: ((path: string, attempt: number) => void) | null = null; - private createAttempts = 0; - - constructor() { - this.files.set(NOTEBOOK, { isFile: true, bytes: new TextEncoder().encode('import marimo\n') }); - this.files.set(OUTPUT, { isFile: true, bytes: new TextEncoder().encode(ORIGINAL_SNAPSHOT) }); - } - - private tick(op: PortOp): void { - this.ops.push(op); - const n = this.ops.length; - if (this.failAt > 0 && (n === this.failAt || (this.failPersistently && n > this.failAt))) { - throw errWithCode('EIO', `injected EIO at port call ${n} (${op})`); - } - } - - text(path: string): string | undefined { - const entry = this.files.get(path); - return entry ? new TextDecoder().decode(entry.bytes) : undefined; - } - - tempPaths(): string[] { - return [...this.files.keys()].filter(p => p.includes(TEMP_MARKER)); - } - - readonly fs: NotebookSnapshotFs = { - stat: async (path): Promise => { - this.tick('fs.stat'); - const entry = this.files.get(path); - return entry ? { isFile: entry.isFile, size: entry.bytes.byteLength } : null; - }, - createExclusive: async path => { - this.tick('fs.createExclusive'); - this.createAttempts += 1; - this.createExclusiveHook?.(path, this.createAttempts); - if (this.files.has(path)) { - throw errWithCode('EEXIST'); - } - this.files.set(path, { isFile: true, bytes: new Uint8Array(0) }); - }, - readBytes: async path => { - this.tick('fs.readBytes'); - const entry = this.files.get(path); - if (!entry) { - throw errWithCode('ENOENT'); - } - return new Uint8Array(entry.bytes); - }, - rename: async (from, to) => { - this.tick('fs.rename'); - const entry = this.files.get(from); - if (!entry) { - throw errWithCode('ENOENT'); - } - this.files.delete(from); - this.files.set(to, entry); - }, - remove: async path => { - this.tick('fs.remove'); - this.files.delete(path); - }, - }; - - readonly runner: NotebookCommandRunner = { - run: async (_command, args): Promise => { - this.runnerArgs.push([...args]); - if (args[0] === 'check') { - this.tick('runner.check'); - return { exitCode: 0, stdout: this.checkStdout, stderr: '' }; - } - this.tick('runner.export'); - const tempPath = args[args.indexOf('-o') + 1] as string; - this.files.set(tempPath, { isFile: true, bytes: this.exportBytes }); - return { exitCode: 0, stdout: '', stderr: '' }; - }, - }; - - options(extra: Partial = {}): ExportNotebookSnapshotOptions { - return { notebookPath: NOTEBOOK, outputPath: OUTPUT, runner: this.runner, fs: this.fs, ...extra }; - } -} - -async function captureSnapshotError(promise: Promise): Promise { - try { - await promise; - } catch (err) { - expect(err).toBeInstanceOf(NotebookSnapshotError); - return err as NotebookSnapshotError; - } - throw new Error('Expected NotebookSnapshotError, but the export resolved.'); -} - -function stubRunner(result: unknown): { runner: NotebookCommandRunner; calls: string[][] } { - const calls: string[][] = []; - return { - calls, - runner: { - run: async (_c, args) => { - calls.push([...args]); - return result as NotebookCommandResult; - }, - }, - }; -} - -// Realistic marimo 0.26.0 `check --format=json` stdout (click.echo appends '\n'). -function marimoCheckStdout( - issues: readonly Record[], - errored: boolean, - totalFiles = 1 -): string { - return `${JSON.stringify({ - issues, - summary: { - total_files: totalFiles, - files_with_issues: issues.length > 0 ? 1 : 0, - total_issues: issues.length, - fixed_issues: 0, - errored, - }, - })}\n`; -} - -describe('exportNotebookSnapshot QA: fail-at-call-N fault injection', () => { - const expectedByStep: ReadonlyArray<{ op: PortOp; code: NotebookSnapshotError['code'] }> = [ - { op: 'fs.stat', code: 'NOTEBOOK_NOT_FOUND' }, - { op: 'runner.check', code: 'CHECK_FAILED' }, - { op: 'fs.createExclusive', code: 'EXPORT_FAILED' }, - { op: 'runner.export', code: 'EXPORT_FAILED' }, - { op: 'fs.stat', code: 'EXPORT_FAILED' }, - { op: 'fs.readBytes', code: 'EXPORT_FAILED' }, - { op: 'fs.rename', code: 'EXPORT_FAILED' }, - ]; - - test('happy path issues exactly the expected ordered port calls', async () => { - const ports = new FaultyPorts(); - await exportNotebookSnapshot(ports.options()); - expect(ports.ops).toEqual(expectedByStep.map(s => s.op)); - }); - - for (const persistent of [false, true]) { - test(`failing port call N (${persistent ? 'and every later call' : 'only'}) fails closed with the mapped code, keeps the old snapshot, and a retry succeeds`, async () => { - for (let n = 1; n <= expectedByStep.length; n += 1) { - const ports = new FaultyPorts(); - ports.failAt = n; - ports.failPersistently = persistent; - - const err = await captureSnapshotError(exportNotebookSnapshot(ports.options())); - const step = expectedByStep[n - 1]!; - - expect({ n, op: ports.ops[n - 1], code: err.code }).toEqual({ n, op: step.op, code: step.code }); - expect(err.cause).toBeDefined(); - expect(ports.text(OUTPUT)).toBe(ORIGINAL_SNAPSHOT); - // Export must never run once the check phase (or anything before it) failed. - if (n <= 2) { - expect(ports.runnerArgs.filter(a => a[0] === 'export')).toHaveLength(0); - expect(ports.ops).not.toContain('fs.createExclusive'); - } - if (!persistent) { - // Cleanup succeeded: no owned temp file survives any injected fault. - expect(ports.tempPaths()).toEqual([]); - if (n >= 4) { - expect(ports.ops.at(-1)).toBe('fs.remove'); - } - } - - // Retry once the fault clears publishes the new snapshot. - ports.failAt = 0; - const receipt = await exportNotebookSnapshot(ports.options()); - expect(ports.text(OUTPUT)).toBe(NEW_SNAPSHOT); - expect(receipt.bytes).toBe(ports.exportBytes.byteLength); - if (!persistent) { - expect(ports.tempPaths()).toEqual([]); - } - } - }); - } - - test('an extra fault index past the last port call means the export succeeds (no hidden fault points)', async () => { - const ports = new FaultyPorts(); - ports.failAt = expectedByStep.length + 1; - const receipt = await exportNotebookSnapshot(ports.options()); - expect(receipt.sha256).toBe(createHash('sha256').update(ports.exportBytes).digest('hex')); - expect(ports.tempPaths()).toEqual([]); - }); -}); - -describe('exportNotebookSnapshot QA: realistic marimo 0.26.0 check reports', () => { - test('accepts the real report shape with trailing newline and formatting/runtime diagnostics', async () => { - const ports = new FaultyPorts(); - const issues = [ - { - type: 'diagnostic', - message: 'Cell is not formatted', - filename: NOTEBOOK, - line: 3, - column: 1, - severity: 'formatting', - name: 'general-formatting', - code: 'MF001', - fixable: true, - cell_id: ['Hbol'], - }, - { - type: 'diagnostic', - message: 'Self import', - filename: NOTEBOOK, - line: 7, - column: 1, - severity: 'runtime', - name: 'self-import', - code: 'MR001', - fixable: false, - }, - ]; - ports.checkStdout = marimoCheckStdout(issues, false); - - const receipt = await exportNotebookSnapshot(ports.options()); - - expect(receipt.checkDiagnostics).toEqual(JSON.parse(ports.checkStdout)); - expect(ports.text(OUTPUT)).toBe(NEW_SNAPSHOT); - }); - - test('blocks export for a file-level error issue even when exit is 0 and summary.errored is false', async () => { - // marimo marks `status == "invalid"` notebooks failed without necessarily - // setting errored first; the gate must not rely on summary.errored alone. - const ports = new FaultyPorts(); - ports.checkStdout = marimoCheckStdout( - [{ type: 'error', filename: NOTEBOOK, error: `Failed to parse: ${NOTEBOOK} (not a valid notebook)` }], - false - ); - - const err = await captureSnapshotError(exportNotebookSnapshot(ports.options())); - - expect(err.code).toBe('CHECK_FAILED'); - expect(ports.runnerArgs).toHaveLength(1); - expect(ports.ops).not.toContain('fs.createExclusive'); - expect(ports.text(OUTPUT)).toBe(ORIGINAL_SNAPSHOT); - }); - - test('blocks export for a breaking diagnostic (MB rule) on exit 0', async () => { - const ports = new FaultyPorts(); - ports.checkStdout = marimoCheckStdout( - [ - { - type: 'diagnostic', - message: "Variable 'x' is defined in multiple cells", - filename: NOTEBOOK, - line: 4, - column: 1, - severity: 'breaking', - name: 'multiple-definitions', - code: 'MB002', - fixable: false, - }, - ], - false - ); - - const err = await captureSnapshotError(exportNotebookSnapshot(ports.options())); - expect(err.code).toBe('CHECK_FAILED'); - expect(ports.runnerArgs).toHaveLength(1); - }); - - test('rejects a report that checked zero files (e.g. notebook vanished before check) as CHECK_OUTPUT_INVALID', async () => { - const ports = new FaultyPorts(); - ports.checkStdout = marimoCheckStdout([], false, 0); - const err = await captureSnapshotError(exportNotebookSnapshot(ports.options())); - expect(err.code).toBe('CHECK_OUTPUT_INVALID'); - expect(ports.runnerArgs).toHaveLength(1); - }); - - test('blocks a nested diagnostics entry with type "error"', async () => { - const ports = new FaultyPorts(); - ports.checkStdout = marimoCheckStdout( - [{ filename: NOTEBOOK, diagnostics: [{ type: 'error', message: 'boom' }] }], - false - ); - const err = await captureSnapshotError(exportNotebookSnapshot(ports.options())); - expect(err.code).toBe('CHECK_FAILED'); - expect(ports.runnerArgs).toHaveLength(1); - }); - - test('rejects non-string severity in an issue as CHECK_OUTPUT_INVALID', async () => { - const ports = new FaultyPorts(); - ports.checkStdout = marimoCheckStdout([{ type: 'diagnostic', severity: 3 }], false); - const err = await captureSnapshotError(exportNotebookSnapshot(ports.options())); - expect(err.code).toBe('CHECK_OUTPUT_INVALID'); - expect(ports.runnerArgs).toHaveLength(1); - }); - - test('receipt diagnostics are deeply frozen and detached from later mutation attempts', async () => { - const ports = new FaultyPorts(); - ports.checkStdout = marimoCheckStdout( - [{ type: 'diagnostic', severity: 'formatting', code: 'MF001', cell_id: ['a'] }], - false - ); - const receipt = await exportNotebookSnapshot(ports.options()); - const diagnostics = receipt.checkDiagnostics!; - - expect(() => { - (diagnostics.summary as { errored: boolean }).errored = true; - }).toThrow(TypeError); - expect(() => { - (diagnostics.issues as unknown[]).push({}); - }).toThrow(TypeError); - expect(() => { - (receipt as { sha256: string }).sha256 = 'x'; - }).toThrow(TypeError); - expect(diagnostics.summary.errored).toBe(false); - }); -}); - -describe('exportNotebookSnapshot QA: runner contract violations', () => { - test('non-timeout runner rejection in check maps to CHECK_FAILED with cause and never exports', async () => { - const spawnError = errWithCode('ENOENT', 'spawn marimo ENOENT'); - const calls: string[][] = []; - const ports = new FaultyPorts(); - const runner: NotebookCommandRunner = { - run: async (_c, args) => { - calls.push([...args]); - throw spawnError; - }, - }; - - const err = await captureSnapshotError(exportNotebookSnapshot(ports.options({ runner }))); - - expect(err.code).toBe('CHECK_FAILED'); - expect(err.cause).toBe(spawnError); - expect(calls).toHaveLength(1); - expect(ports.tempPaths()).toEqual([]); - }); - - test('malformed runner results in check map to CHECK_FAILED and never export', async () => { - const malformed: unknown[] = [ - null, - 'exit 0', - { exitCode: '0', stdout: '', stderr: '' }, - { exitCode: Number.NaN, stdout: '', stderr: '' }, - { exitCode: 0.5, stdout: '', stderr: '' }, - { exitCode: 0, stderr: '' }, - { exitCode: 0, stdout: '', stderr: null }, - ]; - for (const result of malformed) { - const ports = new FaultyPorts(); - const { runner, calls } = stubRunner(result); - const err = await captureSnapshotError(exportNotebookSnapshot(ports.options({ runner }))); - expect(err.code).toBe('CHECK_FAILED'); - expect(calls).toHaveLength(1); - expect(ports.tempPaths()).toEqual([]); - } - }); - - test('malformed runner result in export maps to EXPORT_FAILED, removes temp, and keeps destination', async () => { - const ports = new FaultyPorts(); - const runner: NotebookCommandRunner = { - run: async (_c, args) => - (args[0] === 'check' - ? { exitCode: 0, stdout: '', stderr: '' } - : { exitCode: 0, stdout: undefined, stderr: '' }) as unknown as NotebookCommandResult, - }; - const err = await captureSnapshotError(exportNotebookSnapshot(ports.options({ runner }))); - expect(err.code).toBe('EXPORT_FAILED'); - expect(ports.tempPaths()).toEqual([]); - expect(ports.text(OUTPUT)).toBe(ORIGINAL_SNAPSHOT); - }); - - test('readBytes returning zero bytes despite a nonzero stat size is EXPORT_EMPTY and cleans up', async () => { - const ports = new FaultyPorts(); - const fs: NotebookSnapshotFs = { ...ports.fs, readBytes: async () => new Uint8Array(0) }; - const err = await captureSnapshotError(exportNotebookSnapshot(ports.options({ fs }))); - expect(err.code).toBe('EXPORT_EMPTY'); - expect(ports.tempPaths()).toEqual([]); - expect(ports.text(OUTPUT)).toBe(ORIGINAL_SNAPSHOT); - }); - - test('temp file vanishing between stat and read (ENOENT) is EXPORT_EMPTY', async () => { - const ports = new FaultyPorts(); - const fs: NotebookSnapshotFs = { - ...ports.fs, - readBytes: async () => { - throw errWithCode('ENOENT'); - }, - }; - const err = await captureSnapshotError(exportNotebookSnapshot(ports.options({ fs }))); - expect(err.code).toBe('EXPORT_EMPTY'); - expect(ports.text(OUTPUT)).toBe(ORIGINAL_SNAPSHOT); - }); - - test('notebook stat throwing ENOENT is NOTEBOOK_NOT_FOUND with zero runner calls', async () => { - const ports = new FaultyPorts(); - const fs: NotebookSnapshotFs = { - ...ports.fs, - stat: async () => { - throw errWithCode('ENOENT'); - }, - }; - const err = await captureSnapshotError(exportNotebookSnapshot(ports.options({ fs }))); - expect(err.code).toBe('NOTEBOOK_NOT_FOUND'); - expect(ports.runnerArgs).toHaveLength(0); - }); -}); - -describe('exportNotebookSnapshot QA: temp reservation', () => { - test('retries on EEXIST collisions and exports to the first free sibling', async () => { - const ports = new FaultyPorts(); - ports.createExclusiveHook = (path, attempt) => { - if (attempt <= 3) { - ports.files.set(path, { isFile: true, bytes: new TextEncoder().encode('foreign') }); - } - }; - - await exportNotebookSnapshot(ports.options()); - - const exportArgs = ports.runnerArgs.find(a => a[0] === 'export')!; - const usedTemp = exportArgs[exportArgs.indexOf('-o') + 1]!; - expect(ports.ops.filter(op => op === 'fs.createExclusive')).toHaveLength(4); - expect(usedTemp.startsWith('/work/out/')).toBe(true); - // The three foreign colliding files are not owned and must be left alone. - expect(ports.tempPaths()).toHaveLength(3); - expect(ports.tempPaths()).not.toContain(usedTemp); - expect(ports.text(OUTPUT)).toBe(NEW_SNAPSHOT); - }); - - test('gives up with EXPORT_FAILED after bounded EEXIST collisions, never exports, and never removes foreign files', async () => { - const ports = new FaultyPorts(); - ports.createExclusiveHook = path => { - ports.files.set(path, { isFile: true, bytes: new TextEncoder().encode('foreign') }); - }; - - const err = await captureSnapshotError(exportNotebookSnapshot(ports.options())); - - expect(err.code).toBe('EXPORT_FAILED'); - expect(ports.ops.filter(op => op === 'fs.createExclusive')).toHaveLength(16); - expect(ports.runnerArgs.filter(a => a[0] === 'export')).toHaveLength(0); - expect(ports.ops).not.toContain('fs.remove'); - expect(ports.text(OUTPUT)).toBe(ORIGINAL_SNAPSHOT); - }); - - test('a destination directly under / reserves its temp under / without a double slash', async () => { - const ports = new FaultyPorts(); - ports.files.set('/nb.py', { isFile: true, bytes: new TextEncoder().encode('x') }); - await exportNotebookSnapshot(ports.options({ notebookPath: '/nb.py', outputPath: '/snap.html' })); - const exportArgs = ports.runnerArgs.find(a => a[0] === 'export')!; - const temp = exportArgs[exportArgs.indexOf('-o') + 1]!; - expect(temp).toMatch(/^\/\.marimo-snapshot-[^/]+\.tmp\.html$/); - expect(ports.text('/snap.html')).toBe(NEW_SNAPSHOT); - }); -}); - -describe('exportNotebookSnapshot QA: path normalization and roots', () => { - test('passes and reports normalized paths (dot segments, duplicate slashes) to runner, fs, and receipt', async () => { - const ports = new FaultyPorts(); - const receipt = await exportNotebookSnapshot( - ports.options({ - notebookPath: '/work//notebooks/./sub/../study.py', - outputPath: '/work/out/./x/../study.html', - allowedNotebookRoot: '/work/notebooks/', - allowedOutputRoot: '/work/out', - }) - ); - expect(ports.runnerArgs[0]).toEqual(['check', '--format=json', NOTEBOOK]); - expect(ports.runnerArgs[1]?.[2]).toBe(NOTEBOOK); - expect(receipt.notebookPath).toBe(NOTEBOOK); - expect(receipt.outputPath).toBe(OUTPUT); - expect(ports.text(OUTPUT)).toBe(NEW_SNAPSHOT); - }); - - test('a basename starting with "-" inside an absolute path is passed as one argv element', async () => { - const ports = new FaultyPorts(); - ports.files.set('/work/notebooks/-rf.py', { isFile: true, bytes: new TextEncoder().encode('x') }); - await exportNotebookSnapshot(ports.options({ notebookPath: '/work/notebooks/-rf.py' })); - expect(ports.runnerArgs[0]).toEqual(['check', '--format=json', '/work/notebooks/-rf.py']); - }); - - test('root "/" accepts any absolute path; relative or NUL roots and relative cwd are rejected before any port call', async () => { - const ok = new FaultyPorts(); - await exportNotebookSnapshot(ok.options({ allowedNotebookRoot: '/', allowedOutputRoot: '/' })); - expect(ok.text(OUTPUT)).toBe(NEW_SNAPSHOT); - - const badExtras: Array> = [ - { allowedNotebookRoot: 'work/notebooks' }, - { allowedOutputRoot: './out' }, - { allowedOutputRoot: '/work/out\0' }, - { allowedNotebookRoot: '' }, - { cwd: 'work' }, - // Path equal to the root itself is not "inside" it. - { allowedNotebookRoot: NOTEBOOK }, - // `..` that climbs above the root after normalization. - { notebookPath: '/work/notebooks/../../work/notebooks/../x.py', allowedNotebookRoot: '/work/notebooks' }, - ]; - for (const extra of badExtras) { - const ports = new FaultyPorts(); - const err = await captureSnapshotError(exportNotebookSnapshot(ports.options(extra))); - expect(err.code).toBe('INVALID_PATH'); - expect(ports.ops).toEqual([]); - expect(ports.runnerArgs).toEqual([]); - } - }); - - test('".." above filesystem root clamps to "/" and is still contained by roots', async () => { - const ports = new FaultyPorts(); - const err = await captureSnapshotError( - exportNotebookSnapshot( - ports.options({ notebookPath: '/../../etc/x.py', allowedNotebookRoot: '/work/notebooks' }) - ) - ); - expect(err.code).toBe('INVALID_PATH'); - expect(ports.runnerArgs).toEqual([]); - }); -}); - -describe('exportNotebookSnapshot QA: option validation', () => { - test('rejects malformed ports and options with INVALID_OPTION before any port call', async () => { - const ports = new FaultyPorts(); - const bad: Array | null> = [ - null, - { runner: undefined as unknown as NotebookCommandRunner }, - { runner: {} as NotebookCommandRunner }, - { fs: { ...ports.fs, rename: undefined } as unknown as NotebookSnapshotFs }, - { fs: { ...ports.fs, createExclusive: 'x' } as unknown as NotebookSnapshotFs }, - { timeoutMs: -1 }, - { timeoutMs: 1.5 }, - { timeoutMs: Number.NaN }, - { timeoutMs: Number.POSITIVE_INFINITY }, - { timeoutMs: '1000' as unknown as number }, - { marimoCommand: '' }, - { marimoCommand: ' ' }, - { marimoCommand: 'mar\0imo' }, - { marimoCommand: 42 as unknown as string }, - ]; - for (const extra of bad) { - const options = - extra === null ? (null as unknown as ExportNotebookSnapshotOptions) : ports.options(extra); - const err = await captureSnapshotError(exportNotebookSnapshot(options)); - expect(err.code).toBe('INVALID_OPTION'); - } - expect(ports.ops).toEqual([]); - expect(ports.runnerArgs).toEqual([]); - }); - - test('non-string notebookPath/outputPath are INVALID_PATH', async () => { - for (const extra of [ - { notebookPath: undefined as unknown as string }, - { outputPath: 7 as unknown as string }, - { notebookPath: '' }, - ]) { - const ports = new FaultyPorts(); - const err = await captureSnapshotError(exportNotebookSnapshot(ports.options(extra))); - expect(err.code).toBe('INVALID_PATH'); - expect(ports.ops).toEqual([]); - } - }); - - test('NotebookSnapshotError is a real Error subclass with stable name and code', () => { - const err = new NotebookSnapshotError('TIMEOUT', 'm', { details: { a: 1 } }); - expect(err).toBeInstanceOf(Error); - expect(err.name).toBe('NotebookSnapshotError'); - expect(err.code).toBe('TIMEOUT'); - expect(err.details).toEqual({ a: 1 }); - expect('cause' in err && err.cause !== undefined).toBe(false); - }); -}); diff --git a/libs/research/test/notebook-snapshot.test.ts b/libs/research/test/notebook-snapshot.test.ts deleted file mode 100644 index 3e5e31b0..00000000 --- a/libs/research/test/notebook-snapshot.test.ts +++ /dev/null @@ -1,851 +0,0 @@ -import { createHash } from 'node:crypto'; -import { describe, expect, test } from 'bun:test'; -import { exportNotebookSnapshot as barrelExportNotebookSnapshot } from '../src/index'; -import { - DEFAULT_MARIMO_COMMAND, - DEFAULT_NOTEBOOK_SNAPSHOT_TIMEOUT_MS, - exportNotebookSnapshot, - NotebookSnapshotError, - type NotebookCommandResult, - type NotebookCommandRunner, - type NotebookCommandRunOptions, - type NotebookSnapshotFileStat, - type NotebookSnapshotFs, -} from '../src/notebook-snapshot'; - -interface RecordedCall { - readonly command: string; - readonly args: readonly string[]; - readonly options: NotebookCommandRunOptions; -} - -interface FakeFsEntry { - readonly isFile: boolean; - bytes: Uint8Array; -} - -class InMemoryNotebookFs implements NotebookSnapshotFs { - readonly entries = new Map(); - readonly createdTempPaths: string[] = []; - readonly removedPaths: string[] = []; - readonly renames: Array<{ readonly from: string; readonly to: string }> = []; - failRenameError: Error | null = null; - failRemoveError: Error | null = null; - - putFile(path: string, content: string | Uint8Array): void { - const bytes = - typeof content === 'string' ? new TextEncoder().encode(content) : new Uint8Array(content); - this.entries.set(path, { isFile: true, bytes }); - } - - putDirectory(path: string): void { - this.entries.set(path, { isFile: false, bytes: new Uint8Array(0) }); - } - - getBytes(path: string): Uint8Array | undefined { - const entry = this.entries.get(path); - return entry?.isFile ? entry.bytes : undefined; - } - - getText(path: string): string | undefined { - const bytes = this.getBytes(path); - return bytes ? new TextDecoder().decode(bytes) : undefined; - } - - async stat(path: string): Promise { - const entry = this.entries.get(path); - if (!entry) { - return null; - } - return { isFile: entry.isFile, size: entry.bytes.byteLength }; - } - - async createExclusive(path: string): Promise { - if (this.entries.has(path)) { - const err = new Error(`EEXIST: file already exists '${path}'`) as Error & { code: string }; - err.code = 'EEXIST'; - throw err; - } - this.entries.set(path, { isFile: true, bytes: new Uint8Array(0) }); - this.createdTempPaths.push(path); - } - - async readBytes(path: string): Promise { - const entry = this.entries.get(path); - if (!entry || !entry.isFile) { - const err = new Error(`ENOENT: no such file '${path}'`) as Error & { code: string }; - err.code = 'ENOENT'; - throw err; - } - return new Uint8Array(entry.bytes); - } - - async rename(sourcePath: string, destinationPath: string): Promise { - if (this.failRenameError) { - throw this.failRenameError; - } - const entry = this.entries.get(sourcePath); - if (!entry) { - const err = new Error(`ENOENT: no such file '${sourcePath}'`) as Error & { code: string }; - err.code = 'ENOENT'; - throw err; - } - this.entries.delete(sourcePath); - this.entries.set(destinationPath, entry); - this.renames.push({ from: sourcePath, to: destinationPath }); - } - - async remove(path: string): Promise { - this.removedPaths.push(path); - if (this.failRemoveError) { - throw this.failRemoveError; - } - this.entries.delete(path); - } -} - -type RunnerHandler = ( - command: string, - args: readonly string[], - options: NotebookCommandRunOptions, - callIndex: number -) => Promise; - -function createRecordingRunner(handler: RunnerHandler): { - readonly runner: NotebookCommandRunner; - readonly calls: RecordedCall[]; -} { - const calls: RecordedCall[] = []; - const runner: NotebookCommandRunner = { - async run(command, args, options) { - const callIndex = calls.length; - calls.push({ command, args: [...args], options: { ...options } }); - return handler(command, args, options, callIndex); - }, - }; - return { runner, calls }; -} - -function makeTimeoutError(message = 'Command timed out'): Error & { code: string } { - const err = new Error(message) as Error & { code: string }; - err.code = 'ETIMEDOUT'; - return err; -} - -async function expectSnapshotError( - promise: Promise, - expectedCode: NotebookSnapshotError['code'] -): Promise { - try { - await promise; - } catch (err) { - expect(err).toBeInstanceOf(NotebookSnapshotError); - const snapshotErr = err as NotebookSnapshotError; - expect(snapshotErr.code).toBe(expectedCode); - return snapshotErr; - } - throw new Error(`Expected NotebookSnapshotError(${expectedCode}), but promise resolved.`); -} - -describe('exportNotebookSnapshot', () => { - test('is re-exported from the @stock-bot/research barrel', () => { - expect(barrelExportNotebookSnapshot).toBe(exportNotebookSnapshot); - }); - - test('happy path: runs check then export html with exact argv, publishes via sibling temp rename, and returns frozen receipt with exact non-ASCII bytes and sha256', async () => { - const fs = new InMemoryNotebookFs(); - const notebookPath = '/workspace/research/notebooks/study.py'; - const outputPath = '/workspace/artifacts/study.html'; - fs.putFile(notebookPath, 'import marimo\n'); - - const nonAsciiHtml = - '

CA Shorts — €100 / 日本語

'; - const expectedBytes = new TextEncoder().encode(nonAsciiHtml); - const expectedSha256 = createHash('sha256').update(expectedBytes).digest('hex'); - - const cleanReport = { - issues: [], - summary: { errored: false, total_files: 1 }, - }; - - const { runner, calls } = createRecordingRunner(async (_cmd, args) => { - if (args[0] === 'check') { - return { exitCode: 0, stdout: JSON.stringify(cleanReport), stderr: '' }; - } - const outFlagIdx = args.indexOf('-o'); - const tempPath = args[outFlagIdx + 1] as string; - fs.putFile(tempPath, expectedBytes); - return { exitCode: 0, stdout: '', stderr: '' }; - }); - - const receipt = await exportNotebookSnapshot({ - notebookPath, - outputPath, - runner, - fs, - allowedNotebookRoot: '/workspace/research/notebooks', - allowedOutputRoot: '/workspace/artifacts', - }); - - expect(calls).toHaveLength(2); - expect(calls[0]).toEqual({ - command: DEFAULT_MARIMO_COMMAND, - args: ['check', '--format=json', notebookPath], - options: { timeoutMs: DEFAULT_NOTEBOOK_SNAPSHOT_TIMEOUT_MS }, - }); - - expect(fs.createdTempPaths).toHaveLength(1); - const tempPath = fs.createdTempPaths[0] as string; - expect(tempPath.startsWith('/workspace/artifacts/')).toBe(true); - expect(tempPath.endsWith('.html')).toBe(true); - expect(tempPath).not.toBe(outputPath); - - expect(calls[1]).toEqual({ - command: DEFAULT_MARIMO_COMMAND, - args: ['export', 'html', notebookPath, '-o', tempPath, '--force'], - options: { timeoutMs: DEFAULT_NOTEBOOK_SNAPSHOT_TIMEOUT_MS }, - }); - - expect(fs.renames).toEqual([{ from: tempPath, to: outputPath }]); - expect(fs.getBytes(tempPath)).toBeUndefined(); - expect(fs.getBytes(outputPath)).toEqual(expectedBytes); - - expect(Object.isFrozen(receipt)).toBe(true); - expect(Object.isFrozen(receipt.checkDiagnostics)).toBe(true); - expect(receipt).toEqual({ - notebookPath, - outputPath, - bytes: expectedBytes.byteLength, - sha256: expectedSha256, - checkDiagnostics: cleanReport, - }); - }); - - test('passes custom marimoCommand, timeoutMs, cwd, and notebook paths with spaces and shell metacharacters as single unmodified argv elements', async () => { - const fs = new InMemoryNotebookFs(); - const trickyNotebook = "/work/my notebooks/study $(rm -rf) & 'quote'; echo hi | cat.py"; - const outputPath = '/work/out/report snapshot.html'; - fs.putFile(trickyNotebook, 'import marimo\n'); - - const { runner, calls } = createRecordingRunner(async (_cmd, args) => { - if (args[0] === 'check') { - return { exitCode: 0, stdout: '', stderr: '' }; - } - const tempPath = args[args.indexOf('-o') + 1] as string; - fs.putFile(tempPath, 'ok'); - return { exitCode: 0, stdout: '', stderr: '' }; - }); - - const receipt = await exportNotebookSnapshot({ - notebookPath: trickyNotebook, - outputPath, - runner, - fs, - marimoCommand: '/opt/uv/bin/marimo', - timeoutMs: 45_000, - cwd: '/work', - }); - - expect(calls).toHaveLength(2); - expect(calls[0]?.command).toBe('/opt/uv/bin/marimo'); - expect(calls[0]?.args).toEqual(['check', '--format=json', trickyNotebook]); - expect(calls[0]?.options).toEqual({ cwd: '/work', timeoutMs: 45_000 }); - expect(calls[1]?.command).toBe('/opt/uv/bin/marimo'); - expect(calls[1]?.args[2]).toBe(trickyNotebook); - expect(calls[1]?.options).toEqual({ cwd: '/work', timeoutMs: 45_000 }); - expect(receipt.checkDiagnostics).toBeNull(); - }); - - test('accepts formatting and runtime advisories on clean exit 0', async () => { - const fs = new InMemoryNotebookFs(); - const notebookPath = '/work/nb.py'; - const outputPath = '/work/out.html'; - fs.putFile(notebookPath, 'import marimo\n'); - - const advisoryReport = { - issues: [ - { code: 'MF001', severity: 'formatting', message: 'Formatting suggestion' }, - { code: 'MR001', severity: 'runtime', message: 'Runtime advisory' }, - ], - summary: { errored: false, total_files: 1 }, - }; - - const { runner, calls } = createRecordingRunner(async (_cmd, args) => { - if (args[0] === 'check') { - return { exitCode: 0, stdout: JSON.stringify(advisoryReport), stderr: '' }; - } - const tempPath = args[args.indexOf('-o') + 1] as string; - fs.putFile(tempPath, 'advisory ok'); - return { exitCode: 0, stdout: '', stderr: '' }; - }); - - const receipt = await exportNotebookSnapshot({ notebookPath, outputPath, runner, fs }); - expect(calls).toHaveLength(2); - expect(receipt.checkDiagnostics).toEqual(advisoryReport); - expect(Object.isFrozen(receipt.checkDiagnostics?.issues)).toBe(true); - }); - - test('never invokes export when marimo check exits non-zero and preserves parsed diagnostics', async () => { - const fs = new InMemoryNotebookFs(); - const notebookPath = '/work/bad.py'; - const outputPath = '/work/out.html'; - fs.putFile(notebookPath, 'def broken(:\n'); - - const failureReport = { - issues: [{ code: 'MB001', severity: 'breaking', message: 'Syntax error' }], - summary: { errored: true, total_files: 1 }, - }; - - const { runner, calls } = createRecordingRunner(async () => ({ - exitCode: 1, - stdout: JSON.stringify(failureReport), - stderr: 'check failed', - })); - - const err = await expectSnapshotError( - exportNotebookSnapshot({ notebookPath, outputPath, runner, fs }), - 'CHECK_FAILED' - ); - - expect(calls).toHaveLength(1); - expect(calls[0]?.args[0]).toBe('check'); - expect(fs.createdTempPaths).toHaveLength(0); - expect((err.details as { diagnostics?: unknown }).diagnostics).toEqual(failureReport); - }); - - test('nonzero check exit takes precedence as CHECK_FAILED even when stdout is non-JSON', async () => { - const fs = new InMemoryNotebookFs(); - fs.putFile('/work/bad.py', 'import marimo\n'); - - const { runner, calls } = createRecordingRunner(async () => ({ - exitCode: 2, - stdout: 'not json at all', - stderr: 'fatal error', - })); - - await expectSnapshotError( - exportNotebookSnapshot({ - notebookPath: '/work/bad.py', - outputPath: '/work/out.html', - runner, - fs, - }), - 'CHECK_FAILED' - ); - expect(calls).toHaveLength(1); - }); - - test('never invokes export when check exits 0 with whitespace-only stdout', async () => { - for (const stdout of ['\n', ' \t\r\n']) { - const fs = new InMemoryNotebookFs(); - fs.putFile('/work/nb.py', 'import marimo\n'); - fs.putFile('/work/out.html', 'existing-snapshot'); - const { runner, calls } = createRecordingRunner(async () => ({ - exitCode: 0, - stdout, - stderr: '', - })); - - await expectSnapshotError( - exportNotebookSnapshot({ - notebookPath: '/work/nb.py', - outputPath: '/work/out.html', - runner, - fs, - }), - 'CHECK_OUTPUT_INVALID' - ); - expect(calls).toHaveLength(1); - expect(calls[0]?.args[0]).toBe('check'); - expect(fs.createdTempPaths).toHaveLength(0); - expect(fs.getText('/work/out.html')).toBe('existing-snapshot'); - } - }); - - test('never invokes export when check exits 0 with malformed JSON or invalid report shape', async () => { - const badOutputs = [ - '{not-valid-json', - '[]', - '{}', - JSON.stringify({ issues: 'not-an-array', summary: { errored: false, total_files: 1 } }), - JSON.stringify({ issues: [], summary: { errored: 'false', total_files: 1 } }), - JSON.stringify({ issues: [], summary: { errored: false, total_files: 0 } }), - JSON.stringify({ issues: [], summary: { errored: false, total_files: 2 } }), - JSON.stringify({ issues: [123], summary: { errored: false, total_files: 1 } }), - ]; - - for (const stdout of badOutputs) { - const fs = new InMemoryNotebookFs(); - fs.putFile('/work/nb.py', 'import marimo\n'); - const { runner, calls } = createRecordingRunner(async () => ({ - exitCode: 0, - stdout, - stderr: '', - })); - - await expectSnapshotError( - exportNotebookSnapshot({ - notebookPath: '/work/nb.py', - outputPath: '/work/out.html', - runner, - fs, - }), - 'CHECK_OUTPUT_INVALID' - ); - expect(calls).toHaveLength(1); - expect(fs.createdTempPaths).toHaveLength(0); - } - }); - - test('never invokes export when check exits 0 with summary.errored, file error, or breaking diagnostic', async () => { - const blockingReports = [ - { issues: [], summary: { errored: true, total_files: 1 } }, - { - issues: [{ type: 'error', message: 'Failed to parse notebook' }], - summary: { errored: false, total_files: 1 }, - }, - { - issues: [{ code: 'MB002', severity: 'breaking', message: 'Cycle detected' }], - summary: { errored: false, total_files: 1 }, - }, - { - issues: [ - { - file: '/work/nb.py', - diagnostics: [{ code: 'MB003', severity: 'breaking', message: 'Multiple definitions' }], - }, - ], - summary: { errored: false, total_files: 1 }, - }, - ]; - - for (const report of blockingReports) { - const fs = new InMemoryNotebookFs(); - fs.putFile('/work/nb.py', 'import marimo\n'); - const { runner, calls } = createRecordingRunner(async () => ({ - exitCode: 0, - stdout: JSON.stringify(report), - stderr: '', - })); - - const err = await expectSnapshotError( - exportNotebookSnapshot({ - notebookPath: '/work/nb.py', - outputPath: '/work/out.html', - runner, - fs, - }), - 'CHECK_FAILED' - ); - expect(calls).toHaveLength(1); - expect(fs.createdTempPaths).toHaveLength(0); - expect((err.details as { diagnostics?: unknown }).diagnostics).toEqual(report); - } - }); - - test('maps check timeout to TIMEOUT and never invokes export', async () => { - const fs = new InMemoryNotebookFs(); - fs.putFile('/work/nb.py', 'import marimo\n'); - fs.putFile('/work/out.html', 'original'); - - const { runner, calls } = createRecordingRunner(async () => { - throw makeTimeoutError('check timed out'); - }); - - await expectSnapshotError( - exportNotebookSnapshot({ - notebookPath: '/work/nb.py', - outputPath: '/work/out.html', - runner, - fs, - timeoutMs: 5_000, - }), - 'TIMEOUT' - ); - - expect(calls).toHaveLength(1); - expect(fs.createdTempPaths).toHaveLength(0); - expect(fs.getText('/work/out.html')).toBe('original'); - }); - - test('fail-closed export: nonzero exit after partial HTML write removes temp and preserves existing destination', async () => { - const fs = new InMemoryNotebookFs(); - fs.putFile('/work/nb.py', 'import marimo\n'); - fs.putFile('/work/out.html', 'original-good-snapshot'); - - const { runner } = createRecordingRunner(async (_cmd, args) => { - if (args[0] === 'check') { - return { exitCode: 0, stdout: '', stderr: '' }; - } - const tempPath = args[args.indexOf('-o') + 1] as string; - fs.putFile(tempPath, 'partial-broken-cell-output'); - return { exitCode: 1, stdout: '', stderr: 'ZeroDivisionError in cell 3' }; - }); - - await expectSnapshotError( - exportNotebookSnapshot({ - notebookPath: '/work/nb.py', - outputPath: '/work/out.html', - runner, - fs, - }), - 'EXPORT_FAILED' - ); - - expect(fs.createdTempPaths).toHaveLength(1); - const tempPath = fs.createdTempPaths[0] as string; - expect(fs.removedPaths).toContain(tempPath); - expect(fs.getBytes(tempPath)).toBeUndefined(); - expect(fs.getText('/work/out.html')).toBe('original-good-snapshot'); - }); - - test('fail-closed export: missing or zero-byte temp output throws EXPORT_EMPTY, cleans temp, and preserves destination', async () => { - for (const mode of ['zero-byte', 'missing'] as const) { - const fs = new InMemoryNotebookFs(); - fs.putFile('/work/nb.py', 'import marimo\n'); - fs.putFile('/work/out.html', 'keep-me'); - - const { runner } = createRecordingRunner(async (_cmd, args) => { - if (args[0] === 'check') { - return { exitCode: 0, stdout: '', stderr: '' }; - } - const tempPath = args[args.indexOf('-o') + 1] as string; - if (mode === 'missing') { - fs.entries.delete(tempPath); - } - // In 'zero-byte' mode, tempPath stays at 0 bytes from createExclusive. - return { exitCode: 0, stdout: '', stderr: '' }; - }); - - await expectSnapshotError( - exportNotebookSnapshot({ - notebookPath: '/work/nb.py', - outputPath: '/work/out.html', - runner, - fs, - }), - 'EXPORT_EMPTY' - ); - - const tempPath = fs.createdTempPaths[0] as string; - expect(fs.removedPaths).toContain(tempPath); - expect(fs.getBytes(tempPath)).toBeUndefined(); - expect(fs.getText('/work/out.html')).toBe('keep-me'); - } - }); - - test('fail-closed export: export timeout after partial write throws TIMEOUT, removes temp, and preserves destination', async () => { - const fs = new InMemoryNotebookFs(); - fs.putFile('/work/nb.py', 'import marimo\n'); - fs.putFile('/work/out.html', 'keep-original'); - - const { runner } = createRecordingRunner(async (_cmd, args) => { - if (args[0] === 'check') { - return { exitCode: 0, stdout: '', stderr: '' }; - } - const tempPath = args[args.indexOf('-o') + 1] as string; - fs.putFile(tempPath, 'partial-before-timeout'); - throw makeTimeoutError('export timed out'); - }); - - await expectSnapshotError( - exportNotebookSnapshot({ - notebookPath: '/work/nb.py', - outputPath: '/work/out.html', - runner, - fs, - timeoutMs: 1_000, - }), - 'TIMEOUT' - ); - - const tempPath = fs.createdTempPaths[0] as string; - expect(fs.removedPaths).toContain(tempPath); - expect(fs.getBytes(tempPath)).toBeUndefined(); - expect(fs.getText('/work/out.html')).toBe('keep-original'); - }); - - test('fail-closed export: rename failure throws EXPORT_FAILED, removes temp, and preserves destination', async () => { - const fs = new InMemoryNotebookFs(); - fs.putFile('/work/nb.py', 'import marimo\n'); - fs.putFile('/work/out.html', 'prior-snapshot'); - fs.failRenameError = new Error('EXDEV: cross-device link not permitted'); - - const { runner } = createRecordingRunner(async (_cmd, args) => { - if (args[0] === 'check') { - return { exitCode: 0, stdout: '', stderr: '' }; - } - const tempPath = args[args.indexOf('-o') + 1] as string; - fs.putFile(tempPath, 'new-snapshot'); - return { exitCode: 0, stdout: '', stderr: '' }; - }); - - const err = await expectSnapshotError( - exportNotebookSnapshot({ - notebookPath: '/work/nb.py', - outputPath: '/work/out.html', - runner, - fs, - }), - 'EXPORT_FAILED' - ); - - const tempPath = fs.createdTempPaths[0] as string; - expect(err.cause).toBe(fs.failRenameError); - expect(fs.removedPaths).toContain(tempPath); - expect(fs.getBytes(tempPath)).toBeUndefined(); - expect(fs.getText('/work/out.html')).toBe('prior-snapshot'); - }); - - test('fail-closed export: rename failure preserves primary error if temp cleanup also fails', async () => { - const fs = new InMemoryNotebookFs(); - fs.putFile('/work/nb.py', 'import marimo\n'); - fs.putFile('/work/out.html', 'prior-snapshot'); - fs.failRenameError = new Error('EXDEV: cross-device link not permitted'); - fs.failRemoveError = new Error('EIO: cleanup failed'); - - const { runner } = createRecordingRunner(async (_cmd, args) => { - if (args[0] === 'check') { - return { exitCode: 0, stdout: '', stderr: '' }; - } - const tempPath = args[args.indexOf('-o') + 1] as string; - fs.putFile(tempPath, 'new-snapshot'); - return { exitCode: 0, stdout: '', stderr: '' }; - }); - - const err = await expectSnapshotError( - exportNotebookSnapshot({ - notebookPath: '/work/nb.py', - outputPath: '/work/out.html', - runner, - fs, - }), - 'EXPORT_FAILED' - ); - - expect(err.cause).toBe(fs.failRenameError); - expect(fs.removedPaths).toContain(fs.createdTempPaths[0] as string); - expect(fs.getText('/work/out.html')).toBe('prior-snapshot'); - }); - - test('uses a short sibling temp filename even when output basename is near POSIX NAME_MAX', async () => { - const fs = new InMemoryNotebookFs(); - const notebookPath = '/work/nb.py'; - const longBasename = `${'a'.repeat(250)}.html`; - const outputPath = `/work/${longBasename}`; - fs.putFile(notebookPath, 'import marimo\n'); - - const { runner } = createRecordingRunner(async (_cmd, args) => { - if (args[0] === 'check') { - return { exitCode: 0, stdout: '', stderr: '' }; - } - const tempPath = args[args.indexOf('-o') + 1] as string; - fs.putFile(tempPath, 'long-name-ok'); - return { exitCode: 0, stdout: '', stderr: '' }; - }); - - await exportNotebookSnapshot({ notebookPath, outputPath, runner, fs }); - - expect(fs.createdTempPaths).toHaveLength(1); - const tempPath = fs.createdTempPaths[0] as string; - const tempBasename = tempPath.slice(tempPath.lastIndexOf('/') + 1); - expect(tempPath.startsWith('/work/')).toBe(true); - expect(tempBasename.endsWith('.html')).toBe(true); - expect(tempBasename.length).toBeLessThan(128); - expect(fs.getText(outputPath)).toBe('long-name-ok'); - }); - - test('overlapping exports to the same outputPath reserve separate temp files without partial publication', async () => { - const fs = new InMemoryNotebookFs(); - fs.putFile('/work/nb.py', 'import marimo\n'); - fs.putFile('/work/out.html', 'initial'); - - let releaseFirstExport: (() => void) | null = null; - const firstExportStarted = new Promise(resolve => { - releaseFirstExport = resolve; - }); - let unblockFirstExport: (() => void) | null = null; - const gateFirstExport = new Promise(resolve => { - unblockFirstExport = resolve; - }); - - let exportCount = 0; - const { runner } = createRecordingRunner(async (_cmd, args) => { - if (args[0] === 'check') { - return { exitCode: 0, stdout: '', stderr: '' }; - } - exportCount += 1; - const myExport = exportCount; - const tempPath = args[args.indexOf('-o') + 1] as string; - if (myExport === 1) { - fs.putFile(tempPath, 'snapshot-A'); - releaseFirstExport?.(); - await gateFirstExport; - return { exitCode: 0, stdout: '', stderr: '' }; - } - fs.putFile(tempPath, 'snapshot-B'); - return { exitCode: 0, stdout: '', stderr: '' }; - }); - - const firstPromise = exportNotebookSnapshot({ - notebookPath: '/work/nb.py', - outputPath: '/work/out.html', - runner, - fs, - }); - await firstExportStarted; - - const secondReceipt = await exportNotebookSnapshot({ - notebookPath: '/work/nb.py', - outputPath: '/work/out.html', - runner, - fs, - }); - expect(fs.getText('/work/out.html')).toBe('snapshot-B'); - - unblockFirstExport?.(); - const firstReceipt = await firstPromise; - - expect(fs.createdTempPaths).toHaveLength(2); - expect(fs.createdTempPaths[0]).not.toBe(fs.createdTempPaths[1]); - expect(firstReceipt.bytes).toBe(new TextEncoder().encode('snapshot-A').byteLength); - expect(secondReceipt.bytes).toBe( - new TextEncoder().encode('snapshot-B').byteLength - ); - expect(fs.getText('/work/out.html')).toBe('snapshot-A'); - }); - - test('rejects invalid paths before any runner call', async () => { - const cases: Array<{ - readonly name: string; - readonly notebookPath: string; - readonly outputPath: string; - readonly allowedNotebookRoot?: string; - readonly allowedOutputRoot?: string; - }> = [ - { name: 'non-.py notebook', notebookPath: '/work/nb.txt', outputPath: '/work/out.html' }, - { name: 'bare .py filename', notebookPath: '/work/.py', outputPath: '/work/out.html' }, - { - name: 'trailing slash notebook', - notebookPath: '/work/nb.py/', - outputPath: '/work/out.html', - }, - { name: 'non-.html output', notebookPath: '/work/nb.py', outputPath: '/work/out.htm' }, - { name: 'bare .html filename', notebookPath: '/work/nb.py', outputPath: '/work/.html' }, - { name: 'relative notebook', notebookPath: 'research/nb.py', outputPath: '/work/out.html' }, - { name: 'relative output', notebookPath: '/work/nb.py', outputPath: './out.html' }, - { name: 'leading dash notebook', notebookPath: '-nb.py', outputPath: '/work/out.html' }, - { name: 'leading dash output', notebookPath: '/work/nb.py', outputPath: '--out.html' }, - { name: 'NUL in notebook', notebookPath: '/work/nb\0.py', outputPath: '/work/out.html' }, - { name: 'NUL in output', notebookPath: '/work/nb.py', outputPath: '/work/out\0.html' }, - { - name: '.. escape outside allowedNotebookRoot', - notebookPath: '/work/notebooks/../secret.py', - outputPath: '/work/out/report.html', - allowedNotebookRoot: '/work/notebooks', - }, - { - name: '.. escape outside allowedOutputRoot', - notebookPath: '/work/notebooks/nb.py', - outputPath: '/work/out/../evil.html', - allowedOutputRoot: '/work/out', - }, - { - name: 'same-prefix sibling notebook root', - notebookPath: '/work/notebooks-other/nb.py', - outputPath: '/work/out/report.html', - allowedNotebookRoot: '/work/notebooks', - }, - { - name: 'same-prefix sibling output root', - notebookPath: '/work/notebooks/nb.py', - outputPath: '/work/out-other/report.html', - allowedOutputRoot: '/work/out', - }, - ]; - - for (const tc of cases) { - const fs = new InMemoryNotebookFs(); - fs.putFile('/work/nb.py', 'import marimo\n'); - const { runner, calls } = createRecordingRunner(async () => ({ - exitCode: 0, - stdout: '', - stderr: '', - })); - - await expectSnapshotError( - exportNotebookSnapshot({ - notebookPath: tc.notebookPath, - outputPath: tc.outputPath, - runner, - fs, - ...(tc.allowedNotebookRoot !== undefined - ? { allowedNotebookRoot: tc.allowedNotebookRoot } - : {}), - ...(tc.allowedOutputRoot !== undefined - ? { allowedOutputRoot: tc.allowedOutputRoot } - : {}), - }), - 'INVALID_PATH' - ); - expect(calls).toHaveLength(0); - } - }); - - test('rejects missing notebook or directory in place of notebook with NOTEBOOK_NOT_FOUND and zero runner calls', async () => { - for (const setup of ['missing', 'directory'] as const) { - const fs = new InMemoryNotebookFs(); - if (setup === 'directory') { - fs.putDirectory('/work/nb.py'); - } - const { runner, calls } = createRecordingRunner(async () => ({ - exitCode: 0, - stdout: '', - stderr: '', - })); - - await expectSnapshotError( - exportNotebookSnapshot({ - notebookPath: '/work/nb.py', - outputPath: '/work/out.html', - runner, - fs, - }), - 'NOTEBOOK_NOT_FOUND' - ); - expect(calls).toHaveLength(0); - } - }); - - test('rejects invalid timeoutMs or marimoCommand with INVALID_OPTION and zero runner calls', async () => { - const fs = new InMemoryNotebookFs(); - fs.putFile('/work/nb.py', 'import marimo\n'); - const { runner, calls } = createRecordingRunner(async () => ({ - exitCode: 0, - stdout: '', - stderr: '', - })); - - await expectSnapshotError( - exportNotebookSnapshot({ - notebookPath: '/work/nb.py', - outputPath: '/work/out.html', - runner, - fs, - timeoutMs: 0, - }), - 'INVALID_OPTION' - ); - await expectSnapshotError( - exportNotebookSnapshot({ - notebookPath: '/work/nb.py', - outputPath: '/work/out.html', - runner, - fs, - marimoCommand: '-evil', - }), - 'INVALID_OPTION' - ); - expect(calls).toHaveLength(0); - }); -}); diff --git a/libs/research/test/signal-panel-e2e.test.ts b/libs/research/test/signal-panel-e2e.test.ts deleted file mode 100644 index 379e3c42..00000000 --- a/libs/research/test/signal-panel-e2e.test.ts +++ /dev/null @@ -1,403 +0,0 @@ -import { describe, expect, it } from 'bun:test'; -import { - analyzeSignal, - buildForwardReturnPanel, - collectBars, - createDuckDbMarketDataStore, - shortsTableToSignalRows, - type DuckDbExecutor, - type DuckDbParam, - type TableRow, - type TrialLedgerExecutor, -} from '@stock-bot/research'; - -const CURATED_ROOT = '/mnt/data/stockbot/curated'; -const SEED = 20261129; - -function createSeededRng(seed: number): () => number { - let state = seed >>> 0; - return () => { - state = (state + 0x6d2b79f5) >>> 0; - let t = Math.imul(state ^ (state >>> 15), 1 | state); - t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; - return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296; - }; -} - -function makeBusinessDates(startDate: string, count: number): string[] { - const out: string[] = new Array(count); - const current = new Date(`${startDate}T00:00:00.000Z`); - let written = 0; - while (written < count) { - const day = current.getUTCDay(); - if (day !== 0 && day !== 6) { - out[written] = current.toISOString().slice(0, 10); - written += 1; - } - current.setUTCDate(current.getUTCDate() + 1); - } - return out; -} - -function makeUtcMs(date: string, hourUtc: number): number { - const [y, m, d] = date.split('-').map(Number); - return Date.UTC(y!, m! - 1, d!, hourUtc, 0, 0, 0); -} - -interface StoredTrialRow { - readonly trial_id: string; - readonly created_at: Date; - readonly principal_id: string; - readonly campaign_id: string | null; - readonly stage: string; - readonly universe_market: string; - readonly horizon_bucket: string; - readonly hypothesis_id: string | null; - readonly expression_hash: string; - readonly sample_start: string; - readonly sample_end: string; - readonly n_obs: number; - readonly sharpe_unann: number; - readonly skewness: number; - readonly kurtosis: number; - readonly daily_series: readonly number[]; -} - -function createInMemoryTrialExecutor(): { - executor: TrialLedgerExecutor; - rows: StoredTrialRow[]; -} { - const rows: StoredTrialRow[] = []; - let nextTrialId = 1; - - const executor: TrialLedgerExecutor = { - async query>(text: string, params?: readonly unknown[]) { - const trimmed = text.trimStart(); - if (trimmed.startsWith('INSERT INTO trial_ledger')) { - const p = params ?? []; - const trialId = nextTrialId++; - const createdAt = new Date(Date.UTC(2024, 5, 1, 12, 0, trialId)); - const dailySeries = (p[13] as readonly number[]).map(v => Math.fround(v)); - const stored: StoredTrialRow = { - trial_id: String(trialId), - created_at: createdAt, - principal_id: p[0] as string, - campaign_id: (p[1] as string | null) ?? null, - stage: p[2] as string, - universe_market: p[3] as string, - horizon_bucket: p[4] as string, - hypothesis_id: (p[5] as string | null) ?? null, - expression_hash: p[6] as string, - sample_start: p[7] as string, - sample_end: p[8] as string, - n_obs: p[9] as number, - sharpe_unann: p[10] as number, - skewness: p[11] as number, - kurtosis: p[12] as number, - daily_series: dailySeries, - }; - rows.push(stored); - return { - rows: [{ trial_id: stored.trial_id, created_at: stored.created_at } as unknown as Row], - rowCount: 1, - }; - } - - if (trimmed.startsWith('SELECT')) { - if (text.includes('WHERE trial_id = $1::bigint')) { - const targetId = String(params?.[0]); - const matched = rows.filter(r => r.trial_id === targetId); - return { rows: matched as unknown as Row[], rowCount: matched.length }; - } - if (text.includes('WHERE universe_market = $1')) { - const market = params?.[0] as string; - const bucket = params?.[1] as string; - const matched = rows.filter( - r => r.universe_market === market && r.horizon_bucket === bucket - ); - return { rows: matched as unknown as Row[], rowCount: matched.length }; - } - } - - return { rows: [], rowCount: 0 }; - }, - }; - - return { executor, rows }; -} - -interface CeoShortsFixture { - readonly listingIds: number[]; - readonly allDates: string[]; - readonly vaultCutoffDate: string; - readonly vaultCutoffTs: number; - readonly barRows: TableRow[]; - readonly shortsRows: TableRow[]; -} - -function buildCeoShortsFixture(poisonPostCutoff: boolean): CeoShortsFixture { - const rand = createSeededRng(SEED); - const listingCount = 28; - const preCutoffSessions = 140; // spans late 2022 through early 2023 (pre-2023 & post-2023) - const postCutoffSessions = 10; - const allDates = makeBusinessDates('2022-09-01', preCutoffSessions + postCutoffSessions); - const vaultCutoffDate = allDates[preCutoffSessions]!; - const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0); - - const listingIds = Array.from({ length: listingCount }, (_, i) => 50_001 + i); - const barRows: TableRow[] = []; - const shortsRows: TableRow[] = []; - - // Semi-monthly ceoShorts reports (every 10 trading sessions). Publication follows the CIRO - // working assumption: 17:00 ET (22:00 UTC) four business days after `report_date`. A report - // only drives prices from the session AFTER its publication close, so no close ever reflects - // a report before its `known_at` (QA fix for the reviewer's look-ahead note). - // Plant a negative relationship: higher net_change predicts lower subsequent 5-session return. - const PUBLICATION_LAG_SESSIONS = 4; - const activeNetChange = new Float64Array(listingCount); - const pendingByPublishIdx = new Map(); - const prices = new Float64Array(listingCount); - for (let l = 0; l < listingCount; l += 1) { - prices[l] = 10 + l * 1.5; - } - - for (let t = 0; t < allDates.length; t += 1) { - const date = allDates[t]!; - const closeTs = makeUtcMs(date, 21); // 16:00 ET close - - // Reports published after the previous close become tradeable information today. - const released = pendingByPublishIdx.get(t - 1); - if (released !== undefined) { - for (let l = 0; l < listingCount; l += 1) { - const v = released[l]; - if (v !== null && v !== undefined) { - activeNetChange[l] = v / 20_000; // normalized in [-1, 1] - } - } - } - - const publishIdx = t + PUBLICATION_LAG_SESSIONS; - if (t % 10 === 0 && publishIdx < allDates.length) { - const reportKnownAt = makeUtcMs(allDates[publishIdx]!, 22); // 17:00 ET on T+4 - const pending: (number | null)[] = []; - for (let l = 0; l < listingCount; l += 1) { - const isNullCell = t > 0 && (t + l) % 19 === 0; - const netChange = isNullCell ? null : Math.round((rand() * 2 - 1) * 20_000); - pending.push(netChange); - shortsRows.push({ - listing_id: listingIds[l]!, - report_date: date, - known_at: reportKnownAt, - shares_short: 100_000 + l * 5_000 + Math.round(rand() * 10_000), - net_change: netChange, - pct_float: isNullCell ? null : Number((0.02 + rand() * 0.08).toFixed(4)), - source: 'ceoShorts', - }); - } - pendingByPublishIdx.set(publishIdx, pending); - } - - for (let l = 0; l < listingCount; l += 1) { - // Drift driven negatively by prior known short-interest change + idiosyncratic noise. - const dailyRet = -0.004 * activeNetChange[l]! + (rand() * 2 - 1) * 0.008; - prices[l] = Math.max(0.5, prices[l]! * (1 + dailyRet)); - - const isPostCutoff = date >= vaultCutoffDate; - const closeVal = poisonPostCutoff && isPostCutoff ? 999_999 : Number(prices[l]!.toFixed(6)); - barRows.push({ - listing_id: listingIds[l]!, - ts: closeTs, - open: closeVal, - high: closeVal, - low: closeVal, - close: closeVal, - volume: 50_000, - vwap: closeVal, - known_at: closeTs, - }); - } - } - - return { - listingIds, - allDates, - vaultCutoffDate, - vaultCutoffTs, - barRows, - shortsRows, - }; -} - -function createFakeDuckDbExecutor(fixture: CeoShortsFixture): { - executor: DuckDbExecutor; - runStatements: string[]; - queryCount: () => number; -} { - const runStatements: string[] = []; - let queries = 0; - - const executor: DuckDbExecutor = { - async run(sql: string) { - runStatements.push(sql); - }, - async query(sql: string, params: readonly DuckDbParam[]): Promise { - queries += 1; - - if (sql.includes('bars_1d/year=*/part.parquet')) { - // Bound params: [...listingIds, fromIso, toIso, asOfIso] - const nIds = fixture.listingIds.length; - const idSet = new Set(params.slice(0, nIds) as number[]); - const fromMs = Date.parse(params[nIds] as string); - const toMs = Date.parse(params[nIds + 1] as string); - const asOfMs = Date.parse(params[nIds + 2] as string); - return fixture.barRows.filter(row => { - const lid = row.listing_id as number; - const ts = row.ts as number; - const knownAt = row.known_at as number; - return idSet.has(lid) && ts >= fromMs && ts <= toMs && knownAt <= asOfMs; - }); - } - - if (sql.includes('shorts/part.parquet')) { - // Bound params: [...listingIds, fromDate, toDate, asOfIso] - const nIds = fixture.listingIds.length; - const idSet = new Set(params.slice(0, nIds) as number[]); - const fromDate = params[nIds] as string; - const toDate = params[nIds + 1] as string; - const asOfMs = Date.parse(params[nIds + 2] as string); - return fixture.shortsRows.filter(row => { - const lid = row.listing_id as number; - const reportDate = row.report_date as string; - const knownAt = row.known_at as number; - return idSet.has(lid) && reportDate >= fromDate && reportDate <= toDate && knownAt <= asOfMs; - }); - } - - throw new Error(`Unexpected SQL in fake DuckDbExecutor: ${sql}`); - }, - }; - - return { - executor, - runStatements, - queryCount: () => queries, - }; -} - -describe('ceoShorts end-to-end signal study (headless, no database)', () => { - async function runCeoShortsStudy(poisonPostCutoff: boolean) { - const fixture = buildCeoShortsFixture(poisonPostCutoff); - const duck = createFakeDuckDbExecutor(fixture); - const ledger = createInMemoryTrialExecutor(); - - const store = createDuckDbMarketDataStore({ - executor: duck.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: fixture.vaultCutoffTs, - barBatchSize: 256, - }); - - const from = fixture.allDates[0]!; - const to = fixture.allDates[fixture.allDates.length - 1]!; - - const bars = await collectBars( - store.bars({ - listingIds: fixture.listingIds, - timeframe: '1d', - from, - to, - adjustment: 'raw', - }) - ); - const shortsTable = await store.shortsAsOf({ - listingIds: fixture.listingIds, - from, - to, - }); - - const signals = shortsTableToSignalRows(shortsTable, 'net_change'); - const built = buildForwardReturnPanel({ - bars, - signals, - horizonSessions: 5, - vaultCutoffDate: fixture.vaultCutoffDate, - }); - - const studyResult = await analyzeSignal(ledger.executor, { - principalId: 'operator', - universeMarket: 'CA_EQ', - horizonBucket: 'swing_1_10d', - expression: { - expression: 'ceoshorts_net_change_5d', - params: { field: 'net_change', horizonSessions: 5 }, - universe: 'CA_EQ_FIXTURE', - horizon: '5d', - }, - panel: built.panel, - vaultCutoffDate: fixture.vaultCutoffDate, - }); - - return { fixture, duck, ledger, built, studyResult }; - } - - it('fixture publishes each ceoShorts report after the close four sessions past report_date', () => { - const fixture = buildCeoShortsFixture(false); - expect(fixture.shortsRows.length).toBeGreaterThan(0); - for (const row of fixture.shortsRows) { - const reportIdx = fixture.allDates.indexOf(row.report_date as string); - const publishDate = fixture.allDates[reportIdx + 4]!; - expect(row.known_at).toBe(makeUtcMs(publishDate, 22)); - expect(row.known_at as number).toBeGreaterThan(makeUtcMs(publishDate, 21)); - } - }); - - it('flows DuckDbMarketDataStore -> buildForwardReturnPanel -> analyzeSignal -> trial_ledger + DSR', async () => { - const clean = await runCeoShortsStudy(false); - - // DuckDB connection budget SET statements ran exactly once. - expect(clean.duck.runStatements).toHaveLength(3); - expect(clean.duck.runStatements[0]).toContain('SET memory_limit'); - expect(clean.duck.runStatements[1]).toContain('SET threads'); - expect(clean.duck.runStatements[2]).toContain('SET temp_directory'); - expect(clean.duck.queryCount()).toBe(2); // 1 bars query + 1 shortsAsOf query - - // Panel Vault safety: no emitted date or forward session >= vaultCutoffDate. - expect(clean.built.panel.length).toBeGreaterThan(100); - for (const slice of clean.built.panel) { - expect(slice.date < clean.fixture.vaultCutoffDate).toBe(true); - const idx = clean.built.sessionDates.indexOf(slice.date); - expect(idx).toBeGreaterThanOrEqual(0); - expect(idx + 5).toBeLessThan(clean.built.sessionDates.length); - expect(clean.built.sessionDates[idx + 5]! < clean.fixture.vaultCutoffDate).toBe(true); - } - - // Signal study succeeded and inserted exactly one `signal_ic` row for CA_EQ. - expect(clean.studyResult.status).toBe('ok'); - if (clean.studyResult.status !== 'ok') { - return; - } - - expect(clean.ledger.rows).toHaveLength(1); - const stored = clean.ledger.rows[0]!; - expect(stored.stage).toBe('signal_ic'); - expect(stored.universe_market).toBe('CA_EQ'); - expect(stored.horizon_bucket).toBe('swing_1_10d'); - expect(clean.studyResult.trial.sampleEnd < clean.fixture.vaultCutoffDate).toBe(true); - expect(stored.sample_end < clean.fixture.vaultCutoffDate).toBe(true); - - // Finite DSR with effectiveTrials >= 1. - expect(clean.studyResult.deflatedSharpe.dsr).not.toBeNull(); - expect(Number.isFinite(clean.studyResult.deflatedSharpe.dsr!)).toBe(true); - expect(clean.studyResult.deflatedSharpe.effectiveTrials).toBeGreaterThanOrEqual(1); - - // Planted negative short-interest change -> next-5-session return relationship yields negative mean rank-IC. - expect(clean.studyResult.analysis.rankIc.mean).not.toBeNull(); - expect(clean.studyResult.analysis.rankIc.mean!).toBeLessThan(0); - - // Poisoning post-cutoff fixture bars leaves study result and trial_ledger row byte-identical. - const poisoned = await runCeoShortsStudy(true); - expect(poisoned.studyResult).toEqual(clean.studyResult); - expect(poisoned.ledger.rows).toEqual(clean.ledger.rows); - expect(poisoned.built).toEqual(clean.built); - }); -}); diff --git a/libs/research/test/signal-panel-qa.test.ts b/libs/research/test/signal-panel-qa.test.ts deleted file mode 100644 index 2ba94a03..00000000 --- a/libs/research/test/signal-panel-qa.test.ts +++ /dev/null @@ -1,540 +0,0 @@ -import { describe, expect, it } from 'bun:test'; -import { - SignalPanelError, - buildForwardReturnPanel, - type BarRecord, - type BuildForwardReturnPanelResult, - type SignalObservation, -} from '@stock-bot/research'; - -// QA suite for T-121: compares `buildForwardReturnPanel` against a deliberately naive -// O(n^2) reference model on seeded random panels (gaps, mixed EST/EDT close stamps, -// exact-close and after-close signals, bad closes, exact duplicates, post-cutoff bars), -// plus targeted PIT/Vault probes the authored suite does not pin down. - -const MS_PER_DAY = 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 makeUtcMs(date: string, hourUtc = 21, minuteUtc = 0, ms = 0): number { - const [y, m, d] = date.split('-').map(Number); - return Date.UTC(y!, m! - 1, d!, hourUtc, minuteUtc, 0, ms); -} - -function makeBusinessDates(startDate: string, count: number): string[] { - const out: string[] = []; - const current = new Date(`${startDate}T00:00:00.000Z`); - while (out.length < count) { - const day = current.getUTCDay(); - if (day !== 0 && day !== 6) { - out.push(current.toISOString().slice(0, 10)); - } - current.setUTCDate(current.getUTCDate() + 1); - } - return out; -} - -function makeBarAt(listingId: number, ts: number, close: number): BarRecord { - return { - listingId, - ts, - open: close, - high: close, - low: close, - close, - volume: 1_000, - vwap: close, - knownAt: ts, - }; -} - -function shuffle(items: readonly T[], seed: number): T[] { - const copy = [...items]; - const rand = createSeededRng(seed); - for (let i = copy.length - 1; i > 0; i -= 1) { - const j = Math.floor(rand() * (i + 1)); - const tmp = copy[i]!; - copy[i] = copy[j]!; - copy[j] = tmp; - } - return copy; -} - -interface ReferenceObservation { - readonly date: string; - readonly listingId: number; - readonly signal: number; - readonly forwardReturn: number; -} - -interface ReferenceResult { - readonly observations: ReferenceObservation[]; - readonly sessionDates: string[]; - readonly diagnostics: BuildForwardReturnPanelResult['diagnostics']; -} - -/** - * Naive reference implementation of the documented contract. Intentionally written - * with linear scans and plain objects so it shares no code paths with the optimized - * CSR / merge-pass implementation. - */ -function referencePanel( - bars: readonly BarRecord[], - signals: readonly SignalObservation[], - horizon: number, - vaultCutoffDate: string, - maxAge: number | undefined -): ReferenceResult { - const cutoffDayKey = Date.parse(`${vaultCutoffDate}T00:00:00.000Z`) / MS_PER_DAY; - const preBars = bars.filter(b => Math.floor(b.ts / MS_PER_DAY) < cutoffDayKey); - const postDays = new Set( - bars.map(b => Math.floor(b.ts / MS_PER_DAY)).filter(dk => dk >= cutoffDayKey) - ); - const dayKeys = [...new Set(preBars.map(b => Math.floor(b.ts / MS_PER_DAY)))].sort( - (a, b) => a - b - ); - const sessionDates = dayKeys.map(dk => new Date(dk * MS_PER_DAY).toISOString().slice(0, 10)); - const sessionMaxTs = dayKeys.map(dk => - Math.max(...preBars.filter(b => Math.floor(b.ts / MS_PER_DAY) === dk).map(b => b.ts)) - ); - const preCount = dayKeys.length; - const emittable = Math.max(0, preCount - horizon); - const hasPost = postDays.size > 0; - - let duplicateBars = 0; - let droppedNoSignal = 0; - let droppedStaleSignal = 0; - let droppedMissingForwardBar = 0; - let droppedNonPositiveClose = 0; - const observations: ReferenceObservation[] = []; - - const listingIds = [...new Set(preBars.map(b => b.listingId))].sort((a, b) => a - b); - for (const lid of listingIds) { - const bySession = new Map(); - for (const b of preBars.filter(x => x.listingId === lid)) { - const s = dayKeys.indexOf(Math.floor(b.ts / MS_PER_DAY)); - const prev = bySession.get(s); - if (prev !== undefined) { - const same = - prev.ts === b.ts && (Object.is(prev.close, b.close) || prev.close === b.close); - if (!same) { - throw new Error('reference: conflicting duplicate'); - } - duplicateBars += 1; - continue; - } - bySession.set(s, b); - } - const listingSignals = signals.filter(s => s.listingId === lid); - - for (const [t, bar] of [...bySession.entries()].sort((a, b) => a[0] - b[0])) { - if (hasPost && t >= emittable) { - continue; - } - let active: SignalObservation | undefined; - for (const s of listingSignals) { - if (s.knownAt > bar.ts) { - continue; - } - if ( - active === undefined || - s.knownAt > active.knownAt || - (s.knownAt === active.knownAt && s.value > active.value) - ) { - active = s; - } - } - if (active === undefined) { - droppedNoSignal += 1; - continue; - } - if (maxAge !== undefined) { - let first = sessionMaxTs.findIndex(mx => mx >= active!.knownAt); - if (first < 0) { - first = preCount; - } - if (t - first > maxAge) { - droppedStaleSignal += 1; - continue; - } - } - const fwd = bySession.get(t + horizon); - if (t + horizon >= preCount || fwd === undefined) { - droppedMissingForwardBar += 1; - continue; - } - const c0 = bar.close; - const c1 = fwd.close; - if (!Number.isFinite(c0) || c0 <= 0 || !Number.isFinite(c1) || c1 <= 0) { - droppedNonPositiveClose += 1; - continue; - } - observations.push({ - date: sessionDates[t]!, - listingId: lid, - signal: active.value === 0 ? 0 : active.value, - forwardReturn: c1 / c0 - 1 === 0 ? 0 : c1 / c0 - 1, - }); - } - } - - observations.sort((a, b) => (a.date < b.date ? -1 : a.date > b.date ? 1 : a.listingId - b.listingId)); - return { - observations, - sessionDates, - diagnostics: { - vaultExcludedDates: hasPost ? preCount - emittable + postDays.size : 0, - droppedNoSignal, - droppedStaleSignal, - droppedMissingForwardBar, - droppedNonPositiveClose, - duplicateBars, - }, - }; -} - -function flattenPanel(result: BuildForwardReturnPanelResult): ReferenceObservation[] { - const out: ReferenceObservation[] = []; - for (const slice of result.panel) { - for (let i = 0; i < slice.ids.length; i += 1) { - out.push({ - date: slice.date, - listingId: slice.ids[i]!, - signal: slice.signal[i]!, - forwardReturn: slice.forwardReturn[i]!, - }); - } - } - return out; -} - -interface RandomPanel { - readonly bars: BarRecord[]; - readonly signals: SignalObservation[]; - readonly dates: string[]; -} - -function buildRandomPanel(seed: number): RandomPanel { - const rand = createSeededRng(seed); - const sessionCount = 30 + Math.floor(rand() * 30); - const listingCount = 3 + Math.floor(rand() * 8); - const dates = makeBusinessDates('2023-02-20', sessionCount); // straddles the March DST switch - const bars: BarRecord[] = []; - const signals: SignalObservation[] = []; - - for (let l = 0; l < listingCount; l += 1) { - const listingId = 1_000 - l * 37; // descending ids to exercise id sorting - let price = 20 + l; - for (let t = 0; t < sessionCount; t += 1) { - price *= 1 + (rand() - 0.5) * 0.04; - if (rand() < 0.12) { - continue; // gap - } - const closeHourUtc = rand() < 0.5 ? 20 : 21; // EDT vs EST close stamp - const ts = makeUtcMs(dates[t]!, closeHourUtc); - const roll = rand(); - const close = - roll < 0.03 ? 0 : roll < 0.05 ? Number.NaN : roll < 0.06 ? -1 : Number(price.toFixed(4)); - const bar = makeBarAt(listingId, ts, close); - bars.push(bar); - if (rand() < 0.05) { - bars.push({ ...bar }); // exact duplicate - } - - const sigRoll = rand(); - if (sigRoll < 0.15) { - signals.push({ listingId, knownAt: ts, value: Math.round(rand() * 100) / 10 }); // exactly at close - } else if (sigRoll < 0.3) { - signals.push({ listingId, knownAt: ts + 1, value: Math.round(rand() * 100) / 10 }); // 1 ms after - } else if (sigRoll < 0.4) { - signals.push({ listingId, knownAt: ts + 3_600_000, value: -Math.round(rand() * 100) / 10 }); - } else if (sigRoll < 0.45) { - // Equal-knownAt tie pair. - const knownAt = makeUtcMs(dates[t]!, 13); - signals.push({ listingId, knownAt, value: 1 }, { listingId, knownAt, value: 2 }); - } - } - } - // Signals for an unknown listing must be ignored. - signals.push({ listingId: 7, knownAt: makeUtcMs(dates[0]!, 10), value: 99 }); - return { bars, signals, dates }; -} - -describe('buildForwardReturnPanel vs naive reference model (seeded)', () => { - it('matches the reference panel, sessionDates and diagnostics across random panels', () => { - let totalEmitted = 0; - let totalStale = 0; - let totalExcluded = 0; - for (let seed = 1; seed <= 60; seed += 1) { - const { bars, signals, dates } = buildRandomPanel(seed); - const rand = createSeededRng(seed * 7919); - const horizon = [1, 2, 5, 20][seed % 4]!; - const maxAge = seed % 3 === 0 ? undefined : Math.floor(rand() * 6); - // Cutoff either inside the sample (post-cutoff bars exist) or after it. - const cutoff = - seed % 5 === 0 ? '2030-01-01' : dates[Math.floor(dates.length * (0.6 + rand() * 0.3))]!; - - const actual = buildForwardReturnPanel({ - bars: shuffle(bars, seed), - signals: shuffle(signals, seed + 1), - horizonSessions: horizon, - vaultCutoffDate: cutoff, - maxSignalAgeSessions: maxAge, - }); - const expected = referencePanel(bars, signals, horizon, cutoff, maxAge); - - expect(actual.sessionDates).toEqual(expected.sessionDates); - expect(actual.diagnostics).toEqual(expected.diagnostics); - const flat = flattenPanel(actual); - expect(flat.length).toBe(expected.observations.length); - for (let i = 0; i < flat.length; i += 1) { - const a = flat[i]!; - const e = expected.observations[i]!; - expect(a.date).toBe(e.date); - expect(a.listingId).toBe(e.listingId); - expect(a.signal).toBe(e.signal); - expect(a.forwardReturn).toBe(e.forwardReturn); - } - - // Structural invariants on the emitted panel. - for (let p = 0; p < actual.panel.length; p += 1) { - const slice = actual.panel[p]!; - expect(slice.ids.length).toBeGreaterThan(0); - expect(slice.date < cutoff).toBe(true); - const t = actual.sessionDates.indexOf(slice.date); - expect(t + horizon).toBeLessThan(actual.sessionDates.length); - if (p > 0) { - expect(actual.panel[p - 1]!.date < slice.date).toBe(true); - } - for (let i = 1; i < slice.ids.length; i += 1) { - expect(slice.ids[i]!).toBeGreaterThan(slice.ids[i - 1]!); - } - } - totalEmitted += flat.length; - totalStale += actual.diagnostics.droppedStaleSignal; - totalExcluded += actual.diagnostics.vaultExcludedDates; - } - // Guard against a vacuous fixture: every branch was actually exercised. - expect(totalEmitted).toBeGreaterThan(1_000); - expect(totalStale).toBeGreaterThan(0); - expect(totalExcluded).toBeGreaterThan(0); - }); -}); - -describe('buildForwardReturnPanel point-in-time probes', () => { - it('activates a signal published 1 ms after a close on the very next session (not superseded)', () => { - const dates = makeBusinessDates('2024-03-04', 6); - const bars = dates.map((d, i) => makeBarAt(1, makeUtcMs(d), 100 + i)); - const day0Close = makeUtcMs(dates[0]!); - const day2Close = makeUtcMs(dates[2]!); - const result = buildForwardReturnPanel({ - bars, - signals: [ - { listingId: 1, knownAt: day0Close + 1, value: 10 }, - { listingId: 1, knownAt: day2Close, value: 20 }, - ], - horizonSessions: 1, - vaultCutoffDate: '2025-01-01', - }); - expect(result.panel.map(s => [s.date, s.signal[0]])).toEqual([ - [dates[1], 10], - [dates[2], 20], - [dates[3], 20], - [dates[4], 20], - ]); - expect(result.diagnostics.droppedNoSignal).toBe(1); - }); - - it('adding future signals never changes the signal used on earlier dates (poison test)', () => { - for (let seed = 101; seed <= 115; seed += 1) { - const { bars, signals, dates } = buildRandomPanel(seed); - const base = { bars, horizonSessions: 1, vaultCutoffDate: '2030-01-01' } as const; - const pivot = Math.floor(dates.length / 2); - // Truncate to signals known on or before the pivot close, then poison with absurd - // values published 1 ms after the pivot session's latest close. - const pivotMaxTs = Math.max( - ...bars.filter(b => new Date(b.ts).toISOString().slice(0, 10) === dates[pivot]).map(b => b.ts) - ); - const truncated = signals.filter(s => s.knownAt <= pivotMaxTs); - const poison: SignalObservation[] = [...new Set(bars.map(b => b.listingId))].map(lid => ({ - listingId: lid, - knownAt: pivotMaxTs + 1, - value: 1e12, - })); - - const clean = buildForwardReturnPanel({ ...base, signals: truncated }); - const poisoned = buildForwardReturnPanel({ ...base, signals: [...truncated, ...poison] }); - const pivotDate = dates[pivot]!; - const pick = (r: BuildForwardReturnPanelResult) => - flattenPanel(r).filter(o => o.date <= pivotDate); - expect(pick(poisoned)).toEqual(pick(clean)); - expect(pick(clean).length).toBeGreaterThan(0); - expect(flattenPanel(poisoned).some(o => o.signal === 1e12)).toBe(true); - } - }); - - it('uses each listing’s own close time for PIT, not the latest close across listings', () => { - // Listing 1 closes 20:00 UTC, listing 2 closes 21:00 UTC on the same session date. - const dates = makeBusinessDates('2024-04-01', 4); - const bars = dates.flatMap((d, i) => [ - makeBarAt(1, makeUtcMs(d, 20), 100 + i), - makeBarAt(2, makeUtcMs(d, 21), 200 + i), - ]); - const knownAt = makeUtcMs(dates[0]!, 20, 30); - const result = buildForwardReturnPanel({ - bars, - signals: [ - { listingId: 1, knownAt, value: 1 }, - { listingId: 2, knownAt, value: 2 }, - ], - horizonSessions: 1, - vaultCutoffDate: '2025-01-01', - }); - // Day 0: listing 1 bar at 20:00 precedes knownAt 20:30 -> dropped; listing 2 at 21:00 -> used. - expect(result.panel[0]!.date).toBe(dates[0]); - expect(Array.from(result.panel[0]!.ids)).toEqual([2]); - expect(Array.from(result.panel[1]!.ids)).toEqual([1, 2]); - expect(result.diagnostics.droppedNoSignal).toBe(1); - }); -}); - -describe('buildForwardReturnPanel Vault fence probes', () => { - it('treats a bar at 00:00 UTC on the cutoff date as Vault and 23:59:59.999 the day before as pre-cutoff', () => { - const cutoff = '2024-06-10'; - const preTs = Date.parse('2024-06-09T23:59:59.999Z'); - const postTs = Date.parse('2024-06-10T00:00:00.000Z'); - let postReads = 0; - const trapped = { ...makeBarAt(1, postTs, 1) } as Record; - Object.defineProperty(trapped, 'close', { - enumerable: true, - get() { - postReads += 1; - return 1; - }, - }); - const result = buildForwardReturnPanel({ - bars: [ - makeBarAt(1, Date.parse('2024-06-07T20:00:00.000Z'), 100), - makeBarAt(1, preTs, 110), - trapped as unknown as BarRecord, - ], - signals: [{ listingId: 1, knownAt: 0, value: 1 }], - horizonSessions: 1, - vaultCutoffDate: cutoff, - }); - expect(postReads).toBe(0); - expect(result.sessionDates).toEqual(['2024-06-07', '2024-06-09']); - expect(result.panel).toHaveLength(1); - expect(result.panel[0]!.forwardReturn[0]).toBeCloseTo(0.1, 12); - // h = 1 tail session + 1 post-cutoff day. - expect(result.diagnostics.vaultExcludedDates).toBe(2); - }); - - it('never emits a date whose forward session is in the Vault, even when only another listing reaches the cutoff', () => { - // Listing 1 stops trading well before the cutoff; listing 2 continues into the Vault. - const dates = makeBusinessDates('2024-01-02', 20); - const cutoff = dates[15]!; - const bars: BarRecord[] = []; - for (let t = 0; t < dates.length; t += 1) { - if (t < 10) { - bars.push(makeBarAt(1, makeUtcMs(dates[t]!), 100 + t)); - } - bars.push(makeBarAt(2, makeUtcMs(dates[t]!), 50 + t)); - } - const result = buildForwardReturnPanel({ - bars, - signals: [ - { listingId: 1, knownAt: 0, value: 1 }, - { listingId: 2, knownAt: 0, value: 2 }, - ], - horizonSessions: 3, - vaultCutoffDate: cutoff, - }); - const last = result.panel[result.panel.length - 1]!; - expect(last.date).toBe(dates[11]); // 15 pre-cutoff sessions, last emittable index 15 - 1 - 3 - for (const slice of result.panel) { - const t = dates.indexOf(slice.date); - expect(dates[t + 3]! < cutoff).toBe(true); - } - }); - - it('rejects conflicting duplicates only before the cutoff and ignores them inside the Vault', () => { - const dates = makeBusinessDates('2024-01-02', 4); - const cutoff = dates[2]!; - const vaultBar = makeBarAt(1, makeUtcMs(dates[3]!), 100); - const ok = buildForwardReturnPanel({ - bars: [ - makeBarAt(1, makeUtcMs(dates[0]!), 100), - makeBarAt(1, makeUtcMs(dates[1]!), 101), - vaultBar, - { ...vaultBar, close: 999 }, - ], - signals: [{ listingId: 1, knownAt: 0, value: 1 }], - horizonSessions: 1, - vaultCutoffDate: cutoff, - }); - expect(ok.panel).toHaveLength(1); - - expect(() => - buildForwardReturnPanel({ - bars: [makeBarAt(1, makeUtcMs(dates[0]!), 100), makeBarAt(1, makeUtcMs(dates[0]!, 20), 100)], - signals: [], - horizonSessions: 1, - vaultCutoffDate: cutoff, - }) - ).toThrow(SignalPanelError); - }); -}); - -describe('buildForwardReturnPanel calendar edge cases', () => { - it('uses the sparse Map calendar path for spans above 200,000 days and stays exact', () => { - // ~600 years apart -> day span > 200,000 forces the Map lookup branch. - const ancient = Date.UTC(1500, 0, 3, 21); - const bars = [ - makeBarAt(1, ancient, 10), - makeBarAt(1, Date.UTC(2100, 0, 4, 21), 20), - makeBarAt(1, Date.UTC(2100, 0, 5, 21), 30), - ]; - const result = buildForwardReturnPanel({ - bars: shuffle(bars, 3), - signals: [{ listingId: 1, knownAt: ancient, value: 5 }], - horizonSessions: 1, - vaultCutoffDate: '2200-01-01', - }); - expect(result.sessionDates).toEqual(['1500-01-03', '2100-01-04', '2100-01-05']); - expect(result.panel.map(s => [s.date, s.forwardReturn[0]])).toEqual([ - ['1500-01-03', 1], - ['2100-01-04', 0.5], - ]); - }); - - it('measures horizon in shared calendar sessions, so a holiday for one listing is a missing forward bar', () => { - const dates = makeBusinessDates('2024-07-01', 5); - const bars = [ - ...dates.map((d, i) => makeBarAt(1, makeUtcMs(d), 100 + i)), - // Listing 2 is closed on dates[2] (e.g. a cross-listed holiday). - ...dates.filter((_, i) => i !== 2).map((d, i) => makeBarAt(2, makeUtcMs(d), 200 + i)), - ]; - const result = buildForwardReturnPanel({ - bars, - signals: [ - { listingId: 1, knownAt: 0, value: 1 }, - { listingId: 2, knownAt: 0, value: 2 }, - ], - horizonSessions: 1, - vaultCutoffDate: '2025-01-01', - }); - const day1 = result.panel.find(s => s.date === dates[1])!; - expect(Array.from(day1.ids)).toEqual([1]); - // Listing 2 has no bar on dates[2]: dropped as entry (no row) and as exit for dates[1]. - expect(result.panel.find(s => s.date === dates[2])!.ids.length).toBe(1); - }); -}); diff --git a/libs/research/test/signal-panel.test.ts b/libs/research/test/signal-panel.test.ts deleted file mode 100644 index 6f4ca1c5..00000000 --- a/libs/research/test/signal-panel.test.ts +++ /dev/null @@ -1,766 +0,0 @@ -import { describe, expect, it } from 'bun:test'; -import { readFileSync } from 'node:fs'; -import { - SHORTS_SIGNAL_FIELDS, - SignalPanelError, - buildForwardReturnPanel, - collectBars, - shortsTableToSignalRows, - type BarBatch, - type BarRecord, - type SignalObservation, - type SignalPanelErrorCode, - type Table, -} from '@stock-bot/research'; -import { - SHORTS_SIGNAL_FIELDS as SubpathShortsSignalFields, - SignalPanelError as SubpathSignalPanelError, - buildForwardReturnPanel as subpathBuildForwardReturnPanel, - collectBars as subpathCollectBars, - shortsTableToSignalRows as subpathShortsTableToSignalRows, -} from '@stock-bot/research/signal-panel'; - -function makeUtcMs(date: string, hourUtc = 21, minuteUtc = 0, secondUtc = 0, ms = 0): number { - const [y, m, d] = date.split('-').map(Number); - return Date.UTC(y!, m! - 1, d!, hourUtc, minuteUtc, secondUtc, ms); -} - -function makeBusinessDates(startDate: string, count: number): string[] { - const out: string[] = new Array(count); - const current = new Date(`${startDate}T00:00:00.000Z`); - let written = 0; - while (written < count) { - const day = current.getUTCDay(); - if (day !== 0 && day !== 6) { - out[written] = current.toISOString().slice(0, 10); - written += 1; - } - current.setUTCDate(current.getUTCDate() + 1); - } - return out; -} - -function makeBar(listingId: number, date: string, close: number, hourUtc = 21): BarRecord { - const ts = makeUtcMs(date, hourUtc, 0, 0, 0); - return { - listingId, - ts, - open: close, - high: close, - low: close, - close, - volume: 1_000, - vwap: close, - knownAt: ts, - }; -} - -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 shuffle(items: readonly T[], seed: number): T[] { - const copy = [...items]; - const rand = createSeededRng(seed); - for (let i = copy.length - 1; i > 0; i -= 1) { - const j = Math.floor(rand() * (i + 1)); - const tmp = copy[i]!; - copy[i] = copy[j]!; - copy[j] = tmp; - } - return copy; -} - -function expectSignalPanelError(fn: () => unknown, code: SignalPanelErrorCode): SignalPanelError { - try { - fn(); - } catch (err) { - expect(err).toBeInstanceOf(SignalPanelError); - const typed = err as SignalPanelError; - expect(typed.code).toBe(code); - return typed; - } - throw new Error(`Expected SignalPanelError(${code}), but function did not throw.`); -} - -async function expectSignalPanelErrorAsync( - fn: () => Promise, - code: SignalPanelErrorCode -): Promise { - try { - await fn(); - } catch (err) { - expect(err).toBeInstanceOf(SignalPanelError); - const typed = err as SignalPanelError; - expect(typed.code).toBe(code); - return typed; - } - throw new Error(`Expected async SignalPanelError(${code}), but promise resolved.`); -} - -describe('@stock-bot/research signal-panel exports and browser safety', () => { - it('exposes identical symbols from root and ./signal-panel subpath', () => { - expect(buildForwardReturnPanel).toBe(subpathBuildForwardReturnPanel); - expect(shortsTableToSignalRows).toBe(subpathShortsTableToSignalRows); - expect(collectBars).toBe(subpathCollectBars); - expect(SignalPanelError).toBe(SubpathSignalPanelError); - expect(SHORTS_SIGNAL_FIELDS).toBe(SubpathShortsSignalFields); - }); - - it('has zero node:* imports, zero bare process access, and no new package dependencies', () => { - const src = readFileSync(new URL('../src/signal-panel.ts', import.meta.url), 'utf8'); - expect(src).not.toMatch(/from\s+['"]node:/); - expect(src).not.toMatch(/require\s*\(\s*['"]node:/); - expect(src).not.toMatch(/\bprocess\./); - - const pkg = JSON.parse( - readFileSync(new URL('../package.json', import.meta.url), 'utf8') - ) as { - exports: Record; - dependencies: Record; - }; - expect(pkg.exports['./signal-panel']).toBe('./src/signal-panel.ts'); - expect(Object.keys(pkg.dependencies).sort()).toEqual([ - '@stock-bot/calculations', - '@stock-bot/stock-config', - '@stock-bot/types', - 'zod', - ]); - }); -}); - -describe('buildForwardReturnPanel', () => { - it('computes exact hand-verified forward returns for horizons 1, 5, and 20', () => { - const dates = makeBusinessDates('2024-01-02', 25); - const bars: BarRecord[] = []; - const signals: SignalObservation[] = []; - - // Listing 20 and Listing 10 intentionally inserted out of order to verify ascending ids. - for (let i = 0; i < dates.length; i += 1) { - bars.push(makeBar(20, dates[i]!, 100 + i * 2)); - bars.push(makeBar(10, dates[i]!, 50 + i)); - } - signals.push( - { listingId: 10, knownAt: makeUtcMs(dates[0]!, 20), value: 1.5 }, - { listingId: 20, knownAt: makeUtcMs(dates[0]!, 20), value: -2.5 } - ); - - for (const horizon of [1, 5, 20] as const) { - const result = buildForwardReturnPanel({ - bars, - signals, - horizonSessions: horizon, - vaultCutoffDate: '2025-01-01', - }); - - const expectedEmittedDates = dates.length - horizon; - expect(result.sessionDates).toEqual(dates); - expect(result.panel).toHaveLength(expectedEmittedDates); - expect(result.diagnostics.vaultExcludedDates).toBe(0); - expect(result.diagnostics.droppedNoSignal).toBe(0); - expect(result.diagnostics.droppedStaleSignal).toBe(0); - expect(result.diagnostics.droppedMissingForwardBar).toBe(horizon * 2); - expect(result.diagnostics.droppedNonPositiveClose).toBe(0); - expect(result.diagnostics.duplicateBars).toBe(0); - - let emittedObs = 0; - for (let t = 0; t < expectedEmittedDates; t += 1) { - const slice = result.panel[t]!; - expect(slice.date).toBe(dates[t]); - expect(slice.ids).toBeInstanceOf(Int32Array); - expect(slice.signal).toBeInstanceOf(Float64Array); - expect(slice.forwardReturn).toBeInstanceOf(Float64Array); - expect(Array.from(slice.ids)).toEqual([10, 20]); - expect(Array.from(slice.signal)).toEqual([1.5, -2.5]); - - const expectedRet10 = (50 + t + horizon) / (50 + t) - 1; - const expectedRet20 = (100 + (t + horizon) * 2) / (100 + t * 2) - 1; - expect(slice.forwardReturn[0]).toBeCloseTo(expectedRet10, 12); - expect(slice.forwardReturn[1]).toBeCloseTo(expectedRet20, 12); - emittedObs += slice.ids.length; - } - - // Conservation identity: emitted + all drops === unique pre-cutoff bars. - const totalDrops = - result.diagnostics.droppedNoSignal + - result.diagnostics.droppedStaleSignal + - result.diagnostics.droppedMissingForwardBar + - result.diagnostics.droppedNonPositiveClose; - expect(emittedObs + totalDrops).toBe(bars.length); - } - }); - - it('enforces strict knownAt <= bar.ts point-in-time rule and deterministic tie-breaking', () => { - const dates = makeBusinessDates('2024-03-04', 5); - const bars: BarRecord[] = dates.map((d, idx) => makeBar(1, d, 100 + idx * 10)); - - const day0CloseTs = makeUtcMs(dates[0]!, 21, 0, 0, 0); - const day1CloseTs = makeUtcMs(dates[1]!, 21, 0, 0, 0); - const signals: SignalObservation[] = [ - // Known 1 ms AFTER day 0 close -> must NOT apply on day 0, MUST apply on day 1. - { listingId: 1, knownAt: day0CloseTs + 1, value: 10 }, - // Known EXACTLY at day 1 close -> MUST apply on day 1, overriding the day0+1ms signal. - { listingId: 1, knownAt: day1CloseTs, value: 20 }, - // Tie at exact same knownAt on day 1 close -> deterministic max value (25) regardless of order. - { listingId: 1, knownAt: day1CloseTs, value: 25 }, - ]; - - const result = buildForwardReturnPanel({ - bars, - signals, - horizonSessions: 1, - vaultCutoffDate: '2025-01-01', - }); - - expect(result.diagnostics.droppedNoSignal).toBe(1); // day 0 had no eligible signal - expect(result.panel.map(s => s.date)).toEqual([dates[1], dates[2], dates[3]]); - expect(result.panel[0]!.signal[0]).toBe(25); - expect(result.panel[1]!.signal[0]).toBe(25); - expect(result.panel[2]!.signal[0]).toBe(25); - - // Reverse signal order must produce the exact same tie-break value. - const reversed = buildForwardReturnPanel({ - bars, - signals: [...signals].reverse(), - horizonSessions: 1, - vaultCutoffDate: '2025-01-01', - }); - expect(reversed.panel.map(s => s.signal[0])).toEqual([25, 25, 25]); - }); - - it('drops observations whose forward bar at d + h is missing instead of shifting to d + h + 1', () => { - const dates = makeBusinessDates('2024-04-01', 6); - // Listing 1 has all 6 sessions; Listing 2 is missing dates[3]. - const bars: BarRecord[] = []; - for (let i = 0; i < dates.length; i += 1) { - bars.push(makeBar(1, dates[i]!, 100 + i)); - if (i !== 3) { - bars.push(makeBar(2, dates[i]!, 200 + i)); - } - } - const signals: SignalObservation[] = [ - { listingId: 1, knownAt: makeUtcMs(dates[0]!, 10), value: 1 }, - { listingId: 2, knownAt: makeUtcMs(dates[0]!, 10), value: 2 }, - ]; - - const result = buildForwardReturnPanel({ - bars, - signals, - horizonSessions: 2, - vaultCutoffDate: '2025-01-01', - }); - - // On dates[1], target is dates[3]. Listing 2 has no bar on dates[3], so it must be dropped - // rather than using dates[4]. - const sliceDay1 = result.panel.find(s => s.date === dates[1])!; - expect(Array.from(sliceDay1.ids)).toEqual([1]); - // On dates[2], target is dates[4], which Listing 2 DOES have. - const sliceDay2 = result.panel.find(s => s.date === dates[2])!; - expect(Array.from(sliceDay2.ids)).toEqual([1, 2]); - expect(sliceDay2.forwardReturn[1]).toBeCloseTo(204 / 202 - 1, 12); - - // Missing forward bars: Listing 1 misses dates[4], dates[5] (2); - // Listing 2 misses dates[1] (-> dates[3]), dates[4], dates[5] (3). Total = 5. - expect(result.diagnostics.droppedMissingForwardBar).toBe(5); - }); - - it('enforces maxSignalAgeSessions including age 0 and after-close 17:00 ET signals', () => { - const dates = makeBusinessDates('2024-05-06', 6); - const bars: BarRecord[] = dates.map((d, idx) => makeBar(1, d, 100 + idx, 20)); // 16:00 EDT = 20:00 UTC - - // Signal published at 17:00 EDT (21:00 UTC) on dates[0] -> first actionable session is dates[1] (age 0). - const signals: SignalObservation[] = [ - { listingId: 1, knownAt: makeUtcMs(dates[0]!, 21, 0), value: 3.14 }, - ]; - - // maxSignalAgeSessions = 0: only dates[1] is emitted; dates[2], dates[3], dates[4], dates[5] are stale. - const age0 = buildForwardReturnPanel({ - bars, - signals, - horizonSessions: 1, - vaultCutoffDate: '2025-01-01', - maxSignalAgeSessions: 0, - }); - expect(age0.panel.map(s => s.date)).toEqual([dates[1]]); - expect(age0.diagnostics.droppedNoSignal).toBe(1); // dates[0] - expect(age0.diagnostics.droppedStaleSignal).toBe(4); // dates[2..5] - - // maxSignalAgeSessions = 2: dates[1] (age 0), dates[2] (age 1), dates[3] (age 2) emitted; - // dates[4] (age 3) and dates[5] (age 4) dropped as stale. - const age2 = buildForwardReturnPanel({ - bars, - signals, - horizonSessions: 1, - vaultCutoffDate: '2025-01-01', - maxSignalAgeSessions: 2, - }); - expect(age2.panel.map(s => s.date)).toEqual([dates[1], dates[2], dates[3]]); - expect(age2.diagnostics.droppedNoSignal).toBe(1); - expect(age2.diagnostics.droppedStaleSignal).toBe(2); - }); - - it('drops non-positive and non-finite entry/exit closes into droppedNonPositiveClose without throwing', () => { - const dates = makeBusinessDates('2024-06-03', 6); - const closes = [100, 0, -5, Number.NaN, Number.POSITIVE_INFINITY, 120]; - const bars: BarRecord[] = dates.map((d, i) => makeBar(1, d, closes[i]!)); - // Add a clean listing so we also verify normal rows survive alongside bad closes. - for (let i = 0; i < dates.length; i += 1) { - bars.push(makeBar(2, dates[i]!, 50 + i)); - } - - const signals: SignalObservation[] = [ - { listingId: 1, knownAt: makeUtcMs(dates[0]!, 10), value: 1 }, - { listingId: 2, knownAt: makeUtcMs(dates[0]!, 10), value: 2 }, - ]; - - const result = buildForwardReturnPanel({ - bars, - signals, - horizonSessions: 1, - vaultCutoffDate: '2025-01-01', - }); - - // Every pair for listing 1 touches a non-positive/non-finite close (0->1, 1->2, 2->3, 3->4, 4->5). - expect(result.diagnostics.droppedNonPositiveClose).toBe(5); - expect(result.panel).toHaveLength(5); - for (const slice of result.panel) { - expect(Array.from(slice.ids)).toEqual([2]); - } - }); - - it('deduplicates exact pre-cutoff bars and rejects conflicting duplicates', () => { - const dates = makeBusinessDates('2024-07-01', 3); - const b0 = makeBar(1, dates[0]!, 100); - const b1 = makeBar(1, dates[1]!, 110); - const b2 = makeBar(1, dates[2]!, 121); - const bNaN = makeBar(2, dates[0]!, Number.NaN); - - const result = buildForwardReturnPanel({ - bars: [b0, { ...b0 }, b1, b2, bNaN, { ...bNaN }], - signals: [{ listingId: 1, knownAt: makeUtcMs(dates[0]!, 10), value: 1 }], - horizonSessions: 1, - vaultCutoffDate: '2025-01-01', - }); - - expect(result.diagnostics.duplicateBars).toBe(2); - expect(result.panel).toHaveLength(2); - expect(result.panel[0]!.forwardReturn[0]).toBeCloseTo(0.1, 12); - - // Conflicting close on same (listingId, date) must throw duplicate_bar. - expectSignalPanelError( - () => - buildForwardReturnPanel({ - bars: [b0, { ...b0, close: 101 }, b1], - signals: [], - horizonSessions: 1, - vaultCutoffDate: '2025-01-01', - }), - 'duplicate_bar' - ); - - // Conflicting ts on same (listingId, date) must throw duplicate_bar. - expectSignalPanelError( - () => - buildForwardReturnPanel({ - bars: [b0, { ...b0, ts: b0.ts + 1_000 }, b1], - signals: [], - horizonSessions: 1, - vaultCutoffDate: '2025-01-01', - }), - 'duplicate_bar' - ); - }); - - it('enforces strict Vault cutoff across both d and d + h and never reads post-cutoff closes', () => { - const preCutoffCount = 30; - const postCutoffCount = 6; - const allDates = makeBusinessDates('2024-01-02', preCutoffCount + postCutoffCount); - const vaultCutoffDate = allDates[preCutoffCount]!; - - const baseBars: BarRecord[] = []; - for (let i = 0; i < allDates.length; i += 1) { - baseBars.push(makeBar(1, allDates[i]!, 100 + i)); - baseBars.push(makeBar(2, allDates[i]!, 200 + i * 2)); - } - const signals: SignalObservation[] = [ - { listingId: 1, knownAt: makeUtcMs(allDates[0]!, 10), value: 0.5 }, - { listingId: 2, knownAt: makeUtcMs(allDates[0]!, 10), value: -0.5 }, - ]; - - for (const horizon of [1, 5, 20] as const) { - const clean = buildForwardReturnPanel({ - bars: baseBars, - signals, - horizonSessions: horizon, - vaultCutoffDate, - }); - - const expectedEmittable = preCutoffCount - horizon; - expect(clean.sessionDates).toEqual(allDates.slice(0, preCutoffCount)); - expect(clean.sessionDates.every(d => d < vaultCutoffDate)).toBe(true); - expect(clean.panel).toHaveLength(expectedEmittable); - expect(clean.panel[clean.panel.length - 1]!.date).toBe(allDates[preCutoffCount - 1 - horizon]); - expect(clean.diagnostics.vaultExcludedDates).toBe(horizon + postCutoffCount); - - for (const slice of clean.panel) { - const idx = clean.sessionDates.indexOf(slice.date); - expect(idx).toBeGreaterThanOrEqual(0); - expect(slice.date < vaultCutoffDate).toBe(true); - const fwdDate = allDates[idx + horizon]!; - expect(fwdDate < vaultCutoffDate).toBe(true); - } - - // Poison every post-cutoff close with NaN -> output must be byte-identical. - const poisonedBars: BarRecord[] = baseBars.map(b => { - const date = new Date(b.ts).toISOString().slice(0, 10); - return date >= vaultCutoffDate ? { ...b, close: Number.NaN } : b; - }); - const poisoned = buildForwardReturnPanel({ - bars: poisonedBars, - signals, - horizonSessions: horizon, - vaultCutoffDate, - }); - expect(poisoned).toEqual(clean); - - // Getter trap on every post-cutoff bar's `close` -> must never be accessed. - let closeReadsPostCutoff = 0; - const trappedBars: BarRecord[] = baseBars.map(b => { - const date = new Date(b.ts).toISOString().slice(0, 10); - if (date < vaultCutoffDate) { - return b; - } - const trapped = { - listingId: b.listingId, - ts: b.ts, - open: b.open, - high: b.high, - low: b.low, - volume: b.volume, - vwap: b.vwap, - knownAt: b.knownAt, - } as Record; - Object.defineProperty(trapped, 'close', { - enumerable: true, - get() { - closeReadsPostCutoff += 1; - throw new Error('Post-cutoff close must never be read!'); - }, - }); - return trapped as unknown as BarRecord; - }); - - const trappedResult = buildForwardReturnPanel({ - bars: trappedBars, - signals, - horizonSessions: horizon, - vaultCutoffDate, - }); - expect(closeReadsPostCutoff).toBe(0); - expect(trappedResult).toEqual(clean); - } - }); - - it('produces byte-identical output for shuffled bars and signals and never mutates frozen inputs', () => { - const dates = makeBusinessDates('2024-08-01', 15); - const bars: BarRecord[] = []; - const signals: SignalObservation[] = []; - - for (const lid of [101, 202, 303, 404]) { - for (let i = 0; i < dates.length; i += 1) { - bars.push(makeBar(lid, dates[i]!, 50 + lid * 0.1 + i * 0.5)); - } - signals.push( - { listingId: lid, knownAt: makeUtcMs(dates[0]!, 18), value: lid * 0.01 }, - { listingId: lid, knownAt: makeUtcMs(dates[4]!, 21), value: lid * -0.02 }, - { listingId: lid, knownAt: makeUtcMs(dates[4]!, 21), value: lid * 0.03 } // intentional tie - ); - } - - const frozenInput = Object.freeze({ - bars: Object.freeze(bars.map(b => Object.freeze({ ...b }))), - signals: Object.freeze(signals.map(s => Object.freeze({ ...s }))), - horizonSessions: 3, - vaultCutoffDate: dates[12]!, - maxSignalAgeSessions: 6, - }); - - const baseline = buildForwardReturnPanel(frozenInput); - - for (const seed of [1, 2, 3, 42]) { - const shuffledResult = buildForwardReturnPanel({ - bars: shuffle(bars, seed), - signals: shuffle(signals, seed + 100), - horizonSessions: 3, - vaultCutoffDate: dates[12]!, - maxSignalAgeSessions: 6, - }); - expect(shuffledResult).toEqual(baseline); - } - }); - - it('handles empty bars and post-cutoff-only bars cleanly', () => { - const empty = buildForwardReturnPanel({ - bars: [], - signals: [{ listingId: 1, knownAt: makeUtcMs('2024-01-02', 10), value: 1 }], - horizonSessions: 1, - vaultCutoffDate: '2025-01-01', - }); - expect(empty.panel).toEqual([]); - expect(empty.sessionDates).toEqual([]); - expect(empty.diagnostics).toEqual({ - vaultExcludedDates: 0, - droppedNoSignal: 0, - droppedStaleSignal: 0, - droppedMissingForwardBar: 0, - droppedNonPositiveClose: 0, - duplicateBars: 0, - }); - - const postOnly = buildForwardReturnPanel({ - bars: [makeBar(1, '2025-01-02', 100), makeBar(1, '2025-01-03', 101)], - signals: [], - horizonSessions: 1, - vaultCutoffDate: '2025-01-01', - }); - expect(postOnly.panel).toEqual([]); - expect(postOnly.sessionDates).toEqual([]); - expect(postOnly.diagnostics.vaultExcludedDates).toBe(2); - }); - - it('throws typed SignalPanelError for every invalid input, option, date, bar, and signal', () => { - expectSignalPanelError( - () => buildForwardReturnPanel(null as unknown as Parameters[0]), - 'invalid_input' - ); - expectSignalPanelError( - () => - buildForwardReturnPanel({ - bars: 'not-an-array' as unknown as BarRecord[], - signals: [], - horizonSessions: 1, - vaultCutoffDate: '2025-01-01', - }), - 'invalid_input' - ); - expectSignalPanelError( - () => - buildForwardReturnPanel({ - bars: [], - signals: 'not-an-array' as unknown as SignalObservation[], - horizonSessions: 1, - vaultCutoffDate: '2025-01-01', - }), - 'invalid_input' - ); - - for (const badHorizon of [0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY]) { - expectSignalPanelError( - () => - buildForwardReturnPanel({ - bars: [], - signals: [], - horizonSessions: badHorizon, - vaultCutoffDate: '2025-01-01', - }), - 'invalid_horizon' - ); - } - - for (const badAge of [-1, 0.5, Number.NaN, Number.POSITIVE_INFINITY]) { - expectSignalPanelError( - () => - buildForwardReturnPanel({ - bars: [], - signals: [], - horizonSessions: 1, - vaultCutoffDate: '2025-01-01', - maxSignalAgeSessions: badAge, - }), - 'invalid_option' - ); - } - - for (const badDate of ['', '2025-02-29', '2025-13-01', '2025-01-01T00:00:00Z']) { - expectSignalPanelError( - () => - buildForwardReturnPanel({ - bars: [], - signals: [], - horizonSessions: 1, - vaultCutoffDate: badDate, - }), - 'invalid_date' - ); - } - - expectSignalPanelError( - () => - buildForwardReturnPanel({ - bars: [null as unknown as BarRecord], - signals: [], - horizonSessions: 1, - vaultCutoffDate: '2025-01-01', - }), - 'invalid_bar' - ); - expectSignalPanelError( - () => - buildForwardReturnPanel({ - bars: [{ ...makeBar(1, '2024-01-02', 100), listingId: 1.5 }], - signals: [], - horizonSessions: 1, - vaultCutoffDate: '2025-01-01', - }), - 'invalid_bar' - ); - expectSignalPanelError( - () => - buildForwardReturnPanel({ - bars: [{ ...makeBar(1, '2024-01-02', 100), close: '100' as unknown as number }], - signals: [], - horizonSessions: 1, - vaultCutoffDate: '2025-01-01', - }), - 'invalid_bar' - ); - - expectSignalPanelError( - () => - buildForwardReturnPanel({ - bars: [], - signals: [null as unknown as SignalObservation], - horizonSessions: 1, - vaultCutoffDate: '2025-01-01', - }), - 'invalid_signal' - ); - expectSignalPanelError( - () => - buildForwardReturnPanel({ - bars: [], - signals: [{ listingId: 1, knownAt: makeUtcMs('2024-01-02', 10), value: Number.NaN }], - horizonSessions: 1, - vaultCutoffDate: '2025-01-01', - }), - 'invalid_signal' - ); - }); -}); - -describe('shortsTableToSignalRows and collectBars', () => { - it('maps shortsAsOf table fields, skips nulls, normalizes -0, and rejects malformed inputs', () => { - const knownAt1 = makeUtcMs('2024-02-01', 22, 0); - const knownAt2 = makeUtcMs('2024-02-15', 22, 0); - const table: Table = { - columns: ['listing_id', 'report_date', 'known_at', 'shares_short', 'net_change', 'pct_float', 'source'], - rows: [ - { - listing_id: 10, - report_date: '2024-01-31', - known_at: knownAt1, - shares_short: 50_000, - net_change: -0, - pct_float: 0.042, - source: 'ceoShorts', - }, - { - listing_id: 20, - report_date: '2024-02-15', - known_at: knownAt2, - shares_short: 12_000, - net_change: null, - pct_float: null, - source: 'ceoShorts', - }, - ], - }; - - expect(shortsTableToSignalRows(table, 'shares_short')).toEqual([ - { listingId: 10, knownAt: knownAt1, value: 50_000 }, - { listingId: 20, knownAt: knownAt2, value: 12_000 }, - ]); - - const netChangeRows = shortsTableToSignalRows(table, 'net_change'); - expect(netChangeRows).toEqual([{ listingId: 10, knownAt: knownAt1, value: 0 }]); - expect(Object.is(netChangeRows[0]!.value, 0)).toBe(true); - - expect(shortsTableToSignalRows(table, 'pct_float')).toEqual([ - { listingId: 10, knownAt: knownAt1, value: 0.042 }, - ]); - - expectSignalPanelError( - () => shortsTableToSignalRows(table, 'bad_field' as unknown as 'net_change'), - 'invalid_input' - ); - expectSignalPanelError( - () => - shortsTableToSignalRows( - { columns: ['listing_id', 'known_at'], rows: [] }, - 'net_change' - ), - 'invalid_input' - ); - expectSignalPanelError( - () => - shortsTableToSignalRows( - { - columns: ['listing_id', 'known_at', 'net_change'], - rows: [{ listing_id: 1, known_at: knownAt1, net_change: Number.POSITIVE_INFINITY }], - }, - 'net_change' - ), - 'invalid_signal' - ); - expectSignalPanelError( - () => - shortsTableToSignalRows( - { - columns: ['listing_id', 'known_at', 'net_change'], - rows: [{ listing_id: 1, known_at: knownAt1 }], - }, - 'net_change' - ), - 'invalid_signal' - ); - }); - - it('collects multi-batch async iterables without mutating batches and rejects invalid inputs', async () => { - const b1 = makeBar(1, '2024-01-02', 100); - const b2 = makeBar(1, '2024-01-03', 101); - const b3 = makeBar(2, '2024-01-02', 50); - - const batch1: BarBatch = Object.freeze({ rows: Object.freeze([b1, b2]) }); - const batch2: BarBatch = Object.freeze({ rows: Object.freeze([b3]) }); - - async function* gen(): AsyncIterable { - yield batch1; - yield { rows: [] }; - yield batch2; - } - - const collected = await collectBars(gen()); - expect(collected).toEqual([b1, b2, b3]); - - async function* emptyGen(): AsyncIterable { - // empty - } - expect(await collectBars(emptyGen())).toEqual([]); - - await expectSignalPanelErrorAsync( - () => collectBars(null as unknown as AsyncIterable), - 'invalid_input' - ); - - async function* badBatchGen(): AsyncIterable { - yield { rows: 'not-array' } as unknown as BarBatch; - } - await expectSignalPanelErrorAsync(() => collectBars(badBatchGen()), 'invalid_bar'); - }); -}); diff --git a/package.json b/package.json index e295375c..0e2a41b8 100644 --- a/package.json +++ b/package.json @@ -53,7 +53,6 @@ "clean:fresh:force": "./scripts/clean.sh --fresh --force", "backtest": "turbo run backtest", "benchmark:dataset": "bun run scripts/benchmark-dataset.ts", - "mcp:research-copilot": "bun run scripts/research-copilot-mcp.ts", "docker:start": "./scripts/docker.sh start --dev", "docker:stop": "./scripts/docker.sh stop --dev", "docker:restart": "./scripts/docker.sh restart --dev", diff --git a/python/benchmarks/m1_quant_scan_benchmark.py b/python/benchmarks/m1_quant_scan_benchmark.py deleted file mode 100644 index 6173d936..00000000 --- a/python/benchmarks/m1_quant_scan_benchmark.py +++ /dev/null @@ -1,599 +0,0 @@ -"""M1 Exit Criterion 2 benchmark & NVDA pre-split verification on quant. - -Measures a real 20-year (2005-01-01 .. 2025-02-12) US + CA daily scan plus one -cross-sectional signal evaluation (IC, Q5-Q1 quantile spread, Q5 turnover, -pre/post-2023 recency split, Newey-West t-stat, and N-hat deflated Sharpe) via -DuckDB + Polars over curated Hive-partitioned Parquet (`bars_1d/year=*/part.parquet`), -strictly enforcing the rolling 6-month Vault cutoff (`2025-02-13`). - -Parquet-scan-level Vault verification (not post-filter row counting): -1. Parses `EXPLAIN (ANALYZE, FORMAT JSON)` physical plan `READ_PARQUET` operator - nodes to verify Vault predicates (`session_date < cutoff`, `ts < cutoff`, - `known_at < cutoff`) are pushed into `READ_PARQUET` and records exact - `operator_cardinality` (`parquet_scan_rows_emitted`) and `total_files_read`. -2. Runs a poisoned-Vault canary invariance test in a temporary overlay directory - (symlinking `year=2005..2024`, overwriting every `year=2025` Vault row - `session_date >= 2025-02-13` with sentinel `close = 999_999_999.0`, and adding - a `year=2026/part.parquet` Vault-only partition) proving: - - `year=2026` is 100% file-pruned (`total_files_read == 21`, not `22`), - - `READ_PARQUET` `operator_cardinality` is unchanged, and - - all evaluated signal metrics are bit-for-bit identical. -""" - -from __future__ import annotations - -import argparse -import json -import math -import os -import shutil -import tempfile -import time -from datetime import datetime, timezone -from pathlib import Path -from typing import Any - -import duckdb -import numpy as np -import polars as pl - -from stockbot.calculations import ( - deflated_sharpe_ratio, - evaluate_recency_gate, - newey_west_mean_test, - trial_moments, -) -from stockbot.vault import ( - DEFAULT_DUCKDB_MEMORY_LIMIT, - DEFAULT_DUCKDB_THREADS, - compute_vault_cutoff_ts, -) - - -def _open_duckdb(temp_dir: Path) -> duckdb.DuckDBPyConnection: - con = duckdb.connect(":memory:") - con.execute(f"SET memory_limit = '{DEFAULT_DUCKDB_MEMORY_LIMIT}'") - con.execute(f"SET threads = {DEFAULT_DUCKDB_THREADS}") - con.execute(f"SET temp_directory = '{temp_dir}'") - con.execute("SET preserve_insertion_order = false") - return con - - -def _build_signal_sql(bars_glob: str) -> str: - return f""" - WITH fenced AS ( - SELECT - listing_id, - session_date, - close, - volume - FROM read_parquet('{bars_glob}', hive_partitioning = true) - WHERE year <= 2025 - AND session_date >= CAST(? AS DATE) - AND session_date < CAST(? AS DATE) - AND ts < CAST(? AS TIMESTAMPTZ) - AND known_at < CAST(? AS TIMESTAMPTZ) - AND currency IN ('USD', 'CAD') - AND close > 0 - AND volume > 0 - ), - lagged AS ( - SELECT - listing_id, - session_date, - close, - volume, - LAG(close, 20) OVER w AS prev_close, - LEAD(close, 5) OVER w AS fwd_close - FROM fenced - WINDOW w AS (PARTITION BY listing_id ORDER BY session_date) - ), - liquid AS MATERIALIZED ( - SELECT - listing_id, - session_date, - -LN(close / prev_close) AS signal, - GREATEST(LEAST((fwd_close / close) - 1.0, 1.0), -0.95) AS fwd_ret - FROM lagged - WHERE prev_close > 0 - AND fwd_close > 0 - AND close >= 2.0 - AND close * volume >= 1000000 - AND ABS(LN(close / prev_close)) < 2.0 - ), - daily_raw AS ( - SELECT - session_date, - COUNT(*)::BIGINT AS n_names, - CORR(signal, fwd_ret) AS ic, - QUANTILE_CONT(signal, 0.2) AS q20, - QUANTILE_CONT(signal, 0.8) AS q80 - FROM liquid - GROUP BY session_date - HAVING COUNT(*) >= 50 AND NOT ISNAN(CORR(signal, fwd_ret)) - ), - prev_dates AS ( - SELECT - session_date, - n_names, - ic, - q20, - q80, - LAG(session_date) OVER (ORDER BY session_date) AS prev_session_date - FROM daily_raw - ), - extremes AS ( - SELECT - l.session_date, - l.listing_id, - l.fwd_ret, - p.prev_session_date, - (l.signal >= p.q80) AS is_q5, - (l.signal <= p.q20) AS is_q1 - FROM liquid l - JOIN prev_dates p ON p.session_date = l.session_date - WHERE l.signal >= p.q80 OR l.signal <= p.q20 - ), - q5_tagged AS ( - SELECT - session_date, - fwd_ret, - prev_session_date, - is_q5, - is_q1, - CASE - WHEN is_q5 THEN LAG(session_date) OVER ( - PARTITION BY listing_id, is_q5 ORDER BY session_date - ) - ELSE NULL - END AS prev_q5_date - FROM extremes - ), - daily_stats AS ( - SELECT - session_date, - AVG(fwd_ret) FILTER (WHERE is_q5) - AVG(fwd_ret) FILTER (WHERE is_q1) AS q5_q1_spread, - 1.0 - AVG(CASE WHEN prev_q5_date = prev_session_date THEN 1.0 ELSE 0.0 END) - FILTER (WHERE is_q5 AND prev_session_date IS NOT NULL) AS q5_turnover - FROM q5_tagged - GROUP BY session_date - ) - SELECT - p.session_date::VARCHAR AS session_date, - p.n_names, - p.ic, - d.q5_q1_spread, - d.q5_turnover - FROM prev_dates p - JOIN daily_stats d ON d.session_date = p.session_date - ORDER BY p.session_date - """ - - -def _extract_parquet_scan_nodes(node: dict[str, Any]) -> list[dict[str, Any]]: - found: list[dict[str, Any]] = [] - if node.get("operator_type") == "TABLE_SCAN" or node.get("operator_name") == "READ_PARQUET": - extra = node.get("extra_info") or {} - found.append( - { - "operator_name": node.get("operator_name"), - "operator_cardinality": int(node.get("operator_cardinality", 0)), - "operator_rows_scanned": int(node.get("operator_rows_scanned", 0)), - "total_files_read": int(extra.get("Total Files Read", 0)) - if str(extra.get("Total Files Read", "")).isdigit() - else extra.get("Total Files Read"), - "pushed_filters": extra.get("Filters", []), - "projections": extra.get("Projections", []), - } - ) - for child in node.get("children", []): - found.extend(_extract_parquet_scan_nodes(child)) - return found - - -def _evaluate_signal_once( - con: duckdb.DuckDBPyConnection, - bars_glob: str, - start_date: str, - vault_cutoff_iso_date: str, - vault_cutoff_iso_ts: str, -) -> dict[str, Any]: - sql = _build_signal_sql(bars_glob) - params = [ - start_date, - vault_cutoff_iso_date, - vault_cutoff_iso_ts, - vault_cutoff_iso_ts, - ] - t0 = time.perf_counter() - daily_df = con.execute(sql, params).pl() - t_sql = time.perf_counter() - - session_dates = daily_df["session_date"].to_list() - spreads = daily_df["q5_q1_spread"].drop_nulls().to_list() - ics = daily_df["ic"].drop_nulls().to_list() - turnovers = daily_df["q5_turnover"].drop_nulls().to_list() - - moments = trial_moments(spreads) - nw_res = newey_west_mean_test(spreads, lag=5) - recency = evaluate_recency_gate(session_dates, daily_df["ic"].to_list()) - dsr_res = deflated_sharpe_ratio( - sharpe_unann=moments.sharpe_unann, - n_obs=moments.n_obs, - skewness=moments.skewness, - kurtosis=moments.kurtosis, - n_hat=1.0, - cluster_sharpes=[moments.sharpe_unann], - ) - t_end = time.perf_counter() - - return { - "wall_secs": round(t_end - t0, 4), - "sql_secs": round(t_sql - t0, 4), - "post_secs": round(t_end - t_sql, 4), - "under_5s": (t_end - t0) < 5.0, - "min_date": session_dates[0] if session_dates else None, - "max_date": session_dates[-1] if session_dates else None, - "vault_cutoff_date": vault_cutoff_iso_date, - "n_sessions_evaluated": int(daily_df.height), - "mean_ic": round(float(np.mean(ics)), 6) if ics else 0.0, - "mean_q5_q1_spread": round(float(nw_res.mean), 6), - "mean_q5_turnover": round(float(np.mean(turnovers)), 6) if turnovers else 0.0, - "recency_gate": recency, - "sharpe_unann": round(moments.sharpe_unann, 6), - "sharpe_ann": round(moments.sharpe_unann * math.sqrt(252.0), 4), - "newey_west_t_stat": round(float(nw_res.t_stat), 4), - "newey_west_p_value": round(float(nw_res.p_value), 6), - "dsr": round(float(dsr_res.dsr), 6), - } - - -def _profile_parquet_scan( - con: duckdb.DuckDBPyConnection, - bars_glob: str, - start_date: str, - vault_cutoff_iso_date: str, - vault_cutoff_iso_ts: str, -) -> dict[str, Any]: - sql = "EXPLAIN (ANALYZE, FORMAT JSON)\n" + _build_signal_sql(bars_glob) - params = [ - start_date, - vault_cutoff_iso_date, - vault_cutoff_iso_ts, - vault_cutoff_iso_ts, - ] - raw_json = con.execute(sql, params).fetchall()[0][1] - plan = json.loads(raw_json) - scans = _extract_parquet_scan_nodes(plan) - assert len(scans) == 1, f"Expected single READ_PARQUET scan, got {len(scans)}" - scan = scans[0] - filters_joined = " | ".join(str(f) for f in scan["pushed_filters"]) - return { - "explain_analyze_latency_secs": round(float(plan.get("latency", 0.0)), 4), - "total_files_read": scan["total_files_read"], - "parquet_scan_rows_emitted": scan["operator_cardinality"], - "pushed_filters": scan["pushed_filters"], - "vault_session_date_pushed": vault_cutoff_iso_date in filters_joined, - "vault_ts_pushed": "ts<" in filters_joined.replace(" ", ""), - "vault_known_at_pushed": "known_at<" in filters_joined.replace(" ", ""), - } - - -def _run_poisoned_vault_canary( - curated_root: Path, - temp_dir: Path, - start_date: str, - vault_cutoff_iso_date: str, - vault_cutoff_iso_ts: str, - baseline_result: dict[str, Any], - baseline_scan: dict[str, Any], -) -> dict[str, Any]: - """Mutates all Vault rows (>= cutoff) and adds a year=2026 partition in an isolated overlay. - - Proves at the Parquet-scan and signal-output level that: - 1. A post-cutoff Hive partition (`year=2026`) is 100% file-pruned (`total_files_read` unchanged). - 2. Mutating all 3.36M Vault rows in `year=2025` to sentinel `close=999_999_999.0` leaves - `READ_PARQUET` `operator_cardinality` and every signal metric bit-for-bit identical. - """ - overlay_dir = Path(tempfile.mkdtemp(prefix="vault-canary-", dir=str(temp_dir))) - try: - overlay_bars = overlay_dir / "bars_1d" - overlay_bars.mkdir(parents=True, exist_ok=True) - src_bars = curated_root / "bars_1d" - for child in sorted(src_bars.iterdir()): - if child.name == "year=2025": - continue - (overlay_bars / child.name).symlink_to(child) - - # Build poisoned year=2025 (mutating every row >= vault_cutoff_date) and year=2026 - (overlay_bars / "year=2025").mkdir() - (overlay_bars / "year=2026").mkdir() - pcon = _open_duckdb(temp_dir) - try: - src_2025 = str(src_bars / "year=2025" / "part.parquet") - dst_2025 = str(overlay_bars / "year=2025" / "part.parquet") - dst_2026 = str(overlay_bars / "year=2026" / "part.parquet") - pcon.execute( - f""" - COPY ( - SELECT - listing_id, - session_date, - ts, - CASE WHEN session_date >= CAST(? AS DATE) THEN 999999999.0::DOUBLE ELSE open END AS open, - CASE WHEN session_date >= CAST(? AS DATE) THEN 999999999.0::DOUBLE ELSE high END AS high, - CASE WHEN session_date >= CAST(? AS DATE) THEN 999999999.0::DOUBLE ELSE low END AS low, - CASE WHEN session_date >= CAST(? AS DATE) THEN 999999999.0::DOUBLE ELSE close END AS close, - CASE WHEN session_date >= CAST(? AS DATE) THEN 999999999999.0::DOUBLE ELSE volume END AS volume, - vwap, - currency, - source, - known_at - FROM read_parquet('{src_2025}') - ) TO '{dst_2025}' (FORMAT PARQUET, COMPRESSION ZSTD) - """, - [vault_cutoff_iso_date] * 5, - ) - pcon.execute( - f""" - COPY ( - SELECT - listing_id, - DATE '2026-01-15' AS session_date, - TIMESTAMPTZ '2026-01-15 21:00:00+00' AS ts, - 999999999.0::DOUBLE AS open, - 999999999.0::DOUBLE AS high, - 999999999.0::DOUBLE AS low, - 999999999.0::DOUBLE AS close, - 999999999999.0::DOUBLE AS volume, - vwap, - currency, - source, - TIMESTAMPTZ '2026-01-15 21:00:00+00' AS known_at - FROM read_parquet('{src_2025}') - LIMIT 10000 - ) TO '{dst_2026}' (FORMAT PARQUET, COMPRESSION ZSTD) - """ - ) - - overlay_glob = str(overlay_bars / "year=*" / "part.parquet") - poisoned_vault_rows_on_disk = int( - pcon.execute( - f"SELECT COUNT(*) FROM read_parquet('{overlay_glob}', hive_partitioning = true) WHERE close = 999999999.0" - ).fetchone()[0] - ) - overlay_files_on_disk = len(list(overlay_bars.glob("year=*/part.parquet"))) - canary_result = _evaluate_signal_once( - pcon, - overlay_glob, - start_date, - vault_cutoff_iso_date, - vault_cutoff_iso_ts, - ) - canary_scan = _profile_parquet_scan( - pcon, - overlay_glob, - start_date, - vault_cutoff_iso_date, - vault_cutoff_iso_ts, - ) - finally: - pcon.close() - - keys_to_match = [ - "n_sessions_evaluated", - "mean_ic", - "mean_q5_q1_spread", - "mean_q5_turnover", - "sharpe_unann", - "newey_west_t_stat", - "dsr", - ] - bit_identical = all(canary_result[k] == baseline_result[k] for k in keys_to_match) - year_2026_pruned = ( - overlay_files_on_disk == int(baseline_scan["total_files_read"]) + 1 - and canary_scan["total_files_read"] == baseline_scan["total_files_read"] - ) - scan_cardinality_identical = ( - canary_scan["parquet_scan_rows_emitted"] - == baseline_scan["parquet_scan_rows_emitted"] - ) - - return { - "overlay_files_on_disk": overlay_files_on_disk, - "overlay_files_read_by_parquet_scan": canary_scan["total_files_read"], - "year_2026_partition_pruned": year_2026_pruned, - "poisoned_vault_rows_on_disk": poisoned_vault_rows_on_disk, - "canary_parquet_scan_rows_emitted": canary_scan["parquet_scan_rows_emitted"], - "scan_cardinality_identical": scan_cardinality_identical, - "signal_metrics_bit_identical": bit_identical, - "pass": bool( - poisoned_vault_rows_on_disk > 0 - and year_2026_pruned - and scan_cardinality_identical - and bit_identical - ), - } - finally: - shutil.rmtree(overlay_dir, ignore_errors=True) - - -def run_benchmark( - curated_root: Path, - temp_dir: Path, - max_ingested_date: str = "2025-08-13", - start_date: str = "2005-01-01", - nvda_listing_id: int | None = None, - qm_nvda_dollar_vol: float | None = None, -) -> dict[str, object]: - temp_dir.mkdir(parents=True, exist_ok=True) - vault_cutoff_ms = compute_vault_cutoff_ts(max_ingested_date) - vault_cutoff_dt = datetime.fromtimestamp(vault_cutoff_ms / 1000.0, tz=timezone.utc) - vault_cutoff_iso_date = vault_cutoff_dt.strftime("%Y-%m-%d") - vault_cutoff_iso_ts = vault_cutoff_dt.strftime("%Y-%m-%dT%H:%M:%S.%fZ") - - bars_glob = str(curated_root / "bars_1d" / "year=*" / "part.parquet") - - # 1. Run 1 on a fresh DuckDB connection (before any warmup query on bars_1d) - con_cold = _open_duckdb(temp_dir) - try: - run1 = _evaluate_signal_once( - con_cold, - bars_glob, - start_date, - vault_cutoff_iso_date, - vault_cutoff_iso_ts, - ) - # Run 2 on the same warm DuckDB connection - run2 = _evaluate_signal_once( - con_cold, - bars_glob, - start_date, - vault_cutoff_iso_date, - vault_cutoff_iso_ts, - ) - # Parquet-scan-level physical plan inspection (EXPLAIN ANALYZE FORMAT JSON) - scan_audit = _profile_parquet_scan( - con_cold, - bars_glob, - start_date, - vault_cutoff_iso_date, - vault_cutoff_iso_ts, - ) - - # NVDA pre-split 2024-06-07 dollar volume verification - nvda_check: dict[str, object] | None = None - if nvda_listing_id is not None: - nvda_row = con_cold.execute( - f""" - SELECT session_date::VARCHAR, open, high, low, close, volume, close * volume AS dollar_volume, currency - FROM read_parquet('{bars_glob}', hive_partitioning = true) - WHERE listing_id = ? AND session_date IN (DATE '2024-06-07', DATE '2024-06-10') - ORDER BY session_date - """, - [nvda_listing_id], - ).fetchall() - pre_split = next((r for r in nvda_row if r[0] == "2024-06-07"), None) - post_split = next((r for r in nvda_row if r[0] == "2024-06-10"), None) - rel_diff: float | None = None - if pre_split is not None and qm_nvda_dollar_vol is not None and qm_nvda_dollar_vol > 0: - rel_diff = abs(float(pre_split[6]) - qm_nvda_dollar_vol) / qm_nvda_dollar_vol - nvda_check = { - "listing_id": nvda_listing_id, - "pre_split_2024_06_07": ( - { - "close": float(pre_split[4]), - "raw_volume": float(pre_split[5]), - "dollar_volume": float(pre_split[6]), - "currency": pre_split[7], - } - if pre_split - else None - ), - "post_split_2024_06_10": ( - { - "close": float(post_split[4]), - "raw_volume": float(post_split[5]), - "dollar_volume": float(post_split[6]), - "currency": post_split[7], - } - if post_split - else None - ), - "qm_pre_split_dollar_volume": qm_nvda_dollar_vol, - "rel_diff": rel_diff, - "within_1pct": rel_diff is not None and rel_diff <= 0.01, - } - - # Exact dataset totals on disk - vault_rows_on_disk = int( - con_cold.execute( - f"SELECT COUNT(*) FROM read_parquet('{bars_glob}', hive_partitioning = true) WHERE session_date >= CAST(? AS DATE)", - [vault_cutoff_iso_date], - ).fetchone()[0] - ) - scan_stats = con_cold.execute( - f""" - SELECT COUNT(*)::BIGINT, COUNT(DISTINCT listing_id)::BIGINT, MIN(session_date)::VARCHAR, MAX(session_date)::VARCHAR - FROM read_parquet('{bars_glob}', hive_partitioning = true) - WHERE session_date >= CAST(? AS DATE) - AND session_date < CAST(? AS DATE) - AND currency IN ('USD', 'CAD') - AND close > 0 AND volume > 0 - """, - [start_date, vault_cutoff_iso_date], - ).fetchone() - total_rows_in_scan = int(scan_stats[0]) - distinct_listings_in_scan = int(scan_stats[1]) - finally: - con_cold.close() - - # Poisoned-Vault canary test proving scan-level & signal-level Vault isolation - vault_canary = _run_poisoned_vault_canary( - curated_root=curated_root, - temp_dir=temp_dir, - start_date=start_date, - vault_cutoff_iso_date=vault_cutoff_iso_date, - vault_cutoff_iso_ts=vault_cutoff_iso_ts, - baseline_result=run1, - baseline_scan=scan_audit, - ) - - return { - "host": os.uname().nodename, - "curated_root": str(curated_root), - "duckdb_version": duckdb.__version__, - "polars_version": pl.__version__, - "duckdb_budget": { - "memory_limit": DEFAULT_DUCKDB_MEMORY_LIMIT, - "threads": DEFAULT_DUCKDB_THREADS, - "temp_directory": str(temp_dir), - }, - "cache_state_note": ( - "run1_fresh_conn runs on a brand-new DuckDB process/connection with no prior queries; " - "run2_warm_conn reuses the warm DuckDB connection. Unprivileged execution does not " - "drop Linux kernel OS page cache (/proc/sys/vm/drop_caches requires root)." - ), - "vault_cutoff_date": vault_cutoff_iso_date, - "vault_rows_on_disk": vault_rows_on_disk, - "total_rows_in_scan": total_rows_in_scan, - "distinct_listings_in_scan": distinct_listings_in_scan, - "scan_date_min": scan_stats[2], - "scan_date_max": scan_stats[3], - "nvda_pre_split_check": nvda_check, - "parquet_scan_vault_audit": scan_audit, - "poisoned_vault_canary": vault_canary, - "run1_fresh_conn": run1, - "run2_warm_conn": run2, - "both_runs_under_5s": bool(run1["under_5s"] and run2["under_5s"]), - } - - -def main() -> None: - parser = argparse.ArgumentParser(description="M1 quant 20y US/CA scan + signal benchmark") - parser.add_argument("--curated-root", type=Path, required=True) - parser.add_argument("--temp-dir", type=Path, required=True) - parser.add_argument("--max-ingested-date", default="2025-08-13") - parser.add_argument("--start-date", default="2005-01-01") - parser.add_argument("--nvda-listing-id", type=int, default=None) - parser.add_argument("--qm-nvda-dollar-vol", type=float, default=None) - parser.add_argument("--out-json", type=Path, default=None) - args = parser.parse_args() - - result = run_benchmark( - curated_root=args.curated_root, - temp_dir=args.temp_dir, - max_ingested_date=args.max_ingested_date, - start_date=args.start_date, - nvda_listing_id=args.nvda_listing_id, - qm_nvda_dollar_vol=args.qm_nvda_dollar_vol, - ) - rendered = json.dumps(result, indent=2) - print(rendered) - if args.out_json is not None: - args.out_json.parent.mkdir(parents=True, exist_ok=True) - args.out_json.write_text(rendered + "\n", encoding="utf-8") - - -if __name__ == "__main__": - main() diff --git a/python/pyproject.toml b/python/pyproject.toml deleted file mode 100644 index 0e5315d0..00000000 --- a/python/pyproject.toml +++ /dev/null @@ -1,29 +0,0 @@ -[project] -name = "stockbot" -version = "0.1.0" -description = "Stock Bot Python Research SDK (Vault-fenced DuckDB/Parquet MarketDataStore, Signal Analyzer, Event Study, trial_ledger DSR)" -requires-python = ">=3.11" -dependencies = [ - "duckdb>=1.2.0,<2.0.0", - "polars>=1.20.0,<2.0.0", - "marimo>=0.11.0,<1.0.0", - "psycopg[binary]>=3.2.0,<4.0.0", - "numpy>=1.26.0,<3.0.0", - "scipy>=1.13.0,<2.0.0", - "pyarrow>=18.0.0,<22.0.0", -] - -[project.optional-dependencies] -dev = [ - "pytest>=8.0.0,<9.0.0", -] - -[build-system] -requires = ["hatchling>=1.25.0"] -build-backend = "hatchling.build" - -[tool.hatch.build.targets.wheel] -packages = ["stockbot"] - -[tool.pytest.ini_options] -testpaths = ["tests"] diff --git a/python/stockbot/__init__.py b/python/stockbot/__init__.py deleted file mode 100644 index c61316f0..00000000 --- a/python/stockbot/__init__.py +++ /dev/null @@ -1,80 +0,0 @@ -"""Stock Bot Python Research SDK (`stockbot`).""" - -from . import data -from .calculations import ( - DSR_VALIDATION_GATE, - EULER_MASCHERONI, - RECENCY_MIN_RATIO, - RECENCY_SPLIT_DATE, - DeflatedSharpeResult, - EffectiveTrialsResult, - NeweyWestResult, - TrialMoments, - analyze_signal_panel, - compute_event_study, - deflated_sharpe_ratio, - effective_independent_trials, - evaluate_recency_gate, - newey_west_mean_test, - trial_moments, -) -from .data import MarketDataStore -from .ledger import ( - ClusterDsrSummary, - RecordedTrial, - TrialLedgerClient, - canonical_expression_hash, -) -from .signals import run_event_study_trial, run_signal_study -from .vault import ( - DEFAULT_DUCKDB_MEMORY_LIMIT, - DEFAULT_DUCKDB_TEMP_DIRECTORY, - DEFAULT_DUCKDB_THREADS, - DuckDbConnectionBudget, - FencedTimeRange, - MarketDataStoreValidationError, - VaultHoldoutFenceError, - VaultScopeNotAuthorizedError, - apply_vault_fence, - compute_vault_cutoff_ts, - resolve_duckdb_budget, - vault_cutoff_date_str, -) - -__all__ = [ - "data", - "MarketDataStore", - "TrialLedgerClient", - "RecordedTrial", - "ClusterDsrSummary", - "canonical_expression_hash", - "run_signal_study", - "run_event_study_trial", - "analyze_signal_panel", - "compute_event_study", - "trial_moments", - "effective_independent_trials", - "deflated_sharpe_ratio", - "newey_west_mean_test", - "evaluate_recency_gate", - "TrialMoments", - "EffectiveTrialsResult", - "DeflatedSharpeResult", - "NeweyWestResult", - "DSR_VALIDATION_GATE", - "EULER_MASCHERONI", - "RECENCY_SPLIT_DATE", - "RECENCY_MIN_RATIO", - "DEFAULT_DUCKDB_MEMORY_LIMIT", - "DEFAULT_DUCKDB_THREADS", - "DEFAULT_DUCKDB_TEMP_DIRECTORY", - "DuckDbConnectionBudget", - "FencedTimeRange", - "MarketDataStoreValidationError", - "VaultHoldoutFenceError", - "VaultScopeNotAuthorizedError", - "apply_vault_fence", - "compute_vault_cutoff_ts", - "resolve_duckdb_budget", - "vault_cutoff_date_str", -] diff --git a/python/stockbot/calculations.py b/python/stockbot/calculations.py deleted file mode 100644 index c898b69a..00000000 --- a/python/stockbot/calculations.py +++ /dev/null @@ -1,494 +0,0 @@ -"""Canonical quantitative validation metrics matching `@stock-bot/calculations`. - -Exact formulas from `design/VALIDATION-AND-RIGOR.md` §1, §2.B, §2.C, §3.2: -- `trial_moments`: sample std (N - 1), plugin skewness m3/m2^(3/2), Pearson kurtosis m4/m2^2 -- `effective_independent_trials`: Bailey & Lopez de Prado N-hat -- `deflated_sharpe_ratio`: non-normal DSR with Euler-Mascheroni gamma = 0.5772156649015329 -- `newey_west_mean_test`: Bartlett kernel HAC t-stat and two-sided normal p-value -- `analyze_signal_panel`: fast vectorized Polars/NumPy IC, Rank-IC, quantiles, turnover, recency -- `compute_event_study`: zero-look-ahead AAR/CAAR, R-7 CAR fans, date-clustered HAC t-stat, recency -""" - -from __future__ import annotations - -import math -from dataclasses import dataclass -from typing import Sequence - -import numpy as np -import polars as pl -from scipy.stats import norm - -EULER_MASCHERONI = 0.5772156649015329 -DSR_VALIDATION_GATE = 0.95 -RECENCY_SPLIT_DATE = "2023-01-01" -RECENCY_MIN_RATIO = 0.5 - - -@dataclass(frozen=True) -class TrialMoments: - n_obs: int - sharpe_unann: float - skewness: float - kurtosis: float - - -@dataclass(frozen=True) -class EffectiveTrialsResult: - k: int - pairs_used: int - pairs_skipped: int - mean_correlation: float | None - n_hat: float - - -@dataclass(frozen=True) -class DeflatedSharpeResult: - sr0: float - standard_error: float - dsr: float - - -@dataclass(frozen=True) -class NeweyWestResult: - n_obs: int - lag: int - mean: float - standard_error: float - t_stat: float - p_value: float - - -def trial_moments(series: Sequence[float] | np.ndarray, daily_risk_free: float = 0.0) -> TrialMoments: - """Computes canonical per-trial moments matching `trialMoments` in `@stock-bot/calculations`.""" - arr = np.asarray(series, dtype=np.float64) - finite = arr[np.isfinite(arr)] - n = int(finite.size) - if n < 2: - raise ValueError(f"trial_moments requires at least 2 finite observations (got {n}).") - - mean_val = float(np.mean(finite)) - centered = finite - mean_val - m2 = float(np.mean(centered * centered)) - if m2 <= 0.0: - raise ValueError("trial_moments requires non-zero variance.") - - sample_std = math.sqrt(float(np.sum(centered * centered)) / (n - 1)) - sharpe_unann = (mean_val - daily_risk_free) / sample_std - m3 = float(np.mean(centered ** 3)) - m4 = float(np.mean(centered ** 4)) - skewness = m3 / (m2 ** 1.5) - kurtosis = m4 / (m2 * m2) - return TrialMoments( - n_obs=n, - sharpe_unann=float(sharpe_unann), - skewness=float(skewness), - kurtosis=float(kurtosis), - ) - - -def newey_west_mean_test( - series: Sequence[float] | np.ndarray, lag: int | None = None -) -> NeweyWestResult: - """Bartlett-kernel Newey-West HAC test for H0: mean == 0.""" - arr = np.asarray(series, dtype=np.float64) - arr = arr[np.isfinite(arr)] - n = int(arr.size) - if n < 2: - return NeweyWestResult( - n_obs=n, lag=0, mean=float("nan"), standard_error=float("nan"), t_stat=float("nan"), p_value=float("nan") - ) - max_lag = lag if lag is not None else max(1, int(math.floor(4.0 * ((n / 100.0) ** (2.0 / 9.0))))) - max_lag = min(max_lag, n - 1) - mean_val = float(np.mean(arr)) - u = arr - mean_val - gamma0 = float(np.dot(u, u)) / n - lrv = gamma0 - for l in range(1, max_lag + 1): - weight = 1.0 - l / (max_lag + 1.0) - gamma_l = float(np.dot(u[l:], u[:-l])) / n - lrv += 2.0 * weight * gamma_l - lrv = max(lrv, 0.0) - se = math.sqrt(lrv / n) if lrv > 0.0 else 0.0 - if se == 0.0: - t_stat = 0.0 if mean_val == 0.0 else math.copysign(float("inf"), mean_val) - p_val = 1.0 if mean_val == 0.0 else 0.0 - else: - t_stat = mean_val / se - p_val = float(2.0 * (1.0 - norm.cdf(abs(t_stat)))) - return NeweyWestResult( - n_obs=n, lag=max_lag, mean=mean_val, standard_error=se, t_stat=float(t_stat), p_value=p_val - ) - - -def effective_independent_trials( - aligned_series_by_id: Sequence[tuple[int, dict[str, float]]] -) -> EffectiveTrialsResult: - """Computes Bailey & Lopez de Prado effective independent trials N-hat.""" - k = len(aligned_series_by_id) - if k <= 1: - return EffectiveTrialsResult(k=k, pairs_used=0, pairs_skipped=0, mean_correlation=None, n_hat=1.0) - - corr_sum = 0.0 - pairs_used = 0 - pairs_skipped = 0 - - for i in range(k): - _, map_i = aligned_series_by_id[i] - keys_i = set(map_i.keys()) - for j in range(i + 1, k): - _, map_j = aligned_series_by_id[j] - common = sorted(keys_i.intersection(map_j.keys())) - if len(common) < 2: - pairs_skipped += 1 - continue - xi = np.array([map_i[d] for d in common], dtype=np.float64) - xj = np.array([map_j[d] for d in common], dtype=np.float64) - xi -= xi.mean() - xj -= xj.mean() - denom = math.sqrt(float(np.dot(xi, xi) * np.dot(xj, xj))) - if denom <= 0.0 or not math.isfinite(denom): - pairs_skipped += 1 - continue - rho = max(-1.0, min(1.0, float(np.dot(xi, xj)) / denom)) - corr_sum += rho - pairs_used += 1 - - if pairs_used == 0: - return EffectiveTrialsResult( - k=k, pairs_used=0, pairs_skipped=pairs_skipped, mean_correlation=None, n_hat=float(k) - ) - - mean_corr = corr_sum / pairs_used - n_hat = max(1.0, 1.0 + (k - 1.0) * (1.0 - max(0.0, mean_corr))) - return EffectiveTrialsResult( - k=k, - pairs_used=pairs_used, - pairs_skipped=pairs_skipped, - mean_correlation=float(mean_corr), - n_hat=float(n_hat), - ) - - -def deflated_sharpe_ratio( - *, - sharpe_unann: float, - n_obs: int, - skewness: float, - kurtosis: float, - n_hat: float, - cluster_sharpes: Sequence[float], -) -> DeflatedSharpeResult: - """Computes non-normal Deflated Sharpe Ratio (DSR) per VALIDATION-AND-RIGOR.md §2.C.""" - if n_obs < 2: - raise ValueError("n_obs must be >= 2.") - sr_arr = np.asarray(cluster_sharpes, dtype=np.float64) - sr_arr = sr_arr[np.isfinite(sr_arr)] - - if n_hat <= 1.0 or sr_arr.size < 2: - sr0 = 0.0 - else: - sigma_sr = float(np.std(sr_arr, ddof=1)) - if sigma_sr <= 0.0: - sr0 = 0.0 - else: - z1 = float(norm.ppf(1.0 - 1.0 / n_hat)) - z2 = float(norm.ppf(1.0 - 1.0 / (n_hat * math.e))) - sr0 = sigma_sr * ((1.0 - EULER_MASCHERONI) * z1 + EULER_MASCHERONI * z2) - - se_num = 1.0 - skewness * sharpe_unann + ((kurtosis - 1.0) / 4.0) * (sharpe_unann ** 2) - if se_num <= 0.0: - raise ValueError("Non-positive Sharpe standard-error variance term.") - se = math.sqrt(se_num / (n_obs - 1.0)) - dsr = float(norm.cdf((sharpe_unann - sr0) / se)) - return DeflatedSharpeResult(sr0=float(sr0), standard_error=float(se), dsr=dsr) - - -def evaluate_recency_gate( - dates: Sequence[str], - series: Sequence[float] | np.ndarray, - *, - split_date: str = RECENCY_SPLIT_DATE, - min_ratio: float = RECENCY_MIN_RATIO, -) -> dict[str, object]: - """Post-2023 Recency Gate: post mean > 0 and >= min_ratio * pre mean (sign-preserving).""" - arr = np.asarray(series, dtype=np.float64) - pre_vals = np.array([v for d, v in zip(dates, arr) if d < split_date and math.isfinite(v)], dtype=np.float64) - post_vals = np.array([v for d, v in zip(dates, arr) if d >= split_date and math.isfinite(v)], dtype=np.float64) - pre_mean = float(pre_vals.mean()) if pre_vals.size > 0 else float("nan") - post_mean = float(post_vals.mean()) if post_vals.size > 0 else float("nan") - - if pre_vals.size == 0: - return {"pass": False, "reason": "empty_pre_window", "pre_n": 0, "post_n": int(post_vals.size), "pre_mean": None, "post_mean": post_mean if post_vals.size else None, "ratio": None} - if post_vals.size == 0: - return {"pass": False, "reason": "empty_post_window", "pre_n": int(pre_vals.size), "post_n": 0, "pre_mean": pre_mean, "post_mean": None, "ratio": None} - if pre_mean == 0.0: - return {"pass": False, "reason": "zero_pre_mean", "pre_n": int(pre_vals.size), "post_n": int(post_vals.size), "pre_mean": pre_mean, "post_mean": post_mean, "ratio": None} - - ratio = post_mean / pre_mean - same_sign = (pre_mean > 0 and post_mean > 0) or (pre_mean < 0 and post_mean < 0) - passed = same_sign and ratio >= min_ratio - reason = "passed" if passed else ("sign_flipped" if not same_sign else "post_below_ratio_threshold") - return { - "pass": passed, - "reason": reason, - "pre_n": int(pre_vals.size), - "post_n": int(post_vals.size), - "pre_mean": pre_mean, - "post_mean": post_mean, - "ratio": float(ratio), - } - - -def analyze_signal_panel( - panel: pl.DataFrame, - *, - vault_cutoff_date: str, - n_quantiles: int = 5, - min_cross_section: int = 10, - recency_split_date: str = RECENCY_SPLIT_DATE, -) -> dict[str, object]: - """Vectorized Polars/NumPy cross-sectional Signal Analyzer. - - Expects columns: `session_date` (str YYYY-MM-DD or Date), `listing_id` (int), - `signal` (float), `forward_return` (float). - Enforces strict Vault cutoff `session_date < vault_cutoff_date`. - """ - df = panel.with_columns( - pl.col("session_date").cast(pl.String).alias("session_date"), - pl.col("signal").cast(pl.Float64), - pl.col("forward_return").cast(pl.Float64), - ).filter( - pl.col("signal").is_finite() & pl.col("forward_return").is_finite() - ) - - vault_excluded = int(df.filter(pl.col("session_date") >= vault_cutoff_date).height) - fenced = df.filter(pl.col("session_date") < vault_cutoff_date) - - # Filter dates with enough listings and compute cross-sectional Pearson IC, Rank IC, and Q_top - Q_bot - ranked = ( - fenced.with_columns(pl.len().over("session_date").alias("_n")) - .filter(pl.col("_n") >= min_cross_section) - .with_columns( - pl.col("signal").rank("average").over("session_date").alias("_sig_rank"), - pl.col("forward_return").rank("average").over("session_date").alias("_ret_rank"), - ( - ((pl.col("signal").rank("ordinal").over("session_date") - 1) * n_quantiles // pl.col("_n")) - .clip(0, n_quantiles - 1) - .alias("_q") - ), - ) - ) - - daily_ic = ( - ranked.group_by("session_date") - .agg( - pl.len().alias("n_listings"), - pl.corr("signal", "forward_return").alias("ic"), - pl.corr("_sig_rank", "_ret_rank").alias("rank_ic"), - pl.col("forward_return").filter(pl.col("_q") == (n_quantiles - 1)).mean().alias("q_top"), - pl.col("forward_return").filter(pl.col("_q") == 0).mean().alias("q_bot"), - ) - .with_columns((pl.col("q_top") - pl.col("q_bot")).alias("spread")) - .filter(pl.col("rank_ic").is_finite() & pl.col("spread").is_finite()) - .sort("session_date") - ) - - # Top-quantile membership turnover across consecutive dates - top_members = ( - ranked.filter(pl.col("_q") == (n_quantiles - 1)) - .group_by("session_date") - .agg(pl.col("listing_id").implode().alias("ids")) - .sort("session_date") - ) - prev_set: set[int] | None = None - turnovers: list[float] = [] - for row in top_members.iter_rows(): - cur_set = set(row[1]) - if prev_set is not None and len(cur_set) > 0 and len(prev_set) > 0: - overlap = len(cur_set.intersection(prev_set)) - turnovers.append(1.0 - overlap / max(len(cur_set), len(prev_set))) - prev_set = cur_set - - dates = daily_ic["session_date"].to_list() - rank_ic_series = daily_ic["rank_ic"].to_numpy() - ic_series = daily_ic["ic"].to_numpy() - spread_series = daily_ic["spread"].to_numpy() - - rank_ic_nw = newey_west_mean_test(rank_ic_series) - spread_nw = newey_west_mean_test(spread_series) - recency_ic = evaluate_recency_gate(dates, rank_ic_series, split_date=recency_split_date) - recency_spread = evaluate_recency_gate(dates, spread_series, split_date=recency_split_date) - - return { - "n_dates": len(dates), - "total_observations": int(ranked.height), - "vault_excluded_rows": vault_excluded, - "dates": dates, - "ic_series": ic_series.tolist(), - "rank_ic_series": rank_ic_series.tolist(), - "spread_series": spread_series.tolist(), - "mean_ic": float(np.nanmean(ic_series)) if len(dates) else float("nan"), - "mean_rank_ic": rank_ic_nw.mean, - "rank_ic_nw_t": rank_ic_nw.t_stat, - "rank_ic_nw_p": rank_ic_nw.p_value, - "mean_quantile_spread": spread_nw.mean, - "spread_nw_t": spread_nw.t_stat, - "mean_top_quantile_turnover": float(np.mean(turnovers)) if turnovers else float("nan"), - "recency_rank_ic": recency_ic, - "recency_spread": recency_spread, - } - - -def compute_event_study( - bars_df: pl.DataFrame, - events_df: pl.DataFrame, - *, - vault_cutoff_date: str, - pre_days: int = 5, - post_days: int = 10, - min_events: int = 5, - recency_split_date: str = RECENCY_SPLIT_DATE, -) -> dict[str, object]: - """Zero-look-ahead Event Study over curated daily bars and point-in-time events. - - Events anchor to the first trading session with `bar.ts >= event.known_at`. - All events whose event session or `event + post_days` session >= `vault_cutoff_date` - are strictly excluded before computing returns. - """ - bars = ( - bars_df.select(["listing_id", "session_date", "ts", "close"]) - .with_columns( - pl.col("session_date").cast(pl.String), - pl.col("close").cast(pl.Float64), - ) - .filter((pl.col("session_date") < vault_cutoff_date) & (pl.col("close") > 0)) - .sort(["listing_id", "session_date"]) - ) - - # Build shared session calendar and per-listing daily returns - session_dates = bars["session_date"].unique().sort().to_list() - date_to_idx = {d: i for i, d in enumerate(session_dates)} - n_sessions = len(session_dates) - - # Compute close-to-close simple returns per listing and equal-weight market benchmark - ret_df = ( - bars.with_columns( - (pl.col("close") / pl.col("close").shift(1).over("listing_id") - 1.0).alias("ret") - ) - .filter(pl.col("ret").is_finite()) - ) - bench_df = ( - ret_df.group_by("session_date") - .agg(pl.col("ret").mean().alias("bench_ret")) - ) - abn_df = ( - ret_df.join(bench_df, on="session_date", how="left") - .with_columns((pl.col("ret") - pl.col("bench_ret")).alias("abn_ret")) - ) - - # Index returns per listing into dense arrays for fast window slicing - listing_abn: dict[int, dict[int, float]] = {} - listing_close_ts: dict[int, tuple[np.ndarray, np.ndarray]] = {} - - for lid, grp in bars.group_by("listing_id", maintain_order=False): - lid_int = int(lid[0]) - ts_arr = grp["ts"].cast(pl.Int64).to_numpy() - idx_arr = np.array([date_to_idx[d] for d in grp["session_date"].to_list()], dtype=np.int32) - listing_close_ts[lid_int] = (ts_arr, idx_arr) - - for lid, grp in abn_df.group_by("listing_id", maintain_order=False): - lid_int = int(lid[0]) - d_map: dict[int, float] = {} - for s_date, abn in zip(grp["session_date"].to_list(), grp["abn_ret"].to_list()): - d_map[date_to_idx[s_date]] = float(abn) - listing_abn[lid_int] = d_map - - ev_ts_col = events_df.select(["listing_id", "known_at"]).with_columns( - pl.col("known_at").cast(pl.Int64) - ) - - seen_pairs: set[tuple[int, int]] = set() - cars_by_date: dict[str, list[float]] = {} - window_matrix: list[list[float]] = [] - vault_excluded_events = 0 - - cutoff_ts_micros = int( - datetime_from_ymd(vault_cutoff_date) - ) - - for lid_raw, known_at_us in ev_ts_col.iter_rows(): - if known_at_us >= cutoff_ts_micros: - vault_excluded_events += 1 - continue - lid = int(lid_raw) - if lid not in listing_close_ts or lid not in listing_abn: - continue - ts_arr, idx_arr = listing_close_ts[lid] - pos = int(np.searchsorted(ts_arr, known_at_us, side="left")) - if pos >= ts_arr.size: - continue - day_idx = int(idx_arr[pos]) - if day_idx - pre_days < 0 or day_idx + post_days >= n_sessions: - continue - key = (lid, day_idx) - if key in seen_pairs: - continue - seen_pairs.add(key) - - abn_map = listing_abn[lid] - window_vals: list[float] = [] - complete = True - for offset in range(-pre_days, post_days + 1): - val = abn_map.get(day_idx + offset) - if val is None or not math.isfinite(val): - complete = False - break - window_vals.append(val) - if not complete: - continue - - window_matrix.append(window_vals) - post_car = float(sum(window_vals[pre_days:])) - cars_by_date.setdefault(session_dates[day_idx], []).append(post_car) - - events_used = len(window_matrix) - if events_used < min_events or len(cars_by_date) < 2: - return { - "status": "insufficient_data", - "events_used": events_used, - "n_dates": len(cars_by_date), - "vault_excluded_events": vault_excluded_events, - } - - mat = np.asarray(window_matrix, dtype=np.float64) - aar = mat.mean(axis=0) - caar = np.cumsum(aar) - clustered_dates = sorted(cars_by_date.keys()) - mean_cars = np.array([float(np.mean(cars_by_date[d])) for d in clustered_dates], dtype=np.float64) - nw = newey_west_mean_test(mean_cars) - recency = evaluate_recency_gate(clustered_dates, mean_cars, split_date=recency_split_date) - - return { - "status": "ok", - "pre_days": pre_days, - "post_days": post_days, - "events_used": events_used, - "n_dates": len(clustered_dates), - "vault_excluded_events": vault_excluded_events, - "clustered_dates": clustered_dates, - "mean_cars": mean_cars.tolist(), - "car_mean": nw.mean, - "car_nw_t": nw.t_stat, - "car_nw_p": nw.p_value, - "aar": aar.tolist(), - "caar": caar.tolist(), - "recency": recency, - } - - -def datetime_from_ymd(ymd: str) -> int: - from datetime import datetime, timezone - - dt = datetime.strptime(ymd, "%Y-%m-%d").replace(tzinfo=timezone.utc) - return int(dt.timestamp() * 1_000_000) diff --git a/python/stockbot/data.py b/python/stockbot/data.py deleted file mode 100644 index 5fca1827..00000000 --- a/python/stockbot/data.py +++ /dev/null @@ -1,295 +0,0 @@ -"""Vault-fenced DuckDB + Polars `MarketDataStore` for curated Hive Parquet.""" - -from __future__ import annotations - -import os -from datetime import date, datetime, timedelta, timezone -from pathlib import Path -from typing import Literal, Sequence - -import duckdb -import polars as pl - -from .vault import ( - DataScope, - DuckDbConnectionBudget, - MarketDataStoreValidationError, - apply_vault_fence, - resolve_duckdb_budget, -) - -EventKind = Literal["filing", "earnings", "ceo_post", "corporate_action"] -AdjustmentMode = Literal["raw", "split", "total"] -UniverseRef = Literal["US_EQ", "CA_EQ", "US_CA_EQ"] - -_UNIVERSE_CURRENCIES: dict[str, tuple[str, ...]] = { - "US_EQ": ("USD",), - "CA_EQ": ("CAD",), - "US_CA_EQ": ("USD", "CAD"), -} - - -class MarketDataStore: - """Vault-fenced DuckDB + Parquet reader enforcing `known_at <= as_of` and `ts < vault_cutoff_ts`.""" - - def __init__( - self, - curated_root: str | Path, - *, - vault_cutoff_ts: int, - vault_operator_authorized: bool = False, - budget: DuckDbConnectionBudget | None = None, - adj_factors_path: str | Path | None = None, - ) -> None: - self.curated_root = str(Path(curated_root).resolve()) - self.vault_cutoff_ts = vault_cutoff_ts - self.vault_operator_authorized = vault_operator_authorized - self.budget = budget or resolve_duckdb_budget() - self.adj_factors_path = ( - str(Path(adj_factors_path).resolve()) - if adj_factors_path is not None - else str(Path(self.curated_root) / "adj_factors" / "part.parquet") - ) - os.makedirs(self.budget.temp_directory, exist_ok=True) - self._con = duckdb.connect(":memory:") - for stmt in self.budget.statements: - self._con.execute(stmt) - - def close(self) -> None: - self._con.close() - - def __enter__(self) -> "MarketDataStore": - return self - - def __exit__(self, *_: object) -> None: - self.close() - - def _bars_glob(self) -> str: - return f"{self.curated_root}/bars_1d/year=*/part.parquet" - - def _events_glob(self) -> str: - return f"{self.curated_root}/events/year=*/part.parquet" - - def _shorts_path(self) -> str: - return f"{self.curated_root}/shorts/part.parquet" - - def _fx_path(self) -> str: - return f"{self.curated_root}/fx_1d/part.parquet" - - def _verify_fenced_adj_factors(self, as_of_micros: int, scope: DataScope) -> str: - rows = self._con.execute( - f"SELECT key::VARCHAR AS k, value::VARCHAR AS v FROM parquet_kv_metadata('{self.adj_factors_path}')" - ).fetchall() - kv = {str(k): str(v) for k, v in rows if str(k).startswith("stock_bot.adj_factors.")} - kind = kv.get("stock_bot.adj_factors.snapshot_kind") - if kind != "point_in_time_fenced": - raise MarketDataStoreValidationError( - f"Adjusted bars require point_in_time_fenced adj_factors snapshot (got {kind!r} at {self.adj_factors_path})." - ) - if scope == "vault_fenced": - raw_vc = kv.get("stock_bot.adj_factors.vault_cutoff_micros") - expected_vc = self.vault_cutoff_ts * 1000 - if raw_vc is None or raw_vc == "none" or int(raw_vc) > expected_vc: - raise MarketDataStoreValidationError( - f"adj_factors vault_cutoff_micros ({raw_vc}) incompatible with store cutoff ({expected_vc})." - ) - raw_as_of = kv.get("stock_bot.adj_factors.as_of_micros") - if raw_as_of is not None and raw_as_of != "none" and int(raw_as_of) > as_of_micros: - raise MarketDataStoreValidationError( - f"adj_factors as_of_micros ({raw_as_of}) exceeds query as_of_micros ({as_of_micros})." - ) - return self.adj_factors_path - - def bars( - self, - *, - listing_ids: Sequence[int] | None = None, - currencies: Sequence[str] | None = None, - timeframe: str = "1d", - from_date: str, - to_date: str, - adjustment: AdjustmentMode = "raw", - as_of: str | None = None, - scope: DataScope = "vault_fenced", - ) -> pl.DataFrame: - if timeframe != "1d": - raise NotImplementedError(f"Timeframe {timeframe!r} is reserved for QuestDB (M2).") - fenced = apply_vault_fence( - from_date, - to_date, - self.vault_cutoff_ts, - as_of=as_of, - scope=scope, - vault_operator_authorized=self.vault_operator_authorized, - ) - from_ts = datetime.fromtimestamp(fenced.from_micros / 1_000_000, tz=timezone.utc) - to_ts = datetime.fromtimestamp(fenced.to_micros / 1_000_000, tz=timezone.utc) - as_of_ts = datetime.fromtimestamp(fenced.as_of_micros / 1_000_000, tz=timezone.utc) - - where = ["b.ts >= ?", "b.ts <= ?", "b.known_at <= ?"] - params: list[object] = [from_ts, to_ts, as_of_ts] - if listing_ids is not None: - if len(listing_ids) == 0: - return pl.DataFrame() - placeholders = ", ".join(["?"] * len(listing_ids)) - where.append(f"b.listing_id IN ({placeholders})") - params.extend(int(x) for x in listing_ids) - if currencies is not None: - placeholders = ", ".join(["?"] * len(currencies)) - where.append(f"b.currency IN ({placeholders})") - params.extend(str(c) for c in currencies) - - where_sql = " AND ".join(where) - if adjustment == "raw": - sql = f""" - SELECT - b.listing_id, - b.session_date, - b.ts, - b.open, - b.high, - b.low, - b.close, - b.volume, - b.vwap, - b.currency, - b.source, - b.known_at - FROM read_parquet('{self._bars_glob()}', hive_partitioning = true) b - WHERE {where_sql} - ORDER BY b.listing_id ASC, b.session_date ASC - """ - return self._con.execute(sql, params).pl() - - adj_path = self._verify_fenced_adj_factors(fenced.as_of_micros, fenced.scope) - price_col = "cum_split_factor" if adjustment == "split" else "cum_total_factor" - sql = f""" - WITH adj AS ( - SELECT listing_id, ex_date, cum_split_factor, cum_total_factor - FROM read_parquet('{adj_path}') - WHERE known_at <= ? - ) - SELECT - b.listing_id, - b.session_date, - b.ts, - b.open / COALESCE(a.{price_col}, 1.0) AS open, - b.high / COALESCE(a.{price_col}, 1.0) AS high, - b.low / COALESCE(a.{price_col}, 1.0) AS low, - b.close / COALESCE(a.{price_col}, 1.0) AS close, - b.volume * COALESCE(a.cum_split_factor, 1.0) AS volume, - CASE WHEN b.vwap IS NULL THEN NULL ELSE b.vwap / COALESCE(a.{price_col}, 1.0) END AS vwap, - b.currency, - b.source, - b.known_at - FROM read_parquet('{self._bars_glob()}', hive_partitioning = true) b - ASOF LEFT JOIN adj a - ON b.listing_id = a.listing_id AND b.session_date < a.ex_date - WHERE {where_sql} - ORDER BY b.listing_id ASC, b.session_date ASC - """ - return self._con.execute(sql, [as_of_ts, *params]).pl() - - def shorts_as_of( - self, - *, - listing_ids: Sequence[int] | None = None, - from_date: str, - to_date: str, - as_of: str | None = None, - ) -> pl.DataFrame: - fenced = apply_vault_fence(from_date, to_date, self.vault_cutoff_ts, as_of=as_of, scope="vault_fenced") - from_d = datetime.fromtimestamp(fenced.from_ms / 1000.0, tz=timezone.utc).date() - to_d = datetime.fromtimestamp(fenced.to_ms / 1000.0, tz=timezone.utc).date() - as_of_ts = datetime.fromtimestamp(fenced.as_of_micros / 1_000_000, tz=timezone.utc) - - where = ["report_date >= ?", "report_date <= ?", "known_at <= ?"] - params: list[object] = [from_d, to_d, as_of_ts] - if listing_ids is not None: - if len(listing_ids) == 0: - return pl.DataFrame() - placeholders = ", ".join(["?"] * len(listing_ids)) - where.append(f"listing_id IN ({placeholders})") - params.extend(int(x) for x in listing_ids) - - sql = f""" - SELECT listing_id, report_date, known_at, shares_short, net_change, pct_float, source - FROM read_parquet('{self._shorts_path()}') - WHERE {' AND '.join(where)} - ORDER BY listing_id ASC, report_date ASC - """ - return self._con.execute(sql, params).pl() - - def events( - self, - *, - kinds: Sequence[EventKind], - listing_ids: Sequence[int] | None = None, - from_date: str, - to_date: str, - as_of: str | None = None, - ) -> pl.DataFrame: - if not kinds: - raise MarketDataStoreValidationError("events requires at least one kind.") - fenced = apply_vault_fence(from_date, to_date, self.vault_cutoff_ts, as_of=as_of, scope="vault_fenced") - from_ts = datetime.fromtimestamp(fenced.from_micros / 1_000_000, tz=timezone.utc) - to_ts = datetime.fromtimestamp(fenced.to_micros / 1_000_000, tz=timezone.utc) - as_of_ts = datetime.fromtimestamp(fenced.as_of_micros / 1_000_000, tz=timezone.utc) - - kind_ph = ", ".join(["?"] * len(kinds)) - where = [f"kind IN ({kind_ph})", "ts >= ?", "ts <= ?", "known_at <= ?"] - params: list[object] = [*kinds, from_ts, to_ts, as_of_ts] - if listing_ids is not None: - if len(listing_ids) == 0: - return pl.DataFrame() - lid_ph = ", ".join(["?"] * len(listing_ids)) - where.append(f"listing_id IN ({lid_ph})") - params.extend(int(x) for x in listing_ids) - - sql = f""" - SELECT listing_id, ts, known_at, known_at_source, kind, subtype, payload_json - FROM read_parquet('{self._events_glob()}', hive_partitioning = true) - WHERE {' AND '.join(where)} - ORDER BY listing_id ASC, ts ASC - """ - return self._con.execute(sql, params).pl() - - def fx(self, *, pair: str = "USD.CAD", timeframe: str = "1d", from_date: str, to_date: str) -> pl.DataFrame: - if timeframe != "1d": - raise NotImplementedError("FX intraday 1m is reserved for QuestDB (M2).") - if pair != "USD.CAD": - raise MarketDataStoreValidationError(f"Unsupported FX pair: {pair!r}") - fenced = apply_vault_fence(from_date, to_date, self.vault_cutoff_ts, scope="vault_fenced") - from_ts = datetime.fromtimestamp(fenced.from_micros / 1_000_000, tz=timezone.utc) - to_ts = datetime.fromtimestamp(fenced.to_micros / 1_000_000, tz=timezone.utc) - as_of_ts = datetime.fromtimestamp(fenced.as_of_micros / 1_000_000, tz=timezone.utc) - sql = f""" - SELECT pair, session_date, ts, open, high, low, close, source, known_at - FROM read_parquet('{self._fx_path()}') - WHERE pair = 'USDCAD' AND ts >= ? AND ts <= ? AND known_at <= ? - ORDER BY session_date ASC - """ - return self._con.execute(sql, [from_ts, to_ts, as_of_ts]).pl() - - def universe(self, *, ref: UniverseRef, on_date: str, lookback_days: int = 7) -> list[int]: - if ref not in _UNIVERSE_CURRENCIES: - raise MarketDataStoreValidationError(f"Unsupported universe ref: {ref!r}") - fenced = apply_vault_fence(on_date, on_date, self.vault_cutoff_ts, as_of=on_date, scope="vault_fenced") - end_d = date.fromisoformat(on_date) - start_d = end_d - timedelta(days=lookback_days) - to_ts = datetime.fromtimestamp(fenced.to_micros / 1_000_000, tz=timezone.utc) - as_of_ts = datetime.fromtimestamp(fenced.as_of_micros / 1_000_000, tz=timezone.utc) - currencies = _UNIVERSE_CURRENCIES[ref] - ph = ", ".join(["?"] * len(currencies)) - sql = f""" - SELECT DISTINCT listing_id - FROM read_parquet('{self._bars_glob()}', hive_partitioning = true) - WHERE currency IN ({ph}) - AND session_date >= ? - AND session_date <= ? - AND ts <= ? - AND known_at <= ? - ORDER BY listing_id ASC - """ - rows = self._con.execute(sql, [*currencies, start_d, end_d, to_ts, as_of_ts]).fetchall() - return [int(r[0]) for r in rows] diff --git a/python/stockbot/ledger.py b/python/stockbot/ledger.py deleted file mode 100644 index ecd89305..00000000 --- a/python/stockbot/ledger.py +++ /dev/null @@ -1,269 +0,0 @@ -"""Append-only PostgreSQL `trial_ledger` client and cluster N-hat DSR evaluator.""" - -from __future__ import annotations - -import hashlib -import json -import math -import struct -from dataclasses import dataclass -from typing import Any, Literal, Mapping, Sequence - -import numpy as np -import psycopg - -from .calculations import ( - DSR_VALIDATION_GATE, - DeflatedSharpeResult, - EffectiveTrialsResult, - deflated_sharpe_ratio, - effective_independent_trials, - trial_moments, -) -from .vault import VaultHoldoutFenceError, parse_timestamp_ms - -TrialStage = Literal["signal_ic", "event_study", "screen", "engine_backtest"] -UniverseMarket = Literal["US_EQ", "CA_EQ", "US_CA_EQ", "FX"] -HorizonBucket = Literal["intraday", "swing_1_10d", "position_10d_plus"] - - -def _normalize_json_value(value: Any) -> Any: - if value is None or isinstance(value, (bool, str)): - return value - if isinstance(value, (int, float)): - if isinstance(value, float): - if not math.isfinite(value): - raise ValueError(f"Non-finite number forbidden in expression hash: {value!r}") - if value == 0.0: - return 0 - return value - if isinstance(value, Mapping): - out: dict[str, Any] = {} - for k in sorted(value.keys()): - v = value[k] - if v is not None: - out[str(k)] = _normalize_json_value(v) - return out - if isinstance(value, (list, tuple)): - return [_normalize_json_value(v) for v in value] - raise TypeError(f"Unsupported value type for canonical_expression_hash: {type(value)!r}") - - -def canonical_expression_hash( - *, - expression: str, - params: Mapping[str, Any], - universe: str, - sample_start: str, - sample_end: str, - horizon: str, -) -> str: - """64-hex SHA-256 over canonical ASCII-sorted JSON matching `@stock-bot/research`.""" - collapsed_expr = " ".join(expression.strip().split()) - payload = _normalize_json_value( - { - "expression": collapsed_expr, - "horizon": horizon, - "params": params, - "sampleEnd": sample_end, - "sampleStart": sample_start, - "universe": universe, - } - ) - encoded = json.dumps(payload, separators=(",", ":"), sort_keys=True, ensure_ascii=False).encode("utf-8") - return hashlib.sha256(encoded).hexdigest() - - -@dataclass(frozen=True) -class RecordedTrial: - trial_id: int - created_at: str - expression_hash: str - n_obs: int - sharpe_unann: float - skewness: float - kurtosis: float - - -@dataclass(frozen=True) -class ClusterDsrSummary: - trial_id: int - cluster_size: int - effective_trials: float - mean_correlation: float | None - pairs_used: int - pairs_skipped: int - sr0: float - standard_error: float - dsr: float - passes_gate: bool - - -class TrialLedgerClient: - """Append-only writer and cluster DSR reader for PostgreSQL `trial_ledger`.""" - - def __init__(self, dsn: str) -> None: - self._dsn = dsn - - def record_trial( - self, - *, - principal_id: str, - stage: TrialStage, - universe_market: UniverseMarket, - horizon_bucket: HorizonBucket, - expression_hash: str, - sample_start: str, - sample_end: str, - vault_cutoff_date: str, - daily_series: Sequence[float], - campaign_id: str | None = None, - hypothesis_id: str | None = None, - ) -> RecordedTrial: - """Validates Vault fence + float32 precision and inserts into `trial_ledger`.""" - start_ms = parse_timestamp_ms(sample_start, "start", "sample_start") - end_ms = parse_timestamp_ms(sample_end, "end", "sample_end") - cutoff_ms = parse_timestamp_ms(vault_cutoff_date, "start", "vault_cutoff_date") - if end_ms < start_ms: - raise ValueError(f"sample_end ({sample_end}) precedes sample_start ({sample_start}).") - if start_ms >= cutoff_ms: - raise VaultHoldoutFenceError(sample_start, start_ms, cutoff_ms) - if end_ms >= cutoff_ms: - raise VaultHoldoutFenceError(sample_end, end_ms, cutoff_ms) - - # Quantize to IEEE-754 REAL (float32) before moment calculation so stored values match moments - f32_values: list[float] = [] - for x in daily_series: - fx = float(x) - if not math.isfinite(fx): - raise ValueError("daily_series contains non-finite value.") - packed = struct.unpack(" ClusterDsrSummary: - """Loads target trial and its `(universe_market, horizon_bucket)` cluster and computes DSR.""" - with psycopg.connect(self._dsn) as conn: - with conn.cursor() as cur: - cur.execute( - """ - SELECT trial_id, universe_market, horizon_bucket, n_obs, - sharpe_unann, skewness, kurtosis, daily_series - FROM trial_ledger - WHERE trial_id = %s - """, - (trial_id,), - ) - target = cur.fetchone() - if target is None: - raise LookupError(f"trial_id={trial_id} not found in trial_ledger.") - - _, universe_market, horizon_bucket, n_obs, sr, skew, kurt, _ = target - - cur.execute( - """ - SELECT trial_id, sharpe_unann, daily_series - FROM trial_ledger - WHERE universe_market = %s AND horizon_bucket = %s - ORDER BY trial_id ASC - """, - (universe_market, horizon_bucket), - ) - cluster_rows = cur.fetchall() - - cluster_sharpes = [float(r[1]) for r in cluster_rows] - aligned_items: list[tuple[int, dict[str, float]]] = [] - for r_id, _, r_series in cluster_rows: - tid = int(r_id) - dates = (observation_dates_by_trial_id or {}).get(tid) - if dates is not None and len(dates) == len(r_series): - aligned_items.append((tid, {d: float(v) for d, v in zip(dates, r_series)})) - else: - aligned_items.append((tid, {})) - - eff: EffectiveTrialsResult = effective_independent_trials(aligned_items) - dsr_res: DeflatedSharpeResult = deflated_sharpe_ratio( - sharpe_unann=float(sr), - n_obs=int(n_obs), - skewness=float(skew), - kurtosis=float(kurt), - n_hat=eff.n_hat, - cluster_sharpes=cluster_sharpes, - ) - return ClusterDsrSummary( - trial_id=trial_id, - cluster_size=eff.k, - effective_trials=eff.n_hat, - mean_correlation=eff.mean_correlation, - pairs_used=eff.pairs_used, - pairs_skipped=eff.pairs_skipped, - sr0=dsr_res.sr0, - standard_error=dsr_res.standard_error, - dsr=dsr_res.dsr, - passes_gate=dsr_res.dsr >= dsr_gate, - ) diff --git a/python/stockbot/signals.py b/python/stockbot/signals.py deleted file mode 100644 index da18fbb4..00000000 --- a/python/stockbot/signals.py +++ /dev/null @@ -1,137 +0,0 @@ -"""High-level Signal Analyzer & Event Study runners with write-before-return trial logging.""" - -from __future__ import annotations - -from typing import Any, Mapping - -import polars as pl - -from .calculations import analyze_signal_panel, compute_event_study -from .ledger import ( - ClusterDsrSummary, - HorizonBucket, - RecordedTrial, - TrialLedgerClient, - UniverseMarket, - canonical_expression_hash, -) - - -def run_signal_study( - *, - panel: pl.DataFrame, - ledger: TrialLedgerClient, - principal_id: str = "operator", - universe_market: UniverseMarket, - horizon_bucket: HorizonBucket, - horizon_label: str, - expression: str, - params: Mapping[str, Any], - vault_cutoff_date: str, - n_quantiles: int = 5, - min_cross_section: int = 10, - ledger_series: str = "rank_ic", -) -> dict[str, Any]: - """Runs Signal Analyzer under the Vault fence, writes to `trial_ledger`, and computes cluster DSR.""" - analysis = analyze_signal_panel( - panel, - vault_cutoff_date=vault_cutoff_date, - n_quantiles=n_quantiles, - min_cross_section=min_cross_section, - ) - dates: list[str] = analysis["dates"] # type: ignore[assignment] - if len(dates) < 2: - return {"status": "insufficient_data", "analysis": analysis, "trial": None, "dsr": None} - - series: list[float] = ( - analysis["rank_ic_series"] if ledger_series == "rank_ic" else analysis["spread_series"] - ) # type: ignore[assignment] - expr_hash = canonical_expression_hash( - expression=expression, - params=params, - universe=universe_market, - sample_start=dates[0], - sample_end=dates[-1], - horizon=horizon_label, - ) - recorded: RecordedTrial = ledger.record_trial( - principal_id=principal_id, - stage="signal_ic", - universe_market=universe_market, - horizon_bucket=horizon_bucket, - expression_hash=expr_hash, - sample_start=dates[0], - sample_end=dates[-1], - vault_cutoff_date=vault_cutoff_date, - daily_series=series, - ) - dsr: ClusterDsrSummary = ledger.cluster_deflated_sharpe( - trial_id=recorded.trial_id, - observation_dates_by_trial_id={recorded.trial_id: dates}, - ) - return { - "status": "ok", - "analysis": analysis, - "trial": recorded, - "dsr": dsr, - } - - -def run_event_study_trial( - *, - bars_df: pl.DataFrame, - events_df: pl.DataFrame, - ledger: TrialLedgerClient, - principal_id: str = "operator", - universe_market: UniverseMarket, - horizon_bucket: HorizonBucket, - expression: str, - params: Mapping[str, Any], - vault_cutoff_date: str, - pre_days: int = 5, - post_days: int = 10, - min_events: int = 5, -) -> dict[str, Any]: - """Runs Event Study under the Vault fence, writes to `trial_ledger`, and computes cluster DSR.""" - study = compute_event_study( - bars_df, - events_df, - vault_cutoff_date=vault_cutoff_date, - pre_days=pre_days, - post_days=post_days, - min_events=min_events, - ) - if study.get("status") != "ok": - return {"status": "insufficient_data", "study": study, "trial": None, "dsr": None} - - dates: list[str] = study["clustered_dates"] # type: ignore[assignment] - series: list[float] = study["mean_cars"] # type: ignore[assignment] - expr_hash = canonical_expression_hash( - expression=expression, - params=params, - universe=universe_market, - sample_start=dates[0], - sample_end=dates[-1], - horizon=f"event_-{pre_days}_+{post_days}d", - ) - recorded = ledger.record_trial( - principal_id=principal_id, - stage="event_study", - universe_market=universe_market, - horizon_bucket=horizon_bucket, - expression_hash=expr_hash, - sample_start=dates[0], - sample_end=dates[-1], - vault_cutoff_date=vault_cutoff_date, - daily_series=series, - ) - dsr = ledger.cluster_deflated_sharpe( - trial_id=recorded.trial_id, - observation_dates_by_trial_id={recorded.trial_id: dates}, - ) - return { - "status": "ok", - "study": study, - "trial": recorded, - "dsr": dsr, - } diff --git a/python/stockbot/vault.py b/python/stockbot/vault.py deleted file mode 100644 index b3e714dc..00000000 --- a/python/stockbot/vault.py +++ /dev/null @@ -1,226 +0,0 @@ -"""Rolling 6-month UTC Vault holdout fence & DuckDB connection budget.""" - -from __future__ import annotations - -import calendar -import os -import re -from dataclasses import dataclass -from datetime import datetime, timezone -from typing import Literal, Mapping - -DataScope = Literal["vault_fenced", "vault_evaluation_only"] - -DEFAULT_DUCKDB_MEMORY_LIMIT = "6GB" -DEFAULT_DUCKDB_THREADS = 4 -DEFAULT_DUCKDB_TEMP_DIRECTORY = "/mnt/data/stockbot/tmp/duckdb" - -_DATE_ONLY_RE = re.compile(r"^(\d{4})-(\d{2})-(\d{2})$") -_MEM_LIMIT_RE = re.compile(r"^(\d+(?:\.\d+)?)(MB|GB|MiB|GiB)$") - - -class MarketDataStoreValidationError(ValueError): - """Raised when market-data query bounds, timestamps, or budgets are invalid.""" - - -class VaultHoldoutFenceError(PermissionError): - """Raised when a fenced query reaches or exceeds the rolling 6-month Vault cutoff.""" - - def __init__(self, from_bound: str, from_ms: int, vault_cutoff_ts: int) -> None: - super().__init__( - f'Query start "{from_bound}" ({from_ms}) reaches or exceeds Vault cutoff ({vault_cutoff_ts}).' - ) - self.from_bound = from_bound - self.from_ms = from_ms - self.vault_cutoff_ts = vault_cutoff_ts - - -class VaultScopeNotAuthorizedError(PermissionError): - """Raised when vault_evaluation_only is requested without operator authorization.""" - - -@dataclass(frozen=True) -class FencedTimeRange: - from_ms: int - to_ms: int - as_of_ms: int - scope: DataScope - clamped_to: bool - clamped_as_of: bool - - @property - def from_micros(self) -> int: - return self.from_ms * 1000 - - @property - def to_micros(self) -> int: - # Expand end-of-ms inclusive boundary to last microsecond (.999999) when ms ends in 999 - return self.to_ms * 1000 + (999 if self.to_ms % 1000 == 999 else 0) - - @property - def as_of_micros(self) -> int: - return self.as_of_ms * 1000 + (999 if self.as_of_ms % 1000 == 999 else 0) - - -@dataclass(frozen=True) -class DuckDbConnectionBudget: - memory_limit: str - threads: int - temp_directory: str - - @property - def statements(self) -> tuple[str, str, str]: - escaped = self.temp_directory.replace("'", "''") - return ( - f"SET memory_limit = '{self.memory_limit}';", - f"SET threads = {self.threads};", - f"SET temp_directory = '{escaped}';", - ) - - -def parse_timestamp_ms(raw: str, bound_kind: Literal["start", "end"], field: str) -> int: - if not isinstance(raw, str) or not raw: - raise MarketDataStoreValidationError(f'Expected non-empty ISO-8601 string for "{field}".') - m = _DATE_ONLY_RE.match(raw) - if m: - year, month, day = int(m.group(1)), int(m.group(2)), int(m.group(3)) - if bound_kind == "start": - dt = datetime(year, month, day, 0, 0, 0, 0, tzinfo=timezone.utc) - else: - dt = datetime(year, month, day, 23, 59, 59, 999000, tzinfo=timezone.utc) - return int(dt.timestamp() * 1000) - - try: - dt = datetime.fromisoformat(raw.replace("Z", "+00:00")) - except ValueError as exc: - raise MarketDataStoreValidationError( - f'Invalid ISO-8601 date or UTC timestamp for "{field}": "{raw}".' - ) from exc - if dt.tzinfo is None: - raise MarketDataStoreValidationError( - f'Naive timestamp without timezone offset is forbidden for "{field}": "{raw}".' - ) - dt_utc = dt.astimezone(timezone.utc) - return int(dt_utc.timestamp() * 1000) - - -def compute_vault_cutoff_ts(max_ingested_ts: int | str | datetime) -> int: - """Computes rolling 6-month Vault cutoff (`max_ingested_ts - 6 calendar months` UTC).""" - if isinstance(max_ingested_ts, int) and not isinstance(max_ingested_ts, bool): - epoch_ms = max_ingested_ts - elif isinstance(max_ingested_ts, str): - epoch_ms = parse_timestamp_ms(max_ingested_ts, "start", "max_ingested_ts") - elif isinstance(max_ingested_ts, datetime): - if max_ingested_ts.tzinfo is None: - raise MarketDataStoreValidationError("max_ingested_ts datetime must be timezone-aware.") - epoch_ms = int(max_ingested_ts.astimezone(timezone.utc).timestamp() * 1000) - else: - raise MarketDataStoreValidationError("Invalid max_ingested_ts type.") - - dt = datetime.fromtimestamp(epoch_ms / 1000.0, tz=timezone.utc) - total_months = dt.year * 12 + (dt.month - 1) - 6 - target_year, target_month_zero = divmod(total_months, 12) - target_month = target_month_zero + 1 - max_day = calendar.monthrange(target_year, target_month)[1] - target_day = min(dt.day, max_day) - cutoff_dt = datetime( - target_year, - target_month, - target_day, - dt.hour, - dt.minute, - dt.second, - dt.microsecond, - tzinfo=timezone.utc, - ) - return int(cutoff_dt.timestamp() * 1000) - - -def vault_cutoff_date_str(vault_cutoff_ts: int) -> str: - return datetime.fromtimestamp(vault_cutoff_ts / 1000.0, tz=timezone.utc).strftime("%Y-%m-%d") - - -def apply_vault_fence( - from_bound: str, - to_bound: str, - vault_cutoff_ts: int, - as_of: str | None = None, - scope: DataScope = "vault_fenced", - vault_operator_authorized: bool = False, -) -> FencedTimeRange: - from_ms = parse_timestamp_ms(from_bound, "start", "from") - to_ms = parse_timestamp_ms(to_bound, "end", "to") - if to_ms < from_ms: - raise MarketDataStoreValidationError( - f'Query end "{to_bound}" ({to_ms}) precedes start "{from_bound}" ({from_ms}).' - ) - - if scope == "vault_evaluation_only": - if not vault_operator_authorized: - raise VaultScopeNotAuthorizedError( - "Data scope 'vault_evaluation_only' requires explicit human operator authorization." - ) - as_of_ms = parse_timestamp_ms(as_of, "end", "as_of") if as_of is not None else to_ms - return FencedTimeRange( - from_ms=from_ms, - to_ms=to_ms, - as_of_ms=as_of_ms, - scope=scope, - clamped_to=False, - clamped_as_of=False, - ) - - if scope != "vault_fenced": - raise MarketDataStoreValidationError(f"Unsupported scope: {scope!r}") - - if from_ms >= vault_cutoff_ts: - raise VaultHoldoutFenceError(from_bound, from_ms, vault_cutoff_ts) - - clamped_to = False - if to_ms >= vault_cutoff_ts: - to_ms = vault_cutoff_ts - 1 - clamped_to = True - - clamped_as_of = False - if as_of is None: - as_of_ms = vault_cutoff_ts - 1 - else: - as_of_ms = parse_timestamp_ms(as_of, "end", "as_of") - if as_of_ms >= vault_cutoff_ts: - as_of_ms = vault_cutoff_ts - 1 - clamped_as_of = True - - return FencedTimeRange( - from_ms=from_ms, - to_ms=to_ms, - as_of_ms=as_of_ms, - scope="vault_fenced", - clamped_to=clamped_to, - clamped_as_of=clamped_as_of, - ) - - -def resolve_duckdb_budget( - env: Mapping[str, str] | None = None, - *, - memory_limit: str | None = None, - threads: int | None = None, - temp_directory: str | None = None, -) -> DuckDbConnectionBudget: - source = env if env is not None else os.environ - mem = memory_limit or source.get("STOCK_BOT_DUCKDB_MEMORY_LIMIT") or DEFAULT_DUCKDB_MEMORY_LIMIT - if not _MEM_LIMIT_RE.match(mem): - raise MarketDataStoreValidationError(f"Invalid DuckDB memory_limit: {mem!r}") - raw_threads = threads if threads is not None else int( - source.get("STOCK_BOT_DUCKDB_THREADS", str(DEFAULT_DUCKDB_THREADS)) - ) - if not isinstance(raw_threads, int) or raw_threads < 1 or raw_threads > 64: - raise MarketDataStoreValidationError(f"Invalid DuckDB threads: {raw_threads!r}") - tmp_dir = ( - temp_directory - or source.get("STOCK_BOT_DUCKDB_TEMP_DIRECTORY") - or DEFAULT_DUCKDB_TEMP_DIRECTORY - ) - if not tmp_dir or not tmp_dir.startswith("/"): - raise MarketDataStoreValidationError(f"Invalid DuckDB temp_directory: {tmp_dir!r}") - return DuckDbConnectionBudget(memory_limit=mem, threads=raw_threads, temp_directory=tmp_dir) diff --git a/python/tests/test_stockbot_sdk.py b/python/tests/test_stockbot_sdk.py deleted file mode 100644 index 55ba8fbe..00000000 --- a/python/tests/test_stockbot_sdk.py +++ /dev/null @@ -1,153 +0,0 @@ -"""Unit tests for the `stockbot` Python SDK (Vault fence, DSR parity, DuckDB/Parquet store).""" - -from __future__ import annotations - -import math -from datetime import date, datetime, timezone -from pathlib import Path - -import polars as pl -import pytest - -from stockbot import ( - MarketDataStore, - VaultHoldoutFenceError, - VaultScopeNotAuthorizedError, - analyze_signal_panel, - apply_vault_fence, - canonical_expression_hash, - compute_vault_cutoff_ts, - deflated_sharpe_ratio, - effective_independent_trials, - resolve_duckdb_budget, - trial_moments, -) - - -def test_vault_cutoff_and_fencing_rules() -> None: - cutoff = compute_vault_cutoff_ts("2025-08-13") - expected = int(datetime(2025, 2, 13, 0, 0, 0, tzinfo=timezone.utc).timestamp() * 1000) - assert cutoff == expected - - # Clamps to and as_of strictly below cutoff - fenced = apply_vault_fence("2020-01-01", "2025-08-13", cutoff) - assert fenced.clamped_to is True - assert fenced.to_ms == cutoff - 1 - assert fenced.as_of_ms == cutoff - 1 - - # Rejects start >= cutoff - with pytest.raises(VaultHoldoutFenceError): - apply_vault_fence("2025-02-13", "2025-05-01", cutoff) - - # Rejects unauthorized vault_evaluation_only - with pytest.raises(VaultScopeNotAuthorizedError): - apply_vault_fence("2025-02-13", "2025-05-01", cutoff, scope="vault_evaluation_only") - - -def test_trial_moments_and_dsr_match_canonical_math() -> None: - series = [0.01, 0.02, -0.005, 0.015, 0.008, -0.002, 0.012, 0.004] - m = trial_moments(series) - assert m.n_obs == 8 - assert m.sharpe_unann > 0.0 - assert m.kurtosis >= m.skewness ** 2 + 1.0 - - # Identical series -> rho = 1.0 -> N_hat = 1.0 - dates = [f"2024-01-0{i+1}" for i in range(len(series))] - eff_dup = effective_independent_trials( - [(1, dict(zip(dates, series))), (2, dict(zip(dates, series)))] - ) - assert math.isclose(eff_dup.mean_correlation or 0.0, 1.0, rel_tol=1e-9) - assert math.isclose(eff_dup.n_hat, 1.0, rel_tol=1e-9) - - dsr = deflated_sharpe_ratio( - sharpe_unann=m.sharpe_unann, - n_obs=m.n_obs, - skewness=m.skewness, - kurtosis=m.kurtosis, - n_hat=2.0, - cluster_sharpes=[m.sharpe_unann, 0.1], - ) - assert 0.0 <= dsr.dsr <= 1.0 - assert dsr.standard_error > 0.0 - - -def test_canonical_expression_hash_is_deterministic() -> None: - h1 = canonical_expression_hash( - expression=" ca_shorts neg_shares_short ", - params={"b": 2, "a": 1, "skip": None}, - universe="CA_EQ", - sample_start="2018-01-01", - sample_end="2025-01-31", - horizon="5d", - ) - h2 = canonical_expression_hash( - expression="ca_shorts neg_shares_short", - params={"a": 1, "b": 2}, - universe="CA_EQ", - sample_start="2018-01-01", - sample_end="2025-01-31", - horizon="5d", - ) - assert len(h1) == 64 - assert h1 == h2 - - -def test_duckdb_market_data_store_enforces_vault_fence(tmp_path: Path) -> None: - bars_dir = tmp_path / "bars_1d" / "year=2025" - bars_dir.mkdir(parents=True) - df = pl.DataFrame( - { - "listing_id": pl.Series([1, 1], dtype=pl.Int32), - "ts": pl.Series( - [ - datetime(2025, 2, 10, 21, 0, 0, tzinfo=timezone.utc), - datetime(2025, 2, 20, 21, 0, 0, tzinfo=timezone.utc), - ], - dtype=pl.Datetime("us", "UTC"), - ), - "session_date": pl.Series([date(2025, 2, 10), date(2025, 2, 20)], dtype=pl.Date), - "open": [10.0, 11.0], - "high": [10.5, 11.5], - "low": [9.8, 10.8], - "close": [10.2, 11.2], - "volume": [1000.0, 2000.0], - "vwap": [None, None], - "currency": ["CAD", "CAD"], - "source": ["eod", "eod"], - "known_at": pl.Series( - [ - datetime(2025, 2, 10, 21, 0, 0, tzinfo=timezone.utc), - datetime(2025, 2, 20, 21, 0, 0, tzinfo=timezone.utc), - ], - dtype=pl.Datetime("us", "UTC"), - ), - } - ) - df.write_parquet(bars_dir / "part.parquet") - - cutoff = compute_vault_cutoff_ts("2025-08-13") # 2025-02-13 - budget = resolve_duckdb_budget(memory_limit="1GB", threads=2, temp_directory=str(tmp_path / "tmp")) - with MarketDataStore(tmp_path, vault_cutoff_ts=cutoff, budget=budget) as store: - out = store.bars(from_date="2025-01-01", to_date="2025-08-13", adjustment="raw") - assert out.height == 1 - assert str(out["session_date"][0]) == "2025-02-10" - - -def test_signal_panel_analyzer_excludes_vault_rows() -> None: - rows = [] - for day_idx in range(1, 20): - d = f"2025-02-{day_idx:02d}" - for lid in range(1, 15): - rows.append( - { - "session_date": d, - "listing_id": lid, - "signal": float(lid), - "forward_return": 0.001 * lid + (0.0001 * day_idx), - } - ) - panel = pl.DataFrame(rows) - res = analyze_signal_panel(panel, vault_cutoff_date="2025-02-13", min_cross_section=10) - assert res["vault_excluded_rows"] > 0 - assert all(d < "2025-02-13" for d in res["dates"]) # type: ignore[union-attr] - assert res["mean_rank_ic"] > 0.9 # type: ignore[operator] diff --git a/python/uv.lock b/python/uv.lock deleted file mode 100644 index e673a52e..00000000 --- a/python/uv.lock +++ /dev/null @@ -1,1308 +0,0 @@ -version = 1 -revision = 3 -requires-python = ">=3.11" -resolution-markers = [ - "python_full_version >= '3.12'", - "python_full_version < '3.12'", -] - -[[package]] -name = "anyio" -version = "4.16.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "idna" }, - { name = "typing-extensions", marker = "python_full_version < '3.15'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/a1/98/7e457a3b014976887a050561955c0b76e1e7e2d6e27b78ecef2ef80518f2/anyio-4.16.0.tar.gz", hash = "sha256:59bb03251907983d1603d27c3087ddb1e93299ea2163adcdba37899a4fb12ffb", size = 310971, upload-time = "2026-11-01T11:20:07.282Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/a9/16/7757fb84c819accc7d7e9af5291b261e4abb8627ee040f99e7d35ef2457a/anyio-4.16.0-py3-none-any.whl", hash = "sha256:c66ae634e0b8228396b801741beb3294326d4b6102f7bba4041c0dfb58c29026", size = 134521, upload-time = "2026-11-01T11:20:05.59Z" }, -] - -[[package]] -name = "cffi" -version = "2.1.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pycparser" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/9e/ef/008a1939e372c06329a3fce4279c02f328488f3526744906eeec3da7ad5f/cffi-2.1.1.tar.gz", hash = "sha256:dd31f52ea1086513bb9df30f8fcee9b8918323ae067a3d5b78bc826a000712be", size = 530807, upload-time = "2026-08-03T21:21:18.939Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/70/d2/16d99a0c4948febc0ebd133a13b2f688ff7f8cb04da971e1128872ce0c03/cffi-2.1.1-cp311-cp311-macosx_10_15_x86_64.whl", hash = "sha256:c8d2c9fd1f2d16f780d15127abb050d13d1a76c03a4bd87d7e4980e45e511e12", size = 183838, upload-time = "2026-08-03T21:19:29.637Z" }, - { url = "https://files.pythonhosted.org/packages/cd/95/31b535a9f0220ae9f357de4a08d57ce89cb417653c2fd9f075f50822a388/cffi-2.1.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:398aff33cee2767e3e781d2554c54bd0dff386bb437581e0d8011fde1a942ec1", size = 184168, upload-time = "2026-08-03T21:19:30.764Z" }, - { url = "https://files.pythonhosted.org/packages/ad/5a/4707a0dc1f203f5dde5a907b0d4e3c25d71120241048bd5bc6f1bb9d4e71/cffi-2.1.1-cp311-cp311-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:154852545011f779917b11c78db2358d095da62a9a172b78ad0a583ee5adc0d0", size = 211805, upload-time = "2026-08-03T21:19:31.867Z" }, - { url = "https://files.pythonhosted.org/packages/ad/66/c19feabb28485b6e0bbaaafa90837a1ef5d302e90f2178bd33f17a49879b/cffi-2.1.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:3311ed60d36f83378794e1009ac6258bafbf81f7888b4caa7b35a521e3f95813", size = 218716, upload-time = "2026-08-03T21:19:32.896Z" }, - { url = "https://files.pythonhosted.org/packages/a7/92/500760486c8baab49a7a8a58ba7fc3355ec3974b454b8a09e528efde9e1d/cffi-2.1.1-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:6e192623c49c94421616a5778fba35cf0d5a8d000650c1967ef4448ee5cdd990", size = 205569, upload-time = "2026-08-03T21:19:34.142Z" }, - { url = "https://files.pythonhosted.org/packages/a5/a7/a67c733254d6e7373f7822f8082d8d6beade791e0cf12a7611f376fa61c7/cffi-2.1.1-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a6e721d4b0e45d5b65e87534470e67b18dcd092c83f68fba09f152b9cbc061af", size = 204907, upload-time = "2026-08-03T21:19:35.174Z" }, - { url = "https://files.pythonhosted.org/packages/f7/a4/4399daaf8f7dfee9d7c3327fdb0426ee041cc63edc358b93911ceb2bfc7a/cffi-2.1.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:34e261f78cb6ceaaa36f42f2613f4380d94d9c759a9c73c769ee6e0247364632", size = 217807, upload-time = "2026-08-03T21:19:36.286Z" }, - { url = "https://files.pythonhosted.org/packages/28/f7/dabe6da2466ecbd82dc62e7342dc6b1065dad990c06f00f0ede9ebf2a0ed/cffi-2.1.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:7225e4514edb64eb6740324353e0da0711954fd8d7da4576755b1c6e09b697cd", size = 221252, upload-time = "2026-08-03T21:19:37.416Z" }, - { url = "https://files.pythonhosted.org/packages/ce/87/616202d8e51342c07d2534c510111c4cc37201775ce8f60802c9335d1edd/cffi-2.1.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:df913725b79db7bcf03448f36b7bf8815363417d5b58deecf9305e3e30f0f21a", size = 214214, upload-time = "2026-08-03T21:19:38.507Z" }, - { url = "https://files.pythonhosted.org/packages/b4/c6/ab025d75d2c26c19b087c0124e75ee31cb65032f4fe345d356d8c507ab97/cffi-2.1.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:f5cfbc5fe74540d335175b656c725d74d90e3730c626d92575eea35029d9afaa", size = 219408, upload-time = "2026-08-03T21:19:39.809Z" }, - { url = "https://files.pythonhosted.org/packages/db/e2/7e8109f65445bdc673a7b54f02c677de462db75674220fd1335efc8eb598/cffi-2.1.1-cp311-cp311-win32.whl", hash = "sha256:f8ec5e643a9a937f64e1999eb9f75d072263751912dc5cd06d3c85f8f44be7c3", size = 174470, upload-time = "2026-08-03T21:19:41.246Z" }, - { url = "https://files.pythonhosted.org/packages/73/c0/77ba02423c2f7d7091143c45cd49e0e6575c4c1967394bb542bd923a9b74/cffi-2.1.1-cp311-cp311-win_amd64.whl", hash = "sha256:42f6930c31dc7f50732c9ae793c2786c7b6b044195967bbdde40bb9be81c4cc0", size = 185096, upload-time = "2026-08-03T21:19:42.615Z" }, - { url = "https://files.pythonhosted.org/packages/7c/47/9f1f85f9672ceda4984dc6c4f8824e8558992a2972c3d3c81fb8eb28d4ba/cffi-2.1.1-cp311-cp311-win_arm64.whl", hash = "sha256:c7659f22557c5a0bc4855cd635f55edec690cc008a40768527762cb9fb263455", size = 179941, upload-time = "2026-08-03T21:19:43.747Z" }, - { url = "https://files.pythonhosted.org/packages/10/69/43965eccfdead3b9220015fd1320e117be8c6ed01a62ffab76eeb752f5d5/cffi-2.1.1-cp312-cp312-macosx_10_15_x86_64.whl", hash = "sha256:c8c69575568085ba0b1b10c0249d779a214aea6f6522e949a0fc9fb0fcb449d0", size = 184821, upload-time = "2026-08-03T21:19:44.887Z" }, - { url = "https://files.pythonhosted.org/packages/54/7d/16e5a096677b5e313ca80cd5e5170efa3ea44624a82bb111925522da64b1/cffi-2.1.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f81b3b8f3d4e343550fa4baa0e479bba9f2d29ce9c2e9b51d1ce1718d7442fcf", size = 184719, upload-time = "2026-08-03T21:19:46.129Z" }, - { url = "https://files.pythonhosted.org/packages/56/e6/8941622732edec876dd17d0453dce07317ae96db34f2ec1436c9d3785986/cffi-2.1.1-cp312-cp312-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:811bd1e21d32de12efca32393a0ab3f5133b54fce9bd44b8bd77ab07da14bf6a", size = 214799, upload-time = "2026-08-03T21:19:47.218Z" }, - { url = "https://files.pythonhosted.org/packages/44/de/f98430906df1545ffde0d543dd124a7a439bc2cd32b36b9c53f805df7333/cffi-2.1.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:68e62fe11f30d5ca8289242866f0a5291402d8529ca2178ab8afc5c9694ae890", size = 222389, upload-time = "2026-08-03T21:19:48.331Z" }, - { url = "https://files.pythonhosted.org/packages/6a/5b/717f1526b9957b34456313c31645c5b82b8fb5c3fe9e4752999be7128bfc/cffi-2.1.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:4a7c934f7360e8cd64fe9efadcbd10c7c6364f531e432b9a4bf5ccbc9e0e8b50", size = 210249, upload-time = "2026-08-03T21:19:49.543Z" }, - { url = "https://files.pythonhosted.org/packages/64/b3/f8aa4f3e34986c7e4ec45072d1b1b9dd295b6b18007b45518d79726dd725/cffi-2.1.1-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:3143d81e29e1e20a9ce10901ec369012947876596f75a222235965f2b7ae832e", size = 208775, upload-time = "2026-08-03T21:19:50.918Z" }, - { url = "https://files.pythonhosted.org/packages/b1/db/dceb9dd5b231e1da801793f8acc9f3c52a7e1afe40bb1aae37e02b0faad5/cffi-2.1.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c1453022f490d2459a11819d83ad1d586e9ff65a12ac3e705ffebd46d3685dcf", size = 221822, upload-time = "2026-08-03T21:19:52.054Z" }, - { url = "https://files.pythonhosted.org/packages/a0/d2/6cd24ae3be000a634109c247d1475d62e5616d0dc78c82770942ec384248/cffi-2.1.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:208f941bb9d18e768138677f0a6d2ce01f590df56043dda1df1535ac57c88517", size = 225232, upload-time = "2026-08-03T21:19:53.109Z" }, - { url = "https://files.pythonhosted.org/packages/cb/52/3fa190537004dd7f0ab860a6dc7c0175b8667f68d1e618a46f5498d30250/cffi-2.1.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:210019b6c7cf07f081b4c54635c8cf744377001350e29cc0f81c4377b4797735", size = 223597, upload-time = "2026-08-03T21:19:54.515Z" }, - { url = "https://files.pythonhosted.org/packages/80/fb/0bb75b7039588c074b37ae99f40d9bfddf990ecb2fbc346ebccd2e56b9be/cffi-2.1.1-cp312-cp312-win32.whl", hash = "sha256:046bfc24911b37851ee1b51aab8bffe713d89c68c6a057b09484ce9fd5f69b4e", size = 175292, upload-time = "2026-08-03T21:19:55.566Z" }, - { url = "https://files.pythonhosted.org/packages/d9/79/615cc094e2fb508cade7de88d3b4f6c4ec2bab695c97bce9153dc65aadf5/cffi-2.1.1-cp312-cp312-win_amd64.whl", hash = "sha256:f53e442b08449d42821fa4a4fba000095af9f62742a500f978a9f557ec44339a", size = 185919, upload-time = "2026-08-03T21:19:56.89Z" }, - { url = "https://files.pythonhosted.org/packages/70/c6/d0ea84713fe46b243a436a18fcd47d639732747e21635c8a27191b06dc30/cffi-2.1.1-cp312-cp312-win_arm64.whl", hash = "sha256:7bde5e4cc5c10140859842b9d383af292b22639a4dffb725314baf45968cef80", size = 180093, upload-time = "2026-08-03T21:19:58.155Z" }, - { url = "https://files.pythonhosted.org/packages/9d/f4/035513d4117049066b4779dc3b7c0c0fdad175fa13731c9f4003f1cd1478/cffi-2.1.1-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:b5bdfd1c873d4e093aabc0ca84c4ca6dbc4f752afb5c86f146d9742580c9da2e", size = 194248, upload-time = "2026-08-03T21:19:59.399Z" }, - { url = "https://files.pythonhosted.org/packages/76/af/2aeb4dbb5fc41a04161ae9ff1518de7cec08e164f44a8ce6a4cf7fd2cd1d/cffi-2.1.1-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:31348097ff5bbe827ccc41795d4dd099d9f0625e7def00ee653c137a490c2a6c", size = 196908, upload-time = "2026-08-03T21:20:00.746Z" }, - { url = "https://files.pythonhosted.org/packages/a7/46/2e5fdde8555706dd98139a910ca11be02809f3f605ce956f655d0214e100/cffi-2.1.1-cp313-cp313-macosx_10_15_x86_64.whl", hash = "sha256:9d2055050ea716bd38b7f7f1579c275386646b4894c155a3e2f3cd62ed41b7c6", size = 184805, upload-time = "2026-08-03T21:20:02.02Z" }, - { url = "https://files.pythonhosted.org/packages/55/41/4c7042f317b9217502988f0873af87e16ad606dc20f84e546e3e6ce9764c/cffi-2.1.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:19ee6127ee34de7d83ce3d371ebc5ed91addbdcc39f9ab15ce4eb35a4e534971", size = 184764, upload-time = "2026-08-03T21:20:03.141Z" }, - { url = "https://files.pythonhosted.org/packages/43/1f/1c3d90d91811c8f86ced9ed637956c54bfe5b79ca98fe976d7f8c8979f6b/cffi-2.1.1-cp313-cp313-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:6a8dddef476fab96d066d578fc88526767b836ab5ab21754e1d5bf3879c31c7c", size = 214722, upload-time = "2026-08-03T21:20:04.377Z" }, - { url = "https://files.pythonhosted.org/packages/37/6f/3b5ce4c3b2192d250f04908f2bfd91ef34552ec8f7716a5d4abdb8d67bb2/cffi-2.1.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f16c709686a78c727bbbf059f92b0bf41c6fc60deec706d2dc19f529175a6125", size = 222369, upload-time = "2026-08-03T21:20:05.544Z" }, - { url = "https://files.pythonhosted.org/packages/02/10/4b3c75dde3d9663c9e02ba05c2668b954f671d4bbe346413ca8c696b295a/cffi-2.1.1-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:fcd22650c908d7b7da162bbfaab594a1227a15d1643a98c68b122ac642fa2264", size = 210175, upload-time = "2026-08-03T21:20:06.75Z" }, - { url = "https://files.pythonhosted.org/packages/df/62/14f74b9543e605d17701dc797b815958b8bb70b7624ce1b832ddad48ed6c/cffi-2.1.1-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:aa9511c62d14da7aacc9b4bf51f3f697a621e83b2d6919008243c3aad168eea3", size = 208670, upload-time = "2026-08-03T21:20:08.04Z" }, - { url = "https://files.pythonhosted.org/packages/95/95/86342356ff5953b3fb06f7ef7c5bee212d45e770abc7218d451b9148313c/cffi-2.1.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a931079504ecc49efed7744c476a5c343a92fabf66dec2db95edb1b2fdc770e2", size = 221824, upload-time = "2026-08-03T21:20:09.274Z" }, - { url = "https://files.pythonhosted.org/packages/eb/ff/7b3429ff53aafe931ed8a5fc69f481bbef7ba6de87ddcbb63d08f483f613/cffi-2.1.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a2d7755bef5a12ed488f4ef1f1b69ee9191d7396083b755a5d2295f6edb4768b", size = 225148, upload-time = "2026-08-03T21:20:10.7Z" }, - { url = "https://files.pythonhosted.org/packages/34/34/a95870b9221e09cf4f2ce3178b1a210abdfe63a1bd357da940418d7b8d15/cffi-2.1.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e0bcb7e0f677f543555d2adff3bf19c05f66cdb4796e5ff602442ab2fe3c4ef7", size = 223564, upload-time = "2026-08-03T21:20:12.165Z" }, - { url = "https://files.pythonhosted.org/packages/70/ea/839b50531021a647fb5e929f72cf97bc1ff702b5472166164b5b6e76b851/cffi-2.1.1-cp313-cp313-win32.whl", hash = "sha256:334644fbac4eff73d985a17a91226df55d0f394160c4cfb880e084c8f7161cac", size = 175263, upload-time = "2026-08-03T21:20:13.559Z" }, - { url = "https://files.pythonhosted.org/packages/60/a6/8b149b2c3f2e11aaa1618ef64500b45f50f22c57a977a4dff1aff1f91042/cffi-2.1.1-cp313-cp313-win_amd64.whl", hash = "sha256:1aa5645c30469b09530c4ebca77ebf8f17618293c58f8549cb1a543a50236e7d", size = 185688, upload-time = "2026-08-03T21:20:14.69Z" }, - { url = "https://files.pythonhosted.org/packages/01/9a/11f687cb39d6a3504060d5242f04f48c735afb4d3d533958a20594890cb2/cffi-2.1.1-cp313-cp313-win_arm64.whl", hash = "sha256:63bbfd5ded17c4840ac07cd8f1c21ba9d9708141f840b324f422f41b207e3973", size = 180078, upload-time = "2026-08-03T21:20:15.917Z" }, - { url = "https://files.pythonhosted.org/packages/d3/7b/d6bbf82b8b96e7391438898c42f5bd96dd02030fd5b64937d248220003e2/cffi-2.1.1-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:7dbb61fe3a7699468030f71bbe5f8a0e326a151daa91beb11a6fc1f980c55e1c", size = 194064, upload-time = "2026-08-03T21:20:17.148Z" }, - { url = "https://files.pythonhosted.org/packages/94/e6/bcc91b283be94735e268487a054004f0aa19947b6348fa367db53230abc8/cffi-2.1.1-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:f24fb43132a4c6b4cb4eb029492919b2db645be6808d738f244fd146c03c32cb", size = 196720, upload-time = "2026-08-03T21:20:18.268Z" }, - { url = "https://files.pythonhosted.org/packages/d9/99/c4b0c17cacdc9c3b8f280026286a9826d6a208c0f047591a3c3ce99b91fd/cffi-2.1.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:d28630f5854ab07ab1fd4aba756de52326c82e6be15d414b12793f1975048b54", size = 184964, upload-time = "2026-08-03T21:20:19.708Z" }, - { url = "https://files.pythonhosted.org/packages/b3/a9/9db617d05d7367c1ad0ab00b3aa6e6f9281edd689b4ee9ea0e5a84e89c97/cffi-2.1.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:661c298b4821edebead0c91edd2b00374d67ad7c5a1f7a91d4442633b79d6a72", size = 184962, upload-time = "2026-08-03T21:20:20.833Z" }, - { url = "https://files.pythonhosted.org/packages/67/b8/b42132ca113dc567d37684437b46ca1dafc885902b02a110a02d5b511857/cffi-2.1.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:58acb8ab8e295e6c5ea12f888cbb13cf21511ef2a3303a23f4325c29d17fe5c1", size = 222328, upload-time = "2026-08-03T21:20:22.118Z" }, - { url = "https://files.pythonhosted.org/packages/80/10/c5c0cbf0a657aecf59ef511409734230bf556f05a0d6c9eed7aa5c0a0166/cffi-2.1.1-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:456a61fa52d579ebf9df2e9552ead5129855dbaff6c1e5a9b1bc408809bdc062", size = 209985, upload-time = "2026-08-03T21:20:23.401Z" }, - { url = "https://files.pythonhosted.org/packages/d5/6c/bfa0b87b03b9238148beca990292843c9396ba069b54496596594173de7b/cffi-2.1.1-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a4f00aa42f75d6e4595e8866e748cc1705adc0cddfeb2ca86d0d03993d63ba03", size = 208530, upload-time = "2026-08-03T21:20:24.628Z" }, - { url = "https://files.pythonhosted.org/packages/e9/02/4e7d553a7ac4b4238b38b3c1b80d486e9d4436f8d2acbf87a0997fe3f402/cffi-2.1.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:b0431303acaea1089ad4b3e9ce4e6518193def1118d4073ca848635ee4ea2e96", size = 221525, upload-time = "2026-08-03T21:20:25.758Z" }, - { url = "https://files.pythonhosted.org/packages/82/1d/a4aaf9babd75acb4d5f223bff71533bee748dd770a382619a798960ee9ba/cffi-2.1.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:64faea20f4e2613363a1a9b9c7dd73058f3ecd00133a511e72ad7c511658f527", size = 225053, upload-time = "2026-08-03T21:20:26.985Z" }, - { url = "https://files.pythonhosted.org/packages/81/10/5dc0e7bdd18e22107054288283380fc97a06ae3f1656a106908d666a3c88/cffi-2.1.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5c58fe613dc5e5336357eff555824a314d8e43282600435c8d1cb6a7a2fedd13", size = 223213, upload-time = "2026-08-03T21:20:28.277Z" }, - { url = "https://files.pythonhosted.org/packages/0b/e9/d0061c364cde06ee43168a0d076ac1da512cbc380d44767b844ba34fe2b6/cffi-2.1.1-cp314-cp314-win32.whl", hash = "sha256:1a18a57b58cfb21fc28d72e876acf10eaed67a1ed96226f92af4df681d571c4c", size = 177682, upload-time = "2026-08-03T21:20:44.288Z" }, - { url = "https://files.pythonhosted.org/packages/a7/06/1c3e01e3ba14c39f6d10bfbac52753b7e22259e38088e5cfe1d704918690/cffi-2.1.1-cp314-cp314-win_amd64.whl", hash = "sha256:3222ba5d678f80a030e6afbcc33dc1ae5cb45facabb61cee2c7016b8432fde48", size = 187949, upload-time = "2026-08-03T21:20:45.623Z" }, - { url = "https://files.pythonhosted.org/packages/87/5b/da4e39efe18eeb89cf580ea9cfc66b6a7c3eadb808fc0cc1d3a295cb5a5d/cffi-2.1.1-cp314-cp314-win_arm64.whl", hash = "sha256:ab36d55f9ed2d067327667c2fea18dda018eb628dd6347aa01dda6cf1f5d3836", size = 182947, upload-time = "2026-08-03T21:20:46.955Z" }, - { url = "https://files.pythonhosted.org/packages/23/59/40338bf421c5accea1d45158170c87006ef1cd371b05c077e76476949728/cffi-2.1.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:7750c6449dff7864bb9bb27ddfb0267756189201a3afc911d82b3caacd70dfc3", size = 188504, upload-time = "2026-08-03T21:20:29.495Z" }, - { url = "https://files.pythonhosted.org/packages/7d/47/5ecf1023850036e674c77ec4de86182d309ae344e39e7cba984b7df5d647/cffi-2.1.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:0beceaabe56af686895136a2de78db54ecd8e4046b236b8fd6d6cb61389e9bf2", size = 188259, upload-time = "2026-08-03T21:20:31.291Z" }, - { url = "https://files.pythonhosted.org/packages/2a/9c/92934c3bea9f785b23eba304538c0b4d37a2a96d2431eb3a1bc87a11aa19/cffi-2.1.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:49cbc70e6542d4ccccb936558d1064a8012541e78f821f955cff24e357776c94", size = 223864, upload-time = "2026-08-03T21:20:32.571Z" }, - { url = "https://files.pythonhosted.org/packages/4d/45/ba4c93527bc38616a8bd36488acb69a2212d60486794f0c1f318949bbb76/cffi-2.1.1-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:e2d65b31f36619cda3999b78b2aa9632e76b78448e7a56fc4240824200e7c4fc", size = 211538, upload-time = "2026-08-03T21:20:33.808Z" }, - { url = "https://files.pythonhosted.org/packages/80/e9/b6ef565e452acb932fb0cb5443f44a78efbd1233e566f02b5a83855e9115/cffi-2.1.1-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:28907ab9bfb6aa13184cfc17c6b8e1023c5ab6fd7076d8c20a35e59fe04f8f29", size = 210688, upload-time = "2026-08-03T21:20:34.974Z" }, - { url = "https://files.pythonhosted.org/packages/9a/95/eff5f0cee78d2eabc7eebffec40d3fc1876b5f3c95582e018bb4b99601f2/cffi-2.1.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:51b31d1c98274844cfd7838ce00bfc27c7423a4dc00fc0772fc3331c2cc90676", size = 223803, upload-time = "2026-08-03T21:20:36.564Z" }, - { url = "https://files.pythonhosted.org/packages/fa/01/579d39fb8bef00a335a23d83757b44feb24cd6345a2c451b64cb67b9c362/cffi-2.1.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:5e7cecbaadb83884793e05828cee59b210b24583b9c7425d0ba6a754fe22eb4e", size = 226763, upload-time = "2026-08-03T21:20:37.816Z" }, - { url = "https://files.pythonhosted.org/packages/8d/b0/0b44f47c60b01b57b6e2bbd92343f13a85a1d93bc46ccf6e47e244acd99c/cffi-2.1.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:25792eac27877609e7bb06d42ff88278a6624fff2ba9bbb523c09616b117e80f", size = 225688, upload-time = "2026-08-03T21:20:38.959Z" }, - { url = "https://files.pythonhosted.org/packages/eb/d2/3b7176cb570a1d3e27faf67b72f591af508036e0d8b2be2ef9af9e8c84bb/cffi-2.1.1-cp314-cp314t-win32.whl", hash = "sha256:8ef53b2de9bcb9197d31854256575d59dbac0cba72ac627bb291ef5eceb74be4", size = 182868, upload-time = "2026-08-03T21:20:40.388Z" }, - { url = "https://files.pythonhosted.org/packages/56/78/31f00c1bcd97c9bbf55f1bfdf5bc809a5de8887473e90bb9960dca825e80/cffi-2.1.1-cp314-cp314t-win_amd64.whl", hash = "sha256:616f097f2fe415bc92a247f02e11f634e1f9e9a83d327e3c915c15089c87869e", size = 194104, upload-time = "2026-08-03T21:20:41.725Z" }, - { url = "https://files.pythonhosted.org/packages/7b/1b/58496f2ed0a35de575250c02a43ab3cc2c04d494a88fed31c1cabc0fd176/cffi-2.1.1-cp314-cp314t-win_arm64.whl", hash = "sha256:ad2c86c495b899d862ea0f4b42891b8713a3bd45dd4105c7fd51c2a72f39f3a5", size = 186402, upload-time = "2026-08-03T21:20:43.042Z" }, - { url = "https://files.pythonhosted.org/packages/c1/8f/9ebe220eab48a093d1a5a5e339ab0dc7316eef3bb04d63c42f0251b61f50/cffi-2.1.1-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:dddad92b554513a31f272570678ba307fb9f618f05e3d4a5eacafff9eae03e1d", size = 194043, upload-time = "2026-08-03T21:20:48.179Z" }, - { url = "https://files.pythonhosted.org/packages/ff/69/844bad3ece306c4782c2ecb93597035b6690d48704b803914c199da1e8b3/cffi-2.1.1-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:da0e573f9f97159390c89d9f1a9e41908b66d408cc5b58d08cf3847d844c531b", size = 196737, upload-time = "2026-08-03T21:20:49.457Z" }, - { url = "https://files.pythonhosted.org/packages/1b/8a/af668013284634733f02d683458a0728739c7d6ddb5e14cb0c20832266fe/cffi-2.1.1-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:fb92203a88b3d3053034db775110081c49d28be6551923805e039924093761e4", size = 184933, upload-time = "2026-08-03T21:20:50.639Z" }, - { url = "https://files.pythonhosted.org/packages/0c/75/2f5207ff6d1a613133b23a5203cc0c2a628313b5eb3974d7956ae3c57950/cffi-2.1.1-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:2ae64be792b8966f2c69538199728b290e34726562896df1e5dc8ffd8d8188e8", size = 185002, upload-time = "2026-08-03T21:20:52.173Z" }, - { url = "https://files.pythonhosted.org/packages/e2/31/9e1313b0a6e30e91b3b3d3fff51ae99c857c07738e3afcce1f7334e1b7ab/cffi-2.1.1-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:507a24c282e0f42f8ed737cf048572cbf580468da5555764a8331735e9c736b6", size = 222271, upload-time = "2026-08-03T21:20:53.462Z" }, - { url = "https://files.pythonhosted.org/packages/50/e3/f6234a833e6e08c7007003074723c406559eecf9b48dfc97471e5a8eb7a0/cffi-2.1.1-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:246fa40ce8645a614ff682e0b70f37134e460eaf93a775e0cbe3cca585a67a80", size = 209919, upload-time = "2026-08-03T21:20:54.783Z" }, - { url = "https://files.pythonhosted.org/packages/0d/fc/5f74e293fced6edb51af3a46c4ccf6c23c9943774ecb375ddbd522c76add/cffi-2.1.1-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:471cee653ae88de62096552e6d24ccb4a5adb8c8c9f10b5054d0122c15bf2779", size = 208529, upload-time = "2026-08-03T21:20:56.066Z" }, - { url = "https://files.pythonhosted.org/packages/44/16/29e6d01b388bef055ecd6ca8244b3f4d336bd09e92d5d892187b9601084e/cffi-2.1.1-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:aeae0e330c9f6acd681f647d46cefd30c29f93e3392882e792e82080c9691399", size = 221630, upload-time = "2026-08-03T21:20:57.336Z" }, - { url = "https://files.pythonhosted.org/packages/a4/18/fa7f1f6857d5eb88a4ca99ffcbfb7c387a287ccc154c64a73e86314745d7/cffi-2.1.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:42a494cee34437f05546455144f2b5d9ac09b1face62bcfce597d2e521066688", size = 225134, upload-time = "2026-08-03T21:20:58.675Z" }, - { url = "https://files.pythonhosted.org/packages/e0/9f/e8e3dfa04a1b4c241f8c91faacad872b4d4efd051d49764ad4e2fd4b9fea/cffi-2.1.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:cc572dace3f60ef98d7b12ff411d20f5362feb31a0439eab0085bbfd349982d7", size = 223197, upload-time = "2026-08-03T21:20:59.968Z" }, - { url = "https://files.pythonhosted.org/packages/f8/7e/8debeb04f1ab9fe2a6963964cd6f1aaf7192627b83926586a6a4e089c9fa/cffi-2.1.1-cp315-cp315-win32.whl", hash = "sha256:4f42141fc14250de6dde5ee7ea4432be017252d91f19c5ad043c084cea629cac", size = 177683, upload-time = "2026-08-03T21:21:14.901Z" }, - { url = "https://files.pythonhosted.org/packages/e0/31/5158704cc474ab65c1647932e88be78dc0873f47130e253be38bcaf13d01/cffi-2.1.1-cp315-cp315-win_amd64.whl", hash = "sha256:e6e8cff14d6fb0be70a09c0bdc58096f501952d04624ebf867e0e56da2df8960", size = 187897, upload-time = "2026-08-03T21:21:16.108Z" }, - { url = "https://files.pythonhosted.org/packages/cc/4b/b3a2da8570c704ffc0f9762cdc3ec0f02c8573798e0b5cf7f11c82bbb70f/cffi-2.1.1-cp315-cp315-win_arm64.whl", hash = "sha256:27350daa11d4f10c540e6e89dada4c54feb7256ad03e9a4dc075ebad7ba360d1", size = 182935, upload-time = "2026-08-03T21:21:17.271Z" }, - { url = "https://files.pythonhosted.org/packages/d0/ef/5443574510a1207e6f6bc38ba6e1f1de36cb48fef07b2728bb896a21f430/cffi-2.1.1-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:c26608d2222fb1e94487e4a387d85f13eb55d5ed725cb25a0c589ac4ee60e7bc", size = 188464, upload-time = "2026-08-03T21:21:01.163Z" }, - { url = "https://files.pythonhosted.org/packages/7e/ae/a56fa8c4686ad50e148fcbc8d3ae0d03915ff5c30d795058988c24118cef/cffi-2.1.1-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:4be96343e422f2dfcd12ab5c9f5aebe03f82f737c6bffeca6830b3875cb44aab", size = 188262, upload-time = "2026-08-03T21:21:02.382Z" }, - { url = "https://files.pythonhosted.org/packages/53/b2/6187f46f2912276a3ae284076109cc5c8680482f11f766ccf26db4a86427/cffi-2.1.1-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:937c0052c05a31ca1daf18de3158eed4dbfcb9cc107adbea227728d647be701e", size = 223779, upload-time = "2026-08-03T21:21:03.553Z" }, - { url = "https://files.pythonhosted.org/packages/8a/f6/c3ad28bd19f77047a03084424fbd4cbe997303267c14423737324be0385d/cffi-2.1.1-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:df423d40ee8654634421812bc3b196da3f9bd7d32929da813f8394c4348a5358", size = 211520, upload-time = "2026-08-03T21:21:04.863Z" }, - { url = "https://files.pythonhosted.org/packages/a0/cd/ccac9013a5bd9fd764de118674ab9c805b5ca10c19270d90ee273f8b2240/cffi-2.1.1-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a730a083190634c65cca36ba5f489531576ebd79bcd5c8e172130f6453127231", size = 210673, upload-time = "2026-08-03T21:21:06.223Z" }, - { url = "https://files.pythonhosted.org/packages/52/86/2976131c639aead931c5bee5aba67e4b09fbeb8018b6f282f70803f923a7/cffi-2.1.1-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:363e05fa78e15116c3c32c210ee36884fd6b9afa6d440e47112c3bd511d64cb6", size = 223835, upload-time = "2026-08-03T21:21:07.539Z" }, - { url = "https://files.pythonhosted.org/packages/ac/0c/33a7aeab2f9c76918c52e084beb39c570db3588133412929e8ec06fab90b/cffi-2.1.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:770de9db11e84213beec501cfcaa013b019820ca881e03344dea5844f7876d94", size = 226705, upload-time = "2026-08-03T21:21:08.774Z" }, - { url = "https://files.pythonhosted.org/packages/e3/26/2cde30fdde421130bfc18f70395731a6e6b2053c6a1978a5258ff04e72fa/cffi-2.1.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:7da0c5eff80f0197f3b3d1232ec5a682a9325f4ae9016a78f5f5ca35f9ced1f5", size = 225539, upload-time = "2026-08-03T21:21:09.911Z" }, - { url = "https://files.pythonhosted.org/packages/6d/cd/a361394c94b2129d604bb846f624a8e88255a3ee33129c434a00d715e64f/cffi-2.1.1-cp315-cp315t-win32.whl", hash = "sha256:06c72bb76605a4b0cd0aad6930b69d4baf7dd5d806cfc409b824191099700e66", size = 182707, upload-time = "2026-08-03T21:21:11.226Z" }, - { url = "https://files.pythonhosted.org/packages/9b/b5/ba2b299993c26577d529b6ae29841f9e15b9fcf004d65f423f4fcf94ade9/cffi-2.1.1-cp315-cp315t-win_amd64.whl", hash = "sha256:d9c275eaacd24aa73f94ffd6de08fc3f932424d8b6c376f4bed7cde376fe7bc3", size = 193772, upload-time = "2026-08-03T21:21:12.39Z" }, - { url = "https://files.pythonhosted.org/packages/aa/29/35e016098c814cd93de9cd320c66b5bfba14dc6ecedd3cb518fa7c408c69/cffi-2.1.1-cp315-cp315t-win_arm64.whl", hash = "sha256:d18e5ac0f2f03f4f518d3e23db0f0cad7faa1da8620e9c09461d443bbf6e6692", size = 186360, upload-time = "2026-08-03T21:21:13.636Z" }, -] - -[[package]] -name = "click" -version = "8.5.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/45/37/edbf1b0707709013c0cf2e8317e03d97ed29bf4cac709fe328904ae92a38/click-8.5.1.tar.gz", hash = "sha256:9bbfada76703fd1d784b83eea012e3e8c6a001a876543ef104fa56aaaeb072b4", size = 399151, upload-time = "2026-11-06T17:37:01.021Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/31/7d/164b7ffc8624fe9efb4221bf9af485d5c1e41b9ae118045d2b6dc5457d8b/click-8.5.1-py3-none-any.whl", hash = "sha256:8bb5376d2006950386f8c6427613334a2acadc5f559cb80e638d00b4df957e37", size = 126163, upload-time = "2026-11-06T17:36:59.287Z" }, -] - -[[package]] -name = "colorama" -version = "0.4.6" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697, upload-time = "2022-10-25T02:36:22.414Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, -] - -[[package]] -name = "docutils" -version = "0.23" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/39/a4/5180d9afc57e8fca05601dd652bdff19604c218814037fe90ffc7625a50a/docutils-0.23.tar.gz", hash = "sha256:746f5060322511280a1e50eb76846ed6bf2342984b2ac04dc42caa1a8d78799e", size = 2303823, upload-time = "2026-05-27T17:41:06.934Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/32/91/30151a39f7570f448ed84529390628a651d7f27c87d73c9b887f8189695e/docutils-0.23-py3-none-any.whl", hash = "sha256:25d013af9bf23bc1c7b2b093dff4208166c53a94786c9e447808335ef1185fea", size = 634701, upload-time = "2026-05-27T17:40:58.442Z" }, -] - -[[package]] -name = "duckdb" -version = "1.5.6" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/59/0b/d65ea3be00ea79aa276a8388bec588a9cbf409ce637c6d306e5316210d15/duckdb-1.5.6.tar.gz", hash = "sha256:166a91dbfacfc0c9f08cc76c0243cb6d3d4296bfab5bad72a3cfb63140a5b7c8", size = 18032957, upload-time = "2026-09-28T13:38:37.978Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/36/e5/01e03d30b7ba33a030a4269fdca16ce445ce10f9d29b84a10fdbe0636ad2/duckdb-1.5.6-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:c88700d0ee68ad149a0cc624df21b0f21efc136ea2449aaadd7cd0c9a564962a", size = 32757482, upload-time = "2026-09-28T13:37:29.916Z" }, - { url = "https://files.pythonhosted.org/packages/ba/4f/7f7be626a4649a3948ca646c84d6afc1a00121f292f98e6f0d9ed68330df/duckdb-1.5.6-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:03e4f1b10a8b8ff476eb2b73955590fadbcef978da1167c593114c5edf763960", size = 17372997, upload-time = "2026-09-28T13:37:32.363Z" }, - { url = "https://files.pythonhosted.org/packages/1a/66/9d57573729348d800a0eebdd508f1a833d3714f72e984fef79b47f0e6c45/duckdb-1.5.6-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:34623eaabd2c66ba5c20f1a39486321c3b7d32e4e0e001ced95f81e3372dd361", size = 15514224, upload-time = "2026-09-28T13:37:34.467Z" }, - { url = "https://files.pythonhosted.org/packages/57/ec/97f595214b3a27b4ca42b8cab6d8121c06f3537dcc4d2da7bca0332de4c5/duckdb-1.5.6-cp311-cp311-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:56c0f71c6bee982e9c30568bb12371bf66b26bf129c75d8d7f60bc69d6590a2c", size = 19428776, upload-time = "2026-09-28T13:37:36.689Z" }, - { url = "https://files.pythonhosted.org/packages/68/4a/ab59f4c1f76fb89e28d23f19b2729538e0723c8d328a07e1b8c37f9ee128/duckdb-1.5.6-cp311-cp311-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:73b108c04c932b36c2fa4e41110cc1c3c8cd510eb49f065f92d050be8e6929fd", size = 21537771, upload-time = "2026-09-28T13:37:39.548Z" }, - { url = "https://files.pythonhosted.org/packages/31/4f/9306c442ecad76f2a4d19f249e7fc8861f139dcf748315102eb69de8ca56/duckdb-1.5.6-cp311-cp311-win_amd64.whl", hash = "sha256:dda311932cf5aae955a53fe28a4fc1700c2ab5fa02dc1f165abdd5ec6c39141e", size = 13179009, upload-time = "2026-09-28T13:37:41.981Z" }, - { url = "https://files.pythonhosted.org/packages/a0/40/8a370e998293d3ebbbac4d926db30bb4ac5f700851a06ac31e7093bee386/duckdb-1.5.6-cp311-cp311-win_arm64.whl", hash = "sha256:df5ae02af278e084f54a9730a9f4f211ed736d0bd8f3bc12af925c2effb5b33d", size = 14046340, upload-time = "2026-09-28T13:37:44.187Z" }, - { url = "https://files.pythonhosted.org/packages/d9/d5/d0ab77a0a1702a43171c93874f44c1f6481e30038bd3987df0d77a16a5c6/duckdb-1.5.6-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:48d07d0651aaeac2c3974afd37599970154b7b79b54c18f27c319c14ccf98d9d", size = 32810486, upload-time = "2026-09-28T13:37:47.254Z" }, - { url = "https://files.pythonhosted.org/packages/9f/cd/b22201de5377faa3be6c38d5f3eaa504cb480392a448bed6a4d2239469b4/duckdb-1.5.6-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:79de3dfa8705b1ba0d59e7e3252e40ff399e0afd12f485502a6c7bf7c2fd809a", size = 17405278, upload-time = "2026-09-28T13:37:50.135Z" }, - { url = "https://files.pythonhosted.org/packages/9c/6d/f9cfb1493bbdc2f095693a402e42dce1192077f9e11573f00baed6a748de/duckdb-1.5.6-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:dcccce20965e6986cd083fdf192c461685ad0b93cd1ccd0b2a8207f1185f078b", size = 15532943, upload-time = "2026-09-28T13:37:52.927Z" }, - { url = "https://files.pythonhosted.org/packages/53/04/f65ccfaa5a833f2e570c4a140f03c8f95da416da9fe8ed08401f81f8242a/duckdb-1.5.6-cp312-cp312-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ce89a1025a5317ebe9c520876c48032b5247ac574865486648b1a004f6009875", size = 19454940, upload-time = "2026-09-28T13:37:55.732Z" }, - { url = "https://files.pythonhosted.org/packages/4c/99/be75c788a492f8d77b7a1cdc1b19939ae7be0007f2028691ad371a1a33ee/duckdb-1.5.6-cp312-cp312-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bc9619ed7d4ffa117b5155d84b44794366bb6635178d78ed5e13a6024845c757", size = 21568087, upload-time = "2026-09-28T13:37:58.191Z" }, - { url = "https://files.pythonhosted.org/packages/b5/95/889f8508960e47c0a7c75cc5bf57cde8512fc24f8db7b3129cca5388da42/duckdb-1.5.6-cp312-cp312-win_amd64.whl", hash = "sha256:09ff51b230219f0d8b47fc8a1e17fb595ba9fab0c3d96a6de4d00b8ff86b3cf1", size = 13190189, upload-time = "2026-09-28T13:38:00.407Z" }, - { url = "https://files.pythonhosted.org/packages/a4/c9/baab503364a68309f8368c88e77f5341e7d94927bdf3e6d703f0e5035f3e/duckdb-1.5.6-cp312-cp312-win_arm64.whl", hash = "sha256:b8d795c8b2d5634b3269f974aa97f1fdf878f62f032317a52252a151b693fb1e", size = 14021977, upload-time = "2026-09-28T13:38:02.682Z" }, - { url = "https://files.pythonhosted.org/packages/b1/5e/a476197fcba557738a588ec844747a19bc0a24b0e6f1809e308f29d68c0e/duckdb-1.5.6-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:ae352646374cacf48e9981cf031191c494865192fc436d13667a2531fc5d1da3", size = 32810376, upload-time = "2026-09-28T13:38:05.148Z" }, - { url = "https://files.pythonhosted.org/packages/0c/6d/5466a2b53ddd557644dfa47a763f68748efccdf282e6ae7c4f1bcfb3da69/duckdb-1.5.6-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:5a1261e90785e9d29953293e44f60fa073bd1137098924e8de21a037a861b051", size = 17405385, upload-time = "2026-09-28T13:38:07.363Z" }, - { url = "https://files.pythonhosted.org/packages/d4/a0/bf87071170835ee4a34fe764fc11c1c6e7040a0e021b36c1b6f834a4c22f/duckdb-1.5.6-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:97dd7a555b8f5298b76bc7d48a11cb2c64336e8de9bfde783cffb86ea9f54807", size = 15533132, upload-time = "2026-09-28T13:38:09.681Z" }, - { url = "https://files.pythonhosted.org/packages/31/e0/38095c8e140ecfbe847519ac07bcba94301b8fbb76b2870015e33e07f179/duckdb-1.5.6-cp313-cp313-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:364992ba1089a2b327391cfcb68fd0bd0ce9090cf293baef861a0ba6847abfee", size = 19454994, upload-time = "2026-09-28T13:38:11.836Z" }, - { url = "https://files.pythonhosted.org/packages/70/21/61dd2876bbaa69cf77d7b5c620e52e8b25faae7096f4d2e4a812b52095d7/duckdb-1.5.6-cp313-cp313-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:644f54ce99b3b61844bc9a3fe80e0aecb1ea4084b1fffc4396d1569db6111679", size = 21568700, upload-time = "2026-09-28T13:38:14.258Z" }, - { url = "https://files.pythonhosted.org/packages/4a/4a/100730e7785e85268be4d4d5bd62cfc8314e261d2f42efa208243eef35cb/duckdb-1.5.6-cp313-cp313-win_amd64.whl", hash = "sha256:ced693d33ddcee2e5345f077d342c87d2aaa80e41c514e64c9ff2d4e5963c251", size = 13190707, upload-time = "2026-09-28T13:38:16.875Z" }, - { url = "https://files.pythonhosted.org/packages/f3/2e/bc7f44eab4e89ee5c1cb427bb1168ad021d985042e6841ec0694c3d3d501/duckdb-1.5.6-cp313-cp313-win_arm64.whl", hash = "sha256:41ecc75bb9328d72d154a705c1a653d2c5c60f686a5c0c6578aa80020753c884", size = 14020962, upload-time = "2026-09-28T13:38:19.007Z" }, - { url = "https://files.pythonhosted.org/packages/fb/62/a8a30a4c6b94c0861d348ed5633b963f6745a5525527530f02f3c1a7c931/duckdb-1.5.6-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:aa21d2ad803b2524326e8622d7d96b2bb1ff1d5b60368e1978ee805df9c21fb3", size = 32828003, upload-time = "2026-09-28T13:38:21.414Z" }, - { url = "https://files.pythonhosted.org/packages/71/b7/1dcca0005eb8c67adf9fc06bf0cbb1d2bf4ea1974cc89e7a7c2ad66aac28/duckdb-1.5.6-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:8a1b2ad27d414068cbca06c55cfa802eece10f86ea4812ff082f8ab4cb25fc85", size = 17413912, upload-time = "2026-09-28T13:38:23.915Z" }, - { url = "https://files.pythonhosted.org/packages/93/b0/e3ac175443550f3464f2d95731a8b0aae9b4dc3875c3a186c352262b43c2/duckdb-1.5.6-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:c79c6d222b1d015cde73b5139087186b00db65357fb4e2c94c2308fbbf465a72", size = 15543122, upload-time = "2026-09-28T13:38:26.317Z" }, - { url = "https://files.pythonhosted.org/packages/9d/08/cc510a7952aba69d5cdca17f3ef61c95713d86143f2ee9aa3e097d38f50b/duckdb-1.5.6-cp314-cp314-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1052b8050ef5696e2c0d8c836949c72f3dd11f0690466acbea739613e8e2750b", size = 19457946, upload-time = "2026-09-28T13:38:28.877Z" }, - { url = "https://files.pythonhosted.org/packages/ef/a5/6f8099d9a5a02ddff89e5c85875df3465054845b0920fb0703fbdf8dd2ec/duckdb-1.5.6-cp314-cp314-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:19c5e485e59613b8878d1670bcaa7a010f53c5a4da5ae8e08863e5e529ca6182", size = 21575132, upload-time = "2026-09-28T13:38:31.231Z" }, - { url = "https://files.pythonhosted.org/packages/9f/58/762f7159662d7859e201fa05ca29f306795daeabf84f3e087215a966b001/duckdb-1.5.6-cp314-cp314-win_amd64.whl", hash = "sha256:ebcbd09cd8578ab1093393e9b16289cda0e8f1791ac595bf00eb5bad75c3cf00", size = 13713963, upload-time = "2026-09-28T13:38:33.543Z" }, - { url = "https://files.pythonhosted.org/packages/46/69/64d165db322de13f5c3e75d377b6b9694df1821155ad1fa4b14b04601abc/duckdb-1.5.6-cp314-cp314-win_arm64.whl", hash = "sha256:820a8384faef11cd86068ea48c5da57ce2d8f1c7b3d2bdb9be3398317a7c3728", size = 14514368, upload-time = "2026-09-28T13:38:35.676Z" }, -] - -[[package]] -name = "h11" -version = "0.16.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/01/ee/02a2c011bdab74c6fb3c75474d40b3052059d95df7e73351460c8588d963/h11-0.16.0.tar.gz", hash = "sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1", size = 101250, upload-time = "2025-04-24T03:35:25.427Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" }, -] - -[[package]] -name = "idna" -version = "3.20" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/f5/08/8eea9d4b8302028f3abb2c0813953f7aec26d33b7a8960ed760e65ff29fa/idna-3.20.tar.gz", hash = "sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44", size = 216463, upload-time = "2026-09-17T14:11:04.752Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/58/a2/bb081bab032533a855d44de1d56f8e8426114ff1ba5d1f07a438a0a654f8/idna-3.20-py3-none-any.whl", hash = "sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c", size = 69583, upload-time = "2026-09-17T14:11:03.168Z" }, -] - -[[package]] -name = "iniconfig" -version = "2.3.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/01/e1/2069291243c926a2ff1cd706c7f3eeb9b62144bf60f77c9fb9ff2fb26bd3/iniconfig-2.3.1.tar.gz", hash = "sha256:67f4b9c50da0dedf52af349e7749a80a9057a5031199791b906c3bb3ae878960", size = 21209, upload-time = "2026-10-06T22:48:38.076Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/56/43/4ca9e49d27a1fcf6bece6f6aec0ea46bb9112489b93d4b688fb415457bdb/iniconfig-2.3.1-py3-none-any.whl", hash = "sha256:9121e2c1fdb355232495be3194c8dfe87ccc2d5dee45947b78e68f499790d7a7", size = 7552, upload-time = "2026-10-06T22:48:36.959Z" }, -] - -[[package]] -name = "itsdangerous" -version = "2.2.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/9c/cb/8ac0172223afbccb63986cc25049b154ecfb5e85932587206f42317be31d/itsdangerous-2.2.0.tar.gz", hash = "sha256:e0050c0b7da1eea53ffaf149c0cfbb5c6e2e2b69c4bef22c81fa6eb73e5f6173", size = 54410, upload-time = "2024-04-16T21:28:15.614Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/04/96/92447566d16df59b2a776c0fb82dbc4d9e07cd95062562af01e408583fc4/itsdangerous-2.2.0-py3-none-any.whl", hash = "sha256:c6242fc49e35958c8b15141343aa660db5fc54d4f13a1db01a3f5891b98700ef", size = 16234, upload-time = "2024-04-16T21:28:14.499Z" }, -] - -[[package]] -name = "jedi" -version = "0.20.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "parso" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/a3/a4/4692ecd7fa700ac1066b1c1f6cadef60aa2e01e5e364710235137d823e0a/jedi-0.20.1.tar.gz", hash = "sha256:2f71208c3f9c1bca057c0e90d3f272aba44ace88fc4067d7587e9e069331b7e5", size = 3121738, upload-time = "2026-10-12T17:42:24.361Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/be/c7/71eb0d51cdcbb63b857c931aa4e9218b078b5d9f8ecd383b234f28fe7b0f/jedi-0.20.1-py2.py3-none-any.whl", hash = "sha256:0fb16d86c4a4c73c37ba518c77419975e30fcc620658a8d14fbb5720cdd34142", size = 4885980, upload-time = "2026-10-12T17:42:21.585Z" }, -] - -[[package]] -name = "marimo" -version = "0.26.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "click", marker = "sys_platform != 'emscripten'" }, - { name = "docutils" }, - { name = "itsdangerous" }, - { name = "jedi" }, - { name = "markdown" }, - { name = "msgspec" }, - { name = "narwhals" }, - { name = "packaging" }, - { name = "psutil", marker = "sys_platform != 'android' and sys_platform != 'emscripten'" }, - { name = "pygments" }, - { name = "pymdown-extensions" }, - { name = "python-multipart" }, - { name = "pyyaml" }, - { name = "pyzmq", marker = "sys_platform != 'emscripten'" }, - { name = "starlette", marker = "sys_platform != 'emscripten'" }, - { name = "tomlkit" }, - { name = "typing-extensions", marker = "python_full_version < '3.12'" }, - { name = "uvicorn", marker = "sys_platform != 'emscripten'" }, - { name = "websockets", marker = "sys_platform != 'emscripten'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/30/92/2c76c36c966b1dd0a66f86186cb4190458944e2eda2c4bc9fe0bfbd3c7a5/marimo-0.26.0.tar.gz", hash = "sha256:5b84aadab56724c4da86ec21f88e6fc7b5f40507ef486a1cac71d6518fca2e3c", size = 37932349, upload-time = "2026-11-24T23:53:12.311Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/d6/df/f54fb8ca074936141eb3f9684abc0ec8ba3f6bd2d63befefc935bc9ce166/marimo-0.26.0-py3-none-any.whl", hash = "sha256:ae87e8c7ba7dfb36148f94bdaf2febf3e22816723d3cca97c3aa0e28b75450e3", size = 38526235, upload-time = "2026-11-24T23:53:08.812Z" }, -] - -[[package]] -name = "markdown" -version = "3.11.4" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/1c/ff/8644daa33bfdf552c9cfec8d1fc2c690f57a347808f62c406ac6557329c2/markdown-3.11.4.tar.gz", hash = "sha256:c911a757f33d64a2578bed2d20c57e007b2aedd8a67bceabd593b31143d54ead", size = 505340, upload-time = "2026-11-25T16:26:12.029Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/61/54/188fcc228c71a4ae33244008af08c2e7b1945b657390f56d82dfbe4059f0/markdown-3.11.4-py3-none-any.whl", hash = "sha256:2e30b19cead1968f391206e184ca67dfe6805c2eb8f383fb07b4dc90f8288075", size = 119551, upload-time = "2026-11-25T16:26:10.692Z" }, -] - -[[package]] -name = "msgspec" -version = "0.23.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/7b/72/c9d89595763e54800d2c136efadfb65c8ae789bc85b8a0c890358f967667/msgspec-0.23.0.tar.gz", hash = "sha256:a0d57d3ca7734542eb6861e72d974ab051e6cf73ea6b01b263f77170593362be", size = 378550, upload-time = "2026-11-28T19:29:08.14Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/6e/24/268907b971bda07f6e8f9b4f269fb547e5116138c7d055a3031048cd55ec/msgspec-0.23.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:8546e43bc64c604a9ec8b64d636429f6bb400eab1f9f746f5f3902727650037b", size = 205258, upload-time = "2026-11-28T19:27:33.529Z" }, - { url = "https://files.pythonhosted.org/packages/d3/9e/ee945746966e04dfd45a43dbf0ed09832138b63e8e90c3c7f59955ada7e6/msgspec-0.23.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:68adebfc001bb6bafbbfade8d922691e13ac654293435b5e61f1cb38218a1636", size = 196849, upload-time = "2026-11-28T19:27:34.821Z" }, - { url = "https://files.pythonhosted.org/packages/94/ed/96778b68d3609ff05486599e9da166dae5153a51c2e1cd7f0d6ff9b3fd9e/msgspec-0.23.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6ce60801cf7c8368819ca755deec31a0da02137544dc5d3ab065aac5e59e7cdb", size = 227482, upload-time = "2026-11-28T19:27:36.167Z" }, - { url = "https://files.pythonhosted.org/packages/5c/79/7844827ee0c6e6bc0bf5546b3b9aa30f0352a2fcc00161ac4285c5a36d5c/msgspec-0.23.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:2e514e5b2a23e376f545f4962834b7312d9400705627c53330116b46daddfbe3", size = 232334, upload-time = "2026-11-28T19:27:37.509Z" }, - { url = "https://files.pythonhosted.org/packages/25/eb/be7659eb2d1efebdc9e4311dc3e1dac4304385f12cab1d507037ae8847ec/msgspec-0.23.0-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:45618388dc353565da759be1349f6d8c2d0649954fbf51901662a91b1c8d8a73", size = 240555, upload-time = "2026-11-28T19:27:38.8Z" }, - { url = "https://files.pythonhosted.org/packages/a3/64/4b8906a35c804c91094e2ae3a9fdf6b5063730d187c67c47f344299900a2/msgspec-0.23.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:64b4aa9412783913de79a81d12c4aaa0534acd2f17b79dee06d69983389734b9", size = 232253, upload-time = "2026-11-28T19:27:40.053Z" }, - { url = "https://files.pythonhosted.org/packages/ee/ef/3d822357ec06401a9ca90bbb7c61a34ebb3fc7e65e462035ba910115f256/msgspec-0.23.0-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:b3b00a73f7171edca6118a1375fae8e11636abac67a5dc5e58368f4a8b3b5319", size = 239982, upload-time = "2026-11-28T19:27:41.368Z" }, - { url = "https://files.pythonhosted.org/packages/9b/6a/31d1bb14bacd5659a95c8ad9df5d92706741005f6466ce56a2da64dfbaa7/msgspec-0.23.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:46fe4b44555a8a69e5edce0cc44842ee3364b82292cfba291f38bf22ec527fa2", size = 235377, upload-time = "2026-11-28T19:27:42.565Z" }, - { url = "https://files.pythonhosted.org/packages/c4/e5/53d97827886cf835841e6ab2af4eb61d2b7e9a328c211726e760691af7a4/msgspec-0.23.0-cp311-cp311-win_amd64.whl", hash = "sha256:3f7373410e34db4d186c2a2d8dbe384e059fcad824febabf983c0cd69eaf1f50", size = 198498, upload-time = "2026-11-28T19:27:43.908Z" }, - { url = "https://files.pythonhosted.org/packages/20/27/d7637f630708d7db12ac9068a6ba6453fdbad21b43e52048282a8951d67d/msgspec-0.23.0-cp311-cp311-win_arm64.whl", hash = "sha256:62508294938b64f9dda1663ca18ef16f214e963d281d8d3499fbeb668ad9cd79", size = 194409, upload-time = "2026-11-28T19:27:45.16Z" }, - { url = "https://files.pythonhosted.org/packages/f7/b3/31a7ec58265f9524d964bc5887686f18655f1cf1bf327dff49ff4da140da/msgspec-0.23.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:1e96cf442c0c1072cb5f87c9fd061e234ce0faec9d143f849c9e53c96cab69ed", size = 207894, upload-time = "2026-11-28T19:27:46.406Z" }, - { url = "https://files.pythonhosted.org/packages/4f/5f/c468e0b508e0c09ecd61a7aca74edb9302b7482899d8aeb087eec222baca/msgspec-0.23.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:a58acc6bcb5b528ea400fbd2b362f8a58cd306564636454debf8af029c90f8fb", size = 199553, upload-time = "2026-11-28T19:27:47.653Z" }, - { url = "https://files.pythonhosted.org/packages/7c/51/5389b9be05ce3cf139743ba1d10af3a7bae4917bfcb40a2bae90a0a23b57/msgspec-0.23.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:000abdb9da8b56f53ec2980ed182f00765df4ab07a093785fe9ce5273aa8d4d6", size = 230676, upload-time = "2026-11-28T19:27:48.944Z" }, - { url = "https://files.pythonhosted.org/packages/59/7a/910a8ff19a5e759f6775eb9efc3b27c509d8c3705f142ab18b9ef3ae0c48/msgspec-0.23.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c08f294663135183bd633efd843645687285a445054a876c37506d4e9de7d80b", size = 236624, upload-time = "2026-11-28T19:27:50.272Z" }, - { url = "https://files.pythonhosted.org/packages/c8/0a/5266ede27a6affeb8f1464cf482c3b2476ef8f52803b7095d6b0d37b35c0/msgspec-0.23.0-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:62887038958440092a165d4541220c3c637c43afb9c038c0c23a7afedb86cca1", size = 243124, upload-time = "2026-11-28T19:27:51.565Z" }, - { url = "https://files.pythonhosted.org/packages/98/cb/497c400eebdcc1cb371664776f9a3a49496dd54145110b3a2b8c4d0d8be3/msgspec-0.23.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:4bddda9fcdc38377edfae92d1b8a282fabe2328924517ebdf37fa6e14e874dd5", size = 234112, upload-time = "2026-11-28T19:27:52.763Z" }, - { url = "https://files.pythonhosted.org/packages/76/a3/d225e6ced293541f6a3acfedaf70a46bd26623994c30a6bba0ec1e6948db/msgspec-0.23.0-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:61492ae8f47bedae609723804632beaad688d53057151e6fd54b810eb8d542d9", size = 242167, upload-time = "2026-11-28T19:27:54.375Z" }, - { url = "https://files.pythonhosted.org/packages/ad/b3/60af281f93ed9d357f51a648d6ce79fc604100248ba80de42af4a91b87c2/msgspec-0.23.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:0b8a3cf17156120cc845762a98cfa19f0d02297d338ba529a7d403b2c69ed99e", size = 238651, upload-time = "2026-11-28T19:27:55.626Z" }, - { url = "https://files.pythonhosted.org/packages/df/ed/95847e8818bcbba9f838153f65aeafa0819d85c61973605de9b872f47972/msgspec-0.23.0-cp312-cp312-win_amd64.whl", hash = "sha256:4ea6a15d78dbb61b38ed786913ffde142b2c776c0d8ae517f2419aa3c9e299f9", size = 207534, upload-time = "2026-11-28T19:27:56.889Z" }, - { url = "https://files.pythonhosted.org/packages/00/5f/f470c5f65f9e5fb413d138b8eb47a6fe5f6312564ceb966f3e48958c276d/msgspec-0.23.0-cp312-cp312-win_arm64.whl", hash = "sha256:7db818985fbe9f5b81c71000edd312d987abe7258ae28f01489749f06bcd532b", size = 200060, upload-time = "2026-11-28T19:27:58.116Z" }, - { url = "https://files.pythonhosted.org/packages/eb/12/1b33209749bded16d81a94cc77c383e40aca8c3a2bd3d42656974359d9eb/msgspec-0.23.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:4a3a40bec3559c6fc5fad1f2641f03d59104b2a1f069b5c146ae9fbb857e7c63", size = 207915, upload-time = "2026-11-28T19:27:59.343Z" }, - { url = "https://files.pythonhosted.org/packages/a4/6e/f2ac94a03a1f7fd86a0a890b964d0a30b7f8b1feba770d56e3395c94568c/msgspec-0.23.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:2e852f554a1a8e521f6727da6faa85a6f6d0e2ed34eef29030e51d1991b636b6", size = 199541, upload-time = "2026-11-28T19:28:00.686Z" }, - { url = "https://files.pythonhosted.org/packages/75/b8/99137210e2a95ccdfdce5cf18316f98690d64e5ea2ca768e1a0f5ce2a26e/msgspec-0.23.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ff7f32930c370d2982613dff161d6f0fa05d4e0a4a7d3cd7369411c1e44c2635", size = 230724, upload-time = "2026-11-28T19:28:01.879Z" }, - { url = "https://files.pythonhosted.org/packages/31/c3/eb7c8be54416b678286221728e196484b73c6abb47bab8a356d196a71475/msgspec-0.23.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:35bfe3b61fbb966610c4071c02a27ea8c81ace0effce2aa67acc3ea03b93559b", size = 236671, upload-time = "2026-11-28T19:28:03.222Z" }, - { url = "https://files.pythonhosted.org/packages/b1/62/bbad58dc605e95d49f74e68c407690e71be5722652bd5f893cbc1a5a0888/msgspec-0.23.0-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:16e8be6a4f8addc6af168a07719c2028e1397abcc7b90ec7870b419182bb49c7", size = 243143, upload-time = "2026-11-28T19:28:04.5Z" }, - { url = "https://files.pythonhosted.org/packages/1a/63/c8c8b7dc4a620b319bf504845afbfc14441604da72279c10ffde414c0dbb/msgspec-0.23.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:3966278e188aeb209c827b656170191d25344ca2852eccacaa0856c79230c4ed", size = 234109, upload-time = "2026-11-28T19:28:05.952Z" }, - { url = "https://files.pythonhosted.org/packages/ae/76/d501d4b7bc694d0b8da3d3127d7b24d758a293d2fbf2bc53d16f9345b591/msgspec-0.23.0-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:7e3b36f643594ab9754ffe0006089599815c06a6e5ff8142fc9704a585519c98", size = 242278, upload-time = "2026-11-28T19:28:07.208Z" }, - { url = "https://files.pythonhosted.org/packages/6a/0a/49682eb30167c1b936f96bfe96a936505a7efe99593828087597de35c229/msgspec-0.23.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:4ae9e363c1045c4186245c48c0281dd02e3cd8411748cc33b50b0c4f6e019d57", size = 238794, upload-time = "2026-11-28T19:28:08.503Z" }, - { url = "https://files.pythonhosted.org/packages/8a/a1/3a32fb47b06f5082f36cb334603ff63a1944b59e77f649b0d429a5dd52ca/msgspec-0.23.0-cp313-cp313-win_amd64.whl", hash = "sha256:290624a74fe844a21f01c0b4239561aaea8a7a1fa291c1433d73a40079c4a53f", size = 207486, upload-time = "2026-11-28T19:28:09.759Z" }, - { url = "https://files.pythonhosted.org/packages/d5/af/b51353d95f280ec5eb2bbdda4c9a472bbaff4bf36774167749d805ec9c89/msgspec-0.23.0-cp313-cp313-win_arm64.whl", hash = "sha256:a7bc3d5eb017bd22e6721480022f089db5040439c4e96227a7878c2998cbb75e", size = 200041, upload-time = "2026-11-28T19:28:11.114Z" }, - { url = "https://files.pythonhosted.org/packages/04/e8/c991287d1af017003e5140fc312d15749c54e98ad9849269a2e396dc75cc/msgspec-0.23.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:5e1f845e6eac1a9985e31eec434f57b974a5e19365d175a0434f9864923415c0", size = 207988, upload-time = "2026-11-28T19:28:12.642Z" }, - { url = "https://files.pythonhosted.org/packages/a4/e0/14da7ffff4272e26081fd81c8188284e2f9369d9bbb99d66095942b87534/msgspec-0.23.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:f4e62d63f609cf523c658098bd8d54d2e45d169f521649feff2b1855283fd526", size = 200034, upload-time = "2026-11-28T19:28:13.91Z" }, - { url = "https://files.pythonhosted.org/packages/d8/23/9e82922d6450f094814babc17561f55e4ba304d6627a791af46f2c6fc249/msgspec-0.23.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c5b4cec4279c717a0c70cdf3d2a750349bbed82152a87a6863909f3724224836", size = 231792, upload-time = "2026-11-28T19:28:15.332Z" }, - { url = "https://files.pythonhosted.org/packages/e4/00/bad5774cf84f78ab7c94f2bfe918b1890e9ea518be89b39cbaa111fbf3c2/msgspec-0.23.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9d6df6890bc48a2359172ba38dcdd2a8f4a53013bc68a0a6495f8b3c3d4e4024", size = 236745, upload-time = "2026-11-28T19:28:16.624Z" }, - { url = "https://files.pythonhosted.org/packages/57/0b/18ed7bea89186c765f468cb3b64872ffa28cecad63e18cbd08e729789556/msgspec-0.23.0-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0bfdc53912b2dfc6a00d6d9d570838a30b7b099f2ce9f43f0484b64a589d9c03", size = 243396, upload-time = "2026-11-28T19:28:17.92Z" }, - { url = "https://files.pythonhosted.org/packages/d6/86/65635e81fc76a6c27ea8db6d494f8784dee17c6ee1db089cad6434a60d4f/msgspec-0.23.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:66381457284204c6a243cbf22f4ac2db92a1cf13f1d00367c53b7f5111e17067", size = 235364, upload-time = "2026-11-28T19:28:19.052Z" }, - { url = "https://files.pythonhosted.org/packages/13/34/dd1c79943c218967339b09b22ce02ee7605b876c0c36612b5c05b123ab66/msgspec-0.23.0-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:34317aa997dc7634269716a50c7ba4aebfc7ad99f3419a710a35d6a443ce24d6", size = 242305, upload-time = "2026-11-28T19:28:20.307Z" }, - { url = "https://files.pythonhosted.org/packages/1c/5e/2c40267b37e69efa4bacde3216cc59e3a46e0841be5ad5db671aebc84027/msgspec-0.23.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:d4eea7b2ad6d38d873dbf4b311f36914a2a1b19742f297f8c1235d5172540b52", size = 238690, upload-time = "2026-11-28T19:28:21.737Z" }, - { url = "https://files.pythonhosted.org/packages/fa/33/67509d508c2ba46e7ddf00237259e4164dcebabc4650930bc432ccf57946/msgspec-0.23.0-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:1836f50ad87e7c56600b648a1b75c3bbcce62835cb1f489435fc5fee8d068831", size = 141266, upload-time = "2026-11-28T19:28:23.021Z" }, - { url = "https://files.pythonhosted.org/packages/3b/a7/c1edad90f9a0bc986450fe3abece2beb26bbb018b537eea51a599a54912c/msgspec-0.23.0-cp314-cp314-win_amd64.whl", hash = "sha256:2830b00aa61857a306e692ea3579bc6dc59b3957dd3dedac9f143ea922a555cb", size = 212217, upload-time = "2026-11-28T19:28:24.213Z" }, - { url = "https://files.pythonhosted.org/packages/ab/83/a1ac00e31e39f26953061913f6ce8925c57a8893506d35ce39d3a4cdc234/msgspec-0.23.0-cp314-cp314-win_arm64.whl", hash = "sha256:6abeac42c25d5614a228958a7912ff112458daea33f75c5015457f166694cd2f", size = 205483, upload-time = "2026-11-28T19:28:25.485Z" }, - { url = "https://files.pythonhosted.org/packages/94/c2/d807cea3704813993bfda05964361fd61c0801b141920489a14a973358b1/msgspec-0.23.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:cb991f7d12dd8646437dde8975e8c3d1676dea6bda7f0197853df27bb9849cee", size = 211718, upload-time = "2026-11-28T19:28:27.187Z" }, - { url = "https://files.pythonhosted.org/packages/04/83/293950fe10f944f4fcc61ac9a8fd1fcffc752c35dedc525f94488eb80ea0/msgspec-0.23.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:2f0475ce77031a14b83ed5c2db583dd8ae3001dd191248484aed4f8f08c78bbb", size = 203926, upload-time = "2026-11-28T19:28:28.428Z" }, - { url = "https://files.pythonhosted.org/packages/d2/6f/be093639aadfec6322a3c04da791e12ad03b93320f01ecbe8e731c3d8b8c/msgspec-0.23.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:eee899b5d76ecd1682aaca3e6731fd4f4ceca331702b0625f6fda12090c68121", size = 236410, upload-time = "2026-11-28T19:28:29.702Z" }, - { url = "https://files.pythonhosted.org/packages/37/1c/d384dd55fd8e5568c5cb21da8250b76bff1407185ea85c261c7591fca3c5/msgspec-0.23.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:27ca63a01716dc9f4b261945ec13b66d018db6cdfd2dc2a124129c2e2ec1b369", size = 240296, upload-time = "2026-11-28T19:28:30.938Z" }, - { url = "https://files.pythonhosted.org/packages/f2/a6/ecc0bcdeccefbd66114e0b4a3ed694a7905bb771f8671b4d6564693ca5e8/msgspec-0.23.0-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:e83096f88786933f0ba867df1d3fb1d41e10009d57792b918d84690ddafae1ca", size = 248559, upload-time = "2026-11-28T19:28:32.438Z" }, - { url = "https://files.pythonhosted.org/packages/3e/e0/8c408d7d959b0e1bcf79b5cd3ece7b0e9315a20e83db464c5b9414a74339/msgspec-0.23.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:511c4f83916a369a9afb2abb463c3ddd6774470a0ed1ed049f230702e72679e1", size = 239645, upload-time = "2026-11-28T19:28:33.994Z" }, - { url = "https://files.pythonhosted.org/packages/24/f4/6d31c938cfdee9315abb7c3a8c807afada8d709f0a4289013ef83c3176bf/msgspec-0.23.0-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:532df6d66c52b9fe7c612da29d042c0eda7cee270eb35ed5235dfc54cfcee831", size = 247413, upload-time = "2026-11-28T19:28:35.34Z" }, - { url = "https://files.pythonhosted.org/packages/90/09/91590d5c78c9ed42c2608277b84f2aa974f0cb4b9875ccd0dcb7bdade600/msgspec-0.23.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:13a25949a469c19d82516fcabbe1cf2babb5a1b2dd997d285644ec5c96316b00", size = 242637, upload-time = "2026-11-28T19:28:36.652Z" }, - { url = "https://files.pythonhosted.org/packages/d9/a7/dc0a519d58cffea5c8baa91eba85081c26e37537510c852213b1be3ff268/msgspec-0.23.0-cp314-cp314t-win_amd64.whl", hash = "sha256:379b6d6e016aee2c004797970936cfb5231dd3bea0ad7fa01637876b35479511", size = 217609, upload-time = "2026-11-28T19:28:37.839Z" }, - { url = "https://files.pythonhosted.org/packages/c3/c8/5f318a77af9087844910de28888d9f0acaccc3cc1d1116d34f2849a69bd1/msgspec-0.23.0-cp314-cp314t-win_arm64.whl", hash = "sha256:c5cd5b4e1a97fcde9b15304226b27a700d1931349a29abec9db0884a42f91497", size = 209521, upload-time = "2026-11-28T19:28:39.09Z" }, - { url = "https://files.pythonhosted.org/packages/11/9d/e80ad799eb149d9b63d5ff4787f674d741ad45d590032bb30ba8ab6a8a38/msgspec-0.23.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:55ca292b386fc63813b524c782c8cbb45497d3ca3d78e4576eac374294d0796b", size = 209043, upload-time = "2026-11-28T19:28:40.377Z" }, - { url = "https://files.pythonhosted.org/packages/bd/1c/89dfd220e9d14da2682ac56eeb61dabd94faa20215c260edf9b37c51671d/msgspec-0.23.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:6d02d95225da458a21120606eb06106791f18e9550f206e34b71f9ad8f0a59da", size = 200986, upload-time = "2026-11-28T19:28:41.893Z" }, - { url = "https://files.pythonhosted.org/packages/74/98/04a9ff3eba269e4343302f85fcd1b03c7ceccd41ce5f793417c6bd650027/msgspec-0.23.0-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0d14bc8cfe758d63b8f8376236be434fb53500505c4002b67b9d67a30385c794", size = 233244, upload-time = "2026-11-28T19:28:43.732Z" }, - { url = "https://files.pythonhosted.org/packages/b6/bc/3f5a94b68039d2192a2f8fdf42eef0899da6d640a0aef35de1ca4d5c8fe8/msgspec-0.23.0-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d366ac1b286e30e2dfdb52a67056ce27ac6fe4d4edff6cf5dd8fac44865d505e", size = 237974, upload-time = "2026-11-28T19:28:45.238Z" }, - { url = "https://files.pythonhosted.org/packages/6f/a9/60eba35d65eb41b0198d8324aee46b803d1ad94b3413926a8b45a42abb75/msgspec-0.23.0-cp315-cp315-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:2eed0f1d284eafa228fc7174d13ab79f779615993e0627cfed342cb573d39676", size = 248902, upload-time = "2026-11-28T19:28:47.145Z" }, - { url = "https://files.pythonhosted.org/packages/b3/93/b17150d7e50258f0baa454902309afb824041c7892ec4dce1fb11cd1250a/msgspec-0.23.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:3868a8bf5b2b2f36e1b214968423bdd129521ea26b8f77530265b87cb8bab978", size = 236977, upload-time = "2026-11-28T19:28:48.772Z" }, - { url = "https://files.pythonhosted.org/packages/9f/e5/d24bf3cb8d3ac8719d4268bf3d314602b5d9b51390e57bb4c9d68b9e662c/msgspec-0.23.0-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:2cd244c3e713aa68ab4908385882afb2da6ebaf270bcdf84289d640dc846c2d5", size = 248149, upload-time = "2026-11-28T19:28:50.028Z" }, - { url = "https://files.pythonhosted.org/packages/be/6e/f2a765a71172c5e984eb134debc0a51bc58d8a4c860c4427533fe08dd23d/msgspec-0.23.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:ee58dff142359dedf8e2b4da67eea47189d9c161bca26816a4ded4fb18658946", size = 240310, upload-time = "2026-11-28T19:28:51.23Z" }, - { url = "https://files.pythonhosted.org/packages/b9/59/1029072e0307604b9c77c5170d2f83b4a8d5aa3e2fbbe7d2d50320ac3ff4/msgspec-0.23.0-cp315-cp315-win_amd64.whl", hash = "sha256:492870aa884ca02361a35f7f8d4bb6c31b38ed69ea91dadbf676e24176ec2aa4", size = 212785, upload-time = "2026-11-28T19:28:52.406Z" }, - { url = "https://files.pythonhosted.org/packages/39/d0/31dac480f6bef20a8338d1444f52f11cdf1e2617bc57f2bb82bd868f5b6c/msgspec-0.23.0-cp315-cp315-win_arm64.whl", hash = "sha256:0516c3ad2d8f6c774a3c6ac5e72458eb6196dfc02ed71f7eeb5f753f1afa44fd", size = 205826, upload-time = "2026-11-28T19:28:53.676Z" }, - { url = "https://files.pythonhosted.org/packages/36/a6/7c0a1efff67399b7ac6ca6d3f55b645132acd2510e769bb944c5ac95285e/msgspec-0.23.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:6f1bc450334fe4571c710d555e6b3654285f23b66d074633973d5a42596d63fb", size = 212630, upload-time = "2026-11-28T19:28:54.941Z" }, - { url = "https://files.pythonhosted.org/packages/72/ba/2435104bc78822fd6e75748c6876f46cde0a71f1c8fe159ad1f11f718609/msgspec-0.23.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:d33ec9e27926254558e84251790798c03fd6220c27ee0f7633315439b4b3a5be", size = 205199, upload-time = "2026-11-28T19:28:56.28Z" }, - { url = "https://files.pythonhosted.org/packages/9d/20/0bd08638eff23b25f96470f59c9765546a11ab367a1dd1328e9241d9ec32/msgspec-0.23.0-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:dfeef9ad65224f06430e7413fda72802b917a56e42a4e982b23301f018e1a245", size = 238340, upload-time = "2026-11-28T19:28:57.716Z" }, - { url = "https://files.pythonhosted.org/packages/3a/ee/8087965ea8fd4fe1d356f48dc61f9a6ef79665275a270ca0df991a50406a/msgspec-0.23.0-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c00ac40e1fa738c8b91cbd327331f4a8acf44d74a0c7217016a4e0746c486d82", size = 242541, upload-time = "2026-11-28T19:28:58.952Z" }, - { url = "https://files.pythonhosted.org/packages/4f/95/9d353ae41398265b5367282838c4d5ad2923548c55ac47c53d5f7ef1f762/msgspec-0.23.0-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:9188481152e4f7a1b77c9e3023c086b5ad46253e0ca7b1b067914997e1f89d34", size = 253297, upload-time = "2026-11-28T19:29:00.259Z" }, - { url = "https://files.pythonhosted.org/packages/f3/a4/ebb158a3a4d87a099e2c24381cc4164519bf2d758ed3e3d43571538a3f36/msgspec-0.23.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:fea7eeada89851826e240bba0cd29e7f406d83653a614dddf8c32232aca0425f", size = 241029, upload-time = "2026-11-28T19:29:01.538Z" }, - { url = "https://files.pythonhosted.org/packages/d1/ac/d79d5d3933a778946e807bfd87f15dd6e54fe2e35ff994d439b26152386b/msgspec-0.23.0-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:a7cd9381789b2dc8f6fef5d7ae8a65a8a8511bbd8e04f3a48946a98b03a24bff", size = 254370, upload-time = "2026-11-28T19:29:03.043Z" }, - { url = "https://files.pythonhosted.org/packages/69/7f/6819edf18bd4999aaa1cbbd8d3484187f3770f291b5a4464fe56123a67c5/msgspec-0.23.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:b0c55588edf6e403d76570ea9493574703f328f7adffc111de70f2adaf1834e4", size = 244917, upload-time = "2026-11-28T19:29:04.291Z" }, - { url = "https://files.pythonhosted.org/packages/2e/2f/a37cfbb946de4c8b12518dee0ae8d9ed73f9340ca0f605dfd62cb38a6a67/msgspec-0.23.0-cp315-cp315t-win_amd64.whl", hash = "sha256:5f6993f0d0382cb6a6afb2f48531ca3f6e47526c79aed028702813b6f4a0ed6b", size = 217521, upload-time = "2026-11-28T19:29:05.554Z" }, - { url = "https://files.pythonhosted.org/packages/81/d2/87bb8406c3d172af5ecd21fdce3eed558be3f6cce6692fc7d938e90c396a/msgspec-0.23.0-cp315-cp315t-win_arm64.whl", hash = "sha256:8cb516c68f9b91fbe5c08de75394ec4629fbc78ba2e7da84ed3130f876234ddd", size = 210112, upload-time = "2026-11-28T19:29:06.882Z" }, -] - -[[package]] -name = "narwhals" -version = "2.29.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/c4/20/e2cce41bfa17909205b39c8a4aa3ec730d87f1c4e77453efd3f5aaf50b81/narwhals-2.29.0.tar.gz", hash = "sha256:eb19c877d9a705300bcc9414499a07b32a52db703369414e57e474ca5fc63c42", size = 773295, upload-time = "2026-11-17T15:30:43.03Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/9e/2b/20b4b463c3795dc390db8fa6ec2b5c3e0aea90a760f813305da4c33dd814/narwhals-2.29.0-py3-none-any.whl", hash = "sha256:1c69b3dc30240f6e848c5a673cafc86affa44184ecce721e25b7194663ad10dc", size = 501718, upload-time = "2026-11-17T15:30:41.263Z" }, -] - -[[package]] -name = "numpy" -version = "2.4.6" -source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version < '3.12'", -] -sdist = { url = "https://files.pythonhosted.org/packages/d0/ad/fed0499ce6a338d2a03ebae59cd15093910c8875328855781952abf6c2fe/numpy-2.4.6.tar.gz", hash = "sha256:f3a3570c4a2a16746ac2c31a7c7c7b0c186b95ce902e33db6f28094ed7387dda", size = 20735807, upload-time = "2026-05-18T23:37:14.07Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/b3/49/ec46835a70be8fa6446c495126ac84fdb28cb2558e1620ffb87a10c8b64c/numpy-2.4.6-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:0280e0356c0829a18d9de1cb7eee50ec22ca639878d7240307ca0943d73cd2c4", size = 16969194, upload-time = "2026-05-18T23:33:13.503Z" }, - { url = "https://files.pythonhosted.org/packages/0e/0d/f5957185c0ee2f3e12f78715aa9e3b353fd83633316c8532b38faa37e3f6/numpy-2.4.6-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:110f8b71aacb688ec69062bb7f6938a0f8acb01b7c1c4beb453c65b6d234584d", size = 14964111, upload-time = "2026-05-18T23:33:17.795Z" }, - { url = "https://files.pythonhosted.org/packages/ad/40/40a40ee0ddf7ceb782c49af278894b686e586d65d8c1889c8b5da01a3d7d/numpy-2.4.6-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:4cfe66903cc32a9921a6733d96b19bb6abf310397581bbad89c228f5abaf0ee8", size = 5469159, upload-time = "2026-05-18T23:33:20.654Z" }, - { url = "https://files.pythonhosted.org/packages/63/13/f9a8046535cb21deae82f8d03de9617e08882d274fad2539630761888228/numpy-2.4.6-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:8155154c7c691289fe18f510b5d4657c68c67989f293f0535a91360392ff6538", size = 6798936, upload-time = "2026-05-18T23:33:22.987Z" }, - { url = "https://files.pythonhosted.org/packages/33/a8/6fa8c1a345a8c85dbb21932c447bee07c30a2c2a3f31e369c0a84b300147/numpy-2.4.6-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0ab0a9c4ffb1a6d95ef519fe4247dba8eb6b18ad93999f76b7f657039acabd47", size = 15966692, upload-time = "2026-05-18T23:33:26.62Z" }, - { url = "https://files.pythonhosted.org/packages/02/03/74fe2a4cb3817d94d86402f2506554130a2f01414e299b5a843e5a8a957f/numpy-2.4.6-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:89cd468399cfd2504718f0ba50e410dca55a170b61a02ad92bb18c8a65186e93", size = 16918164, upload-time = "2026-05-18T23:33:29.955Z" }, - { url = "https://files.pythonhosted.org/packages/c5/80/3615be3313f7e7696609bc194b9f0101da809df79e859bdb84e0cd043f46/numpy-2.4.6-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:c2d37ab77531417474168eb79d6d80b14f821a966818505d03013d0833edb7a8", size = 17322877, upload-time = "2026-05-18T23:33:34.724Z" }, - { url = "https://files.pythonhosted.org/packages/ca/ac/a691e0fe2675e370d0e08ff905adc49a1c8830e8cae03efe4477e92cd55d/numpy-2.4.6-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:f407cb6b8e9d6d8c626bc73c945db1706035af8fd632295547bf1c9e46d092d6", size = 18651487, upload-time = "2026-05-18T23:33:38.217Z" }, - { url = "https://files.pythonhosted.org/packages/15/a7/9bc1cd626d7bf6869bfedf27b91b6ab5dd607758bf8e959d6fa80c6a59cb/numpy-2.4.6-cp311-cp311-win32.whl", hash = "sha256:ddea102b48f9e339f3948bf22040944184627a30fdf7f858667673b9c5f033c8", size = 6233945, upload-time = "2026-05-18T23:33:41.331Z" }, - { url = "https://files.pythonhosted.org/packages/c5/31/7fc6239c12bce7e931463251cca4426c465e1876ba3cc785402ef4dd8f4e/numpy-2.4.6-cp311-cp311-win_amd64.whl", hash = "sha256:1e254a00cdf42b1e4d5b3d68d33af63268d41340d8885df2ab6470f2e1500147", size = 12608406, upload-time = "2026-05-18T23:33:44.131Z" }, - { url = "https://files.pythonhosted.org/packages/27/83/140f85a466595a16382996a1bf06b2b54bcd597488921b0c9daaeeda72af/numpy-2.4.6-cp311-cp311-win_arm64.whl", hash = "sha256:ed9749eef4cbd126da3dc1d6bcb3a57f5eb7ac6a6484146bdbf743f552dfc577", size = 10479528, upload-time = "2026-05-18T23:33:50.725Z" }, - { url = "https://files.pythonhosted.org/packages/95/2a/3d7b5ac8aac24feaf9ad7ed58f45b0bbc06d37e4338ae84c9f2298b570f9/numpy-2.4.6-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:001fbb8e08d942dd57599e781f2472269ee7f2755fae407b4f67b2f0b17da3f1", size = 16689119, upload-time = "2026-05-18T23:33:54.065Z" }, - { url = "https://files.pythonhosted.org/packages/ea/12/92c4c131527599e8288d6918e888d88726f84d805d784b771f32408aeaef/numpy-2.4.6-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ebfb099f8dcf083deef3ac1ca4c1503f387cf76296fcb3816b66f5ecb5f54fdb", size = 14699246, upload-time = "2026-05-18T23:33:57.621Z" }, - { url = "https://files.pythonhosted.org/packages/ad/fe/c0a6b7b2ca128a8fb228575147073b660656734b8ebe4d76c8fd748dcc79/numpy-2.4.6-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:3213d622a0283a39a93d188f3cf72b26862df52fbb4ca3697f51705016523d41", size = 5204410, upload-time = "2026-05-18T23:34:00.302Z" }, - { url = "https://files.pythonhosted.org/packages/f3/d4/9770d14ba719432bb90a421bfd443872ed0f70f7264b64bec12ea363d5fd/numpy-2.4.6-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:357cc07a6d7b0b182ff02249616a03742827ebb1277546b5c7cd7f7620a45698", size = 6551240, upload-time = "2026-05-18T23:34:02.852Z" }, - { url = "https://files.pythonhosted.org/packages/c9/c6/50a46a6205feba2343f1d6d17438107c5dc491ed1c736e6ea68689fd906b/numpy-2.4.6-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5f9fb9157b4ce2971008323afe46053787b526ef624fea915b261468a8421a0f", size = 15671012, upload-time = "2026-05-18T23:34:05.485Z" }, - { url = "https://files.pythonhosted.org/packages/99/60/14115e6364fa676c5397c2ad3004e527e9aa487abf5d0706ec81bbd08529/numpy-2.4.6-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:90f9849678c75fe7afa2d348ac842c168b0a4d3d61919687216dfc547976d853", size = 16645538, upload-time = "2026-05-18T23:34:09.265Z" }, - { url = "https://files.pythonhosted.org/packages/ae/c5/693cbe59e57db94d2231fa519ca3978dc9e19da5a8f088588f5c6e947ff2/numpy-2.4.6-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:c1a2af6c6ef86344a6b0db6b97834208bf598db514f2b155042439b62605601a", size = 17020706, upload-time = "2026-05-18T23:34:13.053Z" }, - { url = "https://files.pythonhosted.org/packages/ef/fc/85b7c4eff9b4966ade25c2273cf7e7012e92366c032058653934b37de044/numpy-2.4.6-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:e5805d5a22fd19c8ccff10a9561f9df94436b0545619ea579db2d3c35294bce2", size = 18368541, upload-time = "2026-05-18T23:34:17.024Z" }, - { url = "https://files.pythonhosted.org/packages/f6/81/e1b27545deedce7f4a0b348618c6b62d74e36a4dc9ccd42f3eb2f85eee32/numpy-2.4.6-cp312-cp312-win32.whl", hash = "sha256:e3eeb0aabd6bd5ce64faae67e9935203a6991b4bc2a485a767fbafb2c5125f45", size = 5962825, upload-time = "2026-05-18T23:34:20.3Z" }, - { url = "https://files.pythonhosted.org/packages/ab/ca/feab00bd44aa5fe1ad2c18f08b4d3bb92e26484b0b1d1443897809ed528c/numpy-2.4.6-cp312-cp312-win_amd64.whl", hash = "sha256:d8e8286dd7cea7895157318d1b91cdacac64c479f3cbc8dce548331728484751", size = 12321687, upload-time = "2026-05-18T23:34:23.095Z" }, - { url = "https://files.pythonhosted.org/packages/63/cf/5a6d34850a39d1093558564f77ee8e8e0bee5061151b8f05a55711001ec7/numpy-2.4.6-cp312-cp312-win_arm64.whl", hash = "sha256:4081eb135ac24158bd51cdfbef16f1c64df7063b1143f24731387137c092bec8", size = 10221482, upload-time = "2026-05-18T23:34:25.876Z" }, - { url = "https://files.pythonhosted.org/packages/fb/82/bdab26d7438c6791ca31b7c024ca37c1eab8b726ba236129005cd4a06e45/numpy-2.4.6-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:511dbaf848decaaaf4b4ca48032619fb3138710c4bf7da7617765edad1ef96b0", size = 16684648, upload-time = "2026-05-18T23:34:29.41Z" }, - { url = "https://files.pythonhosted.org/packages/1b/30/a80189bcc7f5e4258b3fbc3968d909d1756f54d023299ecc39ad6fdb9ef8/numpy-2.4.6-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:bf162abab1c1a736333192707cef898e735a5ca00f38f27eeedf44b39d9e85eb", size = 14693902, upload-time = "2026-05-18T23:34:33.013Z" }, - { url = "https://files.pythonhosted.org/packages/97/12/70b5d0d7c15e1ebb8a6a84a8caa1d19e181d84fb58bb6d70aca29099dec1/numpy-2.4.6-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:043191bfa8eab18c776647b62723ac9dddece59743b13f49b2016094129c2b3f", size = 5198992, upload-time = "2026-05-18T23:34:36.132Z" }, - { url = "https://files.pythonhosted.org/packages/ba/8c/ebd2a8f8a83541f8d38cc5667e8c2b69cecfd30da6e45693e8158857d44b/numpy-2.4.6-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:6180d8b35af935aed8ece3a85e0a43f87393ae0ac87c8d2c8bd2c993f7270ef3", size = 6546944, upload-time = "2026-05-18T23:34:38.484Z" }, - { url = "https://files.pythonhosted.org/packages/bb/c5/7b863a97a91671a0338f4253bd3b5a3d3852f0692dae91711c9f4a10e787/numpy-2.4.6-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:72fbe16c6fac95aedf5937fa873445cec2110be35d8a4e9433d7501fd98dae6b", size = 15669392, upload-time = "2026-05-18T23:34:41.257Z" }, - { url = "https://files.pythonhosted.org/packages/a5/9d/3584b9984ca4c047aea75214ce1a4c4c73d849bd71b604264b7f5653f8a8/numpy-2.4.6-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a7830bab239b79cda9c08c2da014761cafb48da6150e1da17ac06283f43b6089", size = 16633220, upload-time = "2026-05-18T23:34:45.075Z" }, - { url = "https://files.pythonhosted.org/packages/05/ae/7c67fba23bd98caec7c99261f3a16072ade14813486b0282cb29846de832/numpy-2.4.6-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:ef4aea96ce4d3b074422cb4f2f64e216bf9e213004bb58ecfdf50ea02ea8eb9a", size = 17020800, upload-time = "2026-05-18T23:34:49.065Z" }, - { url = "https://files.pythonhosted.org/packages/d9/5d/3b6725cb31d983c5e66916f5d36f6d7e5521129e4c4404d64f918292a5b6/numpy-2.4.6-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:dfa20cc6ca228e6b155b11da03825975ce66aea520985dbbddf0f2a5a495c605", size = 18357600, upload-time = "2026-05-18T23:34:52.709Z" }, - { url = "https://files.pythonhosted.org/packages/f7/da/2ccc6c2fe8898dee01d90c75c5f5f914a23daf99e3e0f59516a08760c8b5/numpy-2.4.6-cp313-cp313-win32.whl", hash = "sha256:56b39e5e0622a09a25bf5baf62f4bcf0cb8a41ae6e2819cf49bbc5a74c083f91", size = 5961134, upload-time = "2026-05-18T23:34:55.618Z" }, - { url = "https://files.pythonhosted.org/packages/b5/cd/9cc4dc876fb065d5c220aae4d5e14826b2715331bb7618ce1fb07a679d99/numpy-2.4.6-cp313-cp313-win_amd64.whl", hash = "sha256:c4fc99836233ea196540b17ab0983aff60ed07941751930f5f4d05bc3b3b7359", size = 12318598, upload-time = "2026-05-18T23:34:58.928Z" }, - { url = "https://files.pythonhosted.org/packages/39/1e/c0bcba1f8694116485fe28fd1be698c278fcda4141c5b0e53a2aed8b12a8/numpy-2.4.6-cp313-cp313-win_arm64.whl", hash = "sha256:a7c711e21628b52034bb5ab8d1bce291f752fcc5e92accc615778acee1ff4778", size = 10222272, upload-time = "2026-05-18T23:35:02.167Z" }, - { url = "https://files.pythonhosted.org/packages/63/6d/cc5619247c8f4204e507f5883528372e4ac4bb189e579fb859a12e480b1f/numpy-2.4.6-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:112b06a867b235ef466ed3508ddf0238050df9c727cafb5301ac385b899189a1", size = 14821197, upload-time = "2026-05-18T23:35:05.468Z" }, - { url = "https://files.pythonhosted.org/packages/00/58/f1c39161c87d9e9bed660f1ed4bafc0e403d5ec9650b6dd77aead07d489b/numpy-2.4.6-cp313-cp313t-macosx_14_0_arm64.whl", hash = "sha256:eaf7fa2de5c0be8ae6ff8e9bea2ccd725e980541244521d8d4b5f3354a27babe", size = 5326287, upload-time = "2026-05-18T23:35:08.693Z" }, - { url = "https://files.pythonhosted.org/packages/af/57/3917ab0fd97f271a8694513581b8a36c655f111c446852c302f04ccdb6fc/numpy-2.4.6-cp313-cp313t-macosx_14_0_x86_64.whl", hash = "sha256:7265a2f3d436e54ef9f2b52b5c937e6be778781bd97a590319d7348f1c1ca997", size = 6646763, upload-time = "2026-05-18T23:35:11.459Z" }, - { url = "https://files.pythonhosted.org/packages/eb/0f/037e64c494b67581ae18193d770adef354c41f3f2c8ebf865602d949bf8f/numpy-2.4.6-cp313-cp313t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f74a575920ab21fe304421a3fc28793d82e299cae9eccb37084e9fc7f3617c20", size = 15728070, upload-time = "2026-05-18T23:35:14.79Z" }, - { url = "https://files.pythonhosted.org/packages/21/a6/5d2bae9c9542eb4df16dc9c46dc79c186e9bad53805dfa5399a6023c6db0/numpy-2.4.6-cp313-cp313t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ede83e07a75dd06bc501566c1eca2afc0d61677c1472ac9ad93fdee6e638a48d", size = 16681752, upload-time = "2026-05-18T23:35:18.836Z" }, - { url = "https://files.pythonhosted.org/packages/92/14/23d1dfb410ae362cd59ce53e936b1513d545eb40db3949ced632e19a459e/numpy-2.4.6-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:68bb27509ac1b9a3443094260f6326150663b06abe40b73a2f81160623da5b67", size = 17086024, upload-time = "2026-05-18T23:35:22.52Z" }, - { url = "https://files.pythonhosted.org/packages/4b/6e/23595a2c642cdf3bc567877064bdd7f91c8b0038a4453cf2daf7248eafe9/numpy-2.4.6-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:a0df0043bdb289bde1f62da130d20df23d58b45429f752bc7a8fc5325a225ecd", size = 18403398, upload-time = "2026-05-18T23:35:26.398Z" }, - { url = "https://files.pythonhosted.org/packages/8a/90/0ac3bc947217e66dec77e7cbc6a1979d1af70b6461b82f620d3bccd5e4c8/numpy-2.4.6-cp313-cp313t-win32.whl", hash = "sha256:29a287e0cf63ff528da061de6b9f64a4618da591ca1046aafc54062e40ca7eab", size = 6084971, upload-time = "2026-05-18T23:35:29.387Z" }, - { url = "https://files.pythonhosted.org/packages/77/71/5673e351671a1d2bd6063b91b44f70c0affea7d1516fa7a6572941ba4aa1/numpy-2.4.6-cp313-cp313t-win_amd64.whl", hash = "sha256:25c692919ac5a01f170a3bfcd62d745b24fd095c353d50812637d6fcab442e75", size = 12458532, upload-time = "2026-05-18T23:35:32.175Z" }, - { url = "https://files.pythonhosted.org/packages/3f/88/19d3503c5046e688f049274b27a3ef3d771152fa80d3ba3d01a3dff61abe/numpy-2.4.6-cp313-cp313t-win_arm64.whl", hash = "sha256:1e978ec1e8bd0e0e4de6bb75de9d30cbb74db6b6a2bb727618613703ca0167dd", size = 10291881, upload-time = "2026-05-18T23:35:35.465Z" }, - { url = "https://files.pythonhosted.org/packages/f8/91/3ab2044d05fd16d343c5ac2e69b127f1b2854040dd20b193257c78028bd3/numpy-2.4.6-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:06ca2f61ec4385a07a6977c55ba998a4466c123642b4a32694d3128fce18c079", size = 16683458, upload-time = "2026-05-18T23:35:38.353Z" }, - { url = "https://files.pythonhosted.org/packages/8e/62/764ce66fa4147ae6d73071a3abf804ffe606f174618697c571acdf26a7c9/numpy-2.4.6-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:38efbc8de75c7a0fc1ac190162d892787f3f47b57cc291231aafee36b80982b7", size = 14704559, upload-time = "2026-05-18T23:35:42.14Z" }, - { url = "https://files.pythonhosted.org/packages/60/61/23f27c172f022e04025b7dc2367f4d63c1a398120607ec896228649a6f48/numpy-2.4.6-cp314-cp314-macosx_14_0_arm64.whl", hash = "sha256:d581b735e177fdcdce6fed8e7e8880a3fb6ee4e3653a3ac6af01c6f4c03effc5", size = 5209716, upload-time = "2026-05-18T23:35:45.377Z" }, - { url = "https://files.pythonhosted.org/packages/03/71/21cf70dc6ea3e3acb95fc53a265b2fc248b981f0194ceb5b475271b8809d/numpy-2.4.6-cp314-cp314-macosx_14_0_x86_64.whl", hash = "sha256:0a041d3d761dc3c35cc56ce0351506a02bcbc25f7b169f652435141a17db9096", size = 6543947, upload-time = "2026-05-18T23:35:47.926Z" }, - { url = "https://files.pythonhosted.org/packages/d5/91/64288395ee1799bd2e0b04a305dce9666da90c961e1f3fe982a05ee1c036/numpy-2.4.6-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:40fdc1ae7125e518ea98e53e69a4ebc27e1fd50510c47b7ea130cf21e5e1d42b", size = 15685197, upload-time = "2026-05-18T23:35:50.863Z" }, - { url = "https://files.pythonhosted.org/packages/f3/eb/ebffaa97dc55502df69584a8f0dcf07f69a3e0b3e2323670a2722db9aa39/numpy-2.4.6-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a2c306dea656c12c68f51f4cea133cbe78ca7435eb28c735eac1d3ebe73be6e8", size = 16638245, upload-time = "2026-05-18T23:35:54.752Z" }, - { url = "https://files.pythonhosted.org/packages/b8/0b/54f9da33128d7e350fab89c7455902eeae70349ee52bddb448dc4a576f45/numpy-2.4.6-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:33111801a01c12a8a1e3721f0a9232f8cfc8ae2c6b7098167e6f623c6073f402", size = 17036587, upload-time = "2026-05-18T23:35:58.355Z" }, - { url = "https://files.pythonhosted.org/packages/b6/f0/fdebc1052db1cc37c64beb22072d67cd6d1c71adca1299f53dec2b5e20d3/numpy-2.4.6-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:ae506e6902902557576a26ff33eda8695e7ecb3cb36c3b573a0765dee114ebdb", size = 18363226, upload-time = "2026-05-18T23:36:02.845Z" }, - { url = "https://files.pythonhosted.org/packages/aa/b4/298628d98c72b57e57f7165ae6a481a1deaf6f3c28262a6e4c739c275930/numpy-2.4.6-cp314-cp314-win32.whl", hash = "sha256:aaf159caa35993cb1f56fb9b8e4610d35758e7ca005412eb1daa856a78c9c4b1", size = 6010196, upload-time = "2026-05-18T23:36:05.92Z" }, - { url = "https://files.pythonhosted.org/packages/df/ac/46de6dda46478f7942f839e094970be2d4a861e005c4b3bf07c92e291a09/numpy-2.4.6-cp314-cp314-win_amd64.whl", hash = "sha256:b507f5c4c1d508876d1819b6bf9a49d365b96320b5d4993426b33a23ca4b8261", size = 12450334, upload-time = "2026-05-18T23:36:09.107Z" }, - { url = "https://files.pythonhosted.org/packages/78/92/b8b798ac784102c0da830d2257d59358e3d3d90d1e2b3f2575dad976c5cf/numpy-2.4.6-cp314-cp314-win_arm64.whl", hash = "sha256:6f41ae150c4e32db4f3310cdaf64b1593a03dbabe29eec77fc9b50fe64061df6", size = 10495678, upload-time = "2026-05-18T23:36:12.766Z" }, - { url = "https://files.pythonhosted.org/packages/30/34/ec28d1aa8115971537c01469ab2011ee96827930f0a124de1000cc2a7ed7/numpy-2.4.6-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:ece3d2cfe132e7d51f44a832b303895e6f2d499c5e74dfbdb06ee246147a304a", size = 14823672, upload-time = "2026-05-18T23:36:16.473Z" }, - { url = "https://files.pythonhosted.org/packages/16/bd/f6d1fede4e54e8042a7ff97bb495510f3c220f94bcd9e8b228e87c92cc0d/numpy-2.4.6-cp314-cp314t-macosx_14_0_arm64.whl", hash = "sha256:e3e5193ef5a3dc73bceee50f7fdc2c90dbb76c42df8d8fae3d1067a583df579e", size = 5328731, upload-time = "2026-05-18T23:36:19.767Z" }, - { url = "https://files.pythonhosted.org/packages/f4/f0/e105b9e2fd728a9910103884decd6951d9dd73896b914a98d9a231de02ee/numpy-2.4.6-cp314-cp314t-macosx_14_0_x86_64.whl", hash = "sha256:17f9ade344e7d9b464a084d69bcf18fc691cb1db67c62ed80820bf4926d78f0e", size = 6649805, upload-time = "2026-05-18T23:36:22.266Z" }, - { url = "https://files.pythonhosted.org/packages/82/dd/1206a7ca6ab15e3f02069707ca96222e202af681bb73756da7527f3cb837/numpy-2.4.6-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9cd5ffd25db4e7ba6a375693b3fc0fc1791ec636c17db3720da19bde7180ec43", size = 15730496, upload-time = "2026-05-18T23:36:25.713Z" }, - { url = "https://files.pythonhosted.org/packages/51/e7/38d3ea825dcab85a591734decb2f6c67caa7c8367d374df1a1c3842f9b07/numpy-2.4.6-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7d92c3819208a60205a12a245c91ad70cb0a85336659b19b834205573ac8456e", size = 16679616, upload-time = "2026-05-18T23:36:29.652Z" }, - { url = "https://files.pythonhosted.org/packages/93/b7/caabfdf53edf663e0b4eb74d7d405d83baef09eb5e83bcd32d601d72b93e/numpy-2.4.6-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:e85b752a1e912b70eaad4fafbd4d1238007ab221de2009b9a2f5ae7461239895", size = 17085145, upload-time = "2026-05-18T23:36:33.449Z" }, - { url = "https://files.pythonhosted.org/packages/f9/45/68d7c33a6bcf3e5aa3bdbd57a367e6f615286dfd6482f97e8ffeb734306e/numpy-2.4.6-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:29cb7f67d10b479ff07c17d33e39f78c07f71c40ef30d63c153d340e96cd3fb4", size = 18403813, upload-time = "2026-05-18T23:36:37.369Z" }, - { url = "https://files.pythonhosted.org/packages/9c/50/0753655aa844c99cd9e018aacf76f130f1bd81d881bb74bc0aef5d73a8ba/numpy-2.4.6-cp314-cp314t-win32.whl", hash = "sha256:260a5d70215b61ab4fadf5c7baacd64821842975eea312125ed3c39a6391b063", size = 6156982, upload-time = "2026-05-18T23:36:40.817Z" }, - { url = "https://files.pythonhosted.org/packages/b2/d4/7c67becf668f973cb490cec3e98dfd799d866f9c989a54d355672cfa0db6/numpy-2.4.6-cp314-cp314t-win_amd64.whl", hash = "sha256:81a1cca95ed5bb92aa8b10dd2cdc9a0d3853a50fad926c28b5d7e8ea54389627", size = 12638908, upload-time = "2026-05-18T23:36:43.996Z" }, - { url = "https://files.pythonhosted.org/packages/43/bb/e1c71a4295b1b1d1393d50dbb4f2a36283c6859d9d3892e84f00ec5a91d5/numpy-2.4.6-cp314-cp314t-win_arm64.whl", hash = "sha256:0c9136e14ed34a9e343a31c533d78a9813a69a3148332bce5e9821cb2f996e66", size = 10565867, upload-time = "2026-05-18T23:36:47.114Z" }, - { url = "https://files.pythonhosted.org/packages/de/12/b422cc84439adc0d00de605bf4a308890ae5c26f2c71fbd73e5d08fbb0dd/numpy-2.4.6-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:55cced7c52e981362f708ad635198e97a752dfba412cc03c23bbf3bd8d5cd662", size = 16847511, upload-time = "2026-05-18T23:36:50.673Z" }, - { url = "https://files.pythonhosted.org/packages/44/53/f481bef68011740f8849418d82db07230e825013f31f4eef5ba5b805316a/numpy-2.4.6-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:d6da64deb6b8ed903e7560180a92f2d804ee1ba5eeb849ac2748b8c1aba1f6d7", size = 14889064, upload-time = "2026-05-18T23:36:53.879Z" }, - { url = "https://files.pythonhosted.org/packages/7f/57/42ed575c10ced8af951d426bc4e1f8aff16fd851db33f067036215a7f860/numpy-2.4.6-pp311-pypy311_pp73-macosx_14_0_arm64.whl", hash = "sha256:68a5124b13fa6cc2086764a20005d30bc0548146f7f5322f02fce212ca14317f", size = 5394157, upload-time = "2026-05-18T23:36:57.194Z" }, - { url = "https://files.pythonhosted.org/packages/6a/ef/f66cc724fcc36c1e364c67f51ae9146090b8b584f27d58b97fdae3edd737/numpy-2.4.6-pp311-pypy311_pp73-macosx_14_0_x86_64.whl", hash = "sha256:948424b06129ce883307e8cff868c31396d8dc7630a59c61d70d98dbe70f222c", size = 6708728, upload-time = "2026-05-18T23:36:59.575Z" }, - { url = "https://files.pythonhosted.org/packages/1a/9c/c531f2293b91265d8b48e9b329f54fdd7ffae73cb4134ea10cca4237e9cc/numpy-2.4.6-pp311-pypy311_pp73-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5dbbdb29840ca3d91ee0fece42fc29278886d908280bfec0a5846c6f901a3eb0", size = 15798374, upload-time = "2026-05-18T23:37:02.674Z" }, - { url = "https://files.pythonhosted.org/packages/1a/b0/413077f6b1153ed3cba361401c6783bbad6114804a000cc22eb71c13e190/numpy-2.4.6-pp311-pypy311_pp73-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8ad03c0965fb3c692200e74d458ca28c1dbb4ce96f9a479a8aa041ad5fabca02", size = 16747286, upload-time = "2026-05-18T23:37:06.327Z" }, - { url = "https://files.pythonhosted.org/packages/15/ce/e5ec180bc41812edcd8daeb8639d205622c0e8c02259d8ab25a0201b3c2a/numpy-2.4.6-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:2803abfebfc990042cd494d8ce2d5f82e9d847af6d35ec486923aa19dbad5e73", size = 12504263, upload-time = "2026-05-18T23:37:09.715Z" }, -] - -[[package]] -name = "numpy" -version = "2.5.5" -source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version >= '3.12'", -] -sdist = { url = "https://files.pythonhosted.org/packages/4e/3a/8770c288c47f0b5c2a786d3c20e79f66fd245f2d42cd232d7cd5e00e83e5/numpy-2.5.5.tar.gz", hash = "sha256:5cddc243c75114ba845f01b1f87aca1572dbf7b6c2d88636ed3e1d2bccd7f1bf", size = 20873892, upload-time = "2026-11-15T21:32:28.607Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/20/74/5b99f425938870958d43dc9f7b17c684e793ce47ec46b7885cdc7acea285/numpy-2.5.5-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:7da9a248f149cfbb220c6da964a59c8d051d516704f7758acfb81eb382a05d97", size = 14750374, upload-time = "2026-11-15T21:30:10.113Z" }, - { url = "https://files.pythonhosted.org/packages/5c/f4/06db317e93dd6d618786004c1761214b113832bb77294c8513776956702a/numpy-2.5.5-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:b96e9ee49ccbdb5676359f852a4497f7a9c5df6c377d8877f5330d6fd3ff42e4", size = 10749920, upload-time = "2026-11-15T21:30:13.092Z" }, - { url = "https://files.pythonhosted.org/packages/8a/92/6de34324a266b73c04ba977db5864b9016500076b26f09078a565f527d34/numpy-2.5.5-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:a3856a97e48ed8371c680fb04120b99fbcc29f2076ebe6dc3deb34f77947c5ca", size = 5513680, upload-time = "2026-11-15T21:30:15.201Z" }, - { url = "https://files.pythonhosted.org/packages/1e/a1/6563b74cd67e3873f9897afebb3244529b1494d4c0df30f3201329a7e316/numpy-2.5.5-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:f5e8603f0892d1b848e12124863b5b29af72383ee9b25ddc6fe4967d4c1ee6ef", size = 6797540, upload-time = "2026-11-15T21:30:17.172Z" }, - { url = "https://files.pythonhosted.org/packages/c2/22/82184e9a5b50a4a298e9f8fe0bd8cfc483672dbfea8a3b57c78e2376b139/numpy-2.5.5-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a0750f2156d53446caca85663d0b65d67214e1664b9050454a731ea1418d176a", size = 15284117, upload-time = "2026-11-15T21:30:19.167Z" }, - { url = "https://files.pythonhosted.org/packages/99/61/522b973ba38987b22a4a71beaed2ea6ac9fd4f687baaa2bc9a45100625e0/numpy-2.5.5-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:704d819265e5d1064d932968e9ee85fff2103ccc78c05b878c06943ba27b8507", size = 15720599, upload-time = "2026-11-15T21:30:21.273Z" }, - { url = "https://files.pythonhosted.org/packages/25/cd/182cf60bd9c34e617c516f138f2f68988760062fa65fca8fcc97875cf7cf/numpy-2.5.5-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:86868185bf4b6c4e5a8628ac42cfa165cd9530266c731f7dd1d11b4ad7e7cd1c", size = 16503566, upload-time = "2026-11-15T21:30:24.023Z" }, - { url = "https://files.pythonhosted.org/packages/f3/57/4fa4723e80be805f68af552731ed483974b2a11e511284a9ef6aafbcb3cf/numpy-2.5.5-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:7fb87c4bcc73850ef433a0c42f096b010d3d3d284e9d00028bb030b43df3d078", size = 17082560, upload-time = "2026-11-15T21:30:26.224Z" }, - { url = "https://files.pythonhosted.org/packages/d5/0b/73d2bd5be85d3178a862e8354e2d6441b4040fadf1e7d999e01b0bdfa5c6/numpy-2.5.5-cp312-cp312-win32.whl", hash = "sha256:263b2aa236d752b18f90c5107137d24b2e3856d7db37725609f0ab5bcdb58881", size = 6146378, upload-time = "2026-11-15T21:30:28.328Z" }, - { url = "https://files.pythonhosted.org/packages/d1/71/b1ce51834c21020d189332979d38ba7350eb6cd7ca8c8ec424a663b0ca6f/numpy-2.5.5-cp312-cp312-win_amd64.whl", hash = "sha256:919eb420662b0b4ba34889df503f3d5329775b0c1d5f7e5f5af4fba8315b1e30", size = 12580189, upload-time = "2026-11-15T21:30:30.025Z" }, - { url = "https://files.pythonhosted.org/packages/c2/5e/09ae9d0d02fbfe6b160043349bbe73e6bbbbfb2565bb46146dd943687271/numpy-2.5.5-cp312-cp312-win_arm64.whl", hash = "sha256:f6622e32cb46c60bee3b2c7dd7f5c22bdc86fcb8630336b4822ec81c3986111a", size = 10535386, upload-time = "2026-11-15T21:30:32.112Z" }, - { url = "https://files.pythonhosted.org/packages/0f/fa/4ae71d860267f2f9eaf7640516f693acf61c9575d48157cdea459c0215aa/numpy-2.5.5-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:228e3d90e967495d61ddc79dd64e95267aae3bcf1b1c516a6186429106a0b444", size = 14747053, upload-time = "2026-11-15T21:30:34.251Z" }, - { url = "https://files.pythonhosted.org/packages/d4/9a/01a332ebb0899ddb14d782f86ed66d080463e5387a8778029462d1902019/numpy-2.5.5-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:7e71ac4284c700afa654e2d15b1b174166710dca932f24045e5dc92001b5bda0", size = 10744599, upload-time = "2026-11-15T21:30:36.23Z" }, - { url = "https://files.pythonhosted.org/packages/03/bd/a1a721ab8da5632c811caf56b7735646a440eddbbf6e57817ae1a900c9c9/numpy-2.5.5-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:e0cf407a83118faf0463ade48a4533982f1737c7c58aac29e08855f7d9ad2977", size = 5508218, upload-time = "2026-11-15T21:30:38.357Z" }, - { url = "https://files.pythonhosted.org/packages/9c/63/eb5311935b313926d9127ec59632cc74bdf1fa815089fba4dbee9c6dd90c/numpy-2.5.5-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:ac910558645a4b006f70596b450712b8564730c1b2ac10291fcedd656d321ec0", size = 6794377, upload-time = "2026-11-15T21:30:40.026Z" }, - { url = "https://files.pythonhosted.org/packages/57/06/de83b859944409bb9058bc6110581a3d7fc1f54d6df1222744911d7f6b19/numpy-2.5.5-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ae2b8285d0b4eed24739c3ca9ec0fa424a0247489c01e1d5fe2815a599e11d33", size = 15278148, upload-time = "2026-11-15T21:30:41.819Z" }, - { url = "https://files.pythonhosted.org/packages/40/d6/68dd5a83914bbcaf32b3165993f7955979916708cb0156d1e28231e18803/numpy-2.5.5-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:824025655df929268bfe6b47ed91a00d14209a6f760847cf150be446829e1ce4", size = 15713899, upload-time = "2026-11-15T21:30:44.066Z" }, - { url = "https://files.pythonhosted.org/packages/1f/6e/a78932a1a838ce0d7d759cee2aca225054da8aa4151688edb5867b4af491/numpy-2.5.5-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:4302902ebf82d37f446664757be59db53587822c8b35f16368ca69fe66ec4315", size = 16501259, upload-time = "2026-11-15T21:30:46.469Z" }, - { url = "https://files.pythonhosted.org/packages/bc/08/f4da0ebfa6b684c18f1c300b279bd706f68f3828a2c9aaa1bca54c93a16f/numpy-2.5.5-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:3cedc2980b45794a6a2cfee9c8c3a80f04517082cc1d387e4cc895506c481696", size = 17077101, upload-time = "2026-11-15T21:30:48.916Z" }, - { url = "https://files.pythonhosted.org/packages/1b/81/0ccf314229450ec76363f3f6ec13d0ef54a24c53188787fc13136d6e52e6/numpy-2.5.5-cp313-cp313-win32.whl", hash = "sha256:10396f7c5ebc37d8f3cbdec44e3313912ccc2dc5841cc905de5de54ebbe8e2d3", size = 6141929, upload-time = "2026-11-15T21:30:51.528Z" }, - { url = "https://files.pythonhosted.org/packages/45/74/bb9161943fb65caf24e4bb04c788f5c7815e6cb78ac595e7f46781033c82/numpy-2.5.5-cp313-cp313-win_amd64.whl", hash = "sha256:e0608d1585557b68dcb6a70a41654f7536567960afad79d91752d2863b242b68", size = 12573354, upload-time = "2026-11-15T21:30:53.308Z" }, - { url = "https://files.pythonhosted.org/packages/ac/b0/792631d03588912e948c1249c03a78ca9af0c548670f8fd63ea014cbc14a/numpy-2.5.5-cp313-cp313-win_arm64.whl", hash = "sha256:e0b87886bb45621d9279dad4ab9f2d154b5db0b019d378c107b8f71527b06a4a", size = 10528296, upload-time = "2026-11-15T21:30:55.681Z" }, - { url = "https://files.pythonhosted.org/packages/6a/9a/f1493d897f51947644c45516ba63a67e66a7b06692f930fe37c58346cfbd/numpy-2.5.5-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:ab3ff087826c49d07953d0219eb00663ce5b1a0ef0a6b757e1ac041b09387428", size = 14754557, upload-time = "2026-11-15T21:30:58.008Z" }, - { url = "https://files.pythonhosted.org/packages/18/46/5d1c70b54257a56b3137d6fcc90c6db306f6177c02951eac7ebb42e7e1c7/numpy-2.5.5-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:7ca51125c76817de53473dae31ddc17213776472761bea9cca68a1a0037a4827", size = 10754769, upload-time = "2026-11-15T21:31:00.146Z" }, - { url = "https://files.pythonhosted.org/packages/4c/e1/016c3d9c9c6e5a457d615cfbcf6bcd01a4cabde82c639776be23365186c1/numpy-2.5.5-cp314-cp314-macosx_14_0_arm64.whl", hash = "sha256:229743571f901a082f031f511dc4f926b4b4a714075d98b1ff2af62d836365ac", size = 5518338, upload-time = "2026-11-15T21:31:02.38Z" }, - { url = "https://files.pythonhosted.org/packages/12/7f/f2369b42edb1a32a7f048c2126e6ab5b8bc527308ce9eb6e680ad9c3d2e7/numpy-2.5.5-cp314-cp314-macosx_14_0_x86_64.whl", hash = "sha256:1c24be6a82f5f257afc4dbefde4c3b56dee02146dfed2be2811940e79576b237", size = 6800110, upload-time = "2026-11-15T21:31:04.211Z" }, - { url = "https://files.pythonhosted.org/packages/26/5b/5cd4b88a64bb57ca6d3bd6a9e057db445544a2179a2ebf985660e0454648/numpy-2.5.5-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:cc6eb7502facce90349b4097a26821af224aaa0ab36e78304711cdb544352882", size = 15300777, upload-time = "2026-11-15T21:31:05.967Z" }, - { url = "https://files.pythonhosted.org/packages/a4/1f/fcdce1061fba2bfb2e9bfda01fbd8132d5f7522a4f7c8e2b2f629d54ee38/numpy-2.5.5-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c48960d420e90cf305cb1fde0d4e6082cc90512cda87a9acf0b6e04e91cf4abe", size = 15718051, upload-time = "2026-11-15T21:31:08.12Z" }, - { url = "https://files.pythonhosted.org/packages/5c/bd/9b7de1d0b747e3d1d24874b1cba374c8b0eab6c2034b785387677ecc4dba/numpy-2.5.5-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:5e202d5facc9c0681834018062466d0b3eabd48c540c3570f72905c97f641a90", size = 16518123, upload-time = "2026-11-15T21:31:10.714Z" }, - { url = "https://files.pythonhosted.org/packages/66/14/60c3fc30e63876e44212392eacd4ea1bd201c29835c99f42daa04c2501e4/numpy-2.5.5-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:e10e81d1db6c8fa507f61bebfd1ea383971dbc40c2005ed4db88fac5538b1ef6", size = 17079719, upload-time = "2026-11-15T21:31:13.245Z" }, - { url = "https://files.pythonhosted.org/packages/ac/b9/c0d3a63804a58823155ae221ce48afa4530e0cab8a33fcfb76a7b46b11ef/numpy-2.5.5-cp314-cp314-win32.whl", hash = "sha256:ef2a874cc70e2132c1c499268bdc34e211a715e481bc33c97b8a0190f2559295", size = 6193548, upload-time = "2026-11-15T21:31:15.602Z" }, - { url = "https://files.pythonhosted.org/packages/74/e2/494516771374b43060c1b778b371cba53d576abd3aee1275eecd73896e3b/numpy-2.5.5-cp314-cp314-win_amd64.whl", hash = "sha256:20145b11776d2f7570cd61351b156a51d3a341822282095baa819d87272bc710", size = 12710543, upload-time = "2026-11-15T21:31:17.461Z" }, - { url = "https://files.pythonhosted.org/packages/1b/e7/abe56b23f4dddf8277429d0efa442abac4c1940ec776c1b707c1e58435e8/numpy-2.5.5-cp314-cp314-win_arm64.whl", hash = "sha256:2abd39cfbb3d2af11e9bc8cc92b08cd089b0975fe9b1a30c8b7c740c67d397ce", size = 10812026, upload-time = "2026-11-15T21:31:19.692Z" }, - { url = "https://files.pythonhosted.org/packages/06/76/2974340b984ecd43bb4ee91c06a3fd59968330752c316d36fb8a23310ac1/numpy-2.5.5-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:f82a7567c590ff266f8c18fd527a0662edde074de11be256541a656e274f2b05", size = 10857031, upload-time = "2026-11-15T21:31:21.953Z" }, - { url = "https://files.pythonhosted.org/packages/38/d2/cc6d1f0f4c848f18e30d0f464a70598369336591920952f6aee440da4a2f/numpy-2.5.5-cp314-cp314t-macosx_14_0_arm64.whl", hash = "sha256:31e5be6cd4b896004cb9e416741612ade530fc9a04bceca5219cf66a675113b4", size = 5620763, upload-time = "2026-11-15T21:31:24.1Z" }, - { url = "https://files.pythonhosted.org/packages/c7/d0/2d014e5b68965530ebe46c0d2b07b1242210a029acba5800f53fcb4d4973/numpy-2.5.5-cp314-cp314t-macosx_14_0_x86_64.whl", hash = "sha256:b3d328eebe0056c634878c251131d73d74e0c4af317a3aea718816d6fa0bb963", size = 6897520, upload-time = "2026-11-15T21:31:25.976Z" }, - { url = "https://files.pythonhosted.org/packages/b1/ee/a0fb000c6a57602a7a2958f72a5d07837dd88cb9a158f1edb0a279126428/numpy-2.5.5-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e99bf8a3d54693f2063fa6c7d13955d460a9f543d9dbc80e69a92da288259b28", size = 15342131, upload-time = "2026-11-15T21:31:27.707Z" }, - { url = "https://files.pythonhosted.org/packages/93/43/85cfae380e4e2fe1d246c39a12c88c7a224e751604b6fa13236df3b86600/numpy-2.5.5-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:479e43c183049ec1a820eeb36549e493924f56b3e893a1d5865d0fff12abad47", size = 15751077, upload-time = "2026-11-15T21:31:29.851Z" }, - { url = "https://files.pythonhosted.org/packages/cd/41/5938f05404d2f4531409b658cfd578b0b653a87f22915759afa7f414b4f3/numpy-2.5.5-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:9f44875964889bd9088cf838d191b58c04088d10b4dc9b140e9da2431ecfbb60", size = 16569544, upload-time = "2026-11-15T21:31:32.017Z" }, - { url = "https://files.pythonhosted.org/packages/a0/b1/75f51d9e2fb970228bd7599d46f34eb0829070b4df8b293c43fdf1c81c44/numpy-2.5.5-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:2a9c502cdb9a3050ac1686774624cc278658b11f72e11b971a3a8542d6ded357", size = 17122494, upload-time = "2026-11-15T21:31:34.267Z" }, - { url = "https://files.pythonhosted.org/packages/71/1b/68f54066eb445a98e7c677863d1ece9667151f8d8565eea5860d8445fb72/numpy-2.5.5-cp314-cp314t-win32.whl", hash = "sha256:dec156cda7322bcb1479ca992794705fe226a911b0ffebe13bff97fa1f3be63c", size = 6350011, upload-time = "2026-11-15T21:31:36.491Z" }, - { url = "https://files.pythonhosted.org/packages/58/29/c57eca063b680b23c0ca8d07789b3011a9e962fd4994a656b11f7a21226e/numpy-2.5.5-cp314-cp314t-win_amd64.whl", hash = "sha256:84dfb1611993a3525b250c955b1e2ebab6ce0ed36e4ab4dd5746432dd362fb5d", size = 12909875, upload-time = "2026-11-15T21:31:38.311Z" }, - { url = "https://files.pythonhosted.org/packages/72/06/70b2717589eb8ba57bce789c0f1e477fc5869c720fa0ad444e31fb9aef55/numpy-2.5.5-cp314-cp314t-win_arm64.whl", hash = "sha256:567994389edd2963b643d63d826138402a63401176f1daf84dbb3204eb838b39", size = 10899621, upload-time = "2026-11-15T21:31:40.518Z" }, - { url = "https://files.pythonhosted.org/packages/9c/61/8578c9fdbfb59ba2c4ee633102666937ce4e66f8c3de8bc700573c856af5/numpy-2.5.5-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:ad0c8b963f9281f2eb118e283eb61964c716c8e344ed8e8c309b49c586d41ed1", size = 14752489, upload-time = "2026-11-15T21:31:42.902Z" }, - { url = "https://files.pythonhosted.org/packages/a7/ef/d0f38ea7ca697c03af3d687cb70d8ddc8414dcf430f8f7194ab7359d80f6/numpy-2.5.5-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:d7d9be35d50366fe5ac28188364154c9e1e22ad1b977a06c9465c0680c8eeefe", size = 10753050, upload-time = "2026-11-15T21:31:45.123Z" }, - { url = "https://files.pythonhosted.org/packages/84/b7/de9e6d1ffbc33cc7bcf452c7924a7953daaf06bde559b73ebef93b7f85c6/numpy-2.5.5-cp315-cp315-macosx_14_0_arm64.whl", hash = "sha256:d0c7c0dfabdcb7cde080b7c9ef301c7533e90110198b39965141a903c7dddcf8", size = 5516639, upload-time = "2026-11-15T21:31:47.537Z" }, - { url = "https://files.pythonhosted.org/packages/ac/ac/a95824882c5818a7e31893ebdab2944f5e65b4108bc8bed9e240e3c624be/numpy-2.5.5-cp315-cp315-macosx_14_0_x86_64.whl", hash = "sha256:b7dd0287b6cdd35a27d5678a56b1bc508ff206c2b78b30b4821dd5c3197b393a", size = 6797936, upload-time = "2026-11-15T21:31:49.2Z" }, - { url = "https://files.pythonhosted.org/packages/08/64/c39a7b41df0d433ff37fd4fdd6e32b3fa3b51a82110bbcd386d0e37f5da6/numpy-2.5.5-cp315-cp315-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a207eb88a18e30add597c366c1db7e79f48fc94084b8e7dbd0eefb95a645db12", size = 15294336, upload-time = "2026-11-15T21:31:50.908Z" }, - { url = "https://files.pythonhosted.org/packages/d0/ce/ef0ca1a7dbf657a68ec52ce150cc477a7cdd8d09c7ef77662cdecbca39e4/numpy-2.5.5-cp315-cp315-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9c3e1ac3cd5d3329f4d38709ff4c21f0621bbe8779c094d6de8ec8347246fcdc", size = 15713633, upload-time = "2026-11-15T21:31:53.261Z" }, - { url = "https://files.pythonhosted.org/packages/dd/08/023029d269a7adec40749ef98439af4260ee92bc203d8a7749cc4eee8183/numpy-2.5.5-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:095113ee2ceab6a9501b184eff5ea806973d3a63d74a8cbc15e4911e754da9c1", size = 16510376, upload-time = "2026-11-15T21:31:55.401Z" }, - { url = "https://files.pythonhosted.org/packages/9f/0b/38e65a5ff61b174df3a930898a3b31e94b24caaf4155c719d18417ad63b1/numpy-2.5.5-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:bea7de36bb304a850710c1dfbb35e7cdb9a005928106a3adfc6dc3a753469dec", size = 17078342, upload-time = "2026-11-15T21:31:57.714Z" }, - { url = "https://files.pythonhosted.org/packages/4d/3e/09a62f920e5869888387ba988eeba560057c1f718404cc737e5dbc07e81e/numpy-2.5.5-cp315-cp315-win32.whl", hash = "sha256:fd47c92e0d1e53f9498b1a30305072434fbae6b5a305cbcab514f959e9ce0fab", size = 6192918, upload-time = "2026-11-15T21:31:59.798Z" }, - { url = "https://files.pythonhosted.org/packages/5a/7e/a4c5b4b30dbab285b380130dbf780bccece06de020221491058ea2c66310/numpy-2.5.5-cp315-cp315-win_amd64.whl", hash = "sha256:ae9cfe4e985139c5f2db69d4310de7348bd0abc02cfdc06991c4419065f6fdca", size = 12710024, upload-time = "2026-11-15T21:32:01.352Z" }, - { url = "https://files.pythonhosted.org/packages/7d/57/bdec7de41e7442b9ea0ac938b7597f754d4d625d853551466e8a208e3e64/numpy-2.5.5-cp315-cp315-win_arm64.whl", hash = "sha256:08f1b9abf1707fa89c125aaa17e78389c063fb20ce37a141b47821e996f4a1db", size = 10814707, upload-time = "2026-11-15T21:32:03.326Z" }, - { url = "https://files.pythonhosted.org/packages/f0/e9/7f20d2144d4fbe2876d567a1ae1266cb62a67498af7d3006e2a0ba93deed/numpy-2.5.5-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:3d59ab8f6bfc4ffd29b0f558450e17922c1bc88459882e37726fbcd5834afbfd", size = 14845589, upload-time = "2026-11-15T21:32:05.476Z" }, - { url = "https://files.pythonhosted.org/packages/66/02/ded297ac4c917f7cf90254a50f888f992c028e2ed9a3efd82349c12d4904/numpy-2.5.5-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:bf6fa5a4d73b3a9699a57b8824d4863acde7241808a5305882222843537f02a2", size = 10851494, upload-time = "2026-11-15T21:32:07.944Z" }, - { url = "https://files.pythonhosted.org/packages/c6/ac/1ae013866575827dcec6239ca413b76c05652fa5ac405afd8d904940197c/numpy-2.5.5-cp315-cp315t-macosx_14_0_arm64.whl", hash = "sha256:d64daa409e9b1ac818b0c59e47b005f802e130c8281e40c6a2f7e70c43f75e0f", size = 5615246, upload-time = "2026-11-15T21:32:09.876Z" }, - { url = "https://files.pythonhosted.org/packages/f5/e2/2d89896606a325e584157fe669578ac1b22558e4b3e45e0cb554970e5a19/numpy-2.5.5-cp315-cp315t-macosx_14_0_x86_64.whl", hash = "sha256:ff5c1ab54a637c0adcdbb69ad10e5c4f1c4dedba69c0d1de383249b70c36908f", size = 6890873, upload-time = "2026-11-15T21:32:11.545Z" }, - { url = "https://files.pythonhosted.org/packages/4f/a0/de0484dbe0665ae69cbf9c2bb777c2fa4f402e03a102384c54fe54048d44/numpy-2.5.5-cp315-cp315t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:178cb1eaed819b2cb4e398c554b0776d1499f307e30cb58b9bae1921de35dae6", size = 15340077, upload-time = "2026-11-15T21:32:13.223Z" }, - { url = "https://files.pythonhosted.org/packages/39/d8/60a70cb61b8063e4dfc5b8b55f93c247cb7f1a36515d810e70ca94446396/numpy-2.5.5-cp315-cp315t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b6e30929e3443f46aa7be2749fb003fefbbad6b6a1e2168bf8850a55b657914a", size = 15752447, upload-time = "2026-11-15T21:32:15.629Z" }, - { url = "https://files.pythonhosted.org/packages/09/14/db7e8f5560a329a118bcea53da883f077bac5f00124799c5ac7e9eb1823e/numpy-2.5.5-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:2efb2ae4e0414b6bd636dde7235c158cd65dd52891ff64a320a4847a8ce7400f", size = 16566475, upload-time = "2026-11-15T21:32:17.974Z" }, - { url = "https://files.pythonhosted.org/packages/ec/33/060b8c68e2ed79fe50a20139f7f89fa2d9862f2d3e127fc353d8e6b2589c/numpy-2.5.5-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:32dce94d74bb4d5bb058d65b0d9dad7fa61d07ff9375fd7695d8aa7ea82ee73d", size = 17120613, upload-time = "2026-11-15T21:32:20.094Z" }, - { url = "https://files.pythonhosted.org/packages/99/3a/ab02c902cb380d0b950eccda4f0b67ac4f66ba490c98756d38adc4b3ccb5/numpy-2.5.5-cp315-cp315t-win32.whl", hash = "sha256:b5d08742de581c9eb61102768ccca125a2982913de399611b56981a07278de74", size = 6344124, upload-time = "2026-11-15T21:32:22.058Z" }, - { url = "https://files.pythonhosted.org/packages/fd/49/b04b1f12231e6fbcf26fd5e7949f629530e11c46a6fcd91923f61b017243/numpy-2.5.5-cp315-cp315t-win_amd64.whl", hash = "sha256:410eab02c6718cb42d06ccbb8604659f3522d2ce06ae70cacd5042092659f5af", size = 12898288, upload-time = "2026-11-15T21:32:23.871Z" }, - { url = "https://files.pythonhosted.org/packages/36/7b/935a5896b0bd441c6dd6da81f39bc5ebf8d5da891b7dcff768e1e1c088b5/numpy-2.5.5-cp315-cp315t-win_arm64.whl", hash = "sha256:b6ecbc1ff292c6799067d8064a4dd35cd25ba9d1a24aa41dd635d701691a49b5", size = 10891314, upload-time = "2026-11-15T21:32:26.357Z" }, -] - -[[package]] -name = "packaging" -version = "26.4" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/c3/75/ffb1dc0ed12352139fb4ca0e3fde4325a23e3d0f3f40efe89717bc4f557b/packaging-26.4.tar.gz", hash = "sha256:c4b671c41ddb9bf26e543c37723610d28fb6bf7affc4da17cf048d419d2c062a", size = 355877, upload-time = "2026-11-23T21:44:11.152Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/ba/7b/5504f91c9c2733f693d7759e50ede5d27119d4da7e5836c46d3b5ff81d56/packaging-26.4-py3-none-any.whl", hash = "sha256:81383611a09c1bc0b08b76e0fd5829d7c6824c65b27a6aee339da133f4233ea2", size = 140049, upload-time = "2026-11-23T21:44:09.531Z" }, -] - -[[package]] -name = "parso" -version = "0.8.7" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/30/4b/90c937815137d43ce71ba043cd3566221e9df6b9c805f24b5d138c9d40a7/parso-0.8.7.tar.gz", hash = "sha256:eaaac4c9fdd5e9e8852dc778d2d7405897ec510f2a298071453e5e3a07914bb1", size = 401824, upload-time = "2026-05-01T23:13:02.138Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/99/5d/8268b644392ee874ee82a635cd0df1773de230bde356c38de28e298392cc/parso-0.8.7-py2.py3-none-any.whl", hash = "sha256:a8926eb2a1b915486941fdbd31e86a4baf88fe8c210f25f2f35ecec5b574ca1c", size = 107025, upload-time = "2026-05-01T23:12:58.867Z" }, -] - -[[package]] -name = "pluggy" -version = "1.7.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/bf/db/7fc19e6f2dc92a966727031389fc2e08b558f0f25eb7403c1119ad4713cd/pluggy-1.7.0.tar.gz", hash = "sha256:d1eaa46ebb595891b860ab086b4d09c8588af65ebd4361b8e8f4bb8920b90ba8", size = 123304, upload-time = "2026-10-15T09:50:58.343Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/40/9e/2b38731e0fc536806f16490e1a12d7f0dc2a1235aa8cc07bcc75416a7daa/pluggy-1.7.0-py3-none-any.whl", hash = "sha256:7dd7b0d8832ba3cb632c306926ded123429211b83641b35dc5c41ad2d34f9bec", size = 27082, upload-time = "2026-10-15T09:50:56.808Z" }, -] - -[[package]] -name = "polars" -version = "1.44.2" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "polars-runtime-32" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/a4/15/e8541eefc22fbc7ca89bcb5112298a153729f73cfbc0cf6a668e509f975c/polars-1.44.2.tar.gz", hash = "sha256:86c8e26b6c2de8c8d344bb910b74dfc47b118ac3fe0f19b44909467990a0b281", size = 766272, upload-time = "2026-09-09T07:42:08.859Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/51/6d/3014112c7f717d1253223faa13b6db3ac3a64ed00ab2a3bc1b942bc9cdd4/polars-1.44.2-py3-none-any.whl", hash = "sha256:1bb331f17a40d9d931101533dcd33637b66edc61eb377b07020dac16a0f0377b", size = 865768, upload-time = "2026-09-09T07:40:12.053Z" }, -] - -[[package]] -name = "polars-runtime-32" -version = "1.44.2" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/d4/a1/a7eace6587b56f22cf2a21ab4d5e695db372dc23fd96accb68b1ec12660b/polars_runtime_32-1.44.2.tar.gz", hash = "sha256:b84842f7d621aaca7a52e165e19a24f89db45f8aa13744941430218419a14a67", size = 3172205, upload-time = "2026-09-09T07:42:10.851Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/99/5b/a5215f82c3dd443dc5d6911b0d3e937f97056e0ef7753f7e123422481a18/polars_runtime_32-1.44.2-cp310-abi3-macosx_10_12_x86_64.whl", hash = "sha256:1fd536720668ba203a16a20b08cd6b23057e407a0279cf36b2f35f879d6e3208", size = 48334014, upload-time = "2026-09-09T07:40:16.43Z" }, - { url = "https://files.pythonhosted.org/packages/c2/e0/f3dc93fce4b4e99370db6a89001a1b8d3c606e3560d0d91dda809d6c6324/polars_runtime_32-1.44.2-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:e0fd43720c8222ae39919c8ff891636d53b352706087120e62f83544dd3ff782", size = 43331099, upload-time = "2026-09-09T07:40:21.029Z" }, - { url = "https://files.pythonhosted.org/packages/4e/4f/076626ce93ddd622203c4b27be2a96d034cf5b24110c52e96e6029f0ea33/polars_runtime_32-1.44.2-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:bbf9b45040291dc1c6c588c837019c33557bde25ec536562a9cca9e1f6dfcc45", size = 46590853, upload-time = "2026-09-09T07:40:24.934Z" }, - { url = "https://files.pythonhosted.org/packages/e9/24/ed9982657c446dd5491b089370eea196725673570cfc61f7225a9fdd7ef0/polars_runtime_32-1.44.2-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a1bafb441e99199a62c63bf1bbdc0ea09ee9776dbac2bf31452b5000fb1df2f7", size = 49912258, upload-time = "2026-09-09T07:40:29.238Z" }, - { url = "https://files.pythonhosted.org/packages/71/42/5490ab360aa2406119825ad82203a5e2ff27a3a5893ca8e0b93c053a59a3/polars_runtime_32-1.44.2-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:10c0c695a418407617b5159db7d9a21074a733e4c6d61275b6762f25cb31ca99", size = 46737310, upload-time = "2026-09-09T07:40:33.143Z" }, - { url = "https://files.pythonhosted.org/packages/06/8f/d741afb1dcd1848161189e017d27972e7e78556d8dce66b94d4235093706/polars_runtime_32-1.44.2-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:c4a09fb14aad711526346efc0cb2015c2fd0555ce4118b6524e5debbaea65ff5", size = 49887654, upload-time = "2026-09-09T07:40:37.455Z" }, - { url = "https://files.pythonhosted.org/packages/ba/e7/c61c1c7eea37705920fe7c1302d1dd80d1165db2b928f0da3eae6d1ebb75/polars_runtime_32-1.44.2-cp310-abi3-win_amd64.whl", hash = "sha256:8598e7a20efba70bb74978c7df7af7c606ff4d79b9b48fdd808250b189bc9a13", size = 51297967, upload-time = "2026-09-09T07:40:41.993Z" }, - { url = "https://files.pythonhosted.org/packages/e7/a0/d0dd0d2ec95fa328dd47055905fae53ba3cd79f11c8973326ebe75a49e4c/polars_runtime_32-1.44.2-cp310-abi3-win_arm64.whl", hash = "sha256:d51040d3ab40157f6db3c62be59cab5b80fb3c8d158924769c4982a1c8eef730", size = 44303345, upload-time = "2026-09-09T07:40:47.081Z" }, -] - -[[package]] -name = "psutil" -version = "7.2.2" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/aa/c6/d1ddf4abb55e93cebc4f2ed8b5d6dbad109ecb8d63748dd2b20ab5e57ebe/psutil-7.2.2.tar.gz", hash = "sha256:0746f5f8d406af344fd547f1c8daa5f5c33dbc293bb8d6a16d80b4bb88f59372", size = 493740, upload-time = "2026-01-28T18:14:54.428Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/51/08/510cbdb69c25a96f4ae523f733cdc963ae654904e8db864c07585ef99875/psutil-7.2.2-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:2edccc433cbfa046b980b0df0171cd25bcaeb3a68fe9022db0979e7aa74a826b", size = 130595, upload-time = "2026-01-28T18:14:57.293Z" }, - { url = "https://files.pythonhosted.org/packages/d6/f5/97baea3fe7a5a9af7436301f85490905379b1c6f2dd51fe3ecf24b4c5fbf/psutil-7.2.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:e78c8603dcd9a04c7364f1a3e670cea95d51ee865e4efb3556a3a63adef958ea", size = 131082, upload-time = "2026-01-28T18:14:59.732Z" }, - { url = "https://files.pythonhosted.org/packages/37/d6/246513fbf9fa174af531f28412297dd05241d97a75911ac8febefa1a53c6/psutil-7.2.2-cp313-cp313t-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1a571f2330c966c62aeda00dd24620425d4b0cc86881c89861fbc04549e5dc63", size = 181476, upload-time = "2026-01-28T18:15:01.884Z" }, - { url = "https://files.pythonhosted.org/packages/b8/b5/9182c9af3836cca61696dabe4fd1304e17bc56cb62f17439e1154f225dd3/psutil-7.2.2-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:917e891983ca3c1887b4ef36447b1e0873e70c933afc831c6b6da078ba474312", size = 184062, upload-time = "2026-01-28T18:15:04.436Z" }, - { url = "https://files.pythonhosted.org/packages/16/ba/0756dca669f5a9300d0cbcbfae9a4c30e446dfc7440ffe43ded5724bfd93/psutil-7.2.2-cp313-cp313t-win_amd64.whl", hash = "sha256:ab486563df44c17f5173621c7b198955bd6b613fb87c71c161f827d3fb149a9b", size = 139893, upload-time = "2026-01-28T18:15:06.378Z" }, - { url = "https://files.pythonhosted.org/packages/1c/61/8fa0e26f33623b49949346de05ec1ddaad02ed8ba64af45f40a147dbfa97/psutil-7.2.2-cp313-cp313t-win_arm64.whl", hash = "sha256:ae0aefdd8796a7737eccea863f80f81e468a1e4cf14d926bd9b6f5f2d5f90ca9", size = 135589, upload-time = "2026-01-28T18:15:08.03Z" }, - { url = "https://files.pythonhosted.org/packages/81/69/ef179ab5ca24f32acc1dac0c247fd6a13b501fd5534dbae0e05a1c48b66d/psutil-7.2.2-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:eed63d3b4d62449571547b60578c5b2c4bcccc5387148db46e0c2313dad0ee00", size = 130664, upload-time = "2026-01-28T18:15:09.469Z" }, - { url = "https://files.pythonhosted.org/packages/7b/64/665248b557a236d3fa9efc378d60d95ef56dd0a490c2cd37dafc7660d4a9/psutil-7.2.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:7b6d09433a10592ce39b13d7be5a54fbac1d1228ed29abc880fb23df7cb694c9", size = 131087, upload-time = "2026-01-28T18:15:11.724Z" }, - { url = "https://files.pythonhosted.org/packages/d5/2e/e6782744700d6759ebce3043dcfa661fb61e2fb752b91cdeae9af12c2178/psutil-7.2.2-cp314-cp314t-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1fa4ecf83bcdf6e6c8f4449aff98eefb5d0604bf88cb883d7da3d8d2d909546a", size = 182383, upload-time = "2026-01-28T18:15:13.445Z" }, - { url = "https://files.pythonhosted.org/packages/57/49/0a41cefd10cb7505cdc04dab3eacf24c0c2cb158a998b8c7b1d27ee2c1f5/psutil-7.2.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e452c464a02e7dc7822a05d25db4cde564444a67e58539a00f929c51eddda0cf", size = 185210, upload-time = "2026-01-28T18:15:16.002Z" }, - { url = "https://files.pythonhosted.org/packages/dd/2c/ff9bfb544f283ba5f83ba725a3c5fec6d6b10b8f27ac1dc641c473dc390d/psutil-7.2.2-cp314-cp314t-win_amd64.whl", hash = "sha256:c7663d4e37f13e884d13994247449e9f8f574bc4655d509c3b95e9ec9e2b9dc1", size = 141228, upload-time = "2026-01-28T18:15:18.385Z" }, - { url = "https://files.pythonhosted.org/packages/f2/fc/f8d9c31db14fcec13748d373e668bc3bed94d9077dbc17fb0eebc073233c/psutil-7.2.2-cp314-cp314t-win_arm64.whl", hash = "sha256:11fe5a4f613759764e79c65cf11ebdf26e33d6dd34336f8a337aa2996d71c841", size = 136284, upload-time = "2026-01-28T18:15:19.912Z" }, - { url = "https://files.pythonhosted.org/packages/e7/36/5ee6e05c9bd427237b11b3937ad82bb8ad2752d72c6969314590dd0c2f6e/psutil-7.2.2-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:ed0cace939114f62738d808fdcecd4c869222507e266e574799e9c0faa17d486", size = 129090, upload-time = "2026-01-28T18:15:22.168Z" }, - { url = "https://files.pythonhosted.org/packages/80/c4/f5af4c1ca8c1eeb2e92ccca14ce8effdeec651d5ab6053c589b074eda6e1/psutil-7.2.2-cp36-abi3-macosx_11_0_arm64.whl", hash = "sha256:1a7b04c10f32cc88ab39cbf606e117fd74721c831c98a27dc04578deb0c16979", size = 129859, upload-time = "2026-01-28T18:15:23.795Z" }, - { url = "https://files.pythonhosted.org/packages/b5/70/5d8df3b09e25bce090399cf48e452d25c935ab72dad19406c77f4e828045/psutil-7.2.2-cp36-abi3-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:076a2d2f923fd4821644f5ba89f059523da90dc9014e85f8e45a5774ca5bc6f9", size = 155560, upload-time = "2026-01-28T18:15:25.976Z" }, - { url = "https://files.pythonhosted.org/packages/63/65/37648c0c158dc222aba51c089eb3bdfa238e621674dc42d48706e639204f/psutil-7.2.2-cp36-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b0726cecd84f9474419d67252add4ac0cd9811b04d61123054b9fb6f57df6e9e", size = 156997, upload-time = "2026-01-28T18:15:27.794Z" }, - { url = "https://files.pythonhosted.org/packages/8e/13/125093eadae863ce03c6ffdbae9929430d116a246ef69866dad94da3bfbc/psutil-7.2.2-cp36-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:fd04ef36b4a6d599bbdb225dd1d3f51e00105f6d48a28f006da7f9822f2606d8", size = 148972, upload-time = "2026-01-28T18:15:29.342Z" }, - { url = "https://files.pythonhosted.org/packages/04/78/0acd37ca84ce3ddffaa92ef0f571e073faa6d8ff1f0559ab1272188ea2be/psutil-7.2.2-cp36-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:b58fabe35e80b264a4e3bb23e6b96f9e45a3df7fb7eed419ac0e5947c61e47cc", size = 148266, upload-time = "2026-01-28T18:15:31.597Z" }, - { url = "https://files.pythonhosted.org/packages/b4/90/e2159492b5426be0c1fef7acba807a03511f97c5f86b3caeda6ad92351a7/psutil-7.2.2-cp37-abi3-win_amd64.whl", hash = "sha256:eb7e81434c8d223ec4a219b5fc1c47d0417b12be7ea866e24fb5ad6e84b3d988", size = 137737, upload-time = "2026-01-28T18:15:33.849Z" }, - { url = "https://files.pythonhosted.org/packages/8c/c7/7bb2e321574b10df20cbde462a94e2b71d05f9bbda251ef27d104668306a/psutil-7.2.2-cp37-abi3-win_arm64.whl", hash = "sha256:8c233660f575a5a89e6d4cb65d9f938126312bca76d8fe087b947b3a1aaac9ee", size = 134617, upload-time = "2026-01-28T18:15:36.514Z" }, -] - -[[package]] -name = "psycopg" -version = "3.3.9" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "typing-extensions", marker = "python_full_version < '3.13'" }, - { name = "tzdata", marker = "sys_platform == 'win32'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/b4/74/ff710399dfa9fe9b546c2f5a05ea2f9b9d1dc2145c0b59e53a3fa2013679/psycopg-3.3.9.tar.gz", hash = "sha256:87c1d85c3e0e88e811d3c0b3808f947bd967c6faf34af6cd86fd021f77793d6c", size = 171122, upload-time = "2026-11-12T09:04:06.548Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/52/5d/a7957d1b5484f8e5094a15b1a400929324f978b670bd4a95179e1a012ec2/psycopg-3.3.9-py3-none-any.whl", hash = "sha256:d2d7d04a1ce6dab4f5b27316bea3b52585cafa2f2d631e5b09dd69823f5c26f6", size = 219041, upload-time = "2026-11-12T08:58:18.454Z" }, -] - -[package.optional-dependencies] -binary = [ - { name = "psycopg-binary", marker = "implementation_name != 'pypy'" }, -] - -[[package]] -name = "psycopg-binary" -version = "3.3.9" -source = { registry = "https://pypi.org/simple" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/1a/15/35cd93a0bbbf80b2f47fdc572736a1a050b8eedfb463b7098ca4a144c813/psycopg_binary-3.3.9-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:96ef179795a800f7b8dc7c4abd14ab322cc4986726cfa6dabff552c3e16e446d", size = 4069799, upload-time = "2026-11-12T08:59:14.393Z" }, - { url = "https://files.pythonhosted.org/packages/a6/9d/7f2c869e905a1476c2d2a75b5b1f5c92b86fe54de398ee2e09dfeb4cea4c/psycopg_binary-3.3.9-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:4c064e4d9f5c6a59b975c6d7f6e2f03cab164359cfd3a592817db97f8b0f463a", size = 4118537, upload-time = "2026-11-12T08:59:22.302Z" }, - { url = "https://files.pythonhosted.org/packages/fd/d3/89e0c378206874afa1af7ac4b7ec01ed7c7d37b38124529e4aad9621f57c/psycopg_binary-3.3.9-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:79071f66f484d682b420f08386e835060b2338f23236d918a01a60281a807d3b", size = 4250697, upload-time = "2026-11-12T08:59:26.914Z" }, - { url = "https://files.pythonhosted.org/packages/2e/1d/76ec39728ef21f21b43a29987790509431393ee69adf5639978363390ca1/psycopg_binary-3.3.9-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:0953c1b94c73f97efce5b8fb1dad85cf5e4085b94902e439e27e6805ebc8be99", size = 3944426, upload-time = "2026-11-12T08:59:31.598Z" }, - { url = "https://files.pythonhosted.org/packages/d9/34/4e9e479697f249ad6ab8489b8ca06cc3e578306c4596a278df2368627934/psycopg_binary-3.3.9-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9f6f4108a2e1d55303dfbb41d0f3b16a0aac95232a24ac8eb3df03f56fcb83aa", size = 4159271, upload-time = "2026-11-12T08:59:35.996Z" }, - { url = "https://files.pythonhosted.org/packages/58/ad/c69d9aa809f0e7fbf892a8b993e1fd2774abfc7852102c931ff8cf0700fb/psycopg_binary-3.3.9-cp311-cp311-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:8fee8337812241ce26c6e16f73b2a20e94db643312c6901c00b57a0b2e203e6d", size = 3583287, upload-time = "2026-11-12T08:59:40.153Z" }, - { url = "https://files.pythonhosted.org/packages/4a/c2/689aa5cccb21c623f7e0506470dba9ed222b60b813c716861db495a551d2/psycopg_binary-3.3.9-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:c3dc32af4bed2339bac8110a2c5d65e23fe25d922e075f191e41f2b3a61adc0f", size = 3925250, upload-time = "2026-11-12T08:59:43.973Z" }, - { url = "https://files.pythonhosted.org/packages/bf/84/6825290efeea434c0d485fb07694f576626a565c0fb6b1d4ed7a5e1e63f4/psycopg_binary-3.3.9-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:5bd2e0315dd43b8bb28f4c124f91d9a8eb866d04bd66899ae5d82086f36ac0c2", size = 3620091, upload-time = "2026-11-12T08:59:47.729Z" }, - { url = "https://files.pythonhosted.org/packages/1a/7b/8e2cee1e7034bec74916ade25809d4ba3776d8b14ecead57af5bd327a856/psycopg_binary-3.3.9-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:87e5b145e1363aa6bad904c430e18c3434e7b61565197d71d42157e3084fd9b0", size = 3346805, upload-time = "2026-11-12T08:59:52.153Z" }, - { url = "https://files.pythonhosted.org/packages/5b/f1/e996e9aa6e88e149b720472a934d366765d9477c3e8520a1243d1ce4fc0b/psycopg_binary-3.3.9-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:b2582957ef09a0315fab23cab6ff6445ad73b850bd951a936abec58cb2f3f86e", size = 3651228, upload-time = "2026-11-12T08:59:57.546Z" }, - { url = "https://files.pythonhosted.org/packages/73/08/dc42ab0f86083ce04509464c2cdd8cf24568718ff90debf322dd7d551c75/psycopg_binary-3.3.9-cp311-cp311-win_amd64.whl", hash = "sha256:75dc9ebbad779969174e59422c71444c2bd8d0362d5758a7b6f500eff11aa4ac", size = 2925715, upload-time = "2026-11-12T09:00:03.157Z" }, - { url = "https://files.pythonhosted.org/packages/6e/0c/7fc92c3135ce195bb86052d18f9ef5f64b1592d8f3a5f1d90e9b49c72448/psycopg_binary-3.3.9-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:fcdb76adaab57fdd5b789b13b20699bffaf17000a4bbc0527327581cfdd55e3d", size = 4048935, upload-time = "2026-11-12T09:00:08.958Z" }, - { url = "https://files.pythonhosted.org/packages/f0/a4/e62d11a85fc1a3a49f95b308bd5e2299dfc11125ef87043f6dfc29297d0c/psycopg_binary-3.3.9-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:08689018e9169ca8e6769f5b3f2ce748442bda95b5f1ec260995a8ff63e6d6a4", size = 4111565, upload-time = "2026-11-12T09:00:14.788Z" }, - { url = "https://files.pythonhosted.org/packages/4a/89/d9ca02dfe30a6dc51e7796617dd69cc5c2e66bcc89ced44df4f4a3b5e402/psycopg_binary-3.3.9-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:e7e2e3543ac17cf5bb3eaf738606fc52bcedf993500b9fc8c55a4475a3731ef9", size = 4207484, upload-time = "2026-11-12T09:00:23.781Z" }, - { url = "https://files.pythonhosted.org/packages/4d/aa/f1b6e1cd71aeafa78ab33875adf0339818fe014cde197a1c0c7c419dd0b0/psycopg_binary-3.3.9-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a99f0b9a19ed7a56bf5d6776456b8f15f5364db8853b0f5d184db394a45c391d", size = 3913036, upload-time = "2026-11-12T09:00:30.144Z" }, - { url = "https://files.pythonhosted.org/packages/ae/fe/9e967bfacdda0fef48fee1d869b13de016d82d846a805745b0985ac94a5b/psycopg_binary-3.3.9-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b081348d8992af26e9b252f04876c286428418a6b7845d8d4caae2044b259668", size = 4132657, upload-time = "2026-11-12T09:00:34.401Z" }, - { url = "https://files.pythonhosted.org/packages/cb/b3/c6a9f0bca0fdb06cf408235b698710f400a1d6376ab77e5fec887115aaa5/psycopg_binary-3.3.9-cp312-cp312-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:66b20619acbd434e4e46d734a915768a1192db09754c2ad041d391d72f30e5eb", size = 3545187, upload-time = "2026-11-12T09:00:38.595Z" }, - { url = "https://files.pythonhosted.org/packages/61/24/0443e50d382d3f6dcc03530560e02a02646af6bd8fcbd5a60add68c80208/psycopg_binary-3.3.9-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:b7c4b2039d82f635311e41e7d392ff1bddd94a2447f9668c6531489cc86a8ce2", size = 3897551, upload-time = "2026-11-12T09:00:43.769Z" }, - { url = "https://files.pythonhosted.org/packages/c5/18/e576c5f50f4751ad9f1770134ad57ef216d00e5d79caa1c5b091f41275dc/psycopg_binary-3.3.9-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:3efe96cd98081b755ee3b0a50f2d35d9af55cb1ba462440a41048b9e7c6b9caa", size = 3577016, upload-time = "2026-11-12T09:00:49.375Z" }, - { url = "https://files.pythonhosted.org/packages/cb/c6/434e01b19af141540147427675c116b2205ea58e3ec99e26431edf2d0714/psycopg_binary-3.3.9-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:80ce081d2512ced75f1ca08ff80257a1288a3555079c5fa622164a0f9ed6533a", size = 3305336, upload-time = "2026-11-12T09:00:55.531Z" }, - { url = "https://files.pythonhosted.org/packages/eb/84/0ea715e106cc80a89aca36e34dd6685fa1ee75da9546d41a1d87356efb9f/psycopg_binary-3.3.9-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:30a95cb2b00b94b4ec4fd5d41de047598c60e0db26fd43bd9154152cc380b282", size = 3620366, upload-time = "2026-11-12T09:01:01.033Z" }, - { url = "https://files.pythonhosted.org/packages/81/a7/afe5fe01b4100454ea6543ac84c8b38a3713d6f27790253798ba50f2ef2a/psycopg_binary-3.3.9-cp312-cp312-win_amd64.whl", hash = "sha256:1ce1a6f04211626ca1a3deadee560235e8686e3888fb18f78d2be3e83bceabc4", size = 2907832, upload-time = "2026-11-12T09:01:04.735Z" }, - { url = "https://files.pythonhosted.org/packages/42/9c/68d2172aa2993b129edba644edbdbc7834ddb88f7d43dc1fac2626f59a84/psycopg_binary-3.3.9-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:b98ecad106cd48998517e03aaee56f9d88f8857e043b8e3dbc2aa7facd475db6", size = 4053851, upload-time = "2026-11-12T09:01:08.857Z" }, - { url = "https://files.pythonhosted.org/packages/52/82/f472e2df0b0f7b816efdd18dde10e8a980df74feb5e34564cb3d8aeeef67/psycopg_binary-3.3.9-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:e835af41e74176041d2290b167af92b74793b916ca3413598c39b535dd3674a5", size = 4114709, upload-time = "2026-11-12T09:01:14.257Z" }, - { url = "https://files.pythonhosted.org/packages/eb/0d/71abff2f3219cf61c790e45981ba6e4ff9b4c2f96855f5f89f7da41bf6fd/psycopg_binary-3.3.9-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:4b44a09bb7c92666aec8a00d5d390ff6f4e573d345ccde0f71b45597511449fb", size = 4210297, upload-time = "2026-11-12T09:01:20.266Z" }, - { url = "https://files.pythonhosted.org/packages/fc/b4/713b67741a31c3d93028276b2b634157fdfcf00417023f45bb4410de0ab9/psycopg_binary-3.3.9-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:180e4a99904d7a77f826fbb6dd16834bb3313675d8a6f055e39742fda00c33dc", size = 3915163, upload-time = "2026-11-12T09:01:28.02Z" }, - { url = "https://files.pythonhosted.org/packages/19/22/d67af2a2dd96603b381404d9ae657e3877c763a60cc7c5bf319162652334/psycopg_binary-3.3.9-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:366e2021a785afed9154f83f64793f662348a9ef244fef9779175c0906e8aacc", size = 4132455, upload-time = "2026-11-12T09:01:35.872Z" }, - { url = "https://files.pythonhosted.org/packages/60/c8/662b59cc3e9fb581af9f20d269035ce2a2020732584de05c4e17a3edf0ac/psycopg_binary-3.3.9-cp313-cp313-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:13bfe814718c8a1b9b656c0d754962e0027cc3e43630661825fe197babc99320", size = 3548290, upload-time = "2026-11-12T09:01:41.316Z" }, - { url = "https://files.pythonhosted.org/packages/ec/97/9d1d54a21e881a268a5bc00cdd12a0a87534de07d123d18887ee0ff7f3f6/psycopg_binary-3.3.9-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a0ed63b05046bc40d76109d95c757d3eac38488b17c68ae9e8160040d0ed0f89", size = 3898785, upload-time = "2026-11-12T09:01:45.019Z" }, - { url = "https://files.pythonhosted.org/packages/0e/85/8d7f1fe6161cb663374a06e2d16c408f6353e62e58bb48ff761bd95a028a/psycopg_binary-3.3.9-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:f85821eba1f8c27e080eba955eb9dddaa638f61e363b4f3b2266bd9ec4ff73bd", size = 3577036, upload-time = "2026-11-12T09:01:48.698Z" }, - { url = "https://files.pythonhosted.org/packages/50/bb/4482876d230fa2c330e28d22a135babad7a0f9b3446b54a153a9ffaf25b5/psycopg_binary-3.3.9-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:eb74f5299501f83f3ad7b8e99405ca451b77c74d65767bac7f46d22c4e9411ae", size = 3309862, upload-time = "2026-11-12T09:01:52.208Z" }, - { url = "https://files.pythonhosted.org/packages/4c/1b/f49175ca5bef792c4e3820690b8e81cdf7699f3eee3a7f388c434c04b808/psycopg_binary-3.3.9-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:14666a85aa330058929e4abedd940f754f0e5589efae6366d95c513288856fb5", size = 3621566, upload-time = "2026-11-12T09:01:56.531Z" }, - { url = "https://files.pythonhosted.org/packages/9e/97/06d96b1e9c1b2369cd9d7ada4c70f0649df7c542b8c5da5bb01bacf05eaf/psycopg_binary-3.3.9-cp313-cp313-win_amd64.whl", hash = "sha256:417c3fe0ac2079a82a8c72ba214a65c66c22036a5d2d8c24c77c5708a58938b9", size = 2907276, upload-time = "2026-11-12T09:02:01.257Z" }, - { url = "https://files.pythonhosted.org/packages/25/ef/2369abcb3d7789117bca1f028eeb69e2798237f5b6e5a7b4172eb113a380/psycopg_binary-3.3.9-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:6bc7e10d05f236f53b184d9592e8f3d22587bc2e7b964fea9f5d0de2b1142fe5", size = 4055684, upload-time = "2026-11-12T09:02:06.492Z" }, - { url = "https://files.pythonhosted.org/packages/d3/22/3a2f68ce0e414a6e76f09987f447f155e2ef8b79d13ea6cf4aaa74c941a3/psycopg_binary-3.3.9-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:e853041acf10de2dcb595167138dc9fc27de293d67caa1d80ed282ec27a28e87", size = 4118288, upload-time = "2026-11-12T09:02:10.849Z" }, - { url = "https://files.pythonhosted.org/packages/af/1f/7e9e1f8c00e98fcf9d8be2d4d2120106100db5886cfce807c5d01523d64a/psycopg_binary-3.3.9-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:c25fa1ee28f8fd73aecc5e8612ab9e5700682e8e23f9422437a1617016029934", size = 4215854, upload-time = "2026-11-12T09:02:15.024Z" }, - { url = "https://files.pythonhosted.org/packages/2a/d5/ba4839c38d9d35daa815cb18dfe462582f783ba83b9d932692bb903fba01/psycopg_binary-3.3.9-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:4992acd5a7479013d52615b8c23fdce9bc22f3cacbfb1007fa474e6b5ebe94c7", size = 3918359, upload-time = "2026-11-12T09:02:19.433Z" }, - { url = "https://files.pythonhosted.org/packages/f1/47/243682e14cac97cb7500625a2ca3a53195ddc39e4bb81a59f289286f23d2/psycopg_binary-3.3.9-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:eed1ac135d652e4454777afb4e4bb52cf88520bbfa2f30ae83066cd4df656697", size = 4140188, upload-time = "2026-11-12T09:02:25.013Z" }, - { url = "https://files.pythonhosted.org/packages/c5/4c/5b1a99f245c3a22bd3cca9760f0595e0bd26b4a7c0d5f36fe0288ddc3b2e/psycopg_binary-3.3.9-cp314-cp314-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:85b3892dbc4f5fb21880f82e3aed7329be6bee39fb58a0f059cbb1d0a382e98b", size = 3552025, upload-time = "2026-11-12T09:02:32.354Z" }, - { url = "https://files.pythonhosted.org/packages/c6/cc/32d34dd14d7215b987cb76ce72035963b85a9b4e75d3e3e78104abf7c831/psycopg_binary-3.3.9-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:4ba688a9402e3cc9d425e6ad20f97b96698f59f867279c265c1d0ca6df9dad57", size = 3907596, upload-time = "2026-11-12T09:02:38.276Z" }, - { url = "https://files.pythonhosted.org/packages/79/c4/ac9f35d331f987d83e5534f35d28f76aeac101eebaddc5c0c9f252a2d21f/psycopg_binary-3.3.9-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:300bd86d4b81d297e204a8ba223f54ec09a4b54fd069c32a74bf75b42860703f", size = 3587344, upload-time = "2026-11-12T09:02:41.864Z" }, - { url = "https://files.pythonhosted.org/packages/54/04/e91fedeeab7fe94df2364ad324c0de0e6ebd54b24f3dff396e24ffba9655/psycopg_binary-3.3.9-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:e01a4f4fd0e4beee23af30517123bdde838d53c3ac0ae594da019e36b3adabda", size = 3314235, upload-time = "2026-11-12T09:02:47.199Z" }, - { url = "https://files.pythonhosted.org/packages/da/fc/e522309105d4c1b1f8bfa7e887355a414c1c84e94e32e532a6595c5ded13/psycopg_binary-3.3.9-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5117a4745b3b850872140d3a66a8d83c55801916ae6e3cf502af0a794f64f9b7", size = 3626367, upload-time = "2026-11-12T09:02:52.842Z" }, - { url = "https://files.pythonhosted.org/packages/4e/50/643d5f523fa77a3b808e982716e7aa76da788218e40942721939c5e08c11/psycopg_binary-3.3.9-cp314-cp314-win_amd64.whl", hash = "sha256:109c5df5b0e5117e01a42d3b56a2f4ccd5431bd54d25efdfc89df095ac9f9605", size = 3009572, upload-time = "2026-11-12T09:02:58.474Z" }, - { url = "https://files.pythonhosted.org/packages/c1/81/06d36165c60e32d3909bf9ad036f4120284872ad00234ac384be20fcef5f/psycopg_binary-3.3.9-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:0b513957b283d181ed04961567b9893cae79309e23655d54c91cb8781ad81fc5", size = 4054822, upload-time = "2026-11-12T09:03:04.391Z" }, - { url = "https://files.pythonhosted.org/packages/4c/70/6c9eb0d0f1e124dbeba86dbd4c06b95bf15e7dfe60c0a3b91f6c7b45e237/psycopg_binary-3.3.9-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:a9ee20e3b314c1f36ec13093f1ea46161704a7304a6c334396318d36416bd330", size = 4117160, upload-time = "2026-11-12T09:03:10.7Z" }, - { url = "https://files.pythonhosted.org/packages/7f/84/99ecb47d6ef0752792b60b1fffd3739fae0605f4786aa9827646d1623f4b/psycopg_binary-3.3.9-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:0793764fac48b5f0bf4d7154e38c60def4fa0cce16caa60b737f770bd29016ac", size = 4214359, upload-time = "2026-11-12T09:03:17.69Z" }, - { url = "https://files.pythonhosted.org/packages/b0/32/2fbc8412c6d650886b201a0b1b2d522008d4a8858d885d2ca1b1f35df2d3/psycopg_binary-3.3.9-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:e51c7c493f07b51be56875cfa8a7674824749fa1cda3515339ca64e628f1b992", size = 3920287, upload-time = "2026-11-12T09:03:24.19Z" }, - { url = "https://files.pythonhosted.org/packages/cf/51/cc921a2ce634cbe8ebf3cb2b062d303d97afbf4ee941f8190003d867bea9/psycopg_binary-3.3.9-cp315-cp315-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e5af7a6d4ca7781c03f9f628ef83ff739de8a7e7e0ffe4b6e7a8c274caea6f81", size = 4141389, upload-time = "2026-11-12T09:03:29.754Z" }, - { url = "https://files.pythonhosted.org/packages/db/37/74fd196f755b979de8d2ad8d84f54afe0628036a8d88b63f7fd204e2f8fc/psycopg_binary-3.3.9-cp315-cp315-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:e047c843fb5cd3c9ebc370bf9a9394cb97feb71b678f07f58419de6d1c6cb5a5", size = 3558765, upload-time = "2026-11-12T09:03:37.484Z" }, - { url = "https://files.pythonhosted.org/packages/37/16/096ce6aae0063f42b1d6ae6f6fe0276208fb929daa5405a92718cf3061b2/psycopg_binary-3.3.9-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:9452241b4684a6321c8e047f4b31a029823fafceddb0809827ec1d506784a3cd", size = 3907982, upload-time = "2026-11-12T09:03:43.975Z" }, - { url = "https://files.pythonhosted.org/packages/34/09/1e8063b591433174211908d9797c7d0e85304a11c92069f66ec66c2c741b/psycopg_binary-3.3.9-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:9926a6f98fbfbb47ad34fab6151d5e6de917d640a07e78cf07a91005593f7c65", size = 3586055, upload-time = "2026-11-12T09:03:49.195Z" }, - { url = "https://files.pythonhosted.org/packages/f4/04/206ac77650b2313b3e6b2fb0d00ba3bb663095586b824d350a1937738575/psycopg_binary-3.3.9-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:0f049ea20c87608eab3df8f055e8e29743a7af42f5e3e1bdb653611194fa64eb", size = 3322175, upload-time = "2026-11-12T09:03:55.836Z" }, - { url = "https://files.pythonhosted.org/packages/ec/27/22d7d9865c4722abc12be9a15be1f671624f7d440afb66cbd719dcb44a3e/psycopg_binary-3.3.9-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:6ab13f8174a0a63d0b9ec39ac27dd129a4d78f22099f146455b5c3a73957cfb2", size = 3629954, upload-time = "2026-11-12T09:04:01.437Z" }, - { url = "https://files.pythonhosted.org/packages/fb/4e/d066faaffcb5b9d0ef593c2903e767bdd22a12ee36e117c3f13d59cc5efb/psycopg_binary-3.3.9-cp315-cp315-win_amd64.whl", hash = "sha256:d5281f3453caebc911b2c5553398d59e217a8101f6b2596311256ba3772167fb", size = 3010099, upload-time = "2026-11-12T09:04:04.907Z" }, -] - -[[package]] -name = "pyarrow" -version = "21.0.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/ef/c2/ea068b8f00905c06329a3dfcd40d0fcc2b7d0f2e355bdb25b65e0a0e4cd4/pyarrow-21.0.0.tar.gz", hash = "sha256:5051f2dccf0e283ff56335760cbc8622cf52264d67e359d5569541ac11b6d5bc", size = 1133487, upload-time = "2025-07-18T00:57:31.761Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/94/dc/80564a3071a57c20b7c32575e4a0120e8a330ef487c319b122942d665960/pyarrow-21.0.0-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:c077f48aab61738c237802836fc3844f85409a46015635198761b0d6a688f87b", size = 31243234, upload-time = "2025-07-18T00:55:03.812Z" }, - { url = "https://files.pythonhosted.org/packages/ea/cc/3b51cb2db26fe535d14f74cab4c79b191ed9a8cd4cbba45e2379b5ca2746/pyarrow-21.0.0-cp311-cp311-macosx_12_0_x86_64.whl", hash = "sha256:689f448066781856237eca8d1975b98cace19b8dd2ab6145bf49475478bcaa10", size = 32714370, upload-time = "2025-07-18T00:55:07.495Z" }, - { url = "https://files.pythonhosted.org/packages/24/11/a4431f36d5ad7d83b87146f515c063e4d07ef0b7240876ddb885e6b44f2e/pyarrow-21.0.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:479ee41399fcddc46159a551705b89c05f11e8b8cb8e968f7fec64f62d91985e", size = 41135424, upload-time = "2025-07-18T00:55:11.461Z" }, - { url = "https://files.pythonhosted.org/packages/74/dc/035d54638fc5d2971cbf1e987ccd45f1091c83bcf747281cf6cc25e72c88/pyarrow-21.0.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:40ebfcb54a4f11bcde86bc586cbd0272bac0d516cfa539c799c2453768477569", size = 42823810, upload-time = "2025-07-18T00:55:16.301Z" }, - { url = "https://files.pythonhosted.org/packages/2e/3b/89fced102448a9e3e0d4dded1f37fa3ce4700f02cdb8665457fcc8015f5b/pyarrow-21.0.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:8d58d8497814274d3d20214fbb24abcad2f7e351474357d552a8d53bce70c70e", size = 43391538, upload-time = "2025-07-18T00:55:23.82Z" }, - { url = "https://files.pythonhosted.org/packages/fb/bb/ea7f1bd08978d39debd3b23611c293f64a642557e8141c80635d501e6d53/pyarrow-21.0.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:585e7224f21124dd57836b1530ac8f2df2afc43c861d7bf3d58a4870c42ae36c", size = 45120056, upload-time = "2025-07-18T00:55:28.231Z" }, - { url = "https://files.pythonhosted.org/packages/6e/0b/77ea0600009842b30ceebc3337639a7380cd946061b620ac1a2f3cb541e2/pyarrow-21.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:555ca6935b2cbca2c0e932bedd853e9bc523098c39636de9ad4693b5b1df86d6", size = 26220568, upload-time = "2025-07-18T00:55:32.122Z" }, - { url = "https://files.pythonhosted.org/packages/ca/d4/d4f817b21aacc30195cf6a46ba041dd1be827efa4a623cc8bf39a1c2a0c0/pyarrow-21.0.0-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:3a302f0e0963db37e0a24a70c56cf91a4faa0bca51c23812279ca2e23481fccd", size = 31160305, upload-time = "2025-07-18T00:55:35.373Z" }, - { url = "https://files.pythonhosted.org/packages/a2/9c/dcd38ce6e4b4d9a19e1d36914cb8e2b1da4e6003dd075474c4cfcdfe0601/pyarrow-21.0.0-cp312-cp312-macosx_12_0_x86_64.whl", hash = "sha256:b6b27cf01e243871390474a211a7922bfbe3bda21e39bc9160daf0da3fe48876", size = 32684264, upload-time = "2025-07-18T00:55:39.303Z" }, - { url = "https://files.pythonhosted.org/packages/4f/74/2a2d9f8d7a59b639523454bec12dba35ae3d0a07d8ab529dc0809f74b23c/pyarrow-21.0.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:e72a8ec6b868e258a2cd2672d91f2860ad532d590ce94cdf7d5e7ec674ccf03d", size = 41108099, upload-time = "2025-07-18T00:55:42.889Z" }, - { url = "https://files.pythonhosted.org/packages/ad/90/2660332eeb31303c13b653ea566a9918484b6e4d6b9d2d46879a33ab0622/pyarrow-21.0.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:b7ae0bbdc8c6674259b25bef5d2a1d6af5d39d7200c819cf99e07f7dfef1c51e", size = 42829529, upload-time = "2025-07-18T00:55:47.069Z" }, - { url = "https://files.pythonhosted.org/packages/33/27/1a93a25c92717f6aa0fca06eb4700860577d016cd3ae51aad0e0488ac899/pyarrow-21.0.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:58c30a1729f82d201627c173d91bd431db88ea74dcaa3885855bc6203e433b82", size = 43367883, upload-time = "2025-07-18T00:55:53.069Z" }, - { url = "https://files.pythonhosted.org/packages/05/d9/4d09d919f35d599bc05c6950095e358c3e15148ead26292dfca1fb659b0c/pyarrow-21.0.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:072116f65604b822a7f22945a7a6e581cfa28e3454fdcc6939d4ff6090126623", size = 45133802, upload-time = "2025-07-18T00:55:57.714Z" }, - { url = "https://files.pythonhosted.org/packages/71/30/f3795b6e192c3ab881325ffe172e526499eb3780e306a15103a2764916a2/pyarrow-21.0.0-cp312-cp312-win_amd64.whl", hash = "sha256:cf56ec8b0a5c8c9d7021d6fd754e688104f9ebebf1bf4449613c9531f5346a18", size = 26203175, upload-time = "2025-07-18T00:56:01.364Z" }, - { url = "https://files.pythonhosted.org/packages/16/ca/c7eaa8e62db8fb37ce942b1ea0c6d7abfe3786ca193957afa25e71b81b66/pyarrow-21.0.0-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:e99310a4ebd4479bcd1964dff9e14af33746300cb014aa4a3781738ac63baf4a", size = 31154306, upload-time = "2025-07-18T00:56:04.42Z" }, - { url = "https://files.pythonhosted.org/packages/ce/e8/e87d9e3b2489302b3a1aea709aaca4b781c5252fcb812a17ab6275a9a484/pyarrow-21.0.0-cp313-cp313-macosx_12_0_x86_64.whl", hash = "sha256:d2fe8e7f3ce329a71b7ddd7498b3cfac0eeb200c2789bd840234f0dc271a8efe", size = 32680622, upload-time = "2025-07-18T00:56:07.505Z" }, - { url = "https://files.pythonhosted.org/packages/84/52/79095d73a742aa0aba370c7942b1b655f598069489ab387fe47261a849e1/pyarrow-21.0.0-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:f522e5709379d72fb3da7785aa489ff0bb87448a9dc5a75f45763a795a089ebd", size = 41104094, upload-time = "2025-07-18T00:56:10.994Z" }, - { url = "https://files.pythonhosted.org/packages/89/4b/7782438b551dbb0468892a276b8c789b8bbdb25ea5c5eb27faadd753e037/pyarrow-21.0.0-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:69cbbdf0631396e9925e048cfa5bce4e8c3d3b41562bbd70c685a8eb53a91e61", size = 42825576, upload-time = "2025-07-18T00:56:15.569Z" }, - { url = "https://files.pythonhosted.org/packages/b3/62/0f29de6e0a1e33518dec92c65be0351d32d7ca351e51ec5f4f837a9aab91/pyarrow-21.0.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:731c7022587006b755d0bdb27626a1a3bb004bb56b11fb30d98b6c1b4718579d", size = 43368342, upload-time = "2025-07-18T00:56:19.531Z" }, - { url = "https://files.pythonhosted.org/packages/90/c7/0fa1f3f29cf75f339768cc698c8ad4ddd2481c1742e9741459911c9ac477/pyarrow-21.0.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:dc56bc708f2d8ac71bd1dcb927e458c93cec10b98eb4120206a4091db7b67b99", size = 45131218, upload-time = "2025-07-18T00:56:23.347Z" }, - { url = "https://files.pythonhosted.org/packages/01/63/581f2076465e67b23bc5a37d4a2abff8362d389d29d8105832e82c9c811c/pyarrow-21.0.0-cp313-cp313-win_amd64.whl", hash = "sha256:186aa00bca62139f75b7de8420f745f2af12941595bbbfa7ed3870ff63e25636", size = 26087551, upload-time = "2025-07-18T00:56:26.758Z" }, - { url = "https://files.pythonhosted.org/packages/c9/ab/357d0d9648bb8241ee7348e564f2479d206ebe6e1c47ac5027c2e31ecd39/pyarrow-21.0.0-cp313-cp313t-macosx_12_0_arm64.whl", hash = "sha256:a7a102574faa3f421141a64c10216e078df467ab9576684d5cd696952546e2da", size = 31290064, upload-time = "2025-07-18T00:56:30.214Z" }, - { url = "https://files.pythonhosted.org/packages/3f/8a/5685d62a990e4cac2043fc76b4661bf38d06efed55cf45a334b455bd2759/pyarrow-21.0.0-cp313-cp313t-macosx_12_0_x86_64.whl", hash = "sha256:1e005378c4a2c6db3ada3ad4c217b381f6c886f0a80d6a316fe586b90f77efd7", size = 32727837, upload-time = "2025-07-18T00:56:33.935Z" }, - { url = "https://files.pythonhosted.org/packages/fc/de/c0828ee09525c2bafefd3e736a248ebe764d07d0fd762d4f0929dbc516c9/pyarrow-21.0.0-cp313-cp313t-manylinux_2_28_aarch64.whl", hash = "sha256:65f8e85f79031449ec8706b74504a316805217b35b6099155dd7e227eef0d4b6", size = 41014158, upload-time = "2025-07-18T00:56:37.528Z" }, - { url = "https://files.pythonhosted.org/packages/6e/26/a2865c420c50b7a3748320b614f3484bfcde8347b2639b2b903b21ce6a72/pyarrow-21.0.0-cp313-cp313t-manylinux_2_28_x86_64.whl", hash = "sha256:3a81486adc665c7eb1a2bde0224cfca6ceaba344a82a971ef059678417880eb8", size = 42667885, upload-time = "2025-07-18T00:56:41.483Z" }, - { url = "https://files.pythonhosted.org/packages/0a/f9/4ee798dc902533159250fb4321267730bc0a107d8c6889e07c3add4fe3a5/pyarrow-21.0.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:fc0d2f88b81dcf3ccf9a6ae17f89183762c8a94a5bdcfa09e05cfe413acf0503", size = 43276625, upload-time = "2025-07-18T00:56:48.002Z" }, - { url = "https://files.pythonhosted.org/packages/5a/da/e02544d6997037a4b0d22d8e5f66bc9315c3671371a8b18c79ade1cefe14/pyarrow-21.0.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:6299449adf89df38537837487a4f8d3bd91ec94354fdd2a7d30bc11c48ef6e79", size = 44951890, upload-time = "2025-07-18T00:56:52.568Z" }, - { url = "https://files.pythonhosted.org/packages/e5/4e/519c1bc1876625fe6b71e9a28287c43ec2f20f73c658b9ae1d485c0c206e/pyarrow-21.0.0-cp313-cp313t-win_amd64.whl", hash = "sha256:222c39e2c70113543982c6b34f3077962b44fca38c0bd9e68bb6781534425c10", size = 26371006, upload-time = "2025-07-18T00:56:56.379Z" }, -] - -[[package]] -name = "pycparser" -version = "3.12" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/cb/27/eeb9f307bf07060f3d9f9aa0fb8c15b01bdfded0a941e4b2719c7f94cacd/pycparser-3.12.tar.gz", hash = "sha256:f03387877eab82ce01bbdfd0ba7252ee55a90b1c708d5129e2ce915475cf1db6", size = 158785, upload-time = "2026-10-22T13:40:03.56Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/b6/ae/315bbeee126a769cbde43cf4908acb4b40408d8bf8bbf334dd7368d8dadf/pycparser-3.12-py3-none-any.whl", hash = "sha256:a076f3f489b39b43ed13563a1dafe42447445bec2e294154ec5c57fcdda4c85e", size = 62600, upload-time = "2026-10-22T13:40:02.021Z" }, -] - -[[package]] -name = "pygments" -version = "2.21.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/49/2e/ced460408999b33da6b31b0021b0f37d329e202d4169aeb164493778f25b/pygments-2.21.0.tar.gz", hash = "sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c", size = 5005329, upload-time = "2026-08-17T08:02:48.824Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/71/46/17f022dd3e953bf20a04a028a21ec746d942f8d2af30fa0f124fa0e6a684/pygments-2.21.0-py3-none-any.whl", hash = "sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9", size = 1250147, upload-time = "2026-08-17T08:02:44.912Z" }, -] - -[[package]] -name = "pymdown-extensions" -version = "11.0.2" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "markdown" }, - { name = "pyyaml" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/ad/17/2db4b414de89659144488e0d9c6c0bf0c8395841dc12d81d0532cc6ef310/pymdown_extensions-11.0.2.tar.gz", hash = "sha256:9506fcbe66fa355a775b768084334238dd6805020ac4b92bea0c0dda6f8f223d", size = 855419, upload-time = "2026-08-22T19:28:47.236Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/a6/43/9f45ec4d14e596efc32c925a78104934790438b0c0628b70d741016734ad/pymdown_extensions-11.0.2-py3-none-any.whl", hash = "sha256:259910762019732caa1dfd76f3faa62c59f191d46573e80bcb1d13c0f675bbe5", size = 269929, upload-time = "2026-08-22T19:28:45.389Z" }, -] - -[[package]] -name = "pytest" -version = "8.4.2" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "colorama", marker = "sys_platform == 'win32'" }, - { name = "iniconfig" }, - { name = "packaging" }, - { name = "pluggy" }, - { name = "pygments" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/a3/5c/00a0e072241553e1a7496d638deababa67c5058571567b92a7eaa258397c/pytest-8.4.2.tar.gz", hash = "sha256:86c0d0b93306b961d58d62a4db4879f27fe25513d4b969df351abdddb3c30e01", size = 1519618, upload-time = "2025-09-04T14:34:22.711Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/a8/a4/20da314d277121d6534b3a980b29035dcd51e6744bd79075a6ce8fa4eb8d/pytest-8.4.2-py3-none-any.whl", hash = "sha256:872f880de3fc3a5bdc88a11b39c9710c3497a547cfa9320bc3c5e62fbf272e79", size = 365750, upload-time = "2025-09-04T14:34:20.226Z" }, -] - -[[package]] -name = "python-multipart" -version = "0.0.34" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/7e/c0/c753d487a83d873f6946cee6cbc26cea3fe59a476ad0de99a14938a2fbd8/python_multipart-0.0.34.tar.gz", hash = "sha256:b998ae90ca6e1e363261ce2e0e230281b8af53867b757970abd69ee9edcd843a", size = 52456, upload-time = "2026-11-16T10:40:38.261Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/f5/0e/090c52b122d8ec5fa37942c1410fea9cf04ce98bca0c84dde7f0aa11594d/python_multipart-0.0.34-py3-none-any.whl", hash = "sha256:ebacd224bd686eee2f9aa1066a657affe07435a185834e05e5235e2e59173e91", size = 32585, upload-time = "2026-11-16T10:40:37.119Z" }, -] - -[[package]] -name = "pyyaml" -version = "6.0.4" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/76/b8/c0b780928e2fb1c87e9e375818c6f121da2398b071012d1747be300b83f4/pyyaml-6.0.4.tar.gz", hash = "sha256:e24bf71af8a432d7808fabff134d38dfe16d3cbb41f2873bb4b1e42422de0a1a", size = 136336, upload-time = "2026-11-20T23:37:05.977Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/e1/ba/fb2aad330bc4f31041f989630ceae5f32e307d3ba9819573d35b71e078fa/pyyaml-6.0.4-cp311-cp311-macosx_10_15_x86_64.whl", hash = "sha256:180ac792c958c2173f6e4467c55ae5f73ab1a9a624ee29fc7095c56d5e3a4055", size = 190856, upload-time = "2026-11-20T23:34:50.753Z" }, - { url = "https://files.pythonhosted.org/packages/16/da/1b8397614250ec63bb7ef1cbb0aa5878367ff729ef35a4abf2accbf48a18/pyyaml-6.0.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:730788375056c43d3ac15bd894c9cd2fb7a931a38b302f408620c64b3ef176ed", size = 180950, upload-time = "2026-11-20T23:34:51.629Z" }, - { url = "https://files.pythonhosted.org/packages/fa/88/d99fc8f2cfb33ab7786fb3f6da90eddc1ed9709196bffcb4a487d7f53844/pyyaml-6.0.4-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:71bb5b87465d88d1dfc577115af6d435bff9b26f2512936f610c26aa55966028", size = 810905, upload-time = "2026-11-20T23:34:52.77Z" }, - { url = "https://files.pythonhosted.org/packages/d7/7f/500e5ec119990d1784c72b64197cee8a4f2982f6bc76c572af7f8df02385/pyyaml-6.0.4-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b9fe0b8c65a1611053eb7fcaa7c022f655b7eebeb0ea034572615453cae6b843", size = 914779, upload-time = "2026-11-20T23:34:54.086Z" }, - { url = "https://files.pythonhosted.org/packages/9d/3e/c1c307b6c03e4ea7d86f166f14920ead07aecc35e88d873814d12aa2da66/pyyaml-6.0.4-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:622aa875fa6533f25fedcffe23079357d65a690d462200afed5d8e9d0e01ebee", size = 828016, upload-time = "2026-11-20T23:34:55.213Z" }, - { url = "https://files.pythonhosted.org/packages/03/49/dc931722d7de757596c1c3b944287e4f7d3f419655cd8f5fae382c6179e6/pyyaml-6.0.4-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:49e38a95e24738908ea852e61df0abc58d1e4d4f974ccdb2386eaee412bedc67", size = 799807, upload-time = "2026-11-20T23:34:56.589Z" }, - { url = "https://files.pythonhosted.org/packages/bf/8b/2b7ad9af1c6c5b147c3c860a31586737034a83693d7ae86f854036c6aeb4/pyyaml-6.0.4-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:4d3bbc5e8a84a5a6775adecac786f489510a7159b1c343d6f31426d888cfdd6e", size = 836213, upload-time = "2026-11-20T23:34:57.655Z" }, - { url = "https://files.pythonhosted.org/packages/8c/d8/ebdc04bbf7c00a3c78ea577322239534556418a958d2242af8c0c6ef9093/pyyaml-6.0.4-cp311-cp311-win32.whl", hash = "sha256:c0d68d972f6f6417b4e85e9522f3d57bb4fbc924379766ccd87254a31009c1cd", size = 146012, upload-time = "2026-11-20T23:34:58.75Z" }, - { url = "https://files.pythonhosted.org/packages/7f/c6/ffe94f3159f3543b1ea1702519e1e0a74a67f3a255c286c1f00d51780b82/pyyaml-6.0.4-cp311-cp311-win_amd64.whl", hash = "sha256:0db75f402e99c25239003a499c214a61947b4ef5312af34711d4c63e5c179318", size = 161819, upload-time = "2026-11-20T23:34:59.853Z" }, - { url = "https://files.pythonhosted.org/packages/86/df/5aec8a8c65e4c11fab31b55d53029d8013e5ccfcf409c20f8175e3e267c7/pyyaml-6.0.4-cp312-cp312-macosx_10_15_x86_64.whl", hash = "sha256:1088ad740f50c13178dad16fbc2fa1f634c791d42c7009fdb390e38e5b90b788", size = 187835, upload-time = "2026-11-20T23:35:00.829Z" }, - { url = "https://files.pythonhosted.org/packages/c7/30/efaabf2d135d11f32cbd4752f3b7df0d592894ee3ca252bbba013a7d5891/pyyaml-6.0.4-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:4d30c2f186612bd2f9f07c08a4c96721af59cfc8da3ec7cb27dfa2834e8bb019", size = 179510, upload-time = "2026-11-20T23:35:01.826Z" }, - { url = "https://files.pythonhosted.org/packages/af/fb/d5ff6957db5c843151ff13196277bb8e20b2d5db2e2db3e8d051038d888b/pyyaml-6.0.4-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:45e37dd647db9d67b757444c74060c064ace5fdaa08f42bf4fda3812275d423e", size = 814700, upload-time = "2026-11-20T23:35:02.923Z" }, - { url = "https://files.pythonhosted.org/packages/c4/de/569b907a281bbc49b934bcdad881486b7a476b011cf733f936ca85a8b37d/pyyaml-6.0.4-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:9e7ec9dc75cadd392fd687cc9b8ccf7dd59ada0a991e0d14ae0fad9ecdba00c3", size = 879806, upload-time = "2026-11-20T23:35:04.34Z" }, - { url = "https://files.pythonhosted.org/packages/94/80/1d27f7084b983b7cfd1fb35e65a38276d9eddfdcdabc0922bb26cf9521bc/pyyaml-6.0.4-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:93bfb2459195406a518e2f487a9bbf01df240175f31e06f5a252ac6734c7bbf0", size = 849249, upload-time = "2026-11-20T23:35:05.457Z" }, - { url = "https://files.pythonhosted.org/packages/53/37/9b49dff68570bedf27a05ff447e9a281d75bbdfa4d08dc1ee100a844c612/pyyaml-6.0.4-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:84e97378010f3da8daf673b82d39ed638098d236a1b760d61c0c1348a642bd70", size = 799796, upload-time = "2026-11-20T23:35:06.566Z" }, - { url = "https://files.pythonhosted.org/packages/05/bb/f7df529541b98113bea84129a78f93c3889acb08385ca25f9786823dce67/pyyaml-6.0.4-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:f5c410f9e2ffc9286279a46f2e8c107edaf3b1123510af59c828a9c15b23c9db", size = 825424, upload-time = "2026-11-20T23:35:07.783Z" }, - { url = "https://files.pythonhosted.org/packages/44/00/fc5d40087cc55bf3d7bb5ef55cc3e6513e6946afe33a188680fe1d846eb0/pyyaml-6.0.4-cp312-cp312-win32.whl", hash = "sha256:60e9da2772e259307650e03c24f50e3bc2d9fa5ed1ba44c47582e13b0e7708d1", size = 140667, upload-time = "2026-11-20T23:35:08.846Z" }, - { url = "https://files.pythonhosted.org/packages/a3/95/307a6ceafbad9a08300743d19329c31726224e583e05c4fe5358522ba283/pyyaml-6.0.4-cp312-cp312-win_amd64.whl", hash = "sha256:131d11bd9b60d705a6388366d77ed67850995a4d2be85fe149785a257c17e531", size = 154452, upload-time = "2026-11-20T23:35:09.792Z" }, - { url = "https://files.pythonhosted.org/packages/62/81/15c300b14cca818cb9ee27d8cb61cc124229d04f4f7f7bc4e3fca8e2e8d8/pyyaml-6.0.4-cp312-cp312-win_arm64.whl", hash = "sha256:69380d4bae12aab2a2c9532deff6a2841bc9fda47c333691bd2368b696301768", size = 147167, upload-time = "2026-11-20T23:35:10.763Z" }, - { url = "https://files.pythonhosted.org/packages/95/22/b445c43210fe7f466fcf5a38bcbe850fd3db31b85594db22b5a43e63c482/pyyaml-6.0.4-cp313-cp313-macosx_10_15_x86_64.whl", hash = "sha256:61eef2f08e977b725f37a8d1663f5a222c6f09207ac0794030d5fca062e7c96e", size = 188392, upload-time = "2026-11-20T23:35:11.776Z" }, - { url = "https://files.pythonhosted.org/packages/1f/c3/1536ad41fd962d3915f3f8252ecc7f91192ab15c3120ba72ff45e76b7077/pyyaml-6.0.4-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:9d4211f080920629a90c9e31c51e326fb70cfae38f18d4128b9913c23642bace", size = 179961, upload-time = "2026-11-20T23:35:12.722Z" }, - { url = "https://files.pythonhosted.org/packages/40/fd/c5297cc6370e4ab63d0c44d2e63510cc53354f5e8e74bcff047e2a384698/pyyaml-6.0.4-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:41b4669c3a8fd5750e594dff59d3e62d40e321fec467b50449603710ed0a68f3", size = 804464, upload-time = "2026-11-20T23:35:14.066Z" }, - { url = "https://files.pythonhosted.org/packages/0c/2e/20385f63727a6c08df1adad34a88bde90e2bcc1146d1c8588a83190d53b8/pyyaml-6.0.4-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:efe68ed09903cca9ab4117c2b9ea6ee8d369818808945bb5a7fa8009b5630b45", size = 875357, upload-time = "2026-11-20T23:35:15.537Z" }, - { url = "https://files.pythonhosted.org/packages/70/f2/f280d52f22f6d9853517d02495c02fbf4c80214fae8ca498efa8605013da/pyyaml-6.0.4-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:50588147ab2c6a59b5f990a4905db80899a6c2bd197e046a6201f1e67587e794", size = 838459, upload-time = "2026-11-20T23:35:16.681Z" }, - { url = "https://files.pythonhosted.org/packages/2a/ee/5f7142110583686e94ab4492e3724ed0869cd9fe26ba8293ec25a47ee223/pyyaml-6.0.4-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:4d1e8d6e345b4b4424a05a11e699e999e65a88f422f73636f8a0b354bf219ffa", size = 789384, upload-time = "2026-11-20T23:35:17.734Z" }, - { url = "https://files.pythonhosted.org/packages/4f/ab/1fd22df5305561cbefb85363182a0af5e81d219e8b8b8dfd73f20eb70859/pyyaml-6.0.4-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:a56491babf0d976625807953bd192dd9de973fccb3270e77b1a795b152a26175", size = 814502, upload-time = "2026-11-20T23:35:19.171Z" }, - { url = "https://files.pythonhosted.org/packages/c1/5a/6b53e1711a78fcc14619a341618c36b862ad8c634e7bc43ae18e6a7376b2/pyyaml-6.0.4-cp313-cp313-win32.whl", hash = "sha256:1631d566655f3af7d6c4a4485267830f6b680d3dc9704b659b3c3f4541b5a3fe", size = 140447, upload-time = "2026-11-20T23:35:20.134Z" }, - { url = "https://files.pythonhosted.org/packages/bd/09/e785d2a9d64de2449cc3aecaa03f1c34670d7a688dc00da7246a858b7e8f/pyyaml-6.0.4-cp313-cp313-win_amd64.whl", hash = "sha256:0a3a351f04dc124f9357512bdb80ac37cd1750cf1371da33e7cbb96d80ac865f", size = 154298, upload-time = "2026-11-20T23:36:22.105Z" }, - { url = "https://files.pythonhosted.org/packages/94/44/0ed649c2c1cc37b342042c3a4609247b74201c23a6f7f01f5dd222eae2bd/pyyaml-6.0.4-cp313-cp313-win_arm64.whl", hash = "sha256:f617e4e5c619fef5284335b24e3af3a77ce08dc5c389ff4b25033bb2749032b7", size = 146938, upload-time = "2026-11-20T23:36:23.305Z" }, - { url = "https://files.pythonhosted.org/packages/70/90/a2d37db959cb771389bb6171eff83905776e5aead12a985a5118a587d6eb/pyyaml-6.0.4-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:4a329472db6c8858ebd94f2214a54c8bff8f035a6cc7af1ab39cc1b33a5f0e56", size = 189727, upload-time = "2026-11-20T23:36:24.518Z" }, - { url = "https://files.pythonhosted.org/packages/71/40/de4380acb2bcc733f502a7c8562b08f741890741dcaa8a7f018c87acc060/pyyaml-6.0.4-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:7335809813ec838d9cd334b1744cda33deb141c9ef23a9c0df371c37980d3851", size = 181969, upload-time = "2026-11-20T23:36:25.675Z" }, - { url = "https://files.pythonhosted.org/packages/7f/a1/88baf9d84981ea723fc1dd5cb534548caebff3071939f899509ab7c62d2f/pyyaml-6.0.4-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ed9b957abb12f6ffcd92d5db32fa3ffd4e4a8423d80ddd51b4efa63b42f6a76b", size = 804091, upload-time = "2026-11-20T23:36:26.979Z" }, - { url = "https://files.pythonhosted.org/packages/b8/d4/ce94fe5b0e3cc04834d4a30237c1b5388a13ff5a383b919e857898834857/pyyaml-6.0.4-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b525488d5addf5d59ff4610cd8b1deab9dc97fe0fb3fb74533d7f65e9792bd92", size = 869794, upload-time = "2026-11-20T23:36:28.069Z" }, - { url = "https://files.pythonhosted.org/packages/ef/1b/54ce11b40c8fa1883f14eef46525c3c329509dcc268164074fbe60add8ed/pyyaml-6.0.4-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c604dc2613c417130479cdd6e55c2faa691b6365aa82b3dafddfcecc2eaf1ac7", size = 819491, upload-time = "2026-11-20T23:36:29.189Z" }, - { url = "https://files.pythonhosted.org/packages/8a/d2/6202ffb5d61667c993211a9231836b5d9be5e34165efd1714ac68ea76029/pyyaml-6.0.4-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:f1a4a85b419f5cb6470dd4be5f766bc59532f11b9c22c076b58a0348f05dca5f", size = 790345, upload-time = "2026-11-20T23:36:30.597Z" }, - { url = "https://files.pythonhosted.org/packages/d4/39/d62587fae4a9a32197ea43182c38f221f3f173a09c6f4380254533bdd89e/pyyaml-6.0.4-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:132c3c7c37a8e6f334921b05cfea5d26e241d792dcbb4db0462129d25ca53b43", size = 824626, upload-time = "2026-11-20T23:36:31.9Z" }, - { url = "https://files.pythonhosted.org/packages/b4/b5/e5cf6ca786f8a5b9bd91e01fe8f2113300bc5628fcfdd3ca02d271970824/pyyaml-6.0.4-cp314-cp314-win_amd64.whl", hash = "sha256:1d2f08c122727c86f8303bb1dd45159ca1de1f2d68798e671ec46974e321008e", size = 157525, upload-time = "2026-11-20T23:36:44.254Z" }, - { url = "https://files.pythonhosted.org/packages/75/9c/d78ce9adda3f7db933f73bb2b17ede76f5786fff747a2b73f6e8a6b7bab5/pyyaml-6.0.4-cp314-cp314-win_arm64.whl", hash = "sha256:33506a2620f0e7c49858f09cb44e99f144878d03af3d9c10aa136e9a1d103bcd", size = 151175, upload-time = "2026-11-20T23:36:45.191Z" }, - { url = "https://files.pythonhosted.org/packages/83/f0/e48b8e9736380a039a17506200c4c3080ef181ee86b0e8e2cd6c345ae78a/pyyaml-6.0.4-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:1db4d51d3c2c9545dd44c614febc4594240754f74b30d8e501415b118347f0d1", size = 193903, upload-time = "2026-11-20T23:36:33.086Z" }, - { url = "https://files.pythonhosted.org/packages/98/ba/682030d1e08f2e4bbd57f164b9085d37560386cf54f6299825e754b32d1a/pyyaml-6.0.4-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:93da48af92c84c4236578e330a514ca324362c0bb62894d8d2343363ed57ff03", size = 188971, upload-time = "2026-11-20T23:36:34.034Z" }, - { url = "https://files.pythonhosted.org/packages/e9/2b/4b29107aae981b4d4575945a73d6c73ebd407d27934dcf35a7daa8fbeb43/pyyaml-6.0.4-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3c7129bcee5c88c1450802cc6a95b690ee7c51bfcc7a9b60bbd9549a7a4fcbe6", size = 851356, upload-time = "2026-11-20T23:36:35.21Z" }, - { url = "https://files.pythonhosted.org/packages/12/d4/2b05dddc8f59c3762e67c8d5ac01c1759767ee6ea4aba183a01950644668/pyyaml-6.0.4-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2018fda285d1289527a389e1b4ace1e2d3af410930f949136b55ecb0747744d1", size = 887294, upload-time = "2026-11-20T23:36:36.484Z" }, - { url = "https://files.pythonhosted.org/packages/3e/2a/ce3e0ff674c67b9e1706912aae61063581b3dba22142e60ccdaa64b25c75/pyyaml-6.0.4-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:15c52bb238a15bb4fd7e6342a5ac71d594507667c7fe0e5a5abbc0f6875d1e91", size = 850982, upload-time = "2026-11-20T23:36:38.247Z" }, - { url = "https://files.pythonhosted.org/packages/7e/ad/701d83221865b2512067a9ab2b8e062145af2d362cc2451e72c146ef34cf/pyyaml-6.0.4-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:ab874ebcc5c12c31c859a9e9fe159d688df1f7a099818ef8a35906264a8f5d6b", size = 822547, upload-time = "2026-11-20T23:36:39.852Z" }, - { url = "https://files.pythonhosted.org/packages/61/d1/d88b389313be382ddabd1bca86dbf5da31ac02ecbf29c893588aafb6e11f/pyyaml-6.0.4-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:62c5b5669b05dabf991a705f3a3601f57b65e95121a1d3e3a4ae4446c8632865", size = 845538, upload-time = "2026-11-20T23:36:41.285Z" }, - { url = "https://files.pythonhosted.org/packages/1a/a6/c25ff1b5ebc8bfb11a783a5fde40435f0459629af6f56f9487479bca9766/pyyaml-6.0.4-cp314-cp314t-win_amd64.whl", hash = "sha256:609e8efaffa5662da16b7d53eef76fc4eedbbe56fce5829b67ba808a6e35d399", size = 164060, upload-time = "2026-11-20T23:36:42.238Z" }, - { url = "https://files.pythonhosted.org/packages/08/ad/25d2ac566f0e2f4eb822c9c5e8d9a053406cbfff142273a072b194856823/pyyaml-6.0.4-cp314-cp314t-win_arm64.whl", hash = "sha256:a266cf55ee5cf63c1803432a61c6386e750e0012ca49d12d26ccb0ffd80b343a", size = 157379, upload-time = "2026-11-20T23:36:43.181Z" }, - { url = "https://files.pythonhosted.org/packages/e5/29/fb680bd299c2c6e004c1cc1914f8bad276c6014fe8debd5d6d61ea4c4ff4/pyyaml-6.0.4-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:12a155bc41509d71a2eb73e2191d9e400c1345ea99ac3d9946c31f40a4c840f8", size = 189560, upload-time = "2026-11-20T23:36:46.145Z" }, - { url = "https://files.pythonhosted.org/packages/af/6c/2ffdab56d7afeb039d957479a305516ddbaa08d0162d1e9165fb928e3aeb/pyyaml-6.0.4-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:070c22b6f490d6cc30912be9fb9ab1af9c752769b39b53616f6510c3f038ee6a", size = 181949, upload-time = "2026-11-20T23:36:47.065Z" }, - { url = "https://files.pythonhosted.org/packages/b3/07/3a20ed31a60084206ac20449583b0d1a42116b3c530d6857918e4ddbe4b6/pyyaml-6.0.4-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:872d2a592289061c1b987e335b3568a2616b474be02bd0608d8f551a385441cd", size = 803806, upload-time = "2026-11-20T23:36:48.145Z" }, - { url = "https://files.pythonhosted.org/packages/26/5b/3dd56027457b96e7e5ea2f4f5976e530d699884b4fd4e360e99e57fa6cca/pyyaml-6.0.4-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:914b19e17814315fbcca52031bf79b68237f3d87a948c584a667b18b468e4df7", size = 876808, upload-time = "2026-11-20T23:36:49.294Z" }, - { url = "https://files.pythonhosted.org/packages/b0/51/096a5495b33ff2da32f0c84f5bf8e042cf76f72641cba06ee9618ad01f4d/pyyaml-6.0.4-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c57e40928738c4a202852759f9e1ee2c7063429a9469ee1ac15651bbf7d69963", size = 833052, upload-time = "2026-11-20T23:36:50.505Z" }, - { url = "https://files.pythonhosted.org/packages/da/75/b4e86b5a27fcb9a9cf88e3b81d1b0c12cae2734311e508af18b93ff56286/pyyaml-6.0.4-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:8e0cd755ce5e9009fd95f9c553e5942478feb8f7dffa19435641fcdc3c20e8ca", size = 788983, upload-time = "2026-11-20T23:36:51.821Z" }, - { url = "https://files.pythonhosted.org/packages/2c/00/2a2cdad68237bcd416bd01688ecfb0e3fa1e68a841b74193db97ffd1c716/pyyaml-6.0.4-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:2c11be5ab4d9f603a598b5ce93a2064ae38087bdf1b384c5397170054cda4e36", size = 828806, upload-time = "2026-11-20T23:36:52.959Z" }, - { url = "https://files.pythonhosted.org/packages/a8/15/39efefc88dd6fbc3be23cef08a819f5e8bf9a6c0bcf003fc09d38dd0010e/pyyaml-6.0.4-cp315-cp315-win_amd64.whl", hash = "sha256:67da066ca12eb60114ea87f2ecbcca622fff0c205c743cc900437127564fabf6", size = 157467, upload-time = "2026-11-20T23:37:04.171Z" }, - { url = "https://files.pythonhosted.org/packages/40/1d/fddc53420d9c12e7d27c36a59fabf186ba1f6117314da4927dc40b2da19b/pyyaml-6.0.4-cp315-cp315-win_arm64.whl", hash = "sha256:573debb9fe3075423d4f823795a678580e597218c25baef178d532b124a25a25", size = 151203, upload-time = "2026-11-20T23:37:05.079Z" }, - { url = "https://files.pythonhosted.org/packages/fa/ea/48e62a25084fc4b317f8bcc5c9823ddaaa73a0c7769ca451dda6919ff491/pyyaml-6.0.4-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:c680622f85979f2ff59b4ae44c1ecb5566b2f0f0ffe5d0dc8b4bb6a0e916dabb", size = 193500, upload-time = "2026-11-20T23:36:54.416Z" }, - { url = "https://files.pythonhosted.org/packages/49/dd/8c4df6becc936125261607073fbcd55e1d902a8d53ae4e4893d53b9df0ef/pyyaml-6.0.4-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:18ea9bda247857fc0de05181675dc116b54c1b04ca3db71de5d2108c882823b7", size = 188474, upload-time = "2026-11-20T23:36:55.651Z" }, - { url = "https://files.pythonhosted.org/packages/d0/63/b60236ef09cbab7c5ce174aff59d49a3425b9a8e9bbe4690bd3b9b7d4fba/pyyaml-6.0.4-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6ac167ebebc0c387290406a337b9b5c8c343fa5f7928d5941e45a94b8ba3aa39", size = 848311, upload-time = "2026-11-20T23:36:56.961Z" }, - { url = "https://files.pythonhosted.org/packages/f6/3b/4b14f064ae5d6f69638a86bb7bf1a46d02bb4de083798e693a4a83b1418a/pyyaml-6.0.4-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4a2a8f27d24d4cdc05aa11df5f4c08e13f30d9e6674809b6a5ddcfcba49a653a", size = 891181, upload-time = "2026-11-20T23:36:58.077Z" }, - { url = "https://files.pythonhosted.org/packages/01/36/4e0b01e380bf3695d34a4bf6b9272c529f4c8d3195c733687d64fb9f8f06/pyyaml-6.0.4-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e956541cc7a3fff2bb5b17aeb6c5bb42c86c8e6dafb5ebdd41a05e72e702076b", size = 855715, upload-time = "2026-11-20T23:36:59.165Z" }, - { url = "https://files.pythonhosted.org/packages/6d/a8/2784a29e687fa7a5882d47c925a98d1dbdd60ead521be14a9342c6a74ff9/pyyaml-6.0.4-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:8708f6ab9c2581ffa05f66dae3206bb0385949650537d7295fc7ab0d6454dd70", size = 818754, upload-time = "2026-11-20T23:37:00.248Z" }, - { url = "https://files.pythonhosted.org/packages/bb/85/62d54e223b4bc89ff85f087a5ce2648e5d929d3214d64613dbae17d5e045/pyyaml-6.0.4-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:a65339c24f2fb8d4419e06ceec1bda98bdcff727b3b533a81d5af6bb2dd34520", size = 845763, upload-time = "2026-11-20T23:37:01.331Z" }, - { url = "https://files.pythonhosted.org/packages/eb/40/6bd9090368664be984a83fd7fe64f8e044b067a52449679c309706e3199d/pyyaml-6.0.4-cp315-cp315t-win_amd64.whl", hash = "sha256:a3cc63af3d639d1609143711837b926183418260aae89ed95193c07b25b99d33", size = 163170, upload-time = "2026-11-20T23:37:02.3Z" }, - { url = "https://files.pythonhosted.org/packages/0d/22/468d36762a0c650cf2295052998eb1d419053335ea9ff48a043f5ae4d578/pyyaml-6.0.4-cp315-cp315t-win_arm64.whl", hash = "sha256:d276f23e2371deb5ee68dd252cc9c2402b806b54d8d2cc7efbb6c34c3a78d886", size = 156942, upload-time = "2026-11-20T23:37:03.209Z" }, -] - -[[package]] -name = "pyzmq" -version = "27.3.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "cffi", marker = "implementation_name == 'pypy'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/e2/e1/ea46ab0d707219c098065a37d2add5b53d3b124241aa19429bcd0863e5b4/pyzmq-27.3.0.tar.gz", hash = "sha256:bbedb3d1d99babc625f1dd9d7438acefd442b36b75073fd6bc1ef7c0a4b96d56", size = 293249, upload-time = "2026-11-04T00:31:33.068Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/ba/ea/4b0f153994ff26f654ca4f941b3e38216ae368cf578e10a1a6d1d8847f01/pyzmq-27.3.0-cp311-cp311-macosx_10_15_universal2.whl", hash = "sha256:86fb4408797aabb54a31e147176ae0f2474d99f1715a36a4564089eca9ef9ce8", size = 1262961, upload-time = "2026-11-04T00:28:46.452Z" }, - { url = "https://files.pythonhosted.org/packages/ca/b4/85be2f47469f13bf31a778c88475bd33824299243af36b18728f96631658/pyzmq-27.3.0-cp311-cp311-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f3d14fc8a7b85156c67e3f6ebbe8f2af2f89da2a407997a66e2a578e1bdabf6a", size = 788453, upload-time = "2026-11-04T00:28:48.34Z" }, - { url = "https://files.pythonhosted.org/packages/8e/09/9f33bee7acbb95b0b8b4847a20f0ca15650bbfbed53795c2ca88f3390391/pyzmq-27.3.0-cp311-cp311-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:477b8ad30d66fc905c5388351e83b9ac25824b00e82c0d052b72ea6392636dfd", size = 875050, upload-time = "2026-11-04T00:28:50.344Z" }, - { url = "https://files.pythonhosted.org/packages/5c/90/397107ce4ac5e69c38cf58c190338a3885432263120298738881cdb8b9b2/pyzmq-27.3.0-cp311-cp311-manylinux_2_28_i686.whl", hash = "sha256:6e5a566ba2f0bdbe3eb0046a3c958b9a5d54cd866bf2ef9e5678a5dfed48613a", size = 938860, upload-time = "2026-11-04T00:28:52.638Z" }, - { url = "https://files.pythonhosted.org/packages/40/03/039a3741e4d4a9996ca976ccd5fb46f0b4ac2fe11e9f7f9718bed8952977/pyzmq-27.3.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:aaab8cf85cf6f063f291ccbee20ced0de69b8e945589471e8e7dc355218a0a13", size = 1779740, upload-time = "2026-11-04T00:28:54.563Z" }, - { url = "https://files.pythonhosted.org/packages/a5/c9/4eabf560d2ca533b5e4074911f9eb6ca5a3697497cfd9f6dff98d98196c8/pyzmq-27.3.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:30c57cdda34d208541944f0b2a6bdece682364bfd6579633dde8f732e32f6376", size = 2086501, upload-time = "2026-11-04T00:28:56.811Z" }, - { url = "https://files.pythonhosted.org/packages/bb/e4/6e5969282f4e26fac4035e4fd1f1b5051fc230148cdcc3ea3587e229274b/pyzmq-27.3.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:b1d5c7d0903f5485e0689a115ca528748a9f287fa04ed6c46580772a2e725c46", size = 1913616, upload-time = "2026-11-04T00:29:03.6Z" }, - { url = "https://files.pythonhosted.org/packages/97/fd/6dd284b6c193cec6672d34a97b56d6160fd32c0e2991ce9bdebad5b423f7/pyzmq-27.3.0-cp311-cp311-win32.whl", hash = "sha256:c2ad234ad2566426c8d568df650675f4996de35bd9376d603b33e32a967f5411", size = 575220, upload-time = "2026-11-04T00:29:05.095Z" }, - { url = "https://files.pythonhosted.org/packages/9e/3b/d3f6c6a3d46781f723ceb90fdfafe403fbcc5494b440e70c37c60e3acfdc/pyzmq-27.3.0-cp311-cp311-win_amd64.whl", hash = "sha256:df98c790f86b6aa2378b4bb94dec7b85b0adb195b880b41e429a4990aed2a8c9", size = 658252, upload-time = "2026-11-04T00:29:06.584Z" }, - { url = "https://files.pythonhosted.org/packages/2c/a7/6229f4b219056a21df780c1d340d6d5c86c5a48d2328f2940010ac932157/pyzmq-27.3.0-cp311-cp311-win_arm64.whl", hash = "sha256:652d68fb398e714540d8a577cef81c548c61394c721bc1b996b5a4028e89f73d", size = 580574, upload-time = "2026-11-04T00:29:08.162Z" }, - { url = "https://files.pythonhosted.org/packages/b5/9e/6663ccc8c1af4e7db85de65921560a8058ad4ad4c40ebc49af4b1164f01a/pyzmq-27.3.0-cp312-abi3-macosx_10_15_universal2.whl", hash = "sha256:15155fd8f308d3bd47f67a8f6cc809f9db90abbf63c514c384a17622e2cf080f", size = 1232964, upload-time = "2026-11-04T00:29:09.922Z" }, - { url = "https://files.pythonhosted.org/packages/b4/90/4fc65d7a48077f535705ac957c29a3c07fa54a1f8d2595ca2f5f1489b21c/pyzmq-27.3.0-cp312-abi3-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ad8b828407caee77ff3ab0bdb2984ee8d48922328b226e8fda7c84a71a55dbb4", size = 770405, upload-time = "2026-11-04T00:29:11.487Z" }, - { url = "https://files.pythonhosted.org/packages/2c/62/e4721d8b8b9de685323717489a408521067a786cabc2b73ccd91aa9b9077/pyzmq-27.3.0-cp312-abi3-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:858fe25231e0fd8612da142efde019faa5ef63fa150a821a27870e791b38c798", size = 855178, upload-time = "2026-11-04T00:29:13.042Z" }, - { url = "https://files.pythonhosted.org/packages/39/5f/8190ff273beb195d9c9b62a36d0d87bad79019e76ff4407cabe463bc650d/pyzmq-27.3.0-cp312-abi3-manylinux_2_28_i686.whl", hash = "sha256:8b174298b57d5c2397c74fbefd656101d477357035916881970ed5f53b7b904c", size = 919158, upload-time = "2026-11-04T00:29:14.854Z" }, - { url = "https://files.pythonhosted.org/packages/8f/66/ab116baad852235c82be3d8d83af7098a7165c48995a03f2b6e8d50297dc/pyzmq-27.3.0-cp312-abi3-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:cffd75359342ef88c86c287c99b16b2b100795dab467fd5398bcedd87d49bce7", size = 813613, upload-time = "2026-11-04T00:29:17.239Z" }, - { url = "https://files.pythonhosted.org/packages/b3/55/5075ef84055eca159435e65f8d67591bfe06c562cf310792cd50a6aeb0c9/pyzmq-27.3.0-cp312-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:220095b4c11b0542ae5c0d67411331d3819753ee9ec0468e63a4ca6fd4ccf50f", size = 1762126, upload-time = "2026-11-04T00:29:18.994Z" }, - { url = "https://files.pythonhosted.org/packages/28/6f/e75d5e5aeda920dbcaaedcc413605379287b817578d00e47bfa89a8ea671/pyzmq-27.3.0-cp312-abi3-musllinux_1_2_i686.whl", hash = "sha256:e9e12fe784529e12177937aee8c714b7aed8913a2429ee2567400c904d4d55b5", size = 2067522, upload-time = "2026-11-04T00:29:20.762Z" }, - { url = "https://files.pythonhosted.org/packages/9c/b4/0d91b1e5ea8d659c1014ef39acfda279f4768fc4043120e98b764a59f1c9/pyzmq-27.3.0-cp312-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:d317685b83663fbd03ca8b5c34add7463e9bed094e3e1a69d2a895130b64ffaf", size = 1893864, upload-time = "2026-11-04T00:29:22.451Z" }, - { url = "https://files.pythonhosted.org/packages/2a/23/ed213d9dc6e48913a1f77090d1aed85bc4b1e5567ef74a86fd8fd473f423/pyzmq-27.3.0-cp312-abi3-win32.whl", hash = "sha256:07dd778d7cf242a1e131bfad6244f64df59441dda7ea639d037d0fdb22112b6c", size = 567172, upload-time = "2026-11-04T00:29:24.09Z" }, - { url = "https://files.pythonhosted.org/packages/fa/6d/23a02024011a494fb52bcfb179f10a3b230cff7b6fe0d5b8a3c775ce3b82/pyzmq-27.3.0-cp312-abi3-win_amd64.whl", hash = "sha256:3ea8e8fa5c097e68fef91d70b150fda96f307758103868018fc4deeb9c214122", size = 642389, upload-time = "2026-11-04T00:29:25.739Z" }, - { url = "https://files.pythonhosted.org/packages/e2/1b/410fc7ec4fc114b46da17ed0df3b88606f0624fbe172e184658d361b1dc1/pyzmq-27.3.0-cp312-abi3-win_arm64.whl", hash = "sha256:2187a5ca80691a5edb30690f02d9fb714e2c32d3dfdeb652e159ff5da2dd4283", size = 570810, upload-time = "2026-11-04T00:29:27.709Z" }, - { url = "https://files.pythonhosted.org/packages/d1/0f/81652a1066e994000cfec501f16137fa231e921675b63ee54c8cf4e30362/pyzmq-27.3.0-cp313-cp313-android_24_arm64_v8a.whl", hash = "sha256:a418d35be0a0a2693bf1990d831a744ee2f012b8268b3e0c6cb28b06c2769d76", size = 1136520, upload-time = "2026-11-04T00:29:29.58Z" }, - { url = "https://files.pythonhosted.org/packages/ce/0e/a2e5cb7db327ce85f3c2d11f25be55aba1639f55dad8ea77e03458ec5dbf/pyzmq-27.3.0-cp313-cp313-android_24_x86_64.whl", hash = "sha256:e9012762d869d620dad3c83fb5ff8f4900490decddd98caf6ff80847176c4be0", size = 1181427, upload-time = "2026-11-04T00:29:31.178Z" }, - { url = "https://files.pythonhosted.org/packages/88/b8/8a80749971b1a42fc415c720a52deedd33d0ae72792544331fc76f306ded/pyzmq-27.3.0-cp314-cp314-android_24_arm64_v8a.whl", hash = "sha256:fca5c2352c499e8355b581ddecfe52538984131b7efc052a30e2d32426baf637", size = 1143753, upload-time = "2026-11-04T00:29:32.923Z" }, - { url = "https://files.pythonhosted.org/packages/59/2d/196f50920da3137fd54b1636c36aba97b95d18d467bf097edca5f6ef5be8/pyzmq-27.3.0-cp314-cp314-android_24_x86_64.whl", hash = "sha256:91ac316f440aca4e6eaf3786f54b80f4ab433e5cc4e5e9b82eb44a27c5c987cd", size = 1182341, upload-time = "2026-11-04T00:29:35.073Z" }, - { url = "https://files.pythonhosted.org/packages/c7/3f/bf2a67da7cfac3c1f85c0130b8bd1fc48e96c1e66e8a50c71faea83979b3/pyzmq-27.3.0-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:d292cedc7250db240e9f41994cf3eefe2c7606c702ef5c56aab8d4f03870108c", size = 1271939, upload-time = "2026-11-04T00:29:36.803Z" }, - { url = "https://files.pythonhosted.org/packages/f6/43/2bfa60b57b3febd892d5760c811012b6850306962e3dd6a2f91b96cd5398/pyzmq-27.3.0-cp314-cp314t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:924f870055c05926887157485efe903c8f9668d0f3f19d56df7612bcb3d662cb", size = 779903, upload-time = "2026-11-04T00:29:38.52Z" }, - { url = "https://files.pythonhosted.org/packages/e3/72/4f88cd0d1da0e5db9a26a899e37f8b46d925f328f9bae590f86fc995074b/pyzmq-27.3.0-cp314-cp314t-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6dac496cd8aacf185a634e5cc8930331db1627dd214a58ee4c27948ce4ae79af", size = 864708, upload-time = "2026-11-04T00:29:50.209Z" }, - { url = "https://files.pythonhosted.org/packages/79/5e/fce842845aad4135a2e1936f3cd1a418b4f49e2d45cd7b5576d6f836d95b/pyzmq-27.3.0-cp314-cp314t-manylinux_2_28_i686.whl", hash = "sha256:665b1a3d35a4ffe6cfa626191a5439108159d51d17bd9d44f1beb1690114adfc", size = 927234, upload-time = "2026-11-04T00:29:52.003Z" }, - { url = "https://files.pythonhosted.org/packages/e1/28/945736083a00750e101c4259312b5303aead36ef08539a0f0ad93a1cb899/pyzmq-27.3.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:0fedab58520a5091ffa62547eb507bea44882ce72d49929fa9626061ae1b9a2c", size = 1771921, upload-time = "2026-11-04T00:29:53.677Z" }, - { url = "https://files.pythonhosted.org/packages/3d/30/2a584e845a51c0e5d6e13889fe659aa90912004fbb5bc4750491f558528c/pyzmq-27.3.0-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:1b9b9d11e2e775a81d0e8b5c6cb76a395ddaa7c6b6373f3b0d2c8f8146d95f4a", size = 2075396, upload-time = "2026-11-04T00:29:55.772Z" }, - { url = "https://files.pythonhosted.org/packages/4e/6b/93066f121c31b825c56c74dca01ea5c00847f8b44645ad990f92bd04d29c/pyzmq-27.3.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:169a522c4d166c3bc7b67ed827d3beda549a8e65c4015c9410687757fb39852f", size = 1903986, upload-time = "2026-11-04T00:29:57.741Z" }, - { url = "https://files.pythonhosted.org/packages/85/ae/ecc7c77cd6ea18ff7b2b07a2fd0db5c31c2204ecf9a774e80bd1250dc9d9/pyzmq-27.3.0-cp314-cp314t-win32.whl", hash = "sha256:0228fe121f05a8b638ef218dde7508477a8c46200a588f71ce7143d85987cdd7", size = 597206, upload-time = "2026-11-04T00:29:59.35Z" }, - { url = "https://files.pythonhosted.org/packages/7a/1d/0bee73e1e8ab1c26eecba13a4725dfbe0405b53f451a91671dd515effe00/pyzmq-27.3.0-cp314-cp314t-win_amd64.whl", hash = "sha256:8a3d02fc710302a23c9a67b287bc13f2992067d398c3192b50eb0e30d44ed885", size = 685132, upload-time = "2026-11-04T00:30:01.144Z" }, - { url = "https://files.pythonhosted.org/packages/cd/23/13a768f9a8e66a999250abd216e50e1961a1cd4a8708749f656f5c0c2aea/pyzmq-27.3.0-cp314-cp314t-win_arm64.whl", hash = "sha256:2b9f08778b608fe4f6250e2d132f41b4f99fa8d03051cf2809b1c0420def81b4", size = 595549, upload-time = "2026-11-04T00:30:02.693Z" }, - { url = "https://files.pythonhosted.org/packages/91/ac/674d5c512c196c3ff2c37b27ce87764e9e69c7591902ef48330ff0ebfc07/pyzmq-27.3.0-cp315-cp315-android_24_arm64_v8a.whl", hash = "sha256:81fcd4e798f384a158b1790171a63541e66ccdee5a139a4dd0848a6e88dc7b9e", size = 1143291, upload-time = "2026-11-04T00:30:04.411Z" }, - { url = "https://files.pythonhosted.org/packages/c1/eb/6bf15cb88fb5d9f8fe6ee6b57185c110f862b6bc1ad02772767571bd3c5c/pyzmq-27.3.0-cp315-cp315-android_24_x86_64.whl", hash = "sha256:e9b87a6f40b62c7cd47691fc2ba4fdc28bef58f5fccf48eaf39940d183d2a16c", size = 1181899, upload-time = "2026-11-04T00:30:05.993Z" }, - { url = "https://files.pythonhosted.org/packages/2c/bc/e00cf032d751a709e12d71c3e2e265957bfb0097d8d071fae4f6a45e2d4c/pyzmq-27.3.0-cp315-cp315t-macosx_10_15_universal2.whl", hash = "sha256:23ddfe5d4d0c6ea529614c8999065d609a113f343c7e60dda9746d7dcb00d766", size = 1270101, upload-time = "2026-11-04T00:30:07.977Z" }, - { url = "https://files.pythonhosted.org/packages/20/aa/87ebb4664bb27fa53382d45f21f9f49d6194c0eb6737d7c2c5d5e921f1ee/pyzmq-27.3.0-cp315-cp315t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b437cf437fe737e17082625f470258f12e4bf5d56edfb88cb21d3aa4089fcef9", size = 779378, upload-time = "2026-11-04T00:30:10.504Z" }, - { url = "https://files.pythonhosted.org/packages/c1/85/e998ff27a29aca9b0f8529e32b0913420e75f8f990a54ad9434faa3d4c5e/pyzmq-27.3.0-cp315-cp315t-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bc2cc98f37a14a3c9baccc18173a9fca9c6d18ffb233bca7079e58b2e47ee7f8", size = 864317, upload-time = "2026-11-04T00:30:12.259Z" }, - { url = "https://files.pythonhosted.org/packages/d6/7a/6535a0b2fbde9554291caeb3c41b6452207ed7afeb910af830f48e6731f5/pyzmq-27.3.0-cp315-cp315t-manylinux_2_28_i686.whl", hash = "sha256:1a1e092726596141e8ad2cc7f542fd366ddd692b8a9e254d2972ac47b399b982", size = 926240, upload-time = "2026-11-04T00:30:13.862Z" }, - { url = "https://files.pythonhosted.org/packages/51/6f/0c3b1b621f17ebd3eaa2c974b11507dc88cef529ebdc72b42935d00e4a90/pyzmq-27.3.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:0c9c332883373eb85b72f4d912a9a4402ba7702709fa783d3c76ff2bd703a491", size = 1771499, upload-time = "2026-11-04T00:30:15.471Z" }, - { url = "https://files.pythonhosted.org/packages/e1/a5/b753eb9acc131fbb4da67c4c68037965f12f8782d1fd5e461e803e0a1dc1/pyzmq-27.3.0-cp315-cp315t-musllinux_1_2_i686.whl", hash = "sha256:1f724caa222b1ae3c48f7d25147c816c8bde56fb109c164a650f0502b9005ab6", size = 2074632, upload-time = "2026-11-04T00:30:17.149Z" }, - { url = "https://files.pythonhosted.org/packages/d1/ad/8bce8d0ff0f0cc0958bdfeebbde9ee319cbd025c949607ab2864df657ce6/pyzmq-27.3.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:129ca693e543940527e105144dcacdf9e0ec01d41421098e08893de8227aca58", size = 1903559, upload-time = "2026-11-04T00:30:19.142Z" }, - { url = "https://files.pythonhosted.org/packages/fd/25/e5b3e6a066b59840cdc0ea6de8244b1a50b5f237edc7b7adc0e085973708/pyzmq-27.3.0-cp315-cp315t-win32.whl", hash = "sha256:39b9ff1fbab854ccbc53da0e79cb6b78b61b470fb7c191b89aa034825ea9a883", size = 596443, upload-time = "2026-11-04T00:30:20.811Z" }, - { url = "https://files.pythonhosted.org/packages/3f/c8/20ecc504500aeaab0440a4c8487a3c1cd32f4ac38f3e92482f1671fcaeca/pyzmq-27.3.0-cp315-cp315t-win_amd64.whl", hash = "sha256:3b850eaa955ae7edb926fe266600e57da818255d1f6ee9c3d8049967aa4a22cc", size = 684767, upload-time = "2026-11-04T00:30:22.784Z" }, - { url = "https://files.pythonhosted.org/packages/e8/5d/33c528d9b7ee074d0807e3af1a23a3e50bfdbe28cbc178e99f0466c13648/pyzmq-27.3.0-cp315-cp315t-win_arm64.whl", hash = "sha256:f0b9d192b285a9d38e390e762011f2672432742a301859b6c8cb4fab5f10f687", size = 594143, upload-time = "2026-11-04T00:30:24.33Z" }, - { url = "https://files.pythonhosted.org/packages/67/36/04666a943685abde486ca045701ee9443b1a698e31c0e5d29be965087164/pyzmq-27.3.0-pp311-pypy311_pp80-macosx_10_15_x86_64.whl", hash = "sha256:78157e57c734e8fc6dbf28c76aafc2cd7e871780fc661825c75e0afdc3424a82", size = 689539, upload-time = "2026-11-04T00:30:57.5Z" }, - { url = "https://files.pythonhosted.org/packages/e3/22/ad080fd18de3e6b1618029c8166895991a765f39bd489c32c1ff46f15778/pyzmq-27.3.0-pp311-pypy311_pp80-macosx_11_0_arm64.whl", hash = "sha256:8f15e7f2b5cc6459c45619e06e61f02fd1d9138b677b56e7a677232251a873b7", size = 632029, upload-time = "2026-11-04T00:30:59.361Z" }, - { url = "https://files.pythonhosted.org/packages/1c/45/08e946778c08c1989abade2ed86687114bb6fb22218521f68c7e9fb3eb4c/pyzmq-27.3.0-pp311-pypy311_pp80-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ae989940ebc279e81821bad87864119b9ab179e5abd50fe642dfb425f0eb2f92", size = 684299, upload-time = "2026-11-04T00:31:05.898Z" }, - { url = "https://files.pythonhosted.org/packages/08/6d/00f9a4e5c17135cca4126fdc60df9a397066fcd8ba390dc11cc07ad5a5ed/pyzmq-27.3.0-pp311-pypy311_pp80-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:2ad3ec36c9d107ef33063d167ce07d9066ff92eba23385e320f1c2472437bb8a", size = 761485, upload-time = "2026-11-04T00:31:07.551Z" }, - { url = "https://files.pythonhosted.org/packages/27/18/c66e01646180e453216df42ef6274bddba3f4be412997b82de790bedf6d2/pyzmq-27.3.0-pp311-pypy311_pp80-manylinux_2_28_i686.whl", hash = "sha256:487dc31c44c16cfb5e78ae65a187d25fa82e59d1efad0595b6e79eadc4750c68", size = 821380, upload-time = "2026-11-04T00:31:09.209Z" }, - { url = "https://files.pythonhosted.org/packages/c8/be/aeaef2cfdded411909ce556631e029761dccce49cb2a078162a4d04416be/pyzmq-27.3.0-pp311-pypy311_pp80-win_amd64.whl", hash = "sha256:c72f9b1f6dbaf760daea97082506f4d6fd682a8512dbd320986b5268b189e727", size = 564188, upload-time = "2026-11-04T00:31:10.758Z" }, - { url = "https://files.pythonhosted.org/packages/53/53/6ea90b8bb4c77bcc4babd15ef6a63ed243cfd47920cb270da5f29438d11f/pyzmq-27.3.0-pp312-pypy312_pp80-macosx_10_15_x86_64.whl", hash = "sha256:cff2031014f79b213818b6773253cbf330119c93de33ee1a635596f407da5c35", size = 689536, upload-time = "2026-11-04T00:31:12.423Z" }, - { url = "https://files.pythonhosted.org/packages/a1/9e/699898cdd86e4cd4bc20547b9f1bce24c58900f51e6a9d5fad03c2890407/pyzmq-27.3.0-pp312-pypy312_pp80-macosx_11_0_arm64.whl", hash = "sha256:18da98ce26045ef503b42a3f98fc2a2af0cdb2af87dc0594852fa5cea3795427", size = 632027, upload-time = "2026-11-04T00:31:14.338Z" }, - { url = "https://files.pythonhosted.org/packages/a6/59/5d6ccce5456cafbdf84c98141d3ddf6c073716eb7b958254349e047fad84/pyzmq-27.3.0-pp312-pypy312_pp80-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:13c7336a4112d3e09c5d78d17e17af1cd01da858ec1c5e3755b2d06339aa7d4f", size = 684300, upload-time = "2026-11-04T00:31:15.891Z" }, - { url = "https://files.pythonhosted.org/packages/b4/37/c4cf124d820495c5549b3f606b1292949c9e2053467309a7e1baaf0c3784/pyzmq-27.3.0-pp312-pypy312_pp80-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:51e1358fabf41920d69cab170495b6e263680797ac5b80ace1b5cf1eb2d89642", size = 761485, upload-time = "2026-11-04T00:31:17.817Z" }, - { url = "https://files.pythonhosted.org/packages/a7/cf/caa0bd5f7a1b139b9240faf3b34586867656f682774364101572e8e84f80/pyzmq-27.3.0-pp312-pypy312_pp80-manylinux_2_28_i686.whl", hash = "sha256:cdb5efd4c23465573e928fb8429e40996ac0e1a4809365efe19e2753112b6ee1", size = 821382, upload-time = "2026-11-04T00:31:19.451Z" }, - { url = "https://files.pythonhosted.org/packages/8e/34/81fa1d9701024eb4f48949ba5f93da3a063ab997e0e0c9787ff37f11ecda/pyzmq-27.3.0-pp312-pypy312_pp80-win_amd64.whl", hash = "sha256:1b7ab96158dd50d7e6e430e6e4f744aaccee1df2e9d167ace9e7d2f3e3051712", size = 564187, upload-time = "2026-11-04T00:31:21.486Z" }, -] - -[[package]] -name = "scipy" -version = "1.17.1" -source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version < '3.12'", -] -dependencies = [ - { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" } }, -] -sdist = { url = "https://files.pythonhosted.org/packages/7a/97/5a3609c4f8d58b039179648e62dd220f89864f56f7357f5d4f45c29eb2cc/scipy-1.17.1.tar.gz", hash = "sha256:95d8e012d8cb8816c226aef832200b1d45109ed4464303e997c5b13122b297c0", size = 30573822, upload-time = "2026-02-23T00:26:24.851Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/df/75/b4ce781849931fef6fd529afa6b63711d5a733065722d0c3e2724af9e40a/scipy-1.17.1-cp311-cp311-macosx_10_14_x86_64.whl", hash = "sha256:1f95b894f13729334fb990162e911c9e5dc1ab390c58aa6cbecb389c5b5e28ec", size = 31613675, upload-time = "2026-02-23T00:16:00.13Z" }, - { url = "https://files.pythonhosted.org/packages/f7/58/bccc2861b305abdd1b8663d6130c0b3d7cc22e8d86663edbc8401bfd40d4/scipy-1.17.1-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:e18f12c6b0bc5a592ed23d3f7b891f68fd7f8241d69b7883769eb5d5dfb52696", size = 28162057, upload-time = "2026-02-23T00:16:09.456Z" }, - { url = "https://files.pythonhosted.org/packages/6d/ee/18146b7757ed4976276b9c9819108adbc73c5aad636e5353e20746b73069/scipy-1.17.1-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:a3472cfbca0a54177d0faa68f697d8ba4c80bbdc19908c3465556d9f7efce9ee", size = 20334032, upload-time = "2026-02-23T00:16:17.358Z" }, - { url = "https://files.pythonhosted.org/packages/ec/e6/cef1cf3557f0c54954198554a10016b6a03b2ec9e22a4e1df734936bd99c/scipy-1.17.1-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:766e0dc5a616d026a3a1cffa379af959671729083882f50307e18175797b3dfd", size = 22709533, upload-time = "2026-02-23T00:16:25.791Z" }, - { url = "https://files.pythonhosted.org/packages/4d/60/8804678875fc59362b0fb759ab3ecce1f09c10a735680318ac30da8cd76b/scipy-1.17.1-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:744b2bf3640d907b79f3fd7874efe432d1cf171ee721243e350f55234b4cec4c", size = 33062057, upload-time = "2026-02-23T00:16:36.931Z" }, - { url = "https://files.pythonhosted.org/packages/09/7d/af933f0f6e0767995b4e2d705a0665e454d1c19402aa7e895de3951ebb04/scipy-1.17.1-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:43af8d1f3bea642559019edfe64e9b11192a8978efbd1539d7bc2aaa23d92de4", size = 35349300, upload-time = "2026-02-23T00:16:49.108Z" }, - { url = "https://files.pythonhosted.org/packages/b4/3d/7ccbbdcbb54c8fdc20d3b6930137c782a163fa626f0aef920349873421ba/scipy-1.17.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:cd96a1898c0a47be4520327e01f874acfd61fb48a9420f8aa9f6483412ffa444", size = 35127333, upload-time = "2026-02-23T00:17:01.293Z" }, - { url = "https://files.pythonhosted.org/packages/e8/19/f926cb11c42b15ba08e3a71e376d816ac08614f769b4f47e06c3580c836a/scipy-1.17.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:4eb6c25dd62ee8d5edf68a8e1c171dd71c292fdae95d8aeb3dd7d7de4c364082", size = 37741314, upload-time = "2026-02-23T00:17:12.576Z" }, - { url = "https://files.pythonhosted.org/packages/95/da/0d1df507cf574b3f224ccc3d45244c9a1d732c81dcb26b1e8a766ae271a8/scipy-1.17.1-cp311-cp311-win_amd64.whl", hash = "sha256:d30e57c72013c2a4fe441c2fcb8e77b14e152ad48b5464858e07e2ad9fbfceff", size = 36607512, upload-time = "2026-02-23T00:17:23.424Z" }, - { url = "https://files.pythonhosted.org/packages/68/7f/bdd79ceaad24b671543ffe0ef61ed8e659440eb683b66f033454dcee90eb/scipy-1.17.1-cp311-cp311-win_arm64.whl", hash = "sha256:9ecb4efb1cd6e8c4afea0daa91a87fbddbce1b99d2895d151596716c0b2e859d", size = 24599248, upload-time = "2026-02-23T00:17:34.561Z" }, - { url = "https://files.pythonhosted.org/packages/35/48/b992b488d6f299dbe3f11a20b24d3dda3d46f1a635ede1c46b5b17a7b163/scipy-1.17.1-cp312-cp312-macosx_10_14_x86_64.whl", hash = "sha256:35c3a56d2ef83efc372eaec584314bd0ef2e2f0d2adb21c55e6ad5b344c0dcb8", size = 31610954, upload-time = "2026-02-23T00:17:49.855Z" }, - { url = "https://files.pythonhosted.org/packages/b2/02/cf107b01494c19dc100f1d0b7ac3cc08666e96ba2d64db7626066cee895e/scipy-1.17.1-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:fcb310ddb270a06114bb64bbe53c94926b943f5b7f0842194d585c65eb4edd76", size = 28172662, upload-time = "2026-02-23T00:18:01.64Z" }, - { url = "https://files.pythonhosted.org/packages/cf/a9/599c28631bad314d219cf9ffd40e985b24d603fc8a2f4ccc5ae8419a535b/scipy-1.17.1-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:cc90d2e9c7e5c7f1a482c9875007c095c3194b1cfedca3c2f3291cdc2bc7c086", size = 20344366, upload-time = "2026-02-23T00:18:12.015Z" }, - { url = "https://files.pythonhosted.org/packages/35/f5/906eda513271c8deb5af284e5ef0206d17a96239af79f9fa0aebfe0e36b4/scipy-1.17.1-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:c80be5ede8f3f8eded4eff73cc99a25c388ce98e555b17d31da05287015ffa5b", size = 22704017, upload-time = "2026-02-23T00:18:21.502Z" }, - { url = "https://files.pythonhosted.org/packages/da/34/16f10e3042d2f1d6b66e0428308ab52224b6a23049cb2f5c1756f713815f/scipy-1.17.1-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e19ebea31758fac5893a2ac360fedd00116cbb7628e650842a6691ba7ca28a21", size = 32927842, upload-time = "2026-02-23T00:18:35.367Z" }, - { url = "https://files.pythonhosted.org/packages/01/8e/1e35281b8ab6d5d72ebe9911edcdffa3f36b04ed9d51dec6dd140396e220/scipy-1.17.1-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:02ae3b274fde71c5e92ac4d54bc06c42d80e399fec704383dcd99b301df37458", size = 35235890, upload-time = "2026-02-23T00:18:49.188Z" }, - { url = "https://files.pythonhosted.org/packages/c5/5c/9d7f4c88bea6e0d5a4f1bc0506a53a00e9fcb198de372bfe4d3652cef482/scipy-1.17.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:8a604bae87c6195d8b1045eddece0514d041604b14f2727bbc2b3020172045eb", size = 35003557, upload-time = "2026-02-23T00:18:54.74Z" }, - { url = "https://files.pythonhosted.org/packages/65/94/7698add8f276dbab7a9de9fb6b0e02fc13ee61d51c7c3f85ac28b65e1239/scipy-1.17.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:f590cd684941912d10becc07325a3eeb77886fe981415660d9265c4c418d0bea", size = 37625856, upload-time = "2026-02-23T00:19:00.307Z" }, - { url = "https://files.pythonhosted.org/packages/a2/84/dc08d77fbf3d87d3ee27f6a0c6dcce1de5829a64f2eae85a0ecc1f0daa73/scipy-1.17.1-cp312-cp312-win_amd64.whl", hash = "sha256:41b71f4a3a4cab9d366cd9065b288efc4d4f3c0b37a91a8e0947fb5bd7f31d87", size = 36549682, upload-time = "2026-02-23T00:19:07.67Z" }, - { url = "https://files.pythonhosted.org/packages/bc/98/fe9ae9ffb3b54b62559f52dedaebe204b408db8109a8c66fdd04869e6424/scipy-1.17.1-cp312-cp312-win_arm64.whl", hash = "sha256:f4115102802df98b2b0db3cce5cb9b92572633a1197c77b7553e5203f284a5b3", size = 24547340, upload-time = "2026-02-23T00:19:12.024Z" }, - { url = "https://files.pythonhosted.org/packages/76/27/07ee1b57b65e92645f219b37148a7e7928b82e2b5dbeccecb4dff7c64f0b/scipy-1.17.1-cp313-cp313-macosx_10_14_x86_64.whl", hash = "sha256:5e3c5c011904115f88a39308379c17f91546f77c1667cea98739fe0fccea804c", size = 31590199, upload-time = "2026-02-23T00:19:17.192Z" }, - { url = "https://files.pythonhosted.org/packages/ec/ae/db19f8ab842e9b724bf5dbb7db29302a91f1e55bc4d04b1025d6d605a2c5/scipy-1.17.1-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:6fac755ca3d2c3edcb22f479fceaa241704111414831ddd3bc6056e18516892f", size = 28154001, upload-time = "2026-02-23T00:19:22.241Z" }, - { url = "https://files.pythonhosted.org/packages/5b/58/3ce96251560107b381cbd6e8413c483bbb1228a6b919fa8652b0d4090e7f/scipy-1.17.1-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:7ff200bf9d24f2e4d5dc6ee8c3ac64d739d3a89e2326ba68aaf6c4a2b838fd7d", size = 20325719, upload-time = "2026-02-23T00:19:26.329Z" }, - { url = "https://files.pythonhosted.org/packages/b2/83/15087d945e0e4d48ce2377498abf5ad171ae013232ae31d06f336e64c999/scipy-1.17.1-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:4b400bdc6f79fa02a4d86640310dde87a21fba0c979efff5248908c6f15fad1b", size = 22683595, upload-time = "2026-02-23T00:19:30.304Z" }, - { url = "https://files.pythonhosted.org/packages/b4/e0/e58fbde4a1a594c8be8114eb4aac1a55bcd6587047efc18a61eb1f5c0d30/scipy-1.17.1-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2b64ca7d4aee0102a97f3ba22124052b4bd2152522355073580bf4845e2550b6", size = 32896429, upload-time = "2026-02-23T00:19:35.536Z" }, - { url = "https://files.pythonhosted.org/packages/f5/5f/f17563f28ff03c7b6799c50d01d5d856a1d55f2676f537ca8d28c7f627cd/scipy-1.17.1-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:581b2264fc0aa555f3f435a5944da7504ea3a065d7029ad60e7c3d1ae09c5464", size = 35203952, upload-time = "2026-02-23T00:19:42.259Z" }, - { url = "https://files.pythonhosted.org/packages/8d/a5/9afd17de24f657fdfe4df9a3f1ea049b39aef7c06000c13db1530d81ccca/scipy-1.17.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:beeda3d4ae615106d7094f7e7cef6218392e4465cc95d25f900bebabfded0950", size = 34979063, upload-time = "2026-02-23T00:19:47.547Z" }, - { url = "https://files.pythonhosted.org/packages/8b/13/88b1d2384b424bf7c924f2038c1c409f8d88bb2a8d49d097861dd64a57b2/scipy-1.17.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:6609bc224e9568f65064cfa72edc0f24ee6655b47575954ec6339534b2798369", size = 37598449, upload-time = "2026-02-23T00:19:53.238Z" }, - { url = "https://files.pythonhosted.org/packages/35/e5/d6d0e51fc888f692a35134336866341c08655d92614f492c6860dc45bb2c/scipy-1.17.1-cp313-cp313-win_amd64.whl", hash = "sha256:37425bc9175607b0268f493d79a292c39f9d001a357bebb6b88fdfaff13f6448", size = 36510943, upload-time = "2026-02-23T00:20:50.89Z" }, - { url = "https://files.pythonhosted.org/packages/2a/fd/3be73c564e2a01e690e19cc618811540ba5354c67c8680dce3281123fb79/scipy-1.17.1-cp313-cp313-win_arm64.whl", hash = "sha256:5cf36e801231b6a2059bf354720274b7558746f3b1a4efb43fcf557ccd484a87", size = 24545621, upload-time = "2026-02-23T00:20:55.871Z" }, - { url = "https://files.pythonhosted.org/packages/6f/6b/17787db8b8114933a66f9dcc479a8272e4b4da75fe03b0c282f7b0ade8cd/scipy-1.17.1-cp313-cp313t-macosx_10_14_x86_64.whl", hash = "sha256:d59c30000a16d8edc7e64152e30220bfbd724c9bbb08368c054e24c651314f0a", size = 31936708, upload-time = "2026-02-23T00:19:58.694Z" }, - { url = "https://files.pythonhosted.org/packages/38/2e/524405c2b6392765ab1e2b722a41d5da33dc5c7b7278184a8ad29b6cb206/scipy-1.17.1-cp313-cp313t-macosx_12_0_arm64.whl", hash = "sha256:010f4333c96c9bb1a4516269e33cb5917b08ef2166d5556ca2fd9f082a9e6ea0", size = 28570135, upload-time = "2026-02-23T00:20:03.934Z" }, - { url = "https://files.pythonhosted.org/packages/fd/c3/5bd7199f4ea8556c0c8e39f04ccb014ac37d1468e6cfa6a95c6b3562b76e/scipy-1.17.1-cp313-cp313t-macosx_14_0_arm64.whl", hash = "sha256:2ceb2d3e01c5f1d83c4189737a42d9cb2fc38a6eeed225e7515eef71ad301dce", size = 20741977, upload-time = "2026-02-23T00:20:07.935Z" }, - { url = "https://files.pythonhosted.org/packages/d9/b8/8ccd9b766ad14c78386599708eb745f6b44f08400a5fd0ade7cf89b6fc93/scipy-1.17.1-cp313-cp313t-macosx_14_0_x86_64.whl", hash = "sha256:844e165636711ef41f80b4103ed234181646b98a53c8f05da12ca5ca289134f6", size = 23029601, upload-time = "2026-02-23T00:20:12.161Z" }, - { url = "https://files.pythonhosted.org/packages/6d/a0/3cb6f4d2fb3e17428ad2880333cac878909ad1a89f678527b5328b93c1d4/scipy-1.17.1-cp313-cp313t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:158dd96d2207e21c966063e1635b1063cd7787b627b6f07305315dd73d9c679e", size = 33019667, upload-time = "2026-02-23T00:20:17.208Z" }, - { url = "https://files.pythonhosted.org/packages/f3/c3/2d834a5ac7bf3a0c806ad1508efc02dda3c8c61472a56132d7894c312dea/scipy-1.17.1-cp313-cp313t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:74cbb80d93260fe2ffa334efa24cb8f2f0f622a9b9febf8b483c0b865bfb3475", size = 35264159, upload-time = "2026-02-23T00:20:23.087Z" }, - { url = "https://files.pythonhosted.org/packages/4d/77/d3ed4becfdbd217c52062fafe35a72388d1bd82c2d0ba5ca19d6fcc93e11/scipy-1.17.1-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:dbc12c9f3d185f5c737d801da555fb74b3dcfa1a50b66a1a93e09190f41fab50", size = 35102771, upload-time = "2026-02-23T00:20:28.636Z" }, - { url = "https://files.pythonhosted.org/packages/bd/12/d19da97efde68ca1ee5538bb261d5d2c062f0c055575128f11a2730e3ac1/scipy-1.17.1-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:94055a11dfebe37c656e70317e1996dc197e1a15bbcc351bcdd4610e128fe1ca", size = 37665910, upload-time = "2026-02-23T00:20:34.743Z" }, - { url = "https://files.pythonhosted.org/packages/06/1c/1172a88d507a4baaf72c5a09bb6c018fe2ae0ab622e5830b703a46cc9e44/scipy-1.17.1-cp313-cp313t-win_amd64.whl", hash = "sha256:e30bdeaa5deed6bc27b4cc490823cd0347d7dae09119b8803ae576ea0ce52e4c", size = 36562980, upload-time = "2026-02-23T00:20:40.575Z" }, - { url = "https://files.pythonhosted.org/packages/70/b0/eb757336e5a76dfa7911f63252e3b7d1de00935d7705cf772db5b45ec238/scipy-1.17.1-cp313-cp313t-win_arm64.whl", hash = "sha256:a720477885a9d2411f94a93d16f9d89bad0f28ca23c3f8daa521e2dcc3f44d49", size = 24856543, upload-time = "2026-02-23T00:20:45.313Z" }, - { url = "https://files.pythonhosted.org/packages/cf/83/333afb452af6f0fd70414dc04f898647ee1423979ce02efa75c3b0f2c28e/scipy-1.17.1-cp314-cp314-macosx_10_14_x86_64.whl", hash = "sha256:a48a72c77a310327f6a3a920092fa2b8fd03d7deaa60f093038f22d98e096717", size = 31584510, upload-time = "2026-02-23T00:21:01.015Z" }, - { url = "https://files.pythonhosted.org/packages/ed/a6/d05a85fd51daeb2e4ea71d102f15b34fedca8e931af02594193ae4fd25f7/scipy-1.17.1-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:45abad819184f07240d8a696117a7aacd39787af9e0b719d00285549ed19a1e9", size = 28170131, upload-time = "2026-02-23T00:21:05.888Z" }, - { url = "https://files.pythonhosted.org/packages/db/7b/8624a203326675d7746a254083a187398090a179335b2e4a20e2ddc46e83/scipy-1.17.1-cp314-cp314-macosx_14_0_arm64.whl", hash = "sha256:3fd1fcdab3ea951b610dc4cef356d416d5802991e7e32b5254828d342f7b7e0b", size = 20342032, upload-time = "2026-02-23T00:21:09.904Z" }, - { url = "https://files.pythonhosted.org/packages/c9/35/2c342897c00775d688d8ff3987aced3426858fd89d5a0e26e020b660b301/scipy-1.17.1-cp314-cp314-macosx_14_0_x86_64.whl", hash = "sha256:7bdf2da170b67fdf10bca777614b1c7d96ae3ca5794fd9587dce41eb2966e866", size = 22678766, upload-time = "2026-02-23T00:21:14.313Z" }, - { url = "https://files.pythonhosted.org/packages/ef/f2/7cdb8eb308a1a6ae1e19f945913c82c23c0c442a462a46480ce487fdc0ac/scipy-1.17.1-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:adb2642e060a6549c343603a3851ba76ef0b74cc8c079a9a58121c7ec9fe2350", size = 32957007, upload-time = "2026-02-23T00:21:19.663Z" }, - { url = "https://files.pythonhosted.org/packages/0b/2e/7eea398450457ecb54e18e9d10110993fa65561c4f3add5e8eccd2b9cd41/scipy-1.17.1-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:eee2cfda04c00a857206a4330f0c5e3e56535494e30ca445eb19ec624ae75118", size = 35221333, upload-time = "2026-02-23T00:21:25.278Z" }, - { url = "https://files.pythonhosted.org/packages/d9/77/5b8509d03b77f093a0d52e606d3c4f79e8b06d1d38c441dacb1e26cacf46/scipy-1.17.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:d2650c1fb97e184d12d8ba010493ee7b322864f7d3d00d3f9bb97d9c21de4068", size = 35042066, upload-time = "2026-02-23T00:21:31.358Z" }, - { url = "https://files.pythonhosted.org/packages/f9/df/18f80fb99df40b4070328d5ae5c596f2f00fffb50167e31439e932f29e7d/scipy-1.17.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:08b900519463543aa604a06bec02461558a6e1cef8fdbb8098f77a48a83c8118", size = 37612763, upload-time = "2026-02-23T00:21:37.247Z" }, - { url = "https://files.pythonhosted.org/packages/4b/39/f0e8ea762a764a9dc52aa7dabcfad51a354819de1f0d4652b6a1122424d6/scipy-1.17.1-cp314-cp314-win_amd64.whl", hash = "sha256:3877ac408e14da24a6196de0ddcace62092bfc12a83823e92e49e40747e52c19", size = 37290984, upload-time = "2026-02-23T00:22:35.023Z" }, - { url = "https://files.pythonhosted.org/packages/7c/56/fe201e3b0f93d1a8bcf75d3379affd228a63d7e2d80ab45467a74b494947/scipy-1.17.1-cp314-cp314-win_arm64.whl", hash = "sha256:f8885db0bc2bffa59d5c1b72fad7a6a92d3e80e7257f967dd81abb553a90d293", size = 25192877, upload-time = "2026-02-23T00:22:39.798Z" }, - { url = "https://files.pythonhosted.org/packages/96/ad/f8c414e121f82e02d76f310f16db9899c4fcde36710329502a6b2a3c0392/scipy-1.17.1-cp314-cp314t-macosx_10_14_x86_64.whl", hash = "sha256:1cc682cea2ae55524432f3cdff9e9a3be743d52a7443d0cba9017c23c87ae2f6", size = 31949750, upload-time = "2026-02-23T00:21:42.289Z" }, - { url = "https://files.pythonhosted.org/packages/7c/b0/c741e8865d61b67c81e255f4f0a832846c064e426636cd7de84e74d209be/scipy-1.17.1-cp314-cp314t-macosx_12_0_arm64.whl", hash = "sha256:2040ad4d1795a0ae89bfc7e8429677f365d45aa9fd5e4587cf1ea737f927b4a1", size = 28585858, upload-time = "2026-02-23T00:21:47.706Z" }, - { url = "https://files.pythonhosted.org/packages/ed/1b/3985219c6177866628fa7c2595bfd23f193ceebbe472c98a08824b9466ff/scipy-1.17.1-cp314-cp314t-macosx_14_0_arm64.whl", hash = "sha256:131f5aaea57602008f9822e2115029b55d4b5f7c070287699fe45c661d051e39", size = 20757723, upload-time = "2026-02-23T00:21:52.039Z" }, - { url = "https://files.pythonhosted.org/packages/c0/19/2a04aa25050d656d6f7b9e7b685cc83d6957fb101665bfd9369ca6534563/scipy-1.17.1-cp314-cp314t-macosx_14_0_x86_64.whl", hash = "sha256:9cdc1a2fcfd5c52cfb3045feb399f7b3ce822abdde3a193a6b9a60b3cb5854ca", size = 23043098, upload-time = "2026-02-23T00:21:56.185Z" }, - { url = "https://files.pythonhosted.org/packages/86/f1/3383beb9b5d0dbddd030335bf8a8b32d4317185efe495374f134d8be6cce/scipy-1.17.1-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6e3dcd57ab780c741fde8dc68619de988b966db759a3c3152e8e9142c26295ad", size = 33030397, upload-time = "2026-02-23T00:22:01.404Z" }, - { url = "https://files.pythonhosted.org/packages/41/68/8f21e8a65a5a03f25a79165ec9d2b28c00e66dc80546cf5eb803aeeff35b/scipy-1.17.1-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a9956e4d4f4a301ebf6cde39850333a6b6110799d470dbbb1e25326ac447f52a", size = 35281163, upload-time = "2026-02-23T00:22:07.024Z" }, - { url = "https://files.pythonhosted.org/packages/84/8d/c8a5e19479554007a5632ed7529e665c315ae7492b4f946b0deb39870e39/scipy-1.17.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:a4328d245944d09fd639771de275701ccadf5f781ba0ff092ad141e017eccda4", size = 35116291, upload-time = "2026-02-23T00:22:12.585Z" }, - { url = "https://files.pythonhosted.org/packages/52/52/e57eceff0e342a1f50e274264ed47497b59e6a4e3118808ee58ddda7b74a/scipy-1.17.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:a77cbd07b940d326d39a1d1b37817e2ee4d79cb30e7338f3d0cddffae70fcaa2", size = 37682317, upload-time = "2026-02-23T00:22:18.513Z" }, - { url = "https://files.pythonhosted.org/packages/11/2f/b29eafe4a3fbc3d6de9662b36e028d5f039e72d345e05c250e121a230dd4/scipy-1.17.1-cp314-cp314t-win_amd64.whl", hash = "sha256:eb092099205ef62cd1782b006658db09e2fed75bffcae7cc0d44052d8aa0f484", size = 37345327, upload-time = "2026-02-23T00:22:24.442Z" }, - { url = "https://files.pythonhosted.org/packages/07/39/338d9219c4e87f3e708f18857ecd24d22a0c3094752393319553096b98af/scipy-1.17.1-cp314-cp314t-win_arm64.whl", hash = "sha256:200e1050faffacc162be6a486a984a0497866ec54149a01270adc8a59b7c7d21", size = 25489165, upload-time = "2026-02-23T00:22:29.563Z" }, -] - -[[package]] -name = "scipy" -version = "1.18.1" -source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version >= '3.12'", -] -dependencies = [ - { name = "numpy", version = "2.5.5", source = { registry = "https://pypi.org/simple" } }, -] -sdist = { url = "https://files.pythonhosted.org/packages/7e/74/66de6258867beb2ef08f35f9f2ac017a52cacd5081714d239ff1a442d458/scipy-1.18.1.tar.gz", hash = "sha256:52c4b7422442aba924d03ad4019852b08a92e64ea187b933135687bfe2747307", size = 30781235, upload-time = "2026-08-21T23:28:50.599Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/18/f7/240c110c08693826b4513a52f5717d62ec7c7af72f2920821247c03b17b3/scipy-1.18.1-cp312-cp312-macosx_10_15_x86_64.whl", hash = "sha256:457fd7a2a8edeb044ab6ffbc0aa03ff6cd18491356e5e0c834d76ce621b916d1", size = 31111061, upload-time = "2026-08-21T23:23:44.522Z" }, - { url = "https://files.pythonhosted.org/packages/05/4a/78c6285577c375e7cf27277ea8ee6961224327f1e1a0c44af5f17f23635c/scipy-1.18.1-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:e708533e8b2ae2497d65346538a7dcc92814410b25b81432eac66de0f2af8265", size = 28733332, upload-time = "2026-08-21T23:23:50.015Z" }, - { url = "https://files.pythonhosted.org/packages/a5/f6/a5b82f8abbe14d134691b8b903696f701d25a081353a29dc655c364d9e62/scipy-1.18.1-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:7bbf207c4453ce1ad2e00b17313852b33310b83090c2311bdaf97f93c0380d12", size = 20475078, upload-time = "2026-08-21T23:23:54.138Z" }, - { url = "https://files.pythonhosted.org/packages/23/22/0858a0bbd6b3e825ceb8cd9baf9eaf3b2f2b1d77727eb6be40500bcdc92f/scipy-1.18.1-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:78c0665edead396b1abb4897c41a5c1d9bf090c8a637a4c20a61678e0a264e66", size = 23108904, upload-time = "2026-08-21T23:23:57.824Z" }, - { url = "https://files.pythonhosted.org/packages/75/9a/2e71719f31eaefe0e3a1706c4a1ded94e664bfd95ffca2b219a671faee01/scipy-1.18.1-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3c085faa2cfa879c5141df483f836f4d691045a078224a670fa570fa01612d89", size = 34025113, upload-time = "2026-08-21T23:24:02.209Z" }, - { url = "https://files.pythonhosted.org/packages/df/64/ff35eb9e54894cf471ff4716abd3c81eb0a0626869217ce3e6ba4ccf17d7/scipy-1.18.1-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f55fa87b6c612ecd6b058f167c53231b1d14e412efe361d3d6e38b3631c73218", size = 35344199, upload-time = "2026-08-21T23:24:07.844Z" }, - { url = "https://files.pythonhosted.org/packages/d3/af/c5538be1792f7034c12c7db6ee67cace58253c7b87b122d68253eaf5de89/scipy-1.18.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:c35d74ce0e193ff740c2f2be2ac913ddc232fe6c1ff40b26cfecb9c670c63314", size = 35639587, upload-time = "2026-08-21T23:24:13.05Z" }, - { url = "https://files.pythonhosted.org/packages/91/4c/075e4f66471bac101141ac739e9e135549be1bae584571bd03a530c056e1/scipy-1.18.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:d2924a03db38dc2e848bca2fe9f077dafb891480b91a00a0963a8cf86dfc31c1", size = 37480330, upload-time = "2026-08-21T23:24:19.608Z" }, - { url = "https://files.pythonhosted.org/packages/39/e7/979fd14e75008623df31ba70d6bb144700f68feadcea042021c06a05bf82/scipy-1.18.1-cp312-cp312-win_amd64.whl", hash = "sha256:5e4d44984abc0020154ea81b247adeddcc3ac5527b975ff798bd1ba0adc513c2", size = 36658278, upload-time = "2026-08-21T23:24:25.463Z" }, - { url = "https://files.pythonhosted.org/packages/c7/0b/e1525354ff9d7d5feb6d1b31af6d14072e5c91e9607b421fa1ec889660b3/scipy-1.18.1-cp312-cp312-win_arm64.whl", hash = "sha256:d65d448389b8436493abcf629cc94ad0cf32aecaf06e1acca1de53cc795f2f12", size = 24400588, upload-time = "2026-08-21T23:24:30.579Z" }, - { url = "https://files.pythonhosted.org/packages/b6/55/4540ee0f9c42a9ad7109d0d1a8cc70de54c3572b01c6693a2b1c70e90ceb/scipy-1.18.1-cp313-cp313-macosx_10_15_x86_64.whl", hash = "sha256:3ab3523da44749156e1f68b464dc56af11ae4cbc5c739a49d05f32b982eca9f3", size = 31089958, upload-time = "2026-08-21T23:24:35.8Z" }, - { url = "https://files.pythonhosted.org/packages/2a/f5/769f36d14922b8071a43e95d24d18b6bdafad10d7f5cf647867e1ac052bc/scipy-1.18.1-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:e6fb6a55cc0ba97b59a1f288fb86dc6fce8bdfc0fffcbfd015e3a954bf2a2d93", size = 28715106, upload-time = "2026-08-21T23:24:40.775Z" }, - { url = "https://files.pythonhosted.org/packages/9a/d7/21d890274f75ea37a8209d5519e72da3da90302e3b9fb8397a0918386a62/scipy-1.18.1-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:ea324d9dd34c38bfb9bec8ca4d1b407db97dbb74029f566b8e322b1b6fe56fe6", size = 20456846, upload-time = "2026-08-21T23:24:45.066Z" }, - { url = "https://files.pythonhosted.org/packages/ec/01/798430ecea2e78ec7c02663d5f71c007bb6abeca931080debd40d7fa55ea/scipy-1.18.1-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:75b00eb8fb802090aa903f4ea1c7f5a584779f967361e68b7e98e531cc2d7174", size = 23087986, upload-time = "2026-08-21T23:24:49.539Z" }, - { url = "https://files.pythonhosted.org/packages/e6/5f/4634e9d35c68496e4e34cb6946eafab044458e6cedab42b40b6588e475b6/scipy-1.18.1-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d416b16cccfd70fbf62400e84d0bb2f4e6af519a45557f1692c749b37f14b315", size = 33998146, upload-time = "2026-08-21T23:24:54.714Z" }, - { url = "https://files.pythonhosted.org/packages/41/48/6450ed9243315322bbc19ac57b9b70d66a20bf1d38d124c96bc4bf6af9ea/scipy-1.18.1-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:fdaf5ea890a6183d0565f51a61799d67081bd5b1cf03c5f4b3fd3732108625c9", size = 35312578, upload-time = "2026-08-21T23:25:00.44Z" }, - { url = "https://files.pythonhosted.org/packages/00/bd/bf5a4be6a3525676499f6dff307991739ff6fdcad1481b1aeb6745339f58/scipy-1.18.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:c825cef2f49e46753726a7181a8e199804a912b29519ada542c6ebc654951899", size = 35612621, upload-time = "2026-08-21T23:25:06.144Z" }, - { url = "https://files.pythonhosted.org/packages/bd/4e/3c45c33e00a77996c4b1cb707929f833ba7b1d522ee29f882512c330676d/scipy-1.18.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e3b417bf8c2c7c16e8f58ad91db17783ec911ac16e7b50eb6eab6e809b4f5b07", size = 37457323, upload-time = "2026-08-21T23:25:12.483Z" }, - { url = "https://files.pythonhosted.org/packages/93/0e/e0348fbc0dbab65c114cf78957e7dfeb49f8e8b556b4d930cc12ff195e18/scipy-1.18.1-cp313-cp313-win_amd64.whl", hash = "sha256:559ed65f60c1af5a03f3912605a1b5114f522c7c32fb23c3376ae8f03219fe28", size = 36622841, upload-time = "2026-08-21T23:25:18.722Z" }, - { url = "https://files.pythonhosted.org/packages/50/a8/6a77f5f267c555108f0a864b6db714363dab567a8266422a79a385f9232b/scipy-1.18.1-cp313-cp313-win_arm64.whl", hash = "sha256:cd479fc04dd9401e3b4f49e76518768ef99c4f517a98c284eb091fd725719adf", size = 24399315, upload-time = "2026-08-21T23:25:23.458Z" }, - { url = "https://files.pythonhosted.org/packages/06/d5/d8eb4e280ddb56a4ab2c6f02ee49b56b23f6e977cf0802fd6d68dbef14f5/scipy-1.18.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:83de5453a7799afc9048b4616bd085cef126e36412f0ea2f6370c36a2a3a51e7", size = 31090936, upload-time = "2026-08-21T23:25:28.686Z" }, - { url = "https://files.pythonhosted.org/packages/2a/49/59ea385dc3a62ff498ddf3cfff7c2b41b0f9f9d3c4122b3f1dcb6d6327fe/scipy-1.18.1-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:9554bcc6d715ee87a633a3cc8e7703c6628b100dd29cb8a2efc4c0533c7ff729", size = 28725221, upload-time = "2026-08-21T23:25:33.244Z" }, - { url = "https://files.pythonhosted.org/packages/70/e8/6b0c288c50942d78193696c9f15f9a0874f5178aa0ddf40f83d9924b3e8d/scipy-1.18.1-cp314-cp314-macosx_14_0_arm64.whl", hash = "sha256:011413b7426b75012840e35649e00fe0a2c3bae89fed433876e3a99251572efc", size = 20466839, upload-time = "2026-08-21T23:25:37.516Z" }, - { url = "https://files.pythonhosted.org/packages/4b/e0/54fd3793c729e3b936782f181b59cbb1205bf250ab605a16cb1ba61cdd5e/scipy-1.18.1-cp314-cp314-macosx_14_0_x86_64.whl", hash = "sha256:88f0e784020649f88ea48c9f5ddfa403bf9205820667c0914740b392035afb82", size = 23089121, upload-time = "2026-08-21T23:25:42.019Z" }, - { url = "https://files.pythonhosted.org/packages/0b/56/030af62bea3cf878e0028515dff78c123b01633606a879b63f42d2db99cc/scipy-1.18.1-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2d3ab0e8c69a17dd3559eab8cbb88f258e285c94d572c2719033f90f83290c89", size = 34053851, upload-time = "2026-08-21T23:25:47.998Z" }, - { url = "https://files.pythonhosted.org/packages/6b/89/2a844506d49651e9aa1af6ef95b6bd8031cb1d5a4375edec6155037e04cf/scipy-1.18.1-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ac0333bdf38309aa3dcbe7e3fa7ea29e7a2c37c6ea306a757b700ded8e4596ad", size = 35329183, upload-time = "2026-08-21T23:25:53.522Z" }, - { url = "https://files.pythonhosted.org/packages/eb/56/c7370c3640e92ac9613cbf26cb3f729f9b12ddf1727b55b94b53b24d6f48/scipy-1.18.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:911de823097db8b63f034299d12662db93344e6ffa0b881cbb57748974b70168", size = 35672551, upload-time = "2026-08-21T23:25:59.387Z" }, - { url = "https://files.pythonhosted.org/packages/24/16/ec8536f351421f8bf60a1120930638f83790f4710b8230446aca3d6159d4/scipy-1.18.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:95298364e251be3e60249facbeeca03631d3bb7584f85879516ec55ac717b81f", size = 37469416, upload-time = "2026-08-21T23:26:05.432Z" }, - { url = "https://files.pythonhosted.org/packages/52/94/d73da0d28f16c45bb9b0a5691b91610b0275c5ef0eb5e43c87cf2dc1bf31/scipy-1.18.1-cp314-cp314-win_amd64.whl", hash = "sha256:78a0d7c918e74a232394117160e7e3db503377572a45bcef8826e4ab8a35feba", size = 37362755, upload-time = "2026-08-21T23:26:11.366Z" }, - { url = "https://files.pythonhosted.org/packages/89/25/e996e4dc74e10e227b1e14db5eaf6608bb6dd33884a64851c38f18dd4249/scipy-1.18.1-cp314-cp314-win_arm64.whl", hash = "sha256:cbf38d043c1aa4ab306e1ada6ab6eddacc3322a20b7af1b30bc93254b366fe09", size = 25036090, upload-time = "2026-08-21T23:26:15.887Z" }, - { url = "https://files.pythonhosted.org/packages/fa/c9/c00213f92309d753b48903e6a451b87eb52ff5b7a16e789d1568bbf221c4/scipy-1.18.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:0fcb3c93519f27bb4f0c4b0f7802cdcaca7fcf93267b75edda2e9f4e8a55cbd7", size = 31485550, upload-time = "2026-08-21T23:26:20.776Z" }, - { url = "https://files.pythonhosted.org/packages/74/b2/e3067c487982d4eeab2938928529410370c06fea84a4d3f4925e7d96647d/scipy-1.18.1-cp314-cp314t-macosx_12_0_arm64.whl", hash = "sha256:ddef79fb382df40104a19bb7151b3b23e57c1778fcf857c71ceecd9bd264513f", size = 29174642, upload-time = "2026-08-21T23:26:25.395Z" }, - { url = "https://files.pythonhosted.org/packages/d5/ab/374c9fe2d1ec014e576c781a4b5d8e1ba340e8f6b4638c16f711d2b194f0/scipy-1.18.1-cp314-cp314t-macosx_14_0_arm64.whl", hash = "sha256:0e82073ecc7acc6436fac4b31674109c7e1d3e596789767eda01258a8c9e8123", size = 20916357, upload-time = "2026-08-21T23:26:30.112Z" }, - { url = "https://files.pythonhosted.org/packages/90/38/223915c88a17317cafbf8ca2a42b11c265a9fb1e804aa665544132b5fe8a/scipy-1.18.1-cp314-cp314t-macosx_14_0_x86_64.whl", hash = "sha256:8bcf3c1ba5d6456e2effd30fcbd3459b044d683fcdac79a2e6830f0bdf7de487", size = 23482611, upload-time = "2026-08-21T23:26:34.846Z" }, - { url = "https://files.pythonhosted.org/packages/c4/d1/db0948da8ca57a80b36520ef0a768b967d99f3af65f4b6f1bf6362ad4dd4/scipy-1.18.1-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:cfbf154f2ba187f2ed6cce2639efff7d105f1140573642c0161615b6d91d6a87", size = 34143202, upload-time = "2026-08-21T23:26:40.4Z" }, - { url = "https://files.pythonhosted.org/packages/87/53/39d046cc7574ed6acacb6bd5723e220107ece80bff12faaf3efc4ddeede4/scipy-1.18.1-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a1d33a7836f7ddc1993427966a0823468ec41bcbdb1a9f9942d1d7e57f803ba3", size = 35380876, upload-time = "2026-08-21T23:26:46.1Z" }, - { url = "https://files.pythonhosted.org/packages/f9/da/32e0e799d875a85ca57d9bde6c78148afcc0e38276df683d95854eadc8c3/scipy-1.18.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:7f4b8bc363b6d65ee2152bec57568e3c52639bb34c46057b09857a307ed5e21d", size = 35770885, upload-time = "2026-08-21T23:26:51.533Z" }, - { url = "https://files.pythonhosted.org/packages/88/2e/f97a666d362fee68b18f41c9c30ed502ca5c98b549749bfcb52a8b74d1eb/scipy-1.18.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:11c423f1049c5755ad4409af52a9ada1cff96fe9b50795d4af3619f292901239", size = 37525424, upload-time = "2026-08-21T23:26:56.751Z" }, - { url = "https://files.pythonhosted.org/packages/ca/d5/a9e765a84654ebba8479a1fd1b059ced1af72b168a3b2a3a46540ea38d20/scipy-1.18.1-cp314-cp314t-win_amd64.whl", hash = "sha256:c24acac1e18912761c4700239bbc1fd32f615af690f1584d49b35859be51324d", size = 37416961, upload-time = "2026-08-21T23:27:01.546Z" }, - { url = "https://files.pythonhosted.org/packages/ee/16/e79e0d1c63ef698879d85439d37e9fb434e3b804e506a6991038d086ebd9/scipy-1.18.1-cp314-cp314t-win_arm64.whl", hash = "sha256:9f2897bf7737392ad0d5213ea7b6add72a4edf5679b3153106aeb88b6507b3b9", size = 25331848, upload-time = "2026-08-21T23:27:05.884Z" }, - { url = "https://files.pythonhosted.org/packages/be/4f/1bd37c883b67163e2ca1f60977a399500e6879c15defecac62831c8d078d/scipy-1.18.1-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:eb0dfcf4e28a99c12c999744a2ff67c9b06200e20401c7c88186e33552a46331", size = 31091484, upload-time = "2026-08-21T23:27:11.051Z" }, - { url = "https://files.pythonhosted.org/packages/8c/c5/ba929d7feb9b2332f96827c12e0e924b61973b59b4dea383b603372c65ce/scipy-1.18.1-cp315-cp315-macosx_12_0_arm64.whl", hash = "sha256:30f464bee641fa8e282577c7dce027308403213c6ca8270bba73285c91024bc5", size = 28725057, upload-time = "2026-08-21T23:27:15.9Z" }, - { url = "https://files.pythonhosted.org/packages/a4/19/68f1c50f609d955d230e66d25d02bd3e1e167ec540232135354fb9a4b9e3/scipy-1.18.1-cp315-cp315-macosx_14_0_arm64.whl", hash = "sha256:1bca3b943fc2567ea49cd02c99abde49da4d5178ec46f624bd8255cda8755beb", size = 20466734, upload-time = "2026-08-21T23:27:20.044Z" }, - { url = "https://files.pythonhosted.org/packages/ef/6d/319fa29b73d1802fa80b32a6eaf3f5be456ef81526da2716a9493bcb5501/scipy-1.18.1-cp315-cp315-macosx_14_0_x86_64.whl", hash = "sha256:c9d18a33309122074ea483dd92dd444189166b8b2ec429fe9ed5ac73c7a0aa23", size = 23089664, upload-time = "2026-08-21T23:27:24.345Z" }, - { url = "https://files.pythonhosted.org/packages/b7/db/30992f9b51a63de671daf3888ffd18378b6cb9ec9f2c972264238ffa7fd6/scipy-1.18.1-cp315-cp315-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:82f201b4c878551d48558337aab270d3c6cca5507b8737c8d8a608d234cccde0", size = 34054035, upload-time = "2026-08-21T23:27:29.409Z" }, - { url = "https://files.pythonhosted.org/packages/91/d4/bf3e735dc0b9d5a8ff45079d2540e17d3aff7a2f0048dd8f552ffd031d2b/scipy-1.18.1-cp315-cp315-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0ac49ea97594532dd44b7136094d35f5440fa06e6d9c6384a74c01764df388c5", size = 35333883, upload-time = "2026-08-21T23:27:34.293Z" }, - { url = "https://files.pythonhosted.org/packages/19/93/12d78ce9f871fe945fca588d32644e6e63f553c2a35c564d73f3b22a3313/scipy-1.18.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:ceb30a00ce7c92d459819443d29ca486d882b83fb6738bdcbb2a1cce94ac5daa", size = 35673124, upload-time = "2026-08-21T23:27:39.059Z" }, - { url = "https://files.pythonhosted.org/packages/70/cd/886219313a1012a48e6ae0ec4f302c837151beb92e1ff0d709ef8fdfc488/scipy-1.18.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:f29633129f9fa7e88a3f0fca835de2d030bfc9643f7799e1a0c46cee24d38fc7", size = 37470753, upload-time = "2026-08-21T23:27:44.435Z" }, - { url = "https://files.pythonhosted.org/packages/17/6c/a776888ce618bee54fbde26172f0f46ac1da70d27b63861797fe78e1904b/scipy-1.18.1-cp315-cp315-win_amd64.whl", hash = "sha256:92c14f5bdbfb6216315ce33e78080474082de8b3830122ba97809bfbe65f75c0", size = 37361483, upload-time = "2026-08-21T23:27:49.334Z" }, - { url = "https://files.pythonhosted.org/packages/ab/09/97b651691322ebee97999b017ffc18a15a0b815103844c97e8da9d469731/scipy-1.18.1-cp315-cp315-win_arm64.whl", hash = "sha256:e402cf31eb68f453dbb2d36fc6d722b33f24a55d68b2ae1d92fa6305ca71c298", size = 25035883, upload-time = "2026-08-21T23:27:53.596Z" }, - { url = "https://files.pythonhosted.org/packages/ed/0f/9ec20467bbabd0d44e2a77d0fd3d124f884b4d67df92af82c91d2d6a486f/scipy-1.18.1-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:2a0b02f9fc46f8520330c23d45e6560db7e3a0d927232139427637f98943e11d", size = 31474926, upload-time = "2026-08-21T23:27:57.993Z" }, - { url = "https://files.pythonhosted.org/packages/8a/58/dcb79161e56efbedc50079fcd2f5fe427a0ebb53022eb476aa73c015ad8f/scipy-1.18.1-cp315-cp315t-macosx_12_0_arm64.whl", hash = "sha256:1d73131e358976663dd969e1fb4ed1404b815cd977eaaedc3b3a133ba2d81c35", size = 29164940, upload-time = "2026-08-21T23:28:03.062Z" }, - { url = "https://files.pythonhosted.org/packages/71/d3/1eeea80c817fcb8ef7bd4a05a58824977a0e57a375cfc3d7ea7c911c01ad/scipy-1.18.1-cp315-cp315t-macosx_14_0_arm64.whl", hash = "sha256:bff0b729edd992766136b34e39cc76bc2fad905aa58897ee72a9cd000a6d8443", size = 20906742, upload-time = "2026-08-21T23:28:07.642Z" }, - { url = "https://files.pythonhosted.org/packages/54/46/e59350428b6099301a20128108c995e2eb175a43f383af9a346e38824f9b/scipy-1.18.1-cp315-cp315t-macosx_14_0_x86_64.whl", hash = "sha256:10ac20c69d880f77f375db44c22e3e6a644f9fefa291d4cd2fb9790a89fc99fd", size = 23472183, upload-time = "2026-08-21T23:28:12.109Z" }, - { url = "https://files.pythonhosted.org/packages/89/31/cc91623fa98f0621766a0f0aaaadb2c66de74a7ea7e3837164f6e4354260/scipy-1.18.1-cp315-cp315t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:33a834464fdabc0f26a45508df31b3cc5d028e04dbf6c5ed398541418e0a12fe", size = 34130796, upload-time = "2026-08-21T23:28:17.906Z" }, - { url = "https://files.pythonhosted.org/packages/fc/3e/8572ef536957ddb8aa81bb4090d9e25f257e3b4e05d97deb54319deb8a3a/scipy-1.18.1-cp315-cp315t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:49023963c193dacee096301452f223ee24d86ec5807f8df93c0f7221d119e305", size = 35374253, upload-time = "2026-08-21T23:28:23.732Z" }, - { url = "https://files.pythonhosted.org/packages/b5/c6/59fdeffb4f1435299f93d9dc8140b43ad2916e6cfc944be6c3041fcec86d/scipy-1.18.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:d84a09d0dad90ba6525d8ac1c2334b33e64bf3ccfe9e841f02feb867a22681e4", size = 35758543, upload-time = "2026-08-21T23:28:29.431Z" }, - { url = "https://files.pythonhosted.org/packages/cf/d9/135be205d9de8783193aff9cc3bf483a03a38e4b29432c954e8cb66ac14e/scipy-1.18.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:179ce34a8d0fe273d8883ba59e17e052247d08973dfcb743ca52bb1cce2d60b0", size = 37521946, upload-time = "2026-08-21T23:28:35.245Z" }, - { url = "https://files.pythonhosted.org/packages/5c/a2/5b7d5270621ab7cfa3f7766067bf95dc360b5efb6394694e8143b4156e2b/scipy-1.18.1-cp315-cp315t-win_amd64.whl", hash = "sha256:5632e3ae3d09197c446310cd5187de63e28448ce22f0f67b2b93d97503c0c230", size = 37408295, upload-time = "2026-08-21T23:28:40.724Z" }, - { url = "https://files.pythonhosted.org/packages/63/ad/741c19fcb66755ff953daf9243af8480e4bf3d7fbe57583c178c7d2b6b51/scipy-1.18.1-cp315-cp315t-win_arm64.whl", hash = "sha256:eda632a7981f69730d6281f451db9c1c370993a2c0d7ddb43e2a809a2862b83a", size = 25319710, upload-time = "2026-08-21T23:28:45.713Z" }, -] - -[[package]] -name = "starlette" -version = "1.10.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "anyio" }, - { name = "typing-extensions", marker = "python_full_version < '3.13'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/48/bb/3d8757f21e9a53d9035c9eb039a777047139a16bfdbedfc7a58241c3d914/starlette-1.10.0.tar.gz", hash = "sha256:b8399098d4c1e3522734f7235dc79b1fc967f96cf139c81e0fa30479e0685f9b", size = 2734356, upload-time = "2026-10-24T15:04:12.342Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/88/2e/947cfe02def9371c07cd5bf5b6b61c829e9aecb9904db02a66cfafbc1eec/starlette-1.10.0-py3-none-any.whl", hash = "sha256:478c0ab3b4ced6e82719849c118fa406f0278a3499c1a898cd15cd31bdc38ce4", size = 80571, upload-time = "2026-10-24T15:04:10.371Z" }, -] - -[[package]] -name = "stockbot" -version = "0.1.0" -source = { editable = "." } -dependencies = [ - { name = "duckdb" }, - { name = "marimo" }, - { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, - { name = "numpy", version = "2.5.5", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, - { name = "polars" }, - { name = "psycopg", extra = ["binary"] }, - { name = "pyarrow" }, - { name = "scipy", version = "1.17.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, - { name = "scipy", version = "1.18.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, -] - -[package.optional-dependencies] -dev = [ - { name = "pytest" }, -] - -[package.metadata] -requires-dist = [ - { name = "duckdb", specifier = ">=1.2.0,<2.0.0" }, - { name = "marimo", specifier = ">=0.11.0,<1.0.0" }, - { name = "numpy", specifier = ">=1.26.0,<3.0.0" }, - { name = "polars", specifier = ">=1.20.0,<2.0.0" }, - { name = "psycopg", extras = ["binary"], specifier = ">=3.2.0,<4.0.0" }, - { name = "pyarrow", specifier = ">=18.0.0,<22.0.0" }, - { name = "pytest", marker = "extra == 'dev'", specifier = ">=8.0.0,<9.0.0" }, - { name = "scipy", specifier = ">=1.13.0,<2.0.0" }, -] -provides-extras = ["dev"] - -[[package]] -name = "tomlkit" -version = "0.15.3" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/c9/85/4a7c68111c057a6498f5bc721ef93b388b420bb31d7020759f18a5f0c2ec/tomlkit-0.15.3.tar.gz", hash = "sha256:b3c3020ec1a4bd469d12e31fb4da938e7f6ba758cdbec3fd9047db63120eaf81", size = 204435, upload-time = "2026-11-24T07:21:10.422Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/c3/49/6b0a22e69c844c0b18cb66c206bdd791693d0cf845badc5f84e6448f2192/tomlkit-0.15.3-py3-none-any.whl", hash = "sha256:a83ce6de3b648e68dd9b50aabadad749ba823eb58b1d026f3c0a283c4767a9c1", size = 55467, upload-time = "2026-11-24T07:21:11.239Z" }, -] - -[[package]] -name = "typing-extensions" -version = "4.16.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/f6/cc/6253133b5bb138fc3306cebfbda2c520f545d36b5be2c7255cc528bb45d6/typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5", size = 113555, upload-time = "2026-07-02T08:40:05.92Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" }, -] - -[[package]] -name = "tzdata" -version = "2026.6" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/7a/29/6a1391d31cd00ff9e927215a224a880e1e84e826b64ba80a499e51c074d8/tzdata-2026.6.tar.gz", hash = "sha256:85d2cd9c09f81f0bb29db27759fc83af4f1e620efb814f8c5bf8b4cc4feece6d", size = 201017, upload-time = "2026-10-28T09:57:09.137Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/0a/66/9a06c2227fedfd4919f0eaaa8b94377d9730882a7e4f95823c9a331ab5e1/tzdata-2026.6-py2.py3-none-any.whl", hash = "sha256:0a10eec6e13ef16b627fabed9a5f2ba61a62b1c67f327305f4e7e412a70b4aec", size = 348210, upload-time = "2026-10-28T09:57:07.276Z" }, -] - -[[package]] -name = "uvicorn" -version = "0.55.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "click" }, - { name = "h11" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/60/32/ed1b49f4eca183639f1048bc48494c8e24386c865dce1357cd108d5871ea/uvicorn-0.55.0.tar.gz", hash = "sha256:b65ae5f0f30cdcbc26a104b93d7d19723aa5f46fec3915a6c247d5795449331c", size = 114540, upload-time = "2026-11-28T13:03:51.048Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/d2/05/3f8e143f2180eb21ed5e28b3c319143960c797c68852744c4d9116480928/uvicorn-0.55.0-py3-none-any.whl", hash = "sha256:bee604c5af6e15fb0584913c632b222c09db1048c26fc05053203207c4b9e37d", size = 87457, upload-time = "2026-11-28T13:03:49.635Z" }, -] - -[[package]] -name = "websockets" -version = "17.4" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/75/79/590c5f0cc7d1661195aeefccb0e342b79f4c77d368d526d028821a390332/websockets-17.4.tar.gz", hash = "sha256:09d3939b70df0c8ad2da145ebd50978bccaee1d565e838b0e7921a34d38571eb", size = 191391, upload-time = "2026-10-30T15:10:35.873Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/e7/d8/2d4ec550208432538d152a41f0c36dc6728cfae0050c6b1442605456d3bd/websockets-17.4-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:06ea46717553cdd10f2682126cf7a66e91c8ed17b6969f4a95e94b4e01d06188", size = 218746, upload-time = "2026-10-30T15:06:39.361Z" }, - { url = "https://files.pythonhosted.org/packages/56/99/3090fc0e2e343cc7ee60d532b67a2d413830c8fbb0be9ec3bcfbe3371f2e/websockets-17.4-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:75b32cf33ea40f945f226f97bc1d43151e1a5adff21f420b5e63c468b1a28114", size = 216437, upload-time = "2026-10-30T15:06:41.324Z" }, - { url = "https://files.pythonhosted.org/packages/3c/e9/3d4fb98e5d8aecc7bdbc59c4edf6380fdeddf935445e7f4a205466682991/websockets-17.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:b8451f31ae24620cc9372acd2728d87922f2bb0cae3fa57aed68b152844cdf08", size = 216709, upload-time = "2026-10-30T15:06:42.995Z" }, - { url = "https://files.pythonhosted.org/packages/0c/4d/5c7d4f53cc0d7c6f268bbd93865b185e05f65f37f84712a41ab311118f8f/websockets-17.4-cp311-cp311-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:3b76837cd051d8875913f3934b27205f7a592f78b8a4f4a1f3abc36a2420c5bc", size = 225773, upload-time = "2026-10-30T15:06:44.607Z" }, - { url = "https://files.pythonhosted.org/packages/57/70/80f870701f8610e88649d3cd173a0e7ce66433913da3683035a4370063ad/websockets-17.4-cp311-cp311-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:cebad8f4796248b91fc2168515e507e5cb6b663a32befd09f3b1e7920acdcb1a", size = 226041, upload-time = "2026-10-30T15:06:46.224Z" }, - { url = "https://files.pythonhosted.org/packages/a2/bc/f2e84b5a933c86d52184814d38b0f9d51fc90fd3205cb7af0d9417ebbff2/websockets-17.4-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:954d43574f72be244b65f0fa61e2f814214b024f2ec849f487aa2f553f7c6e71", size = 227279, upload-time = "2026-10-30T15:06:47.619Z" }, - { url = "https://files.pythonhosted.org/packages/34/7e/4710475f46afbfe5390b4139556aa4fa0692d3d31878a25a1b26e8a6d78a/websockets-17.4-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:b529ad6c81ad21db2f4e3d6e33db78ce3b9f272066b438b5d673361f9282898d", size = 230592, upload-time = "2026-10-30T15:06:49.357Z" }, - { url = "https://files.pythonhosted.org/packages/bd/10/cca6dc2316dd8c3b1a62fbf7f8986926ad8c4b2ae3d3be7888059a96b142/websockets-17.4-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:799c5a23126c9589cb10b6c6b54f9087246940dad20cd74bf3f06fc9ae3bbab5", size = 227837, upload-time = "2026-10-30T15:06:51.015Z" }, - { url = "https://files.pythonhosted.org/packages/68/21/ac1c3d7781d756bd40fbe501890b54a0205b1f0528a559fdcabcede0bd54/websockets-17.4-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:f01a680d4b66fd15cc7513fae55c673cc8cc340d41340305b7f9a782abdbefed", size = 226613, upload-time = "2026-10-30T15:06:52.556Z" }, - { url = "https://files.pythonhosted.org/packages/b8/a0/bd122578f2765fb3714eeef80bd66074e355ff80e0a6de7fefa10de5f36a/websockets-17.4-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0e51546a3bedadd80dfa5c2efaed840ac51b8632d8db7f9f502175f5349382a9", size = 223893, upload-time = "2026-10-30T15:06:54.106Z" }, - { url = "https://files.pythonhosted.org/packages/51/50/a5214db6b778995b7fe1bfaab6228ba967cb6fd523d4b7af83154aa0ac66/websockets-17.4-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:6686d29eaafddeeab9e48af92103dc0d26161035faa4be083b8b488f1ab47219", size = 226768, upload-time = "2026-10-30T15:06:55.889Z" }, - { url = "https://files.pythonhosted.org/packages/fb/41/5d62d4889ff8a400cf32c8ad35e58b18e92b0e936db0bae785307cd1b105/websockets-17.4-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:7b23db4b469d9e051ac74d96db9bf61e27c9054de64f8263fefa32bf72867ba1", size = 225358, upload-time = "2026-10-30T15:06:57.706Z" }, - { url = "https://files.pythonhosted.org/packages/b4/94/c344744fad06ae721a6ec69f728a3dd4bd1b94beb7bb64400a8cd0efc644/websockets-17.4-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:0132e3cbd3f5cfc1ec77588961b302d72a02e2603b82c2c23fd5fb59dc4fa206", size = 226125, upload-time = "2026-10-30T15:06:59.125Z" }, - { url = "https://files.pythonhosted.org/packages/0d/00/90d66792bf1ce315fabe18f838eb2090ebad3425139047ed4c4ad354a90c/websockets-17.4-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:98f16db5e79f2605194c0f899d0532005bb12269e698bf96f62a5635bcf33010", size = 227169, upload-time = "2026-10-30T15:07:00.687Z" }, - { url = "https://files.pythonhosted.org/packages/24/7f/c069129b20504c35bd22abb276a6562e92dccb69c974ca93021a23fb00ce/websockets-17.4-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:ee48728a07566c32e097d267f4d4d01b85123c9ae748a42da02185b908cbedc4", size = 224750, upload-time = "2026-10-30T15:07:02.077Z" }, - { url = "https://files.pythonhosted.org/packages/4e/3a/0fcb37d6da690aa2512faadb0e9cb5e1043fff659fd415dc8b518883789e/websockets-17.4-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:2103982762460a764a7ef0021443bb471f46d45ecc6858276e4fe699ebac6b94", size = 225782, upload-time = "2026-10-30T15:07:03.783Z" }, - { url = "https://files.pythonhosted.org/packages/49/61/422745448862b18b8d373347bb73debcd440330f21dd899feac5f920d531/websockets-17.4-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:648adde345cfd13335342e23cfe94871c7f7f55a43fb254f3b95acb071072968", size = 226021, upload-time = "2026-10-30T15:07:05.237Z" }, - { url = "https://files.pythonhosted.org/packages/96/74/3ea38c6758b497a5d1b7bd953542e9e6446b84aa075a061e9a47e24ceb75/websockets-17.4-cp311-cp311-win32.whl", hash = "sha256:679eef0123861ca381dd8fd9bdc1920e87636ac55eae6cff875c53dcb05fbcf8", size = 219255, upload-time = "2026-10-30T15:07:06.871Z" }, - { url = "https://files.pythonhosted.org/packages/55/66/00ca8b75a634c9fcf70579f9a242b96a7f7a3abeb21a02e2380fff491d2c/websockets-17.4-cp311-cp311-win_amd64.whl", hash = "sha256:e4beaef2f4796558e738e15ca0b8802e35f419a9fa374a978e41706f43c48b26", size = 219556, upload-time = "2026-10-30T15:07:08.538Z" }, - { url = "https://files.pythonhosted.org/packages/4b/7b/c8ccb313439f4803779f186b8133563e6c49c023467a265ae52da7b7e25d/websockets-17.4-cp311-cp311-win_arm64.whl", hash = "sha256:ddab54dc0ec46ed09ef9ac131252cb5740ed21fbe6fc145f3c6fed0b575a8f15", size = 219487, upload-time = "2026-10-30T15:07:09.94Z" }, - { url = "https://files.pythonhosted.org/packages/af/71/b020221345ea6c012dcf7496827a48a744b58696470b2b07fef95a32905a/websockets-17.4-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:3d512e3a6c528c42ce220ed9c3caff83c6fdcd98a1b98249f08ccfc66ad111b1", size = 218779, upload-time = "2026-10-30T15:07:11.522Z" }, - { url = "https://files.pythonhosted.org/packages/8e/84/1c372ae7c032021a84e5c9e9b76b0dddefb354e9b4af783a97efd4d80ab3/websockets-17.4-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:7390e060f830b3d132f484b21ac2783a2d227b682ef62bb8146e1c1b4ca0e45a", size = 216457, upload-time = "2026-10-30T15:07:13Z" }, - { url = "https://files.pythonhosted.org/packages/74/b6/cff249107473f149c6c916a49cba967379fa63b0a7d2dce6896d6848f0a3/websockets-17.4-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:bcad49104711f88b2b7c3ba166de172857d837248205e541b044a552558fecc3", size = 216726, upload-time = "2026-10-30T15:07:14.468Z" }, - { url = "https://files.pythonhosted.org/packages/77/5d/aff8ecbf1c55c4d96f6dacc46a52102895f58b85bb284c8d325aaf31606a/websockets-17.4-cp312-cp312-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:cf99debb17227a50620aee16647bb33a0387f5fa5418d628666c0f05745e0d2a", size = 226043, upload-time = "2026-10-30T15:07:15.937Z" }, - { url = "https://files.pythonhosted.org/packages/cb/18/6229d6583031ca81d092a0cd887a13a57b402fb555acc323d39b45967eb7/websockets-17.4-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:9ae1429ee9e52b139167ed0169757806a27ed7307e942e8c62037a9184e9843b", size = 226321, upload-time = "2026-10-30T15:07:17.563Z" }, - { url = "https://files.pythonhosted.org/packages/b8/61/7aba018fd53873e792a25afe1f4c005518133477b727d7455f2f7550c425/websockets-17.4-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:51adfc30f467077293a6695d8149bcef501c0728386f3a491054f835dadb60b2", size = 227559, upload-time = "2026-10-30T15:07:18.998Z" }, - { url = "https://files.pythonhosted.org/packages/fb/66/37b207df9cdacaa017aa4487f3a9f2fcd668f6f7cfbafdac5b95ea258ee0/websockets-17.4-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c564d1e6531611bf87078c28780456ecc75459dcca189629fff2fe7c020d8e67", size = 230386, upload-time = "2026-10-30T15:07:20.431Z" }, - { url = "https://files.pythonhosted.org/packages/ad/f6/87507e11fbae53817a435945273953b5b020589e309fac4fd60527ee5999/websockets-17.4-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:4c792e6cce24d08f92199d907785c9e64f74c357deeed3dbaf7d699ed5930b64", size = 228193, upload-time = "2026-10-30T15:07:22.112Z" }, - { url = "https://files.pythonhosted.org/packages/2f/3d/90a04f0aa989b68fbd2efcd38237420afe2abe5a1cab0b5d7c2aa4f0dbb6/websockets-17.4-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:c44776f82b04e623eb9e1b81fcd17ac6e9808ae1ba5cdf8edce1f7c869a95a9b", size = 226952, upload-time = "2026-10-30T15:07:23.643Z" }, - { url = "https://files.pythonhosted.org/packages/ad/3e/50952af22b8e3e2d03f7e83f0e335851c6b484c3fd88586626fb1c2a34b3/websockets-17.4-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:4d2636a5b61c69e32db0e74b57073dd4a66f1ad195e9398c5f01bba41090deea", size = 224183, upload-time = "2026-10-30T15:07:25.507Z" }, - { url = "https://files.pythonhosted.org/packages/c4/73/2a4a5d9c6bca1127f24af7bf08f406a69052d7f341bc81f08d9e8eb446b4/websockets-17.4-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:cfbbba4597f19ad717f79fd3f2a67ae7efae647bd6a61e14554e1b5ad242a5bf", size = 226991, upload-time = "2026-10-30T15:07:27.355Z" }, - { url = "https://files.pythonhosted.org/packages/68/de/90d96a579839bfe541ef214315df81d2bd519d952847c303328518ffdd02/websockets-17.4-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:c7b996c02de5e032cb63dc65482b73693b7ecaa586654126be2749ddea239c40", size = 225600, upload-time = "2026-10-30T15:07:28.973Z" }, - { url = "https://files.pythonhosted.org/packages/91/17/12c15ed446d842e40918cd16e79b56ee4422d6fbf210258cb8882f50bbd5/websockets-17.4-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:a920e99155d75d1b1c08172da8aaa7200e7b30871fb628d1631d7891a333e30e", size = 226366, upload-time = "2026-10-30T15:07:30.472Z" }, - { url = "https://files.pythonhosted.org/packages/9d/73/cb4c927e806a73a0377696e031ef3c0db409028cdb2373f96ee863e8df8e/websockets-17.4-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:8c00c5c49f80a588a2c4f99d519d2abed4ce26cdca11273041bc8b7e60af60de", size = 227470, upload-time = "2026-10-30T15:07:32.122Z" }, - { url = "https://files.pythonhosted.org/packages/33/b3/e682b3ea069933044f4bf4809eea0cd83e3a5bdbdff601d1777a9ae90795/websockets-17.4-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:52c31d123f5adf14dec694c2a4036bf42c523df7cefc641d31cd05653de56e49", size = 225026, upload-time = "2026-10-30T15:07:33.544Z" }, - { url = "https://files.pythonhosted.org/packages/2d/e9/d039757260705e5a265a31c9fff36b0d4567b842ce2b54e5d14369f200bd/websockets-17.4-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:d0acd8191c0e5a61d1c27bfa33b6ec8431982299f5d71c02129aa4f16f182ad0", size = 226007, upload-time = "2026-10-30T15:07:34.954Z" }, - { url = "https://files.pythonhosted.org/packages/db/e7/cb9907fac6f9b28f93beded6efda2953960cd02b633d432acf3451590859/websockets-17.4-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:2a9cb5bbfc33b4ebd3c8d3714d6e09805437f60a14977774e4bd11b5ace46c23", size = 226286, upload-time = "2026-10-30T15:07:36.292Z" }, - { url = "https://files.pythonhosted.org/packages/39/99/85f6f4dd104a5d9a33a1ef272f501d0f2e8527ddf66be1b383d51f90ce56/websockets-17.4-cp312-cp312-win32.whl", hash = "sha256:c63c0d7832956d5f3bb77888b93c854569d13f806289ff75c43926d25c6e5fd2", size = 219256, upload-time = "2026-10-30T15:07:37.686Z" }, - { url = "https://files.pythonhosted.org/packages/59/31/d1636ba67ee9232a60033d90483e48686aa3856014e59110f29015f97bd2/websockets-17.4-cp312-cp312-win_amd64.whl", hash = "sha256:dde9cd67f18803949ebf96de8aba12b8ec5ee3115e34c75a2db85a3b0a6c20d5", size = 219561, upload-time = "2026-10-30T15:07:39.19Z" }, - { url = "https://files.pythonhosted.org/packages/23/aa/e3859d52188f041a5a05c9f3ac005a9c829723f521f0fe60e2c5f9c93bb9/websockets-17.4-cp312-cp312-win_arm64.whl", hash = "sha256:c634053459278cf31fb404ddb5ecd38124e4609e8b609166da621edc2d5796db", size = 219487, upload-time = "2026-10-30T15:07:41.161Z" }, - { url = "https://files.pythonhosted.org/packages/cd/58/eaf27fce59e3f5b9997cd7c77749ef214e077daeffac95479be6ff9f5cfa/websockets-17.4-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:f24bed98595b9d854da8d6debaf82754abf3e8fe63ec90505ef560566814df7e", size = 218769, upload-time = "2026-10-30T15:07:42.558Z" }, - { url = "https://files.pythonhosted.org/packages/13/8e/287eca6d399a953253492189153976676994dfba1b7e82f0f992d14c1404/websockets-17.4-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:156221ad7638b5abccefd6f798916bf3f8ffd6ac51480eb4ba5b05df914ccbf3", size = 216454, upload-time = "2026-10-30T15:07:43.874Z" }, - { url = "https://files.pythonhosted.org/packages/b3/65/098fd4d221d691395492fcba88c895dde19a51d371b06b8d0be71d3f781b/websockets-17.4-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:74e46409666c358b93fce0d8c6f4cb107d8dd7cba1302a38d49adf6fa8193c7e", size = 216715, upload-time = "2026-10-30T15:07:45.409Z" }, - { url = "https://files.pythonhosted.org/packages/e9/29/9f9833bc83c1bf2e5597d1ef374d3ccd6467b9b45400cff399c85331ef6c/websockets-17.4-cp313-cp313-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:e3e80cad85ba68c07c1e8d4ccc9cf51e63bf6a73d6bf631640be947bd72b6b63", size = 226096, upload-time = "2026-10-30T15:07:46.929Z" }, - { url = "https://files.pythonhosted.org/packages/ef/75/6a95f93661bba2f1a4ec82eb26c6d30e6ba253569ecabb7a675139db6051/websockets-17.4-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:25eb661d8ba7e2b85ebb4e7a1bb9f6a3280910ed10b84330a7abfb5ed32d2764", size = 226382, upload-time = "2026-10-30T15:07:48.332Z" }, - { url = "https://files.pythonhosted.org/packages/80/b0/b0d9427dde0609e2727a9a966fb5fc5c6ef6aa7eba4cfc98791f8b7f1b75/websockets-17.4-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c74954409ea5789f7a60daa5f94580c00ad0b60b20751c47b35c4784877b5057", size = 227617, upload-time = "2026-10-30T15:07:49.799Z" }, - { url = "https://files.pythonhosted.org/packages/3b/00/fb1016d850d61676d1732434e2361d116c1de369078e59d21f4713115a19/websockets-17.4-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:47beedf07a706140b50786457e082497ee6b5970c41e49bcd1572ee3f4c73f80", size = 229054, upload-time = "2026-10-30T15:07:51.258Z" }, - { url = "https://files.pythonhosted.org/packages/77/c4/bb666e196541e42237fdb625303ad099005cc835c4e2e0a5d97bb9c4185c/websockets-17.4-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:9e282f35ece8895b9fa5af406fc6a4cb42f01e1009525cf46641de584781c83b", size = 228243, upload-time = "2026-10-30T15:07:52.975Z" }, - { url = "https://files.pythonhosted.org/packages/6d/f1/32ae0f45d8464e1606ef3f6a54318d8754b27889de18bb1b2176a19bea39/websockets-17.4-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:361f9a21a33191d5287e7a75f508fc3b9bf47aaffb0241198d6b7be3384f294e", size = 226995, upload-time = "2026-10-30T15:07:54.574Z" }, - { url = "https://files.pythonhosted.org/packages/f8/9f/5680151ef10e0bfb6f3bf09a992ce6c3e93bbb84fc8ec5d03ad570ac6532/websockets-17.4-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:4073ab7cefe5a2e7dc368c1f01eb27716dc8ea8f1c69e9b7725ebce05aa53cf7", size = 224244, upload-time = "2026-10-30T15:07:56.158Z" }, - { url = "https://files.pythonhosted.org/packages/e2/66/409117b6882b91960598d62b95fac33d70a7aa2e1e1e854c6b64e76712f6/websockets-17.4-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a50bd9b44dd9b7b845802030b4d88610c01c7f95571b4cbd3a1aeec17a34c9fd", size = 227058, upload-time = "2026-10-30T15:07:57.539Z" }, - { url = "https://files.pythonhosted.org/packages/35/e6/34cab5913bea9d011ae2592a7672340179ff14fb98e889e5e41b071d8134/websockets-17.4-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:ad2e9e152bec6c4f7e4cdb4adcea6b708400090eec04bfe5ee5b30d368ffd721", size = 225654, upload-time = "2026-10-30T15:07:59.044Z" }, - { url = "https://files.pythonhosted.org/packages/a6/b0/6cfe18e12f23618a3d69723c828037c1282fee7ffce006ae7b5cc0e58ca4/websockets-17.4-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:5830f94a7190a33e55d06d89242ea951ee2009c3a27fc31538f3ac9386b27edd", size = 226425, upload-time = "2026-10-30T15:08:00.492Z" }, - { url = "https://files.pythonhosted.org/packages/c9/71/14d31ea34bafc07c6d96b362a44b301b9a0f2fb260490a8a6cb7db682bc4/websockets-17.4-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:c0cc2cb47face4dae64bd70a9268dbebddb3e48c1b48cf6d7b6ac1471609fd88", size = 227532, upload-time = "2026-10-30T15:08:01.932Z" }, - { url = "https://files.pythonhosted.org/packages/28/69/df3398ca1320a8b76e57ee41053d5c09955383cf60888ffa5771f51a4cc8/websockets-17.4-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:d0b6a9bd86f865ebc9d847a1eb0a655a0e2b447cbcde743dda97c4298415cc0b", size = 225090, upload-time = "2026-10-30T15:08:03.328Z" }, - { url = "https://files.pythonhosted.org/packages/d6/94/06afe778cf9893e9ac10209c0d4c70aaf0b72289245a8b7efb92cc80927c/websockets-17.4-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:7a7e9321822ca59ba56fa8744c3e3f01ef74d547aafe0d383d000d7a4d11eb79", size = 226041, upload-time = "2026-10-30T15:08:04.714Z" }, - { url = "https://files.pythonhosted.org/packages/c6/7a/28e9822dbf0bc63341dc45d8d5f1f1f7f375991fc8895bc731105fbde371/websockets-17.4-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:de29795f23833cdfb68ba45c8a5cc0ec49778ea5deb670188f4465bba5930d25", size = 226323, upload-time = "2026-10-30T15:08:06.103Z" }, - { url = "https://files.pythonhosted.org/packages/5a/d8/606c9c404e82731e4520f6397c8c16549e9cbd39ac583e7ea7d8972a6ae7/websockets-17.4-cp313-cp313-win32.whl", hash = "sha256:37ed7782972545e67d97ef9a172e9499d25459b1e32cb99d1c2a30c572f2441b", size = 219248, upload-time = "2026-10-30T15:08:07.617Z" }, - { url = "https://files.pythonhosted.org/packages/60/a1/17e507dadbfccb755758ba977b165fec92924dfc4a8d2573b4fc1561b0cd/websockets-17.4-cp313-cp313-win_amd64.whl", hash = "sha256:203e42eb77e06f85778a908b34c5ad032f34e98a68ef33920d6685c1e65a9420", size = 219560, upload-time = "2026-10-30T15:08:09.108Z" }, - { url = "https://files.pythonhosted.org/packages/01/ba/4f51fe8db73889ea3ecfdeee283d4ac3b7ad7a609c0e4c1fc6de04078021/websockets-17.4-cp313-cp313-win_arm64.whl", hash = "sha256:d8255971f6789cf0cb365e3e22b9b166eba978548a26241eaa5b7af0440d885a", size = 219496, upload-time = "2026-10-30T15:08:10.574Z" }, - { url = "https://files.pythonhosted.org/packages/1f/5b/085530961668661300de7248f9bf3ba84e98f47875f0fcc87637d024f82b/websockets-17.4-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:d0f943b53bb1d7389d72a5380078670e5fcc34a1328142148b72d20fd82031c7", size = 218810, upload-time = "2026-10-30T15:08:12.14Z" }, - { url = "https://files.pythonhosted.org/packages/f2/fb/5a29e9569f74988822b7bc076287dd7f9f5b68a2070cf5eb4cfada5863d8/websockets-17.4-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:2fd562372d4afaf18d1c7f1c68e39bd32818bb16d5f57f778a4a4ed88eedcaae", size = 216506, upload-time = "2026-10-30T15:08:13.561Z" }, - { url = "https://files.pythonhosted.org/packages/df/73/eb8544367c13cd87df39d41b74853741fb7182e2a4bb659ad7d36f9066c8/websockets-17.4-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:a0457561e8a87a6a3b509e21c35084d7d207ced262139de3f738e9676a476bbd", size = 216719, upload-time = "2026-10-30T15:08:15.08Z" }, - { url = "https://files.pythonhosted.org/packages/24/fe/c3707e426d9bd779dfad9f319b2b431e5e60d563d7547d3780cbd1646028/websockets-17.4-cp314-cp314-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:7b4ee34acefa9ba1333f02b817982f1e4127f6f9b975017a707c4e738d7f9fb9", size = 226098, upload-time = "2026-10-30T15:08:16.581Z" }, - { url = "https://files.pythonhosted.org/packages/c1/24/d203439f909ffbf37260ca28a3432381412d2e79912ebf98be572e63055e/websockets-17.4-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:ef03fb4b3685df0ed9dc6a074a090f030345cad2c23c61818da3e08e693a9caa", size = 226449, upload-time = "2026-10-30T15:08:18.29Z" }, - { url = "https://files.pythonhosted.org/packages/4b/17/3ae5d9486a170a222dd0437b4f2bc02ecf324177498a942dcac200e65d05/websockets-17.4-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c5e970d3996c597186c9dbb6e77a8048737a834ac03cb13186a54999e0e1c31e", size = 227695, upload-time = "2026-10-30T15:08:19.692Z" }, - { url = "https://files.pythonhosted.org/packages/34/37/1307a8e30a961726f2350982fc01b0b3498db29b030c78c566e65ba64487/websockets-17.4-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:6afc32a7a1a40b071070419537df3559d26907086556769683fa97b7b6e90fd5", size = 229069, upload-time = "2026-10-30T15:08:21.682Z" }, - { url = "https://files.pythonhosted.org/packages/9c/bd/4c6167744e202d20a3c770bcde8fae5d427317b1885712c2e02718cd8133/websockets-17.4-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:5da7f7f1ecf866186f195f7ecc374c915e1838496b86f2f3b41da27c798a25c3", size = 228296, upload-time = "2026-10-30T15:08:23.371Z" }, - { url = "https://files.pythonhosted.org/packages/14/b3/3438eee41b39afb44c3c6e45dd686b88a7f8d742b96877b77de4fe0e0255/websockets-17.4-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:043945a43873c7c11a3f75238d475c95f902e967de329eb8763704546cfaa6b6", size = 227045, upload-time = "2026-10-30T15:08:24.749Z" }, - { url = "https://files.pythonhosted.org/packages/46/39/0bac9052d402efaad1b202ff2f1a57b6334aa624d20f509312765601b507/websockets-17.4-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:927d602fb8fb595a69e6b1ae998a6ec19851d0fb9391759456e6425090996647", size = 224297, upload-time = "2026-10-30T15:08:26.275Z" }, - { url = "https://files.pythonhosted.org/packages/a1/7f/5809f6ba5a7d1065301800daf605bdb661a9db5ef868ed189dbf691122ac/websockets-17.4-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:769e4f7b090e10cae4c082e3e39b9458ec2444505df84953c16c0468b16539c4", size = 227169, upload-time = "2026-10-30T15:08:27.703Z" }, - { url = "https://files.pythonhosted.org/packages/fc/f7/c8f6771e7cc2a038cf78bb12d04d29dbbbabf2a84d76999bcc94532f3020/websockets-17.4-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:03ddf4eb76ced8725dcbb000ff60b0fb8d7330ed011f6dc725a1925c5fe02051", size = 225632, upload-time = "2026-10-30T15:08:29.441Z" }, - { url = "https://files.pythonhosted.org/packages/2c/2f/9104786d952978ca2d011321109e35c05be24c3937ef2a62b4d6e25f7515/websockets-17.4-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:94622cf24e80d03054ceb69a06a86c950e12fe993ed06b933f7895232cacbc3e", size = 226415, upload-time = "2026-10-30T15:08:30.962Z" }, - { url = "https://files.pythonhosted.org/packages/ae/a7/2e1606b3d616b86bb6c70a62d5f87fc9a3dbd81f0bbe24c4706ace76751d/websockets-17.4-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:bc581579885728bb54ef15000295c20e6a64a200b1b73d5cfca71879a3eb3e1f", size = 227594, upload-time = "2026-10-30T15:08:32.443Z" }, - { url = "https://files.pythonhosted.org/packages/67/2d/78ca44e2be6d397aee63a4e68d3a99a33bb14bb3405e94688bc5a2160db5/websockets-17.4-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:f42671900e0b602d05a074c52fd3d757c2f8e5c4f73f771794dae1aa4aea5f0e", size = 225146, upload-time = "2026-10-30T15:08:33.888Z" }, - { url = "https://files.pythonhosted.org/packages/d9/b6/6dad684e54fc8e09d70c9a095506db5c836207d8e846e3cb1e79424e3492/websockets-17.4-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:2b23dacf7a8a88afe92f77bcdbf4cf043a84692bac2f2da02f4011c687e19b48", size = 226095, upload-time = "2026-10-30T15:08:35.285Z" }, - { url = "https://files.pythonhosted.org/packages/d9/e5/7b04bad7c11c1f92238429352defbac1406743338049afe1328c7a7f95c0/websockets-17.4-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:d48795c7d64ca1c42e3d61fcc6478cb15a19b6ad3f9c882bc8d8dee49d4a420f", size = 226395, upload-time = "2026-10-30T15:08:36.8Z" }, - { url = "https://files.pythonhosted.org/packages/b1/16/4eb29c4b12f77b3139470063308ae1e6a0860b9073b1d27d56e8ce19c512/websockets-17.4-cp314-cp314-win32.whl", hash = "sha256:8588edf317fbe4f16a949bc5a6ccdd22b6e6fd5b4745d128bc40bccf31024ce5", size = 218784, upload-time = "2026-10-30T15:08:38.263Z" }, - { url = "https://files.pythonhosted.org/packages/6d/85/2496a24de80c215b55a15f037bc368a2ed0ce7ecb1e909039ff4e76395de/websockets-17.4-cp314-cp314-win_amd64.whl", hash = "sha256:70293c25d79d1f084fdd665894481547575e429d2a75e8d72caec2f6b6b07af8", size = 219137, upload-time = "2026-10-30T15:08:40.112Z" }, - { url = "https://files.pythonhosted.org/packages/9a/a3/cfe95d4eb569035e5a1d2e5cbeb4ccf0eb15a19e1ef2ad819a85960bf375/websockets-17.4-cp314-cp314-win_arm64.whl", hash = "sha256:adc30e5d064c9e33049e825408fa4e952f4e8a0cf4c329dc2ded72e1bb5bae08", size = 219017, upload-time = "2026-10-30T15:08:41.778Z" }, - { url = "https://files.pythonhosted.org/packages/2b/dd/4143048a2b27303e7de8ef53d7d0ee3987734fbf93e09491d5a1b0a55187/websockets-17.4-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:bbb6bed49f083e2ec8ae0bb21c00c7c5171ab8e08a8b008c61a43fc6c944fdac", size = 219141, upload-time = "2026-10-30T15:08:43.184Z" }, - { url = "https://files.pythonhosted.org/packages/a8/3e/a63b5f3a5c24be2898eb22a3093a56d4ac4cd24ae79e7ab7a1b971ed4611/websockets-17.4-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:c7a56140fcbf4662cb263754a754c651a16fe2196cae1fd232d18f89acd30c83", size = 216675, upload-time = "2026-10-30T15:08:44.682Z" }, - { url = "https://files.pythonhosted.org/packages/d6/80/f238a10f0b23853c665c602a42784023995ac26674e480252c21af39f4f8/websockets-17.4-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:18d3710becc612ec6f0229425bd6495133dfcbf30f7b6569585acc8ed2f1b452", size = 216880, upload-time = "2026-10-30T15:08:46.304Z" }, - { url = "https://files.pythonhosted.org/packages/d1/b1/899b69aba1e8d65ac5bfe90b97ada22a815f1dcd3840bf188104738aac33/websockets-17.4-cp314-cp314t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:00ad98e4bb0df7a6711c645eec16d5a9fdf99f0692bd4f5b6cb85a68677ba8df", size = 226462, upload-time = "2026-10-30T15:08:47.723Z" }, - { url = "https://files.pythonhosted.org/packages/28/a8/598c2b2a22dfe14d352400df804db8b78a68c1498b3f775a658f07f21618/websockets-17.4-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:7849a096d6fdba3f2bdf849eb89f2d233a24400c92faa3efb25fa8dc615b706c", size = 226741, upload-time = "2026-10-30T15:08:49.314Z" }, - { url = "https://files.pythonhosted.org/packages/6e/ad/84a6de3cc3dd4ee336428c31f89a82e002299f83e10d967f0e9a5cbaf591/websockets-17.4-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e30550965c78223439815dbdf40c93eb8931dfbf12427110dcfcaeebef76feb6", size = 227914, upload-time = "2026-10-30T15:08:50.746Z" }, - { url = "https://files.pythonhosted.org/packages/69/ab/1e191b97d60a934c071b7b73c39c5db39721a925cc53acd929c615f85550/websockets-17.4-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:725be1aff55f1c873a79cea0f612df9dff21a9d2c2e05783665b824b8aa7c24e", size = 230059, upload-time = "2026-10-30T15:08:52.596Z" }, - { url = "https://files.pythonhosted.org/packages/f2/57/ef8a64732ef4367091ab05f9b22c1ee4c28657d4a0d088a644198eb5ded6/websockets-17.4-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:b6c7f91520c29420639925fd1cecceac9ca07366b50c09ea24eac1cd116b4866", size = 228486, upload-time = "2026-10-30T15:08:53.967Z" }, - { url = "https://files.pythonhosted.org/packages/48/1f/dbad3afcacf2c52d1fdf83b611d849598f0a047d7333ff476266532877b8/websockets-17.4-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:6531540aa63e6864cb0615a3a5da70ae03191334507852a5385320bb7916df3f", size = 227216, upload-time = "2026-10-30T15:08:55.687Z" }, - { url = "https://files.pythonhosted.org/packages/5b/47/59e325d6ca3e04ba5cc7a139d891ef83cad3fb460a183c8f359f378b69a9/websockets-17.4-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0a57b99f2e28922b5a2434317580fd23fdf118caff4c5b752f5452836426205a", size = 224755, upload-time = "2026-10-30T15:08:57.203Z" }, - { url = "https://files.pythonhosted.org/packages/b8/b6/28a471318dfb0060b58c47d0a252cb5078528a1aa1fdf5e6e88e2a61cf18/websockets-17.4-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:8fd30d217a4275107667fe1d4f601e2d50c797d0727148cfbb384536d65f04d3", size = 227508, upload-time = "2026-10-30T15:08:58.597Z" }, - { url = "https://files.pythonhosted.org/packages/ee/29/7485ac6fc4b342b43964811381f56276fec967cae6a851ae4b815613b10c/websockets-17.4-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:cc0cd4065a65ac98f3e2742ee9f314da9d224db49b07dc17d3a20cef0d79658d", size = 225961, upload-time = "2026-10-30T15:09:00.414Z" }, - { url = "https://files.pythonhosted.org/packages/95/a6/520e1f7aa9644ddf58f5a51fc37f46e15293a68cd35b70d5b81b7331ca1e/websockets-17.4-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:71f76bb8e59be847330b8a8d3753f85397677e128f9f9692c215f8cf721cefc7", size = 226851, upload-time = "2026-10-30T15:09:01.979Z" }, - { url = "https://files.pythonhosted.org/packages/e5/0d/444799abe7418f361da8c201c6858b64b4e8d47265f90851e5cb68b4d90f/websockets-17.4-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:c2db7b9e2d726f7e051bedb67abcf460b84b11437b2f9fdacda7e6931dace85b", size = 227869, upload-time = "2026-10-30T15:09:03.405Z" }, - { url = "https://files.pythonhosted.org/packages/cb/86/6da20322a07364a0ab0787a2b0d4367770f59404fdab6e35122413a7f63e/websockets-17.4-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:332b88022d0acd47c44158bcd43f47f14eaddcd979247f242b1a33291c45cdd1", size = 225562, upload-time = "2026-10-30T15:09:04.891Z" }, - { url = "https://files.pythonhosted.org/packages/2a/da/53e44d96238dc207011ad5d93b0540c58e1c680a86f48dc3fa8e5138b343/websockets-17.4-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:5cec3e7fbc911ff4fcf43b24aaf1b96906381ad36030f42897def3ff4b78729e", size = 226334, upload-time = "2026-10-30T15:09:06.42Z" }, - { url = "https://files.pythonhosted.org/packages/18/08/82cea972a87f229ee1903e9adf74c17d1e6c4371d581ebb11ccbed4e3a7b/websockets-17.4-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:cbdf4b42f4514422051889424fd03bc269be8c5d751bf39ec29ad761590bd10d", size = 226767, upload-time = "2026-10-30T15:09:07.837Z" }, - { url = "https://files.pythonhosted.org/packages/96/f3/ee6afff802e39e8d6ef29ee4bdc30f8272aaa38295c19a911fad91fe95fc/websockets-17.4-cp314-cp314t-win32.whl", hash = "sha256:16550e24ac22c27e0a728100d8de196b5f054bab6748ef9f0b168fb8b3c32e35", size = 218918, upload-time = "2026-10-30T15:09:09.31Z" }, - { url = "https://files.pythonhosted.org/packages/11/56/b0b07917f9c85a4d24a37300f4ae888bfa7c20f08902dd6a5c61a0d1b26f/websockets-17.4-cp314-cp314t-win_amd64.whl", hash = "sha256:5ec906bb21b35e66cfdcc2ea0133f249f52b7d89e3e45ec8d2bd2d84a0255d7d", size = 219260, upload-time = "2026-10-30T15:09:10.832Z" }, - { url = "https://files.pythonhosted.org/packages/19/a6/a63113909ea602d3d22b0f32a7a9950d8d18b725cfdce735eab9b5f5d198/websockets-17.4-cp314-cp314t-win_arm64.whl", hash = "sha256:c00f0c45851a2c61efffd03dde8fb4d594026b5cc18196c94e15460f1225f2ed", size = 219176, upload-time = "2026-10-30T15:09:12.444Z" }, - { url = "https://files.pythonhosted.org/packages/ee/be/4032fde05e62d1c52edd250fda475e910cac0cd180e377690bff24147b5e/websockets-17.4-cp315-cp315-macosx_10_15_universal2.whl", hash = "sha256:8c51ac7b31578a7275650f580aac985940985b6d2e57247ac6d5e07f2c936cd6", size = 218740, upload-time = "2026-10-30T15:09:13.833Z" }, - { url = "https://files.pythonhosted.org/packages/74/1c/b47f5786eb45599072411571651606fb22f6e825d522d627daad974ea636/websockets-17.4-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:023dc13bdc42a55e152acc81c39c90ec6cc4159ed17d23c6d73460fa2a73ab16", size = 216470, upload-time = "2026-10-30T15:09:15.394Z" }, - { url = "https://files.pythonhosted.org/packages/70/98/0021f55de633617b4a8390cca17e700c9ba5d99323103128412dc2c15aca/websockets-17.4-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:6fd8cac4907fec8302726d49e6969acfffaf720bc39b1cee23f473b81f4dce01", size = 216695, upload-time = "2026-10-30T15:09:17.185Z" }, - { url = "https://files.pythonhosted.org/packages/28/56/2c67389b47c4b9e9e9318d9b3e4bb52a2fef3749ff00b0b151a342c4d42d/websockets-17.4-cp315-cp315-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:4441d655a53185ef1b01b1d42ad9b3a96b905110a9219043e3fdaec855ba3b6e", size = 226134, upload-time = "2026-10-30T15:09:19.156Z" }, - { url = "https://files.pythonhosted.org/packages/75/bd/ee3a679a10741a0cdd7aa8bdd6d03999069672826aa7a6495fdf589ed961/websockets-17.4-cp315-cp315-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:3acc45494c08a4d27375a2c28474537f68910219f42624a08011221b04623d04", size = 226569, upload-time = "2026-10-30T15:09:20.587Z" }, - { url = "https://files.pythonhosted.org/packages/c4/42/b293a5d07099549797138d09fda5bf878d302b4980e61678981c8dfdc98f/websockets-17.4-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3b78b39377630a70aa2198e5f03be416e690364a046b1d8af80a9263733083d0", size = 227726, upload-time = "2026-10-30T15:09:22.015Z" }, - { url = "https://files.pythonhosted.org/packages/2d/81/d048ff83c4d0fc386f6008529d12690d0dcb410f73570430f13fe4d543f0/websockets-17.4-cp315-cp315-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:6cf4c002268da5c11cae9083aec71ac943bce9d95e0f83c8bf9a95a3ce421fbb", size = 229426, upload-time = "2026-10-30T15:09:23.444Z" }, - { url = "https://files.pythonhosted.org/packages/e6/21/1df51f94047dfb76c32fd7508036e4b55352d0f04fd0e3bee525a2122225/websockets-17.4-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ed7fe197b8bb66eef4f62c052e33752d456d2fdda74805469d4bd954950ab339", size = 228211, upload-time = "2026-10-30T15:09:24.902Z" }, - { url = "https://files.pythonhosted.org/packages/cf/13/33d6a28471da4c30a98a2313c76f984be2056a703c5c532225dc28f5dba3/websockets-17.4-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:f0494d3d97502e270282cc6a1f8648cd7335b4fe8d5c452006e5b7f9d62b8892", size = 227106, upload-time = "2026-10-30T15:09:26.315Z" }, - { url = "https://files.pythonhosted.org/packages/4a/86/ff8441e56ca677e51f9c826868fccde2a82bafe0ffa337fd38823b64253a/websockets-17.4-cp315-cp315-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:ab9e4bd60796866c578e3afa0a17c98636887827a39c2e238a61989c18fd8e7b", size = 224499, upload-time = "2026-10-30T15:09:28.116Z" }, - { url = "https://files.pythonhosted.org/packages/da/91/470d7a619ce4aa837ff5b6a5836227c43bdfdc42ef837cce48f508992438/websockets-17.4-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:8d148b4b295224d3a19e7bd9f02ebe7344de254b3b2c4d0628ce42ade0bca119", size = 227213, upload-time = "2026-10-30T15:09:29.847Z" }, - { url = "https://files.pythonhosted.org/packages/a4/ba/55ed1422d6c73b5b81996ca195f2a256a339b26c553f5686afc2a926bc2b/websockets-17.4-cp315-cp315-musllinux_1_2_armv7l.whl", hash = "sha256:6597a1f7413189b4bc58437babcdf39b79da416e5c477ae98323a88ecc108188", size = 225876, upload-time = "2026-10-30T15:09:31.249Z" }, - { url = "https://files.pythonhosted.org/packages/e9/59/f133d260e7a48d3e231c3a495eeb6114b880c1e96bfc781a949c1f73991c/websockets-17.4-cp315-cp315-musllinux_1_2_i686.whl", hash = "sha256:a9b0026538719f7a532998d84640ab2e91ca1a051ce4b8d924fdcb607307e921", size = 226403, upload-time = "2026-10-30T15:09:33.199Z" }, - { url = "https://files.pythonhosted.org/packages/45/16/bb3355453ffdc31d3a14ddc0b50e058f13a97d2ed019ba6c380e03456169/websockets-17.4-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:a703f23ca15a51251fc94f1774683f5aa511588a7ad6bbb83960cdb2a4dcd978", size = 227558, upload-time = "2026-10-30T15:09:34.703Z" }, - { url = "https://files.pythonhosted.org/packages/0c/ab/f3d55a83c2a4daa8bf62594b00a721dc8767518ccb833f932b0178eb6c19/websockets-17.4-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:6b061ea7ca94966af7cd7a87cb189ff15972c103244611a2b1e8408c04f1dbe6", size = 225369, upload-time = "2026-10-30T15:09:36.204Z" }, - { url = "https://files.pythonhosted.org/packages/88/66/3a320bfb718d9ae1eff15ba7790979c0e6fdec74e388430f426e6647d7f4/websockets-17.4-cp315-cp315-musllinux_1_2_s390x.whl", hash = "sha256:e6d2a185ec4ff0478089305abd833da3a9fda8803eb77325b89ebeae5585a3b7", size = 226268, upload-time = "2026-10-30T15:09:37.565Z" }, - { url = "https://files.pythonhosted.org/packages/da/ee/1f9cdeeaaa2d5e158b7a40f971e74b641b35f977674b46229a5bb14e270a/websockets-17.4-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:9a4e95d56994a45ac76541853796720436ffe462957d0b1b89e87ff3d3b1627e", size = 226530, upload-time = "2026-10-30T15:09:39.171Z" }, - { url = "https://files.pythonhosted.org/packages/da/28/506406ef09e6e168796f0187bdac0767f38a560e6785c4ee26e583aaaf76/websockets-17.4-cp315-cp315-win32.whl", hash = "sha256:b7ea61af293a153f2d67430038cf0efc10140caa623f2bdf5a9f5a457ff20f57", size = 218751, upload-time = "2026-10-30T15:09:40.748Z" }, - { url = "https://files.pythonhosted.org/packages/25/a6/818647a9a9b3ee8bf131e9ab4fa1f2db9c6539f08e7084dd57549e0bd49d/websockets-17.4-cp315-cp315-win_amd64.whl", hash = "sha256:8b45d40f07081b377f0b837ddbfba4a9ab4a89a7b569d3c095436564e767a27b", size = 219045, upload-time = "2026-10-30T15:09:42.251Z" }, - { url = "https://files.pythonhosted.org/packages/3d/b2/0338a9abec3df8556627af987352657ce1c8456f2060b54741570b174122/websockets-17.4-cp315-cp315-win_arm64.whl", hash = "sha256:29b615c2d5dd883f89c107a782681b73a7aa8b2bd894130310e45eb09b143913", size = 218957, upload-time = "2026-10-30T15:09:43.866Z" }, - { url = "https://files.pythonhosted.org/packages/68/92/22e83d003cdbd22be5d35e28c260203e9fbb6c73b17a8e1509f4ad49e74d/websockets-17.4-cp315-cp315t-macosx_10_15_universal2.whl", hash = "sha256:c568e72f5425a74616daeb824afe28da460cbeea036432f41c6af5380b83300d", size = 219056, upload-time = "2026-10-30T15:09:45.528Z" }, - { url = "https://files.pythonhosted.org/packages/2f/ca/071d38e7237f6ada4f577b74f7cbf5bc2ff7e1f9360ebd2837e74a22dfd4/websockets-17.4-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:bfc86dff091104eec770c29ea1831dbe191968a70aa2d8ae8eda3240d863970a", size = 216630, upload-time = "2026-10-30T15:09:46.951Z" }, - { url = "https://files.pythonhosted.org/packages/fa/76/22d4523f92d88b8f5ebfd3df7ab5e825146af100f7e2caeae7d359ae51ea/websockets-17.4-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:f5f06f59e19aa0770aaf651ce91c196fa620b35aed49a7e6c36e7335f3f83db7", size = 216841, upload-time = "2026-10-30T15:09:48.285Z" }, - { url = "https://files.pythonhosted.org/packages/87/29/bc94be4a8bc19ef518e9efecd90a992f2991b7cfc6eb8a7430c4e2dc097c/websockets-17.4-cp315-cp315t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:8f32a6cb0b101170abc2d8053af1473a2a29ef2a06d7130994ee8455a50f5dbf", size = 226992, upload-time = "2026-10-30T15:09:49.776Z" }, - { url = "https://files.pythonhosted.org/packages/fa/25/58f69b5fec064764ddf5b88045397433cdb028f5b17c82fbe047fd31fff7/websockets-17.4-cp315-cp315t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:72d0a731eccf482d5661c6711abfcd5921f3dbfbbb0789061e1918ef4bc89c70", size = 227258, upload-time = "2026-10-30T15:09:51.172Z" }, - { url = "https://files.pythonhosted.org/packages/21/7c/bc932a54c5f1bd78461574aea539fc562fd2de494738a2c0675c4de860be/websockets-17.4-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:48c83103f82fce36191a9e3a8a80731d4340e2da544eae8c5aaaf6a45280e7d0", size = 228589, upload-time = "2026-10-30T15:09:52.628Z" }, - { url = "https://files.pythonhosted.org/packages/c4/92/57ec83066d0bfa8a9b9f594bc61951073c4a86e34c562a5292604118dab6/websockets-17.4-cp315-cp315t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c8052c3058c402d53602583da5ddcf1a15a63ab1efe0222f47c7be59944e6463", size = 230217, upload-time = "2026-10-30T15:09:54.058Z" }, - { url = "https://files.pythonhosted.org/packages/6e/fc/0f2fe533b5b4dc22ac704b3357f5c99fa60a3837218b3c6c6ad63a60120e/websockets-17.4-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:0c22a9c6b2349204f56123dd0ca7779e989d68e336d0dc02ad823485d44925de", size = 229026, upload-time = "2026-10-30T15:09:55.727Z" }, - { url = "https://files.pythonhosted.org/packages/7c/cc/ed28307835106a9a2dbd1a5efc597e8befa3d0a5f2b46a4c1e466b2f4759/websockets-17.4-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:0dcce83837328e6795225ead920d3aa8d867cc9d6922aa558b0e9111599fdbb9", size = 227904, upload-time = "2026-10-30T15:09:57.221Z" }, - { url = "https://files.pythonhosted.org/packages/39/4d/24ad7deddc7b31c3e430acc1c00c7b384ae42f1f973e9cc01aa42d19628f/websockets-17.4-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:4b79ea31cf277c72d2307c6cb8bd32a2c151959e80a2f24fa85df620c5f2860c", size = 225253, upload-time = "2026-10-30T15:09:58.624Z" }, - { url = "https://files.pythonhosted.org/packages/93/f6/9c92230ebfab42fee482b236c45c32ed34b24f7360080b400cce6cfcac11/websockets-17.4-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:3d27153a0413696767b98b5d96173a2a7e27cbfca02000a6069cea7b977765a7", size = 228089, upload-time = "2026-10-30T15:10:00.308Z" }, - { url = "https://files.pythonhosted.org/packages/fe/7a/f523830e562da9b1d7a610174752753720c5e47e84b59b5fc47721d416bd/websockets-17.4-cp315-cp315t-musllinux_1_2_armv7l.whl", hash = "sha256:e0feb03a338f8f5e819ae23a73aabb7b46fd3b73f15f7df782dd12d99e2b02ad", size = 226743, upload-time = "2026-10-30T15:10:01.744Z" }, - { url = "https://files.pythonhosted.org/packages/2c/e6/d1a56495cb7b1a0a4688145131be38cfd0c1342bde8125e136a6e6ee494e/websockets-17.4-cp315-cp315t-musllinux_1_2_i686.whl", hash = "sha256:9ff89e36451a19775e7556d95ebfa4a0b24b84cc87565d6b5d0ec8ea82bf3f2c", size = 227237, upload-time = "2026-10-30T15:10:03.417Z" }, - { url = "https://files.pythonhosted.org/packages/44/41/c4e53f7ad63838d7eba6e82c5d743827e91dafe5e48c88a58f7e90043945/websockets-17.4-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:ee6c4e0085bff5f6621bf9c53452584dcb91ebd993ce841e1f4061ac12b6b556", size = 228348, upload-time = "2026-10-30T15:10:05.149Z" }, - { url = "https://files.pythonhosted.org/packages/ca/01/f6f78c3edeb8ad2b3c35a8c4117ec2cf9346215afaed8155af1e7933818b/websockets-17.4-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:1962f3bfde085af18878f1bb1aafb300c9a6ac33da886d0b0d97e33c9ce7a222", size = 226099, upload-time = "2026-10-30T15:10:06.588Z" }, - { url = "https://files.pythonhosted.org/packages/8d/01/d8c11740231b63d1aba6bad6b1d4e72e8384b26c5448801da238ebe82c92/websockets-17.4-cp315-cp315t-musllinux_1_2_s390x.whl", hash = "sha256:42d7a6e818214336cf7af9a3aae5c6923f94f09fa07ac5aab98268ba2a98a6d5", size = 226956, upload-time = "2026-10-30T15:10:08.141Z" }, - { url = "https://files.pythonhosted.org/packages/99/87/dbfd43ae01ea8fdb7478a1b3d58b32aca83bb9c4aa61ebe187d1e188ac8e/websockets-17.4-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:c9f8fdb7bbefc4907c2bb3593f810f2b67a2d5329e1d38724a1aa3d763cf63eb", size = 227253, upload-time = "2026-10-30T15:10:09.533Z" }, - { url = "https://files.pythonhosted.org/packages/bf/8e/fbd968a75428063560ada02d564de8d6c49ca34ec29dfb78e5d900f4b0ef/websockets-17.4-cp315-cp315t-win32.whl", hash = "sha256:506623128d7a55b726a5a46e4c9a8eae4c9dd0f04ff60b041fe7df85b9d034fe", size = 218877, upload-time = "2026-10-30T15:10:10.925Z" }, - { url = "https://files.pythonhosted.org/packages/f9/53/8f37a3943517bba77fc86f7c4162c455018c5b6d760c5e9c9a11de9e37f7/websockets-17.4-cp315-cp315t-win_amd64.whl", hash = "sha256:6e6558efbb256b532c9f06a21ba42bcac729718e365c505819f181f25e5c0eca", size = 219195, upload-time = "2026-10-30T15:10:12.336Z" }, - { url = "https://files.pythonhosted.org/packages/69/35/cf33cba7248fcd80cfe5911ffe67aa2637f50c2bfaada123b1e9d2aeca90/websockets-17.4-cp315-cp315t-win_arm64.whl", hash = "sha256:fcac44d917672ad6257ad64b80b5168306f168a78cab5c0612e4c699caed18cf", size = 219117, upload-time = "2026-10-30T15:10:13.771Z" }, - { url = "https://files.pythonhosted.org/packages/a0/80/78c580302991d229ac5ad0a00c361916f7f84deaf6dd76370034dd8e7383/websockets-17.4-pp311-pypy311_pp80-macosx_10_15_x86_64.whl", hash = "sha256:73b00645316121105274fd266ed54a20e6514650126d399cdea39876ab1e7b04", size = 216364, upload-time = "2026-10-30T15:10:15.472Z" }, - { url = "https://files.pythonhosted.org/packages/d9/27/7d18d381994c7c27a855131ae064ff43ec00ded636b7c6ead4abb4cec841/websockets-17.4-pp311-pypy311_pp80-macosx_11_0_arm64.whl", hash = "sha256:02f380df26de14999ecace203fe1396ac14d1c6132afc7924eb6f8c8b646c69d", size = 216642, upload-time = "2026-10-30T15:10:17.153Z" }, - { url = "https://files.pythonhosted.org/packages/fc/91/43e73997fbdc7ef3cb434148888329113a07b66d97a8ea6aa2f93e574028/websockets-17.4-pp311-pypy311_pp80-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:f5b1d315a615cec81a79e2ce3a94221dc5c23e7fd4012897085d3b5e5a5638d0", size = 217587, upload-time = "2026-10-30T15:10:19.123Z" }, - { url = "https://files.pythonhosted.org/packages/a8/17/5e3e6be945512aff7351c9f60134803902ccb07cd7d6c9becdfa349a32d5/websockets-17.4-pp311-pypy311_pp80-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:046ed16d3d83d64594e4a40655fef061ccf36059d8c30a01feca8a9481fe13b8", size = 217478, upload-time = "2026-10-30T15:10:20.665Z" }, - { url = "https://files.pythonhosted.org/packages/7d/5f/0a1ee98aeff04c200492a479a386ff106d1ef6d5c9d6613959b3e3d79469/websockets-17.4-pp311-pypy311_pp80-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5f772007dfba8941873dbd276b6a6845428cc740888b5c6c37bf483b1ea34b42", size = 218371, upload-time = "2026-10-30T15:10:22.35Z" }, - { url = "https://files.pythonhosted.org/packages/17/97/acb333fa9a54bb1ad616c1add65185f9ab580c3c76366a3d1abc1090979b/websockets-17.4-pp311-pypy311_pp80-win_amd64.whl", hash = "sha256:accb5e9492b9bc9c9aeec5b72ea8f2ddcbefc6143d1c626fba960ecbdc89807e", size = 306811, upload-time = "2026-10-30T15:10:23.76Z" }, - { url = "https://files.pythonhosted.org/packages/e9/a3/d8fbc72c5c0e78905caf2d6dcf806e532451e3f48e2a09a8ebe1de9ad412/websockets-17.4-pp312-pypy312_pp80-macosx_10_15_x86_64.whl", hash = "sha256:c7f66a53e9b7ec831abb15e3d9b6cee8f52d6a24cd0a374786bf46c3ec218bc6", size = 216397, upload-time = "2026-10-30T15:10:25.255Z" }, - { url = "https://files.pythonhosted.org/packages/d3/de/1bf313cd0f4662df4884a7602932cd13347090e59dd6047865eee2bb5aa5/websockets-17.4-pp312-pypy312_pp80-macosx_11_0_arm64.whl", hash = "sha256:4fb2db1f649b6464711846b5bb9c1611bd906ce939d9460cbd1fa419552cd6c3", size = 216664, upload-time = "2026-10-30T15:10:27.016Z" }, - { url = "https://files.pythonhosted.org/packages/30/e2/7912bd417511b54907853bd495aef2daee111062dbafd43d133a3f7253a7/websockets-17.4-pp312-pypy312_pp80-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:32110d954d9d0e51f36edb0396673bf4d35193a0a80ba7013bf7f7d58a33ca07", size = 217603, upload-time = "2026-10-30T15:10:28.475Z" }, - { url = "https://files.pythonhosted.org/packages/56/6f/2e8d5610f6184a2e1720bf8ce256402ed99ad30ea87c461fba5bc4d651d9/websockets-17.4-pp312-pypy312_pp80-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:88ba8a439b2bad97bb69c38db5bf0ec16a061ee834cf0f244089186ee803e899", size = 217489, upload-time = "2026-10-30T15:10:29.999Z" }, - { url = "https://files.pythonhosted.org/packages/29/3a/a05bc57eadcd7e8e072d917888128e6d22e1203984afb21a8da3198982fe/websockets-17.4-pp312-pypy312_pp80-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:868744c68e9342768888c7326604da2228c19bb6946aa46b5f9e1ac32ea8d40b", size = 218356, upload-time = "2026-10-30T15:10:31.432Z" }, - { url = "https://files.pythonhosted.org/packages/b2/49/eed86bfb8863093a82cbaa52c9159be1ce2374d5ace6fe1f8e8031567e7d/websockets-17.4-pp312-pypy312_pp80-win_amd64.whl", hash = "sha256:829bcaa90be8737c132d9515d6a466e8528e3b3d050d3f3466f36ea94d3beb48", size = 306838, upload-time = "2026-10-30T15:10:32.954Z" }, - { url = "https://files.pythonhosted.org/packages/eb/27/9db924cb0dbf22eade78d98fbae77790f9bf6bc729e6ab29aef9d68e4156/websockets-17.4-py3-none-any.whl", hash = "sha256:c6bd2c9781915592b209160d0f017d4c7c82ad53075e6b0c24d2a89299e7f9e9", size = 212900, upload-time = "2026-10-30T15:10:34.482Z" }, -] diff --git a/research/notebooks/ca_shorts_filings_study.py b/research/notebooks/ca_shorts_filings_study.py deleted file mode 100644 index f116355e..00000000 --- a/research/notebooks/ca_shorts_filings_study.py +++ /dev/null @@ -1,251 +0,0 @@ -import marimo - -__generated_with = "0.26.0" -app = marimo.App(width="medium") - - -@app.cell -def _(): - import os - from pathlib import Path - - import marimo as mo - import polars as pl - - from stockbot import ( - MarketDataStore, - TrialLedgerClient, - compute_vault_cutoff_ts, - resolve_duckdb_budget, - run_event_study_trial, - run_signal_study, - vault_cutoff_date_str, - ) - - curated_root = Path(os.environ.get("STOCK_BOT_CURATED_ROOT", "/mnt/data/stockbot/m1-curated")) - max_ingested_date = os.environ.get("STOCK_BOT_MAX_INGESTED_DATE", "2025-08-13") - vault_cutoff_ts = compute_vault_cutoff_ts(max_ingested_date) - vault_cutoff_date = vault_cutoff_date_str(vault_cutoff_ts) - trial_ledger_dsn = os.environ.get("STOCK_BOT_TRIAL_LEDGER_DSN", "") - temp_dir = os.environ.get("STOCK_BOT_DUCKDB_TEMP_DIRECTORY", "/tmp/stockbot-duckdb") - - mo.md( - f""" - # Canadian `ceoShorts` & `qmFilings` Signal Lab Study (M1) - - - **Curated Root:** `{curated_root}` - - **Max Ingested Date:** `{max_ingested_date}` - - **Rolling 6-Month Vault Cutoff (exclusive):** `{vault_cutoff_date}` - - **Trial Ledger Configured:** `{"yes" if bool(trial_ledger_dsn) else "no"}` - """ - ) - return ( - MarketDataStore, - TrialLedgerClient, - curated_root, - mo, - pl, - resolve_duckdb_budget, - run_event_study_trial, - run_signal_study, - temp_dir, - trial_ledger_dsn, - vault_cutoff_date, - vault_cutoff_ts, - ) - - -@app.cell -def _( - MarketDataStore, - curated_root, - mo, - pl, - resolve_duckdb_budget, - temp_dir, - vault_cutoff_date, - vault_cutoff_ts, -): - _budget = resolve_duckdb_budget( - memory_limit="4GB", - threads=4, - temp_directory=temp_dir, - ) - _adj_fenced = curated_root / "adj_factors_fenced" / "part.parquet" - if not _adj_fenced.exists(): - _adj_fenced = curated_root / "adj_factors" / "part.parquet" - _adj_mode = "total" if _adj_fenced.exists() else "raw" - - with MarketDataStore( - curated_root, - vault_cutoff_ts=vault_cutoff_ts, - budget=_budget, - adj_factors_path=_adj_fenced if _adj_fenced.exists() else None, - ) as _store: - _ca_bars = _store.bars( - currencies=["CAD"], - from_date="2017-01-01", - to_date=vault_cutoff_date, - adjustment=_adj_mode, - ) - _ca_shorts = _store.shorts_as_of( - from_date="2017-01-01", - to_date=vault_cutoff_date, - ) - _ca_events = _store.events( - kinds=["filing"], - from_date="2017-01-01", - to_date=vault_cutoff_date, - ) - - _ca_listing_ids = _ca_bars.select("listing_id").unique() - _ca_events = _ca_events.join(_ca_listing_ids, on="listing_id", how="semi") - _ca_shorts = _ca_shorts.join(_ca_listing_ids, on="listing_id", how="semi") - - # Confirm zero Vault rows leaked into any frame - _vault_bar_leaks = int( - _ca_bars.filter(pl.col("session_date").cast(pl.String) >= vault_cutoff_date).height - ) - assert _vault_bar_leaks == 0, f"Vault fence breach: {_vault_bar_leaks} bars >= {vault_cutoff_date}" - - # Build strict PIT ceoShorts signal panel (join_asof known_at <= bar.ts) with 5-session forward return - _bars_fwd = ( - _ca_bars.sort(["listing_id", "session_date"]) - .with_columns( - (pl.col("close").shift(-5).over("listing_id") / pl.col("close") - 1.0).alias( - "forward_return" - ), - (pl.col("close") * pl.col("volume")).alias("dollar_vol"), - ) - .filter(pl.col("forward_return").is_finite() & (pl.col("close") > 0.10)) - ) - - _shorts_sorted = ( - _ca_shorts.select(["listing_id", "known_at", "shares_short", "net_change"]) - .filter(pl.col("shares_short") > 0) - .sort(["listing_id", "known_at"]) - ) - - shorts_panel = ( - _bars_fwd.sort(["listing_id", "ts"]) - .join_asof( - _shorts_sorted, - left_on="ts", - right_on="known_at", - by="listing_id", - strategy="backward", - ) - .filter(pl.col("shares_short").is_not_null()) - .with_columns( - (-(pl.col("shares_short") / (pl.col("volume").clip(lower_bound=1.0)))).alias("signal") - ) - .select(["session_date", "listing_id", "signal", "forward_return"]) - ) - - ca_bars_summary = { - "adjustment": _adj_mode, - "ca_bars_rows": int(_ca_bars.height), - "ca_shorts_rows": int(_ca_shorts.height), - "ca_filings_rows": int(_ca_events.height), - "shorts_panel_rows": int(shorts_panel.height), - "vault_bar_leaks": _vault_bar_leaks, - } - ca_bars_slim = _ca_bars.filter(pl.col("close") >= 0.10).select(["listing_id", "session_date", "ts", "close"]) - ca_filings_slim = _ca_events.select(["listing_id", "known_at", "subtype"]) - - mo.md( - f""" - ## Loaded Curated Canadian Datasets (Zero Vault Rows) - - - **Adjustment mode:** `{ca_bars_summary['adjustment']}` - - **Canadian `bars_1d` rows:** `{ca_bars_summary['ca_bars_rows']:,}` (`vault_bar_leaks = {ca_bars_summary['vault_bar_leaks']}`) - - **Canadian `shorts` (`ceoShorts`, +4bd lag) rows:** `{ca_bars_summary['ca_shorts_rows']:,}` - - **Canadian `events` (`qmFilings`) rows:** `{ca_bars_summary['ca_filings_rows']:,}` - - **Joined PIT `ceoShorts` panel rows:** `{ca_bars_summary['shorts_panel_rows']:,}` - """ - ) - return ca_bars_slim, ca_bars_summary, ca_filings_slim, shorts_panel - - -@app.cell -def _( - TrialLedgerClient, - ca_bars_slim, - ca_filings_slim, - mo, - run_event_study_trial, - run_signal_study, - shorts_panel, - trial_ledger_dsn, - vault_cutoff_date, -): - if not trial_ledger_dsn: - mo.stop(True, mo.md("Set `STOCK_BOT_TRIAL_LEDGER_DSN` to write trials to `trial_ledger`.")) - - _ledger = TrialLedgerClient(trial_ledger_dsn) - - shorts_study = run_signal_study( - panel=shorts_panel, - ledger=_ledger, - principal_id="operator", - universe_market="CA_EQ", - horizon_bucket="swing_1_10d", - horizon_label="5d", - expression="neg_ciro_short_interest_to_volume_5d", - params={"lag_bd": 4, "horizon_sessions": 5, "min_price_cad": 0.10, "n_quantiles": 5}, - vault_cutoff_date=vault_cutoff_date, - n_quantiles=5, - min_cross_section=10, - ledger_series="rank_ic", - ) - - filings_study = run_event_study_trial( - bars_df=ca_bars_slim, - events_df=ca_filings_slim, - ledger=_ledger, - principal_id="operator", - universe_market="CA_EQ", - horizon_bucket="swing_1_10d", - expression="ca_qm_filings_abnormal_return_event_study", - params={"pre_days": 5, "post_days": 10, "benchmark": "equal_weight"}, - vault_cutoff_date=vault_cutoff_date, - pre_days=5, - post_days=10, - min_events=5, - ) - - _s_trial = shorts_study["trial"] - _s_dsr = shorts_study["dsr"] - _s_ana = shorts_study["analysis"] - _f_trial = filings_study["trial"] - _f_dsr = filings_study["dsr"] - _f_stu = filings_study["study"] - - mo.md( - f""" - ## Study Results & `trial_ledger` Deflated Sharpe - - ### 1. Canadian `ceoShorts` 5-Day Forward Return Signal - - **Status:** `{shorts_study['status']}` - - **Trial ID:** `{_s_trial.trial_id if _s_trial else None}` | **n_obs:** `{_s_trial.n_obs if _s_trial else 0}` - - **Mean Rank-IC:** `{_s_ana['mean_rank_ic']:.6f}` (Newey-West t = `{_s_ana['rank_ic_nw_t']:.3f}`) - - **Mean Q5-Q1 Spread:** `{_s_ana['mean_quantile_spread']:.6f}` (Turnover = `{_s_ana['mean_top_quantile_turnover']:.3f}`) - - **Recency Gate (Post-2023):** `{_s_ana['recency_rank_ic']}` - - **Unannualized Sharpe:** `{_s_trial.sharpe_unann if _s_trial else float('nan'):.6f}` - - **Cluster Size ($K$) / Effective Trials ($\\hat{{N}}$):** `{_s_dsr.cluster_size if _s_dsr else 0}` / `{_s_dsr.effective_trials if _s_dsr else 0.0:.4f}` - - **Deflated Sharpe Ratio (DSR):** `{_s_dsr.dsr if _s_dsr else float('nan'):.6f}` (`passes_gate = {_s_dsr.passes_gate if _s_dsr else False}`) - - ### 2. Canadian `qmFilings` Event Study (`[-5, +10]` sessions) - - **Status:** `{filings_study['status']}` - - **Trial ID:** `{_f_trial.trial_id if _f_trial else None}` | **Events Used:** `{_f_stu.get('events_used', 0)}` | **Event Dates:** `{_f_stu.get('n_dates', 0)}` - - **Mean Post-Event CAR:** `{_f_stu.get('car_mean', float('nan')):.6f}` (Newey-West t = `{_f_stu.get('car_nw_t', float('nan')):.3f}`) - - **Recency Gate (Post-2023):** `{_f_stu.get('recency')}` - - **Cluster Size ($K$) / Effective Trials ($\\hat{{N}}$):** `{_f_dsr.cluster_size if _f_dsr else 0}` / `{_f_dsr.effective_trials if _f_dsr else 0.0:.4f}` - - **Deflated Sharpe Ratio (DSR):** `{_f_dsr.dsr if _f_dsr else float('nan'):.6f}` (`passes_gate = {_f_dsr.passes_gate if _f_dsr else False}`) - """ - ) - return filings_study, shorts_study - - -if __name__ == "__main__": - app.run() diff --git a/scripts/research-copilot-mcp.ts b/scripts/research-copilot-mcp.ts deleted file mode 100644 index 391d5f00..00000000 --- a/scripts/research-copilot-mcp.ts +++ /dev/null @@ -1,112 +0,0 @@ -/** - * Runnable stdio entrypoint for the headless MCP research copilot server. - * - * Parses `RESEARCH_MCP_*` environment variables, composes the Vault-fenced - * PostgreSQL executor, DuckDB market data store, and read-only library card - * reader, and serves newline-delimited JSON-RPC 2.0 over stdio. - * - * Fail-closed: configuration or host errors write a single fixed line to - * stderr and exit with code 1 without exposing DSNs, passwords, or raw error - * objects. Stdout carries only MCP protocol bytes. - */ - -import { randomUUID } from 'node:crypto'; -import { - type LibraryCardReaderHandle, - type ManagedMarketDataStore, - type ManagedPostgresExecutor, - type ResearchCopilotHostConfig, - type ResearchCopilotStdioHostDeps, - type StdioInput, - type StdioOutput, - createLibraryCardReader, - createNodeLibraryCardFs, - parseResearchCopilotHostConfig, - runResearchCopilotStdioHost, -} from '@stock-bot/research/mcp'; - -export const RESEARCH_COPILOT_CONFIG_ERROR_LINE = - 'Research copilot MCP server failed: invalid RESEARCH_MCP_* configuration.\n'; - -export const RESEARCH_COPILOT_HOST_ERROR_LINE = - 'Research copilot MCP server failed while running stdio host.\n'; - -export interface ResearchCopilotStderr { - write(chunk: string): boolean; -} - -export interface ResearchCopilotMcpDeps { - readonly env?: Readonly>; - readonly input?: StdioInput; - readonly output?: StdioOutput; - readonly stderr?: ResearchCopilotStderr; - readonly openExecutor?: ResearchCopilotStdioHostDeps['openExecutor']; - readonly openStore?: ResearchCopilotStdioHostDeps['openStore']; - readonly createLibraryCardReader?: ResearchCopilotStdioHostDeps['createLibraryCardReader']; - readonly newId?: () => string; - readonly now?: () => Date | number; -} - -async function defaultOpenExecutor( - config: ResearchCopilotHostConfig -): Promise { - const { openResearchCopilotExecutor } = await import( - '../libs/data/postgres/src/research-copilot-executor' - ); - return openResearchCopilotExecutor(config); -} - -async function defaultOpenStore( - config: ResearchCopilotHostConfig -): Promise { - const { openResearchCopilotStore } = await import( - '../libs/data/duckdb/src/research-copilot-store' - ); - return openResearchCopilotStore(config); -} - -function defaultCreateLibraryCardReader( - config: ResearchCopilotHostConfig -): LibraryCardReaderHandle { - return createLibraryCardReader({ - root: config.libraryRoot, - fs: createNodeLibraryCardFs(), - }); -} - -export async function runResearchCopilotMcp( - deps: ResearchCopilotMcpDeps = {} -): Promise { - const stderr = deps.stderr ?? process.stderr; - - let config: ResearchCopilotHostConfig; - try { - config = parseResearchCopilotHostConfig(deps.env ?? process.env); - } catch { - stderr.write(RESEARCH_COPILOT_CONFIG_ERROR_LINE); - return 1; - } - - try { - await runResearchCopilotStdioHost({ - config, - openExecutor: deps.openExecutor ?? defaultOpenExecutor, - openStore: deps.openStore ?? defaultOpenStore, - createLibraryCardReader: deps.createLibraryCardReader ?? defaultCreateLibraryCardReader, - newId: deps.newId ?? randomUUID, - now: deps.now ?? Date.now, - stdio: { - input: deps.input ?? process.stdin, - output: deps.output ?? process.stdout, - }, - }); - return 0; - } catch { - stderr.write(RESEARCH_COPILOT_HOST_ERROR_LINE); - return 1; - } -} - -if (import.meta.main) { - process.exitCode = await runResearchCopilotMcp(); -} diff --git a/scripts/test/m2-gap-audit.test.ts b/scripts/test/m2-gap-audit.test.ts deleted file mode 100644 index 84742687..00000000 --- a/scripts/test/m2-gap-audit.test.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { existsSync, readFileSync } from 'node:fs'; -import { join } from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { describe, expect, test } from 'bun:test'; - -// Guards the T-203 M2 gap audit (design/m2-gap-audit.md) against citation rot: -// every repo path it cites must resolve, and every symbol it reports as -// "present" must still live in the file it names. Gaps the audit reports as -// missing are deliberately NOT asserted, so landing a fix never breaks this test. - -const repoRoot = fileURLToPath(new URL('../../', import.meta.url)); -const auditPath = join(repoRoot, 'design/m2-gap-audit.md'); -const audit = readFileSync(auditPath, 'utf8'); - -// Paths the audit cites as absent (the gap itself) or as the wrong location. -const CITED_AS_ABSENT = new Set(['scripts/research-copilot-mcp.ts', 'docs/']); - -function expandBraces(path: string): string[] { - const match = /^(.*)\{([^}]+)\}(.*)$/.exec(path); - if (!match) return [path]; - const [, prefix, options, suffix] = match; - return options!.split(',').flatMap((option) => expandBraces(`${prefix}${option}${suffix}`)); -} - -function citedRepoPaths(markdown: string): string[] { - const spans = [...markdown.matchAll(/`([^`\s]+)`/g)].map((m) => m[1]!); - const pathLike = spans.filter( - (span) => - /^(apps|libs|tools|python|scripts|design|test|docs)\//.test(span) || - /^[A-Za-z0-9_.-]+\.(md|json|yml)$/.test(span) - ); - return [...new Set(pathLike.map((span) => span.replace(/:\d+$/, '')).flatMap(expandBraces))].sort(); -} - -describe('design/m2-gap-audit.md citations', () => { - test('cites only repo paths that exist, except those it reports as absent', () => { - const cited = citedRepoPaths(audit); - expect(cited.length).toBeGreaterThan(30); - - const missing = cited.filter((p) => !CITED_AS_ABSENT.has(p) && !existsSync(join(repoRoot, p))); - expect(missing).toEqual([]); - }); - - test('every path listed as absent is actually absent in the audited checkout or is the docs/ relocation note', () => { - // docs/ is cited because milestone docs moved to design/; it must stay absent for that note to hold. - expect(existsSync(join(repoRoot, 'docs'))).toBe(false); - expect(existsSync(join(repoRoot, 'design/MILESTONES.md'))).toBe(true); - }); - - // Symbols the audit reports as PRESENT, keyed by the file it attributes them to. - const presentSymbols: Array<[file: string, symbol: string | RegExp]> = [ - ['libs/research/src/mcp/tools/query-data.ts', 'createQueryDataTool'], - ['libs/research/src/mcp/tools/query-data.ts', 'fenceVaultQueryBounds'], - ['libs/research/src/mcp/tools/query-data.ts', "'vault_fenced'"], - ['libs/research/src/mcp/adapters/postgres-copilot.ts', 'createPostgresResearchCopilotServer'], - ['libs/data/duckdb/src/research-copilot-store.ts', 'openResearchCopilotStore'], - ['libs/data/postgres/src/research-copilot-executor.ts', 'openResearchCopilotExecutor'], - ['libs/research/src/notebook-snapshot.ts', 'exportNotebookSnapshot'], - ['libs/research/src/mcp/host/stdio-host.ts', 'runResearchCopilotStdioHost'], - ['libs/research/src/feature-library.ts', 'registerSignal'], - ['libs/research/src/feature-library.ts', 'runFeatureBatch'], - ['libs/data/questdb/src/schema.ts', 'M2_INTRADAY_SCHEMAS'], - ['libs/data/questdb/src/schema.ts', 'getM2IntradayDDL'], - ['libs/research/src/market-data-store-routed.ts', 'createRoutedMarketDataStore'], - ['libs/research/src/market-data-store-questdb.ts', 'createQuestDbIntradayBarsReader'], - ['tools/curate-etl/src/cli.rs', 'CurateMacro('], - ['tools/curate-etl/src/cli.rs', 'SendIlp('], - ['tools/curate-etl/src/cli.rs', 'CuratePosts('], - ['tools/curate-etl/src/cli.rs', 'CurateFundamentals('], - ['tools/curate-etl/src/cli.rs', 'CurateBars1m('], - ['tools/curate-etl/src/cli.rs', 'CurateFx1m('], - ['tools/curate-etl/src/run_curate_bars_1m_tests.rs', 'fn split_boundary_nvda_and_nexm_match_raw_bars_1d_closes'], - ['tools/curate-etl/src/run_curate_posts.rs', 'EventsDatasetExists'], - ['tools/curate-etl/src/run_curate_qm_bars_1m.rs', /pub fn run_curate_qm_bars_1m\b/], - ['tools/curate-etl/src/fundamentals.rs', 'build_fundamentals_rows'], - ]; - - test.each(presentSymbols)('%s defines %p as the audit reports', (file, symbol) => { - const source = readFileSync(join(repoRoot, file), 'utf8'); - if (typeof symbol === 'string') expect(source).toContain(symbol); - else expect(source).toMatch(symbol); - }); - - test('pins QuestDB 10.2.0 in every compose file the audit cites', () => { - for (const file of ['docker-compose.yml', 'docker-compose.dev.yml', 'docker-compose.prod.yml']) { - expect(readFileSync(join(repoRoot, file), 'utf8')).toContain('questdb/questdb:10.2.0'); - } - }); - - test('lists the three closure-checklist sections the task requires', () => { - expect(audit).toMatch(/^## 2\. Verified on `master`/m); - expect(audit).toMatch(/^## 3\. Remaining M2 Code Gaps/m); - expect(audit).toMatch(/^## 4\. Manual Host-Only Closure Gates/m); - }); - - test('keeps master verification pending rather than claiming unverified passes', () => { - expect(audit).toContain('**OPEN'); - expect(audit).toMatch(/PENDING/); - expect(audit).not.toMatch(/\|\s*\*\*PASS\*\*\s*\|/); - }); -}); diff --git a/scripts/test/m2-master-audit.test.ts b/scripts/test/m2-master-audit.test.ts deleted file mode 100644 index 9b8f6cca..00000000 --- a/scripts/test/m2-master-audit.test.ts +++ /dev/null @@ -1,208 +0,0 @@ -import { existsSync, readFileSync } from 'node:fs'; -import { join } from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { describe, expect, test } from 'bun:test'; - -// Guards the T-208 M2 master audit (design/m2-master-audit.md) against citation rot. -// Every repo path it cites must still resolve, every symbol or test it reports as -// landed must still be in the file it names, and the audited baseline must stay -// pinned. The gaps it reports as missing are deliberately not asserted, so closing -// a gap never breaks this test. - -const repoRoot = fileURLToPath(new URL('../../', import.meta.url)); -const audit = readFileSync(join(repoRoot, 'design/m2-master-audit.md'), 'utf8'); -const designIndex = readFileSync(join(repoRoot, 'design/README.md'), 'utf8'); - -// Cited as gaps or future outputs, so they must not be required to exist. -const CITED_AS_ABSENT = new Set([ - 'scripts/export-notebook-snapshot.ts', - 'design/m2-close-evidence.md', - 'docs/', - 'docs/*.md', - 'design/*.md', -]); - -function expandBraces(path: string): string[] { - const match = /^(.*)\{([^}]+)\}(.*)$/.exec(path); - if (!match) return [path]; - const [, prefix, options, suffix] = match; - return options!.split(',').flatMap((option) => expandBraces(`${prefix}${option}${suffix}`)); -} - -function citedRepoPaths(markdown: string): string[] { - const spans = [...markdown.matchAll(/`([^`\s]+)`/g)].map((m) => m[1]!); - const repoRelative = spans.filter((span) => - /^(apps|libs|tools|python|scripts|design|test|database|docs)\//.test(span) - ); - return [ - ...new Set(repoRelative.map((span) => span.replace(/:[\d,-]+$/, '')).flatMap(expandBraces)), - ] - .filter((p) => !p.includes('*') || CITED_AS_ABSENT.has(p)) - .sort(); -} - -function lineAt(file: string, line: number): string { - return readFileSync(join(repoRoot, file), 'utf8').split('\n')[line - 1] ?? ''; -} - -describe('design/m2-master-audit.md citations', () => { - test('cites only repo paths that exist, except gaps and future evidence files', () => { - const cited = citedRepoPaths(audit); - expect(cited.length).toBeGreaterThan(40); - - const missing = cited.filter((p) => !CITED_AS_ABSENT.has(p) && !existsSync(join(repoRoot, p))); - expect(missing).toEqual([]); - }); - - test('paths cited as gaps are still absent, and specs live under design/', () => { - expect(existsSync(join(repoRoot, 'docs'))).toBe(false); - expect(existsSync(join(repoRoot, 'design/MILESTONES.md'))).toBe(true); - }); - - // [file, 1-based line the audit cites, text that line must contain] - const lineCitations: Array<[file: string, line: number, expected: string]> = [ - ['tools/curate-etl/src/parquet_posts.rs', 22, 'EVENT_KIND_POST'], - ['tools/curate-etl/src/run_curate_posts.rs', 133, 'EventsDatasetExists'], - ['tools/curate-etl/src/mongo_stream.rs', 53, 'pub enum SourceCollection'], - ['tools/curate-etl/src/run_curate_fundamentals.rs', 113, 'pub struct CurateFundamentalsArgs'], - ['tools/curate-etl/src/cli.rs', 98, 'CurateBars1m('], - ['tools/curate-etl/src/cli.rs', 99, 'CurateQmBars1m('], - ['tools/curate-etl/src/cli.rs', 100, 'CurateFx1m('], - ['tools/curate-etl/src/cli.rs', 101, 'CuratePosts('], - ['tools/curate-etl/src/cli.rs', 102, 'CurateFundamentals('], - ['tools/curate-etl/src/cli.rs', 103, 'CurateMacro('], - ['tools/curate-etl/src/cli.rs', 104, 'SendIlp('], - ['tools/curate-etl/src/cli.rs', 1317, 'CliAction::CuratePosts'], - ['tools/curate-etl/src/cli.rs', 1636, 'CliAction::CurateFundamentals'], - ['tools/curate-etl/src/cli.rs', 1689, 'CliAction::CurateMacro'], - ['tools/curate-etl/src/cli.rs', 2110, 'CliAction::CurateBars1m'], - ['tools/curate-etl/src/cli.rs', 2277, 'CliAction::CurateQmBars1m'], - ['tools/curate-etl/src/cli.rs', 2381, 'CliAction::CurateFx1m'], - ['tools/curate-etl/src/cli.rs', 2461, 'CliAction::SendIlp'], - ['tools/curate-etl/src/main.rs', 22, 'run_send_ilp'], - ['tools/curate-etl/src/main.rs', 39, 'run_curate_qm_bars_1m'], - [ - 'tools/curate-etl/src/fundamentals_tests.rs', - 104, - 'fn restatement_of_q1_after_q2_updates_q1_and_ttm_without_overwriting_q2', - ], - [ - 'tools/curate-etl/src/parquet_fundamentals_tests.rs', - 1107, - 'fn restatement_of_q1_after_q2_preserves_q2_on_disk_and_updates_ttm', - ], - [ - 'tools/curate-etl/src/run_curate_bars_1m_tests.rs', - 402, - 'fn split_boundary_nvda_and_nexm_match_raw_bars_1d_closes', - ], - ['tools/curate-etl/tests/cli.rs', 1747, 'fn send_ilp_cli_help_missing_flag_success_and_partial_error_routing'], - ['tools/curate-etl/tests/cli.rs', 1787, 'TcpListener::bind("127.0.0.1:0")'], - [ - 'tools/curate-etl/tests/cli.rs', - 1877, - 'fn send_ilp_cli_shard_gap_exits_without_partial_report_or_connect_and_bad_prefix_prints_usage', - ], - ['tools/curate-etl/tests/cli.rs', 1939, 'fn send_ilp_cli_ignores_questdb_env_vars_and_requires_explicit_addr'], - [ - 'tools/curate-etl/tests/curate_macro.rs', - 178, - 'fn cli_publishes_runner_equivalent_macro_parquet_with_pit_lag_and_no_forecast_leakage', - ], - [ - 'tools/curate-etl/tests/curate_macro.rs', - 471, - 'fn cli_publishes_runner_equivalent_macro_parquet_and_excludes_forecast_sentinel', - ], - ['tools/curate-etl/tests/curate_macro.rs', 709, 'fn cli_rerun_on_same_inputs_is_byte_deterministic'], - [ - 'tools/curate-etl/tests/curate_qm_bars_1m.rs', - 336, - 'fn curate_qm_bars_1m_binary_matches_direct_runner_bytes_report_and_invariants', - ], - [ - 'tools/curate-etl/tests/curate_qm_bars_1m.rs', - 527, - 'fn curate_qm_bars_1m_binary_refuses_overwrite_and_coexists_with_eod_bars_1m_shards', - ], - [ - 'tools/curate-etl/tests/curate_qm_bars_1m.rs', - 622, - 'fn curate_qm_bars_1m_binary_applies_date_effective_mapping_and_reports_dropped_unmapped', - ], - ['tools/curate-etl/src/run_curate_fx_1m.rs', 24, 'bar-start `ts`'], - ['libs/data/questdb/src/schema.ts', 33, 'fx_1m: {'], - ['libs/data/questdb/src/schema.ts', 139, 'export function getM2IntradayDDL'], - ['libs/data/duckdb/src/research-copilot-store.ts', 33, 'export const openResearchCopilotStore'], - ['libs/data/duckdb/src/research-copilot-store.ts', 40, 'vaultOperatorAuthorized: false'], - ['libs/data/duckdb/test/duckdb-market-data-store.test.ts', 251, 'fundamentalsAsOf enforces restatement non-overwrite'], - ['libs/research/src/market-data-store-duckdb.ts', 1448, "'events/year=*/part.parquet'"], - ['libs/research/src/market-data-store-duckdb.ts', 1529, "timeframe === '1m'"], - ['libs/research/src/market-data-store-duckdb.ts', 2283, 'crossSection('], - ['libs/research/src/market-data-store-duckdb.ts', 2287, 'async fundamentalsAsOf('], - ['libs/research/src/market-data-store-duckdb.ts', 2294, 'macroAsOf('], - ['libs/research/src/market-data-store-routed.ts', 185, 'return daily.fx(q)'], - ['libs/research/src/mcp/tools/analyze-signal.ts', 122, 'discriminatedUnion'], - ['libs/research/src/feature-library.ts', 29, 'RET_1D_V1'], - ['libs/research/src/feature-library.ts', 61, 'export const FEATURE_INPUT_DATASETS'], - ['libs/research/src/notebook-snapshot-node.ts', 67, 'export function createNodeNotebookCommandRunner'], - ['scripts/research-copilot-mcp.ts', 77, 'export async function runResearchCopilotMcp'], - ['python/stockbot/data.py', 21, '"ceo_post"'], - ['python/stockbot/data.py', 71, 'events/year=*/part.parquet'], - ['python/stockbot/data.py', 259, 'NotImplementedError'], - ['package.json', 56, '"mcp:research-copilot"'], - ['design/MILESTONES.md', 96, 'eodIntraday1M'], - ['docker-compose.quant.yml', 35, '1048576'], - ]; - - test.each(lineCitations)('%s:%d contains %p as cited', (file, line, expected) => { - expect(audit).toContain(file.split('/').pop()!); - expect(lineAt(file, line)).toContain(expected); - }); - - test('pins the audited master baseline and accepted M1 separately from the review branch', () => { - expect(audit).toContain('d45014a1f6dfc5ba5a73bcc0d6e57e486c2c7c52'); - expect(audit).toContain('d52aa20bff3f5c259fb6e2bcfc2d3a78ad5224b1'); - expect(audit).toContain('git rev-parse master'); - expect(audit).toMatch(/not `git rev-parse HEAD`/); - }); - - test('maps every M2 deliverable and exit criterion to a Done/Partial/Missing status', () => { - for (const row of ['M2.1', 'M2.2', 'M2.3', 'M2.4', 'EC-1', 'EC-2', 'EC-3']) { - const line = audit.split('\n').find((l) => l.startsWith(`| **${row}`)); - expect(line, row).toBeDefined(); - expect(line!).toMatch(/\|\s*\*\*(Done|Partial|Missing)\b/); - } - }); - - test('keeps host and quant checks pending rather than claiming them passed', () => { - expect(audit).toMatch(/\*\*PENDING \(host closure\)\*\*/); - expect(audit).toMatch(/\*\*PENDING \(host\/`quant`\)\*\*/); - expect(audit).toMatch(/\*\*Partial \(Synthetic Done; Live `quant` Missing\)\*\*/); - }); - - test('lists the seven approved backlog keys in dependency order', () => { - const keys = [ - 'm2-ceo-posts-events-compat', - 'm2-store-macro-cross-section-fx1m', - 'm2-data-pipeline-m2-inputs-and-probes', - 'm2-curate-etl-mongo-and-financials-old', - 'm2-python-sdk-m2-parity', - 'm2-ec1-snapshot-cli-and-doc-paths', - 'm2-host-quant-verification-and-closure', - ]; - const section = audit.slice(audit.indexOf('## 5. Ordered M2 Closure Backlog')); - const rows = section.split('\n').filter((l) => /^\| \*\*\d\*\* \|/.test(l)); - expect(rows.map((r) => /`(m2-[a-z0-9-]+)`/.exec(r)?.[1])).toEqual(keys); - rows.forEach((row, i) => { - for (const dep of [...row.split('|')[4]!.matchAll(/`(m2-[a-z0-9-]+)`/g)].map((m) => m[1]!)) { - expect(keys.indexOf(dep), `${keys[i]} depends on ${dep}`).toBeLessThan(i); - } - }); - }); - - test('proposes no CI workflow and is indexed in design/README.md', () => { - expect(audit).not.toMatch(/\.github\/workflows/); - expect(designIndex).toContain('[m2-master-audit.md](m2-master-audit.md)'); - }); -}); diff --git a/scripts/test/research-copilot-mcp-defaults.test.ts b/scripts/test/research-copilot-mcp-defaults.test.ts deleted file mode 100644 index 429f5672..00000000 --- a/scripts/test/research-copilot-mcp-defaults.test.ts +++ /dev/null @@ -1,332 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import type { BarBatch, BarQuery, MarketDataStore } from '@stock-bot/research/market-data-store'; -import { MarketDataStoreNotImplementedError } from '@stock-bot/research/market-data-store-duckdb'; -import { - type LibraryCardReaderHandle, - MCP_PROTOCOL_VERSION, - type PostgresResearchCopilotExecutor, - type ReadKnowledgeResultPayload, - RESEARCH_COPILOT_TOOL_NAMES, - type StdioInput, - type StdioOutput, -} from '@stock-bot/research/mcp'; -import { - RESEARCH_COPILOT_HOST_ERROR_LINE, - runResearchCopilotMcp, -} from '../research-copilot-mcp'; - -const FAKE_PASSWORD = 's3cr@t-default-pw#42'; -const FAKE_ENCODED_PASSWORD = encodeURIComponent(FAKE_PASSWORD); -const VALID_AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555'; -const VALID_CUTOFF_ISO = '2025-06-01T00:00:00Z'; -const FIXED_NOW_MS = Date.UTC(2025, 4, 15, 12, 0, 0, 0); - -function createMemoryWriter(): { - readonly stream: StdioOutput; - text(): string; -} { - const chunks: string[] = []; - return { - stream: { - write(chunk: string): boolean { - chunks.push(chunk); - return true; - }, - }, - text: () => chunks.join(''), - }; -} - -function createMemoryInput(lines: readonly string[]): StdioInput { - return { - async *[Symbol.asyncIterator](): AsyncIterator { - for (const line of lines) { - yield `${line}\n`; - } - }, - }; -} - -function createFakeExecutor(): PostgresResearchCopilotExecutor { - return { - async query>(): Promise<{ readonly rows: readonly Row[] }> { - return { rows: [] }; - }, - }; -} - -function createFakeStore(): MarketDataStore { - return { - async *bars(q: BarQuery): AsyncIterable { - yield { - listingId: q.listingIds[0] ?? 0, - timeframe: q.timeframe, - rows: [], - }; - }, - async crossSection() { - throw new MarketDataStoreNotImplementedError('crossSection'); - }, - async fundamentalsAsOf() { - throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); - }, - async events() { - throw new MarketDataStoreNotImplementedError('events'); - }, - async shortsAsOf() { - throw new MarketDataStoreNotImplementedError('shortsAsOf'); - }, - async macroAsOf() { - throw new MarketDataStoreNotImplementedError('macroAsOf'); - }, - async fx() { - throw new MarketDataStoreNotImplementedError('fx'); - }, - async universe() { - return []; - }, - }; -} - -function createFakeLibraryReader(): LibraryCardReaderHandle { - return { - async listLibraryCards() { - return []; - }, - }; -} - -describe('scripts/research-copilot-mcp.ts default factory wiring', () => { - test('default createLibraryCardReader resolves master createLibraryCardReader + createNodeLibraryCardFs over a temp dir', async () => { - const tempDir = await mkdtemp(join(tmpdir(), 'stockbot-mcp-lib-')); - try { - await mkdir(join(tempDir, 'cards', 'quant'), { recursive: true }); - await writeFile( - join(tempDir, 'library.yml'), - 'id: research-lib\nsections:\n quant: Quantitative Methods\n', - 'utf8' - ); - await writeFile( - join(tempDir, 'cards', 'quant', 'dsr-basics.md'), - [ - '---', - 'title: "Deflated Sharpe Ratio"', - 'summary: "Adjusts Sharpe for multiple testing."', - 'matches: ["dsr", "sharpe"]', - '---', - '', - 'Use DSR to account for trial count.', - ].join('\n'), - 'utf8' - ); - - const stdout = createMemoryWriter(); - const stderr = createMemoryWriter(); - const closed: string[] = []; - - const input = createMemoryInput([ - JSON.stringify({ - jsonrpc: '2.0', - id: 1, - method: 'initialize', - params: { - protocolVersion: MCP_PROTOCOL_VERSION, - capabilities: {}, - clientInfo: { name: 'defaults-test', version: '1.0.0' }, - }, - }), - JSON.stringify({ - jsonrpc: '2.0', - method: 'notifications/initialized', - }), - JSON.stringify({ - jsonrpc: '2.0', - id: 2, - method: 'tools/call', - params: { - name: 'read_knowledge', - arguments: { - source: 'library', - id: 'research-lib:quant/dsr-basics', - }, - }, - }), - ]); - - const exitCode = await runResearchCopilotMcp({ - env: { - RESEARCH_MCP_POSTGRES_URL: `postgresql://research_ro:${FAKE_ENCODED_PASSWORD}@127.0.0.1:5433/trading_bot_dev`, - RESEARCH_MCP_CURATED_ROOT: '/tmp/unused-curated-root', - RESEARCH_MCP_VAULT_CUTOFF_TS: VALID_CUTOFF_ISO, - RESEARCH_MCP_PRINCIPAL_ID: VALID_AGENT_PRINCIPAL, - RESEARCH_MCP_LIBRARY_ROOT: tempDir, - RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: JSON.stringify({ XNYS: [101] }), - }, - input, - output: stdout.stream, - stderr: stderr.stream, - openExecutor: () => ({ - executor: createFakeExecutor(), - close: () => { - closed.push('executor'); - }, - }), - openStore: () => ({ - store: createFakeStore(), - close: () => { - closed.push('store'); - }, - }), - // Intentionally omit createLibraryCardReader to exercise the default factory. - newId: () => '00000000-0000-4000-8000-000000000002', - now: () => FIXED_NOW_MS, - }); - - expect(exitCode).toBe(0); - expect(stderr.text()).toBe(''); - expect(closed).toEqual(['store', 'executor']); - - const responses = stdout - .text() - .trim() - .split('\n') - .map(line => JSON.parse(line) as Record); - expect(responses).toHaveLength(2); - - const callResp = responses[1] as { - id: number; - result: { - isError?: boolean; - content: Array<{ type: string; text: string }>; - }; - }; - expect(callResp.id).toBe(2); - expect(callResp.result.isError).not.toBe(true); - const payload = JSON.parse(callResp.result.content[0]!.text) as ReadKnowledgeResultPayload; - expect(payload.rowCount).toBe(1); - expect(payload.rows).toHaveLength(1); - const firstRow = payload.rows[0]; - expect(firstRow?.source).toBe('library'); - if (firstRow?.source === 'library') { - expect(firstRow.id).toBe('research-lib:quant/dsr-basics'); - expect(firstRow.title).toBe('Deflated Sharpe Ratio'); - } - } finally { - await rm(tempDir, { recursive: true, force: true }); - } - }); - - test('default openExecutor resolves master openResearchCopilotExecutor and fails closed without opening a DB socket', async () => { - // Passes parseResearchCopilotHostConfig (valid scheme + host), but fails - // openResearchCopilotExecutor synchronously (missing database path) before creating pg.Pool. - const urlWithoutDatabase = `postgresql://research_ro:${FAKE_ENCODED_PASSWORD}@127.0.0.1:5433`; - const stdout = createMemoryWriter(); - const stderr = createMemoryWriter(); - let openStoreCalled = false; - - const exitCode = await runResearchCopilotMcp({ - env: { - RESEARCH_MCP_POSTGRES_URL: urlWithoutDatabase, - RESEARCH_MCP_CURATED_ROOT: '/tmp/unused-curated-root', - RESEARCH_MCP_VAULT_CUTOFF_TS: VALID_CUTOFF_ISO, - RESEARCH_MCP_PRINCIPAL_ID: VALID_AGENT_PRINCIPAL, - RESEARCH_MCP_LIBRARY_ROOT: '/tmp/unused-library-root', - RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: JSON.stringify({ XNYS: [101] }), - }, - input: createMemoryInput([]), - output: stdout.stream, - stderr: stderr.stream, - // Intentionally omit openExecutor to exercise lazy import of openResearchCopilotExecutor. - openStore: () => { - openStoreCalled = true; - return { store: createFakeStore(), close: () => undefined }; - }, - createLibraryCardReader: () => createFakeLibraryReader(), - }); - - expect(exitCode).toBe(1); - expect(stdout.text()).toBe(''); - expect(stderr.text()).toBe(RESEARCH_COPILOT_HOST_ERROR_LINE); - expect(stderr.text()).not.toContain(FAKE_PASSWORD); - expect(stderr.text()).not.toContain(FAKE_ENCODED_PASSWORD); - expect(stderr.text()).not.toContain(urlWithoutDatabase); - expect(openStoreCalled).toBe(false); - }); - - test('default openStore resolves master openResearchCopilotStore (in-memory DuckDB) and closes cleanly', async () => { - const tempCuratedRoot = await mkdtemp(join(tmpdir(), 'stockbot-mcp-curated-')); - try { - const stdout = createMemoryWriter(); - const stderr = createMemoryWriter(); - const closed: string[] = []; - - const input = createMemoryInput([ - JSON.stringify({ - jsonrpc: '2.0', - id: 1, - method: 'initialize', - params: { - protocolVersion: MCP_PROTOCOL_VERSION, - capabilities: {}, - clientInfo: { name: 'defaults-store-test', version: '1.0.0' }, - }, - }), - JSON.stringify({ - jsonrpc: '2.0', - method: 'notifications/initialized', - }), - JSON.stringify({ - jsonrpc: '2.0', - id: 2, - method: 'tools/list', - params: {}, - }), - ]); - - const exitCode = await runResearchCopilotMcp({ - env: { - RESEARCH_MCP_POSTGRES_URL: `postgresql://research_ro:${FAKE_ENCODED_PASSWORD}@127.0.0.1:5433/trading_bot_dev`, - RESEARCH_MCP_CURATED_ROOT: tempCuratedRoot, - RESEARCH_MCP_VAULT_CUTOFF_TS: VALID_CUTOFF_ISO, - RESEARCH_MCP_PRINCIPAL_ID: VALID_AGENT_PRINCIPAL, - RESEARCH_MCP_LIBRARY_ROOT: '/tmp/unused-library-root', - RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: JSON.stringify({ XNYS: [101] }), - }, - input, - output: stdout.stream, - stderr: stderr.stream, - openExecutor: () => ({ - executor: createFakeExecutor(), - close: () => { - closed.push('executor'); - }, - }), - // Intentionally omit openStore to exercise lazy import of openResearchCopilotStore. - createLibraryCardReader: () => createFakeLibraryReader(), - newId: () => '00000000-0000-4000-8000-000000000003', - now: () => FIXED_NOW_MS, - }); - - expect(exitCode).toBe(0); - expect(stderr.text()).toBe(''); - expect(closed).toEqual(['executor']); - - const responses = stdout - .text() - .trim() - .split('\n') - .map(line => JSON.parse(line) as Record); - expect(responses).toHaveLength(2); - const listResp = responses[1] as { - id: number; - result: { tools: Array<{ name: string }> }; - }; - expect(listResp.result.tools.map(t => t.name)).toEqual([...RESEARCH_COPILOT_TOOL_NAMES]); - } finally { - await rm(tempCuratedRoot, { recursive: true, force: true }); - } - }); -}); diff --git a/scripts/test/research-copilot-mcp.test.ts b/scripts/test/research-copilot-mcp.test.ts deleted file mode 100644 index a92f6f8d..00000000 --- a/scripts/test/research-copilot-mcp.test.ts +++ /dev/null @@ -1,391 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { readFileSync } from 'node:fs'; -import { join } from 'node:path'; -import { fileURLToPath } from 'node:url'; -import type { BarBatch, BarQuery, MarketDataStore } from '@stock-bot/research/market-data-store'; -import { MarketDataStoreNotImplementedError } from '@stock-bot/research/market-data-store-duckdb'; -import { - type LibraryCardReaderHandle, - MCP_PROTOCOL_VERSION, - type PostgresResearchCopilotExecutor, - RESEARCH_COPILOT_HOST_NAME, - RESEARCH_COPILOT_HOST_VERSION, - RESEARCH_COPILOT_TOOL_NAMES, - type StdioInput, - type StdioOutput, -} from '@stock-bot/research/mcp'; -import { - RESEARCH_COPILOT_CONFIG_ERROR_LINE, - RESEARCH_COPILOT_HOST_ERROR_LINE, - runResearchCopilotMcp, -} from '../research-copilot-mcp'; - -const FAKE_DECODED_PASSWORD = 's3cr@t pass#99!'; -const FAKE_ENCODED_PASSWORD = encodeURIComponent(FAKE_DECODED_PASSWORD); -const FAKE_POSTGRES_URL = `postgresql://research_ro:${FAKE_ENCODED_PASSWORD}@127.0.0.1:5433/trading_bot_dev?sslmode=disable`; -const VALID_AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555'; -const VALID_CUTOFF_ISO = '2025-06-01T00:00:00Z'; -const FIXED_NOW_MS = Date.UTC(2025, 4, 15, 12, 0, 0, 0); - -function buildValidEnv( - overrides: Readonly> = {} -): Record { - return { - PATH: '/usr/local/bin:/usr/bin', - NODE_ENV: 'test', - RESEARCH_MCP_POSTGRES_URL: FAKE_POSTGRES_URL, - RESEARCH_MCP_POSTGRES_SCHEMA: 'research_ro', - RESEARCH_MCP_CURATED_ROOT: '/tmp/fake-curated-root-secret-path', - RESEARCH_MCP_VAULT_CUTOFF_TS: VALID_CUTOFF_ISO, - RESEARCH_MCP_PRINCIPAL_ID: VALID_AGENT_PRINCIPAL, - RESEARCH_MCP_LIBRARY_ROOT: '/tmp/fake-library-root-secret-path', - RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: JSON.stringify({ - XNYS: [101], - }), - ...overrides, - }; -} - -function createMemoryWriter(): { - readonly stream: StdioOutput; - readonly chunks: string[]; - text(): string; -} { - const chunks: string[] = []; - return { - stream: { - write(chunk: string): boolean { - chunks.push(chunk); - return true; - }, - }, - chunks, - text: () => chunks.join(''), - }; -} - -function createMemoryInput(lines: readonly string[]): StdioInput { - return { - async *[Symbol.asyncIterator](): AsyncIterator { - for (const line of lines) { - yield `${line}\n`; - } - }, - }; -} - -function createFakeExecutor(): PostgresResearchCopilotExecutor { - return { - async query>(): Promise<{ readonly rows: readonly Row[] }> { - return { rows: [] }; - }, - }; -} - -function createFakeStore(): MarketDataStore { - return { - async *bars(q: BarQuery): AsyncIterable { - yield { - listingId: q.listingIds[0] ?? 0, - timeframe: q.timeframe, - rows: [], - }; - }, - async crossSection() { - throw new MarketDataStoreNotImplementedError('crossSection'); - }, - async fundamentalsAsOf() { - throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); - }, - async events() { - throw new MarketDataStoreNotImplementedError('events'); - }, - async shortsAsOf() { - throw new MarketDataStoreNotImplementedError('shortsAsOf'); - }, - async macroAsOf() { - throw new MarketDataStoreNotImplementedError('macroAsOf'); - }, - async fx() { - throw new MarketDataStoreNotImplementedError('fx'); - }, - async universe() { - return []; - }, - }; -} - -function createFakeLibraryReader(): LibraryCardReaderHandle { - return { - async listLibraryCards() { - return []; - }, - }; -} - -function assertSingleFixedLineNoSecrets( - stderrText: string, - expectedLine: string, - env: Readonly> -): void { - expect(stderrText).toBe(expectedLine); - expect(stderrText.endsWith('\n')).toBe(true); - expect(stderrText.slice(0, -1)).not.toContain('\n'); - - const forbidden = [ - FAKE_POSTGRES_URL, - FAKE_ENCODED_PASSWORD, - FAKE_DECODED_PASSWORD, - env.RESEARCH_MCP_POSTGRES_URL, - env.RESEARCH_MCP_CURATED_ROOT, - env.RESEARCH_MCP_LIBRARY_ROOT, - env.RESEARCH_MCP_PRINCIPAL_ID, - ].filter((value): value is string => typeof value === 'string' && value.length > 0); - - for (const secret of forbidden) { - expect(stderrText).not.toContain(secret); - } -} - -describe('scripts/research-copilot-mcp.ts', () => { - test('package.json defines mcp:research-copilot pointing to scripts/research-copilot-mcp.ts', () => { - const repoRoot = fileURLToPath(new URL('../../', import.meta.url)); - const pkg = JSON.parse(readFileSync(join(repoRoot, 'package.json'), 'utf8')) as { - scripts?: Record; - }; - expect(pkg.scripts?.['mcp:research-copilot']).toBe('bun run scripts/research-copilot-mcp.ts'); - }); - - test('missing required RESEARCH_MCP_* env returns exit code 1, one fixed stderr line, and zero stdout bytes', async () => { - const env = buildValidEnv({ RESEARCH_MCP_POSTGRES_URL: undefined }); - const stdout = createMemoryWriter(); - const stderr = createMemoryWriter(); - let openExecutorCalled = false; - let openStoreCalled = false; - - const exitCode = await runResearchCopilotMcp({ - env, - input: createMemoryInput([]), - output: stdout.stream, - stderr: stderr.stream, - openExecutor: () => { - openExecutorCalled = true; - return { executor: createFakeExecutor(), close: () => undefined }; - }, - openStore: () => { - openStoreCalled = true; - return { store: createFakeStore(), close: () => undefined }; - }, - createLibraryCardReader: () => createFakeLibraryReader(), - }); - - expect(exitCode).toBe(1); - expect(stdout.text()).toBe(''); - assertSingleFixedLineNoSecrets(stderr.text(), RESEARCH_COPILOT_CONFIG_ERROR_LINE, env); - expect(openExecutorCalled).toBe(false); - expect(openStoreCalled).toBe(false); - }); - - test('invalid RESEARCH_MCP_* env fails closed with one fixed stderr line and zero stdout bytes', async () => { - const env = buildValidEnv({ - RESEARCH_MCP_POSTGRES_URL: `http://research_ro:${FAKE_ENCODED_PASSWORD}@127.0.0.1:5433/trading_bot_dev`, - }); - const stdout = createMemoryWriter(); - const stderr = createMemoryWriter(); - - const exitCode = await runResearchCopilotMcp({ - env, - input: createMemoryInput([]), - output: stdout.stream, - stderr: stderr.stream, - openExecutor: () => ({ executor: createFakeExecutor(), close: () => undefined }), - openStore: () => ({ store: createFakeStore(), close: () => undefined }), - createLibraryCardReader: () => createFakeLibraryReader(), - }); - - expect(exitCode).toBe(1); - expect(stdout.text()).toBe(''); - assertSingleFixedLineNoSecrets(stderr.text(), RESEARCH_COPILOT_CONFIG_ERROR_LINE, env); - }); - - test('openExecutor failure returns 1 with fixed stderr line leaking no DSN, password, or env values', async () => { - const env = buildValidEnv(); - const stdout = createMemoryWriter(); - const stderr = createMemoryWriter(); - let openStoreCalled = false; - - const exitCode = await runResearchCopilotMcp({ - env, - input: createMemoryInput([]), - output: stdout.stream, - stderr: stderr.stream, - openExecutor: () => { - throw new Error( - `connect failed for ${FAKE_POSTGRES_URL} (pw=${FAKE_DECODED_PASSWORD}) root=${env.RESEARCH_MCP_CURATED_ROOT}` - ); - }, - openStore: () => { - openStoreCalled = true; - return { store: createFakeStore(), close: () => undefined }; - }, - createLibraryCardReader: () => createFakeLibraryReader(), - }); - - expect(exitCode).toBe(1); - expect(stdout.text()).toBe(''); - assertSingleFixedLineNoSecrets(stderr.text(), RESEARCH_COPILOT_HOST_ERROR_LINE, env); - expect(openStoreCalled).toBe(false); - }); - - test('openStore failure closes already-opened executor and returns 1 with fixed stderr line', async () => { - const env = buildValidEnv(); - const stdout = createMemoryWriter(); - const stderr = createMemoryWriter(); - const closed: string[] = []; - - const exitCode = await runResearchCopilotMcp({ - env, - input: createMemoryInput([]), - output: stdout.stream, - stderr: stderr.stream, - openExecutor: () => ({ - executor: createFakeExecutor(), - close: () => { - closed.push('executor'); - }, - }), - openStore: () => { - throw new Error(`DuckDB failed for ${env.RESEARCH_MCP_CURATED_ROOT} ${FAKE_POSTGRES_URL}`); - }, - createLibraryCardReader: () => createFakeLibraryReader(), - }); - - expect(exitCode).toBe(1); - expect(stdout.text()).toBe(''); - assertSingleFixedLineNoSecrets(stderr.text(), RESEARCH_COPILOT_HOST_ERROR_LINE, env); - expect(closed).toEqual(['executor']); - }); - - test('stdio host failure closes store and executor in reverse order and leaks no secrets', async () => { - const env = buildValidEnv(); - const stdout = createMemoryWriter(); - const stderr = createMemoryWriter(); - const closed: string[] = []; - - const failingInput: StdioInput = { - async *[Symbol.asyncIterator](): AsyncIterator { - throw new Error(`stdin boom ${FAKE_POSTGRES_URL} ${FAKE_DECODED_PASSWORD}`); - }, - }; - - const exitCode = await runResearchCopilotMcp({ - env, - input: failingInput, - output: stdout.stream, - stderr: stderr.stream, - openExecutor: () => ({ - executor: createFakeExecutor(), - close: () => { - closed.push('executor'); - }, - }), - openStore: () => ({ - store: createFakeStore(), - close: () => { - closed.push('store'); - }, - }), - createLibraryCardReader: () => createFakeLibraryReader(), - }); - - expect(exitCode).toBe(1); - expect(stdout.text()).toBe(''); - assertSingleFixedLineNoSecrets(stderr.text(), RESEARCH_COPILOT_HOST_ERROR_LINE, env); - expect(closed).toEqual(['store', 'executor']); - }); - - test('MCP initialize + tools/list round trip returns all 6 copilot tools on stdout, exit 0, and closes resources', async () => { - const env = buildValidEnv(); - const stdout = createMemoryWriter(); - const stderr = createMemoryWriter(); - const closed: string[] = []; - - const input = createMemoryInput([ - JSON.stringify({ - jsonrpc: '2.0', - id: 1, - method: 'initialize', - params: { - protocolVersion: MCP_PROTOCOL_VERSION, - capabilities: {}, - clientInfo: { name: 'test-client', version: '1.0.0' }, - }, - }), - JSON.stringify({ - jsonrpc: '2.0', - method: 'notifications/initialized', - }), - JSON.stringify({ - jsonrpc: '2.0', - id: 2, - method: 'tools/list', - params: {}, - }), - ]); - - const exitCode = await runResearchCopilotMcp({ - env, - input, - output: stdout.stream, - stderr: stderr.stream, - openExecutor: () => ({ - executor: createFakeExecutor(), - close: () => { - closed.push('executor'); - }, - }), - openStore: () => ({ - store: createFakeStore(), - close: () => { - closed.push('store'); - }, - }), - createLibraryCardReader: () => createFakeLibraryReader(), - newId: () => '00000000-0000-4000-8000-000000000001', - now: () => FIXED_NOW_MS, - }); - - expect(exitCode).toBe(0); - expect(stderr.text()).toBe(''); - expect(closed).toEqual(['store', 'executor']); - - const lines = stdout - .text() - .trim() - .split('\n') - .map(line => JSON.parse(line) as Record); - expect(lines).toHaveLength(2); - - const initResp = lines[0] as { - id: number; - result: { - protocolVersion: string; - serverInfo: { name: string; version: string }; - }; - }; - expect(initResp.id).toBe(1); - expect(initResp.result.protocolVersion).toBe(MCP_PROTOCOL_VERSION); - expect(initResp.result.serverInfo).toEqual({ - name: RESEARCH_COPILOT_HOST_NAME, - version: RESEARCH_COPILOT_HOST_VERSION, - }); - - const listResp = lines[1] as { - id: number; - result: { tools: Array<{ name: string }> }; - }; - expect(listResp.id).toBe(2); - expect(listResp.result.tools.map(t => t.name)).toEqual([...RESEARCH_COPILOT_TOOL_NAMES]); - expect(listResp.result.tools).toHaveLength(6); - }); -}); diff --git a/test/postgres/fresh-database-schema.test.ts b/test/postgres/fresh-database-schema.test.ts index 8bfb3325..df95c7b7 100644 --- a/test/postgres/fresh-database-schema.test.ts +++ b/test/postgres/fresh-database-schema.test.ts @@ -78,7 +78,6 @@ const RESEARCH_FILES = [ '32-candidate-parameter-defaults.sql', '33-candidate-decimal-normalization.sql', '36-trial-ledger.sql', - '37-research-findings.sql', ]; const cleanup: (() => Promise | void)[] = []; @@ -139,13 +138,13 @@ async function createIsolatedFixture() { } describe.skipIf(!url)('fresh PostgreSQL database schema', () => { - test('Case A: init SQL 01-37 contain no CREATE DATABASE/\\c and create all master and research tables', async () => { + test('Case A: init SQL 01-36 contain no CREATE DATABASE/\\c and create all master and research tables', async () => { const f = await createIsolatedFixture(); const sqlFiles = readdirSync(initDir) .filter(file => file.endsWith('.sql')) .sort(); - expect(sqlFiles.length).toBeGreaterThanOrEqual(37); + expect(sqlFiles.length).toBeGreaterThanOrEqual(36); for (const file of sqlFiles) { const sql = readFileSync(join(initDir, file), 'utf8'); @@ -160,7 +159,7 @@ describe.skipIf(!url)('fresh PostgreSQL database schema', () => { ...LEGACY_MASTER_TABLES, // Security master tables (34) ...SECURITY_MASTER_TABLES, - // Research tables (06-33, 36-37, including representatives from 12, 16, 20, 22, 28, 30, 36, 37) + // Research tables (06-33, 36, including representatives from 12, 16, 20, 22, 28, 30, 36) 'backtests', 'backtest_results', 'runs', @@ -172,8 +171,6 @@ describe.skipIf(!url)('fresh PostgreSQL database schema', () => { 'paper_deployments', 'trial_ledger', 'vault_evaluations', - 'findings', - 'provider_caveats', ]) { expect(createdTables.has(expectedTable)).toBe(true); } @@ -196,8 +193,6 @@ describe.skipIf(!url)('fresh PostgreSQL database schema', () => { } expect(createdTables.has('trial_ledger')).toBe(false); expect(createdTables.has('vault_evaluations')).toBe(false); - expect(createdTables.has('findings')).toBe(false); - expect(createdTables.has('provider_caveats')).toBe(false); expect(await f.hasColumn('exchanges', 'visible')).toBe(true); const second = await runPostgresMigrations(f.postgres, { track: 'master' }); @@ -205,7 +200,7 @@ describe.skipIf(!url)('fresh PostgreSQL database schema', () => { expect(await f.recorded()).toEqual(MASTER_FILES); }); - test('Case C: all track with 06-08 pre-applied records master + research (including 36-37) and never records 06-08', async () => { + test('Case C: all track with 06-08 pre-applied records master + research (including 36) and never records 06-08', async () => { const f = await createIsolatedFixture(); for (const file of BOOTSTRAP_FILES) { @@ -228,8 +223,6 @@ describe.skipIf(!url)('fresh PostgreSQL database schema', () => { } expect(createdTables.has('trial_ledger')).toBe(true); expect(createdTables.has('vault_evaluations')).toBe(true); - expect(createdTables.has('findings')).toBe(true); - expect(createdTables.has('provider_caveats')).toBe(true); const second = await runPostgresMigrations(f.postgres, { track: 'all' }); expect(second).toEqual([]); diff --git a/test/postgres/mcp-copilot-executor.test.ts b/test/postgres/mcp-copilot-executor.test.ts deleted file mode 100644 index 526f9d78..00000000 --- a/test/postgres/mcp-copilot-executor.test.ts +++ /dev/null @@ -1,404 +0,0 @@ -import { randomUUID } from 'node:crypto'; -import { readFileSync } from 'node:fs'; -import { fileURLToPath } from 'node:url'; -import { afterEach, describe, expect, test } from 'bun:test'; -import { Client, Pool, type PoolConfig } from 'pg'; -import { getLogger, setLoggerConfig } from '@stock-bot/logger'; -import { - PostgreSQLClient, - RESEARCH_COPILOT_PG_POOL_MAX, - ResearchCopilotExecutorError, - openResearchCopilotExecutor, - runPostgresMigrations, -} from '@stock-bot/postgres'; -import { - createPostgresFindingWritePort, - createPostgresKnowledgeReaders, - createPostgresTrialRefLookupPort, -} from '../../libs/research/src/mcp/index'; - -setLoggerConfig({ logLevel: 'fatal', logConsole: false }); -const logger = getLogger('mcp-copilot-executor-pg-test'); -const url = process.env.PIPELINE_TEST_DATABASE_URL; -const initDir = fileURLToPath(new URL('../../database/postgres/init/', import.meta.url)); - -const VAULT_CUTOFF_TS = Date.UTC(2025, 5, 30, 0, 0, 0, 0); -const FIXED_TS = '2026-01-15T12:34:56.789Z'; - -const cleanup: Array<() => Promise | void> = []; -afterEach(async () => { - let firstError: unknown; - for (const close of cleanup.splice(0).reverse()) { - try { - await close(); - } catch (err) { - firstError ??= err; - } - } - if (firstError !== undefined) { - throw firstError; - } -}); - -function assertSafetyDatabaseUrl(connectionString: string | undefined): string { - if (!connectionString) { - throw new Error('Dedicated stock_bot_safety database required'); - } - let parsed: URL; - try { - parsed = new URL(connectionString); - } catch { - throw new Error('Dedicated stock_bot_safety database required'); - } - if (parsed.protocol !== 'postgres:' && parsed.protocol !== 'postgresql:') { - throw new Error('Dedicated stock_bot_safety database required'); - } - const client = new Client({ connectionString }); - const effectiveDb = ( - client as unknown as { connectionParameters?: { database?: unknown } } - ).connectionParameters?.database; - if ( - typeof effectiveDb !== 'string' || - !effectiveDb.startsWith('stock_bot_safety') || - !parsed.pathname.startsWith('/stock_bot_safety') - ) { - throw new Error('Dedicated stock_bot_safety database required'); - } - return connectionString; -} - -function buildIsolatedPoolConfig(connectionString: string, schema: string): PoolConfig { - const safeUrl = assertSafetyDatabaseUrl(connectionString); - const parsed = new URL(safeUrl); - const existingOptions = parsed.searchParams - .getAll('options') - .map(value => value.trim()) - .filter(value => value.length > 0); - parsed.searchParams.delete('options'); - - const options = [ - ...existingOptions, - `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`, - ].join(' '); - - return { - connectionString: parsed.toString(), - options, - }; -} - -function buildExecutorUrl( - connectionString: string, - schema: string, - applicationName: string, - extraParams?: Readonly> -): string { - const safeUrl = assertSafetyDatabaseUrl(connectionString); - const parsed = new URL(safeUrl); - const existingOptions = parsed.searchParams - .getAll('options') - .map(value => value.trim()) - .filter(value => value.length > 0); - parsed.searchParams.delete('options'); - const combinedOptions = [...existingOptions, `-c search_path=${schema}`].join(' '); - parsed.searchParams.set('options', combinedOptions); - parsed.searchParams.set('application_name', applicationName); - if (extraParams) { - for (const [k, v] of Object.entries(extraParams)) { - parsed.searchParams.set(k, v); - } - } - return parsed.toString(); -} - -async function createIsolatedFixture(connectionString: string | undefined = url) { - const safeUrl = assertSafetyDatabaseUrl(connectionString); - const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`; - const admin = new Pool({ connectionString: safeUrl }); - cleanup.push(() => admin.end()); - await admin.query(`CREATE SCHEMA ${schema}`); - cleanup.push(() => admin.query(`DROP SCHEMA ${schema} CASCADE`).then(() => undefined)); - - const setupPool = new Pool(buildIsolatedPoolConfig(safeUrl, schema)); - cleanup.push(() => setupPool.end()); - - const { rows: schemaRows } = await setupPool.query<{ current_schema: string | null }>( - 'SELECT current_schema() AS current_schema' - ); - if (schemaRows[0]?.current_schema !== schema) { - throw new Error( - `Isolated fixture pool expected current_schema()=${schema}, got ${String(schemaRows[0]?.current_schema)}` - ); - } - - for (const filename of [ - '06-create-backtest-tables.sql', - '07-fix-execution-time-type.sql', - '08-create-runs-table.sql', - ]) { - await setupPool.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: () => setupPool.connect(), - }), - }); - - await runPostgresMigrations(postgres, { track: 'research' }); - - return { admin, setupPool, schema, safeUrl }; -} - -async function waitForZeroBackends(admin: Pool, applicationName: string): Promise { - const deadline = Date.now() + 2_000; - let count = -1; - while (Date.now() < deadline) { - const { rows } = await admin.query<{ c: number }>( - 'SELECT count(*)::int AS c FROM pg_stat_activity WHERE application_name = $1', - [applicationName] - ); - count = rows[0]?.c ?? -1; - if (count === 0) { - return 0; - } - await new Promise(resolve => setTimeout(resolve, 25)); - } - return count; -} - -describe('PostgreSQL MCP copilot executor safety guard', () => { - test('rejects missing or non-safety database URLs', () => { - expect(() => assertSafetyDatabaseUrl(undefined)).toThrow( - 'Dedicated stock_bot_safety database required' - ); - expect(() => - assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/trading_bot') - ).toThrow('Dedicated stock_bot_safety database required'); - expect(() => - assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5433/trading_bot_dev') - ).toThrow('Dedicated stock_bot_safety database required'); - expect( - assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test') - ).toBe('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test'); - }); -}); - -describe.skipIf(!url)('PostgreSQL MCP copilot executor (real PostgreSQL)', () => { - test('enforces effective 10s statement_timeout and 2s lock_timeout even when URL specifies overrides', async () => { - const f = await createIsolatedFixture(); - const appName = `copilot_timeouts_${randomUUID().slice(0, 8)}`; - const executorUrl = buildExecutorUrl(f.safeUrl, f.schema, appName, { - statement_timeout: '99999', - lock_timeout: '99999', - query_timeout: '99999', - }); - - const handle = await openResearchCopilotExecutor({ postgresUrl: executorUrl }); - cleanup.push(() => handle.close()); - - const { rows: stmtRows } = await handle.executor.query<{ statement_timeout: string }>( - 'SHOW statement_timeout' - ); - const { rows: lockRows } = await handle.executor.query<{ lock_timeout: string }>( - 'SHOW lock_timeout' - ); - - expect(stmtRows[0]?.statement_timeout).toBe('10s'); - expect(lockRows[0]?.lock_timeout).toBe('2s'); - }); - - test('preserves PGOPTIONS search_path when URL omits options while enforcing 10s/2s timeouts', async () => { - const f = await createIsolatedFixture(); - const appName = `copilot_pgoptions_${randomUUID().slice(0, 8)}`; - - // Build a URL with NO options query parameter so pg must honor PGOPTIONS. - const parsed = new URL(f.safeUrl); - parsed.searchParams.delete('options'); - parsed.searchParams.set('application_name', appName); - - const previousPgOptions = process.env.PGOPTIONS; - process.env.PGOPTIONS = `-c search_path=${f.schema} -c statement_timeout=99999 -c lock_timeout=88888`; - cleanup.push(() => { - if (previousPgOptions === undefined) { - delete process.env.PGOPTIONS; - } else { - process.env.PGOPTIONS = previousPgOptions; - } - }); - - const handle = await openResearchCopilotExecutor({ postgresUrl: parsed.toString() }); - cleanup.push(() => handle.close()); - - const { rows: schemaRows } = await handle.executor.query<{ current_schema: string | null }>( - 'SELECT current_schema() AS current_schema' - ); - const { rows: stmtRows } = await handle.executor.query<{ statement_timeout: string }>( - 'SHOW statement_timeout' - ); - const { rows: lockRows } = await handle.executor.query<{ lock_timeout: string }>( - 'SHOW lock_timeout' - ); - - expect(schemaRows[0]?.current_schema).toBe(f.schema); - expect(stmtRows[0]?.statement_timeout).toBe('10s'); - expect(lockRows[0]?.lock_timeout).toBe('2s'); - - // Verify unqualified findings writes and reads resolve against the PGOPTIONS search_path. - const writePort = createPostgresFindingWritePort({ executor: handle.executor }); - const readers = createPostgresKnowledgeReaders({ executor: handle.executor }); - const created = await writePort.appendFinding( - { - id: 'finding-pgoptions-0001', - kind: 'finding', - title: 'PGOPTIONS search_path finding', - summary: 'Resolved via PGOPTIONS search_path without explicit schema option.', - status: 'pending_review', - createdAt: FIXED_TS, - trialRefs: [], - evidenceRefs: [], - }, - 'idem-pgoptions-0001' - ); - expect(created.status).toBe('created'); - - const listed = await readers.listFindings({ query: 'PGOPTIONS search_path' }); - expect(listed).toHaveLength(1); - expect(listed[0]?.id).toBe('finding-pgoptions-0001'); - }); - - test('supports migrated findings writes, reads, idempotent replay, and real 23505 preservation', async () => { - const f = await createIsolatedFixture(); - const appName = `copilot_findings_${randomUUID().slice(0, 8)}`; - const executorUrl = buildExecutorUrl(f.safeUrl, f.schema, appName); - - const handle = await openResearchCopilotExecutor({ postgresUrl: executorUrl }); - cleanup.push(() => handle.close()); - - const writePort = createPostgresFindingWritePort({ - executor: handle.executor, - schema: f.schema, - }); - const readers = createPostgresKnowledgeReaders({ - executor: handle.executor, - schema: f.schema, - }); - - const record = { - id: 'finding-exec-0001', - kind: 'finding' as const, - title: 'Executor integration finding', - summary: 'Verified against migrated schema via openResearchCopilotExecutor.', - status: 'pending_review' as const, - createdAt: FIXED_TS, - trialRefs: ['101'], - evidenceRefs: ['snap:2025-06-29:ic'], - }; - - const first = await writePort.appendFinding(record, 'idem-key-0001'); - expect(first).toEqual({ - status: 'created', - id: 'finding-exec-0001', - createdAt: FIXED_TS, - }); - - // Same-ID, same-key replay must return the original finding and timestamp. - const replay = await writePort.appendFinding(record, 'idem-key-0001'); - expect(replay).toEqual({ - status: 'replayed', - id: 'finding-exec-0001', - createdAt: FIXED_TS, - }); - - // Unkeyed duplicate-PK insert hits PostgreSQL's primary-key constraint directly; - // verify the executor preserves SQLSTATE 23505 without leaking driver fields. - let pkCollisionErr: unknown; - try { - await writePort.appendFinding(record); - } catch (err) { - pkCollisionErr = err; - } - expect(pkCollisionErr).toBeInstanceOf(ResearchCopilotExecutorError); - expect((pkCollisionErr as ResearchCopilotExecutorError).code).toBe('23505'); - expect('cause' in (pkCollisionErr as object)).toBe(false); - expect('detail' in (pkCollisionErr as object)).toBe(false); - - const listed = await readers.listFindings({ query: 'Executor integration' }); - expect(listed).toHaveLength(1); - expect(listed[0]?.id).toBe('finding-exec-0001'); - expect(listed[0]?.trialRefs).toEqual(['101']); - - // Executor remains usable after 23505 collision. - const { rows } = await handle.executor.query<{ count: number }>( - `SELECT count(*)::int AS count FROM "${f.schema}".findings` - ); - expect(rows[0]?.count).toBe(1); - }); - - test('enforces Vault cutoff when wired into createPostgresTrialRefLookupPort', async () => { - const f = await createIsolatedFixture(); - await f.setupPool.query( - `INSERT INTO trial_ledger ( - trial_id, principal_id, stage, universe_market, horizon_bucket, expression_hash, - sample_start, sample_end, n_obs, sharpe_unann, skewness, kurtosis, daily_series - ) - OVERRIDING SYSTEM VALUE - VALUES - (1, 'operator', 'signal_ic', 'US_EQ', 'swing_1_10d', repeat('a', 64), '2020-01-01'::date, '2025-06-29'::date, 2, 0, 0, 3, ARRAY[0.1, 0.2]::real[]), - (2, 'operator', 'signal_ic', 'US_EQ', 'swing_1_10d', repeat('a', 64), '2020-01-01'::date, '2025-06-30'::date, 2, 0, 0, 3, ARRAY[0.1, 0.2]::real[])` - ); - - const appName = `copilot_vault_${randomUUID().slice(0, 8)}`; - const handle = await openResearchCopilotExecutor({ - postgresUrl: buildExecutorUrl(f.safeUrl, f.schema, appName), - }); - cleanup.push(() => handle.close()); - - const trialLookup = createPostgresTrialRefLookupPort({ - executor: handle.executor, - vaultCutoffTs: VAULT_CUTOFF_TS, - schema: f.schema, - }); - - expect(await trialLookup.hasResearchVisibleTrial('1')).toBe(true); - expect(await trialLookup.hasResearchVisibleTrial('2')).toBe(false); - }); - - test('caps concurrent backend connections at 4 and disconnects all backends on close()', async () => { - const f = await createIsolatedFixture(); - const appName = `copilot_cap_${randomUUID().slice(0, 8)}`; - const handle = await openResearchCopilotExecutor({ - postgresUrl: buildExecutorUrl(f.safeUrl, f.schema, appName), - }); - cleanup.push(() => handle.close()); - - const results = await Promise.all( - Array.from({ length: RESEARCH_COPILOT_PG_POOL_MAX + 2 }, () => - handle.executor.query<{ pid: number }>( - 'SELECT pg_backend_pid() AS pid FROM pg_sleep(0.15)' - ) - ) - ); - const distinctPids = new Set(results.map(r => r.rows[0]?.pid)); - expect(distinctPids.size).toBeGreaterThanOrEqual(1); - expect(distinctPids.size).toBeLessThanOrEqual(RESEARCH_COPILOT_PG_POOL_MAX); - - await handle.close(); - - const remainingBackends = await waitForZeroBackends(f.admin, appName); - expect(remainingBackends).toBe(0); - - let caught: unknown; - try { - await handle.executor.query('SELECT 1'); - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(ResearchCopilotExecutorError); - expect((caught as ResearchCopilotExecutorError).code).toBe('EXECUTOR_CLOSED'); - }); -}); diff --git a/test/postgres/mcp-findings-adapter.test.ts b/test/postgres/mcp-findings-adapter.test.ts deleted file mode 100644 index 30857d7d..00000000 --- a/test/postgres/mcp-findings-adapter.test.ts +++ /dev/null @@ -1,934 +0,0 @@ -import { randomUUID } from 'node:crypto'; -import { readFileSync } from 'node:fs'; -import { fileURLToPath } from 'node:url'; -import { afterEach, describe, expect, test } from 'bun:test'; -import { Client, Pool, type PoolClient, type PoolConfig } from 'pg'; -import { getLogger, setLoggerConfig } from '@stock-bot/logger'; -import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres'; -import { - FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF, - type FileFindingResultPayload, - type FiledFindingRecord, - type PostgresFindingsExecutor, - type ReadKnowledgeResultPayload, - createFileFindingTool, - createMcpServer, - createPostgresFindingWritePort, - createPostgresKnowledgeReaders, - createReadKnowledgeTool, -} from '../../libs/research/src/mcp/index'; - -setLoggerConfig({ logLevel: 'fatal', logConsole: false }); -const logger = getLogger('mcp-findings-adapter-pg-test'); -const url = process.env.PIPELINE_TEST_DATABASE_URL; -const initDir = fileURLToPath(new URL('../../database/postgres/init/', import.meta.url)); - -const FIXED_TS = '2026-01-15T12:34:56.789Z'; - -const cleanup: (() => Promise | void)[] = []; -afterEach(async () => { - for (const close of cleanup.splice(0).reverse()) { - await close(); - } -}); - -function assertSafetyDatabaseUrl(connectionString: string | undefined): string { - if (!connectionString) { - throw new Error('Dedicated stock_bot_safety database required'); - } - let parsed: URL; - try { - parsed = new URL(connectionString); - } catch { - throw new Error('Dedicated stock_bot_safety database required'); - } - if (parsed.protocol !== 'postgres:' && parsed.protocol !== 'postgresql:') { - throw new Error('Dedicated stock_bot_safety database required'); - } - const client = new Client({ connectionString }); - const effectiveDb = ( - client as unknown as { connectionParameters?: { database?: unknown } } - ).connectionParameters?.database; - if ( - typeof effectiveDb !== 'string' || - !effectiveDb.startsWith('stock_bot_safety') || - !parsed.pathname.startsWith('/stock_bot_safety') - ) { - throw new Error('Dedicated stock_bot_safety database required'); - } - return connectionString; -} - -function createPgExecutor(queryable: Pick | Pick): PostgresFindingsExecutor { - return { - query>( - text: string, - params?: readonly unknown[] - ): Promise<{ readonly rows: readonly Row[] }> { - return queryable.query( - text, - params === undefined ? undefined : [...params] - ) as unknown as Promise<{ readonly rows: readonly Row[] }>; - }, - }; -} - -async function waitForBackendLockWait(pool: Pool, pid: number, timeoutMs = 2000): Promise { - const deadline = Date.now() + timeoutMs; - while (Date.now() < deadline) { - const { rows } = await pool.query<{ wait_event_type: string | null }>( - 'SELECT wait_event_type FROM pg_stat_activity WHERE pid = $1', - [pid] - ); - if (rows[0]?.wait_event_type === 'Lock') { - return; - } - await new Promise(resolve => setTimeout(resolve, 10)); - } - throw new Error(`Timed out waiting for backend pid ${pid} to enter Lock wait`); -} - -function buildIsolatedPoolConfig(connectionString: string | undefined, schema: string): PoolConfig { - const safeUrl = assertSafetyDatabaseUrl(connectionString); - const parsed = new URL(safeUrl); - const existingOptions = parsed.searchParams - .getAll('options') - .map(value => value.trim()) - .filter(value => value.length > 0); - parsed.searchParams.delete('options'); - - const schemaOptions = `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`; - const options = [...existingOptions, schemaOptions].join(' '); - - return { - connectionString: parsed.toString(), - options, - }; -} - -async function createIsolatedFixture(connectionString: string | undefined = url) { - const safeUrl = assertSafetyDatabaseUrl(connectionString); - const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`; - const admin = new Pool({ connectionString: safeUrl }); - await admin.query(`CREATE SCHEMA ${schema}`); - const pool = new Pool(buildIsolatedPoolConfig(safeUrl, schema)); - cleanup.push(async () => { - await pool.end(); - await admin.query(`DROP SCHEMA ${schema} CASCADE`); - await admin.end(); - }); - - const { rows: schemaRows } = await pool.query<{ current_schema: string | null }>( - 'SELECT current_schema() AS current_schema' - ); - if (schemaRows[0]?.current_schema !== schema) { - throw new Error( - `Isolated fixture pool expected current_schema()=${schema}, got ${String(schemaRows[0]?.current_schema)}` - ); - } - - // 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 { admin, pool, schema }; -} - -function makeFinding(overrides: Partial = {}): FiledFindingRecord { - return { - id: `finding-${randomUUID()}`, - kind: 'finding', - title: 'Momentum factor decays after 5 sessions', - status: 'pending_review', - createdAt: FIXED_TS, - summary: 'Cross-sectional rank IC turns negative past day 5.', - trialRefs: ['101', '102'], - evidenceRefs: ['snap:2026-01-15:ic'], - ...overrides, - }; -} - -describe('PostgreSQL findings adapter safety guard', () => { - test('rejects unsafe database targets before connecting', () => { - expect(() => assertSafetyDatabaseUrl(undefined)).toThrow( - 'Dedicated stock_bot_safety database required' - ); - expect(() => - assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/trading_bot') - ).toThrow('Dedicated stock_bot_safety database required'); - expect(() => - assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5433/trading_bot_dev') - ).toThrow('Dedicated stock_bot_safety database required'); - expect(() => - assertSafetyDatabaseUrl('socket:/stock_bot_safety?db=trading_bot') - ).toThrow('Dedicated stock_bot_safety database required'); - expect(() => - assertSafetyDatabaseUrl('socket:///stock_bot_safety?db=trading_bot') - ).toThrow('Dedicated stock_bot_safety database required'); - expect(() => - assertSafetyDatabaseUrl('http://127.0.0.1:5432/stock_bot_safety_test') - ).toThrow('Dedicated stock_bot_safety database required'); - expect(() => assertSafetyDatabaseUrl('not-a-valid-url')).toThrow( - 'Dedicated stock_bot_safety database required' - ); - expect( - assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test') - ).toBe('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test'); - expect( - assertSafetyDatabaseUrl( - 'postgresql://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test' - ) - ).toBe('postgresql://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test'); - }); - - test('preserves isolated schema search_path precedence over URL startup options', () => { - const schema = 'stock_bot_safety_findings_options'; - const urlWithOptions = - 'postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test?options=-c%20statement_timeout%3D30000%20-c%20search_path%3Dpublic'; - const poolConfig = buildIsolatedPoolConfig(urlWithOptions, schema); - - expect(new URL(poolConfig.connectionString!).searchParams.has('options')).toBe(false); - - const client = new Client(poolConfig); - const resolvedOptions = (client as unknown as { connectionParameters: { options?: string } }) - .connectionParameters.options; - expect(resolvedOptions).toBe( - `-c statement_timeout=30000 -c search_path=public -c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000` - ); - }); -}); - -describe.skipIf(!url)('PostgreSQL MCP findings & provider caveats adapter', () => { - test('supports unkeyed inserts, keyed created -> replayed -> conflict, same-ID retries, and unrelated duplicate PK errors', async () => { - const f = await createIsolatedFixture(); - const writePort = createPostgresFindingWritePort({ executor: createPgExecutor(f.pool) }); - - // Two independent unkeyed inserts produce two distinct rows. - const u1 = await writePort.appendFinding(makeFinding({ id: 'f-unkeyed-1' })); - const u2 = await writePort.appendFinding(makeFinding({ id: 'f-unkeyed-2' })); - expect(u1).toEqual({ status: 'created', id: 'f-unkeyed-1', createdAt: FIXED_TS }); - expect(u2).toEqual({ status: 'created', id: 'f-unkeyed-2', createdAt: FIXED_TS }); - - // Keyed create -> replay -> conflict - const original = makeFinding({ - id: 'f-keyed-1', - createdAt: '2026-01-15T12:34:56.789Z', - }); - const created = await writePort.appendFinding(original, 'idem-roundtrip'); - expect(created).toEqual({ - status: 'created', - id: 'f-keyed-1', - createdAt: '2026-01-15T12:34:56.789Z', - }); - - // Replay with new generated ID and timestamp returns original stored ID and timestamp. - const replayed = await writePort.appendFinding( - { - ...original, - id: 'f-keyed-retry-new-id', - createdAt: '2026-01-16T00:00:00.000Z', - }, - 'idem-roundtrip' - ); - expect(replayed).toEqual({ - status: 'replayed', - id: 'f-keyed-1', - createdAt: '2026-01-15T12:34:56.789Z', - }); - - // Same-ID retry (triggers PK 23505) resolves cleanly as replayed / conflict. - const sameIdReplay = await writePort.appendFinding(original, 'idem-roundtrip'); - expect(sameIdReplay).toEqual({ - status: 'replayed', - id: 'f-keyed-1', - createdAt: '2026-01-15T12:34:56.789Z', - }); - const sameIdConflict = await writePort.appendFinding( - { ...original, title: 'Mutated title on same-ID retry' }, - 'idem-roundtrip' - ); - expect(sameIdConflict).toEqual({ status: 'conflict' }); - - // Different payload with new ID returns conflict and leaves row count unchanged. - const conflict = await writePort.appendFinding( - { ...original, id: 'f-keyed-conflict', summary: 'Different summary' }, - 'idem-roundtrip' - ); - expect(conflict).toEqual({ status: 'conflict' }); - - // Unrelated duplicate primary key (collides with unkeyed row f-unkeyed-1) propagates 23505. - let pkError: unknown; - try { - await writePort.appendFinding(makeFinding({ id: 'f-unkeyed-1' }), 'idem-fresh-unrelated'); - } catch (err) { - pkError = err; - } - expect((pkError as { code?: string } | null)?.code).toBe('23505'); - - const countRow = (await f.pool.query<{ c: number }>('SELECT count(*)::int AS c FROM findings')) - .rows[0]; - expect(countRow?.c).toBe(3); - }); - - test('concurrent same-key appends on pinned connections observe committed winner via fresh snapshot for identical and differing payloads', async () => { - const f = await createIsolatedFixture(); - - const runPinnedRace = async ( - key: string, - winnerRecord: FiledFindingRecord, - loserRecord: FiledFindingRecord - ) => { - const winnerClient = await f.pool.connect(); - let winnerOpen = false; - cleanup.push(async () => { - if (winnerOpen) { - await winnerClient.query('ROLLBACK').catch(() => {}); - } - winnerClient.release(); - }); - const loserClient = await f.pool.connect(); - cleanup.push(() => { - loserClient.release(); - }); - - const loserPid = ( - await loserClient.query<{ pid: number }>('SELECT pg_backend_pid() AS pid') - ).rows[0]!.pid; - - const winnerPort = createPostgresFindingWritePort({ - executor: createPgExecutor(winnerClient), - }); - const loserPort = createPostgresFindingWritePort({ - executor: createPgExecutor(loserClient), - }); - - await winnerClient.query('BEGIN'); - winnerOpen = true; - const winnerOutcome = await winnerPort.appendFinding(winnerRecord, key); - expect(winnerOutcome).toEqual({ - status: 'created', - id: winnerRecord.id, - createdAt: winnerRecord.createdAt, - }); - - // Start the competing append on the second connection and wait until PostgreSQL - // blocks its INSERT ... ON CONFLICT DO NOTHING on the winner's uncommitted tuple. - const loserPromise = loserPort.appendFinding(loserRecord, key); - await waitForBackendLockWait(f.pool, loserPid); - - await winnerClient.query('COMMIT'); - winnerOpen = false; - - const loserOutcome = await loserPromise; - return { winnerOutcome, loserOutcome }; - }; - - // Concurrent identical payloads: loser's separate READ COMMITTED lookup sees winner -> replayed - const recA = makeFinding({ id: 'f-race-same-a', createdAt: '2026-01-15T10:00:00.000Z' }); - const recB = { ...recA, id: 'f-race-same-b', createdAt: '2026-01-15T10:00:01.000Z' }; - const sameRace = await runPinnedRace('idem-race-same', recA, recB); - expect(sameRace.loserOutcome).toEqual({ - status: 'replayed', - id: recA.id, - createdAt: recA.createdAt, - }); - - const storedSame = ( - await f.pool.query<{ id: string }>( - 'SELECT id FROM findings WHERE idempotency_key = $1', - ['idem-race-same'] - ) - ).rows; - expect(storedSame).toEqual([{ id: recA.id }]); - - // Concurrent differing payloads: loser's separate READ COMMITTED lookup sees winner -> conflict - const diffA = makeFinding({ - id: 'f-race-diff-a', - title: 'Race title A', - createdAt: '2026-01-15T11:00:00.000Z', - }); - const diffB = makeFinding({ - id: 'f-race-diff-b', - title: 'Race title B', - createdAt: '2026-01-15T11:00:01.000Z', - }); - const diffRace = await runPinnedRace('idem-race-diff', diffA, diffB); - expect(diffRace.loserOutcome).toEqual({ status: 'conflict' }); - - const storedDiff = ( - await f.pool.query<{ id: string }>( - 'SELECT id FROM findings WHERE idempotency_key = $1', - ['idem-race-diff'] - ) - ).rows; - expect(storedDiff).toEqual([{ id: diffA.id }]); - }); - - test('readers return all eligible candidates in deterministic id order with mixed-case, provider, exact-id precedence, wildcard escaping, and explicit schema', async () => { - const f = await createIsolatedFixture(); - // Use admin pool (default search_path) with explicit schema option to verify quoting. - const writePort = createPostgresFindingWritePort({ - executor: createPgExecutor(f.admin), - schema: f.schema, - }); - const readers = createPostgresKnowledgeReaders({ - executor: createPgExecutor(f.admin), - schema: f.schema, - }); - - await writePort.appendFinding( - makeFinding({ - id: 'f-003', - title: '100% Pure_Wild\\Match', - summary: 'Literal wildcard finding.', - createdAt: '2026-01-15T03:00:00.000Z', - }) - ); - await writePort.appendFinding( - makeFinding({ - id: 'f-001', - title: '100X PureAWildXMatch', - summary: 'Near-match without literal wildcards.', - createdAt: '2026-01-15T01:00:00.000Z', - }) - ); - await writePort.appendFinding( - makeFinding({ - id: 'f-002', - title: 'Alpha Drift Signal', - summary: 'Observed on TSX equities.', - createdAt: '2026-01-15T02:00:00.000Z', - }) - ); - - await f.pool.query( - `INSERT INTO provider_caveats (id, provider, dataset, caveat, created_at) - VALUES - ('c-003', 'EODHD', 'eodIntraday1M', '100% split_adjusted\\bars', '2026-01-15T03:00:00.000Z'), - ('c-001', 'QuoteMedia', 'qmSplits', '100X splitXadjustedYbars', '2026-01-15T01:00:00.000Z'), - ('c-002', 'EODHD', 'eodPrices', 'Daily raw OHLCV needs un-adjustment.', '2026-01-15T02:00:00.000Z')` - ); - - // Deterministic id ASC order for unfiltered reads - expect((await readers.listFindings({})).map(r => r.id)).toEqual(['f-001', 'f-002', 'f-003']); - expect((await readers.listProviderCaveats({})).map(r => r.id)).toEqual([ - 'c-001', - 'c-002', - 'c-003', - ]); - - // Mixed-case query matching - expect((await readers.listFindings({ query: 'tsx EQUITIES' })).map(r => r.id)).toEqual([ - 'f-002', - ]); - expect((await readers.listProviderCaveats({ query: 'DAILY RAW' })).map(r => r.id)).toEqual([ - 'c-002', - ]); - - // Case-insensitive provider filter - expect((await readers.listProviderCaveats({ provider: 'eodhd' })).map(r => r.id)).toEqual([ - 'c-002', - 'c-003', - ]); - - // Exact id is case-sensitive and takes precedence over query - expect( - (await readers.listFindings({ id: 'f-002', query: 'does-not-match' })).map(r => r.id) - ).toEqual(['f-002']); - expect(await readers.listFindings({ id: 'F-002' })).toEqual([]); - - // Provider condition still applies with exact id - expect( - (await readers.listProviderCaveats({ id: 'c-002', provider: 'eodhd', query: 'nope' })).map( - r => r.id - ) - ).toEqual(['c-002']); - expect( - await readers.listProviderCaveats({ id: 'c-002', provider: 'quotemedia' }) - ).toEqual([]); - - // Literal wildcard escaping: matches f-003 / c-003 and excludes near-matches f-001 / c-001 - expect((await readers.listFindings({ query: '100% Pure_Wild\\' })).map(r => r.id)).toEqual([ - 'f-003', - ]); - expect( - (await readers.listProviderCaveats({ query: '100% split_adjusted\\' })).map(r => r.id) - ).toEqual(['c-003']); - }); - - test('round-trips createFileFindingTool -> createReadKnowledgeTool through MCP server', async () => { - const f = await createIsolatedFixture(); - const executor = createPgExecutor(f.pool); - const writePort = createPostgresFindingWritePort({ executor }); - const readers = createPostgresKnowledgeReaders({ executor }); - - await f.pool.query( - `INSERT INTO provider_caveats (id, provider, dataset, caveat, created_at) - VALUES ('caveat-eod-1', 'EODHD', 'eodIntraday1M', 'Retroactively split-adjusted.', $1::timestamptz)`, - [FIXED_TS] - ); - - let idSeq = 0; - const allowedTrials = new Set(['101', '102']); - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createFileFindingTool({ - port: writePort, - trialLookup: { - hasResearchVisibleTrial(ref) { - return allowedTrials.has(ref); - }, - }, - newId: () => { - idSeq += 1; - return `finding-mcp-${idSeq}`; - }, - now: () => new Date(FIXED_TS), - }), - createReadKnowledgeTool({ - port: { - listLibraryCards: async () => [], - ...readers, - }, - }), - ], - }); - - const callTool = async (name: string, args: Record) => { - const raw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: `req-${name}`, - method: 'tools/call', - params: { name, arguments: args }, - }) - ); - expect(raw).not.toBeNull(); - const parsed = JSON.parse(raw!) as { - result: { isError?: boolean; content: Array<{ text: string }> }; - }; - return parsed.result; - }; - - // File a new finding through MCP - const fileRes = await callTool('file_finding', { - kind: 'finding', - title: 'Post-earnings drift persists 3 sessions', - summary: 'Positive rank IC across research-visible trials 101 and 102.', - trialRefs: ['102', '101'], - evidenceRefs: ['snap:b', 'snap:a'], - idempotencyKey: 'mcp-idem-1', - }); - expect(fileRes.isError).toBeUndefined(); - const receipt = JSON.parse(fileRes.content[0]!.text) as FileFindingResultPayload; - expect(receipt).toEqual({ - id: 'finding-mcp-1', - createdAt: FIXED_TS, - created: true, - }); - - // Retry with reordered & duplicate refs -> normalized replay with original receipt - const retryRes = await callTool('file_finding', { - kind: 'finding', - title: 'Post-earnings drift persists 3 sessions', - summary: 'Positive rank IC across research-visible trials 101 and 102.', - trialRefs: ['101', '102', '101'], - evidenceRefs: ['snap:a', 'snap:b', 'snap:a'], - idempotencyKey: 'mcp-idem-1', - }); - expect(retryRes.isError).toBeUndefined(); - const retryReceipt = JSON.parse(retryRes.content[0]!.text) as FileFindingResultPayload; - expect(retryReceipt).toEqual({ - id: 'finding-mcp-1', - createdAt: FIXED_TS, - created: false, - }); - - // Unavailable / Vault-only trial ref returns error and writes zero rows - const deniedRes = await callTool('file_finding', { - kind: 'dead_end', - title: 'Should not persist', - summary: 'References unavailable trial.', - trialRefs: ['999-vault'], - }); - expect(deniedRes.isError).toBe(true); - expect(deniedRes.content[0]!.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF); - - // Read back the filed finding by receipt ID via read_knowledge - const readRes = await callTool('read_knowledge', { - source: 'findings', - id: receipt.id, - }); - expect(readRes.isError).toBeUndefined(); - const knowledge = JSON.parse(readRes.content[0]!.text) as ReadKnowledgeResultPayload; - expect(knowledge).toEqual({ - rowCount: 1, - sources: { library: 0, findings: 1, provider_caveats: 0 }, - rows: [ - { - source: 'findings', - id: 'finding-mcp-1', - title: 'Post-earnings drift persists 3 sessions', - status: 'pending_review', - createdAt: FIXED_TS, - summary: 'Positive rank IC across research-visible trials 101 and 102.', - trialRefs: ['101', '102'], - evidenceRefs: ['snap:a', 'snap:b'], - truncated: false, - }, - ], - }); - - // Verify provider_caveats case-insensitive filter through read_knowledge - const caveatRes = await callTool('read_knowledge', { - source: 'provider_caveats', - provider: 'eodhd', - }); - expect(caveatRes.isError).toBeUndefined(); - const caveatsPayload = JSON.parse(caveatRes.content[0]!.text) as ReadKnowledgeResultPayload; - expect(caveatsPayload.rowCount).toBe(1); - expect(caveatsPayload.sources).toEqual({ library: 0, findings: 0, provider_caveats: 1 }); - expect(caveatsPayload.rows[0]).toEqual({ - source: 'provider_caveats', - id: 'caveat-eod-1', - provider: 'EODHD', - dataset: 'eodIntraday1M', - caveat: 'Retroactively split-adjusted.', - createdAt: FIXED_TS, - truncated: false, - }); - - // Confirm only 1 finding row was persisted in total - const totalFindings = ( - await f.pool.query<{ c: number }>('SELECT count(*)::int AS c FROM findings') - ).rows[0]?.c; - expect(totalFindings).toBe(1); - - // Regression: Unicode final sigma (κοσμος vs ΚΟΣΜΟΣ) must not be dropped by libc ILIKE - const sigmaFileRes = await callTool('file_finding', { - kind: 'finding', - title: 'κοσμος', - summary: 'Greek final sigma regression finding.', - trialRefs: ['101'], - evidenceRefs: [], - }); - expect(sigmaFileRes.isError).toBeUndefined(); - const sigmaReceipt = JSON.parse(sigmaFileRes.content[0]!.text) as FileFindingResultPayload; - - const sigmaReadRes = await callTool('read_knowledge', { - source: 'findings', - query: 'ΚΟΣΜΟΣ', - }); - expect(sigmaReadRes.isError).toBeUndefined(); - const sigmaKnowledge = JSON.parse( - sigmaReadRes.content[0]!.text - ) as ReadKnowledgeResultPayload; - expect(sigmaKnowledge.rowCount).toBe(1); - expect(sigmaKnowledge.rows[0]?.id).toBe(sigmaReceipt.id); - - await f.pool.query( - `INSERT INTO provider_caveats (id, provider, dataset, caveat, created_at) - VALUES ('caveat-sigma-1', 'EODHD', 'eodPrices', 'Caveat for κοσμος tickers.', $1::timestamptz)`, - [FIXED_TS] - ); - const sigmaCaveatRes = await callTool('read_knowledge', { - source: 'provider_caveats', - provider: 'eodhd', - query: 'ΚΟΣΜΟΣ', - }); - expect(sigmaCaveatRes.isError).toBeUndefined(); - const sigmaCaveats = JSON.parse( - sigmaCaveatRes.content[0]!.text - ) as ReadKnowledgeResultPayload; - expect(sigmaCaveats.rowCount).toBe(1); - expect(sigmaCaveats.rows[0]?.id).toBe('caveat-sigma-1'); - }); - - test('matches ASCII queries and providers against Unicode stored text under PostgreSQL C collation through MCP', async () => { - const f = await createIsolatedFixture(); - - // Force C collation on text columns to reproduce the C-collation casing mismatch - // regardless of the host test database's default collation. - await f.pool.query(` - ALTER TABLE findings - ALTER COLUMN title TYPE TEXT COLLATE "C", - ALTER COLUMN summary TYPE TEXT COLLATE "C"; - ALTER TABLE provider_caveats - ALTER COLUMN provider TYPE TEXT COLLATE "C", - ALTER COLUMN dataset TYPE TEXT COLLATE "C", - ALTER COLUMN caveat TYPE TEXT COLLATE "C"; - `); - - // Prove PostgreSQL C collation itself fails both direct SQL casing comparisons. - const pgCheck = ( - await f.pool.query<{ ilike_match: boolean; lower_match: boolean }>( - `SELECT - ('BİST exchange coverage' COLLATE "C" ILIKE '%bi%') AS ilike_match, - (lower('K' COLLATE "C") = lower('k' COLLATE "C")) AS lower_match` - ) - ).rows[0]!; - expect(pgCheck.ilike_match).toBe(false); - expect(pgCheck.lower_match).toBe(false); - - const executor = createPgExecutor(f.pool); - const writePort = createPostgresFindingWritePort({ executor }); - const readers = createPostgresKnowledgeReaders({ executor }); - - let idSeq = 0; - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createFileFindingTool({ - port: writePort, - trialLookup: { - hasResearchVisibleTrial(ref) { - return ref === '101'; - }, - }, - newId: () => { - idSeq += 1; - return `finding-c-coll-${idSeq}`; - }, - now: () => new Date(FIXED_TS), - }), - createReadKnowledgeTool({ - port: { - listLibraryCards: async () => [], - ...readers, - }, - }), - ], - }); - - const callTool = async (name: string, args: Record) => { - const raw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: `req-c-coll-${name}`, - method: 'tools/call', - params: { name, arguments: args }, - }) - ); - expect(raw).not.toBeNull(); - const parsed = JSON.parse(raw!) as { - result: { isError?: boolean; content: Array<{ text: string }> }; - }; - return parsed.result; - }; - - // File Unicode finding 'BİST exchange coverage' and an unrelated Unicode finding 'κόσμος' - const bistFileRes = await callTool('file_finding', { - kind: 'finding', - title: 'BİST exchange coverage', - summary: 'Turkish equities universe check.', - trialRefs: ['101'], - evidenceRefs: [], - }); - expect(bistFileRes.isError).toBeUndefined(); - const bistReceipt = JSON.parse(bistFileRes.content[0]!.text) as FileFindingResultPayload; - - const unrelatedFileRes = await callTool('file_finding', { - kind: 'finding', - title: 'κόσμος', - summary: 'Unrelated Greek finding.', - trialRefs: ['101'], - evidenceRefs: [], - }); - expect(unrelatedFileRes.isError).toBeUndefined(); - - // ASCII query 'bi' must match 'BİST exchange coverage' and exclude 'κόσμος' - const bistReadRes = await callTool('read_knowledge', { - source: 'findings', - query: 'bi', - }); - expect(bistReadRes.isError).toBeUndefined(); - const bistKnowledge = JSON.parse( - bistReadRes.content[0]!.text - ) as ReadKnowledgeResultPayload; - expect(bistKnowledge.rowCount).toBe(1); - expect(bistKnowledge.rows[0]?.id).toBe(bistReceipt.id); - - // Provider caveats: ASCII query against 'BİST' text, and ASCII provider 'k' against 'K' (U+212A) - await f.pool.query( - `INSERT INTO provider_caveats (id, provider, dataset, caveat, created_at) - VALUES - ('caveat-c-bist', 'EODHD', 'eodPrices', 'BİST intraday feed caveat.', $1::timestamptz), - ('caveat-c-kelvin', 'K', 'kelvinBars', 'Kelvin sign provider caveat.', $1::timestamptz), - ('caveat-c-greek', 'EODHD', 'eodPrices', 'Unrelated κόσμος caveat.', $1::timestamptz)`, - [FIXED_TS] - ); - - const bistCaveatRes = await callTool('read_knowledge', { - source: 'provider_caveats', - provider: 'eodhd', - query: 'bi', - }); - expect(bistCaveatRes.isError).toBeUndefined(); - const bistCaveats = JSON.parse( - bistCaveatRes.content[0]!.text - ) as ReadKnowledgeResultPayload; - expect(bistCaveats.rowCount).toBe(1); - expect(bistCaveats.rows[0]?.id).toBe('caveat-c-bist'); - - const kelvinCaveatRes = await callTool('read_knowledge', { - source: 'provider_caveats', - provider: 'k', - }); - expect(kelvinCaveatRes.isError).toBeUndefined(); - const kelvinCaveats = JSON.parse( - kelvinCaveatRes.content[0]!.text - ) as ReadKnowledgeResultPayload; - expect(kelvinCaveats.rowCount).toBe(1); - expect(kelvinCaveats.rows[0]?.id).toBe('caveat-c-kelvin'); - }); -}); - -// QA (T-161): seeded differential check that the adapter's SQL pushdown plus JS -// post-filter never drops or adds a row relative to read_knowledge's JS matching -// rules, against real PostgreSQL under both the database default and "C" collation. -function qaMulberry32(seed: number): () => number { - let a = seed >>> 0; - return () => { - a = (a + 0x6d2b79f5) >>> 0; - let t = a; - t = Math.imul(t ^ (t >>> 15), t | 1); - t ^= t + Math.imul(t ^ (t >>> 7), t | 61); - return ((t ^ (t >>> 14)) >>> 0) / 4294967296; - }; -} - -const QA_ALPHABET = ['a', 'B', 'i', 'I', 's', 'S', 'k', '%', '_', '\\', ' ', 'İ', 'ı', 'Σ', 'ς', 'K', 'é', 'ß']; - -function qaText(rand: () => number, min: number, max: number): string { - const len = min + Math.floor(rand() * (max - min + 1)); - let out = ''; - for (let i = 0; i < len; i += 1) { - out += QA_ALPHABET[Math.floor(rand() * QA_ALPHABET.length)]; - } - return out; -} - -function qaQuery(rand: () => number, corpus: readonly string[]): string { - if (rand() < 0.5) { - const source = corpus[Math.floor(rand() * corpus.length)]!; - const start = Math.floor(rand() * source.length); - const end = Math.min(source.length, start + 1 + Math.floor(rand() * 3)); - let q = ''; - for (const ch of source.slice(start, end)) { - q += rand() < 0.5 ? ch.toUpperCase() : ch.toLowerCase(); - } - return q.length > 0 ? q : 'a'; - } - return qaText(rand, 1, 2); -} - -describe.skipIf(!url)('PostgreSQL findings readers QA differential vs read_knowledge matching', () => { - for (const forceCCollation of [false, true]) { - test(`seeded corpus/query fuzz agrees with JS matching (${forceCCollation ? 'C' : 'default'} collation)`, async () => { - const f = await createIsolatedFixture(); - if (forceCCollation) { - await f.pool.query(` - ALTER TABLE findings - ALTER COLUMN title TYPE TEXT COLLATE "C", - ALTER COLUMN summary TYPE TEXT COLLATE "C"; - ALTER TABLE provider_caveats - ALTER COLUMN provider TYPE TEXT COLLATE "C", - ALTER COLUMN dataset TYPE TEXT COLLATE "C", - ALTER COLUMN caveat TYPE TEXT COLLATE "C"; - `); - } - const executor = createPgExecutor(f.pool); - const writePort = createPostgresFindingWritePort({ executor }); - const readers = createPostgresKnowledgeReaders({ executor }); - const rand = qaMulberry32(forceCCollation ? 4242 : 161); - - const findings = Array.from({ length: 30 }, (_, i) => ({ - id: `qa-f-${String(i).padStart(3, '0')}`, - title: `T${qaText(rand, 2, 6)}`, - summary: `S${qaText(rand, 2, 6)}`, - })); - for (const row of findings) { - const outcome = await writePort.appendFinding( - makeFinding({ id: row.id, title: row.title, summary: row.summary }) - ); - expect(outcome.status).toBe('created'); - } - - const providers = ['EODHD', 'eodhd', 'K', 'kelvin', 'İBK', 'ibk', 'ΣΙΣ', 'σις']; - const caveats = Array.from({ length: 30 }, (_, i) => ({ - id: `qa-c-${String(i).padStart(3, '0')}`, - provider: providers[Math.floor(rand() * providers.length)]!, - dataset: `D${qaText(rand, 2, 5)}`, - caveat: `C${qaText(rand, 2, 6)}`, - })); - for (const row of caveats) { - await f.pool.query( - `INSERT INTO provider_caveats (id, provider, dataset, caveat, created_at) - VALUES ($1, $2, $3, $4, $5::timestamptz)`, - [row.id, row.provider, row.dataset, row.caveat, FIXED_TS] - ); - } - - const findingCorpus = findings.flatMap(r => [r.title, r.summary]); - for (let n = 0; n < 60; n += 1) { - const query = qaQuery(rand, findingCorpus); - const lower = query.toLowerCase(); - const expected = findings - .filter( - r => r.title.toLowerCase().includes(lower) || r.summary.toLowerCase().includes(lower) - ) - .map(r => r.id); - const actual = (await readers.listFindings({ query })).map(r => r.id); - expect({ query, ids: actual }).toEqual({ query, ids: expected }); - } - - const caveatCorpus = caveats.flatMap(r => [r.provider, r.dataset, r.caveat]); - for (let n = 0; n < 60; n += 1) { - const provider = - rand() < 0.6 - ? providers[Math.floor(rand() * providers.length)]!.toUpperCase() - : undefined; - const query = rand() < 0.7 ? qaQuery(rand, caveatCorpus) : undefined; - const lowerProvider = provider?.toLowerCase(); - const lowerQuery = query?.toLowerCase(); - const expected = caveats - .filter(r => lowerProvider === undefined || r.provider.toLowerCase() === lowerProvider) - .filter( - r => - lowerQuery === undefined || - r.provider.toLowerCase().includes(lowerQuery) || - r.dataset.toLowerCase().includes(lowerQuery) || - r.caveat.toLowerCase().includes(lowerQuery) - ) - .map(r => r.id); - const actual = ( - await readers.listProviderCaveats({ - ...(provider !== undefined ? { provider } : {}), - ...(query !== undefined ? { query } : {}), - }) - ).map(r => r.id); - expect({ provider, query, ids: actual }).toEqual({ provider, query, ids: expected }); - } - }, 30_000); - } -}); diff --git a/test/postgres/mcp-symbol-search-adapter.test.ts b/test/postgres/mcp-symbol-search-adapter.test.ts deleted file mode 100644 index d0270313..00000000 --- a/test/postgres/mcp-symbol-search-adapter.test.ts +++ /dev/null @@ -1,587 +0,0 @@ -import { randomUUID } from 'node:crypto'; -import { afterEach, describe, expect, test } from 'bun:test'; -import { Client, Pool, type PoolConfig } from 'pg'; -import { getLogger, setLoggerConfig } from '@stock-bot/logger'; -import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres'; -import { - createMcpServer, - createPostgresSymbolSearchPort, - createSearchSymbolsTool, - type SearchSymbolsResultPayload, - type SymbolSearchExecutor, -} from '../../libs/research/src/mcp/index'; - -setLoggerConfig({ logLevel: 'fatal', logConsole: false }); -const logger = getLogger('mcp-symbol-search-adapter-pg-test'); -const url = process.env.PIPELINE_TEST_DATABASE_URL; - -const VAULT_CUTOFF_DATE = '2024-06-30'; -const VAULT_CUTOFF_TS = Date.UTC(2024, 5, 30, 0, 0, 0, 0); - -const cleanup: (() => Promise | void)[] = []; -afterEach(async () => { - for (const close of cleanup.splice(0).reverse()) { - await close(); - } -}); - -function assertSafetyDatabaseUrl(connectionString: string | undefined): string { - if (!connectionString || !new URL(connectionString).pathname.startsWith('/stock_bot_safety')) { - throw new Error('Dedicated stock_bot_safety database required'); - } - return connectionString; -} - -function createPgExecutor(pool: Pool): SymbolSearchExecutor { - return { - query>( - text: string, - params?: readonly unknown[] - ): Promise<{ readonly rows: readonly Row[] }> { - return pool.query( - text, - params === undefined ? undefined : [...params] - ) as unknown as Promise<{ readonly rows: readonly Row[] }>; - }, - }; -} - -function buildIsolatedPoolConfig(connectionString: string | undefined, schema: string): PoolConfig { - const safeUrl = assertSafetyDatabaseUrl(connectionString); - const parsed = new URL(safeUrl); - const existingOptions = parsed.searchParams - .getAll('options') - .map(value => value.trim()) - .filter(value => value.length > 0); - parsed.searchParams.delete('options'); - - const schemaOptions = `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`; - const options = [...existingOptions, schemaOptions].join(' '); - - return { - connectionString: parsed.toString(), - options, - }; -} - -async function createIsolatedFixture(connectionString: string | undefined = url) { - const safeUrl = assertSafetyDatabaseUrl(connectionString); - const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`; - const admin = new Pool({ connectionString: safeUrl }); - await admin.query(`CREATE SCHEMA ${schema}`); - const pool = new Pool(buildIsolatedPoolConfig(safeUrl, schema)); - cleanup.push(async () => { - await pool.end(); - await admin.query(`DROP SCHEMA ${schema} CASCADE`); - await admin.end(); - }); - - const { rows: schemaRows } = await pool.query<{ current_schema: string | null }>( - 'SELECT current_schema() AS current_schema' - ); - if (schemaRows[0]?.current_schema !== schema) { - throw new Error( - `Isolated fixture pool expected current_schema()=${schema}, got ${String(schemaRows[0]?.current_schema)}` - ); - } - - 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' }); - await seedFixture(pool); - - return { admin, pool, schema }; -} - -async function seedFixture(pool: Pool): Promise { - const client = await pool.connect(); - try { - await client.query('BEGIN'); - - await client.query(` - INSERT INTO exchange (mic, operating_mic, name, country_iso, currency, timezone, calendar_code, board_lot_policy) - VALUES - ('XNAS', 'XNAS', 'NASDAQ', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'), - ('XNYS', 'XNYS', 'NYSE', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'), - ('XTSE', 'XTSE', 'TSX', 'CA', 'CAD', 'America/Toronto', 'XTSE', 'tsx_tiered') - ON CONFLICT (mic) DO NOTHING - `); - - await client.query(` - INSERT INTO instrument (instrument_id, primary_isin, canonical_name, security_type, issuer_country) - OVERRIDING SYSTEM VALUE - VALUES - (101, 'CA1010000001', 'Alpha Oldco Canada', 'common', 'CA'), - (102, 'US1020000002', 'Gap Rename Corp', 'common', 'US'), - (103, 'US1030000003', 'Stealth Future Ventures', 'common', 'US'), - (104, 'CA1040000004', 'No History Metals', 'common', 'CA'), - (105, 'US1050000005', 'Overlap Equity Inc', 'common', 'US'), - (106, 'US1060000006', 'Post Cutoff IPO Inc', 'common', 'US'), - (107, 'CA1070000007', 'Unknown Start Corp', 'common', 'CA'), - (108, 'US1080000008', 'Delist Boundary Co', 'common', 'US'), - (109, 'US1090000009', 'Delist Boundary Active', 'common', 'US'), - (110, 'US1100000010', 'Delist Boundary Unspecified', 'common', 'US'), - (111, 'US1110000011', 'Delist Boundary Future', 'common', 'US'), - (112, 'US1120000012', '100% Pure_Wild\\Co', 'common', 'US'), - (113, 'US1130000013', 'Second Oldco Group', 'common', 'US'), - (114, 'US1140000014', 'Renamed Holdings Inc', 'common', 'US') - `); - - await client.query(` - INSERT INTO listing ( - listing_id, instrument_id, mic, ticker_root, class_suffix, currency, - listed_from, listed_to, delist_reason - ) - OVERRIDING SYSTEM VALUE - VALUES - (101, 101, 'XTSE', 'ZOLD', '', 'CAD', '2020-01-01', '2024-06-28', 'active'), - (102, 102, 'XNYS', 'GAPNEW', '', 'USD', '2019-01-01', '2024-12-31', 'active'), - (103, 103, 'XNAS', 'FUTROOT', '', 'USD', '2020-01-01', NULL, NULL), - (104, 104, 'XTSE', 'NOHIST', 'A', 'CAD', '2021-03-15', '2024-06-28', 'active'), - (105, 105, 'XNYS', 'OVLP', '', 'USD', '2018-01-01', '2024-06-28', 'active'), - (106, 106, 'XNAS', 'IPO25', '', 'USD', '2024-07-01', NULL, 'active'), - (107, 107, 'XTSE', 'NULLSTART', '', 'CAD', NULL, NULL, NULL), - (108, 108, 'XNAS', 'DLST1', '', 'USD', '2015-01-01', '2024-06-30', 'merger_cash'), - (109, 109, 'XNAS', 'DLST2', '', 'USD', '2015-01-01', '2024-06-28', 'active'), - (110, 110, 'XNAS', 'DLST3', '', 'USD', '2015-01-01', '2024-06-28', NULL), - (111, 111, 'XNAS', 'DLST4', '', 'USD', '2015-01-01', '2024-09-15', 'bankruptcy_cancelled'), - (112, 112, 'XNYS', 'WILD', '', 'USD', '2020-01-01', '2024-06-28', 'active'), - (113, 113, 'XNAS', 'OLDCO2', '', 'USD', '2020-01-01', '2024-06-28', 'active'), - (114, 114, 'XNAS', 'NEWCO', '', 'USD', '2018-01-02', '2024-12-31', 'active') - `); - - await client.query(` - INSERT INTO listing_symbol_history (listing_id, ticker, valid_from, valid_to, source) - VALUES - (114, 'OLDCO', '2018-01-02', '2024-06-30', 'eod'), - (114, 'NEWCO', '2024-07-01', NULL, 'eod'), - (102, 'GAPOLD', '2019-01-01', '2024-05-31', 'eod'), - (102, 'GAPNEW', '2024-07-01', NULL, 'eod'), - (103, 'FUTROOT', '2024-07-15', NULL, 'eod'), - (105, 'OVLP1', '2018-01-01', NULL, 'eod'), - (105, 'OVLPZ', '2023-01-01', NULL, 'eod'), - (105, 'OVLPA', '2023-01-01', NULL, 'eod') - `); - - await client.query('COMMIT'); - } catch (err) { - await client.query('ROLLBACK'); - throw err; - } finally { - client.release(); - } -} - -describe('PostgreSQL symbol search safety guard', () => { - test('rejects unsafe database targets before connecting', () => { - expect(() => assertSafetyDatabaseUrl(undefined)).toThrow( - 'Dedicated stock_bot_safety database required' - ); - expect(() => - assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/trading_bot') - ).toThrow('Dedicated stock_bot_safety database required'); - expect(() => - assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5433/trading_bot_dev') - ).toThrow('Dedicated stock_bot_safety database required'); - expect( - assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test') - ).toBe('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test'); - }); - - test('preserves isolated schema search_path precedence over URL startup options', () => { - const schema = 'stock_bot_safety_fixture_options'; - const urlWithOptions = - 'postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test?options=-c%20statement_timeout%3D30000%20-c%20search_path%3Dpublic'; - const poolConfig = buildIsolatedPoolConfig(urlWithOptions, schema); - - expect(new URL(poolConfig.connectionString!).searchParams.has('options')).toBe(false); - - const client = new Client(poolConfig); - const resolvedOptions = (client as unknown as { connectionParameters: { options?: string } }) - .connectionParameters.options; - expect(resolvedOptions).toBe( - `-c statement_timeout=30000 -c search_path=public -c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000` - ); - }); -}); - -describe.skipIf(!url)('PostgreSQL MCP symbol search adapter', () => { - test('enforces as-of-cutoff ticker resolution, root suppression, and listed_from bounds', async () => { - const f = await createIsolatedFixture(); - const port = createPostgresSymbolSearchPort({ executor: createPgExecutor(f.pool) }); - - // (a)/(g) Post-cutoff rename: OLDCO is valid on 2024-06-30; NEWCO starts 2024-07-01 and is invisible even as ticker_root - const oldcoRows = await port.searchSymbols({ - query: 'OLDCO', - limit: 1, - includeDelisted: true, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - expect(oldcoRows.map(r => r.listingId)).toEqual([101, 113, 114]); - expect(oldcoRows[2]).toEqual({ - listingId: 114, - instrumentId: 114, - ticker: 'OLDCO', - classSuffix: null, - name: 'Renamed Holdings Inc', - mic: 'XNAS', - currency: 'USD', - isin: 'US1140000014', - firstBarDate: '2018-01-02', - lastBarDate: '2024-12-31', - delistedAt: null, - }); - - const newcoRows = await port.searchSymbols({ - query: 'NEWCO', - limit: 20, - includeDelisted: true, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - expect(newcoRows).toEqual([]); - - // Expired-but-known fallback (step 3c): GAPNEW is future-only root, falls back to GAPOLD - const gapOldRows = await port.searchSymbols({ - query: 'GAPOLD', - limit: 20, - includeDelisted: true, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - expect(gapOldRows.map(r => ({ id: r.listingId, ticker: r.ticker }))).toEqual([ - { id: 102, ticker: 'GAPOLD' }, - ]); - const gapNewRows = await port.searchSymbols({ - query: 'GAPNEW', - limit: 20, - includeDelisted: true, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - expect(gapNewRows).toEqual([]); - - // (h) Future-only root with no prior history: excluded by root, name, and ISIN searches - expect( - await port.searchSymbols({ - query: 'FUTROOT', - limit: 20, - includeDelisted: true, - vaultCutoffTs: VAULT_CUTOFF_TS, - }) - ).toEqual([]); - expect( - await port.searchSymbols({ - query: 'Stealth Future', - limit: 20, - includeDelisted: true, - vaultCutoffTs: VAULT_CUTOFF_TS, - }) - ).toEqual([]); - expect( - await port.searchSymbols({ - query: 'US1030000003', - limit: 20, - includeDelisted: true, - vaultCutoffTs: VAULT_CUTOFF_TS, - }) - ).toEqual([]); - - // (i) No history rows at all: falls back to ticker_root - const noHistRows = await port.searchSymbols({ - query: 'NOHIST', - limit: 20, - includeDelisted: true, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - expect(noHistRows).toEqual([ - { - listingId: 104, - instrumentId: 104, - ticker: 'NOHIST', - classSuffix: 'A', - name: 'No History Metals', - mic: 'XTSE', - currency: 'CAD', - isin: 'CA1040000004', - firstBarDate: '2021-03-15', - lastBarDate: '2024-06-28', - delistedAt: null, - }, - ]); - - // Overlapping valid history: latest valid_from wins, tie-breaking by ticker ASC (OVLPA < OVLPZ) - const overlapRows = await port.searchSymbols({ - query: 'Overlap Equity', - limit: 20, - includeDelisted: true, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - expect(overlapRows).toHaveLength(1); - expect(overlapRows[0]!.listingId).toBe(105); - expect(overlapRows[0]!.ticker).toBe('OVLPA'); - - // (b) listed_from > cutoff excluded - expect( - await port.searchSymbols({ - query: 'IPO25', - limit: 20, - includeDelisted: true, - vaultCutoffTs: VAULT_CUTOFF_TS, - }) - ).toEqual([]); - - // (c) listed_from IS NULL included - const nullStartRows = await port.searchSymbols({ - query: 'NULLSTART', - limit: 20, - includeDelisted: true, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - expect(nullStartRows).toHaveLength(1); - expect(nullStartRows[0]!.listingId).toBe(107); - expect(nullStartRows[0]!.firstBarDate).toBeNull(); - expect(nullStartRows[0]!.lastBarDate).toBeNull(); - expect(nullStartRows[0]!.delistedAt).toBeNull(); - }); - - test('supports country filter, case-insensitive exact ISIN, literal wildcards, delisting semantics, explicit schema, and deterministic ordering', async () => { - const f = await createIsolatedFixture(); - // Use admin pool (default search_path) with explicit schema option to verify schema quoting - const port = createPostgresSymbolSearchPort({ - executor: createPgExecutor(f.admin), - schema: f.schema, - }); - - // (d) country: 'CA' returns only CA-venue listings - const caRows = await port.searchSymbols({ - query: 'OLDCO', - limit: 20, - country: 'CA', - includeDelisted: true, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - expect(caRows.map(r => ({ id: r.listingId, mic: r.mic }))).toEqual([{ id: 101, mic: 'XTSE' }]); - - // (e) Case-insensitive exact ISIN match with partial-ISIN negative - const isinRows = await port.searchSymbols({ - query: 'ca1040000004', - limit: 20, - includeDelisted: true, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - expect(isinRows.map(r => r.listingId)).toEqual([104]); - - const partialIsinRows = await port.searchSymbols({ - query: 'CA104000', - limit: 20, - includeDelisted: true, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - expect(partialIsinRows).toEqual([]); - - // Literal wildcard matching: %, _, and \ are escaped - const wildRows = await port.searchSymbols({ - query: '100% Pure_Wild\\', - limit: 20, - includeDelisted: true, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - expect(wildRows.map(r => r.listingId)).toEqual([112]); - - // Delisting boundary: 108 confirmed delisted on cutoff (2024-06-30), 109 active, 110 null reason, 111 future delist (2024-09-15) - const allDelist = await port.searchSymbols({ - query: 'Delist Boundary', - limit: 1, - includeDelisted: true, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - expect(allDelist.map(r => ({ id: r.listingId, delistedAt: r.delistedAt }))).toEqual([ - { id: 108, delistedAt: '2024-06-30' }, - { id: 109, delistedAt: null }, - { id: 110, delistedAt: null }, - { id: 111, delistedAt: '2024-09-15' }, - ]); - - const activeAsOfCutoff = await port.searchSymbols({ - query: 'Delist Boundary', - limit: 20, - includeDelisted: false, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - expect(activeAsOfCutoff.map(r => r.listingId)).toEqual([109, 110, 111]); - - // Repeated pinned query produces identical deterministic rows - const repeat = await port.searchSymbols({ - query: 'Delist Boundary', - limit: 1, - includeDelisted: true, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - expect(repeat).toEqual(allDelist); - }); - - test('composes with createSearchSymbolsTool through MCP for ranking, truncation, clamping, and future delisting masking', async () => { - const f = await createIsolatedFixture(); - const port = createPostgresSymbolSearchPort({ executor: createPgExecutor(f.pool) }); - - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createSearchSymbolsTool({ - port, - vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, - }), - ], - }); - - const callTool = async (args: Record): Promise => { - const raw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 'mcp-pg-1', - method: 'tools/call', - params: { - name: 'search_symbols', - arguments: args, - }, - }) - ); - expect(raw).not.toBeNull(); - const parsed = JSON.parse(raw!) as { - result: { isError?: boolean; content: Array<{ text: string }> }; - }; - expect(parsed.result.isError).toBeUndefined(); - return JSON.parse(parsed.result.content[0]!.text) as SearchSymbolsResultPayload; - }; - - // Ranking & truncation: adapter returns ascending listing_id [101 (name), 113 (prefix), 114 (exact)]; - // MCP tool must re-rank to exact ticker OLDCO (114) > prefix OLDCO2 (113) and drop name match ZOLD (101) - const oldcoPayload = await callTool({ query: 'OLDCO', limit: 2 }); - expect(oldcoPayload.scope).toBe('vault_fenced'); - expect(oldcoPayload.vaultCutoffTs).toBe(VAULT_CUTOFF_TS); - expect(oldcoPayload.truncated).toBe(true); - expect(oldcoPayload.rowCount).toBe(2); - expect(oldcoPayload.rows.map(r => ({ id: r.listingId, ticker: r.ticker }))).toEqual([ - { id: 114, ticker: 'OLDCO' }, - { id: 113, ticker: 'OLDCO2' }, - ]); - // Post-cutoff lastBarDate (2024-12-31) is clamped to vaultCutoffDate (2024-06-30) - expect(oldcoPayload.rows[0]!.lastBarDate).toBe(VAULT_CUTOFF_DATE); - - // Future delisting (111: listed_to=2024-09-15, delist_reason=bankruptcy_cancelled) is masked to null and clamped - const futureDelistPayload = await callTool({ - query: 'DLST4', - includeDelisted: false, - }); - expect(futureDelistPayload.rowCount).toBe(1); - expect(futureDelistPayload.rows[0]!.listingId).toBe(111); - expect(futureDelistPayload.rows[0]!.lastBarDate).toBe(VAULT_CUTOFF_DATE); - expect(futureDelistPayload.rows[0]!.delistedAt).toBeNull(); - }); - - test('moves as-of resolution with the cutoff date, including a near-midnight UTC instant', async () => { - const f = await createIsolatedFixture(); - const port = createPostgresSymbolSearchPort({ executor: createPgExecutor(f.pool) }); - const search = (query: string, vaultCutoffTs: number, includeDelisted = true) => - port.searchSymbols({ query, limit: 20, includeDelisted, vaultCutoffTs }); - const lastMsOfCutoffDay = Date.UTC(2024, 5, 30, 23, 59, 59, 999); - const dayAfterCutoff = Date.UTC(2024, 6, 1, 0, 0, 0, 0); - - // Last millisecond of 2024-06-30 UTC still resolves the pre-rename ticker. - const lateOld = await search('OLDCO', lastMsOfCutoffDay); - expect(lateOld.map(r => ({ id: r.listingId, ticker: r.ticker }))).toEqual([ - { id: 101, ticker: 'ZOLD' }, - { id: 113, ticker: 'OLDCO2' }, - { id: 114, ticker: 'OLDCO' }, - ]); - expect(await search('NEWCO', lastMsOfCutoffDay)).toEqual([]); - - // One day later the rename, the GAPNEW start and the IPO become visible, and OLDCO no longer resolves to 114. - const nextOld = await search('OLDCO', dayAfterCutoff); - expect(nextOld.map(r => r.listingId)).toEqual([101, 113]); - const nextNew = await search('NEWCO', dayAfterCutoff); - expect(nextNew.map(r => ({ id: r.listingId, ticker: r.ticker }))).toEqual([ - { id: 114, ticker: 'NEWCO' }, - ]); - const nextGap = await search('GAPNEW', dayAfterCutoff); - expect(nextGap.map(r => ({ id: r.listingId, ticker: r.ticker }))).toEqual([ - { id: 102, ticker: 'GAPNEW' }, - ]); - expect(await search('GAPOLD', dayAfterCutoff)).toEqual([]); - expect((await search('IPO25', dayAfterCutoff)).map(r => r.listingId)).toEqual([106]); - - // A cutoff on the future delisting date makes that delisting confirmed and filterable. - const onFutureDelist = await search('Delist Boundary', Date.UTC(2024, 8, 15), false); - expect(onFutureDelist.map(r => r.listingId)).toEqual([109, 110]); - }); - - test('projects identical calendar dates regardless of the session TimeZone', async () => { - const f = await createIsolatedFixture(); - const client = await f.pool.connect(); - try { - await client.query("SET TimeZone = 'Pacific/Kiritimati'"); - const executor: SymbolSearchExecutor = { - query>(text: string, params?: readonly unknown[]) { - return client.query( - text, - params === undefined ? undefined : [...params] - ) as unknown as Promise<{ - readonly rows: readonly Row[]; - }>; - }, - }; - const port = createPostgresSymbolSearchPort({ executor }); - - const rows = await port.searchSymbols({ - query: 'Delist Boundary', - limit: 20, - includeDelisted: true, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - - expect( - rows.map(r => ({ - id: r.listingId, - first: r.firstBarDate, - last: r.lastBarDate, - delistedAt: r.delistedAt, - })) - ).toEqual([ - { id: 108, first: '2015-01-01', last: '2024-06-30', delistedAt: '2024-06-30' }, - { id: 109, first: '2015-01-01', last: '2024-06-28', delistedAt: null }, - { id: 110, first: '2015-01-01', last: '2024-06-28', delistedAt: null }, - { id: 111, first: '2015-01-01', last: '2024-09-15', delistedAt: '2024-09-15' }, - ]); - } finally { - await client.query('RESET TimeZone'); - client.release(); - } - }); - - test('isolates fixture schema even when the safety database URL includes startup options', async () => { - const parsed = new URL(assertSafetyDatabaseUrl(url)); - parsed.searchParams.set('options', '-c statement_timeout=30000 -c search_path=public'); - - const f = await createIsolatedFixture(parsed.toString()); - const { rows } = await f.pool.query<{ current_schema: string | null }>( - 'SELECT current_schema() AS current_schema' - ); - expect(rows[0]?.current_schema).toBe(f.schema); - - const port = createPostgresSymbolSearchPort({ executor: createPgExecutor(f.pool) }); - const matches = await port.searchSymbols({ - query: 'OLDCO', - limit: 20, - includeDelisted: true, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - expect(matches.map(r => r.listingId)).toEqual([101, 113, 114]); - }); -}); diff --git a/test/postgres/mcp-trial-ref-adapter.test.ts b/test/postgres/mcp-trial-ref-adapter.test.ts deleted file mode 100644 index 2a91334f..00000000 --- a/test/postgres/mcp-trial-ref-adapter.test.ts +++ /dev/null @@ -1,484 +0,0 @@ -import { randomUUID } from 'node:crypto'; -import { readFileSync } from 'node:fs'; -import { fileURLToPath } from 'node:url'; -import { afterEach, describe, expect, test } from 'bun:test'; -import { Client, Pool, type PoolClient, type PoolConfig } from 'pg'; -import { getLogger, setLoggerConfig } from '@stock-bot/logger'; -import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres'; -import { - type AppendFindingResult, - FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF, - type FileFindingResultPayload, - type FiledFindingRecord, - type TrialRefExecutor, - createFileFindingTool, - createMcpServer, - createPostgresFindingWritePort, - createPostgresTrialRefLookupPort, -} from '../../libs/research/src/mcp/index'; - -setLoggerConfig({ logLevel: 'fatal', logConsole: false }); -const logger = getLogger('mcp-trial-ref-adapter-pg-test'); -const url = process.env.PIPELINE_TEST_DATABASE_URL; -const initDir = fileURLToPath(new URL('../../database/postgres/init/', import.meta.url)); - -// Vault cutoff date 2025-06-30 (exclusive): sample_end must be < 2025-06-30 to be research-visible. -const VAULT_CUTOFF_TS = Date.UTC(2025, 5, 30, 0, 0, 0, 0); -const FIXED_TS = '2026-01-15T12:34:56.789Z'; -const MAX_BIGINT_REF = '9223372036854775807'; -// 2^53 + 1 is not representable as a JS number; Number('9007199254740993') === 9007199254740992. -const ABOVE_SAFE_INT_REF = '9007199254740993'; -const ABOVE_SAFE_INT_NEIGHBOR_REF = '9007199254740992'; - -const cleanup: (() => Promise | void)[] = []; -afterEach(async () => { - // Run every cleanup step even if an earlier one fails, then surface the first failure. - let firstError: unknown; - for (const close of cleanup.splice(0).reverse()) { - try { - await close(); - } catch (err) { - firstError ??= err; - } - } - if (firstError !== undefined) { - throw firstError; - } -}); - -function assertSafetyDatabaseUrl(connectionString: string | undefined): string { - if (!connectionString) { - throw new Error('Dedicated stock_bot_safety database required'); - } - let parsed: URL; - try { - parsed = new URL(connectionString); - } catch { - throw new Error('Dedicated stock_bot_safety database required'); - } - if (parsed.protocol !== 'postgres:' && parsed.protocol !== 'postgresql:') { - throw new Error('Dedicated stock_bot_safety database required'); - } - const client = new Client({ connectionString }); - const effectiveDb = ( - client as unknown as { connectionParameters?: { database?: unknown } } - ).connectionParameters?.database; - if ( - typeof effectiveDb !== 'string' || - !effectiveDb.startsWith('stock_bot_safety') || - !parsed.pathname.startsWith('/stock_bot_safety') - ) { - throw new Error('Dedicated stock_bot_safety database required'); - } - return connectionString; -} - -function createPgExecutor( - queryable: Pick | Pick -): TrialRefExecutor { - return { - query>( - text: string, - params?: readonly unknown[] - ): Promise<{ readonly rows: readonly Row[] }> { - return queryable.query( - text, - params === undefined ? undefined : [...params] - ) as unknown as Promise<{ readonly rows: readonly Row[] }>; - }, - }; -} - -function buildIsolatedPoolConfig( - connectionString: string | undefined, - schema: string, - extraOptions?: string -): PoolConfig { - const safeUrl = assertSafetyDatabaseUrl(connectionString); - const parsed = new URL(safeUrl); - const existingOptions = parsed.searchParams - .getAll('options') - .map(value => value.trim()) - .filter(value => value.length > 0); - parsed.searchParams.delete('options'); - - const schemaOptions = extraOptions - ? `-c search_path=${schema} ${extraOptions}` - : `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`; - const options = [...existingOptions, schemaOptions].join(' '); - - return { - connectionString: parsed.toString(), - options, - }; -} - -async function createIsolatedFixture(connectionString: string | undefined = url) { - const safeUrl = assertSafetyDatabaseUrl(connectionString); - const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`; - const admin = new Pool({ connectionString: safeUrl }); - // Registered before CREATE SCHEMA so the admin pool closes even if creation or teardown fails. - cleanup.push(() => admin.end()); - await admin.query(`CREATE SCHEMA ${schema}`); - cleanup.push(() => admin.query(`DROP SCHEMA ${schema} CASCADE`).then(() => undefined)); - const pool = new Pool(buildIsolatedPoolConfig(safeUrl, schema)); - cleanup.push(() => pool.end()); - const readOnlyPool = new Pool( - buildIsolatedPoolConfig( - safeUrl, - schema, - '-c default_transaction_read_only=on -c statement_timeout=5000' - ) - ); - cleanup.push(() => readOnlyPool.end()); - - const { rows: schemaRows } = await pool.query<{ current_schema: string | null }>( - 'SELECT current_schema() AS current_schema' - ); - if (schemaRows[0]?.current_schema !== schema) { - throw new Error( - `Isolated fixture pool expected current_schema()=${schema}, got ${String(schemaRows[0]?.current_schema)}` - ); - } - - // 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' }); - await seedTrials(pool); - - return { admin, pool, readOnlyPool, schema }; -} - -async function seedTrials(pool: Pool): Promise { - const trials: readonly (readonly [string, string])[] = [ - ['1', '2025-06-29'], // last research-visible day - ['2', '2025-06-30'], // sample_end == cutoff: Vault-only - ['3', '2025-07-15'], // sample_end after cutoff: Vault-only - [ABOVE_SAFE_INT_REF, '2024-01-31'], - [MAX_BIGINT_REF, '2020-01-31'], - ]; - for (const [trialId, sampleEnd] of trials) { - await pool.query( - `INSERT INTO trial_ledger ( - trial_id, principal_id, stage, universe_market, horizon_bucket, expression_hash, - sample_start, sample_end, n_obs, sharpe_unann, skewness, kurtosis, daily_series - ) - OVERRIDING SYSTEM VALUE - VALUES ($1::bigint, 'operator', 'signal_ic', 'US_EQ', 'swing_1_10d', repeat('a', 64), - '2020-01-01'::date, $2::date, 2, 0, 0, 3, ARRAY[0.1, 0.2]::real[])`, - [trialId, sampleEnd] - ); - } -} - -describe('PostgreSQL trial-ref adapter safety guard', () => { - test('rejects unsafe database targets before connecting', () => { - expect(() => assertSafetyDatabaseUrl(undefined)).toThrow( - 'Dedicated stock_bot_safety database required' - ); - expect(() => - assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/trading_bot') - ).toThrow('Dedicated stock_bot_safety database required'); - expect(() => - assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5433/trading_bot_dev') - ).toThrow('Dedicated stock_bot_safety database required'); - expect(() => - assertSafetyDatabaseUrl('socket:/stock_bot_safety?db=trading_bot') - ).toThrow('Dedicated stock_bot_safety database required'); - expect(() => - assertSafetyDatabaseUrl('http://127.0.0.1:5432/stock_bot_safety_test') - ).toThrow('Dedicated stock_bot_safety database required'); - expect(() => assertSafetyDatabaseUrl('not-a-valid-url')).toThrow( - 'Dedicated stock_bot_safety database required' - ); - expect( - assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test') - ).toBe('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test'); - }); - - test('preserves isolated schema search_path precedence over URL startup options', () => { - const schema = 'stock_bot_safety_trial_ref_options'; - const urlWithOptions = - 'postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test?options=-c%20statement_timeout%3D30000%20-c%20search_path%3Dpublic'; - const poolConfig = buildIsolatedPoolConfig(urlWithOptions, schema); - - expect(new URL(poolConfig.connectionString!).searchParams.has('options')).toBe(false); - - const client = new Client(poolConfig); - const resolvedOptions = (client as unknown as { connectionParameters: { options?: string } }) - .connectionParameters.options; - expect(resolvedOptions).toBe( - `-c statement_timeout=30000 -c search_path=public -c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000` - ); - }); -}); - -describe.skipIf(!url)('PostgreSQL MCP trial-ref lookup adapter', () => { - test('exposes only trials with sample_end strictly before the UTC Vault cutoff date', async () => { - const f = await createIsolatedFixture(); - const port = createPostgresTrialRefLookupPort({ - executor: createPgExecutor(f.pool), - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - - expect(await port.hasResearchVisibleTrial('1')).toBe(true); - expect(await port.hasResearchVisibleTrial('2')).toBe(false); - expect(await port.hasResearchVisibleTrial('3')).toBe(false); - expect(await port.hasResearchVisibleTrial('4')).toBe(false); // unknown - expect(await port.hasResearchVisibleTrial(MAX_BIGINT_REF)).toBe(true); - }); - - test('matches BIGINT ids above 2^53 exactly without numeric coercion', async () => { - const f = await createIsolatedFixture(); - const port = createPostgresTrialRefLookupPort({ - executor: createPgExecutor(f.pool), - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - - expect(await port.hasResearchVisibleTrial(ABOVE_SAFE_INT_REF)).toBe(true); - expect(await port.hasResearchVisibleTrial(ABOVE_SAFE_INT_NEIGHBOR_REF)).toBe(false); - }); - - test('moves the visibility boundary with the cutoff date, including a near-midnight UTC instant', async () => { - const f = await createIsolatedFixture(); - const executor = createPgExecutor(f.pool); - const lastMsOfCutoffDay = createPostgresTrialRefLookupPort({ - executor, - vaultCutoffTs: Date.UTC(2025, 5, 30, 23, 59, 59, 999), - }); - const nextDay = createPostgresTrialRefLookupPort({ - executor, - vaultCutoffTs: Date.UTC(2025, 6, 1, 0, 0, 0, 0), - }); - - expect(await lastMsOfCutoffDay.hasResearchVisibleTrial('2')).toBe(false); - expect(await nextDay.hasResearchVisibleTrial('2')).toBe(true); - expect(await nextDay.hasResearchVisibleTrial('3')).toBe(false); - }); - - test('runs in a read-only session and is unaffected by the session TimeZone', async () => { - const f = await createIsolatedFixture(); - const client = await f.readOnlyPool.connect(); - try { - await client.query("SET TimeZone = 'Pacific/Kiritimati'"); - const port = createPostgresTrialRefLookupPort({ - executor: createPgExecutor(client), - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - - expect(await port.hasResearchVisibleTrial('1')).toBe(true); - expect(await port.hasResearchVisibleTrial('2')).toBe(false); - } finally { - await client.query('RESET TimeZone'); - client.release(); - } - }); - - test('qualifies trial_ledger with an explicit schema when the session search_path does not include it', async () => { - const f = await createIsolatedFixture(); - const client = await f.admin.connect(); - try { - // Pin a search_path that cannot contain trial_ledger, independent of the shared public schema. - await client.query('SET search_path TO pg_catalog'); - const unqualified = createPostgresTrialRefLookupPort({ - executor: createPgExecutor(client), - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - const qualified = createPostgresTrialRefLookupPort({ - executor: createPgExecutor(client), - vaultCutoffTs: VAULT_CUTOFF_TS, - schema: f.schema, - }); - - expect(await qualified.hasResearchVisibleTrial('1')).toBe(true); - expect(await qualified.hasResearchVisibleTrial('2')).toBe(false); - // Missing relation must surface as a rejection, never as "not visible". - await expect(unqualified.hasResearchVisibleTrial('1')).rejects.toMatchObject({ - code: '42P01', - }); - } finally { - await client.query('RESET search_path'); - client.release(); - } - }); - - test('leaves trial_ledger untouched and never executes an injection-shaped ref', async () => { - const f = await createIsolatedFixture(); - const port = createPostgresTrialRefLookupPort({ - executor: createPgExecutor(f.pool), - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - - expect(await port.hasResearchVisibleTrial('1 OR 1=1')).toBe(false); - expect(await port.hasResearchVisibleTrial("1'; DELETE FROM trial_ledger; --")).toBe(false); - - const { rows } = await f.pool.query<{ n: string }>('SELECT count(*)::text AS n FROM trial_ledger'); - expect(rows[0]!.n).toBe('5'); - }); - - test('files through createFileFindingTool only when every trial ref is research-visible', async () => { - const f = await createIsolatedFixture(); - const trialLookup = createPostgresTrialRefLookupPort({ - executor: createPgExecutor(f.pool), - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - const appended: FiledFindingRecord[] = []; - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createFileFindingTool({ - port: { - async appendFinding(record: FiledFindingRecord): Promise { - appended.push(record); - return { status: 'created', id: record.id, createdAt: record.createdAt }; - }, - }, - trialLookup, - newId: () => 'finding-pg-0001', - now: () => Date.UTC(2025, 5, 29, 12, 0, 0, 0), - }), - ], - }); - - const call = async (trialRefs: readonly string[]) => { - const raw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 1, - method: 'tools/call', - params: { - name: 'file_finding', - arguments: { - kind: 'finding', - title: 'Pre-vault signal', - summary: 'Research-visible evidence only.', - trialRefs, - }, - }, - }) - ); - return (JSON.parse(raw!) as { result: { isError?: boolean; content: { text: string }[] } }) - .result; - }; - - const mixed = await call(['1', '2']); - expect(mixed.isError).toBe(true); - expect(mixed.content[0]!.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF); - expect(appended).toHaveLength(0); - - const visible = await call(['1', MAX_BIGINT_REF]); - expect(visible.isError).toBeUndefined(); - expect(appended).toHaveLength(1); - expect(appended[0]!.trialRefs).toEqual(['1', MAX_BIGINT_REF]); - }); - - test('composes with createFileFindingTool and createPostgresFindingWritePort through MCP', async () => { - const f = await createIsolatedFixture(); - const executor = createPgExecutor(f.pool); - const trialLookup = createPostgresTrialRefLookupPort({ - executor, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - const writePort = createPostgresFindingWritePort({ executor }); - - let idSeq = 0; - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createFileFindingTool({ - port: writePort, - trialLookup, - newId: () => { - idSeq += 1; - return `finding-trial-ref-${idSeq}`; - }, - now: () => new Date(FIXED_TS), - }), - ], - }); - - const callFileFinding = async (args: Record) => { - const raw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 'req-file-finding', - method: 'tools/call', - params: { - name: 'file_finding', - arguments: args, - }, - }) - ); - expect(raw).not.toBeNull(); - const parsed = JSON.parse(raw!) as { - result: { isError?: boolean; content: Array<{ text: string }> }; - }; - return parsed.result; - }; - - // Visible trial (sample_end = 2025-06-29 < 2025-06-30) succeeds and persists pending_review row. - const okRes = await callFileFinding({ - kind: 'finding', - title: 'Pre-cutoff signal holds across US equities', - summary: 'Positive IC verified strictly before the Vault cutoff.', - trialRefs: ['1'], - evidenceRefs: ['snap:2025-06-29:ic'], - }); - expect(okRes.isError).toBeUndefined(); - const receipt = JSON.parse(okRes.content[0]!.text) as FileFindingResultPayload; - expect(receipt).toEqual({ - id: 'finding-trial-ref-1', - createdAt: FIXED_TS, - created: true, - }); - - const storedRows = ( - await f.pool.query<{ id: string; status: string; trial_refs: string[] }>( - 'SELECT id, status, trial_refs FROM findings ORDER BY id ASC' - ) - ).rows; - expect(storedRows).toEqual([ - { - id: 'finding-trial-ref-1', - status: 'pending_review', - trial_refs: ['1'], - }, - ]); - - // Vault-only (equal to cutoff, after cutoff) and unknown citations all return the same error with zero rows added. - for (const deniedRef of ['2', '3', '999999999']) { - const deniedRes = await callFileFinding({ - kind: 'dead_end', - title: 'Should be rejected by Vault fence', - summary: 'References non-visible trial.', - trialRefs: [deniedRef], - }); - expect(deniedRes.isError).toBe(true); - expect(deniedRes.content[0]!.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF); - } - - const totalFindings = ( - await f.pool.query<{ c: number }>('SELECT count(*)::int AS c FROM findings') - ).rows[0]?.c; - expect(totalFindings).toBe(1); - }); -}); diff --git a/test/postgres/migration-runner.test.ts b/test/postgres/migration-runner.test.ts index 0e87eebb..6b43c3d3 100644 --- a/test/postgres/migration-runner.test.ts +++ b/test/postgres/migration-runner.test.ts @@ -37,7 +37,6 @@ const migrations = [ '32-candidate-parameter-defaults.sql', '33-candidate-decimal-normalization.sql', '36-trial-ledger.sql', - '37-research-findings.sql', ]; const cleanup: (() => Promise)[] = []; afterEach(async () => { @@ -385,22 +384,17 @@ describe.skipIf(!url)('startup migrations on real PostgreSQL', () => { ]; // 1. research track must NOT apply 34-security-master.sql or 35-security-master-exchange-seed.sql, - // and MUST apply 36-trial-ledger.sql and 37-research-findings.sql; master track applies 34-35 (not 36-37) and is idempotent on re-run. + // and MUST apply 36-trial-ledger.sql; master track applies 34-35 (not 36) and is idempotent on re-run. const f1 = await fixture(); const runner1 = f1.startup(); const researchApplied = await runner1.runTrack('research'); expect(researchApplied).not.toContain('34-security-master.sql'); expect(researchApplied).not.toContain('35-security-master-exchange-seed.sql'); expect(researchApplied).toContain('36-trial-ledger.sql'); - expect(researchApplied).toContain('37-research-findings.sql'); - expect(researchApplied.indexOf('37-research-findings.sql')).toBe( - researchApplied.indexOf('36-trial-ledger.sql') + 1 - ); const recordedAfterResearch = await f1.recorded(); expect(recordedAfterResearch).not.toContain('34-security-master.sql'); expect(recordedAfterResearch).not.toContain('35-security-master-exchange-seed.sql'); expect(recordedAfterResearch).toContain('36-trial-ledger.sql'); - expect(recordedAfterResearch).toContain('37-research-findings.sql'); const tablesAfterResearch = new Set(await f1.relations()); for (const table of securityMasterTables) { @@ -408,14 +402,11 @@ describe.skipIf(!url)('startup migrations on real PostgreSQL', () => { } expect(tablesAfterResearch.has('trial_ledger')).toBe(true); expect(tablesAfterResearch.has('vault_evaluations')).toBe(true); - expect(tablesAfterResearch.has('findings')).toBe(true); - expect(tablesAfterResearch.has('provider_caveats')).toBe(true); const masterApplied = await runner1.runTrack('master'); expect(masterApplied).toContain('34-security-master.sql'); expect(masterApplied).toContain('35-security-master-exchange-seed.sql'); expect(masterApplied).not.toContain('36-trial-ledger.sql'); - expect(masterApplied).not.toContain('37-research-findings.sql'); expect(masterApplied.indexOf('35-security-master-exchange-seed.sql')).toBe( masterApplied.indexOf('34-security-master.sql') + 1 ); @@ -430,7 +421,7 @@ describe.skipIf(!url)('startup migrations on real PostgreSQL', () => { expect(await runner1.runTrack('master')).toEqual([]); - // 2. all track applies 34, 35, 36, and 37 alongside 01-05 and 09-33 and is idempotent. + // 2. all track applies 34, 35, and 36 alongside 01-05 and 09-33 and is idempotent. const f2 = await fixture(); const runner2 = f2.startup(); const allApplied = await runner2.runTrack('all'); @@ -441,12 +432,10 @@ describe.skipIf(!url)('startup migrations on real PostgreSQL', () => { expect(allApplied).toContain('34-security-master.sql'); expect(allApplied).toContain('35-security-master-exchange-seed.sql'); expect(allApplied).toContain('36-trial-ledger.sql'); - expect(allApplied).toContain('37-research-findings.sql'); const recordedAfterAll = await f2.recorded(); expect(recordedAfterAll).toContain('34-security-master.sql'); expect(recordedAfterAll).toContain('35-security-master-exchange-seed.sql'); expect(recordedAfterAll).toContain('36-trial-ledger.sql'); - expect(recordedAfterAll).toContain('37-research-findings.sql'); const tablesAfterAll = new Set(await f2.relations()); for (const table of securityMasterTables) { @@ -454,8 +443,6 @@ describe.skipIf(!url)('startup migrations on real PostgreSQL', () => { } expect(tablesAfterAll.has('trial_ledger')).toBe(true); expect(tablesAfterAll.has('vault_evaluations')).toBe(true); - expect(tablesAfterAll.has('findings')).toBe(true); - expect(tablesAfterAll.has('provider_caveats')).toBe(true); expect(await runner2.runTrack('all')).toEqual([]); }); diff --git a/test/postgres/research-findings-contract.test.ts b/test/postgres/research-findings-contract.test.ts deleted file mode 100644 index 36c9d2e3..00000000 --- a/test/postgres/research-findings-contract.test.ts +++ /dev/null @@ -1,180 +0,0 @@ -import { readFileSync } from 'node:fs'; -import { fileURLToPath } from 'node:url'; -import { describe, expect, test } from 'bun:test'; -import { setLoggerConfig } from '@stock-bot/logger'; -import { runPostgresMigrations, type MigrationTrack } from '@stock-bot/postgres'; -import { - FILE_FINDING_INITIAL_STATUS, - FILE_FINDING_KINDS, - FILE_FINDING_MAX_EVIDENCE_REFS, - FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH, - FILE_FINDING_MAX_REF_LENGTH, - FILE_FINDING_MAX_SUMMARY_LENGTH, - FILE_FINDING_MAX_TITLE_LENGTH, - FILE_FINDING_MAX_TRIAL_REFS, -} from '@stock-bot/research/mcp'; - -// Static contract checks for 37-research-findings.sql. No database needed, so these run in the -// sandbox as well as in Studio's unsandboxed run. They guard against drift between the SQL CHECKs, -// the MCP tool limits they mirror, and the design/DATA-CONTRACTS.md copy of the schema. - -setLoggerConfig({ logLevel: 'fatal', logConsole: false }); - -const initDir = fileURLToPath(new URL('../../database/postgres/init/', import.meta.url)); -const sqlPath = `${initDir}37-research-findings.sql`; -const docPath = fileURLToPath(new URL('../../design/DATA-CONTRACTS.md', import.meta.url)); - -const readSql = () => readFileSync(sqlPath, 'utf8'); -const readDoc = () => readFileSync(docPath, 'utf8'); - -function stripComments(sql: string): string { - return sql - .split('\n') - .map(line => line.replace(/--.*$/, '').trimEnd()) - .join('\n'); -} - -function normalize(sql: string): string { - return stripComments(sql).replace(/\s+/g, ' ').trim(); -} - -function tableBlock(sql: string, table: string): string { - const match = new RegExp(`CREATE TABLE IF NOT EXISTS ${table} \\(\\n([\\s\\S]*?)\\n\\);`).exec( - stripComments(sql) - ); - if (!match?.[1]) { - throw new Error(`CREATE TABLE ${table} not found`); - } - return match[1].replace(/\s+/g, ' ').trim(); -} - -function docSqlBlock(): string { - const doc = readDoc(); - const tableStart = doc.indexOf('CREATE TABLE IF NOT EXISTS findings ('); - expect(tableStart).toBeGreaterThan(-1); - const fenceStart = doc.lastIndexOf('```sql', tableStart); - const fenceEnd = doc.indexOf('```', tableStart); - return doc.slice(fenceStart + '```sql'.length, fenceEnd).trim(); -} - -function trimCodePointsFromSql(): number[] { - const match = /U&'([^']*)'/.exec(stripComments(readSql())); - if (!match?.[1]) { - throw new Error('research_trim_ecmascript U& character set not found'); - } - return match[1] - .split('\\') - .filter(part => part.length > 0) - .map(part => { - expect(part).toMatch(/^[0-9A-F]{4}$/i); - return Number.parseInt(part, 16); - }); -} - -async function filesForTrack(track: MigrationTrack): Promise { - const postgres = { - transaction: async (callback: (client: { query: (sql: string) => unknown }) => Promise) => - callback({ query: async () => ({ rows: [] }) }), - }; - return runPostgresMigrations(postgres as never, { track }); -} - -describe('37-research-findings.sql static contract', () => { - test('creates exactly findings and provider_caveats with IF NOT EXISTS and no schema qualifiers', () => { - const sql = stripComments(readSql()); - const created = [...sql.matchAll(/CREATE TABLE\s+(IF NOT EXISTS\s+)?("?[\w.]+"?)/g)]; - expect(created.map(m => m[2])).toEqual(['findings', 'provider_caveats']); - expect(created.every(m => m[1] !== undefined)).toBe(true); - expect(sql).not.toMatch(/CREATE\s+DATABASE/i); - expect(sql).not.toMatch(/^\s*\\c\b/m); - expect(sql).not.toMatch(/\bSET\s+search_path\b/i); - expect(sql).not.toMatch(/\b(?:TABLE|EXISTS|ON|FROM)\s+"?\w+"?\."?\w+/i); - }); - - test('findings CHECKs mirror the file_finding tool limits exported from file-finding.ts', () => { - const findings = tableBlock(readSql(), 'findings'); - const kinds = FILE_FINDING_KINDS.map(kind => `'${kind}'`).join(', '); - - expect(findings).toContain(`CHECK (kind IN (${kinds}))`); - expect(findings).toContain(`DEFAULT '${FILE_FINDING_INITIAL_STATUS}'`); - expect(findings).toContain( - `CHECK (char_length(research_trim_ecmascript(title)) BETWEEN 1 AND ${FILE_FINDING_MAX_TITLE_LENGTH})` - ); - expect(findings).toContain( - `CHECK (char_length(research_trim_ecmascript(summary)) BETWEEN 1 AND ${FILE_FINDING_MAX_SUMMARY_LENGTH})` - ); - expect(findings).toContain(`CHECK (cardinality(trial_refs) <= ${FILE_FINDING_MAX_TRIAL_REFS})`); - expect(findings).toContain( - `CHECK (cardinality(evidence_refs) <= ${FILE_FINDING_MAX_EVIDENCE_REFS})` - ); - expect(findings).toContain( - `CHECK (research_finding_refs_valid(trial_refs, ${FILE_FINDING_MAX_REF_LENGTH}))` - ); - expect(findings).toContain( - `CHECK (research_finding_refs_valid(evidence_refs, ${FILE_FINDING_MAX_REF_LENGTH}))` - ); - expect(findings).toContain( - `char_length(idempotency_key) BETWEEN 1 AND ${FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH}` - ); - expect(findings).toContain('created_at TIMESTAMPTZ NOT NULL,'); - expect(findings).toMatch(/idempotency_key TEXT CHECK \(idempotency_key IS NULL OR/); - }); - - test('research_trim_ecmascript strips exactly the BMP code points String.prototype.trim() strips', () => { - const sqlSet = trimCodePointsFromSql(); - const jsSet: number[] = []; - for (let cp = 0; cp <= 0xffff; cp++) { - if (cp >= 0xd800 && cp <= 0xdfff) { - continue; - } - if (String.fromCharCode(cp).trim() === '') { - jsSet.push(cp); - } - } - - expect(new Set(sqlSet).size).toBe(sqlSet.length); - expect([...sqlSet].sort((a, b) => a - b)).toEqual(jsSet); - expect(sqlSet).toHaveLength(25); - }); - - test('both tables are append-only via reject_research_evidence_mutation row and TRUNCATE triggers', () => { - const sql = normalize(readSql()); - for (const table of ['findings', 'provider_caveats']) { - expect(sql).toContain( - `DROP TRIGGER IF EXISTS ${table}_retained ON ${table}; CREATE TRIGGER ${table}_retained BEFORE UPDATE OR DELETE ON ${table} FOR EACH ROW EXECUTE FUNCTION reject_research_evidence_mutation();` - ); - expect(sql).toContain( - `DROP TRIGGER IF EXISTS ${table}_no_truncate ON ${table}; CREATE TRIGGER ${table}_no_truncate BEFORE TRUNCATE ON ${table} FOR EACH STATEMENT EXECUTE FUNCTION reject_research_evidence_mutation();` - ); - } - // The migration must reuse the shared function, never redefine it. - expect(sql).not.toMatch(/FUNCTION reject_research_evidence_mutation\s*\(\s*\)\s*RETURNS/i); - }); - - test('design/DATA-CONTRACTS.md documents both tables and indexes exactly as the migration creates them', () => { - const doc = docSqlBlock(); - const sql = readSql(); - expect(tableBlock(doc, 'findings')).toBe(tableBlock(sql, 'findings')); - expect(tableBlock(doc, 'provider_caveats')).toBe(tableBlock(sql, 'provider_caveats')); - - const indexes = (text: string) => - [...normalize(text).matchAll(/CREATE (?:UNIQUE )?INDEX IF NOT EXISTS [^;]+;/g)].map( - m => m[0] - ); - expect(indexes(doc)).toEqual(indexes(sql)); - expect(indexes(sql)).toHaveLength(3); - }); - - test('37-research-findings.sql runs on research and all tracks right after 36 and never on master', async () => { - const research = await filesForTrack('research'); - const all = await filesForTrack('all'); - const master = await filesForTrack('master'); - - expect(research.indexOf('37-research-findings.sql')).toBe( - research.indexOf('36-trial-ledger.sql') + 1 - ); - expect(research.indexOf('36-trial-ledger.sql')).toBeGreaterThan(-1); - expect(all).toContain('37-research-findings.sql'); - expect(master).not.toContain('37-research-findings.sql'); - }); -}); diff --git a/test/postgres/research-findings-schema.test.ts b/test/postgres/research-findings-schema.test.ts deleted file mode 100644 index 60324763..00000000 --- a/test/postgres/research-findings-schema.test.ts +++ /dev/null @@ -1,700 +0,0 @@ -import { randomUUID } from 'node:crypto'; -import { readFileSync } from 'node:fs'; -import { fileURLToPath } from 'node:url'; -import { afterEach, describe, expect, test } from 'bun:test'; -import { Pool } from 'pg'; -import { getLogger, setLoggerConfig } from '@stock-bot/logger'; -import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres'; - -setLoggerConfig({ logLevel: 'fatal', logConsole: false }); -const logger = getLogger('research-findings-schema-test'); -const url = process.env.PIPELINE_TEST_DATABASE_URL; -const initDir = fileURLToPath(new URL('../../database/postgres/init/', import.meta.url)); -const researchFindingsSqlPath = `${initDir}37-research-findings.sql`; - -const FIXED_TS = '2026-01-15T12:34:56.789Z'; -const EXPECTED_IMMUTABLE_MSG = /Retained research evidence cannot be rewritten or deleted/; - -const cleanup: (() => Promise | void)[] = []; -afterEach(async () => { - for (const close of cleanup.splice(0).reverse()) { - await close(); - } -}); - -async function createIsolatedFixture() { - if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { - throw new Error('Dedicated stock_bot_safety database required'); - } - const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`; - const admin = new Pool({ connectionString: url }); - await admin.query(`CREATE SCHEMA ${schema}`); - const poolUrl = new URL(url); - const existingOptions = poolUrl.searchParams.get('options')?.trim(); - const fixtureOptions = `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`; - poolUrl.searchParams.set( - 'options', - existingOptions ? `${existingOptions} ${fixtureOptions}` : fixtureOptions - ); - const pool = new Pool({ connectionString: poolUrl.toString() }); - cleanup.push(async () => { - await pool.end(); - await admin.query(`DROP SCHEMA ${schema} CASCADE`); - await admin.end(); - }); - - const activeSchema = (await pool.query<{ schema: string }>('SELECT current_schema() AS schema')) - .rows[0]?.schema; - if (activeSchema !== schema) { - throw new Error(`Expected active fixture schema ${schema}, got ${activeSchema ?? 'null'}`); - } - - // Bootstrap pre-additive tables needed by the research migration track. - for (const filename of [ - '06-create-backtest-tables.sql', - '07-fix-execution-time-type.sql', - '08-create-runs-table.sql', - ]) { - await pool.query(readFileSync(`${initDir}${filename}`, 'utf8')); - } - - const postgres = new PostgreSQLClient( - { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, - logger - ); - Object.defineProperty(postgres, 'connectionPool', { - get: () => ({ - connect: () => pool.connect(), - }), - }); - - await runPostgresMigrations(postgres, { track: 'research' }); - - return { pool, schema, postgres }; -} - -async function expectPgErrorCode( - operation: Promise, - expectedCode: string, - messagePattern?: RegExp -): Promise { - try { - await operation; - } catch (error) { - const pgError = error as { code?: string; message?: string } | null; - expect(pgError?.code).toBe(expectedCode); - if (messagePattern) { - expect(pgError?.message ?? '').toMatch(messagePattern); - } - return; - } - throw new Error(`Expected PostgreSQL error code ${expectedCode}, but query succeeded`); -} - -interface FindingInsertOverrides { - id?: string; - kind?: string; - title?: string; - summary?: string; - status?: string; - createdAt?: string; - trialRefs?: (string | null)[]; - evidenceRefs?: (string | null)[]; - idempotencyKey?: string | null; -} - -function insertFinding(pool: Pool, overrides: FindingInsertOverrides = {}) { - const id = overrides.id ?? `finding-${randomUUID()}`; - const kind = overrides.kind ?? 'finding'; - const title = overrides.title ?? 'Momentum factor decays after 5 sessions'; - const summary = overrides.summary ?? 'Cross-sectional rank IC turns negative past day 5.'; - const createdAt = overrides.createdAt ?? FIXED_TS; - const trialRefs = overrides.trialRefs ?? ['101', '102']; - const evidenceRefs = overrides.evidenceRefs ?? ['snap:2026-01-15:ic']; - const idempotencyKey = overrides.idempotencyKey === undefined ? null : overrides.idempotencyKey; - - if (overrides.status !== undefined) { - return pool.query( - `INSERT INTO findings ( - id, kind, title, summary, status, created_at, trial_refs, evidence_refs, idempotency_key - ) VALUES ($1, $2, $3, $4, $5, $6::timestamptz, $7::text[], $8::text[], $9) - RETURNING id, kind, title, summary, status, created_at, trial_refs, evidence_refs, idempotency_key`, - [ - id, - kind, - title, - summary, - overrides.status, - createdAt, - trialRefs, - evidenceRefs, - idempotencyKey, - ] - ); - } - - return pool.query( - `INSERT INTO findings ( - id, kind, title, summary, created_at, trial_refs, evidence_refs, idempotency_key - ) VALUES ($1, $2, $3, $4, $5::timestamptz, $6::text[], $7::text[], $8) - RETURNING id, kind, title, summary, status, created_at, trial_refs, evidence_refs, idempotency_key`, - [id, kind, title, summary, createdAt, trialRefs, evidenceRefs, idempotencyKey] - ); -} - -interface ProviderCaveatInsertOverrides { - id?: string; - provider?: string; - dataset?: string; - caveat?: string; - createdAt?: string; -} - -function insertProviderCaveat(pool: Pool, overrides: ProviderCaveatInsertOverrides = {}) { - const id = overrides.id ?? `caveat-${randomUUID()}`; - const provider = overrides.provider ?? 'EODHD'; - const dataset = overrides.dataset ?? 'eodIntraday1M'; - const caveat = - overrides.caveat ?? 'Intraday 1m OHLCV is retroactively split-adjusted; un-adjust before use.'; - - if (overrides.createdAt !== undefined) { - return pool.query( - `INSERT INTO provider_caveats (id, provider, dataset, caveat, created_at) - VALUES ($1, $2, $3, $4, $5::timestamptz) - RETURNING id, provider, dataset, caveat, created_at`, - [id, provider, dataset, caveat, overrides.createdAt] - ); - } - - return pool.query( - `INSERT INTO provider_caveats (id, provider, dataset, caveat) - VALUES ($1, $2, $3, $4) - RETURNING id, provider, dataset, caveat, created_at`, - [id, provider, dataset, caveat] - ); -} - -interface ProtectionTriggerRow { - relname: string; - tgname: string; - proname: string; - tgenabled: string; -} - -const EXPECTED_PROTECTION_TRIGGERS: ProtectionTriggerRow[] = [ - { - relname: 'findings', - tgname: 'findings_no_truncate', - proname: 'reject_research_evidence_mutation', - tgenabled: 'O', - }, - { - relname: 'findings', - tgname: 'findings_retained', - proname: 'reject_research_evidence_mutation', - tgenabled: 'O', - }, - { - relname: 'provider_caveats', - tgname: 'provider_caveats_no_truncate', - proname: 'reject_research_evidence_mutation', - tgenabled: 'O', - }, - { - relname: 'provider_caveats', - tgname: 'provider_caveats_retained', - proname: 'reject_research_evidence_mutation', - tgenabled: 'O', - }, -]; - -async function listProtectionTriggers(pool: Pool, schema: string): Promise { - const result = await pool.query( - `SELECT c.relname, t.tgname, p.proname, t.tgenabled::text AS tgenabled - FROM pg_trigger t - JOIN pg_class c ON c.oid = t.tgrelid - JOIN pg_namespace n ON n.oid = c.relnamespace - JOIN pg_proc p ON p.oid = t.tgfoid - WHERE NOT t.tgisinternal - AND n.nspname = $1 - AND c.relname IN ('findings', 'provider_caveats') - ORDER BY c.relname COLLATE "C", t.tgname COLLATE "C"`, - [schema] - ); - return result.rows; -} - -describe.skipIf(!url)('findings and provider_caveats PostgreSQL schema', () => { - test('creates tables, indexes, and triggers and is idempotent on runner re-run and raw SQL re-execution', async () => { - const f = await createIsolatedFixture(); - - const tables = new Set( - ( - await f.pool.query('SELECT tablename FROM pg_tables WHERE schemaname = $1', [f.schema]) - ).rows.map(row => row.tablename as string) - ); - expect(tables.has('findings')).toBe(true); - expect(tables.has('provider_caveats')).toBe(true); - - const indexDefs = new Map( - ( - await f.pool.query('SELECT indexname, indexdef FROM pg_indexes WHERE schemaname = $1', [ - f.schema, - ]) - ).rows.map(row => [row.indexname as string, row.indexdef as string]) - ); - expect(indexDefs.get('idx_findings_idempotency_key')).toMatch( - /CREATE UNIQUE INDEX idx_findings_idempotency_key ON .*findings .* \(idempotency_key\) WHERE \(idempotency_key IS NOT NULL\)/ - ); - expect(indexDefs.get('idx_findings_created_at')).toMatch( - /CREATE INDEX idx_findings_created_at ON .*findings .* \(created_at\)/ - ); - expect(indexDefs.get('idx_provider_caveats_lower_provider')).toMatch( - /CREATE INDEX idx_provider_caveats_lower_provider ON .*provider_caveats .* \(lower\(provider\)\)/ - ); - - expect(await listProtectionTriggers(f.pool, f.schema)).toEqual(EXPECTED_PROTECTION_TRIGGERS); - - const insertedFinding = ( - await insertFinding(f.pool, { id: 'f-idempotent', idempotencyKey: 'idem-keep' }) - ).rows[0]; - const insertedCaveat = ( - await insertProviderCaveat(f.pool, { id: 'c-idempotent', createdAt: FIXED_TS }) - ).rows[0]; - - expect(await runPostgresMigrations(f.postgres, { track: 'research' })).toEqual([]); - - const rawSql = readFileSync(researchFindingsSqlPath, 'utf8'); - await f.pool.query(rawSql); - - expect(await listProtectionTriggers(f.pool, f.schema)).toEqual(EXPECTED_PROTECTION_TRIGGERS); - - const findingsAfter = (await f.pool.query('SELECT * FROM findings')).rows; - const caveatsAfter = (await f.pool.query('SELECT * FROM provider_caveats')).rows; - expect(findingsAfter).toEqual([insertedFinding]); - expect(caveatsAfter).toEqual([insertedCaveat]); - - await expectPgErrorCode( - f.pool.query("UPDATE findings SET title = 'mutated'"), - '23514', - EXPECTED_IMMUTABLE_MSG - ); - await expectPgErrorCode(f.pool.query('DELETE FROM findings'), '23514', EXPECTED_IMMUTABLE_MSG); - await expectPgErrorCode(f.pool.query('TRUNCATE findings'), '23514', EXPECTED_IMMUTABLE_MSG); - - await expectPgErrorCode( - f.pool.query("UPDATE provider_caveats SET caveat = 'mutated'"), - '23514', - EXPECTED_IMMUTABLE_MSG - ); - await expectPgErrorCode( - f.pool.query('DELETE FROM provider_caveats'), - '23514', - EXPECTED_IMMUTABLE_MSG - ); - await expectPgErrorCode( - f.pool.query('TRUNCATE provider_caveats'), - '23514', - EXPECTED_IMMUTABLE_MSG - ); - - expect((await f.pool.query('SELECT * FROM findings')).rows).toEqual([insertedFinding]); - expect((await f.pool.query('SELECT * FROM provider_caveats')).rows).toEqual([insertedCaveat]); - }); - - test('findings round-trips every FiledFindingRecord field, defaults status, and accepts exact limit boundaries', async () => { - const f = await createIsolatedFixture(); - - const first = ( - await insertFinding(f.pool, { - id: 'finding-001', - kind: 'finding', - title: 'Earnings drift persists through day 3', - summary: 'Post-announcement drift remains positive across US large caps.', - createdAt: FIXED_TS, - trialRefs: ['42', '43'], - evidenceRefs: ['artifact:drift-v1'], - idempotencyKey: 'req-001', - }) - ).rows[0]; - - expect(first.id).toBe('finding-001'); - expect(first.kind).toBe('finding'); - expect(first.title).toBe('Earnings drift persists through day 3'); - expect(first.summary).toBe('Post-announcement drift remains positive across US large caps.'); - expect(first.status).toBe('pending_review'); - expect((first.created_at as Date).toISOString()).toBe(FIXED_TS); - expect(first.trial_refs).toEqual(['42', '43']); - expect(first.evidence_refs).toEqual(['artifact:drift-v1']); - expect(first.idempotency_key).toBe('req-001'); - - // Second row exercises dead_end, empty evidence_refs, and exact boundary lengths/cardinalities - // including Unicode NBSP / ideographic-space padding around max-length title and summary. - const maxRefs = Array.from({ length: 32 }, (_, i) => `${i}`.padStart(256, 'r')); - const boundary = ( - await insertFinding(f.pool, { - id: 'finding-002', - kind: 'dead_end', - title: `\u00A0${'t'.repeat(256)}\u00A0`, - summary: `\u00A0\u3000${'s'.repeat(4096)}\u00A0`, - createdAt: '2026-02-01T00:00:00.000Z', - trialRefs: maxRefs, - evidenceRefs: [], - idempotencyKey: 'k'.repeat(128), - }) - ).rows[0]; - - expect(boundary.kind).toBe('dead_end'); - expect(boundary.status).toBe('pending_review'); - expect((boundary.created_at as Date).toISOString()).toBe('2026-02-01T00:00:00.000Z'); - expect(boundary.trial_refs).toEqual(maxRefs); - expect(boundary.evidence_refs).toEqual([]); - expect(boundary.idempotency_key).toBe('k'.repeat(128)); - - // 32 evidence_refs at 256 chars and 1-char idempotency key also succeed. - const maxEvidence = ( - await insertFinding(f.pool, { - id: 'finding-003', - trialRefs: [], - evidenceRefs: maxRefs, - idempotencyKey: 'x', - }) - ).rows[0]; - expect(maxEvidence.trial_refs).toEqual([]); - expect(maxEvidence.evidence_refs).toEqual(maxRefs); - expect(maxEvidence.idempotency_key).toBe('x'); - }); - - test('findings rejects invalid kind, blank or oversized fields, malformed ref arrays, and invalid idempotency keys', async () => { - const f = await createIsolatedFixture(); - - // Blank / whitespace-only (ASCII and ECMAScript Unicode) id and status - const unicodeBlanks = ['\u00A0', '\u00A0\u2003\u3000\uFEFF', '\u2028\u2029']; - await expectPgErrorCode(insertFinding(f.pool, { id: '' }), '23514'); - await expectPgErrorCode(insertFinding(f.pool, { id: ' \t\n ' }), '23514'); - await expectPgErrorCode(insertFinding(f.pool, { status: '' }), '23514'); - await expectPgErrorCode(insertFinding(f.pool, { status: ' \t\r\n ' }), '23514'); - for (const blank of unicodeBlanks) { - await expectPgErrorCode(insertFinding(f.pool, { id: blank }), '23514'); - await expectPgErrorCode(insertFinding(f.pool, { status: blank }), '23514'); - } - - // Invalid kind - await expectPgErrorCode(insertFinding(f.pool, { kind: 'hypothesis' }), '23514'); - await expectPgErrorCode(insertFinding(f.pool, { kind: 'FINDING' }), '23514'); - await expectPgErrorCode(insertFinding(f.pool, { kind: '' }), '23514'); - - // Blank, whitespace-only (ASCII and ECMAScript Unicode), or oversized title / summary - await expectPgErrorCode(insertFinding(f.pool, { title: '' }), '23514'); - await expectPgErrorCode(insertFinding(f.pool, { title: ' \t\n\r ' }), '23514'); - await expectPgErrorCode(insertFinding(f.pool, { title: 't'.repeat(257) }), '23514'); - await expectPgErrorCode( - insertFinding(f.pool, { title: `\u00A0${'t'.repeat(257)}\u00A0` }), - '23514' - ); - await expectPgErrorCode(insertFinding(f.pool, { summary: '' }), '23514'); - await expectPgErrorCode(insertFinding(f.pool, { summary: ' \t\n\r ' }), '23514'); - await expectPgErrorCode(insertFinding(f.pool, { summary: 's'.repeat(4097) }), '23514'); - for (const blank of unicodeBlanks) { - await expectPgErrorCode(insertFinding(f.pool, { title: blank }), '23514'); - await expectPgErrorCode(insertFinding(f.pool, { summary: blank }), '23514'); - } - - // Cardinality > 32 - const refs33 = Array.from({ length: 33 }, (_, i) => `ref-${i}`); - await expectPgErrorCode(insertFinding(f.pool, { trialRefs: refs33 }), '23514'); - await expectPgErrorCode(insertFinding(f.pool, { evidenceRefs: refs33 }), '23514'); - - // Ref length > 256 - const ref257 = 'r'.repeat(257); - await expectPgErrorCode(insertFinding(f.pool, { trialRefs: [ref257] }), '23514'); - await expectPgErrorCode(insertFinding(f.pool, { evidenceRefs: ['ok', ref257] }), '23514'); - - // NULL array elements - await expectPgErrorCode(insertFinding(f.pool, { trialRefs: ['101', null] }), '23514'); - await expectPgErrorCode(insertFinding(f.pool, { evidenceRefs: [null] }), '23514'); - - // Multidimensional arrays - await expectPgErrorCode( - f.pool.query( - `INSERT INTO findings (id, kind, title, summary, created_at, trial_refs, evidence_refs) - VALUES ('f-2d-trial', 'finding', 'Title', 'Summary', $1::timestamptz, '{{a,b},{c,d}}'::text[], '{}'::text[])`, - [FIXED_TS] - ), - '23514' - ); - await expectPgErrorCode( - f.pool.query( - `INSERT INTO findings (id, kind, title, summary, created_at, trial_refs, evidence_refs) - VALUES ('f-2d-ev', 'finding', 'Title', 'Summary', $1::timestamptz, '{101}'::text[], '{{a,b},{c,d}}'::text[])`, - [FIXED_TS] - ), - '23514' - ); - - // Invalid idempotency_key (empty, whitespace-only, > 128 chars) - await expectPgErrorCode(insertFinding(f.pool, { idempotencyKey: '' }), '23514'); - await expectPgErrorCode(insertFinding(f.pool, { idempotencyKey: ' \t\n ' }), '23514'); - for (const blank of unicodeBlanks) { - await expectPgErrorCode(insertFinding(f.pool, { idempotencyKey: blank }), '23514'); - } - await expectPgErrorCode(insertFinding(f.pool, { idempotencyKey: 'k'.repeat(129) }), '23514'); - - expect((await f.pool.query('SELECT count(*)::int AS c FROM findings')).rows[0].c).toBe(0); - }); - - test('findings enforces unique non-NULL idempotency_key while allowing multiple NULL keys', async () => { - const f = await createIsolatedFixture(); - - await insertFinding(f.pool, { id: 'f-key-1', idempotencyKey: 'shared-key' }); - await expectPgErrorCode( - insertFinding(f.pool, { id: 'f-key-2', idempotencyKey: 'shared-key' }), - '23505' - ); - - await insertFinding(f.pool, { id: 'f-null-1', idempotencyKey: null }); - await insertFinding(f.pool, { id: 'f-null-2', idempotencyKey: null }); - - expect((await f.pool.query('SELECT count(*)::int AS c FROM findings')).rows[0].c).toBe(3); - }); - - test('provider_caveats round-trips every ProviderCaveatRecord field, defaults created_at, and rejects blank fields', async () => { - const f = await createIsolatedFixture(); - - const explicit = ( - await insertProviderCaveat(f.pool, { - id: 'caveat-001', - provider: 'QuoteMedia', - dataset: 'qmSplits', - caveat: 'splitratio stores old_shares / new_shares; invert to canonical new / old.', - createdAt: FIXED_TS, - }) - ).rows[0]; - - expect(explicit.id).toBe('caveat-001'); - expect(explicit.provider).toBe('QuoteMedia'); - expect(explicit.dataset).toBe('qmSplits'); - expect(explicit.caveat).toBe( - 'splitratio stores old_shares / new_shares; invert to canonical new / old.' - ); - expect((explicit.created_at as Date).toISOString()).toBe(FIXED_TS); - - const defaulted = (await insertProviderCaveat(f.pool, { id: 'caveat-002' })).rows[0]; - expect(defaulted.created_at).toBeInstanceOf(Date); - - for (const blank of [ - '', - ' ', - '\t\n\r', - '\u00A0', - '\u00A0\u2003\u3000\uFEFF', - '\u2028\u2029', - ]) { - await expectPgErrorCode(insertProviderCaveat(f.pool, { id: blank }), '23514'); - await expectPgErrorCode(insertProviderCaveat(f.pool, { provider: blank }), '23514'); - await expectPgErrorCode(insertProviderCaveat(f.pool, { dataset: blank }), '23514'); - await expectPgErrorCode(insertProviderCaveat(f.pool, { caveat: blank }), '23514'); - } - - expect((await f.pool.query('SELECT count(*)::int AS c FROM provider_caveats')).rows[0].c).toBe( - 2 - ); - }); - - test('UPDATE, DELETE, and TRUNCATE are blocked on both findings and provider_caveats', async () => { - const f = await createIsolatedFixture(); - - const findingBefore = (await insertFinding(f.pool, { id: 'f-immutable' })).rows[0]; - const caveatBefore = ( - await insertProviderCaveat(f.pool, { id: 'c-immutable', createdAt: FIXED_TS }) - ).rows[0]; - - await expectPgErrorCode( - f.pool.query("UPDATE findings SET status = 'approved'"), - '23514', - EXPECTED_IMMUTABLE_MSG - ); - await expectPgErrorCode(f.pool.query('DELETE FROM findings'), '23514', EXPECTED_IMMUTABLE_MSG); - await expectPgErrorCode(f.pool.query('TRUNCATE findings'), '23514', EXPECTED_IMMUTABLE_MSG); - - await expectPgErrorCode( - f.pool.query("UPDATE provider_caveats SET provider = 'Other'"), - '23514', - EXPECTED_IMMUTABLE_MSG - ); - await expectPgErrorCode( - f.pool.query('DELETE FROM provider_caveats'), - '23514', - EXPECTED_IMMUTABLE_MSG - ); - await expectPgErrorCode( - f.pool.query('TRUNCATE provider_caveats'), - '23514', - EXPECTED_IMMUTABLE_MSG - ); - - expect((await f.pool.query('SELECT * FROM findings')).rows).toEqual([findingBefore]); - expect((await f.pool.query('SELECT * FROM provider_caveats')).rows).toEqual([caveatBefore]); - }); -}); - -describe.skipIf(!url)('findings and provider_caveats PostgreSQL schema edge cases (QA)', () => { - test('research_trim_ecmascript matches String.prototype.trim() for every ECMAScript blank and for look-alike non-blanks', async () => { - const f = await createIsolatedFixture(); - // 25 ECMAScript WhiteSpace + LineTerminator code points, plus characters JS trim() keeps: - // ZERO WIDTH SPACE, NEXT LINE, MONGOLIAN VOWEL SEPARATOR, WORD JOINER. - const codePoints = [ - 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x20, 0xa0, 0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, - 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200a, 0x2028, 0x2029, 0x202f, 0x205f, 0x3000, - 0xfeff, 0x200b, 0x0085, 0x180e, 0x2060, - ]; - for (const cp of codePoints) { - const c = String.fromCodePoint(cp); - for (const input of [c, `${c}${c}a b${c}`]) { - const sqlTrimmed = ( - await f.pool.query<{ v: string }>('SELECT research_trim_ecmascript($1) AS v', [input]) - ).rows[0]?.v; - expect({ cp, input, trimmed: sqlTrimmed }).toEqual({ cp, input, trimmed: input.trim() }); - } - } - }); - - test('non-ECMAScript blanks the MCP tool accepts (U+200B, U+0085) are accepted, and text is stored untrimmed', async () => { - const f = await createIsolatedFixture(); - const paddedTitle = `\u00A0 Interior spacing\tkept \u3000`; - - const zwsp = (await insertFinding(f.pool, { id: 'f-zwsp', title: '\u200B' })).rows[0]; - const nel = (await insertFinding(f.pool, { id: 'f-nel', summary: '\u0085' })).rows[0]; - const padded = (await insertFinding(f.pool, { id: 'f-padded', title: paddedTitle })).rows[0]; - - expect(zwsp.title).toBe('\u200B'); - expect(nel.summary).toBe('\u0085'); - expect(padded.title).toBe(paddedTitle); - }); - - test('title/summary caps count code points: 256 astral characters accepted, 257 rejected', async () => { - const f = await createIsolatedFixture(); - const emoji = '\u{1F4C8}'; - - const ok = (await insertFinding(f.pool, { id: 'f-astral-ok', title: emoji.repeat(256) })) - .rows[0]; - expect(ok.title).toBe(emoji.repeat(256)); - await expectPgErrorCode( - insertFinding(f.pool, { id: 'f-astral-bad', title: emoji.repeat(257) }), - '23514' - ); - await expectPgErrorCode( - insertFinding(f.pool, { id: 'f-astral-ref', trialRefs: [emoji.repeat(257)] }), - '23514' - ); - }); - - test('NOT NULL columns reject NULL with SQLSTATE 23502 and leave no rows', async () => { - const f = await createIsolatedFixture(); - const base = { - id: 'f-null', - kind: 'finding', - title: 'Title', - summary: 'Summary', - created_at: FIXED_TS, - trial_refs: ['1'], - evidence_refs: [] as string[], - }; - for (const column of Object.keys(base) as (keyof typeof base)[]) { - const row = { ...base, [column]: null }; - await expectPgErrorCode( - f.pool.query( - `INSERT INTO findings (id, kind, title, summary, created_at, trial_refs, evidence_refs) - VALUES ($1, $2, $3, $4, $5::timestamptz, $6::text[], $7::text[])`, - [ - row.id, - row.kind, - row.title, - row.summary, - row.created_at, - row.trial_refs, - row.evidence_refs, - ] - ), - '23502' - ); - } - // created_at has no default on findings: the tool's clock must supply it. - await expectPgErrorCode( - f.pool.query( - `INSERT INTO findings (id, kind, title, summary, trial_refs, evidence_refs) - VALUES ('f-no-ts', 'finding', 'Title', 'Summary', '{1}', '{}')` - ), - '23502' - ); - await expectPgErrorCode( - f.pool.query( - `INSERT INTO findings (id, kind, title, summary, created_at, trial_refs, evidence_refs, status) - VALUES ('f-null-status', 'finding', 'Title', 'Summary', $1::timestamptz, '{1}', '{}', NULL)`, - [FIXED_TS] - ), - '23502' - ); - for (const column of ['id', 'provider', 'dataset', 'caveat', 'created_at']) { - const values: Record = { - id: 'c-null', - provider: 'EODHD', - dataset: 'eodPrices', - caveat: 'Caveat text', - created_at: FIXED_TS, - [column]: null, - }; - await expectPgErrorCode( - f.pool.query( - `INSERT INTO provider_caveats (id, provider, dataset, caveat, created_at) - VALUES ($1, $2, $3, $4, $5::timestamptz)`, - [values.id, values.provider, values.dataset, values.caveat, values.created_at] - ), - '23502' - ); - } - - expect((await f.pool.query('SELECT count(*)::int AS c FROM findings')).rows[0].c).toBe(0); - expect((await f.pool.query('SELECT count(*)::int AS c FROM provider_caveats')).rows[0].c).toBe( - 0 - ); - }); - - test('duplicate ids are rejected (23505) on both tables and idempotency keys are case-sensitive', async () => { - const f = await createIsolatedFixture(); - - await insertFinding(f.pool, { id: 'dup-finding' }); - await expectPgErrorCode(insertFinding(f.pool, { id: 'dup-finding' }), '23505'); - await insertProviderCaveat(f.pool, { id: 'dup-caveat' }); - await expectPgErrorCode(insertProviderCaveat(f.pool, { id: 'dup-caveat' }), '23505'); - - // file_finding compares idempotency keys exactly; the unique index must not fold case. - await insertFinding(f.pool, { id: 'f-case-1', idempotencyKey: 'Retry-Key' }); - await insertFinding(f.pool, { id: 'f-case-2', idempotencyKey: 'retry-key' }); - - expect((await f.pool.query('SELECT count(*)::int AS c FROM findings')).rows[0].c).toBe(3); - expect((await f.pool.query('SELECT count(*)::int AS c FROM provider_caveats')).rows[0].c).toBe( - 1 - ); - }); - - test('a rejected UPDATE matching one row leaves every other row and column untouched', async () => { - const f = await createIsolatedFixture(); - await insertFinding(f.pool, { id: 'f-a', createdAt: '2026-01-01T00:00:00.000Z' }); - await insertFinding(f.pool, { id: 'f-b', createdAt: '2026-01-02T00:00:00.000Z' }); - const before = (await f.pool.query('SELECT * FROM findings ORDER BY id')).rows; - - await expectPgErrorCode( - f.pool.query("UPDATE findings SET status = 'approved' WHERE id = 'f-b'"), - '23514', - EXPECTED_IMMUTABLE_MSG - ); - await expectPgErrorCode( - f.pool.query("DELETE FROM findings WHERE id = 'f-a'"), - '23514', - EXPECTED_IMMUTABLE_MSG - ); - - expect((await f.pool.query('SELECT * FROM findings ORDER BY id')).rows).toEqual(before); - }); -}); diff --git a/test/postgres/security-master-contract.test.ts b/test/postgres/security-master-contract.test.ts index 292bca21..eb140bb2 100644 --- a/test/postgres/security-master-contract.test.ts +++ b/test/postgres/security-master-contract.test.ts @@ -274,13 +274,12 @@ describe('34-security-master.sql track registration', () => { expect(await runPostgresMigrations(postgres as never)).toEqual(research); }); - test('all track runs 33, 34, 35, 36, 37 last in exact order and skips 06-08', async () => { + test('all track runs 33, 34, 35, 36 last in exact order and skips 06-08', async () => { const all = await filesForTrack('all'); - expect(all.at(-5)).toBe('33-candidate-decimal-normalization.sql'); - expect(all.at(-4)).toBe('34-security-master.sql'); - expect(all.at(-3)).toBe('35-security-master-exchange-seed.sql'); - expect(all.at(-2)).toBe('36-trial-ledger.sql'); - expect(all.at(-1)).toBe('37-research-findings.sql'); + expect(all.at(-4)).toBe('33-candidate-decimal-normalization.sql'); + expect(all.at(-3)).toBe('34-security-master.sql'); + expect(all.at(-2)).toBe('35-security-master-exchange-seed.sql'); + expect(all.at(-1)).toBe('36-trial-ledger.sql'); for (const bootstrap of [ '06-create-backtest-tables.sql', '07-fix-execution-time-type.sql', diff --git a/test/postgres/security-master-export-curate-inputs.test.ts b/test/postgres/security-master-export-curate-inputs.test.ts deleted file mode 100644 index 51705ecd..00000000 --- a/test/postgres/security-master-export-curate-inputs.test.ts +++ /dev/null @@ -1,493 +0,0 @@ -import { randomUUID } from 'node:crypto'; -import { mkdtemp, readFile, rm } from 'node:fs/promises'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -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 { - exportCurateInputs, - pinCurateInputSnapshot, - type SecurityMasterQueryable, - type SecurityMasterQueryResult, -} from '../../apps/stock/data-pipeline/src/security-master'; - -setLoggerConfig({ logLevel: 'fatal', logConsole: false }); -const logger = getLogger('security-master-export-curate-inputs-pg-test'); -const url = process.env.PIPELINE_TEST_DATABASE_URL; - -const cleanup: (() => Promise | void)[] = []; -afterEach(async () => { - for (const close of cleanup.splice(0).reverse()) { - await close(); - } -}); - -async function makeTempDir(prefix = 'curate-inputs-pg-'): Promise { - const dir = await mkdtemp(join(tmpdir(), prefix)); - cleanup.push(() => rm(dir, { recursive: true, force: true })); - return dir; -} - -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 withRecordingClient( - pool: Pool, - fn: (queryable: SecurityMasterQueryable, recordedSql: string[]) => Promise -): Promise { - const client: PoolClient = await pool.connect(); - const recordedSql: string[] = []; - const queryable: SecurityMasterQueryable = { - query>( - text: string, - values?: readonly unknown[] - ): Promise> { - recordedSql.push(text.replace(/\s+/g, ' ').trim()); - return client.query( - text, - values === undefined ? undefined : [...values] - ) as unknown as Promise>; - }, - release: () => { - client.release(); - }, - }; - try { - return await fn(queryable, recordedSql); - } finally { - client.release(); - } -} - -async function seedFixtureData(pool: Pool) { - const client = await pool.connect(); - try { - await client.query('BEGIN'); - - // Ensure required MICs exist (migration 35 seeds them, ON CONFLICT DO NOTHING keeps idempotent). - await client.query(` - INSERT INTO exchange (mic, operating_mic, name, country_iso, currency, timezone, calendar_code, board_lot_policy) - VALUES - ('XNAS', 'XNAS', 'NASDAQ', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'), - ('XNYS', 'XNYS', 'NYSE', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'), - ('XTSE', 'XTSE', 'TSX', 'CA', 'CAD', 'America/Toronto', 'XTSE', 'tsx_tiered'), - ('OTCM', 'OTCM', 'OTC Markets', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100') - ON CONFLICT (mic) DO NOTHING - `); - - const insertInstrument = async ( - isin: string, - cusip: string, - name: string, - securityType: string, - country: string - ): Promise => { - const res = await client.query<{ instrument_id: number }>( - `INSERT INTO instrument (primary_isin, primary_cusip, canonical_name, security_type, issuer_country) - VALUES ($1, $2, $3, $4, $5) - RETURNING instrument_id`, - [isin, cusip, name, securityType, country] - ); - return res.rows[0]!.instrument_id; - }; - - const instAapl = await insertInstrument('US0378331005', '037833100', 'Apple Inc.', 'common', 'US'); - const instShop = await insertInstrument('CA82509L1076', '82509L107', 'Shopify Inc.', 'common', 'CA'); - const instFbOld = await insertInstrument('US30303M1027', '30303M102', 'Meta Platforms', 'common', 'US'); - const instFbNew = await insertInstrument('US4642872000', '464287200', 'FB Thematic ETF', 'etf', 'US'); - const instSivb = await insertInstrument('US78486Q1013', '78486Q101', 'SVB Financial Group', 'common', 'US'); - const instSivbReuse = await insertInstrument('US0000000019', '000000001', 'SIVB Reused Corp', 'common', 'US'); - const instDel30 = await insertInstrument('US0000000027', '000000002', 'Delisted 30 Corp', 'common', 'US'); - const instNoListedTo = await insertInstrument('US0000000035', '000000003', 'No ListedTo Corp', 'common', 'US'); - const instNoQm = await insertInstrument('US0000000043', '000000004', 'No QM Mapping Corp', 'common', 'US'); - const instNoSuccQm = await insertInstrument('US0000000050', '000000005', 'No Succ QM Corp', 'common', 'US'); - - const insertListing = async (params: { - instrumentId: number; - mic: string; - tickerRoot: string; - currency: string; - listedFrom: string | null; - listedTo: string | null; - delistReason: string | null; - terminalReturn: string | null; - }): Promise => { - const res = await client.query<{ listing_id: number }>( - `INSERT INTO listing ( - instrument_id, mic, ticker_root, class_suffix, currency, - listed_from, listed_to, delist_reason, terminal_return - ) - VALUES ($1, $2, $3, '', $4, $5::date, $6::date, $7, $8::numeric) - RETURNING listing_id`, - [ - params.instrumentId, - params.mic, - params.tickerRoot, - params.currency, - params.listedFrom, - params.listedTo, - params.delistReason, - params.terminalReturn, - ] - ); - return res.rows[0]!.listing_id; - }; - - const aaplId = await insertListing({ - instrumentId: instAapl, - mic: 'XNAS', - tickerRoot: 'AAPL', - currency: 'USD', - listedFrom: '1980-12-12', - listedTo: null, - delistReason: 'active', - terminalReturn: null, - }); - const shopId = await insertListing({ - instrumentId: instShop, - mic: 'XTSE', - tickerRoot: 'SHOP', - currency: 'CAD', - listedFrom: '2015-05-21', - listedTo: null, - delistReason: 'active', - terminalReturn: null, - }); - const fbOldId = await insertListing({ - instrumentId: instFbOld, - mic: 'XNAS', - tickerRoot: 'FB', - currency: 'USD', - listedFrom: '2012-05-18', - listedTo: '2022-06-08', - delistReason: null, - terminalReturn: null, - }); - const fbNewId = await insertListing({ - instrumentId: instFbNew, - mic: 'XNYS', - tickerRoot: 'FB', - currency: 'USD', - listedFrom: '2022-06-09', - listedTo: null, - delistReason: 'active', - terminalReturn: null, - }); - const sivbId = await insertListing({ - instrumentId: instSivb, - mic: 'XNAS', - tickerRoot: 'SIVB', - currency: 'USD', - listedFrom: '1988-01-04', - listedTo: '2023-03-10', - delistReason: 'moved_to_otc', - terminalReturn: null, - }); - const sivbReuseId = await insertListing({ - instrumentId: instSivbReuse, - mic: 'XNAS', - tickerRoot: 'SIVB', - currency: 'USD', - listedFrom: '2023-03-20', - listedTo: null, - delistReason: 'active', - terminalReturn: null, - }); - const sivbqId = await insertListing({ - instrumentId: instSivb, - mic: 'OTCM', - tickerRoot: 'SIVBQ', - currency: 'USD', - listedFrom: '2023-03-28', - listedTo: '2024-11-07', - delistReason: 'bankruptcy_cancelled', - terminalReturn: '-1.000000', - }); - const del30Id = await insertListing({ - instrumentId: instDel30, - mic: 'XNYS', - tickerRoot: 'DEL30', - currency: 'USD', - listedFrom: '2018-01-02', - listedTo: '2023-06-15', - delistReason: 'unknown_involuntary', - terminalReturn: '-0.300000', - }); - const noListedToId = await insertListing({ - instrumentId: instNoListedTo, - mic: 'XNYS', - tickerRoot: 'NLDT', - currency: 'USD', - listedFrom: '2019-01-02', - listedTo: null, - delistReason: 'unknown_involuntary', - terminalReturn: '-0.300000', - }); - const noQmId = await insertListing({ - instrumentId: instNoQm, - mic: 'XNYS', - tickerRoot: 'NOQM', - currency: 'USD', - listedFrom: '2019-01-02', - listedTo: '2023-07-01', - delistReason: 'unknown_involuntary', - terminalReturn: '-0.300000', - }); - const noSuccQmFromId = await insertListing({ - instrumentId: instNoSuccQm, - mic: 'XNYS', - tickerRoot: 'NOSU', - currency: 'USD', - listedFrom: '2019-01-02', - listedTo: '2023-03-10', - delistReason: 'moved_to_otc', - terminalReturn: null, - }); - const noSuccQmToId = await insertListing({ - instrumentId: instNoSuccQm, - mic: 'OTCM', - tickerRoot: 'NOSUQ', - currency: 'USD', - listedFrom: '2023-03-28', - listedTo: null, - delistReason: null, - terminalReturn: null, - }); - - const insertMapping = async ( - source: string, - sourceId: string, - validFrom: string, - validTo: string | null, - listingId: number - ) => { - await client.query( - `INSERT INTO provider_mapping (source, source_id, valid_from, valid_to, listing_id, method, confidence) - VALUES ($1, $2, $3::date, $4::date, $5, 'tier1_isin', 0.990)`, - [source, sourceId, validFrom, validTo, listingId] - ); - }; - - // Active US + CA - await insertMapping('eod', 'AAPL.US', '1980-12-12', null, aaplId); - await insertMapping('qm', 'AAPL', '1980-12-12', null, aaplId); - await insertMapping('eod', 'SHOP.TO', '2015-05-21', null, shopId); - await insertMapping('qm', 'SHOP:CA', '2015-05-21', null, shopId); - - // Ticker reuse FB across two date ranges - await insertMapping('eod', 'FB.US', '2012-05-18', '2022-06-08', fbOldId); - await insertMapping('eod', 'FB.US', '2022-06-09', null, fbNewId); - await insertMapping('qm', 'FB', '2012-05-18', '2022-06-08', fbOldId); - await insertMapping('qm', 'FB', '2022-06-09', null, fbNewId); - - // SIVB -> SIVBQ across ticker reuse - await insertMapping('eod', 'SIVB.US', '1988-01-04', '2023-03-10', sivbId); - await insertMapping('eod', 'SIVB.US', '2023-03-20', null, sivbReuseId); - await insertMapping('eod', 'SIVBQ.US', '2023-03-28', '2024-11-07', sivbqId); - await insertMapping('qm', 'SIVB', '1988-01-04', '2023-03-10', sivbId); - await insertMapping('qm', 'SIVB', '2023-03-20', null, sivbReuseId); - await insertMapping('qm', 'SIVBQ', '2023-03-28', '2024-11-07', sivbqId); - - // DEL30 -0.3 terminal delisting - await insertMapping('eod', 'DEL30.US', '2018-01-02', '2023-06-15', del30Id); - await insertMapping('qm', 'DEL30', '2018-01-02', '2023-06-15', del30Id); - - // Skipped-row mappings: noQm has only eod; noSuccQmFrom has qm, successor has no qm - await insertMapping('eod', 'NOQM.US', '2019-01-02', '2023-07-01', noQmId); - await insertMapping('qm', 'NOSU', '2019-01-02', '2023-03-10', noSuccQmFromId); - - // Continuities - await client.query( - `INSERT INTO corporate_action_continuity (from_listing_id, to_listing_id, effective_date, kind) - VALUES - ($1, $2, '2023-03-28'::date, 'otc_delist_transfer'), - ($3, $4, '2023-03-28'::date, 'otc_delist_transfer')`, - [sivbId, sivbqId, noSuccQmFromId, noSuccQmToId] - ); - - await client.query('COMMIT'); - - return { - aaplId, - shopId, - fbOldId, - fbNewId, - sivbId, - sivbReuseId, - sivbqId, - del30Id, - noListedToId, - noQmId, - noSuccQmFromId, - noSuccQmToId, - }; - } catch (error) { - await client.query('ROLLBACK').catch(() => {}); - throw error; - } finally { - client.release(); - } -} - -describe('exportCurateInputs PostgreSQL integration (isolated stock_bot_safety_*)', () => { - test('exports exact TSV bytes read-only and matches across chunkSize=1 and chunkSize=5000', async () => { - const { pool } = await createIsolatedFixture(); - const ids = await seedFixtureData(pool); - - const outDir5000 = await makeTempDir('curate-inputs-pg-5000-'); - const outDir1 = await makeTempDir('curate-inputs-pg-1-'); - - const { result: res5000, sql: sql5000 } = await withRecordingClient( - pool, - async (queryable, recordedSql) => ({ - result: await exportCurateInputs(queryable, { outDir: outDir5000, chunkSize: 5000 }), - sql: recordedSql, - }) - ); - - const { result: res1, sql: sql1 } = await withRecordingClient( - pool, - async (queryable, recordedSql) => ({ - result: await exportCurateInputs(queryable, { outDir: outDir1, chunkSize: 1 }), - sql: recordedSql, - }) - ); - - // Read-only SQL verification: REPEATABLE READ READ ONLY transaction + server-side cursor + zero writes/DDL. - for (const sqlLog of [sql5000, sql1]) { - expect(sqlLog[0]).toBe('BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY'); - expect(sqlLog[sqlLog.length - 1]).toBe('COMMIT'); - expect(sqlLog.some(s => s.startsWith('DECLARE curate_export_pm_cursor NO SCROLL CURSOR FOR'))).toBe( - true - ); - expect(sqlLog.some(s => s === 'CLOSE curate_export_pm_cursor')).toBe(true); - for (const stmt of sqlLog) { - expect(stmt).not.toMatch(/\b(INSERT|UPDATE|DELETE|CREATE|ALTER|DROP|TRUNCATE|GRANT|REVOKE)\b/i); - } - } - - // Verify snapshot pinning resolves to the published immutable generation. - const pinned5000 = await pinCurateInputSnapshot(outDir5000); - expect(pinned5000.generationId).toBe(res5000.generationId); - expect(pinned5000.providerMapping).toBe(res5000.providerMapping.path); - expect(pinned5000.listingCurrencies).toBe(res5000.listingCurrencies.path); - expect(pinned5000.delistings).toBe(res5000.delistings.path); - - // Verify chunkSize=1 actually paginated across multiple queries. - expect(sql1.length).toBeGreaterThan(sql5000.length); - - // Byte-identical outputs between chunkSize=1 and chunkSize=5000. - const pm5000 = await readFile(res5000.providerMapping.path, 'utf8'); - const lc5000 = await readFile(res5000.listingCurrencies.path, 'utf8'); - const dl5000 = await readFile(res5000.delistings.path, 'utf8'); - - expect(await readFile(res1.providerMapping.path, 'utf8')).toBe(pm5000); - expect(await readFile(res1.listingCurrencies.path, 'utf8')).toBe(lc5000); - expect(await readFile(res1.delistings.path, 'utf8')).toBe(dl5000); - - // Assert exact provider_mapping.tsv content (COLLATE "C" ASCII order). - expect(pm5000).toBe( - [ - `eod\tAAPL.US\t1980-12-12\t\t${ids.aaplId}`, - `eod\tDEL30.US\t2018-01-02\t2023-06-15\t${ids.del30Id}`, - `eod\tFB.US\t2012-05-18\t2022-06-08\t${ids.fbOldId}`, - `eod\tFB.US\t2022-06-09\t\t${ids.fbNewId}`, - `eod\tNOQM.US\t2019-01-02\t2023-07-01\t${ids.noQmId}`, - `eod\tSHOP.TO\t2015-05-21\t\t${ids.shopId}`, - `eod\tSIVB.US\t1988-01-04\t2023-03-10\t${ids.sivbId}`, - `eod\tSIVB.US\t2023-03-20\t\t${ids.sivbReuseId}`, - `eod\tSIVBQ.US\t2023-03-28\t2024-11-07\t${ids.sivbqId}`, - `qm\tAAPL\t1980-12-12\t\t${ids.aaplId}`, - `qm\tDEL30\t2018-01-02\t2023-06-15\t${ids.del30Id}`, - `qm\tFB\t2012-05-18\t2022-06-08\t${ids.fbOldId}`, - `qm\tFB\t2022-06-09\t\t${ids.fbNewId}`, - `qm\tNOSU\t2019-01-02\t2023-03-10\t${ids.noSuccQmFromId}`, - `qm\tSHOP:CA\t2015-05-21\t\t${ids.shopId}`, - `qm\tSIVB\t1988-01-04\t2023-03-10\t${ids.sivbId}`, - `qm\tSIVB\t2023-03-20\t\t${ids.sivbReuseId}`, - `qm\tSIVBQ\t2023-03-28\t2024-11-07\t${ids.sivbqId}`, - '', - ].join('\n') - ); - - // Assert exact listing_currencies.tsv content (btrim(CHAR(3)), ascending listing_id). - expect(lc5000).toBe( - [ - `${ids.aaplId}\tUSD`, - `${ids.shopId}\tCAD`, - `${ids.fbOldId}\tUSD`, - `${ids.fbNewId}\tUSD`, - `${ids.sivbId}\tUSD`, - `${ids.sivbReuseId}\tUSD`, - `${ids.sivbqId}\tUSD`, - `${ids.del30Id}\tUSD`, - `${ids.noListedToId}\tUSD`, - `${ids.noQmId}\tUSD`, - `${ids.noSuccQmFromId}\tUSD`, - `${ids.noSuccQmToId}\tUSD`, - '', - ].join('\n') - ); - - // Assert exact delistings.tsv content. - expect(dl5000).toBe( - [ - `DEL30\t2023-06-15\t${ids.del30Id}\t\t-0.3`, - `SIVB\t2023-03-28\t${ids.sivbId}\tSIVBQ\t`, - `SIVBQ\t2024-11-07\t${ids.sivbqId}\t\t-1`, - '', - ].join('\n') - ); - - // Assert exact stats reconciliation. - const stats = res5000.delistings.stats; - expect(stats).toEqual({ - rowsIn: 12, - rowsOut: 3, - otcTransfersOut: 1, - terminalDelistingsOut: 2, - skippedTotal: 9, - skipped: { - active: 4, // AAPL, SHOP, FB new, SIVB reuse - noOutcome: 2, // FB old, NOSUQ - missingListedTo: 1, // NLDT - missingOutgoingQmMapping: 1, // NOQM - missingSuccessorQmMapping: 1, // NOSU -> NOSUQ - nonOtcContinuity: 0, - }, - }); - expect(stats.rowsIn).toBe(stats.rowsOut + stats.skippedTotal); - expect(res1.delistings.stats).toEqual(stats); - }); -}); diff --git a/test/unit/data-pipeline-rust-evaluation-doc.test.ts b/test/unit/data-pipeline-rust-evaluation-doc.test.ts deleted file mode 100644 index aa5f1489..00000000 --- a/test/unit/data-pipeline-rust-evaluation-doc.test.ts +++ /dev/null @@ -1,192 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { existsSync, readFileSync } from 'node:fs'; -import { dirname, join, resolve } from 'node:path'; - -// Guards the T-124 decision brief (design/data-pipeline/rust-migration-evaluation.md) against -// silent drift: it must stay linked, keep its seven required sections, keep internally consistent -// totals and derived figures, and every quoted benchmark figure must still appear verbatim in the -// README it cites. Live file counts are deliberately not pinned here (they change with every -// data-pipeline task); the document's own reproducible commands cover that at its commit. -const repoRoot = join(import.meta.dir, '..', '..'); -const evalRel = 'design/data-pipeline/rust-migration-evaluation.md'; -const evalPath = join(repoRoot, evalRel); -const designReadmePath = join(repoRoot, 'design/README.md'); -const curateReadme = readFileSync(join(repoRoot, 'tools/curate-etl/README.md'), 'utf8'); -const pipelineReadme = readFileSync(join(repoRoot, 'apps/stock/data-pipeline/README.md'), 'utf8'); -const doc = readFileSync(evalPath, 'utf8'); - -function num(text: string): number { - return Number(text.replace(/[`,*]/g, '').trim()); -} - -function section(title: RegExp): string { - const lines = doc.split('\n'); - const start = lines.findIndex(line => /^## /.test(line) && title.test(line)); - expect(start).toBeGreaterThan(-1); - const rest = lines.slice(start + 1); - const end = rest.findIndex(line => /^## /.test(line)); - return rest.slice(0, end === -1 ? undefined : end).join('\n'); -} - -function tableRows(body: string, firstCell: RegExp): string[][] { - return body - .split('\n') - .filter(line => line.startsWith('|')) - .map(line => line.split('|').slice(1, -1).map(cell => cell.trim())) - .filter(cells => firstCell.test(cells[0] ?? '')); -} - -describe('data-pipeline Rust migration evaluation document', () => { - test('design/README.md links to the evaluation and the link resolves', () => { - const readme = readFileSync(designReadmePath, 'utf8'); - expect(readme).toContain('](data-pipeline/rust-migration-evaluation.md)'); - expect(existsSync(evalPath)).toBe(true); - }); - - test('contains all seven required sections in order', () => { - const headings = doc.split('\n').filter(line => /^## \d\./.test(line)); - expect(headings.map(h => h.match(/^## (\d)\./)![1])).toEqual(['1', '2', '3', '4', '5', '6', '7']); - expect(headings[0]).toMatch(/Inventory/); - expect(headings[1]).toMatch(/Rust/); - expect(headings[2]).toMatch(/Workload Classification/); - expect(headings[3]).toMatch(/Options Comparison/); - expect(headings[4]).toMatch(/Compliance/); - expect(headings[5]).toMatch(/Recommendation/); - expect(headings[6]).toMatch(/Not Verified/); - }); - - test('inventory covers the T-89/T-105 CLI, T-116 TSV exporter, T-117 raw-BSON exporter and web-api coupling', () => { - const inventory = section(/^## 1\./); - for (const needle of ['T-89', 'T-105', 'T-116', 'T-117', 'run-security-master.ts', 'export-curate-inputs.ts', 'export-raw-bson.ts', '{data-pipeline_exchanges}', '{data-pipeline_symbols}', 'getFullQueueName', '@stock-bot/types', 'mongoReadOnly: true', 'assertEnvironmentSafety()']) { - expect(inventory).toContain(needle); - } - // The commands that make the counts reproducible are printed verbatim. - expect(inventory).toContain("find \"apps/stock/data-pipeline/src/$area\" -type f -name '*.ts'"); - }); - - test('every path referenced by the inventory commands exists', () => { - const inventory = section(/^## 1\./); - const block = inventory.match(/```bash\n([\s\S]*?)```/)![1]!; - for (const area of ['security-master', 'normalization', 'handlers', 'repositories', 'routes', 'types']) { - expect(existsSync(join(repoRoot, 'apps/stock/data-pipeline/src', area))).toBe(true); - } - const paths = new Set(block.match(/(?:apps|test|tools)\/[\w./-]+/g) ?? []); - expect(paths.size).toBeGreaterThan(0); - for (const path of paths) { - expect({ path, exists: existsSync(join(repoRoot, path)) }).toEqual({ path, exists: true }); - } - }); - - test('per-area inventory rows sum to the stated src/ total', () => { - const rows = tableRows(section(/^## 1\./), /^`(security-master|normalization|handlers|repositories|routes|types)\/`$|^`index\.ts`$|Total/); - const areas = rows.filter(r => !/Total/.test(r[0]!)); - const total = rows.find(r => /Total/.test(r[0]!))!; - expect(areas).toHaveLength(7); - const sum = (col: number) => areas.reduce((acc, r) => acc + (Number.isNaN(num(r[col]!)) ? 0 : num(r[col]!)), 0); - expect(sum(1)).toBe(num(total[1]!)); - expect(sum(2)).toBe(num(total[2]!)); - // pipeline-safety.test.ts is attributed to handlers/ and shared with repositories/ (counted once). - expect(sum(3)).toBe(num(total[3]!)); - expect(sum(4)).toBe(num(total[4]!)); - }); - - test('curate-etl module groups sum to the stated Rust total and the non-test/test split', () => { - const rows = tableRows(section(/^## 2\./), /./).filter(r => /^\d/.test(r[1]?.replace(/\*/g, '') ?? '')); - const total = rows.find(r => /Total/.test(r[0]!))!; - const groups = rows.filter(r => r !== total); - const tests = groups.find(r => /test modules/.test(r[0]!))!; - const files = groups.reduce((acc, r) => acc + num(r[1]!), 0); - const loc = groups.reduce((acc, r) => acc + num(r[2]!), 0); - expect(files).toBe(num(total[1]!)); - expect(loc).toBe(num(total[2]!)); - expect(total[3]).toContain(`${files - num(tests[1]!)} non-test files (${(loc - num(tests[2]!)).toLocaleString('en-US')} LOC)`); - expect(total[3]).toContain(`${num(tests[1]!)} test files (${num(tests[2]!).toLocaleString('en-US')} LOC)`); - }); - - test('derived figures in the brief are arithmetically consistent', () => { - // 88.1% of src/ LOC is security-master/. - expect(doc).toContain('88.1%'); - expect(((17_924 / 20_349) * 100).toFixed(1)).toBe('88.1'); - // rayon write speedup from the dated local re-run. - expect(doc).toContain('4.72x'); - expect((445.79 / 94.42).toFixed(2)).toBe('4.72'); - // Scratch estimates are binary GiB: docs x bytes/doc / 2^30, total I/O = 2x peak. - const gib = (docs: number, bytes: number) => Math.round((docs * bytes) / 2 ** 30); - expect([gib(845.7e6, 161.7), gib(845.7e6, 285.6)]).toEqual([127, 225]); - expect([gib(3.40e9 + 173.3e6, 150), gib(3.40e9 + 173.3e6, 250)]).toEqual([499, 832]); - expect(doc).toContain('~127–225 GiB'); - expect(doc).toContain('~255–450 GiB'); - expect(doc).toContain('~499–832 GiB'); - expect(doc).toContain('~998–1,664 GiB'); - expect(doc).not.toMatch(/\d\s?GB peak/); - }); - - test('every README-sourced benchmark row quotes figures present in the cited README', () => { - const rows = tableRows(section(/^## 2\./), /./).filter(r => /README\.md/.test(r[1] ?? '')); - expect(rows.length).toBeGreaterThanOrEqual(15); - for (const [name, source, command, result] of rows) { - const readme = source!.includes('tools/curate-etl/README.md') ? curateReadme : pipelineReadme; - // Each row states a date or explicitly says the README omits one. - expect({ name, dated: /\d{4}-\d{2}-\d{2}|date omitted/.test(source!) }).toEqual({ name, dated: true }); - // The command is copied in full (no ellipsis abbreviations) and appears in the README. - const cmd = command!.replace(/`/g, ''); - expect({ name, abbreviated: cmd.includes('...') || cmd.includes('…') }).toEqual({ name, abbreviated: false }); - const bin = cmd.match(/-- (\S+)/)?.[1] ?? cmd.match(/(\S+\.(?:test\.)?ts)/)?.[1]; - expect({ name, bin, inReadme: readme.includes(bin!) }).toEqual({ name, bin, inReadme: true }); - // Every millisecond figure in the bolded result appears verbatim in the README. - const bold = (result!.match(/\*\*([^*]+)\*\*/g) ?? []).join(' '); - for (const ms of bold.match(/[\d,]+\.\d+(?= ms)/g) ?? []) { - expect({ name, ms, inReadme: readme.includes(ms) || readme.includes(ms.replace(/,/g, '')) }).toEqual({ name, ms, inReadme: true }); - } - } - }); - - test('the only non-README benchmark is a labelled local synthetic re-run, never quant or live Mongo', () => { - const rows = tableRows(section(/^## 2\./), /^`/).filter(r => r.length === 4 && !/README\.md/.test(r[1]!)); - expect(rows).toHaveLength(1); - const [, source, command] = rows[0]!; - expect(source).toMatch(/Local sandbox re-run/); - expect(source).toMatch(/2026-11-29/); - expect(source).toMatch(/synthetic/); - expect(command).toContain('--offline'); - expect(section(/^## 2\./)).toContain('Zero Live QA MongoDB or `quant` Runs'); - }); - - test('options table compares at least three options across the required dimensions', () => { - const body = section(/^## 4\./); - const header = body.split('\n').find(line => line.startsWith('| Dimension'))!; - expect(header.match(/Option [A-Z]/g)!.length).toBeGreaterThanOrEqual(3); - for (const dim of ['Estimated Effort', 'New Rust Crates Required', 'Expected Runtime', 'Key Risks', 'Impact on M2']) { - expect(body).toContain(dim); - } - expect(body).toMatch(/End-to-end wall-time speedup is unmeasured/); - }); - - test('compliance matrix covers D1–D12 and QA safety rules for every option', () => { - const body = section(/^## 5\./); - for (let d = 1; d <= 12; d++) { - const row = tableRows(body, new RegExp(`^\\*\\*D${d}\\*\\*`)); - expect({ d, rows: row.length, cells: row[0]?.length }).toEqual({ d, rows: 1, cells: 4 }); - } - expect(body).toMatch(/Reopens §4 layer table/); - for (const needle of ['studio_stock_bot_read', 'trading_admin', 'stock_bot_safety*']) { - expect(body).toContain(needle); - } - }); - - test('gives exactly one recommendation, director-gated follow-ups and a non-port list', () => { - const body = section(/^## 6\./); - expect(body.match(/\*\*Select Option [A-C]\.\*\*/g)).toEqual(['**Select Option B.**']); - expect(body).toMatch(/Director-Gated — Not Yet Queued or Enacted/); - expect(body.match(/^\d+\. \*\*/gm)!.length).toBeGreaterThanOrEqual(3); - expect(body).toContain('### What Should NOT Be Ported to Rust'); - }); - - test('every relative Markdown link in the brief resolves', () => { - const links = [...doc.matchAll(/\]\(([^)#\s]+)(?:#[^)]*)?\)/g)].map(m => m[1]!).filter(l => !/^[a-z]+:/i.test(l)); - for (const link of links) { - const target = resolve(dirname(evalPath), link); - expect({ link, exists: existsSync(target) }).toEqual({ link, exists: true }); - } - }); -}); diff --git a/test/unit/m2-baseline-report-doc.test.ts b/test/unit/m2-baseline-report-doc.test.ts deleted file mode 100644 index ca0504ba..00000000 --- a/test/unit/m2-baseline-report-doc.test.ts +++ /dev/null @@ -1,178 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { existsSync, readFileSync } from 'node:fs'; -import { join } from 'node:path'; - -// Guards the T-128 M2.0 baseline report (design/m2-baseline-report.md) against silent drift: it is -// the gate evidence the director reads before M2 starts, so its provenance SHAs, gate commands, -// exit codes and failure accounting must stay complete and internally consistent. Live repository -// facts it records (bun.lock contents, studio.config.json paths) are deliberately not pinned here: -// they are a point-in-time snapshot that M2 work is expected to change. -const repoRoot = join(import.meta.dir, '..', '..'); -const reportPath = join(repoRoot, 'design/m2-baseline-report.md'); -const doc = readFileSync(reportPath, 'utf8'); - -const M1_SHA = 'd52aa20bff3f5c259fb6e2bcfc2d3a78ad5224b1'; -const MASTER_SHA = '56b73b7e663d293079ab7bac264950dfa7a68b00'; -const STUDIO_TEST_COMMAND = - 'bun --env-file=/home/boki/.studio/test-env/stock-bot.env test && CARGO_BUILD_JOBS=2 cargo test --workspace --lib --offline'; - -function section(title: RegExp): string { - const lines = doc.split('\n'); - const start = lines.findIndex(line => /^## /.test(line) && title.test(line)); - expect(start).toBeGreaterThan(-1); - const rest = lines.slice(start + 1); - const end = rest.findIndex(line => /^## /.test(line)); - return rest.slice(0, end === -1 ? undefined : end).join('\n'); -} - -function subsection(body: string, title: RegExp): string { - const lines = body.split('\n'); - const start = lines.findIndex(line => /^### /.test(line) && title.test(line)); - expect(start).toBeGreaterThan(-1); - const rest = lines.slice(start + 1); - const end = rest.findIndex(line => /^### /.test(line)); - return rest.slice(0, end === -1 ? undefined : end).join('\n'); -} - -function tableRows(body: string): string[][] { - return body - .split('\n') - .filter(line => line.startsWith('|') && !/^\|\s*-/.test(line)) - .map(line => line.split('|').slice(1, -1).map(cell => cell.trim())) - .slice(1); // drop header row -} - -describe('M2 baseline verification report (T-128)', () => { - test('exists and leads with an explicit GREEN verdict and zero real failures', () => { - expect(existsSync(reportPath)).toBe(true); - const verdictLine = doc.split('\n').find(line => line.startsWith('**Verdict:**')); - expect(verdictLine).toBeDefined(); - expect(verdictLine).toContain('GREEN'); - expect(verdictLine).toContain('0 real failures'); - }); - - test('provenance records full M1 and master SHAs and the ancestry check exiting 0', () => { - const provenance = section(/^## 1\./); - expect(provenance).toContain(M1_SHA); - expect(provenance).toContain(MASTER_SHA); - const ancestry = tableRows(subsection(provenance, /Ancestry/)); - expect(ancestry.length).toBeGreaterThan(0); - for (const [command, , exitCode] of ancestry) { - expect(command).toContain(`git merge-base --is-ancestor ${M1_SHA} `); - expect(exitCode).toBe('`0`'); - } - expect(ancestry.some(([command]) => command!.includes(MASTER_SHA))).toBe(true); - }); - - test('sandbox git errors are preserved as exit 128, not reported as passes', () => { - const rows = tableRows(subsection(section(/^## 1\./), /Sandbox `git`/)); - expect(rows.map(r => r[0])).toEqual([ - '`git rev-parse HEAD`', - `\`git merge-base --is-ancestor ${M1_SHA} HEAD\``, - ]); - for (const row of rows) { - expect(row[1]).toBe('`128`'); - expect(row[2]).toContain('fatal:'); - } - }); - - test('every AGENTS.md sandbox gate is listed with exit code 0 and zero failures', () => { - const rows = tableRows(section(/^## 2\./)); - const gates = [ - 'bun run typecheck', - 'bun run test:contracts', - 'bun run lint:check', - 'CARGO_BUILD_JOBS=2 bun run test:native', - 'bun run test:utils', - 'bun run test:calculations', - 'CARGO_BUILD_JOBS=2 cargo test --workspace --lib --offline', - ]; - for (const gate of gates) { - const row = rows.find(cells => cells[0]!.startsWith(`\`${gate}\``)); - expect(row, gate).toBeDefined(); - expect(row![1]).toBe('`0`'); - expect(row![2]).toMatch(/^PASS/); - expect(row![2]).toMatch(/0 (errors|fail|failed)/); - } - }); - - test('sandbox failure classification sums to the reported 40 failures, all sandbox-only', () => { - const triage = section(/^## 3\./); - expect(triage).toMatch(/`40 fail`/); - expect(triage).toMatch(/\*\*Real failures:\*\* \*\*`0`\*\*/); - const rows = tableRows(subsection(triage, /Failure Classification Summary/)); - expect(rows).toHaveLength(10); - - let total = 0; - let gitBoundary = 0; - let postgresBoundary = 0; - for (const [file, fails, errorText, classification] of rows) { - const path = file!.replace(/`/g, ''); - expect(existsSync(join(repoRoot, path)), path).toBe(true); - const count = Number(fails!.match(/^(\d+)/)![1]); - total += count; - expect(classification).toContain('(a) Expected sandbox-only'); - if (/stock_bot_safety/.test(errorText!)) { - expect(path.startsWith('test/postgres/')).toBe(true); - postgresBoundary += count; - } else { - expect(errorText).toMatch(/git|Cannot inspect tracked files/); - gitBoundary += count; - } - } - expect(total).toBe(40); - expect(gitBoundary).toBe(38); - expect(postgresBoundary).toBe(2); - }); - - test('individual failing test names match the per-file counts in the classification table', () => { - const triage = section(/^## 3\./); - const summary = new Map( - tableRows(subsection(triage, /Failure Classification Summary/)).map(([file, fails]) => [ - file!.replace(/`/g, ''), - Number(fails!.match(/^(\d+)/)![1]), - ]), - ); - const lines = subsection(triage, /Individual Failing Test Names/).split('\n'); - const listed = new Map(); - let current: string | undefined; - for (const line of lines) { - const header = line.match(/^\d+\. \*\*`([^`]+)`\*\* \((\d+) fails?;/); - if (header) { - current = header[1]!; - expect(Number(header[2])).toBe(summary.get(current)!); - listed.set(current, []); - continue; - } - const name = line.match(/^\s+- `(.+)`$/); - if (name && current) {listed.get(current)!.push(name[1]!);} - } - expect([...listed.keys()].sort()).toEqual([...summary.keys()].sort()); - for (const [file, names] of listed) { - expect(names.length, file).toBe(summary.get(file)!); - expect(new Set(names).size, file).toBe(names.length); - } - }); - - test("Studio's authoritative build and test commands are recorded verbatim with exit 0", () => { - const rows = tableRows(section(/^## 4\./)); - const build = rows.find(r => r[0]!.includes('Build')); - const tests = rows.find(r => r[0]!.includes('Test')); - expect(build?.[2]).toBe('`bun run build`'); - expect(build?.[3]).toBe('`0`'); - expect(tests?.[2]).toBe(`\`${STUDIO_TEST_COMMAND}\``); - expect(tests?.[3]).toBe('`0`'); - for (const row of [build!, tests!]) {expect(row[4]).toContain('PASS');} - }); - - test('records all three M2 planning facts', () => { - const facts = section(/^## 5\./); - expect(facts).toContain('`@modelcontextprotocol/sdk` is **not present** in `bun.lock`'); - expect(facts).toContain('`crates.io`, `index.crates.io`, and `static.crates.io`'); - expect(facts).toContain('`python/tests/test_stockbot_sdk.py`'); - expect(facts).toContain('**is not invoked**'); - expect(facts).toContain('`docs/` does not exist'); - expect(facts).toContain('`design/MILESTONES.md` lines 83–103'); - expect(facts).toContain('left untouched'); - }); -}); diff --git a/test/unit/m2-completion-audit-doc.test.ts b/test/unit/m2-completion-audit-doc.test.ts deleted file mode 100644 index 66017991..00000000 --- a/test/unit/m2-completion-audit-doc.test.ts +++ /dev/null @@ -1,175 +0,0 @@ -import { existsSync, readFileSync } from 'node:fs'; -import { join } from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { describe, expect, test } from 'bun:test'; - -// Guards the T-204 M2 completion audit (design/m2-completion-audit.md) against -// citation rot: every repo path it cites must resolve, every symbol it reports as -// landed must still live in the file it names, and the report must keep host-only -// verification marked pending. Gaps the audit reports as missing are deliberately -// NOT asserted, so landing an M2 fix never breaks this test. - -const repoRoot = fileURLToPath(new URL('../../', import.meta.url)); -const audit = readFileSync(join(repoRoot, 'design/m2-completion-audit.md'), 'utf8'); -const designIndex = readFileSync(join(repoRoot, 'design/README.md'), 'utf8'); - -// Cited as the gap itself (absent today), as already-retired code, as a sandbox env -// note, or as the stale pre-rename docs/ location. -const CITED_AS_ABSENT = new Set([ - 'scripts/research-copilot-mcp.ts', - 'apps/stock/analytics', - 'python/.venv', - 'docs', - 'docs/', - 'docs/*.md', -]); - -function expandBraces(path: string): string[] { - const match = /^(.*)\{([^}]+)\}(.*)$/.exec(path); - if (!match) {return [path];} - const [, prefix, options, suffix] = match; - return options!.split(',').flatMap((option) => expandBraces(`${prefix}${option}${suffix}`)); -} - -function citedRepoPaths(markdown: string): string[] { - const spans = [...markdown.matchAll(/`([^`\s]+)`/g)].map((m) => m[1]!); - const pathLike = spans.filter( - (span) => - /^(apps|libs|tools|python|scripts|design|test|database|docs)\//.test(span) || - /^[A-Za-z0-9_.-]+\.(md|json|yml)$/.test(span) - ); - return [ - ...new Set( - pathLike - // Strip `:line`, `:a-b`, and `:a-b,c` suffixes and trailing globs. - .map((span) => span.replace(/:[\d,-]+$/, '').replace(/\/\*$/, '')) - .flatMap(expandBraces) - ), - ].sort(); -} - -describe('design/m2-completion-audit.md citations', () => { - test('cites only repo paths that exist, except those it reports as absent', () => { - const cited = citedRepoPaths(audit); - expect(cited.length).toBeGreaterThan(40); - - const missing = cited.filter((p) => !CITED_AS_ABSENT.has(p) && !existsSync(join(repoRoot, p))); - expect(missing).toEqual([]); - }); - - test('docs/ stays absent so the documentation path-drift note holds', () => { - expect(existsSync(join(repoRoot, 'docs'))).toBe(false); - expect(existsSync(join(repoRoot, 'design/MILESTONES.md'))).toBe(true); - }); - - // Symbols the audit reports as LANDED, keyed by the file it attributes them to. - const landedSymbols: Array<[file: string, symbol: string | RegExp]> = [ - ['libs/research/src/mcp/copilot-server.ts', 'createResearchCopilotMcpServer'], - ['libs/research/src/mcp/host/stdio-host.ts', 'runResearchCopilotStdioHost'], - ['libs/data/postgres/src/research-copilot-executor.ts', 'openResearchCopilotExecutor'], - ['libs/data/duckdb/src/research-copilot-store.ts', 'openResearchCopilotStore'], - ['libs/data/duckdb/src/research-copilot-store.ts', 'vaultOperatorAuthorized: false'], - ['libs/research/src/mcp/tools/query-data.ts', 'createQueryDataTool'], - ['libs/research/src/notebook-snapshot.ts', 'exportNotebookSnapshot'], - ['libs/research/src/notebook-snapshot-node.ts', 'exportNotebookSnapshot'], - ['libs/research/src/market-data-store-duckdb.ts', 'fundamentalsAsOf'], - ['libs/research/src/market-data-store-routed.ts', 'createRoutedMarketDataStore'], - ['libs/research/src/market-data-store-questdb.ts', 'createQuestDbIntradayBarsReader'], - ['libs/research/src/feature-library.ts', 'registerSignal'], - ['libs/research/src/feature-library.ts', 'runFeatureBatch'], - ['libs/research/src/feature-library.ts', 'export const RET_1D_V1'], - ['libs/research/src/feature-library.ts', 'export const FEATURE_INPUT_DATASETS'], - ['libs/data/questdb/src/schema.ts', 'M2_INTRADAY_SCHEMAS'], - ['libs/data/questdb/src/schema.ts', 'getM2IntradayDDL'], - // The schema is declarative; DDL keywords are rendered from these fields. - ['libs/data/questdb/src/schema.ts', "capacity: 65536, cache: false"], - ['libs/data/questdb/src/schema.ts', "partitionBy: 'MONTH'"], - ['libs/data/questdb/src/schema.ts', 'dedupUpsertKeys'], - ['tools/curate-etl/src/cli.rs', 'SendIlp('], - ['tools/curate-etl/src/cli.rs', 'CurateFundamentals('], - ['tools/curate-etl/src/cli.rs', 'CuratePosts('], - ['tools/curate-etl/src/cli.rs', 'CurateMacro('], - ['tools/curate-etl/src/cli.rs', 'CurateBars1m('], - ['tools/curate-etl/src/cli.rs', 'CurateFx1m('], - ['tools/curate-etl/src/main.rs', 'run_send_ilp('], - ['tools/curate-etl/src/mongo_stream.rs', 'pub enum SourceCollection'], - ['tools/curate-etl/src/run_curate_posts.rs', 'EventsDatasetExists'], - ['tools/curate-etl/src/run_curate_qm_bars_1m.rs', /pub fn run_curate_qm_bars_1m\b/], - ['tools/curate-etl/src/ilp_send_tests.rs', 'fn tcp_sends_separate_shards_and_half_closes'], - [ - 'tools/curate-etl/src/fundamentals_tests.rs', - 'fn restatement_of_q1_after_q2_updates_q1_and_ttm_without_overwriting_q2', - ], - [ - 'tools/curate-etl/src/run_curate_bars_1m_tests.rs', - 'fn split_boundary_nvda_and_nexm_match_raw_bars_1d_closes', - ], - ['libs/data/duckdb/test/duckdb-market-data-store.test.ts', 'restatement non-overwrite'], - ['docker-compose.quant.yml', 'hard: 1048576'], - ['docker-compose.quant.yml', 'QDB_RAM_USAGE_LIMIT_BYTES=21474836480'], - ['database/postgres/init/37-research-findings.sql', 'provider_caveats'], - ['database/postgres/init/36-trial-ledger.sql', 'vault_evaluations'], - ]; - - test.each(landedSymbols)('%s contains %p as the audit reports', (file, symbol) => { - const source = readFileSync(join(repoRoot, file), 'utf8'); - if (typeof symbol === 'string') {expect(source).toContain(symbol);} - else {expect(source).toMatch(symbol);} - }); - - test('every MCP tool the audit counts is registered in the copilot server', () => { - const server = readFileSync(join(repoRoot, 'libs/research/src/mcp/copilot-server.ts'), 'utf8'); - const tools = ['search_symbols', 'query_data', 'analyze_signal', 'event_study', 'file_finding', 'read_knowledge']; - for (const tool of tools) {expect(server).toContain(`'${tool}'`);} - expect(audit).toContain('6 MCP tools'); - }); - - test('the synthetic split fixture still documents the observed-data comparison as open', () => { - // The audit's EC-3 "synthetic only" status rests on this scope note. - const fixture = readFileSync(join(repoRoot, 'tools/curate-etl/src/run_curate_bars_1m_tests.rs'), 'utf8'); - expect(fixture).toMatch(/Does NOT prove .* against retained `bars_1d` data/); - expect(audit).toMatch(/OPEN \(Synthetic Only\)/); - }); -}); - -describe('design/m2-completion-audit.md structure and honesty', () => { - test('holds M3 and covers every section the task requires', () => { - expect(audit).toMatch(/HOLD M3/); - expect(audit).toMatch(/^## 1\. Verification Gate Results/m); - expect(audit).toMatch(/^## 2\. M2 Deliverables & Exit Criteria Matrix/m); - expect(audit).toMatch(/^## 3\. Candidate Causes/m); - expect(audit).toMatch(/^## 4\. Concrete Blockers Needing Director Decisions/m); - expect(audit).toMatch(/^## 5\. M3 Readiness Mapping/m); - }); - - test('covers all four M2 deliverables and all three M2 exit criteria', () => { - for (const area of ['M2.1', 'M2.2', 'M2.3', 'M2.4']) {expect(audit).toContain(`**${area}**`);} - for (const ec of ['EC-1', 'EC-2', 'EC-3']) {expect(audit).toContain(`**${ec}:**`);} - for (const ec of ['M3 EC-1', 'M3 EC-2', 'M3 EC-3']) {expect(audit).toContain(`**${ec}:**`);} - }); - - test('keeps host-only verification pending and parking causes unattributed', () => { - expect(audit).toMatch(/\|\s*\*\*PENDING\*\*\s*\|/); - expect(audit).toContain('none of the four items below can be attributed to a specific parked task'); - expect(audit).not.toMatch(/EC-3[^|]*\|\s*\*\*SATISFIED/); - }); - - test('asks the director three decisions, each with a recommendation', () => { - const decisions = audit.split(/^## 4\./m)[1]!.split(/^## 5\./m)[0]!; - expect(decisions.match(/^\d\. \*\*/gm)?.length).toBe(3); - expect(decisions.match(/\*Recommended:\*/g)?.length).toBe(3); - }); - - test('carries the teData regime-filter-only limit into macro follow-ups', () => { - expect(audit).toContain('design/DATA-CONTRACTS.md:26'); - expect(readFileSync(join(repoRoot, 'design/DATA-CONTRACTS.md'), 'utf8').split('\n')[25]).toContain( - 'final-revised values only' - ); - }); - - test('is indexed exactly once in design/README.md', () => { - const rows = designIndex.split('\n').filter((line) => line.includes('(m2-completion-audit.md)')); - expect(rows).toHaveLength(1); - expect(rows[0]).toMatch(/^\| \*\*\[m2-completion-audit\.md\]\(m2-completion-audit\.md\)\*\* \|.*\|.*\|$/); - }); -}); diff --git a/test/unit/mongodb-read-only.test.ts b/test/unit/mongodb-read-only.test.ts index 4fc604aa..27e94434 100644 --- a/test/unit/mongodb-read-only.test.ts +++ b/test/unit/mongodb-read-only.test.ts @@ -1,5 +1,5 @@ import { describe, expect, mock, test } from 'bun:test'; -import { BSON, MongoClient } from 'mongodb'; +import { MongoClient } from 'mongodb'; import { getLogger, setLoggerConfig } from '@stock-bot/logger'; import { MongoDBClient } from '@stock-bot/mongodb'; @@ -1196,82 +1196,4 @@ describe('MongoDBClient read-only mode (offline)', () => { expect(collectionStub.insertOne).toHaveBeenCalledTimes(2); expect(dbStub.createCollection).toHaveBeenCalledTimes(1); }); - - test('forwards find(filter, { raw: true, batchSize, limit }) through read-only collection/cursor and yields raw BSON buffers untouched', async () => { - const logger = getLogger('mongodb-read-only-raw-find-test'); - const rawFrames = [ - Buffer.from(BSON.serialize({ eodSearchCode: 'AAPL.US', date: '2025-01-02', close: 250.5 })), - Buffer.from(BSON.serialize({ eodSearchCode: 'RY.TO', date: '2025-01-02', close: 175.25 })), - ]; - const closeMock = mock(async () => {}); - const rawCursorStub = { - close: closeMock, - [Symbol.asyncIterator]: async function* () { - for (const frame of rawFrames) { - yield frame; - } - }, - }; - const findCalls: Array<{ filter: unknown; options: unknown }> = []; - const collectionStub = { - collectionName: 'eodPrices', - dbName: 'stock', - namespace: 'stock.eodPrices', - find: mock((filter: unknown, options: unknown) => { - findCalls.push({ filter, options }); - return rawCursorStub; - }), - insertOne: mock(async () => ({ insertedId: 'id-1' })), - drop: mock(async () => true), - }; - const dbStub = { - databaseName: 'stock', - namespace: 'stock', - collection: mock(() => collectionStub), - }; - - const client = new MongoDBClient( - { host: '127.0.0.1', port: 1, database: 'stock', readOnly: true }, - logger - ); - Object.assign(client, { - client: { db: mock(() => dbStub) }, - db: dbStub, - isConnected: true, - }); - - const collection = client.getCollection('eodPrices'); - const cursor = collection.find( - { eodSearchCode: 'CAD.FOREX' }, - { raw: true, batchSize: 128, limit: 2 } - ); - - expect(findCalls).toEqual([ - { - filter: { eodSearchCode: 'CAD.FOREX' }, - options: { raw: true, batchSize: 128, limit: 2 }, - }, - ]); - - const yielded: unknown[] = []; - try { - for await (const frame of cursor) { - yielded.push(frame); - } - } finally { - await cursor.close(); - } - - expect(yielded).toHaveLength(2); - expect(yielded[0]).toBe(rawFrames[0]); - expect(yielded[1]).toBe(rawFrames[1]); - expect(yielded[0]).toBeInstanceOf(Uint8Array); - expect(closeMock).toHaveBeenCalledTimes(1); - - // Write and DDL guards remain intact on the same read-only collection wrapper - expect(() => collection.insertOne({ a: 1 })).toThrow(/read-only mode/); - expect(() => collection.drop()).toThrow(/read-only mode/); - expect(collectionStub.insertOne).not.toHaveBeenCalled(); - expect(collectionStub.drop).not.toHaveBeenCalled(); - }); }); diff --git a/test/unit/security-master-export-curate-inputs-parity.test.ts b/test/unit/security-master-export-curate-inputs-parity.test.ts deleted file mode 100644 index 88052c91..00000000 --- a/test/unit/security-master-export-curate-inputs-parity.test.ts +++ /dev/null @@ -1,740 +0,0 @@ -/** - * QA differential tests for the curate-etl TSV exporter (T-116). - * - * - The streaming PostgreSQL exporter (`exportCurateInputs`) and the pure core - * (`formatProviderMappingTsv`, `formatListingCurrenciesTsv`, `buildDelistingExportRows` + - * `formatDelistingsTsv`) must produce byte-identical TSVs and identical skip stats on the same - * seeded random security master, for every chunk size (including exact chunk-boundary sizes). - * - Every emitted `delistings.tsv` row must resolve under the exact Rust `curate-corporate-actions` - * lookup rules (`cursor.resolve(delist_date) == from_listing_id` for terminal rows, - * `resolve_for_listing_on_or_before` + successor `resolve(effective_date)` for OTC rows) against the - * emitted `provider_mapping.tsv`, so the exporter never feeds Rust a row it would drop. - */ -import { mkdtemp, readFile, rm } from 'node:fs/promises'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import { afterEach, describe, expect, test } from 'bun:test'; -import { - buildDelistingExportRows, - CURATE_INPUT_FILES, - exportCurateInputs, - formatDelistingsTsv, - formatListingCurrenciesTsv, - formatProviderMappingTsv, - type ContinuityExportSourceRow, - type ListingDelistingSourceRow, - type ProviderMappingExportRow, - type SecurityMasterQueryable, - type SecurityMasterQueryResult, -} from '../../apps/stock/data-pipeline/src/security-master'; -import { compareAscii } from '../../apps/stock/data-pipeline/src/security-master/exchange-pass1'; - -const tempDirs: string[] = []; -afterEach(async () => { - for (const dir of tempDirs.splice(0).reverse()) { - await rm(dir, { recursive: true, force: true }); - } -}); - -async function makeTempDir(): Promise { - const dir = await mkdtemp(join(tmpdir(), 'curate-inputs-parity-')); - tempDirs.push(dir); - return dir; -} - -/** mulberry32: small deterministic PRNG so every run sees the same dataset. */ -function createRng(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; - }; -} - -const DAY_MS = 86_400_000; -const EPOCH_2010 = Date.UTC(2010, 0, 1); - -function dayToYmd(day: number): string { - return new Date(EPOCH_2010 + day * DAY_MS).toISOString().slice(0, 10); -} - -function ymdToDay(ymd: string): number { - return Math.round((Date.parse(`${ymd}T00:00:00Z`) - EPOCH_2010) / DAY_MS); -} - -interface DbListing { - listing_id: number; - currency: string; - listed_to: string | null; - delist_reason: string | null; - terminal_return: string | null; -} - -interface DbContinuity { - from_listing_id: number; - to_listing_id: number; - effective_date: string; - kind: string; -} - -interface DbMapping { - source: string; - source_id: string; - valid_from: string; - valid_to: string | null; - listing_id: number; -} - -interface Dataset { - listings: DbListing[]; - continuities: DbContinuity[]; - mappings: DbMapping[]; -} - -/** - * Builds a seeded random security master that satisfies the DB invariants the exporter relies on - * (unique PKs, non-overlapping `(source, source_id)` ranges, at most one OTC continuity per - * `from_listing_id`), with ticker reuse, OTC chains, terminal returns as PG `numeric::text`, - * missing mappings, mappings that end before `listed_to`, and successors starting late. - */ -function buildRandomDataset(seed: number, listingCount: number): Dataset { - const rng = createRng(seed); - const pick = (items: readonly T[]): T => items[Math.floor(rng() * items.length)] as T; - const listings: DbListing[] = []; - const continuities: DbContinuity[] = []; - const mappings: DbMapping[] = []; - // Per (source, source_id): last occupied end day (null = open-ended) to keep ranges disjoint. - const tickerEnds = new Map(); - const tickerPool = Array.from( - { length: Math.max(4, Math.floor(listingCount / 3)) }, - (_, i) => `T${String(i).padStart(3, '0')}${pick(['', '.A', '-B', 'Q'])}` - ); - - const addMapping = ( - source: string, - listingId: number, - fromDay: number, - toDay: number | null - ): boolean => { - for (let attempt = 0; attempt < 6; attempt++) { - const sourceId = pick(tickerPool); - const key = `${source}\u0000${sourceId}`; - if (tickerEnds.has(key)) { - const end = tickerEnds.get(key); - if (end === null || end === undefined || end >= fromDay) { - continue; - } - } - tickerEnds.set(key, toDay); - mappings.push({ - source, - source_id: sourceId, - valid_from: dayToYmd(fromDay), - valid_to: toDay === null ? null : dayToYmd(toDay), - listing_id: listingId, - }); - return true; - } - return false; - }; - - // Allocate listing ids with gaps so keyset pagination over non-contiguous ids is exercised. - const ids: number[] = []; - let nextId = 1; - for (let i = 0; i < listingCount; i++) { - nextId += 1 + Math.floor(rng() * 3); - ids.push(nextId); - } - - // Listings are generated in chronological "start" order so reuse can find free tickers. - const otcSuccessorIds = new Set(); - for (let i = 0; i < ids.length; i++) { - const listingId = ids[i] as number; - if (otcSuccessorIds.has(listingId)) { - continue; - } - const startDay = Math.floor(rng() * 3000); - const roll = rng(); - const currency = pick(['USD', 'USD', 'CAD']); - - if (roll < 0.35) { - listings.push({ - listing_id: listingId, - currency, - listed_to: null, - delist_reason: 'active', - terminal_return: null, - }); - addMapping('qm', listingId, startDay, null); - addMapping('eod', listingId, startDay, null); - continue; - } - - const endDay = startDay + 30 + Math.floor(rng() * 400); - if (roll < 0.55 && i + 1 < ids.length) { - // OTC transfer to the next id (successor), possibly ending in a terminal cancellation. - const successorId = ids[i + 1] as number; - otcSuccessorIds.add(successorId); - const gap = Math.floor(rng() * 20); - const effectiveDay = endDay + gap; - listings.push({ - listing_id: listingId, - currency, - listed_to: dayToYmd(endDay), - delist_reason: 'moved_to_otc', - terminal_return: null, - }); - continuities.push({ - from_listing_id: listingId, - to_listing_id: successorId, - effective_date: dayToYmd(effectiveDay), - kind: 'otc_delist_transfer', - }); - if (rng() < 0.9) { - addMapping('qm', listingId, startDay, endDay); - } - addMapping('eod', listingId, startDay, endDay); - - const successorEnd = effectiveDay + 50 + Math.floor(rng() * 200); - const successorCancelled = rng() < 0.6; - listings.push({ - listing_id: successorId, - currency, - listed_to: successorCancelled ? dayToYmd(successorEnd) : null, - delist_reason: successorCancelled ? 'bankruptcy_cancelled' : 'active', - terminal_return: successorCancelled ? '-1.000000' : null, - }); - const successorRoll = rng(); - if (successorRoll < 0.8) { - addMapping('qm', successorId, effectiveDay, successorCancelled ? successorEnd : null); - } else if (successorRoll < 0.9) { - // Successor mapping starts after effective_date -> missingSuccessorQmMapping. - addMapping('qm', successorId, effectiveDay + 3, successorCancelled ? successorEnd : null); - } - continue; - } - - if (roll < 0.85) { - const terminalReturn = pick([ - '-0.300000', - '-1.000000', - '0.000000', - '-0.000001', - '-0.550000', - '-0.123456', - ]); - const missingDate = rng() < 0.08; - listings.push({ - listing_id: listingId, - currency, - listed_to: missingDate ? null : dayToYmd(endDay), - delist_reason: pick(['unknown_involuntary', 'bankruptcy_cancelled', 'merger_cash']), - terminal_return: terminalReturn, - }); - const mappingRoll = rng(); - if (mappingRoll < 0.8) { - addMapping('qm', listingId, startDay, endDay); - } else if (mappingRoll < 0.9) { - // qm mapping ends before listed_to -> not valid on delist_date. - addMapping('qm', listingId, startDay, endDay - 5); - } - addMapping('eod', listingId, startDay, endDay); - continue; - } - - listings.push({ - listing_id: listingId, - currency, - listed_to: dayToYmd(endDay), - delist_reason: rng() < 0.5 ? null : 'unknown', - terminal_return: null, - }); - addMapping('qm', listingId, startDay, endDay); - } - - // Non-OTC continuities must be ignored by the DB query (`WHERE kind = 'otc_delist_transfer'`). - continuities.push({ - from_listing_id: ids[0] as number, - to_listing_id: ids[1] as number, - effective_date: '2015-01-02', - kind: 'ticker_change', - }); - - return { listings, continuities, mappings }; -} - -function shuffle(items: readonly T[], rng: () => number): T[] { - const out = [...items]; - for (let i = out.length - 1; i > 0; i--) { - const j = Math.floor(rng() * (i + 1)); - [out[i], out[j]] = [out[j] as T, out[i] as T]; - } - return out; -} - -/** In-memory PostgreSQL stand-in honouring the exporter's SQL contract (keyset + NO SCROLL cursor). */ -function createQueryable(data: Dataset, recordedSql: string[]): SecurityMasterQueryable { - const otc = data.continuities - .filter(c => c.kind === 'otc_delist_transfer') - .sort( - (a, b) => - a.from_listing_id - b.from_listing_id || compareAscii(a.effective_date, b.effective_date) - ); - const listings = [...data.listings].sort((a, b) => a.listing_id - b.listing_id); - const mappings = [...data.mappings].sort( - (a, b) => - compareAscii(a.source, b.source) || - compareAscii(a.source_id, b.source_id) || - compareAscii(a.valid_from, b.valid_from) - ); - let cursorOffset = -1; - - return { - async query>( - text: string, - values?: readonly unknown[] - ): Promise> { - const sql = text.replace(/\s+/g, ' ').trim(); - recordedSql.push(sql); - const rows = (r: unknown[]) => ({ rows: r as Row[] }); - if (sql.startsWith('BEGIN') || sql === 'COMMIT' || sql === 'ROLLBACK') { - return rows([]); - } - if (sql.startsWith('DECLARE ')) { - cursorOffset = 0; - return rows([]); - } - const fetch = /^FETCH FORWARD (\d+) FROM \S+$/.exec(sql); - if (fetch) { - if (cursorOffset < 0) { - throw new Error('FETCH without DECLARE'); - } - const slice = mappings.slice(cursorOffset, cursorOffset + Number(fetch[1])); - cursorOffset += slice.length; - return rows(slice); - } - if (sql.startsWith('CLOSE ')) { - cursorOffset = -1; - return rows([]); - } - if (sql.includes('FROM corporate_action_continuity')) { - if (values?.length === 1) { - return rows(otc.slice(0, values[0] as number)); - } - const [lastFrom, lastEff, limit] = values as [number, string, number]; - return rows( - otc - .filter( - c => - c.from_listing_id > lastFrom || - (c.from_listing_id === lastFrom && c.effective_date > lastEff) - ) - .slice(0, limit) - ); - } - if (sql.includes('FROM listing')) { - if (values?.length === 1) { - return rows(listings.slice(0, values[0] as number)); - } - const [lastId, limit] = values as [number, number]; - return rows(listings.filter(l => l.listing_id > lastId).slice(0, limit)); - } - throw new Error(`Unexpected SQL: ${sql}`); - }, - release: () => {}, - }; -} - -function toPure(data: Dataset): { - providerMappings: ProviderMappingExportRow[]; - delistingListings: ListingDelistingSourceRow[]; - continuities: ContinuityExportSourceRow[]; -} { - return { - providerMappings: data.mappings.map(m => ({ - source: m.source, - sourceId: m.source_id, - validFrom: m.valid_from, - validTo: m.valid_to, - listingId: m.listing_id, - })), - delistingListings: data.listings.map(l => ({ - listingId: l.listing_id, - listedTo: l.listed_to, - delistReason: l.delist_reason, - terminalReturn: l.terminal_return, - })), - continuities: data.continuities - .filter(c => c.kind === 'otc_delist_transfer') - .map(c => ({ - fromListingId: c.from_listing_id, - toListingId: c.to_listing_id, - effectiveDate: c.effective_date, - kind: c.kind, - })), - }; -} - -interface RustRange { - validFrom: number; - validTo: number | null; - listingId: number; -} - -/** Parses emitted `provider_mapping.tsv` into Rust `ProviderMappingTable` shape (sorted by valid_from). */ -function parseMappingTable(tsv: string): Map { - const table = new Map(); - for (const line of tsv.split('\n')) { - if (line.length === 0) { - continue; - } - const [source, sourceId, from, to, listingId] = line.split('\t') as [ - string, - string, - string, - string, - string, - ]; - const key = `${source}\u0000${sourceId}`; - const list = table.get(key) ?? []; - list.push({ - validFrom: ymdToDay(from), - validTo: to === '' ? null : ymdToDay(to), - listingId: Number(listingId), - }); - table.set(key, list); - } - for (const list of table.values()) { - list.sort((a, b) => a.validFrom - b.validFrom); - } - return table; -} - -/** Mirror of `ProviderMappingTable::resolve` (provider_mapping.rs). */ -function rustResolve(ranges: readonly RustRange[], day: number): number | null { - let idx = 0; - while (idx < ranges.length && (ranges[idx] as RustRange).validFrom <= day) { - idx += 1; - } - if (idx === 0) { - return null; - } - const candidate = ranges[idx - 1] as RustRange; - return candidate.validTo === null || candidate.validTo >= day ? candidate.listingId : null; -} - -/** Mirror of `resolve_for_listing_on_or_before` (curate_corporate_actions.rs). */ -function rustResolveForListingOnOrBefore( - ranges: readonly RustRange[], - day: number, - expected: number -): number | null { - for (let i = ranges.length - 1; i >= 0; i--) { - const r = ranges[i] as RustRange; - if (r.validFrom <= day && r.listingId === expected) { - return r.listingId; - } - } - return null; -} - -async function runExport(data: Dataset, chunkSize: number) { - const outDir = await makeTempDir(); - const recordedSql: string[] = []; - const result = await exportCurateInputs(createQueryable(data, recordedSql), { - outDir, - chunkSize, - }); - const read = (file: string) => readFile(join(outDir, file), 'utf8'); - return { - result, - recordedSql, - providerMapping: await read(CURATE_INPUT_FILES.providerMapping), - listingCurrencies: await read(CURATE_INPUT_FILES.listingCurrencies), - delistings: await read(CURATE_INPUT_FILES.delistings), - }; -} - -describe('exportCurateInputs streaming vs pure core parity (seeded random security master)', () => { - for (const seed of [11, 4242, 90210]) { - test(`seed ${seed}: streamed TSV bytes and skip stats equal the pure formatters for every chunk size`, async () => { - // Arrange - const data = buildRandomDataset(seed, 160); - const pure = toPure(data); - const rng = createRng(seed ^ 0x5eed); - const expectedProviderMapping = formatProviderMappingTsv(shuffle(pure.providerMappings, rng)); - const expectedListingCurrencies = formatListingCurrenciesTsv( - shuffle( - data.listings.map(l => ({ listingId: l.listing_id, currency: l.currency })), - rng - ) - ); - const built = buildDelistingExportRows( - shuffle(pure.delistingListings, rng), - shuffle(pure.continuities, rng), - shuffle(pure.providerMappings, rng) - ); - const expectedDelistings = formatDelistingsTsv(shuffle(built.rows, rng)); - const mappingRows = data.mappings.length; - const listingRows = data.listings.length; - - // Sanity: the generator really exercises every branch, otherwise parity proves little. - expect(built.stats.otcTransfersOut).toBeGreaterThan(0); - expect(built.stats.terminalDelistingsOut).toBeGreaterThan(0); - expect(built.stats.skipped.active).toBeGreaterThan(0); - expect(built.stats.skipped.noOutcome).toBeGreaterThan(0); - expect(built.stats.skipped.missingOutgoingQmMapping).toBeGreaterThan(0); - - // Act + Assert: chunk sizes include 1, a prime, exact divisors of the row counts, and max. - for (const chunkSize of [1, 7, listingRows, mappingRows, 5000]) { - const out = await runExport(data, Math.min(chunkSize, 5000)); - expect(out.providerMapping).toBe(expectedProviderMapping); - expect(out.listingCurrencies).toBe(expectedListingCurrencies); - expect(out.delistings).toBe(expectedDelistings); - - const s = out.result.delistings.stats; - expect(s.rowsOut).toBe(built.stats.rowsOut); - expect(s.otcTransfersOut).toBe(built.stats.otcTransfersOut); - expect(s.terminalDelistingsOut).toBe(built.stats.terminalDelistingsOut); - expect({ ...s.skipped, nonOtcContinuity: 0 }).toEqual({ - ...built.stats.skipped, - nonOtcContinuity: 0, - }); - expect(s.skipped.nonOtcContinuity).toBe(0); - const skipSum = Object.values(s.skipped).reduce((acc, n) => acc + n, 0); - expect(s.skippedTotal).toBe(skipSum); - expect(s.rowsIn).toBe(s.rowsOut + s.skippedTotal); - // Every non-OTC-transferred listing is accounted for exactly once, plus OTC sources. - expect(s.rowsIn).toBe(listingRows); - - expect(out.result.providerMapping.rowsIn).toBe(mappingRows); - expect(out.result.providerMapping.rowsOut).toBe(mappingRows); - expect(out.result.listingCurrencies.rowsOut).toBe(listingRows); - expect(out.result.totalBytesWritten).toBe( - Buffer.byteLength(out.providerMapping) + - Buffer.byteLength(out.listingCurrencies) + - Buffer.byteLength(out.delistings) - ); - - // Read-only contract: SELECT/cursor statements only, all inside one READ ONLY transaction. - expect(out.recordedSql[0]).toBe( - 'BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY' - ); - expect(out.recordedSql.at(-1)).toBe('COMMIT'); - for (const sql of out.recordedSql) { - expect(sql).not.toMatch( - /\b(INSERT|UPDATE|DELETE|TRUNCATE|CREATE|ALTER|DROP|GRANT|COPY)\b/i - ); - } - const fetches = out.recordedSql.filter(sql => sql.startsWith('FETCH FORWARD')); - expect(fetches.length).toBeGreaterThanOrEqual( - Math.ceil(mappingRows / Math.min(chunkSize, 5000)) - ); - for (const fetch of fetches) { - const n = Number(/FETCH FORWARD (\d+)/.exec(fetch)?.[1]); - expect(n).toBeLessThanOrEqual(5000); - } - } - }); - } - - test('every emitted delisting resolves under the Rust curate-corporate-actions lookup rules (0 drops)', async () => { - for (const seed of [11, 4242, 90210, 7]) { - // Arrange - const data = buildRandomDataset(seed, 200); - - // Act - const out = await runExport(data, 13); - const table = parseMappingTable(out.providerMapping); - - // Assert - const lines = out.delistings.split('\n').filter(line => line.length > 0); - expect(lines.length).toBe(out.result.delistings.rowsOut); - for (const line of lines) { - const fields = line.split('\t'); - expect(fields.length).toBe(5); - const [sourceId, delistDate, fromListingId, successorSourceId, terminalReturn] = fields as [ - string, - string, - string, - string, - string, - ]; - const day = ymdToDay(delistDate); - const expectedId = Number(fromListingId); - expect(Number.isInteger(expectedId) && expectedId > 0).toBe(true); - const ranges = table.get(`qm\u0000${sourceId}`) ?? []; - - if (successorSourceId === '') { - // Terminal: cursor.resolve(ex_date).filter(id == from_listing_id); terminal_return parses in [-1, 0]. - expect(rustResolve(ranges, day)).toBe(expectedId); - const parsed = Number(terminalReturn); - expect(terminalReturn).toMatch(/^-?\d+(\.\d+)?$/); - expect(parsed >= -1 && parsed <= 0).toBe(true); - const listing = data.listings.find(l => l.listing_id === expectedId); - expect(listing?.listed_to).toBe(delistDate); - expect(parsed).toBe(Number(listing?.terminal_return)); - } else { - expect(terminalReturn).toBe(''); - expect(rustResolveForListingOnOrBefore(ranges, day, expectedId)).toBe(expectedId); - const successorId = rustResolve(table.get(`qm\u0000${successorSourceId}`) ?? [], day); - const continuity = data.continuities.find( - c => c.kind === 'otc_delist_transfer' && c.from_listing_id === expectedId - ); - expect(continuity?.effective_date).toBe(delistDate); - expect(successorId).toBe(continuity?.to_listing_id ?? -1); - expect(successorId).not.toBe(expectedId); - } - } - } - }); - - test('terminal returns from PostgreSQL numeric::text are normalized to plain decimals Rust parses identically', async () => { - // Arrange - const data: Dataset = { - listings: [ - { - listing_id: 1, - currency: 'USD', - listed_to: '2023-01-03', - delist_reason: 'x', - terminal_return: '0.000000', - }, - { - listing_id: 2, - currency: 'USD', - listed_to: '2023-01-03', - delist_reason: 'x', - terminal_return: '-0.000000', - }, - { - listing_id: 3, - currency: 'USD', - listed_to: '2023-01-03', - delist_reason: 'x', - terminal_return: '-0.000001', - }, - { - listing_id: 4, - currency: 'USD', - listed_to: '2023-01-03', - delist_reason: 'x', - terminal_return: '-1.000000', - }, - { - listing_id: 5, - currency: 'USD', - listed_to: '2023-01-03', - delist_reason: 'x', - terminal_return: '-0.300000', - }, - ], - continuities: [], - mappings: [1, 2, 3, 4, 5].map(id => ({ - source: 'qm', - source_id: `L${id}`, - valid_from: '2020-01-01', - valid_to: '2023-01-03', - listing_id: id, - })), - }; - - // Act - const out = await runExport(data, 2); - - // Assert - expect(out.delistings).toBe( - [ - 'L1\t2023-01-03\t1\t\t0', - 'L2\t2023-01-03\t2\t\t0', - 'L3\t2023-01-03\t3\t\t-0.000001', - 'L4\t2023-01-03\t4\t\t-1', - 'L5\t2023-01-03\t5\t\t-0.3', - '', - ].join('\n') - ); - }); - - test('exact chunk-boundary row counts neither drop nor duplicate the last page', async () => { - // Arrange: 4 listings, 4 mappings, 2 OTC continuities with chunkSize 2 (two full pages each). - const data: Dataset = { - listings: [ - { - listing_id: 10, - currency: 'USD', - listed_to: '2023-03-10', - delist_reason: 'moved_to_otc', - terminal_return: null, - }, - { - listing_id: 11, - currency: 'USD', - listed_to: null, - delist_reason: 'active', - terminal_return: null, - }, - { - listing_id: 20, - currency: 'CAD', - listed_to: '2023-03-10', - delist_reason: 'moved_to_otc', - terminal_return: null, - }, - { - listing_id: 21, - currency: 'CAD', - listed_to: null, - delist_reason: 'active', - terminal_return: null, - }, - ], - continuities: [ - { - from_listing_id: 10, - to_listing_id: 11, - effective_date: '2023-03-28', - kind: 'otc_delist_transfer', - }, - { - from_listing_id: 20, - to_listing_id: 21, - effective_date: '2023-03-28', - kind: 'otc_delist_transfer', - }, - ], - mappings: [ - { - source: 'qm', - source_id: 'A', - valid_from: '2000-01-03', - valid_to: '2023-03-10', - listing_id: 10, - }, - { source: 'qm', source_id: 'AQ', valid_from: '2023-03-28', valid_to: null, listing_id: 11 }, - { - source: 'qm', - source_id: 'B', - valid_from: '2000-01-03', - valid_to: '2023-03-10', - listing_id: 20, - }, - { source: 'qm', source_id: 'BQ', valid_from: '2023-03-28', valid_to: null, listing_id: 21 }, - ], - }; - - // Act - const out = await runExport(data, 2); - - // Assert - expect(out.listingCurrencies).toBe('10\tUSD\n11\tUSD\n20\tCAD\n21\tCAD\n'); - expect(out.providerMapping).toBe( - 'qm\tA\t2000-01-03\t2023-03-10\t10\nqm\tAQ\t2023-03-28\t\t11\nqm\tB\t2000-01-03\t2023-03-10\t20\nqm\tBQ\t2023-03-28\t\t21\n' - ); - expect(out.delistings).toBe('A\t2023-03-28\t10\tAQ\t\nB\t2023-03-28\t20\tBQ\t\n'); - expect(out.result.delistings.stats.rowsIn).toBe(4); - expect(out.result.delistings.stats.skipped.active).toBe(2); - }); -}); diff --git a/test/unit/security-master-export-curate-inputs.test.ts b/test/unit/security-master-export-curate-inputs.test.ts deleted file mode 100644 index 9d3f728d..00000000 --- a/test/unit/security-master-export-curate-inputs.test.ts +++ /dev/null @@ -1,1619 +0,0 @@ -import { afterEach, describe, expect, test } from 'bun:test'; -import { mkdtemp, open, readdir, readFile, rename, rm, unlink, writeFile } from 'node:fs/promises'; -import { tmpdir } from 'node:os'; -import { join, resolve } from 'node:path'; -import { - initializeStockConfig, - resetStockConfig, - type StockAppConfig, -} from '@stock-bot/stock-config'; -import { - assertExportCurateInputsSafety, - buildDelistingExportRows, - CURATE_INPUT_FILES, - CURATE_INPUT_PUBLISH_LOCK, - CurateInputExportError, - DEFAULT_EXPORT_CHUNK_SIZE, - EXPORT_CURATE_INPUTS_USAGE, - exportCurateInputs, - formatDelistingsTsv, - formatExportCurateInputsSummary, - formatListingCurrenciesTsv, - formatPlainDecimal, - formatProviderMappingTsv, - parseExportCurateInputsArgs, - pinCurateInputSnapshot, - runExportCurateInputs, - runExportCurateInputsCli, - type ContinuityExportSourceRow, - type DelistingExportRow, - type ListingCurrencyExportRow, - type ListingDelistingSourceRow, - type ProviderMappingExportRow, - type SecurityMasterQueryable, - type SecurityMasterQueryResult, -} from '../../apps/stock/data-pipeline/src/security-master'; -import { compareAscii } from '../../apps/stock/data-pipeline/src/security-master/exchange-pass1'; - -const tempDirs: string[] = []; -afterEach(async () => { - for (const dir of tempDirs.splice(0).reverse()) { - await rm(dir, { recursive: true, force: true }); - } -}); - -async function makeTempDir(prefix = 'curate-inputs-unit-'): Promise { - const dir = await mkdtemp(join(tmpdir(), prefix)); - tempDirs.push(dir); - return dir; -} - -function expectExportError( - fn: () => unknown, - expectedCode: CurateInputExportError['code'], - expectedTable: string, - expectedKeySubstring: string -): CurateInputExportError { - try { - fn(); - } catch (error) { - expect(error).toBeInstanceOf(CurateInputExportError); - const err = error as CurateInputExportError; - expect(err.code).toBe(expectedCode); - expect(err.table).toBe(expectedTable); - expect(err.key).toContain(expectedKeySubstring); - expect(err.message).toContain(expectedTable); - expect(err.message).toContain(expectedKeySubstring); - return err; - } - throw new Error(`Expected CurateInputExportError(${expectedCode}), but function did not throw`); -} - -async function expectExportErrorAsync( - fn: () => Promise, - expectedCode: CurateInputExportError['code'], - expectedTable: string, - expectedKeySubstring: string -): Promise { - try { - await fn(); - } catch (error) { - expect(error).toBeInstanceOf(CurateInputExportError); - const err = error as CurateInputExportError; - expect(err.code).toBe(expectedCode); - expect(err.table).toBe(expectedTable); - expect(err.key).toContain(expectedKeySubstring); - expect(err.message).toContain(expectedTable); - expect(err.message).toContain(expectedKeySubstring); - return err; - } - throw new Error(`Expected CurateInputExportError(${expectedCode}), but async fn did not throw`); -} - -interface InMemorySecurityMasterData { - readonly listings: readonly { - readonly listing_id: number; - readonly currency: string | null; - readonly listed_to: string | null; - readonly delist_reason: string | null; - readonly terminal_return: string | null; - }[]; - readonly continuities: readonly { - readonly from_listing_id: number; - readonly to_listing_id: number; - readonly effective_date: string; - readonly kind: string; - }[]; - readonly providerMappings: readonly { - readonly source: string | null; - readonly source_id: string | null; - readonly valid_from: string | null; - readonly valid_to: string | null; - readonly listing_id: number; - }[]; -} - -function createInMemoryQueryable( - data: InMemorySecurityMasterData, - hooks?: { - readonly failOnQueryNumber?: number; - readonly recordedSql?: string[]; - } -): SecurityMasterQueryable { - const sortedContinuities = [...data.continuities] - .filter(c => c.kind === 'otc_delist_transfer') - .sort( - (a, b) => - a.from_listing_id - b.from_listing_id || compareAscii(a.effective_date, b.effective_date) - ); - const sortedListings = [...data.listings].sort((a, b) => a.listing_id - b.listing_id); - const sortedMappings = [...data.providerMappings].sort( - (a, b) => - compareAscii(a.source ?? '', b.source ?? '') || - compareAscii(a.source_id ?? '', b.source_id ?? '') || - compareAscii(a.valid_from ?? '', b.valid_from ?? '') - ); - - let queryCount = 0; - let pmCursorOpen = false; - let pmCursorOffset = 0; - - return { - async query>( - text: string, - values?: readonly unknown[] - ): Promise> { - queryCount += 1; - hooks?.recordedSql?.push(text.trim()); - if (hooks?.failOnQueryNumber === queryCount) { - throw new Error(`Simulated DB query failure at query #${queryCount}`); - } - - const normalized = text.replace(/\s+/g, ' ').trim(); - if ( - normalized.startsWith('BEGIN') || - normalized === 'COMMIT' || - normalized === 'ROLLBACK' - ) { - if (normalized === 'COMMIT' || normalized === 'ROLLBACK') { - pmCursorOpen = false; - pmCursorOffset = 0; - } - return { rows: [] }; - } - - if (normalized.startsWith('DECLARE ') && normalized.includes('FROM provider_mapping')) { - pmCursorOpen = true; - pmCursorOffset = 0; - return { rows: [] }; - } - - const fetchMatch = /^FETCH FORWARD (\d+) FROM \S+$/i.exec(normalized); - if (fetchMatch) { - if (!pmCursorOpen) { - throw new Error('Cursor not open for FETCH'); - } - const limit = Number(fetchMatch[1]); - const slice = sortedMappings.slice(pmCursorOffset, pmCursorOffset + limit); - pmCursorOffset += slice.length; - return { rows: slice as unknown as Row[] }; - } - - if (/^CLOSE \S+$/i.test(normalized)) { - pmCursorOpen = false; - pmCursorOffset = 0; - return { rows: [] }; - } - - if (normalized.includes('FROM corporate_action_continuity')) { - if (values && values.length === 1) { - const limit = values[0] as number; - return { rows: sortedContinuities.slice(0, limit) as unknown as Row[] }; - } - const [lastFromId, lastEffDate, limit] = values as [number, string, number]; - const filtered = sortedContinuities.filter( - c => - c.from_listing_id > lastFromId || - (c.from_listing_id === lastFromId && c.effective_date > lastEffDate) - ); - return { rows: filtered.slice(0, limit) as unknown as Row[] }; - } - - if (normalized.includes('FROM listing')) { - if (values && values.length === 1) { - const limit = values[0] as number; - return { rows: sortedListings.slice(0, limit) as unknown as Row[] }; - } - const [lastListingId, limit] = values as [number, number]; - const filtered = sortedListings.filter(l => l.listing_id > lastListingId); - return { rows: filtered.slice(0, limit) as unknown as Row[] }; - } - - if (normalized.includes('FROM provider_mapping')) { - if (values && values.length === 1) { - const limit = values[0] as number; - return { rows: sortedMappings.slice(0, limit) as unknown as Row[] }; - } - const [lastSource, lastSourceId, lastValidFrom, limit] = values as [ - string, - string, - string, - number, - ]; - const filtered = sortedMappings.filter(m => { - const src = m.source ?? ''; - const sid = m.source_id ?? ''; - const vf = m.valid_from ?? ''; - const srcCmp = compareAscii(src, lastSource); - if (srcCmp !== 0) { - return srcCmp > 0; - } - const sidCmp = compareAscii(sid, lastSourceId); - if (sidCmp !== 0) { - return sidCmp > 0; - } - return compareAscii(vf, lastValidFrom) > 0; - }); - return { rows: filtered.slice(0, limit) as unknown as Row[] }; - } - - throw new Error(`Unexpected SQL in in-memory queryable: ${normalized}`); - }, - release: () => {}, - }; -} - -/** - * Canonical golden fixture dataset shared with `tools/curate-etl/tests/fixtures/curate-inputs/` - * and `tools/curate-etl/src/tsv_fixture_tests.rs`. - */ -function buildGoldenFixtureDataset() { - const listings: ListingCurrencyExportRow[] = [ - { listingId: 1, currency: 'USD' }, // AAPL active US - { listingId: 2, currency: 'USD' }, // FB old (ticker reuse range 1) - { listingId: 3, currency: 'USD' }, // FB new ETF (ticker reuse range 2) - { listingId: 4, currency: 'USD' }, // SIVB primary listing -> OTC transfer to 6 - { listingId: 5, currency: 'USD' }, // SIVB unrelated ticker reuse after halt - { listingId: 6, currency: 'USD' }, // SIVBQ OTC successor -> later cancelled (-1) - { listingId: 7, currency: 'USD' }, // DEL30 Shumway terminal delisting (-0.3) - { listingId: 8, currency: 'CAD' }, // SHOP active CA - ]; - - const delistingListings: ListingDelistingSourceRow[] = [ - { listingId: 1, listedTo: null, delistReason: 'active', terminalReturn: null }, - { listingId: 2, listedTo: '2022-06-08', delistReason: null, terminalReturn: null }, - { listingId: 3, listedTo: null, delistReason: 'active', terminalReturn: null }, - { listingId: 4, listedTo: '2023-03-10', delistReason: 'moved_to_otc', terminalReturn: null }, - { listingId: 5, listedTo: null, delistReason: 'active', terminalReturn: null }, - { - listingId: 6, - listedTo: '2024-11-07', - delistReason: 'bankruptcy_cancelled', - terminalReturn: '-1.000000', - }, - { - listingId: 7, - listedTo: '2023-06-15', - delistReason: 'unknown_involuntary', - terminalReturn: '-0.300000', - }, - { listingId: 8, listedTo: null, delistReason: 'active', terminalReturn: null }, - ]; - - const continuities: ContinuityExportSourceRow[] = [ - { - fromListingId: 4, - toListingId: 6, - effectiveDate: '2023-03-28', - kind: 'otc_delist_transfer', - }, - ]; - - const providerMappings: ProviderMappingExportRow[] = [ - { source: 'eod', sourceId: 'AAPL.US', validFrom: '1980-12-12', validTo: null, listingId: 1 }, - { - source: 'eod', - sourceId: 'DEL30.US', - validFrom: '2018-01-02', - validTo: '2023-06-15', - listingId: 7, - }, - { - source: 'eod', - sourceId: 'FB.US', - validFrom: '2012-05-18', - validTo: '2022-06-08', - listingId: 2, - }, - { source: 'eod', sourceId: 'FB.US', validFrom: '2022-06-09', validTo: null, listingId: 3 }, - { source: 'eod', sourceId: 'SHOP.TO', validFrom: '2015-05-21', validTo: null, listingId: 8 }, - { - source: 'eod', - sourceId: 'SIVB.US', - validFrom: '1988-01-04', - validTo: '2023-03-10', - listingId: 4, - }, - { source: 'eod', sourceId: 'SIVB.US', validFrom: '2023-03-20', validTo: null, listingId: 5 }, - { - source: 'eod', - sourceId: 'SIVBQ.US', - validFrom: '2023-03-28', - validTo: '2024-11-07', - listingId: 6, - }, - { source: 'qm', sourceId: 'AAPL', validFrom: '1980-12-12', validTo: null, listingId: 1 }, - { - source: 'qm', - sourceId: 'DEL30', - validFrom: '2018-01-02', - validTo: '2023-06-15', - listingId: 7, - }, - { - source: 'qm', - sourceId: 'FB', - validFrom: '2012-05-18', - validTo: '2022-06-08', - listingId: 2, - }, - { source: 'qm', sourceId: 'FB', validFrom: '2022-06-09', validTo: null, listingId: 3 }, - { source: 'qm', sourceId: 'SHOP:CA', validFrom: '2015-05-21', validTo: null, listingId: 8 }, - { - source: 'qm', - sourceId: 'SIVB', - validFrom: '1988-01-04', - validTo: '2023-03-10', - listingId: 4, - }, - { source: 'qm', sourceId: 'SIVB', validFrom: '2023-03-20', validTo: null, listingId: 5 }, - { - source: 'qm', - sourceId: 'SIVBQ', - validFrom: '2023-03-28', - validTo: '2024-11-07', - listingId: 6, - }, - ]; - - return { listings, delistingListings, continuities, providerMappings }; -} - -describe('formatPlainDecimal', () => { - test('normalizes -0 to 0 and expands scientific notation without losing precision', () => { - expect(formatPlainDecimal(-0)).toBe('0'); - expect(formatPlainDecimal(0)).toBe('0'); - expect(formatPlainDecimal(-1)).toBe('-1'); - expect(formatPlainDecimal(-0.3)).toBe('-0.3'); - expect(formatPlainDecimal(-1e-7)).toBe('-0.0000001'); - expect(formatPlainDecimal(-5.25e-8)).toBe('-0.0000000525'); - }); -}); - -describe('formatProviderMappingTsv', () => { - test('emits exact bytes with deterministic ASCII sort under shuffled input, empty valid_to, and verbatim source_id', () => { - const rows: ProviderMappingExportRow[] = [ - { source: 'qm', sourceId: 'b', validFrom: '2020-01-01', validTo: null, listingId: 2 }, - { source: 'eod', sourceId: ' AAPL.US ', validFrom: '2000-01-03', validTo: null, listingId: 1 }, - { source: 'qm', sourceId: 'A', validFrom: '2022-06-09', validTo: null, listingId: 4 }, - { - source: 'qm', - sourceId: 'A', - validFrom: '2012-05-18', - validTo: '2022-06-08', - listingId: 3, - }, - ]; - - const expected = [ - 'eod\t AAPL.US \t2000-01-03\t\t1', - 'qm\tA\t2012-05-18\t2022-06-08\t3', - 'qm\tA\t2022-06-09\t\t4', - 'qm\tb\t2020-01-01\t\t2', - '', - ].join('\n'); - - expect(formatProviderMappingTsv(rows)).toBe(expected); - expect(formatProviderMappingTsv([...rows].reverse())).toBe(expected); - }); - - test('empty input produces empty string (0-byte file)', () => { - expect(formatProviderMappingTsv([])).toBe(''); - }); - - test('fails closed on forbidden control chars, blanks, bad dates, bad listing_id, duplicates, and overlaps', () => { - expectExportError( - () => - formatProviderMappingTsv([ - { source: 'eod', sourceId: 'BAD\tID', validFrom: '2020-01-01', validTo: null, listingId: 1 }, - ]), - 'FORBIDDEN_CONTROL_CHAR', - 'provider_mapping', - 'eod:row#0' - ); - expectExportError( - () => - formatProviderMappingTsv([ - { source: 'eod', sourceId: 'BAD\nID', validFrom: '2020-01-01', validTo: null, listingId: 1 }, - ]), - 'FORBIDDEN_CONTROL_CHAR', - 'provider_mapping', - 'eod:row#0' - ); - expectExportError( - () => - formatProviderMappingTsv([ - { source: 'eod', sourceId: 'BAD\rID', validFrom: '2020-01-01', validTo: null, listingId: 1 }, - ]), - 'FORBIDDEN_CONTROL_CHAR', - 'provider_mapping', - 'eod:row#0' - ); - expectExportError( - () => - formatProviderMappingTsv([ - { source: ' ', sourceId: 'AAPL', validFrom: '2020-01-01', validTo: null, listingId: 1 }, - ]), - 'BLANK_FIELD', - 'provider_mapping', - 'row#0' - ); - expectExportError( - () => - formatProviderMappingTsv([ - { source: 'eod', sourceId: ' ', validFrom: '2020-01-01', validTo: null, listingId: 1 }, - ]), - 'BLANK_FIELD', - 'provider_mapping', - 'eod:row#0' - ); - expectExportError( - () => - formatProviderMappingTsv([ - { source: 'eod', sourceId: 'AAPL', validFrom: '2023-02-29', validTo: null, listingId: 1 }, - ]), - 'INVALID_DATE', - 'provider_mapping', - 'eod:AAPL:2023-02-29' - ); - expectExportError( - () => - formatProviderMappingTsv([ - { - source: 'eod', - sourceId: 'AAPL', - validFrom: '2023-05-01', - validTo: '2023-04-30', - listingId: 1, - }, - ]), - 'INVALID_DATE_RANGE', - 'provider_mapping', - 'eod:AAPL:2023-05-01' - ); - expectExportError( - () => - formatProviderMappingTsv([ - { source: 'eod', sourceId: 'AAPL', validFrom: '2020-01-01', validTo: null, listingId: 0 }, - ]), - 'INVALID_LISTING_ID', - 'provider_mapping', - 'eod:AAPL:2020-01-01' - ); - expectExportError( - () => - formatProviderMappingTsv([ - { - source: 'eod', - sourceId: 'AAPL', - validFrom: '2020-01-01', - validTo: null, - listingId: 2_147_483_648, - }, - ]), - 'INVALID_LISTING_ID', - 'provider_mapping', - 'eod:AAPL:2020-01-01' - ); - expectExportError( - () => - formatProviderMappingTsv([ - { source: 'qm', sourceId: 'FB', validFrom: '2020-01-01', validTo: '2021-01-01', listingId: 1 }, - { source: 'qm', sourceId: 'FB', validFrom: '2020-01-01', validTo: '2022-01-01', listingId: 2 }, - ]), - 'DUPLICATE_PROVIDER_MAPPING', - 'provider_mapping', - 'qm:FB:2020-01-01' - ); - expectExportError( - () => - formatProviderMappingTsv([ - { source: 'qm', sourceId: 'FB', validFrom: '2020-01-01', validTo: '2021-06-01', listingId: 1 }, - { source: 'qm', sourceId: 'FB', validFrom: '2021-06-01', validTo: null, listingId: 2 }, - ]), - 'OVERLAPPING_PROVIDER_MAPPING', - 'provider_mapping', - 'qm:FB:2021-06-01' - ); - expectExportError( - () => - formatProviderMappingTsv([ - { source: 'qm', sourceId: 'FB', validFrom: '2020-01-01', validTo: null, listingId: 1 }, - { source: 'qm', sourceId: 'FB', validFrom: '2021-06-01', validTo: null, listingId: 2 }, - ]), - 'OVERLAPPING_PROVIDER_MAPPING', - 'provider_mapping', - 'qm:FB:2021-06-01' - ); - }); -}); - -describe('formatListingCurrenciesTsv', () => { - test('sorts by ascending listing_id and handles empty input', () => { - expect(formatListingCurrenciesTsv([])).toBe(''); - const rows: ListingCurrencyExportRow[] = [ - { listingId: 10, currency: 'CAD' }, - { listingId: 2, currency: 'USD' }, - { listingId: 5, currency: 'USD' }, - ]; - const expected = '2\tUSD\n5\tUSD\n10\tCAD\n'; - expect(formatListingCurrenciesTsv(rows)).toBe(expected); - expect(formatListingCurrenciesTsv([...rows].reverse())).toBe(expected); - }); - - test('fails closed on blank/null currency, control chars, invalid listing_id, and duplicate listing_id', () => { - expectExportError( - () => formatListingCurrenciesTsv([{ listingId: 1, currency: '' }]), - 'BLANK_FIELD', - 'listing', - 'listing_id=1' - ); - expectExportError( - () => formatListingCurrenciesTsv([{ listingId: 1, currency: null as unknown as string }]), - 'BLANK_FIELD', - 'listing', - 'listing_id=1' - ); - expectExportError( - () => formatListingCurrenciesTsv([{ listingId: 1, currency: 'US\tD' }]), - 'FORBIDDEN_CONTROL_CHAR', - 'listing', - 'listing_id=1' - ); - expectExportError( - () => formatListingCurrenciesTsv([{ listingId: -3, currency: 'USD' }]), - 'INVALID_LISTING_ID', - 'listing', - 'row#0' - ); - expectExportError( - () => - formatListingCurrenciesTsv([ - { listingId: 7, currency: 'USD' }, - { listingId: 7, currency: 'CAD' }, - ]), - 'DUPLICATE_LISTING_CURRENCY', - 'listing', - 'listing_id=7' - ); - }); -}); - -describe('buildDelistingExportRows and formatDelistingsTsv', () => { - test('handles OTC transfer + successor terminal delisting (SIVB -> SIVBQ -> -1), -0.3 Shumway, active/null skips, and stats conservation', () => { - const listings: ListingDelistingSourceRow[] = [ - { listingId: 1, listedTo: null, delistReason: 'active', terminalReturn: null }, - { listingId: 2, listedTo: '2022-06-08', delistReason: null, terminalReturn: null }, - { listingId: 4, listedTo: '2023-03-10', delistReason: 'moved_to_otc', terminalReturn: null }, - { listingId: 6, listedTo: '2024-11-07', delistReason: 'bankruptcy_cancelled', terminalReturn: -1 }, - { listingId: 7, listedTo: '2023-06-15', delistReason: 'unknown_involuntary', terminalReturn: -0.3 }, - { listingId: 9, listedTo: null, delistReason: 'unknown_involuntary', terminalReturn: -0.3 }, // missingListedTo - { listingId: 10, listedTo: '2023-07-01', delistReason: 'unknown_involuntary', terminalReturn: -0.3 }, // missingOutgoingQmMapping - { listingId: 11, listedTo: '2023-03-10', delistReason: 'moved_to_otc', terminalReturn: null }, // missingSuccessorQmMapping - { listingId: 12, listedTo: '2023-03-10', delistReason: 'moved_to_otc', terminalReturn: null }, // missingOutgoingQmMapping for OTC - { listingId: 13, listedTo: '2023-08-01', delistReason: 'merger_cash', terminalReturn: -0 }, // -0 normalized to 0 - { listingId: 14, listedTo: '2023-08-02', delistReason: 'merger_cash', terminalReturn: -1e-7 }, // tiny decimal without sci notation - ]; - - const continuities: ContinuityExportSourceRow[] = [ - { fromListingId: 4, toListingId: 6, effectiveDate: '2023-03-28', kind: 'otc_delist_transfer' }, - { fromListingId: 11, toListingId: 99, effectiveDate: '2023-03-28', kind: 'otc_delist_transfer' }, - { fromListingId: 12, toListingId: 6, effectiveDate: '2023-03-28', kind: 'otc_delist_transfer' }, - { fromListingId: 1, toListingId: 2, effectiveDate: '2021-01-01', kind: 'venue_uplisting' }, - ]; - - const mappings: ProviderMappingExportRow[] = [ - { source: 'qm', sourceId: 'SIVB', validFrom: '1988-01-04', validTo: '2023-03-10', listingId: 4 }, - { source: 'qm', sourceId: 'SIVBQ', validFrom: '2023-03-28', validTo: '2024-11-07', listingId: 6 }, - { source: 'qm', sourceId: 'DEL30', validFrom: '2018-01-02', validTo: '2023-06-15', listingId: 7 }, - { source: 'qm', sourceId: 'NOSUCC', validFrom: '2019-01-01', validTo: '2023-03-10', listingId: 11 }, - { source: 'qm', sourceId: 'ZERO', validFrom: '2020-01-01', validTo: '2023-08-01', listingId: 13 }, - { source: 'qm', sourceId: 'TINY', validFrom: '2020-01-01', validTo: '2023-08-02', listingId: 14 }, - { source: 'eod', sourceId: 'NOQM.US', validFrom: '2020-01-01', validTo: '2023-07-01', listingId: 10 }, - ]; - - const result = buildDelistingExportRows(listings, continuities, mappings); - const { stats } = result; - expect(stats.otcTransfersOut).toBe(1); - expect(stats.terminalDelistingsOut).toBe(4); - expect(stats.rowsOut).toBe(5); - expect(stats.skipped).toEqual({ - active: 1, - noOutcome: 1, - missingListedTo: 1, - missingOutgoingQmMapping: 2, - missingSuccessorQmMapping: 1, - nonOtcContinuity: 1, - }); - expect(stats.skippedTotal).toBe(7); - expect(stats.rowsIn).toBe(stats.rowsOut + stats.skippedTotal); - - const tsv = formatDelistingsTsv(result.rows); - expect(tsv).toBe( - [ - 'DEL30\t2023-06-15\t7\t\t-0.3', - 'SIVB\t2023-03-28\t4\tSIVBQ\t', - 'SIVBQ\t2024-11-07\t6\t\t-1', - 'TINY\t2023-08-02\t14\t\t-0.0000001', - 'ZERO\t2023-08-01\t13\t\t0', - '', - ].join('\n') - ); - - // Deterministic under shuffled inputs - const shuffledResult = buildDelistingExportRows( - [...listings].reverse(), - [...continuities].reverse(), - [...mappings].reverse() - ); - expect(formatDelistingsTsv(shuffledResult.rows)).toBe(tsv); - expect(shuffledResult.stats).toEqual(stats); - }); - - test('empty input produces empty string (0-byte file)', () => { - expect(formatDelistingsTsv([])).toBe(''); - }); - - test('fails closed on invalid delisting rows and DB conflicts', () => { - const bothOutcomes: DelistingExportRow = { - sourceId: 'SIVB', - delistDate: '2023-03-28', - fromListingId: 4, - successorSourceId: 'SIVBQ', - terminalReturn: -0.3, - }; - expectExportError( - () => formatDelistingsTsv([bothOutcomes]), - 'INVALID_DELISTING_OUTCOME', - 'delistings', - 'SIVB:2023-03-28' - ); - - const neitherOutcome: DelistingExportRow = { - sourceId: 'SIVB', - delistDate: '2023-03-28', - fromListingId: 4, - successorSourceId: null, - terminalReturn: null, - }; - expectExportError( - () => formatDelistingsTsv([neitherOutcome]), - 'INVALID_DELISTING_OUTCOME', - 'delistings', - 'SIVB:2023-03-28' - ); - - expectExportError( - () => - formatDelistingsTsv([ - { - sourceId: 'SIVB', - delistDate: '2023-03-28', - fromListingId: null, - successorSourceId: 'SIVBQ', - terminalReturn: null, - }, - ]), - 'MISSING_FROM_LISTING_ID', - 'delistings', - 'SIVB:2023-03-28' - ); - - for (const badReturn of [0.01, -1.01, Number.NaN, Number.POSITIVE_INFINITY, ' -0.3', 'abc']) { - expectExportError( - () => - formatDelistingsTsv([ - { - sourceId: 'BADRET', - delistDate: '2023-06-15', - fromListingId: 7, - successorSourceId: null, - terminalReturn: badReturn, - }, - ]), - 'INVALID_TERMINAL_RETURN', - 'delistings', - 'BADRET:2023-06-15' - ); - } - - expectExportError( - () => - buildDelistingExportRows( - [{ listingId: 1, listedTo: null, delistReason: 'active', terminalReturn: -0.3 }], - [], - [] - ), - 'ACTIVE_LISTING_WITH_OUTCOME', - 'listing', - 'listing_id=1' - ); - - expectExportError( - () => - buildDelistingExportRows( - [{ listingId: 4, listedTo: '2023-03-10', delistReason: 'moved_to_otc', terminalReturn: -0.3 }], - [{ fromListingId: 4, toListingId: 6, effectiveDate: '2023-03-28', kind: 'otc_delist_transfer' }], - [] - ), - 'INVALID_DELISTING_OUTCOME', - 'listing', - 'listing_id=4' - ); - - expectExportError( - () => - buildDelistingExportRows( - [{ listingId: 4, listedTo: '2023-03-10', delistReason: 'moved_to_otc', terminalReturn: null }], - [{ fromListingId: 4, toListingId: 4, effectiveDate: '2023-03-28', kind: 'otc_delist_transfer' }], - [] - ), - 'SELF_SUCCESSOR_CONTINUITY', - 'corporate_action_continuity', - 'from_listing_id=4@2023-03-28' - ); - }); -}); - -describe('exportCurateInputs atomic publish and streaming', () => { - test('leaves pre-existing files byte-identical with zero leftover temp/bak files on mid-query, mid-validation, and mid-rename failures', async () => { - const outDir = await makeTempDir('curate-inputs-atomic-'); - const pmPath = join(outDir, CURATE_INPUT_FILES.providerMapping); - const lcPath = join(outDir, CURATE_INPUT_FILES.listingCurrencies); - const dlPath = join(outDir, CURATE_INPUT_FILES.delistings); - - const origPm = 'eod\tORIG.US\t2020-01-01\t\t1\n'; - const origLc = '1\tUSD\n'; - const origDl = 'ORIG\t2023-01-01\t1\t\t-0.3\n'; - await writeFile(pmPath, origPm, 'utf8'); - await writeFile(lcPath, origLc, 'utf8'); - await writeFile(dlPath, origDl, 'utf8'); - - const baseData: InMemorySecurityMasterData = { - listings: [ - { listing_id: 1, currency: 'USD', listed_to: null, delist_reason: 'active', terminal_return: null }, - ], - continuities: [], - providerMappings: [ - { source: 'eod', source_id: 'NEW.US', valid_from: '2021-01-01', valid_to: null, listing_id: 1 }, - ], - }; - - const assertIntact = async () => { - expect(await readFile(pmPath, 'utf8')).toBe(origPm); - expect(await readFile(lcPath, 'utf8')).toBe(origLc); - expect(await readFile(dlPath, 'utf8')).toBe(origDl); - const entries = (await readdir(outDir)).sort(); - expect(entries).toEqual([ - CURATE_INPUT_FILES.delistings, - CURATE_INPUT_FILES.listingCurrencies, - CURATE_INPUT_FILES.providerMapping, - ]); - }; - - // 1. Mid-query failure - const failingQueryClient = createInMemoryQueryable(baseData, { failOnQueryNumber: 3 }); - await expect(exportCurateInputs(failingQueryClient, { outDir })).rejects.toThrow( - 'Simulated DB query failure' - ); - await assertIntact(); - - // 2. Mid-validation failure (tab inside source_id) - const badDataClient = createInMemoryQueryable({ - ...baseData, - providerMappings: [ - { source: 'eod', source_id: 'BAD\tID', valid_from: '2021-01-01', valid_to: null, listing_id: 1 }, - ], - }); - await expectExportErrorAsync( - () => exportCurateInputs(badDataClient, { outDir }), - 'FORBIDDEN_CONTROL_CHAR', - 'provider_mapping', - 'eod:row#0' - ); - await assertIntact(); - - // 3. Mid-rename failure on the 2nd top-level target symlink replacement (after staging->gen + 1st backup/link + 2nd backup) - let renameCalls = 0; - const goodClient = createInMemoryQueryable(baseData); - await expect( - exportCurateInputs(goodClient, { - outDir, - fs: { - rename: async (oldPath, newPath) => { - renameCalls += 1; - if (renameCalls === 5) { - throw new Error('Simulated EIO on 2nd target publish rename'); - } - return rename(oldPath, newPath); - }, - }, - }) - ).rejects.toThrow('Simulated EIO on 2nd target publish rename'); - await assertIntact(); - - // 4. Failure at the atomic `current` commit rename restores all 3 pre-existing files cleanly - const commitFailClient = createInMemoryQueryable(baseData); - await expect( - exportCurateInputs(commitFailClient, { - outDir, - fs: { - rename: async (oldPath, newPath) => { - if (String(newPath) === join(outDir, 'current')) { - throw new Error('Simulated EIO on current commit rename'); - } - return rename(oldPath, newPath); - }, - }, - }) - ).rejects.toThrow('Simulated EIO on current commit rename'); - await assertIntact(); - }); - - test('post-commit backup deletion failure does not roll back committed publication and reports warning', async () => { - const outDir = await makeTempDir('curate-inputs-post-commit-cleanup-'); - const pmPath = join(outDir, CURATE_INPUT_FILES.providerMapping); - const lcPath = join(outDir, CURATE_INPUT_FILES.listingCurrencies); - const dlPath = join(outDir, CURATE_INPUT_FILES.delistings); - - await writeFile(pmPath, 'eod\tOLD.US\t2020-01-01\t\t1\n', 'utf8'); - await writeFile(lcPath, '1\tUSD\n', 'utf8'); - await writeFile(dlPath, 'OLD\t2023-01-01\t1\t\t-0.3\n', 'utf8'); - - const newData: InMemorySecurityMasterData = { - listings: [ - { listing_id: 2, currency: 'CAD', listed_to: null, delist_reason: 'active', terminal_return: null }, - ], - continuities: [], - providerMappings: [ - { source: 'eod', source_id: 'NEW.TO', valid_from: '2022-01-01', valid_to: null, listing_id: 2 }, - ], - }; - - let backupUnlinkCalls = 0; - const result = await exportCurateInputs(createInMemoryQueryable(newData), { - outDir, - fs: { - unlink: async filePath => { - if (String(filePath).endsWith('.bak')) { - backupUnlinkCalls += 1; - if (backupUnlinkCalls === 2) { - throw new Error('Simulated EIO deleting 2nd backup'); - } - } - return unlink(filePath); - }, - }, - }); - - // All three live paths reflect the new committed snapshot (no partial rollback). - expect(await readFile(pmPath, 'utf8')).toBe('eod\tNEW.TO\t2022-01-01\t\t2\n'); - expect(await readFile(lcPath, 'utf8')).toBe('2\tCAD\n'); - expect(await readFile(dlPath, 'utf8')).toBe(''); - - // Backup #1 and #3 were deleted; #2 failed and is reported in cleanupWarnings. - expect(backupUnlinkCalls).toBe(3); - expect(result.cleanupWarnings).toHaveLength(1); - expect(result.cleanupWarnings[0]).toContain('Simulated EIO deleting 2nd backup'); - expect(result.cleanupWarnings[0]).toContain('.bak'); - expect(formatExportCurateInputsSummary(result)).toContain('warning:'); - }); - - test('failure during rollback restoration retains unrestored backup on disk and reports it', async () => { - const outDir = await makeTempDir('curate-inputs-restore-fail-'); - const pmPath = join(outDir, CURATE_INPUT_FILES.providerMapping); - const lcPath = join(outDir, CURATE_INPUT_FILES.listingCurrencies); - const dlPath = join(outDir, CURATE_INPUT_FILES.delistings); - - const origPm = 'eod\tORIG.US\t2020-01-01\t\t1\n'; - const origLc = '1\tUSD\n'; - const origDl = 'ORIG\t2023-01-01\t1\t\t-0.3\n'; - await writeFile(pmPath, origPm, 'utf8'); - await writeFile(lcPath, origLc, 'utf8'); - await writeFile(dlPath, origDl, 'utf8'); - - const newData: InMemorySecurityMasterData = { - listings: [ - { listing_id: 2, currency: 'CAD', listed_to: null, delist_reason: 'active', terminal_return: null }, - ], - continuities: [], - providerMappings: [ - { source: 'eod', source_id: 'NEW.TO', valid_from: '2022-01-01', valid_to: null, listing_id: 2 }, - ], - }; - - const err = await expectExportErrorAsync( - () => - exportCurateInputs(createInMemoryQueryable(newData), { - outDir, - fs: { - rename: async (oldPath, newPath) => { - // Fail at the atomic commit point to trigger rollback of all 3 backups. - if (String(newPath) === join(outDir, 'current')) { - throw new Error('Simulated commit EIO'); - } - // Fail restoring the provider_mapping backup specifically. - if ( - String(oldPath).includes(`${CURATE_INPUT_FILES.providerMapping}.`) && - String(oldPath).endsWith('.bak') && - String(newPath) === pmPath - ) { - throw new Error('Simulated restore EIO'); - } - return rename(oldPath, newPath); - }, - }, - }), - 'PUBLISH_ROLLBACK_FAILED', - 'publish', - 'providerMapping' - ); - - expect(err.message).toContain('Simulated commit EIO'); - expect(err.message).toContain('Simulated restore EIO'); - expect(err.message).toContain('.bak'); - - // The other two targets were restored intact. - expect(await readFile(lcPath, 'utf8')).toBe(origLc); - expect(await readFile(dlPath, 'utf8')).toBe(origDl); - - // The unrestored provider_mapping backup MUST still exist on disk with original bytes! - const entries = await readdir(outDir); - const retainedBackups = entries.filter( - e => e.startsWith(`${CURATE_INPUT_FILES.providerMapping}.`) && e.endsWith('.bak') - ); - expect(retainedBackups).toHaveLength(1); - expect(await readFile(join(outDir, retainedBackups[0]!), 'utf8')).toBe(origPm); - }); - - test('consumer pinning snapshot during publication reads consistent pre-refresh generation while new consumers see new generation', async () => { - const outDir = await makeTempDir('curate-inputs-pin-during-publish-'); - - // Generation 1: only SIVB active (no SIVBQ successor yet). - const gen1Data: InMemorySecurityMasterData = { - listings: [ - { listing_id: 4, currency: 'USD', listed_to: null, delist_reason: 'active', terminal_return: null }, - ], - continuities: [], - providerMappings: [ - { source: 'qm', source_id: 'SIVB', valid_from: '1988-01-04', valid_to: null, listing_id: 4 }, - ], - }; - - // Generation 2: SIVB -> SIVBQ OTC transfer added to both provider_mapping and delistings. - const gen2Data: InMemorySecurityMasterData = { - listings: [ - { listing_id: 4, currency: 'USD', listed_to: '2023-03-10', delist_reason: 'moved_to_otc', terminal_return: null }, - { listing_id: 6, currency: 'USD', listed_to: null, delist_reason: 'active', terminal_return: null }, - ], - continuities: [ - { from_listing_id: 4, to_listing_id: 6, effective_date: '2023-03-28', kind: 'otc_delist_transfer' }, - ], - providerMappings: [ - { source: 'qm', source_id: 'SIVB', valid_from: '1988-01-04', valid_to: '2023-03-10', listing_id: 4 }, - { source: 'qm', source_id: 'SIVBQ', valid_from: '2023-03-28', valid_to: null, listing_id: 6 }, - ], - }; - - const res1 = await exportCurateInputs(createInMemoryQueryable(gen1Data), { outDir }); - - // Consumer 1 pins generation 1 before opening any TSV, then reads provider_mapping.tsv. - const pinned1 = await pinCurateInputSnapshot(outDir); - expect(pinned1.generationId).toBe(res1.generationId); - const consumer1Pm = await readFile(pinned1.providerMapping, 'utf8'); - expect(consumer1Pm).toBe('qm\tSIVB\t1988-01-04\t\t4\n'); - - // While Consumer 1 is mid-read, Generation 2 publishes atomically. - const res2 = await exportCurateInputs(createInMemoryQueryable(gen2Data), { outDir }); - expect(res2.generationId).not.toBe(res1.generationId); - - // Consumer 1 finishes reading listing_currencies.tsv and delistings.tsv from its pinned generation 1. - const consumer1Lc = await readFile(pinned1.listingCurrencies, 'utf8'); - const consumer1Dl = await readFile(pinned1.delistings, 'utf8'); - expect(consumer1Lc).toBe('4\tUSD\n'); - expect(consumer1Dl).toBe(''); // Consistent with gen1 (no SIVBQ transfer referencing missing SIVBQ!) - - // Consumer 2 pins after Generation 2 committed and sees the full Generation 2 snapshot. - const pinned2 = await pinCurateInputSnapshot(outDir); - expect(pinned2.generationId).toBe(res2.generationId); - expect(await readFile(pinned2.providerMapping, 'utf8')).toBe( - 'qm\tSIVB\t1988-01-04\t2023-03-10\t4\nqm\tSIVBQ\t2023-03-28\t\t6\n' - ); - expect(await readFile(pinned2.listingCurrencies, 'utf8')).toBe('4\tUSD\n6\tUSD\n'); - expect(await readFile(pinned2.delistings, 'utf8')).toBe('SIVB\t2023-03-28\t4\tSIVBQ\t\n'); - }); - - test('concurrent exports to the same outDir never interleave into a mixed snapshot', async () => { - const outDir = await makeTempDir('curate-inputs-concurrent-'); - - const snapA: InMemorySecurityMasterData = { - listings: [ - { listing_id: 10, currency: 'USD', listed_to: '2023-06-15', delist_reason: 'unknown_involuntary', terminal_return: '-0.3' }, - ], - continuities: [], - providerMappings: [ - { source: 'qm', source_id: 'SNAP_A', valid_from: '2020-01-01', valid_to: '2023-06-15', listing_id: 10 }, - ], - }; - const snapB: InMemorySecurityMasterData = { - listings: [ - { listing_id: 20, currency: 'CAD', listed_to: '2024-01-15', delist_reason: 'bankruptcy_cancelled', terminal_return: '-1' }, - ], - continuities: [], - providerMappings: [ - { source: 'qm', source_id: 'SNAP_B', valid_from: '2021-01-01', valid_to: '2024-01-15', listing_id: 20 }, - ], - }; - - const [resA, resB] = await Promise.all([ - exportCurateInputs(createInMemoryQueryable(snapA), { outDir }), - exportCurateInputs(createInMemoryQueryable(snapB), { outDir }), - ]); - - const pinned = await pinCurateInputSnapshot(outDir); - const pm = await readFile(pinned.providerMapping, 'utf8'); - const lc = await readFile(pinned.listingCurrencies, 'utf8'); - const dl = await readFile(pinned.delistings, 'utf8'); - - const isAllA = - pinned.generationId === resA.generationId && - pm === 'qm\tSNAP_A\t2020-01-01\t2023-06-15\t10\n' && - lc === '10\tUSD\n' && - dl === 'SNAP_A\t2023-06-15\t10\t\t-0.3\n'; - const isAllB = - pinned.generationId === resB.generationId && - pm === 'qm\tSNAP_B\t2021-01-01\t2024-01-15\t20\n' && - lc === '20\tCAD\n' && - dl === 'SNAP_B\t2024-01-15\t20\t\t-1\n'; - - expect(isAllA || isAllB).toBe(true); - }); - - test('concurrent fresh-dir exports serialize publish/rollback so a failed export never deletes a committed export top-level links', async () => { - const snapA: InMemorySecurityMasterData = { - listings: [ - { listing_id: 10, currency: 'USD', listed_to: '2023-06-15', delist_reason: 'unknown_involuntary', terminal_return: '-0.3' }, - ], - continuities: [], - providerMappings: [ - { source: 'qm', source_id: 'SNAP_A', valid_from: '2020-01-01', valid_to: '2023-06-15', listing_id: 10 }, - ], - }; - const snapB: InMemorySecurityMasterData = { - listings: [ - { listing_id: 20, currency: 'CAD', listed_to: '2024-01-15', delist_reason: 'bankruptcy_cancelled', terminal_return: '-1' }, - ], - continuities: [], - providerMappings: [ - { source: 'qm', source_id: 'SNAP_B', valid_from: '2021-01-01', valid_to: '2024-01-15', listing_id: 20 }, - ], - }; - - // Case 1: Export A enters publish first on a fresh dir, creates top-level links, and fails at - // commit rename while Export B is waiting for `.publish.lock`. A rolls back cleanly under the - // lock; B then acquires the lock and commits with all top-level and pinned paths readable. - { - const outDir = await makeTempDir('curate-inputs-race-a-fails-'); - let aEnteredPublishResolve!: () => void; - const aEnteredPublish = new Promise(resolve => { - aEnteredPublishResolve = resolve; - }); - let bWaitingForLockResolve!: () => void; - const bWaitingForLock = new Promise(resolve => { - bWaitingForLockResolve = resolve; - }); - - const promiseA = exportCurateInputs(createInMemoryQueryable(snapA), { - outDir, - fs: { - rename: async (oldPath, newPath) => { - if (String(newPath) === join(outDir, 'current')) { - aEnteredPublishResolve(); - await bWaitingForLock; - throw new Error('Simulated commit EIO in Export A'); - } - return rename(oldPath, newPath); - }, - }, - }); - - const promiseB = (async () => { - await aEnteredPublish; - let signaledWait = false; - return exportCurateInputs(createInMemoryQueryable(snapB), { - outDir, - fs: { - open: async (filePath, flags) => { - if (String(filePath) === join(outDir, CURATE_INPUT_PUBLISH_LOCK) && !signaledWait) { - signaledWait = true; - bWaitingForLockResolve(); - } - return open(filePath, flags); - }, - }, - }); - })(); - - const [settledA, settledB] = await Promise.allSettled([promiseA, promiseB]); - expect(settledA.status).toBe('rejected'); - expect(settledB.status).toBe('fulfilled'); - - // Top-level TSV paths AND pinned snapshot must both resolve to Export B cleanly. - expect(await readFile(join(outDir, CURATE_INPUT_FILES.providerMapping), 'utf8')).toBe( - 'qm\tSNAP_B\t2021-01-01\t2024-01-15\t20\n' - ); - expect(await readFile(join(outDir, CURATE_INPUT_FILES.listingCurrencies), 'utf8')).toBe( - '20\tCAD\n' - ); - expect(await readFile(join(outDir, CURATE_INPUT_FILES.delistings), 'utf8')).toBe( - 'SNAP_B\t2024-01-15\t20\t\t-1\n' - ); - const pinned = await pinCurateInputSnapshot(outDir); - expect(await readFile(pinned.delistings, 'utf8')).toBe('SNAP_B\t2024-01-15\t20\t\t-1\n'); - const entries = await readdir(outDir); - expect(entries.some(e => e.includes('.tmp') || e.includes('.bak') || e === CURATE_INPUT_PUBLISH_LOCK)).toBe(false); - } - - // Case 2: Export B enters publish first on a fresh dir and commits while Export A is waiting - // on `.publish.lock`; Export A then acquires the lock, sees existing top-level links, and fails - // at commit rename. A's rollback must leave B's top-level links and `current` intact. - { - const outDir = await makeTempDir('curate-inputs-race-b-commits-'); - let bEnteredPublishResolve!: () => void; - const bEnteredPublish = new Promise(resolve => { - bEnteredPublishResolve = resolve; - }); - let aWaitingForLockResolve!: () => void; - const aWaitingForLock = new Promise(resolve => { - aWaitingForLockResolve = resolve; - }); - - const promiseB = exportCurateInputs(createInMemoryQueryable(snapB), { - outDir, - fs: { - rename: async (oldPath, newPath) => { - if (String(newPath) === join(outDir, 'current')) { - bEnteredPublishResolve(); - await aWaitingForLock; - } - return rename(oldPath, newPath); - }, - }, - }); - - const promiseA = (async () => { - await bEnteredPublish; - let signaledWait = false; - return exportCurateInputs(createInMemoryQueryable(snapA), { - outDir, - fs: { - open: async (filePath, flags) => { - if (String(filePath) === join(outDir, CURATE_INPUT_PUBLISH_LOCK) && !signaledWait) { - signaledWait = true; - aWaitingForLockResolve(); - } - return open(filePath, flags); - }, - rename: async (oldPath, newPath) => { - if (String(newPath) === join(outDir, 'current')) { - throw new Error('Simulated commit EIO in Export A after B committed'); - } - return rename(oldPath, newPath); - }, - }, - }); - })(); - - const [settledB, settledA] = await Promise.allSettled([promiseB, promiseA]); - expect(settledB.status).toBe('fulfilled'); - expect(settledA.status).toBe('rejected'); - - // Export B's top-level TSV paths AND pinned snapshot remain 100% readable. - expect(await readFile(join(outDir, CURATE_INPUT_FILES.providerMapping), 'utf8')).toBe( - 'qm\tSNAP_B\t2021-01-01\t2024-01-15\t20\n' - ); - expect(await readFile(join(outDir, CURATE_INPUT_FILES.listingCurrencies), 'utf8')).toBe( - '20\tCAD\n' - ); - expect(await readFile(join(outDir, CURATE_INPUT_FILES.delistings), 'utf8')).toBe( - 'SNAP_B\t2024-01-15\t20\t\t-1\n' - ); - const pinned = await pinCurateInputSnapshot(outDir); - expect(await readFile(pinned.providerMapping, 'utf8')).toBe( - 'qm\tSNAP_B\t2021-01-01\t2024-01-15\t20\n' - ); - const entries = await readdir(outDir); - expect(entries.some(e => e.includes('.tmp') || e.includes('.bak') || e === CURATE_INPUT_PUBLISH_LOCK)).toBe(false); - } - }); - - test('fails closed with PUBLISH_LOCK_TIMEOUT when publish lock is held past timeout without removing foreign lock', async () => { - const outDir = await makeTempDir('curate-inputs-lock-timeout-'); - const lockPath = join(outDir, CURATE_INPUT_PUBLISH_LOCK); - await writeFile(lockPath, '{"pid":999999,"runTag":"foreign"}\n', 'utf8'); - - const client = createInMemoryQueryable({ - listings: [], - continuities: [], - providerMappings: [], - }); - - await expectExportErrorAsync( - () => exportCurateInputs(client, { outDir, publishLockTimeoutMs: 15 }), - 'PUBLISH_LOCK_TIMEOUT', - 'publish', - outDir - ); - - // Foreign lock file must remain untouched. - expect(await readFile(lockPath, 'utf8')).toBe('{"pid":999999,"runTag":"foreign"}\n'); - }); - - test('removes .publish.lock when writing metadata fails after exclusive creation so an immediate retry succeeds', async () => { - const outDir = await makeTempDir('curate-inputs-lock-write-fail-'); - const lockPath = join(outDir, CURATE_INPUT_PUBLISH_LOCK); - - const makeClient = () => - createInMemoryQueryable({ - listings: [ - { - listing_id: 1, - currency: 'USD', - listed_to: null, - delist_reason: 'active', - terminal_return: null, - }, - ], - continuities: [], - providerMappings: [ - { - source: 'qm', - source_id: 'AAPL', - valid_from: '2020-01-01', - valid_to: null, - listing_id: 1, - }, - ], - }); - - let injected = false; - await expect( - exportCurateInputs(makeClient(), { - outDir, - fs: { - open: async (path, flags, mode) => { - const realHandle = await open(path, flags, mode); - if (!injected && String(path) === lockPath && flags === 'wx') { - injected = true; - const wrappedHandle = Object.create(realHandle) as typeof realHandle; - wrappedHandle.write = async () => { - const err = new Error('Simulated ENOSPC while writing lock metadata') as NodeJS.ErrnoException; - err.code = 'ENOSPC'; - throw err; - }; - wrappedHandle.close = () => realHandle.close(); - return wrappedHandle; - } - return realHandle; - }, - }, - }) - ).rejects.toThrow('Simulated ENOSPC while writing lock metadata'); - - expect(injected).toBe(true); - const entriesAfterFailure = await readdir(outDir); - expect(entriesAfterFailure).not.toContain(CURATE_INPUT_PUBLISH_LOCK); - - // Immediate retry to the same outDir must succeed without PUBLISH_LOCK_TIMEOUT. - const retryResult = await exportCurateInputs(makeClient(), { - outDir, - publishLockTimeoutMs: 50, - }); - expect(retryResult.providerMapping.rowsOut).toBe(1); - expect(await readFile(join(outDir, CURATE_INPUT_FILES.providerMapping), 'utf8')).toBe( - 'qm\tAAPL\t2020-01-01\t\t1\n' - ); - const entriesAfterRetry = await readdir(outDir); - expect(entriesAfterRetry).not.toContain(CURATE_INPUT_PUBLISH_LOCK); - }); - - test('rejects pool-like objects and invalid chunkSize', async () => { - const outDir = await makeTempDir('curate-inputs-pool-'); - const poolLike = { - query: async () => ({ rows: [] }), - connect: async () => ({}), - } as unknown as SecurityMasterQueryable; - - await expectExportErrorAsync( - () => exportCurateInputs(poolLike, { outDir }), - 'INVALID_CLIENT', - 'connection', - 'client' - ); - - const validClient = createInMemoryQueryable({ - listings: [], - continuities: [], - providerMappings: [], - }); - await expectExportErrorAsync( - () => exportCurateInputs(validClient, { outDir, chunkSize: 5001 }), - 'INVALID_OPTION', - 'options', - 'chunkSize' - ); - }); -}); - -describe('golden fixtures cross-language parity', () => { - test('TS exporter reproduces committed tools/curate-etl/tests/fixtures/curate-inputs/*.tsv byte-for-byte', async () => { - const fixtureDir = resolve( - import.meta.dir, - '../../tools/curate-etl/tests/fixtures/curate-inputs' - ); - const dataset = buildGoldenFixtureDataset(); - - const expectedPm = formatProviderMappingTsv(dataset.providerMappings); - const expectedLc = formatListingCurrenciesTsv(dataset.listings); - const builtDelistings = buildDelistingExportRows( - dataset.delistingListings, - dataset.continuities, - dataset.providerMappings - ); - const expectedDl = formatDelistingsTsv(builtDelistings.rows); - - expect(await readFile(join(fixtureDir, CURATE_INPUT_FILES.providerMapping), 'utf8')).toBe( - expectedPm - ); - expect(await readFile(join(fixtureDir, CURATE_INPUT_FILES.listingCurrencies), 'utf8')).toBe( - expectedLc - ); - expect(await readFile(join(fixtureDir, CURATE_INPUT_FILES.delistings), 'utf8')).toBe( - expectedDl - ); - - // Also verify streaming exportCurateInputs produces identical bytes with chunkSize=2. - const outDir = await makeTempDir('curate-inputs-golden-'); - const queryable = createInMemoryQueryable({ - listings: dataset.delistingListings.map((l, idx) => ({ - listing_id: l.listingId, - currency: dataset.listings[idx]!.currency, - listed_to: l.listedTo, - delist_reason: l.delistReason, - terminal_return: l.terminalReturn === null ? null : String(l.terminalReturn), - })), - continuities: dataset.continuities.map(c => ({ - from_listing_id: c.fromListingId, - to_listing_id: c.toListingId, - effective_date: c.effectiveDate, - kind: c.kind, - })), - providerMappings: dataset.providerMappings.map(m => ({ - source: m.source, - source_id: m.sourceId, - valid_from: m.validFrom, - valid_to: m.validTo, - listing_id: m.listingId, - })), - }); - - const result = await exportCurateInputs(queryable, { outDir, chunkSize: 2 }); - expect(await readFile(result.providerMapping.path, 'utf8')).toBe(expectedPm); - expect(await readFile(result.listingCurrencies.path, 'utf8')).toBe(expectedLc); - expect(await readFile(result.delistings.path, 'utf8')).toBe(expectedDl); - expect(result.delistings.stats).toEqual(builtDelistings.stats); - }); -}); - -describe('CLI args, safety guard, and runner', () => { - test('parseExportCurateInputsArgs parses --out-dir, --chunk-size, and --help', () => { - expect(parseExportCurateInputsArgs(['--help'])).toEqual({ help: true }); - expect(parseExportCurateInputsArgs(['--out-dir', '/tmp/curate'])).toEqual({ - help: false, - outDir: '/tmp/curate', - chunkSize: DEFAULT_EXPORT_CHUNK_SIZE, - }); - expect(parseExportCurateInputsArgs(['--out-dir=/tmp/curate', '--chunk-size=250'])).toEqual({ - help: false, - outDir: '/tmp/curate', - chunkSize: 250, - }); - expect(() => parseExportCurateInputsArgs([])).toThrow(EXPORT_CURATE_INPUTS_USAGE); - expect(() => parseExportCurateInputsArgs(['--out-dir', '/tmp/a', '--chunk-size', '5001'])).toThrow( - 'Invalid --chunk-size' - ); - expect(() => parseExportCurateInputsArgs(['--unknown'])).toThrow('Unknown argument'); - }); - - test('assertExportCurateInputsSafety blocks disabled PG and dev->QA PG even when override env var is set', () => { - const devOnQaConfig = { - environment: 'development', - database: { - postgres: { - enabled: true, - host: 'localhost', - port: 5432, - database: 'trading_bot', - }, - mongodb: { - enabled: true, - uri: 'mongodb://localhost:27017/stock', - database: 'stock', - }, - }, - } as unknown as StockAppConfig; - - expect(() => - assertExportCurateInputsSafety(devOnQaConfig, { - STOCK_BOT_ALLOW_DEV_ON_QA_DB: 'true', - }) - ).toThrow(); - - const disabledPgConfig = { - ...devOnQaConfig, - database: { - ...devOnQaConfig.database, - postgres: { ...devOnQaConfig.database.postgres, enabled: false }, - }, - } as unknown as StockAppConfig; - expect(() => assertExportCurateInputsSafety(disabledPgConfig, {})).toThrow( - 'PostgreSQL is disabled' - ); - - const safeDevConfig = { - ...devOnQaConfig, - database: { - ...devOnQaConfig.database, - postgres: { - enabled: true, - host: 'localhost', - port: 5433, - database: 'trading_bot_dev', - }, - }, - } as unknown as StockAppConfig; - expect(() => assertExportCurateInputsSafety(safeDevConfig, {})).not.toThrow(); - }); - - test('runExportCurateInputs runs safety, exports, closes PG client, and prints summary', async () => { - const outDir = await makeTempDir('curate-inputs-cli-'); - let safetyChecked = false; - let closed = false; - let stdoutText = ''; - - const queryable = createInMemoryQueryable({ - listings: [ - { listing_id: 1, currency: 'USD', listed_to: null, delist_reason: 'active', terminal_return: null }, - ], - continuities: [], - providerMappings: [ - { source: 'qm', source_id: 'AAPL', valid_from: '2020-01-01', valid_to: null, listing_id: 1 }, - ], - }); - - const output = await runExportCurateInputs( - { - assertSafety: () => { - safetyChecked = true; - }, - createPostgresClient: () => ({ - queryable, - close: () => { - closed = true; - }, - }), - writeStdout: text => { - stdoutText += text; - }, - }, - { outDir, chunkSize: 100 } - ); - - expect(safetyChecked).toBe(true); - expect(closed).toBe(true); - expect(output.summary).toBe(formatExportCurateInputsSummary(output.result)); - expect(stdoutText).toContain('provider_mapping.tsv: rows_in=1 rows_out=1'); - expect(stdoutText).toContain('listing_currencies.tsv: rows_in=1 rows_out=1'); - expect(stdoutText).toContain('delistings.tsv: rows_in=1 rows_out=0'); - }); - - test('runExportCurateInputsCli initializes postgresOnly config so unrelated QA MONGODB_URI does not block dev PostgreSQL export', async () => { - const outDir = await makeTempDir('curate-inputs-cli-pg-only-'); - const envKeys = [ - 'NODE_ENV', - 'POSTGRES_ENABLED', - 'POSTGRES_HOST', - 'POSTGRES_PORT', - 'POSTGRES_DATABASE', - 'DATABASE_POSTGRES_HOST', - 'DATABASE_POSTGRES_PORT', - 'DATABASE_POSTGRES_DATABASE', - 'MONGODB_URI', - 'MONGODB_READ_URI', - 'DATABASE_MONGODB_URI', - 'DATABASE_MONGODB_READURI', - 'STOCK_BOT_ALLOW_DEV_ON_QA_DB', - ] as const; - const savedEnv: Record = {}; - for (const key of envKeys) { - savedEnv[key] = process.env[key]; - } - - try { - resetStockConfig(); - process.env.NODE_ENV = 'development'; - process.env.POSTGRES_ENABLED = 'true'; - process.env.POSTGRES_HOST = 'localhost'; - process.env.POSTGRES_PORT = '5433'; - process.env.POSTGRES_DATABASE = 'trading_bot_dev'; - process.env.DATABASE_POSTGRES_HOST = 'localhost'; - process.env.DATABASE_POSTGRES_PORT = '5433'; - process.env.DATABASE_POSTGRES_DATABASE = 'trading_bot_dev'; - process.env.MONGODB_URI = 'mongodb://trading_admin:secret@localhost:27017/stock'; - delete process.env.MONGODB_READ_URI; - delete process.env.DATABASE_MONGODB_URI; - delete process.env.DATABASE_MONGODB_READURI; - delete process.env.STOCK_BOT_ALLOW_DEV_ON_QA_DB; - - // Prove the exact same env fails under the old mongoReadOnly config init. - expect(() => initializeStockConfig('dataPipeline', { mongoReadOnly: true })).toThrow( - 'Safety guard' - ); - resetStockConfig(); - - const queryable = createInMemoryQueryable({ - listings: [ - { listing_id: 1, currency: 'USD', listed_to: null, delist_reason: 'active', terminal_return: null }, - ], - continuities: [], - providerMappings: [ - { source: 'qm', source_id: 'AAPL', valid_from: '2020-01-01', valid_to: null, listing_id: 1 }, - ], - }); - - let stdoutText = ''; - await runExportCurateInputsCli(['--out-dir', outDir], { - createPostgresClient: () => ({ - queryable, - close: () => {}, - }), - writeStdout: text => { - stdoutText += text; - }, - }); - - expect(stdoutText).toContain('Curate-ETL TSV export complete'); - expect(await readFile(join(outDir, CURATE_INPUT_FILES.providerMapping), 'utf8')).toBe( - 'qm\tAAPL\t2020-01-01\t\t1\n' - ); - - // Still rejects dev -> QA PostgreSQL even with STOCK_BOT_ALLOW_DEV_ON_QA_DB=true! - resetStockConfig(); - process.env.POSTGRES_PORT = '5432'; - process.env.POSTGRES_DATABASE = 'trading_bot'; - process.env.DATABASE_POSTGRES_PORT = '5432'; - process.env.DATABASE_POSTGRES_DATABASE = 'trading_bot'; - process.env.STOCK_BOT_ALLOW_DEV_ON_QA_DB = 'true'; - - await expect( - runExportCurateInputsCli(['--out-dir', outDir], { - createPostgresClient: () => ({ - queryable, - close: () => {}, - }), - writeStdout: () => {}, - }) - ).rejects.toThrow('Safety guard'); - } finally { - for (const key of envKeys) { - const value = savedEnv[key]; - if (value === undefined) { - delete process.env[key]; - } else { - process.env[key] = value; - } - } - resetStockConfig(); - } - }); -}); diff --git a/test/unit/security-master-m1-gate-denominator.test.ts b/test/unit/security-master-m1-gate-denominator.test.ts deleted file mode 100644 index f911a21e..00000000 --- a/test/unit/security-master-m1-gate-denominator.test.ts +++ /dev/null @@ -1,288 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { - buildMatchReport, - composeSecurityMasterRun, - matchListingsStageB, - renderMatchReportMarkdown, - sourceCountryKey, - type StageBInput, -} from '../../apps/stock/data-pipeline/src/security-master'; -import { SYNTHETIC_EOD_ISIN_PREFIX } from '../../apps/stock/data-pipeline/src/security-master/instrument-stage-a'; -import type { GateOutOfScopeReason } from '../../apps/stock/data-pipeline/src/security-master/match-report'; - -describe('M1 security-master IB disambiguation, CEO crawl-only fallback, and gate denominator', () => { - test('enableIbTickerDisambiguation resolves ambiguous active/delisted listings and links identifier-less & reverse-split EOD listings', () => { - const input: StageBInput = { - instruments: [ - { - primaryIsin: 'US0378331005', - primaryCusip: '037833100', - issuerCountry: 'US', - canonicalName: 'Apple Inc', - members: [ - { source: 'eod', sourceId: 'AAPL.US', currency: 'USD', method: 'tier1_isin' }, - { source: 'eod', sourceId: 'AAPL_OLD.US', currency: 'USD', method: 'tier1_isin' }, - { source: 'ib', sourceId: '265598', currency: 'USD', method: 'tier1_isin' }, - ], - }, - { - primaryIsin: `${SYNTHETIC_EOD_ISIN_PREFIX}NOISIN.US`, - primaryCusip: null, - issuerCountry: 'US', - canonicalName: 'No ISIN EOD Corp', - members: [ - { - source: 'eod', - sourceId: 'NOISIN.US', - currency: 'USD', - method: 'tier3_ticker_span', - }, - ], - }, - { - primaryIsin: 'US9999991009', - primaryCusip: '999999100', - issuerCountry: 'US', - canonicalName: 'No ISIN EOD Corp', - members: [{ source: 'ib', sourceId: '999001', currency: 'USD', method: 'tier1_isin' }], - }, - { - primaryIsin: 'US00091F1066', - primaryCusip: '00091F106', - issuerCountry: 'US', - canonicalName: 'ABVC Biopharma Pre-Split', - members: [{ source: 'eod', sourceId: 'ABVC.US', currency: 'USD', method: 'tier1_isin' }], - }, - { - primaryIsin: 'US00091F3047', - primaryCusip: '00091F304', - issuerCountry: 'US', - canonicalName: 'ABVC Biopharma Post-Reverse-Split', - members: [{ source: 'ib', sourceId: '555001', currency: 'USD', method: 'tier1_isin' }], - }, - ], - eodListings: [ - { - sourceId: 'AAPL.US', - ticker: 'AAPL', - mic: 'XNAS', - role: 'primary_venue', - currency: 'USD', - span: { firstBarDate: '2005-01-03', lastBarDate: '2025-08-13' }, - }, - { - sourceId: 'AAPL_OLD.US', - ticker: 'AAPLOLD', - mic: 'OTCM', - role: 'primary_venue', - currency: 'USD', - span: { firstBarDate: '2000-01-03', lastBarDate: '2010-01-04' }, - }, - { - sourceId: 'NOISIN.US', - ticker: 'NOISIN', - mic: 'XNAS', - role: 'primary_venue', - currency: 'USD', - span: { firstBarDate: '2020-01-02', lastBarDate: '2025-08-13' }, - }, - { - sourceId: 'ABVC.US', - ticker: 'ABVC', - mic: 'XNAS', - role: 'primary_venue', - currency: 'USD', - span: { firstBarDate: '2018-01-02', lastBarDate: '2025-08-13' }, - }, - ], - ibContracts: [ - { sourceId: '265598', conid: 265598, currency: 'USD', primaryExchange: 'NASDAQ', ticker: 'AAPL' }, - { sourceId: '999001', conid: 999001, currency: 'USD', primaryExchange: 'NASDAQ', ticker: 'NOISIN' }, - { sourceId: '555001', conid: 555001, currency: 'USD', primaryExchange: 'NASDAQ', ticker: 'ABVC' }, - ], - tickerSources: [], - }; - - const res = matchListingsStageB(input, { enableIbTickerDisambiguation: true }); - expect(res.conflicts).toEqual([]); - expect(res.stats.bySource.ib.matched).toBe(3); - expect(res.providerMappings.find(m => m.source === 'ib' && m.sourceId === '265598')?.listingKey.mic).toBe('XNAS'); - expect(res.providerMappings.find(m => m.source === 'ib' && m.sourceId === '999001')?.listingKey.tickerRoot).toBe('NOISIN'); - expect(res.providerMappings.find(m => m.source === 'ib' && m.sourceId === '555001')?.listingKey.tickerRoot).toBe('ABVC'); - }); - - test('allowUniqueTickerFallbackForCrawlOnlyCeo links unique delisted listing but never links reused tickers', () => { - const input: StageBInput = { - instruments: [ - { - primaryIsin: 'CA1111111111', - primaryCusip: null, - issuerCountry: 'CA', - canonicalName: 'Unique Delisted TSX', - members: [{ source: 'eod', sourceId: 'DELIST.TO', currency: 'CAD', method: 'tier1_isin' }], - }, - { - primaryIsin: 'CA2222222222', - primaryCusip: null, - issuerCountry: 'CA', - canonicalName: 'Reused Ticker Old', - members: [{ source: 'eod', sourceId: 'REUSE_OLD.TO', currency: 'CAD', method: 'tier1_isin' }], - }, - { - primaryIsin: 'CA3333333333', - primaryCusip: null, - issuerCountry: 'CA', - canonicalName: 'Reused Ticker New', - members: [{ source: 'eod', sourceId: 'REUSE_NEW.TO', currency: 'CAD', method: 'tier1_isin' }], - }, - ], - eodListings: [ - { - sourceId: 'DELIST.TO', - ticker: 'DELIST', - mic: 'XTSE', - role: 'primary_venue', - currency: 'CAD', - span: { firstBarDate: '2012-01-03', lastBarDate: '2021-06-30' }, - }, - { - sourceId: 'REUSE_OLD.TO', - ticker: 'REUSE', - mic: 'XTSE', - role: 'primary_venue', - currency: 'CAD', - span: { firstBarDate: '2010-01-04', lastBarDate: '2018-12-31' }, - }, - { - sourceId: 'REUSE_NEW.TO', - ticker: 'REUSE', - mic: 'XTSE', - role: 'primary_venue', - currency: 'CAD', - span: { firstBarDate: '2020-01-02', lastBarDate: '2023-12-29' }, - }, - ], - ibContracts: [], - tickerSources: [ - { - source: 'ceo', - sourceId: 'ceo:delist', - ticker: 'DELIST', - mic: 'XTSE', - role: 'primary_venue', - currency: 'CAD', - span: { firstBarDate: '2025-07-01', lastBarDate: '2025-07-01' }, - }, - { - source: 'ceo', - sourceId: 'ceo:reuse', - ticker: 'REUSE', - mic: 'XTSE', - role: 'primary_venue', - currency: 'CAD', - span: { firstBarDate: '2025-07-01', lastBarDate: '2025-07-01' }, - }, - ], - }; - - const res = matchListingsStageB(input, { allowUniqueTickerFallbackForCrawlOnlyCeo: true }); - expect(res.providerMappings.filter(m => m.source === 'ceo' && m.sourceId === 'ceo:delist')).toHaveLength(1); - expect(res.unresolved.find(u => u.source === 'ceo' && u.sourceId === 'ceo:reuse')?.reason).toBe('no_span_overlap'); - }); - - test('buildMatchReport and composeSecurityMasterRun transparently itemize Out of Gate Scope without hiding raw totals', () => { - const stageB = matchListingsStageB({ - instruments: [ - { - primaryIsin: 'US0378331005', - primaryCusip: '037833100', - issuerCountry: 'US', - canonicalName: 'Apple Inc', - members: [{ source: 'eod', sourceId: 'AAPL.US', currency: 'USD', method: 'tier1_isin' }], - }, - ], - eodListings: [ - { - sourceId: 'AAPL.US', - ticker: 'AAPL', - mic: 'XNAS', - role: 'primary_venue', - currency: 'USD', - span: { firstBarDate: '2020-01-02', lastBarDate: '2025-08-13' }, - }, - ], - ibContracts: [], - tickerSources: [ - { - source: 'qm', - sourceId: 'AAPL', - ticker: 'AAPL', - mic: 'XNAS', - role: 'primary_venue', - currency: 'USD', - span: { firstBarDate: '2021-01-04', lastBarDate: '2025-08-13' }, - }, - { - source: 'qm', - sourceId: 'GHOST', - ticker: 'GHOST', - mic: 'XNAS', - role: 'primary_venue', - currency: 'USD', - span: null, - }, - { - source: 'qm', - sourceId: 'CSE1:CA', - ticker: 'CSE1', - mic: 'XCNQ', - role: 'primary_venue', - currency: 'CAD', - span: { firstBarDate: '2021-01-04', lastBarDate: '2025-08-13' }, - }, - ], - }); - - const gateOutOfScope = new Map([ - [sourceCountryKey('qm', 'GHOST'), 'zero_bar_catalog_ghost'], - [sourceCountryKey('qm', 'CSE1:CA'), 'uncovered_venue'], - ]); - - const report = buildMatchReport({ - stageA: { - instruments: [], - unresolved: [], - conflicts: [], - stats: { - totalRecords: 1, - totalInstruments: 1, - bySource: { - eod: { total: 1, tier1Isin: 1, tier2Cusip: 0, unresolved: 0, conflict: 0 }, - ib: { total: 0, tier1Isin: 0, tier2Cusip: 0, unresolved: 0, conflict: 0 }, - }, - }, - }, - stageB, - gateOutOfScope, - gateDenominatorNote: 'Custom test gate note.', - }); - - const qmRow = report.resolutionBySource.find(r => r.source === 'qm'); - expect(qmRow?.total).toBe(3); - expect(qmRow?.matched).toBe(1); - expect(qmRow?.outOfGateScope).toBe(2); - expect(qmRow?.eligibleTotal).toBe(1); - expect(qmRow?.eligibleResolvedPct).toBe(1); - expect(report.meetsExitThresholds.equitiesResolved95).toBe(true); - - const md = renderMatchReportMarkdown(report); - expect(md).toContain('## Gate Denominator Definition'); - expect(md).toContain('Out of Gate Scope'); - expect(md).toContain('## Out-of-Gate-Scope Breakdown'); - expect(md).toContain('| qm | zero_bar_catalog_ghost | 1 |'); - expect(md).toContain('| qm | uncovered_venue | 1 |'); - - // Ensure composeSecurityMasterRun default without applyUsCaEquityGateDenominator remains unchanged - expect(typeof composeSecurityMasterRun).toBe('function'); - }); -}); diff --git a/tools/curate-etl/Cargo.toml b/tools/curate-etl/Cargo.toml index b4755d02..2f81cd3a 100644 --- a/tools/curate-etl/Cargo.toml +++ b/tools/curate-etl/Cargo.toml @@ -7,7 +7,5 @@ license.workspace = true [dependencies] bson = { version = "=3.1.0", default-features = false, features = ["compat-3-0-0"] } -mongodb = { version = "=3.10.2", default-features = false, features = ["compat-3-3-0", "bson-3", "sync", "rustls-tls", "dns-resolver"] } parquet = { version = "=60.2.0", default-features = false, features = ["zstd"] } -rayon = "=1.12.0" diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index 6f9c9176..fe50b9b4 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -1,6 +1,6 @@ # `curate-etl` -Dedicated Rust crate (three exact-pinned direct dependencies: `bson` `=3.1.0` with `default-features = false, features = ["compat-3-0-0"]`, `parquet` `=60.2.0` with `default-features = false, features = ["zstd"]`, and `rayon` `=1.12.0`) 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, the `M1.2i` streaming Zstd Parquet writer for `bars_1d`, the `M1.2j` streaming Zstd Parquet writer for `shorts`, the `M1.2k` streaming Zstd Parquet writer for `events`, the `M1.2l` streaming Zstd Parquet writer for `fx_1d`, the `M1.2m` streaming Zstd Parquet writer for `adj_factors`, the `M1.2n` streaming Zstd Parquet writer for `corporate_actions`, the `M1.2o` zero-copy raw BSON decoder for `eodPrices`, the `M1.2w` zero-copy raw BSON decoders for `qmSplits` and `qmDividends`, the `M1.2y` bounded-memory streaming reader for concatenated raw BSON (`bson_stream`), the `M1.2ad` `ceoShorts` decoder + `curate-shorts` command, the `M1.2ae` `qmFilings` / `qmEarnings` decoders + `curate-events` command, the `M1.2ah` zero-copy `qmPrices` decoder + optional `--qm-prices` volume cross-check in `curate-bars-1d`, the `M1.2ai` `rayon` year-sharded parallel Zstd Parquet writer (`--threads`) for `curate-bars-1d`, the `M1.2ak` read-only MongoDB URI safety guard (`mongo_safety`), and the `M1.2al` driver-independent read-only MongoDB raw-BSON cursor seam (`mongo_stream`). +Dedicated Rust crate (two exact-pinned direct dependencies: `bson` `=3.1.0` with `default-features = false, features = ["compat-3-0-0"]` and `parquet` `=60.2.0` 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, the `M1.2i` streaming Zstd Parquet writer for `bars_1d`, the `M1.2j` streaming Zstd Parquet writer for `shorts`, the `M1.2k` streaming Zstd Parquet writer for `events`, the `M1.2l` streaming Zstd Parquet writer for `fx_1d`, the `M1.2m` streaming Zstd Parquet writer for `adj_factors`, the `M1.2n` streaming Zstd Parquet writer for `corporate_actions`, and the `M1.2o` zero-copy raw BSON decoder for `eodPrices`. ## Scope & Sign Conventions @@ -131,28 +131,6 @@ Rules: Deferred out of `src/shorts.rs`: MongoDB `ceoShorts` BSON streaming, `provider_mapping` `listing_id` resolution, Zstd Parquet writing, `rayon` sharding, and deriving `pct_float` from shares outstanding (values are passed through as supplied by the caller). -## `posts` Builder (`M2.2b`) - -`build_posts` (`src/posts.rs`) turns already-decoded `ceoPosts` rows (`CeoPost`) into two disjoint, deterministically sorted point-in-time `PostRow` streams (`newswire` and `retail`) aligned with `design/DATA-CONTRACTS.md` §1 (`ceoSymbols`, `ceoPosts`, `ceoShorts` row). - -Rules: -1. **Newswire vs. retail split:** `is_bot` is `true` iff `bot` is `"1"` after trimming whitespace; only `is_bot == true` rows route to `newswire`, and all other values (`None`, `"0"`, `""`, etc.) route to `retail`. -2. **Point-in-time `known_at` guard:** `posted_at = timestamp_ms * 1_000` (UTC microseconds) and `known_at = max(timestamp_ms, edited_ms) * 1_000` (`COALESCE(edited, timestamp)` clamped so `known_at >= posted_at` always holds). Any text-based feature MUST join on `known_at`, never `posted_at`. Rows with `edited_ms < timestamp_ms` clamp `known_at` to `posted_at` and increment `stats.edited_before_posted`. Both `stats.edited` and `stats.edited_before_posted` are counted on valid input rows before deduplication. Because `ceoPosts` overwrites `spiel` in place without version history, the builder retains one supplied version per `spiel_id` and cannot recover earlier pre-edit text. -3. **Validation & overflow:** Empty `spiel_id` or `timestamp_ms <= 0` rows are rejected before conversion and counted in `stats.rejected_invalid`. Overflow converting `timestamp_ms` or the selected `known_at` millisecond value to UTC microseconds returns `PostsError::TimestampOverflow`. -4. **Global `spiel_id` deduplication & deterministic tie-break:** Deduplicates globally on `spiel_id` before splitting into `newswire` and `retail`. Within each `spiel_id` group, the survivor is the row with the greatest `known_at`, breaking ties by the maximum lexicographic tuple `(posted_at, is_edited, is_bot, key, user_id, text)` (`None < Some` for `user_id`), with zero dependence on input order. The remaining `group_len - 1` rows are counted in `stats.duplicates_dropped`. -5. **Sort order & invariants:** Both `newswire` and `retail` are sorted strictly ascending by `(key, known_at, spiel_id)`. Any input permutation yields identical `newswire`, `retail`, and `stats`, and `input == newswire + retail + duplicates_dropped + rejected_invalid`. - -Deferred out of `src/posts.rs`: benchmark, live `ceoPosts` verification (including live `edited` BSON type verification), `--from-mongo` streaming, and co-publishing with `curate-events` output (offline raw-BSON decoding lives in `src/bson_ceo_posts.rs`, chunked streaming in `src/bson_stream.rs`, `events` Parquet row mapping in `src/parquet_posts.rs`, `provider_mapping` listing resolution + Parquet writing in `src/curate_posts.rs`, the file-to-file runner in `src/run_curate_posts.rs`, and the file-mode `curate-posts` CLI command in `src/cli.rs` + `src/main.rs`). - -### `run_curate_posts` File-to-File Runner (`M2.2i`) - -`run_curate_posts` / `run_curate_posts_with_reader` (`src/run_curate_posts.rs`) connects a concatenated raw BSON `ceoPosts` dump file and a headerless 5-column `provider_mapping.tsv` (`load_provider_mapping_tsv`) through `decode_ceo_posts_chunks` (`src/bson_stream.rs`) and `curate_and_write_posts` into `/events/year=YYYY/part.parquet` (Zstd Parquet): - -- **Explicit timestamp unit (no default):** `CuratePostsArgs::timestamp_unit` requires callers to pass `CeoPostsTimestampUnit::Seconds` or `CeoPostsTimestampUnit::Millis` explicitly (the live MongoDB numeric unit is unverified in the repo; BSON `DateTime` values are always epoch milliseconds). -- **Dedicated output directory & clobber guard:** Because `write_events_dataset` replaces whole `events/year=YYYY/part.parquet` files and `run_curate_events` (filings + earnings) writes to the same `/events` path, `run_curate_posts` requires a dedicated `--out` directory and fails closed with `RunCuratePostsError::EventsDatasetExists` before any write whenever `/events` already contains any `year=*` entry. Combining filings, earnings, and posts into a single `events` dataset is a separate follow-up. -- **Zero-row & fail-closed behavior:** Empty or all-unmapped inputs return `Ok` with `rows_written == 0` without creating `/events`. Validation, clobber checks, TSV loading, full BSON decoding, and curation complete before `out_dir` is touched. -- **In-memory accumulation:** `RawBsonChunkReader` bounds only the raw BSON chunk buffer (`peak_chunk_bytes`); decoded posts and their text accumulate in memory before `curate_and_write_posts` runs (as `curate_posts` requires). - ## `events` Builder (`M1.2g`) `build_events` (`src/events.rs`) turns raw `qmFilings` (`QmFiling`) and `qmEarnings` (`QmEarning`) streams into deterministically sorted point-in-time `EventRow` records matching `events/year=YYYY/part.parquet` in `design/DATA-CONTRACTS.md` (`listing_id, ts, known_at, known_at_source, kind, subtype, payload_json`), plus `partition_year_utc` / `EventRow::partition_year` for UTC `year=YYYY` partitioning. @@ -180,7 +158,7 @@ Rules: - 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`: live MongoDB `qmFilings` / `qmEarnings` cursors and M2 `fundamentals_pit` joins (concatenated-BSON decoding, `provider_mapping` resolution, and Zstd Parquet publishing are wired in `src/bson_qm_events.rs` + `src/run_curate_events.rs`). +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`) @@ -214,17 +192,13 @@ Rules: - Writes `/bars_1d/year=YYYY/part.parquet` lazily per observed `session_date` calendar year (`1900..=2200`); empty input and empty years create no directories or files. - Zstd compression on every column chunk (`DEFAULT_ZSTD_LEVEL = 3`, configurable via `Bars1dWriteOptions::zstd_level`). - Bounded streaming buffers (`DEFAULT_ROW_GROUP_ROWS = 1_000_000`, configurable via `Bars1dWriteOptions::row_group_rows`): each active year buffers at most one row group of columnar data (with string interning for `currency`/`source`), flushing and clearing buffers on every row-group boundary. - - **Year-sharded `rayon` parallel write (`M1.2ai`):** configurable via `Bars1dWriteOptions::threads` (`DEFAULT_WRITE_THREADS = 1` in `Bars1dWriteOptions::default()` to keep bounded streaming memory for library callers; `default_parallel_threads()` returns `std::thread::available_parallelism()`, falling back to `1`). When `threads == 1`, runs the unchanged single-pass streaming path. When `threads > 1`, runs one sequential validation + order-preserving year-bucketing pass, encodes and Zstd-compresses each `year=YYYY` staging file on a local `rayon::ThreadPool` sized to `threads.min(years).max(1)` (never the global pool), catches worker panics (`WorkerPanicked`), sorts outcomes by ascending year (returning the lowest failing year's error deterministically on failure after unlinking only this run's staging files), and publishes sequentially in ascending year order. - - **Byte-identical determinism guarantee:** identical inputs produce byte-for-byte identical `bars_1d/year=YYYY/part.parquet` files regardless of `threads` (same row order per year, same `row_group_rows` flush boundaries, same schema, dictionary interning order, and `created_by` metadata). + - Deterministic `created_by` metadata so identical inputs produce byte-identical `part.parquet` files. 3. **Sort, concurrency & atomicity rules:** - Input must already be sorted strictly ascending by `(listing_id, session_date)`; within each year file rows remain in `(listing_id, session_date)` order. - Concurrent writers targeting the same `/bars_1d` directory are serialized via an in-process per-dataset mutex and a bounded-wait exclusive `.write.lock` file (30 s default timeout returning `ParquetBarsError::LockTimeout` with the lock path if a crashed process left a stale lock behind). Every year partition writes to an exclusively created per-run staging file (`part.parquet..tmp`), flushes, and calls `File::sync_all()` before publication. During publication, pre-existing `part.parquet` files are backed up in place (hard link with exclusive copy fallback) so the live path remains readable until replaced by a single atomic `rename`; on any error, all open writers are dropped, replaced partitions are restored from backup, newly published partitions are removed (reporting any rollback failures alongside the original error via `RollbackFailed`), and only staging files owned by the current run are unlinked. 4. **Typed errors (`ParquetBarsError`):** - `InvalidRowGroupRows` (`row_group_rows == 0`) - `InvalidZstdLevel { level }` - - `InvalidThreads` (`threads == 0`) - - `ThreadPoolBuild { threads, detail }` - - `WorkerPanicked { year, detail }` - `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 }` @@ -479,29 +453,7 @@ Rules: - `iter_raw_bson_docs` walks concatenated 4-byte little-endian length-prefixed BSON documents (wire / `mongodump` layout), terminating cleanly on unrecoverable framing errors (`TruncatedDocument`, `CorruptDocumentLength`) while skipping validly framed corrupt documents (`CorruptBson`). - `decode_eod_price_buffer` reports and skips per-document errors without aborting the stream, reconciling `BsonEodDecodeStats` with `decoded + rejected_total() == docs_in`. 5. **Deferred out of `M1.2o`:** - - MongoDB driver (`mongodb` crate) read-only cursor streaming, `rayon` parallel sharding, `provider_mapping` PostgreSQL preload wiring, and decoders for remaining collections (`eodIntraday1M`). (`qmSplits`/`qmDividends`, `qmPrices`, `teMarketData`, `ceoShorts`, and `qmFilings`/`qmEarnings` decoders are now implemented alongside all six M1 `curate-*` file-to-Parquet commands.) - -## `qmSplits` / `qmDividends` Raw BSON Decoders (`M1.2w`) - -`decode_qm_split_doc`, `decode_qm_split_bytes`, `decode_qm_split_buffer`, `decode_qm_dividend_doc`, `decode_qm_dividend_bytes`, and `decode_qm_dividend_buffer` (`src/bson_qm_actions.rs`) decode raw MongoDB `qmSplits` and `qmDividends` BSON documents in a single forward pass over `RawDocument::iter_elements()` into borrowed `RawQmSplit<'a>` and `RawQmDividend<'a>` views without allocating a `String` or `bson::Document` per row, reusing `bson_eod_prices::iter_raw_bson_docs` for concatenated length-prefixed buffers. - -1. **Field contract & cited in-repo sources:** - - `qmSearchCode` (`FIELD_QM_SEARCH_CODE`): BSON UTF-8 `String` (borrowed verbatim; empty or whitespace-only is rejected). Cited: `apps/stock/data-ingestion/src/handlers/qm/actions/events.action.ts:98,118`. - - `date` (`FIELD_DATE`): strict 10-byte ASCII `YYYY-MM-DD` BSON `String` (validated via `split::ymd_to_epoch_days`) or BSON `DateTime` (UTC epoch day via `timestamp_millis().div_euclid(86_400_000)` with `i32` bounds check so pre-1970 timestamps floor accurately). Cited: `apps/stock/data-ingestion/src/handlers/qm/actions/events.action.ts:99,119`, `design/DATA-CONTRACTS.md` §1 (line 25). - - `declared` (`FIELD_DECLARED`, optional): absent, BSON `Null`, or empty/whitespace-only `String` maps to `None`; strict `YYYY-MM-DD` `String` or BSON `DateTime` maps to `Some(i32)`; malformed strings/out-of-range `DateTime` return `MalformedDate { field: "declared" }` and other types return `WrongType { field: "declared", .. }`. Cited: `design/DATA-CONTRACTS.md` §1 (line 25). - - `splitratio` (`FIELD_SPLIT_RATIO`), `forfactor` (`FIELD_FOR_FACTOR`), `tofactor` (`FIELD_TO_FACTOR`): BSON `Double`, `Int32`, or `Int64`; `splitratio` must be finite and `> 0.0`. Empirically across all `18,751` live `qmSplits` documents (`16,892/16,892` with numeric `forfactor`/`tofactor`), QuoteMedia stores `splitratio = forfactor / tofactor = old_shares / new_shares` (e.g., `0.1` for NVDA's `2024-06-10` 10:1 forward split; `8` for GE's `2021-08-02` 1:8 reverse split). `decode_qm_split_doc` converts to canonical `new_shares / old_shares` via exact `tofactor / forfactor` when both are positive numbers (avoiding 6-decimal truncation like `0.142857` for 7:1), or `1.0 / splitratio` otherwise. `ratio == 1.0` no-ops are **decoded, not dropped** here (downstream builders drop them) and counted in `BsonQmActionDecodeStats::split_noop_ratio_one` (a subset of `decoded`, never added to `rejected_total()`). Cited: `design/DATA-CONTRACTS.md` §1 (line 25). - - `usdFxRate` (`FIELD_USD_FX_RATE`): explicitly ignored without calling `elem.value()` per `design/DATA-CONTRACTS.md` §1 (line 25: bogus `usdFxRate: 1` on CAD dividend rows). All other unknown extra fields (`_id`, `symbol`, `exchange`, `reportDate`, `created_at`, `updated_at`, nested objects/arrays) are likewise skipped without decoding. - - `amount` (`FIELD_DIVIDEND_CASH`): BSON `Double`, `Int32`, or `Int64`; must be finite and `>= 0.0` (`-0.0` normalized to `+0.0`). See **Unverified field names** below. - - `currency` (`FIELD_DIVIDEND_CURRENCY`): BSON UTF-8 `String` (borrowed verbatim; empty or whitespace-only is rejected). See **Unverified field names** below. -2. **Zero-allocation key mapping & builder conversions:** - - `RawQmSplit::to_split_event` → `SplitEvent`, `to_split_action_event` → `SplitActionEvent`; `RawQmDividend::to_dividend_event` → `DividendEvent`, `to_dividend_action_event` → `DividendActionEvent`. - - `try_map_key(|code, ex_date| ...)` and `try_into_*` helpers mirror `RawEodDailyBar::try_into_eod_daily_bar` so callers can resolve `("qm", qmSearchCode, ex_date)` through `ProviderMappingTable` before allocating `currency` on dividends. -3. **Typed errors & stream accounting policy:** - - Never panics on untrusted input. `BsonQmActionError` names the offending field on every field-level error (`MissingField`, `EmptyField`, `WrongType`, `MalformedDate`, `InvalidNumber`, plus framing variants `TruncatedDocument`, `CorruptDocumentLength`, `CorruptBson`). - - Buffer decoders report and skip per-document errors without aborting the stream, always reconciling `decoded + rejected_total() == docs_in`. -4. **Unverified field names:** - - `amount` (`FIELD_DIVIDEND_CASH`) and `currency` (`FIELD_DIVIDEND_CURRENCY`) could not be proven from any in-repo schema or fixture (`events.action.ts` spreads `...dividend` untyped and `design/DATA-CONTRACTS.md` names only `date`, `declared`, and `usdFxRate` for `qmDividends`). Both are isolated in single `pub const` constants so the live MongoDB cursor task can confirm or adjust them in one place before touching QA data. - - Numeric strings (e.g. `"10.0"`, `"1.42"`) are currently rejected as `WrongType` because no in-repo source proves QuoteMedia sends `splitratio` or dividend cash as strings; live schema inspection should confirm whether string coercion is needed. + - MongoDB driver (`mongodb` crate) read-only cursor streaming, `rayon` parallel sharding, `provider_mapping` PostgreSQL preload wiring, end-to-end `curate bars_1d` CLI command, and decoders for other collections (`qmPrices`, `qmSplits`, `qmDividends`, `ceoShorts`, `qmFilings`, `qmEarnings`, `eodIntraday1M`). ## Local Benchmarks @@ -717,55 +669,6 @@ Command (`2026-11-28`, two back-to-back runs with identical checksum `0x05af9d27 - Run 2: `elapsed=217.38 ms`, `throughput=4600307 rows/s`, `scan=1253.15 MB/s`, `latency=217.38 ns/row`, `checksum=0x05af9d2746d1b5e3` - Extrapolation to full `846,000,000` `eodPrices` documents on one core (decode-only, excluding MongoDB cursor I/O and Parquet writes): `183.9 s`–`187.7 s` (`3.07`–`3.13 min`). -### `bench-bson-qm-actions` - -Fixed-seed (`std`-only SplitMix64) zero-copy raw BSON decode benchmark over `1,000,000` realistic synthetic QuoteMedia corporate-action documents (~4% `qmSplits`, ~96% `qmDividends`, with extra metadata `_id`, `symbol`, `exchange`, `reportDate`, `created_at`, `updated_at`, bogus `usdFxRate: 1`, `declared` present/missing/`Null`, ~5% BSON `DateTime` dates, mixed `Double`/`Int32`/`Int64` numerics, ~1.5% `splitratio == 1` no-ops, and ~0.5% deterministic rejected rows) pre-encoded into two contiguous length-prefixed buffers up front, timing decode-only via `decode_qm_split_buffer` and `decode_qm_dividend_buffer`: - -```bash -cargo run --release -p curate-etl --offline -- bench-bson-qm-actions [rows] -``` - -Command (`2026-11-28`, two back-to-back runs with identical checksum `0x6d48cd59e46dc9dc`): `cargo run --release -p curate-etl --offline -- bench-bson-qm-actions` - -- Input: `rows=1000000`, `splits=40146`, `dividends=959854`, `bytes=236043886` (~225.1 MiB, ~236.0 bytes/doc) -- Splits: `decoded=39937`, `noop_ratio_one=616`, `rejected=209` (`missing=93`, `empty=0`, `wrong_type=45`, `malformed_date=38`, `invalid_number=33`, `corrupt=0`) -- Dividends: `decoded=954952`, `rejected=4902` (`missing=1952`, `empty=0`, `wrong_type=1009`, `malformed_date=946`, `invalid_number=995`, `corrupt=0`) -- Run 1: `elapsed=275.12 ms`, `throughput=3634828 docs/s`, `scan=818.23 MB/s`, `latency=275.12 ns/doc`, `checksum=0x6d48cd59e46dc9dc` -- Run 2: `elapsed=282.92 ms`, `throughput=3534598 docs/s`, `scan=795.67 MB/s`, `latency=282.92 ns/doc`, `checksum=0x6d48cd59e46dc9dc` - -## Raw BSON Streaming Reader (`bson_stream`, `M1.2y`) - -`RawBsonChunkReader` (`src/bson_stream.rs`) frames arbitrary concatenated length-prefixed raw BSON streams (files, stdin pipes, or future cursor adapters) into whole-document [`RawBsonChunk`] slices using a single reused buffer, feeding the existing zero-copy decoders (`decode_eod_price_buffer`, `decode_qm_split_buffer`, `decode_qm_dividend_buffer`) unchanged without requiring the full dataset to fit in memory. - -1. **Bounded memory & exact growth:** - - Defaults: `DEFAULT_CHUNK_CAPACITY_BYTES = 8 MiB`, `DEFAULT_MAX_DOC_BYTES = 16 MiB + 16 KiB` (MongoDB max document size plus headroom). `BsonStreamOptions::validate` rejects `chunk_capacity_bytes == 0` (`InvalidChunkCapacity`) and `max_doc_bytes < 5` (`InvalidMaxDocBytes`). - - Reuses one internal `Vec` buffer across chunks, compacting any trailing partial document to the front via `copy_within`. Grows only via `reserve_exact` + `resize` when a single document exceeds the current buffer length (or to 4 bytes when `chunk_capacity_bytes < 4`), and never beyond `max_doc_bytes`. `buffer_capacity()` exposes the current allocation ceiling. - - Retries `ErrorKind::Interrupted` transparently and handles arbitrary short reads down to 1 byte at a time. -2. **Error semantics & sticky terminal state:** - - Complete prefix documents already buffered are always yielded before surfacing a trailing framing or I/O error. - - Terminal errors carry the absolute byte `offset: u64` of the offending document: declared length `< 5` or `> max_doc_bytes` → `CorruptDocumentLength`; EOF mid-header or mid-document → `TruncatedDocument`; underlying read error → `Io`. After any terminal error, subsequent `next_chunk()` calls keep returning an error without panicking, looping, or re-reading the underlying source. -3. **Streaming decode helpers (`for<'a>` callbacks):** - - `decode_eod_price_stream` / `decode_eod_price_chunks` → `Result` - - `decode_qm_split_stream` / `decode_qm_split_chunks` → `Result` - - `decode_qm_dividend_stream` / `decode_qm_dividend_chunks` → `Result` - - `decode_te_data_stream` / `decode_te_data_chunks` → `Result` (borrowed historical `TeDataPoint<'a>` points only — `forecast` unread — with absolute `u64` error offsets) - - Because borrowed zero-copy views (`RawEodDailyBar<'a>`, `RawQmSplit<'a>`, `RawQmDividend<'a>`) borrow from the reused chunk buffer, callbacks are higher-ranked (`for<'a> FnMut(...)`). Per-document decode errors are skipped and reported with absolute `u64` stream offsets (rebasing embedded `offset` fields on `CorruptBson` errors), and chunk stats sum via `AddAssign` so `decoded + rejected_total() == docs_in` holds across the entire stream. - -### `bench-bson-stream` - -Fixed-seed (`std`-only SplitMix64) streaming vs in-memory buffer decode benchmark over `2,000,000` synthetic `eodPrices` documents (reusing the exact `bench-bson-eod-prices` generator), decoding once via `decode_eod_price_buffer` and once via `RawBsonChunkReader` + `decode_eod_price_chunks` over an irregular short-read adapter (`257 B`..`128 KiB` prime steps straddling document and 4-byte header boundaries), asserting identical stats and checksum: - -```bash -cargo run --release -p curate-etl --offline -- bench-bson-stream [rows] -``` - -Command (`2026-11-28`): `cargo run --release -p curate-etl --offline -- bench-bson-stream` - -- Input: `rows=2000000`, `bytes=571280190` (~544.8 MiB) -- Decode: `decoded=1989987`, `rejected=10013` (`missing=3964`, `empty=0`, `wrong_type=2033`, `malformed_date=2027`, `invalid_number=1989`, `corrupt=0`), `checksum=0x94f87c60c9d3fbc6` -- Buffer baseline: `elapsed=524.54 ms`, `throughput=3812856 rows/s`, `scan=1038.65 MiB/s` -- Streamed short-read: `elapsed=544.59 ms`, `throughput=3672494 rows/s`, `scan=1000.42 MiB/s`, `ratio=0.963x`, `peak_buffer_capacity=8388608 bytes` (8 MiB) - ## Deferred Follow-Ups (`M1.3+` / `M2`) This crate currently depends only on `bson` (`=3.1.0`, `default-features = false, features = ["compat-3-0-0"]`) and `parquet` (`=60.2.0`, Zstd-only, no Arrow/async) so all tests and benchmarks run strictly offline. Follow-up tasks will add: @@ -900,30 +803,6 @@ Command (`2026-11-28`, two back-to-back runs with identical checksum `0x0a1b7ace - Parquet write: `elapsed=682.82 ms`, `throughput=709419 rows/s` - Combined (stage → Parquet): `elapsed=1272.06 ms`, `throughput=393065 rows/s` -## `posts` Curation Stage (`M2.2h`) - -`curate_posts` and `curate_and_write_posts` (`src/curate_posts.rs`) join `build_posts`, `ProviderMappingTable`, `parquet_posts`, and `write_events_dataset` into contract `EventsParquetRow` records strictly ascending in the 7-field writer sort key `(listing_id, ts_micros, kind, subtype, payload_json, known_at_micros, known_at_source)`. - -1. **Contract & Eastern-posting-date mapping rules:** - - Validates that `mapping_source` is non-blank before consuming the input iterator (`CuratePostsError::EmptyMappingSource`), then runs `build_posts` unchanged on source keys so global `spiel_id` deduplication, `bot == "1"` newswire vs. retail splitting, and the `edited` text `known_at` guard execute before listing resolution. - - **Mapping date (`posted_at` in `America/Toronto`):** resolves `(mapping_source, key, et_date) -> listing_id` where `et_date` is the Eastern local calendar date of `posted_at` computed via `session_close::utc_micros_to_et_local` (supported Eastern calendar range `1976-01-01..=2030-12-31`, i.e. `1976-01-01T05:00:00Z..=2031-01-01T04:59:59.999999Z`). Never uses the UTC date and never uses the `known_at` date, so a post edited days later stays on the listing active when it was posted while its text remains guarded by `known_at`. - - Uses one `ProviderMappingTable::cursor_for` per contiguous `key` run in each builder stream (`newswire`, then `retail`); because `build_posts` sorts by `(key, known_at, spiel_id)` rather than `posted_at`, backward `et_date` steps use `ProviderMappingCursor::resolve`'s binary-search fallback automatically. - - Converts each mapped `PostRow` via `EventsParquetRow::from` (reusing `parquet_posts` labels `kind = "post"`, `subtype = "newswire" | "retail"`, `known_at_source = "post_timestamp" | "post_edited"`, and its RFC 8259 `payload_json` encoder), then sorts in place by the 7-field writer key and collapses exact 7-field duplicates into `listing_duplicate_collapsed`. - - `curate_and_write_posts` publishes Zstd Parquet partitions to `/events/year=YYYY/part.parquet` (partitioned by UTC calendar year of `ts_micros`). Any `CuratePostsError` returns before `write_events_dataset` is called, leaving `out_dir` untouched. -2. **Drop policy & stats conservation invariants (`CuratePostsStats`):** - - Posts whose `posted_at` falls outside `utc_micros_to_et_local`'s supported range are dropped and counted in `dropped_unsupported_date` (checked before mapping coverage) without aborting or panicking. - - Posts whose `(mapping_source, key, et_date)` has no covering `provider_mapping` range are dropped into `dropped_unmapped`. - - Exact conservation invariants: - - `rows_in == builder.newswire + builder.retail` - - `rows_in == rows_out + dropped_unmapped + dropped_unsupported_date + listing_duplicate_collapsed` - - `rows_out == newswire_out + retail_out` - - Typed errors: `CuratePostsError` (`Posts(PostsError)`, `EmptyMappingSource`) and `CuratePostsWriteError` (`Curate(CuratePostsError)`, `Parquet(ParquetEventsError)`). -3. **Known limits & deferred work:** - - **Global `spiel_id` deduplication & `listing_duplicate_collapsed`:** because `build_posts` deduplicates globally on `spiel_id` (keeping the greatest `known_at` and breaking ties by the maximum `(posted_at, is_edited, is_bot, key, user_id, text)` tuple) and `payload_json` carries `spiel_id`, `listing_duplicate_collapsed` is expected to be `0` for real input and exists only as a defensive writer-key uniqueness guard; when the same `spiel_id` appears under two source keys, the surviving key is chosen by `build_posts`'s existing tie-break. - - **In-memory buffering:** both `build_posts` and the final 7-field sort buffer all rows in RAM; full-corpus memory and throughput over the 14.8M-row `ceoPosts` dataset remain unverified. - - **Separate output root (no co-publishing with `curate-events`):** `write_events_dataset` writes and replaces `/events/year=YYYY/part.parquet` partitions, so publishing curated posts alongside `curate-events` filings/earnings in the same `events/` directory is not handled here; pass a dedicated `out_dir` until a unified publisher exists. - - **Not done / deferred:** benchmark, `--from-mongo` / live `ceoPosts` run and schema verification, and co-publishing posts with `curate-events` output remain deferred to follow-up tasks. - ## `fx_1d` Curation Stage (`M1.2t`) `curate_fx_1d` and `curate_and_write_fx_1d` (`src/curate_fx.rs`) join `build_fx_1d` and `write_fx_1d_dataset` into contract `Fx1dParquetRow` records sorted and unique by `session_date` (no `provider_mapping` lookup is needed because FX rows are keyed by `pair = "USDCAD"`, not `listing_id`). @@ -962,913 +841,3 @@ cargo run --release -p curate-etl --offline -- bench-curate-fx [rows] - Parquet write: `files=1`, `row_groups=1`, `bytes=27440094`, `read_back_rows=859916`, `elapsed=215.804 ms`, `throughput=3984706 rows/s` - Combined (stage → Parquet): `elapsed=275.456 ms`, `throughput=3630342 rows/s` - Overlap: `te_superseded=103169`, `checked=103169`, `within_tol=97958`, `mismatched=5211`, `max_overlap_rel=0.025000` - -## `adj_factors` Curation Stage (`M1.2v`) - -`curate_adj_factors`, `curate_adj_factors_as_of`, `curate_and_write_adj_factors`, `curate_and_write_adj_factors_as_of`, `read_adj_factors_dataset`, `read_adj_factors_dataset_as_of`, and `adj_factors_for_bar` (`src/curate_adj.rs`) join `ProviderMappingTable`, `build_adj_factors`, `session_close::et_session_close_utc_micros`, and `write_adj_factors_dataset` into contract `AdjFactorsParquetRow` records sorted and unique by `(listing_id, ex_date)`. - -1. **Map-before-build rule:** - - Resolves every source-keyed `qmSplits` and `qmDividends` event via `(mapping_source, source_key, ex_date) -> listing_id: i32` (using a cached per-key `ProviderMappingCursor`) *before* invoking `build_adj_factors::` unchanged. - - Cumulative factors (`cum_split_factor`, `cum_total_factor`) therefore chain continuously per permanent `listing_id` across ticker renames (two adjacent source-key ranges mapping to one `listing_id`), while ticker reuse across distinct `listing_id`s (e.g. `FB` 2012–2022 vs `FB` 2025+) produces two independent chains with no cross-listing bleed. - - Unmapped splits and dividends are dropped and counted separately (`splits_dropped_unmapped`, `dividends_dropped_unmapped`). -2. **Collision policy (fail closed on cross-key conflict):** - - Single-source-key groups on `(listing_id, ex_date)` pass through unchanged to `build_adj_factors` (preserving same-day multi-dividend summation, same-day split multiplication, `1:1` no-op drops, and zero-cash dividend drops). - - Multi-source-key groups with bitwise-identical split ratios (or bitwise-identical dividend `cash`/`currency`/`prev_close`/`prev_close_currency`) collapse to one event and are counted in `splits_collision_collapsed`, `dividends_collision_collapsed`, and `listing_collision_collapsed`. - - Multi-source-key groups with conflicting split ratios or differing dividend payloads fail closed with `CurateAdjError::ConflictingCrossKeySplit` / `CurateAdjError::ConflictingCrossKeyDividend` (silently dropping or doubling an event would corrupt every earlier cumulative factor). -3. **Conservative `known_at` & point-in-time / vault-fence policy:** - - Stamps every curated row with `known_at_micros = session_close::et_session_close_utc_micros(ex_date)` (`16:00:00 America/New_York` / `America/Toronto`: `21:00 UTC` in EST, `20:00 UTC` in EDT) because `qmSplits` / `qmDividends` adj builder inputs carry no announcement timestamp. - - Any mapped row whose `ex_date` lies outside `1976-01-01..=2030-12-31` returns `CurateAdjError::ExDateOutOfRange` naming `(listing_id, ex_date)` without panicking (dropping a row would break the cumulative chain). - - **Retrospective vs. Point-in-Time snapshots:** because `cum_split_factor` and `cum_total_factor` are right-to-left suffix products, later splits and dividends are embedded in earlier rows. `curate_adj_factors` / `curate_and_write_adj_factors` explicitly tag their output as `AdjSnapshotKind::RetrospectiveSnapshot` — slicing a retrospective snapshot with a bare `known_at <= as_of` filter would still leak future or held-out vault actions into earlier bars. - - **Point-in-time & Vault fencing:** `curate_adj_factors_as_of` / `curate_and_write_adj_factors_as_of` accept an `AdjPointInTimeFence { as_of_micros, vault_cutoff_micros }` (`known_at <= as_of_micros` inclusive and `known_at < vault_cutoff_micros` strictly exclusive, matching `design/DATA-CONTRACTS.md` §4) and fence mapped source events *before* compaction and compounding, tagging the output as `AdjSnapshotKind::PointInTimeFenced(fence)`. Appending any future or vault-held action leaves earlier rows and `adj_factors_for_bar` reads bitwise identical. - - **Persisted Parquet footer metadata & verified readers:** `curate_and_write_adj_factors` / `curate_and_write_adj_factors_as_of` publish `/adj_factors/part.parquet` in a single atomic file commit (one dataset lock, exclusive staging, live-preserving backup, single `rename`) embedding `stock_bot.adj_factors.{format_version, snapshot_kind, as_of_micros, vault_cutoff_micros, rows_written, snapshot_checksum}` directly in the Parquet footer `key_value_metadata` (where `snapshot_checksum` binds `format_version`, `snapshot_kind` / exact fence, row count, and all 8 columns of every row). When a run produces 0 rows (e.g. a fence excludes every event), an explicit 0-row Zstd Parquet file with the contract schema and embedded footer metadata is atomically published so any previous `part.parquet` is superseded rather than left stale. `read_adj_factors_dataset_as_of` requires a non-retrospective fence, fails closed on missing/corrupt/unsupported footer metadata, rejects retrospective snapshots (`RetrospectiveSnapshotRejected`) or any mismatched fence (`IncompatibleFence`), checks every row's `known_at` against the fence (`RowOutsideFence`), verifies per-listing `cum_split_factor` reverse suffix products, and verifies the bound `snapshot_checksum` (`SnapshotIntegrityMismatch`). -4. **Accounting & error handling:** - - Exact conservation invariants in `CurateAdjFactorsStats`: - - `splits_in == splits_dropped_unmapped + splits_dropped_fenced + splits_collision_collapsed + builder.split_events_in` - - `dividends_in == dividends_dropped_unmapped + dividends_dropped_fenced + dividends_collision_collapsed + builder.dividend_events_in` - - `listing_collision_collapsed == splits_collision_collapsed + dividends_collision_collapsed` - - `rows_out == builder.rows_out` and `listings_out == builder.keys_out` - - For `AdjSnapshotKind::RetrospectiveSnapshot`, `splits_dropped_fenced == 0` and `dividends_dropped_fenced == 0`. - - `curate_and_write_adj_factors` / `curate_and_write_adj_factors_as_of` run curation before touching `out_dir`, so any `CurateAdjError` leaves `out_dir` untouched and publishes no `adj_factors/part.parquet` (surfacing via `CurateAdjWriteError::{Curate, Parquet}`). -5. **Deferred items:** - - Live MongoDB cursor streaming and BSON decoders for `qmSplits` / `qmDividends` - - PostgreSQL `provider_mapping` preload - - Sourcing `DividendEvent.prev_close` from `bars_1d` (currently supplied by the caller) - - `rayon` parallel sharding and end-to-end `curate` CLI command - -### `bench-curate-adj` - -Fixed-seed (`std`-only SplitMix64) benchmark over `1,000,000` (default) or `[events]` source-keyed `qmSplits` (~4%) and `qmDividends` (~96%) events across `20,000` `String` source keys spanning `1990..=2025` (single-range keys, ticker-rename pairs, ticker-reuse keys with an H2-2018 gap, unmapped keys, and explicit bitwise-identical alias keys), separately timing in-memory `curate_adj_factors` and Zstd Parquet `write_adj_factors_dataset` into a temp directory with footer row-count verification and cleanup: - -```bash -cargo run --release -p curate-etl --offline -- bench-curate-adj [events] -``` - -Command (`2026-11-28`, two back-to-back runs with identical checksum `0x024ec73a1afe7e6b`): `cargo run --release -p curate-etl --offline -- bench-curate-adj` - -- Input: `events=1000000`, `splits=40221`, `dividends=959779`, `keys=20000` -- Builder: `rows_out=946414`, `keys_out=19500`, `split_noops=1938`, `zero_div=9234`, `missing_prev_close=18458`, `currency_mismatch=18461`, `not_below_prev_close=9193` -- Output: `rows_out=946414` (`94.64%` retained), `listings_out=19500`, `files=1`, `row_groups=1`, `bytes=11872037`, `read_back_rows=946414` -- Curation stats: `splits_unmapped=1486`, `divs_unmapped=34220`, `splits_coll_collapsed=213`, `divs_coll_collapsed=4717`, `coll_collapsed=4930` -- Run 1: - - Stage (in-memory): `elapsed=930.92 ms`, `throughput=1074206 events/s`, `latency=930.92 ns/event`, `checksum=0x024ec73a1afe7e6b` - - Parquet write: `elapsed=262.42 ms`, `throughput=3606439 rows/s` - - Combined (stage → Parquet): `elapsed=1193.34 ms`, `throughput=837982 events/s` -- Run 2: - - Stage (in-memory): `elapsed=933.02 ms`, `throughput=1071785 events/s`, `latency=933.02 ns/event`, `checksum=0x024ec73a1afe7e6b` - - Parquet write: `elapsed=262.81 ms`, `throughput=3601091 rows/s` - - Combined (stage → Parquet): `elapsed=1195.84 ms`, `throughput=836235 events/s` - -## `corporate_actions` Curation Stage (`M1.2u`) - -`curate_corporate_actions` and `curate_and_write_corporate_actions` (`src/curate_corporate_actions.rs`) join `build_corporate_actions`, `ProviderMappingTable`, `session_close::et_session_close_utc_micros`, and `write_corporate_actions_dataset` into contract `CorporateActionsParquetRow` records sorted deterministically with non-decreasing `(listing_id, ex_date, kind)`. - -1. **Field & timestamp rules:** - - Calls `build_corporate_actions` unchanged (`1:1` split no-ops, `0.0` cash dividends, and delistings without an outcome drop inside the builder; same-key multi-dividends stay separate; late declarations clamp to `ex_date` with `KnownAtSource::ExDateFallback`; local `currency` is preserved). - - Resolves `(mapping_source, key, ex_date) -> listing_id` via `ProviderMappingTable::cursor_for` / `ProviderMappingCursor::resolve` (one cursor per contiguous `key` run) for `split`, `dividend`, and terminal `delisting` rows. - - For `otc_delist_transfer` rows, Pass 6 anchors `ex_date` (and `known_at`) to `effectiveDate` (the successor's first OTC trading date), which normally falls after the outgoing listing's primary-venue `valid_to` (e.g. `SIVB.US` ends `2023-03-10`, `SIVBQ.US` starts `2023-03-28`) and may coincide with ticker reuse. `otc_delist_transfer` therefore requires Pass 6's outgoing listing identity via `CurateDelistingInput::from_listing_id` (`Some(id)`): curation selects only a `provider_mapping` range for `(mapping_source, key)` with `valid_from <= ex_date` and `listing_id == id` (never attaching to an unrelated ticker occupant), and any identity-less `otc_delist_transfer` (`from_listing_id = None`) drops into `dropped_unmapped`. `successor_key` is always resolved strictly on `ex_date` to `successor_listing_id`. Never emits an `otc_delist_transfer` with `successor_listing_id = None` or `successor_listing_id == listing_id`. - - Stamps `known_at_micros = et_session_close_utc_micros(known_at_date)` (`16:00:00 ET` of `known_at_date`, matching `bars_1d`'s conservative end-of-session convention because source corporate-action records carry no intraday announcement time) and carries `known_at_source` through unchanged. - - Carries `ex_date`, `declared_date`, `kind`, `ratio`, `cash_amount`, `currency`, and `terminal_return` through bit-exactly (`"USD"`/`"CAD"` interned as `Cow::Borrowed`). -2. **Drop & collision policy (never panics or aborts on bad rows):** - - Strict drop priority per built row: - 1. `dropped_unmapped`: no covering `provider_mapping` range for `(mapping_source, key, ex_date)` (or, for `otc_delist_transfer`, missing `from_listing_id = None` or no range with `valid_from <= ex_date` matching `from_listing_id = Some(id)`; or, for terminal `delisting` with `from_listing_id = Some(id)`, active occupant does not match `id`). - 2. `dropped_unmapped_successor`: `otc_delist_transfer` whose `successor_key` has no covering range on `ex_date`. - 3. `dropped_self_successor`: `otc_delist_transfer` whose `successor_key` resolves to the row's own `listing_id`. - 4. `dropped_known_at_out_of_range`: `known_at_date` falls outside `et_session_close_utc_micros`'s `1976-01-01..=2030-12-31` window. - - After re-sorting deterministically by all 11 columns (prefix `(listing_id, ex_date, kind)`): - - Cross-key conflicting `split` ratios on the same `(listing_id, ex_date)` (`> 1` source key and `> 1` distinct `ratio` bit pattern) drop the entire group (`listing_collision_dropped`). - - Bitwise-identical rows from multiple source keys collapse to `max_per_key` copies (`listing_collision_collapsed`), preserving same-key multi-dividends (including equal-amount same-day regular + special dividends) while collapsing cross-key aliases. - - Exact conservation invariant in `CurateCorporateActionsStats`: `rows_in == builder.rows_out` and `rows_in == rows_out + dropped_unmapped + dropped_unmapped_successor + dropped_self_successor + dropped_known_at_out_of_range + listing_collision_collapsed + listing_collision_dropped`. - - Typed caller errors: `CurateCorporateActionsError` (`CorporateAction(CorporateActionError)`, `EmptyMappingSource`) and `CurateCorporateActionsWriteError` (`Curate(CurateCorporateActionsError)`, `Parquet(ParquetCorporateActionsError)`). A curate error in `curate_and_write_corporate_actions` returns before invoking `write_corporate_actions_dataset`, leaving `out_dir` untouched. - -### `bench-curate-corporate-actions` - -Fixed-seed (`std`-only SplitMix64) benchmark over `520,000` source-keyed corporate-action events (~3.6% splits ≈20.3k incl. `1:1` no-ops and alias collisions, ~95.4% USD/CAD dividends ≈494.6k incl. `0.0` drops and same-day multi-dividends, ~1.0% delisting outcomes ≈5.1k incl. OTC transfers and `-0.3`/`-1.0`/no-outcome) across `20,000` `String` keys with multi-range `provider_mapping` reuse gaps, aliases, unmapped/self successors, and pre-1976 dates, separately timing in-memory `curate_corporate_actions` and Zstd Parquet `write_corporate_actions_dataset` into a temp directory with footer row-count verification and cleanup: - -```bash -cargo run --release -p curate-etl --offline -- bench-curate-corporate-actions [events] -``` - -Command (`2026-11-28`, two back-to-back runs with identical checksum `0x0c22a1a1ab7caad4`): `cargo run --release -p curate-etl --offline -- bench-curate-corporate-actions` - -- Input: `events=520000`, `splits=20262`, `dividends=494624`, `delistings=5114`, `keys=20000` -- Builder: `rows_out=514224`, `splits_out=19938`, `split_noops=324`, `divs_out=489671`, `zero_div=4953`, `otc_out=2856`, `delist_out=1759`, `delist_no_outcome=499` -- Output: `rows_out=494518` (`95.10%` retained), `listings_out=19996`, `files=1`, `row_groups=1`, `bytes=3802001`, `read_back_rows=494518` -- Curation stats: `unmapped=12886`, `unmapped_succ=511`, `self_succ=531`, `known_at_oor=2526`, `coll_collapsed=1398`, `coll_dropped=1854` -- Run 1: - - Stage (in-memory): `elapsed=278.66 ms`, `throughput=1866040 events/s`, `latency=535.89 ns/event`, `checksum=0x0c22a1a1ab7caad4` - - Parquet write: `elapsed=84.14 ms`, `throughput=5877527 rows/s` - - Combined (stage → Parquet): `elapsed=362.80 ms`, `throughput=1433288 events/s` -- Run 2: - - Stage (in-memory): `elapsed=284.33 ms`, `throughput=1828877 events/s`, `latency=546.78 ns/event`, `checksum=0x0c22a1a1ab7caad4` - - Parquet write: `elapsed=87.57 ms`, `throughput=5647404 rows/s` - - Combined (stage → Parquet): `elapsed=371.89 ms`, `throughput=1398252 events/s` - -## `curate-bars-1d` Command (`M1.2z` / `M1.2ah` / `M1.2ai`) - -End-to-end file-to-Parquet CLI command (`src/run_curate_bars.rs`) wiring `RawBsonChunkReader`, `decode_eod_price_chunks`, `decode_qm_split_chunks`, optional `decode_qm_price_chunks` (`src/bson_qm_prices.rs`), `ProviderMappingTable`, `SplitTable`, and `curate_and_write_bars_1d` (with `rayon` year-sharded parallel Zstd Parquet encoding) into `/bars_1d/year=YYYY/part.parquet` with no database connections. - -### Invocation - -```bash -curate-etl curate-bars-1d \ - --eod-prices # concatenated raw BSON (mongodump eodPrices.bson) - --qm-splits # concatenated raw BSON (mongodump qmSplits.bson) - [--qm-prices ] # optional concatenated raw BSON (qmPrices.bson) for read-only sharevolume cross-check - --curate-inputs # exporter output dir (pins /current once before opening TSVs) - --out # dataset root -> bars_1d/year=YYYY/part.parquet - [--rel-tolerance ] # default: 0.01 - [--threads ] # default: available_parallelism() (1 = bounded-RAM sequential write) -``` - -Instead of `--curate-inputs `, standalone TSV files may be passed directly with `--provider-mapping --listing-currencies ` (mutually exclusive with `--curate-inputs`). When reading from a live exporter output directory, always prefer `--curate-inputs ` so `curate-bars-1d` pins `/current` once before opening either TSV and cannot mix generations across a concurrent refresh. - -Both `--flag value` and `--flag=value` forms are accepted (in the separated `--flag value` form, a following `--...` token is rejected as a missing value; use `--flag=value` for literal paths starting with `--`). Invalid/missing/duplicate flags exit non-zero with usage on stderr. Runtime errors (missing files, truncated or oversized BSON documents, malformed TSV lines, overlapping mapping ranges, conflicting cross-key QM splits, unwritable `--out`) print a single-line stderr message naming the offending path (and 1-based line number for TSV errors), exit non-zero, and leave no partial `bars_1d` files under `--out`. Volume cross-check mismatches never fail the run (exit code `0`) and never modify emitted Parquet bytes. - -### `qmPrices` Raw BSON Decoder (`src/bson_qm_prices.rs`) - -- **Documented field names & raw-volume semantics** (`prices.action.ts:97-109`, `bar-spans.ts:19-24`, `sample-closes.ts:300-303`, `design/DATA-CONTRACTS.md` §1): `qmPrices` stores QuoteMedia daily bars keyed by `qmSearchCode` with provider date field `date` (and a separate BSON `Date` in `dateTime`) and unadjusted share volume in `sharevolume`. -- **Accepted BSON types (live `qmPrices` date format and numeric type distribution remain unverified against QA MongoDB):** - - `qmSearchCode`: BSON UTF-8 `String` borrowed verbatim (never trimmed; empty/whitespace-only rejected as `EmptyField`). - - `date`: strict 10-byte ASCII `YYYY-MM-DD` BSON `String` validated via `parse_ymd_strict_days` (non-string `date` — including BSON `DateTime` — is rejected as `WrongType` and counted in `qm_bson.rejected`; bad format/calendar strings are rejected as `MalformedDate`). - - `sharevolume`: BSON `Double`, `Int32`, or `Int64` converted to `f64`. Numeric domain validity (negative / non-finite) is passed through to `build_bars_1d` (`qm_invalid_volume_dropped`); missing, `Null`, or non-numeric types are rejected with counted reasons. - - All extra fields (`_id`, `dateTime`, `unadjustedopen..unadjustedclose`, nested docs/arrays) are skipped without calling `elem.value()`. -- **Accounting invariant:** `docs_in == decoded + rejected_total()` (`rejected_missing_field + rejected_empty_field + rejected_wrong_type + rejected_malformed_date + rejected_corrupt_document`). - -### TSV Formats (strict, headerless, `\t`-separated) - -- `provider_mapping`: `source \t source_id \t valid_from(YYYY-MM-DD) \t valid_to(YYYY-MM-DD or empty) \t listing_id` - - `source` and `source_id` are preserved verbatim (never trimmed); blank/whitespace-only values are rejected. - - Dates are parsed strictly with `YYYY-MM-DD` Gregorian validation; `listing_id` must be a strict positive ASCII integer. -- `listing_currencies`: `listing_id \t currency` - - Unique positive `listing_id` per row; non-blank currency code (`"USD"` and `"CAD"` are interned). -- Both files accept `\n` or `\r\n` line endings and at most one trailing blank line. Header rows, wrong column counts, interior blank lines, multiple trailing blank lines, interior `\r`, and invalid UTF-8 are rejected with the 1-based line number. - -### Split Re-Keying, `qmPrices` Re-Keying, Early Filter & Missing-Currency Policy - -1. **Split re-keying (`qmSearchCode` → `eodSearchCode`):** Each decoded `qmSplits` row with `ratio != 1.0` resolves `("qm", qmSearchCode, ex_date) -> listing_id` via `ProviderMappingTable`. Before fanning out to `"eod"` partners, mapped splits are compacted by `(listing_id, ex_date)` using the same cross-key policy as `curate_adj_factors`: single-QM-key same-day groups pass through unchanged, multi-QM-key alias groups with bitwise-identical ratios collapse to one event (`splits_collision_collapsed`), and multi-QM-key groups with conflicting ratios fail closed (`ConflictingCrossKeySplit`). Surviving events are attached to every deduplicated `"eod"` `source_id` pointing at that `listing_id` (preventing ratio squaring when one `(listing_id, eod_source_id)` spans multiple date ranges). No ticker-text guessing is performed. -2. **Date-aware `qmPrices` volume re-keying (optional `--qm-prices`):** Each decoded `qmPrices` row resolves `("qm", qmSearchCode, session_date) -> listing_id` via `ProviderMappingTable`, then fans out only to `"eod"` `source_id`s whose mapping range covers `session_date` (reusing interned `Arc` EOD keys; no ticker-text guessing, so reused EOD tickers never receive volumes from another occupant). Unmapped QM keys and QM rows whose `listing_id` has no date-covering `"eod"` partner are early-filtered before buffering into `qm_unmapped_qm` and `qm_no_eod_partner`. When `--qm-prices` is omitted, no reverse range index is built and `qm_volumes` stays empty. -3. **Early filter & key interning:** While streaming `eodPrices`, bars whose `eodSearchCode` has no `"eod"` range in `provider_mapping` are dropped before buffering (`bars_unmapped_source_dropped`). Retained bars share interned `Arc` keys rather than allocating a `String` per bar. -4. **Missing-currency behavior:** Delegated unchanged to `curate_bars_1d` — mapped listings absent from `--listing-currencies` (or blank) are dropped into `dropped_missing_currency` without failing the run. - -### Report Counters & Conservation Invariants - -On success, `curate-bars-1d` prints deterministic `key=value` lines to stdout (`eod_bson`, `splits_bson`, `splits`, `filter`, `builder`, `curate`, `write`, ascending `years`, `qm_check: qm_prices=absent` when `--qm-prices` is omitted or `qm_bson` / `qm_rekey` / `qm_check` + up to `100` `qm_mismatch` lines when supplied, `config: threads=`, and `timing`): - -- `splits_in == splits_applied + splits_collision_collapsed + splits_unmapped_qm + splits_no_eod_partner + splits_noop_dropped + splits_bson.rejected` -- `eod_bson.docs_framed == eod_bson.docs_in == eod_bson.decoded + eod_bson.rejected` -- `eod_bson.decoded == write.rows_written + bars_unmapped_source_dropped + builder.(invalid_ohlc + inconsistent_ohlc + invalid_vol + dup_collapsed + dup_conflict_dropped) + curate.(dropped_unmapped + dropped_missing_currency + dropped_ts_out_of_range + listing_collision_collapsed + listing_collision_dropped)` -- When `--qm-prices` is provided: - - `qm_bson.docs_framed == qm_bson.docs_in == qm_bson.decoded + qm_bson.rejected` - - `qm_rekey.qm_in == qm_rekey.qm_attached + qm_rekey.qm_unmapped_qm + qm_rekey.qm_no_eod_partner + qm_bson.rejected` - - `qm_rekey.qm_volumes_attached == qm_check.qm_rows_in` - - `qm_check.volume_checked + qm_check.volume_unchecked == builder.rows_out` - - `qm_check.volume_within_tolerance + qm_check.volume_mismatched == qm_check.volume_checked` - -### `bench-curate-bars-cmd` - -Fixed-seed (`std`-only SplitMix64) end-to-end file→Parquet benchmark synthesizing `eodPrices.bson`, `qmSplits.bson`, `qmPrices.bson` (matching `Double`/`Int32`/`Int64` `sharevolume` partners, unmapped QM keys, QM keys with no EOD partner, wrong-typed `sharevolume` rejects, and exact injected >1% divergences), `provider_mapping.tsv`, and `listing_currencies.tsv` into a temp dir, timing decode / qm decode+rekey / curate / sequential (`threads=1`, `write_1`) vs parallel (`threads=available_parallelism()`, `write` + `speedup`) Parquet writes on the exact same curated rows, verifying Parquet footer row counts for both outputs, and cleaning up on drop: - -```bash -cargo run -p curate-etl --release --offline -- bench-curate-bars-cmd [rows] -``` - -Single-threaded baseline measured locally (`2026-11-29`, prior to `rayon` parallel write; multi-thread `write_1` vs `write` numbers pending first unsandboxed release run after `rayon = "=1.12.0"` is fetched): - -1. **1,000,000 rows** (`cargo run -p curate-etl --release --offline -- bench-curate-bars-cmd 1000000`): - - Input: `rows=1000000`, `eod_bytes=161690000` (154.2 MiB), `splits_docs=2040`, `splits_bytes=188080`, `qm_docs=227439`, `qm_bytes=20815907` (19.9 MiB), `keys=2000` - - Decode (all inputs): `elapsed=234.63 ms`, `throughput=4262081 rows/s`, `scan=742.58 MB/s`, `unmapped_dropped=20000`, `buffered_bars=980000`, `buffered_bytes=67161784` (`68.5 bytes/bar`) - - QM decode + rekey: `elapsed=31.93 ms`, `throughput=7123258 docs/s`, `scan=621.74 MB/s`, `attached=224939`, `unmapped=1000`, `no_eod_partner=1000`, `rejected=500`, `checked=224939`, `within_tol=222689`, `mismatched=2250 (injected=2250)`, `unchecked=755021`, `samples=100` - - Curate: `elapsed=208.07 ms`, `throughput=4709887 rows/s`, `rows_out=938023` (`93.80%` retained), `listings_out=1941`, `unmapped=595`, `missing_curr=9500`, `ts_oor=1842`, `coll_collapsed=10000`, `coll_dropped=20000` - - Write: `elapsed=456.39 ms`, `throughput=2055293 rows/s`, `write=53.70 MB/s`, `files=36`, `row_groups=36`, `bytes=25699104`, `read_back_rows=938023` - - Total: `elapsed=899.09 ms`, `throughput=1112231 rows/s`, `throughput_mb=193.78 MB/s`, `splits_applied=1699`, `splits_coll_collapsed=40`, `splits_unmapped_qm=101`, `splits_no_eod_partner=100`, `splits_noop=100` -2. **5,000,000 rows** (`cargo run -p curate-etl --release --offline -- bench-curate-bars-cmd 5000000`): - - Input: `rows=5000000`, `eod_bytes=808449920` (771.0 MiB), `splits_docs=4080`, `splits_bytes=376160`, `qm_docs=1138361`, `qm_bytes=104186437` (99.4 MiB), `keys=6000` - - Decode (all inputs): `elapsed=1167.06 ms`, `throughput=4284272 rows/s`, `scan=746.08 MB/s`, `unmapped_dropped=99960`, `buffered_bars=4900040`, `buffered_bytes=537029672` (`109.6 bytes/bar`) - - QM decode + rekey: `elapsed=171.72 ms`, `throughput=6629277 docs/s`, `scan=578.63 MB/s`, `attached=1125861`, `unmapped=5000`, `no_eod_partner=5000`, `rejected=2500`, `checked=1125861`, `within_tol=1114602`, `mismatched=11259 (injected=11259)`, `unchecked=3773805`, `samples=100` - - Curate: `elapsed=1119.70 ms`, `throughput=4376207 rows/s`, `rows_out=4691865` (`93.84%` retained), `listings_out=5822`, `unmapped=2879`, `missing_curr=48328`, `ts_oor=9132`, `coll_collapsed=49206`, `coll_dropped=98256` - - Write: `elapsed=1238.26 ms`, `throughput=3789066 rows/s`, `write=79.75 MB/s`, `files=36`, `row_groups=36`, `bytes=103552480`, `read_back_rows=4691865` - - Total: `elapsed=3525.02 ms`, `throughput=1418430 rows/s`, `throughput_mb=247.01 MB/s`, `splits_applied=3399`, `splits_coll_collapsed=80`, `splits_unmapped_qm=201`, `splits_no_eod_partner=200`, `splits_noop=200` - -### Known Limits - -- **Full in-RAM buffering of mapped bars (and optional QM volumes) + parallel year-bucketing RAM:** `curate-bars-1d` buffers every mapped bar in `Vec>>` before sorting (`64 B/bar` struct size; measured `68.5–109.6 B/bar` including `Vec` geometric growth headroom, plus ~200 B/row peak during `curate_bars_1d` while `built.rows` and `Bars1dParquetRow` briefly coexist), plus `32 B/row` for mapped `QmRawVolume>` when `--qm-prices` is supplied (~1.6 GiB worst case if all 51.5M QM rows map). When `--threads > 1`, Pass 1 of `write_bars_1d_dataset` buckets validated `Bars1dParquetRow`s by year (`~136 B/row` struct size plus `Vec` growth slack, `~180–200 B/row` transient overhead before the caller's `curated.rows` vector drops) and holds up to `min(threads, years)` concurrent `RowGroupBuffer`s during parallel Zstd encoding (each year's bucket drops as soon as its worker finishes). Pass `--threads 1` to use the bounded-RAM single-pass streaming writer. For the US+CA subset (~100–150M rows of the 846M-row `eodPrices` collection), this implies roughly **20–30 GiB peak RAM** (viable on a 64 GiB workstation, tight on 32 GiB); running all 846M global rows unsharded would exceed 160 GiB. -- **Parallelism scope & direct MongoDB cursors:** `rayon` year-sharded parallelism currently covers the `curate-bars-1d` Parquet write stage (`--threads`); parallel BSON decode, parallel curate/sort, other `curate-*` commands, and direct MongoDB cursors remain deferred to follow-up tasks. -- **Ticker-reuse split keying caveat:** because `curate_bars_1d` takes `SplitTable` keyed by `eodSearchCode` rather than `listing_id`, attaching a split to every `"eod"` `source_id` pointing at a `listing_id` means a later split on a reused `eodSearchCode` could affect an earlier listing that previously held that same `eodSearchCode`. -- **Partition-level replacement on `--out` reuse:** `write_bars_1d_dataset` atomically replaces only the `bars_1d/year=YYYY/part.parquet` partitions emitted by the current run. Reusing an existing `--out` directory for a narrower year range leaves older year partitions intact on disk; use a fresh `--out` directory for a complete rebuild. - -## `curate-adj-factors` Command (`M1.2aa`) - -End-to-end file-to-Parquet CLI command (`src/run_curate_adj.rs`) wiring `RawBsonChunkReader`, `decode_qm_split_chunks`, `decode_qm_dividend_chunks`, `load_provider_mapping_tsv`, a column-projected `bars_1d` Parquet reader for strict pre-ex-date `prev_close`, and `curate_and_write_adj_factors` into an atomically published `/adj_factors/part.parquet` retrospective snapshot with zero extra crates and no database connections. - -### Invocation - -```bash -curate-etl curate-adj-factors \ - --qm-splits qmSplits.bson \ - --qm-dividends qmDividends.bson \ - --provider-mapping provider_mapping.tsv \ - --bars-1d ./out/bars_1d \ - --out ./out -``` - -Inputs and output: -- `--qm-splits `: concatenated raw BSON (`mongodump` `qmSplits.bson`). -- `--qm-dividends `: concatenated raw BSON (`mongodump` `qmDividends.bson`). -- `--provider-mapping `: headerless 5-column TSV (same format as `curate-bars-1d`). -- `--bars-1d `: `bars_1d` directory containing `year=YYYY/part.parquet` (or parent root containing `bars_1d/`). -- `--out `: dataset root where `adj_factors/part.parquet` is atomically published. - -Both `--flag value` and `--flag=value` forms are accepted (in the separated `--flag value` form, a following `--...` token is rejected as a missing value; use `--flag=value` for literal paths starting with `--`). Invalid, missing, duplicate, or unknown flags exit non-zero with usage on stderr. Any runtime error (missing input file, missing/invalid `--bars-1d` directory, missing/wrong-schema/corrupt `part.parquet`, duplicate `(listing_id, session_date)` in `bars_1d`, malformed `provider_mapping.tsv` reporting 1-based line number, truncated/oversized BSON stream, or cross-key split/dividend curation conflict) prints a single-line stderr message naming the offending path, exits non-zero, and returns before touching `--out` (leaving any pre-existing `/adj_factors/part.parquet` byte-identical). - -### `prev_close` Lookup & Contract Rules - -- **Column-projected `bars_1d` reader:** validates every discovered `year=YYYY/part.parquet` against `bars_1d_parquet_schema()` and reads only 4 of the 12 columns (`listing_id`, `session_date`, `close`, `currency`) in bounded `65,536`-row batches into a compact in-RAM index (`16 bytes/bar`, currency strings interned to `u16`). -- **Strict pre-ex-date boundary:** for each decoded `qmDividends` document, resolves `("qm", qmSearchCode, ex_date) -> listing_id` via `ProviderMappingTable` and attaches the raw `close` and `currency` of the last `bars_1d` session strictly before `ex_date` (`session_date < ex_date`; a bar on `ex_date` itself is never used). When no earlier bar exists (or the dividend is unmapped), `prev_close` and `prev_close_currency` are `None`. -- **`usdFxRate` & `splitratio == 1`:** `usdFxRate` stays ignored per `design/DATA-CONTRACTS.md` §1; `splitratio == 1` no-op handling and cross-key collision rules stay delegated unchanged to `curate_and_write_adj_factors`. Per-document BSON decode rejects are counted without aborting the run. - -### Report Counters & Conservation Invariants - -On success, `curate-adj-factors` prints deterministic `key=value` lines to stdout (`bars_1d`, `splits_bson`, `dividends_bson`, `prev_close`, `builder`, `curate`, `write`, and `timing`): - -- **Splits:** `splits_bson.docs_framed == splits_bson.docs_in == splits_bson.rejected + curate.splits_unmapped + curate.splits_fenced + curate.splits_coll_collapsed + builder.splits_in` -- **Dividends:** `dividends_bson.docs_framed == dividends_bson.docs_in == dividends_bson.rejected + curate.divs_unmapped + curate.divs_fenced + curate.divs_coll_collapsed + builder.dividends_in` -- **Dividend `prev_close` partition:** `dividends_bson.decoded == prev_close.with_prev_close + prev_close.without_prev_close + curate.divs_unmapped` - -### `bench-curate-adj-cmd` - -Fixed-seed (`std`-only SplitMix64) end-to-end file→Parquet benchmark synthesizing `provider_mapping.tsv`, a 16-year `bars_1d` Parquet dataset (`2010..=2025`, `62,720` bars across `3,920` mapped listings), `qmSplits.bson` (~4% of events incl. `1:1` no-ops, unmapped, identical cross-key aliases, and ~0.5% malformed decode rejects), and `qmDividends.bson` (~96% of events incl. USD/CAD with bogus `usdFxRate: 1`, `cash == 0.0`, unmapped, identical cross-key aliases, pre-first-bar dates for missing `prev_close`, currency mismatches, and ~0.5% malformed decode rejects) into a temp dir, timing `bars_load` / `decode` / `curate` / `write` separately, verifying Parquet footer row count, and cleaning up on drop: - -```bash -cargo run -p curate-etl --release --offline -- bench-curate-adj-cmd [events] -``` - -Measured locally (`2026-11-29`): - -1. **100,000 events** (`cargo run -p curate-etl --release --offline -- bench-curate-adj-cmd 100000`): - - Input: `events=100000`, `splits_docs=4000` (`422,398 B`), `dividends_docs=96000` (`11,592,112 B`), `bars_files=16`, `bars_rows=62720`, `keys=4000` - - `bars_load`: `elapsed=3.69 ms`, `throughput=17006461 bars/s` (`listings=3920`) - - `decode`: `elapsed=31.13 ms`, `throughput=3211920 events/s`, `scan=368.02 MB/s`, `splits_rejected=20`, `divs_rejected=453`, `with_prev_close=89914`, `without_prev_close=2792` - - `curate`: `elapsed=36.62 ms`, `throughput=2717561 events/s`, `rows_out=88215` (`88.22%` retained), `listings_out=3920`, `checksum=0xdacf704be0642aff` - - `write`: `elapsed=24.36 ms`, `throughput=3621493 rows/s`, `write=49.47 MB/s`, `files=1`, `row_groups=1`, `bytes=1263546`, `read_back_rows=88215` - - `total`: `elapsed=95.80 ms`, `throughput=1043793 events/s`, `checksum=0xdacf704be0642aff` -2. **500,000 events** (default; two back-to-back runs with identical checksum `0x16b8d07222f35849`): `cargo run -p curate-etl --release --offline -- bench-curate-adj-cmd` - - Input: `events=500000`, `splits_docs=20000` (`2,112,208 B`), `dividends_docs=480000` (`57,960,382 B`), `bars_files=16`, `bars_rows=62720`, `keys=4000` - - Output: `rows_out=431459` (`86.29%` retained), `listings_out=3920`, `files=1`, `row_groups=1`, `bytes=5539481`, `read_back_rows=431459` - - Run 1: `bars_load=3.76 ms` (`16,702,636 bars/s`), `decode=129.61 ms` (`3,857,829 events/s`, `442.03 MB/s`), `curate=283.10 ms` (`1,758,001 events/s`), `write=84.42 ms` (`5,111,126 rows/s`, `62.58 MB/s`), `total=500.88 ms` (`998,252 events/s`), `checksum=0x16b8d07222f35849` - - Run 2: `bars_load=3.73 ms` (`16,832,966 bars/s`), `decode=125.40 ms` (`3,987,232 events/s`, `456.85 MB/s`), `curate=228.61 ms` (`2,177,036 events/s`), `write=79.17 ms` (`5,449,842 rows/s`, `66.73 MB/s`), `total=436.90 ms` (`1,144,419 events/s`), `checksum=0x16b8d07222f35849` - -### Known Limits - -- **Retrospective snapshot only:** `curate-adj-factors` publishes an unfenced `AdjSnapshotKind::RetrospectiveSnapshot` whose earlier cumulative factors embed later splits/dividends. Point-in-time readers (`read_adj_factors_dataset_as_of`) reject retrospective snapshots automatically; use `curate_and_write_adj_factors_as_of` when a point-in-time or vault-fenced snapshot is required. -- **In-RAM `bars_1d` close index:** loading `bars_1d` into `PrevCloseIndex` takes `16 bytes/bar` (plus `Vec` growth slack, ~1.6–2.5 GiB for 100M bars). -- **Single-threaded file-to-file execution:** no `rayon` sharding or direct MongoDB/PostgreSQL connections yet. - -## `curate-corporate-actions` Command (`M1.2ab`) - -End-to-end file-to-Parquet CLI command (`src/run_curate_corporate_actions.rs`) wiring `RawBsonChunkReader`, `decode_qm_split_chunks`, `decode_qm_dividend_chunks`, `load_provider_mapping_tsv`, a strict Pass 6 `delistings.tsv` loader (`load_delistings_tsv`), and `curate_and_write_corporate_actions` into an atomically published `/corporate_actions/part.parquet` dataset with zero extra crates and no database connections. - -### Invocation - -```bash -curate-etl curate-corporate-actions \ - --qm-splits qmSplits.bson \ - --qm-dividends qmDividends.bson \ - --curate-inputs ./tmp/curate-inputs \ - --out ./out -``` - -Inputs and output: -- `--qm-splits `: concatenated raw BSON (`mongodump` `qmSplits.bson`). -- `--qm-dividends `: concatenated raw BSON (`mongodump` `qmDividends.bson`). -- `--curate-inputs `: exporter output directory containing a committed `current` link. Requires `/current` and resolves it once via `canonicalize` before opening `provider_mapping.tsv` and `delistings.tsv` so both files always come from the same atomic PostgreSQL snapshot even if an export refreshes `current` concurrently. Fails closed if `current` is absent (use `--provider-mapping` / `--delistings` for standalone files or direct generation paths). Mutually exclusive with `--provider-mapping` and `--delistings`. -- `--provider-mapping ` / `--delistings ` *(alternative to `--curate-inputs`)*: standalone headerless 5-column TSVs (`--delistings` is optional when using explicit TSV paths; when omitted, zero delisting rows are loaded). -- `--out `: dataset root where `corporate_actions/part.parquet` is atomically published. - -Both `--flag value` and `--flag=value` forms are accepted (in the separated `--flag value` form, a following `--...` token is rejected as a missing value; use `--flag=value` for literal paths starting with `--`). Invalid, missing, duplicate (including duplicate `--delistings`), or unknown flags exit non-zero with usage on stderr. Any runtime error (missing input file, malformed `provider_mapping.tsv` or `delistings.tsv` reporting path + 1-based line number, overlapping mapping ranges, truncated/corrupt/oversized BSON stream carrying byte offset, or unwritable `--out`) prints a single-line stderr message, exits non-zero, and returns before touching `--out` (leaving any pre-existing `/corporate_actions/part.parquet` byte-identical). - -### TSV Formats (strict, headerless, `\t`-separated) - -- `provider_mapping` (5 columns; identical to `curate-bars-1d`): - `source \t source_id \t valid_from(YYYY-MM-DD) \t valid_to(YYYY-MM-DD or empty) \t listing_id` -- `delistings` (optional file; 5 columns when supplied): - `source_id \t delist_date(YYYY-MM-DD) \t from_listing_id(int or empty) \t successor_source_id(or empty) \t terminal_return(float or empty)` - - `source_id` is preserved verbatim (never trimmed) and must not be empty or whitespace-only. - - `delist_date` is parsed strictly with `YYYY-MM-DD` Gregorian validation. - - `from_listing_id` is empty (`None`) or a strict positive ASCII base-10 `i32`. - - `successor_source_id` is empty (`None`) or a non-blank string preserved verbatim. - - `terminal_return` is empty (`None`) or a finite `f64` in `[-1.0, 0.0]` with no leading/trailing whitespace (`-0.0` is normalized to `0.0`). - - Exactly one of `successor_source_id` or `terminal_return` must be set on every row. - - Any row with `successor_source_id` set (OTC transfer) requires `from_listing_id` to be set. -- Both TSVs accept `\n` or `\r\n` line endings and at most one trailing blank line. Header rows, wrong column counts, interior blank lines, multiple trailing blank lines, interior `\r`, and invalid UTF-8 are rejected with the 1-based line number. - -### `declared_date` / `known_at`, `usdFxRate` & Empty-Input Rules - -- **`declared_date` & `known_at`:** `RawQmSplit::to_split_action_event` and `RawQmDividend::to_dividend_action_event` carry `declared_date` from the raw BSON `declared` field when present. Downstream `build_corporate_actions` clamps late declarations (`declared_date > ex_date`) to `ex_date` with `KnownAtSource::ExDateFallback`, and `curate_corporate_actions` stamps `known_at = 16:00:00 ET` of `known_at_date` (`1976-01-01..=2030-12-31`). -- **`usdFxRate` & no-ops:** `usdFxRate` stays ignored per `design/DATA-CONTRACTS.md` §1; `splitratio == 1.0` no-op drops, `cash == 0.0` dividend drops, and cross-key collision rules stay delegated unchanged to `curate_and_write_corporate_actions`. Per-document BSON decode rejects are counted without aborting the run. -- **Empty-input behavior:** delegated unchanged to `curate_and_write_corporate_actions` / `write_corporate_actions_dataset`, which returns `Ok` with `rows_written == 0` and `files_written == 0` without creating `/corporate_actions` or modifying any pre-existing `part.parquet` (matching `curate-bars-1d`). - -### Report Counters & Conservation Invariants - -On success, `curate-corporate-actions` prints deterministic `key=value` lines to stdout (`splits_bson`, `dividends_bson`, `delistings_tsv`, `builder`, `curate`, `write`, and `timing`): - -- **Splits:** - `splits_bson.docs_framed == splits_bson.docs_in == splits_bson.decoded + splits_bson.rejected` - `splits_bson.decoded == builder.splits_in == builder.splits_out + builder.split_noops` -- **Dividends:** - `dividends_bson.docs_framed == dividends_bson.docs_in == dividends_bson.decoded + dividends_bson.rejected` - `dividends_bson.decoded == builder.dividends_in == builder.dividends_out + builder.zero_div` -- **Delistings:** - `delistings_tsv.rows_loaded == builder.delistings_in == builder.otc_out + builder.delistings_out` (`builder.delist_no_outcome == 0` under strict TSV validation) -- **Stage & Write:** - `curate.rows_in == builder.rows_out == curate.rows_out + curate.unmapped + curate.unmapped_succ + curate.self_succ + curate.known_at_oor + curate.coll_collapsed + curate.coll_dropped` - `write.rows_written == curate.rows_out` - -### `bench-curate-corporate-actions-cmd` - -Fixed-seed (`std`-only SplitMix64) end-to-end file→Parquet benchmark synthesizing `provider_mapping.tsv` (20,000 keys with single-range, ended primary-venue listings for OTC transfer testing, ticker-reuse gaps, aliases, unmapped keys, and 500 OTC successors), `qmSplits.bson` (~3.6% incl. forward/reverse splits, `declared` variants, `1:1` no-ops, unmapped, identical + conflicting alias collisions, and ~0.5% malformed rejects), `qmDividends.bson` (~95.4% incl. USD/CAD with bogus `usdFxRate: 1`, `declared` variants, `0.0` cash, same-day multi-dividends, identical alias duplicates, unmapped, and ~0.5% malformed rejects), and `delistings.tsv` (~1.0% incl. valid OTC transfers with `from_listing_id`, unmapped/self successors, and `-0.3`/`-1.0` terminal delistings) into a temp dir, timing `decode` / `curate` / `write` separately, verifying Parquet footer row count, and cleaning up on drop: - -```bash -cargo run -p curate-etl --release --offline -- bench-curate-corporate-actions-cmd [events] -``` - -Measured locally (`2026-11-29`): - -1. **200,000 events** (`cargo run -p curate-etl --release --offline -- bench-curate-corporate-actions-cmd 200000`): - - Input: `events=200000`, `splits_docs=7986` (`1,014,335 B`), `dividends_docs=190038` (`26,806,832 B`), `delistings_rows=1976` (`72,436 B`), `keys=20000` - - `decode`: `elapsed=50.15 ms`, `throughput=3987987 events/s`, `scan=530.43 MB/s`, `splits_rejected=38`, `divs_rejected=921` - - `curate`: `elapsed=65.24 ms`, `throughput=3051003 events/s`, `rows_out=188558` (`94.28%` retained), `listings_out=19850`, `unmapped=5809`, `unmapped_succ=193`, `self_succ=189`, `known_at_oor=967`, `coll_collapsed=542`, `coll_dropped=720`, `split_noops=154`, `zero_div=1909`, `checksum=0x29f0c9ec1451e7c5` - - `write`: `elapsed=40.53 ms`, `throughput=4652522 rows/s`, `write=39.23 MB/s`, `files=1`, `row_groups=1`, `bytes=1667357`, `read_back_rows=188558` - - `total`: `elapsed=155.92 ms`, `throughput=1282737 events/s`, `checksum=0x29f0c9ec1451e7c5` -2. **1,000,000 events** (two back-to-back runs with identical checksum `0xa0fb2bf8e2710d67`): `cargo run -p curate-etl --release --offline -- bench-curate-corporate-actions-cmd 1000000` - - Input: `events=1000000`, `splits_docs=39186` (`4,979,926 B`), `dividends_docs=950896` (`134,135,512 B`), `delistings_rows=9918` (`364,087 B`), `keys=20000` - - Output: `rows_out=944029` (`94.40%` retained), `listings_out=20000`, `files=1`, `row_groups=1`, `bytes=6890801`, `read_back_rows=944029` - - Curation stats: `unmapped=28446`, `unmapped_succ=986`, `self_succ=977`, `known_at_oor=4736`, `coll_collapsed=2555`, `coll_dropped=3392`, `split_noops=738`, `zero_div=9233` - - Run 1: `decode=222.11 ms` (`4,502,250 events/s`, `598.88 MB/s`), `curate=406.07 ms` (`2,450,553 events/s`), `write=147.49 ms` (`6,400,505 rows/s`, `44.56 MB/s`), `total=775.67 ms` (`1,289,204 events/s`), `checksum=0xa0fb2bf8e2710d67` - - Run 2: `decode=211.87 ms` (`4,719,887 events/s`, `627.83 MB/s`), `curate=396.55 ms` (`2,509,369 events/s`), `write=144.29 ms` (`6,542,758 rows/s`, `45.55 MB/s`), `total=752.71 ms` (`1,328,540 events/s`), `checksum=0xa0fb2bf8e2710d67` - -### Known Limits - -- **Unverified MongoDB `qmDividends` field names:** `bson_qm_actions::FIELD_DIVIDEND_CASH` (`"amount"`) and `FIELD_DIVIDEND_CURRENCY` (`"currency"`) remain isolated constants pending verification against live `mongodump` `qmDividends` exports. -- **In-RAM buffering of decoded events:** the single-threaded runner buffers decoded splits, dividends, and delistings in RAM (with `Arc` key interning) before curation — small for real `qmSplits` (~19k) + `qmDividends` (~500k) + Pass 6 delistings, unlike `eodPrices`. -- **Single-threaded file-to-file execution:** no `rayon` sharding and no direct MongoDB/PostgreSQL connections. The TypeScript read-only PostgreSQL → TSV exporter (`apps/stock/data-pipeline/src/security-master/run-export-curate-inputs.ts`) generates `provider_mapping.tsv`, `listing_currencies.tsv`, and Pass 6 `delistings.tsv` for all `curate-etl` commands. - -## `curate-fx-1d` Command (`M1.2ac`) - -End-to-end file-to-Parquet CLI command (`src/run_curate_fx.rs`) wiring `RawBsonChunkReader`, `decode_eod_price_chunks`, the zero-copy `teMarketData` decoder (`src/bson_te_market_data.rs`, `decode_te_market_data_chunks`), and `curate_and_write_fx_1d` into an atomically published `/fx_1d/part.parquet` dataset with zero extra crates and no database connections. - -### Invocation - -```bash -curate-etl curate-fx-1d \ - --eod-prices eodPrices.bson \ - --te-market-data teMarketData.bson \ - [--te-symbol USDCAD] \ - --out ./out -``` - -Inputs and output: -- `--eod-prices `: concatenated raw BSON (`mongodump` `eodPrices.bson`). Streams through `decode_eod_price_chunks` and keeps only documents whose `eodSearchCode` is **exact** `"CAD.FOREX"` (other symbols are counted in `eod_other_symbol_skipped`; `eodPrices.volume` is ignored when mapping to `FxDailyBar`). -- `--te-market-data `: concatenated raw BSON (`mongodump` `teMarketData.bson`). Streams through `decode_te_market_data_chunks` and keeps only documents whose `teSymbol` matches `--te-symbol` (ASCII case-insensitive, default `USDCAD`). -- `--te-symbol ` *(optional)*: target `teMarketData.teSymbol` to match (default: `USDCAD`; must match the USD/CAD allowlist `ALLOWED_TE_SYMBOLS` = `["USDCAD"]` ASCII case-insensitively so non-USD/CAD instruments cannot enter `fx_1d`). -- `--out `: dataset root where `fx_1d/part.parquet` is atomically published. - -Both `--flag value` and `--flag=value` forms are accepted (in the separated `--flag value` form, a following `--...` token is rejected as a missing value; use `--flag=value` for literal paths starting with `--`). Invalid, missing, duplicate (including duplicate `--te-symbol`), or unknown flags exit non-zero with usage on stderr. Any runtime error (missing input file, invalid `--out`, unsupported/blank `--te-symbol`, truncated/corrupt/oversized BSON framing or element bytes in either input, zero decoded bars across both inputs, or zero publishable rows after FX curation) prints a single-line stderr message, exits non-zero, and leaves any pre-existing `/fx_1d/part.parquet` byte-identical. - -### `teMarketData` Input Contract & `t` Epoch Unit Rule - -- Document shape (derived from `apps/stock/data-ingestion/src/handlers/te/actions/market-data-fetch.action.ts`; field names isolated as `pub const FIELD_*` in `src/bson_te_market_data.rs`): - - Top-level `teSymbol: string` and `daily: [{ t, o, h, l, c, pc, ac }]`. - - `monthly`, `pc`, `ac`, and all unknown fields are skipped without decoding their values. - - `daily` is captured lazily as a raw element and only decoded after `teSymbol` matches `--te-symbol`, so field ordering (`daily` before `teSymbol`) never causes false rejects on non-target symbols. -- Numeric fields `t`, `o`, `h`, `l`, `c` accept BSON `Int32`, `Int64`, or `Double`. Malformed points (non-document element, missing field, wrong type, `NaN`/`±Inf`, out-of-`i32`-range date) are counted under per-reason reject counters and skipped without panicking. -- **`t` epoch unit rule** (`TE_EPOCH_MILLIS_THRESHOLD = 100_000_000_000`): - - `|t| >= 100_000_000_000` → treated as Unix **milliseconds** (`session_date = floor(t / 86_400_000)` UTC). - - `|t| < 100_000_000_000` → treated as Unix **seconds** (`session_date = floor(t / 86_400)` UTC). - - Uses `unsigned_abs()` + `div_euclid` (flooring pre-1970 negative timestamps to the earlier UTC day) and checked `i32::try_from` bounds checking. -- Merge precedence (`CAD.FOREX` wins on overlap, `teMarketData` fills interior gaps and post-EOD tail), read-only 1% overlap cross-check, and conservative `23:59:59.999999 UTC` `ts`/`known_at` stamping stay delegated unchanged to `curate_and_write_fx_1d`. - -### Report Counters & Conservation Invariants - -On success, `curate-fx-1d` prints deterministic `key=value` lines to stdout (`eod_bson`, `te_bson`, `builder`, `curate`, `write`, and `timing`): - -- **EOD BSON:** - `eod_bson.docs_framed == eod_bson.docs_in == eod_bson.decoded + eod_bson.rejected` - `eod_bson.decoded == eod_bson.cad_forex_kept + eod_bson.other_symbol_skipped` - `eod_bson.cad_forex_kept == builder.eod_in` -- **TE BSON:** - `te_bson.docs_framed == te_bson.docs_in == te_bson.matched + te_bson.other_symbol + te_bson.docs_rejected` - `te_bson.points_in == te_bson.points_decoded + te_bson.points_rejected` - `te_bson.points_decoded == builder.te_in` -- **Stage & Write:** - `curate.rows_in == curate.rows_out == write.rows_written` - -### `bench-curate-fx-cmd` - -Fixed-seed (`std`-only SplitMix64) end-to-end file→Parquet benchmark synthesizing `eodPrices.bson` (`CAD.FOREX` with interior gaps, invalid/inconsistent/duplicate bars, skipped other symbols, and malformed docs) and `teMarketData.bson` (`USDCAD` with overlap including >1% cross-check mismatches, interior gap fills, post-EOD tail, mixed seconds/ms `t` across `Int32`/`Int64`/`Double`, malformed points, ignored `monthly`, and skipped other symbols) into a temp dir, timing `decode` / `curate` / `write` separately, verifying Parquet footer row count, and cleaning up on drop: - -```bash -cargo run -p curate-etl --release --offline -- bench-curate-fx-cmd [rows] -``` - -Measured locally (`2026-11-29`, post-fix `curate-fx-1d` with full-document corruption scanning, default `20,000` rows; two back-to-back runs with identical checksum `0x45ac34f4ddf4407c`): - -- Input: `rows=20000`, `eod_docs=18936` (`2,706,485 B`), `te_docs=3`, `te_points=5000` (`443,498 B`) -- Decode counts: `eod_kept=14918`, `eod_other=3936`, `eod_rejected=82`, `te_matched=1`, `te_other=2`, `te_decoded=4925`, `te_rejected=75` -- Output: `rows_out=17524` (`eod_out=14569`, `te_out=2955`, `te_superseded=1970`), `files=1`, `row_groups=1`, `bytes=733752`, `read_back_rows=17524`, `overlap: checked=1970 within_tol=1870 mismatched=100 max_rel=0.025000` -- Run 1: `decode=4.33 ms` (`4,614,470 rows/s`, `693.11 MB/s`), `curate=0.64 ms` (`30,806,515 rows/s`), `write=24.99 ms` (`701,274 rows/s`, `28.00 MB/s`), `total=29.97 ms` (`667,398 rows/s`), `checksum=0x45ac34f4ddf4407c` -- Run 2: `decode=4.26 ms` (`4,694,381 rows/s`, `705.11 MB/s`), `curate=0.67 ms` (`29,800,156 rows/s`), `write=15.27 ms` (`1,147,886 rows/s`, `45.84 MB/s`), `total=20.19 ms` (`990,462 rows/s`), `checksum=0x45ac34f4ddf4407c` - -### Known Limits - -- **Unverified live `teMarketData` schema & `t` unit:** `bson_te_market_data::FIELD_*` constants and the `|t| >= 100_000_000_000` ms/s threshold are derived from `market-data-fetch.action.ts` and have not yet been verified against a live `mongodump` export. -- **`eodPrices` `volume` field:** `decode_eod_price_chunks` still requires a non-negative `volume` field on `CAD.FOREX` documents (ignored when mapping to `FxDailyBar`); if a live `CAD.FOREX` dump omits `volume`, those docs will surface in `eod_bson.rejected (missing=...)`. -- **Single-threaded file-to-file execution:** no `rayon` sharding, no direct MongoDB connection, and `fx_1m` is out of scope. - -## `curate-shorts` Command (`M1.2ad`) - -End-to-end file-to-Parquet CLI command (`src/run_curate_shorts.rs`) wiring `RawBsonChunkReader`, the zero-copy `ceoShorts` decoder (`src/bson_ceo_shorts.rs`, `decode_ceo_shorts_chunks`), `load_provider_mapping_tsv`, and `curate_and_write_shorts` into an atomically published `/shorts/part.parquet` dataset (`+4` Canadian TSX business days at `17:00 America/Toronto`, `source = "ceo_shorts"`) with zero extra crates and no database connections. - -### Invocation - -```bash -curate-etl curate-shorts \ - --ceo-shorts ceoShorts.bson \ - --provider-mapping provider_mapping.tsv \ - --out ./out \ - --shares-short-field \ - [--key-field symbol] \ - [--report-date-field timestamp] \ - [--net-change-field ] \ - [--pct-float-field ] \ - [--mapping-source ceo] -``` - -Inputs and output: -- `--ceo-shorts ` *(required)*: concatenated raw BSON (`mongodump` `ceoShorts.bson`). -- `--provider-mapping ` *(required)*: headerless 5-column TSV (same format as `curate-bars-1d`). -- `--out ` *(required)*: dataset root where `shorts/part.parquet` is atomically published. -- `--shares-short-field ` *(required, no default)*: BSON field name holding the short-share count (intentionally has no default because live `ceoShorts` value field names are unverified in the repo). -- `--key-field ` *(optional, default `symbol`)*: BSON field name holding the security key (passed verbatim to `provider_mapping` without trimming or suffix stripping). -- `--report-date-field ` *(optional, default `timestamp`)*: BSON field name holding the report period date. -- `--net-change-field ` *(optional)*: BSON field name holding optional net change vs. prior report. -- `--pct-float-field ` *(optional)*: BSON field name holding optional percent-of-float short. -- `--mapping-source ` *(optional, default `ceo`)*: `provider_mapping` source name used to resolve `(mapping_source, key, report_date) -> listing_id`. - -Both `--flag value` and `--flag=value` forms are accepted (in the separated `--flag value` form, a following `--...` token is rejected as a missing value; use `--flag=value` for literal paths starting with `--`). Missing required flags (including `--shares-short-field`), duplicate flags, unknown flags, empty/blank field names or `--mapping-source`, positional arguments, and any two configured roles resolving to the same BSON field name (checked after applying defaults) exit non-zero with usage on stderr. Any runtime error (missing input file, malformed or overlapping `provider_mapping.tsv`, truncated/corrupt/oversized BSON framing or element bytes, out-of-range `report_date`, or obstructed `--out`) prints a single-line stderr message, exits non-zero, and returns before touching `--out` (leaving any pre-existing `/shorts/part.parquet` byte-identical). - -### `ceoShorts` Decoder Rules - -- Scans and validates every element and nested raw value (including unused strings, embedded documents, and arrays) of each `RawDocument` to completion before applying semantic skip priority (`key` → `report_date` → `shares_short`) so structural BSON corruption always fails closed with a typed error carrying the absolute byte offset. -- `key`: BSON UTF-8 `String` passed through verbatim (empty/whitespace-only, missing, or wrong type skipped and counted). -- `report_date`: BSON `DateTime` (UTC calendar day via `timestamp_millis().div_euclid(86_400_000)` checked to `i32`), or `Int32` / `Int64` / integral finite `Double` via `te_epoch_i64_to_session_date` (seconds vs. milliseconds UTC). Non-finite or fractional `Double`s skip under `invalid_date`; values overflowing `i64`/`i32` skip under `date_oor`. -- `shares_short`: strict BSON `Double`, `Int32`, or `Int64` (numeric strings are rejected as `wrong_shares_type`). Sign and finiteness validation remains in `build_shorts`. -- `net_change` / `pct_float`: unconfigured, absent, or BSON `Null` → `None`; wrong BSON type → `None` and counted in `nulled_wrong_type` (only on emitted rows). -- Empty or all-unmapped inputs return `Ok` with `rows_written=0` and `files=0`, leaving any pre-existing `shorts/part.parquet` untouched. - -### Report Counters & Conservation Invariants - -On success, `curate-shorts` prints deterministic `key=value` lines to stdout (`ceo_bson`, `builder`, `curate`, `write`, and `timing`): - -- **BSON Decode:** `ceo_bson.docs_framed == ceo_bson.docs_in == ceo_bson.rows_out + ceo_bson.skipped` -- **Builder:** `ceo_bson.rows_out == builder.rows_in == builder.rows_out + builder.invalid_shares + builder.dup_collapsed + builder.dup_conflict` -- **Stage & Write:** `curate.rows_in == builder.rows_out == curate.rows_out + curate.dropped_unmapped + curate.coll_collapsed + curate.coll_dropped`, and `write.rows_written == curate.rows_out` - -### `bench-curate-shorts-command` - -Fixed-seed (`std`-only SplitMix64) end-to-end file→Parquet benchmark synthesizing a concatenated-BSON `ceoShorts` file (default `700,000` docs, `12,500` keys distributed across all 218 semi-monthly dates `2017-04-15..=2026-04-30`, mixing `DateTime`/`Int32`/`Int64`/`Double` dates, optional fields with nulls and wrong types, ~0.5% semantically skipped docs, invalid `shares_short`, explicit identical/conflicting same-key duplicates, explicit identical/conflicting primary+alias collisions, ticker-reuse gap dates, and unmapped keys) plus `provider_mapping.tsv` into a temp dir, timing `decode` / `curate` / `write` separately, verifying Parquet footer row count, and cleaning up on drop: - -```bash -cargo run -p curate-etl --release --offline -- bench-curate-shorts-command [rows] -``` - -Measured locally (`2026-11-29`, Linux `6.8.0-151-generic`, AMD Ryzen 9 9950X3D 16-Core Processor, default `700,000` rows; two back-to-back runs with identical checksum `0xa759372dd4476f50`): - -- Input: `rows=700000`, `docs_framed=700000`, `bytes_read=67925127` (`64.78 MiB`), `keys=12500`, `peak_chunk_bytes=8388608` (`8 MiB`) -- Decode counts: `rows_out=696570`, `skipped=3430`, `nulled_net_change=6860`, `nulled_pct_float=5717` -- Output: `rows_out=656911` (`93.84%` retained), `listings_out=12345`, `dropped_unmapped=15229`, `dup_collapsed=3500`, `dup_conflict=7000`, `coll_collapsed=3500`, `coll_dropped=7000`, `invalid_shares=3430`, `files=1`, `row_groups=1`, `bytes=5791000`, `read_back_rows=656911` -- Run 1: `decode=141.29 ms` (`4,954,433 rows/s`, `458.49 MB/s`), `curate=130.95 ms` (`5,319,222 rows/s`), `write=93.49 ms` (`7,026,896 rows/s`, `59.08 MB/s`), `total=365.73 ms` (`1,914,000 rows/s`), `peak_chunk_bytes=8388608`, `checksum=0xa759372dd4476f50` -- Run 2: `decode=152.15 ms` (`4,600,763 rows/s`, `425.76 MB/s`), `curate=130.95 ms` (`5,319,464 rows/s`), `write=86.38 ms` (`7,604,711 rows/s`, `63.93 MB/s`), `total=369.48 ms` (`1,894,564 rows/s`), `peak_chunk_bytes=8388608`, `checksum=0xa759372dd4476f50` - -### Known Limitations - -- **Unverified live `ceoShorts` field names and `timestamp` unit/timezone:** `ceoShorts` value field names (`--shares-short-field`, `--net-change-field`, `--pct-float-field`, `--key-field`) and `timestamp` unit/timezone are unverified against live QA MongoDB data. Confirm them before the first real run with the read-only field-shape probe: - ```bash - bun run apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts --collections ceoShorts --out - ``` -- **Single-threaded file-to-file execution:** no `rayon` sharding, no direct MongoDB/PostgreSQL connection, and `pct_float` is passed through as supplied rather than derived from shares outstanding. - -## `curate-events` Command (`M1.2ae`) - -End-to-end file-to-Parquet CLI command (`src/run_curate_events.rs`) wiring `RawBsonChunkReader`, the zero-copy `qmFilings` + `qmEarnings` decoders (`src/bson_qm_events.rs`, `decode_qm_filings_chunks`, `decode_qm_earnings_chunks`), `load_provider_mapping_tsv`, and `curate_and_write_events` into atomically published `/events/year=YYYY/part.parquet` partitions with zero extra crates and no database connections. - -### Invocation - -```bash -curate-etl curate-events \ - --qm-filings qmFilings.bson \ - --qm-earnings qmEarnings.bson \ - --provider-mapping provider_mapping.tsv \ - --out ./out \ - --filings-form-type-field \ - [--filings-key-field symbol] \ - [--filings-timefiled-field timefiled] \ - [--filings-filing-id-field ] \ - [--filings-url-field ] \ - [--earnings-key-field qmSearchCode] \ - [--earnings-report-date-field reportDate] \ - [--earnings-announce-time-field announceTime] \ - [--earnings-fiscal-period-end-field ] \ - [--earnings-actual-eps-field ] \ - [--earnings-revenue-field ] \ - [--mapping-source qm] -``` - -Inputs and verified vs. configured field names: -- `--qm-filings ` *(required)*: concatenated raw BSON (`mongodump` `qmFilings.bson`). -- `--qm-earnings ` *(required)*: concatenated raw BSON (`mongodump` `qmEarnings.bson`). -- `--provider-mapping ` *(required)*: headerless 5-column TSV (same format as `curate-bars-1d`). -- `--out ` *(required)*: dataset root where `events/year=YYYY/part.parquet` is atomically published. Upfront path validation rejects `--out` or `/events` being a regular file, or any input path resolving to `--out` or inside `/events/...` (preventing input clobbering). -- **Verified defaults** (grounded in `apps/stock/data-ingestion/src/handlers/qm/actions/filings.action.ts`, `events.action.ts`, and `design/DATA-CONTRACTS.md` §1): - - `qmFilings`: `--filings-key-field` (`symbol`; note `filings.action.ts` does **not** add `qmSearchCode` to stored docs despite the upsert key), `--filings-timefiled-field` (`timefiled`). - - `qmEarnings`: `--earnings-key-field` (`qmSearchCode`), `--earnings-report-date-field` (`reportDate`), `--earnings-announce-time-field` (`announceTime`). -- **Caller-configured fields (no defaults):** - - `--filings-form-type-field ` *(required, no default)*: BSON field holding the EDGAR/SEDAR+ form type string. - - Optional: `--filings-filing-id-field`, `--filings-url-field`, `--earnings-fiscal-period-end-field`, `--earnings-actual-eps-field`, `--earnings-revenue-field`. -- `--mapping-source ` *(optional, default `qm`)*: `provider_mapping` source name used to resolve `(mapping_source, key, event_date) -> listing_id` on each event's exact Eastern local calendar date. -- **`consensusEps` exclusion:** `consensusEps` is structurally omitted from `RawQmEarning` / `QmEarning` and explicitly rejected (case-insensitively as `consensusEps` / `consensus_eps`) on any earnings field flag per `design/DATA-CONTRACTS.md` §1. - -Both `--flag value` and `--flag=value` forms are accepted. Missing required flags (including `--filings-form-type-field`), duplicate flags, unknown flags, blank field names or `--mapping-source`, colliding role mappings within a collection, or any `consensusEps` mapping exit non-zero with usage on stderr. Any runtime error (missing input file, malformed/overlapping `provider_mapping.tsv`, truncated/corrupt BSON in either stream, or obstructed/overlapping `--out`) prints a single-line stderr message, exits non-zero, and returns before touching `--out` (leaving any pre-existing `/events/` partitions byte-identical). - -### `qmFilings` & `qmEarnings` Decoder Rules - -- Scans and structurally validates every element and nested document/array/JS-with-scope (depth limit `128`) of each `RawDocument` before applying semantic skip rules so structural corruption always fails closed with a typed error carrying the absolute byte offset. -- `qmFilings` deterministic skip priority: `key` → `timefiled` → `form_type` (all required non-blank UTF-8 `String`s passed verbatim; timestamp syntax remains in `events::build_events`). Optional `filing_id` / `url`: unconfigured, absent, `Null`, or blank string → `None`; wrong BSON type → `None` + `nulled_wrong_type_*` (emitted rows only). -- `qmEarnings` deterministic skip priority: `key` → `report_date` → `announce_time`. `report_date` accepts BSON `DateTime` (UTC epoch day checked to `i32`) or strict `YYYY-MM-DD` `String`. Optional `fiscal_period_end` accepts absent/`Null`/blank (`None`), `DateTime` or strict `YYYY-MM-DD` (`Some(i32)`), wrong BSON type (`nulled_wrong_type_fiscal_period_end`), or malformed/out-of-range (`nulled_invalid_fiscal_period_end`, emitted rows only). Optional `actual_eps` / `revenue` accept absent/`Null` (`None`), `Double`/`Int32`/`Int64` (`Some(f64)`), or wrong BSON type (`nulled_wrong_type_*`, emitted rows only). -- Empty or all-unmapped inputs return `Ok` with `rows_written=0` and `files=0` without creating `/events` or modifying any pre-existing partitions. - -### Report Counters & Conservation Invariants - -On success, `curate-events` prints deterministic `key=value` lines to stdout (`filings_bson`, `earnings_bson`, `builder`, `curate`, `write`, ascending `years`, and `timing`): - -- **Filings BSON:** `filings_bson.docs_framed == filings_bson.docs_in == filings_bson.rows_out + filings_bson.skipped`, and `filings_bson.rows_out == builder.filings_in`. -- **Earnings BSON:** `earnings_bson.docs_framed == earnings_bson.docs_in == earnings_bson.rows_out + earnings_bson.skipped`, and `earnings_bson.rows_out == builder.earnings_in`. -- **Builder:** `builder.filings_in == builder.filings_out + malformed_ts + unknown_zone + invalid_dt + filing_dup`, `builder.earnings_in == builder.earnings_out + earnings_oor + earnings_dup + earnings_conflict`, `builder.earnings_out == linked + lagged_1605`, and `builder.rows_out == builder.filings_out + builder.earnings_out`. -- **Stage & Write:** `curate.rows_in == builder.rows_out == curate.rows_out + curate.dropped_unmapped + curate.listing_dup_collapsed`, and `write.rows_written == curate.rows_out`. - -### `bench-curate-events-cmd` - -Fixed-seed (`std`-only SplitMix64) end-to-end file→Parquet benchmark synthesizing `provider_mapping.tsv` (`5,000` keys with ~2% unmapped), `qmFilings.bson` (~98.5% of `rows`, mixed EST/EDT `2015..=2025`, EDGAR + SEDAR+ form types, ~0.5% skips/wrong-type optionals), and `qmEarnings.bson` (~1.5% of `rows`, mixed `DateTime`/`YYYY-MM-DD`, linked & unlinked rows, `consensusEps` present and ignored, ~0.5% skips/wrong-type optionals) into a temp dir, timing `decode` / `curate` / `write` separately, verifying Parquet footer row counts across all UTC year partitions, extrapolating to the full `30.52M + 444.9k` (`30,964,900` rows) QA MongoDB dataset, and cleaning up on drop: - -```bash -cargo run -p curate-etl --release --offline -- bench-curate-events-cmd [rows] -``` - -Measured locally (`2026-11-29`, default `500,000` rows; two back-to-back runs with identical checksum `0x2076c3a54dc2403e`): - -- Input: `rows=500000`, `filings_docs=492500` (`71,019,899 B`), `earnings_docs=7500` (`1,233,791 B`), `keys=5000`, `peak_chunk_bytes=8388608` (`8 MiB`) -- Decode counts: `filings_out=490021`, `filings_skipped=2479`, `earnings_out=7462`, `earnings_skipped=38` -- Output: `rows_out=487589` (`97.52%` retained; `filings_out=480258`, `earnings_out=7331`), `listings_out=4900`, `linked=3008`, `lagged_1605=4452`, `unmapped=9892`, `files=12`, `row_groups=12`, `bytes=14125012`, `read_back_rows=487589` -- Run 1: `decode=136.07 ms` (`3,674,605 rows/s`, `506.41 MB/s`), `curate=278.55 ms` (`1,786,003 rows/s`), `write=446.48 ms` (`1,092,064 rows/s`, `30.17 MB/s`), `total=861.10 ms` (`580,654 rows/s`), **extrapolation to `30.52M` filings + `444.9k` earnings (`30.96M` rows): `53.3 s` (`0.89 min`) single-core**, `checksum=0x2076c3a54dc2403e` -- Run 2: `decode=136.68 ms` (`3,658,115 rows/s`, `504.14 MB/s`), `curate=264.16 ms` (`1,883,251 rows/s`), `write=437.86 ms` (`1,113,564 rows/s`, `30.76 MB/s`), `total=838.71 ms` (`596,155 rows/s`), **extrapolation to `30.52M` filings + `444.9k` earnings (`30.96M` rows): `51.9 s` (`0.87 min`) single-core**, `checksum=0x2076c3a54dc2403e` - -### Known Limitations - -- **Unverified live `qmFilings` / `qmEarnings` field names:** `--filings-form-type-field`, optional filings fields (`filing_id`, `url`), optional earnings fields (`fiscal_period_end`, `actual_eps`, `revenue`), and whether live `qmFilings` documents carry `qmSearchCode` vs. `symbol` are unverified against live QA MongoDB. Confirm them before the first real run with the read-only field-shape probe: - ```bash - bun run apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts --collections qmFilings,qmEarnings --out - ``` -- **Key-namespace alignment between `qmFilings` and `qmEarnings`:** `qmFilings` defaults to `symbol` while `qmEarnings` defaults to `qmSearchCode`. Both exports must carry an unambiguous key in the `provider_mapping` namespace (for example, the QuoteMedia security ID, not a bare ticker — the security master records distinct QuoteMedia IDs such as `VOY:CNX` and `VOY:CC` for the same symbol and exchange, so switching earnings to bare `symbol` can merge distinct identities or drop rows). If a live `qmFilings` export lacks that unambiguous key, prepare the export with verified QuoteMedia IDs and exclude unresolved rows rather than downgrading `qmEarnings` to bare tickers. -- **In-RAM buffering & single-threaded execution:** decoded filings and earnings are buffered in RAM (with shared `Arc` key interning) before sorting/curation; `rayon` key-sharded streaming, direct MongoDB/PostgreSQL connections, and M2 `fundamentals_pit` joins remain out of scope. - -## `curate-posts` Command (`M2.2j`) - -End-to-end file-to-Parquet CLI command (`src/run_curate_posts.rs`, wired in `src/cli.rs` and `src/main.rs`) streaming a concatenated raw BSON `ceoPosts` dump alongside `provider_mapping.tsv` into atomically published `/events/year=YYYY/part.parquet` partitions with zero extra crates and no database connections (`--from-mongo` is not supported yet and is rejected as an unknown flag). - -### Invocation - -```bash -curate-etl curate-posts \ - --ceo-posts ceoPosts.bson \ - --provider-mapping provider_mapping.tsv \ - --out ./out-posts \ - --timestamp-unit seconds -``` - -Inputs, defaults, and output rules: -- `--ceo-posts ` *(required)*: concatenated raw BSON (`mongodump` `ceoPosts.bson`). -- `--provider-mapping ` *(required)*: headerless 5-column TSV (same format as `curate-bars-1d`). -- `--out ` *(required, dedicated output directory)*: dataset root where `/events/year=YYYY/part.parquet` is atomically published. Because `curate-events` (filings + earnings) writes to the same `/events` directory layout, `curate-posts` requires a dedicated `--out` directory and fails closed before any write if `/events` already contains any `year=*` entry (leaving existing partitions byte-identical). -- `--timestamp-unit ` *(required, **no default**)*: explicit numeric epoch unit (`seconds` or `millis`) for numeric `timestamp` and `edited` fields. There is intentionally no default because the live MongoDB `ceoPosts` numeric timestamp unit is unverified in the repository; BSON `DateTime` values are always epoch milliseconds regardless of unit. -- Optional field-name overrides (defaults from `src/bson_ceo_posts.rs` / `get-posts.action.ts`): - - `--key-field` (default `ceoId`) - - `--spiel-id-field` (default `spielId`) - - `--timestamp-field` (default `timestamp`) - - `--edited-field` (default `edited`) - - `--bot-field` (default `bot`) - - `--user-id-field` (default `userId`) - - `--text-field` (default `spiel`) -- `--mapping-source ` *(optional, default `ceo`)*: `provider_mapping` source name used to resolve `(mapping_source, key, et_date) -> listing_id` on the Eastern local posting date of `posted_at`. - -Both `--flag value` and `--flag=value` forms are accepted. Missing required flags, invalid `--timestamp-unit`, duplicate flags, unknown flags (including `--from-mongo`), positional arguments, blank field names or `--mapping-source`, and colliding field-name roles (checked after applying defaults) exit non-zero with usage on stderr. - -## `curate-fundamentals` Command (`M2.2r`) - -End-to-end file-to-Parquet CLI command (`src/run_curate_fundamentals.rs`, wired in `src/cli.rs` and `src/main.rs`) streaming concatenated raw BSON `qmFinancials` and `qmFilings` dumps alongside `provider_mapping.tsv` and `listing_venues.tsv` into atomically published `/fundamentals_pit/year=YYYY/part.parquet` partitions with zero extra crates and no database connections (**file mode only** — `--from-mongo` and `--mongo-uri*` are not supported and are rejected as unknown flags). - -### Invocation - -```bash -curate-etl curate-fundamentals \ - --qm-financials qmFinancials.bson \ - --qm-filings qmFilings.bson \ - --provider-mapping provider_mapping.tsv \ - --listing-venues listing_venues.tsv \ - --out ./out \ - --currency-field currency \ - --filings-form-type-field formType \ - --k 4 \ - --quarterly-tokens Q1,Q2,Q3,Q4 \ - --annual-tokens FY \ - --revenue-field IncomeStatement.revenue \ - --net-income-field IncomeStatement.netIncome \ - --operating-cash-flow-field CashFlow.operatingCashFlow \ - --total-assets-field BalanceSheet.totalAssets \ - --total-equity-field BalanceSheet.totalEquity \ - --shares-outstanding-field BalanceSheet.sharesOutstanding -``` - -Inputs, explicit configuration, defaults, and output rules: -- **Required flags (no defaults, because live `qmFinancials`/`qmFilings` field names and token strings are unverified in the repository):** - - `--qm-financials `: concatenated raw BSON (`mongodump` `qmFinancials.bson`). - - `--qm-filings `: concatenated raw BSON (`mongodump` `qmFilings.bson`). - - `--provider-mapping `: headerless 5-column TSV (`sourceprovider_keyeffective_fromeffective_tolisting_id`, same format as `curate-bars-1d`). - - `--listing-venues `: headerless 2-column TSV (`listing_idvenue`, where `listing_id` is a strictly positive ASCII integer and `venue` is exact `us_tsx` or `tsxv_cse`). - - `--out `: dataset root where `/fundamentals_pit/year=YYYY/part.parquet` is atomically published. - - `--currency-field `: dotted BSON path to the reporting currency in `qmFinancials`. - - `--filings-form-type-field `: BSON field name for periodic filing form type in `qmFilings`. - - `--k `: strict positive integer (`>= 1`) snapshot period limit. - - **Fiscal-period mode (mutually exclusive; supply exactly one mode):** - - `--fiscal-period ` to assign a fixed period to every decoded document, **or** - - `--quarterly-tokens ` and/or `--annual-tokens ` (comma-separated exact tokens preserving spelling and whitespace; empty/blank or overlapping tokens fail closed). -- **Optional flags with verified defaults:** - - `--financials-key-field` (default `qmSearchCode`) - - `--period-end-field` (default `periodEndDate`) - - `--report-date-field` (default `reportDate`) - - `--report-period-field` (default `reportPeriod`) - - `--filings-key-field` (default `symbol`) - - `--filings-timefiled-field` (default `timefiled`) - - `--mapping-source` (default `qm`) -- **Optional flags defaulting to `None` (unconfigured metrics emit `NULL` in Parquet):** - - `--revenue-field `, `--net-income-field `, `--operating-cash-flow-field `, `--total-assets-field `, `--total-equity-field `, `--shares-outstanding-field ` - - `--filings-filing-id-field `, `--filings-url-field ` - -Both `--flag value` and `--flag=value` forms are accepted. Missing required flags, combining or omitting fiscal-period modes, invalid `--k` (`0`, signs, non-digits, overflow), duplicate flags, unknown flags (including `--from-mongo` and `--mongo-uri*`), positional arguments, malformed dotted paths, overlapping `qmFilings` field names, or blank/overlapping fiscal tokens fail closed before touching `--out`, exiting non-zero with a single-line diagnostic error and usage on stderr. On success, stdout prints `format_curate_fundamentals_report`. - -## Read-Only MongoDB URI Safety Guard (`M1.2ak`) - -Pure, offline, `std`-only MongoDB URI safety guard (`src/mongo_safety.rs`, zero new crates, no sockets, no DNS resolution, no subprocesses) that ports the QA MongoDB target-classification rules from `apps/stock/config/src/env-safety.ts` before any Rust code may open a MongoDB connection. - -### Public API - -- `parse_mongo_target(uri: &str) -> Result` — parses `mongodb://` and `mongodb+srv://` URIs, splits authority at `/` or `?` (never `#`), percent-decodes usernames (strict UTF-8, without converting `+` to space), iteratively percent-decodes seed hosts up to `8` passes (handling bracketed IPv6 with zone IDs and `mongodb://` `.sock` Unix domain sockets), and rejects control characters, Unicode whitespace, unencoded `#` or multiple `@` in authority, `@` in path/query when authority has no credentials, invalid percent-encoding, and forbidden decoded host characters. -- `is_qa_mongo_target(target: &MongoTarget, local_hosts: &LocalHosts) -> bool` — returns `true` when any seed host is loopback (`localhost`, trailing-dot/case variants, `0.0.0.0`, `127.0.0.0/8` in dotted, shorthand `127.1`, decimal `2130706433`, hex `0x7f000001`, octal `0177.0.0.1`, leading-zero decimal `0127.0.0.1`, IPv6 `::` / `::1` with optional zone ID, and IPv4-mapped `::ffff:127.0.0.0/8` / `::ffff:0.0.0.0`) or matches an injected `LocalHosts` entry on port `27017` (or omitted/default port), regardless of database path. -- `LocalHosts` — deterministic injected set (`LocalHosts::empty()`, `new(...)`, `from_hostname_and_ips(...)`, `with_host(...)`, `contains(...)`) plus `LocalHosts::detect()`, which is **best-effort** and `std`-only (reads `HOSTNAME` and `/etc/hostname` without NIC enumeration or DNS lookups; multi-homed callers should inject LAN IPs via `LocalHosts::from_hostname_and_ips`). -- `assert_read_only_mongo_uri(uri, policy: &ReadOnlyPolicy, local_hosts) -> Result` — fail-closed guard returning a `ValidatedReadOnlyMongoUri` proof token whose fields are private and whose only public constructor is `assert_read_only_mongo_uri`. -- **Password redaction:** `ValidatedReadOnlyMongoUri`'s `Display`, `Debug`, and `redacted()` always replace the password between the first `:` and `@` in userinfo with `[REDACTED]`. `MongoSafetyError` variants never store raw URIs, raw authorities, or passwords. -- **No URI query-option parsing:** beyond authority/remainder splitting and the no-credentials remainder-`@` check, URI query options are intentionally not parsed or validated (matching `apps/stock/config/src/env-safety.ts`). -- **Unix domain sockets:** `.sock` Unix-socket hosts (e.g. `%2Ftmp%2Fmongodb-27017.sock`) are never classified as QA targets (same as `env-safety.ts`). - -### Intentional Stricter-than-`env-safety.ts` Differences - -Target classification (`parse_mongo_target` + `is_qa_mongo_target`) mirrors all five `test/unit/environment-safety*.test.ts` suites (including the 42-case `hostSpellings × ports` matrix, the 3,000-iteration seeded percent-encoding sweep, and all 30,000 cases per authority-split fuzz seed `0x7e28` / `0x28e7`) with identical QA / not-QA / rejected outcomes **except for the intentional stricter rules listed below**. `parse_mongo_target`, `is_qa_mongo_target`, and `assert_read_only_mongo_uri` are deliberately stricter than `env-safety.ts` in eight ways for read-only ETL safety: - -1. **Global case-insensitive `trading_admin` ban:** rejects percent-decoded `trading_admin` (ASCII case-insensitive) on **any** host (QA, dev, or remote), even if a caller adds it to `ReadOnlyPolicy::allowed_read_users` (whereas `env-safety.ts` only checks `username === 'trading_admin'` on QA targets for dev `dataPipeline`). -2. **Mandatory QA credentials & allowlist:** any QA target must provide a username present in `ReadOnlyPolicy::allowed_read_users` (default: `["studio_stock_bot_read"]`, exact match after percent-decoding); missing credentials and non-allowlisted users are rejected. -3. **Rejection of empty, malformed, or invalid bracketed-IPv6 host segments:** URIs like `mongodb://u:p@bad:port,localhost:27017/stock`, `mongodb://u:p@localhost:27018,,localhost:27017/stock`, or `mongodb://u:p@[fe80::g]:27017,localhost:27017/stock` still classify as QA in `parse_mongo_target` / `is_qa_mongo_target` (matching `env-safety.ts`), and are rejected fail-closed with `MalformedHostSegment` by `assert_read_only_mongo_uri` (matching `libs/core/config/src/schemas/database.schema.ts`). Single-seed malformed bracketed IPv6 literals such as `[fe80::g]:27017` are rejected with `NoValidHosts`. -4. **Strict `mongodb+srv://` seed rules:** `assert_read_only_mongo_uri` rejects `mongodb+srv://` URIs with multiple hosts or any explicit `:` port suffix (`InvalidSrvTarget`), matching `database.schema.ts`. -5. **No-credentials remainder-`@` check and strict username percent-decoding:** rejects unencoded `@` in path/query when authority has no `@` (matching `database.schema.ts`), and rejects invalid percent-encoding in the username (e.g. `%ff`, failing closed with `InvalidUsernameEncoding` instead of falling back to the raw username string). -6. **No silent trimming of leading/trailing whitespace:** `env-safety.ts` calls `uri.trim()` before checking `/\s/`, whereas `parse_mongo_target` rejects any Unicode whitespace anywhere in the URI (including leading or trailing spaces) with `ForbiddenWhitespace`. -7. **Leading-zero decimal LAN IPs matched against `LocalHosts`:** `is_qa_mongo_target` normalizes 4-part decimal IPv4 spellings with leading zeros (e.g. `192.168.001.050:27017`) before checking `LocalHosts`, flagging them as QA even where `env-safety.ts` does not. -8. **Machine's own zoned link-local IPv6 matched against `LocalHosts`:** `is_qa_mongo_target` strips `%zone` suffixes when matching bracketed IPv6 hosts against `LocalHosts` (e.g. `[fe80::1234:5678%25eth0]:27017`), flagging the machine's own link-local IPv6 on port `27017` as QA even where `env-safety.ts` misses it. - -## Driver-Independent MongoDB Raw-BSON Cursor Seam (`M1.2al`) - -Library-only, driver-independent read-only MongoDB raw-BSON cursor seam (`src/mongo_stream.rs`, tested offline in `src/mongo_stream_tests.rs`) bridging the read-only safety model (`src/mongo_safety.rs`) into the existing `bson_stream` zero-copy decoders (`RawBsonChunkReader` and `decode_*_stream`) with zero new dependencies and zero CLI/command wiring yet. - -### Dependencies - -- **No new dependency added:** `tools/curate-etl/Cargo.toml` and `Cargo.lock` are unchanged (still three exact-pinned direct dependencies: `bson = "=3.1.0"`, `parquet = "=60.2.0"`, and `rayon = "=1.12.0"`). `src/mongo_stream.rs` contains no `mongodb::` driver paths yet. - -### Public API & Sealing Guarantees - -- **Closed collection allowlist (`SourceCollection`):** 8 variants matching `RAW_BSON_EXPORT_COLLECTIONS` in `apps/stock/data-pipeline/src/security-master/export-raw-bson.ts` in exact order (`eodPrices`, `qmSplits`, `qmDividends`, `qmPrices`, `teMarketData`, `ceoShorts`, `qmFilings`, `qmEarnings`). No API accepts a free-form collection name string. -- **Typed read spec (`MongoReadSpec`, `MongoDateRange`, `FilterDateValue`, `build_filter_document`):** validates `batch_size` (`1..=100_000`, default `4_096`), `limit` (`1..=i64::MAX`), `max_doc_bytes` (`>= 5`, default `16 MiB + 16 KiB`), non-blank `key_eq`, and half-open `[gte, lt)` `date_range` (rejected on `teMarketData`; `qmFilings.timefiled` server-side string ranges require Eastern calendar-day boundaries `YYYY-MM-DD` so neither UTC offsets nor fall-back DST local-string inversions can silently miss filings), building `bson::Document` via `Document::from_iter(...)`. -- **Driver-independent seam (`RawDocumentSource`, `SliceRawDocumentSource`, `VecRawDocumentSource`) + bounded-memory `io::Read` adapter (`RawBsonCursorReader`):** validates every raw BSON frame (`len >= 5`, `len <= max_doc_bytes`, 4-byte LE length prefix `== len`, trailing `0x00`), copies directly into the caller's buffer when it fits, spills only the unread tail of a single current document into a reused `pending` buffer, tracks `docs_read()` / `bytes_read()` / `pending_capacity()`, and surfaces mid-stream errors as sticky `io::Error`s carrying `MongoStreamError`. -- **Error redaction (`MongoStreamError`, `MongoStreamError::redacted_source`):** never stores raw URIs or passwords; sanitizes raw URI, raw password, percent-decoded password, and embedded `mongodb://` / `mongodb+srv://` userinfo passwords (including passwords containing punctuation such as `,`, `;`, quotes, brackets, or `@`) to `[REDACTED]` (reusing `mongo_safety::redact_mongo_uri_password`). - -### `bench-mongo-stream` - -Offline fixed-seed benchmark comparing decoding `1,000,000` synthetic `eodPrices` documents (`285,639,152` bytes) through plain `io::Cursor<&[u8]>` → `decode_eod_price_stream` vs. `SliceRawDocumentSource` → `RawBsonCursorReader` → `decode_eod_price_stream`: - -```bash -cargo run -p curate-etl --release --offline -- bench-mongo-stream 1000000 -``` - -Measured locally (`2026-11-30`, two back-to-back offline runs on the final code with identical stats `decoded=995008`, `rejected=4992`, and checksum `0x05af9d2746d1b5e3`): - -- **Run 1:** plain `264.49 ms` (`3,780,816 docs/s`, `1,029.92 MiB/s`) vs. `RawBsonCursorReader` `263.32 ms` (`3,797,634 docs/s`, `1,034.50 MiB/s`, ratio `1.004x`, `peak_pending_capacity=271 bytes`) -- **Run 2:** plain `281.99 ms` (`3,546,241 docs/s`, `966.02 MiB/s`) vs. `RawBsonCursorReader` `270.90 ms` (`3,691,390 docs/s`, `1,005.56 MiB/s`, ratio `1.041x`, `peak_pending_capacity=271 bytes`) - -### Not Done / Not Verified - -- **Deferred `mongodb`-backed `MongoRawDocumentSource`:** the `mongodb` crate could not be fetched into the offline Cargo cache from the sandbox (`cargo fetch` failed with `failed to download from https://index.crates.io/config.json: [6] Could not resolve hostname (Could not resolve host: index.crates.io)`), and its driver-backed code has never been compiled. Adding exact-pinned `mongodb` (`Cargo.toml` / `Cargo.lock`) and `MongoRawDocumentSource::open(&ValidatedReadOnlyMongoUri, ...)` is deferred to a follow-up task once `mongodb` and its transitive crates are cached via a host-side `cargo fetch` or working crates.io egress. -- **Live QA MongoDB cursor throughput on `quant`:** not run (all tests and benchmarks run 100% offline with zero network connections; live cursor throughput against read-only QA MongoDB on `quant` is deferred to the driver/CLI wiring and live-host verification tasks). - -## Zero-Copy `eodIntraday1M` BSON Decoder (`M2.3d`) - -`src/bson_eod_intraday.rs` decodes raw `eodIntraday1M` MongoDB BSON documents in a single zero-copy forward pass (`RawEodIntradayBar<'a>`, `decode_eod_intraday_doc`, `decode_eod_intraday_bytes`, `decode_eod_intraday_buffer`, `BsonEodIntradayError`, `BsonEodIntradayDecodeStats`) with bounded-memory streaming helpers in `src/bson_stream.rs` (`decode_eod_intraday_chunks`, `decode_eod_intraday_stream`): - -- **Timestamp units:** `timestamp` is bar-start **UTC Unix seconds** (accepted in BSON `Int32`, `Int64`, or finite integral `Double` within `0..=i64::MAX / 1_000_000`) converted to UTC microseconds (`ts: i64`) via checked multiplication by `1_000_000`. It is bar start only (not a publication / `known_at` timestamp). -- **Split-adjusted passthrough:** `open`, `high`, `low`, `close` (finite and `> 0.0`) and `volume` (finite and `>= 0.0`, `-0.0` normalized to `+0.0`) are passed through untouched as the provider's retroactively split-adjusted values; downstream `bars_1m::build_bars_1m` performs split un-adjustment via `SplitTable`. -- **Conversion & zero-copy:** `eodSearchCode` is borrowed verbatim from the input `&RawDocument` slice; `into_eod_intraday_bar` / `try_into_eod_intraday_bar` map `(&'a str, i64)` directly into `bars_1m::EodIntradayBar`. - -## Point-in-Time Fundamentals Core (`M2.2a`) - -Pure, I/O-free, two-stage point-in-time fundamentals builder (`src/fundamentals.rs`, tested in `src/fundamentals_tests.rs`) generic over listing key `K`. BSON decoding, Zstd Parquet writing, CLI `curate-*` wiring, and `MarketDataStore.fundamentalsAsOf` are deferred to follow-up tasks. - -### Public API & Field Set - -- **Single field definition (`FundamentalsFields`):** - - Flow fields (4-quarter TTM-eligible): `revenue`, `net_income`, `operating_cash_flow`. - - Stock fields (point-in-time values, never summed for TTM): `total_assets`, `total_equity`, `shares_outstanding`. -- **Stage 1 (`build_fundamentals_rows`):** joins `FinancialObservation` against periodic `events::QmFiling` records (reusing `events::classify_form_type`, `FilingFormGroup::is_periodic_financial_report`, and `events::parse_filing_timefiled`) using an ordered `BTreeMap` (`UsTsx` vs `TsxvCse`). - - `10-Q` / SEDAR `Interim financial statements` map to `FiscalPeriod::Quarterly`; `10-K` / `40-F` / SEDAR `Annual financial statements` map to `FiscalPeriod::Annual`; non-periodic forms (`8-K`, `News release`, `MD&A`, etc.) are never linked. - - **Dated observations (`report_date: Some(rd)`):** links to the earliest matching periodic filing (amended or unamended) on that Eastern calendar date (`et_date == rd`, strictly after `period_end`), allowing late restatements/amendments beyond the inference window. If unlinked and `rd > lag_date`, the observation is dropped (`observations_dropped_unanchored_vintage`) rather than backdated. If a dated statutory-lag estimate for `(key, period_end, fiscal_period)` would become visible at or after a newer dated version (`rd_b > rd_a`, `known_at_b <= lag_micros`) of the same statement, the stale estimate is dropped (`observations_dropped_stale_estimate`) so an older vintage never rolls a newer filing backward. - - **Undated observations (`report_date: None`):** links to the earliest matching **non-amended** periodic filing strictly after `period_end` within inclusive heuristic windows of `QUARTERLY_FILING_LINK_WINDOW_DAYS = 75` or `ANNUAL_FILING_LINK_WINDOW_DAYS = 150` calendar days (sampled `qmFilings` carries no statement-period field). - - **Statutory-lag fallback:** unlinked rows receive `period_end + lag_days` (`+45d` Q / `+90d` FY for `UsTsx`; `+60d` Q / `+120d` FY for `TsxvCse`) at `16:05:00 America/Toronto` via `shorts::et_to_utc_micros`, tagged `known_at_source = "statutory_lag_estimate"`. - - **Validation, deduplication & determinism:** validates dates against `MIN_SUPPORTED_DATE..=MAX_SUPPORTED_DATE` (`2008-01-01..=2030-12-31`), drops bad rows into per-category `FundamentalsStats` counters without panicking, normalizes `-0.0` to `0.0`, collapses exact duplicates, discards conflicting `(key, period_end, known_at_utc_micros)` groups, preserves distinct `known_at_utc_micros` restatement versions, and emits rows strictly sorted by `(key, period_end, known_at_utc_micros)`. -- **Stage 2 (`build_fundamentals_snapshots`, `fundamentals_as_of` / `fundamentals::as_of`):** - - Sweeps rows in `(key, known_at_utc_micros, period_end)` order, applying all updates at a timestamp before emitting one `FundamentalsSnapshot` with the latest `k` (`k >= 1`) visible periods in descending `period_end` order. - - Carries `None` fields forward only from the prior visible version of the same `(period_end, fiscal_period, currency)`, retaining per-field provenance so a snapshot is flagged `has_estimated_lag = true` (`known_at_source = "statutory_lag_estimate"`) whenever any visible slot or any quarter contributing to TTM used an estimate. - - Resolves standalone quarterly versions separately from `FY` rows (so an annual report sharing December 31 with standalone `Q4` never erases `Q4` from TTM) and computes 4-quarter TTM flow sums independently of `k` from the 4 latest visible standalone quarters when adjacent `period_end` gaps are `77..=105` calendar days (`TTM_CONSECUTIVE_QUARTER_MIN_DAYS..=TTM_CONSECUTIVE_QUARTER_MAX_DAYS`) and all 4 share one currency. - - `as_of(snapshots, key, as_of_micros)` performs an inclusive `O(log N)` binary search on `(key, effective_known_at_utc_micros)`. - -### `bench-fundamentals` - -Fixed-seed (`SplitMix64`), offline benchmark exercising both venue classes, linked periodic filings, statutory-lag fallback, exact duplicates, complete 4-quarter TTM histories, and late Q1 amendments across both stages (`k = 4`): - -```bash -cargo run -p curate-etl --release --offline -- bench-fundamentals [rows] -``` - -Measured locally (`2026-12-01`, default `rows = 100000`, `filings = 79157`, `keys = 2500`, `rows_out = 97106`, `snapshots_out = 97105`, deterministic checksum `0xd5f693a28da4d1f0` hashing all row fields, ordered snapshot slots, TTM flows, and provenance): - -- **Run 1:** Stage 1 `47.63 ms`, Stage 2 `41.81 ms`, total `89.44 ms` (`1,118,108 rows/s`, `894.37 ns/row`) -- **Run 2:** Stage 1 `44.34 ms`, Stage 2 `39.73 ms`, total `84.07 ms` (`1,189,459 rows/s`, `840.72 ns/row`) - -## Exporting Input Files (`data-pipeline`) - -All `curate-*` commands read local TSV and concatenated raw-BSON files produced by the read-only exporters in `@stock-bot/data-pipeline`: - -- **PostgreSQL security-master TSVs (`provider_mapping.tsv`, `listing_currencies.tsv`, `delistings.tsv`):** `apps/stock/data-pipeline/src/security-master/run-export-curate-inputs.ts` -- **MongoDB concatenated raw-BSON files (`.bson`):** `apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts` - -See [apps/stock/data-pipeline/README.md](../../apps/stock/data-pipeline/README.md#read-only-raw-bson-exporter-export-raw-bsonts) for flags, read-only safety guards, and the full M1 Step 2 execution order (`run-export-curate-inputs.ts` → `run-export-raw-bson.ts` → `curate-etl curate-*`). - -## Zero-Copy `qmFinancials` BSON Decoder (`M2.2k`) - -`src/bson_qm_financials.rs` (tested in `src/bson_qm_financials_tests.rs`) decodes raw `qmFinancials` / `qmFinancials-old` MongoDB BSON documents without allocating a `bson::Document`, emitting `FinancialObservation<&str>` rows (key borrowed verbatim from the input BSON slice; owned `currency` allocated only on emission) through `decode_qm_financials_doc`, `decode_qm_financials_bytes`, and `decode_qm_financials_buffer`: - -- **Unverified live schema (explicit caller configuration):** Only the four repo-evidenced top-level field names have defaults (`qmSearchCode`, `periodEndDate`, `reportDate`, `reportPeriod`). Live inner field names under `BalanceSheet`, `CashFlow`, and `IncomeStatement`, the currency path, `reportPeriod` token strings, and date BSON types are **unverified against a live dump**, so `QmFinancialsFieldNames::with_verified_defaults(currency, revenue, net_income, operating_cash_flow, total_assets, total_equity, shares_outstanding)` requires callers to explicitly supply the dotted `currency` path and an `Option<&str>` choice (`Some(path)` or intentional `None` opt-out) for all six `FundamentalsFields` metrics, alongside `QmFinancialsFiscalPeriod` (`ByTokens { quarterly, annual }` or `Fixed(FiscalPeriod)`). Empty paths, empty/blank dotted segments, blank tokens, and overlapping token lists fail closed before decoding. -- **Fail-closed dates, periods & BSON framing:** Every document is structurally validated (nested documents/arrays/JS-with-scope up to depth `128`) before semantic skips run so corrupt BSON always returns `Err(BsonQmFinancialsError::CorruptBson)` with the failing byte offset (in buffer mode, callbacks may have already fired for earlier valid documents). `periodEndDate` (required) and `reportDate` (optional) accept BSON `DateTime` (UTC epoch day) or strict `YYYY-MM-DD` strings within `MIN_SUPPORTED_DATE..=MAX_SUPPORTED_DATE`; only an absent or BSON `Null` `reportDate` emits `None` (present-but-invalid vintage dates skip the document rather than silently dropping the vintage). Numeric paths accept `Double`, `Int32`, `Int64`, and trimmed numeric strings (`f64`), counting missing paths, wrong types, unparsable strings, and non-finite values on emitted rows while leaving unconfigured (`None`) paths and BSON `Null` leaves uncounted. -- **Accounting invariant & ownership boundary:** `BsonQmFinancialsDecodeStats` satisfies `docs_in == rows_out + skipped_total()`. QuoteMedia owns the source statement inputs; `build_fundamentals_rows` owns filing linkage and `known_at` derivation, while this decoder preserves the supplied `report_date` vintage and `currency`. Chunked streaming (`bson_stream`), file-to-file runner, and CLI wiring are deferred to follow-up tasks. - -## `run_curate_fundamentals` File-to-File Runner (`M2.2m`) - -`run_curate_fundamentals` / `run_curate_fundamentals_with_readers` (`src/run_curate_fundamentals.rs`) connects concatenated raw BSON `qmFinancials` and `qmFilings` dump files, a headerless 5-column `provider_mapping.tsv`, and a headerless 2-column `listing_venues.tsv` through `decode_qm_financials_chunks` / `decode_qm_filings_chunks` (`src/bson_stream.rs`) and `curate_and_write_fundamentals` into `/fundamentals_pit/year=YYYY/part.parquet` (Zstd Parquet): - -- **Explicit field paths & fiscal policy (no unverified defaults):** `CurateFundamentalsArgs::with_verified_defaults(...)` populates only the four verified `qmFinancials` defaults (`qmSearchCode`, `periodEndDate`, `reportDate`, `reportPeriod`), the two verified `qmFilings` defaults (`symbol`, `timefiled`), and `mapping_source = "qm"`. Callers must explicitly supply the `currency` path, all six numeric metric `Option` paths, `CurateFundamentalsFiscalPeriod` (`Fixed(FiscalPeriod)` or `ByTokens { quarterly, annual }`), `filings_form_type_field`, and snapshot period limit `k >= 1`. -- **`listing_venues.tsv` format (`load_listing_venues_tsv`):** strict headerless 2-column tab-separated file `listing_idvenue`, where `listing_id` is a strictly positive ASCII base-10 integer and `venue` is exact `us_tsx` (`StatutoryLagVenue::UsTsx`) or `tsxv_cse` (`StatutoryLagVenue::TsxvCse`). Wrong column counts, non-integer/non-positive IDs, unknown venues, duplicate IDs, and interior blank lines fail closed with a single-line error naming the path and 1-based line number. -- **Fail-closed & zero-row behavior:** Config validation, output/input path alias checks (including existing `year=YYYY` partition targets), TSV loading, and both BSON stream decodes complete before `curate_and_write_fundamentals` runs. Empty or all-unmapped inputs return `Ok` with `rows_written == 0` without creating `/fundamentals_pit` or modifying pre-existing partitions. CLI wiring (`curate-fundamentals`) is a separate follow-up. - -## `run_curate_bars_1m` Bounded-Memory File-to-File Runner (`M2.3k`) - -`run_curate_bars_1m` / `run_curate_bars_1m_with_readers` (`src/run_curate_bars_1m.rs`) streams a concatenated raw BSON `eodIntraday1M` dump alongside a `qmSplits` BSON dump and a headerless 5-column `provider_mapping.tsv` (reusing `load_provider_mapping_tsv` and the shared `qmSplits` loader from `src/run_curate_bars.rs`) into per-shard QuestDB ILP v2 files (`/bars_1m.shard-.ilp`): - -- **Bounded-memory chunking & listing-keyed splits:** Drives `RawBsonChunkReader::with_options`, `next_chunk()`, and `decode_eod_intraday_buffer` directly (the same reader and decoder wrapped by `decode_eod_intraday_chunks`, which hides chunk boundaries), resolving each bar's `listing_id` on its Eastern Time `session_date` before applying `listing_id`-keyed `qmSplits` un-adjustment (preventing split leakage across reused tickers) into one shared `IlpShardedWriter` and calling `finish()` once after EOF. Peak memory is bounded by the reference tables, `BsonStreamOptions::chunk_capacity_bytes` (growing only for a single document up to `max_doc_bytes`), per-chunk curation buffers, and one ILP batch buffer per shard. -- **Cross-chunk semantics & reporting:** `mapping_source` must be `"eod"`. Collision collapse/drop and `(listing_id, ts)` ordering apply per chunk; the same `(listing_id, ts)` appearing in two chunks is emitted twice and relies on QuestDB `DEDUP UPSERT KEYS(ts, listing_id)`. Aggregated `curate_stats.listings_out` and `curate_stats.builder.keys_out` are sums of per-chunk counts (not global distinct counts). `known_at_micros` is caller-supplied and supplies no evidence of earlier market availability. -- **Fail-closed publication:** Preflight scans `out_dir` for any pre-existing `bars_1m.shard-.ilp` file (regardless of `shard_count`) and rejects before staging, writes to exclusively created temp files in `out_dir`, flushes and `sync_all`s on `finish`, publishes via same-directory `hard_link` + temp removal, and rolls back only final files created by the current run on any publication error. File-mode CLI wiring is available via `curate-bars-1m` below; `--from-mongo` and live QuestDB ingestion remain follow-ups. - -### `curate-bars-1m` Command (`M2.3n`) - -File-mode CLI command wiring `run_curate_bars_1m` into the `curate-etl` binary: - -```bash -curate-etl curate-bars-1m \ - --eod-intraday eodIntraday1M.bson \ - --qm-splits qmSplits.bson \ - --provider-mapping provider_mapping.tsv \ - --out ./out \ - --shards 4 \ - --known-at-micros 1750000000000000 -``` - -- **Required flags:** `--eod-intraday `, `--qm-splits `, `--provider-mapping `, `--out `, `--shards ` (positive base-10 integer, no default), and `--known-at-micros ` (positive base-10 UTC microsecond timestamp, no default). -- **Optional flag:** `--mapping-source ` (defaults to `eod`; only `eod` is accepted by the runner). -- **Timestamp semantics:** `--known-at-micros` records the caller-supplied curation run timestamp verbatim in each ILP row's `known_at` column; it does not establish historical market availability. -- **Outputs & fail-closed publication:** writes `/bars_1m.shard-.ilp` (`00`..``) and prints the `format_curate_bars_1m_report` summary to stdout. Inherits the runner's fail-closed preflight and staging/rollback guarantees (refuses to overwrite existing `bars_1m.shard-*.ilp` files and leaves no partial shard or staging files on error). -- **File mode only:** MongoDB streaming flags (such as `--from-mongo` and `--mongo-uri`) are rejected; `--from-mongo` streaming and live QuestDB ingestion remain follow-ups. - -## `run_curate_fx_1m` File-to-File Runner (`M2.3l`) - -`run_curate_fx_1m` / `run_curate_fx_1m_with_readers` (`src/run_curate_fx_1m.rs`) streams a concatenated raw BSON `eodIntraday1M` dump into per-shard QuestDB ILP v2 files (`/fx_1m.shard-.ilp`) via `curate_and_write_fx_1m_from_bson` (`src/curate_fx_1m.rs`): - -- **Global sort & deduplication with bounded non-FX memory:** Calls `curate_and_write_fx_1m_from_bson` once over the entire input stream so `ts` sorting and deduplication (bitwise-identical OHLC collapse vs. conflicting-group drop) are global across all BSON stream chunks, then calls `IlpShardedWriter::finish()` once after clean EOF. Because `Fx1mAccumulator::push` counts wrong-code rows and returns before appending, peak memory is bounded by accepted `CAD.FOREX` rows plus `BsonStreamOptions::chunk_capacity_bytes` (growing only for a single document up to `max_doc_bytes`) and bounded per-shard output buffers. -- **Single-pair sharding & empty runs:** Every curated row carries `pair = "USDCAD"`, `source = "eod"`, and EODHD's UTC microsecond bar-start `ts` (preserving CAD-per-USD OHLC bits without implying bar-close observability at bar start), routing all rows deterministically to `shard_for_fx_pair("USDCAD", shard_count)` while publishing all other shards as empty files. Empty or wrong-code-only inputs succeed with `rows_written == 0` and publish the full set of empty shard files. -- **Fail-closed publication:** Reuses the shared `run_curate_bars_1m` staging and publication helpers parameterized by table name (`fx_1m`): preflight rejects any pre-existing `fx_1m.shard-.ilp` in `out_dir` regardless of `shard_count` (while allowing `bars_1m.shard-*.ilp` to coexist untouched), writes to exclusively created temp files, flushes and `sync_all`s on `finish`, publishes via same-directory `hard_link` + temp removal, and rolls back only final files created by the current run on any error. File-mode CLI wiring is available via `curate-fx-1m` below; `--from-mongo` and live QuestDB load remain follow-ups. - -### `curate-fx-1m` Command (`M2.3o`) - -File-mode CLI command wiring `run_curate_fx_1m` into the `curate-etl` binary: - -```bash -curate-etl curate-fx-1m \ - --eod-intraday eodIntraday1M.bson \ - --out ./out \ - --shards 4 -``` - -- **Required flags:** `--eod-intraday ` (local concatenated raw BSON `eodIntraday1M` dump), `--out `, and `--shards ` (positive base-10 integer, no default). -- **Outputs & fail-closed publication:** writes `/fx_1m.shard-.ilp` (`00`..``) and prints the `format_curate_fx_1m_report` summary to stdout. Inherits the runner's fail-closed preflight and staging/rollback guarantees (refuses to overwrite existing `fx_1m.shard-*.ilp` files and leaves no partial shard or staging files on error). -- **File mode only:** MongoDB streaming flags (such as `--from-mongo` and `--mongo-uri`) are rejected; `--from-mongo` streaming and live QuestDB ingestion remain follow-ups. - -### `send-ilp` Command (`M2.3q`) - -CLI command wiring `discover_ilp_shard_files`, `tcp_ilp_connector`, and `send_ilp_shard_files` (`run_send_ilp`) into the `curate-etl` binary to stream published intraday ILP v2 shard files to an explicit QuestDB TCP endpoint: - -```bash -curate-etl send-ilp \ - --dir ./out \ - --prefix bars_1m \ - --addr -``` - -- **Required flags (no default target):** `--dir `, `--prefix `, and `--addr ` are all required (accepting both `--flag value` and `--flag=value`). There is **no default address and no environment-variable fallback**, which prevents implicit targeting; operators must explicitly supply and verify an approved endpoint so QA QuestDB is not targeted by mistake. -- **Allowed prefixes:** restricted to `bars_1m` (`curate-bars-1m`), `bars_1m_qm` (`run_curate_qm_bars_1m`), and `fx_1m` (`curate-fx-1m`). -- **Fail-closed order & reporting:** validates and discovers the contiguous `0..N` shard set in `--dir` before resolving `--addr` or opening any socket; streams each shard verbatim over its own TCP socket using `IlpTcpOptions::default()` and `IlpSendOptions::default()`; prints `format_ilp_send_report` to stdout on exit `0`, or `error: ...` plus any formatted partial report (`per_shard_bytes`) to stderr on non-zero exit. -- **Delivery & protocol caveats:** TCP ILP provides no per-row or per-batch server acknowledgement — exit `0` means all bytes were accepted by local sockets and write-half shutdown succeeded, **not** that rows were committed in QuestDB; verify committed row counts and representative values via PGWire after loading. QuestDB `10.2.0` acceptance of ILP v2 binary `DOUBLE` payloads over TCP without a handshake remains **unverified** until the manual `quant` load check. - -## `run_curate_qm_bars_1m` Bounded-Memory File-to-File Runner (`M2.3m`) - -`run_curate_qm_bars_1m` / `run_curate_qm_bars_1m_with_readers` (`src/run_curate_qm_bars_1m.rs`) streams a concatenated raw BSON `qmIntraday` dump alongside a headerless 5-column `provider_mapping.tsv` (`load_provider_mapping_tsv`) into per-shard QuestDB ILP v2 files (`/bars_1m_qm.shard-.ilp`) via `curate_and_write_qm_bars_1m` (`src/curate_qm_bars_1m.rs`): - -- **Bounded-memory chunking & raw OHLCV passthrough:** Drives `RawBsonChunkReader::with_options`, `next_chunk()`, and `decode_qm_intraday_buffer` directly, borrowing `qmSearchCode` per chunk and curating without split un-adjustment (no splits input; raw `qmIntraday` OHLCV passes through bit-identical aside from `-0.0 -> +0.0` volume normalization) into one shared `IlpShardedWriter` with `finish()` called once after clean EOF. `mapping_source` rejects blank values and forwards any nonblank namespace verbatim (`DEFAULT_QM_BARS_1M_MAPPING_SOURCE = "qm"`). -- **Cross-chunk semantics, table/file separation & reporting:** Sorting and collision collapse/drop apply per chunk; cross-chunk duplicates rely on QuestDB `DEDUP UPSERT KEYS(ts, listing_id)`, and `curate_stats.listings_out` / `curate_stats.builder.keys_out` sum per-chunk counts. Emitted ILP v2 rows target table `bars_1m` with `source=qm_raw` and caller-supplied `known_at_micros`, while output files use the `bars_1m_qm.shard-.ilp` prefix so QM and EOD (`bars_1m.shard-.ilp`) exports can share `out_dir` safely. -- **Fail-closed publication:** Preflight rejects any pre-existing `bars_1m_qm.shard-.ilp` in `out_dir` regardless of `shard_count`, writes to exclusively created staging files, flushes and `sync_all`s on `finish`, publishes via same-directory `hard_link` + temp removal, and rolls back only this run's final and staging files on any error. CLI wiring, `--from-mongo`, and live QuestDB ingestion remain follow-ups. - -## Lagged Macro Regime Series Builder (`M2.2n`) - -`build_macro_rows` (`src/macro_series.rs`, tested in `src/macro_series_tests.rs`) is a pure, in-memory builder turning `MacroObservation` inputs and a caller-supplied `(country_iso, indicator) -> Option` lookup into sorted, unique `MacroRow` records matching `macro/part.parquet` in `design/DATA-CONTRACTS.md` (§1 and §3A). - -- **Governance & provenance:** Quant Research owns the coarse regime-use policy; the caller owns the explicit `(country_iso, indicator)` lag mapping. TradingEconomics indicator names are **not** hardcoded because live `teIndicators` / `teData` names are unverified in this crate. Because `teData` carries final-revised `{d, v}` values without verified release dates or historical vintages, availability starts strictly at `known_at` (`00:00:00 UTC` of `period_date + lag_days`), tagged `known_at_source = "publication_lag_estimate"` (`MACRO_KNOWN_AT_SOURCE`). -- **Locked lag classes (`MacroLagClass`):** `PolicyRate` (`+1d`, `POLICY_RATE_LAG_DAYS`), `MonthlyRelease` (`+35d`, `MONTHLY_RELEASE_LAG_DAYS`), `Gdp65` (`+65d`, `GDP65_LAG_DAYS`), and `Gdp90` (`+90d`, `GDP90_LAG_DAYS`). -- **Fail-closed filtering, deduplication & overflow:** Unmapped `(country_iso, indicator)` pairs are skipped first (`skipped_unmapped_indicator`) and never given a default lag; non-finite values on mapped pairs are skipped (`skipped_non_finite_value`). Surviving rows are sorted by `(country_iso, indicator, period_date)`; bitwise-identical (`f64::to_bits()`) duplicates collapse (`skipped_duplicate`), while conflicting values (including `+0.0` vs. `-0.0`) return `MacroError::ConflictingDuplicate`. Checked `i32` date addition and `i64` microsecond scaling return `MacroError::KnownAtOverflow` rather than panicking. `MacroBuildStats` satisfies `input == emitted + skipped_unmapped_indicator + skipped_non_finite_value + skipped_duplicate`. -- **Parquet writer (`M2.2o`) & deferred items:** `write_macro_dataset` (`src/parquet_macro.rs`, tested in `src/parquet_macro_tests.rs`) writes `MacroParquetRow` (via `From<&MacroRow>`) atomically to `/macro/part.parquet` (6-column Zstd contract schema); deferred: `macroAsOf` DuckDB reader and live MongoDB access. - -## Zero-Copy `teData` BSON Decoder (`M2.2p`) - -`src/bson_te_data.rs` (tested in `src/bson_te_data_tests.rs`) decodes raw `teData` MongoDB BSON documents in a single forward pass without allocating a `bson::Document` or per-point heap memory, emitting borrowed `TeDataPoint<'a>` views through `decode_te_data_doc`, `decode_te_data_bytes`, and `decode_te_data_buffer`. - -- **History-only (zero forecast leakage):** Reads only `data` (`[{ d: "YYYY-MM-DD", v: number }]`) and skips `forecast`, descriptive metadata, timestamps, and unknown fields without calling `elem.value()`. -- **Writer-derived schema & no hardcoded mappings:** Field names (`teSymbol`, `country`, `category`, `data`, `forecast`, `d`, `v`) come from `apps/stock/data-ingestion/src/handlers/te/actions/data-fetch.action.ts` and are not verified against a live `mongodump`. Provider `te_symbol`, `country`, and `category` strings are preserved verbatim; downstream runners own country/indicator/lag mapping into `build_macro_rows`. -- **Fail-closed accounting:** Rejects missing/empty/non-string `teSymbol`, `country`, or `category`, and missing/non-array `data` before emitting any point; rejects malformed/non-string `d` and non-numeric `v` per point while passing finite and non-finite `Double` values through unchanged. `BsonTeDataDecodeStats` maintains `docs_in == docs_accepted + docs_rejected_total()` and `points_in == points_decoded + rejected_total()`. - -## Pure `macro` Curation Stage (`M2.2q`) - -`curate_macro` and `curate_and_write_macro` (`src/curate_macro.rs`, tested in `src/curate_macro_tests.rs`) join decoded `TeDataPoint<'a>` records, `build_macro_rows`, and `write_macro_dataset` into atomically published `/macro/part.parquet`: - -- **Explicit caller-supplied series map:** Maps verbatim `(te_symbol, country, category)` triples to `Option`; unmapped points are dropped into `dropped_unmapped_series` with no default lag, and conflicting lag classes targeting the same `(country_iso, indicator)` fail closed with `CurateMacroError::ConflictingLagClass` independent of input order before writing. -- **Delegated builder & atomic publish:** Delegates filtering, sorting, deduplication, and `known_at` calculation unchanged to `build_macro_rows`, emits strictly ascending unique `MacroParquetRow`s with reconciling `CurateMacroStats` (`points_in == dropped_unmapped_series + builder.input`, `rows_out == builder.emitted`), and leaves `/macro/part.parquet` untouched on empty/all-unmapped input or any curation error. - -## `run_curate_macro` File-to-File Runner (`M2.2s`) - -`run_curate_macro` and `run_curate_macro_with_readers` (`src/run_curate_macro.rs`, tested in `src/run_curate_macro_tests.rs`) connect a concatenated length-prefixed raw BSON `teData` dump (`te_data`) and a caller-supplied series-map TSV (`series_map`) through `decode_te_data_buffer` and `curate_and_write_macro` into `/macro/part.parquet`: - -- **Caller-owned series-map TSV (`load_macro_series_map_tsv`):** Requires the exact line-1 header `te_symbolcountrycategorycountry_isoindicatorlag_class` (LF or CRLF line endings). Each data row must have 6 nonempty tab-separated columns with verbatim `(te_symbol, country, category)` keys (no trimming, no case folding), unique key triples (duplicates fail closed even when targets match), and an exact `lag_class` token in `policy_rate`, `monthly_release`, `gdp65`, or `gdp90`. There is no hardcoded default mapping or default lag class. -- **Buffering, decode & fail-closed behavior:** Validates the full series map first, buffers the concatenated `teData` BSON input in memory (memory grows with dump size), counts per-document/per-point semantic rejects in `BsonTeDataDecodeStats`, and fails closed on the first structural BSON error (`TruncatedDocument`, `CorruptDocumentLength`, `CorruptBson`, `CorruptPointBson`) before publishing. Any I/O, TSV, structural BSON, or curation error (such as `ConflictingLagClass`) returns a single-line `RunCurateMacroError` and leaves `out_dir` and any pre-existing `/macro/part.parquet` byte-identical. Empty or all-unmapped inputs preserve `curate_and_write_macro`'s zero-row no-op. -- **Governance, provenance & reproducibility:** Quant Research owns the coarse regime-use policy and the caller owns the mapping. Because `teData` carries final-revised `{d, v}` values without verified release timestamps or historical vintages, observations become available strictly at the estimated `known_at` (`00:00:00 UTC` of `period_date + lag_days`, `known_at_source = "publication_lag_estimate"`) for coarse regime use. For reproducible checks, pin the `teData` BSON dump and series-map TSV together against the pure stage and fixed expected rows. Real QA `teData` provider-label verification remains a manual host check, and `--from-mongo` streaming remains a separate follow-up. - -## `curate-macro` Command (`M2.2t`) - -File-mode CLI command wiring `run_curate_macro` into the `curate-etl` binary to curate a local `teData` raw BSON dump and caller-supplied series-map TSV into `/macro/part.parquet`: - -```bash -curate-etl curate-macro \ - --te-data ./teData.bson \ - --series-map ./series-map.tsv \ - --out ./out -``` - -- **Required flags (no defaults):** `--te-data `, `--series-map `, and `--out ` are all required (accepting both `--flag value` and `--flag=value`). Duplicate flags, empty values, positional arguments, and unknown flags (including `--from-mongo` and `--mongo-uri*`) are rejected at parse time before touching `--out`. -- **Series-map TSV & lag tokens:** `--series-map` must start with the exact 6-column header `te_symbolcountrycategorycountry_isoindicatorlag_class` with verbatim keys and `lag_class` in `{policy_rate, monthly_release, gdp65, gdp90}`; no country, indicator, or lag-class defaults are built in. -- **Output, fail-closed & zero-row behavior:** Prints `format_curate_macro_report` to stdout on exit `0` and atomically publishes `/macro/part.parquet` (empty or all-unmapped inputs succeed as a zero-row no-op without writing). Runtime errors (missing input, invalid TSV, structural BSON corruption, or curation error) print a single-line `error: ...` to stderr and exit non-zero without creating `--out` or modifying any pre-existing `/macro/part.parquet`; CLI parse errors print `error: ...` followed by `Usage:` to stderr and exit non-zero. diff --git a/tools/curate-etl/src/bars_1m.rs b/tools/curate-etl/src/bars_1m.rs deleted file mode 100644 index 88d2ad9d..00000000 --- a/tools/curate-etl/src/bars_1m.rs +++ /dev/null @@ -1,954 +0,0 @@ -//! Pure, in-memory `bars_1m` intraday 1-minute bar builder (`eodIntraday1M` + `SplitTable`) -//! and `bars_1d` session-close cross-check. -//! -//! Produces sorted, unique per-`(key, ts)` rows with full OHLCV un-adjusted via -//! [`crate::split::unadjust_ohlcv`] using the cumulative split factor for each bar's **Eastern -//! Time session date** (strict `ex_date > session_date` boundary, matching -//! [`SplitTable::cum_factor_after`] bitwise), plus `PRE`/`RTH`/`POST` session tagging. -//! -//! Aligned with `design/DATA-CONTRACTS.md` (§1 `eodIntraday1M` and §B `bars_1m`): -//! - `eodIntraday1M` has both OHLC and volume retroactively split-adjusted, so -//! `raw_price = adj_price * factor` and `raw_volume = adj_volume / factor` (preserving dollar -//! volume `close * volume`). -//! - Session classification uses Eastern Time (`America/New_York` / `America/Toronto`) derived -//! from UTC microseconds via [`crate::session_close::utc_micros_to_et_local`]: -//! `PRE` (`< 09:30 ET`), `RTH` (`09:30..=15:59 ET`), `POST` (`>= 16:00 ET`). -//! - `vwap` and `known_at` are intentionally left to the downstream writer stage (ILP v2 / -//! QuestDB writer), keeping this module pure and I/O-free. -//! - Bad single rows never panic or abort the build; each failure category is dropped and counted -//! separately in [`Bars1mStats`]. - -use std::borrow::Borrow; -use std::cmp::Ordering; -use std::collections::{BinaryHeap, HashMap}; -use std::error::Error; -use std::fmt; -use std::hash::Hash; - -use crate::bars::{Bar1dRow, MAX_MISMATCH_SAMPLES}; -use crate::session_close::utc_micros_to_et_local; -use crate::split::{unadjust_ohlcv, OhlcvBar, SplitTable}; - -/// Canonical provenance label written to [`Bar1mRow::source`] for un-adjusted `eodIntraday1M` bars. -pub const BARS_1M_SOURCE_EOD: &str = "eod_unadj"; - -/// Canonical provenance label written to [`Bar1mRow::source`] for raw `qmIntraday` bars. -pub const BARS_1M_SOURCE_QM: &str = "qm_raw"; - -/// Regular Trading Hours start minute in Eastern Time (`09:30 ET` = `570`). -pub const RTH_START_MINUTE_ET: u16 = 9 * 60 + 30; - -/// Regular Trading Hours exclusive end minute in Eastern Time (`16:00 ET` = `960`). -pub const RTH_END_MINUTE_ET: u16 = 16 * 60; - -/// Intraday market session classification in Eastern Time (`America/New_York` / `America/Toronto`). -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub enum IntradaySession { - /// Pre-market (`00:00..09:30 ET`, i.e., `minute_of_day < 570`). - Pre, - /// Regular trading hours (`09:30..16:00 ET`, i.e., `570 <= minute_of_day < 960`). - Rth, - /// Post-market / after-hours (`16:00..24:00 ET`, i.e., `minute_of_day >= 960`). - Post, -} - -impl IntradaySession { - /// Returns the canonical `bars_1m.session` string tag (`"PRE"`, `"RTH"`, or `"POST"`). - #[inline] - pub const fn as_str(self) -> &'static str { - match self { - Self::Pre => "PRE", - Self::Rth => "RTH", - Self::Post => "POST", - } - } - - /// Classifies an Eastern Time minute-of-day (`0..=1439`) into [`IntradaySession`]. - #[inline] - pub const fn from_et_minute(minute_of_day: u16) -> Self { - if minute_of_day < RTH_START_MINUTE_ET { - Self::Pre - } else if minute_of_day < RTH_END_MINUTE_ET { - Self::Rth - } else { - Self::Post - } - } -} - -/// A single raw `eodIntraday1M` 1-minute bar input. -/// -/// Per `design/DATA-CONTRACTS.md` §1, both OHLC and `volume` are retroactively split-adjusted. -#[derive(Debug, Clone, PartialEq)] -pub struct EodIntradayBar { - pub key: K, - /// Bar start timestamp in UTC microseconds since the Unix epoch. - pub ts: i64, - pub open: f64, - pub high: f64, - pub low: f64, - pub close: f64, - pub volume: f64, -} - -/// A single curated `bars_1m` row, sorted and unique by `(key, ts)`. -/// -/// Carries the `bars_1m` contract columns from `design/DATA-CONTRACTS.md` §B (`key`, `ts`, -/// raw un-adjusted OHLCV, `session`, `source`) plus the derived Eastern Time `session_date`. -/// Downstream writer columns (`vwap`, `known_at`) are intentionally left to the writer stage. -#[derive(Debug, Clone, PartialEq)] -pub struct Bar1mRow { - pub key: K, - /// Bar start timestamp in UTC microseconds since the Unix epoch. - pub ts: i64, - /// Local Eastern Time calendar date as days since `1970-01-01`. - pub session_date: i32, - pub open: f64, - pub high: f64, - pub low: f64, - pub close: f64, - pub volume: f64, - pub session: IntradaySession, - pub source: &'static str, -} - -/// Summary counters produced alongside [`Bars1mBuild::rows`]. -/// -/// Conservation invariants: -/// - `bars_in == rows_out + dropped_invalid_ohlc + dropped_inconsistent_ohlc + dropped_invalid_volume + dropped_ts_out_of_range + duplicate_collapsed + duplicate_conflict_dropped` -/// - `pre_rows_out + rth_rows_out + post_rows_out == rows_out` -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct Bars1mStats { - pub bars_in: usize, - pub rows_out: usize, - pub keys_out: usize, - pub pre_rows_out: usize, - pub rth_rows_out: usize, - pub post_rows_out: usize, - pub dropped_invalid_ohlc: usize, - pub dropped_inconsistent_ohlc: usize, - pub dropped_invalid_volume: usize, - pub dropped_ts_out_of_range: usize, - pub duplicate_collapsed: usize, - pub duplicate_conflict_dropped: usize, -} - -/// Output of [`build_bars_1m`]: sorted, unique 1m rows and build statistics. -#[derive(Debug, Clone, PartialEq)] -pub struct Bars1mBuild { - pub rows: Vec>, - pub stats: Bars1mStats, -} - -/// Typed caller errors returned by [`check_session_closes`]. -#[derive(Debug, Clone, Copy, PartialEq)] -pub enum Bars1mError { - /// Caller-supplied `rel_tolerance` was non-finite (`NaN`, `+/-inf`) or `< 0.0`. - InvalidTolerance { rel_tolerance: f64 }, -} - -impl fmt::Display for Bars1mError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match *self { - Self::InvalidTolerance { rel_tolerance } => write!( - f, - "invalid relative tolerance {rel_tolerance}: must be finite and >= 0" - ), - } - } -} - -impl Error for Bars1mError {} - -/// Daily raw close reference used by [`check_session_closes`]. -#[derive(Debug, Clone, PartialEq)] -pub struct DailySessionClose { - pub key: K, - /// Session date as days since `1970-01-01` (Eastern / trading calendar date). - pub session_date: i32, - pub close: f64, - /// Optional exclusive Eastern Time session-close cutoff in UTC microseconds. - /// - /// When `Some(cutoff_ts)`, only [`IntradaySession::Rth`] bars with `ts < cutoff_ts` are - /// eligible as the session's closing bar (for example, `13:00:00 ET` on an early-close half - /// day so post-close prints between `13:00` and `15:59 ET` do not displace the `12:59 ET` - /// closing bar while [`Bar1mRow::session`] retains the fixed `PRE`/`RTH`/`POST` tags). - /// When `None`, defaults to the standard `16:00:00 ET` RTH boundary. - pub session_close_ts: Option, -} - -impl DailySessionClose { - /// Creates a daily close reference using the standard `16:00:00 ET` RTH cutoff. - #[inline] - pub const fn new(key: K, session_date: i32, close: f64) -> Self { - Self { - key, - session_date, - close, - session_close_ts: None, - } - } - - /// Creates a daily close reference with an explicit exclusive UTC microsecond session-close - /// cutoff (for example, `13:00:00 ET` on a half-day early close). - #[inline] - pub const fn with_close_cutoff( - key: K, - session_date: i32, - close: f64, - session_close_ts: i64, - ) -> Self { - Self { - key, - session_date, - close, - session_close_ts: Some(session_close_ts), - } - } -} - -/// Explicit in-memory session-close cutoff policy required when resolving raw [`Bar1dRow`] -/// references for [`check_session_closes_against_bars_1d`] or [`DailySessionClose::from_bar_1d`]. -/// -/// Lookup precedence for `(key, session_date)`: -/// 1. Per-listing, per-date override (`Some(cutoff_ts)` or `None` to explicitly use standard -/// `16:00:00 ET` even when a market-wide per-date cutoff is configured, e.g., a TSX listing on -/// a US early-close day). -/// 2. Per-date cutoff (e.g., `13:00:00 ET` on the Friday after US Thanksgiving). -/// 3. Standard `16:00:00 ET` RTH boundary (`None`). -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct SessionCloseCutoffPolicy -where - K: Eq + Hash, -{ - per_date: HashMap, - per_listing_date: HashMap>>, -} - -impl SessionCloseCutoffPolicy { - /// Creates an explicit policy using the standard `16:00:00 ET` RTH boundary for all listings - /// and dates (no early-close overrides). - pub fn standard_rth() -> Self { - Self { - per_date: HashMap::new(), - per_listing_date: HashMap::new(), - } - } - - /// Sets an exclusive UTC microsecond session-close cutoff for all listings on `session_date` - /// (unless overridden by a listing-specific rule). - pub fn set_date_cutoff(&mut self, session_date: i32, cutoff_ts: i64) { - self.per_date.insert(session_date, cutoff_ts); - } - - /// Builder-style variant of [`Self::set_date_cutoff`]. - pub fn with_date_cutoff(mut self, session_date: i32, cutoff_ts: i64) -> Self { - self.set_date_cutoff(session_date, cutoff_ts); - self - } - - /// Builder-style helper to populate multiple `(session_date, cutoff_ts)` per-date cutoffs. - pub fn with_date_cutoffs(mut self, cutoffs: I) -> Self - where - I: IntoIterator, - { - for (session_date, cutoff_ts) in cutoffs { - self.set_date_cutoff(session_date, cutoff_ts); - } - self - } - - /// Sets a per-listing, per-date cutoff override. - /// - /// Pass `Some(cutoff_ts)` for a listing-specific early close, or `None` to explicitly select - /// the standard `16:00:00 ET` cutoff for `key` on `session_date` even if a per-date cutoff is - /// configured. - pub fn set_listing_date_cutoff(&mut self, key: K, session_date: i32, cutoff_ts: Option) { - self.per_listing_date - .entry(key) - .or_default() - .insert(session_date, cutoff_ts); - } - - /// Builder-style variant of [`Self::set_listing_date_cutoff`]. - pub fn with_listing_date_cutoff( - mut self, - key: K, - session_date: i32, - cutoff_ts: Option, - ) -> Self { - self.set_listing_date_cutoff(key, session_date, cutoff_ts); - self - } - - /// Builder-style helper to populate multiple `(key, session_date, cutoff_ts)` listing - /// overrides. - pub fn with_listing_date_cutoffs(mut self, cutoffs: I) -> Self - where - I: IntoIterator)>, - { - for (key, session_date, cutoff_ts) in cutoffs { - self.set_listing_date_cutoff(key, session_date, cutoff_ts); - } - self - } - - /// Resolves the exclusive UTC microsecond session-close cutoff for `(key, session_date)`, - /// returning `None` when the standard `16:00:00 ET` RTH boundary applies. - #[inline] - pub fn cutoff_for(&self, key: &K, session_date: i32) -> Option { - if let Some(listing_cutoffs) = self.per_listing_date.get(key) { - if let Some(&override_cutoff) = listing_cutoffs.get(&session_date) { - return override_cutoff; - } - } - self.per_date.get(&session_date).copied() - } -} - -impl DailySessionClose { - /// Converts a raw [`Bar1dRow`] into a [`DailySessionClose`] using an explicit - /// [`SessionCloseCutoffPolicy`]. - #[inline] - pub fn from_bar_1d(row: Bar1dRow, cutoff_policy: &SessionCloseCutoffPolicy) -> Self { - let session_close_ts = cutoff_policy.cutoff_for(&row.key, row.session_date); - Self { - key: row.key, - session_date: row.session_date, - close: row.close, - session_close_ts, - } - } - - /// Converts a borrowed [`Bar1dRow`] into a [`DailySessionClose`] using an explicit - /// [`SessionCloseCutoffPolicy`]. - #[inline] - pub fn from_bar_1d_ref(row: &Bar1dRow, cutoff_policy: &SessionCloseCutoffPolicy) -> Self - where - K: Clone, - { - let session_close_ts = cutoff_policy.cutoff_for(&row.key, row.session_date); - Self { - key: row.key.clone(), - session_date: row.session_date, - close: row.close, - session_close_ts, - } - } -} - -/// A single session-close cross-check mismatch sample retained for downstream reporting. -#[derive(Debug, Clone, PartialEq)] -pub struct SessionCloseMismatchSample { - pub key: K, - pub session_date: i32, - pub last_rth_ts: i64, - pub close_1m: f64, - pub close_1d: f64, - pub rel: f64, -} - -/// Summary counters and mismatch metrics produced by [`check_session_closes`]. -/// -/// Conservation invariants: -/// - `checked + unchecked == rth_sessions` -/// - `within_tolerance + mismatched == checked` -/// - `daily_rows_in == daily_unique_partners + daily_invalid_close_dropped + daily_duplicate_collapsed + daily_duplicate_conflict_dropped` -#[derive(Debug, Clone, Copy, Default, PartialEq)] -pub struct SessionCloseStats { - pub rth_sessions: usize, - pub checked: usize, - pub within_tolerance: usize, - pub mismatched: usize, - pub unchecked: usize, - pub max_rel_diff: f64, - pub daily_rows_in: usize, - pub daily_unique_partners: usize, - pub daily_invalid_close_dropped: usize, - pub daily_duplicate_collapsed: usize, - pub daily_duplicate_conflict_dropped: usize, -} - -/// Output of [`check_session_closes`]: summary statistics and capped worst mismatch samples. -#[derive(Debug, Clone, PartialEq)] -pub struct SessionCloseCheck { - pub stats: SessionCloseStats, - pub mismatch_samples: Vec>, -} - -#[inline] -fn is_valid_price(price: f64) -> bool { - price.is_finite() && price > 0.0 -} - -#[inline] -fn is_consistent_ohlc(open: f64, high: f64, low: f64, close: f64) -> bool { - high >= low && open >= low && open <= high && close >= low && close <= high -} - -struct ValidatedIntradayBar { - key: K, - ts: i64, - session_date: i32, - session: IntradaySession, - open: f64, - high: f64, - low: f64, - close: f64, - volume: f64, -} - -#[inline] -fn validated_bar_values_bit_eq( - a: &ValidatedIntradayBar, - b: &ValidatedIntradayBar, -) -> bool { - a.open.to_bits() == b.open.to_bits() - && a.high.to_bits() == b.high.to_bits() - && a.low.to_bits() == b.low.to_bits() - && a.close.to_bits() == b.close.to_bits() - && a.volume.to_bits() == b.volume.to_bits() -} - -/// Builds sorted, unique `bars_1m` rows from split-adjusted `eodIntraday1M` bars. -/// -/// - Validates each input bar without panicking in strict priority order: -/// `dropped_invalid_ohlc` -> `dropped_inconsistent_ohlc` -> `dropped_invalid_volume` -> -/// `dropped_ts_out_of_range`. -/// - Normalizes `-0.0` volume to `+0.0`, sorts surviving bars by `(key, ts)`, collapses -/// bitwise-identical `(key, ts)` duplicates (`duplicate_collapsed`), and drops conflicting -/// duplicate groups (`duplicate_conflict_dropped`). -/// - Looks up the cumulative split factor on the strict `ex_date > session_date` boundary using -/// each bar's **Eastern Time** `session_date`, un-adjusts full OHLCV via [`unadjust_ohlcv`], -/// and re-validates post-unadjust values against floating-point overflow/underflow. -/// - Tags each emitted row with [`IntradaySession`] (`PRE`/`RTH`/`POST`) and -/// [`BARS_1M_SOURCE_EOD`]. -pub fn build_bars_1m(bars: B, splits: &SplitTable) -> Bars1mBuild -where - K: Ord + Eq + Hash + Clone, - B: IntoIterator>, -{ - let bars_iter = bars.into_iter(); - let mut valid_bars: Vec> = Vec::with_capacity(bars_iter.size_hint().0); - let mut stats = Bars1mStats::default(); - - for bar in bars_iter { - stats.bars_in += 1; - - if !is_valid_price(bar.open) - || !is_valid_price(bar.high) - || !is_valid_price(bar.low) - || !is_valid_price(bar.close) - { - stats.dropped_invalid_ohlc += 1; - continue; - } - if !is_consistent_ohlc(bar.open, bar.high, bar.low, bar.close) { - stats.dropped_inconsistent_ohlc += 1; - continue; - } - if !bar.volume.is_finite() || bar.volume < 0.0 { - stats.dropped_invalid_volume += 1; - continue; - } - let Ok(et_local) = utc_micros_to_et_local(bar.ts) else { - stats.dropped_ts_out_of_range += 1; - continue; - }; - - let volume = if bar.volume == 0.0 { 0.0 } else { bar.volume }; - valid_bars.push(ValidatedIntradayBar { - key: bar.key, - ts: bar.ts, - session_date: et_local.session_date, - session: IntradaySession::from_et_minute(et_local.minute_of_day), - open: bar.open, - high: bar.high, - low: bar.low, - close: bar.close, - volume, - }); - } - - valid_bars.sort_unstable_by(|a, b| a.key.cmp(&b.key).then_with(|| a.ts.cmp(&b.ts))); - - let mut rows: Vec> = Vec::with_capacity(valid_bars.len()); - let total_valid = valid_bars.len(); - let mut idx = 0usize; - - while idx < total_valid { - let key_start = idx; - let key = valid_bars[key_start].key.clone(); - while idx < total_valid && valid_bars[idx].key == key { - idx += 1; - } - let key_end = idx; - - let key_splits = splits.splits_for(&key); - let mut split_idx = 0usize; - let key_rows_start = rows.len(); - - let mut bar_idx = key_start; - while bar_idx < key_end { - let ts = valid_bars[bar_idx].ts; - let group_start = bar_idx; - while bar_idx < key_end && valid_bars[bar_idx].ts == ts { - bar_idx += 1; - } - let group_end = bar_idx; - let group_len = group_end - group_start; - - let first = &valid_bars[group_start]; - let all_identical = valid_bars[group_start + 1..group_end] - .iter() - .all(|other| validated_bar_values_bit_eq(first, other)); - - if !all_identical { - stats.duplicate_conflict_dropped += group_len; - continue; - } - - stats.duplicate_collapsed += group_len - 1; - - // `session_date` is monotonically non-decreasing with UTC `ts` (DST transitions - // happen at 02:00 local, never crossing midnight), so this two-pointer scan matches - // `SplitTable::cum_factor_after(&key, first.session_date)` bitwise. - while split_idx < key_splits.len() - && key_splits[split_idx].ex_date <= first.session_date - { - split_idx += 1; - } - - let factor = key_splits.get(split_idx).map_or(1.0, |e| e.suffix_factor); - let mut unadj = unadjust_ohlcv( - OhlcvBar { - open: first.open, - high: first.high, - low: first.low, - close: first.close, - volume: first.volume, - }, - factor, - ); - - if !is_valid_price(unadj.open) - || !is_valid_price(unadj.high) - || !is_valid_price(unadj.low) - || !is_valid_price(unadj.close) - { - stats.dropped_invalid_ohlc += 1; - continue; - } - if !is_consistent_ohlc(unadj.open, unadj.high, unadj.low, unadj.close) { - stats.dropped_inconsistent_ohlc += 1; - continue; - } - if !unadj.volume.is_finite() - || unadj.volume < 0.0 - || (first.volume > 0.0 && unadj.volume == 0.0) - { - stats.dropped_invalid_volume += 1; - continue; - } - if unadj.volume == 0.0 { - unadj.volume = 0.0; - } - - match first.session { - IntradaySession::Pre => stats.pre_rows_out += 1, - IntradaySession::Rth => stats.rth_rows_out += 1, - IntradaySession::Post => stats.post_rows_out += 1, - } - - rows.push(Bar1mRow { - key: key.clone(), - ts, - session_date: first.session_date, - open: unadj.open, - high: unadj.high, - low: unadj.low, - close: unadj.close, - volume: unadj.volume, - session: first.session, - source: BARS_1M_SOURCE_EOD, - }); - } - - if rows.len() > key_rows_start { - stats.keys_out += 1; - } - } - - stats.rows_out = rows.len(); - Bars1mBuild { rows, stats } -} - -/// Wrapper ordering [`SessionCloseMismatchSample`] by desired output order: -/// `(rel DESC, key ASC, session_date ASC)`. -/// -/// In a max-heap ([`BinaryHeap`]), the *largest* element (smallest `rel`, or latest `(key, date)` -/// tie) sits at the top and is evicted when the heap exceeds [`MAX_MISMATCH_SAMPLES`]. Calling -/// [`BinaryHeap::into_sorted_vec`] then returns samples in ascending `Ord` order (worst mismatch -/// first). -struct HeapSessionCloseMismatch(SessionCloseMismatchSample); - -impl Ord for HeapSessionCloseMismatch { - #[inline] - fn cmp(&self, other: &Self) -> Ordering { - other - .0 - .rel - .total_cmp(&self.0.rel) - .then_with(|| self.0.key.cmp(&other.0.key)) - .then_with(|| self.0.session_date.cmp(&other.0.session_date)) - } -} - -impl PartialOrd for HeapSessionCloseMismatch { - #[inline] - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.cmp(other)) - } -} - -impl PartialEq for HeapSessionCloseMismatch { - #[inline] - fn eq(&self, other: &Self) -> bool { - self.cmp(other) == Ordering::Equal - } -} - -impl Eq for HeapSessionCloseMismatch {} - -struct LastRthBar<'a, K> { - key: &'a K, - session_date: i32, - ts: i64, - close: f64, - /// `true` when multiple eligible `Rth` bars shared the maximum `ts` with differing closes. - conflicting_last_ts: bool, -} - -fn select_last_rth_bars<'a, K, I>( - rth_sorted: I, - valid_daily: &[DailySessionClose], -) -> Vec> -where - K: Ord + 'a, - I: IntoIterator, -{ - let mut result: Vec> = Vec::new(); - let mut daily_idx = 0usize; - - let mut cur_group: Option<(&'a K, i32, Option)> = None; - let mut cur_best: Option> = None; - - for (key, session_date, ts, close) in rth_sorted { - let cutoff = match cur_group { - Some((gk, gd, cutoff)) if gk == key && gd == session_date => cutoff, - _ => { - if let Some(best) = cur_best.take() { - result.push(best); - } - while daily_idx < valid_daily.len() { - match valid_daily[daily_idx] - .key - .cmp(key) - .then_with(|| valid_daily[daily_idx].session_date.cmp(&session_date)) - { - Ordering::Less => daily_idx += 1, - Ordering::Equal | Ordering::Greater => break, - } - } - let cutoff = if daily_idx < valid_daily.len() - && &valid_daily[daily_idx].key == key - && valid_daily[daily_idx].session_date == session_date - { - valid_daily[daily_idx].session_close_ts - } else { - None - }; - cur_group = Some((key, session_date, cutoff)); - cutoff - } - }; - - if let Some(cutoff_ts) = cutoff { - if ts >= cutoff_ts { - continue; - } - } - - match &mut cur_best { - Some(best) => match ts.cmp(&best.ts) { - Ordering::Greater => { - best.ts = ts; - best.close = close; - best.conflicting_last_ts = false; - } - Ordering::Equal => { - if close.to_bits() != best.close.to_bits() { - best.conflicting_last_ts = true; - } - } - Ordering::Less => {} - }, - None => { - cur_best = Some(LastRthBar { - key, - session_date, - ts, - close, - conflicting_last_ts: false, - }); - } - } - } - - if let Some(best) = cur_best { - result.push(best); - } - result -} - -fn collect_last_rth_bars<'a, K: Ord>( - rows_1m: &'a [Bar1mRow], - valid_daily: &[DailySessionClose], -) -> Vec> { - let is_sorted = rows_1m.windows(2).all(|w| { - w[0].key - .cmp(&w[1].key) - .then_with(|| w[0].session_date.cmp(&w[1].session_date)) - .then_with(|| w[0].ts.cmp(&w[1].ts)) - != Ordering::Greater - }); - - if is_sorted { - return select_last_rth_bars( - rows_1m - .iter() - .filter(|row| row.session == IntradaySession::Rth) - .map(|row| (&row.key, row.session_date, row.ts, row.close)), - valid_daily, - ); - } - - let mut rth_rows: Vec<(&'a K, i32, i64, f64)> = rows_1m - .iter() - .filter(|row| row.session == IntradaySession::Rth) - .map(|row| (&row.key, row.session_date, row.ts, row.close)) - .collect(); - - rth_rows.sort_unstable_by(|a, b| { - a.0.cmp(b.0) - .then_with(|| a.1.cmp(&b.1)) - .then_with(|| a.2.cmp(&b.2)) - }); - - select_last_rth_bars(rth_rows, valid_daily) -} - -/// Cross-checks the close of the last [`IntradaySession::Rth`] 1-minute bar per -/// `(key, session_date)` against raw daily `bars_1d` closes. -/// -/// - Returns [`Bars1mError::InvalidTolerance`] if `rel_tolerance` is non-finite or `< 0.0`. -/// - Selects the last `RTH` bar by max `ts` per `(key, session_date)` strictly before the -/// partner's optional [`DailySessionClose::session_close_ts`] cutoff (defaulting to the -/// standard `16:00:00 ET` boundary when `None`), ignoring `PRE`/`POST` bars and excluding -/// sessions with no eligible `RTH` bar before their cutoff. -/// - If a caller supplies multiple eligible `RTH` bars sharing the session's maximum `ts` with -/// differing `close` values, the session is deterministically counted as `unchecked` regardless -/// of input order. -/// - Uses an `O(N)` single-pass scan when `rows_1m` is already sorted by `(key, session_date, ts)` -/// and falls back to a deterministic sort otherwise. -/// - Filters invalid (`<= 0`, non-finite), collapses bitwise-identical duplicate, and drops -/// conflicting duplicate `bars_1d_closes` partners (comparing both `close` and -/// `session_close_ts`). -/// - Retains up to [`MAX_MISMATCH_SAMPLES`] worst mismatches ordered by -/// `(rel DESC, key ASC, session_date ASC)`. -pub fn check_session_closes( - rows_1m: &[Bar1mRow], - bars_1d_closes: I, - rel_tolerance: f64, -) -> Result, Bars1mError> -where - K: Ord + Clone, - D: Into>, - I: IntoIterator, -{ - if !rel_tolerance.is_finite() || rel_tolerance < 0.0 { - return Err(Bars1mError::InvalidTolerance { rel_tolerance }); - } - - let mut stats = SessionCloseStats::default(); - - let daily_iter = bars_1d_closes.into_iter(); - let mut valid_daily: Vec> = Vec::with_capacity(daily_iter.size_hint().0); - for item in daily_iter { - let daily: DailySessionClose = item.into(); - stats.daily_rows_in += 1; - if !is_valid_price(daily.close) { - stats.daily_invalid_close_dropped += 1; - continue; - } - valid_daily.push(daily); - } - - valid_daily.sort_unstable_by(|a, b| { - a.key - .cmp(&b.key) - .then_with(|| a.session_date.cmp(&b.session_date)) - }); - - let mut write_idx = 0usize; - let mut read_idx = 0usize; - let daily_valid_len = valid_daily.len(); - while read_idx < daily_valid_len { - let mut group_end = read_idx + 1; - while group_end < daily_valid_len - && valid_daily[group_end].key == valid_daily[read_idx].key - && valid_daily[group_end].session_date == valid_daily[read_idx].session_date - { - group_end += 1; - } - let group_len = group_end - read_idx; - let first_bits = valid_daily[read_idx].close.to_bits(); - let first_cutoff = valid_daily[read_idx].session_close_ts; - let all_identical = valid_daily[read_idx + 1..group_end].iter().all(|other| { - other.close.to_bits() == first_bits && other.session_close_ts == first_cutoff - }); - - if all_identical { - stats.daily_duplicate_collapsed += group_len - 1; - if write_idx != read_idx { - valid_daily.swap(write_idx, read_idx); - } - write_idx += 1; - } else { - stats.daily_duplicate_conflict_dropped += group_len; - } - read_idx = group_end; - } - valid_daily.truncate(write_idx); - stats.daily_unique_partners = valid_daily.len(); - - let last_rth = collect_last_rth_bars(rows_1m, &valid_daily); - stats.rth_sessions = last_rth.len(); - - let mut daily_idx = 0usize; - let mut heap: BinaryHeap> = - BinaryHeap::with_capacity(MAX_MISMATCH_SAMPLES + 1); - - for rth in &last_rth { - if rth.conflicting_last_ts { - stats.unchecked += 1; - continue; - } - - while daily_idx < valid_daily.len() { - match valid_daily[daily_idx] - .key - .cmp(rth.key) - .then_with(|| valid_daily[daily_idx].session_date.cmp(&rth.session_date)) - { - Ordering::Less => daily_idx += 1, - Ordering::Equal | Ordering::Greater => break, - } - } - - if daily_idx < valid_daily.len() - && &valid_daily[daily_idx].key == rth.key - && valid_daily[daily_idx].session_date == rth.session_date - { - let close_1d = valid_daily[daily_idx].close; - daily_idx += 1; - stats.checked += 1; - - let rel = if is_valid_price(rth.close) { - (rth.close - close_1d).abs() / close_1d - } else { - f64::INFINITY - }; - let within = rel.is_finite() && rel <= rel_tolerance; - - if rel > stats.max_rel_diff { - stats.max_rel_diff = rel; - } - - if within { - stats.within_tolerance += 1; - } else { - stats.mismatched += 1; - - let should_insert = if heap.len() < MAX_MISMATCH_SAMPLES { - true - } else if let Some(worst_kept) = heap.peek() { - worst_kept - .0 - .rel - .total_cmp(&rel) - .then_with(|| rth.key.cmp(&worst_kept.0.key)) - .then_with(|| rth.session_date.cmp(&worst_kept.0.session_date)) - == Ordering::Less - } else { - false - }; - - if should_insert { - heap.push(HeapSessionCloseMismatch(SessionCloseMismatchSample { - key: rth.key.clone(), - session_date: rth.session_date, - last_rth_ts: rth.ts, - close_1m: rth.close, - close_1d, - rel, - })); - if heap.len() > MAX_MISMATCH_SAMPLES { - heap.pop(); - } - } - } - } else { - stats.unchecked += 1; - } - } - - let mismatch_samples: Vec> = - heap.into_sorted_vec().into_iter().map(|w| w.0).collect(); - - Ok(SessionCloseCheck { - stats, - mismatch_samples, - }) -} - -/// Cross-checks the close of the last [`IntradaySession::Rth`] 1-minute bar per -/// `(key, session_date)` against raw [`Bar1dRow`] daily rows using an explicit -/// [`SessionCloseCutoffPolicy`]. -/// -/// Raw `Bar1dRow` values do not carry an exchange session-close cutoff, so callers must pass -/// `cutoff_policy` (for example, [`SessionCloseCutoffPolicy::standard_rth`] or a policy populated -/// with per-date / per-listing early-close cutoffs) rather than silently assuming `16:00:00 ET`. -pub fn check_session_closes_against_bars_1d( - rows_1m: &[Bar1mRow], - bars_1d: I, - cutoff_policy: &SessionCloseCutoffPolicy, - rel_tolerance: f64, -) -> Result, Bars1mError> -where - K: Ord + Eq + Hash + Clone, - R: Borrow>, - I: IntoIterator, -{ - check_session_closes( - rows_1m, - bars_1d - .into_iter() - .map(|row| DailySessionClose::from_bar_1d_ref(row.borrow(), cutoff_policy)), - rel_tolerance, - ) -} - -#[cfg(test)] -#[path = "bars_1m_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/bars_1m_tests.rs b/tools/curate-etl/src/bars_1m_tests.rs deleted file mode 100644 index de8e7d68..00000000 --- a/tools/curate-etl/src/bars_1m_tests.rs +++ /dev/null @@ -1,878 +0,0 @@ -use super::*; -use crate::bars::Bar1dRow; -use crate::session_close::{SESSION_MAX_SUPPORTED_UTC_MICROS, SESSION_MIN_SUPPORTED_UTC_MICROS}; -use crate::shorts::et_to_utc_micros; -use crate::split::{ymd_to_epoch_days, SplitEvent}; - -fn day(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).expect("valid date") -} - -fn et_ts(y: i32, m: u32, d: u32, hour: u8, minute: u8) -> i64 { - et_to_utc_micros(day(y, m, d), hour, minute, 0).expect("valid ET timestamp") -} - -fn utc_ts(y: i32, m: u32, d: u32, hour: i64, minute: i64) -> i64 { - (i64::from(day(y, m, d)) * 86_400 + hour * 3_600 + minute * 60) * 1_000_000 -} - -fn bar_1m( - key: K, - ts: i64, - open: f64, - high: f64, - low: f64, - close: f64, - volume: f64, -) -> EodIntradayBar { - EodIntradayBar { - key, - ts, - open, - high, - low, - close, - volume, - } -} - -fn daily_row(key: K, session_date: i32, close: f64) -> Bar1dRow { - Bar1dRow { - key, - session_date, - open: close, - high: close, - low: close, - close, - volume: 100_000.0, - } -} - -fn assert_rel_eq(actual: f64, expected: f64, rel_tol: f64) { - let diff = (actual - expected).abs(); - let scale = expected.abs().max(1.0); - assert!( - diff <= rel_tol * scale, - "actual={actual} expected={expected} diff={diff} rel_tol={rel_tol}" - ); -} - -fn assert_bars_1m_invariants(stats: &Bars1mStats) { - assert_eq!( - stats.bars_in, - stats.rows_out - + stats.dropped_invalid_ohlc - + stats.dropped_inconsistent_ohlc - + stats.dropped_invalid_volume - + stats.dropped_ts_out_of_range - + stats.duplicate_collapsed - + stats.duplicate_conflict_dropped, - "bars_1m conservation invariant failed: {stats:?}" - ); - assert_eq!( - stats.rows_out, - stats.pre_rows_out + stats.rth_rows_out + stats.post_rows_out, - "session breakdown != rows_out: {stats:?}" - ); -} - -fn assert_close_check_invariants(stats: &SessionCloseStats) { - assert_eq!( - stats.checked + stats.unchecked, - stats.rth_sessions, - "checked + unchecked != rth_sessions: {stats:?}" - ); - assert_eq!( - stats.within_tolerance + stats.mismatched, - stats.checked, - "within_tolerance + mismatched != checked: {stats:?}" - ); - assert_eq!( - stats.daily_rows_in, - stats.daily_unique_partners - + stats.daily_invalid_close_dropped - + stats.daily_duplicate_collapsed - + stats.daily_duplicate_conflict_dropped, - "daily partner conservation failed: {stats:?}" - ); -} - -#[test] -fn nexm_reverse_split_1_for_20_unadjusts_pre_split_preserves_ex_date_and_matches_bars_1d() { - let pre_day = day(2025, 6, 17); - let ex_date = day(2025, 6, 18); - let post_day = day(2025, 6, 19); - - let splits = SplitTable::from_events([( - "NEXM.V".to_string(), - SplitEvent { - ex_date, - ratio: 0.05, - }, - )]) - .unwrap(); - - // Adjusted 1m bars from eodIntraday1M: - // Pre-split close = 24.29 -> un-adjusted = 24.29 * 0.05 = 1.2145, volume = 5000 / 0.05 = 100_000. - let pre_open_bar = bar_1m( - "NEXM.V".to_string(), - et_ts(2025, 6, 17, 9, 30), - 24.00, - 24.60, - 23.80, - 24.20, - 2_000.0, - ); - let pre_close_bar = bar_1m( - "NEXM.V".to_string(), - et_ts(2025, 6, 17, 15, 59), - 24.20, - 24.40, - 24.10, - 24.29, - 5_000.0, - ); - let ex_bar = bar_1m( - "NEXM.V".to_string(), - et_ts(2025, 6, 18, 15, 59), - 24.10, - 24.50, - 23.90, - 24.30, - 12_500.0, - ); - let post_bar = bar_1m( - "NEXM.V".to_string(), - et_ts(2025, 6, 19, 15, 59), - 24.30, - 24.80, - 24.00, - 24.65, - 9_800.0, - ); - - let built = build_bars_1m( - [ - pre_open_bar.clone(), - pre_close_bar.clone(), - ex_bar.clone(), - post_bar.clone(), - ], - &splits, - ); - assert_bars_1m_invariants(&built.stats); - assert_eq!(built.rows.len(), 4); - assert_eq!(built.stats.keys_out, 1); - assert_eq!(built.stats.rth_rows_out, 4); - - // Pre-split close bar un-adjusted: price * 0.05, volume / 0.05, dollar volume invariant. - let pre_close_out = &built.rows[1]; - assert_eq!(pre_close_out.session_date, pre_day); - assert_eq!(pre_close_out.session, IntradaySession::Rth); - assert_eq!(pre_close_out.source, BARS_1M_SOURCE_EOD); - assert_rel_eq(pre_close_out.open, 1.21, 1e-12); - assert_rel_eq(pre_close_out.high, 1.22, 1e-12); - assert_rel_eq(pre_close_out.low, 1.205, 1e-12); - assert_rel_eq(pre_close_out.close, 1.2145, 1e-12); - assert_rel_eq(pre_close_out.volume, 100_000.0, 1e-12); - assert_rel_eq( - pre_close_out.close * pre_close_out.volume, - pre_close_bar.close * pre_close_bar.volume, - 1e-12, - ); - - // Ex-date and post-split bars must be bit-for-bit unchanged. - for (actual, expected) in [(&built.rows[2], &ex_bar), (&built.rows[3], &post_bar)] { - assert_eq!(actual.open.to_bits(), expected.open.to_bits()); - assert_eq!(actual.high.to_bits(), expected.high.to_bits()); - assert_eq!(actual.low.to_bits(), expected.low.to_bits()); - assert_eq!(actual.close.to_bits(), expected.close.to_bits()); - assert_eq!(actual.volume.to_bits(), expected.volume.to_bits()); - } - - // Raw bars_1d closes match within 0.5% (0 mismatches). - let daily_closes = [ - daily_row("NEXM.V".to_string(), pre_day, 1.215), // ~0.041% diff vs 1.2145 - daily_row("NEXM.V".to_string(), ex_date, 24.30), - daily_row("NEXM.V".to_string(), post_day, 24.65), - ]; - let standard_policy = SessionCloseCutoffPolicy::standard_rth(); - let check = - check_session_closes_against_bars_1d(&built.rows, &daily_closes, &standard_policy, 0.005) - .unwrap(); - assert_close_check_invariants(&check.stats); - assert_eq!(check.stats.rth_sessions, 3); - assert_eq!(check.stats.checked, 3); - assert_eq!(check.stats.within_tolerance, 3); - assert_eq!(check.stats.mismatched, 0); - assert_eq!(check.stats.unchecked, 0); - assert!(check.stats.max_rel_diff < 0.005); - assert!(check.mismatch_samples.is_empty()); -} - -#[test] -fn nvda_forward_split_10_for_1_unadjusts_pre_split_and_matches_bars_1d() { - let pre_day = day(2024, 6, 7); - let ex_date = day(2024, 6, 10); - let post_day = day(2024, 6, 11); - - let splits = SplitTable::from_events([( - "NVDA.US".to_string(), - SplitEvent { - ex_date, - ratio: 10.0, - }, - )]) - .unwrap(); - - // Pre-split adjusted 1m close = 120.888 -> raw = 1208.88; volume = 412_390 -> raw = 41_239. - let pre_bar = bar_1m( - "NVDA.US".to_string(), - et_ts(2024, 6, 7, 15, 59), - 120.50, - 121.00, - 120.40, - 120.888, - 412_390.0, - ); - let ex_bar = bar_1m( - "NVDA.US".to_string(), - et_ts(2024, 6, 10, 15, 59), - 121.50, - 121.95, - 121.40, - 121.79, - 350_000.0, - ); - let post_bar = bar_1m( - "NVDA.US".to_string(), - et_ts(2024, 6, 11, 15, 59), - 120.80, - 121.10, - 120.70, - 120.91, - 290_000.0, - ); - - let built = build_bars_1m([pre_bar.clone(), ex_bar.clone(), post_bar.clone()], &splits); - assert_bars_1m_invariants(&built.stats); - assert_eq!(built.rows.len(), 3); - - let pre_out = &built.rows[0]; - assert_rel_eq(pre_out.open, 1_205.0, 1e-12); - assert_rel_eq(pre_out.high, 1_210.0, 1e-12); - assert_rel_eq(pre_out.low, 1_204.0, 1e-12); - assert_rel_eq(pre_out.close, 1_208.88, 1e-12); - assert_rel_eq(pre_out.volume, 41_239.0, 1e-12); - assert_rel_eq( - pre_out.close * pre_out.volume, - pre_bar.close * pre_bar.volume, - 1e-12, - ); - - // Post-split unchanged bit-for-bit. - assert_eq!(built.rows[1].close.to_bits(), ex_bar.close.to_bits()); - assert_eq!(built.rows[1].volume.to_bits(), ex_bar.volume.to_bits()); - assert_eq!(built.rows[2].close.to_bits(), post_bar.close.to_bits()); - assert_eq!(built.rows[2].volume.to_bits(), post_bar.volume.to_bits()); - - let daily_closes = [ - daily_row("NVDA.US".to_string(), pre_day, 1_208.88), - daily_row("NVDA.US".to_string(), ex_date, 121.79), - daily_row("NVDA.US".to_string(), post_day, 120.91), - ]; - let standard_policy = SessionCloseCutoffPolicy::standard_rth(); - let check = - check_session_closes_against_bars_1d(&built.rows, daily_closes, &standard_policy, 0.005) - .unwrap(); - assert_close_check_invariants(&check.stats); - assert_eq!(check.stats.checked, 3); - assert_eq!(check.stats.within_tolerance, 3); - assert_eq!(check.stats.mismatched, 0); - assert!(check.mismatch_samples.is_empty()); -} - -#[test] -fn negative_non_vacuity_still_adjusted_pre_split_bars_fail_session_close_check() { - let pre_day = day(2025, 6, 17); - let ex_date = day(2025, 6, 18); - let empty_splits: SplitTable = SplitTable::default(); - - // Build with an empty split table so pre-split bar stays retroactively adjusted (24.29). - let built = build_bars_1m( - [ - bar_1m( - "NEXM.V".to_string(), - et_ts(2025, 6, 17, 15, 59), - 24.20, - 24.40, - 24.10, - 24.29, - 5_000.0, - ), - bar_1m( - "NEXM.V".to_string(), - et_ts(2025, 6, 18, 15, 59), - 24.10, - 24.50, - 23.90, - 24.30, - 12_500.0, - ), - ], - &empty_splits, - ); - - let daily_closes = [ - daily_row("NEXM.V".to_string(), pre_day, 1.2145), - daily_row("NEXM.V".to_string(), ex_date, 24.30), - ]; - let standard_policy = SessionCloseCutoffPolicy::standard_rth(); - let check = - check_session_closes_against_bars_1d(&built.rows, daily_closes, &standard_policy, 0.005) - .unwrap(); - assert_close_check_invariants(&check.stats); - assert_eq!(check.stats.checked, 2); - assert_eq!(check.stats.within_tolerance, 1); - assert_eq!(check.stats.mismatched, 1); - assert!( - check.stats.max_rel_diff > 0.005, - "expected max_rel_diff > 0.005, got {}", - check.stats.max_rel_diff - ); - assert_eq!(check.mismatch_samples.len(), 1); - assert_eq!(check.mismatch_samples[0].key, "NEXM.V"); - assert_eq!(check.mismatch_samples[0].session_date, pre_day); - assert_rel_eq(check.mismatch_samples[0].rel, 19.0, 1e-6); -} - -#[test] -fn session_tagging_boundaries_in_est_and_edt_and_utc_date_rollover_split_lookup() { - assert_eq!(IntradaySession::Pre.as_str(), "PRE"); - assert_eq!(IntradaySession::Rth.as_str(), "RTH"); - assert_eq!(IntradaySession::Post.as_str(), "POST"); - - // 1. EST (winter: 2025-01-15) and EDT (summer: 2024-06-10) session boundaries. - let splits_empty: SplitTable<&'static str> = SplitTable::default(); - let boundary_bars = [ - // EST (UTC-5): 09:29 ET = 14:29 UTC, 09:30 = 14:30, 15:59 = 20:59, 16:00 = 21:00 - bar_1m("EST", utc_ts(2025, 1, 15, 14, 29), 10.0, 10.5, 9.5, 10.1, 100.0), - bar_1m("EST", utc_ts(2025, 1, 15, 14, 30), 10.0, 10.5, 9.5, 10.2, 100.0), - bar_1m("EST", utc_ts(2025, 1, 15, 20, 59), 10.0, 10.5, 9.5, 10.3, 100.0), - bar_1m("EST", utc_ts(2025, 1, 15, 21, 0), 10.0, 10.5, 9.5, 10.4, 100.0), - // EDT (UTC-4): 09:29 ET = 13:29 UTC, 09:30 = 13:30, 15:59 = 19:59, 16:00 = 20:00 - bar_1m("EDT", utc_ts(2024, 6, 10, 13, 29), 10.0, 10.5, 9.5, 10.1, 100.0), - bar_1m("EDT", utc_ts(2024, 6, 10, 13, 30), 10.0, 10.5, 9.5, 10.2, 100.0), - bar_1m("EDT", utc_ts(2024, 6, 10, 19, 59), 10.0, 10.5, 9.5, 10.3, 100.0), - bar_1m("EDT", utc_ts(2024, 6, 10, 20, 0), 10.0, 10.5, 9.5, 10.4, 100.0), - ]; - let built = build_bars_1m(boundary_bars, &splits_empty); - assert_bars_1m_invariants(&built.stats); - assert_eq!(built.stats.pre_rows_out, 2); - assert_eq!(built.stats.rth_rows_out, 4); - assert_eq!(built.stats.post_rows_out, 2); - - let expected_sessions = [ - IntradaySession::Pre, - IntradaySession::Rth, - IntradaySession::Rth, - IntradaySession::Post, - ]; - for (idx, row) in built.rows.iter().enumerate() { - assert_eq!(row.session, expected_sessions[idx % 4], "row {idx}"); - } - - // 2. UTC date == ex_date while ET session_date == ex_date - 1 (both EDT and EST): - // must use ET session_date so the pre-split factor IS applied. - let edt_ex = day(2024, 6, 10); - let est_ex = day(2025, 1, 16); - let splits = SplitTable::from_events([ - ( - "EDT_ROLL".to_string(), - SplitEvent { - ex_date: edt_ex, - ratio: 10.0, - }, - ), - ( - "EST_ROLL".to_string(), - SplitEvent { - ex_date: est_ex, - ratio: 2.0, - }, - ), - ]) - .unwrap(); - - // 2024-06-10 00:30 UTC == 2024-06-09 20:30 EDT (POST, session_date = edt_ex - 1) - let edt_evening_ts = utc_ts(2024, 6, 10, 0, 30); - // 2025-01-16 00:30 UTC == 2025-01-15 19:30 EST (POST, session_date = est_ex - 1) - let est_evening_ts = utc_ts(2025, 1, 16, 0, 30); - - let rollover = build_bars_1m( - [ - bar_1m("EDT_ROLL".to_string(), edt_evening_ts, 12.0, 12.5, 11.5, 12.2, 1_000.0), - bar_1m("EST_ROLL".to_string(), est_evening_ts, 50.0, 51.0, 49.0, 50.5, 400.0), - ], - &splits, - ); - assert_bars_1m_invariants(&rollover.stats); - assert_eq!(rollover.rows.len(), 2); - - assert_eq!(rollover.rows[0].key, "EDT_ROLL"); - assert_eq!(rollover.rows[0].session_date, edt_ex - 1); - assert_eq!(rollover.rows[0].session, IntradaySession::Post); - assert_rel_eq(rollover.rows[0].close, 122.0, 1e-12); - assert_rel_eq(rollover.rows[0].volume, 100.0, 1e-12); - - assert_eq!(rollover.rows[1].key, "EST_ROLL"); - assert_eq!(rollover.rows[1].session_date, est_ex - 1); - assert_eq!(rollover.rows[1].session, IntradaySession::Post); - assert_rel_eq(rollover.rows[1].close, 101.0, 1e-12); - assert_rel_eq(rollover.rows[1].volume, 200.0, 1e-12); - - // 3. Fall-back DST repeated 01:30 ET hour (EDT 05:30 UTC vs EST 06:30 UTC on 2024-11-03): - // distinct UTC timestamps must NOT collide as duplicates. - let fall_edt = utc_ts(2024, 11, 3, 5, 30); - let fall_est = utc_ts(2024, 11, 3, 6, 30); - let fall_built = build_bars_1m( - [ - bar_1m("FALL", fall_est, 10.0, 10.2, 9.9, 10.1, 20.0), - bar_1m("FALL", fall_edt, 10.0, 10.3, 9.8, 10.2, 10.0), - ], - &splits_empty, - ); - assert_bars_1m_invariants(&fall_built.stats); - assert_eq!(fall_built.rows.len(), 2); - assert_eq!(fall_built.rows[0].ts, fall_edt); - assert_eq!(fall_built.rows[1].ts, fall_est); - assert_eq!(fall_built.rows[0].session_date, day(2024, 11, 3)); - assert_eq!(fall_built.rows[1].session_date, day(2024, 11, 3)); -} - -#[test] -fn drops_bad_rows_by_priority_handles_post_unadjust_overflow_underflow_and_duplicates() { - let base_ts = et_ts(2024, 5, 1, 10, 0); - let ex_date = day(2024, 6, 1); - - let splits = SplitTable::from_events([ - ( - 1_i32, - SplitEvent { - ex_date, - ratio: 1e-200, - }, - ), - ( - 2_i32, - SplitEvent { - ex_date, - ratio: 1e200, - }, - ), - ]) - .unwrap(); - - let minute = 60_000_000_i64; - let built = build_bars_1m( - [ - // Priority 1: invalid OHLC (also inconsistent / bad vol / bad ts to verify priority) - bar_1m(1, i64::MIN, f64::NAN, 10.0, 5.0, 8.0, -1.0), - bar_1m(1, base_ts + minute, 10.0, f64::INFINITY, 5.0, 8.0, 10.0), - bar_1m(1, base_ts + 2 * minute, 10.0, 12.0, 0.0, 8.0, 10.0), - bar_1m(1, base_ts + 3 * minute, 10.0, 12.0, 5.0, -1.0, 10.0), - // Priority 2: inconsistent OHLC (high < low, open/close out of [low, high]) - bar_1m(1, base_ts + 4 * minute, 10.0, 8.0, 9.0, 8.5, -5.0), - bar_1m(1, base_ts + 5 * minute, 4.0, 10.0, 5.0, 8.0, 10.0), - bar_1m(1, base_ts + 6 * minute, 11.0, 10.0, 5.0, 8.0, 10.0), - bar_1m(1, base_ts + 7 * minute, 8.0, 10.0, 5.0, 4.0, 10.0), - bar_1m(1, base_ts + 8 * minute, 8.0, 10.0, 5.0, 11.0, 10.0), - // Priority 3: invalid volume (NaN, Inf, negative) - bar_1m(1, base_ts + 9 * minute, 8.0, 10.0, 5.0, 8.0, f64::NAN), - bar_1m(1, base_ts + 10 * minute, 8.0, 10.0, 5.0, 8.0, f64::INFINITY), - bar_1m(1, base_ts + 11 * minute, 8.0, 10.0, 5.0, 8.0, -1.0), - // Priority 4: out-of-range ts (pre-1976, post-2030, i64::MIN, i64::MAX) - bar_1m(1, SESSION_MIN_SUPPORTED_UTC_MICROS - 1, 8.0, 10.0, 5.0, 8.0, 10.0), - bar_1m(1, SESSION_MAX_SUPPORTED_UTC_MICROS + 1, 8.0, 10.0, 5.0, 8.0, 10.0), - bar_1m(1, i64::MIN, 8.0, 10.0, 5.0, 8.0, 10.0), - bar_1m(1, i64::MAX, 8.0, 10.0, 5.0, 8.0, 10.0), - // Post-unadjust volume overflow (1e200 / 1e-200 -> Inf) -> dropped_invalid_volume - bar_1m(1, base_ts + 12 * minute, 8.0, 10.0, 5.0, 8.0, 1e200), - // Post-unadjust positive volume underflow (1e-200 / 1e200 -> 0.0) -> dropped_invalid_volume - bar_1m(2, base_ts + 15 * minute, 8.0, 10.0, 5.0, 8.0, 1e-200), - // Post-unadjust price underflow (1e-200 * 1e-200 -> 0.0) -> dropped_invalid_ohlc - bar_1m(1, base_ts + 13 * minute, 1e-200, 1e-200, 1e-200, 1e-200, 10.0), - // Post-unadjust price overflow (1e200 * 1e200 -> Inf) -> dropped_invalid_ohlc - bar_1m(2, base_ts + 14 * minute, 1e200, 1e200, 1e200, 1e200, 10.0), - // Exact duplicate triple (including -0.0 vs +0.0 volume) -> collapses to 1 row - bar_1m(3, base_ts, 10.0, 12.0, 9.0, 11.0, 0.0), - bar_1m(3, base_ts, 10.0, 12.0, 9.0, 11.0, -0.0), - bar_1m(3, base_ts, 10.0, 12.0, 9.0, 11.0, 0.0), - // Conflicting duplicate pair -> both dropped - bar_1m(3, base_ts + minute, 10.0, 12.0, 9.0, 11.0, 50.0), - bar_1m(3, base_ts + minute, 10.0, 12.0, 9.0, 11.01, 50.0), - ], - &splits, - ); - - assert_bars_1m_invariants(&built.stats); - assert_eq!(built.stats.bars_in, 25); - assert_eq!(built.stats.dropped_invalid_ohlc, 6); // 4 input + 1 underflow + 1 overflow - assert_eq!(built.stats.dropped_inconsistent_ohlc, 5); - assert_eq!(built.stats.dropped_invalid_volume, 5); // 3 input + 1 overflow + 1 positive underflow - assert_eq!(built.stats.dropped_ts_out_of_range, 4); - assert_eq!(built.stats.duplicate_collapsed, 2); - assert_eq!(built.stats.duplicate_conflict_dropped, 2); - assert_eq!(built.stats.rows_out, 1); - assert_eq!(built.stats.keys_out, 1); - assert_eq!(built.rows[0].key, 3); - assert_eq!(built.rows[0].volume.to_bits(), 0.0_f64.to_bits()); -} - -#[test] -fn check_session_closes_handles_early_close_pre_post_only_unsorted_hygiene_cap_and_errors() { - // 1. Invalid tolerances return Bars1mError::InvalidTolerance. - for bad_tol in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -0.001] { - let err = check_session_closes::, _>( - &[], - std::iter::empty(), - bad_tol, - ) - .unwrap_err(); - assert!(matches!(err, Bars1mError::InvalidTolerance { .. })); - assert!(err.source().is_none()); - assert!(err.to_string().contains("invalid relative tolerance")); - } - - // 2. Half-day early close (Friday after US Thanksgiving, 13:00 ET close) via raw Bar1dRow path: - // - build_bars_1m preserves the fixed PRE/RTH/POST tags (13:00 and 13:15 still carry RTH). - // - check_session_closes_against_bars_1d applies an explicit SessionCloseCutoffPolicy - // supporting per-date cutoffs and per-listing overrides: - // * listing 1 (US equity): inherits per-date 13:00 ET cutoff -> selects 12:59 ET, - // excluding 13:00 / 13:15 / 16:15 ET prints. - // * listing 2 (e.g. TSX equity on US Thanksgiving Friday): per-listing `None` override - // uses standard 16:00 ET close -> selects 15:59 ET. - // * listing 3: per-listing custom 14:00 ET cutoff -> selects 13:59 ET, excluding 14:15. - let half_day = day(2024, 11, 29); // Friday after US Thanksgiving - let post_only_day = day(2024, 12, 2); - let ts_1259 = et_ts(2024, 11, 29, 12, 59); - let ts_1300 = et_ts(2024, 11, 29, 13, 0); - let ts_1315 = et_ts(2024, 11, 29, 13, 15); - let ts_1359 = et_ts(2024, 11, 29, 13, 59); - let ts_1400 = et_ts(2024, 11, 29, 14, 0); - let ts_1415 = et_ts(2024, 11, 29, 14, 15); - let ts_1559 = et_ts(2024, 11, 29, 15, 59); - let splits: SplitTable = SplitTable::default(); - - let built = build_bars_1m( - [ - bar_1m(1, et_ts(2024, 11, 29, 9, 30), 100.0, 101.0, 99.5, 100.5, 500.0), - bar_1m(1, ts_1259, 101.0, 101.5, 100.8, 101.25, 800.0), - // Exact 13:00 ET boundary and 13:15 ET after-hours print (>4% away): - // fixed tags stay RTH, but the 13:00 ET cutoff must exclude both from the close check. - bar_1m(1, ts_1300, 103.5, 104.2, 103.2, 104.0, 120.0), - bar_1m(1, ts_1315, 105.0, 106.0, 104.5, 105.5, 100.0), - bar_1m(1, et_ts(2024, 11, 29, 16, 15), 105.5, 106.5, 105.0, 106.0, 80.0), - // PRE/POST-only session must be excluded from rth_sessions. - bar_1m(1, et_ts(2024, 12, 2, 8, 0), 102.0, 103.0, 101.5, 102.5, 50.0), - bar_1m(1, et_ts(2024, 12, 2, 17, 0), 103.0, 104.0, 102.5, 103.5, 50.0), - // Listing 2 (standard 16:00 ET close override on half_day): 12:59 vs 15:59 (>5% apart). - bar_1m(2, ts_1259, 50.0, 50.5, 49.5, 50.0, 300.0), - bar_1m(2, ts_1559, 53.0, 53.5, 52.5, 53.25, 400.0), - // Listing 3 (listing-specific 14:00 ET cutoff override on half_day): 13:59 vs 14:15. - bar_1m(3, ts_1359, 20.0, 20.2, 19.8, 20.10, 250.0), - bar_1m(3, ts_1415, 21.5, 21.8, 21.2, 21.60, 100.0), - ], - &splits, - ); - // Output tags strictly follow fixed 09:30..16:00 ET bounds. - assert_eq!(built.rows[0].session, IntradaySession::Rth); - assert_eq!(built.rows[1].session, IntradaySession::Rth); - assert_eq!(built.rows[2].session, IntradaySession::Rth); - assert_eq!(built.rows[3].session, IntradaySession::Rth); - assert_eq!(built.rows[4].session, IntradaySession::Post); - - // Reverse rows_1m to exercise the unsorted fallback path in check_session_closes. - let mut reversed_rows = built.rows.clone(); - reversed_rows.reverse(); - - let cutoff_policy = SessionCloseCutoffPolicy::standard_rth() - .with_date_cutoff(half_day, ts_1300) - .with_listing_date_cutoff(2, half_day, None) - .with_listing_date_cutoff(3, half_day, Some(ts_1400)); - - let raw_daily_rows = [ - daily_row(1, half_day, 101.25), - daily_row(1, post_only_day, 103.5), - daily_row(2, half_day, 53.25), - daily_row(3, half_day, 20.10), - ]; - - let sorted_check = - check_session_closes_against_bars_1d(&built.rows, &raw_daily_rows, &cutoff_policy, 0.005) - .unwrap(); - let unsorted_check = - check_session_closes_against_bars_1d(&reversed_rows, &raw_daily_rows, &cutoff_policy, 0.005) - .unwrap(); - assert_eq!(sorted_check, unsorted_check); - assert_close_check_invariants(&sorted_check.stats); - assert_eq!(sorted_check.stats.rth_sessions, 3); - assert_eq!(sorted_check.stats.checked, 3); - assert_eq!(sorted_check.stats.within_tolerance, 3); - assert_eq!(sorted_check.stats.mismatched, 0); - assert_eq!(sorted_check.stats.max_rel_diff, 0.0); - - // Verify DailySessionClose::from_bar_1d / from_bar_1d_ref parity with the cutoff policy. - let converted_owned: Vec> = raw_daily_rows - .iter() - .cloned() - .map(|row| DailySessionClose::from_bar_1d(row, &cutoff_policy)) - .collect(); - assert_eq!(converted_owned[0].session_close_ts, Some(ts_1300)); - assert_eq!(converted_owned[1].session_close_ts, None); - assert_eq!(converted_owned[2].session_close_ts, None); - assert_eq!(converted_owned[3].session_close_ts, Some(ts_1400)); - assert_eq!( - check_session_closes(&built.rows, converted_owned, 0.005).unwrap(), - sorted_check - ); - - // Prove 12:59 ET (101.25) was actually selected for listing 1 under the 13:00 ET cutoff: - // comparing its raw Bar1dRow against the 13:15 ET price (105.5) must mismatch at ts_1259. - let prove_1259 = check_session_closes_against_bars_1d( - &built.rows, - [daily_row(1, half_day, 105.5)], - &cutoff_policy, - 0.005, - ) - .unwrap(); - assert_eq!(prove_1259.stats.mismatched, 1); - assert_eq!(prove_1259.mismatch_samples[0].last_rth_ts, ts_1259); - assert_eq!(prove_1259.mismatch_samples[0].close_1m, 101.25); - - // Under an explicit standard 16:00 ET policy, listing 1 picks 13:15 ET (105.5) and mismatches. - let standard_only = check_session_closes_against_bars_1d( - &built.rows, - [daily_row(1, half_day, 101.25)], - &SessionCloseCutoffPolicy::standard_rth(), - 0.005, - ) - .unwrap(); - assert_eq!(standard_only.stats.mismatched, 1); - assert_eq!(standard_only.mismatch_samples[0].last_rth_ts, ts_1315); - assert_eq!(standard_only.mismatch_samples[0].close_1m, 105.5); - - // A half-day session whose only RTH bars are at/after the cutoff has no eligible RTH bar. - let post_cutoff_only = build_bars_1m( - [bar_1m(9, ts_1315, 105.0, 106.0, 104.5, 105.5, 100.0)], - &splits, - ); - let post_cutoff_check = check_session_closes_against_bars_1d( - &post_cutoff_only.rows, - [daily_row(9, half_day, 101.25)], - &cutoff_policy, - 0.005, - ) - .unwrap(); - assert_close_check_invariants(&post_cutoff_check.stats); - assert_eq!(post_cutoff_check.stats.rth_sessions, 0); - assert_eq!(post_cutoff_check.stats.checked, 0); - - // 3. Daily close hygiene (invalid, identical dup, conflicting dup) + >100 mismatch sample cap. - let base_day = day(2024, 1, 2); - let mut rows_1m_in = Vec::new(); - let mut daily_in = Vec::new(); - - // Session 0: exact match with identical daily duplicate -> collapses to 1 - rows_1m_in.push(bar_1m(1, et_ts(2024, 1, 2, 15, 59), 10.0, 10.5, 9.5, 10.0, 100.0)); - daily_in.push(DailySessionClose::new(1, base_day, 10.0)); - daily_in.push(DailySessionClose::new(1, base_day, 10.0)); - - // Session 1: conflicting daily duplicate -> dropped -> unchecked - rows_1m_in.push(bar_1m(1, et_ts(2024, 1, 3, 15, 59), 10.0, 10.5, 9.5, 10.0, 100.0)); - daily_in.push(DailySessionClose::new(1, base_day + 1, 10.0)); - daily_in.push(DailySessionClose::new(1, base_day + 1, 10.5)); - - // Session 2: invalid daily closes (NaN, <=0) -> dropped -> unchecked - rows_1m_in.push(bar_1m(1, et_ts(2024, 1, 4, 15, 59), 10.0, 10.5, 9.5, 10.0, 100.0)); - daily_in.push(DailySessionClose::new(1, base_day + 2, f64::NAN)); - daily_in.push(DailySessionClose::new(1, base_day + 2, 0.0)); - - // Session 3: same daily close but conflicting session_close_ts -> dropped -> unchecked - rows_1m_in.push(bar_1m(1, et_ts(2024, 1, 5, 15, 59), 10.0, 10.5, 9.5, 10.0, 100.0)); - daily_in.push(DailySessionClose::new(1, base_day + 3, 10.0)); - daily_in.push(DailySessionClose::with_close_cutoff( - 1, - base_day + 3, - 10.0, - et_ts(2024, 1, 5, 13, 0), - )); - - // 110 mismatches across distinct days on key=2 (plus a tie on key=3 to verify tie-break order). - let start_day = day(2024, 2, 1); - for i in 0..110_i32 { - let d = start_day + i; - let ts = et_to_utc_micros(d, 15, 59, 0).unwrap(); - let close_1m = 100.0 + (i + 2) as f64; // rel = (i + 2) / 100 >= 0.02 > 0.005 - rows_1m_in.push(bar_1m(2, ts, close_1m, close_1m, close_1m, close_1m, 100.0)); - daily_in.push(DailySessionClose::new(2, d, 100.0)); - } - // Tie with highest rel (1.11) on key=3 vs key=2 -> key=2 must sort before key=3. - let tie_d = start_day + 109; - let tie_ts = et_to_utc_micros(tie_d, 15, 59, 0).unwrap(); - rows_1m_in.push(bar_1m(3, tie_ts, 211.0, 211.0, 211.0, 211.0, 100.0)); - daily_in.push(DailySessionClose::new(3, tie_d, 100.0)); - - let built_many = build_bars_1m(rows_1m_in, &splits); - let check_many = check_session_closes(&built_many.rows, daily_in, 0.005).unwrap(); - assert_close_check_invariants(&check_many.stats); - assert_eq!(check_many.stats.daily_invalid_close_dropped, 2); - assert_eq!(check_many.stats.daily_duplicate_collapsed, 1); - assert_eq!(check_many.stats.daily_duplicate_conflict_dropped, 4); - assert_eq!(check_many.stats.unchecked, 3); - assert_eq!(check_many.stats.mismatched, 111); - assert_eq!(check_many.mismatch_samples.len(), MAX_MISMATCH_SAMPLES); - - // Top two samples have rel == 1.11: key=2 before key=3. - assert_rel_eq(check_many.mismatch_samples[0].rel, 1.11, 1e-12); - assert_eq!(check_many.mismatch_samples[0].key, 2); - assert_rel_eq(check_many.mismatch_samples[1].rel, 1.11, 1e-12); - assert_eq!(check_many.mismatch_samples[1].key, 3); - - // Entire mismatch_samples slice is strictly ordered by (rel DESC, key ASC, session_date ASC). - for w in check_many.mismatch_samples.windows(2) { - let ord = w[1] - .rel - .total_cmp(&w[0].rel) - .then_with(|| w[0].key.cmp(&w[1].key)) - .then_with(|| w[0].session_date.cmp(&w[1].session_date)); - assert_eq!(ord, Ordering::Less, "samples out of order: {:?} vs {:?}", w[0], w[1]); - } -} - -#[test] -fn output_is_sorted_unique_and_deterministic_across_input_permutations() { - let splits = SplitTable::from_events([ - ( - "B".to_string(), - SplitEvent { - ex_date: day(2024, 6, 10), - ratio: 5.0, - }, - ), - ( - "A".to_string(), - SplitEvent { - ex_date: day(2024, 6, 12), - ratio: 0.25, - }, - ), - ]) - .unwrap(); - - let mut bars = vec![ - bar_1m("B".to_string(), et_ts(2024, 6, 10, 15, 59), 20.0, 21.0, 19.5, 20.5, 300.0), - bar_1m("A".to_string(), et_ts(2024, 6, 11, 9, 30), 40.0, 41.0, 39.0, 40.2, 100.0), - bar_1m("B".to_string(), et_ts(2024, 6, 7, 15, 59), 19.0, 20.0, 18.5, 19.8, 500.0), - bar_1m("A".to_string(), et_ts(2024, 6, 11, 9, 30), 40.0, 41.0, 39.0, 40.2, 100.0), - bar_1m("A".to_string(), et_ts(2024, 6, 12, 16, 0), 10.0, 10.5, 9.8, 10.1, 200.0), - ]; - - let forward = build_bars_1m(bars.clone(), &splits); - bars.reverse(); - let reversed = build_bars_1m(bars, &splits); - - assert_eq!(forward, reversed); - assert_bars_1m_invariants(&forward.stats); - for w in forward.rows.windows(2) { - let ord = w[0].key.cmp(&w[1].key).then_with(|| w[0].ts.cmp(&w[1].ts)); - assert_eq!(ord, Ordering::Less, "output not strictly sorted/unique"); - } -} - -#[test] -fn check_session_closes_handles_conflicting_latest_rth_timestamps_deterministically() { - let d1 = day(2024, 6, 10); - let d2 = day(2024, 6, 11); - let d3 = day(2024, 6, 12); - - let mk_row = |key: i32, session_date: i32, ts: i64, close: f64| Bar1mRow { - key, - session_date, - ts, - open: close, - high: close, - low: close, - close, - volume: 100.0, - session: IntradaySession::Rth, - source: BARS_1M_SOURCE_EOD, - }; - - // d1: conflicting closes at the latest RTH timestamp (one matches 100.0, one is 105.0). - let ts_d1_last = et_ts(2024, 6, 10, 15, 59); - let d1_match = mk_row(1, d1, ts_d1_last, 100.0); - let d1_mismatch = mk_row(1, d1, ts_d1_last, 105.0); - - // d2: identical duplicate closes at the latest RTH timestamp -> checked and matched. - let ts_d2_last = et_ts(2024, 6, 11, 15, 59); - let d2_a = mk_row(1, d2, ts_d2_last, 50.0); - let d2_b = mk_row(1, d2, ts_d2_last, 50.0); - - // d3: conflicting closes at an earlier timestamp (10:00) followed by a unique latest bar (15:59) - // -> latest bar is unambiguous, so d3 is checked and matched. - let ts_d3_early = et_ts(2024, 6, 12, 10, 0); - let ts_d3_last = et_ts(2024, 6, 12, 15, 59); - let d3_early_a = mk_row(1, d3, ts_d3_early, 20.0); - let d3_early_b = mk_row(1, d3, ts_d3_early, 25.0); - let d3_last = mk_row(1, d3, ts_d3_last, 22.0); - - let daily = [ - DailySessionClose::new(1, d1, 100.0), - DailySessionClose::new(1, d2, 50.0), - DailySessionClose::new(1, d3, 22.0), - ]; - - // Order A (sorted): matching bar before mismatching bar on d1. - let order_a = vec![ - d1_match.clone(), - d1_mismatch.clone(), - d2_a.clone(), - d2_b.clone(), - d3_early_a.clone(), - d3_early_b.clone(), - d3_last.clone(), - ]; - // Order B (sorted): mismatching bar before matching bar on d1. - let order_b = vec![ - d1_mismatch.clone(), - d1_match.clone(), - d2_b.clone(), - d2_a.clone(), - d3_early_b.clone(), - d3_early_a.clone(), - d3_last.clone(), - ]; - // Order C (unsorted fallback): reversed order_a. - let mut order_c = order_a.clone(); - order_c.reverse(); - // Order D (unsorted fallback): reversed order_b. - let mut order_d = order_b.clone(); - order_d.reverse(); - - let check_a = check_session_closes(&order_a, daily.clone(), 0.005).unwrap(); - let check_b = check_session_closes(&order_b, daily.clone(), 0.005).unwrap(); - let check_c = check_session_closes(&order_c, daily.clone(), 0.005).unwrap(); - let check_d = check_session_closes(&order_d, daily, 0.005).unwrap(); - - assert_eq!(check_a, check_b); - assert_eq!(check_a, check_c); - assert_eq!(check_a, check_d); - assert_close_check_invariants(&check_a.stats); - assert_eq!(check_a.stats.rth_sessions, 3); - assert_eq!(check_a.stats.checked, 2); - assert_eq!(check_a.stats.within_tolerance, 2); - assert_eq!(check_a.stats.mismatched, 0); - assert_eq!(check_a.stats.unchecked, 1); - assert!(check_a.mismatch_samples.is_empty()); -} diff --git a/tools/curate-etl/src/bench.rs b/tools/curate-etl/src/bench.rs index 4c352817..02b8bbd7 100644 --- a/tools/curate-etl/src/bench.rs +++ b/tools/curate-etl/src/bench.rs @@ -1,7 +1,6 @@ //! Fixed-seed, std-only benchmark for the split-factor lookup and un-adjustment hot loop. use std::borrow::Cow; -use std::collections::BTreeMap; use std::fs::{self, File}; use std::hint::black_box; use std::io; @@ -10,26 +9,14 @@ use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; use std::time::Instant; use bson::oid::ObjectId; -use bson::raw::{cstr, RawBsonRef, RawDocumentBuf}; +use bson::raw::{cstr, RawDocumentBuf}; use bson::DateTime; use parquet::errors::ParquetError; use parquet::file::reader::{FileReader, SerializedFileReader}; use crate::adj::{build_adj_factors, AdjBuildStats, AdjError, DividendEvent}; use crate::bars::{build_bars_1d, Bars1dStats, BarsError, EodDailyBar, QmRawVolume}; -use crate::bars_1m::{ - build_bars_1m, check_session_closes, Bar1mRow, Bars1mError, Bars1mStats, DailySessionClose, - EodIntradayBar, IntradaySession, SessionCloseStats, BARS_1M_SOURCE_EOD, -}; -use crate::bson_eod_prices::{decode_eod_price_buffer, iter_raw_bson_docs, BsonEodDecodeStats}; -use crate::bson_qm_actions::{ - decode_qm_dividend_buffer, decode_qm_split_buffer, BsonQmActionDecodeStats, -}; -use crate::bson_stream::{ - decode_eod_price_chunks, decode_eod_price_stream, BsonStreamError, BsonStreamOptions, - RawBsonChunkReader, -}; -use crate::mongo_stream::{RawBsonCursorReader, SliceRawDocumentSource}; +use crate::bson_eod_prices::{decode_eod_price_buffer, BsonEodDecodeStats}; use crate::corporate_actions::{ build_corporate_actions, CorporateActionError, CorporateActionKind, CorporateActionsStats, DelistingOutcomeEvent, DividendActionEvent, KnownAtSource, SplitActionEvent, @@ -39,12 +26,7 @@ use crate::events::{ EventsStats, QmEarning, QmFiling, EVENT_KIND_EARNINGS, EVENT_KIND_FILING, KNOWN_AT_SOURCE_FILING_TIMESTAMP, KNOWN_AT_SOURCE_STATUTORY_LAG, }; -use crate::fundamentals::{ - build_fundamentals_rows, build_fundamentals_snapshots, FinancialObservation, FiscalPeriod, - FundamentalsError, FundamentalsFields, FundamentalsStats, StatutoryLagVenue, -}; use crate::fx::{build_fx_1d, fx_rate_on_or_before, Fx1dStats, FxDailyBar, FxSource, FX_PAIR_USDCAD}; -use crate::ilp::{IlpShardedWriter, IlpWriterError, IlpWriterOptions}; use crate::parquet_adj::{ write_adj_factors_dataset, AdjFactorsParquetRow, AdjFactorsWriteOptions, ParquetAdjError, }; @@ -65,7 +47,6 @@ use crate::parquet_shorts::{ write_shorts_dataset, ParquetShortsError, ShortsParquetRow, ShortsWriteOptions, }; use crate::provider_mapping::{ProviderMappingError, ProviderMappingRow, ProviderMappingTable}; -use crate::session_close::{et_session_close_utc_micros, SESSION_MIN_SUPPORTED_UTC_MICROS}; use crate::shorts::{ add_canadian_business_days, build_shorts, epoch_days_to_ymd, et_to_utc_micros, CeoShortReport, ShortsError, ShortsStats, SHORTS_DISSEMINATION_HOUR_ET, SHORTS_DISSEMINATION_MINUTE_ET, @@ -77,14 +58,10 @@ pub const DEFAULT_BENCH_ROWS: usize = 10_000_000; pub const DEFAULT_ADJ_BENCH_EVENTS: usize = 1_000_000; pub const DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS: usize = 1_000_000; pub const DEFAULT_BARS_BENCH_ROWS: usize = 10_000_000; -pub const DEFAULT_BARS_1M_BENCH_ROWS: usize = 10_000_000; -pub const DEFAULT_ILP_BARS_1M_BENCH_ROWS: usize = DEFAULT_BARS_1M_BENCH_ROWS; -pub const ILP_BARS_1M_BENCH_SHARDS: usize = 4; pub const DEFAULT_FX_BENCH_ROWS: usize = 20_000; pub const DEFAULT_FX_BENCH_LOOKUPS: usize = 1_000_000; pub const DEFAULT_SHORTS_BENCH_ROWS: usize = 700_000; pub const DEFAULT_EVENTS_BENCH_ROWS: usize = 500_000; -pub const DEFAULT_FUNDAMENTALS_BENCH_ROWS: usize = 100_000; pub const DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS: usize = 10_000_000; pub const DEFAULT_PARQUET_BARS_BENCH_ROWS: usize = 5_000_000; pub const PARQUET_BARS_RAW_ROW_BYTES: usize = 84; @@ -102,9 +79,6 @@ pub const DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS: usize = 1_000_000; /// + `known_at` (8) + `known_at_source` (~13) = 72 bytes. pub const PARQUET_CORPORATE_ACTIONS_RAW_ROW_BYTES: usize = 72; pub const DEFAULT_BSON_EOD_PRICES_BENCH_ROWS: usize = 1_000_000; -pub const DEFAULT_BSON_QM_ACTIONS_BENCH_ROWS: usize = 1_000_000; -pub const DEFAULT_BSON_STREAM_BENCH_ROWS: usize = 2_000_000; -pub const DEFAULT_MONGO_STREAM_BENCH_ROWS: usize = 1_000_000; pub const BENCH_KEY_COUNT: usize = 20_000; pub const BENCH_EVENT_COUNT: usize = 19_000; pub const PROVIDER_MAPPING_BENCH_KEY_COUNT: usize = 60_000; @@ -120,16 +94,9 @@ const BENCH_SEED: u64 = 0x570C_4B07_5171_7E57; const ADJ_BENCH_SEED: u64 = 0x570C_4B07_AD7F_AC70; const CORPORATE_ACTIONS_BENCH_SEED: u64 = 0x570C_4B07_C049_AC71; const BARS_BENCH_SEED: u64 = 0x570C_4B07_BA45_1D00; -const BARS_1M_BENCH_SEED: u64 = 0x570C_4B07_BA45_0100; -const ILP_BARS_1M_BENCH_SEED: u64 = 0x570C_4B07_119B_A451; -const BARS_1M_BENCH_KEY_COUNT: usize = 2_000; -const BARS_1M_BENCH_EVENT_COUNT: usize = 2_000; const FX_BENCH_SEED: u64 = 0x570C_4B07_F81D_CADE; const SHORTS_BENCH_SEED: u64 = 0x570C_4B07_5404_7500; const EVENTS_BENCH_SEED: u64 = 0x570C_4B07_E7E4_7500; -const FUNDAMENTALS_BENCH_SEED: u64 = 0x570C_4B07_F04D_A001; -const FUNDAMENTALS_BENCH_TARGET_OBS_PER_KEY: usize = 40; -const FUNDAMENTALS_BENCH_SNAPSHOT_K: usize = 4; const PROVIDER_MAPPING_BENCH_SEED: u64 = 0x570C_4B07_9407_1D00; const PARQUET_BARS_BENCH_SEED: u64 = 0x570C_4B07_9A49_BA45; const PARQUET_SHORTS_BENCH_SEED: u64 = 0x570C_4B07_9A49_5404; @@ -137,7 +104,6 @@ const PARQUET_EVENTS_BENCH_SEED: u64 = 0x570C_4B07_9A49_E7E4; const PARQUET_FX_BENCH_SEED: u64 = 0x570C_4B07_9A49_F81D; const PARQUET_ADJ_BENCH_SEED: u64 = 0x570C_4B07_9A49_AD7F; const BSON_EOD_PRICES_BENCH_SEED: u64 = 0x570C_4B07_B504_E0D1; -const BSON_QM_ACTIONS_BENCH_SEED: u64 = 0x570C_4B07_B504_AC71; const PARQUET_CORPORATE_ACTIONS_BENCH_SEED: u64 = 0x570C_4B07_9A49_C049; const SAMPLE_RATIOS: [f64; 9] = [2.0, 3.0, 4.0, 5.0, 10.0, 0.5, 0.25, 0.1, 0.05]; @@ -711,578 +677,6 @@ pub fn run_bars_benchmark(rows: usize) -> Result { }) } -/// Summary metrics produced by [`run_bars_1m_benchmark`]. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct Bars1mBenchReport { - pub rows: usize, - pub key_count: usize, - pub split_event_count: usize, - pub daily_rows_in: usize, - pub rows_out: usize, - pub keys_out: usize, - pub mismatch_samples_out: usize, - pub build_elapsed_ms: f64, - pub check_elapsed_ms: f64, - pub total_elapsed_ms: f64, - pub rows_per_sec: f64, - pub ns_per_row: f64, - pub checksum: u64, - pub build_stats: Bars1mStats, - pub close_stats: SessionCloseStats, -} - -fn verify_bars_1m_bench_self_check() -> Result<(), Bars1mError> { - let nexm_ex = ymd_to_epoch_days(2025, 6, 18).unwrap_or(20_257); - let nvda_ex = ymd_to_epoch_days(2024, 6, 10).unwrap_or(19_884); - let splits = SplitTable::from_events([ - ( - "NEXM.V", - SplitEvent { - ex_date: nexm_ex, - ratio: 0.05, - }, - ), - ( - "NVDA.US", - SplitEvent { - ex_date: nvda_ex, - ratio: 10.0, - }, - ), - ]) - .expect("valid bench self-check splits"); - - let nexm_pre_ts = et_to_utc_micros(nexm_ex - 1, 15, 59, 0).expect("valid ET"); - let nexm_ex_ts = et_to_utc_micros(nexm_ex, 15, 59, 0).expect("valid ET"); - let nvda_pre_ts = et_to_utc_micros(nvda_ex - 3, 15, 59, 0).expect("valid ET"); - let nvda_ex_ts = et_to_utc_micros(nvda_ex, 15, 59, 0).expect("valid ET"); - let est_day = ymd_to_epoch_days(2025, 1, 15).expect("valid date"); - let est_pre_ts = et_to_utc_micros(est_day, 9, 29, 0).expect("valid ET"); - let est_rth_ts = et_to_utc_micros(est_day, 9, 30, 0).expect("valid ET"); - let est_post_ts = et_to_utc_micros(est_day, 16, 0, 0).expect("valid ET"); - - let built = build_bars_1m( - [ - EodIntradayBar { - key: "NEXM.V", - ts: nexm_pre_ts, - open: 24.0, - high: 24.5, - low: 23.9, - close: 24.29, - volume: 5_000.0, - }, - EodIntradayBar { - key: "NEXM.V", - ts: nexm_ex_ts, - open: 24.1, - high: 24.4, - low: 24.0, - close: 24.30, - volume: 10_000.0, - }, - EodIntradayBar { - key: "NVDA.US", - ts: nvda_pre_ts, - open: 120.5, - high: 121.0, - low: 120.4, - close: 120.888, - volume: 412_390.0, - }, - EodIntradayBar { - key: "NVDA.US", - ts: nvda_ex_ts, - open: 121.5, - high: 121.9, - low: 121.4, - close: 121.79, - volume: 300_000.0, - }, - EodIntradayBar { - key: "SESS", - ts: est_pre_ts, - open: 10.0, - high: 10.1, - low: 9.9, - close: 10.0, - volume: 100.0, - }, - EodIntradayBar { - key: "SESS", - ts: est_rth_ts, - open: 10.0, - high: 10.1, - low: 9.9, - close: 10.0, - volume: 100.0, - }, - EodIntradayBar { - key: "SESS", - ts: est_post_ts, - open: 10.0, - high: 10.1, - low: 9.9, - close: 10.0, - volume: 100.0, - }, - ], - &splits, - ); - - assert_eq!(built.rows.len(), 7, "self-check expected 7 bars"); - assert!( - (built.rows[0].close - 1.2145).abs() < 1e-9, - "NEXM.V pre-split self-check failed" - ); - assert_eq!(built.rows[1].close.to_bits(), 24.30_f64.to_bits()); - assert!( - (built.rows[2].close - 1_208.88).abs() < 1e-9, - "NVDA.US pre-split close self-check failed" - ); - assert!( - (built.rows[2].volume - 41_239.0).abs() < 1e-9, - "NVDA.US pre-split volume self-check failed" - ); - assert_eq!(built.rows[3].close.to_bits(), 121.79_f64.to_bits()); - assert_eq!(built.rows[4].session, IntradaySession::Pre); - assert_eq!(built.rows[5].session, IntradaySession::Rth); - assert_eq!(built.rows[6].session, IntradaySession::Post); - - let daily = [ - DailySessionClose::new("NEXM.V", nexm_ex - 1, 1.2145), - DailySessionClose::new("NEXM.V", nexm_ex, 24.30), - DailySessionClose::new("NVDA.US", nvda_ex - 3, 1_208.88), - DailySessionClose::new("NVDA.US", nvda_ex, 121.79), - ]; - let check = check_session_closes(&built.rows, daily, 0.005)?; - assert_eq!(check.stats.checked, 4, "self-check expected 4 checked sessions"); - assert_eq!(check.stats.mismatched, 0, "self-check expected 0 mismatches"); - Ok(()) -} - -/// Runs the fixed-seed `build_bars_1m` + `check_session_closes` benchmark for `rows` 1-minute bars. -/// -/// Executes a pre-timing correctness self-check (NEXM.V 1:20 reverse split, NVDA.US 10:1 forward -/// split, EST/EDT session tagging, and `check_session_closes`), then generates `rows` deterministic -/// multi-session EST/EDT 1m bars across `2_000` `i32` keys with forward/reverse splits, a small -/// share of invalid/inconsistent/out-of-range/duplicate bars, and one daily close reference per -/// sampled synthetic session derived from its expected last valid RTH minute (with deliberate -/// mismatches and duplicate conflicts injected separately). Times [`build_bars_1m`] and -/// [`check_session_closes`] and returns throughput plus a deterministic `u64` checksum. -pub fn run_bars_1m_benchmark(rows: usize) -> Result { - verify_bars_1m_bench_self_check()?; - - let min_date = ymd_to_epoch_days(2024, 1, 2).unwrap_or(19_724); - let max_date = ymd_to_epoch_days(2025, 12, 31).unwrap_or(20_453); - let date_span = (max_date - min_date + 1) as u64; - - let mut rng = SplitMix64::new(BARS_1M_BENCH_SEED); - - let mut split_events = Vec::with_capacity(BARS_1M_BENCH_EVENT_COUNT); - for _ in 0..BARS_1M_BENCH_EVENT_COUNT { - let key = (rng.next_u64() % (BARS_1M_BENCH_KEY_COUNT as u64)) as i32 + 1; - let ex_date = min_date + (rng.next_u64() % date_span) as i32; - let ratio = SAMPLE_RATIOS[(rng.next_u64() % (SAMPLE_RATIOS.len() as u64)) as usize]; - split_events.push((key, SplitEvent { ex_date, ratio })); - } - let splits = SplitTable::from_events(split_events).unwrap_or_default(); - let split_event_count = splits.event_count(); - - struct BenchRthCandidate { - key: i32, - session_date: i32, - ts: i64, - open: f64, - high: f64, - low: f64, - close: f64, - volume: f64, - } - - #[inline] - fn to_bench_rth_candidate(bar: &EodIntradayBar, session_date: i32) -> BenchRthCandidate { - BenchRthCandidate { - key: bar.key, - session_date, - ts: bar.ts, - open: bar.open, - high: bar.high, - low: bar.low, - close: bar.close, - volume: if bar.volume == 0.0 { 0.0 } else { bar.volume }, - } - } - - #[inline] - fn bench_rth_values_bit_eq(a: &BenchRthCandidate, b: &BenchRthCandidate) -> bool { - a.open.to_bits() == b.open.to_bits() - && a.high.to_bits() == b.high.to_bits() - && a.low.to_bits() == b.low.to_bits() - && a.close.to_bits() == b.close.to_bits() - && a.volume.to_bits() == b.volume.to_bits() - } - - let mut bars: Vec> = Vec::with_capacity(rows); - // Track every valid RTH candidate with all five normalized OHLCV fields (including exact and - // conflicting duplicates) so we match `build_bars_1m`'s duplicate-conflict drop rule when - // deriving each session's expected last surviving valid RTH bar before timing. - let mut valid_rth_candidates: Vec = Vec::with_capacity(rows / 2 + 64); - - let mut last_valid: Option<(EodIntradayBar, i32, bool)> = None; - for _ in 0..rows { - let roll = rng.next_u64() % 1_000; - if roll < 5 { - if let Some((prev, prev_date, prev_is_rth)) = last_valid.clone() { - if prev_is_rth { - valid_rth_candidates.push(to_bench_rth_candidate(&prev, prev_date)); - } - bars.push(prev); - continue; - } - } else if roll < 7 { - if let Some((mut prev, prev_date, prev_is_rth)) = last_valid.clone() { - let orig_close_bits = prev.close.to_bits(); - prev.close = (prev.close + 0.05).min(prev.high); - if prev.close.to_bits() == orig_close_bits { - prev.close = (prev.close - 0.05).max(prev.low); - } - if prev_is_rth { - valid_rth_candidates.push(to_bench_rth_candidate(&prev, prev_date)); - } - bars.push(prev); - continue; - } - } - - let key = (rng.next_u64() % (BARS_1M_BENCH_KEY_COUNT as u64)) as i32 + 1; - let session_date = min_date + (rng.next_u64() % date_span) as i32; - // 08:00..=19:59 ET (minutes 480..1200) -> spans PRE, RTH, and POST on both EST and EDT. - let et_minute = 480 + (rng.next_u64() % 720) as i64; - let is_rth = (570..960).contains(&et_minute); - let close_1600_utc = et_session_close_utc_micros(session_date).unwrap_or(0); - let ts = close_1600_utc + (et_minute - 960) * 60_000_000; - - let low = ((rng.next_u64() % 40_000) + 100) as f64 * 0.01; - let spread = ((rng.next_u64() % 300) + 5) as f64 * 0.01; - let high = low + spread; - let open = low + spread * ((rng.next_u64() % 100) as f64 * 0.01); - let close = low + spread * ((rng.next_u64() % 100) as f64 * 0.01); - let volume = ((rng.next_u64() % 500_000) + 10) as f64; - - let bar = match roll { - 7..=8 => EodIntradayBar { - key, - ts, - open: -1.0, - high, - low, - close, - volume, - }, - 9..=10 => EodIntradayBar { - key, - ts, - open, - high: low - 0.5, - low, - close, - volume, - }, - 11..=12 => EodIntradayBar { - key, - ts, - open, - high, - low, - close, - volume: -10.0, - }, - 13..=14 => EodIntradayBar { - key, - ts: SESSION_MIN_SUPPORTED_UTC_MICROS - 60_000_000, - open, - high, - low, - close, - volume, - }, - 15..=17 => { - let b = EodIntradayBar { - key, - ts, - open, - high, - low, - close, - volume: 0.0, - }; - if is_rth { - valid_rth_candidates.push(to_bench_rth_candidate(&b, session_date)); - } - last_valid = Some((b.clone(), session_date, is_rth)); - b - } - _ => { - let b = EodIntradayBar { - key, - ts, - open, - high, - low, - close, - volume, - }; - if is_rth { - valid_rth_candidates.push(to_bench_rth_candidate(&b, session_date)); - } - last_valid = Some((b.clone(), session_date, is_rth)); - b - } - }; - bars.push(bar); - } - - // Derive one daily reference close per sampled synthetic session from its expected last - // surviving valid RTH bar, then inject deliberate mismatches and conflicts separately. - valid_rth_candidates.sort_unstable_by(|a, b| { - a.key - .cmp(&b.key) - .then_with(|| a.session_date.cmp(&b.session_date)) - .then_with(|| a.ts.cmp(&b.ts)) - }); - - let mut daily_closes: Vec> = - Vec::with_capacity(valid_rth_candidates.len() / 4 + 64); - let mut idx = 0usize; - while idx < valid_rth_candidates.len() { - let key = valid_rth_candidates[idx].key; - let session_date = valid_rth_candidates[idx].session_date; - let mut session_end = idx + 1; - while session_end < valid_rth_candidates.len() - && valid_rth_candidates[session_end].key == key - && valid_rth_candidates[session_end].session_date == session_date - { - session_end += 1; - } - - // Find the last non-conflicted `(key, ts)` subgroup within this `(key, session_date)`. - let mut expected_last_close: Option = None; - let mut g = idx; - while g < session_end { - let ts = valid_rth_candidates[g].ts; - let mut g_end = g + 1; - while g_end < session_end && valid_rth_candidates[g_end].ts == ts { - g_end += 1; - } - let first = &valid_rth_candidates[g]; - let all_same = valid_rth_candidates[g + 1..g_end] - .iter() - .all(|c| bench_rth_values_bit_eq(first, c)); - if all_same { - expected_last_close = Some(first.close); - } - g = g_end; - } - idx = session_end; - - let Some(adj_close) = expected_last_close else { - continue; - }; - if (rng.next_u64() % 4) != 0 { - continue; - } - - let factor = splits.cum_factor_after(&key, session_date); - let raw_close = adj_close * factor; - let case_roll = rng.next_u64() % 200; - match case_roll { - 0..=1 => { - // Deliberate 5% mismatch (> 0.5% tolerance). - daily_closes.push(DailySessionClose::new(key, session_date, raw_close * 1.05)); - } - 2 => { - // Deliberate conflicting duplicate daily reference. - daily_closes.push(DailySessionClose::new(key, session_date, raw_close)); - daily_closes.push(DailySessionClose::new(key, session_date, raw_close * 1.03)); - } - 3 => { - // Deliberate identical duplicate daily reference. - daily_closes.push(DailySessionClose::new(key, session_date, raw_close)); - daily_closes.push(DailySessionClose::new(key, session_date, raw_close)); - } - _ => { - // Within-tolerance reference (-0.20%..+0.20%). - let jitter_bp = (rng.next_u64() % 41) as f64 - 20.0; - daily_closes.push(DailySessionClose::new( - key, - session_date, - raw_close * (1.0 + jitter_bp * 0.0001), - )); - } - } - } - drop(valid_rth_candidates); - - let daily_rows_in = daily_closes.len(); - - let build_start = Instant::now(); - let built = build_bars_1m(bars, &splits); - let build_elapsed_secs = build_start.elapsed().as_secs_f64(); - - let check_start = Instant::now(); - let checked = check_session_closes(&built.rows, daily_closes, 0.005)?; - let check_elapsed_secs = check_start.elapsed().as_secs_f64(); - - let total_elapsed_secs = build_elapsed_secs + check_elapsed_secs; - let build_elapsed_ms = build_elapsed_secs * 1_000.0; - let check_elapsed_ms = check_elapsed_secs * 1_000.0; - let total_elapsed_ms = total_elapsed_secs * 1_000.0; - - let mut hash = 0u64; - for row in &built.rows { - hash = mix_u64(hash, row.key as u64); - hash = mix_u64(hash, row.ts as u64); - hash = mix_u64(hash, row.session_date as u64); - hash = mix_u64(hash, row.session as u64); - hash = mix_u64(hash, row.open.to_bits()); - hash = mix_u64(hash, row.high.to_bits()); - hash = mix_u64(hash, row.low.to_bits()); - hash = mix_u64(hash, row.close.to_bits()); - hash = mix_u64(hash, row.volume.to_bits()); - } - for sample in &checked.mismatch_samples { - hash = mix_u64(hash, sample.key as u64); - hash = mix_u64(hash, sample.session_date as u64); - hash = mix_u64(hash, sample.last_rth_ts as u64); - hash = mix_u64(hash, sample.close_1m.to_bits()); - hash = mix_u64(hash, sample.close_1d.to_bits()); - hash = mix_u64(hash, sample.rel.to_bits()); - } - let checksum = black_box(hash); - let (rows_per_sec, ns_per_row) = compute_rates(rows, total_elapsed_secs); - - Ok(Bars1mBenchReport { - rows, - key_count: BARS_1M_BENCH_KEY_COUNT, - split_event_count, - daily_rows_in, - rows_out: built.stats.rows_out, - keys_out: built.stats.keys_out, - mismatch_samples_out: checked.mismatch_samples.len(), - build_elapsed_ms, - check_elapsed_ms, - total_elapsed_ms, - rows_per_sec, - ns_per_row, - checksum, - build_stats: built.stats, - close_stats: checked.stats, - }) -} - -/// Summary metrics produced by [`run_ilp_bars_1m_benchmark`]. -#[derive(Debug, Clone, PartialEq)] -pub struct IlpBars1mBenchReport { - pub rows: usize, - pub rows_encoded: usize, - pub key_count: usize, - pub shards: usize, - pub bytes: usize, - pub flushes: usize, - pub elapsed_ms: f64, - pub rows_per_sec: f64, - pub ns_per_row: f64, - pub bytes_per_row: f64, - pub mb_per_sec: f64, - pub per_shard_rows: Vec, -} - -/// Runs the fixed-seed QuestDB ILP v2 `bars_1m` encoding + sharded batching benchmark for `rows` -/// curated 1-minute equity bars across four `std::io::sink()` shards. -/// -/// Generates `rows` deterministic curated [`Bar1mRow`] records and `known_at` timestamps -/// across `2_000` `i32` listing IDs spanning `2024-01-02..=2025-12-31` (`PRE`/`RTH`/`POST`), then -/// times encoding and batching through [`IlpShardedWriter`] including [`IlpShardedWriter::finish`]. -pub fn run_ilp_bars_1m_benchmark(rows: usize) -> Result { - let min_date = ymd_to_epoch_days(2024, 1, 2).unwrap_or(19_724); - let max_date = ymd_to_epoch_days(2025, 12, 31).unwrap_or(20_453); - let date_span = (max_date - min_date + 1) as u64; - - let mut rng = SplitMix64::new(ILP_BARS_1M_BENCH_SEED); - let mut input_rows: Vec<(Bar1mRow, i64)> = Vec::with_capacity(rows); - - for _ in 0..rows { - let key = (rng.next_u64() % (BARS_1M_BENCH_KEY_COUNT as u64)) as i32 + 1; - let session_date = min_date + (rng.next_u64() % date_span) as i32; - let et_minute = (480 + (rng.next_u64() % 720)) as u16; - let close_1600_utc = et_session_close_utc_micros(session_date).unwrap_or(0); - let ts = close_1600_utc + (i64::from(et_minute) - 960) * 60_000_000; - let known_at = ts + 60_000_000; - - let low = ((rng.next_u64() % 40_000) + 100) as f64 * 0.01; - let spread = ((rng.next_u64() % 300) + 5) as f64 * 0.01; - let high = low + spread; - let open = low + spread * ((rng.next_u64() % 100) as f64 * 0.01); - let close = low + spread * ((rng.next_u64() % 100) as f64 * 0.01); - let volume = ((rng.next_u64() % 500_000) + 10) as f64; - - input_rows.push(( - Bar1mRow { - key, - ts, - session_date, - open, - high, - low, - close, - volume, - session: IntradaySession::from_et_minute(et_minute), - source: BARS_1M_SOURCE_EOD, - }, - known_at, - )); - } - - let sinks: Vec = (0..ILP_BARS_1M_BENCH_SHARDS).map(|_| io::sink()).collect(); - let mut writer = IlpShardedWriter::new(sinks, IlpWriterOptions::default())?; - - let start = Instant::now(); - for (row, known_at) in &input_rows { - writer.write_bar_1m(row, *known_at)?; - } - let stats = black_box(writer.finish()?); - let elapsed_secs = start.elapsed().as_secs_f64(); - let elapsed_ms = elapsed_secs * 1_000.0; - - let (rows_per_sec, ns_per_row) = compute_rates(stats.rows, elapsed_secs); - let bytes_per_row = if stats.rows == 0 { - 0.0 - } else { - stats.bytes as f64 / stats.rows as f64 - }; - let mb_per_sec = if elapsed_secs <= 0.0 || !elapsed_secs.is_finite() { - 0.0 - } else { - (stats.bytes as f64 / 1_000_000.0) / elapsed_secs - }; - - Ok(IlpBars1mBenchReport { - rows, - rows_encoded: stats.rows, - key_count: BARS_1M_BENCH_KEY_COUNT, - shards: ILP_BARS_1M_BENCH_SHARDS, - bytes: stats.bytes, - flushes: stats.flushes, - elapsed_ms, - rows_per_sec, - ns_per_row, - bytes_per_row, - mb_per_sec, - per_shard_rows: stats.per_shard_rows, - }) -} - /// Summary metrics produced by [`run_fx_benchmark`]. #[derive(Debug, Clone, Copy, PartialEq)] pub struct FxBenchReport { @@ -3750,13 +3144,6 @@ fn verify_parquet_adj_row_count( if expected_rows == 0 { return Ok(0); } - verify_parquet_adj_snapshot_row_count(out_dir, expected_rows) -} - -fn verify_parquet_adj_snapshot_row_count( - out_dir: &Path, - expected_rows: usize, -) -> Result { let path = out_dir.join("adj_factors/part.parquet"); let file = File::open(&path).map_err(|source| ParquetAdjError::Io { path: path.clone(), @@ -4228,7 +3615,28 @@ pub struct BsonEodPricesBenchReport { pub stats: BsonEodDecodeStats, } -fn build_bson_eod_prices_bench_buffer(rows: usize) -> Vec { +/// Runs the fixed-seed raw BSON `eodPrices` zero-copy decode benchmark for `rows` synthetic +/// documents. +/// +/// Pre-encodes `rows` realistic `eodPrices` documents (including extra metadata fields `_id`, +/// `symbol`, `exchange`, `providerExchange`, `source`, `adjustedClose`, `created_at`, +/// `updated_at`, mixed `Double`/`Int32`/`Int64` numerics, `YYYY-MM-DD` strings + ~5% BSON +/// `DateTime` dates, and ~0.5% deterministic rejected rows) into one contiguous length-prefixed +/// `Vec` buffer up front, then times decode-only via [`decode_eod_price_buffer`]. +pub fn run_bson_eod_prices_benchmark(rows: usize) -> BsonEodPricesBenchReport { + if rows == 0 { + return BsonEodPricesBenchReport { + rows: 0, + bytes: 0, + elapsed_ms: 0.0, + rows_per_sec: 0.0, + mb_per_sec: 0.0, + ns_per_row: 0.0, + checksum: 0, + stats: BsonEodDecodeStats::default(), + }; + } + const SYMBOL_POOL: usize = 2_000; const EXCHANGES: [&str; 4] = ["NASDAQ", "NYSE", "TSX", "TSXV"]; const PROVIDER_EXCHANGES: [&str; 4] = ["US", "US", "TO", "V"]; @@ -4342,33 +3750,6 @@ fn build_bson_eod_prices_bench_buffer(rows: usize) -> Vec { buffer.extend_from_slice(doc.as_bytes()); } - buffer -} - -/// Runs the fixed-seed raw BSON `eodPrices` zero-copy decode benchmark for `rows` synthetic -/// documents. -/// -/// Pre-encodes `rows` realistic `eodPrices` documents (including extra metadata fields `_id`, -/// `symbol`, `exchange`, `providerExchange`, `source`, `adjustedClose`, `created_at`, -/// `updated_at`, mixed `Double`/`Int32`/`Int64` numerics, `YYYY-MM-DD` strings + ~5% BSON -/// `DateTime` dates, and ~0.5% deterministic rejected rows) into one contiguous length-prefixed -/// `Vec` buffer up front, then times decode-only via [`decode_eod_price_buffer`]. -pub fn run_bson_eod_prices_benchmark(rows: usize) -> BsonEodPricesBenchReport { - if rows == 0 { - return BsonEodPricesBenchReport { - rows: 0, - bytes: 0, - elapsed_ms: 0.0, - rows_per_sec: 0.0, - mb_per_sec: 0.0, - ns_per_row: 0.0, - checksum: 0, - stats: BsonEodDecodeStats::default(), - }; - } - - let buffer = build_bson_eod_prices_bench_buffer(rows); - let bytes = buffer.len(); let mut hash = 0u64; let mut err_hash = 0u64; @@ -4411,600 +3792,6 @@ pub fn run_bson_eod_prices_benchmark(rows: usize) -> BsonEodPricesBenchReport { } } -/// Summary metrics produced by [`run_bson_stream_benchmark`]. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct BsonStreamBenchReport { - pub rows: usize, - pub bytes: usize, - pub buffer_elapsed_ms: f64, - pub buffer_rows_per_sec: f64, - pub buffer_mib_per_sec: f64, - pub stream_elapsed_ms: f64, - pub stream_rows_per_sec: f64, - pub stream_mib_per_sec: f64, - pub stream_to_buffer_ratio: f64, - pub peak_buffer_capacity: usize, - pub checksum: u64, - pub stats: BsonEodDecodeStats, -} - -/// Deterministic reader returning irregular prime/odd short reads across ~257 B..128 KiB so every -/// read straddles BSON document and 4-byte length-prefix boundaries. -struct IrregularShortReader<'a> { - data: &'a [u8], - pos: usize, - step_idx: usize, -} - -impl<'a> IrregularShortReader<'a> { - const STEPS: [usize; 10] = [ - 257, 1_021, 4_093, 16_381, 65_521, 131_071, 521, 8_191, 32_749, 49_157, - ]; - - fn new(data: &'a [u8]) -> Self { - Self { - data, - pos: 0, - step_idx: 0, - } - } -} - -impl io::Read for IrregularShortReader<'_> { - fn read(&mut self, buf: &mut [u8]) -> io::Result { - let remaining = self.data.len() - self.pos; - if remaining == 0 { - return Ok(0); - } - let step = Self::STEPS[self.step_idx % Self::STEPS.len()]; - self.step_idx = self.step_idx.wrapping_add(1); - let take = remaining.min(step).min(buf.len()); - buf[..take].copy_from_slice(&self.data[self.pos..self.pos + take]); - self.pos += take; - Ok(take) - } -} - -/// Runs the fixed-seed raw BSON streaming vs in-memory buffer decode benchmark for `rows` -/// synthetic `eodPrices` documents. -/// -/// Reuses the identical fixed-seed synthetic buffer from [`run_bson_eod_prices_benchmark`], decodes -/// once via [`decode_eod_price_buffer`] (baseline) and once via [`RawBsonChunkReader`] + -/// [`decode_eod_price_chunks`] over irregular short reads, asserts identical stats and row+error -/// checksum, and reports throughput and peak buffer capacity. -pub fn run_bson_stream_benchmark(rows: usize) -> Result { - if rows == 0 { - return Ok(BsonStreamBenchReport { - rows: 0, - bytes: 0, - buffer_elapsed_ms: 0.0, - buffer_rows_per_sec: 0.0, - buffer_mib_per_sec: 0.0, - stream_elapsed_ms: 0.0, - stream_rows_per_sec: 0.0, - stream_mib_per_sec: 0.0, - stream_to_buffer_ratio: 0.0, - peak_buffer_capacity: 0, - checksum: 0, - stats: BsonEodDecodeStats::default(), - }); - } - - let buffer = build_bson_eod_prices_bench_buffer(rows); - let bytes = buffer.len(); - - // Baseline: in-memory buffer decode. - let mut buf_hash = 0u64; - let mut buf_err_hash = 0u64; - let buf_start = Instant::now(); - let buf_stats = decode_eod_price_buffer( - &buffer, - |bar| { - buf_hash = mix_bytes(buf_hash, bar.eod_search_code.as_bytes()); - buf_hash = mix_u64(buf_hash, bar.session_date as u64); - buf_hash = mix_u64(buf_hash, bar.open.to_bits()); - buf_hash = mix_u64(buf_hash, bar.high.to_bits()); - buf_hash = mix_u64(buf_hash, bar.low.to_bits()); - buf_hash = mix_u64(buf_hash, bar.close.to_bits()); - buf_hash = mix_u64(buf_hash, bar.adj_volume.to_bits()); - }, - |offset, _err| { - buf_err_hash = mix_u64(buf_err_hash, offset as u64 ^ 0xDEAD_BEEF_CAFE_BABEu64); - }, - ); - let buf_elapsed_secs = buf_start.elapsed().as_secs_f64(); - let buf_checksum = black_box(buf_hash ^ buf_err_hash); - - // Streamed decode over irregular short reads using default bounded chunk capacity. - let mut chunk_reader = RawBsonChunkReader::with_options( - IrregularShortReader::new(&buffer), - BsonStreamOptions::default(), - )?; - let mut stream_hash = 0u64; - let mut stream_err_hash = 0u64; - let stream_start = Instant::now(); - let stream_stats = decode_eod_price_chunks( - &mut chunk_reader, - |bar| { - stream_hash = mix_bytes(stream_hash, bar.eod_search_code.as_bytes()); - stream_hash = mix_u64(stream_hash, bar.session_date as u64); - stream_hash = mix_u64(stream_hash, bar.open.to_bits()); - stream_hash = mix_u64(stream_hash, bar.high.to_bits()); - stream_hash = mix_u64(stream_hash, bar.low.to_bits()); - stream_hash = mix_u64(stream_hash, bar.close.to_bits()); - stream_hash = mix_u64(stream_hash, bar.adj_volume.to_bits()); - }, - |offset, _err| { - stream_err_hash = mix_u64(stream_err_hash, offset ^ 0xDEAD_BEEF_CAFE_BABEu64); - }, - )?; - let stream_elapsed_secs = stream_start.elapsed().as_secs_f64(); - let stream_checksum = black_box(stream_hash ^ stream_err_hash); - let peak_buffer_capacity = chunk_reader.buffer_capacity(); - - assert_eq!( - stream_stats, buf_stats, - "stream decode stats must match in-memory buffer decode" - ); - assert_eq!( - stream_checksum, buf_checksum, - "stream decode checksum must match in-memory buffer decode" - ); - - let buffer_elapsed_ms = buf_elapsed_secs * 1_000.0; - let (buffer_rows_per_sec, _) = compute_rates(rows, buf_elapsed_secs); - let buffer_mib_per_sec = if buf_elapsed_secs > 0.0 && buf_elapsed_secs.is_finite() { - (bytes as f64 / (1024.0 * 1024.0)) / buf_elapsed_secs - } else { - 0.0 - }; - - let stream_elapsed_ms = stream_elapsed_secs * 1_000.0; - let (stream_rows_per_sec, _) = compute_rates(rows, stream_elapsed_secs); - let stream_mib_per_sec = if stream_elapsed_secs > 0.0 && stream_elapsed_secs.is_finite() { - (bytes as f64 / (1024.0 * 1024.0)) / stream_elapsed_secs - } else { - 0.0 - }; - - let stream_to_buffer_ratio = if buffer_rows_per_sec > 0.0 { - stream_rows_per_sec / buffer_rows_per_sec - } else { - 0.0 - }; - - Ok(BsonStreamBenchReport { - rows, - bytes, - buffer_elapsed_ms, - buffer_rows_per_sec, - buffer_mib_per_sec, - stream_elapsed_ms, - stream_rows_per_sec, - stream_mib_per_sec, - stream_to_buffer_ratio, - peak_buffer_capacity, - checksum: stream_checksum, - stats: stream_stats, - }) -} - -/// Summary metrics produced by [`run_mongo_stream_benchmark`]. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct MongoStreamBenchReport { - pub rows: usize, - pub bytes: usize, - pub plain_elapsed_ms: f64, - pub plain_docs_per_sec: f64, - pub plain_mib_per_sec: f64, - pub cursor_elapsed_ms: f64, - pub cursor_docs_per_sec: f64, - pub cursor_mib_per_sec: f64, - pub cursor_to_plain_ratio: f64, - pub peak_pending_capacity: usize, - pub checksum: u64, - pub stats: BsonEodDecodeStats, -} - -/// Runs the offline fixed-seed `RawBsonCursorReader` vs plain in-memory `io::Cursor<&[u8]>` -/// decode benchmark for `rows` synthetic `eodPrices` documents. -pub fn run_mongo_stream_benchmark(rows: usize) -> Result { - if rows == 0 { - return Ok(MongoStreamBenchReport { - rows: 0, - bytes: 0, - plain_elapsed_ms: 0.0, - plain_docs_per_sec: 0.0, - plain_mib_per_sec: 0.0, - cursor_elapsed_ms: 0.0, - cursor_docs_per_sec: 0.0, - cursor_mib_per_sec: 0.0, - cursor_to_plain_ratio: 0.0, - peak_pending_capacity: 0, - checksum: 0, - stats: BsonEodDecodeStats::default(), - }); - } - - let buffer = build_bson_eod_prices_bench_buffer(rows); - let bytes = buffer.len(); - - let mut doc_slices: Vec<&[u8]> = Vec::with_capacity(rows); - for doc_res in iter_raw_bson_docs(&buffer) { - let raw_doc = doc_res.expect("synthetic benchmark buffer must have valid BSON frames"); - doc_slices.push(raw_doc.as_bytes()); - } - assert_eq!(doc_slices.len(), rows); - - // Baseline: plain in-memory io::Cursor<&[u8]> -> decode_eod_price_stream. - let mut plain_hash = 0u64; - let mut plain_err_hash = 0u64; - let plain_start = Instant::now(); - let plain_stats = decode_eod_price_stream( - io::Cursor::new(buffer.as_slice()), - BsonStreamOptions::default(), - |bar| { - plain_hash = mix_bytes(plain_hash, bar.eod_search_code.as_bytes()); - plain_hash = mix_u64(plain_hash, bar.session_date as u64); - plain_hash = mix_u64(plain_hash, bar.open.to_bits()); - plain_hash = mix_u64(plain_hash, bar.high.to_bits()); - plain_hash = mix_u64(plain_hash, bar.low.to_bits()); - plain_hash = mix_u64(plain_hash, bar.close.to_bits()); - plain_hash = mix_u64(plain_hash, bar.adj_volume.to_bits()); - }, - |offset, _err| { - plain_err_hash = mix_u64(plain_err_hash, offset ^ 0xDEAD_BEEF_CAFE_BABEu64); - }, - )?; - let plain_elapsed_secs = plain_start.elapsed().as_secs_f64(); - let plain_checksum = black_box(plain_hash ^ plain_err_hash); - - // Candidate: in-memory RawDocumentSource -> RawBsonCursorReader -> decode_eod_price_stream. - let mut cursor_reader = RawBsonCursorReader::new(SliceRawDocumentSource::new(&doc_slices)); - let mut cursor_hash = 0u64; - let mut cursor_err_hash = 0u64; - let cursor_start = Instant::now(); - let cursor_stats = decode_eod_price_stream( - &mut cursor_reader, - BsonStreamOptions::default(), - |bar| { - cursor_hash = mix_bytes(cursor_hash, bar.eod_search_code.as_bytes()); - cursor_hash = mix_u64(cursor_hash, bar.session_date as u64); - cursor_hash = mix_u64(cursor_hash, bar.open.to_bits()); - cursor_hash = mix_u64(cursor_hash, bar.high.to_bits()); - cursor_hash = mix_u64(cursor_hash, bar.low.to_bits()); - cursor_hash = mix_u64(cursor_hash, bar.close.to_bits()); - cursor_hash = mix_u64(cursor_hash, bar.adj_volume.to_bits()); - }, - |offset, _err| { - cursor_err_hash = mix_u64(cursor_err_hash, offset ^ 0xDEAD_BEEF_CAFE_BABEu64); - }, - )?; - let cursor_elapsed_secs = cursor_start.elapsed().as_secs_f64(); - let cursor_checksum = black_box(cursor_hash ^ cursor_err_hash); - let peak_pending_capacity = cursor_reader.pending_capacity(); - - assert_eq!( - cursor_stats, plain_stats, - "cursor reader decode stats must match plain in-memory reader" - ); - assert_eq!( - cursor_checksum, plain_checksum, - "cursor reader decode checksum must match plain in-memory reader" - ); - assert_eq!(cursor_reader.docs_read(), rows as u64); - assert_eq!(cursor_reader.bytes_read(), bytes as u64); - - let plain_elapsed_ms = plain_elapsed_secs * 1_000.0; - let (plain_docs_per_sec, _) = compute_rates(rows, plain_elapsed_secs); - let plain_mib_per_sec = if plain_elapsed_secs > 0.0 && plain_elapsed_secs.is_finite() { - (bytes as f64 / (1024.0 * 1024.0)) / plain_elapsed_secs - } else { - 0.0 - }; - - let cursor_elapsed_ms = cursor_elapsed_secs * 1_000.0; - let (cursor_docs_per_sec, _) = compute_rates(rows, cursor_elapsed_secs); - let cursor_mib_per_sec = if cursor_elapsed_secs > 0.0 && cursor_elapsed_secs.is_finite() { - (bytes as f64 / (1024.0 * 1024.0)) / cursor_elapsed_secs - } else { - 0.0 - }; - - let cursor_to_plain_ratio = if plain_docs_per_sec > 0.0 { - cursor_docs_per_sec / plain_docs_per_sec - } else { - 0.0 - }; - - Ok(MongoStreamBenchReport { - rows, - bytes, - plain_elapsed_ms, - plain_docs_per_sec, - plain_mib_per_sec, - cursor_elapsed_ms, - cursor_docs_per_sec, - cursor_mib_per_sec, - cursor_to_plain_ratio, - peak_pending_capacity, - checksum: cursor_checksum, - stats: cursor_stats, - }) -} - -/// Summary metrics produced by [`run_bson_qm_actions_benchmark`]. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct BsonQmActionsBenchReport { - pub rows: usize, - pub split_rows: usize, - pub dividend_rows: usize, - pub bytes: usize, - pub elapsed_ms: f64, - pub docs_per_sec: f64, - pub mb_per_sec: f64, - pub ns_per_doc: f64, - pub checksum: u64, - pub split_stats: BsonQmActionDecodeStats, - pub dividend_stats: BsonQmActionDecodeStats, -} - -/// Runs the fixed-seed raw BSON `qmSplits` + `qmDividends` zero-copy decode benchmark for `rows` -/// synthetic documents (~4% splits, ~96% dividends). -/// -/// Pre-encodes realistic QuoteMedia documents (including extra metadata `_id`, `symbol`, -/// `exchange`, `reportDate`, `created_at`, `updated_at`, bogus `usdFxRate: 1`, `declared` -/// present/missing/`Null`, ~5% BSON `DateTime` dates, mixed `Double`/`Int32`/`Int64` numerics, -/// ~1.5% `splitratio == 1` no-ops, and ~0.5% deterministic rejected rows) into two contiguous -/// length-prefixed buffers, then times decode-only via [`decode_qm_split_buffer`] and -/// [`decode_qm_dividend_buffer`] and asserts exact stats reconciliation. -pub fn run_bson_qm_actions_benchmark(rows: usize) -> BsonQmActionsBenchReport { - if rows == 0 { - return BsonQmActionsBenchReport { - rows: 0, - split_rows: 0, - dividend_rows: 0, - bytes: 0, - elapsed_ms: 0.0, - docs_per_sec: 0.0, - mb_per_sec: 0.0, - ns_per_doc: 0.0, - checksum: 0, - split_stats: BsonQmActionDecodeStats::default(), - dividend_stats: BsonQmActionDecodeStats::default(), - }; - } - - const SYMBOL_POOL: usize = 2_000; - const EXCHANGES: [&str; 4] = ["NASDAQ", "NYSE", "TSX", "TSXV"]; - const CURRENCIES: [&str; 4] = ["USD", "USD", "CAD", "CAD"]; - const MILLIS_PER_DAY: i64 = 86_400_000; - - let min_date = ymd_to_epoch_days(2005, 1, 3).unwrap_or(12_786); - let max_date = ymd_to_epoch_days(2025, 12, 31).unwrap_or(20_453); - let mut date_days: Vec = Vec::with_capacity(5_600); - let mut date_strings: Vec = Vec::with_capacity(5_600); - for d in min_date..=max_date { - let dow = (d + 4).rem_euclid(7); - if dow == 0 || dow == 6 { - continue; - } - let (y, m, day) = epoch_days_to_ymd(d); - date_days.push(d); - date_strings.push(format!("{y:04}-{m:02}-{day:02}")); - } - - let symbols: Vec<(String, String, &'static str, &'static str)> = (0..SYMBOL_POOL) - .map(|i| { - let ex_idx = i % EXCHANGES.len(); - let sym = format!("QM{i:04}"); - let code = if ex_idx >= 2 { - format!("{sym}:CA") - } else { - sym.clone() - }; - (sym, code, EXCHANGES[ex_idx], CURRENCIES[ex_idx]) - }) - .collect(); - - let mut rng = SplitMix64::new(BSON_QM_ACTIONS_BENCH_SEED); - let mut split_rows = 0usize; - let mut dividend_rows = 0usize; - let mut split_buf: Vec = Vec::with_capacity((rows / 20).saturating_mul(224)); - let mut dividend_buf: Vec = Vec::with_capacity(rows.saturating_mul(256)); - - for i in 0..rows { - let is_split = (rng.next_u64() % 100) < 4; - let sym_idx = (rng.next_u64() as usize) % symbols.len(); - let (ref symbol, ref code, exchange, currency) = symbols[sym_idx]; - let date_idx = (rng.next_u64() as usize) % date_days.len(); - let epoch_day = date_days[date_idx]; - let date_str = &date_strings[date_idx]; - let decl_idx = date_idx.saturating_sub(15); - let decl_day = date_days[decl_idx]; - let decl_str = &date_strings[decl_idx]; - - let mut oid_bytes = [0u8; 12]; - let seq = (i as u64).to_be_bytes(); - oid_bytes[4..12].copy_from_slice(&seq); - - let report_ms = i64::from(epoch_day) * MILLIS_PER_DAY; - let created_ms = report_ms + 79_200_000; - let updated_ms = created_ms + 60_000; - - let bad_roll = rng.next_u64() % 1_000; - let date_as_dt = (rng.next_u64() % 20) == 0; - let decl_roll = rng.next_u64() % 1_000; - - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("_id"), ObjectId::from_bytes(oid_bytes)); - doc.append(cstr!("symbol"), symbol.as_str()); - doc.append(cstr!("exchange"), exchange); - doc.append(cstr!("qmSearchCode"), code.as_str()); - doc.append(cstr!("reportDate"), DateTime::from_millis(report_ms)); - - if bad_roll == 0 { - doc.append(cstr!("date"), "2023-02-29"); - } else if date_as_dt { - doc.append(cstr!("date"), DateTime::from_millis(report_ms)); - } else { - doc.append(cstr!("date"), date_str.as_str()); - } - - if is_split { - split_rows += 1; - // ~30% declared present, ~20% Null, ~50% missing. - if decl_roll < 300 { - if date_as_dt { - doc.append( - cstr!("declared"), - DateTime::from_millis(i64::from(decl_day) * MILLIS_PER_DAY), - ); - } else { - doc.append(cstr!("declared"), decl_str.as_str()); - } - } else if decl_roll < 500 { - doc.append(cstr!("declared"), RawBsonRef::Null); - } - - if bad_roll == 1 { - doc.append(cstr!("splitratio"), "2.0"); - } else if bad_roll == 2 { - doc.append(cstr!("splitratio"), 0.0_f64); - } else if bad_roll != 3 && bad_roll != 4 { - if (rng.next_u64() % 1_000) < 15 { - match i % 3 { - 0 => doc.append(cstr!("splitratio"), 1.0_f64), - 1 => doc.append(cstr!("splitratio"), 1_i32), - _ => doc.append(cstr!("splitratio"), 1_i64), - } - } else { - let ratio = SAMPLE_RATIOS[(rng.next_u64() as usize) % SAMPLE_RATIOS.len()]; - if i % 5 == 0 && ratio >= 1.0 { - doc.append(cstr!("splitratio"), ratio as i32); - } else if i % 7 == 0 && ratio >= 1.0 { - doc.append(cstr!("splitratio"), ratio as i64); - } else { - doc.append(cstr!("splitratio"), ratio); - } - } - } - - doc.append(cstr!("usdFxRate"), 1_i32); - doc.append(cstr!("created_at"), DateTime::from_millis(created_ms)); - doc.append(cstr!("updated_at"), DateTime::from_millis(updated_ms)); - split_buf.extend_from_slice(doc.as_bytes()); - } else { - dividend_rows += 1; - // ~82% declared present, ~9% Null, ~9% missing. - if decl_roll < 820 { - if date_as_dt { - doc.append( - cstr!("declared"), - DateTime::from_millis(i64::from(decl_day) * MILLIS_PER_DAY), - ); - } else { - doc.append(cstr!("declared"), decl_str.as_str()); - } - } else if decl_roll < 910 { - doc.append(cstr!("declared"), RawBsonRef::Null); - } - - let cents = (rng.next_u64() % 400) as i64; - if bad_roll == 1 { - doc.append(cstr!("amount"), "0.25"); - } else if bad_roll == 2 { - doc.append(cstr!("amount"), -0.25_f64); - } else if bad_roll != 3 { - match i % 10 { - 0 => doc.append(cstr!("amount"), (cents / 100) as i32), - 1 => doc.append(cstr!("amount"), cents / 100), - _ => doc.append(cstr!("amount"), cents as f64 / 100.0), - } - } - - if bad_roll != 4 { - doc.append(cstr!("currency"), currency); - } - doc.append(cstr!("usdFxRate"), 1_i32); - doc.append(cstr!("created_at"), DateTime::from_millis(created_ms)); - doc.append(cstr!("updated_at"), DateTime::from_millis(updated_ms)); - dividend_buf.extend_from_slice(doc.as_bytes()); - } - } - - let bytes = split_buf.len() + dividend_buf.len(); - let mut hash = 0u64; - let mut err_hash = 0u64; - - let start = Instant::now(); - let split_stats = decode_qm_split_buffer( - &split_buf, - |s| { - hash = mix_bytes(hash, s.qm_search_code.as_bytes()); - hash = mix_u64(hash, s.ex_date as u64); - hash = mix_u64(hash, s.ratio.to_bits()); - hash = mix_u64(hash, s.declared_date.unwrap_or(i32::MIN) as u64); - }, - |offset, _err| { - err_hash = mix_u64(err_hash, offset as u64 ^ 0x5171_DEAD_BEEF_0001u64); - }, - ); - let dividend_stats = decode_qm_dividend_buffer( - ÷nd_buf, - |d| { - hash = mix_bytes(hash, d.qm_search_code.as_bytes()); - hash = mix_u64(hash, d.ex_date as u64); - hash = mix_u64(hash, d.cash.to_bits()); - hash = mix_bytes(hash, d.currency.as_bytes()); - hash = mix_u64(hash, d.declared_date.unwrap_or(i32::MIN) as u64); - }, - |offset, _err| { - err_hash = mix_u64(err_hash, offset as u64 ^ 0xD171_DEAD_BEEF_0002u64); - }, - ); - let elapsed_secs = start.elapsed().as_secs_f64(); - - assert_eq!( - split_stats.decoded + split_stats.rejected_total(), - split_stats.docs_in, - "qmSplits decode stats must reconcile" - ); - assert_eq!( - dividend_stats.decoded + dividend_stats.rejected_total(), - dividend_stats.docs_in, - "qmDividends decode stats must reconcile" - ); - assert_eq!( - split_stats.docs_in + dividend_stats.docs_in, - rows, - "total decoded+rejected docs must equal input rows" - ); - - let elapsed_ms = elapsed_secs * 1_000.0; - let (docs_per_sec, ns_per_doc) = compute_rates(rows, elapsed_secs); - let mb_per_sec = if elapsed_secs > 0.0 && elapsed_secs.is_finite() { - (bytes as f64 / (1024.0 * 1024.0)) / elapsed_secs - } else { - 0.0 - }; - let checksum = black_box(hash ^ err_hash); - - BsonQmActionsBenchReport { - rows, - split_rows, - dividend_rows, - bytes, - elapsed_ms, - docs_per_sec, - mb_per_sec, - ns_per_doc, - checksum, - split_stats, - dividend_stats, - } -} - pub const DEFAULT_CURATE_BARS_BENCH_ROWS: usize = 2_000_000; pub const EOD_PRICES_FULL_ROW_COUNT: f64 = 846_000_000.0; const CURATE_BARS_BENCH_SEED: u64 = 0x570C_4B07_C04A_BA45; @@ -5640,824 +4427,6 @@ pub fn run_curate_bars_benchmark(rows: usize) -> Result) -> std::fmt::Result { - match self { - Self::FixtureIo { path, source } => { - write!(f, "fixture I/O error at '{}': {source}", path.display()) - } - Self::Run(err) => write!(f, "{err}"), - Self::Verify(err) => write!(f, "parquet verify failed: {err}"), - } - } -} - -impl std::error::Error for CurateBarsCmdBenchError { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - match self { - Self::FixtureIo { source, .. } => Some(source), - Self::Run(err) => Some(err), - Self::Verify(err) => Some(err), - } - } -} - -/// Metrics returned by [`run_curate_bars_cmd_benchmark`]. -#[derive(Debug, Clone, PartialEq)] -pub struct CurateBarsCmdBenchReport { - pub rows: usize, - pub key_count: usize, - pub eod_docs_framed: u64, - pub eod_bytes_read: u64, - pub splits_docs_framed: u64, - pub splits_bytes_read: u64, - pub qm_docs_framed: u64, - pub qm_bytes_read: u64, - pub bars_unmapped_source_dropped: usize, - pub buffered_bars: usize, - pub buffered_bar_bytes: usize, - pub bytes_per_buffered_bar: f64, - pub rows_out: usize, - pub listings_out: usize, - pub files_written: usize, - pub row_groups_written: usize, - pub bytes_written: u64, - pub parallel_threads: usize, - pub read_back_rows_seq: usize, - pub read_back_rows: usize, - pub decode_elapsed_ms: f64, - pub decode_rows_per_sec: f64, - pub input_mb_per_sec: f64, - pub qm_decode_rekey_elapsed_ms: f64, - pub qm_decode_rekey_docs_per_sec: f64, - pub qm_input_mb_per_sec: f64, - pub curate_elapsed_ms: f64, - pub curate_rows_per_sec: f64, - pub write_seq_elapsed_ms: f64, - pub write_seq_rows_per_sec: f64, - pub write_seq_mb_per_sec: f64, - pub write_elapsed_ms: f64, - pub write_rows_per_sec: f64, - pub write_mb_per_sec: f64, - pub write_speedup: f64, - pub total_elapsed_ms: f64, - pub total_rows_per_sec: f64, - pub total_mb_per_sec: f64, - pub split_rekey: crate::run_curate_bars::SplitRekeyStats, - pub eod_decode: BsonEodDecodeStats, - pub splits_decode: BsonQmActionDecodeStats, - pub qm_prices_decode: crate::bson_qm_prices::BsonQmPriceDecodeStats, - pub qm_rekey: crate::run_curate_bars::QmVolumeRekeyStats, - pub qm_matched_us: usize, - pub qm_matched_ca: usize, - pub injected_mismatches: usize, - pub mismatch_samples_out: usize, - pub curate_stats: crate::curate_bars::CurateBars1dStats, -} - -fn format_ymd_string(epoch_day: i32) -> String { - let (y, m, d) = epoch_days_to_ymd(epoch_day); - format!("{y:04}-{m:02}-{d:02}") -} - -fn build_weekday_pool(start_year: i32, end_year: i32) -> Vec { - let start = ymd_to_epoch_days(start_year, 1, 1).expect("valid start year"); - let end = ymd_to_epoch_days(end_year, 12, 31).expect("valid end year"); - let mut days = Vec::with_capacity(((end - start + 1) as usize * 5) / 7 + 8); - let mut d = start; - while d <= end { - let dow = (d + 4).rem_euclid(7); - if dow != 0 && dow != 6 { - days.push(d); - } - d += 1; - } - days -} - -fn gcd_usize(mut a: usize, mut b: usize) -> usize { - while b != 0 { - let t = a % b; - a = b; - b = t; - } - a -} - -fn choose_coprime_stride(len: usize, start: usize) -> usize { - if len <= 1 { - return 1; - } - let mut s = start.max(1) % len; - if s == 0 { - s = 1; - } - while gcd_usize(s, len) != 1 { - s += 1; - if s >= len { - s = 1; - } - } - s -} - -fn run_curate_bars_cmd_benchmark_tracked( - rows: usize, -) -> Result<(CurateBarsCmdBenchReport, PathBuf), CurateBarsCmdBenchError> { - use std::io::{BufWriter, Write}; - - use crate::bson_eod_prices::MILLIS_PER_DAY; - use crate::parquet_bars::default_parallel_threads; - use crate::run_curate_bars::{ - run_curate_bars_1d_timed_compare, CurateBars1dArgs, DEFAULT_CURATE_BARS_REL_TOLERANCE, - }; - - const MIB: f64 = 1_048_576.0; - - let temp = BenchTempDir::new_in_with_prefix( - &std::env::temp_dir(), - "curate-etl-bench-curate-bars-cmd", - ) - .map_err(|(path, source)| CurateBarsCmdBenchError::FixtureIo { path, source })?; - let temp_path = temp.path.clone(); - - let eod_path = temp.path.join("eodPrices.bson"); - let splits_path = temp.path.join("qmSplits.bson"); - let qm_prices_path = temp.path.join("qmPrices.bson"); - let mapping_path = temp.path.join("provider_mapping.tsv"); - let currencies_path = temp.path.join("listing_currencies.tsv"); - let out_dir_seq = temp.path.join("out_seq"); - let out_dir_par = temp.path.join("out_par"); - - let key_count = curate_bars_bench_key_count(rows.max(1)); - - // Precompute weekday date pools for 2008..=2025, 1990..=2007, and 1970..=1975. - let main_days = build_weekday_pool(2008, 2025); - let main_strs: Vec = main_days.iter().copied().map(format_ymd_string).collect(); - let pre2008_days = build_weekday_pool(1990, 2007); - let pre2008_strs: Vec = pre2008_days - .iter() - .copied() - .map(format_ymd_string) - .collect(); - let pre1976_days = build_weekday_pool(1970, 1975); - let pre1976_strs: Vec = pre1976_days - .iter() - .copied() - .map(format_ymd_string) - .collect(); - - let mut rng = SplitMix64::new(CURATE_BARS_CMD_BENCH_SEED); - - // 1. Write `provider_mapping.tsv` and `listing_currencies.tsv`. - { - let mut map_w = BufWriter::with_capacity( - 256 * 1024, - File::create(&mapping_path).map_err(|source| CurateBarsCmdBenchError::FixtureIo { - path: mapping_path.clone(), - source, - })?, - ); - let mut curr_w = BufWriter::with_capacity( - 64 * 1024, - File::create(¤cies_path).map_err(|source| { - CurateBarsCmdBenchError::FixtureIo { - path: currencies_path.clone(), - source, - } - })?, - ); - - let mapped_keys = key_count - (key_count / 50).max(1); - for k in 0..mapped_keys { - let listing_id = (k + 1) as i32; - let is_cad = k % 4 == 0; - let suffix = if is_cad { "TO" } else { "US" }; - let eod_code = format!("CMD{k:05}.{suffix}"); - let qm_code = format!("QM{k:05}:{suffix}"); - - if k % 50 == 1 { - // Ticker reuse with interior H2-2016 gap (starts 1990 so pre-1976 + gap -> unmapped). - let reuse_listing_id = (mapped_keys + k + 10) as i32; - writeln!(map_w, "eod\t{eod_code}\t1990-01-01\t2016-06-30\t{listing_id}") - .map_err(|source| CurateBarsCmdBenchError::FixtureIo { - path: mapping_path.clone(), - source, - })?; - writeln!(map_w, "eod\t{eod_code}\t2017-01-01\t\t{reuse_listing_id}") - .map_err(|source| CurateBarsCmdBenchError::FixtureIo { - path: mapping_path.clone(), - source, - })?; - writeln!(map_w, "qm\t{qm_code}\t1990-01-01\t2016-06-30\t{listing_id}") - .map_err(|source| CurateBarsCmdBenchError::FixtureIo { - path: mapping_path.clone(), - source, - })?; - writeln!(map_w, "qm\t{qm_code}\t2017-01-01\t\t{reuse_listing_id}") - .map_err(|source| CurateBarsCmdBenchError::FixtureIo { - path: mapping_path.clone(), - source, - })?; - let curr = if is_cad { "CAD" } else { "USD" }; - writeln!(curr_w, "{reuse_listing_id}\t{curr}").map_err(|source| { - CurateBarsCmdBenchError::FixtureIo { - path: currencies_path.clone(), - source, - } - })?; - } else if k % 50 == 2 { - // Cross-key EOD + QM alias sharing listing_id with `k - 2` (currency already - // emitted by `k - 2`; starts 1970-01-01). - let base_listing_id = (k - 2 + 1) as i32; - writeln!( - map_w, - "eod\t{eod_code}\t1970-01-01\t\t{base_listing_id}" - ) - .map_err(|source| CurateBarsCmdBenchError::FixtureIo { - path: mapping_path.clone(), - source, - })?; - writeln!( - map_w, - "qm\t{qm_code}\t1970-01-01\t\t{base_listing_id}" - ) - .map_err(|source| CurateBarsCmdBenchError::FixtureIo { - path: mapping_path.clone(), - source, - })?; - continue; - } else { - // Covering mapping from 1970-01-01 so pre-1976 bars reach timestamp validation - // and exercise `dropped_ts_out_of_range`. - writeln!(map_w, "eod\t{eod_code}\t1970-01-01\t\t{listing_id}").map_err( - |source| CurateBarsCmdBenchError::FixtureIo { - path: mapping_path.clone(), - source, - }, - )?; - writeln!(map_w, "qm\t{qm_code}\t1970-01-01\t\t{listing_id}").map_err(|source| { - CurateBarsCmdBenchError::FixtureIo { - path: mapping_path.clone(), - source, - } - })?; - } - - // Leave ~1% listings without currency to exercise `dropped_missing_currency`. - if k % 100 != 99 { - let curr = if is_cad { "CAD" } else { "USD" }; - writeln!(curr_w, "{listing_id}\t{curr}").map_err(|source| { - CurateBarsCmdBenchError::FixtureIo { - path: currencies_path.clone(), - source, - } - })?; - } - } - - // One QM-only listing (no EOD partner) to exercise `splits_no_eod_partner`. - let qm_only_listing = (key_count * 4 + 1) as i32; - writeln!(map_w, "qm\tQM_ONLY:US\t1990-01-01\t\t{qm_only_listing}").map_err(|source| { - CurateBarsCmdBenchError::FixtureIo { - path: mapping_path.clone(), - source, - } - })?; - writeln!(curr_w, "{qm_only_listing}\tUSD").map_err(|source| { - CurateBarsCmdBenchError::FixtureIo { - path: currencies_path.clone(), - source, - } - })?; - - map_w.flush().map_err(|source| CurateBarsCmdBenchError::FixtureIo { - path: mapping_path.clone(), - source, - })?; - curr_w.flush().map_err(|source| CurateBarsCmdBenchError::FixtureIo { - path: currencies_path.clone(), - source, - })?; - } - - // 2. Stream-write `qmSplits.bson` and track applied split events per key index so synthetic - // `qmPrices.sharevolume` partners match un-adjusted EOD volumes except on exact injected - // >1% divergences. - let gap_start = ymd_to_epoch_days(2016, 7, 1).expect("valid gap start"); - let gap_end = ymd_to_epoch_days(2016, 12, 31).expect("valid gap end"); - let mut ref_split_events: Vec<(usize, SplitEvent)> = Vec::new(); - { - let mut splits_w = BufWriter::with_capacity( - 256 * 1024, - File::create(&splits_path).map_err(|source| CurateBarsCmdBenchError::FixtureIo { - path: splits_path.clone(), - source, - })?, - ); - if rows > 0 { - let mapped_keys = key_count - (key_count / 50).max(1); - let split_count = key_count.min(4_000); - const RATIOS: [f64; 6] = [2.0, 3.0, 4.0, 10.0, 0.5, 0.25]; - for i in 0..split_count { - let mut doc = RawDocumentBuf::new(); - let date_idx = (rng.next_u64() as usize) % main_days.len(); - let ex_date = main_days[date_idx]; - let date_str = &main_strs[date_idx]; - let mut oid_bytes = [0u8; 12]; - oid_bytes[4..12].copy_from_slice(&(i as u64).to_be_bytes()); - doc.append(cstr!("_id"), ObjectId::from_bytes(oid_bytes)); - - if i % 20 == 0 { - // 1:1 no-op split. - let k = i % mapped_keys; - let suffix = if k % 4 == 0 { "TO" } else { "US" }; - let qm_code = format!("QM{k:05}:{suffix}"); - doc.append(cstr!("qmSearchCode"), qm_code.as_str()); - doc.append(cstr!("date"), date_str.as_str()); - doc.append(cstr!("splitratio"), 1.0_f64); - } else if i % 20 == 1 { - // Unmapped QM code. - doc.append(cstr!("qmSearchCode"), "QM_UNMAPPED:US"); - doc.append(cstr!("date"), date_str.as_str()); - doc.append(cstr!("splitratio"), 2.0_f64); - } else if i % 20 == 2 { - // Mapped QM listing with no EOD partner. - doc.append(cstr!("qmSearchCode"), "QM_ONLY:US"); - doc.append(cstr!("date"), date_str.as_str()); - doc.append(cstr!("splitratio"), 2.0_f64); - } else { - let mut k = i % mapped_keys; - if k % 50 == 2 { - k -= 2; - } - let suffix = if k % 4 == 0 { "TO" } else { "US" }; - let qm_code = format!("QM{k:05}:{suffix}"); - let ratio = RATIOS[(rng.next_u64() as usize) % RATIOS.len()]; - doc.append(cstr!("qmSearchCode"), qm_code.as_str()); - doc.append(cstr!("date"), date_str.as_str()); - doc.append(cstr!("splitratio"), 1.0 / ratio); - doc.append(cstr!("forfactor"), 1.0_f64); - doc.append(cstr!("tofactor"), ratio); - - let in_reuse_gap = k % 50 == 1 && (gap_start..=gap_end).contains(&ex_date); - if !in_reuse_gap { - ref_split_events.push((k, SplitEvent { ex_date, ratio })); - } - - // Emit an identical split under the QM alias key `k + 2` to exercise - // `splits_collision_collapsed` without introducing ratio conflicts. - if k % 50 == 0 && k + 2 < mapped_keys { - splits_w.write_all(doc.as_bytes()).map_err(|source| { - CurateBarsCmdBenchError::FixtureIo { - path: splits_path.clone(), - source, - } - })?; - let alias_k = k + 2; - let alias_suffix = if alias_k % 4 == 0 { "TO" } else { "US" }; - let alias_qm_code = format!("QM{alias_k:05}:{alias_suffix}"); - let mut alias_oid = [0u8; 12]; - alias_oid[0] = 1; - alias_oid[4..12].copy_from_slice(&(i as u64).to_be_bytes()); - doc = RawDocumentBuf::new(); - doc.append(cstr!("_id"), ObjectId::from_bytes(alias_oid)); - doc.append(cstr!("qmSearchCode"), alias_qm_code.as_str()); - doc.append(cstr!("date"), date_str.as_str()); - doc.append(cstr!("splitratio"), 1.0 / ratio); - doc.append(cstr!("forfactor"), 1.0_f64); - doc.append(cstr!("tofactor"), ratio); - } - } - splits_w - .write_all(doc.as_bytes()) - .map_err(|source| CurateBarsCmdBenchError::FixtureIo { - path: splits_path.clone(), - source, - })?; - } - } - splits_w - .flush() - .map_err(|source| CurateBarsCmdBenchError::FixtureIo { - path: splits_path.clone(), - source, - })?; - } - let ref_splits = SplitTable::::from_events(ref_split_events).map_err(|source| { - CurateBarsCmdBenchError::Run(crate::run_curate_bars::RunCurateBarsError::SplitTable { - path: splits_path.clone(), - source, - }) - })?; - - // 3. Stream-write `eodPrices.bson` and `qmPrices.bson` directly to disk. - let mut injected_mismatches = 0usize; - let mut qm_matched_emitted = 0usize; - let mut qm_matched_us = 0usize; - let mut qm_matched_ca = 0usize; - { - let mut eod_w = BufWriter::with_capacity( - 512 * 1024, - File::create(&eod_path).map_err(|source| CurateBarsCmdBenchError::FixtureIo { - path: eod_path.clone(), - source, - })?, - ); - let mut qm_w = BufWriter::with_capacity( - 512 * 1024, - File::create(&qm_prices_path).map_err(|source| CurateBarsCmdBenchError::FixtureIo { - path: qm_prices_path.clone(), - source, - })?, - ); - let mapped_keys = key_count - (key_count / 50).max(1); - let eod_codes: Vec = (0..key_count) - .map(|k| { - let suffix = if k % 4 == 0 { "TO" } else { "US" }; - if k < mapped_keys { - format!("CMD{k:05}.{suffix}") - } else { - format!("UNMAP{k:05}.{suffix}") - } - }) - .collect(); - let qm_codes: Vec = (0..mapped_keys) - .map(|k| { - let suffix = if k % 4 == 0 { "TO" } else { "US" }; - format!("QM{k:05}:{suffix}") - }) - .collect(); - - // Per-key coprime-stride cursors over `main_days` so 5M rows stay unique per key. - // Alias keys (`k % 50 == 2`) share the starting cursor of their base key (`k - 2`) - // so both land on identical `(listing_id, session_date)` pairs. - let main_len = main_days.len(); - let stride = choose_coprime_stride(main_len, 17); - let mut cursors: Vec = (0..key_count) - .map(|k| { - let base_k = if k < mapped_keys && k % 50 == 2 { - k - 2 - } else { - k - }; - (base_k * 13) % main_len - }) - .collect(); - - for i in 0..rows { - let k = i % key_count; - let pass = i / key_count; - let code = &eod_codes[k]; - let roll = rng.next_u64() % 1_000; - let is_alias_base = k < mapped_keys && k % 50 == 0 && k + 2 < mapped_keys; - let is_alias_key = k < mapped_keys && k % 50 == 2; - - let (epoch_day, date_str) = if is_alias_base || is_alias_key { - let idx = cursors[k]; - cursors[k] = (idx + stride) % main_len; - (main_days[idx], &main_strs[idx]) - } else if roll < 20 { - let idx = (rng.next_u64() as usize) % pre2008_days.len(); - (pre2008_days[idx], &pre2008_strs[idx]) - } else if roll < 22 { - let idx = (rng.next_u64() as usize) % pre1976_days.len(); - (pre1976_days[idx], &pre1976_strs[idx]) - } else { - let idx = cursors[k]; - cursors[k] = (idx + stride) % main_len; - (main_days[idx], &main_strs[idx]) - }; - - let (open, high, low, close, volume_i64) = if is_alias_base || is_alias_key { - // Deterministic OHLCV keyed by `(base_k, epoch_day)`: identical on even passes - // (`listing_collision_collapsed`) and differing on odd passes (`listing_collision_dropped`). - let base_k = if is_alias_key { k - 2 } else { k }; - let base = 50.0 + ((base_k % 200) as f64) + ((epoch_day.rem_euclid(50)) as f64) * 0.25; - let bump = if is_alias_key && pass % 2 == 1 { - 1.0 - } else { - 0.0 - }; - let open = base + bump; - let high = open + 2.0; - let low = open - 1.0; - let close = open + 0.5; - let volume_i64 = 100_000 + ((base_k as i64) * 100) + ((epoch_day as i64) & 0x3ff); - (open, high, low, close, volume_i64) - } else { - let base_cents = 100 + (rng.next_u64() % 50_000) as i64; - let open = base_cents as f64 / 100.0; - let spread = 1.0 + (rng.next_u64() % 200) as f64 / 100.0; - let high = open + spread; - let low = (open - spread * 0.5).max(0.01); - let close = low + (high - low) * ((rng.next_u64() % 100) as f64 / 100.0); - let volume_i64 = 1_000 + (rng.next_u64() % 50_000_000) as i64; - (open, high, low, close, volume_i64) - }; - - let mut oid_bytes = [0u8; 12]; - oid_bytes[4..12].copy_from_slice(&(i as u64).to_be_bytes()); - - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("_id"), ObjectId::from_bytes(oid_bytes)); - doc.append(cstr!("eodSearchCode"), code.as_str()); - if i % 20 == 0 { - doc.append( - cstr!("date"), - DateTime::from_millis(i64::from(epoch_day) * MILLIS_PER_DAY), - ); - } else { - doc.append(cstr!("date"), date_str.as_str()); - } - doc.append(cstr!("open"), open); - doc.append(cstr!("high"), high); - doc.append(cstr!("low"), low); - doc.append(cstr!("close"), close); - doc.append(cstr!("volume"), volume_i64); - doc.append(cstr!("source"), "eod"); - - eod_w - .write_all(doc.as_bytes()) - .map_err(|source| CurateBarsCmdBenchError::FixtureIo { - path: eod_path.clone(), - source, - })?; - - // Emit a synthetic `qmPrices` partner for 25% of unique non-alias, non-gap mapped bars - // using a deterministic selector independent of `k % 4` so both US (`k % 4 != 0`) and - // Canadian (`k % 4 == 0`) tickers are sampled across every pass. - let is_clean_unique_main_bar = k < mapped_keys - && k % 50 != 0 - && k % 50 != 1 - && k % 50 != 2 - && roll >= 22; - if is_clean_unique_main_bar && ((i / 4) ^ i ^ pass) % 4 == 0 { - qm_matched_emitted += 1; - if k % 4 == 0 { - qm_matched_ca += 1; - } else { - qm_matched_us += 1; - } - let factor = ref_splits.cum_factor_after(&k, epoch_day); - let raw_vol = crate::split::unadjust_volume(volume_i64 as f64, factor); - let mut qdoc = RawDocumentBuf::new(); - let mut qoid = [0u8; 12]; - qoid[0] = 2; - qoid[4..12].copy_from_slice(&(i as u64).to_be_bytes()); - qdoc.append(cstr!("_id"), ObjectId::from_bytes(qoid)); - qdoc.append(cstr!("qmSearchCode"), qm_codes[k].as_str()); - qdoc.append(cstr!("date"), date_str.as_str()); - if qm_matched_emitted % 100 == 1 { - // Exact injected >1% divergence (~4.76% relative diff). - qdoc.append(cstr!("sharevolume"), raw_vol * 1.05); - injected_mismatches += 1; - } else { - let rounded = raw_vol.round(); - let safe_int = rounded >= 1.0 - && (rounded - raw_vol).abs() / raw_vol <= 0.005; - if qm_matched_emitted % 3 == 1 && safe_int && rounded <= i32::MAX as f64 { - qdoc.append(cstr!("sharevolume"), rounded as i32); - } else if qm_matched_emitted % 3 == 2 && safe_int && rounded <= i64::MAX as f64 { - qdoc.append(cstr!("sharevolume"), rounded as i64); - } else { - qdoc.append(cstr!("sharevolume"), raw_vol); - } - } - qm_w.write_all(qdoc.as_bytes()) - .map_err(|source| CurateBarsCmdBenchError::FixtureIo { - path: qm_prices_path.clone(), - source, - })?; - } - } - - // Emit deterministic unmapped, no-EOD-partner, and wrong-typed `qmPrices` docs when rows > 0. - if rows > 0 { - let unmapped_n = (rows / 1_000).max(1); - let no_partner_n = (rows / 1_000).max(1); - let wrong_type_n = (rows / 2_000).max(1); - - for j in 0..unmapped_n { - let mut qdoc = RawDocumentBuf::new(); - qdoc.append(cstr!("qmSearchCode"), "QM_UNMAPPED:US"); - qdoc.append(cstr!("date"), main_strs[j % main_len].as_str()); - qdoc.append(cstr!("sharevolume"), 50_000_i32); - qm_w.write_all(qdoc.as_bytes()) - .map_err(|source| CurateBarsCmdBenchError::FixtureIo { - path: qm_prices_path.clone(), - source, - })?; - } - for j in 0..no_partner_n { - let mut qdoc = RawDocumentBuf::new(); - qdoc.append(cstr!("qmSearchCode"), "QM_ONLY:US"); - qdoc.append(cstr!("date"), main_strs[j % main_len].as_str()); - qdoc.append(cstr!("sharevolume"), 75_000_i64); - qm_w.write_all(qdoc.as_bytes()) - .map_err(|source| CurateBarsCmdBenchError::FixtureIo { - path: qm_prices_path.clone(), - source, - })?; - } - for j in 0..wrong_type_n { - let mut qdoc = RawDocumentBuf::new(); - qdoc.append(cstr!("qmSearchCode"), qm_codes[0].as_str()); - qdoc.append(cstr!("date"), main_strs[j % main_len].as_str()); - qdoc.append(cstr!("sharevolume"), "bad-volume"); - qm_w.write_all(qdoc.as_bytes()) - .map_err(|source| CurateBarsCmdBenchError::FixtureIo { - path: qm_prices_path.clone(), - source, - })?; - } - } - - eod_w - .flush() - .map_err(|source| CurateBarsCmdBenchError::FixtureIo { - path: eod_path.clone(), - source, - })?; - qm_w.flush() - .map_err(|source| CurateBarsCmdBenchError::FixtureIo { - path: qm_prices_path.clone(), - source, - })?; - } - - // 4. Run the full command path file -> Parquet with decode / curate / seq+par write timing. - let parallel_threads = default_parallel_threads(); - let args = CurateBars1dArgs { - eod_prices: eod_path, - qm_splits: splits_path, - qm_prices: Some(qm_prices_path), - provider_mapping: mapping_path, - listing_currencies: currencies_path, - out_dir: out_dir_par.clone(), - rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, - threads: parallel_threads, - }; - let timed = run_curate_bars_1d_timed_compare(&args, &out_dir_seq, &out_dir_par, parallel_threads) - .map_err(CurateBarsCmdBenchError::Run)?; - - let read_back_rows_seq = verify_parquet_bars_row_count( - &out_dir_seq, - timed.write_stats_seq.rows_by_year.keys().copied(), - timed.write_stats_seq.rows_written, - ) - .map_err(CurateBarsCmdBenchError::Verify)?; - - let read_back_rows = verify_parquet_bars_row_count( - &out_dir_par, - timed.report.write_stats.rows_by_year.keys().copied(), - timed.report.write_stats.rows_written, - ) - .map_err(CurateBarsCmdBenchError::Verify)?; - - let decode_elapsed_ms = timed.decode_elapsed_secs * 1_000.0; - let qm_decode_rekey_elapsed_ms = timed.qm_decode_rekey_elapsed_secs * 1_000.0; - let curate_elapsed_ms = timed.curate_elapsed_secs * 1_000.0; - let write_seq_elapsed_ms = timed.write_seq_elapsed_secs * 1_000.0; - let write_elapsed_ms = timed.write_par_elapsed_secs * 1_000.0; - let total_elapsed_secs = - timed.decode_elapsed_secs + timed.curate_elapsed_secs + timed.write_par_elapsed_secs; - let total_elapsed_ms = total_elapsed_secs * 1_000.0; - - let (decode_rows_per_sec, _) = compute_rates(rows, timed.decode_elapsed_secs); - let (qm_decode_rekey_docs_per_sec, _) = compute_rates( - timed.report.qm_prices_docs_framed as usize, - timed.qm_decode_rekey_elapsed_secs, - ); - let (curate_rows_per_sec, _) = - compute_rates(timed.report.buffered_bars, timed.curate_elapsed_secs); - let (write_seq_rows_per_sec, _) = compute_rates( - timed.write_stats_seq.rows_written, - timed.write_seq_elapsed_secs, - ); - let (write_rows_per_sec, _) = compute_rates( - timed.report.write_stats.rows_written, - timed.write_par_elapsed_secs, - ); - let (total_rows_per_sec, _) = compute_rates(rows, total_elapsed_secs); - - let total_input_bytes = timed.report.eod_bytes_read - + timed.report.splits_bytes_read - + timed.report.qm_prices_bytes_read; - let input_mb_per_sec = if timed.decode_elapsed_secs > 0.0 { - (total_input_bytes as f64 / MIB) / timed.decode_elapsed_secs - } else { - 0.0 - }; - let qm_input_mb_per_sec = if timed.qm_decode_rekey_elapsed_secs > 0.0 { - (timed.report.qm_prices_bytes_read as f64 / MIB) / timed.qm_decode_rekey_elapsed_secs - } else { - 0.0 - }; - let write_seq_mb_per_sec = if timed.write_seq_elapsed_secs > 0.0 { - (timed.write_stats_seq.bytes_written as f64 / MIB) / timed.write_seq_elapsed_secs - } else { - 0.0 - }; - let write_mb_per_sec = if timed.write_par_elapsed_secs > 0.0 { - (timed.report.write_stats.bytes_written as f64 / MIB) / timed.write_par_elapsed_secs - } else { - 0.0 - }; - let write_speedup = if timed.write_par_elapsed_secs > 0.0 && timed.write_seq_elapsed_secs > 0.0 { - timed.write_seq_elapsed_secs / timed.write_par_elapsed_secs - } else { - 1.0 - }; - let total_mb_per_sec = if total_elapsed_secs > 0.0 { - (total_input_bytes as f64 / MIB) / total_elapsed_secs - } else { - 0.0 - }; - let bytes_per_buffered_bar = if timed.report.buffered_bars > 0 { - timed.report.buffered_bar_bytes as f64 / timed.report.buffered_bars as f64 - } else { - 0.0 - }; - - let report = CurateBarsCmdBenchReport { - rows, - key_count, - eod_docs_framed: timed.report.eod_docs_framed, - eod_bytes_read: timed.report.eod_bytes_read, - splits_docs_framed: timed.report.splits_docs_framed, - splits_bytes_read: timed.report.splits_bytes_read, - qm_docs_framed: timed.report.qm_prices_docs_framed, - qm_bytes_read: timed.report.qm_prices_bytes_read, - bars_unmapped_source_dropped: timed.report.bars_unmapped_source_dropped, - buffered_bars: timed.report.buffered_bars, - buffered_bar_bytes: timed.report.buffered_bar_bytes, - bytes_per_buffered_bar, - rows_out: timed.report.curate_stats.rows_out, - listings_out: timed.report.curate_stats.listings_out, - files_written: timed.report.write_stats.files_written, - row_groups_written: timed.report.write_stats.row_groups_written, - bytes_written: timed.report.write_stats.bytes_written, - parallel_threads, - read_back_rows_seq, - read_back_rows, - decode_elapsed_ms, - decode_rows_per_sec, - input_mb_per_sec, - qm_decode_rekey_elapsed_ms, - qm_decode_rekey_docs_per_sec, - qm_input_mb_per_sec, - curate_elapsed_ms, - curate_rows_per_sec, - write_seq_elapsed_ms, - write_seq_rows_per_sec, - write_seq_mb_per_sec, - write_elapsed_ms, - write_rows_per_sec, - write_mb_per_sec, - write_speedup, - total_elapsed_ms, - total_rows_per_sec, - total_mb_per_sec, - split_rekey: timed.report.split_rekey, - eod_decode: timed.report.eod_decode, - splits_decode: timed.report.splits_decode, - qm_prices_decode: timed.report.qm_prices_decode, - qm_rekey: timed.report.qm_rekey, - qm_matched_us, - qm_matched_ca, - injected_mismatches, - mismatch_samples_out: timed.report.mismatch_samples.len(), - curate_stats: timed.report.curate_stats, - }; - - drop(temp); - Ok((report, temp_path)) -} - -/// Runs the fixed-seed end-to-end `curate-bars-1d` file -> Parquet benchmark for `rows` -/// synthetic `eodPrices` BSON documents. -pub fn run_curate_bars_cmd_benchmark( - rows: usize, -) -> Result { - let (report, _) = run_curate_bars_cmd_benchmark_tracked(rows)?; - Ok(report) -} - pub const DEFAULT_CURATE_SHORTS_BENCH_ROWS: usize = 2_000_000; const CURATE_SHORTS_BENCH_SEED: u64 = 0x570C_4B07_C04A_5407; const CURATE_SHORTS_BENCH_KEY_COUNT: usize = 12_500; @@ -7416,3949 +5385,6 @@ pub fn run_curate_fx_benchmark( Ok(report) } -pub const DEFAULT_CURATE_ADJ_BENCH_EVENTS: usize = 1_000_000; -const CURATE_ADJ_BENCH_SEED: u64 = 0x570C_4B07_C04A_AD7F; -const CURATE_ADJ_BENCH_KEY_COUNT: usize = 20_000; - -/// Summary metrics produced by [`run_curate_adj_benchmark`]. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct CurateAdjBenchReport { - pub events: usize, - pub splits_in: usize, - pub dividends_in: usize, - pub key_count: usize, - pub rows_out: usize, - pub listings_out: usize, - pub stage_elapsed_ms: f64, - pub stage_events_per_sec: f64, - pub stage_ns_per_event: f64, - pub parquet_elapsed_ms: f64, - pub parquet_rows_per_sec: f64, - pub total_elapsed_ms: f64, - pub total_events_per_sec: f64, - pub files_written: usize, - pub row_groups_written: usize, - pub bytes_written: u64, - pub read_back_rows: usize, - pub checksum: u64, - pub stats: crate::curate_adj::CurateAdjFactorsStats, -} - -fn run_curate_adj_benchmark_tracked( - events: usize, -) -> Result<(CurateAdjBenchReport, PathBuf), crate::curate_adj::CurateAdjWriteError> { - use crate::curate_adj::{curate_adj_factors, CurateAdjFactorsStats, CurateAdjWriteError}; - - let temp = - BenchTempDir::new_in_with_prefix(&std::env::temp_dir(), "curate-etl-bench-curate-adj") - .map_err(|(path, source)| { - CurateAdjWriteError::Parquet(ParquetAdjError::Io { path, source }) - })?; - let temp_path = temp.path.clone(); - - if events == 0 { - let empty_mapping = ProviderMappingTable::default(); - let curated = curate_adj_factors( - &empty_mapping, - "qm", - std::iter::empty::<(String, SplitEvent)>(), - std::iter::empty::<(String, DividendEvent)>(), - )?; - let write_stats = write_adj_factors_dataset( - &temp.path, - &curated.rows, - AdjFactorsWriteOptions::default(), - )?; - let read_back_rows = verify_parquet_adj_row_count(&temp.path, 0)?; - drop(temp); - return Ok(( - CurateAdjBenchReport { - events: 0, - splits_in: 0, - dividends_in: 0, - key_count: CURATE_ADJ_BENCH_KEY_COUNT, - rows_out: 0, - listings_out: 0, - stage_elapsed_ms: 0.0, - stage_events_per_sec: 0.0, - stage_ns_per_event: 0.0, - parquet_elapsed_ms: 0.0, - parquet_rows_per_sec: 0.0, - total_elapsed_ms: 0.0, - total_events_per_sec: 0.0, - files_written: write_stats.files_written, - row_groups_written: write_stats.row_groups_written, - bytes_written: write_stats.bytes_written, - read_back_rows, - checksum: 0, - stats: CurateAdjFactorsStats::default(), - }, - temp_path, - )); - } - - let min_date = ymd_to_epoch_days(1990, 1, 1).expect("valid min_date"); - let max_date = ymd_to_epoch_days(2025, 12, 31).expect("valid max_date"); - let date_span = (max_date - min_date + 1) as u64; // 13,149 days - let rename_cutoff = ymd_to_epoch_days(2014, 12, 31).expect("valid rename_cutoff"); - let reuse_end_old = ymd_to_epoch_days(2018, 6, 30).expect("valid reuse_end_old"); - let reuse_start_new = ymd_to_epoch_days(2019, 1, 1).expect("valid reuse_start_new"); - - const SINGLE_RANGE_END: usize = 18_000; - const RENAME_PAIRS: usize = 300; - const RENAME_END: usize = SINGLE_RANGE_END + RENAME_PAIRS * 2; // 18_600 - const REUSE_COUNT: usize = 600; - const REUSE_END: usize = RENAME_END + REUSE_COUNT; // 19_200 - const UNMAPPED_COUNT: usize = 400; - const ORDINARY_KEY_COUNT: usize = REUSE_END + UNMAPPED_COUNT; // 19_600 - const ALIAS_COUNT: usize = CURATE_ADJ_BENCH_KEY_COUNT - ORDINARY_KEY_COUNT; // 400 - - let keys: Vec = (0..CURATE_ADJ_BENCH_KEY_COUNT) - .map(|i| format!("QM{i:05}")) - .collect(); - - let mut mapping_rows: Vec = - Vec::with_capacity(CURATE_ADJ_BENCH_KEY_COUNT + REUSE_COUNT); - - // 1. Single-range keys [0..18_000) -> listing_id 1..=18_000 - for (i, key) in keys.iter().enumerate().take(SINGLE_RANGE_END) { - mapping_rows.push(ProviderMappingRow { - source: "qm".to_string(), - source_id: key.clone(), - valid_from: min_date, - valid_to: None, - listing_id: (i as i32) + 1, - }); - } - - // 2. Ticker-rename pairs [18_000..18_600) -> 300 listings (18_001..=18_300) - let mut next_listing_id = (SINGLE_RANGE_END as i32) + 1; - for p in 0..RENAME_PAIRS { - let old_idx = SINGLE_RANGE_END + p * 2; - let new_idx = old_idx + 1; - let lid = next_listing_id; - next_listing_id += 1; - mapping_rows.push(ProviderMappingRow { - source: "qm".to_string(), - source_id: keys[old_idx].clone(), - valid_from: min_date, - valid_to: Some(rename_cutoff), - listing_id: lid, - }); - mapping_rows.push(ProviderMappingRow { - source: "qm".to_string(), - source_id: keys[new_idx].clone(), - valid_from: rename_cutoff + 1, - valid_to: None, - listing_id: lid, - }); - } - - // 3. Ticker-reuse keys [18_600..19_200) -> two non-overlapping ranges with H2-2018 gap - for r in 0..REUSE_COUNT { - let key_idx = RENAME_END + r; - let old_lid = next_listing_id; - let new_lid = next_listing_id + 1; - next_listing_id += 2; - mapping_rows.push(ProviderMappingRow { - source: "qm".to_string(), - source_id: keys[key_idx].clone(), - valid_from: min_date, - valid_to: Some(reuse_end_old), - listing_id: old_lid, - }); - mapping_rows.push(ProviderMappingRow { - source: "qm".to_string(), - source_id: keys[key_idx].clone(), - valid_from: reuse_start_new, - valid_to: None, - listing_id: new_lid, - }); - } - - // 4. Unmapped keys [19_200..19_600) intentionally have no mapping rows. - // 5. Alias keys [19_600..20_000) mirror keys [0..400) -> listing_id 1..=400. - for a in 0..ALIAS_COUNT { - mapping_rows.push(ProviderMappingRow { - source: "qm".to_string(), - source_id: keys[ORDINARY_KEY_COUNT + a].clone(), - valid_from: min_date, - valid_to: None, - listing_id: (a as i32) + 1, - }); - } - - let provider_mapping = - ProviderMappingTable::from_rows(mapping_rows).expect("valid curate_adj bench mapping"); - - let mut rng = SplitMix64::new(CURATE_ADJ_BENCH_SEED); - let mut splits: Vec<(String, SplitEvent)> = Vec::with_capacity(events / 20); - let mut dividends: Vec<(String, DividendEvent)> = Vec::with_capacity(events); - // Per-key unique-date step counter for keys [0..ALIAS_COUNT) so alias clones never collide - // with a second differing event on the same (listing_id, ex_date). - let mut alias_date_steps = [0u64; ALIAS_COUNT]; - let mut emitted = 0usize; - - while emitted < events { - let mut key_idx = (rng.next_u64() as usize) % ORDINARY_KEY_COUNT; - let (ex_date, emit_alias) = if key_idx < ALIAS_COUNT { - let step = alias_date_steps[key_idx]; - if step < date_span { - alias_date_steps[key_idx] = step + 1; - // 197 is prime and coprime to 13,149, so every step yields a unique ex_date. - let offset = (step * 197 + (key_idx as u64) * 31) % date_span; - let dup = emitted + 1 < events && (rng.next_u64() % 4) == 0; - (min_date + offset as i32, dup) - } else { - key_idx = ALIAS_COUNT + (key_idx % (ORDINARY_KEY_COUNT - ALIAS_COUNT)); - (min_date + (rng.next_u64() % date_span) as i32, false) - } - } else { - (min_date + (rng.next_u64() % date_span) as i32, false) - }; - - let kind_roll = rng.next_u64() % 100; - if kind_roll < 4 { - let ratio_roll = rng.next_u64() % 20; - let ratio = if ratio_roll == 0 { - 1.0 - } else { - SAMPLE_RATIOS[(rng.next_u64() as usize) % SAMPLE_RATIOS.len()] - }; - let ev = SplitEvent { ex_date, ratio }; - splits.push((keys[key_idx].clone(), ev)); - emitted += 1; - if emit_alias { - splits.push((keys[ORDINARY_KEY_COUNT + key_idx].clone(), ev)); - emitted += 1; - } - } else { - let (home_curr, alt_curr) = if key_idx % 5 == 0 { - ("CAD", "USD") - } else { - ("USD", "CAD") - }; - let fallback_roll = rng.next_u64() % 100; - let cash = if fallback_roll == 5 { - 0.0 - } else { - ((rng.next_u64() % 150) + 5) as f64 * 0.01 - }; - let (prev_close, prev_close_currency) = match fallback_roll { - 0 | 1 => (None, Some(home_curr.to_string())), - 2 | 3 => ( - Some(20.0 + (rng.next_u64() % 200) as f64), - Some(alt_curr.to_string()), - ), - 4 => (Some(cash * 0.5), Some(home_curr.to_string())), - _ => ( - Some(20.0 + (rng.next_u64() % 200) as f64), - Some(home_curr.to_string()), - ), - }; - let ev = DividendEvent { - ex_date, - cash, - currency: home_curr.to_string(), - prev_close, - prev_close_currency, - }; - if emit_alias { - dividends.push((keys[ORDINARY_KEY_COUNT + key_idx].clone(), ev.clone())); - emitted += 1; - } - dividends.push((keys[key_idx].clone(), ev)); - emitted += 1; - } - } - - let splits_in = splits.len(); - let dividends_in = dividends.len(); - - // 1. Time pure in-memory curation stage. - let stage_start = Instant::now(); - let curated = curate_adj_factors(&provider_mapping, "qm", splits, dividends)?; - let stage_elapsed_secs = stage_start.elapsed().as_secs_f64(); - let stage_elapsed_ms = stage_elapsed_secs * 1_000.0; - - let mut hash = 0u64; - for row in &curated.rows { - hash = mix_u64(hash, row.listing_id as u64); - hash = mix_u64(hash, row.ex_date as u64); - hash = mix_u64(hash, row.split_factor.to_bits()); - hash = mix_u64(hash, row.div_cash.to_bits()); - match row.div_currency.as_deref() { - Some(curr) => { - hash = mix_u64(hash, 1); - hash = mix_str_u64(hash, curr); - } - None => { - hash = mix_u64(hash, 0); - } - } - hash = mix_u64(hash, row.cum_split_factor.to_bits()); - hash = mix_u64(hash, row.cum_total_factor.to_bits()); - hash = mix_u64(hash, row.known_at_micros as u64); - } - let checksum = black_box(hash); - - // 2. Separately time Parquet write to temp dir. - let parquet_start = Instant::now(); - let write_stats = write_adj_factors_dataset( - &temp.path, - &curated.rows, - AdjFactorsWriteOptions::default(), - )?; - let parquet_elapsed_secs = parquet_start.elapsed().as_secs_f64(); - let parquet_elapsed_ms = parquet_elapsed_secs * 1_000.0; - - let read_back_rows = verify_parquet_adj_row_count(&temp.path, curated.rows.len())?; - - let (stage_events_per_sec, stage_ns_per_event) = compute_rates(events, stage_elapsed_secs); - let (parquet_rows_per_sec, _) = compute_rates(curated.rows.len(), parquet_elapsed_secs); - let total_elapsed_secs = stage_elapsed_secs + parquet_elapsed_secs; - let total_elapsed_ms = total_elapsed_secs * 1_000.0; - let (total_events_per_sec, _) = compute_rates(events, total_elapsed_secs); - - let report = CurateAdjBenchReport { - events, - splits_in, - dividends_in, - key_count: CURATE_ADJ_BENCH_KEY_COUNT, - rows_out: curated.stats.rows_out, - listings_out: curated.stats.listings_out, - stage_elapsed_ms, - stage_events_per_sec, - stage_ns_per_event, - parquet_elapsed_ms, - parquet_rows_per_sec, - total_elapsed_ms, - total_events_per_sec, - files_written: write_stats.files_written, - row_groups_written: write_stats.row_groups_written, - bytes_written: write_stats.bytes_written, - read_back_rows, - checksum, - stats: curated.stats, - }; - - drop(temp); - Ok((report, temp_path)) -} - -/// Runs the fixed-seed `adj_factors` curation stage + Zstd Parquet write benchmark for `events` -/// mixed `qmSplits` (~4%) and `qmDividends` (~96%) events across `20,000` `String` source keys -/// (single-range, ticker-rename, ticker-reuse with gap, unmapped, and bitwise-identical alias -/// keys), separately timing in-memory `curate_adj_factors` and Zstd Parquet -/// `write_adj_factors_dataset` into a temp directory removed on drop. -pub fn run_curate_adj_benchmark( - events: usize, -) -> Result { - let (report, _) = run_curate_adj_benchmark_tracked(events)?; - Ok(report) -} - -pub const DEFAULT_CURATE_ADJ_CMD_BENCH_EVENTS: usize = 500_000; -const CURATE_ADJ_CMD_BENCH_SEED: u64 = 0x570C_4B07_C04A_AD1C; -const CURATE_ADJ_CMD_BENCH_KEY_COUNT: usize = 4_000; - -/// Errors returned by [`run_curate_adj_cmd_benchmark`]. -#[derive(Debug)] -pub enum CurateAdjCmdBenchError { - FixtureIo { - path: PathBuf, - source: io::Error, - }, - FixtureBars(ParquetBarsError), - Run(crate::run_curate_adj::RunCurateAdjError), - Verify(ParquetAdjError), -} - -impl std::fmt::Display for CurateAdjCmdBenchError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Self::FixtureIo { path, source } => { - write!(f, "fixture I/O error at '{}': {source}", path.display()) - } - Self::FixtureBars(err) => write!(f, "fixture bars_1d write failed: {err}"), - Self::Run(err) => write!(f, "{err}"), - Self::Verify(err) => write!(f, "parquet verify failed: {err}"), - } - } -} - -impl std::error::Error for CurateAdjCmdBenchError { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - match self { - Self::FixtureIo { source, .. } => Some(source), - Self::FixtureBars(err) => Some(err), - Self::Run(err) => Some(err), - Self::Verify(err) => Some(err), - } - } -} - -/// Metrics returned by [`run_curate_adj_cmd_benchmark`]. -#[derive(Debug, Clone, PartialEq)] -pub struct CurateAdjCmdBenchReport { - pub events: usize, - pub key_count: usize, - pub bars_files_read: usize, - pub bars_rows_loaded: usize, - pub bars_listings_indexed: usize, - pub splits_docs_framed: u64, - pub splits_bytes_read: u64, - pub dividends_docs_framed: u64, - pub dividends_bytes_read: u64, - pub dividends_with_prev_close: usize, - pub dividends_without_prev_close: usize, - pub rows_out: usize, - pub listings_out: usize, - pub files_written: usize, - pub row_groups_written: usize, - pub bytes_written: u64, - pub read_back_rows: usize, - pub bars_load_elapsed_ms: f64, - pub bars_load_rows_per_sec: f64, - pub decode_elapsed_ms: f64, - pub decode_events_per_sec: f64, - pub input_mb_per_sec: f64, - pub curate_elapsed_ms: f64, - pub curate_events_per_sec: f64, - pub write_elapsed_ms: f64, - pub write_rows_per_sec: f64, - pub write_mb_per_sec: f64, - pub total_elapsed_ms: f64, - pub total_events_per_sec: f64, - pub checksum: u64, - pub splits_decode: BsonQmActionDecodeStats, - pub dividends_decode: BsonQmActionDecodeStats, - pub curate_stats: crate::curate_adj::CurateAdjFactorsStats, -} - -fn run_curate_adj_cmd_benchmark_tracked( - events: usize, -) -> Result<(CurateAdjCmdBenchReport, PathBuf), CurateAdjCmdBenchError> { - use std::io::{BufWriter, Write}; - - use crate::bson_eod_prices::MILLIS_PER_DAY; - use crate::curate_bars::BARS_1D_SOURCE_EOD; - use crate::run_curate_adj::{run_curate_adj_factors_timed, CurateAdjFactorsArgs}; - use crate::session_close::et_session_close_utc_micros; - - const MIB: f64 = 1_048_576.0; - - let temp = BenchTempDir::new_in_with_prefix( - &std::env::temp_dir(), - "curate-etl-bench-curate-adj-cmd", - ) - .map_err(|(path, source)| CurateAdjCmdBenchError::FixtureIo { path, source })?; - let temp_path = temp.path.clone(); - - let splits_path = temp.path.join("qmSplits.bson"); - let dividends_path = temp.path.join("qmDividends.bson"); - let mapping_path = temp.path.join("provider_mapping.tsv"); - let bars_root = temp.path.join("bars_root"); - let out_dir = temp.path.join("out"); - - fs::create_dir_all(&bars_root).map_err(|source| CurateAdjCmdBenchError::FixtureIo { - path: bars_root.clone(), - source, - })?; - - let key_count = CURATE_ADJ_CMD_BENCH_KEY_COUNT; - - if events == 0 { - for p in [&splits_path, ÷nds_path, &mapping_path] { - File::create(p).map_err(|source| CurateAdjCmdBenchError::FixtureIo { - path: p.clone(), - source, - })?; - } - let session_date = ymd_to_epoch_days(2024, 1, 15).expect("valid zero-event bar date"); - let ts_micros = et_session_close_utc_micros(session_date).expect("valid zero-event bar ts"); - write_bars_1d_dataset( - &bars_root, - &[Bars1dParquetRow { - listing_id: 1, - ts_micros, - session_date, - open: 100.0, - high: 101.0, - low: 99.0, - close: 100.0, - volume: 1_000.0, - vwap: None, - currency: Cow::Borrowed("USD"), - source: Cow::Borrowed(BARS_1D_SOURCE_EOD), - known_at_micros: ts_micros, - }], - Bars1dWriteOptions::default(), - ) - .map_err(CurateAdjCmdBenchError::FixtureBars)?; - let args = CurateAdjFactorsArgs { - qm_splits: splits_path, - qm_dividends: dividends_path, - provider_mapping: mapping_path, - bars_1d_dir: bars_root.join("bars_1d"), - out_dir: out_dir.clone(), - }; - let timed = run_curate_adj_factors_timed(&args).map_err(CurateAdjCmdBenchError::Run)?; - let read_back_rows = - verify_parquet_adj_snapshot_row_count(&out_dir, timed.report.write_stats.rows_written) - .map_err(CurateAdjCmdBenchError::Verify)?; - let report = CurateAdjCmdBenchReport { - events: 0, - key_count, - bars_files_read: timed.report.bars_files_read, - bars_rows_loaded: timed.report.bars_rows_loaded, - bars_listings_indexed: timed.report.bars_listings_indexed, - splits_docs_framed: 0, - splits_bytes_read: 0, - dividends_docs_framed: 0, - dividends_bytes_read: 0, - dividends_with_prev_close: 0, - dividends_without_prev_close: 0, - rows_out: 0, - listings_out: 0, - files_written: timed.report.write_stats.files_written, - row_groups_written: timed.report.write_stats.row_groups_written, - bytes_written: timed.report.write_stats.bytes_written, - read_back_rows, - bars_load_elapsed_ms: 0.0, - bars_load_rows_per_sec: 0.0, - decode_elapsed_ms: 0.0, - decode_events_per_sec: 0.0, - input_mb_per_sec: 0.0, - curate_elapsed_ms: 0.0, - curate_events_per_sec: 0.0, - write_elapsed_ms: 0.0, - write_rows_per_sec: 0.0, - write_mb_per_sec: 0.0, - total_elapsed_ms: 0.0, - total_events_per_sec: 0.0, - checksum: timed.checksum, - splits_decode: timed.report.splits_decode, - dividends_decode: timed.report.dividends_decode, - curate_stats: timed.report.curate_stats, - }; - drop(temp); - return Ok((report, temp_path)); - } - - let mapped_keys = key_count - (key_count / 50).max(1); - let mut all_listings: Vec = Vec::with_capacity(mapped_keys + (mapped_keys / 50) + 1); - - // 1. Write `provider_mapping.tsv`. - { - let mut map_w = BufWriter::with_capacity( - 256 * 1024, - File::create(&mapping_path).map_err(|source| CurateAdjCmdBenchError::FixtureIo { - path: mapping_path.clone(), - source, - })?, - ); - for k in 0..mapped_keys { - let listing_id = (k + 1) as i32; - let suffix = if listing_id % 4 == 0 { "TO" } else { "US" }; - let qm_code = format!("QM{k:05}:{suffix}"); - if k % 50 == 1 { - let reuse_lid = (mapped_keys + k + 10) as i32; - writeln!(map_w, "qm\t{qm_code}\t1990-01-01\t2016-06-30\t{listing_id}").map_err( - |source| CurateAdjCmdBenchError::FixtureIo { - path: mapping_path.clone(), - source, - }, - )?; - writeln!(map_w, "qm\t{qm_code}\t2017-01-01\t\t{reuse_lid}").map_err(|source| { - CurateAdjCmdBenchError::FixtureIo { - path: mapping_path.clone(), - source, - } - })?; - all_listings.push(listing_id); - all_listings.push(reuse_lid); - } else if k % 50 == 2 { - let base_lid = (k - 2 + 1) as i32; - let alias_suffix = if base_lid % 4 == 0 { "TO" } else { "US" }; - let alias_qm_code = format!("QM{k:05}:{alias_suffix}"); - writeln!(map_w, "qm\t{alias_qm_code}\t1990-01-01\t\t{base_lid}").map_err( - |source| CurateAdjCmdBenchError::FixtureIo { - path: mapping_path.clone(), - source, - }, - )?; - } else { - writeln!(map_w, "qm\t{qm_code}\t1990-01-01\t\t{listing_id}").map_err(|source| { - CurateAdjCmdBenchError::FixtureIo { - path: mapping_path.clone(), - source, - } - })?; - all_listings.push(listing_id); - } - } - map_w - .flush() - .map_err(|source| CurateAdjCmdBenchError::FixtureIo { - path: mapping_path.clone(), - source, - })?; - } - - // 2. Write a compact multi-year `bars_1d` Parquet dataset (16 yearly bars per listing, 2010..=2025). - all_listings.sort_unstable(); - all_listings.dedup(); - let bar_dates: Vec<(i32, i64)> = (2010..=2025) - .map(|year| { - let mut d = ymd_to_epoch_days(year, 1, 15).expect("valid bar date"); - let dow = (d + 4).rem_euclid(7); - if dow == 6 { - d += 2; - } else if dow == 0 { - d += 1; - } - let ts = et_session_close_utc_micros(d).expect("valid bar ts"); - (d, ts) - }) - .collect(); - { - let mut bar_rows: Vec = - Vec::with_capacity(all_listings.len() * bar_dates.len()); - for &lid in &all_listings { - let curr: Cow<'static, str> = if lid % 4 == 0 { - Cow::Borrowed("CAD") - } else { - Cow::Borrowed("USD") - }; - let base_price = 30.0 + ((lid % 200) as f64); - for (yi, &(session_date, ts_micros)) in bar_dates.iter().enumerate() { - let close = base_price + (yi as f64) * 1.5; - bar_rows.push(Bars1dParquetRow { - listing_id: lid, - ts_micros, - session_date, - open: close - 0.5, - high: close + 1.0, - low: close - 1.0, - close, - volume: 250_000.0, - vwap: None, - currency: curr.clone(), - source: Cow::Borrowed(BARS_1D_SOURCE_EOD), - known_at_micros: ts_micros, - }); - } - } - write_bars_1d_dataset(&bars_root, &bar_rows, Bars1dWriteOptions::default()) - .map_err(CurateAdjCmdBenchError::FixtureBars)?; - } - - // Weekday pool strictly after 2010-01-18 so dividends have a valid `prev_close` in `bars_1d`. - let main_days: Vec = build_weekday_pool(2010, 2025) - .into_iter() - .filter(|&d| d > bar_dates[0].0) - .collect(); - let main_strs: Vec = main_days.iter().copied().map(format_ymd_string).collect(); - let main_len = main_days.len(); - let stride = choose_coprime_stride(main_len, 19); - - let qm_codes: Vec = (0..mapped_keys) - .map(|k| { - let lid = if k % 50 == 2 { - (k - 2 + 1) as i32 - } else { - (k + 1) as i32 - }; - let suffix = if lid % 4 == 0 { "TO" } else { "US" }; - format!("QM{k:05}:{suffix}") - }) - .collect(); - - let non_alias_keys: Vec = (0..mapped_keys) - .filter(|&k| k % 50 != 0 && k % 50 != 2) - .collect(); - let alias_base_keys: Vec = (0..mapped_keys) - .filter(|&k| k % 50 == 0 && k + 2 < mapped_keys) - .collect(); - - let mut alias_split_cursors: Vec = (0..alias_base_keys.len()) - .map(|idx| (idx * 11) % main_len) - .collect(); - let mut alias_div_cursors: Vec = (0..alias_base_keys.len()) - .map(|idx| (idx * 23 + 7) % main_len) - .collect(); - - let mut rng = SplitMix64::new(CURATE_ADJ_CMD_BENCH_SEED); - let split_target = (events * 4) / 100; - let div_target = events - split_target; - - // 3. Stream-write `qmSplits.bson`. - { - const RATIOS: [f64; 6] = [2.0, 3.0, 4.0, 10.0, 0.5, 0.25]; - let mut splits_w = BufWriter::with_capacity( - 256 * 1024, - File::create(&splits_path).map_err(|source| CurateAdjCmdBenchError::FixtureIo { - path: splits_path.clone(), - source, - })?, - ); - let mut pending_alias: Option<(usize, usize, f64)> = None; - for i in 0..split_target { - let mut oid_bytes = [0u8; 12]; - oid_bytes[4..12].copy_from_slice(&(i as u64).to_be_bytes()); - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("_id"), ObjectId::from_bytes(oid_bytes)); - - if let Some((alias_k, date_idx, ratio)) = pending_alias.take() { - doc.append(cstr!("qmSearchCode"), qm_codes[alias_k].as_str()); - doc.append(cstr!("date"), main_strs[date_idx].as_str()); - doc.append(cstr!("splitratio"), ratio); - doc.append(cstr!("usdFxRate"), 1_i32); - } else { - let roll = rng.next_u64() % 1_000; - if roll < 5 { - // Malformed date -> decode reject. - doc.append(cstr!("qmSearchCode"), qm_codes[0].as_str()); - doc.append(cstr!("date"), "2023-02-29"); - doc.append(cstr!("splitratio"), 2.0_f64); - } else if roll < 55 { - // 1:1 no-op split. - let k = non_alias_keys[(rng.next_u64() as usize) % non_alias_keys.len()]; - let date_idx = (rng.next_u64() as usize) % main_len; - doc.append(cstr!("qmSearchCode"), qm_codes[k].as_str()); - doc.append(cstr!("date"), main_strs[date_idx].as_str()); - doc.append(cstr!("splitratio"), 1.0_f64); - } else if roll < 85 { - // Unmapped QM code. - let date_idx = (rng.next_u64() as usize) % main_len; - doc.append(cstr!("qmSearchCode"), "QM_UNMAP:US"); - doc.append(cstr!("date"), main_strs[date_idx].as_str()); - doc.append(cstr!("splitratio"), 2.0_f64); - } else if roll < 185 && i + 1 < split_target && !alias_base_keys.is_empty() { - let slot = (rng.next_u64() as usize) % alias_base_keys.len(); - let base_k = alias_base_keys[slot]; - let date_idx = alias_split_cursors[slot]; - alias_split_cursors[slot] = (date_idx + stride) % main_len; - let ratio = RATIOS[(rng.next_u64() as usize) % RATIOS.len()]; - doc.append(cstr!("qmSearchCode"), qm_codes[base_k].as_str()); - doc.append(cstr!("date"), main_strs[date_idx].as_str()); - doc.append(cstr!("splitratio"), ratio); - doc.append(cstr!("usdFxRate"), 1_i32); - pending_alias = Some((base_k + 2, date_idx, ratio)); - } else { - let k = non_alias_keys[(rng.next_u64() as usize) % non_alias_keys.len()]; - let date_idx = (rng.next_u64() as usize) % main_len; - let ratio = RATIOS[(rng.next_u64() as usize) % RATIOS.len()]; - doc.append(cstr!("qmSearchCode"), qm_codes[k].as_str()); - if i % 20 == 0 { - doc.append( - cstr!("date"), - DateTime::from_millis(i64::from(main_days[date_idx]) * MILLIS_PER_DAY), - ); - } else { - doc.append(cstr!("date"), main_strs[date_idx].as_str()); - } - doc.append(cstr!("splitratio"), ratio); - doc.append(cstr!("usdFxRate"), 1_i32); - } - } - - splits_w - .write_all(doc.as_bytes()) - .map_err(|source| CurateAdjCmdBenchError::FixtureIo { - path: splits_path.clone(), - source, - })?; - } - splits_w - .flush() - .map_err(|source| CurateAdjCmdBenchError::FixtureIo { - path: splits_path.clone(), - source, - })?; - } - - // 4. Stream-write `qmDividends.bson`. - { - let mut divs_w = BufWriter::with_capacity( - 512 * 1024, - File::create(÷nds_path).map_err(|source| CurateAdjCmdBenchError::FixtureIo { - path: dividends_path.clone(), - source, - })?, - ); - let mut pending_alias: Option<(usize, usize, f64, &'static str)> = None; - for i in 0..div_target { - let mut oid_bytes = [0u8; 12]; - oid_bytes[0] = 2; - oid_bytes[4..12].copy_from_slice(&(i as u64).to_be_bytes()); - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("_id"), ObjectId::from_bytes(oid_bytes)); - - if let Some((alias_k, date_idx, cash, curr)) = pending_alias.take() { - doc.append(cstr!("qmSearchCode"), qm_codes[alias_k].as_str()); - doc.append(cstr!("date"), main_strs[date_idx].as_str()); - doc.append(cstr!("amount"), cash); - doc.append(cstr!("currency"), curr); - doc.append(cstr!("usdFxRate"), 1_i32); - } else { - let roll = rng.next_u64() % 1_000; - if roll < 5 { - // Malformed date or negative amount -> decode reject. - doc.append(cstr!("qmSearchCode"), qm_codes[0].as_str()); - if i % 2 == 0 { - doc.append(cstr!("date"), "2023-02-29"); - doc.append(cstr!("amount"), 0.25_f64); - } else { - doc.append(cstr!("date"), "2023-06-15"); - doc.append(cstr!("amount"), -0.25_f64); - } - doc.append(cstr!("currency"), "USD"); - doc.append(cstr!("usdFxRate"), 1_i32); - } else if roll < 20 { - // Zero cash dividend. - let k = non_alias_keys[(rng.next_u64() as usize) % non_alias_keys.len()]; - let lid = (k + 1) as i32; - let curr = if lid % 4 == 0 { "CAD" } else { "USD" }; - let date_idx = (rng.next_u64() as usize) % main_len; - doc.append(cstr!("qmSearchCode"), qm_codes[k].as_str()); - doc.append(cstr!("date"), main_strs[date_idx].as_str()); - doc.append(cstr!("amount"), 0.0_f64); - doc.append(cstr!("currency"), curr); - doc.append(cstr!("usdFxRate"), 1_i32); - } else if roll < 50 { - // Unmapped dividend. - let date_idx = (rng.next_u64() as usize) % main_len; - doc.append(cstr!("qmSearchCode"), "QM_UNMAP:US"); - doc.append(cstr!("date"), main_strs[date_idx].as_str()); - doc.append(cstr!("amount"), 0.50_f64); - doc.append(cstr!("currency"), "USD"); - doc.append(cstr!("usdFxRate"), 1_i32); - } else if roll < 80 { - // Pre-first-bar date -> mapped but missing `prev_close`. - let k = non_alias_keys[(rng.next_u64() as usize) % non_alias_keys.len()]; - let lid = (k + 1) as i32; - let curr = if lid % 4 == 0 { "CAD" } else { "USD" }; - let cash = (5 + (rng.next_u64() % 150)) as f64 / 100.0; - doc.append(cstr!("qmSearchCode"), qm_codes[k].as_str()); - doc.append(cstr!("date"), "2009-06-15"); - doc.append(cstr!("amount"), cash); - doc.append(cstr!("currency"), curr); - doc.append(cstr!("usdFxRate"), 1_i32); - } else if roll < 100 { - // Dedicated mismatch keys (`k % 50 == 3`) always emit the opposite currency - // of their `bars_1d` bars so no single listing ever gets two conflicting - // dividend currencies on the same `ex_date`. - let k = non_alias_keys[(rng.next_u64() as usize) % non_alias_keys.len()]; - let lid = (k + 1) as i32; - let curr = if k % 50 == 3 { - if lid % 4 == 0 { "USD" } else { "CAD" } - } else if lid % 4 == 0 { - "CAD" - } else { - "USD" - }; - let date_idx = (rng.next_u64() as usize) % main_len; - let cash = (5 + (rng.next_u64() % 150)) as f64 / 100.0; - doc.append(cstr!("qmSearchCode"), qm_codes[k].as_str()); - doc.append(cstr!("date"), main_strs[date_idx].as_str()); - doc.append(cstr!("amount"), cash); - doc.append(cstr!("currency"), curr); - doc.append(cstr!("usdFxRate"), 1_i32); - } else if roll < 160 && i + 1 < div_target && !alias_base_keys.is_empty() { - let slot = (rng.next_u64() as usize) % alias_base_keys.len(); - let base_k = alias_base_keys[slot]; - let base_lid = (base_k + 1) as i32; - let curr = if base_lid % 4 == 0 { "CAD" } else { "USD" }; - let date_idx = alias_div_cursors[slot]; - alias_div_cursors[slot] = (date_idx + stride) % main_len; - let cash = (10 + (rng.next_u64() % 200)) as f64 / 100.0; - doc.append(cstr!("qmSearchCode"), qm_codes[base_k].as_str()); - doc.append(cstr!("date"), main_strs[date_idx].as_str()); - doc.append(cstr!("amount"), cash); - doc.append(cstr!("currency"), curr); - doc.append(cstr!("usdFxRate"), 1_i32); - pending_alias = Some((base_k + 2, date_idx, cash, curr)); - } else { - let k = non_alias_keys[(rng.next_u64() as usize) % non_alias_keys.len()]; - let lid = (k + 1) as i32; - let curr = if k % 50 == 3 { - if lid % 4 == 0 { "USD" } else { "CAD" } - } else if lid % 4 == 0 { - "CAD" - } else { - "USD" - }; - let date_idx = (rng.next_u64() as usize) % main_len; - let cash = (5 + (rng.next_u64() % 250)) as f64 / 100.0; - doc.append(cstr!("qmSearchCode"), qm_codes[k].as_str()); - if i % 20 == 0 { - doc.append( - cstr!("date"), - DateTime::from_millis(i64::from(main_days[date_idx]) * MILLIS_PER_DAY), - ); - } else { - doc.append(cstr!("date"), main_strs[date_idx].as_str()); - } - doc.append(cstr!("amount"), cash); - doc.append(cstr!("currency"), curr); - doc.append(cstr!("usdFxRate"), 1_i32); - } - } - - divs_w - .write_all(doc.as_bytes()) - .map_err(|source| CurateAdjCmdBenchError::FixtureIo { - path: dividends_path.clone(), - source, - })?; - } - divs_w - .flush() - .map_err(|source| CurateAdjCmdBenchError::FixtureIo { - path: dividends_path.clone(), - source, - })?; - } - - // 5. Run stage-timed end-to-end command and verify Parquet footer row count. - let args = CurateAdjFactorsArgs { - qm_splits: splits_path, - qm_dividends: dividends_path, - provider_mapping: mapping_path, - bars_1d_dir: bars_root.join("bars_1d"), - out_dir: out_dir.clone(), - }; - let timed = run_curate_adj_factors_timed(&args).map_err(CurateAdjCmdBenchError::Run)?; - let read_back_rows = - verify_parquet_adj_snapshot_row_count(&out_dir, timed.report.write_stats.rows_written) - .map_err(CurateAdjCmdBenchError::Verify)?; - - let bars_load_elapsed_ms = timed.bars_load_elapsed_secs * 1_000.0; - let decode_elapsed_ms = timed.decode_elapsed_secs * 1_000.0; - let curate_elapsed_ms = timed.curate_elapsed_secs * 1_000.0; - let write_elapsed_ms = timed.write_elapsed_secs * 1_000.0; - let total_elapsed_secs = timed.bars_load_elapsed_secs - + timed.decode_elapsed_secs - + timed.curate_elapsed_secs - + timed.write_elapsed_secs; - let total_elapsed_ms = total_elapsed_secs * 1_000.0; - - let (bars_load_rows_per_sec, _) = - compute_rates(timed.report.bars_rows_loaded, timed.bars_load_elapsed_secs); - let (decode_events_per_sec, _) = compute_rates(events, timed.decode_elapsed_secs); - let decoded_events = timed.report.curate_stats.splits_in + timed.report.curate_stats.dividends_in; - let (curate_events_per_sec, _) = compute_rates(decoded_events, timed.curate_elapsed_secs); - let (write_rows_per_sec, _) = - compute_rates(timed.report.write_stats.rows_written, timed.write_elapsed_secs); - let (total_events_per_sec, _) = compute_rates(events, total_elapsed_secs); - - let total_input_bytes = timed.report.splits_bytes_read + timed.report.dividends_bytes_read; - let input_mb_per_sec = if timed.decode_elapsed_secs > 0.0 { - (total_input_bytes as f64 / MIB) / timed.decode_elapsed_secs - } else { - 0.0 - }; - let write_mb_per_sec = if timed.write_elapsed_secs > 0.0 { - (timed.report.write_stats.bytes_written as f64 / MIB) / timed.write_elapsed_secs - } else { - 0.0 - }; - - let report = CurateAdjCmdBenchReport { - events, - key_count, - bars_files_read: timed.report.bars_files_read, - bars_rows_loaded: timed.report.bars_rows_loaded, - bars_listings_indexed: timed.report.bars_listings_indexed, - splits_docs_framed: timed.report.splits_docs_framed, - splits_bytes_read: timed.report.splits_bytes_read, - dividends_docs_framed: timed.report.dividends_docs_framed, - dividends_bytes_read: timed.report.dividends_bytes_read, - dividends_with_prev_close: timed.report.dividends_with_prev_close, - dividends_without_prev_close: timed.report.dividends_without_prev_close, - rows_out: timed.report.curate_stats.rows_out, - listings_out: timed.report.curate_stats.listings_out, - files_written: timed.report.write_stats.files_written, - row_groups_written: timed.report.write_stats.row_groups_written, - bytes_written: timed.report.write_stats.bytes_written, - read_back_rows, - bars_load_elapsed_ms, - bars_load_rows_per_sec, - decode_elapsed_ms, - decode_events_per_sec, - input_mb_per_sec, - curate_elapsed_ms, - curate_events_per_sec, - write_elapsed_ms, - write_rows_per_sec, - write_mb_per_sec, - total_elapsed_ms, - total_events_per_sec, - checksum: timed.checksum, - splits_decode: timed.report.splits_decode, - dividends_decode: timed.report.dividends_decode, - curate_stats: timed.report.curate_stats, - }; - - drop(temp); - Ok((report, temp_path)) -} - -/// Runs the fixed-seed end-to-end `curate-adj-factors` file -> Parquet benchmark for `events` -/// synthetic `qmSplits` (~4%) and `qmDividends` (~96%) BSON documents with a multi-year `bars_1d` -/// Parquet dataset. -pub fn run_curate_adj_cmd_benchmark( - events: usize, -) -> Result { - let (report, _) = run_curate_adj_cmd_benchmark_tracked(events)?; - Ok(report) -} - -pub const DEFAULT_CURATE_CORPORATE_ACTIONS_BENCH_EVENTS: usize = 520_000; -const CURATE_CORPORATE_ACTIONS_BENCH_SEED: u64 = 0x570C_4B07_C04A_AC72; -const CURATE_CORPORATE_ACTIONS_BENCH_KEY_COUNT: usize = 20_000; - -/// Summary metrics produced by [`run_curate_corporate_actions_benchmark`]. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct CurateCorporateActionsBenchReport { - pub events: usize, - pub splits_in: usize, - pub dividends_in: usize, - pub delistings_in: usize, - pub key_count: usize, - pub rows_out: usize, - pub listings_out: usize, - pub stage_elapsed_ms: f64, - pub stage_events_per_sec: f64, - pub stage_ns_per_event: f64, - pub parquet_elapsed_ms: f64, - pub parquet_rows_per_sec: f64, - pub total_elapsed_ms: f64, - pub total_events_per_sec: f64, - pub files_written: usize, - pub row_groups_written: usize, - pub bytes_written: u64, - pub read_back_rows: usize, - pub checksum: u64, - pub stats: crate::curate_corporate_actions::CurateCorporateActionsStats, -} - -struct CurateCorporateActionsBenchFixture { - splits: Vec<(String, SplitActionEvent)>, - dividends: Vec<(String, DividendActionEvent)>, - delistings: Vec>, - provider_mapping: ProviderMappingTable, - key_count: usize, -} - -fn build_curate_corporate_actions_bench_fixture( - events: usize, -) -> CurateCorporateActionsBenchFixture { - const KEY_COUNT: usize = CURATE_CORPORATE_ACTIONS_BENCH_KEY_COUNT; - const SINGLE_RANGE_END: usize = 18_000; - const REUSE_END: usize = 19_000; - const ALIAS_END: usize = 19_500; - const ALIAS_COUNT: usize = ALIAS_END - REUSE_END; - const OTC_SUCC_COUNT: usize = 500; - - let valid_from_start = ymd_to_epoch_days(1970, 1, 1).expect("valid start"); - let reuse_end = ymd_to_epoch_days(2015, 6, 30).expect("valid reuse end"); - let reuse_resume = ymd_to_epoch_days(2016, 1, 1).expect("valid reuse resume"); - let in_range_start = ymd_to_epoch_days(1977, 1, 3).expect("valid in-range start"); - let in_range_end = ymd_to_epoch_days(2025, 12, 31).expect("valid in-range end"); - let in_range_span = (in_range_end - in_range_start + 1) as u64; - let pre_1976_day = ymd_to_epoch_days(1975, 6, 15).expect("valid pre-1976 day"); - - let keys: Vec = (0..KEY_COUNT).map(|i| format!("CA{i:05}")).collect(); - let otc_keys: Vec = (0..OTC_SUCC_COUNT).map(|i| format!("OTC{i:05}")).collect(); - - let mut mapping_rows: Vec = - Vec::with_capacity(KEY_COUNT + (REUSE_END - SINGLE_RANGE_END) + OTC_SUCC_COUNT); - for (i, key) in keys.iter().enumerate() { - if i < SINGLE_RANGE_END { - mapping_rows.push(ProviderMappingRow { - source: "qm".to_string(), - source_id: key.clone(), - valid_from: valid_from_start, - valid_to: None, - listing_id: (i + 1) as i32, - }); - } else if i < REUSE_END { - mapping_rows.push(ProviderMappingRow { - source: "qm".to_string(), - source_id: key.clone(), - valid_from: valid_from_start, - valid_to: Some(reuse_end), - listing_id: (i + 1) as i32, - }); - mapping_rows.push(ProviderMappingRow { - source: "qm".to_string(), - source_id: key.clone(), - valid_from: reuse_resume, - valid_to: None, - listing_id: (i + 100_001) as i32, - }); - } else if i < ALIAS_END { - let alias_lid = (i - REUSE_END + 1) as i32; - mapping_rows.push(ProviderMappingRow { - source: "qm".to_string(), - source_id: key.clone(), - valid_from: valid_from_start, - valid_to: None, - listing_id: alias_lid, - }); - } - } - for (i, otc_key) in otc_keys.iter().enumerate() { - mapping_rows.push(ProviderMappingRow { - source: "qm".to_string(), - source_id: otc_key.clone(), - valid_from: valid_from_start, - valid_to: None, - listing_id: (500_001 + i) as i32, - }); - } - - let provider_mapping = - ProviderMappingTable::from_rows(mapping_rows).expect("valid bench provider mapping"); - - let mut rng = SplitMix64::new(CURATE_CORPORATE_ACTIONS_BENCH_SEED); - let mut splits: Vec<(String, SplitActionEvent)> = Vec::with_capacity(events / 25 + 64); - let mut dividends: Vec<(String, DividendActionEvent)> = Vec::with_capacity(events); - let mut delistings: Vec> = - Vec::with_capacity(events / 90 + 32); - - let mut generated = 0usize; - while generated < events { - let r1 = rng.next_u64(); - let r2 = rng.next_u64(); - let kind_roll = r1 % 1_000; - let is_pre_1976 = ((r1 >> 10) % 200) == 0; - let ex_date = if is_pre_1976 { - pre_1976_day - } else { - in_range_start + ((r2 % in_range_span) as i32) - }; - - if kind_roll < 36 { - // ~3.6% splits (~18.7k at 520k), including 1:1 no-ops and alias collisions. - let is_alias_target = !is_pre_1976 && ((r1 >> 18) % 10) == 0; - let key_idx = if is_alias_target { - ((r2 >> 24) as usize) % ALIAS_COUNT - } else { - ((r2 >> 24) as usize) % KEY_COUNT - }; - let is_noop = ((r1 >> 22) % 50) == 0; - let ratio = if is_noop { - 1.0 - } else { - SAMPLE_RATIOS[((r1 >> 28) as usize) % SAMPLE_RATIOS.len()] - }; - let decl_roll = (r1 >> 36) % 100; - let declared_date = if decl_roll < 80 { - Some(ex_date - 21) - } else if decl_roll < 98 { - None - } else { - Some(ex_date + 3) - }; - - let ev = SplitActionEvent { - ex_date, - ratio, - declared_date, - }; - splits.push((keys[key_idx].clone(), ev)); - generated += 1; - - if is_alias_target && !is_noop && generated < events { - let alias_key = keys[REUSE_END + key_idx].clone(); - let alias_ratio = if ((r1 >> 44) & 1) == 0 { - ratio - } else { - ratio * 1.5 - }; - splits.push(( - alias_key, - SplitActionEvent { - ex_date, - ratio: alias_ratio, - declared_date, - }, - )); - generated += 1; - } - } else if kind_roll < 990 { - // ~95.4% dividends (~496k at 520k), USD/CAD, 0.0 drops, multi-dividends, alias dups. - let key_idx = ((r2 >> 24) as usize) % KEY_COUNT; - let is_zero = ((r1 >> 18) % 100) == 0; - let cash = if is_zero { - 0.0 - } else { - (((r1 >> 26) % 250) + 1) as f64 * 0.01 - }; - let currency = if ((r1 >> 34) & 3) == 0 { "CAD" } else { "USD" }; - let decl_roll = (r1 >> 38) % 100; - let declared_date = if decl_roll < 80 { - Some(ex_date - 21) - } else if decl_roll < 98 { - None - } else { - Some(ex_date + 3) - }; - - dividends.push(( - keys[key_idx].clone(), - DividendActionEvent { - ex_date, - cash, - currency: currency.to_string(), - declared_date, - }, - )); - generated += 1; - - if !is_zero && !is_pre_1976 && generated < events { - if ((r1 >> 46) % 100) == 0 { - // Same-key same-day special dividend. - dividends.push(( - keys[key_idx].clone(), - DividendActionEvent { - ex_date, - cash: cash * 2.0, - currency: currency.to_string(), - declared_date, - }, - )); - generated += 1; - } else if key_idx < ALIAS_COUNT && ((r1 >> 52) % 25) == 0 { - // Identical cross-key alias dividend. - dividends.push(( - keys[REUSE_END + key_idx].clone(), - DividendActionEvent { - ex_date, - cash, - currency: currency.to_string(), - declared_date, - }, - )); - generated += 1; - } - } - } else { - // ~1.0% delistings (~5.2k at 520k): OTC transfers (valid/unmapped/self), -0.3, -1.0, none. - let key_idx = ((r2 >> 24) as usize) % KEY_COUNT; - let outcome_roll = (r1 >> 18) % 100; - let ev = if outcome_roll < 35 { - let succ_idx = ((r2 >> 40) as usize) % OTC_SUCC_COUNT; - DelistingOutcomeEvent { - delist_date: ex_date, - successor_key: Some(otc_keys[succ_idx].clone()), - terminal_return: None, - } - } else if outcome_roll < 45 { - DelistingOutcomeEvent { - delist_date: ex_date, - successor_key: Some("OTC_UNMAPPED".to_string()), - terminal_return: None, - } - } else if outcome_roll < 55 { - DelistingOutcomeEvent { - delist_date: ex_date, - successor_key: Some(keys[key_idx].clone()), - terminal_return: None, - } - } else if outcome_roll < 75 { - DelistingOutcomeEvent { - delist_date: ex_date, - successor_key: None, - terminal_return: Some(-0.3), - } - } else if outcome_roll < 90 { - DelistingOutcomeEvent { - delist_date: ex_date, - successor_key: None, - terminal_return: Some(-1.0), - } - } else { - DelistingOutcomeEvent { - delist_date: ex_date, - successor_key: None, - terminal_return: None, - } - }; - let from_listing_id = if outcome_roll < 55 { - if key_idx < SINGLE_RANGE_END { - Some((key_idx + 1) as i32) - } else if key_idx < REUSE_END { - if ex_date >= reuse_resume { - Some((key_idx + 100_001) as i32) - } else { - Some((key_idx + 1) as i32) - } - } else if key_idx < ALIAS_END { - Some((key_idx - REUSE_END + 1) as i32) - } else { - None - } - } else { - None - }; - delistings.push(crate::curate_corporate_actions::CurateDelistingInput { - key: keys[key_idx].clone(), - event: ev, - from_listing_id, - }); - generated += 1; - } - } - - CurateCorporateActionsBenchFixture { - splits, - dividends, - delistings, - provider_mapping, - key_count: KEY_COUNT, - } -} - -fn run_curate_corporate_actions_benchmark_tracked( - events: usize, -) -> Result< - (CurateCorporateActionsBenchReport, PathBuf), - crate::curate_corporate_actions::CurateCorporateActionsWriteError, -> { - use crate::curate_corporate_actions::{ - curate_corporate_actions, CurateCorporateActionsStats, CurateCorporateActionsWriteError, - }; - - let temp = BenchTempDir::new_in_with_prefix( - &std::env::temp_dir(), - "curate-etl-bench-curate-corp-actions", - ) - .map_err(|(path, source)| { - CurateCorporateActionsWriteError::Parquet(ParquetCorporateActionsError::Io { path, source }) - })?; - let temp_path = temp.path.clone(); - - if events == 0 { - let mapping = ProviderMappingTable::default(); - let curated = curate_corporate_actions( - std::iter::empty::<(String, SplitActionEvent)>(), - std::iter::empty::<(String, DividendActionEvent)>(), - std::iter::empty::<(String, DelistingOutcomeEvent)>(), - "qm", - &mapping, - )?; - let write_stats = write_corporate_actions_dataset( - &temp.path, - &curated.rows, - CorporateActionsWriteOptions::default(), - )?; - let read_back_rows = verify_parquet_corporate_actions_row_count(&temp.path, 0)?; - drop(temp); - return Ok(( - CurateCorporateActionsBenchReport { - events: 0, - splits_in: 0, - dividends_in: 0, - delistings_in: 0, - key_count: CURATE_CORPORATE_ACTIONS_BENCH_KEY_COUNT, - rows_out: 0, - listings_out: 0, - stage_elapsed_ms: 0.0, - stage_events_per_sec: 0.0, - stage_ns_per_event: 0.0, - parquet_elapsed_ms: 0.0, - parquet_rows_per_sec: 0.0, - total_elapsed_ms: 0.0, - total_events_per_sec: 0.0, - files_written: write_stats.files_written, - row_groups_written: write_stats.row_groups_written, - bytes_written: write_stats.bytes_written, - read_back_rows, - checksum: 0, - stats: CurateCorporateActionsStats::default(), - }, - temp_path, - )); - } - - let fixture = build_curate_corporate_actions_bench_fixture(events); - let splits_in = fixture.splits.len(); - let dividends_in = fixture.dividends.len(); - let delistings_in = fixture.delistings.len(); - let key_count = fixture.key_count; - - // 1. Time pure in-memory curation stage. - let stage_start = Instant::now(); - let curated = curate_corporate_actions( - fixture.splits, - fixture.dividends, - fixture.delistings, - "qm", - &fixture.provider_mapping, - )?; - let stage_elapsed_secs = stage_start.elapsed().as_secs_f64(); - let stage_elapsed_ms = stage_elapsed_secs * 1_000.0; - - let mut hash = 0u64; - for row in &curated.rows { - hash = mix_u64(hash, row.listing_id as u64); - hash = mix_u64(hash, row.ex_date as u64); - hash = mix_u64(hash, row.declared_date.map_or(u64::MAX, |d| d as u64)); - hash = mix_u64(hash, row.kind as u64); - hash = mix_u64(hash, row.ratio.map_or(0, f64::to_bits)); - hash = mix_u64(hash, row.cash_amount.map_or(0, f64::to_bits)); - if let Some(curr) = row.currency.as_deref() { - hash = mix_str_u64(hash, curr); - } - hash = mix_u64( - hash, - row.successor_listing_id.map_or(u64::MAX, |id| id as u64), - ); - hash = mix_u64(hash, row.terminal_return.map_or(0, f64::to_bits)); - hash = mix_u64(hash, row.known_at_micros as u64); - hash = mix_u64(hash, row.known_at_source as u64); - } - let checksum = black_box(hash); - - // 2. Separately time Parquet write to temp dir. - let parquet_start = Instant::now(); - let write_stats = write_corporate_actions_dataset( - &temp.path, - &curated.rows, - CorporateActionsWriteOptions::default(), - )?; - let parquet_elapsed_secs = parquet_start.elapsed().as_secs_f64(); - let parquet_elapsed_ms = parquet_elapsed_secs * 1_000.0; - - let read_back_rows = - verify_parquet_corporate_actions_row_count(&temp.path, curated.rows.len())?; - - let (stage_events_per_sec, stage_ns_per_event) = compute_rates(events, stage_elapsed_secs); - let (parquet_rows_per_sec, _) = compute_rates(curated.rows.len(), parquet_elapsed_secs); - let total_elapsed_secs = stage_elapsed_secs + parquet_elapsed_secs; - let total_elapsed_ms = total_elapsed_secs * 1_000.0; - let (total_events_per_sec, _) = compute_rates(events, total_elapsed_secs); - - let report = CurateCorporateActionsBenchReport { - events, - splits_in, - dividends_in, - delistings_in, - key_count, - rows_out: curated.stats.rows_out, - listings_out: curated.stats.listings_out, - stage_elapsed_ms, - stage_events_per_sec, - stage_ns_per_event, - parquet_elapsed_ms, - parquet_rows_per_sec, - total_elapsed_ms, - total_events_per_sec, - files_written: write_stats.files_written, - row_groups_written: write_stats.row_groups_written, - bytes_written: write_stats.bytes_written, - read_back_rows, - checksum, - stats: curated.stats, - }; - - drop(temp); - Ok((report, temp_path)) -} - -/// Runs the fixed-seed `corporate_actions` curation stage + Zstd Parquet write benchmark for -/// `events` source-keyed splits (~3.6%), USD/CAD dividends (~95.4%), and delisting outcomes -/// (~1.0%) across `20,000` `String` keys with multi-range `provider_mapping` reuse gaps, -/// aliases, unmapped/self successors, and pre-1976 dates. -pub fn run_curate_corporate_actions_benchmark( - events: usize, -) -> Result< - CurateCorporateActionsBenchReport, - crate::curate_corporate_actions::CurateCorporateActionsWriteError, -> { - let (report, _) = run_curate_corporate_actions_benchmark_tracked(events)?; - Ok(report) -} - -pub const DEFAULT_CURATE_CORPORATE_ACTIONS_CMD_BENCH_EVENTS: usize = 500_000; -const CURATE_CORPORATE_ACTIONS_CMD_BENCH_SEED: u64 = 0x570C_4B07_C04A_AC7C; - -/// Typed errors returned by [`run_curate_corporate_actions_cmd_benchmark`]. -#[derive(Debug)] -pub enum CurateCorporateActionsCmdBenchError { - FixtureIo { - path: PathBuf, - source: io::Error, - }, - Run(crate::run_curate_corporate_actions::RunCurateCorporateActionsError), - Verify(ParquetCorporateActionsError), -} - -impl std::fmt::Display for CurateCorporateActionsCmdBenchError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Self::FixtureIo { path, source } => { - write!(f, "benchmark fixture I/O '{}': {source}", path.display()) - } - Self::Run(err) => write!(f, "{err}"), - Self::Verify(err) => write!(f, "Parquet verify failed: {err}"), - } - } -} - -impl std::error::Error for CurateCorporateActionsCmdBenchError { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - match self { - Self::FixtureIo { source, .. } => Some(source), - Self::Run(err) => Some(err), - Self::Verify(err) => Some(err), - } - } -} - -/// Summary metrics produced by [`run_curate_corporate_actions_cmd_benchmark`]. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct CurateCorporateActionsCmdBenchReport { - pub events: usize, - pub key_count: usize, - pub splits_docs_framed: u64, - pub splits_bytes_read: u64, - pub dividends_docs_framed: u64, - pub dividends_bytes_read: u64, - pub delistings_rows_loaded: usize, - pub delistings_bytes_read: u64, - pub rows_out: usize, - pub listings_out: usize, - pub files_written: usize, - pub row_groups_written: usize, - pub bytes_written: u64, - pub read_back_rows: usize, - pub decode_elapsed_ms: f64, - pub decode_events_per_sec: f64, - pub input_mb_per_sec: f64, - pub curate_elapsed_ms: f64, - pub curate_events_per_sec: f64, - pub write_elapsed_ms: f64, - pub write_rows_per_sec: f64, - pub write_mb_per_sec: f64, - pub total_elapsed_ms: f64, - pub total_events_per_sec: f64, - pub checksum: u64, - pub splits_decode: BsonQmActionDecodeStats, - pub dividends_decode: BsonQmActionDecodeStats, - pub curate_stats: crate::curate_corporate_actions::CurateCorporateActionsStats, -} - -fn run_curate_corporate_actions_cmd_benchmark_tracked( - events: usize, -) -> Result<(CurateCorporateActionsCmdBenchReport, PathBuf), CurateCorporateActionsCmdBenchError> { - use std::io::{BufWriter, Write}; - - use crate::bson_eod_prices::MILLIS_PER_DAY; - use crate::run_curate_corporate_actions::{ - run_curate_corporate_actions_timed, CurateCorporateActionsArgs, - }; - - const MIB: f64 = 1024.0 * 1024.0; - const KEY_COUNT: usize = CURATE_CORPORATE_ACTIONS_BENCH_KEY_COUNT; - const ENDED_START: usize = 17_500; - const SINGLE_RANGE_END: usize = 18_000; - const REUSE_END: usize = 19_000; - const ALIAS_END: usize = 19_500; - const ALIAS_COUNT: usize = ALIAS_END - REUSE_END; - const OTC_SUCC_COUNT: usize = 500; - - let temp = BenchTempDir::new_in_with_prefix( - &std::env::temp_dir(), - "curate-etl-bench-curate-corp-actions-cmd", - ) - .map_err(|(path, source)| CurateCorporateActionsCmdBenchError::FixtureIo { path, source })?; - let temp_path = temp.path.clone(); - - let splits_path = temp.path.join("qmSplits.bson"); - let dividends_path = temp.path.join("qmDividends.bson"); - let mapping_path = temp.path.join("provider_mapping.tsv"); - let delistings_path = temp.path.join("delistings.tsv"); - let out_dir = temp.path.join("out"); - - if events == 0 { - for p in [&splits_path, ÷nds_path, &mapping_path, &delistings_path] { - File::create(p).map_err(|source| CurateCorporateActionsCmdBenchError::FixtureIo { - path: p.clone(), - source, - })?; - } - let args = CurateCorporateActionsArgs { - qm_splits: splits_path, - qm_dividends: dividends_path, - provider_mapping: mapping_path, - delistings: Some(delistings_path), - out_dir: out_dir.clone(), - }; - let timed = run_curate_corporate_actions_timed(&args) - .map_err(CurateCorporateActionsCmdBenchError::Run)?; - let read_back_rows = - verify_parquet_corporate_actions_row_count(&out_dir, timed.report.write_stats.rows_written) - .map_err(CurateCorporateActionsCmdBenchError::Verify)?; - - let report = CurateCorporateActionsCmdBenchReport { - events: 0, - key_count: 0, - splits_docs_framed: timed.report.splits_docs_framed, - splits_bytes_read: timed.report.splits_bytes_read, - dividends_docs_framed: timed.report.dividends_docs_framed, - dividends_bytes_read: timed.report.dividends_bytes_read, - delistings_rows_loaded: timed.report.delistings_rows_loaded, - delistings_bytes_read: timed.report.delistings_bytes_read, - rows_out: timed.report.curate_stats.rows_out, - listings_out: timed.report.curate_stats.listings_out, - files_written: timed.report.write_stats.files_written, - row_groups_written: timed.report.write_stats.row_groups_written, - bytes_written: timed.report.write_stats.bytes_written, - read_back_rows, - decode_elapsed_ms: timed.decode_elapsed_secs * 1_000.0, - decode_events_per_sec: 0.0, - input_mb_per_sec: 0.0, - curate_elapsed_ms: timed.curate_elapsed_secs * 1_000.0, - curate_events_per_sec: 0.0, - write_elapsed_ms: timed.write_elapsed_secs * 1_000.0, - write_rows_per_sec: 0.0, - write_mb_per_sec: 0.0, - total_elapsed_ms: (timed.decode_elapsed_secs - + timed.curate_elapsed_secs - + timed.write_elapsed_secs) - * 1_000.0, - total_events_per_sec: 0.0, - checksum: timed.checksum, - splits_decode: timed.report.splits_decode, - dividends_decode: timed.report.dividends_decode, - curate_stats: timed.report.curate_stats, - }; - drop(temp); - return Ok((report, temp_path)); - } - - let keys: Vec = (0..KEY_COUNT) - .map(|i| { - let suffix = if i % 4 == 0 { "CA" } else { "US" }; - format!("CA{i:05}:{suffix}") - }) - .collect(); - let otc_keys: Vec = (0..OTC_SUCC_COUNT) - .map(|i| format!("OTC{i:05}:US")) - .collect(); - - // 1. Write `provider_mapping.tsv`. - { - let mut map_w = BufWriter::new(File::create(&mapping_path).map_err(|source| { - CurateCorporateActionsCmdBenchError::FixtureIo { - path: mapping_path.clone(), - source, - } - })?); - for (i, key) in keys.iter().enumerate() { - if i < ENDED_START { - writeln!(map_w, "qm\t{key}\t1970-01-01\t\t{}", i + 1) - } else if i < SINGLE_RANGE_END { - // Ended primary-venue listing so OTC transfers after 2018-06-30 exercise - // `from_listing_id` resolution across ended outgoing ranges. - writeln!(map_w, "qm\t{key}\t1970-01-01\t2018-06-30\t{}", i + 1) - } else if i < REUSE_END { - writeln!(map_w, "qm\t{key}\t1970-01-01\t2015-06-30\t{}", i + 1).and_then(|()| { - writeln!(map_w, "qm\t{key}\t2016-01-01\t\t{}", i + 100_001) - }) - } else if i < ALIAS_END { - let alias_lid = i - REUSE_END + 1; - writeln!(map_w, "qm\t{key}\t1970-01-01\t\t{alias_lid}") - } else { - Ok(()) - } - .map_err(|source| CurateCorporateActionsCmdBenchError::FixtureIo { - path: mapping_path.clone(), - source, - })?; - } - for (i, otc_key) in otc_keys.iter().enumerate() { - writeln!(map_w, "qm\t{otc_key}\t1970-01-01\t\t{}", 500_001 + i).map_err(|source| { - CurateCorporateActionsCmdBenchError::FixtureIo { - path: mapping_path.clone(), - source, - } - })?; - } - map_w - .flush() - .map_err(|source| CurateCorporateActionsCmdBenchError::FixtureIo { - path: mapping_path.clone(), - source, - })?; - } - - let in_range_start = ymd_to_epoch_days(1977, 1, 3).expect("valid start"); - let in_range_end = ymd_to_epoch_days(2025, 12, 31).expect("valid end"); - let in_range_span = (in_range_end - in_range_start + 1) as u64; - let pre_1976_day = ymd_to_epoch_days(1975, 6, 15).expect("valid pre-1976 day"); - let reuse_resume = ymd_to_epoch_days(2016, 1, 1).expect("valid reuse resume"); - let ended_post_day = ymd_to_epoch_days(2019, 3, 15).expect("valid post-ended day"); - - let mut rng = SplitMix64::new(CURATE_CORPORATE_ACTIONS_CMD_BENCH_SEED); - - // 2. Stream-write `qmSplits.bson`, `qmDividends.bson`, and `delistings.tsv` in one pass. - { - let mut splits_w = BufWriter::with_capacity( - 256 * 1024, - File::create(&splits_path).map_err(|source| { - CurateCorporateActionsCmdBenchError::FixtureIo { - path: splits_path.clone(), - source, - } - })?, - ); - let mut divs_w = BufWriter::with_capacity( - 512 * 1024, - File::create(÷nds_path).map_err(|source| { - CurateCorporateActionsCmdBenchError::FixtureIo { - path: dividends_path.clone(), - source, - } - })?, - ); - let mut delist_w = BufWriter::with_capacity( - 128 * 1024, - File::create(&delistings_path).map_err(|source| { - CurateCorporateActionsCmdBenchError::FixtureIo { - path: delistings_path.clone(), - source, - } - })?, - ); - - let mut generated = 0usize; - let mut split_seq = 0u64; - let mut div_seq = 0u64; - - while generated < events { - let r1 = rng.next_u64(); - let r2 = rng.next_u64(); - let kind_roll = r1 % 1_000; - let is_pre_1976 = ((r1 >> 10) % 200) == 0; - let ex_date = if is_pre_1976 { - pre_1976_day - } else { - in_range_start + ((r2 % in_range_span) as i32) - }; - - if kind_roll < 36 { - // ~3.6% splits: forward/reverse, declared variants, 1:1 no-ops, unmapped, alias - // collisions (identical + conflicting), and ~0.5% malformed decode rejects. - let reject_roll = (r1 >> 18) % 200; - if reject_roll == 0 { - let mut oid = [0u8; 12]; - oid[4..12].copy_from_slice(&split_seq.to_be_bytes()); - split_seq += 1; - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("_id"), ObjectId::from_bytes(oid)); - doc.append(cstr!("qmSearchCode"), keys[0].as_str()); - doc.append(cstr!("date"), "2023-02-29"); - doc.append(cstr!("splitratio"), 2.0_f64); - splits_w.write_all(doc.as_bytes()).map_err(|source| { - CurateCorporateActionsCmdBenchError::FixtureIo { - path: splits_path.clone(), - source, - } - })?; - generated += 1; - continue; - } - - let is_alias_target = !is_pre_1976 && ((r1 >> 26) % 10) == 0; - let key_idx = if is_alias_target { - ((r2 >> 24) as usize) % ALIAS_COUNT - } else { - ((r2 >> 24) as usize) % KEY_COUNT - }; - let is_noop = ((r1 >> 30) % 50) == 0; - let ratio = if is_noop { - 1.0 - } else { - SAMPLE_RATIOS[((r1 >> 36) as usize) % SAMPLE_RATIOS.len()] - }; - let decl_roll = (r1 >> 42) % 100; - let declared_date = if decl_roll < 80 { - Some(ex_date - 21) - } else if decl_roll < 98 { - None - } else { - Some(ex_date + 3) - }; - - let ex_str = format_ymd_string(ex_date); - let decl_str = declared_date.map(format_ymd_string); - - let write_split = |w: &mut BufWriter, - seq: &mut u64, - code: &str, - r: f64, - use_dt: bool| - -> Result<(), CurateCorporateActionsCmdBenchError> { - let mut oid = [0u8; 12]; - oid[4..12].copy_from_slice(&seq.to_be_bytes()); - *seq += 1; - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("_id"), ObjectId::from_bytes(oid)); - doc.append(cstr!("qmSearchCode"), code); - if use_dt { - doc.append( - cstr!("date"), - DateTime::from_millis(i64::from(ex_date) * MILLIS_PER_DAY), - ); - } else { - doc.append(cstr!("date"), ex_str.as_str()); - } - if let Some(ref ds) = decl_str { - doc.append(cstr!("declared"), ds.as_str()); - } - doc.append(cstr!("splitratio"), r); - doc.append(cstr!("usdFxRate"), 1_i32); - w.write_all(doc.as_bytes()).map_err(|source| { - CurateCorporateActionsCmdBenchError::FixtureIo { - path: splits_path.clone(), - source, - } - }) - }; - - let use_dt = split_seq % 20 == 0; - write_split(&mut splits_w, &mut split_seq, &keys[key_idx], ratio, use_dt)?; - generated += 1; - - if is_alias_target && !is_noop && generated < events { - let alias_ratio = if ((r1 >> 50) & 1) == 0 { - ratio - } else { - ratio * 1.5 - }; - write_split( - &mut splits_w, - &mut split_seq, - &keys[REUSE_END + key_idx], - alias_ratio, - false, - )?; - generated += 1; - } - } else if kind_roll < 990 { - // ~95.4% dividends: USD/CAD with bogus usdFxRate: 1, declared variants, 0.0 cash, - // same-day multi-dividends, identical alias duplicates, unmapped, ~0.5% malformed. - let reject_roll = (r1 >> 18) % 200; - if reject_roll == 0 { - let mut oid = [0u8; 12]; - oid[0] = 2; - oid[4..12].copy_from_slice(&div_seq.to_be_bytes()); - div_seq += 1; - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("_id"), ObjectId::from_bytes(oid)); - doc.append(cstr!("qmSearchCode"), keys[0].as_str()); - if div_seq % 2 == 0 { - doc.append(cstr!("date"), "2023-02-29"); - doc.append(cstr!("amount"), 0.25_f64); - } else { - doc.append(cstr!("date"), "2023-06-15"); - doc.append(cstr!("amount"), -0.25_f64); - } - doc.append(cstr!("currency"), "USD"); - doc.append(cstr!("usdFxRate"), 1_i32); - divs_w.write_all(doc.as_bytes()).map_err(|source| { - CurateCorporateActionsCmdBenchError::FixtureIo { - path: dividends_path.clone(), - source, - } - })?; - generated += 1; - continue; - } - - let key_idx = ((r2 >> 24) as usize) % KEY_COUNT; - let is_zero = ((r1 >> 26) % 100) == 0; - let cash = if is_zero { - 0.0 - } else { - (((r1 >> 34) % 250) + 1) as f64 * 0.01 - }; - let currency = if key_idx % 4 == 0 { "CAD" } else { "USD" }; - let decl_roll = (r1 >> 42) % 100; - let declared_date = if decl_roll < 80 { - Some(ex_date - 21) - } else if decl_roll < 98 { - None - } else { - Some(ex_date + 3) - }; - - let ex_str = format_ymd_string(ex_date); - let decl_str = declared_date.map(format_ymd_string); - - let write_div = |w: &mut BufWriter, - seq: &mut u64, - code: &str, - c: f64, - use_dt: bool| - -> Result<(), CurateCorporateActionsCmdBenchError> { - let mut oid = [0u8; 12]; - oid[0] = 2; - oid[4..12].copy_from_slice(&seq.to_be_bytes()); - *seq += 1; - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("_id"), ObjectId::from_bytes(oid)); - doc.append(cstr!("qmSearchCode"), code); - if use_dt { - doc.append( - cstr!("date"), - DateTime::from_millis(i64::from(ex_date) * MILLIS_PER_DAY), - ); - } else { - doc.append(cstr!("date"), ex_str.as_str()); - } - if let Some(ref ds) = decl_str { - doc.append(cstr!("declared"), ds.as_str()); - } - doc.append(cstr!("amount"), c); - doc.append(cstr!("currency"), currency); - doc.append(cstr!("usdFxRate"), 1_i32); - w.write_all(doc.as_bytes()).map_err(|source| { - CurateCorporateActionsCmdBenchError::FixtureIo { - path: dividends_path.clone(), - source, - } - }) - }; - - let use_dt = div_seq % 20 == 0; - write_div(&mut divs_w, &mut div_seq, &keys[key_idx], cash, use_dt)?; - generated += 1; - - if !is_zero && !is_pre_1976 && generated < events { - if ((r1 >> 50) % 100) == 0 { - // Same-key same-day special dividend. - write_div(&mut divs_w, &mut div_seq, &keys[key_idx], cash * 2.0, false)?; - generated += 1; - } else if key_idx < ALIAS_COUNT && ((r1 >> 54) % 25) == 0 { - // Identical cross-key alias dividend. - write_div( - &mut divs_w, - &mut div_seq, - &keys[REUSE_END + key_idx], - cash, - false, - )?; - generated += 1; - } - } - } else { - // ~1.0% delistings: valid OTC transfers (including ended outgoing ranges), - // unmapped successors, self successors, -0.3 and -1.0 terminal delistings. - let outcome_roll = (r1 >> 18) % 100; - if outcome_roll < 40 { - // Valid OTC transfer with `from_listing_id`. Half target ended listings. - let (key_idx, delist_day, from_lid) = if outcome_roll < 20 { - let k = ENDED_START + (((r2 >> 24) as usize) % (SINGLE_RANGE_END - ENDED_START)); - (k, ended_post_day, (k + 1) as i32) - } else { - let k = ((r2 >> 24) as usize) % ENDED_START; - (k, ex_date, (k + 1) as i32) - }; - let succ_idx = ((r2 >> 40) as usize) % OTC_SUCC_COUNT; - let date_str = format_ymd_string(delist_day); - writeln!( - delist_w, - "{}\t{date_str}\t{from_lid}\t{}\t", - keys[key_idx], otc_keys[succ_idx] - ) - } else if outcome_roll < 50 { - // Unmapped successor. - let k = ((r2 >> 24) as usize) % ENDED_START; - let date_str = format_ymd_string(ex_date); - writeln!( - delist_w, - "{}\t{date_str}\t{}\tOTC_UNMAPPED:US\t", - keys[k], - k + 1 - ) - } else if outcome_roll < 60 { - // Self successor. - let k = ((r2 >> 24) as usize) % ENDED_START; - let date_str = format_ymd_string(ex_date); - writeln!( - delist_w, - "{}\t{date_str}\t{}\t{}\t", - keys[k], - k + 1, - keys[k] - ) - } else if outcome_roll < 82 { - // -0.3 terminal delisting (some with explicit from_listing_id, some without). - let k = ((r2 >> 24) as usize) % KEY_COUNT; - let date_str = format_ymd_string(ex_date); - if k < REUSE_END && ((r1 >> 26) & 1) == 0 { - let lid = if k >= SINGLE_RANGE_END && ex_date >= reuse_resume { - k + 100_001 - } else { - k + 1 - }; - writeln!(delist_w, "{}\t{date_str}\t{lid}\t\t-0.3", keys[k]) - } else { - writeln!(delist_w, "{}\t{date_str}\t\t\t-0.3", keys[k]) - } - } else { - // -1.0 terminal delisting. - let k = ((r2 >> 24) as usize) % KEY_COUNT; - let date_str = format_ymd_string(ex_date); - writeln!(delist_w, "{}\t{date_str}\t\t\t-1.0", keys[k]) - } - .map_err(|source| CurateCorporateActionsCmdBenchError::FixtureIo { - path: delistings_path.clone(), - source, - })?; - generated += 1; - } - } - - splits_w.flush().map_err(|source| { - CurateCorporateActionsCmdBenchError::FixtureIo { - path: splits_path.clone(), - source, - } - })?; - divs_w.flush().map_err(|source| { - CurateCorporateActionsCmdBenchError::FixtureIo { - path: dividends_path.clone(), - source, - } - })?; - delist_w.flush().map_err(|source| { - CurateCorporateActionsCmdBenchError::FixtureIo { - path: delistings_path.clone(), - source, - } - })?; - } - - // 3. Run stage-timed end-to-end command and verify Parquet footer row count. - let args = CurateCorporateActionsArgs { - qm_splits: splits_path, - qm_dividends: dividends_path, - provider_mapping: mapping_path, - delistings: Some(delistings_path), - out_dir: out_dir.clone(), - }; - let timed = run_curate_corporate_actions_timed(&args) - .map_err(CurateCorporateActionsCmdBenchError::Run)?; - let read_back_rows = - verify_parquet_corporate_actions_row_count(&out_dir, timed.report.write_stats.rows_written) - .map_err(CurateCorporateActionsCmdBenchError::Verify)?; - - let decode_elapsed_ms = timed.decode_elapsed_secs * 1_000.0; - let curate_elapsed_ms = timed.curate_elapsed_secs * 1_000.0; - let write_elapsed_ms = timed.write_elapsed_secs * 1_000.0; - let total_elapsed_secs = - timed.decode_elapsed_secs + timed.curate_elapsed_secs + timed.write_elapsed_secs; - let total_elapsed_ms = total_elapsed_secs * 1_000.0; - - let (decode_events_per_sec, _) = compute_rates(events, timed.decode_elapsed_secs); - let decoded_events = timed.report.curate_stats.builder.splits_in - + timed.report.curate_stats.builder.dividends_in - + timed.report.curate_stats.builder.delistings_in; - let (curate_events_per_sec, _) = compute_rates(decoded_events, timed.curate_elapsed_secs); - let (write_rows_per_sec, _) = - compute_rates(timed.report.write_stats.rows_written, timed.write_elapsed_secs); - let (total_events_per_sec, _) = compute_rates(events, total_elapsed_secs); - - let total_input_bytes = timed.report.splits_bytes_read - + timed.report.dividends_bytes_read - + timed.report.delistings_bytes_read; - let input_mb_per_sec = if timed.decode_elapsed_secs > 0.0 { - (total_input_bytes as f64 / MIB) / timed.decode_elapsed_secs - } else { - 0.0 - }; - let write_mb_per_sec = if timed.write_elapsed_secs > 0.0 { - (timed.report.write_stats.bytes_written as f64 / MIB) / timed.write_elapsed_secs - } else { - 0.0 - }; - - let report = CurateCorporateActionsCmdBenchReport { - events, - key_count: KEY_COUNT, - splits_docs_framed: timed.report.splits_docs_framed, - splits_bytes_read: timed.report.splits_bytes_read, - dividends_docs_framed: timed.report.dividends_docs_framed, - dividends_bytes_read: timed.report.dividends_bytes_read, - delistings_rows_loaded: timed.report.delistings_rows_loaded, - delistings_bytes_read: timed.report.delistings_bytes_read, - rows_out: timed.report.curate_stats.rows_out, - listings_out: timed.report.curate_stats.listings_out, - files_written: timed.report.write_stats.files_written, - row_groups_written: timed.report.write_stats.row_groups_written, - bytes_written: timed.report.write_stats.bytes_written, - read_back_rows, - decode_elapsed_ms, - decode_events_per_sec, - input_mb_per_sec, - curate_elapsed_ms, - curate_events_per_sec, - write_elapsed_ms, - write_rows_per_sec, - write_mb_per_sec, - total_elapsed_ms, - total_events_per_sec, - checksum: timed.checksum, - splits_decode: timed.report.splits_decode, - dividends_decode: timed.report.dividends_decode, - curate_stats: timed.report.curate_stats, - }; - - drop(temp); - Ok((report, temp_path)) -} - -/// Runs the fixed-seed end-to-end `curate-corporate-actions` file -> Parquet benchmark for -/// `events` synthetic `qmSplits` (~3.6%), `qmDividends` (~95.4%), and Pass 6 `delistings.tsv` -/// (~1.0%) inputs. -pub fn run_curate_corporate_actions_cmd_benchmark( - events: usize, -) -> Result { - let (report, _) = run_curate_corporate_actions_cmd_benchmark_tracked(events)?; - Ok(report) -} - -pub const DEFAULT_CURATE_FX_CMD_BENCH_ROWS: usize = 20_000; -const CURATE_FX_CMD_BENCH_SEED: u64 = 0x570C_4B07_C04A_F01D; - -/// Errors returned by [`run_curate_fx_cmd_benchmark`]. -#[derive(Debug)] -pub enum CurateFxCmdBenchError { - FixtureIo { - path: PathBuf, - source: io::Error, - }, - Run(crate::run_curate_fx::RunCurateFxError), - Verify(ParquetFxError), -} - -impl std::fmt::Display for CurateFxCmdBenchError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Self::FixtureIo { path, source } => { - write!(f, "benchmark fixture I/O '{}': {source}", path.display()) - } - Self::Run(err) => write!(f, "{err}"), - Self::Verify(err) => write!(f, "Parquet verify failed: {err}"), - } - } -} - -impl std::error::Error for CurateFxCmdBenchError { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - match self { - Self::FixtureIo { source, .. } => Some(source), - Self::Run(err) => Some(err), - Self::Verify(err) => Some(err), - } - } -} - -/// Summary metrics produced by [`run_curate_fx_cmd_benchmark`]. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct CurateFxCmdBenchReport { - pub rows: usize, - pub eod_docs_framed: u64, - pub eod_bytes_read: u64, - pub eod_cad_forex_kept: usize, - pub eod_other_symbol_skipped: usize, - pub te_docs_framed: u64, - pub te_bytes_read: u64, - pub rows_out: usize, - pub files_written: usize, - pub row_groups_written: usize, - pub bytes_written: u64, - pub read_back_rows: usize, - pub decode_elapsed_ms: f64, - pub decode_rows_per_sec: f64, - pub input_mb_per_sec: f64, - pub curate_elapsed_ms: f64, - pub curate_rows_per_sec: f64, - pub write_elapsed_ms: f64, - pub write_rows_per_sec: f64, - pub write_mb_per_sec: f64, - pub total_elapsed_ms: f64, - pub total_rows_per_sec: f64, - pub checksum: u64, - pub eod_decode: BsonEodDecodeStats, - pub te_decode: crate::bson_te_market_data::BsonTeMarketDataDecodeStats, - pub curate_stats: crate::curate_fx::CurateFx1dStats, -} - -fn run_curate_fx_cmd_benchmark_tracked( - rows: usize, -) -> Result<(CurateFxCmdBenchReport, PathBuf), CurateFxCmdBenchError> { - use std::io::{BufWriter, Write}; - - use bson::raw::RawArrayBuf; - - use crate::bson_te_market_data::{ - BsonTeMarketDataDecodeStats, MILLIS_PER_DAY as TE_MILLIS_PER_DAY, - SECONDS_PER_DAY as TE_SECONDS_PER_DAY, - }; - use crate::curate_fx::CurateFx1dStats; - use crate::run_curate_fx::{ - run_curate_fx_1d_timed, CurateFx1dArgs, DEFAULT_TE_SYMBOL, EOD_CAD_FOREX_CODE, - }; - - const MIB: f64 = 1024.0 * 1024.0; - const OTHER_EOD_CODES: [&str; 4] = ["EUR.FOREX", "AAPL.US", "RY.TO", "cad.forex"]; - const MAX_TE_POINTS_PER_DOC: usize = 50_000; - - let temp = - BenchTempDir::new_in_with_prefix(&std::env::temp_dir(), "curate-etl-bench-curate-fx-cmd") - .map_err(|(path, source)| CurateFxCmdBenchError::FixtureIo { path, source })?; - let temp_path = temp.path.clone(); - - if rows == 0 { - drop(temp); - return Ok(( - CurateFxCmdBenchReport { - rows: 0, - eod_docs_framed: 0, - eod_bytes_read: 0, - eod_cad_forex_kept: 0, - eod_other_symbol_skipped: 0, - te_docs_framed: 0, - te_bytes_read: 0, - rows_out: 0, - files_written: 0, - row_groups_written: 0, - bytes_written: 0, - read_back_rows: 0, - decode_elapsed_ms: 0.0, - decode_rows_per_sec: 0.0, - input_mb_per_sec: 0.0, - curate_elapsed_ms: 0.0, - curate_rows_per_sec: 0.0, - write_elapsed_ms: 0.0, - write_rows_per_sec: 0.0, - write_mb_per_sec: 0.0, - total_elapsed_ms: 0.0, - total_rows_per_sec: 0.0, - checksum: 0, - eod_decode: BsonEodDecodeStats::default(), - te_decode: BsonTeMarketDataDecodeStats::default(), - curate_stats: CurateFx1dStats::default(), - }, - temp_path, - )); - } - - let eod_path = temp.path.join("eodPrices.bson"); - let te_path = temp.path.join("teMarketData.bson"); - let out_dir = temp.path.join("out"); - - let mut rng = SplitMix64::new(CURATE_FX_CMD_BENCH_SEED); - // Start in 1975 so every date's millisecond epoch exceeds TE_EPOCH_MILLIS_THRESHOLD (1e11). - let start_day = ymd_to_epoch_days(1975, 1, 2).expect("valid start_day"); - - let eod_target = (rows * 75 / 100).max(1); - let te_target = rows.saturating_sub(eod_target); - - // Track EOD valid dates, closes, and interior gap dates so TE points can overlap and fill gaps. - let mut eod_valid_dates: Vec<(i32, f64)> = Vec::with_capacity(eod_target); - let mut gap_dates: Vec = Vec::new(); - let mut last_eod_day = start_day; - - // 1. Write `eodPrices.bson` (`CAD.FOREX` + skipped other symbols + malformed docs). - { - let mut eod_w = BufWriter::new(File::create(&eod_path).map_err(|source| { - CurateFxCmdBenchError::FixtureIo { - path: eod_path.clone(), - source, - } - })?); - - let mut eod_seq = 0u64; - let mut write_eod_doc = - |code: &str, - day: i32, - open: f64, - high: f64, - low: f64, - close: f64, - omit_close: bool| - -> Result<(), CurateFxCmdBenchError> { - let mut oid = [0u8; 12]; - oid[0] = 1; - oid[4..12].copy_from_slice(&eod_seq.to_be_bytes()); - eod_seq += 1; - let date_str = format_ymd_string(day); - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("_id"), ObjectId::from_bytes(oid)); - doc.append(cstr!("eodSearchCode"), code); - if eod_seq % 10 == 0 { - doc.append( - cstr!("date"), - DateTime::from_millis(i64::from(day) * TE_MILLIS_PER_DAY), - ); - } else { - doc.append(cstr!("date"), date_str.as_str()); - } - doc.append(cstr!("open"), open); - doc.append(cstr!("high"), high); - doc.append(cstr!("low"), low); - if !omit_close { - doc.append(cstr!("close"), close); - } - doc.append(cstr!("volume"), 0.0_f64); - eod_w.write_all(doc.as_bytes()).map_err(|source| { - CurateFxCmdBenchError::FixtureIo { - path: eod_path.clone(), - source, - } - }) - }; - - let mut day_cursor = start_day; - let mut generated_eod = 0usize; - let mut rate = 1.32_f64; - - while generated_eod < eod_target { - // Interleave an other-symbol doc every 4th iteration so `eod_other_symbol_skipped > 0`. - if generated_eod % 4 == 0 { - let other_code = OTHER_EOD_CODES[(rng.next_u64() as usize) % OTHER_EOD_CODES.len()]; - write_eod_doc(other_code, day_cursor, 10.0, 10.5, 9.8, 10.2, false)?; - } - - // Leave every 25th calendar day as an interior gap for TE to fill. - if (day_cursor - start_day) % 25 == 12 { - gap_dates.push(day_cursor); - day_cursor += 1; - continue; - } - - let step = ((rng.next_u64() % 201) as f64 - 100.0) * 0.0002; - rate = (rate + step).clamp(0.95, 1.65); - let spread = 0.003 + ((rng.next_u64() % 40) as f64) * 0.0002; - let low = rate - spread * 0.5; - let high = rate + spread * 0.5; - let open = low + spread * ((rng.next_u64() % 100) as f64 * 0.01); - let close = low + spread * ((rng.next_u64() % 100) as f64 * 0.01); - - let roll = rng.next_u64() % 200; - if roll == 0 { - // Malformed EOD doc (missing `close`) -> decoder reject. - write_eod_doc(EOD_CAD_FOREX_CODE, day_cursor, open, high, low, close, true)?; - generated_eod += 1; - } else if roll == 1 { - // Invalid OHLC (`close == 0.0`) -> builder drop. - write_eod_doc(EOD_CAD_FOREX_CODE, day_cursor, open, high, low, 0.0, false)?; - generated_eod += 1; - } else if roll == 2 { - // Inconsistent OHLC (`high < low`) -> builder drop. - write_eod_doc(EOD_CAD_FOREX_CODE, day_cursor, open, low - 0.01, high, close, false)?; - generated_eod += 1; - } else if roll == 3 && generated_eod + 1 < eod_target { - // Identical duplicate pair -> collapsed in builder. - write_eod_doc(EOD_CAD_FOREX_CODE, day_cursor, open, high, low, close, false)?; - write_eod_doc(EOD_CAD_FOREX_CODE, day_cursor, open, high, low, close, false)?; - eod_valid_dates.push((day_cursor, close)); - generated_eod += 2; - } else if roll == 4 && generated_eod + 1 < eod_target { - // Conflicting duplicate pair -> dropped in builder. - write_eod_doc(EOD_CAD_FOREX_CODE, day_cursor, open, high, low, close, false)?; - write_eod_doc( - EOD_CAD_FOREX_CODE, - day_cursor, - open, - high, - low, - (close + 0.001).min(high), - false, - )?; - generated_eod += 2; - } else { - write_eod_doc(EOD_CAD_FOREX_CODE, day_cursor, open, high, low, close, false)?; - eod_valid_dates.push((day_cursor, close)); - generated_eod += 1; - } - - last_eod_day = day_cursor; - day_cursor += 1; - } - - eod_w.flush().map_err(|source| CurateFxCmdBenchError::FixtureIo { - path: eod_path.clone(), - source, - })?; - } - - // 2. Write `teMarketData.bson` (other symbols + `USDCAD` with overlap, gap fill, tail, - // mixed seconds/ms `t`, malformed points, and ignored `monthly`). - { - let mut te_w = BufWriter::new(File::create(&te_path).map_err(|source| { - CurateFxCmdBenchError::FixtureIo { - path: te_path.clone(), - source, - } - })?); - - // Two non-target symbol documents to exercise `docs_other_symbol`. - for other_sym in ["EURUSD", "GBPUSD"] { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("teSymbol"), other_sym); - let mut arr = RawArrayBuf::new(); - let mut pt = RawDocumentBuf::new(); - pt.append(cstr!("t"), i64::from(start_day) * TE_MILLIS_PER_DAY); - pt.append(cstr!("o"), 1.10_f64); - pt.append(cstr!("h"), 1.12_f64); - pt.append(cstr!("l"), 1.09_f64); - pt.append(cstr!("c"), 1.11_f64); - arr.push(pt); - doc.append(cstr!("daily"), arr); - te_w.write_all(doc.as_bytes()).map_err(|source| { - CurateFxCmdBenchError::FixtureIo { - path: te_path.clone(), - source, - } - })?; - } - - // Build `USDCAD` points across one or more docs (<= MAX_TE_POINTS_PER_DOC each). - let overlap_quota = (te_target * 40 / 100).min(eod_valid_dates.len()); - let gap_quota = (te_target * 20 / 100).min(gap_dates.len()); - let mut te_points_written = 0usize; - let mut tail_day = last_eod_day + 1; - let mut doc_idx = 0usize; - - while te_points_written < te_target || doc_idx == 0 { - let batch_count = (te_target - te_points_written).min(MAX_TE_POINTS_PER_DOC); - let mut daily = RawArrayBuf::new(); - - for _ in 0..batch_count { - let idx = te_points_written; - te_points_written += 1; - - // ~1.5% malformed points (missing field, wrong type, non-finite) - let bad_roll = idx % 200; - if bad_roll == 197 { - let mut pt = RawDocumentBuf::new(); - pt.append(cstr!("t"), i64::from(tail_day) * TE_SECONDS_PER_DAY); - pt.append(cstr!("o"), 1.35_f64); - pt.append(cstr!("h"), 1.36_f64); - pt.append(cstr!("l"), 1.34_f64); - // Missing `c` - daily.push(pt); - continue; - } else if bad_roll == 198 { - let mut pt = RawDocumentBuf::new(); - pt.append(cstr!("t"), "not-a-timestamp"); - pt.append(cstr!("o"), 1.35_f64); - pt.append(cstr!("h"), 1.36_f64); - pt.append(cstr!("l"), 1.34_f64); - pt.append(cstr!("c"), 1.35_f64); - daily.push(pt); - continue; - } else if bad_roll == 199 { - let mut pt = RawDocumentBuf::new(); - pt.append(cstr!("t"), i64::from(tail_day) * TE_MILLIS_PER_DAY); - pt.append(cstr!("o"), f64::NAN); - pt.append(cstr!("h"), 1.36_f64); - pt.append(cstr!("l"), 1.34_f64); - pt.append(cstr!("c"), 1.35_f64); - daily.push(pt); - continue; - } - - let (day, base_close) = if idx < overlap_quota { - let (d, eod_c) = eod_valid_dates[idx]; - // ~5% overlap mismatch (> 1%) to exercise read-only overlap cross-check. - let c = if idx % 20 == 0 { - eod_c * 1.025 - } else { - eod_c * 1.001 - }; - (d, c) - } else if idx < overlap_quota + gap_quota { - let d = gap_dates[idx - overlap_quota]; - (d, 1.34 + ((rng.next_u64() % 100) as f64) * 0.0005) - } else { - let d = tail_day; - tail_day += 1; - (d, 1.36 + ((rng.next_u64() % 100) as f64) * 0.0005) - }; - - let low = base_close - 0.004; - let high = base_close + 0.004; - let open = base_close - 0.001; - let close = base_close; - - let mut pt = RawDocumentBuf::new(); - // Mix seconds (i32/i64/f64) and milliseconds (i64/f64). - match idx % 5 { - 0 => pt.append(cstr!("t"), i64::from(day) * TE_MILLIS_PER_DAY + 43_200_000), - 1 => pt.append(cstr!("t"), (i64::from(day) * TE_MILLIS_PER_DAY) as f64), - 2 => { - let secs = i64::from(day) * TE_SECONDS_PER_DAY + 3_600; - if let Ok(s32) = i32::try_from(secs) { - pt.append(cstr!("t"), s32); - } else { - pt.append(cstr!("t"), secs); - } - } - 3 => pt.append(cstr!("t"), i64::from(day) * TE_SECONDS_PER_DAY), - _ => pt.append(cstr!("t"), (i64::from(day) * TE_SECONDS_PER_DAY) as f64), - } - pt.append(cstr!("o"), open); - pt.append(cstr!("h"), high); - pt.append(cstr!("l"), low); - pt.append(cstr!("c"), close); - pt.append(cstr!("pc"), 0.01_f64); - pt.append(cstr!("ac"), 0.0001_f64); - daily.push(pt); - } - - let mut monthly = RawArrayBuf::new(); - monthly.push("ignored-monthly-entry"); - - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("teSymbol"), DEFAULT_TE_SYMBOL); - doc.append(cstr!("monthly"), monthly); - doc.append(cstr!("daily"), daily); - te_w.write_all(doc.as_bytes()).map_err(|source| { - CurateFxCmdBenchError::FixtureIo { - path: te_path.clone(), - source, - } - })?; - doc_idx += 1; - if te_points_written >= te_target { - break; - } - } - - te_w.flush().map_err(|source| CurateFxCmdBenchError::FixtureIo { - path: te_path.clone(), - source, - })?; - } - - let args = CurateFx1dArgs { - eod_prices: eod_path, - te_market_data: te_path, - te_symbol: DEFAULT_TE_SYMBOL.to_string(), - out_dir: out_dir.clone(), - }; - let timed = run_curate_fx_1d_timed(&args).map_err(CurateFxCmdBenchError::Run)?; - let read_back_rows = - verify_parquet_fx_row_count(&out_dir, timed.report.write_stats.rows_written) - .map_err(CurateFxCmdBenchError::Verify)?; - - let decode_elapsed_ms = timed.decode_elapsed_secs * 1_000.0; - let curate_elapsed_ms = timed.curate_elapsed_secs * 1_000.0; - let write_elapsed_ms = timed.write_elapsed_secs * 1_000.0; - let total_elapsed_secs = - timed.decode_elapsed_secs + timed.curate_elapsed_secs + timed.write_elapsed_secs; - let total_elapsed_ms = total_elapsed_secs * 1_000.0; - - let (decode_rows_per_sec, _) = compute_rates(rows, timed.decode_elapsed_secs); - let decoded_rows = - timed.report.eod_cad_forex_kept + timed.report.te_decode.points_decoded; - let (curate_rows_per_sec, _) = compute_rates(decoded_rows, timed.curate_elapsed_secs); - let (write_rows_per_sec, _) = - compute_rates(timed.report.write_stats.rows_written, timed.write_elapsed_secs); - let (total_rows_per_sec, _) = compute_rates(rows, total_elapsed_secs); - - let total_input_bytes = timed.report.eod_bytes_read + timed.report.te_bytes_read; - let input_mb_per_sec = if timed.decode_elapsed_secs > 0.0 { - (total_input_bytes as f64 / MIB) / timed.decode_elapsed_secs - } else { - 0.0 - }; - let write_mb_per_sec = if timed.write_elapsed_secs > 0.0 { - (timed.report.write_stats.bytes_written as f64 / MIB) / timed.write_elapsed_secs - } else { - 0.0 - }; - - let report = CurateFxCmdBenchReport { - rows, - eod_docs_framed: timed.report.eod_docs_framed, - eod_bytes_read: timed.report.eod_bytes_read, - eod_cad_forex_kept: timed.report.eod_cad_forex_kept, - eod_other_symbol_skipped: timed.report.eod_other_symbol_skipped, - te_docs_framed: timed.report.te_docs_framed, - te_bytes_read: timed.report.te_bytes_read, - rows_out: timed.report.curate_stats.rows_out, - files_written: timed.report.write_stats.files_written, - row_groups_written: timed.report.write_stats.row_groups_written, - bytes_written: timed.report.write_stats.bytes_written, - read_back_rows, - decode_elapsed_ms, - decode_rows_per_sec, - input_mb_per_sec, - curate_elapsed_ms, - curate_rows_per_sec, - write_elapsed_ms, - write_rows_per_sec, - write_mb_per_sec, - total_elapsed_ms, - total_rows_per_sec, - checksum: timed.checksum, - eod_decode: timed.report.eod_decode, - te_decode: timed.report.te_decode, - curate_stats: timed.report.curate_stats, - }; - - drop(temp); - Ok((report, temp_path)) -} - -/// Runs the fixed-seed end-to-end `curate-fx-1d` file -> Parquet benchmark for `rows` synthetic -/// `eodPrices` (`CAD.FOREX` + skipped other symbols + malformed docs) and `teMarketData` -/// (`USDCAD` + skipped other symbols + overlap + interior gap fills + post-EOD tail + mixed -/// seconds/ms `t` + malformed points) inputs. -pub fn run_curate_fx_cmd_benchmark( - rows: usize, -) -> Result { - let (report, _) = run_curate_fx_cmd_benchmark_tracked(rows)?; - Ok(report) -} - -/// Default document count for `bench-curate-shorts-command` (~700k `ceoShorts` docs). -pub const DEFAULT_CURATE_SHORTS_COMMAND_BENCH_ROWS: usize = 700_000; -const CURATE_SHORTS_CMD_BENCH_SEED: u64 = 0x570C_4B07_CE05_0A75; -const CURATE_SHORTS_CMD_BENCH_KEYS: usize = 12_500; - -/// Errors returned by [`run_curate_shorts_command_benchmark`]. -#[derive(Debug)] -pub enum CurateShortsCmdBenchError { - FixtureIo { - path: PathBuf, - source: io::Error, - }, - Run(crate::run_curate_shorts::RunCurateShortsError), - Verify(ParquetShortsError), -} - -impl std::fmt::Display for CurateShortsCmdBenchError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Self::FixtureIo { path, source } => { - write!(f, "benchmark fixture I/O '{}': {source}", path.display()) - } - Self::Run(err) => write!(f, "{err}"), - Self::Verify(err) => write!(f, "Parquet verify failed: {err}"), - } - } -} - -impl std::error::Error for CurateShortsCmdBenchError { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - match self { - Self::FixtureIo { source, .. } => Some(source), - Self::Run(err) => Some(err), - Self::Verify(err) => Some(err), - } - } -} - -/// Summary metrics produced by [`run_curate_shorts_command_benchmark`]. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct CurateShortsCmdBenchReport { - pub rows: usize, - pub key_count: usize, - pub min_report_date: Option, - pub max_report_date: Option, - pub docs_framed: u64, - pub bytes_read: u64, - pub peak_chunk_bytes: usize, - pub rows_out: usize, - pub listings_out: usize, - pub files_written: usize, - pub row_groups_written: usize, - pub bytes_written: u64, - pub read_back_rows: usize, - pub decode_elapsed_ms: f64, - pub decode_rows_per_sec: f64, - pub input_mb_per_sec: f64, - pub curate_elapsed_ms: f64, - pub curate_rows_per_sec: f64, - pub write_elapsed_ms: f64, - pub write_rows_per_sec: f64, - pub write_mb_per_sec: f64, - pub total_elapsed_ms: f64, - pub total_rows_per_sec: f64, - pub checksum: u64, - pub decode: crate::bson_ceo_shorts::BsonCeoShortsDecodeStats, - pub curate_stats: crate::curate_shorts::CurateShortsStats, -} - -fn run_curate_shorts_command_benchmark_tracked( - rows: usize, -) -> Result<(CurateShortsCmdBenchReport, PathBuf), CurateShortsCmdBenchError> { - use std::io::{BufWriter, Write}; - - use bson::raw::{cstr, RawBson, RawDocumentBuf}; - use bson::DateTime as BsonDateTime; - - use crate::bson_ceo_shorts::{ - BsonCeoShortsDecodeStats, DEFAULT_KEY_FIELD, DEFAULT_REPORT_DATE_FIELD, - }; - use crate::curate_shorts::CurateShortsStats; - use crate::run_curate_shorts::{ - run_curate_shorts_timed, CurateShortsArgs, DEFAULT_MAPPING_SOURCE, - }; - - const MIB: f64 = 1024.0 * 1024.0; - - let temp = BenchTempDir::new_in_with_prefix( - &std::env::temp_dir(), - "curate-etl-bench-curate-shorts-cmd", - ) - .map_err(|(path, source)| CurateShortsCmdBenchError::FixtureIo { path, source })?; - let temp_path = temp.path.clone(); - - if rows == 0 { - drop(temp); - return Ok(( - CurateShortsCmdBenchReport { - rows: 0, - key_count: 0, - min_report_date: None, - max_report_date: None, - docs_framed: 0, - bytes_read: 0, - peak_chunk_bytes: 0, - rows_out: 0, - listings_out: 0, - files_written: 0, - row_groups_written: 0, - bytes_written: 0, - read_back_rows: 0, - decode_elapsed_ms: 0.0, - decode_rows_per_sec: 0.0, - input_mb_per_sec: 0.0, - curate_elapsed_ms: 0.0, - curate_rows_per_sec: 0.0, - write_elapsed_ms: 0.0, - write_rows_per_sec: 0.0, - write_mb_per_sec: 0.0, - total_elapsed_ms: 0.0, - total_rows_per_sec: 0.0, - checksum: 0, - decode: BsonCeoShortsDecodeStats::default(), - curate_stats: CurateShortsStats::default(), - }, - temp_path, - )); - } - - let key_count = CURATE_SHORTS_CMD_BENCH_KEYS; - let all_dates = semi_monthly_report_dates(); - let date_count = all_dates.len(); - - let map_path = temp.path.join("provider_mapping.tsv"); - let bson_path = temp.path.join("ceoShorts.bson"); - let out_dir = temp.path.join("out"); - - // 1. Write provider_mapping.tsv: - // - 96% mapped single-range keys - // - 2% reuse-gap keys (2017-01-01..=2020-12-31 -> L, 2022-01-01.. -> L + 50_000) - // - 2% unmapped keys (omitted from TSV) - // - Plus 200 alias keys mapping to listing_ids 1..=200 for cross-key collisions. - { - let f = File::create(&map_path).map_err(|source| CurateShortsCmdBenchError::FixtureIo { - path: map_path.clone(), - source, - })?; - let mut w = BufWriter::with_capacity(256 * 1024, f); - for k in 0..key_count { - let listing_id = (k as i32) + 1; - let bucket = k % 50; - if bucket == 49 { - // Unmapped key - continue; - } else if bucket == 48 { - writeln!( - w, - "{DEFAULT_MAPPING_SOURCE}\tCEO{k:05}\t2017-01-01\t2020-12-31\t{listing_id}" - ) - .and_then(|()| { - writeln!( - w, - "{DEFAULT_MAPPING_SOURCE}\tCEO{k:05}\t2022-01-01\t\t{}", - listing_id + 50_000 - ) - }) - .map_err(|source| CurateShortsCmdBenchError::FixtureIo { - path: map_path.clone(), - source, - })?; - } else { - writeln!( - w, - "{DEFAULT_MAPPING_SOURCE}\tCEO{k:05}\t2017-01-01\t\t{listing_id}" - ) - .map_err(|source| CurateShortsCmdBenchError::FixtureIo { - path: map_path.clone(), - source, - })?; - } - } - for a in 0..200usize { - let listing_id = (a as i32) + 1; - writeln!( - w, - "{DEFAULT_MAPPING_SOURCE}\tALIAS{a:03}\t2017-01-01\t\t{listing_id}" - ) - .map_err(|source| CurateShortsCmdBenchError::FixtureIo { - path: map_path.clone(), - source, - })?; - } - w.flush() - .map_err(|source| CurateShortsCmdBenchError::FixtureIo { - path: map_path.clone(), - source, - })?; - } - - // 2. Write synthetic concatenated-BSON ceoShorts file with fixed-seed SplitMix64. - // Distribute base rows across all 218 semi-monthly dates (2017-04-15..=2026-04-30) and - // reserve explicit rows for same-key identical/conflicting duplicates and primary/alias - // identical/conflicting collisions. - struct SeedRow { - key_idx: usize, - report_date: i32, - shares_short: f64, - net_change: Option, - pct_float: Option, - } - - let mut min_report_date: Option = None; - let mut max_report_date: Option = None; - - { - let f = File::create(&bson_path).map_err(|source| { - CurateShortsCmdBenchError::FixtureIo { - path: bson_path.clone(), - source, - } - })?; - let mut w = BufWriter::with_capacity(1024 * 1024, f); - let mut rng = SplitMix64::new(CURATE_SHORTS_CMD_BENCH_SEED); - - let dup_identical_target = rows / 200; - let dup_conflict_target = rows / 200; - let alias_identical_target = rows / 200; - let alias_conflict_target = rows / 200; - let reserved_extras = dup_identical_target - + dup_conflict_target - + alias_identical_target - + alias_conflict_target; - let base_rows = rows.saturating_sub(reserved_extras); - - let mut dup_identical_seeds: Vec = Vec::with_capacity(dup_identical_target); - let mut dup_conflict_seeds: Vec = Vec::with_capacity(dup_conflict_target); - let mut alias_identical_seeds: Vec = Vec::with_capacity(alias_identical_target); - let mut alias_conflict_seeds: Vec = Vec::with_capacity(alias_conflict_target); - - let write_doc = |w: &mut BufWriter, doc: &RawDocumentBuf| { - w.write_all(doc.as_bytes()) - .map_err(|source| CurateShortsCmdBenchError::FixtureIo { - path: bson_path.clone(), - source, - }) - }; - - let append_date = |doc: &mut RawDocumentBuf, encoding: usize, report_date: i32| { - let epoch_secs = i64::from(report_date) * 86_400; - let epoch_millis = epoch_secs * 1_000; - match encoding % 5 { - 0 => doc.append(cstr!("timestamp"), BsonDateTime::from_millis(epoch_millis)), - 1 => doc.append(cstr!("timestamp"), epoch_secs as i32), - 2 => doc.append(cstr!("timestamp"), epoch_secs), - 3 => doc.append(cstr!("timestamp"), epoch_millis), - _ => doc.append(cstr!("timestamp"), epoch_secs as f64), - } - }; - - let mut emitted = 0usize; - for i in 0..base_rows { - let r = rng.next_u64(); - let date_idx = i % date_count; - let key_idx = ((i / date_count) + date_idx * 57) % key_count; - let report_date = all_dates[date_idx]; - let epoch_secs = i64::from(report_date) * 86_400; - - let mut doc = RawDocumentBuf::new(); - - // ~0.5% semantically skipped docs (1 in 200) - if i % 200 == 199 { - match (i / 200) % 4 { - 0 => { - doc.append(cstr!("symbol"), ""); - doc.append(cstr!("timestamp"), epoch_secs); - doc.append(cstr!("sharesShort"), 1_000_i32); - } - 1 => { - doc.append(cstr!("symbol"), format!("CEO{key_idx:05}")); - doc.append(cstr!("timestamp"), "2024-03-15"); - doc.append(cstr!("sharesShort"), 1_000_i32); - } - 2 => { - doc.append(cstr!("symbol"), format!("CEO{key_idx:05}")); - doc.append(cstr!("timestamp"), epoch_secs as f64 + 0.5); - doc.append(cstr!("sharesShort"), 1_000_i32); - } - _ => { - doc.append(cstr!("symbol"), format!("CEO{key_idx:05}")); - doc.append(cstr!("timestamp"), epoch_secs); - doc.append(cstr!("sharesShort"), "bad_num"); - } - } - write_doc(&mut w, &doc)?; - emitted += 1; - continue; - } - - doc.append(cstr!("symbol"), format!("CEO{key_idx:05}")); - - // Mix report_date BSON encodings: DateTime, Int32 secs, Int64 secs, Int64 millis, integral Double - append_date(&mut doc, i, report_date); - - // ~0.5% invalid shares_short (negative), otherwise deterministic positive count - let invalid_shares = i % 200 == 100; - let shares_short = if invalid_shares { - -50.0 - } else { - ((r % 5_000_000) as f64) * 1.0 - }; - doc.append(cstr!("sharesShort"), shares_short); - - // Optional netChange: present, null, absent, or occasional wrong type - let net_change_val = match i % 10 { - 0 => { - doc.append(cstr!("netChange"), RawBson::Null); - None - } - 1 => None, // absent - 2 if i % 100 == 2 => { - doc.append(cstr!("netChange"), "n/a"); - None - } - _ => { - let delta = ((r >> 16) % 200_000) as f64 - 100_000.0; - doc.append(cstr!("netChange"), delta); - Some(delta) - } - }; - - // Optional pctFloat: present, null, absent, or occasional wrong type - let pct_float_val = match i % 12 { - 0 => { - doc.append(cstr!("pctFloat"), RawBson::Null); - None - } - 1 => None, // absent - 3 if i % 120 == 3 => { - doc.append(cstr!("pctFloat"), true); - None - } - _ => { - let pct = ((r >> 32) % 2500) as f64 / 100.0; - doc.append(cstr!("pctFloat"), pct); - Some(pct) - } - }; - - write_doc(&mut w, &doc)?; - emitted += 1; - - // Track full date span and collect clean mapped single-range seeds for explicit - // duplicate and alias-collision pairs. - if !invalid_shares && key_idx % 50 < 48 { - min_report_date = Some(min_report_date.map_or(report_date, |m| m.min(report_date))); - max_report_date = Some(max_report_date.map_or(report_date, |m| m.max(report_date))); - if key_idx < 200 { - if alias_identical_seeds.len() < alias_identical_target { - alias_identical_seeds.push(SeedRow { - key_idx, - report_date, - shares_short, - net_change: net_change_val, - pct_float: pct_float_val, - }); - } else if alias_conflict_seeds.len() < alias_conflict_target { - alias_conflict_seeds.push(SeedRow { - key_idx, - report_date, - shares_short, - net_change: net_change_val, - pct_float: pct_float_val, - }); - } - } else if dup_identical_seeds.len() < dup_identical_target { - dup_identical_seeds.push(SeedRow { - key_idx, - report_date, - shares_short, - net_change: net_change_val, - pct_float: pct_float_val, - }); - } else if dup_conflict_seeds.len() < dup_conflict_target { - dup_conflict_seeds.push(SeedRow { - key_idx, - report_date, - shares_short, - net_change: net_change_val, - pct_float: pct_float_val, - }); - } - } - } - - let mut emit_seed = |sym: String, - encoding: usize, - seed: &SeedRow, - shares_override: Option| - -> Result<(), CurateShortsCmdBenchError> { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("symbol"), sym); - append_date(&mut doc, encoding, seed.report_date); - doc.append( - cstr!("sharesShort"), - shares_override.unwrap_or(seed.shares_short), - ); - if let Some(v) = seed.net_change { - doc.append(cstr!("netChange"), v); - } - if let Some(v) = seed.pct_float { - doc.append(cstr!("pctFloat"), v); - } - write_doc(&mut w, &doc)?; - emitted += 1; - Ok(()) - }; - - for (idx, seed) in dup_identical_seeds.iter().enumerate() { - emit_seed(format!("CEO{:05}", seed.key_idx), idx, seed, None)?; - } - for (idx, seed) in dup_conflict_seeds.iter().enumerate() { - emit_seed( - format!("CEO{:05}", seed.key_idx), - idx + 1, - seed, - Some(seed.shares_short + 1_000.0), - )?; - } - for (idx, seed) in alias_identical_seeds.iter().enumerate() { - emit_seed(format!("ALIAS{:03}", seed.key_idx), idx + 2, seed, None)?; - } - for (idx, seed) in alias_conflict_seeds.iter().enumerate() { - emit_seed( - format!("ALIAS{:03}", seed.key_idx), - idx + 3, - seed, - Some(seed.shares_short + 1_000.0), - )?; - } - - // If `rows` is tiny and we didn't collect all reserved seeds, top up with clean base docs. - let mut fill_idx = base_rows; - while emitted < rows { - let r = rng.next_u64(); - let date_idx = fill_idx % date_count; - let key_idx = ((fill_idx / date_count) + date_idx * 57) % key_count; - let report_date = all_dates[date_idx]; - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("symbol"), format!("CEO{key_idx:05}")); - append_date(&mut doc, fill_idx, report_date); - doc.append(cstr!("sharesShort"), ((r % 5_000_000) as f64) * 1.0); - write_doc(&mut w, &doc)?; - emitted += 1; - fill_idx += 1; - } - debug_assert_eq!(emitted, rows); - - w.flush() - .map_err(|source| CurateShortsCmdBenchError::FixtureIo { - path: bson_path.clone(), - source, - })?; - } - - let args = CurateShortsArgs { - ceo_shorts: bson_path, - provider_mapping: map_path, - out_dir: out_dir.clone(), - key_field: DEFAULT_KEY_FIELD.to_string(), - report_date_field: DEFAULT_REPORT_DATE_FIELD.to_string(), - shares_short_field: "sharesShort".to_string(), - net_change_field: Some("netChange".to_string()), - pct_float_field: Some("pctFloat".to_string()), - mapping_source: DEFAULT_MAPPING_SOURCE.to_string(), - }; - - let timed = run_curate_shorts_timed(&args).map_err(CurateShortsCmdBenchError::Run)?; - - let read_back_rows = - verify_parquet_shorts_row_count(&out_dir, timed.report.curate_stats.rows_out) - .map_err(CurateShortsCmdBenchError::Verify)?; - - let decode_elapsed_ms = timed.decode_elapsed_secs * 1_000.0; - let curate_elapsed_ms = timed.curate_elapsed_secs * 1_000.0; - let write_elapsed_ms = timed.write_elapsed_secs * 1_000.0; - let total_elapsed_secs = - timed.decode_elapsed_secs + timed.curate_elapsed_secs + timed.write_elapsed_secs; - let total_elapsed_ms = total_elapsed_secs * 1_000.0; - - let (decode_rows_per_sec, _) = compute_rates(rows, timed.decode_elapsed_secs); - let (curate_rows_per_sec, _) = - compute_rates(timed.report.decode.rows_out, timed.curate_elapsed_secs); - let (write_rows_per_sec, _) = - compute_rates(timed.report.write_stats.rows_written, timed.write_elapsed_secs); - let (total_rows_per_sec, _) = compute_rates(rows, total_elapsed_secs); - - let input_mb_per_sec = if timed.decode_elapsed_secs > 0.0 { - (timed.report.bytes_read as f64 / MIB) / timed.decode_elapsed_secs - } else { - 0.0 - }; - let write_mb_per_sec = if timed.write_elapsed_secs > 0.0 { - (timed.report.write_stats.bytes_written as f64 / MIB) / timed.write_elapsed_secs - } else { - 0.0 - }; - - let report = CurateShortsCmdBenchReport { - rows, - key_count, - min_report_date, - max_report_date, - docs_framed: timed.report.docs_framed, - bytes_read: timed.report.bytes_read, - peak_chunk_bytes: timed.report.peak_chunk_bytes, - rows_out: timed.report.curate_stats.rows_out, - listings_out: timed.report.curate_stats.listings_out, - files_written: timed.report.write_stats.files_written, - row_groups_written: timed.report.write_stats.row_groups_written, - bytes_written: timed.report.write_stats.bytes_written, - read_back_rows, - decode_elapsed_ms, - decode_rows_per_sec, - input_mb_per_sec, - curate_elapsed_ms, - curate_rows_per_sec, - write_elapsed_ms, - write_rows_per_sec, - write_mb_per_sec, - total_elapsed_ms, - total_rows_per_sec, - checksum: timed.checksum, - decode: timed.report.decode, - curate_stats: timed.report.curate_stats, - }; - - drop(temp); - Ok((report, temp_path)) -} - -/// Runs the fixed-seed end-to-end `curate-shorts` file -> Parquet benchmark for `rows` synthetic -/// `ceoShorts` BSON documents and `provider_mapping.tsv`. -pub fn run_curate_shorts_command_benchmark( - rows: usize, -) -> Result { - let (report, _) = run_curate_shorts_command_benchmark_tracked(rows)?; - Ok(report) -} - -/// Default total document count for `bench-curate-events-cmd` (~98.5% `qmFilings` / ~1.5% `qmEarnings`). -pub const DEFAULT_CURATE_EVENTS_CMD_BENCH_ROWS: usize = 500_000; -/// Live QA MongoDB dataset size (`30.52M` `qmFilings` + `444.9k` `qmEarnings`) used for single-core extrapolation. -pub const CURATE_EVENTS_FULL_DATASET_ROWS: f64 = 30_520_000.0 + 444_900.0; -const CURATE_EVENTS_CMD_BENCH_SEED: u64 = 0x570C_4B07_E7E4_7501; -const CURATE_EVENTS_CMD_BENCH_KEYS: usize = 5_000; - -/// Errors returned by [`run_curate_events_cmd_benchmark`]. -#[derive(Debug)] -pub enum CurateEventsCmdBenchError { - FixtureIo { - path: PathBuf, - source: io::Error, - }, - Run(crate::run_curate_events::RunCurateEventsError), - Verify(ParquetEventsError), -} - -impl std::fmt::Display for CurateEventsCmdBenchError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Self::FixtureIo { path, source } => { - write!(f, "benchmark fixture I/O '{}': {source}", path.display()) - } - Self::Run(err) => write!(f, "{err}"), - Self::Verify(err) => write!(f, "Parquet verify failed: {err}"), - } - } -} - -impl std::error::Error for CurateEventsCmdBenchError { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - match self { - Self::FixtureIo { source, .. } => Some(source), - Self::Run(err) => Some(err), - Self::Verify(err) => Some(err), - } - } -} - -/// Summary metrics produced by [`run_curate_events_cmd_benchmark`]. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct CurateEventsCmdBenchReport { - pub rows: usize, - pub key_count: usize, - pub filings_docs_framed: u64, - pub filings_bytes_read: u64, - pub earnings_docs_framed: u64, - pub earnings_bytes_read: u64, - pub peak_chunk_bytes: usize, - pub rows_out: usize, - pub filings_out: usize, - pub earnings_out: usize, - pub listings_out: usize, - pub files_written: usize, - pub row_groups_written: usize, - pub bytes_written: u64, - pub read_back_rows: usize, - pub decode_elapsed_ms: f64, - pub decode_rows_per_sec: f64, - pub input_mb_per_sec: f64, - pub curate_elapsed_ms: f64, - pub curate_rows_per_sec: f64, - pub write_elapsed_ms: f64, - pub write_rows_per_sec: f64, - pub write_mb_per_sec: f64, - pub total_elapsed_ms: f64, - pub total_rows_per_sec: f64, - pub total_extrap_full_secs: f64, - pub checksum: u64, - pub filings_decode: crate::bson_qm_events::BsonQmFilingsDecodeStats, - pub earnings_decode: crate::bson_qm_events::BsonQmEarningsDecodeStats, - pub curate_stats: crate::curate_events::CurateEventsStats, -} - -fn run_curate_events_cmd_benchmark_tracked( - rows: usize, -) -> Result<(CurateEventsCmdBenchReport, PathBuf), CurateEventsCmdBenchError> { - use std::io::{BufWriter, Write}; - - use bson::raw::{cstr, RawBsonRef, RawDocumentBuf}; - use bson::DateTime as BsonDateTime; - - use crate::bson_eod_prices::MILLIS_PER_DAY; - use crate::bson_qm_events::{ - BsonQmEarningsDecodeStats, BsonQmFilingsDecodeStats, DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD, - DEFAULT_EARNINGS_KEY_FIELD, DEFAULT_EARNINGS_REPORT_DATE_FIELD, DEFAULT_FILINGS_KEY_FIELD, - DEFAULT_FILINGS_TIMEFILED_FIELD, - }; - use crate::curate_events::CurateEventsStats; - use crate::run_curate_events::{ - run_curate_events_timed, CurateEventsArgs, DEFAULT_EVENTS_MAPPING_SOURCE, - }; - - const MIB: f64 = 1024.0 * 1024.0; - const FORM_TYPES: [&str; 10] = [ - "8-K", - "10-Q", - "10-K", - "4", - "144", - "News release", - "Interim financial statements", - "Annual financial statements", - "MD&A", - "52-109", - ]; - const ANNOUNCE_TIMES: [&str; 3] = ["N/A", "AMC", "BTO"]; - - let temp = BenchTempDir::new_in_with_prefix( - &std::env::temp_dir(), - "curate-etl-bench-curate-events-cmd", - ) - .map_err(|(path, source)| CurateEventsCmdBenchError::FixtureIo { path, source })?; - let temp_path = temp.path.clone(); - - if rows == 0 { - drop(temp); - return Ok(( - CurateEventsCmdBenchReport { - rows: 0, - key_count: 0, - filings_docs_framed: 0, - filings_bytes_read: 0, - earnings_docs_framed: 0, - earnings_bytes_read: 0, - peak_chunk_bytes: 0, - rows_out: 0, - filings_out: 0, - earnings_out: 0, - listings_out: 0, - files_written: 0, - row_groups_written: 0, - bytes_written: 0, - read_back_rows: 0, - decode_elapsed_ms: 0.0, - decode_rows_per_sec: 0.0, - input_mb_per_sec: 0.0, - curate_elapsed_ms: 0.0, - curate_rows_per_sec: 0.0, - write_elapsed_ms: 0.0, - write_rows_per_sec: 0.0, - write_mb_per_sec: 0.0, - total_elapsed_ms: 0.0, - total_rows_per_sec: 0.0, - total_extrap_full_secs: 0.0, - checksum: 0, - filings_decode: BsonQmFilingsDecodeStats::default(), - earnings_decode: BsonQmEarningsDecodeStats::default(), - curate_stats: CurateEventsStats::default(), - }, - temp_path, - )); - } - - let key_count = CURATE_EVENTS_CMD_BENCH_KEYS; - let mapped_keys = (key_count * 98) / 100; // ~2% unmapped keys - let keys: Vec = (0..key_count) - .map(|i| { - if i % 3 == 0 { - format!("QM{i:04}:CA") - } else { - format!("QM{i:04}") - } - }) - .collect(); - - // Write provider_mapping.tsv - let mapping_path = temp.path.join("provider_mapping.tsv"); - { - let f = fs::File::create(&mapping_path).map_err(|source| { - CurateEventsCmdBenchError::FixtureIo { - path: mapping_path.clone(), - source, - } - })?; - let mut w = BufWriter::with_capacity(256 * 1024, f); - for (idx, key) in keys.iter().take(mapped_keys).enumerate() { - let listing_id = (idx as i32) + 1; - writeln!( - w, - "{DEFAULT_EVENTS_MAPPING_SOURCE}\t{key}\t2015-01-01\t\t{listing_id}" - ) - .map_err(|source| CurateEventsCmdBenchError::FixtureIo { - path: mapping_path.clone(), - source, - })?; - } - w.flush() - .map_err(|source| CurateEventsCmdBenchError::FixtureIo { - path: mapping_path.clone(), - source, - })?; - } - - let min_day = ymd_to_epoch_days(2015, 1, 2).unwrap_or(16_437); - let max_day = ymd_to_epoch_days(2025, 12, 31).unwrap_or(20_453); - let day_span = (max_day - min_day + 1) as u64; - - let earnings_target = ((rows as u64 * 15) / 1_000).max(1) as usize; - let filings_target = rows.saturating_sub(earnings_target); - - let filings_path = temp.path.join("qmFilings.bson"); - let earnings_path = temp.path.join("qmEarnings.bson"); - - let mut rng = SplitMix64::new(CURATE_EVENTS_CMD_BENCH_SEED); - - // Record a sample of (key_idx, epoch_day) from qualifying 8-K / News release filings so ~40% - // of synthetic earnings link to a real same-day filing. - let mut link_anchors: Vec<(usize, i32)> = Vec::with_capacity(earnings_target); - - { - let f = fs::File::create(&filings_path).map_err(|source| { - CurateEventsCmdBenchError::FixtureIo { - path: filings_path.clone(), - source, - } - })?; - let mut w = BufWriter::with_capacity(1024 * 1024, f); - let mut doc = RawDocumentBuf::new(); - - for i in 0..filings_target { - doc = RawDocumentBuf::new(); - let key_idx = (rng.next_u64() as usize) % key_count; - let epoch_day = min_day + (rng.next_u64() % day_span) as i32; - let (y, m, d) = epoch_days_to_ymd(epoch_day); - let hh = (rng.next_u64() % 18) + 6; // 06..=23 - let mm = rng.next_u64() % 60; - let ss = rng.next_u64() % 60; - let tz = if (4..=10).contains(&m) { "EDT" } else { "EST" }; - let form_idx = (rng.next_u64() as usize) % FORM_TYPES.len(); - let form_type = FORM_TYPES[form_idx]; - let roll = rng.next_u64() % 1_000; - - doc.append(cstr!("symbol"), keys[key_idx].as_str()); - doc.append( - cstr!("timefiled"), - format!("{y:04}-{m:02}-{d:02}T{hh:02}:{mm:02}:{ss:02} {tz}"), - ); - if roll < 5 { - // ~0.5% semantic skip (blank formtype) - doc.append(cstr!("formtype"), " "); - } else { - doc.append(cstr!("formtype"), form_type); - if (form_idx == 0 || form_idx == 5) && link_anchors.len() < earnings_target { - link_anchors.push((key_idx, epoch_day)); - } - } - - if roll == 10 { - doc.append(cstr!("filingId"), 42_i32); // wrong type -> nulled - } else { - doc.append(cstr!("filingId"), format!("F-{i:08}")); - } - - if roll == 11 { - doc.append(cstr!("url"), false); // wrong type -> nulled - } else if i % 4 != 0 { - doc.append(cstr!("url"), format!("https://filings.example/{i}")); - } else { - doc.append(cstr!("url"), RawBsonRef::Null); - } - - w.write_all(doc.as_bytes()).map_err(|source| { - CurateEventsCmdBenchError::FixtureIo { - path: filings_path.clone(), - source, - } - })?; - } - let _ = doc; - w.flush() - .map_err(|source| CurateEventsCmdBenchError::FixtureIo { - path: filings_path.clone(), - source, - })?; - } - - { - let f = fs::File::create(&earnings_path).map_err(|source| { - CurateEventsCmdBenchError::FixtureIo { - path: earnings_path.clone(), - source, - } - })?; - let mut w = BufWriter::with_capacity(256 * 1024, f); - for i in 0..earnings_target { - let mut doc = RawDocumentBuf::new(); - let (key_idx, epoch_day) = if i % 5 < 2 && i < link_anchors.len() { - link_anchors[i] - } else { - ( - (rng.next_u64() as usize) % key_count, - min_day + (rng.next_u64() % day_span) as i32, - ) - }; - let (y, m, d) = epoch_days_to_ymd(epoch_day); - let roll = rng.next_u64() % 1_000; - - doc.append(cstr!("qmSearchCode"), keys[key_idx].as_str()); - if i % 2 == 0 { - doc.append( - cstr!("reportDate"), - BsonDateTime::from_millis(i64::from(epoch_day) * MILLIS_PER_DAY), - ); - } else { - doc.append(cstr!("reportDate"), format!("{y:04}-{m:02}-{d:02}")); - } - - if roll < 5 { - doc.append(cstr!("announceTime"), ""); // ~0.5% semantic skip - } else { - let at = ANNOUNCE_TIMES[(rng.next_u64() as usize) % ANNOUNCE_TIMES.len()]; - doc.append(cstr!("announceTime"), at); - } - - let fpe_day = epoch_day - 45; - if roll == 12 { - doc.append(cstr!("periodEndDate"), "bad-date"); - } else { - let (fy, fm, fd) = epoch_days_to_ymd(fpe_day); - doc.append(cstr!("periodEndDate"), format!("{fy:04}-{fm:02}-{fd:02}")); - } - - let eps = ((rng.next_u64() % 800) as f64 - 200.0) / 100.0; - if roll == 13 { - doc.append(cstr!("actualEps"), "bad-eps"); - } else { - doc.append(cstr!("actualEps"), eps); - } - doc.append( - cstr!("revenue"), - ((rng.next_u64() % 50_000) as i64 + 10) * 1_000_000, - ); - // Include post-hoc consensusEps to verify it is ignored on the hot path. - doc.append(cstr!("consensusEps"), eps + 0.05); - - w.write_all(doc.as_bytes()).map_err(|source| { - CurateEventsCmdBenchError::FixtureIo { - path: earnings_path.clone(), - source, - } - })?; - } - w.flush() - .map_err(|source| CurateEventsCmdBenchError::FixtureIo { - path: earnings_path.clone(), - source, - })?; - } - - let out_dir = temp.path.join("out"); - let args = CurateEventsArgs { - qm_filings: filings_path, - qm_earnings: earnings_path, - provider_mapping: mapping_path, - out_dir: out_dir.clone(), - filings_key_field: DEFAULT_FILINGS_KEY_FIELD.to_string(), - filings_timefiled_field: DEFAULT_FILINGS_TIMEFILED_FIELD.to_string(), - filings_form_type_field: "formtype".to_string(), - filings_filing_id_field: Some("filingId".to_string()), - filings_url_field: Some("url".to_string()), - earnings_key_field: DEFAULT_EARNINGS_KEY_FIELD.to_string(), - earnings_report_date_field: DEFAULT_EARNINGS_REPORT_DATE_FIELD.to_string(), - earnings_announce_time_field: DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD.to_string(), - earnings_fiscal_period_end_field: Some("periodEndDate".to_string()), - earnings_actual_eps_field: Some("actualEps".to_string()), - earnings_revenue_field: Some("revenue".to_string()), - mapping_source: DEFAULT_EVENTS_MAPPING_SOURCE.to_string(), - }; - - let timed = run_curate_events_timed(&args).map_err(CurateEventsCmdBenchError::Run)?; - - let read_back_rows = verify_parquet_events_row_count( - &out_dir, - timed.report.write_stats.rows_by_year.keys().copied(), - timed.report.write_stats.rows_written, - ) - .map_err(CurateEventsCmdBenchError::Verify)?; - - let total_bytes_read = timed.report.filings_bytes_read + timed.report.earnings_bytes_read; - let decode_elapsed_ms = timed.decode_elapsed_secs * 1_000.0; - let curate_elapsed_ms = timed.curate_elapsed_secs * 1_000.0; - let write_elapsed_ms = timed.write_elapsed_secs * 1_000.0; - let total_elapsed_secs = - timed.decode_elapsed_secs + timed.curate_elapsed_secs + timed.write_elapsed_secs; - let total_elapsed_ms = total_elapsed_secs * 1_000.0; - - let (decode_rows_per_sec, _) = compute_rates(rows, timed.decode_elapsed_secs); - let input_mb_per_sec = if timed.decode_elapsed_secs > 0.0 { - (total_bytes_read as f64 / MIB) / timed.decode_elapsed_secs - } else { - 0.0 - }; - let (curate_rows_per_sec, _) = compute_rates( - timed.report.curate_stats.builder.filings_in - + timed.report.curate_stats.builder.earnings_in, - timed.curate_elapsed_secs, - ); - let (write_rows_per_sec, _) = - compute_rates(timed.report.write_stats.rows_written, timed.write_elapsed_secs); - let write_mb_per_sec = if timed.write_elapsed_secs > 0.0 { - (timed.report.write_stats.bytes_written as f64 / MIB) / timed.write_elapsed_secs - } else { - 0.0 - }; - let (total_rows_per_sec, _) = compute_rates(rows, total_elapsed_secs); - let total_extrap_full_secs = if total_rows_per_sec > 0.0 { - CURATE_EVENTS_FULL_DATASET_ROWS / total_rows_per_sec - } else { - 0.0 - }; - - let peak_chunk_bytes = timed - .report - .filings_peak_chunk_bytes - .max(timed.report.earnings_peak_chunk_bytes); - - let report = CurateEventsCmdBenchReport { - rows, - key_count, - filings_docs_framed: timed.report.filings_docs_framed, - filings_bytes_read: timed.report.filings_bytes_read, - earnings_docs_framed: timed.report.earnings_docs_framed, - earnings_bytes_read: timed.report.earnings_bytes_read, - peak_chunk_bytes, - rows_out: timed.report.curate_stats.rows_out, - filings_out: timed.report.curate_stats.filings_out, - earnings_out: timed.report.curate_stats.earnings_out, - listings_out: timed.report.curate_stats.listings_out, - files_written: timed.report.write_stats.files_written, - row_groups_written: timed.report.write_stats.row_groups_written, - bytes_written: timed.report.write_stats.bytes_written, - read_back_rows, - decode_elapsed_ms, - decode_rows_per_sec, - input_mb_per_sec, - curate_elapsed_ms, - curate_rows_per_sec, - write_elapsed_ms, - write_rows_per_sec, - write_mb_per_sec, - total_elapsed_ms, - total_rows_per_sec, - total_extrap_full_secs, - checksum: timed.checksum, - filings_decode: timed.report.filings_decode, - earnings_decode: timed.report.earnings_decode, - curate_stats: timed.report.curate_stats, - }; - - drop(temp); - Ok((report, temp_path)) -} - -/// Runs the fixed-seed end-to-end `curate-events` file -> Parquet benchmark for `rows` synthetic -/// `qmFilings` (~98.5%) + `qmEarnings` (~1.5%) BSON documents and `provider_mapping.tsv`. -pub fn run_curate_events_cmd_benchmark( - rows: usize, -) -> Result { - let (report, _) = run_curate_events_cmd_benchmark_tracked(rows)?; - Ok(report) -} - -/// Summary metrics produced by [`run_fundamentals_benchmark`]. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct FundamentalsBenchReport { - pub rows: usize, - pub filings_in: usize, - pub key_count: usize, - pub rows_out: usize, - pub keys_out: usize, - pub snapshots_out: usize, - pub rows_elapsed_ms: f64, - pub snapshots_elapsed_ms: f64, - pub total_elapsed_ms: f64, - pub rows_per_sec: f64, - pub ns_per_row: f64, - pub checksum: u64, - pub stats: FundamentalsStats, -} - -fn format_bench_filing_timefiled(epoch_day: i32, hour: u8, minute: u8, second: u8) -> String { - let (y, m, d) = epoch_days_to_ymd(epoch_day); - let zone = if (4..=10).contains(&m) { "EDT" } else { "EST" }; - format!("{y:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02} {zone}") -} - -/// Runs the fixed-seed two-stage `fundamentals` benchmark (`build_fundamentals_rows` + -/// `build_fundamentals_snapshots`) for `rows` synthetic statement observations. -/// -/// Generates filings and observations before timing, exercising both `UsTsx` and `TsxvCse` venue -/// classes, linked periodic filings (10-Q/10-K/40-F/SEDAR), statutory-lag fallback, exact -/// duplicates, complete 4-quarter histories for TTM, and late Q1-style amendments. -pub fn run_fundamentals_benchmark( - rows: usize, -) -> Result { - if rows == 0 { - return Ok(FundamentalsBenchReport { - rows: 0, - filings_in: 0, - key_count: 0, - rows_out: 0, - keys_out: 0, - snapshots_out: 0, - rows_elapsed_ms: 0.0, - snapshots_elapsed_ms: 0.0, - total_elapsed_ms: 0.0, - rows_per_sec: 0.0, - ns_per_row: 0.0, - checksum: 0, - stats: FundamentalsStats::default(), - }); - } - - let key_count = (rows / FUNDAMENTALS_BENCH_TARGET_OBS_PER_KEY).max(1); - let mut venues: BTreeMap = BTreeMap::new(); - for k in 1..=(key_count as i32) { - let venue = if k % 10 < 7 { - StatutoryLagVenue::UsTsx - } else { - StatutoryLagVenue::TsxvCse - }; - venues.insert(k, venue); - } - - let base_start = ymd_to_epoch_days(2015, 3, 31).unwrap_or(16_525); - let mut rng = SplitMix64::new(FUNDAMENTALS_BENCH_SEED); - let mut observations: Vec> = Vec::with_capacity(rows); - let mut filings: Vec> = Vec::with_capacity(rows); - - let mut period_step: i32 = 0; - while observations.len() < rows { - for key in 1..=(key_count as i32) { - if observations.len() >= rows { - break; - } - let venue = venues[&key]; - let currency = match venue { - StatutoryLagVenue::UsTsx => { - if key % 5 == 0 { - "CAD" - } else { - "USD" - } - } - StatutoryLagVenue::TsxvCse => "CAD", - }; - - let is_annual = period_step % 5 == 4; - let quarter_index = period_step - (period_step / 5); - let period_end = if is_annual { - base_start + (quarter_index - 1) * 91 + 1 - } else { - base_start + quarter_index * 91 - }; - let fiscal_period = if is_annual { - FiscalPeriod::Annual - } else { - FiscalPeriod::Quarterly - }; - - let rev = ((rng.next_u64() % 50_000) + 1_000) as f64; - let fields = FundamentalsFields { - revenue: Some(rev), - net_income: Some(rev * 0.12), - operating_cash_flow: Some(rev * 0.18), - total_assets: Some(rev * 4.5), - total_equity: Some(rev * 2.1), - shares_outstanding: Some(1_000_000.0 + (key as f64) * 100.0), - }; - - let roll = rng.next_u64() % 100; - let report_date = if roll < 75 { - let lag = 25 + (rng.next_u64() % 30) as i32; - let file_day = period_end + lag; - let form_type = match (venue, fiscal_period) { - (StatutoryLagVenue::UsTsx, FiscalPeriod::Quarterly) => "10-Q", - (StatutoryLagVenue::UsTsx, FiscalPeriod::Annual) => { - if key % 5 == 0 { - "40-F" - } else { - "10-K" - } - } - (StatutoryLagVenue::TsxvCse, FiscalPeriod::Quarterly) => { - "Interim financial statements/report - English" - } - (StatutoryLagVenue::TsxvCse, FiscalPeriod::Annual) => { - "Annual financial statements - English" - } - }; - let hour = 8 + (rng.next_u64() % 10) as u8; - let minute = (rng.next_u64() % 60) as u8; - filings.push(QmFiling { - key, - timefiled: format_bench_filing_timefiled(file_day, hour, minute, 0), - form_type: form_type.to_string(), - filing_id: None, - url: None, - }); - if roll < 50 { - Some(file_day) - } else { - None - } - } else { - None - }; - - if roll % 19 == 0 { - filings.push(QmFiling { - key, - timefiled: format_bench_filing_timefiled(period_end + 10, 16, 15, 0), - form_type: "8-K".to_string(), - filing_id: None, - url: None, - }); - } - - let obs = FinancialObservation { - key, - period_end, - fiscal_period, - currency: currency.to_string(), - report_date, - fields, - }; - observations.push(obs.clone()); - - // ~3% exact duplicate - if observations.len() < rows && roll < 3 { - observations.push(obs); - } - - // ~2% late amendment of prior quarter (after current quarter's filing) - if observations.len() < rows && !is_annual && quarter_index >= 1 && (3..5).contains(&roll) - { - let prior_pe = period_end - 91; - let amend_day = period_end + 60; - filings.push(QmFiling { - key, - timefiled: format_bench_filing_timefiled(amend_day, 17, 0, 0), - form_type: "10-Q/A".to_string(), - filing_id: None, - url: None, - }); - observations.push(FinancialObservation { - key, - period_end: prior_pe, - fiscal_period: FiscalPeriod::Quarterly, - currency: currency.to_string(), - report_date: Some(amend_day), - fields: FundamentalsFields { - revenue: Some(rev * 1.03), - net_income: Some(rev * 0.13), - operating_cash_flow: None, - total_assets: None, - total_equity: Some(rev * 2.15), - shares_outstanding: None, - }, - }); - } - } - period_step += 1; - } - - let filings_in = filings.len(); - - let rows_start = Instant::now(); - let built = build_fundamentals_rows(observations, filings, &venues); - let rows_elapsed_secs = rows_start.elapsed().as_secs_f64(); - - let snaps_start = Instant::now(); - let snapshots = build_fundamentals_snapshots(&built.rows, FUNDAMENTALS_BENCH_SNAPSHOT_K)?; - let snaps_elapsed_secs = snaps_start.elapsed().as_secs_f64(); - - let total_elapsed_secs = rows_elapsed_secs + snaps_elapsed_secs; - let (rows_per_sec, ns_per_row) = compute_rates(rows, total_elapsed_secs); - - let checksum = black_box(hash_fundamentals_outputs(&built.rows, &snapshots)); - - Ok(FundamentalsBenchReport { - rows, - filings_in, - key_count, - rows_out: built.stats.rows_out, - keys_out: built.stats.keys_out, - snapshots_out: snapshots.len(), - rows_elapsed_ms: rows_elapsed_secs * 1_000.0, - snapshots_elapsed_ms: snaps_elapsed_secs * 1_000.0, - total_elapsed_ms: total_elapsed_secs * 1_000.0, - rows_per_sec, - ns_per_row, - checksum, - stats: built.stats, - }) -} - -#[inline] -fn mix_opt_f64(hash: u64, value: Option) -> u64 { - match value { - None => mix_u64(hash, 0), - Some(v) => mix_u64(mix_u64(hash, 1), v.to_bits()), - } -} - -#[inline] -fn mix_str(mut hash: u64, value: &str) -> u64 { - hash = mix_u64(hash, value.len() as u64); - for byte in value.bytes() { - hash = mix_u64(hash, u64::from(byte)); - } - hash -} - -#[inline] -fn mix_fundamentals_fields(mut hash: u64, fields: &FundamentalsFields) -> u64 { - hash = mix_opt_f64(hash, fields.revenue); - hash = mix_opt_f64(hash, fields.net_income); - hash = mix_opt_f64(hash, fields.operating_cash_flow); - hash = mix_opt_f64(hash, fields.total_assets); - hash = mix_opt_f64(hash, fields.total_equity); - hash = mix_opt_f64(hash, fields.shares_outstanding); - hash -} - -fn hash_fundamentals_outputs( - rows: &[crate::fundamentals::FundamentalsRow], - snapshots: &[crate::fundamentals::FundamentalsSnapshot], -) -> u64 { - let mut hash = 0u64; - for row in rows { - hash = mix_u64(hash, row.key as u64); - hash = mix_u64(hash, row.period_end as u64); - hash = mix_u64(hash, row.fiscal_period as u64); - hash = mix_str(hash, &row.currency); - hash = mix_u64(hash, row.known_at_utc_micros as u64); - hash = mix_str(hash, row.known_at_source); - hash = mix_fundamentals_fields(hash, &row.fields); - } - for snap in snapshots { - hash = mix_u64(hash, snap.key as u64); - hash = mix_u64(hash, snap.effective_known_at_utc_micros as u64); - hash = mix_str(hash, snap.known_at_source); - hash = mix_u64(hash, u64::from(snap.has_estimated_lag)); - hash = mix_u64(hash, snap.periods.len() as u64); - for slot in &snap.periods { - hash = mix_u64(hash, slot.period_end as u64); - hash = mix_u64(hash, slot.fiscal_period as u64); - hash = mix_str(hash, &slot.currency); - hash = mix_u64(hash, slot.known_at_utc_micros as u64); - hash = mix_str(hash, slot.known_at_source); - hash = mix_u64(hash, u64::from(slot.has_estimated_lag)); - hash = mix_fundamentals_fields(hash, &slot.fields); - } - match &snap.ttm { - None => { - hash = mix_u64(hash, 0); - } - Some(ttm) => { - hash = mix_u64(hash, 1); - hash = mix_u64(hash, ttm.ending_period_end as u64); - hash = mix_str(hash, &ttm.currency); - hash = mix_u64(hash, u64::from(ttm.has_estimated_lag)); - hash = mix_opt_f64(hash, ttm.flows.revenue); - hash = mix_opt_f64(hash, ttm.flows.net_income); - hash = mix_opt_f64(hash, ttm.flows.operating_cash_flow); - } - } - } - hash -} - #[cfg(test)] mod tests { use super::*; @@ -12185,140 +6211,6 @@ mod tests { assert_eq!(report.stats, BsonEodDecodeStats::default()); } - #[test] - fn bson_stream_benchmark_small_run_matches_buffer_and_stream_helper() { - let a = run_bson_stream_benchmark(20_000).expect("stream bench must succeed"); - let b = run_bson_stream_benchmark(20_000).expect("stream bench must be deterministic"); - - assert_eq!(a.rows, 20_000); - assert_eq!(a.bytes, b.bytes); - assert!(a.bytes > 0); - assert_eq!(a.checksum, b.checksum); - assert_eq!(a.stats, b.stats); - assert_eq!(a.stats.docs_in, 20_000); - assert_eq!(a.stats.decoded + a.stats.rejected_total(), a.stats.docs_in); - assert_eq!( - a.peak_buffer_capacity, - crate::bson_stream::DEFAULT_CHUNK_CAPACITY_BYTES - ); - assert!(a.buffer_rows_per_sec.is_finite() && a.buffer_rows_per_sec >= 0.0); - assert!(a.stream_rows_per_sec.is_finite() && a.stream_rows_per_sec >= 0.0); - assert!(a.stream_to_buffer_ratio.is_finite() && a.stream_to_buffer_ratio >= 0.0); - - // Verify decode_eod_price_stream produces identical stats and checksum on the same bytes. - let buf = build_bson_eod_prices_bench_buffer(20_000); - let mut h = 0u64; - let mut eh = 0u64; - let s = crate::bson_stream::decode_eod_price_stream( - IrregularShortReader::new(&buf), - BsonStreamOptions::default(), - |bar| { - h = mix_bytes(h, bar.eod_search_code.as_bytes()); - h = mix_u64(h, bar.session_date as u64); - h = mix_u64(h, bar.open.to_bits()); - h = mix_u64(h, bar.high.to_bits()); - h = mix_u64(h, bar.low.to_bits()); - h = mix_u64(h, bar.close.to_bits()); - h = mix_u64(h, bar.adj_volume.to_bits()); - }, - |offset, _err| { - eh = mix_u64(eh, offset ^ 0xDEAD_BEEF_CAFE_BABEu64); - }, - ) - .expect("decode_eod_price_stream must succeed"); - assert_eq!(s, a.stats); - assert_eq!(h ^ eh, a.checksum); - } - - #[test] - fn bson_stream_benchmark_zero_rows_handles_cleanly() { - let report = run_bson_stream_benchmark(0).expect("zero-row stream bench must succeed"); - assert_eq!(report.rows, 0); - assert_eq!(report.bytes, 0); - assert_eq!(report.buffer_elapsed_ms, 0.0); - assert_eq!(report.stream_elapsed_ms, 0.0); - assert_eq!(report.stream_to_buffer_ratio, 0.0); - assert_eq!(report.peak_buffer_capacity, 0); - assert_eq!(report.checksum, 0); - assert_eq!(report.stats, BsonEodDecodeStats::default()); - } - - #[test] - fn mongo_stream_benchmark_small_run_is_deterministic_with_parity() { - let a = run_mongo_stream_benchmark(2_000).expect("mongo-stream bench must succeed"); - let b = run_mongo_stream_benchmark(2_000).expect("mongo-stream bench must be deterministic"); - - assert_eq!(a.rows, 2_000); - assert_eq!(a.bytes, b.bytes); - assert!(a.bytes > 0); - assert_eq!(a.checksum, b.checksum); - assert_eq!(a.stats, b.stats); - assert_eq!(a.stats.docs_in, 2_000); - assert_eq!(a.stats.decoded + a.stats.rejected_total(), a.stats.docs_in); - assert!(a.plain_docs_per_sec.is_finite() && a.plain_docs_per_sec >= 0.0); - assert!(a.cursor_docs_per_sec.is_finite() && a.cursor_docs_per_sec >= 0.0); - assert!(a.cursor_to_plain_ratio.is_finite() && a.cursor_to_plain_ratio >= 0.0); - } - - #[test] - fn mongo_stream_benchmark_zero_rows_handles_cleanly() { - let report = run_mongo_stream_benchmark(0).expect("zero-row mongo-stream bench must succeed"); - assert_eq!(report.rows, 0); - assert_eq!(report.bytes, 0); - assert_eq!(report.plain_elapsed_ms, 0.0); - assert_eq!(report.cursor_elapsed_ms, 0.0); - assert_eq!(report.cursor_to_plain_ratio, 0.0); - assert_eq!(report.peak_pending_capacity, 0); - assert_eq!(report.checksum, 0); - assert_eq!(report.stats, BsonEodDecodeStats::default()); - } - - #[test] - fn bson_qm_actions_benchmark_small_run_is_deterministic() { - let a = run_bson_qm_actions_benchmark(20_000); - let b = run_bson_qm_actions_benchmark(20_000); - - assert_eq!(a.rows, 20_000); - assert_eq!(a.split_rows + a.dividend_rows, 20_000); - assert!(a.split_rows > 0 && a.dividend_rows > 0); - assert_eq!(a.bytes, b.bytes); - assert!(a.bytes > 0); - assert_eq!(a.checksum, b.checksum); - assert_eq!(a.split_stats, b.split_stats); - assert_eq!(a.dividend_stats, b.dividend_stats); - assert_eq!(a.split_stats.docs_in, a.split_rows); - assert_eq!(a.dividend_stats.docs_in, a.dividend_rows); - assert_eq!( - a.split_stats.decoded + a.split_stats.rejected_total(), - a.split_stats.docs_in - ); - assert_eq!( - a.dividend_stats.decoded + a.dividend_stats.rejected_total(), - a.dividend_stats.docs_in - ); - assert!(a.split_stats.split_noop_ratio_one > 0); - assert!(a.dividend_stats.rejected_total() > 0); - assert!(a.docs_per_sec.is_finite() && a.docs_per_sec >= 0.0); - assert!(a.mb_per_sec.is_finite() && a.mb_per_sec >= 0.0); - assert!(a.ns_per_doc.is_finite() && a.ns_per_doc >= 0.0); - } - - #[test] - fn bson_qm_actions_benchmark_zero_rows_handles_cleanly() { - let report = run_bson_qm_actions_benchmark(0); - assert_eq!(report.rows, 0); - assert_eq!(report.split_rows, 0); - assert_eq!(report.dividend_rows, 0); - assert_eq!(report.bytes, 0); - assert_eq!(report.elapsed_ms, 0.0); - assert_eq!(report.docs_per_sec, 0.0); - assert_eq!(report.mb_per_sec, 0.0); - assert_eq!(report.ns_per_doc, 0.0); - assert_eq!(report.checksum, 0); - assert_eq!(report.split_stats, BsonQmActionDecodeStats::default()); - assert_eq!(report.dividend_stats, BsonQmActionDecodeStats::default()); - } - #[test] fn curate_bars_benchmark_small_run_is_deterministic_and_cleans_up() { let (a, dir_a) = run_curate_bars_benchmark_tracked(20_000).unwrap(); @@ -12829,808 +6721,4 @@ mod tests { assert_eq!(report.total_rows_per_sec, 0.0); assert_eq!(report.stats, crate::curate_fx::CurateFx1dStats::default()); } - - #[test] - fn curate_adj_benchmark_small_run_is_deterministic_and_cleans_up() { - let (a, dir_a) = run_curate_adj_benchmark_tracked(25_000).unwrap(); - let (b, dir_b) = run_curate_adj_benchmark_tracked(25_000).unwrap(); - - assert!( - !dir_a.exists(), - "temp dir {} should be removed", - dir_a.display() - ); - assert!( - !dir_b.exists(), - "temp dir {} should be removed", - dir_b.display() - ); - assert_eq!(a.events, 25_000); - assert_eq!(a.splits_in + a.dividends_in, 25_000); - assert_eq!(a.stats.splits_in, a.splits_in); - assert_eq!(a.stats.dividends_in, a.dividends_in); - assert_eq!(a.key_count, CURATE_ADJ_BENCH_KEY_COUNT); - assert!(a.rows_out > 0); - assert_eq!(a.rows_out, b.rows_out); - assert_eq!(a.read_back_rows, a.rows_out); - assert_eq!(a.listings_out, b.listings_out); - assert_eq!(a.files_written, 1); - assert_eq!(a.row_groups_written, b.row_groups_written); - assert_eq!(a.bytes_written, b.bytes_written); - assert!(a.bytes_written > 0); - assert_eq!(a.stats, b.stats); - assert_eq!(a.checksum, b.checksum); - assert_ne!(a.checksum, 0); - assert!(a.stage_events_per_sec.is_finite() && a.stage_events_per_sec >= 0.0); - assert!(a.stage_ns_per_event.is_finite() && a.stage_ns_per_event >= 0.0); - assert!(a.parquet_rows_per_sec.is_finite() && a.parquet_rows_per_sec >= 0.0); - assert!(a.total_events_per_sec.is_finite() && a.total_events_per_sec >= 0.0); - assert_eq!( - a.stats.splits_in, - a.stats.splits_dropped_unmapped - + a.stats.splits_collision_collapsed - + a.stats.builder.split_events_in - ); - assert_eq!( - a.stats.dividends_in, - a.stats.dividends_dropped_unmapped - + a.stats.dividends_collision_collapsed - + a.stats.builder.dividend_events_in - ); - assert_eq!( - a.stats.listing_collision_collapsed, - a.stats.splits_collision_collapsed + a.stats.dividends_collision_collapsed - ); - assert!(a.stats.splits_dropped_unmapped > 0); - assert!(a.stats.dividends_dropped_unmapped > 0); - assert!(a.stats.listing_collision_collapsed > 0); - } - - #[test] - fn curate_adj_benchmark_zero_events_handles_cleanly() { - let (report, dir) = run_curate_adj_benchmark_tracked(0).unwrap(); - assert!(!dir.exists(), "temp dir {} should be removed", dir.display()); - assert_eq!(report.events, 0); - assert_eq!(report.splits_in, 0); - assert_eq!(report.dividends_in, 0); - assert_eq!(report.key_count, CURATE_ADJ_BENCH_KEY_COUNT); - assert_eq!(report.rows_out, 0); - assert_eq!(report.listings_out, 0); - assert_eq!(report.read_back_rows, 0); - assert_eq!(report.files_written, 0); - assert_eq!(report.row_groups_written, 0); - assert_eq!(report.bytes_written, 0); - assert_eq!(report.checksum, 0); - assert_eq!(report.stage_elapsed_ms, 0.0); - assert_eq!(report.stage_events_per_sec, 0.0); - assert_eq!(report.stage_ns_per_event, 0.0); - assert_eq!(report.parquet_elapsed_ms, 0.0); - assert_eq!(report.parquet_rows_per_sec, 0.0); - assert_eq!(report.total_elapsed_ms, 0.0); - assert_eq!(report.total_events_per_sec, 0.0); - assert_eq!( - report.stats, - crate::curate_adj::CurateAdjFactorsStats::default() - ); - } - - #[test] - fn curate_corporate_actions_benchmark_small_run_is_deterministic_and_cleans_up() { - let (a, dir_a) = run_curate_corporate_actions_benchmark_tracked(20_000).unwrap(); - let (b, dir_b) = run_curate_corporate_actions_benchmark_tracked(20_000).unwrap(); - - assert!( - !dir_a.exists(), - "temp dir {} should be removed", - dir_a.display() - ); - assert!( - !dir_b.exists(), - "temp dir {} should be removed", - dir_b.display() - ); - assert_eq!(a.events, 20_000); - assert_eq!(a.splits_in + a.dividends_in + a.delistings_in, 20_000); - assert_eq!(a.stats.builder.splits_in, a.splits_in); - assert_eq!(a.stats.builder.dividends_in, a.dividends_in); - assert_eq!(a.stats.builder.delistings_in, a.delistings_in); - assert_eq!(a.rows_out, b.rows_out); - assert_eq!(a.read_back_rows, a.rows_out); - assert_eq!(a.listings_out, b.listings_out); - assert_eq!(a.files_written, 1); - assert_eq!(a.row_groups_written, b.row_groups_written); - assert_eq!(a.bytes_written, b.bytes_written); - assert!(a.bytes_written > 0); - assert_eq!(a.stats, b.stats); - assert_eq!(a.checksum, b.checksum); - assert_ne!(a.checksum, 0); - assert!(a.stage_events_per_sec.is_finite() && a.stage_events_per_sec >= 0.0); - assert!(a.stage_ns_per_event.is_finite() && a.stage_ns_per_event >= 0.0); - assert!(a.parquet_rows_per_sec.is_finite() && a.parquet_rows_per_sec >= 0.0); - assert!(a.total_events_per_sec.is_finite() && a.total_events_per_sec >= 0.0); - - // Conservation invariants - assert_eq!(a.stats.rows_in, a.stats.builder.rows_out); - assert_eq!( - a.stats.rows_in, - a.stats.rows_out - + a.stats.dropped_unmapped - + a.stats.dropped_unmapped_successor - + a.stats.dropped_self_successor - + a.stats.dropped_known_at_out_of_range - + a.stats.listing_collision_collapsed - + a.stats.listing_collision_dropped - ); - - // All major builder and curation counters exercised - assert!(a.stats.builder.splits_out > 0); - assert!(a.stats.builder.split_noops_dropped > 0); - assert!(a.stats.builder.dividends_out > 0); - assert!(a.stats.builder.dividend_zero_cash_dropped > 0); - assert!(a.stats.builder.otc_delist_transfers_out > 0); - assert!(a.stats.builder.delistings_out > 0); - assert!(a.stats.builder.delist_without_outcome > 0); - assert!(a.stats.dropped_unmapped > 0); - assert!(a.stats.dropped_unmapped_successor > 0); - assert!(a.stats.dropped_self_successor > 0); - assert!(a.stats.dropped_known_at_out_of_range > 0); - assert!(a.stats.listing_collision_collapsed > 0); - assert!(a.stats.listing_collision_dropped > 0); - } - - #[test] - fn curate_corporate_actions_benchmark_zero_events_handles_cleanly() { - let (report, dir) = run_curate_corporate_actions_benchmark_tracked(0).unwrap(); - assert!(!dir.exists(), "temp dir {} should be removed", dir.display()); - assert_eq!(report.events, 0); - assert_eq!(report.splits_in, 0); - assert_eq!(report.dividends_in, 0); - assert_eq!(report.delistings_in, 0); - assert_eq!(report.rows_out, 0); - assert_eq!(report.read_back_rows, 0); - assert_eq!(report.listings_out, 0); - assert_eq!(report.files_written, 0); - assert_eq!(report.row_groups_written, 0); - assert_eq!(report.bytes_written, 0); - assert_eq!(report.checksum, 0); - assert_eq!(report.stage_elapsed_ms, 0.0); - assert_eq!(report.stage_events_per_sec, 0.0); - assert_eq!(report.stage_ns_per_event, 0.0); - assert_eq!(report.parquet_elapsed_ms, 0.0); - assert_eq!(report.parquet_rows_per_sec, 0.0); - assert_eq!(report.total_elapsed_ms, 0.0); - assert_eq!(report.total_events_per_sec, 0.0); - assert_eq!( - report.stats, - crate::curate_corporate_actions::CurateCorporateActionsStats::default() - ); - } - - #[test] - fn curate_bars_cmd_benchmark_small_run_cleans_up_and_conserves_counts() { - let (report, dir) = run_curate_bars_cmd_benchmark_tracked(4_000).unwrap(); - assert!(!dir.exists(), "temp dir {} should be removed", dir.display()); - assert_eq!(report.rows, 4_000); - assert_eq!(report.eod_docs_framed, 4_000); - assert_eq!(report.eod_decode.docs_in, 4_000); - assert_eq!( - report.eod_decode.decoded, - report.buffered_bars + report.bars_unmapped_source_dropped - ); - assert!(report.bars_unmapped_source_dropped > 0); - assert!(report.rows_out > 0); - assert_eq!(report.read_back_rows_seq, report.rows_out); - assert_eq!(report.read_back_rows, report.rows_out); - assert!(report.parallel_threads >= 1); - assert!(report.write_speedup.is_finite() && report.write_speedup > 0.0); - assert!(report.bytes_per_buffered_bar >= 64.0); - assert_eq!( - report.split_rekey.splits_in, - report.split_rekey.splits_applied - + report.split_rekey.splits_collision_collapsed - + report.split_rekey.splits_unmapped_qm - + report.split_rekey.splits_no_eod_partner - + report.split_rekey.splits_noop_dropped - + report.splits_decode.rejected_total() - ); - assert!(report.split_rekey.splits_applied > 0); - assert!(report.split_rekey.splits_collision_collapsed > 0); - assert!(report.split_rekey.splits_unmapped_qm > 0); - assert!(report.split_rekey.splits_no_eod_partner > 0); - assert!(report.split_rekey.splits_noop_dropped > 0); - assert!(report.curate_stats.dropped_ts_out_of_range > 0); - assert!(report.curate_stats.listing_collision_collapsed > 0); - assert!(report.curate_stats.listing_collision_dropped > 0); - assert!(report.curate_stats.dropped_missing_currency > 0); - assert!(report.qm_docs_framed > 0); - assert_eq!( - report.qm_rekey.qm_in, - report.qm_rekey.qm_attached - + report.qm_rekey.qm_unmapped_qm - + report.qm_rekey.qm_no_eod_partner - + report.qm_prices_decode.rejected_total() - ); - assert!(report.qm_rekey.qm_attached > 0); - assert!(report.qm_matched_us > 0); - assert!(report.qm_matched_ca > 0); - assert_eq!( - report.qm_matched_us + report.qm_matched_ca, - report.qm_rekey.qm_attached - ); - assert!(report.qm_rekey.qm_unmapped_qm > 0); - assert!(report.qm_rekey.qm_no_eod_partner > 0); - assert!(report.qm_prices_decode.rejected_wrong_type > 0); - assert_eq!( - report.qm_rekey.qm_volumes_attached, - report.curate_stats.builder.qm_rows_in - ); - assert_eq!( - report.curate_stats.builder.volume_checked - + report.curate_stats.builder.volume_unchecked, - report.curate_stats.builder.rows_out - ); - assert_eq!( - report.curate_stats.builder.volume_within_tolerance - + report.curate_stats.builder.volume_mismatched, - report.curate_stats.builder.volume_checked - ); - assert!(report.injected_mismatches > 0); - assert_eq!( - report.curate_stats.builder.volume_mismatched, - report.injected_mismatches - ); - assert_eq!( - report.mismatch_samples_out, - report.injected_mismatches.min(crate::bars::MAX_MISMATCH_SAMPLES) - ); - } - - #[test] - fn curate_bars_cmd_benchmark_zero_rows_handles_cleanly() { - let (report, dir) = run_curate_bars_cmd_benchmark_tracked(0).unwrap(); - assert!(!dir.exists(), "temp dir {} should be removed", dir.display()); - assert_eq!(report.rows, 0); - assert_eq!(report.read_back_rows_seq, 0); - assert_eq!(report.read_back_rows, 0); - assert!(report.parallel_threads >= 1); - assert!(report.write_speedup.is_finite() && report.write_speedup > 0.0); - assert_eq!(report.eod_docs_framed, 0); - assert_eq!(report.qm_docs_framed, 0); - assert_eq!(report.qm_matched_us, 0); - assert_eq!(report.qm_matched_ca, 0); - assert_eq!(report.injected_mismatches, 0); - assert_eq!(report.curate_stats.builder.volume_mismatched, 0); - assert_eq!(report.mismatch_samples_out, 0); - } - - #[test] - fn curate_adj_cmd_benchmark_small_run_is_deterministic_cleans_up_and_conserves_counts() { - let (a, dir_a) = run_curate_adj_cmd_benchmark_tracked(5_000).unwrap(); - let (b, dir_b) = run_curate_adj_cmd_benchmark_tracked(5_000).unwrap(); - - assert!( - !dir_a.exists(), - "temp dir {} should be removed", - dir_a.display() - ); - assert!( - !dir_b.exists(), - "temp dir {} should be removed", - dir_b.display() - ); - assert_eq!(a.events, 5_000); - assert_eq!(a.splits_docs_framed + a.dividends_docs_framed, 5_000); - assert_eq!(a.checksum, b.checksum); - assert_ne!(a.checksum, 0); - assert_eq!(a.rows_out, b.rows_out); - assert_eq!(a.read_back_rows, a.rows_out); - assert_eq!(a.bytes_written, b.bytes_written); - assert!(a.bars_files_read >= 16); - assert!(a.bars_rows_loaded > 0); - assert!(a.dividends_with_prev_close > 0); - assert!(a.dividends_without_prev_close > 0); - assert!(a.curate_stats.splits_dropped_unmapped > 0); - assert!(a.curate_stats.dividends_dropped_unmapped > 0); - assert!(a.curate_stats.splits_collision_collapsed > 0); - assert!(a.curate_stats.dividends_collision_collapsed > 0); - assert!(a.curate_stats.builder.split_noops_dropped > 0); - assert!(a.curate_stats.builder.dividend_zero_cash_dropped > 0); - assert!(a.curate_stats.builder.dividends_currency_mismatch > 0); - assert_eq!( - a.splits_docs_framed as usize, - a.splits_decode.rejected_total() - + a.curate_stats.splits_dropped_unmapped - + a.curate_stats.splits_dropped_fenced - + a.curate_stats.splits_collision_collapsed - + a.curate_stats.builder.split_events_in - ); - assert_eq!( - a.dividends_docs_framed as usize, - a.dividends_decode.rejected_total() - + a.curate_stats.dividends_dropped_unmapped - + a.curate_stats.dividends_dropped_fenced - + a.curate_stats.dividends_collision_collapsed - + a.curate_stats.builder.dividend_events_in - ); - assert_eq!( - a.dividends_decode.decoded, - a.dividends_with_prev_close - + a.dividends_without_prev_close - + a.curate_stats.dividends_dropped_unmapped - ); - } - - #[test] - fn curate_adj_cmd_benchmark_zero_events_handles_cleanly() { - let (report, dir) = run_curate_adj_cmd_benchmark_tracked(0).unwrap(); - assert!(!dir.exists(), "temp dir {} should be removed", dir.display()); - assert_eq!(report.events, 0); - assert_eq!(report.bars_files_read, 1); - assert_eq!(report.bars_rows_loaded, 1); - assert_eq!(report.bars_listings_indexed, 1); - assert_eq!(report.rows_out, 0); - assert_eq!(report.files_written, 1); - assert!(report.bytes_written > 0); - assert_eq!(report.read_back_rows, 0); - assert_eq!(report.splits_docs_framed, 0); - assert_eq!(report.dividends_docs_framed, 0); - } - - #[test] - fn curate_corporate_actions_cmd_benchmark_small_run_is_deterministic_cleans_up_and_conserves_counts() - { - let (a, dir_a) = run_curate_corporate_actions_cmd_benchmark_tracked(10_000).unwrap(); - let (b, dir_b) = run_curate_corporate_actions_cmd_benchmark_tracked(10_000).unwrap(); - - assert!( - !dir_a.exists(), - "temp dir {} should be removed", - dir_a.display() - ); - assert!( - !dir_b.exists(), - "temp dir {} should be removed", - dir_b.display() - ); - assert_eq!(a.events, 10_000); - assert_eq!( - a.splits_docs_framed as usize - + a.dividends_docs_framed as usize - + a.delistings_rows_loaded, - 10_000 - ); - assert_eq!(a.checksum, b.checksum); - assert_ne!(a.checksum, 0); - assert_eq!(a.rows_out, b.rows_out); - assert_eq!(a.read_back_rows, a.rows_out); - assert_eq!(a.bytes_written, b.bytes_written); - assert!(a.splits_docs_framed > 0); - assert!(a.dividends_docs_framed > 0); - assert!(a.delistings_rows_loaded > 0); - assert!(a.curate_stats.builder.splits_out > 0); - assert!(a.curate_stats.builder.dividends_out > 0); - assert!(a.curate_stats.builder.otc_delist_transfers_out > 0); - assert!(a.curate_stats.builder.delistings_out > 0); - assert_eq!(a.curate_stats.builder.delist_without_outcome, 0); - assert_eq!(a.splits_docs_framed as usize, a.splits_decode.docs_in); - assert_eq!( - a.splits_decode.docs_in, - a.splits_decode.decoded + a.splits_decode.rejected_total() - ); - assert_eq!(a.dividends_docs_framed as usize, a.dividends_decode.docs_in); - assert_eq!( - a.dividends_decode.docs_in, - a.dividends_decode.decoded + a.dividends_decode.rejected_total() - ); - assert_eq!( - a.curate_stats.rows_in, - a.curate_stats.rows_out - + a.curate_stats.dropped_unmapped - + a.curate_stats.dropped_unmapped_successor - + a.curate_stats.dropped_self_successor - + a.curate_stats.dropped_known_at_out_of_range - + a.curate_stats.listing_collision_collapsed - + a.curate_stats.listing_collision_dropped - ); - } - - #[test] - fn curate_corporate_actions_cmd_benchmark_zero_events_handles_cleanly() { - let (report, dir) = run_curate_corporate_actions_cmd_benchmark_tracked(0).unwrap(); - assert!(!dir.exists(), "temp dir {} should be removed", dir.display()); - assert_eq!(report.events, 0); - assert_eq!(report.rows_out, 0); - assert_eq!(report.files_written, 0); - assert_eq!(report.bytes_written, 0); - assert_eq!(report.read_back_rows, 0); - assert_eq!(report.splits_docs_framed, 0); - assert_eq!(report.dividends_docs_framed, 0); - assert_eq!(report.delistings_rows_loaded, 0); - } - - #[test] - fn curate_fx_cmd_benchmark_small_run_is_deterministic_cleans_up_and_conserves_counts() { - let (a, dir_a) = run_curate_fx_cmd_benchmark_tracked(2_000).unwrap(); - let (b, dir_b) = run_curate_fx_cmd_benchmark_tracked(2_000).unwrap(); - - assert!( - !dir_a.exists(), - "temp dir {} should be removed", - dir_a.display() - ); - assert!( - !dir_b.exists(), - "temp dir {} should be removed", - dir_b.display() - ); - assert_eq!(a.rows, 2_000); - assert_eq!(a.checksum, b.checksum); - assert_ne!(a.checksum, 0); - assert_eq!(a.rows_out, b.rows_out); - assert!(a.rows_out > 0); - assert_eq!(a.read_back_rows, a.rows_out); - assert_eq!(a.files_written, 1); - assert_eq!(a.bytes_written, b.bytes_written); - assert!(a.bytes_written > 0); - assert!(a.eod_cad_forex_kept > 0); - assert!(a.eod_other_symbol_skipped > 0); - assert!(a.eod_decode.rejected_total() > 0); - assert!(a.te_decode.docs_matched > 0); - assert!(a.te_decode.docs_other_symbol > 0); - assert!(a.te_decode.points_decoded > 0); - assert!(a.te_decode.rejected_total() > 0); - assert!(a.curate_stats.builder.eod_rows_out > 0); - assert!(a.curate_stats.builder.te_rows_out > 0); - assert!(a.curate_stats.builder.te_superseded_by_eod > 0); - assert!(a.curate_stats.builder.overlap_within_tolerance > 0); - assert!(a.curate_stats.builder.overlap_mismatched > 0); - - // Conservation invariants - assert_eq!(a.eod_docs_framed as usize, a.eod_decode.docs_in); - assert_eq!( - a.eod_decode.docs_in, - a.eod_decode.decoded + a.eod_decode.rejected_total() - ); - assert_eq!( - a.eod_decode.decoded, - a.eod_cad_forex_kept + a.eod_other_symbol_skipped - ); - assert_eq!(a.eod_cad_forex_kept, a.curate_stats.builder.eod.rows_in); - assert_eq!(a.te_docs_framed as usize, a.te_decode.docs_in); - assert_eq!( - a.te_decode.docs_in, - a.te_decode.docs_matched - + a.te_decode.docs_other_symbol - + a.te_decode.docs_rejected_total() - ); - assert_eq!( - a.te_decode.points_in, - a.te_decode.points_decoded + a.te_decode.rejected_total() - ); - assert_eq!(a.te_decode.points_decoded, a.curate_stats.builder.te.rows_in); - assert_eq!(a.curate_stats.rows_in, a.curate_stats.builder.rows_out); - assert_eq!(a.curate_stats.rows_out, a.rows_out); - } - - #[test] - fn curate_fx_cmd_benchmark_zero_rows_handles_cleanly() { - let (report, dir) = run_curate_fx_cmd_benchmark_tracked(0).unwrap(); - assert!(!dir.exists(), "temp dir {} should be removed", dir.display()); - assert_eq!(report.rows, 0); - assert_eq!(report.eod_docs_framed, 0); - assert_eq!(report.te_docs_framed, 0); - assert_eq!(report.rows_out, 0); - assert_eq!(report.files_written, 0); - assert_eq!(report.bytes_written, 0); - assert_eq!(report.read_back_rows, 0); - assert_eq!(report.checksum, 0); - } - - #[test] - fn curate_shorts_cmd_benchmark_small_run_is_deterministic_cleans_up_and_conserves_counts() { - let (a, dir_a) = run_curate_shorts_command_benchmark_tracked(5_000).unwrap(); - let (b, dir_b) = run_curate_shorts_command_benchmark_tracked(5_000).unwrap(); - let all_dates = semi_monthly_report_dates(); - - assert!(!dir_a.exists(), "temp dir {} should be removed", dir_a.display()); - assert!(!dir_b.exists(), "temp dir {} should be removed", dir_b.display()); - assert_eq!(a.rows, 5_000); - assert_eq!(a.min_report_date, Some(all_dates[0])); - assert_eq!(a.max_report_date, Some(*all_dates.last().unwrap())); - assert_eq!(a.checksum, b.checksum); - assert_ne!(a.checksum, 0); - assert_eq!(a.rows_out, b.rows_out); - assert!(a.rows_out > 0); - assert_eq!(a.read_back_rows, a.rows_out); - assert_eq!(a.files_written, 1); - assert_eq!(a.bytes_written, b.bytes_written); - assert!(a.peak_chunk_bytes > 0); - assert!(a.decode.skipped_total() > 0); - assert!(a.decode.nulled_wrong_type_net_change > 0); - assert!(a.decode.nulled_wrong_type_pct_float > 0); - assert!(a.curate_stats.builder.dropped_invalid_shares_short > 0); - assert!(a.curate_stats.builder.duplicate_collapsed > 0); - assert!(a.curate_stats.builder.duplicate_conflict_dropped > 0); - assert!(a.curate_stats.dropped_unmapped > 0); - assert!(a.curate_stats.listing_collision_collapsed > 0); - assert!(a.curate_stats.listing_collision_dropped > 0); - - // Conservation invariants - assert_eq!(a.docs_framed as usize, a.decode.docs_in); - assert_eq!(a.decode.docs_in, a.decode.rows_out + a.decode.skipped_total()); - assert_eq!(a.decode.rows_out, a.curate_stats.builder.rows_in); - assert_eq!(a.curate_stats.rows_in, a.curate_stats.builder.rows_out); - assert_eq!( - a.curate_stats.rows_in, - a.curate_stats.rows_out - + a.curate_stats.dropped_unmapped - + a.curate_stats.listing_collision_collapsed - + a.curate_stats.listing_collision_dropped - ); - } - - #[test] - fn curate_shorts_cmd_benchmark_zero_rows_handles_cleanly() { - let (report, dir) = run_curate_shorts_command_benchmark_tracked(0).unwrap(); - assert!(!dir.exists(), "temp dir {} should be removed", dir.display()); - assert_eq!(report.rows, 0); - assert_eq!(report.docs_framed, 0); - assert_eq!(report.rows_out, 0); - assert_eq!(report.files_written, 0); - assert_eq!(report.bytes_written, 0); - assert_eq!(report.read_back_rows, 0); - assert_eq!(report.checksum, 0); - } - - #[test] - fn curate_events_cmd_benchmark_small_run_is_deterministic_cleans_up_and_conserves_counts() { - let (a, dir_a) = run_curate_events_cmd_benchmark_tracked(5_000).unwrap(); - let (b, dir_b) = run_curate_events_cmd_benchmark_tracked(5_000).unwrap(); - - assert!(!dir_a.exists(), "temp dir {} should be removed", dir_a.display()); - assert!(!dir_b.exists(), "temp dir {} should be removed", dir_b.display()); - assert_eq!(a.rows, 5_000); - assert_eq!(a.checksum, b.checksum); - assert_ne!(a.checksum, 0); - assert_eq!(a.rows_out, b.rows_out); - assert!(a.rows_out > 0); - assert_eq!(a.read_back_rows, a.rows_out); - assert!(a.files_written > 0); - assert_eq!(a.bytes_written, b.bytes_written); - assert!(a.peak_chunk_bytes > 0); - assert!(a.curate_stats.builder.earnings_linked_to_filing > 0); - assert!(a.curate_stats.builder.earnings_lagged_1605 > 0); - assert!(a.curate_stats.dropped_unmapped > 0); - - // Conservation invariants - assert_eq!(a.filings_docs_framed as usize, a.filings_decode.docs_in); - assert_eq!( - a.filings_decode.docs_in, - a.filings_decode.rows_out + a.filings_decode.skipped_total() - ); - assert_eq!(a.earnings_docs_framed as usize, a.earnings_decode.docs_in); - assert_eq!( - a.earnings_decode.docs_in, - a.earnings_decode.rows_out + a.earnings_decode.skipped_total() - ); - assert_eq!( - a.filings_decode.rows_out, - a.curate_stats.builder.filings_in - ); - assert_eq!( - a.earnings_decode.rows_out, - a.curate_stats.builder.earnings_in - ); - assert_eq!(a.curate_stats.rows_in, a.curate_stats.builder.rows_out); - assert_eq!( - a.curate_stats.rows_in, - a.curate_stats.rows_out - + a.curate_stats.dropped_unmapped - + a.curate_stats.listing_duplicate_collapsed - ); - } - - #[test] - fn curate_events_cmd_benchmark_zero_rows_handles_cleanly() { - let (report, dir) = run_curate_events_cmd_benchmark_tracked(0).unwrap(); - assert!(!dir.exists(), "temp dir {} should be removed", dir.display()); - assert_eq!(report.rows, 0); - assert_eq!(report.filings_docs_framed, 0); - assert_eq!(report.earnings_docs_framed, 0); - assert_eq!(report.rows_out, 0); - assert_eq!(report.files_written, 0); - assert_eq!(report.bytes_written, 0); - assert_eq!(report.read_back_rows, 0); - assert_eq!(report.checksum, 0); - } - - #[test] - fn bars_1m_benchmark_small_run_is_deterministic_and_conserves_counts() { - let a = run_bars_1m_benchmark(5_000).unwrap(); - let b = run_bars_1m_benchmark(5_000).unwrap(); - - assert_eq!(a.rows, 5_000); - assert_eq!(a.checksum, b.checksum); - assert_ne!(a.checksum, 0); - assert_eq!(a.rows_out, b.rows_out); - assert_eq!(a.build_stats, b.build_stats); - assert_eq!(a.close_stats, b.close_stats); - assert!(a.rows_out > 0); - assert!(a.build_stats.pre_rows_out > 0); - assert!(a.build_stats.rth_rows_out > 0); - assert!(a.build_stats.post_rows_out > 0); - assert!(a.build_stats.dropped_invalid_ohlc > 0); - assert!(a.build_stats.dropped_inconsistent_ohlc > 0); - assert!(a.build_stats.dropped_invalid_volume > 0); - assert!(a.build_stats.dropped_ts_out_of_range > 0); - assert!(a.close_stats.checked > 0); - - // Conservation invariants - assert_eq!( - a.build_stats.bars_in, - a.build_stats.rows_out - + a.build_stats.dropped_invalid_ohlc - + a.build_stats.dropped_inconsistent_ohlc - + a.build_stats.dropped_invalid_volume - + a.build_stats.dropped_ts_out_of_range - + a.build_stats.duplicate_collapsed - + a.build_stats.duplicate_conflict_dropped - ); - assert_eq!( - a.build_stats.rows_out, - a.build_stats.pre_rows_out + a.build_stats.rth_rows_out + a.build_stats.post_rows_out - ); - assert_eq!( - a.close_stats.checked + a.close_stats.unchecked, - a.close_stats.rth_sessions - ); - assert_eq!( - a.close_stats.within_tolerance + a.close_stats.mismatched, - a.close_stats.checked - ); - } - - #[test] - fn bars_1m_benchmark_zero_rows_handles_cleanly() { - let report = run_bars_1m_benchmark(0).unwrap(); - assert_eq!(report.rows, 0); - assert_eq!(report.rows_out, 0); - assert_eq!(report.keys_out, 0); - assert_eq!(report.daily_rows_in, 0); - assert_eq!(report.mismatch_samples_out, 0); - assert_eq!(report.checksum, 0); - assert_eq!(report.rows_per_sec, 0.0); - assert_eq!(report.ns_per_row, 0.0); - } - - #[test] - fn ilp_bars_1m_benchmark_small_run_is_deterministic_and_conserves_counts() { - let a = run_ilp_bars_1m_benchmark(5_000).unwrap(); - let b = run_ilp_bars_1m_benchmark(5_000).unwrap(); - - assert_eq!(a.rows, 5_000); - assert_eq!(a.rows_encoded, a.rows); - assert_eq!(a.shards, ILP_BARS_1M_BENCH_SHARDS); - assert_eq!(a.bytes, b.bytes); - assert_eq!(a.flushes, b.flushes); - assert_eq!(a.per_shard_rows, b.per_shard_rows); - assert_eq!(a.per_shard_rows.len(), ILP_BARS_1M_BENCH_SHARDS); - assert_eq!(a.per_shard_rows.iter().sum::(), a.rows_encoded); - assert!(a.bytes > 0); - assert!(a.bytes_per_row > 100.0); - assert!(a.flushes >= ILP_BARS_1M_BENCH_SHARDS); - } - - #[test] - fn ilp_bars_1m_benchmark_zero_rows_handles_cleanly() { - let report = run_ilp_bars_1m_benchmark(0).unwrap(); - assert_eq!(report.rows, 0); - assert_eq!(report.rows_encoded, 0); - assert_eq!(report.bytes, 0); - assert_eq!(report.flushes, 0); - assert_eq!(report.bytes_per_row, 0.0); - assert_eq!(report.rows_per_sec, 0.0); - assert_eq!(report.ns_per_row, 0.0); - assert_eq!(report.per_shard_rows, vec![0; ILP_BARS_1M_BENCH_SHARDS]); - } - - #[test] - fn fundamentals_benchmark_small_run_is_deterministic_and_conserves_counts() { - let a = run_fundamentals_benchmark(1_000).unwrap(); - let b = run_fundamentals_benchmark(1_000).unwrap(); - - assert_eq!(a.rows, 1_000); - assert_eq!(a.checksum, b.checksum); - assert_ne!(a.checksum, 0); - assert_eq!(a.rows_out, b.rows_out); - assert_eq!(a.snapshots_out, b.snapshots_out); - assert_eq!(a.stats, b.stats); - assert!(a.rows_out > 0); - assert!(a.snapshots_out > 0); - assert!(a.stats.rows_linked_to_filing > 0); - assert!(a.stats.rows_statutory_lag_estimate > 0); - assert!(a.stats.duplicate_collapsed > 0); - assert_eq!( - a.stats.observations_in, - a.stats.rows_out - + a.stats.observations_dropped_unknown_key - + a.stats.observations_dropped_non_finite - + a.stats.observations_dropped_date_out_of_range - + a.stats.observations_dropped_report_date_not_after_period_end - + a.stats.observations_dropped_unanchored_vintage - + a.stats.observations_dropped_stale_estimate - + a.stats.duplicate_collapsed - + a.stats.duplicate_conflict_dropped - ); - } - - #[test] - fn fundamentals_checksum_distinguishes_none_zero_slots_and_non_revenue_ttm() { - use crate::fundamentals::{ - FundamentalsPeriodSlot, FundamentalsSnapshot, FundamentalsTtm, TtmFlowFields, - }; - - let base_slot = FundamentalsPeriodSlot { - period_end: 19_000, - fiscal_period: FiscalPeriod::Quarterly, - currency: "USD".to_string(), - known_at_utc_micros: 1_000, - known_at_source: crate::events::KNOWN_AT_SOURCE_FILING_TIMESTAMP, - has_estimated_lag: false, - fields: FundamentalsFields { - revenue: Some(10.0), - net_income: None, - operating_cash_flow: Some(5.0), - total_assets: Some(100.0), - total_equity: Some(50.0), - shares_outstanding: Some(1_000.0), - }, - }; - let base_snap = FundamentalsSnapshot { - key: 1, - effective_known_at_utc_micros: 1_000, - known_at_source: crate::events::KNOWN_AT_SOURCE_FILING_TIMESTAMP, - has_estimated_lag: false, - periods: vec![base_slot], - ttm: Some(FundamentalsTtm { - ending_period_end: 19_000, - currency: "USD".to_string(), - flows: TtmFlowFields { - revenue: Some(40.0), - net_income: None, - operating_cash_flow: Some(20.0), - }, - has_estimated_lag: false, - }), - }; - - let h_base = hash_fundamentals_outputs(&[], &[base_snap.clone()]); - - // None vs Some(0.0) in slot net_income - let mut s_zero = base_snap.clone(); - s_zero.periods[0].fields.net_income = Some(0.0); - assert_ne!(h_base, hash_fundamentals_outputs(&[], &[s_zero])); - - // Non-revenue TTM flow change (operating_cash_flow) - let mut s_ttm = base_snap.clone(); - s_ttm.ttm.as_mut().unwrap().flows.operating_cash_flow = Some(21.0); - assert_ne!(h_base, hash_fundamentals_outputs(&[], &[s_ttm])); - - // Carried-forward slot provenance change - let mut s_prov = base_snap; - s_prov.periods[0].has_estimated_lag = true; - assert_ne!(h_base, hash_fundamentals_outputs(&[], &[s_prov])); - } - - #[test] - fn fundamentals_benchmark_zero_rows_handles_cleanly() { - let report = run_fundamentals_benchmark(0).unwrap(); - assert_eq!(report.rows, 0); - assert_eq!(report.filings_in, 0); - assert_eq!(report.rows_out, 0); - assert_eq!(report.snapshots_out, 0); - assert_eq!(report.checksum, 0); - assert_eq!(report.rows_per_sec, 0.0); - assert_eq!(report.ns_per_row, 0.0); - } } diff --git a/tools/curate-etl/src/bson_ceo_posts.rs b/tools/curate-etl/src/bson_ceo_posts.rs deleted file mode 100644 index 046ec0f9..00000000 --- a/tools/curate-etl/src/bson_ceo_posts.rs +++ /dev/null @@ -1,860 +0,0 @@ -//! Zero-copy raw BSON decoder for MongoDB `ceoPosts` documents (`M2.2g`). -//! -//! Decodes `&bson::RawDocument` slices in a single forward pass over `iter_elements()` without -//! allocating a `bson::Document`, emitting [`CeoPost<&str>`] rows (borrowing `key` directly from -//! the input buffer and allocating owned `String`s only for rows that will be emitted) via a -//! caller-supplied callback. -//! -//! # Unverified Live Schema & Explicit Timestamp Unit -//! -//! `apps/stock/data-ingestion/src/handlers/ceo/actions/get-posts.action.ts` establishes the -//! default stored field names (`ceoId`, `spielId`, `timestamp`, `edited`, `bot`, `userId`, -//! `spiel`), but the live MongoDB BSON types and whether `timestamp` / `edited` are stored in -//! epoch seconds or epoch milliseconds are **not verified** in the repository. Callers must -//! therefore supply [`CeoPostsTimestampUnit`] explicitly (there is intentionally no default). -//! -//! # Decoding & Validation Rules -//! - Every element and nested subdocument/array/JS-with-scope (up to depth `128`) of each -//! [`RawDocument`] is scanned and structurally validated to completion before applying semantic -//! skip rules, so structural BSON corruption always returns -//! `Err(BsonCeoPostsError::CorruptBson)` rather than being masked by an earlier semantic skip. -//! - `key` (`ceoId`): required non-blank UTF-8 BSON `String`, passed through verbatim (no -//! trimming). Missing, wrong type, or empty/whitespace-only strings skip the row under -//! `skipped_missing_key`, `skipped_wrong_key_type`, or `skipped_empty_key`. -//! - `spiel_id` (`spielId`): required UTF-8 BSON `String` (verbatim, non-blank) or `Int32` / -//! `Int64` rendered as decimal. Missing, wrong type, or empty/whitespace-only strings skip the -//! row under `skipped_missing_spiel_id`, `skipped_wrong_spiel_id_type`, or -//! `skipped_empty_spiel_id`. -//! - `timestamp` (`timestamp`): required `Int32`, `Int64`, finite integral `Double` in the -//! half-open `[-2^63, 2^63)` range, or BSON `DateTime` (already epoch milliseconds; unit -//! ignored). Under [`CeoPostsTimestampUnit::Seconds`], numeric values are multiplied by `1_000` -//! using `checked_mul`; overflow or out-of-range doubles skip under -//! `skipped_timestamp_out_of_range`. Non-finite or fractional doubles skip under -//! `skipped_invalid_timestamp`. Missing or other BSON types skip under -//! `skipped_missing_timestamp` or `skipped_wrong_timestamp_type`. Values `<= 0` are passed -//! through so [`crate::posts::build_posts`] remains the single place rejecting non-positive -//! creation timestamps. -//! - `edited` (`edited`, **point-in-time guard, fail closed**): -//! - Absent or BSON `Null` yields `edited_ms = None`. -//! - Numeric `0` (`Int32(0)`, `Int64(0)`, `Double(0.0)`, `Double(-0.0)`) or `Boolean(false)` -//! yields `edited_ms = None` and increments `edited_zero_or_false` (on emitted rows). -//! - Positive integral numeric values (`Int32`, `Int64`, finite integral `Double` in -//! `[-2^63, 2^63)`) converted with `unit` (checked multiply for seconds), or non-negative BSON -//! `DateTime` (including epoch-zero `DateTime(0)` -> `Some(0)` because the zero sentinel is -//! numeric), yield `edited_ms = Some(ms)`. -//! - Anything else — negative values, fractional or non-finite doubles, `Boolean(true)`, -//! `String`, other BSON types, seconds overflow, or repeated `edited` fields in the same -//! document — skips the row under `skipped_invalid_edited`. A row with a present but -//! unreadable `edited` field is never emitted as unedited. -//! - `text` (`spiel`): UTF-8 BSON `String` (verbatim); absent or BSON `Null` emits `String::new()` -//! and increments `empty_text` (on emitted rows); any other BSON type skips under -//! `skipped_wrong_text_type`. -//! - `bot` (`bot`): normalized only for emitted rows. UTF-8 `String` (verbatim), `Int32`/`Int64` -//! rendered as decimal, `Boolean` mapped to `"1"` / `"0"`, absent or `Null` -> `None`; any -//! other BSON type -> `None` and increments `nulled_wrong_type_bot`. -//! - `user_id` (`userId`): normalized only for emitted rows. UTF-8 `String` (verbatim), -//! `Int32`/`Int64` rendered as decimal, absent or `Null` -> `None`; any other BSON type -> -//! `None` and increments `nulled_wrong_type_user_id`. -//! - Deterministic semantic skip priority: `key` → `spiel_id` → `timestamp` → `edited` → `text`. -//! - Emitted-row counters (`edited_zero_or_false`, `nulled_wrong_type_bot`, -//! `nulled_wrong_type_user_id`, `empty_text`) are incremented only on rows that pass all skip -//! checks and are emitted to `on_row`. -//! - Conservation invariant: `docs_in == rows_out + skipped_total()`. - -use std::error::Error; -use std::fmt; - -use bson::raw::{RawBsonRef, RawDocument}; - -use crate::bson_eod_prices::{iter_raw_bson_docs, parse_single_raw_doc, BsonEodPriceError}; -use crate::posts::CeoPost; - -/// Default BSON field name for the `ceoPosts` channel / security key (`get-posts.action.ts`). -pub const DEFAULT_KEY_FIELD: &str = "ceoId"; -/// Default BSON field name for the `ceoPosts` post identifier (`get-posts.action.ts`). -pub const DEFAULT_SPIEL_ID_FIELD: &str = "spielId"; -/// Default BSON field name for the `ceoPosts` creation timestamp (`get-posts.action.ts`). -pub const DEFAULT_TIMESTAMP_FIELD: &str = "timestamp"; -/// Default BSON field name for the `ceoPosts` last-edit timestamp (`get-posts.action.ts`). -pub const DEFAULT_EDITED_FIELD: &str = "edited"; -/// Default BSON field name for the `ceoPosts` bot/newswire flag (`get-posts.action.ts`). -pub const DEFAULT_BOT_FIELD: &str = "bot"; -/// Default BSON field name for the `ceoPosts` author identifier (`get-posts.action.ts`). -pub const DEFAULT_USER_ID_FIELD: &str = "userId"; -/// Default BSON field name for the `ceoPosts` post body (`get-posts.action.ts`). -pub const DEFAULT_TEXT_FIELD: &str = "spiel"; - -/// Explicit numeric timestamp unit for `ceoPosts` `timestamp` and `edited` fields. -/// -/// Intentionally has no `Default`: the live MongoDB unit is unverified in the repository, so -/// callers must choose explicitly. BSON `DateTime` values are always epoch milliseconds and ignore -/// this setting. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum CeoPostsTimestampUnit { - /// Numeric `timestamp` / `edited` values are Unix epoch seconds (multiplied by `1_000`). - Seconds, - /// Numeric `timestamp` / `edited` values are Unix epoch milliseconds. - Millis, -} - -/// Borrowed BSON field-name configuration for decoding `ceoPosts` documents. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct CeoPostsFieldNames<'a> { - pub key: &'a str, - pub spiel_id: &'a str, - pub timestamp: &'a str, - pub edited: &'a str, - pub bot: &'a str, - pub user_id: &'a str, - pub text: &'a str, -} - -impl Default for CeoPostsFieldNames<'static> { - fn default() -> Self { - Self { - key: DEFAULT_KEY_FIELD, - spiel_id: DEFAULT_SPIEL_ID_FIELD, - timestamp: DEFAULT_TIMESTAMP_FIELD, - edited: DEFAULT_EDITED_FIELD, - bot: DEFAULT_BOT_FIELD, - user_id: DEFAULT_USER_ID_FIELD, - text: DEFAULT_TEXT_FIELD, - } - } -} - -impl<'a> CeoPostsFieldNames<'a> { - /// Validates that every configured field name is non-empty/non-blank and that no two - /// configured roles point to the same BSON field name. - pub fn validate(&self) -> Result<(), BsonCeoPostsError> { - let roles: [(&'static str, &str); 7] = [ - ("key", self.key), - ("spiel_id", self.spiel_id), - ("timestamp", self.timestamp), - ("edited", self.edited), - ("bot", self.bot), - ("user_id", self.user_id), - ("text", self.text), - ]; - - for &(role, name) in &roles { - if name.trim().is_empty() { - return Err(BsonCeoPostsError::InvalidFieldNames { - detail: format!("field name for '{role}' must not be empty or blank"), - }); - } - } - - for i in 0..roles.len() { - let (role_a, name_a) = roles[i]; - for &(role_b, name_b) in &roles[i + 1..] { - if name_a == name_b { - return Err(BsonCeoPostsError::InvalidFieldNames { - detail: format!( - "roles '{role_a}' and '{role_b}' cannot share BSON field '{name_a}'" - ), - }); - } - } - } - - Ok(()) - } -} - -/// Typed errors returned while validating field configuration or decoding raw `ceoPosts` BSON. -/// -/// Structural BSON framing or element errors fail closed and carry a `u64` byte offset; -/// every variant's `Display` output is a single line. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum BsonCeoPostsError { - /// Invalid [`CeoPostsFieldNames`] configuration (empty/blank name or duplicate role mapping). - InvalidFieldNames { detail: String }, - /// Buffer ended before a complete 4-byte length prefix or declared document body. - TruncatedDocument { - offset: u64, - remaining: usize, - declared_len: Option, - }, - /// Declared 4-byte little-endian BSON document length was `< 5` (or did not match a single - /// document slice). - CorruptDocumentLength { offset: u64, declared_len: i32 }, - /// Underlying BSON framing or element bytes were malformed. - CorruptBson { offset: u64, detail: String }, -} - -impl fmt::Display for BsonCeoPostsError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::InvalidFieldNames { detail } => { - write!(f, "invalid ceoPosts field configuration: {detail}") - } - Self::TruncatedDocument { - offset, - remaining, - declared_len, - } => match declared_len { - Some(len) => write!( - f, - "truncated BSON document at byte offset {offset}: declared length {len} exceeds remaining {remaining} bytes" - ), - None => write!( - f, - "truncated BSON document header at byte offset {offset}: only {remaining} bytes remaining" - ), - }, - Self::CorruptDocumentLength { - offset, - declared_len, - } => write!( - f, - "corrupt BSON document length {declared_len} at byte offset {offset}" - ), - Self::CorruptBson { offset, detail } => { - write!(f, "corrupt BSON bytes at byte offset {offset}: {detail}") - } - } - } -} - -impl Error for BsonCeoPostsError {} - -#[inline] -fn map_framing_error(err: BsonEodPriceError) -> BsonCeoPostsError { - match err { - BsonEodPriceError::TruncatedDocument { - offset, - remaining, - declared_len, - } => BsonCeoPostsError::TruncatedDocument { - offset: offset as u64, - remaining, - declared_len, - }, - BsonEodPriceError::CorruptDocumentLength { - offset, - declared_len, - } => BsonCeoPostsError::CorruptDocumentLength { - offset: offset as u64, - declared_len, - }, - BsonEodPriceError::CorruptBson { offset, detail } => BsonCeoPostsError::CorruptBson { - offset: offset as u64, - detail, - }, - other => BsonCeoPostsError::CorruptBson { - offset: 0, - detail: other.to_string(), - }, - } -} - -/// Per-batch decode accounting for `ceoPosts`. -/// -/// Conservation invariant: -/// `docs_in == rows_out + skipped_total()` -/// -/// Emitted-row counters (`edited_zero_or_false`, `nulled_wrong_type_bot`, -/// `nulled_wrong_type_user_id`, `empty_text`) are incremented only for emitted rows and are -/// excluded from [`Self::skipped_total`]. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct BsonCeoPostsDecodeStats { - pub docs_in: usize, - pub rows_out: usize, - pub skipped_missing_key: usize, - pub skipped_wrong_key_type: usize, - pub skipped_empty_key: usize, - pub skipped_missing_spiel_id: usize, - pub skipped_wrong_spiel_id_type: usize, - pub skipped_empty_spiel_id: usize, - pub skipped_missing_timestamp: usize, - pub skipped_wrong_timestamp_type: usize, - pub skipped_invalid_timestamp: usize, - pub skipped_timestamp_out_of_range: usize, - pub skipped_invalid_edited: usize, - pub skipped_wrong_text_type: usize, - pub edited_zero_or_false: usize, - pub nulled_wrong_type_bot: usize, - pub nulled_wrong_type_user_id: usize, - pub empty_text: usize, -} - -impl BsonCeoPostsDecodeStats { - /// Total number of semantically skipped documents across all skip categories. - #[inline] - pub fn skipped_total(&self) -> usize { - self.skipped_missing_key - + self.skipped_wrong_key_type - + self.skipped_empty_key - + self.skipped_missing_spiel_id - + self.skipped_wrong_spiel_id_type - + self.skipped_empty_spiel_id - + self.skipped_missing_timestamp - + self.skipped_wrong_timestamp_type - + self.skipped_invalid_timestamp - + self.skipped_timestamp_out_of_range - + self.skipped_invalid_edited - + self.skipped_wrong_text_type - } - - /// Accumulates counters from another batch into `self`. - #[inline] - pub fn merge(&mut self, other: &Self) { - self.docs_in += other.docs_in; - self.rows_out += other.rows_out; - self.skipped_missing_key += other.skipped_missing_key; - self.skipped_wrong_key_type += other.skipped_wrong_key_type; - self.skipped_empty_key += other.skipped_empty_key; - self.skipped_missing_spiel_id += other.skipped_missing_spiel_id; - self.skipped_wrong_spiel_id_type += other.skipped_wrong_spiel_id_type; - self.skipped_empty_spiel_id += other.skipped_empty_spiel_id; - self.skipped_missing_timestamp += other.skipped_missing_timestamp; - self.skipped_wrong_timestamp_type += other.skipped_wrong_timestamp_type; - self.skipped_invalid_timestamp += other.skipped_invalid_timestamp; - self.skipped_timestamp_out_of_range += other.skipped_timestamp_out_of_range; - self.skipped_invalid_edited += other.skipped_invalid_edited; - self.skipped_wrong_text_type += other.skipped_wrong_text_type; - self.edited_zero_or_false += other.edited_zero_or_false; - self.nulled_wrong_type_bot += other.nulled_wrong_type_bot; - self.nulled_wrong_type_user_id += other.nulled_wrong_type_user_id; - self.empty_text += other.empty_text; - } -} - -impl std::ops::AddAssign for BsonCeoPostsDecodeStats { - #[inline] - fn add_assign(&mut self, rhs: Self) { - self.merge(&rhs); - } -} - -enum KeyState<'a> { - Missing, - WrongType, - Empty, - Valid(&'a str), -} - -enum SpielIdState<'a> { - Missing, - WrongType, - Empty, - Str(&'a str), - Int32(i32), - Int64(i64), -} - -enum TimestampState { - Missing, - WrongType, - Invalid, - OutOfRange, - Valid(i64), -} - -enum EditedState { - Absent, - Null, - ZeroOrFalse, - Valid(i64), - Invalid, -} - -enum TextState<'a> { - MissingOrNull, - WrongType, - Str(&'a str), -} - -enum BotState<'a> { - None, - WrongType, - Str(&'a str), - Int32(i32), - Int64(i64), - Bool(bool), -} - -enum UserIdState<'a> { - None, - WrongType, - Str(&'a str), - Int32(i32), - Int64(i64), -} - -#[inline] -fn scale_numeric_timestamp(raw: i64, unit: CeoPostsTimestampUnit) -> TimestampState { - match unit { - CeoPostsTimestampUnit::Millis => TimestampState::Valid(raw), - CeoPostsTimestampUnit::Seconds => match raw.checked_mul(1_000) { - Some(ms) => TimestampState::Valid(ms), - None => TimestampState::OutOfRange, - }, - } -} - -#[inline] -fn decode_timestamp_val(val: RawBsonRef<'_>, unit: CeoPostsTimestampUnit) -> TimestampState { - match val { - RawBsonRef::DateTime(dt) => TimestampState::Valid(dt.timestamp_millis()), - RawBsonRef::Int32(v) => scale_numeric_timestamp(i64::from(v), unit), - RawBsonRef::Int64(v) => scale_numeric_timestamp(v, unit), - RawBsonRef::Double(v) => { - if !v.is_finite() || v.fract() != 0.0 { - return TimestampState::Invalid; - } - // Exact half-open range of `f64` values representable as `i64` (`[-2^63, 2^63)`). - if !(-9_223_372_036_854_775_808.0..9_223_372_036_854_775_808.0).contains(&v) { - return TimestampState::OutOfRange; - } - scale_numeric_timestamp(v as i64, unit) - } - _ => TimestampState::WrongType, - } -} - -#[inline] -fn decode_edited_val(val: RawBsonRef<'_>, unit: CeoPostsTimestampUnit) -> EditedState { - match val { - RawBsonRef::Null => EditedState::Null, - RawBsonRef::Boolean(false) => EditedState::ZeroOrFalse, - RawBsonRef::Boolean(true) => EditedState::Invalid, - RawBsonRef::DateTime(dt) => { - let ms = dt.timestamp_millis(); - if ms < 0 { - EditedState::Invalid - } else { - // Epoch-zero BSON DateTime is a timestamp, not the numeric `0` sentinel. - EditedState::Valid(ms) - } - } - RawBsonRef::Int32(_) | RawBsonRef::Int64(_) | RawBsonRef::Double(_) => { - match decode_timestamp_val(val, unit) { - TimestampState::Valid(0) => EditedState::ZeroOrFalse, - TimestampState::Valid(ms) if ms > 0 => EditedState::Valid(ms), - TimestampState::Valid(_) - | TimestampState::Invalid - | TimestampState::OutOfRange - | TimestampState::WrongType - | TimestampState::Missing => EditedState::Invalid, - } - } - _ => EditedState::Invalid, - } -} - -#[inline] -fn decode_spiel_id_val(val: RawBsonRef<'_>) -> SpielIdState<'_> { - match val { - RawBsonRef::String(s) => { - if s.trim().is_empty() { - SpielIdState::Empty - } else { - SpielIdState::Str(s) - } - } - RawBsonRef::Int32(v) => SpielIdState::Int32(v), - RawBsonRef::Int64(v) => SpielIdState::Int64(v), - _ => SpielIdState::WrongType, - } -} - -#[inline] -fn decode_bot_val(val: RawBsonRef<'_>) -> BotState<'_> { - match val { - RawBsonRef::Null => BotState::None, - RawBsonRef::String(s) => BotState::Str(s), - RawBsonRef::Int32(v) => BotState::Int32(v), - RawBsonRef::Int64(v) => BotState::Int64(v), - RawBsonRef::Boolean(b) => BotState::Bool(b), - _ => BotState::WrongType, - } -} - -#[inline] -fn decode_user_id_val(val: RawBsonRef<'_>) -> UserIdState<'_> { - match val { - RawBsonRef::Null => UserIdState::None, - RawBsonRef::String(s) => UserIdState::Str(s), - RawBsonRef::Int32(v) => UserIdState::Int32(v), - RawBsonRef::Int64(v) => UserIdState::Int64(v), - _ => UserIdState::WrongType, - } -} - -#[inline] -fn decode_text_val(val: RawBsonRef<'_>) -> TextState<'_> { - match val { - RawBsonRef::Null => TextState::MissingOrNull, - RawBsonRef::String(s) => TextState::Str(s), - _ => TextState::WrongType, - } -} - -/// Maximum recursive nesting depth accepted while validating raw BSON documents and arrays. -const MAX_BSON_VALIDATION_DEPTH: usize = 128; - -#[inline] -fn is_exact_array_index(key: &str, expected: usize) -> bool { - let bytes = key.as_bytes(); - if bytes.is_empty() || (bytes.len() > 1 && bytes[0] == b'0') { - return false; - } - let mut parsed: usize = 0; - for &b in bytes { - if !b.is_ascii_digit() { - return false; - } - let digit = usize::from(b - b'0'); - match parsed.checked_mul(10).and_then(|n| n.checked_add(digit)) { - Some(next) => parsed = next, - None => return false, - } - } - parsed == expected -} - -fn validate_raw_bson_value( - val: RawBsonRef<'_>, - doc_offset: u64, - field_name: &str, - depth: usize, -) -> Result<(), BsonCeoPostsError> { - match val { - RawBsonRef::Document(subdoc) => { - validate_raw_document(subdoc, doc_offset, field_name, depth + 1) - } - RawBsonRef::Array(arr) => { - if depth >= MAX_BSON_VALIDATION_DEPTH { - return Err(BsonCeoPostsError::CorruptBson { - offset: doc_offset, - detail: format!( - "field '{field_name}': nested BSON depth exceeds limit {MAX_BSON_VALIDATION_DEPTH}" - ), - }); - } - for (expected_idx, elem_res) in arr.iter_elements().enumerate() { - let elem = elem_res.map_err(|err| BsonCeoPostsError::CorruptBson { - offset: doc_offset, - detail: format!("field '{field_name}': {err}"), - })?; - let key = elem.key().as_str(); - if !is_exact_array_index(key, expected_idx) { - return Err(BsonCeoPostsError::CorruptBson { - offset: doc_offset, - detail: format!( - "field '{field_name}': invalid BSON array index '{key}' at position {expected_idx}" - ), - }); - } - let item = elem.value().map_err(|err| BsonCeoPostsError::CorruptBson { - offset: doc_offset, - detail: format!("field '{field_name}': {err}"), - })?; - validate_raw_bson_value(item, doc_offset, field_name, depth + 1)?; - } - Ok(()) - } - RawBsonRef::JavaScriptCodeWithScope(code_with_scope) => { - validate_raw_document(code_with_scope.scope, doc_offset, field_name, depth + 1) - } - _ => Ok(()), - } -} - -fn validate_raw_document( - doc: &RawDocument, - doc_offset: u64, - field_name: &str, - depth: usize, -) -> Result<(), BsonCeoPostsError> { - if depth > MAX_BSON_VALIDATION_DEPTH { - return Err(BsonCeoPostsError::CorruptBson { - offset: doc_offset, - detail: format!( - "field '{field_name}': nested BSON depth exceeds limit {MAX_BSON_VALIDATION_DEPTH}" - ), - }); - } - for elem_res in doc.iter_elements() { - let elem = elem_res.map_err(|err| BsonCeoPostsError::CorruptBson { - offset: doc_offset, - detail: format!("field '{field_name}': {err}"), - })?; - let val = elem.value().map_err(|err| BsonCeoPostsError::CorruptBson { - offset: doc_offset, - detail: format!("field '{field_name}': {err}"), - })?; - validate_raw_bson_value(val, doc_offset, field_name, depth)?; - } - Ok(()) -} - -fn decode_ceo_posts_doc_at<'a, F>( - doc: &'a RawDocument, - doc_offset: u64, - fields: &CeoPostsFieldNames<'_>, - unit: CeoPostsTimestampUnit, - mut on_row: F, -) -> Result -where - F: FnMut(CeoPost<&'a str>), -{ - let mut stats = BsonCeoPostsDecodeStats { - docs_in: 1, - ..BsonCeoPostsDecodeStats::default() - }; - - let mut key_state = KeyState::Missing; - let mut spiel_id_state = SpielIdState::Missing; - let mut timestamp_state = TimestampState::Missing; - let mut edited_state = EditedState::Absent; - let mut bot_state = BotState::None; - let mut user_id_state = UserIdState::None; - let mut text_state = TextState::MissingOrNull; - - // Scan and validate every element and nested raw value to completion so structural BSON - // corruption (including invalid UTF-8 in unused fields or malformed nested documents/arrays) - // always fails closed and is never masked by an earlier semantic skip. - for elem_res in doc.iter_elements() { - let elem = elem_res.map_err(|err| BsonCeoPostsError::CorruptBson { - offset: doc_offset, - detail: err.to_string(), - })?; - let name = elem.key().as_str(); - let val = elem.value().map_err(|err| BsonCeoPostsError::CorruptBson { - offset: doc_offset, - detail: format!("field '{name}': {err}"), - })?; - validate_raw_bson_value(val, doc_offset, name, 0)?; - - if name == fields.key { - key_state = match val { - RawBsonRef::String(s) => { - if s.trim().is_empty() { - KeyState::Empty - } else { - KeyState::Valid(s) - } - } - _ => KeyState::WrongType, - }; - } else if name == fields.spiel_id { - spiel_id_state = decode_spiel_id_val(val); - } else if name == fields.timestamp { - timestamp_state = decode_timestamp_val(val, unit); - } else if name == fields.edited { - // Fail closed on repeated `edited` fields so a later value (e.g. Null) can never - // mask an earlier unreadable or later edit timestamp. - edited_state = if matches!(edited_state, EditedState::Absent) { - decode_edited_val(val, unit) - } else { - EditedState::Invalid - }; - } else if name == fields.bot { - bot_state = decode_bot_val(val); - } else if name == fields.user_id { - user_id_state = decode_user_id_val(val); - } else if name == fields.text { - text_state = decode_text_val(val); - } - } - - // Apply deterministic semantic skip priority: key -> spiel_id -> timestamp -> edited -> text. - let key = match key_state { - KeyState::Valid(s) => s, - KeyState::Missing => { - stats.skipped_missing_key += 1; - return Ok(stats); - } - KeyState::WrongType => { - stats.skipped_wrong_key_type += 1; - return Ok(stats); - } - KeyState::Empty => { - stats.skipped_empty_key += 1; - return Ok(stats); - } - }; - - match spiel_id_state { - SpielIdState::Str(_) | SpielIdState::Int32(_) | SpielIdState::Int64(_) => {} - SpielIdState::Missing => { - stats.skipped_missing_spiel_id += 1; - return Ok(stats); - } - SpielIdState::WrongType => { - stats.skipped_wrong_spiel_id_type += 1; - return Ok(stats); - } - SpielIdState::Empty => { - stats.skipped_empty_spiel_id += 1; - return Ok(stats); - } - } - - let timestamp_ms = match timestamp_state { - TimestampState::Valid(ms) => ms, - TimestampState::Missing => { - stats.skipped_missing_timestamp += 1; - return Ok(stats); - } - TimestampState::WrongType => { - stats.skipped_wrong_timestamp_type += 1; - return Ok(stats); - } - TimestampState::Invalid => { - stats.skipped_invalid_timestamp += 1; - return Ok(stats); - } - TimestampState::OutOfRange => { - stats.skipped_timestamp_out_of_range += 1; - return Ok(stats); - } - }; - - let (edited_ms, edited_is_zero_or_false) = match edited_state { - EditedState::Absent | EditedState::Null => (None, false), - EditedState::ZeroOrFalse => (None, true), - EditedState::Valid(ms) => (Some(ms), false), - EditedState::Invalid => { - stats.skipped_invalid_edited += 1; - return Ok(stats); - } - }; - - let (text, text_is_empty) = match text_state { - TextState::Str(s) => (s.to_owned(), false), - TextState::MissingOrNull => (String::new(), true), - TextState::WrongType => { - stats.skipped_wrong_text_type += 1; - return Ok(stats); - } - }; - - // Row passed all skip checks: record emitted-row counters and allocate owned fields. - if edited_is_zero_or_false { - stats.edited_zero_or_false += 1; - } - if text_is_empty { - stats.empty_text += 1; - } - - let spiel_id = match spiel_id_state { - SpielIdState::Str(s) => s.to_owned(), - SpielIdState::Int32(v) => v.to_string(), - SpielIdState::Int64(v) => v.to_string(), - SpielIdState::Missing | SpielIdState::WrongType | SpielIdState::Empty => { - unreachable!("validated above") - } - }; - - let bot = match bot_state { - BotState::None => None, - BotState::Str(s) => Some(s.to_owned()), - BotState::Int32(v) => Some(v.to_string()), - BotState::Int64(v) => Some(v.to_string()), - BotState::Bool(true) => Some("1".to_owned()), - BotState::Bool(false) => Some("0".to_owned()), - BotState::WrongType => { - stats.nulled_wrong_type_bot += 1; - None - } - }; - - let user_id = match user_id_state { - UserIdState::None => None, - UserIdState::Str(s) => Some(s.to_owned()), - UserIdState::Int32(v) => Some(v.to_string()), - UserIdState::Int64(v) => Some(v.to_string()), - UserIdState::WrongType => { - stats.nulled_wrong_type_user_id += 1; - None - } - }; - - stats.rows_out += 1; - on_row(CeoPost { - key, - spiel_id, - timestamp_ms, - edited_ms, - bot, - user_id, - text, - }); - Ok(stats) -} - -/// Decodes a single `&RawDocument` representing a `ceoPosts` MongoDB document in one forward pass -/// without allocating a `bson::Document`. -/// -/// Validates `fields` before inspecting the document. -pub fn decode_ceo_posts_doc<'a, F>( - doc: &'a RawDocument, - fields: &CeoPostsFieldNames<'_>, - unit: CeoPostsTimestampUnit, - on_row: F, -) -> Result -where - F: FnMut(CeoPost<&'a str>), -{ - fields.validate()?; - decode_ceo_posts_doc_at(doc, 0, fields, unit, on_row) -} - -/// Decodes a single length-prefixed raw BSON document byte slice representing a `ceoPosts` -/// document. -/// -/// Validates `fields` before inspecting the bytes. -pub fn decode_ceo_posts_bytes<'a, F>( - bytes: &'a [u8], - fields: &CeoPostsFieldNames<'_>, - unit: CeoPostsTimestampUnit, - on_row: F, -) -> Result -where - F: FnMut(CeoPost<&'a str>), -{ - fields.validate()?; - let doc = parse_single_raw_doc(bytes).map_err(map_framing_error)?; - decode_ceo_posts_doc_at(doc, 0, fields, unit, on_row) -} - -/// Streams a concatenated length-prefixed BSON buffer through [`decode_ceo_posts_doc`], -/// emitting every valid [`CeoPost<&str>`] to `on_row` and failing closed on the first structural -/// BSON framing or element corruption. -/// -/// Validates `fields` once before reading the buffer. If an error occurs after one or more valid -/// documents, `on_row` has already been invoked for those earlier documents. -/// -/// Always maintains `stats.docs_in == stats.rows_out + stats.skipped_total()`. -pub fn decode_ceo_posts_buffer<'a, F>( - buf: &'a [u8], - fields: &CeoPostsFieldNames<'_>, - unit: CeoPostsTimestampUnit, - mut on_row: F, -) -> Result -where - F: FnMut(CeoPost<&'a str>), -{ - fields.validate()?; - let mut total = BsonCeoPostsDecodeStats::default(); - let mut iter = iter_raw_bson_docs(buf); - while let Some(item) = iter.next_with_offset() { - match item { - Ok((offset, doc)) => { - let doc_stats = - decode_ceo_posts_doc_at(doc, offset as u64, fields, unit, &mut on_row)?; - total += doc_stats; - } - Err((_, err)) => return Err(map_framing_error(err)), - } - } - Ok(total) -} - -#[cfg(test)] -#[path = "bson_ceo_posts_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/bson_ceo_posts_tests.rs b/tools/curate-etl/src/bson_ceo_posts_tests.rs deleted file mode 100644 index abd8a6cd..00000000 --- a/tools/curate-etl/src/bson_ceo_posts_tests.rs +++ /dev/null @@ -1,1453 +0,0 @@ -use bson::raw::{cstr, RawArrayBuf, RawBson, RawDocument, RawDocumentBuf}; -use bson::DateTime as BsonDateTime; - -use super::*; -use crate::posts::build_posts; - -fn assert_conservation(stats: &BsonCeoPostsDecodeStats) { - assert_eq!( - stats.docs_in, - stats.rows_out + stats.skipped_total(), - "conservation invariant failed: {stats:?}" - ); -} - -fn make_base_doc(key: &str, spiel_id: &str, ts_secs: i64) -> RawDocumentBuf { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("ceoId"), key); - doc.append(cstr!("spielId"), spiel_id); - doc.append(cstr!("timestamp"), ts_secs); - doc.append(cstr!("spiel"), "hello world"); - doc -} - -#[test] -fn validates_field_names_rejecting_empty_blank_and_duplicates() { - let defaults = CeoPostsFieldNames::default(); - assert_eq!(defaults.key, DEFAULT_KEY_FIELD); - assert_eq!(defaults.spiel_id, DEFAULT_SPIEL_ID_FIELD); - assert_eq!(defaults.timestamp, DEFAULT_TIMESTAMP_FIELD); - assert_eq!(defaults.edited, DEFAULT_EDITED_FIELD); - assert_eq!(defaults.bot, DEFAULT_BOT_FIELD); - assert_eq!(defaults.user_id, DEFAULT_USER_ID_FIELD); - assert_eq!(defaults.text, DEFAULT_TEXT_FIELD); - assert!(defaults.validate().is_ok()); - - let custom = CeoPostsFieldNames { - key: "channel", - spiel_id: "postId", - timestamp: "createdAt", - edited: "updatedAt", - bot: "isBot", - user_id: "authorId", - text: "body", - }; - assert!(custom.validate().is_ok()); - - let bad_configs = [ - CeoPostsFieldNames { - key: "", - ..defaults - }, - CeoPostsFieldNames { - key: " \t ", - ..defaults - }, - CeoPostsFieldNames { - spiel_id: "", - ..defaults - }, - CeoPostsFieldNames { - timestamp: " ", - ..defaults - }, - CeoPostsFieldNames { - edited: "", - ..defaults - }, - CeoPostsFieldNames { - bot: " ", - ..defaults - }, - CeoPostsFieldNames { - user_id: "", - ..defaults - }, - CeoPostsFieldNames { - text: "\t", - ..defaults - }, - // Duplicate role mappings - CeoPostsFieldNames { - key: "dup", - spiel_id: "dup", - ..defaults - }, - CeoPostsFieldNames { - timestamp: "edited", - ..defaults - }, - CeoPostsFieldNames { - bot: "userId", - ..defaults - }, - CeoPostsFieldNames { - text: "ceoId", - ..defaults - }, - ]; - - let empty_doc = RawDocumentBuf::new(); - - for cfg in bad_configs { - let err = cfg.validate().unwrap_err(); - assert!( - matches!(err, BsonCeoPostsError::InvalidFieldNames { .. }), - "expected InvalidFieldNames for {cfg:?}, got {err:?}" - ); - let msg = err.to_string(); - assert!(!msg.contains('\n'), "single-line display expected: {msg}"); - - // All three entry points validate config before touching bytes/docs. - assert!(matches!( - decode_ceo_posts_buffer(&[], &cfg, CeoPostsTimestampUnit::Seconds, |_| {}), - Err(BsonCeoPostsError::InvalidFieldNames { .. }) - )); - assert!(matches!( - decode_ceo_posts_bytes(&[], &cfg, CeoPostsTimestampUnit::Millis, |_| {}), - Err(BsonCeoPostsError::InvalidFieldNames { .. }) - )); - assert!(matches!( - decode_ceo_posts_doc( - empty_doc.as_ref(), - &cfg, - CeoPostsTimestampUnit::Seconds, - |_| {} - ), - Err(BsonCeoPostsError::InvalidFieldNames { .. }) - )); - } -} - -#[test] -fn decodes_timestamp_and_edited_across_types_under_seconds_and_millis() { - let fields = CeoPostsFieldNames::default(); - let ts_sec_i32: i32 = 1_710_460_800; // 2024-03-15T00:00:00Z - let ed_sec_i32: i32 = 1_710_461_400; // +600s - let ts_sec_i64: i64 = 1_710_460_900; - let ed_sec_i64: i64 = 1_710_461_900; - let ts_dt_ms: i64 = 1_710_460_800_123; - let ed_dt_ms: i64 = 1_710_461_400_456; - - // --- Seconds unit --- - let mut sec_buf = Vec::new(); - - // 1. Int32 timestamp + Int32 edited - let mut d1 = RawDocumentBuf::new(); - d1.append(cstr!("ceoId"), " CH-1 "); // verbatim - d1.append(cstr!("spielId"), "s1"); - d1.append(cstr!("timestamp"), ts_sec_i32); - d1.append(cstr!("edited"), ed_sec_i32); - d1.append(cstr!("spiel"), "int32"); - sec_buf.extend_from_slice(d1.as_bytes()); - - // 2. Int64 timestamp + Int64 edited - let mut d2 = RawDocumentBuf::new(); - d2.append(cstr!("ceoId"), "CH-2"); - d2.append(cstr!("spielId"), 200_i32); - d2.append(cstr!("timestamp"), ts_sec_i64); - d2.append(cstr!("edited"), ed_sec_i64); - d2.append(cstr!("spiel"), "int64"); - sec_buf.extend_from_slice(d2.as_bytes()); - - // 3. Integral Double timestamp + integral Double edited - let mut d3 = RawDocumentBuf::new(); - d3.append(cstr!("ceoId"), "CH-3"); - d3.append(cstr!("spielId"), 300_i64); - d3.append(cstr!("timestamp"), ts_sec_i64 as f64); - d3.append(cstr!("edited"), ed_sec_i64 as f64); - d3.append(cstr!("spiel"), "double"); - sec_buf.extend_from_slice(d3.as_bytes()); - - // 4. BSON DateTime (already ms; unit ignored) - let mut d4 = RawDocumentBuf::new(); - d4.append(cstr!("ceoId"), "CH-4"); - d4.append(cstr!("spielId"), "s4"); - d4.append(cstr!("timestamp"), BsonDateTime::from_millis(ts_dt_ms)); - d4.append(cstr!("edited"), BsonDateTime::from_millis(ed_dt_ms)); - d4.append(cstr!("spiel"), "datetime"); - sec_buf.extend_from_slice(d4.as_bytes()); - - // 5. Non-positive creation times (<= 0) passed through verbatim (build_posts rejects them) - let mut d5 = RawDocumentBuf::new(); - d5.append(cstr!("ceoId"), "CH-5"); - d5.append(cstr!("spielId"), "s5"); - d5.append(cstr!("timestamp"), 0_i32); - d5.append(cstr!("spiel"), "zero"); - sec_buf.extend_from_slice(d5.as_bytes()); - - let mut d6 = RawDocumentBuf::new(); - d6.append(cstr!("ceoId"), "CH-6"); - d6.append(cstr!("spielId"), "s6"); - d6.append(cstr!("timestamp"), -10_i64); - d6.append(cstr!("spiel"), "neg"); - sec_buf.extend_from_slice(d6.as_bytes()); - - let mut d7 = RawDocumentBuf::new(); - d7.append(cstr!("ceoId"), "CH-7"); - d7.append(cstr!("spielId"), "s7"); - d7.append(cstr!("timestamp"), -0.0_f64); - d7.append(cstr!("spiel"), "negzero"); - sec_buf.extend_from_slice(d7.as_bytes()); - - let buf_start = sec_buf.as_ptr() as usize; - let buf_end = buf_start + sec_buf.len(); - - let mut sec_rows = Vec::new(); - let stats = decode_ceo_posts_buffer(&sec_buf, &fields, CeoPostsTimestampUnit::Seconds, |r| { - // Verify zero-copy borrow: `key` points directly into `sec_buf`. - let key_ptr = r.key.as_ptr() as usize; - assert!( - key_ptr >= buf_start && key_ptr + r.key.len() <= buf_end, - "decoded key must borrow directly from input buffer" - ); - sec_rows.push(( - r.key.to_owned(), - r.spiel_id, - r.timestamp_ms, - r.edited_ms, - r.text, - )); - }) - .expect("decode seconds buffer"); - - assert_conservation(&stats); - assert_eq!(stats.docs_in, 7); - assert_eq!(stats.rows_out, 7); - assert_eq!( - sec_rows, - vec![ - ( - " CH-1 ".to_string(), - "s1".to_string(), - i64::from(ts_sec_i32) * 1_000, - Some(i64::from(ed_sec_i32) * 1_000), - "int32".to_string() - ), - ( - "CH-2".to_string(), - "200".to_string(), - ts_sec_i64 * 1_000, - Some(ed_sec_i64 * 1_000), - "int64".to_string() - ), - ( - "CH-3".to_string(), - "300".to_string(), - ts_sec_i64 * 1_000, - Some(ed_sec_i64 * 1_000), - "double".to_string() - ), - ( - "CH-4".to_string(), - "s4".to_string(), - ts_dt_ms, - Some(ed_dt_ms), - "datetime".to_string() - ), - ( - "CH-5".to_string(), - "s5".to_string(), - 0, - None, - "zero".to_string() - ), - ( - "CH-6".to_string(), - "s6".to_string(), - -10_000, - None, - "neg".to_string() - ), - ( - "CH-7".to_string(), - "s7".to_string(), - 0, - None, - "negzero".to_string() - ), - ] - ); - - // --- Millis unit --- - let mut ms_buf = Vec::new(); - - // Int32 millis - let mut m1 = RawDocumentBuf::new(); - m1.append(cstr!("ceoId"), "M1"); - m1.append(cstr!("spielId"), "m1"); - m1.append(cstr!("timestamp"), 1_000_000_i32); - m1.append(cstr!("edited"), 1_000_500_i32); - m1.append(cstr!("spiel"), "m1"); - ms_buf.extend_from_slice(m1.as_bytes()); - - // Int64 millis - let mut m2 = RawDocumentBuf::new(); - m2.append(cstr!("ceoId"), "M2"); - m2.append(cstr!("spielId"), "m2"); - m2.append(cstr!("timestamp"), ts_dt_ms); - m2.append(cstr!("edited"), ed_dt_ms); - m2.append(cstr!("spiel"), "m2"); - ms_buf.extend_from_slice(m2.as_bytes()); - - // Integral Double millis (including exact -2^63 and 2^63 - 1024 boundaries) - let mut m3 = RawDocumentBuf::new(); - m3.append(cstr!("ceoId"), "M3"); - m3.append(cstr!("spielId"), "m3"); - m3.append(cstr!("timestamp"), -9_223_372_036_854_775_808.0_f64); - m3.append(cstr!("edited"), 9_223_372_036_854_774_784.0_f64); - m3.append(cstr!("spiel"), "m3"); - ms_buf.extend_from_slice(m3.as_bytes()); - - // BSON DateTime under Millis (unchanged) - let mut m4 = RawDocumentBuf::new(); - m4.append(cstr!("ceoId"), "M4"); - m4.append(cstr!("spielId"), "m4"); - m4.append(cstr!("timestamp"), BsonDateTime::from_millis(ts_dt_ms)); - m4.append(cstr!("edited"), BsonDateTime::from_millis(ed_dt_ms)); - m4.append(cstr!("spiel"), "m4"); - ms_buf.extend_from_slice(m4.as_bytes()); - - let mut ms_rows = Vec::new(); - let ms_stats = decode_ceo_posts_buffer(&ms_buf, &fields, CeoPostsTimestampUnit::Millis, |r| { - ms_rows.push((r.spiel_id, r.timestamp_ms, r.edited_ms)); - }) - .expect("decode millis buffer"); - - assert_conservation(&ms_stats); - assert_eq!(ms_stats.docs_in, 4); - assert_eq!(ms_stats.rows_out, 4); - assert_eq!( - ms_rows, - vec![ - ("m1".to_string(), 1_000_000, Some(1_000_500)), - ("m2".to_string(), ts_dt_ms, Some(ed_dt_ms)), - ( - "m3".to_string(), - i64::MIN, - Some(9_223_372_036_854_774_784_i64) - ), - ("m4".to_string(), ts_dt_ms, Some(ed_dt_ms)), - ] - ); -} - -#[test] -fn skips_timestamp_seconds_overflow_and_double_range_boundaries() { - let fields = CeoPostsFieldNames::default(); - let mut buf = Vec::new(); - - // 1. Positive Int64 seconds overflow (i64::MAX / 1_000 + 1) - let mut d1 = RawDocumentBuf::new(); - d1.append(cstr!("ceoId"), "CH"); - d1.append(cstr!("spielId"), "ovf_pos"); - d1.append(cstr!("timestamp"), (i64::MAX / 1_000) + 1); - buf.extend_from_slice(d1.as_bytes()); - - // 2. Negative Int64 seconds overflow (i64::MIN / 1_000 - 1) - let mut d2 = RawDocumentBuf::new(); - d2.append(cstr!("ceoId"), "CH"); - d2.append(cstr!("spielId"), "ovf_neg"); - d2.append(cstr!("timestamp"), (i64::MIN / 1_000) - 1); - buf.extend_from_slice(d2.as_bytes()); - - // 3. Double exactly at 2^63 (outside half-open [-2^63, 2^63)) - let mut d3 = RawDocumentBuf::new(); - d3.append(cstr!("ceoId"), "CH"); - d3.append(cstr!("spielId"), "dbl_2p63"); - d3.append(cstr!("timestamp"), 9_223_372_036_854_775_808.0_f64); - buf.extend_from_slice(d3.as_bytes()); - - // 4. Double below -2^63 - let mut d4 = RawDocumentBuf::new(); - d4.append(cstr!("ceoId"), "CH"); - d4.append(cstr!("spielId"), "dbl_neg_oob"); - d4.append(cstr!("timestamp"), -1e20_f64); - buf.extend_from_slice(d4.as_bytes()); - - // 5. Double in i64 range but overflows when multiplied by 1_000 - let mut d5 = RawDocumentBuf::new(); - d5.append(cstr!("ceoId"), "CH"); - d5.append(cstr!("spielId"), "dbl_sec_ovf"); - d5.append(cstr!("timestamp"), 9_223_372_036_854_774_784.0_f64); - buf.extend_from_slice(d5.as_bytes()); - - let mut emitted = 0usize; - let stats = decode_ceo_posts_buffer(&buf, &fields, CeoPostsTimestampUnit::Seconds, |_| { - emitted += 1; - }) - .expect("decode overflow buffer"); - - assert_conservation(&stats); - assert_eq!(emitted, 0); - assert_eq!(stats.docs_in, 5); - assert_eq!(stats.skipped_timestamp_out_of_range, 5); - - // Under Millis, 2^63 is still out of range. - let stats_2p63 = decode_ceo_posts_bytes( - d3.as_bytes(), - &fields, - CeoPostsTimestampUnit::Millis, - |_| panic!("2^63 double must not emit"), - ) - .expect("decode 2^63 under millis"); - assert_eq!(stats_2p63.skipped_timestamp_out_of_range, 1); -} - -#[test] -fn edited_fail_closed_rule_and_sentinel_accounting() { - let fields = CeoPostsFieldNames::default(); - let ts_sec: i64 = 1_710_460_800; - - // --- Unedited & valid cases --- - let mut valid_buf = Vec::new(); - - // 1. Absent edited -> None (not counted in edited_zero_or_false) - valid_buf.extend_from_slice(make_base_doc("CH", "e_absent", ts_sec).as_bytes()); - - // 2. Null edited -> None (not counted in edited_zero_or_false) - let mut d = make_base_doc("CH", "e_null", ts_sec); - d.append(cstr!("edited"), RawBson::Null); - valid_buf.extend_from_slice(d.as_bytes()); - - // 3. Int32(0) -> None + edited_zero_or_false - let mut d = make_base_doc("CH", "e_i32_zero", ts_sec); - d.append(cstr!("edited"), 0_i32); - valid_buf.extend_from_slice(d.as_bytes()); - - // 4. Int64(0) -> None + edited_zero_or_false - let mut d = make_base_doc("CH", "e_i64_zero", ts_sec); - d.append(cstr!("edited"), 0_i64); - valid_buf.extend_from_slice(d.as_bytes()); - - // 5. Double(0.0) -> None + edited_zero_or_false - let mut d = make_base_doc("CH", "e_f64_zero", ts_sec); - d.append(cstr!("edited"), 0.0_f64); - valid_buf.extend_from_slice(d.as_bytes()); - - // 6. Double(-0.0) -> None + edited_zero_or_false - let mut d = make_base_doc("CH", "e_f64_neg_zero", ts_sec); - d.append(cstr!("edited"), -0.0_f64); - valid_buf.extend_from_slice(d.as_bytes()); - - // 7. Boolean(false) -> None + edited_zero_or_false - let mut d = make_base_doc("CH", "e_bool_false", ts_sec); - d.append(cstr!("edited"), false); - valid_buf.extend_from_slice(d.as_bytes()); - - // 8. Epoch-zero BSON DateTime -> Some(0) (not numeric zero sentinel) - let mut d = make_base_doc("CH", "e_dt_zero", ts_sec); - d.append(cstr!("edited"), BsonDateTime::from_millis(0)); - valid_buf.extend_from_slice(d.as_bytes()); - - let mut valid_out = Vec::new(); - let valid_stats = - decode_ceo_posts_buffer(&valid_buf, &fields, CeoPostsTimestampUnit::Seconds, |r| { - valid_out.push((r.spiel_id, r.edited_ms)); - }) - .expect("decode valid edited buffer"); - - assert_conservation(&valid_stats); - assert_eq!(valid_stats.docs_in, 8); - assert_eq!(valid_stats.rows_out, 8); - assert_eq!(valid_stats.skipped_invalid_edited, 0); - assert_eq!(valid_stats.edited_zero_or_false, 5); - assert_eq!( - valid_out, - vec![ - ("e_absent".to_string(), None), - ("e_null".to_string(), None), - ("e_i32_zero".to_string(), None), - ("e_i64_zero".to_string(), None), - ("e_f64_zero".to_string(), None), - ("e_f64_neg_zero".to_string(), None), - ("e_bool_false".to_string(), None), - ("e_dt_zero".to_string(), Some(0)), - ] - ); - - // --- Fail-closed rejected cases (must NEVER invoke on_row) --- - let mut bad_buf = Vec::new(); - - // 1. Negative Int32 - let mut d = make_base_doc("CH", "bad_neg_i32", ts_sec); - d.append(cstr!("edited"), -1_i32); - bad_buf.extend_from_slice(d.as_bytes()); - - // 2. Negative Int64 - let mut d = make_base_doc("CH", "bad_neg_i64", ts_sec); - d.append(cstr!("edited"), -5_000_i64); - bad_buf.extend_from_slice(d.as_bytes()); - - // 3. Negative Double - let mut d = make_base_doc("CH", "bad_neg_f64", ts_sec); - d.append(cstr!("edited"), -1.0_f64); - bad_buf.extend_from_slice(d.as_bytes()); - - // 4. Negative DateTime - let mut d = make_base_doc("CH", "bad_neg_dt", ts_sec); - d.append(cstr!("edited"), BsonDateTime::from_millis(-1)); - bad_buf.extend_from_slice(d.as_bytes()); - - // 5. Fractional Double - let mut d = make_base_doc("CH", "bad_frac", ts_sec); - d.append(cstr!("edited"), 1_710_461_400.5_f64); - bad_buf.extend_from_slice(d.as_bytes()); - - // 6. NaN Double - let mut d = make_base_doc("CH", "bad_nan", ts_sec); - d.append(cstr!("edited"), f64::NAN); - bad_buf.extend_from_slice(d.as_bytes()); - - // 7. +Inf Double - let mut d = make_base_doc("CH", "bad_inf", ts_sec); - d.append(cstr!("edited"), f64::INFINITY); - bad_buf.extend_from_slice(d.as_bytes()); - - // 8. Boolean(true) - let mut d = make_base_doc("CH", "bad_true", ts_sec); - d.append(cstr!("edited"), true); - bad_buf.extend_from_slice(d.as_bytes()); - - // 9. String - let mut d = make_base_doc("CH", "bad_str", ts_sec); - d.append(cstr!("edited"), "1710461400"); - bad_buf.extend_from_slice(d.as_bytes()); - - // 10. Unsupported type (embedded document) - let mut d = make_base_doc("CH", "bad_doc", ts_sec); - d.append(cstr!("edited"), RawDocumentBuf::new()); - bad_buf.extend_from_slice(d.as_bytes()); - - // 11. Seconds overflow - let mut d = make_base_doc("CH", "bad_ovf", ts_sec); - d.append(cstr!("edited"), (i64::MAX / 1_000) + 1); - bad_buf.extend_from_slice(d.as_bytes()); - - // 12. Repeated `edited` with unreadable value followed by Null (must fail closed!) - let mut d = make_base_doc("CH", "bad_dup_unreadable_then_null", ts_sec); - d.append(cstr!("edited"), "unreadable"); - d.append(cstr!("edited"), RawBson::Null); - bad_buf.extend_from_slice(d.as_bytes()); - - // 13. Repeated `edited` with valid timestamp followed by Null - let mut d = make_base_doc("CH", "bad_dup_valid_then_null", ts_sec); - d.append(cstr!("edited"), ts_sec + 60); - d.append(cstr!("edited"), RawBson::Null); - bad_buf.extend_from_slice(d.as_bytes()); - - // 14. Repeated `edited` with Null followed by valid timestamp - let mut d = make_base_doc("CH", "bad_dup_null_then_valid", ts_sec); - d.append(cstr!("edited"), RawBson::Null); - d.append(cstr!("edited"), ts_sec + 60); - bad_buf.extend_from_slice(d.as_bytes()); - - let mut bad_emitted = 0usize; - let bad_stats = - decode_ceo_posts_buffer(&bad_buf, &fields, CeoPostsTimestampUnit::Seconds, |_| { - bad_emitted += 1; - }) - .expect("decode bad edited buffer"); - - assert_conservation(&bad_stats); - assert_eq!(bad_emitted, 0); - assert_eq!(bad_stats.docs_in, 14); - assert_eq!(bad_stats.rows_out, 0); - assert_eq!(bad_stats.skipped_invalid_edited, 14); - assert_eq!(bad_stats.edited_zero_or_false, 0); -} - -#[test] -fn skips_every_counter_respects_priority_and_matches_single_doc_sum() { - let fields = CeoPostsFieldNames::default(); - let ts_sec: i64 = 1_710_460_800; - - let mut docs: Vec = Vec::new(); - - // 1. skipped_missing_key (also missing spiel_id, timestamp, bad edited, bad text -> key wins) - let mut d = RawDocumentBuf::new(); - d.append(cstr!("spiel"), 123_i32); - d.append(cstr!("edited"), true); - docs.push(d); - - // 2. skipped_wrong_key_type (fields in reverse priority order -> key still wins) - let mut d = RawDocumentBuf::new(); - d.append(cstr!("spiel"), 123_i32); - d.append(cstr!("edited"), "bad"); - d.append(cstr!("timestamp"), "bad"); - d.append(cstr!("spielId"), true); - d.append(cstr!("ceoId"), 42_i32); - docs.push(d); - - // 3. skipped_empty_key (with wrong-type optionals & zero edited -> emitted-row counters stay 0) - let mut d = RawDocumentBuf::new(); - d.append(cstr!("ceoId"), " "); - d.append(cstr!("spielId"), "s3"); - d.append(cstr!("timestamp"), ts_sec); - d.append(cstr!("edited"), 0_i32); - d.append(cstr!("bot"), 1.5_f64); - d.append(cstr!("userId"), true); - docs.push(d); - - // 4. skipped_missing_spiel_id (also bad timestamp, edited, text -> spiel_id wins) - let mut d = RawDocumentBuf::new(); - d.append(cstr!("spiel"), false); - d.append(cstr!("edited"), true); - d.append(cstr!("timestamp"), f64::NAN); - d.append(cstr!("ceoId"), "CH"); - docs.push(d); - - // 5. skipped_wrong_spiel_id_type - let mut d = RawDocumentBuf::new(); - d.append(cstr!("ceoId"), "CH"); - d.append(cstr!("spielId"), true); - d.append(cstr!("timestamp"), ts_sec); - docs.push(d); - - // 6. skipped_empty_spiel_id - let mut d = RawDocumentBuf::new(); - d.append(cstr!("ceoId"), "CH"); - d.append(cstr!("spielId"), " "); - d.append(cstr!("timestamp"), ts_sec); - docs.push(d); - - // 7. skipped_missing_timestamp (also bad edited & bad text -> timestamp wins) - let mut d = RawDocumentBuf::new(); - d.append(cstr!("spiel"), 99_i32); - d.append(cstr!("edited"), "bad"); - d.append(cstr!("spielId"), "s7"); - d.append(cstr!("ceoId"), "CH"); - docs.push(d); - - // 8. skipped_wrong_timestamp_type - let mut d = RawDocumentBuf::new(); - d.append(cstr!("ceoId"), "CH"); - d.append(cstr!("spielId"), "s8"); - d.append(cstr!("timestamp"), "2024-03-15"); - docs.push(d); - - // 9. skipped_invalid_timestamp (fractional Double) - let mut d = RawDocumentBuf::new(); - d.append(cstr!("ceoId"), "CH"); - d.append(cstr!("spielId"), "s9"); - d.append(cstr!("timestamp"), 1_710_460_800.25_f64); - docs.push(d); - - // 10. skipped_timestamp_out_of_range (Seconds overflow) - let mut d = RawDocumentBuf::new(); - d.append(cstr!("ceoId"), "CH"); - d.append(cstr!("spielId"), "s10"); - d.append(cstr!("timestamp"), i64::MAX); - docs.push(d); - - // 11. skipped_invalid_edited (also bad text -> edited wins over text) - let mut d = RawDocumentBuf::new(); - d.append(cstr!("spiel"), 99_i32); - d.append(cstr!("edited"), true); - d.append(cstr!("timestamp"), ts_sec); - d.append(cstr!("spielId"), "s11"); - d.append(cstr!("ceoId"), "CH"); - docs.push(d); - - // 12. skipped_wrong_text_type (with valid edited=0 and wrong-type bot/userId -> emitted counters stay 0) - let mut d = RawDocumentBuf::new(); - d.append(cstr!("ceoId"), "CH"); - d.append(cstr!("spielId"), "s12"); - d.append(cstr!("timestamp"), ts_sec); - d.append(cstr!("edited"), false); - d.append(cstr!("bot"), 2.5_f64); - d.append(cstr!("userId"), true); - d.append(cstr!("spiel"), 123_i32); - docs.push(d); - - // 13. Valid emitted row with missing text, wrong-type bot & userId, edited=false - let mut d = RawDocumentBuf::new(); - d.append(cstr!("ceoId"), "CH"); - d.append(cstr!("spielId"), "ok1"); - d.append(cstr!("timestamp"), ts_sec); - d.append(cstr!("edited"), false); - d.append(cstr!("bot"), 2.5_f64); - d.append(cstr!("userId"), false); - docs.push(d); - - // 14. Valid emitted row with Null text, Int32 userId, String bot - let mut d = RawDocumentBuf::new(); - d.append(cstr!("ceoId"), "CH"); - d.append(cstr!("spielId"), "ok2"); - d.append(cstr!("timestamp"), ts_sec); - d.append(cstr!("bot"), "1"); - d.append(cstr!("userId"), 777_i32); - d.append(cstr!("spiel"), RawBson::Null); - docs.push(d); - - // 15. Valid emitted row with explicit empty string text (not counted in empty_text) and Int64 userId - let mut d = RawDocumentBuf::new(); - d.append(cstr!("ceoId"), "CH"); - d.append(cstr!("spielId"), "ok3"); - d.append(cstr!("timestamp"), ts_sec); - d.append(cstr!("bot"), 0_i64); - d.append(cstr!("userId"), 9_000_000_000_i64); - d.append(cstr!("spiel"), ""); - docs.push(d); - - let mut combined = Vec::new(); - let mut summed = BsonCeoPostsDecodeStats::default(); - for doc in &docs { - combined.extend_from_slice(doc.as_bytes()); - let single = decode_ceo_posts_doc( - doc.as_ref(), - &fields, - CeoPostsTimestampUnit::Seconds, - |_| {}, - ) - .expect("decode single doc"); - assert_conservation(&single); - summed += single; - } - - let mut emitted = Vec::new(); - let buf_stats = - decode_ceo_posts_buffer(&combined, &fields, CeoPostsTimestampUnit::Seconds, |r| { - emitted.push((r.spiel_id, r.bot, r.user_id, r.text)) - }) - .expect("decode combined buffer"); - - assert_conservation(&buf_stats); - assert_eq!(buf_stats, summed); - assert_eq!(buf_stats.docs_in, 15); - assert_eq!(buf_stats.rows_out, 3); - assert_eq!(buf_stats.skipped_total(), 12); - assert_eq!(buf_stats.skipped_missing_key, 1); - assert_eq!(buf_stats.skipped_wrong_key_type, 1); - assert_eq!(buf_stats.skipped_empty_key, 1); - assert_eq!(buf_stats.skipped_missing_spiel_id, 1); - assert_eq!(buf_stats.skipped_wrong_spiel_id_type, 1); - assert_eq!(buf_stats.skipped_empty_spiel_id, 1); - assert_eq!(buf_stats.skipped_missing_timestamp, 1); - assert_eq!(buf_stats.skipped_wrong_timestamp_type, 1); - assert_eq!(buf_stats.skipped_invalid_timestamp, 1); - assert_eq!(buf_stats.skipped_timestamp_out_of_range, 1); - assert_eq!(buf_stats.skipped_invalid_edited, 1); - assert_eq!(buf_stats.skipped_wrong_text_type, 1); - assert_eq!(buf_stats.edited_zero_or_false, 1); - assert_eq!(buf_stats.nulled_wrong_type_bot, 1); - assert_eq!(buf_stats.nulled_wrong_type_user_id, 1); - assert_eq!(buf_stats.empty_text, 2); - - assert_eq!( - emitted, - vec![ - ("ok1".to_string(), None, None, String::new()), - ( - "ok2".to_string(), - Some("1".to_string()), - Some("777".to_string()), - String::new() - ), - ( - "ok3".to_string(), - Some("0".to_string()), - Some("9000000000".to_string()), - String::new() - ), - ] - ); -} - -#[test] -fn decodes_custom_field_names_and_feeds_build_posts_deterministically() { - let fields = CeoPostsFieldNames { - key: "channelId", - spiel_id: "postId", - timestamp: "postedSec", - edited: "editedSec", - bot: "botFlag", - user_id: "author", - text: "body", - }; - - let t0_sec: i64 = 1_710_460_800; // 2024-03-15T00:00:00Z - let t_edit_sec: i64 = t0_sec + 900; // +15m - - let mut raw_docs: Vec = Vec::new(); - - // 1. bot = "1" (newswire, unedited baseline) - let mut d = RawDocumentBuf::new(); - d.append(cstr!("channelId"), "CH-A"); - d.append(cstr!("postId"), "nw_str_1"); - d.append(cstr!("postedSec"), t0_sec); - d.append(cstr!("botFlag"), "1"); - d.append(cstr!("author"), "wire"); - d.append(cstr!("body"), "Press release"); - raw_docs.push(d); - - // 2. bot = Int32(1) (newswire, edited later -> known_at == edited_ms * 1_000) - let mut d = RawDocumentBuf::new(); - d.append(cstr!("channelId"), "CH-A"); - d.append(cstr!("postId"), "nw_i32_1"); - d.append(cstr!("postedSec"), t0_sec + 10); - d.append(cstr!("editedSec"), t_edit_sec); - d.append(cstr!("botFlag"), 1_i32); - d.append(cstr!("author"), 42_i32); - d.append(cstr!("body"), "Corrected release"); - raw_docs.push(d); - - // 3. bot = Boolean(true) (newswire) - let mut d = RawDocumentBuf::new(); - d.append(cstr!("channelId"), "CH-A"); - d.append(cstr!("postId"), "nw_bool_true"); - d.append(cstr!("postedSec"), t0_sec + 20); - d.append(cstr!("botFlag"), true); - d.append(cstr!("body"), "Auto alert"); - raw_docs.push(d); - - // 4. bot = "0" (retail) - let mut d = RawDocumentBuf::new(); - d.append(cstr!("channelId"), "CH-A"); - d.append(cstr!("postId"), "ret_str_0"); - d.append(cstr!("postedSec"), t0_sec + 30); - d.append(cstr!("botFlag"), "0"); - d.append(cstr!("body"), "Retail chatter"); - raw_docs.push(d); - - // 5. bot absent (retail) - let mut d = RawDocumentBuf::new(); - d.append(cstr!("channelId"), "CH-A"); - d.append(cstr!("postId"), "ret_absent"); - d.append(cstr!("postedSec"), t0_sec + 40); - d.append(cstr!("body"), "No bot field"); - raw_docs.push(d); - - // 6. bot wrong type (Double -> nulled -> retail) - let mut d = RawDocumentBuf::new(); - d.append(cstr!("channelId"), "CH-A"); - d.append(cstr!("postId"), "ret_wrong_type"); - d.append(cstr!("postedSec"), t0_sec + 50); - d.append(cstr!("botFlag"), 1.0_f64); - d.append(cstr!("body"), "Wrong type bot"); - raw_docs.push(d); - - // 7. Non-positive creation time passed through by decoder, rejected by build_posts - let mut d = RawDocumentBuf::new(); - d.append(cstr!("channelId"), "CH-A"); - d.append(cstr!("postId"), "zero_ts"); - d.append(cstr!("postedSec"), 0_i64); - d.append(cstr!("body"), "Zero ts"); - raw_docs.push(d); - - let mut buf = Vec::new(); - for d in &raw_docs { - buf.extend_from_slice(d.as_bytes()); - } - - // Run through all three entry points and confirm identical decoded rows. - let mut rows_from_buffer = Vec::new(); - let stats_buf = decode_ceo_posts_buffer(&buf, &fields, CeoPostsTimestampUnit::Seconds, |r| { - rows_from_buffer.push(r); - }) - .expect("decode buffer"); - - let mut rows_from_bytes = Vec::new(); - let mut stats_bytes = BsonCeoPostsDecodeStats::default(); - for d in &raw_docs { - stats_bytes += - decode_ceo_posts_bytes(d.as_bytes(), &fields, CeoPostsTimestampUnit::Seconds, |r| { - rows_from_bytes.push(r) - }) - .expect("decode bytes"); - } - - let mut rows_from_doc = Vec::new(); - let mut stats_doc = BsonCeoPostsDecodeStats::default(); - for d in &raw_docs { - let raw_doc = RawDocument::from_bytes(d.as_bytes()).expect("valid raw doc"); - stats_doc += decode_ceo_posts_doc(raw_doc, &fields, CeoPostsTimestampUnit::Seconds, |r| { - rows_from_doc.push(r) - }) - .expect("decode doc"); - } - - assert_eq!(stats_buf, stats_bytes); - assert_eq!(stats_buf, stats_doc); - assert_eq!(stats_buf.nulled_wrong_type_bot, 1); - assert_eq!(rows_from_buffer, rows_from_bytes); - assert_eq!(rows_from_buffer, rows_from_doc); - - // Feed into `build_posts` twice and verify exact classification, known_at, and determinism. - let build1 = build_posts(rows_from_buffer.clone()).expect("build_posts run 1"); - let build2 = build_posts(rows_from_buffer).expect("build_posts run 2"); - assert_eq!(build1, build2); - - let newswire_ids: Vec<&str> = build1 - .newswire - .iter() - .map(|r| r.spiel_id.as_str()) - .collect(); - let retail_ids: Vec<&str> = build1.retail.iter().map(|r| r.spiel_id.as_str()).collect(); - assert_eq!(newswire_ids, vec!["nw_str_1", "nw_bool_true", "nw_i32_1"]); - assert_eq!( - retail_ids, - vec!["ret_str_0", "ret_absent", "ret_wrong_type"] - ); - assert_eq!(build1.stats.rejected_invalid, 1); - - // Baseline unedited post: known_at == posted_at. - let baseline = build1 - .newswire - .iter() - .find(|r| r.spiel_id == "nw_str_1") - .expect("baseline row"); - assert_eq!(baseline.posted_at, t0_sec * 1_000_000); - assert_eq!(baseline.known_at, baseline.posted_at); - assert!(!baseline.is_edited); - - // Edited post: known_at == edited_ms * 1_000 (UTC microseconds). - let edited = build1 - .newswire - .iter() - .find(|r| r.spiel_id == "nw_i32_1") - .expect("edited row"); - assert_eq!(edited.posted_at, (t0_sec + 10) * 1_000_000); - assert_eq!(edited.known_at, (t_edit_sec * 1_000) * 1_000); - assert!(edited.is_edited); - assert_eq!(edited.user_id.as_deref(), Some("42")); -} - -#[test] -fn framing_and_structural_corruption_fail_closed_with_exact_offsets() { - let fields = CeoPostsFieldNames::default(); - let ts_sec: i64 = 1_710_460_800; - - let good = make_base_doc("CH-OK", "ok_first", ts_sec); - let good_len = good.as_bytes().len() as u64; - - // 1. Truncated header (< 4 bytes) after one valid doc - let mut combined = good.as_bytes().to_vec(); - combined.extend_from_slice(&[0x10, 0x00]); - let mut emitted = Vec::new(); - let err = decode_ceo_posts_buffer(&combined, &fields, CeoPostsTimestampUnit::Seconds, |r| { - emitted.push(r.spiel_id); - }) - .unwrap_err(); - assert_eq!(emitted, vec!["ok_first".to_string()]); - assert_eq!( - err, - BsonCeoPostsError::TruncatedDocument { - offset: good_len, - remaining: 2, - declared_len: None, - } - ); - assert!(!err.to_string().contains('\n')); - - // 2. Truncated body after one valid doc - let mut combined = good.as_bytes().to_vec(); - combined.extend_from_slice(&[20, 0, 0, 0, 0, 0]); - let mut emitted = Vec::new(); - let err = decode_ceo_posts_buffer(&combined, &fields, CeoPostsTimestampUnit::Seconds, |r| { - emitted.push(r.spiel_id); - }) - .unwrap_err(); - assert_eq!(emitted, vec!["ok_first".to_string()]); - assert_eq!( - err, - BsonCeoPostsError::TruncatedDocument { - offset: good_len, - remaining: 6, - declared_len: Some(20), - } - ); - assert!(!err.to_string().contains('\n')); - - // 3. Declared length < 5 after one valid doc - let mut combined = good.as_bytes().to_vec(); - combined.extend_from_slice(&[3, 0, 0, 0, 0]); - let mut emitted = Vec::new(); - let err = decode_ceo_posts_buffer(&combined, &fields, CeoPostsTimestampUnit::Seconds, |r| { - emitted.push(r.spiel_id); - }) - .unwrap_err(); - assert_eq!(emitted, vec!["ok_first".to_string()]); - assert_eq!( - err, - BsonCeoPostsError::CorruptDocumentLength { - offset: good_len, - declared_len: 3, - } - ); - assert!(!err.to_string().contains('\n')); - - // 4. Malformed element AFTER a semantically invalid field (must not be masked by skip) - let mut bad_after_skip = RawDocumentBuf::new(); - bad_after_skip.append(cstr!("ceoId"), ""); // would be skipped_empty_key - bad_after_skip.append(cstr!("z"), 1_i32); - let mut bad_bytes = bad_after_skip.into_bytes(); - let z_pos = bad_bytes - .windows(3) - .position(|w| w == [0x10, b'z', 0x00]) - .expect("locate z element"); - bad_bytes[z_pos] = 0x7e; - - let mut combined = good.as_bytes().to_vec(); - combined.extend_from_slice(&bad_bytes); - let mut emitted = Vec::new(); - let err = decode_ceo_posts_buffer(&combined, &fields, CeoPostsTimestampUnit::Seconds, |r| { - emitted.push(r.spiel_id); - }) - .unwrap_err(); - assert_eq!(emitted, vec!["ok_first".to_string()]); - assert!( - matches!(err, BsonCeoPostsError::CorruptBson { offset, .. } if offset == good_len), - "expected CorruptBson at offset {good_len}, got {err:?}" - ); - assert!(!err.to_string().contains('\n')); - - // 5. Corruption inside an unused nested embedded document after one valid doc - let mut inner = RawDocumentBuf::new(); - inner.append(cstr!("nestedText"), "INNER!"); - let mut nested_bad = make_base_doc("CH-2", "nested_bad", ts_sec); - nested_bad.append(cstr!("poll"), inner); - let mut nested_bytes = nested_bad.into_bytes(); - let pos = nested_bytes - .windows(6) - .position(|w| w == b"INNER!") - .expect("locate INNER!"); - nested_bytes[pos] = 0xff; - - let mut combined = good.as_bytes().to_vec(); - combined.extend_from_slice(&nested_bytes); - let mut emitted = Vec::new(); - let err = decode_ceo_posts_buffer(&combined, &fields, CeoPostsTimestampUnit::Seconds, |r| { - emitted.push(r.spiel_id); - }) - .unwrap_err(); - assert_eq!(emitted, vec!["ok_first".to_string()]); - assert!( - matches!(err, BsonCeoPostsError::CorruptBson { offset, .. } if offset == good_len), - "expected CorruptBson for nested embedded doc at offset {good_len}, got {err:?}" - ); - - // 6. Corrupt array index inside an unused array after one valid doc - let mut arr = RawArrayBuf::new(); - arr.push(10_i32); - arr.push(20_i32); - let mut arr_bad = make_base_doc("CH-3", "arr_bad", ts_sec); - arr_bad.append(cstr!("votes"), arr); - let mut arr_bytes = arr_bad.into_bytes(); - let idx1 = arr_bytes - .windows(3) - .position(|w| w == [0x10, b'1', 0x00]) - .expect("locate index 1"); - arr_bytes[idx1 + 1] = b'2'; - - let mut combined = good.as_bytes().to_vec(); - combined.extend_from_slice(&arr_bytes); - let mut emitted = Vec::new(); - let err = decode_ceo_posts_buffer(&combined, &fields, CeoPostsTimestampUnit::Seconds, |r| { - emitted.push(r.spiel_id); - }) - .unwrap_err(); - assert_eq!(emitted, vec!["ok_first".to_string()]); - assert!( - matches!(err, BsonCeoPostsError::CorruptBson { offset, .. } if offset == good_len), - "expected CorruptBson for corrupt array index at offset {good_len}, got {err:?}" - ); - - // 7. Trailing bytes on decode_ceo_posts_bytes -> CorruptDocumentLength - let mut extra = good.as_bytes().to_vec(); - extra.push(0x00); - let err = decode_ceo_posts_bytes(&extra, &fields, CeoPostsTimestampUnit::Seconds, |_| {}) - .unwrap_err(); - assert!(matches!( - err, - BsonCeoPostsError::CorruptDocumentLength { .. } - )); -} - -// --------------------------------------------------------------------------- -// QA edge cases (T-160) -// --------------------------------------------------------------------------- - -fn decode_one_seconds_and_millis( - doc: &RawDocumentBuf, -) -> [(BsonCeoPostsDecodeStats, Vec>); 2] { - let fields = CeoPostsFieldNames::default(); - [ - CeoPostsTimestampUnit::Seconds, - CeoPostsTimestampUnit::Millis, - ] - .map(|unit| { - let mut rows = Vec::new(); - let stats = decode_ceo_posts_bytes(doc.as_bytes(), &fields, unit, |r| { - rows.push(CeoPost { - key: r.key.to_owned(), - spiel_id: r.spiel_id, - timestamp_ms: r.timestamp_ms, - edited_ms: r.edited_ms, - bot: r.bot, - user_id: r.user_id, - text: r.text, - }) - }) - .expect("decode single doc"); - assert_conservation(&stats); - (stats, rows) - }) -} - -#[test] -fn same_numeric_bytes_scale_by_unit_but_datetime_ignores_unit() { - // Arrange: numeric Int64 timestamp/edited and a DateTime doc. - let mut numeric = make_base_doc("CH", "n", 1_710_460_800); - numeric.append(cstr!("edited"), 1_710_461_400_i64); - let mut dt_doc = RawDocumentBuf::new(); - dt_doc.append(cstr!("ceoId"), "CH"); - dt_doc.append(cstr!("spielId"), "d"); - dt_doc.append( - cstr!("timestamp"), - BsonDateTime::from_millis(1_710_460_800_000), - ); - dt_doc.append( - cstr!("edited"), - BsonDateTime::from_millis(1_710_461_400_000), - ); - - // Act - let [(_, n_sec), (_, n_ms)] = decode_one_seconds_and_millis(&numeric); - let [(_, d_sec), (_, d_ms)] = decode_one_seconds_and_millis(&dt_doc); - - // Assert: numeric values differ by exactly 1000x; DateTime is identical under both units. - assert_eq!(n_sec[0].timestamp_ms, 1_710_460_800_000); - assert_eq!(n_sec[0].edited_ms, Some(1_710_461_400_000)); - assert_eq!(n_ms[0].timestamp_ms, 1_710_460_800); - assert_eq!(n_ms[0].edited_ms, Some(1_710_461_400)); - assert_eq!(d_sec, d_ms); - assert_eq!(d_sec[0].timestamp_ms, 1_710_460_800_000); - assert_eq!(d_sec[0].edited_ms, Some(1_710_461_400_000)); -} - -#[test] -fn edited_rejections_hold_under_millis_and_large_millis_values_do_not_overflow() { - // Negative/fractional/true/string edits must also fail closed under Millis. - let bad: Vec = vec![ - RawBson::Int32(-1), - RawBson::Int64(i64::MIN), - RawBson::Double(-0.5), - RawBson::Double(0.5), - RawBson::Double(f64::NEG_INFINITY), - RawBson::Boolean(true), - RawBson::String(String::new()), - RawBson::Double(9_223_372_036_854_775_808.0), - ]; - for value in bad { - let mut d = make_base_doc("CH", "x", 1_710_460_800_000); - d.append(cstr!("edited"), value.clone()); - let [_, (stats, rows)] = decode_one_seconds_and_millis(&d); - assert!( - rows.is_empty(), - "edited {value:?} must not emit under Millis" - ); - assert_eq!(stats.skipped_invalid_edited, 1, "edited {value:?}"); - } - - // A value that overflows under Seconds is valid under Millis. - let mut d = make_base_doc("CH", "big", 1); - d.append(cstr!("edited"), i64::MAX); - let [(sec_stats, sec_rows), (ms_stats, ms_rows)] = decode_one_seconds_and_millis(&d); - assert!(sec_rows.is_empty()); - assert_eq!(sec_stats.skipped_invalid_edited, 1); - assert_eq!(ms_stats.rows_out, 1); - assert_eq!(ms_rows[0].edited_ms, Some(i64::MAX)); -} - -#[test] -fn bot_and_user_id_normalization_covers_int64_false_null_and_verbatim_strings() { - let cases: Vec<(RawBson, Option<&str>, usize)> = vec![ - (RawBson::Int64(1), Some("1"), 0), - (RawBson::Int32(-7), Some("-7"), 0), - (RawBson::Boolean(false), Some("0"), 0), - (RawBson::Null, None, 0), - (RawBson::String(" 1 ".into()), Some(" 1 "), 0), - (RawBson::Document(RawDocumentBuf::new()), None, 1), - ]; - for (value, expected, nulled) in cases { - let mut d = make_base_doc("CH", "b", 1_710_460_800); - d.append(cstr!("bot"), value.clone()); - d.append(cstr!("userId"), value.clone()); - let [(stats, rows), _] = decode_one_seconds_and_millis(&d); - assert_eq!(stats.rows_out, 1, "bot {value:?}"); - assert_eq!(rows[0].bot.as_deref(), expected, "bot {value:?}"); - assert_eq!(stats.nulled_wrong_type_bot, nulled, "bot {value:?}"); - let expected_user = match value { - // Boolean is not an accepted user_id type. - RawBson::Boolean(_) => None, - _ => expected, - }; - let expected_user_nulled = usize::from(matches!(value, RawBson::Boolean(_))) + nulled; - assert_eq!( - rows[0].user_id.as_deref(), - expected_user, - "userId {value:?}" - ); - assert_eq!( - stats.nulled_wrong_type_user_id, expected_user_nulled, - "userId {value:?}" - ); - } -} - -#[test] -fn preserves_unicode_text_and_key_verbatim_and_key_borrows_from_single_doc_bytes() { - let mut d = RawDocumentBuf::new(); - d.append(cstr!("ceoId"), "Ünïcødé-CH 📈"); - d.append(cstr!("spielId"), " s 1 "); - d.append(cstr!("timestamp"), 1_710_460_800_i64); - d.append(cstr!("spiel"), " $XYZ to the 🌕\nline2\t "); - let bytes = d.as_bytes(); - let (start, end) = ( - bytes.as_ptr() as usize, - bytes.as_ptr() as usize + bytes.len(), - ); - - let mut seen = Vec::new(); - decode_ceo_posts_bytes( - bytes, - &CeoPostsFieldNames::default(), - CeoPostsTimestampUnit::Seconds, - |r| { - let p = r.key.as_ptr() as usize; - assert!( - p >= start && p + r.key.len() <= end, - "key must borrow from input bytes" - ); - seen.push((r.key, r.spiel_id, r.text)); - }, - ) - .expect("decode"); - - assert_eq!( - seen, - vec![( - "Ünïcødé-CH 📈", - " s 1 ".to_string(), - " $XYZ to the 🌕\nline2\t ".to_string() - )] - ); -} - -#[test] -fn spiel_id_int64_extremes_render_as_decimal() { - for (value, expected) in [ - (RawBson::Int64(i64::MIN), i64::MIN.to_string()), - (RawBson::Int64(i64::MAX), i64::MAX.to_string()), - (RawBson::Int32(0), "0".to_string()), - ] { - let mut d = RawDocumentBuf::new(); - d.append(cstr!("ceoId"), "CH"); - d.append(cstr!("spielId"), value); - d.append(cstr!("timestamp"), 1_i64); - let [(_, rows), _] = decode_one_seconds_and_millis(&d); - assert_eq!(rows[0].spiel_id, expected); - } -} - -#[test] -fn invalid_utf8_in_unused_or_key_field_is_corrupt_bson_not_a_skip() { - let fields = CeoPostsFieldNames::default(); - for marker in ["ceoId", "extra"] { - let mut d = make_base_doc("KEYVAL", "s", 1_710_460_800); - d.append(cstr!("extra"), "EXTRAV"); - let mut bytes = d.into_bytes(); - let needle: &[u8] = if marker == "ceoId" { - b"KEYVAL" - } else { - b"EXTRAV" - }; - let pos = bytes.windows(6).position(|w| w == needle).expect("needle"); - bytes[pos] = 0xff; - - let mut emitted = 0; - let err = decode_ceo_posts_buffer(&bytes, &fields, CeoPostsTimestampUnit::Seconds, |_| { - emitted += 1 - }) - .unwrap_err(); - assert_eq!(emitted, 0, "{marker}"); - assert!( - matches!(err, BsonCeoPostsError::CorruptBson { offset: 0, .. }), - "{marker}: {err:?}" - ); - } -} - -#[test] -fn corruption_in_first_document_reports_offset_zero_and_emits_nothing() { - let fields = CeoPostsFieldNames::default(); - let good = make_base_doc("CH", "after", 1_710_460_800); - let mut buf = vec![3, 0, 0, 0, 0]; - buf.extend_from_slice(good.as_bytes()); - let mut emitted = 0; - let err = decode_ceo_posts_buffer(&buf, &fields, CeoPostsTimestampUnit::Seconds, |_| { - emitted += 1 - }) - .unwrap_err(); - assert_eq!(emitted, 0); - assert_eq!( - err, - BsonCeoPostsError::CorruptDocumentLength { - offset: 0, - declared_len: 3 - } - ); -} - -#[test] -fn excessive_nesting_fails_closed_without_stack_overflow_and_moderate_nesting_decodes() { - fn nested(depth: usize) -> RawDocumentBuf { - let mut inner = RawDocumentBuf::new(); - inner.append(cstr!("leaf"), 1_i32); - for _ in 0..depth { - let mut outer = RawDocumentBuf::new(); - outer.append(cstr!("n"), inner); - inner = outer; - } - inner - } - let fields = CeoPostsFieldNames::default(); - - let mut ok = make_base_doc("CH", "shallow", 1_710_460_800); - ok.append(cstr!("meta"), nested(10)); - let stats = decode_ceo_posts_bytes( - ok.as_bytes(), - &fields, - CeoPostsTimestampUnit::Seconds, - |_| {}, - ) - .expect("moderate nesting decodes"); - assert_eq!(stats.rows_out, 1); - - let mut deep = make_base_doc("CH", "deep", 1_710_460_800); - deep.append(cstr!("meta"), nested(400)); - let err = decode_ceo_posts_bytes( - deep.as_bytes(), - &fields, - CeoPostsTimestampUnit::Seconds, - |_| panic!("deep nesting must not emit"), - ) - .unwrap_err(); - assert!( - matches!(err, BsonCeoPostsError::CorruptBson { offset: 0, .. }), - "{err:?}" - ); -} - -#[test] -fn empty_buffer_yields_zero_stats() { - let stats = decode_ceo_posts_buffer( - &[], - &CeoPostsFieldNames::default(), - CeoPostsTimestampUnit::Millis, - |_| panic!("no rows"), - ) - .expect("empty buffer ok"); - assert_eq!(stats, BsonCeoPostsDecodeStats::default()); -} - -#[test] -fn add_assign_sums_every_counter() { - let a = BsonCeoPostsDecodeStats { - docs_in: 1, - rows_out: 2, - skipped_missing_key: 3, - skipped_wrong_key_type: 4, - skipped_empty_key: 5, - skipped_missing_spiel_id: 6, - skipped_wrong_spiel_id_type: 7, - skipped_empty_spiel_id: 8, - skipped_missing_timestamp: 9, - skipped_wrong_timestamp_type: 10, - skipped_invalid_timestamp: 11, - skipped_timestamp_out_of_range: 12, - skipped_invalid_edited: 13, - skipped_wrong_text_type: 14, - edited_zero_or_false: 15, - nulled_wrong_type_bot: 16, - nulled_wrong_type_user_id: 17, - empty_text: 18, - }; - let mut sum = a; - sum += a; - let doubled = BsonCeoPostsDecodeStats { - docs_in: 2, - rows_out: 4, - skipped_missing_key: 6, - skipped_wrong_key_type: 8, - skipped_empty_key: 10, - skipped_missing_spiel_id: 12, - skipped_wrong_spiel_id_type: 14, - skipped_empty_spiel_id: 16, - skipped_missing_timestamp: 18, - skipped_wrong_timestamp_type: 20, - skipped_invalid_timestamp: 22, - skipped_timestamp_out_of_range: 24, - skipped_invalid_edited: 26, - skipped_wrong_text_type: 28, - edited_zero_or_false: 30, - nulled_wrong_type_bot: 32, - nulled_wrong_type_user_id: 34, - empty_text: 36, - }; - assert_eq!(sum, doubled); - // skipped_total excludes docs_in, rows_out and emitted-row counters: 3+..+14 = 102. - assert_eq!(a.skipped_total(), 102); -} - -#[test] -fn edited_text_is_excluded_at_a_cutoff_between_post_and_edit() { - // Point-in-time check: a consumer filtering `known_at < cutoff` must not see edited text - // whose edit happened after the cutoff, while an unedited post at the same time is visible. - let posted = 1_710_460_800_i64; // seconds - let edit = posted + 600; - let cutoff_us = (posted + 300) * 1_000_000; - - let mut unedited = make_base_doc("CH", "plain", posted); - unedited.append(cstr!("edited"), 0_i32); - let mut edited = make_base_doc("CH", "edited", posted); - edited.append(cstr!("edited"), edit); - let mut buf = unedited.into_bytes(); - buf.extend_from_slice(edited.as_bytes()); - - let mut rows = Vec::new(); - decode_ceo_posts_buffer( - &buf, - &CeoPostsFieldNames::default(), - CeoPostsTimestampUnit::Seconds, - |r| rows.push(r), - ) - .expect("decode"); - let built = build_posts(rows).expect("build"); - - let visible: Vec<&str> = built - .retail - .iter() - .filter(|r| r.known_at < cutoff_us) - .map(|r| r.spiel_id.as_str()) - .collect(); - assert_eq!(visible, vec!["plain"]); - let late = built - .retail - .iter() - .find(|r| r.spiel_id == "edited") - .expect("edited row"); - assert_eq!(late.known_at, edit * 1_000_000); - assert_eq!(late.posted_at, posted * 1_000_000); -} diff --git a/tools/curate-etl/src/bson_ceo_shorts.rs b/tools/curate-etl/src/bson_ceo_shorts.rs deleted file mode 100644 index dff169a0..00000000 --- a/tools/curate-etl/src/bson_ceo_shorts.rs +++ /dev/null @@ -1,627 +0,0 @@ -//! Zero-copy raw BSON decoder for MongoDB `ceoShorts` documents (`M1.2ad`). -//! -//! Decodes `&bson::RawDocument` slices in a single forward pass over `iter_elements()` without -//! allocating a `bson::Document` or per-row `String`s, emitting borrowed [`CeoShortReport<&str>`] -//! rows via a caller-supplied callback. -//! -//! # Unverified Live Schema & Explicit Field Configuration -//! -//! `apps/stock/data-ingestion/src/handlers/ceo/actions/get-shorts.action.ts` stores the upstream -//! `positions[]` payload verbatim, and `design/DATA-CONTRACTS.md` §1 only establishes `timestamp` -//! (the report period date). The value field names are not recorded anywhere in the repository, so -//! callers must supply all field names explicitly via [`CeoShortsFieldNames`] (and the CLI -//! requires `--shares-short-field` with no default). -//! -//! # Decoding & Validation Rules -//! - Every element of each [`RawDocument`] is scanned to completion before applying semantic skip -//! rules so structural BSON corruption always returns `Err(BsonCeoShortsError::CorruptBson)` -//! rather than being masked by an earlier semantic skip. -//! - `key`: BSON UTF-8 `String` passed through verbatim (no trimming, no suffix stripping); empty -//! or whitespace-only strings are skipped (`skipped_empty_key`). -//! - `report_date`: BSON `DateTime` (UTC calendar day via `timestamp_millis().div_euclid(86_400_000)` -//! checked to `i32`), or `Int32` / `Int64` / integral finite `Double` converted via -//! [`crate::bson_te_market_data::te_epoch_i64_to_session_date`] (seconds vs. milliseconds UTC). -//! Non-finite or fractional `Double`s are skipped under `skipped_invalid_report_date`; values -//! outside `i64`/`i32` epoch-day range are skipped under `skipped_report_date_out_of_range`. -//! - `shares_short`: BSON `Double`, `Int32`, or `Int64` (strings are rejected as wrong type per -//! crate convention). Sign and finiteness validation remains in [`crate::shorts::build_shorts`]. -//! - `net_change` and `pct_float`: optional; unconfigured, absent, or BSON `Null` yields `None`; -//! wrong BSON type yields `None` and increments `nulled_wrong_type_*` (only on emitted rows). -//! - Deterministic semantic skip priority: `key` → `report_date` → `shares_short`. -//! - Conservation invariant: `docs_in == rows_out + skipped_total()`. - -use std::error::Error; -use std::fmt; - -use bson::raw::{RawBsonRef, RawDocument}; - -use crate::bson_eod_prices::{iter_raw_bson_docs, parse_single_raw_doc, BsonEodPriceError}; -use crate::bson_te_market_data::{te_epoch_i64_to_session_date, MILLIS_PER_DAY}; -use crate::shorts::CeoShortReport; - -/// Default BSON field name for the `ceoShorts` security key (`--key-field`). -pub const DEFAULT_KEY_FIELD: &str = "symbol"; -/// Default BSON field name for the `ceoShorts` report period date (`--report-date-field`). -pub const DEFAULT_REPORT_DATE_FIELD: &str = "timestamp"; - -/// Borrowed BSON field-name configuration for decoding `ceoShorts` documents. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct CeoShortsFieldNames<'a> { - pub key: &'a str, - pub report_date: &'a str, - pub shares_short: &'a str, - pub net_change: Option<&'a str>, - pub pct_float: Option<&'a str>, -} - -impl<'a> CeoShortsFieldNames<'a> { - /// Validates that every configured field name is non-empty/non-blank and that no two - /// configured roles point to the same BSON field name. - pub fn validate(&self) -> Result<(), BsonCeoShortsError> { - let mut roles: [(&'static str, Option<&str>); 5] = [ - ("key", Some(self.key)), - ("report_date", Some(self.report_date)), - ("shares_short", Some(self.shares_short)), - ("net_change", self.net_change), - ("pct_float", self.pct_float), - ]; - - for &(role, name_opt) in &roles { - if let Some(name) = name_opt { - if name.trim().is_empty() { - return Err(BsonCeoShortsError::InvalidFieldNames { - detail: format!("field name for '{role}' must not be empty or blank"), - }); - } - } - } - - for i in 0..roles.len() { - let (role_a, Some(name_a)) = roles[i] else { - continue; - }; - for &(role_b, name_b_opt) in &roles[i + 1..] { - if let Some(name_b) = name_b_opt { - if name_a == name_b { - return Err(BsonCeoShortsError::InvalidFieldNames { - detail: format!( - "roles '{role_a}' and '{role_b}' cannot share BSON field '{name_a}'" - ), - }); - } - } - } - } - - // Keep `roles` binding clean without unused_mut warnings. - let _ = &mut roles; - Ok(()) - } -} - -/// Typed errors returned while validating field configuration or decoding raw `ceoShorts` BSON. -/// -/// Structural BSON framing or element errors fail closed and carry a `u64` byte offset; -/// every variant's `Display` output is a single line. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum BsonCeoShortsError { - /// Invalid [`CeoShortsFieldNames`] configuration (empty/blank name or duplicate role mapping). - InvalidFieldNames { detail: String }, - /// Buffer ended before a complete 4-byte length prefix or declared document body. - TruncatedDocument { - offset: u64, - remaining: usize, - declared_len: Option, - }, - /// Declared 4-byte little-endian BSON document length was `< 5` (or did not match a single - /// document slice). - CorruptDocumentLength { offset: u64, declared_len: i32 }, - /// Underlying BSON framing or element bytes were malformed. - CorruptBson { offset: u64, detail: String }, -} - -impl fmt::Display for BsonCeoShortsError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::InvalidFieldNames { detail } => { - write!(f, "invalid ceoShorts field configuration: {detail}") - } - Self::TruncatedDocument { - offset, - remaining, - declared_len, - } => match declared_len { - Some(len) => write!( - f, - "truncated BSON document at byte offset {offset}: declared length {len} exceeds remaining {remaining} bytes" - ), - None => write!( - f, - "truncated BSON document header at byte offset {offset}: only {remaining} bytes remaining" - ), - }, - Self::CorruptDocumentLength { - offset, - declared_len, - } => write!( - f, - "corrupt BSON document length {declared_len} at byte offset {offset}" - ), - Self::CorruptBson { offset, detail } => { - write!(f, "corrupt BSON bytes at byte offset {offset}: {detail}") - } - } - } -} - -impl Error for BsonCeoShortsError {} - -#[inline] -fn map_framing_error(err: BsonEodPriceError) -> BsonCeoShortsError { - match err { - BsonEodPriceError::TruncatedDocument { - offset, - remaining, - declared_len, - } => BsonCeoShortsError::TruncatedDocument { - offset: offset as u64, - remaining, - declared_len, - }, - BsonEodPriceError::CorruptDocumentLength { - offset, - declared_len, - } => BsonCeoShortsError::CorruptDocumentLength { - offset: offset as u64, - declared_len, - }, - BsonEodPriceError::CorruptBson { offset, detail } => BsonCeoShortsError::CorruptBson { - offset: offset as u64, - detail, - }, - other => BsonCeoShortsError::CorruptBson { - offset: 0, - detail: other.to_string(), - }, - } -} - -/// Per-batch decode accounting for `ceoShorts`. -/// -/// Conservation invariant: -/// `docs_in == rows_out + skipped_total()` -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct BsonCeoShortsDecodeStats { - pub docs_in: usize, - pub rows_out: usize, - pub skipped_missing_key: usize, - pub skipped_wrong_key_type: usize, - pub skipped_empty_key: usize, - pub skipped_missing_report_date: usize, - pub skipped_wrong_report_date_type: usize, - pub skipped_invalid_report_date: usize, - pub skipped_report_date_out_of_range: usize, - pub skipped_missing_shares_short: usize, - pub skipped_wrong_shares_short_type: usize, - pub nulled_wrong_type_net_change: usize, - pub nulled_wrong_type_pct_float: usize, -} - -impl BsonCeoShortsDecodeStats { - /// Total number of semantically skipped documents across all skip categories. - #[inline] - pub fn skipped_total(&self) -> usize { - self.skipped_missing_key - + self.skipped_wrong_key_type - + self.skipped_empty_key - + self.skipped_missing_report_date - + self.skipped_wrong_report_date_type - + self.skipped_invalid_report_date - + self.skipped_report_date_out_of_range - + self.skipped_missing_shares_short - + self.skipped_wrong_shares_short_type - } - - /// Accumulates counters from another batch into `self`. - #[inline] - pub fn merge(&mut self, other: &Self) { - self.docs_in += other.docs_in; - self.rows_out += other.rows_out; - self.skipped_missing_key += other.skipped_missing_key; - self.skipped_wrong_key_type += other.skipped_wrong_key_type; - self.skipped_empty_key += other.skipped_empty_key; - self.skipped_missing_report_date += other.skipped_missing_report_date; - self.skipped_wrong_report_date_type += other.skipped_wrong_report_date_type; - self.skipped_invalid_report_date += other.skipped_invalid_report_date; - self.skipped_report_date_out_of_range += other.skipped_report_date_out_of_range; - self.skipped_missing_shares_short += other.skipped_missing_shares_short; - self.skipped_wrong_shares_short_type += other.skipped_wrong_shares_short_type; - self.nulled_wrong_type_net_change += other.nulled_wrong_type_net_change; - self.nulled_wrong_type_pct_float += other.nulled_wrong_type_pct_float; - } -} - -impl std::ops::AddAssign for BsonCeoShortsDecodeStats { - #[inline] - fn add_assign(&mut self, rhs: Self) { - self.merge(&rhs); - } -} - -enum KeyState<'a> { - Missing, - WrongType, - Empty, - Valid(&'a str), -} - -enum DateState { - Missing, - WrongType, - Invalid, - OutOfRange, - Valid(i32), -} - -enum SharesState { - Missing, - WrongType, - Valid(f64), -} - -enum OptionalNumState { - None, - WrongType, - Valid(f64), -} - -#[inline] -fn decode_report_date_val(val: RawBsonRef<'_>) -> DateState { - match val { - RawBsonRef::DateTime(dt) => { - let days = dt.timestamp_millis().div_euclid(MILLIS_PER_DAY); - match i32::try_from(days) { - Ok(d) => DateState::Valid(d), - Err(_) => DateState::OutOfRange, - } - } - RawBsonRef::Int32(v) => match te_epoch_i64_to_session_date(i64::from(v)) { - Some(d) => DateState::Valid(d), - None => DateState::OutOfRange, - }, - RawBsonRef::Int64(v) => match te_epoch_i64_to_session_date(v) { - Some(d) => DateState::Valid(d), - None => DateState::OutOfRange, - }, - RawBsonRef::Double(v) => { - if !v.is_finite() || v.fract() != 0.0 { - return DateState::Invalid; - } - // Exact half-open range of `f64` values representable as `i64` (`[-2^63, 2^63)`). - if !(-9_223_372_036_854_775_808.0..9_223_372_036_854_775_808.0).contains(&v) { - return DateState::OutOfRange; - } - match te_epoch_i64_to_session_date(v as i64) { - Some(d) => DateState::Valid(d), - None => DateState::OutOfRange, - } - } - _ => DateState::WrongType, - } -} - -#[inline] -fn decode_required_number(val: RawBsonRef<'_>) -> SharesState { - match val { - RawBsonRef::Double(v) => SharesState::Valid(v), - RawBsonRef::Int32(v) => SharesState::Valid(f64::from(v)), - RawBsonRef::Int64(v) => SharesState::Valid(v as f64), - _ => SharesState::WrongType, - } -} - -#[inline] -fn decode_optional_number(val: RawBsonRef<'_>) -> OptionalNumState { - match val { - RawBsonRef::Null => OptionalNumState::None, - RawBsonRef::Double(v) => OptionalNumState::Valid(v), - RawBsonRef::Int32(v) => OptionalNumState::Valid(f64::from(v)), - RawBsonRef::Int64(v) => OptionalNumState::Valid(v as f64), - _ => OptionalNumState::WrongType, - } -} - -/// Maximum recursive nesting depth accepted while validating raw BSON documents and arrays. -const MAX_BSON_VALIDATION_DEPTH: usize = 128; - -#[inline] -fn is_exact_array_index(key: &str, expected: usize) -> bool { - let bytes = key.as_bytes(); - if bytes.is_empty() || (bytes.len() > 1 && bytes[0] == b'0') { - return false; - } - let mut parsed: usize = 0; - for &b in bytes { - if !b.is_ascii_digit() { - return false; - } - let digit = usize::from(b - b'0'); - match parsed.checked_mul(10).and_then(|n| n.checked_add(digit)) { - Some(next) => parsed = next, - None => return false, - } - } - parsed == expected -} - -fn validate_raw_bson_value( - val: RawBsonRef<'_>, - doc_offset: u64, - field_name: &str, - depth: usize, -) -> Result<(), BsonCeoShortsError> { - match val { - RawBsonRef::Document(subdoc) => { - validate_raw_document(subdoc, doc_offset, field_name, depth + 1) - } - RawBsonRef::Array(arr) => { - if depth >= MAX_BSON_VALIDATION_DEPTH { - return Err(BsonCeoShortsError::CorruptBson { - offset: doc_offset, - detail: format!( - "field '{field_name}': nested BSON depth exceeds limit {MAX_BSON_VALIDATION_DEPTH}" - ), - }); - } - for (expected_idx, elem_res) in arr.iter_elements().enumerate() { - let elem = elem_res.map_err(|err| BsonCeoShortsError::CorruptBson { - offset: doc_offset, - detail: format!("field '{field_name}': {err}"), - })?; - let key = elem.key().as_str(); - if !is_exact_array_index(key, expected_idx) { - return Err(BsonCeoShortsError::CorruptBson { - offset: doc_offset, - detail: format!( - "field '{field_name}': invalid BSON array index '{key}' at position {expected_idx}" - ), - }); - } - let item = elem.value().map_err(|err| BsonCeoShortsError::CorruptBson { - offset: doc_offset, - detail: format!("field '{field_name}': {err}"), - })?; - validate_raw_bson_value(item, doc_offset, field_name, depth + 1)?; - } - Ok(()) - } - RawBsonRef::JavaScriptCodeWithScope(code_with_scope) => { - validate_raw_document(code_with_scope.scope, doc_offset, field_name, depth + 1) - } - _ => Ok(()), - } -} - -fn validate_raw_document( - doc: &RawDocument, - doc_offset: u64, - field_name: &str, - depth: usize, -) -> Result<(), BsonCeoShortsError> { - if depth > MAX_BSON_VALIDATION_DEPTH { - return Err(BsonCeoShortsError::CorruptBson { - offset: doc_offset, - detail: format!( - "field '{field_name}': nested BSON depth exceeds limit {MAX_BSON_VALIDATION_DEPTH}" - ), - }); - } - for elem_res in doc.iter_elements() { - let elem = elem_res.map_err(|err| BsonCeoShortsError::CorruptBson { - offset: doc_offset, - detail: format!("field '{field_name}': {err}"), - })?; - let val = elem.value().map_err(|err| BsonCeoShortsError::CorruptBson { - offset: doc_offset, - detail: format!("field '{field_name}': {err}"), - })?; - validate_raw_bson_value(val, doc_offset, field_name, depth)?; - } - Ok(()) -} - -fn decode_ceo_shorts_doc_at<'a, F>( - doc: &'a RawDocument, - doc_offset: u64, - fields: &CeoShortsFieldNames<'_>, - mut on_row: F, -) -> Result -where - F: FnMut(CeoShortReport<&'a str>), -{ - let mut stats = BsonCeoShortsDecodeStats { - docs_in: 1, - ..BsonCeoShortsDecodeStats::default() - }; - - let mut key_state = KeyState::Missing; - let mut date_state = DateState::Missing; - let mut shares_state = SharesState::Missing; - let mut net_change_state = OptionalNumState::None; - let mut pct_float_state = OptionalNumState::None; - - // Scan and validate every element and nested raw value to completion so structural BSON - // corruption (including invalid UTF-8 in unused fields or malformed nested documents/arrays) - // always fails closed and is never masked by an earlier semantic skip. - for elem_res in doc.iter_elements() { - let elem = elem_res.map_err(|err| BsonCeoShortsError::CorruptBson { - offset: doc_offset, - detail: err.to_string(), - })?; - let name = elem.key().as_str(); - let val = elem.value().map_err(|err| BsonCeoShortsError::CorruptBson { - offset: doc_offset, - detail: format!("field '{name}': {err}"), - })?; - validate_raw_bson_value(val, doc_offset, name, 0)?; - - if name == fields.key { - key_state = match val { - RawBsonRef::String(s) => { - if s.trim().is_empty() { - KeyState::Empty - } else { - KeyState::Valid(s) - } - } - _ => KeyState::WrongType, - }; - } else if name == fields.report_date { - date_state = decode_report_date_val(val); - } else if name == fields.shares_short { - shares_state = decode_required_number(val); - } else if fields.net_change == Some(name) { - net_change_state = decode_optional_number(val); - } else if fields.pct_float == Some(name) { - pct_float_state = decode_optional_number(val); - } - } - - // Apply deterministic semantic skip priority: key -> report_date -> shares_short. - let key = match key_state { - KeyState::Valid(s) => s, - KeyState::Missing => { - stats.skipped_missing_key += 1; - return Ok(stats); - } - KeyState::WrongType => { - stats.skipped_wrong_key_type += 1; - return Ok(stats); - } - KeyState::Empty => { - stats.skipped_empty_key += 1; - return Ok(stats); - } - }; - - let report_date = match date_state { - DateState::Valid(d) => d, - DateState::Missing => { - stats.skipped_missing_report_date += 1; - return Ok(stats); - } - DateState::WrongType => { - stats.skipped_wrong_report_date_type += 1; - return Ok(stats); - } - DateState::Invalid => { - stats.skipped_invalid_report_date += 1; - return Ok(stats); - } - DateState::OutOfRange => { - stats.skipped_report_date_out_of_range += 1; - return Ok(stats); - } - }; - - let shares_short = match shares_state { - SharesState::Valid(v) => v, - SharesState::Missing => { - stats.skipped_missing_shares_short += 1; - return Ok(stats); - } - SharesState::WrongType => { - stats.skipped_wrong_shares_short_type += 1; - return Ok(stats); - } - }; - - let net_change = match net_change_state { - OptionalNumState::Valid(v) => Some(v), - OptionalNumState::None => None, - OptionalNumState::WrongType => { - stats.nulled_wrong_type_net_change += 1; - None - } - }; - - let pct_float = match pct_float_state { - OptionalNumState::Valid(v) => Some(v), - OptionalNumState::None => None, - OptionalNumState::WrongType => { - stats.nulled_wrong_type_pct_float += 1; - None - } - }; - - stats.rows_out += 1; - on_row(CeoShortReport { - key, - report_date, - shares_short, - net_change, - pct_float, - }); - Ok(stats) -} - -/// Decodes a single `&RawDocument` representing a `ceoShorts` MongoDB document in one forward -/// pass without allocating a `bson::Document` or per-row `String`s. -pub fn decode_ceo_shorts_doc<'a, F>( - doc: &'a RawDocument, - fields: &CeoShortsFieldNames<'_>, - on_row: F, -) -> Result -where - F: FnMut(CeoShortReport<&'a str>), -{ - fields.validate()?; - decode_ceo_shorts_doc_at(doc, 0, fields, on_row) -} - -/// Decodes a single length-prefixed raw BSON document byte slice representing a `ceoShorts` -/// document. -pub fn decode_ceo_shorts_bytes<'a, F>( - bytes: &'a [u8], - fields: &CeoShortsFieldNames<'_>, - on_row: F, -) -> Result -where - F: FnMut(CeoShortReport<&'a str>), -{ - fields.validate()?; - let doc = parse_single_raw_doc(bytes).map_err(map_framing_error)?; - decode_ceo_shorts_doc_at(doc, 0, fields, on_row) -} - -/// Streams a concatenated length-prefixed BSON buffer through [`decode_ceo_shorts_doc`], -/// emitting every valid [`CeoShortReport<&str>`] to `on_row` and failing closed on any structural -/// BSON framing or element corruption. -/// -/// Always maintains `stats.docs_in == stats.rows_out + stats.skipped_total()`. -pub fn decode_ceo_shorts_buffer<'a, F>( - buf: &'a [u8], - fields: &CeoShortsFieldNames<'_>, - mut on_row: F, -) -> Result -where - F: FnMut(CeoShortReport<&'a str>), -{ - fields.validate()?; - let mut total = BsonCeoShortsDecodeStats::default(); - let mut iter = iter_raw_bson_docs(buf); - while let Some(item) = iter.next_with_offset() { - match item { - Ok((offset, doc)) => { - let doc_stats = decode_ceo_shorts_doc_at(doc, offset as u64, fields, &mut on_row)?; - total += doc_stats; - } - Err((_, err)) => return Err(map_framing_error(err)), - } - } - Ok(total) -} - -#[cfg(test)] -#[path = "bson_ceo_shorts_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/bson_ceo_shorts_tests.rs b/tools/curate-etl/src/bson_ceo_shorts_tests.rs deleted file mode 100644 index cac3c154..00000000 --- a/tools/curate-etl/src/bson_ceo_shorts_tests.rs +++ /dev/null @@ -1,732 +0,0 @@ -use bson::raw::{cstr, RawBson, RawDocumentBuf}; -use bson::DateTime as BsonDateTime; - -use super::*; -use crate::split::ymd_to_epoch_days; - -fn day(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).expect("valid date") -} - -fn default_fields() -> CeoShortsFieldNames<'static> { - CeoShortsFieldNames { - key: DEFAULT_KEY_FIELD, - report_date: DEFAULT_REPORT_DATE_FIELD, - shares_short: "sharesShort", - net_change: Some("netChange"), - pct_float: Some("pctFloat"), - } -} - -fn assert_conservation(stats: &BsonCeoShortsDecodeStats) { - assert_eq!( - stats.docs_in, - stats.rows_out + stats.skipped_total(), - "conservation invariant failed: {stats:?}" - ); -} - -#[test] -fn validates_field_names_rejecting_empty_blank_and_duplicates() { - assert!(default_fields().validate().is_ok()); - - let no_opt = CeoShortsFieldNames { - key: "k", - report_date: "d", - shares_short: "s", - net_change: None, - pct_float: None, - }; - assert!(no_opt.validate().is_ok()); - - let bad_configs = [ - CeoShortsFieldNames { - key: "", - ..default_fields() - }, - CeoShortsFieldNames { - key: " \t ", - ..default_fields() - }, - CeoShortsFieldNames { - report_date: "", - ..default_fields() - }, - CeoShortsFieldNames { - shares_short: " ", - ..default_fields() - }, - CeoShortsFieldNames { - net_change: Some(""), - ..default_fields() - }, - CeoShortsFieldNames { - pct_float: Some(" "), - ..default_fields() - }, - // Duplicate roles - CeoShortsFieldNames { - key: "same", - report_date: "same", - ..default_fields() - }, - CeoShortsFieldNames { - key: "symbol", - shares_short: "symbol", - ..default_fields() - }, - CeoShortsFieldNames { - report_date: "timestamp", - shares_short: "timestamp", - ..default_fields() - }, - CeoShortsFieldNames { - net_change: Some("sharesShort"), - ..default_fields() - }, - CeoShortsFieldNames { - pct_float: Some("netChange"), - ..default_fields() - }, - ]; - - for cfg in bad_configs { - let err = cfg.validate().unwrap_err(); - assert!( - matches!(err, BsonCeoShortsError::InvalidFieldNames { .. }), - "expected InvalidFieldNames for {cfg:?}, got {err:?}" - ); - let msg = err.to_string(); - assert!(!msg.contains('\n'), "single-line display expected: {msg}"); - - // Entry points also reject invalid config before touching bytes. - assert!(matches!( - decode_ceo_shorts_buffer(&[], &cfg, |_| {}), - Err(BsonCeoShortsError::InvalidFieldNames { .. }) - )); - } -} - -#[test] -fn decodes_report_date_across_datetime_int32_int64_and_integral_double() { - let fields = default_fields(); - let d_2024_03_15 = day(2024, 3, 15); - let secs_2024_03_15 = i64::from(d_2024_03_15) * 86_400 + 3_600; // 01:00 UTC - let millis_2024_03_15 = secs_2024_03_15 * 1_000 + 500; - - let mut buf = Vec::new(); - - // 1. BSON DateTime - let mut doc1 = RawDocumentBuf::new(); - doc1.append(cstr!("symbol"), "RY"); - doc1.append( - cstr!("timestamp"), - BsonDateTime::from_millis(millis_2024_03_15), - ); - doc1.append(cstr!("sharesShort"), 100_000_i32); - doc1.append(cstr!("netChange"), -5_000_i32); - doc1.append(cstr!("pctFloat"), 1.25_f64); - buf.extend_from_slice(doc1.as_bytes()); - - // 2. Int32 seconds - let mut doc2 = RawDocumentBuf::new(); - doc2.append(cstr!("symbol"), "TD"); - doc2.append(cstr!("timestamp"), secs_2024_03_15 as i32); - doc2.append(cstr!("sharesShort"), 250_000_i64); - doc2.append(cstr!("netChange"), 10_000_i64); - doc2.append(cstr!("pctFloat"), 2_i32); - buf.extend_from_slice(doc2.as_bytes()); - - // 3. Int64 seconds - let mut doc3 = RawDocumentBuf::new(); - doc3.append(cstr!("symbol"), "BNS"); - doc3.append(cstr!("timestamp"), secs_2024_03_15); - doc3.append(cstr!("sharesShort"), 300_000.5_f64); - buf.extend_from_slice(doc3.as_bytes()); - - // 4. Int64 millis - let mut doc4 = RawDocumentBuf::new(); - doc4.append(cstr!("symbol"), "BMO"); - doc4.append(cstr!("timestamp"), millis_2024_03_15); - doc4.append(cstr!("sharesShort"), 400_000.0_f64); - buf.extend_from_slice(doc4.as_bytes()); - - // 5. Integral finite Double (seconds) - let mut doc5 = RawDocumentBuf::new(); - doc5.append(cstr!("symbol"), "CM"); - doc5.append(cstr!("timestamp"), secs_2024_03_15 as f64); - doc5.append(cstr!("sharesShort"), 500_000.0_f64); - buf.extend_from_slice(doc5.as_bytes()); - - // 6. Integral finite Double (millis) - let mut doc6 = RawDocumentBuf::new(); - doc6.append(cstr!("symbol"), "NA"); - doc6.append(cstr!("timestamp"), millis_2024_03_15 as f64); - doc6.append(cstr!("sharesShort"), 600_000.0_f64); - buf.extend_from_slice(doc6.as_bytes()); - - // 7. Pre-1970 negative floor via DateTime (-1 ms -> 1969-12-31 == -1) - let mut doc7 = RawDocumentBuf::new(); - doc7.append(cstr!("symbol"), "PRE_DT"); - doc7.append(cstr!("timestamp"), BsonDateTime::from_millis(-1)); - doc7.append(cstr!("sharesShort"), 700_i32); - buf.extend_from_slice(doc7.as_bytes()); - - // 8. Pre-1970 negative floor via integral Double (-1.0 sec -> 1969-12-31 == -1) - let mut doc8 = RawDocumentBuf::new(); - doc8.append(cstr!("symbol"), "PRE_DBL"); - doc8.append(cstr!("timestamp"), -1.0_f64); - doc8.append(cstr!("sharesShort"), 800_i32); - buf.extend_from_slice(doc8.as_bytes()); - - // 9. -0.0 Double -> epoch day 0 (1970-01-01) - let mut doc9 = RawDocumentBuf::new(); - doc9.append(cstr!("symbol"), "NEG_ZERO"); - doc9.append(cstr!("timestamp"), -0.0_f64); - doc9.append(cstr!("sharesShort"), 900_i32); - buf.extend_from_slice(doc9.as_bytes()); - - let mut rows = Vec::new(); - let stats = decode_ceo_shorts_buffer(&buf, &fields, |r| { - rows.push(CeoShortReport { - key: r.key.to_string(), - report_date: r.report_date, - shares_short: r.shares_short, - net_change: r.net_change, - pct_float: r.pct_float, - }); - }) - .expect("decode buffer"); - - assert_conservation(&stats); - assert_eq!(stats.docs_in, 9); - assert_eq!(stats.rows_out, 9); - assert_eq!(stats.skipped_total(), 0); - - for row in &rows[..6] { - assert_eq!(row.report_date, d_2024_03_15); - } - assert_eq!(rows[0].net_change, Some(-5_000.0)); - assert_eq!(rows[0].pct_float, Some(1.25)); - assert_eq!(rows[1].net_change, Some(10_000.0)); - assert_eq!(rows[1].pct_float, Some(2.0)); - assert_eq!(rows[2].net_change, None); - assert_eq!(rows[2].pct_float, None); - assert_eq!(rows[6].report_date, -1); - assert_eq!(rows[7].report_date, -1); - assert_eq!(rows[8].report_date, 0); -} - -#[test] -fn decodes_custom_field_names_and_preserves_verbatim_key_and_unconfigured_optionals() { - let fields = CeoShortsFieldNames { - key: "tickerCode", - report_date: "asOfDate", - shares_short: "shortPos", - net_change: None, - pct_float: None, - }; - - let d = day(2024, 6, 30); - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("_id"), "ignored_id"); - doc.append(cstr!("tickerCode"), " SHOP.TO "); // verbatim, not trimmed - doc.append(cstr!("asOfDate"), i64::from(d) * 86_400); - doc.append(cstr!("shortPos"), 42_000_i64); - // Even if unrelated fields exist with wrong types, unconfigured optionals stay None without counting. - doc.append(cstr!("netChange"), "not-a-number"); - doc.append(cstr!("pctFloat"), true); - - let mut rows = Vec::new(); - let stats = decode_ceo_shorts_bytes(doc.as_bytes(), &fields, |r| { - rows.push(( - r.key.to_string(), - r.report_date, - r.shares_short, - r.net_change, - r.pct_float, - )); - }) - .expect("decode bytes"); - - assert_conservation(&stats); - assert_eq!(stats.rows_out, 1); - assert_eq!(stats.nulled_wrong_type_net_change, 0); - assert_eq!(stats.nulled_wrong_type_pct_float, 0); - assert_eq!(rows, vec![(" SHOP.TO ".to_string(), d, 42_000.0, None, None)]); -} - -#[test] -fn skips_bad_required_fields_with_exact_counters_and_priority() { - let fields = default_fields(); - let d_secs = i64::from(day(2024, 3, 15)) * 86_400; - - let mut buf = Vec::new(); - - // 1. Missing key (also missing date & shares -> key wins priority) - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("extra"), 1_i32); - buf.extend_from_slice(doc.as_bytes()); - - // 2. Wrong key type (Int32) - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("symbol"), 123_i32); - doc.append(cstr!("timestamp"), d_secs); - doc.append(cstr!("sharesShort"), 10_i32); - buf.extend_from_slice(doc.as_bytes()); - - // 3. Empty/blank key (and wrong-typed optionals must NOT increment nulled_wrong_type_*) - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("symbol"), " "); - doc.append(cstr!("timestamp"), d_secs); - doc.append(cstr!("sharesShort"), 10_i32); - doc.append(cstr!("netChange"), "bad"); - doc.append(cstr!("pctFloat"), false); - buf.extend_from_slice(doc.as_bytes()); - - // 4. Missing report_date (also missing shares -> report_date wins priority) - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("symbol"), "A"); - buf.extend_from_slice(doc.as_bytes()); - - // 5. Wrong report_date type (String) - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("symbol"), "A"); - doc.append(cstr!("timestamp"), "2024-03-15"); - doc.append(cstr!("sharesShort"), 10_i32); - buf.extend_from_slice(doc.as_bytes()); - - // 6. Invalid report_date: fractional Double - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("symbol"), "A"); - doc.append(cstr!("timestamp"), 1_710_460_800.5_f64); - doc.append(cstr!("sharesShort"), 10_i32); - buf.extend_from_slice(doc.as_bytes()); - - // 7. Invalid report_date: NaN Double - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("symbol"), "A"); - doc.append(cstr!("timestamp"), f64::NAN); - doc.append(cstr!("sharesShort"), 10_i32); - buf.extend_from_slice(doc.as_bytes()); - - // 8. Invalid report_date: +Inf Double - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("symbol"), "A"); - doc.append(cstr!("timestamp"), f64::INFINITY); - doc.append(cstr!("sharesShort"), 10_i32); - buf.extend_from_slice(doc.as_bytes()); - - // 9. Out-of-range report_date: Double > 2^63 - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("symbol"), "A"); - doc.append(cstr!("timestamp"), 1e30_f64); - doc.append(cstr!("sharesShort"), 10_i32); - buf.extend_from_slice(doc.as_bytes()); - - // 10. Out-of-range report_date: DateTime overflowing i32 days - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("symbol"), "A"); - doc.append(cstr!("timestamp"), BsonDateTime::from_millis(i64::MAX)); - doc.append(cstr!("sharesShort"), 10_i32); - buf.extend_from_slice(doc.as_bytes()); - - // 11. Out-of-range report_date: Int64 overflowing i32 days - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("symbol"), "A"); - doc.append(cstr!("timestamp"), i64::MAX); - doc.append(cstr!("sharesShort"), 10_i32); - buf.extend_from_slice(doc.as_bytes()); - - // 12. Missing shares_short - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("symbol"), "A"); - doc.append(cstr!("timestamp"), d_secs); - buf.extend_from_slice(doc.as_bytes()); - - // 13. Wrong shares_short type: numeric string is rejected, not parsed - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("symbol"), "A"); - doc.append(cstr!("timestamp"), d_secs); - doc.append(cstr!("sharesShort"), "12345"); - buf.extend_from_slice(doc.as_bytes()); - - let mut emitted = 0usize; - let stats = decode_ceo_shorts_buffer(&buf, &fields, |_| emitted += 1).expect("decode buffer"); - assert_conservation(&stats); - assert_eq!(emitted, 0); - assert_eq!(stats.docs_in, 13); - assert_eq!(stats.rows_out, 0); - assert_eq!(stats.skipped_missing_key, 1); - assert_eq!(stats.skipped_wrong_key_type, 1); - assert_eq!(stats.skipped_empty_key, 1); - assert_eq!(stats.skipped_missing_report_date, 1); - assert_eq!(stats.skipped_wrong_report_date_type, 1); - assert_eq!(stats.skipped_invalid_report_date, 3); - assert_eq!(stats.skipped_report_date_out_of_range, 3); - assert_eq!(stats.skipped_missing_shares_short, 1); - assert_eq!(stats.skipped_wrong_shares_short_type, 1); - assert_eq!(stats.nulled_wrong_type_net_change, 0); - assert_eq!(stats.nulled_wrong_type_pct_float, 0); -} - -#[test] -fn passes_negative_and_nan_shares_through_and_handles_null_and_wrong_type_optionals() { - let fields = default_fields(); - let d_secs = i64::from(day(2024, 3, 15)) * 86_400; - - let mut buf = Vec::new(); - - // 1. Negative shares_short + Null optionals (not counted as wrong type) - let mut doc1 = RawDocumentBuf::new(); - doc1.append(cstr!("symbol"), "NEG"); - doc1.append(cstr!("timestamp"), d_secs); - doc1.append(cstr!("sharesShort"), -50.0_f64); - doc1.append(cstr!("netChange"), RawBson::Null); - doc1.append(cstr!("pctFloat"), RawBson::Null); - buf.extend_from_slice(doc1.as_bytes()); - - // 2. NaN shares_short + wrong-type optionals (counted on emitted row) - let mut doc2 = RawDocumentBuf::new(); - doc2.append(cstr!("symbol"), "NAN"); - doc2.append(cstr!("timestamp"), d_secs); - doc2.append(cstr!("sharesShort"), f64::NAN); - doc2.append(cstr!("netChange"), "123"); - doc2.append(cstr!("pctFloat"), true); - buf.extend_from_slice(doc2.as_bytes()); - - let mut rows = Vec::new(); - let stats = decode_ceo_shorts_buffer(&buf, &fields, |r| { - rows.push(( - r.key.to_string(), - r.shares_short, - r.net_change, - r.pct_float, - )); - }) - .expect("decode buffer"); - - assert_conservation(&stats); - assert_eq!(stats.docs_in, 2); - assert_eq!(stats.rows_out, 2); - assert_eq!(stats.nulled_wrong_type_net_change, 1); - assert_eq!(stats.nulled_wrong_type_pct_float, 1); - assert_eq!(rows[0].0, "NEG"); - assert_eq!(rows[0].1, -50.0); - assert_eq!(rows[0].2, None); - assert_eq!(rows[0].3, None); - assert_eq!(rows[1].0, "NAN"); - assert!(rows[1].1.is_nan()); - assert_eq!(rows[1].2, None); - assert_eq!(rows[1].3, None); -} - -#[test] -fn structural_bson_corruption_fails_closed_even_after_semantic_skip() { - let fields = default_fields(); - - // Build a doc with a bad key (semantic skip) followed by a corrupt trailing element type byte. - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("symbol"), ""); // would be skipped_empty_key - doc.append(cstr!("z"), 1_i32); - let mut bytes = doc.into_bytes(); - // Corrupt the element type byte of "z" (which is 0x10 = Int32) to an invalid BSON type 0x7e. - let z_pos = bytes - .windows(3) - .position(|w| w == [0x10, b'z', 0x00]) - .expect("locate z element"); - bytes[z_pos] = 0x7e; - - let err = decode_ceo_shorts_bytes(&bytes, &fields, |_| {}).unwrap_err(); - assert!( - matches!(err, BsonCeoShortsError::CorruptBson { offset: 0, .. }), - "expected CorruptBson at offset 0, got {err:?}" - ); - - // Also test second document in a buffer has accurate byte offset. - let mut good = RawDocumentBuf::new(); - good.append(cstr!("symbol"), "OK"); - good.append(cstr!("timestamp"), i64::from(day(2024, 3, 15)) * 86_400); - good.append(cstr!("sharesShort"), 100_i32); - let good_len = good.as_bytes().len() as u64; - - let mut combined = Vec::new(); - combined.extend_from_slice(good.as_bytes()); - combined.extend_from_slice(&bytes); - - let err = decode_ceo_shorts_buffer(&combined, &fields, |_| {}).unwrap_err(); - assert!( - matches!(err, BsonCeoShortsError::CorruptBson { offset, .. } if offset == good_len), - "expected CorruptBson at offset {good_len}, got {err:?}" - ); -} - -#[test] -fn framing_errors_return_typed_errors_with_offsets() { - let fields = default_fields(); - - // Truncated header (< 4 bytes) - let err = decode_ceo_shorts_buffer(&[0x10, 0x00], &fields, |_| {}).unwrap_err(); - assert!(matches!( - err, - BsonCeoShortsError::TruncatedDocument { - offset: 0, - remaining: 2, - declared_len: None - } - )); - - // Truncated body - let err = decode_ceo_shorts_buffer(&[20, 0, 0, 0, 0, 0], &fields, |_| {}).unwrap_err(); - assert!(matches!( - err, - BsonCeoShortsError::TruncatedDocument { - offset: 0, - remaining: 6, - declared_len: Some(20) - } - )); - - // Corrupt length (< 5) - let err = decode_ceo_shorts_buffer(&[3, 0, 0, 0, 0], &fields, |_| {}).unwrap_err(); - assert!(matches!( - err, - BsonCeoShortsError::CorruptDocumentLength { - offset: 0, - declared_len: 3 - } - )); - - // Trailing bytes on decode_ceo_shorts_bytes - let mut good = RawDocumentBuf::new(); - good.append(cstr!("symbol"), "OK"); - let mut extra = good.into_bytes(); - extra.push(0x00); - let err = decode_ceo_shorts_bytes(&extra, &fields, |_| {}).unwrap_err(); - assert!(matches!(err, BsonCeoShortsError::CorruptDocumentLength { .. })); -} - -#[test] -fn corrupt_unused_string_embedded_doc_and_array_fail_closed() { - use bson::raw::RawArrayBuf; - - let fields = default_fields(); - let d_secs = i64::from(day(2024, 3, 15)) * 86_400; - - // 1. Valid unused nested doc & array still decode cleanly. - let mut inner = RawDocumentBuf::new(); - inner.append(cstr!("tag"), "clean"); - let mut arr = RawArrayBuf::new(); - arr.push("ok"); - arr.push(inner.clone()); - - let mut valid_doc = RawDocumentBuf::new(); - valid_doc.append(cstr!("symbol"), "RY"); - valid_doc.append(cstr!("timestamp"), d_secs); - valid_doc.append(cstr!("sharesShort"), 100_i32); - valid_doc.append(cstr!("note"), "hello"); - valid_doc.append(cstr!("meta"), inner.clone()); - valid_doc.append(cstr!("tags"), arr); - - let mut emitted = 0usize; - let stats = decode_ceo_shorts_bytes(valid_doc.as_bytes(), &fields, |_| emitted += 1) - .expect("valid nested doc/array should decode"); - assert_conservation(&stats); - assert_eq!(emitted, 1); - - // 2. Invalid UTF-8 in an unused string field fails closed (0 rows emitted). - let mut bad_utf8_doc = RawDocumentBuf::new(); - bad_utf8_doc.append(cstr!("symbol"), "RY"); - bad_utf8_doc.append(cstr!("timestamp"), d_secs); - bad_utf8_doc.append(cstr!("sharesShort"), 100_i32); - bad_utf8_doc.append(cstr!("unusedNote"), "MARKER"); - let mut bytes = bad_utf8_doc.into_bytes(); - let pos = bytes - .windows(6) - .position(|w| w == b"MARKER") - .expect("locate MARKER"); - bytes[pos] = 0xff; - bytes[pos + 1] = 0xfe; - - let mut emitted = 0usize; - let err = decode_ceo_shorts_bytes(&bytes, &fields, |_| emitted += 1).unwrap_err(); - assert_eq!(emitted, 0); - assert!( - matches!(err, BsonCeoShortsError::CorruptBson { offset: 0, .. }), - "expected CorruptBson for invalid UTF-8 in unused string, got {err:?}" - ); - - // 3. Malformed element inside an unused embedded document fails closed. - let mut bad_inner = RawDocumentBuf::new(); - bad_inner.append(cstr!("nestedText"), "INNER!"); - let mut bad_nested_doc = RawDocumentBuf::new(); - bad_nested_doc.append(cstr!("symbol"), "RY"); - bad_nested_doc.append(cstr!("timestamp"), d_secs); - bad_nested_doc.append(cstr!("sharesShort"), 100_i32); - bad_nested_doc.append(cstr!("meta"), bad_inner); - let mut bytes = bad_nested_doc.into_bytes(); - let pos = bytes - .windows(6) - .position(|w| w == b"INNER!") - .expect("locate INNER!"); - bytes[pos] = 0xff; - - let mut emitted = 0usize; - let err = decode_ceo_shorts_bytes(&bytes, &fields, |_| emitted += 1).unwrap_err(); - assert_eq!(emitted, 0); - assert!( - matches!(err, BsonCeoShortsError::CorruptBson { offset: 0, .. }), - "expected CorruptBson for invalid UTF-8 in embedded doc, got {err:?}" - ); - - // 4. Corrupt element type byte inside an unused embedded document fails closed. - let mut bad_type_inner = RawDocumentBuf::new(); - bad_type_inner.append(cstr!("k"), 42_i32); - let mut bad_type_doc = RawDocumentBuf::new(); - bad_type_doc.append(cstr!("symbol"), "RY"); - bad_type_doc.append(cstr!("timestamp"), d_secs); - bad_type_doc.append(cstr!("sharesShort"), 100_i32); - bad_type_doc.append(cstr!("meta"), bad_type_inner); - let mut bytes = bad_type_doc.into_bytes(); - let k_pos = bytes - .windows(3) - .position(|w| w == [0x10, b'k', 0x00]) - .expect("locate nested int32 element"); - bytes[k_pos] = 0x7e; - - let err = decode_ceo_shorts_bytes(&bytes, &fields, |_| {}).unwrap_err(); - assert!( - matches!(err, BsonCeoShortsError::CorruptBson { offset: 0, .. }), - "expected CorruptBson for corrupt element type in embedded doc, got {err:?}" - ); - - // 5. Invalid UTF-8 inside an unused array element fails closed. - let mut bad_arr = RawArrayBuf::new(); - bad_arr.push("ARRVAL"); - let mut bad_arr_doc = RawDocumentBuf::new(); - bad_arr_doc.append(cstr!("symbol"), "RY"); - bad_arr_doc.append(cstr!("timestamp"), d_secs); - bad_arr_doc.append(cstr!("sharesShort"), 100_i32); - bad_arr_doc.append(cstr!("tags"), bad_arr); - let mut bytes = bad_arr_doc.into_bytes(); - let pos = bytes - .windows(6) - .position(|w| w == b"ARRVAL") - .expect("locate ARRVAL"); - bytes[pos] = 0xff; - - let err = decode_ceo_shorts_bytes(&bytes, &fields, |_| {}).unwrap_err(); - assert!( - matches!(err, BsonCeoShortsError::CorruptBson { offset: 0, .. }), - "expected CorruptBson for invalid UTF-8 in unused array, got {err:?}" - ); -} - -#[test] -fn corrupt_array_indexes_fail_closed() { - use bson::raw::RawArrayBuf; - - let fields = default_fields(); - let d_secs = i64::from(day(2024, 3, 15)) * 86_400; - - // Valid multi-element unused array succeeds. - let mut good_arr = RawArrayBuf::new(); - good_arr.push("first"); - good_arr.push("second"); - good_arr.push("third"); - let mut good_doc = RawDocumentBuf::new(); - good_doc.append(cstr!("symbol"), "RY"); - good_doc.append(cstr!("timestamp"), d_secs); - good_doc.append(cstr!("sharesShort"), 100_i32); - good_doc.append(cstr!("tags"), good_arr); - let mut rows = 0usize; - let stats = decode_ceo_shorts_bytes(good_doc.as_bytes(), &fields, |_| rows += 1).unwrap(); - assert_eq!(rows, 1); - assert_conservation(&stats); - - // Helper: build a doc with an unused 2-element array [10, 20] and mutate the array keys. - let build_two_elem_array_doc = || { - let mut arr = RawArrayBuf::new(); - arr.push(10_i32); - arr.push(20_i32); - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("symbol"), "RY"); - doc.append(cstr!("timestamp"), d_secs); - doc.append(cstr!("sharesShort"), 100_i32); - doc.append(cstr!("tags"), arr); - doc.into_bytes() - }; - - // 1. First index mutated from "0" to "8". - let mut bytes = build_two_elem_array_doc(); - let idx0 = bytes - .windows(3) - .position(|w| w == [0x10, b'0', 0x00]) - .expect("locate index 0 element"); - bytes[idx0 + 1] = b'8'; - let err = decode_ceo_shorts_bytes(&bytes, &fields, |_| {}).unwrap_err(); - assert!( - matches!(err, BsonCeoShortsError::CorruptBson { offset: 0, .. }), - "expected CorruptBson for non-zero starting array index, got {err:?}" - ); - - // 2. Repeated index ("0", "0"). - let mut bytes = build_two_elem_array_doc(); - let idx1 = bytes - .windows(3) - .position(|w| w == [0x10, b'1', 0x00]) - .expect("locate index 1 element"); - bytes[idx1 + 1] = b'0'; - let err = decode_ceo_shorts_bytes(&bytes, &fields, |_| {}).unwrap_err(); - assert!( - matches!(err, BsonCeoShortsError::CorruptBson { offset: 0, .. }), - "expected CorruptBson for repeated array index, got {err:?}" - ); - - // 3. Skipped/out-of-order index ("0", "2"). - let mut bytes = build_two_elem_array_doc(); - let idx1 = bytes - .windows(3) - .position(|w| w == [0x10, b'1', 0x00]) - .expect("locate index 1 element"); - bytes[idx1 + 1] = b'2'; - let err = decode_ceo_shorts_bytes(&bytes, &fields, |_| {}).unwrap_err(); - assert!( - matches!(err, BsonCeoShortsError::CorruptBson { offset: 0, .. }), - "expected CorruptBson for skipped array index, got {err:?}" - ); - - // 4. Non-numeric index ("a", "1"). - let mut bytes = build_two_elem_array_doc(); - let idx0 = bytes - .windows(3) - .position(|w| w == [0x10, b'0', 0x00]) - .expect("locate index 0 element"); - bytes[idx0 + 1] = b'a'; - let err = decode_ceo_shorts_bytes(&bytes, &fields, |_| {}).unwrap_err(); - assert!( - matches!(err, BsonCeoShortsError::CorruptBson { offset: 0, .. }), - "expected CorruptBson for non-numeric array index, got {err:?}" - ); - - // 5. Leading-zero index ("00") constructed as raw document bytes placed in an array field. - let mut fake_arr = RawDocumentBuf::new(); - fake_arr.append(cstr!("00"), 10_i32); - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("symbol"), "RY"); - doc.append(cstr!("timestamp"), d_secs); - doc.append(cstr!("sharesShort"), 100_i32); - doc.append(cstr!("tags"), fake_arr); - let mut bytes = doc.into_bytes(); - // Change field 'tags' element type from EmbeddedDocument (0x03) to Array (0x04). - let tags_pos = bytes - .windows(6) - .position(|w| w == [0x03, b't', b'a', b'g', b's', 0x00]) - .expect("locate tags document element"); - bytes[tags_pos] = 0x04; - let err = decode_ceo_shorts_bytes(&bytes, &fields, |_| {}).unwrap_err(); - assert!( - matches!(err, BsonCeoShortsError::CorruptBson { offset: 0, .. }), - "expected CorruptBson for leading-zero array index, got {err:?}" - ); -} diff --git a/tools/curate-etl/src/bson_eod_intraday.rs b/tools/curate-etl/src/bson_eod_intraday.rs deleted file mode 100644 index c8b9237b..00000000 --- a/tools/curate-etl/src/bson_eod_intraday.rs +++ /dev/null @@ -1,663 +0,0 @@ -//! Zero-copy raw BSON decoder for MongoDB `eodIntraday1M` documents (`M2.3d`). -//! -//! Decodes `&bson::RawDocument` slices in a single forward pass over `iter_elements()` into -//! borrowed [`RawEodIntradayBar`] views without allocating a `String` or `bson::Document` per row. -//! Callers convert borrowed views into [`crate::bars_1m::EodIntradayBar`] via a caller-supplied -//! key mapper (for example [`crate::provider_mapping::ProviderMappingTable::resolve`] or an -//! interned integer symbol ID), keeping the 3.40B-document path free of per-row `String` -//! allocations. -//! -//! # Empirical Field Contract & Cited Sources -//! -//! Field names and semantics are grounded in the repository's ingestion writer, historical reader, -//! and empirical data contract: -//! - `apps/stock/data-ingestion/src/handlers/eod/actions/intraday.ts:565-585` (`fetchIntraday` -//! writes `symbol`, `exchange`, `eodSearchCode`, `datetime`, `timestamp`, `gmtoffset`, `open`, -//! `high`, `low`, `close`, `volume`, `source` into `eodIntraday1M`, keyed by -//! `['timestamp', 'eodSearchCode']`) -//! - `libs/trading-runtime/src/historical-storage.ts:265-298` (`timestamp` is bar-start **UTC -//! Unix seconds**, not a local `datetime` label and not a publication / `known_at` time) -//! - `design/DATA-CONTRACTS.md` §1: `eodIntraday1M` (~3.40B docs) stores retroactively -//! split-adjusted OHLC and volume. This decoder passes those split-adjusted values through -//! untouched; split un-adjustment happens downstream in [`crate::bars_1m::build_bars_1m`]. -//! -//! # Accepted BSON Representations & Daily-Decoder Conventions -//! -//! Where a rule is ambiguous, this module follows [`crate::bson_eod_prices`]: -//! - `eodSearchCode`: BSON UTF-8 `String`, borrowed verbatim (never trimmed). Empty or -//! whitespace-only strings are rejected as [`BsonEodIntradayError::EmptyField`]; non-string -//! values (including BSON `Null`) are rejected as [`BsonEodIntradayError::WrongType`]. -//! - `timestamp`: bar-start UTC Unix seconds in BSON `Int32`, `Int64`, or finite integral `Double` -//! within `0..=i64::MAX / 1_000_000`, converted to UTC microseconds via checked multiplication -//! by `1_000_000`. Non-numeric types (including `Null` and `DateTime`) are rejected as -//! [`BsonEodIntradayError::WrongType`]; negative, fractional, non-finite, or microsecond-overflow -//! values are rejected as [`BsonEodIntradayError::InvalidTimestamp`]. -//! - `open`, `high`, `low`, `close`: BSON `Double`, `Int32`, or `Int64`; must be finite and -//! strictly positive (`> 0.0`). Non-numeric types (including `Null`) are rejected as -//! [`BsonEodIntradayError::WrongType`]; `NaN`, `±inf`, `0.0`, `-0.0`, and `< 0.0` are rejected -//! as [`BsonEodIntradayError::InvalidNumber`]. -//! - `volume`: BSON `Double`, `Int32`, or `Int64`; must be finite and `>= 0.0` (`-0.0` is -//! normalized to `+0.0`). Non-numeric types (including `Null`) are rejected as -//! [`BsonEodIntradayError::WrongType`]; `NaN`, `±inf`, and `< 0.0` are rejected as -//! [`BsonEodIntradayError::InvalidNumber`]. -//! - Unknown extra fields (`_id`, `symbol`, `exchange`, `datetime`, `gmtoffset`, `source`, nested -//! objects/arrays, etc.) are validated as borrowed `RawBsonRef` views (zero allocation) and -//! otherwise ignored, so malformed payloads (such as invalid UTF-8 in `datetime`) still surface -//! as [`BsonEodIntradayError::CorruptBson`]. -//! - Error precedence: retains the first semantic error while continuing to scan remaining -//! top-level elements so any malformed BSON bytes surface immediately as `CorruptBson`. - -use std::error::Error; -use std::fmt; - -use bson::raw::{cstr, RawBsonRef, RawDocument, RawElement}; -use bson::spec::ElementType; - -use crate::bars_1m::EodIntradayBar; -use crate::bson_eod_prices::{iter_raw_bson_docs, parse_single_raw_doc, BsonEodPriceError}; - -const MICROS_PER_SECOND: i64 = 1_000_000; -/// Largest whole Unix-second timestamp that fits in signed `i64` microseconds (`9_223_372_036_854`). -pub(crate) const MAX_TIMESTAMP_SECONDS: i64 = i64::MAX / MICROS_PER_SECOND; - -/// Borrowed zero-copy view of a single decoded `eodIntraday1M` BSON document. -/// -/// Borrows `eod_search_code` directly from the underlying `&RawDocument` byte slice. -/// `open`, `high`, `low`, `close`, and `volume` are passed through as the provider's -/// split-adjusted values so [`crate::bars_1m::build_bars_1m`] can apply split un-adjustment. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct RawEodIntradayBar<'a> { - pub eod_search_code: &'a str, - /// Bar start timestamp in UTC microseconds since the Unix epoch. - pub ts: i64, - pub open: f64, - pub high: f64, - pub low: f64, - pub close: f64, - pub volume: f64, -} - -impl<'a> RawEodIntradayBar<'a> { - /// Converts this borrowed view into an [`EodIntradayBar`] using a caller-supplied key - /// mapper. - /// - /// `map_key` receives `(eod_search_code, ts)` (provider code and UTC bar-start microseconds) - /// so callers can resolve an integer `listing_id` or interned key without allocating a per-row - /// `String`. - #[inline] - pub fn into_eod_intraday_bar(self, map_key: F) -> EodIntradayBar - where - F: FnOnce(&'a str, i64) -> K, - { - EodIntradayBar { - key: map_key(self.eod_search_code, self.ts), - ts: self.ts, - open: self.open, - high: self.high, - low: self.low, - close: self.close, - volume: self.volume, - } - } - - /// Fallible conversion into [`EodIntradayBar`] using a caller-supplied key resolver. - #[inline] - pub fn try_into_eod_intraday_bar(self, map_key: F) -> Option> - where - F: FnOnce(&'a str, i64) -> Option, - { - let key = map_key(self.eod_search_code, self.ts)?; - Some(EodIntradayBar { - key, - ts: self.ts, - open: self.open, - high: self.high, - low: self.low, - close: self.close, - volume: self.volume, - }) - } -} - -/// Typed errors returned while decoding raw `eodIntraday1M` BSON documents or length-prefixed -/// buffers. -/// -/// Every field-level error names the offending BSON field in both its structure and `Display` -/// output; framing errors carry byte offsets; no input path panics. -#[derive(Debug, Clone, PartialEq)] -pub enum BsonEodIntradayError { - /// A required field was absent from the document. - MissingField { field: &'static str }, - /// A required string field was empty or contained only whitespace. - EmptyField { field: &'static str }, - /// A required field had an unexpected BSON element type (including `Null`). - WrongType { - field: &'static str, - actual: ElementType, - }, - /// `timestamp` was negative, non-integral, non-finite, or overflowed `i64` microseconds. - InvalidTimestamp { field: &'static str }, - /// An OHLC field was non-finite or `<= 0.0`, or `volume` was non-finite or `< 0.0`. - InvalidNumber { field: &'static str, value: f64 }, - /// Buffer ended before a complete 4-byte length prefix or declared document body. - TruncatedDocument { - offset: usize, - remaining: usize, - declared_len: Option, - }, - /// Declared 4-byte little-endian BSON document length was `< 5` (or did not match a single - /// document slice). - CorruptDocumentLength { offset: usize, declared_len: i32 }, - /// Underlying BSON framing or element bytes were malformed. - CorruptBson { offset: usize, detail: String }, -} - -impl fmt::Display for BsonEodIntradayError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::MissingField { field } => { - write!(f, "eodIntraday1M BSON missing required field '{field}'") - } - Self::EmptyField { field } => { - write!( - f, - "eodIntraday1M BSON field '{field}' must not be empty or blank" - ) - } - Self::WrongType { field, actual } => { - write!( - f, - "eodIntraday1M BSON field '{field}' has unexpected BSON type {actual:?}" - ) - } - Self::InvalidTimestamp { field } => { - write!( - f, - "eodIntraday1M BSON field '{field}' is not a valid non-negative integral Unix-seconds timestamp within i64 microsecond range" - ) - } - Self::InvalidNumber { field, value } => { - if *field == "volume" { - write!( - f, - "eodIntraday1M BSON field '{field}' has invalid numeric value {value}: must be finite and >= 0" - ) - } else { - write!( - f, - "eodIntraday1M BSON field '{field}' has invalid numeric value {value}: must be finite and > 0" - ) - } - } - Self::TruncatedDocument { - offset, - remaining, - declared_len, - } => match declared_len { - Some(len) => write!( - f, - "truncated BSON document at byte offset {offset}: declared length {len} exceeds remaining {remaining} bytes" - ), - None => write!( - f, - "truncated BSON document header at byte offset {offset}: only {remaining} bytes remaining" - ), - }, - Self::CorruptDocumentLength { - offset, - declared_len, - } => write!( - f, - "corrupt BSON document length {declared_len} at byte offset {offset}" - ), - Self::CorruptBson { offset, detail } => { - write!(f, "corrupt BSON bytes at byte offset {offset}: {detail}") - } - } - } -} - -impl Error for BsonEodIntradayError {} - -#[inline] -fn map_framing_error(err: BsonEodPriceError) -> BsonEodIntradayError { - match err { - BsonEodPriceError::TruncatedDocument { - offset, - remaining, - declared_len, - } => BsonEodIntradayError::TruncatedDocument { - offset, - remaining, - declared_len, - }, - BsonEodPriceError::CorruptDocumentLength { - offset, - declared_len, - } => BsonEodIntradayError::CorruptDocumentLength { - offset, - declared_len, - }, - BsonEodPriceError::CorruptBson { offset, detail } => { - BsonEodIntradayError::CorruptBson { offset, detail } - } - BsonEodPriceError::MissingField { field } => BsonEodIntradayError::MissingField { field }, - BsonEodPriceError::EmptyField { field } => BsonEodIntradayError::EmptyField { field }, - BsonEodPriceError::WrongType { field, actual } => { - BsonEodIntradayError::WrongType { field, actual } - } - BsonEodPriceError::MalformedDate { field } => { - BsonEodIntradayError::InvalidTimestamp { field } - } - BsonEodPriceError::InvalidNumber { field, value } => { - BsonEodIntradayError::InvalidNumber { field, value } - } - } -} - -/// Per-batch decode and rejection accounting for [`decode_eod_intraday_buffer`]. -/// -/// Conservation invariant: `rows_decoded + rejected_total() == docs_seen`. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct BsonEodIntradayDecodeStats { - pub docs_seen: usize, - pub rows_decoded: usize, - pub rejected_missing_field: usize, - pub rejected_empty_field: usize, - pub rejected_wrong_type: usize, - pub rejected_invalid_timestamp: usize, - pub rejected_invalid_number: usize, - pub rejected_corrupt_document: usize, -} - -impl BsonEodIntradayDecodeStats { - /// Total number of rejected documents across all error categories. - #[inline] - pub fn rejected_total(&self) -> usize { - self.rejected_missing_field - + self.rejected_empty_field - + self.rejected_wrong_type - + self.rejected_invalid_timestamp - + self.rejected_invalid_number - + self.rejected_corrupt_document - } - - /// Increments the rejection counter corresponding to `err`. - #[inline] - pub fn record_error(&mut self, err: &BsonEodIntradayError) { - match err { - BsonEodIntradayError::MissingField { .. } => self.rejected_missing_field += 1, - BsonEodIntradayError::EmptyField { .. } => self.rejected_empty_field += 1, - BsonEodIntradayError::WrongType { .. } => self.rejected_wrong_type += 1, - BsonEodIntradayError::InvalidTimestamp { .. } => self.rejected_invalid_timestamp += 1, - BsonEodIntradayError::InvalidNumber { .. } => self.rejected_invalid_number += 1, - BsonEodIntradayError::TruncatedDocument { .. } - | BsonEodIntradayError::CorruptDocumentLength { .. } - | BsonEodIntradayError::CorruptBson { .. } => self.rejected_corrupt_document += 1, - } - } - - /// Accumulates counters from another batch into `self`. - #[inline] - pub fn merge(&mut self, other: &Self) { - self.docs_seen += other.docs_seen; - self.rows_decoded += other.rows_decoded; - self.rejected_missing_field += other.rejected_missing_field; - self.rejected_empty_field += other.rejected_empty_field; - self.rejected_wrong_type += other.rejected_wrong_type; - self.rejected_invalid_timestamp += other.rejected_invalid_timestamp; - self.rejected_invalid_number += other.rejected_invalid_number; - self.rejected_corrupt_document += other.rejected_corrupt_document; - } -} - -impl std::ops::AddAssign for BsonEodIntradayDecodeStats { - #[inline] - fn add_assign(&mut self, rhs: Self) { - self.merge(&rhs); - } -} - -#[inline] -fn decode_element_value<'a>( - field: &'static str, - elem: RawElement<'a>, - offset: usize, -) -> Result, BsonEodIntradayError> { - elem.value().map_err(|err| BsonEodIntradayError::CorruptBson { - offset, - detail: format!("field '{field}': {err}"), - }) -} - -#[inline] -fn decode_timestamp_seconds_to_micros(val: RawBsonRef<'_>) -> Result { - let secs = match val { - RawBsonRef::Int32(v) => { - if v < 0 { - return Err(BsonEodIntradayError::InvalidTimestamp { field: "timestamp" }); - } - i64::from(v) - } - RawBsonRef::Int64(v) => { - if v < 0 { - return Err(BsonEodIntradayError::InvalidTimestamp { field: "timestamp" }); - } - v - } - RawBsonRef::Double(v) => { - // `MAX_TIMESTAMP_SECONDS` (9_223_372_036_854 < 2^44) is well within `f64`'s exact - // 53-bit integer range, so both the upper bound and the cast are exact. - if !v.is_finite() - || v < 0.0 - || v.fract() != 0.0 - || v > MAX_TIMESTAMP_SECONDS as f64 - { - return Err(BsonEodIntradayError::InvalidTimestamp { field: "timestamp" }); - } - v as i64 - } - other => { - return Err(BsonEodIntradayError::WrongType { - field: "timestamp", - actual: other.element_type(), - }); - } - }; - - secs.checked_mul(MICROS_PER_SECOND) - .ok_or(BsonEodIntradayError::InvalidTimestamp { field: "timestamp" }) -} - -#[inline] -fn decode_positive_number( - field: &'static str, - val: RawBsonRef<'_>, -) -> Result { - match val { - RawBsonRef::Double(v) => { - if !v.is_finite() || v <= 0.0 { - return Err(BsonEodIntradayError::InvalidNumber { field, value: v }); - } - Ok(v) - } - RawBsonRef::Int32(v) => { - if v <= 0 { - return Err(BsonEodIntradayError::InvalidNumber { - field, - value: f64::from(v), - }); - } - Ok(f64::from(v)) - } - RawBsonRef::Int64(v) => { - if v <= 0 { - return Err(BsonEodIntradayError::InvalidNumber { - field, - value: v as f64, - }); - } - Ok(v as f64) - } - other => Err(BsonEodIntradayError::WrongType { - field, - actual: other.element_type(), - }), - } -} - -#[inline] -fn decode_non_negative_number( - field: &'static str, - val: RawBsonRef<'_>, -) -> Result { - match val { - RawBsonRef::Double(v) => { - if !v.is_finite() || v < 0.0 { - return Err(BsonEodIntradayError::InvalidNumber { field, value: v }); - } - if v == 0.0 { - Ok(0.0) - } else { - Ok(v) - } - } - RawBsonRef::Int32(v) => { - if v < 0 { - return Err(BsonEodIntradayError::InvalidNumber { - field, - value: f64::from(v), - }); - } - Ok(f64::from(v)) - } - RawBsonRef::Int64(v) => { - if v < 0 { - return Err(BsonEodIntradayError::InvalidNumber { - field, - value: v as f64, - }); - } - Ok(v as f64) - } - other => Err(BsonEodIntradayError::WrongType { - field, - actual: other.element_type(), - }), - } -} - -fn decode_eod_intraday_doc_at<'a>( - doc: &'a RawDocument, - offset: usize, -) -> Result, BsonEodIntradayError> { - let mut eod_search_code: Option<&'a str> = None; - let mut ts: Option = None; - let mut open: Option = None; - let mut high: Option = None; - let mut low: Option = None; - let mut close: Option = None; - let mut volume: Option = None; - let mut first_semantic_err: Option = None; - - for elem_res in doc.iter_elements() { - let elem = elem_res.map_err(|err| BsonEodIntradayError::CorruptBson { - offset, - detail: err.to_string(), - })?; - let key = elem.key(); - - if key == cstr!("eodSearchCode") { - match decode_element_value("eodSearchCode", elem, offset)? { - RawBsonRef::String(s) => { - if s.trim().is_empty() { - if first_semantic_err.is_none() { - first_semantic_err = Some(BsonEodIntradayError::EmptyField { - field: "eodSearchCode", - }); - } - } else { - eod_search_code = Some(s); - } - } - other => { - if first_semantic_err.is_none() { - first_semantic_err = Some(BsonEodIntradayError::WrongType { - field: "eodSearchCode", - actual: other.element_type(), - }); - } - } - } - } else if key == cstr!("timestamp") { - let val = decode_element_value("timestamp", elem, offset)?; - match decode_timestamp_seconds_to_micros(val) { - Ok(micros) => ts = Some(micros), - Err(err) => { - if first_semantic_err.is_none() { - first_semantic_err = Some(err); - } - } - } - } else if key == cstr!("open") { - let val = decode_element_value("open", elem, offset)?; - match decode_positive_number("open", val) { - Ok(v) => open = Some(v), - Err(err) => { - if first_semantic_err.is_none() { - first_semantic_err = Some(err); - } - } - } - } else if key == cstr!("high") { - let val = decode_element_value("high", elem, offset)?; - match decode_positive_number("high", val) { - Ok(v) => high = Some(v), - Err(err) => { - if first_semantic_err.is_none() { - first_semantic_err = Some(err); - } - } - } - } else if key == cstr!("low") { - let val = decode_element_value("low", elem, offset)?; - match decode_positive_number("low", val) { - Ok(v) => low = Some(v), - Err(err) => { - if first_semantic_err.is_none() { - first_semantic_err = Some(err); - } - } - } - } else if key == cstr!("close") { - let val = decode_element_value("close", elem, offset)?; - match decode_positive_number("close", val) { - Ok(v) => close = Some(v), - Err(err) => { - if first_semantic_err.is_none() { - first_semantic_err = Some(err); - } - } - } - } else if key == cstr!("volume") { - let val = decode_element_value("volume", elem, offset)?; - match decode_non_negative_number("volume", val) { - Ok(v) => volume = Some(v), - Err(err) => { - if first_semantic_err.is_none() { - first_semantic_err = Some(err); - } - } - } - } else { - // Validate skipped top-level payloads via borrowed `RawBsonRef` views (zero - // allocation) so malformed bytes (e.g. invalid UTF-8 in `datetime`) still reject the - // document as `CorruptBson` at its frame offset. - elem.value().map_err(|err| BsonEodIntradayError::CorruptBson { - offset, - detail: format!("field '{}': {err}", key.as_str()), - })?; - } - } - - if let Some(err) = first_semantic_err { - return Err(err); - } - - let Some(eod_search_code) = eod_search_code else { - return Err(BsonEodIntradayError::MissingField { - field: "eodSearchCode", - }); - }; - let Some(ts) = ts else { - return Err(BsonEodIntradayError::MissingField { field: "timestamp" }); - }; - let Some(open) = open else { - return Err(BsonEodIntradayError::MissingField { field: "open" }); - }; - let Some(high) = high else { - return Err(BsonEodIntradayError::MissingField { field: "high" }); - }; - let Some(low) = low else { - return Err(BsonEodIntradayError::MissingField { field: "low" }); - }; - let Some(close) = close else { - return Err(BsonEodIntradayError::MissingField { field: "close" }); - }; - let Some(volume) = volume else { - return Err(BsonEodIntradayError::MissingField { field: "volume" }); - }; - - Ok(RawEodIntradayBar { - eod_search_code, - ts, - open, - high, - low, - close, - volume, - }) -} - -/// Decodes a single `&RawDocument` representing an `eodIntraday1M` MongoDB document in one forward -/// pass without allocating a `String` or owned `bson::Document`. -#[inline] -pub fn decode_eod_intraday_doc<'a>( - doc: &'a RawDocument, -) -> Result, BsonEodIntradayError> { - decode_eod_intraday_doc_at(doc, 0) -} - -/// Decodes a single length-prefixed raw BSON document byte slice into a borrowed -/// [`RawEodIntradayBar`]. -pub fn decode_eod_intraday_bytes<'a>( - bytes: &'a [u8], -) -> Result, BsonEodIntradayError> { - let doc = parse_single_raw_doc(bytes).map_err(map_framing_error)?; - decode_eod_intraday_doc_at(doc, 0) -} - -/// Streams a concatenated length-prefixed BSON buffer through [`decode_eod_intraday_doc`], -/// invoking `on_bar` for every valid document and `on_error(byte_offset, err)` for every rejected -/// document without aborting the stream on per-document errors. -/// -/// Always maintains `stats.rows_decoded + stats.rejected_total() == stats.docs_seen`. -pub fn decode_eod_intraday_buffer<'a, F, E>( - buf: &'a [u8], - mut on_bar: F, - mut on_error: E, -) -> BsonEodIntradayDecodeStats -where - F: FnMut(RawEodIntradayBar<'a>), - E: FnMut(usize, BsonEodIntradayError), -{ - let mut stats = BsonEodIntradayDecodeStats::default(); - let mut iter = iter_raw_bson_docs(buf); - - while let Some(item) = iter.next_with_offset() { - stats.docs_seen += 1; - match item { - Ok((doc_offset, doc)) => match decode_eod_intraday_doc_at(doc, doc_offset) { - Ok(bar) => { - stats.rows_decoded += 1; - on_bar(bar); - } - Err(err) => { - stats.record_error(&err); - on_error(doc_offset, err); - } - }, - Err((doc_offset, err)) => { - let mapped = map_framing_error(err); - stats.record_error(&mapped); - on_error(doc_offset, mapped); - } - } - } - - stats -} - -#[cfg(test)] -#[path = "bson_eod_intraday_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/bson_eod_intraday_tests.rs b/tools/curate-etl/src/bson_eod_intraday_tests.rs deleted file mode 100644 index 6374d2b8..00000000 --- a/tools/curate-etl/src/bson_eod_intraday_tests.rs +++ /dev/null @@ -1,896 +0,0 @@ -use bson::oid::ObjectId; -use bson::raw::{cstr, RawArrayBuf, RawBsonRef, RawDocumentBuf}; -use bson::spec::ElementType; -use bson::DateTime; - -use super::*; -use crate::bars_1m::{build_bars_1m, IntradaySession, BARS_1M_SOURCE_EOD}; -use crate::split::{ymd_to_epoch_days, SplitEvent, SplitTable}; - -fn day(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).unwrap() -} - -fn make_valid_doc( - code: &str, - timestamp_sec: i64, - open: f64, - high: f64, - low: f64, - close: f64, - volume: f64, -) -> RawDocumentBuf { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), code); - doc.append(cstr!("timestamp"), timestamp_sec); - doc.append(cstr!("open"), open); - doc.append(cstr!("high"), high); - doc.append(cstr!("low"), low); - doc.append(cstr!("close"), close); - doc.append(cstr!("volume"), volume); - doc -} - -fn make_doc_with_timestamp(timestamp: RawBsonRef<'_>) -> RawDocumentBuf { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), "NVDA.US"); - doc.append(cstr!("timestamp"), timestamp); - doc.append(cstr!("open"), 120.15_f64); - doc.append(cstr!("high"), 120.42_f64); - doc.append(cstr!("low"), 120.05_f64); - doc.append(cstr!("close"), 120.38_f64); - doc.append(cstr!("volume"), 842_500.0_f64); - doc -} - -fn assert_rel_eq(actual: f64, expected: f64, rel_tol: f64) { - let diff = (actual - expected).abs(); - let scale = expected.abs().max(1.0); - assert!( - diff <= rel_tol * scale, - "actual={actual} expected={expected} diff={diff} rel_tol={rel_tol}" - ); -} - -#[test] -fn decodes_nvda_fixture_across_int32_int64_double_timestamps_and_ignores_metadata() { - const TS_SEC: i32 = 1_717_767_000; - const EXPECTED_TS_MICROS: i64 = 1_717_767_000_000_000; - - let mut nested = RawDocumentBuf::new(); - nested.append(cstr!("provider"), "eodhd"); - nested.append(cstr!("interval"), "1m"); - - let mut tags = RawArrayBuf::new(); - tags.push("us"); - tags.push("intraday"); - - let mut doc_i32 = RawDocumentBuf::new(); - doc_i32.append( - cstr!("_id"), - ObjectId::from_bytes([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]), - ); - doc_i32.append(cstr!("symbol"), "NVDA"); - doc_i32.append(cstr!("exchange"), "US"); - doc_i32.append(cstr!("eodSearchCode"), "NVDA.US"); - doc_i32.append(cstr!("datetime"), "2024-06-07 13:30:00"); - doc_i32.append(cstr!("timestamp"), TS_SEC); - doc_i32.append(cstr!("gmtoffset"), 0_i32); - doc_i32.append(cstr!("open"), 119.77_f64); - doc_i32.append(cstr!("high"), 121.692_f64); - doc_i32.append(cstr!("low"), 118.022_f64); - doc_i32.append(cstr!("close"), 120.888_f64); - doc_i32.append(cstr!("volume"), 412_390.0_f64); - doc_i32.append(cstr!("source"), "eod"); - doc_i32.append(cstr!("meta"), RawBsonRef::Document(nested.as_ref())); - doc_i32.append(cstr!("tags"), RawBsonRef::Array(tags.as_ref())); - - let bar_i32 = decode_eod_intraday_doc(&doc_i32).unwrap(); - assert_eq!(bar_i32.eod_search_code, "NVDA.US"); - assert_eq!(bar_i32.ts, EXPECTED_TS_MICROS); - assert_eq!(bar_i32.open.to_bits(), 119.77_f64.to_bits()); - assert_eq!(bar_i32.high.to_bits(), 121.692_f64.to_bits()); - assert_eq!(bar_i32.low.to_bits(), 118.022_f64.to_bits()); - assert_eq!(bar_i32.close.to_bits(), 120.888_f64.to_bits()); - assert_eq!(bar_i32.volume.to_bits(), 412_390.0_f64.to_bits()); - - // decode_eod_intraday_bytes matches decode_eod_intraday_doc bit-for-bit. - let from_bytes = decode_eod_intraday_bytes(doc_i32.as_bytes()).unwrap(); - assert_eq!(from_bytes, bar_i32); - - // Same document with timestamp as Int64 and as integral Double decodes identically. - let mut doc_i64 = RawDocumentBuf::new(); - doc_i64.append(cstr!("eodSearchCode"), "NVDA.US"); - doc_i64.append(cstr!("timestamp"), i64::from(TS_SEC)); - doc_i64.append(cstr!("open"), 119.77_f64); - doc_i64.append(cstr!("high"), 121.692_f64); - doc_i64.append(cstr!("low"), 118.022_f64); - doc_i64.append(cstr!("close"), 120.888_f64); - doc_i64.append(cstr!("volume"), 412_390.0_f64); - - let mut doc_f64 = RawDocumentBuf::new(); - doc_f64.append(cstr!("eodSearchCode"), "NVDA.US"); - doc_f64.append(cstr!("timestamp"), f64::from(TS_SEC)); - doc_f64.append(cstr!("open"), 119.77_f64); - doc_f64.append(cstr!("high"), 121.692_f64); - doc_f64.append(cstr!("low"), 118.022_f64); - doc_f64.append(cstr!("close"), 120.888_f64); - doc_f64.append(cstr!("volume"), 412_390.0_f64); - - let bar_i64 = decode_eod_intraday_doc(&doc_i64).unwrap(); - let bar_f64 = decode_eod_intraday_doc(&doc_f64).unwrap(); - assert_eq!(bar_i64, bar_i32); - assert_eq!(bar_f64, bar_i32); - - // Verify into_eod_intraday_bar and try_into_eod_intraday_bar pass exact (code, ts). - let mut seen_into: Option<(&str, i64)> = None; - let mapped = bar_i32.into_eod_intraday_bar(|code, ts| { - seen_into = Some((code, ts)); - 42_u64 - }); - assert_eq!(seen_into, Some(("NVDA.US", EXPECTED_TS_MICROS))); - assert_eq!(mapped.key, 42_u64); - assert_eq!(mapped.ts, EXPECTED_TS_MICROS); - assert_eq!(mapped.close.to_bits(), 120.888_f64.to_bits()); - - let mut seen_try_some: Option<(&str, i64)> = None; - let try_some = bar_i32.try_into_eod_intraday_bar(|code, ts| { - seen_try_some = Some((code, ts)); - Some(99_u64) - }); - assert_eq!(seen_try_some, Some(("NVDA.US", EXPECTED_TS_MICROS))); - assert_eq!(try_some.unwrap().key, 99_u64); - - let try_none: Option> = bar_i32.try_into_eod_intraday_bar(|code, ts| { - assert_eq!(code, "NVDA.US"); - assert_eq!(ts, EXPECTED_TS_MICROS); - None - }); - assert!(try_none.is_none()); -} - -#[test] -fn borrows_eod_search_code_zero_copy_from_input_buffer() { - let doc = make_valid_doc("NVDA.US", 1_717_767_000, 120.0, 121.0, 119.5, 120.5, 1000.0); - let bytes = doc.as_bytes(); - let buf_start = bytes.as_ptr() as usize; - let buf_end = buf_start + bytes.len(); - - let bar = decode_eod_intraday_bytes(bytes).unwrap(); - let code_start = bar.eod_search_code.as_ptr() as usize; - let code_end = code_start + bar.eod_search_code.len(); - assert!( - code_start >= buf_start && code_end <= buf_end, - "expected eod_search_code pointer {code_start:#x}..{code_end:#x} inside input buffer {buf_start:#x}..{buf_end:#x}" - ); - assert_eq!(bar.eod_search_code, "NVDA.US"); -} - -#[test] -fn accepts_mixed_numeric_types_zero_volume_and_timestamp_boundaries() { - let mut mixed = RawDocumentBuf::new(); - mixed.append(cstr!("eodSearchCode"), "SHOP.TO"); - mixed.append(cstr!("timestamp"), 0_i32); - mixed.append(cstr!("open"), 100_i32); - mixed.append(cstr!("high"), 105_i64); - mixed.append(cstr!("low"), 99.5_f64); - mixed.append(cstr!("close"), 104_i32); - mixed.append(cstr!("volume"), 5_000_000_000_i64); - - let bar = decode_eod_intraday_doc(&mixed).unwrap(); - assert_eq!(bar.eod_search_code, "SHOP.TO"); - assert_eq!(bar.ts, 0); - assert_eq!(bar.open.to_bits(), 100.0_f64.to_bits()); - assert_eq!(bar.high.to_bits(), 105.0_f64.to_bits()); - assert_eq!(bar.low.to_bits(), 99.5_f64.to_bits()); - assert_eq!(bar.close.to_bits(), 104.0_f64.to_bits()); - assert_eq!(bar.volume.to_bits(), 5_000_000_000.0_f64.to_bits()); - - // Epoch zero in Int32, Int64, Double (+0.0 and -0.0). - for zero_ts in [ - RawBsonRef::Int32(0), - RawBsonRef::Int64(0), - RawBsonRef::Double(0.0), - RawBsonRef::Double(-0.0), - ] { - let doc = make_doc_with_timestamp(zero_ts); - let decoded = decode_eod_intraday_doc(&doc).unwrap(); - assert_eq!(decoded.ts, 0); - } - - // Largest accepted whole second in Int64 and Double. - let expected_max_micros = MAX_TIMESTAMP_SECONDS * 1_000_000; - for max_ts in [ - RawBsonRef::Int64(MAX_TIMESTAMP_SECONDS), - RawBsonRef::Double(MAX_TIMESTAMP_SECONDS as f64), - ] { - let doc = make_doc_with_timestamp(max_ts); - let decoded = decode_eod_intraday_doc(&doc).unwrap(); - assert_eq!(decoded.ts, expected_max_micros); - } - - // Zero volume in Double (+0.0, -0.0), Int32 (0), Int64 (0) normalizes to +0.0. - for zero_vol in [ - RawBsonRef::Double(0.0), - RawBsonRef::Double(-0.0), - RawBsonRef::Int32(0), - RawBsonRef::Int64(0), - ] { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), "NVDA.US"); - doc.append(cstr!("timestamp"), 1_717_767_000_i64); - doc.append(cstr!("open"), 10.0_f64); - doc.append(cstr!("high"), 11.0_f64); - doc.append(cstr!("low"), 9.5_f64); - doc.append(cstr!("close"), 10.5_f64); - doc.append(cstr!("volume"), zero_vol); - - let decoded = decode_eod_intraday_doc(&doc).unwrap(); - assert_eq!(decoded.volume.to_bits(), 0.0_f64.to_bits()); - } -} - -#[test] -fn rejects_invalid_eod_search_code_variants_with_matching_stats() { - // Missing eodSearchCode - let mut missing = RawDocumentBuf::new(); - missing.append(cstr!("timestamp"), 1_717_767_000_i64); - missing.append(cstr!("open"), 10.0_f64); - missing.append(cstr!("high"), 11.0_f64); - missing.append(cstr!("low"), 9.0_f64); - missing.append(cstr!("close"), 10.5_f64); - missing.append(cstr!("volume"), 100.0_f64); - let err = decode_eod_intraday_doc(&missing).unwrap_err(); - assert_eq!( - err, - BsonEodIntradayError::MissingField { - field: "eodSearchCode" - } - ); - let mut stats = BsonEodIntradayDecodeStats::default(); - stats.record_error(&err); - assert_eq!(stats.rejected_missing_field, 1); - assert_eq!(stats.rejected_total(), 1); - - // Empty and whitespace-only keys - for blank in ["", " ", "\t\n\r "] { - let doc = make_valid_doc(blank, 1_717_767_000, 10.0, 11.0, 9.0, 10.5, 100.0); - let err = decode_eod_intraday_doc(&doc).unwrap_err(); - assert_eq!( - err, - BsonEodIntradayError::EmptyField { - field: "eodSearchCode" - } - ); - let mut s = BsonEodIntradayDecodeStats::default(); - s.record_error(&err); - assert_eq!(s.rejected_empty_field, 1); - assert_eq!(s.rejected_total(), 1); - } - - // Wrong BSON types for eodSearchCode - let wrong_types: [(RawBsonRef<'_>, ElementType); 3] = [ - (RawBsonRef::Null, ElementType::Null), - (RawBsonRef::Int32(123), ElementType::Int32), - (RawBsonRef::Boolean(true), ElementType::Boolean), - ]; - for (val, expected_type) in wrong_types { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), val); - doc.append(cstr!("timestamp"), 1_717_767_000_i64); - doc.append(cstr!("open"), 10.0_f64); - doc.append(cstr!("high"), 11.0_f64); - doc.append(cstr!("low"), 9.0_f64); - doc.append(cstr!("close"), 10.5_f64); - doc.append(cstr!("volume"), 100.0_f64); - let err = decode_eod_intraday_doc(&doc).unwrap_err(); - assert_eq!( - err, - BsonEodIntradayError::WrongType { - field: "eodSearchCode", - actual: expected_type, - } - ); - let mut s = BsonEodIntradayDecodeStats::default(); - s.record_error(&err); - assert_eq!(s.rejected_wrong_type, 1); - assert_eq!(s.rejected_total(), 1); - } -} - -#[test] -fn rejects_invalid_timestamp_variants_with_matching_stats() { - // Missing timestamp - let mut missing = RawDocumentBuf::new(); - missing.append(cstr!("eodSearchCode"), "NVDA.US"); - missing.append(cstr!("open"), 10.0_f64); - missing.append(cstr!("high"), 11.0_f64); - missing.append(cstr!("low"), 9.0_f64); - missing.append(cstr!("close"), 10.5_f64); - missing.append(cstr!("volume"), 100.0_f64); - let err = decode_eod_intraday_doc(&missing).unwrap_err(); - assert_eq!(err, BsonEodIntradayError::MissingField { field: "timestamp" }); - let mut stats = BsonEodIntradayDecodeStats::default(); - stats.record_error(&err); - assert_eq!(stats.rejected_missing_field, 1); - assert_eq!(stats.rejected_total(), 1); - - // Wrong BSON types for timestamp - let wrong_types: [(RawBsonRef<'_>, ElementType); 4] = [ - (RawBsonRef::Null, ElementType::Null), - (RawBsonRef::String("1717767000"), ElementType::String), - ( - RawBsonRef::DateTime(DateTime::from_millis(1_717_767_000_000)), - ElementType::DateTime, - ), - (RawBsonRef::Boolean(false), ElementType::Boolean), - ]; - for (val, expected_type) in wrong_types { - let doc = make_doc_with_timestamp(val); - let err = decode_eod_intraday_doc(&doc).unwrap_err(); - assert_eq!( - err, - BsonEodIntradayError::WrongType { - field: "timestamp", - actual: expected_type, - } - ); - let mut s = BsonEodIntradayDecodeStats::default(); - s.record_error(&err); - assert_eq!(s.rejected_wrong_type, 1); - assert_eq!(s.rejected_total(), 1); - } - - // Invalid numeric timestamps: fractional, NaN, inf, -inf, negative, overflowing - let invalid_timestamps: [RawBsonRef<'_>; 11] = [ - RawBsonRef::Double(1_717_767_000.5), - RawBsonRef::Double(0.25), - RawBsonRef::Double(f64::NAN), - RawBsonRef::Double(f64::INFINITY), - RawBsonRef::Double(f64::NEG_INFINITY), - RawBsonRef::Int32(-1), - RawBsonRef::Int64(-1), - RawBsonRef::Double(-1.0), - RawBsonRef::Int64(MAX_TIMESTAMP_SECONDS + 1), - RawBsonRef::Int64(i64::MAX), - RawBsonRef::Double((MAX_TIMESTAMP_SECONDS + 1) as f64), - ]; - for bad_ts in invalid_timestamps { - let doc = make_doc_with_timestamp(bad_ts); - let err = decode_eod_intraday_doc(&doc).unwrap_err(); - assert_eq!( - err, - BsonEodIntradayError::InvalidTimestamp { field: "timestamp" } - ); - let mut s = BsonEodIntradayDecodeStats::default(); - s.record_error(&err); - assert_eq!(s.rejected_invalid_timestamp, 1); - assert_eq!(s.rejected_total(), 1); - } -} - -#[test] -fn rejects_invalid_ohlc_and_volume_variants_with_matching_stats() { - let ohlc_fields = ["open", "high", "low", "close"]; - - for target in ohlc_fields { - // Missing field - let mut missing = RawDocumentBuf::new(); - missing.append(cstr!("eodSearchCode"), "NVDA.US"); - missing.append(cstr!("timestamp"), 1_717_767_000_i64); - for (f, key) in [ - ("open", cstr!("open")), - ("high", cstr!("high")), - ("low", cstr!("low")), - ("close", cstr!("close")), - ("volume", cstr!("volume")), - ] { - if f != target { - missing.append(key, 10.0_f64); - } - } - let err = decode_eod_intraday_doc(&missing).unwrap_err(); - assert_eq!(err, BsonEodIntradayError::MissingField { field: target }); - let mut s = BsonEodIntradayDecodeStats::default(); - s.record_error(&err); - assert_eq!(s.rejected_missing_field, 1); - assert_eq!(s.rejected_total(), 1); - - let build_with_field = |val: RawBsonRef<'_>| { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), "NVDA.US"); - doc.append(cstr!("timestamp"), 1_717_767_000_i64); - for (name, key) in [ - ("open", cstr!("open")), - ("high", cstr!("high")), - ("low", cstr!("low")), - ("close", cstr!("close")), - ("volume", cstr!("volume")), - ] { - if name == target { - doc.append(key, val); - } else { - doc.append(key, 10.0_f64); - } - } - doc - }; - - // Null and wrong types -> WrongType - for (val, expected_type) in [ - (RawBsonRef::Null, ElementType::Null), - (RawBsonRef::String("10.0"), ElementType::String), - (RawBsonRef::Boolean(true), ElementType::Boolean), - ] { - let doc = build_with_field(val); - let err = decode_eod_intraday_doc(&doc).unwrap_err(); - assert_eq!( - err, - BsonEodIntradayError::WrongType { - field: target, - actual: expected_type, - } - ); - let mut st = BsonEodIntradayDecodeStats::default(); - st.record_error(&err); - assert_eq!(st.rejected_wrong_type, 1); - assert_eq!(st.rejected_total(), 1); - } - - // Non-finite, zero, and negative -> InvalidNumber - for bad_num in [ - RawBsonRef::Double(f64::NAN), - RawBsonRef::Double(f64::INFINITY), - RawBsonRef::Double(f64::NEG_INFINITY), - RawBsonRef::Double(0.0), - RawBsonRef::Double(-0.0), - RawBsonRef::Double(-1.25), - RawBsonRef::Int32(0), - RawBsonRef::Int32(-5), - RawBsonRef::Int64(0), - RawBsonRef::Int64(-5), - ] { - let doc = build_with_field(bad_num); - let err = decode_eod_intraday_doc(&doc).unwrap_err(); - match &err { - BsonEodIntradayError::InvalidNumber { field, .. } => assert_eq!(*field, target), - other => panic!("expected InvalidNumber for {target}, got {other:?}"), - } - let mut st = BsonEodIntradayDecodeStats::default(); - st.record_error(&err); - assert_eq!(st.rejected_invalid_number, 1); - assert_eq!(st.rejected_total(), 1); - } - } - - // Volume: missing, Null/wrong-type, negative/NaN/inf - let mut missing_vol = RawDocumentBuf::new(); - missing_vol.append(cstr!("eodSearchCode"), "NVDA.US"); - missing_vol.append(cstr!("timestamp"), 1_717_767_000_i64); - missing_vol.append(cstr!("open"), 10.0_f64); - missing_vol.append(cstr!("high"), 11.0_f64); - missing_vol.append(cstr!("low"), 9.0_f64); - missing_vol.append(cstr!("close"), 10.5_f64); - let err = decode_eod_intraday_doc(&missing_vol).unwrap_err(); - assert_eq!(err, BsonEodIntradayError::MissingField { field: "volume" }); - - let build_with_vol = |val: RawBsonRef<'_>| { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), "NVDA.US"); - doc.append(cstr!("timestamp"), 1_717_767_000_i64); - doc.append(cstr!("open"), 10.0_f64); - doc.append(cstr!("high"), 11.0_f64); - doc.append(cstr!("low"), 9.0_f64); - doc.append(cstr!("close"), 10.5_f64); - doc.append(cstr!("volume"), val); - doc - }; - - for (val, expected_type) in [ - (RawBsonRef::Null, ElementType::Null), - (RawBsonRef::String("100"), ElementType::String), - (RawBsonRef::Boolean(false), ElementType::Boolean), - ] { - let doc = build_with_vol(val); - let err = decode_eod_intraday_doc(&doc).unwrap_err(); - assert_eq!( - err, - BsonEodIntradayError::WrongType { - field: "volume", - actual: expected_type, - } - ); - let mut st = BsonEodIntradayDecodeStats::default(); - st.record_error(&err); - assert_eq!(st.rejected_wrong_type, 1); - assert_eq!(st.rejected_total(), 1); - } - - for bad_vol in [ - RawBsonRef::Double(-0.01), - RawBsonRef::Double(f64::NAN), - RawBsonRef::Double(f64::INFINITY), - RawBsonRef::Double(f64::NEG_INFINITY), - RawBsonRef::Int32(-1), - RawBsonRef::Int64(-1), - ] { - let doc = build_with_vol(bad_vol); - let err = decode_eod_intraday_doc(&doc).unwrap_err(); - match &err { - BsonEodIntradayError::InvalidNumber { field, .. } => assert_eq!(*field, "volume"), - other => panic!("expected InvalidNumber for volume, got {other:?}"), - } - let mut st = BsonEodIntradayDecodeStats::default(); - st.record_error(&err); - assert_eq!(st.rejected_invalid_number, 1); - assert_eq!(st.rejected_total(), 1); - } -} - -#[test] -fn rejects_truncated_and_corrupt_single_doc_bytes_without_panicking() { - // Truncated header (< 4 bytes) - assert_eq!( - decode_eod_intraday_bytes(&[0x10, 0x00]), - Err(BsonEodIntradayError::TruncatedDocument { - offset: 0, - remaining: 2, - declared_len: None, - }) - ); - - // Declared length < 5 - assert_eq!( - decode_eod_intraday_bytes(&[4, 0, 0, 0]), - Err(BsonEodIntradayError::CorruptDocumentLength { - offset: 0, - declared_len: 4, - }) - ); - - // Truncated body (declared_len > remaining) - let valid = make_valid_doc("NVDA.US", 1_717_767_000, 10.0, 11.0, 9.0, 10.5, 100.0); - let truncated = &valid.as_bytes()[..valid.as_bytes().len() - 3]; - assert_eq!( - decode_eod_intraday_bytes(truncated), - Err(BsonEodIntradayError::TruncatedDocument { - offset: 0, - remaining: truncated.len(), - declared_len: Some(valid.as_bytes().len() as i32), - }) - ); - - // Trailing extra bytes on single-doc decode -> CorruptDocumentLength - let mut with_trailing = valid.as_bytes().to_vec(); - with_trailing.push(0x00); - assert_eq!( - decode_eod_intraday_bytes(&with_trailing), - Err(BsonEodIntradayError::CorruptDocumentLength { - offset: 0, - declared_len: valid.as_bytes().len() as i32, - }) - ); - - // Malformed BSON (missing trailing null terminator) - let mut bad_term = valid.as_bytes().to_vec(); - *bad_term.last_mut().unwrap() = 0xFF; - match decode_eod_intraday_bytes(&bad_term) { - Err(BsonEodIntradayError::CorruptBson { offset: 0, .. }) => {} - other => panic!("expected CorruptBson, got {other:?}"), - } -} - -#[test] -fn rejects_corrupt_utf8_in_skipped_top_level_field_and_recovers_to_next_frame() { - // Build a valid document with a skipped `datetime` string field, then corrupt one payload byte - // inside `datetime` to invalid UTF-8 (0xFF) while leaving all lengths and NUL terminators - // intact. - const DATETIME_MARKER: &[u8] = b"2024-06-07 13:30:00"; - let mut doc_with_datetime = make_valid_doc( - "NVDA.US", - 1_717_767_000, - 120.50, - 121.25, - 120.10, - 120.90, - 1_000.0, - ); - doc_with_datetime.append(cstr!("datetime"), "2024-06-07 13:30:00"); - - let mut corrupt_bytes = doc_with_datetime.as_bytes().to_vec(); - let marker_pos = corrupt_bytes - .windows(DATETIME_MARKER.len()) - .position(|w| w == DATETIME_MARKER) - .expect("datetime payload must exist in serialized BSON"); - corrupt_bytes[marker_pos + 4] = 0xFF; - - // Single-document decode must reject as CorruptBson at offset 0. - match decode_eod_intraday_bytes(&corrupt_bytes) { - Err(BsonEodIntradayError::CorruptBson { offset: 0, detail }) => { - assert!( - detail.contains("datetime"), - "expected offending field name in detail, got: {detail}" - ); - } - other => panic!("expected CorruptBson at offset 0, got {other:?}"), - } - - // Buffer decode with a preceding valid frame and a following valid frame: rejects the - // damaged frame at its exact byte offset, increments `rejected_corrupt_document`, and - // recovers cleanly to decode the next frame. - let valid_before = - make_valid_doc("AAPL.US", 1_717_766_940, 195.0, 196.0, 194.5, 195.5, 500.0); - let valid_after = - make_valid_doc("MSFT.US", 1_717_767_060, 420.0, 421.0, 419.5, 420.5, 750.0); - - let mut buf = Vec::new(); - buf.extend_from_slice(valid_before.as_bytes()); - let corrupt_offset = buf.len(); - buf.extend_from_slice(&corrupt_bytes); - buf.extend_from_slice(valid_after.as_bytes()); - - let mut rows = Vec::new(); - let mut errors = Vec::new(); - let stats = decode_eod_intraday_buffer( - &buf, - |bar| rows.push((bar.eod_search_code.to_owned(), bar.ts, bar.close)), - |off, err| errors.push((off, err)), - ); - - assert_eq!( - rows, - vec![ - ("AAPL.US".to_owned(), 1_717_766_940_000_000, 195.5), - ("MSFT.US".to_owned(), 1_717_767_060_000_000, 420.5), - ] - ); - assert_eq!(stats.docs_seen, 3); - assert_eq!(stats.rows_decoded, 2); - assert_eq!(stats.rejected_corrupt_document, 1); - assert_eq!(stats.rejected_total(), 1); - assert_eq!(stats.docs_seen, stats.rows_decoded + stats.rejected_total()); - assert_eq!(errors.len(), 1); - assert_eq!(errors[0].0, corrupt_offset); - assert!(matches!( - &errors[0].1, - BsonEodIntradayError::CorruptBson { offset, detail } - if *offset == corrupt_offset && detail.contains("datetime") - )); -} - -#[test] -fn decodes_mixed_buffer_preserving_order_recovering_past_corrupt_frame_and_merging_stats() { - let valid1 = make_valid_doc("NVDA.US", 1_717_767_000, 120.0, 121.0, 119.5, 120.5, 1000.0); - let empty_key = make_valid_doc(" ", 1_717_767_060, 120.5, 121.0, 120.0, 120.8, 500.0); - let bad_ts = make_doc_with_timestamp(RawBsonRef::Double(1_717_767_120.5)); - let bad_price = make_valid_doc("NVDA.US", 1_717_767_180, 0.0, 121.0, 119.0, 120.0, 200.0); - - let mut wrong_type = RawDocumentBuf::new(); - wrong_type.append(cstr!("eodSearchCode"), "NVDA.US"); - wrong_type.append(cstr!("timestamp"), 1_717_767_240_i64); - wrong_type.append(cstr!("open"), RawBsonRef::Null); - wrong_type.append(cstr!("high"), 121.0_f64); - wrong_type.append(cstr!("low"), 119.0_f64); - wrong_type.append(cstr!("close"), 120.0_f64); - wrong_type.append(cstr!("volume"), 200.0_f64); - - let mut missing_field = RawDocumentBuf::new(); - missing_field.append(cstr!("eodSearchCode"), "NVDA.US"); - missing_field.append(cstr!("timestamp"), 1_717_767_300_i64); - missing_field.append(cstr!("open"), 120.0_f64); - missing_field.append(cstr!("high"), 121.0_f64); - missing_field.append(cstr!("low"), 119.0_f64); - missing_field.append(cstr!("close"), 120.0_f64); - - // Valid length-framed doc whose trailing terminator is corrupt -> CorruptBson, but buffer - // iteration recovers and decodes valid2 after it. - let mut corrupt_framed = valid1.as_bytes().to_vec(); - *corrupt_framed.last_mut().unwrap() = 0xAA; - - let valid2 = make_valid_doc("AAPL.US", 1_717_767_360, 195.0, 196.0, 194.5, 195.5, 0.0); - - let mut buf = Vec::new(); - buf.extend_from_slice(valid1.as_bytes()); - let off_empty = buf.len(); - buf.extend_from_slice(empty_key.as_bytes()); - let off_bad_ts = buf.len(); - buf.extend_from_slice(bad_ts.as_bytes()); - let off_bad_price = buf.len(); - buf.extend_from_slice(bad_price.as_bytes()); - let off_wrong_type = buf.len(); - buf.extend_from_slice(wrong_type.as_bytes()); - let off_missing = buf.len(); - buf.extend_from_slice(missing_field.as_bytes()); - let off_corrupt = buf.len(); - buf.extend_from_slice(&corrupt_framed); - buf.extend_from_slice(valid2.as_bytes()); - - let mut rows = Vec::new(); - let mut errors = Vec::new(); - let stats = decode_eod_intraday_buffer( - &buf, - |bar| rows.push((bar.eod_search_code.to_owned(), bar.ts, bar.close, bar.volume)), - |offset, err| errors.push((offset, err)), - ); - - assert_eq!(rows.len(), 2); - assert_eq!(rows[0], ("NVDA.US".to_owned(), 1_717_767_000_000_000, 120.5, 1000.0)); - assert_eq!(rows[1], ("AAPL.US".to_owned(), 1_717_767_360_000_000, 195.5, 0.0)); - - assert_eq!(stats.docs_seen, 8); - assert_eq!(stats.rows_decoded, 2); - assert_eq!(stats.rejected_empty_field, 1); - assert_eq!(stats.rejected_invalid_timestamp, 1); - assert_eq!(stats.rejected_invalid_number, 1); - assert_eq!(stats.rejected_wrong_type, 1); - assert_eq!(stats.rejected_missing_field, 1); - assert_eq!(stats.rejected_corrupt_document, 1); - assert_eq!(stats.rejected_total(), 6); - assert_eq!(stats.docs_seen, stats.rows_decoded + stats.rejected_total()); - - assert_eq!(errors.len(), 6); - assert_eq!(errors[0].0, off_empty); - assert_eq!(errors[1].0, off_bad_ts); - assert_eq!(errors[2].0, off_bad_price); - assert_eq!(errors[3].0, off_wrong_type); - assert_eq!(errors[4].0, off_missing); - assert_eq!(errors[5].0, off_corrupt); - assert!(matches!( - errors[5].1, - BsonEodIntradayError::CorruptBson { offset, .. } if offset == off_corrupt - )); - - // Verify BsonEodIntradayDecodeStats::merge sums every counter. - let mut merged = BsonEodIntradayDecodeStats { - docs_seen: 10, - rows_decoded: 4, - rejected_missing_field: 1, - rejected_empty_field: 1, - rejected_wrong_type: 1, - rejected_invalid_timestamp: 1, - rejected_invalid_number: 1, - rejected_corrupt_document: 1, - }; - merged.merge(&stats); - assert_eq!( - merged, - BsonEodIntradayDecodeStats { - docs_seen: 18, - rows_decoded: 6, - rejected_missing_field: 2, - rejected_empty_field: 2, - rejected_wrong_type: 2, - rejected_invalid_timestamp: 2, - rejected_invalid_number: 2, - rejected_corrupt_document: 2, - } - ); - assert_eq!(merged.docs_seen, merged.rows_decoded + merged.rejected_total()); - - // Truncated tail stops cleanly and still maintains conservation invariant. - let mut with_trunc = buf.clone(); - let trunc_off = with_trunc.len(); - with_trunc.extend_from_slice(&valid2.as_bytes()[..10]); - let mut trunc_errs = Vec::new(); - let trunc_stats = decode_eod_intraday_buffer( - &with_trunc, - |_| {}, - |off, err| trunc_errs.push((off, err)), - ); - assert_eq!(trunc_stats.docs_seen, 9); - assert_eq!(trunc_stats.rows_decoded, 2); - assert_eq!(trunc_stats.rejected_corrupt_document, 2); - assert_eq!( - trunc_stats.docs_seen, - trunc_stats.rows_decoded + trunc_stats.rejected_total() - ); - assert_eq!(trunc_errs.last().unwrap().0, trunc_off); - assert!(matches!( - trunc_errs.last().unwrap().1, - BsonEodIntradayError::TruncatedDocument { offset, remaining: 10, declared_len: Some(_) } - if offset == trunc_off - )); -} - -#[test] -fn decoded_nvda_bars_feed_build_bars_1m_end_to_end_with_10_for_1_split() { - // NVDA 10:1 split ex-date: 2024-06-10. - // Bar 1: 2024-06-07 15:59 ET (EDT, UTC-4) = 2024-06-07 19:59:00 UTC = 1_717_790_340 s. - // Bar 2: 2024-06-10 09:30 ET (EDT, UTC-4) = 2024-06-10 13:30:00 UTC = 1_718_026_200 s. - const PRE_SPLIT_TS_SEC: i64 = 1_717_790_340; - const EX_DATE_TS_SEC: i64 = 1_718_026_200; - - // Provider's retroactively split-adjusted 1m values. - let pre_split_doc = make_valid_doc( - "NVDA.US", - PRE_SPLIT_TS_SEC, - 120.80, - 121.05, - 120.72, - 120.888, - 2_500_000.0, - ); - let ex_date_doc = make_valid_doc( - "NVDA.US", - EX_DATE_TS_SEC, - 120.37, - 121.10, - 120.15, - 120.95, - 1_800_000.0, - ); - - let mut raw_buf = Vec::new(); - raw_buf.extend_from_slice(pre_split_doc.as_bytes()); - raw_buf.extend_from_slice(ex_date_doc.as_bytes()); - - let splits = SplitTable::from_events([( - "NVDA.US".to_owned(), - SplitEvent { - ex_date: day(2024, 6, 10), - ratio: 10.0, - }, - )]) - .unwrap(); - let empty_splits = SplitTable::::default(); - - let run_once = |table: &SplitTable| { - let mut bars = Vec::new(); - let mut decode_errors = Vec::new(); - let decode_stats = decode_eod_intraday_buffer( - &raw_buf, - |raw| bars.push(raw.into_eod_intraday_bar(|code, _ts| code.to_owned())), - |off, err| decode_errors.push((off, err)), - ); - assert!(decode_errors.is_empty()); - assert_eq!(decode_stats.docs_seen, 2); - assert_eq!(decode_stats.rows_decoded, 2); - let built = build_bars_1m(bars, table); - (decode_stats, built) - }; - - let (stats_split, built_split) = run_once(&splits); - let (stats_empty, built_empty) = run_once(&empty_splits); - let (stats_replay, built_replay) = run_once(&splits); - - // Deterministic replay produces identical rows and stats. - assert_eq!(stats_split, stats_replay); - assert_eq!(built_split.rows, built_replay.rows); - assert_eq!(built_split.stats, built_replay.stats); - assert_eq!(stats_split, stats_empty); - - assert_eq!(built_split.rows.len(), 2); - assert_eq!(built_empty.rows.len(), 2); - - // Pre-split bar: OHLC * 10, volume / 10, dollar volume (close * volume) conserved. - let pre_split = &built_split.rows[0]; - let pre_empty = &built_empty.rows[0]; - assert_eq!(pre_split.key, "NVDA.US"); - assert_eq!(pre_split.ts, PRE_SPLIT_TS_SEC * 1_000_000); - assert_eq!(pre_split.session_date, day(2024, 6, 7)); - assert_eq!(pre_split.session, IntradaySession::Rth); - assert_eq!(pre_split.source, BARS_1M_SOURCE_EOD); - assert_rel_eq(pre_split.open, pre_empty.open * 10.0, 1e-12); - assert_rel_eq(pre_split.high, pre_empty.high * 10.0, 1e-12); - assert_rel_eq(pre_split.low, pre_empty.low * 10.0, 1e-12); - assert_rel_eq(pre_split.close, 1_208.88, 1e-12); - assert_rel_eq(pre_split.close, pre_empty.close * 10.0, 1e-12); - assert_rel_eq(pre_split.volume, pre_empty.volume / 10.0, 1e-12); - assert_rel_eq( - pre_split.close * pre_split.volume, - pre_empty.close * pre_empty.volume, - 1e-12, - ); - - // Ex-date bar: unchanged by the 2024-06-10 split (strict ex_date > session_date boundary). - let ex_split = &built_split.rows[1]; - let ex_empty = &built_empty.rows[1]; - assert_eq!(ex_split.ts, EX_DATE_TS_SEC * 1_000_000); - assert_eq!(ex_split.session_date, day(2024, 6, 10)); - assert_eq!(ex_split.session, IntradaySession::Rth); - assert_eq!(ex_split.open.to_bits(), ex_empty.open.to_bits()); - assert_eq!(ex_split.high.to_bits(), ex_empty.high.to_bits()); - assert_eq!(ex_split.low.to_bits(), ex_empty.low.to_bits()); - assert_eq!(ex_split.close.to_bits(), ex_empty.close.to_bits()); - assert_eq!(ex_split.volume.to_bits(), ex_empty.volume.to_bits()); -} diff --git a/tools/curate-etl/src/bson_eod_prices.rs b/tools/curate-etl/src/bson_eod_prices.rs index a7602240..9547f250 100644 --- a/tools/curate-etl/src/bson_eod_prices.rs +++ b/tools/curate-etl/src/bson_eod_prices.rs @@ -42,7 +42,7 @@ use bson::spec::ElementType; use crate::bars::EodDailyBar; use crate::split::ymd_to_epoch_days; -pub(crate) const MILLIS_PER_DAY: i64 = 86_400_000; +const MILLIS_PER_DAY: i64 = 86_400_000; const MIN_BSON_DOC_LEN: i32 = 5; /// Borrowed zero-copy view of a single decoded `eodPrices` BSON document. @@ -235,26 +235,6 @@ impl BsonEodDecodeStats { | BsonEodPriceError::CorruptBson { .. } => self.rejected_corrupt_document += 1, } } - - /// Accumulates counters from another batch into `self`. - #[inline] - pub fn merge(&mut self, other: &Self) { - self.docs_in += other.docs_in; - self.decoded += other.decoded; - self.rejected_missing_field += other.rejected_missing_field; - self.rejected_empty_field += other.rejected_empty_field; - self.rejected_wrong_type += other.rejected_wrong_type; - self.rejected_malformed_date += other.rejected_malformed_date; - self.rejected_invalid_number += other.rejected_invalid_number; - self.rejected_corrupt_document += other.rejected_corrupt_document; - } -} - -impl std::ops::AddAssign for BsonEodDecodeStats { - #[inline] - fn add_assign(&mut self, rhs: Self) { - self.merge(&rhs); - } } #[inline] @@ -270,20 +250,22 @@ fn parse_ascii_digits_u32(bytes: &[u8]) -> Option { } #[inline] -pub(crate) fn parse_ymd_strict_days(s: &str) -> Option { +fn parse_ymd_strict(s: &str) -> Result { let bytes = s.as_bytes(); if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' { - return None; + return Err(BsonEodPriceError::MalformedDate { field: "date" }); } - let year_u32 = parse_ascii_digits_u32(&bytes[0..4])?; - let month = parse_ascii_digits_u32(&bytes[5..7])?; - let day = parse_ascii_digits_u32(&bytes[8..10])?; - ymd_to_epoch_days(year_u32 as i32, month, day).ok() -} - -#[inline] -fn parse_ymd_strict(s: &str) -> Result { - parse_ymd_strict_days(s).ok_or(BsonEodPriceError::MalformedDate { field: "date" }) + let Some(year_u32) = parse_ascii_digits_u32(&bytes[0..4]) else { + return Err(BsonEodPriceError::MalformedDate { field: "date" }); + }; + let Some(month) = parse_ascii_digits_u32(&bytes[5..7]) else { + return Err(BsonEodPriceError::MalformedDate { field: "date" }); + }; + let Some(day) = parse_ascii_digits_u32(&bytes[8..10]) else { + return Err(BsonEodPriceError::MalformedDate { field: "date" }); + }; + ymd_to_epoch_days(year_u32 as i32, month, day) + .map_err(|_| BsonEodPriceError::MalformedDate { field: "date" }) } #[inline] @@ -350,7 +332,6 @@ fn decode_eod_price_doc_at<'a>( let mut low: Option = None; let mut close: Option = None; let mut adj_volume: Option = None; - let mut first_semantic_err: Option = None; for elem_res in doc.iter_elements() { let elem = elem_res.map_err(|err| BsonEodPriceError::CorruptBson { @@ -363,113 +344,56 @@ fn decode_eod_price_doc_at<'a>( match decode_element_value("eodSearchCode", elem, offset)? { RawBsonRef::String(s) => { if s.trim().is_empty() { - if first_semantic_err.is_none() { - first_semantic_err = Some(BsonEodPriceError::EmptyField { - field: "eodSearchCode", - }); - } - } else { - eod_search_code = Some(s); - } - } - other => { - if first_semantic_err.is_none() { - first_semantic_err = Some(BsonEodPriceError::WrongType { + return Err(BsonEodPriceError::EmptyField { field: "eodSearchCode", - actual: other.element_type(), }); } + eod_search_code = Some(s); + } + other => { + return Err(BsonEodPriceError::WrongType { + field: "eodSearchCode", + actual: other.element_type(), + }); } } } else if key == cstr!("date") { match decode_element_value("date", elem, offset)? { - RawBsonRef::String(s) => match parse_ymd_strict(s) { - Ok(d) => session_date = Some(d), - Err(err) => { - if first_semantic_err.is_none() { - first_semantic_err = Some(err); - } - } - }, + RawBsonRef::String(s) => { + session_date = Some(parse_ymd_strict(s)?); + } RawBsonRef::DateTime(dt) => { let days = dt.timestamp_millis().div_euclid(MILLIS_PER_DAY); - match i32::try_from(days) { - Ok(day_i32) => session_date = Some(day_i32), - Err(_) => { - if first_semantic_err.is_none() { - first_semantic_err = - Some(BsonEodPriceError::MalformedDate { field: "date" }); - } - } - } + let day_i32 = i32::try_from(days) + .map_err(|_| BsonEodPriceError::MalformedDate { field: "date" })?; + session_date = Some(day_i32); } other => { - if first_semantic_err.is_none() { - first_semantic_err = Some(BsonEodPriceError::WrongType { - field: "date", - actual: other.element_type(), - }); - } + return Err(BsonEodPriceError::WrongType { + field: "date", + actual: other.element_type(), + }); } } } else if key == cstr!("open") { let val = decode_element_value("open", elem, offset)?; - match decode_non_negative_number("open", val) { - Ok(v) => open = Some(v), - Err(err) => { - if first_semantic_err.is_none() { - first_semantic_err = Some(err); - } - } - } + open = Some(decode_non_negative_number("open", val)?); } else if key == cstr!("high") { let val = decode_element_value("high", elem, offset)?; - match decode_non_negative_number("high", val) { - Ok(v) => high = Some(v), - Err(err) => { - if first_semantic_err.is_none() { - first_semantic_err = Some(err); - } - } - } + high = Some(decode_non_negative_number("high", val)?); } else if key == cstr!("low") { let val = decode_element_value("low", elem, offset)?; - match decode_non_negative_number("low", val) { - Ok(v) => low = Some(v), - Err(err) => { - if first_semantic_err.is_none() { - first_semantic_err = Some(err); - } - } - } + low = Some(decode_non_negative_number("low", val)?); } else if key == cstr!("close") { let val = decode_element_value("close", elem, offset)?; - match decode_non_negative_number("close", val) { - Ok(v) => close = Some(v), - Err(err) => { - if first_semantic_err.is_none() { - first_semantic_err = Some(err); - } - } - } + close = Some(decode_non_negative_number("close", val)?); } else if key == cstr!("volume") { let val = decode_element_value("volume", elem, offset)?; - match decode_non_negative_number("volume", val) { - Ok(v) => adj_volume = Some(v), - Err(err) => { - if first_semantic_err.is_none() { - first_semantic_err = Some(err); - } - } - } + adj_volume = Some(decode_non_negative_number("volume", val)?); } // Unknown extra fields are skipped without calling `elem.value()`. } - if let Some(err) = first_semantic_err { - return Err(err); - } - let Some(eod_search_code) = eod_search_code else { return Err(BsonEodPriceError::MissingField { field: "eodSearchCode", @@ -514,7 +438,11 @@ pub fn decode_eod_price_doc<'a>( decode_eod_price_doc_at(doc, 0) } -pub(crate) fn parse_single_raw_doc(bytes: &[u8]) -> Result<&RawDocument, BsonEodPriceError> { +/// Decodes a single length-prefixed raw BSON document byte slice into a borrowed +/// [`RawEodDailyBar`]. +pub fn decode_eod_price_bytes<'a>( + bytes: &'a [u8], +) -> Result, BsonEodPriceError> { if bytes.len() < 4 { return Err(BsonEodPriceError::TruncatedDocument { offset: 0, @@ -543,18 +471,10 @@ pub(crate) fn parse_single_raw_doc(bytes: &[u8]) -> Result<&RawDocument, BsonEod declared_len, }); } - RawDocument::from_bytes(bytes).map_err(|err| BsonEodPriceError::CorruptBson { + let doc = RawDocument::from_bytes(bytes).map_err(|err| BsonEodPriceError::CorruptBson { offset: 0, detail: err.to_string(), - }) -} - -/// Decodes a single length-prefixed raw BSON document byte slice into a borrowed -/// [`RawEodDailyBar`]. -pub fn decode_eod_price_bytes<'a>( - bytes: &'a [u8], -) -> Result, BsonEodPriceError> { - let doc = parse_single_raw_doc(bytes)?; + })?; decode_eod_price_doc_at(doc, 0) } diff --git a/tools/curate-etl/src/bson_eod_prices_tests.rs b/tools/curate-etl/src/bson_eod_prices_tests.rs index 42def67e..e5a614b5 100644 --- a/tools/curate-etl/src/bson_eod_prices_tests.rs +++ b/tools/curate-etl/src/bson_eod_prices_tests.rs @@ -783,20 +783,3 @@ fn corrupt_length_prefix_in_middle_stops_stream_cleanly() { )] ); } - -#[test] -fn structural_corruption_after_semantic_reject_takes_precedence() { - let doc = make_valid_doc("CAD.FOREX", "2025-01-02", f64::NAN, 1.44, 1.42, 1.435, 0.0); - let mut bytes = doc.as_bytes().to_vec(); - let close_elem_pos = bytes - .windows(7) - .position(|w| w == b"\x01close\0") - .expect("find double element 'close'"); - bytes[close_elem_pos] = 0xFF; - - let err = decode_eod_price_bytes(&bytes).unwrap_err(); - assert!( - matches!(err, BsonEodPriceError::CorruptBson { offset: 0, .. }), - "expected CorruptBson to take precedence over InvalidNumber, got {err:?}" - ); -} diff --git a/tools/curate-etl/src/bson_qm_actions.rs b/tools/curate-etl/src/bson_qm_actions.rs deleted file mode 100644 index 210e6d45..00000000 --- a/tools/curate-etl/src/bson_qm_actions.rs +++ /dev/null @@ -1,863 +0,0 @@ -//! Zero-copy raw BSON decoders for MongoDB `qmSplits` and `qmDividends` documents (`M1.2w`). -//! -//! Decodes `&bson::RawDocument` slices in a single forward pass over `iter_elements()` into -//! borrowed [`RawQmSplit`] and [`RawQmDividend`] views without allocating a `String` or -//! `bson::Document` per row. Callers convert borrowed views into [`SplitEvent`], [`DividendEvent`], -//! [`SplitActionEvent`], or [`DividendActionEvent`], optionally resolving `("qm", qmSearchCode, ex_date)` -//! through a caller-supplied key mapper (such as [`crate::provider_mapping::ProviderMappingTable::resolve`]). -//! -//! # Empirical Field Contract & Cited Sources -//! -//! - `apps/stock/data-ingestion/src/handlers/qm/actions/events.action.ts:92-124`: writes -//! `qmSearchCode`, `symbol`, `exchange`, `reportDate: new Date(x.date)` plus the spread -//! QuoteMedia API payload into `qmDividends` and `qmSplits`. -//! - `design/DATA-CONTRACTS.md` §1 (line 25): documents `date`, `declared`, `splitratio` -//! (`258` rows have `splitratio == 1`), and `usdFxRate` (bogus `usdFxRate: 1` on CAD dividend -//! rows; contract rule: ignore `usdFxRate`). -//! - **Unverified field names:** the raw MongoDB dividend cash and currency field names are not -//! proven by any in-repo schema or fixture (`events.action.ts` spreads `...dividend` untyped). -//! They are isolated in [`FIELD_DIVIDEND_CASH`] (`"amount"`) and [`FIELD_DIVIDEND_CURRENCY`] -//! (`"currency"`) and explicitly listed under "Unverified field names" in `tools/curate-etl/README.md`. -//! -//! Accepted BSON field representations: -//! - `qmSearchCode`, `currency`: BSON UTF-8 `String` (borrowed verbatim; empty or whitespace-only -//! is rejected). -//! - `date`: strict 10-byte ASCII `YYYY-MM-DD` BSON `String` (validated via -//! [`crate::split::ymd_to_epoch_days`]) or BSON `DateTime` (UTC epoch day via -//! `timestamp_millis().div_euclid(86_400_000)` with `i32` bounds check). -//! - `declared` (optional): absent, BSON `Null`, or empty/whitespace `String` maps to `None`; -//! otherwise strict `YYYY-MM-DD` `String` or BSON `DateTime` maps to `Some(i32)`. -//! - `splitratio`: BSON `Double`, `Int32`, or `Int64`; must be finite and `> 0.0`. `ratio == 1.0` -//! no-ops are **decoded, not dropped** (downstream builders drop them) and counted in -//! [`BsonQmActionDecodeStats::split_noop_ratio_one`]. -//! - `amount` (dividend cash): BSON `Double`, `Int32`, or `Int64`; must be finite and `>= 0.0` -//! (`-0.0` is normalized to `+0.0`). -//! - `usdFxRate` and all unknown extra fields (`_id`, `symbol`, `exchange`, `reportDate`, -//! `created_at`, `updated_at`, nested objects/arrays, etc.) are skipped without calling -//! `elem.value()`. - -use std::error::Error; -use std::fmt; - -use bson::raw::{RawBsonRef, RawDocument, RawElement}; -use bson::spec::ElementType; - -use crate::adj::DividendEvent; -use crate::bson_eod_prices::{ - iter_raw_bson_docs, parse_single_raw_doc, parse_ymd_strict_days, BsonEodPriceError, - MILLIS_PER_DAY, -}; -use crate::corporate_actions::{DividendActionEvent, SplitActionEvent}; -use crate::split::SplitEvent; - -/// MongoDB field name for the QuoteMedia security key (`events.action.ts:98,118`). -pub const FIELD_QM_SEARCH_CODE: &str = "qmSearchCode"; -/// MongoDB field name for the ex-split / ex-dividend date (`events.action.ts:99,119`, `DATA-CONTRACTS.md:25`). -pub const FIELD_DATE: &str = "date"; -/// MongoDB field name for the optional declaration date (`DATA-CONTRACTS.md:25`). -pub const FIELD_DECLARED: &str = "declared"; -/// MongoDB field name for the split ratio (`DATA-CONTRACTS.md:25`). -/// -/// Empirically verified across all `18,751` documents in `qmSplits` (`16,892/16,892` with numeric -/// `forfactor`/`tofactor`): QuoteMedia stores `splitratio = forfactor / tofactor = old_shares / -/// new_shares` (e.g. `0.1` for a 10:1 forward split such as `NVDA 2024-06-10`, `8.0` for a 1:8 -/// reverse split such as `GE 2021-08-02`). [`decode_qm_split_doc`] converts this to canonical -/// `new_shares / old_shares` via `tofactor / forfactor` when both are positive numbers (avoiding -/// QuoteMedia's 6-decimal truncation such as `0.142857` for 7:1), or `1.0 / splitratio` otherwise. -pub const FIELD_SPLIT_RATIO: &str = "splitratio"; -/// MongoDB field name for QuoteMedia's `old_shares` factor (`forfactor`). -pub const FIELD_FOR_FACTOR: &str = "forfactor"; -/// MongoDB field name for QuoteMedia's `new_shares` factor (`tofactor`). -pub const FIELD_TO_FACTOR: &str = "tofactor"; -/// MongoDB field name for the bogus FX field explicitly ignored per contract (`DATA-CONTRACTS.md:25`). -pub const FIELD_USD_FX_RATE: &str = "usdFxRate"; -/// MongoDB field name for dividend cash amount (**unverified in repo**; QuoteMedia convention). -pub const FIELD_DIVIDEND_CASH: &str = "amount"; -/// MongoDB field name for dividend currency code (**unverified in repo**; QuoteMedia convention). -pub const FIELD_DIVIDEND_CURRENCY: &str = "currency"; - -/// Borrowed zero-copy view of a single decoded `qmSplits` BSON document. -/// -/// Borrows `qm_search_code` directly from the underlying `&RawDocument` byte slice. -/// `ratio == 1.0` no-op rows are preserved here so downstream builders (`SplitTable`, -/// `build_adj_factors`, `build_corporate_actions`) apply their own filtering and accounting. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct RawQmSplit<'a> { - pub qm_search_code: &'a str, - /// Ex-split date as days since `1970-01-01` (UTC Gregorian). - pub ex_date: i32, - /// `new_shares / old_shares` (finite and `> 0.0`). - pub ratio: f64, - /// Optional declaration date as days since `1970-01-01` (UTC Gregorian). - pub declared_date: Option, -} - -impl<'a> RawQmSplit<'a> { - /// Converts this borrowed split into a [`SplitEvent`] for [`crate::split::SplitTable`] or - /// [`crate::adj::build_adj_factors`]. - #[inline] - pub fn to_split_event(self) -> SplitEvent { - SplitEvent { - ex_date: self.ex_date, - ratio: self.ratio, - } - } - - /// Converts this borrowed split into a [`SplitActionEvent`] for - /// [`crate::corporate_actions::build_corporate_actions`]. - #[inline] - pub fn to_split_action_event(self) -> SplitActionEvent { - SplitActionEvent { - ex_date: self.ex_date, - ratio: self.ratio, - declared_date: self.declared_date, - } - } - - /// Resolves `(qm_search_code, ex_date)` via a caller-supplied key mapper - /// (for example `|code, date| mapping.resolve("qm", code, date)`). - #[inline] - pub fn try_map_key(self, map_key: F) -> Option - where - F: FnOnce(&'a str, i32) -> Option, - { - map_key(self.qm_search_code, self.ex_date) - } - - /// Fallibly resolves the key and pairs it with [`SplitEvent`]. - #[inline] - pub fn try_into_split_event(self, map_key: F) -> Option<(K, SplitEvent)> - where - F: FnOnce(&'a str, i32) -> Option, - { - let key = self.try_map_key(map_key)?; - Some((key, self.to_split_event())) - } - - /// Fallibly resolves the key and pairs it with [`SplitActionEvent`]. - #[inline] - pub fn try_into_split_action_event(self, map_key: F) -> Option<(K, SplitActionEvent)> - where - F: FnOnce(&'a str, i32) -> Option, - { - let key = self.try_map_key(map_key)?; - Some((key, self.to_split_action_event())) - } -} - -/// Borrowed zero-copy view of a single decoded `qmDividends` BSON document. -/// -/// Borrows `qm_search_code` and `currency` directly from the underlying `&RawDocument` byte slice. -/// Deliberately omits `usdFxRate` per `design/DATA-CONTRACTS.md` §1. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct RawQmDividend<'a> { - pub qm_search_code: &'a str, - /// Ex-dividend date as days since `1970-01-01` (UTC Gregorian). - pub ex_date: i32, - /// Cash dividend amount per share (finite and `>= 0.0`, with `-0.0` normalized to `+0.0`). - pub cash: f64, - /// Local dividend currency code (e.g. `"USD"`, `"CAD"`). - pub currency: &'a str, - /// Optional declaration date as days since `1970-01-01` (UTC Gregorian). - pub declared_date: Option, -} - -impl<'a> RawQmDividend<'a> { - /// Converts this borrowed dividend into a [`DividendEvent`] for - /// [`crate::adj::build_adj_factors`], attaching caller-supplied `prev_close` context. - #[inline] - pub fn to_dividend_event( - self, - prev_close: Option, - prev_close_currency: Option, - ) -> DividendEvent { - DividendEvent { - ex_date: self.ex_date, - cash: self.cash, - currency: self.currency.to_owned(), - prev_close, - prev_close_currency, - } - } - - /// Converts this borrowed dividend into a [`DividendActionEvent`] for - /// [`crate::corporate_actions::build_corporate_actions`]. - #[inline] - pub fn to_dividend_action_event(self) -> DividendActionEvent { - DividendActionEvent { - ex_date: self.ex_date, - cash: self.cash, - currency: self.currency.to_owned(), - declared_date: self.declared_date, - } - } - - /// Resolves `(qm_search_code, ex_date)` via a caller-supplied key mapper - /// (for example `|code, date| mapping.resolve("qm", code, date)`). - #[inline] - pub fn try_map_key(self, map_key: F) -> Option - where - F: FnOnce(&'a str, i32) -> Option, - { - map_key(self.qm_search_code, self.ex_date) - } - - /// Fallibly resolves the key before allocating `currency` and pairs it with [`DividendEvent`]. - #[inline] - pub fn try_into_dividend_event( - self, - prev_close: Option, - prev_close_currency: Option, - map_key: F, - ) -> Option<(K, DividendEvent)> - where - F: FnOnce(&'a str, i32) -> Option, - { - let key = self.try_map_key(map_key)?; - Some((key, self.to_dividend_event(prev_close, prev_close_currency))) - } - - /// Fallibly resolves the key before allocating `currency` and pairs it with - /// [`DividendActionEvent`]. - #[inline] - pub fn try_into_dividend_action_event( - self, - map_key: F, - ) -> Option<(K, DividendActionEvent)> - where - F: FnOnce(&'a str, i32) -> Option, - { - let key = self.try_map_key(map_key)?; - Some((key, self.to_dividend_action_event())) - } -} - -/// Typed errors returned while decoding raw `qmSplits` or `qmDividends` BSON documents or -/// length-prefixed buffers. -/// -/// Every field-level error names the offending BSON field in both its structure and `Display` -/// output; no input path panics. -#[derive(Debug, Clone, PartialEq)] -pub enum BsonQmActionError { - /// A required field was absent from the document. - MissingField { field: &'static str }, - /// A required string field was empty or contained only whitespace. - EmptyField { field: &'static str }, - /// A decoded field had an unexpected BSON element type. - WrongType { - field: &'static str, - actual: ElementType, - }, - /// A date field was not a valid strict `YYYY-MM-DD` Gregorian date or BSON `DateTime` - /// overflowed `i32` epoch days. - MalformedDate { field: &'static str }, - /// A numeric field was non-finite (`NaN`, `±inf`) or violated its domain bound (`> 0` for - /// `splitratio`, `>= 0` for dividend cash). - InvalidNumber { field: &'static str, value: f64 }, - /// Buffer ended before a complete 4-byte length prefix or declared document body. - TruncatedDocument { - offset: usize, - remaining: usize, - declared_len: Option, - }, - /// Declared 4-byte little-endian BSON document length was `< 5` (or did not match a single - /// document slice). - CorruptDocumentLength { offset: usize, declared_len: i32 }, - /// Underlying BSON framing or element bytes were malformed. - CorruptBson { offset: usize, detail: String }, -} - -impl fmt::Display for BsonQmActionError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::MissingField { field } => { - write!(f, "qm action BSON missing required field '{field}'") - } - Self::EmptyField { field } => { - write!(f, "qm action BSON field '{field}' must not be empty or blank") - } - Self::WrongType { field, actual } => { - write!( - f, - "qm action BSON field '{field}' has unexpected BSON type {actual:?}" - ) - } - Self::MalformedDate { field } => { - write!( - f, - "qm action BSON field '{field}' is not a valid YYYY-MM-DD date or in-range DateTime" - ) - } - Self::InvalidNumber { field, value } => { - write!( - f, - "qm action BSON field '{field}' has invalid numeric value {value}" - ) - } - Self::TruncatedDocument { - offset, - remaining, - declared_len, - } => match declared_len { - Some(len) => write!( - f, - "truncated BSON document at byte offset {offset}: declared length {len} exceeds remaining {remaining} bytes" - ), - None => write!( - f, - "truncated BSON document header at byte offset {offset}: only {remaining} bytes remaining" - ), - }, - Self::CorruptDocumentLength { - offset, - declared_len, - } => write!( - f, - "corrupt BSON document length {declared_len} at byte offset {offset}" - ), - Self::CorruptBson { offset, detail } => { - write!(f, "corrupt BSON bytes at byte offset {offset}: {detail}") - } - } - } -} - -impl Error for BsonQmActionError {} - -#[inline] -fn map_framing_error(err: BsonEodPriceError) -> BsonQmActionError { - match err { - BsonEodPriceError::TruncatedDocument { - offset, - remaining, - declared_len, - } => BsonQmActionError::TruncatedDocument { - offset, - remaining, - declared_len, - }, - BsonEodPriceError::CorruptDocumentLength { - offset, - declared_len, - } => BsonQmActionError::CorruptDocumentLength { - offset, - declared_len, - }, - BsonEodPriceError::CorruptBson { offset, detail } => { - BsonQmActionError::CorruptBson { offset, detail } - } - BsonEodPriceError::MissingField { field } => BsonQmActionError::MissingField { field }, - BsonEodPriceError::EmptyField { field } => BsonQmActionError::EmptyField { field }, - BsonEodPriceError::WrongType { field, actual } => { - BsonQmActionError::WrongType { field, actual } - } - BsonEodPriceError::MalformedDate { field } => BsonQmActionError::MalformedDate { field }, - BsonEodPriceError::InvalidNumber { field, value } => { - BsonQmActionError::InvalidNumber { field, value } - } - } -} - -/// Per-batch decode and rejection accounting for [`decode_qm_split_buffer`] and -/// [`decode_qm_dividend_buffer`]. -/// -/// Conservation invariant: `decoded + rejected_total() == docs_in`. -/// `split_noop_ratio_one` counts decoded `qmSplits` documents with `ratio == 1.0` (a subset of -/// `decoded`, never added to `rejected_total()`). -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct BsonQmActionDecodeStats { - pub docs_in: usize, - pub decoded: usize, - /// Decoded `qmSplits` rows with `splitratio == 1.0` (subset of `decoded`). - pub split_noop_ratio_one: usize, - pub rejected_missing_field: usize, - pub rejected_empty_field: usize, - pub rejected_wrong_type: usize, - pub rejected_malformed_date: usize, - pub rejected_invalid_number: usize, - pub rejected_corrupt_document: usize, -} - -impl BsonQmActionDecodeStats { - /// Total number of rejected documents across all error categories. - #[inline] - pub fn rejected_total(&self) -> usize { - self.rejected_missing_field - + self.rejected_empty_field - + self.rejected_wrong_type - + self.rejected_malformed_date - + self.rejected_invalid_number - + self.rejected_corrupt_document - } - - /// Increments the rejection counter corresponding to `err`. - #[inline] - pub fn record_error(&mut self, err: &BsonQmActionError) { - match err { - BsonQmActionError::MissingField { .. } => self.rejected_missing_field += 1, - BsonQmActionError::EmptyField { .. } => self.rejected_empty_field += 1, - BsonQmActionError::WrongType { .. } => self.rejected_wrong_type += 1, - BsonQmActionError::MalformedDate { .. } => self.rejected_malformed_date += 1, - BsonQmActionError::InvalidNumber { .. } => self.rejected_invalid_number += 1, - BsonQmActionError::TruncatedDocument { .. } - | BsonQmActionError::CorruptDocumentLength { .. } - | BsonQmActionError::CorruptBson { .. } => self.rejected_corrupt_document += 1, - } - } - - /// Accumulates counters from another batch into `self`. - #[inline] - pub fn merge(&mut self, other: &Self) { - self.docs_in += other.docs_in; - self.decoded += other.decoded; - self.split_noop_ratio_one += other.split_noop_ratio_one; - self.rejected_missing_field += other.rejected_missing_field; - self.rejected_empty_field += other.rejected_empty_field; - self.rejected_wrong_type += other.rejected_wrong_type; - self.rejected_malformed_date += other.rejected_malformed_date; - self.rejected_invalid_number += other.rejected_invalid_number; - self.rejected_corrupt_document += other.rejected_corrupt_document; - } -} - -impl std::ops::AddAssign for BsonQmActionDecodeStats { - #[inline] - fn add_assign(&mut self, rhs: Self) { - self.merge(&rhs); - } -} - -#[inline] -fn decode_element_value<'a>( - field: &'static str, - elem: RawElement<'a>, - offset: usize, -) -> Result, BsonQmActionError> { - elem.value().map_err(|err| BsonQmActionError::CorruptBson { - offset, - detail: format!("field '{field}': {err}"), - }) -} - -#[inline] -fn decode_non_empty_str<'a>( - field: &'static str, - val: RawBsonRef<'a>, -) -> Result<&'a str, BsonQmActionError> { - match val { - RawBsonRef::String(s) => { - if s.trim().is_empty() { - return Err(BsonQmActionError::EmptyField { field }); - } - Ok(s) - } - other => Err(BsonQmActionError::WrongType { - field, - actual: other.element_type(), - }), - } -} - -#[inline] -fn decode_required_date( - field: &'static str, - val: RawBsonRef<'_>, -) -> Result { - match val { - RawBsonRef::String(s) => { - parse_ymd_strict_days(s).ok_or(BsonQmActionError::MalformedDate { field }) - } - RawBsonRef::DateTime(dt) => { - let days = dt.timestamp_millis().div_euclid(MILLIS_PER_DAY); - i32::try_from(days).map_err(|_| BsonQmActionError::MalformedDate { field }) - } - other => Err(BsonQmActionError::WrongType { - field, - actual: other.element_type(), - }), - } -} - -#[inline] -fn decode_optional_date( - field: &'static str, - val: RawBsonRef<'_>, -) -> Result, BsonQmActionError> { - match val { - RawBsonRef::Null => Ok(None), - RawBsonRef::String(s) => { - if s.trim().is_empty() { - return Ok(None); - } - parse_ymd_strict_days(s) - .map(Some) - .ok_or(BsonQmActionError::MalformedDate { field }) - } - RawBsonRef::DateTime(dt) => { - let days = dt.timestamp_millis().div_euclid(MILLIS_PER_DAY); - i32::try_from(days) - .map(Some) - .map_err(|_| BsonQmActionError::MalformedDate { field }) - } - other => Err(BsonQmActionError::WrongType { - field, - actual: other.element_type(), - }), - } -} - -#[inline] -fn decode_positive_number( - field: &'static str, - val: RawBsonRef<'_>, -) -> Result { - match val { - RawBsonRef::Double(v) => { - if !v.is_finite() || v <= 0.0 { - return Err(BsonQmActionError::InvalidNumber { field, value: v }); - } - Ok(v) - } - RawBsonRef::Int32(v) => { - if v <= 0 { - return Err(BsonQmActionError::InvalidNumber { - field, - value: f64::from(v), - }); - } - Ok(f64::from(v)) - } - RawBsonRef::Int64(v) => { - if v <= 0 { - return Err(BsonQmActionError::InvalidNumber { - field, - value: v as f64, - }); - } - Ok(v as f64) - } - other => Err(BsonQmActionError::WrongType { - field, - actual: other.element_type(), - }), - } -} - -#[inline] -fn decode_non_negative_number( - field: &'static str, - val: RawBsonRef<'_>, -) -> Result { - match val { - RawBsonRef::Double(v) => { - if !v.is_finite() || v < 0.0 { - return Err(BsonQmActionError::InvalidNumber { field, value: v }); - } - if v == 0.0 { - Ok(0.0) - } else { - Ok(v) - } - } - RawBsonRef::Int32(v) => { - if v < 0 { - return Err(BsonQmActionError::InvalidNumber { - field, - value: f64::from(v), - }); - } - Ok(f64::from(v)) - } - RawBsonRef::Int64(v) => { - if v < 0 { - return Err(BsonQmActionError::InvalidNumber { - field, - value: v as f64, - }); - } - Ok(v as f64) - } - other => Err(BsonQmActionError::WrongType { - field, - actual: other.element_type(), - }), - } -} - -#[inline] -fn decode_optional_positive_factor(val: RawBsonRef<'_>) -> Option { - match val { - RawBsonRef::Double(v) if v.is_finite() && v > 0.0 => Some(v), - RawBsonRef::Int32(v) if v > 0 => Some(f64::from(v)), - RawBsonRef::Int64(v) if v > 0 => Some(v as f64), - _ => None, - } -} - -fn decode_qm_split_doc_at<'a>( - doc: &'a RawDocument, - offset: usize, -) -> Result, BsonQmActionError> { - let mut qm_search_code: Option<&'a str> = None; - let mut ex_date: Option = None; - let mut raw_split_ratio: Option = None; - let mut for_factor: Option = None; - let mut to_factor: Option = None; - let mut declared_date: Option = None; - - for elem_res in doc.iter_elements() { - let elem = elem_res.map_err(|err| BsonQmActionError::CorruptBson { - offset, - detail: err.to_string(), - })?; - let key = elem.key().as_str(); - - if key == FIELD_QM_SEARCH_CODE { - let val = decode_element_value(FIELD_QM_SEARCH_CODE, elem, offset)?; - qm_search_code = Some(decode_non_empty_str(FIELD_QM_SEARCH_CODE, val)?); - } else if key == FIELD_DATE { - let val = decode_element_value(FIELD_DATE, elem, offset)?; - ex_date = Some(decode_required_date(FIELD_DATE, val)?); - } else if key == FIELD_SPLIT_RATIO { - let val = decode_element_value(FIELD_SPLIT_RATIO, elem, offset)?; - raw_split_ratio = Some(decode_positive_number(FIELD_SPLIT_RATIO, val)?); - } else if key == FIELD_FOR_FACTOR { - let val = decode_element_value(FIELD_FOR_FACTOR, elem, offset)?; - for_factor = decode_optional_positive_factor(val); - } else if key == FIELD_TO_FACTOR { - let val = decode_element_value(FIELD_TO_FACTOR, elem, offset)?; - to_factor = decode_optional_positive_factor(val); - } else if key == FIELD_DECLARED { - let val = decode_element_value(FIELD_DECLARED, elem, offset)?; - declared_date = decode_optional_date(FIELD_DECLARED, val)?; - } - // `FIELD_USD_FX_RATE` and all unknown extra fields are skipped without calling `elem.value()`. - } - - let Some(qm_search_code) = qm_search_code else { - return Err(BsonQmActionError::MissingField { - field: FIELD_QM_SEARCH_CODE, - }); - }; - let Some(ex_date) = ex_date else { - return Err(BsonQmActionError::MissingField { field: FIELD_DATE }); - }; - let Some(raw_split_ratio) = raw_split_ratio else { - return Err(BsonQmActionError::MissingField { - field: FIELD_SPLIT_RATIO, - }); - }; - - // QuoteMedia stores `splitratio = forfactor / tofactor = old_shares / new_shares`. - // Convert to canonical `new_shares / old_shares`, preferring exact `tofactor / forfactor` - // when both are present and positive. - let ratio = match (for_factor, to_factor) { - (Some(f), Some(t)) => { - let exact = t / f; - if exact.is_finite() && exact > 0.0 { - exact - } else { - 1.0 / raw_split_ratio - } - } - _ => 1.0 / raw_split_ratio, - }; - if !ratio.is_finite() || ratio <= 0.0 { - return Err(BsonQmActionError::InvalidNumber { - field: FIELD_SPLIT_RATIO, - value: raw_split_ratio, - }); - } - - Ok(RawQmSplit { - qm_search_code, - ex_date, - ratio, - declared_date, - }) -} - -fn decode_qm_dividend_doc_at<'a>( - doc: &'a RawDocument, - offset: usize, -) -> Result, BsonQmActionError> { - let mut qm_search_code: Option<&'a str> = None; - let mut ex_date: Option = None; - let mut cash: Option = None; - let mut currency: Option<&'a str> = None; - let mut declared_date: Option = None; - - for elem_res in doc.iter_elements() { - let elem = elem_res.map_err(|err| BsonQmActionError::CorruptBson { - offset, - detail: err.to_string(), - })?; - let key = elem.key().as_str(); - - if key == FIELD_QM_SEARCH_CODE { - let val = decode_element_value(FIELD_QM_SEARCH_CODE, elem, offset)?; - qm_search_code = Some(decode_non_empty_str(FIELD_QM_SEARCH_CODE, val)?); - } else if key == FIELD_DATE { - let val = decode_element_value(FIELD_DATE, elem, offset)?; - ex_date = Some(decode_required_date(FIELD_DATE, val)?); - } else if key == FIELD_DIVIDEND_CASH { - let val = decode_element_value(FIELD_DIVIDEND_CASH, elem, offset)?; - cash = Some(decode_non_negative_number(FIELD_DIVIDEND_CASH, val)?); - } else if key == FIELD_DIVIDEND_CURRENCY { - let val = decode_element_value(FIELD_DIVIDEND_CURRENCY, elem, offset)?; - currency = Some(decode_non_empty_str(FIELD_DIVIDEND_CURRENCY, val)?); - } else if key == FIELD_DECLARED { - let val = decode_element_value(FIELD_DECLARED, elem, offset)?; - declared_date = decode_optional_date(FIELD_DECLARED, val)?; - } - // `FIELD_USD_FX_RATE` and all unknown extra fields are skipped without calling `elem.value()`. - } - - let Some(qm_search_code) = qm_search_code else { - return Err(BsonQmActionError::MissingField { - field: FIELD_QM_SEARCH_CODE, - }); - }; - let Some(ex_date) = ex_date else { - return Err(BsonQmActionError::MissingField { field: FIELD_DATE }); - }; - let Some(cash) = cash else { - return Err(BsonQmActionError::MissingField { - field: FIELD_DIVIDEND_CASH, - }); - }; - let Some(currency) = currency else { - return Err(BsonQmActionError::MissingField { - field: FIELD_DIVIDEND_CURRENCY, - }); - }; - - Ok(RawQmDividend { - qm_search_code, - ex_date, - cash, - currency, - declared_date, - }) -} - -/// Decodes a single `&RawDocument` representing a `qmSplits` MongoDB document in one forward pass -/// without allocating a `String` or owned `bson::Document`. -#[inline] -pub fn decode_qm_split_doc<'a>(doc: &'a RawDocument) -> Result, BsonQmActionError> { - decode_qm_split_doc_at(doc, 0) -} - -/// Decodes a single length-prefixed raw BSON document byte slice into a borrowed [`RawQmSplit`]. -pub fn decode_qm_split_bytes<'a>(bytes: &'a [u8]) -> Result, BsonQmActionError> { - let doc = parse_single_raw_doc(bytes).map_err(map_framing_error)?; - decode_qm_split_doc_at(doc, 0) -} - -/// Decodes a single `&RawDocument` representing a `qmDividends` MongoDB document in one forward -/// pass without allocating a `String` or owned `bson::Document`. -#[inline] -pub fn decode_qm_dividend_doc<'a>( - doc: &'a RawDocument, -) -> Result, BsonQmActionError> { - decode_qm_dividend_doc_at(doc, 0) -} - -/// Decodes a single length-prefixed raw BSON document byte slice into a borrowed -/// [`RawQmDividend`]. -pub fn decode_qm_dividend_bytes<'a>( - bytes: &'a [u8], -) -> Result, BsonQmActionError> { - let doc = parse_single_raw_doc(bytes).map_err(map_framing_error)?; - decode_qm_dividend_doc_at(doc, 0) -} - -/// Streams a concatenated length-prefixed BSON buffer through [`decode_qm_split_doc`], invoking -/// `on_split` for every valid document (including `splitratio == 1.0`, counted in -/// `stats.split_noop_ratio_one`) and `on_error(byte_offset, err)` for every rejected document -/// without aborting the stream on per-document errors. -/// -/// Always maintains `stats.decoded + stats.rejected_total() == stats.docs_in`. -pub fn decode_qm_split_buffer<'a, F, E>( - buf: &'a [u8], - mut on_split: F, - mut on_error: E, -) -> BsonQmActionDecodeStats -where - F: FnMut(RawQmSplit<'a>), - E: FnMut(usize, BsonQmActionError), -{ - let mut stats = BsonQmActionDecodeStats::default(); - let mut iter = iter_raw_bson_docs(buf); - - while let Some(item) = iter.next_with_offset() { - stats.docs_in += 1; - match item { - Ok((doc_offset, doc)) => match decode_qm_split_doc_at(doc, doc_offset) { - Ok(split) => { - stats.decoded += 1; - if split.ratio == 1.0 { - stats.split_noop_ratio_one += 1; - } - on_split(split); - } - Err(err) => { - stats.record_error(&err); - on_error(doc_offset, err); - } - }, - Err((doc_offset, err)) => { - let mapped = map_framing_error(err); - stats.record_error(&mapped); - on_error(doc_offset, mapped); - } - } - } - - stats -} - -/// Streams a concatenated length-prefixed BSON buffer through [`decode_qm_dividend_doc`], invoking -/// `on_dividend` for every valid document and `on_error(byte_offset, err)` for every rejected -/// document without aborting the stream on per-document errors. -/// -/// Always maintains `stats.decoded + stats.rejected_total() == stats.docs_in`. -pub fn decode_qm_dividend_buffer<'a, F, E>( - buf: &'a [u8], - mut on_dividend: F, - mut on_error: E, -) -> BsonQmActionDecodeStats -where - F: FnMut(RawQmDividend<'a>), - E: FnMut(usize, BsonQmActionError), -{ - let mut stats = BsonQmActionDecodeStats::default(); - let mut iter = iter_raw_bson_docs(buf); - - while let Some(item) = iter.next_with_offset() { - stats.docs_in += 1; - match item { - Ok((doc_offset, doc)) => match decode_qm_dividend_doc_at(doc, doc_offset) { - Ok(dividend) => { - stats.decoded += 1; - on_dividend(dividend); - } - Err(err) => { - stats.record_error(&err); - on_error(doc_offset, err); - } - }, - Err((doc_offset, err)) => { - let mapped = map_framing_error(err); - stats.record_error(&mapped); - on_error(doc_offset, mapped); - } - } - } - - stats -} - -#[cfg(test)] -#[path = "bson_qm_actions_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/bson_qm_actions_tests.rs b/tools/curate-etl/src/bson_qm_actions_tests.rs deleted file mode 100644 index e49a76fe..00000000 --- a/tools/curate-etl/src/bson_qm_actions_tests.rs +++ /dev/null @@ -1,918 +0,0 @@ -use bson::oid::ObjectId; -use bson::raw::{cstr, RawArrayBuf, RawBsonRef, RawDocumentBuf}; -use bson::spec::ElementType; -use bson::DateTime; - -use super::*; -use crate::corporate_actions::{build_corporate_actions, CorporateActionKind, KnownAtSource}; -use crate::curate_adj::curate_adj_factors; -use crate::provider_mapping::{ProviderMappingRow, ProviderMappingTable}; -use crate::split::{ymd_to_epoch_days, SplitTable}; - -fn day(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).unwrap() -} - -fn make_split_doc(code: &str, date: &str, ratio: f64, declared: Option<&str>) -> RawDocumentBuf { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), code); - doc.append(cstr!("date"), date); - if ratio.is_finite() && ratio > 0.0 { - doc.append(cstr!("splitratio"), 1.0 / ratio); - doc.append(cstr!("forfactor"), 1.0_f64); - doc.append(cstr!("tofactor"), ratio); - } else { - doc.append(cstr!("splitratio"), ratio); - } - if let Some(decl) = declared { - doc.append(cstr!("declared"), decl); - } - doc -} - -fn make_dividend_doc( - code: &str, - date: &str, - cash: f64, - currency: &str, - declared: Option<&str>, -) -> RawDocumentBuf { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), code); - doc.append(cstr!("date"), date); - doc.append(cstr!("amount"), cash); - doc.append(cstr!("currency"), currency); - if let Some(decl) = declared { - doc.append(cstr!("declared"), decl); - } - doc -} - -#[test] -fn decodes_realistic_qm_split_and_dividend_docs_and_ignores_extra_and_usd_fx_rate() { - let mut nested = RawDocumentBuf::new(); - nested.append(cstr!("provider"), "quotemedia"); - nested.append(cstr!("version"), 1_i32); - - let mut tags = RawArrayBuf::new(); - tags.push("ca"); - tags.push("equity"); - - // Realistic qmSplits document with extra metadata and bogus usdFxRate. - let mut split_doc = RawDocumentBuf::new(); - split_doc.append( - cstr!("_id"), - ObjectId::from_bytes([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]), - ); - split_doc.append(cstr!("symbol"), "NVDA"); - split_doc.append(cstr!("exchange"), "NASDAQ"); - split_doc.append(cstr!("qmSearchCode"), "NVDA"); - split_doc.append(cstr!("date"), "2024-06-10"); - split_doc.append(cstr!("declared"), "2024-05-22"); - split_doc.append(cstr!("forfactor"), 1_i32); - split_doc.append(cstr!("tofactor"), 10_i32); - split_doc.append(cstr!("splitratio"), 0.1_f64); - split_doc.append(cstr!("usdFxRate"), "bogus-ignored-type"); - split_doc.append( - cstr!("reportDate"), - DateTime::from_millis(i64::from(day(2024, 6, 10)) * MILLIS_PER_DAY), - ); - split_doc.append(cstr!("created_at"), DateTime::from_millis(1_718_000_000_000)); - split_doc.append(cstr!("updated_at"), DateTime::from_millis(1_718_000_060_000)); - split_doc.append(cstr!("meta"), RawBsonRef::Document(nested.as_ref())); - split_doc.append(cstr!("tags"), RawBsonRef::Array(tags.as_ref())); - - let split = decode_qm_split_doc(&split_doc).unwrap(); - assert_eq!(split.qm_search_code, "NVDA"); - assert_eq!(split.ex_date, day(2024, 6, 10)); - assert_eq!(split.ratio.to_bits(), 10.0_f64.to_bits()); - assert_eq!(split.declared_date, Some(day(2024, 5, 22))); - assert_eq!(decode_qm_split_bytes(split_doc.as_bytes()).unwrap(), split); - - // Realistic qmDividends document with bogus usdFxRate: 1 on CAD row. - let mut div_doc = RawDocumentBuf::new(); - div_doc.append( - cstr!("_id"), - ObjectId::from_bytes([12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]), - ); - div_doc.append(cstr!("symbol"), "RY"); - div_doc.append(cstr!("exchange"), "TSX"); - div_doc.append(cstr!("qmSearchCode"), "RY:CA"); - div_doc.append(cstr!("date"), "2024-11-15"); - div_doc.append(cstr!("declared"), "2024-10-30"); - div_doc.append(cstr!("amount"), 1.42_f64); - div_doc.append(cstr!("currency"), "CAD"); - div_doc.append(cstr!("usdFxRate"), 1_i32); - div_doc.append( - cstr!("reportDate"), - DateTime::from_millis(i64::from(day(2024, 11, 15)) * MILLIS_PER_DAY), - ); - div_doc.append(cstr!("meta"), RawBsonRef::Document(nested.as_ref())); - div_doc.append(cstr!("tags"), RawBsonRef::Array(tags.as_ref())); - - let div = decode_qm_dividend_doc(&div_doc).unwrap(); - assert_eq!(div.qm_search_code, "RY:CA"); - assert_eq!(div.ex_date, day(2024, 11, 15)); - assert_eq!(div.cash.to_bits(), 1.42_f64.to_bits()); - assert_eq!(div.currency, "CAD"); - assert_eq!(div.declared_date, Some(day(2024, 10, 30))); - assert_eq!(decode_qm_dividend_bytes(div_doc.as_bytes()).unwrap(), div); -} - -#[test] -fn decodes_date_and_declared_as_string_and_datetime_including_pre_1970_and_leap_day() { - // Pre-1970 mid-day: 1969-12-31T12:34:56.789Z must floor to epoch day -1 (not 0). - let pre_1970_ex_ms: i64 = -MILLIS_PER_DAY + (12 * 3600 + 34 * 60 + 56) * 1000 + 789; - let pre_1970_decl_ms: i64 = -10 * MILLIS_PER_DAY + 43_200_000; - - let mut split_dt = RawDocumentBuf::new(); - split_dt.append(cstr!("qmSearchCode"), "IBM"); - split_dt.append(cstr!("date"), DateTime::from_millis(pre_1970_ex_ms)); - split_dt.append(cstr!("declared"), DateTime::from_millis(pre_1970_decl_ms)); - split_dt.append(cstr!("splitratio"), 0.5_f64); - - let split = decode_qm_split_doc(&split_dt).unwrap(); - assert_eq!(split.ex_date, -1); - assert_eq!(split.declared_date, Some(-10)); - assert_eq!(split.ratio, 2.0); - - // Leap day string + DateTime declared. - let mut div_leap = RawDocumentBuf::new(); - div_leap.append(cstr!("qmSearchCode"), "TD:CA"); - div_leap.append(cstr!("date"), "2024-02-29"); - div_leap.append( - cstr!("declared"), - DateTime::from_millis(i64::from(day(2024, 2, 1)) * MILLIS_PER_DAY + 36_000_000), - ); - div_leap.append(cstr!("amount"), 1.02_f64); - div_leap.append(cstr!("currency"), "CAD"); - - let div = decode_qm_dividend_doc(&div_leap).unwrap(); - assert_eq!(div.ex_date, day(2024, 2, 29)); - assert_eq!(div.declared_date, Some(day(2024, 2, 1))); -} - -#[test] -fn decodes_double_int32_int64_numerics_and_normalizes_negative_zero_cash() { - // Splits: Double, Int32, Int64 (QuoteMedia stores old_shares / new_shares, inverted to new/old). - for (val, expected) in [ - (RawBsonRef::Double(20.0), 0.05_f64), - (RawBsonRef::Int32(4), 0.25_f64), - (RawBsonRef::Int64(10), 0.1_f64), - ] { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), "TEST"); - doc.append(cstr!("date"), "2024-06-10"); - doc.append(cstr!("splitratio"), val); - let decoded = decode_qm_split_doc(&doc).unwrap(); - assert_eq!(decoded.ratio.to_bits(), expected.to_bits()); - } - - // Exact forfactor / tofactor precedence over truncated splitratio (e.g. AAPL 7:1, GE 1:8, NVDA 2:1 empty). - { - let mut aapl = RawDocumentBuf::new(); - aapl.append(cstr!("qmSearchCode"), "AAPL"); - aapl.append(cstr!("date"), "2014-06-09"); - aapl.append(cstr!("forfactor"), 1_i32); - aapl.append(cstr!("tofactor"), 7_i32); - aapl.append(cstr!("splitratio"), 0.142857_f64); - assert_eq!(decode_qm_split_doc(&aapl).unwrap().ratio, 7.0); - - let mut ge = RawDocumentBuf::new(); - ge.append(cstr!("qmSearchCode"), "GE"); - ge.append(cstr!("date"), "2021-08-02"); - ge.append(cstr!("forfactor"), 8_i32); - ge.append(cstr!("tofactor"), 1_i32); - ge.append(cstr!("splitratio"), 8_i32); - assert_eq!(decode_qm_split_doc(&ge).unwrap().ratio, 0.125); - - let mut nvda_legacy = RawDocumentBuf::new(); - nvda_legacy.append(cstr!("qmSearchCode"), "NVDA"); - nvda_legacy.append(cstr!("date"), "2000-06-27"); - nvda_legacy.append(cstr!("forfactor"), ""); - nvda_legacy.append(cstr!("tofactor"), ""); - nvda_legacy.append(cstr!("splitratio"), 0.5_f64); - assert_eq!(decode_qm_split_doc(&nvda_legacy).unwrap().ratio, 2.0); - } - - // Dividends: Double, Int32, Int64, 0, and -0.0 -> +0.0. - for (val, expected) in [ - (RawBsonRef::Double(0.25), 0.25_f64), - (RawBsonRef::Double(-0.0), 0.0_f64), - (RawBsonRef::Double(0.0), 0.0_f64), - (RawBsonRef::Int32(0), 0.0_f64), - (RawBsonRef::Int32(2), 2.0_f64), - (RawBsonRef::Int64(0), 0.0_f64), - (RawBsonRef::Int64(5), 5.0_f64), - ] { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), "TEST"); - doc.append(cstr!("date"), "2024-06-10"); - doc.append(cstr!("amount"), val); - doc.append(cstr!("currency"), "USD"); - let decoded = decode_qm_dividend_doc(&doc).unwrap(); - assert_eq!(decoded.cash.to_bits(), expected.to_bits()); - assert!(!decoded.cash.is_sign_negative()); - } -} - -#[test] -fn handles_optional_declared_missing_null_empty_malformed_and_wrong_type() { - // Missing declared -> None. - let s_missing = make_split_doc("AAPL", "2020-08-31", 4.0, None); - assert_eq!(decode_qm_split_doc(&s_missing).unwrap().declared_date, None); - - // Null declared -> None. - let mut s_null = make_split_doc("AAPL", "2020-08-31", 4.0, None); - s_null.append(cstr!("declared"), RawBsonRef::Null); - assert_eq!(decode_qm_split_doc(&s_null).unwrap().declared_date, None); - - // Empty and whitespace-only declared -> None. - for blank in ["", " ", "\t\n"] { - let d_blank = make_dividend_doc("AAPL", "2024-08-12", 0.25, "USD", Some(blank)); - assert_eq!( - decode_qm_dividend_doc(&d_blank).unwrap().declared_date, - None - ); - } - - // Malformed declared -> MalformedDate naming "declared". - let s_bad = make_split_doc("AAPL", "2020-08-31", 4.0, Some("2023-02-29")); - let err = decode_qm_split_doc(&s_bad).unwrap_err(); - assert_eq!( - err, - BsonQmActionError::MalformedDate { - field: FIELD_DECLARED - } - ); - assert!(err.to_string().contains(FIELD_DECLARED)); - - // Wrong type on declared -> WrongType naming "declared". - let mut d_wrong = make_dividend_doc("AAPL", "2024-08-12", 0.25, "USD", None); - d_wrong.append(cstr!("declared"), 20240801_i32); - let err = decode_qm_dividend_doc(&d_wrong).unwrap_err(); - assert_eq!( - err, - BsonQmActionError::WrongType { - field: FIELD_DECLARED, - actual: ElementType::Int32, - } - ); - assert!(err.to_string().contains(FIELD_DECLARED)); -} - -#[test] -fn split_ratio_one_is_decoded_not_dropped_and_counted_as_noop() { - let mut buf = Vec::new(); - for val in [ - RawBsonRef::Double(1.0), - RawBsonRef::Int32(1), - RawBsonRef::Int64(1), - RawBsonRef::Double(0.5), - ] { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), "NOOP"); - doc.append(cstr!("date"), "2024-03-15"); - doc.append(cstr!("splitratio"), val); - buf.extend_from_slice(doc.as_bytes()); - } - - let mut decoded_ratios = Vec::new(); - let stats = decode_qm_split_buffer( - &buf, - |s| decoded_ratios.push(s.ratio), - |_, err| panic!("unexpected error: {err}"), - ); - - assert_eq!(decoded_ratios, vec![1.0, 1.0, 1.0, 2.0]); - assert_eq!(stats.docs_in, 4); - assert_eq!(stats.decoded, 4); - assert_eq!(stats.split_noop_ratio_one, 3); - assert_eq!(stats.rejected_total(), 0); - assert_eq!(stats.decoded + stats.rejected_total(), stats.docs_in); -} - -#[test] -fn rejects_every_error_variant_and_names_offending_field() { - // 1. Missing required fields on splits. - { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("date"), "2024-06-10"); - doc.append(cstr!("splitratio"), 2.0_f64); - let err = decode_qm_split_doc(&doc).unwrap_err(); - assert_eq!( - err, - BsonQmActionError::MissingField { - field: FIELD_QM_SEARCH_CODE - } - ); - assert!(err.to_string().contains(FIELD_QM_SEARCH_CODE)); - } - { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), "NVDA"); - doc.append(cstr!("splitratio"), 2.0_f64); - let err = decode_qm_split_doc(&doc).unwrap_err(); - assert_eq!(err, BsonQmActionError::MissingField { field: FIELD_DATE }); - assert!(err.to_string().contains(FIELD_DATE)); - } - { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), "NVDA"); - doc.append(cstr!("date"), "2024-06-10"); - let err = decode_qm_split_doc(&doc).unwrap_err(); - assert_eq!( - err, - BsonQmActionError::MissingField { - field: FIELD_SPLIT_RATIO - } - ); - assert!(err.to_string().contains(FIELD_SPLIT_RATIO)); - } - - // 2. Missing required fields on dividends. - { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("date"), "2024-06-10"); - doc.append(cstr!("amount"), 0.5_f64); - doc.append(cstr!("currency"), "USD"); - let err = decode_qm_dividend_doc(&doc).unwrap_err(); - assert_eq!( - err, - BsonQmActionError::MissingField { - field: FIELD_QM_SEARCH_CODE - } - ); - assert!(err.to_string().contains(FIELD_QM_SEARCH_CODE)); - } - { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), "RY:CA"); - doc.append(cstr!("amount"), 0.5_f64); - doc.append(cstr!("currency"), "CAD"); - let err = decode_qm_dividend_doc(&doc).unwrap_err(); - assert_eq!(err, BsonQmActionError::MissingField { field: FIELD_DATE }); - assert!(err.to_string().contains(FIELD_DATE)); - } - { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), "RY:CA"); - doc.append(cstr!("date"), "2024-06-10"); - doc.append(cstr!("currency"), "CAD"); - let err = decode_qm_dividend_doc(&doc).unwrap_err(); - assert_eq!( - err, - BsonQmActionError::MissingField { - field: FIELD_DIVIDEND_CASH - } - ); - assert!(err.to_string().contains(FIELD_DIVIDEND_CASH)); - } - { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), "RY:CA"); - doc.append(cstr!("date"), "2024-06-10"); - doc.append(cstr!("amount"), 0.5_f64); - let err = decode_qm_dividend_doc(&doc).unwrap_err(); - assert_eq!( - err, - BsonQmActionError::MissingField { - field: FIELD_DIVIDEND_CURRENCY - } - ); - assert!(err.to_string().contains(FIELD_DIVIDEND_CURRENCY)); - } - - // 3. Empty / whitespace-only string fields. - for blank in ["", " ", "\t\n"] { - let s = make_split_doc(blank, "2024-06-10", 2.0, None); - let err = decode_qm_split_doc(&s).unwrap_err(); - assert_eq!( - err, - BsonQmActionError::EmptyField { - field: FIELD_QM_SEARCH_CODE - } - ); - assert!(err.to_string().contains(FIELD_QM_SEARCH_CODE)); - - let d = make_dividend_doc("RY:CA", "2024-06-10", 0.5, blank, None); - let err = decode_qm_dividend_doc(&d).unwrap_err(); - assert_eq!( - err, - BsonQmActionError::EmptyField { - field: FIELD_DIVIDEND_CURRENCY - } - ); - assert!(err.to_string().contains(FIELD_DIVIDEND_CURRENCY)); - } - - // 4. Wrong BSON types (including string-encoded numerics). - { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), 123_i32); - doc.append(cstr!("date"), "2024-06-10"); - doc.append(cstr!("splitratio"), 2.0_f64); - let err = decode_qm_split_doc(&doc).unwrap_err(); - assert_eq!( - err, - BsonQmActionError::WrongType { - field: FIELD_QM_SEARCH_CODE, - actual: ElementType::Int32, - } - ); - assert!(err.to_string().contains(FIELD_QM_SEARCH_CODE)); - } - { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), "NVDA"); - doc.append(cstr!("date"), 20240610_i32); - doc.append(cstr!("splitratio"), 2.0_f64); - let err = decode_qm_split_doc(&doc).unwrap_err(); - assert_eq!( - err, - BsonQmActionError::WrongType { - field: FIELD_DATE, - actual: ElementType::Int32, - } - ); - assert!(err.to_string().contains(FIELD_DATE)); - } - { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), "NVDA"); - doc.append(cstr!("date"), "2024-06-10"); - doc.append(cstr!("splitratio"), "10.0"); - let err = decode_qm_split_doc(&doc).unwrap_err(); - assert_eq!( - err, - BsonQmActionError::WrongType { - field: FIELD_SPLIT_RATIO, - actual: ElementType::String, - } - ); - assert!(err.to_string().contains(FIELD_SPLIT_RATIO)); - } - { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), "RY:CA"); - doc.append(cstr!("date"), "2024-06-10"); - doc.append(cstr!("amount"), "1.42"); - doc.append(cstr!("currency"), "CAD"); - let err = decode_qm_dividend_doc(&doc).unwrap_err(); - assert_eq!( - err, - BsonQmActionError::WrongType { - field: FIELD_DIVIDEND_CASH, - actual: ElementType::String, - } - ); - assert!(err.to_string().contains(FIELD_DIVIDEND_CASH)); - } - { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), "RY:CA"); - doc.append(cstr!("date"), "2024-06-10"); - doc.append(cstr!("amount"), 1.42_f64); - doc.append(cstr!("currency"), true); - let err = decode_qm_dividend_doc(&doc).unwrap_err(); - assert_eq!( - err, - BsonQmActionError::WrongType { - field: FIELD_DIVIDEND_CURRENCY, - actual: ElementType::Boolean, - } - ); - assert!(err.to_string().contains(FIELD_DIVIDEND_CURRENCY)); - } - - // 5. Malformed dates (bad calendar date, bad format, and DateTime overflowing i32 days). - for bad_date in ["2023-02-29", "2024/06/10", "2024-6-10", "not-a-date"] { - let doc = make_split_doc("NVDA", bad_date, 2.0, None); - let err = decode_qm_split_doc(&doc).unwrap_err(); - assert_eq!(err, BsonQmActionError::MalformedDate { field: FIELD_DATE }); - assert!(err.to_string().contains(FIELD_DATE)); - } - { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), "NVDA"); - doc.append(cstr!("date"), DateTime::from_millis(i64::MAX)); - doc.append(cstr!("splitratio"), 2.0_f64); - let err = decode_qm_split_doc(&doc).unwrap_err(); - assert_eq!(err, BsonQmActionError::MalformedDate { field: FIELD_DATE }); - } - { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), "NVDA"); - doc.append(cstr!("date"), "2024-06-10"); - doc.append(cstr!("declared"), DateTime::from_millis(i64::MIN)); - doc.append(cstr!("splitratio"), 2.0_f64); - let err = decode_qm_split_doc(&doc).unwrap_err(); - assert_eq!( - err, - BsonQmActionError::MalformedDate { - field: FIELD_DECLARED - } - ); - } - - // 6. Invalid numeric values for splitratio (<= 0 or non-finite). - for bad_ratio in [ - RawBsonRef::Double(f64::NAN), - RawBsonRef::Double(f64::INFINITY), - RawBsonRef::Double(f64::NEG_INFINITY), - RawBsonRef::Double(0.0), - RawBsonRef::Double(-0.0), - RawBsonRef::Double(-2.0), - RawBsonRef::Int32(0), - RawBsonRef::Int32(-1), - RawBsonRef::Int64(0), - RawBsonRef::Int64(-5), - ] { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), "NVDA"); - doc.append(cstr!("date"), "2024-06-10"); - doc.append(cstr!("splitratio"), bad_ratio); - let err = decode_qm_split_doc(&doc).unwrap_err(); - assert!( - matches!( - err, - BsonQmActionError::InvalidNumber { - field: FIELD_SPLIT_RATIO, - .. - } - ), - "expected InvalidNumber for {bad_ratio:?}, got {err:?}" - ); - assert!(err.to_string().contains(FIELD_SPLIT_RATIO)); - } - - // 7. Invalid numeric values for dividend cash (< 0 or non-finite). - for bad_cash in [ - RawBsonRef::Double(f64::NAN), - RawBsonRef::Double(f64::INFINITY), - RawBsonRef::Double(f64::NEG_INFINITY), - RawBsonRef::Double(-0.01), - RawBsonRef::Int32(-1), - RawBsonRef::Int64(-10), - ] { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), "RY:CA"); - doc.append(cstr!("date"), "2024-06-10"); - doc.append(cstr!("amount"), bad_cash); - doc.append(cstr!("currency"), "CAD"); - let err = decode_qm_dividend_doc(&doc).unwrap_err(); - assert!( - matches!( - err, - BsonQmActionError::InvalidNumber { - field: FIELD_DIVIDEND_CASH, - .. - } - ), - "expected InvalidNumber for {bad_cash:?}, got {err:?}" - ); - assert!(err.to_string().contains(FIELD_DIVIDEND_CASH)); - } - - // 8. Truncated and corrupt documents (zero panics). - assert!(matches!( - decode_qm_split_bytes(&[]), - Err(BsonQmActionError::TruncatedDocument { - offset: 0, - remaining: 0, - declared_len: None - }) - )); - assert!(matches!( - decode_qm_dividend_bytes(&[1, 2, 3]), - Err(BsonQmActionError::TruncatedDocument { - offset: 0, - remaining: 3, - declared_len: None - }) - )); - assert!(matches!( - decode_qm_split_bytes(&4_i32.to_le_bytes()), - Err(BsonQmActionError::CorruptDocumentLength { - offset: 0, - declared_len: 4 - }) - )); - let valid_bytes = make_split_doc("NVDA", "2024-06-10", 10.0, None) - .as_bytes() - .to_vec(); - assert!(matches!( - decode_qm_split_bytes(&valid_bytes[..valid_bytes.len() - 1]), - Err(BsonQmActionError::TruncatedDocument { - offset: 0, - declared_len: Some(_), - .. - }) - )); - let mut with_trailing = valid_bytes.clone(); - with_trailing.push(0); - assert!(matches!( - decode_qm_split_bytes(&with_trailing), - Err(BsonQmActionError::CorruptDocumentLength { offset: 0, .. }) - )); - let mut bad_terminator = valid_bytes; - *bad_terminator.last_mut().unwrap() = 0xFF; - assert!(matches!( - decode_qm_split_bytes(&bad_terminator), - Err(BsonQmActionError::CorruptBson { offset: 0, .. }) - )); - - // Invalid UTF-8 inside a known string field (`qmSearchCode`). - let mut invalid_utf8_doc: Vec = Vec::new(); - // Placeholder 4-byte length. - invalid_utf8_doc.extend_from_slice(&0_i32.to_le_bytes()); - invalid_utf8_doc.push(0x02); // UTF-8 String element - invalid_utf8_doc.extend_from_slice(b"qmSearchCode\0"); - invalid_utf8_doc.extend_from_slice(&3_i32.to_le_bytes()); // 2 bytes + NUL - invalid_utf8_doc.extend_from_slice(&[0xFF, 0xFE, 0x00]); - invalid_utf8_doc.push(0x00); // doc terminator - let total_len = invalid_utf8_doc.len() as i32; - invalid_utf8_doc[0..4].copy_from_slice(&total_len.to_le_bytes()); - let err = decode_qm_split_bytes(&invalid_utf8_doc).unwrap_err(); - assert!(matches!(err, BsonQmActionError::CorruptBson { offset: 0, .. })); - assert!(err.to_string().contains(FIELD_QM_SEARCH_CODE)); -} - -#[test] -fn buffer_decoders_survive_per_doc_errors_and_reconcile_stats_for_both_collections() { - // 1. qmSplits mixed valid/invalid buffer. - let s1 = make_split_doc("NVDA", "2024-06-10", 10.0, Some("2024-05-22")); - let s_noop = make_split_doc("NOOP", "2024-06-11", 1.0, None); - let mut s_missing = RawDocumentBuf::new(); - s_missing.append(cstr!("qmSearchCode"), "MISS"); - s_missing.append(cstr!("date"), "2024-06-12"); - let s_empty = make_split_doc(" ", "2024-06-13", 2.0, None); - let mut s_wrong = RawDocumentBuf::new(); - s_wrong.append(cstr!("qmSearchCode"), "WRNG"); - s_wrong.append(cstr!("date"), "2024-06-14"); - s_wrong.append(cstr!("splitratio"), "2.0"); - let s_bad_date = make_split_doc("DATE", "2023-02-29", 2.0, None); - let s_bad_num = make_split_doc("NUM", "2024-06-15", 0.0, None); - let mut s_corrupt = make_split_doc("CORR", "2024-06-16", 2.0, None) - .as_bytes() - .to_vec(); - *s_corrupt.last_mut().unwrap() = 0xAA; - let s2 = make_split_doc("NEXM:CA", "2025-06-18", 0.05, None); - - let mut split_buf = Vec::new(); - split_buf.extend_from_slice(s1.as_bytes()); - split_buf.extend_from_slice(s_noop.as_bytes()); - split_buf.extend_from_slice(s_missing.as_bytes()); - split_buf.extend_from_slice(s_empty.as_bytes()); - split_buf.extend_from_slice(s_wrong.as_bytes()); - split_buf.extend_from_slice(s_bad_date.as_bytes()); - split_buf.extend_from_slice(s_bad_num.as_bytes()); - split_buf.extend_from_slice(&s_corrupt); - split_buf.extend_from_slice(s2.as_bytes()); - - let mut split_codes = Vec::new(); - let mut split_errors = Vec::new(); - let split_stats = decode_qm_split_buffer( - &split_buf, - |s| split_codes.push(s.qm_search_code.to_owned()), - |off, err| split_errors.push((off, err)), - ); - - assert_eq!(split_codes, vec!["NVDA", "NOOP", "NEXM:CA"]); - assert_eq!(split_errors.len(), 6); - assert_eq!(split_stats.docs_in, 9); - assert_eq!(split_stats.decoded, 3); - assert_eq!(split_stats.split_noop_ratio_one, 1); - assert_eq!(split_stats.rejected_missing_field, 1); - assert_eq!(split_stats.rejected_empty_field, 1); - assert_eq!(split_stats.rejected_wrong_type, 1); - assert_eq!(split_stats.rejected_malformed_date, 1); - assert_eq!(split_stats.rejected_invalid_number, 1); - assert_eq!(split_stats.rejected_corrupt_document, 1); - assert_eq!( - split_stats.decoded + split_stats.rejected_total(), - split_stats.docs_in - ); - - // 2. qmDividends mixed valid/invalid buffer ending with a corrupt length prefix. - let d1 = make_dividend_doc("RY:CA", "2024-11-15", 1.42, "CAD", Some("2024-10-30")); - let mut d_missing = RawDocumentBuf::new(); - d_missing.append(cstr!("qmSearchCode"), "MISS"); - d_missing.append(cstr!("date"), "2024-11-15"); - d_missing.append(cstr!("amount"), 0.5_f64); - let d_empty = make_dividend_doc("RY:CA", "2024-11-15", 0.5, " ", None); - let mut d_wrong = RawDocumentBuf::new(); - d_wrong.append(cstr!("qmSearchCode"), "RY:CA"); - d_wrong.append(cstr!("date"), "2024-11-15"); - d_wrong.append(cstr!("amount"), "0.5"); - d_wrong.append(cstr!("currency"), "CAD"); - let d_bad_date = make_dividend_doc("RY:CA", "2024-11-15", 0.5, "CAD", Some("bad")); - let d_bad_num = make_dividend_doc("RY:CA", "2024-11-15", -0.1, "CAD", None); - let d2 = make_dividend_doc("AAPL", "2024-08-12", 0.25, "USD", None); - - let mut div_buf = Vec::new(); - div_buf.extend_from_slice(d1.as_bytes()); - div_buf.extend_from_slice(d_missing.as_bytes()); - div_buf.extend_from_slice(d_empty.as_bytes()); - div_buf.extend_from_slice(d_wrong.as_bytes()); - div_buf.extend_from_slice(d_bad_date.as_bytes()); - div_buf.extend_from_slice(d_bad_num.as_bytes()); - div_buf.extend_from_slice(d2.as_bytes()); - // Trailing corrupt length < 5 stops cleanly. - div_buf.extend_from_slice(&2_i32.to_le_bytes()); - div_buf.extend_from_slice(d2.as_bytes()); - - let mut div_codes = Vec::new(); - let mut div_errors = Vec::new(); - let div_stats = decode_qm_dividend_buffer( - &div_buf, - |d| div_codes.push(d.qm_search_code.to_owned()), - |off, err| div_errors.push((off, err)), - ); - - assert_eq!(div_codes, vec!["RY:CA", "AAPL"]); - assert_eq!(div_errors.len(), 6); - assert_eq!(div_stats.docs_in, 8); - assert_eq!(div_stats.decoded, 2); - assert_eq!(div_stats.split_noop_ratio_one, 0); - assert_eq!(div_stats.rejected_missing_field, 1); - assert_eq!(div_stats.rejected_empty_field, 1); - assert_eq!(div_stats.rejected_wrong_type, 1); - assert_eq!(div_stats.rejected_malformed_date, 1); - assert_eq!(div_stats.rejected_invalid_number, 1); - assert_eq!(div_stats.rejected_corrupt_document, 1); - assert_eq!( - div_stats.decoded + div_stats.rejected_total(), - div_stats.docs_in - ); -} - -#[test] -fn decoded_events_feed_split_table_curate_adj_factors_and_corporate_actions_unchanged() { - // 1. SplitTable interoperability (NVDA 10:1 forward, NEXM:CA 1:20 reverse, 1:1 no-op). - let mut split_buf = Vec::new(); - split_buf.extend_from_slice( - make_split_doc("NVDA", "2024-06-10", 10.0, Some("2024-05-22")).as_bytes(), - ); - split_buf.extend_from_slice(make_split_doc("NVDA", "2024-07-01", 1.0, None).as_bytes()); - split_buf.extend_from_slice(make_split_doc("NEXM:CA", "2025-06-18", 0.05, None).as_bytes()); - split_buf.extend_from_slice(make_split_doc("UNMAPPED", "2024-06-10", 2.0, None).as_bytes()); - - let mut div_buf = Vec::new(); - let mut ry_div = make_dividend_doc("RY:CA", "2024-11-15", 1.42, "CAD", Some("2024-10-30")); - ry_div.append(cstr!("usdFxRate"), 1_i32); // bogus usdFxRate must have zero effect - div_buf.extend_from_slice(ry_div.as_bytes()); - let mut unmapped_div = make_dividend_doc("UNMAPPED", "2024-11-15", 0.50, "USD", None); - unmapped_div.append(cstr!("usdFxRate"), 999.0_f64); - div_buf.extend_from_slice(unmapped_div.as_bytes()); - - let mut source_splits = Vec::new(); - let split_stats = decode_qm_split_buffer( - &split_buf, - |s| source_splits.push((s.qm_search_code.to_owned(), s.to_split_event())), - |_, err| panic!("unexpected split decode error: {err}"), - ); - assert_eq!(split_stats.split_noop_ratio_one, 1); - - let table = SplitTable::from_events(source_splits.iter().cloned()).unwrap(); - assert_eq!(table.cum_factor_after("NVDA", day(2024, 6, 7)), 10.0); - assert_eq!(table.cum_factor_after("NVDA", day(2024, 6, 10)), 1.0); - assert_eq!(table.cum_factor_after("NEXM:CA", day(2025, 6, 17)), 0.05); - assert_eq!(table.cum_factor_after("NEXM:CA", day(2025, 6, 18)), 1.0); - - // 2. ProviderMappingTable + curate_adj_factors interoperability. - let mapping = ProviderMappingTable::from_rows([ - ProviderMappingRow { - source: "qm".to_string(), - source_id: "NVDA".to_string(), - listing_id: 101, - valid_from: day(2020, 1, 1), - valid_to: None, - }, - ProviderMappingRow { - source: "qm".to_string(), - source_id: "NEXM:CA".to_string(), - listing_id: 202, - valid_from: day(2020, 1, 1), - valid_to: None, - }, - ProviderMappingRow { - source: "qm".to_string(), - source_id: "RY:CA".to_string(), - listing_id: 303, - valid_from: day(2020, 1, 1), - valid_to: None, - }, - ]) - .unwrap(); - - let mut source_divs = Vec::new(); - decode_qm_dividend_buffer( - &div_buf, - |d| { - source_divs.push(( - d.qm_search_code.to_owned(), - d.to_dividend_event(Some(142.0), Some("CAD".to_string())), - )); - }, - |_, err| panic!("unexpected dividend decode error: {err}"), - ); - - let curated = curate_adj_factors(&mapping, "qm", source_splits, source_divs).unwrap(); - // 1:1 NVDA split dropped by builder; UNMAPPED split & dividend dropped by mapping. - assert_eq!(curated.rows.len(), 3); - assert_eq!(curated.stats.builder.split_noops_dropped, 1); - assert_eq!(curated.stats.splits_dropped_unmapped, 1); - assert_eq!(curated.stats.dividends_dropped_unmapped, 1); - - // Row 0: listing 101 (NVDA) 10:1 split - assert_eq!(curated.rows[0].listing_id, 101); - assert_eq!(curated.rows[0].ex_date, day(2024, 6, 10)); - assert_eq!(curated.rows[0].split_factor, 10.0); - assert_eq!(curated.rows[0].cum_split_factor, 10.0); - - // Row 1: listing 202 (NEXM:CA) 1:20 reverse split - assert_eq!(curated.rows[1].listing_id, 202); - assert_eq!(curated.rows[1].ex_date, day(2025, 6, 18)); - assert_eq!(curated.rows[1].split_factor, 0.05); - - // Row 2: listing 303 (RY:CA) CAD dividend with usdFxRate ignored - assert_eq!(curated.rows[2].listing_id, 303); - assert_eq!(curated.rows[2].ex_date, day(2024, 11, 15)); - assert_eq!(curated.rows[2].div_cash, 1.42); - assert_eq!(curated.rows[2].div_currency.as_deref(), Some("CAD")); - let expected_div_factor = 142.0 / (142.0 - 1.42); - assert!((curated.rows[2].cum_total_factor - expected_div_factor).abs() < 1e-12); - - // 3. try_map_key / try_into_*_action_event -> build_corporate_actions. - let mut mapped_split_actions = Vec::new(); - decode_qm_split_buffer( - &split_buf, - |s| { - if let Some(pair) = - s.try_into_split_action_event(|code, date| mapping.resolve("qm", code, date)) - { - mapped_split_actions.push(pair); - } - }, - |_, err| panic!("unexpected error: {err}"), - ); - - let mut mapped_div_actions = Vec::new(); - decode_qm_dividend_buffer( - &div_buf, - |d| { - if let Some(pair) = - d.try_into_dividend_action_event(|code, date| mapping.resolve("qm", code, date)) - { - mapped_div_actions.push(pair); - } - }, - |_, err| panic!("unexpected error: {err}"), - ); - - // Also verify try_into_split_event & try_into_dividend_event filter unmapped keys. - let unmapped_split_doc = make_split_doc("UNMAPPED", "2024-06-10", 2.0, None); - let unmapped_split = decode_qm_split_doc(&unmapped_split_doc).unwrap(); - assert_eq!( - unmapped_split.try_into_split_event(|code, date| mapping.resolve("qm", code, date)), - None - ); - let mapped_div = decode_qm_dividend_doc(&ry_div).unwrap(); - let (lid, div_ev) = mapped_div - .try_into_dividend_event(Some(142.0), Some("CAD".to_string()), |code, date| { - mapping.resolve("qm", code, date) - }) - .unwrap(); - assert_eq!(lid, 303); - assert_eq!(div_ev.currency, "CAD"); - - let ca = build_corporate_actions( - mapped_split_actions, - mapped_div_actions, - std::iter::empty(), - ) - .unwrap(); - assert_eq!(ca.rows.len(), 3); - assert_eq!(ca.stats.split_noops_dropped, 1); - - // NVDA split has declared_date -> DeclaredDate. - assert_eq!(ca.rows[0].key, 101); - assert_eq!(ca.rows[0].kind, CorporateActionKind::Split); - assert_eq!(ca.rows[0].declared_date, Some(day(2024, 5, 22))); - assert_eq!(ca.rows[0].known_at_source, KnownAtSource::DeclaredDate); - - // NEXM split has no declared_date -> ExDateFallback. - assert_eq!(ca.rows[1].key, 202); - assert_eq!(ca.rows[1].kind, CorporateActionKind::Split); - assert_eq!(ca.rows[1].declared_date, None); - assert_eq!(ca.rows[1].known_at_source, KnownAtSource::ExDateFallback); - - // RY:CA dividend has declared_date -> DeclaredDate. - assert_eq!(ca.rows[2].key, 303); - assert_eq!(ca.rows[2].kind, CorporateActionKind::Dividend); - assert_eq!(ca.rows[2].cash_amount, Some(1.42)); - assert_eq!(ca.rows[2].currency.as_deref(), Some("CAD")); - assert_eq!(ca.rows[2].declared_date, Some(day(2024, 10, 30))); - assert_eq!(ca.rows[2].known_at_source, KnownAtSource::DeclaredDate); -} diff --git a/tools/curate-etl/src/bson_qm_events.rs b/tools/curate-etl/src/bson_qm_events.rs deleted file mode 100644 index 91b9e597..00000000 --- a/tools/curate-etl/src/bson_qm_events.rs +++ /dev/null @@ -1,1072 +0,0 @@ -//! Zero-copy raw BSON decoders for MongoDB `qmFilings` and `qmEarnings` documents (`M1.2ae`). -//! -//! Decodes `&bson::RawDocument` slices in a single forward pass over `iter_elements()` without -//! allocating a `bson::Document` or per-row `String`s, emitting borrowed [`RawQmFiling<&str>`] -//! and [`RawQmEarning<&str>`] views via a caller-supplied callback. -//! -//! # Verified vs. Caller-Configured Field Names -//! -//! Field defaults are restricted strictly to names established by in-repo evidence: -//! - **`qmFilings`** (`apps/stock/data-ingestion/src/handlers/qm/actions/filings.action.ts` -//! stores `{ ...filing, symbol, exchange }` — note it does **not** add `qmSearchCode` to the -//! stored document even though the upsert key names `['qmSearchCode', 'filingId']`; -//! `design/DATA-CONTRACTS.md` §1 establishes `timefiled`): -//! - Verified defaults: `key = "symbol"` ([`DEFAULT_FILINGS_KEY_FIELD`]), -//! `timefiled = "timefiled"` ([`DEFAULT_FILINGS_TIMEFILED_FIELD`]). -//! - Caller-configured (no default): `form_type` (required; live QuoteMedia field name is not -//! recorded in the repo), `filing_id` (optional), `url` (optional). -//! - **`qmEarnings`** (`apps/stock/data-ingestion/src/handlers/qm/actions/events.action.ts` -//! stores `{ ...earning, symbol, exchange, qmSearchCode, reportDate: new Date(...) }`; -//! `design/DATA-CONTRACTS.md` §1 establishes `reportDate`, `announceTime`, and forbids -//! `consensusEps` because it is overwritten post-hoc): -//! - Verified defaults: `key = "qmSearchCode"` ([`DEFAULT_EARNINGS_KEY_FIELD`]), -//! `report_date = "reportDate"` ([`DEFAULT_EARNINGS_REPORT_DATE_FIELD`]), -//! `announce_time = "announceTime"` ([`DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD`]). -//! - Caller-configured (optional, unconfigured unless passed): `fiscal_period_end`, -//! `actual_eps`, `revenue`. -//! - Confirm unverified live field names before the first QA/prod run via the read-only probe in -//! `apps/stock/data-pipeline/src/security-master/source-field-shapes.ts` -//! (`probe-source-field-shapes.ts --collections qmFilings,qmEarnings`). -//! - **Key-namespace alignment note:** `qmFilings` defaults to `symbol` while `qmEarnings` -//! defaults to `qmSearchCode`. Both exports must carry an unambiguous key in the -//! `provider_mapping` namespace (for example, the QuoteMedia security ID rather than a bare -//! ticker, since distinct QuoteMedia IDs such as `VOY:CNX` and `VOY:CC` can share the same -//! symbol and exchange). Where a `qmFilings` export lacks that unambiguous key, prepare the -//! export with verified IDs and exclude unresolved rows instead of switching `qmEarnings` to -//! bare tickers. -//! - **Point-in-time safety (`consensusEps`):** `consensusEps` is structurally omitted from -//! [`RawQmEarning`] and [`QmEarning`], never decoded from BSON, and explicitly rejected by -//! [`QmEarningsFieldNames::validate`] if configured on any role. -//! -//! # Decoding & Validation Rules -//! - Every element and nested subdocument/array/JS-with-scope (up to depth `128`) of each -//! [`RawDocument`] is scanned and structurally validated to completion before applying semantic -//! skip rules so structural BSON corruption always returns `Err(BsonQmEventsError::CorruptBson)` -//! rather than being masked by an earlier semantic skip. -//! - **`qmFilings`** deterministic skip priority: `key` → `timefiled` → `form_type`. All three -//! are required non-blank UTF-8 BSON `String`s passed verbatim (timestamp syntax validation -//! remains in [`crate::events::build_events`]). Optional `filing_id` and `url`: unconfigured, -//! absent, BSON `Null`, or blank `String` yields `None`; wrong BSON type yields `None` and -//! increments `nulled_wrong_type_*` (only on emitted rows). -//! - **`qmEarnings`** deterministic skip priority: `key` → `report_date` → `announce_time`. -//! `key` and `announce_time` are required non-blank UTF-8 BSON `String`s passed verbatim. -//! `report_date` accepts BSON `DateTime` (`timestamp_millis().div_euclid(86_400_000)` checked -//! to `i32`) or strict `YYYY-MM-DD` BSON `String`. Optional `fiscal_period_end` accepts absent / -//! `Null` / blank `String` (`None`), `DateTime` or strict `YYYY-MM-DD` `String` (`Some(i32)`), -//! wrong BSON type (`None` + `nulled_wrong_type_fiscal_period_end`), or malformed string / -//! out-of-range `DateTime` (`None` + `nulled_invalid_fiscal_period_end`, emitted rows only). -//! Optional `actual_eps` and `revenue` accept absent / `Null` (`None`), `Double` / `Int32` / -//! `Int64` (`Some(f64)`, non-finite sanitized downstream by `events::build_events`), or wrong -//! BSON type (`None` + `nulled_wrong_type_*`, emitted rows only). -//! - Conservation invariant on both stats structs: `docs_in == rows_out + skipped_total()`. - -use std::error::Error; -use std::fmt; - -use bson::raw::{RawBsonRef, RawDocument}; - -use crate::bson_eod_prices::{ - iter_raw_bson_docs, parse_single_raw_doc, parse_ymd_strict_days, BsonEodPriceError, - MILLIS_PER_DAY, -}; -use crate::events::{QmEarning, QmFiling}; - -/// Verified default BSON field name for the `qmFilings` security key (`filings.action.ts`). -pub const DEFAULT_FILINGS_KEY_FIELD: &str = "symbol"; -/// Verified default BSON field name for `qmFilings.timefiled` (`design/DATA-CONTRACTS.md` §1). -pub const DEFAULT_FILINGS_TIMEFILED_FIELD: &str = "timefiled"; - -/// Verified default BSON field name for the `qmEarnings` security key (`events.action.ts`). -pub const DEFAULT_EARNINGS_KEY_FIELD: &str = "qmSearchCode"; -/// Verified default BSON field name for `qmEarnings.reportDate` (`events.action.ts`, `DATA-CONTRACTS.md` §1). -pub const DEFAULT_EARNINGS_REPORT_DATE_FIELD: &str = "reportDate"; -/// Verified default BSON field name for `qmEarnings.announceTime` (`design/DATA-CONTRACTS.md` §1). -pub const DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD: &str = "announceTime"; - -/// Borrowed BSON field-name configuration for decoding `qmFilings` documents. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct QmFilingsFieldNames<'a> { - pub key: &'a str, - pub timefiled: &'a str, - pub form_type: &'a str, - pub filing_id: Option<&'a str>, - pub url: Option<&'a str>, -} - -impl<'a> QmFilingsFieldNames<'a> { - /// Validates that every configured field name is non-empty/non-blank and that no two - /// configured roles point to the same BSON field name. - pub fn validate(&self) -> Result<(), BsonQmEventsError> { - let roles: [(&'static str, Option<&str>); 5] = [ - ("filings.key", Some(self.key)), - ("filings.timefiled", Some(self.timefiled)), - ("filings.form_type", Some(self.form_type)), - ("filings.filing_id", self.filing_id), - ("filings.url", self.url), - ]; - validate_role_names(&roles, false) - } -} - -/// Borrowed BSON field-name configuration for decoding `qmEarnings` documents. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct QmEarningsFieldNames<'a> { - pub key: &'a str, - pub report_date: &'a str, - pub announce_time: &'a str, - pub fiscal_period_end: Option<&'a str>, - pub actual_eps: Option<&'a str>, - pub revenue: Option<&'a str>, -} - -impl<'a> QmEarningsFieldNames<'a> { - /// Validates that every configured field name is non-empty/non-blank, that no two configured - /// roles point to the same BSON field name, and that no role maps to `consensusEps` / - /// `consensus_eps` (case-insensitive), which is forbidden per `design/DATA-CONTRACTS.md` §1. - pub fn validate(&self) -> Result<(), BsonQmEventsError> { - let roles: [(&'static str, Option<&str>); 6] = [ - ("earnings.key", Some(self.key)), - ("earnings.report_date", Some(self.report_date)), - ("earnings.announce_time", Some(self.announce_time)), - ("earnings.fiscal_period_end", self.fiscal_period_end), - ("earnings.actual_eps", self.actual_eps), - ("earnings.revenue", self.revenue), - ]; - validate_role_names(&roles, true) - } -} - -#[inline] -fn is_forbidden_consensus_eps_field(name: &str) -> bool { - let trimmed = name.trim(); - trimmed.eq_ignore_ascii_case("consensuseps") || trimmed.eq_ignore_ascii_case("consensus_eps") -} - -fn validate_role_names( - roles: &[(&'static str, Option<&str>)], - forbid_consensus_eps: bool, -) -> Result<(), BsonQmEventsError> { - for &(role, name_opt) in roles { - if let Some(name) = name_opt { - if name.trim().is_empty() { - return Err(BsonQmEventsError::InvalidFieldNames { - detail: format!("field name for '{role}' must not be empty or blank"), - }); - } - if forbid_consensus_eps && is_forbidden_consensus_eps_field(name) { - return Err(BsonQmEventsError::InvalidFieldNames { - detail: format!( - "field name '{name}' for '{role}' is forbidden (consensusEps is not point-in-time safe)" - ), - }); - } - } - } - - for i in 0..roles.len() { - let (role_a, Some(name_a)) = roles[i] else { - continue; - }; - for &(role_b, name_b_opt) in &roles[i + 1..] { - if let Some(name_b) = name_b_opt { - if name_a == name_b { - return Err(BsonQmEventsError::InvalidFieldNames { - detail: format!( - "roles '{role_a}' and '{role_b}' cannot share BSON field '{name_a}'" - ), - }); - } - } - } - } - - Ok(()) -} - -/// Borrowed zero-copy view of a single decoded `qmFilings` BSON document. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct RawQmFiling<'a> { - pub key: &'a str, - pub exchange: Option<&'a str>, - pub timefiled: &'a str, - pub form_type: &'a str, - pub filing_id: Option<&'a str>, - pub url: Option<&'a str>, -} - -impl<'a> RawQmFiling<'a> { - /// Converts this borrowed view into an owned [`QmFiling`] using a caller-supplied key. - #[inline] - pub fn to_qm_filing(self, key: K) -> QmFiling { - QmFiling { - key, - timefiled: self.timefiled.to_string(), - form_type: self.form_type.to_string(), - filing_id: self.filing_id.map(str::to_string), - url: self.url.map(str::to_string), - } - } -} - -/// Borrowed zero-copy view of a single decoded `qmEarnings` BSON document. -/// -/// Structurally omits `consensusEps`, which is overwritten post-hoc in `qmEarnings` per -/// `design/DATA-CONTRACTS.md` §1 and is not point-in-time safe. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct RawQmEarning<'a> { - pub key: &'a str, - pub report_date: i32, - pub announce_time: &'a str, - pub fiscal_period_end: Option, - pub actual_eps: Option, - pub revenue: Option, -} - -impl<'a> RawQmEarning<'a> { - /// Converts this borrowed view into an owned [`QmEarning`] using a caller-supplied key. - #[inline] - pub fn to_qm_earning(self, key: K) -> QmEarning { - QmEarning { - key, - report_date: self.report_date, - announce_time: self.announce_time.to_string(), - fiscal_period_end: self.fiscal_period_end, - actual_eps: self.actual_eps, - revenue: self.revenue, - } - } -} - -/// Typed errors returned while validating field configuration or decoding raw `qmFilings` / -/// `qmEarnings` BSON. -/// -/// Structural BSON framing or element errors fail closed and carry a `u64` byte offset; -/// every variant's `Display` output is a single line. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum BsonQmEventsError { - /// Invalid [`QmFilingsFieldNames`] or [`QmEarningsFieldNames`] configuration. - InvalidFieldNames { detail: String }, - /// Buffer ended before a complete 4-byte length prefix or declared document body. - TruncatedDocument { - offset: u64, - remaining: usize, - declared_len: Option, - }, - /// Declared 4-byte little-endian BSON document length was `< 5` (or did not match a single - /// document slice). - CorruptDocumentLength { offset: u64, declared_len: i32 }, - /// Underlying BSON framing or element bytes were malformed. - CorruptBson { offset: u64, detail: String }, -} - -impl fmt::Display for BsonQmEventsError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::InvalidFieldNames { detail } => { - write!(f, "invalid qmEvents field configuration: {detail}") - } - Self::TruncatedDocument { - offset, - remaining, - declared_len, - } => match declared_len { - Some(len) => write!( - f, - "truncated BSON document at byte offset {offset}: declared length {len} exceeds remaining {remaining} bytes" - ), - None => write!( - f, - "truncated BSON document header at byte offset {offset}: only {remaining} bytes remaining" - ), - }, - Self::CorruptDocumentLength { - offset, - declared_len, - } => write!( - f, - "corrupt BSON document length {declared_len} at byte offset {offset}" - ), - Self::CorruptBson { offset, detail } => { - write!(f, "corrupt BSON bytes at byte offset {offset}: {detail}") - } - } - } -} - -impl Error for BsonQmEventsError {} - -#[inline] -fn map_framing_error(err: BsonEodPriceError) -> BsonQmEventsError { - match err { - BsonEodPriceError::TruncatedDocument { - offset, - remaining, - declared_len, - } => BsonQmEventsError::TruncatedDocument { - offset: offset as u64, - remaining, - declared_len, - }, - BsonEodPriceError::CorruptDocumentLength { - offset, - declared_len, - } => BsonQmEventsError::CorruptDocumentLength { - offset: offset as u64, - declared_len, - }, - BsonEodPriceError::CorruptBson { offset, detail } => BsonQmEventsError::CorruptBson { - offset: offset as u64, - detail, - }, - other => BsonQmEventsError::CorruptBson { - offset: 0, - detail: other.to_string(), - }, - } -} - -/// Per-batch decode accounting for `qmFilings`. -/// -/// Conservation invariant: -/// `docs_in == rows_out + skipped_total()` -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct BsonQmFilingsDecodeStats { - pub docs_in: usize, - pub rows_out: usize, - pub skipped_missing_key: usize, - pub skipped_wrong_key_type: usize, - pub skipped_empty_key: usize, - pub skipped_missing_timefiled: usize, - pub skipped_wrong_timefiled_type: usize, - pub skipped_empty_timefiled: usize, - pub skipped_missing_form_type: usize, - pub skipped_wrong_form_type_type: usize, - pub skipped_empty_form_type: usize, - pub nulled_wrong_type_filing_id: usize, - pub nulled_wrong_type_url: usize, -} - -impl BsonQmFilingsDecodeStats { - /// Total number of semantically skipped `qmFilings` documents across all skip categories. - #[inline] - pub fn skipped_total(&self) -> usize { - self.skipped_missing_key - + self.skipped_wrong_key_type - + self.skipped_empty_key - + self.skipped_missing_timefiled - + self.skipped_wrong_timefiled_type - + self.skipped_empty_timefiled - + self.skipped_missing_form_type - + self.skipped_wrong_form_type_type - + self.skipped_empty_form_type - } - - /// Accumulates counters from another batch into `self`. - #[inline] - pub fn merge(&mut self, other: &Self) { - self.docs_in += other.docs_in; - self.rows_out += other.rows_out; - self.skipped_missing_key += other.skipped_missing_key; - self.skipped_wrong_key_type += other.skipped_wrong_key_type; - self.skipped_empty_key += other.skipped_empty_key; - self.skipped_missing_timefiled += other.skipped_missing_timefiled; - self.skipped_wrong_timefiled_type += other.skipped_wrong_timefiled_type; - self.skipped_empty_timefiled += other.skipped_empty_timefiled; - self.skipped_missing_form_type += other.skipped_missing_form_type; - self.skipped_wrong_form_type_type += other.skipped_wrong_form_type_type; - self.skipped_empty_form_type += other.skipped_empty_form_type; - self.nulled_wrong_type_filing_id += other.nulled_wrong_type_filing_id; - self.nulled_wrong_type_url += other.nulled_wrong_type_url; - } -} - -impl std::ops::AddAssign for BsonQmFilingsDecodeStats { - #[inline] - fn add_assign(&mut self, rhs: Self) { - self.merge(&rhs); - } -} - -/// Per-batch decode accounting for `qmEarnings`. -/// -/// Conservation invariant: -/// `docs_in == rows_out + skipped_total()` -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct BsonQmEarningsDecodeStats { - pub docs_in: usize, - pub rows_out: usize, - pub skipped_missing_key: usize, - pub skipped_wrong_key_type: usize, - pub skipped_empty_key: usize, - pub skipped_missing_report_date: usize, - pub skipped_wrong_report_date_type: usize, - pub skipped_invalid_report_date: usize, - pub skipped_report_date_out_of_range: usize, - pub skipped_missing_announce_time: usize, - pub skipped_wrong_announce_time_type: usize, - pub skipped_empty_announce_time: usize, - pub nulled_wrong_type_fiscal_period_end: usize, - pub nulled_invalid_fiscal_period_end: usize, - pub nulled_wrong_type_actual_eps: usize, - pub nulled_wrong_type_revenue: usize, -} - -impl BsonQmEarningsDecodeStats { - /// Total number of semantically skipped `qmEarnings` documents across all skip categories. - #[inline] - pub fn skipped_total(&self) -> usize { - self.skipped_missing_key - + self.skipped_wrong_key_type - + self.skipped_empty_key - + self.skipped_missing_report_date - + self.skipped_wrong_report_date_type - + self.skipped_invalid_report_date - + self.skipped_report_date_out_of_range - + self.skipped_missing_announce_time - + self.skipped_wrong_announce_time_type - + self.skipped_empty_announce_time - } - - /// Accumulates counters from another batch into `self`. - #[inline] - pub fn merge(&mut self, other: &Self) { - self.docs_in += other.docs_in; - self.rows_out += other.rows_out; - self.skipped_missing_key += other.skipped_missing_key; - self.skipped_wrong_key_type += other.skipped_wrong_key_type; - self.skipped_empty_key += other.skipped_empty_key; - self.skipped_missing_report_date += other.skipped_missing_report_date; - self.skipped_wrong_report_date_type += other.skipped_wrong_report_date_type; - self.skipped_invalid_report_date += other.skipped_invalid_report_date; - self.skipped_report_date_out_of_range += other.skipped_report_date_out_of_range; - self.skipped_missing_announce_time += other.skipped_missing_announce_time; - self.skipped_wrong_announce_time_type += other.skipped_wrong_announce_time_type; - self.skipped_empty_announce_time += other.skipped_empty_announce_time; - self.nulled_wrong_type_fiscal_period_end += other.nulled_wrong_type_fiscal_period_end; - self.nulled_invalid_fiscal_period_end += other.nulled_invalid_fiscal_period_end; - self.nulled_wrong_type_actual_eps += other.nulled_wrong_type_actual_eps; - self.nulled_wrong_type_revenue += other.nulled_wrong_type_revenue; - } -} - -impl std::ops::AddAssign for BsonQmEarningsDecodeStats { - #[inline] - fn add_assign(&mut self, rhs: Self) { - self.merge(&rhs); - } -} - -enum ReqStrState<'a> { - Missing, - WrongType, - Empty, - Valid(&'a str), -} - -enum OptStrState<'a> { - None, - WrongType, - Valid(&'a str), -} - -enum ReqDateState { - Missing, - WrongType, - Invalid, - OutOfRange, - Valid(i32), -} - -enum OptDateState { - None, - WrongType, - Invalid, - Valid(i32), -} - -enum OptNumState { - None, - WrongType, - Valid(f64), -} - -#[inline] -fn decode_required_str<'a>(val: RawBsonRef<'a>) -> ReqStrState<'a> { - match val { - RawBsonRef::String(s) => { - if s.trim().is_empty() { - ReqStrState::Empty - } else { - ReqStrState::Valid(s) - } - } - _ => ReqStrState::WrongType, - } -} - -#[inline] -fn decode_optional_str<'a>(val: RawBsonRef<'a>) -> OptStrState<'a> { - match val { - RawBsonRef::Null => OptStrState::None, - RawBsonRef::String(s) => { - if s.trim().is_empty() { - OptStrState::None - } else { - OptStrState::Valid(s) - } - } - _ => OptStrState::WrongType, - } -} - -#[inline] -fn decode_required_date(val: RawBsonRef<'_>) -> ReqDateState { - match val { - RawBsonRef::DateTime(dt) => { - let days = dt.timestamp_millis().div_euclid(MILLIS_PER_DAY); - match i32::try_from(days) { - Ok(d) => ReqDateState::Valid(d), - Err(_) => ReqDateState::OutOfRange, - } - } - RawBsonRef::String(s) => match parse_ymd_strict_days(s) { - Some(d) => ReqDateState::Valid(d), - None => ReqDateState::Invalid, - }, - _ => ReqDateState::WrongType, - } -} - -#[inline] -fn decode_optional_date(val: RawBsonRef<'_>) -> OptDateState { - match val { - RawBsonRef::Null => OptDateState::None, - RawBsonRef::DateTime(dt) => { - let days = dt.timestamp_millis().div_euclid(MILLIS_PER_DAY); - match i32::try_from(days) { - Ok(d) => OptDateState::Valid(d), - Err(_) => OptDateState::Invalid, - } - } - RawBsonRef::String(s) => { - if s.trim().is_empty() { - OptDateState::None - } else { - match parse_ymd_strict_days(s) { - Some(d) => OptDateState::Valid(d), - None => OptDateState::Invalid, - } - } - } - _ => OptDateState::WrongType, - } -} - -#[inline] -fn decode_optional_number(val: RawBsonRef<'_>) -> OptNumState { - match val { - RawBsonRef::Null => OptNumState::None, - RawBsonRef::Double(v) => OptNumState::Valid(v), - RawBsonRef::Int32(v) => OptNumState::Valid(f64::from(v)), - RawBsonRef::Int64(v) => OptNumState::Valid(v as f64), - _ => OptNumState::WrongType, - } -} - -/// Maximum recursive nesting depth accepted while validating raw BSON documents and arrays. -const MAX_BSON_VALIDATION_DEPTH: usize = 128; - -#[inline] -fn is_exact_array_index(key: &str, expected: usize) -> bool { - let bytes = key.as_bytes(); - if bytes.is_empty() || (bytes.len() > 1 && bytes[0] == b'0') { - return false; - } - let mut parsed: usize = 0; - for &b in bytes { - if !b.is_ascii_digit() { - return false; - } - let digit = usize::from(b - b'0'); - match parsed.checked_mul(10).and_then(|n| n.checked_add(digit)) { - Some(next) => parsed = next, - None => return false, - } - } - parsed == expected -} - -fn validate_raw_bson_value( - val: RawBsonRef<'_>, - doc_offset: u64, - field_name: &str, - depth: usize, -) -> Result<(), BsonQmEventsError> { - match val { - RawBsonRef::Document(subdoc) => { - validate_raw_document(subdoc, doc_offset, field_name, depth + 1) - } - RawBsonRef::Array(arr) => { - if depth >= MAX_BSON_VALIDATION_DEPTH { - return Err(BsonQmEventsError::CorruptBson { - offset: doc_offset, - detail: format!( - "field '{field_name}': nested BSON depth exceeds limit {MAX_BSON_VALIDATION_DEPTH}" - ), - }); - } - for (expected_idx, elem_res) in arr.iter_elements().enumerate() { - let elem = elem_res.map_err(|err| BsonQmEventsError::CorruptBson { - offset: doc_offset, - detail: format!("field '{field_name}': {err}"), - })?; - let key = elem.key().as_str(); - if !is_exact_array_index(key, expected_idx) { - return Err(BsonQmEventsError::CorruptBson { - offset: doc_offset, - detail: format!( - "field '{field_name}': invalid BSON array index '{key}' at position {expected_idx}" - ), - }); - } - let item = elem.value().map_err(|err| BsonQmEventsError::CorruptBson { - offset: doc_offset, - detail: format!("field '{field_name}': {err}"), - })?; - validate_raw_bson_value(item, doc_offset, field_name, depth + 1)?; - } - Ok(()) - } - RawBsonRef::JavaScriptCodeWithScope(code_with_scope) => { - validate_raw_document(code_with_scope.scope, doc_offset, field_name, depth + 1) - } - _ => Ok(()), - } -} - -fn validate_raw_document( - doc: &RawDocument, - doc_offset: u64, - field_name: &str, - depth: usize, -) -> Result<(), BsonQmEventsError> { - if depth > MAX_BSON_VALIDATION_DEPTH { - return Err(BsonQmEventsError::CorruptBson { - offset: doc_offset, - detail: format!( - "field '{field_name}': nested BSON depth exceeds limit {MAX_BSON_VALIDATION_DEPTH}" - ), - }); - } - for elem_res in doc.iter_elements() { - let elem = elem_res.map_err(|err| BsonQmEventsError::CorruptBson { - offset: doc_offset, - detail: format!("field '{field_name}': {err}"), - })?; - let val = elem.value().map_err(|err| BsonQmEventsError::CorruptBson { - offset: doc_offset, - detail: format!("field '{field_name}': {err}"), - })?; - validate_raw_bson_value(val, doc_offset, field_name, depth)?; - } - Ok(()) -} - -fn decode_qm_filing_doc_at<'a, F>( - doc: &'a RawDocument, - doc_offset: u64, - fields: &QmFilingsFieldNames<'_>, - mut on_row: F, -) -> Result -where - F: FnMut(RawQmFiling<'a>), -{ - let mut stats = BsonQmFilingsDecodeStats { - docs_in: 1, - ..BsonQmFilingsDecodeStats::default() - }; - - let mut key_state = ReqStrState::Missing; - let mut exchange: Option<&'a str> = None; - let mut timefiled_state = ReqStrState::Missing; - let mut form_type_state = ReqStrState::Missing; - let mut filing_id_state = OptStrState::None; - let mut url_state = OptStrState::None; - - // Scan and structurally validate every element and nested raw value to completion so - // structural BSON corruption always fails closed rather than being masked by a semantic skip. - for elem_res in doc.iter_elements() { - let elem = elem_res.map_err(|err| BsonQmEventsError::CorruptBson { - offset: doc_offset, - detail: err.to_string(), - })?; - let name = elem.key().as_str(); - let val = elem.value().map_err(|err| BsonQmEventsError::CorruptBson { - offset: doc_offset, - detail: format!("field '{name}': {err}"), - })?; - validate_raw_bson_value(val, doc_offset, name, 0)?; - - if name == fields.key { - key_state = decode_required_str(val); - } else if name == fields.timefiled { - timefiled_state = decode_required_str(val); - } else if name == fields.form_type { - form_type_state = decode_required_str(val); - } else if fields.filing_id == Some(name) { - filing_id_state = decode_optional_str(val); - } else if fields.url == Some(name) { - url_state = decode_optional_str(val); - } else if name == "exchange" { - if let RawBsonRef::String(s) = val { - let trimmed = s.trim(); - if !trimmed.is_empty() { - exchange = Some(trimmed); - } - } - } - } - - // Apply deterministic semantic skip priority: key -> timefiled -> form_type. - let key = match key_state { - ReqStrState::Valid(s) => s, - ReqStrState::Missing => { - stats.skipped_missing_key += 1; - return Ok(stats); - } - ReqStrState::WrongType => { - stats.skipped_wrong_key_type += 1; - return Ok(stats); - } - ReqStrState::Empty => { - stats.skipped_empty_key += 1; - return Ok(stats); - } - }; - - let timefiled = match timefiled_state { - ReqStrState::Valid(s) => s, - ReqStrState::Missing => { - stats.skipped_missing_timefiled += 1; - return Ok(stats); - } - ReqStrState::WrongType => { - stats.skipped_wrong_timefiled_type += 1; - return Ok(stats); - } - ReqStrState::Empty => { - stats.skipped_empty_timefiled += 1; - return Ok(stats); - } - }; - - let form_type = match form_type_state { - ReqStrState::Valid(s) => s, - ReqStrState::Missing => { - stats.skipped_missing_form_type += 1; - return Ok(stats); - } - ReqStrState::WrongType => { - stats.skipped_wrong_form_type_type += 1; - return Ok(stats); - } - ReqStrState::Empty => { - stats.skipped_empty_form_type += 1; - return Ok(stats); - } - }; - - let filing_id = match filing_id_state { - OptStrState::Valid(s) => Some(s), - OptStrState::None => None, - OptStrState::WrongType => { - stats.nulled_wrong_type_filing_id += 1; - None - } - }; - - let url = match url_state { - OptStrState::Valid(s) => Some(s), - OptStrState::None => None, - OptStrState::WrongType => { - stats.nulled_wrong_type_url += 1; - None - } - }; - - stats.rows_out += 1; - on_row(RawQmFiling { - key, - exchange, - timefiled, - form_type, - filing_id, - url, - }); - Ok(stats) -} - -fn decode_qm_earning_doc_at<'a, F>( - doc: &'a RawDocument, - doc_offset: u64, - fields: &QmEarningsFieldNames<'_>, - mut on_row: F, -) -> Result -where - F: FnMut(RawQmEarning<'a>), -{ - let mut stats = BsonQmEarningsDecodeStats { - docs_in: 1, - ..BsonQmEarningsDecodeStats::default() - }; - - let mut key_state = ReqStrState::Missing; - let mut date_state = ReqDateState::Missing; - let mut announce_state = ReqStrState::Missing; - let mut fiscal_end_state = OptDateState::None; - let mut actual_eps_state = OptNumState::None; - let mut revenue_state = OptNumState::None; - - // Scan and structurally validate every element and nested raw value to completion so - // structural BSON corruption always fails closed rather than being masked by a semantic skip. - // Note: `consensusEps` is never matched or decoded. - for elem_res in doc.iter_elements() { - let elem = elem_res.map_err(|err| BsonQmEventsError::CorruptBson { - offset: doc_offset, - detail: err.to_string(), - })?; - let name = elem.key().as_str(); - let val = elem.value().map_err(|err| BsonQmEventsError::CorruptBson { - offset: doc_offset, - detail: format!("field '{name}': {err}"), - })?; - validate_raw_bson_value(val, doc_offset, name, 0)?; - - if name == fields.key { - key_state = decode_required_str(val); - } else if name == fields.report_date { - date_state = decode_required_date(val); - } else if name == fields.announce_time { - announce_state = decode_required_str(val); - } else if fields.fiscal_period_end == Some(name) { - fiscal_end_state = decode_optional_date(val); - } else if fields.actual_eps == Some(name) { - actual_eps_state = decode_optional_number(val); - } else if fields.revenue == Some(name) { - revenue_state = decode_optional_number(val); - } - } - - // Apply deterministic semantic skip priority: key -> report_date -> announce_time. - let key = match key_state { - ReqStrState::Valid(s) => s, - ReqStrState::Missing => { - stats.skipped_missing_key += 1; - return Ok(stats); - } - ReqStrState::WrongType => { - stats.skipped_wrong_key_type += 1; - return Ok(stats); - } - ReqStrState::Empty => { - stats.skipped_empty_key += 1; - return Ok(stats); - } - }; - - let report_date = match date_state { - ReqDateState::Valid(d) => d, - ReqDateState::Missing => { - stats.skipped_missing_report_date += 1; - return Ok(stats); - } - ReqDateState::WrongType => { - stats.skipped_wrong_report_date_type += 1; - return Ok(stats); - } - ReqDateState::Invalid => { - stats.skipped_invalid_report_date += 1; - return Ok(stats); - } - ReqDateState::OutOfRange => { - stats.skipped_report_date_out_of_range += 1; - return Ok(stats); - } - }; - - let announce_time = match announce_state { - ReqStrState::Valid(s) => s, - ReqStrState::Missing => { - stats.skipped_missing_announce_time += 1; - return Ok(stats); - } - ReqStrState::WrongType => { - stats.skipped_wrong_announce_time_type += 1; - return Ok(stats); - } - ReqStrState::Empty => { - stats.skipped_empty_announce_time += 1; - return Ok(stats); - } - }; - - let fiscal_period_end = match fiscal_end_state { - OptDateState::Valid(d) => Some(d), - OptDateState::None => None, - OptDateState::WrongType => { - stats.nulled_wrong_type_fiscal_period_end += 1; - None - } - OptDateState::Invalid => { - stats.nulled_invalid_fiscal_period_end += 1; - None - } - }; - - let actual_eps = match actual_eps_state { - OptNumState::Valid(v) => Some(v), - OptNumState::None => None, - OptNumState::WrongType => { - stats.nulled_wrong_type_actual_eps += 1; - None - } - }; - - let revenue = match revenue_state { - OptNumState::Valid(v) => Some(v), - OptNumState::None => None, - OptNumState::WrongType => { - stats.nulled_wrong_type_revenue += 1; - None - } - }; - - stats.rows_out += 1; - on_row(RawQmEarning { - key, - report_date, - announce_time, - fiscal_period_end, - actual_eps, - revenue, - }); - Ok(stats) -} - -/// Decodes a single `&RawDocument` representing a `qmFilings` MongoDB document in one forward -/// pass without allocating a `bson::Document` or per-row `String`s. -pub fn decode_qm_filing_doc<'a, F>( - doc: &'a RawDocument, - fields: &QmFilingsFieldNames<'_>, - on_row: F, -) -> Result -where - F: FnMut(RawQmFiling<'a>), -{ - fields.validate()?; - decode_qm_filing_doc_at(doc, 0, fields, on_row) -} - -/// Decodes a single length-prefixed raw BSON document byte slice representing a `qmFilings` -/// document. -pub fn decode_qm_filing_bytes<'a, F>( - bytes: &'a [u8], - fields: &QmFilingsFieldNames<'_>, - on_row: F, -) -> Result -where - F: FnMut(RawQmFiling<'a>), -{ - fields.validate()?; - let doc = parse_single_raw_doc(bytes).map_err(map_framing_error)?; - decode_qm_filing_doc_at(doc, 0, fields, on_row) -} - -/// Streams a concatenated length-prefixed BSON buffer of `qmFilings` documents through -/// [`decode_qm_filing_doc`], emitting every valid [`RawQmFiling<&str>`] to `on_row` and failing -/// closed on any structural BSON framing or element corruption. -/// -/// Always maintains `stats.docs_in == stats.rows_out + stats.skipped_total()`. -pub fn decode_qm_filing_buffer<'a, F>( - buf: &'a [u8], - fields: &QmFilingsFieldNames<'_>, - mut on_row: F, -) -> Result -where - F: FnMut(RawQmFiling<'a>), -{ - fields.validate()?; - let mut total = BsonQmFilingsDecodeStats::default(); - let mut iter = iter_raw_bson_docs(buf); - while let Some(item) = iter.next_with_offset() { - match item { - Ok((offset, doc)) => { - let doc_stats = decode_qm_filing_doc_at(doc, offset as u64, fields, &mut on_row)?; - total += doc_stats; - } - Err((_, err)) => return Err(map_framing_error(err)), - } - } - Ok(total) -} - -/// Decodes a single `&RawDocument` representing a `qmEarnings` MongoDB document in one forward -/// pass without allocating a `bson::Document` or per-row `String`s. -pub fn decode_qm_earning_doc<'a, F>( - doc: &'a RawDocument, - fields: &QmEarningsFieldNames<'_>, - on_row: F, -) -> Result -where - F: FnMut(RawQmEarning<'a>), -{ - fields.validate()?; - decode_qm_earning_doc_at(doc, 0, fields, on_row) -} - -/// Decodes a single length-prefixed raw BSON document byte slice representing a `qmEarnings` -/// document. -pub fn decode_qm_earning_bytes<'a, F>( - bytes: &'a [u8], - fields: &QmEarningsFieldNames<'_>, - on_row: F, -) -> Result -where - F: FnMut(RawQmEarning<'a>), -{ - fields.validate()?; - let doc = parse_single_raw_doc(bytes).map_err(map_framing_error)?; - decode_qm_earning_doc_at(doc, 0, fields, on_row) -} - -/// Streams a concatenated length-prefixed BSON buffer of `qmEarnings` documents through -/// [`decode_qm_earning_doc`], emitting every valid [`RawQmEarning<&str>`] to `on_row` and failing -/// closed on any structural BSON framing or element corruption. -/// -/// Always maintains `stats.docs_in == stats.rows_out + stats.skipped_total()`. -pub fn decode_qm_earning_buffer<'a, F>( - buf: &'a [u8], - fields: &QmEarningsFieldNames<'_>, - mut on_row: F, -) -> Result -where - F: FnMut(RawQmEarning<'a>), -{ - fields.validate()?; - let mut total = BsonQmEarningsDecodeStats::default(); - let mut iter = iter_raw_bson_docs(buf); - while let Some(item) = iter.next_with_offset() { - match item { - Ok((offset, doc)) => { - let doc_stats = decode_qm_earning_doc_at(doc, offset as u64, fields, &mut on_row)?; - total += doc_stats; - } - Err((_, err)) => return Err(map_framing_error(err)), - } - } - Ok(total) -} - -#[cfg(test)] -#[path = "bson_qm_events_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/bson_qm_events_tests.rs b/tools/curate-etl/src/bson_qm_events_tests.rs deleted file mode 100644 index 01df13f6..00000000 --- a/tools/curate-etl/src/bson_qm_events_tests.rs +++ /dev/null @@ -1,500 +0,0 @@ -use bson::{rawdoc, DateTime, RawDocumentBuf}; - -use super::*; -use crate::split::ymd_to_epoch_days; - -fn day(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).expect("valid date") -} - -fn dt_from_ymd(y: i32, m: u32, d: u32) -> DateTime { - DateTime::from_millis(i64::from(day(y, m, d)) * MILLIS_PER_DAY) -} - -fn default_filings_fields() -> QmFilingsFieldNames<'static> { - QmFilingsFieldNames { - key: DEFAULT_FILINGS_KEY_FIELD, - timefiled: DEFAULT_FILINGS_TIMEFILED_FIELD, - form_type: "formtype", - filing_id: Some("filingId"), - url: Some("url"), - } -} - -fn default_earnings_fields() -> QmEarningsFieldNames<'static> { - QmEarningsFieldNames { - key: DEFAULT_EARNINGS_KEY_FIELD, - report_date: DEFAULT_EARNINGS_REPORT_DATE_FIELD, - announce_time: DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD, - fiscal_period_end: Some("periodEndDate"), - actual_eps: Some("actualEps"), - revenue: Some("revenue"), - } -} - -fn make_raw_doc_with_invalid_utf8_unused_field(include_required: bool) -> Vec { - let mut body = Vec::new(); - if include_required { - // String field "symbol": "AAPL" - body.push(0x02); - body.extend_from_slice(b"symbol\0"); - body.extend_from_slice(&5_i32.to_le_bytes()); - body.extend_from_slice(b"AAPL\0"); - // String field "timefiled": "2025-01-31T06:01:27 EST" - let ts = b"2025-01-31T06:01:27 EST"; - body.push(0x02); - body.extend_from_slice(b"timefiled\0"); - body.extend_from_slice(&((ts.len() + 1) as i32).to_le_bytes()); - body.extend_from_slice(ts); - body.push(0); - // String field "formtype": "10-K" - body.push(0x02); - body.extend_from_slice(b"formtype\0"); - body.extend_from_slice(&5_i32.to_le_bytes()); - body.extend_from_slice(b"10-K\0"); - } - // Unused string field "extra" with invalid UTF-8 bytes [0xFF, 0xFE] - body.push(0x02); - body.extend_from_slice(b"extra\0"); - body.extend_from_slice(&3_i32.to_le_bytes()); - body.extend_from_slice(&[0xFF, 0xFE, 0x00]); - body.push(0x00); // doc terminator - - let total_len = (4 + body.len()) as i32; - let mut out = Vec::with_capacity(total_len as usize); - out.extend_from_slice(&total_len.to_le_bytes()); - out.extend_from_slice(&body); - out -} - -fn make_raw_doc_with_bad_array_index() -> Vec { - // Nested array "badArr" with key "1" instead of "0" - let mut arr_body = Vec::new(); - arr_body.push(0x10); // Int32 - arr_body.extend_from_slice(b"1\0"); - arr_body.extend_from_slice(&42_i32.to_le_bytes()); - arr_body.push(0x00); - let arr_len = (4 + arr_body.len()) as i32; - - let mut body = Vec::new(); - body.push(0x04); // Array - body.extend_from_slice(b"badArr\0"); - body.extend_from_slice(&arr_len.to_le_bytes()); - body.extend_from_slice(&arr_body); - body.push(0x00); - - let total_len = (4 + body.len()) as i32; - let mut out = Vec::with_capacity(total_len as usize); - out.extend_from_slice(&total_len.to_le_bytes()); - out.extend_from_slice(&body); - out -} - -#[test] -fn field_name_validation_rejects_blank_colliding_and_consensus_eps() { - assert!(default_filings_fields().validate().is_ok()); - assert!(default_earnings_fields().validate().is_ok()); - - // Blank required / optional filings fields - let mut f = default_filings_fields(); - f.form_type = " "; - let err = f.validate().unwrap_err(); - assert!(matches!(err, BsonQmEventsError::InvalidFieldNames { .. })); - assert!(!err.to_string().contains('\n')); - - let mut f = default_filings_fields(); - f.url = Some(""); - assert!(matches!( - f.validate(), - Err(BsonQmEventsError::InvalidFieldNames { .. }) - )); - - // Colliding filings fields - let mut f = default_filings_fields(); - f.form_type = DEFAULT_FILINGS_KEY_FIELD; - assert!(matches!( - f.validate(), - Err(BsonQmEventsError::InvalidFieldNames { .. }) - )); - - // Blank earnings field - let mut e = default_earnings_fields(); - e.actual_eps = Some(" \t "); - assert!(matches!( - e.validate(), - Err(BsonQmEventsError::InvalidFieldNames { .. }) - )); - - // Colliding earnings fields - let mut e = default_earnings_fields(); - e.revenue = Some("actualEps"); - assert!(matches!( - e.validate(), - Err(BsonQmEventsError::InvalidFieldNames { .. }) - )); - - // Forbidden consensusEps / consensus_eps (case-insensitive) on any role - for bad in ["consensusEps", "CONSENSUSEPS", "consensus_eps", " Consensus_Eps "] { - let mut e = default_earnings_fields(); - e.actual_eps = Some(bad); - let err = e.validate().unwrap_err(); - assert!(matches!(err, BsonQmEventsError::InvalidFieldNames { .. })); - assert!(err.to_string().contains("consensusEps")); - assert!(!err.to_string().contains('\n')); - - let mut e2 = default_earnings_fields(); - e2.revenue = Some(bad); - assert!(matches!( - e2.validate(), - Err(BsonQmEventsError::InvalidFieldNames { .. }) - )); - } -} - -#[test] -fn qm_filings_happy_path_and_optionals() { - let fields = default_filings_fields(); - let doc1 = rawdoc! { - "symbol": " AAPL ", // preserved verbatim - "timefiled": "2025-01-31T06:01:27 EST", - "formtype": "10-Q", - "filingId": "0000320193-25-000008", - "url": "https://www.sec.gov/Archives/edgar/data/320193/10q.htm", - "extra": { "nested": [1, 2, 3] }, - }; - let doc2 = rawdoc! { - "symbol": "SHOP:CA", - "timefiled": "2025-07-15T17:05:00 EDT", - "formtype": "News release", - "filingId": null, - "url": " ", - }; - - let mut buf = Vec::new(); - buf.extend_from_slice(doc1.as_bytes()); - buf.extend_from_slice(doc2.as_bytes()); - - let mut rows = Vec::new(); - let stats = decode_qm_filing_buffer(&buf, &fields, |r| { - rows.push(r.to_qm_filing(r.key.to_string())); - }) - .expect("decode succeeds"); - - assert_eq!(stats.docs_in, 2); - assert_eq!(stats.rows_out, 2); - assert_eq!(stats.skipped_total(), 0); - assert_eq!(stats.nulled_wrong_type_filing_id, 0); - assert_eq!(stats.nulled_wrong_type_url, 0); - assert_eq!(stats.docs_in, stats.rows_out + stats.skipped_total()); - - assert_eq!(rows[0].key, " AAPL "); - assert_eq!(rows[0].timefiled, "2025-01-31T06:01:27 EST"); - assert_eq!(rows[0].form_type, "10-Q"); - assert_eq!(rows[0].filing_id.as_deref(), Some("0000320193-25-000008")); - assert_eq!( - rows[0].url.as_deref(), - Some("https://www.sec.gov/Archives/edgar/data/320193/10q.htm") - ); - - assert_eq!(rows[1].key, "SHOP:CA"); - assert_eq!(rows[1].filing_id, None); - assert_eq!(rows[1].url, None); -} - -#[test] -fn qm_filings_skip_reasons_priority_and_optional_wrong_type_counters() { - let fields = default_filings_fields(); - let docs: Vec = vec![ - // 1. missing key (even though timefiled & formtype are also missing + optional wrong type) - rawdoc! { "filingId": 123, "url": false }, - // 2. wrong key type (priority over missing timefiled) - rawdoc! { "symbol": 42 }, - // 3. empty key (priority over missing formtype) - rawdoc! { "symbol": " ", "timefiled": "2025-01-31T06:01:27 EST" }, - // 4. missing timefiled (priority over missing formtype) - rawdoc! { "symbol": "AAPL" }, - // 5. wrong timefiled type - rawdoc! { "symbol": "AAPL", "timefiled": 12345, "formtype": "8-K" }, - // 6. empty timefiled - rawdoc! { "symbol": "AAPL", "timefiled": "", "formtype": "8-K" }, - // 7. missing formtype - rawdoc! { "symbol": "AAPL", "timefiled": "2025-01-31T06:01:27 EST" }, - // 8. wrong formtype type - rawdoc! { "symbol": "AAPL", "timefiled": "2025-01-31T06:01:27 EST", "formtype": 10 }, - // 9. empty formtype (with wrong-type optionals that must NOT increment nulled counters) - rawdoc! { - "symbol": "AAPL", - "timefiled": "2025-01-31T06:01:27 EST", - "formtype": " \t ", - "filingId": 999, - "url": 888, - }, - // 10. valid row with wrong-type optionals -> emitted with None + nulled counters incremented - rawdoc! { - "symbol": "MSFT", - "timefiled": "2025-02-01T16:30:00 EST", - "formtype": "8-K", - "filingId": 999, - "url": true, - }, - ]; - - let mut buf = Vec::new(); - for d in &docs { - buf.extend_from_slice(d.as_bytes()); - } - - let mut emitted = Vec::new(); - let stats = decode_qm_filing_buffer(&buf, &fields, |r| { - emitted.push(r.to_qm_filing(r.key.to_string())); - }) - .expect("decode succeeds"); - - assert_eq!(stats.docs_in, 10); - assert_eq!(stats.rows_out, 1); - assert_eq!(stats.skipped_missing_key, 1); - assert_eq!(stats.skipped_wrong_key_type, 1); - assert_eq!(stats.skipped_empty_key, 1); - assert_eq!(stats.skipped_missing_timefiled, 1); - assert_eq!(stats.skipped_wrong_timefiled_type, 1); - assert_eq!(stats.skipped_empty_timefiled, 1); - assert_eq!(stats.skipped_missing_form_type, 1); - assert_eq!(stats.skipped_wrong_form_type_type, 1); - assert_eq!(stats.skipped_empty_form_type, 1); - assert_eq!(stats.skipped_total(), 9); - assert_eq!(stats.docs_in, stats.rows_out + stats.skipped_total()); - assert_eq!(stats.nulled_wrong_type_filing_id, 1); - assert_eq!(stats.nulled_wrong_type_url, 1); - - assert_eq!(emitted.len(), 1); - assert_eq!(emitted[0].key, "MSFT"); - assert_eq!(emitted[0].filing_id, None); - assert_eq!(emitted[0].url, None); -} - -#[test] -fn qm_earnings_happy_path_types_and_ignores_consensus_eps() { - let fields = default_earnings_fields(); - let doc1 = rawdoc! { - "qmSearchCode": "AAPL", - "reportDate": dt_from_ymd(2025, 1, 30), - "announceTime": "AMC", - "periodEndDate": dt_from_ymd(2024, 12, 28), - "actualEps": 2.40_f64, - "revenue": 124_300_000_000_i64, - "consensusEps": 2.35_f64, - }; - let doc2 = rawdoc! { - "qmSearchCode": "SHOP:CA", - "reportDate": "2025-02-11", - "announceTime": "N/A", - "periodEndDate": "2024-12-31", - "actualEps": 1_i32, - "revenue": 2_810_000_000.5_f64, - "consensusEps": 0.99_f64, - }; - let doc3 = rawdoc! { - "qmSearchCode": "TD:CA", - "reportDate": "2025-02-27", - "announceTime": "BTO", - "periodEndDate": null, - "actualEps": null, - "revenue": null, - }; - - let mut buf = Vec::new(); - buf.extend_from_slice(doc1.as_bytes()); - buf.extend_from_slice(doc2.as_bytes()); - buf.extend_from_slice(doc3.as_bytes()); - - let mut rows = Vec::new(); - let stats = decode_qm_earning_buffer(&buf, &fields, |r| { - rows.push(r.to_qm_earning(r.key.to_string())); - }) - .expect("decode succeeds"); - - assert_eq!(stats.docs_in, 3); - assert_eq!(stats.rows_out, 3); - assert_eq!(stats.skipped_total(), 0); - assert_eq!(stats.docs_in, stats.rows_out + stats.skipped_total()); - - assert_eq!(rows[0].key, "AAPL"); - assert_eq!(rows[0].report_date, day(2025, 1, 30)); - assert_eq!(rows[0].announce_time, "AMC"); - assert_eq!(rows[0].fiscal_period_end, Some(day(2024, 12, 28))); - assert_eq!(rows[0].actual_eps, Some(2.40)); - assert_eq!(rows[0].revenue, Some(124_300_000_000.0)); - - assert_eq!(rows[1].key, "SHOP:CA"); - assert_eq!(rows[1].report_date, day(2025, 2, 11)); - assert_eq!(rows[1].announce_time, "N/A"); - assert_eq!(rows[1].fiscal_period_end, Some(day(2024, 12, 31))); - assert_eq!(rows[1].actual_eps, Some(1.0)); - assert_eq!(rows[1].revenue, Some(2_810_000_000.5)); - - assert_eq!(rows[2].key, "TD:CA"); - assert_eq!(rows[2].fiscal_period_end, None); - assert_eq!(rows[2].actual_eps, None); - assert_eq!(rows[2].revenue, None); -} - -#[test] -fn qm_earnings_skip_reasons_priority_and_optional_nulling_counters() { - let fields = default_earnings_fields(); - let oor_dt = DateTime::from_millis(i64::MAX); - let docs: Vec = vec![ - // 1. missing key (with bad optionals that must not increment nulled counters) - rawdoc! { "periodEndDate": 123, "actualEps": "bad", "revenue": false }, - // 2. wrong key type - rawdoc! { "qmSearchCode": 100 }, - // 3. empty key - rawdoc! { "qmSearchCode": " ", "reportDate": "2025-01-30", "announceTime": "AMC" }, - // 4. missing reportDate - rawdoc! { "qmSearchCode": "AAPL", "announceTime": "AMC" }, - // 5. wrong reportDate type - rawdoc! { "qmSearchCode": "AAPL", "reportDate": 20250130, "announceTime": "AMC" }, - // 6. invalid reportDate string - rawdoc! { "qmSearchCode": "AAPL", "reportDate": "2025-02-30", "announceTime": "AMC" }, - // 7. out-of-range reportDate DateTime - rawdoc! { "qmSearchCode": "AAPL", "reportDate": oor_dt, "announceTime": "AMC" }, - // 8. missing announceTime - rawdoc! { "qmSearchCode": "AAPL", "reportDate": "2025-01-30" }, - // 9. wrong announceTime type - rawdoc! { "qmSearchCode": "AAPL", "reportDate": "2025-01-30", "announceTime": 1 }, - // 10. empty announceTime (bad optionals must NOT increment nulled counters) - rawdoc! { - "qmSearchCode": "AAPL", - "reportDate": "2025-01-30", - "announceTime": " ", - "periodEndDate": "not-a-date", - "actualEps": "1.2", - "revenue": "500", - }, - // 11. valid row with wrong-type optionals - rawdoc! { - "qmSearchCode": "NVDA", - "reportDate": "2025-02-26", - "announceTime": "AMC", - "periodEndDate": 20250126, - "actualEps": "0.89", - "revenue": true, - }, - // 12. valid row with invalid string fiscal_period_end - rawdoc! { - "qmSearchCode": "AMD", - "reportDate": "2025-02-04", - "announceTime": "AMC", - "periodEndDate": "2024-13-01", - "actualEps": 1.09, - "revenue": 7_658_000_000_i64, - }, - // 13. valid row with out-of-range DateTime fiscal_period_end - rawdoc! { - "qmSearchCode": "INTC", - "reportDate": "2025-01-30", - "announceTime": "AMC", - "periodEndDate": oor_dt, - }, - ]; - - let mut buf = Vec::new(); - for d in &docs { - buf.extend_from_slice(d.as_bytes()); - } - - let mut emitted = Vec::new(); - let stats = decode_qm_earning_buffer(&buf, &fields, |r| { - emitted.push(r.to_qm_earning(r.key.to_string())); - }) - .expect("decode succeeds"); - - assert_eq!(stats.docs_in, 13); - assert_eq!(stats.rows_out, 3); - assert_eq!(stats.skipped_missing_key, 1); - assert_eq!(stats.skipped_wrong_key_type, 1); - assert_eq!(stats.skipped_empty_key, 1); - assert_eq!(stats.skipped_missing_report_date, 1); - assert_eq!(stats.skipped_wrong_report_date_type, 1); - assert_eq!(stats.skipped_invalid_report_date, 1); - assert_eq!(stats.skipped_report_date_out_of_range, 1); - assert_eq!(stats.skipped_missing_announce_time, 1); - assert_eq!(stats.skipped_wrong_announce_time_type, 1); - assert_eq!(stats.skipped_empty_announce_time, 1); - assert_eq!(stats.skipped_total(), 10); - assert_eq!(stats.docs_in, stats.rows_out + stats.skipped_total()); - - assert_eq!(stats.nulled_wrong_type_fiscal_period_end, 1); - assert_eq!(stats.nulled_invalid_fiscal_period_end, 2); - assert_eq!(stats.nulled_wrong_type_actual_eps, 1); - assert_eq!(stats.nulled_wrong_type_revenue, 1); - - assert_eq!(emitted.len(), 3); - assert_eq!(emitted[0].fiscal_period_end, None); - assert_eq!(emitted[0].actual_eps, None); - assert_eq!(emitted[0].revenue, None); - assert_eq!(emitted[1].fiscal_period_end, None); - assert_eq!(emitted[1].actual_eps, Some(1.09)); - assert_eq!(emitted[2].fiscal_period_end, None); -} - -#[test] -fn corrupt_and_truncated_bson_fail_closed_even_when_required_fields_missing() { - let f_fields = default_filings_fields(); - let e_fields = default_earnings_fields(); - - // Invalid UTF-8 in unused field with NO required fields present -> must still Err(CorruptBson) - let corrupt_no_req = make_raw_doc_with_invalid_utf8_unused_field(false); - assert!(matches!( - decode_qm_filing_bytes(&corrupt_no_req, &f_fields, |_| {}), - Err(BsonQmEventsError::CorruptBson { offset: 0, .. }) - )); - assert!(matches!( - decode_qm_earning_bytes(&corrupt_no_req, &e_fields, |_| {}), - Err(BsonQmEventsError::CorruptBson { offset: 0, .. }) - )); - - // Invalid UTF-8 in unused field with required fields present -> must Err(CorruptBson) - let corrupt_with_req = make_raw_doc_with_invalid_utf8_unused_field(true); - assert!(matches!( - decode_qm_filing_bytes(&corrupt_with_req, &f_fields, |_| {}), - Err(BsonQmEventsError::CorruptBson { offset: 0, .. }) - )); - - // Bad nested array index -> Err(CorruptBson) - let bad_arr = make_raw_doc_with_bad_array_index(); - assert!(matches!( - decode_qm_filing_bytes(&bad_arr, &f_fields, |_| {}), - Err(BsonQmEventsError::CorruptBson { offset: 0, .. }) - )); - assert!(matches!( - decode_qm_earning_bytes(&bad_arr, &e_fields, |_| {}), - Err(BsonQmEventsError::CorruptBson { offset: 0, .. }) - )); - - // Truncated BSON buffer after one valid doc -> Err(TruncatedDocument) with exact offset - let valid_doc = rawdoc! { - "symbol": "AAPL", - "timefiled": "2025-01-31T06:01:27 EST", - "formtype": "10-K", - }; - let mut trunc_buf = valid_doc.as_bytes().to_vec(); - let expected_offset = trunc_buf.len() as u64; - trunc_buf.extend_from_slice(&valid_doc.as_bytes()[..10]); - - let err = decode_qm_filing_buffer(&trunc_buf, &f_fields, |_| {}).unwrap_err(); - assert!(matches!( - err, - BsonQmEventsError::TruncatedDocument { offset, .. } if offset == expected_offset - )); - assert!(!err.to_string().contains('\n')); - - // Corrupt document length (< 5) -> Err(CorruptDocumentLength) - let bad_len = 3_i32.to_le_bytes(); - assert!(matches!( - decode_qm_earning_buffer(&bad_len, &e_fields, |_| {}), - Err(BsonQmEventsError::CorruptDocumentLength { - offset: 0, - declared_len: 3 - }) - )); -} diff --git a/tools/curate-etl/src/bson_qm_financials.rs b/tools/curate-etl/src/bson_qm_financials.rs deleted file mode 100644 index 8627c843..00000000 --- a/tools/curate-etl/src/bson_qm_financials.rs +++ /dev/null @@ -1,949 +0,0 @@ -//! Zero-copy raw BSON decoder for MongoDB `qmFinancials` (and `qmFinancials-old`) documents (`M2.2k`). -//! -//! Decodes `&bson::RawDocument` slices without allocating a `bson::Document`, emitting -//! [`FinancialObservation<&str>`] rows (borrowing `key` verbatim from the input BSON slice and -//! allocating the owned `currency: String` only when a row is emitted) via a caller-supplied -//! callback. -//! -//! # Unverified Live Schema & Caller-Supplied Paths -//! -//! QuoteMedia owns the source statement inputs; the existing builder -//! ([`crate::fundamentals::build_fundamentals_rows`]) owns filing linkage and `known_at` -//! derivation, while this decoder preserves the supplied `report_date` vintage and `currency`. -//! -//! Field defaults are restricted strictly to names established by in-repo evidence -//! (`apps/stock/data-ingestion/src/handlers/qm/actions/financials.action.ts` and -//! `design/DATA-CONTRACTS.md` §1): -//! - Verified defaults: `key = "qmSearchCode"` ([`DEFAULT_QM_FINANCIALS_KEY_FIELD`]), -//! `period_end = "periodEndDate"` ([`DEFAULT_QM_FINANCIALS_PERIOD_END_FIELD`]), -//! `report_date = "reportDate"` ([`DEFAULT_QM_FINANCIALS_REPORT_DATE_FIELD`]), -//! `report_period = "reportPeriod"` ([`DEFAULT_QM_FINANCIALS_REPORT_PERIOD_FIELD`]). -//! - **Unverified against a live dump:** the inner field names under `BalanceSheet`, `CashFlow`, -//! and `IncomeStatement`, the currency field path, the exact `reportPeriod` token strings, and -//! the live MongoDB BSON types of `periodEndDate` / `reportDate` have **not** been verified -//! against a live `qmFinancials` dump. Callers must therefore explicitly supply: -//! - `currency` path and each of the six numeric value paths (`Option<&str>`, dotted paths such -//! as `"IncomeStatement.totalRevenue"` or `None` to leave a field unconfigured) in -//! [`QmFinancialsFieldNames`]; -//! - [`QmFinancialsFiscalPeriod`] (`ByTokens` with explicit quarterly/annual string lists, or -//! `Fixed` for a caller-known uniform input). -//! -//! # Decoding & Validation Rules -//! - Every element and nested subdocument/array/JS-with-scope (up to depth `128`) of each -//! [`RawDocument`] is structurally validated to completion before semantic skip checks run, so -//! structural BSON corruption always returns `Err(BsonQmFinancialsError::CorruptBson)` rather -//! than being masked by an earlier semantic skip. -//! - Deterministic semantic skip priority: -//! `key` → `period_end` → `fiscal_period` (`report_period`) → `report_date` → `currency`. -//! - `key` and `currency`: required non-blank UTF-8 BSON `String`s passed verbatim (no trimming). -//! Missing, wrong-typed (including non-document intermediate segments), or blank values skip the -//! document under their respective counters. -//! - `period_end`: required BSON `DateTime` (UTC epoch day via -//! `timestamp_millis().div_euclid(86_400_000)` with checked `i32` conversion) or strict -//! `YYYY-MM-DD` UTF-8 BSON `String`, validated inclusively against -//! [`MIN_SUPPORTED_DATE`]..=[`MAX_SUPPORTED_DATE`] (`2008-01-01..=2030-12-31`). -//! - `fiscal_period`: under [`QmFinancialsFiscalPeriod::ByTokens`], `report_period` must be a -//! UTF-8 `String` matching an exact configured quarterly or annual token; missing, wrong-typed, -//! or unmapped values skip the document (fail closed). Under -//! [`QmFinancialsFiscalPeriod::Fixed`], the supplied [`FiscalPeriod`] is used without consulting -//! `fields.report_period`. -//! - `report_date` (**point-in-time vintage guard, fail closed**): only an absent path (or null -//! intermediate) or BSON `Null` emits `None`. A present but wrong-typed, malformed/blank, or -//! out-of-range `report_date` skips the document rather than silently dropping a vintage date. -//! - Numeric fields (`FundamentalsFields`): decoded only on rows that pass all skip checks. -//! Unconfigured (`None`) paths emit `None` without incrementing any null counter. Configured -//! (`Some(path)`) paths accept BSON `Double`, `Int32`, `Int64`, and UTF-8 `String`s parsed as -//! finite `f64` (trimmed before parsing); BSON `Null` emits `None` cleanly. Missing paths -//! (including missing or null intermediate subdocuments), wrong types (including non-document -//! intermediates), unparsable strings, and non-finite doubles/strings emit `None` and increment -//! `nulled_missing_path`, `nulled_wrong_type`, `nulled_unparsable_string`, or -//! `nulled_non_finite` respectively. -//! - Buffer error semantics: if [`decode_qm_financials_buffer`] encounters a framing or BSON -//! corruption error after one or more valid documents, `on_row` has already been invoked for -//! those earlier valid documents and the error carries the failing document's byte offset. -//! - Conservation invariant on [`BsonQmFinancialsDecodeStats`]: -//! `docs_in == rows_out + skipped_total()`. - -use std::error::Error; -use std::fmt; - -use bson::raw::{RawBsonRef, RawDocument}; - -use crate::bson_eod_prices::{ - iter_raw_bson_docs, parse_single_raw_doc, parse_ymd_strict_days, BsonEodPriceError, - MILLIS_PER_DAY, -}; -use crate::fundamentals::{FinancialObservation, FiscalPeriod, FundamentalsFields}; -use crate::shorts::{MAX_SUPPORTED_DATE, MIN_SUPPORTED_DATE}; - -/// Verified default BSON field name for the `qmFinancials` security key (`financials.action.ts`). -pub const DEFAULT_QM_FINANCIALS_KEY_FIELD: &str = "qmSearchCode"; -/// Verified default BSON field name for `qmFinancials.periodEndDate` (`design/DATA-CONTRACTS.md` §1). -pub const DEFAULT_QM_FINANCIALS_PERIOD_END_FIELD: &str = "periodEndDate"; -/// Verified default BSON field name for `qmFinancials.reportDate` (`financials.action.ts`, `DATA-CONTRACTS.md` §1). -pub const DEFAULT_QM_FINANCIALS_REPORT_DATE_FIELD: &str = "reportDate"; -/// Verified default BSON field name for `qmFinancials.reportPeriod` (`financials.action.ts`). -pub const DEFAULT_QM_FINANCIALS_REPORT_PERIOD_FIELD: &str = "reportPeriod"; - -/// Borrowed dotted BSON field-path configuration for decoding `qmFinancials` documents. -/// -/// Intentionally has no `Default`: live inner field names under `BalanceSheet`, `CashFlow`, and -/// `IncomeStatement` and the currency path are unverified against a live dump. Use -/// [`Self::with_verified_defaults`] to populate only the four repo-evidenced top-level defaults -/// while explicitly supplying `currency` and an `Option<&str>` choice for each of the six numeric -/// value paths. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct QmFinancialsFieldNames<'a> { - pub key: &'a str, - pub period_end: &'a str, - pub report_date: &'a str, - pub report_period: &'a str, - pub currency: &'a str, - pub revenue: Option<&'a str>, - pub net_income: Option<&'a str>, - pub operating_cash_flow: Option<&'a str>, - pub total_assets: Option<&'a str>, - pub total_equity: Option<&'a str>, - pub shares_outstanding: Option<&'a str>, -} - -impl<'a> QmFinancialsFieldNames<'a> { - /// Constructs a configuration pre-populated with the four repo-evidenced defaults - /// (`qmSearchCode`, `periodEndDate`, `reportDate`, `reportPeriod`) while requiring the caller - /// to explicitly supply the `currency` path and an `Option<&str>` choice (`Some(path)` or - /// intentional `None` opt-out) for each of the six numeric value fields. - #[inline] - pub const fn with_verified_defaults( - currency: &'a str, - revenue: Option<&'a str>, - net_income: Option<&'a str>, - operating_cash_flow: Option<&'a str>, - total_assets: Option<&'a str>, - total_equity: Option<&'a str>, - shares_outstanding: Option<&'a str>, - ) -> Self { - Self { - key: DEFAULT_QM_FINANCIALS_KEY_FIELD, - period_end: DEFAULT_QM_FINANCIALS_PERIOD_END_FIELD, - report_date: DEFAULT_QM_FINANCIALS_REPORT_DATE_FIELD, - report_period: DEFAULT_QM_FINANCIALS_REPORT_PERIOD_FIELD, - currency, - revenue, - net_income, - operating_cash_flow, - total_assets, - total_equity, - shares_outstanding, - } - } - - /// Validates that every configured dotted field path is non-empty/non-blank and contains no - /// empty or whitespace-only segments (rejecting leading, trailing, or consecutive dots). - pub fn validate(&self) -> Result<(), BsonQmFinancialsError> { - let roles: [(&'static str, Option<&str>); 11] = [ - ("key", Some(self.key)), - ("period_end", Some(self.period_end)), - ("report_date", Some(self.report_date)), - ("report_period", Some(self.report_period)), - ("currency", Some(self.currency)), - ("revenue", self.revenue), - ("net_income", self.net_income), - ("operating_cash_flow", self.operating_cash_flow), - ("total_assets", self.total_assets), - ("total_equity", self.total_equity), - ("shares_outstanding", self.shares_outstanding), - ]; - - for &(role, path_opt) in &roles { - if let Some(path) = path_opt { - validate_dotted_path(role, path)?; - } - } - - Ok(()) - } -} - -fn validate_dotted_path(role: &'static str, path: &str) -> Result<(), BsonQmFinancialsError> { - if path.is_empty() || path.trim().is_empty() { - return Err(BsonQmFinancialsError::InvalidFieldNames { - detail: format!("field path for '{role}' must not be empty or blank"), - }); - } - for segment in path.split('.') { - if segment.is_empty() || segment.trim().is_empty() { - return Err(BsonQmFinancialsError::InvalidFieldNames { - detail: format!( - "field path '{path}' for '{role}' contains an empty or blank segment" - ), - }); - } - } - Ok(()) -} - -/// Explicit fiscal-period resolution policy for `qmFinancials` documents. -/// -/// Intentionally has no `Default`: the live `reportPeriod` token strings in MongoDB are -/// unverified in the repository, so callers must either supply explicit token lists or a fixed -/// [`FiscalPeriod`] override for a caller-known uniform input. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum QmFinancialsFiscalPeriod<'a> { - /// Map exact UTF-8 BSON `String` values of `fields.report_period` against caller-supplied - /// quarterly and annual token slices. Missing, wrong-typed, or unmapped values skip the - /// document (fail closed). - ByTokens { - quarterly: &'a [&'a str], - annual: &'a [&'a str], - }, - /// Assign a fixed [`FiscalPeriod`] to every decoded document without consulting - /// `fields.report_period`. - Fixed(FiscalPeriod), -} - -impl<'a> QmFinancialsFiscalPeriod<'a> { - /// Validates token-mode configuration, rejecting empty/blank tokens and any token present in - /// both `quarterly` and `annual`. - pub fn validate(&self) -> Result<(), BsonQmFinancialsError> { - match *self { - Self::Fixed(_) => Ok(()), - Self::ByTokens { quarterly, annual } => { - for &tok in quarterly { - if tok.is_empty() || tok.trim().is_empty() { - return Err(BsonQmFinancialsError::InvalidFiscalPeriodConfig { - detail: "quarterly report_period token must not be empty or blank" - .to_string(), - }); - } - } - for &tok in annual { - if tok.is_empty() || tok.trim().is_empty() { - return Err(BsonQmFinancialsError::InvalidFiscalPeriodConfig { - detail: "annual report_period token must not be empty or blank" - .to_string(), - }); - } - } - for &q_tok in quarterly { - if annual.contains(&q_tok) { - return Err(BsonQmFinancialsError::InvalidFiscalPeriodConfig { - detail: format!( - "report_period token '{q_tok}' cannot appear in both quarterly and annual lists" - ), - }); - } - } - Ok(()) - } - } - } -} - -/// Typed errors returned while validating configuration or decoding raw `qmFinancials` BSON. -/// -/// Structural BSON framing or element errors fail closed and carry a `u64` byte offset; -/// every variant's `Display` output is a single line. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum BsonQmFinancialsError { - /// Invalid [`QmFinancialsFieldNames`] configuration (empty/blank path or segment). - InvalidFieldNames { detail: String }, - /// Invalid [`QmFinancialsFiscalPeriod`] configuration (blank token or overlapping token lists). - InvalidFiscalPeriodConfig { detail: String }, - /// Buffer ended before a complete 4-byte length prefix or declared document body. - TruncatedDocument { - offset: u64, - remaining: usize, - declared_len: Option, - }, - /// Declared 4-byte little-endian BSON document length was `< 5` (or did not match a single - /// document slice). - CorruptDocumentLength { offset: u64, declared_len: i32 }, - /// Underlying BSON framing or element bytes were malformed. - CorruptBson { offset: u64, detail: String }, -} - -impl fmt::Display for BsonQmFinancialsError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::InvalidFieldNames { detail } => { - write!(f, "invalid qmFinancials field configuration: {detail}") - } - Self::InvalidFiscalPeriodConfig { detail } => { - write!( - f, - "invalid qmFinancials fiscal period configuration: {detail}" - ) - } - Self::TruncatedDocument { - offset, - remaining, - declared_len, - } => match declared_len { - Some(len) => write!( - f, - "truncated BSON document at byte offset {offset}: declared length {len} exceeds remaining {remaining} bytes" - ), - None => write!( - f, - "truncated BSON document header at byte offset {offset}: only {remaining} bytes remaining" - ), - }, - Self::CorruptDocumentLength { - offset, - declared_len, - } => write!( - f, - "corrupt BSON document length {declared_len} at byte offset {offset}" - ), - Self::CorruptBson { offset, detail } => { - write!(f, "corrupt BSON bytes at byte offset {offset}: {detail}") - } - } - } -} - -impl Error for BsonQmFinancialsError {} - -#[inline] -fn map_framing_error(err: BsonEodPriceError) -> BsonQmFinancialsError { - match err { - BsonEodPriceError::TruncatedDocument { - offset, - remaining, - declared_len, - } => BsonQmFinancialsError::TruncatedDocument { - offset: offset as u64, - remaining, - declared_len, - }, - BsonEodPriceError::CorruptDocumentLength { - offset, - declared_len, - } => BsonQmFinancialsError::CorruptDocumentLength { - offset: offset as u64, - declared_len, - }, - BsonEodPriceError::CorruptBson { offset, detail } => BsonQmFinancialsError::CorruptBson { - offset: offset as u64, - detail, - }, - other => BsonQmFinancialsError::CorruptBson { - offset: 0, - detail: other.to_string(), - }, - } -} - -/// Per-batch decode accounting for `qmFinancials`. -/// -/// Conservation invariant: -/// `docs_in == rows_out + skipped_total()` -/// -/// Numeric null counters (`nulled_missing_path`, `nulled_wrong_type`, -/// `nulled_unparsable_string`, `nulled_non_finite`) are incremented only on emitted rows and are -/// excluded from [`Self::skipped_total`]. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct BsonQmFinancialsDecodeStats { - pub docs_in: usize, - pub rows_out: usize, - pub skipped_missing_key: usize, - pub skipped_wrong_key_type: usize, - pub skipped_empty_key: usize, - pub skipped_missing_period_end: usize, - pub skipped_wrong_period_end_type: usize, - pub skipped_invalid_period_end: usize, - pub skipped_period_end_out_of_range: usize, - pub skipped_missing_report_period: usize, - pub skipped_wrong_report_period_type: usize, - pub skipped_unmapped_report_period: usize, - pub skipped_wrong_report_date_type: usize, - pub skipped_invalid_report_date: usize, - pub skipped_report_date_out_of_range: usize, - pub skipped_missing_currency: usize, - pub skipped_wrong_currency_type: usize, - pub skipped_empty_currency: usize, - pub nulled_missing_path: usize, - pub nulled_wrong_type: usize, - pub nulled_unparsable_string: usize, - pub nulled_non_finite: usize, -} - -impl BsonQmFinancialsDecodeStats { - /// Total number of semantically skipped `qmFinancials` documents across all skip categories. - #[inline] - pub fn skipped_total(&self) -> usize { - self.skipped_missing_key - + self.skipped_wrong_key_type - + self.skipped_empty_key - + self.skipped_missing_period_end - + self.skipped_wrong_period_end_type - + self.skipped_invalid_period_end - + self.skipped_period_end_out_of_range - + self.skipped_missing_report_period - + self.skipped_wrong_report_period_type - + self.skipped_unmapped_report_period - + self.skipped_wrong_report_date_type - + self.skipped_invalid_report_date - + self.skipped_report_date_out_of_range - + self.skipped_missing_currency - + self.skipped_wrong_currency_type - + self.skipped_empty_currency - } - - /// Accumulates counters from another batch into `self`. - #[inline] - pub fn merge(&mut self, other: &Self) { - self.docs_in += other.docs_in; - self.rows_out += other.rows_out; - self.skipped_missing_key += other.skipped_missing_key; - self.skipped_wrong_key_type += other.skipped_wrong_key_type; - self.skipped_empty_key += other.skipped_empty_key; - self.skipped_missing_period_end += other.skipped_missing_period_end; - self.skipped_wrong_period_end_type += other.skipped_wrong_period_end_type; - self.skipped_invalid_period_end += other.skipped_invalid_period_end; - self.skipped_period_end_out_of_range += other.skipped_period_end_out_of_range; - self.skipped_missing_report_period += other.skipped_missing_report_period; - self.skipped_wrong_report_period_type += other.skipped_wrong_report_period_type; - self.skipped_unmapped_report_period += other.skipped_unmapped_report_period; - self.skipped_wrong_report_date_type += other.skipped_wrong_report_date_type; - self.skipped_invalid_report_date += other.skipped_invalid_report_date; - self.skipped_report_date_out_of_range += other.skipped_report_date_out_of_range; - self.skipped_missing_currency += other.skipped_missing_currency; - self.skipped_wrong_currency_type += other.skipped_wrong_currency_type; - self.skipped_empty_currency += other.skipped_empty_currency; - self.nulled_missing_path += other.nulled_missing_path; - self.nulled_wrong_type += other.nulled_wrong_type; - self.nulled_unparsable_string += other.nulled_unparsable_string; - self.nulled_non_finite += other.nulled_non_finite; - } -} - -impl std::ops::AddAssign for BsonQmFinancialsDecodeStats { - #[inline] - fn add_assign(&mut self, rhs: Self) { - self.merge(&rhs); - } -} - -/// Maximum recursive nesting depth accepted while validating raw BSON documents and arrays. -const MAX_BSON_VALIDATION_DEPTH: usize = 128; - -#[inline] -fn is_exact_array_index(key: &str, expected: usize) -> bool { - let bytes = key.as_bytes(); - if bytes.is_empty() || (bytes.len() > 1 && bytes[0] == b'0') { - return false; - } - let mut parsed: usize = 0; - for &b in bytes { - if !b.is_ascii_digit() { - return false; - } - let digit = usize::from(b - b'0'); - match parsed.checked_mul(10).and_then(|n| n.checked_add(digit)) { - Some(next) => parsed = next, - None => return false, - } - } - parsed == expected -} - -fn validate_raw_bson_value( - val: RawBsonRef<'_>, - doc_offset: u64, - field_name: &str, - depth: usize, -) -> Result<(), BsonQmFinancialsError> { - match val { - RawBsonRef::Document(subdoc) => { - validate_raw_document(subdoc, doc_offset, field_name, depth + 1) - } - RawBsonRef::Array(arr) => { - if depth >= MAX_BSON_VALIDATION_DEPTH { - return Err(BsonQmFinancialsError::CorruptBson { - offset: doc_offset, - detail: format!( - "field '{field_name}': nested BSON depth exceeds limit {MAX_BSON_VALIDATION_DEPTH}" - ), - }); - } - for (expected_idx, elem_res) in arr.iter_elements().enumerate() { - let elem = elem_res.map_err(|err| BsonQmFinancialsError::CorruptBson { - offset: doc_offset, - detail: format!("field '{field_name}': {err}"), - })?; - let key = elem.key().as_str(); - if !is_exact_array_index(key, expected_idx) { - return Err(BsonQmFinancialsError::CorruptBson { - offset: doc_offset, - detail: format!( - "field '{field_name}': invalid BSON array index '{key}' at position {expected_idx}" - ), - }); - } - let item = elem - .value() - .map_err(|err| BsonQmFinancialsError::CorruptBson { - offset: doc_offset, - detail: format!("field '{field_name}': {err}"), - })?; - validate_raw_bson_value(item, doc_offset, field_name, depth + 1)?; - } - Ok(()) - } - RawBsonRef::JavaScriptCodeWithScope(code_with_scope) => { - validate_raw_document(code_with_scope.scope, doc_offset, field_name, depth + 1) - } - _ => Ok(()), - } -} - -fn validate_raw_document( - doc: &RawDocument, - doc_offset: u64, - field_name: &str, - depth: usize, -) -> Result<(), BsonQmFinancialsError> { - if depth > MAX_BSON_VALIDATION_DEPTH { - return Err(BsonQmFinancialsError::CorruptBson { - offset: doc_offset, - detail: format!( - "field '{field_name}': nested BSON depth exceeds limit {MAX_BSON_VALIDATION_DEPTH}" - ), - }); - } - for elem_res in doc.iter_elements() { - let elem = elem_res.map_err(|err| BsonQmFinancialsError::CorruptBson { - offset: doc_offset, - detail: format!("field '{field_name}': {err}"), - })?; - let val = elem - .value() - .map_err(|err| BsonQmFinancialsError::CorruptBson { - offset: doc_offset, - detail: format!("field '{field_name}': {err}"), - })?; - validate_raw_bson_value(val, doc_offset, field_name, depth)?; - } - Ok(()) -} - -fn validate_top_level_document( - doc: &RawDocument, - doc_offset: u64, -) -> Result<(), BsonQmFinancialsError> { - for elem_res in doc.iter_elements() { - let elem = elem_res.map_err(|err| BsonQmFinancialsError::CorruptBson { - offset: doc_offset, - detail: err.to_string(), - })?; - let name = elem.key().as_str(); - let val = elem - .value() - .map_err(|err| BsonQmFinancialsError::CorruptBson { - offset: doc_offset, - detail: format!("field '{name}': {err}"), - })?; - validate_raw_bson_value(val, doc_offset, name, 0)?; - } - Ok(()) -} - -enum PathLookup<'a> { - Found(RawBsonRef<'a>), - Missing, - NonDocumentIntermediate, -} - -fn lookup_dotted_path<'a>( - doc: &'a RawDocument, - path: &str, - doc_offset: u64, -) -> Result, BsonQmFinancialsError> { - let mut current_doc = doc; - let mut segments = path.split('.').peekable(); - - while let Some(seg) = segments.next() { - let is_last = segments.peek().is_none(); - let mut matched: Option> = None; - - for elem_res in current_doc.iter_elements() { - let elem = elem_res.map_err(|err| BsonQmFinancialsError::CorruptBson { - offset: doc_offset, - detail: err.to_string(), - })?; - if elem.key().as_str() == seg { - let val = elem - .value() - .map_err(|err| BsonQmFinancialsError::CorruptBson { - offset: doc_offset, - detail: format!("field '{path}': {err}"), - })?; - matched = Some(val); - } - } - - let Some(val) = matched else { - return Ok(PathLookup::Missing); - }; - - if is_last { - return Ok(PathLookup::Found(val)); - } - - match val { - RawBsonRef::Document(subdoc) => { - current_doc = subdoc; - } - RawBsonRef::Null => return Ok(PathLookup::Missing), - _ => return Ok(PathLookup::NonDocumentIntermediate), - } - } - - Ok(PathLookup::Missing) -} - -#[inline] -fn is_supported_date(epoch_day: i32) -> bool { - (MIN_SUPPORTED_DATE..=MAX_SUPPORTED_DATE).contains(&epoch_day) -} - -enum DateParseResult { - Valid(i32), - WrongType, - Invalid, - OutOfRange, -} - -#[inline] -fn decode_date_value(val: RawBsonRef<'_>) -> DateParseResult { - match val { - RawBsonRef::DateTime(dt) => { - let days = dt.timestamp_millis().div_euclid(MILLIS_PER_DAY); - match i32::try_from(days) { - Ok(d) if is_supported_date(d) => DateParseResult::Valid(d), - _ => DateParseResult::OutOfRange, - } - } - RawBsonRef::String(s) => match parse_ymd_strict_days(s) { - Some(d) if is_supported_date(d) => DateParseResult::Valid(d), - Some(_) => DateParseResult::OutOfRange, - None => DateParseResult::Invalid, - }, - _ => DateParseResult::WrongType, - } -} - -fn decode_numeric_field( - doc: &RawDocument, - path_opt: Option<&str>, - doc_offset: u64, - stats: &mut BsonQmFinancialsDecodeStats, -) -> Result, BsonQmFinancialsError> { - let Some(path) = path_opt else { - return Ok(None); - }; - - match lookup_dotted_path(doc, path, doc_offset)? { - PathLookup::Missing => { - stats.nulled_missing_path += 1; - Ok(None) - } - PathLookup::NonDocumentIntermediate => { - stats.nulled_wrong_type += 1; - Ok(None) - } - PathLookup::Found(val) => match val { - RawBsonRef::Null => Ok(None), - RawBsonRef::Double(v) => { - if v.is_finite() { - Ok(Some(v)) - } else { - stats.nulled_non_finite += 1; - Ok(None) - } - } - RawBsonRef::Int32(v) => Ok(Some(f64::from(v))), - RawBsonRef::Int64(v) => Ok(Some(v as f64)), - RawBsonRef::String(s) => { - let trimmed = s.trim(); - match trimmed.parse::() { - Ok(v) if v.is_finite() => Ok(Some(v)), - Ok(_) => { - stats.nulled_non_finite += 1; - Ok(None) - } - Err(_) => { - stats.nulled_unparsable_string += 1; - Ok(None) - } - } - } - _ => { - stats.nulled_wrong_type += 1; - Ok(None) - } - }, - } -} - -fn decode_qm_financials_doc_at<'a, F>( - doc: &'a RawDocument, - doc_offset: u64, - fields: &QmFinancialsFieldNames<'_>, - fiscal_period_cfg: QmFinancialsFiscalPeriod<'_>, - mut on_row: F, -) -> Result -where - F: FnMut(FinancialObservation<&'a str>), -{ - // Validate the entire raw document structurally first so BSON corruption always returns - // `Err(BsonQmFinancialsError::CorruptBson)` rather than being masked by a semantic skip. - validate_top_level_document(doc, doc_offset)?; - - let mut stats = BsonQmFinancialsDecodeStats { - docs_in: 1, - ..BsonQmFinancialsDecodeStats::default() - }; - - // 1. Key (required non-blank UTF-8 string, borrowed verbatim). - let key = match lookup_dotted_path(doc, fields.key, doc_offset)? { - PathLookup::Missing => { - stats.skipped_missing_key += 1; - return Ok(stats); - } - PathLookup::NonDocumentIntermediate => { - stats.skipped_wrong_key_type += 1; - return Ok(stats); - } - PathLookup::Found(RawBsonRef::String(s)) => { - if s.trim().is_empty() { - stats.skipped_empty_key += 1; - return Ok(stats); - } - s - } - PathLookup::Found(_) => { - stats.skipped_wrong_key_type += 1; - return Ok(stats); - } - }; - - // 2. Period end date (required DateTime or strict YYYY-MM-DD within supported calendar bounds). - let period_end = match lookup_dotted_path(doc, fields.period_end, doc_offset)? { - PathLookup::Missing => { - stats.skipped_missing_period_end += 1; - return Ok(stats); - } - PathLookup::NonDocumentIntermediate => { - stats.skipped_wrong_period_end_type += 1; - return Ok(stats); - } - PathLookup::Found(val) => match decode_date_value(val) { - DateParseResult::Valid(d) => d, - DateParseResult::WrongType => { - stats.skipped_wrong_period_end_type += 1; - return Ok(stats); - } - DateParseResult::Invalid => { - stats.skipped_invalid_period_end += 1; - return Ok(stats); - } - DateParseResult::OutOfRange => { - stats.skipped_period_end_out_of_range += 1; - return Ok(stats); - } - }, - }; - - // 3. Fiscal period (explicit token mapping or fixed override; fail closed in token mode). - let fiscal_period = match fiscal_period_cfg { - QmFinancialsFiscalPeriod::Fixed(fp) => fp, - QmFinancialsFiscalPeriod::ByTokens { quarterly, annual } => { - match lookup_dotted_path(doc, fields.report_period, doc_offset)? { - PathLookup::Missing => { - stats.skipped_missing_report_period += 1; - return Ok(stats); - } - PathLookup::NonDocumentIntermediate => { - stats.skipped_wrong_report_period_type += 1; - return Ok(stats); - } - PathLookup::Found(RawBsonRef::String(s)) => { - if quarterly.contains(&s) { - FiscalPeriod::Quarterly - } else if annual.contains(&s) { - FiscalPeriod::Annual - } else { - stats.skipped_unmapped_report_period += 1; - return Ok(stats); - } - } - PathLookup::Found(_) => { - stats.skipped_wrong_report_period_type += 1; - return Ok(stats); - } - } - } - }; - - // 4. Report date (optional vintage date: only absent or BSON Null -> None; invalid skips row). - let report_date = match lookup_dotted_path(doc, fields.report_date, doc_offset)? { - PathLookup::Missing => None, - PathLookup::NonDocumentIntermediate => { - stats.skipped_wrong_report_date_type += 1; - return Ok(stats); - } - PathLookup::Found(RawBsonRef::Null) => None, - PathLookup::Found(val) => match decode_date_value(val) { - DateParseResult::Valid(d) => Some(d), - DateParseResult::WrongType => { - stats.skipped_wrong_report_date_type += 1; - return Ok(stats); - } - DateParseResult::Invalid => { - stats.skipped_invalid_report_date += 1; - return Ok(stats); - } - DateParseResult::OutOfRange => { - stats.skipped_report_date_out_of_range += 1; - return Ok(stats); - } - }, - }; - - // 5. Currency (required non-blank UTF-8 string; owned String allocated only on emission). - let currency_str = match lookup_dotted_path(doc, fields.currency, doc_offset)? { - PathLookup::Missing => { - stats.skipped_missing_currency += 1; - return Ok(stats); - } - PathLookup::NonDocumentIntermediate => { - stats.skipped_wrong_currency_type += 1; - return Ok(stats); - } - PathLookup::Found(RawBsonRef::String(s)) => { - if s.trim().is_empty() { - stats.skipped_empty_currency += 1; - return Ok(stats); - } - s - } - PathLookup::Found(_) => { - stats.skipped_wrong_currency_type += 1; - return Ok(stats); - } - }; - - // Row passed all skip checks: decode configured numeric statement fields and emit. - let statement_fields = FundamentalsFields { - revenue: decode_numeric_field(doc, fields.revenue, doc_offset, &mut stats)?, - net_income: decode_numeric_field(doc, fields.net_income, doc_offset, &mut stats)?, - operating_cash_flow: decode_numeric_field( - doc, - fields.operating_cash_flow, - doc_offset, - &mut stats, - )?, - total_assets: decode_numeric_field(doc, fields.total_assets, doc_offset, &mut stats)?, - total_equity: decode_numeric_field(doc, fields.total_equity, doc_offset, &mut stats)?, - shares_outstanding: decode_numeric_field( - doc, - fields.shares_outstanding, - doc_offset, - &mut stats, - )?, - }; - - stats.rows_out += 1; - on_row(FinancialObservation { - key, - period_end, - fiscal_period, - currency: currency_str.to_owned(), - report_date, - fields: statement_fields, - }); - Ok(stats) -} - -/// Decodes a single `&RawDocument` representing a `qmFinancials` MongoDB document without -/// allocating a `bson::Document`. -/// -/// Validates `fields` and `fiscal_period` before inspecting the document. -pub fn decode_qm_financials_doc<'a, F>( - doc: &'a RawDocument, - fields: &QmFinancialsFieldNames<'_>, - fiscal_period: QmFinancialsFiscalPeriod<'_>, - on_row: F, -) -> Result -where - F: FnMut(FinancialObservation<&'a str>), -{ - fields.validate()?; - fiscal_period.validate()?; - decode_qm_financials_doc_at(doc, 0, fields, fiscal_period, on_row) -} - -/// Decodes a single length-prefixed raw BSON document byte slice representing a `qmFinancials` -/// document. -/// -/// Validates `fields` and `fiscal_period` before inspecting the bytes. -pub fn decode_qm_financials_bytes<'a, F>( - bytes: &'a [u8], - fields: &QmFinancialsFieldNames<'_>, - fiscal_period: QmFinancialsFiscalPeriod<'_>, - on_row: F, -) -> Result -where - F: FnMut(FinancialObservation<&'a str>), -{ - fields.validate()?; - fiscal_period.validate()?; - let doc = parse_single_raw_doc(bytes).map_err(map_framing_error)?; - decode_qm_financials_doc_at(doc, 0, fields, fiscal_period, on_row) -} - -/// Streams a concatenated length-prefixed BSON buffer of `qmFinancials` documents through -/// [`decode_qm_financials_doc`], emitting every valid [`FinancialObservation<&str>`] to `on_row` -/// and failing closed on the first structural BSON framing or element corruption. -/// -/// Validates `fields` and `fiscal_period` once before reading the buffer. If an error occurs after -/// one or more valid documents, `on_row` has already been invoked for those earlier documents and -/// the returned error reports the failing document's byte offset. -/// -/// Always maintains `stats.docs_in == stats.rows_out + stats.skipped_total()`. -pub fn decode_qm_financials_buffer<'a, F>( - buf: &'a [u8], - fields: &QmFinancialsFieldNames<'_>, - fiscal_period: QmFinancialsFiscalPeriod<'_>, - mut on_row: F, -) -> Result -where - F: FnMut(FinancialObservation<&'a str>), -{ - fields.validate()?; - fiscal_period.validate()?; - let mut total = BsonQmFinancialsDecodeStats::default(); - let mut iter = iter_raw_bson_docs(buf); - while let Some(item) = iter.next_with_offset() { - match item { - Ok((offset, doc)) => { - let doc_stats = decode_qm_financials_doc_at( - doc, - offset as u64, - fields, - fiscal_period, - &mut on_row, - )?; - total += doc_stats; - } - Err((_, err)) => return Err(map_framing_error(err)), - } - } - Ok(total) -} - -#[cfg(test)] -#[path = "bson_qm_financials_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/bson_qm_financials_tests.rs b/tools/curate-etl/src/bson_qm_financials_tests.rs deleted file mode 100644 index b563060a..00000000 --- a/tools/curate-etl/src/bson_qm_financials_tests.rs +++ /dev/null @@ -1,1007 +0,0 @@ -use std::collections::BTreeMap; - -use bson::raw::{cstr, RawArrayBuf, RawBson, RawDocument, RawDocumentBuf}; -use bson::DateTime as BsonDateTime; - -use super::*; -use crate::events::{QmFiling, KNOWN_AT_SOURCE_FILING_TIMESTAMP}; -use crate::fundamentals::{ - as_of, build_fundamentals_rows, build_fundamentals_snapshots, StatutoryLagVenue, -}; -use crate::shorts::epoch_days_to_ymd; -use crate::split::ymd_to_epoch_days; - -fn assert_conservation(stats: &BsonQmFinancialsDecodeStats) { - assert_eq!( - stats.docs_in, - stats.rows_out + stats.skipped_total(), - "conservation invariant failed: {stats:?}" - ); -} - -fn full_test_fields() -> QmFinancialsFieldNames<'static> { - QmFinancialsFieldNames::with_verified_defaults( - "currency", - Some("IncomeStatement.totalRevenue"), - Some("IncomeStatement.netIncome"), - Some("CashFlow.operatingCashFlow"), - Some("BalanceSheet.totalAssets"), - Some("BalanceSheet.totalEquity"), - Some("BalanceSheet.commonSharesOutstanding"), - ) -} - -const QUARTERLY_TOKENS: &[&str] = &["Q", "Q1", "Q2", "Q3", "Q4"]; -const ANNUAL_TOKENS: &[&str] = &["A", "FY"]; - -fn token_period_cfg() -> QmFinancialsFiscalPeriod<'static> { - QmFinancialsFiscalPeriod::ByTokens { - quarterly: QUARTERLY_TOKENS, - annual: ANNUAL_TOKENS, - } -} - -fn make_nested_doc( - key: &str, - period_end: RawBson, - report_period: &str, - report_date: Option, - currency: &str, - statements: (RawDocumentBuf, RawDocumentBuf, RawDocumentBuf), -) -> RawDocumentBuf { - let (income, balance, cash_flow) = statements; - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), key); - doc.append(cstr!("periodEndDate"), period_end); - doc.append(cstr!("reportPeriod"), report_period); - if let Some(rd) = report_date { - doc.append(cstr!("reportDate"), rd); - } - doc.append(cstr!("currency"), currency); - doc.append(cstr!("IncomeStatement"), income); - doc.append(cstr!("BalanceSheet"), balance); - doc.append(cstr!("CashFlow"), cash_flow); - doc -} - -fn make_valid_doc(key: &str) -> RawDocumentBuf { - let mut income = RawDocumentBuf::new(); - income.append(cstr!("totalRevenue"), 1_250_000.5_f64); - income.append(cstr!("netIncome"), 125_000_i32); - - let mut balance = RawDocumentBuf::new(); - balance.append(cstr!("totalAssets"), 9_000_000_000_i64); - balance.append(cstr!("totalEquity"), "4500000.25"); - balance.append(cstr!("commonSharesOutstanding"), " 100000000 "); - - let mut cash_flow = RawDocumentBuf::new(); - cash_flow.append(cstr!("operatingCashFlow"), 300_000.75_f64); - - make_nested_doc( - key, - RawBson::String("2024-06-30".to_string()), - "Q2", - Some(RawBson::String("2024-08-02".to_string())), - "USD", - (income, balance, cash_flow), - ) -} - -#[test] -fn decodes_nested_statements_all_entry_points_date_and_numeric_types() { - let fields = full_test_fields(); - let period_cfg = token_period_cfg(); - - // Doc 1: String dates + Double, Int32, Int64, numeric String (with spaces). - let doc1 = make_valid_doc("AAPL:US"); - - // Doc 2: BSON DateTime dates (mid-day UTC) + Annual token + negative numeric string. - let pe_day = ymd_to_epoch_days(2024, 12, 31).unwrap(); - let rd_day = ymd_to_epoch_days(2025, 2, 14).unwrap(); - let mut income2 = RawDocumentBuf::new(); - income2.append(cstr!("totalRevenue"), 5_000_000_i64); - income2.append(cstr!("netIncome"), "-42500.5"); - let mut balance2 = RawDocumentBuf::new(); - balance2.append(cstr!("totalAssets"), 20_000_000_i32); - balance2.append(cstr!("totalEquity"), 12_500_000.0_f64); - balance2.append(cstr!("commonSharesOutstanding"), 50_000_000_i64); - let mut cash2 = RawDocumentBuf::new(); - cash2.append(cstr!("operatingCashFlow"), -10_000_i32); - - let doc2 = make_nested_doc( - "SHOP:CA", - RawBson::DateTime(BsonDateTime::from_millis( - i64::from(pe_day) * MILLIS_PER_DAY + 43_200_000, - )), - "FY", - Some(RawBson::DateTime(BsonDateTime::from_millis( - i64::from(rd_day) * MILLIS_PER_DAY + 3_600_000, - ))), - "CAD", - (income2, balance2, cash2), - ); - - // 1. decode_qm_financials_doc (zero-copy check on borrowed key) - let raw_doc1: &RawDocument = doc1.as_ref(); - let raw_bytes1 = raw_doc1.as_bytes(); - let range1 = raw_bytes1.as_ptr() as usize..raw_bytes1.as_ptr() as usize + raw_bytes1.len(); - let mut rows_doc = Vec::new(); - let stats_doc = decode_qm_financials_doc(raw_doc1, &fields, period_cfg, |obs| { - let key_ptr = obs.key.as_ptr() as usize; - assert!( - range1.contains(&key_ptr), - "expected key to borrow directly from input RawDocument slice" - ); - rows_doc.push(obs); - }) - .unwrap(); - assert_conservation(&stats_doc); - assert_eq!(stats_doc.docs_in, 1); - assert_eq!(stats_doc.rows_out, 1); - assert_eq!(rows_doc.len(), 1); - assert_eq!( - rows_doc[0], - FinancialObservation { - key: "AAPL:US", - period_end: ymd_to_epoch_days(2024, 6, 30).unwrap(), - fiscal_period: FiscalPeriod::Quarterly, - currency: "USD".to_string(), - report_date: Some(ymd_to_epoch_days(2024, 8, 2).unwrap()), - fields: FundamentalsFields { - revenue: Some(1_250_000.5), - net_income: Some(125_000.0), - operating_cash_flow: Some(300_000.75), - total_assets: Some(9_000_000_000.0), - total_equity: Some(4_500_000.25), - shares_outstanding: Some(100_000_000.0), - }, - } - ); - - // 2. decode_qm_financials_bytes - let bytes2 = doc2.as_bytes(); - let mut rows_bytes = Vec::new(); - let stats_bytes = decode_qm_financials_bytes(bytes2, &fields, period_cfg, |obs| { - rows_bytes.push(obs); - }) - .unwrap(); - assert_conservation(&stats_bytes); - assert_eq!(stats_bytes.docs_in, 1); - assert_eq!(stats_bytes.rows_out, 1); - assert_eq!( - rows_bytes[0], - FinancialObservation { - key: "SHOP:CA", - period_end: pe_day, - fiscal_period: FiscalPeriod::Annual, - currency: "CAD".to_string(), - report_date: Some(rd_day), - fields: FundamentalsFields { - revenue: Some(5_000_000.0), - net_income: Some(-42_500.5), - operating_cash_flow: Some(-10_000.0), - total_assets: Some(20_000_000.0), - total_equity: Some(12_500_000.0), - shares_outstanding: Some(50_000_000.0), - }, - } - ); - - // 3. decode_qm_financials_buffer - let mut buf = Vec::new(); - buf.extend_from_slice(doc1.as_bytes()); - buf.extend_from_slice(doc2.as_bytes()); - let mut rows_buf = Vec::new(); - let stats_buf = decode_qm_financials_buffer(&buf, &fields, period_cfg, |obs| { - rows_buf.push(obs); - }) - .unwrap(); - assert_conservation(&stats_buf); - assert_eq!(stats_buf.docs_in, 2); - assert_eq!(stats_buf.rows_out, 2); - assert_eq!(rows_buf, vec![rows_doc[0].clone(), rows_bytes[0].clone()]); -} - -#[test] -fn rejects_invalid_field_paths_and_fiscal_period_configs_before_decoding() { - let base = full_test_fields(); - let bad_field_configs = [ - QmFinancialsFieldNames { key: "", ..base }, - QmFinancialsFieldNames { key: " ", ..base }, - QmFinancialsFieldNames { - period_end: ".periodEndDate", - ..base - }, - QmFinancialsFieldNames { - report_date: "reportDate.", - ..base - }, - QmFinancialsFieldNames { - report_period: "a..b", - ..base - }, - QmFinancialsFieldNames { - currency: "", - ..base - }, - QmFinancialsFieldNames { - currency: "meta. .currency", - ..base - }, - QmFinancialsFieldNames { - revenue: Some(""), - ..base - }, - QmFinancialsFieldNames { - net_income: Some(".netIncome"), - ..base - }, - QmFinancialsFieldNames { - operating_cash_flow: Some("CashFlow."), - ..base - }, - QmFinancialsFieldNames { - total_assets: Some("BalanceSheet..totalAssets"), - ..base - }, - QmFinancialsFieldNames { - total_equity: Some("BalanceSheet. \t .totalEquity"), - ..base - }, - QmFinancialsFieldNames { - shares_outstanding: Some("."), - ..base - }, - ]; - - let doc = make_valid_doc("AAPL:US"); - - for cfg in bad_field_configs { - let err = cfg.validate().unwrap_err(); - assert!( - matches!(err, BsonQmFinancialsError::InvalidFieldNames { .. }), - "expected InvalidFieldNames for {cfg:?}, got {err:?}" - ); - assert!(!err.to_string().contains('\n')); - - let mut called = false; - assert!(matches!( - decode_qm_financials_doc(doc.as_ref(), &cfg, token_period_cfg(), |_| called = true), - Err(BsonQmFinancialsError::InvalidFieldNames { .. }) - )); - assert!(matches!( - decode_qm_financials_bytes(doc.as_bytes(), &cfg, token_period_cfg(), |_| called = true), - Err(BsonQmFinancialsError::InvalidFieldNames { .. }) - )); - assert!(matches!( - decode_qm_financials_buffer(doc.as_bytes(), &cfg, token_period_cfg(), |_| called = - true), - Err(BsonQmFinancialsError::InvalidFieldNames { .. }) - )); - assert!(!called); - } - - let bad_period_configs = [ - QmFinancialsFiscalPeriod::ByTokens { - quarterly: &["Q", "BOTH"], - annual: &["FY", "BOTH"], - }, - QmFinancialsFiscalPeriod::ByTokens { - quarterly: &[""], - annual: &["FY"], - }, - QmFinancialsFiscalPeriod::ByTokens { - quarterly: &["Q"], - annual: &[" "], - }, - ]; - - for pcfg in bad_period_configs { - let err = pcfg.validate().unwrap_err(); - assert!( - matches!(err, BsonQmFinancialsError::InvalidFiscalPeriodConfig { .. }), - "expected InvalidFiscalPeriodConfig for {pcfg:?}, got {err:?}" - ); - assert!(!err.to_string().contains('\n')); - - let mut called = false; - assert!(matches!( - decode_qm_financials_doc(doc.as_ref(), &base, pcfg, |_| called = true), - Err(BsonQmFinancialsError::InvalidFiscalPeriodConfig { .. }) - )); - assert!(matches!( - decode_qm_financials_bytes(doc.as_bytes(), &base, pcfg, |_| called = true), - Err(BsonQmFinancialsError::InvalidFiscalPeriodConfig { .. }) - )); - assert!(matches!( - decode_qm_financials_buffer(doc.as_bytes(), &base, pcfg, |_| called = true), - Err(BsonQmFinancialsError::InvalidFiscalPeriodConfig { .. }) - )); - assert!(!called); - } -} - -#[test] -fn covers_each_skip_counter_and_inclusive_date_bounds() { - let fields = full_test_fields(); - let pcfg = token_period_cfg(); - - // Helper to decode a single doc and assert zero rows emitted. - let decode_skipped = |doc: &RawDocumentBuf| -> BsonQmFinancialsDecodeStats { - let mut count = 0usize; - let stats = decode_qm_financials_doc(doc.as_ref(), &fields, pcfg, |_| count += 1).unwrap(); - assert_eq!(count, 0); - assert_eq!(stats.rows_out, 0); - assert_conservation(&stats); - stats - }; - - // --- Key skips --- - let mut missing_key = RawDocumentBuf::new(); - missing_key.append(cstr!("periodEndDate"), "2024-06-30"); - missing_key.append(cstr!("reportPeriod"), "Q"); - missing_key.append(cstr!("currency"), "USD"); - assert_eq!(decode_skipped(&missing_key).skipped_missing_key, 1); - - let mut wrong_key = RawDocumentBuf::new(); - wrong_key.append(cstr!("qmSearchCode"), 12345_i32); - wrong_key.append(cstr!("periodEndDate"), "2024-06-30"); - wrong_key.append(cstr!("reportPeriod"), "Q"); - wrong_key.append(cstr!("currency"), "USD"); - assert_eq!(decode_skipped(&wrong_key).skipped_wrong_key_type, 1); - - let mut empty_key = RawDocumentBuf::new(); - empty_key.append(cstr!("qmSearchCode"), " \t "); - empty_key.append(cstr!("periodEndDate"), "2024-06-30"); - empty_key.append(cstr!("reportPeriod"), "Q"); - empty_key.append(cstr!("currency"), "USD"); - assert_eq!(decode_skipped(&empty_key).skipped_empty_key, 1); - - // --- periodEndDate skips --- - let mut missing_pe = RawDocumentBuf::new(); - missing_pe.append(cstr!("qmSearchCode"), "AAPL:US"); - missing_pe.append(cstr!("reportPeriod"), "Q"); - missing_pe.append(cstr!("currency"), "USD"); - assert_eq!(decode_skipped(&missing_pe).skipped_missing_period_end, 1); - - let mut wrong_pe = RawDocumentBuf::new(); - wrong_pe.append(cstr!("qmSearchCode"), "AAPL:US"); - wrong_pe.append(cstr!("periodEndDate"), 20240630_i32); - wrong_pe.append(cstr!("reportPeriod"), "Q"); - wrong_pe.append(cstr!("currency"), "USD"); - assert_eq!(decode_skipped(&wrong_pe).skipped_wrong_period_end_type, 1); - - let mut invalid_pe = RawDocumentBuf::new(); - invalid_pe.append(cstr!("qmSearchCode"), "AAPL:US"); - invalid_pe.append(cstr!("periodEndDate"), "2024-02-30"); - invalid_pe.append(cstr!("reportPeriod"), "Q"); - invalid_pe.append(cstr!("currency"), "USD"); - assert_eq!(decode_skipped(&invalid_pe).skipped_invalid_period_end, 1); - - let mut oor_pe_low = RawDocumentBuf::new(); - oor_pe_low.append(cstr!("qmSearchCode"), "AAPL:US"); - oor_pe_low.append(cstr!("periodEndDate"), "2007-12-31"); - oor_pe_low.append(cstr!("reportPeriod"), "Q"); - oor_pe_low.append(cstr!("currency"), "USD"); - assert_eq!( - decode_skipped(&oor_pe_low).skipped_period_end_out_of_range, - 1 - ); - - let mut oor_pe_high_dt = RawDocumentBuf::new(); - oor_pe_high_dt.append(cstr!("qmSearchCode"), "AAPL:US"); - oor_pe_high_dt.append( - cstr!("periodEndDate"), - BsonDateTime::from_millis(i64::from(MAX_SUPPORTED_DATE + 1) * MILLIS_PER_DAY), - ); - oor_pe_high_dt.append(cstr!("reportPeriod"), "Q"); - oor_pe_high_dt.append(cstr!("currency"), "USD"); - assert_eq!( - decode_skipped(&oor_pe_high_dt).skipped_period_end_out_of_range, - 1 - ); - - // --- reportPeriod skips --- - let mut missing_rp = RawDocumentBuf::new(); - missing_rp.append(cstr!("qmSearchCode"), "AAPL:US"); - missing_rp.append(cstr!("periodEndDate"), "2024-06-30"); - missing_rp.append(cstr!("currency"), "USD"); - assert_eq!(decode_skipped(&missing_rp).skipped_missing_report_period, 1); - - let mut wrong_rp = RawDocumentBuf::new(); - wrong_rp.append(cstr!("qmSearchCode"), "AAPL:US"); - wrong_rp.append(cstr!("periodEndDate"), "2024-06-30"); - wrong_rp.append(cstr!("reportPeriod"), 4_i32); - wrong_rp.append(cstr!("currency"), "USD"); - assert_eq!( - decode_skipped(&wrong_rp).skipped_wrong_report_period_type, - 1 - ); - - let mut unmapped_rp = RawDocumentBuf::new(); - unmapped_rp.append(cstr!("qmSearchCode"), "AAPL:US"); - unmapped_rp.append(cstr!("periodEndDate"), "2024-06-30"); - unmapped_rp.append(cstr!("reportPeriod"), "TTM"); - unmapped_rp.append(cstr!("currency"), "USD"); - assert_eq!( - decode_skipped(&unmapped_rp).skipped_unmapped_report_period, - 1 - ); - - // --- reportDate skips (present-but-invalid fails closed) --- - let mut wrong_rd = RawDocumentBuf::new(); - wrong_rd.append(cstr!("qmSearchCode"), "AAPL:US"); - wrong_rd.append(cstr!("periodEndDate"), "2024-06-30"); - wrong_rd.append(cstr!("reportPeriod"), "Q"); - wrong_rd.append(cstr!("reportDate"), true); - wrong_rd.append(cstr!("currency"), "USD"); - assert_eq!(decode_skipped(&wrong_rd).skipped_wrong_report_date_type, 1); - - let mut invalid_rd = RawDocumentBuf::new(); - invalid_rd.append(cstr!("qmSearchCode"), "AAPL:US"); - invalid_rd.append(cstr!("periodEndDate"), "2024-06-30"); - invalid_rd.append(cstr!("reportPeriod"), "Q"); - invalid_rd.append(cstr!("reportDate"), "08/02/2024"); - invalid_rd.append(cstr!("currency"), "USD"); - assert_eq!(decode_skipped(&invalid_rd).skipped_invalid_report_date, 1); - - let mut blank_rd = RawDocumentBuf::new(); - blank_rd.append(cstr!("qmSearchCode"), "AAPL:US"); - blank_rd.append(cstr!("periodEndDate"), "2024-06-30"); - blank_rd.append(cstr!("reportPeriod"), "Q"); - blank_rd.append(cstr!("reportDate"), " "); - blank_rd.append(cstr!("currency"), "USD"); - assert_eq!(decode_skipped(&blank_rd).skipped_invalid_report_date, 1); - - let mut oor_rd = RawDocumentBuf::new(); - oor_rd.append(cstr!("qmSearchCode"), "AAPL:US"); - oor_rd.append(cstr!("periodEndDate"), "2024-06-30"); - oor_rd.append(cstr!("reportPeriod"), "Q"); - oor_rd.append(cstr!("reportDate"), "2031-01-01"); - oor_rd.append(cstr!("currency"), "USD"); - assert_eq!(decode_skipped(&oor_rd).skipped_report_date_out_of_range, 1); - - // --- currency skips --- - let mut missing_ccy = RawDocumentBuf::new(); - missing_ccy.append(cstr!("qmSearchCode"), "AAPL:US"); - missing_ccy.append(cstr!("periodEndDate"), "2024-06-30"); - missing_ccy.append(cstr!("reportPeriod"), "Q"); - assert_eq!(decode_skipped(&missing_ccy).skipped_missing_currency, 1); - - let mut wrong_ccy = RawDocumentBuf::new(); - wrong_ccy.append(cstr!("qmSearchCode"), "AAPL:US"); - wrong_ccy.append(cstr!("periodEndDate"), "2024-06-30"); - wrong_ccy.append(cstr!("reportPeriod"), "Q"); - wrong_ccy.append(cstr!("currency"), 840_i32); - assert_eq!(decode_skipped(&wrong_ccy).skipped_wrong_currency_type, 1); - - let mut empty_ccy = RawDocumentBuf::new(); - empty_ccy.append(cstr!("qmSearchCode"), "AAPL:US"); - empty_ccy.append(cstr!("periodEndDate"), "2024-06-30"); - empty_ccy.append(cstr!("reportPeriod"), "Q"); - empty_ccy.append(cstr!("currency"), " "); - assert_eq!(decode_skipped(&empty_ccy).skipped_empty_currency, 1); - - // --- Inclusive date bounds + absent/Null reportDate --- - let (min_y, min_m, min_d) = epoch_days_to_ymd(MIN_SUPPORTED_DATE); - let (max_y, max_m, max_d) = epoch_days_to_ymd(MAX_SUPPORTED_DATE); - let min_str = format!("{min_y:04}-{min_m:02}-{min_d:02}"); - let max_str = format!("{max_y:04}-{max_m:02}-{max_d:02}"); - - let mut min_bound_absent_rd = RawDocumentBuf::new(); - min_bound_absent_rd.append(cstr!("qmSearchCode"), "AAPL:US"); - min_bound_absent_rd.append(cstr!("periodEndDate"), min_str.as_str()); - min_bound_absent_rd.append(cstr!("reportPeriod"), "Q"); - min_bound_absent_rd.append(cstr!("currency"), "USD"); - - let mut max_bound_null_rd = RawDocumentBuf::new(); - max_bound_null_rd.append(cstr!("qmSearchCode"), "AAPL:US"); - max_bound_null_rd.append(cstr!("periodEndDate"), max_str.as_str()); - max_bound_null_rd.append(cstr!("reportPeriod"), "FY"); - max_bound_null_rd.append(cstr!("reportDate"), RawBson::Null); - max_bound_null_rd.append(cstr!("currency"), "USD"); - - let minimal_fields = - QmFinancialsFieldNames::with_verified_defaults("currency", None, None, None, None, None, None); - let mut emitted = Vec::new(); - let mut buf = Vec::new(); - buf.extend_from_slice(min_bound_absent_rd.as_bytes()); - buf.extend_from_slice(max_bound_null_rd.as_bytes()); - let stats = decode_qm_financials_buffer(&buf, &minimal_fields, pcfg, |obs| { - emitted.push(obs); - }) - .unwrap(); - assert_conservation(&stats); - assert_eq!(stats.rows_out, 2); - assert_eq!(emitted[0].period_end, MIN_SUPPORTED_DATE); - assert_eq!(emitted[0].report_date, None); - assert_eq!(emitted[1].period_end, MAX_SUPPORTED_DATE); - assert_eq!(emitted[1].report_date, None); -} - -#[test] -fn fixed_fiscal_period_override_ignores_report_period_field() { - let fields = - QmFinancialsFieldNames::with_verified_defaults("currency", None, None, None, None, None, None); - - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), "MSFT:US"); - doc.append(cstr!("periodEndDate"), "2024-09-30"); - // Wrong-typed reportPeriod would fail in ByTokens mode, but Fixed mode ignores it. - doc.append(cstr!("reportPeriod"), 999_i32); - doc.append(cstr!("currency"), "USD"); - - let mut rows = Vec::new(); - let stats = decode_qm_financials_doc( - doc.as_ref(), - &fields, - QmFinancialsFiscalPeriod::Fixed(FiscalPeriod::Annual), - |obs| rows.push(obs), - ) - .unwrap(); - assert_conservation(&stats); - assert_eq!(stats.rows_out, 1); - assert_eq!(rows[0].fiscal_period, FiscalPeriod::Annual); -} - -#[test] -fn numeric_null_counters_and_unconfigured_paths() { - // Configure 5 of 6 paths; leave `shares_outstanding` explicitly unconfigured (`None`). - let fields = QmFinancialsFieldNames::with_verified_defaults( - "meta.currency", - Some("IncomeStatement.totalRevenue"), // missing sub-document - Some("BalanceSheet.netIncome"), // wrong type (boolean) - Some("CashFlow.ocf"), // unparsable string - Some("BalanceSheet.assets"), // non-finite double (NaN) - Some("BalanceSheet.equity"), // non-finite string ("inf") - None, // unconfigured -> no null counter - ); - - let mut meta = RawDocumentBuf::new(); - meta.append(cstr!("currency"), "CAD"); - - let mut balance = RawDocumentBuf::new(); - balance.append(cstr!("netIncome"), true); - balance.append(cstr!("assets"), f64::NAN); - balance.append(cstr!("equity"), "inf"); - - let mut cash = RawDocumentBuf::new(); - cash.append(cstr!("ocf"), "N/A"); - - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), "RY:CA"); - doc.append(cstr!("periodEndDate"), "2024-10-31"); - doc.append(cstr!("reportPeriod"), "FY"); - doc.append(cstr!("meta"), meta); - // IncomeStatement intentionally omitted -> nulled_missing_path - doc.append(cstr!("BalanceSheet"), balance); - doc.append(cstr!("CashFlow"), cash); - - let mut rows = Vec::new(); - let stats = decode_qm_financials_doc(doc.as_ref(), &fields, token_period_cfg(), |obs| { - rows.push(obs); - }) - .unwrap(); - assert_conservation(&stats); - assert_eq!(stats.rows_out, 1); - assert_eq!(stats.nulled_missing_path, 1); - assert_eq!(stats.nulled_wrong_type, 1); - assert_eq!(stats.nulled_unparsable_string, 1); - assert_eq!(stats.nulled_non_finite, 2); - assert_eq!(rows[0].currency, "CAD"); - assert_eq!(rows[0].fields, FundamentalsFields::default()); - - // BSON Null on a configured numeric leaf emits None cleanly without incrementing null counters. - let mut income_null = RawDocumentBuf::new(); - income_null.append(cstr!("totalRevenue"), RawBson::Null); - let mut doc_null = RawDocumentBuf::new(); - doc_null.append(cstr!("qmSearchCode"), "RY:CA"); - doc_null.append(cstr!("periodEndDate"), "2024-10-31"); - doc_null.append(cstr!("reportPeriod"), "FY"); - doc_null.append(cstr!("currency"), "CAD"); - doc_null.append(cstr!("IncomeStatement"), income_null); - - let single_field = QmFinancialsFieldNames::with_verified_defaults( - "currency", - Some("IncomeStatement.totalRevenue"), - None, - None, - None, - None, - None, - ); - let mut rows_null = Vec::new(); - let stats_null = - decode_qm_financials_doc(doc_null.as_ref(), &single_field, token_period_cfg(), |obs| { - rows_null.push(obs); - }) - .unwrap(); - assert_eq!(stats_null.rows_out, 1); - assert_eq!(stats_null.nulled_missing_path, 0); - assert_eq!(stats_null.nulled_wrong_type, 0); - assert_eq!(stats_null.nulled_unparsable_string, 0); - assert_eq!(stats_null.nulled_non_finite, 0); - assert_eq!(rows_null[0].fields.revenue, None); -} - -#[test] -fn mixed_buffer_reconciles_stats_and_framing_errors_fail_closed_with_offset() { - let fields = full_test_fields(); - let pcfg = token_period_cfg(); - - let good = make_valid_doc("AAPL:US"); - - let mut bad_key = RawDocumentBuf::new(); - bad_key.append(cstr!("periodEndDate"), "2024-06-30"); - bad_key.append(cstr!("reportPeriod"), "Q"); - bad_key.append(cstr!("currency"), "USD"); - - let mut bad_period = RawDocumentBuf::new(); - bad_period.append(cstr!("qmSearchCode"), "AAPL:US"); - bad_period.append(cstr!("periodEndDate"), "2024-06-30"); - bad_period.append(cstr!("reportPeriod"), "UNKNOWN"); - bad_period.append(cstr!("currency"), "USD"); - - let mut bad_rd = RawDocumentBuf::new(); - bad_rd.append(cstr!("qmSearchCode"), "AAPL:US"); - bad_rd.append(cstr!("periodEndDate"), "2024-06-30"); - bad_rd.append(cstr!("reportPeriod"), "Q"); - bad_rd.append(cstr!("reportDate"), "not-a-date"); - bad_rd.append(cstr!("currency"), "USD"); - - let mut mixed = Vec::new(); - mixed.extend_from_slice(good.as_bytes()); - mixed.extend_from_slice(bad_key.as_bytes()); - mixed.extend_from_slice(bad_period.as_bytes()); - mixed.extend_from_slice(bad_rd.as_bytes()); - - let mut emitted = Vec::new(); - let stats = decode_qm_financials_buffer(&mixed, &fields, pcfg, |obs| emitted.push(obs)).unwrap(); - assert_eq!(stats.docs_in, 4); - assert_eq!(stats.rows_out, 1); - assert_eq!(stats.skipped_missing_key, 1); - assert_eq!(stats.skipped_unmapped_report_period, 1); - assert_eq!(stats.skipped_invalid_report_date, 1); - assert_eq!(stats.skipped_total(), 3); - assert_conservation(&stats); - assert_eq!(emitted.len(), 1); - - // 1. Truncated length prefix after a valid document. - let prefix_len = good.as_bytes().len() as u64; - let mut truncated_hdr = good.as_bytes().to_vec(); - truncated_hdr.extend_from_slice(&[0x10, 0x00]); - let mut seen = 0usize; - let err = decode_qm_financials_buffer(&truncated_hdr, &fields, pcfg, |_| seen += 1).unwrap_err(); - assert_eq!(seen, 1); - assert_eq!( - err, - BsonQmFinancialsError::TruncatedDocument { - offset: prefix_len, - remaining: 2, - declared_len: None, - } - ); - - // 2. Truncated document body after a valid document. - let mut truncated_body = good.as_bytes().to_vec(); - truncated_body.extend_from_slice(&good.as_bytes()[..10]); - let err = decode_qm_financials_buffer(&truncated_body, &fields, pcfg, |_| {}).unwrap_err(); - assert!(matches!( - err, - BsonQmFinancialsError::TruncatedDocument { - offset, - remaining: 10, - declared_len: Some(_), - } if offset == prefix_len - )); - - // 3. Invalid declared document length (< 5). - let mut bad_len = good.as_bytes().to_vec(); - bad_len.extend_from_slice(&3_i32.to_le_bytes()); - bad_len.push(0x00); - let err = decode_qm_financials_buffer(&bad_len, &fields, pcfg, |_| {}).unwrap_err(); - assert_eq!( - err, - BsonQmFinancialsError::CorruptDocumentLength { - offset: prefix_len, - declared_len: 3, - } - ); - - // 4. Malformed nested BSON (invalid UTF-8 inside an unused nested subdocument) in a document - // that ALSO lacks a key: must return CorruptBson rather than silently skipping! - let mut nested = RawDocumentBuf::new(); - nested.append(cstr!("note"), "AAAA"); - let mut nested_bytes = nested.into_bytes(); - // Corrupt the 4-byte ASCII payload "AAAA" into invalid UTF-8 bytes. - let pos = nested_bytes - .windows(4) - .position(|w| w == b"AAAA") - .expect("marker present"); - nested_bytes[pos] = 0xFF; - nested_bytes[pos + 1] = 0xFE; - - // Build outer doc containing no key (would skip) + the corrupt nested subdoc. - let mut outer = Vec::new(); - let placeholder_len = 0_i32; - outer.extend_from_slice(&placeholder_len.to_le_bytes()); - outer.push(0x03); // Embedded Document element type - outer.extend_from_slice(b"extra\0"); - outer.extend_from_slice(&nested_bytes); - outer.push(0x00); // Document terminator - let total_len = i32::try_from(outer.len()).unwrap(); - outer[..4].copy_from_slice(&total_len.to_le_bytes()); - - let mut with_prefix = good.as_bytes().to_vec(); - with_prefix.extend_from_slice(&outer); - let err = decode_qm_financials_buffer(&with_prefix, &fields, pcfg, |_| {}).unwrap_err(); - assert!( - matches!(err, BsonQmFinancialsError::CorruptBson { offset, .. } if offset == prefix_len), - "expected CorruptBson at offset {prefix_len}, got {err:?}" - ); - - // 5. Corrupt array index inside a nested array fails closed. - let mut bad_arr = RawArrayBuf::new(); - bad_arr.push(1_i32); - let mut arr_bytes = bad_arr.as_bytes().to_vec(); - // Replace key "0" with "1" so array index validation rejects it. - let zero_pos = arr_bytes - .windows(2) - .position(|w| w == b"0\0") - .expect("index 0 key present"); - arr_bytes[zero_pos] = b'1'; - let mut outer_arr = Vec::new(); - outer_arr.extend_from_slice(&0_i32.to_le_bytes()); - outer_arr.push(0x04); // Array element type - outer_arr.extend_from_slice(b"arr\0"); - outer_arr.extend_from_slice(&arr_bytes); - outer_arr.push(0x00); - let arr_total_len = i32::try_from(outer_arr.len()).unwrap(); - outer_arr[..4].copy_from_slice(&arr_total_len.to_le_bytes()); - - let err = decode_qm_financials_bytes(&outer_arr, &fields, pcfg, |_| {}).unwrap_err(); - assert!(matches!(err, BsonQmFinancialsError::CorruptBson { offset: 0, .. })); -} - -#[test] -fn decoded_observation_feeds_build_fundamentals_rows_with_filing_timestamp() { - let fields = full_test_fields(); - let doc = make_valid_doc("AAPL:US"); - - let mut observations: Vec> = Vec::new(); - let decode_stats = - decode_qm_financials_bytes(doc.as_bytes(), &fields, token_period_cfg(), |obs| { - observations.push(obs); - }) - .unwrap(); - assert_conservation(&decode_stats); - assert_eq!(observations.len(), 1); - - let timefiled = "2024-08-02T16:30:15 EDT"; - // 2024-08-02T16:30:15 EDT == 2024-08-02T20:30:15Z (1,722,630,615 seconds since Unix epoch). - let expected_micros: i64 = 1_722_630_615_000_000; - - let filings = vec![QmFiling { - key: "AAPL:US", - timefiled: timefiled.to_string(), - form_type: "10-Q".to_string(), - filing_id: Some("0000320193-24-000081".to_string()), - url: None, - }]; - - let mut venues = BTreeMap::new(); - venues.insert("AAPL:US", StatutoryLagVenue::UsTsx); - - let build = build_fundamentals_rows(observations, filings, &venues); - assert_eq!(build.stats.observations_in, 1); - assert_eq!(build.stats.rows_out, 1); - assert_eq!(build.stats.rows_linked_to_filing, 1); - assert_eq!(build.stats.rows_statutory_lag_estimate, 0); - assert_eq!(build.rows.len(), 1); - - let row = &build.rows[0]; - assert_eq!(row.key, "AAPL:US"); - assert_eq!(row.period_end, ymd_to_epoch_days(2024, 6, 30).unwrap()); - assert_eq!(row.fiscal_period, FiscalPeriod::Quarterly); - assert_eq!(row.currency, "USD"); - assert_eq!(row.known_at_utc_micros, expected_micros); - assert_eq!(row.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); - assert_eq!(row.fields.revenue, Some(1_250_000.5)); - assert_eq!(row.fields.net_income, Some(125_000.0)); - assert_eq!(row.fields.operating_cash_flow, Some(300_000.75)); - assert_eq!(row.fields.total_assets, Some(9_000_000_000.0)); - assert_eq!(row.fields.total_equity, Some(4_500_000.25)); - assert_eq!(row.fields.shares_outstanding, Some(100_000_000.0)); -} - -#[test] -fn nested_vintages_preserve_the_earlier_snapshot_until_the_amended_filing() { - let fields = QmFinancialsFieldNames { - key: "metadata.identity.code", - period_end: "metadata.period.end", - report_period: "metadata.period.token", - report_date: "metadata.period.vintage", - ..QmFinancialsFieldNames::with_verified_defaults( - "metadata.identity.currency", - Some("IncomeStatement.values.revenue"), - None, - None, - None, - None, - None, - ) - }; - let statement = |vintage: RawBson, revenue: i32| { - let mut identity = RawDocumentBuf::new(); - identity.append(cstr!("code"), "FIXTURE:CA"); - identity.append(cstr!("currency"), "CAD"); - let mut period = RawDocumentBuf::new(); - period.append(cstr!("end"), "2024-06-30"); - period.append(cstr!("token"), "Q2"); - period.append(cstr!("vintage"), vintage); - let mut metadata = RawDocumentBuf::new(); - metadata.append(cstr!("identity"), identity); - metadata.append(cstr!("period"), period); - let mut values = RawDocumentBuf::new(); - values.append(cstr!("revenue"), revenue); - let mut income = RawDocumentBuf::new(); - income.append(cstr!("values"), values); - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("metadata"), metadata); - doc.append(cstr!("IncomeStatement"), income); - doc - }; - let original = statement(RawBson::String("2024-08-02".to_owned()), 2_100_000); - let amendment = statement(RawBson::String("2024-09-06".to_owned()), 900_000); - let invalid = statement(RawBson::DateTime(BsonDateTime::from_millis(i64::MAX)), 1); - let filing = |timefiled: &str, form_type: &str, id: &str| QmFiling { - key: "FIXTURE:CA", - timefiled: timefiled.to_owned(), - form_type: form_type.to_owned(), - filing_id: Some(id.to_owned()), - url: None, - }; - let original_filing = filing("2024-08-02T16:30:15 EDT", "10-Q", "fixture-original"); - let amended_filing = filing("2024-09-06T16:30:15 EDT", "10-Q/A", "fixture-amended"); - let original_micros = 1_722_630_615_000_000; - let amended_micros = 1_725_654_615_000_000; - let venues = BTreeMap::from([("FIXTURE:CA", StatutoryLagVenue::UsTsx)]); - let decode = |bytes| { - let mut observations = Vec::new(); - let stats = decode_qm_financials_buffer(bytes, &fields, token_period_cfg(), |obs| { - observations.push(obs); - }) - .unwrap(); - assert_conservation(&stats); - (observations, stats) - }; - - let (baseline, _) = decode(original.as_bytes()); - let baseline = build_fundamentals_rows(baseline, [original_filing.clone()], &venues); - let baseline = build_fundamentals_snapshots(&baseline.rows, 1).unwrap(); - let input = [ - amendment.as_bytes(), - invalid.as_bytes(), - original.as_bytes(), - ] - .concat(); - let (observations, stats) = decode(&input); - let full = build_fundamentals_rows(observations, [amended_filing, original_filing], &venues); - let snapshots = build_fundamentals_snapshots(&full.rows, 1).unwrap(); - - assert_eq!( - stats, - BsonQmFinancialsDecodeStats { - docs_in: 3, - rows_out: 2, - skipped_report_date_out_of_range: 1, - ..Default::default() - } - ); - assert_eq!(full.stats.rows_linked_to_filing, 2); - assert_eq!(full.stats.rows_statutory_lag_estimate, 0); - assert_eq!(snapshots.len(), 2); - assert_eq!(as_of(&snapshots, "FIXTURE:CA", original_micros - 1), None); - let prior = as_of(&snapshots, "FIXTURE:CA", amended_micros - 1).unwrap(); - assert_eq!(prior, &baseline[0]); - assert_eq!(prior.effective_known_at_utc_micros, original_micros); - assert_eq!(prior.periods[0].fields.revenue, Some(2_100_000.0)); - let revised = as_of(&snapshots, "FIXTURE:CA", amended_micros).unwrap(); - assert_eq!(revised.effective_known_at_utc_micros, amended_micros); - assert_eq!(revised.periods[0].fields.revenue, Some(900_000.0)); -} - -#[test] -fn distinguishes_null_and_scalar_intermediates_and_matches_period_tokens_verbatim() { - let fields = QmFinancialsFieldNames { - report_date: "disclosure.vintage", - ..QmFinancialsFieldNames::with_verified_defaults( - "currency", - Some("IncomeStatement.revenue"), - None, - None, - None, - None, - None, - ) - }; - let fixture = |token: &str, disclosure: RawBson, income: RawBson| { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), " FIXTURE:CA "); - doc.append(cstr!("periodEndDate"), "2024-06-30"); - doc.append(cstr!("reportPeriod"), token); - doc.append(cstr!("currency"), "CAD"); - doc.append(cstr!("disclosure"), disclosure); - doc.append(cstr!("IncomeStatement"), income); - doc - }; - let docs = [ - fixture("Q2", RawBson::Null, RawBson::Null), - fixture("Q2", RawBson::Null, RawBson::Int32(1)), - fixture("Q2", RawBson::Int32(1), RawBson::Null), - fixture(" Q2 ", RawBson::Int32(1), RawBson::Int32(1)), - fixture("q2", RawBson::Null, RawBson::Null), - ]; - let input: Vec = docs - .iter() - .flat_map(|doc| doc.as_bytes().iter().copied()) - .collect(); - let mut rows = Vec::new(); - - let stats = decode_qm_financials_buffer(&input, &fields, token_period_cfg(), |row| { - rows.push(row); - }) - .unwrap(); - - assert_conservation(&stats); - assert_eq!( - stats, - BsonQmFinancialsDecodeStats { - docs_in: 5, - rows_out: 2, - skipped_unmapped_report_period: 2, - skipped_wrong_report_date_type: 1, - nulled_missing_path: 1, - nulled_wrong_type: 1, - ..Default::default() - } - ); - assert_eq!(rows.len(), 2); - for row in rows { - assert_eq!(row.key, " FIXTURE:CA "); - assert_eq!(row.report_date, None); - assert_eq!(row.fields.revenue, None); - } -} - -#[test] -fn validates_unused_nested_documents_at_the_depth_boundary() { - let nest = |levels| { - let mut inner = RawDocumentBuf::new(); - for _ in 1..levels { - let mut parent = RawDocumentBuf::new(); - parent.append(cstr!("nested"), inner); - inner = parent; - } - inner - }; - let mut good = make_valid_doc("AAPL:US"); - good.append(cstr!("extra"), nest(128)); - let mut bad = make_valid_doc("SHOP:CA"); - bad.append(cstr!("extra"), nest(129)); - let input = [good.as_bytes(), bad.as_bytes(), good.as_bytes()].concat(); - let mut seen = Vec::new(); - - let error = - decode_qm_financials_buffer(&input, &full_test_fields(), token_period_cfg(), |row| { - seen.push(row.key); - }) - .unwrap_err(); - - assert_eq!(seen, ["AAPL:US"]); - assert!(matches!( - error, - BsonQmFinancialsError::CorruptBson { offset, .. } - if offset == good.as_bytes().len() as u64 - )); -} diff --git a/tools/curate-etl/src/bson_qm_intraday.rs b/tools/curate-etl/src/bson_qm_intraday.rs deleted file mode 100644 index 491d4138..00000000 --- a/tools/curate-etl/src/bson_qm_intraday.rs +++ /dev/null @@ -1,641 +0,0 @@ -//! Zero-copy raw BSON decoder for MongoDB `qmIntraday` documents (`M2.3i`). -//! -//! Decodes `&bson::RawDocument` slices in a single forward pass over `iter_elements()` into -//! borrowed [`RawQmIntradayBar`] views without allocating a `String` or `bson::Document` per row. -//! Callers can convert borrowed views into [`crate::bars_1m::EodIntradayBar`] via a -//! caller-supplied key mapper without per-row `String` allocations, keeping in mind that -//! `qmIntraday` raw fields are already un-adjusted (see [`RawQmIntradayBar::into_eod_intraday_bar`]). -//! -//! # Empirical Field Contract & Cited Sources -//! -//! Field names and semantics are grounded in the repository's ingestion writer and empirical data -//! contract: -//! - `apps/stock/data-ingestion/src/handlers/qm/actions/intraday-crawl.action.ts:119-131,165-173` -//! (requests 1-minute bars via `interval: '1'`, spreads the provider bar payload, adds -//! `qmSearchCode`, `symbol`, `exchange`, and -//! `timestamp: new Date(bar.startdatetime || bar.date || bar.datetime)`, and upserts into -//! `qmIntraday` keyed by `['qmSearchCode', 'timestamp']`) -//! - `design/DATA-CONTRACTS.md:16` (§1 row `qmIntraday`, ~173.3M docs): stores **both** raw -//! (`open..close`, `sharevolume`) and split-adjusted (`adjustedopen..adjustedclose`, `avolume`) -//! fields. This decoder reads the raw fields only; all adjusted fields are validated as borrowed -//! `RawBsonRef` payloads and otherwise ignored. -//! -//! `ts` is decoded as bar-start UTC microseconds (`DateTime` milliseconds × `1_000`). Downstream -//! research/curation owns availability (`known_at`) decisions. -//! -//! # Accepted BSON Representations & Decoder Conventions -//! -//! Following [`crate::bson_eod_intraday`] and [`crate::bson_qm_prices`]: -//! - `qmSearchCode`: BSON UTF-8 `String`, borrowed verbatim (never trimmed). Empty or -//! whitespace-only strings are rejected as [`BsonQmIntradayError::EmptyField`]; non-string -//! values (including BSON `Null`) are rejected as [`BsonQmIntradayError::WrongType`]. -//! - `timestamp`: BSON `DateTime` (UTC milliseconds since Unix epoch), converted to UTC -//! microseconds via checked multiplication by `1_000`. Non-`DateTime` types (including `Null`, -//! integers, doubles, strings, and BSON `Timestamp`) are rejected as -//! [`BsonQmIntradayError::WrongType`]; negative millisecond values or values overflowing `i64` -//! microseconds are rejected as [`BsonQmIntradayError::InvalidTimestamp`]. -//! - `open`, `high`, `low`, `close`: BSON `Double`, `Int32`, or `Int64`; must be finite and -//! strictly positive (`> 0.0`). Non-numeric types (including `Null`) are rejected as -//! [`BsonQmIntradayError::WrongType`]; `NaN`, `±inf`, `0.0`, `-0.0`, and `< 0.0` are rejected -//! as [`BsonQmIntradayError::InvalidNumber`]. -//! - `sharevolume`: BSON `Double`, `Int32`, or `Int64`; must be finite and `>= 0.0` (`-0.0` is -//! normalized to `+0.0`). Non-numeric types (including `Null`) are rejected as -//! [`BsonQmIntradayError::WrongType`]; `NaN`, `±inf`, and `< 0.0` are rejected as -//! [`BsonQmIntradayError::InvalidNumber`]. -//! - All other top-level fields (`_id`, `symbol`, `exchange`, `adjustedopen`, `adjustedhigh`, -//! `adjustedlow`, `adjustedclose`, `avolume`, `startdatetime`, nested objects/arrays, etc.) are -//! validated as borrowed `RawBsonRef` views (zero allocation) and otherwise ignored, so malformed -//! bytes in skipped fields still surface as [`BsonQmIntradayError::CorruptBson`]. -//! - Duplicate fields and error precedence: later valid duplicates replace earlier valid values, -//! the first semantic error is retained (a later valid duplicate cannot clear an earlier semantic -//! error), and malformed BSON bytes take precedence immediately as `CorruptBson`. After the scan, -//! the first semantic error is returned, or else the first missing required field in -//! `qmSearchCode`, `timestamp`, `open`, `high`, `low`, `close`, `sharevolume` order. - -use std::error::Error; -use std::fmt; - -use bson::raw::{cstr, RawBsonRef, RawDocument, RawElement}; -use bson::spec::ElementType; - -use crate::bars_1m::EodIntradayBar; -use crate::bson_eod_prices::{iter_raw_bson_docs, parse_single_raw_doc, BsonEodPriceError}; - -/// MongoDB field name for the QuoteMedia security key (`intraday-crawl.action.ts:167,173`). -pub const FIELD_QM_SEARCH_CODE: &str = "qmSearchCode"; -/// MongoDB field name for the bar-start BSON `DateTime` (`intraday-crawl.action.ts:170,173`). -pub const FIELD_TIMESTAMP: &str = "timestamp"; -/// MongoDB field name for raw bar open price (`DATA-CONTRACTS.md:16`). -pub const FIELD_OPEN: &str = "open"; -/// MongoDB field name for raw bar high price (`DATA-CONTRACTS.md:16`). -pub const FIELD_HIGH: &str = "high"; -/// MongoDB field name for raw bar low price (`DATA-CONTRACTS.md:16`). -pub const FIELD_LOW: &str = "low"; -/// MongoDB field name for raw bar close price (`DATA-CONTRACTS.md:16`). -pub const FIELD_CLOSE: &str = "close"; -/// MongoDB field name for raw bar share volume (`DATA-CONTRACTS.md:16`). -pub const FIELD_SHARE_VOLUME: &str = "sharevolume"; - -const MICROS_PER_MILLI: i64 = 1_000; -/// Largest UTC millisecond timestamp that fits in signed `i64` microseconds (`9_223_372_036_854_775`). -#[cfg(test)] -pub(crate) const MAX_TIMESTAMP_MILLIS: i64 = i64::MAX / MICROS_PER_MILLI; - -/// Borrowed zero-copy view of a single decoded `qmIntraday` BSON document. -/// -/// Borrows `qm_search_code` directly from the underlying `&RawDocument` byte slice. -/// `open`, `high`, `low`, `close`, and `volume` are the provider's already-raw values -/// (`open..close`, `sharevolume`); adjusted fields are ignored. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct RawQmIntradayBar<'a> { - pub qm_search_code: &'a str, - /// Bar start timestamp in UTC microseconds since the Unix epoch. - pub ts: i64, - pub open: f64, - pub high: f64, - pub low: f64, - pub close: f64, - pub volume: f64, -} - -impl<'a> RawQmIntradayBar<'a> { - /// Converts this borrowed view into an [`EodIntradayBar`] using a caller-supplied key - /// mapper. - /// - /// `map_key` receives `(qm_search_code, ts)` (provider code and UTC bar-start microseconds) - /// and this method only maps the key and copies the raw OHLCV fields verbatim. - /// - /// **Important:** [`crate::bars_1m::build_bars_1m`] applies split un-adjustment to - /// [`EodIntradayBar`] inputs (which is required for retroactively split-adjusted - /// `eodIntraday1M` bars). Passing already-raw `qmIntraday` bars through a split-unadjusting - /// path with non-empty splits would distort raw prices and volumes; downstream `qmIntraday` - /// curation must ingest raw values without split un-adjustment. - #[inline] - pub fn into_eod_intraday_bar(self, map_key: F) -> EodIntradayBar - where - F: FnOnce(&'a str, i64) -> K, - { - EodIntradayBar { - key: map_key(self.qm_search_code, self.ts), - ts: self.ts, - open: self.open, - high: self.high, - low: self.low, - close: self.close, - volume: self.volume, - } - } - - /// Fallible conversion into [`EodIntradayBar`] using a caller-supplied key resolver. - /// - /// Maps `(qm_search_code, ts)` and copies the raw OHLCV fields verbatim without applying any - /// split adjustment. See [`Self::into_eod_intraday_bar`] for the split un-adjustment caveat. - #[inline] - pub fn try_into_eod_intraday_bar(self, map_key: F) -> Option> - where - F: FnOnce(&'a str, i64) -> Option, - { - let key = map_key(self.qm_search_code, self.ts)?; - Some(EodIntradayBar { - key, - ts: self.ts, - open: self.open, - high: self.high, - low: self.low, - close: self.close, - volume: self.volume, - }) - } -} - -/// Typed errors returned while decoding raw `qmIntraday` BSON documents or length-prefixed -/// buffers. -/// -/// Every field-level error names the offending BSON field in both its structure and `Display` -/// output; malformed and truncated BSON framing errors report `CorruptBson` with byte offset and -/// framing detail; no input path panics. -#[derive(Debug, Clone, PartialEq)] -pub enum BsonQmIntradayError { - /// A required field was absent from the document. - MissingField { field: &'static str }, - /// A required string field was empty or contained only whitespace. - EmptyField { field: &'static str }, - /// A required field had an unexpected BSON element type (including `Null`). - WrongType { - field: &'static str, - actual: ElementType, - }, - /// `timestamp` BSON `DateTime` was negative or overflowed `i64` microseconds. - InvalidTimestamp { field: &'static str }, - /// An OHLC field was non-finite or `<= 0.0`, or `sharevolume` was non-finite or `< 0.0`. - InvalidNumber { field: &'static str, value: f64 }, - /// Underlying BSON framing, truncation, document length, or element bytes were malformed. - CorruptBson { offset: usize, detail: String }, -} - -impl fmt::Display for BsonQmIntradayError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::MissingField { field } => { - write!(f, "qmIntraday BSON missing required field '{field}'") - } - Self::EmptyField { field } => { - write!( - f, - "qmIntraday BSON field '{field}' must not be empty or blank" - ) - } - Self::WrongType { field, actual } => { - write!( - f, - "qmIntraday BSON field '{field}' has unexpected BSON type {actual:?}" - ) - } - Self::InvalidTimestamp { field } => { - write!( - f, - "qmIntraday BSON field '{field}' is not a valid non-negative DateTime within i64 microsecond range" - ) - } - Self::InvalidNumber { field, value } => { - if *field == FIELD_SHARE_VOLUME { - write!( - f, - "qmIntraday BSON field '{field}' has invalid numeric value {value}: must be finite and >= 0" - ) - } else { - write!( - f, - "qmIntraday BSON field '{field}' has invalid numeric value {value}: must be finite and > 0" - ) - } - } - Self::CorruptBson { offset, detail } => { - write!(f, "corrupt BSON bytes at byte offset {offset}: {detail}") - } - } - } -} - -impl Error for BsonQmIntradayError {} - -#[inline] -fn map_framing_error(err: BsonEodPriceError) -> BsonQmIntradayError { - match err { - BsonEodPriceError::TruncatedDocument { offset, .. } - | BsonEodPriceError::CorruptDocumentLength { offset, .. } => { - BsonQmIntradayError::CorruptBson { - offset, - detail: err.to_string(), - } - } - BsonEodPriceError::CorruptBson { offset, detail } => { - BsonQmIntradayError::CorruptBson { offset, detail } - } - BsonEodPriceError::MissingField { field } => BsonQmIntradayError::MissingField { field }, - BsonEodPriceError::EmptyField { field } => BsonQmIntradayError::EmptyField { field }, - BsonEodPriceError::WrongType { field, actual } => { - BsonQmIntradayError::WrongType { field, actual } - } - BsonEodPriceError::MalformedDate { field } => { - BsonQmIntradayError::InvalidTimestamp { field } - } - BsonEodPriceError::InvalidNumber { field, value } => { - BsonQmIntradayError::InvalidNumber { field, value } - } - } -} - -/// Per-batch decode and rejection accounting for [`decode_qm_intraday_buffer`]. -/// -/// Conservation invariant: `rows_decoded + rejected_total() == docs_seen`. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct BsonQmIntradayDecodeStats { - pub docs_seen: usize, - pub rows_decoded: usize, - pub rejected_missing_field: usize, - pub rejected_empty_field: usize, - pub rejected_wrong_type: usize, - pub rejected_invalid_timestamp: usize, - pub rejected_invalid_number: usize, - pub rejected_corrupt_document: usize, -} - -impl BsonQmIntradayDecodeStats { - /// Total number of rejected documents across all error categories. - #[inline] - pub fn rejected_total(&self) -> usize { - self.rejected_missing_field - + self.rejected_empty_field - + self.rejected_wrong_type - + self.rejected_invalid_timestamp - + self.rejected_invalid_number - + self.rejected_corrupt_document - } - - /// Increments the rejection counter corresponding to `err`. - #[inline] - pub fn record_error(&mut self, err: &BsonQmIntradayError) { - match err { - BsonQmIntradayError::MissingField { .. } => self.rejected_missing_field += 1, - BsonQmIntradayError::EmptyField { .. } => self.rejected_empty_field += 1, - BsonQmIntradayError::WrongType { .. } => self.rejected_wrong_type += 1, - BsonQmIntradayError::InvalidTimestamp { .. } => self.rejected_invalid_timestamp += 1, - BsonQmIntradayError::InvalidNumber { .. } => self.rejected_invalid_number += 1, - BsonQmIntradayError::CorruptBson { .. } => self.rejected_corrupt_document += 1, - } - } - - /// Accumulates counters from another batch into `self`. - #[inline] - pub fn merge(&mut self, other: &Self) { - self.docs_seen += other.docs_seen; - self.rows_decoded += other.rows_decoded; - self.rejected_missing_field += other.rejected_missing_field; - self.rejected_empty_field += other.rejected_empty_field; - self.rejected_wrong_type += other.rejected_wrong_type; - self.rejected_invalid_timestamp += other.rejected_invalid_timestamp; - self.rejected_invalid_number += other.rejected_invalid_number; - self.rejected_corrupt_document += other.rejected_corrupt_document; - } -} - -impl std::ops::AddAssign for BsonQmIntradayDecodeStats { - #[inline] - fn add_assign(&mut self, rhs: Self) { - self.merge(&rhs); - } -} - -#[inline] -fn decode_element_value<'a>( - field: &'static str, - elem: RawElement<'a>, - offset: usize, -) -> Result, BsonQmIntradayError> { - elem.value().map_err(|err| BsonQmIntradayError::CorruptBson { - offset, - detail: format!("field '{field}': {err}"), - }) -} - -#[inline] -fn decode_timestamp_datetime_to_micros(val: RawBsonRef<'_>) -> Result { - match val { - RawBsonRef::DateTime(dt) => { - let millis = dt.timestamp_millis(); - if millis < 0 { - return Err(BsonQmIntradayError::InvalidTimestamp { - field: FIELD_TIMESTAMP, - }); - } - millis - .checked_mul(MICROS_PER_MILLI) - .ok_or(BsonQmIntradayError::InvalidTimestamp { - field: FIELD_TIMESTAMP, - }) - } - other => Err(BsonQmIntradayError::WrongType { - field: FIELD_TIMESTAMP, - actual: other.element_type(), - }), - } -} - -#[inline] -fn decode_positive_number( - field: &'static str, - val: RawBsonRef<'_>, -) -> Result { - match val { - RawBsonRef::Double(v) => { - if !v.is_finite() || v <= 0.0 { - return Err(BsonQmIntradayError::InvalidNumber { field, value: v }); - } - Ok(v) - } - RawBsonRef::Int32(v) => { - if v <= 0 { - return Err(BsonQmIntradayError::InvalidNumber { - field, - value: f64::from(v), - }); - } - Ok(f64::from(v)) - } - RawBsonRef::Int64(v) => { - if v <= 0 { - return Err(BsonQmIntradayError::InvalidNumber { - field, - value: v as f64, - }); - } - Ok(v as f64) - } - other => Err(BsonQmIntradayError::WrongType { - field, - actual: other.element_type(), - }), - } -} - -#[inline] -fn decode_non_negative_number( - field: &'static str, - val: RawBsonRef<'_>, -) -> Result { - match val { - RawBsonRef::Double(v) => { - if !v.is_finite() || v < 0.0 { - return Err(BsonQmIntradayError::InvalidNumber { field, value: v }); - } - if v == 0.0 { - Ok(0.0) - } else { - Ok(v) - } - } - RawBsonRef::Int32(v) => { - if v < 0 { - return Err(BsonQmIntradayError::InvalidNumber { - field, - value: f64::from(v), - }); - } - Ok(f64::from(v)) - } - RawBsonRef::Int64(v) => { - if v < 0 { - return Err(BsonQmIntradayError::InvalidNumber { - field, - value: v as f64, - }); - } - Ok(v as f64) - } - other => Err(BsonQmIntradayError::WrongType { - field, - actual: other.element_type(), - }), - } -} - -fn decode_qm_intraday_doc_at<'a>( - doc: &'a RawDocument, - offset: usize, -) -> Result, BsonQmIntradayError> { - let mut qm_search_code: Option<&'a str> = None; - let mut ts: Option = None; - let mut open: Option = None; - let mut high: Option = None; - let mut low: Option = None; - let mut close: Option = None; - let mut volume: Option = None; - let mut first_semantic_err: Option = None; - - for elem_res in doc.iter_elements() { - let elem = elem_res.map_err(|err| BsonQmIntradayError::CorruptBson { - offset, - detail: err.to_string(), - })?; - let key = elem.key(); - - if key == cstr!("qmSearchCode") { - match decode_element_value(FIELD_QM_SEARCH_CODE, elem, offset)? { - RawBsonRef::String(s) => { - if s.trim().is_empty() { - if first_semantic_err.is_none() { - first_semantic_err = Some(BsonQmIntradayError::EmptyField { - field: FIELD_QM_SEARCH_CODE, - }); - } - } else { - qm_search_code = Some(s); - } - } - other => { - if first_semantic_err.is_none() { - first_semantic_err = Some(BsonQmIntradayError::WrongType { - field: FIELD_QM_SEARCH_CODE, - actual: other.element_type(), - }); - } - } - } - } else if key == cstr!("timestamp") { - let val = decode_element_value(FIELD_TIMESTAMP, elem, offset)?; - match decode_timestamp_datetime_to_micros(val) { - Ok(micros) => ts = Some(micros), - Err(err) => { - if first_semantic_err.is_none() { - first_semantic_err = Some(err); - } - } - } - } else if key == cstr!("open") { - let val = decode_element_value(FIELD_OPEN, elem, offset)?; - match decode_positive_number(FIELD_OPEN, val) { - Ok(v) => open = Some(v), - Err(err) => { - if first_semantic_err.is_none() { - first_semantic_err = Some(err); - } - } - } - } else if key == cstr!("high") { - let val = decode_element_value(FIELD_HIGH, elem, offset)?; - match decode_positive_number(FIELD_HIGH, val) { - Ok(v) => high = Some(v), - Err(err) => { - if first_semantic_err.is_none() { - first_semantic_err = Some(err); - } - } - } - } else if key == cstr!("low") { - let val = decode_element_value(FIELD_LOW, elem, offset)?; - match decode_positive_number(FIELD_LOW, val) { - Ok(v) => low = Some(v), - Err(err) => { - if first_semantic_err.is_none() { - first_semantic_err = Some(err); - } - } - } - } else if key == cstr!("close") { - let val = decode_element_value(FIELD_CLOSE, elem, offset)?; - match decode_positive_number(FIELD_CLOSE, val) { - Ok(v) => close = Some(v), - Err(err) => { - if first_semantic_err.is_none() { - first_semantic_err = Some(err); - } - } - } - } else if key == cstr!("sharevolume") { - let val = decode_element_value(FIELD_SHARE_VOLUME, elem, offset)?; - match decode_non_negative_number(FIELD_SHARE_VOLUME, val) { - Ok(v) => volume = Some(v), - Err(err) => { - if first_semantic_err.is_none() { - first_semantic_err = Some(err); - } - } - } - } else { - // Validate skipped top-level payloads (including adjustedopen..adjustedclose and - // avolume) via borrowed `RawBsonRef` views (zero allocation) so malformed bytes still - // reject the document as `CorruptBson` at its frame offset. - elem.value().map_err(|err| BsonQmIntradayError::CorruptBson { - offset, - detail: format!("field '{}': {err}", key.as_str()), - })?; - } - } - - if let Some(err) = first_semantic_err { - return Err(err); - } - - let Some(qm_search_code) = qm_search_code else { - return Err(BsonQmIntradayError::MissingField { - field: FIELD_QM_SEARCH_CODE, - }); - }; - let Some(ts) = ts else { - return Err(BsonQmIntradayError::MissingField { - field: FIELD_TIMESTAMP, - }); - }; - let Some(open) = open else { - return Err(BsonQmIntradayError::MissingField { field: FIELD_OPEN }); - }; - let Some(high) = high else { - return Err(BsonQmIntradayError::MissingField { field: FIELD_HIGH }); - }; - let Some(low) = low else { - return Err(BsonQmIntradayError::MissingField { field: FIELD_LOW }); - }; - let Some(close) = close else { - return Err(BsonQmIntradayError::MissingField { field: FIELD_CLOSE }); - }; - let Some(volume) = volume else { - return Err(BsonQmIntradayError::MissingField { - field: FIELD_SHARE_VOLUME, - }); - }; - - Ok(RawQmIntradayBar { - qm_search_code, - ts, - open, - high, - low, - close, - volume, - }) -} - -/// Decodes a single `&RawDocument` representing a `qmIntraday` MongoDB document in one forward -/// pass without allocating a `String` or owned `bson::Document`. -#[inline] -pub fn decode_qm_intraday_doc<'a>( - doc: &'a RawDocument, -) -> Result, BsonQmIntradayError> { - decode_qm_intraday_doc_at(doc, 0) -} - -/// Decodes a single length-prefixed raw BSON document byte slice into a borrowed -/// [`RawQmIntradayBar`]. -pub fn decode_qm_intraday_bytes<'a>( - bytes: &'a [u8], -) -> Result, BsonQmIntradayError> { - let doc = parse_single_raw_doc(bytes).map_err(map_framing_error)?; - decode_qm_intraday_doc_at(doc, 0) -} - -/// Streams a concatenated length-prefixed BSON buffer through [`decode_qm_intraday_doc`], -/// invoking `on_bar` for every valid document and `on_error(byte_offset, err)` for every rejected -/// document without aborting the stream on recoverable per-document errors. -/// -/// Stops at an unrecoverable frame length or truncated tail and counts it once. -/// Always maintains `stats.rows_decoded + stats.rejected_total() == stats.docs_seen`. -pub fn decode_qm_intraday_buffer<'a, F, E>( - buf: &'a [u8], - mut on_bar: F, - mut on_error: E, -) -> BsonQmIntradayDecodeStats -where - F: FnMut(RawQmIntradayBar<'a>), - E: FnMut(usize, BsonQmIntradayError), -{ - let mut stats = BsonQmIntradayDecodeStats::default(); - let mut iter = iter_raw_bson_docs(buf); - - while let Some(item) = iter.next_with_offset() { - stats.docs_seen += 1; - match item { - Ok((doc_offset, doc)) => match decode_qm_intraday_doc_at(doc, doc_offset) { - Ok(bar) => { - stats.rows_decoded += 1; - on_bar(bar); - } - Err(err) => { - stats.record_error(&err); - on_error(doc_offset, err); - } - }, - Err((doc_offset, err)) => { - let mapped = map_framing_error(err); - stats.record_error(&mapped); - on_error(doc_offset, mapped); - } - } - } - - stats -} - -#[cfg(test)] -#[path = "bson_qm_intraday_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/bson_qm_intraday_tests.rs b/tools/curate-etl/src/bson_qm_intraday_tests.rs deleted file mode 100644 index b4638271..00000000 --- a/tools/curate-etl/src/bson_qm_intraday_tests.rs +++ /dev/null @@ -1,1092 +0,0 @@ -use bson::oid::ObjectId; -use bson::raw::{cstr, RawArrayBuf, RawBsonRef, RawDocumentBuf}; -use bson::spec::ElementType; -use bson::{DateTime, Timestamp}; - -use super::*; - -fn make_valid_doc( - code: &str, - timestamp_ms: i64, - open: f64, - high: f64, - low: f64, - close: f64, - sharevolume: f64, -) -> RawDocumentBuf { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), code); - doc.append(cstr!("timestamp"), DateTime::from_millis(timestamp_ms)); - doc.append(cstr!("open"), open); - doc.append(cstr!("high"), high); - doc.append(cstr!("low"), low); - doc.append(cstr!("close"), close); - doc.append(cstr!("sharevolume"), sharevolume); - doc -} - -fn make_doc_with_timestamp(timestamp: RawBsonRef<'_>) -> RawDocumentBuf { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), "SHOP:CA"); - doc.append(cstr!("timestamp"), timestamp); - doc.append(cstr!("open"), 84.10_f64); - doc.append(cstr!("high"), 84.55_f64); - doc.append(cstr!("low"), 84.02_f64); - doc.append(cstr!("close"), 84.40_f64); - doc.append(cstr!("sharevolume"), 12_500.0_f64); - doc -} - -#[test] -fn decodes_raw_fields_ignoring_differing_adjusted_fields_with_zero_copy_key_and_mappers() { - // 2024-06-07T13:30:00.375Z (nonzero milliseconds to verify exact * 1_000 scaling) - const TS_MS: i64 = 1_717_767_000_375; - const EXPECTED_TS_MICROS: i64 = 1_717_767_000_375_000; - const VERBATIM_KEY: &str = " SHOP:CA "; - - let mut nested = RawDocumentBuf::new(); - nested.append(cstr!("provider"), "quotemedia"); - nested.append(cstr!("interval"), 1_i32); - - let mut tags = RawArrayBuf::new(); - tags.push("ca"); - tags.push("1m"); - - let mut doc = RawDocumentBuf::new(); - doc.append( - cstr!("_id"), - ObjectId::from_bytes([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]), - ); - doc.append(cstr!("symbol"), "SHOP"); - doc.append(cstr!("exchange"), "TSX"); - doc.append(cstr!("qmSearchCode"), VERBATIM_KEY); - doc.append(cstr!("startdatetime"), "2024-06-07 09:30:00"); - doc.append(cstr!("timestamp"), DateTime::from_millis(TS_MS)); - // Mixed numeric encodings for raw fields: - doc.append(cstr!("open"), 84_i32); - doc.append(cstr!("high"), 85_i64); - doc.append(cstr!("low"), 83.75_f64); - doc.append(cstr!("close"), 84.50_f64); - doc.append(cstr!("sharevolume"), 12_500_i64); - // Deliberately different adjusted fields that must be ignored: - doc.append(cstr!("adjustedopen"), 8.40_f64); - doc.append(cstr!("adjustedhigh"), 8.50_f64); - doc.append(cstr!("adjustedlow"), 8.375_f64); - doc.append(cstr!("adjustedclose"), 8.45_f64); - doc.append(cstr!("avolume"), 125_000.0_f64); - doc.append(cstr!("meta"), RawBsonRef::Document(nested.as_ref())); - doc.append(cstr!("tags"), RawBsonRef::Array(tags.as_ref())); - - let bytes = doc.as_bytes(); - let buf_start = bytes.as_ptr() as usize; - let buf_end = buf_start + bytes.len(); - - let from_doc = decode_qm_intraday_doc(&doc).unwrap(); - let from_bytes = decode_qm_intraday_bytes(bytes).unwrap(); - assert_eq!(from_doc, from_bytes); - - for bar in [from_doc, from_bytes] { - assert_eq!(bar.qm_search_code, VERBATIM_KEY); - assert_eq!(bar.ts, EXPECTED_TS_MICROS); - assert_eq!(bar.open.to_bits(), 84.0_f64.to_bits()); - assert_eq!(bar.high.to_bits(), 85.0_f64.to_bits()); - assert_eq!(bar.low.to_bits(), 83.75_f64.to_bits()); - assert_eq!(bar.close.to_bits(), 84.50_f64.to_bits()); - assert_eq!(bar.volume.to_bits(), 12_500.0_f64.to_bits()); - - // Zero-copy proof: borrowed key slice points inside the input BSON buffer. - let key_start = bar.qm_search_code.as_ptr() as usize; - let key_end = key_start + bar.qm_search_code.len(); - assert!( - key_start >= buf_start && key_end <= buf_end, - "expected qm_search_code pointer {key_start:#x}..{key_end:#x} inside input buffer {buf_start:#x}..{buf_end:#x}" - ); - } - - // Verify into_eod_intraday_bar and try_into_eod_intraday_bar preserve raw OHLCV verbatim. - let mut seen_into: Option<(&str, i64)> = None; - let mapped = from_doc.into_eod_intraday_bar(|code, ts| { - seen_into = Some((code, ts)); - 42_u64 - }); - assert_eq!(seen_into, Some((VERBATIM_KEY, EXPECTED_TS_MICROS))); - assert_eq!(mapped.key, 42_u64); - assert_eq!(mapped.ts, EXPECTED_TS_MICROS); - assert_eq!(mapped.open.to_bits(), 84.0_f64.to_bits()); - assert_eq!(mapped.high.to_bits(), 85.0_f64.to_bits()); - assert_eq!(mapped.low.to_bits(), 83.75_f64.to_bits()); - assert_eq!(mapped.close.to_bits(), 84.50_f64.to_bits()); - assert_eq!(mapped.volume.to_bits(), 12_500.0_f64.to_bits()); - - let mut seen_try_some: Option<(&str, i64)> = None; - let try_some = from_doc.try_into_eod_intraday_bar(|code, ts| { - seen_try_some = Some((code, ts)); - Some(99_u64) - }); - assert_eq!(seen_try_some, Some((VERBATIM_KEY, EXPECTED_TS_MICROS))); - let try_some = try_some.unwrap(); - assert_eq!(try_some.key, 99_u64); - assert_eq!(try_some.ts, EXPECTED_TS_MICROS); - assert_eq!(try_some.open.to_bits(), 84.0_f64.to_bits()); - assert_eq!(try_some.high.to_bits(), 85.0_f64.to_bits()); - assert_eq!(try_some.low.to_bits(), 83.75_f64.to_bits()); - assert_eq!(try_some.close.to_bits(), 84.50_f64.to_bits()); - assert_eq!(try_some.volume.to_bits(), 12_500.0_f64.to_bits()); - - let try_none: Option> = from_doc.try_into_eod_intraday_bar(|code, ts| { - assert_eq!(code, VERBATIM_KEY); - assert_eq!(ts, EXPECTED_TS_MICROS); - None - }); - assert!(try_none.is_none()); -} - -#[test] -fn table_tests_all_seven_required_fields_for_omission_null_and_wrong_type() { - const ALL_FIELDS: [&str; 7] = [ - FIELD_QM_SEARCH_CODE, - FIELD_TIMESTAMP, - FIELD_OPEN, - FIELD_HIGH, - FIELD_LOW, - FIELD_CLOSE, - FIELD_SHARE_VOLUME, - ]; - - let append_valid = |doc: &mut RawDocumentBuf, field: &str| match field { - FIELD_QM_SEARCH_CODE => doc.append(cstr!("qmSearchCode"), "SHOP:CA"), - FIELD_TIMESTAMP => doc.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_000_000)), - FIELD_OPEN => doc.append(cstr!("open"), 10.0_f64), - FIELD_HIGH => doc.append(cstr!("high"), 11.0_f64), - FIELD_LOW => doc.append(cstr!("low"), 9.5_f64), - FIELD_CLOSE => doc.append(cstr!("close"), 10.5_f64), - FIELD_SHARE_VOLUME => doc.append(cstr!("sharevolume"), 100.0_f64), - other => unreachable!("unexpected field {other}"), - }; - - let append_override = |doc: &mut RawDocumentBuf, field: &str, val: RawBsonRef<'_>| match field { - FIELD_QM_SEARCH_CODE => doc.append(cstr!("qmSearchCode"), val), - FIELD_TIMESTAMP => doc.append(cstr!("timestamp"), val), - FIELD_OPEN => doc.append(cstr!("open"), val), - FIELD_HIGH => doc.append(cstr!("high"), val), - FIELD_LOW => doc.append(cstr!("low"), val), - FIELD_CLOSE => doc.append(cstr!("close"), val), - FIELD_SHARE_VOLUME => doc.append(cstr!("sharevolume"), val), - other => unreachable!("unexpected field {other}"), - }; - - for target in ALL_FIELDS { - // 1. Omission -> MissingField - let mut missing = RawDocumentBuf::new(); - for f in ALL_FIELDS { - if f != target { - append_valid(&mut missing, f); - } - } - let err = decode_qm_intraday_doc(&missing).unwrap_err(); - assert_eq!(err, BsonQmIntradayError::MissingField { field: target }); - assert!(err.to_string().contains(target)); - let mut st = BsonQmIntradayDecodeStats::default(); - st.record_error(&err); - assert_eq!(st.rejected_missing_field, 1); - assert_eq!(st.rejected_total(), 1); - - // 2. Null -> WrongType(Null) - let mut with_null = RawDocumentBuf::new(); - for f in ALL_FIELDS { - if f == target { - append_override(&mut with_null, f, RawBsonRef::Null); - } else { - append_valid(&mut with_null, f); - } - } - let err = decode_qm_intraday_doc(&with_null).unwrap_err(); - assert_eq!( - err, - BsonQmIntradayError::WrongType { - field: target, - actual: ElementType::Null, - } - ); - assert!(err.to_string().contains(target)); - let mut st = BsonQmIntradayDecodeStats::default(); - st.record_error(&err); - assert_eq!(st.rejected_wrong_type, 1); - assert_eq!(st.rejected_total(), 1); - - // 3. Another inappropriate BSON type -> WrongType - let (bad_val, expected_type) = match target { - FIELD_QM_SEARCH_CODE => (RawBsonRef::Int32(123), ElementType::Int32), - FIELD_TIMESTAMP => (RawBsonRef::Boolean(true), ElementType::Boolean), - _ => (RawBsonRef::String("10.0"), ElementType::String), - }; - let mut with_wrong = RawDocumentBuf::new(); - for f in ALL_FIELDS { - if f == target { - append_override(&mut with_wrong, f, bad_val); - } else { - append_valid(&mut with_wrong, f); - } - } - let err = decode_qm_intraday_doc(&with_wrong).unwrap_err(); - assert_eq!( - err, - BsonQmIntradayError::WrongType { - field: target, - actual: expected_type, - } - ); - let mut st = BsonQmIntradayDecodeStats::default(); - st.record_error(&err); - assert_eq!(st.rejected_wrong_type, 1); - assert_eq!(st.rejected_total(), 1); - } - - // Empty document checks missing-field order starts at qmSearchCode. - let empty_doc = RawDocumentBuf::new(); - assert_eq!( - decode_qm_intraday_doc(&empty_doc).unwrap_err(), - BsonQmIntradayError::MissingField { - field: FIELD_QM_SEARCH_CODE - } - ); -} - -#[test] -fn rejects_empty_and_whitespace_only_qm_search_code() { - for blank in ["", " ", " ", "\t\n\r "] { - let doc = make_valid_doc(blank, 1_717_767_000_000, 10.0, 11.0, 9.0, 10.5, 100.0); - let err = decode_qm_intraday_doc(&doc).unwrap_err(); - assert_eq!( - err, - BsonQmIntradayError::EmptyField { - field: FIELD_QM_SEARCH_CODE - } - ); - assert!(err.to_string().contains(FIELD_QM_SEARCH_CODE)); - let mut st = BsonQmIntradayDecodeStats::default(); - st.record_error(&err); - assert_eq!(st.rejected_empty_field, 1); - assert_eq!(st.rejected_total(), 1); - } -} - -#[test] -fn validates_timestamp_datetime_boundaries_and_rejects_substitutes() { - // Epoch zero is valid. - let epoch_doc = make_doc_with_timestamp(RawBsonRef::DateTime(DateTime::from_millis(0))); - assert_eq!(decode_qm_intraday_doc(&epoch_doc).unwrap().ts, 0); - - // Largest in-range millisecond timestamp (i64::MAX / 1_000) is valid. - let max_doc = make_doc_with_timestamp(RawBsonRef::DateTime(DateTime::from_millis( - MAX_TIMESTAMP_MILLIS, - ))); - assert_eq!( - decode_qm_intraday_doc(&max_doc).unwrap().ts, - MAX_TIMESTAMP_MILLIS * 1_000 - ); - - // Negative and overflowing DateTime values -> InvalidTimestamp. - for bad_ms in [-1_i64, i64::MIN, MAX_TIMESTAMP_MILLIS + 1, i64::MAX] { - let doc = make_doc_with_timestamp(RawBsonRef::DateTime(DateTime::from_millis(bad_ms))); - let err = decode_qm_intraday_doc(&doc).unwrap_err(); - assert_eq!( - err, - BsonQmIntradayError::InvalidTimestamp { - field: FIELD_TIMESTAMP - } - ); - assert!(err.to_string().contains(FIELD_TIMESTAMP)); - let mut st = BsonQmIntradayDecodeStats::default(); - st.record_error(&err); - assert_eq!(st.rejected_invalid_timestamp, 1); - assert_eq!(st.rejected_total(), 1); - } - - // Numeric, string, and BSON Timestamp substitutes -> WrongType. - let wrong_ts: [(RawBsonRef<'_>, ElementType); 6] = [ - (RawBsonRef::Int32(1_717_767_000), ElementType::Int32), - (RawBsonRef::Int64(1_717_767_000_000), ElementType::Int64), - (RawBsonRef::Double(1_717_767_000_000.0), ElementType::Double), - ( - RawBsonRef::String("2024-06-07T13:30:00Z"), - ElementType::String, - ), - ( - RawBsonRef::Timestamp(Timestamp { - time: 1_717_767_000, - increment: 1, - }), - ElementType::Timestamp, - ), - (RawBsonRef::Null, ElementType::Null), - ]; - for (val, expected_type) in wrong_ts { - let doc = make_doc_with_timestamp(val); - let err = decode_qm_intraday_doc(&doc).unwrap_err(); - assert_eq!( - err, - BsonQmIntradayError::WrongType { - field: FIELD_TIMESTAMP, - actual: expected_type, - } - ); - } -} - -#[test] -fn validates_ohlc_and_sharevolume_domains_and_normalizes_negative_zero_volume() { - let ohlc_fields = [FIELD_OPEN, FIELD_HIGH, FIELD_LOW, FIELD_CLOSE]; - - for target in ohlc_fields { - let build_with = |val: RawBsonRef<'_>| { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), "SHOP:CA"); - doc.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_000_000)); - for (name, key) in [ - (FIELD_OPEN, cstr!("open")), - (FIELD_HIGH, cstr!("high")), - (FIELD_LOW, cstr!("low")), - (FIELD_CLOSE, cstr!("close")), - (FIELD_SHARE_VOLUME, cstr!("sharevolume")), - ] { - if name == target { - doc.append(key, val); - } else { - doc.append(key, 10.0_f64); - } - } - doc - }; - - for bad_num in [ - RawBsonRef::Double(0.0), - RawBsonRef::Double(-0.0), - RawBsonRef::Double(-1.25), - RawBsonRef::Double(f64::NAN), - RawBsonRef::Double(f64::INFINITY), - RawBsonRef::Double(f64::NEG_INFINITY), - RawBsonRef::Int32(0), - RawBsonRef::Int32(-5), - RawBsonRef::Int64(0), - RawBsonRef::Int64(-5), - ] { - let doc = build_with(bad_num); - let err = decode_qm_intraday_doc(&doc).unwrap_err(); - match &err { - BsonQmIntradayError::InvalidNumber { field, .. } => assert_eq!(*field, target), - other => panic!("expected InvalidNumber for {target}, got {other:?}"), - } - assert!(err.to_string().contains(target)); - let mut st = BsonQmIntradayDecodeStats::default(); - st.record_error(&err); - assert_eq!(st.rejected_invalid_number, 1); - assert_eq!(st.rejected_total(), 1); - } - } - - let build_with_vol = |val: RawBsonRef<'_>| { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), "SHOP:CA"); - doc.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_000_000)); - doc.append(cstr!("open"), 10.0_f64); - doc.append(cstr!("high"), 11.0_f64); - doc.append(cstr!("low"), 9.5_f64); - doc.append(cstr!("close"), 10.5_f64); - doc.append(cstr!("sharevolume"), val); - doc - }; - - // Zero sharevolume in +0.0, -0.0, Int32(0), Int64(0) canonicalizes to +0.0. - for zero_vol in [ - RawBsonRef::Double(0.0), - RawBsonRef::Double(-0.0), - RawBsonRef::Int32(0), - RawBsonRef::Int64(0), - ] { - let doc = build_with_vol(zero_vol); - let decoded = decode_qm_intraday_doc(&doc).unwrap(); - assert_eq!(decoded.volume.to_bits(), 0.0_f64.to_bits()); - } - - // Negative and non-finite sharevolume -> InvalidNumber. - for bad_vol in [ - RawBsonRef::Double(-0.01), - RawBsonRef::Double(f64::NAN), - RawBsonRef::Double(f64::INFINITY), - RawBsonRef::Double(f64::NEG_INFINITY), - RawBsonRef::Int32(-1), - RawBsonRef::Int64(-1), - ] { - let doc = build_with_vol(bad_vol); - let err = decode_qm_intraday_doc(&doc).unwrap_err(); - match &err { - BsonQmIntradayError::InvalidNumber { field, .. } => { - assert_eq!(*field, FIELD_SHARE_VOLUME) - } - other => panic!("expected InvalidNumber for sharevolume, got {other:?}"), - } - assert!(err.to_string().contains(FIELD_SHARE_VOLUME)); - let mut st = BsonQmIntradayDecodeStats::default(); - st.record_error(&err); - assert_eq!(st.rejected_invalid_number, 1); - assert_eq!(st.rejected_total(), 1); - } -} - -#[test] -fn duplicate_fields_and_semantic_vs_corrupt_precedence() { - // 1. All duplicate occurrences valid -> last valid value wins. - let mut dup_valid = RawDocumentBuf::new(); - dup_valid.append(cstr!("qmSearchCode"), "FIRST:CA"); - dup_valid.append(cstr!("timestamp"), DateTime::from_millis(1_000)); - dup_valid.append(cstr!("open"), 10.0_f64); - dup_valid.append(cstr!("high"), 11.0_f64); - dup_valid.append(cstr!("low"), 9.0_f64); - dup_valid.append(cstr!("close"), 10.5_f64); - dup_valid.append(cstr!("sharevolume"), 100.0_f64); - dup_valid.append(cstr!("qmSearchCode"), "SECOND:CA"); - dup_valid.append(cstr!("timestamp"), DateTime::from_millis(2_500)); - dup_valid.append(cstr!("open"), 20.0_f64); - dup_valid.append(cstr!("high"), 22.0_f64); - dup_valid.append(cstr!("low"), 19.0_f64); - dup_valid.append(cstr!("close"), 21.5_f64); - dup_valid.append(cstr!("sharevolume"), 250_i32); - - let bar = decode_qm_intraday_doc(&dup_valid).unwrap(); - assert_eq!(bar.qm_search_code, "SECOND:CA"); - assert_eq!(bar.ts, 2_500_000); - assert_eq!(bar.open.to_bits(), 20.0_f64.to_bits()); - assert_eq!(bar.high.to_bits(), 22.0_f64.to_bits()); - assert_eq!(bar.low.to_bits(), 19.0_f64.to_bits()); - assert_eq!(bar.close.to_bits(), 21.5_f64.to_bits()); - assert_eq!(bar.volume.to_bits(), 250.0_f64.to_bits()); - - // 2. A valid duplicate cannot erase an earlier semantic error. - let mut err_then_valid = RawDocumentBuf::new(); - err_then_valid.append(cstr!("qmSearchCode"), " "); - err_then_valid.append(cstr!("qmSearchCode"), "SHOP:CA"); - err_then_valid.append(cstr!("timestamp"), DateTime::from_millis(1_000)); - err_then_valid.append(cstr!("open"), 10.0_f64); - err_then_valid.append(cstr!("high"), 11.0_f64); - err_then_valid.append(cstr!("low"), 9.0_f64); - err_then_valid.append(cstr!("close"), 10.5_f64); - err_then_valid.append(cstr!("sharevolume"), 100.0_f64); - assert_eq!( - decode_qm_intraday_doc(&err_then_valid).unwrap_err(), - BsonQmIntradayError::EmptyField { - field: FIELD_QM_SEARCH_CODE - } - ); - - // 3. First semantic error survives a second semantic error. - let mut two_errors = RawDocumentBuf::new(); - two_errors.append(cstr!("qmSearchCode"), "SHOP:CA"); - two_errors.append(cstr!("timestamp"), DateTime::from_millis(-1)); - two_errors.append(cstr!("open"), -5.0_f64); - two_errors.append(cstr!("high"), RawBsonRef::Null); - two_errors.append(cstr!("low"), 9.0_f64); - two_errors.append(cstr!("close"), 10.5_f64); - two_errors.append(cstr!("sharevolume"), 100.0_f64); - assert_eq!( - decode_qm_intraday_doc(&two_errors).unwrap_err(), - BsonQmIntradayError::InvalidTimestamp { - field: FIELD_TIMESTAMP - } - ); - - // 4. Malformed UTF-8 in a later skipped field overrides an earlier semantic error as CorruptBson. - const MARKER: &[u8] = b"2024-06-07 09:30:00"; - let mut semantic_then_corrupt = RawDocumentBuf::new(); - semantic_then_corrupt.append(cstr!("qmSearchCode"), " "); // earlier EmptyField - semantic_then_corrupt.append(cstr!("timestamp"), DateTime::from_millis(-5)); // second semantic err - semantic_then_corrupt.append(cstr!("open"), 10.0_f64); - semantic_then_corrupt.append(cstr!("high"), 11.0_f64); - semantic_then_corrupt.append(cstr!("low"), 9.0_f64); - semantic_then_corrupt.append(cstr!("close"), 10.5_f64); - semantic_then_corrupt.append(cstr!("sharevolume"), 100.0_f64); - semantic_then_corrupt.append(cstr!("startdatetime"), "2024-06-07 09:30:00"); - - let mut corrupt_bytes = semantic_then_corrupt.as_bytes().to_vec(); - let pos = corrupt_bytes - .windows(MARKER.len()) - .position(|w| w == MARKER) - .expect("startdatetime marker must exist"); - corrupt_bytes[pos + 4] = 0xFF; - - match decode_qm_intraday_bytes(&corrupt_bytes) { - Err(BsonQmIntradayError::CorruptBson { offset: 0, detail }) => { - assert!( - detail.contains("startdatetime"), - "expected offending skipped field name in detail, got: {detail}" - ); - } - other => panic!("expected CorruptBson overriding earlier semantic error, got {other:?}"), - } -} - -#[test] -fn rejects_truncated_corrupt_and_trailing_single_doc_bytes_as_corrupt_bson() { - // Truncated header (< 4 bytes) - match decode_qm_intraday_bytes(&[0x10, 0x00]) { - Err(BsonQmIntradayError::CorruptBson { offset: 0, detail }) => { - assert!(detail.contains("truncated"), "detail={detail}"); - } - other => panic!("expected CorruptBson for truncated header, got {other:?}"), - } - - // Declared length < 5 - match decode_qm_intraday_bytes(&[4, 0, 0, 0]) { - Err(BsonQmIntradayError::CorruptBson { offset: 0, detail }) => { - assert!(detail.contains('4'), "detail={detail}"); - } - other => panic!("expected CorruptBson for length < 5, got {other:?}"), - } - - let valid = make_valid_doc("SHOP:CA", 1_717_767_000_000, 84.0, 85.0, 83.5, 84.5, 1000.0); - - // Truncated body - let truncated = &valid.as_bytes()[..valid.as_bytes().len() - 3]; - match decode_qm_intraday_bytes(truncated) { - Err(BsonQmIntradayError::CorruptBson { offset: 0, detail }) => { - assert!(detail.contains("truncated"), "detail={detail}"); - } - other => panic!("expected CorruptBson for truncated body, got {other:?}"), - } - - // Trailing extra bytes on single-doc decode - let mut with_trailing = valid.as_bytes().to_vec(); - with_trailing.push(0x00); - match decode_qm_intraday_bytes(&with_trailing) { - Err(BsonQmIntradayError::CorruptBson { offset: 0, detail }) => { - assert!(detail.contains("length"), "detail={detail}"); - } - other => panic!("expected CorruptBson for trailing bytes, got {other:?}"), - } - - // Malformed BSON (bad trailing NUL terminator) - let mut bad_term = valid.as_bytes().to_vec(); - *bad_term.last_mut().unwrap() = 0xFF; - match decode_qm_intraday_bytes(&bad_term) { - Err(BsonQmIntradayError::CorruptBson { offset: 0, .. }) => {} - other => panic!("expected CorruptBson for bad terminator, got {other:?}"), - } -} - -#[test] -fn decodes_mixed_buffer_deterministically_recovers_past_corrupt_frame_and_merges_stats() { - // Empty buffer -> zero stats and no callbacks. - let mut empty_rows = 0usize; - let mut empty_errs = 0usize; - let empty_stats = decode_qm_intraday_buffer(&[], |_| empty_rows += 1, |_, _| empty_errs += 1); - assert_eq!(empty_stats, BsonQmIntradayDecodeStats::default()); - assert_eq!(empty_stats.rejected_total(), 0); - assert_eq!(empty_rows, 0); - assert_eq!(empty_errs, 0); - - let valid1 = make_valid_doc("SHOP:CA", 1_717_767_000_000, 84.0, 85.0, 83.5, 84.5, 1000.0); - let empty_key = make_valid_doc(" ", 1_717_767_060_000, 84.5, 85.0, 84.0, 84.8, 500.0); - let bad_ts = make_doc_with_timestamp(RawBsonRef::DateTime(DateTime::from_millis(-10))); - let bad_price = make_valid_doc("SHOP:CA", 1_717_767_180_000, 0.0, 85.0, 83.0, 84.0, 200.0); - - let mut wrong_type = RawDocumentBuf::new(); - wrong_type.append(cstr!("qmSearchCode"), "SHOP:CA"); - wrong_type.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_240_000)); - wrong_type.append(cstr!("open"), RawBsonRef::Null); - wrong_type.append(cstr!("high"), 85.0_f64); - wrong_type.append(cstr!("low"), 83.0_f64); - wrong_type.append(cstr!("close"), 84.0_f64); - wrong_type.append(cstr!("sharevolume"), 200.0_f64); - - let mut missing_field = RawDocumentBuf::new(); - missing_field.append(cstr!("qmSearchCode"), "SHOP:CA"); - missing_field.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_300_000)); - missing_field.append(cstr!("open"), 84.0_f64); - missing_field.append(cstr!("high"), 85.0_f64); - missing_field.append(cstr!("low"), 83.0_f64); - missing_field.append(cstr!("close"), 84.0_f64); - - // Valid length-framed doc whose trailing terminator is corrupt -> CorruptBson, but buffer - // iteration recovers past the known frame boundary and decodes valid2 after it. - let mut corrupt_framed = valid1.as_bytes().to_vec(); - *corrupt_framed.last_mut().unwrap() = 0xAA; - - let valid2 = make_valid_doc("X:CA", 1_717_767_360_000, 39.5, 40.0, 39.25, 39.75, -0.0); - - let mut batch1 = Vec::new(); - batch1.extend_from_slice(valid1.as_bytes()); - let off_empty = batch1.len(); - batch1.extend_from_slice(empty_key.as_bytes()); - let off_bad_ts = batch1.len(); - batch1.extend_from_slice(bad_ts.as_bytes()); - let off_bad_price = batch1.len(); - batch1.extend_from_slice(bad_price.as_bytes()); - - let mut batch2 = Vec::new(); - batch2.extend_from_slice(wrong_type.as_bytes()); - batch2.extend_from_slice(missing_field.as_bytes()); - batch2.extend_from_slice(&corrupt_framed); - batch2.extend_from_slice(valid2.as_bytes()); - - let mut full_buf = Vec::new(); - full_buf.extend_from_slice(&batch1); - let off_wrong_type = full_buf.len(); - full_buf.extend_from_slice(wrong_type.as_bytes()); - let off_missing = full_buf.len(); - full_buf.extend_from_slice(missing_field.as_bytes()); - let off_corrupt = full_buf.len(); - full_buf.extend_from_slice(&corrupt_framed); - full_buf.extend_from_slice(valid2.as_bytes()); - let off_trunc = full_buf.len(); - // Truncated tail: stops cleanly and is counted once. - full_buf.extend_from_slice(&valid2.as_bytes()[..10]); - - let run_once = |buf: &[u8]| { - let mut rows = Vec::new(); - let mut errors = Vec::new(); - let stats = decode_qm_intraday_buffer( - buf, - |bar| { - rows.push(( - bar.qm_search_code.to_owned(), - bar.ts, - bar.close.to_bits(), - bar.volume.to_bits(), - )) - }, - |offset, err| errors.push((offset, err)), - ); - (rows, errors, stats) - }; - - let (rows_a, errs_a, stats_a) = run_once(&full_buf); - let (rows_b, errs_b, stats_b) = run_once(&full_buf); - - // Deterministic replay produces identical rows, errors, offsets, and stats. - assert_eq!(rows_a, rows_b); - assert_eq!(errs_a, errs_b); - assert_eq!(stats_a, stats_b); - - assert_eq!( - rows_a, - vec![ - ( - "SHOP:CA".to_owned(), - 1_717_767_000_000_000, - 84.5_f64.to_bits(), - 1000.0_f64.to_bits(), - ), - ( - "X:CA".to_owned(), - 1_717_767_360_000_000, - 39.75_f64.to_bits(), - 0.0_f64.to_bits(), - ), - ] - ); - - assert_eq!(stats_a.docs_seen, 9); - assert_eq!(stats_a.rows_decoded, 2); - assert_eq!(stats_a.rejected_empty_field, 1); - assert_eq!(stats_a.rejected_invalid_timestamp, 1); - assert_eq!(stats_a.rejected_invalid_number, 1); - assert_eq!(stats_a.rejected_wrong_type, 1); - assert_eq!(stats_a.rejected_missing_field, 1); - assert_eq!(stats_a.rejected_corrupt_document, 2); // corrupt_framed + truncated tail - assert_eq!(stats_a.rejected_total(), 7); - assert_eq!( - stats_a.docs_seen, - stats_a.rows_decoded + stats_a.rejected_total() - ); - - assert_eq!(errs_a.len(), 7); - assert_eq!(errs_a[0].0, off_empty); - assert_eq!( - errs_a[0].1, - BsonQmIntradayError::EmptyField { - field: FIELD_QM_SEARCH_CODE - } - ); - assert_eq!(errs_a[1].0, off_bad_ts); - assert_eq!( - errs_a[1].1, - BsonQmIntradayError::InvalidTimestamp { - field: FIELD_TIMESTAMP - } - ); - assert_eq!(errs_a[2].0, off_bad_price); - assert!(matches!( - errs_a[2].1, - BsonQmIntradayError::InvalidNumber { - field: FIELD_OPEN, - .. - } - )); - assert_eq!(errs_a[3].0, off_wrong_type); - assert_eq!( - errs_a[3].1, - BsonQmIntradayError::WrongType { - field: FIELD_OPEN, - actual: ElementType::Null, - } - ); - assert_eq!(errs_a[4].0, off_missing); - assert_eq!( - errs_a[4].1, - BsonQmIntradayError::MissingField { - field: FIELD_SHARE_VOLUME - } - ); - assert_eq!(errs_a[5].0, off_corrupt); - assert!(matches!( - &errs_a[5].1, - BsonQmIntradayError::CorruptBson { offset, .. } if *offset == off_corrupt - )); - assert_eq!(errs_a[6].0, off_trunc); - assert!(matches!( - &errs_a[6].1, - BsonQmIntradayError::CorruptBson { offset, detail } - if *offset == off_trunc && detail.contains("truncated") - )); - - // Verify merge and AddAssign match decoding frame-aligned batches separately. - let mut batch2_with_trunc = batch2.clone(); - batch2_with_trunc.extend_from_slice(&valid2.as_bytes()[..10]); - let s1 = decode_qm_intraday_buffer(&batch1, |_| {}, |_, _| {}); - let s2 = decode_qm_intraday_buffer(&batch2_with_trunc, |_| {}, |_, _| {}); - let mut merged = s1; - merged.merge(&s2); - assert_eq!(merged, stats_a); - - let mut added = s1; - added += s2; - assert_eq!(added, stats_a); -} - -// --- QA edge cases (T-150) ------------------------------------------------------------------- - -fn find_marker(bytes: &[u8], marker: &[u8]) -> usize { - bytes - .windows(marker.len()) - .position(|w| w == marker) - .expect("marker must exist in fixture bytes") -} - -#[test] -fn corrupt_bytes_inside_an_adjusted_field_reject_the_document_as_corrupt_bson() { - // Proves adjusted fields are validated (not blindly skipped) even though they are never read: - // flip `adjustedclose` from Double (0x01) to String (0x02) so its 8 payload bytes are read as a - // bogus string length. - let mut doc = make_valid_doc("SHOP:CA", 1_717_767_000_000, 84.0, 85.0, 83.5, 84.5, 1000.0); - doc.append(cstr!("adjustedclose"), 8.45_f64); - doc.append(cstr!("avolume"), 10_000.0_f64); - let mut bytes = doc.as_bytes().to_vec(); - let key_pos = find_marker(&bytes, b"adjustedclose\0"); - assert_eq!( - bytes[key_pos - 1], - 0x01, - "fixture: element type byte precedes key" - ); - bytes[key_pos - 1] = 0x02; - - match decode_qm_intraday_bytes(&bytes) { - Err(BsonQmIntradayError::CorruptBson { offset: 0, .. }) => {} - other => panic!("expected CorruptBson for corrupt adjustedclose, got {other:?}"), - } -} - -#[test] -fn adjusted_fields_of_any_type_or_value_do_not_affect_raw_decode() { - // Adjusted fields that would fail raw validation (Null, negative, NaN, string) must be ignored. - let mut doc = make_valid_doc( - "RY:CA", - 1_717_767_000_000, - 130.0, - 131.0, - 129.5, - 130.5, - 2_000.0, - ); - doc.append(cstr!("adjustedopen"), RawBsonRef::Null); - doc.append(cstr!("adjustedhigh"), -1.0_f64); - doc.append(cstr!("adjustedlow"), f64::NAN); - doc.append(cstr!("adjustedclose"), "n/a"); - doc.append(cstr!("avolume"), -5_i64); - - let bar = decode_qm_intraday_doc(&doc).unwrap(); - assert_eq!(bar.qm_search_code, "RY:CA"); - assert_eq!(bar.ts, 1_717_767_000_000_000); - assert_eq!(bar.open.to_bits(), 130.0_f64.to_bits()); - assert_eq!(bar.high.to_bits(), 131.0_f64.to_bits()); - assert_eq!(bar.low.to_bits(), 129.5_f64.to_bits()); - assert_eq!(bar.close.to_bits(), 130.5_f64.to_bits()); - assert_eq!(bar.volume.to_bits(), 2_000.0_f64.to_bits()); -} - -#[test] -fn adjusted_only_document_is_missing_raw_fields_not_silently_substituted() { - // A doc carrying only adjusted prices/volume must not fall back to them. - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), "SHOP:CA"); - doc.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_000_000)); - doc.append(cstr!("adjustedopen"), 8.4_f64); - doc.append(cstr!("adjustedhigh"), 8.5_f64); - doc.append(cstr!("adjustedlow"), 8.3_f64); - doc.append(cstr!("adjustedclose"), 8.45_f64); - doc.append(cstr!("avolume"), 125_000.0_f64); - assert_eq!( - decode_qm_intraday_doc(&doc).unwrap_err(), - BsonQmIntradayError::MissingField { field: FIELD_OPEN } - ); - - // Same with only `volume`/`avolume` instead of `sharevolume`. - let mut doc = make_doc_without_sharevolume(); - doc.append(cstr!("volume"), 100.0_f64); - doc.append(cstr!("avolume"), 100.0_f64); - assert_eq!( - decode_qm_intraday_doc(&doc).unwrap_err(), - BsonQmIntradayError::MissingField { - field: FIELD_SHARE_VOLUME - } - ); -} - -fn make_doc_without_sharevolume() -> RawDocumentBuf { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), "SHOP:CA"); - doc.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_000_000)); - doc.append(cstr!("open"), 10.0_f64); - doc.append(cstr!("high"), 11.0_f64); - doc.append(cstr!("low"), 9.0_f64); - doc.append(cstr!("close"), 10.5_f64); - doc -} - -#[test] -fn field_names_match_case_sensitively() { - // `Open` / `QmSearchCode` are unknown fields, so the real ones are reported missing. - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("QmSearchCode"), "SHOP:CA"); - doc.append(cstr!("qmSearchCode"), "SHOP:CA"); - doc.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_000_000)); - doc.append(cstr!("Open"), 10.0_f64); - doc.append(cstr!("high"), 11.0_f64); - doc.append(cstr!("low"), 9.0_f64); - doc.append(cstr!("close"), 10.5_f64); - doc.append(cstr!("sharevolume"), 1.0_f64); - assert_eq!( - decode_qm_intraday_doc(&doc).unwrap_err(), - BsonQmIntradayError::MissingField { field: FIELD_OPEN } - ); -} - -#[test] -fn field_order_does_not_change_the_decoded_bar() { - let forward = make_valid_doc( - "SHOP:CA", - 1_717_767_000_123, - 84.0, - 85.0, - 83.5, - 84.5, - 1_000.0, - ); - - let mut reversed = RawDocumentBuf::new(); - reversed.append(cstr!("sharevolume"), 1_000.0_f64); - reversed.append(cstr!("close"), 84.5_f64); - reversed.append(cstr!("low"), 83.5_f64); - reversed.append(cstr!("high"), 85.0_f64); - reversed.append(cstr!("open"), 84.0_f64); - reversed.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_000_123)); - reversed.append(cstr!("qmSearchCode"), "SHOP:CA"); - - assert_eq!( - decode_qm_intraday_doc(&forward).unwrap(), - decode_qm_intraday_doc(&reversed).unwrap() - ); -} - -#[test] -fn missing_field_precedence_follows_declared_order_and_semantic_error_beats_missing() { - // close and sharevolume both missing -> close (earlier in declared order) is reported. - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), "SHOP:CA"); - doc.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_000_000)); - doc.append(cstr!("open"), 10.0_f64); - doc.append(cstr!("high"), 11.0_f64); - doc.append(cstr!("low"), 9.0_f64); - assert_eq!( - decode_qm_intraday_doc(&doc).unwrap_err(), - BsonQmIntradayError::MissingField { field: FIELD_CLOSE } - ); - - // A semantic error on a late field wins over an earlier-ordered missing field. - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_000_000)); - doc.append(cstr!("sharevolume"), -1.0_f64); - let err = decode_qm_intraday_doc(&doc).unwrap_err(); - assert!( - matches!( - err, - BsonQmIntradayError::InvalidNumber { - field: FIELD_SHARE_VOLUME, - .. - } - ), - "got {err:?}" - ); -} - -#[test] -fn invalid_duplicate_after_valid_value_still_rejects_the_document() { - // Valid open followed by an invalid duplicate open: the semantic error must be kept. - let mut doc = make_valid_doc("SHOP:CA", 1_717_767_000_000, 10.0, 11.0, 9.0, 10.5, 100.0); - doc.append(cstr!("open"), 0.0_f64); - let err = decode_qm_intraday_doc(&doc).unwrap_err(); - assert!( - matches!(err, BsonQmIntradayError::InvalidNumber { field: FIELD_OPEN, value } if value == 0.0), - "got {err:?}" - ); -} - -#[test] -fn malformed_utf8_in_qm_search_code_is_corrupt_bson_naming_the_field() { - let doc = make_valid_doc("SHOP:CA", 1_717_767_000_000, 10.0, 11.0, 9.0, 10.5, 100.0); - let mut bytes = doc.as_bytes().to_vec(); - let pos = find_marker(&bytes, b"SHOP:CA"); - bytes[pos + 1] = 0xFF; - match decode_qm_intraday_bytes(&bytes) { - Err(BsonQmIntradayError::CorruptBson { offset: 0, detail }) => { - assert!(detail.contains(FIELD_QM_SEARCH_CODE), "detail={detail}"); - } - other => panic!("expected CorruptBson for invalid UTF-8 key, got {other:?}"), - } -} - -#[test] -fn non_ascii_and_large_integer_values_are_preserved_exactly() { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), "BCE.PR.Ä:CA"); - doc.append(cstr!("timestamp"), DateTime::from_millis(1_735_689_599_999)); - doc.append(cstr!("open"), 1_i32); - doc.append(cstr!("high"), i32::MAX); - doc.append(cstr!("low"), 1_i64); - doc.append(cstr!("close"), 9_007_199_254_740_992_i64); // 2^53, exact in f64 - doc.append(cstr!("sharevolume"), i64::MAX); - - let bar = decode_qm_intraday_doc(&doc).unwrap(); - assert_eq!(bar.qm_search_code, "BCE.PR.Ä:CA"); - assert_eq!(bar.ts, 1_735_689_599_999_000); - assert_eq!(bar.open, 1.0); - assert_eq!(bar.high, f64::from(i32::MAX)); - assert_eq!(bar.low, 1.0); - assert_eq!(bar.close, 9_007_199_254_740_992.0); - assert_eq!(bar.volume, i64::MAX as f64); - assert!(bar.volume.is_finite()); -} - -#[test] -fn display_messages_name_field_and_domain() { - let vol = BsonQmIntradayError::InvalidNumber { - field: FIELD_SHARE_VOLUME, - value: -1.0, - } - .to_string(); - assert!(vol.contains("sharevolume") && vol.contains(">= 0"), "{vol}"); - let price = BsonQmIntradayError::InvalidNumber { - field: FIELD_HIGH, - value: 0.0, - } - .to_string(); - assert!( - price.contains("high") && price.contains("> 0") && !price.contains(">= 0"), - "{price}" - ); - let corrupt = BsonQmIntradayError::CorruptBson { - offset: 77, - detail: "x".into(), - } - .to_string(); - assert!(corrupt.contains("77"), "{corrupt}"); -} - -#[test] -fn buffer_stops_at_unrecoverable_frame_length_counting_it_once_and_keeps_earlier_rows() { - let a = make_valid_doc("A:CA", 1_717_767_000_000, 10.0, 11.0, 9.0, 10.5, 100.0); - let b = make_valid_doc("B:CA", 1_717_767_060_000, 20.0, 21.0, 19.0, 20.5, 200.0); - let c = make_valid_doc("C:CA", 1_717_767_120_000, 30.0, 31.0, 29.0, 30.5, 300.0); - - let mut buf = Vec::new(); - buf.extend_from_slice(a.as_bytes()); - buf.extend_from_slice(b.as_bytes()); - let bad_off = buf.len(); - buf.extend_from_slice(&3_i32.to_le_bytes()); // declared length < 5: no boundary known - buf.extend_from_slice(c.as_bytes()); // must NOT be decoded (cannot resync safely) - - let mut codes = Vec::new(); - let mut errors = Vec::new(); - let stats = decode_qm_intraday_buffer( - &buf, - |bar| codes.push(bar.qm_search_code), - |off, err| errors.push((off, err)), - ); - - assert_eq!(codes, vec!["A:CA", "B:CA"]); - assert_eq!(errors.len(), 1); - assert_eq!(errors[0].0, bad_off); - assert!(matches!( - &errors[0].1, - BsonQmIntradayError::CorruptBson { offset, .. } if *offset == bad_off - )); - assert_eq!(stats.docs_seen, 3); - assert_eq!(stats.rows_decoded, 2); - assert_eq!(stats.rejected_corrupt_document, 1); - assert_eq!(stats.docs_seen, stats.rows_decoded + stats.rejected_total()); -} - -#[test] -fn buffer_rows_borrow_keys_from_the_input_buffer() { - let a = make_valid_doc("A:CA", 1_717_767_000_000, 10.0, 11.0, 9.0, 10.5, 100.0); - let b = make_valid_doc("B:CA", 1_717_767_060_000, 20.0, 21.0, 19.0, 20.5, 200.0); - let mut buf = Vec::new(); - buf.extend_from_slice(a.as_bytes()); - buf.extend_from_slice(b.as_bytes()); - let range = buf.as_ptr_range(); - - let mut ptrs = Vec::new(); - let stats = decode_qm_intraday_buffer( - &buf, - |bar| ptrs.push(bar.qm_search_code.as_ptr()), - |_, err| panic!("unexpected error {err:?}"), - ); - assert_eq!(stats.rows_decoded, 2); - assert_eq!(ptrs.len(), 2); - for p in ptrs { - assert!( - range.contains(&p), - "key pointer {p:?} outside input buffer {range:?}" - ); - } -} - -#[test] -fn single_valid_doc_buffer_with_short_trailing_bytes_decodes_row_then_counts_truncated_tail() { - let a = make_valid_doc("A:CA", 1_717_767_000_000, 10.0, 11.0, 9.0, 10.5, 100.0); - let mut buf = a.as_bytes().to_vec(); - let tail_off = buf.len(); - buf.extend_from_slice(&[0x00, 0x00]); - - let mut rows = 0usize; - let mut errors = Vec::new(); - let stats = decode_qm_intraday_buffer(&buf, |_| rows += 1, |off, err| errors.push((off, err))); - assert_eq!(rows, 1); - assert_eq!(errors.len(), 1); - assert_eq!(errors[0].0, tail_off); - assert!(matches!( - errors[0].1, - BsonQmIntradayError::CorruptBson { .. } - )); - assert_eq!(stats.docs_seen, 2); - assert_eq!(stats.docs_seen, stats.rows_decoded + stats.rejected_total()); -} diff --git a/tools/curate-etl/src/bson_qm_prices.rs b/tools/curate-etl/src/bson_qm_prices.rs deleted file mode 100644 index 10c82ee6..00000000 --- a/tools/curate-etl/src/bson_qm_prices.rs +++ /dev/null @@ -1,458 +0,0 @@ -//! Zero-copy raw BSON decoder for MongoDB `qmPrices` documents (`M1.2ah`). -//! -//! Decodes `&bson::RawDocument` slices in a single forward pass over `iter_elements()` into -//! borrowed [`RawQmPrice`] views without allocating a `String` or `bson::Document` per row. -//! Callers convert borrowed views into [`crate::bars::QmRawVolume`] via a caller-supplied key -//! mapper (such as date-aware `provider_mapping` re-keying into interned `"eod"` keys). -//! -//! # Empirical Field Contract & Cited Sources -//! -//! - `apps/stock/data-ingestion/src/handlers/qm/actions/prices.action.ts:97-109`: writes -//! `...price` (the raw QuoteMedia EOD payload including `date` and `sharevolume`), `symbol`, -//! `exchange`, `qmSearchCode`, and `dateTime: new Date(price.date)` into `qmPrices`, keyed by -//! `['qmSearchCode', 'date']`. -//! - `apps/stock/data-pipeline/src/normalization/bar-spans.ts:19-24`: `qmPrices` uses -//! `qmSearchCode` and `date`. -//! - `apps/stock/data-pipeline/src/security-master/sample-closes.ts:300-303`: documents `qmPrices` -//! copying the provider's `date` string verbatim (`YYYY-MM-DD`, with BSON `Date` stored -//! separately in `dateTime`). -//! - `design/DATA-CONTRACTS.md` §1 (line 14): `qmPrices` (`51.5M` docs) stores genuinely raw -//! `unadjustedopen..unadjustedclose` and `sharevolume` for `eodPrices` volume cross-checking. -//! -//! Accepted BSON field representations: -//! - `qmSearchCode`: BSON UTF-8 `String` (borrowed verbatim — never trimmed; empty or -//! whitespace-only is rejected as [`BsonQmPriceError::EmptyField`]). -//! - `date`: strict 10-byte ASCII `YYYY-MM-DD` BSON `String` validated via -//! [`crate::bson_eod_prices::parse_ymd_strict_days`]; BSON `DateTime` and other types are -//! rejected as [`BsonQmPriceError::WrongType`], and malformed/non-calendar strings as -//! [`BsonQmPriceError::MalformedDate`]. -//! - `sharevolume`: BSON `Double`, `Int32`, or `Int64` decoded to `f64`. Numeric value validity -//! (non-finite / negative) is intentionally left to [`crate::bars::build_bars_1d`] -//! (`qm_invalid_volume_dropped`). Missing, `Null`, or non-numeric types are rejected with -//! counted reasons. -//! - Unknown extra fields (`_id`, `symbol`, `exchange`, `dateTime`, -//! `unadjustedopen..unadjustedclose`, nested objects/arrays, etc.) are skipped without calling -//! `elem.value()`. - -use std::error::Error; -use std::fmt; - -use bson::raw::{cstr, RawBsonRef, RawDocument, RawElement}; -use bson::spec::ElementType; - -use crate::bars::QmRawVolume; -use crate::bson_eod_prices::{ - iter_raw_bson_docs, parse_single_raw_doc, parse_ymd_strict_days, BsonEodPriceError, -}; - -/// MongoDB field name for the QuoteMedia security key (`prices.action.ts:101,108`). -pub const FIELD_QM_SEARCH_CODE: &str = "qmSearchCode"; -/// MongoDB field name for the verbatim `YYYY-MM-DD` session date string (`prices.action.ts:102,108`). -pub const FIELD_DATE: &str = "date"; -/// MongoDB field name for the genuinely raw QuoteMedia share volume (`DATA-CONTRACTS.md` §1). -pub const FIELD_SHARE_VOLUME: &str = "sharevolume"; - -/// Borrowed zero-copy view of a single decoded `qmPrices` BSON document. -/// -/// Borrows `qm_search_code` directly from the underlying `&RawDocument` byte slice. -/// `share_volume` is passed through without domain filtering so downstream [`crate::bars::build_bars_1d`] -/// accounts for negative or non-finite values under `qm_invalid_volume_dropped`. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct RawQmPrice<'a> { - pub qm_search_code: &'a str, - /// Session date as days since `1970-01-01` (UTC Gregorian). - pub session_date: i32, - /// Raw `qmPrices.sharevolume` converted from BSON `Double`, `Int32`, or `Int64`. - pub share_volume: f64, -} - -impl<'a> RawQmPrice<'a> { - /// Converts this borrowed view into a [`QmRawVolume`] using a caller-supplied key mapper. - #[inline] - pub fn into_qm_raw_volume(self, map_key: F) -> QmRawVolume - where - F: FnOnce(&'a str, i32) -> K, - { - QmRawVolume { - key: map_key(self.qm_search_code, self.session_date), - session_date: self.session_date, - share_volume: self.share_volume, - } - } - - /// Fallible conversion into [`QmRawVolume`] using a caller-supplied key resolver. - #[inline] - pub fn try_into_qm_raw_volume(self, map_key: F) -> Option> - where - F: FnOnce(&'a str, i32) -> Option, - { - let key = map_key(self.qm_search_code, self.session_date)?; - Some(QmRawVolume { - key, - session_date: self.session_date, - share_volume: self.share_volume, - }) - } -} - -/// Typed errors returned while decoding raw `qmPrices` BSON documents or length-prefixed buffers. -/// -/// Every field-level error names the offending BSON field in both its structure and `Display` -/// output; no input path panics. -#[derive(Debug, Clone, PartialEq)] -pub enum BsonQmPriceError { - /// A required field was absent from the document. - MissingField { field: &'static str }, - /// A required string field was empty or contained only whitespace. - EmptyField { field: &'static str }, - /// A required field had an unexpected BSON element type. - WrongType { - field: &'static str, - actual: ElementType, - }, - /// `date` string was not a valid strict `YYYY-MM-DD` Gregorian calendar date. - MalformedDate { field: &'static str }, - /// Buffer ended before a complete 4-byte length prefix or declared document body. - TruncatedDocument { - offset: usize, - remaining: usize, - declared_len: Option, - }, - /// Declared 4-byte little-endian BSON document length was `< 5` (or did not match a single - /// document slice). - CorruptDocumentLength { offset: usize, declared_len: i32 }, - /// Underlying BSON framing or element bytes were malformed. - CorruptBson { offset: usize, detail: String }, -} - -impl fmt::Display for BsonQmPriceError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::MissingField { field } => { - write!(f, "qmPrices BSON missing required field '{field}'") - } - Self::EmptyField { field } => { - write!( - f, - "qmPrices BSON field '{field}' must not be empty or blank" - ) - } - Self::WrongType { field, actual } => { - write!( - f, - "qmPrices BSON field '{field}' has unexpected BSON type {actual:?}" - ) - } - Self::MalformedDate { field } => { - write!( - f, - "qmPrices BSON field '{field}' is not a valid strict YYYY-MM-DD date" - ) - } - Self::TruncatedDocument { - offset, - remaining, - declared_len, - } => match declared_len { - Some(len) => write!( - f, - "truncated BSON document at byte offset {offset}: declared length {len} exceeds remaining {remaining} bytes" - ), - None => write!( - f, - "truncated BSON document header at byte offset {offset}: only {remaining} bytes remaining" - ), - }, - Self::CorruptDocumentLength { - offset, - declared_len, - } => write!( - f, - "corrupt BSON document length {declared_len} at byte offset {offset}" - ), - Self::CorruptBson { offset, detail } => { - write!(f, "corrupt BSON bytes at byte offset {offset}: {detail}") - } - } - } -} - -impl Error for BsonQmPriceError {} - -#[inline] -fn map_framing_error(err: BsonEodPriceError) -> BsonQmPriceError { - match err { - BsonEodPriceError::TruncatedDocument { - offset, - remaining, - declared_len, - } => BsonQmPriceError::TruncatedDocument { - offset, - remaining, - declared_len, - }, - BsonEodPriceError::CorruptDocumentLength { - offset, - declared_len, - } => BsonQmPriceError::CorruptDocumentLength { - offset, - declared_len, - }, - BsonEodPriceError::CorruptBson { offset, detail } => { - BsonQmPriceError::CorruptBson { offset, detail } - } - BsonEodPriceError::MissingField { field } => BsonQmPriceError::MissingField { field }, - BsonEodPriceError::EmptyField { field } => BsonQmPriceError::EmptyField { field }, - BsonEodPriceError::WrongType { field, actual } => { - BsonQmPriceError::WrongType { field, actual } - } - BsonEodPriceError::MalformedDate { field } => BsonQmPriceError::MalformedDate { field }, - BsonEodPriceError::InvalidNumber { field, .. } => BsonQmPriceError::CorruptBson { - offset: 0, - detail: format!("unexpected numeric framing error on field '{field}'"), - }, - } -} - -/// Per-batch decode and rejection accounting for [`decode_qm_price_buffer`]. -/// -/// Conservation invariant: `decoded + rejected_total() == docs_in`. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct BsonQmPriceDecodeStats { - pub docs_in: usize, - pub decoded: usize, - pub rejected_missing_field: usize, - pub rejected_empty_field: usize, - pub rejected_wrong_type: usize, - pub rejected_malformed_date: usize, - pub rejected_corrupt_document: usize, -} - -impl BsonQmPriceDecodeStats { - /// Total number of rejected documents across all error categories. - #[inline] - pub fn rejected_total(&self) -> usize { - self.rejected_missing_field - + self.rejected_empty_field - + self.rejected_wrong_type - + self.rejected_malformed_date - + self.rejected_corrupt_document - } - - /// Increments the rejection counter corresponding to `err`. - #[inline] - pub fn record_error(&mut self, err: &BsonQmPriceError) { - match err { - BsonQmPriceError::MissingField { .. } => self.rejected_missing_field += 1, - BsonQmPriceError::EmptyField { .. } => self.rejected_empty_field += 1, - BsonQmPriceError::WrongType { .. } => self.rejected_wrong_type += 1, - BsonQmPriceError::MalformedDate { .. } => self.rejected_malformed_date += 1, - BsonQmPriceError::TruncatedDocument { .. } - | BsonQmPriceError::CorruptDocumentLength { .. } - | BsonQmPriceError::CorruptBson { .. } => self.rejected_corrupt_document += 1, - } - } - - /// Accumulates counters from another batch into `self`. - #[inline] - pub fn merge(&mut self, other: &Self) { - self.docs_in += other.docs_in; - self.decoded += other.decoded; - self.rejected_missing_field += other.rejected_missing_field; - self.rejected_empty_field += other.rejected_empty_field; - self.rejected_wrong_type += other.rejected_wrong_type; - self.rejected_malformed_date += other.rejected_malformed_date; - self.rejected_corrupt_document += other.rejected_corrupt_document; - } -} - -impl std::ops::AddAssign for BsonQmPriceDecodeStats { - #[inline] - fn add_assign(&mut self, rhs: Self) { - self.merge(&rhs); - } -} - -#[inline] -fn decode_element_value<'a>( - field: &'static str, - elem: RawElement<'a>, - offset: usize, -) -> Result, BsonQmPriceError> { - elem.value().map_err(|err| BsonQmPriceError::CorruptBson { - offset, - detail: format!("field '{field}': {err}"), - }) -} - -#[inline] -fn decode_numeric_passthrough( - field: &'static str, - val: RawBsonRef<'_>, -) -> Result { - match val { - RawBsonRef::Double(v) => Ok(v), - RawBsonRef::Int32(v) => Ok(f64::from(v)), - RawBsonRef::Int64(v) => Ok(v as f64), - other => Err(BsonQmPriceError::WrongType { - field, - actual: other.element_type(), - }), - } -} - -fn decode_qm_price_doc_at<'a>( - doc: &'a RawDocument, - offset: usize, -) -> Result, BsonQmPriceError> { - let mut qm_search_code: Option<&'a str> = None; - let mut session_date: Option = None; - let mut share_volume: Option = None; - let mut first_semantic_err: Option = None; - - for elem_res in doc.iter_elements() { - let elem = elem_res.map_err(|err| BsonQmPriceError::CorruptBson { - offset, - detail: err.to_string(), - })?; - let key = elem.key(); - - if key == cstr!("qmSearchCode") { - match decode_element_value(FIELD_QM_SEARCH_CODE, elem, offset)? { - RawBsonRef::String(s) => { - if s.trim().is_empty() { - if first_semantic_err.is_none() { - first_semantic_err = Some(BsonQmPriceError::EmptyField { - field: FIELD_QM_SEARCH_CODE, - }); - } - } else { - qm_search_code = Some(s); - } - } - other => { - if first_semantic_err.is_none() { - first_semantic_err = Some(BsonQmPriceError::WrongType { - field: FIELD_QM_SEARCH_CODE, - actual: other.element_type(), - }); - } - } - } - } else if key == cstr!("date") { - match decode_element_value(FIELD_DATE, elem, offset)? { - RawBsonRef::String(s) => match parse_ymd_strict_days(s) { - Some(d) => session_date = Some(d), - None => { - if first_semantic_err.is_none() { - first_semantic_err = - Some(BsonQmPriceError::MalformedDate { field: FIELD_DATE }); - } - } - }, - other => { - if first_semantic_err.is_none() { - first_semantic_err = Some(BsonQmPriceError::WrongType { - field: FIELD_DATE, - actual: other.element_type(), - }); - } - } - } - } else if key == cstr!("sharevolume") { - let val = decode_element_value(FIELD_SHARE_VOLUME, elem, offset)?; - match decode_numeric_passthrough(FIELD_SHARE_VOLUME, val) { - Ok(v) => share_volume = Some(v), - Err(err) => { - if first_semantic_err.is_none() { - first_semantic_err = Some(err); - } - } - } - } - // Unknown extra fields (`_id`, `dateTime`, `unadjustedopen..unadjustedclose`, etc.) - // are skipped without calling `elem.value()`. - } - - if let Some(err) = first_semantic_err { - return Err(err); - } - - let Some(qm_search_code) = qm_search_code else { - return Err(BsonQmPriceError::MissingField { - field: FIELD_QM_SEARCH_CODE, - }); - }; - let Some(session_date) = session_date else { - return Err(BsonQmPriceError::MissingField { field: FIELD_DATE }); - }; - let Some(share_volume) = share_volume else { - return Err(BsonQmPriceError::MissingField { - field: FIELD_SHARE_VOLUME, - }); - }; - - Ok(RawQmPrice { - qm_search_code, - session_date, - share_volume, - }) -} - -/// Decodes a single `&RawDocument` representing a `qmPrices` MongoDB document in one forward pass -/// without allocating a `String` or owned `bson::Document`. -#[inline] -pub fn decode_qm_price_doc<'a>(doc: &'a RawDocument) -> Result, BsonQmPriceError> { - decode_qm_price_doc_at(doc, 0) -} - -/// Decodes a single length-prefixed raw BSON document byte slice into a borrowed [`RawQmPrice`]. -pub fn decode_qm_price_bytes<'a>(bytes: &'a [u8]) -> Result, BsonQmPriceError> { - let doc = parse_single_raw_doc(bytes).map_err(map_framing_error)?; - decode_qm_price_doc_at(doc, 0) -} - -/// Streams a concatenated length-prefixed BSON buffer through [`decode_qm_price_doc`], invoking -/// `on_price` for every valid document and `on_error(byte_offset, err)` for every rejected -/// document without aborting the stream on per-document errors. -/// -/// Always maintains `stats.decoded + stats.rejected_total() == stats.docs_in`. -pub fn decode_qm_price_buffer<'a, F, E>( - buf: &'a [u8], - mut on_price: F, - mut on_error: E, -) -> BsonQmPriceDecodeStats -where - F: FnMut(RawQmPrice<'a>), - E: FnMut(usize, BsonQmPriceError), -{ - let mut stats = BsonQmPriceDecodeStats::default(); - let mut iter = iter_raw_bson_docs(buf); - - while let Some(item) = iter.next_with_offset() { - stats.docs_in += 1; - match item { - Ok((doc_offset, doc)) => match decode_qm_price_doc_at(doc, doc_offset) { - Ok(price) => { - stats.decoded += 1; - on_price(price); - } - Err(err) => { - stats.record_error(&err); - on_error(doc_offset, err); - } - }, - Err((doc_offset, err)) => { - let mapped = map_framing_error(err); - stats.record_error(&mapped); - on_error(doc_offset, mapped); - } - } - } - - stats -} - -#[cfg(test)] -#[path = "bson_qm_prices_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/bson_qm_prices_tests.rs b/tools/curate-etl/src/bson_qm_prices_tests.rs deleted file mode 100644 index f94f4442..00000000 --- a/tools/curate-etl/src/bson_qm_prices_tests.rs +++ /dev/null @@ -1,413 +0,0 @@ -use bson::oid::ObjectId; -use bson::raw::{cstr, RawArrayBuf, RawBsonRef, RawDocumentBuf}; -use bson::spec::ElementType; -use bson::DateTime; - -use super::*; -use crate::bson_eod_prices::MILLIS_PER_DAY; -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 make_qm_price_doc_f64(code: &str, date: &str, share_volume: f64) -> RawDocumentBuf { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), code); - doc.append(cstr!("date"), date); - doc.append(cstr!("sharevolume"), share_volume); - doc -} - -#[test] -fn decodes_realistic_qm_price_doc_and_ignores_extra_fields() { - let mut nested = RawDocumentBuf::new(); - nested.append(cstr!("provider"), "quotemedia"); - nested.append(cstr!("version"), 2_i32); - - let mut tags = RawArrayBuf::new(); - tags.push("eod"); - tags.push("raw"); - - let mut doc = RawDocumentBuf::new(); - doc.append( - cstr!("_id"), - ObjectId::from_bytes([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]), - ); - doc.append(cstr!("symbol"), "NVDA"); - doc.append(cstr!("exchange"), "NASDAQ"); - doc.append(cstr!("qmSearchCode"), "NVDA"); - doc.append(cstr!("date"), "2024-06-07"); - doc.append( - cstr!("dateTime"), - DateTime::from_millis(i64::from(day(2024, 6, 7)) * MILLIS_PER_DAY), - ); - doc.append(cstr!("unadjustedopen"), 1197.7_f64); - doc.append(cstr!("unadjustedhigh"), 1216.92_f64); - doc.append(cstr!("unadjustedlow"), 1180.22_f64); - doc.append(cstr!("unadjustedclose"), 1208.88_f64); - doc.append(cstr!("sharevolume"), 41_239_000.0_f64); - doc.append(cstr!("meta"), RawBsonRef::Document(nested.as_ref())); - doc.append(cstr!("tags"), RawBsonRef::Array(tags.as_ref())); - - let decoded = decode_qm_price_doc(&doc).unwrap(); - assert_eq!(decoded.qm_search_code, "NVDA"); - assert_eq!(decoded.session_date, day(2024, 6, 7)); - assert_eq!(decoded.share_volume.to_bits(), 41_239_000.0_f64.to_bits()); - assert_eq!(decode_qm_price_bytes(doc.as_bytes()).unwrap(), decoded); - - let mapped = decoded.into_qm_raw_volume(|code, _d| format!("{code}.US")); - assert_eq!(mapped.key, "NVDA.US"); - assert_eq!(mapped.session_date, day(2024, 6, 7)); - assert_eq!(mapped.share_volume.to_bits(), 41_239_000.0_f64.to_bits()); - - let maybe_mapped = decoded.try_into_qm_raw_volume(|code, _d| Some(code.to_owned())); - assert_eq!( - maybe_mapped, - Some(QmRawVolume { - key: "NVDA".to_string(), - session_date: day(2024, 6, 7), - share_volume: 41_239_000.0, - }) - ); - assert_eq!( - decoded.try_into_qm_raw_volume::(|_, _| None), - None - ); -} - -#[test] -fn accepts_sharevolume_as_double_int32_and_int64() { - let mut doc_f64 = RawDocumentBuf::new(); - doc_f64.append(cstr!("qmSearchCode"), "AAPL"); - doc_f64.append(cstr!("date"), "2024-06-07"); - doc_f64.append(cstr!("sharevolume"), 12_345_678.5_f64); - - let mut doc_i32 = RawDocumentBuf::new(); - doc_i32.append(cstr!("qmSearchCode"), "RY:CA"); - doc_i32.append(cstr!("date"), "2024-06-07"); - doc_i32.append(cstr!("sharevolume"), 500_000_i32); - - let mut doc_i64 = RawDocumentBuf::new(); - doc_i64.append(cstr!("qmSearchCode"), "SHOP:CA"); - doc_i64.append(cstr!("date"), "2024-06-07"); - doc_i64.append(cstr!("sharevolume"), 3_000_000_000_i64); - - let p_f64 = decode_qm_price_doc(&doc_f64).unwrap(); - assert_eq!(p_f64.share_volume.to_bits(), 12_345_678.5_f64.to_bits()); - - let p_i32 = decode_qm_price_doc(&doc_i32).unwrap(); - assert_eq!(p_i32.share_volume.to_bits(), 500_000.0_f64.to_bits()); - - let p_i64 = decode_qm_price_doc(&doc_i64).unwrap(); - assert_eq!(p_i64.share_volume.to_bits(), 3_000_000_000.0_f64.to_bits()); -} - -#[test] -fn passes_through_negative_nan_inf_and_neg_zero_sharevolume_to_builder() { - let cases = [ - (-100.0_f64, true), - (f64::NAN, false), - (f64::INFINITY, true), - (f64::NEG_INFINITY, true), - (-0.0_f64, true), - ]; - - for (val, compare_bits) in cases { - let doc = make_qm_price_doc_f64("NVDA", "2024-06-07", val); - let decoded = decode_qm_price_doc(&doc).unwrap(); - if compare_bits { - assert_eq!(decoded.share_volume.to_bits(), val.to_bits()); - } else { - assert!(decoded.share_volume.is_nan()); - } - } - - let mut neg_i32 = RawDocumentBuf::new(); - neg_i32.append(cstr!("qmSearchCode"), "NVDA"); - neg_i32.append(cstr!("date"), "2024-06-07"); - neg_i32.append(cstr!("sharevolume"), -42_i32); - assert_eq!(decode_qm_price_doc(&neg_i32).unwrap().share_volume, -42.0); -} - -#[test] -fn preserves_qm_search_code_verbatim_including_leading_and_trailing_spaces() { - let doc = make_qm_price_doc_f64(" NVDA ", "2024-06-07", 1_000.0); - let decoded = decode_qm_price_doc(&doc).unwrap(); - assert_eq!(decoded.qm_search_code, " NVDA "); -} - -#[test] -fn rejects_missing_null_empty_and_wrong_typed_fields() { - // Missing qmSearchCode - let mut missing_code = RawDocumentBuf::new(); - missing_code.append(cstr!("date"), "2024-06-07"); - missing_code.append(cstr!("sharevolume"), 100.0_f64); - assert_eq!( - decode_qm_price_doc(&missing_code), - Err(BsonQmPriceError::MissingField { - field: FIELD_QM_SEARCH_CODE, - }) - ); - - // Missing date - let mut missing_date = RawDocumentBuf::new(); - missing_date.append(cstr!("qmSearchCode"), "NVDA"); - missing_date.append(cstr!("sharevolume"), 100.0_f64); - assert_eq!( - decode_qm_price_doc(&missing_date), - Err(BsonQmPriceError::MissingField { field: FIELD_DATE }) - ); - - // Missing sharevolume - let mut missing_vol = RawDocumentBuf::new(); - missing_vol.append(cstr!("qmSearchCode"), "NVDA"); - missing_vol.append(cstr!("date"), "2024-06-07"); - assert_eq!( - decode_qm_price_doc(&missing_vol), - Err(BsonQmPriceError::MissingField { - field: FIELD_SHARE_VOLUME, - }) - ); - - // Empty / whitespace-only qmSearchCode - for blank in ["", " ", "\t\n"] { - let doc = make_qm_price_doc_f64(blank, "2024-06-07", 100.0); - assert_eq!( - decode_qm_price_doc(&doc), - Err(BsonQmPriceError::EmptyField { - field: FIELD_QM_SEARCH_CODE, - }) - ); - } - - // Null / wrong-typed qmSearchCode - let mut null_code = RawDocumentBuf::new(); - null_code.append(cstr!("qmSearchCode"), RawBsonRef::Null); - null_code.append(cstr!("date"), "2024-06-07"); - null_code.append(cstr!("sharevolume"), 100.0_f64); - assert_eq!( - decode_qm_price_doc(&null_code), - Err(BsonQmPriceError::WrongType { - field: FIELD_QM_SEARCH_CODE, - actual: ElementType::Null, - }) - ); - - let mut int_code = RawDocumentBuf::new(); - int_code.append(cstr!("qmSearchCode"), 42_i32); - int_code.append(cstr!("date"), "2024-06-07"); - int_code.append(cstr!("sharevolume"), 100.0_f64); - assert_eq!( - decode_qm_price_doc(&int_code), - Err(BsonQmPriceError::WrongType { - field: FIELD_QM_SEARCH_CODE, - actual: ElementType::Int32, - }) - ); - - // Null / BSON DateTime / int date - let mut null_date = RawDocumentBuf::new(); - null_date.append(cstr!("qmSearchCode"), "NVDA"); - null_date.append(cstr!("date"), RawBsonRef::Null); - null_date.append(cstr!("sharevolume"), 100.0_f64); - assert_eq!( - decode_qm_price_doc(&null_date), - Err(BsonQmPriceError::WrongType { - field: FIELD_DATE, - actual: ElementType::Null, - }) - ); - - let mut dt_date = RawDocumentBuf::new(); - dt_date.append(cstr!("qmSearchCode"), "NVDA"); - dt_date.append( - cstr!("date"), - DateTime::from_millis(i64::from(day(2024, 6, 7)) * MILLIS_PER_DAY), - ); - dt_date.append(cstr!("sharevolume"), 100.0_f64); - assert_eq!( - decode_qm_price_doc(&dt_date), - Err(BsonQmPriceError::WrongType { - field: FIELD_DATE, - actual: ElementType::DateTime, - }) - ); - - // Null / string / bool sharevolume - let mut null_vol = RawDocumentBuf::new(); - null_vol.append(cstr!("qmSearchCode"), "NVDA"); - null_vol.append(cstr!("date"), "2024-06-07"); - null_vol.append(cstr!("sharevolume"), RawBsonRef::Null); - assert_eq!( - decode_qm_price_doc(&null_vol), - Err(BsonQmPriceError::WrongType { - field: FIELD_SHARE_VOLUME, - actual: ElementType::Null, - }) - ); - - let mut str_vol = RawDocumentBuf::new(); - str_vol.append(cstr!("qmSearchCode"), "NVDA"); - str_vol.append(cstr!("date"), "2024-06-07"); - str_vol.append(cstr!("sharevolume"), "1000"); - assert_eq!( - decode_qm_price_doc(&str_vol), - Err(BsonQmPriceError::WrongType { - field: FIELD_SHARE_VOLUME, - actual: ElementType::String, - }) - ); - - let mut bool_vol = RawDocumentBuf::new(); - bool_vol.append(cstr!("qmSearchCode"), "NVDA"); - bool_vol.append(cstr!("date"), "2024-06-07"); - bool_vol.append(cstr!("sharevolume"), true); - assert_eq!( - decode_qm_price_doc(&bool_vol), - Err(BsonQmPriceError::WrongType { - field: FIELD_SHARE_VOLUME, - actual: ElementType::Boolean, - }) - ); -} - -#[test] -fn rejects_malformed_and_non_calendar_date_strings() { - let bad_dates = [ - "", - "2023-02-29", - "2024-04-31", - "2024-00-10", - "2024-13-01", - "2024/06/07", - " 2024-06-07", - "2024-06-07 ", - "2024-06-07T00:00:00Z", - "24-06-07", - ]; - for bad in bad_dates { - let doc = make_qm_price_doc_f64("NVDA", bad, 100.0); - assert_eq!( - decode_qm_price_doc(&doc), - Err(BsonQmPriceError::MalformedDate { field: FIELD_DATE }), - "expected MalformedDate for '{bad}'" - ); - } - - // Leap day 2024-02-29 is valid. - let leap = make_qm_price_doc_f64("NVDA", "2024-02-29", 100.0); - assert_eq!( - decode_qm_price_doc(&leap).unwrap().session_date, - day(2024, 2, 29) - ); -} - -#[test] -fn corrupt_and_truncated_buffers_never_panic_and_preserve_accounting() { - assert!(matches!( - decode_qm_price_bytes(&[1, 2]), - Err(BsonQmPriceError::TruncatedDocument { offset: 0, .. }) - )); - assert!(matches!( - decode_qm_price_bytes(&4_i32.to_le_bytes()), - Err(BsonQmPriceError::CorruptDocumentLength { - offset: 0, - declared_len: 4 - }) - )); - - // Mixed buffer: 3 valid (Double, Int32, Int64), 1 missing field, 1 empty field, - // 1 wrong type, 1 malformed date, 1 trailing truncated doc. - let mut buf = Vec::new(); - buf.extend_from_slice(make_qm_price_doc_f64("NVDA", "2024-06-07", 41_239_000.0).as_bytes()); - - let mut d_i32 = RawDocumentBuf::new(); - d_i32.append(cstr!("qmSearchCode"), "RY:CA"); - d_i32.append(cstr!("date"), "2024-06-07"); - d_i32.append(cstr!("sharevolume"), 2_500_000_i32); - buf.extend_from_slice(d_i32.as_bytes()); - - let mut d_i64 = RawDocumentBuf::new(); - d_i64.append(cstr!("qmSearchCode"), "AAPL"); - d_i64.append(cstr!("date"), "2024-06-07"); - d_i64.append(cstr!("sharevolume"), 50_000_000_i64); - buf.extend_from_slice(d_i64.as_bytes()); - - let mut missing = RawDocumentBuf::new(); - missing.append(cstr!("qmSearchCode"), "MSFT"); - missing.append(cstr!("date"), "2024-06-07"); - buf.extend_from_slice(missing.as_bytes()); - - buf.extend_from_slice(make_qm_price_doc_f64(" ", "2024-06-07", 10.0).as_bytes()); - - let mut wrong_type = RawDocumentBuf::new(); - wrong_type.append(cstr!("qmSearchCode"), "AMZN"); - wrong_type.append(cstr!("date"), "2024-06-07"); - wrong_type.append(cstr!("sharevolume"), "not-a-number"); - buf.extend_from_slice(wrong_type.as_bytes()); - - buf.extend_from_slice(make_qm_price_doc_f64("GOOG", "2023-02-29", 10.0).as_bytes()); - - let truncated_offset = buf.len(); - buf.extend_from_slice(&50_i32.to_le_bytes()); - buf.extend_from_slice(&[0x02, b'a', 0x00]); - - let mut decoded_rows: Vec<(String, i32, f64)> = Vec::new(); - let mut errors: Vec<(usize, BsonQmPriceError)> = Vec::new(); - let stats = decode_qm_price_buffer( - &buf, - |p| decoded_rows.push((p.qm_search_code.to_owned(), p.session_date, p.share_volume)), - |off, err| errors.push((off, err)), - ); - - assert_eq!(stats.docs_in, 8); - assert_eq!(stats.decoded, 3); - assert_eq!(stats.rejected_missing_field, 1); - assert_eq!(stats.rejected_empty_field, 1); - assert_eq!(stats.rejected_wrong_type, 1); - assert_eq!(stats.rejected_malformed_date, 1); - assert_eq!(stats.rejected_corrupt_document, 1); - assert_eq!(stats.rejected_total(), 5); - assert_eq!(stats.docs_in, stats.decoded + stats.rejected_total()); - assert_eq!(decoded_rows.len(), 3); - assert_eq!(errors.len(), 5); - assert_eq!(errors.last().unwrap().0, truncated_offset); - assert!(matches!( - errors.last().unwrap().1, - BsonQmPriceError::TruncatedDocument { .. } - )); - - // Verify merge / AddAssign. - let mut merged = BsonQmPriceDecodeStats::default(); - merged += stats; - merged += stats; - assert_eq!(merged.docs_in, 16); - assert_eq!(merged.decoded, 6); - assert_eq!(merged.rejected_total(), 10); - assert_eq!(merged.docs_in, merged.decoded + merged.rejected_total()); -} - -#[test] -fn corrupt_bson_later_in_doc_surfaces_before_semantic_error() { - // Build a doc with a semantic error (wrong-typed sharevolume) followed by corrupt trailing bytes. - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), "NVDA"); - doc.append(cstr!("date"), "2024-06-07"); - doc.append(cstr!("sharevolume"), "bad-type"); - doc.append(cstr!("extra"), "hello"); - let mut bytes = doc.into_bytes(); - // Corrupt the type byte of "extra" (change string element type 0x02 to invalid 0x7E) - // Locate "extra\0" in bytes; the type byte is right before it. - let pos = bytes - .windows(6) - .position(|w| w == b"extra\0") - .expect("extra key"); - bytes[pos - 1] = 0x7E; - - let err = decode_qm_price_bytes(&bytes).unwrap_err(); - assert!( - matches!(err, BsonQmPriceError::CorruptBson { offset: 0, .. }), - "expected CorruptBson, got {err:?}" - ); -} diff --git a/tools/curate-etl/src/bson_stream.rs b/tools/curate-etl/src/bson_stream.rs deleted file mode 100644 index 564a70ae..00000000 --- a/tools/curate-etl/src/bson_stream.rs +++ /dev/null @@ -1,1544 +0,0 @@ -//! Bounded-memory streaming reader for concatenated raw BSON (`M1.2y`). -//! -//! Reads length-prefixed raw BSON documents from any [`std::io::Read`] source (files, stdin pipes, -//! or future cursor adapters) into a single reused byte buffer with a fixed memory ceiling, -//! framing only complete documents into [`RawBsonChunk`] slices that can be passed directly to the -//! existing zero-copy decoders (`decode_eod_price_buffer`, `decode_qm_split_buffer`, -//! `decode_qm_dividend_buffer`). -//! -//! # Callback Lifetime Bound (`for<'a>`) -//! -//! Because [`RawBsonChunkReader`] reuses one internal byte buffer across chunks, borrowed zero-copy -//! document views ([`RawEodDailyBar<'a>`], [`RawQmSplit<'a>`], [`RawQmDividend<'a>`]) only remain -//! valid for the duration of the chunk in which they were decoded. The streaming decode helpers -//! ([`decode_eod_price_stream`], [`decode_qm_split_stream`], [`decode_qm_dividend_stream`], and -//! their `*_chunks` counterparts) therefore require higher-ranked callbacks -//! (`F: for<'a> FnMut(RawEodDailyBar<'a>)`, etc.) so closures cannot escape borrowed slices past a -//! chunk boundary. Callers should map or intern borrowed keys (e.g. via -//! `ProviderMappingTable::resolve`) or copy only the retained fields inside the callback. - -use std::error::Error; -use std::fmt; -use std::io; - -use crate::bson_ceo_posts::{ - decode_ceo_posts_buffer, BsonCeoPostsDecodeStats, BsonCeoPostsError, CeoPostsFieldNames, - CeoPostsTimestampUnit, -}; -use crate::bson_ceo_shorts::{ - decode_ceo_shorts_buffer, BsonCeoShortsDecodeStats, BsonCeoShortsError, CeoShortsFieldNames, -}; -use crate::bson_eod_intraday::{ - decode_eod_intraday_buffer, BsonEodIntradayDecodeStats, BsonEodIntradayError, - RawEodIntradayBar, -}; -use crate::bson_eod_prices::{ - decode_eod_price_buffer, BsonEodDecodeStats, BsonEodPriceError, RawEodDailyBar, -}; -use crate::bson_qm_actions::{ - decode_qm_dividend_buffer, decode_qm_split_buffer, BsonQmActionDecodeStats, BsonQmActionError, - RawQmDividend, RawQmSplit, -}; -use crate::bson_qm_events::{ - decode_qm_earning_buffer, decode_qm_filing_buffer, BsonQmEarningsDecodeStats, - BsonQmEventsError, BsonQmFilingsDecodeStats, QmEarningsFieldNames, QmFilingsFieldNames, - RawQmEarning, RawQmFiling, -}; -use crate::bson_qm_financials::{ - decode_qm_financials_buffer, BsonQmFinancialsDecodeStats, BsonQmFinancialsError, - QmFinancialsFieldNames, QmFinancialsFiscalPeriod, -}; -use crate::bson_qm_intraday::{ - decode_qm_intraday_buffer, BsonQmIntradayDecodeStats, BsonQmIntradayError, RawQmIntradayBar, -}; -use crate::bson_qm_prices::{ - decode_qm_price_buffer, BsonQmPriceDecodeStats, BsonQmPriceError, RawQmPrice, -}; -use crate::bson_te_data::{ - decode_te_data_buffer, BsonTeDataDecodeStats, BsonTeDataError, TeDataPoint, -}; -use crate::bson_te_market_data::{ - decode_te_market_data_buffer, BsonTeMarketDataDecodeStats, BsonTeMarketDataError, -}; -use crate::fundamentals::FinancialObservation; -use crate::fx::FxDailyBar; -use crate::posts::CeoPost; -use crate::shorts::CeoShortReport; - -/// Default chunk buffer capacity: 8 MiB. -pub const DEFAULT_CHUNK_CAPACITY_BYTES: usize = 8 * 1024 * 1024; -/// Default maximum allowed BSON document size: 16 MiB (MongoDB limit) + 16 KiB headroom. -pub const DEFAULT_MAX_DOC_BYTES: usize = 16 * 1024 * 1024 + 16 * 1024; -/// Minimum valid length-prefixed BSON document size (4-byte length prefix + trailing `0x00`). -pub const MIN_BSON_DOC_BYTES: usize = 5; - -/// Configuration options for [`RawBsonChunkReader`] and the `decode_*_stream` helpers. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct BsonStreamOptions { - /// Initial reusable buffer size in bytes (capped at `max_doc_bytes`). Must be `> 0`. - pub chunk_capacity_bytes: usize, - /// Hard upper bound on any single BSON document's declared byte length. Must be `>= 5`. - pub max_doc_bytes: usize, -} - -impl Default for BsonStreamOptions { - #[inline] - fn default() -> Self { - Self { - chunk_capacity_bytes: DEFAULT_CHUNK_CAPACITY_BYTES, - max_doc_bytes: DEFAULT_MAX_DOC_BYTES, - } - } -} - -impl BsonStreamOptions { - /// Validates option invariants, rejecting `chunk_capacity_bytes == 0` and `max_doc_bytes < 5`. - #[inline] - pub fn validate(&self) -> Result<(), BsonStreamError> { - if self.chunk_capacity_bytes == 0 { - return Err(BsonStreamError::InvalidChunkCapacity); - } - if self.max_doc_bytes < MIN_BSON_DOC_BYTES { - return Err(BsonStreamError::InvalidMaxDocBytes); - } - Ok(()) - } -} - -/// Terminal errors returned by [`RawBsonChunkReader`] and the `decode_*_stream` helpers. -/// -/// Every stream-level framing or I/O error carries the absolute byte `offset` of the offending -/// document in the underlying stream. -#[derive(Debug)] -pub enum BsonStreamError { - /// `BsonStreamOptions::chunk_capacity_bytes` was `0`. - InvalidChunkCapacity, - /// `BsonStreamOptions::max_doc_bytes` was `< 5`. - InvalidMaxDocBytes, - /// Declared 4-byte little-endian BSON document length was `< 5` or `> max_doc_bytes`. - CorruptDocumentLength { - offset: u64, - declared_len: i32, - max_doc_bytes: usize, - }, - /// Stream reached EOF mid-header (`declared_len == None`) or mid-document (`Some(len)`). - TruncatedDocument { - offset: u64, - remaining: usize, - declared_len: Option, - }, - /// Underlying [`std::io::Read`] failed with a non-`Interrupted` error. - Io { offset: u64, source: io::Error }, -} - -impl fmt::Display for BsonStreamError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::InvalidChunkCapacity => { - write!(f, "invalid BSON stream chunk_capacity_bytes: must be > 0") - } - Self::InvalidMaxDocBytes => { - write!( - f, - "invalid BSON stream max_doc_bytes: must be >= {MIN_BSON_DOC_BYTES}" - ) - } - Self::CorruptDocumentLength { - offset, - declared_len, - max_doc_bytes, - } => write!( - f, - "corrupt BSON document length {declared_len} at stream offset {offset} (valid range: {MIN_BSON_DOC_BYTES}..={max_doc_bytes})" - ), - Self::TruncatedDocument { - offset, - remaining, - declared_len, - } => match declared_len { - Some(len) => write!( - f, - "truncated BSON document at stream offset {offset}: declared length {len} exceeds remaining {remaining} bytes" - ), - None => write!( - f, - "truncated BSON document header at stream offset {offset}: only {remaining} bytes remaining" - ), - }, - Self::Io { offset, source } => { - write!( - f, - "I/O error reading BSON stream at offset {offset}: {source}" - ) - } - } - } -} - -impl Error for BsonStreamError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::Io { source, .. } => Some(source), - _ => None, - } - } -} - -/// A borrowed chunk of complete, length-prefixed raw BSON documents from [`RawBsonChunkReader`]. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct RawBsonChunk<'a> { - /// Contiguous bytes containing one or more complete length-prefixed BSON documents. - pub bytes: &'a [u8], - /// Absolute byte offset of `bytes[0]` from the start of the underlying stream. - pub start_offset: u64, -} - -#[derive(Debug, Clone)] -enum StickyError { - CorruptDocumentLength { - offset: u64, - declared_len: i32, - max_doc_bytes: usize, - }, - TruncatedDocument { - offset: u64, - remaining: usize, - declared_len: Option, - }, - Io { - offset: u64, - kind: io::ErrorKind, - message: String, - }, -} - -impl StickyError { - fn to_error(&self) -> BsonStreamError { - match self { - Self::CorruptDocumentLength { - offset, - declared_len, - max_doc_bytes, - } => BsonStreamError::CorruptDocumentLength { - offset: *offset, - declared_len: *declared_len, - max_doc_bytes: *max_doc_bytes, - }, - Self::TruncatedDocument { - offset, - remaining, - declared_len, - } => BsonStreamError::TruncatedDocument { - offset: *offset, - remaining: *remaining, - declared_len: *declared_len, - }, - Self::Io { - offset, - kind, - message, - } => BsonStreamError::Io { - offset: *offset, - source: io::Error::new(*kind, message.clone()), - }, - } - } -} - -#[derive(Debug)] -enum TerminalState { - Active, - Eof, - Failed(StickyError), -} - -#[inline] -fn read_i32_le(bytes: &[u8]) -> i32 { - i32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) -} - -/// Bounded-memory chunked reader for concatenated length-prefixed raw BSON documents. -/// -/// Reuses a single internal byte buffer across all calls to [`Self::next_chunk`], carrying any -/// trailing partial document to the front of the buffer before the next fill. The initial -/// allocation is capped at `min(options.chunk_capacity_bytes, options.max_doc_bytes)`; the buffer -/// grows only when a single document exceeds the current buffer length (or to 4 bytes when -/// `chunk_capacity_bytes < 4`), and never beyond `options.max_doc_bytes`. -pub struct RawBsonChunkReader { - reader: R, - options: BsonStreamOptions, - buf: Vec, - filled: usize, - consumed: usize, - buf_start_offset: u64, - bytes_read: u64, - docs_framed: u64, - eof_reached: bool, - pending_io_err: Option, - terminal: TerminalState, -} - -impl RawBsonChunkReader { - /// Creates a new chunk reader with [`BsonStreamOptions::default`]. - pub fn new(reader: R) -> Self { - let options = BsonStreamOptions::default(); - let initial_cap = options.chunk_capacity_bytes.min(options.max_doc_bytes); - Self { - reader, - options, - buf: vec![0u8; initial_cap], - filled: 0, - consumed: 0, - buf_start_offset: 0, - bytes_read: 0, - docs_framed: 0, - eof_reached: false, - pending_io_err: None, - terminal: TerminalState::Active, - } - } - - /// Creates a new chunk reader with explicit [`BsonStreamOptions`], validating them up front. - pub fn with_options(reader: R, options: BsonStreamOptions) -> Result { - options.validate()?; - let initial_cap = options.chunk_capacity_bytes.min(options.max_doc_bytes); - Ok(Self { - reader, - options, - buf: vec![0u8; initial_cap], - filled: 0, - consumed: 0, - buf_start_offset: 0, - bytes_read: 0, - docs_framed: 0, - eof_reached: false, - pending_io_err: None, - terminal: TerminalState::Active, - }) - } - - /// Returns the configured stream options. - #[inline] - pub fn options(&self) -> BsonStreamOptions { - self.options - } - - /// Returns the current allocated capacity of the reusable internal buffer in bytes. - #[inline] - pub fn buffer_capacity(&self) -> usize { - self.buf.capacity() - } - - /// Returns the total number of bytes read from the underlying reader so far. - #[inline] - pub fn bytes_read(&self) -> u64 { - self.bytes_read - } - - /// Returns the total number of complete length-prefixed documents framed and yielded so far. - #[inline] - pub fn docs_framed(&self) -> u64 { - self.docs_framed - } - - /// Consumes the chunk reader, returning the underlying [`std::io::Read`] source. - #[inline] - pub fn into_inner(self) -> R { - self.reader - } - - /// Grows `self.buf` to exactly `target_len` without doubling past `max_doc_bytes`. - fn grow_buf_exact(&mut self, target_len: usize) { - debug_assert!(target_len <= self.options.max_doc_bytes); - if target_len > self.buf.len() { - if target_len > self.buf.capacity() { - self.buf.reserve_exact(target_len - self.buf.len()); - } - self.buf.resize(target_len, 0); - } - } - - /// Reads and frames the next chunk of complete length-prefixed BSON documents. - /// - /// Returns `Ok(None)` at clean EOF. Any terminal framing or I/O error locks the reader into a - /// failed state so subsequent calls continue returning an error without panicking or looping. - pub fn next_chunk(&mut self) -> Result>, BsonStreamError> { - match &self.terminal { - TerminalState::Active => {} - TerminalState::Eof => return Ok(None), - TerminalState::Failed(err) => return Err(err.to_error()), - } - - // Compact bytes already yielded by the previous chunk. - if self.consumed > 0 { - if self.consumed < self.filled { - self.buf.copy_within(self.consumed..self.filled, 0); - } - self.filled -= self.consumed; - self.buf_start_offset += self.consumed as u64; - self.consumed = 0; - } - - let mut chunk_end = 0usize; - let mut chunk_docs = 0u64; - loop { - // Incrementally frame complete documents as bytes arrive so a corrupt length prefix - // stops the fill loop immediately without issuing further reads. - let mut saw_corrupt_len = false; - while self.filled - chunk_end >= 4 { - let declared_len = read_i32_le(&self.buf[chunk_end..chunk_end + 4]); - if declared_len < MIN_BSON_DOC_BYTES as i32 - || (declared_len as usize) > self.options.max_doc_bytes - { - if chunk_end == 0 { - let err = StickyError::CorruptDocumentLength { - offset: self.buf_start_offset, - declared_len, - max_doc_bytes: self.options.max_doc_bytes, - }; - self.terminal = TerminalState::Failed(err.clone()); - return Err(err.to_error()); - } - // Yield any complete preceding documents first; the next call will compact - // this corrupt header to index 0 and surface `CorruptDocumentLength`. - saw_corrupt_len = true; - break; - } - let doc_len = declared_len as usize; - if chunk_end == 0 - && doc_len > self.buf.len() - && !self.eof_reached - && self.pending_io_err.is_none() - { - self.grow_buf_exact(doc_len); - } - if doc_len > self.filled - chunk_end { - break; - } - chunk_end += doc_len; - chunk_docs += 1; - } - - if saw_corrupt_len || self.eof_reached || self.pending_io_err.is_some() { - break; - } - - if self.filled == self.buf.len() { - if self.filled < 4 { - // `chunk_capacity_bytes` was in `1..=3`; grow to 4 bytes (always <= max_doc_bytes). - self.grow_buf_exact(4); - } else { - // Buffer is full and the leading document fit in `self.buf.len()`, so at least - // one complete document is ready to yield. - break; - } - } - - match self.reader.read(&mut self.buf[self.filled..]) { - Ok(0) => { - self.eof_reached = true; - break; - } - Ok(n) => { - self.filled += n; - self.bytes_read += n as u64; - } - Err(err) if err.kind() == io::ErrorKind::Interrupted => continue, - Err(err) => { - self.pending_io_err = Some(err); - break; - } - } - } - - if chunk_end > 0 { - self.consumed = chunk_end; - self.docs_framed += chunk_docs; - return Ok(Some(RawBsonChunk { - bytes: &self.buf[..chunk_end], - start_offset: self.buf_start_offset, - })); - } - - // No complete document could be framed; surface pending I/O error, clean EOF, or truncation. - if let Some(source) = self.pending_io_err.take() { - let offset = self.buf_start_offset; - self.terminal = TerminalState::Failed(StickyError::Io { - offset, - kind: source.kind(), - message: source.to_string(), - }); - return Err(BsonStreamError::Io { offset, source }); - } - - if self.filled == 0 { - self.terminal = TerminalState::Eof; - return Ok(None); - } - - let declared_len = if self.filled >= 4 { - Some(read_i32_le(&self.buf[0..4])) - } else { - None - }; - let err = StickyError::TruncatedDocument { - offset: self.buf_start_offset, - remaining: self.filled, - declared_len, - }; - self.terminal = TerminalState::Failed(err.clone()); - Err(err.to_error()) - } -} - -#[inline] -fn rebase_offset(base: u64, local: usize) -> usize { - let abs = base.saturating_add(local as u64); - usize::try_from(abs).unwrap_or(usize::MAX) -} - -#[inline] -fn rebase_eod_error(base: u64, err: BsonEodPriceError) -> BsonEodPriceError { - match err { - BsonEodPriceError::TruncatedDocument { - offset, - remaining, - declared_len, - } => BsonEodPriceError::TruncatedDocument { - offset: rebase_offset(base, offset), - remaining, - declared_len, - }, - BsonEodPriceError::CorruptDocumentLength { - offset, - declared_len, - } => BsonEodPriceError::CorruptDocumentLength { - offset: rebase_offset(base, offset), - declared_len, - }, - BsonEodPriceError::CorruptBson { offset, detail } => BsonEodPriceError::CorruptBson { - offset: rebase_offset(base, offset), - detail, - }, - other => other, - } -} - -#[inline] -fn rebase_qm_error(base: u64, err: BsonQmActionError) -> BsonQmActionError { - match err { - BsonQmActionError::TruncatedDocument { - offset, - remaining, - declared_len, - } => BsonQmActionError::TruncatedDocument { - offset: rebase_offset(base, offset), - remaining, - declared_len, - }, - BsonQmActionError::CorruptDocumentLength { - offset, - declared_len, - } => BsonQmActionError::CorruptDocumentLength { - offset: rebase_offset(base, offset), - declared_len, - }, - BsonQmActionError::CorruptBson { offset, detail } => BsonQmActionError::CorruptBson { - offset: rebase_offset(base, offset), - detail, - }, - other => other, - } -} - -#[inline] -fn rebase_eod_intraday_error(base: u64, err: BsonEodIntradayError) -> BsonEodIntradayError { - match err { - BsonEodIntradayError::TruncatedDocument { - offset, - remaining, - declared_len, - } => BsonEodIntradayError::TruncatedDocument { - offset: rebase_offset(base, offset), - remaining, - declared_len, - }, - BsonEodIntradayError::CorruptDocumentLength { - offset, - declared_len, - } => BsonEodIntradayError::CorruptDocumentLength { - offset: rebase_offset(base, offset), - declared_len, - }, - BsonEodIntradayError::CorruptBson { offset, detail } => { - BsonEodIntradayError::CorruptBson { - offset: rebase_offset(base, offset), - detail, - } - } - other => other, - } -} - -/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_eod_intraday_buffer`], -/// accumulating [`BsonEodIntradayDecodeStats`] and rebasing per-document error offsets to -/// absolute stream byte offsets. -pub fn decode_eod_intraday_chunks( - reader: &mut RawBsonChunkReader, - mut on_bar: F, - mut on_error: E, -) -> Result -where - R: io::Read, - F: for<'a> FnMut(RawEodIntradayBar<'a>), - E: FnMut(u64, BsonEodIntradayError), -{ - let mut total = BsonEodIntradayDecodeStats::default(); - while let Some(chunk) = reader.next_chunk()? { - let base = chunk.start_offset; - let chunk_stats = decode_eod_intraday_buffer( - chunk.bytes, - &mut on_bar, - |local_offset, err| { - let abs_offset = base + local_offset as u64; - on_error(abs_offset, rebase_eod_intraday_error(base, err)); - }, - ); - total += chunk_stats; - } - Ok(total) -} - -/// Streams a concatenated raw BSON `eodIntraday1M` [`std::io::Read`] source through -/// [`decode_eod_intraday_buffer`] with bounded memory. -/// -/// Per-document decode errors are reported to `on_error` with their absolute stream byte offset -/// and skipped; stream-level framing or I/O errors return `Err(BsonStreamError)`. -pub fn decode_eod_intraday_stream( - reader: R, - options: BsonStreamOptions, - on_bar: F, - on_error: E, -) -> Result -where - R: io::Read, - F: for<'a> FnMut(RawEodIntradayBar<'a>), - E: FnMut(u64, BsonEodIntradayError), -{ - let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?; - decode_eod_intraday_chunks(&mut chunk_reader, on_bar, on_error) -} - -#[inline] -fn rebase_qm_intraday_error(base: u64, err: BsonQmIntradayError) -> BsonQmIntradayError { - match err { - BsonQmIntradayError::CorruptBson { offset, detail } => BsonQmIntradayError::CorruptBson { - offset: rebase_offset(base, offset), - detail, - }, - other => other, - } -} - -/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_qm_intraday_buffer`], -/// accumulating [`BsonQmIntradayDecodeStats`] and rebasing per-document error offsets to -/// absolute stream byte offsets. -pub fn decode_qm_intraday_chunks( - reader: &mut RawBsonChunkReader, - mut on_bar: F, - mut on_error: E, -) -> Result -where - R: io::Read, - F: for<'a> FnMut(RawQmIntradayBar<'a>), - E: FnMut(u64, BsonQmIntradayError), -{ - let mut total = BsonQmIntradayDecodeStats::default(); - while let Some(chunk) = reader.next_chunk()? { - let base = chunk.start_offset; - let chunk_stats = decode_qm_intraday_buffer( - chunk.bytes, - &mut on_bar, - |local_offset, err| { - let abs_offset = base + local_offset as u64; - on_error(abs_offset, rebase_qm_intraday_error(base, err)); - }, - ); - total += chunk_stats; - } - Ok(total) -} - -/// Streams a concatenated raw BSON `qmIntraday` [`std::io::Read`] source through -/// [`decode_qm_intraday_buffer`] with bounded memory. -/// -/// Per-document decode errors are reported to `on_error` with their absolute stream byte offset -/// and skipped; stream-level framing or I/O errors return `Err(BsonStreamError)`. -pub fn decode_qm_intraday_stream( - reader: R, - options: BsonStreamOptions, - on_bar: F, - on_error: E, -) -> Result -where - R: io::Read, - F: for<'a> FnMut(RawQmIntradayBar<'a>), - E: FnMut(u64, BsonQmIntradayError), -{ - let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?; - decode_qm_intraday_chunks(&mut chunk_reader, on_bar, on_error) -} - -/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_eod_price_buffer`], -/// accumulating [`BsonEodDecodeStats`] and rebasing per-document error offsets to absolute stream -/// byte offsets. -pub fn decode_eod_price_chunks( - reader: &mut RawBsonChunkReader, - mut on_bar: F, - mut on_error: E, -) -> Result -where - R: io::Read, - F: for<'a> FnMut(RawEodDailyBar<'a>), - E: FnMut(u64, BsonEodPriceError), -{ - let mut total = BsonEodDecodeStats::default(); - while let Some(chunk) = reader.next_chunk()? { - let base = chunk.start_offset; - let chunk_stats = decode_eod_price_buffer( - chunk.bytes, - &mut on_bar, - |local_offset, err| { - let abs_offset = base + local_offset as u64; - on_error(abs_offset, rebase_eod_error(base, err)); - }, - ); - total += chunk_stats; - } - Ok(total) -} - -/// Streams a concatenated raw BSON `eodPrices` [`std::io::Read`] source through -/// [`decode_eod_price_buffer`] with bounded memory. -/// -/// Per-document decode errors are reported to `on_error` with their absolute stream byte offset -/// and skipped; stream-level framing or I/O errors return `Err(BsonStreamError)`. -pub fn decode_eod_price_stream( - reader: R, - options: BsonStreamOptions, - on_bar: F, - on_error: E, -) -> Result -where - R: io::Read, - F: for<'a> FnMut(RawEodDailyBar<'a>), - E: FnMut(u64, BsonEodPriceError), -{ - let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?; - decode_eod_price_chunks(&mut chunk_reader, on_bar, on_error) -} - -/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_qm_split_buffer`], -/// accumulating [`BsonQmActionDecodeStats`] and rebasing per-document error offsets to absolute -/// stream byte offsets. -pub fn decode_qm_split_chunks( - reader: &mut RawBsonChunkReader, - mut on_split: F, - mut on_error: E, -) -> Result -where - R: io::Read, - F: for<'a> FnMut(RawQmSplit<'a>), - E: FnMut(u64, BsonQmActionError), -{ - let mut total = BsonQmActionDecodeStats::default(); - while let Some(chunk) = reader.next_chunk()? { - let base = chunk.start_offset; - let chunk_stats = decode_qm_split_buffer( - chunk.bytes, - &mut on_split, - |local_offset, err| { - let abs_offset = base + local_offset as u64; - on_error(abs_offset, rebase_qm_error(base, err)); - }, - ); - total += chunk_stats; - } - Ok(total) -} - -/// Streams a concatenated raw BSON `qmSplits` [`std::io::Read`] source through -/// [`decode_qm_split_buffer`] with bounded memory. -pub fn decode_qm_split_stream( - reader: R, - options: BsonStreamOptions, - on_split: F, - on_error: E, -) -> Result -where - R: io::Read, - F: for<'a> FnMut(RawQmSplit<'a>), - E: FnMut(u64, BsonQmActionError), -{ - let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?; - decode_qm_split_chunks(&mut chunk_reader, on_split, on_error) -} - -/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_qm_dividend_buffer`], -/// accumulating [`BsonQmActionDecodeStats`] and rebasing per-document error offsets to absolute -/// stream byte offsets. -pub fn decode_qm_dividend_chunks( - reader: &mut RawBsonChunkReader, - mut on_dividend: F, - mut on_error: E, -) -> Result -where - R: io::Read, - F: for<'a> FnMut(RawQmDividend<'a>), - E: FnMut(u64, BsonQmActionError), -{ - let mut total = BsonQmActionDecodeStats::default(); - while let Some(chunk) = reader.next_chunk()? { - let base = chunk.start_offset; - let chunk_stats = decode_qm_dividend_buffer( - chunk.bytes, - &mut on_dividend, - |local_offset, err| { - let abs_offset = base + local_offset as u64; - on_error(abs_offset, rebase_qm_error(base, err)); - }, - ); - total += chunk_stats; - } - Ok(total) -} - -/// Streams a concatenated raw BSON `qmDividends` [`std::io::Read`] source through -/// [`decode_qm_dividend_buffer`] with bounded memory. -pub fn decode_qm_dividend_stream( - reader: R, - options: BsonStreamOptions, - on_dividend: F, - on_error: E, -) -> Result -where - R: io::Read, - F: for<'a> FnMut(RawQmDividend<'a>), - E: FnMut(u64, BsonQmActionError), -{ - let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?; - decode_qm_dividend_chunks(&mut chunk_reader, on_dividend, on_error) -} - -#[inline] -fn rebase_qm_price_error(base: u64, err: BsonQmPriceError) -> BsonQmPriceError { - match err { - BsonQmPriceError::TruncatedDocument { - offset, - remaining, - declared_len, - } => BsonQmPriceError::TruncatedDocument { - offset: rebase_offset(base, offset), - remaining, - declared_len, - }, - BsonQmPriceError::CorruptDocumentLength { - offset, - declared_len, - } => BsonQmPriceError::CorruptDocumentLength { - offset: rebase_offset(base, offset), - declared_len, - }, - BsonQmPriceError::CorruptBson { offset, detail } => BsonQmPriceError::CorruptBson { - offset: rebase_offset(base, offset), - detail, - }, - other => other, - } -} - -/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_qm_price_buffer`], -/// accumulating [`BsonQmPriceDecodeStats`] and rebasing per-document error offsets to absolute -/// stream byte offsets. -pub fn decode_qm_price_chunks( - reader: &mut RawBsonChunkReader, - mut on_price: F, - mut on_error: E, -) -> Result -where - R: io::Read, - F: for<'a> FnMut(RawQmPrice<'a>), - E: FnMut(u64, BsonQmPriceError), -{ - let mut total = BsonQmPriceDecodeStats::default(); - while let Some(chunk) = reader.next_chunk()? { - let base = chunk.start_offset; - let chunk_stats = decode_qm_price_buffer(chunk.bytes, &mut on_price, |local_offset, err| { - let abs_offset = base + local_offset as u64; - on_error(abs_offset, rebase_qm_price_error(base, err)); - }); - total += chunk_stats; - } - Ok(total) -} - -/// Streams a concatenated raw BSON `qmPrices` [`std::io::Read`] source through -/// [`decode_qm_price_buffer`] with bounded memory. -pub fn decode_qm_price_stream( - reader: R, - options: BsonStreamOptions, - on_price: F, - on_error: E, -) -> Result -where - R: io::Read, - F: for<'a> FnMut(RawQmPrice<'a>), - E: FnMut(u64, BsonQmPriceError), -{ - let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?; - decode_qm_price_chunks(&mut chunk_reader, on_price, on_error) -} - -#[inline] -fn rebase_te_error(base: u64, err: BsonTeMarketDataError) -> BsonTeMarketDataError { - match err { - BsonTeMarketDataError::TruncatedDocument { - offset, - remaining, - declared_len, - } => BsonTeMarketDataError::TruncatedDocument { - offset: rebase_offset(base, offset), - remaining, - declared_len, - }, - BsonTeMarketDataError::CorruptDocumentLength { - offset, - declared_len, - } => BsonTeMarketDataError::CorruptDocumentLength { - offset: rebase_offset(base, offset), - declared_len, - }, - BsonTeMarketDataError::CorruptBson { offset, detail } => { - BsonTeMarketDataError::CorruptBson { - offset: rebase_offset(base, offset), - detail, - } - } - BsonTeMarketDataError::CorruptPointBson { - offset, - point_index, - detail, - } => BsonTeMarketDataError::CorruptPointBson { - offset: rebase_offset(base, offset), - point_index, - detail, - }, - other => other, - } -} - -/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_te_market_data_buffer`], -/// accumulating [`BsonTeMarketDataDecodeStats`] and rebasing per-document and per-point error -/// offsets to absolute stream byte offsets. -pub fn decode_te_market_data_chunks( - reader: &mut RawBsonChunkReader, - target_symbol: &str, - mut on_bar: F, - mut on_error: E, -) -> Result -where - R: io::Read, - F: FnMut(FxDailyBar), - E: FnMut(u64, BsonTeMarketDataError), -{ - let mut total = BsonTeMarketDataDecodeStats::default(); - while let Some(chunk) = reader.next_chunk()? { - let base = chunk.start_offset; - let chunk_stats = decode_te_market_data_buffer( - chunk.bytes, - target_symbol, - &mut on_bar, - |local_offset, err| { - let abs_offset = base + local_offset as u64; - on_error(abs_offset, rebase_te_error(base, err)); - }, - ); - total += chunk_stats; - } - Ok(total) -} - -/// Streams a concatenated raw BSON `teMarketData` [`std::io::Read`] source through -/// [`decode_te_market_data_buffer`] with bounded memory. -pub fn decode_te_market_data_stream( - reader: R, - options: BsonStreamOptions, - target_symbol: &str, - on_bar: F, - on_error: E, -) -> Result -where - R: io::Read, - F: FnMut(FxDailyBar), - E: FnMut(u64, BsonTeMarketDataError), -{ - let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?; - decode_te_market_data_chunks(&mut chunk_reader, target_symbol, on_bar, on_error) -} - -#[inline] -fn rebase_te_data_error(base: u64, err: BsonTeDataError) -> BsonTeDataError { - match err { - BsonTeDataError::TruncatedDocument { - offset, - remaining, - declared_len, - } => BsonTeDataError::TruncatedDocument { - offset: rebase_offset(base, offset), - remaining, - declared_len, - }, - BsonTeDataError::CorruptDocumentLength { - offset, - declared_len, - } => BsonTeDataError::CorruptDocumentLength { - offset: rebase_offset(base, offset), - declared_len, - }, - BsonTeDataError::CorruptBson { offset, detail } => BsonTeDataError::CorruptBson { - offset: rebase_offset(base, offset), - detail, - }, - BsonTeDataError::CorruptPointBson { - offset, - point_index, - detail, - } => BsonTeDataError::CorruptPointBson { - offset: rebase_offset(base, offset), - point_index, - detail, - }, - other => other, - } -} - -/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_te_data_buffer`], -/// accumulating [`BsonTeDataDecodeStats`] and rebasing per-document and per-point error offsets -/// to absolute stream byte offsets. -/// -/// Emits historical `data` observations as borrowed [`TeDataPoint<'a>`] values; `forecast` is -/// never read. Per-document and per-point data-quality errors are reported to `on_error` and do -/// not abort the stream; only stream-level framing or I/O errors return `Err(BsonStreamError)`. -pub fn decode_te_data_chunks( - reader: &mut RawBsonChunkReader, - mut on_point: F, - mut on_error: E, -) -> Result -where - R: io::Read, - F: for<'a> FnMut(TeDataPoint<'a>), - E: FnMut(u64, BsonTeDataError), -{ - let mut total = BsonTeDataDecodeStats::default(); - while let Some(chunk) = reader.next_chunk()? { - let base = chunk.start_offset; - let chunk_stats = decode_te_data_buffer( - chunk.bytes, - &mut on_point, - |local_offset, err| { - let abs_offset = base + local_offset as u64; - on_error(abs_offset, rebase_te_data_error(base, err)); - }, - ); - total += chunk_stats; - } - Ok(total) -} - -/// Streams a concatenated raw BSON `teData` [`std::io::Read`] source through -/// [`decode_te_data_buffer`] with bounded memory. -pub fn decode_te_data_stream( - reader: R, - options: BsonStreamOptions, - on_point: F, - on_error: E, -) -> Result -where - R: io::Read, - F: for<'a> FnMut(TeDataPoint<'a>), - E: FnMut(u64, BsonTeDataError), -{ - let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?; - decode_te_data_chunks(&mut chunk_reader, on_point, on_error) -} - -/// Terminal error returned by [`decode_ceo_posts_chunks`] and [`decode_ceo_posts_stream`]. -#[derive(Debug)] -pub enum BsonCeoPostsStreamError { - Stream(BsonStreamError), - Decode(BsonCeoPostsError), -} - -impl fmt::Display for BsonCeoPostsStreamError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Stream(err) => write!(f, "{err}"), - Self::Decode(err) => write!(f, "{err}"), - } - } -} - -impl Error for BsonCeoPostsStreamError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::Stream(err) => Some(err), - Self::Decode(err) => Some(err), - } - } -} - -impl From for BsonCeoPostsStreamError { - fn from(err: BsonStreamError) -> Self { - Self::Stream(err) - } -} - -impl From for BsonCeoPostsStreamError { - fn from(err: BsonCeoPostsError) -> Self { - Self::Decode(err) - } -} - -#[inline] -fn rebase_ceo_posts_error(base: u64, err: BsonCeoPostsError) -> BsonCeoPostsError { - match err { - BsonCeoPostsError::TruncatedDocument { - offset, - remaining, - declared_len, - } => BsonCeoPostsError::TruncatedDocument { - offset: base.saturating_add(offset), - remaining, - declared_len, - }, - BsonCeoPostsError::CorruptDocumentLength { - offset, - declared_len, - } => BsonCeoPostsError::CorruptDocumentLength { - offset: base.saturating_add(offset), - declared_len, - }, - BsonCeoPostsError::CorruptBson { offset, detail } => BsonCeoPostsError::CorruptBson { - offset: base.saturating_add(offset), - detail, - }, - other => other, - } -} - -/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_ceo_posts_buffer`], -/// accumulating [`BsonCeoPostsDecodeStats`] and rebasing structural BSON error offsets to -/// absolute stream byte offsets. -pub fn decode_ceo_posts_chunks( - reader: &mut RawBsonChunkReader, - fields: &CeoPostsFieldNames<'_>, - unit: CeoPostsTimestampUnit, - mut on_row: F, -) -> Result -where - R: io::Read, - F: for<'a> FnMut(CeoPost<&'a str>), -{ - fields.validate()?; - let mut total = BsonCeoPostsDecodeStats::default(); - while let Some(chunk) = reader.next_chunk()? { - let base = chunk.start_offset; - let chunk_stats = decode_ceo_posts_buffer(chunk.bytes, fields, unit, &mut on_row) - .map_err(|err| BsonCeoPostsStreamError::Decode(rebase_ceo_posts_error(base, err)))?; - total += chunk_stats; - } - Ok(total) -} - -/// Streams a concatenated raw BSON `ceoPosts` [`std::io::Read`] source through -/// [`decode_ceo_posts_buffer`] with bounded memory. -pub fn decode_ceo_posts_stream( - reader: R, - options: BsonStreamOptions, - fields: &CeoPostsFieldNames<'_>, - unit: CeoPostsTimestampUnit, - on_row: F, -) -> Result -where - R: io::Read, - F: for<'a> FnMut(CeoPost<&'a str>), -{ - fields.validate()?; - let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?; - decode_ceo_posts_chunks(&mut chunk_reader, fields, unit, on_row) -} - -/// Terminal error returned by [`decode_ceo_shorts_chunks`] and [`decode_ceo_shorts_stream`]. -#[derive(Debug)] -pub enum BsonCeoShortsStreamError { - Stream(BsonStreamError), - Decode(BsonCeoShortsError), -} - -impl fmt::Display for BsonCeoShortsStreamError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Stream(err) => write!(f, "{err}"), - Self::Decode(err) => write!(f, "{err}"), - } - } -} - -impl Error for BsonCeoShortsStreamError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::Stream(err) => Some(err), - Self::Decode(err) => Some(err), - } - } -} - -impl From for BsonCeoShortsStreamError { - fn from(err: BsonStreamError) -> Self { - Self::Stream(err) - } -} - -impl From for BsonCeoShortsStreamError { - fn from(err: BsonCeoShortsError) -> Self { - Self::Decode(err) - } -} - -#[inline] -fn rebase_ceo_shorts_error(base: u64, err: BsonCeoShortsError) -> BsonCeoShortsError { - match err { - BsonCeoShortsError::TruncatedDocument { - offset, - remaining, - declared_len, - } => BsonCeoShortsError::TruncatedDocument { - offset: base.saturating_add(offset), - remaining, - declared_len, - }, - BsonCeoShortsError::CorruptDocumentLength { - offset, - declared_len, - } => BsonCeoShortsError::CorruptDocumentLength { - offset: base.saturating_add(offset), - declared_len, - }, - BsonCeoShortsError::CorruptBson { offset, detail } => BsonCeoShortsError::CorruptBson { - offset: base.saturating_add(offset), - detail, - }, - other => other, - } -} - -/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_ceo_shorts_buffer`], -/// accumulating [`BsonCeoShortsDecodeStats`] and rebasing structural BSON error offsets to -/// absolute stream byte offsets. -pub fn decode_ceo_shorts_chunks( - reader: &mut RawBsonChunkReader, - fields: &CeoShortsFieldNames<'_>, - mut on_row: F, -) -> Result -where - R: io::Read, - F: for<'a> FnMut(CeoShortReport<&'a str>), -{ - fields.validate()?; - let mut total = BsonCeoShortsDecodeStats::default(); - while let Some(chunk) = reader.next_chunk()? { - let base = chunk.start_offset; - let chunk_stats = decode_ceo_shorts_buffer(chunk.bytes, fields, &mut on_row) - .map_err(|err| BsonCeoShortsStreamError::Decode(rebase_ceo_shorts_error(base, err)))?; - total += chunk_stats; - } - Ok(total) -} - -/// Streams a concatenated raw BSON `ceoShorts` [`std::io::Read`] source through -/// [`decode_ceo_shorts_buffer`] with bounded memory. -pub fn decode_ceo_shorts_stream( - reader: R, - options: BsonStreamOptions, - fields: &CeoShortsFieldNames<'_>, - on_row: F, -) -> Result -where - R: io::Read, - F: for<'a> FnMut(CeoShortReport<&'a str>), -{ - fields.validate()?; - let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?; - decode_ceo_shorts_chunks(&mut chunk_reader, fields, on_row) -} - -/// Terminal error returned by [`decode_qm_filings_chunks`], [`decode_qm_filings_stream`], -/// [`decode_qm_earnings_chunks`], and [`decode_qm_earnings_stream`]. -#[derive(Debug)] -pub enum BsonQmEventsStreamError { - Stream(BsonStreamError), - Decode(BsonQmEventsError), -} - -impl fmt::Display for BsonQmEventsStreamError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Stream(err) => write!(f, "{err}"), - Self::Decode(err) => write!(f, "{err}"), - } - } -} - -impl Error for BsonQmEventsStreamError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::Stream(err) => Some(err), - Self::Decode(err) => Some(err), - } - } -} - -impl From for BsonQmEventsStreamError { - fn from(err: BsonStreamError) -> Self { - Self::Stream(err) - } -} - -impl From for BsonQmEventsStreamError { - fn from(err: BsonQmEventsError) -> Self { - Self::Decode(err) - } -} - -#[inline] -fn rebase_qm_events_error(base: u64, err: BsonQmEventsError) -> BsonQmEventsError { - match err { - BsonQmEventsError::TruncatedDocument { - offset, - remaining, - declared_len, - } => BsonQmEventsError::TruncatedDocument { - offset: base.saturating_add(offset), - remaining, - declared_len, - }, - BsonQmEventsError::CorruptDocumentLength { - offset, - declared_len, - } => BsonQmEventsError::CorruptDocumentLength { - offset: base.saturating_add(offset), - declared_len, - }, - BsonQmEventsError::CorruptBson { offset, detail } => BsonQmEventsError::CorruptBson { - offset: base.saturating_add(offset), - detail, - }, - other => other, - } -} - -/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_qm_filing_buffer`], -/// accumulating [`BsonQmFilingsDecodeStats`] and rebasing structural BSON error offsets to -/// absolute stream byte offsets. -pub fn decode_qm_filings_chunks( - reader: &mut RawBsonChunkReader, - fields: &QmFilingsFieldNames<'_>, - mut on_row: F, -) -> Result -where - R: io::Read, - F: for<'a> FnMut(RawQmFiling<'a>), -{ - fields.validate()?; - let mut total = BsonQmFilingsDecodeStats::default(); - while let Some(chunk) = reader.next_chunk()? { - let base = chunk.start_offset; - let chunk_stats = decode_qm_filing_buffer(chunk.bytes, fields, &mut on_row) - .map_err(|err| BsonQmEventsStreamError::Decode(rebase_qm_events_error(base, err)))?; - total += chunk_stats; - } - Ok(total) -} - -/// Streams a concatenated raw BSON `qmFilings` [`std::io::Read`] source through -/// [`decode_qm_filing_buffer`] with bounded memory. -pub fn decode_qm_filings_stream( - reader: R, - options: BsonStreamOptions, - fields: &QmFilingsFieldNames<'_>, - on_row: F, -) -> Result -where - R: io::Read, - F: for<'a> FnMut(RawQmFiling<'a>), -{ - fields.validate()?; - let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?; - decode_qm_filings_chunks(&mut chunk_reader, fields, on_row) -} - -/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_qm_earning_buffer`], -/// accumulating [`BsonQmEarningsDecodeStats`] and rebasing structural BSON error offsets to -/// absolute stream byte offsets. -pub fn decode_qm_earnings_chunks( - reader: &mut RawBsonChunkReader, - fields: &QmEarningsFieldNames<'_>, - mut on_row: F, -) -> Result -where - R: io::Read, - F: for<'a> FnMut(RawQmEarning<'a>), -{ - fields.validate()?; - let mut total = BsonQmEarningsDecodeStats::default(); - while let Some(chunk) = reader.next_chunk()? { - let base = chunk.start_offset; - let chunk_stats = decode_qm_earning_buffer(chunk.bytes, fields, &mut on_row) - .map_err(|err| BsonQmEventsStreamError::Decode(rebase_qm_events_error(base, err)))?; - total += chunk_stats; - } - Ok(total) -} - -/// Streams a concatenated raw BSON `qmEarnings` [`std::io::Read`] source through -/// [`decode_qm_earning_buffer`] with bounded memory. -pub fn decode_qm_earnings_stream( - reader: R, - options: BsonStreamOptions, - fields: &QmEarningsFieldNames<'_>, - on_row: F, -) -> Result -where - R: io::Read, - F: for<'a> FnMut(RawQmEarning<'a>), -{ - fields.validate()?; - let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?; - decode_qm_earnings_chunks(&mut chunk_reader, fields, on_row) -} - -/// Terminal error returned by [`decode_qm_financials_chunks`] and [`decode_qm_financials_stream`]. -#[derive(Debug)] -pub enum BsonQmFinancialsStreamError { - Stream(BsonStreamError), - Decode(BsonQmFinancialsError), -} - -impl fmt::Display for BsonQmFinancialsStreamError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Stream(err) => write!(f, "{err}"), - Self::Decode(err) => write!(f, "{err}"), - } - } -} - -impl Error for BsonQmFinancialsStreamError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::Stream(err) => Some(err), - Self::Decode(err) => Some(err), - } - } -} - -impl From for BsonQmFinancialsStreamError { - fn from(err: BsonStreamError) -> Self { - Self::Stream(err) - } -} - -impl From for BsonQmFinancialsStreamError { - fn from(err: BsonQmFinancialsError) -> Self { - Self::Decode(err) - } -} - -#[inline] -fn rebase_qm_financials_error(base: u64, err: BsonQmFinancialsError) -> BsonQmFinancialsError { - match err { - BsonQmFinancialsError::TruncatedDocument { - offset, - remaining, - declared_len, - } => BsonQmFinancialsError::TruncatedDocument { - offset: base.saturating_add(offset), - remaining, - declared_len, - }, - BsonQmFinancialsError::CorruptDocumentLength { - offset, - declared_len, - } => BsonQmFinancialsError::CorruptDocumentLength { - offset: base.saturating_add(offset), - declared_len, - }, - BsonQmFinancialsError::CorruptBson { offset, detail } => { - BsonQmFinancialsError::CorruptBson { - offset: base.saturating_add(offset), - detail, - } - } - other => other, - } -} - -/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_qm_financials_buffer`], -/// accumulating [`BsonQmFinancialsDecodeStats`] and rebasing structural BSON error offsets to -/// absolute stream byte offsets. -pub fn decode_qm_financials_chunks( - reader: &mut RawBsonChunkReader, - fields: &QmFinancialsFieldNames<'_>, - fiscal_period: QmFinancialsFiscalPeriod<'_>, - mut on_row: F, -) -> Result -where - R: io::Read, - F: for<'a> FnMut(FinancialObservation<&'a str>), -{ - fields.validate()?; - fiscal_period.validate()?; - let mut total = BsonQmFinancialsDecodeStats::default(); - while let Some(chunk) = reader.next_chunk()? { - let base = chunk.start_offset; - let chunk_stats = - decode_qm_financials_buffer(chunk.bytes, fields, fiscal_period, &mut on_row).map_err( - |err| BsonQmFinancialsStreamError::Decode(rebase_qm_financials_error(base, err)), - )?; - total += chunk_stats; - } - Ok(total) -} - -/// Streams a concatenated raw BSON `qmFinancials` [`std::io::Read`] source through -/// [`decode_qm_financials_buffer`] with bounded memory. -pub fn decode_qm_financials_stream( - reader: R, - options: BsonStreamOptions, - fields: &QmFinancialsFieldNames<'_>, - fiscal_period: QmFinancialsFiscalPeriod<'_>, - on_row: F, -) -> Result -where - R: io::Read, - F: for<'a> FnMut(FinancialObservation<&'a str>), -{ - fields.validate()?; - fiscal_period.validate()?; - let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?; - decode_qm_financials_chunks(&mut chunk_reader, fields, fiscal_period, on_row) -} - -#[cfg(test)] -#[path = "bson_stream_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/bson_stream_tests.rs b/tools/curate-etl/src/bson_stream_tests.rs deleted file mode 100644 index a903b778..00000000 --- a/tools/curate-etl/src/bson_stream_tests.rs +++ /dev/null @@ -1,3834 +0,0 @@ -use std::error::Error as _; -use std::io::{self, Cursor, Read}; - -use bson::raw::{cstr, RawArrayBuf, RawDocumentBuf}; -use bson::DateTime; - -use crate::bson_eod_intraday::{ - decode_eod_intraday_buffer, BsonEodIntradayError, -}; -use crate::bson_eod_prices::{ - decode_eod_price_buffer, iter_raw_bson_docs, BsonEodDecodeStats, -}; -use crate::bson_qm_actions::{ - decode_qm_dividend_buffer, decode_qm_split_buffer, BsonQmActionDecodeStats, -}; -use crate::bson_qm_financials::{ - decode_qm_financials_buffer, BsonQmFinancialsDecodeStats, BsonQmFinancialsError, - QmFinancialsFieldNames, QmFinancialsFiscalPeriod, -}; -use crate::bson_qm_intraday::{ - decode_qm_intraday_buffer, BsonQmIntradayDecodeStats, BsonQmIntradayError, -}; -use crate::bson_qm_prices::{decode_qm_price_buffer, BsonQmPriceError}; -use crate::bson_stream::{ - decode_eod_intraday_chunks, decode_eod_intraday_stream, decode_eod_price_stream, - decode_qm_dividend_stream, decode_qm_financials_chunks, decode_qm_financials_stream, - decode_qm_intraday_chunks, decode_qm_intraday_stream, decode_qm_price_stream, - decode_qm_split_stream, decode_te_data_chunks, decode_te_data_stream, - BsonQmFinancialsStreamError, BsonStreamError, BsonStreamOptions, - RawBsonChunkReader, DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES, -}; -use crate::bson_te_data::{ - decode_te_data_buffer, BsonTeDataDecodeStats, BsonTeDataError, TeDataPoint, -}; -use crate::fundamentals::FinancialObservation; - -#[derive(Debug, Clone, Copy)] -struct SplitMix64(u64); - -impl SplitMix64 { - 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) - } -} - -/// Reader returning at most `max_step` bytes per `read()` call. -struct FixedStepReader<'a> { - data: &'a [u8], - pos: usize, - max_step: usize, -} - -impl<'a> FixedStepReader<'a> { - fn new(data: &'a [u8], max_step: usize) -> Self { - Self { - data, - pos: 0, - max_step: max_step.max(1), - } - } -} - -impl Read for FixedStepReader<'_> { - fn read(&mut self, buf: &mut [u8]) -> io::Result { - let remaining = self.data.len() - self.pos; - if remaining == 0 { - return Ok(0); - } - let take = remaining.min(self.max_step).min(buf.len()); - buf[..take].copy_from_slice(&self.data[self.pos..self.pos + take]); - self.pos += take; - Ok(take) - } -} - -/// Reader returning deterministic pseudo-random read sizes and optional `Interrupted` errors. -struct RandomInterruptReader<'a> { - data: &'a [u8], - pos: usize, - rng: SplitMix64, - inject_interrupts: bool, - calls: usize, -} - -impl<'a> RandomInterruptReader<'a> { - fn new(data: &'a [u8], seed: u64, inject_interrupts: bool) -> Self { - Self { - data, - pos: 0, - rng: SplitMix64::new(seed), - inject_interrupts, - calls: 0, - } - } -} - -impl Read for RandomInterruptReader<'_> { - fn read(&mut self, buf: &mut [u8]) -> io::Result { - self.calls += 1; - if self.inject_interrupts && self.calls % 3 == 0 { - return Err(io::Error::new( - io::ErrorKind::Interrupted, - "simulated EINTR", - )); - } - let remaining = self.data.len() - self.pos; - if remaining == 0 { - return Ok(0); - } - let max_chunk = (self.rng.next_u64() as usize % 511) + 1; - let take = remaining.min(max_chunk).min(buf.len()); - buf[..take].copy_from_slice(&self.data[self.pos..self.pos + take]); - self.pos += take; - Ok(take) - } -} - -/// Reader that delivers scripted chunks and then returns a terminal `io::Error`. -struct FailingReader { - data: Vec, - pos: usize, - fail_kind: io::ErrorKind, - fail_msg: &'static str, - failed: bool, - reads_after_fail: usize, -} - -impl FailingReader { - fn new(data: Vec, fail_kind: io::ErrorKind, fail_msg: &'static str) -> Self { - Self { - data, - pos: 0, - fail_kind, - fail_msg, - failed: false, - reads_after_fail: 0, - } - } -} - -impl Read for FailingReader { - fn read(&mut self, buf: &mut [u8]) -> io::Result { - if self.failed { - self.reads_after_fail += 1; - return Err(io::Error::new(self.fail_kind, "read after terminal fail")); - } - let remaining = self.data.len() - self.pos; - if remaining == 0 { - self.failed = true; - return Err(io::Error::new(self.fail_kind, self.fail_msg)); - } - let take = remaining.min(buf.len()); - buf[..take].copy_from_slice(&self.data[self.pos..self.pos + take]); - self.pos += take; - Ok(take) - } -} - -fn make_eod_doc(code: &str, date: &str, open: f64, high: f64, low: f64, close: f64, vol: i64) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), code); - doc.append(cstr!("date"), date); - doc.append(cstr!("open"), open); - doc.append(cstr!("high"), high); - doc.append(cstr!("low"), low); - doc.append(cstr!("close"), close); - doc.append(cstr!("volume"), vol); - doc.into_bytes() -} - -/// Builds a validly length-prefixed BSON document whose trailing null terminator is corrupted -/// (`0xFF` instead of `0x00`), triggering `CorruptBson` inside `iter_raw_bson_docs` while still -/// cleanly advancing past the document. -fn make_corrupt_bson_doc(len: usize) -> Vec { - assert!(len >= MIN_BSON_DOC_BYTES); - let mut bytes = vec![0u8; len]; - bytes[0..4].copy_from_slice(&(len as i32).to_le_bytes()); - bytes[len - 1] = 0xFF; - bytes -} - -fn build_mixed_eod_fixture() -> Vec { - let mut out = Vec::new(); - // 1. Valid with extra metadata fields. - { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("symbol"), "AAPL"); - doc.append(cstr!("exchange"), "NASDAQ"); - doc.append(cstr!("eodSearchCode"), "AAPL.US"); - doc.append(cstr!("date"), "2024-06-10"); - doc.append(cstr!("open"), 195.5_f64); - doc.append(cstr!("high"), 198.0_f64); - doc.append(cstr!("low"), 194.25_f64); - doc.append(cstr!("close"), 197.1_f64); - doc.append(cstr!("volume"), 42_000_000_i64); - doc.append(cstr!("adjustedClose"), 197.1_f64); - out.extend_from_slice(doc.as_bytes()); - } - // 2. Missing required field (`volume`). - { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), "MSFT.US"); - doc.append(cstr!("date"), "2024-06-10"); - doc.append(cstr!("open"), 420.0_f64); - doc.append(cstr!("high"), 425.0_f64); - doc.append(cstr!("low"), 419.0_f64); - doc.append(cstr!("close"), 424.0_f64); - out.extend_from_slice(doc.as_bytes()); - } - // 3. Empty string field (`eodSearchCode`). - { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), " "); - doc.append(cstr!("date"), "2024-06-10"); - doc.append(cstr!("open"), 10.0_f64); - doc.append(cstr!("high"), 11.0_f64); - doc.append(cstr!("low"), 9.5_f64); - doc.append(cstr!("close"), 10.5_f64); - doc.append(cstr!("volume"), 100_i32); - out.extend_from_slice(doc.as_bytes()); - } - // 4. Valid with BSON DateTime and Int32 numerics. - { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), "RY.TO"); - doc.append(cstr!("date"), DateTime::from_millis(19_884_i64 * 86_400_000)); - doc.append(cstr!("open"), 140_i32); - doc.append(cstr!("high"), 142_i32); - doc.append(cstr!("low"), 139_i32); - doc.append(cstr!("close"), 141_i32); - doc.append(cstr!("volume"), 0_i32); - out.extend_from_slice(doc.as_bytes()); - } - // 5. Length-framed CorruptBson (exercises offset rebasing across chunk boundaries). - out.extend_from_slice(&make_corrupt_bson_doc(37)); - // 6. WrongType on `open`. - { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), "NVDA.US"); - doc.append(cstr!("date"), "2024-06-11"); - doc.append(cstr!("open"), "not-a-number"); - doc.append(cstr!("high"), 122.0_f64); - doc.append(cstr!("low"), 118.0_f64); - doc.append(cstr!("close"), 121.0_f64); - doc.append(cstr!("volume"), 1_000_i64); - out.extend_from_slice(doc.as_bytes()); - } - // 7. MalformedDate. - { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), "TD.TO"); - doc.append(cstr!("date"), "2023-02-29"); - doc.append(cstr!("open"), 80.0_f64); - doc.append(cstr!("high"), 81.0_f64); - doc.append(cstr!("low"), 79.0_f64); - doc.append(cstr!("close"), 80.5_f64); - doc.append(cstr!("volume"), 500_i64); - out.extend_from_slice(doc.as_bytes()); - } - // 8. InvalidNumber (negative high). - { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), "BCE.TO"); - doc.append(cstr!("date"), "2024-06-12"); - doc.append(cstr!("open"), 45.0_f64); - doc.append(cstr!("high"), -46.0_f64); - doc.append(cstr!("low"), 44.0_f64); - doc.append(cstr!("close"), 45.5_f64); - doc.append(cstr!("volume"), 500_i64); - out.extend_from_slice(doc.as_bytes()); - } - // 9..24. More valid docs + another CorruptBson so multi-chunk streams span many boundaries. - for i in 0..16 { - out.extend_from_slice(&make_eod_doc( - &format!("SYM{i:03}.US"), - "2024-06-14", - 10.0 + i as f64, - 11.0 + i as f64, - 9.5 + i as f64, - 10.5 + i as f64, - 10_000 + i as i64 * 100, - )); - } - out.extend_from_slice(&make_corrupt_bson_doc(23)); - out.extend_from_slice(&make_eod_doc( - "FINAL.TO", - "2024-06-15", - 50.0, - 52.0, - 49.5, - 51.25, - 99_999, - )); - out -} - -fn build_mixed_qm_split_fixture() -> Vec { - let mut out = Vec::new(); - // 1. Valid forward split with declared date and extra fields. - { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("symbol"), "NVDA"); - doc.append(cstr!("usdFxRate"), 1_i32); - doc.append(cstr!("qmSearchCode"), "NVDA"); - doc.append(cstr!("date"), "2024-06-10"); - doc.append(cstr!("declared"), "2024-05-22"); - doc.append(cstr!("splitratio"), 10.0_f64); - out.extend_from_slice(doc.as_bytes()); - } - // 2. Valid ratio == 1.0 no-op (preserved and counted in split_noop_ratio_one). - { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), "NOOP"); - doc.append(cstr!("date"), "2024-06-11"); - doc.append(cstr!("splitratio"), 1_i32); - out.extend_from_slice(doc.as_bytes()); - } - // 3. InvalidNumber (ratio <= 0). - { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), "BAD"); - doc.append(cstr!("date"), "2024-06-12"); - doc.append(cstr!("splitratio"), 0.0_f64); - out.extend_from_slice(doc.as_bytes()); - } - // 4. Length-framed CorruptBson. - out.extend_from_slice(&make_corrupt_bson_doc(29)); - // 5. MissingField (`splitratio`). - { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), "MISS"); - doc.append(cstr!("date"), "2024-06-13"); - out.extend_from_slice(doc.as_bytes()); - } - // 6. Reverse split with DateTime date. - { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), "NEXM:CA"); - doc.append(cstr!("date"), DateTime::from_millis(20_257_i64 * 86_400_000)); - doc.append(cstr!("splitratio"), 0.05_f64); - out.extend_from_slice(doc.as_bytes()); - } - // 7..16. Additional valid splits. - for i in 0..10 { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), format!("SPL{i:02}")); - doc.append(cstr!("date"), "2024-06-14"); - doc.append(cstr!("splitratio"), if i % 4 == 0 { 1.0 } else { 2.0 + i as f64 }); - out.extend_from_slice(doc.as_bytes()); - } - out -} - -fn build_mixed_qm_dividend_fixture() -> Vec { - let mut out = Vec::new(); - // 1. Valid CAD dividend with bogus usdFxRate (ignored) and declared date. - { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), "RY:CA"); - doc.append(cstr!("date"), "2024-07-25"); - doc.append(cstr!("declared"), "2024-05-30"); - doc.append(cstr!("amount"), 1.42_f64); - doc.append(cstr!("currency"), "CAD"); - doc.append(cstr!("usdFxRate"), 1_i32); - out.extend_from_slice(doc.as_bytes()); - } - // 2. EmptyField (`currency`). - { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), "TD:CA"); - doc.append(cstr!("date"), "2024-07-25"); - doc.append(cstr!("amount"), 1.02_f64); - doc.append(cstr!("currency"), " "); - out.extend_from_slice(doc.as_bytes()); - } - // 3. Length-framed CorruptBson. - out.extend_from_slice(&make_corrupt_bson_doc(31)); - // 4. MalformedDate. - { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), "AAPL"); - doc.append(cstr!("date"), "not-a-date"); - doc.append(cstr!("amount"), 0.25_f64); - doc.append(cstr!("currency"), "USD"); - out.extend_from_slice(doc.as_bytes()); - } - // 5..16. Additional valid USD/CAD dividends. - for i in 0..12 { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), format!("DIV{i:02}")); - doc.append(cstr!("date"), "2024-07-26"); - doc.append(cstr!("amount"), 0.10 * (i as f64)); - doc.append(cstr!("currency"), if i % 2 == 0 { "USD" } else { "CAD" }); - out.extend_from_slice(doc.as_bytes()); - } - out -} - -#[derive(Debug, PartialEq)] -struct OwnedEodBar { - code: String, - session_date: i32, - open: u64, - high: u64, - low: u64, - close: u64, - adj_volume: u64, -} - -#[derive(Debug, PartialEq)] -struct OwnedQmSplit { - code: String, - ex_date: i32, - ratio: u64, - declared_date: Option, -} - -#[derive(Debug, PartialEq)] -struct OwnedQmDividend { - code: String, - ex_date: i32, - cash: u64, - currency: String, - declared_date: Option, -} - -#[test] -fn rejects_invalid_options_and_accepts_valid_boundaries() { - assert!(matches!( - RawBsonChunkReader::with_options( - Cursor::new(&[][..]), - BsonStreamOptions { - chunk_capacity_bytes: 0, - max_doc_bytes: DEFAULT_MAX_DOC_BYTES, - } - ), - Err(BsonStreamError::InvalidChunkCapacity) - )); - assert!(matches!( - RawBsonChunkReader::with_options( - Cursor::new(&[][..]), - BsonStreamOptions { - chunk_capacity_bytes: 1024, - max_doc_bytes: 4, - } - ), - Err(BsonStreamError::InvalidMaxDocBytes) - )); - assert!(matches!( - RawBsonChunkReader::with_options( - Cursor::new(&[][..]), - BsonStreamOptions { - chunk_capacity_bytes: 1024, - max_doc_bytes: 0, - } - ), - Err(BsonStreamError::InvalidMaxDocBytes) - )); - - let min_reader = RawBsonChunkReader::with_options( - Cursor::new(&[][..]), - BsonStreamOptions { - chunk_capacity_bytes: 1, - max_doc_bytes: MIN_BSON_DOC_BYTES, - }, - ) - .expect("minimum valid options must succeed"); - assert_eq!(min_reader.buffer_capacity(), 1); - assert_eq!(min_reader.options().chunk_capacity_bytes, 1); - assert_eq!(min_reader.options().max_doc_bytes, MIN_BSON_DOC_BYTES); - - let default_reader = RawBsonChunkReader::new(Cursor::new(&[][..])); - assert_eq!( - default_reader.options(), - BsonStreamOptions { - chunk_capacity_bytes: DEFAULT_CHUNK_CAPACITY_BYTES, - max_doc_bytes: DEFAULT_MAX_DOC_BYTES, - } - ); - let _inner: Cursor<&[u8]> = default_reader.into_inner(); -} - -#[test] -fn empty_input_returns_none_and_zero_stats() { - let mut reader = RawBsonChunkReader::with_options( - Cursor::new(&[][..]), - BsonStreamOptions { - chunk_capacity_bytes: 64, - max_doc_bytes: 1024, - }, - ) - .unwrap(); - assert!(reader.next_chunk().unwrap().is_none()); - assert!(reader.next_chunk().unwrap().is_none()); - assert_eq!(reader.bytes_read(), 0); - assert_eq!(reader.docs_framed(), 0); - - let opts = BsonStreamOptions { - chunk_capacity_bytes: 64, - max_doc_bytes: 1024, - }; - let eod_stats = decode_eod_price_stream( - Cursor::new(&[][..]), - opts, - |_| panic!("unexpected bar on empty input"), - |_, _| panic!("unexpected error on empty input"), - ) - .unwrap(); - assert_eq!(eod_stats, BsonEodDecodeStats::default()); - - let split_stats = decode_qm_split_stream( - Cursor::new(&[][..]), - opts, - |_| panic!("unexpected split on empty input"), - |_, _| panic!("unexpected error on empty input"), - ) - .unwrap(); - assert_eq!(split_stats, BsonQmActionDecodeStats::default()); - - let div_stats = decode_qm_dividend_stream( - Cursor::new(&[][..]), - opts, - |_| panic!("unexpected dividend on empty input"), - |_, _| panic!("unexpected error on empty input"), - ) - .unwrap(); - assert_eq!(div_stats, BsonQmActionDecodeStats::default()); -} - -#[test] -fn chunk_invariants_hold_across_capacities_including_tiny_headers() { - let mut input = Vec::new(); - let doc_count = 30usize; - for i in 0..doc_count { - input.extend_from_slice(&make_eod_doc( - &format!("CHK{i:03}.US"), - "2024-06-10", - 10.0 + i as f64, - 11.0 + i as f64, - 9.0 + i as f64, - 10.5 + i as f64, - 1_000 + i as i64, - )); - } - - for cap in [1, 2, 3, 4, 5, 64, 256, input.len(), input.len() + 512] { - let mut reader = RawBsonChunkReader::with_options( - FixedStepReader::new(&input, 7), - BsonStreamOptions { - chunk_capacity_bytes: cap, - max_doc_bytes: 4096, - }, - ) - .unwrap(); - - let mut reconstructed = Vec::new(); - let mut expected_offset = 0u64; - let mut total_reframed_docs = 0u64; - - while let Some(chunk) = reader.next_chunk().unwrap() { - assert!(!chunk.bytes.is_empty(), "yielded chunk must be non-empty"); - assert_eq!(chunk.start_offset, expected_offset); - expected_offset += chunk.bytes.len() as u64; - reconstructed.extend_from_slice(chunk.bytes); - - let mut consumed_in_chunk = 0usize; - for item in iter_raw_bson_docs(chunk.bytes) { - let doc = item.expect("chunk must contain only cleanly framed whole docs"); - consumed_in_chunk += doc.as_bytes().len(); - total_reframed_docs += 1; - } - assert_eq!(consumed_in_chunk, chunk.bytes.len()); - } - - assert!(reader.next_chunk().unwrap().is_none()); - assert_eq!(reconstructed, input); - assert_eq!(expected_offset, input.len() as u64); - assert_eq!(reader.bytes_read(), input.len() as u64); - assert_eq!(reader.docs_framed(), doc_count as u64); - assert_eq!(total_reframed_docs, doc_count as u64); - } -} - -#[test] -fn decode_eod_price_stream_matches_buffer_across_readers_and_capacities() { - let fixture = build_mixed_eod_fixture(); - - let mut expected_bars = Vec::new(); - let mut expected_errs = Vec::new(); - let expected_stats = decode_eod_price_buffer( - &fixture, - |bar| { - expected_bars.push(OwnedEodBar { - code: bar.eod_search_code.to_owned(), - session_date: bar.session_date, - open: bar.open.to_bits(), - high: bar.high.to_bits(), - low: bar.low.to_bits(), - close: bar.close.to_bits(), - adj_volume: bar.adj_volume.to_bits(), - }); - }, - |offset, err| expected_errs.push((offset as u64, err)), - ); - assert!(expected_stats.decoded > 0); - assert!(expected_stats.rejected_total() >= 7); - assert_eq!( - expected_stats.decoded + expected_stats.rejected_total(), - expected_stats.docs_in - ); - - let capacities = [64, 256, 512, fixture.len(), fixture.len() + 4096]; - - for &cap in &capacities { - let opts = BsonStreamOptions { - chunk_capacity_bytes: cap, - max_doc_bytes: DEFAULT_MAX_DOC_BYTES, - }; - - let modes: [(&str, Box); 5] = [ - ("1-byte", Box::new(FixedStepReader::new(&fixture, 1))), - ("7-byte", Box::new(FixedStepReader::new(&fixture, 7))), - ("4093-byte", Box::new(FixedStepReader::new(&fixture, 4093))), - ( - "random", - Box::new(RandomInterruptReader::new(&fixture, 0xA11C_E0D1, false)), - ), - ( - "random+EINTR", - Box::new(RandomInterruptReader::new(&fixture, 0xB22D_E0D2, true)), - ), - ]; - - for (label, reader) in modes { - let mut got_bars = Vec::new(); - let mut got_errs = Vec::new(); - let got_stats = decode_eod_price_stream( - reader, - opts, - |bar| { - got_bars.push(OwnedEodBar { - code: bar.eod_search_code.to_owned(), - session_date: bar.session_date, - open: bar.open.to_bits(), - high: bar.high.to_bits(), - low: bar.low.to_bits(), - close: bar.close.to_bits(), - adj_volume: bar.adj_volume.to_bits(), - }); - }, - |offset, err| got_errs.push((offset, err)), - ) - .unwrap_or_else(|e| panic!("cap={cap} mode={label} failed: {e}")); - - assert_eq!(got_stats, expected_stats, "stats mismatch cap={cap} mode={label}"); - assert_eq!(got_bars, expected_bars, "bars mismatch cap={cap} mode={label}"); - assert_eq!(got_errs, expected_errs, "errors mismatch cap={cap} mode={label}"); - } - } -} - -#[test] -fn decode_qm_split_stream_matches_buffer_across_readers_and_capacities() { - let fixture = build_mixed_qm_split_fixture(); - - let mut expected_rows = Vec::new(); - let mut expected_errs = Vec::new(); - let expected_stats = decode_qm_split_buffer( - &fixture, - |s| { - expected_rows.push(OwnedQmSplit { - code: s.qm_search_code.to_owned(), - ex_date: s.ex_date, - ratio: s.ratio.to_bits(), - declared_date: s.declared_date, - }); - }, - |offset, err| expected_errs.push((offset as u64, err)), - ); - assert!(expected_stats.decoded > 0); - assert!(expected_stats.split_noop_ratio_one > 0); - assert!(expected_stats.rejected_total() >= 3); - - for &cap in &[48, 192, fixture.len(), fixture.len() + 1024] { - let opts = BsonStreamOptions { - chunk_capacity_bytes: cap, - max_doc_bytes: DEFAULT_MAX_DOC_BYTES, - }; - let modes: [(&str, Box); 5] = [ - ("1-byte", Box::new(FixedStepReader::new(&fixture, 1))), - ("7-byte", Box::new(FixedStepReader::new(&fixture, 7))), - ("4093-byte", Box::new(FixedStepReader::new(&fixture, 4093))), - ( - "random", - Box::new(RandomInterruptReader::new(&fixture, 0xC33E_5917, false)), - ), - ( - "random+EINTR", - Box::new(RandomInterruptReader::new(&fixture, 0xD44F_5918, true)), - ), - ]; - - for (label, reader) in modes { - let mut got_rows = Vec::new(); - let mut got_errs = Vec::new(); - let got_stats = decode_qm_split_stream( - reader, - opts, - |s| { - got_rows.push(OwnedQmSplit { - code: s.qm_search_code.to_owned(), - ex_date: s.ex_date, - ratio: s.ratio.to_bits(), - declared_date: s.declared_date, - }); - }, - |offset, err| got_errs.push((offset, err)), - ) - .unwrap_or_else(|e| panic!("split cap={cap} mode={label} failed: {e}")); - - assert_eq!(got_stats, expected_stats, "split stats cap={cap} mode={label}"); - assert_eq!(got_rows, expected_rows, "split rows cap={cap} mode={label}"); - assert_eq!(got_errs, expected_errs, "split errs cap={cap} mode={label}"); - } - } -} - -#[test] -fn decode_qm_dividend_stream_matches_buffer_across_readers_and_capacities() { - let fixture = build_mixed_qm_dividend_fixture(); - - let mut expected_rows = Vec::new(); - let mut expected_errs = Vec::new(); - let expected_stats = decode_qm_dividend_buffer( - &fixture, - |d| { - expected_rows.push(OwnedQmDividend { - code: d.qm_search_code.to_owned(), - ex_date: d.ex_date, - cash: d.cash.to_bits(), - currency: d.currency.to_owned(), - declared_date: d.declared_date, - }); - }, - |offset, err| expected_errs.push((offset as u64, err)), - ); - assert!(expected_stats.decoded > 0); - assert!(expected_stats.rejected_total() >= 3); - - for &cap in &[48, 192, fixture.len(), fixture.len() + 1024] { - let opts = BsonStreamOptions { - chunk_capacity_bytes: cap, - max_doc_bytes: DEFAULT_MAX_DOC_BYTES, - }; - let modes: [(&str, Box); 5] = [ - ("1-byte", Box::new(FixedStepReader::new(&fixture, 1))), - ("7-byte", Box::new(FixedStepReader::new(&fixture, 7))), - ("4093-byte", Box::new(FixedStepReader::new(&fixture, 4093))), - ( - "random", - Box::new(RandomInterruptReader::new(&fixture, 0xE550_D171, false)), - ), - ( - "random+EINTR", - Box::new(RandomInterruptReader::new(&fixture, 0xF661_D172, true)), - ), - ]; - - for (label, reader) in modes { - let mut got_rows = Vec::new(); - let mut got_errs = Vec::new(); - let got_stats = decode_qm_dividend_stream( - reader, - opts, - |d| { - got_rows.push(OwnedQmDividend { - code: d.qm_search_code.to_owned(), - ex_date: d.ex_date, - cash: d.cash.to_bits(), - currency: d.currency.to_owned(), - declared_date: d.declared_date, - }); - }, - |offset, err| got_errs.push((offset, err)), - ) - .unwrap_or_else(|e| panic!("dividend cap={cap} mode={label} failed: {e}")); - - assert_eq!(got_stats, expected_stats, "div stats cap={cap} mode={label}"); - assert_eq!(got_rows, expected_rows, "div rows cap={cap} mode={label}"); - assert_eq!(got_errs, expected_errs, "div errs cap={cap} mode={label}"); - } - } -} - -#[test] -fn memory_ceiling_holds_over_one_megabyte_and_oversized_single_doc() { - // 1) >= 1,000,000 bytes of small docs with chunk_capacity_bytes = 4096. - let single_doc = make_eod_doc("MEM.US", "2024-06-10", 10.0, 11.0, 9.5, 10.5, 50_000); - let repeats = (1_050_000 / single_doc.len()) + 1; - let mut big_input = Vec::with_capacity(repeats * single_doc.len()); - for _ in 0..repeats { - big_input.extend_from_slice(&single_doc); - } - assert!(big_input.len() >= 1_000_000); - - let mut reader = RawBsonChunkReader::with_options( - FixedStepReader::new(&big_input, 1009), - BsonStreamOptions { - chunk_capacity_bytes: 4096, - max_doc_bytes: 6000, - }, - ) - .unwrap(); - let mut total_bytes = 0usize; - while let Some(chunk) = reader.next_chunk().unwrap() { - total_bytes += chunk.bytes.len(); - assert!( - reader.buffer_capacity() <= 4096, - "capacity {} exceeded 4096 on small docs", - reader.buffer_capacity() - ); - } - assert_eq!(total_bytes, big_input.len()); - assert_eq!(reader.docs_framed(), repeats as u64); - - // 2) Single doc larger than chunk_capacity_bytes (4096) and equal to exact max_doc_bytes (6000). - let mut oversized = RawDocumentBuf::new(); - oversized.append(cstr!("eodSearchCode"), "BIG.US"); - oversized.append(cstr!("date"), "2024-06-10"); - oversized.append(cstr!("open"), 10.0_f64); - oversized.append(cstr!("high"), 11.0_f64); - oversized.append(cstr!("low"), 9.5_f64); - oversized.append(cstr!("close"), 10.5_f64); - oversized.append(cstr!("volume"), 1_000_i64); - // Pad with an extra string field so the total BSON length equals 6000 bytes exactly. - let base_len = oversized.as_bytes().len(); - // Adding string element "pad" costs: 1 (type) + 4 ("pad\0") + 4 (i32 len) + pad_len + 1 (null). - let pad_len = 6000 - base_len - 10; - oversized.append(cstr!("pad"), "x".repeat(pad_len)); - let oversized_bytes = oversized.into_bytes(); - assert_eq!(oversized_bytes.len(), 6000); - - let mut stream_bytes = Vec::new(); - stream_bytes.extend_from_slice(&single_doc); - stream_bytes.extend_from_slice(&oversized_bytes); - stream_bytes.extend_from_slice(&single_doc); - - let mut oversized_reader = RawBsonChunkReader::with_options( - FixedStepReader::new(&stream_bytes, 331), - BsonStreamOptions { - chunk_capacity_bytes: 4096, - max_doc_bytes: 6000, - }, - ) - .unwrap(); - let mut reconstructed = Vec::new(); - while let Some(chunk) = oversized_reader.next_chunk().unwrap() { - reconstructed.extend_from_slice(chunk.bytes); - assert!( - oversized_reader.buffer_capacity() <= 6000, - "capacity {} exceeded max_doc_bytes 6000", - oversized_reader.buffer_capacity() - ); - } - assert_eq!(reconstructed, stream_bytes); - assert_eq!(oversized_reader.docs_framed(), 3); - assert_eq!(oversized_reader.buffer_capacity(), 6000); -} - -#[test] -fn corrupt_document_length_delivers_valid_prefix_and_is_sticky() { - let valid_doc = make_eod_doc("OK.US", "2024-06-10", 10.0, 11.0, 9.0, 10.5, 100); - let prefix_len = valid_doc.len() as u64; - let max_doc = 512usize; - - for bad_len in [0_i32, 4, -1, i32::MIN, (max_doc as i32) + 1] { - let mut bytes = valid_doc.clone(); - bytes.extend_from_slice(&bad_len.to_le_bytes()); - bytes.extend_from_slice(&[0u8; 16]); - - let mut reader = RawBsonChunkReader::with_options( - Cursor::new(bytes), - BsonStreamOptions { - chunk_capacity_bytes: 256, - max_doc_bytes: max_doc, - }, - ) - .unwrap(); - - // First chunk delivers the valid prefix document intact. - let chunk = reader - .next_chunk() - .expect("valid prefix must succeed") - .expect("expected valid prefix chunk"); - assert_eq!(chunk.start_offset, 0); - assert_eq!(chunk.bytes, valid_doc.as_slice()); - - // Second call surfaces CorruptDocumentLength at exact offset of the bad header. - let err = reader.next_chunk().unwrap_err(); - assert!( - matches!( - err, - BsonStreamError::CorruptDocumentLength { - offset, - declared_len, - max_doc_bytes, - } if offset == prefix_len && declared_len == bad_len && max_doc_bytes == max_doc - ), - "unexpected error for bad_len={bad_len}: {err:?}" - ); - assert!(err.source().is_none()); - assert!(err.to_string().contains(&prefix_len.to_string())); - - // Sticky on repeated calls. - for _ in 0..3 { - assert!(matches!( - reader.next_chunk(), - Err(BsonStreamError::CorruptDocumentLength { offset, declared_len, .. }) - if offset == prefix_len && declared_len == bad_len - )); - } - } -} - -#[test] -fn truncated_header_and_truncated_body_deliver_prefix_and_are_sticky() { - let valid_doc = make_eod_doc("PRE.US", "2024-06-10", 10.0, 11.0, 9.0, 10.5, 100); - let prefix_len = valid_doc.len() as u64; - - // 1) EOF inside the 4-byte length prefix (1, 2, 3 trailing bytes). - for tail_len in [1usize, 2, 3] { - let mut bytes = valid_doc.clone(); - bytes.extend_from_slice(&vec![0x20u8; tail_len]); - - let mut reader = RawBsonChunkReader::with_options( - FixedStepReader::new(&bytes, 13), - BsonStreamOptions { - chunk_capacity_bytes: 256, - max_doc_bytes: 4096, - }, - ) - .unwrap(); - - let chunk = reader.next_chunk().unwrap().unwrap(); - assert_eq!(chunk.bytes, valid_doc.as_slice()); - - let err = reader.next_chunk().unwrap_err(); - assert!( - matches!( - err, - BsonStreamError::TruncatedDocument { - offset, - remaining, - declared_len: None, - } if offset == prefix_len && remaining == tail_len - ), - "unexpected error for tail_len={tail_len}: {err:?}" - ); - assert!(err.to_string().contains(&prefix_len.to_string())); - - // Sticky. - assert!(matches!( - reader.next_chunk(), - Err(BsonStreamError::TruncatedDocument { - offset, - remaining, - declared_len: None, - }) if offset == prefix_len && remaining == tail_len - )); - } - - // 2) EOF mid-document body. - let mut mid_bytes = valid_doc.clone(); - mid_bytes.extend_from_slice(&valid_doc[..valid_doc.len() - 5]); - let expected_remaining = valid_doc.len() - 5; - let expected_declared = valid_doc.len() as i32; - - let mut reader = RawBsonChunkReader::with_options( - FixedStepReader::new(&mid_bytes, 11), - BsonStreamOptions { - chunk_capacity_bytes: 256, - max_doc_bytes: 4096, - }, - ) - .unwrap(); - - let chunk = reader.next_chunk().unwrap().unwrap(); - assert_eq!(chunk.bytes, valid_doc.as_slice()); - - let err = reader.next_chunk().unwrap_err(); - assert!(matches!( - err, - BsonStreamError::TruncatedDocument { - offset, - remaining, - declared_len: Some(declared), - } if offset == prefix_len && remaining == expected_remaining && declared == expected_declared - )); - assert!(err.to_string().contains(&prefix_len.to_string())); - - // Sticky. - assert!(matches!( - reader.next_chunk(), - Err(BsonStreamError::TruncatedDocument { offset, .. }) if offset == prefix_len - )); -} - -#[test] -fn io_error_delivers_valid_prefix_and_is_sticky_without_rereading() { - let valid_doc = make_eod_doc("IO.US", "2024-06-10", 10.0, 11.0, 9.0, 10.5, 100); - let prefix_len = valid_doc.len() as u64; - - // 1) Valid doc followed by partial doc bytes, then BrokenPipe. - let mut partial = valid_doc.clone(); - partial.extend_from_slice(&valid_doc[..10]); - let mut reader = RawBsonChunkReader::with_options( - FailingReader::new(partial, io::ErrorKind::BrokenPipe, "pipe closed"), - BsonStreamOptions { - chunk_capacity_bytes: 512, - max_doc_bytes: 4096, - }, - ) - .unwrap(); - - let chunk = reader.next_chunk().unwrap().unwrap(); - assert_eq!(chunk.bytes, valid_doc.as_slice()); - - let err = reader.next_chunk().unwrap_err(); - assert!(matches!( - err, - BsonStreamError::Io { offset, ref source } - if offset == prefix_len && source.kind() == io::ErrorKind::BrokenPipe - )); - assert!(err.source().is_some()); - assert!(err.to_string().contains("pipe closed")); - - // Sticky: subsequent calls return Io without touching underlying reader again. - for _ in 0..3 { - assert!(matches!( - reader.next_chunk(), - Err(BsonStreamError::Io { offset, ref source }) - if offset == prefix_len && source.kind() == io::ErrorKind::BrokenPipe - )); - } - assert_eq!(reader.into_inner().reads_after_fail, 0); - - // 2) Immediate Io error on first read -> offset 0. - let mut immediate = RawBsonChunkReader::with_options( - FailingReader::new(Vec::new(), io::ErrorKind::PermissionDenied, "denied"), - BsonStreamOptions { - chunk_capacity_bytes: 64, - max_doc_bytes: 4096, - }, - ) - .unwrap(); - assert!(matches!( - immediate.next_chunk(), - Err(BsonStreamError::Io { offset: 0, ref source }) - if source.kind() == io::ErrorKind::PermissionDenied - )); - assert!(matches!( - immediate.next_chunk(), - Err(BsonStreamError::Io { offset: 0, .. }) - )); - assert_eq!(immediate.into_inner().reads_after_fail, 0); -} - -#[test] -fn stats_merge_and_add_assign_sum_all_fields() { - let a = BsonEodDecodeStats { - docs_in: 10, - decoded: 4, - rejected_missing_field: 1, - rejected_empty_field: 1, - rejected_wrong_type: 1, - rejected_malformed_date: 1, - rejected_invalid_number: 1, - rejected_corrupt_document: 1, - }; - let b = BsonEodDecodeStats { - docs_in: 20, - decoded: 8, - rejected_missing_field: 2, - rejected_empty_field: 2, - rejected_wrong_type: 2, - rejected_malformed_date: 2, - rejected_invalid_number: 2, - rejected_corrupt_document: 2, - }; - let mut acc = a; - acc += b; - assert_eq!(acc.docs_in, 30); - assert_eq!(acc.decoded, 12); - assert_eq!(acc.rejected_total(), 18); - assert_eq!(acc.decoded + acc.rejected_total(), acc.docs_in); - - let q1 = BsonQmActionDecodeStats { - docs_in: 12, - decoded: 6, - split_noop_ratio_one: 2, - rejected_missing_field: 1, - rejected_empty_field: 1, - rejected_wrong_type: 1, - rejected_malformed_date: 1, - rejected_invalid_number: 1, - rejected_corrupt_document: 1, - }; - let mut q_acc = q1; - q_acc.merge(&q1); - assert_eq!(q_acc.docs_in, 24); - assert_eq!(q_acc.decoded, 12); - assert_eq!(q_acc.split_noop_ratio_one, 4); - assert_eq!(q_acc.rejected_total(), 12); - assert_eq!(q_acc.decoded + q_acc.rejected_total(), q_acc.docs_in); -} - -#[test] -fn initial_allocation_is_capped_at_max_doc_bytes() { - let max_doc = 1024 * 1024; - let empty_reader = RawBsonChunkReader::with_options( - Cursor::new(&[][..]), - BsonStreamOptions { - chunk_capacity_bytes: DEFAULT_CHUNK_CAPACITY_BYTES, - max_doc_bytes: max_doc, - }, - ) - .expect("chunk_capacity_bytes > max_doc_bytes must succeed with capped buffer"); - assert!( - empty_reader.buffer_capacity() <= max_doc, - "initial capacity {} exceeded max_doc_bytes {max_doc}", - empty_reader.buffer_capacity() - ); - assert_eq!(empty_reader.buffer_capacity(), max_doc); - - // Also verify streaming valid docs when chunk_capacity_bytes > max_doc_bytes. - let doc = make_eod_doc("CAP.US", "2024-06-10", 10.0, 11.0, 9.0, 10.5, 100); - let mut input = Vec::new(); - for _ in 0..8 { - input.extend_from_slice(&doc); - } - let small_max = 256usize; - assert!(doc.len() < small_max); - - let mut reader = RawBsonChunkReader::with_options( - FixedStepReader::new(&input, 37), - BsonStreamOptions { - chunk_capacity_bytes: 4096, - max_doc_bytes: small_max, - }, - ) - .unwrap(); - assert_eq!(reader.buffer_capacity(), small_max); - - let mut reconstructed = Vec::new(); - while let Some(chunk) = reader.next_chunk().unwrap() { - reconstructed.extend_from_slice(chunk.bytes); - assert!(reader.buffer_capacity() <= small_max); - } - assert_eq!(reconstructed, input); - assert_eq!(reader.docs_framed(), 8); - assert!(reader.buffer_capacity() <= small_max); -} - -#[test] -fn corrupt_header_after_valid_doc_stops_fill_without_extra_read() { - struct ScriptedReader { - chunks: Vec>, - idx: usize, - read_calls: usize, - } - - impl Read for ScriptedReader { - fn read(&mut self, buf: &mut [u8]) -> io::Result { - self.read_calls += 1; - if self.idx >= self.chunks.len() { - panic!( - "unexpected extra read #{} after supplying scripted chunks", - self.read_calls - ); - } - let src = &self.chunks[self.idx]; - assert!( - src.len() <= buf.len(), - "scripted chunk ({}) exceeds caller buffer ({})", - src.len(), - buf.len() - ); - buf[..src.len()].copy_from_slice(src); - self.idx += 1; - Ok(src.len()) - } - } - - let valid_doc = make_eod_doc("PIPE.US", "2024-06-10", 10.0, 11.0, 9.0, 10.5, 100); - let prefix_len = valid_doc.len() as u64; - let bad_len = 0_i32; - - // Case 1: single short read supplies both the valid doc and the corrupt 4-byte header. - let mut single_packet = valid_doc.clone(); - single_packet.extend_from_slice(&bad_len.to_le_bytes()); - - let mut reader = RawBsonChunkReader::with_options( - ScriptedReader { - chunks: vec![single_packet], - idx: 0, - read_calls: 0, - }, - BsonStreamOptions { - chunk_capacity_bytes: 4096, - max_doc_bytes: 4096, - }, - ) - .unwrap(); - - let chunk = reader - .next_chunk() - .expect("valid prefix must be yielded immediately") - .expect("expected valid prefix chunk"); - assert_eq!(chunk.start_offset, 0); - assert_eq!(chunk.bytes, valid_doc.as_slice()); - - let err = reader.next_chunk().unwrap_err(); - assert!(matches!( - err, - BsonStreamError::CorruptDocumentLength { - offset, - declared_len, - max_doc_bytes: 4096, - } if offset == prefix_len && declared_len == bad_len - )); - assert_eq!(reader.into_inner().read_calls, 1); - - // Case 2: corrupt header split across two short reads; stops immediately once 4 bytes arrive. - let mut part1 = valid_doc.clone(); - let bad_bytes = (-42_i32).to_le_bytes(); - part1.extend_from_slice(&bad_bytes[..2]); - let part2 = bad_bytes[2..].to_vec(); - - let mut split_reader = RawBsonChunkReader::with_options( - ScriptedReader { - chunks: vec![part1, part2], - idx: 0, - read_calls: 0, - }, - BsonStreamOptions { - chunk_capacity_bytes: 4096, - max_doc_bytes: 4096, - }, - ) - .unwrap(); - - let chunk = split_reader.next_chunk().unwrap().unwrap(); - assert_eq!(chunk.bytes, valid_doc.as_slice()); - let err = split_reader.next_chunk().unwrap_err(); - assert!(matches!( - err, - BsonStreamError::CorruptDocumentLength { - offset, - declared_len: -42, - max_doc_bytes: 4096, - } if offset == prefix_len - )); - assert_eq!(split_reader.into_inner().read_calls, 2); -} - -#[test] -fn eof_is_sticky_and_does_not_reread_source() { - struct CountingEofReader { - data: Vec, - pos: usize, - eof_returned: bool, - reads_after_eof: usize, - } - - impl Read for CountingEofReader { - fn read(&mut self, buf: &mut [u8]) -> io::Result { - if self.eof_returned { - self.reads_after_eof += 1; - return Ok(0); - } - let remaining = self.data.len() - self.pos; - if remaining == 0 { - self.eof_returned = true; - return Ok(0); - } - let take = remaining.min(buf.len()); - buf[..take].copy_from_slice(&self.data[self.pos..self.pos + take]); - self.pos += take; - Ok(take) - } - } - - let doc = make_eod_doc("EOF.US", "2024-06-10", 10.0, 11.0, 9.0, 10.5, 100); - let mut reader = RawBsonChunkReader::with_options( - CountingEofReader { - data: doc.clone(), - pos: 0, - eof_returned: false, - reads_after_eof: 0, - }, - BsonStreamOptions { - chunk_capacity_bytes: 512, - max_doc_bytes: 4096, - }, - ) - .unwrap(); - - let chunk = reader.next_chunk().unwrap().unwrap(); - assert_eq!(chunk.bytes, doc.as_slice()); - assert!(reader.next_chunk().unwrap().is_none()); - for _ in 0..5 { - assert!(reader.next_chunk().unwrap().is_none()); - } - assert_eq!(reader.into_inner().reads_after_eof, 0); -} - -#[test] -fn retries_many_consecutive_interrupted_reads() { - struct BurstInterruptReader<'a> { - data: &'a [u8], - pos: usize, - remaining_interrupts: usize, - } - - impl Read for BurstInterruptReader<'_> { - fn read(&mut self, buf: &mut [u8]) -> io::Result { - if self.remaining_interrupts > 0 { - self.remaining_interrupts -= 1; - return Err(io::Error::new( - io::ErrorKind::Interrupted, - "burst EINTR", - )); - } - let remaining = self.data.len() - self.pos; - if remaining == 0 { - return Ok(0); - } - let take = remaining.min(buf.len()); - buf[..take].copy_from_slice(&self.data[self.pos..self.pos + take]); - self.pos += take; - Ok(take) - } - } - - let doc = make_eod_doc("INTR.US", "2024-06-10", 20.0, 21.0, 19.0, 20.5, 500); - let mut reader = RawBsonChunkReader::with_options( - BurstInterruptReader { - data: &doc, - pos: 0, - remaining_interrupts: 100, - }, - BsonStreamOptions { - chunk_capacity_bytes: 256, - max_doc_bytes: 4096, - }, - ) - .unwrap(); - - let chunk = reader.next_chunk().unwrap().unwrap(); - assert_eq!(chunk.bytes, doc.as_slice()); - assert!(reader.next_chunk().unwrap().is_none()); - assert_eq!(reader.docs_framed(), 1); - assert_eq!(reader.bytes_read(), doc.len() as u64); -} - -#[test] -fn exact_single_doc_buffer_yields_one_doc_per_chunk_without_growing() { - let doc = make_eod_doc("EXACT.US", "2024-06-10", 10.0, 11.0, 9.0, 10.5, 100); - let doc_len = doc.len(); - let count = 12usize; - let mut input = Vec::with_capacity(doc_len * count); - for _ in 0..count { - input.extend_from_slice(&doc); - } - - let mut reader = RawBsonChunkReader::with_options( - FixedStepReader::new(&input, 19), - BsonStreamOptions { - chunk_capacity_bytes: doc_len, - max_doc_bytes: 4096, - }, - ) - .unwrap(); - assert_eq!(reader.buffer_capacity(), doc_len); - - let mut chunks = 0usize; - while let Some(chunk) = reader.next_chunk().unwrap() { - assert_eq!(chunk.bytes, doc.as_slice()); - assert_eq!(chunk.start_offset, (chunks * doc_len) as u64); - assert_eq!(reader.buffer_capacity(), doc_len); - chunks += 1; - } - assert_eq!(chunks, count); - assert_eq!(reader.docs_framed(), count as u64); -} - -#[test] -fn declared_length_one_over_max_rejects_without_growing_or_extra_read() { - struct HeaderOnlyReader { - header: [u8; 4], - sent: bool, - reads: usize, - } - - impl Read for HeaderOnlyReader { - fn read(&mut self, buf: &mut [u8]) -> io::Result { - self.reads += 1; - if self.sent { - panic!("unexpected read #{} after sending oversized header", self.reads); - } - self.sent = true; - let take = 4.min(buf.len()); - buf[..take].copy_from_slice(&self.header[..take]); - Ok(take) - } - } - - let max_doc = 512usize; - let over_len = (max_doc + 1) as i32; - let mut reader = RawBsonChunkReader::with_options( - HeaderOnlyReader { - header: over_len.to_le_bytes(), - sent: false, - reads: 0, - }, - BsonStreamOptions { - chunk_capacity_bytes: 64, - max_doc_bytes: max_doc, - }, - ) - .unwrap(); - assert_eq!(reader.buffer_capacity(), 64); - - let err = reader.next_chunk().unwrap_err(); - assert!(matches!( - err, - BsonStreamError::CorruptDocumentLength { - offset: 0, - declared_len, - max_doc_bytes, - } if declared_len == over_len && max_doc_bytes == max_doc - )); - assert_eq!(reader.buffer_capacity(), 64); - assert_eq!(reader.into_inner().reads, 1); -} - -#[test] -fn oversized_truncated_document_reports_declared_len_within_memory_limit() { - let max_doc = 2048usize; - let declared_len = 1500i32; - let mut truncated = Vec::with_capacity(900); - truncated.extend_from_slice(&declared_len.to_le_bytes()); - truncated.resize(900, 0x11); - - let mut reader = RawBsonChunkReader::with_options( - FixedStepReader::new(&truncated, 127), - BsonStreamOptions { - chunk_capacity_bytes: 256, - max_doc_bytes: max_doc, - }, - ) - .unwrap(); - - let err = reader.next_chunk().unwrap_err(); - assert!(matches!( - err, - BsonStreamError::TruncatedDocument { - offset: 0, - remaining: 900, - declared_len: Some(1500), - } - )); - assert!( - reader.buffer_capacity() <= max_doc, - "capacity {} exceeded max_doc_bytes {max_doc}", - reader.buffer_capacity() - ); -} - -#[test] -fn stream_helpers_deliver_prefix_rows_before_terminal_error() { - let eod_doc = make_eod_doc("PRE1.US", "2024-06-10", 10.0, 11.0, 9.0, 10.5, 100); - let split_doc = { - let mut d = RawDocumentBuf::new(); - d.append(cstr!("qmSearchCode"), "SPL1"); - d.append(cstr!("date"), "2024-06-10"); - d.append(cstr!("splitratio"), 2.0_f64); - d.into_bytes() - }; - let div_doc = { - let mut d = RawDocumentBuf::new(); - d.append(cstr!("qmSearchCode"), "DIV1"); - d.append(cstr!("date"), "2024-06-10"); - d.append(cstr!("amount"), 0.5_f64); - d.append(cstr!("currency"), "USD"); - d.into_bytes() - }; - - let opts = BsonStreamOptions { - chunk_capacity_bytes: 512, - max_doc_bytes: 4096, - }; - - // 1) Truncated tail after valid prefix. - { - let mut bytes = eod_doc.clone(); - bytes.extend_from_slice(&eod_doc[..10]); - let mut seen = 0usize; - let err = decode_eod_price_stream(Cursor::new(bytes), opts, |_| seen += 1, |_, _| {}) - .unwrap_err(); - assert_eq!(seen, 1); - assert!(matches!( - err, - BsonStreamError::TruncatedDocument { offset, remaining: 10, .. } - if offset == eod_doc.len() as u64 - )); - } - { - let mut bytes = split_doc.clone(); - bytes.extend_from_slice(&split_doc[..6]); - let mut seen = 0usize; - let err = decode_qm_split_stream(Cursor::new(bytes), opts, |_| seen += 1, |_, _| {}) - .unwrap_err(); - assert_eq!(seen, 1); - assert!(matches!( - err, - BsonStreamError::TruncatedDocument { offset, remaining: 6, .. } - if offset == split_doc.len() as u64 - )); - } - { - let mut bytes = div_doc.clone(); - bytes.extend_from_slice(&[1, 2]); - let mut seen = 0usize; - let err = decode_qm_dividend_stream(Cursor::new(bytes), opts, |_| seen += 1, |_, _| {}) - .unwrap_err(); - assert_eq!(seen, 1); - assert!(matches!( - err, - BsonStreamError::TruncatedDocument { offset, remaining: 2, declared_len: None } - if offset == div_doc.len() as u64 - )); - } - - // 2) I/O error after valid prefix. - { - let mut seen = 0usize; - let err = decode_eod_price_stream( - FailingReader::new(eod_doc.clone(), io::ErrorKind::ConnectionReset, "reset"), - opts, - |_| seen += 1, - |_, _| {}, - ) - .unwrap_err(); - assert_eq!(seen, 1); - assert!(matches!( - err, - BsonStreamError::Io { offset, ref source } - if offset == eod_doc.len() as u64 && source.kind() == io::ErrorKind::ConnectionReset - )); - } - { - let mut seen = 0usize; - let err = decode_qm_split_stream( - FailingReader::new(split_doc.clone(), io::ErrorKind::ConnectionReset, "reset"), - opts, - |_| seen += 1, - |_, _| {}, - ) - .unwrap_err(); - assert_eq!(seen, 1); - assert!(matches!( - err, - BsonStreamError::Io { offset, .. } if offset == split_doc.len() as u64 - )); - } - { - let mut seen = 0usize; - let err = decode_qm_dividend_stream( - FailingReader::new(div_doc.clone(), io::ErrorKind::ConnectionReset, "reset"), - opts, - |_| seen += 1, - |_, _| {}, - ) - .unwrap_err(); - assert_eq!(seen, 1); - assert!(matches!( - err, - BsonStreamError::Io { offset, .. } if offset == div_doc.len() as u64 - )); - } - - // 3) Corrupt length header after valid prefix. - { - let mut bytes = eod_doc.clone(); - bytes.extend_from_slice(&3_i32.to_le_bytes()); - let mut seen = 0usize; - let err = decode_eod_price_stream(Cursor::new(bytes), opts, |_| seen += 1, |_, _| {}) - .unwrap_err(); - assert_eq!(seen, 1); - assert!(matches!( - err, - BsonStreamError::CorruptDocumentLength { offset, declared_len: 3, .. } - if offset == eod_doc.len() as u64 - )); - } - { - let mut bytes = split_doc.clone(); - bytes.extend_from_slice(&(-7_i32).to_le_bytes()); - let mut seen = 0usize; - let err = decode_qm_split_stream(Cursor::new(bytes), opts, |_| seen += 1, |_, _| {}) - .unwrap_err(); - assert_eq!(seen, 1); - assert!(matches!( - err, - BsonStreamError::CorruptDocumentLength { offset, declared_len: -7, .. } - if offset == split_doc.len() as u64 - )); - } - { - let mut bytes = div_doc.clone(); - bytes.extend_from_slice(&(5000_i32).to_le_bytes()); - let mut seen = 0usize; - let err = decode_qm_dividend_stream(Cursor::new(bytes), opts, |_| seen += 1, |_, _| {}) - .unwrap_err(); - assert_eq!(seen, 1); - assert!(matches!( - err, - BsonStreamError::CorruptDocumentLength { offset, declared_len: 5000, .. } - if offset == div_doc.len() as u64 - )); - } -} - -#[test] -fn stream_helpers_reject_invalid_options_before_reading() { - struct PanicOnRead; - impl Read for PanicOnRead { - fn read(&mut self, _buf: &mut [u8]) -> io::Result { - panic!("reader must not be read when options are invalid"); - } - } - - let bad_cap = BsonStreamOptions { - chunk_capacity_bytes: 0, - max_doc_bytes: DEFAULT_MAX_DOC_BYTES, - }; - let bad_max = BsonStreamOptions { - chunk_capacity_bytes: 64, - max_doc_bytes: 4, - }; - - assert!(matches!( - decode_eod_price_stream(PanicOnRead, bad_cap, |_| {}, |_, _| {}), - Err(BsonStreamError::InvalidChunkCapacity) - )); - assert!(matches!( - decode_eod_price_stream(PanicOnRead, bad_max, |_| {}, |_, _| {}), - Err(BsonStreamError::InvalidMaxDocBytes) - )); - assert!(matches!( - decode_qm_split_stream(PanicOnRead, bad_cap, |_| {}, |_, _| {}), - Err(BsonStreamError::InvalidChunkCapacity) - )); - assert!(matches!( - decode_qm_split_stream(PanicOnRead, bad_max, |_| {}, |_, _| {}), - Err(BsonStreamError::InvalidMaxDocBytes) - )); - assert!(matches!( - decode_qm_dividend_stream(PanicOnRead, bad_cap, |_| {}, |_, _| {}), - Err(BsonStreamError::InvalidChunkCapacity) - )); - assert!(matches!( - decode_qm_dividend_stream(PanicOnRead, bad_max, |_| {}, |_, _| {}), - Err(BsonStreamError::InvalidMaxDocBytes) - )); -} - -#[test] -fn randomized_buffer_and_read_size_sweep_matches_buffer_decoder() { - let fixture = build_mixed_eod_fixture(); - - let mut expected_bars = Vec::new(); - let mut expected_errs = Vec::new(); - let expected_stats = decode_eod_price_buffer( - &fixture, - |bar| { - expected_bars.push(OwnedEodBar { - code: bar.eod_search_code.to_owned(), - session_date: bar.session_date, - open: bar.open.to_bits(), - high: bar.high.to_bits(), - low: bar.low.to_bits(), - close: bar.close.to_bits(), - adj_volume: bar.adj_volume.to_bits(), - }); - }, - |offset, err| expected_errs.push((offset as u64, err)), - ); - - let mut rng = SplitMix64::new(0x5EED_6464_B501_2026); - for case in 0..64 { - let cap = (rng.next_u64() as usize % (fixture.len() + 256)) + 1; - let step = (rng.next_u64() as usize % 512) + 1; - let opts = BsonStreamOptions { - chunk_capacity_bytes: cap, - max_doc_bytes: DEFAULT_MAX_DOC_BYTES, - }; - - let mut got_bars = Vec::new(); - let mut got_errs = Vec::new(); - let got_stats = decode_eod_price_stream( - FixedStepReader::new(&fixture, step), - opts, - |bar| { - got_bars.push(OwnedEodBar { - code: bar.eod_search_code.to_owned(), - session_date: bar.session_date, - open: bar.open.to_bits(), - high: bar.high.to_bits(), - low: bar.low.to_bits(), - close: bar.close.to_bits(), - adj_volume: bar.adj_volume.to_bits(), - }); - }, - |offset, err| got_errs.push((offset, err)), - ) - .unwrap_or_else(|e| panic!("case {case} (cap={cap}, step={step}) failed: {e}")); - - assert_eq!(got_stats, expected_stats, "case {case} stats mismatch"); - assert_eq!(got_bars, expected_bars, "case {case} bars mismatch"); - assert_eq!(got_errs, expected_errs, "case {case} errs mismatch"); - } -} - -#[test] -fn ceo_posts_chunks_match_buffer_across_small_chunks_and_respect_timestamp_unit() { - use super::{decode_ceo_posts_chunks, BsonStreamOptions, RawBsonChunkReader}; - use crate::bson_ceo_posts::{ - decode_ceo_posts_buffer, CeoPostsFieldNames, CeoPostsTimestampUnit, - }; - use crate::posts::CeoPost; - - let fields = CeoPostsFieldNames::default(); - - let mut fixture = Vec::new(); - for i in 0..40_i32 { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("ceoId"), format!("CEO{i}")); - doc.append(cstr!("spielId"), format!("sp-{i}")); - let ts_secs = 1_710_000_000_i64 + i64::from(i) * 60; - if i % 4 == 0 { - // BSON DateTime (always epoch milliseconds regardless of unit) - doc.append( - cstr!("timestamp"), - bson::DateTime::from_millis(ts_secs * 1_000), - ); - } else if i % 4 == 1 { - doc.append(cstr!("timestamp"), ts_secs); - } else if i % 4 == 2 { - doc.append(cstr!("timestamp"), ts_secs as f64); - } else { - doc.append(cstr!("timestamp"), ts_secs as i32); - } - - if i % 6 == 0 { - // Edited with numeric timestamp - doc.append(cstr!("edited"), ts_secs + 120); - } else if i % 6 == 1 { - // Edited with BSON DateTime - doc.append( - cstr!("edited"), - bson::DateTime::from_millis((ts_secs + 180) * 1_000), - ); - } else if i % 6 == 2 { - // Zero sentinel -> unedited - doc.append(cstr!("edited"), 0_i32); - } else if i % 6 == 3 { - // Semantic skip: invalid edited value (boolean true) - doc.append(cstr!("edited"), true); - } - - if i % 5 == 0 { - doc.append(cstr!("bot"), "1"); - } else if i % 5 == 1 { - doc.append(cstr!("bot"), false); - } - doc.append(cstr!("userId"), format!("user-{i}")); - if i % 9 == 0 { - // Semantic skip: wrong text type - doc.append(cstr!("spiel"), 123_i32); - } else { - doc.append(cstr!("spiel"), format!("post body #{i}")); - } - fixture.extend_from_slice(doc.as_bytes()); - } - - let to_owned = |p: CeoPost<&str>| CeoPost { - key: p.key.to_owned(), - spiel_id: p.spiel_id, - timestamp_ms: p.timestamp_ms, - edited_ms: p.edited_ms, - bot: p.bot, - user_id: p.user_id, - text: p.text, - }; - - for unit in [CeoPostsTimestampUnit::Seconds, CeoPostsTimestampUnit::Millis] { - let mut expected_rows = Vec::new(); - let expected_stats = decode_ceo_posts_buffer(&fixture, &fields, unit, |p| { - expected_rows.push(to_owned(p)); - }) - .expect("buffer decode"); - assert!(expected_stats.rows_out > 0); - assert!(expected_stats.skipped_total() > 0); - - // Tiny capacities and small read steps splitting reads within documents, plus single-chunk. - for (cap, step) in [(17, 7), (64, 19), (128, 37), (fixture.len() + 64, fixture.len())] { - let opts = BsonStreamOptions { - chunk_capacity_bytes: cap, - max_doc_bytes: 4096, - }; - let mut reader = - RawBsonChunkReader::with_options(FixedStepReader::new(&fixture, step), opts) - .unwrap(); - let mut got_rows = Vec::new(); - let got_stats = decode_ceo_posts_chunks(&mut reader, &fields, unit, |p| { - got_rows.push(to_owned(p)); - }) - .expect("chunk decode"); - - assert_eq!(got_stats, expected_stats, "unit={unit:?} cap={cap}"); - assert_eq!(got_rows, expected_rows, "unit={unit:?} cap={cap}"); - assert_eq!(reader.docs_framed() as usize, expected_stats.docs_in); - assert!( - reader.buffer_capacity() <= 4096.max(fixture.len() + 64), - "capacity {} exceeded expected bound", - reader.buffer_capacity() - ); - } - } - - // Explicitly verify 1,000x difference for numeric posting & edit timestamps and unit - // independence for BSON DateTime. - let mut unit_fixture = Vec::new(); - let numeric_ts = 1_710_000_123_i64; - let numeric_ed = 1_710_000_456_i64; - let dt_ts_ms = 1_710_000_789_000_i64; - let dt_ed_ms = 1_710_000_999_000_i64; - { - let mut d_num = RawDocumentBuf::new(); - d_num.append(cstr!("ceoId"), "NUM"); - d_num.append(cstr!("spielId"), "sp-num"); - d_num.append(cstr!("timestamp"), numeric_ts); - d_num.append(cstr!("edited"), numeric_ed); - d_num.append(cstr!("spiel"), "numeric"); - unit_fixture.extend_from_slice(d_num.as_bytes()); - - let mut d_dt = RawDocumentBuf::new(); - d_dt.append(cstr!("ceoId"), "DT"); - d_dt.append(cstr!("spielId"), "sp-dt"); - d_dt.append(cstr!("timestamp"), bson::DateTime::from_millis(dt_ts_ms)); - d_dt.append(cstr!("edited"), bson::DateTime::from_millis(dt_ed_ms)); - d_dt.append(cstr!("spiel"), "datetime"); - unit_fixture.extend_from_slice(d_dt.as_bytes()); - } - - let decode_unit = |unit: CeoPostsTimestampUnit| -> Vec> { - let mut rows = Vec::new(); - let mut reader = RawBsonChunkReader::with_options( - FixedStepReader::new(&unit_fixture, 11), - BsonStreamOptions { - chunk_capacity_bytes: 32, - max_doc_bytes: 4096, - }, - ) - .unwrap(); - decode_ceo_posts_chunks(&mut reader, &fields, unit, |p| rows.push(to_owned(p))) - .expect("decode unit fixture"); - rows - }; - - let rows_sec = decode_unit(CeoPostsTimestampUnit::Seconds); - let rows_ms = decode_unit(CeoPostsTimestampUnit::Millis); - assert_eq!(rows_sec.len(), 2); - assert_eq!(rows_ms.len(), 2); - - // Numeric doc: Seconds is 1,000x Millis for both timestamp and edited. - assert_eq!(rows_ms[0].timestamp_ms, numeric_ts); - assert_eq!(rows_sec[0].timestamp_ms, numeric_ts * 1_000); - assert_eq!(rows_ms[0].edited_ms, Some(numeric_ed)); - assert_eq!(rows_sec[0].edited_ms, Some(numeric_ed * 1_000)); - - // DateTime doc: identical under both Seconds and Millis. - assert_eq!(rows_ms[1].timestamp_ms, dt_ts_ms); - assert_eq!(rows_sec[1].timestamp_ms, dt_ts_ms); - assert_eq!(rows_ms[1].edited_ms, Some(dt_ed_ms)); - assert_eq!(rows_sec[1].edited_ms, Some(dt_ed_ms)); -} - -#[test] -fn ceo_posts_stream_rebases_corrupt_bson_offset_and_rejects_invalid_fields() { - use super::{ - decode_ceo_posts_chunks, decode_ceo_posts_stream, BsonCeoPostsStreamError, - BsonStreamError, BsonStreamOptions, RawBsonChunkReader, - }; - use crate::bson_ceo_posts::{BsonCeoPostsError, CeoPostsFieldNames, CeoPostsTimestampUnit}; - - // Duplicate field role rejected before reading. - let bad_fields = CeoPostsFieldNames { - key: "ceoId", - spiel_id: "ceoId", - ..CeoPostsFieldNames::default() - }; - assert!(matches!( - decode_ceo_posts_stream( - Cursor::new(Vec::::new()), - BsonStreamOptions::default(), - &bad_fields, - CeoPostsTimestampUnit::Millis, - |_| {}, - ), - Err(BsonCeoPostsStreamError::Decode( - BsonCeoPostsError::InvalidFieldNames { .. } - )) - )); - - let fields = CeoPostsFieldNames::default(); - let mut good = RawDocumentBuf::new(); - good.append(cstr!("ceoId"), "RY"); - good.append(cstr!("spielId"), "sp-1"); - good.append(cstr!("timestamp"), 1_710_460_800_000_i64); - good.append(cstr!("spiel"), "ok"); - let good_bytes = good.into_bytes(); - - let mut corrupt = RawDocumentBuf::new(); - corrupt.append(cstr!("ceoId"), "TD"); - corrupt.append(cstr!("z"), 1_i32); - let mut corrupt_bytes = corrupt.into_bytes(); - let z_pos = corrupt_bytes - .windows(3) - .position(|w| w == [0x10, b'z', 0x00]) - .expect("locate z"); - corrupt_bytes[z_pos] = 0x7e; - - let mut combined = Vec::new(); - combined.extend_from_slice(&good_bytes); - combined.extend_from_slice(&good_bytes); - let expected_offset = combined.len() as u64; - combined.extend_from_slice(&corrupt_bytes); - - // Chunk capacity == one doc forces the corrupt doc into a subsequent chunk. - let opts = BsonStreamOptions { - chunk_capacity_bytes: good_bytes.len(), - max_doc_bytes: 4096, - }; - let mut reader = RawBsonChunkReader::with_options(Cursor::new(combined), opts).unwrap(); - let err = decode_ceo_posts_chunks( - &mut reader, - &fields, - CeoPostsTimestampUnit::Millis, - |_| {}, - ) - .unwrap_err(); - assert!( - matches!( - err, - BsonCeoPostsStreamError::Decode(BsonCeoPostsError::CorruptBson { offset, .. }) - if offset == expected_offset - ), - "expected rebased CorruptBson at {expected_offset}, got {err:?}" - ); - - // Truncated trailing document preserves RawBsonChunkReader's absolute offset. - let mut truncated = Vec::new(); - truncated.extend_from_slice(&good_bytes); - let trunc_offset = truncated.len() as u64; - truncated.extend_from_slice(&64_i32.to_le_bytes()); - truncated.extend_from_slice(&[0x02, b'a', 0x00]); - let err = decode_ceo_posts_stream( - Cursor::new(truncated), - opts, - &fields, - CeoPostsTimestampUnit::Millis, - |_| {}, - ) - .unwrap_err(); - assert!( - matches!( - err, - BsonCeoPostsStreamError::Stream(BsonStreamError::TruncatedDocument { offset, .. }) - if offset == trunc_offset - ), - "expected TruncatedDocument at {trunc_offset}, got {err:?}" - ); -} - -#[test] -fn ceo_shorts_stream_matches_buffer_across_small_chunks_and_preserves_bounded_capacity() { - use super::{decode_ceo_shorts_chunks, BsonStreamOptions, RawBsonChunkReader}; - use crate::bson_ceo_shorts::{ - decode_ceo_shorts_buffer, CeoShortsFieldNames, DEFAULT_KEY_FIELD, - DEFAULT_REPORT_DATE_FIELD, - }; - - let fields = CeoShortsFieldNames { - key: DEFAULT_KEY_FIELD, - report_date: DEFAULT_REPORT_DATE_FIELD, - shares_short: "sharesShort", - net_change: Some("netChange"), - pct_float: Some("pctFloat"), - }; - - let mut fixture = Vec::new(); - for i in 0..40_i32 { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("symbol"), format!("SYM{i}")); - let day_secs = (19_700_i64 + i64::from(i) * 15) * 86_400; - if i % 3 == 0 { - doc.append( - cstr!("timestamp"), - bson::DateTime::from_millis(day_secs * 1_000), - ); - } else if i % 3 == 1 { - doc.append(cstr!("timestamp"), day_secs); - } else { - doc.append(cstr!("timestamp"), (day_secs * 1_000) as f64); - } - if i % 10 == 0 { - // semantic skip: wrong shares type - doc.append(cstr!("sharesShort"), "not_a_number"); - } else { - doc.append(cstr!("sharesShort"), 10_000 + i * 250); - } - if i % 5 == 0 { - doc.append(cstr!("netChange"), "wrong"); - } else { - doc.append(cstr!("netChange"), (i - 10) as f64); - } - doc.append(cstr!("pctFloat"), 0.5 + f64::from(i) * 0.01); - fixture.extend_from_slice(doc.as_bytes()); - } - - let mut expected_rows = Vec::new(); - let expected_stats = decode_ceo_shorts_buffer(&fixture, &fields, |r| { - expected_rows.push(( - r.key.to_owned(), - r.report_date, - r.shares_short.to_bits(), - r.net_change.map(f64::to_bits), - r.pct_float.map(f64::to_bits), - )); - }) - .expect("buffer decode"); - - for cap in [64usize, 128, 1024] { - let opts = BsonStreamOptions { - chunk_capacity_bytes: cap, - max_doc_bytes: 4096, - }; - let mut reader = - RawBsonChunkReader::with_options(FixedStepReader::new(&fixture, 37), opts).unwrap(); - let mut got_rows = Vec::new(); - let got_stats = decode_ceo_shorts_chunks(&mut reader, &fields, |r| { - got_rows.push(( - r.key.to_owned(), - r.report_date, - r.shares_short.to_bits(), - r.net_change.map(f64::to_bits), - r.pct_float.map(f64::to_bits), - )); - }) - .expect("chunk decode"); - - assert_eq!(got_stats, expected_stats, "cap={cap}"); - assert_eq!(got_rows, expected_rows, "cap={cap}"); - assert!( - reader.buffer_capacity() <= 4096, - "capacity {} exceeded max_doc_bytes", - reader.buffer_capacity() - ); - } -} - -#[test] -fn ceo_shorts_stream_rebases_corrupt_bson_offset_and_rejects_invalid_fields() { - use super::{decode_ceo_shorts_stream, BsonCeoShortsStreamError, BsonStreamOptions}; - use crate::bson_ceo_shorts::{BsonCeoShortsError, CeoShortsFieldNames}; - - let bad_fields = CeoShortsFieldNames { - key: "symbol", - report_date: "symbol", - shares_short: "sharesShort", - net_change: None, - pct_float: None, - }; - assert!(matches!( - decode_ceo_shorts_stream(Cursor::new(Vec::::new()), BsonStreamOptions::default(), &bad_fields, |_| {}), - Err(BsonCeoShortsStreamError::Decode(BsonCeoShortsError::InvalidFieldNames { .. })) - )); - - let fields = CeoShortsFieldNames { - key: "symbol", - report_date: "timestamp", - shares_short: "sharesShort", - net_change: None, - pct_float: None, - }; - - let mut good = RawDocumentBuf::new(); - good.append(cstr!("symbol"), "RY"); - good.append(cstr!("timestamp"), 1_710_460_800_i64); - good.append(cstr!("sharesShort"), 1000_i32); - let good_bytes = good.into_bytes(); - - let mut corrupt = RawDocumentBuf::new(); - corrupt.append(cstr!("symbol"), "TD"); - corrupt.append(cstr!("z"), 1_i32); - let mut corrupt_bytes = corrupt.into_bytes(); - let z_pos = corrupt_bytes - .windows(3) - .position(|w| w == [0x10, b'z', 0x00]) - .expect("locate z"); - corrupt_bytes[z_pos] = 0x7e; - - let mut combined = Vec::new(); - combined.extend_from_slice(&good_bytes); - combined.extend_from_slice(&good_bytes); - let expected_offset = combined.len() as u64; - combined.extend_from_slice(&corrupt_bytes); - - let opts = BsonStreamOptions { - chunk_capacity_bytes: good_bytes.len(), - max_doc_bytes: 4096, - }; - let err = decode_ceo_shorts_stream(Cursor::new(combined), opts, &fields, |_| {}).unwrap_err(); - assert!( - matches!( - err, - BsonCeoShortsStreamError::Decode(BsonCeoShortsError::CorruptBson { offset, .. }) - if offset == expected_offset - ), - "expected rebased CorruptBson at {expected_offset}, got {err:?}" - ); -} - -#[test] -fn qm_filings_and_earnings_stream_match_buffer_and_rebase_corrupt_offsets() { - use super::{ - decode_qm_earnings_chunks, decode_qm_earnings_stream, decode_qm_filings_chunks, - decode_qm_filings_stream, BsonQmEventsStreamError, BsonStreamOptions, RawBsonChunkReader, - }; - use crate::bson_qm_events::{ - decode_qm_earning_buffer, decode_qm_filing_buffer, BsonQmEventsError, - QmEarningsFieldNames, QmFilingsFieldNames, - }; - - let f_fields = QmFilingsFieldNames { - key: "symbol", - timefiled: "timefiled", - form_type: "formtype", - filing_id: Some("filingId"), - url: Some("url"), - }; - let e_fields = QmEarningsFieldNames { - key: "qmSearchCode", - report_date: "reportDate", - announce_time: "announceTime", - fiscal_period_end: Some("periodEndDate"), - actual_eps: Some("actualEps"), - revenue: Some("revenue"), - }; - - let mut filings_buf = Vec::new(); - let mut earnings_buf = Vec::new(); - for i in 0..30_i32 { - let mut fdoc = RawDocumentBuf::new(); - fdoc.append(cstr!("symbol"), format!("SYM{}", i % 5)); - fdoc.append(cstr!("timefiled"), format!("2025-01-{:02}T10:00:00 EST", 1 + (i % 20))); - if i % 9 == 0 { - fdoc.append(cstr!("formtype"), 99_i32); // semantic skip - } else { - fdoc.append(cstr!("formtype"), if i % 2 == 0 { "8-K" } else { "10-Q" }); - } - fdoc.append(cstr!("filingId"), format!("F-{i}")); - fdoc.append(cstr!("url"), format!("https://example.test/{i}")); - filings_buf.extend_from_slice(fdoc.as_bytes()); - - let mut edoc = RawDocumentBuf::new(); - edoc.append(cstr!("qmSearchCode"), format!("SYM{}", i % 5)); - if i % 2 == 0 { - edoc.append(cstr!("reportDate"), format!("2025-01-{:02}", 1 + (i % 20))); - } else { - let ms = (20_089_i64 + i64::from(i % 20)) * 86_400_000; - edoc.append(cstr!("reportDate"), bson::DateTime::from_millis(ms)); - } - if i % 10 == 0 { - edoc.append(cstr!("announceTime"), ""); // semantic skip - } else { - edoc.append(cstr!("announceTime"), if i % 3 == 0 { "N/A" } else { "AMC" }); - } - edoc.append(cstr!("actualEps"), 1.25 + f64::from(i) * 0.1); - edoc.append(cstr!("consensusEps"), 999.0_f64); - earnings_buf.extend_from_slice(edoc.as_bytes()); - } - - let mut exp_filings = Vec::new(); - let exp_f_stats = decode_qm_filing_buffer(&filings_buf, &f_fields, |r| { - exp_filings.push(r.to_qm_filing(r.key.to_owned())); - }) - .expect("filings buffer decode"); - - let mut exp_earnings = Vec::new(); - let exp_e_stats = decode_qm_earning_buffer(&earnings_buf, &e_fields, |r| { - exp_earnings.push(r.to_qm_earning(r.key.to_owned())); - }) - .expect("earnings buffer decode"); - - for cap in [96usize, 256, 1024] { - let opts = BsonStreamOptions { - chunk_capacity_bytes: cap, - max_doc_bytes: 4096, - }; - let mut f_reader = - RawBsonChunkReader::with_options(FixedStepReader::new(&filings_buf, 29), opts).unwrap(); - let mut got_filings = Vec::new(); - let got_f_stats = decode_qm_filings_chunks(&mut f_reader, &f_fields, |r| { - got_filings.push(r.to_qm_filing(r.key.to_owned())); - }) - .expect("filings chunk decode"); - assert_eq!(got_f_stats, exp_f_stats, "filings cap={cap}"); - assert_eq!(got_filings, exp_filings, "filings rows cap={cap}"); - - let mut e_reader = - RawBsonChunkReader::with_options(FixedStepReader::new(&earnings_buf, 31), opts).unwrap(); - let mut got_earnings = Vec::new(); - let got_e_stats = decode_qm_earnings_chunks(&mut e_reader, &e_fields, |r| { - got_earnings.push(r.to_qm_earning(r.key.to_owned())); - }) - .expect("earnings chunk decode"); - assert_eq!(got_e_stats, exp_e_stats, "earnings cap={cap}"); - assert_eq!(got_earnings, exp_earnings, "earnings rows cap={cap}"); - } - - // Corrupt BSON mid-stream rebases offset accurately for both filings and earnings streams. - let mut good_f = RawDocumentBuf::new(); - good_f.append(cstr!("symbol"), "AAPL"); - good_f.append(cstr!("timefiled"), "2025-01-31T06:01:27 EST"); - good_f.append(cstr!("formtype"), "10-K"); - let good_f_bytes = good_f.into_bytes(); - - let mut corrupt = RawDocumentBuf::new(); - corrupt.append(cstr!("symbol"), "BAD"); - corrupt.append(cstr!("z"), 1_i32); - let mut corrupt_bytes = corrupt.into_bytes(); - let z_pos = corrupt_bytes - .windows(3) - .position(|w| w == [0x10, b'z', 0x00]) - .expect("locate z"); - corrupt_bytes[z_pos] = 0x7e; - - let mut combined = Vec::new(); - combined.extend_from_slice(&good_f_bytes); - combined.extend_from_slice(&good_f_bytes); - let expected_offset = combined.len() as u64; - combined.extend_from_slice(&corrupt_bytes); - - let opts = BsonStreamOptions { - chunk_capacity_bytes: good_f_bytes.len(), - max_doc_bytes: 4096, - }; - let err_f = decode_qm_filings_stream(Cursor::new(combined.clone()), opts, &f_fields, |_| {}) - .unwrap_err(); - assert!(matches!( - err_f, - BsonQmEventsStreamError::Decode(BsonQmEventsError::CorruptBson { offset, .. }) - if offset == expected_offset - )); - - let err_e = - decode_qm_earnings_stream(Cursor::new(combined), opts, &e_fields, |_| {}).unwrap_err(); - assert!(matches!( - err_e, - BsonQmEventsStreamError::Decode(BsonQmEventsError::CorruptBson { offset, .. }) - if offset == expected_offset - )); -} - -#[test] -fn decode_qm_price_stream_matches_buffer_rebases_offsets_and_fails_on_framing() { - let make_doc = |code: &str, date: &str, vol: f64| -> Vec { - let mut d = RawDocumentBuf::new(); - d.append(cstr!("qmSearchCode"), code); - d.append(cstr!("date"), date); - d.append(cstr!("sharevolume"), vol); - d.into_bytes() - }; - - let mut fixture = Vec::new(); - fixture.extend_from_slice(&make_doc("NVDA", "2024-06-07", 41_239_000.0)); - - let mut bad_type = RawDocumentBuf::new(); - bad_type.append(cstr!("qmSearchCode"), "AAPL"); - bad_type.append(cstr!("date"), "2024-06-07"); - bad_type.append(cstr!("sharevolume"), "bad"); - fixture.extend_from_slice(&bad_type.into_bytes()); - - let mut int_doc = RawDocumentBuf::new(); - int_doc.append(cstr!("qmSearchCode"), "RY:CA"); - int_doc.append(cstr!("date"), "2024-06-07"); - int_doc.append(cstr!("sharevolume"), 2_500_000_i64); - fixture.extend_from_slice(&int_doc.into_bytes()); - - // Corrupt element inside a cleanly framed document to verify CorruptBson offset rebasing. - let mut corrupt = RawDocumentBuf::new(); - corrupt.append(cstr!("qmSearchCode"), "BAD"); - corrupt.append(cstr!("date"), "2024-06-07"); - corrupt.append(cstr!("sharevolume"), 100.0_f64); - corrupt.append(cstr!("z"), 1_i32); - let mut corrupt_bytes = corrupt.into_bytes(); - let z_pos = corrupt_bytes - .windows(3) - .position(|w| w == [0x10, b'z', 0x00]) - .expect("locate z"); - corrupt_bytes[z_pos] = 0x7e; - let corrupt_offset = fixture.len() as u64; - fixture.extend_from_slice(&corrupt_bytes); - - fixture.extend_from_slice(&make_doc("SHOP:CA", "2024-06-10", 1_234_567.0)); - - let mut expected_rows = Vec::new(); - let mut expected_errs = Vec::new(); - let expected_stats = decode_qm_price_buffer( - &fixture, - |p| expected_rows.push((p.qm_search_code.to_owned(), p.session_date, p.share_volume.to_bits())), - |off, err| expected_errs.push((off as u64, err)), - ); - assert_eq!(expected_stats.docs_in, 5); - assert_eq!(expected_stats.decoded, 3); - assert_eq!(expected_stats.rejected_total(), 2); - - for cap in [1, 17, 64, 512] { - let opts = BsonStreamOptions { - chunk_capacity_bytes: cap, - max_doc_bytes: 4096, - }; - let mut got_rows = Vec::new(); - let mut got_errs = Vec::new(); - let got_stats = decode_qm_price_stream( - FixedStepReader::new(&fixture, 7), - opts, - |p| got_rows.push((p.qm_search_code.to_owned(), p.session_date, p.share_volume.to_bits())), - |off, err| got_errs.push((off, err)), - ) - .unwrap(); - - assert_eq!(got_stats, expected_stats); - assert_eq!(got_rows, expected_rows); - assert_eq!(got_errs.len(), expected_errs.len()); - for ((g_off, g_err), (e_off, e_err)) in got_errs.iter().zip(&expected_errs) { - assert_eq!(g_off, e_off); - assert_eq!(g_err, e_err); - } - assert!(matches!( - got_errs[1], - (off, BsonQmPriceError::CorruptBson { offset, .. }) - if off == corrupt_offset && offset as u64 == corrupt_offset - )); - } - - // Truncated trailing document must fail closed with BsonStreamError::TruncatedDocument. - let mut truncated = fixture.clone(); - truncated.extend_from_slice(&100_i32.to_le_bytes()); - truncated.extend_from_slice(&[0x02, b'a', 0x00]); - let err = decode_qm_price_stream( - Cursor::new(&truncated), - BsonStreamOptions { - chunk_capacity_bytes: 64, - max_doc_bytes: 4096, - }, - |_| {}, - |_, _| {}, - ) - .unwrap_err(); - assert!(matches!(err, BsonStreamError::TruncatedDocument { .. })); -} - -#[test] -fn decode_eod_intraday_chunks_and_stream_match_buffer_and_rebase_offsets() { - let make_doc = |code: &str, ts: i64, open: f64, close: f64, vol: f64| -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), code); - doc.append(cstr!("timestamp"), ts); - doc.append(cstr!("open"), open); - doc.append(cstr!("high"), open.max(close) + 0.5); - doc.append(cstr!("low"), open.min(close) - 0.5); - doc.append(cstr!("close"), close); - doc.append(cstr!("volume"), vol); - doc.into_bytes() - }; - - let mut fixture = Vec::new(); - fixture.extend_from_slice(&make_doc("NVDA.US", 1_717_767_000, 120.0, 120.5, 1000.0)); - fixture.extend_from_slice(&make_doc("AAPL.US", 1_717_767_060, 195.0, 195.25, 0.0)); - - // Semantic error: invalid timestamp (negative) - let bad_ts_offset = fixture.len() as u64; - fixture.extend_from_slice(&make_doc("NVDA.US", -60, 120.0, 120.5, 100.0)); - - // Valid length-framed doc with corrupt trailing terminator -> CorruptBson with embedded offset - let mut corrupt_bytes = make_doc("MSFT.US", 1_717_767_120, 420.0, 421.0, 500.0); - *corrupt_bytes.last_mut().unwrap() = 0xEE; - let corrupt_offset = fixture.len() as u64; - fixture.extend_from_slice(&corrupt_bytes); - - fixture.extend_from_slice(&make_doc("SHOP.TO", 1_717_767_180, 88.0, 88.4, 2500.0)); - - let mut expected_rows = Vec::new(); - let mut expected_errs = Vec::new(); - let expected_stats = decode_eod_intraday_buffer( - &fixture, - |b| { - expected_rows.push(( - b.eod_search_code.to_owned(), - b.ts, - b.open.to_bits(), - b.high.to_bits(), - b.low.to_bits(), - b.close.to_bits(), - b.volume.to_bits(), - )) - }, - |off, err| expected_errs.push((off as u64, err)), - ); - assert_eq!(expected_stats.docs_seen, 5); - assert_eq!(expected_stats.rows_decoded, 3); - assert_eq!(expected_stats.rejected_invalid_timestamp, 1); - assert_eq!(expected_stats.rejected_corrupt_document, 1); - assert_eq!(expected_stats.rejected_total(), 2); - - // Exercise decode_eod_intraday_stream across small capacities and short reads splitting - // length prefixes and document bodies. - for (cap, step) in [(1, 1), (3, 2), (17, 3), (64, 7), (512, 13)] { - let opts = BsonStreamOptions { - chunk_capacity_bytes: cap, - max_doc_bytes: 4096, - }; - let mut got_rows = Vec::new(); - let mut got_errs = Vec::new(); - let got_stats = decode_eod_intraday_stream( - FixedStepReader::new(&fixture, step), - opts, - |b| { - got_rows.push(( - b.eod_search_code.to_owned(), - b.ts, - b.open.to_bits(), - b.high.to_bits(), - b.low.to_bits(), - b.close.to_bits(), - b.volume.to_bits(), - )) - }, - |off, err| got_errs.push((off, err)), - ) - .unwrap(); - - assert_eq!(got_stats, expected_stats); - assert_eq!(got_rows, expected_rows); - assert_eq!(got_errs, expected_errs); - assert_eq!(got_errs[0].0, bad_ts_offset); - assert!(matches!( - got_errs[1], - (off, BsonEodIntradayError::CorruptBson { offset, .. }) - if off == corrupt_offset && offset as u64 == corrupt_offset - )); - } - - // Exercise decode_eod_intraday_chunks directly with random read sizes and EINTR interrupts. - let opts = BsonStreamOptions { - chunk_capacity_bytes: 32, - max_doc_bytes: 4096, - }; - let mut chunk_reader = - RawBsonChunkReader::with_options(RandomInterruptReader::new(&fixture, 0x141, true), opts) - .unwrap(); - let mut chunk_rows = Vec::new(); - let mut chunk_errs = Vec::new(); - let chunk_stats = decode_eod_intraday_chunks( - &mut chunk_reader, - |b| { - chunk_rows.push(( - b.eod_search_code.to_owned(), - b.ts, - b.open.to_bits(), - b.high.to_bits(), - b.low.to_bits(), - b.close.to_bits(), - b.volume.to_bits(), - )) - }, - |off, err| chunk_errs.push((off, err)), - ) - .unwrap(); - assert_eq!(chunk_stats, expected_stats); - assert_eq!(chunk_rows, expected_rows); - assert_eq!(chunk_errs, expected_errs); - - // Truncated trailing document must deliver the complete prefix first and then return - // BsonStreamError::TruncatedDocument at the exact tail offset. - let mut truncated = fixture.clone(); - let trunc_offset = truncated.len() as u64; - truncated.extend_from_slice(&120_i32.to_le_bytes()); - truncated.extend_from_slice(&[0x02, b'a', 0x00]); - let mut prefix_rows = Vec::new(); - let mut prefix_errs = Vec::new(); - let err = decode_eod_intraday_stream( - FixedStepReader::new(&truncated, 5), - BsonStreamOptions { - chunk_capacity_bytes: 32, - max_doc_bytes: 4096, - }, - |b| { - prefix_rows.push(( - b.eod_search_code.to_owned(), - b.ts, - b.open.to_bits(), - b.high.to_bits(), - b.low.to_bits(), - b.close.to_bits(), - b.volume.to_bits(), - )) - }, - |off, e| prefix_errs.push((off, e)), - ) - .unwrap_err(); - assert_eq!(prefix_rows, expected_rows); - assert_eq!(prefix_errs, expected_errs); - assert!(matches!( - err, - BsonStreamError::TruncatedDocument { - offset, - remaining: 7, - declared_len: Some(120), - } if offset == trunc_offset - )); -} - -#[test] -fn decode_qm_intraday_chunks_and_stream_match_buffer_and_rebase_offsets() { - let make_doc = |code: &str, ts_ms: i64, open: f64, close: f64, vol: f64| -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), code); - doc.append(cstr!("timestamp"), DateTime::from_millis(ts_ms)); - doc.append(cstr!("open"), open); - doc.append(cstr!("high"), open.max(close) + 0.5); - doc.append(cstr!("low"), open.min(close) - 0.5); - doc.append(cstr!("close"), close); - doc.append(cstr!("sharevolume"), vol); - // Include adjusted fields that must be validated and ignored. - doc.append(cstr!("adjustedopen"), open / 10.0); - doc.append(cstr!("adjustedclose"), close / 10.0); - doc.append(cstr!("avolume"), vol * 10.0); - doc.into_bytes() - }; - - // Empty input returns zeroed stats with zero callbacks. - { - let mut empty_rows = 0usize; - let mut empty_errs = 0usize; - let stats = decode_qm_intraday_stream( - Cursor::new(Vec::::new()), - BsonStreamOptions::default(), - |_| empty_rows += 1, - |_, _| empty_errs += 1, - ) - .unwrap(); - assert_eq!(stats, BsonQmIntradayDecodeStats::default()); - assert_eq!(empty_rows, 0); - assert_eq!(empty_errs, 0); - } - - let mut fixture = Vec::new(); - fixture.extend_from_slice(&make_doc("NVDA", 1_717_767_000_000, 1200.0, 1205.0, 1_000.0)); - fixture.extend_from_slice(&make_doc("AAPL", 1_717_767_060_000, 195.0, 195.25, 0.0)); - - // Semantic error: invalid timestamp (negative DateTime millis). - let bad_ts_offset = fixture.len() as u64; - fixture.extend_from_slice(&make_doc("NVDA", -60_000, 1200.0, 1205.0, 100.0)); - - // Valid length-framed doc with corrupt trailing terminator -> CorruptBson with embedded offset. - let mut corrupt_bytes = make_doc("MSFT", 1_717_767_120_000, 420.0, 421.0, 500.0); - *corrupt_bytes.last_mut().unwrap() = 0xEE; - let corrupt_offset = fixture.len() as u64; - fixture.extend_from_slice(&corrupt_bytes); - - fixture.extend_from_slice(&make_doc("SHOP:CA", 1_717_767_180_000, 88.0, 88.4, 2_500.0)); - - let mut expected_rows = Vec::new(); - let mut expected_errs = Vec::new(); - let expected_stats = decode_qm_intraday_buffer( - &fixture, - |b| { - expected_rows.push(( - b.qm_search_code.to_owned(), - b.ts, - b.open.to_bits(), - b.high.to_bits(), - b.low.to_bits(), - b.close.to_bits(), - b.volume.to_bits(), - )) - }, - |off, err| expected_errs.push((off as u64, err)), - ); - assert_eq!(expected_stats.docs_seen, 5); - assert_eq!(expected_stats.rows_decoded, 3); - assert_eq!(expected_stats.rejected_invalid_timestamp, 1); - assert_eq!(expected_stats.rejected_corrupt_document, 1); - assert_eq!(expected_stats.rejected_total(), 2); - - // Exercise decode_qm_intraday_stream across small capacities and short reads splitting - // length prefixes and document bodies. - for (cap, step) in [(1, 1), (3, 2), (17, 3), (64, 7), (512, 13)] { - let opts = BsonStreamOptions { - chunk_capacity_bytes: cap, - max_doc_bytes: 4096, - }; - let mut got_rows = Vec::new(); - let mut got_errs = Vec::new(); - let got_stats = decode_qm_intraday_stream( - FixedStepReader::new(&fixture, step), - opts, - |b| { - got_rows.push(( - b.qm_search_code.to_owned(), - b.ts, - b.open.to_bits(), - b.high.to_bits(), - b.low.to_bits(), - b.close.to_bits(), - b.volume.to_bits(), - )) - }, - |off, err| got_errs.push((off, err)), - ) - .unwrap(); - - assert_eq!(got_stats, expected_stats); - assert_eq!(got_rows, expected_rows); - assert_eq!(got_errs, expected_errs); - assert_eq!(got_errs[0].0, bad_ts_offset); - assert!(matches!( - got_errs[1], - (off, BsonQmIntradayError::CorruptBson { offset, .. }) - if off == corrupt_offset && offset as u64 == corrupt_offset - )); - } - - // Exercise decode_qm_intraday_chunks directly with random read sizes and EINTR interrupts. - let opts = BsonStreamOptions { - chunk_capacity_bytes: 32, - max_doc_bytes: 4096, - }; - let mut chunk_reader = - RawBsonChunkReader::with_options(RandomInterruptReader::new(&fixture, 0x152, true), opts) - .unwrap(); - let mut chunk_rows = Vec::new(); - let mut chunk_errs = Vec::new(); - let chunk_stats = decode_qm_intraday_chunks( - &mut chunk_reader, - |b| { - chunk_rows.push(( - b.qm_search_code.to_owned(), - b.ts, - b.open.to_bits(), - b.high.to_bits(), - b.low.to_bits(), - b.close.to_bits(), - b.volume.to_bits(), - )) - }, - |off, err| chunk_errs.push((off, err)), - ) - .unwrap(); - assert_eq!(chunk_stats, expected_stats); - assert_eq!(chunk_rows, expected_rows); - assert_eq!(chunk_errs, expected_errs); - - // Truncated trailing document must deliver the complete prefix first and then return - // BsonStreamError::TruncatedDocument at the exact tail offset. - let mut truncated = fixture.clone(); - let trunc_offset = truncated.len() as u64; - truncated.extend_from_slice(&120_i32.to_le_bytes()); - truncated.extend_from_slice(&[0x02, b'a', 0x00]); - let mut prefix_rows = Vec::new(); - let mut prefix_errs = Vec::new(); - let err = decode_qm_intraday_stream( - FixedStepReader::new(&truncated, 5), - BsonStreamOptions { - chunk_capacity_bytes: 32, - max_doc_bytes: 4096, - }, - |b| { - prefix_rows.push(( - b.qm_search_code.to_owned(), - b.ts, - b.open.to_bits(), - b.high.to_bits(), - b.low.to_bits(), - b.close.to_bits(), - b.volume.to_bits(), - )) - }, - |off, e| prefix_errs.push((off, e)), - ) - .unwrap_err(); - assert_eq!(prefix_rows, expected_rows); - assert_eq!(prefix_errs, expected_errs); - assert!(matches!( - err, - BsonStreamError::TruncatedDocument { - offset, - remaining: 7, - declared_len: Some(120), - } if offset == trunc_offset - )); -} - -#[allow(clippy::too_many_arguments)] -fn make_qm_financials_doc( - key: Option<&str>, - period_end: &str, - report_date: Option<&str>, - report_period: &str, - currency: &str, - revenue: Option, - net_income_str: Option<&str>, - total_assets: Option, -) -> Vec { - let mut doc = RawDocumentBuf::new(); - if let Some(k) = key { - doc.append(cstr!("qmSearchCode"), k); - } - doc.append(cstr!("periodEndDate"), period_end); - if let Some(rd) = report_date { - doc.append(cstr!("reportDate"), rd); - } - doc.append(cstr!("reportPeriod"), report_period); - doc.append(cstr!("currency"), currency); - - let mut income = RawDocumentBuf::new(); - if let Some(rev) = revenue { - income.append(cstr!("revenue"), rev); - } - if let Some(ni) = net_income_str { - income.append(cstr!("netIncome"), ni); - } - doc.append(cstr!("IncomeStatement"), income); - - let mut balance = RawDocumentBuf::new(); - if let Some(assets) = total_assets { - balance.append(cstr!("totalAssets"), assets); - } - doc.append(cstr!("BalanceSheet"), balance); - - doc.into_bytes() -} - -fn sample_qm_financials_fields() -> QmFinancialsFieldNames<'static> { - QmFinancialsFieldNames::with_verified_defaults( - "currency", - Some("IncomeStatement.revenue"), - Some("IncomeStatement.netIncome"), - None, - Some("BalanceSheet.totalAssets"), - None, - None, - ) -} - -fn owned_financial_obs(obs: FinancialObservation<&str>) -> FinancialObservation { - FinancialObservation { - key: obs.key.to_owned(), - period_end: obs.period_end, - fiscal_period: obs.fiscal_period, - currency: obs.currency, - report_date: obs.report_date, - fields: obs.fields, - } -} - -#[test] -fn qm_financials_chunks_match_buffer_across_small_chunks() { - let fields = sample_qm_financials_fields(); - let fiscal = QmFinancialsFiscalPeriod::ByTokens { - quarterly: &["Q1", "Q2", "Q3", "Q4"], - annual: &["FY"], - }; - - // Empty input returns zeroed stats and zero rows. - { - let mut empty_rows = 0usize; - let stats = decode_qm_financials_stream( - Cursor::new(Vec::::new()), - BsonStreamOptions::default(), - &fields, - fiscal, - |_| empty_rows += 1, - ) - .unwrap(); - assert_eq!(stats, BsonQmFinancialsDecodeStats::default()); - assert_eq!(empty_rows, 0); - } - - let mut fixture = Vec::new(); - // 1. Valid quarterly row with all configured metrics present. - fixture.extend_from_slice(&make_qm_financials_doc( - Some("NVDA"), - "2024-03-31", - Some("2024-05-01"), - "Q1", - "USD", - Some(100.0), - Some("25.5"), - Some(500.0), - )); - // 2. Semantic skip: missing key. - fixture.extend_from_slice(&make_qm_financials_doc( - None, - "2024-06-30", - Some("2024-08-01"), - "Q2", - "USD", - Some(120.0), - Some("30.0"), - Some(520.0), - )); - // 3. Valid annual row with nullable metric (unparsable netIncome + missing totalAssets). - fixture.extend_from_slice(&make_qm_financials_doc( - Some("SHOP:CA"), - "2024-12-31", - None, - "FY", - "CAD", - Some(450.0), - Some("not-a-number"), - None, - )); - // 4. Semantic skip: unmapped report_period token. - fixture.extend_from_slice(&make_qm_financials_doc( - Some("NVDA"), - "2024-09-30", - Some("2024-11-01"), - "SEMIANNUAL", - "USD", - Some(130.0), - Some("32.0"), - Some(540.0), - )); - // 5. Valid quarterly row. - fixture.extend_from_slice(&make_qm_financials_doc( - Some("NVDA"), - "2024-06-30", - Some("2024-08-02"), - "Q2", - "USD", - Some(140.0), - Some("35.0"), - Some(560.0), - )); - - let mut expected_rows = Vec::new(); - let expected_stats = decode_qm_financials_buffer(&fixture, &fields, fiscal, |obs| { - expected_rows.push(owned_financial_obs(obs)); - }) - .unwrap(); - assert_eq!(expected_stats.docs_in, 5); - assert_eq!(expected_stats.rows_out, 3); - assert_eq!(expected_stats.skipped_missing_key, 1); - assert_eq!(expected_stats.skipped_unmapped_report_period, 1); - assert_eq!(expected_stats.nulled_unparsable_string, 1); - assert_eq!(expected_stats.nulled_missing_path, 1); - - // Force multiple chunks via small chunk_capacity_bytes and short reads. - for (cap, step) in [(1, 1), (3, 2), (32, 7), (128, 17), (256, 29)] { - let opts = BsonStreamOptions { - chunk_capacity_bytes: cap, - max_doc_bytes: 4096, - }; - let mut got_rows = Vec::new(); - let got_stats = decode_qm_financials_stream( - FixedStepReader::new(&fixture, step), - opts, - &fields, - fiscal, - |obs| got_rows.push(owned_financial_obs(obs)), - ) - .unwrap(); - assert_eq!(got_stats, expected_stats); - assert_eq!(got_rows, expected_rows); - } - - // Exercise decode_qm_financials_chunks directly with random read sizes and EINTR interrupts. - let mut chunk_reader = RawBsonChunkReader::with_options( - RandomInterruptReader::new(&fixture, 0xF1A7, true), - BsonStreamOptions { - chunk_capacity_bytes: 64, - max_doc_bytes: 4096, - }, - ) - .unwrap(); - let mut chunk_rows = Vec::new(); - let chunk_stats = - decode_qm_financials_chunks(&mut chunk_reader, &fields, fiscal, |obs| { - chunk_rows.push(owned_financial_obs(obs)); - }) - .unwrap(); - assert_eq!(chunk_stats, expected_stats); - assert_eq!(chunk_rows, expected_rows); - assert_eq!(chunk_reader.docs_framed(), 5); - assert_eq!(chunk_reader.bytes_read(), fixture.len() as u64); -} - -#[test] -fn qm_financials_stream_rebases_later_chunk_corruption() { - let fields = sample_qm_financials_fields(); - let fiscal = QmFinancialsFiscalPeriod::ByTokens { - quarterly: &["Q1", "Q2"], - annual: &["FY"], - }; - - let doc1 = make_qm_financials_doc( - Some("NVDA"), - "2024-03-31", - Some("2024-05-01"), - "Q1", - "USD", - Some(100.0), - Some("20.0"), - Some(400.0), - ); - let doc2 = make_qm_financials_doc( - Some("NVDA"), - "2024-06-30", - Some("2024-08-01"), - "Q2", - "USD", - Some(110.0), - Some("22.0"), - Some(420.0), - ); - let mut corrupt_doc3 = make_qm_financials_doc( - Some("NVDA"), - "2024-09-30", - Some("2024-11-01"), - "Q3", - "USD", - Some(120.0), - Some("24.0"), - Some(440.0), - ); - // Corrupt an element type byte while preserving the 4-byte length prefix and trailing 0x00. - // Byte 4 is the type tag of the first element ("qmSearchCode"); 0x7E is an invalid BSON type. - corrupt_doc3[4] = 0x7E; - - let mut fixture = Vec::new(); - fixture.extend_from_slice(&doc1); - fixture.extend_from_slice(&doc2); - let corrupt_offset = fixture.len() as u64; - fixture.extend_from_slice(&corrupt_doc3); - - // Small chunk capacity guarantees corrupt_doc3 lands in a later chunk (start_offset > 0). - let opts = BsonStreamOptions { - chunk_capacity_bytes: doc1.len(), - max_doc_bytes: 4096, - }; - let mut seen_rows = Vec::new(); - let err = decode_qm_financials_stream( - FixedStepReader::new(&fixture, 11), - opts, - &fields, - fiscal, - |obs| seen_rows.push(owned_financial_obs(obs)), - ) - .unwrap_err(); - - assert_eq!(seen_rows.len(), 2); - assert!( - matches!( - err, - BsonQmFinancialsStreamError::Decode(BsonQmFinancialsError::CorruptBson { offset, .. }) - if offset == corrupt_offset - ), - "expected rebased CorruptBson at offset {corrupt_offset}, got: {err}" - ); - assert!(err.source().is_some()); -} - -#[test] -fn qm_financials_stream_rejects_invalid_config_before_read() { - struct PanicOnRead; - impl Read for PanicOnRead { - fn read(&mut self, _buf: &mut [u8]) -> io::Result { - panic!("reader must not be read when config validation fails"); - } - } - - let valid_fields = sample_qm_financials_fields(); - let valid_fiscal = QmFinancialsFiscalPeriod::ByTokens { - quarterly: &["Q1"], - annual: &["FY"], - }; - - // 1. Invalid dotted path (consecutive dot / empty segment). - let bad_fields = QmFinancialsFieldNames::with_verified_defaults( - "currency", - Some("IncomeStatement..revenue"), - None, - None, - None, - None, - None, - ); - let err = decode_qm_financials_stream( - PanicOnRead, - BsonStreamOptions::default(), - &bad_fields, - valid_fiscal, - |_| {}, - ) - .unwrap_err(); - assert!(matches!( - err, - BsonQmFinancialsStreamError::Decode(BsonQmFinancialsError::InvalidFieldNames { .. }) - )); - - let mut chunk_reader = RawBsonChunkReader::new(PanicOnRead); - let err = decode_qm_financials_chunks(&mut chunk_reader, &bad_fields, valid_fiscal, |_| {}) - .unwrap_err(); - assert!(matches!( - err, - BsonQmFinancialsStreamError::Decode(BsonQmFinancialsError::InvalidFieldNames { .. }) - )); - - // 2. Blank token in ByTokens. - let blank_token_fiscal = QmFinancialsFiscalPeriod::ByTokens { - quarterly: &["Q1", " "], - annual: &["FY"], - }; - let err = decode_qm_financials_stream( - PanicOnRead, - BsonStreamOptions::default(), - &valid_fields, - blank_token_fiscal, - |_| {}, - ) - .unwrap_err(); - assert!(matches!( - err, - BsonQmFinancialsStreamError::Decode(BsonQmFinancialsError::InvalidFiscalPeriodConfig { .. }) - )); - - // 3. Overlapping token between quarterly and annual. - let overlap_fiscal = QmFinancialsFiscalPeriod::ByTokens { - quarterly: &["Q1", "FY"], - annual: &["FY"], - }; - let err = decode_qm_financials_stream( - PanicOnRead, - BsonStreamOptions::default(), - &valid_fields, - overlap_fiscal, - |_| {}, - ) - .unwrap_err(); - assert!(matches!( - err, - BsonQmFinancialsStreamError::Decode(BsonQmFinancialsError::InvalidFiscalPeriodConfig { .. }) - )); - - let mut chunk_reader = RawBsonChunkReader::new(PanicOnRead); - let err = - decode_qm_financials_chunks(&mut chunk_reader, &valid_fields, overlap_fiscal, |_| {}) - .unwrap_err(); - assert!(matches!( - err, - BsonQmFinancialsStreamError::Decode(BsonQmFinancialsError::InvalidFiscalPeriodConfig { .. }) - )); -} - -#[derive(Debug, PartialEq, Eq)] -struct OwnedTeDataPoint { - te_symbol: String, - country: String, - category: String, - period_date: i32, - value_bits: u64, -} - -fn owned_te_data_point(p: TeDataPoint<'_>) -> OwnedTeDataPoint { - OwnedTeDataPoint { - te_symbol: p.te_symbol.to_owned(), - country: p.country.to_owned(), - category: p.category.to_owned(), - period_date: p.period_date, - value_bits: p.value.to_bits(), - } -} - -fn make_te_data_doc( - te_symbol: Option<&str>, - country: &str, - category: &str, - data_points: &[(&str, f64)], - forecast_points: &[(&str, f64)], -) -> Vec { - let mut doc = RawDocumentBuf::new(); - if let Some(sym) = te_symbol { - doc.append(cstr!("teSymbol"), sym); - } - doc.append(cstr!("country"), country); - doc.append(cstr!("category"), category); - - let mut data_arr = RawArrayBuf::new(); - for &(d, v) in data_points { - let mut pt = RawDocumentBuf::new(); - pt.append(cstr!("d"), d); - pt.append(cstr!("v"), v); - data_arr.push(pt); - } - doc.append(cstr!("data"), data_arr); - - if !forecast_points.is_empty() { - let mut fc_arr = RawArrayBuf::new(); - for &(d, v) in forecast_points { - let mut pt = RawDocumentBuf::new(); - pt.append(cstr!("d"), d); - pt.append(cstr!("v"), v); - fc_arr.push(pt); - } - doc.append(cstr!("forecast"), fc_arr); - } - - doc.into_bytes() -} - -#[test] -fn te_data_stream_and_chunks_match_buffer_across_tiny_chunks_and_short_reads() { - let mut fixture = Vec::new(); - fixture.extend_from_slice(&make_te_data_doc( - Some("USACPI"), - "United States", - "Inflation Rate", - &[("2024-01-31", 3.1), ("2024-02-29", 3.2)], - &[("2025-06-30", 2.4)], - )); - fixture.extend_from_slice(&make_te_data_doc( - Some("CACPI"), - "Canada", - "Inflation Rate", - &[("2024-01-31", 2.9), ("2024-02-29", 2.8), ("2024-03-31", 2.9)], - &[], - )); - // Include a rejected doc (missing teSymbol) and a doc with a bad point date + valid trailing point. - fixture.extend_from_slice(&make_te_data_doc( - None, - "United States", - "GDP", - &[("2024-03-31", 2.1)], - &[], - )); - fixture.extend_from_slice(&make_te_data_doc( - Some("USAGDP"), - "United States", - "GDP Growth Rate", - &[("2024-01-31", 1.6), ("2023-02-29", 9.9), ("2024-06-30", 3.0)], - &[("2025-12-31", 2.0)], - )); - fixture.extend_from_slice(&make_te_data_doc( - Some("CAPOLICY"), - "Canada", - "Interest Rate", - &[("2024-06-05", 4.75)], - &[], - )); - - let mut expected_points = Vec::new(); - let mut expected_errs = Vec::new(); - let expected_stats = decode_te_data_buffer( - &fixture, - |p| expected_points.push(owned_te_data_point(p)), - |off, err| expected_errs.push((off as u64, err)), - ); - assert_eq!(expected_stats.docs_in, 5); - assert_eq!(expected_stats.docs_accepted, 4); - assert_eq!(expected_stats.docs_rejected_total(), 1); - assert_eq!(expected_stats.points_in, 9); - assert_eq!(expected_stats.points_decoded, 8); - assert_eq!(expected_stats.rejected_total(), 1); - assert_eq!( - expected_stats.docs_in, - expected_stats.docs_accepted + expected_stats.docs_rejected_total() - ); - assert_eq!( - expected_stats.points_in, - expected_stats.points_decoded + expected_stats.rejected_total() - ); - - // Tiny chunk capacities force multiple whole-document chunks; short FixedStepReader splits - // both 4-byte length prefixes and document bodies across reads. - let max_doc_bytes = 4096; - for (cap, step) in [(1, 1), (3, 2), (17, 3), (64, 7), (128, 17)] { - let opts = BsonStreamOptions { - chunk_capacity_bytes: cap, - max_doc_bytes, - }; - let mut got_points = Vec::new(); - let mut got_errs = Vec::new(); - let got_stats = decode_te_data_stream( - FixedStepReader::new(&fixture, step), - opts, - |p| got_points.push(owned_te_data_point(p)), - |off, err| got_errs.push((off, err)), - ) - .unwrap_or_else(|e| panic!("teData stream cap={cap} step={step} failed: {e}")); - - assert_eq!(got_stats, expected_stats, "stats mismatch cap={cap} step={step}"); - assert_eq!(got_points, expected_points, "points mismatch cap={cap} step={step}"); - assert_eq!(got_errs, expected_errs, "errors mismatch cap={cap} step={step}"); - } - - // Exercise decode_te_data_chunks directly with tiny buffer + FixedStepReader and verify - // buffer_capacity stays within max_doc_bytes. - let chunk_opts = BsonStreamOptions { - chunk_capacity_bytes: 32, - max_doc_bytes, - }; - let mut chunk_reader = RawBsonChunkReader::with_options( - RandomInterruptReader::new(&fixture, 0x7E_DA7A, true), - chunk_opts, - ) - .unwrap(); - let mut chunk_points = Vec::new(); - let mut chunk_errs = Vec::new(); - let chunk_stats = decode_te_data_chunks( - &mut chunk_reader, - |p| chunk_points.push(owned_te_data_point(p)), - |off, err| chunk_errs.push((off, err)), - ) - .unwrap(); - assert_eq!(chunk_stats, expected_stats); - assert_eq!(chunk_points, expected_points); - assert_eq!(chunk_errs, expected_errs); - assert!(chunk_reader.buffer_capacity() <= max_doc_bytes); - assert_eq!(chunk_reader.docs_framed(), 5); - assert_eq!(chunk_reader.bytes_read(), fixture.len() as u64); -} - -#[test] -fn te_data_stream_later_chunk_rejects_continue_with_absolute_offsets() { - let doc1 = make_te_data_doc( - Some("USACPI"), - "United States", - "Inflation Rate", - &[("2024-01-31", 3.1)], - &[], - ); - let doc2_missing_sym = make_te_data_doc( - None, - "United States", - "Unemployment Rate", - &[("2024-01-31", 3.7)], - &[], - ); - let doc3_bad_point = make_te_data_doc( - Some("CACPI"), - "Canada", - "Inflation Rate", - &[ - ("2024-01-31", 2.9), - ("not-a-date", 99.0), - ("2024-03-31", 2.8), - ], - &[], - ); - let doc4_trailing_valid = make_te_data_doc( - Some("USAGDP"), - "United States", - "GDP Growth Rate", - &[("2024-06-30", 3.0)], - &[], - ); - - let mut fixture = Vec::new(); - fixture.extend_from_slice(&doc1); - let missing_sym_offset = fixture.len() as u64; - assert!(missing_sym_offset > 0); - fixture.extend_from_slice(&doc2_missing_sym); - let bad_point_doc_offset = fixture.len() as u64; - assert!(bad_point_doc_offset > missing_sym_offset); - fixture.extend_from_slice(&doc3_bad_point); - fixture.extend_from_slice(&doc4_trailing_valid); - - // chunk_capacity_bytes == doc1.len() guarantees doc2 and doc3 start in non-first chunks. - let opts = BsonStreamOptions { - chunk_capacity_bytes: doc1.len(), - max_doc_bytes: 4096, - }; - let mut points = Vec::new(); - let mut errs = Vec::new(); - let stats = decode_te_data_stream( - FixedStepReader::new(&fixture, 9), - opts, - |p| points.push(owned_te_data_point(p)), - |off, err| errs.push((off, err)), - ) - .unwrap(); - - // Valid prefix, valid point before and after bad point, and trailing valid doc all emit. - assert_eq!(points.len(), 4); - assert_eq!(points[0].te_symbol, "USACPI"); - assert_eq!(points[1].te_symbol, "CACPI"); - assert_eq!(points[1].value_bits, 2.9_f64.to_bits()); - assert_eq!(points[2].te_symbol, "CACPI"); - assert_eq!(points[2].value_bits, 2.8_f64.to_bits()); - assert_eq!(points[3].te_symbol, "USAGDP"); - - assert_eq!( - errs, - vec![ - (missing_sym_offset, BsonTeDataError::MissingSymbol), - ( - bad_point_doc_offset, - BsonTeDataError::InvalidPointDate { point_index: 1 }, - ), - ] - ); - - assert_eq!(stats.docs_in, 4); - assert_eq!(stats.docs_accepted, 3); - assert_eq!(stats.rejected_missing_symbol, 1); - assert_eq!(stats.docs_rejected_total(), 1); - assert_eq!(stats.points_in, 5); - assert_eq!(stats.points_decoded, 4); - assert_eq!(stats.rejected_invalid_date, 1); - assert_eq!(stats.rejected_total(), 1); - assert_eq!( - stats.docs_in, - stats.docs_accepted + stats.docs_rejected_total() - ); - assert_eq!(stats.points_in, stats.points_decoded + stats.rejected_total()); -} - -#[test] -fn te_data_stream_rebases_corrupt_bson_and_corrupt_point_bson_in_later_chunks() { - let doc1 = make_te_data_doc( - Some("USACPI"), - "United States", - "Inflation Rate", - &[("2024-01-31", 3.1)], - &[], - ); - // Length-framed corrupt top-level BSON doc. - let doc2_corrupt_top = make_corrupt_bson_doc(37); - // Length-framed teData doc whose second point (point_index = 1) has a corrupt element type tag. - let mut doc3_corrupt_point = make_te_data_doc( - Some("CACPI"), - "Canada", - "Inflation Rate", - &[("2024-01-31", 2.9), ("2024-02-29", 2.8)], - &[], - ); - let second_d_pos = doc3_corrupt_point - .windows(3) - .enumerate() - .filter(|(_, w)| *w == b"\x02d\0") - .nth(1) - .map(|(idx, _)| idx) - .expect("locate second point's 'd' element"); - doc3_corrupt_point[second_d_pos] = 0x7E; - - let doc4_after = make_te_data_doc( - Some("USAGDP"), - "United States", - "GDP Growth Rate", - &[("2024-06-30", 3.0)], - &[], - ); - - let mut fixture = Vec::new(); - fixture.extend_from_slice(&doc1); - let corrupt_top_offset = fixture.len() as u64; - fixture.extend_from_slice(&doc2_corrupt_top); - let corrupt_point_offset = fixture.len() as u64; - fixture.extend_from_slice(&doc3_corrupt_point); - fixture.extend_from_slice(&doc4_after); - - let opts = BsonStreamOptions { - chunk_capacity_bytes: doc1.len(), - max_doc_bytes: 4096, - }; - let mut points = Vec::new(); - let mut errs = Vec::new(); - let stats = decode_te_data_stream( - FixedStepReader::new(&fixture, 11), - opts, - |p| points.push(owned_te_data_point(p)), - |off, err| errs.push((off, err)), - ) - .unwrap(); - - // doc1 point + doc3's valid first point + doc4 point all emit. - assert_eq!(points.len(), 3); - assert_eq!(points[0].te_symbol, "USACPI"); - assert_eq!(points[1].te_symbol, "CACPI"); - assert_eq!(points[2].te_symbol, "USAGDP"); - - assert_eq!(errs.len(), 2); - assert!( - matches!( - &errs[0], - (abs_off, BsonTeDataError::CorruptBson { offset, .. }) - if *abs_off == corrupt_top_offset && *offset as u64 == corrupt_top_offset - ), - "expected rebased CorruptBson at {corrupt_top_offset}, got {:?}", - errs[0] - ); - assert!( - matches!( - &errs[1], - ( - abs_off, - BsonTeDataError::CorruptPointBson { - offset, - point_index: 1, - .. - } - ) if *abs_off == corrupt_point_offset && *offset as u64 == corrupt_point_offset - ), - "expected rebased CorruptPointBson at {corrupt_point_offset}, got {:?}", - errs[1] - ); - - assert_eq!(stats.docs_in, 4); - assert_eq!(stats.docs_accepted, 3); - assert_eq!(stats.rejected_corrupt_document, 1); - assert_eq!(stats.points_in, 4); - assert_eq!(stats.points_decoded, 3); - assert_eq!(stats.rejected_corrupt_point, 1); - assert_eq!( - stats.docs_in, - stats.docs_accepted + stats.docs_rejected_total() - ); - assert_eq!(stats.points_in, stats.points_decoded + stats.rejected_total()); - - // Directly exercise rebase_te_data_error for the two framing-offset variants intercepted by - // RawBsonChunkReader, plus non-offset variants. - assert_eq!( - super::rebase_te_data_error( - 1_000, - BsonTeDataError::TruncatedDocument { - offset: 42, - remaining: 3, - declared_len: Some(64), - }, - ), - BsonTeDataError::TruncatedDocument { - offset: 1_042, - remaining: 3, - declared_len: Some(64), - } - ); - assert_eq!( - super::rebase_te_data_error( - 2_000, - BsonTeDataError::CorruptDocumentLength { - offset: 17, - declared_len: 3, - }, - ), - BsonTeDataError::CorruptDocumentLength { - offset: 2_017, - declared_len: 3, - } - ); - assert_eq!( - super::rebase_te_data_error(500, BsonTeDataError::InvalidPointDate { point_index: 4 }), - BsonTeDataError::InvalidPointDate { point_index: 4 } - ); - assert_eq!( - super::rebase_te_data_error(500, BsonTeDataError::MissingSymbol), - BsonTeDataError::MissingSymbol - ); -} - -#[test] -fn te_data_stream_ignores_forecast_and_handles_empty_input() { - // Empty input via both decode_te_data_stream and decode_te_data_chunks. - let opts = BsonStreamOptions { - chunk_capacity_bytes: 64, - max_doc_bytes: 1024, - }; - let empty_stats = decode_te_data_stream( - Cursor::new(&[][..]), - opts, - |_| panic!("unexpected point on empty input"), - |_, _| panic!("unexpected error on empty input"), - ) - .unwrap(); - assert_eq!(empty_stats, BsonTeDataDecodeStats::default()); - - let mut empty_reader = RawBsonChunkReader::with_options(Cursor::new(&[][..]), opts).unwrap(); - let empty_chunk_stats = decode_te_data_chunks( - &mut empty_reader, - |_| panic!("unexpected point on empty chunks"), - |_, _| panic!("unexpected error on empty chunks"), - ) - .unwrap(); - assert_eq!(empty_chunk_stats, BsonTeDataDecodeStats::default()); - - // Document with distinct historical `data` and forward-looking `forecast` arrays. - let doc = make_te_data_doc( - Some("USACPI"), - "United States", - "Inflation Rate", - &[("2024-01-31", 3.1), ("2024-02-29", 3.2)], - &[("2026-01-31", 99.1), ("2026-06-30", 99.2), ("2027-01-31", 99.3)], - ); - let mut points = Vec::new(); - let stats = decode_te_data_stream( - FixedStepReader::new(&doc, 7), - BsonStreamOptions { - chunk_capacity_bytes: 32, - max_doc_bytes: 4096, - }, - |p| points.push(owned_te_data_point(p)), - |off, err| panic!("unexpected error at {off}: {err}"), - ) - .unwrap(); - - assert_eq!(stats.docs_in, 1); - assert_eq!(stats.docs_accepted, 1); - assert_eq!(stats.points_in, 2); - assert_eq!(stats.points_decoded, 2); - assert_eq!(stats.rejected_total(), 0); - assert_eq!(points.len(), 2); - assert_eq!(points[0].value_bits, 3.1_f64.to_bits()); - assert_eq!(points[1].value_bits, 3.2_f64.to_bits()); -} - -#[test] -fn te_data_stream_returns_terminal_errors_for_truncated_and_oversized_docs() { - let prefix_doc = make_te_data_doc( - Some("USACPI"), - "United States", - "Inflation Rate", - &[("2024-01-31", 3.1)], - &[], - ); - - // 1. Truncated trailing document after valid prefix. - let mut truncated = prefix_doc.clone(); - let trunc_offset = truncated.len() as u64; - truncated.extend_from_slice(&120_i32.to_le_bytes()); - truncated.extend_from_slice(&[0x02, b'a', 0x00]); - - let mut trunc_points = Vec::new(); - let trunc_err = decode_te_data_stream( - FixedStepReader::new(&truncated, 5), - BsonStreamOptions { - chunk_capacity_bytes: 32, - max_doc_bytes: 4096, - }, - |p| trunc_points.push(owned_te_data_point(p)), - |off, err| panic!("terminal stream error must not reach on_error ({off}: {err})"), - ) - .unwrap_err(); - - assert_eq!(trunc_points.len(), 1); - assert_eq!(trunc_points[0].te_symbol, "USACPI"); - assert!(matches!( - trunc_err, - BsonStreamError::TruncatedDocument { - offset, - remaining: 7, - declared_len: Some(120), - } if offset == trunc_offset - )); - - // 2. Oversized trailing document (declared length > max_doc_bytes) after valid prefix. - let mut oversized = prefix_doc; - let oversize_offset = oversized.len() as u64; - oversized.extend_from_slice(&1024_i32.to_le_bytes()); - oversized.extend_from_slice(&[0x00; 16]); - - let mut oversize_points = Vec::new(); - let oversize_err = decode_te_data_stream( - FixedStepReader::new(&oversized, 5), - BsonStreamOptions { - chunk_capacity_bytes: 32, - max_doc_bytes: 512, - }, - |p| oversize_points.push(owned_te_data_point(p)), - |off, err| panic!("terminal stream error must not reach on_error ({off}: {err})"), - ) - .unwrap_err(); - - assert_eq!(oversize_points.len(), 1); - assert_eq!(oversize_points[0].te_symbol, "USACPI"); - assert!(matches!( - oversize_err, - BsonStreamError::CorruptDocumentLength { - offset, - declared_len: 1024, - max_doc_bytes: 512, - } if offset == oversize_offset - )); -} - -/// Builds a two-point teData doc whose byte length depends only on the string lengths, so -/// fixtures can be made of equal-length documents and chunk layouts are exact. -fn make_fixed_len_te_data_doc(te_symbol: &str, v0: f64, v1: f64) -> Vec { - make_te_data_doc( - Some(te_symbol), - "Canada", - "Inflation Rate", - &[("2024-01-31", v0), ("2024-02-29", v1)], - &[], - ) -} - -#[test] -fn te_data_stream_rebases_errors_at_nonzero_local_offsets_inside_later_multi_doc_chunks() { - // Arrange: six equal-length docs, chunk capacity = 2 docs, so every chunk holds exactly two - // documents and each offending document sits at local offset L inside a chunk with base 2L/4L. - // This separates `chunk.start_offset` from the in-chunk local offset, which single-doc chunks - // (local offset 0) cannot do. - let doc_a = make_fixed_len_te_data_doc("TEDOCA", 1.0, 1.5); - let len = doc_a.len(); - let doc_b = make_fixed_len_te_data_doc("TEDOCB", 2.0, 2.5); - let doc_c = make_fixed_len_te_data_doc("TEDOCC", 3.0, 3.5); - let doc_d_corrupt_top = make_corrupt_bson_doc(len); - let doc_e = make_fixed_len_te_data_doc("TEDOCE", 5.0, 5.5); - let mut doc_f_corrupt_point = make_fixed_len_te_data_doc("TEDOCF", 6.0, 6.5); - let second_d_pos = doc_f_corrupt_point - .windows(3) - .enumerate() - .filter(|(_, w)| *w == b"\x02d\0") - .nth(1) - .map(|(idx, _)| idx) - .expect("locate second point's 'd' element"); - doc_f_corrupt_point[second_d_pos] = 0x7E; - - let docs = [ - &doc_a, - &doc_b, - &doc_c, - &doc_d_corrupt_top, - &doc_e, - &doc_f_corrupt_point, - ]; - for d in docs { - assert_eq!(d.len(), len, "fixture docs must be equal length"); - } - let fixture: Vec = docs.iter().flat_map(|d| d.iter().copied()).collect(); - let opts = BsonStreamOptions { - chunk_capacity_bytes: 2 * len, - max_doc_bytes: 4096, - }; - - // Pin the chunk layout the assertions below rely on. - let mut layout_reader = - RawBsonChunkReader::with_options(Cursor::new(fixture.as_slice()), opts).unwrap(); - let mut layout = Vec::new(); - while let Some(chunk) = layout_reader.next_chunk().unwrap() { - layout.push((chunk.start_offset, chunk.bytes.len())); - } - let l = len as u64; - assert_eq!( - layout, - vec![(0, 2 * len), (2 * l, 2 * len), (4 * l, 2 * len)] - ); - - // Act: both entry points. - let mut stream_points = Vec::new(); - let mut stream_errs = Vec::new(); - let stream_stats = decode_te_data_stream( - Cursor::new(fixture.as_slice()), - opts, - |p| stream_points.push(owned_te_data_point(p)), - |off, err| stream_errs.push((off, err)), - ) - .unwrap(); - - let mut chunk_reader = - RawBsonChunkReader::with_options(Cursor::new(fixture.as_slice()), opts).unwrap(); - let mut chunk_points = Vec::new(); - let mut chunk_errs = Vec::new(); - let chunk_stats = decode_te_data_chunks( - &mut chunk_reader, - |p| chunk_points.push(owned_te_data_point(p)), - |off, err| chunk_errs.push((off, err)), - ) - .unwrap(); - - // Assert: absolute offsets 3L and 5L both in the callback argument and the embedded error. - assert_eq!(stream_errs.len(), 2, "{stream_errs:?}"); - match &stream_errs[0] { - (abs, BsonTeDataError::CorruptBson { offset, .. }) => { - assert_eq!(*abs, 3 * l); - assert_eq!(*offset as u64, 3 * l); - } - other => panic!("expected CorruptBson at {}, got {other:?}", 3 * l), - } - match &stream_errs[1] { - ( - abs, - BsonTeDataError::CorruptPointBson { - offset, - point_index, - .. - }, - ) => { - assert_eq!(*abs, 5 * l); - assert_eq!(*offset as u64, 5 * l); - assert_eq!(*point_index, 1); - } - other => panic!("expected CorruptPointBson at {}, got {other:?}", 5 * l), - } - assert_eq!(chunk_errs, stream_errs); - - let symbols: Vec<(&str, u64)> = stream_points - .iter() - .map(|p| (p.te_symbol.as_str(), p.value_bits)) - .collect(); - assert_eq!( - symbols, - vec![ - ("TEDOCA", 1.0_f64.to_bits()), - ("TEDOCA", 1.5_f64.to_bits()), - ("TEDOCB", 2.0_f64.to_bits()), - ("TEDOCB", 2.5_f64.to_bits()), - ("TEDOCC", 3.0_f64.to_bits()), - ("TEDOCC", 3.5_f64.to_bits()), - ("TEDOCE", 5.0_f64.to_bits()), - ("TEDOCE", 5.5_f64.to_bits()), - ("TEDOCF", 6.0_f64.to_bits()), - ] - ); - assert_eq!(chunk_points, stream_points); - - assert_eq!(stream_stats, chunk_stats); - assert_eq!(stream_stats.docs_in, 6); - assert_eq!(stream_stats.docs_accepted, 5); - assert_eq!(stream_stats.rejected_corrupt_document, 1); - assert_eq!(stream_stats.points_in, 10); - assert_eq!(stream_stats.points_decoded, 9); - assert_eq!(stream_stats.rejected_corrupt_point, 1); - assert_eq!( - stream_stats.docs_in, - stream_stats.docs_accepted + stream_stats.docs_rejected_total() - ); - assert_eq!( - stream_stats.points_in, - stream_stats.points_decoded + stream_stats.rejected_total() - ); - assert_eq!(chunk_reader.docs_framed(), 6); -} - -#[test] -fn te_data_rebase_preserves_payload_fields_and_saturates_offsets() { - // CorruptBson keeps its detail; CorruptPointBson keeps point_index and detail. - assert_eq!( - super::rebase_te_data_error( - 4_096, - BsonTeDataError::CorruptBson { - offset: 10, - detail: "bad top".to_owned(), - }, - ), - BsonTeDataError::CorruptBson { - offset: 4_106, - detail: "bad top".to_owned(), - } - ); - assert_eq!( - super::rebase_te_data_error( - 4_096, - BsonTeDataError::CorruptPointBson { - offset: 0, - point_index: 7, - detail: "bad point".to_owned(), - }, - ), - BsonTeDataError::CorruptPointBson { - offset: 4_096, - point_index: 7, - detail: "bad point".to_owned(), - } - ); - // Overflowing absolute offsets saturate instead of wrapping (shared `rebase_offset` policy). - assert_eq!( - super::rebase_te_data_error( - u64::MAX, - BsonTeDataError::CorruptBson { - offset: 1, - detail: String::new(), - }, - ), - BsonTeDataError::CorruptBson { - offset: usize::MAX, - detail: String::new(), - } - ); - // Point-level variants without an offset pass through unchanged. - let passthrough = BsonTeDataError::WrongPointFieldType { - point_index: 2, - field: "v", - actual: bson::spec::ElementType::String, - }; - assert_eq!( - super::rebase_te_data_error(9_999, passthrough.clone()), - passthrough - ); -} diff --git a/tools/curate-etl/src/bson_te_data.rs b/tools/curate-etl/src/bson_te_data.rs deleted file mode 100644 index b82b1509..00000000 --- a/tools/curate-etl/src/bson_te_data.rs +++ /dev/null @@ -1,854 +0,0 @@ -//! Zero-copy raw BSON decoder for MongoDB `teData` documents (`M2.2p`). -//! -//! Decodes `&bson::RawDocument` slices in a single forward pass over `iter_elements()` without -//! allocating a `bson::Document` or per-point heap memory, emitting borrowed [`TeDataPoint`] -//! values via a caller-supplied callback. -//! -//! # Empirical Field Contract & Unverified Assumptions -//! -//! - Field names are derived strictly from the ingestion writer in -//! `apps/stock/data-ingestion/src/handlers/te/actions/data-fetch.action.ts:87-156` -//! (`teSymbol`, `name`, `unit`, `source`, `frequency`, `country`, `category`, `data`, `forecast`, -//! `lastUpdated`, `createdAt`; `data: [{ d: "YYYY-MM-DD", v: number }]`; `forecast: [{ d, v }]`), -//! and isolated in the `pub const FIELD_*` constants below. They have **not** been verified -//! against a live `mongodump` of `teData`. -//! - **History-only (zero forecast leakage):** `forecast` stores forward-looking provider -//! forecasts. `forecast`, descriptive metadata (`name`, `unit`, `source`, `frequency`), -//! timestamps (`lastUpdated`, `createdAt`), and all unknown fields are skipped by key without -//! calling `elem.value()`, so forecast observations can never leak into research inputs. -//! - **Ownership & no hardcoded mappings:** `TeDataPoint` preserves the verbatim provider -//! `te_symbol`, `country`, and `category` strings. No country-to-ISO, indicator-name, or -//! publication-lag mapping is hardcoded here: Quant Research owns the coarse regime-use policy, -//! and the downstream caller/runner owns all explicit mapping into [`crate::macro_series`]. -//! - **Observation dates & provenance:** `period_date` is the provider observation date parsed from -//! strict `YYYY-MM-DD`. Because `teData` carries final-revised values without verified -//! first-release vintages, downstream availability begins strictly at the builder's estimated -//! `known_at` ([`crate::macro_series::build_macro_rows`]). -//! - **Lazy `data` capture:** `data` is retained as a raw [`RawElement`] during the top-level -//! scan and only decoded after `teSymbol`, `country`, and `category` pass validation, so raw -//! BSON field ordering (`data` before metadata) does not affect output or rejection accounting. -//! - **Non-finite doubles:** `v` accepts BSON `Double`, `Int32`, and `Int64` only. Finite and -//! non-finite (`NaN`, `±inf`) doubles are passed through unchanged so the downstream -//! [`crate::macro_series::build_macro_rows`] builder can account for them in -//! `skipped_non_finite_value`. - -use std::error::Error; -use std::fmt; - -use bson::raw::{RawBsonRef, RawDocument, RawElement}; -use bson::spec::ElementType; - -use crate::bson_eod_prices::{ - iter_raw_bson_docs, parse_single_raw_doc, parse_ymd_strict_days, BsonEodPriceError, -}; - -/// MongoDB field name for the TradingEconomics symbol key (`data-fetch.action.ts:94`). -pub const FIELD_TE_SYMBOL: &str = "teSymbol"; -/// MongoDB field name for the provider country label (`data-fetch.action.ts:99`). -pub const FIELD_COUNTRY: &str = "country"; -/// MongoDB field name for the provider category/indicator label (`data-fetch.action.ts:100`). -pub const FIELD_CATEGORY: &str = "category"; -/// MongoDB field name for the historical observation array (`data-fetch.action.ts:101`). -pub const FIELD_DATA: &str = "data"; -/// MongoDB field name for the forward-looking forecast array, never read (`data-fetch.action.ts:102`). -pub const FIELD_FORECAST: &str = "forecast"; -/// Point field name for the `YYYY-MM-DD` observation date string (`data-fetch.action.ts:78`). -pub const FIELD_POINT_D: &str = "d"; -/// Point field name for the numeric observation value (`data-fetch.action.ts:78`). -pub const FIELD_POINT_V: &str = "v"; - -/// Borrowed zero-copy view of a single historical `teData.data` observation. -/// -/// `te_symbol`, `country`, and `category` are borrowed verbatim from the underlying -/// `&RawDocument` byte slice with zero per-point heap allocation. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct TeDataPoint<'a> { - pub te_symbol: &'a str, - pub country: &'a str, - pub category: &'a str, - /// Observation period date as days since `1970-01-01` (UTC Gregorian). - pub period_date: i32, - pub value: f64, -} - -/// Typed errors returned while decoding raw `teData` BSON documents or length-prefixed buffers. -/// -/// Every variant's `Display` output is a single line; no input path panics. -#[derive(Debug, Clone, PartialEq)] -pub enum BsonTeDataError { - /// Required top-level `teSymbol` field was absent. - MissingSymbol, - /// Top-level `teSymbol` string was empty or whitespace-only. - EmptySymbol, - /// Top-level `teSymbol` had an unexpected BSON element type. - WrongSymbolType { actual: ElementType }, - /// Required top-level `country` field was absent. - MissingCountry, - /// Top-level `country` string was empty or whitespace-only. - EmptyCountry, - /// Top-level `country` had an unexpected BSON element type. - WrongCountryType { actual: ElementType }, - /// Required top-level `category` field was absent. - MissingCategory, - /// Top-level `category` string was empty or whitespace-only. - EmptyCategory, - /// Top-level `category` had an unexpected BSON element type. - WrongCategoryType { actual: ElementType }, - /// Required top-level `data` field was absent. - MissingData, - /// Top-level `data` field was not a BSON array. - DataNotArray { actual: ElementType }, - /// An element inside `data` was not an embedded BSON document. - PointNotDocument { - point_index: usize, - actual: ElementType, - }, - /// A required field (`d` or `v`) was absent from a `data` point document. - MissingPointField { - point_index: usize, - field: &'static str, - }, - /// A required field (`d` or `v`) in a `data` point document had an unexpected BSON type. - WrongPointFieldType { - point_index: usize, - field: &'static str, - actual: ElementType, - }, - /// Point date `d` was not a strict, valid Gregorian `YYYY-MM-DD` string. - InvalidPointDate { point_index: usize }, - /// Buffer ended before a complete 4-byte length prefix or declared document body. - TruncatedDocument { - offset: usize, - remaining: usize, - declared_len: Option, - }, - /// Declared 4-byte little-endian BSON document length was `< 5` (or did not match a single - /// document slice). - CorruptDocumentLength { offset: usize, declared_len: i32 }, - /// Underlying top-level BSON framing or element bytes were malformed. - CorruptBson { offset: usize, detail: String }, - /// Underlying BSON bytes inside a `data` array or point document were malformed. - CorruptPointBson { - offset: usize, - point_index: usize, - detail: String, - }, -} - -impl fmt::Display for BsonTeDataError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::MissingSymbol => { - write!(f, "teData BSON missing required field '{FIELD_TE_SYMBOL}'") - } - Self::EmptySymbol => { - write!( - f, - "teData BSON field '{FIELD_TE_SYMBOL}' must not be empty or blank" - ) - } - Self::WrongSymbolType { actual } => write!( - f, - "teData BSON field '{FIELD_TE_SYMBOL}' has unexpected BSON type {actual:?}" - ), - Self::MissingCountry => { - write!(f, "teData BSON missing required field '{FIELD_COUNTRY}'") - } - Self::EmptyCountry => { - write!( - f, - "teData BSON field '{FIELD_COUNTRY}' must not be empty or blank" - ) - } - Self::WrongCountryType { actual } => write!( - f, - "teData BSON field '{FIELD_COUNTRY}' has unexpected BSON type {actual:?}" - ), - Self::MissingCategory => { - write!(f, "teData BSON missing required field '{FIELD_CATEGORY}'") - } - Self::EmptyCategory => { - write!( - f, - "teData BSON field '{FIELD_CATEGORY}' must not be empty or blank" - ) - } - Self::WrongCategoryType { actual } => write!( - f, - "teData BSON field '{FIELD_CATEGORY}' has unexpected BSON type {actual:?}" - ), - Self::MissingData => { - write!(f, "teData BSON missing required field '{FIELD_DATA}'") - } - Self::DataNotArray { actual } => write!( - f, - "teData BSON field '{FIELD_DATA}' has unexpected BSON type {actual:?} (expected Array)" - ), - Self::PointNotDocument { - point_index, - actual, - } => write!( - f, - "teData BSON '{FIELD_DATA}[{point_index}]' has unexpected BSON type {actual:?} (expected EmbeddedDocument)" - ), - Self::MissingPointField { point_index, field } => write!( - f, - "teData BSON '{FIELD_DATA}[{point_index}]' missing required field '{field}'" - ), - Self::WrongPointFieldType { - point_index, - field, - actual, - } => write!( - f, - "teData BSON '{FIELD_DATA}[{point_index}].{field}' has unexpected BSON type {actual:?}" - ), - Self::InvalidPointDate { point_index } => write!( - f, - "teData BSON '{FIELD_DATA}[{point_index}].{FIELD_POINT_D}' is not a valid strict YYYY-MM-DD date" - ), - Self::TruncatedDocument { - offset, - remaining, - declared_len, - } => match declared_len { - Some(len) => write!( - f, - "truncated BSON document at byte offset {offset}: declared length {len} exceeds remaining {remaining} bytes" - ), - None => write!( - f, - "truncated BSON document header at byte offset {offset}: only {remaining} bytes remaining" - ), - }, - Self::CorruptDocumentLength { - offset, - declared_len, - } => write!( - f, - "corrupt BSON document length {declared_len} at byte offset {offset}" - ), - Self::CorruptBson { offset, detail } => { - write!(f, "corrupt BSON bytes at byte offset {offset}: {detail}") - } - Self::CorruptPointBson { - offset, - point_index, - detail, - } => write!( - f, - "corrupt BSON bytes in '{FIELD_DATA}[{point_index}]' at byte offset {offset}: {detail}" - ), - } - } -} - -impl Error for BsonTeDataError {} - -#[inline] -fn map_framing_error(err: BsonEodPriceError) -> BsonTeDataError { - match err { - BsonEodPriceError::TruncatedDocument { - offset, - remaining, - declared_len, - } => BsonTeDataError::TruncatedDocument { - offset, - remaining, - declared_len, - }, - BsonEodPriceError::CorruptDocumentLength { - offset, - declared_len, - } => BsonTeDataError::CorruptDocumentLength { - offset, - declared_len, - }, - BsonEodPriceError::CorruptBson { offset, detail } => { - BsonTeDataError::CorruptBson { offset, detail } - } - other => BsonTeDataError::CorruptBson { - offset: 0, - detail: other.to_string(), - }, - } -} - -/// Per-batch document and point decode accounting for `teData`. -/// -/// Conservation invariants: -/// - `docs_in == docs_accepted + docs_rejected_total()` -/// - `points_in == points_decoded + rejected_total()` -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct BsonTeDataDecodeStats { - pub docs_in: usize, - pub docs_accepted: usize, - pub rejected_missing_symbol: usize, - pub rejected_empty_symbol: usize, - pub rejected_wrong_symbol_type: usize, - pub rejected_missing_country: usize, - pub rejected_empty_country: usize, - pub rejected_wrong_country_type: usize, - pub rejected_missing_category: usize, - pub rejected_empty_category: usize, - pub rejected_wrong_category_type: usize, - pub rejected_data_missing: usize, - pub rejected_data_not_array: usize, - pub rejected_corrupt_document: usize, - pub points_in: usize, - pub points_decoded: usize, - pub rejected_point_not_document: usize, - pub rejected_invalid_date: usize, - pub rejected_invalid_value: usize, - pub rejected_corrupt_point: usize, -} - -impl BsonTeDataDecodeStats { - /// Total number of document-level rejects across all document error categories. - #[inline] - pub fn docs_rejected_total(&self) -> usize { - self.rejected_missing_symbol - + self.rejected_empty_symbol - + self.rejected_wrong_symbol_type - + self.rejected_missing_country - + self.rejected_empty_country - + self.rejected_wrong_country_type - + self.rejected_missing_category - + self.rejected_empty_category - + self.rejected_wrong_category_type - + self.rejected_data_missing - + self.rejected_data_not_array - + self.rejected_corrupt_document - } - - /// Total number of point-level rejects across all point error categories. - #[inline] - pub fn rejected_total(&self) -> usize { - self.rejected_point_not_document - + self.rejected_invalid_date - + self.rejected_invalid_value - + self.rejected_corrupt_point - } - - /// Increments the document-level rejection counter corresponding to `err`. - #[inline] - fn record_doc_error(&mut self, err: &BsonTeDataError) { - match err { - BsonTeDataError::MissingSymbol => self.rejected_missing_symbol += 1, - BsonTeDataError::EmptySymbol => self.rejected_empty_symbol += 1, - BsonTeDataError::WrongSymbolType { .. } => self.rejected_wrong_symbol_type += 1, - BsonTeDataError::MissingCountry => self.rejected_missing_country += 1, - BsonTeDataError::EmptyCountry => self.rejected_empty_country += 1, - BsonTeDataError::WrongCountryType { .. } => self.rejected_wrong_country_type += 1, - BsonTeDataError::MissingCategory => self.rejected_missing_category += 1, - BsonTeDataError::EmptyCategory => self.rejected_empty_category += 1, - BsonTeDataError::WrongCategoryType { .. } => self.rejected_wrong_category_type += 1, - BsonTeDataError::MissingData => self.rejected_data_missing += 1, - BsonTeDataError::DataNotArray { .. } => self.rejected_data_not_array += 1, - _ => self.rejected_corrupt_document += 1, - } - } - - /// Increments the point-level rejection counter corresponding to `err`. - #[inline] - fn record_point_error(&mut self, err: &BsonTeDataError) { - match err { - BsonTeDataError::PointNotDocument { .. } => { - self.rejected_point_not_document += 1; - } - BsonTeDataError::InvalidPointDate { .. } => { - self.rejected_invalid_date += 1; - } - BsonTeDataError::MissingPointField { field, .. } - | BsonTeDataError::WrongPointFieldType { field, .. } => { - if *field == FIELD_POINT_D { - self.rejected_invalid_date += 1; - } else if *field == FIELD_POINT_V { - self.rejected_invalid_value += 1; - } else { - self.rejected_corrupt_point += 1; - } - } - BsonTeDataError::CorruptPointBson { .. } => { - self.rejected_corrupt_point += 1; - } - _ => { - self.rejected_corrupt_point += 1; - } - } - } - - /// Accumulates counters from another batch into `self`. - #[inline] - pub fn merge(&mut self, other: &Self) { - self.docs_in += other.docs_in; - self.docs_accepted += other.docs_accepted; - self.rejected_missing_symbol += other.rejected_missing_symbol; - self.rejected_empty_symbol += other.rejected_empty_symbol; - self.rejected_wrong_symbol_type += other.rejected_wrong_symbol_type; - self.rejected_missing_country += other.rejected_missing_country; - self.rejected_empty_country += other.rejected_empty_country; - self.rejected_wrong_country_type += other.rejected_wrong_country_type; - self.rejected_missing_category += other.rejected_missing_category; - self.rejected_empty_category += other.rejected_empty_category; - self.rejected_wrong_category_type += other.rejected_wrong_category_type; - self.rejected_data_missing += other.rejected_data_missing; - self.rejected_data_not_array += other.rejected_data_not_array; - self.rejected_corrupt_document += other.rejected_corrupt_document; - self.points_in += other.points_in; - self.points_decoded += other.points_decoded; - self.rejected_point_not_document += other.rejected_point_not_document; - self.rejected_invalid_date += other.rejected_invalid_date; - self.rejected_invalid_value += other.rejected_invalid_value; - self.rejected_corrupt_point += other.rejected_corrupt_point; - } -} - -impl std::ops::AddAssign for BsonTeDataDecodeStats { - #[inline] - fn add_assign(&mut self, rhs: Self) { - self.merge(&rhs); - } -} - -#[inline] -fn decode_point_d(point_index: usize, val: RawBsonRef<'_>) -> Result { - match val { - RawBsonRef::String(s) => { - parse_ymd_strict_days(s).ok_or(BsonTeDataError::InvalidPointDate { point_index }) - } - other => Err(BsonTeDataError::WrongPointFieldType { - point_index, - field: FIELD_POINT_D, - actual: other.element_type(), - }), - } -} - -#[inline] -fn decode_point_v(point_index: usize, val: RawBsonRef<'_>) -> Result { - match val { - RawBsonRef::Double(v) => Ok(v), - RawBsonRef::Int32(v) => Ok(f64::from(v)), - RawBsonRef::Int64(v) => Ok(v as f64), - other => Err(BsonTeDataError::WrongPointFieldType { - point_index, - field: FIELD_POINT_V, - actual: other.element_type(), - }), - } -} - -fn decode_point_doc( - point_doc: &RawDocument, - doc_offset: usize, - point_index: usize, -) -> Result<(i32, f64), BsonTeDataError> { - let mut period_date: Option = None; - let mut value: Option = None; - let mut d_err: Option = None; - let mut v_err: Option = None; - - for elem_res in point_doc.iter_elements() { - let elem = elem_res.map_err(|err| BsonTeDataError::CorruptPointBson { - offset: doc_offset, - point_index, - detail: err.to_string(), - })?; - let key = elem.key().as_str(); - - if key == FIELD_POINT_D { - let val = elem - .value() - .map_err(|err| BsonTeDataError::CorruptPointBson { - offset: doc_offset, - point_index, - detail: format!("field '{FIELD_POINT_D}': {err}"), - })?; - match decode_point_d(point_index, val) { - Ok(d) => period_date = Some(d), - Err(err) => { - if d_err.is_none() { - d_err = Some(err); - } - } - } - } else if key == FIELD_POINT_V { - let val = elem - .value() - .map_err(|err| BsonTeDataError::CorruptPointBson { - offset: doc_offset, - point_index, - detail: format!("field '{FIELD_POINT_V}': {err}"), - })?; - match decode_point_v(point_index, val) { - Ok(v) => value = Some(v), - Err(err) => { - if v_err.is_none() { - v_err = Some(err); - } - } - } - } - // Unknown point fields are skipped without calling `elem.value()`. - } - - if let Some(err) = d_err { - return Err(err); - } - let Some(period_date) = period_date else { - return Err(BsonTeDataError::MissingPointField { - point_index, - field: FIELD_POINT_D, - }); - }; - if let Some(err) = v_err { - return Err(err); - } - let Some(value) = value else { - return Err(BsonTeDataError::MissingPointField { - point_index, - field: FIELD_POINT_V, - }); - }; - - Ok((period_date, value)) -} - -fn decode_te_data_doc_at<'a, F, E>( - doc: &'a RawDocument, - doc_offset: usize, - mut on_point: F, - mut on_error: E, -) -> BsonTeDataDecodeStats -where - F: FnMut(TeDataPoint<'a>), - E: FnMut(BsonTeDataError), -{ - let mut stats = BsonTeDataDecodeStats { - docs_in: 1, - ..BsonTeDataDecodeStats::default() - }; - - let mut te_symbol: Option<&'a str> = None; - let mut te_symbol_err: Option = None; - let mut country: Option<&'a str> = None; - let mut country_err: Option = None; - let mut category: Option<&'a str> = None; - let mut category_err: Option = None; - let mut data_elem: Option> = None; - - for elem_res in doc.iter_elements() { - let elem = match elem_res { - Ok(elem) => elem, - Err(err) => { - stats.rejected_corrupt_document += 1; - on_error(BsonTeDataError::CorruptBson { - offset: doc_offset, - detail: err.to_string(), - }); - return stats; - } - }; - let key = elem.key().as_str(); - if key == FIELD_TE_SYMBOL { - let val = match elem.value() { - Ok(val) => val, - Err(err) => { - stats.rejected_corrupt_document += 1; - on_error(BsonTeDataError::CorruptBson { - offset: doc_offset, - detail: format!("field '{FIELD_TE_SYMBOL}': {err}"), - }); - return stats; - } - }; - match val { - RawBsonRef::String(s) => { - if s.trim().is_empty() { - if te_symbol_err.is_none() { - te_symbol_err = Some(BsonTeDataError::EmptySymbol); - } - } else { - te_symbol = Some(s); - } - } - other => { - if te_symbol_err.is_none() { - te_symbol_err = Some(BsonTeDataError::WrongSymbolType { - actual: other.element_type(), - }); - } - } - } - } else if key == FIELD_COUNTRY { - let val = match elem.value() { - Ok(val) => val, - Err(err) => { - stats.rejected_corrupt_document += 1; - on_error(BsonTeDataError::CorruptBson { - offset: doc_offset, - detail: format!("field '{FIELD_COUNTRY}': {err}"), - }); - return stats; - } - }; - match val { - RawBsonRef::String(s) => { - if s.trim().is_empty() { - if country_err.is_none() { - country_err = Some(BsonTeDataError::EmptyCountry); - } - } else { - country = Some(s); - } - } - other => { - if country_err.is_none() { - country_err = Some(BsonTeDataError::WrongCountryType { - actual: other.element_type(), - }); - } - } - } - } else if key == FIELD_CATEGORY { - let val = match elem.value() { - Ok(val) => val, - Err(err) => { - stats.rejected_corrupt_document += 1; - on_error(BsonTeDataError::CorruptBson { - offset: doc_offset, - detail: format!("field '{FIELD_CATEGORY}': {err}"), - }); - return stats; - } - }; - match val { - RawBsonRef::String(s) => { - if s.trim().is_empty() { - if category_err.is_none() { - category_err = Some(BsonTeDataError::EmptyCategory); - } - } else { - category = Some(s); - } - } - other => { - if category_err.is_none() { - category_err = Some(BsonTeDataError::WrongCategoryType { - actual: other.element_type(), - }); - } - } - } - } else if key == FIELD_DATA { - data_elem = Some(elem); - } - // `FIELD_FORECAST`, `name`, `unit`, `source`, `frequency`, `lastUpdated`, `createdAt`, - // and all other top-level fields are skipped without calling `elem.value()`. - } - - // Deterministic top-level validation order: `teSymbol`, `country`, `category`, then `data`. - if let Some(err) = te_symbol_err { - stats.record_doc_error(&err); - on_error(err); - return stats; - } - let Some(te_symbol) = te_symbol else { - let err = BsonTeDataError::MissingSymbol; - stats.record_doc_error(&err); - on_error(err); - return stats; - }; - - if let Some(err) = country_err { - stats.record_doc_error(&err); - on_error(err); - return stats; - } - let Some(country) = country else { - let err = BsonTeDataError::MissingCountry; - stats.record_doc_error(&err); - on_error(err); - return stats; - }; - - if let Some(err) = category_err { - stats.record_doc_error(&err); - on_error(err); - return stats; - } - let Some(category) = category else { - let err = BsonTeDataError::MissingCategory; - stats.record_doc_error(&err); - on_error(err); - return stats; - }; - - let Some(data_elem) = data_elem else { - let err = BsonTeDataError::MissingData; - stats.record_doc_error(&err); - on_error(err); - return stats; - }; - - let data_val = match data_elem.value() { - Ok(val) => val, - Err(err) => { - stats.rejected_corrupt_document += 1; - on_error(BsonTeDataError::CorruptBson { - offset: doc_offset, - detail: format!("field '{FIELD_DATA}': {err}"), - }); - return stats; - } - }; - - let data_arr = match data_val { - RawBsonRef::Array(arr) => arr, - other => { - let err = BsonTeDataError::DataNotArray { - actual: other.element_type(), - }; - stats.record_doc_error(&err); - on_error(err); - return stats; - } - }; - - stats.docs_accepted += 1; - - for (point_index, item_res) in data_arr.into_iter().enumerate() { - stats.points_in += 1; - let item = match item_res { - Ok(item) => item, - Err(err) => { - let err = BsonTeDataError::CorruptPointBson { - offset: doc_offset, - point_index, - detail: err.to_string(), - }; - stats.record_point_error(&err); - on_error(err); - break; - } - }; - - let point_doc = match item { - RawBsonRef::Document(point_doc) => point_doc, - other => { - let err = BsonTeDataError::PointNotDocument { - point_index, - actual: other.element_type(), - }; - stats.record_point_error(&err); - on_error(err); - continue; - } - }; - - match decode_point_doc(point_doc, doc_offset, point_index) { - Ok((period_date, value)) => { - stats.points_decoded += 1; - on_point(TeDataPoint { - te_symbol, - country, - category, - period_date, - value, - }); - } - Err(err) => { - stats.record_point_error(&err); - on_error(err); - } - } - } - - stats -} - -/// Decodes a single `&RawDocument` representing a `teData` MongoDB document in one forward pass -/// without allocating a `bson::Document` or per-point heap memory. -/// -/// Emits each valid historical `data` point as a borrowed [`TeDataPoint`] via `on_point` and -/// reports document- or point-level errors to `on_error` without panicking. `forecast` is never -/// read or emitted. -#[inline] -pub fn decode_te_data_doc<'a, F, E>( - doc: &'a RawDocument, - on_point: F, - on_error: E, -) -> BsonTeDataDecodeStats -where - F: FnMut(TeDataPoint<'a>), - E: FnMut(BsonTeDataError), -{ - decode_te_data_doc_at(doc, 0, on_point, on_error) -} - -/// Decodes a single length-prefixed raw BSON document byte slice representing a `teData` document. -pub fn decode_te_data_bytes<'a, F, E>( - bytes: &'a [u8], - on_point: F, - mut on_error: E, -) -> BsonTeDataDecodeStats -where - F: FnMut(TeDataPoint<'a>), - E: FnMut(BsonTeDataError), -{ - match parse_single_raw_doc(bytes) { - Ok(doc) => decode_te_data_doc_at(doc, 0, on_point, on_error), - Err(err) => { - let mut stats = BsonTeDataDecodeStats { - docs_in: 1, - ..BsonTeDataDecodeStats::default() - }; - stats.rejected_corrupt_document += 1; - on_error(map_framing_error(err)); - stats - } - } -} - -/// Streams a concatenated length-prefixed BSON buffer through [`decode_te_data_doc`], emitting -/// every valid historical [`TeDataPoint`] to `on_point` and reporting document- or point-level -/// errors to `on_error(byte_offset, err)` without aborting on per-document semantic errors. -/// -/// Always maintains: -/// - `stats.docs_in == stats.docs_accepted + stats.docs_rejected_total()` -/// - `stats.points_in == stats.points_decoded + stats.rejected_total()` -pub fn decode_te_data_buffer<'a, F, E>( - buf: &'a [u8], - mut on_point: F, - mut on_error: E, -) -> BsonTeDataDecodeStats -where - F: FnMut(TeDataPoint<'a>), - E: FnMut(usize, BsonTeDataError), -{ - let mut stats = BsonTeDataDecodeStats::default(); - let mut iter = iter_raw_bson_docs(buf); - - while let Some(item) = iter.next_with_offset() { - match item { - Ok((doc_offset, doc)) => { - let doc_stats = decode_te_data_doc_at(doc, doc_offset, &mut on_point, |err| { - on_error(doc_offset, err) - }); - stats += doc_stats; - } - Err((doc_offset, err)) => { - stats.docs_in += 1; - stats.rejected_corrupt_document += 1; - on_error(doc_offset, map_framing_error(err)); - } - } - } - - stats -} - -#[cfg(test)] -#[path = "bson_te_data_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/bson_te_data_tests.rs b/tools/curate-etl/src/bson_te_data_tests.rs deleted file mode 100644 index 88218964..00000000 --- a/tools/curate-etl/src/bson_te_data_tests.rs +++ /dev/null @@ -1,1282 +0,0 @@ -use bson::raw::{cstr, RawArrayBuf, RawBson, RawDocumentBuf}; -use bson::spec::ElementType; -use bson::DateTime; - -use super::*; -use crate::split::ymd_to_epoch_days; - -fn day(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).expect("valid date") -} - -fn assert_stats_conserved(stats: &BsonTeDataDecodeStats) { - assert_eq!( - stats.docs_in, - stats.docs_accepted + stats.docs_rejected_total(), - "doc conservation failed: {stats:?}" - ); - assert_eq!( - stats.points_in, - stats.points_decoded + stats.rejected_total(), - "point conservation failed: {stats:?}" - ); -} - -#[derive(Debug, PartialEq)] -struct OwnedPoint { - te_symbol: String, - country: String, - category: String, - period_date: i32, - value_bits: u64, -} - -impl From> for OwnedPoint { - fn from(p: TeDataPoint<'_>) -> Self { - Self { - te_symbol: p.te_symbol.to_owned(), - country: p.country.to_owned(), - category: p.category.to_owned(), - period_date: p.period_date, - value_bits: p.value.to_bits(), - } - } -} - -fn make_point_f64(d: &str, v: f64) -> RawDocumentBuf { - let mut pt = RawDocumentBuf::new(); - pt.append(cstr!("d"), d); - pt.append(cstr!("v"), v); - pt -} - -fn make_writer_order_doc( - te_symbol: &str, - country: &str, - category: &str, - data: RawArrayBuf, - forecast: Option, -) -> RawDocumentBuf { - let mut doc = RawDocumentBuf::new(); - // Exact field order from `apps/stock/data-ingestion/src/handlers/te/actions/data-fetch.action.ts:93-105` - doc.append(cstr!("teSymbol"), te_symbol); - doc.append(cstr!("name"), "United States Fed Funds Interest Rate"); - doc.append(cstr!("unit"), "percent"); - doc.append(cstr!("source"), "Federal Reserve"); - doc.append(cstr!("frequency"), "Daily"); - doc.append(cstr!("country"), country); - doc.append(cstr!("category"), category); - doc.append(cstr!("data"), data); - if let Some(fc) = forecast { - doc.append(cstr!("forecast"), fc); - } - doc.append( - cstr!("lastUpdated"), - DateTime::from_millis(1_710_000_000_000), - ); - doc.append(cstr!("createdAt"), DateTime::from_millis(1_700_000_000_000)); - doc -} - -#[test] -fn decodes_writer_order_document_across_all_three_entry_points() { - let mut data = RawArrayBuf::new(); - data.push(make_point_f64("2024-02-29", 5.5_f64)); - data.push(make_point_f64("2024-03-31", -0.25_f64)); - data.push(make_point_f64("1970-01-01", 0.0_f64)); - - let doc = make_writer_order_doc("FDTR", "United States", "Interest Rate", data, None); - - let expected = vec![ - OwnedPoint { - te_symbol: "FDTR".to_owned(), - country: "United States".to_owned(), - category: "Interest Rate".to_owned(), - period_date: 19_782, // 2024-02-29 - value_bits: 5.5_f64.to_bits(), - }, - OwnedPoint { - te_symbol: "FDTR".to_owned(), - country: "United States".to_owned(), - category: "Interest Rate".to_owned(), - period_date: day(2024, 3, 31), - value_bits: (-0.25_f64).to_bits(), - }, - OwnedPoint { - te_symbol: "FDTR".to_owned(), - country: "United States".to_owned(), - category: "Interest Rate".to_owned(), - period_date: 0, - value_bits: 0.0_f64.to_bits(), - }, - ]; - - // 1. decode_te_data_doc (verify zero-copy borrowed slices directly) - let mut doc_points: Vec> = Vec::new(); - let mut doc_errs = Vec::new(); - let doc_stats = decode_te_data_doc(&doc, |p| doc_points.push(p), |e| doc_errs.push(e)); - assert_stats_conserved(&doc_stats); - assert!(doc_errs.is_empty(), "unexpected errors: {doc_errs:?}"); - assert_eq!(doc_stats.docs_in, 1); - assert_eq!(doc_stats.docs_accepted, 1); - assert_eq!(doc_stats.points_in, 3); - assert_eq!(doc_stats.points_decoded, 3); - let doc_owned: Vec = doc_points.into_iter().map(OwnedPoint::from).collect(); - assert_eq!(doc_owned, expected); - - // 2. decode_te_data_bytes - let mut bytes_points = Vec::new(); - let mut bytes_errs = Vec::new(); - let bytes_stats = decode_te_data_bytes( - doc.as_bytes(), - |p| bytes_points.push(OwnedPoint::from(p)), - |e| bytes_errs.push(e), - ); - assert_stats_conserved(&bytes_stats); - assert!(bytes_errs.is_empty(), "unexpected errors: {bytes_errs:?}"); - assert_eq!(bytes_stats, doc_stats); - assert_eq!(bytes_points, expected); - - // 3. decode_te_data_buffer - let mut buf_points = Vec::new(); - let mut buf_errs = Vec::new(); - let buf_stats = decode_te_data_buffer( - doc.as_bytes(), - |p| buf_points.push(OwnedPoint::from(p)), - |off, e| buf_errs.push((off, e)), - ); - assert_stats_conserved(&buf_stats); - assert!(buf_errs.is_empty(), "unexpected errors: {buf_errs:?}"); - assert_eq!(buf_stats, doc_stats); - assert_eq!(buf_points, expected); -} - -#[test] -fn empty_data_array_accepts_document_and_emits_zero_points() { - let doc = make_writer_order_doc( - "CACPI", - "Canada", - "Inflation Rate", - RawArrayBuf::new(), - None, - ); - let mut points = Vec::new(); - let mut errs = Vec::new(); - let stats = decode_te_data_doc(&doc, |p| points.push(p), |e| errs.push(e)); - - assert_stats_conserved(&stats); - assert!(errs.is_empty(), "unexpected errors: {errs:?}"); - assert!(points.is_empty()); - assert_eq!(stats.docs_in, 1); - assert_eq!(stats.docs_accepted, 1); - assert_eq!(stats.points_in, 0); - assert_eq!(stats.points_decoded, 0); -} - -#[test] -fn data_before_metadata_decodes_identically_to_writer_order() { - let make_data = || { - let mut data = RawArrayBuf::new(); - data.push(make_point_f64("2024-02-29", 4.75_f64)); - data.push(make_point_f64("2025-01-15", 3.25_f64)); - data - }; - - let writer_doc = make_writer_order_doc("CABOC", "Canada", "Interest Rate", make_data(), None); - - let mut reordered_doc = RawDocumentBuf::new(); - reordered_doc.append(cstr!("data"), make_data()); - reordered_doc.append(cstr!("category"), "Interest Rate"); - reordered_doc.append(cstr!("country"), "Canada"); - reordered_doc.append(cstr!("teSymbol"), "CABOC"); - - let mut writer_points = Vec::new(); - let mut writer_errs = Vec::new(); - let writer_stats = decode_te_data_doc( - &writer_doc, - |p| writer_points.push(OwnedPoint::from(p)), - |e| writer_errs.push(e), - ); - - let mut reordered_points = Vec::new(); - let mut reordered_errs = Vec::new(); - let reordered_stats = decode_te_data_doc( - &reordered_doc, - |p| reordered_points.push(OwnedPoint::from(p)), - |e| reordered_errs.push(e), - ); - - assert_stats_conserved(&writer_stats); - assert_stats_conserved(&reordered_stats); - assert!(writer_errs.is_empty()); - assert!(reordered_errs.is_empty()); - assert_eq!(reordered_stats, writer_stats); - assert_eq!(reordered_points, writer_points); -} - -#[test] -fn forecast_is_never_read_or_emitted_before_after_or_when_corrupted() { - let make_data = || { - let mut data = RawArrayBuf::new(); - data.push(make_point_f64("2024-02-29", 3.1_f64)); - data.push(make_point_f64("2024-03-31", 3.2_f64)); - data - }; - - let make_forecast = || { - let mut fc = RawArrayBuf::new(); - fc.push(make_point_f64("2026-06-30", 2.0_f64)); - fc.push("not-even-a-document"); - let mut bad_pt = RawDocumentBuf::new(); - bad_pt.append(cstr!("d"), "invalid-date"); - bad_pt.append(cstr!("v"), RawBson::Null); - fc.push(bad_pt); - fc - }; - - // Baseline: data-only - let baseline_doc = make_writer_order_doc( - "USCPI", - "United States", - "Inflation Rate", - make_data(), - None, - ); - let mut base_points = Vec::new(); - let mut base_errs = Vec::new(); - let base_stats = decode_te_data_doc( - &baseline_doc, - |p| base_points.push(OwnedPoint::from(p)), - |e| base_errs.push(e), - ); - assert_stats_conserved(&base_stats); - assert!(base_errs.is_empty()); - assert_eq!(base_points.len(), 2); - - // Variant 1: populated forecast AFTER data (writer order) - let after_doc = make_writer_order_doc( - "USCPI", - "United States", - "Inflation Rate", - make_data(), - Some(make_forecast()), - ); - let mut after_points = Vec::new(); - let mut after_errs = Vec::new(); - let after_stats = decode_te_data_doc( - &after_doc, - |p| after_points.push(OwnedPoint::from(p)), - |e| after_errs.push(e), - ); - assert_eq!(after_stats, base_stats); - assert_eq!(after_points, base_points); - assert!(after_errs.is_empty()); - - // Variant 2: populated forecast BEFORE data - let mut before_doc = RawDocumentBuf::new(); - before_doc.append(cstr!("forecast"), make_forecast()); - before_doc.append(cstr!("teSymbol"), "USCPI"); - before_doc.append(cstr!("country"), "United States"); - before_doc.append(cstr!("category"), "Inflation Rate"); - before_doc.append(cstr!("data"), make_data()); - - let mut before_points = Vec::new(); - let mut before_errs = Vec::new(); - let before_stats = decode_te_data_doc( - &before_doc, - |p| before_points.push(OwnedPoint::from(p)), - |e| before_errs.push(e), - ); - assert_eq!(before_stats, base_stats); - assert_eq!(before_points, base_points); - assert!(before_errs.is_empty()); - - // Variant 3: corrupt a byte inside the `forecast` array payload while preserving the - // enclosing array length and document terminator. If `elem.value()` or array iteration ever - // inspected `forecast`, this would fail with a corrupt BSON error. - let mut corrupt_fc_bytes = before_doc.as_bytes().to_vec(); - // Locate the array element `\x04forecast\0`, then advance past its 4-byte length prefix - // into the first inner array element's type byte (`0x03` EmbeddedDocument) and corrupt it - // to `0xFF`. - let fc_header = b"\x04forecast\0"; - let fc_pos = corrupt_fc_bytes - .windows(fc_header.len()) - .position(|w| w == fc_header) - .expect("find forecast array element"); - let first_inner_elem_type_pos = fc_pos + fc_header.len() + 4; - assert_eq!( - corrupt_fc_bytes[first_inner_elem_type_pos], 0x03, - "expected EmbeddedDocument type byte for forecast[0]" - ); - corrupt_fc_bytes[first_inner_elem_type_pos] = 0xFF; - - let mut corrupt_fc_points = Vec::new(); - let mut corrupt_fc_errs = Vec::new(); - let corrupt_fc_stats = decode_te_data_bytes( - &corrupt_fc_bytes, - |p| corrupt_fc_points.push(OwnedPoint::from(p)), - |e| corrupt_fc_errs.push(e), - ); - assert_stats_conserved(&corrupt_fc_stats); - assert_eq!(corrupt_fc_stats, base_stats); - assert_eq!(corrupt_fc_points, base_points); - assert!( - corrupt_fc_errs.is_empty(), - "corrupt forecast payload must never be read, got: {corrupt_fc_errs:?}" - ); -} - -#[test] -fn rejects_missing_empty_and_wrong_type_required_top_level_fields() { - let valid_data = || { - let mut data = RawArrayBuf::new(); - data.push(make_point_f64("2024-02-29", 1.0_f64)); - data - }; - - // Helper to assert a single rejected doc emits zero points and exact error + counter. - let check_reject = |doc: RawDocumentBuf, - expected_err: BsonTeDataError, - check_counter: fn(&BsonTeDataDecodeStats) -> usize| { - let mut points = Vec::new(); - let mut errs = Vec::new(); - let stats = decode_te_data_doc(&doc, |p| points.push(p), |e| errs.push(e)); - assert_stats_conserved(&stats); - assert!(points.is_empty(), "rejected doc must emit zero points"); - assert_eq!(stats.docs_in, 1); - assert_eq!(stats.docs_accepted, 0); - assert_eq!(stats.docs_rejected_total(), 1); - assert_eq!( - check_counter(&stats), - 1, - "wrong counter for {expected_err:?}: {stats:?}" - ); - assert_eq!(errs, vec![expected_err]); - let msg = errs[0].to_string(); - assert!(!msg.contains('\n'), "multiline error display: {msg}"); - }; - - // --- teSymbol --- - // Missing - let mut d = RawDocumentBuf::new(); - d.append(cstr!("country"), "Canada"); - d.append(cstr!("category"), "GDP"); - d.append(cstr!("data"), valid_data()); - check_reject(d, BsonTeDataError::MissingSymbol, |s| { - s.rejected_missing_symbol - }); - - // Empty ("") - let mut d = RawDocumentBuf::new(); - d.append(cstr!("teSymbol"), ""); - d.append(cstr!("country"), "Canada"); - d.append(cstr!("category"), "GDP"); - d.append(cstr!("data"), valid_data()); - check_reject(d, BsonTeDataError::EmptySymbol, |s| s.rejected_empty_symbol); - - // Whitespace-only (" \t ") - let mut d = RawDocumentBuf::new(); - d.append(cstr!("teSymbol"), " \t "); - d.append(cstr!("country"), "Canada"); - d.append(cstr!("category"), "GDP"); - d.append(cstr!("data"), valid_data()); - check_reject(d, BsonTeDataError::EmptySymbol, |s| s.rejected_empty_symbol); - - // Non-string - let mut d = RawDocumentBuf::new(); - d.append(cstr!("teSymbol"), 42_i32); - d.append(cstr!("country"), "Canada"); - d.append(cstr!("category"), "GDP"); - d.append(cstr!("data"), valid_data()); - check_reject( - d, - BsonTeDataError::WrongSymbolType { - actual: ElementType::Int32, - }, - |s| s.rejected_wrong_symbol_type, - ); - - // --- country --- - // Missing - let mut d = RawDocumentBuf::new(); - d.append(cstr!("teSymbol"), "CAGDP"); - d.append(cstr!("category"), "GDP"); - d.append(cstr!("data"), valid_data()); - check_reject(d, BsonTeDataError::MissingCountry, |s| { - s.rejected_missing_country - }); - - // Empty ("") - let mut d = RawDocumentBuf::new(); - d.append(cstr!("teSymbol"), "CAGDP"); - d.append(cstr!("country"), ""); - d.append(cstr!("category"), "GDP"); - d.append(cstr!("data"), valid_data()); - check_reject(d, BsonTeDataError::EmptyCountry, |s| { - s.rejected_empty_country - }); - - // Whitespace-only - let mut d = RawDocumentBuf::new(); - d.append(cstr!("teSymbol"), "CAGDP"); - d.append(cstr!("country"), " "); - d.append(cstr!("category"), "GDP"); - d.append(cstr!("data"), valid_data()); - check_reject(d, BsonTeDataError::EmptyCountry, |s| { - s.rejected_empty_country - }); - - // Non-string - let mut d = RawDocumentBuf::new(); - d.append(cstr!("teSymbol"), "CAGDP"); - d.append(cstr!("country"), RawBson::Null); - d.append(cstr!("category"), "GDP"); - d.append(cstr!("data"), valid_data()); - check_reject( - d, - BsonTeDataError::WrongCountryType { - actual: ElementType::Null, - }, - |s| s.rejected_wrong_country_type, - ); - - // --- category --- - // Missing - let mut d = RawDocumentBuf::new(); - d.append(cstr!("teSymbol"), "CAGDP"); - d.append(cstr!("country"), "Canada"); - d.append(cstr!("data"), valid_data()); - check_reject(d, BsonTeDataError::MissingCategory, |s| { - s.rejected_missing_category - }); - - // Empty ("") - let mut d = RawDocumentBuf::new(); - d.append(cstr!("teSymbol"), "CAGDP"); - d.append(cstr!("country"), "Canada"); - d.append(cstr!("category"), ""); - d.append(cstr!("data"), valid_data()); - check_reject(d, BsonTeDataError::EmptyCategory, |s| { - s.rejected_empty_category - }); - - // Non-string - let mut d = RawDocumentBuf::new(); - d.append(cstr!("teSymbol"), "CAGDP"); - d.append(cstr!("country"), "Canada"); - d.append(cstr!("category"), true); - d.append(cstr!("data"), valid_data()); - check_reject( - d, - BsonTeDataError::WrongCategoryType { - actual: ElementType::Boolean, - }, - |s| s.rejected_wrong_category_type, - ); - - // --- data --- - // Missing - let mut d = RawDocumentBuf::new(); - d.append(cstr!("teSymbol"), "CAGDP"); - d.append(cstr!("country"), "Canada"); - d.append(cstr!("category"), "GDP"); - check_reject(d, BsonTeDataError::MissingData, |s| s.rejected_data_missing); - - // Document-valued `data` - let mut d = RawDocumentBuf::new(); - d.append(cstr!("teSymbol"), "CAGDP"); - d.append(cstr!("country"), "Canada"); - d.append(cstr!("category"), "GDP"); - d.append(cstr!("data"), RawDocumentBuf::new()); - check_reject( - d, - BsonTeDataError::DataNotArray { - actual: ElementType::EmbeddedDocument, - }, - |s| s.rejected_data_not_array, - ); - - // Scalar `data` - let mut d = RawDocumentBuf::new(); - d.append(cstr!("teSymbol"), "CAGDP"); - d.append(cstr!("country"), "Canada"); - d.append(cstr!("category"), "GDP"); - d.append(cstr!("data"), "not-an-array"); - check_reject( - d, - BsonTeDataError::DataNotArray { - actual: ElementType::String, - }, - |s| s.rejected_data_not_array, - ); -} - -#[test] -fn point_level_validation_numeric_types_and_non_finite_passthrough() { - let mut data = RawArrayBuf::new(); - - // [0] Valid Double - data.push(make_point_f64("2024-02-29", 5.25_f64)); - - // [1] Invalid date: non-existent Feb 30 - data.push(make_point_f64("2024-02-30", 1.0_f64)); - // [2] Invalid date: non-leap year Feb 29 - data.push(make_point_f64("2023-02-29", 1.0_f64)); - // [3] Invalid date: non-padded month/day - data.push(make_point_f64("2024-2-1", 1.0_f64)); - // [4] Invalid date: leading whitespace (no trimming) - data.push(make_point_f64(" 2024-01-01", 1.0_f64)); - // [5] Invalid date: compact YYYYMMDD - data.push(make_point_f64("20240101", 1.0_f64)); - // [6] Invalid date: non-string (`Int32`) - let mut pt_int_d = RawDocumentBuf::new(); - pt_int_d.append(cstr!("d"), 20240101_i32); - pt_int_d.append(cstr!("v"), 1.0_f64); - data.push(pt_int_d); - // [7] Missing `d` - let mut pt_no_d = RawDocumentBuf::new(); - pt_no_d.append(cstr!("v"), 1.0_f64); - data.push(pt_no_d); - - // [8] Valid Int32 `v` (interleaved after bad dates to prove continuation) - let mut pt_i32 = RawDocumentBuf::new(); - pt_i32.append(cstr!("d"), "2024-03-01"); - pt_i32.append(cstr!("v"), -7_i32); - data.push(pt_i32); - - // [9] Invalid `v`: Null - let mut pt_null_v = RawDocumentBuf::new(); - pt_null_v.append(cstr!("d"), "2024-03-02"); - pt_null_v.append(cstr!("v"), RawBson::Null); - data.push(pt_null_v); - // [10] Invalid `v`: String - let mut pt_str_v = RawDocumentBuf::new(); - pt_str_v.append(cstr!("d"), "2024-03-03"); - pt_str_v.append(cstr!("v"), "5.25"); - data.push(pt_str_v); - // [11] Invalid `v`: Bool - let mut pt_bool_v = RawDocumentBuf::new(); - pt_bool_v.append(cstr!("d"), "2024-03-04"); - pt_bool_v.append(cstr!("v"), false); - data.push(pt_bool_v); - // [12] Missing `v` - let mut pt_no_v = RawDocumentBuf::new(); - pt_no_v.append(cstr!("d"), "2024-03-05"); - data.push(pt_no_v); - - // [13] Non-document array element - data.push("scalar-item"); - - // [14] Valid Int64 `v` - let mut pt_i64 = RawDocumentBuf::new(); - pt_i64.append(cstr!("d"), "2024-03-06"); - pt_i64.append(cstr!("v"), 1_000_000_000_000_i64); - data.push(pt_i64); - - // [15] Signed zero (-0.0) passed through bit-identically - data.push(make_point_f64("2024-03-07", -0.0_f64)); - // [16] Payload-bearing NaN passed through bit-identically - let payload_nan = f64::from_bits(0x7ff8_0000_0000_1234); - assert!(payload_nan.is_nan()); - data.push(make_point_f64("2024-03-08", payload_nan)); - // [17] +Infinity passed through bit-identically - data.push(make_point_f64("2024-03-09", f64::INFINITY)); - // [18] -Infinity passed through bit-identically - data.push(make_point_f64("2024-03-10", f64::NEG_INFINITY)); - - let doc = make_writer_order_doc("TEST", "United States", "CPI", data, None); - - let mut points = Vec::new(); - let mut errs = Vec::new(); - let stats = decode_te_data_doc(&doc, |p| points.push(p), |e| errs.push(e)); - - assert_stats_conserved(&stats); - assert_eq!(stats.docs_in, 1); - assert_eq!(stats.docs_accepted, 1); - assert_eq!(stats.points_in, 19); - assert_eq!(stats.points_decoded, 7); - assert_eq!(stats.rejected_invalid_date, 7); - assert_eq!(stats.rejected_invalid_value, 4); - assert_eq!(stats.rejected_point_not_document, 1); - assert_eq!(stats.rejected_corrupt_point, 0); - assert_eq!(errs.len(), 12); - - assert_eq!(points.len(), 7); - assert_eq!(points[0].period_date, 19_782); - assert_eq!(points[0].value.to_bits(), 5.25_f64.to_bits()); - - assert_eq!(points[1].period_date, day(2024, 3, 1)); - assert_eq!(points[1].value.to_bits(), (-7.0_f64).to_bits()); - - assert_eq!(points[2].period_date, day(2024, 3, 6)); - assert_eq!(points[2].value.to_bits(), 1_000_000_000_000.0_f64.to_bits()); - - assert_eq!(points[3].period_date, day(2024, 3, 7)); - assert_eq!(points[3].value.to_bits(), (-0.0_f64).to_bits()); - - assert_eq!(points[4].period_date, day(2024, 3, 8)); - assert_eq!(points[4].value.to_bits(), payload_nan.to_bits()); - - assert_eq!(points[5].period_date, day(2024, 3, 9)); - assert_eq!(points[5].value.to_bits(), f64::INFINITY.to_bits()); - - assert_eq!(points[6].period_date, day(2024, 3, 10)); - assert_eq!(points[6].value.to_bits(), f64::NEG_INFINITY.to_bits()); - - // Spot-check error variants and single-line Display - assert!(errs - .iter() - .any(|e| matches!(e, BsonTeDataError::InvalidPointDate { point_index: 1 }))); - assert!(errs.iter().any(|e| matches!( - e, - BsonTeDataError::WrongPointFieldType { - point_index: 6, - field: FIELD_POINT_D, - actual: ElementType::Int32 - } - ))); - assert!(errs.iter().any(|e| matches!( - e, - BsonTeDataError::MissingPointField { - point_index: 7, - field: FIELD_POINT_D - } - ))); - assert!(errs.iter().any(|e| matches!( - e, - BsonTeDataError::WrongPointFieldType { - point_index: 9, - field: FIELD_POINT_V, - actual: ElementType::Null - } - ))); - assert!(errs.iter().any(|e| matches!( - e, - BsonTeDataError::MissingPointField { - point_index: 12, - field: FIELD_POINT_V - } - ))); - assert!(errs.iter().any(|e| matches!( - e, - BsonTeDataError::PointNotDocument { - point_index: 13, - actual: ElementType::String - } - ))); - - for err in &errs { - let msg = err.to_string(); - assert!(!msg.contains('\n'), "multiline error display: {msg}"); - } -} - -#[test] -fn multi_doc_buffer_conservation_and_chunk_merge_parity() { - // Chunk 1: good doc + rejected doc (missing country) + mixed valid/invalid points doc - let mut chunk1 = Vec::new(); - - let mut d1_data = RawArrayBuf::new(); - d1_data.push(make_point_f64("2024-01-31", 4.5_f64)); - d1_data.push(make_point_f64("2024-02-29", 4.5_f64)); - let doc1 = make_writer_order_doc("FDTR", "United States", "Interest Rate", d1_data, None); - chunk1.extend_from_slice(doc1.as_bytes()); - - let mut doc2_missing_country = RawDocumentBuf::new(); - doc2_missing_country.append(cstr!("teSymbol"), "BAD1"); - doc2_missing_country.append(cstr!("category"), "GDP"); - doc2_missing_country.append(cstr!("data"), RawArrayBuf::new()); - chunk1.extend_from_slice(doc2_missing_country.as_bytes()); - - let mut d3_data = RawArrayBuf::new(); - d3_data.push(make_point_f64("2023-02-29", 1.0_f64)); // invalid date - d3_data.push(make_point_f64("2024-03-31", 2.9_f64)); // valid - let doc3 = make_writer_order_doc("CACPI", "Canada", "Inflation Rate", d3_data, None); - chunk1.extend_from_slice(doc3.as_bytes()); - - // Chunk 2: rejected doc (data not array) + empty-data doc + valid doc with bad v - let mut chunk2 = Vec::new(); - - let mut doc4_bad_data = RawDocumentBuf::new(); - doc4_bad_data.append(cstr!("teSymbol"), "BAD2"); - doc4_bad_data.append(cstr!("country"), "Canada"); - doc4_bad_data.append(cstr!("category"), "GDP"); - doc4_bad_data.append(cstr!("data"), 99_i32); - chunk2.extend_from_slice(doc4_bad_data.as_bytes()); - - let doc5_empty = make_writer_order_doc("EMPTY", "Canada", "GDP", RawArrayBuf::new(), None); - chunk2.extend_from_slice(doc5_empty.as_bytes()); - - let mut d6_data = RawArrayBuf::new(); - d6_data.push(123_i32); // PointNotDocument - let mut bad_v = RawDocumentBuf::new(); - bad_v.append(cstr!("d"), "2024-04-30"); - bad_v.append(cstr!("v"), "NaN"); - d6_data.push(bad_v); - d6_data.push(make_point_f64("2024-05-31", 1.75_f64)); - let doc6 = make_writer_order_doc("CAGDP", "Canada", "GDP Growth Rate", d6_data, None); - chunk2.extend_from_slice(doc6.as_bytes()); - - let mut full_buf = Vec::with_capacity(chunk1.len() + chunk2.len()); - full_buf.extend_from_slice(&chunk1); - full_buf.extend_from_slice(&chunk2); - - // Decode concatenated buffer - let mut full_points = Vec::new(); - let mut full_errs = Vec::new(); - let full_stats = decode_te_data_buffer( - &full_buf, - |p| full_points.push(OwnedPoint::from(p)), - |off, e| full_errs.push((off, e)), - ); - assert_stats_conserved(&full_stats); - - // Decode chunk 1 and chunk 2 separately and merge - let mut split_points = Vec::new(); - let stats1 = decode_te_data_buffer( - &chunk1, - |p| split_points.push(OwnedPoint::from(p)), - |_, _| {}, - ); - assert_stats_conserved(&stats1); - - let stats2 = decode_te_data_buffer( - &chunk2, - |p| split_points.push(OwnedPoint::from(p)), - |_, _| {}, - ); - assert_stats_conserved(&stats2); - - let mut merged = stats1; - merged.merge(&stats2); - assert_stats_conserved(&merged); - - assert_eq!(merged, full_stats); - assert_eq!(split_points, full_points); - assert_eq!(full_stats.docs_in, 6); - assert_eq!(full_stats.docs_accepted, 4); - assert_eq!(full_stats.docs_rejected_total(), 2); - assert_eq!(full_stats.points_in, 7); - assert_eq!(full_stats.points_decoded, 4); - assert_eq!(full_stats.rejected_total(), 3); - assert_eq!(full_errs.len(), 5); -} - -#[test] -fn framed_corrupt_doc_recovery_and_truncated_tail_offsets() { - // 1. decode_te_data_bytes on truncated input - let mut trunc_errs = Vec::new(); - let trunc_stats = decode_te_data_bytes(&[10, 0, 0, 0, 1], |_| {}, |e| trunc_errs.push(e)); - assert_stats_conserved(&trunc_stats); - assert_eq!(trunc_stats.docs_in, 1); - assert_eq!(trunc_stats.rejected_corrupt_document, 1); - assert!(matches!( - trunc_errs.as_slice(), - [BsonTeDataError::TruncatedDocument { - offset: 0, - remaining: 5, - declared_len: Some(10) - }] - )); - - // 2. Buffer: [recoverably corrupt framed doc] + [valid doc] + [truncated tail] - // Valid 4-byte length prefix (12 bytes) with invalid element type byte 0xFF and trailing NUL - let bad_framed_doc: [u8; 12] = [12, 0, 0, 0, 0xFF, b'a', 0, 0, 0, 0, 0, 0]; - - let mut good_data = RawArrayBuf::new(); - good_data.push(make_point_f64("2024-02-29", 3.5_f64)); - let good_doc = make_writer_order_doc("FDTR", "United States", "Interest Rate", good_data, None); - - let truncated_tail: [u8; 3] = [20, 0, 0]; - - let mut buf = Vec::new(); - buf.extend_from_slice(&bad_framed_doc); - let good_offset = buf.len(); - buf.extend_from_slice(good_doc.as_bytes()); - let tail_offset = buf.len(); - buf.extend_from_slice(&truncated_tail); - - let mut points = Vec::new(); - let mut errs = Vec::new(); - let stats = decode_te_data_buffer( - &buf, - |p| points.push(OwnedPoint::from(p)), - |off, e| errs.push((off, e)), - ); - - assert_stats_conserved(&stats); - assert_eq!(good_offset, 12); - assert_eq!(stats.docs_in, 3); - assert_eq!(stats.docs_accepted, 1); - assert_eq!(stats.rejected_corrupt_document, 2); - assert_eq!(stats.points_in, 1); - assert_eq!(stats.points_decoded, 1); - assert_eq!(points.len(), 1); - assert_eq!(points[0].te_symbol, "FDTR"); - assert_eq!(points[0].period_date, 19_782); - assert_eq!(points[0].value_bits, 3.5_f64.to_bits()); - - assert_eq!(errs.len(), 2); - assert_eq!(errs[0].0, 0); - assert!(matches!( - errs[0].1, - BsonTeDataError::CorruptBson { offset: 0, .. } - )); - assert_eq!(errs[1].0, tail_offset); - assert!(matches!( - errs[1].1, - BsonTeDataError::TruncatedDocument { - offset, - remaining: 3, - declared_len: None - } if offset == tail_offset - )); - - // 3. CorruptDocumentLength (< 5) terminates cleanly - let bad_len_buf: [u8; 8] = [4, 0, 0, 0, 0, 0, 0, 0]; - let mut bad_len_errs = Vec::new(); - let bad_len_stats = decode_te_data_buffer( - &bad_len_buf, - |_| panic!("no points expected"), - |off, e| bad_len_errs.push((off, e)), - ); - assert_stats_conserved(&bad_len_stats); - assert_eq!(bad_len_stats.docs_in, 1); - assert_eq!(bad_len_stats.rejected_corrupt_document, 1); - assert_eq!( - bad_len_errs, - vec![( - 0, - BsonTeDataError::CorruptDocumentLength { - offset: 0, - declared_len: 4 - } - )] - ); -} - -#[test] -fn structural_corruption_after_semantic_reject_takes_precedence() { - // 1. Point with invalid `d` followed by corrupt element type byte on `v`. - let mut pt = RawDocumentBuf::new(); - pt.append(cstr!("d"), "2024-02-30"); - pt.append(cstr!("v"), 1.25_f64); - - let mut data = RawArrayBuf::new(); - data.push(pt); - let doc = make_writer_order_doc("FDTR", "United States", "Interest Rate", data, None); - let mut bytes = doc.as_bytes().to_vec(); - let v_elem_pos = bytes - .windows(3) - .position(|w| w == b"\x01v\0") - .expect("find double element 'v'"); - bytes[v_elem_pos] = 0xFF; - - let mut points = Vec::new(); - let mut errs = Vec::new(); - let stats = decode_te_data_bytes(&bytes, |p| points.push(p), |e| errs.push(e)); - assert_stats_conserved(&stats); - assert!(points.is_empty()); - assert_eq!(stats.points_in, 1); - assert_eq!(stats.rejected_corrupt_point, 1); - assert_eq!(stats.rejected_invalid_date, 0); - assert!( - matches!( - errs.as_slice(), - [BsonTeDataError::CorruptPointBson { point_index: 0, .. }] - ), - "expected CorruptPointBson to take precedence over InvalidPointDate, got {errs:?}" - ); - - // 2. Top-level doc with empty `teSymbol` followed by corrupt element type byte on `data`. - let mut bad_top = RawDocumentBuf::new(); - bad_top.append(cstr!("teSymbol"), ""); - bad_top.append(cstr!("country"), "Canada"); - bad_top.append(cstr!("category"), "GDP"); - bad_top.append(cstr!("data"), RawArrayBuf::new()); - let mut doc_bytes = bad_top.as_bytes().to_vec(); - let data_elem_pos = doc_bytes - .windows(6) - .position(|w| w == b"\x04data\0") - .expect("find array element 'data'"); - doc_bytes[data_elem_pos] = 0xFF; - - let mut top_errs = Vec::new(); - let top_stats = decode_te_data_bytes(&doc_bytes, |_| {}, |e| top_errs.push(e)); - assert_stats_conserved(&top_stats); - assert_eq!(top_stats.rejected_corrupt_document, 1); - assert_eq!(top_stats.rejected_empty_symbol, 0); - assert!( - matches!(top_errs.as_slice(), [BsonTeDataError::CorruptBson { .. }]), - "expected CorruptBson to take precedence over EmptySymbol, got {top_errs:?}" - ); -} - -// --------------------------------------------------------------------------- -// QA (T-174) edge cases -// --------------------------------------------------------------------------- - -/// Replaces the first occurrence of `needle` in `bytes` with `replacement` (same length), so -/// BSON length prefixes and terminators stay intact. -fn patch_bytes(bytes: &mut [u8], needle: &[u8], replacement: &[u8]) { - assert_eq!(needle.len(), replacement.len()); - let pos = bytes - .windows(needle.len()) - .position(|w| w == needle) - .expect("needle present in fixture"); - bytes[pos..pos + needle.len()].copy_from_slice(replacement); -} - -fn decode_bytes_owned( - bytes: &[u8], -) -> (Vec, Vec, BsonTeDataDecodeStats) { - let mut points = Vec::new(); - let mut errs = Vec::new(); - let stats = decode_te_data_bytes( - bytes, - |p| points.push(OwnedPoint::from(p)), - |e| errs.push(e), - ); - assert_stats_conserved(&stats); - (points, errs, stats) -} - -fn two_point_data() -> RawArrayBuf { - let mut data = RawArrayBuf::new(); - data.push(make_point_f64("2024-01-31", 5.33_f64)); - data.push(make_point_f64("2024-02-29", 5.33_f64)); - data -} - -#[test] -fn qa_forecast_and_metadata_with_value_level_corruption_are_skipped_unread() { - let baseline = make_writer_order_doc( - "FDTR", - "United States", - "Interest Rate", - two_point_data(), - None, - ); - let (base_points, base_errs, base_stats) = decode_bytes_owned(baseline.as_bytes()); - assert!(base_errs.is_empty()); - assert_eq!(base_points.len(), 2); - - // `forecast` as a framed BSON string whose payload is invalid UTF-8: framing is intact, but - // `elem.value()` fails. Same for descriptive `name` and an unknown field. - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("forecast"), "QQQQFC"); - doc.append(cstr!("teSymbol"), "FDTR"); - doc.append(cstr!("name"), "QQQQNM"); - doc.append(cstr!("country"), "United States"); - doc.append(cstr!("category"), "Interest Rate"); - doc.append(cstr!("data"), two_point_data()); - doc.append(cstr!("someFutureField"), "QQQQUF"); - let mut bytes = doc.as_bytes().to_vec(); - patch_bytes(&mut bytes, b"QQQQFC", &[0xFF, 0xFE, 0xFF, 0xFE, 0xFF, 0xFE]); - patch_bytes(&mut bytes, b"QQQQNM", &[0xFF, 0xFE, 0xFF, 0xFE, 0xFF, 0xFE]); - patch_bytes(&mut bytes, b"QQQQUF", &[0xFF, 0xFE, 0xFF, 0xFE, 0xFF, 0xFE]); - - // Fixture sanity: resolving these values really fails, so a reader that called - // `elem.value()` on them would surface an error. - let raw = RawDocument::from_bytes(&bytes).expect("framing intact"); - for key in ["forecast", "name", "someFutureField"] { - let elem = raw - .iter_elements() - .map(|e| e.expect("element framing intact")) - .find(|e| e.key().as_str() == key) - .expect("key present"); - assert!( - elem.value().is_err(), - "fixture for {key} must fail at elem.value()" - ); - } - - let (points, errs, stats) = decode_bytes_owned(&bytes); - assert!( - errs.is_empty(), - "skipped fields must never be resolved: {errs:?}" - ); - assert_eq!(stats, base_stats); - assert_eq!(points, base_points); -} - -#[test] -fn qa_forecast_only_document_is_rejected_as_missing_data_with_no_fallback() { - let mut fc = RawArrayBuf::new(); - fc.push(make_point_f64("2027-12-31", 9.99_f64)); - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("teSymbol"), "FDTR"); - doc.append(cstr!("country"), "United States"); - doc.append(cstr!("category"), "Interest Rate"); - doc.append(cstr!("forecast"), fc); - - let (points, errs, stats) = decode_bytes_owned(doc.as_bytes()); - assert!( - points.is_empty(), - "forecast must never substitute for missing data" - ); - assert_eq!(errs, vec![BsonTeDataError::MissingData]); - assert_eq!(stats.rejected_data_missing, 1); - assert_eq!(stats.docs_accepted, 0); - assert_eq!(stats.points_in, 0); -} - -#[test] -fn qa_provider_labels_are_verbatim_and_borrowed_from_input_bytes() { - let doc = make_writer_order_doc( - " usgdp ", - "Côte d'Ivoire", - "GDP Growth Rate ", - two_point_data(), - None, - ); - let bytes = doc.as_bytes(); - let range = bytes.as_ptr_range(); - let mut points = Vec::new(); - let stats = decode_te_data_bytes(bytes, |p| points.push(p), |e| panic!("unexpected {e:?}")); - assert_stats_conserved(&stats); - assert_eq!(points.len(), 2); - for p in &points { - // No trimming, case folding or ISO mapping. - assert_eq!(p.te_symbol, " usgdp "); - assert_eq!(p.country, "Côte d'Ivoire"); - assert_eq!(p.category, "GDP Growth Rate "); - // Zero-copy: every label slice points into the caller's buffer. - for s in [p.te_symbol, p.country, p.category] { - assert!( - range.contains(&s.as_ptr()), - "label {s:?} not borrowed from input" - ); - } - } -} - -#[test] -fn qa_additional_strict_date_and_value_type_rejections() { - let bad_dates = [ - "2024-01-01 ", - "2024-01-01T00:00:00Z", - "2024-01-01T00:00:00.000Z", - "2024/01/01", - "", - "2024-13-01", - "2024-00-10", - "2024-01-00", - "2024-04-31", - ]; - let mut data = RawArrayBuf::new(); - for d in bad_dates { - data.push(make_point_f64(d, 1.0)); - } - // `d` as BSON DateTime (not a string) is rejected, not coerced. - let mut pt = RawDocumentBuf::new(); - pt.append(cstr!("d"), DateTime::from_millis(1_704_067_200_000)); - pt.append(cstr!("v"), 1.0_f64); - data.push(pt); - // `v` as DateTime and as an embedded document are rejected. - let mut pt = RawDocumentBuf::new(); - pt.append(cstr!("d"), "2024-01-02"); - pt.append(cstr!("v"), DateTime::from_millis(0)); - data.push(pt); - let mut pt = RawDocumentBuf::new(); - pt.append(cstr!("d"), "2024-01-03"); - pt.append(cstr!("v"), RawDocumentBuf::new()); - data.push(pt); - // Field order `v` before `d` plus an unknown point field still decodes. - let mut pt = RawDocumentBuf::new(); - pt.append(cstr!("v"), i32::MIN); - pt.append(cstr!("note"), "ignored"); - pt.append(cstr!("d"), "2000-02-29"); - data.push(pt); - let mut pt = RawDocumentBuf::new(); - pt.append(cstr!("d"), "1969-12-31"); - pt.append(cstr!("v"), i64::MAX); - data.push(pt); - - let doc = make_writer_order_doc("X", "Y", "Z", data, None); - let mut points = Vec::new(); - let mut errs = Vec::new(); - let stats = decode_te_data_doc(&doc, |p| points.push(OwnedPoint::from(p)), |e| errs.push(e)); - assert_stats_conserved(&stats); - assert_eq!(stats.points_in, 14); - assert_eq!(stats.rejected_invalid_date, 10); - assert_eq!(stats.rejected_invalid_value, 2); - assert_eq!(stats.points_decoded, 2); - assert!(errs.iter().any(|e| matches!( - e, - BsonTeDataError::WrongPointFieldType { - point_index: 9, - field: FIELD_POINT_D, - actual: ElementType::DateTime - } - ))); - assert!(errs.iter().any(|e| matches!( - e, - BsonTeDataError::WrongPointFieldType { - point_index: 11, - field: FIELD_POINT_V, - actual: ElementType::EmbeddedDocument - } - ))); - assert_eq!(points[0].period_date, day(2000, 2, 29)); - assert_eq!(points[0].value_bits, f64::from(i32::MIN).to_bits()); - assert_eq!(points[1].period_date, -1); - assert_eq!(points[1].value_bits, (i64::MAX as f64).to_bits()); -} - -#[test] -fn qa_top_level_rejection_order_is_deterministic_and_counts_once() { - // Missing teSymbol + wrong-typed country + no data: only MissingSymbol is counted. - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("data"), 1_i32); - doc.append(cstr!("country"), 5_i32); - doc.append(cstr!("category"), ""); - let (points, errs, stats) = decode_bytes_owned(doc.as_bytes()); - assert!(points.is_empty()); - assert_eq!(errs, vec![BsonTeDataError::MissingSymbol]); - assert_eq!(stats.docs_rejected_total(), 1); - assert_eq!(stats.rejected_missing_symbol, 1); - - // Valid symbol, empty country, empty category, non-array data: country wins. - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("data"), "nope"); - doc.append(cstr!("category"), ""); - doc.append(cstr!("country"), " "); - doc.append(cstr!("teSymbol"), "S"); - let (_, errs, stats) = decode_bytes_owned(doc.as_bytes()); - assert_eq!(errs, vec![BsonTeDataError::EmptyCountry]); - assert_eq!(stats.docs_rejected_total(), 1); - - // Duplicate `teSymbol` where one copy is blank fails closed in either order. - for (first, second) in [("FDTR", ""), ("", "FDTR")] { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("teSymbol"), first); - doc.append(cstr!("teSymbol"), second); - doc.append(cstr!("country"), "United States"); - doc.append(cstr!("category"), "Interest Rate"); - doc.append(cstr!("data"), two_point_data()); - let (points, errs, stats) = decode_bytes_owned(doc.as_bytes()); - assert!( - points.is_empty(), - "duplicate blank teSymbol must reject ({first:?},{second:?})" - ); - assert_eq!(errs, vec![BsonTeDataError::EmptySymbol]); - assert_eq!(stats.rejected_empty_symbol, 1); - } -} - -#[test] -fn qa_bytes_entry_point_rejects_trailing_bytes_and_short_headers() { - let doc = make_writer_order_doc( - "FDTR", - "United States", - "Interest Rate", - two_point_data(), - None, - ); - let mut bytes = doc.as_bytes().to_vec(); - bytes.push(0); - let (points, errs, stats) = decode_bytes_owned(&bytes); - assert!(points.is_empty()); - assert_eq!(stats.rejected_corrupt_document, 1); - assert!(matches!( - errs.as_slice(), - [BsonTeDataError::CorruptDocumentLength { offset: 0, .. }] - )); - - let (points, errs, stats) = decode_bytes_owned(&[1, 0]); - assert!(points.is_empty()); - assert_eq!(stats.docs_in, 1); - assert!(matches!( - errs.as_slice(), - [BsonTeDataError::TruncatedDocument { - offset: 0, - remaining: 2, - declared_len: None - }] - )); -} - -#[test] -fn qa_empty_buffer_yields_zero_stats() { - let stats = decode_te_data_buffer( - &[], - |_| panic!("no points"), - |_, e| panic!("no errors: {e:?}"), - ); - assert_eq!(stats, BsonTeDataDecodeStats::default()); -} - -#[test] -fn qa_buffer_semantic_errors_report_the_owning_document_offset() { - let good = make_writer_order_doc("A", "Canada", "GDP", two_point_data(), None); - let mut bad_point_data = RawArrayBuf::new(); - bad_point_data.push(make_point_f64("2024-02-30", 1.0)); - let bad_point = make_writer_order_doc("B", "Canada", "GDP", bad_point_data, None); - let mut no_symbol = RawDocumentBuf::new(); - no_symbol.append(cstr!("country"), "Canada"); - no_symbol.append(cstr!("category"), "GDP"); - no_symbol.append(cstr!("data"), two_point_data()); - - let mut buf = Vec::new(); - buf.extend_from_slice(good.as_bytes()); - let bad_point_off = buf.len(); - buf.extend_from_slice(bad_point.as_bytes()); - let no_symbol_off = buf.len(); - buf.extend_from_slice(no_symbol.as_bytes()); - - let mut points = Vec::new(); - let mut errs = Vec::new(); - let stats = decode_te_data_buffer( - &buf, - |p| points.push(OwnedPoint::from(p)), - |o, e| errs.push((o, e)), - ); - assert_stats_conserved(&stats); - assert_eq!(points.len(), 2); - assert!(points.iter().all(|p| p.te_symbol == "A")); - assert_eq!( - errs, - vec![ - ( - bad_point_off, - BsonTeDataError::InvalidPointDate { point_index: 0 } - ), - (no_symbol_off, BsonTeDataError::MissingSymbol), - ] - ); -} - -#[test] -fn qa_unreadable_scalar_in_data_is_counted_and_never_fabricates_points() { - // A framed scalar string with invalid UTF-8 inside `data`, between two valid points. - let mut data = RawArrayBuf::new(); - data.push(make_point_f64("2024-01-31", 1.5)); - data.push("QQQQBD"); - data.push(make_point_f64("2024-02-29", 2.5)); - let doc = make_writer_order_doc("FDTR", "United States", "Interest Rate", data, None); - let mut bytes = doc.as_bytes().to_vec(); - patch_bytes(&mut bytes, b"QQQQBD", &[0xFF, 0xFE, 0xFF, 0xFE, 0xFF, 0xFE]); - - let (points, errs, stats) = decode_bytes_owned(&bytes); - assert_eq!(stats.docs_accepted, 1); - assert_eq!(points[0].period_date, day(2024, 1, 31)); - assert_eq!(points[0].value_bits, 1.5_f64.to_bits()); - // Every emitted point is one of the genuine observations, never a fabricated one. - for p in &points { - assert!( - (p.period_date == day(2024, 1, 31) && p.value_bits == 1.5_f64.to_bits()) - || (p.period_date == day(2024, 2, 29) && p.value_bits == 2.5_f64.to_bits()), - "fabricated point {p:?}" - ); - } - assert!( - stats.rejected_total() >= 1, - "unreadable item must be counted: {stats:?}" - ); - assert!(errs.iter().any(|e| matches!( - e, - BsonTeDataError::CorruptPointBson { point_index: 1, .. } - | BsonTeDataError::PointNotDocument { point_index: 1, .. } - ))); -} diff --git a/tools/curate-etl/src/bson_te_market_data.rs b/tools/curate-etl/src/bson_te_market_data.rs deleted file mode 100644 index fd9cff97..00000000 --- a/tools/curate-etl/src/bson_te_market_data.rs +++ /dev/null @@ -1,839 +0,0 @@ -//! Zero-copy raw BSON decoder for MongoDB `teMarketData` documents (`M1.2ac`). -//! -//! Decodes `&bson::RawDocument` slices in a single forward pass over `iter_elements()` without -//! allocating a `bson::Document` or per-point heap memory, emitting [`FxDailyBar`] values via a -//! caller-supplied callback. -//! -//! # Empirical Field Contract & Unverified Assumptions -//! -//! - Field names are derived from the ingestion writer in -//! `apps/stock/data-ingestion/src/handlers/te/actions/market-data-fetch.action.ts` -//! (`teSymbol`, `daily: [{ t, o, h, l, c, pc, ac }]`, `monthly`), and isolated in the -//! `pub const FIELD_*` constants below. They have **not** yet been verified against a live -//! `mongodump` of `teMarketData`. -//! - **`t` epoch unit rule (unverified in repo):** TradingEconomics CDN series timestamps may be -//! stored in either Unix seconds or Unix milliseconds. This decoder converts numeric `t` via -//! [`TE_EPOCH_MILLIS_THRESHOLD`] (`100_000_000_000`): -//! - `|t| >= 100_000_000_000` → treated as Unix **milliseconds** -//! (`session_date = floor(t / 86_400_000)` UTC). -//! - `|t| < 100_000_000_000` → treated as Unix **seconds** -//! (`session_date = floor(t / 86_400)` UTC). -//! - Floor division (`div_euclid`) ensures pre-1970 negative timestamps round down to the -//! earlier UTC calendar day rather than truncating toward zero. -//! - `monthly`, `pc`, `ac`, and all unknown fields are skipped without calling `elem.value()`. -//! - `daily` is captured lazily as a raw [`RawElement`] during the top-level scan and only decoded -//! after `teSymbol` matches `target_symbol` (ASCII case-insensitive), so non-target symbols pay -//! zero array-scan cost and never emit false `daily` errors even when `daily` precedes `teSymbol` -//! in raw BSON field order. - -use std::error::Error; -use std::fmt; - -use bson::raw::{RawBsonRef, RawDocument, RawElement}; -use bson::spec::ElementType; - -use crate::bson_eod_prices::{iter_raw_bson_docs, parse_single_raw_doc, BsonEodPriceError}; -use crate::fx::FxDailyBar; - -/// MongoDB field name for the TradingEconomics symbol key (`market-data-fetch.action.ts:133`). -pub const FIELD_TE_SYMBOL: &str = "teSymbol"; -/// MongoDB field name for the daily OHLC array (`market-data-fetch.action.ts:144`). -pub const FIELD_DAILY: &str = "daily"; -/// MongoDB field name for the monthly OHLC array, explicitly ignored (`market-data-fetch.action.ts:145`). -pub const FIELD_MONTHLY: &str = "monthly"; -/// Point field name for the Unix epoch timestamp (`market-data-fetch.action.ts:15`). -pub const FIELD_POINT_T: &str = "t"; -/// Point field name for open price (`market-data-fetch.action.ts:16`). -pub const FIELD_POINT_O: &str = "o"; -/// Point field name for high price (`market-data-fetch.action.ts:17`). -pub const FIELD_POINT_H: &str = "h"; -/// Point field name for low price (`market-data-fetch.action.ts:18`). -pub const FIELD_POINT_L: &str = "l"; -/// Point field name for close price (`market-data-fetch.action.ts:19`). -pub const FIELD_POINT_C: &str = "c"; - -/// Magnitude threshold distinguishing Unix milliseconds (`|t| >= 100_000_000_000`) from Unix -/// seconds (`|t| < 100_000_000_000`). -pub const TE_EPOCH_MILLIS_THRESHOLD: i64 = 100_000_000_000; -/// Number of seconds in one UTC calendar day. -pub const SECONDS_PER_DAY: i64 = 86_400; -/// Number of milliseconds in one UTC calendar day. -pub const MILLIS_PER_DAY: i64 = 86_400_000; - -/// Converts an integer Unix epoch timestamp `t` (seconds or milliseconds per -/// [`TE_EPOCH_MILLIS_THRESHOLD`]) into UTC `session_date` (days since `1970-01-01`). -/// -/// Uses `unsigned_abs()` (avoiding `i64::MIN.abs()` overflow), `div_euclid` (flooring negative -/// pre-1970 timestamps to the earlier UTC calendar day), and checked `i32::try_from`. -#[inline] -pub fn te_epoch_i64_to_session_date(t: i64) -> Option { - let days = if t.unsigned_abs() >= TE_EPOCH_MILLIS_THRESHOLD as u64 { - t.div_euclid(MILLIS_PER_DAY) - } else { - t.div_euclid(SECONDS_PER_DAY) - }; - i32::try_from(days).ok() -} - -#[inline] -fn te_epoch_f64_to_session_date(point_index: usize, v: f64) -> Result { - if !v.is_finite() { - return Err(BsonTeMarketDataError::NonFiniteValue { - point_index, - field: FIELD_POINT_T, - value: v, - }); - } - let is_millis = v.abs() >= TE_EPOCH_MILLIS_THRESHOLD as f64; - let t_floor = v.floor(); - // Exact half-open range of `f64` values representable as `i64` (`[-2^63, 2^63)`). - if !(-9_223_372_036_854_775_808.0..9_223_372_036_854_775_808.0).contains(&t_floor) { - return Err(BsonTeMarketDataError::DateOutOfRange { point_index }); - } - let t_i64 = t_floor as i64; - let days = if is_millis { - t_i64.div_euclid(MILLIS_PER_DAY) - } else { - t_i64.div_euclid(SECONDS_PER_DAY) - }; - i32::try_from(days).map_err(|_| BsonTeMarketDataError::DateOutOfRange { point_index }) -} - -/// Typed errors returned while decoding raw `teMarketData` BSON documents or length-prefixed -/// buffers. -/// -/// Every variant's `Display` output is a single line; no input path panics. -#[derive(Debug, Clone, PartialEq)] -pub enum BsonTeMarketDataError { - /// Required top-level `teSymbol` field was absent. - MissingSymbol, - /// Top-level `teSymbol` string was empty or whitespace-only. - EmptySymbol, - /// Top-level `teSymbol` had an unexpected BSON element type. - WrongSymbolType { actual: ElementType }, - /// Required `daily` field was absent on a matched `teSymbol` document. - MissingDaily, - /// `daily` field on a matched `teSymbol` document was not a BSON array. - DailyNotArray { actual: ElementType }, - /// An element inside `daily` was not an embedded BSON document. - PointNotDocument { - point_index: usize, - actual: ElementType, - }, - /// A required field (`t`, `o`, `h`, `l`, or `c`) was absent from a `daily` point document. - MissingPointField { - point_index: usize, - field: &'static str, - }, - /// A required field in a `daily` point document had an unexpected BSON type. - WrongPointFieldType { - point_index: usize, - field: &'static str, - actual: ElementType, - }, - /// A numeric field (`t`, `o`, `h`, `l`, or `c`) in a `daily` point was `NaN` or `±inf`. - NonFiniteValue { - point_index: usize, - field: &'static str, - value: f64, - }, - /// Point timestamp `t` mapped outside the `i32` UTC epoch-day range. - DateOutOfRange { point_index: usize }, - /// Buffer ended before a complete 4-byte length prefix or declared document body. - TruncatedDocument { - offset: usize, - remaining: usize, - declared_len: Option, - }, - /// Declared 4-byte little-endian BSON document length was `< 5` (or did not match a single - /// document slice). - CorruptDocumentLength { offset: usize, declared_len: i32 }, - /// Underlying top-level BSON framing or element bytes were malformed. - CorruptBson { offset: usize, detail: String }, - /// Underlying BSON bytes inside a `daily` array or point document were malformed. - CorruptPointBson { - offset: usize, - point_index: usize, - detail: String, - }, -} - -impl fmt::Display for BsonTeMarketDataError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::MissingSymbol => { - write!(f, "teMarketData BSON missing required field '{FIELD_TE_SYMBOL}'") - } - Self::EmptySymbol => { - write!( - f, - "teMarketData BSON field '{FIELD_TE_SYMBOL}' must not be empty or blank" - ) - } - Self::WrongSymbolType { actual } => write!( - f, - "teMarketData BSON field '{FIELD_TE_SYMBOL}' has unexpected BSON type {actual:?}" - ), - Self::MissingDaily => { - write!(f, "teMarketData BSON missing required field '{FIELD_DAILY}'") - } - Self::DailyNotArray { actual } => write!( - f, - "teMarketData BSON field '{FIELD_DAILY}' has unexpected BSON type {actual:?} (expected Array)" - ), - Self::PointNotDocument { - point_index, - actual, - } => write!( - f, - "teMarketData BSON '{FIELD_DAILY}[{point_index}]' has unexpected BSON type {actual:?} (expected EmbeddedDocument)" - ), - Self::MissingPointField { point_index, field } => write!( - f, - "teMarketData BSON '{FIELD_DAILY}[{point_index}]' missing required field '{field}'" - ), - Self::WrongPointFieldType { - point_index, - field, - actual, - } => write!( - f, - "teMarketData BSON '{FIELD_DAILY}[{point_index}].{field}' has unexpected BSON type {actual:?}" - ), - Self::NonFiniteValue { - point_index, - field, - value, - } => write!( - f, - "teMarketData BSON '{FIELD_DAILY}[{point_index}].{field}' has non-finite value {value}" - ), - Self::DateOutOfRange { point_index } => write!( - f, - "teMarketData BSON '{FIELD_DAILY}[{point_index}].{FIELD_POINT_T}' overflows i32 UTC session_date" - ), - Self::TruncatedDocument { - offset, - remaining, - declared_len, - } => match declared_len { - Some(len) => write!( - f, - "truncated BSON document at byte offset {offset}: declared length {len} exceeds remaining {remaining} bytes" - ), - None => write!( - f, - "truncated BSON document header at byte offset {offset}: only {remaining} bytes remaining" - ), - }, - Self::CorruptDocumentLength { - offset, - declared_len, - } => write!( - f, - "corrupt BSON document length {declared_len} at byte offset {offset}" - ), - Self::CorruptBson { offset, detail } => { - write!(f, "corrupt BSON bytes at byte offset {offset}: {detail}") - } - Self::CorruptPointBson { - offset, - point_index, - detail, - } => write!( - f, - "corrupt BSON bytes in '{FIELD_DAILY}[{point_index}]' at byte offset {offset}: {detail}" - ), - } - } -} - -impl Error for BsonTeMarketDataError {} - -#[inline] -fn map_framing_error(err: BsonEodPriceError) -> BsonTeMarketDataError { - match err { - BsonEodPriceError::TruncatedDocument { - offset, - remaining, - declared_len, - } => BsonTeMarketDataError::TruncatedDocument { - offset, - remaining, - declared_len, - }, - BsonEodPriceError::CorruptDocumentLength { - offset, - declared_len, - } => BsonTeMarketDataError::CorruptDocumentLength { - offset, - declared_len, - }, - BsonEodPriceError::CorruptBson { offset, detail } => { - BsonTeMarketDataError::CorruptBson { offset, detail } - } - other => BsonTeMarketDataError::CorruptBson { - offset: 0, - detail: other.to_string(), - }, - } -} - -/// Per-batch document and point decode accounting for `teMarketData`. -/// -/// Conservation invariants: -/// - `docs_in == docs_matched + docs_other_symbol + docs_rejected_total()` -/// - `points_in == points_decoded + rejected_total()` -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct BsonTeMarketDataDecodeStats { - pub docs_in: usize, - pub docs_matched: usize, - pub docs_other_symbol: usize, - pub rejected_missing_symbol: usize, - pub rejected_empty_symbol: usize, - pub rejected_wrong_symbol_type: usize, - pub rejected_daily_missing: usize, - pub rejected_daily_not_array: usize, - pub rejected_corrupt_document: usize, - pub points_in: usize, - pub points_decoded: usize, - pub rejected_point_not_document: usize, - pub rejected_missing_field: usize, - pub rejected_wrong_type: usize, - pub rejected_non_finite: usize, - pub rejected_date_out_of_range: usize, - pub rejected_corrupt_point: usize, -} - -impl BsonTeMarketDataDecodeStats { - /// Total number of document-level rejects across all document error categories. - #[inline] - pub fn docs_rejected_total(&self) -> usize { - self.rejected_missing_symbol - + self.rejected_empty_symbol - + self.rejected_wrong_symbol_type - + self.rejected_daily_missing - + self.rejected_daily_not_array - + self.rejected_corrupt_document - } - - /// Total number of point-level rejects across all point error categories. - #[inline] - pub fn rejected_total(&self) -> usize { - self.rejected_point_not_document - + self.rejected_missing_field - + self.rejected_wrong_type - + self.rejected_non_finite - + self.rejected_date_out_of_range - + self.rejected_corrupt_point - } - - /// Increments the point-level rejection counter corresponding to `err`. - #[inline] - fn record_point_error(&mut self, err: &BsonTeMarketDataError) { - match err { - BsonTeMarketDataError::PointNotDocument { .. } => { - self.rejected_point_not_document += 1; - } - BsonTeMarketDataError::MissingPointField { .. } => { - self.rejected_missing_field += 1; - } - BsonTeMarketDataError::WrongPointFieldType { .. } => { - self.rejected_wrong_type += 1; - } - BsonTeMarketDataError::NonFiniteValue { .. } => { - self.rejected_non_finite += 1; - } - BsonTeMarketDataError::DateOutOfRange { .. } => { - self.rejected_date_out_of_range += 1; - } - BsonTeMarketDataError::CorruptPointBson { .. } => { - self.rejected_corrupt_point += 1; - } - _ => { - self.rejected_corrupt_point += 1; - } - } - } - - /// Accumulates counters from another batch into `self`. - #[inline] - pub fn merge(&mut self, other: &Self) { - self.docs_in += other.docs_in; - self.docs_matched += other.docs_matched; - self.docs_other_symbol += other.docs_other_symbol; - self.rejected_missing_symbol += other.rejected_missing_symbol; - self.rejected_empty_symbol += other.rejected_empty_symbol; - self.rejected_wrong_symbol_type += other.rejected_wrong_symbol_type; - self.rejected_daily_missing += other.rejected_daily_missing; - self.rejected_daily_not_array += other.rejected_daily_not_array; - self.rejected_corrupt_document += other.rejected_corrupt_document; - self.points_in += other.points_in; - self.points_decoded += other.points_decoded; - self.rejected_point_not_document += other.rejected_point_not_document; - self.rejected_missing_field += other.rejected_missing_field; - self.rejected_wrong_type += other.rejected_wrong_type; - self.rejected_non_finite += other.rejected_non_finite; - self.rejected_date_out_of_range += other.rejected_date_out_of_range; - self.rejected_corrupt_point += other.rejected_corrupt_point; - } -} - -impl std::ops::AddAssign for BsonTeMarketDataDecodeStats { - #[inline] - fn add_assign(&mut self, rhs: Self) { - self.merge(&rhs); - } -} - -#[inline] -fn decode_point_t( - point_index: usize, - val: RawBsonRef<'_>, -) -> Result { - match val { - RawBsonRef::Int32(v) => te_epoch_i64_to_session_date(i64::from(v)) - .ok_or(BsonTeMarketDataError::DateOutOfRange { point_index }), - RawBsonRef::Int64(v) => te_epoch_i64_to_session_date(v) - .ok_or(BsonTeMarketDataError::DateOutOfRange { point_index }), - RawBsonRef::Double(v) => te_epoch_f64_to_session_date(point_index, v), - other => Err(BsonTeMarketDataError::WrongPointFieldType { - point_index, - field: FIELD_POINT_T, - actual: other.element_type(), - }), - } -} - -#[inline] -fn decode_point_price( - point_index: usize, - field: &'static str, - val: RawBsonRef<'_>, -) -> Result { - match val { - RawBsonRef::Double(v) => { - if !v.is_finite() { - return Err(BsonTeMarketDataError::NonFiniteValue { - point_index, - field, - value: v, - }); - } - Ok(v) - } - RawBsonRef::Int32(v) => Ok(f64::from(v)), - RawBsonRef::Int64(v) => Ok(v as f64), - other => Err(BsonTeMarketDataError::WrongPointFieldType { - point_index, - field, - actual: other.element_type(), - }), - } -} - -fn decode_point_doc( - point_doc: &RawDocument, - doc_offset: usize, - point_index: usize, -) -> Result { - let mut session_date: Option = None; - let mut open: Option = None; - let mut high: Option = None; - let mut low: Option = None; - let mut close: Option = None; - let mut first_semantic_err: Option = None; - - for elem_res in point_doc.iter_elements() { - let elem = elem_res.map_err(|err| BsonTeMarketDataError::CorruptPointBson { - offset: doc_offset, - point_index, - detail: err.to_string(), - })?; - let key = elem.key().as_str(); - - if key == FIELD_POINT_T { - let val = elem - .value() - .map_err(|err| BsonTeMarketDataError::CorruptPointBson { - offset: doc_offset, - point_index, - detail: format!("field '{FIELD_POINT_T}': {err}"), - })?; - match decode_point_t(point_index, val) { - Ok(v) => session_date = Some(v), - Err(err) => { - if first_semantic_err.is_none() { - first_semantic_err = Some(err); - } - } - } - } else if key == FIELD_POINT_O { - let val = elem - .value() - .map_err(|err| BsonTeMarketDataError::CorruptPointBson { - offset: doc_offset, - point_index, - detail: format!("field '{FIELD_POINT_O}': {err}"), - })?; - match decode_point_price(point_index, FIELD_POINT_O, val) { - Ok(v) => open = Some(v), - Err(err) => { - if first_semantic_err.is_none() { - first_semantic_err = Some(err); - } - } - } - } else if key == FIELD_POINT_H { - let val = elem - .value() - .map_err(|err| BsonTeMarketDataError::CorruptPointBson { - offset: doc_offset, - point_index, - detail: format!("field '{FIELD_POINT_H}': {err}"), - })?; - match decode_point_price(point_index, FIELD_POINT_H, val) { - Ok(v) => high = Some(v), - Err(err) => { - if first_semantic_err.is_none() { - first_semantic_err = Some(err); - } - } - } - } else if key == FIELD_POINT_L { - let val = elem - .value() - .map_err(|err| BsonTeMarketDataError::CorruptPointBson { - offset: doc_offset, - point_index, - detail: format!("field '{FIELD_POINT_L}': {err}"), - })?; - match decode_point_price(point_index, FIELD_POINT_L, val) { - Ok(v) => low = Some(v), - Err(err) => { - if first_semantic_err.is_none() { - first_semantic_err = Some(err); - } - } - } - } else if key == FIELD_POINT_C { - let val = elem - .value() - .map_err(|err| BsonTeMarketDataError::CorruptPointBson { - offset: doc_offset, - point_index, - detail: format!("field '{FIELD_POINT_C}': {err}"), - })?; - match decode_point_price(point_index, FIELD_POINT_C, val) { - Ok(v) => close = Some(v), - Err(err) => { - if first_semantic_err.is_none() { - first_semantic_err = Some(err); - } - } - } - } - // `pc`, `ac`, and all unknown fields are skipped without calling `elem.value()`. - } - - if let Some(err) = first_semantic_err { - return Err(err); - } - - let Some(session_date) = session_date else { - return Err(BsonTeMarketDataError::MissingPointField { - point_index, - field: FIELD_POINT_T, - }); - }; - let Some(open) = open else { - return Err(BsonTeMarketDataError::MissingPointField { - point_index, - field: FIELD_POINT_O, - }); - }; - let Some(high) = high else { - return Err(BsonTeMarketDataError::MissingPointField { - point_index, - field: FIELD_POINT_H, - }); - }; - let Some(low) = low else { - return Err(BsonTeMarketDataError::MissingPointField { - point_index, - field: FIELD_POINT_L, - }); - }; - let Some(close) = close else { - return Err(BsonTeMarketDataError::MissingPointField { - point_index, - field: FIELD_POINT_C, - }); - }; - - Ok(FxDailyBar { - session_date, - open, - high, - low, - close, - }) -} - -fn decode_te_market_data_doc_at( - doc: &RawDocument, - doc_offset: usize, - target_symbol: &str, - mut on_bar: F, - mut on_error: E, -) -> BsonTeMarketDataDecodeStats -where - F: FnMut(FxDailyBar), - E: FnMut(BsonTeMarketDataError), -{ - let mut stats = BsonTeMarketDataDecodeStats { - docs_in: 1, - ..BsonTeMarketDataDecodeStats::default() - }; - - let mut te_symbol: Option<&str> = None; - let mut symbol_err: Option = None; - let mut daily_elem: Option> = None; - - for elem_res in doc.iter_elements() { - let elem = match elem_res { - Ok(elem) => elem, - Err(err) => { - stats.rejected_corrupt_document += 1; - on_error(BsonTeMarketDataError::CorruptBson { - offset: doc_offset, - detail: err.to_string(), - }); - return stats; - } - }; - let key = elem.key().as_str(); - if key == FIELD_TE_SYMBOL { - let val = match elem.value() { - Ok(val) => val, - Err(err) => { - stats.rejected_corrupt_document += 1; - on_error(BsonTeMarketDataError::CorruptBson { - offset: doc_offset, - detail: format!("field '{FIELD_TE_SYMBOL}': {err}"), - }); - return stats; - } - }; - match val { - RawBsonRef::String(s) => { - if s.trim().is_empty() { - if symbol_err.is_none() { - symbol_err = Some(BsonTeMarketDataError::EmptySymbol); - } - } else { - te_symbol = Some(s); - } - } - other => { - if symbol_err.is_none() { - symbol_err = Some(BsonTeMarketDataError::WrongSymbolType { - actual: other.element_type(), - }); - } - } - } - } else if key == FIELD_DAILY { - daily_elem = Some(elem); - } - // `FIELD_MONTHLY` and all other top-level fields are skipped without calling `elem.value()`. - } - - if let Some(err) = symbol_err { - match &err { - BsonTeMarketDataError::EmptySymbol => stats.rejected_empty_symbol += 1, - BsonTeMarketDataError::WrongSymbolType { .. } => stats.rejected_wrong_symbol_type += 1, - _ => stats.rejected_corrupt_document += 1, - } - on_error(err); - return stats; - } - - let Some(symbol) = te_symbol else { - stats.rejected_missing_symbol += 1; - on_error(BsonTeMarketDataError::MissingSymbol); - return stats; - }; - - if !symbol.eq_ignore_ascii_case(target_symbol) { - stats.docs_other_symbol += 1; - return stats; - } - - let Some(daily_elem) = daily_elem else { - stats.rejected_daily_missing += 1; - on_error(BsonTeMarketDataError::MissingDaily); - return stats; - }; - - let daily_val = match daily_elem.value() { - Ok(val) => val, - Err(err) => { - stats.rejected_corrupt_document += 1; - on_error(BsonTeMarketDataError::CorruptBson { - offset: doc_offset, - detail: format!("field '{FIELD_DAILY}': {err}"), - }); - return stats; - } - }; - - let daily_arr = match daily_val { - RawBsonRef::Array(arr) => arr, - other => { - stats.rejected_daily_not_array += 1; - on_error(BsonTeMarketDataError::DailyNotArray { - actual: other.element_type(), - }); - return stats; - } - }; - - stats.docs_matched += 1; - - for (point_index, item_res) in daily_arr.into_iter().enumerate() { - stats.points_in += 1; - let item = match item_res { - Ok(item) => item, - Err(err) => { - let err = BsonTeMarketDataError::CorruptPointBson { - offset: doc_offset, - point_index, - detail: err.to_string(), - }; - stats.record_point_error(&err); - on_error(err); - break; - } - }; - - let point_doc = match item { - RawBsonRef::Document(point_doc) => point_doc, - other => { - let err = BsonTeMarketDataError::PointNotDocument { - point_index, - actual: other.element_type(), - }; - stats.record_point_error(&err); - on_error(err); - continue; - } - }; - - match decode_point_doc(point_doc, doc_offset, point_index) { - Ok(bar) => { - stats.points_decoded += 1; - on_bar(bar); - } - Err(err) => { - stats.record_point_error(&err); - on_error(err); - } - } - } - - stats -} - -/// Decodes a single `&RawDocument` representing a `teMarketData` MongoDB document in one forward -/// pass without allocating a `bson::Document` or per-point heap memory. -/// -/// Matches `teSymbol` against `target_symbol` using ASCII case-insensitive comparison. For matched -/// documents, emits each valid `daily` point as an [`FxDailyBar`] via `on_bar` and reports -/// document- or point-level errors to `on_error` without panicking. -#[inline] -pub fn decode_te_market_data_doc( - doc: &RawDocument, - target_symbol: &str, - on_bar: F, - on_error: E, -) -> BsonTeMarketDataDecodeStats -where - F: FnMut(FxDailyBar), - E: FnMut(BsonTeMarketDataError), -{ - decode_te_market_data_doc_at(doc, 0, target_symbol, on_bar, on_error) -} - -/// Decodes a single length-prefixed raw BSON document byte slice representing a `teMarketData` -/// document. -pub fn decode_te_market_data_bytes( - bytes: &[u8], - target_symbol: &str, - on_bar: F, - mut on_error: E, -) -> BsonTeMarketDataDecodeStats -where - F: FnMut(FxDailyBar), - E: FnMut(BsonTeMarketDataError), -{ - match parse_single_raw_doc(bytes) { - Ok(doc) => decode_te_market_data_doc_at(doc, 0, target_symbol, on_bar, on_error), - Err(err) => { - let mut stats = BsonTeMarketDataDecodeStats { - docs_in: 1, - ..BsonTeMarketDataDecodeStats::default() - }; - stats.rejected_corrupt_document += 1; - on_error(map_framing_error(err)); - stats - } - } -} - -/// Streams a concatenated length-prefixed BSON buffer through [`decode_te_market_data_doc`], -/// emitting every valid [`FxDailyBar`] for `target_symbol` (ASCII case-insensitive) to `on_bar` -/// and reporting document- or point-level errors to `on_error(byte_offset, err)` without aborting. -/// -/// Always maintains: -/// - `stats.docs_in == stats.docs_matched + stats.docs_other_symbol + stats.docs_rejected_total()` -/// - `stats.points_in == stats.points_decoded + stats.rejected_total()` -pub fn decode_te_market_data_buffer( - buf: &[u8], - target_symbol: &str, - mut on_bar: F, - mut on_error: E, -) -> BsonTeMarketDataDecodeStats -where - F: FnMut(FxDailyBar), - E: FnMut(usize, BsonTeMarketDataError), -{ - let mut stats = BsonTeMarketDataDecodeStats::default(); - let mut iter = iter_raw_bson_docs(buf); - - while let Some(item) = iter.next_with_offset() { - match item { - Ok((doc_offset, doc)) => { - let doc_stats = decode_te_market_data_doc_at( - doc, - doc_offset, - target_symbol, - &mut on_bar, - |err| on_error(doc_offset, err), - ); - stats += doc_stats; - } - Err((doc_offset, err)) => { - stats.docs_in += 1; - stats.rejected_corrupt_document += 1; - on_error(doc_offset, map_framing_error(err)); - } - } - } - - stats -} - -#[cfg(test)] -#[path = "bson_te_market_data_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/bson_te_market_data_tests.rs b/tools/curate-etl/src/bson_te_market_data_tests.rs deleted file mode 100644 index 69bb354c..00000000 --- a/tools/curate-etl/src/bson_te_market_data_tests.rs +++ /dev/null @@ -1,522 +0,0 @@ -use bson::raw::{cstr, RawArrayBuf, RawDocumentBuf}; -use bson::spec::ElementType; - -use super::*; -use crate::bson_stream::{decode_te_market_data_stream, BsonStreamOptions}; -use crate::split::ymd_to_epoch_days; - -fn day(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).expect("valid date") -} - -fn assert_stats_conserved(stats: &BsonTeMarketDataDecodeStats) { - assert_eq!( - stats.docs_in, - stats.docs_matched + stats.docs_other_symbol + stats.docs_rejected_total(), - "doc conservation failed: {stats:?}" - ); - assert_eq!( - stats.points_in, - stats.points_decoded + stats.rejected_total(), - "point conservation failed: {stats:?}" - ); -} - -fn make_te_doc(symbol: &str, daily: RawArrayBuf) -> RawDocumentBuf { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("teSymbol"), symbol); - doc.append(cstr!("daily"), daily); - doc -} - -#[test] -fn decodes_int32_int64_double_and_seconds_vs_millis_to_same_session_date() { - let d_2025 = day(2025, 1, 2); - let secs_2025 = i64::from(d_2025) * SECONDS_PER_DAY; - let ms_2025 = i64::from(d_2025) * MILLIS_PER_DAY; - - let mut daily = RawArrayBuf::new(); - - // Point 0: Int32 seconds + Int32 OHLC - let mut p0 = RawDocumentBuf::new(); - p0.append(cstr!("t"), i32::try_from(secs_2025 + 43_200).unwrap()); - p0.append(cstr!("o"), 1_i32); - p0.append(cstr!("h"), 2_i32); - p0.append(cstr!("l"), 1_i32); - p0.append(cstr!("c"), 2_i32); - p0.append(cstr!("pc"), 0.5_f64); - p0.append(cstr!("ac"), 0.01_f64); - daily.push(p0); - - // Point 1: Int64 milliseconds + Int64 OHLC - let mut p1 = RawDocumentBuf::new(); - p1.append(cstr!("t"), ms_2025 + 86_399_999); - p1.append(cstr!("o"), 1_i64); - p1.append(cstr!("h"), 3_i64); - p1.append(cstr!("l"), 1_i64); - p1.append(cstr!("c"), 2_i64); - daily.push(p1); - - // Point 2: Double seconds + Double OHLC - let mut p2 = RawDocumentBuf::new(); - p2.append(cstr!("t"), (secs_2025 as f64) + 123.75); - p2.append(cstr!("o"), 1.430_f64); - p2.append(cstr!("h"), 1.445_f64); - p2.append(cstr!("l"), 1.425_f64); - p2.append(cstr!("c"), 1.438_f64); - daily.push(p2); - - // Point 3: Double milliseconds + Double OHLC - let mut p3 = RawDocumentBuf::new(); - p3.append(cstr!("t"), (ms_2025 as f64) + 500.5); - p3.append(cstr!("o"), 1.431_f64); - p3.append(cstr!("h"), 1.446_f64); - p3.append(cstr!("l"), 1.426_f64); - p3.append(cstr!("c"), 1.439_f64); - daily.push(p3); - - let doc = make_te_doc("USDCAD", daily); - let mut bars = Vec::new(); - let mut errors = Vec::new(); - let stats = decode_te_market_data_doc(&doc, "USDCAD", |b| bars.push(b), |e| errors.push(e)); - - assert_stats_conserved(&stats); - assert!(errors.is_empty(), "unexpected errors: {errors:?}"); - assert_eq!(stats.docs_in, 1); - assert_eq!(stats.docs_matched, 1); - assert_eq!(stats.points_in, 4); - assert_eq!(stats.points_decoded, 4); - assert_eq!(bars.len(), 4); - for bar in &bars { - assert_eq!(bar.session_date, d_2025); - } - assert_eq!(bars[0].open, 1.0); - assert_eq!(bars[0].high, 2.0); - assert_eq!(bars[1].high, 3.0); - assert_eq!(bars[2].close.to_bits(), 1.438_f64.to_bits()); - assert_eq!(bars[3].close.to_bits(), 1.439_f64.to_bits()); -} - -#[test] -fn epoch_threshold_boundaries_and_negative_pre_1970_floor_correctly() { - // Exact threshold boundaries - assert_eq!( - te_epoch_i64_to_session_date(TE_EPOCH_MILLIS_THRESHOLD - 1), - Some((TE_EPOCH_MILLIS_THRESHOLD - 1).div_euclid(SECONDS_PER_DAY) as i32) - ); - assert_eq!( - te_epoch_i64_to_session_date(TE_EPOCH_MILLIS_THRESHOLD), - Some(TE_EPOCH_MILLIS_THRESHOLD.div_euclid(MILLIS_PER_DAY) as i32) - ); - assert_eq!( - te_epoch_i64_to_session_date(-(TE_EPOCH_MILLIS_THRESHOLD - 1)), - Some((-(TE_EPOCH_MILLIS_THRESHOLD - 1)).div_euclid(SECONDS_PER_DAY) as i32) - ); - assert_eq!( - te_epoch_i64_to_session_date(-TE_EPOCH_MILLIS_THRESHOLD), - Some((-TE_EPOCH_MILLIS_THRESHOLD).div_euclid(MILLIS_PER_DAY) as i32) - ); - - // Pre-1970 negative timestamps floor to earlier UTC day - assert_eq!(te_epoch_i64_to_session_date(0), Some(0)); // 1970-01-01 - assert_eq!(te_epoch_i64_to_session_date(-1), Some(-1)); // 1969-12-31 23:59:59 UTC - assert_eq!(te_epoch_i64_to_session_date(-SECONDS_PER_DAY), Some(-1)); // 1969-12-31 00:00:00 UTC - assert_eq!(te_epoch_i64_to_session_date(-SECONDS_PER_DAY - 1), Some(-2)); // 1969-12-30 - - // Pre-1970 negative milliseconds (1966-10-31 is past -100_000_000_000 ms) - let neg_ms = -100_000_000_001_i64; - assert_eq!( - te_epoch_i64_to_session_date(neg_ms), - Some(neg_ms.div_euclid(MILLIS_PER_DAY) as i32) - ); - - // Overflow boundaries: i64::MIN and i64::MAX must never panic, return None - assert_eq!(te_epoch_i64_to_session_date(i64::MIN), None); - assert_eq!(te_epoch_i64_to_session_date(i64::MAX), None); - - // Fractional negative Double values in BSON - let mut daily = RawArrayBuf::new(); - for t_val in [-1.5_f64, -86_400.5_f64, -100_000_000_000.5_f64] { - let mut pt = RawDocumentBuf::new(); - pt.append(cstr!("t"), t_val); - pt.append(cstr!("o"), 1.05_f64); - pt.append(cstr!("h"), 1.06_f64); - pt.append(cstr!("l"), 1.04_f64); - pt.append(cstr!("c"), 1.05_f64); - daily.push(pt); - } - let doc = make_te_doc("USDCAD", daily); - let mut bars = Vec::new(); - let mut errors = Vec::new(); - let stats = decode_te_market_data_doc(&doc, "USDCAD", |b| bars.push(b), |e| errors.push(e)); - assert_stats_conserved(&stats); - assert!(errors.is_empty(), "{errors:?}"); - assert_eq!(bars[0].session_date, -1); // -1.5 -> floor -2s -> day -1 - assert_eq!(bars[1].session_date, -2); // -86400.5 -> floor -86401s -> day -2 - assert_eq!( - bars[2].session_date, - (-100_000_000_001_i64).div_euclid(MILLIS_PER_DAY) as i32 - ); -} - -#[test] -fn daily_before_symbol_case_insensitive_match_and_monthly_ignored() { - let d1 = day(2025, 3, 10); - - // 1. Matched doc (lowercase "usdcad") with `daily` BEFORE `teSymbol` and broken `monthly` - let mut daily = RawArrayBuf::new(); - let mut pt = RawDocumentBuf::new(); - pt.append(cstr!("t"), i64::from(d1) * SECONDS_PER_DAY); - pt.append(cstr!("o"), 1.44_f64); - pt.append(cstr!("h"), 1.45_f64); - pt.append(cstr!("l"), 1.43_f64); - pt.append(cstr!("c"), 1.445_f64); - pt.append(cstr!("pc"), bson::raw::RawBson::Null); - pt.append(cstr!("ac"), bson::raw::RawBson::Null); - pt.append(cstr!("extra"), "ignored"); - daily.push(pt); - - let mut bad_monthly = RawArrayBuf::new(); - bad_monthly.push("not-a-doc"); - bad_monthly.push(f64::NAN); - - let mut doc1 = RawDocumentBuf::new(); - doc1.append(cstr!("monthly"), bad_monthly); - doc1.append(cstr!("daily"), daily); - doc1.append(cstr!("teSymbol"), "usdcad"); - - // 2. Non-target symbol with invalid `daily` (not an array) placed BEFORE `teSymbol`: - // must be counted as `docs_other_symbol` with zero errors! - let mut doc2 = RawDocumentBuf::new(); - doc2.append(cstr!("daily"), "not-an-array"); - doc2.append(cstr!("teSymbol"), "EURUSD"); - - let mut buf = Vec::new(); - buf.extend_from_slice(doc1.as_bytes()); - buf.extend_from_slice(doc2.as_bytes()); - - let mut bars = Vec::new(); - let mut errors = Vec::new(); - let stats = decode_te_market_data_buffer( - &buf, - "USDCAD", - |b| bars.push(b), - |off, e| errors.push((off, e)), - ); - - assert_stats_conserved(&stats); - assert!(errors.is_empty(), "unexpected errors: {errors:?}"); - assert_eq!(stats.docs_in, 2); - assert_eq!(stats.docs_matched, 1); - assert_eq!(stats.docs_other_symbol, 1); - assert_eq!(stats.points_in, 1); - assert_eq!(stats.points_decoded, 1); - assert_eq!(bars.len(), 1); - assert_eq!(bars[0].session_date, d1); -} - -#[test] -fn counts_every_doc_and_point_reject_reason_without_panicking() { - let mut buf = Vec::new(); - - // Doc 0: MissingSymbol - let mut d_missing_sym = RawDocumentBuf::new(); - d_missing_sym.append(cstr!("daily"), RawArrayBuf::new()); - buf.extend_from_slice(d_missing_sym.as_bytes()); - - // Doc 1: EmptySymbol - let mut d_empty_sym = RawDocumentBuf::new(); - d_empty_sym.append(cstr!("teSymbol"), " "); - d_empty_sym.append(cstr!("daily"), RawArrayBuf::new()); - buf.extend_from_slice(d_empty_sym.as_bytes()); - - // Doc 2: WrongSymbolType - let mut d_wrong_sym = RawDocumentBuf::new(); - d_wrong_sym.append(cstr!("teSymbol"), 42_i32); - buf.extend_from_slice(d_wrong_sym.as_bytes()); - - // Doc 3: MissingDaily - let mut d_missing_daily = RawDocumentBuf::new(); - d_missing_daily.append(cstr!("teSymbol"), "USDCAD"); - buf.extend_from_slice(d_missing_daily.as_bytes()); - - // Doc 4: DailyNotArray - let mut d_not_array = RawDocumentBuf::new(); - d_not_array.append(cstr!("teSymbol"), "USDCAD"); - d_not_array.append(cstr!("daily"), 123_i32); - buf.extend_from_slice(d_not_array.as_bytes()); - - // Doc 5: Matched doc containing every point-level reject + 1 valid point - let mut daily = RawArrayBuf::new(); - // [0] PointNotDocument - daily.push("not-a-doc"); - // [1] MissingPointField (`t`) - let mut p_no_t = RawDocumentBuf::new(); - p_no_t.append(cstr!("o"), 1.3_f64); - p_no_t.append(cstr!("h"), 1.4_f64); - p_no_t.append(cstr!("l"), 1.2_f64); - p_no_t.append(cstr!("c"), 1.35_f64); - daily.push(p_no_t); - // [2] MissingPointField (`o`) - let mut p_no_o = RawDocumentBuf::new(); - p_no_o.append(cstr!("t"), 0_i32); - p_no_o.append(cstr!("h"), 1.4_f64); - p_no_o.append(cstr!("l"), 1.2_f64); - p_no_o.append(cstr!("c"), 1.35_f64); - daily.push(p_no_o); - // [3] WrongPointFieldType (`t` as String) - let mut p_bad_t = RawDocumentBuf::new(); - p_bad_t.append(cstr!("t"), "2025-01-01"); - p_bad_t.append(cstr!("o"), 1.3_f64); - p_bad_t.append(cstr!("h"), 1.4_f64); - p_bad_t.append(cstr!("l"), 1.2_f64); - p_bad_t.append(cstr!("c"), 1.35_f64); - daily.push(p_bad_t); - // [4] WrongPointFieldType (`c` as Bool) - let mut p_bad_c = RawDocumentBuf::new(); - p_bad_c.append(cstr!("t"), 0_i32); - p_bad_c.append(cstr!("o"), 1.3_f64); - p_bad_c.append(cstr!("h"), 1.4_f64); - p_bad_c.append(cstr!("l"), 1.2_f64); - p_bad_c.append(cstr!("c"), true); - daily.push(p_bad_c); - // [5] NonFiniteValue (`t` = NaN) - let mut p_nan_t = RawDocumentBuf::new(); - p_nan_t.append(cstr!("t"), f64::NAN); - p_nan_t.append(cstr!("o"), 1.3_f64); - p_nan_t.append(cstr!("h"), 1.4_f64); - p_nan_t.append(cstr!("l"), 1.2_f64); - p_nan_t.append(cstr!("c"), 1.35_f64); - daily.push(p_nan_t); - // [6] NonFiniteValue (`h` = +Inf) - let mut p_inf_h = RawDocumentBuf::new(); - p_inf_h.append(cstr!("t"), 0_i32); - p_inf_h.append(cstr!("o"), 1.3_f64); - p_inf_h.append(cstr!("h"), f64::INFINITY); - p_inf_h.append(cstr!("l"), 1.2_f64); - p_inf_h.append(cstr!("c"), 1.35_f64); - daily.push(p_inf_h); - // [7] NonFiniteValue (`l` = -Inf) - let mut p_ninf_l = RawDocumentBuf::new(); - p_ninf_l.append(cstr!("t"), 0_i32); - p_ninf_l.append(cstr!("o"), 1.3_f64); - p_ninf_l.append(cstr!("h"), 1.4_f64); - p_ninf_l.append(cstr!("l"), f64::NEG_INFINITY); - p_ninf_l.append(cstr!("c"), 1.35_f64); - daily.push(p_ninf_l); - // [8] DateOutOfRange (`i64::MIN`) - let mut p_oor_min = RawDocumentBuf::new(); - p_oor_min.append(cstr!("t"), i64::MIN); - p_oor_min.append(cstr!("o"), 1.3_f64); - p_oor_min.append(cstr!("h"), 1.4_f64); - p_oor_min.append(cstr!("l"), 1.2_f64); - p_oor_min.append(cstr!("c"), 1.35_f64); - daily.push(p_oor_min); - // [9] DateOutOfRange (`i64::MAX`) - let mut p_oor_max = RawDocumentBuf::new(); - p_oor_max.append(cstr!("t"), i64::MAX); - p_oor_max.append(cstr!("o"), 1.3_f64); - p_oor_max.append(cstr!("h"), 1.4_f64); - p_oor_max.append(cstr!("l"), 1.2_f64); - p_oor_max.append(cstr!("c"), 1.35_f64); - daily.push(p_oor_max); - // [10] DateOutOfRange (Double 1e20) - let mut p_oor_f64 = RawDocumentBuf::new(); - p_oor_f64.append(cstr!("t"), 1e20_f64); - p_oor_f64.append(cstr!("o"), 1.3_f64); - p_oor_f64.append(cstr!("h"), 1.4_f64); - p_oor_f64.append(cstr!("l"), 1.2_f64); - p_oor_f64.append(cstr!("c"), 1.35_f64); - daily.push(p_oor_f64); - // [11] Valid point - let d_ok = day(2026, 2, 14); - let mut p_ok = RawDocumentBuf::new(); - p_ok.append(cstr!("t"), i64::from(d_ok) * MILLIS_PER_DAY); - p_ok.append(cstr!("o"), 1.38_f64); - p_ok.append(cstr!("h"), 1.39_f64); - p_ok.append(cstr!("l"), 1.37_f64); - p_ok.append(cstr!("c"), 1.385_f64); - daily.push(p_ok); - - let doc5 = make_te_doc("UsdCad", daily); - buf.extend_from_slice(doc5.as_bytes()); - - let mut bars = Vec::new(); - let mut errors = Vec::new(); - let stats = decode_te_market_data_buffer( - &buf, - "USDCAD", - |b| bars.push(b), - |off, e| errors.push((off, e)), - ); - - assert_stats_conserved(&stats); - assert_eq!(stats.docs_in, 6); - assert_eq!(stats.docs_matched, 1); - assert_eq!(stats.docs_other_symbol, 0); - assert_eq!(stats.rejected_missing_symbol, 1); - assert_eq!(stats.rejected_empty_symbol, 1); - assert_eq!(stats.rejected_wrong_symbol_type, 1); - assert_eq!(stats.rejected_daily_missing, 1); - assert_eq!(stats.rejected_daily_not_array, 1); - assert_eq!(stats.rejected_corrupt_document, 0); - - assert_eq!(stats.points_in, 12); - assert_eq!(stats.points_decoded, 1); - assert_eq!(stats.rejected_point_not_document, 1); - assert_eq!(stats.rejected_missing_field, 2); - assert_eq!(stats.rejected_wrong_type, 2); - assert_eq!(stats.rejected_non_finite, 3); - assert_eq!(stats.rejected_date_out_of_range, 3); - assert_eq!(stats.rejected_corrupt_point, 0); - assert_eq!(bars.len(), 1); - assert_eq!(bars[0].session_date, d_ok); - - assert!(errors.iter().any(|(_, e)| matches!(e, BsonTeMarketDataError::MissingSymbol))); - assert!(errors.iter().any(|(_, e)| matches!(e, BsonTeMarketDataError::EmptySymbol))); - assert!(errors.iter().any(|(_, e)| matches!( - e, - BsonTeMarketDataError::WrongSymbolType { - actual: ElementType::Int32 - } - ))); - assert!(errors.iter().any(|(_, e)| matches!(e, BsonTeMarketDataError::MissingDaily))); - assert!(errors.iter().any(|(_, e)| matches!( - e, - BsonTeMarketDataError::DailyNotArray { - actual: ElementType::Int32 - } - ))); - assert!(errors.iter().any(|(_, e)| matches!( - e, - BsonTeMarketDataError::PointNotDocument { - point_index: 0, - actual: ElementType::String - } - ))); - // Every error Display is single-line - for (_, err) in &errors { - let msg = err.to_string(); - assert!(!msg.contains('\n'), "multiline error display: {msg}"); - } -} - -#[test] -fn corrupt_bson_bytes_and_streaming_rebase_offsets() { - // 1. decode_te_market_data_bytes on truncated input - let mut errs = Vec::new(); - let stats = decode_te_market_data_bytes(&[10, 0, 0, 0, 1], "USDCAD", |_| {}, |e| errs.push(e)); - assert_stats_conserved(&stats); - assert_eq!(stats.docs_in, 1); - assert_eq!(stats.rejected_corrupt_document, 1); - assert!(matches!( - errs.as_slice(), - [BsonTeMarketDataError::TruncatedDocument { .. }] - )); - - // 2. Streaming across tiny chunks rebases corrupt inner BSON offset accurately - let mut good_daily = RawArrayBuf::new(); - let mut pt = RawDocumentBuf::new(); - pt.append(cstr!("t"), 0_i32); - pt.append(cstr!("o"), 1.3_f64); - pt.append(cstr!("h"), 1.4_f64); - pt.append(cstr!("l"), 1.2_f64); - pt.append(cstr!("c"), 1.35_f64); - good_daily.push(pt); - let doc1 = make_te_doc("USDCAD", good_daily); - let doc1_len = doc1.as_bytes().len() as u64; - - // Second doc: valid 4-byte length prefix (12 bytes) but invalid element type byte 0xFF - let bad_doc: [u8; 12] = [12, 0, 0, 0, 0xFF, b'a', 0, 0, 0, 0, 0, 0]; - - let mut stream_bytes = Vec::new(); - stream_bytes.extend_from_slice(doc1.as_bytes()); - stream_bytes.extend_from_slice(&bad_doc); - - let opts = BsonStreamOptions { - chunk_capacity_bytes: 32, - max_doc_bytes: 4096, - }; - let mut bars = Vec::new(); - let mut stream_errs = Vec::new(); - let stream_stats = decode_te_market_data_stream( - std::io::Cursor::new(&stream_bytes), - opts, - "USDCAD", - |b| bars.push(b), - |off, err| stream_errs.push((off, err)), - ) - .expect("stream framing itself is valid"); - - assert_stats_conserved(&stream_stats); - assert_eq!(bars.len(), 1); - assert_eq!(stream_stats.rejected_corrupt_document, 1); - assert_eq!(stream_errs.len(), 1); - assert_eq!(stream_errs[0].0, doc1_len); - match &stream_errs[0].1 { - BsonTeMarketDataError::CorruptBson { offset, .. } => { - assert_eq!(*offset as u64, doc1_len); - } - other => panic!("expected CorruptBson with rebased offset, got {other:?}"), - } -} - -#[test] -fn structural_corruption_after_semantic_reject_takes_precedence() { - // 1. Point with non-finite `t` followed by corrupt element type byte on `c`. - let mut pt = RawDocumentBuf::new(); - pt.append(cstr!("t"), f64::NAN); - pt.append(cstr!("o"), 1.38_f64); - pt.append(cstr!("h"), 1.39_f64); - pt.append(cstr!("l"), 1.37_f64); - pt.append(cstr!("c"), 1.385_f64); - - let mut daily = RawArrayBuf::new(); - daily.push(pt); - let doc = make_te_doc("USDCAD", daily); - let mut bytes = doc.as_bytes().to_vec(); - let c_elem_pos = bytes - .windows(3) - .position(|w| w == b"\x01c\0") - .expect("find double element 'c'"); - bytes[c_elem_pos] = 0xFF; - - let mut bars = Vec::new(); - let mut errs = Vec::new(); - let stats = decode_te_market_data_bytes(&bytes, "USDCAD", |b| bars.push(b), |e| errs.push(e)); - assert_stats_conserved(&stats); - assert!(bars.is_empty()); - assert_eq!(stats.points_in, 1); - assert_eq!(stats.rejected_corrupt_point, 1); - assert_eq!(stats.rejected_non_finite, 0); - assert!( - matches!( - errs.as_slice(), - [BsonTeMarketDataError::CorruptPointBson { point_index: 0, .. }] - ), - "expected CorruptPointBson to take precedence over NonFiniteValue, got {errs:?}" - ); - - // 2. Top-level doc with empty `teSymbol` followed by corrupt element type byte on `daily`. - let doc_empty_sym = make_te_doc("", RawArrayBuf::new()); - let mut doc_bytes = doc_empty_sym.as_bytes().to_vec(); - let daily_elem_pos = doc_bytes - .windows(7) - .position(|w| w == b"\x04daily\0") - .expect("find array element 'daily'"); - doc_bytes[daily_elem_pos] = 0xFF; - - let mut top_errs = Vec::new(); - let top_stats = - decode_te_market_data_bytes(&doc_bytes, "USDCAD", |_| {}, |e| top_errs.push(e)); - assert_stats_conserved(&top_stats); - assert_eq!(top_stats.rejected_corrupt_document, 1); - assert_eq!(top_stats.rejected_empty_symbol, 0); - assert!( - matches!( - top_errs.as_slice(), - [BsonTeMarketDataError::CorruptBson { .. }] - ), - "expected CorruptBson to take precedence over EmptySymbol, got {top_errs:?}" - ); -} diff --git a/tools/curate-etl/src/cli.rs b/tools/curate-etl/src/cli.rs index 27d4d76a..95fc40b6 100644 --- a/tools/curate-etl/src/cli.rs +++ b/tools/curate-etl/src/cli.rs @@ -3,115 +3,29 @@ //! Kept inside the library crate so CLI argument parsing tests run under //! `cargo test --workspace --lib --offline`. -use std::fs; -use std::io; -use std::path::{Path, PathBuf}; - use crate::bench::{ - DEFAULT_ADJ_BENCH_EVENTS, DEFAULT_BARS_1M_BENCH_ROWS, DEFAULT_BARS_BENCH_ROWS, - DEFAULT_BENCH_ROWS, - DEFAULT_BSON_EOD_PRICES_BENCH_ROWS, DEFAULT_BSON_QM_ACTIONS_BENCH_ROWS, - DEFAULT_BSON_STREAM_BENCH_ROWS, DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS, - DEFAULT_CURATE_ADJ_BENCH_EVENTS, DEFAULT_CURATE_ADJ_CMD_BENCH_EVENTS, - DEFAULT_CURATE_BARS_BENCH_ROWS, DEFAULT_CURATE_BARS_CMD_BENCH_ROWS, - DEFAULT_CURATE_CORPORATE_ACTIONS_BENCH_EVENTS, - DEFAULT_CURATE_CORPORATE_ACTIONS_CMD_BENCH_EVENTS, DEFAULT_CURATE_EVENTS_BENCH_ROWS, - DEFAULT_CURATE_EVENTS_CMD_BENCH_ROWS, DEFAULT_CURATE_FX_BENCH_ROWS, - DEFAULT_CURATE_FX_CMD_BENCH_ROWS, DEFAULT_CURATE_SHORTS_BENCH_ROWS, - DEFAULT_CURATE_SHORTS_COMMAND_BENCH_ROWS, DEFAULT_EVENTS_BENCH_ROWS, - DEFAULT_FUNDAMENTALS_BENCH_ROWS, DEFAULT_FX_BENCH_ROWS, DEFAULT_ILP_BARS_1M_BENCH_ROWS, - DEFAULT_MONGO_STREAM_BENCH_ROWS, DEFAULT_PARQUET_ADJ_BENCH_ROWS, - DEFAULT_PARQUET_BARS_BENCH_ROWS, + DEFAULT_ADJ_BENCH_EVENTS, DEFAULT_BARS_BENCH_ROWS, DEFAULT_BENCH_ROWS, + DEFAULT_BSON_EOD_PRICES_BENCH_ROWS, DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS, + DEFAULT_CURATE_BARS_BENCH_ROWS, DEFAULT_CURATE_EVENTS_BENCH_ROWS, + DEFAULT_CURATE_FX_BENCH_ROWS, DEFAULT_CURATE_SHORTS_BENCH_ROWS, DEFAULT_EVENTS_BENCH_ROWS, + DEFAULT_FX_BENCH_ROWS, DEFAULT_PARQUET_ADJ_BENCH_ROWS, DEFAULT_PARQUET_BARS_BENCH_ROWS, DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS, DEFAULT_PARQUET_EVENTS_BENCH_ROWS, DEFAULT_PARQUET_FX_BENCH_ROWS, DEFAULT_PARQUET_SHORTS_BENCH_ROWS, DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS, DEFAULT_SHORTS_BENCH_ROWS, }; -use crate::bson_ceo_posts::{ - CeoPostsTimestampUnit, DEFAULT_BOT_FIELD as DEFAULT_POSTS_BOT_FIELD, - DEFAULT_EDITED_FIELD as DEFAULT_POSTS_EDITED_FIELD, - DEFAULT_KEY_FIELD as DEFAULT_POSTS_KEY_FIELD, - DEFAULT_SPIEL_ID_FIELD as DEFAULT_POSTS_SPIEL_ID_FIELD, - DEFAULT_TEXT_FIELD as DEFAULT_POSTS_TEXT_FIELD, - DEFAULT_TIMESTAMP_FIELD as DEFAULT_POSTS_TIMESTAMP_FIELD, - DEFAULT_USER_ID_FIELD as DEFAULT_POSTS_USER_ID_FIELD, -}; -use crate::bson_ceo_shorts::{DEFAULT_KEY_FIELD, DEFAULT_REPORT_DATE_FIELD}; -use crate::bson_eod_prices::parse_ymd_strict_days; -use crate::bson_qm_events::{ - DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD, DEFAULT_EARNINGS_KEY_FIELD, - DEFAULT_EARNINGS_REPORT_DATE_FIELD, DEFAULT_FILINGS_KEY_FIELD, DEFAULT_FILINGS_TIMEFILED_FIELD, -}; -use crate::bson_qm_financials::{ - DEFAULT_QM_FINANCIALS_KEY_FIELD, DEFAULT_QM_FINANCIALS_PERIOD_END_FIELD, - DEFAULT_QM_FINANCIALS_REPORT_DATE_FIELD, DEFAULT_QM_FINANCIALS_REPORT_PERIOD_FIELD, -}; -use crate::bson_stream::BsonStreamOptions; -use crate::curate_adj::AdjPointInTimeFence; -use crate::fundamentals::FiscalPeriod; -use crate::ilp::IlpWriterOptions; -use crate::ilp_send::SendIlpArgs; -use crate::mongo_stream::{ - MongoCliOptions, MongoUriSource, DEFAULT_MONGO_BATCH_SIZE, DEFAULT_MONGO_URI_ENV, - MAX_MONGO_BATCH_SIZE, -}; -use crate::run_curate_adj::CurateAdjFactorsArgs; -use crate::run_curate_bars::{ - default_curate_bars_threads, CurateBars1dArgs, DEFAULT_CURATE_BARS_REL_TOLERANCE, -}; -use crate::run_curate_bars_1m::{CurateBars1mArgs, DEFAULT_BARS_1M_MAPPING_SOURCE}; -use crate::run_curate_corporate_actions::CurateCorporateActionsArgs; -use crate::run_curate_events::{CurateEventsArgs, DEFAULT_EVENTS_MAPPING_SOURCE}; -use crate::run_curate_fundamentals::{ - CurateFundamentalsArgs, CurateFundamentalsFiscalPeriod, DEFAULT_FUNDAMENTALS_MAPPING_SOURCE, -}; -use crate::run_curate_fx::{is_supported_te_symbol, CurateFx1dArgs, DEFAULT_TE_SYMBOL}; -use crate::run_curate_fx_1m::CurateFx1mArgs; -use crate::run_curate_macro::CurateMacroArgs; -use crate::run_curate_posts::{ - CuratePostsArgs, DEFAULT_MAPPING_SOURCE as DEFAULT_POSTS_MAPPING_SOURCE, -}; -use crate::run_curate_qm_bars_1m::{CurateQmBars1mArgs, DEFAULT_QM_BARS_1M_MAPPING_SOURCE}; -use crate::run_curate_shorts::{CurateShortsArgs, DEFAULT_MAPPING_SOURCE}; -use crate::run_mongo::{ - CurateAdjFactorsMongoArgs, CurateBars1dMongoArgs, CurateCorporateActionsMongoArgs, - CurateEventsMongoArgs, CurateFx1dMongoArgs, CurateShortsMongoArgs, -}; /// Parsed CLI command to execute. -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum CliAction { Help, Version, - CurateBars1d(CurateBars1dArgs), - CurateBars1dMongo(CurateBars1dMongoArgs), - CurateAdjFactors(CurateAdjFactorsArgs), - CurateAdjFactorsFenced(CurateAdjFactorsArgs, AdjPointInTimeFence), - CurateAdjFactorsMongo(CurateAdjFactorsMongoArgs), - CurateCorporateActions(CurateCorporateActionsArgs), - CurateCorporateActionsMongo(CurateCorporateActionsMongoArgs), - CurateFx1d(CurateFx1dArgs), - CurateFx1dMongo(CurateFx1dMongoArgs), - CurateShorts(CurateShortsArgs), - CurateShortsMongo(CurateShortsMongoArgs), - CurateEvents(CurateEventsArgs), - CurateEventsMongo(CurateEventsMongoArgs), - CurateBars1m(CurateBars1mArgs), - CurateQmBars1m(CurateQmBars1mArgs), - CurateFx1m(CurateFx1mArgs), - CuratePosts(CuratePostsArgs), - CurateFundamentals(CurateFundamentalsArgs), - CurateMacro(CurateMacroArgs), - SendIlp(SendIlpArgs), BenchSplit(usize), BenchAdj(usize), BenchCorporateActions(usize), BenchBars(usize), - BenchBars1m(usize), - BenchIlpBars1m(usize), BenchFx(usize), BenchShorts(usize), BenchEvents(usize), - BenchFundamentals(usize), BenchProviderMapping(usize), BenchParquetBars(usize), BenchParquetShorts(usize), @@ -120,21 +34,10 @@ pub enum CliAction { BenchParquetAdj(usize), BenchParquetCorporateActions(usize), BenchBsonEodPrices(usize), - BenchBsonQmActions(usize), - BenchBsonStream(usize), - BenchMongoStream(usize), BenchCurateBars(usize), - BenchCurateBarsCmd(usize), BenchCurateShorts(usize), - BenchCurateShortsCommand(usize), BenchCurateEvents(usize), - BenchCurateEventsCmd(usize), BenchCurateFx(usize), - BenchCurateFxCmd(usize), - BenchCurateAdj(usize), - BenchCurateAdjCmd(usize), - BenchCurateCorporateActions(usize), - BenchCurateCorporateActionsCmd(usize), } /// Formats full help text including binary name and version. @@ -145,48 +48,13 @@ pub fn format_usage(name: &str, version: &str) -> String { Usage:\n\ {name} [--help | -h]\n\ {name} [--version | -V]\n\ - {name} curate-bars-1d --eod-prices --qm-splits [--qm-prices ] (--curate-inputs | --provider-mapping --listing-currencies ) --out [--rel-tolerance ] [--threads ]\n\ - {name} curate-bars-1d --from-mongo [--mongo-uri-env | --mongo-uri ] [--with-qm-prices] [--batch-size ] [--limit ] [--date-gte ] [--date-lt ] (--curate-inputs | --provider-mapping --listing-currencies ) --out [--rel-tolerance ] [--threads ]\n\ - Curate daily bars from BSON + TSV files or read-only MongoDB into bars_1d/year=YYYY/part.parquet (default --rel-tolerance: {DEFAULT_CURATE_BARS_REL_TOLERANCE}, --threads: available parallelism)\n\ - {name} curate-adj-factors --qm-splits --qm-dividends --provider-mapping --bars-1d --out [--as-of ] [--vault-cutoff ]\n\ - {name} curate-adj-factors --from-mongo [--mongo-uri-env | --mongo-uri ] [--batch-size ] [--limit ] [--date-gte ] [--date-lt ] --provider-mapping --bars-1d --out [--as-of ] [--vault-cutoff ]\n\ - Curate retrospective or point-in-time fenced adj_factors into adj_factors/part.parquet\n\ - {name} curate-corporate-actions --qm-splits --qm-dividends (--curate-inputs | --provider-mapping [--delistings ]) --out \n\ - {name} curate-corporate-actions --from-mongo [--mongo-uri-env | --mongo-uri ] [--batch-size ] [--limit ] (--curate-inputs | --provider-mapping [--delistings ]) --out \n\ - Curate corporate_actions from BSON + TSV files or read-only MongoDB into corporate_actions/part.parquet\n\ - {name} curate-fx-1d --eod-prices --te-market-data [--te-symbol ] --out \n\ - {name} curate-fx-1d --from-mongo [--mongo-uri-env | --mongo-uri ] [--batch-size ] [--limit ] [--te-symbol ] --out \n\ - Curate USD/CAD fx_1d from eodPrices + teMarketData BSON files or read-only MongoDB into fx_1d/part.parquet (default --te-symbol: {DEFAULT_TE_SYMBOL})\n\ - {name} curate-shorts --ceo-shorts --provider-mapping --out --shares-short-field [--key-field ] [--report-date-field ] [--net-change-field ] [--pct-float-field ] [--mapping-source ]\n\ - {name} curate-shorts --from-mongo [--mongo-uri-env | --mongo-uri ] [--batch-size ] [--limit ] --provider-mapping --out --shares-short-field [--key-field ] [--report-date-field ] [--net-change-field ] [--pct-float-field ] [--mapping-source ]\n\ - Curate shorts from ceoShorts BSON or read-only MongoDB + provider_mapping TSV into shorts/part.parquet (defaults: --key-field {DEFAULT_KEY_FIELD}, --report-date-field {DEFAULT_REPORT_DATE_FIELD}, --mapping-source {DEFAULT_MAPPING_SOURCE})\n\ - {name} curate-events --qm-filings --qm-earnings --provider-mapping --out --filings-form-type-field [--filings-key-field ] [--filings-timefiled-field ] [--filings-filing-id-field ] [--filings-url-field ] [--earnings-key-field ] [--earnings-report-date-field ] [--earnings-announce-time-field ] [--earnings-fiscal-period-end-field ] [--earnings-actual-eps-field ] [--earnings-revenue-field ] [--mapping-source ]\n\ - {name} curate-events --from-mongo [--mongo-uri-env | --mongo-uri ] [--batch-size ] [--limit ] [--date-gte ] [--date-lt ] --provider-mapping --out --filings-form-type-field [--filings-key-field ] [--filings-timefiled-field ] [--filings-filing-id-field ] [--filings-url-field ] [--earnings-key-field ] [--earnings-report-date-field ] [--earnings-announce-time-field ] [--earnings-fiscal-period-end-field ] [--earnings-actual-eps-field ] [--earnings-revenue-field ] [--mapping-source ]\n\ - Curate events from qmFilings + qmEarnings BSON or read-only MongoDB + provider_mapping TSV into events/year=YYYY/part.parquet (defaults: --filings-key-field {DEFAULT_FILINGS_KEY_FIELD}, --filings-timefiled-field {DEFAULT_FILINGS_TIMEFILED_FIELD}, --earnings-key-field {DEFAULT_EARNINGS_KEY_FIELD}, --earnings-report-date-field {DEFAULT_EARNINGS_REPORT_DATE_FIELD}, --earnings-announce-time-field {DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD}, --mapping-source {DEFAULT_EVENTS_MAPPING_SOURCE})\n\ - {name} curate-bars-1m --eod-intraday --qm-splits --provider-mapping --out --shards --known-at-micros [--mapping-source ]\n\ - Curate split-unadjusted 1-minute bars from eodIntraday1M + qmSplits BSON + provider_mapping TSV into bars_1m.shard-.ilp (default --mapping-source: {DEFAULT_BARS_1M_MAPPING_SOURCE})\n\ - {name} curate-qm-bars-1m --qm-intraday --provider-mapping --out --shards --known-at-micros [--mapping-source ]\n\ - Curate raw 1-minute bars from qmIntraday BSON + provider_mapping TSV into bars_1m_qm.shard-.ilp (file mode only; default --mapping-source: {DEFAULT_QM_BARS_1M_MAPPING_SOURCE})\n\ - {name} curate-fx-1m --eod-intraday --out --shards \n\ - Curate USD/CAD 1-minute FX bars from eodIntraday1M BSON into fx_1m.shard-.ilp\n\ - {name} curate-posts --ceo-posts --provider-mapping --out --timestamp-unit [--key-field ] [--spiel-id-field ] [--timestamp-field ] [--edited-field ] [--bot-field ] [--user-id-field ] [--text-field ] [--mapping-source ]\n\ - Curate ceoPosts from BSON + provider_mapping TSV into /events/year=YYYY/part.parquet using a dedicated --out directory (--timestamp-unit has no default; defaults: --key-field {DEFAULT_POSTS_KEY_FIELD}, --spiel-id-field {DEFAULT_POSTS_SPIEL_ID_FIELD}, --timestamp-field {DEFAULT_POSTS_TIMESTAMP_FIELD}, --edited-field {DEFAULT_POSTS_EDITED_FIELD}, --bot-field {DEFAULT_POSTS_BOT_FIELD}, --user-id-field {DEFAULT_POSTS_USER_ID_FIELD}, --text-field {DEFAULT_POSTS_TEXT_FIELD}, --mapping-source {DEFAULT_POSTS_MAPPING_SOURCE})\n\ - {name} curate-fundamentals --qm-financials --qm-filings --provider-mapping --listing-venues --out --currency-field --filings-form-type-field --k (--fiscal-period | [--quarterly-tokens ] [--annual-tokens ]) [--financials-key-field ] [--period-end-field ] [--report-date-field ] [--report-period-field ] [--revenue-field ] [--net-income-field ] [--operating-cash-flow-field ] [--total-assets-field ] [--total-equity-field ] [--shares-outstanding-field ] [--filings-key-field ] [--filings-timefiled-field ] [--filings-filing-id-field ] [--filings-url-field ] [--mapping-source ]\n\ - Curate point-in-time fundamentals from qmFinancials + qmFilings BSON + provider_mapping/listing_venues TSVs into fundamentals_pit/year=YYYY/part.parquet (file mode only; defaults: --financials-key-field {DEFAULT_QM_FINANCIALS_KEY_FIELD}, --period-end-field {DEFAULT_QM_FINANCIALS_PERIOD_END_FIELD}, --report-date-field {DEFAULT_QM_FINANCIALS_REPORT_DATE_FIELD}, --report-period-field {DEFAULT_QM_FINANCIALS_REPORT_PERIOD_FIELD}, --filings-key-field {DEFAULT_FILINGS_KEY_FIELD}, --filings-timefiled-field {DEFAULT_FILINGS_TIMEFILED_FIELD}, --mapping-source {DEFAULT_FUNDAMENTALS_MAPPING_SOURCE})\n\ - {name} curate-macro --te-data --series-map --out \n\ - Curate macro regime series from a teData BSON dump + series-map TSV into /macro/part.parquet (file mode only)\n\ - {name} send-ilp --dir --prefix --addr \n\ - Stream published ILP v2 shard files to an explicit QuestDB TCP endpoint (no default address; success means bytes were accepted by local sockets, not rows committed — verify row counts via PGWire; ILP v2 binary doubles over TCP on QuestDB 10.2.0 are unverified until the manual quant load check)\n\ {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})\n\ - {name} bench-bars-1m [rows] Run fixed-seed bars_1m build + session-close cross-check benchmark (default: {DEFAULT_BARS_1M_BENCH_ROWS})\n\ - {name} bench-ilp-bars-1m [rows] Run fixed-seed QuestDB ILP v2 bars_1m encode + sharded batch benchmark (default: {DEFAULT_ILP_BARS_1M_BENCH_ROWS})\n\ {name} bench-fx [rows] Run fixed-seed fx_1d build + lookup benchmark (default: {DEFAULT_FX_BENCH_ROWS})\n\ {name} bench-shorts [rows] Run fixed-seed shorts build benchmark (default: {DEFAULT_SHORTS_BENCH_ROWS})\n\ {name} bench-events [rows] Run fixed-seed events build benchmark (default: {DEFAULT_EVENTS_BENCH_ROWS})\n\ - {name} bench-fundamentals [rows] Run fixed-seed fundamentals bitemporal + PIT snapshot benchmark (default: {DEFAULT_FUNDAMENTALS_BENCH_ROWS})\n\ {name} bench-provider-mapping [lookups] Run fixed-seed provider_mapping build + lookup benchmark (default: {DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS})\n\ {name} bench-parquet-bars [rows] Run fixed-seed bars_1d Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_BARS_BENCH_ROWS})\n\ {name} bench-parquet-shorts [rows] Run fixed-seed shorts Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_SHORTS_BENCH_ROWS})\n\ @@ -195,21 +63,10 @@ pub fn format_usage(name: &str, version: &str) -> String { {name} bench-parquet-adj [rows] Run fixed-seed adj_factors Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_ADJ_BENCH_ROWS})\n\ {name} bench-parquet-corporate-actions [rows] Run fixed-seed corporate_actions Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS})\n\ {name} bench-bson-eod-prices [rows] Run fixed-seed eodPrices raw BSON zero-copy decode benchmark (default: {DEFAULT_BSON_EOD_PRICES_BENCH_ROWS})\n\ - {name} bench-bson-qm-actions [rows] Run fixed-seed qmSplits/qmDividends raw BSON zero-copy decode benchmark (default: {DEFAULT_BSON_QM_ACTIONS_BENCH_ROWS})\n\ - {name} bench-bson-stream [rows] Run fixed-seed eodPrices raw BSON stream vs buffer decode benchmark (default: {DEFAULT_BSON_STREAM_BENCH_ROWS})\n\ - {name} bench-mongo-stream [rows] Run offline fixed-seed RawBsonCursorReader vs plain in-memory eodPrices decode benchmark (default: {DEFAULT_MONGO_STREAM_BENCH_ROWS})\n\ {name} bench-curate-bars [rows] Run fixed-seed bars_1d curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_BARS_BENCH_ROWS})\n\ - {name} bench-curate-bars-cmd [rows] Run fixed-seed end-to-end curate-bars-1d file->Parquet benchmark (default: {DEFAULT_CURATE_BARS_CMD_BENCH_ROWS})\n\ {name} bench-curate-shorts [rows] Run fixed-seed shorts curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_SHORTS_BENCH_ROWS})\n\ - {name} bench-curate-shorts-command [rows] Run fixed-seed end-to-end curate-shorts file->Parquet benchmark (default: {DEFAULT_CURATE_SHORTS_COMMAND_BENCH_ROWS})\n\ {name} bench-curate-events [rows] Run fixed-seed events curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_EVENTS_BENCH_ROWS})\n\ - {name} bench-curate-events-cmd [rows] Run fixed-seed end-to-end curate-events file->Parquet benchmark (default: {DEFAULT_CURATE_EVENTS_CMD_BENCH_ROWS})\n\ - {name} bench-curate-fx [rows] Run fixed-seed fx_1d curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_FX_BENCH_ROWS})\n\ - {name} bench-curate-fx-cmd [rows] Run fixed-seed end-to-end curate-fx-1d file->Parquet benchmark (default: {DEFAULT_CURATE_FX_CMD_BENCH_ROWS})\n\ - {name} bench-curate-adj [events] Run fixed-seed adj_factors curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_ADJ_BENCH_EVENTS})\n\ - {name} bench-curate-adj-cmd [events] Run fixed-seed end-to-end curate-adj-factors file->Parquet benchmark (default: {DEFAULT_CURATE_ADJ_CMD_BENCH_EVENTS})\n\ - {name} bench-curate-corporate-actions [events] Run fixed-seed corporate_actions curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_CORPORATE_ACTIONS_BENCH_EVENTS})\n\ - {name} bench-curate-corporate-actions-cmd [events] Run fixed-seed end-to-end curate-corporate-actions file->Parquet benchmark (default: {DEFAULT_CURATE_CORPORATE_ACTIONS_CMD_BENCH_EVENTS})" + {name} bench-curate-fx [rows] Run fixed-seed fx_1d curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_FX_BENCH_ROWS})" ) } @@ -219,29 +76,13 @@ pub fn format_usage_stderr(name: &str) -> String { "Usage:\n\ {name} [--help | -h]\n\ {name} [--version | -V]\n\ - {name} curate-bars-1d --eod-prices --qm-splits [--qm-prices ] (--curate-inputs | --provider-mapping --listing-currencies ) --out [--rel-tolerance ] [--threads ]\n\ - {name} curate-adj-factors --qm-splits --qm-dividends --provider-mapping --bars-1d --out \n\ - {name} curate-corporate-actions --qm-splits --qm-dividends (--curate-inputs | --provider-mapping [--delistings ]) --out \n\ - {name} curate-fx-1d --eod-prices --te-market-data [--te-symbol ] --out \n\ - {name} curate-shorts --ceo-shorts --provider-mapping --out --shares-short-field [--key-field ] [--report-date-field ] [--net-change-field ] [--pct-float-field ] [--mapping-source ]\n\ - {name} curate-events --qm-filings --qm-earnings --provider-mapping --out --filings-form-type-field [--filings-key-field ] [--filings-timefiled-field ] [--filings-filing-id-field ] [--filings-url-field ] [--earnings-key-field ] [--earnings-report-date-field ] [--earnings-announce-time-field ] [--earnings-fiscal-period-end-field ] [--earnings-actual-eps-field ] [--earnings-revenue-field ] [--mapping-source ]\n\ - {name} curate-bars-1m --eod-intraday --qm-splits --provider-mapping --out --shards --known-at-micros [--mapping-source ]\n\ - {name} curate-qm-bars-1m --qm-intraday --provider-mapping --out --shards --known-at-micros [--mapping-source ]\n\ - {name} curate-fx-1m --eod-intraday --out --shards \n\ - {name} curate-posts --ceo-posts --provider-mapping --out --timestamp-unit [--key-field ] [--spiel-id-field ] [--timestamp-field ] [--edited-field ] [--bot-field ] [--user-id-field ] [--text-field ] [--mapping-source ]\n\ - {name} curate-fundamentals --qm-financials --qm-filings --provider-mapping --listing-venues --out --currency-field --filings-form-type-field --k (--fiscal-period | [--quarterly-tokens ] [--annual-tokens ]) [--financials-key-field ] [--period-end-field ] [--report-date-field ] [--report-period-field ] [--revenue-field ] [--net-income-field ] [--operating-cash-flow-field ] [--total-assets-field ] [--total-equity-field ] [--shares-outstanding-field ] [--filings-key-field ] [--filings-timefiled-field ] [--filings-filing-id-field ] [--filings-url-field ] [--mapping-source ]\n\ - {name} curate-macro --te-data --series-map --out \n\ - {name} send-ilp --dir --prefix --addr \n\ {name} bench-split [rows]\n\ {name} bench-adj [events]\n\ {name} bench-corporate-actions [events]\n\ {name} bench-bars [rows]\n\ - {name} bench-bars-1m [rows]\n\ - {name} bench-ilp-bars-1m [rows]\n\ {name} bench-fx [rows]\n\ {name} bench-shorts [rows]\n\ {name} bench-events [rows]\n\ - {name} bench-fundamentals [rows]\n\ {name} bench-provider-mapping [lookups]\n\ {name} bench-parquet-bars [rows]\n\ {name} bench-parquet-shorts [rows]\n\ @@ -250,2217 +91,13 @@ pub fn format_usage_stderr(name: &str) -> String { {name} bench-parquet-adj [rows]\n\ {name} bench-parquet-corporate-actions [rows]\n\ {name} bench-bson-eod-prices [rows]\n\ - {name} bench-bson-qm-actions [rows]\n\ - {name} bench-bson-stream [rows]\n\ - {name} bench-mongo-stream [rows]\n\ {name} bench-curate-bars [rows]\n\ - {name} bench-curate-bars-cmd [rows]\n\ {name} bench-curate-shorts [rows]\n\ - {name} bench-curate-shorts-command [rows]\n\ {name} bench-curate-events [rows]\n\ - {name} bench-curate-events-cmd [rows]\n\ - {name} bench-curate-fx [rows]\n\ - {name} bench-curate-fx-cmd [rows]\n\ - {name} bench-curate-adj [events]\n\ - {name} bench-curate-adj-cmd [events]\n\ - {name} bench-curate-corporate-actions [events]\n\ - {name} bench-curate-corporate-actions-cmd [events]" + {name} bench-curate-fx [rows]" ) } -/// Pins a `curate-inputs` directory to one immutable generation directory before opening any TSV. -/// -/// Requires `/current` (the atomic symlink published by `run-export-curate-inputs.ts`) to -/// exist and resolves it once via [`fs::canonicalize`] so every TSV in this invocation comes from -/// that exact generation even if a concurrent export refreshes `current`. Fails closed when -/// `/current` is absent; pass explicit `--provider-mapping`, `--listing-currencies`, or -/// `--delistings` flags for standalone files or direct generation directories. -pub fn pin_curate_inputs_dir(dir: &Path) -> Result { - let current = dir.join("current"); - match fs::symlink_metadata(¤t) { - Ok(_) => {} - Err(err) if err.kind() == io::ErrorKind::NotFound => { - return Err(format!( - "--curate-inputs '{}' requires a committed 'current' link (missing '{}'); pass explicit --provider-mapping / --listing-currencies / --delistings flags for standalone or direct-generation TSV files", - dir.display(), - current.display() - )); - } - Err(err) => { - return Err(format!( - "failed to inspect --curate-inputs '{}': {err}", - current.display() - )); - } - } - let canonical = fs::canonicalize(¤t).map_err(|err| { - format!( - "failed to resolve --curate-inputs '{}': {err}", - current.display() - ) - })?; - if !canonical.is_dir() { - return Err(format!( - "--curate-inputs '{}' does not resolve to a directory", - dir.display() - )); - } - Ok(canonical) -} - -const MICROS_PER_DAY: i64 = 86_400_000_000; - -#[derive(Default)] -struct MongoFlagState { - from_mongo: bool, - mongo_uri: Option, - mongo_uri_env: Option, - batch_size: Option, - limit: Option, - date_gte: Option, - date_lt: Option, -} - -impl MongoFlagState { - fn has_any_mongo_option(&self) -> bool { - self.mongo_uri.is_some() - || self.mongo_uri_env.is_some() - || self.batch_size.is_some() - || self.limit.is_some() - || self.date_gte.is_some() - || self.date_lt.is_some() - } - - fn try_parse_value_flag( - &mut self, - flag: &str, - value: &str, - allow_date_range: bool, - ) -> Result { - match flag { - "--mongo-uri" => { - if self.mongo_uri.is_some() { - return Err("duplicate flag '--mongo-uri'".to_string()); - } - if value.trim().is_empty() { - return Err("empty value for flag '--mongo-uri'".to_string()); - } - self.mongo_uri = Some(value.to_string()); - Ok(true) - } - "--mongo-uri-env" => { - if self.mongo_uri_env.is_some() { - return Err("duplicate flag '--mongo-uri-env'".to_string()); - } - if value.trim().is_empty() { - return Err("empty value for flag '--mongo-uri-env'".to_string()); - } - self.mongo_uri_env = Some(value.to_string()); - Ok(true) - } - "--batch-size" => { - if self.batch_size.is_some() { - return Err("duplicate flag '--batch-size'".to_string()); - } - let parsed = value.parse::().map_err(|_| { - format!( - "invalid --batch-size '{value}' (expected an integer in 1..={MAX_MONGO_BATCH_SIZE})" - ) - })?; - if parsed == 0 || parsed > MAX_MONGO_BATCH_SIZE { - return Err(format!( - "invalid --batch-size '{value}' (expected an integer in 1..={MAX_MONGO_BATCH_SIZE})" - )); - } - self.batch_size = Some(parsed); - Ok(true) - } - "--limit" => { - if self.limit.is_some() { - return Err("duplicate flag '--limit'".to_string()); - } - let parsed = value.parse::().map_err(|_| { - format!("invalid --limit '{value}' (expected a positive integer)") - })?; - if parsed == 0 || parsed > i64::MAX as u64 { - return Err(format!( - "invalid --limit '{value}' (expected a positive integer <= {})", - i64::MAX - )); - } - self.limit = Some(parsed); - Ok(true) - } - "--date-gte" if allow_date_range => { - if self.date_gte.is_some() { - return Err("duplicate flag '--date-gte'".to_string()); - } - if parse_ymd_strict_days(value).is_none() { - return Err(format!( - "invalid --date-gte '{value}' (expected strict YYYY-MM-DD)" - )); - } - self.date_gte = Some(value.to_string()); - Ok(true) - } - "--date-lt" if allow_date_range => { - if self.date_lt.is_some() { - return Err("duplicate flag '--date-lt'".to_string()); - } - if parse_ymd_strict_days(value).is_none() { - return Err(format!( - "invalid --date-lt '{value}' (expected strict YYYY-MM-DD)" - )); - } - self.date_lt = Some(value.to_string()); - Ok(true) - } - _ => Ok(false), - } - } - - fn build_options(self) -> Result { - if self.mongo_uri.is_some() && self.mongo_uri_env.is_some() { - return Err("cannot combine '--mongo-uri' with '--mongo-uri-env'".to_string()); - } - if let (Some(gte), Some(lt)) = (&self.date_gte, &self.date_lt) { - if gte >= lt { - return Err(format!( - "invalid date range: --date-gte '{gte}' must be strictly less than --date-lt '{lt}'" - )); - } - } - let uri_source = if let Some(uri) = self.mongo_uri { - MongoUriSource::Literal(uri) - } else { - MongoUriSource::EnvVar( - self.mongo_uri_env - .unwrap_or_else(|| DEFAULT_MONGO_URI_ENV.to_owned()), - ) - }; - Ok(MongoCliOptions { - uri_source, - batch_size: self.batch_size.unwrap_or(DEFAULT_MONGO_BATCH_SIZE), - limit: self.limit, - date_gte: self.date_gte, - date_lt: self.date_lt, - }) - } -} - -fn parse_curate_bars_1d_args(args: &[&str]) -> Result { - let mut mongo = MongoFlagState::default(); - let mut with_qm_prices = false; - let mut eod_prices: Option = None; - let mut qm_splits: Option = None; - let mut qm_prices: Option = None; - let mut curate_inputs: Option = None; - let mut provider_mapping: Option = None; - let mut listing_currencies: Option = None; - let mut out_dir: Option = None; - let mut rel_tolerance: Option = None; - let mut threads: Option = None; - - let mut i = 0usize; - while i < args.len() { - let token = args[i]; - if !token.starts_with("--") { - return Err(format!( - "unexpected positional argument '{token}' for curate-bars-1d" - )); - } - - if token == "--from-mongo" { - if mongo.from_mongo { - return Err("duplicate flag '--from-mongo'".to_string()); - } - mongo.from_mongo = true; - i += 1; - continue; - } - if token == "--with-qm-prices" { - if with_qm_prices { - return Err("duplicate flag '--with-qm-prices'".to_string()); - } - with_qm_prices = true; - i += 1; - continue; - } - - let (flag, value) = if let Some((k, v)) = token.split_once('=') { - i += 1; - (k, v) - } else { - let Some(&v) = args.get(i + 1) else { - return Err(format!("missing value for flag '{token}'")); - }; - if v.starts_with("--") { - return Err(format!("missing value for flag '{token}'")); - } - i += 2; - (token, v) - }; - - if mongo.try_parse_value_flag(flag, value, true)? { - continue; - } - - let set_path = |slot: &mut Option, flag_name: &str, raw: &str| -> Result<(), String> { - if slot.is_some() { - return Err(format!("duplicate flag '{flag_name}'")); - } - if raw.is_empty() { - return Err(format!("empty value for flag '{flag_name}'")); - } - *slot = Some(PathBuf::from(raw)); - Ok(()) - }; - - match flag { - "--eod-prices" => set_path(&mut eod_prices, "--eod-prices", value)?, - "--qm-splits" => set_path(&mut qm_splits, "--qm-splits", value)?, - "--qm-prices" => set_path(&mut qm_prices, "--qm-prices", value)?, - "--curate-inputs" => set_path(&mut curate_inputs, "--curate-inputs", value)?, - "--provider-mapping" => set_path(&mut provider_mapping, "--provider-mapping", value)?, - "--listing-currencies" => { - set_path(&mut listing_currencies, "--listing-currencies", value)?; - } - "--out" => set_path(&mut out_dir, "--out", value)?, - "--rel-tolerance" => { - if rel_tolerance.is_some() { - return Err("duplicate flag '--rel-tolerance'".to_string()); - } - let parsed = value.parse::().map_err(|_| { - format!( - "invalid --rel-tolerance '{value}' (expected a finite non-negative number)" - ) - })?; - if !parsed.is_finite() || parsed < 0.0 { - return Err(format!( - "invalid --rel-tolerance '{value}' (expected a finite non-negative number)" - )); - } - let normalized = if parsed == 0.0 { 0.0 } else { parsed }; - rel_tolerance = Some(normalized); - } - "--threads" => { - if threads.is_some() { - return Err("duplicate flag '--threads'".to_string()); - } - if value.is_empty() || !value.bytes().all(|b| b.is_ascii_digit()) { - return Err(format!( - "invalid --threads '{value}' (expected a positive integer >= 1)" - )); - } - let parsed = value.parse::().map_err(|_| { - format!("invalid --threads '{value}' (expected a positive integer >= 1)") - })?; - if parsed == 0 { - return Err(format!( - "invalid --threads '{value}' (expected a positive integer >= 1)" - )); - } - threads = Some(parsed); - } - other => return Err(format!("unknown flag '{other}' for curate-bars-1d")), - } - } - - if mongo.from_mongo { - if eod_prices.is_some() || qm_splits.is_some() || qm_prices.is_some() { - return Err( - "cannot combine '--from-mongo' with '--eod-prices', '--qm-splits', or '--qm-prices'" - .to_string(), - ); - } - let mongo_opts = mongo.build_options()?; - let (provider_mapping, listing_currencies) = if let Some(inputs_dir) = curate_inputs { - if provider_mapping.is_some() { - return Err( - "cannot combine '--curate-inputs' with '--provider-mapping'".to_string() - ); - } - if listing_currencies.is_some() { - return Err( - "cannot combine '--curate-inputs' with '--listing-currencies'".to_string(), - ); - } - let pinned = pin_curate_inputs_dir(&inputs_dir)?; - ( - pinned.join("provider_mapping.tsv"), - pinned.join("listing_currencies.tsv"), - ) - } else { - let provider_mapping = provider_mapping - .ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?; - let listing_currencies = listing_currencies - .ok_or_else(|| "missing required flag '--listing-currencies'".to_string())?; - (provider_mapping, listing_currencies) - }; - let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; - return Ok(CliAction::CurateBars1dMongo(CurateBars1dMongoArgs { - mongo: mongo_opts, - with_qm_prices, - provider_mapping, - listing_currencies, - out_dir, - rel_tolerance: rel_tolerance.unwrap_or(DEFAULT_CURATE_BARS_REL_TOLERANCE), - threads: threads.unwrap_or_else(default_curate_bars_threads), - })); - } - - if mongo.has_any_mongo_option() || with_qm_prices { - return Err("MongoDB streaming flags require '--from-mongo'".to_string()); - } - - let eod_prices = - eod_prices.ok_or_else(|| "missing required flag '--eod-prices'".to_string())?; - let qm_splits = qm_splits.ok_or_else(|| "missing required flag '--qm-splits'".to_string())?; - let (provider_mapping, listing_currencies) = if let Some(inputs_dir) = curate_inputs { - if provider_mapping.is_some() { - return Err("cannot combine '--curate-inputs' with '--provider-mapping'".to_string()); - } - if listing_currencies.is_some() { - return Err( - "cannot combine '--curate-inputs' with '--listing-currencies'".to_string(), - ); - } - let pinned = pin_curate_inputs_dir(&inputs_dir)?; - ( - pinned.join("provider_mapping.tsv"), - pinned.join("listing_currencies.tsv"), - ) - } else { - let provider_mapping = provider_mapping - .ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?; - let listing_currencies = listing_currencies - .ok_or_else(|| "missing required flag '--listing-currencies'".to_string())?; - (provider_mapping, listing_currencies) - }; - let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; - - Ok(CliAction::CurateBars1d(CurateBars1dArgs { - eod_prices, - qm_splits, - qm_prices, - provider_mapping, - listing_currencies, - out_dir, - rel_tolerance: rel_tolerance.unwrap_or(DEFAULT_CURATE_BARS_REL_TOLERANCE), - threads: threads.unwrap_or_else(default_curate_bars_threads), - })) -} - -fn parse_curate_adj_factors_args(args: &[&str]) -> Result { - let mut mongo = MongoFlagState::default(); - let mut qm_splits: Option = None; - let mut qm_dividends: Option = None; - let mut provider_mapping: Option = None; - let mut bars_1d_dir: Option = None; - let mut out_dir: Option = None; - let mut as_of_date: Option = None; - let mut vault_cutoff_date: Option = None; - - let mut i = 0usize; - while i < args.len() { - let token = args[i]; - if !token.starts_with("--") { - return Err(format!( - "unexpected positional argument '{token}' for curate-adj-factors" - )); - } - - if token == "--from-mongo" { - if mongo.from_mongo { - return Err("duplicate flag '--from-mongo'".to_string()); - } - mongo.from_mongo = true; - i += 1; - continue; - } - - let (flag, value) = if let Some((k, v)) = token.split_once('=') { - i += 1; - (k, v) - } else { - let Some(&v) = args.get(i + 1) else { - return Err(format!("missing value for flag '{token}'")); - }; - if v.starts_with("--") { - return Err(format!("missing value for flag '{token}'")); - } - i += 2; - (token, v) - }; - - if mongo.try_parse_value_flag(flag, value, true)? { - continue; - } - - let set_path = |slot: &mut Option, flag_name: &str, raw: &str| -> Result<(), String> { - if slot.is_some() { - return Err(format!("duplicate flag '{flag_name}'")); - } - if raw.is_empty() { - return Err(format!("empty value for flag '{flag_name}'")); - } - *slot = Some(PathBuf::from(raw)); - Ok(()) - }; - - match flag { - "--qm-splits" => set_path(&mut qm_splits, "--qm-splits", value)?, - "--qm-dividends" => set_path(&mut qm_dividends, "--qm-dividends", value)?, - "--provider-mapping" => set_path(&mut provider_mapping, "--provider-mapping", value)?, - "--bars-1d" => set_path(&mut bars_1d_dir, "--bars-1d", value)?, - "--out" => set_path(&mut out_dir, "--out", value)?, - "--as-of" => { - if as_of_date.is_some() { - return Err("duplicate flag '--as-of'".to_string()); - } - let days = parse_ymd_strict_days(value).ok_or_else(|| { - format!("invalid --as-of '{value}' (expected strict YYYY-MM-DD)") - })?; - as_of_date = Some(days); - } - "--vault-cutoff" => { - if vault_cutoff_date.is_some() { - return Err("duplicate flag '--vault-cutoff'".to_string()); - } - let days = parse_ymd_strict_days(value).ok_or_else(|| { - format!("invalid --vault-cutoff '{value}' (expected strict YYYY-MM-DD)") - })?; - vault_cutoff_date = Some(days); - } - other => return Err(format!("unknown flag '{other}' for curate-adj-factors")), - } - } - - let fence = if as_of_date.is_some() || vault_cutoff_date.is_some() { - let as_of_micros = as_of_date.map(|d| (i64::from(d) + 1) * MICROS_PER_DAY - 1); - let vault_cutoff_micros = vault_cutoff_date.map(|d| i64::from(d) * MICROS_PER_DAY); - Some(AdjPointInTimeFence { - as_of_micros, - vault_cutoff_micros, - }) - } else { - None - }; - - if mongo.from_mongo { - if qm_splits.is_some() || qm_dividends.is_some() { - return Err( - "cannot combine '--from-mongo' with '--qm-splits' or '--qm-dividends'".to_string(), - ); - } - let mongo_opts = mongo.build_options()?; - let provider_mapping = provider_mapping - .ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?; - let bars_1d_dir = - bars_1d_dir.ok_or_else(|| "missing required flag '--bars-1d'".to_string())?; - let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; - return Ok(CliAction::CurateAdjFactorsMongo( - CurateAdjFactorsMongoArgs { - mongo: mongo_opts, - provider_mapping, - bars_1d_dir, - out_dir, - fence, - }, - )); - } - - if mongo.has_any_mongo_option() { - return Err("MongoDB streaming flags require '--from-mongo'".to_string()); - } - - let qm_splits = qm_splits.ok_or_else(|| "missing required flag '--qm-splits'".to_string())?; - let qm_dividends = - qm_dividends.ok_or_else(|| "missing required flag '--qm-dividends'".to_string())?; - let provider_mapping = - provider_mapping.ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?; - let bars_1d_dir = bars_1d_dir.ok_or_else(|| "missing required flag '--bars-1d'".to_string())?; - let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; - - let base = CurateAdjFactorsArgs { - qm_splits, - qm_dividends, - provider_mapping, - bars_1d_dir, - out_dir, - }; - match fence { - Some(f) => Ok(CliAction::CurateAdjFactorsFenced(base, f)), - None => Ok(CliAction::CurateAdjFactors(base)), - } -} - -fn parse_curate_corporate_actions_args(args: &[&str]) -> Result { - let mut mongo = MongoFlagState::default(); - let mut qm_splits: Option = None; - let mut qm_dividends: Option = None; - let mut curate_inputs: Option = None; - let mut provider_mapping: Option = None; - let mut delistings: Option = None; - let mut out_dir: Option = None; - - let mut i = 0usize; - while i < args.len() { - let token = args[i]; - if !token.starts_with("--") { - return Err(format!( - "unexpected positional argument '{token}' for curate-corporate-actions" - )); - } - - if token == "--from-mongo" { - if mongo.from_mongo { - return Err("duplicate flag '--from-mongo'".to_string()); - } - mongo.from_mongo = true; - i += 1; - continue; - } - - let (flag, value) = if let Some((k, v)) = token.split_once('=') { - i += 1; - (k, v) - } else { - let Some(&v) = args.get(i + 1) else { - return Err(format!("missing value for flag '{token}'")); - }; - if v.starts_with("--") { - return Err(format!("missing value for flag '{token}'")); - } - i += 2; - (token, v) - }; - - if mongo.try_parse_value_flag(flag, value, false)? { - continue; - } - - let set_path = |slot: &mut Option, flag_name: &str, raw: &str| -> Result<(), String> { - if slot.is_some() { - return Err(format!("duplicate flag '{flag_name}'")); - } - if raw.is_empty() { - return Err(format!("empty value for flag '{flag_name}'")); - } - *slot = Some(PathBuf::from(raw)); - Ok(()) - }; - - match flag { - "--qm-splits" => set_path(&mut qm_splits, "--qm-splits", value)?, - "--qm-dividends" => set_path(&mut qm_dividends, "--qm-dividends", value)?, - "--curate-inputs" => set_path(&mut curate_inputs, "--curate-inputs", value)?, - "--provider-mapping" => set_path(&mut provider_mapping, "--provider-mapping", value)?, - "--delistings" => set_path(&mut delistings, "--delistings", value)?, - "--out" => set_path(&mut out_dir, "--out", value)?, - other => { - return Err(format!( - "unknown flag '{other}' for curate-corporate-actions" - )) - } - } - } - - if mongo.from_mongo { - if qm_splits.is_some() || qm_dividends.is_some() { - return Err( - "cannot combine '--from-mongo' with '--qm-splits' or '--qm-dividends'".to_string(), - ); - } - let mongo_opts = mongo.build_options()?; - let (provider_mapping, delistings) = if let Some(inputs_dir) = curate_inputs { - if provider_mapping.is_some() { - return Err( - "cannot combine '--curate-inputs' with '--provider-mapping'".to_string() - ); - } - if delistings.is_some() { - return Err("cannot combine '--curate-inputs' with '--delistings'".to_string()); - } - let pinned = pin_curate_inputs_dir(&inputs_dir)?; - ( - pinned.join("provider_mapping.tsv"), - Some(pinned.join("delistings.tsv")), - ) - } else { - let provider_mapping = provider_mapping - .ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?; - (provider_mapping, delistings) - }; - let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; - return Ok(CliAction::CurateCorporateActionsMongo( - CurateCorporateActionsMongoArgs { - mongo: mongo_opts, - provider_mapping, - delistings, - out_dir, - }, - )); - } - - if mongo.has_any_mongo_option() { - return Err("MongoDB streaming flags require '--from-mongo'".to_string()); - } - - let qm_splits = qm_splits.ok_or_else(|| "missing required flag '--qm-splits'".to_string())?; - let qm_dividends = - qm_dividends.ok_or_else(|| "missing required flag '--qm-dividends'".to_string())?; - let (provider_mapping, delistings) = if let Some(inputs_dir) = curate_inputs { - if provider_mapping.is_some() { - return Err("cannot combine '--curate-inputs' with '--provider-mapping'".to_string()); - } - if delistings.is_some() { - return Err("cannot combine '--curate-inputs' with '--delistings'".to_string()); - } - let pinned = pin_curate_inputs_dir(&inputs_dir)?; - ( - pinned.join("provider_mapping.tsv"), - Some(pinned.join("delistings.tsv")), - ) - } else { - let provider_mapping = provider_mapping - .ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?; - (provider_mapping, delistings) - }; - let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; - - Ok(CliAction::CurateCorporateActions( - CurateCorporateActionsArgs { - qm_splits, - qm_dividends, - provider_mapping, - delistings, - out_dir, - }, - )) -} - -fn parse_curate_fx_1d_args(args: &[&str]) -> Result { - let mut mongo = MongoFlagState::default(); - let mut eod_prices: Option = None; - let mut te_market_data: Option = None; - let mut te_symbol: Option = None; - let mut out_dir: Option = None; - - let mut i = 0usize; - while i < args.len() { - let token = args[i]; - if !token.starts_with("--") { - return Err(format!( - "unexpected positional argument '{token}' for curate-fx-1d" - )); - } - - if token == "--from-mongo" { - if mongo.from_mongo { - return Err("duplicate flag '--from-mongo'".to_string()); - } - mongo.from_mongo = true; - i += 1; - continue; - } - - let (flag, value) = if let Some((k, v)) = token.split_once('=') { - i += 1; - (k, v) - } else { - let Some(&v) = args.get(i + 1) else { - return Err(format!("missing value for flag '{token}'")); - }; - if v.starts_with("--") { - return Err(format!("missing value for flag '{token}'")); - } - i += 2; - (token, v) - }; - - if mongo.try_parse_value_flag(flag, value, false)? { - continue; - } - - let set_path = |slot: &mut Option, flag_name: &str, raw: &str| -> Result<(), String> { - if slot.is_some() { - return Err(format!("duplicate flag '{flag_name}'")); - } - if raw.is_empty() { - return Err(format!("empty value for flag '{flag_name}'")); - } - *slot = Some(PathBuf::from(raw)); - Ok(()) - }; - - match flag { - "--eod-prices" => set_path(&mut eod_prices, "--eod-prices", value)?, - "--te-market-data" => set_path(&mut te_market_data, "--te-market-data", value)?, - "--te-symbol" => { - if te_symbol.is_some() { - return Err("duplicate flag '--te-symbol'".to_string()); - } - if !is_supported_te_symbol(value) { - return Err(format!( - "invalid --te-symbol '{value}': only USD/CAD selector '{DEFAULT_TE_SYMBOL}' (case-insensitive) is supported for fx_1d" - )); - } - te_symbol = Some(value.to_string()); - } - "--out" => set_path(&mut out_dir, "--out", value)?, - other => return Err(format!("unknown flag '{other}' for curate-fx-1d")), - } - } - - if mongo.from_mongo { - if eod_prices.is_some() || te_market_data.is_some() { - return Err( - "cannot combine '--from-mongo' with '--eod-prices' or '--te-market-data'" - .to_string(), - ); - } - let mongo_opts = mongo.build_options()?; - let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; - return Ok(CliAction::CurateFx1dMongo(CurateFx1dMongoArgs { - mongo: mongo_opts, - te_symbol: te_symbol.unwrap_or_else(|| DEFAULT_TE_SYMBOL.to_string()), - out_dir, - })); - } - - if mongo.has_any_mongo_option() { - return Err("MongoDB streaming flags require '--from-mongo'".to_string()); - } - - let eod_prices = - eod_prices.ok_or_else(|| "missing required flag '--eod-prices'".to_string())?; - let te_market_data = - te_market_data.ok_or_else(|| "missing required flag '--te-market-data'".to_string())?; - let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; - - Ok(CliAction::CurateFx1d(CurateFx1dArgs { - eod_prices, - te_market_data, - te_symbol: te_symbol.unwrap_or_else(|| DEFAULT_TE_SYMBOL.to_string()), - out_dir, - })) -} - -fn set_path(slot: &mut Option, flag_name: &str, raw: &str) -> Result<(), String> { - if slot.is_some() { - return Err(format!("duplicate flag '{flag_name}'")); - } - if raw.is_empty() { - return Err(format!("empty value for flag '{flag_name}'")); - } - *slot = Some(PathBuf::from(raw)); - Ok(()) -} - -fn set_name(slot: &mut Option, flag_name: &str, raw: &str) -> Result<(), String> { - if slot.is_some() { - return Err(format!("duplicate flag '{flag_name}'")); - } - if raw.trim().is_empty() { - return Err(format!("empty value for flag '{flag_name}'")); - } - *slot = Some(raw.to_string()); - Ok(()) -} - -fn parse_curate_shorts_args(args: &[&str]) -> Result { - let mut mongo = MongoFlagState::default(); - let mut ceo_shorts: Option = None; - let mut provider_mapping: Option = None; - let mut out_dir: Option = None; - let mut key_field: Option = None; - let mut report_date_field: Option = None; - let mut shares_short_field: Option = None; - let mut net_change_field: Option = None; - let mut pct_float_field: Option = None; - let mut mapping_source: Option = None; - - let mut i = 0usize; - while i < args.len() { - let token = args[i]; - if !token.starts_with("--") { - return Err(format!( - "unexpected positional argument '{token}' for curate-shorts" - )); - } - - if token == "--from-mongo" { - if mongo.from_mongo { - return Err("duplicate flag '--from-mongo'".to_string()); - } - mongo.from_mongo = true; - i += 1; - continue; - } - - let (flag, value) = if let Some((k, v)) = token.split_once('=') { - i += 1; - (k, v) - } else { - let Some(&v) = args.get(i + 1) else { - return Err(format!("missing value for flag '{token}'")); - }; - if v.starts_with("--") { - return Err(format!("missing value for flag '{token}'")); - } - i += 2; - (token, v) - }; - - if mongo.try_parse_value_flag(flag, value, false)? { - continue; - } - - match flag { - "--ceo-shorts" => set_path(&mut ceo_shorts, "--ceo-shorts", value)?, - "--provider-mapping" => set_path(&mut provider_mapping, "--provider-mapping", value)?, - "--out" => set_path(&mut out_dir, "--out", value)?, - "--key-field" => set_name(&mut key_field, "--key-field", value)?, - "--report-date-field" => { - set_name(&mut report_date_field, "--report-date-field", value)?; - } - "--shares-short-field" => { - set_name(&mut shares_short_field, "--shares-short-field", value)?; - } - "--net-change-field" => set_name(&mut net_change_field, "--net-change-field", value)?, - "--pct-float-field" => set_name(&mut pct_float_field, "--pct-float-field", value)?, - "--mapping-source" => set_name(&mut mapping_source, "--mapping-source", value)?, - other => return Err(format!("unknown flag '{other}' for curate-shorts")), - } - } - - if mongo.from_mongo { - if ceo_shorts.is_some() { - return Err("cannot combine '--from-mongo' with '--ceo-shorts'".to_string()); - } - let mongo_opts = mongo.build_options()?; - let provider_mapping = provider_mapping - .ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?; - let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; - let shares_short_field = shares_short_field - .ok_or_else(|| "missing required flag '--shares-short-field'".to_string())?; - let key_field = key_field.unwrap_or_else(|| DEFAULT_KEY_FIELD.to_string()); - let report_date_field = - report_date_field.unwrap_or_else(|| DEFAULT_REPORT_DATE_FIELD.to_string()); - let check = CurateShortsArgs { - ceo_shorts: PathBuf::from("mongodb://ceoShorts"), - provider_mapping: provider_mapping.clone(), - out_dir: out_dir.clone(), - key_field: key_field.clone(), - report_date_field: report_date_field.clone(), - shares_short_field: shares_short_field.clone(), - net_change_field: net_change_field.clone(), - pct_float_field: pct_float_field.clone(), - mapping_source: mapping_source - .clone() - .unwrap_or_else(|| DEFAULT_MAPPING_SOURCE.to_string()), - }; - check.field_names().validate().map_err(|e| e.to_string())?; - return Ok(CliAction::CurateShortsMongo(CurateShortsMongoArgs { - mongo: mongo_opts, - provider_mapping, - out_dir, - key_field, - report_date_field, - shares_short_field, - net_change_field, - pct_float_field, - mapping_source: mapping_source.unwrap_or_else(|| DEFAULT_MAPPING_SOURCE.to_string()), - })); - } - - if mongo.has_any_mongo_option() { - return Err("MongoDB streaming flags require '--from-mongo'".to_string()); - } - - let ceo_shorts = - ceo_shorts.ok_or_else(|| "missing required flag '--ceo-shorts'".to_string())?; - let provider_mapping = - provider_mapping.ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?; - let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; - let shares_short_field = shares_short_field - .ok_or_else(|| "missing required flag '--shares-short-field'".to_string())?; - - let parsed = CurateShortsArgs { - ceo_shorts, - provider_mapping, - out_dir, - key_field: key_field.unwrap_or_else(|| DEFAULT_KEY_FIELD.to_string()), - report_date_field: report_date_field - .unwrap_or_else(|| DEFAULT_REPORT_DATE_FIELD.to_string()), - shares_short_field, - net_change_field, - pct_float_field, - mapping_source: mapping_source.unwrap_or_else(|| DEFAULT_MAPPING_SOURCE.to_string()), - }; - - parsed.field_names().validate().map_err(|e| e.to_string())?; - Ok(CliAction::CurateShorts(parsed)) -} - -fn parse_curate_posts_args(args: &[&str]) -> Result { - let mut ceo_posts: Option = None; - let mut provider_mapping: Option = None; - let mut out_dir: Option = None; - let mut timestamp_unit: Option = None; - let mut key_field: Option = None; - let mut spiel_id_field: Option = None; - let mut timestamp_field: Option = None; - let mut edited_field: Option = None; - let mut bot_field: Option = None; - let mut user_id_field: Option = None; - let mut text_field: Option = None; - let mut mapping_source: Option = None; - - let mut i = 0usize; - while i < args.len() { - let token = args[i]; - if !token.starts_with("--") { - return Err(format!( - "unexpected positional argument '{token}' for curate-posts" - )); - } - - let flag_name = token.split_once('=').map_or(token, |(k, _)| k); - if !matches!( - flag_name, - "--ceo-posts" - | "--provider-mapping" - | "--out" - | "--timestamp-unit" - | "--key-field" - | "--spiel-id-field" - | "--timestamp-field" - | "--edited-field" - | "--bot-field" - | "--user-id-field" - | "--text-field" - | "--mapping-source" - ) { - return Err(format!("unknown flag '{flag_name}' for curate-posts")); - } - - let (flag, value) = if let Some((k, v)) = token.split_once('=') { - i += 1; - (k, v) - } else { - let Some(&v) = args.get(i + 1) else { - return Err(format!("missing value for flag '{token}'")); - }; - if v.starts_with("--") { - return Err(format!("missing value for flag '{token}'")); - } - i += 2; - (token, v) - }; - - match flag { - "--ceo-posts" => set_path(&mut ceo_posts, "--ceo-posts", value)?, - "--provider-mapping" => set_path(&mut provider_mapping, "--provider-mapping", value)?, - "--out" => set_path(&mut out_dir, "--out", value)?, - "--timestamp-unit" => { - if timestamp_unit.is_some() { - return Err("duplicate flag '--timestamp-unit'".to_string()); - } - timestamp_unit = Some(match value { - "seconds" => CeoPostsTimestampUnit::Seconds, - "millis" => CeoPostsTimestampUnit::Millis, - _ => { - return Err(format!( - "invalid --timestamp-unit '{value}' (expected 'seconds' or 'millis')" - )); - } - }); - } - "--key-field" => set_name(&mut key_field, "--key-field", value)?, - "--spiel-id-field" => set_name(&mut spiel_id_field, "--spiel-id-field", value)?, - "--timestamp-field" => set_name(&mut timestamp_field, "--timestamp-field", value)?, - "--edited-field" => set_name(&mut edited_field, "--edited-field", value)?, - "--bot-field" => set_name(&mut bot_field, "--bot-field", value)?, - "--user-id-field" => set_name(&mut user_id_field, "--user-id-field", value)?, - "--text-field" => set_name(&mut text_field, "--text-field", value)?, - "--mapping-source" => set_name(&mut mapping_source, "--mapping-source", value)?, - other => return Err(format!("unknown flag '{other}' for curate-posts")), - } - } - - let ceo_posts = ceo_posts.ok_or_else(|| "missing required flag '--ceo-posts'".to_string())?; - let provider_mapping = - provider_mapping.ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?; - let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; - let timestamp_unit = - timestamp_unit.ok_or_else(|| "missing required flag '--timestamp-unit'".to_string())?; - - let parsed = CuratePostsArgs { - ceo_posts, - provider_mapping, - out_dir, - timestamp_unit, - key_field: key_field.unwrap_or_else(|| DEFAULT_POSTS_KEY_FIELD.to_string()), - spiel_id_field: spiel_id_field.unwrap_or_else(|| DEFAULT_POSTS_SPIEL_ID_FIELD.to_string()), - timestamp_field: timestamp_field - .unwrap_or_else(|| DEFAULT_POSTS_TIMESTAMP_FIELD.to_string()), - edited_field: edited_field.unwrap_or_else(|| DEFAULT_POSTS_EDITED_FIELD.to_string()), - bot_field: bot_field.unwrap_or_else(|| DEFAULT_POSTS_BOT_FIELD.to_string()), - user_id_field: user_id_field.unwrap_or_else(|| DEFAULT_POSTS_USER_ID_FIELD.to_string()), - text_field: text_field.unwrap_or_else(|| DEFAULT_POSTS_TEXT_FIELD.to_string()), - mapping_source: mapping_source.unwrap_or_else(|| DEFAULT_POSTS_MAPPING_SOURCE.to_string()), - }; - - parsed.field_names().validate().map_err(|e| e.to_string())?; - Ok(CliAction::CuratePosts(parsed)) -} - -fn sanitize_single_line(s: &str) -> String { - s.replace('\r', "\\r").replace('\n', "\\n") -} - -fn set_token_list( - slot: &mut Option>, - flag_name: &str, - raw: &str, -) -> Result<(), String> { - if slot.is_some() { - return Err(format!("duplicate flag '{flag_name}'")); - } - if raw.is_empty() { - return Err(format!("empty value for flag '{flag_name}'")); - } - *slot = Some(raw.split(',').map(str::to_string).collect()); - Ok(()) -} - -fn parse_curate_fundamentals_args(args: &[&str]) -> Result { - parse_curate_fundamentals_args_inner(args).map_err(|e| sanitize_single_line(&e)) -} - -fn parse_curate_fundamentals_args_inner(args: &[&str]) -> Result { - let mut qm_financials: Option = None; - let mut qm_filings: Option = None; - let mut provider_mapping: Option = None; - let mut listing_venues: Option = None; - let mut out_dir: Option = None; - let mut currency_field: Option = None; - let mut filings_form_type_field: Option = None; - let mut k: Option = None; - let mut fiscal_period_fixed: Option = None; - let mut quarterly_tokens: Option> = None; - let mut annual_tokens: Option> = None; - let mut financials_key_field: Option = None; - let mut period_end_field: Option = None; - let mut report_date_field: Option = None; - let mut report_period_field: Option = None; - let mut filings_key_field: Option = None; - let mut filings_timefiled_field: Option = None; - let mut mapping_source: Option = None; - let mut revenue_field: Option = None; - let mut net_income_field: Option = None; - let mut operating_cash_flow_field: Option = None; - let mut total_assets_field: Option = None; - let mut total_equity_field: Option = None; - let mut shares_outstanding_field: Option = None; - let mut filings_filing_id_field: Option = None; - let mut filings_url_field: Option = None; - - let mut i = 0usize; - while i < args.len() { - let token = args[i]; - if !token.starts_with("--") { - return Err(format!( - "unexpected positional argument '{token}' for curate-fundamentals" - )); - } - - let flag_name = token.split_once('=').map_or(token, |(flag, _)| flag); - if !matches!( - flag_name, - "--qm-financials" - | "--qm-filings" - | "--provider-mapping" - | "--listing-venues" - | "--out" - | "--currency-field" - | "--filings-form-type-field" - | "--k" - | "--fiscal-period" - | "--quarterly-tokens" - | "--annual-tokens" - | "--financials-key-field" - | "--period-end-field" - | "--report-date-field" - | "--report-period-field" - | "--filings-key-field" - | "--filings-timefiled-field" - | "--mapping-source" - | "--revenue-field" - | "--net-income-field" - | "--operating-cash-flow-field" - | "--total-assets-field" - | "--total-equity-field" - | "--shares-outstanding-field" - | "--filings-filing-id-field" - | "--filings-url-field" - ) { - return Err(format!( - "unknown flag '{flag_name}' for curate-fundamentals" - )); - } - - let (flag, value) = if let Some((flag, v)) = token.split_once('=') { - i += 1; - (flag, v) - } else { - let Some(&v) = args.get(i + 1) else { - return Err(format!("missing value for flag '{token}'")); - }; - if v.starts_with("--") { - return Err(format!("missing value for flag '{token}'")); - } - i += 2; - (token, v) - }; - - match flag { - "--qm-financials" => set_path(&mut qm_financials, "--qm-financials", value)?, - "--qm-filings" => set_path(&mut qm_filings, "--qm-filings", value)?, - "--provider-mapping" => set_path(&mut provider_mapping, "--provider-mapping", value)?, - "--listing-venues" => set_path(&mut listing_venues, "--listing-venues", value)?, - "--out" => set_path(&mut out_dir, "--out", value)?, - "--currency-field" => set_name(&mut currency_field, "--currency-field", value)?, - "--filings-form-type-field" => { - set_name(&mut filings_form_type_field, "--filings-form-type-field", value)?; - } - "--k" => { - if k.is_some() { - return Err("duplicate flag '--k'".to_string()); - } - if value.is_empty() { - return Err("empty value for flag '--k'".to_string()); - } - if !value.bytes().all(|b| b.is_ascii_digit()) { - return Err(format!( - "invalid --k '{value}' (expected a positive integer >= 1)" - )); - } - let parsed = value.parse::().map_err(|_| { - format!("invalid --k '{value}' (expected a positive integer >= 1)") - })?; - if parsed == 0 { - return Err(format!( - "invalid --k '{value}' (expected a positive integer >= 1)" - )); - } - k = Some(parsed); - } - "--fiscal-period" => { - if fiscal_period_fixed.is_some() { - return Err("duplicate flag '--fiscal-period'".to_string()); - } - fiscal_period_fixed = Some(match value { - "quarterly" => FiscalPeriod::Quarterly, - "annual" => FiscalPeriod::Annual, - _ => { - return Err(format!( - "invalid --fiscal-period '{value}' (expected 'quarterly' or 'annual')" - )); - } - }); - } - "--quarterly-tokens" => { - set_token_list(&mut quarterly_tokens, "--quarterly-tokens", value)?; - } - "--annual-tokens" => set_token_list(&mut annual_tokens, "--annual-tokens", value)?, - "--financials-key-field" => { - set_name(&mut financials_key_field, "--financials-key-field", value)?; - } - "--period-end-field" => set_name(&mut period_end_field, "--period-end-field", value)?, - "--report-date-field" => { - set_name(&mut report_date_field, "--report-date-field", value)?; - } - "--report-period-field" => { - set_name(&mut report_period_field, "--report-period-field", value)?; - } - "--filings-key-field" => { - set_name(&mut filings_key_field, "--filings-key-field", value)?; - } - "--filings-timefiled-field" => { - set_name( - &mut filings_timefiled_field, - "--filings-timefiled-field", - value, - )?; - } - "--mapping-source" => set_name(&mut mapping_source, "--mapping-source", value)?, - "--revenue-field" => set_name(&mut revenue_field, "--revenue-field", value)?, - "--net-income-field" => set_name(&mut net_income_field, "--net-income-field", value)?, - "--operating-cash-flow-field" => { - set_name( - &mut operating_cash_flow_field, - "--operating-cash-flow-field", - value, - )?; - } - "--total-assets-field" => { - set_name(&mut total_assets_field, "--total-assets-field", value)?; - } - "--total-equity-field" => { - set_name(&mut total_equity_field, "--total-equity-field", value)?; - } - "--shares-outstanding-field" => { - set_name( - &mut shares_outstanding_field, - "--shares-outstanding-field", - value, - )?; - } - "--filings-filing-id-field" => { - set_name( - &mut filings_filing_id_field, - "--filings-filing-id-field", - value, - )?; - } - "--filings-url-field" => { - set_name(&mut filings_url_field, "--filings-url-field", value)?; - } - other => return Err(format!("unknown flag '{other}' for curate-fundamentals")), - } - } - - let qm_financials = - qm_financials.ok_or_else(|| "missing required flag '--qm-financials'".to_string())?; - let qm_filings = - qm_filings.ok_or_else(|| "missing required flag '--qm-filings'".to_string())?; - let provider_mapping = - provider_mapping.ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?; - let listing_venues = - listing_venues.ok_or_else(|| "missing required flag '--listing-venues'".to_string())?; - let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; - let currency_field = - currency_field.ok_or_else(|| "missing required flag '--currency-field'".to_string())?; - let filings_form_type_field = filings_form_type_field - .ok_or_else(|| "missing required flag '--filings-form-type-field'".to_string())?; - let k = k.ok_or_else(|| "missing required flag '--k'".to_string())?; - - let fiscal_period = match (fiscal_period_fixed, quarterly_tokens, annual_tokens) { - (Some(_), Some(_), _) | (Some(_), _, Some(_)) => { - return Err( - "cannot combine '--fiscal-period' with '--quarterly-tokens' or '--annual-tokens'" - .to_string(), - ); - } - (Some(fixed), None, None) => CurateFundamentalsFiscalPeriod::Fixed(fixed), - (None, Some(quarterly), Some(annual)) => { - CurateFundamentalsFiscalPeriod::ByTokens { quarterly, annual } - } - (None, Some(quarterly), None) => CurateFundamentalsFiscalPeriod::ByTokens { - quarterly, - annual: Vec::new(), - }, - (None, None, Some(annual)) => CurateFundamentalsFiscalPeriod::ByTokens { - quarterly: Vec::new(), - annual, - }, - (None, None, None) => { - return Err( - "missing required fiscal-period mode: pass either '--fiscal-period ' or '--quarterly-tokens' / '--annual-tokens'" - .to_string(), - ); - } - }; - - let mut parsed = CurateFundamentalsArgs::with_verified_defaults( - qm_financials, - qm_filings, - provider_mapping, - listing_venues, - out_dir, - currency_field, - revenue_field, - net_income_field, - operating_cash_flow_field, - total_assets_field, - total_equity_field, - shares_outstanding_field, - fiscal_period, - filings_form_type_field, - k, - ); - if let Some(v) = financials_key_field { - parsed.financials_key_field = v; - } - if let Some(v) = period_end_field { - parsed.financials_period_end_field = v; - } - if let Some(v) = report_date_field { - parsed.financials_report_date_field = v; - } - if let Some(v) = report_period_field { - parsed.financials_report_period_field = v; - } - if let Some(v) = filings_key_field { - parsed.filings_key_field = v; - } - if let Some(v) = filings_timefiled_field { - parsed.filings_timefiled_field = v; - } - if let Some(v) = filings_filing_id_field { - parsed.filings_filing_id_field = Some(v); - } - if let Some(v) = filings_url_field { - parsed.filings_url_field = Some(v); - } - if let Some(v) = mapping_source { - parsed.mapping_source = v; - } - - parsed - .financials_field_names() - .validate() - .map_err(|e| e.to_string())?; - parsed - .filings_field_names() - .validate() - .map_err(|e| e.to_string())?; - parsed - .fiscal_period - .with_borrowed(|period| period.validate()) - .map_err(|e| e.to_string())?; - - Ok(CliAction::CurateFundamentals(parsed)) -} - -fn parse_curate_macro_args(args: &[&str]) -> Result { - parse_curate_macro_args_inner(args).map_err(|e| sanitize_single_line(&e)) -} - -fn parse_curate_macro_args_inner(args: &[&str]) -> Result { - let mut te_data: Option = None; - let mut series_map: Option = None; - let mut out_dir: Option = None; - - let mut i = 0usize; - while i < args.len() { - let token = args[i]; - if !token.starts_with("--") { - return Err(format!( - "unexpected positional argument '{token}' for curate-macro" - )); - } - - let flag_name = token.split_once('=').map_or(token, |(flag, _)| flag); - if !matches!(flag_name, "--te-data" | "--series-map" | "--out") { - return Err(format!("unknown flag '{flag_name}' for curate-macro")); - } - - let (flag, value) = if let Some((flag, v)) = token.split_once('=') { - i += 1; - (flag, v) - } else { - let Some(&v) = args.get(i + 1) else { - return Err(format!("missing value for flag '{token}'")); - }; - if v.starts_with("--") { - return Err(format!("missing value for flag '{token}'")); - } - i += 2; - (token, v) - }; - - match flag { - "--te-data" => set_path(&mut te_data, "--te-data", value)?, - "--series-map" => set_path(&mut series_map, "--series-map", value)?, - "--out" => set_path(&mut out_dir, "--out", value)?, - other => return Err(format!("unknown flag '{other}' for curate-macro")), - } - } - - let te_data = te_data.ok_or_else(|| "missing required flag '--te-data'".to_string())?; - let series_map = - series_map.ok_or_else(|| "missing required flag '--series-map'".to_string())?; - let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; - - Ok(CliAction::CurateMacro(CurateMacroArgs { - te_data, - series_map, - out_dir, - })) -} - -fn parse_curate_events_args(args: &[&str]) -> Result { - let mut mongo = MongoFlagState::default(); - let mut qm_filings: Option = None; - let mut qm_earnings: Option = None; - let mut provider_mapping: Option = None; - let mut out_dir: Option = None; - let mut filings_key_field: Option = None; - let mut filings_timefiled_field: Option = None; - let mut filings_form_type_field: Option = None; - let mut filings_filing_id_field: Option = None; - let mut filings_url_field: Option = None; - let mut earnings_key_field: Option = None; - let mut earnings_report_date_field: Option = None; - let mut earnings_announce_time_field: Option = None; - let mut earnings_fiscal_period_end_field: Option = None; - let mut earnings_actual_eps_field: Option = None; - let mut earnings_revenue_field: Option = None; - let mut mapping_source: Option = None; - - let mut i = 0usize; - while i < args.len() { - let token = args[i]; - if !token.starts_with("--") { - return Err(format!( - "unexpected positional argument '{token}' for curate-events" - )); - } - - if token == "--from-mongo" { - if mongo.from_mongo { - return Err("duplicate flag '--from-mongo'".to_string()); - } - mongo.from_mongo = true; - i += 1; - continue; - } - - let (flag, value) = if let Some((k, v)) = token.split_once('=') { - i += 1; - (k, v) - } else { - let Some(&v) = args.get(i + 1) else { - return Err(format!("missing value for flag '{token}'")); - }; - if v.starts_with("--") { - return Err(format!("missing value for flag '{token}'")); - } - i += 2; - (token, v) - }; - - if mongo.try_parse_value_flag(flag, value, true)? { - continue; - } - - let set_path = |slot: &mut Option, flag_name: &str, raw: &str| -> Result<(), String> { - if slot.is_some() { - return Err(format!("duplicate flag '{flag_name}'")); - } - if raw.is_empty() { - return Err(format!("empty value for flag '{flag_name}'")); - } - *slot = Some(PathBuf::from(raw)); - Ok(()) - }; - - let set_name = |slot: &mut Option, flag_name: &str, raw: &str| -> Result<(), String> { - if slot.is_some() { - return Err(format!("duplicate flag '{flag_name}'")); - } - if raw.trim().is_empty() { - return Err(format!("empty value for flag '{flag_name}'")); - } - *slot = Some(raw.to_string()); - Ok(()) - }; - - match flag { - "--qm-filings" => set_path(&mut qm_filings, "--qm-filings", value)?, - "--qm-earnings" => set_path(&mut qm_earnings, "--qm-earnings", value)?, - "--provider-mapping" => set_path(&mut provider_mapping, "--provider-mapping", value)?, - "--out" => set_path(&mut out_dir, "--out", value)?, - "--filings-key-field" => { - set_name(&mut filings_key_field, "--filings-key-field", value)?; - } - "--filings-timefiled-field" => { - set_name( - &mut filings_timefiled_field, - "--filings-timefiled-field", - value, - )?; - } - "--filings-form-type-field" => { - set_name( - &mut filings_form_type_field, - "--filings-form-type-field", - value, - )?; - } - "--filings-filing-id-field" => { - set_name( - &mut filings_filing_id_field, - "--filings-filing-id-field", - value, - )?; - } - "--filings-url-field" => { - set_name(&mut filings_url_field, "--filings-url-field", value)?; - } - "--earnings-key-field" => { - set_name(&mut earnings_key_field, "--earnings-key-field", value)?; - } - "--earnings-report-date-field" => { - set_name( - &mut earnings_report_date_field, - "--earnings-report-date-field", - value, - )?; - } - "--earnings-announce-time-field" => { - set_name( - &mut earnings_announce_time_field, - "--earnings-announce-time-field", - value, - )?; - } - "--earnings-fiscal-period-end-field" => { - set_name( - &mut earnings_fiscal_period_end_field, - "--earnings-fiscal-period-end-field", - value, - )?; - } - "--earnings-actual-eps-field" => { - set_name( - &mut earnings_actual_eps_field, - "--earnings-actual-eps-field", - value, - )?; - } - "--earnings-revenue-field" => { - set_name( - &mut earnings_revenue_field, - "--earnings-revenue-field", - value, - )?; - } - "--mapping-source" => set_name(&mut mapping_source, "--mapping-source", value)?, - other => return Err(format!("unknown flag '{other}' for curate-events")), - } - } - - if mongo.from_mongo { - if qm_filings.is_some() || qm_earnings.is_some() { - return Err( - "cannot combine '--from-mongo' with '--qm-filings' or '--qm-earnings'".to_string(), - ); - } - let mongo_opts = mongo.build_options()?; - let provider_mapping = provider_mapping - .ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?; - let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; - let filings_form_type_field = filings_form_type_field - .ok_or_else(|| "missing required flag '--filings-form-type-field'".to_string())?; - let filings_key_field = - filings_key_field.unwrap_or_else(|| DEFAULT_FILINGS_KEY_FIELD.to_string()); - let filings_timefiled_field = - filings_timefiled_field.unwrap_or_else(|| DEFAULT_FILINGS_TIMEFILED_FIELD.to_string()); - let earnings_key_field = - earnings_key_field.unwrap_or_else(|| DEFAULT_EARNINGS_KEY_FIELD.to_string()); - let earnings_report_date_field = earnings_report_date_field - .unwrap_or_else(|| DEFAULT_EARNINGS_REPORT_DATE_FIELD.to_string()); - let earnings_announce_time_field = earnings_announce_time_field - .unwrap_or_else(|| DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD.to_string()); - let mapping_source = - mapping_source.unwrap_or_else(|| DEFAULT_EVENTS_MAPPING_SOURCE.to_string()); - - let check = CurateEventsArgs { - qm_filings: PathBuf::from("mongodb://qmFilings"), - qm_earnings: PathBuf::from("mongodb://qmEarnings"), - provider_mapping: provider_mapping.clone(), - out_dir: out_dir.clone(), - filings_key_field: filings_key_field.clone(), - filings_timefiled_field: filings_timefiled_field.clone(), - filings_form_type_field: filings_form_type_field.clone(), - filings_filing_id_field: filings_filing_id_field.clone(), - filings_url_field: filings_url_field.clone(), - earnings_key_field: earnings_key_field.clone(), - earnings_report_date_field: earnings_report_date_field.clone(), - earnings_announce_time_field: earnings_announce_time_field.clone(), - earnings_fiscal_period_end_field: earnings_fiscal_period_end_field.clone(), - earnings_actual_eps_field: earnings_actual_eps_field.clone(), - earnings_revenue_field: earnings_revenue_field.clone(), - mapping_source: mapping_source.clone(), - }; - check - .filings_field_names() - .validate() - .map_err(|e| e.to_string())?; - check - .earnings_field_names() - .validate() - .map_err(|e| e.to_string())?; - - return Ok(CliAction::CurateEventsMongo(CurateEventsMongoArgs { - mongo: mongo_opts, - provider_mapping, - out_dir, - filings_key_field, - filings_timefiled_field, - filings_form_type_field, - filings_filing_id_field, - filings_url_field, - earnings_key_field, - earnings_report_date_field, - earnings_announce_time_field, - earnings_fiscal_period_end_field, - earnings_actual_eps_field, - earnings_revenue_field, - mapping_source, - })); - } - - if mongo.has_any_mongo_option() { - return Err("MongoDB streaming flags require '--from-mongo'".to_string()); - } - - let qm_filings = - qm_filings.ok_or_else(|| "missing required flag '--qm-filings'".to_string())?; - let qm_earnings = - qm_earnings.ok_or_else(|| "missing required flag '--qm-earnings'".to_string())?; - let provider_mapping = - provider_mapping.ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?; - let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; - let filings_form_type_field = filings_form_type_field - .ok_or_else(|| "missing required flag '--filings-form-type-field'".to_string())?; - - let parsed = CurateEventsArgs { - qm_filings, - qm_earnings, - provider_mapping, - out_dir, - filings_key_field: filings_key_field - .unwrap_or_else(|| DEFAULT_FILINGS_KEY_FIELD.to_string()), - filings_timefiled_field: filings_timefiled_field - .unwrap_or_else(|| DEFAULT_FILINGS_TIMEFILED_FIELD.to_string()), - filings_form_type_field, - filings_filing_id_field, - filings_url_field, - earnings_key_field: earnings_key_field - .unwrap_or_else(|| DEFAULT_EARNINGS_KEY_FIELD.to_string()), - earnings_report_date_field: earnings_report_date_field - .unwrap_or_else(|| DEFAULT_EARNINGS_REPORT_DATE_FIELD.to_string()), - earnings_announce_time_field: earnings_announce_time_field - .unwrap_or_else(|| DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD.to_string()), - earnings_fiscal_period_end_field, - earnings_actual_eps_field, - earnings_revenue_field, - mapping_source: mapping_source - .unwrap_or_else(|| DEFAULT_EVENTS_MAPPING_SOURCE.to_string()), - }; - - parsed - .filings_field_names() - .validate() - .map_err(|e| e.to_string())?; - parsed - .earnings_field_names() - .validate() - .map_err(|e| e.to_string())?; - Ok(CliAction::CurateEvents(parsed)) -} - -fn parse_curate_bars_1m_args(args: &[&str]) -> Result { - let mut intraday_path: Option = None; - let mut splits_path: Option = None; - let mut provider_mapping_path: Option = None; - let mut out_dir: Option = None; - let mut shard_count: Option = None; - let mut known_at_micros: Option = None; - let mut mapping_source: Option = None; - - let mut i = 0usize; - while i < args.len() { - let token = args[i]; - if !token.starts_with("--") { - return Err(format!( - "unexpected positional argument '{token}' for curate-bars-1m" - )); - } - - let flag_name = token.split_once('=').map_or(token, |(k, _)| k); - if matches!( - flag_name, - "--from-mongo" - | "--mongo-uri" - | "--mongo-uri-env" - | "--batch-size" - | "--limit" - | "--date-gte" - | "--date-lt" - | "--with-qm-prices" - ) { - return Err(format!( - "MongoDB streaming flag '{flag_name}' is not supported by curate-bars-1m (file mode only)" - )); - } - - let (flag, value) = if let Some((k, v)) = token.split_once('=') { - i += 1; - (k, v) - } else { - let Some(&v) = args.get(i + 1) else { - return Err(format!("missing value for flag '{token}'")); - }; - if v.starts_with("--") { - return Err(format!("missing value for flag '{token}'")); - } - i += 2; - (token, v) - }; - - let set_path = |slot: &mut Option, flag_name: &str, raw: &str| -> Result<(), String> { - if slot.is_some() { - return Err(format!("duplicate flag '{flag_name}'")); - } - if raw.is_empty() { - return Err(format!("empty value for flag '{flag_name}'")); - } - *slot = Some(PathBuf::from(raw)); - Ok(()) - }; - - let set_name = |slot: &mut Option, flag_name: &str, raw: &str| -> Result<(), String> { - if slot.is_some() { - return Err(format!("duplicate flag '{flag_name}'")); - } - if raw.trim().is_empty() { - return Err(format!("empty value for flag '{flag_name}'")); - } - *slot = Some(raw.to_string()); - Ok(()) - }; - - match flag { - "--eod-intraday" => set_path(&mut intraday_path, "--eod-intraday", value)?, - "--qm-splits" => set_path(&mut splits_path, "--qm-splits", value)?, - "--provider-mapping" => { - set_path(&mut provider_mapping_path, "--provider-mapping", value)?; - } - "--out" => set_path(&mut out_dir, "--out", value)?, - "--shards" => { - if shard_count.is_some() { - return Err("duplicate flag '--shards'".to_string()); - } - if value.is_empty() { - return Err("empty value for flag '--shards'".to_string()); - } - if !value.bytes().all(|b| b.is_ascii_digit()) { - return Err(format!( - "invalid --shards '{value}' (expected a positive integer >= 1)" - )); - } - let parsed = value.parse::().map_err(|_| { - format!("invalid --shards '{value}' (expected a positive integer >= 1)") - })?; - if parsed == 0 { - return Err(format!( - "invalid --shards '{value}' (expected a positive integer >= 1)" - )); - } - shard_count = Some(parsed); - } - "--known-at-micros" => { - if known_at_micros.is_some() { - return Err("duplicate flag '--known-at-micros'".to_string()); - } - if value.is_empty() { - return Err("empty value for flag '--known-at-micros'".to_string()); - } - if !value.bytes().all(|b| b.is_ascii_digit()) { - return Err(format!( - "invalid --known-at-micros '{value}' (expected a positive 64-bit integer >= 1)" - )); - } - let parsed = value.parse::().map_err(|_| { - format!( - "invalid --known-at-micros '{value}' (expected a positive 64-bit integer >= 1)" - ) - })?; - if parsed <= 0 { - return Err(format!( - "invalid --known-at-micros '{value}' (expected a positive 64-bit integer >= 1)" - )); - } - known_at_micros = Some(parsed); - } - "--mapping-source" => set_name(&mut mapping_source, "--mapping-source", value)?, - other => return Err(format!("unknown flag '{other}' for curate-bars-1m")), - } - } - - let intraday_path = - intraday_path.ok_or_else(|| "missing required flag '--eod-intraday'".to_string())?; - let splits_path = - splits_path.ok_or_else(|| "missing required flag '--qm-splits'".to_string())?; - let provider_mapping_path = provider_mapping_path - .ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?; - let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; - let shard_count = - shard_count.ok_or_else(|| "missing required flag '--shards'".to_string())?; - let known_at_micros = - known_at_micros.ok_or_else(|| "missing required flag '--known-at-micros'".to_string())?; - - Ok(CliAction::CurateBars1m(CurateBars1mArgs { - intraday_path, - splits_path, - provider_mapping_path, - out_dir, - mapping_source: mapping_source - .unwrap_or_else(|| DEFAULT_BARS_1M_MAPPING_SOURCE.to_string()), - shard_count, - known_at_micros, - stream_options: BsonStreamOptions::default(), - ilp_options: IlpWriterOptions::default(), - })) -} - -fn parse_curate_qm_bars_1m_args(args: &[&str]) -> Result { - parse_curate_qm_bars_1m_args_inner(args).map_err(|e| sanitize_single_line(&e)) -} - -fn parse_curate_qm_bars_1m_args_inner(args: &[&str]) -> Result { - let mut intraday_path: Option = None; - let mut provider_mapping_path: Option = None; - let mut out_dir: Option = None; - let mut shard_count: Option = None; - let mut known_at_micros: Option = None; - let mut mapping_source: Option = None; - - let mut i = 0usize; - while i < args.len() { - let token = args[i]; - if !token.starts_with("--") { - return Err(format!( - "unexpected positional argument '{token}' for curate-qm-bars-1m" - )); - } - - let flag_name = token.split_once('=').map_or(token, |(k, _)| k); - if matches!( - flag_name, - "--from-mongo" - | "--mongo-uri" - | "--mongo-uri-env" - | "--batch-size" - | "--limit" - | "--date-gte" - | "--date-lt" - | "--with-qm-prices" - ) { - return Err(format!( - "MongoDB streaming flag '{flag_name}' is not supported by curate-qm-bars-1m (file mode only)" - )); - } - - if !matches!( - flag_name, - "--qm-intraday" - | "--provider-mapping" - | "--out" - | "--shards" - | "--known-at-micros" - | "--mapping-source" - ) { - return Err(format!("unknown flag '{flag_name}' for curate-qm-bars-1m")); - } - - let (flag, value) = if let Some((k, v)) = token.split_once('=') { - i += 1; - (k, v) - } else { - let Some(&v) = args.get(i + 1) else { - return Err(format!("missing value for flag '{token}'")); - }; - if v.starts_with("--") { - return Err(format!("missing value for flag '{token}'")); - } - i += 2; - (token, v) - }; - - let set_path = |slot: &mut Option, flag_name: &str, raw: &str| -> Result<(), String> { - if slot.is_some() { - return Err(format!("duplicate flag '{flag_name}'")); - } - if raw.is_empty() { - return Err(format!("empty value for flag '{flag_name}'")); - } - *slot = Some(PathBuf::from(raw)); - Ok(()) - }; - - let set_name = |slot: &mut Option, flag_name: &str, raw: &str| -> Result<(), String> { - if slot.is_some() { - return Err(format!("duplicate flag '{flag_name}'")); - } - if raw.trim().is_empty() { - return Err(format!("empty value for flag '{flag_name}'")); - } - *slot = Some(raw.to_string()); - Ok(()) - }; - - match flag { - "--qm-intraday" => set_path(&mut intraday_path, "--qm-intraday", value)?, - "--provider-mapping" => { - set_path(&mut provider_mapping_path, "--provider-mapping", value)?; - } - "--out" => set_path(&mut out_dir, "--out", value)?, - "--shards" => { - if shard_count.is_some() { - return Err("duplicate flag '--shards'".to_string()); - } - if value.is_empty() { - return Err("empty value for flag '--shards'".to_string()); - } - if !value.bytes().all(|b| b.is_ascii_digit()) { - return Err(format!( - "invalid --shards '{value}' (expected a positive integer >= 1)" - )); - } - let parsed = value.parse::().map_err(|_| { - format!("invalid --shards '{value}' (expected a positive integer >= 1)") - })?; - if parsed == 0 { - return Err(format!( - "invalid --shards '{value}' (expected a positive integer >= 1)" - )); - } - shard_count = Some(parsed); - } - "--known-at-micros" => { - if known_at_micros.is_some() { - return Err("duplicate flag '--known-at-micros'".to_string()); - } - if value.is_empty() { - return Err("empty value for flag '--known-at-micros'".to_string()); - } - if !value.bytes().all(|b| b.is_ascii_digit()) { - return Err(format!( - "invalid --known-at-micros '{value}' (expected a positive 64-bit integer >= 1)" - )); - } - let parsed = value.parse::().map_err(|_| { - format!( - "invalid --known-at-micros '{value}' (expected a positive 64-bit integer >= 1)" - ) - })?; - if parsed <= 0 { - return Err(format!( - "invalid --known-at-micros '{value}' (expected a positive 64-bit integer >= 1)" - )); - } - known_at_micros = Some(parsed); - } - "--mapping-source" => set_name(&mut mapping_source, "--mapping-source", value)?, - other => return Err(format!("unknown flag '{other}' for curate-qm-bars-1m")), - } - } - - let intraday_path = - intraday_path.ok_or_else(|| "missing required flag '--qm-intraday'".to_string())?; - let provider_mapping_path = provider_mapping_path - .ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?; - let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; - let shard_count = - shard_count.ok_or_else(|| "missing required flag '--shards'".to_string())?; - let known_at_micros = - known_at_micros.ok_or_else(|| "missing required flag '--known-at-micros'".to_string())?; - - Ok(CliAction::CurateQmBars1m(CurateQmBars1mArgs { - intraday_path, - provider_mapping_path, - out_dir, - mapping_source: mapping_source - .unwrap_or_else(|| DEFAULT_QM_BARS_1M_MAPPING_SOURCE.to_string()), - shard_count, - known_at_micros, - stream_options: BsonStreamOptions::default(), - ilp_options: IlpWriterOptions::default(), - })) -} - -fn parse_curate_fx_1m_args(args: &[&str]) -> Result { - let mut intraday_path: Option = None; - let mut out_dir: Option = None; - let mut shard_count: Option = None; - - let mut i = 0usize; - while i < args.len() { - let token = args[i]; - if !token.starts_with("--") { - return Err(format!( - "unexpected positional argument '{token}' for curate-fx-1m" - )); - } - - let flag_name = token.split_once('=').map_or(token, |(k, _)| k); - if matches!( - flag_name, - "--from-mongo" - | "--mongo-uri" - | "--mongo-uri-env" - | "--batch-size" - | "--limit" - | "--date-gte" - | "--date-lt" - | "--with-qm-prices" - ) { - return Err(format!( - "MongoDB streaming flag '{flag_name}' is not supported by curate-fx-1m (file mode only)" - )); - } - - let (flag, value) = if let Some((k, v)) = token.split_once('=') { - i += 1; - (k, v) - } else { - let Some(&v) = args.get(i + 1) else { - return Err(format!("missing value for flag '{token}'")); - }; - if v.starts_with("--") { - return Err(format!("missing value for flag '{token}'")); - } - i += 2; - (token, v) - }; - - let set_path = |slot: &mut Option, flag_name: &str, raw: &str| -> Result<(), String> { - if slot.is_some() { - return Err(format!("duplicate flag '{flag_name}'")); - } - if raw.is_empty() { - return Err(format!("empty value for flag '{flag_name}'")); - } - *slot = Some(PathBuf::from(raw)); - Ok(()) - }; - - match flag { - "--eod-intraday" => set_path(&mut intraday_path, "--eod-intraday", value)?, - "--out" => set_path(&mut out_dir, "--out", value)?, - "--shards" => { - if shard_count.is_some() { - return Err("duplicate flag '--shards'".to_string()); - } - if value.is_empty() { - return Err("empty value for flag '--shards'".to_string()); - } - if !value.bytes().all(|b| b.is_ascii_digit()) { - return Err(format!( - "invalid --shards '{value}' (expected a positive integer >= 1)" - )); - } - let parsed = value.parse::().map_err(|_| { - format!("invalid --shards '{value}' (expected a positive integer >= 1)") - })?; - if parsed == 0 { - return Err(format!( - "invalid --shards '{value}' (expected a positive integer >= 1)" - )); - } - shard_count = Some(parsed); - } - other => return Err(format!("unknown flag '{other}' for curate-fx-1m")), - } - } - - let intraday_path = - intraday_path.ok_or_else(|| "missing required flag '--eod-intraday'".to_string())?; - let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; - let shard_count = - shard_count.ok_or_else(|| "missing required flag '--shards'".to_string())?; - - Ok(CliAction::CurateFx1m(CurateFx1mArgs { - intraday_path, - out_dir, - shard_count, - stream_options: BsonStreamOptions::default(), - ilp_options: IlpWriterOptions::default(), - })) -} - -const ALLOWED_SEND_ILP_PREFIXES: [&str; 3] = ["bars_1m", "bars_1m_qm", "fx_1m"]; - -fn parse_send_ilp_args(args: &[&str]) -> Result { - let mut dir: Option = None; - let mut prefix: Option = None; - let mut addr: Option = None; - - let mut i = 0usize; - while i < args.len() { - let token = args[i]; - if !token.starts_with("--") { - return Err(format!( - "unexpected positional argument '{token}' for send-ilp" - )); - } - - let (flag, value) = if let Some((k, v)) = token.split_once('=') { - i += 1; - (k, v) - } else { - let Some(&v) = args.get(i + 1) else { - return Err(format!("missing value for flag '{token}'")); - }; - if v.starts_with("--") { - return Err(format!("missing value for flag '{token}'")); - } - i += 2; - (token, v) - }; - - match flag { - "--dir" => { - if dir.is_some() { - return Err("duplicate flag '--dir'".to_string()); - } - if value.is_empty() { - return Err("empty value for flag '--dir'".to_string()); - } - dir = Some(PathBuf::from(value)); - } - "--prefix" => { - if prefix.is_some() { - return Err("duplicate flag '--prefix'".to_string()); - } - if value.is_empty() { - return Err("empty value for flag '--prefix'".to_string()); - } - if !ALLOWED_SEND_ILP_PREFIXES.contains(&value) { - return Err(format!( - "unsupported --prefix '{value}' for send-ilp (expected one of: bars_1m, bars_1m_qm, fx_1m)" - )); - } - prefix = Some(value.to_string()); - } - "--addr" => { - if addr.is_some() { - return Err("duplicate flag '--addr'".to_string()); - } - if value.trim().is_empty() { - return Err("empty value for flag '--addr'".to_string()); - } - addr = Some(value.to_string()); - } - other => return Err(format!("unknown flag '{other}' for send-ilp")), - } - } - - let dir = dir.ok_or_else(|| "missing required flag '--dir'".to_string())?; - let prefix = prefix.ok_or_else(|| "missing required flag '--prefix'".to_string())?; - let addr = addr.ok_or_else(|| "missing required flag '--addr'".to_string())?; - - Ok(CliAction::SendIlp(SendIlpArgs { dir, prefix, addr })) -} - /// Parses CLI arguments (excluding `argv[0]`) into a [`CliAction`]. pub fn parse_args(args: &[String]) -> Result { let slices: Vec<&str> = args.iter().map(String::as_str).collect(); @@ -2470,19 +107,6 @@ pub fn parse_args(args: &[String]) -> Result { [flag @ ("--help" | "-h" | "--version" | "-V"), extra, ..] => { Err(format!("unexpected argument '{extra}' after '{flag}'")) } - ["curate-bars-1d", rest @ ..] => parse_curate_bars_1d_args(rest), - ["curate-adj-factors", rest @ ..] => parse_curate_adj_factors_args(rest), - ["curate-corporate-actions", rest @ ..] => parse_curate_corporate_actions_args(rest), - ["curate-fx-1d", rest @ ..] => parse_curate_fx_1d_args(rest), - ["curate-shorts", rest @ ..] => parse_curate_shorts_args(rest), - ["curate-events", rest @ ..] => parse_curate_events_args(rest), - ["curate-bars-1m", rest @ ..] => parse_curate_bars_1m_args(rest), - ["curate-qm-bars-1m", rest @ ..] => parse_curate_qm_bars_1m_args(rest), - ["curate-fx-1m", rest @ ..] => parse_curate_fx_1m_args(rest), - ["curate-posts", rest @ ..] => parse_curate_posts_args(rest), - ["curate-fundamentals", rest @ ..] => parse_curate_fundamentals_args(rest), - ["curate-macro", rest @ ..] => parse_curate_macro_args(rest), - ["send-ilp", rest @ ..] => parse_send_ilp_args(rest), ["bench-split"] => Ok(CliAction::BenchSplit(DEFAULT_BENCH_ROWS)), ["bench-split", raw] => match raw.parse::() { Ok(n) if n > 0 => Ok(CliAction::BenchSplit(n)), @@ -2519,22 +143,6 @@ pub fn parse_args(args: &[String]) -> Result { )), }, ["bench-bars", _, ..] => Err("too many arguments for bench-bars".to_string()), - ["bench-bars-1m"] => Ok(CliAction::BenchBars1m(DEFAULT_BARS_1M_BENCH_ROWS)), - ["bench-bars-1m", raw] => match raw.parse::() { - Ok(n) if n > 0 => Ok(CliAction::BenchBars1m(n)), - _ => Err(format!( - "invalid row count '{raw}' (expected a positive integer)" - )), - }, - ["bench-bars-1m", _, ..] => Err("too many arguments for bench-bars-1m".to_string()), - ["bench-ilp-bars-1m"] => Ok(CliAction::BenchIlpBars1m(DEFAULT_ILP_BARS_1M_BENCH_ROWS)), - ["bench-ilp-bars-1m", raw] => match raw.parse::() { - Ok(n) if n > 0 => Ok(CliAction::BenchIlpBars1m(n)), - _ => Err(format!( - "invalid row count '{raw}' (expected a positive integer)" - )), - }, - ["bench-ilp-bars-1m", _, ..] => Err("too many arguments for bench-ilp-bars-1m".to_string()), ["bench-fx"] => Ok(CliAction::BenchFx(DEFAULT_FX_BENCH_ROWS)), ["bench-fx", raw] => match raw.parse::() { Ok(n) if n > 0 => Ok(CliAction::BenchFx(n)), @@ -2559,18 +167,6 @@ pub fn parse_args(args: &[String]) -> Result { )), }, ["bench-events", _, ..] => Err("too many arguments for bench-events".to_string()), - ["bench-fundamentals"] => Ok(CliAction::BenchFundamentals( - DEFAULT_FUNDAMENTALS_BENCH_ROWS, - )), - ["bench-fundamentals", raw] => match raw.parse::() { - Ok(n) if n > 0 => Ok(CliAction::BenchFundamentals(n)), - _ => Err(format!( - "invalid row count '{raw}' (expected a positive integer)" - )), - }, - ["bench-fundamentals", _, ..] => { - Err("too many arguments for bench-fundamentals".to_string()) - } ["bench-provider-mapping"] => Ok(CliAction::BenchProviderMapping( DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS, )), @@ -2663,38 +259,6 @@ pub fn parse_args(args: &[String]) -> Result { ["bench-bson-eod-prices", _, ..] => { Err("too many arguments for bench-bson-eod-prices".to_string()) } - ["bench-bson-qm-actions"] => Ok(CliAction::BenchBsonQmActions( - DEFAULT_BSON_QM_ACTIONS_BENCH_ROWS, - )), - ["bench-bson-qm-actions", raw] => match raw.parse::() { - Ok(n) if n > 0 => Ok(CliAction::BenchBsonQmActions(n)), - _ => Err(format!( - "invalid row count '{raw}' (expected a positive integer)" - )), - }, - ["bench-bson-qm-actions", _, ..] => { - Err("too many arguments for bench-bson-qm-actions".to_string()) - } - ["bench-bson-stream"] => Ok(CliAction::BenchBsonStream(DEFAULT_BSON_STREAM_BENCH_ROWS)), - ["bench-bson-stream", raw] => match raw.parse::() { - Ok(n) if n > 0 => Ok(CliAction::BenchBsonStream(n)), - _ => Err(format!( - "invalid row count '{raw}' (expected a positive integer)" - )), - }, - ["bench-bson-stream", _, ..] => { - Err("too many arguments for bench-bson-stream".to_string()) - } - ["bench-mongo-stream"] => Ok(CliAction::BenchMongoStream(DEFAULT_MONGO_STREAM_BENCH_ROWS)), - ["bench-mongo-stream", raw] => match raw.parse::() { - Ok(n) if n > 0 => Ok(CliAction::BenchMongoStream(n)), - _ => Err(format!( - "invalid row count '{raw}' (expected a positive integer)" - )), - }, - ["bench-mongo-stream", _, ..] => { - Err("too many arguments for bench-mongo-stream".to_string()) - } ["bench-curate-bars"] => Ok(CliAction::BenchCurateBars(DEFAULT_CURATE_BARS_BENCH_ROWS)), ["bench-curate-bars", raw] => match raw.parse::() { Ok(n) if n > 0 => Ok(CliAction::BenchCurateBars(n)), @@ -2705,18 +269,6 @@ pub fn parse_args(args: &[String]) -> Result { ["bench-curate-bars", _, ..] => { Err("too many arguments for bench-curate-bars".to_string()) } - ["bench-curate-bars-cmd"] => Ok(CliAction::BenchCurateBarsCmd( - DEFAULT_CURATE_BARS_CMD_BENCH_ROWS, - )), - ["bench-curate-bars-cmd", raw] => match raw.parse::() { - Ok(n) if n > 0 => Ok(CliAction::BenchCurateBarsCmd(n)), - _ => Err(format!( - "invalid row count '{raw}' (expected a positive integer)" - )), - }, - ["bench-curate-bars-cmd", _, ..] => { - Err("too many arguments for bench-curate-bars-cmd".to_string()) - } ["bench-curate-shorts"] => { Ok(CliAction::BenchCurateShorts(DEFAULT_CURATE_SHORTS_BENCH_ROWS)) } @@ -2729,18 +281,6 @@ pub fn parse_args(args: &[String]) -> Result { ["bench-curate-shorts", _, ..] => { Err("too many arguments for bench-curate-shorts".to_string()) } - ["bench-curate-shorts-command"] => Ok(CliAction::BenchCurateShortsCommand( - DEFAULT_CURATE_SHORTS_COMMAND_BENCH_ROWS, - )), - ["bench-curate-shorts-command", raw] => match raw.parse::() { - Ok(n) if n > 0 => Ok(CliAction::BenchCurateShortsCommand(n)), - _ => Err(format!( - "invalid row count '{raw}' (expected a positive integer)" - )), - }, - ["bench-curate-shorts-command", _, ..] => { - Err("too many arguments for bench-curate-shorts-command".to_string()) - } ["bench-curate-events"] => { Ok(CliAction::BenchCurateEvents(DEFAULT_CURATE_EVENTS_BENCH_ROWS)) } @@ -2753,18 +293,6 @@ pub fn parse_args(args: &[String]) -> Result { ["bench-curate-events", _, ..] => { Err("too many arguments for bench-curate-events".to_string()) } - ["bench-curate-events-cmd"] => Ok(CliAction::BenchCurateEventsCmd( - DEFAULT_CURATE_EVENTS_CMD_BENCH_ROWS, - )), - ["bench-curate-events-cmd", raw] => match raw.parse::() { - Ok(n) if n > 0 => Ok(CliAction::BenchCurateEventsCmd(n)), - _ => Err(format!( - "invalid row count '{raw}' (expected a positive integer)" - )), - }, - ["bench-curate-events-cmd", _, ..] => { - Err("too many arguments for bench-curate-events-cmd".to_string()) - } ["bench-curate-fx"] => Ok(CliAction::BenchCurateFx(DEFAULT_CURATE_FX_BENCH_ROWS)), ["bench-curate-fx", raw] => match raw.parse::() { Ok(n) if n > 0 => Ok(CliAction::BenchCurateFx(n)), @@ -2773,62 +301,6 @@ pub fn parse_args(args: &[String]) -> Result { )), }, ["bench-curate-fx", _, ..] => Err("too many arguments for bench-curate-fx".to_string()), - ["bench-curate-fx-cmd"] => Ok(CliAction::BenchCurateFxCmd( - DEFAULT_CURATE_FX_CMD_BENCH_ROWS, - )), - ["bench-curate-fx-cmd", raw] => match raw.parse::() { - Ok(n) if n > 0 => Ok(CliAction::BenchCurateFxCmd(n)), - _ => Err(format!( - "invalid row count '{raw}' (expected a positive integer)" - )), - }, - ["bench-curate-fx-cmd", _, ..] => { - Err("too many arguments for bench-curate-fx-cmd".to_string()) - } - ["bench-curate-adj"] => Ok(CliAction::BenchCurateAdj(DEFAULT_CURATE_ADJ_BENCH_EVENTS)), - ["bench-curate-adj", raw] => match raw.parse::() { - Ok(n) if n > 0 => Ok(CliAction::BenchCurateAdj(n)), - _ => Err(format!( - "invalid event count '{raw}' (expected a positive integer)" - )), - }, - ["bench-curate-adj", _, ..] => Err("too many arguments for bench-curate-adj".to_string()), - ["bench-curate-adj-cmd"] => Ok(CliAction::BenchCurateAdjCmd( - DEFAULT_CURATE_ADJ_CMD_BENCH_EVENTS, - )), - ["bench-curate-adj-cmd", raw] => match raw.parse::() { - Ok(n) if n > 0 => Ok(CliAction::BenchCurateAdjCmd(n)), - _ => Err(format!( - "invalid event count '{raw}' (expected a positive integer)" - )), - }, - ["bench-curate-adj-cmd", _, ..] => { - Err("too many arguments for bench-curate-adj-cmd".to_string()) - } - ["bench-curate-corporate-actions"] => Ok(CliAction::BenchCurateCorporateActions( - DEFAULT_CURATE_CORPORATE_ACTIONS_BENCH_EVENTS, - )), - ["bench-curate-corporate-actions", raw] => match raw.parse::() { - Ok(n) if n > 0 => Ok(CliAction::BenchCurateCorporateActions(n)), - _ => Err(format!( - "invalid event count '{raw}' (expected a positive integer)" - )), - }, - ["bench-curate-corporate-actions", _, ..] => { - Err("too many arguments for bench-curate-corporate-actions".to_string()) - } - ["bench-curate-corporate-actions-cmd"] => Ok(CliAction::BenchCurateCorporateActionsCmd( - DEFAULT_CURATE_CORPORATE_ACTIONS_CMD_BENCH_EVENTS, - )), - ["bench-curate-corporate-actions-cmd", raw] => match raw.parse::() { - Ok(n) if n > 0 => Ok(CliAction::BenchCurateCorporateActionsCmd(n)), - _ => Err(format!( - "invalid event count '{raw}' (expected a positive integer)" - )), - }, - ["bench-curate-corporate-actions-cmd", _, ..] => { - Err("too many arguments for bench-curate-corporate-actions-cmd".to_string()) - } [other, ..] => Err(format!("unknown argument '{other}'")), } } @@ -3116,56 +588,6 @@ mod tests { assert!(parse_args(&to_args(&["bench-bson-eod-prices", "10", "20"])).is_err()); } - #[test] - fn parses_and_validates_bench_bson_qm_actions_args() { - assert_eq!( - parse_args(&to_args(&["bench-bson-qm-actions"])), - Ok(CliAction::BenchBsonQmActions( - DEFAULT_BSON_QM_ACTIONS_BENCH_ROWS - )) - ); - assert_eq!( - parse_args(&to_args(&["bench-bson-qm-actions", "250000"])), - Ok(CliAction::BenchBsonQmActions(250_000)) - ); - assert!(parse_args(&to_args(&["bench-bson-qm-actions", "0"])).is_err()); - assert!(parse_args(&to_args(&["bench-bson-qm-actions", "-5"])).is_err()); - assert!(parse_args(&to_args(&["bench-bson-qm-actions", "abc"])).is_err()); - assert!(parse_args(&to_args(&["bench-bson-qm-actions", "10", "20"])).is_err()); - } - - #[test] - fn parses_and_validates_bench_bson_stream_args() { - assert_eq!( - parse_args(&to_args(&["bench-bson-stream"])), - Ok(CliAction::BenchBsonStream(DEFAULT_BSON_STREAM_BENCH_ROWS)) - ); - assert_eq!( - parse_args(&to_args(&["bench-bson-stream", "250000"])), - Ok(CliAction::BenchBsonStream(250_000)) - ); - assert!(parse_args(&to_args(&["bench-bson-stream", "0"])).is_err()); - assert!(parse_args(&to_args(&["bench-bson-stream", "-5"])).is_err()); - assert!(parse_args(&to_args(&["bench-bson-stream", "abc"])).is_err()); - assert!(parse_args(&to_args(&["bench-bson-stream", "10", "20"])).is_err()); - } - - #[test] - fn parses_and_validates_bench_mongo_stream_args() { - assert_eq!( - parse_args(&to_args(&["bench-mongo-stream"])), - Ok(CliAction::BenchMongoStream(DEFAULT_MONGO_STREAM_BENCH_ROWS)) - ); - assert_eq!( - parse_args(&to_args(&["bench-mongo-stream", "100000"])), - Ok(CliAction::BenchMongoStream(100_000)) - ); - assert!(parse_args(&to_args(&["bench-mongo-stream", "0"])).is_err()); - assert!(parse_args(&to_args(&["bench-mongo-stream", "-5"])).is_err()); - assert!(parse_args(&to_args(&["bench-mongo-stream", "abc"])).is_err()); - assert!(parse_args(&to_args(&["bench-mongo-stream", "10", "20"])).is_err()); - } - #[test] fn usage_strings_mention_all_benchmarks() { let full = format_usage("curate-etl", "0.1.0"); @@ -3173,7 +595,6 @@ mod tests { assert!(full.contains("bench-adj")); assert!(full.contains("bench-corporate-actions")); assert!(full.contains("bench-bars")); - assert!(full.contains("bench-bars-1m")); assert!(full.contains("bench-fx")); assert!(full.contains("bench-shorts")); assert!(full.contains("bench-events")); @@ -3185,27 +606,16 @@ mod tests { assert!(full.contains("bench-parquet-adj")); assert!(full.contains("bench-parquet-corporate-actions")); assert!(full.contains("bench-bson-eod-prices")); - assert!(full.contains("bench-bson-qm-actions")); - assert!(full.contains("bench-bson-stream")); - assert!(full.contains("curate-bars-1d")); - assert!(full.contains("curate-adj-factors")); - assert!(full.contains("curate-corporate-actions")); assert!(full.contains("bench-curate-bars")); - assert!(full.contains("bench-curate-bars-cmd")); assert!(full.contains("bench-curate-shorts")); assert!(full.contains("bench-curate-events")); assert!(full.contains("bench-curate-fx")); - assert!(full.contains("bench-curate-adj")); - assert!(full.contains("bench-curate-adj-cmd")); - assert!(full.contains("bench-curate-corporate-actions")); - assert!(full.contains("bench-curate-corporate-actions-cmd")); 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-bars-1m")); assert!(short.contains("bench-fx")); assert!(short.contains("bench-shorts")); assert!(short.contains("bench-events")); @@ -3217,36 +627,10 @@ mod tests { assert!(short.contains("bench-parquet-adj")); assert!(short.contains("bench-parquet-corporate-actions")); assert!(short.contains("bench-bson-eod-prices")); - assert!(short.contains("bench-bson-qm-actions")); - assert!(short.contains("bench-bson-stream")); - assert!(short.contains("curate-bars-1d")); - assert!(short.contains("curate-adj-factors")); - assert!(short.contains("curate-corporate-actions")); assert!(short.contains("bench-curate-bars")); - assert!(short.contains("bench-curate-bars-cmd")); assert!(short.contains("bench-curate-shorts")); assert!(short.contains("bench-curate-events")); assert!(short.contains("bench-curate-fx")); - assert!(short.contains("bench-curate-adj")); - assert!(short.contains("bench-curate-adj-cmd")); - assert!(short.contains("bench-curate-corporate-actions")); - assert!(short.contains("bench-curate-corporate-actions-cmd")); - } - - #[test] - fn parses_and_validates_bench_bars_1m_args() { - assert_eq!( - parse_args(&to_args(&["bench-bars-1m"])), - Ok(CliAction::BenchBars1m(DEFAULT_BARS_1M_BENCH_ROWS)) - ); - assert_eq!( - parse_args(&to_args(&["bench-bars-1m", "1000000"])), - Ok(CliAction::BenchBars1m(1_000_000)) - ); - assert!(parse_args(&to_args(&["bench-bars-1m", "0"])).is_err()); - assert!(parse_args(&to_args(&["bench-bars-1m", "-5"])).is_err()); - assert!(parse_args(&to_args(&["bench-bars-1m", "abc"])).is_err()); - assert!(parse_args(&to_args(&["bench-bars-1m", "10", "20"])).is_err()); } #[test] @@ -3316,3464 +700,4 @@ mod tests { assert!(parse_args(&to_args(&["bench-curate-fx", "abc"])).is_err()); assert!(parse_args(&to_args(&["bench-curate-fx", "10", "20"])).is_err()); } - - #[test] - fn parses_and_validates_bench_curate_adj_args() { - assert_eq!( - parse_args(&to_args(&["bench-curate-adj"])), - Ok(CliAction::BenchCurateAdj(DEFAULT_CURATE_ADJ_BENCH_EVENTS)) - ); - assert_eq!( - parse_args(&to_args(&["bench-curate-adj", "100000"])), - Ok(CliAction::BenchCurateAdj(100_000)) - ); - assert!(parse_args(&to_args(&["bench-curate-adj", "0"])).is_err()); - assert!(parse_args(&to_args(&["bench-curate-adj", "-5"])).is_err()); - assert!(parse_args(&to_args(&["bench-curate-adj", "abc"])).is_err()); - assert!(parse_args(&to_args(&["bench-curate-adj", "10", "20"])).is_err()); - } - - #[test] - fn parses_and_validates_bench_curate_corporate_actions_args() { - assert_eq!( - parse_args(&to_args(&["bench-curate-corporate-actions"])), - Ok(CliAction::BenchCurateCorporateActions( - DEFAULT_CURATE_CORPORATE_ACTIONS_BENCH_EVENTS - )) - ); - assert_eq!( - parse_args(&to_args(&["bench-curate-corporate-actions", "20000"])), - Ok(CliAction::BenchCurateCorporateActions(20_000)) - ); - assert!(parse_args(&to_args(&["bench-curate-corporate-actions", "0"])).is_err()); - assert!(parse_args(&to_args(&["bench-curate-corporate-actions", "-5"])).is_err()); - assert!(parse_args(&to_args(&["bench-curate-corporate-actions", "abc"])).is_err()); - assert!(parse_args(&to_args(&["bench-curate-corporate-actions", "10", "20"])).is_err()); - } - - #[test] - fn parses_and_validates_bench_curate_bars_cmd_args() { - assert_eq!( - parse_args(&to_args(&["bench-curate-bars-cmd"])), - Ok(CliAction::BenchCurateBarsCmd( - DEFAULT_CURATE_BARS_CMD_BENCH_ROWS - )) - ); - assert_eq!( - parse_args(&to_args(&["bench-curate-bars-cmd", "5000"])), - Ok(CliAction::BenchCurateBarsCmd(5_000)) - ); - assert!(parse_args(&to_args(&["bench-curate-bars-cmd", "0"])).is_err()); - assert!(parse_args(&to_args(&["bench-curate-bars-cmd", "-5"])).is_err()); - assert!(parse_args(&to_args(&["bench-curate-bars-cmd", "abc"])).is_err()); - assert!(parse_args(&to_args(&["bench-curate-bars-cmd", "10", "20"])).is_err()); - } - - #[test] - fn parses_valid_curate_bars_1d_args() { - let parsed = parse_args(&to_args(&[ - "curate-bars-1d", - "--eod-prices", - "/tmp/eodPrices.bson", - "--qm-splits", - "/tmp/qmSplits.bson", - "--provider-mapping", - "/tmp/provider_mapping.tsv", - "--listing-currencies", - "/tmp/listing_currencies.tsv", - "--out", - "/tmp/out", - ])) - .expect("valid curate-bars-1d args"); - assert_eq!( - parsed, - CliAction::CurateBars1d(CurateBars1dArgs { - eod_prices: PathBuf::from("/tmp/eodPrices.bson"), - qm_splits: PathBuf::from("/tmp/qmSplits.bson"), - qm_prices: None, - provider_mapping: PathBuf::from("/tmp/provider_mapping.tsv"), - listing_currencies: PathBuf::from("/tmp/listing_currencies.tsv"), - out_dir: PathBuf::from("/tmp/out"), - rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, - threads: default_curate_bars_threads(), - }) - ); - - let with_qm_prices = parse_args(&to_args(&[ - "curate-bars-1d", - "--eod-prices", - "/tmp/eodPrices.bson", - "--qm-splits", - "/tmp/qmSplits.bson", - "--qm-prices", - "/tmp/qmPrices.bson", - "--provider-mapping", - "/tmp/provider_mapping.tsv", - "--listing-currencies", - "/tmp/listing_currencies.tsv", - "--out", - "/tmp/out", - ])) - .expect("valid curate-bars-1d args with --qm-prices"); - assert_eq!( - with_qm_prices, - CliAction::CurateBars1d(CurateBars1dArgs { - eod_prices: PathBuf::from("/tmp/eodPrices.bson"), - qm_splits: PathBuf::from("/tmp/qmSplits.bson"), - qm_prices: Some(PathBuf::from("/tmp/qmPrices.bson")), - provider_mapping: PathBuf::from("/tmp/provider_mapping.tsv"), - listing_currencies: PathBuf::from("/tmp/listing_currencies.tsv"), - out_dir: PathBuf::from("/tmp/out"), - rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, - threads: default_curate_bars_threads(), - }) - ); - - let equals_style = parse_args(&to_args(&[ - "curate-bars-1d", - "--eod-prices=/tmp/e.bson", - "--qm-splits=/tmp/s.bson", - "--qm-prices=/tmp/q.bson", - "--provider-mapping=/tmp/m.tsv", - "--listing-currencies=/tmp/c.tsv", - "--out=--literal-out-dir", - "--rel-tolerance=-0.0", - ])) - .expect("equals-style curate-bars-1d args"); - match equals_style { - CliAction::CurateBars1d(a) => { - assert_eq!(a.qm_prices, Some(PathBuf::from("/tmp/q.bson"))); - assert_eq!(a.out_dir, PathBuf::from("--literal-out-dir")); - assert_eq!(a.rel_tolerance.to_bits(), 0.0_f64.to_bits()); - } - other => panic!("unexpected action: {other:?}"), - } - } - - #[test] - fn rejects_invalid_curate_bars_1d_flags() { - let full = [ - "curate-bars-1d", - "--eod-prices", - "e.bson", - "--qm-splits", - "s.bson", - "--provider-mapping", - "m.tsv", - "--listing-currencies", - "c.tsv", - "--out", - "out", - ]; - - // Each required flag missing one at a time. - for (drop_idx, expected_flag) in [ - (1, "--eod-prices"), - (3, "--qm-splits"), - (5, "--provider-mapping"), - (7, "--listing-currencies"), - (9, "--out"), - ] { - let mut subset: Vec<&str> = Vec::new(); - for (idx, &tok) in full.iter().enumerate() { - if idx != drop_idx && idx != drop_idx + 1 { - subset.push(tok); - } - } - let err = parse_args(&to_args(&subset)).unwrap_err(); - assert!( - err.contains(expected_flag), - "expected missing {expected_flag}, got: {err}" - ); - } - - // Duplicate flags (including mixed `--flag val` and `--flag=val`). - let mut dup = full.to_vec(); - dup.push("--out=other"); - let err = parse_args(&to_args(&dup)).unwrap_err(); - assert!(err.contains("duplicate flag '--out'"), "{err}"); - - // Invalid --qm-prices: duplicate, empty, missing value. - let mut dup_qm = full.to_vec(); - dup_qm.extend(["--qm-prices", "q1.bson", "--qm-prices=q2.bson"]); - let err = parse_args(&to_args(&dup_qm)).unwrap_err(); - assert!(err.contains("duplicate flag '--qm-prices'"), "{err}"); - - let mut empty_qm = full.to_vec(); - empty_qm.push("--qm-prices="); - let err = parse_args(&to_args(&empty_qm)).unwrap_err(); - assert!(err.contains("empty value for flag '--qm-prices'"), "{err}"); - - let mut missing_qm = full.to_vec(); - missing_qm.push("--qm-prices"); - let err = parse_args(&to_args(&missing_qm)).unwrap_err(); - assert!(err.contains("missing value for flag '--qm-prices'"), "{err}"); - - // Valid --threads forms (separated and equals) and default. - let mut with_threads = full.to_vec(); - with_threads.extend(["--threads", "4"]); - match parse_args(&to_args(&with_threads)).expect("valid --threads 4") { - CliAction::CurateBars1d(a) => assert_eq!(a.threads, 4), - other => panic!("unexpected action: {other:?}"), - } - let mut with_threads_eq = full.to_vec(); - with_threads_eq.push("--threads=8"); - match parse_args(&to_args(&with_threads_eq)).expect("valid --threads=8") { - CliAction::CurateBars1d(a) => assert_eq!(a.threads, 8), - other => panic!("unexpected action: {other:?}"), - } - - // Invalid --threads values: 0, non-integer, negative, empty, missing, duplicate. - for bad in ["0", "abc", "-1", "+2", "1.5", ""] { - let mut args_eq = full.to_vec(); - let flag = format!("--threads={bad}"); - args_eq.push(&flag); - let err = parse_args(&to_args(&args_eq)).unwrap_err(); - assert!( - err.contains("invalid --threads"), - "expected invalid --threads for '{bad}', got: {err}" - ); - } - let mut missing_threads = full.to_vec(); - missing_threads.push("--threads"); - let err = parse_args(&to_args(&missing_threads)).unwrap_err(); - assert!(err.contains("missing value for flag '--threads'"), "{err}"); - - let mut dup_threads = full.to_vec(); - dup_threads.extend(["--threads", "2", "--threads=4"]); - let err = parse_args(&to_args(&dup_threads)).unwrap_err(); - assert!(err.contains("duplicate flag '--threads'"), "{err}"); - - assert!(format_usage("curate-etl", "0.1.0").contains("[--threads ]")); - assert!(format_usage_stderr("curate-etl").contains("[--threads ]")); - - // Unknown flag. - let mut unk = full.to_vec(); - unk.extend(["--bogus", "1"]); - let err = parse_args(&to_args(&unk)).unwrap_err(); - assert!(err.contains("unknown flag '--bogus'"), "{err}"); - - // Missing value for flag at end of args. - let err = parse_args(&to_args(&["curate-bars-1d", "--out"])).unwrap_err(); - assert!(err.contains("missing value for flag '--out'"), "{err}"); - - // Separated flag followed immediately by another `--` option token (e.g. unset `$OUT` - // before a misspelled flag) must fail as missing value rather than consuming it as a path. - let err = parse_args(&to_args(&[ - "curate-bars-1d", - "--eod-prices", - "e.bson", - "--qm-splits", - "s.bson", - "--provider-mapping", - "m.tsv", - "--listing-currencies", - "c.tsv", - "--out", - "--rel-tolerence=0.01", - ])) - .unwrap_err(); - assert!(err.contains("missing value for flag '--out'"), "{err}"); - - // Empty path value. - let mut empty_val = full.to_vec(); - empty_val[10] = ""; - let err = parse_args(&to_args(&empty_val)).unwrap_err(); - assert!(err.contains("empty value for flag '--out'"), "{err}"); - - // Unexpected positional argument. - let mut pos = full.to_vec(); - pos.push("extra"); - let err = parse_args(&to_args(&pos)).unwrap_err(); - assert!(err.contains("unexpected positional argument"), "{err}"); - - // Invalid --rel-tolerance values. - for bad in ["abc", "-0.01", "NaN", "inf", "-inf", ""] { - let mut bad_tol = full.to_vec(); - bad_tol.extend(["--rel-tolerance", bad]); - let err = parse_args(&to_args(&bad_tol)).unwrap_err(); - assert!( - err.contains("--rel-tolerance"), - "expected --rel-tolerance error for '{bad}', got: {err}" - ); - } - } - - #[test] - fn parses_and_validates_bench_curate_adj_cmd_args() { - assert_eq!( - parse_args(&to_args(&["bench-curate-adj-cmd"])), - Ok(CliAction::BenchCurateAdjCmd( - DEFAULT_CURATE_ADJ_CMD_BENCH_EVENTS - )) - ); - assert_eq!( - parse_args(&to_args(&["bench-curate-adj-cmd", "5000"])), - Ok(CliAction::BenchCurateAdjCmd(5_000)) - ); - assert!(parse_args(&to_args(&["bench-curate-adj-cmd", "0"])).is_err()); - assert!(parse_args(&to_args(&["bench-curate-adj-cmd", "-5"])).is_err()); - assert!(parse_args(&to_args(&["bench-curate-adj-cmd", "abc"])).is_err()); - assert!(parse_args(&to_args(&["bench-curate-adj-cmd", "10", "20"])).is_err()); - } - - #[test] - fn parses_valid_curate_adj_factors_args() { - let parsed = parse_args(&to_args(&[ - "curate-adj-factors", - "--qm-splits", - "/tmp/qmSplits.bson", - "--qm-dividends", - "/tmp/qmDividends.bson", - "--provider-mapping", - "/tmp/provider_mapping.tsv", - "--bars-1d", - "/tmp/bars_1d", - "--out", - "/tmp/out", - ])) - .expect("valid curate-adj-factors args"); - assert_eq!( - parsed, - CliAction::CurateAdjFactors(CurateAdjFactorsArgs { - qm_splits: PathBuf::from("/tmp/qmSplits.bson"), - qm_dividends: PathBuf::from("/tmp/qmDividends.bson"), - provider_mapping: PathBuf::from("/tmp/provider_mapping.tsv"), - bars_1d_dir: PathBuf::from("/tmp/bars_1d"), - out_dir: PathBuf::from("/tmp/out"), - }) - ); - - let equals_style = parse_args(&to_args(&[ - "curate-adj-factors", - "--qm-splits=/tmp/s.bson", - "--qm-dividends=/tmp/d.bson", - "--provider-mapping=/tmp/m.tsv", - "--bars-1d=/tmp/bars", - "--out=--literal-out-dir", - ])) - .expect("equals-style curate-adj-factors args"); - assert_eq!( - equals_style, - CliAction::CurateAdjFactors(CurateAdjFactorsArgs { - qm_splits: PathBuf::from("/tmp/s.bson"), - qm_dividends: PathBuf::from("/tmp/d.bson"), - provider_mapping: PathBuf::from("/tmp/m.tsv"), - bars_1d_dir: PathBuf::from("/tmp/bars"), - out_dir: PathBuf::from("--literal-out-dir"), - }) - ); - } - - #[test] - fn rejects_invalid_curate_adj_factors_flags() { - let full = [ - "curate-adj-factors", - "--qm-splits", - "s.bson", - "--qm-dividends", - "d.bson", - "--provider-mapping", - "m.tsv", - "--bars-1d", - "bars", - "--out", - "out", - ]; - - for (drop_idx, expected_flag) in [ - (1, "--qm-splits"), - (3, "--qm-dividends"), - (5, "--provider-mapping"), - (7, "--bars-1d"), - (9, "--out"), - ] { - let mut subset: Vec<&str> = Vec::new(); - for (idx, &tok) in full.iter().enumerate() { - if idx != drop_idx && idx != drop_idx + 1 { - subset.push(tok); - } - } - let err = parse_args(&to_args(&subset)).unwrap_err(); - assert!( - err.contains(expected_flag), - "expected missing {expected_flag}, got: {err}" - ); - } - - // Duplicate flag. - let mut dup = full.to_vec(); - dup.push("--out=other"); - let err = parse_args(&to_args(&dup)).unwrap_err(); - assert!(err.contains("duplicate flag '--out'"), "{err}"); - - // Unknown flag. - let mut unk = full.to_vec(); - unk.extend(["--bogus", "1"]); - let err = parse_args(&to_args(&unk)).unwrap_err(); - assert!(err.contains("unknown flag '--bogus'"), "{err}"); - - // Missing value at end. - let err = parse_args(&to_args(&["curate-adj-factors", "--out"])).unwrap_err(); - assert!(err.contains("missing value for flag '--out'"), "{err}"); - - // Separated flag followed immediately by another `--` token. - let err = parse_args(&to_args(&[ - "curate-adj-factors", - "--qm-splits", - "s.bson", - "--qm-dividends", - "d.bson", - "--provider-mapping", - "m.tsv", - "--bars-1d", - "--out", - "out", - ])) - .unwrap_err(); - assert!(err.contains("missing value for flag '--bars-1d'"), "{err}"); - - // Empty value. - let mut empty_val = full.to_vec(); - empty_val[10] = ""; - let err = parse_args(&to_args(&empty_val)).unwrap_err(); - assert!(err.contains("empty value for flag '--out'"), "{err}"); - - // Unexpected positional arg. - let mut pos = full.to_vec(); - pos.push("extra"); - let err = parse_args(&to_args(&pos)).unwrap_err(); - assert!(err.contains("unexpected positional argument"), "{err}"); - } - - #[test] - fn parses_and_validates_bench_curate_corporate_actions_cmd_args() { - assert_eq!( - parse_args(&to_args(&["bench-curate-corporate-actions-cmd"])), - Ok(CliAction::BenchCurateCorporateActionsCmd( - DEFAULT_CURATE_CORPORATE_ACTIONS_CMD_BENCH_EVENTS - )) - ); - assert_eq!( - parse_args(&to_args(&["bench-curate-corporate-actions-cmd", "5000"])), - Ok(CliAction::BenchCurateCorporateActionsCmd(5_000)) - ); - assert!(parse_args(&to_args(&["bench-curate-corporate-actions-cmd", "0"])).is_err()); - assert!(parse_args(&to_args(&["bench-curate-corporate-actions-cmd", "-5"])).is_err()); - assert!(parse_args(&to_args(&["bench-curate-corporate-actions-cmd", "abc"])).is_err()); - assert!( - parse_args(&to_args(&["bench-curate-corporate-actions-cmd", "10", "20"])).is_err() - ); - } - - #[test] - fn parses_valid_curate_corporate_actions_args() { - let without_delistings = parse_args(&to_args(&[ - "curate-corporate-actions", - "--qm-splits", - "/tmp/qmSplits.bson", - "--qm-dividends", - "/tmp/qmDividends.bson", - "--provider-mapping", - "/tmp/provider_mapping.tsv", - "--out", - "/tmp/out", - ])) - .expect("valid curate-corporate-actions args without --delistings"); - assert_eq!( - without_delistings, - CliAction::CurateCorporateActions(CurateCorporateActionsArgs { - qm_splits: PathBuf::from("/tmp/qmSplits.bson"), - qm_dividends: PathBuf::from("/tmp/qmDividends.bson"), - provider_mapping: PathBuf::from("/tmp/provider_mapping.tsv"), - delistings: None, - out_dir: PathBuf::from("/tmp/out"), - }) - ); - - let with_delistings_eq = parse_args(&to_args(&[ - "curate-corporate-actions", - "--qm-splits=/tmp/s.bson", - "--qm-dividends=/tmp/d.bson", - "--provider-mapping=/tmp/m.tsv", - "--delistings=/tmp/delist.tsv", - "--out=--literal-out", - ])) - .expect("equals-style curate-corporate-actions args with --delistings"); - assert_eq!( - with_delistings_eq, - CliAction::CurateCorporateActions(CurateCorporateActionsArgs { - qm_splits: PathBuf::from("/tmp/s.bson"), - qm_dividends: PathBuf::from("/tmp/d.bson"), - provider_mapping: PathBuf::from("/tmp/m.tsv"), - delistings: Some(PathBuf::from("/tmp/delist.tsv")), - out_dir: PathBuf::from("--literal-out"), - }) - ); - } - - #[test] - fn rejects_invalid_curate_corporate_actions_flags() { - let full = [ - "curate-corporate-actions", - "--qm-splits", - "s.bson", - "--qm-dividends", - "d.bson", - "--provider-mapping", - "m.tsv", - "--out", - "out", - ]; - - for (drop_idx, expected_flag) in [ - (1, "--qm-splits"), - (3, "--qm-dividends"), - (5, "--provider-mapping"), - (7, "--out"), - ] { - let mut subset: Vec<&str> = Vec::new(); - for (idx, &tok) in full.iter().enumerate() { - if idx != drop_idx && idx != drop_idx + 1 { - subset.push(tok); - } - } - let err = parse_args(&to_args(&subset)).unwrap_err(); - assert!( - err.contains(expected_flag), - "expected missing {expected_flag}, got: {err}" - ); - } - - // Duplicate required flag. - let mut dup = full.to_vec(); - dup.push("--out=other"); - let err = parse_args(&to_args(&dup)).unwrap_err(); - assert!(err.contains("duplicate flag '--out'"), "{err}"); - - // Duplicate optional --delistings flag. - let mut dup_delist = full.to_vec(); - dup_delist.extend(["--delistings", "a.tsv", "--delistings=b.tsv"]); - let err = parse_args(&to_args(&dup_delist)).unwrap_err(); - assert!(err.contains("duplicate flag '--delistings'"), "{err}"); - - // Unknown flag. - let mut unk = full.to_vec(); - unk.extend(["--bogus", "1"]); - let err = parse_args(&to_args(&unk)).unwrap_err(); - assert!(err.contains("unknown flag '--bogus'"), "{err}"); - - // Missing value at end. - let err = parse_args(&to_args(&["curate-corporate-actions", "--delistings"])).unwrap_err(); - assert!( - err.contains("missing value for flag '--delistings'"), - "{err}" - ); - - // Separated flag followed immediately by another `--` token. - let err = parse_args(&to_args(&[ - "curate-corporate-actions", - "--qm-splits", - "s.bson", - "--qm-dividends", - "d.bson", - "--provider-mapping", - "m.tsv", - "--delistings", - "--out", - "out", - ])) - .unwrap_err(); - assert!( - err.contains("missing value for flag '--delistings'"), - "{err}" - ); - - // Empty value. - let mut empty_val = full.to_vec(); - empty_val[8] = ""; - let err = parse_args(&to_args(&empty_val)).unwrap_err(); - assert!(err.contains("empty value for flag '--out'"), "{err}"); - - let mut empty_delist = full.to_vec(); - empty_delist.push("--delistings="); - let err = parse_args(&to_args(&empty_delist)).unwrap_err(); - assert!(err.contains("empty value for flag '--delistings'"), "{err}"); - - // Unexpected positional arg. - let mut pos = full.to_vec(); - pos.push("extra"); - let err = parse_args(&to_args(&pos)).unwrap_err(); - assert!(err.contains("unexpected positional argument"), "{err}"); - } - - #[test] - fn parses_and_validates_curate_fx_1d_and_bench_curate_fx_cmd_args() { - // Usage strings include both new commands. - let usage = format_usage("curate-etl", "0.1.0"); - assert!(usage.contains("curate-fx-1d"), "{usage}"); - assert!(usage.contains("bench-curate-fx-cmd"), "{usage}"); - let usage_err = format_usage_stderr("curate-etl"); - assert!(usage_err.contains("curate-fx-1d"), "{usage_err}"); - assert!(usage_err.contains("bench-curate-fx-cmd"), "{usage_err}"); - - // Default --te-symbol with separated flags. - assert_eq!( - parse_args(&to_args(&[ - "curate-fx-1d", - "--eod-prices", - "eod.bson", - "--te-market-data", - "te.bson", - "--out", - "out_dir", - ])), - Ok(CliAction::CurateFx1d(CurateFx1dArgs { - eod_prices: PathBuf::from("eod.bson"), - te_market_data: PathBuf::from("te.bson"), - te_symbol: DEFAULT_TE_SYMBOL.to_string(), - out_dir: PathBuf::from("out_dir"), - })) - ); - - // Explicit --te-symbol and `--flag=value` form. - assert_eq!( - parse_args(&to_args(&[ - "curate-fx-1d", - "--eod-prices=eod.bson", - "--te-market-data=te.bson", - "--te-symbol=usdcad", - "--out=out_dir", - ])), - Ok(CliAction::CurateFx1d(CurateFx1dArgs { - eod_prices: PathBuf::from("eod.bson"), - te_market_data: PathBuf::from("te.bson"), - te_symbol: "usdcad".to_string(), - out_dir: PathBuf::from("out_dir"), - })) - ); - - // Missing required flags. - for (missing, args) in [ - ( - "--eod-prices", - &[ - "curate-fx-1d", - "--te-market-data", - "te.bson", - "--out", - "out", - ][..], - ), - ( - "--te-market-data", - &["curate-fx-1d", "--eod-prices", "eod.bson", "--out", "out"][..], - ), - ( - "--out", - &[ - "curate-fx-1d", - "--eod-prices", - "eod.bson", - "--te-market-data", - "te.bson", - ][..], - ), - ] { - let err = parse_args(&to_args(args)).unwrap_err(); - assert!( - err.contains(&format!("missing required flag '{missing}'")), - "{err}" - ); - } - - // Duplicate flags (including --te-symbol). - for (dup_flag, args) in [ - ( - "--eod-prices", - &[ - "curate-fx-1d", - "--eod-prices", - "a.bson", - "--eod-prices=b.bson", - "--te-market-data", - "te.bson", - "--out", - "out", - ][..], - ), - ( - "--te-symbol", - &[ - "curate-fx-1d", - "--eod-prices", - "eod.bson", - "--te-market-data", - "te.bson", - "--te-symbol", - "USDCAD", - "--te-symbol=USDCAD", - "--out", - "out", - ][..], - ), - ] { - let err = parse_args(&to_args(args)).unwrap_err(); - assert!(err.contains(&format!("duplicate flag '{dup_flag}'")), "{err}"); - } - - // Unknown flag, missing value (end / followed by --), empty/whitespace, positional. - let err = parse_args(&to_args(&[ - "curate-fx-1d", - "--eod-prices", - "eod.bson", - "--te-market-data", - "te.bson", - "--out", - "out", - "--bogus", - "1", - ])) - .unwrap_err(); - assert!(err.contains("unknown flag '--bogus'"), "{err}"); - - let err = parse_args(&to_args(&["curate-fx-1d", "--te-symbol"])).unwrap_err(); - assert!(err.contains("missing value for flag '--te-symbol'"), "{err}"); - - let err = parse_args(&to_args(&[ - "curate-fx-1d", - "--eod-prices", - "--te-market-data", - "te.bson", - "--out", - "out", - ])) - .unwrap_err(); - assert!( - err.contains("missing value for flag '--eod-prices'"), - "{err}" - ); - - for bad_sym in [" ", "EURUSD", "CADUSD"] { - let err = parse_args(&to_args(&[ - "curate-fx-1d", - "--eod-prices", - "eod.bson", - "--te-market-data", - "te.bson", - "--te-symbol", - bad_sym, - "--out", - "out", - ])) - .unwrap_err(); - assert!( - err.contains("invalid --te-symbol"), - "expected invalid --te-symbol for '{bad_sym}', got: {err}" - ); - } - - let err = parse_args(&to_args(&[ - "curate-fx-1d", - "--eod-prices", - "eod.bson", - "--te-market-data", - "te.bson", - "--out", - "", - ])) - .unwrap_err(); - assert!(err.contains("empty value for flag '--out'"), "{err}"); - - let err = parse_args(&to_args(&[ - "curate-fx-1d", - "--eod-prices", - "eod.bson", - "--te-market-data", - "te.bson", - "--out", - "out", - "extra", - ])) - .unwrap_err(); - assert!(err.contains("unexpected positional argument"), "{err}"); - - // bench-curate-fx-cmd parsing - assert_eq!( - parse_args(&to_args(&["bench-curate-fx-cmd"])), - Ok(CliAction::BenchCurateFxCmd(DEFAULT_CURATE_FX_CMD_BENCH_ROWS)) - ); - assert_eq!( - parse_args(&to_args(&["bench-curate-fx-cmd", "4000"])), - Ok(CliAction::BenchCurateFxCmd(4_000)) - ); - assert!(parse_args(&to_args(&["bench-curate-fx-cmd", "0"])).is_err()); - assert!(parse_args(&to_args(&["bench-curate-fx-cmd", "-5"])).is_err()); - assert!(parse_args(&to_args(&["bench-curate-fx-cmd", "abc"])).is_err()); - assert!(parse_args(&to_args(&["bench-curate-fx-cmd", "10", "20"])).is_err()); - } - - #[test] - fn parses_and_validates_curate_shorts_and_bench_curate_shorts_command() { - let usage = format_usage("curate-etl", "0.1.0"); - assert!(usage.contains("curate-shorts")); - assert!(usage.contains("bench-curate-shorts-command")); - - // Minimal required flags with defaults - assert_eq!( - parse_args(&to_args(&[ - "curate-shorts", - "--ceo-shorts", - "shorts.bson", - "--provider-mapping", - "map.tsv", - "--out", - "out", - "--shares-short-field", - "sharesShort", - ])), - Ok(CliAction::CurateShorts(CurateShortsArgs { - ceo_shorts: PathBuf::from("shorts.bson"), - provider_mapping: PathBuf::from("map.tsv"), - out_dir: PathBuf::from("out"), - key_field: DEFAULT_KEY_FIELD.to_string(), - report_date_field: DEFAULT_REPORT_DATE_FIELD.to_string(), - shares_short_field: "sharesShort".to_string(), - net_change_field: None, - pct_float_field: None, - mapping_source: DEFAULT_MAPPING_SOURCE.to_string(), - })) - ); - - // Full custom flags with = syntax - assert_eq!( - parse_args(&to_args(&[ - "curate-shorts", - "--ceo-shorts=s.bson", - "--provider-mapping=m.tsv", - "--out=o", - "--shares-short-field=qty", - "--key-field=ticker", - "--report-date-field=asOf", - "--net-change-field=delta", - "--pct-float-field=pct", - "--mapping-source=ceo_alt", - ])), - Ok(CliAction::CurateShorts(CurateShortsArgs { - ceo_shorts: PathBuf::from("s.bson"), - provider_mapping: PathBuf::from("m.tsv"), - out_dir: PathBuf::from("o"), - key_field: "ticker".to_string(), - report_date_field: "asOf".to_string(), - shares_short_field: "qty".to_string(), - net_change_field: Some("delta".to_string()), - pct_float_field: Some("pct".to_string()), - mapping_source: "ceo_alt".to_string(), - })) - ); - - // Missing --shares-short-field - let err = parse_args(&to_args(&[ - "curate-shorts", - "--ceo-shorts", - "s.bson", - "--provider-mapping", - "m.tsv", - "--out", - "o", - ])) - .unwrap_err(); - assert!(err.contains("--shares-short-field"), "{err}"); - - // Duplicate flag - let err = parse_args(&to_args(&[ - "curate-shorts", - "--ceo-shorts", - "s.bson", - "--ceo-shorts", - "s2.bson", - "--provider-mapping", - "m.tsv", - "--out", - "o", - "--shares-short-field", - "qty", - ])) - .unwrap_err(); - assert!(err.contains("duplicate flag '--ceo-shorts'"), "{err}"); - - // Unknown flag - let err = parse_args(&to_args(&[ - "curate-shorts", - "--ceo-shorts", - "s.bson", - "--provider-mapping", - "m.tsv", - "--out", - "o", - "--shares-short-field", - "qty", - "--bogus", - "1", - ])) - .unwrap_err(); - assert!(err.contains("unknown flag '--bogus'"), "{err}"); - - // Empty / blank field name - let err = parse_args(&to_args(&[ - "curate-shorts", - "--ceo-shorts", - "s.bson", - "--provider-mapping", - "m.tsv", - "--out", - "o", - "--shares-short-field", - " ", - ])) - .unwrap_err(); - assert!(err.contains("empty value for flag '--shares-short-field'"), "{err}"); - - // Colliding roles with default 'symbol' - let err = parse_args(&to_args(&[ - "curate-shorts", - "--ceo-shorts", - "s.bson", - "--provider-mapping", - "m.tsv", - "--out", - "o", - "--shares-short-field", - "symbol", - ])) - .unwrap_err(); - assert!(err.contains("cannot share BSON field 'symbol'"), "{err}"); - - // Colliding optional roles - let err = parse_args(&to_args(&[ - "curate-shorts", - "--ceo-shorts", - "s.bson", - "--provider-mapping", - "m.tsv", - "--out", - "o", - "--shares-short-field", - "qty", - "--net-change-field", - "same", - "--pct-float-field", - "same", - ])) - .unwrap_err(); - assert!(err.contains("cannot share BSON field 'same'"), "{err}"); - - // bench-curate-shorts-command - assert_eq!( - parse_args(&to_args(&["bench-curate-shorts-command"])), - Ok(CliAction::BenchCurateShortsCommand( - DEFAULT_CURATE_SHORTS_COMMAND_BENCH_ROWS - )) - ); - assert_eq!( - parse_args(&to_args(&["bench-curate-shorts-command", "2500"])), - Ok(CliAction::BenchCurateShortsCommand(2_500)) - ); - assert!(parse_args(&to_args(&["bench-curate-shorts-command", "0"])).is_err()); - assert!(parse_args(&to_args(&["bench-curate-shorts-command", "-1"])).is_err()); - assert!(parse_args(&to_args(&["bench-curate-shorts-command", "abc"])).is_err()); - assert!(parse_args(&to_args(&["bench-curate-shorts-command", "1", "2"])).is_err()); - } - - #[test] - fn curate_events_and_bench_curate_events_cmd_parsing_and_usage() { - let usage = format_usage("curate-etl", "0.1.0"); - let stderr_usage = format_usage_stderr("curate-etl"); - assert!(usage.contains("curate-events --qm-filings")); - assert!(usage.contains("bench-curate-events-cmd [rows]")); - assert!(stderr_usage.contains("curate-events --qm-filings")); - assert!(stderr_usage.contains("bench-curate-events-cmd [rows]")); - - // Minimal required flags with defaults - let action = parse_args(&to_args(&[ - "curate-events", - "--qm-filings", - "f.bson", - "--qm-earnings", - "e.bson", - "--provider-mapping", - "m.tsv", - "--out", - "out_dir", - "--filings-form-type-field", - "formtype", - ])) - .expect("minimal curate-events args"); - assert_eq!( - action, - CliAction::CurateEvents(CurateEventsArgs { - qm_filings: PathBuf::from("f.bson"), - qm_earnings: PathBuf::from("e.bson"), - provider_mapping: PathBuf::from("m.tsv"), - out_dir: PathBuf::from("out_dir"), - filings_key_field: DEFAULT_FILINGS_KEY_FIELD.to_string(), - filings_timefiled_field: DEFAULT_FILINGS_TIMEFILED_FIELD.to_string(), - filings_form_type_field: "formtype".to_string(), - filings_filing_id_field: None, - filings_url_field: None, - earnings_key_field: DEFAULT_EARNINGS_KEY_FIELD.to_string(), - earnings_report_date_field: DEFAULT_EARNINGS_REPORT_DATE_FIELD.to_string(), - earnings_announce_time_field: DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD.to_string(), - earnings_fiscal_period_end_field: None, - earnings_actual_eps_field: None, - earnings_revenue_field: None, - mapping_source: DEFAULT_EVENTS_MAPPING_SOURCE.to_string(), - }) - ); - - // Full custom flags via --flag=value - let full = parse_args(&to_args(&[ - "curate-events", - "--qm-filings=f2.bson", - "--qm-earnings=e2.bson", - "--provider-mapping=m2.tsv", - "--out=o2", - "--filings-key-field=qmSearchCode", - "--filings-timefiled-field=ts", - "--filings-form-type-field=form", - "--filings-filing-id-field=fid", - "--filings-url-field=docUrl", - "--earnings-key-field=symbol", - "--earnings-report-date-field=rDate", - "--earnings-announce-time-field=aTime", - "--earnings-fiscal-period-end-field=fpe", - "--earnings-actual-eps-field=eps", - "--earnings-revenue-field=rev", - "--mapping-source=qm_alt", - ])) - .expect("full curate-events args"); - assert_eq!( - full, - CliAction::CurateEvents(CurateEventsArgs { - qm_filings: PathBuf::from("f2.bson"), - qm_earnings: PathBuf::from("e2.bson"), - provider_mapping: PathBuf::from("m2.tsv"), - out_dir: PathBuf::from("o2"), - filings_key_field: "qmSearchCode".to_string(), - filings_timefiled_field: "ts".to_string(), - filings_form_type_field: "form".to_string(), - filings_filing_id_field: Some("fid".to_string()), - filings_url_field: Some("docUrl".to_string()), - earnings_key_field: "symbol".to_string(), - earnings_report_date_field: "rDate".to_string(), - earnings_announce_time_field: "aTime".to_string(), - earnings_fiscal_period_end_field: Some("fpe".to_string()), - earnings_actual_eps_field: Some("eps".to_string()), - earnings_revenue_field: Some("rev".to_string()), - mapping_source: "qm_alt".to_string(), - }) - ); - - // Missing required --filings-form-type-field - let err = parse_args(&to_args(&[ - "curate-events", - "--qm-filings", - "f.bson", - "--qm-earnings", - "e.bson", - "--provider-mapping", - "m.tsv", - "--out", - "out_dir", - ])) - .unwrap_err(); - assert!(err.contains("missing required flag '--filings-form-type-field'"), "{err}"); - - // Duplicate flag - let err = parse_args(&to_args(&[ - "curate-events", - "--qm-filings", - "f.bson", - "--qm-filings", - "f2.bson", - "--qm-earnings", - "e.bson", - "--provider-mapping", - "m.tsv", - "--out", - "out_dir", - "--filings-form-type-field", - "formtype", - ])) - .unwrap_err(); - assert!(err.contains("duplicate flag '--qm-filings'"), "{err}"); - - // Unknown flag - let err = parse_args(&to_args(&[ - "curate-events", - "--qm-filings", - "f.bson", - "--qm-earnings", - "e.bson", - "--provider-mapping", - "m.tsv", - "--out", - "out_dir", - "--filings-form-type-field", - "formtype", - "--nope", - "1", - ])) - .unwrap_err(); - assert!(err.contains("unknown flag '--nope'"), "{err}"); - - // Colliding field names - let err = parse_args(&to_args(&[ - "curate-events", - "--qm-filings", - "f.bson", - "--qm-earnings", - "e.bson", - "--provider-mapping", - "m.tsv", - "--out", - "out_dir", - "--filings-form-type-field", - "symbol", - ])) - .unwrap_err(); - assert!(err.contains("cannot share BSON field 'symbol'"), "{err}"); - - // Forbidden consensusEps - let err = parse_args(&to_args(&[ - "curate-events", - "--qm-filings", - "f.bson", - "--qm-earnings", - "e.bson", - "--provider-mapping", - "m.tsv", - "--out", - "out_dir", - "--filings-form-type-field", - "formtype", - "--earnings-actual-eps-field", - "consensusEps", - ])) - .unwrap_err(); - assert!(err.contains("consensusEps"), "{err}"); - - // bench-curate-events-cmd - assert_eq!( - parse_args(&to_args(&["bench-curate-events-cmd"])), - Ok(CliAction::BenchCurateEventsCmd( - DEFAULT_CURATE_EVENTS_CMD_BENCH_ROWS - )) - ); - assert_eq!( - parse_args(&to_args(&["bench-curate-events-cmd", "1000"])), - Ok(CliAction::BenchCurateEventsCmd(1_000)) - ); - assert!(parse_args(&to_args(&["bench-curate-events-cmd", "0"])).is_err()); - assert!(parse_args(&to_args(&["bench-curate-events-cmd", "abc"])).is_err()); - assert!(parse_args(&to_args(&["bench-curate-events-cmd", "1", "2"])).is_err()); - - // bench-ilp-bars-1m - assert_eq!( - parse_args(&to_args(&["bench-ilp-bars-1m"])), - Ok(CliAction::BenchIlpBars1m(DEFAULT_ILP_BARS_1M_BENCH_ROWS)) - ); - assert_eq!( - parse_args(&to_args(&["bench-ilp-bars-1m", "2500"])), - Ok(CliAction::BenchIlpBars1m(2_500)) - ); - assert!(parse_args(&to_args(&["bench-ilp-bars-1m", "0"])).is_err()); - assert!(parse_args(&to_args(&["bench-ilp-bars-1m", "-5"])).is_err()); - assert!(parse_args(&to_args(&["bench-ilp-bars-1m", "abc"])).is_err()); - assert!(parse_args(&to_args(&["bench-ilp-bars-1m", "1", "2"])).is_err()); - - // bench-fundamentals - assert_eq!( - parse_args(&to_args(&["bench-fundamentals"])), - Ok(CliAction::BenchFundamentals(DEFAULT_FUNDAMENTALS_BENCH_ROWS)) - ); - assert_eq!( - parse_args(&to_args(&["bench-fundamentals", "2500"])), - Ok(CliAction::BenchFundamentals(2_500)) - ); - assert!(parse_args(&to_args(&["bench-fundamentals", "0"])).is_err()); - assert!(parse_args(&to_args(&["bench-fundamentals", "abc"])).is_err()); - assert!(parse_args(&to_args(&["bench-fundamentals", "1", "2"])).is_err()); - } - - #[test] - fn parse_curate_bars_1m_valid_default_and_explicit_mapping_source() { - let parsed = parse_args(&to_args(&[ - "curate-bars-1m", - "--eod-intraday", - "intraday.bson", - "--qm-splits", - "splits.bson", - "--provider-mapping", - "mapping.tsv", - "--out", - "out_dir", - "--shards", - "4", - "--known-at-micros", - "1735689600000000", - ])) - .expect("valid curate-bars-1m args with default mapping source"); - - assert_eq!( - parsed, - CliAction::CurateBars1m(CurateBars1mArgs { - intraday_path: PathBuf::from("intraday.bson"), - splits_path: PathBuf::from("splits.bson"), - provider_mapping_path: PathBuf::from("mapping.tsv"), - out_dir: PathBuf::from("out_dir"), - mapping_source: DEFAULT_BARS_1M_MAPPING_SOURCE.to_string(), - shard_count: 4, - known_at_micros: 1_735_689_600_000_000, - stream_options: BsonStreamOptions::default(), - ilp_options: IlpWriterOptions::default(), - }) - ); - - let parsed_eq = parse_args(&to_args(&[ - "curate-bars-1m", - "--eod-intraday=i2.bson", - "--qm-splits=s2.bson", - "--provider-mapping=m2.tsv", - "--out=o2", - "--shards=2", - "--known-at-micros=9223372036854775807", - "--mapping-source=eod_alt", - ])) - .expect("valid curate-bars-1m args with equals form and explicit mapping source"); - - assert_eq!( - parsed_eq, - CliAction::CurateBars1m(CurateBars1mArgs { - intraday_path: PathBuf::from("i2.bson"), - splits_path: PathBuf::from("s2.bson"), - provider_mapping_path: PathBuf::from("m2.tsv"), - out_dir: PathBuf::from("o2"), - mapping_source: "eod_alt".to_string(), - shard_count: 2, - known_at_micros: i64::MAX, - stream_options: BsonStreamOptions::default(), - ilp_options: IlpWriterOptions::default(), - }) - ); - } - - #[test] - fn curate_bars_1m_usage_mentions_command_and_all_flags() { - let expected_flags = [ - "--eod-intraday", - "--qm-splits", - "--provider-mapping", - "--out", - "--shards", - "--known-at-micros", - "--mapping-source", - ]; - let usage = format_usage("curate-etl", "0.1.0"); - let usage_stderr = format_usage_stderr("curate-etl"); - let usage_line = usage - .lines() - .find(|line| line.trim_start().starts_with("curate-etl curate-bars-1m ")) - .expect("format_usage missing curate-bars-1m command line"); - let stderr_line = usage_stderr - .lines() - .find(|line| line.trim_start().starts_with("curate-etl curate-bars-1m ")) - .expect("format_usage_stderr missing curate-bars-1m command line"); - for flag in expected_flags { - assert!( - usage_line.contains(flag), - "format_usage curate-bars-1m line missing {flag}: {usage_line}" - ); - assert!( - stderr_line.contains(flag), - "format_usage_stderr curate-bars-1m line missing {flag}: {stderr_line}" - ); - } - } - - #[test] - fn parse_curate_bars_1m_rejects_missing_required_flags() { - let required: [(&str, &str); 6] = [ - ("--eod-intraday", "intraday.bson"), - ("--qm-splits", "splits.bson"), - ("--provider-mapping", "mapping.tsv"), - ("--out", "out_dir"), - ("--shards", "2"), - ("--known-at-micros", "1735689600000000"), - ]; - - for omit in 0..required.len() { - let mut argv: Vec<&str> = vec!["curate-bars-1m"]; - for (idx, &(flag, val)) in required.iter().enumerate() { - if idx != omit { - argv.push(flag); - argv.push(val); - } - } - let err = parse_args(&to_args(&argv)).unwrap_err(); - let missing_flag = required[omit].0; - assert!( - err.contains(&format!("missing required flag '{missing_flag}'")), - "expected missing required flag '{missing_flag}', got: {err}" - ); - } - } - - #[test] - fn parse_curate_bars_1m_rejects_duplicates_empty_missing_value_unknown_and_positional() { - let base = [ - "curate-bars-1m", - "--eod-intraday", - "i.bson", - "--qm-splits", - "s.bson", - "--provider-mapping", - "m.tsv", - "--out", - "o", - "--shards", - "2", - "--known-at-micros", - "1000", - "--mapping-source", - "eod", - ]; - - // Duplicate flags (path, numeric, and name). - for (flag, extra_val) in [ - ("--eod-intraday", "i2.bson"), - ("--qm-splits", "s2.bson"), - ("--provider-mapping", "m2.tsv"), - ("--out", "o2"), - ("--shards", "3"), - ("--known-at-micros", "2000"), - ("--mapping-source", "eod"), - ] { - let mut argv = base.to_vec(); - argv.push(flag); - argv.push(extra_val); - let err = parse_args(&to_args(&argv)).unwrap_err(); - assert!( - err.contains(&format!("duplicate flag '{flag}'")), - "expected duplicate error for {flag}, got: {err}" - ); - } - - // Empty values via --flag= and whitespace-only --mapping-source. - for flag in [ - "--eod-intraday", - "--qm-splits", - "--provider-mapping", - "--out", - "--shards", - "--known-at-micros", - "--mapping-source", - ] { - let empty_token = format!("{flag}="); - let err = parse_args(&to_args(&["curate-bars-1m", &empty_token])).unwrap_err(); - assert!( - err.contains(&format!("empty value for flag '{flag}'")), - "expected empty value error for {flag}, got: {err}" - ); - } - let err = parse_args(&to_args(&["curate-bars-1m", "--mapping-source", " "])).unwrap_err(); - assert!( - err.contains("empty value for flag '--mapping-source'"), - "{err}" - ); - - // Flag at end of input or followed by another flag. - let err = parse_args(&to_args(&["curate-bars-1m", "--eod-intraday"])).unwrap_err(); - assert!( - err.contains("missing value for flag '--eod-intraday'"), - "{err}" - ); - let err = parse_args(&to_args(&[ - "curate-bars-1m", - "--shards", - "--out", - "o", - ])) - .unwrap_err(); - assert!(err.contains("missing value for flag '--shards'"), "{err}"); - - // Unknown flag. - let mut unknown = base.to_vec(); - unknown.push("--nope"); - unknown.push("1"); - let err = parse_args(&to_args(&unknown)).unwrap_err(); - assert!( - err.contains("unknown flag '--nope' for curate-bars-1m"), - "{err}" - ); - - // Positional argument. - let err = parse_args(&to_args(&["curate-bars-1m", "positional"])).unwrap_err(); - assert!( - err.contains("unexpected positional argument 'positional' for curate-bars-1m"), - "{err}" - ); - } - - #[test] - fn parse_curate_bars_1m_rejects_invalid_numeric_flags() { - let base_without_shards = [ - "curate-bars-1m", - "--eod-intraday", - "i.bson", - "--qm-splits", - "s.bson", - "--provider-mapping", - "m.tsv", - "--out", - "o", - "--known-at-micros", - "1000", - ]; - - for bad_shards in [ - "0", - "-1", - "+1", - "abc", - "1.5", - "999999999999999999999999999999999999999", - ] { - let mut argv = base_without_shards.to_vec(); - argv.push("--shards"); - argv.push(bad_shards); - let err = parse_args(&to_args(&argv)).unwrap_err(); - assert!( - err.contains("invalid --shards"), - "expected invalid --shards for '{bad_shards}', got: {err}" - ); - } - - let base_without_known_at = [ - "curate-bars-1m", - "--eod-intraday", - "i.bson", - "--qm-splits", - "s.bson", - "--provider-mapping", - "m.tsv", - "--out", - "o", - "--shards", - "2", - ]; - - for bad_known_at in [ - "0", - "-1", - "-9223372036854775808", - "+1000", - "abc", - "1.5", - "9223372036854775808", - "999999999999999999999999999999", - ] { - let mut argv = base_without_known_at.to_vec(); - argv.push("--known-at-micros"); - argv.push(bad_known_at); - let err = parse_args(&to_args(&argv)).unwrap_err(); - assert!( - err.contains("invalid --known-at-micros"), - "expected invalid --known-at-micros for '{bad_known_at}', got: {err}" - ); - } - } - - #[test] - fn parse_curate_bars_1m_rejects_all_mongo_streaming_flags_without_echoing_values() { - let mongo_flags = [ - "--from-mongo", - "--mongo-uri", - "--mongo-uri-env", - "--batch-size", - "--limit", - "--date-gte", - "--date-lt", - "--with-qm-prices", - ]; - - let secret = "mongodb://user:s3cr3t_pw@localhost:27017/stock"; - for flag in mongo_flags { - // Bare form (at end of argv). - let err_bare = parse_args(&to_args(&["curate-bars-1m", flag])).unwrap_err(); - assert!( - err_bare.contains(flag) && err_bare.contains("file mode only"), - "bare {flag} should fail with file-mode error, got: {err_bare}" - ); - - // Separated value form. - let err_sep = parse_args(&to_args(&["curate-bars-1m", flag, secret])).unwrap_err(); - assert!( - err_sep.contains(flag) && err_sep.contains("file mode only"), - "separated {flag} should fail with file-mode error, got: {err_sep}" - ); - assert!( - !err_sep.contains("s3cr3t_pw"), - "separated {flag} error leaked value: {err_sep}" - ); - - // Equals form. - let eq_token = format!("{flag}={secret}"); - let err_eq = parse_args(&to_args(&["curate-bars-1m", &eq_token])).unwrap_err(); - assert!( - err_eq.contains(flag) && err_eq.contains("file mode only"), - "equals {flag} should fail with file-mode error, got: {err_eq}" - ); - assert!( - !err_eq.contains("s3cr3t_pw"), - "equals {flag} error leaked value: {err_eq}" - ); - } - } - - #[test] - fn parse_curate_qm_bars_1m_valid_default_and_explicit_mapping_source() { - let parsed = parse_args(&to_args(&[ - "curate-qm-bars-1m", - "--qm-intraday", - "qm_intraday.bson", - "--provider-mapping", - "mapping.tsv", - "--out", - "out_dir", - "--shards", - "4", - "--known-at-micros", - "1735689600000000", - ])) - .expect("valid curate-qm-bars-1m args with default mapping source"); - - assert_eq!( - parsed, - CliAction::CurateQmBars1m(CurateQmBars1mArgs { - intraday_path: PathBuf::from("qm_intraday.bson"), - provider_mapping_path: PathBuf::from("mapping.tsv"), - out_dir: PathBuf::from("out_dir"), - mapping_source: DEFAULT_QM_BARS_1M_MAPPING_SOURCE.to_string(), - shard_count: 4, - known_at_micros: 1_735_689_600_000_000, - stream_options: BsonStreamOptions::default(), - ilp_options: IlpWriterOptions::default(), - }) - ); - assert_eq!(DEFAULT_QM_BARS_1M_MAPPING_SOURCE, "qm"); - - let parsed_eq = parse_args(&to_args(&[ - "curate-qm-bars-1m", - "--qm-intraday=i2.bson", - "--provider-mapping=m2.tsv", - "--out=o2", - "--shards=2", - "--known-at-micros=9223372036854775807", - "--mapping-source=qm_alt", - ])) - .expect("valid curate-qm-bars-1m args with equals form and explicit mapping source"); - - assert_eq!( - parsed_eq, - CliAction::CurateQmBars1m(CurateQmBars1mArgs { - intraday_path: PathBuf::from("i2.bson"), - provider_mapping_path: PathBuf::from("m2.tsv"), - out_dir: PathBuf::from("o2"), - mapping_source: "qm_alt".to_string(), - shard_count: 2, - known_at_micros: i64::MAX, - stream_options: BsonStreamOptions::default(), - ilp_options: IlpWriterOptions::default(), - }) - ); - } - - #[test] - fn curate_qm_bars_1m_usage_mentions_command_and_all_flags() { - let expected_flags = [ - "--qm-intraday", - "--provider-mapping", - "--out", - "--shards", - "--known-at-micros", - "--mapping-source", - ]; - let usage = format_usage("curate-etl", "0.1.0"); - let usage_stderr = format_usage_stderr("curate-etl"); - let usage_line = usage - .lines() - .find(|line| line.trim_start().starts_with("curate-etl curate-qm-bars-1m ")) - .expect("format_usage missing curate-qm-bars-1m command line"); - let stderr_line = usage_stderr - .lines() - .find(|line| line.trim_start().starts_with("curate-etl curate-qm-bars-1m ")) - .expect("format_usage_stderr missing curate-qm-bars-1m command line"); - for flag in expected_flags { - assert!( - usage_line.contains(flag), - "format_usage curate-qm-bars-1m line missing {flag}: {usage_line}" - ); - assert!( - stderr_line.contains(flag), - "format_usage_stderr curate-qm-bars-1m line missing {flag}: {stderr_line}" - ); - } - assert!( - !usage_line.contains("--qm-splits"), - "format_usage curate-qm-bars-1m line must not list --qm-splits: {usage_line}" - ); - assert!( - !stderr_line.contains("--qm-splits"), - "format_usage_stderr curate-qm-bars-1m line must not list --qm-splits: {stderr_line}" - ); - } - - #[test] - fn parse_curate_qm_bars_1m_rejects_missing_required_flags() { - let required: [(&str, &str); 5] = [ - ("--qm-intraday", "qm_intraday.bson"), - ("--provider-mapping", "mapping.tsv"), - ("--out", "out_dir"), - ("--shards", "2"), - ("--known-at-micros", "1735689600000000"), - ]; - - for omit in 0..required.len() { - let mut argv: Vec<&str> = vec!["curate-qm-bars-1m"]; - for (idx, &(flag, val)) in required.iter().enumerate() { - if idx != omit { - argv.push(flag); - argv.push(val); - } - } - let err = parse_args(&to_args(&argv)).unwrap_err(); - let missing_flag = required[omit].0; - assert!( - err.contains(&format!("missing required flag '{missing_flag}'")), - "expected missing required flag '{missing_flag}', got: {err}" - ); - } - } - - #[test] - fn parse_curate_qm_bars_1m_rejects_duplicates_empty_missing_value_unknown_and_positional() { - let base = [ - "curate-qm-bars-1m", - "--qm-intraday", - "i.bson", - "--provider-mapping", - "m.tsv", - "--out", - "o", - "--shards", - "2", - "--known-at-micros", - "1000", - "--mapping-source", - "qm", - ]; - - // Duplicate flags (path, numeric, and name). - for (flag, extra_val) in [ - ("--qm-intraday", "i2.bson"), - ("--provider-mapping", "m2.tsv"), - ("--out", "o2"), - ("--shards", "3"), - ("--known-at-micros", "2000"), - ("--mapping-source", "qm"), - ] { - let mut argv = base.to_vec(); - argv.push(flag); - argv.push(extra_val); - let err = parse_args(&to_args(&argv)).unwrap_err(); - assert!( - err.contains(&format!("duplicate flag '{flag}'")), - "expected duplicate error for {flag}, got: {err}" - ); - } - - // Empty values via --flag= and whitespace-only --mapping-source. - for flag in [ - "--qm-intraday", - "--provider-mapping", - "--out", - "--shards", - "--known-at-micros", - "--mapping-source", - ] { - let empty_token = format!("{flag}="); - let err = parse_args(&to_args(&["curate-qm-bars-1m", &empty_token])).unwrap_err(); - assert!( - err.contains(&format!("empty value for flag '{flag}'")), - "expected empty value error for {flag}, got: {err}" - ); - } - let err = - parse_args(&to_args(&["curate-qm-bars-1m", "--mapping-source", " "])).unwrap_err(); - assert!( - err.contains("empty value for flag '--mapping-source'"), - "{err}" - ); - - // Flag at end of input or followed by another flag. - let err = parse_args(&to_args(&["curate-qm-bars-1m", "--qm-intraday"])).unwrap_err(); - assert!( - err.contains("missing value for flag '--qm-intraday'"), - "{err}" - ); - let err = parse_args(&to_args(&[ - "curate-qm-bars-1m", - "--shards", - "--out", - "o", - ])) - .unwrap_err(); - assert!(err.contains("missing value for flag '--shards'"), "{err}"); - - // Unknown flags (including curate-bars-1m-only flags --qm-splits and --eod-intraday), - // both with a value and bare (without consuming a value first). - for unknown_flag in ["--nope", "--qm-splits", "--eod-intraday"] { - let mut unknown = base.to_vec(); - unknown.push(unknown_flag); - unknown.push("x"); - let err = parse_args(&to_args(&unknown)).unwrap_err(); - assert!( - err.contains(&format!("unknown flag '{unknown_flag}' for curate-qm-bars-1m")), - "expected unknown flag error for {unknown_flag}, got: {err}" - ); - - let err_bare = parse_args(&to_args(&["curate-qm-bars-1m", unknown_flag])).unwrap_err(); - assert!( - err_bare.contains(&format!("unknown flag '{unknown_flag}' for curate-qm-bars-1m")), - "expected unknown flag error for bare {unknown_flag}, got: {err_bare}" - ); - } - - // Positional argument. - let err = parse_args(&to_args(&["curate-qm-bars-1m", "positional"])).unwrap_err(); - assert!( - err.contains("unexpected positional argument 'positional' for curate-qm-bars-1m"), - "{err}" - ); - - // Multiline error sanitization (CR/LF escaped to single line). - let err = parse_args(&to_args(&["curate-qm-bars-1m", "bad\r\narg"])).unwrap_err(); - assert!( - !err.contains('\r') && !err.contains('\n'), - "error must be single-line: {err:?}" - ); - assert!(err.contains("bad\\r\\narg"), "expected escaped CR/LF: {err}"); - } - - #[test] - fn parse_curate_qm_bars_1m_rejects_invalid_numeric_flags() { - let base_without_shards = [ - "curate-qm-bars-1m", - "--qm-intraday", - "i.bson", - "--provider-mapping", - "m.tsv", - "--out", - "o", - "--known-at-micros", - "1000", - ]; - - for bad_shards in [ - "0", - "-1", - "+1", - "abc", - "1.5", - "999999999999999999999999999999999999999", - ] { - let mut argv = base_without_shards.to_vec(); - argv.push("--shards"); - argv.push(bad_shards); - let err = parse_args(&to_args(&argv)).unwrap_err(); - assert!( - err.contains("invalid --shards"), - "expected invalid --shards for '{bad_shards}', got: {err}" - ); - } - - let base_without_known_at = [ - "curate-qm-bars-1m", - "--qm-intraday", - "i.bson", - "--provider-mapping", - "m.tsv", - "--out", - "o", - "--shards", - "2", - ]; - - for bad_known_at in [ - "0", - "-1", - "-9223372036854775808", - "+1000", - "abc", - "1.5", - "9223372036854775808", - "999999999999999999999999999999", - ] { - let mut argv = base_without_known_at.to_vec(); - argv.push("--known-at-micros"); - argv.push(bad_known_at); - let err = parse_args(&to_args(&argv)).unwrap_err(); - assert!( - err.contains("invalid --known-at-micros"), - "expected invalid --known-at-micros for '{bad_known_at}', got: {err}" - ); - } - } - - #[test] - fn parse_curate_qm_bars_1m_rejects_all_mongo_streaming_flags_without_echoing_values() { - let mongo_flags = [ - "--from-mongo", - "--mongo-uri", - "--mongo-uri-env", - "--batch-size", - "--limit", - "--date-gte", - "--date-lt", - "--with-qm-prices", - ]; - - let secret = "mongodb://user:s3cr3t_pw@localhost:27017/stock"; - for flag in mongo_flags { - // Bare form (at end of argv). - let err_bare = parse_args(&to_args(&["curate-qm-bars-1m", flag])).unwrap_err(); - assert!( - err_bare.contains(flag) && err_bare.contains("file mode only"), - "bare {flag} should fail with file-mode error, got: {err_bare}" - ); - assert!( - !err_bare.contains('\r') && !err_bare.contains('\n'), - "bare {flag} error must be single-line: {err_bare:?}" - ); - - // Separated value form. - let err_sep = parse_args(&to_args(&["curate-qm-bars-1m", flag, secret])).unwrap_err(); - assert!( - err_sep.contains(flag) && err_sep.contains("file mode only"), - "separated {flag} should fail with file-mode error, got: {err_sep}" - ); - assert!( - !err_sep.contains("s3cr3t_pw"), - "separated {flag} error leaked value: {err_sep}" - ); - - // Equals form. - let eq_token = format!("{flag}={secret}"); - let err_eq = parse_args(&to_args(&["curate-qm-bars-1m", &eq_token])).unwrap_err(); - assert!( - err_eq.contains(flag) && err_eq.contains("file mode only"), - "equals {flag} should fail with file-mode error, got: {err_eq}" - ); - assert!( - !err_eq.contains("s3cr3t_pw"), - "equals {flag} error leaked value: {err_eq}" - ); - } - } - - #[test] - fn parse_curate_fx_1m_valid_space_and_equals_forms() { - let expected = CliAction::CurateFx1m(CurateFx1mArgs { - intraday_path: PathBuf::from("A"), - out_dir: PathBuf::from("B"), - shard_count: 4, - stream_options: BsonStreamOptions::default(), - ilp_options: IlpWriterOptions::default(), - }); - - let parsed_space = parse_args(&to_args(&[ - "curate-fx-1m", - "--eod-intraday", - "A", - "--out", - "B", - "--shards", - "4", - ])) - .expect("valid curate-fx-1m args in space form"); - assert_eq!(parsed_space, expected); - - let parsed_eq = parse_args(&to_args(&[ - "curate-fx-1m", - "--eod-intraday=A", - "--out=B", - "--shards=4", - ])) - .expect("valid curate-fx-1m args in equals form"); - assert_eq!(parsed_eq, expected); - } - - #[test] - fn curate_fx_1m_usage_mentions_command_and_all_flags() { - let expected_flags = ["--eod-intraday", "--out", "--shards"]; - let usage = format_usage("curate-etl", "0.1.0"); - let usage_stderr = format_usage_stderr("curate-etl"); - let usage_line = usage - .lines() - .find(|line| line.trim_start().starts_with("curate-etl curate-fx-1m ")) - .expect("format_usage missing curate-fx-1m command line"); - let stderr_line = usage_stderr - .lines() - .find(|line| line.trim_start().starts_with("curate-etl curate-fx-1m ")) - .expect("format_usage_stderr missing curate-fx-1m command line"); - for flag in expected_flags { - assert!( - usage_line.contains(flag), - "format_usage curate-fx-1m line missing {flag}: {usage_line}" - ); - assert!( - stderr_line.contains(flag), - "format_usage_stderr curate-fx-1m line missing {flag}: {stderr_line}" - ); - } - } - - #[test] - fn parse_curate_fx_1m_rejects_missing_required_flags() { - let required: [(&str, &str); 3] = [ - ("--eod-intraday", "intraday.bson"), - ("--out", "out_dir"), - ("--shards", "4"), - ]; - - for omit in 0..required.len() { - let mut argv: Vec<&str> = vec!["curate-fx-1m"]; - for (idx, &(flag, val)) in required.iter().enumerate() { - if idx != omit { - argv.push(flag); - argv.push(val); - } - } - let err = parse_args(&to_args(&argv)).unwrap_err(); - let missing_flag = required[omit].0; - assert!( - err.contains(&format!("missing required flag '{missing_flag}'")), - "expected missing required flag '{missing_flag}', got: {err}" - ); - } - } - - #[test] - fn parse_curate_fx_1m_rejects_duplicates_empty_missing_value_unknown_and_positional() { - let base = [ - "curate-fx-1m", - "--eod-intraday", - "i.bson", - "--out", - "o", - "--shards", - "4", - ]; - - // Duplicate flags (path and numeric). - for (flag, extra_val) in [ - ("--eod-intraday", "i2.bson"), - ("--out", "o2"), - ("--shards", "2"), - ] { - let mut argv = base.to_vec(); - argv.push(flag); - argv.push(extra_val); - let err = parse_args(&to_args(&argv)).unwrap_err(); - assert!( - err.contains(&format!("duplicate flag '{flag}'")), - "expected duplicate error for {flag}, got: {err}" - ); - } - - // Empty values via --flag=. - for flag in ["--eod-intraday", "--out", "--shards"] { - let empty_token = format!("{flag}="); - let err = parse_args(&to_args(&["curate-fx-1m", &empty_token])).unwrap_err(); - assert!( - err.contains(&format!("empty value for flag '{flag}'")), - "expected empty value error for {flag}, got: {err}" - ); - } - - // Flag at end of input or followed by another flag. - let err = parse_args(&to_args(&["curate-fx-1m", "--eod-intraday"])).unwrap_err(); - assert!( - err.contains("missing value for flag '--eod-intraday'"), - "{err}" - ); - let err = parse_args(&to_args(&["curate-fx-1m", "--shards", "--out", "o"])).unwrap_err(); - assert!(err.contains("missing value for flag '--shards'"), "{err}"); - - // Unknown flag. - let mut unknown = base.to_vec(); - unknown.push("--nope"); - unknown.push("1"); - let err = parse_args(&to_args(&unknown)).unwrap_err(); - assert!( - err.contains("unknown flag '--nope' for curate-fx-1m"), - "{err}" - ); - - // Bars-only flags must be rejected as unknown flags. - for (flag, val) in [ - ("--qm-splits", "splits.bson"), - ("--provider-mapping", "mapping.tsv"), - ("--known-at-micros", "1735689600000000"), - ("--mapping-source", "eod"), - ] { - let mut argv = base.to_vec(); - argv.push(flag); - argv.push(val); - let err = parse_args(&to_args(&argv)).unwrap_err(); - assert!( - err.contains(&format!("unknown flag '{flag}' for curate-fx-1m")), - "expected unknown flag error for {flag}, got: {err}" - ); - } - - // Positional argument. - let err = parse_args(&to_args(&["curate-fx-1m", "positional"])).unwrap_err(); - assert!( - err.contains("unexpected positional argument 'positional' for curate-fx-1m"), - "{err}" - ); - } - - #[test] - fn parse_curate_fx_1m_rejects_invalid_shards() { - let base_without_shards = [ - "curate-fx-1m", - "--eod-intraday", - "i.bson", - "--out", - "o", - ]; - - for bad_shards in [ - "0", - "-1", - "+1", - "1.5", - "abc", - "999999999999999999999999999999999999999", - ] { - let mut argv = base_without_shards.to_vec(); - argv.push("--shards"); - argv.push(bad_shards); - let err = parse_args(&to_args(&argv)).unwrap_err(); - assert!( - err.contains("invalid --shards"), - "expected invalid --shards for '{bad_shards}', got: {err}" - ); - } - } - - #[test] - fn parse_curate_fx_1m_rejects_all_mongo_streaming_flags_without_echoing_values() { - let mongo_flags = [ - "--from-mongo", - "--mongo-uri", - "--mongo-uri-env", - "--batch-size", - "--limit", - "--date-gte", - "--date-lt", - "--with-qm-prices", - ]; - - let secret = "mongodb://user:s3cr3t_pw@localhost:27017/stock"; - for flag in mongo_flags { - let expected = format!( - "MongoDB streaming flag '{flag}' is not supported by curate-fx-1m (file mode only)" - ); - - // Bare form (at end of argv). - let err_bare = parse_args(&to_args(&["curate-fx-1m", flag])).unwrap_err(); - assert_eq!(err_bare, expected, "bare {flag} error mismatch"); - - // Separated value form. - let err_sep = parse_args(&to_args(&["curate-fx-1m", flag, secret])).unwrap_err(); - assert_eq!(err_sep, expected, "separated {flag} error mismatch"); - assert!( - !err_sep.contains("s3cr3t_pw"), - "separated {flag} error leaked value: {err_sep}" - ); - - // Equals form. - let eq_token = format!("{flag}={secret}"); - let err_eq = parse_args(&to_args(&["curate-fx-1m", &eq_token])).unwrap_err(); - assert_eq!(err_eq, expected, "equals {flag} error mismatch"); - assert!( - !err_eq.contains("s3cr3t_pw"), - "equals {flag} error leaked value: {err_eq}" - ); - } - } - - #[test] - fn curate_posts_parsing_validation_and_usage() { - let usage = format_usage("curate-etl", "0.1.0"); - let stderr_usage = format_usage_stderr("curate-etl"); - assert!(usage.contains("curate-posts --ceo-posts")); - assert!(stderr_usage.contains("curate-posts --ceo-posts")); - - // Minimal valid invocation with --timestamp-unit seconds fills all 8 defaults - assert_eq!( - parse_args(&to_args(&[ - "curate-posts", - "--ceo-posts", - "posts.bson", - "--provider-mapping", - "map.tsv", - "--out", - "posts_out", - "--timestamp-unit", - "seconds", - ])), - Ok(CliAction::CuratePosts(CuratePostsArgs { - ceo_posts: PathBuf::from("posts.bson"), - provider_mapping: PathBuf::from("map.tsv"), - out_dir: PathBuf::from("posts_out"), - timestamp_unit: CeoPostsTimestampUnit::Seconds, - key_field: "ceoId".to_string(), - spiel_id_field: "spielId".to_string(), - timestamp_field: "timestamp".to_string(), - edited_field: "edited".to_string(), - bot_field: "bot".to_string(), - user_id_field: "userId".to_string(), - text_field: "spiel".to_string(), - mapping_source: "ceo".to_string(), - })) - ); - - // Minimal valid invocation with --timestamp-unit millis - assert_eq!( - parse_args(&to_args(&[ - "curate-posts", - "--ceo-posts", - "posts.bson", - "--provider-mapping", - "map.tsv", - "--out", - "posts_out", - "--timestamp-unit", - "millis", - ])), - Ok(CliAction::CuratePosts(CuratePostsArgs { - ceo_posts: PathBuf::from("posts.bson"), - provider_mapping: PathBuf::from("map.tsv"), - out_dir: PathBuf::from("posts_out"), - timestamp_unit: CeoPostsTimestampUnit::Millis, - key_field: DEFAULT_POSTS_KEY_FIELD.to_string(), - spiel_id_field: DEFAULT_POSTS_SPIEL_ID_FIELD.to_string(), - timestamp_field: DEFAULT_POSTS_TIMESTAMP_FIELD.to_string(), - edited_field: DEFAULT_POSTS_EDITED_FIELD.to_string(), - bot_field: DEFAULT_POSTS_BOT_FIELD.to_string(), - user_id_field: DEFAULT_POSTS_USER_ID_FIELD.to_string(), - text_field: DEFAULT_POSTS_TEXT_FIELD.to_string(), - mapping_source: DEFAULT_POSTS_MAPPING_SOURCE.to_string(), - })) - ); - - // All 8 optional flags overridden using --flag=value syntax - assert_eq!( - parse_args(&to_args(&[ - "curate-posts", - "--ceo-posts=p2.bson", - "--provider-mapping=m2.tsv", - "--out=o2", - "--timestamp-unit=millis", - "--key-field=channel", - "--spiel-id-field=postId", - "--timestamp-field=createdAt", - "--edited-field=updatedAt", - "--bot-field=isBot", - "--user-id-field=authorId", - "--text-field=body", - "--mapping-source=ceo_alt", - ])), - Ok(CliAction::CuratePosts(CuratePostsArgs { - ceo_posts: PathBuf::from("p2.bson"), - provider_mapping: PathBuf::from("m2.tsv"), - out_dir: PathBuf::from("o2"), - timestamp_unit: CeoPostsTimestampUnit::Millis, - key_field: "channel".to_string(), - spiel_id_field: "postId".to_string(), - timestamp_field: "createdAt".to_string(), - edited_field: "updatedAt".to_string(), - bot_field: "isBot".to_string(), - user_id_field: "authorId".to_string(), - text_field: "body".to_string(), - mapping_source: "ceo_alt".to_string(), - })) - ); - - // Each missing required flag errors - for (missing_flag, args) in [ - ( - "--ceo-posts", - &[ - "curate-posts", - "--provider-mapping", - "m.tsv", - "--out", - "o", - "--timestamp-unit", - "seconds", - ][..], - ), - ( - "--provider-mapping", - &[ - "curate-posts", - "--ceo-posts", - "p.bson", - "--out", - "o", - "--timestamp-unit", - "seconds", - ][..], - ), - ( - "--out", - &[ - "curate-posts", - "--ceo-posts", - "p.bson", - "--provider-mapping", - "m.tsv", - "--timestamp-unit", - "seconds", - ][..], - ), - ( - "--timestamp-unit", - &[ - "curate-posts", - "--ceo-posts", - "p.bson", - "--provider-mapping", - "m.tsv", - "--out", - "o", - ][..], - ), - ] { - let err = parse_args(&to_args(args)).unwrap_err(); - assert!( - err.contains(&format!("missing required flag '{missing_flag}'")), - "expected missing {missing_flag}, got: {err}" - ); - } - - // Invalid --timestamp-unit values - for bad_unit in ["", " ", "ms", "sec", "SECONDS", "MILLIS", "micros"] { - let err = parse_args(&to_args(&[ - "curate-posts", - "--ceo-posts", - "p.bson", - "--provider-mapping", - "m.tsv", - "--out", - "o", - "--timestamp-unit", - bad_unit, - ])) - .unwrap_err(); - assert!( - err.contains("invalid --timestamp-unit"), - "expected invalid --timestamp-unit for '{bad_unit}', got: {err}" - ); - } - - // Missing flag value (at end and followed by --flag) - let err = parse_args(&to_args(&["curate-posts", "--ceo-posts"])).unwrap_err(); - assert!(err.contains("missing value for flag '--ceo-posts'"), "{err}"); - - let err = parse_args(&to_args(&[ - "curate-posts", - "--ceo-posts", - "--provider-mapping", - "m.tsv", - "--out", - "o", - "--timestamp-unit", - "seconds", - ])) - .unwrap_err(); - assert!(err.contains("missing value for flag '--ceo-posts'"), "{err}"); - - // Duplicate flags including --timestamp-unit - for (dup_flag, args) in [ - ( - "--ceo-posts", - &[ - "curate-posts", - "--ceo-posts", - "a.bson", - "--ceo-posts=b.bson", - "--provider-mapping", - "m.tsv", - "--out", - "o", - "--timestamp-unit", - "seconds", - ][..], - ), - ( - "--timestamp-unit", - &[ - "curate-posts", - "--ceo-posts", - "a.bson", - "--provider-mapping", - "m.tsv", - "--out", - "o", - "--timestamp-unit", - "seconds", - "--timestamp-unit=millis", - ][..], - ), - ( - "--key-field", - &[ - "curate-posts", - "--ceo-posts", - "a.bson", - "--provider-mapping", - "m.tsv", - "--out", - "o", - "--timestamp-unit", - "seconds", - "--key-field", - "k1", - "--key-field=k2", - ][..], - ), - ] { - let err = parse_args(&to_args(args)).unwrap_err(); - assert!( - err.contains(&format!("duplicate flag '{dup_flag}'")), - "expected duplicate {dup_flag}, got: {err}" - ); - } - - // Unknown flags and --from-mongo (bare, followed by other flags, or with =) - let err = parse_args(&to_args(&[ - "curate-posts", - "--ceo-posts", - "p.bson", - "--provider-mapping", - "m.tsv", - "--out", - "o", - "--timestamp-unit", - "seconds", - "--bogus", - "1", - ])) - .unwrap_err(); - assert_eq!(err, "unknown flag '--bogus' for curate-posts"); - - for from_mongo_args in [ - &["curate-posts", "--from-mongo"][..], - &[ - "curate-posts", - "--from-mongo", - "--provider-mapping", - "m.tsv", - "--out", - "o", - "--timestamp-unit", - "seconds", - ][..], - &["curate-posts", "--from-mongo=true"][..], - ] { - let err = parse_args(&to_args(from_mongo_args)).unwrap_err(); - assert_eq!(err, "unknown flag '--from-mongo' for curate-posts"); - } - - // Positional argument rejected - let err = parse_args(&to_args(&[ - "curate-posts", - "extra", - "--ceo-posts", - "p.bson", - "--provider-mapping", - "m.tsv", - "--out", - "o", - "--timestamp-unit", - "seconds", - ])) - .unwrap_err(); - assert_eq!(err, "unexpected positional argument 'extra' for curate-posts"); - - // Empty / blank field names and path values rejected - let err = parse_args(&to_args(&[ - "curate-posts", - "--ceo-posts=", - "--provider-mapping", - "m.tsv", - "--out", - "o", - "--timestamp-unit", - "seconds", - ])) - .unwrap_err(); - assert!(err.contains("empty value for flag '--ceo-posts'"), "{err}"); - - let err = parse_args(&to_args(&[ - "curate-posts", - "--ceo-posts", - "p.bson", - "--provider-mapping", - "m.tsv", - "--out", - "o", - "--timestamp-unit", - "seconds", - "--text-field", - " ", - ])) - .unwrap_err(); - assert!(err.contains("empty value for flag '--text-field'"), "{err}"); - - let err = parse_args(&to_args(&[ - "curate-posts", - "--ceo-posts", - "p.bson", - "--provider-mapping", - "m.tsv", - "--out", - "o", - "--timestamp-unit", - "seconds", - "--mapping-source", - " ", - ])) - .unwrap_err(); - assert!( - err.contains("empty value for flag '--mapping-source'"), - "{err}" - ); - - // Role collisions after defaults are applied - let err = parse_args(&to_args(&[ - "curate-posts", - "--ceo-posts", - "p.bson", - "--provider-mapping", - "m.tsv", - "--out", - "o", - "--timestamp-unit", - "seconds", - "--text-field", - "ceoId", - ])) - .unwrap_err(); - assert!(err.contains("cannot share BSON field 'ceoId'"), "{err}"); - - let err = parse_args(&to_args(&[ - "curate-posts", - "--ceo-posts", - "p.bson", - "--provider-mapping", - "m.tsv", - "--out", - "o", - "--timestamp-unit", - "seconds", - "--bot-field", - "shared", - "--user-id-field", - "shared", - ])) - .unwrap_err(); - assert!(err.contains("cannot share BSON field 'shared'"), "{err}"); - } - - #[test] - fn curate_fundamentals_parsing_validation_and_usage() { - let usage = format_usage("curate-etl", "0.1.0"); - let stderr_usage = format_usage_stderr("curate-etl"); - for text in [&usage, &stderr_usage] { - assert!(text.contains("curate-fundamentals --qm-financials"), "{text}"); - assert!(text.contains("--fiscal-period "), "{text}"); - assert!(text.contains("--quarterly-tokens"), "{text}"); - assert!(text.contains("--annual-tokens"), "{text}"); - } - - // Minimal valid invocation with --fiscal-period quarterly fills all verified defaults and None metrics - assert_eq!( - parse_args(&to_args(&[ - "curate-fundamentals", - "--qm-financials", - "fin.bson", - "--qm-filings", - "fil.bson", - "--provider-mapping", - "map.tsv", - "--listing-venues", - "venues.tsv", - "--out", - "fund_out", - "--currency-field", - "currency", - "--filings-form-type-field", - "formType", - "--k", - "4", - "--fiscal-period", - "quarterly", - ])), - Ok(CliAction::CurateFundamentals(CurateFundamentalsArgs { - qm_financials: PathBuf::from("fin.bson"), - qm_filings: PathBuf::from("fil.bson"), - provider_mapping: PathBuf::from("map.tsv"), - listing_venues: PathBuf::from("venues.tsv"), - out_dir: PathBuf::from("fund_out"), - financials_key_field: DEFAULT_QM_FINANCIALS_KEY_FIELD.to_string(), - financials_period_end_field: DEFAULT_QM_FINANCIALS_PERIOD_END_FIELD.to_string(), - financials_report_date_field: DEFAULT_QM_FINANCIALS_REPORT_DATE_FIELD.to_string(), - financials_report_period_field: DEFAULT_QM_FINANCIALS_REPORT_PERIOD_FIELD - .to_string(), - financials_currency_field: "currency".to_string(), - financials_revenue_field: None, - financials_net_income_field: None, - financials_operating_cash_flow_field: None, - financials_total_assets_field: None, - financials_total_equity_field: None, - financials_shares_outstanding_field: None, - fiscal_period: CurateFundamentalsFiscalPeriod::Fixed(FiscalPeriod::Quarterly), - filings_key_field: DEFAULT_FILINGS_KEY_FIELD.to_string(), - filings_timefiled_field: DEFAULT_FILINGS_TIMEFILED_FIELD.to_string(), - filings_form_type_field: "formType".to_string(), - filings_filing_id_field: None, - filings_url_field: None, - mapping_source: DEFAULT_FUNDAMENTALS_MAPPING_SOURCE.to_string(), - k: 4, - })) - ); - - // Fixed annual mode - assert_eq!( - parse_args(&to_args(&[ - "curate-fundamentals", - "--qm-financials=fin.bson", - "--qm-filings=fil.bson", - "--provider-mapping=map.tsv", - "--listing-venues=venues.tsv", - "--out=fund_out", - "--currency-field=currency", - "--filings-form-type-field=formType", - "--k=2", - "--fiscal-period=annual", - ])), - Ok(CliAction::CurateFundamentals( - CurateFundamentalsArgs::with_verified_defaults( - PathBuf::from("fin.bson"), - PathBuf::from("fil.bson"), - PathBuf::from("map.tsv"), - PathBuf::from("venues.tsv"), - PathBuf::from("fund_out"), - "currency", - None, - None, - None, - None, - None, - None, - CurateFundamentalsFiscalPeriod::Fixed(FiscalPeriod::Annual), - "formType", - 2, - ) - )) - ); - - // All optional flags overridden with --flag=value and paired token lists (preserving token whitespace) - assert_eq!( - parse_args(&to_args(&[ - "curate-fundamentals", - "--qm-financials=fin2.bson", - "--qm-filings=fil2.bson", - "--provider-mapping=map2.tsv", - "--listing-venues=venues2.tsv", - "--out=out2", - "--currency-field=meta.ccy", - "--filings-form-type-field=filingForm", - "--k=8", - "--quarterly-tokens=Q1,Q2, Q3 ,Q4", - "--annual-tokens=FY,Annual", - "--financials-key-field=secId", - "--period-end-field=periodEnd", - "--report-date-field=reportedAt", - "--report-period-field=periodCode", - "--revenue-field=IncomeStatement.revenue", - "--net-income-field=IncomeStatement.netIncome", - "--operating-cash-flow-field=CashFlow.operatingCashFlow", - "--total-assets-field=BalanceSheet.totalAssets", - "--total-equity-field=BalanceSheet.totalEquity", - "--shares-outstanding-field=BalanceSheet.sharesOutstanding", - "--filings-key-field=qmId", - "--filings-timefiled-field=filedAt", - "--filings-filing-id-field=filingId", - "--filings-url-field=filingUrl", - "--mapping-source=qm_alt", - ])), - Ok(CliAction::CurateFundamentals(CurateFundamentalsArgs { - qm_financials: PathBuf::from("fin2.bson"), - qm_filings: PathBuf::from("fil2.bson"), - provider_mapping: PathBuf::from("map2.tsv"), - listing_venues: PathBuf::from("venues2.tsv"), - out_dir: PathBuf::from("out2"), - financials_key_field: "secId".to_string(), - financials_period_end_field: "periodEnd".to_string(), - financials_report_date_field: "reportedAt".to_string(), - financials_report_period_field: "periodCode".to_string(), - financials_currency_field: "meta.ccy".to_string(), - financials_revenue_field: Some("IncomeStatement.revenue".to_string()), - financials_net_income_field: Some("IncomeStatement.netIncome".to_string()), - financials_operating_cash_flow_field: Some( - "CashFlow.operatingCashFlow".to_string() - ), - financials_total_assets_field: Some("BalanceSheet.totalAssets".to_string()), - financials_total_equity_field: Some("BalanceSheet.totalEquity".to_string()), - financials_shares_outstanding_field: Some( - "BalanceSheet.sharesOutstanding".to_string() - ), - fiscal_period: CurateFundamentalsFiscalPeriod::ByTokens { - quarterly: vec![ - "Q1".to_string(), - "Q2".to_string(), - " Q3 ".to_string(), - "Q4".to_string(), - ], - annual: vec!["FY".to_string(), "Annual".to_string()], - }, - filings_key_field: "qmId".to_string(), - filings_timefiled_field: "filedAt".to_string(), - filings_form_type_field: "filingForm".to_string(), - filings_filing_id_field: Some("filingId".to_string()), - filings_url_field: Some("filingUrl".to_string()), - mapping_source: "qm_alt".to_string(), - k: 8, - })) - ); - - // Single token-list modes (quarterly-only and annual-only) - let q_only = parse_args(&to_args(&[ - "curate-fundamentals", - "--qm-financials", - "fin.bson", - "--qm-filings", - "fil.bson", - "--provider-mapping", - "map.tsv", - "--listing-venues", - "venues.tsv", - "--out", - "out", - "--currency-field", - "currency", - "--filings-form-type-field", - "formType", - "--k", - "1", - "--quarterly-tokens", - "Q1,Q2", - ])) - .expect("quarterly-only token list"); - assert!(matches!( - q_only, - CliAction::CurateFundamentals(CurateFundamentalsArgs { - fiscal_period: CurateFundamentalsFiscalPeriod::ByTokens { - ref quarterly, - ref annual, - }, - .. - }) if quarterly == &["Q1", "Q2"] && annual.is_empty() - )); - - let a_only = parse_args(&to_args(&[ - "curate-fundamentals", - "--qm-financials", - "fin.bson", - "--qm-filings", - "fil.bson", - "--provider-mapping", - "map.tsv", - "--listing-venues", - "venues.tsv", - "--out", - "out", - "--currency-field", - "currency", - "--filings-form-type-field", - "formType", - "--k", - "1", - "--annual-tokens", - "FY", - ])) - .expect("annual-only token list"); - assert!(matches!( - a_only, - CliAction::CurateFundamentals(CurateFundamentalsArgs { - fiscal_period: CurateFundamentalsFiscalPeriod::ByTokens { - ref quarterly, - ref annual, - }, - .. - }) if quarterly.is_empty() && annual == &["FY"] - )); - - // Each omitted required flag errors - let required: [(&str, &str); 8] = [ - ("--qm-financials", "fin.bson"), - ("--qm-filings", "fil.bson"), - ("--provider-mapping", "map.tsv"), - ("--listing-venues", "venues.tsv"), - ("--out", "out"), - ("--currency-field", "currency"), - ("--filings-form-type-field", "formType"), - ("--k", "4"), - ]; - for omit in 0..required.len() { - let mut argv = vec!["curate-fundamentals", "--fiscal-period", "quarterly"]; - for (idx, &(flag, val)) in required.iter().enumerate() { - if idx != omit { - argv.push(flag); - argv.push(val); - } - } - let err = parse_args(&to_args(&argv)).unwrap_err(); - let missing_flag = required[omit].0; - assert!( - err.contains(&format!("missing required flag '{missing_flag}'")), - "expected missing {missing_flag}, got: {err}" - ); - } - - // Neither fiscal mode supplied - let mut base_no_fiscal = vec!["curate-fundamentals"]; - for &(flag, val) in &required { - base_no_fiscal.push(flag); - base_no_fiscal.push(val); - } - let err = parse_args(&to_args(&base_no_fiscal)).unwrap_err(); - assert!(err.contains("missing required fiscal-period mode"), "{err}"); - - // Both fiscal modes supplied - for extra in [ - &["--fiscal-period", "quarterly", "--quarterly-tokens", "Q1"][..], - &["--fiscal-period", "annual", "--annual-tokens", "FY"][..], - &[ - "--fiscal-period", - "quarterly", - "--quarterly-tokens", - "Q1", - "--annual-tokens", - "FY", - ][..], - ] { - let mut argv = base_no_fiscal.clone(); - argv.extend_from_slice(extra); - let err = parse_args(&to_args(&argv)).unwrap_err(); - assert!(err.contains("cannot combine '--fiscal-period'"), "{err}"); - } - - // Invalid fixed --fiscal-period - for bad in ["", " ", "q", "QUARTERLY", "ANNUAL", "semi-annual"] { - let mut argv = base_no_fiscal.clone(); - argv.extend_from_slice(&["--fiscal-period", bad]); - let err = parse_args(&to_args(&argv)).unwrap_err(); - assert!(err.contains("invalid --fiscal-period"), "{bad}: {err}"); - } - - // Empty / blank tokens and token in both lists - for (flag, bad_tokens) in [ - ("--quarterly-tokens", ""), - ("--annual-tokens", ""), - ("--quarterly-tokens", " "), - ("--quarterly-tokens", "Q1,,Q2"), - ("--quarterly-tokens", ",Q1"), - ("--quarterly-tokens", "Q1,"), - ("--annual-tokens", "FY, ,Annual"), - ] { - let mut argv = base_no_fiscal.clone(); - let tok = format!("{flag}={bad_tokens}"); - argv.push(&tok); - let err = parse_args(&to_args(&argv)).unwrap_err(); - assert!( - err.contains("empty value for flag") || err.contains("must not be empty or blank"), - "{flag}={bad_tokens:?}: {err}" - ); - } - - let mut overlap = base_no_fiscal.clone(); - overlap.extend_from_slice(&["--quarterly-tokens", "Q1,FY", "--annual-tokens", "FY"]); - let err = parse_args(&to_args(&overlap)).unwrap_err(); - assert!( - err.contains("cannot appear in both quarterly and annual lists"), - "{err}" - ); - - // Malformed financials dotted path and overlapping filings fields - for bad_path in ["Income..revenue", ".revenue", "revenue.", "Income. .rev"] { - let mut argv = base_no_fiscal.clone(); - argv.extend_from_slice(&["--fiscal-period", "quarterly", "--revenue-field", bad_path]); - let err = parse_args(&to_args(&argv)).unwrap_err(); - assert!( - err.contains("empty or blank segment"), - "{bad_path}: {err}" - ); - } - - let mut filings_collision = base_no_fiscal.clone(); - filings_collision.extend_from_slice(&[ - "--fiscal-period", - "quarterly", - "--filings-filing-id-field", - "timefiled", - ]); - let err = parse_args(&to_args(&filings_collision)).unwrap_err(); - assert!(err.contains("cannot share BSON field 'timefiled'"), "{err}"); - - // Invalid --k values: 0, -1, +1, abc, overflow, empty - for bad_k in [ - "0", - "-1", - "+1", - "abc", - "999999999999999999999999999999", - "", - ] { - let mut argv = vec![ - "curate-fundamentals", - "--qm-financials", - "fin.bson", - "--qm-filings", - "fil.bson", - "--provider-mapping", - "map.tsv", - "--listing-venues", - "venues.tsv", - "--out", - "out", - "--currency-field", - "currency", - "--filings-form-type-field", - "formType", - "--fiscal-period", - "quarterly", - ]; - let k_tok = format!("--k={bad_k}"); - argv.push(&k_tok); - let err = parse_args(&to_args(&argv)).unwrap_err(); - assert!( - err.contains("invalid --k") || err.contains("empty value for flag '--k'"), - "k={bad_k:?}: {err}" - ); - } - - // Duplicate flags - for (dup_flag, extra) in [ - ("--qm-financials", &["--qm-financials=other.bson"][..]), - ("--k", &["--k=2"][..]), - ("--fiscal-period", &["--fiscal-period=annual"][..]), - ("--revenue-field", &["--revenue-field=a", "--revenue-field=b"][..]), - ] { - let mut argv = base_no_fiscal.clone(); - argv.extend_from_slice(&["--fiscal-period", "quarterly"]); - argv.extend_from_slice(extra); - let err = parse_args(&to_args(&argv)).unwrap_err(); - assert!( - err.contains(&format!("duplicate flag '{dup_flag}'")), - "{dup_flag}: {err}" - ); - } - - let mut dup_tok = base_no_fiscal.clone(); - dup_tok.extend_from_slice(&["--quarterly-tokens=Q1", "--quarterly-tokens=Q2"]); - let err = parse_args(&to_args(&dup_tok)).unwrap_err(); - assert!(err.contains("duplicate flag '--quarterly-tokens'"), "{err}"); - - // Unknown flags including --from-mongo and --mongo-uri (rejected before consuming a value) - for (args, expected_flag) in [ - (&["curate-fundamentals", "--bogus", "1"][..], "--bogus"), - (&["curate-fundamentals", "--from-mongo"][..], "--from-mongo"), - ( - &["curate-fundamentals", "--from-mongo", "--out", "o"][..], - "--from-mongo", - ), - ( - &["curate-fundamentals", "--from-mongo=true"][..], - "--from-mongo", - ), - ( - &["curate-fundamentals", "--mongo-uri", "mongodb://host"][..], - "--mongo-uri", - ), - ( - &["curate-fundamentals", "--mongo-uri-env=MONGODB_READ_URI"][..], - "--mongo-uri-env", - ), - ] { - let err = parse_args(&to_args(args)).unwrap_err(); - assert_eq!( - err, - format!("unknown flag '{expected_flag}' for curate-fundamentals") - ); - } - - // Positional argument rejected - let err = parse_args(&to_args(&["curate-fundamentals", "extra"])).unwrap_err(); - assert_eq!( - err, - "unexpected positional argument 'extra' for curate-fundamentals" - ); - - // Missing value at end or before another flag - let err = parse_args(&to_args(&["curate-fundamentals", "--qm-financials"])).unwrap_err(); - assert_eq!(err, "missing value for flag '--qm-financials'"); - - let err = parse_args(&to_args(&[ - "curate-fundamentals", - "--k", - "--out", - "o", - ])) - .unwrap_err(); - assert_eq!(err, "missing value for flag '--k'"); - - // Multiline arguments are sanitized to a single diagnostic line - let err = parse_args(&to_args(&["curate-fundamentals", "bad\nline\rarg"])).unwrap_err(); - assert!(!err.contains('\n') && !err.contains('\r'), "{err:?}"); - assert!(err.contains("bad\\nline\\rarg"), "{err:?}"); - } - - #[test] - fn curate_macro_parsing_validation_and_usage() { - let usage = format_usage("curate-etl", "0.1.0"); - let stderr_usage = format_usage_stderr("curate-etl"); - for text in [&usage, &stderr_usage] { - assert!( - text.contains("curate-macro --te-data --series-map --out "), - "{text}" - ); - } - assert!(usage.contains("/macro/part.parquet"), "{usage}"); - assert!(usage.contains("file mode only"), "{usage}"); - - let expected = CliAction::CurateMacro(CurateMacroArgs { - te_data: PathBuf::from("teData.bson"), - series_map: PathBuf::from("macro_series_map.tsv"), - out_dir: PathBuf::from("macro_out"), - }); - - // Happy path: space-separated flags - assert_eq!( - parse_args(&to_args(&[ - "curate-macro", - "--te-data", - "teData.bson", - "--series-map", - "macro_series_map.tsv", - "--out", - "macro_out", - ])), - Ok(expected.clone()) - ); - - // Reordered flags with mixed `--flag value` and `--flag=value` forms - assert_eq!( - parse_args(&to_args(&[ - "curate-macro", - "--out=macro_out", - "--te-data", - "teData.bson", - "--series-map=macro_series_map.tsv", - ])), - Ok(expected.clone()) - ); - - // All `--flag=value` form in another order - assert_eq!( - parse_args(&to_args(&[ - "curate-macro", - "--series-map=macro_series_map.tsv", - "--out=macro_out", - "--te-data=teData.bson", - ])), - Ok(expected) - ); - - // `--flag=value` with `=` inside path and `--`-prefixed literal dir - assert_eq!( - parse_args(&to_args(&[ - "curate-macro", - "--te-data=/tmp/year=2025/teData.bson", - "--series-map=/tmp/v=1/series-map.tsv", - "--out=--literal-dir", - ])), - Ok(CliAction::CurateMacro(CurateMacroArgs { - te_data: PathBuf::from("/tmp/year=2025/teData.bson"), - series_map: PathBuf::from("/tmp/v=1/series-map.tsv"), - out_dir: PathBuf::from("--literal-dir"), - })) - ); - - // Bare `curate-macro` fails with missing required flag - let err = parse_args(&to_args(&["curate-macro"])).unwrap_err(); - assert_eq!(err, "missing required flag '--te-data'"); - - // Omission of each required flag - let required: [(&str, &str); 3] = [ - ("--te-data", "teData.bson"), - ("--series-map", "macro_series_map.tsv"), - ("--out", "macro_out"), - ]; - for omit in 0..required.len() { - let mut argv = vec!["curate-macro"]; - for (idx, &(flag, val)) in required.iter().enumerate() { - if idx != omit { - argv.push(flag); - argv.push(val); - } - } - let err = parse_args(&to_args(&argv)).unwrap_err(); - let missing_flag = required[omit].0; - assert_eq!(err, format!("missing required flag '{missing_flag}'")); - } - - // Missing value at end or before another flag - for (args, expected_flag) in [ - (&["curate-macro", "--te-data"][..], "--te-data"), - (&["curate-macro", "--series-map"][..], "--series-map"), - (&["curate-macro", "--out"][..], "--out"), - ( - &["curate-macro", "--te-data", "--out", "macro_out"][..], - "--te-data", - ), - ( - &["curate-macro", "--series-map", "--te-data", "teData.bson"][..], - "--series-map", - ), - ] { - let err = parse_args(&to_args(args)).unwrap_err(); - assert_eq!(err, format!("missing value for flag '{expected_flag}'")); - } - - // Empty values in both `--flag=` and `--flag ""` forms - for (args, expected_flag) in [ - (&["curate-macro", "--te-data="][..], "--te-data"), - (&["curate-macro", "--series-map="][..], "--series-map"), - (&["curate-macro", "--out="][..], "--out"), - (&["curate-macro", "--te-data", ""][..], "--te-data"), - (&["curate-macro", "--series-map", ""][..], "--series-map"), - (&["curate-macro", "--out", ""][..], "--out"), - ] { - let err = parse_args(&to_args(args)).unwrap_err(); - assert_eq!(err, format!("empty value for flag '{expected_flag}'")); - } - - // Duplicate flags across forms - for (dup_flag, args) in [ - ( - "--te-data", - &[ - "curate-macro", - "--te-data", - "a.bson", - "--te-data=b.bson", - "--series-map", - "map.tsv", - "--out", - "out", - ][..], - ), - ( - "--series-map", - &[ - "curate-macro", - "--series-map=a.tsv", - "--series-map", - "b.tsv", - "--te-data", - "te.bson", - "--out", - "out", - ][..], - ), - ( - "--out", - &[ - "curate-macro", - "--out", - "out1", - "--out=out2", - "--te-data", - "te.bson", - "--series-map", - "map.tsv", - ][..], - ), - ] { - let err = parse_args(&to_args(args)).unwrap_err(); - assert_eq!(err, format!("duplicate flag '{dup_flag}'")); - } - - // Unknown flags including --mongo-uri and --from-mongo (rejected before consuming a value) - for (args, expected_flag) in [ - (&["curate-macro", "--bogus", "1"][..], "--bogus"), - (&["curate-macro", "--from-mongo"][..], "--from-mongo"), - ( - &["curate-macro", "--from-mongo", "--out", "o"][..], - "--from-mongo", - ), - (&["curate-macro", "--from-mongo=true"][..], "--from-mongo"), - ( - &["curate-macro", "--mongo-uri", "mongodb://host"][..], - "--mongo-uri", - ), - ( - &["curate-macro", "--mongo-uri-env=MONGODB_READ_URI"][..], - "--mongo-uri-env", - ), - ] { - let err = parse_args(&to_args(args)).unwrap_err(); - assert_eq!( - err, - format!("unknown flag '{expected_flag}' for curate-macro") - ); - } - - // Unexpected positional arguments rejected (including single-dash token) - for pos in ["extra", "-x"] { - let err = parse_args(&to_args(&["curate-macro", pos])).unwrap_err(); - assert_eq!( - err, - format!("unexpected positional argument '{pos}' for curate-macro") - ); - } - - // CR/LF in arguments are escaped to a single diagnostic line - let err = parse_args(&to_args(&["curate-macro", "bad\nline\rarg"])).unwrap_err(); - assert!(!err.contains('\n') && !err.contains('\r'), "{err:?}"); - assert_eq!( - err, - "unexpected positional argument 'bad\\nline\\rarg' for curate-macro" - ); - - let err = parse_args(&to_args(&["curate-macro", "--bad\nflag\r=1"])).unwrap_err(); - assert!(!err.contains('\n') && !err.contains('\r'), "{err:?}"); - assert_eq!(err, "unknown flag '--bad\\nflag\\r' for curate-macro"); - } - - #[test] - fn parse_send_ilp_valid_space_and_equals_forms_and_all_allowed_prefixes() { - for prefix in ["bars_1m", "bars_1m_qm", "fx_1m"] { - let expected = CliAction::SendIlp(SendIlpArgs { - dir: PathBuf::from("/tmp/shards"), - prefix: prefix.to_string(), - addr: "127.0.0.1:9009".to_string(), - }); - - let parsed_space = parse_args(&to_args(&[ - "send-ilp", - "--dir", - "/tmp/shards", - "--prefix", - prefix, - "--addr", - "127.0.0.1:9009", - ])) - .expect("valid send-ilp args in space form"); - assert_eq!(parsed_space, expected); - - let prefix_eq = format!("--prefix={prefix}"); - let parsed_eq = parse_args(&to_args(&[ - "send-ilp", - "--dir=/tmp/shards", - &prefix_eq, - "--addr=127.0.0.1:9009", - ])) - .expect("valid send-ilp args in equals form"); - assert_eq!(parsed_eq, expected); - } - } - - #[test] - fn send_ilp_usage_mentions_command_flags_and_delivery_caveat() { - let expected_flags = ["--dir", "--prefix", "--addr"]; - let usage = format_usage("curate-etl", "0.1.0"); - let usage_stderr = format_usage_stderr("curate-etl"); - let usage_line = usage - .lines() - .find(|line| line.trim_start().starts_with("curate-etl send-ilp ")) - .expect("format_usage missing send-ilp command line"); - let stderr_line = usage_stderr - .lines() - .find(|line| line.trim_start().starts_with("curate-etl send-ilp ")) - .expect("format_usage_stderr missing send-ilp command line"); - for flag in expected_flags { - assert!( - usage_line.contains(flag), - "format_usage send-ilp line missing {flag}: {usage_line}" - ); - assert!( - stderr_line.contains(flag), - "format_usage_stderr send-ilp line missing {flag}: {stderr_line}" - ); - } - assert!( - usage.contains("no default address"), - "format_usage missing no-default-address note" - ); - assert!( - usage.contains("PGWire"), - "format_usage missing PGWire verification note" - ); - assert!( - usage.contains("10.2.0"), - "format_usage missing QuestDB 10.2.0 unverified note" - ); - } - - #[test] - fn parse_send_ilp_rejects_missing_required_flags_with_no_default_addr() { - let required: [(&str, &str); 3] = [ - ("--dir", "/tmp/shards"), - ("--prefix", "fx_1m"), - ("--addr", "127.0.0.1:9009"), - ]; - - for omit in 0..required.len() { - let mut argv: Vec<&str> = vec!["send-ilp"]; - for (idx, &(flag, val)) in required.iter().enumerate() { - if idx != omit { - argv.push(flag); - argv.push(val); - } - } - let err = parse_args(&to_args(&argv)).unwrap_err(); - let missing_flag = required[omit].0; - assert!( - err.contains(&format!("missing required flag '{missing_flag}'")), - "expected missing required flag '{missing_flag}', got: {err}" - ); - } - } - - #[test] - fn parse_send_ilp_rejects_duplicates_empty_missing_value_unknown_positional_and_bad_prefix() { - let base = [ - "send-ilp", - "--dir", - "/tmp/shards", - "--prefix", - "bars_1m", - "--addr", - "127.0.0.1:9009", - ]; - - // Duplicate flags. - for (flag, extra_val) in [ - ("--dir", "/tmp/other"), - ("--prefix", "fx_1m"), - ("--addr", "127.0.0.1:9010"), - ] { - let mut argv = base.to_vec(); - argv.push(flag); - argv.push(extra_val); - let err = parse_args(&to_args(&argv)).unwrap_err(); - assert!( - err.contains(&format!("duplicate flag '{flag}'")), - "expected duplicate error for {flag}, got: {err}" - ); - } - - // Empty values via --flag=. - for flag in ["--dir", "--prefix", "--addr"] { - let empty_token = format!("{flag}="); - let err = parse_args(&to_args(&["send-ilp", &empty_token])).unwrap_err(); - assert!( - err.contains(&format!("empty value for flag '{flag}'")), - "expected empty value error for {flag}, got: {err}" - ); - } - - // Whitespace-only --addr. - let err = parse_args(&to_args(&[ - "send-ilp", - "--dir", - "/tmp/shards", - "--prefix", - "fx_1m", - "--addr", - " ", - ])) - .unwrap_err(); - assert!(err.contains("empty value for flag '--addr'"), "{err}"); - - // Missing value at end of input or followed by another flag. - let err = parse_args(&to_args(&["send-ilp", "--dir"])).unwrap_err(); - assert!(err.contains("missing value for flag '--dir'"), "{err}"); - let err = parse_args(&to_args(&[ - "send-ilp", - "--prefix", - "--addr", - "127.0.0.1:9009", - ])) - .unwrap_err(); - assert!(err.contains("missing value for flag '--prefix'"), "{err}"); - - // Unknown flag (including --from-mongo). - for flag in ["--nope", "--from-mongo", "--timeout"] { - let mut argv = base.to_vec(); - argv.push(flag); - argv.push("1"); - let err = parse_args(&to_args(&argv)).unwrap_err(); - assert!( - err.contains(&format!("unknown flag '{flag}' for send-ilp")), - "expected unknown flag error for {flag}, got: {err}" - ); - } - - // Positional argument. - let err = parse_args(&to_args(&["send-ilp", "positional"])).unwrap_err(); - assert!( - err.contains("unexpected positional argument 'positional' for send-ilp"), - "{err}" - ); - - // Unsupported non-empty prefixes must list all three allowed values. - for bad_prefix in [ - "bars_1d", - "../x", - "BARS_1M", - "fx_1d", - "fx_1m_extra", - " bars_1m", - "bars_1m ", - "./bars_1m", - "dir/fx_1m", - ] { - let err = parse_args(&to_args(&[ - "send-ilp", - "--dir", - "/tmp/shards", - "--prefix", - bad_prefix, - "--addr", - "127.0.0.1:9009", - ])) - .unwrap_err(); - assert!( - err.contains("bars_1m") && err.contains("bars_1m_qm") && err.contains("fx_1m"), - "expected allowed prefixes in error for '{bad_prefix}', got: {err}" - ); - } - } - - #[test] - fn parse_send_ilp_edge_cases_bare_empty_space_form_order_equals_in_dir_and_ipv6() { - // Bare `send-ilp` with no flags fails with missing required flag. - let err = parse_args(&to_args(&["send-ilp"])).unwrap_err(); - assert!(err.contains("missing required flag '--dir'"), "{err}"); - - // Empty values in space form. - for (argv, flag) in [ - ( - &[ - "send-ilp", - "--dir", - "", - "--prefix", - "fx_1m", - "--addr", - "127.0.0.1:9009", - ][..], - "--dir", - ), - ( - &[ - "send-ilp", - "--dir", - "/tmp/shards", - "--prefix", - "", - "--addr", - "127.0.0.1:9009", - ][..], - "--prefix", - ), - ( - &[ - "send-ilp", - "--dir", - "/tmp/shards", - "--prefix", - "fx_1m", - "--addr", - "", - ][..], - "--addr", - ), - ] { - let err = parse_args(&to_args(argv)).unwrap_err(); - assert!( - err.contains(&format!("empty value for flag '{flag}'")), - "expected empty value error for {flag}, got: {err}" - ); - } - - // Mixed flag order, `=` inside --dir path, and IPv6 --addr in both forms. - let expected = CliAction::SendIlp(SendIlpArgs { - dir: PathBuf::from("/tmp/year=2025/shards"), - prefix: "bars_1m_qm".to_string(), - addr: "[::1]:9009".to_string(), - }); - let parsed_mixed = parse_args(&to_args(&[ - "send-ilp", - "--addr", - "[::1]:9009", - "--prefix=bars_1m_qm", - "--dir=/tmp/year=2025/shards", - ])) - .expect("mixed order with equals in dir and IPv6 addr"); - assert_eq!(parsed_mixed, expected); - - let parsed_space = parse_args(&to_args(&[ - "send-ilp", - "--prefix", - "bars_1m_qm", - "--addr=[::1]:9009", - "--dir", - "/tmp/year=2025/shards", - ])) - .expect("space dir with equals and IPv6 equals addr"); - assert_eq!(parsed_space, expected); - } } diff --git a/tools/curate-etl/src/curate_adj.rs b/tools/curate-etl/src/curate_adj.rs deleted file mode 100644 index fa22c910..00000000 --- a/tools/curate-etl/src/curate_adj.rs +++ /dev/null @@ -1,1944 +0,0 @@ -//! Pure, in-memory `adj_factors` curation stage joining -//! [`crate::provider_mapping::ProviderMappingTable`], [`crate::adj::build_adj_factors`], -//! [`crate::session_close::et_session_close_utc_micros`], and -//! [`crate::parquet_adj::write_adj_factors_dataset`] into contract [`AdjFactorsParquetRow`]s. -//! -//! # Contract & Point-in-Time Rules -//! - **Map before build:** every source-keyed `qmSplits` and `qmDividends` event is resolved via -//! `(mapping_source, source_key, ex_date) -> listing_id: i32` *before* calling -//! [`build_adj_factors`] on `i32` listing keys. Cumulative factors (`cum_split_factor`, -//! `cum_total_factor`) therefore chain continuously per permanent `listing_id` across ticker -//! renames, while ticker reuse across distinct `listing_id`s produces independent chains. -//! - **Unmapped events:** splits and dividends with no covering `provider_mapping` range on -//! `ex_date` are dropped and counted separately in `splits_dropped_unmapped` and -//! `dividends_dropped_unmapped`. -//! - **Cross-key collision policy (fail closed on conflict):** after mapping, events on the same -//! `(listing_id, ex_date)` are grouped deterministically: -//! - Single-source-key groups pass through unchanged to [`build_adj_factors`] (preserving -//! same-day multi-dividend summation, same-day split multiplication, `1:1` no-op drops, and -//! zero-cash dividend drops). -//! - Multi-source-key groups whose payloads are bitwise identical collapse to one event and are -//! counted in `splits_collision_collapsed` / `dividends_collision_collapsed` and -//! `listing_collision_collapsed`. -//! - Multi-source-key groups with conflicting split ratios or conflicting dividend fields return -//! [`CurateAdjError::ConflictingCrossKeySplit`] / -//! [`CurateAdjError::ConflictingCrossKeyDividend`] rather than silently dropping or doubling an -//! event that would corrupt every earlier cumulative factor. -//! - **Conservative `known_at` & point-in-time snapshot contract:** -//! - Every row's `known_at_micros` is stamped with -//! `et_session_close_utc_micros(ex_date)` (`16:00:00 America/New_York` / -//! `America/Toronto` on `ex_date`: `21:00 UTC` in EST, `20:00 UTC` in EDT). -//! Any mapped row whose `ex_date` lies outside `1976-01-01..=2030-12-31` returns -//! [`CurateAdjError::ExDateOutOfRange`] naming `(listing_id, ex_date)` without panicking. -//! - Because [`build_adj_factors`] computes right-to-left suffix products -//! (`cum_split_factor`, `cum_total_factor`), later splits and dividends are compounded into -//! earlier rows. Consequently, [`curate_adj_factors`] produces an explicitly tagged -//! [`AdjSnapshotKind::RetrospectiveSnapshot`] (full-history snapshot): slicing it with a bare -//! `known_at <= as_of` filter would still admit earlier rows whose cumulative factors embed -//! future or held-out vault actions. -//! - For point-in-time and vault-fenced reads, callers MUST use [`curate_adj_factors_as_of`] / -//! [`curate_and_write_adj_factors_as_of`] with an [`AdjPointInTimeFence`] (`as_of_micros` -//! inclusive `<=`, `vault_cutoff_micros` exclusive `<`), which fences source events *before* -//! compaction and compounding and tags the output as [`AdjSnapshotKind::PointInTimeFenced`]. - -use std::borrow::Cow; -use std::cmp::Ordering; -use std::collections::HashMap; -use std::error::Error; -use std::fmt; -use std::fs::{self, File}; -use std::io::{self, BufWriter, Write}; -use std::path::{Path, PathBuf}; -use std::sync::Arc; - -use parquet::basic::{Compression, ZstdLevel}; -use parquet::column::reader::ColumnReader; -use parquet::data_type::ByteArray; -use parquet::errors::ParquetError; -use parquet::file::metadata::KeyValue; -use parquet::file::properties::WriterProperties; -use parquet::file::reader::{FileReader, SerializedFileReader}; -use parquet::file::writer::SerializedFileWriter; -use parquet::schema::types::ColumnPath; - -use crate::adj::{build_adj_factors, AdjBuildStats, AdjError, DividendEvent}; -use crate::parquet_adj::{ - adj_factors_parquet_schema, AdjFactorsParquetRow, AdjFactorsWriteOptions, AdjFactorsWriteStats, - ParquetAdjError, RollbackFailure, -}; -use crate::parquet_publish::{ - create_backup_preserving_live, create_exclusive_tmp_file, dataset_mutex, next_run_id, - write_f64_col, write_i32_col, write_i64_col, write_optional_interned_str_col, DatasetFileLock, - StagingFileGuard, StringInterner, DEFAULT_LOCK_TIMEOUT, FILE_BUF_CAPACITY_BYTES, - STRING_WRITE_BATCH_ROWS, -}; -use crate::provider_mapping::{ProviderMappingCursor, ProviderMappingTable}; -use crate::session_close::{et_session_close_utc_micros, SessionCloseError}; -use crate::split::SplitEvent; - -/// Current format version embedded in `adj_factors/part.parquet` footer `key_value_metadata`. -pub const ADJ_SNAPSHOT_FORMAT_VERSION: u32 = 1; - -const KV_PREFIX: &str = "stock_bot.adj_factors."; -const KV_FORMAT_VERSION: &str = "stock_bot.adj_factors.format_version"; -const KV_SNAPSHOT_KIND: &str = "stock_bot.adj_factors.snapshot_kind"; -const KV_AS_OF_MICROS: &str = "stock_bot.adj_factors.as_of_micros"; -const KV_VAULT_CUTOFF_MICROS: &str = "stock_bot.adj_factors.vault_cutoff_micros"; -const KV_ROWS_WRITTEN: &str = "stock_bot.adj_factors.rows_written"; -const KV_SNAPSHOT_CHECKSUM: &str = "stock_bot.adj_factors.snapshot_checksum"; - -/// Point-in-time and Vault holdout fence applied to source events *before* -/// [`build_adj_factors`] computes right-to-left cumulative suffix factors. -/// -/// - `as_of_micros`: inclusive UTC microsecond upper bound (`event_known_at <= as_of_micros`). -/// - `vault_cutoff_micros`: exclusive UTC microsecond Vault holdout boundary -/// (`event_known_at < vault_cutoff_micros`), matching `design/DATA-CONTRACTS.md` §4. -/// -/// When both bounds are set, an event must satisfy both (`known_at <= as_of_micros` AND -/// `known_at < vault_cutoff_micros`), so the vault cutoff always wins even if `as_of_micros` is -/// at or past `vault_cutoff_micros`. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct AdjPointInTimeFence { - pub as_of_micros: Option, - pub vault_cutoff_micros: Option, -} - -impl AdjPointInTimeFence { - /// Unbounded retrospective full-history snapshot (no `as_of` or vault fence). - #[inline] - pub const fn retrospective() -> Self { - Self { - as_of_micros: None, - vault_cutoff_micros: None, - } - } - - /// Inclusive `known_at <= as_of_micros` fence without a separate vault cutoff. - #[inline] - pub const fn as_of(as_of_micros: i64) -> Self { - Self { - as_of_micros: Some(as_of_micros), - vault_cutoff_micros: None, - } - } - - /// Exclusive `known_at < vault_cutoff_micros` vault holdout fence. - #[inline] - pub const fn vault_fenced(vault_cutoff_micros: i64) -> Self { - Self { - as_of_micros: None, - vault_cutoff_micros: Some(vault_cutoff_micros), - } - } - - /// Combined `known_at <= as_of_micros` and `known_at < vault_cutoff_micros` fence. - #[inline] - pub const fn as_of_with_vault_cutoff(as_of_micros: i64, vault_cutoff_micros: i64) -> Self { - Self { - as_of_micros: Some(as_of_micros), - vault_cutoff_micros: Some(vault_cutoff_micros), - } - } - - /// Returns `true` when neither an `as_of` nor a `vault_cutoff` bound is set. - #[inline] - pub const fn is_retrospective(&self) -> bool { - self.as_of_micros.is_none() && self.vault_cutoff_micros.is_none() - } - - /// Returns `true` iff an event with `known_at_micros` is admitted by this fence. - #[inline] - pub const fn admits(&self, known_at_micros: i64) -> bool { - if let Some(as_of) = self.as_of_micros { - if known_at_micros > as_of { - return false; - } - } - if let Some(vault_cutoff) = self.vault_cutoff_micros { - if known_at_micros >= vault_cutoff { - return false; - } - } - true - } -} - -/// Identifies whether a curated `adj_factors` output is an unfenced retrospective full-history -/// snapshot or a point-in-time / vault-fenced snapshot. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum AdjSnapshotKind { - /// Built from the full input history with no `as_of` or vault fence. Earlier rows embed - /// later actions in `cum_split_factor` / `cum_total_factor`; do not slice with a bare - /// `known_at <= as_of` filter for point-in-time research reads. - RetrospectiveSnapshot, - /// Built after fencing source events by the attached [`AdjPointInTimeFence`] before - /// compaction and compounding, so no action beyond the fence is embedded in any row. - PointInTimeFenced(AdjPointInTimeFence), -} - -/// Accounting summary produced alongside [`CurateAdjFactorsOutput::rows`]. -/// -/// Conservation invariants: -/// - `splits_in == splits_dropped_unmapped + splits_dropped_fenced + splits_collision_collapsed + builder.split_events_in` -/// - `dividends_in == dividends_dropped_unmapped + dividends_dropped_fenced + dividends_collision_collapsed + builder.dividend_events_in` -/// - `listing_collision_collapsed == splits_collision_collapsed + dividends_collision_collapsed` -/// - `rows_out == builder.rows_out` -/// - `listings_out == builder.keys_out` -/// - For [`AdjSnapshotKind::RetrospectiveSnapshot`], `splits_dropped_fenced == 0` and -/// `dividends_dropped_fenced == 0`. -/// - `builder` independently satisfies all [`AdjBuildStats`] invariants. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct CurateAdjFactorsStats { - pub builder: AdjBuildStats, - pub splits_in: usize, - pub dividends_in: usize, - pub splits_dropped_unmapped: usize, - pub dividends_dropped_unmapped: usize, - pub splits_dropped_fenced: usize, - pub dividends_dropped_fenced: usize, - pub splits_collision_collapsed: usize, - pub dividends_collision_collapsed: usize, - pub listing_collision_collapsed: usize, - pub rows_out: usize, - pub listings_out: usize, -} - -/// Output of [`curate_adj_factors`] / [`curate_adj_factors_as_of`]: contract Parquet rows sorted -/// and unique by `(listing_id, ex_date)`, explicit snapshot classification, and full stage + -/// builder stats. -#[derive(Debug, Clone, PartialEq)] -pub struct CurateAdjFactorsOutput { - pub rows: Vec, - pub stats: CurateAdjFactorsStats, - pub snapshot_kind: AdjSnapshotKind, -} - -/// Typed errors returned by [`curate_adj_factors`]. -#[derive(Debug, Clone, PartialEq)] -pub enum CurateAdjError { - /// Caller-supplied `mapping_source` was empty or contained only whitespace. - EmptyMappingSource, - /// Validation or compounding error propagated from [`build_adj_factors`]. - Adj(AdjError), - /// Two distinct source keys mapped to the same `(listing_id, ex_date)` with conflicting split - /// ratios. - ConflictingCrossKeySplit { - listing_id: i32, - ex_date: i32, - first_key: String, - first_ratio: f64, - second_key: String, - second_ratio: f64, - }, - /// Two distinct source keys mapped to the same `(listing_id, ex_date)` with differing dividend - /// payloads (`cash`, `currency`, `prev_close`, or `prev_close_currency`). - ConflictingCrossKeyDividend { - listing_id: i32, - ex_date: i32, - first_key: String, - second_key: String, - }, - /// A curated row's `ex_date` fell outside [`et_session_close_utc_micros`]'s supported - /// `1976-01-01..=2030-12-31` window. - ExDateOutOfRange { - listing_id: i32, - ex_date: i32, - source: SessionCloseError, - }, -} - -impl fmt::Display for CurateAdjError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::EmptyMappingSource => { - write!(f, "mapping_source must not be empty or blank") - } - Self::Adj(err) => write!(f, "{err}"), - Self::ConflictingCrossKeySplit { - listing_id, - ex_date, - first_key, - first_ratio, - second_key, - second_ratio, - } => write!( - f, - "conflicting cross-key splits for listing_id {listing_id} on epoch day {ex_date}: key '{first_key}' ratio {first_ratio} vs key '{second_key}' ratio {second_ratio}" - ), - Self::ConflictingCrossKeyDividend { - listing_id, - ex_date, - first_key, - second_key, - } => write!( - f, - "conflicting cross-key dividends for listing_id {listing_id} on epoch day {ex_date}: key '{first_key}' vs key '{second_key}'" - ), - Self::ExDateOutOfRange { - listing_id, - ex_date, - source, - } => write!( - f, - "adj_factors ex_date {ex_date} for listing_id {listing_id} out of range: {source}" - ), - } - } -} - -impl Error for CurateAdjError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::Adj(err) => Some(err), - Self::ExDateOutOfRange { source, .. } => Some(source), - Self::EmptyMappingSource - | Self::ConflictingCrossKeySplit { .. } - | Self::ConflictingCrossKeyDividend { .. } => None, - } - } -} - -impl From for CurateAdjError { - fn from(err: AdjError) -> Self { - Self::Adj(err) - } -} - -/// Combined stats returned by [`curate_and_write_adj_factors`] and -/// [`curate_and_write_adj_factors_as_of`]. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct CurateAdjFactorsWriteReport { - pub curate_stats: CurateAdjFactorsStats, - pub write_stats: AdjFactorsWriteStats, - pub snapshot_kind: AdjSnapshotKind, -} - -/// Typed error returned by [`curate_and_write_adj_factors`] and -/// [`curate_and_write_adj_factors_as_of`]. -#[derive(Debug)] -pub enum CurateAdjWriteError { - Curate(CurateAdjError), - Parquet(ParquetAdjError), -} - -impl fmt::Display for CurateAdjWriteError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Curate(err) => write!(f, "adj_factors curation failed: {err}"), - Self::Parquet(err) => write!(f, "adj_factors Parquet write failed: {err}"), - } - } -} - -impl Error for CurateAdjWriteError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::Curate(err) => Some(err), - Self::Parquet(err) => Some(err), - } - } -} - -impl From for CurateAdjWriteError { - fn from(err: CurateAdjError) -> Self { - Self::Curate(err) - } -} - -impl From for CurateAdjWriteError { - fn from(err: ParquetAdjError) -> Self { - Self::Parquet(err) - } -} - -struct MappedSplit { - listing_id: i32, - ex_date: i32, - source_key: K, - ratio: f64, -} - -struct MappedDividend { - listing_id: i32, - source_key: K, - event: DividendEvent, -} - -#[inline] -fn resolve_with_cache<'a>( - cache: &mut HashMap>, - mapping: &'a ProviderMappingTable, - mapping_source: &str, - key_str: &str, - ex_date: i32, -) -> Option { - if let Some(cursor) = cache.get_mut(key_str) { - return cursor.resolve(ex_date); - } - let mut cursor = mapping.cursor_for(mapping_source, key_str); - let resolved = cursor.resolve(ex_date); - cache.insert(key_str.to_owned(), cursor); - resolved -} - -#[inline] -fn cmp_opt_f64(a: Option, b: Option) -> Ordering { - match (a, b) { - (None, None) => Ordering::Equal, - (None, Some(_)) => Ordering::Less, - (Some(_), None) => Ordering::Greater, - (Some(x), Some(y)) => x.total_cmp(&y), - } -} - -#[inline] -fn cmp_dividend_event(a: &DividendEvent, b: &DividendEvent) -> Ordering { - a.ex_date - .cmp(&b.ex_date) - .then_with(|| a.cash.total_cmp(&b.cash)) - .then_with(|| a.currency.cmp(&b.currency)) - .then_with(|| cmp_opt_f64(a.prev_close, b.prev_close)) - .then_with(|| a.prev_close_currency.cmp(&b.prev_close_currency)) -} - -#[inline] -fn dividend_event_bit_eq(a: &DividendEvent, b: &DividendEvent) -> bool { - a.ex_date == b.ex_date - && a.cash.to_bits() == b.cash.to_bits() - && a.currency == b.currency - && a.prev_close.map(f64::to_bits) == b.prev_close.map(f64::to_bits) - && a.prev_close_currency == b.prev_close_currency -} - -fn compact_mapped_splits>( - mut mapped: Vec>, -) -> Result<(Vec<(i32, SplitEvent)>, usize), CurateAdjError> { - mapped.sort_unstable_by(|a, b| { - a.listing_id - .cmp(&b.listing_id) - .then_with(|| a.ex_date.cmp(&b.ex_date)) - .then_with(|| a.source_key.as_ref().cmp(b.source_key.as_ref())) - .then_with(|| a.ratio.total_cmp(&b.ratio)) - }); - - let mut out: Vec<(i32, SplitEvent)> = Vec::with_capacity(mapped.len()); - let mut collapsed_total = 0usize; - let mut iter = mapped.into_iter().peekable(); - let mut group: Vec> = Vec::with_capacity(4); - - while let Some(first) = iter.next() { - let listing_id = first.listing_id; - let ex_date = first.ex_date; - group.clear(); - group.push(first); - while let Some(next) = iter.peek() { - if next.listing_id == listing_id && next.ex_date == ex_date { - group.push(iter.next().expect("peeked split")); - } else { - break; - } - } - - let group_len = group.len(); - if group_len == 1 { - let item = group.pop().expect("single split"); - out.push(( - listing_id, - SplitEvent { - ex_date, - ratio: item.ratio, - }, - )); - continue; - } - - let first_key = group[0].source_key.as_ref(); - let last_key = group[group_len - 1].source_key.as_ref(); - if first_key == last_key { - // Single source key: pass every event through unchanged to preserve `build_adj_factors` - // same-day split semantics. - for item in group.drain(..) { - out.push(( - listing_id, - SplitEvent { - ex_date, - ratio: item.ratio, - }, - )); - } - continue; - } - - let first_ratio = group[0].ratio; - let first_ratio_bits = first_ratio.to_bits(); - let all_identical = group[1..] - .iter() - .all(|other| other.ratio.to_bits() == first_ratio_bits); - - if all_identical { - collapsed_total += group_len - 1; - out.push(( - listing_id, - SplitEvent { - ex_date, - ratio: first_ratio, - }, - )); - } else { - // Find a deterministic pair with distinct source keys and differing ratios. - let (lhs, rhs) = if let Some(other) = group[1..] - .iter() - .find(|e| e.source_key.as_ref() != first_key && e.ratio.to_bits() != first_ratio_bits) - { - (&group[0], other) - } else { - let bad = group[1..] - .iter() - .find(|e| e.ratio.to_bits() != first_ratio_bits) - .expect("non-identical split exists"); - let other_key = group[1..] - .iter() - .find(|e| e.source_key.as_ref() != first_key) - .expect("distinct source key exists"); - (bad, other_key) - }; - return Err(CurateAdjError::ConflictingCrossKeySplit { - listing_id, - ex_date, - first_key: lhs.source_key.as_ref().to_owned(), - first_ratio: lhs.ratio, - second_key: rhs.source_key.as_ref().to_owned(), - second_ratio: rhs.ratio, - }); - } - } - - Ok((out, collapsed_total)) -} - -fn compact_mapped_dividends>( - mut mapped: Vec>, -) -> Result<(Vec<(i32, DividendEvent)>, usize), CurateAdjError> { - mapped.sort_unstable_by(|a, b| { - a.listing_id - .cmp(&b.listing_id) - .then_with(|| a.event.ex_date.cmp(&b.event.ex_date)) - .then_with(|| a.source_key.as_ref().cmp(b.source_key.as_ref())) - .then_with(|| cmp_dividend_event(&a.event, &b.event)) - }); - - let mut out: Vec<(i32, DividendEvent)> = Vec::with_capacity(mapped.len()); - let mut collapsed_total = 0usize; - let mut iter = mapped.into_iter().peekable(); - let mut group: Vec> = Vec::with_capacity(4); - - while let Some(first) = iter.next() { - let listing_id = first.listing_id; - let ex_date = first.event.ex_date; - group.clear(); - group.push(first); - while let Some(next) = iter.peek() { - if next.listing_id == listing_id && next.event.ex_date == ex_date { - group.push(iter.next().expect("peeked dividend")); - } else { - break; - } - } - - let group_len = group.len(); - if group_len == 1 { - let item = group.pop().expect("single dividend"); - out.push((listing_id, item.event)); - continue; - } - - let first_key = group[0].source_key.as_ref(); - let last_key = group[group_len - 1].source_key.as_ref(); - if first_key == last_key { - // Single source key: pass every event through unchanged to preserve `build_adj_factors` - // same-day multi-dividend semantics (e.g. regular + special dividend). - for item in group.drain(..) { - out.push((listing_id, item.event)); - } - continue; - } - - let all_identical = group[1..] - .iter() - .all(|other| dividend_event_bit_eq(&group[0].event, &other.event)); - - if all_identical { - collapsed_total += group_len - 1; - let first = group.swap_remove(0); - out.push((listing_id, first.event)); - } else { - let other_key = group[1..] - .iter() - .find(|e| { - e.source_key.as_ref() != first_key && !dividend_event_bit_eq(&group[0].event, &e.event) - }) - .or_else(|| { - group[1..] - .iter() - .find(|e| e.source_key.as_ref() != first_key) - }) - .expect("distinct source key exists"); - return Err(CurateAdjError::ConflictingCrossKeyDividend { - listing_id, - ex_date, - first_key: first_key.to_owned(), - second_key: other_key.source_key.as_ref().to_owned(), - }); - } - } - - Ok((out, collapsed_total)) -} - -/// Pure `adj_factors` curation stage producing a **retrospective full-history snapshot** -/// ([`AdjSnapshotKind::RetrospectiveSnapshot`]). -/// -/// Resolves source-keyed `qmSplits` and `qmDividends` through `provider_mapping` to permanent -/// `listing_id: i32` keys *before* factor building, compacts cross-key collisions (collapsing -/// bitwise-identical aliases and failing closed on conflicts), computes cumulative factors via -/// [`build_adj_factors`] unchanged, and stamps conservative `16:00 ET` `known_at` timestamps via -/// [`et_session_close_utc_micros`]. -/// -/// **Point-in-time warning:** because `cum_split_factor` and `cum_total_factor` compound all later -/// actions in the input into earlier rows, filtering this retrospective snapshot by -/// `known_at <= as_of` leaks future or held-out vault actions into earlier bars. Use -/// [`curate_adj_factors_as_of`] to fence source events by `as_of` and `vault_cutoff` *before* -/// compounding. -/// -/// Output rows are sorted strictly ascending and unique by `(listing_id, ex_date)`. -pub fn curate_adj_factors( - mapping: &ProviderMappingTable, - mapping_source: &str, - splits: S, - dividends: D, -) -> Result -where - K: AsRef + Ord + Clone, - S: IntoIterator, - D: IntoIterator, -{ - curate_adj_factors_as_of( - mapping, - mapping_source, - splits, - dividends, - AdjPointInTimeFence::retrospective(), - ) -} - -/// Point-in-time and vault-fenced `adj_factors` curation stage. -/// -/// Applies `fence` (`known_at <= as_of_micros` and/or `known_at < vault_cutoff_micros`, where each -/// event's `known_at` is `et_session_close_utc_micros(ex_date)`) to mapped source events *before* -/// cross-key compaction and *before* [`build_adj_factors`] compounds cumulative suffix factors. -/// Appending any future or held-out vault action beyond `fence` therefore leaves the curated rows -/// and adjusted reads bitwise identical. -/// -/// When `fence.is_retrospective()` is `true`, this behaves identically to [`curate_adj_factors`] -/// and tags the output as [`AdjSnapshotKind::RetrospectiveSnapshot`]; otherwise it tags the output -/// as [`AdjSnapshotKind::PointInTimeFenced`]. -pub fn curate_adj_factors_as_of( - mapping: &ProviderMappingTable, - mapping_source: &str, - splits: S, - dividends: D, - fence: AdjPointInTimeFence, -) -> Result -where - K: AsRef + Ord + Clone, - S: IntoIterator, - D: IntoIterator, -{ - if mapping_source.trim().is_empty() { - return Err(CurateAdjError::EmptyMappingSource); - } - - let is_fenced = !fence.is_retrospective(); - let splits_iter = splits.into_iter(); - let divs_iter = dividends.into_iter(); - - let mut stats = CurateAdjFactorsStats::default(); - let mut cursor_cache: HashMap> = HashMap::new(); - - let mut mapped_splits: Vec> = Vec::with_capacity(splits_iter.size_hint().0); - for (key, event) in splits_iter { - stats.splits_in += 1; - let Some(listing_id) = resolve_with_cache( - &mut cursor_cache, - mapping, - mapping_source, - key.as_ref(), - event.ex_date, - ) else { - stats.splits_dropped_unmapped += 1; - continue; - }; - if is_fenced { - let known_at = et_session_close_utc_micros(event.ex_date).map_err(|source| { - CurateAdjError::ExDateOutOfRange { - listing_id, - ex_date: event.ex_date, - source, - } - })?; - if !fence.admits(known_at) { - stats.splits_dropped_fenced += 1; - continue; - } - } - mapped_splits.push(MappedSplit { - listing_id, - ex_date: event.ex_date, - source_key: key, - ratio: event.ratio, - }); - } - - let mut mapped_divs: Vec> = Vec::with_capacity(divs_iter.size_hint().0); - for (key, event) in divs_iter { - stats.dividends_in += 1; - let Some(listing_id) = resolve_with_cache( - &mut cursor_cache, - mapping, - mapping_source, - key.as_ref(), - event.ex_date, - ) else { - stats.dividends_dropped_unmapped += 1; - continue; - }; - if is_fenced { - let known_at = et_session_close_utc_micros(event.ex_date).map_err(|source| { - CurateAdjError::ExDateOutOfRange { - listing_id, - ex_date: event.ex_date, - source, - } - })?; - if !fence.admits(known_at) { - stats.dividends_dropped_fenced += 1; - continue; - } - } - mapped_divs.push(MappedDividend { - listing_id, - source_key: key, - event, - }); - } - - drop(cursor_cache); - - let (compacted_splits, splits_collapsed) = compact_mapped_splits(mapped_splits)?; - let (compacted_divs, divs_collapsed) = compact_mapped_dividends(mapped_divs)?; - stats.splits_collision_collapsed = splits_collapsed; - stats.dividends_collision_collapsed = divs_collapsed; - stats.listing_collision_collapsed = splits_collapsed + divs_collapsed; - - let built = build_adj_factors::(compacted_splits, compacted_divs)?; - - let mut rows: Vec = Vec::with_capacity(built.rows.len()); - for row in &built.rows { - let known_at_micros = et_session_close_utc_micros(row.ex_date).map_err(|source| { - CurateAdjError::ExDateOutOfRange { - listing_id: row.key, - ex_date: row.ex_date, - source, - } - })?; - rows.push(AdjFactorsParquetRow::from_adj_row(row, known_at_micros)); - } - - stats.builder = built.stats; - stats.rows_out = rows.len(); - stats.listings_out = built.stats.keys_out; - - let snapshot_kind = if is_fenced { - AdjSnapshotKind::PointInTimeFenced(fence) - } else { - AdjSnapshotKind::RetrospectiveSnapshot - }; - - Ok(CurateAdjFactorsOutput { - rows, - stats, - snapshot_kind, - }) -} - -/// Zero-allocation binary-search helper returning `(cum_split_factor, cum_total_factor)` of the -/// first curated row for `listing_id` with `ex_date > bar_date`, or `(1.0, 1.0)` if no such row -/// exists. -/// -/// Assumes `rows` is sorted ascending by `(listing_id, ex_date)` (as produced by -/// [`curate_adj_factors`] or [`curate_adj_factors_as_of`]). For point-in-time reads, pass rows -/// produced by [`curate_adj_factors_as_of`] with the desired `as_of` / `vault_cutoff` fence. -#[inline] -pub fn adj_factors_for_bar( - rows: &[AdjFactorsParquetRow], - listing_id: i32, - bar_date: i32, -) -> (f64, f64) { - let idx = rows.partition_point(|row| match row.listing_id.cmp(&listing_id) { - Ordering::Less => true, - Ordering::Equal => row.ex_date <= bar_date, - Ordering::Greater => false, - }); - match rows.get(idx) { - Some(row) if row.listing_id == listing_id => (row.cum_split_factor, row.cum_total_factor), - _ => (1.0, 1.0), - } -} - -/// Thin end-to-end wrapper running [`curate_adj_factors`] (retrospective full-history snapshot) -/// and atomically publishing `/adj_factors/part.parquet` with snapshot metadata embedded -/// in the Parquet footer `key_value_metadata`. -/// -/// Any [`CurateAdjError`] returns before touching `out_dir`, leaving any existing snapshot -/// untouched and publishing no `adj_factors/part.parquet`. -pub fn curate_and_write_adj_factors( - out_dir: P, - mapping: &ProviderMappingTable, - mapping_source: &str, - splits: S, - dividends: D, - options: AdjFactorsWriteOptions, -) -> Result -where - P: AsRef, - K: AsRef + Ord + Clone, - S: IntoIterator, - D: IntoIterator, -{ - curate_and_write_adj_factors_as_of( - out_dir, - mapping, - mapping_source, - splits, - dividends, - AdjPointInTimeFence::retrospective(), - options, - ) -} - -/// Point-in-time / vault-fenced end-to-end wrapper running [`curate_adj_factors_as_of`] and -/// atomically publishing `/adj_factors/part.parquet` in a single file commit with snapshot -/// metadata embedded in the Parquet footer `key_value_metadata`. -/// -/// - Any [`CurateAdjError`] returns before touching `out_dir`, leaving any existing snapshot -/// untouched and publishing no files. -/// - When the curated result has 0 rows (e.g. a fence excludes every event), an explicit 0-row -/// Zstd Parquet file with the contract [`adj_factors_parquet_schema`] and embedded footer -/// metadata is atomically published so any previously published `part.parquet` is superseded -/// rather than left stale on disk. -/// - The Parquet footer `key_value_metadata` binds `format_version`, `snapshot_kind`, exact -/// `as_of_micros` / `vault_cutoff_micros`, `rows_written`, and `snapshot_checksum` into the -/// single atomic file commit, allowing [`read_adj_factors_dataset_as_of`] to verify integrity, -/// per-row fence admission, and cumulative-chain consistency when reopening the artifact. -pub fn curate_and_write_adj_factors_as_of( - out_dir: P, - mapping: &ProviderMappingTable, - mapping_source: &str, - splits: S, - dividends: D, - fence: AdjPointInTimeFence, - options: AdjFactorsWriteOptions, -) -> Result -where - P: AsRef, - K: AsRef + Ord + Clone, - S: IntoIterator, - D: IntoIterator, -{ - let curated = curate_adj_factors_as_of(mapping, mapping_source, splits, dividends, fence)?; - let write_stats = write_adj_factors_snapshot_parquet( - out_dir.as_ref(), - &curated.rows, - curated.snapshot_kind, - options, - )?; - - Ok(CurateAdjFactorsWriteReport { - curate_stats: curated.stats, - write_stats, - snapshot_kind: curated.snapshot_kind, - }) -} - -/// Verified `adj_factors` snapshot reopened from `/adj_factors/part.parquet`. -#[derive(Debug, Clone, PartialEq)] -pub struct AdjFactorsSnapshot { - pub rows: Vec, - pub snapshot_kind: AdjSnapshotKind, -} - -impl AdjFactorsSnapshot { - /// Returns `(cum_split_factor, cum_total_factor)` of the first row for `listing_id` with - /// `ex_date > bar_date`, or `(1.0, 1.0)` if no such row exists. - #[inline] - pub fn factors_for_bar(&self, listing_id: i32, bar_date: i32) -> (f64, f64) { - adj_factors_for_bar(&self.rows, listing_id, bar_date) - } -} - -/// Typed error returned by [`read_adj_factors_dataset`] and [`read_adj_factors_dataset_as_of`]. -#[derive(Debug)] -pub enum CurateAdjReadError { - /// Caller passed an unfenced (`retrospective`) fence to [`read_adj_factors_dataset_as_of`]. - UnfencedReadRequested, - /// `/adj_factors/part.parquet` footer carries no `stock_bot.adj_factors.*` metadata - /// keys; refusing to open an unverified Parquet file. - MissingSnapshotMetadata { path: PathBuf }, - /// `/adj_factors/part.parquet` footer metadata has partial, duplicate, unknown, or - /// malformed `stock_bot.adj_factors.*` keys. - InvalidSnapshotMetadata { path: PathBuf, message: String }, - /// `/adj_factors/part.parquet` footer metadata carries an unsupported `format_version`. - UnsupportedSnapshotVersion { - path: PathBuf, - version: u32, - supported: u32, - }, - /// Point-in-time reader refused to open a retrospective full-history snapshot. - RetrospectiveSnapshotRejected { path: PathBuf }, - /// Point-in-time reader refused a snapshot whose persisted fence does not match the requested - /// fence. - IncompatibleFence { - path: PathBuf, - actual: AdjPointInTimeFence, - required: AdjPointInTimeFence, - }, - /// A decoded row's `known_at_micros` fell outside the snapshot's verified point-in-time / - /// vault fence. - RowOutsideFence { - path: PathBuf, - listing_id: i32, - ex_date: i32, - known_at_micros: i64, - fence: AdjPointInTimeFence, - }, - /// `/adj_factors/part.parquet` schema did not match [`adj_factors_parquet_schema`]. - SchemaMismatch { path: PathBuf }, - /// `/adj_factors/part.parquet` failed row-count, ordering, cumulative-split chain, - /// or bound snapshot checksum verification. - SnapshotIntegrityMismatch { path: PathBuf, detail: String }, - /// I/O error reading `part.parquet`. - Io { path: PathBuf, source: io::Error }, - /// Parquet decoding error reading `part.parquet`. - Parquet { path: PathBuf, source: ParquetError }, -} - -impl fmt::Display for CurateAdjReadError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::UnfencedReadRequested => write!( - f, - "read_adj_factors_dataset_as_of requires a non-retrospective point-in-time or vault fence" - ), - Self::MissingSnapshotMetadata { path } => write!( - f, - "missing adj_factors snapshot metadata in Parquet footer at '{}' (refusing to open unverified Parquet)", - path.display() - ), - Self::InvalidSnapshotMetadata { path, message } => write!( - f, - "invalid adj_factors snapshot metadata in Parquet footer at '{}': {message}", - path.display() - ), - Self::UnsupportedSnapshotVersion { - path, - version, - supported, - } => write!( - f, - "unsupported adj_factors snapshot metadata version {version} at '{}' (supported: {supported})", - path.display() - ), - Self::RetrospectiveSnapshotRejected { path } => write!( - f, - "point-in-time reader rejected retrospective adj_factors snapshot at '{}'", - path.display() - ), - Self::IncompatibleFence { - path, - actual, - required, - } => write!( - f, - "point-in-time reader rejected adj_factors snapshot at '{}': persisted fence {:?} does not match required fence {:?}", - path.display(), - actual, - required - ), - Self::RowOutsideFence { - path, - listing_id, - ex_date, - known_at_micros, - fence, - } => write!( - f, - "adj_factors row (listing_id={listing_id}, ex_date={ex_date}, known_at_micros={known_at_micros}) in '{}' falls outside fence {:?}", - path.display(), - fence - ), - Self::SchemaMismatch { path } => write!( - f, - "adj_factors Parquet schema mismatch at '{}'", - path.display() - ), - Self::SnapshotIntegrityMismatch { path, detail } => write!( - f, - "adj_factors snapshot integrity mismatch at '{}': {detail}", - path.display() - ), - Self::Io { path, source } => { - write!(f, "I/O error at '{}': {source}", path.display()) - } - Self::Parquet { path, source } => { - write!(f, "Parquet error at '{}': {source}", path.display()) - } - } - } -} - -impl Error for CurateAdjReadError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::Io { source, .. } => Some(source), - Self::Parquet { source, .. } => Some(source), - _ => None, - } - } -} - -/// Reopens a published `adj_factors` artifact from `/adj_factors/part.parquet` for -/// point-in-time research reads, requiring persisted [`AdjSnapshotKind::PointInTimeFenced`] footer -/// metadata whose exact fence matches `required_fence`. -/// -/// Fails closed if `required_fence` is retrospective, the Parquet footer lacks valid -/// `stock_bot.adj_factors.*` metadata, the published artifact is a -/// [`AdjSnapshotKind::RetrospectiveSnapshot`], the persisted fence differs from `required_fence`, -/// any row's `known_at` falls outside the fence, per-listing `cum_split_factor` suffix products -/// are inconsistent, or the bound snapshot checksum does not match. -pub fn read_adj_factors_dataset_as_of>( - out_dir: P, - required_fence: AdjPointInTimeFence, -) -> Result { - if required_fence.is_retrospective() { - return Err(CurateAdjReadError::UnfencedReadRequested); - } - let part_path = out_dir.as_ref().join("adj_factors").join("part.parquet"); - let reader = open_parquet_reader(&part_path)?; - let metadata = parse_snapshot_key_value_metadata( - &part_path, - reader.metadata().file_metadata().key_value_metadata(), - )?; - match metadata.snapshot_kind { - AdjSnapshotKind::RetrospectiveSnapshot => { - return Err(CurateAdjReadError::RetrospectiveSnapshotRejected { path: part_path }); - } - AdjSnapshotKind::PointInTimeFenced(actual) if actual != required_fence => { - return Err(CurateAdjReadError::IncompatibleFence { - path: part_path, - actual, - required: required_fence, - }); - } - AdjSnapshotKind::PointInTimeFenced(_) => {} - } - load_verified_parquet_snapshot(&part_path, &reader, &metadata) -} - -/// Reopens a published `adj_factors` artifact from `/adj_factors/part.parquet`, returning -/// its rows together with its verified [`AdjSnapshotKind`]. -/// -/// Requires valid `stock_bot.adj_factors.*` Parquet footer metadata and verifies schema, row -/// count, sort order, per-row fence admission (for fenced snapshots), per-listing -/// `cum_split_factor` suffix-product consistency, and the bound snapshot checksum. For -/// point-in-time research reads, prefer [`read_adj_factors_dataset_as_of`]. -pub fn read_adj_factors_dataset>( - out_dir: P, -) -> Result { - let part_path = out_dir.as_ref().join("adj_factors").join("part.parquet"); - let reader = open_parquet_reader(&part_path)?; - let metadata = parse_snapshot_key_value_metadata( - &part_path, - reader.metadata().file_metadata().key_value_metadata(), - )?; - load_verified_parquet_snapshot(&part_path, &reader, &metadata) -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -struct PersistedAdjSnapshotMetadata { - format_version: u32, - snapshot_kind: AdjSnapshotKind, - rows_written: usize, - snapshot_checksum: u64, -} - -fn fnv1a_update(mut hash: u64, bytes: &[u8]) -> u64 { - for &b in bytes { - hash ^= u64::from(b); - hash = hash.wrapping_mul(0x0000_0100_0000_01b3); - } - hash -} - -fn fnv1a_update_opt_i64(hash: u64, val: Option) -> u64 { - match val { - Some(v) => { - let hash = fnv1a_update(hash, &[1]); - fnv1a_update(hash, &v.to_le_bytes()) - } - None => fnv1a_update(hash, &[0]), - } -} - -fn compute_snapshot_checksum( - format_version: u32, - snapshot_kind: AdjSnapshotKind, - rows: &[AdjFactorsParquetRow], -) -> u64 { - let mut hash = 0xcbf2_9ce4_8422_2325_u64; - hash = fnv1a_update(hash, &format_version.to_le_bytes()); - let (kind_tag, as_of, vault_cutoff) = match snapshot_kind { - AdjSnapshotKind::RetrospectiveSnapshot => (0u8, None, None), - AdjSnapshotKind::PointInTimeFenced(fence) => { - (1u8, fence.as_of_micros, fence.vault_cutoff_micros) - } - }; - hash = fnv1a_update(hash, &[kind_tag]); - hash = fnv1a_update_opt_i64(hash, as_of); - hash = fnv1a_update_opt_i64(hash, vault_cutoff); - hash = fnv1a_update(hash, &(rows.len() as u64).to_le_bytes()); - - for row in rows { - hash = fnv1a_update(hash, &row.listing_id.to_le_bytes()); - hash = fnv1a_update(hash, &row.ex_date.to_le_bytes()); - hash = fnv1a_update(hash, &row.split_factor.to_bits().to_le_bytes()); - hash = fnv1a_update(hash, &row.div_cash.to_bits().to_le_bytes()); - match row.div_currency.as_deref() { - Some(curr) => { - hash = fnv1a_update(hash, &[1]); - hash = fnv1a_update(hash, &(curr.len() as u64).to_le_bytes()); - hash = fnv1a_update(hash, curr.as_bytes()); - } - None => { - hash = fnv1a_update(hash, &[0]); - } - } - hash = fnv1a_update(hash, &row.cum_split_factor.to_bits().to_le_bytes()); - hash = fnv1a_update(hash, &row.cum_total_factor.to_bits().to_le_bytes()); - hash = fnv1a_update(hash, &row.known_at_micros.to_le_bytes()); - } - hash -} - -fn format_opt_i64_kv(val: Option) -> String { - match val { - Some(v) => v.to_string(), - None => "none".to_string(), - } -} - -fn build_snapshot_key_value_metadata( - format_version: u32, - snapshot_kind: AdjSnapshotKind, - rows_written: usize, - snapshot_checksum: u64, -) -> Vec { - let (kind_str, as_of, vault_cutoff) = match snapshot_kind { - AdjSnapshotKind::RetrospectiveSnapshot => ("retrospective", None, None), - AdjSnapshotKind::PointInTimeFenced(fence) => ( - "point_in_time_fenced", - fence.as_of_micros, - fence.vault_cutoff_micros, - ), - }; - vec![ - KeyValue::new(KV_FORMAT_VERSION.to_string(), format_version.to_string()), - KeyValue::new(KV_SNAPSHOT_KIND.to_string(), kind_str.to_string()), - KeyValue::new(KV_AS_OF_MICROS.to_string(), format_opt_i64_kv(as_of)), - KeyValue::new( - KV_VAULT_CUTOFF_MICROS.to_string(), - format_opt_i64_kv(vault_cutoff), - ), - KeyValue::new(KV_ROWS_WRITTEN.to_string(), rows_written.to_string()), - KeyValue::new( - KV_SNAPSHOT_CHECKSUM.to_string(), - format!("0x{snapshot_checksum:016x}"), - ), - ] -} - -pub(crate) fn write_adj_factors_snapshot_parquet( - out_dir: &Path, - rows: &[AdjFactorsParquetRow], - snapshot_kind: AdjSnapshotKind, - options: AdjFactorsWriteOptions, -) -> Result { - write_adj_factors_snapshot_parquet_impl(out_dir, rows, snapshot_kind, options, |_, _| Ok(())) -} - -#[cfg(test)] -fn write_adj_factors_snapshot_parquet_with_hooks( - out_dir: &Path, - rows: &[AdjFactorsParquetRow], - snapshot_kind: AdjSnapshotKind, - options: AdjFactorsWriteOptions, - on_before_rename: F, -) -> Result -where - F: FnMut(&Path, Option<&Path>) -> io::Result<()>, -{ - write_adj_factors_snapshot_parquet_impl( - out_dir, - rows, - snapshot_kind, - options, - on_before_rename, - ) -} - -fn write_adj_factors_snapshot_parquet_impl( - out_dir: &Path, - rows: &[AdjFactorsParquetRow], - snapshot_kind: AdjSnapshotKind, - options: AdjFactorsWriteOptions, - mut on_before_rename: F, -) -> Result -where - F: FnMut(&Path, Option<&Path>) -> io::Result<()>, -{ - if options.row_group_rows == 0 { - return Err(ParquetAdjError::InvalidRowGroupRows); - } - let zstd_level = ZstdLevel::try_new(options.zstd_level).map_err(|_| { - ParquetAdjError::InvalidZstdLevel { - level: options.zstd_level, - } - })?; - - let adj_dir = out_dir.join("adj_factors"); - let schema = adj_factors_parquet_schema().map_err(|source| ParquetAdjError::Parquet { - path: adj_dir.clone(), - source, - })?; - let snapshot_checksum = - compute_snapshot_checksum(ADJ_SNAPSHOT_FORMAT_VERSION, snapshot_kind, rows); - let kv_metadata = build_snapshot_key_value_metadata( - ADJ_SNAPSHOT_FORMAT_VERSION, - snapshot_kind, - rows.len(), - snapshot_checksum, - ); - let props = Arc::new( - WriterProperties::builder() - .set_compression(Compression::ZSTD(zstd_level)) - .set_column_dictionary_enabled(ColumnPath::from("div_currency"), true) - .set_created_by(format!("curate-etl {}", env!("CARGO_PKG_VERSION"))) - .set_key_value_metadata(Some(kv_metadata)) - .build(), - ); - - fs::create_dir_all(&adj_dir).map_err(|source| ParquetAdjError::Io { - path: adj_dir.clone(), - source, - })?; - - let dataset_mu = dataset_mutex(&adj_dir); - let _in_process_guard = dataset_mu.lock().unwrap_or_else(|err| err.into_inner()); - let _file_lock = DatasetFileLock::acquire_with_timeout(&adj_dir, DEFAULT_LOCK_TIMEOUT)?; - - let run_id = next_run_id(); - let (tmp_path, tmp_file) = create_exclusive_tmp_file(&adj_dir, &run_id)?; - let mut staging_guard = StagingFileGuard::new(tmp_path.clone()); - let final_path = adj_dir.join("part.parquet"); - - let map_pq = |source: ParquetError| ParquetAdjError::Parquet { - path: tmp_path.clone(), - source, - }; - - let buf_writer = BufWriter::with_capacity(FILE_BUF_CAPACITY_BYTES, tmp_file); - let mut writer = SerializedFileWriter::new(buf_writer, schema, props).map_err(map_pq)?; - - let mut row_groups_written = 0usize; - if !rows.is_empty() { - let cap = rows.len().min(options.row_group_rows); - let mut listing_id = Vec::with_capacity(cap); - let mut ex_date = Vec::with_capacity(cap); - let mut split_factor = Vec::with_capacity(cap); - let mut div_cash = Vec::with_capacity(cap); - let mut div_currency_ids = Vec::with_capacity(cap); - let mut div_currency_def_levels = Vec::with_capacity(cap); - let mut div_currency_interner = StringInterner::default(); - let mut cum_split_factor = Vec::with_capacity(cap); - let mut cum_total_factor = Vec::with_capacity(cap); - let mut known_at_micros = Vec::with_capacity(cap); - let mut scratch: Vec = Vec::with_capacity(STRING_WRITE_BATCH_ROWS); - - for chunk in rows.chunks(options.row_group_rows) { - listing_id.clear(); - ex_date.clear(); - split_factor.clear(); - div_cash.clear(); - div_currency_ids.clear(); - div_currency_def_levels.clear(); - div_currency_interner.clear(); - cum_split_factor.clear(); - cum_total_factor.clear(); - known_at_micros.clear(); - - for row in chunk { - listing_id.push(row.listing_id); - ex_date.push(row.ex_date); - split_factor.push(row.split_factor); - div_cash.push(row.div_cash); - match row.div_currency.as_deref() { - Some(currency) => { - let id = div_currency_interner.intern(currency); - div_currency_ids.push(id); - div_currency_def_levels.push(1); - } - None => { - div_currency_def_levels.push(0); - } - } - cum_split_factor.push(row.cum_split_factor); - cum_total_factor.push(row.cum_total_factor); - known_at_micros.push(row.known_at_micros); - } - - let mut rg_writer = writer.next_row_group().map_err(map_pq)?; - write_i32_col(&mut rg_writer, &listing_id).map_err(map_pq)?; - write_i32_col(&mut rg_writer, &ex_date).map_err(map_pq)?; - write_f64_col(&mut rg_writer, &split_factor, None).map_err(map_pq)?; - write_f64_col(&mut rg_writer, &div_cash, None).map_err(map_pq)?; - write_optional_interned_str_col( - &mut rg_writer, - &div_currency_ids, - &div_currency_def_levels, - &div_currency_interner, - &mut scratch, - ) - .map_err(map_pq)?; - write_f64_col(&mut rg_writer, &cum_split_factor, None).map_err(map_pq)?; - write_f64_col(&mut rg_writer, &cum_total_factor, None).map_err(map_pq)?; - write_i64_col(&mut rg_writer, &known_at_micros).map_err(map_pq)?; - rg_writer.close().map_err(map_pq)?; - - row_groups_written += 1; - } - } - - let mut buf_writer = writer.into_inner().map_err(map_pq)?; - buf_writer.flush().map_err(|source| ParquetAdjError::Io { - path: tmp_path.clone(), - source, - })?; - let file = buf_writer - .into_inner() - .map_err(|err| ParquetAdjError::Io { - path: tmp_path.clone(), - source: err.into_error(), - })?; - file.sync_all().map_err(|source| ParquetAdjError::Io { - path: tmp_path.clone(), - source, - })?; - let bytes = file - .metadata() - .map_err(|source| ParquetAdjError::Io { - path: tmp_path.clone(), - source, - })? - .len(); - drop(file); - - let backup_path = match fs::symlink_metadata(&final_path) { - Ok(meta) if !meta.is_dir() => Some(create_backup_preserving_live(&final_path, &run_id)?), - Ok(_) => None, - Err(err) if err.kind() == io::ErrorKind::NotFound => None, - Err(source) => { - return Err(ParquetAdjError::Io { - path: final_path, - source, - }); - } - }; - - let commit_result = on_before_rename(&final_path, backup_path.as_deref()) - .and_then(|()| fs::rename(&tmp_path, &final_path)); - if let Err(source) = commit_result { - let backup_remove_failure = backup_path.and_then(|bak| { - fs::remove_file(&bak).err().map(|remove_err| RollbackFailure { - final_path: final_path.clone(), - backup_path: Some(bak), - source: remove_err, - }) - }); - let cause = ParquetAdjError::Io { - path: final_path, - source, - }; - return match backup_remove_failure { - Some(failure) => Err(ParquetAdjError::RollbackFailed { - cause: Box::new(cause), - failures: vec![failure], - }), - None => Err(cause), - }; - } - - staging_guard.disarm(); - - if let Some(bak) = backup_path { - if let Err(remove_err) = fs::remove_file(&bak) { - let cause = ParquetAdjError::Io { - path: bak.clone(), - source: remove_err, - }; - return match fs::rename(&bak, &final_path) { - Ok(()) => Err(cause), - Err(restore_err) => Err(ParquetAdjError::RollbackFailed { - cause: Box::new(cause), - failures: vec![RollbackFailure { - final_path, - backup_path: Some(bak), - source: restore_err, - }], - }), - }; - } - } - - Ok(AdjFactorsWriteStats { - rows_written: rows.len(), - files_written: 1, - row_groups_written, - bytes_written: bytes, - }) -} - -fn open_parquet_reader(part_path: &Path) -> Result, CurateAdjReadError> { - let file = File::open(part_path).map_err(|source| CurateAdjReadError::Io { - path: part_path.to_path_buf(), - source, - })?; - SerializedFileReader::new(file).map_err(|source| CurateAdjReadError::Parquet { - path: part_path.to_path_buf(), - source, - }) -} - -fn parse_opt_i64_kv( - value: &str, - field: &str, - path: &Path, -) -> Result, CurateAdjReadError> { - if value == "none" { - return Ok(None); - } - value - .parse::() - .map(Some) - .map_err(|_| CurateAdjReadError::InvalidSnapshotMetadata { - path: path.to_path_buf(), - message: format!("invalid i64 value '{value}' for '{field}'"), - }) -} - -fn parse_snapshot_key_value_metadata( - path: &Path, - kv_meta: Option<&Vec>, -) -> Result { - let invalid = |msg: &str| CurateAdjReadError::InvalidSnapshotMetadata { - path: path.to_path_buf(), - message: msg.to_string(), - }; - - let Some(entries) = kv_meta else { - return Err(CurateAdjReadError::MissingSnapshotMetadata { - path: path.to_path_buf(), - }); - }; - - let mut found_any = false; - let mut format_version: Option = None; - let mut snapshot_kind_str: Option<&str> = None; - let mut as_of_micros: Option> = None; - let mut vault_cutoff_micros: Option> = None; - let mut rows_written: Option = None; - let mut snapshot_checksum: Option = None; - - for kv in entries { - if !kv.key.starts_with(KV_PREFIX) { - continue; - } - found_any = true; - let val = kv.value.as_deref().ok_or_else(|| { - CurateAdjReadError::InvalidSnapshotMetadata { - path: path.to_path_buf(), - message: format!("missing value for metadata key '{}'", kv.key), - } - })?; - - match kv.key.as_str() { - KV_FORMAT_VERSION => { - if format_version.is_some() { - return Err(invalid("duplicate 'stock_bot.adj_factors.format_version' key")); - } - format_version = Some( - val.parse::() - .map_err(|_| invalid("invalid 'stock_bot.adj_factors.format_version'"))?, - ); - } - KV_SNAPSHOT_KIND => { - if snapshot_kind_str.is_some() { - return Err(invalid("duplicate 'stock_bot.adj_factors.snapshot_kind' key")); - } - snapshot_kind_str = Some(val); - } - KV_AS_OF_MICROS => { - if as_of_micros.is_some() { - return Err(invalid("duplicate 'stock_bot.adj_factors.as_of_micros' key")); - } - as_of_micros = Some(parse_opt_i64_kv(val, KV_AS_OF_MICROS, path)?); - } - KV_VAULT_CUTOFF_MICROS => { - if vault_cutoff_micros.is_some() { - return Err(invalid( - "duplicate 'stock_bot.adj_factors.vault_cutoff_micros' key", - )); - } - vault_cutoff_micros = Some(parse_opt_i64_kv(val, KV_VAULT_CUTOFF_MICROS, path)?); - } - KV_ROWS_WRITTEN => { - if rows_written.is_some() { - return Err(invalid("duplicate 'stock_bot.adj_factors.rows_written' key")); - } - rows_written = Some( - val.parse::() - .map_err(|_| invalid("invalid 'stock_bot.adj_factors.rows_written'"))?, - ); - } - KV_SNAPSHOT_CHECKSUM => { - if snapshot_checksum.is_some() { - return Err(invalid( - "duplicate 'stock_bot.adj_factors.snapshot_checksum' key", - )); - } - let hex = val.strip_prefix("0x").ok_or_else(|| { - invalid("'stock_bot.adj_factors.snapshot_checksum' must start with '0x'") - })?; - if hex.len() != 16 { - return Err(invalid( - "'stock_bot.adj_factors.snapshot_checksum' must be 16 hex digits", - )); - } - snapshot_checksum = Some( - u64::from_str_radix(hex, 16) - .map_err(|_| invalid("invalid hex in 'stock_bot.adj_factors.snapshot_checksum'"))?, - ); - } - other => { - return Err(CurateAdjReadError::InvalidSnapshotMetadata { - path: path.to_path_buf(), - message: format!("unknown metadata key '{other}'"), - }); - } - } - } - - if !found_any { - return Err(CurateAdjReadError::MissingSnapshotMetadata { - path: path.to_path_buf(), - }); - } - - let format_version = format_version - .ok_or_else(|| invalid("missing 'stock_bot.adj_factors.format_version'"))?; - if format_version != ADJ_SNAPSHOT_FORMAT_VERSION { - return Err(CurateAdjReadError::UnsupportedSnapshotVersion { - path: path.to_path_buf(), - version: format_version, - supported: ADJ_SNAPSHOT_FORMAT_VERSION, - }); - } - - let snapshot_kind_str = snapshot_kind_str - .ok_or_else(|| invalid("missing 'stock_bot.adj_factors.snapshot_kind'"))?; - let as_of_micros = - as_of_micros.ok_or_else(|| invalid("missing 'stock_bot.adj_factors.as_of_micros'"))?; - let vault_cutoff_micros = vault_cutoff_micros - .ok_or_else(|| invalid("missing 'stock_bot.adj_factors.vault_cutoff_micros'"))?; - let rows_written = - rows_written.ok_or_else(|| invalid("missing 'stock_bot.adj_factors.rows_written'"))?; - let snapshot_checksum = snapshot_checksum - .ok_or_else(|| invalid("missing 'stock_bot.adj_factors.snapshot_checksum'"))?; - - let snapshot_kind = match snapshot_kind_str { - "retrospective" => { - if as_of_micros.is_some() || vault_cutoff_micros.is_some() { - return Err(invalid( - "retrospective snapshot must have 'none' as_of_micros and vault_cutoff_micros", - )); - } - AdjSnapshotKind::RetrospectiveSnapshot - } - "point_in_time_fenced" => { - let fence = AdjPointInTimeFence { - as_of_micros, - vault_cutoff_micros, - }; - if fence.is_retrospective() { - return Err(invalid( - "point_in_time_fenced snapshot must specify as_of_micros and/or vault_cutoff_micros", - )); - } - AdjSnapshotKind::PointInTimeFenced(fence) - } - other => { - return Err(CurateAdjReadError::InvalidSnapshotMetadata { - path: path.to_path_buf(), - message: format!("unknown snapshot_kind '{other}'"), - }); - } - }; - - Ok(PersistedAdjSnapshotMetadata { - format_version, - snapshot_kind, - rows_written, - snapshot_checksum, - }) -} - -fn load_verified_parquet_snapshot( - part_path: &Path, - reader: &SerializedFileReader, - metadata: &PersistedAdjSnapshotMetadata, -) -> Result { - let expected_schema = adj_factors_parquet_schema().map_err(|source| { - CurateAdjReadError::Parquet { - path: part_path.to_path_buf(), - source, - } - })?; - if reader.metadata().file_metadata().schema_descr().root_schema() != expected_schema.as_ref() { - return Err(CurateAdjReadError::SchemaMismatch { - path: part_path.to_path_buf(), - }); - } - - let footer_rows = - usize::try_from(reader.metadata().file_metadata().num_rows()).map_err(|_| { - CurateAdjReadError::SnapshotIntegrityMismatch { - path: part_path.to_path_buf(), - detail: format!( - "negative or overflowing Parquet footer row count {}", - reader.metadata().file_metadata().num_rows() - ), - } - })?; - if footer_rows != metadata.rows_written { - return Err(CurateAdjReadError::SnapshotIntegrityMismatch { - path: part_path.to_path_buf(), - detail: format!( - "parquet footer row count {footer_rows} does not match metadata rows_written {}", - metadata.rows_written - ), - }); - } - - let mut rows = Vec::with_capacity(footer_rows); - let file_meta = reader.metadata(); - for rg_idx in 0..file_meta.num_row_groups() { - let rg_reader = - reader - .get_row_group(rg_idx) - .map_err(|source| CurateAdjReadError::Parquet { - path: part_path.to_path_buf(), - source, - })?; - let num_rows = usize::try_from(file_meta.row_group(rg_idx).num_rows()).map_err(|_| { - CurateAdjReadError::SnapshotIntegrityMismatch { - path: part_path.to_path_buf(), - detail: "negative or overflowing row-group row count".to_string(), - } - })?; - - let read_i32 = |col_idx: usize| -> Result, CurateAdjReadError> { - let mut vals = Vec::with_capacity(num_rows); - match rg_reader - .get_column_reader(col_idx) - .map_err(|source| CurateAdjReadError::Parquet { - path: part_path.to_path_buf(), - source, - })? { - ColumnReader::Int32ColumnReader(mut r) => { - let (read, _, _) = r - .read_records(num_rows, None, None, &mut vals) - .map_err(|source| CurateAdjReadError::Parquet { - path: part_path.to_path_buf(), - source, - })?; - if read != num_rows { - return Err(CurateAdjReadError::SnapshotIntegrityMismatch { - path: part_path.to_path_buf(), - detail: format!( - "column {col_idx} returned {read} rows, expected {num_rows}" - ), - }); - } - } - _ => { - return Err(CurateAdjReadError::SchemaMismatch { - path: part_path.to_path_buf(), - }); - } - } - Ok(vals) - }; - let read_i64 = |col_idx: usize| -> Result, CurateAdjReadError> { - let mut vals = Vec::with_capacity(num_rows); - match rg_reader - .get_column_reader(col_idx) - .map_err(|source| CurateAdjReadError::Parquet { - path: part_path.to_path_buf(), - source, - })? { - ColumnReader::Int64ColumnReader(mut r) => { - let (read, _, _) = r - .read_records(num_rows, None, None, &mut vals) - .map_err(|source| CurateAdjReadError::Parquet { - path: part_path.to_path_buf(), - source, - })?; - if read != num_rows { - return Err(CurateAdjReadError::SnapshotIntegrityMismatch { - path: part_path.to_path_buf(), - detail: format!( - "column {col_idx} returned {read} rows, expected {num_rows}" - ), - }); - } - } - _ => { - return Err(CurateAdjReadError::SchemaMismatch { - path: part_path.to_path_buf(), - }); - } - } - Ok(vals) - }; - let read_f64 = |col_idx: usize| -> Result, CurateAdjReadError> { - let mut vals = Vec::with_capacity(num_rows); - match rg_reader - .get_column_reader(col_idx) - .map_err(|source| CurateAdjReadError::Parquet { - path: part_path.to_path_buf(), - source, - })? { - ColumnReader::DoubleColumnReader(mut r) => { - let (read, _, _) = r - .read_records(num_rows, None, None, &mut vals) - .map_err(|source| CurateAdjReadError::Parquet { - path: part_path.to_path_buf(), - source, - })?; - if read != num_rows { - return Err(CurateAdjReadError::SnapshotIntegrityMismatch { - path: part_path.to_path_buf(), - detail: format!( - "column {col_idx} returned {read} rows, expected {num_rows}" - ), - }); - } - } - _ => { - return Err(CurateAdjReadError::SchemaMismatch { - path: part_path.to_path_buf(), - }); - } - } - Ok(vals) - }; - let read_opt_str = |col_idx: usize| -> Result>, CurateAdjReadError> { - let mut vals = Vec::with_capacity(num_rows); - let mut def_levels = Vec::with_capacity(num_rows); - match rg_reader - .get_column_reader(col_idx) - .map_err(|source| CurateAdjReadError::Parquet { - path: part_path.to_path_buf(), - source, - })? { - ColumnReader::ByteArrayColumnReader(mut r) => { - let (read, _, levels_read) = r - .read_records(num_rows, Some(&mut def_levels), None, &mut vals) - .map_err(|source| CurateAdjReadError::Parquet { - path: part_path.to_path_buf(), - source, - })?; - if read != num_rows || levels_read != num_rows { - return Err(CurateAdjReadError::SnapshotIntegrityMismatch { - path: part_path.to_path_buf(), - detail: format!( - "column {col_idx} returned ({read}, {levels_read}) rows, expected {num_rows}" - ), - }); - } - } - _ => { - return Err(CurateAdjReadError::SchemaMismatch { - path: part_path.to_path_buf(), - }); - } - } - let mut val_idx = 0usize; - let mut out = Vec::with_capacity(num_rows); - for def in def_levels { - match def { - 0 => out.push(None), - 1 => { - let bytes = vals.get(val_idx).ok_or_else(|| { - CurateAdjReadError::SnapshotIntegrityMismatch { - path: part_path.to_path_buf(), - detail: "definition levels exceeded byte array values".to_string(), - } - })?; - let text = std::str::from_utf8(bytes.data()) - .map_err(|_| CurateAdjReadError::SnapshotIntegrityMismatch { - path: part_path.to_path_buf(), - detail: "non-UTF8 div_currency value in Parquet".to_string(), - })? - .to_owned(); - val_idx += 1; - out.push(Some(text)); - } - other => { - return Err(CurateAdjReadError::SnapshotIntegrityMismatch { - path: part_path.to_path_buf(), - detail: format!("unexpected definition level {other} in div_currency"), - }); - } - } - } - Ok(out) - }; - - let listing_id = read_i32(0)?; - let ex_date = read_i32(1)?; - let split_factor = read_f64(2)?; - let div_cash = read_f64(3)?; - let div_currency = read_opt_str(4)?; - let cum_split_factor = read_f64(5)?; - let cum_total_factor = read_f64(6)?; - let known_at_micros = read_i64(7)?; - - for i in 0..num_rows { - rows.push(AdjFactorsParquetRow { - listing_id: listing_id[i], - ex_date: ex_date[i], - split_factor: split_factor[i], - div_cash: div_cash[i], - div_currency: div_currency[i].clone().map(Cow::Owned), - cum_split_factor: cum_split_factor[i], - cum_total_factor: cum_total_factor[i], - known_at_micros: known_at_micros[i], - }); - } - } - - if rows.len() != metadata.rows_written { - return Err(CurateAdjReadError::SnapshotIntegrityMismatch { - path: part_path.to_path_buf(), - detail: format!( - "decoded {} rows, metadata declared {}", - rows.len(), - metadata.rows_written - ), - }); - } - - for pair in rows.windows(2) { - if (pair[0].listing_id, pair[0].ex_date) >= (pair[1].listing_id, pair[1].ex_date) { - return Err(CurateAdjReadError::SnapshotIntegrityMismatch { - path: part_path.to_path_buf(), - detail: format!( - "rows are not strictly ascending by (listing_id, ex_date): ({}, {}) followed by ({}, {})", - pair[0].listing_id, pair[0].ex_date, pair[1].listing_id, pair[1].ex_date - ), - }); - } - } - - // 1. Verify every row's known_at falls inside the verified fence (for fenced snapshots). - if let AdjSnapshotKind::PointInTimeFenced(fence) = metadata.snapshot_kind { - for row in &rows { - if !fence.admits(row.known_at_micros) { - return Err(CurateAdjReadError::RowOutsideFence { - path: part_path.to_path_buf(), - listing_id: row.listing_id, - ex_date: row.ex_date, - known_at_micros: row.known_at_micros, - fence, - }); - } - } - } - - // 2. Verify per-listing cum_split_factor suffix-product consistency in reverse. - let mut start = 0usize; - while start < rows.len() { - let listing_id = rows[start].listing_id; - let mut end = start + 1; - while end < rows.len() && rows[end].listing_id == listing_id { - end += 1; - } - let mut running_split = 1.0_f64; - for row in rows[start..end].iter().rev() { - if row.split_factor != 1.0 { - running_split *= row.split_factor; - } - if row.cum_split_factor.to_bits() != running_split.to_bits() { - return Err(CurateAdjReadError::SnapshotIntegrityMismatch { - path: part_path.to_path_buf(), - detail: format!( - "cum_split_factor mismatch for (listing_id={}, ex_date={}): persisted {} != recomputed {}", - row.listing_id, row.ex_date, row.cum_split_factor, running_split - ), - }); - } - } - start = end; - } - - // 3. Verify bound snapshot checksum covering format_version, snapshot_kind/fence, and all rows. - let actual_checksum = - compute_snapshot_checksum(metadata.format_version, metadata.snapshot_kind, &rows); - if actual_checksum != metadata.snapshot_checksum { - return Err(CurateAdjReadError::SnapshotIntegrityMismatch { - path: part_path.to_path_buf(), - detail: format!( - "snapshot checksum 0x{actual_checksum:016x} does not match footer 0x{:016x}", - metadata.snapshot_checksum - ), - }); - } - - Ok(AdjFactorsSnapshot { - rows, - snapshot_kind: metadata.snapshot_kind, - }) -} - -#[cfg(test)] -#[path = "curate_adj_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/curate_adj_tests.rs b/tools/curate-etl/src/curate_adj_tests.rs deleted file mode 100644 index b4a4d0b9..00000000 --- a/tools/curate-etl/src/curate_adj_tests.rs +++ /dev/null @@ -1,2312 +0,0 @@ -use super::*; - -use std::borrow::Cow; -use std::error::Error; -use std::fs::{self, File}; -use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; - -use parquet::column::reader::ColumnReader; -use parquet::file::reader::{FileReader, SerializedFileReader}; - -use crate::parquet_adj::{adj_factors_parquet_schema, write_adj_factors_dataset}; -use crate::provider_mapping::ProviderMappingRow; -use crate::session_close::{ - SESSION_CLOSE_MAX_SUPPORTED_DATE, SESSION_CLOSE_MIN_SUPPORTED_DATE, -}; -use crate::split::{ymd_to_epoch_days, SplitTable}; - -static TEST_DIR_SEQ: AtomicU64 = AtomicU64::new(0); - -struct TestTempDir { - path: PathBuf, -} - -impl TestTempDir { - fn new(label: &str) -> Self { - let seq = TEST_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); - let path = std::env::temp_dir().join(format!( - "curate-etl-curate-adj-test-{label}-{}-{seq}", - std::process::id() - )); - fs::create_dir_all(&path).expect("create test temp dir"); - Self { path } - } -} - -impl Drop for TestTempDir { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.path); - } -} - -fn day(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).expect("valid date") -} - -fn map_row( - source: &str, - source_id: &str, - valid_from: i32, - valid_to: Option, - listing_id: i32, -) -> ProviderMappingRow { - ProviderMappingRow { - source: source.to_string(), - source_id: source_id.to_string(), - valid_from, - valid_to, - listing_id, - } -} - -fn div( - ex_date: i32, - cash: f64, - currency: &str, - prev_close: Option, - prev_close_currency: Option<&str>, -) -> DividendEvent { - DividendEvent { - ex_date, - cash, - currency: currency.to_string(), - prev_close, - prev_close_currency: prev_close_currency.map(str::to_string), - } -} - -fn assert_conservation(output: &CurateAdjFactorsOutput) { - let s = &output.stats; - assert_eq!( - s.splits_in, - s.splits_dropped_unmapped - + s.splits_dropped_fenced - + s.splits_collision_collapsed - + s.builder.split_events_in, - "split conservation invariant failed: {s:?}" - ); - assert_eq!( - s.dividends_in, - s.dividends_dropped_unmapped - + s.dividends_dropped_fenced - + s.dividends_collision_collapsed - + s.builder.dividend_events_in, - "dividend conservation invariant failed: {s:?}" - ); - if output.snapshot_kind == AdjSnapshotKind::RetrospectiveSnapshot { - assert_eq!(s.splits_dropped_fenced, 0); - assert_eq!(s.dividends_dropped_fenced, 0); - } - assert_eq!( - s.listing_collision_collapsed, - s.splits_collision_collapsed + s.dividends_collision_collapsed, - "listing_collision_collapsed must equal split + dividend collapses: {s:?}" - ); - assert_eq!(s.rows_out, s.builder.rows_out); - assert_eq!(s.rows_out, output.rows.len()); - assert_eq!(s.listings_out, s.builder.keys_out); - - for pair in output.rows.windows(2) { - assert!( - (pair[0].listing_id, pair[0].ex_date) < (pair[1].listing_id, pair[1].ex_date), - "rows must be strictly sorted and unique on (listing_id, ex_date): {:?} vs {:?}", - (pair[0].listing_id, pair[0].ex_date), - (pair[1].listing_id, pair[1].ex_date) - ); - } -} - -fn assert_rel_eq(actual: f64, expected: f64, rel_tol: f64) { - let diff = (actual - expected).abs(); - let scale = expected.abs().max(1.0); - assert!( - diff <= rel_tol * scale, - "actual={actual} expected={expected} diff={diff} rel_tol={rel_tol}" - ); -} - -fn assert_row_bitwise_eq(actual: &AdjFactorsParquetRow, expected: &AdjFactorsParquetRow) { - assert_eq!(actual.listing_id, expected.listing_id); - assert_eq!(actual.ex_date, expected.ex_date); - assert_eq!(actual.split_factor.to_bits(), expected.split_factor.to_bits()); - assert_eq!(actual.div_cash.to_bits(), expected.div_cash.to_bits()); - assert_eq!(actual.div_currency, expected.div_currency); - assert_eq!( - actual.cum_split_factor.to_bits(), - expected.cum_split_factor.to_bits() - ); - assert_eq!( - actual.cum_total_factor.to_bits(), - expected.cum_total_factor.to_bits() - ); - assert_eq!(actual.known_at_micros, expected.known_at_micros); -} - -fn cum_split_after_parquet(rows: &[AdjFactorsParquetRow], listing_id: i32, bar_date: i32) -> f64 { - let idx = rows.partition_point(|r| match r.listing_id.cmp(&listing_id) { - Ordering::Less => true, - Ordering::Equal => r.ex_date <= bar_date, - Ordering::Greater => false, - }); - match rows.get(idx) { - Some(r) if r.listing_id == listing_id => r.cum_split_factor, - _ => 1.0, - } -} - -fn read_parquet_rows(path: &Path) -> Vec { - let file = File::open(path).expect("open parquet file"); - let reader = SerializedFileReader::new(file).expect("open parquet reader"); - let metadata = reader.metadata(); - let mut out = Vec::new(); - - for rg_idx in 0..metadata.num_row_groups() { - let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); - let num_rows = metadata.row_group(rg_idx).num_rows() as usize; - - let read_i32 = |col_idx: usize| -> Vec { - let mut vals = Vec::with_capacity(num_rows); - match rg_reader.get_column_reader(col_idx).expect("col reader") { - ColumnReader::Int32ColumnReader(mut r) => { - let (read, _, _) = r - .read_records(num_rows, None, None, &mut vals) - .expect("read i32"); - assert_eq!(read, num_rows); - } - _ => panic!("expected INT32 column at index {col_idx}"), - } - vals - }; - let read_i64 = |col_idx: usize| -> Vec { - let mut vals = Vec::with_capacity(num_rows); - match rg_reader.get_column_reader(col_idx).expect("col reader") { - ColumnReader::Int64ColumnReader(mut r) => { - let (read, _, _) = r - .read_records(num_rows, None, None, &mut vals) - .expect("read i64"); - assert_eq!(read, num_rows); - } - _ => panic!("expected INT64 column at index {col_idx}"), - } - vals - }; - let read_f64 = |col_idx: usize| -> Vec { - let mut vals = Vec::with_capacity(num_rows); - match rg_reader.get_column_reader(col_idx).expect("col reader") { - ColumnReader::DoubleColumnReader(mut r) => { - let (read, _, _) = r - .read_records(num_rows, None, None, &mut vals) - .expect("read f64"); - assert_eq!(read, num_rows); - } - _ => panic!("expected DOUBLE column at index {col_idx}"), - } - vals - }; - let read_opt_str = |col_idx: usize| -> Vec> { - let mut vals = Vec::with_capacity(num_rows); - let mut def_levels = Vec::with_capacity(num_rows); - match rg_reader.get_column_reader(col_idx).expect("col reader") { - ColumnReader::ByteArrayColumnReader(mut r) => { - let (read, _, levels_read) = r - .read_records(num_rows, Some(&mut def_levels), None, &mut vals) - .expect("read optional utf8"); - assert_eq!(read, num_rows); - assert_eq!(levels_read, num_rows); - } - _ => panic!("expected BYTE_ARRAY column at index {col_idx}"), - } - let mut val_idx = 0usize; - let mut result = Vec::with_capacity(num_rows); - for def in def_levels { - match def { - 0 => result.push(None), - 1 => { - let text = std::str::from_utf8(vals[val_idx].data()) - .expect("valid utf8") - .to_owned(); - val_idx += 1; - result.push(Some(text)); - } - other => panic!("unexpected definition level {other}"), - } - } - assert_eq!(val_idx, vals.len()); - result - }; - - let listing_id = read_i32(0); - let ex_date = read_i32(1); - let split_factor = read_f64(2); - let div_cash = read_f64(3); - let div_currency = read_opt_str(4); - let cum_split_factor = read_f64(5); - let cum_total_factor = read_f64(6); - let known_at_micros = read_i64(7); - - for i in 0..num_rows { - out.push(AdjFactorsParquetRow { - listing_id: listing_id[i], - ex_date: ex_date[i], - split_factor: split_factor[i], - div_cash: div_cash[i], - div_currency: div_currency[i].clone().map(Cow::Owned), - cum_split_factor: cum_split_factor[i], - cum_total_factor: cum_total_factor[i], - known_at_micros: known_at_micros[i], - }); - } - } - out -} - -#[test] -fn nvda_ten_for_one_split_matches_split_table_before_on_and_after_ex_date() { - let mapping = ProviderMappingTable::from_rows([map_row( - "qm", - "NVDA", - day(1999, 1, 22), - None, - 42, - )]) - .unwrap(); - let ex_date = day(2024, 6, 10); - - let splits = [("NVDA", SplitEvent { ex_date, ratio: 10.0 })]; - let out = curate_adj_factors( - &mapping, - "qm", - splits, - std::iter::empty::<(&str, DividendEvent)>(), - ) - .unwrap(); - - assert_conservation(&out); - assert_eq!(out.rows.len(), 1); - assert_eq!(out.stats.listings_out, 1); - assert_eq!(out.rows[0].listing_id, 42); - assert_eq!(out.rows[0].ex_date, ex_date); - assert_eq!(out.rows[0].split_factor, 10.0); - assert_eq!(out.rows[0].cum_split_factor, 10.0); - assert_eq!(out.rows[0].cum_total_factor, 10.0); - assert_eq!(out.rows[0].div_cash, 0.0); - assert_eq!(out.rows[0].div_currency, None); - - let split_table = SplitTable::from_events([(42_i32, SplitEvent { ex_date, ratio: 10.0 })]).unwrap(); - for bar_date in [ex_date - 5, ex_date - 1, ex_date, ex_date + 1, ex_date + 30] { - let expected = split_table.cum_factor_after(&42, bar_date); - let actual = cum_split_after_parquet(&out.rows, 42, bar_date); - assert_eq!( - actual.to_bits(), - expected.to_bits(), - "mismatch on bar_date={bar_date}" - ); - } -} - -#[test] -fn ticker_rename_chains_cum_split_factor_continuously_under_one_listing_id() { - let rename_cutoff = day(2022, 6, 8); - let mapping = ProviderMappingTable::from_rows([ - map_row("qm", "OLD_TICK", day(2015, 1, 1), Some(rename_cutoff), 700), - map_row("qm", "NEW_TICK", rename_cutoff + 1, None, 700), - ]) - .unwrap(); - - let d1 = day(2020, 8, 31); // under OLD_TICK - let d2 = day(2024, 6, 10); // under NEW_TICK - - let out = curate_adj_factors( - &mapping, - "qm", - [ - ("OLD_TICK", SplitEvent { ex_date: d1, ratio: 4.0 }), - ("NEW_TICK", SplitEvent { ex_date: d2, ratio: 10.0 }), - ], - std::iter::empty::<(&str, DividendEvent)>(), - ) - .unwrap(); - - assert_conservation(&out); - assert_eq!(out.stats.listings_out, 1); - assert_eq!(out.rows.len(), 2); - - // Earliest row must reflect the product of both splits (4.0 * 10.0 = 40.0). - assert_eq!(out.rows[0].listing_id, 700); - assert_eq!(out.rows[0].ex_date, d1); - assert_eq!(out.rows[0].split_factor, 4.0); - assert_eq!(out.rows[0].cum_split_factor, 40.0); - assert_eq!(out.rows[0].cum_total_factor, 40.0); - - // Later row has only its own split (10.0). - assert_eq!(out.rows[1].listing_id, 700); - assert_eq!(out.rows[1].ex_date, d2); - assert_eq!(out.rows[1].split_factor, 10.0); - assert_eq!(out.rows[1].cum_split_factor, 10.0); - assert_eq!(out.rows[1].cum_total_factor, 10.0); -} - -#[test] -fn ticker_reuse_produces_two_independent_chains_without_cross_listing_bleed() { - // FB 2012-2022 -> listing 1001, FB 2025+ -> listing 2002 (non-overlapping ranges) - let mapping = ProviderMappingTable::from_rows([ - map_row("qm", "FB", day(2012, 5, 18), Some(day(2022, 6, 8)), 1001), - map_row("qm", "FB", day(2025, 1, 2), None, 2002), - ]) - .unwrap(); - - let d_old = day(2018, 4, 15); - let d_gap = day(2023, 7, 1); // unmapped gap between ranges - let d_new = day(2025, 9, 10); - - let out = curate_adj_factors( - &mapping, - "qm", - [ - ("FB", SplitEvent { ex_date: d_old, ratio: 2.0 }), - ("FB", SplitEvent { ex_date: d_gap, ratio: 3.0 }), - ("FB", SplitEvent { ex_date: d_new, ratio: 5.0 }), - ], - std::iter::empty::<(&str, DividendEvent)>(), - ) - .unwrap(); - - assert_conservation(&out); - assert_eq!(out.stats.splits_in, 3); - assert_eq!(out.stats.splits_dropped_unmapped, 1); - assert_eq!(out.stats.listings_out, 2); - assert_eq!(out.rows.len(), 2); - - // Listing 1001 must NOT be affected by listing 2002's 5:1 split. - assert_eq!(out.rows[0].listing_id, 1001); - assert_eq!(out.rows[0].ex_date, d_old); - assert_eq!(out.rows[0].split_factor, 2.0); - assert_eq!(out.rows[0].cum_split_factor, 2.0); - - // Listing 2002 has its own independent 5:1 split. - assert_eq!(out.rows[1].listing_id, 2002); - assert_eq!(out.rows[1].ex_date, d_new); - assert_eq!(out.rows[1].split_factor, 5.0); - assert_eq!(out.rows[1].cum_split_factor, 5.0); -} - -#[test] -fn unmapped_splits_and_dividends_are_dropped_and_counted_separately() { - let mapping = ProviderMappingTable::from_rows([map_row( - "qm", - "AAPL", - day(2020, 1, 1), - Some(day(2024, 12, 31)), - 10, - )]) - .unwrap(); - - let out = curate_adj_factors( - &mapping, - "qm", - [ - ("AAPL", SplitEvent { ex_date: day(2020, 8, 31), ratio: 4.0 }), - ("AAPL", SplitEvent { ex_date: day(2019, 1, 1), ratio: 2.0 }), // before valid_from - ("UNKNOWN", SplitEvent { ex_date: day(2022, 5, 1), ratio: 3.0 }), - ], - [ - ("AAPL", div(day(2024, 2, 9), 0.24, "USD", Some(188.0), Some("USD"))), - ("AAPL", div(day(2025, 2, 10), 0.25, "USD", Some(220.0), Some("USD"))), // after valid_to - ("NO_SUCH", div(day(2023, 5, 12), 0.50, "USD", Some(50.0), Some("USD"))), - ("NO_SUCH", div(day(2023, 8, 12), 0.50, "USD", Some(52.0), Some("USD"))), - ], - ) - .unwrap(); - - assert_conservation(&out); - assert_eq!(out.stats.splits_in, 3); - assert_eq!(out.stats.splits_dropped_unmapped, 2); - assert_eq!(out.stats.dividends_in, 4); - assert_eq!(out.stats.dividends_dropped_unmapped, 3); - assert_eq!(out.stats.builder.split_events_in, 1); - assert_eq!(out.stats.builder.dividend_events_in, 1); - assert_eq!(out.stats.rows_out, 2); - assert_eq!(out.stats.listings_out, 1); -} - -#[test] -fn bitwise_identical_cross_key_events_collapse_and_are_counted() { - // Two distinct source keys overlapping on the same listing_id. - let mapping = ProviderMappingTable::from_rows([ - map_row("qm", "SYM_A", day(2020, 1, 1), None, 55), - map_row("qm", "SYM_B", day(2020, 1, 1), None, 55), - map_row("qm", "SYM_C", day(2020, 1, 1), None, 55), - ]) - .unwrap(); - - let d_split = day(2022, 6, 15); - let d_div = day(2023, 9, 15); - let div_ev = div(d_div, 1.25, "USD", Some(100.0), Some("USD")); - - let out = curate_adj_factors( - &mapping, - "qm", - [ - ("SYM_A", SplitEvent { ex_date: d_split, ratio: 2.0 }), - ("SYM_B", SplitEvent { ex_date: d_split, ratio: 2.0 }), - ("SYM_C", SplitEvent { ex_date: d_split, ratio: 2.0 }), - ], - [ - ("SYM_A", div_ev.clone()), - ("SYM_B", div_ev), - ], - ) - .unwrap(); - - assert_conservation(&out); - assert_eq!(out.stats.splits_in, 3); - assert_eq!(out.stats.splits_collision_collapsed, 2); - assert_eq!(out.stats.dividends_in, 2); - assert_eq!(out.stats.dividends_collision_collapsed, 1); - assert_eq!(out.stats.listing_collision_collapsed, 3); - assert_eq!(out.stats.builder.split_events_in, 1); - assert_eq!(out.stats.builder.dividend_events_in, 1); - assert_eq!(out.rows.len(), 2); - - // Split was collapsed to a single 2:1 (NOT 2*2*2 = 8:1). - assert_eq!(out.rows[0].split_factor, 2.0); - assert_eq!(out.rows[0].cum_split_factor, 2.0); - // Dividend was collapsed to a single $1.25 (NOT $2.50). - assert_eq!(out.rows[1].div_cash, 1.25); - assert_rel_eq(out.rows[1].cum_total_factor, 100.0 / 98.75, 1e-12); -} - -#[test] -fn conflicting_cross_key_split_fails_closed_and_publishes_no_parquet() { - let mapping = ProviderMappingTable::from_rows([ - map_row("qm", "ALIAS_1", day(2020, 1, 1), None, 77), - map_row("qm", "ALIAS_2", day(2020, 1, 1), None, 77), - ]) - .unwrap(); - - let d = day(2023, 5, 1); - let splits = [ - ("ALIAS_1", SplitEvent { ex_date: d, ratio: 2.0 }), - ("ALIAS_2", SplitEvent { ex_date: d, ratio: 3.0 }), - ]; - - let err = curate_adj_factors( - &mapping, - "qm", - splits, - std::iter::empty::<(&str, DividendEvent)>(), - ) - .unwrap_err(); - assert_eq!( - err, - CurateAdjError::ConflictingCrossKeySplit { - listing_id: 77, - ex_date: d, - first_key: "ALIAS_1".to_string(), - first_ratio: 2.0, - second_key: "ALIAS_2".to_string(), - second_ratio: 3.0, - } - ); - assert!(err.source().is_none()); - let msg = err.to_string(); - assert!(msg.contains("77") && msg.contains("ALIAS_1") && msg.contains("ALIAS_2")); - - let temp = TestTempDir::new("conflict-split"); - let write_err = curate_and_write_adj_factors( - &temp.path, - &mapping, - "qm", - splits, - std::iter::empty::<(&str, DividendEvent)>(), - AdjFactorsWriteOptions::default(), - ) - .unwrap_err(); - assert!(matches!( - write_err, - CurateAdjWriteError::Curate(CurateAdjError::ConflictingCrossKeySplit { listing_id: 77, .. }) - )); - assert!(write_err.source().is_some()); - assert!( - !temp.path.join("adj_factors/part.parquet").exists(), - "curate error must not publish adj_factors/part.parquet" - ); - assert!( - !temp.path.join("adj_factors").exists(), - "curate error must leave out_dir untouched" - ); -} - -#[test] -fn conflicting_cross_key_dividend_fails_closed_on_any_field_mismatch() { - let mapping = ProviderMappingTable::from_rows([ - map_row("qm", "KEY_A", day(2020, 1, 1), None, 88), - map_row("qm", "KEY_B", day(2020, 1, 1), None, 88), - ]) - .unwrap(); - let d = day(2024, 3, 15); - let base = div(d, 0.50, "USD", Some(50.0), Some("USD")); - - let variants = [ - div(d, 0.75, "USD", Some(50.0), Some("USD")), // differing cash - div(d, 0.50, "CAD", Some(50.0), Some("USD")), // differing currency - div(d, 0.50, "USD", Some(51.0), Some("USD")), // differing prev_close - div(d, 0.50, "USD", Some(50.0), Some("CAD")), // differing prev_close_currency - div(d, 0.50, "USD", None, None), // missing prev_close vs present - ]; - - for (idx, other) in variants.into_iter().enumerate() { - let err = curate_adj_factors( - &mapping, - "qm", - std::iter::empty::<(&str, SplitEvent)>(), - [("KEY_A", base.clone()), ("KEY_B", other.clone())], - ) - .unwrap_err(); - assert_eq!( - err, - CurateAdjError::ConflictingCrossKeyDividend { - listing_id: 88, - ex_date: d, - first_key: "KEY_A".to_string(), - second_key: "KEY_B".to_string(), - }, - "variant {idx} should fail closed" - ); - - let temp = TestTempDir::new(&format!("conflict-div-{idx}")); - let write_err = curate_and_write_adj_factors( - &temp.path, - &mapping, - "qm", - std::iter::empty::<(&str, SplitEvent)>(), - [("KEY_A", base.clone()), ("KEY_B", other)], - AdjFactorsWriteOptions::default(), - ) - .unwrap_err(); - assert!(matches!( - write_err, - CurateAdjWriteError::Curate(CurateAdjError::ConflictingCrossKeyDividend { - listing_id: 88, - .. - }) - )); - assert!(!temp.path.join("adj_factors/part.parquet").exists()); - } -} - -#[test] -fn same_key_multi_events_noops_and_dividend_compounding_preserve_builder_semantics() { - let mapping = ProviderMappingTable::from_rows([map_row( - "qm", - "COMP", - day(2020, 1, 1), - None, - 300, - )]) - .unwrap(); - - let d_split = day(2022, 3, 1); - let d_noop = day(2022, 6, 1); - let d_div = day(2023, 9, 15); - let d_zero_div = day(2023, 12, 15); - - let out = curate_adj_factors( - &mapping, - "qm", - [ - // Same-key same-day splits multiply (2.0 * 1.5 = 3.0). - ("COMP", SplitEvent { ex_date: d_split, ratio: 2.0 }), - ("COMP", SplitEvent { ex_date: d_split, ratio: 1.5 }), - // 1:1 no-op split dropped by builder. - ("COMP", SplitEvent { ex_date: d_noop, ratio: 1.0 }), - ], - [ - // Same-key regular + special dividend sum (0.50 + 1.50 = 2.00). - ("COMP", div(d_div, 0.50, "USD", Some(100.0), Some("USD"))), - ("COMP", div(d_div, 1.50, "USD", Some(100.0), Some("USD"))), - // Zero-cash dividend dropped by builder. - ("COMP", div(d_zero_div, 0.0, "", None, None)), - ], - ) - .unwrap(); - - assert_conservation(&out); - assert_eq!(out.stats.listing_collision_collapsed, 0); - assert_eq!(out.stats.builder.split_noops_dropped, 1); - assert_eq!(out.stats.builder.dividend_zero_cash_dropped, 1); - assert_eq!(out.rows.len(), 2); - - let expected_div_factor = 100.0 / 98.0; - - // Earlier split row: cum_total_factor > cum_split_factor because of later dividend. - assert_eq!(out.rows[0].ex_date, d_split); - assert_eq!(out.rows[0].split_factor, 3.0); - assert_eq!(out.rows[0].cum_split_factor, 3.0); - assert!(out.rows[0].cum_total_factor > out.rows[0].cum_split_factor); - assert_rel_eq(out.rows[0].cum_total_factor, 3.0 * expected_div_factor, 1e-12); - - // Later dividend row. - assert_eq!(out.rows[1].ex_date, d_div); - assert_eq!(out.rows[1].split_factor, 1.0); - assert_eq!(out.rows[1].div_cash, 2.0); - assert_eq!(out.rows[1].div_currency.as_deref(), Some("USD")); - assert_eq!(out.rows[1].cum_split_factor, 1.0); - assert_rel_eq(out.rows[1].cum_total_factor, expected_div_factor, 1e-12); -} - -#[test] -fn invalid_builder_inputs_and_blank_mapping_source_return_typed_errors() { - let mapping = ProviderMappingTable::from_rows([map_row( - "qm", - "BAD", - day(2020, 1, 1), - None, - 50, - )]) - .unwrap(); - - // Blank mapping_source - for blank in ["", " ", "\t\n"] { - let err = curate_adj_factors( - &mapping, - blank, - std::iter::empty::<(&str, SplitEvent)>(), - std::iter::empty::<(&str, DividendEvent)>(), - ) - .unwrap_err(); - assert_eq!(err, CurateAdjError::EmptyMappingSource); - assert!(err.source().is_none()); - } - - // Invalid split ratio (NaN, 0.0, negative) propagates AdjError - let d = day(2023, 1, 10); - let err = curate_adj_factors( - &mapping, - "qm", - [("BAD", SplitEvent { ex_date: d, ratio: -1.0 })], - std::iter::empty::<(&str, DividendEvent)>(), - ) - .unwrap_err(); - assert_eq!( - err, - CurateAdjError::Adj(AdjError::InvalidSplitRatio { - ex_date: d, - ratio: -1.0 - }) - ); - assert!(err.source().is_some()); - - // Invalid dividend cash propagates AdjError - let err = curate_adj_factors( - &mapping, - "qm", - std::iter::empty::<(&str, SplitEvent)>(), - [("BAD", div(d, f64::NAN, "USD", None, None))], - ) - .unwrap_err(); - assert!(matches!( - err, - CurateAdjError::Adj(AdjError::InvalidDividendCash { ex_date, .. }) if ex_date == d - )); -} - -#[test] -fn known_at_matches_est_winter_and_edt_summer_and_out_of_range_ex_date_errors_without_panicking() { - let mapping = ProviderMappingTable::from_rows([map_row( - "qm", - "TZ", - i32::MIN, - None, - 99, - )]) - .unwrap(); - - let winter_est = day(2024, 1, 15); // EST -> 21:00 UTC - let summer_edt = day(2024, 7, 15); // EDT -> 20:00 UTC - - let out = curate_adj_factors( - &mapping, - "qm", - [ - ("TZ", SplitEvent { ex_date: winter_est, ratio: 2.0 }), - ("TZ", SplitEvent { ex_date: summer_edt, ratio: 3.0 }), - ], - std::iter::empty::<(&str, DividendEvent)>(), - ) - .unwrap(); - - assert_conservation(&out); - assert_eq!(out.rows.len(), 2); - - let expected_winter = et_session_close_utc_micros(winter_est).unwrap(); - let expected_summer = et_session_close_utc_micros(summer_edt).unwrap(); - assert_eq!(out.rows[0].known_at_micros, expected_winter); - assert_eq!(out.rows[1].known_at_micros, expected_summer); - // Sanity-check UTC hours: 21:00 UTC in EST, 20:00 UTC in EDT. - assert_eq!( - (out.rows[0].known_at_micros - i64::from(winter_est) * 86_400_000_000) / 3_600_000_000, - 21 - ); - assert_eq!( - (out.rows[1].known_at_micros - i64::from(summer_edt) * 86_400_000_000) / 3_600_000_000, - 20 - ); - - // Out-of-range dates outside 1976-01-01..=2030-12-31 must return typed error without panicking. - let bad_dates = [ - day(1975, 12, 31), - day(2031, 1, 1), - i32::MIN, - i32::MAX, - ]; - for bad_date in bad_dates { - let err = curate_adj_factors( - &mapping, - "qm", - [("TZ", SplitEvent { ex_date: bad_date, ratio: 2.0 })], - std::iter::empty::<(&str, DividendEvent)>(), - ) - .unwrap_err(); - assert_eq!( - err, - CurateAdjError::ExDateOutOfRange { - listing_id: 99, - ex_date: bad_date, - source: SessionCloseError::DateOutOfRange { - epoch_day: bad_date, - min_supported: SESSION_CLOSE_MIN_SUPPORTED_DATE, - max_supported: SESSION_CLOSE_MAX_SUPPORTED_DATE, - }, - } - ); - assert!(err.source().is_some()); - let msg = err.to_string(); - assert!( - msg.contains("99") && msg.contains(&bad_date.to_string()), - "Display must name listing_id and ex_date, got: {msg}" - ); - } - - // Also verify boundary dates 1976-01-01 and 2030-12-31 succeed. - let boundary_out = curate_adj_factors( - &mapping, - "qm", - [ - ("TZ", SplitEvent { ex_date: SESSION_CLOSE_MIN_SUPPORTED_DATE, ratio: 2.0 }), - ("TZ", SplitEvent { ex_date: SESSION_CLOSE_MAX_SUPPORTED_DATE, ratio: 2.0 }), - ], - std::iter::empty::<(&str, DividendEvent)>(), - ) - .unwrap(); - assert_eq!(boundary_out.rows.len(), 2); -} - -#[test] -fn permutation_invariance_holds_across_splits_and_dividends() { - let mapping = ProviderMappingTable::from_rows([ - map_row("qm", "A_OLD", day(2010, 1, 1), Some(day(2020, 12, 31)), 100), - map_row("qm", "A_NEW", day(2021, 1, 1), None, 100), - map_row("qm", "A_ALIAS", day(2021, 1, 1), None, 100), - map_row("qm", "B", day(2015, 1, 1), None, 200), - ]) - .unwrap(); - - let base_splits = vec![ - ("A_OLD", SplitEvent { ex_date: day(2018, 5, 1), ratio: 2.0 }), - ("A_NEW", SplitEvent { ex_date: day(2023, 6, 1), ratio: 5.0 }), - ("A_ALIAS", SplitEvent { ex_date: day(2023, 6, 1), ratio: 5.0 }), - ("B", SplitEvent { ex_date: day(2022, 1, 10), ratio: 0.25 }), - ("UNMAPPED", SplitEvent { ex_date: day(2022, 3, 1), ratio: 2.0 }), - ]; - let base_divs = vec![ - ("A_OLD", div(day(2019, 3, 15), 0.40, "USD", Some(80.0), Some("USD"))), - ("A_NEW", div(day(2024, 3, 15), 0.50, "USD", Some(100.0), Some("USD"))), - ("A_ALIAS", div(day(2024, 3, 15), 0.50, "USD", Some(100.0), Some("USD"))), - ("B", div(day(2024, 4, 1), 1.00, "CAD", Some(40.0), Some("CAD"))), - ("B", div(day(2024, 4, 1), 0.25, "CAD", Some(40.0), Some("CAD"))), - ]; - - let baseline = curate_adj_factors(&mapping, "qm", base_splits.clone(), base_divs.clone()).unwrap(); - assert_conservation(&baseline); - - let mut rev_splits = base_splits; - rev_splits.reverse(); - let mut rev_divs = base_divs; - rev_divs.reverse(); - - let reversed = curate_adj_factors(&mapping, "qm", rev_splits, rev_divs).unwrap(); - assert_conservation(&reversed); - assert_eq!(reversed.stats, baseline.stats); - assert_eq!(reversed.rows.len(), baseline.rows.len()); - for (a, b) in reversed.rows.iter().zip(baseline.rows.iter()) { - assert_row_bitwise_eq(a, b); - } -} - -#[test] -fn curate_and_write_adj_factors_round_trips_parquet_schema_and_rows() { - let mapping = ProviderMappingTable::from_rows([ - map_row("qm", "NVDA", day(1999, 1, 22), None, 10), - map_row("qm", "RY.TO", day(2000, 1, 1), None, 20), - map_row("qm", "RY_ALIAS", day(2000, 1, 1), None, 20), - ]) - .unwrap(); - - let splits = vec![ - ("NVDA", SplitEvent { ex_date: day(2021, 7, 20), ratio: 4.0 }), - ("NVDA", SplitEvent { ex_date: day(2024, 6, 10), ratio: 10.0 }), - ("RY.TO", SplitEvent { ex_date: day(2022, 4, 1), ratio: 2.0 }), - ("RY_ALIAS", SplitEvent { ex_date: day(2022, 4, 1), ratio: 2.0 }), - ]; - let dividends = vec![ - ("NVDA", div(day(2024, 6, 11), 0.01, "USD", Some(120.0), Some("USD"))), - ("RY.TO", div(day(2024, 1, 25), 1.38, "CAD", Some(132.0), Some("CAD"))), - ("RY.TO", div(day(2024, 7, 25), 1.42, "CAD", None, None)), - ]; - - let in_mem = curate_adj_factors(&mapping, "qm", splits.clone(), dividends.clone()).unwrap(); - assert_conservation(&in_mem); - - let temp = TestTempDir::new("round-trip"); - let report = curate_and_write_adj_factors( - &temp.path, - &mapping, - "qm", - splits, - dividends, - AdjFactorsWriteOptions::default(), - ) - .unwrap(); - - assert_eq!(report.curate_stats, in_mem.stats); - assert_eq!(report.write_stats.rows_written, in_mem.rows.len()); - assert_eq!(report.write_stats.files_written, 1); - assert!(report.write_stats.bytes_written > 0); - - let part_path = temp.path.join("adj_factors/part.parquet"); - assert!(part_path.is_file()); - - // Verify Parquet schema matches contract schema from adj_factors_parquet_schema(). - let expected_schema = adj_factors_parquet_schema().unwrap(); - let file = File::open(&part_path).unwrap(); - let reader = SerializedFileReader::new(file).unwrap(); - assert_eq!( - reader.metadata().file_metadata().schema_descr().root_schema(), - expected_schema.as_ref() - ); - - // Read back all rows and assert bitwise identity plus strict (listing_id, ex_date) ordering. - let read_back = read_parquet_rows(&part_path); - assert_eq!(read_back.len(), in_mem.rows.len()); - for (actual, expected) in read_back.iter().zip(in_mem.rows.iter()) { - assert_row_bitwise_eq(actual, expected); - } - for pair in read_back.windows(2) { - assert!((pair[0].listing_id, pair[0].ex_date) < (pair[1].listing_id, pair[1].ex_date)); - } - - // Empty input publishes an explicit 0-row Parquet with embedded footer metadata that round-trips. - let empty_temp = TestTempDir::new("empty"); - let empty_report = curate_and_write_adj_factors( - &empty_temp.path, - &mapping, - "qm", - std::iter::empty::<(&str, SplitEvent)>(), - std::iter::empty::<(&str, DividendEvent)>(), - AdjFactorsWriteOptions::default(), - ) - .unwrap(); - assert_eq!(empty_report.curate_stats.rows_out, 0); - assert_eq!(empty_report.write_stats.rows_written, 0); - assert_eq!(empty_report.write_stats.files_written, 1); - assert!(empty_report.write_stats.bytes_written > 0); - assert_eq!(empty_report.snapshot_kind, AdjSnapshotKind::RetrospectiveSnapshot); - assert!(empty_temp.path.join("adj_factors/part.parquet").is_file()); - assert!(!empty_temp.path.join("adj_factors/snapshot.json").exists()); - let empty_loaded = read_adj_factors_dataset(&empty_temp.path).unwrap(); - assert!(empty_loaded.rows.is_empty()); - assert_eq!(empty_loaded.snapshot_kind, AdjSnapshotKind::RetrospectiveSnapshot); -} - -#[test] -fn point_in_time_fencing_keeps_earlier_adjusted_read_identical_when_future_actions_are_appended() { - let mapping = ProviderMappingTable::from_rows([ - map_row("qm", "NVDA", day(1999, 1, 22), None, 42), - map_row("qm", "NVDA_ALIAS", day(1999, 1, 22), None, 42), - ]) - .unwrap(); - - let d_split_2021 = day(2021, 7, 20); // 4:1 split - let d_div_2022 = day(2022, 9, 7); // $0.04 dividend on $137.00 prev_close - let d_split_2024 = day(2024, 6, 10); // 10:1 split (future relative to Dec 2023) - let d_div_2024 = day(2024, 9, 12); // future dividend - - let bar_pre_2021 = day(2021, 1, 4); - let raw_close = 800.0_f64; - - // Dec 31, 2023 23:59:59.999999 UTC - let as_of_dec_2023 = i64::from(day(2024, 1, 1)) * 86_400_000_000 - 1; - let fence = AdjPointInTimeFence::as_of(as_of_dec_2023); - - // Baseline: only events through 2023 exist. - let base_splits = vec![("NVDA", SplitEvent { ex_date: d_split_2021, ratio: 4.0 })]; - let base_divs = vec![( - "NVDA", - div(d_div_2022, 0.04, "USD", Some(137.0), Some("USD")), - )]; - - let pit_before = curate_adj_factors_as_of( - &mapping, - "qm", - base_splits.clone(), - base_divs.clone(), - fence, - ) - .unwrap(); - assert_conservation(&pit_before); - assert_eq!(pit_before.snapshot_kind, AdjSnapshotKind::PointInTimeFenced(fence)); - assert_eq!(pit_before.stats.splits_dropped_fenced, 0); - assert_eq!(pit_before.stats.dividends_dropped_fenced, 0); - - let (split_f_before, total_f_before) = adj_factors_for_bar(&pit_before.rows, 42, bar_pre_2021); - assert_eq!(split_f_before, 4.0); - assert_eq!(raw_close / split_f_before, 200.0); - - // Now append the June 2024 10:1 split, a Sept 2024 dividend, AND a conflicting future alias - // split on June 2024 — none of them existed as of Dec 31, 2023. - let mut with_future_splits = base_splits.clone(); - with_future_splits.push(("NVDA", SplitEvent { ex_date: d_split_2024, ratio: 10.0 })); - with_future_splits.push(("NVDA_ALIAS", SplitEvent { ex_date: d_split_2024, ratio: 99.0 })); - let mut with_future_divs = base_divs.clone(); - with_future_divs.push(( - "NVDA", - div(d_div_2024, 0.01, "USD", Some(115.0), Some("USD")), - )); - - let pit_after = curate_adj_factors_as_of( - &mapping, - "qm", - with_future_splits, - with_future_divs, - fence, - ) - .unwrap(); - assert_conservation(&pit_after); - assert_eq!(pit_after.snapshot_kind, AdjSnapshotKind::PointInTimeFenced(fence)); - assert_eq!(pit_after.stats.splits_dropped_fenced, 2); - assert_eq!(pit_after.stats.dividends_dropped_fenced, 1); - assert_eq!(pit_after.rows.len(), pit_before.rows.len()); - - // Every curated row must be bitwise identical to the pre-future baseline. - for (actual, expected) in pit_after.rows.iter().zip(pit_before.rows.iter()) { - assert_row_bitwise_eq(actual, expected); - } - - // Earlier bar's split-adjusted and total-adjusted reads stay bitwise identical (divide by 4, - // never 40). - let (split_f_after, total_f_after) = adj_factors_for_bar(&pit_after.rows, 42, bar_pre_2021); - assert_eq!(split_f_after.to_bits(), split_f_before.to_bits()); - assert_eq!(total_f_after.to_bits(), total_f_before.to_bits()); - assert_eq!((raw_close / split_f_after).to_bits(), 200.0_f64.to_bits()); - - // Contrast with retrospective full-history snapshot (without the conflicting alias): - // explicitly tagged as RetrospectiveSnapshot, with cum_split_factor == 40.0 on the 2021 row. - let retro = curate_adj_factors( - &mapping, - "qm", - [ - ("NVDA", SplitEvent { ex_date: d_split_2021, ratio: 4.0 }), - ("NVDA", SplitEvent { ex_date: d_split_2024, ratio: 10.0 }), - ], - [ - ("NVDA", div(d_div_2022, 0.04, "USD", Some(137.0), Some("USD"))), - ("NVDA", div(d_div_2024, 0.01, "USD", Some(115.0), Some("USD"))), - ], - ) - .unwrap(); - assert_conservation(&retro); - assert_eq!(retro.snapshot_kind, AdjSnapshotKind::RetrospectiveSnapshot); - let (retro_split_f, _) = adj_factors_for_bar(&retro.rows, 42, bar_pre_2021); - assert_eq!(retro_split_f, 40.0); -} - -#[test] -fn vault_cutoff_is_strictly_exclusive_and_overrides_later_as_of() { - let mapping = ProviderMappingTable::from_rows([map_row( - "qm", - "NVDA", - day(1999, 1, 22), - None, - 42, - )]) - .unwrap(); - - let d_2021 = day(2021, 7, 20); - let d_2024 = day(2024, 6, 10); - let known_2024 = et_session_close_utc_micros(d_2024).unwrap(); - let splits = [ - ("NVDA", SplitEvent { ex_date: d_2021, ratio: 4.0 }), - ("NVDA", SplitEvent { ex_date: d_2024, ratio: 10.0 }), - ]; - - // as_of is inclusive (<=): known_2024 - 1 excludes 2024 split; known_2024 includes it. - let before_as_of = curate_adj_factors_as_of( - &mapping, - "qm", - splits, - std::iter::empty::<(&str, DividendEvent)>(), - AdjPointInTimeFence::as_of(known_2024 - 1), - ) - .unwrap(); - assert_conservation(&before_as_of); - assert_eq!(before_as_of.rows.len(), 1); - assert_eq!(before_as_of.rows[0].cum_split_factor, 4.0); - - let at_as_of = curate_adj_factors_as_of( - &mapping, - "qm", - splits, - std::iter::empty::<(&str, DividendEvent)>(), - AdjPointInTimeFence::as_of(known_2024), - ) - .unwrap(); - assert_conservation(&at_as_of); - assert_eq!(at_as_of.rows.len(), 2); - assert_eq!(at_as_of.rows[0].cum_split_factor, 40.0); - - // vault_cutoff is strictly exclusive (<): at known_2024 it excludes 2024 split even if as_of - // is later than vault_cutoff. - let vault_at_boundary = curate_adj_factors_as_of( - &mapping, - "qm", - splits, - std::iter::empty::<(&str, DividendEvent)>(), - AdjPointInTimeFence::as_of_with_vault_cutoff(known_2024 + 86_400_000_000, known_2024), - ) - .unwrap(); - assert_conservation(&vault_at_boundary); - assert_eq!(vault_at_boundary.rows.len(), 1); - assert_eq!(vault_at_boundary.stats.splits_dropped_fenced, 1); - assert_eq!(vault_at_boundary.rows[0].cum_split_factor, 4.0); - - // vault_cutoff = known_2024 + 1 admits the 2024 split when no earlier as_of blocks it. - let vault_past_boundary = curate_adj_factors_as_of( - &mapping, - "qm", - splits, - std::iter::empty::<(&str, DividendEvent)>(), - AdjPointInTimeFence::vault_fenced(known_2024 + 1), - ) - .unwrap(); - assert_conservation(&vault_past_boundary); - assert_eq!(vault_past_boundary.rows.len(), 2); - assert_eq!(vault_past_boundary.rows[0].cum_split_factor, 40.0); -} - -#[test] -fn curate_and_write_adj_factors_as_of_round_trips_and_rejects_out_of_range_ex_date() { - let mapping = ProviderMappingTable::from_rows([map_row( - "qm", - "NVDA", - i32::MIN, - None, - 42, - )]) - .unwrap(); - - let d_2021 = day(2021, 7, 20); - let d_2024 = day(2024, 6, 10); - let vault_2024_01_01 = i64::from(day(2024, 1, 1)) * 86_400_000_000; - let fence = AdjPointInTimeFence::vault_fenced(vault_2024_01_01); - - let temp = TestTempDir::new("pit-round-trip"); - let report = curate_and_write_adj_factors_as_of( - &temp.path, - &mapping, - "qm", - [ - ("NVDA", SplitEvent { ex_date: d_2021, ratio: 4.0 }), - ("NVDA", SplitEvent { ex_date: d_2024, ratio: 10.0 }), - ], - std::iter::empty::<(&str, DividendEvent)>(), - fence, - AdjFactorsWriteOptions::default(), - ) - .unwrap(); - - assert_eq!(report.snapshot_kind, AdjSnapshotKind::PointInTimeFenced(fence)); - assert_eq!(report.curate_stats.splits_dropped_fenced, 1); - assert_eq!(report.write_stats.rows_written, 1); - - let read_back = read_parquet_rows(&temp.path.join("adj_factors/part.parquet")); - assert_eq!(read_back.len(), 1); - assert_eq!(read_back[0].ex_date, d_2021); - assert_eq!(read_back[0].cum_split_factor, 4.0); - assert_eq!(adj_factors_for_bar(&read_back, 42, day(2021, 1, 4)), (4.0, 4.0)); - assert_eq!(adj_factors_for_bar(&read_back, 42, d_2021), (1.0, 1.0)); - assert_eq!(adj_factors_for_bar(&read_back, 999, day(2021, 1, 4)), (1.0, 1.0)); - - // Out-of-range ex_date under a fenced call returns typed ExDateOutOfRange without panicking - // and publishes no Parquet file. - let err_temp = TestTempDir::new("pit-oor"); - let err = curate_and_write_adj_factors_as_of( - &err_temp.path, - &mapping, - "qm", - [("NVDA", SplitEvent { ex_date: day(2031, 1, 1), ratio: 2.0 })], - std::iter::empty::<(&str, DividendEvent)>(), - fence, - AdjFactorsWriteOptions::default(), - ) - .unwrap_err(); - assert!(matches!( - err, - CurateAdjWriteError::Curate(CurateAdjError::ExDateOutOfRange { listing_id: 42, .. }) - )); - assert!(!err_temp.path.join("adj_factors/part.parquet").exists()); - assert!(!err_temp.path.join("adj_factors").exists()); -} - -#[test] -fn reopened_parquet_artifact_persists_fence_and_rejects_retrospective_or_incompatible_pit_reads() { - let mapping = ProviderMappingTable::from_rows([map_row( - "qm", - "NVDA", - day(1999, 1, 22), - None, - 42, - )]) - .unwrap(); - - let d_split_2021 = day(2021, 7, 20); // 4:1 split - let d_split_2024 = day(2024, 6, 10); // 10:1 split - let pre_2021_bar = day(2021, 1, 4); - - let as_of_dec_2023 = i64::from(day(2024, 1, 1)) * 86_400_000_000 - 1; - let as_of_dec_2022 = i64::from(day(2023, 1, 1)) * 86_400_000_000 - 1; - let as_of_dec_2024 = i64::from(day(2025, 1, 1)) * 86_400_000_000 - 1; - let vault_jan_2024 = i64::from(day(2024, 1, 1)) * 86_400_000_000; - - let fence_dec_2023 = AdjPointInTimeFence::as_of(as_of_dec_2023); - let splits = [ - ("NVDA", SplitEvent { ex_date: d_split_2021, ratio: 4.0 }), - ("NVDA", SplitEvent { ex_date: d_split_2024, ratio: 10.0 }), - ]; - - // 1. Publish retrospective snapshot; point-in-time reader MUST reject it on reopen. - let retro_dir = TestTempDir::new("reopen-retro"); - curate_and_write_adj_factors( - &retro_dir.path, - &mapping, - "qm", - splits, - std::iter::empty::<(&str, DividendEvent)>(), - AdjFactorsWriteOptions::default(), - ) - .unwrap(); - - let pit_err = read_adj_factors_dataset_as_of(&retro_dir.path, fence_dec_2023).unwrap_err(); - assert!(matches!( - pit_err, - CurateAdjReadError::RetrospectiveSnapshotRejected { .. } - )); - - // General reader still opens it and explicitly reports RetrospectiveSnapshot. - let retro_loaded = read_adj_factors_dataset(&retro_dir.path).unwrap(); - assert_eq!(retro_loaded.snapshot_kind, AdjSnapshotKind::RetrospectiveSnapshot); - assert_eq!(retro_loaded.factors_for_bar(42, pre_2021_bar), (40.0, 40.0)); - - // 2. Publish Dec 2023 fenced snapshot; reopening with matching fence returns factor 4.0. - let fenced_dir = TestTempDir::new("reopen-fenced"); - curate_and_write_adj_factors_as_of( - &fenced_dir.path, - &mapping, - "qm", - splits, - std::iter::empty::<(&str, DividendEvent)>(), - fence_dec_2023, - AdjFactorsWriteOptions::default(), - ) - .unwrap(); - - let reopened = read_adj_factors_dataset_as_of(&fenced_dir.path, fence_dec_2023).unwrap(); - assert_eq!(reopened.snapshot_kind, AdjSnapshotKind::PointInTimeFenced(fence_dec_2023)); - assert_eq!(reopened.rows.len(), 1); - assert_eq!(reopened.factors_for_bar(42, pre_2021_bar), (4.0, 4.0)); - - // 3. Reopening with any incompatible or unfenced fence MUST fail closed. - for incompatible in [ - AdjPointInTimeFence::as_of(as_of_dec_2022), - AdjPointInTimeFence::as_of(as_of_dec_2024), - AdjPointInTimeFence::vault_fenced(vault_jan_2024), - AdjPointInTimeFence::as_of_with_vault_cutoff(as_of_dec_2023, vault_jan_2024), - ] { - let err = read_adj_factors_dataset_as_of(&fenced_dir.path, incompatible).unwrap_err(); - assert!(matches!( - err, - CurateAdjReadError::IncompatibleFence { actual, required, .. } - if actual == fence_dec_2023 && required == incompatible - )); - } - let unfenced_err = read_adj_factors_dataset_as_of( - &fenced_dir.path, - AdjPointInTimeFence::retrospective(), - ) - .unwrap_err(); - assert!(matches!(unfenced_err, CurateAdjReadError::UnfencedReadRequested)); - - // 4. Raw Parquet written via write_adj_factors_dataset carries no snapshot footer metadata -> - // fails closed with MissingSnapshotMetadata. - let retro_curated = curate_adj_factors( - &mapping, - "qm", - splits, - std::iter::empty::<(&str, DividendEvent)>(), - ) - .unwrap(); - write_adj_factors_dataset( - &fenced_dir.path, - &retro_curated.rows, - AdjFactorsWriteOptions::default(), - ) - .unwrap(); - let missing_err = read_adj_factors_dataset_as_of(&fenced_dir.path, fence_dec_2023).unwrap_err(); - assert!(matches!( - missing_err, - CurateAdjReadError::MissingSnapshotMetadata { .. } - )); - - // 5. Unsupported format_version in Parquet footer fails closed. - let unsupported_kv = vec![ - KeyValue::new(KV_FORMAT_VERSION.to_string(), "99".to_string()), - KeyValue::new( - KV_SNAPSHOT_KIND.to_string(), - "point_in_time_fenced".to_string(), - ), - KeyValue::new(KV_AS_OF_MICROS.to_string(), as_of_dec_2023.to_string()), - KeyValue::new(KV_VAULT_CUTOFF_MICROS.to_string(), "none".to_string()), - KeyValue::new(KV_ROWS_WRITTEN.to_string(), "0".to_string()), - KeyValue::new( - KV_SNAPSHOT_CHECKSUM.to_string(), - "0xcbf29ce484222325".to_string(), - ), - ]; - write_forged_parquet_with_kv(&fenced_dir.path, &[], unsupported_kv); - let version_err = read_adj_factors_dataset(&fenced_dir.path).unwrap_err(); - assert!(matches!( - version_err, - CurateAdjReadError::UnsupportedSnapshotVersion { - version: 99, - supported: 1, - .. - } - )); -} - -fn write_forged_parquet_with_kv( - out_dir: &Path, - rows: &[AdjFactorsParquetRow], - kv_metadata: Vec, -) { - let adj_dir = out_dir.join("adj_factors"); - fs::create_dir_all(&adj_dir).unwrap(); - let part_path = adj_dir.join("part.parquet"); - let schema = adj_factors_parquet_schema().unwrap(); - let props = Arc::new( - WriterProperties::builder() - .set_compression(Compression::ZSTD(ZstdLevel::try_new(3).unwrap())) - .set_key_value_metadata(Some(kv_metadata)) - .build(), - ); - let file = BufWriter::new(File::create(&part_path).unwrap()); - let mut writer = SerializedFileWriter::new(file, schema, props).unwrap(); - if !rows.is_empty() { - let mut listing_id = Vec::with_capacity(rows.len()); - let mut ex_date = Vec::with_capacity(rows.len()); - let mut split_factor = Vec::with_capacity(rows.len()); - let mut div_cash = Vec::with_capacity(rows.len()); - let mut div_currency_ids = Vec::with_capacity(rows.len()); - let mut div_currency_def_levels = Vec::with_capacity(rows.len()); - let mut div_currency_interner = StringInterner::default(); - let mut cum_split_factor = Vec::with_capacity(rows.len()); - let mut cum_total_factor = Vec::with_capacity(rows.len()); - let mut known_at_micros = Vec::with_capacity(rows.len()); - let mut scratch = Vec::new(); - for row in rows { - listing_id.push(row.listing_id); - ex_date.push(row.ex_date); - split_factor.push(row.split_factor); - div_cash.push(row.div_cash); - match row.div_currency.as_deref() { - Some(c) => { - div_currency_ids.push(div_currency_interner.intern(c)); - div_currency_def_levels.push(1); - } - None => div_currency_def_levels.push(0), - } - cum_split_factor.push(row.cum_split_factor); - cum_total_factor.push(row.cum_total_factor); - known_at_micros.push(row.known_at_micros); - } - let mut rg = writer.next_row_group().unwrap(); - write_i32_col(&mut rg, &listing_id).unwrap(); - write_i32_col(&mut rg, &ex_date).unwrap(); - write_f64_col(&mut rg, &split_factor, None).unwrap(); - write_f64_col(&mut rg, &div_cash, None).unwrap(); - write_optional_interned_str_col( - &mut rg, - &div_currency_ids, - &div_currency_def_levels, - &div_currency_interner, - &mut scratch, - ) - .unwrap(); - write_f64_col(&mut rg, &cum_split_factor, None).unwrap(); - write_f64_col(&mut rg, &cum_total_factor, None).unwrap(); - write_i64_col(&mut rg, &known_at_micros).unwrap(); - rg.close().unwrap(); - } - writer.close().unwrap(); -} - -fn assert_no_transient_files(adj_dir: &Path) { - for entry in fs::read_dir(adj_dir).unwrap() { - let name = entry.unwrap().file_name().to_string_lossy().into_owned(); - assert_eq!( - name, "part.parquet", - "unexpected leftover file in adj_factors dir: {name}" - ); - } -} - -#[test] -fn empty_fenced_rebuild_atomically_supersedes_previous_nonempty_parquet_snapshot() { - let mapping = ProviderMappingTable::from_rows([map_row( - "qm", - "NVDA", - day(1999, 1, 22), - None, - 42, - )]) - .unwrap(); - - let d_split_2024 = day(2024, 6, 10); // 10:1 split - let bar_2023 = day(2023, 6, 15); - let as_of_dec_2023 = i64::from(day(2024, 1, 1)) * 86_400_000_000 - 1; - let as_of_dec_2025 = i64::from(day(2026, 1, 1)) * 86_400_000_000 - 1; - let fence_dec_2023 = AdjPointInTimeFence::as_of(as_of_dec_2023); - let fence_dec_2025 = AdjPointInTimeFence::as_of(as_of_dec_2025); - - let splits = [("NVDA", SplitEvent { ex_date: d_split_2024, ratio: 10.0 })]; - let dir = TestTempDir::new("empty-fenced-supersede"); - - // Step 1: Publish a nonempty snapshot containing the June 2024 10:1 split. - let first_report = curate_and_write_adj_factors_as_of( - &dir.path, - &mapping, - "qm", - splits, - std::iter::empty::<(&str, DividendEvent)>(), - fence_dec_2025, - AdjFactorsWriteOptions::default(), - ) - .unwrap(); - assert_eq!(first_report.write_stats.rows_written, 1); - let first_loaded = read_adj_factors_dataset_as_of(&dir.path, fence_dec_2025).unwrap(); - assert_eq!(first_loaded.factors_for_bar(42, bar_2023), (10.0, 10.0)); - - // Step 2: Rebuild the SAME output root as of Dec 2023 with that split as the only input. - // The fence excludes every event -> 0 rows MUST supersede the old part.parquet. - let second_report = curate_and_write_adj_factors_as_of( - &dir.path, - &mapping, - "qm", - splits, - std::iter::empty::<(&str, DividendEvent)>(), - fence_dec_2023, - AdjFactorsWriteOptions::default(), - ) - .unwrap(); - assert_eq!(second_report.snapshot_kind, AdjSnapshotKind::PointInTimeFenced(fence_dec_2023)); - assert_eq!(second_report.curate_stats.splits_dropped_fenced, 1); - assert_eq!(second_report.curate_stats.rows_out, 0); - assert_eq!(second_report.write_stats.rows_written, 0); - assert_eq!(second_report.write_stats.files_written, 1); - assert!(second_report.write_stats.bytes_written > 0); - assert_no_transient_files(&dir.path.join("adj_factors")); - - // Reopening via the verified PIT reader sees 0 rows and factor (1.0, 1.0) — never 10.0. - let reopened = read_adj_factors_dataset_as_of(&dir.path, fence_dec_2023).unwrap(); - assert_eq!(reopened.snapshot_kind, AdjSnapshotKind::PointInTimeFenced(fence_dec_2023)); - assert!(reopened.rows.is_empty()); - assert_eq!(reopened.factors_for_bar(42, bar_2023), (1.0, 1.0)); - - // Reopening part.parquet directly also sees a valid 0-row Parquet with contract schema. - let part_path = dir.path.join("adj_factors/part.parquet"); - let expected_schema = adj_factors_parquet_schema().unwrap(); - let reader = SerializedFileReader::new(File::open(&part_path).unwrap()).unwrap(); - assert_eq!( - reader.metadata().file_metadata().schema_descr().root_schema(), - expected_schema.as_ref() - ); - assert_eq!(reader.metadata().file_metadata().num_rows(), 0); - let raw_rows = read_parquet_rows(&part_path); - assert!(raw_rows.is_empty()); - assert_eq!(adj_factors_for_bar(&raw_rows, 42, bar_2023), (1.0, 1.0)); - - // Old fence is now rejected as incompatible. - let old_fence_err = read_adj_factors_dataset_as_of(&dir.path, fence_dec_2025).unwrap_err(); - assert!(matches!( - old_fence_err, - CurateAdjReadError::IncompatibleFence { .. } - )); -} - -#[test] -fn concurrent_overlapping_publishes_never_leave_torn_snapshot_or_transient_files() { - use std::sync::Barrier; - - let mapping = Arc::new( - ProviderMappingTable::from_rows([map_row("qm", "NVDA", day(1999, 1, 22), None, 42)]) - .unwrap(), - ); - let d_split_2021 = day(2021, 7, 20); - let d_split_2024 = day(2024, 6, 10); - let pre_2021_bar = day(2021, 1, 4); - - let as_of_dec_2023 = i64::from(day(2024, 1, 1)) * 86_400_000_000 - 1; - let as_of_dec_2024 = i64::from(day(2025, 1, 1)) * 86_400_000_000 - 1; - let fence_dec_2023 = AdjPointInTimeFence::as_of(as_of_dec_2023); - let fence_dec_2024 = AdjPointInTimeFence::as_of(as_of_dec_2024); - - let splits = vec![ - ("NVDA", SplitEvent { ex_date: d_split_2021, ratio: 4.0 }), - ("NVDA", SplitEvent { ex_date: d_split_2024, ratio: 10.0 }), - ]; - - let dir = TestTempDir::new("concurrent-publish"); - let barrier = Arc::new(Barrier::new(2)); - - for _round in 0..8 { - std::thread::scope(|scope| { - let b1 = Arc::clone(&barrier); - let m1 = Arc::clone(&mapping); - let s1 = splits.clone(); - let p1 = dir.path.clone(); - let h1 = scope.spawn(move || { - b1.wait(); - curate_and_write_adj_factors_as_of( - &p1, - &m1, - "qm", - s1, - std::iter::empty::<(&str, DividendEvent)>(), - fence_dec_2023, - AdjFactorsWriteOptions::default(), - ) - }); - - let b2 = Arc::clone(&barrier); - let m2 = Arc::clone(&mapping); - let s2 = splits.clone(); - let p2 = dir.path.clone(); - let h2 = scope.spawn(move || { - b2.wait(); - curate_and_write_adj_factors_as_of( - &p2, - &m2, - "qm", - s2, - std::iter::empty::<(&str, DividendEvent)>(), - fence_dec_2024, - AdjFactorsWriteOptions::default(), - ) - }); - - let r1 = h1.join().unwrap().unwrap(); - let r2 = h2.join().unwrap().unwrap(); - assert_eq!(r1.snapshot_kind, AdjSnapshotKind::PointInTimeFenced(fence_dec_2023)); - assert_eq!(r2.snapshot_kind, AdjSnapshotKind::PointInTimeFenced(fence_dec_2024)); - }); - - assert_no_transient_files(&dir.path.join("adj_factors")); - - // Reopening must succeed with a self-consistent snapshot matching one of the two exact fences. - let loaded = read_adj_factors_dataset(&dir.path).unwrap(); - match loaded.snapshot_kind { - AdjSnapshotKind::PointInTimeFenced(f) if f == fence_dec_2023 => { - assert_eq!(loaded.rows.len(), 1); - assert_eq!(loaded.factors_for_bar(42, pre_2021_bar), (4.0, 4.0)); - let pit_ok = read_adj_factors_dataset_as_of(&dir.path, fence_dec_2023).unwrap(); - assert_eq!(pit_ok.factors_for_bar(42, pre_2021_bar), (4.0, 4.0)); - let pit_err = - read_adj_factors_dataset_as_of(&dir.path, fence_dec_2024).unwrap_err(); - assert!(matches!( - pit_err, - CurateAdjReadError::IncompatibleFence { actual, required, .. } - if actual == fence_dec_2023 && required == fence_dec_2024 - )); - } - AdjSnapshotKind::PointInTimeFenced(f) if f == fence_dec_2024 => { - assert_eq!(loaded.rows.len(), 2); - assert_eq!(loaded.factors_for_bar(42, pre_2021_bar), (40.0, 40.0)); - let pit_ok = read_adj_factors_dataset_as_of(&dir.path, fence_dec_2024).unwrap(); - assert_eq!(pit_ok.factors_for_bar(42, pre_2021_bar), (40.0, 40.0)); - let pit_err = - read_adj_factors_dataset_as_of(&dir.path, fence_dec_2023).unwrap_err(); - assert!(matches!( - pit_err, - CurateAdjReadError::IncompatibleFence { actual, required, .. } - if actual == fence_dec_2024 && required == fence_dec_2023 - )); - } - other => panic!("unexpected snapshot_kind after concurrent publish: {other:?}"), - } - } -} - -#[test] -fn interrupted_replacement_before_rename_preserves_previous_snapshot_and_cleans_up() { - let mapping = ProviderMappingTable::from_rows([map_row( - "qm", - "NVDA", - day(1999, 1, 22), - None, - 42, - )]) - .unwrap(); - - let d_split_2021 = day(2021, 7, 20); - let d_split_2024 = day(2024, 6, 10); - let pre_2021_bar = day(2021, 1, 4); - let as_of_dec_2023 = i64::from(day(2024, 1, 1)) * 86_400_000_000 - 1; - let as_of_dec_2024 = i64::from(day(2025, 1, 1)) * 86_400_000_000 - 1; - let fence_dec_2023 = AdjPointInTimeFence::as_of(as_of_dec_2023); - let fence_dec_2024 = AdjPointInTimeFence::as_of(as_of_dec_2024); - - let splits = [ - ("NVDA", SplitEvent { ex_date: d_split_2021, ratio: 4.0 }), - ("NVDA", SplitEvent { ex_date: d_split_2024, ratio: 10.0 }), - ]; - - let dir = TestTempDir::new("interrupted-replacement"); - - // Step 1: Publish a valid Dec 2023 snapshot (factor 4.0). - curate_and_write_adj_factors_as_of( - &dir.path, - &mapping, - "qm", - splits, - std::iter::empty::<(&str, DividendEvent)>(), - fence_dec_2023, - AdjFactorsWriteOptions::default(), - ) - .unwrap(); - - // Step 2: Attempt to replace with Dec 2024 snapshot, injecting an I/O failure after staging + - // backup and before fs::rename. - let dec_2024 = curate_adj_factors_as_of( - &mapping, - "qm", - splits, - std::iter::empty::<(&str, DividendEvent)>(), - fence_dec_2024, - ) - .unwrap(); - let mut saw_backup = false; - let err = write_adj_factors_snapshot_parquet_with_hooks( - &dir.path, - &dec_2024.rows, - dec_2024.snapshot_kind, - AdjFactorsWriteOptions::default(), - |_final_path, backup_path| { - saw_backup = backup_path.is_some_and(Path::is_file); - Err(io::Error::new( - io::ErrorKind::Interrupted, - "injected pre-rename failure", - )) - }, - ) - .unwrap_err(); - - assert!(saw_backup, "backup file must have been created before hook ran"); - assert!(matches!(err, ParquetAdjError::Io { .. })); - assert_no_transient_files(&dir.path.join("adj_factors")); - - // Step 3: Prior Dec 2023 snapshot must remain intact and readable with factor 4.0. - let reopened = read_adj_factors_dataset_as_of(&dir.path, fence_dec_2023).unwrap(); - assert_eq!(reopened.snapshot_kind, AdjSnapshotKind::PointInTimeFenced(fence_dec_2023)); - assert_eq!(reopened.rows.len(), 1); - assert_eq!(reopened.factors_for_bar(42, pre_2021_bar), (4.0, 4.0)); -} - -#[test] -fn tampered_cutoff_out_of_fence_and_forged_chain_are_rejected_on_reopen() { - let mapping = ProviderMappingTable::from_rows([map_row( - "qm", - "NVDA", - day(1999, 1, 22), - None, - 42, - )]) - .unwrap(); - - let d_split_2021 = day(2021, 7, 20); - let d_split_2024 = day(2024, 6, 10); - let as_of_dec_2023 = i64::from(day(2024, 1, 1)) * 86_400_000_000 - 1; - let as_of_dec_2024 = i64::from(day(2025, 1, 1)) * 86_400_000_000 - 1; - let fence_dec_2023 = AdjPointInTimeFence::as_of(as_of_dec_2023); - let fence_dec_2024 = AdjPointInTimeFence::as_of(as_of_dec_2024); - - let splits = [ - ("NVDA", SplitEvent { ex_date: d_split_2021, ratio: 4.0 }), - ("NVDA", SplitEvent { ex_date: d_split_2024, ratio: 10.0 }), - ]; - - let dec_2024 = curate_adj_factors_as_of( - &mapping, - "qm", - splits, - std::iter::empty::<(&str, DividendEvent)>(), - fence_dec_2024, - ) - .unwrap(); - assert_eq!(dec_2024.rows.len(), 2); - assert_eq!(dec_2024.rows[0].cum_split_factor, 40.0); - - // Case 1: Rewrite Dec 2024 Parquet changing ONLY as_of_micros in footer to Dec 2023 - // (keeping Dec 2024 rows and old Dec 2024 checksum) -> must be rejected (never returns 40.0). - let dir1 = TestTempDir::new("tampered-cutoff-only"); - let old_checksum = compute_snapshot_checksum( - ADJ_SNAPSHOT_FORMAT_VERSION, - AdjSnapshotKind::PointInTimeFenced(fence_dec_2024), - &dec_2024.rows, - ); - let tampered_kv = build_snapshot_key_value_metadata( - ADJ_SNAPSHOT_FORMAT_VERSION, - AdjSnapshotKind::PointInTimeFenced(fence_dec_2023), - dec_2024.rows.len(), - old_checksum, - ); - write_forged_parquet_with_kv(&dir1.path, &dec_2024.rows, tampered_kv); - let err1 = read_adj_factors_dataset_as_of(&dir1.path, fence_dec_2023).unwrap_err(); - assert!( - matches!( - err1, - CurateAdjReadError::RowOutsideFence { .. } - | CurateAdjReadError::SnapshotIntegrityMismatch { .. } - ), - "expected RowOutsideFence or SnapshotIntegrityMismatch, got: {err1:?}" - ); - - // Case 2: Forge a Parquet file declaring Dec 2023 with a recomputed checksum over Dec 2024 - // rows -> rejected with RowOutsideFence. - let dir2 = TestTempDir::new("forged-out-of-fence"); - let forged_checksum_2 = compute_snapshot_checksum( - ADJ_SNAPSHOT_FORMAT_VERSION, - AdjSnapshotKind::PointInTimeFenced(fence_dec_2023), - &dec_2024.rows, - ); - let forged_kv_2 = build_snapshot_key_value_metadata( - ADJ_SNAPSHOT_FORMAT_VERSION, - AdjSnapshotKind::PointInTimeFenced(fence_dec_2023), - dec_2024.rows.len(), - forged_checksum_2, - ); - write_forged_parquet_with_kv(&dir2.path, &dec_2024.rows, forged_kv_2); - let err2 = read_adj_factors_dataset_as_of(&dir2.path, fence_dec_2023).unwrap_err(); - assert!( - matches!( - err2, - CurateAdjReadError::RowOutsideFence { - listing_id: 42, - ex_date, - fence, - .. - } if ex_date == d_split_2024 && fence == fence_dec_2023 - ), - "expected RowOutsideFence for 2024 split, got: {err2:?}" - ); - - // Case 3: Forge a Parquet file declaring Dec 2023 with a recomputed checksum over ONLY the - // pre-2024 row carrying stale cum_split_factor = 40.0 (split_factor = 4.0) -> rejected with - // SnapshotIntegrityMismatch by per-listing suffix-product verification. - let dir3 = TestTempDir::new("forged-stale-chain"); - let stale_rows = vec![dec_2024.rows[0].clone()]; - assert_eq!(stale_rows[0].split_factor, 4.0); - assert_eq!(stale_rows[0].cum_split_factor, 40.0); - let forged_checksum_3 = compute_snapshot_checksum( - ADJ_SNAPSHOT_FORMAT_VERSION, - AdjSnapshotKind::PointInTimeFenced(fence_dec_2023), - &stale_rows, - ); - let forged_kv_3 = build_snapshot_key_value_metadata( - ADJ_SNAPSHOT_FORMAT_VERSION, - AdjSnapshotKind::PointInTimeFenced(fence_dec_2023), - stale_rows.len(), - forged_checksum_3, - ); - write_forged_parquet_with_kv(&dir3.path, &stale_rows, forged_kv_3); - let err3 = read_adj_factors_dataset_as_of(&dir3.path, fence_dec_2023).unwrap_err(); - assert!( - matches!(err3, CurateAdjReadError::SnapshotIntegrityMismatch { .. }), - "expected SnapshotIntegrityMismatch for stale cum_split_factor=40.0, got: {err3:?}" - ); -} - -#[test] -fn checksum_binds_cutoff_and_snapshot_kind_even_when_all_rows_remain_admitted() { - let mapping = ProviderMappingTable::from_rows([map_row( - "qm", - "NVDA", - day(1999, 1, 22), - None, - 42, - )]) - .unwrap(); - - let d_split_2021 = day(2021, 7, 20); - let as_of_dec_2023 = i64::from(day(2024, 1, 1)) * 86_400_000_000 - 1; - let fence_dec_2023 = AdjPointInTimeFence::as_of(as_of_dec_2023); - - let splits = [("NVDA", SplitEvent { ex_date: d_split_2021, ratio: 4.0 })]; - let dec_2023 = curate_adj_factors_as_of( - &mapping, - "qm", - splits, - std::iter::empty::<(&str, DividendEvent)>(), - fence_dec_2023, - ) - .unwrap(); - assert_conservation(&dec_2023); - assert_eq!(dec_2023.rows.len(), 1); - let row_known_at = dec_2023.rows[0].known_at_micros; - - let original_checksum = compute_snapshot_checksum( - ADJ_SNAPSHOT_FORMAT_VERSION, - AdjSnapshotKind::PointInTimeFenced(fence_dec_2023), - &dec_2023.rows, - ); - - // Edit 1: Shift as_of_micros forward by +1 day (still admits the 2021 row) while keeping - // the original checksum -> must fail with SnapshotIntegrityMismatch (not RowOutsideFence). - let edited_as_of_fence = AdjPointInTimeFence::as_of(as_of_dec_2023 + 86_400_000_000); - assert!(edited_as_of_fence.admits(row_known_at)); - let dir_as_of = TestTempDir::new("checksum-binds-as-of"); - let kv_as_of = build_snapshot_key_value_metadata( - ADJ_SNAPSHOT_FORMAT_VERSION, - AdjSnapshotKind::PointInTimeFenced(edited_as_of_fence), - dec_2023.rows.len(), - original_checksum, - ); - write_forged_parquet_with_kv(&dir_as_of.path, &dec_2023.rows, kv_as_of); - let err_as_of = read_adj_factors_dataset_as_of(&dir_as_of.path, edited_as_of_fence).unwrap_err(); - assert!( - matches!(err_as_of, CurateAdjReadError::SnapshotIntegrityMismatch { .. }), - "expected SnapshotIntegrityMismatch for edited as_of_micros, got: {err_as_of:?}" - ); - - // Edit 2: Add a vault_cutoff_micros after the 2021 row's known_at (still admits the row) - // while keeping the original checksum -> must fail with SnapshotIntegrityMismatch. - let vault_after_2021 = i64::from(day(2024, 6, 1)) * 86_400_000_000; - let edited_vault_fence = - AdjPointInTimeFence::as_of_with_vault_cutoff(as_of_dec_2023, vault_after_2021); - assert!(edited_vault_fence.admits(row_known_at)); - let dir_vault = TestTempDir::new("checksum-binds-vault"); - let kv_vault = build_snapshot_key_value_metadata( - ADJ_SNAPSHOT_FORMAT_VERSION, - AdjSnapshotKind::PointInTimeFenced(edited_vault_fence), - dec_2023.rows.len(), - original_checksum, - ); - write_forged_parquet_with_kv(&dir_vault.path, &dec_2023.rows, kv_vault); - let err_vault = - read_adj_factors_dataset_as_of(&dir_vault.path, edited_vault_fence).unwrap_err(); - assert!( - matches!(err_vault, CurateAdjReadError::SnapshotIntegrityMismatch { .. }), - "expected SnapshotIntegrityMismatch for edited vault_cutoff_micros, got: {err_vault:?}" - ); - - // Edit 3: Relabel the snapshot as RetrospectiveSnapshot while keeping the original checksum - // -> must fail with SnapshotIntegrityMismatch. - let dir_retro = TestTempDir::new("checksum-binds-kind"); - let kv_retro = build_snapshot_key_value_metadata( - ADJ_SNAPSHOT_FORMAT_VERSION, - AdjSnapshotKind::RetrospectiveSnapshot, - dec_2023.rows.len(), - original_checksum, - ); - write_forged_parquet_with_kv(&dir_retro.path, &dec_2023.rows, kv_retro); - let err_retro = read_adj_factors_dataset(&dir_retro.path).unwrap_err(); - assert!( - matches!(err_retro, CurateAdjReadError::SnapshotIntegrityMismatch { .. }), - "expected SnapshotIntegrityMismatch for relabeled snapshot_kind, got: {err_retro:?}" - ); -} - -#[test] -fn unverified_missing_and_corrupt_parquet_files_fail_closed_with_typed_errors() { - let fence = AdjPointInTimeFence::as_of(i64::from(day(2024, 1, 1)) * 86_400_000_000 - 1); - - // 1. Missing adj_factors/part.parquet -> CurateAdjReadError::Io - let missing_dir = TestTempDir::new("read-missing-file"); - let missing_err = read_adj_factors_dataset(&missing_dir.path).unwrap_err(); - assert!( - matches!(missing_err, CurateAdjReadError::Io { .. }), - "expected Io for missing part.parquet, got: {missing_err:?}" - ); - let missing_pit_err = read_adj_factors_dataset_as_of(&missing_dir.path, fence).unwrap_err(); - assert!( - matches!(missing_pit_err, CurateAdjReadError::Io { .. }), - "expected Io for missing part.parquet in PIT reader, got: {missing_pit_err:?}" - ); - - // 2. Raw Parquet written via write_adj_factors_dataset (no stock_bot.adj_factors.* keys) - // -> CurateAdjReadError::MissingSnapshotMetadata - let raw_dir = TestTempDir::new("read-raw-parquet"); - let mapping = ProviderMappingTable::from_rows([map_row( - "qm", - "NVDA", - day(1999, 1, 22), - None, - 42, - )]) - .unwrap(); - let curated = curate_adj_factors( - &mapping, - "qm", - [("NVDA", SplitEvent { ex_date: day(2021, 7, 20), ratio: 4.0 })], - std::iter::empty::<(&str, DividendEvent)>(), - ) - .unwrap(); - write_adj_factors_dataset(&raw_dir.path, &curated.rows, AdjFactorsWriteOptions::default()) - .unwrap(); - let raw_err = read_adj_factors_dataset(&raw_dir.path).unwrap_err(); - assert!( - matches!(raw_err, CurateAdjReadError::MissingSnapshotMetadata { .. }), - "expected MissingSnapshotMetadata for raw Parquet, got: {raw_err:?}" - ); - let raw_pit_err = read_adj_factors_dataset_as_of(&raw_dir.path, fence).unwrap_err(); - assert!( - matches!(raw_pit_err, CurateAdjReadError::MissingSnapshotMetadata { .. }), - "expected MissingSnapshotMetadata for raw Parquet in PIT reader, got: {raw_pit_err:?}" - ); - - // 3. Garbage bytes written to adj_factors/part.parquet -> CurateAdjReadError::Parquet - let corrupt_dir = TestTempDir::new("read-garbage-bytes"); - let adj_dir = corrupt_dir.path.join("adj_factors"); - fs::create_dir_all(&adj_dir).unwrap(); - fs::write(adj_dir.join("part.parquet"), b"not a valid parquet file at all").unwrap(); - let corrupt_err = read_adj_factors_dataset(&corrupt_dir.path).unwrap_err(); - assert!( - matches!(corrupt_err, CurateAdjReadError::Parquet { .. }), - "expected Parquet error for garbage bytes, got: {corrupt_err:?}" - ); - let corrupt_pit_err = read_adj_factors_dataset_as_of(&corrupt_dir.path, fence).unwrap_err(); - assert!( - matches!(corrupt_pit_err, CurateAdjReadError::Parquet { .. }), - "expected Parquet error for garbage bytes in PIT reader, got: {corrupt_pit_err:?}" - ); -} - -#[test] -fn asymmetric_cross_key_multi_event_days_fail_closed() { - let mapping = ProviderMappingTable::from_rows([ - map_row("qm", "PRIMARY", day(2020, 1, 1), None, 777), - map_row("qm", "ALIAS", day(2020, 1, 1), None, 777), - ]) - .unwrap(); - - let d = day(2023, 8, 15); - - // Case 1: Primary emits regular + special dividend on (777, d), alias emits only regular. - let regular = div(d, 0.25, "USD", Some(100.0), Some("USD")); - let special = div(d, 1.50, "USD", Some(100.0), Some("USD")); - let div_err = curate_adj_factors( - &mapping, - "qm", - std::iter::empty::<(&str, SplitEvent)>(), - [ - ("PRIMARY", regular.clone()), - ("PRIMARY", special), - ("ALIAS", regular), - ], - ) - .unwrap_err(); - assert!( - matches!( - div_err, - CurateAdjError::ConflictingCrossKeyDividend { - listing_id: 777, - ex_date, - .. - } if ex_date == d - ), - "expected ConflictingCrossKeyDividend, got: {div_err:?}" - ); - - // Case 2: Primary emits two differing splits on (777, d), alias emits only one of them. - let split_err = curate_adj_factors( - &mapping, - "qm", - [ - ("PRIMARY", SplitEvent { ex_date: d, ratio: 2.0 }), - ("PRIMARY", SplitEvent { ex_date: d, ratio: 3.0 }), - ("ALIAS", SplitEvent { ex_date: d, ratio: 2.0 }), - ], - std::iter::empty::<(&str, DividendEvent)>(), - ) - .unwrap_err(); - assert!( - matches!( - split_err, - CurateAdjError::ConflictingCrossKeySplit { - listing_id: 777, - ex_date, - .. - } if ex_date == d - ), - "expected ConflictingCrossKeySplit, got: {split_err:?}" - ); -} - -#[test] -fn bitwise_identical_cross_key_noop_splits_collapse_then_drop_with_conservation() { - let mapping = ProviderMappingTable::from_rows([ - map_row("qm", "NOOP_A", day(2020, 1, 1), None, 808), - map_row("qm", "NOOP_B", day(2020, 1, 1), None, 808), - ]) - .unwrap(); - let d = day(2023, 5, 1); - - let out = curate_adj_factors( - &mapping, - "qm", - [ - ("NOOP_A", SplitEvent { ex_date: d, ratio: 1.0 }), - ("NOOP_B", SplitEvent { ex_date: d, ratio: 1.0 }), - ], - std::iter::empty::<(&str, DividendEvent)>(), - ) - .unwrap(); - - assert_conservation(&out); - assert_eq!(out.stats.splits_in, 2); - assert_eq!(out.stats.splits_dropped_unmapped, 0); - assert_eq!(out.stats.splits_dropped_fenced, 0); - assert_eq!(out.stats.splits_collision_collapsed, 1); - assert_eq!(out.stats.listing_collision_collapsed, 1); - assert_eq!(out.stats.builder.split_events_in, 1); - assert_eq!(out.stats.builder.split_noops_dropped, 1); - assert_eq!(out.stats.rows_out, 0); - assert_eq!(out.stats.listings_out, 0); - assert!(out.rows.is_empty()); -} - -#[test] -fn unmapped_out_of_range_dates_count_as_unmapped_without_error() { - let mapping = ProviderMappingTable::from_rows([map_row( - "qm", - "MAPPED", - day(2020, 1, 1), - Some(day(2024, 12, 31)), - 101, - )]) - .unwrap(); - - let pre_1976 = day(1975, 12, 31); - let in_range_day = day(2022, 6, 15); - - let splits = vec![ - ("UNMAPPED", SplitEvent { ex_date: pre_1976, ratio: 2.0 }), - ("UNMAPPED", SplitEvent { ex_date: i32::MIN, ratio: 3.0 }), - ("UNMAPPED", SplitEvent { ex_date: i32::MAX, ratio: 4.0 }), - ("MAPPED", SplitEvent { ex_date: pre_1976, ratio: 5.0 }), - ("MAPPED", SplitEvent { ex_date: i32::MIN, ratio: 6.0 }), - ("MAPPED", SplitEvent { ex_date: i32::MAX, ratio: 7.0 }), - ("MAPPED", SplitEvent { ex_date: in_range_day, ratio: 2.0 }), - ]; - let dividends = vec![ - ("UNMAPPED", div(pre_1976, 0.5, "USD", Some(10.0), Some("USD"))), - ("UNMAPPED", div(i32::MIN, 0.5, "USD", Some(10.0), Some("USD"))), - ("UNMAPPED", div(i32::MAX, 0.5, "USD", Some(10.0), Some("USD"))), - ("MAPPED", div(pre_1976, 0.25, "USD", Some(10.0), Some("USD"))), - ("MAPPED", div(i32::MIN, 0.25, "USD", Some(10.0), Some("USD"))), - ("MAPPED", div(i32::MAX, 0.25, "USD", Some(10.0), Some("USD"))), - ]; - - // Retrospective mode: all 6 out-of-range unmapped splits and 6 dividends drop cleanly. - let retro = curate_adj_factors(&mapping, "qm", splits.clone(), dividends.clone()).unwrap(); - assert_conservation(&retro); - assert_eq!(retro.stats.splits_in, 7); - assert_eq!(retro.stats.splits_dropped_unmapped, 6); - assert_eq!(retro.stats.dividends_in, 6); - assert_eq!(retro.stats.dividends_dropped_unmapped, 6); - assert_eq!(retro.stats.rows_out, 1); - assert_eq!(retro.rows[0].listing_id, 101); - assert_eq!(retro.rows[0].ex_date, in_range_day); - - // Point-in-time fenced mode: unmapped out-of-range events still count as unmapped, not - // ExDateOutOfRange, before fencing runs. - let fence = AdjPointInTimeFence::as_of(i64::from(day(2023, 1, 1)) * 86_400_000_000 - 1); - let fenced = curate_adj_factors_as_of(&mapping, "qm", splits, dividends, fence).unwrap(); - assert_conservation(&fenced); - assert_eq!(fenced.stats.splits_in, 7); - assert_eq!(fenced.stats.splits_dropped_unmapped, 6); - assert_eq!(fenced.stats.splits_dropped_fenced, 0); - assert_eq!(fenced.stats.dividends_in, 6); - assert_eq!(fenced.stats.dividends_dropped_unmapped, 6); - assert_eq!(fenced.stats.dividends_dropped_fenced, 0); - assert_eq!(fenced.stats.rows_out, 1); - assert_eq!(fenced.rows[0].listing_id, 101); - assert_eq!(fenced.rows[0].ex_date, in_range_day); -} - -struct TestRng(u64); - -impl TestRng { - 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 range_usize(&mut self, upper: usize) -> usize { - (self.next_u64() as usize) % upper - } - - fn range_i32(&mut self, lo: i32, hi_inclusive: i32) -> i32 { - let span = u64::from((hi_inclusive - lo) as u32) + 1; - lo + (self.next_u64() % span) as i32 - } -} - -type SeededAdjFixture = ( - ProviderMappingTable, - Vec<(String, SplitEvent)>, - Vec<(String, DividendEvent)>, -); - -fn build_seeded_multi_listing_fixture(seed: u64) -> SeededAdjFixture { - let mut rng = TestRng(seed); - let min_date = day(2016, 1, 4); - let max_date = day(2025, 12, 15); - - let mut mapping_rows = Vec::new(); - let mut keys = Vec::new(); - for idx in 0..12_i32 { - let listing_id = 1_000 + idx; - let key = format!("SYM_{idx:02}"); - mapping_rows.push(map_row("qm", &key, day(2010, 1, 1), None, listing_id)); - keys.push(key); - } - let mapping = ProviderMappingTable::from_rows(mapping_rows).unwrap(); - - let split_ratios = [2.0_f64, 3.0, 4.0, 0.5, 0.25, 1.5, 1.0]; - let currencies = ["USD", "CAD"]; - - let mut splits = Vec::new(); - let mut dividends = Vec::new(); - - // Deterministic same-day multi-split and reciprocal split scenarios on listing 1000 & 1001. - let same_day_split = day(2020, 4, 15); - splits.push(("SYM_00".to_string(), SplitEvent { ex_date: same_day_split, ratio: 2.0 })); - splits.push(("SYM_00".to_string(), SplitEvent { ex_date: same_day_split, ratio: 3.0 })); - // Reciprocal splits (2:1 followed by 1:2) across distinct dates and on the same day. - splits.push(("SYM_01".to_string(), SplitEvent { ex_date: day(2019, 3, 11), ratio: 2.0 })); - splits.push(("SYM_01".to_string(), SplitEvent { ex_date: day(2021, 9, 20), ratio: 0.5 })); - splits.push(("SYM_01".to_string(), SplitEvent { ex_date: day(2022, 5, 2), ratio: 4.0 })); - splits.push(("SYM_01".to_string(), SplitEvent { ex_date: day(2022, 5, 2), ratio: 0.25 })); - - // Same-day regular + special dividend on listing 1002. - let same_day_div = day(2021, 11, 10); - dividends.push(( - "SYM_02".to_string(), - div(same_day_div, 0.35, "USD", Some(80.0), Some("USD")), - )); - dividends.push(( - "SYM_02".to_string(), - div(same_day_div, 1.25, "USD", Some(80.0), Some("USD")), - )); - - // Seeded random splits and dividends spanning 2016..=2025. - for _ in 0..48 { - let key = keys[rng.range_usize(keys.len())].clone(); - let ex_date = rng.range_i32(min_date, max_date); - let ratio = split_ratios[rng.range_usize(split_ratios.len())]; - splits.push((key, SplitEvent { ex_date, ratio })); - } - for _ in 0..140 { - let key = keys[rng.range_usize(keys.len())].clone(); - let ex_date = rng.range_i32(min_date, max_date); - let cash = (rng.range_usize(200) as f64) * 0.01; // includes 0.0 no-op dividends - let currency = currencies[rng.range_usize(currencies.len())]; - let prev_close = if rng.range_usize(5) == 0 { - None - } else { - Some(20.0 + (rng.range_usize(400) as f64) * 0.5) - }; - let prev_close_currency = prev_close.map(|_| currency); - dividends.push((key, div(ex_date, cash, currency, prev_close, prev_close_currency))); - } - - (mapping, splits, dividends) -} - -#[test] -fn seeded_multi_row_group_round_trip_and_cutoff_equivalence() { - let (mapping, splits, dividends) = build_seeded_multi_listing_fixture(0x5EED_AD01); - let cutoff_as_of = i64::from(day(2022, 1, 1)) * 86_400_000_000 - 1; - let fence = AdjPointInTimeFence::as_of(cutoff_as_of); - - let opts = AdjFactorsWriteOptions { - row_group_rows: 7, - ..AdjFactorsWriteOptions::default() - }; - - // 1. Retrospective multi-row-group round-trip (row_group_rows = 7) is bit-for-bit identical. - let retro_dir = TestTempDir::new("seeded-rg7-retro"); - let retro_expected = - curate_adj_factors(&mapping, "qm", splits.clone(), dividends.clone()).unwrap(); - assert_conservation(&retro_expected); - assert!( - retro_expected.rows.len() > 14, - "fixture must span multiple 7-row row groups" - ); - - let retro_report = curate_and_write_adj_factors( - &retro_dir.path, - &mapping, - "qm", - splits.clone(), - dividends.clone(), - opts, - ) - .unwrap(); - assert_eq!(retro_report.write_stats.rows_written, retro_expected.rows.len()); - - let part_path = retro_dir.path.join("adj_factors/part.parquet"); - let raw_reader = SerializedFileReader::new(File::open(&part_path).unwrap()).unwrap(); - assert!( - raw_reader.metadata().num_row_groups() > 1, - "expected multiple row groups with row_group_rows=7" - ); - - let retro_reopened = read_adj_factors_dataset(&retro_dir.path).unwrap(); - assert_eq!(retro_reopened.snapshot_kind, AdjSnapshotKind::RetrospectiveSnapshot); - assert_eq!(retro_reopened.rows.len(), retro_expected.rows.len()); - for (actual, expected) in retro_reopened.rows.iter().zip(&retro_expected.rows) { - assert_row_bitwise_eq(actual, expected); - } - - // 2. Fenced multi-row-group round-trip is bit-for-bit identical. - let fenced_dir = TestTempDir::new("seeded-rg7-fenced"); - let fenced_expected = - curate_adj_factors_as_of(&mapping, "qm", splits.clone(), dividends.clone(), fence) - .unwrap(); - assert_conservation(&fenced_expected); - assert!(fenced_expected.stats.splits_dropped_fenced > 0); - assert!(fenced_expected.stats.dividends_dropped_fenced > 0); - assert!(fenced_expected.rows.len() > 7); - - curate_and_write_adj_factors_as_of( - &fenced_dir.path, - &mapping, - "qm", - splits.clone(), - dividends.clone(), - fence, - opts, - ) - .unwrap(); - let fenced_reopened = read_adj_factors_dataset_as_of(&fenced_dir.path, fence).unwrap(); - assert_eq!( - fenced_reopened.snapshot_kind, - AdjSnapshotKind::PointInTimeFenced(fence) - ); - assert_eq!(fenced_reopened.rows.len(), fenced_expected.rows.len()); - for (actual, expected) in fenced_reopened.rows.iter().zip(&fenced_expected.rows) { - assert_row_bitwise_eq(actual, expected); - } - - // 3. Cutoff equivalence: curating full history with `fence` produces rows bitwise-identical - // to curating only the events admitted by `fence`. - let admitted_splits: Vec<_> = splits - .into_iter() - .filter(|(_, ev)| { - let known_at = et_session_close_utc_micros(ev.ex_date).unwrap(); - fence.admits(known_at) - }) - .collect(); - let admitted_dividends: Vec<_> = dividends - .into_iter() - .filter(|(_, ev)| { - let known_at = et_session_close_utc_micros(ev.ex_date).unwrap(); - fence.admits(known_at) - }) - .collect(); - let pre_filtered = - curate_adj_factors(&mapping, "qm", admitted_splits, admitted_dividends).unwrap(); - assert_conservation(&pre_filtered); - assert_eq!(fenced_expected.rows.len(), pre_filtered.rows.len()); - for (actual, expected) in fenced_expected.rows.iter().zip(&pre_filtered.rows) { - assert_row_bitwise_eq(actual, expected); - } -} - -#[test] -fn seeded_lookahead_invariance_across_500_pre_cutoff_bar_queries() { - let (mapping, splits, dividends) = build_seeded_multi_listing_fixture(0x5EED_AD02); - let cutoff_day = day(2021, 12, 31); - let cutoff_as_of = et_session_close_utc_micros(cutoff_day).unwrap(); - let vault_cutoff = i64::from(day(2022, 7, 1)) * 86_400_000_000; - let fence = AdjPointInTimeFence::as_of_with_vault_cutoff(cutoff_as_of, vault_cutoff); - - let full_fenced = - curate_adj_factors_as_of(&mapping, "qm", splits.clone(), dividends.clone(), fence).unwrap(); - assert_conservation(&full_fenced); - assert!( - full_fenced.stats.splits_dropped_fenced > 0 - && full_fenced.stats.dividends_dropped_fenced > 0, - "fixture must contain post-cutoff future events to exercise look-ahead invariance" - ); - - let past_splits: Vec<_> = splits - .into_iter() - .filter(|(_, ev)| fence.admits(et_session_close_utc_micros(ev.ex_date).unwrap())) - .collect(); - let past_dividends: Vec<_> = dividends - .into_iter() - .filter(|(_, ev)| fence.admits(et_session_close_utc_micros(ev.ex_date).unwrap())) - .collect(); - let past_only_fenced = - curate_adj_factors_as_of(&mapping, "qm", past_splits, past_dividends, fence).unwrap(); - assert_conservation(&past_only_fenced); - - let mut query_rng = TestRng(0x5EED_0500); - let query_start = day(2015, 1, 2); - for _ in 0..500 { - let listing_id = 1_000 + query_rng.range_i32(0, 11); - let bar_date = query_rng.range_i32(query_start, cutoff_day); - - let (split_with_future, total_with_future) = - adj_factors_for_bar(&full_fenced.rows, listing_id, bar_date); - let (split_past_only, total_past_only) = - adj_factors_for_bar(&past_only_fenced.rows, listing_id, bar_date); - - assert_eq!( - split_with_future.to_bits(), - split_past_only.to_bits(), - "split factor look-ahead leak for listing_id={listing_id} bar_date={bar_date}" - ); - assert_eq!( - total_with_future.to_bits(), - total_past_only.to_bits(), - "total factor look-ahead leak for listing_id={listing_id} bar_date={bar_date}" - ); - } -} diff --git a/tools/curate-etl/src/curate_bars.rs b/tools/curate-etl/src/curate_bars.rs index cf2e7fa0..515b3f8d 100644 --- a/tools/curate-etl/src/curate_bars.rs +++ b/tools/curate-etl/src/curate_bars.rs @@ -386,7 +386,7 @@ where mapping_source, listing_currencies, )?; - let write_stats = write_bars_1d_dataset(out_dir, curated.rows, options)?; + let write_stats = write_bars_1d_dataset(out_dir, &curated.rows, options)?; Ok(CurateBars1dWriteReport { curate_stats: curated.stats, write_stats, diff --git a/tools/curate-etl/src/curate_bars_1m.rs b/tools/curate-etl/src/curate_bars_1m.rs deleted file mode 100644 index f8c7689f..00000000 --- a/tools/curate-etl/src/curate_bars_1m.rs +++ /dev/null @@ -1,589 +0,0 @@ -//! Pure, in-memory `bars_1m` curation stage joining [`crate::bars_1m::build_bars_1m`], -//! [`crate::provider_mapping::ProviderMappingTable`], [`crate::bars_1m::check_session_closes_against_bars_1d`], -//! [`crate::ilp::IlpShardedWriter`], and [`crate::bson_stream::decode_eod_intraday_stream`]. -//! -//! # Contract & Point-in-Time Rules -//! - Calls [`build_bars_1m`] with provider source keys intact so [`SplitTable`] applies split -//! un-adjustment on each bar's **Eastern Time** `session_date` (`ex_date > session_date`) -//! before `listing_id` resolution. -//! - Resolves each built row's `(mapping_source, source_id, session_date)` to a permanent -//! `listing_id: i32` via [`ProviderMappingTable::cursor_for`] / [`crate::provider_mapping::ProviderMappingCursor::resolve`] -//! (one cursor per contiguous source-key run, since `build_bars_1m` emits rows sorted by -//! `(key, ts)` and `session_date` is monotonically non-decreasing with UTC `ts`). -//! - Re-sorts mapped rows in place by `(listing_id, ts)` and compacts cross-`source_id` -//! collisions on the same `(listing_id, ts)`: bitwise-identical OHLCV and matching `session` -//! collapse to one row (`listing_collision_collapsed`), while any OHLCV or `session` conflict -//! drops the entire group (`listing_collision_dropped`), mirroring `curate_bars_1d`. -//! - Writes sorted `Bar1mRow` rows into a caller-owned [`IlpShardedWriter`] without calling -//! [`IlpShardedWriter::finish`], allowing multiple chunks to stream through one writer. - -use std::borrow::Borrow; -use std::error::Error; -use std::fmt; -use std::hash::Hash; -use std::io::{self, Write}; - -use crate::bars::Bar1dRow; -use crate::bars_1m::{ - build_bars_1m, check_session_closes_against_bars_1d, Bar1mRow, Bars1mBuild, Bars1mError, - Bars1mStats, EodIntradayBar, IntradaySession, SessionCloseCheck, SessionCloseCutoffPolicy, - BARS_1M_SOURCE_EOD, -}; -use crate::bson_eod_intraday::BsonEodIntradayDecodeStats; -use crate::bson_stream::{decode_eod_intraday_stream, BsonStreamError, BsonStreamOptions}; -use crate::ilp::{IlpShardedWriter, IlpWriterError}; -use crate::provider_mapping::ProviderMappingTable; -use crate::split::{unadjust_ohlcv, OhlcvBar, SplitTable}; - -/// Accounting summary produced alongside [`CurateBars1mOutput::rows`]. -/// -/// Conservation invariants: -/// - `rows_in == builder.rows_out` -/// - `rows_in == rows_out + dropped_unmapped + listing_collision_collapsed + listing_collision_dropped` -/// - `pre_rows_out + rth_rows_out + post_rows_out == rows_out` -/// - `builder` independently satisfies all [`Bars1mStats`] conservation invariants. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct CurateBars1mStats { - pub builder: Bars1mStats, - pub rows_in: usize, - pub rows_out: usize, - pub listings_out: usize, - pub pre_rows_out: usize, - pub rth_rows_out: usize, - pub post_rows_out: usize, - pub dropped_unmapped: usize, - pub listing_collision_collapsed: usize, - pub listing_collision_dropped: usize, -} - -/// Output of [`curate_bars_1m`]: curated `bars_1m` rows keyed by permanent `listing_id`, sorted -/// and unique by `(listing_id, ts)`, plus full stage and builder statistics. -#[derive(Debug, Clone, PartialEq)] -pub struct CurateBars1mOutput { - pub rows: Vec>, - pub stats: CurateBars1mStats, -} - -/// Typed caller errors returned by [`curate_bars_1m`]. -/// -/// Bad single rows (unmapped dates and cross-`source_id` collisions) are dropped and counted in -/// [`CurateBars1mStats`] rather than aborting the stage. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum CurateBars1mError { - /// Caller-supplied `mapping_source` was empty or contained only whitespace. - EmptyMappingSource, -} - -impl fmt::Display for CurateBars1mError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match *self { - Self::EmptyMappingSource => { - write!(f, "mapping_source must not be empty or blank") - } - } - } -} - -impl Error for CurateBars1mError {} - -/// Summary returned by [`curate_and_write_bars_1m`]. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct CurateBars1mWriteReport { - pub curate_stats: CurateBars1mStats, - /// Number of curated rows accepted by [`IlpShardedWriter::write_bar_1m`] in this call. - pub rows_written: usize, -} - -/// Typed error returned by [`curate_and_write_bars_1m`]. -#[derive(Debug)] -pub enum CurateBars1mWriteError { - Curate(CurateBars1mError), - Ilp(IlpWriterError), -} - -impl fmt::Display for CurateBars1mWriteError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Curate(err) => write!(f, "bars_1m curation failed: {err}"), - Self::Ilp(err) => write!(f, "bars_1m ILP write failed: {err}"), - } - } -} - -impl Error for CurateBars1mWriteError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::Curate(err) => Some(err), - Self::Ilp(err) => Some(err), - } - } -} - -impl From for CurateBars1mWriteError { - fn from(err: CurateBars1mError) -> Self { - Self::Curate(err) - } -} - -impl From for CurateBars1mWriteError { - fn from(err: IlpWriterError) -> Self { - Self::Ilp(err) - } -} - -/// Combined decode and write summary returned by [`curate_and_write_bars_1m_from_bson`]. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct CurateBars1mBsonReport { - pub decode_stats: BsonEodIntradayDecodeStats, - pub write_report: CurateBars1mWriteReport, -} - -/// Typed error returned by [`curate_and_write_bars_1m_from_bson`]. -#[derive(Debug)] -pub enum CurateBars1mBsonError { - Stream(BsonStreamError), - Write(CurateBars1mWriteError), -} - -impl fmt::Display for CurateBars1mBsonError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Stream(err) => write!(f, "bars_1m BSON stream failed: {err}"), - Self::Write(err) => write!(f, "{err}"), - } - } -} - -impl Error for CurateBars1mBsonError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::Stream(err) => Some(err), - Self::Write(err) => Some(err), - } - } -} - -impl From for CurateBars1mBsonError { - fn from(err: BsonStreamError) -> Self { - Self::Stream(err) - } -} - -impl From for CurateBars1mBsonError { - fn from(err: CurateBars1mWriteError) -> Self { - Self::Write(err) - } -} - -#[inline] -fn bar_1m_values_bit_eq(a: &Bar1mRow, b: &Bar1mRow) -> bool { - a.open.to_bits() == b.open.to_bits() - && a.high.to_bits() == b.high.to_bits() - && a.low.to_bits() == b.low.to_bits() - && a.close.to_bits() == b.close.to_bits() - && a.volume.to_bits() == b.volume.to_bits() - && a.session == b.session -} - -#[inline] -fn is_valid_price(price: f64) -> bool { - price.is_finite() && price > 0.0 -} - -#[inline] -fn is_consistent_ohlc(open: f64, high: f64, low: f64, close: f64) -> bool { - high >= low && open >= low && open <= high && close >= low && close <= high -} - -#[inline] -fn decrement_builder_session_count(stats: &mut Bars1mStats, session: IntradaySession) { - match session { - IntradaySession::Pre => stats.pre_rows_out -= 1, - IntradaySession::Rth => stats.rth_rows_out -= 1, - IntradaySession::Post => stats.post_rows_out -= 1, - } -} - -/// Maps source-keyed [`Bars1mBuild`] rows to permanent `listing_id: i32` keys via -/// `provider_mapping` on each bar's Eastern Time `session_date`, optionally un-adjusts OHLCV via -/// `listing_splits` (keyed by permanent `listing_id`, preventing split leakage across reused -/// tickers), stamps `source`, re-sorts in place by `(listing_id, ts)`, and compacts -/// cross-`source_id` collisions. -fn map_bars_1m_impl( - built: Bars1mBuild, - provider_mapping: &ProviderMappingTable, - mapping_source: &str, - source: &'static str, - listing_splits: Option<&SplitTable>, -) -> CurateBars1mOutput -where - K: Eq + AsRef, -{ - let mut stats = CurateBars1mStats { - builder: built.stats, - rows_in: built.rows.len(), - ..CurateBars1mStats::default() - }; - - let mut rows: Vec> = Vec::with_capacity(built.rows.len()); - let total_built = built.rows.len(); - let mut idx = 0usize; - - while idx < total_built { - let run_start = idx; - let run_key = &built.rows[run_start].key; - idx += 1; - while idx < total_built && built.rows[idx].key == *run_key { - idx += 1; - } - let run_end = idx; - - let mut cursor = provider_mapping.cursor_for(mapping_source, run_key.as_ref()); - if cursor.ranges().is_empty() { - stats.dropped_unmapped += run_end - run_start; - continue; - } - - let mut key_kept_or_unmapped = false; - for bar in &built.rows[run_start..run_end] { - let Some(listing_id) = cursor.resolve(bar.session_date) else { - stats.dropped_unmapped += 1; - key_kept_or_unmapped = true; - continue; - }; - - let (open, high, low, close, volume) = if let Some(splits) = listing_splits { - let factor = splits.cum_factor_after(&listing_id, bar.session_date); - if factor != 1.0 { - let mut unadj = unadjust_ohlcv( - OhlcvBar { - open: bar.open, - high: bar.high, - low: bar.low, - close: bar.close, - volume: bar.volume, - }, - factor, - ); - if !is_valid_price(unadj.open) - || !is_valid_price(unadj.high) - || !is_valid_price(unadj.low) - || !is_valid_price(unadj.close) - { - stats.builder.dropped_invalid_ohlc += 1; - stats.builder.rows_out -= 1; - decrement_builder_session_count(&mut stats.builder, bar.session); - stats.rows_in -= 1; - continue; - } - if !is_consistent_ohlc(unadj.open, unadj.high, unadj.low, unadj.close) { - stats.builder.dropped_inconsistent_ohlc += 1; - stats.builder.rows_out -= 1; - decrement_builder_session_count(&mut stats.builder, bar.session); - stats.rows_in -= 1; - continue; - } - if !unadj.volume.is_finite() - || unadj.volume < 0.0 - || (bar.volume > 0.0 && unadj.volume == 0.0) - { - stats.builder.dropped_invalid_volume += 1; - stats.builder.rows_out -= 1; - decrement_builder_session_count(&mut stats.builder, bar.session); - stats.rows_in -= 1; - continue; - } - if unadj.volume == 0.0 { - unadj.volume = 0.0; - } - (unadj.open, unadj.high, unadj.low, unadj.close, unadj.volume) - } else { - (bar.open, bar.high, bar.low, bar.close, bar.volume) - } - } else { - (bar.open, bar.high, bar.low, bar.close, bar.volume) - }; - - key_kept_or_unmapped = true; - rows.push(Bar1mRow { - key: listing_id, - ts: bar.ts, - session_date: bar.session_date, - open, - high, - low, - close, - volume, - session: bar.session, - source, - }); - } - - if !key_kept_or_unmapped { - stats.builder.keys_out -= 1; - } - } - - // Free builder rows before sorting/compacting mapped rows to cut peak RAM. - drop(built.rows); - - rows.sort_unstable_by(|a, b| a.key.cmp(&b.key).then_with(|| a.ts.cmp(&b.ts))); - - let mut write_idx = 0usize; - let mut read_idx = 0usize; - let total_mapped = rows.len(); - let mut last_listing_id: Option = None; - - while read_idx < total_mapped { - let listing_id = rows[read_idx].key; - let ts = rows[read_idx].ts; - let mut group_end = read_idx + 1; - while group_end < total_mapped - && rows[group_end].key == listing_id - && rows[group_end].ts == ts - { - group_end += 1; - } - let group_len = group_end - read_idx; - - let retain_group = if group_len == 1 { - true - } else { - let first = &rows[read_idx]; - let all_identical = rows[read_idx + 1..group_end] - .iter() - .all(|other| bar_1m_values_bit_eq(first, other)); - if all_identical { - stats.listing_collision_collapsed += group_len - 1; - true - } else { - stats.listing_collision_dropped += group_len; - false - } - }; - - if retain_group { - if write_idx != read_idx { - rows.swap(write_idx, read_idx); - } - if last_listing_id != Some(listing_id) { - stats.listings_out += 1; - last_listing_id = Some(listing_id); - } - match rows[write_idx].session { - IntradaySession::Pre => stats.pre_rows_out += 1, - IntradaySession::Rth => stats.rth_rows_out += 1, - IntradaySession::Post => stats.post_rows_out += 1, - } - write_idx += 1; - } - - read_idx = group_end; - } - - rows.truncate(write_idx); - stats.rows_out = rows.len(); - - CurateBars1mOutput { rows, stats } -} - -/// Maps source-keyed [`Bars1mBuild`] rows to permanent `listing_id: i32` keys via -/// `provider_mapping` on each bar's Eastern Time `session_date`, stamps `source`, re-sorts in -/// place by `(listing_id, ts)`, and compacts cross-`source_id` collisions. -pub(crate) fn map_bars_1m( - built: Bars1mBuild, - provider_mapping: &ProviderMappingTable, - mapping_source: &str, - source: &'static str, -) -> CurateBars1mOutput -where - K: Eq + AsRef, -{ - map_bars_1m_impl(built, provider_mapping, mapping_source, source, None) -} - -/// Pure `bars_1m` curation stage: un-adjusts source-keyed `eodIntraday1M` bars via -/// [`build_bars_1m`], resolves `(mapping_source, source_id, session_date) -> listing_id` through -/// `provider_mapping` using each bar's Eastern Time `session_date`, and emits [`Bar1mRow`] -/// rows sorted and unique by `(listing_id, ts)`. -/// -/// - Rejects empty or whitespace-only `mapping_source` with [`CurateBars1mError::EmptyMappingSource`]. -/// Non-blank `mapping_source` values are looked up verbatim. -/// - Rows whose `(mapping_source, source_id, session_date)` is not covered by any range in -/// `provider_mapping` are counted in [`CurateBars1mStats::dropped_unmapped`]. -/// - After re-sorting in place by `(listing_id, ts)`, cross-`source_id` collisions on the same -/// `(listing_id, ts)` collapse to one row when OHLCV (bitwise) and `session` match -/// (`listing_collision_collapsed += g - 1`), and drop the entire group otherwise -/// (`listing_collision_dropped += g`). -pub fn curate_bars_1m( - bars: B, - splits: &SplitTable, - provider_mapping: &ProviderMappingTable, - mapping_source: &str, -) -> Result -where - K: Ord + Eq + Hash + Clone + AsRef, - B: IntoIterator>, -{ - if mapping_source.trim().is_empty() { - return Err(CurateBars1mError::EmptyMappingSource); - } - - let built = build_bars_1m(bars, splits); - Ok(map_bars_1m( - built, - provider_mapping, - mapping_source, - BARS_1M_SOURCE_EOD, - )) -} - -/// Thin wrapper running [`check_session_closes_against_bars_1d`] over `listing_id`-keyed curated -/// `bars_1m` rows against `listing_id`-keyed raw [`Bar1dRow`] closes using the caller's -/// [`SessionCloseCutoffPolicy`] and `rel_tolerance`. -pub fn check_curated_session_closes( - rows_1m: &[Bar1mRow], - bars_1d: I, - cutoff_policy: &SessionCloseCutoffPolicy, - rel_tolerance: f64, -) -> Result, Bars1mError> -where - R: Borrow>, - I: IntoIterator, -{ - check_session_closes_against_bars_1d(rows_1m, bars_1d, cutoff_policy, rel_tolerance) -} - -/// Runs [`curate_bars_1m`] and streams every curated row in `(listing_id, ts)` order into the -/// caller-owned [`IlpShardedWriter`] using `known_at_micros`. -/// -/// Intentionally does **not** call [`IlpShardedWriter::finish`], so callers may stream multiple -/// chunks through a single writer before flushing and collecting aggregate [`crate::ilp::IlpWriteStats`]. -pub fn curate_and_write_bars_1m( - bars: B, - splits: &SplitTable, - provider_mapping: &ProviderMappingTable, - mapping_source: &str, - writer: &mut IlpShardedWriter, - known_at_micros: i64, -) -> Result -where - W: Write + Send, - K: Ord + Eq + Hash + Clone + AsRef, - B: IntoIterator>, -{ - let curated = curate_bars_1m(bars, splits, provider_mapping, mapping_source)?; - let mut rows_written = 0usize; - for row in &curated.rows { - writer.write_bar_1m(row, known_at_micros)?; - rows_written += 1; - } - - Ok(CurateBars1mWriteReport { - curate_stats: curated.stats, - rows_written, - }) -} - -/// Variant of [`curate_and_write_bars_1m`] that takes a [`SplitTable`] keyed by permanent -/// `listing_id` and resolves `(mapping_source, source_id, session_date) -> listing_id` on each -/// bar's Eastern Time `session_date` **before** applying split un-adjustment. -/// -/// This prevents split leakage across reused tickers (e.g., `FB.US` listing 10 through June 2022 -/// vs. listing 20 starting in 2025) while preserving all [`CurateBars1mStats`] conservation -/// invariants and cross-`source_id` collision handling. -pub(crate) fn curate_and_write_bars_1m_by_listing( - bars: B, - listing_splits: &SplitTable, - provider_mapping: &ProviderMappingTable, - mapping_source: &str, - writer: &mut IlpShardedWriter, - known_at_micros: i64, -) -> Result -where - W: Write + Send, - K: Ord + Eq + Hash + Clone + AsRef, - B: IntoIterator>, -{ - if mapping_source.trim().is_empty() { - return Err(CurateBars1mError::EmptyMappingSource.into()); - } - - let empty_splits: SplitTable = SplitTable::default(); - let built = build_bars_1m(bars, &empty_splits); - let curated = map_bars_1m_impl( - built, - provider_mapping, - mapping_source, - BARS_1M_SOURCE_EOD, - Some(listing_splits), - ); - let mut rows_written = 0usize; - for row in &curated.rows { - writer.write_bar_1m(row, known_at_micros)?; - rows_written += 1; - } - - Ok(CurateBars1mWriteReport { - curate_stats: curated.stats, - rows_written, - }) -} - -/// Decodes a concatenated raw BSON `eodIntraday1M` stream via [`decode_eod_intraday_stream`], -/// converts each valid document via [`crate::bson_eod_intraday::RawEodIntradayBar::into_eod_intraday_bar`], -/// and runs [`curate_and_write_bars_1m`] against the caller-owned [`IlpShardedWriter`]. -/// -/// Per-document semantic decode errors are counted and skipped in [`BsonEodIntradayDecodeStats`]; -/// fatal stream framing or I/O errors abort before any row from this call is written to `writer`. -/// -/// # Memory note -/// This helper buffers all decoded [`EodIntradayBar`] rows for a single call in memory -/// before curating and writing. Bounded chunking by listing or calendar month is handled by -/// higher-level runner stages. -#[allow(clippy::too_many_arguments)] -pub fn curate_and_write_bars_1m_from_bson( - reader: R, - options: BsonStreamOptions, - splits: &SplitTable, - provider_mapping: &ProviderMappingTable, - mapping_source: &str, - writer: &mut IlpShardedWriter, - known_at_micros: i64, -) -> Result -where - R: io::Read, - W: Write + Send, -{ - if mapping_source.trim().is_empty() { - return Err(CurateBars1mWriteError::Curate(CurateBars1mError::EmptyMappingSource).into()); - } - - let mut bars: Vec> = Vec::new(); - let decode_stats = decode_eod_intraday_stream( - reader, - options, - |raw| { - bars.push(raw.into_eod_intraday_bar(|code, _| code.to_owned())); - }, - |_offset, _err| {}, - )?; - - let write_report = curate_and_write_bars_1m( - bars, - splits, - provider_mapping, - mapping_source, - writer, - known_at_micros, - )?; - - Ok(CurateBars1mBsonReport { - decode_stats, - write_report, - }) -} - -#[cfg(test)] -#[path = "curate_bars_1m_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/curate_bars_1m_tests.rs b/tools/curate-etl/src/curate_bars_1m_tests.rs deleted file mode 100644 index fc56c83e..00000000 --- a/tools/curate-etl/src/curate_bars_1m_tests.rs +++ /dev/null @@ -1,886 +0,0 @@ -use std::error::Error; -use std::io::{self, Cursor, Write}; - -use bson::raw::{cstr, RawDocumentBuf}; - -use super::*; -use crate::bars::Bar1dRow; -use crate::bars_1m::{BARS_1M_SOURCE_EOD, IntradaySession}; -use crate::ilp::{encode_bar_1m, shard_for_listing_id, IlpWriterOptions, TABLE_BARS_1M}; -use crate::provider_mapping::ProviderMappingRow; -use crate::shorts::et_to_utc_micros; -use crate::split::{ymd_to_epoch_days, SplitEvent}; - -fn day(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).expect("valid date") -} - -fn et_ts(y: i32, m: u32, d: u32, hour: u8, minute: u8) -> i64 { - et_to_utc_micros(day(y, m, d), hour, minute, 0).expect("valid ET timestamp") -} - -fn bar_1m( - key: &str, - ts: i64, - open: f64, - high: f64, - low: f64, - close: f64, - volume: f64, -) -> EodIntradayBar { - EodIntradayBar { - key: key.to_string(), - ts, - open, - high, - low, - close, - volume, - } -} - -fn daily_row(listing_id: i32, session_date: i32, close: f64) -> Bar1dRow { - Bar1dRow { - key: listing_id, - session_date, - open: close, - high: close, - low: close, - close, - volume: 100_000.0, - } -} - -fn map_row( - source: &str, - source_id: &str, - valid_from: i32, - valid_to: Option, - listing_id: i32, -) -> ProviderMappingRow { - ProviderMappingRow { - source: source.to_string(), - source_id: source_id.to_string(), - valid_from, - valid_to, - listing_id, - } -} - -fn make_bson_doc( - code: &str, - timestamp_sec: i64, - open: f64, - high: f64, - low: f64, - close: f64, - volume: f64, -) -> RawDocumentBuf { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), code); - doc.append(cstr!("timestamp"), timestamp_sec); - doc.append(cstr!("open"), open); - doc.append(cstr!("high"), high); - doc.append(cstr!("low"), low); - doc.append(cstr!("close"), close); - doc.append(cstr!("volume"), volume); - doc -} - -fn assert_rel_eq(actual: f64, expected: f64, rel_tol: f64) { - let diff = (actual - expected).abs(); - let scale = expected.abs().max(1.0); - assert!( - diff <= rel_tol * scale, - "actual={actual} expected={expected} diff={diff} rel_tol={rel_tol}" - ); -} - -fn assert_conservation_and_order(out: &CurateBars1mOutput) { - let s = &out.stats; - assert_eq!( - s.rows_in, s.builder.rows_out, - "rows_in != builder.rows_out: {s:?}" - ); - assert_eq!(s.rows_out, out.rows.len(), "rows_out != rows.len(): {s:?}"); - assert_eq!( - s.rows_in, - s.rows_out - + s.dropped_unmapped - + s.listing_collision_collapsed - + s.listing_collision_dropped, - "curate_bars_1m conservation invariant failed: {s:?}" - ); - assert_eq!( - s.rows_out, - s.pre_rows_out + s.rth_rows_out + s.post_rows_out, - "session breakdown != rows_out: {s:?}" - ); - - for pair in out.rows.windows(2) { - assert!( - (pair[0].key, pair[0].ts) < (pair[1].key, pair[1].ts), - "rows not strictly sorted and unique by (listing_id, ts): {:?} vs {:?}", - (pair[0].key, pair[0].ts), - (pair[1].key, pair[1].ts) - ); - } -} - -fn contains_subslice(haystack: &[u8], needle: &[u8]) -> bool { - !needle.is_empty() && haystack.windows(needle.len()).any(|w| w == needle) -} - -#[test] -fn nexm_reverse_split_1_for_20_curates_by_listing_id_and_matches_bars_1d() { - let pre_day = day(2025, 6, 17); - let ex_date = day(2025, 6, 18); - let nexm_listing_id = 42_001; - - let splits = SplitTable::from_events([( - "NEXM.V".to_string(), - SplitEvent { - ex_date, - ratio: 0.05, - }, - )]) - .unwrap(); - let mapping = ProviderMappingTable::from_rows([map_row( - "eod", - "NEXM.V", - day(2020, 1, 1), - None, - nexm_listing_id, - )]) - .unwrap(); - - // Pre-split adjusted 1m close = 24.29 -> raw = 24.29 * 0.05 = 1.2145, volume = 5000 / 0.05 = 100_000. - let pre_open_bar = bar_1m( - "NEXM.V", - et_ts(2025, 6, 17, 9, 30), - 24.00, - 24.60, - 23.80, - 24.20, - 2_000.0, - ); - let pre_close_bar = bar_1m( - "NEXM.V", - et_ts(2025, 6, 17, 15, 59), - 24.20, - 24.40, - 24.10, - 24.29, - 5_000.0, - ); - let ex_bar = bar_1m( - "NEXM.V", - et_ts(2025, 6, 18, 15, 59), - 24.10, - 24.50, - 23.90, - 24.30, - 12_500.0, - ); - - let out = curate_bars_1m( - [pre_open_bar, pre_close_bar.clone(), ex_bar.clone()], - &splits, - &mapping, - "eod", - ) - .unwrap(); - assert_conservation_and_order(&out); - assert_eq!(out.stats.rows_in, 3); - assert_eq!(out.stats.rows_out, 3); - assert_eq!(out.stats.listings_out, 1); - assert_eq!(out.stats.rth_rows_out, 3); - assert!(out.rows.iter().all(|r| r.key == nexm_listing_id)); - - let pre_close_out = &out.rows[1]; - assert_eq!(pre_close_out.key, nexm_listing_id); - assert_eq!(pre_close_out.session_date, pre_day); - assert_eq!(pre_close_out.session, IntradaySession::Rth); - assert_eq!(pre_close_out.source, BARS_1M_SOURCE_EOD); - assert_rel_eq(pre_close_out.open, 1.21, 1e-12); - assert_rel_eq(pre_close_out.high, 1.22, 1e-12); - assert_rel_eq(pre_close_out.low, 1.205, 1e-12); - assert_rel_eq(pre_close_out.close, 1.2145, 1e-12); - assert_rel_eq(pre_close_out.volume, 100_000.0, 1e-12); - assert_rel_eq( - pre_close_out.close * pre_close_out.volume, - pre_close_bar.close * pre_close_bar.volume, - 1e-12, - ); - - // Ex-date bar must be bitwise unchanged. - let ex_out = &out.rows[2]; - assert_eq!(ex_out.key, nexm_listing_id); - assert_eq!(ex_out.session_date, ex_date); - assert_eq!(ex_out.open.to_bits(), ex_bar.open.to_bits()); - assert_eq!(ex_out.high.to_bits(), ex_bar.high.to_bits()); - assert_eq!(ex_out.low.to_bits(), ex_bar.low.to_bits()); - assert_eq!(ex_out.close.to_bits(), ex_bar.close.to_bits()); - assert_eq!(ex_out.volume.to_bits(), ex_bar.volume.to_bits()); - - let daily_closes = [ - daily_row(nexm_listing_id, pre_day, 1.215), // ~0.041% diff vs 1.2145 - daily_row(nexm_listing_id, ex_date, 24.30), - ]; - let policy = SessionCloseCutoffPolicy::standard_rth(); - let check = check_curated_session_closes(&out.rows, &daily_closes, &policy, 0.005).unwrap(); - assert_eq!(check.stats.checked, 2); - assert_eq!(check.stats.within_tolerance, 2); - assert_eq!(check.stats.mismatched, 0); - assert_eq!(check.stats.unchecked, 0); - assert!(check.stats.max_rel_diff < 0.005); - assert!(check.mismatch_samples.is_empty()); -} - -#[test] -fn nvda_forward_split_10_for_1_matches_bars_1d_and_fails_negative_control_without_splits() { - let pre_day = day(2024, 6, 7); - let ex_date = day(2024, 6, 10); - let nvda_listing_id = 77_001; - - let splits = SplitTable::from_events([( - "NVDA.US".to_string(), - SplitEvent { - ex_date, - ratio: 10.0, - }, - )]) - .unwrap(); - let mapping = ProviderMappingTable::from_rows([map_row( - "eod", - "NVDA.US", - day(2020, 1, 1), - None, - nvda_listing_id, - )]) - .unwrap(); - - // Pre-split adjusted 1m close = 120.888 -> raw = 1208.88; volume = 412_390 -> raw = 41_239. - let pre_bar = bar_1m( - "NVDA.US", - et_ts(2024, 6, 7, 15, 59), - 120.50, - 121.00, - 120.40, - 120.888, - 412_390.0, - ); - let ex_bar = bar_1m( - "NVDA.US", - et_ts(2024, 6, 10, 15, 59), - 121.50, - 121.95, - 121.40, - 121.79, - 350_000.0, - ); - let daily_closes = [ - daily_row(nvda_listing_id, pre_day, 1208.88), - daily_row(nvda_listing_id, ex_date, 121.79), - ]; - let policy = SessionCloseCutoffPolicy::standard_rth(); - - let out = curate_bars_1m([pre_bar.clone(), ex_bar.clone()], &splits, &mapping, "eod").unwrap(); - assert_conservation_and_order(&out); - assert_eq!(out.stats.rows_in, 2); - assert_eq!(out.stats.rows_out, 2); - assert_eq!(out.stats.listings_out, 1); - assert_eq!(out.stats.rth_rows_out, 2); - - let pre_out = &out.rows[0]; - assert_eq!(pre_out.key, nvda_listing_id); - assert_eq!(pre_out.session_date, pre_day); - assert_rel_eq(pre_out.open, 1205.0, 1e-12); - assert_rel_eq(pre_out.high, 1210.0, 1e-12); - assert_rel_eq(pre_out.low, 1204.0, 1e-12); - assert_rel_eq(pre_out.close, 1208.88, 1e-12); - assert_rel_eq(pre_out.volume, 41_239.0, 1e-12); - assert_rel_eq( - pre_out.close * pre_out.volume, - pre_bar.close * pre_bar.volume, - 1e-12, - ); - - let ex_out = &out.rows[1]; - assert_eq!(ex_out.key, nvda_listing_id); - assert_eq!(ex_out.session_date, ex_date); - assert_eq!(ex_out.open.to_bits(), ex_bar.open.to_bits()); - assert_eq!(ex_out.high.to_bits(), ex_bar.high.to_bits()); - assert_eq!(ex_out.low.to_bits(), ex_bar.low.to_bits()); - assert_eq!(ex_out.close.to_bits(), ex_bar.close.to_bits()); - assert_eq!(ex_out.volume.to_bits(), ex_bar.volume.to_bits()); - - let check = check_curated_session_closes(&out.rows, &daily_closes, &policy, 0.005).unwrap(); - assert_eq!(check.stats.checked, 2); - assert_eq!(check.stats.within_tolerance, 2); - assert_eq!(check.stats.mismatched, 0); - assert_eq!(check.stats.unchecked, 0); - assert!(check.mismatch_samples.is_empty()); - - // Negative control: empty split table leaves pre-split 1m bar split-adjusted, so June 7 fails. - let empty_splits = SplitTable::::default(); - let unsplit_out = - curate_bars_1m([pre_bar, ex_bar], &empty_splits, &mapping, "eod").unwrap(); - assert_conservation_and_order(&unsplit_out); - let neg_check = - check_curated_session_closes(&unsplit_out.rows, &daily_closes, &policy, 0.005).unwrap(); - assert_eq!(neg_check.stats.checked, 2); - assert_eq!(neg_check.stats.within_tolerance, 1); - assert_eq!(neg_check.stats.mismatched, 1); - assert_eq!(neg_check.stats.unchecked, 0); - assert_eq!(neg_check.mismatch_samples.len(), 1); - assert_eq!(neg_check.mismatch_samples[0].key, nvda_listing_id); - assert_eq!(neg_check.mismatch_samples[0].session_date, pre_day); -} - -#[test] -fn check_curated_session_closes_forwards_early_close_cutoff_policy() { - let early_day = day(2024, 11, 29); - let listing_id = 55_001; - let splits = SplitTable::::default(); - let mapping = ProviderMappingTable::from_rows([map_row( - "eod", - "NVDA.US", - day(2020, 1, 1), - None, - listing_id, - )]) - .unwrap(); - - // 12:59 ET matches the official early-close daily close; a stray 15:59 ET print differs. - let out = curate_bars_1m( - [ - bar_1m("NVDA.US", et_ts(2024, 11, 29, 12, 59), 138.0, 138.5, 137.8, 138.25, 10_000.0), - bar_1m("NVDA.US", et_ts(2024, 11, 29, 15, 59), 145.0, 145.5, 144.8, 145.00, 100.0), - ], - &splits, - &mapping, - "eod", - ) - .unwrap(); - assert_conservation_and_order(&out); - - let daily = [daily_row(listing_id, early_day, 138.25)]; - let early_policy = SessionCloseCutoffPolicy::standard_rth() - .with_date_cutoff(early_day, et_ts(2024, 11, 29, 13, 0)); - let early_check = - check_curated_session_closes(&out.rows, &daily, &early_policy, 0.005).unwrap(); - assert_eq!(early_check.stats.checked, 1); - assert_eq!(early_check.stats.within_tolerance, 1); - assert_eq!(early_check.stats.mismatched, 0); - assert_eq!(early_check.stats.unchecked, 0); - - // Without the early-close cutoff, the 15:59 ET bar is selected and mismatches. - let standard_policy = SessionCloseCutoffPolicy::standard_rth(); - let standard_check = - check_curated_session_closes(&out.rows, &daily, &standard_policy, 0.005).unwrap(); - assert_eq!(standard_check.stats.checked, 1); - assert_eq!(standard_check.stats.within_tolerance, 0); - assert_eq!(standard_check.stats.mismatched, 1); -} - -#[test] -fn unmapped_source_code_is_dropped_and_conserved() { - let splits = SplitTable::::default(); - let mapping = ProviderMappingTable::from_rows([map_row( - "eod", - "OTHER.US", - day(2020, 1, 1), - None, - 101, - )]) - .unwrap(); - - let out = curate_bars_1m( - [bar_1m( - "MISSING.US", - et_ts(2024, 6, 10, 10, 0), - 10.0, - 10.5, - 9.8, - 10.2, - 1_000.0, - )], - &splits, - &mapping, - "eod", - ) - .unwrap(); - assert_conservation_and_order(&out); - assert!(out.rows.is_empty()); - assert_eq!(out.stats.rows_in, 1); - assert_eq!(out.stats.rows_out, 0); - assert_eq!(out.stats.dropped_unmapped, 1); - assert_eq!(out.stats.listings_out, 0); - assert_eq!(out.stats.listing_collision_collapsed, 0); - assert_eq!(out.stats.listing_collision_dropped, 0); -} - -#[test] -fn mapping_range_change_uses_et_session_date_and_sorts_by_listing_id_and_ts() { - let d1 = day(2024, 6, 10); - let d2 = day(2024, 6, 11); - let earlier_listing_id = 200; // intentionally larger than later_listing_id - let later_listing_id = 100; - - let splits = SplitTable::::default(); - let mapping = ProviderMappingTable::from_rows([ - map_row("eod", "REUSED.US", day(2020, 1, 1), Some(d1), earlier_listing_id), - map_row("eod", "REUSED.US", d2, None, later_listing_id), - ]) - .unwrap(); - - // 20:30 ET on 2024-06-10 (EDT = UTC-4) is 00:30 UTC on 2024-06-11. - // Lookup must use ET session_date (d1), not UTC date (d2). - let pre_change_late_et = bar_1m( - "REUSED.US", - et_ts(2024, 6, 10, 20, 30), - 10.0, - 10.2, - 9.9, - 10.1, - 500.0, - ); - let post_change_pre_market = bar_1m( - "REUSED.US", - et_ts(2024, 6, 11, 8, 15), - 20.0, - 20.5, - 19.8, - 20.2, - 800.0, - ); - - // Supply out of final (listing_id, ts) order (listing 200 before listing 100). - let out = curate_bars_1m( - [pre_change_late_et.clone(), post_change_pre_market.clone()], - &splits, - &mapping, - "eod", - ) - .unwrap(); - assert_conservation_and_order(&out); - assert_eq!(out.stats.rows_in, 2); - assert_eq!(out.stats.rows_out, 2); - assert_eq!(out.stats.listings_out, 2); - assert_eq!(out.stats.dropped_unmapped, 0); - assert_eq!(out.stats.pre_rows_out, 1); - assert_eq!(out.stats.rth_rows_out, 0); - assert_eq!(out.stats.post_rows_out, 1); - - assert_eq!(out.rows[0].key, later_listing_id); - assert_eq!(out.rows[0].session_date, d2); - assert_eq!(out.rows[0].session, IntradaySession::Pre); - assert_eq!(out.rows[0].ts, post_change_pre_market.ts); - - assert_eq!(out.rows[1].key, earlier_listing_id); - assert_eq!(out.rows[1].session_date, d1); - assert_eq!(out.rows[1].session, IntradaySession::Post); - assert_eq!(out.rows[1].ts, pre_change_late_et.ts); -} - -#[test] -fn cross_source_identical_aliases_collapse_and_conflicting_aliases_drop_group() { - let ts_same = et_ts(2024, 6, 10, 10, 15); - let listing_id = 300; - let splits = SplitTable::::default(); - let mapping = ProviderMappingTable::from_rows([ - map_row("eod", "ALIAS_A.US", day(2020, 1, 1), None, listing_id), - map_row("eod", "ALIAS_B.US", day(2020, 1, 1), None, listing_id), - map_row("eod", "ALIAS_C.US", day(2020, 1, 1), None, listing_id), - ]) - .unwrap(); - - // Identical aliases: 2 in, 1 out, 1 collapsed. - let collapsed = curate_bars_1m( - [ - bar_1m("ALIAS_A.US", ts_same, 50.0, 51.0, 49.5, 50.5, 1_200.0), - bar_1m("ALIAS_B.US", ts_same, 50.0, 51.0, 49.5, 50.5, 1_200.0), - ], - &splits, - &mapping, - "eod", - ) - .unwrap(); - assert_conservation_and_order(&collapsed); - assert_eq!(collapsed.stats.rows_in, 2); - assert_eq!(collapsed.stats.rows_out, 1); - assert_eq!(collapsed.stats.listings_out, 1); - assert_eq!(collapsed.stats.rth_rows_out, 1); - assert_eq!(collapsed.stats.listing_collision_collapsed, 1); - assert_eq!(collapsed.stats.listing_collision_dropped, 0); - - // Conflicting aliases: 2 matching + 1 differing -> 3 in, 0 out, 3 dropped. - let conflicted = curate_bars_1m( - [ - bar_1m("ALIAS_A.US", ts_same, 50.0, 51.0, 49.5, 50.5, 1_200.0), - bar_1m("ALIAS_B.US", ts_same, 50.0, 51.0, 49.5, 50.5, 1_200.0), - bar_1m("ALIAS_C.US", ts_same, 50.0, 51.0, 49.5, 50.75, 1_200.0), - ], - &splits, - &mapping, - "eod", - ) - .unwrap(); - assert_conservation_and_order(&conflicted); - assert!(conflicted.rows.is_empty()); - assert_eq!(conflicted.stats.rows_in, 3); - assert_eq!(conflicted.stats.rows_out, 0); - assert_eq!(conflicted.stats.listings_out, 0); - assert_eq!(conflicted.stats.listing_collision_collapsed, 0); - assert_eq!(conflicted.stats.listing_collision_dropped, 3); -} - -#[test] -fn blank_or_whitespace_mapping_source_returns_empty_mapping_source_error() { - let splits = SplitTable::::default(); - let mapping = ProviderMappingTable::default(); - - assert_eq!( - curate_bars_1m(Vec::>::new(), &splits, &mapping, ""), - Err(CurateBars1mError::EmptyMappingSource) - ); - assert_eq!( - curate_bars_1m(Vec::>::new(), &splits, &mapping, " \t\n "), - Err(CurateBars1mError::EmptyMappingSource) - ); - - let mut sink = Vec::::new(); - let mut writer = IlpShardedWriter::new(vec![&mut sink], IlpWriterOptions::default()).unwrap(); - let err = curate_and_write_bars_1m( - Vec::>::new(), - &splits, - &mapping, - " ", - &mut writer, - 1_700_000_000_000_000, - ) - .unwrap_err(); - assert!(matches!( - err, - CurateBars1mWriteError::Curate(CurateBars1mError::EmptyMappingSource) - )); - assert!(err.source().is_some()); -} - -#[test] -fn ilp_round_trip_matches_exact_per_shard_bytes_and_supports_multi_call_writer_reuse() { - let known_at = 1_718_050_000_000_000_i64; - let splits = SplitTable::::default(); - let listing_ids = [101_i32, 202, 303, 404, 505, 606]; - let mapping = ProviderMappingTable::from_rows(listing_ids.iter().map(|&id| { - map_row( - "eod", - &format!("SYM{id}.US"), - day(2020, 1, 1), - None, - id, - ) - })) - .unwrap(); - - let chunk1: Vec> = listing_ids - .iter() - .enumerate() - .flat_map(|(i, &id)| { - let code = format!("SYM{id}.US"); - let base = 10.0 + i as f64; - [ - bar_1m(&code, et_ts(2024, 6, 10, 9, 30), base, base + 1.0, base - 0.5, base + 0.2, 100.0), - bar_1m(&code, et_ts(2024, 6, 10, 15, 59), base + 0.2, base + 1.2, base, base + 0.8, 250.0), - ] - }) - .collect(); - - // Expected exact per-shard binary payloads from curate_bars_1m + encode_bar_1m. - let curated1 = curate_bars_1m(chunk1.clone(), &splits, &mapping, "eod").unwrap(); - assert_conservation_and_order(&curated1); - let mut expected_shards = vec![Vec::::new(); 4]; - for row in &curated1.rows { - let shard = shard_for_listing_id(row.key, 4); - encode_bar_1m(&mut expected_shards[shard], row, known_at).unwrap(); - } - - let mut s0 = Vec::new(); - let mut s1 = Vec::new(); - let mut s2 = Vec::new(); - let mut s3 = Vec::new(); - let (report1, stats1) = { - let mut writer = IlpShardedWriter::new( - vec![&mut s0, &mut s1, &mut s2, &mut s3], - IlpWriterOptions::default(), - ) - .unwrap(); - let report = - curate_and_write_bars_1m(chunk1.clone(), &splits, &mapping, "eod", &mut writer, known_at) - .unwrap(); - let stats = writer.finish().unwrap(); - (report, stats) - }; - - assert_eq!(report1.rows_written, report1.curate_stats.rows_out); - assert_eq!(stats1.rows, report1.rows_written); - assert_eq!(stats1.rows, 12); - - let actual_shards = [&s0, &s1, &s2, &s3]; - for shard in 0..4 { - assert_eq!(actual_shards[shard], &expected_shards[shard]); - if !actual_shards[shard].is_empty() { - assert!(contains_subslice( - actual_shards[shard], - TABLE_BARS_1M.as_bytes() - )); - } - } - - for &id in &listing_ids { - let target_shard = shard_for_listing_id(id, 4); - let token = format!(",listing_id={id},"); - for (shard, payload) in actual_shards.iter().enumerate() { - if shard == target_shard { - assert!( - contains_subslice(payload, token.as_bytes()), - "missing listing {id} on target shard {target_shard}" - ); - } else { - assert!( - !contains_subslice(payload, token.as_bytes()), - "listing {id} leaked onto non-target shard {shard}" - ); - } - } - } - - // Reuse one writer across two calls and verify aggregate finish() row count. - let chunk2 = vec![ - bar_1m("SYM101.US", et_ts(2024, 6, 11, 9, 30), 11.0, 11.5, 10.8, 11.2, 300.0), - bar_1m("SYM202.US", et_ts(2024, 6, 11, 16, 15), 12.0, 12.4, 11.9, 12.1, 400.0), - ]; - let mut r0 = Vec::new(); - let mut r1 = Vec::new(); - let mut r2 = Vec::new(); - let mut r3 = Vec::new(); - let mut writer = IlpShardedWriter::new( - vec![&mut r0, &mut r1, &mut r2, &mut r3], - IlpWriterOptions::default(), - ) - .unwrap(); - let rep_a = - curate_and_write_bars_1m(chunk1, &splits, &mapping, "eod", &mut writer, known_at).unwrap(); - let rep_b = - curate_and_write_bars_1m(chunk2, &splits, &mapping, "eod", &mut writer, known_at).unwrap(); - let agg_stats = writer.finish().unwrap(); - assert_eq!(agg_stats.rows, rep_a.rows_written + rep_b.rows_written); - assert_eq!(agg_stats.rows, 14); -} - -struct FailingSink { - fail_on_write: bool, -} - -impl Write for FailingSink { - fn write(&mut self, buf: &[u8]) -> io::Result { - if self.fail_on_write { - Err(io::Error::new( - io::ErrorKind::BrokenPipe, - "simulated sink write failure", - )) - } else { - Ok(buf.len()) - } - } - - fn flush(&mut self) -> io::Result<()> { - Ok(()) - } -} - -#[test] -fn writer_io_failure_surfaces_typed_error_with_source_and_poisons_writer() { - let listing_id = 909; - let target_shard = shard_for_listing_id(listing_id, 4); - let splits = SplitTable::::default(); - let mapping = ProviderMappingTable::from_rows([map_row( - "eod", - "FAIL.US", - day(2020, 1, 1), - None, - listing_id, - )]) - .unwrap(); - - let sinks: Vec = (0..4) - .map(|idx| FailingSink { - fail_on_write: idx == target_shard, - }) - .collect(); - let mut writer = IlpShardedWriter::new( - sinks, - IlpWriterOptions { - max_batch_bytes: 1024, - max_batch_rows: 1, - }, - ) - .unwrap(); - - let bar = bar_1m("FAIL.US", et_ts(2024, 6, 10, 10, 0), 10.0, 10.5, 9.9, 10.2, 500.0); - let err = curate_and_write_bars_1m( - [bar.clone()], - &splits, - &mapping, - "eod", - &mut writer, - 1_718_050_000_000_000, - ) - .unwrap_err(); - - match &err { - CurateBars1mWriteError::Ilp(IlpWriterError::Io { shard, source }) => { - assert_eq!(*shard, target_shard); - assert_eq!(source.kind(), io::ErrorKind::BrokenPipe); - } - other => panic!("expected Ilp(Io) error, got {other:?}"), - } - let ilp_source = err.source().expect("write error exposes IlpWriterError"); - assert!(ilp_source.source().is_some()); - - // Subsequent call must observe the writer's poisoned state. - let poisoned_err = curate_and_write_bars_1m( - [bar], - &splits, - &mapping, - "eod", - &mut writer, - 1_718_050_000_000_000, - ) - .unwrap_err(); - assert!(matches!( - poisoned_err, - CurateBars1mWriteError::Ilp(IlpWriterError::Poisoned { failed_shard }) - if failed_shard == target_shard - )); -} - -#[test] -fn bson_stream_counts_rejected_doc_and_aborts_cleanly_on_truncated_tail() { - let listing_id = 77_001; - let known_at = 1_718_050_000_000_000_i64; - let splits = SplitTable::from_events([( - "NVDA.US".to_string(), - SplitEvent { - ex_date: day(2024, 6, 10), - ratio: 10.0, - }, - )]) - .unwrap(); - let mapping = ProviderMappingTable::from_rows([map_row( - "eod", - "NVDA.US", - day(2020, 1, 1), - None, - listing_id, - )]) - .unwrap(); - - let doc1 = make_bson_doc( - "NVDA.US", - et_ts(2024, 6, 7, 15, 59) / 1_000_000, - 120.50, - 121.00, - 120.40, - 120.888, - 412_390.0, - ); - let doc2 = make_bson_doc( - "NVDA.US", - et_ts(2024, 6, 10, 15, 59) / 1_000_000, - 121.50, - 121.95, - 121.40, - 121.79, - 350_000.0, - ); - // Correctly framed BSON document missing required field `close`. - let mut bad_doc = RawDocumentBuf::new(); - bad_doc.append(cstr!("eodSearchCode"), "NVDA.US"); - bad_doc.append(cstr!("timestamp"), et_ts(2024, 6, 10, 10, 0) / 1_000_000); - bad_doc.append(cstr!("open"), 120.0_f64); - bad_doc.append(cstr!("high"), 121.0_f64); - bad_doc.append(cstr!("low"), 119.5_f64); - bad_doc.append(cstr!("volume"), 1_000.0_f64); - - let mut stream_bytes = Vec::new(); - stream_bytes.extend_from_slice(doc1.as_bytes()); - stream_bytes.extend_from_slice(bad_doc.as_bytes()); - stream_bytes.extend_from_slice(doc2.as_bytes()); - - let mut sink = Vec::new(); - let (report, ilp_stats) = { - let mut writer = - IlpShardedWriter::new(vec![&mut sink], IlpWriterOptions::default()).unwrap(); - let report = curate_and_write_bars_1m_from_bson( - Cursor::new(&stream_bytes), - BsonStreamOptions::default(), - &splits, - &mapping, - "eod", - &mut writer, - known_at, - ) - .unwrap(); - let stats = writer.finish().unwrap(); - (report, stats) - }; - - assert_eq!(report.decode_stats.docs_seen, 3); - assert_eq!(report.decode_stats.rows_decoded, 2); - assert_eq!(report.decode_stats.rejected_total(), 1); - assert_eq!(report.decode_stats.rejected_missing_field, 1); - assert_eq!(report.write_report.rows_written, 2); - assert_eq!(report.write_report.curate_stats.rows_out, 2); - assert_eq!(ilp_stats.rows, 2); - assert!(contains_subslice(&sink, TABLE_BARS_1M.as_bytes())); - - // Fatal framing error: truncated second document must fail and write zero rows to any sink. - let mut truncated_bytes = Vec::new(); - truncated_bytes.extend_from_slice(doc1.as_bytes()); - let doc2_bytes = doc2.as_bytes(); - truncated_bytes.extend_from_slice(&doc2_bytes[..doc2_bytes.len() / 2]); - - let mut sink_trunc = Vec::new(); - let (err, trunc_stats) = { - let mut writer = IlpShardedWriter::new( - vec![&mut sink_trunc], - IlpWriterOptions { - max_batch_bytes: 1024, - max_batch_rows: 1, - }, - ) - .unwrap(); - let err = curate_and_write_bars_1m_from_bson( - Cursor::new(&truncated_bytes), - BsonStreamOptions::default(), - &splits, - &mapping, - "eod", - &mut writer, - known_at, - ) - .unwrap_err(); - let stats = writer.finish().unwrap(); - (err, stats) - }; - - assert!(matches!( - err, - CurateBars1mBsonError::Stream(BsonStreamError::TruncatedDocument { .. }) - )); - assert!(err.source().is_some()); - assert_eq!(trunc_stats.rows, 0); - assert!(sink_trunc.is_empty()); -} diff --git a/tools/curate-etl/src/curate_corporate_actions.rs b/tools/curate-etl/src/curate_corporate_actions.rs deleted file mode 100644 index 07711998..00000000 --- a/tools/curate-etl/src/curate_corporate_actions.rs +++ /dev/null @@ -1,600 +0,0 @@ -//! Pure, in-memory `corporate_actions` curation stage joining -//! [`crate::corporate_actions::build_corporate_actions`], -//! [`crate::provider_mapping::ProviderMappingTable`], -//! [`crate::session_close::et_session_close_utc_micros`], and -//! [`crate::parquet_corporate_actions::write_corporate_actions_dataset`] into contract -//! [`CorporateActionsParquetRow`]s. -//! -//! # Contract & Point-in-Time Rules -//! - Calls [`build_corporate_actions`] unchanged (drops `ratio == 1.0` split no-ops, `cash == 0.0` -//! dividends, and delistings without an outcome; keeps same-key multi-dividends separate; clamps -//! late declarations to `ex_date` with `KnownAtSource::ExDateFallback`). -//! - Resolves each built row's `(mapping_source, key, ex_date) -> listing_id` via -//! [`ProviderMappingTable::cursor_for`] / [`crate::provider_mapping::ProviderMappingCursor::resolve`] -//! (one cursor per contiguous `key` run, since `build_corporate_actions` emits rows sorted by -//! `key` then `ex_date`). -//! - For [`CorporateActionKind::OtcDelistTransfer`] rows, Pass 6 anchors `ex_date` (and `known_at`) -//! to `effectiveDate` (the successor's first OTC trading date), which normally falls after the -//! outgoing listing's primary-venue `valid_to` (e.g. `SIVB.US` ends `2023-03-10`, `SIVBQ.US` -//! starts `2023-03-28`) and may coincide with ticker reuse. `OtcDelistTransfer` therefore requires -//! Pass 6's outgoing listing identity via [`CurateDelistingInput::from_listing_id`] (`Some(id)`): -//! curation selects the `(mapping_source, key)` range with `valid_from <= ex_date` whose -//! `listing_id == id` (so an unrelated occupant of `key` is never linked to the OTC successor), -//! and any identity-less `OtcDelistTransfer` (`from_listing_id = None`) drops into -//! `dropped_unmapped`. `successor_key` is always resolved strictly on `ex_date` to -//! `successor_listing_id`. Unmapped outgoing keys (`dropped_unmapped`), unmapped successors -//! (`dropped_unmapped_successor`), and successors that alias to the row's own `listing_id` -//! (`dropped_self_successor`) are dropped—never emitted with `successor_listing_id = None` or a -//! self-link. -//! - Stamps `known_at_micros = et_session_close_utc_micros(known_at_date)` (`16:00:00 ET` of -//! `known_at_date`, matching `bars_1d`'s conservative end-of-session convention because source -//! corporate-action records carry no intraday announcement time). Dates outside -//! `1976-01-01..=2030-12-31` drop into `dropped_known_at_out_of_range` without panicking. -//! - Re-sorts mapped rows deterministically by all 11 columns (prefix `(listing_id, ex_date, kind)`) -//! and resolves cross-`key` collisions: -//! - `Split` groups on the same `(listing_id, ex_date)` with `> 1` distinct source key and `> 1` -//! distinct `ratio` bit pattern drop the entire group (`listing_collision_dropped`). -//! - Bitwise-identical rows from multiple source keys collapse to `max_per_key` copies -//! (`listing_collision_collapsed`), preserving same-key multi-dividends (including equal-amount -//! same-day regular + special dividends) while deduplicating cross-key aliases. - -use std::borrow::Cow; -use std::cmp::Ordering; -use std::error::Error; -use std::fmt; -use std::path::Path; - -use crate::corporate_actions::{ - build_corporate_actions, CorporateActionError, CorporateActionKind, CorporateActionsStats, - DelistingOutcomeEvent, DividendActionEvent, SplitActionEvent, -}; -use crate::parquet_corporate_actions::{ - write_corporate_actions_dataset, CorporateActionsParquetRow, CorporateActionsWriteOptions, - CorporateActionsWriteStats, ParquetCorporateActionsError, -}; -use crate::provider_mapping::{MappingRange, ProviderMappingTable}; -use crate::session_close::et_session_close_utc_micros; - -/// Accounting summary produced alongside [`CurateCorporateActionsOutput::rows`]. -/// -/// Conservation invariants: -/// - `rows_in == builder.rows_out` -/// - `rows_in == rows_out + dropped_unmapped + dropped_unmapped_successor + dropped_self_successor -/// + dropped_known_at_out_of_range + listing_collision_collapsed + listing_collision_dropped` -/// - `builder` independently satisfies all [`CorporateActionsStats`] conservation invariants. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct CurateCorporateActionsStats { - pub builder: CorporateActionsStats, - pub rows_in: usize, - pub rows_out: usize, - pub listings_out: usize, - pub dropped_unmapped: usize, - pub dropped_unmapped_successor: usize, - pub dropped_self_successor: usize, - pub dropped_known_at_out_of_range: usize, - pub listing_collision_collapsed: usize, - pub listing_collision_dropped: usize, -} - -/// Output of [`curate_corporate_actions`]: contract Parquet rows sorted deterministically with -/// non-decreasing `(listing_id, ex_date, kind)` plus full stage and builder stats. -#[derive(Debug, Clone, PartialEq)] -pub struct CurateCorporateActionsOutput { - pub rows: Vec, - pub stats: CurateCorporateActionsStats, -} - -/// Typed caller errors returned by [`curate_corporate_actions`]. -/// -/// Bad single rows (unmapped keys/successors, self-successors, out-of-range `known_at_date`, and -/// cross-key collisions) are dropped and counted in [`CurateCorporateActionsStats`] rather than -/// aborting the stage. -#[derive(Debug, Clone, PartialEq)] -pub enum CurateCorporateActionsError { - /// Error propagated from [`build_corporate_actions`] (e.g. non-positive split ratio). - CorporateAction(CorporateActionError), - /// Caller-supplied `mapping_source` was empty or contained only whitespace. - EmptyMappingSource, -} - -impl fmt::Display for CurateCorporateActionsError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::CorporateAction(err) => write!(f, "{err}"), - Self::EmptyMappingSource => { - write!(f, "mapping_source must not be empty or blank") - } - } - } -} - -impl Error for CurateCorporateActionsError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::CorporateAction(err) => Some(err), - Self::EmptyMappingSource => None, - } - } -} - -impl From for CurateCorporateActionsError { - fn from(err: CorporateActionError) -> Self { - Self::CorporateAction(err) - } -} - -/// Combined stats returned by [`curate_and_write_corporate_actions`]. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct CurateCorporateActionsWriteReport { - pub curate_stats: CurateCorporateActionsStats, - pub write_stats: CorporateActionsWriteStats, -} - -/// Typed error returned by [`curate_and_write_corporate_actions`]. -#[derive(Debug)] -pub enum CurateCorporateActionsWriteError { - Curate(CurateCorporateActionsError), - Parquet(ParquetCorporateActionsError), -} - -impl fmt::Display for CurateCorporateActionsWriteError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Curate(err) => write!(f, "corporate_actions curation failed: {err}"), - Self::Parquet(err) => write!(f, "corporate_actions Parquet write failed: {err}"), - } - } -} - -impl Error for CurateCorporateActionsWriteError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::Curate(err) => Some(err), - Self::Parquet(err) => Some(err), - } - } -} - -impl From for CurateCorporateActionsWriteError { - fn from(err: CurateCorporateActionsError) -> Self { - Self::Curate(err) - } -} - -impl From for CurateCorporateActionsWriteError { - fn from(err: ParquetCorporateActionsError) -> Self { - Self::Parquet(err) - } -} - -/// Input delisting item for [`curate_corporate_actions`], pairing a source key and -/// [`DelistingOutcomeEvent`] with Pass 6's optional outgoing `listing_id` (`from_listing_id` in -/// `corporate_action_continuity`). -/// -/// Implements `From<(K, DelistingOutcomeEvent)>` (with `from_listing_id = None`) for terminal -/// delisting callers; `OtcDelistTransfer` rows require `from_listing_id = Some(id)` (via -/// [`CurateDelistingInput::with_from_listing_id`]) so ended or reused outgoing tickers are never -/// attached to an unrelated occupant—identity-less OTC transfers drop into `dropped_unmapped`. -#[derive(Debug, Clone, PartialEq)] -pub struct CurateDelistingInput { - pub key: K, - pub event: DelistingOutcomeEvent, - pub from_listing_id: Option, -} - -impl CurateDelistingInput { - /// Creates a delisting input without an explicit Pass 6 outgoing `listing_id`. - #[inline] - pub fn new(key: K, event: DelistingOutcomeEvent) -> Self { - Self { - key, - event, - from_listing_id: None, - } - } - - /// Creates a delisting input carrying Pass 6's outgoing `from_listing_id`. - #[inline] - pub fn with_from_listing_id( - key: K, - from_listing_id: i32, - event: DelistingOutcomeEvent, - ) -> Self { - Self { - key, - event, - from_listing_id: Some(from_listing_id), - } - } -} - -impl From<(K, DelistingOutcomeEvent)> for CurateDelistingInput { - #[inline] - fn from((key, event): (K, DelistingOutcomeEvent)) -> Self { - Self::new(key, event) - } -} - -#[derive(Debug, Clone)] -struct DelistingIdentity { - key: K, - ex_date: i32, - kind: CorporateActionKind, - successor_key: Option, - terminal_return_bits: Option, - from_listing_id: Option, -} - -#[inline] -fn cmp_delisting_identity(a: &DelistingIdentity, b: &DelistingIdentity) -> Ordering { - a.key - .cmp(&b.key) - .then_with(|| a.ex_date.cmp(&b.ex_date)) - .then_with(|| a.kind.cmp(&b.kind)) - .then_with(|| a.successor_key.cmp(&b.successor_key)) - .then_with(|| a.terminal_return_bits.cmp(&b.terminal_return_bits)) - .then_with(|| a.from_listing_id.cmp(&b.from_listing_id)) -} - -#[inline] -fn resolve_for_listing_on_or_before( - ranges: &[MappingRange], - date: i32, - expected_listing_id: i32, -) -> Option { - let end = ranges.partition_point(|r| r.valid_from <= date); - ranges[..end] - .iter() - .rev() - .find(|r| r.listing_id == expected_listing_id) - .map(|r| r.listing_id) -} - -#[inline] -fn opt_f64_bits(value: Option) -> Option { - value.map(f64::to_bits) -} - -#[inline] -fn intern_currency(currency: Option) -> Option> { - currency.map(|c| match c.as_str() { - "USD" => Cow::Borrowed("USD"), - "CAD" => Cow::Borrowed("CAD"), - _ => Cow::Owned(c), - }) -} - -#[inline] -fn cmp_parquet_row(a: &CorporateActionsParquetRow, b: &CorporateActionsParquetRow) -> Ordering { - a.listing_id - .cmp(&b.listing_id) - .then_with(|| a.ex_date.cmp(&b.ex_date)) - .then_with(|| a.kind.cmp(&b.kind)) - .then_with(|| a.declared_date.cmp(&b.declared_date)) - .then_with(|| opt_f64_bits(a.ratio).cmp(&opt_f64_bits(b.ratio))) - .then_with(|| opt_f64_bits(a.cash_amount).cmp(&opt_f64_bits(b.cash_amount))) - .then_with(|| a.currency.as_deref().cmp(&b.currency.as_deref())) - .then_with(|| a.successor_listing_id.cmp(&b.successor_listing_id)) - .then_with(|| opt_f64_bits(a.terminal_return).cmp(&opt_f64_bits(b.terminal_return))) - .then_with(|| a.known_at_micros.cmp(&b.known_at_micros)) - .then_with(|| a.known_at_source.cmp(&b.known_at_source)) -} - -/// Pure `corporate_actions` curation stage: validates and builds source-keyed splits, dividends, -/// and delisting outcomes via [`build_corporate_actions`], resolves `(mapping_source, key, -/// ex_date) -> listing_id` (and OTC transfer `successor_key` on `ex_date`) through -/// `provider_mapping`, stamps `known_at_micros = et_session_close_utc_micros(known_at_date)`, -/// compacts cross-key collisions, and emits contract [`CorporateActionsParquetRow`]s sorted -/// deterministically with non-decreasing `(listing_id, ex_date, kind)`. -pub fn curate_corporate_actions( - splits: S, - dividends: D, - delistings: L, - mapping_source: &str, - mapping: &ProviderMappingTable, -) -> Result -where - K: Ord + Clone + AsRef, - S: IntoIterator, - D: IntoIterator, - L: IntoIterator, - I: Into>, -{ - if mapping_source.trim().is_empty() { - return Err(CurateCorporateActionsError::EmptyMappingSource); - } - - let delistings_iter = delistings.into_iter(); - let delistings_hint = delistings_iter.size_hint().0; - let mut delistings_for_builder: Vec<(K, DelistingOutcomeEvent)> = - Vec::with_capacity(delistings_hint); - let mut delisting_identities: Vec> = Vec::with_capacity(delistings_hint); - - for raw in delistings_iter { - let item = raw.into(); - match (&item.event.successor_key, item.event.terminal_return) { - (Some(succ), None) => { - delisting_identities.push(DelistingIdentity { - key: item.key.clone(), - ex_date: item.event.delist_date, - kind: CorporateActionKind::OtcDelistTransfer, - successor_key: Some(succ.clone()), - terminal_return_bits: None, - from_listing_id: item.from_listing_id, - }); - } - (None, Some(raw_return)) => { - let norm = if raw_return == 0.0 { 0.0 } else { raw_return }; - delisting_identities.push(DelistingIdentity { - key: item.key.clone(), - ex_date: item.event.delist_date, - kind: CorporateActionKind::Delisting, - successor_key: None, - terminal_return_bits: Some(norm.to_bits()), - from_listing_id: item.from_listing_id, - }); - } - _ => {} - } - delistings_for_builder.push((item.key, item.event)); - } - - let built = build_corporate_actions(splits, dividends, delistings_for_builder)?; - delisting_identities.sort_unstable_by(cmp_delisting_identity); - let mut delisting_id_idx = 0usize; - - let mut stats = CurateCorporateActionsStats { - builder: built.stats, - rows_in: built.rows.len(), - ..CurateCorporateActionsStats::default() - }; - - let mut tagged: Vec<(CorporateActionsParquetRow, usize)> = Vec::with_capacity(built.rows.len()); - - let mut current_key: Option = None; - let mut key_run_id: usize = 0; - let mut cursor = mapping.cursor_for(mapping_source, ""); - - for row in built.rows { - let from_listing_id = match row.kind { - CorporateActionKind::OtcDelistTransfer | CorporateActionKind::Delisting => { - let ident = &delisting_identities[delisting_id_idx]; - debug_assert!(ident.key == row.key); - debug_assert_eq!(ident.ex_date, row.ex_date); - debug_assert_eq!(ident.kind, row.kind); - debug_assert!(ident.successor_key == row.successor_key); - debug_assert_eq!(ident.terminal_return_bits, opt_f64_bits(row.terminal_return)); - delisting_id_idx += 1; - ident.from_listing_id - } - CorporateActionKind::Split | CorporateActionKind::Dividend => None, - }; - - let key_changed = match ¤t_key { - Some(prev) => *prev != row.key, - None => true, - }; - if key_changed { - if current_key.is_some() { - key_run_id += 1; - } - cursor = mapping.cursor_for(mapping_source, row.key.as_ref()); - current_key = Some(row.key); - } - - // Strict drop priority: - // 1. Primary listing lookup -> dropped_unmapped. - // For `OtcDelistTransfer`, Pass 6 anchors `ex_date` to the successor's first OTC - // trading date (`effectiveDate`), after the outgoing listing's primary-venue mapping - // has typically ended (e.g. SIVB.US ends 2023-03-10, SIVBQ.US starts 2023-03-28) and - // possibly after ticker reuse. `OtcDelistTransfer` therefore requires Pass 6's - // `from_listing_id = Some(id)` (selecting only a range with `valid_from <= ex_date` - // matching `id`); identity-less OTC transfers (`None`) always drop into - // `dropped_unmapped` so they can never attach to an unrelated replacement occupant. - if cursor.ranges().is_empty() { - stats.dropped_unmapped += 1; - continue; - } - let primary_listing_id = match (row.kind, from_listing_id) { - (CorporateActionKind::OtcDelistTransfer, Some(expected_id)) => { - resolve_for_listing_on_or_before(cursor.ranges(), row.ex_date, expected_id) - } - (CorporateActionKind::OtcDelistTransfer, None) => None, - (CorporateActionKind::Delisting, Some(expected_id)) => { - cursor.resolve(row.ex_date).filter(|&id| id == expected_id) - } - _ => cursor.resolve(row.ex_date), - }; - let Some(listing_id) = primary_listing_id else { - stats.dropped_unmapped += 1; - continue; - }; - - // 2. For otc_delist_transfer, resolve successor_key on ex_date (Pass 6 effectiveDate) - let successor_listing_id = if row.kind == CorporateActionKind::OtcDelistTransfer { - let Some(ref succ_key) = row.successor_key else { - stats.dropped_unmapped_successor += 1; - continue; - }; - let Some(succ_id) = mapping.resolve(mapping_source, succ_key.as_ref(), row.ex_date) - else { - stats.dropped_unmapped_successor += 1; - continue; - }; - if succ_id == listing_id { - stats.dropped_self_successor += 1; - continue; - } - Some(succ_id) - } else { - None - }; - - // 3. Convert known_at_date to 16:00:00 ET UTC microseconds - let Ok(known_at_micros) = et_session_close_utc_micros(row.known_at_date) else { - stats.dropped_known_at_out_of_range += 1; - continue; - }; - - tagged.push(( - CorporateActionsParquetRow { - listing_id, - ex_date: row.ex_date, - declared_date: row.declared_date, - kind: row.kind, - ratio: row.ratio, - cash_amount: row.cash_amount, - currency: intern_currency(row.currency), - successor_listing_id, - terminal_return: row.terminal_return, - known_at_micros, - known_at_source: row.known_at_source, - }, - key_run_id, - )); - } - - tagged.sort_unstable_by(|a, b| cmp_parquet_row(&a.0, &b.0).then_with(|| a.1.cmp(&b.1))); - - let mut write_idx = 0usize; - let mut read_idx = 0usize; - let total_mapped = tagged.len(); - let mut last_listing_id: Option = None; - - while read_idx < total_mapped { - let listing_id = tagged[read_idx].0.listing_id; - let ex_date = tagged[read_idx].0.ex_date; - let kind = tagged[read_idx].0.kind; - - let mut group_end = read_idx + 1; - while group_end < total_mapped - && tagged[group_end].0.listing_id == listing_id - && tagged[group_end].0.ex_date == ex_date - && tagged[group_end].0.kind == kind - { - group_end += 1; - } - let group_len = group_end - read_idx; - - // Cross-key conflicting split ratios on the same (listing_id, ex_date) drop the whole group. - if kind == CorporateActionKind::Split && group_len > 1 { - let first_key = tagged[read_idx].1; - let first_ratio = opt_f64_bits(tagged[read_idx].0.ratio); - let mut has_multi_key = false; - let mut has_multi_ratio = false; - for item in &tagged[read_idx + 1..group_end] { - if item.1 != first_key { - has_multi_key = true; - } - if opt_f64_bits(item.0.ratio) != first_ratio { - has_multi_ratio = true; - } - if has_multi_key && has_multi_ratio { - break; - } - } - if has_multi_key && has_multi_ratio { - stats.listing_collision_dropped += group_len; - read_idx = group_end; - continue; - } - } - - // Compact contiguous runs of bitwise-identical rows: keep `max_per_key` copies so - // same-key multi-dividends (including equal-amount regular + special) stay separate while - // cross-key alias duplicates collapse cleanly. - let mut run_start = read_idx; - while run_start < group_end { - let mut run_end = run_start + 1; - while run_end < group_end - && cmp_parquet_row(&tagged[run_start].0, &tagged[run_end].0) == Ordering::Equal - { - run_end += 1; - } - let run_len = run_end - run_start; - - let keep_count = if run_len == 1 { - 1 - } else { - let mut max_per_key = 0usize; - let mut cur_key = tagged[run_start].1; - let mut cur_count = 1usize; - for item in &tagged[run_start + 1..run_end] { - if item.1 == cur_key { - cur_count += 1; - } else { - if cur_count > max_per_key { - max_per_key = cur_count; - } - cur_key = item.1; - cur_count = 1; - } - } - if cur_count > max_per_key { - max_per_key = cur_count; - } - max_per_key - }; - - stats.listing_collision_collapsed += run_len - keep_count; - - for offset in 0..keep_count { - let src_idx = run_start + offset; - if write_idx != src_idx { - tagged.swap(write_idx, src_idx); - } - write_idx += 1; - } - - if last_listing_id != Some(listing_id) { - stats.listings_out += 1; - last_listing_id = Some(listing_id); - } - - run_start = run_end; - } - - read_idx = group_end; - } - - tagged.truncate(write_idx); - let rows: Vec = tagged.into_iter().map(|(row, _)| row).collect(); - stats.rows_out = rows.len(); - - Ok(CurateCorporateActionsOutput { rows, stats }) -} - -/// Thin end-to-end wrapper running [`curate_corporate_actions`] and publishing the resulting -/// contract rows via [`write_corporate_actions_dataset`] to -/// `/corporate_actions/part.parquet`. -/// -/// Any [`CurateCorporateActionsError`] returns before [`write_corporate_actions_dataset`] is -/// invoked, leaving `out_dir` untouched. -pub fn curate_and_write_corporate_actions( - out_dir: P, - splits: S, - dividends: D, - delistings: L, - mapping_source: &str, - mapping: &ProviderMappingTable, - options: CorporateActionsWriteOptions, -) -> Result -where - P: AsRef, - K: Ord + Clone + AsRef, - S: IntoIterator, - D: IntoIterator, - L: IntoIterator, - I: Into>, -{ - let curated = curate_corporate_actions(splits, dividends, delistings, mapping_source, mapping)?; - let write_stats = write_corporate_actions_dataset(out_dir, &curated.rows, options)?; - Ok(CurateCorporateActionsWriteReport { - curate_stats: curated.stats, - write_stats, - }) -} - -#[cfg(test)] -#[path = "curate_corporate_actions_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/curate_corporate_actions_tests.rs b/tools/curate-etl/src/curate_corporate_actions_tests.rs deleted file mode 100644 index ea9aca5e..00000000 --- a/tools/curate-etl/src/curate_corporate_actions_tests.rs +++ /dev/null @@ -1,1658 +0,0 @@ -use std::error::Error; -use std::fs::{self, File}; -use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; - -use parquet::basic::{Compression, ConvertedType, LogicalType, Repetition, TimeUnit, Type as PhysicalType}; -use parquet::file::reader::{FileReader, SerializedFileReader}; -use parquet::schema::types::Type; - -use super::*; -use crate::corporate_actions::KnownAtSource; -use crate::parquet_corporate_actions::tests::{ - assert_no_transient_files, assert_row_bitwise_eq, read_parquet_rows, -}; -use crate::provider_mapping::ProviderMappingRow; -use crate::split::ymd_to_epoch_days; - -static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0); - -struct TempDirGuard { - path: PathBuf, -} - -impl TempDirGuard { - fn new(label: &str) -> Self { - let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); - let pid = std::process::id(); - let path = std::env::temp_dir().join(format!( - "curate-etl-curate-corp-actions-{label}-{pid}-{seq}" - )); - let _ = fs::remove_dir_all(&path); - fs::create_dir_all(&path).expect("create test temp dir"); - Self { path } - } - - fn path(&self) -> &Path { - &self.path - } -} - -impl Drop for TempDirGuard { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.path); - } -} - -fn day(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).expect("valid date") -} - -fn map_row( - source: &str, - source_id: &str, - valid_from: i32, - valid_to: Option, - listing_id: i32, -) -> ProviderMappingRow { - ProviderMappingRow { - source: source.to_string(), - source_id: source_id.to_string(), - valid_from, - valid_to, - listing_id, - } -} - -fn split_ev(key: &str, ex_date: i32, ratio: f64, declared_date: Option) -> (String, SplitActionEvent) { - ( - key.to_string(), - SplitActionEvent { - ex_date, - ratio, - declared_date, - }, - ) -} - -fn div_ev( - key: &str, - ex_date: i32, - cash: f64, - currency: &str, - declared_date: Option, -) -> (String, DividendActionEvent) { - ( - key.to_string(), - DividendActionEvent { - ex_date, - cash, - currency: currency.to_string(), - declared_date, - }, - ) -} - -fn otc_ev(key: &str, delist_date: i32, successor_key: &str) -> CurateDelistingInput { - CurateDelistingInput::new( - key.to_string(), - DelistingOutcomeEvent { - delist_date, - successor_key: Some(successor_key.to_string()), - terminal_return: None, - }, - ) -} - -fn otc_ev_from( - key: &str, - from_listing_id: i32, - delist_date: i32, - successor_key: &str, -) -> CurateDelistingInput { - CurateDelistingInput::with_from_listing_id( - key.to_string(), - from_listing_id, - DelistingOutcomeEvent { - delist_date, - successor_key: Some(successor_key.to_string()), - terminal_return: None, - }, - ) -} - -fn term_ev(key: &str, delist_date: i32, terminal_return: f64) -> CurateDelistingInput { - CurateDelistingInput::new( - key.to_string(), - DelistingOutcomeEvent { - delist_date, - successor_key: None, - terminal_return: Some(terminal_return), - }, - ) -} - -fn term_ev_from( - key: &str, - from_listing_id: i32, - delist_date: i32, - terminal_return: f64, -) -> CurateDelistingInput { - CurateDelistingInput::with_from_listing_id( - key.to_string(), - from_listing_id, - DelistingOutcomeEvent { - delist_date, - successor_key: None, - terminal_return: Some(terminal_return), - }, - ) -} - -fn no_outcome_ev(key: &str, delist_date: i32) -> CurateDelistingInput { - CurateDelistingInput::new( - key.to_string(), - DelistingOutcomeEvent { - delist_date, - successor_key: None, - terminal_return: None, - }, - ) -} - -fn empty_splits() -> Vec<(String, SplitActionEvent)> { - Vec::new() -} - -fn empty_divs() -> Vec<(String, DividendActionEvent)> { - Vec::new() -} - -fn empty_delistings() -> Vec<(String, DelistingOutcomeEvent)> { - Vec::new() -} - -fn assert_conservation_and_order(out: &CurateCorporateActionsOutput) { - let s = &out.stats; - assert_eq!( - s.rows_in, s.builder.rows_out, - "rows_in != builder.rows_out: {s:?}" - ); - assert_eq!(s.rows_out, out.rows.len(), "rows_out != rows.len(): {s:?}"); - assert_eq!( - s.rows_in, - s.rows_out - + s.dropped_unmapped - + s.dropped_unmapped_successor - + s.dropped_self_successor - + s.dropped_known_at_out_of_range - + s.listing_collision_collapsed - + s.listing_collision_dropped, - "curate accounting conservation mismatch: {s:?}" - ); - assert_eq!( - s.builder.splits_in, - s.builder.splits_out + s.builder.split_noops_dropped - ); - assert_eq!( - s.builder.dividends_in, - s.builder.dividends_out + s.builder.dividend_zero_cash_dropped - ); - assert_eq!( - s.builder.delistings_in, - s.builder.otc_delist_transfers_out - + s.builder.delistings_out - + s.builder.delist_without_outcome - ); - assert_eq!( - s.builder.rows_out, - s.builder.splits_out - + s.builder.dividends_out - + s.builder.otc_delist_transfers_out - + s.builder.delistings_out - ); - assert_eq!( - s.builder.rows_out, - s.builder.known_at_declared_date - + s.builder.known_at_ex_date_fallback - + s.builder.known_at_delist_date - ); - - let mut distinct_listings = 0usize; - let mut prev_listing: Option = None; - for row in &out.rows { - if row.kind == CorporateActionKind::OtcDelistTransfer { - let succ = row - .successor_listing_id - .expect("otc_delist_transfer must never emit successor_listing_id = None"); - assert_ne!( - succ, row.listing_id, - "otc_delist_transfer must never emit self-successor" - ); - } - if prev_listing != Some(row.listing_id) { - distinct_listings += 1; - prev_listing = Some(row.listing_id); - } - } - assert_eq!(s.listings_out, distinct_listings); - - for pair in out.rows.windows(2) { - assert!( - (pair[0].listing_id, pair[0].ex_date, pair[0].kind) - <= (pair[1].listing_id, pair[1].ex_date, pair[1].kind), - "output must be non-decreasing by (listing_id, ex_date, kind): {:?} > {:?}", - (pair[0].listing_id, pair[0].ex_date, pair[0].kind), - (pair[1].listing_id, pair[1].ex_date, pair[1].kind), - ); - assert!( - cmp_parquet_row(&pair[0], &pair[1]) != Ordering::Greater, - "output must be non-decreasing by full 11-column comparator" - ); - } -} - -fn assert_contract_schema(schema: &Type) { - assert_eq!(schema.name(), "corporate_actions"); - let fields = schema.get_fields(); - assert_eq!(fields.len(), 11); - - let expected: [( - &str, - PhysicalType, - Repetition, - Option, - ConvertedType, - ); 11] = [ - ("listing_id", PhysicalType::INT32, Repetition::REQUIRED, None, ConvertedType::NONE), - ("ex_date", PhysicalType::INT32, Repetition::REQUIRED, Some(LogicalType::Date), ConvertedType::DATE), - ("declared_date", PhysicalType::INT32, Repetition::OPTIONAL, Some(LogicalType::Date), ConvertedType::DATE), - ("kind", PhysicalType::BYTE_ARRAY, Repetition::REQUIRED, Some(LogicalType::String), ConvertedType::UTF8), - ("ratio", PhysicalType::DOUBLE, Repetition::OPTIONAL, None, ConvertedType::NONE), - ("cash_amount", PhysicalType::DOUBLE, Repetition::OPTIONAL, None, ConvertedType::NONE), - ("currency", PhysicalType::BYTE_ARRAY, Repetition::OPTIONAL, Some(LogicalType::String), ConvertedType::UTF8), - ("successor_listing_id", PhysicalType::INT32, Repetition::OPTIONAL, None, ConvertedType::NONE), - ("terminal_return", PhysicalType::DOUBLE, Repetition::OPTIONAL, None, ConvertedType::NONE), - ("known_at", PhysicalType::INT64, Repetition::REQUIRED, Some(LogicalType::timestamp(true, TimeUnit::MICROS)), ConvertedType::TIMESTAMP_MICROS), - ("known_at_source", PhysicalType::BYTE_ARRAY, Repetition::REQUIRED, Some(LogicalType::String), ConvertedType::UTF8), - ]; - - for (idx, (name, phys, rep, logical, converted)) in expected.into_iter().enumerate() { - let f = &fields[idx]; - assert_eq!(f.name(), name, "field {idx} name"); - assert_eq!(f.get_physical_type(), phys, "field {name} physical type"); - assert_eq!(f.get_basic_info().repetition(), rep, "field {name} repetition"); - assert_eq!( - f.get_basic_info().logical_type_ref().cloned(), - logical, - "field {name} logical type" - ); - assert_eq!( - f.get_basic_info().converted_type(), - converted, - "field {name} converted type" - ); - } -} - -fn read_and_verify_curated_parquet(path: &Path) -> (usize, Vec) { - let file = File::open(path).expect("open parquet file"); - let reader = SerializedFileReader::new(file).expect("open parquet reader"); - let metadata = reader.metadata(); - assert_contract_schema(metadata.file_metadata().schema()); - - for rg in metadata.row_groups() { - for col in rg.columns() { - assert!( - matches!(col.compression(), Compression::ZSTD(_)), - "column {} expected ZSTD, got {:?}", - col.column_path(), - col.compression() - ); - } - } - - let footer_rows = metadata.file_metadata().num_rows() as usize; - let out = read_parquet_rows(path); - (footer_rows, out) -} - -#[test] -fn happy_path_all_kinds_est_edt_known_at_and_sources() { - let d_est_decl = day(2024, 1, 10); // EST -> 21:00 UTC - let d_est_ex = day(2024, 1, 25); // EST -> 21:00 UTC - let d_edt_ex = day(2024, 6, 10); // EDT -> 20:00 UTC - let d_sivb_halt = day(2023, 3, 10); // Last Nasdaq print before halt - let d_sivb_otc = day(2023, 3, 28); // EDT -> 20:00 UTC (Pass 6 effectiveDate) - let d_term_est = day(2024, 2, 15); // EST -> 21:00 UTC - let d_term_edt = day(2024, 7, 15); // EDT -> 20:00 UTC - - let mapping = ProviderMappingTable::from_rows([ - map_row("qm", "NVDA", day(2000, 1, 1), None, 10), - map_row("qm", "RY.TO", day(2000, 1, 1), None, 20), - map_row("qm", "SIVB", day(1987, 10, 26), Some(d_sivb_halt), 30), - map_row("qm", "SIVBQ", d_sivb_otc, Some(day(2024, 11, 7)), 31), - map_row("qm", "FAIL1", day(2000, 1, 1), Some(d_term_est), 40), - map_row("qm", "FAIL2", day(2000, 1, 1), Some(d_term_edt), 50), - ]) - .unwrap(); - - let splits = vec![ - // EST declared_date -> DeclaredDate - split_ev("NVDA", d_est_ex, 10.0, Some(d_est_decl)), - // EDT missing declared_date -> ExDateFallback - split_ev("NVDA", d_edt_ex, 0.05, None), - // 1:1 no-op dropped by builder - split_ev("NVDA", d_edt_ex, 1.0, Some(d_est_decl)), - ]; - let dividends = vec![ - // USD dividend with EST declared_date - div_ev("NVDA", d_est_ex, 0.04, "USD", Some(d_est_decl)), - // CAD dividend with late declared_date (> ex_date) -> ExDateFallback on EDT ex_date - div_ev("RY.TO", d_edt_ex, 1.42, "CAD", Some(d_edt_ex + 5)), - // Zero cash dropped by builder - div_ev("RY.TO", d_edt_ex, 0.0, "CAD", None), - ]; - let delistings = vec![ - // SIVB (listing_id=30, ended Mar 10) -> SIVBQ (31) OTC delist transfer on EDT date -> DelistDate - otc_ev_from("SIVB", 30, d_sivb_otc, "SIVBQ"), - // Terminal delisting -0.3 on EST date -> DelistDate - term_ev("FAIL1", d_term_est, -0.3), - // Terminal delisting -1.0 on EDT date -> DelistDate - term_ev("FAIL2", d_term_edt, -1.0), - // No outcome dropped by builder - no_outcome_ev("FAIL2", d_term_est), - ]; - - let out = curate_corporate_actions(splits, dividends, delistings, "qm", &mapping).unwrap(); - assert_conservation_and_order(&out); - - assert_eq!(out.stats.builder.splits_in, 3); - assert_eq!(out.stats.builder.split_noops_dropped, 1); - assert_eq!(out.stats.builder.dividends_in, 3); - assert_eq!(out.stats.builder.dividend_zero_cash_dropped, 1); - assert_eq!(out.stats.builder.delistings_in, 4); - assert_eq!(out.stats.builder.delist_without_outcome, 1); - assert_eq!(out.stats.rows_in, 7); - assert_eq!(out.stats.rows_out, 7); - assert_eq!(out.stats.listings_out, 5); - assert_eq!(out.stats.dropped_unmapped, 0); - assert_eq!(out.stats.dropped_unmapped_successor, 0); - assert_eq!(out.stats.dropped_self_successor, 0); - assert_eq!(out.stats.dropped_known_at_out_of_range, 0); - assert_eq!(out.stats.listing_collision_collapsed, 0); - assert_eq!(out.stats.listing_collision_dropped, 0); - - // Row 0: NVDA (10) Split on d_est_ex, known_at = d_est_decl (EST = 21:00 UTC) - let r0 = &out.rows[0]; - assert_eq!(r0.listing_id, 10); - assert_eq!(r0.ex_date, d_est_ex); - assert_eq!(r0.declared_date, Some(d_est_decl)); - assert_eq!(r0.kind, CorporateActionKind::Split); - assert_eq!(r0.ratio.map(f64::to_bits), Some(10.0f64.to_bits())); - assert_eq!(r0.cash_amount, None); - assert_eq!(r0.currency, None); - assert_eq!(r0.successor_listing_id, None); - assert_eq!(r0.terminal_return, None); - assert_eq!(r0.known_at_micros, et_session_close_utc_micros(d_est_decl).unwrap()); - assert_eq!(r0.known_at_source, KnownAtSource::DeclaredDate); - - // Row 1: NVDA (10) Dividend on d_est_ex (Split < Dividend) - let r1 = &out.rows[1]; - assert_eq!(r1.listing_id, 10); - assert_eq!(r1.ex_date, d_est_ex); - assert_eq!(r1.kind, CorporateActionKind::Dividend); - assert_eq!(r1.cash_amount.map(f64::to_bits), Some(0.04f64.to_bits())); - assert_eq!(r1.currency.as_deref(), Some("USD")); - assert_eq!(r1.known_at_micros, et_session_close_utc_micros(d_est_decl).unwrap()); - assert_eq!(r1.known_at_source, KnownAtSource::DeclaredDate); - - // Row 2: NVDA (10) Reverse split on d_edt_ex, known_at = d_edt_ex (EDT = 20:00 UTC) - let r2 = &out.rows[2]; - assert_eq!(r2.listing_id, 10); - assert_eq!(r2.ex_date, d_edt_ex); - assert_eq!(r2.declared_date, None); - assert_eq!(r2.kind, CorporateActionKind::Split); - assert_eq!(r2.ratio.map(f64::to_bits), Some(0.05f64.to_bits())); - assert_eq!(r2.known_at_micros, et_session_close_utc_micros(d_edt_ex).unwrap()); - assert_eq!(r2.known_at_source, KnownAtSource::ExDateFallback); - - // Row 3: RY.TO (20) CAD Dividend with late declared_date preserved, known_at = d_edt_ex - let r3 = &out.rows[3]; - assert_eq!(r3.listing_id, 20); - assert_eq!(r3.ex_date, d_edt_ex); - assert_eq!(r3.declared_date, Some(d_edt_ex + 5)); - assert_eq!(r3.kind, CorporateActionKind::Dividend); - assert_eq!(r3.cash_amount.map(f64::to_bits), Some(1.42f64.to_bits())); - assert_eq!(r3.currency.as_deref(), Some("CAD")); - assert_eq!(r3.known_at_micros, et_session_close_utc_micros(d_edt_ex).unwrap()); - assert_eq!(r3.known_at_source, KnownAtSource::ExDateFallback); - - // Row 4: SIVB (30) -> SIVBQ (31) OTC delist transfer - let r4 = &out.rows[4]; - assert_eq!(r4.listing_id, 30); - assert_eq!(r4.ex_date, d_sivb_otc); - assert_eq!(r4.declared_date, None); - assert_eq!(r4.kind, CorporateActionKind::OtcDelistTransfer); - assert_eq!(r4.successor_listing_id, Some(31)); - assert_eq!(r4.terminal_return, None); - assert_eq!(r4.known_at_micros, et_session_close_utc_micros(d_sivb_otc).unwrap()); - assert_eq!(r4.known_at_source, KnownAtSource::DelistDate); - - // Row 5: FAIL1 (40) Terminal delisting -0.3 on EST date - let r5 = &out.rows[5]; - assert_eq!(r5.listing_id, 40); - assert_eq!(r5.ex_date, d_term_est); - assert_eq!(r5.kind, CorporateActionKind::Delisting); - assert_eq!(r5.terminal_return.map(f64::to_bits), Some((-0.3f64).to_bits())); - assert_eq!(r5.known_at_micros, et_session_close_utc_micros(d_term_est).unwrap()); - assert_eq!(r5.known_at_source, KnownAtSource::DelistDate); - - // Row 6: FAIL2 (50) Terminal delisting -1.0 on EDT date - let r6 = &out.rows[6]; - assert_eq!(r6.listing_id, 50); - assert_eq!(r6.ex_date, d_term_edt); - assert_eq!(r6.kind, CorporateActionKind::Delisting); - assert_eq!(r6.terminal_return.map(f64::to_bits), Some((-1.0f64).to_bits())); - assert_eq!(r6.known_at_micros, et_session_close_utc_micros(d_term_edt).unwrap()); - assert_eq!(r6.known_at_source, KnownAtSource::DelistDate); - - // Verify EST (21:00 UTC) vs EDT (20:00 UTC) hour offset explicitly - let est_hour = (r0.known_at_micros / 1_000_000 - i64::from(d_est_decl) * 86_400) / 3_600; - let edt_hour = (r2.known_at_micros / 1_000_000 - i64::from(d_edt_ex) * 86_400) / 3_600; - assert_eq!(est_hour, 21); - assert_eq!(edt_hour, 20); -} - -#[test] -fn point_in_time_mapping_boundaries_gaps_and_source_isolation() { - let r1_from = day(2012, 5, 18); - let r1_to = day(2022, 6, 8); - let r2_from = day(2025, 1, 2); - let r2_to = day(2025, 12, 31); - - let mapping = ProviderMappingTable::from_rows([ - map_row("qm", "FB", r1_from, Some(r1_to), 100), - map_row("qm", "FB", r2_from, Some(r2_to), 200), - // Different source must not match "qm" - map_row("eod", "FB", day(2000, 1, 1), None, 999), - ]) - .unwrap(); - - let divs = vec![ - // Before first range -> unmapped - div_ev("FB", r1_from - 1, 0.10, "USD", None), - // On r1_from -> 100 - div_ev("FB", r1_from, 0.11, "USD", None), - // On r1_to -> 100 - div_ev("FB", r1_to, 0.12, "USD", None), - // Interior gap -> unmapped - div_ev("FB", r1_to + 1, 0.13, "USD", None), - div_ev("FB", r2_from - 1, 0.14, "USD", None), - // On r2_from with declared_date in gap -> resolves by ex_date to 200 - div_ev("FB", r2_from, 0.15, "USD", Some(r2_from - 10)), - // On r2_to -> 200 - div_ev("FB", r2_to, 0.16, "USD", None), - // After last range -> unmapped - div_ev("FB", r2_to + 1, 0.17, "USD", None), - ]; - - let out = curate_corporate_actions(empty_splits(), divs, empty_delistings(), "qm", &mapping) - .unwrap(); - assert_conservation_and_order(&out); - - assert_eq!(out.stats.rows_in, 8); - assert_eq!(out.stats.rows_out, 4); - assert_eq!(out.stats.dropped_unmapped, 4); - assert_eq!(out.stats.listings_out, 2); - - let resolved: Vec<(i32, i32, f64)> = out - .rows - .iter() - .map(|r| (r.listing_id, r.ex_date, r.cash_amount.unwrap())) - .collect(); - assert_eq!( - resolved, - vec![ - (100, r1_from, 0.11), - (100, r1_to, 0.12), - (200, r2_from, 0.15), - (200, r2_to, 0.16), - ] - ); -} - -#[test] -fn drop_counters_and_priority_unmapped_successor_self_successor_and_known_at_oor() { - let d_valid = day(2024, 5, 15); - let d_pre_1976 = day(1975, 12, 31); - let d_post_2030 = day(2031, 1, 1); - let d_early_1976 = day(1976, 1, 5); - - let mapping = ProviderMappingTable::from_rows([ - map_row("qm", "GOOD", day(1970, 1, 1), None, 10), - map_row("qm", "GOOD_ALIAS", day(1970, 1, 1), None, 10), - map_row("qm", "SUCC_LATER", d_valid + 1, None, 20), - ]) - .unwrap(); - - let splits = vec![ - // 1. Unmapped key -> dropped_unmapped (also pre-1976 to prove primary mapping has priority) - split_ev("UNKNOWN", d_pre_1976, 2.0, None), - // 2. Known-at out of range: pre-1976 ex_date -> dropped_known_at_out_of_range - split_ev("GOOD", d_pre_1976, 2.0, None), - // 3. Known-at out of range: in-range ex_date (1976-01-05) but declared_date = 1975-12-31 - split_ev("GOOD", d_early_1976, 3.0, Some(d_pre_1976)), - // 4. Known-at out of range: post-2030 -> dropped_known_at_out_of_range - split_ev("GOOD", d_post_2030, 4.0, None), - // 5. Valid in-range row - split_ev("GOOD", d_valid, 2.0, Some(d_valid - 10)), - ]; - - let delistings = vec![ - // 0. Identity-less OTC transfer drops into dropped_unmapped before successor checks - otc_ev("GOOD", d_valid, "NO_SUCH_SUCC"), - // 1. Unmapped successor key (unknown) -> dropped_unmapped_successor - otc_ev_from("GOOD", 10, d_valid, "NO_SUCH_SUCC"), - // 2. Successor only mapped starting d_valid + 1 (not on ex_date = d_valid) -> dropped_unmapped_successor - otc_ev_from("GOOD", 10, d_valid, "SUCC_LATER"), - // 3. Unmapped successor + out-of-range known_at_date -> successor check precedes known_at check - otc_ev_from("GOOD", 10, d_pre_1976, "NO_SUCH_SUCC"), - // 4. Self-successor via alias key -> dropped_self_successor - otc_ev_from("GOOD", 10, d_valid, "GOOD_ALIAS"), - // 5. Self-successor via identical key + out-of-range -> self_successor precedes known_at check - otc_ev_from("GOOD", 10, d_post_2030, "GOOD"), - ]; - - let out = curate_corporate_actions(splits, empty_divs(), delistings, "qm", &mapping).unwrap(); - assert_conservation_and_order(&out); - - assert_eq!(out.stats.rows_in, 11); - assert_eq!(out.stats.rows_out, 1); - assert_eq!(out.stats.listings_out, 1); - assert_eq!(out.stats.dropped_unmapped, 2); - assert_eq!(out.stats.dropped_unmapped_successor, 3); - assert_eq!(out.stats.dropped_self_successor, 2); - assert_eq!(out.stats.dropped_known_at_out_of_range, 3); - assert_eq!(out.stats.listing_collision_collapsed, 0); - assert_eq!(out.stats.listing_collision_dropped, 0); - assert_eq!(out.rows[0].ex_date, d_valid); - assert_eq!(out.rows[0].ratio, Some(2.0)); -} - -#[test] -fn cross_key_identical_collisions_collapse_across_all_kinds() { - let d1 = day(2024, 3, 15); - let d2 = day(2024, 6, 15); - let d3 = day(2024, 9, 15); - let d4 = day(2024, 12, 15); - - let mapping = ProviderMappingTable::from_rows([ - map_row("qm", "K1", day(2020, 1, 1), None, 10), - map_row("qm", "K2", day(2020, 1, 1), None, 10), - map_row("qm", "SUCC", day(2020, 1, 1), None, 99), - ]) - .unwrap(); - - let splits = vec![ - split_ev("K1", d1, 2.0, Some(d1 - 14)), - split_ev("K2", d1, 2.0, Some(d1 - 14)), - ]; - let dividends = vec![ - div_ev("K1", d2, 0.50, "USD", Some(d2 - 14)), - div_ev("K2", d2, 0.50, "USD", Some(d2 - 14)), - ]; - let delistings = vec![ - otc_ev_from("K1", 10, d3, "SUCC"), - otc_ev_from("K2", 10, d3, "SUCC"), - term_ev("K1", d4, -0.30), - term_ev("K2", d4, -0.30), - ]; - - let out = curate_corporate_actions(splits, dividends, delistings, "qm", &mapping).unwrap(); - assert_conservation_and_order(&out); - - assert_eq!(out.stats.rows_in, 8); - assert_eq!(out.stats.rows_out, 4); - assert_eq!(out.stats.listings_out, 1); - assert_eq!(out.stats.listing_collision_collapsed, 4); - assert_eq!(out.stats.listing_collision_dropped, 0); -} - -#[test] -fn cross_key_conflicting_split_ratios_drop_entire_group_including_three_way() { - let d1 = day(2024, 4, 10); - let d2 = day(2024, 8, 10); - - let mapping = ProviderMappingTable::from_rows([ - // Listing 10: 2-way conflict (2.0 vs 3.0) — only row for listing 10, so listings_out skips 10 - map_row("qm", "A1", day(2020, 1, 1), None, 10), - map_row("qm", "A2", day(2020, 1, 1), None, 10), - // Listing 20: 3-way conflict (2.0, 2.0, 3.0) plus a valid dividend on the same date - map_row("qm", "B1", day(2020, 1, 1), None, 20), - map_row("qm", "B2", day(2020, 1, 1), None, 20), - map_row("qm", "B3", day(2020, 1, 1), None, 20), - ]) - .unwrap(); - - let splits = vec![ - split_ev("A1", d1, 2.0, None), - split_ev("A2", d1, 3.0, None), - split_ev("B1", d2, 2.0, Some(d2 - 10)), - split_ev("B2", d2, 2.0, Some(d2 - 10)), - split_ev("B3", d2, 3.0, Some(d2 - 10)), - ]; - let dividends = vec![div_ev("B1", d2, 0.75, "USD", Some(d2 - 10))]; - - let out = curate_corporate_actions(splits, dividends, empty_delistings(), "qm", &mapping) - .unwrap(); - assert_conservation_and_order(&out); - - assert_eq!(out.stats.rows_in, 6); - assert_eq!(out.stats.rows_out, 1); - assert_eq!(out.stats.listings_out, 1); // Listing 10 had all rows dropped - assert_eq!(out.stats.listing_collision_collapsed, 0); - assert_eq!(out.stats.listing_collision_dropped, 5); // 2 + 3 - assert_eq!(out.rows[0].listing_id, 20); - assert_eq!(out.rows[0].kind, CorporateActionKind::Dividend); -} - -#[test] -fn same_key_multiple_same_day_dividends_preserved_for_differing_and_equal_amounts() { - let d1 = day(2024, 11, 15); - let d2 = day(2024, 12, 15); - let mapping = ProviderMappingTable::from_rows([ - map_row("qm", "RY.TO", day(2020, 1, 1), None, 10), - map_row("qm", "RY_ALIAS", day(2020, 1, 1), None, 10), - ]) - .unwrap(); - - let dividends = vec![ - // Same key, same day, differing cash amounts -> both preserved - div_ev("RY.TO", d1, 0.25, "CAD", Some(d1 - 14)), - div_ev("RY.TO", d1, 1.42, "CAD", Some(d1 - 14)), - // Same key, same day, equal cash amounts (regular + special) -> both preserved - div_ev("RY.TO", d2, 0.50, "CAD", Some(d2 - 14)), - div_ev("RY.TO", d2, 0.50, "CAD", Some(d2 - 14)), - // Alias key carrying one copy of the d2 $0.50 dividend -> collapses into the 2 kept copies - div_ev("RY_ALIAS", d2, 0.50, "CAD", Some(d2 - 14)), - ]; - - let out = curate_corporate_actions(empty_splits(), dividends, empty_delistings(), "qm", &mapping) - .unwrap(); - assert_conservation_and_order(&out); - - assert_eq!(out.stats.rows_in, 5); - assert_eq!(out.stats.rows_out, 4); - assert_eq!(out.stats.listing_collision_collapsed, 1); - assert_eq!(out.stats.listing_collision_dropped, 0); - - let d1_cash: Vec = out - .rows - .iter() - .filter(|r| r.ex_date == d1) - .map(|r| r.cash_amount.unwrap()) - .collect(); - assert_eq!(d1_cash, vec![0.25, 1.42]); - - let d2_cash: Vec = out - .rows - .iter() - .filter(|r| r.ex_date == d2) - .map(|r| r.cash_amount.unwrap()) - .collect(); - assert_eq!(d2_cash, vec![0.50, 0.50]); -} - -#[test] -fn permutation_invariance_shuffled_and_reversed_inputs_match_bit_for_bit() { - let d1 = day(2023, 3, 15); - let d2 = day(2023, 6, 15); - let d3 = day(2024, 1, 15); - let d4 = day(2024, 9, 15); - - let mapping = ProviderMappingTable::from_rows([ - map_row("qm", "Z_KEY", day(2020, 1, 1), None, 10), - map_row("qm", "A_KEY", day(2020, 1, 1), None, 20), - map_row("qm", "A_ALIAS", day(2020, 1, 1), None, 20), - map_row("qm", "M_KEY", day(2020, 1, 1), Some(d4 - 18), 30), - map_row("qm", "M_KEY", d4 - 5, None, 39), - map_row("qm", "M_SUCC", d4, None, 31), - ]) - .unwrap(); - - let mut splits = vec![ - split_ev("Z_KEY", d2, 2.0, Some(d2 - 14)), - split_ev("A_KEY", d1, 4.0, None), - split_ev("A_ALIAS", d1, 4.0, None), - split_ev("A_KEY", d3, 2.0, None), - split_ev("A_ALIAS", d3, 3.0, None), - split_ev("UNMAPPED", d1, 5.0, None), - ]; - let mut dividends = vec![ - div_ev("Z_KEY", d2, 0.25, "USD", Some(d2 - 10)), - div_ev("Z_KEY", d2, 1.00, "USD", Some(d2 - 10)), - div_ev("A_KEY", d1, 0.40, "CAD", Some(d1 + 2)), - div_ev("A_ALIAS", d1, 0.40, "CAD", Some(d1 + 2)), - div_ev("M_KEY", d3, 0.75, "EUR", None), - ]; - let mut delistings = vec![ - otc_ev_from("M_KEY", 30, d4, "M_SUCC"), - otc_ev_from("M_KEY", 999, d4, "M_SUCC"), - term_ev("Z_KEY", d4, -0.30), - otc_ev_from("A_KEY", 20, d4, "A_ALIAS"), - ]; - - let baseline = curate_corporate_actions( - splits.clone(), - dividends.clone(), - delistings.clone(), - "qm", - &mapping, - ) - .unwrap(); - assert_conservation_and_order(&baseline); - - // Reversed order - splits.reverse(); - dividends.reverse(); - delistings.reverse(); - let reversed = curate_corporate_actions( - splits.clone(), - dividends.clone(), - delistings.clone(), - "qm", - &mapping, - ) - .unwrap(); - assert_conservation_and_order(&reversed); - assert_eq!(reversed.stats, baseline.stats); - assert_eq!(reversed.rows.len(), baseline.rows.len()); - for (a, b) in reversed.rows.iter().zip(&baseline.rows) { - assert_row_bitwise_eq(a, b); - } - - // Deterministic Fisher-Yates shuffles across several seeds - for seed in [1u64, 42, 0xDEAD_BEEF] { - let mut s = splits.clone(); - let mut d = dividends.clone(); - let mut l = delistings.clone(); - let mut state = seed; - let mut next = || { - state = state.wrapping_add(0x9E37_79B9_7F4A_7C15); - let mut z = state; - z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); - z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); - z ^ (z >> 31) - }; - for i in (1..s.len()).rev() { - let j = (next() % (i as u64 + 1)) as usize; - s.swap(i, j); - } - for i in (1..d.len()).rev() { - let j = (next() % (i as u64 + 1)) as usize; - d.swap(i, j); - } - for i in (1..l.len()).rev() { - let j = (next() % (i as u64 + 1)) as usize; - l.swap(i, j); - } - - let shuffled = curate_corporate_actions(s, d, l, "qm", &mapping).unwrap(); - assert_conservation_and_order(&shuffled); - assert_eq!(shuffled.stats, baseline.stats); - assert_eq!(shuffled.rows.len(), baseline.rows.len()); - for (a, b) in shuffled.rows.iter().zip(&baseline.rows) { - assert_row_bitwise_eq(a, b); - } - } -} - -#[test] -fn failure_modes_empty_mapping_source_builder_error_parquet_error_and_out_dir_safety() { - let d1 = day(2024, 6, 10); - let mapping = - ProviderMappingTable::from_rows([map_row("qm", "AAPL", day(2020, 1, 1), None, 10)]) - .unwrap(); - - // 1. Empty / whitespace mapping_source returns EmptyMappingSource even with invalid builder input - for blank in ["", " ", "\t\n"] { - let err = curate_corporate_actions( - vec![split_ev("AAPL", d1, -2.0, None)], - empty_divs(), - empty_delistings(), - blank, - &mapping, - ) - .unwrap_err(); - assert_eq!(err, CurateCorporateActionsError::EmptyMappingSource); - assert!(err.source().is_none()); - assert!(err.to_string().contains("mapping_source")); - } - - // 2. Builder error propagates wrapped in CurateCorporateActionsError::CorporateAction - let err = curate_corporate_actions( - vec![split_ev("AAPL", d1, 0.0, None)], - empty_divs(), - empty_delistings(), - "qm", - &mapping, - ) - .unwrap_err(); - assert!(matches!( - err, - CurateCorporateActionsError::CorporateAction(CorporateActionError::InvalidSplitRatio { .. }) - )); - assert!(err.source().is_some()); - assert!(!err.to_string().is_empty()); - - // 3. curate_and_write_corporate_actions on curate error leaves fresh out_dir untouched - let tmp = TempDirGuard::new("error-safety"); - let fresh = tmp.path().join("fresh"); - let write_err = curate_and_write_corporate_actions( - &fresh, - vec![split_ev("AAPL", d1, -1.0, None)], - empty_divs(), - empty_delistings(), - "qm", - &mapping, - CorporateActionsWriteOptions::default(), - ) - .unwrap_err(); - assert!(matches!( - write_err, - CurateCorporateActionsWriteError::Curate(CurateCorporateActionsError::CorporateAction(_)) - )); - assert!(write_err.source().is_some()); - assert!(write_err.to_string().contains("curation failed")); - assert!( - !fresh.exists(), - "curate error must not create out_dir or corporate_actions/" - ); - - // 4. Pre-existing corporate_actions/part.parquet stays byte-identical on curate error - let seeded = tmp.path().join("seeded"); - curate_and_write_corporate_actions( - &seeded, - vec![split_ev("AAPL", d1, 2.0, Some(d1 - 10))], - empty_divs(), - empty_delistings(), - "qm", - &mapping, - CorporateActionsWriteOptions::default(), - ) - .unwrap(); - let part_path = seeded.join("corporate_actions/part.parquet"); - let bytes_before = fs::read(&part_path).unwrap(); - - let empty_src_err = curate_and_write_corporate_actions( - &seeded, - vec![split_ev("AAPL", d1, 4.0, None)], - empty_divs(), - empty_delistings(), - " ", - &mapping, - CorporateActionsWriteOptions::default(), - ) - .unwrap_err(); - assert!(matches!( - empty_src_err, - CurateCorporateActionsWriteError::Curate(CurateCorporateActionsError::EmptyMappingSource) - )); - assert_eq!(fs::read(&part_path).unwrap(), bytes_before); - assert_no_transient_files(&seeded.join("corporate_actions")); - - // 5. ParquetCorporateActionsError propagates wrapped in CurateCorporateActionsWriteError::Parquet - let pq_err = curate_and_write_corporate_actions( - &seeded, - vec![split_ev("AAPL", d1, 2.0, None)], - empty_divs(), - empty_delistings(), - "qm", - &mapping, - CorporateActionsWriteOptions { - row_group_rows: 0, - ..CorporateActionsWriteOptions::default() - }, - ) - .unwrap_err(); - assert!(matches!( - pq_err, - CurateCorporateActionsWriteError::Parquet(ParquetCorporateActionsError::InvalidRowGroupRows) - )); - assert!(pq_err.source().is_some()); - assert!(pq_err.to_string().contains("Parquet write failed")); - assert_eq!(fs::read(&part_path).unwrap(), bytes_before); -} - -#[test] -fn parquet_round_trip_byte_identical_double_write_and_empty_input() { - let tmp = TempDirGuard::new("round-trip"); - let d1 = day(2024, 1, 15); // EST - let d2 = day(2024, 6, 10); // EDT - let d3 = day(2024, 9, 20); // EDT - let d4 = day(2024, 12, 10); // EST - - let mapping = ProviderMappingTable::from_rows([ - map_row("qm", "NVDA", day(2015, 1, 1), None, 10), - map_row("qm", "RY.TO", day(2015, 1, 1), None, 20), - map_row("qm", "SIVB", day(2015, 1, 1), Some(d3 - 18), 30), - map_row("qm", "SIVBQ", d3, None, 31), - map_row("qm", "FAIL", day(2015, 1, 1), Some(d4), 40), - ]) - .unwrap(); - - let splits = vec![ - split_ev("NVDA", d2, 10.0, Some(d2 - 19)), - split_ev("RY.TO", d1, 0.5, None), - ]; - let dividends = vec![ - div_ev("NVDA", d2, 0.04, "USD", Some(d2 - 14)), - div_ev("NVDA", d2, 0.10, "USD", None), - div_ev("RY.TO", d1, 1.42, "CAD", Some(d1 + 3)), - ]; - let delistings = vec![ - otc_ev_from("SIVB", 30, d3, "SIVBQ"), - term_ev("FAIL", d4, -0.30), - ]; - - let curated = curate_corporate_actions( - splits.clone(), - dividends.clone(), - delistings.clone(), - "qm", - &mapping, - ) - .unwrap(); - assert_conservation_and_order(&curated); - - let opts = CorporateActionsWriteOptions { - row_group_rows: 3, - ..CorporateActionsWriteOptions::default() - }; - - let dir_a = tmp.path().join("run_a"); - let dir_b = tmp.path().join("run_b"); - - let report_a = curate_and_write_corporate_actions( - &dir_a, - splits.clone(), - dividends.clone(), - delistings.clone(), - "qm", - &mapping, - opts, - ) - .unwrap(); - let report_b = curate_and_write_corporate_actions( - &dir_b, - splits, - dividends, - delistings, - "qm", - &mapping, - opts, - ) - .unwrap(); - - assert_eq!(report_a, report_b); - assert_eq!(report_a.curate_stats, curated.stats); - assert_eq!(report_a.write_stats.rows_written, curated.rows.len()); - assert_eq!(report_a.write_stats.files_written, 1); - assert_eq!(report_a.write_stats.row_groups_written, 3); // ceil(7 / 3) - assert!(report_a.write_stats.bytes_written > 0); - - let part_a = dir_a.join("corporate_actions/part.parquet"); - let part_b = dir_b.join("corporate_actions/part.parquet"); - let bytes_a = fs::read(&part_a).unwrap(); - let bytes_b = fs::read(&part_b).unwrap(); - assert_eq!(bytes_a, bytes_b, "double write must be byte-identical"); - assert_eq!(bytes_a.len() as u64, report_a.write_stats.bytes_written); - - let (footer_rows, read_back) = read_and_verify_curated_parquet(&part_a); - assert_eq!(footer_rows, curated.rows.len()); - assert_eq!(read_back.len(), curated.rows.len()); - for (actual, expected) in read_back.iter().zip(&curated.rows) { - assert_row_bitwise_eq(actual, expected); - } - assert_no_transient_files(&dir_a.join("corporate_actions")); - assert_no_transient_files(&dir_b.join("corporate_actions")); - - // Empty input writes nothing and leaves out_dir untouched - let empty_dir = tmp.path().join("empty_out"); - let empty_report = curate_and_write_corporate_actions( - &empty_dir, - empty_splits(), - empty_divs(), - empty_delistings(), - "qm", - &mapping, - CorporateActionsWriteOptions::default(), - ) - .unwrap(); - assert_eq!(empty_report.curate_stats.rows_in, 0); - assert_eq!(empty_report.curate_stats.rows_out, 0); - assert_eq!(empty_report.write_stats, CorporateActionsWriteStats::default()); - assert!(!empty_dir.exists(), "empty input must not create out_dir"); -} - -#[test] -fn otc_delist_transfer_resolves_ended_outgoing_listing_sivb_to_sivbq() { - // Mirrors the security-master persistence fixture (test/postgres/security-master-persist.test.ts): - // SIVB.US ends on 2023-03-10 (halt / last Nasdaq print), SIVBQ.US begins OTC trading on - // 2023-03-28, and Pass 6 records the continuity transfer with effectiveDate = 2023-03-28. - let d_sivb_start = day(1987, 10, 26); - let d_sivb_end = day(2023, 3, 10); - let d_sivbq_start = day(2023, 3, 28); - let d_sivbq_end = day(2024, 11, 7); - let d_reuse_start = day(2025, 1, 2); - - let mapping = ProviderMappingTable::from_rows([ - map_row("eod", "SIVB.US", d_sivb_start, Some(d_sivb_end), 30), - // Later reuse of the same ticker must not be selected for the 2023-03-28 transfer. - map_row("eod", "SIVB.US", d_reuse_start, None, 39), - map_row("eod", "SIVBQ.US", d_sivbq_start, Some(d_sivbq_end), 31), - // Successor that starts one day after effectiveDate must still fail successor lookup. - map_row("eod", "SIVBQ_LATE.US", d_sivbq_start + 1, None, 32), - ]) - .unwrap(); - - let dividends = vec![ - // Non-transfer event on SIVB.US on 2023-03-28 (after valid_to = 2023-03-10) must still drop. - div_ev("SIVB.US", d_sivbq_start, 0.25, "USD", None), - ]; - let delistings = vec![ - // Real SIVB.US (listing_id=30, ended Mar 10) -> SIVBQ.US (31, starts Mar 28) transfer. - otc_ev_from("SIVB.US", 30, d_sivbq_start, "SIVBQ.US"), - // Same transfer without Pass 6 from_listing_id must not guess an ended range -> dropped_unmapped. - otc_ev("SIVB.US", d_sivbq_start, "SIVBQ.US"), - // Transfer before outgoing valid_from (1987-10-26) -> dropped_unmapped. - otc_ev_from("SIVB.US", 30, d_sivb_start - 1, "SIVBQ.US"), - // Successor lookup remains strictly anchored to effectiveDate (Mar 28) -> dropped_unmapped_successor. - otc_ev_from("SIVB.US", 30, d_sivbq_start, "SIVBQ_LATE.US"), - ]; - - let out = curate_corporate_actions(empty_splits(), dividends, delistings, "eod", &mapping) - .unwrap(); - assert_conservation_and_order(&out); - - assert_eq!(out.stats.rows_in, 5); - assert_eq!(out.stats.rows_out, 1); - assert_eq!(out.stats.listings_out, 1); - assert_eq!(out.stats.dropped_unmapped, 3); - assert_eq!(out.stats.dropped_unmapped_successor, 1); - assert_eq!(out.stats.dropped_self_successor, 0); - assert_eq!(out.stats.dropped_known_at_out_of_range, 0); - assert_eq!(out.stats.listing_collision_collapsed, 0); - assert_eq!(out.stats.listing_collision_dropped, 0); - - let row = &out.rows[0]; - assert_eq!(row.listing_id, 30); - assert_eq!(row.successor_listing_id, Some(31)); - assert_eq!(row.kind, CorporateActionKind::OtcDelistTransfer); - assert_eq!(row.ex_date, d_sivbq_start); - assert_eq!(row.declared_date, None); - assert_eq!( - row.known_at_micros, - et_session_close_utc_micros(d_sivbq_start).unwrap() - ); - assert_eq!(row.known_at_source, KnownAtSource::DelistDate); -} - -#[test] -fn otc_delist_transfer_never_attaches_to_unrelated_ticker_occupant() { - let d_halt = day(2023, 3, 10); - let d_reuse_early = day(2023, 3, 20); // Unrelated issuer takes over ticker before OTC date - let d_otc = day(2023, 3, 28); // Pass 6 effectiveDate (18 days after halt) - - let mapping = ProviderMappingTable::from_rows([ - // Case 1: Outgoing listing 30 ended Mar 10, unrelated listing 99 reused REUSE.US on Mar 20. - map_row("eod", "REUSE.US", day(2015, 1, 1), Some(d_halt), 30), - map_row("eod", "REUSE.US", d_reuse_early, None, 99), - map_row("eod", "REUSEQ.US", d_otc, None, 31), - // Case 2: Outgoing listing 40 is missing from provider_mapping; only an older unrelated - // occupant (listing 12, ended 2018) exists for OLD_ONLY.US. - map_row("eod", "OLD_ONLY.US", day(2010, 1, 1), Some(day(2018, 12, 31)), 12), - map_row("eod", "OLD_ONLYQ.US", d_otc, None, 41), - // Case 3: Outgoing listing 50 is missing from provider_mapping; only a newer unrelated - // occupant (listing 88, active on d_otc) exists for NEW_ONLY.US. - map_row("eod", "NEW_ONLY.US", d_reuse_early, None, 88), - map_row("eod", "NEW_ONLYQ.US", d_otc, None, 51), - ]) - .unwrap(); - - // Tuple-input regression (From<(K, DelistingOutcomeEvent)> with from_listing_id = None): - // REUSE.US is actively occupied by unrelated listing 99 on d_otc (2023-03-28), so an - // identity-less tuple OTC transfer must drop into dropped_unmapped and NEVER emit 99 -> 31. - let tuple_out = curate_corporate_actions( - empty_splits(), - empty_divs(), - vec![( - "REUSE.US".to_string(), - DelistingOutcomeEvent { - delist_date: d_otc, - successor_key: Some("REUSEQ.US".to_string()), - terminal_return: None, - }, - )], - "eod", - &mapping, - ) - .unwrap(); - assert_conservation_and_order(&tuple_out); - assert_eq!(tuple_out.stats.rows_in, 1); - assert_eq!(tuple_out.stats.rows_out, 0); - assert_eq!(tuple_out.stats.listings_out, 0); - assert_eq!(tuple_out.stats.dropped_unmapped, 1); - assert!(tuple_out.rows.is_empty()); - - let delistings = vec![ - // Case 1a: Must select outgoing listing 30 (NOT unrelated new occupant 99). - otc_ev_from("REUSE.US", 30, d_otc, "REUSEQ.US"), - // Case 1b: Identity-less OTC transfer on active reused ticker -> dropped_unmapped (NOT 99). - otc_ev("REUSE.US", d_otc, "REUSEQ.US"), - // Case 2a: Outgoing listing 40 missing -> must drop, NOT attach to older occupant 12. - otc_ev_from("OLD_ONLY.US", 40, d_otc, "OLD_ONLYQ.US"), - // Case 2b: Same ticker without from_listing_id -> must drop, NOT guess older occupant 12. - otc_ev("OLD_ONLY.US", d_otc, "OLD_ONLYQ.US"), - // Case 3: Outgoing listing 50 missing -> must drop, NOT attach to active new occupant 88. - otc_ev_from("NEW_ONLY.US", 50, d_otc, "NEW_ONLYQ.US"), - // Case 4: Terminal delisting carrying wrong from_listing_id -> must drop, NOT attach to 88. - term_ev_from("NEW_ONLY.US", 50, d_otc, -1.0), - ]; - - let out = curate_corporate_actions( - empty_splits(), - empty_divs(), - delistings, - "eod", - &mapping, - ) - .unwrap(); - assert_conservation_and_order(&out); - - assert_eq!(out.stats.rows_in, 6); - assert_eq!(out.stats.rows_out, 1); - assert_eq!(out.stats.listings_out, 1); - assert_eq!(out.stats.dropped_unmapped, 5); - assert_eq!(out.stats.dropped_unmapped_successor, 0); - assert_eq!(out.stats.dropped_self_successor, 0); - - // Only the true outgoing listing 30 -> 31 transfer is emitted; no row for 12, 88, or 99. - assert_eq!(out.rows.len(), 1); - let row = &out.rows[0]; - assert_eq!(row.listing_id, 30); - assert_eq!(row.successor_listing_id, Some(31)); - assert_eq!(row.kind, CorporateActionKind::OtcDelistTransfer); - assert_eq!(row.ex_date, d_otc); - assert_eq!( - row.known_at_micros, - et_session_close_utc_micros(d_otc).unwrap() - ); - assert_eq!(row.known_at_source, KnownAtSource::DelistDate); - assert!(out - .rows - .iter() - .all(|r| r.listing_id != 12 && r.listing_id != 88 && r.listing_id != 99)); -} - -#[test] -fn same_day_delistings_on_one_key_pair_identities_in_both_orders() { - let d_halt = day(2023, 3, 10); - let d_reuse = day(2023, 3, 20); - let d_event = day(2023, 3, 28); - - let mapping = ProviderMappingTable::from_rows([ - // Shared key with two distinct listings active by d_event (10 ended, 20 active) - map_row("eod", "SHARED.US", day(2015, 1, 1), Some(d_halt), 10), - map_row("eod", "SHARED.US", d_reuse, None, 20), - map_row("eod", "SUCC_A.US", d_event, None, 101), - map_row("eod", "SUCC_B.US", d_event, None, 201), - // Separate key for same-day terminal delistings with matching vs mismatched from_listing_id - map_row("eod", "TERM.US", day(2015, 1, 1), Some(d_event), 30), - ]) - .unwrap(); - - let delistings_ab = vec![ - otc_ev_from("SHARED.US", 10, d_event, "SUCC_A.US"), - otc_ev_from("SHARED.US", 20, d_event, "SUCC_B.US"), - term_ev_from("TERM.US", 30, d_event, -0.30), - term_ev_from("TERM.US", 99, d_event, -1.00), - ]; - let mut delistings_ba = delistings_ab.clone(); - delistings_ba.reverse(); - - let out_ab = - curate_corporate_actions(empty_splits(), empty_divs(), delistings_ab, "eod", &mapping) - .unwrap(); - let out_ba = - curate_corporate_actions(empty_splits(), empty_divs(), delistings_ba, "eod", &mapping) - .unwrap(); - - assert_conservation_and_order(&out_ab); - assert_conservation_and_order(&out_ba); - assert_eq!(out_ab.stats, out_ba.stats); - assert_eq!(out_ab.rows.len(), out_ba.rows.len()); - for (a, b) in out_ab.rows.iter().zip(&out_ba.rows) { - assert_row_bitwise_eq(a, b); - } - - assert_eq!(out_ab.stats.rows_in, 4); - assert_eq!(out_ab.stats.rows_out, 3); - assert_eq!(out_ab.stats.listings_out, 3); - assert_eq!(out_ab.stats.dropped_unmapped, 1); - - // Listing 10 stays paired with SUCC_A (101), listing 20 with SUCC_B (201), listing 30 with -0.30. - assert_eq!(out_ab.rows[0].listing_id, 10); - assert_eq!(out_ab.rows[0].kind, CorporateActionKind::OtcDelistTransfer); - assert_eq!(out_ab.rows[0].successor_listing_id, Some(101)); - - assert_eq!(out_ab.rows[1].listing_id, 20); - assert_eq!(out_ab.rows[1].kind, CorporateActionKind::OtcDelistTransfer); - assert_eq!(out_ab.rows[1].successor_listing_id, Some(201)); - - assert_eq!(out_ab.rows[2].listing_id, 30); - assert_eq!(out_ab.rows[2].kind, CorporateActionKind::Delisting); - assert_eq!( - out_ab.rows[2].terminal_return.map(f64::to_bits), - Some((-0.30_f64).to_bits()) - ); -} - -#[test] -fn same_day_otc_transfer_and_terminal_delisting_on_one_key_pair_identities() { - let d_halt = day(2023, 3, 10); - let d_reuse = day(2023, 3, 20); - let d_event = day(2023, 3, 28); - - let mapping = ProviderMappingTable::from_rows([ - map_row("eod", "MIX.US", day(2015, 1, 1), Some(d_halt), 10), - map_row("eod", "MIX.US", d_reuse, Some(d_event), 20), - map_row("eod", "MIXQ.US", d_event, None, 11), - ]) - .unwrap(); - - let order_a = vec![ - otc_ev_from("MIX.US", 10, d_event, "MIXQ.US"), - term_ev_from("MIX.US", 20, d_event, -0.55), - ]; - let order_b = vec![order_a[1].clone(), order_a[0].clone()]; - - let out_a = - curate_corporate_actions(empty_splits(), empty_divs(), order_a, "eod", &mapping).unwrap(); - let out_b = - curate_corporate_actions(empty_splits(), empty_divs(), order_b, "eod", &mapping).unwrap(); - - assert_conservation_and_order(&out_a); - assert_conservation_and_order(&out_b); - assert_eq!(out_a.stats, out_b.stats); - assert_eq!(out_a.rows.len(), 2); - for (a, b) in out_a.rows.iter().zip(&out_b.rows) { - assert_row_bitwise_eq(a, b); - } - - assert_eq!(out_a.stats.rows_in, 2); - assert_eq!(out_a.stats.rows_out, 2); - assert_eq!(out_a.stats.listings_out, 2); - assert_eq!(out_a.stats.dropped_unmapped, 0); - - assert_eq!(out_a.rows[0].listing_id, 10); - assert_eq!(out_a.rows[0].kind, CorporateActionKind::OtcDelistTransfer); - assert_eq!(out_a.rows[0].successor_listing_id, Some(11)); - - assert_eq!(out_a.rows[1].listing_id, 20); - assert_eq!(out_a.rows[1].kind, CorporateActionKind::Delisting); - assert_eq!( - out_a.rows[1].terminal_return.map(f64::to_bits), - Some((-0.55_f64).to_bits()) - ); -} - -#[test] -fn otc_transfer_before_outgoing_mapping_valid_from_drops_as_unmapped() { - let d_otc = day(2023, 3, 28); - - let mapping = ProviderMappingTable::from_rows([ - // Unrelated older occupant on the same ticker must not be matched either. - map_row("eod", "EARLY.US", day(2010, 1, 1), Some(day(2020, 12, 31)), 59), - // Outgoing listing 60 only begins after ex_date (valid_from > d_otc). - map_row("eod", "EARLY.US", d_otc + 1, None, 60), - map_row("eod", "EARLYQ.US", d_otc, None, 61), - ]) - .unwrap(); - - let out = curate_corporate_actions( - empty_splits(), - empty_divs(), - vec![otc_ev_from("EARLY.US", 60, d_otc, "EARLYQ.US")], - "eod", - &mapping, - ) - .unwrap(); - assert_conservation_and_order(&out); - - assert_eq!(out.stats.rows_in, 1); - assert_eq!(out.stats.rows_out, 0); - assert_eq!(out.stats.listings_out, 0); - assert_eq!(out.stats.dropped_unmapped, 1); - assert_eq!(out.stats.dropped_unmapped_successor, 0); - assert!(out.rows.is_empty()); -} - -#[test] -fn point_in_time_post_cutoff_mutations_leave_on_or_before_cutoff_rows_bitwise_identical() { - let cutoff = day(2023, 6, 30); - let d_pre_1 = day(2023, 2, 15); - let d_pre_2 = cutoff; // exactly on cutoff - let d_post_1 = cutoff + 1; - let d_post_2 = day(2023, 10, 15); - - let base_mapping = ProviderMappingTable::from_rows([ - map_row("qm", "ALPHA", day(2015, 1, 1), Some(cutoff), 10), - map_row("qm", "ALPHA", d_post_1, None, 11), - map_row("qm", "BETA", day(2015, 1, 1), Some(d_pre_1 - 10), 20), - map_row("qm", "BETAQ", d_pre_1, None, 21), - map_row("qm", "GAMMA", day(2015, 1, 1), Some(d_post_2), 30), - ]) - .unwrap(); - - let mutated_mapping = ProviderMappingTable::from_rows([ - map_row("qm", "ALPHA", day(2015, 1, 1), Some(cutoff), 10), - // Post-cutoff range reassigned to a different listing_id - map_row("qm", "ALPHA", d_post_1, None, 111), - map_row("qm", "BETA", day(2015, 1, 1), Some(d_pre_1 - 10), 20), - map_row("qm", "BETAQ", d_pre_1, None, 21), - map_row("qm", "GAMMA", day(2015, 1, 1), Some(cutoff), 30), - map_row("qm", "GAMMA", d_post_1, Some(d_post_2), 330), - ]) - .unwrap(); - - let base_splits = vec![ - split_ev("ALPHA", d_pre_1, 2.0, Some(d_pre_1 - 14)), - split_ev("ALPHA", d_post_1, 4.0, Some(d_post_1 - 5)), - ]; - let mutated_splits = vec![ - split_ev("ALPHA", d_pre_1, 2.0, Some(d_pre_1 - 14)), - split_ev("ALPHA", d_post_1, 5.0, Some(d_post_1 - 2)), - ]; - - let base_divs = vec![ - div_ev("ALPHA", d_pre_2, 0.50, "USD", Some(d_pre_2 - 10)), - div_ev("ALPHA", d_post_2, 0.75, "USD", Some(d_post_2 - 10)), - ]; - let mutated_divs = vec![ - div_ev("ALPHA", d_pre_2, 0.50, "USD", Some(d_pre_2 - 10)), - div_ev("ALPHA", d_post_2, 1.25, "CAD", Some(d_post_2 - 7)), - ]; - - let base_delistings = vec![ - otc_ev_from("BETA", 20, d_pre_1, "BETAQ"), - term_ev("GAMMA", d_post_2, -0.30), - ]; - let mutated_delistings = vec![ - otc_ev_from("BETA", 20, d_pre_1, "BETAQ"), - term_ev("GAMMA", d_post_2, -1.00), - ]; - - let base_out = curate_corporate_actions( - base_splits, - base_divs, - base_delistings, - "qm", - &base_mapping, - ) - .unwrap(); - let mutated_out = curate_corporate_actions( - mutated_splits, - mutated_divs, - mutated_delistings, - "qm", - &mutated_mapping, - ) - .unwrap(); - - assert_conservation_and_order(&base_out); - assert_conservation_and_order(&mutated_out); - - let base_le: Vec<&CorporateActionsParquetRow> = - base_out.rows.iter().filter(|r| r.ex_date <= cutoff).collect(); - let mut_le: Vec<&CorporateActionsParquetRow> = - mutated_out.rows.iter().filter(|r| r.ex_date <= cutoff).collect(); - assert_eq!(base_le.len(), 3); - assert_eq!(base_le.len(), mut_le.len()); - for (a, b) in base_le.iter().zip(&mut_le) { - assert_row_bitwise_eq(a, b); - } - - let base_gt: Vec<&CorporateActionsParquetRow> = - base_out.rows.iter().filter(|r| r.ex_date > cutoff).collect(); - let mut_gt: Vec<&CorporateActionsParquetRow> = - mutated_out.rows.iter().filter(|r| r.ex_date > cutoff).collect(); - assert_eq!(base_gt.len(), 3); - assert_eq!(mut_gt.len(), 3); - assert_ne!(base_gt, mut_gt, "post-cutoff rows must reflect post-cutoff mutations"); - - // Verify each of the three post-cutoff mutations independently by effective date and kind. - let mut_split = mut_gt - .iter() - .find(|r| r.ex_date == d_post_1 && r.kind == CorporateActionKind::Split) - .expect("mutated post-cutoff split row"); - assert_eq!(mut_split.listing_id, 111); - assert_eq!(mut_split.ratio, Some(5.0)); - - let mut_div = mut_gt - .iter() - .find(|r| r.ex_date == d_post_2 && r.kind == CorporateActionKind::Dividend) - .expect("mutated post-cutoff dividend row"); - assert_eq!(mut_div.listing_id, 111); - assert_eq!(mut_div.cash_amount, Some(1.25)); - assert_eq!(mut_div.currency.as_deref(), Some("CAD")); - - let mut_delist = mut_gt - .iter() - .find(|r| r.ex_date == d_post_2 && r.kind == CorporateActionKind::Delisting) - .expect("mutated post-cutoff delisting row"); - assert_eq!(mut_delist.listing_id, 330); - assert_eq!(mut_delist.terminal_return, Some(-1.00)); -} - -#[test] -fn moving_mapping_boundary_onto_cutoff_changes_cutoff_day_listing_id() { - let cutoff = day(2023, 6, 30); - - let mapping_after_cutoff = ProviderMappingTable::from_rows([ - map_row("qm", "BND", day(2020, 1, 1), Some(cutoff), 100), - map_row("qm", "BND", cutoff + 1, None, 200), - ]) - .unwrap(); - - let mapping_on_cutoff = ProviderMappingTable::from_rows([ - map_row("qm", "BND", day(2020, 1, 1), Some(cutoff - 1), 100), - map_row("qm", "BND", cutoff, None, 200), - ]) - .unwrap(); - - let divs = vec![ - div_ev("BND", cutoff - 1, 0.25, "USD", None), - div_ev("BND", cutoff, 0.30, "USD", None), - div_ev("BND", cutoff + 1, 0.35, "USD", None), - ]; - - let before_out = curate_corporate_actions( - empty_splits(), - divs.clone(), - empty_delistings(), - "qm", - &mapping_after_cutoff, - ) - .unwrap(); - let after_out = curate_corporate_actions( - empty_splits(), - divs, - empty_delistings(), - "qm", - &mapping_on_cutoff, - ) - .unwrap(); - - assert_conservation_and_order(&before_out); - assert_conservation_and_order(&after_out); - - let listing_on = |out: &CurateCorporateActionsOutput, d: i32| { - out.rows - .iter() - .find(|r| r.ex_date == d) - .expect("row on date") - .listing_id - }; - - assert_eq!(listing_on(&before_out, cutoff - 1), 100); - assert_eq!(listing_on(&before_out, cutoff), 100); - assert_eq!(listing_on(&before_out, cutoff + 1), 200); - - assert_eq!(listing_on(&after_out, cutoff - 1), 100); - assert_eq!(listing_on(&after_out, cutoff), 200); - assert_eq!(listing_on(&after_out, cutoff + 1), 200); -} - -#[test] -fn negative_zero_terminal_return_normalizes_in_builder_and_is_carried_bit_exactly() { - let d_delist = day(2024, 4, 15); - let mapping = - ProviderMappingTable::from_rows([map_row("qm", "ZERO", day(2020, 1, 1), None, 70)]) - .unwrap(); - - // Confirm normalization of -0.0 -> +0.0 happens inside build_corporate_actions itself. - let built = build_corporate_actions( - empty_splits(), - empty_divs(), - vec![( - "ZERO".to_string(), - DelistingOutcomeEvent { - delist_date: d_delist, - successor_key: None, - terminal_return: Some(-0.0_f64), - }, - )], - ) - .unwrap(); - assert_eq!(built.rows.len(), 1); - let builder_bits = built.rows[0].terminal_return.unwrap().to_bits(); - assert_eq!(builder_bits, 0.0_f64.to_bits()); - assert_ne!(builder_bits, (-0.0_f64).to_bits()); - - // Curate stage carries the builder's terminal_return bits through unchanged (+0.0). - let out = curate_corporate_actions( - empty_splits(), - empty_divs(), - vec![term_ev("ZERO", d_delist, -0.0_f64)], - "qm", - &mapping, - ) - .unwrap(); - assert_conservation_and_order(&out); - assert_eq!(out.stats.rows_in, 1); - assert_eq!(out.stats.rows_out, 1); - let curated_bits = out.rows[0].terminal_return.unwrap().to_bits(); - assert_eq!(curated_bits, builder_bits); - assert_eq!(curated_bits, 0.0_f64.to_bits()); -} - -#[test] -fn non_usd_cad_currency_gbp_preserved_through_parquet_round_trip() { - let tmp = TempDirGuard::new("gbp-round-trip"); - let d_ex = day(2024, 5, 16); - let d_decl = day(2024, 4, 25); - - let mapping = - ProviderMappingTable::from_rows([map_row("qm", "ULVR.L", day(2015, 1, 1), None, 80)]) - .unwrap(); - - let divs = vec![div_ev("ULVR.L", d_ex, 0.43, "GBP", Some(d_decl))]; - - let curated = - curate_corporate_actions(empty_splits(), divs.clone(), empty_delistings(), "qm", &mapping) - .unwrap(); - assert_conservation_and_order(&curated); - assert_eq!(curated.rows.len(), 1); - assert_eq!(curated.rows[0].currency.as_deref(), Some("GBP")); - - let out_dir = tmp.path().join("gbp_out"); - let report = curate_and_write_corporate_actions( - &out_dir, - empty_splits(), - divs, - empty_delistings(), - "qm", - &mapping, - CorporateActionsWriteOptions::default(), - ) - .unwrap(); - assert_eq!(report.curate_stats, curated.stats); - assert_eq!(report.write_stats.rows_written, 1); - - let part_path = out_dir.join("corporate_actions/part.parquet"); - let read_back = read_parquet_rows(&part_path); - assert_eq!(read_back.len(), 1); - assert_row_bitwise_eq(&read_back[0], &curated.rows[0]); - assert_eq!(read_back[0].currency.as_deref(), Some("GBP")); - assert_no_transient_files(&out_dir.join("corporate_actions")); -} - -#[test] -fn collision_scope_same_key_splits_kept_and_cross_key_drop_is_day_and_kind_scoped() { - let d1 = day(2024, 4, 10); - let d2 = d1 + 1; - - let mapping = ProviderMappingTable::from_rows([ - // Listing 10: single key reporting two differing split ratios on d1 -> both kept - map_row("qm", "SOLO", day(2020, 1, 1), None, 10), - // Listing 20: two keys with conflicting splits on d1, plus same-day dividend and next-day split - map_row("qm", "CK1", day(2020, 1, 1), None, 20), - map_row("qm", "CK2", day(2020, 1, 1), None, 20), - ]) - .unwrap(); - - let splits = vec![ - split_ev("SOLO", d1, 2.0, None), - split_ev("SOLO", d1, 3.0, None), - split_ev("CK1", d1, 2.0, None), - split_ev("CK2", d1, 3.0, None), - split_ev("CK1", d2, 4.0, None), - ]; - let dividends = vec![div_ev("CK1", d1, 0.50, "USD", None)]; - - let out = - curate_corporate_actions(splits, dividends, empty_delistings(), "qm", &mapping).unwrap(); - assert_conservation_and_order(&out); - - assert_eq!(out.stats.rows_in, 6); - assert_eq!(out.stats.rows_out, 4); - assert_eq!(out.stats.listings_out, 2); - assert_eq!(out.stats.listing_collision_collapsed, 0); - assert_eq!(out.stats.listing_collision_dropped, 2); - - // Listing 10 kept both same-key splits on d1 - let l10_ratios: Vec = out - .rows - .iter() - .filter(|r| r.listing_id == 10) - .map(|r| r.ratio.unwrap()) - .collect(); - assert_eq!(l10_ratios, vec![2.0, 3.0]); - - // Listing 20 dropped only the d1 conflicting split group, keeping d1 dividend and d2 split - let l20_rows: Vec<(i32, CorporateActionKind)> = out - .rows - .iter() - .filter(|r| r.listing_id == 20) - .map(|r| (r.ex_date, r.kind)) - .collect(); - assert_eq!( - l20_rows, - vec![ - (d1, CorporateActionKind::Dividend), - (d2, CorporateActionKind::Split), - ] - ); -} diff --git a/tools/curate-etl/src/curate_fundamentals.rs b/tools/curate-etl/src/curate_fundamentals.rs deleted file mode 100644 index 02092a68..00000000 --- a/tools/curate-etl/src/curate_fundamentals.rs +++ /dev/null @@ -1,282 +0,0 @@ -//! Pure, in-memory `fundamentals_pit` curation stage joining -//! [`crate::provider_mapping::ProviderMappingTable`], -//! [`crate::fundamentals::build_fundamentals_rows`], -//! [`crate::fundamentals::build_fundamentals_snapshots`], and -//! [`crate::parquet_fundamentals::write_fundamentals_pit_dataset`] into contract -//! [`FundamentalsPitParquetRow`]s. -//! -//! # Contract & Point-in-Time Rules -//! - Resolves provider source keys to permanent `listing_id: i32` **before** building -//! bitemporal rows and snapshots so ticker reuse never mixes issuers or spans TTM windows -//! across distinct listings: -//! - **Observations:** resolved on `(mapping_source, obs.key, obs.period_end)` (the fiscal -//! period end date, not `report_date`). -//! - **Filings:** `filing.timefiled` is parsed first via [`parse_filing_timefiled`]; parse -//! failures are dropped and counted in -//! [`CurateFundamentalsStats::filings_dropped_invalid_timestamp`] (never fabricating a -//! placeholder `listing_id`). Valid filings are resolved on -//! `(mapping_source, filing.key, parsed.et_date)` (Eastern local calendar date, never UTC -//! date). -//! - Unmapped observations and filings are dropped and counted in -//! [`CurateFundamentalsStats::observations_dropped_unmapped`] and -//! [`CurateFundamentalsStats::filings_dropped_unmapped`]. -//! - Feeds mapped inputs into [`build_fundamentals_rows`] with `K = i32` and the caller's -//! `venues` map, then [`build_fundamentals_snapshots`] with `k`, then converts each snapshot via -//! [`FundamentalsPitParquetRow::from`]. Output rows preserve the builder's strictly ascending -//! `(listing_id, effective_known_at_micros)` order and are independent of input order. - -use std::collections::BTreeMap; -use std::error::Error; -use std::fmt; -use std::path::Path; - -use crate::events::{parse_filing_timefiled, QmFiling}; -use crate::fundamentals::{ - build_fundamentals_rows, build_fundamentals_snapshots, FinancialObservation, FundamentalsError, - FundamentalsStats, StatutoryLagVenue, -}; -use crate::parquet_fundamentals::{ - write_fundamentals_pit_dataset, FundamentalsPitParquetRow, FundamentalsPitWriteOptions, - FundamentalsPitWriteStats, ParquetFundamentalsError, -}; -use crate::provider_mapping::ProviderMappingTable; - -/// Accounting summary produced alongside [`CurateFundamentalsOutput::rows`]. -/// -/// Conservation invariants: -/// - `observations_in == observations_dropped_unmapped + build.observations_in` -/// - `filings_in == filings_dropped_unmapped + filings_dropped_invalid_timestamp + build.filings_in` -/// - `build` independently satisfies all [`FundamentalsStats`] conservation invariants (with -/// `build.filings_dropped_invalid_timestamp == 0` because malformed filings are filtered at the -/// stage before mapping lookup). -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct CurateFundamentalsStats { - pub build: FundamentalsStats, - pub observations_in: usize, - pub observations_dropped_unmapped: usize, - pub filings_in: usize, - pub filings_dropped_unmapped: usize, - pub filings_dropped_invalid_timestamp: usize, - pub rows_out: usize, - pub listings_out: usize, -} - -/// Output of [`curate_fundamentals`]: contract Parquet rows strictly ascending by -/// `(listing_id, effective_known_at_micros)` and full stage + builder stats. -#[derive(Debug, Clone, PartialEq)] -pub struct CurateFundamentalsOutput { - pub rows: Vec, - pub stats: CurateFundamentalsStats, -} - -/// Typed caller errors returned by [`curate_fundamentals`]. -/// -/// Unmapped inputs and malformed filing timestamps are dropped and counted in -/// [`CurateFundamentalsStats`] rather than aborting the stage. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum CurateFundamentalsError { - /// Error propagated from [`build_fundamentals_snapshots`] (e.g., `k == 0`). - Fundamentals(FundamentalsError), - /// Caller-supplied `mapping_source` was empty or contained only whitespace. - EmptyMappingSource, -} - -impl fmt::Display for CurateFundamentalsError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match *self { - Self::Fundamentals(err) => write!(f, "{err}"), - Self::EmptyMappingSource => { - write!(f, "mapping_source must not be empty or blank") - } - } - } -} - -impl Error for CurateFundamentalsError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::Fundamentals(err) => Some(err), - Self::EmptyMappingSource => None, - } - } -} - -impl From for CurateFundamentalsError { - fn from(err: FundamentalsError) -> Self { - Self::Fundamentals(err) - } -} - -/// Combined stats returned by [`curate_and_write_fundamentals`]. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct CurateFundamentalsWriteReport { - pub curate_stats: CurateFundamentalsStats, - pub write_stats: FundamentalsPitWriteStats, -} - -/// Typed error returned by [`curate_and_write_fundamentals`]. -#[derive(Debug)] -pub enum CurateFundamentalsWriteError { - Curate(CurateFundamentalsError), - Parquet(ParquetFundamentalsError), -} - -impl fmt::Display for CurateFundamentalsWriteError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Curate(err) => write!(f, "fundamentals curation failed: {err}"), - Self::Parquet(err) => write!(f, "fundamentals Parquet write failed: {err}"), - } - } -} - -impl Error for CurateFundamentalsWriteError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::Curate(err) => Some(err), - Self::Parquet(err) => Some(err), - } - } -} - -impl From for CurateFundamentalsWriteError { - fn from(err: CurateFundamentalsError) -> Self { - Self::Curate(err) - } -} - -impl From for CurateFundamentalsWriteError { - fn from(err: ParquetFundamentalsError) -> Self { - Self::Parquet(err) - } -} - -/// Pure `fundamentals_pit` curation stage: resolves provider source keys to permanent -/// `listing_id`s via `provider_mapping` (observations on `period_end`, filings on Eastern local -/// date `ParsedFilingTime::et_date`), builds bitemporal rows and 2D point-in-time snapshots via -/// [`build_fundamentals_rows`] and [`build_fundamentals_snapshots`], and emits contract -/// [`FundamentalsPitParquetRow`]s strictly ascending by `(listing_id, effective_known_at_micros)`. -/// -/// Rejects blank `mapping_source` with [`CurateFundamentalsError::EmptyMappingSource`] and `k == 0` -/// with [`CurateFundamentalsError::Fundamentals`] (`FundamentalsError::InvalidPeriodLimit`) before -/// consuming input iterators. -pub fn curate_fundamentals( - observations: IO, - filings: IF, - mapping_source: &str, - mapping: &ProviderMappingTable, - venues: &BTreeMap, - k: usize, -) -> Result -where - K: AsRef, - IO: IntoIterator>, - IF: IntoIterator>, -{ - if mapping_source.trim().is_empty() { - return Err(CurateFundamentalsError::EmptyMappingSource); - } - if k == 0 { - return Err(FundamentalsError::InvalidPeriodLimit { k }.into()); - } - - let obs_iter = observations.into_iter(); - let filings_iter = filings.into_iter(); - - let mut stats = CurateFundamentalsStats::default(); - let mut mapped_observations: Vec> = - Vec::with_capacity(obs_iter.size_hint().0); - let mut mapped_filings: Vec> = Vec::with_capacity(filings_iter.size_hint().0); - - for obs in obs_iter { - stats.observations_in += 1; - let Some(listing_id) = mapping.resolve(mapping_source, obs.key.as_ref(), obs.period_end) - else { - stats.observations_dropped_unmapped += 1; - continue; - }; - mapped_observations.push(FinancialObservation { - key: listing_id, - period_end: obs.period_end, - fiscal_period: obs.fiscal_period, - currency: obs.currency, - report_date: obs.report_date, - fields: obs.fields, - }); - } - - for filing in filings_iter { - stats.filings_in += 1; - let Ok(parsed_time) = parse_filing_timefiled(&filing.timefiled) else { - stats.filings_dropped_invalid_timestamp += 1; - continue; - }; - let Some(listing_id) = - mapping.resolve(mapping_source, filing.key.as_ref(), parsed_time.et_date) - else { - stats.filings_dropped_unmapped += 1; - continue; - }; - mapped_filings.push(QmFiling { - key: listing_id, - timefiled: filing.timefiled, - form_type: filing.form_type, - filing_id: filing.filing_id, - url: filing.url, - }); - } - - let built = build_fundamentals_rows(mapped_observations, mapped_filings, venues); - stats.build = built.stats; - - let snapshots = build_fundamentals_snapshots(&built.rows, k)?; - let rows: Vec = snapshots - .into_iter() - .map(FundamentalsPitParquetRow::from) - .collect(); - - let mut last_listing_id: Option = None; - for row in &rows { - if last_listing_id != Some(row.listing_id) { - stats.listings_out += 1; - last_listing_id = Some(row.listing_id); - } - } - stats.rows_out = rows.len(); - - Ok(CurateFundamentalsOutput { rows, stats }) -} - -/// Thin end-to-end wrapper running [`curate_fundamentals`] and publishing the resulting contract -/// rows via [`write_fundamentals_pit_dataset`] to `/fundamentals_pit/year=YYYY/part.parquet`. -/// -/// Any [`CurateFundamentalsError`] returns before [`write_fundamentals_pit_dataset`] is invoked, -/// leaving `out_dir` untouched. -#[allow(clippy::too_many_arguments)] -pub fn curate_and_write_fundamentals( - out_dir: P, - observations: IO, - filings: IF, - mapping_source: &str, - mapping: &ProviderMappingTable, - venues: &BTreeMap, - k: usize, - options: FundamentalsPitWriteOptions, -) -> Result -where - P: AsRef, - K: AsRef, - IO: IntoIterator>, - IF: IntoIterator>, -{ - let curated = curate_fundamentals(observations, filings, mapping_source, mapping, venues, k)?; - let write_stats = write_fundamentals_pit_dataset(out_dir, &curated.rows, options)?; - Ok(CurateFundamentalsWriteReport { - curate_stats: curated.stats, - write_stats, - }) -} - -#[cfg(test)] -#[path = "curate_fundamentals_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/curate_fundamentals_tests.rs b/tools/curate-etl/src/curate_fundamentals_tests.rs deleted file mode 100644 index 5dd241b1..00000000 --- a/tools/curate-etl/src/curate_fundamentals_tests.rs +++ /dev/null @@ -1,1719 +0,0 @@ -//! Unit, replay, PIT-leakage, mapping, determinism, error, and Parquet round-trip tests for -//! `curate_fundamentals`. - -use std::collections::{BTreeMap, HashMap}; -use std::error::Error; -use std::fs::{self, File}; -use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; - -use parquet::basic::Compression; -use parquet::column::reader::ColumnReader; -use parquet::file::reader::{FileReader, SerializedFileReader}; - -use super::{ - curate_and_write_fundamentals, curate_fundamentals, CurateFundamentalsError, - CurateFundamentalsStats, CurateFundamentalsWriteError, -}; -use crate::events::{ - parse_filing_timefiled, partition_year_utc, QmFiling, KNOWN_AT_SOURCE_FILING_TIMESTAMP, - KNOWN_AT_SOURCE_STATUTORY_LAG, -}; -use crate::fundamentals::{ - FinancialObservation, FiscalPeriod, FundamentalsError, FundamentalsFields, FundamentalsTtm, - StatutoryLagVenue, TtmFlowFields, -}; -use crate::parquet_fundamentals::{FundamentalsPitParquetRow, FundamentalsPitWriteOptions}; -use crate::provider_mapping::{ProviderMappingRow, ProviderMappingTable}; -use crate::shorts::et_to_utc_micros; -use crate::split::ymd_to_epoch_days; - -static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0); - -struct TempDirGuard { - path: PathBuf, -} - -impl TempDirGuard { - fn new(label: &str) -> Self { - let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); - let pid = std::process::id(); - let path = std::env::temp_dir().join(format!( - "curate-etl-curate-fundamentals-test-{label}-{pid}-{seq}" - )); - let _ = fs::remove_dir_all(&path); - fs::create_dir_all(&path).expect("create test temp dir"); - Self { path } - } - - fn path(&self) -> &Path { - &self.path - } -} - -impl Drop for TempDirGuard { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.path); - } -} - -fn day(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).expect("valid test date") -} - -fn utc_micros(y: i32, m: u32, d: u32, hour: u8, minute: u8, second: u8) -> 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 mapping_row( - source: &str, - source_id: &str, - valid_from: i32, - valid_to: Option, - listing_id: i32, -) -> ProviderMappingRow { - ProviderMappingRow { - source: source.to_string(), - source_id: source_id.to_string(), - valid_from, - valid_to, - listing_id, - } -} - -fn filing(key: &str, timefiled: &str, form_type: &str) -> QmFiling { - QmFiling { - key: key.to_string(), - timefiled: timefiled.to_string(), - form_type: form_type.to_string(), - filing_id: None, - url: None, - } -} - -fn obs( - key: &str, - period_end: i32, - fiscal_period: FiscalPeriod, - currency: &str, - report_date: Option, - fields: FundamentalsFields, -) -> FinancialObservation { - FinancialObservation { - key: key.to_string(), - period_end, - fiscal_period, - currency: currency.to_string(), - report_date, - fields, - } -} - -fn sample_fields( - rev: f64, - ni: f64, - ocf: f64, - assets: f64, - equity: f64, - shares: f64, -) -> FundamentalsFields { - FundamentalsFields { - revenue: Some(rev), - net_income: Some(ni), - operating_cash_flow: Some(ocf), - total_assets: Some(assets), - total_equity: Some(equity), - shares_outstanding: Some(shares), - } -} - -fn assert_stage_conservation(stats: &CurateFundamentalsStats) { - assert_eq!( - stats.observations_in, - stats.observations_dropped_unmapped + stats.build.observations_in, - "observation stage conservation failed: {stats:?}" - ); - assert_eq!( - stats.filings_in, - stats.filings_dropped_unmapped - + stats.filings_dropped_invalid_timestamp - + stats.build.filings_in, - "filing stage conservation failed: {stats:?}" - ); - assert_eq!( - stats.build.filings_dropped_invalid_timestamp, 0, - "malformed filings must be dropped at the stage before build_fundamentals_rows" - ); - assert_eq!( - stats.build.observations_in, - stats.build.rows_out - + stats.build.observations_dropped_unknown_key - + stats.build.observations_dropped_non_finite - + stats.build.observations_dropped_date_out_of_range - + stats - .build - .observations_dropped_report_date_not_after_period_end - + stats.build.observations_dropped_unanchored_vintage - + stats.build.observations_dropped_stale_estimate - + stats.build.duplicate_collapsed - + stats.build.duplicate_conflict_dropped, - "builder observation conservation failed: {stats:?}" - ); - assert_eq!( - stats.build.filings_in, - stats.build.filings_eligible - + stats.build.filings_dropped_unknown_key - + stats.build.filings_ignored_non_periodic - + stats.build.filings_dropped_invalid_timestamp - + stats.build.filings_dropped_date_out_of_range - + stats.build.filings_dropped_before_period_end, - "builder filing conservation failed: {stats:?}" - ); -} - -fn permutations(items: &[T]) -> Vec> { - if items.is_empty() { - return vec![Vec::new()]; - } - let mut out = Vec::new(); - for i in 0..items.len() { - let mut rest = items.to_vec(); - let head = rest.remove(i); - for mut tail in permutations(&rest) { - let mut perm = Vec::with_capacity(items.len()); - perm.push(head.clone()); - perm.append(&mut tail); - out.push(perm); - } - } - out -} - -#[derive(Debug, Clone, PartialEq)] -struct DecodedParquetRow { - listing_id: i32, - effective_known_at: i64, - known_at_source: String, - has_estimated_lag: bool, - period_end: i32, - fiscal_period: String, - currency: String, - period_known_at: i64, - revenue: Option, - net_income: Option, - operating_cash_flow: Option, - total_assets: Option, - total_equity: Option, - shares_outstanding: Option, - ttm_period_end: Option, - ttm_currency: Option, - ttm_revenue: Option, - ttm_net_income: Option, - ttm_operating_cash_flow: Option, - ttm_has_estimated_lag: Option, -} - -/// Reads a `fundamentals_pit` Parquet file resolving every column strictly by schema column name -/// (never by positional index). -fn read_parquet_rows_by_name(path: &Path) -> Vec { - let file = File::open(path).expect("open parquet file"); - let reader = SerializedFileReader::new(file).expect("open parquet reader"); - let meta = reader.metadata(); - let schema_descr = meta.file_metadata().schema_descr(); - - let mut col_idx_by_name: HashMap<&str, usize> = HashMap::new(); - for (idx, col) in schema_descr.columns().iter().enumerate() { - col_idx_by_name.insert(col.name(), idx); - } - - let col_idx = |name: &str| -> usize { - *col_idx_by_name - .get(name) - .unwrap_or_else(|| panic!("missing expected Parquet column '{name}'")) - }; - - let mut out = Vec::new(); - for rg_idx in 0..meta.num_row_groups() { - let rg_meta = meta.row_group(rg_idx); - for c in 0..rg_meta.num_columns() { - assert_eq!( - rg_meta.column(c).compression(), - Compression::ZSTD(Default::default()), - "expected Zstd compression on column {c}" - ); - } - - let rg_rows = rg_meta.num_rows() as usize; - let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); - - let read_req_i32 = |name: &str| -> Vec { - let idx = col_idx(name); - let mut vals = Vec::with_capacity(rg_rows); - match rg_reader.get_column_reader(idx).expect("col reader") { - ColumnReader::Int32ColumnReader(mut typed) => { - let mut read = 0usize; - while read < rg_rows { - let (n, _, _) = typed - .read_records(rg_rows - read, None, None, &mut vals) - .expect("read req i32"); - assert!(n > 0); - read += n; - } - } - _ => panic!("expected INT32 for column '{name}'"), - } - vals - }; - - let read_opt_i32 = |name: &str| -> Vec> { - let idx = col_idx(name); - let mut vals = Vec::with_capacity(rg_rows); - let mut defs = Vec::with_capacity(rg_rows); - match rg_reader.get_column_reader(idx).expect("col reader") { - ColumnReader::Int32ColumnReader(mut typed) => { - let mut read = 0usize; - while read < rg_rows { - let (n, _, _) = typed - .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) - .expect("read opt i32"); - assert!(n > 0); - read += n; - } - } - _ => panic!("expected INT32 for column '{name}'"), - } - let mut vi = 0usize; - defs.into_iter() - .map(|d| { - if d == 1 { - let v = vals[vi]; - vi += 1; - Some(v) - } else { - assert_eq!(d, 0); - None - } - }) - .collect() - }; - - let read_req_i64 = |name: &str| -> Vec { - let idx = col_idx(name); - let mut vals = Vec::with_capacity(rg_rows); - match rg_reader.get_column_reader(idx).expect("col reader") { - ColumnReader::Int64ColumnReader(mut typed) => { - let mut read = 0usize; - while read < rg_rows { - let (n, _, _) = typed - .read_records(rg_rows - read, None, None, &mut vals) - .expect("read req i64"); - assert!(n > 0); - read += n; - } - } - _ => panic!("expected INT64 for column '{name}'"), - } - vals - }; - - let read_req_bool = |name: &str| -> Vec { - let idx = col_idx(name); - let mut vals = Vec::with_capacity(rg_rows); - match rg_reader.get_column_reader(idx).expect("col reader") { - ColumnReader::BoolColumnReader(mut typed) => { - let mut read = 0usize; - while read < rg_rows { - let (n, _, _) = typed - .read_records(rg_rows - read, None, None, &mut vals) - .expect("read req bool"); - assert!(n > 0); - read += n; - } - } - _ => panic!("expected BOOLEAN for column '{name}'"), - } - vals - }; - - let read_opt_bool = |name: &str| -> Vec> { - let idx = col_idx(name); - let mut vals = Vec::with_capacity(rg_rows); - let mut defs = Vec::with_capacity(rg_rows); - match rg_reader.get_column_reader(idx).expect("col reader") { - ColumnReader::BoolColumnReader(mut typed) => { - let mut read = 0usize; - while read < rg_rows { - let (n, _, _) = typed - .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) - .expect("read opt bool"); - assert!(n > 0); - read += n; - } - } - _ => panic!("expected BOOLEAN for column '{name}'"), - } - let mut vi = 0usize; - defs.into_iter() - .map(|d| { - if d == 1 { - let v = vals[vi]; - vi += 1; - Some(v) - } else { - assert_eq!(d, 0); - None - } - }) - .collect() - }; - - let read_opt_f64 = |name: &str| -> Vec> { - let idx = col_idx(name); - let mut vals = Vec::with_capacity(rg_rows); - let mut defs = Vec::with_capacity(rg_rows); - match rg_reader.get_column_reader(idx).expect("col reader") { - ColumnReader::DoubleColumnReader(mut typed) => { - let mut read = 0usize; - while read < rg_rows { - let (n, _, _) = typed - .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) - .expect("read opt f64"); - assert!(n > 0); - read += n; - } - } - _ => panic!("expected DOUBLE for column '{name}'"), - } - let mut vi = 0usize; - defs.into_iter() - .map(|d| { - if d == 1 { - let v = vals[vi]; - vi += 1; - Some(v) - } else { - assert_eq!(d, 0); - None - } - }) - .collect() - }; - - let read_req_str = |name: &str| -> Vec { - let idx = col_idx(name); - let mut vals = Vec::with_capacity(rg_rows); - match rg_reader.get_column_reader(idx).expect("col reader") { - ColumnReader::ByteArrayColumnReader(mut typed) => { - let mut read = 0usize; - while read < rg_rows { - let (n, _, _) = typed - .read_records(rg_rows - read, None, None, &mut vals) - .expect("read req str"); - assert!(n > 0); - read += n; - } - } - _ => panic!("expected BYTE_ARRAY for column '{name}'"), - } - vals.into_iter() - .map(|b| String::from_utf8(b.data().to_vec()).expect("utf8")) - .collect() - }; - - let read_opt_str = |name: &str| -> Vec> { - let idx = col_idx(name); - let mut vals = Vec::with_capacity(rg_rows); - let mut defs = Vec::with_capacity(rg_rows); - match rg_reader.get_column_reader(idx).expect("col reader") { - ColumnReader::ByteArrayColumnReader(mut typed) => { - let mut read = 0usize; - while read < rg_rows { - let (n, _, _) = typed - .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) - .expect("read opt str"); - assert!(n > 0); - read += n; - } - } - _ => panic!("expected BYTE_ARRAY for column '{name}'"), - } - let mut vi = 0usize; - defs.into_iter() - .map(|d| { - if d == 1 { - let v = String::from_utf8(vals[vi].data().to_vec()).expect("utf8"); - vi += 1; - Some(v) - } else { - assert_eq!(d, 0); - None - } - }) - .collect() - }; - - let listing_id = read_req_i32("listing_id"); - let effective_known_at = read_req_i64("effective_known_at"); - let known_at_source = read_req_str("known_at_source"); - let has_estimated_lag = read_req_bool("has_estimated_lag"); - let period_end = read_req_i32("period_end"); - let fiscal_period = read_req_str("fiscal_period"); - let currency = read_req_str("currency"); - let period_known_at = read_req_i64("period_known_at"); - let revenue = read_opt_f64("revenue"); - let net_income = read_opt_f64("net_income"); - let operating_cash_flow = read_opt_f64("operating_cash_flow"); - let total_assets = read_opt_f64("total_assets"); - let total_equity = read_opt_f64("total_equity"); - let shares_outstanding = read_opt_f64("shares_outstanding"); - let ttm_period_end = read_opt_i32("ttm_period_end"); - let ttm_currency = read_opt_str("ttm_currency"); - let ttm_revenue = read_opt_f64("ttm_revenue"); - let ttm_net_income = read_opt_f64("ttm_net_income"); - let ttm_operating_cash_flow = read_opt_f64("ttm_operating_cash_flow"); - let ttm_has_estimated_lag = read_opt_bool("ttm_has_estimated_lag"); - - for i in 0..rg_rows { - out.push(DecodedParquetRow { - listing_id: listing_id[i], - effective_known_at: effective_known_at[i], - known_at_source: known_at_source[i].clone(), - has_estimated_lag: has_estimated_lag[i], - period_end: period_end[i], - fiscal_period: fiscal_period[i].clone(), - currency: currency[i].clone(), - period_known_at: period_known_at[i], - revenue: revenue[i], - net_income: net_income[i], - operating_cash_flow: operating_cash_flow[i], - total_assets: total_assets[i], - total_equity: total_equity[i], - shares_outstanding: shares_outstanding[i], - ttm_period_end: ttm_period_end[i], - ttm_currency: ttm_currency[i].clone(), - ttm_revenue: ttm_revenue[i], - ttm_net_income: ttm_net_income[i], - ttm_operating_cash_flow: ttm_operating_cash_flow[i], - ttm_has_estimated_lag: ttm_has_estimated_lag[i], - }); - } - } - out -} - -fn decoded_from_curated(row: &FundamentalsPitParquetRow) -> DecodedParquetRow { - let latest = row - .latest_period() - .expect("curated row must have latest_period"); - DecodedParquetRow { - listing_id: row.listing_id, - effective_known_at: row.effective_known_at_micros, - known_at_source: row.known_at_source.to_string(), - has_estimated_lag: row.has_estimated_lag, - period_end: latest.period_end, - fiscal_period: latest.fiscal_period.to_string(), - currency: latest.currency.clone(), - period_known_at: latest.period_known_at_micros, - revenue: latest.fields.revenue, - net_income: latest.fields.net_income, - operating_cash_flow: latest.fields.operating_cash_flow, - total_assets: latest.fields.total_assets, - total_equity: latest.fields.total_equity, - shares_outstanding: latest.fields.shares_outstanding, - ttm_period_end: row.ttm.as_ref().map(|t| t.ending_period_end), - ttm_currency: row.ttm.as_ref().map(|t| t.currency.clone()), - ttm_revenue: row.ttm.as_ref().and_then(|t| t.flows.revenue), - ttm_net_income: row.ttm.as_ref().and_then(|t| t.flows.net_income), - ttm_operating_cash_flow: row.ttm.as_ref().and_then(|t| t.flows.operating_cash_flow), - ttm_has_estimated_lag: row.ttm.as_ref().map(|t| t.has_estimated_lag), - } -} - -#[test] -fn restatement_after_q2_preserves_prior_snapshots_and_never_displaces_q2() { - let mapping = - ProviderMappingTable::from_rows([mapping_row("qm", "ACME", day(2024, 1, 1), None, 1001)]) - .expect("valid mapping"); - let venues = BTreeMap::from([(1001, StatutoryLagVenue::UsTsx)]); - - let q1_end = day(2024, 3, 31); - let q2_end = day(2024, 6, 30); - let q1_fields = sample_fields(100.0, 12.0, 15.0, 500.0, 250.0, 10.0); - let q2_fields = sample_fields(130.0, 18.0, 21.0, 540.0, 270.0, 10.0); - let q1_restated_fields = sample_fields(92.0, 9.0, 11.0, 490.0, 245.0, 10.0); - - let base_observations = vec![ - obs( - "ACME", - q1_end, - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 5, 1)), - q1_fields, - ), - obs( - "ACME", - q2_end, - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 8, 1)), - q2_fields, - ), - ]; - let base_filings = vec![ - filing("ACME", "2024-05-01T16:10:00 EDT", "10-Q"), - filing("ACME", "2024-08-01T16:15:00 EDT", "10-Q"), - ]; - - let baseline = curate_fundamentals( - base_observations.clone(), - base_filings.clone(), - "qm", - &mapping, - &venues, - 4, - ) - .expect("baseline curate"); - assert_stage_conservation(&baseline.stats); - assert_eq!(baseline.rows.len(), 2); - - let mut revised_observations = base_observations; - revised_observations.push(obs( - "ACME", - q1_end, - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 9, 15)), - q1_restated_fields, - )); - let mut revised_filings = base_filings; - revised_filings.push(filing("ACME", "2024-09-15T16:30:00 EDT", "10-Q/A")); - - let revised = curate_fundamentals( - revised_observations, - revised_filings, - "qm", - &mapping, - &venues, - 4, - ) - .expect("revised curate"); - assert_stage_conservation(&revised.stats); - assert_eq!(revised.rows.len(), 3); - - let q2_known_at = parse_filing_timefiled("2024-08-01T16:15:00 EDT") - .expect("q2 ts") - .utc_micros; - let amend_known_at = parse_filing_timefiled("2024-09-15T16:30:00 EDT") - .expect("amend ts") - .utc_micros; - - // Snapshots before the amendment must be bit-for-bit identical to the baseline replay. - assert_eq!(&revised.rows[..2], &baseline.rows[..]); - - // The amendment produces a new snapshot at the amendment timestamp, while Q2 remains latest. - assert_eq!(revised.rows[2].effective_known_at_micros, amend_known_at); - for row in revised - .rows - .iter() - .filter(|r| r.effective_known_at_micros >= q2_known_at) - { - let latest = row.latest_period().expect("latest period"); - assert_eq!(latest.period_end, q2_end); - assert_eq!(latest.fields, q2_fields); - assert_eq!(latest.period_known_at_micros, q2_known_at); - assert_ne!(latest.period_end, q1_end); - } -} - -#[test] -fn statutory_lag_deadlines_and_filing_timestamp_provenance() { - let mapping = ProviderMappingTable::from_rows([ - mapping_row("qm", "US_CO", day(2024, 1, 1), None, 10), - mapping_row("qm", "TSXV_CO", day(2024, 1, 1), None, 20), - mapping_row("qm", "LINKED_CO", day(2024, 1, 1), None, 30), - ]) - .expect("valid mapping"); - let venues = BTreeMap::from([ - (10, StatutoryLagVenue::UsTsx), - (20, StatutoryLagVenue::TsxvCse), - (30, StatutoryLagVenue::UsTsx), - ]); - - let q_end = day(2024, 3, 31); - let fy_end = day(2024, 12, 31); - let fields = sample_fields(50.0, 5.0, 6.0, 200.0, 120.0, 8.0); - - // 1. UsTsx quarterly (+45d -> 2024-05-15 16:05 EDT = 20:05 UTC) - let us_q = curate_fundamentals( - [obs( - "US_CO", - q_end, - FiscalPeriod::Quarterly, - "USD", - None, - fields, - )], - Vec::>::new(), - "qm", - &mapping, - &venues, - 4, - ) - .expect("us quarterly"); - assert_eq!(us_q.rows.len(), 1); - let expected_us_q = et_to_utc_micros(q_end + 45, 16, 5, 0).expect("us q et"); - assert_eq!(expected_us_q, utc_micros(2024, 5, 15, 20, 5, 0)); - assert_eq!(us_q.rows[0].effective_known_at_micros, expected_us_q); - assert_eq!( - us_q.rows[0].known_at_source.as_ref(), - KNOWN_AT_SOURCE_STATUTORY_LAG - ); - assert!(us_q.rows[0].has_estimated_lag); - - // 2. UsTsx annual (+90d -> 2025-03-31 16:05 EDT = 20:05 UTC) - let us_fy = curate_fundamentals( - [obs( - "US_CO", - fy_end, - FiscalPeriod::Annual, - "USD", - None, - fields, - )], - Vec::>::new(), - "qm", - &mapping, - &venues, - 4, - ) - .expect("us annual"); - assert_eq!(us_fy.rows.len(), 1); - let expected_us_fy = et_to_utc_micros(fy_end + 90, 16, 5, 0).expect("us fy et"); - assert_eq!(expected_us_fy, utc_micros(2025, 3, 31, 20, 5, 0)); - assert_eq!(us_fy.rows[0].effective_known_at_micros, expected_us_fy); - assert_eq!( - us_fy.rows[0].known_at_source.as_ref(), - KNOWN_AT_SOURCE_STATUTORY_LAG - ); - assert!(us_fy.rows[0].has_estimated_lag); - - // 3. TsxvCse quarterly (+60d -> 2024-05-30 16:05 EDT = 20:05 UTC) - let tsxv_q = curate_fundamentals( - [obs( - "TSXV_CO", - q_end, - FiscalPeriod::Quarterly, - "CAD", - None, - fields, - )], - Vec::>::new(), - "qm", - &mapping, - &venues, - 4, - ) - .expect("tsxv quarterly"); - assert_eq!(tsxv_q.rows.len(), 1); - let expected_tsxv_q = et_to_utc_micros(q_end + 60, 16, 5, 0).expect("tsxv q et"); - assert_eq!(expected_tsxv_q, utc_micros(2024, 5, 30, 20, 5, 0)); - assert_eq!(tsxv_q.rows[0].effective_known_at_micros, expected_tsxv_q); - assert_eq!( - tsxv_q.rows[0].known_at_source.as_ref(), - KNOWN_AT_SOURCE_STATUTORY_LAG - ); - assert!(tsxv_q.rows[0].has_estimated_lag); - - // 4. TsxvCse annual (+120d -> 2025-04-30 16:05 EDT = 20:05 UTC) - let tsxv_fy = curate_fundamentals( - [obs( - "TSXV_CO", - fy_end, - FiscalPeriod::Annual, - "CAD", - None, - fields, - )], - Vec::>::new(), - "qm", - &mapping, - &venues, - 4, - ) - .expect("tsxv annual"); - assert_eq!(tsxv_fy.rows.len(), 1); - let expected_tsxv_fy = et_to_utc_micros(fy_end + 120, 16, 5, 0).expect("tsxv fy et"); - assert_eq!(expected_tsxv_fy, utc_micros(2025, 4, 30, 20, 5, 0)); - assert_eq!(tsxv_fy.rows[0].effective_known_at_micros, expected_tsxv_fy); - assert_eq!( - tsxv_fy.rows[0].known_at_source.as_ref(), - KNOWN_AT_SOURCE_STATUTORY_LAG - ); - assert!(tsxv_fy.rows[0].has_estimated_lag); - - // 5. Filing-linked observation uses exact parsed filing timestamp and filing_timestamp source. - let linked = curate_fundamentals( - [obs( - "LINKED_CO", - q_end, - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 5, 2)), - fields, - )], - [filing("LINKED_CO", "2024-05-02T08:30:15 EDT", "10-Q")], - "qm", - &mapping, - &venues, - 4, - ) - .expect("linked quarterly"); - assert_eq!(linked.rows.len(), 1); - let expected_linked = utc_micros(2024, 5, 2, 12, 30, 15); - assert_eq!(linked.rows[0].effective_known_at_micros, expected_linked); - assert_eq!( - linked.rows[0].known_at_source.as_ref(), - KNOWN_AT_SOURCE_FILING_TIMESTAMP - ); - assert!(!linked.rows[0].has_estimated_lag); -} - -#[test] -fn ticker_remap_across_utc_midnight_separates_listings_and_prevents_cross_listing_ttm() { - // Source key "REUSED" belongs to listing 101 through 2023-08-05 ET, then listing 202 starting - // 2023-08-06 ET. - let mapping = ProviderMappingTable::from_rows([ - mapping_row("qm", "REUSED", day(2023, 1, 1), Some(day(2023, 8, 5)), 101), - mapping_row("qm", "REUSED", day(2023, 8, 6), None, 202), - ]) - .expect("valid remap"); - let venues = BTreeMap::from([ - (101, StatutoryLagVenue::UsTsx), - (202, StatutoryLagVenue::UsTsx), - ]); - - let f = sample_fields(10.0, 1.0, 2.0, 50.0, 25.0, 5.0); - - // Listing 101 gets Q1 (2023-03-31) and Q2 (2023-06-30). - // Q2's filing is at 2023-08-05T21:00:00 EDT (2023-08-06T01:00:00 UTC): Eastern date is - // 2023-08-05 (listing 101), whereas UTC date is 2023-08-06 (listing 202). - // Listing 202 gets Q3 (2023-09-30) and Q4 (2023-12-31). - let observations = vec![ - obs( - "REUSED", - day(2023, 3, 31), - FiscalPeriod::Quarterly, - "USD", - Some(day(2023, 5, 10)), - f, - ), - obs( - "REUSED", - day(2023, 6, 30), - FiscalPeriod::Quarterly, - "USD", - Some(day(2023, 8, 5)), - f, - ), - obs( - "REUSED", - day(2023, 9, 30), - FiscalPeriod::Quarterly, - "USD", - Some(day(2023, 11, 8)), - f, - ), - obs( - "REUSED", - day(2023, 12, 31), - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 2, 12)), - f, - ), - ]; - let filings = vec![ - filing("REUSED", "2023-05-10T16:00:00 EDT", "10-Q"), - filing("REUSED", "2023-08-05T21:00:00 EDT", "10-Q"), - filing("REUSED", "2023-11-08T16:00:00 EST", "10-Q"), - filing("REUSED", "2024-02-12T16:00:00 EST", "10-Q"), - ]; - - let out = curate_fundamentals(observations, filings, "qm", &mapping, &venues, 4) - .expect("remap curate"); - assert_stage_conservation(&out.stats); - assert_eq!(out.stats.listings_out, 2); - assert_eq!(out.rows.len(), 4); - - let l101: Vec<&FundamentalsPitParquetRow> = - out.rows.iter().filter(|r| r.listing_id == 101).collect(); - let l202: Vec<&FundamentalsPitParquetRow> = - out.rows.iter().filter(|r| r.listing_id == 202).collect(); - assert_eq!(l101.len(), 2); - assert_eq!(l202.len(), 2); - - // Late-evening EDT filing must link to listing 101's Q2 (not listing 202). - assert_eq!( - l101[1].effective_known_at_micros, - utc_micros(2023, 8, 6, 1, 0, 0) - ); - assert_eq!( - l101[1].known_at_source.as_ref(), - KNOWN_AT_SOURCE_FILING_TIMESTAMP - ); - assert!(!l101[1].has_estimated_lag); - - // Neither listing has 4 quarters, so TTM must never span across the ticker remap. - assert!(out.rows.iter().all(|r| r.ttm.is_none())); - - // Also verify observation resolution uses period_end even when report_date falls after remap. - let after_remap_report = curate_fundamentals( - [obs( - "REUSED", - day(2023, 6, 30), - FiscalPeriod::Quarterly, - "USD", - Some(day(2023, 8, 10)), // after 2023-08-05 remap, <= statutory lag 2023-08-14 - f, - )], - Vec::>::new(), - "qm", - &mapping, - &venues, - 4, - ) - .expect("period_end resolution"); - assert_eq!(after_remap_report.rows.len(), 1); - assert_eq!(after_remap_report.rows[0].listing_id, 101); -} - -#[test] -fn unmapped_and_malformed_inputs_are_counted_and_conserved() { - let mapping = ProviderMappingTable::from_rows([mapping_row( - "qm", - "KNOWN", - day(2024, 1, 1), - Some(day(2024, 12, 31)), - 501, - )]) - .expect("valid mapping"); - let venues = BTreeMap::from([(501, StatutoryLagVenue::UsTsx)]); - let f = sample_fields(25.0, 3.0, 4.0, 100.0, 60.0, 2.0); - - let valid_obs = obs( - "KNOWN", - day(2024, 3, 31), - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 5, 1)), - f, - ); - let valid_filing = filing("KNOWN", "2024-05-01T17:00:00 EDT", "10-Q"); - - let clean = curate_fundamentals( - [valid_obs.clone()], - [valid_filing.clone()], - "qm", - &mapping, - &venues, - 4, - ) - .expect("clean curate"); - - let with_noise = curate_fundamentals( - [ - valid_obs, - // Unmapped observation (unknown key) - obs( - "UNKNOWN", - day(2024, 3, 31), - FiscalPeriod::Quarterly, - "USD", - None, - f, - ), - // Unmapped observation (known key, period_end outside range) - obs( - "KNOWN", - day(2023, 12, 31), - FiscalPeriod::Quarterly, - "USD", - None, - f, - ), - ], - [ - valid_filing, - // Parseable unmapped filing - filing("UNKNOWN", "2024-05-01T10:00:00 EDT", "10-Q"), - // Malformed filing timestamp for mapped key - filing("KNOWN", "2024-05-01 09:00:00 UTC", "10-Q"), - ], - "qm", - &mapping, - &venues, - 4, - ) - .expect("noisy curate"); - - assert_stage_conservation(&with_noise.stats); - assert_eq!(with_noise.stats.observations_in, 3); - assert_eq!(with_noise.stats.observations_dropped_unmapped, 2); - assert_eq!(with_noise.stats.build.observations_in, 1); - - assert_eq!(with_noise.stats.filings_in, 3); - assert_eq!(with_noise.stats.filings_dropped_unmapped, 1); - assert_eq!(with_noise.stats.filings_dropped_invalid_timestamp, 1); - assert_eq!(with_noise.stats.build.filings_in, 1); - assert_eq!(with_noise.stats.build.filings_eligible, 1); - - // Malformed and unmapped inputs must have zero effect on availability or emitted rows. - assert_eq!(with_noise.rows, clean.rows); -} - -#[test] -fn permutation_invariance_and_strict_ascending_order() { - let mapping = ProviderMappingTable::from_rows([ - mapping_row("qm", "ALPHA", day(2024, 1, 1), None, 200), - mapping_row("qm", "BETA", day(2024, 1, 1), None, 100), - ]) - .expect("valid mapping"); - let venues = BTreeMap::from([ - (100, StatutoryLagVenue::UsTsx), - (200, StatutoryLagVenue::TsxvCse), - ]); - - let f1 = sample_fields(10.0, 1.0, 2.0, 40.0, 20.0, 4.0); - let f2 = sample_fields(15.0, 2.0, 3.0, 45.0, 22.0, 4.0); - let f3 = sample_fields(20.0, 3.0, 4.0, 60.0, 30.0, 6.0); - - let base_obs = vec![ - obs( - "ALPHA", - day(2024, 3, 31), - FiscalPeriod::Quarterly, - "CAD", - Some(day(2024, 5, 1)), - f1, - ), - obs( - "ALPHA", - day(2024, 6, 30), - FiscalPeriod::Quarterly, - "CAD", - Some(day(2024, 8, 1)), - f2, - ), - obs( - "BETA", - day(2024, 3, 31), - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 5, 1)), - f3, - ), - ]; - let base_filings = vec![ - filing( - "ALPHA", - "2024-05-01T16:00:00 EDT", - "Interim financial statements", - ), - filing( - "ALPHA", - "2024-08-01T16:00:00 EDT", - "Interim financial statements", - ), - // Same-instant filing for BETA - filing("BETA", "2024-05-01T16:00:00 EDT", "10-Q"), - ]; - - let reference = curate_fundamentals( - base_obs.clone(), - base_filings.clone(), - "qm", - &mapping, - &venues, - 4, - ) - .expect("reference run"); - assert_stage_conservation(&reference.stats); - assert_eq!(reference.rows.len(), 3); - - for pair in reference.rows.windows(2) { - let a = (pair[0].listing_id, pair[0].effective_known_at_micros); - let b = (pair[1].listing_id, pair[1].effective_known_at_micros); - assert!(a < b, "rows not strictly ascending: {a:?} >= {b:?}"); - } - - let obs_perms = permutations(&base_obs); - let filing_perms = permutations(&base_filings); - assert_eq!(obs_perms.len(), 6); - assert_eq!(filing_perms.len(), 6); - - for op in &obs_perms { - for fp in &filing_perms { - let out = curate_fundamentals( - op.iter().cloned(), - fp.iter().cloned(), - "qm", - &mapping, - &venues, - 4, - ) - .expect("permuted run"); - assert_eq!(out.rows, reference.rows); - assert_eq!(out.stats, reference.stats); - } - } -} - -#[test] -fn typed_errors_and_untouched_out_dir_on_curation_failure() { - let mapping = - ProviderMappingTable::from_rows([mapping_row("qm", "ACME", day(2024, 1, 1), None, 10)]) - .expect("valid mapping"); - let venues = BTreeMap::from([(10, StatutoryLagVenue::UsTsx)]); - let invalid_writer_opts = FundamentalsPitWriteOptions { - row_group_rows: 0, - ..FundamentalsPitWriteOptions::default() - }; - - for blank_source in ["", " \t\n "] { - let err = curate_fundamentals( - Vec::>::new(), - Vec::>::new(), - blank_source, - &mapping, - &venues, - 4, - ) - .expect_err("blank mapping_source must fail"); - assert_eq!(err, CurateFundamentalsError::EmptyMappingSource); - assert!(err.source().is_none()); - assert!(err.to_string().contains("mapping_source")); - - let tmp = TempDirGuard::new("empty-source"); - let write_err = curate_and_write_fundamentals( - tmp.path(), - Vec::>::new(), - Vec::>::new(), - blank_source, - &mapping, - &venues, - 4, - invalid_writer_opts, - ) - .expect_err("curation error must take precedence over invalid writer options"); - assert!(matches!( - write_err, - CurateFundamentalsWriteError::Curate(CurateFundamentalsError::EmptyMappingSource) - )); - assert!(write_err.source().is_some()); - assert!(write_err - .to_string() - .contains("fundamentals curation failed")); - assert!( - !tmp.path().join("fundamentals_pit").exists(), - "out_dir must remain untouched on curation failure" - ); - } - - let k_err = curate_fundamentals( - Vec::>::new(), - Vec::>::new(), - "qm", - &mapping, - &venues, - 0, - ) - .expect_err("k == 0 must fail"); - assert_eq!( - k_err, - CurateFundamentalsError::Fundamentals(FundamentalsError::InvalidPeriodLimit { k: 0 }) - ); - assert!(k_err.source().is_some()); - - let tmp_k = TempDirGuard::new("k-zero"); - let write_k_err = curate_and_write_fundamentals( - tmp_k.path(), - Vec::>::new(), - Vec::>::new(), - "qm", - &mapping, - &venues, - 0, - invalid_writer_opts, - ) - .expect_err("k == 0 must fail before writer"); - assert!(matches!( - write_k_err, - CurateFundamentalsWriteError::Curate(CurateFundamentalsError::Fundamentals( - FundamentalsError::InvalidPeriodLimit { k: 0 } - )) - )); - assert!( - !tmp_k.path().join("fundamentals_pit").exists(), - "out_dir must remain untouched on k == 0 failure" - ); -} - -#[test] -fn curate_and_write_fundamentals_round_trips_four_quarters_and_ttm_by_column_name() { - let mapping = - ProviderMappingTable::from_rows([mapping_row("qm", "GROW", day(2023, 1, 1), None, 777)]) - .expect("valid mapping"); - let venues = BTreeMap::from([(777, StatutoryLagVenue::UsTsx)]); - - let q1_f = sample_fields(100.0, 10.0, 15.0, 500.0, 200.0, 10.0); - let q2_f = sample_fields(110.0, 12.0, 18.0, 520.0, 212.0, 10.0); - let q3_f = sample_fields(125.0, 14.0, 20.0, 545.0, 226.0, 10.0); - let q4_f = sample_fields(140.0, 16.0, 22.0, 575.0, 242.0, 10.0); - - let observations = vec![ - obs( - "GROW", - day(2023, 3, 31), - FiscalPeriod::Quarterly, - "USD", - Some(day(2023, 5, 1)), - q1_f, - ), - obs( - "GROW", - day(2023, 6, 30), - FiscalPeriod::Quarterly, - "USD", - Some(day(2023, 8, 1)), - q2_f, - ), - obs( - "GROW", - day(2023, 9, 30), - FiscalPeriod::Quarterly, - "USD", - Some(day(2023, 11, 1)), - q3_f, - ), - obs( - "GROW", - day(2023, 12, 31), - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 2, 15)), - q4_f, - ), - ]; - let filings = vec![ - filing("GROW", "2023-05-01T16:10:00 EDT", "10-Q"), - filing("GROW", "2023-08-01T16:10:00 EDT", "10-Q"), - filing("GROW", "2023-11-01T16:10:00 EDT", "10-Q"), - filing("GROW", "2024-02-15T16:10:00 EST", "10-Q"), - ]; - - let curated = curate_fundamentals( - observations.clone(), - filings.clone(), - "qm", - &mapping, - &venues, - 4, - ) - .expect("curate four quarters"); - assert_stage_conservation(&curated.stats); - assert_eq!(curated.rows.len(), 4); - assert!(curated.rows[0].ttm.is_none()); - assert!(curated.rows[1].ttm.is_none()); - assert!(curated.rows[2].ttm.is_none()); - assert_eq!( - curated.rows[3].ttm, - Some(FundamentalsTtm { - ending_period_end: day(2023, 12, 31), - currency: "USD".to_string(), - flows: TtmFlowFields { - revenue: Some(100.0 + 110.0 + 125.0 + 140.0), - net_income: Some(10.0 + 12.0 + 14.0 + 16.0), - operating_cash_flow: Some(15.0 + 18.0 + 20.0 + 22.0), - }, - has_estimated_lag: false, - }) - ); - - let tmp = TempDirGuard::new("round-trip"); - let report = curate_and_write_fundamentals( - tmp.path(), - observations, - filings, - "qm", - &mapping, - &venues, - 4, - FundamentalsPitWriteOptions::default(), - ) - .expect("curate and write"); - - assert_eq!(report.curate_stats, curated.stats); - assert_eq!(report.write_stats.files_written, 2); - assert_eq!(report.write_stats.rows_written, 4); - assert_eq!( - report.write_stats.rows_by_year, - BTreeMap::from([(2023, 3), (2024, 1)]) - ); - - let mut read_back = Vec::new(); - for year in [2023, 2024] { - let part_path = tmp - .path() - .join("fundamentals_pit") - .join(format!("year={year}")) - .join("part.parquet"); - assert!( - part_path.exists(), - "missing partition {}", - part_path.display() - ); - let part_rows = read_parquet_rows_by_name(&part_path); - for row in &part_rows { - assert_eq!(partition_year_utc(row.effective_known_at), year); - } - read_back.extend(part_rows); - } - - let expected: Vec = curated.rows.iter().map(decoded_from_curated).collect(); - assert_eq!(read_back, expected); -} - -// --------------------------------------------------------------------------------------------- -// QA additions (T-169): amendment TTM propagation, UTC-year partitioning, Eastern-date filing -// resolution, builder venue misses, cutoff-truncation PIT replay, and empty input. -// --------------------------------------------------------------------------------------------- - -fn grow_four_quarters() -> (Vec>, Vec>) { - let observations = vec![ - obs( - "GROW", - day(2023, 3, 31), - FiscalPeriod::Quarterly, - "USD", - Some(day(2023, 5, 1)), - sample_fields(100.0, 10.0, 15.0, 500.0, 200.0, 10.0), - ), - obs( - "GROW", - day(2023, 6, 30), - FiscalPeriod::Quarterly, - "USD", - Some(day(2023, 8, 1)), - sample_fields(110.0, 12.0, 18.0, 520.0, 212.0, 10.0), - ), - obs( - "GROW", - day(2023, 9, 30), - FiscalPeriod::Quarterly, - "USD", - Some(day(2023, 11, 1)), - sample_fields(125.0, 14.0, 20.0, 545.0, 226.0, 10.0), - ), - obs( - "GROW", - day(2023, 12, 31), - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 2, 15)), - sample_fields(140.0, 16.0, 22.0, 575.0, 242.0, 10.0), - ), - ]; - let filings = vec![ - filing("GROW", "2023-05-01T16:10:00 EDT", "10-Q"), - filing("GROW", "2023-08-01T16:10:00 EDT", "10-Q"), - filing("GROW", "2023-11-01T16:10:00 EDT", "10-Q"), - filing("GROW", "2024-02-15T16:10:00 EST", "10-Q"), - ]; - (observations, filings) -} - -fn grow_mapping() -> (ProviderMappingTable, BTreeMap) { - let mapping = - ProviderMappingTable::from_rows([mapping_row("qm", "GROW", day(2023, 1, 1), None, 777)]) - .expect("valid mapping"); - (mapping, BTreeMap::from([(777, StatutoryLagVenue::UsTsx)])) -} - -#[test] -fn q1_amendment_after_q4_first_changes_ttm_at_its_filing_instant_and_keeps_q4_latest() { - let (mapping, venues) = grow_mapping(); - let (observations, filings) = grow_four_quarters(); - - let baseline = curate_fundamentals( - observations.clone(), - filings.clone(), - "qm", - &mapping, - &venues, - 4, - ) - .expect("baseline"); - assert_eq!(baseline.rows.len(), 4); - let baseline_ttm = baseline.rows[3].ttm.clone().expect("baseline ttm"); - assert_eq!(baseline_ttm.flows.revenue, Some(475.0)); - - let mut revised_obs = observations; - revised_obs.push(obs( - "GROW", - day(2023, 3, 31), - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 3, 20)), - sample_fields(80.0, 4.0, 9.0, 480.0, 190.0, 10.0), - )); - let mut revised_filings = filings; - revised_filings.push(filing("GROW", "2024-03-20T17:45:00 EDT", "10-Q/A")); - - let revised = curate_fundamentals(revised_obs, revised_filings, "qm", &mapping, &venues, 4) - .expect("revised"); - assert_stage_conservation(&revised.stats); - assert_eq!(revised.rows.len(), 5); - - // Every pre-amendment snapshot is unchanged (no look-back leak of the restated Q1). - assert_eq!(&revised.rows[..4], &baseline.rows[..]); - - let amend_at = utc_micros(2024, 3, 20, 21, 45, 0); - let amended = &revised.rows[4]; - assert_eq!(amended.effective_known_at_micros, amend_at); - assert_eq!( - amended.known_at_source.as_ref(), - KNOWN_AT_SOURCE_FILING_TIMESTAMP - ); - - // Latest period stays Q4 with Q4's fields and Q4's original availability. - let latest = amended.latest_period().expect("latest"); - assert_eq!(latest.period_end, day(2023, 12, 31)); - assert_eq!( - latest.fields, - sample_fields(140.0, 16.0, 22.0, 575.0, 242.0, 10.0) - ); - assert_eq!( - latest.period_known_at_micros, - utc_micros(2024, 2, 15, 21, 10, 0) - ); - - // The TTM total first reflects the restated Q1 at the amendment instant. - let ttm = amended.ttm.as_ref().expect("amended ttm"); - assert_eq!(ttm.ending_period_end, day(2023, 12, 31)); - assert_eq!(ttm.flows.revenue, Some(80.0 + 110.0 + 125.0 + 140.0)); - assert_eq!(ttm.flows.net_income, Some(4.0 + 12.0 + 14.0 + 16.0)); - assert_eq!( - ttm.flows.operating_cash_flow, - Some(9.0 + 18.0 + 20.0 + 22.0) - ); - assert_ne!(ttm.flows, baseline_ttm.flows); -} - -#[test] -fn late_december_eastern_filing_partitions_into_next_utc_year() { - // Listing 900 is valid through 2023-12-31 ET only; a 21:00 EST filing on Dec 31 is - // 2024-01-01T02:00Z, so it must resolve on the Eastern date but partition by UTC year. - let mapping = ProviderMappingTable::from_rows([mapping_row( - "qm", - "NYE", - day(2023, 1, 1), - Some(day(2023, 12, 31)), - 900, - )]) - .expect("valid mapping"); - let venues = BTreeMap::from([(900, StatutoryLagVenue::UsTsx)]); - - let observations = vec![ - obs( - "NYE", - day(2023, 8, 31), - FiscalPeriod::Quarterly, - "USD", - Some(day(2023, 10, 10)), - sample_fields(5.0, 1.0, 1.0, 20.0, 10.0, 1.0), - ), - obs( - "NYE", - day(2023, 11, 30), - FiscalPeriod::Quarterly, - "USD", - Some(day(2023, 12, 31)), - sample_fields(6.0, 1.5, 1.2, 22.0, 11.0, 1.0), - ), - ]; - let filings = vec![ - filing("NYE", "2023-10-10T16:00:00 EDT", "10-Q"), - filing("NYE", "2023-12-31T21:00:00 EST", "10-Q"), - ]; - - let tmp = TempDirGuard::new("nye"); - let report = curate_and_write_fundamentals( - tmp.path(), - observations.clone(), - filings.clone(), - "qm", - &mapping, - &venues, - 4, - FundamentalsPitWriteOptions::default(), - ) - .expect("curate and write"); - assert_stage_conservation(&report.curate_stats); - assert_eq!(report.curate_stats.filings_dropped_unmapped, 0); - assert_eq!(report.curate_stats.build.rows_linked_to_filing, 2); - assert_eq!( - report.write_stats.rows_by_year, - BTreeMap::from([(2023, 1), (2024, 1)]) - ); - - let curated = - curate_fundamentals(observations, filings, "qm", &mapping, &venues, 4).expect("curate"); - let nye_row = &curated.rows[1]; - assert_eq!( - nye_row.effective_known_at_micros, - utc_micros(2024, 1, 1, 2, 0, 0) - ); - - let y2024 = read_parquet_rows_by_name( - &tmp.path() - .join("fundamentals_pit") - .join("year=2024") - .join("part.parquet"), - ); - assert_eq!(y2024, vec![decoded_from_curated(nye_row)]); - let y2023 = read_parquet_rows_by_name( - &tmp.path() - .join("fundamentals_pit") - .join("year=2023") - .join("part.parquet"), - ); - assert_eq!(y2023, vec![decoded_from_curated(&curated.rows[0])]); -} - -#[test] -fn filing_matching_mapping_only_by_utc_date_is_dropped_unmapped() { - // Mapping starts 2024-05-02 ET. The filing is 2024-05-01T21:00 EDT (= 2024-05-02T01:00Z): - // mapped on its UTC date it would link; on its Eastern date it must not. - let mapping = - ProviderMappingTable::from_rows([mapping_row("qm", "EDGE", day(2024, 5, 2), None, 42)]) - .expect("valid mapping"); - let venues = BTreeMap::from([(42, StatutoryLagVenue::UsTsx)]); - - let out = curate_fundamentals( - [obs( - "EDGE", - day(2024, 6, 30), - FiscalPeriod::Quarterly, - "USD", - None, - sample_fields(1.0, 1.0, 1.0, 1.0, 1.0, 1.0), - )], - [filing("EDGE", "2024-05-01T21:00:00 EDT", "10-Q")], - "qm", - &mapping, - &venues, - 4, - ) - .expect("curate"); - assert_stage_conservation(&out.stats); - assert_eq!(out.stats.filings_in, 1); - assert_eq!(out.stats.filings_dropped_unmapped, 1); - assert_eq!(out.stats.build.filings_in, 0); - assert_eq!(out.stats.observations_dropped_unmapped, 0); - assert_eq!(out.rows.len(), 1); - assert_eq!(out.rows[0].listing_id, 42); -} - -#[test] -fn wrong_mapping_source_drops_everything_and_mapped_listing_without_venue_is_counted_by_builder() { - let mapping = ProviderMappingTable::from_rows([ - mapping_row("qm", "NOVENUE", day(2024, 1, 1), None, 7), - mapping_row("qm", "OK", day(2024, 1, 1), None, 8), - ]) - .expect("valid mapping"); - let venues = BTreeMap::from([(8, StatutoryLagVenue::TsxvCse)]); - let f = sample_fields(3.0, 1.0, 1.0, 9.0, 4.0, 1.0); - let observations = vec![ - obs( - "NOVENUE", - day(2024, 3, 31), - FiscalPeriod::Quarterly, - "CAD", - Some(day(2024, 5, 20)), - f, - ), - obs( - "OK", - day(2024, 3, 31), - FiscalPeriod::Quarterly, - "CAD", - Some(day(2024, 5, 21)), - f, - ), - ]; - let filings = vec![ - filing( - "NOVENUE", - "2024-05-20T16:00:00 EDT", - "Interim financial statements", - ), - filing( - "OK", - "2024-05-21T16:00:00 EDT", - "Interim financial statements", - ), - ]; - - let out = curate_fundamentals( - observations.clone(), - filings.clone(), - "qm", - &mapping, - &venues, - 4, - ) - .expect("curate"); - assert_stage_conservation(&out.stats); - assert_eq!(out.stats.observations_dropped_unmapped, 0); - assert_eq!(out.stats.build.observations_dropped_unknown_key, 1); - assert_eq!(out.stats.build.filings_dropped_unknown_key, 1); - assert_eq!(out.stats.listings_out, 1); - assert_eq!(out.stats.rows_out, 1); - assert_eq!(out.rows[0].listing_id, 8); - - let other = curate_fundamentals(observations, filings, "eodhd", &mapping, &venues, 4) - .expect("other source"); - assert_stage_conservation(&other.stats); - assert_eq!(other.stats.observations_dropped_unmapped, 2); - assert_eq!(other.stats.filings_dropped_unmapped, 2); - assert!(other.rows.is_empty()); - assert_eq!(other.stats.listings_out, 0); -} - -#[test] -fn rebuilding_from_inputs_available_by_each_cutoff_reproduces_the_published_prefix() { - // PIT audit: for each published instant t, rebuild from only the (observation, filing) - // pairs available at or before t; the result must equal the full run's rows with - // effective_known_at <= t. Then append an extreme far-future revision and require every - // earlier row to stay byte-identical. - let mapping = ProviderMappingTable::from_rows([ - mapping_row("qm", "GROW", day(2023, 1, 1), None, 777), - mapping_row("qm", "SMALL", day(2023, 1, 1), None, 555), - ]) - .expect("valid mapping"); - let venues = BTreeMap::from([ - (777, StatutoryLagVenue::UsTsx), - (555, StatutoryLagVenue::TsxvCse), - ]); - let (mut observations, mut filings) = grow_four_quarters(); - observations.push(obs( - "SMALL", - day(2023, 6, 30), - FiscalPeriod::Quarterly, - "CAD", - Some(day(2023, 8, 1)), - sample_fields(2.0, 0.5, 0.4, 8.0, 3.0, 50.0), - )); - filings.push(filing( - "SMALL", - "2023-08-01T16:10:00 EDT", - "Interim financial statements", - )); - observations.push(obs( - "SMALL", - day(2023, 9, 30), - FiscalPeriod::Quarterly, - "CAD", - Some(day(2023, 11, 20)), - sample_fields(2.5, 0.6, 0.5, 9.0, 3.4, 50.0), - )); - filings.push(filing( - "SMALL", - "2023-11-20T09:00:00 EST", - "Interim financial statements", - )); - - let full = curate_fundamentals( - observations.clone(), - filings.clone(), - "qm", - &mapping, - &venues, - 4, - ) - .expect("full"); - assert_eq!(full.rows.len(), 6); - - let pair_known_at: Vec = filings - .iter() - .map(|f| parse_filing_timefiled(&f.timefiled).expect("ts").utc_micros) - .collect(); - for cutoff in full.rows.iter().map(|r| r.effective_known_at_micros) { - let keep: Vec = (0..filings.len()) - .filter(|&i| pair_known_at[i] <= cutoff) - .collect(); - let truncated = curate_fundamentals( - keep.iter().map(|&i| observations[i].clone()), - keep.iter().map(|&i| filings[i].clone()), - "qm", - &mapping, - &venues, - 4, - ) - .expect("truncated"); - let mut expected: Vec = full - .rows - .iter() - .filter(|r| r.effective_known_at_micros <= cutoff) - .cloned() - .collect(); - expected.sort_by_key(|r| (r.listing_id, r.effective_known_at_micros)); - assert_eq!(truncated.rows, expected, "cutoff {cutoff}"); - } - - let mut future_obs = observations.clone(); - future_obs.push(obs( - "GROW", - day(2023, 3, 31), - FiscalPeriod::Quarterly, - "USD", - Some(day(2030, 1, 2)), - sample_fields(1.0e12, -1.0e12, 1.0e12, 1.0e13, -1.0e12, 1.0), - )); - let mut future_filings = filings.clone(); - future_filings.push(filing("GROW", "2030-01-02T16:00:00 EST", "10-Q/A")); - let with_future = curate_fundamentals(future_obs, future_filings, "qm", &mapping, &venues, 4) - .expect("with future revision"); - assert_stage_conservation(&with_future.stats); - let future_at = utc_micros(2030, 1, 2, 21, 0, 0); - let before: Vec<_> = with_future - .rows - .iter() - .filter(|r| r.effective_known_at_micros < future_at) - .cloned() - .collect(); - assert_eq!(before, full.rows); - assert_eq!(with_future.rows.len(), full.rows.len() + 1); -} - -#[test] -fn empty_inputs_yield_no_rows_and_zero_stats() { - let (mapping, venues) = grow_mapping(); - let out = curate_fundamentals( - Vec::>::new(), - Vec::>::new(), - "qm", - &mapping, - &venues, - 4, - ) - .expect("empty"); - assert!(out.rows.is_empty()); - assert_eq!(out.stats, CurateFundamentalsStats::default()); -} diff --git a/tools/curate-etl/src/curate_fx_1m.rs b/tools/curate-etl/src/curate_fx_1m.rs deleted file mode 100644 index 0bdcc390..00000000 --- a/tools/curate-etl/src/curate_fx_1m.rs +++ /dev/null @@ -1,327 +0,0 @@ -//! Pure, in-memory `fx_1m` curation stage for EODHD `CAD.FOREX` 1-minute FX bars (`M2.3k`), -//! joining [`crate::bson_eod_intraday::RawEodIntradayBar`], -//! [`crate::bson_stream::decode_eod_intraday_stream`], and [`crate::ilp::IlpShardedWriter`]. -//! -//! # Contract & Point-in-Time Rules -//! - **Source selection:** accepts only rows whose `eod_search_code` matches -//! [`EOD_CAD_FOREX_CODE`] (`"CAD.FOREX"`) verbatim. Any other code is dropped and counted in -//! [`CurateFx1mStats::dropped_wrong_code`] without erroring. -//! - **No split un-adjustment, listing mapping, or session tagging:** FX trades ~24h and is not -//! subject to equity splits or `provider_mapping` ranges. Every valid `CAD.FOREX` bar is kept -//! with its UTC microsecond bar-start `ts` unchanged (preserving the source clock without -//! implying the bar's close was observable at bar start). -//! - **Rate direction & bitwise preservation:** OHLC values pass through bit-identical in CAD per -//! 1 USD (matching `fx_1d`); `volume` is ignored at the curation layer. -//! - **Canonical labels:** emits `pair = FX_PAIR_USDCAD` (`"USDCAD"`, shared with `fx_1d` so -//! daily and intraday FX tables join on the same label) and `source = FX_1M_SOURCE_EOD` -//! (`"eod"`, fitting QuestDB `SYMBOL CAPACITY 8`). -//! - **Validation precedence:** bad single bars never panic or abort the stage; each bar is -//! classified once in strict priority order: -//! 1. `dropped_wrong_code` (`eod_search_code != "CAD.FOREX"`) -//! 2. `dropped_negative_ts` (`ts < 0`) -//! 3. `dropped_invalid_ohlc` (any of `open`, `high`, `low`, `close` non-finite or `<= 0.0`) -//! 4. `dropped_high_below_bound` (`high < max(open, close, low)`) -//! 5. `dropped_low_above_bound` (`low > min(open, close)`) -//! - **Ordering & deduplication:** surviving rows are sorted ascending by `ts` and compacted in -//! place per timestamp group using `f64::to_bits` equality across all four OHLC fields: -//! bitwise-identical groups of size `n` emit one row (`duplicate_collapsed += n - 1`), while -//! conflicting groups emit zero rows (`duplicate_conflict_dropped += n`). -//! - **Writer lifecycle:** [`curate_and_write_fx_1m`] and [`curate_and_write_fx_1m_from_bson`] -//! stream sorted [`Fx1mRow`]s into a caller-owned [`IlpShardedWriter`] via -//! [`IlpShardedWriter::write_fx_1m`] without calling [`IlpShardedWriter::finish`], allowing -//! multiple chunks to share one writer. -//! -//! # Memory, Chunking & BSON Validation Boundary -//! - **In-memory sort & per-call deduplication:** sorting buffers accepted `CAD.FOREX` rows for a -//! single call in memory, and deduplication applies within that call only. Callers splitting -//! large inputs across calls must keep all copies of a timestamp in the same call and submit -//! chunks in chronological order when global ordering is required. -//! - **BSON validation boundary:** [`curate_and_write_fx_1m_from_bson`] decodes via -//! [`decode_eod_intraday_stream`], which validates non-empty `eodSearchCode`, non-negative -//! integral `timestamp`, finite positive OHLC, and finite non-negative `volume` before invoking -//! the curation accumulator. Document-level decode rejects are accounted in -//! [`BsonEodIntradayDecodeStats`] (so `decode_stats.rows_decoded == write_report.curate_stats.bars_in`), -//! while direct in-memory calls to [`build_fx_1m`] / [`curate_and_write_fx_1m`] exercise the full -//! builder validation rules and ignore `volume`. - -use std::error::Error; -use std::fmt; -use std::io::{self, Write}; - -use crate::bson_eod_intraday::{BsonEodIntradayDecodeStats, RawEodIntradayBar}; -use crate::bson_stream::{decode_eod_intraday_stream, BsonStreamError, BsonStreamOptions}; -use crate::fx::FX_PAIR_USDCAD; -use crate::ilp::{Fx1mRow, IlpShardedWriter, IlpWriterError}; -use crate::run_curate_fx::EOD_CAD_FOREX_CODE; - -/// Canonical provenance label written to [`Fx1mRow::source`] for EODHD `eodIntraday1M` FX bars -/// (`SYMBOL CAPACITY 8`). -pub const FX_1M_SOURCE_EOD: &str = "eod"; - -/// Accounting summary produced alongside [`CurateFx1mOutput::rows`]. -/// -/// Conservation invariant: -/// `bars_in == rows_out + dropped_wrong_code + dropped_negative_ts + dropped_invalid_ohlc + dropped_high_below_bound + dropped_low_above_bound + duplicate_collapsed + duplicate_conflict_dropped` -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct CurateFx1mStats { - pub bars_in: usize, - pub rows_out: usize, - pub dropped_wrong_code: usize, - pub dropped_negative_ts: usize, - pub dropped_invalid_ohlc: usize, - pub dropped_high_below_bound: usize, - pub dropped_low_above_bound: usize, - pub duplicate_collapsed: usize, - pub duplicate_conflict_dropped: usize, -} - -/// Output of [`build_fx_1m`]: curated `fx_1m` rows sorted and unique by `ts`, plus exact -/// accounting statistics. -#[derive(Debug, Clone, PartialEq)] -pub struct CurateFx1mOutput { - pub rows: Vec>, - pub stats: CurateFx1mStats, -} - -/// Summary returned by [`curate_and_write_fx_1m`]. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct CurateFx1mWriteReport { - pub curate_stats: CurateFx1mStats, - /// Number of curated rows accepted by [`IlpShardedWriter::write_fx_1m`] in this call. - pub rows_written: usize, -} - -/// Combined decode and write summary returned by [`curate_and_write_fx_1m_from_bson`]. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct CurateFx1mBsonReport { - pub decode_stats: BsonEodIntradayDecodeStats, - pub write_report: CurateFx1mWriteReport, -} - -/// Typed error returned by [`curate_and_write_fx_1m_from_bson`]. -#[derive(Debug)] -pub enum CurateFx1mBsonError { - Stream(BsonStreamError), - Write(IlpWriterError), -} - -impl fmt::Display for CurateFx1mBsonError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Stream(err) => write!(f, "fx_1m BSON stream failed: {err}"), - Self::Write(err) => write!(f, "fx_1m ILP write failed: {err}"), - } - } -} - -impl Error for CurateFx1mBsonError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::Stream(err) => Some(err), - Self::Write(err) => Some(err), - } - } -} - -impl From for CurateFx1mBsonError { - fn from(err: BsonStreamError) -> Self { - Self::Stream(err) - } -} - -impl From for CurateFx1mBsonError { - fn from(err: IlpWriterError) -> Self { - Self::Write(err) - } -} - -#[inline] -fn is_valid_rate(rate: f64) -> bool { - rate.is_finite() && rate > 0.0 -} - -#[inline] -fn fx_1m_ohlc_bit_eq(a: &Fx1mRow<'_>, b: &Fx1mRow<'_>) -> bool { - a.open.to_bits() == b.open.to_bits() - && a.high.to_bits() == b.high.to_bits() - && a.low.to_bits() == b.low.to_bits() - && a.close.to_bits() == b.close.to_bits() -} - -#[derive(Default)] -struct Fx1mAccumulator { - rows: Vec>, - stats: CurateFx1mStats, -} - -impl Fx1mAccumulator { - #[inline] - fn push(&mut self, bar: RawEodIntradayBar<'_>) { - self.stats.bars_in += 1; - - if bar.eod_search_code != EOD_CAD_FOREX_CODE { - self.stats.dropped_wrong_code += 1; - return; - } - if bar.ts < 0 { - self.stats.dropped_negative_ts += 1; - return; - } - if !is_valid_rate(bar.open) - || !is_valid_rate(bar.high) - || !is_valid_rate(bar.low) - || !is_valid_rate(bar.close) - { - self.stats.dropped_invalid_ohlc += 1; - return; - } - if bar.high < bar.open || bar.high < bar.close || bar.high < bar.low { - self.stats.dropped_high_below_bound += 1; - return; - } - if bar.low > bar.open || bar.low > bar.close { - self.stats.dropped_low_above_bound += 1; - return; - } - - self.rows.push(Fx1mRow { - pair: FX_PAIR_USDCAD, - ts: bar.ts, - open: bar.open, - high: bar.high, - low: bar.low, - close: bar.close, - source: FX_1M_SOURCE_EOD, - }); - } - - fn finish(mut self) -> CurateFx1mOutput { - self.rows.sort_unstable_by_key(|row| row.ts); - - let len = self.rows.len(); - let mut write_idx = 0usize; - let mut read_idx = 0usize; - - while read_idx < len { - let ts = self.rows[read_idx].ts; - let mut group_end = read_idx + 1; - while group_end < len && self.rows[group_end].ts == ts { - group_end += 1; - } - let group_len = group_end - read_idx; - let first = self.rows[read_idx]; - let all_identical = self.rows[read_idx + 1..group_end] - .iter() - .all(|other| fx_1m_ohlc_bit_eq(&first, other)); - - if all_identical { - self.stats.duplicate_collapsed += group_len - 1; - if write_idx != read_idx { - self.rows[write_idx] = first; - } - write_idx += 1; - } else { - self.stats.duplicate_conflict_dropped += group_len; - } - - read_idx = group_end; - } - - self.rows.truncate(write_idx); - self.stats.rows_out = self.rows.len(); - - CurateFx1mOutput { - rows: self.rows, - stats: self.stats, - } - } -} - -fn write_curated_fx_1m( - curated: CurateFx1mOutput, - writer: &mut IlpShardedWriter, -) -> Result { - let mut rows_written = 0usize; - for row in &curated.rows { - writer.write_fx_1m(row)?; - rows_written += 1; - } - - Ok(CurateFx1mWriteReport { - curate_stats: curated.stats, - rows_written, - }) -} - -/// Pure `eodIntraday1M` (`CAD.FOREX`) -> `fx_1m` curation builder. -/// -/// Filters to exact [`EOD_CAD_FOREX_CODE`] rows, validates timestamps and OHLC in strict priority -/// order (ignoring `volume`), sorts ascending by `ts`, and deduplicates same-`ts` groups using -/// bitwise OHLC equality. Valid OHLC and UTC microsecond `ts` pass through unchanged, stamped -/// with `pair = FX_PAIR_USDCAD` and `source = FX_1M_SOURCE_EOD`. -pub fn build_fx_1m<'a, B>(bars: B) -> CurateFx1mOutput -where - B: IntoIterator>, -{ - let mut acc = Fx1mAccumulator::default(); - for bar in bars { - acc.push(bar); - } - acc.finish() -} - -/// Runs [`build_fx_1m`] and streams every curated row in ascending `ts` order into the -/// caller-owned [`IlpShardedWriter`] via [`IlpShardedWriter::write_fx_1m`]. -/// -/// Intentionally does **not** call [`IlpShardedWriter::finish`], so callers may stream multiple -/// chunks through a single writer before flushing and collecting aggregate -/// [`crate::ilp::IlpWriteStats`]. -pub fn curate_and_write_fx_1m<'a, W, B>( - bars: B, - writer: &mut IlpShardedWriter, -) -> Result -where - W: Write + Send, - B: IntoIterator>, -{ - let curated = build_fx_1m(bars); - write_curated_fx_1m(curated, writer) -} - -/// Decodes a concatenated raw BSON `eodIntraday1M` stream via [`decode_eod_intraday_stream`], -/// feeds every decoded [`RawEodIntradayBar`] directly into the `fx_1m` curation accumulator, and -/// streams sorted curated rows into the caller-owned [`IlpShardedWriter`]. -/// -/// - Per-document semantic decode errors are counted and skipped in -/// [`BsonEodIntradayDecodeStats`]; fatal stream framing or I/O errors abort before any row from -/// this call is written to `writer`. -/// - Intentionally does **not** call [`IlpShardedWriter::finish`]. -pub fn curate_and_write_fx_1m_from_bson( - reader: R, - options: BsonStreamOptions, - writer: &mut IlpShardedWriter, -) -> Result -where - R: io::Read, - W: Write + Send, -{ - let mut acc = Fx1mAccumulator::default(); - let decode_stats = decode_eod_intraday_stream( - reader, - options, - |raw| acc.push(raw), - |_offset, _err| {}, - )?; - - let curated = acc.finish(); - let write_report = write_curated_fx_1m(curated, writer)?; - - Ok(CurateFx1mBsonReport { - decode_stats, - write_report, - }) -} - -#[cfg(test)] -#[path = "curate_fx_1m_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/curate_fx_1m_tests.rs b/tools/curate-etl/src/curate_fx_1m_tests.rs deleted file mode 100644 index 8a5622d3..00000000 --- a/tools/curate-etl/src/curate_fx_1m_tests.rs +++ /dev/null @@ -1,560 +0,0 @@ -use std::error::Error; -use std::io::{self, Cursor, Write}; - -use bson::raw::{cstr, RawDocumentBuf}; - -use super::*; -use crate::ilp::{encode_fx_1m, shard_for_fx_pair, IlpWriterOptions}; - -fn raw_bar<'a>( - code: &'a str, - ts: i64, - open: f64, - high: f64, - low: f64, - close: f64, - volume: f64, -) -> RawEodIntradayBar<'a> { - RawEodIntradayBar { - eod_search_code: code, - ts, - open, - high, - low, - close, - volume, - } -} - -fn make_eod_intraday_bson_doc( - code: &str, - ts_seconds: i64, - open: f64, - high: f64, - low: f64, - close: f64, - volume: f64, -) -> RawDocumentBuf { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), code); - doc.append(cstr!("timestamp"), ts_seconds); - doc.append(cstr!("open"), open); - doc.append(cstr!("high"), high); - doc.append(cstr!("low"), low); - doc.append(cstr!("close"), close); - doc.append(cstr!("volume"), volume); - doc -} - -fn assert_conservation_and_order(out: &CurateFx1mOutput) { - let s = &out.stats; - assert_eq!(s.rows_out, out.rows.len(), "rows_out != rows.len(): {s:?}"); - assert_eq!( - s.bars_in, - s.rows_out - + s.dropped_wrong_code - + s.dropped_negative_ts - + s.dropped_invalid_ohlc - + s.dropped_high_below_bound - + s.dropped_low_above_bound - + s.duplicate_collapsed - + s.duplicate_conflict_dropped, - "curate_fx_1m conservation invariant failed: {s:?}" - ); - - for pair in out.rows.windows(2) { - assert!( - pair[0].ts < pair[1].ts, - "rows not strictly ascending by ts: {} >= {}", - pair[0].ts, - pair[1].ts - ); - } - - for row in &out.rows { - assert_eq!(row.pair, FX_PAIR_USDCAD); - assert_eq!(row.source, FX_1M_SOURCE_EOD); - } -} - -struct FailingSink; - -impl Write for FailingSink { - fn write(&mut self, _buf: &[u8]) -> io::Result { - Err(io::Error::new(io::ErrorKind::BrokenPipe, "sink failure")) - } - - fn flush(&mut self) -> io::Result<()> { - Err(io::Error::new(io::ErrorKind::BrokenPipe, "flush failure")) - } -} - -#[test] -fn empty_input_returns_empty_rows_and_zeroed_stats() { - let out = build_fx_1m(std::iter::empty()); - assert!(out.rows.is_empty()); - assert_eq!(out.stats, CurateFx1mStats::default()); - assert_conservation_and_order(&out); -} - -#[test] -fn valid_out_of_order_bars_sort_preserve_ohlc_bits_keep_off_session_and_ignore_volume() { - // 2024-06-09 22:15:00 UTC (Sunday evening FX open, off equity RTH). - let ts_sunday_utc = 1_717_971_300_000_000_i64; - // 2024-06-10 03:00:00 UTC (overnight). - let ts_overnight_utc = 1_717_988_400_000_000_i64; - // Exact epoch start ts = 0 must be accepted. - let ts_zero = 0_i64; - - let b_late = raw_bar( - EOD_CAD_FOREX_CODE, - ts_overnight_utc, - 1.37654321, - 1.37712345, - 1.37611111, - 1.37689012, - -99.0, // invalid volume ignored by builder - ); - let b_zero = raw_bar( - EOD_CAD_FOREX_CODE, - ts_zero, - 1.0725, - 1.0731, - 1.0720, - 1.0728, - f64::NAN, // NaN volume ignored by builder - ); - let b_mid = raw_bar( - EOD_CAD_FOREX_CODE, - ts_sunday_utc, - 1.3750, - 1.3755, - 1.3745, - 1.3752, - f64::INFINITY, // inf volume ignored by builder - ); - // Exact-match failures (case mismatch, trailing space, different ticker) -> dropped, not errored. - let b_lowercase = raw_bar("cad.forex", ts_sunday_utc + 60_000_000, 1.37, 1.38, 1.36, 1.37, 0.0); - let b_padded = raw_bar("CAD.FOREX ", ts_sunday_utc + 120_000_000, 1.37, 1.38, 1.36, 1.37, 0.0); - let b_other = raw_bar("AAPL.US", ts_sunday_utc + 180_000_000, 195.0, 196.0, 194.5, 195.5, 1000.0); - - let out = build_fx_1m([b_late, b_lowercase, b_zero, b_other, b_mid, b_padded]); - assert_conservation_and_order(&out); - - assert_eq!(out.stats.bars_in, 6); - assert_eq!(out.stats.rows_out, 3); - assert_eq!(out.stats.dropped_wrong_code, 3); - assert_eq!(out.stats.dropped_negative_ts, 0); - assert_eq!(out.stats.dropped_invalid_ohlc, 0); - assert_eq!(out.stats.dropped_high_below_bound, 0); - assert_eq!(out.stats.dropped_low_above_bound, 0); - assert_eq!(out.stats.duplicate_collapsed, 0); - assert_eq!(out.stats.duplicate_conflict_dropped, 0); - - let expected_inputs = [b_zero, b_mid, b_late]; - for (row, src) in out.rows.iter().zip(expected_inputs) { - assert_eq!(row.pair, FX_PAIR_USDCAD); - assert_eq!(row.source, FX_1M_SOURCE_EOD); - assert_eq!(row.ts, src.ts); - assert_eq!(row.open.to_bits(), src.open.to_bits()); - assert_eq!(row.high.to_bits(), src.high.to_bits()); - assert_eq!(row.low.to_bits(), src.low.to_bits()); - assert_eq!(row.close.to_bits(), src.close.to_bits()); - } -} - -#[test] -fn every_reject_reason_counted_separately_with_strict_precedence() { - let base_ts = 1_718_000_000_000_000_i64; - let bars = vec![ - // 1. Wrong code (also has negative ts and NaN OHLC to verify wrong_code precedence). - raw_bar("USD.FOREX", -1, f64::NAN, 1.0, 2.0, 0.0, 0.0), - // 2. Negative timestamps (second also has NaN OHLC to verify negative_ts precedence). - raw_bar(EOD_CAD_FOREX_CODE, -1, 1.35, 1.36, 1.34, 1.35, 0.0), - raw_bar(EOD_CAD_FOREX_CODE, i64::MIN, f64::NAN, 1.36, 1.34, 1.35, 0.0), - // 3. Invalid OHLC: NaN, +inf, -inf, +0.0, -0.0, negative price. - raw_bar(EOD_CAD_FOREX_CODE, base_ts, f64::NAN, 1.36, 1.34, 1.35, 0.0), - raw_bar(EOD_CAD_FOREX_CODE, base_ts + 1, 1.35, f64::INFINITY, 1.34, 1.35, 0.0), - raw_bar(EOD_CAD_FOREX_CODE, base_ts + 2, 1.35, 1.36, f64::NEG_INFINITY, 1.35, 0.0), - raw_bar(EOD_CAD_FOREX_CODE, base_ts + 3, 1.35, 1.36, 1.34, 0.0, 0.0), - raw_bar(EOD_CAD_FOREX_CODE, base_ts + 4, -0.0, 1.36, 1.34, 1.35, 0.0), - raw_bar(EOD_CAD_FOREX_CODE, base_ts + 5, 1.35, 1.36, -1.34, 1.35, 0.0), - // 4. high < max(open, close, low): - // - high < open - raw_bar(EOD_CAD_FOREX_CODE, base_ts + 6, 1.37, 1.36, 1.34, 1.35, 0.0), - // - high < close - raw_bar(EOD_CAD_FOREX_CODE, base_ts + 7, 1.35, 1.36, 1.34, 1.37, 0.0), - // - high < low (while high >= open/close is impossible if low > open/close, test open=close=1.35, high=1.35, low=1.36) - raw_bar(EOD_CAD_FOREX_CODE, base_ts + 8, 1.35, 1.35, 1.36, 1.35, 0.0), - // - overlapping high < open AND low > close -> pinned to dropped_high_below_bound - raw_bar(EOD_CAD_FOREX_CODE, base_ts + 9, 1.38, 1.36, 1.37, 1.35, 0.0), - // 5. low > min(open, close) (with high >= max(open, close, low)): - // - low > open - raw_bar(EOD_CAD_FOREX_CODE, base_ts + 10, 1.33, 1.36, 1.34, 1.35, 0.0), - // - low > close - raw_bar(EOD_CAD_FOREX_CODE, base_ts + 11, 1.35, 1.36, 1.34, 1.33, 0.0), - // Valid bar. - raw_bar(EOD_CAD_FOREX_CODE, base_ts + 12, 1.35, 1.36, 1.34, 1.355, 0.0), - ]; - - let out = build_fx_1m(bars); - assert_conservation_and_order(&out); - - assert_eq!(out.stats.bars_in, 16); - assert_eq!(out.stats.dropped_wrong_code, 1); - assert_eq!(out.stats.dropped_negative_ts, 2); - assert_eq!(out.stats.dropped_invalid_ohlc, 6); - assert_eq!(out.stats.dropped_high_below_bound, 4); - assert_eq!(out.stats.dropped_low_above_bound, 2); - assert_eq!(out.stats.duplicate_collapsed, 0); - assert_eq!(out.stats.duplicate_conflict_dropped, 0); - assert_eq!(out.stats.rows_out, 1); - assert_eq!(out.rows[0].ts, base_ts + 12); -} - -#[test] -fn dedup_collapses_identical_ohlc_drops_conflicting_group_and_is_permutation_invariant() { - let ts_identical = 1_718_000_060_000_000_i64; - let ts_conflict = 1_718_000_120_000_000_i64; - let ts_valid_plus_bad = 1_718_000_180_000_000_i64; - - // Group 1: three bitwise-identical OHLC bars with differing volumes -> collapse to 1. - let id1 = raw_bar(EOD_CAD_FOREX_CODE, ts_identical, 1.3610, 1.3620, 1.3605, 1.3615, 0.0); - let id2 = raw_bar(EOD_CAD_FOREX_CODE, ts_identical, 1.3610, 1.3620, 1.3605, 1.3615, 42.0); - let id3 = raw_bar(EOD_CAD_FOREX_CODE, ts_identical, 1.3610, 1.3620, 1.3605, 1.3615, f64::NAN); - - // Group 2: two identical rows + one conflicting close -> drop all 3. - let cf1 = raw_bar(EOD_CAD_FOREX_CODE, ts_conflict, 1.3620, 1.3630, 1.3615, 1.3625, 1.0); - let cf2 = raw_bar(EOD_CAD_FOREX_CODE, ts_conflict, 1.3620, 1.3630, 1.3615, 1.3625, 1.0); - let cf3 = raw_bar(EOD_CAD_FOREX_CODE, ts_conflict, 1.3620, 1.3630, 1.3615, 1.3626, 1.0); - - // Group 3: one valid row + one invalid row at same ts -> invalid rejected early, valid survives. - let ok = raw_bar(EOD_CAD_FOREX_CODE, ts_valid_plus_bad, 1.3630, 1.3640, 1.3625, 1.3635, 0.0); - let bad = raw_bar(EOD_CAD_FOREX_CODE, ts_valid_plus_bad, f64::NAN, 1.3640, 1.3625, 1.3635, 0.0); - - let perm_a = [id1, id2, id3, cf1, cf2, cf3, ok, bad]; - let perm_b = [cf3, bad, id3, cf1, ok, id1, cf2, id2]; - let perm_c = [ok, cf2, id2, cf3, id1, bad, cf1, id3]; - - let out_a = build_fx_1m(perm_a); - let out_b = build_fx_1m(perm_b); - let out_c = build_fx_1m(perm_c); - - assert_conservation_and_order(&out_a); - assert_conservation_and_order(&out_b); - assert_conservation_and_order(&out_c); - assert_eq!(out_a, out_b); - assert_eq!(out_a, out_c); - - assert_eq!(out_a.stats.bars_in, 8); - assert_eq!(out_a.stats.dropped_invalid_ohlc, 1); - assert_eq!(out_a.stats.duplicate_collapsed, 2); - assert_eq!(out_a.stats.duplicate_conflict_dropped, 3); - assert_eq!(out_a.stats.rows_out, 2); - - assert_eq!(out_a.rows[0].ts, ts_identical); - assert_eq!(out_a.rows[0].close.to_bits(), 1.3615_f64.to_bits()); - assert_eq!(out_a.rows[1].ts, ts_valid_plus_bad); - assert_eq!(out_a.rows[1].close.to_bits(), 1.3635_f64.to_bits()); -} - -#[test] -fn writer_streams_two_chunks_through_one_writer_matches_encode_fx_1m_and_routes_one_shard() { - let ts1 = 1_718_000_000_000_000_i64; - let ts2 = 1_718_000_060_000_000_i64; - let ts3 = 1_718_000_120_000_000_i64; - - // Chunk 1 given out of order plus an unrelated ticker. - let chunk1 = [ - raw_bar(EOD_CAD_FOREX_CODE, ts2, 1.3710, 1.3720, 1.3705, 1.3715, 0.0), - raw_bar("EUR.FOREX", ts1, 1.0800, 1.0810, 1.0790, 1.0805, 0.0), - raw_bar(EOD_CAD_FOREX_CODE, ts1, 1.3700, 1.3710, 1.3695, 1.3705, 0.0), - ]; - // Chunk 2 chronologically after chunk 1. - let chunk2 = [raw_bar( - EOD_CAD_FOREX_CODE, - ts3, - 1.3715, - 1.3725, - 1.3710, - 1.3722, - 0.0, - )]; - - let mut s0 = Vec::new(); - let mut s1 = Vec::new(); - let mut s2 = Vec::new(); - let mut s3 = Vec::new(); - let (rep1, rep2, ilp_stats) = { - let mut writer = IlpShardedWriter::new( - vec![&mut s0, &mut s1, &mut s2, &mut s3], - IlpWriterOptions::default(), - ) - .unwrap(); - let rep1 = curate_and_write_fx_1m(chunk1, &mut writer).unwrap(); - // Writer remains open (finish was NOT called) so chunk 2 streams into the same writer. - let rep2 = curate_and_write_fx_1m(chunk2, &mut writer).unwrap(); - let stats = writer.finish().unwrap(); - (rep1, rep2, stats) - }; - - assert_eq!(rep1.curate_stats.bars_in, 3); - assert_eq!(rep1.curate_stats.dropped_wrong_code, 1); - assert_eq!(rep1.curate_stats.rows_out, 2); - assert_eq!(rep1.rows_written, 2); - - assert_eq!(rep2.curate_stats.bars_in, 1); - assert_eq!(rep2.curate_stats.rows_out, 1); - assert_eq!(rep2.rows_written, 1); - - assert_eq!(ilp_stats.rows, rep1.rows_written + rep2.rows_written); - assert_eq!(ilp_stats.rows, 3); - - let expected_rows = [ - Fx1mRow { - pair: FX_PAIR_USDCAD, - ts: ts1, - open: 1.3700, - high: 1.3710, - low: 1.3695, - close: 1.3705, - source: FX_1M_SOURCE_EOD, - }, - Fx1mRow { - pair: FX_PAIR_USDCAD, - ts: ts2, - open: 1.3710, - high: 1.3720, - low: 1.3705, - close: 1.3715, - source: FX_1M_SOURCE_EOD, - }, - Fx1mRow { - pair: FX_PAIR_USDCAD, - ts: ts3, - open: 1.3715, - high: 1.3725, - low: 1.3710, - close: 1.3722, - source: FX_1M_SOURCE_EOD, - }, - ]; - let mut expected_bytes = Vec::new(); - for row in &expected_rows { - encode_fx_1m(&mut expected_bytes, row).unwrap(); - } - - let target_shard = shard_for_fx_pair(FX_PAIR_USDCAD, 4); - let actual_shards = [&s0, &s1, &s2, &s3]; - for (idx, shard_bytes) in actual_shards.iter().enumerate() { - if idx == target_shard { - assert_eq!(*shard_bytes, &expected_bytes, "target shard ILP mismatch"); - } else { - assert!( - shard_bytes.is_empty(), - "non-target shard {idx} should be empty" - ); - } - } - assert_eq!(ilp_stats.per_shard_rows[target_shard], 3); -} - -#[test] -fn bson_stream_handles_mixed_docs_matches_builder_and_supports_writer_reuse() { - let ts1_sec = 1_718_000_000_i64; - let ts2_sec = 1_718_000_060_i64; - let ts3_sec = 1_718_000_120_i64; - - // Out-of-order CAD.FOREX docs + an identical duplicate + a decodable other code + a malformed doc. - let doc_late = - make_eod_intraday_bson_doc(EOD_CAD_FOREX_CODE, ts2_sec, 1.3720, 1.3730, 1.3715, 1.3725, 0.0); - let doc_other = - make_eod_intraday_bson_doc("AAPL.US", ts1_sec, 195.0, 196.0, 194.5, 195.5, 1200.0); - // Correctly framed BSON document missing required field `close`. - let mut doc_missing_close = RawDocumentBuf::new(); - doc_missing_close.append(cstr!("eodSearchCode"), EOD_CAD_FOREX_CODE); - doc_missing_close.append(cstr!("timestamp"), ts1_sec); - doc_missing_close.append(cstr!("open"), 1.3700_f64); - doc_missing_close.append(cstr!("high"), 1.3710_f64); - doc_missing_close.append(cstr!("low"), 1.3695_f64); - doc_missing_close.append(cstr!("volume"), 0.0_f64); - - let doc_early = - make_eod_intraday_bson_doc(EOD_CAD_FOREX_CODE, ts1_sec, 1.3700, 1.3710, 1.3695, 1.3705, 0.0); - let doc_early_dup = - make_eod_intraday_bson_doc(EOD_CAD_FOREX_CODE, ts1_sec, 1.3700, 1.3710, 1.3695, 1.3705, 5.0); - - let mut chunk1_bytes = Vec::new(); - chunk1_bytes.extend_from_slice(doc_late.as_bytes()); - chunk1_bytes.extend_from_slice(doc_other.as_bytes()); - chunk1_bytes.extend_from_slice(doc_missing_close.as_bytes()); - chunk1_bytes.extend_from_slice(doc_early.as_bytes()); - chunk1_bytes.extend_from_slice(doc_early_dup.as_bytes()); - - let doc_chunk2 = - make_eod_intraday_bson_doc(EOD_CAD_FOREX_CODE, ts3_sec, 1.3725, 1.3735, 1.3720, 1.3731, 0.0); - let chunk2_bytes = doc_chunk2.as_bytes().to_vec(); - - // Small chunk capacity forces multi-chunk framing across documents. - let stream_opts = BsonStreamOptions { - chunk_capacity_bytes: 64, - max_doc_bytes: 4096, - }; - - let mut s0 = Vec::new(); - let mut s1 = Vec::new(); - let (rep1, rep2, ilp_stats) = { - let mut writer = IlpShardedWriter::new( - vec![&mut s0, &mut s1], - IlpWriterOptions::default(), - ) - .unwrap(); - let rep1 = - curate_and_write_fx_1m_from_bson(Cursor::new(&chunk1_bytes), stream_opts, &mut writer) - .unwrap(); - let rep2 = - curate_and_write_fx_1m_from_bson(Cursor::new(&chunk2_bytes), stream_opts, &mut writer) - .unwrap(); - let stats = writer.finish().unwrap(); - (rep1, rep2, stats) - }; - - // Decode accounting: 5 docs seen = 4 decoded + 1 missing_field reject. - assert_eq!(rep1.decode_stats.docs_seen, 5); - assert_eq!(rep1.decode_stats.rows_decoded, 4); - assert_eq!(rep1.decode_stats.rejected_missing_field, 1); - assert_eq!( - rep1.decode_stats.docs_seen, - rep1.decode_stats.rows_decoded + rep1.decode_stats.rejected_total() - ); - - // Builder input equals rows_decoded. - assert_eq!( - rep1.write_report.curate_stats.bars_in, - rep1.decode_stats.rows_decoded - ); - assert_eq!(rep1.write_report.curate_stats.dropped_wrong_code, 1); - assert_eq!(rep1.write_report.curate_stats.duplicate_collapsed, 1); - assert_eq!(rep1.write_report.curate_stats.rows_out, 2); - assert_eq!(rep1.write_report.rows_written, 2); - - // Compare chunk 1 curation stats directly against `build_fx_1m` on the same decoded inputs. - let direct_expected = build_fx_1m([ - raw_bar(EOD_CAD_FOREX_CODE, ts2_sec * 1_000_000, 1.3720, 1.3730, 1.3715, 1.3725, 0.0), - raw_bar("AAPL.US", ts1_sec * 1_000_000, 195.0, 196.0, 194.5, 195.5, 1200.0), - raw_bar(EOD_CAD_FOREX_CODE, ts1_sec * 1_000_000, 1.3700, 1.3710, 1.3695, 1.3705, 0.0), - raw_bar(EOD_CAD_FOREX_CODE, ts1_sec * 1_000_000, 1.3700, 1.3710, 1.3695, 1.3705, 5.0), - ]); - assert_eq!(rep1.write_report.curate_stats, direct_expected.stats); - - // Chunk 2 stats & aggregate ILP stats. - assert_eq!(rep2.decode_stats.docs_seen, 1); - assert_eq!(rep2.decode_stats.rows_decoded, 1); - assert_eq!(rep2.write_report.rows_written, 1); - assert_eq!(ilp_stats.rows, 3); - - // Exact ILP bytes match `encode_fx_1m` of chunk 1 + chunk 2 expected rows in order. - let mut expected_bytes = Vec::new(); - for row in &direct_expected.rows { - encode_fx_1m(&mut expected_bytes, row).unwrap(); - } - encode_fx_1m( - &mut expected_bytes, - &Fx1mRow { - pair: FX_PAIR_USDCAD, - ts: ts3_sec * 1_000_000, - open: 1.3725, - high: 1.3735, - low: 1.3720, - close: 1.3731, - source: FX_1M_SOURCE_EOD, - }, - ) - .unwrap(); - - let target_shard = shard_for_fx_pair(FX_PAIR_USDCAD, 2); - let other_shard = 1 - target_shard; - let shards = [&s0, &s1]; - assert_eq!(shards[target_shard], &expected_bytes); - assert!(shards[other_shard].is_empty()); -} - -#[test] -fn truncated_bson_stream_fails_closed_with_zero_rows_written_and_typed_errors_format() { - let doc1 = make_eod_intraday_bson_doc( - EOD_CAD_FOREX_CODE, - 1_718_000_000, - 1.3700, - 1.3710, - 1.3695, - 1.3705, - 0.0, - ); - let doc2 = make_eod_intraday_bson_doc( - EOD_CAD_FOREX_CODE, - 1_718_000_060, - 1.3710, - 1.3720, - 1.3705, - 1.3715, - 0.0, - ); - - let mut truncated_bytes = Vec::new(); - truncated_bytes.extend_from_slice(doc1.as_bytes()); - let doc2_bytes = doc2.as_bytes(); - truncated_bytes.extend_from_slice(&doc2_bytes[..doc2_bytes.len() / 2]); - - let mut s0 = Vec::new(); - let mut s1 = Vec::new(); - let (stream_err, stats) = { - let mut writer = IlpShardedWriter::new( - vec![&mut s0, &mut s1], - IlpWriterOptions { - max_batch_bytes: 1024, - max_batch_rows: 1, - }, - ) - .unwrap(); - let err = curate_and_write_fx_1m_from_bson( - Cursor::new(&truncated_bytes), - BsonStreamOptions::default(), - &mut writer, - ) - .unwrap_err(); - let stats = writer.finish().unwrap(); - (err, stats) - }; - - assert!(matches!( - stream_err, - CurateFx1mBsonError::Stream(BsonStreamError::TruncatedDocument { .. }) - )); - assert!(stream_err.source().is_some()); - assert!(stream_err.to_string().contains("fx_1m BSON stream failed")); - assert_eq!(stats.rows, 0); - assert!(s0.is_empty()); - assert!(s1.is_empty()); - - // Writer I/O failure surfaces as `CurateFx1mBsonError::Write(IlpWriterError::Io { .. })`. - let mut failing_writer = IlpShardedWriter::new( - vec![FailingSink], - IlpWriterOptions { - max_batch_bytes: 1024, - max_batch_rows: 1, - }, - ) - .unwrap(); - let write_err = curate_and_write_fx_1m_from_bson( - Cursor::new(doc1.as_bytes()), - BsonStreamOptions::default(), - &mut failing_writer, - ) - .unwrap_err(); - assert!(matches!( - write_err, - CurateFx1mBsonError::Write(IlpWriterError::Io { shard: 0, .. }) - )); - assert!(write_err.source().is_some()); - assert!(write_err.to_string().contains("fx_1m ILP write failed")); -} diff --git a/tools/curate-etl/src/curate_macro.rs b/tools/curate-etl/src/curate_macro.rs deleted file mode 100644 index 73fb72ff..00000000 --- a/tools/curate-etl/src/curate_macro.rs +++ /dev/null @@ -1,347 +0,0 @@ -//! Pure, in-memory `macro` curation stage joining [`crate::bson_te_data::TeDataPoint`], -//! [`crate::macro_series::build_macro_rows`], and -//! [`crate::parquet_macro::write_macro_dataset`] into contract [`MacroParquetRow`]s. -//! -//! # Governance & Contract Rules -//! - **Caller-owned series mapping:** Every [`TeDataPoint`] carries verbatim provider -//! `(te_symbol, country, category)` labels. No country-to-ISO, indicator-name, or lag-class -//! mapping is hardcoded here because live `teData` labels are unverified and Quant Research owns -//! the coarse regime-use policy. -//! - **Fail-closed unmapped drop:** Points whose `(te_symbol, country, category)` maps to `None` -//! are dropped and counted in [`CurateMacroStats::dropped_unmapped_series`] without ever -//! assigning a default publication lag. -//! - **Fail-closed lag-class consistency:** If two mapped points reach the same -//! `(country_iso, indicator)` target with different [`MacroLagClass`] values (even if one point -//! has a non-finite value), curation fails with [`CurateMacroError::ConflictingLagClass`] -//! naming the first conflicting target in ascending `(country_iso, indicator)` key order, -//! independent of input order. -//! - **Delegated builder semantics:** Mapped observations pass unchanged to [`build_macro_rows`] -//! for finite-value filtering, sorting, bitwise deduplication / conflict detection, and -//! estimated `known_at` calculation (`00:00:00 UTC` of `period_date + lag_days`, -//! `known_at_source = "publication_lag_estimate"`). Output rows are converted via -//! [`MacroParquetRow::from`] in strictly ascending, unique `(country_iso, indicator, period_date)` -//! order. - -use std::collections::BTreeMap; -use std::error::Error; -use std::fmt; -use std::path::Path; - -use crate::bson_te_data::TeDataPoint; -use crate::macro_series::{ - build_macro_rows, MacroBuildStats, MacroError, MacroLagClass, MacroObservation, -}; -use crate::parquet_macro::{ - write_macro_dataset, MacroParquetRow, MacroWriteOptions, MacroWriteStats, ParquetMacroError, -}; - -/// Caller-supplied mapping target for a provider `teData` series. -#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct MacroSeriesTarget { - pub country_iso: String, - pub indicator: String, - pub lag_class: MacroLagClass, -} - -/// Accounting summary produced alongside [`CurateMacroOutput::rows`]. -/// -/// Conservation invariants: -/// - `points_in == dropped_unmapped_series + builder.input` -/// - `rows_out == builder.emitted` -/// - `builder` independently satisfies -/// `builder.input == builder.emitted + builder.skipped_unmapped_indicator + builder.skipped_non_finite_value + builder.skipped_duplicate` -/// (with `builder.skipped_unmapped_indicator == 0` because unmapped series are filtered before -/// calling [`build_macro_rows`]). -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct CurateMacroStats { - pub builder: MacroBuildStats, - pub points_in: usize, - pub rows_out: usize, - pub dropped_unmapped_series: usize, - pub series_out: usize, -} - -/// Output of [`curate_macro`]: contract Parquet rows strictly ascending and unique by -/// `(country_iso, indicator, period_date)` and reconciling stage + builder stats. -#[derive(Debug, Clone, PartialEq)] -pub struct CurateMacroOutput { - pub rows: Vec, - pub stats: CurateMacroStats, -} - -/// Typed error returned by [`curate_macro`]. -/// -/// Every variant's `Display` output is guaranteed to be a single line. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum CurateMacroError { - /// One `(country_iso, indicator)` target was reached with two different [`MacroLagClass`] - /// values across mapped points. `first_lag_class < second_lag_class` in [`MacroLagClass`] - /// `Ord` order so the error is identical for any input permutation. - ConflictingLagClass { - country_iso: String, - indicator: String, - first_lag_class: MacroLagClass, - second_lag_class: MacroLagClass, - }, - /// Error propagated from [`build_macro_rows`] (`ConflictingDuplicate` or `KnownAtOverflow`). - Macro(MacroError), -} - -fn fmt_single_line(f: &mut fmt::Formatter<'_>, text: &str) -> fmt::Result { - for ch in text.chars() { - match ch { - '\n' => f.write_str("\\n")?, - '\r' => f.write_str("\\r")?, - other => fmt::Write::write_char(f, other)?, - } - } - Ok(()) -} - -impl fmt::Display for CurateMacroError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::ConflictingLagClass { - country_iso, - indicator, - first_lag_class, - second_lag_class, - } => write!( - f, - "conflicting lag classes for macro target ({country_iso:?}, {indicator:?}): {first_lag_class:?} (+{}d) vs {second_lag_class:?} (+{}d)", - first_lag_class.lag_days(), - second_lag_class.lag_days(), - ), - Self::Macro(err) => fmt_single_line(f, &err.to_string()), - } - } -} - -impl Error for CurateMacroError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::ConflictingLagClass { .. } => None, - Self::Macro(err) => Some(err), - } - } -} - -impl From> for CurateMacroError { - fn from(err: MacroError) -> Self { - Self::Macro(err) - } -} - -/// Combined stats returned by [`curate_and_write_macro`]. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct CurateMacroWriteReport { - pub curate_stats: CurateMacroStats, - pub write_stats: MacroWriteStats, -} - -/// Typed error returned by [`curate_and_write_macro`]. -/// -/// Every variant's `Display` output is guaranteed to be a single line. -#[derive(Debug)] -pub enum CurateMacroWriteError { - Curate(CurateMacroError), - Parquet(ParquetMacroError), -} - -impl fmt::Display for CurateMacroWriteError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Curate(err) => { - f.write_str("macro curation failed: ")?; - fmt_single_line(f, &err.to_string()) - } - Self::Parquet(err) => { - f.write_str("macro Parquet write failed: ")?; - fmt_single_line(f, &err.to_string()) - } - } - } -} - -impl Error for CurateMacroWriteError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::Curate(err) => Some(err), - Self::Parquet(err) => Some(err), - } - } -} - -impl From for CurateMacroWriteError { - fn from(err: CurateMacroError) -> Self { - Self::Curate(err) - } -} - -impl From for CurateMacroWriteError { - fn from(err: ParquetMacroError) -> Self { - Self::Parquet(err) - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum LagAssignment { - Single(MacroLagClass), - Conflict { - min_class: MacroLagClass, - max_class: MacroLagClass, - }, -} - -impl LagAssignment { - #[inline] - fn record(&mut self, lag_class: MacroLagClass) { - match *self { - Self::Single(existing) if existing == lag_class => {} - Self::Single(existing) => { - *self = Self::Conflict { - min_class: existing.min(lag_class), - max_class: existing.max(lag_class), - }; - } - Self::Conflict { - min_class, - max_class, - } => { - *self = Self::Conflict { - min_class: min_class.min(lag_class), - max_class: max_class.max(lag_class), - }; - } - } - } - - #[inline] - fn single(&self) -> Option { - match *self { - Self::Single(class) => Some(class), - Self::Conflict { .. } => None, - } - } -} - -/// Pure `macro` curation stage: maps decoded [`TeDataPoint`]s via the caller-supplied -/// `(te_symbol, country, category) -> Option` lookup, verifies lag-class -/// consistency per `(country_iso, indicator)` target, delegates filtering, deduplication, and -/// `known_at` derivation to [`build_macro_rows`], and emits contract [`MacroParquetRow`]s -/// strictly ascending and unique by `(country_iso, indicator, period_date)`. -/// -/// The caller lookup `series_for` must be deterministic/stable for each verbatim -/// `(te_symbol, country, category)` triple. Any permutation of `points` produces identical `rows` -/// (including `f64` bit patterns) and `stats`, or the same [`CurateMacroError`]. -pub fn curate_macro<'a, I, F>( - points: I, - series_for: F, -) -> Result -where - I: IntoIterator>, - F: Fn(&str, &str, &str) -> Option, -{ - let iter = points.into_iter(); - let (lower, _) = iter.size_hint(); - let mut stats = CurateMacroStats::default(); - let mut observations: Vec> = Vec::with_capacity(lower); - let mut target_lags: BTreeMap> = BTreeMap::new(); - - for point in iter { - stats.points_in += 1; - let Some(target) = series_for(point.te_symbol, point.country, point.category) else { - stats.dropped_unmapped_series += 1; - continue; - }; - - if let Some(assignment) = target_lags - .get_mut(&target.country_iso) - .and_then(|by_indicator| by_indicator.get_mut(&target.indicator)) - { - assignment.record(target.lag_class); - } else { - target_lags - .entry(target.country_iso.clone()) - .or_default() - .insert( - target.indicator.clone(), - LagAssignment::Single(target.lag_class), - ); - } - - observations.push(MacroObservation { - country_iso: target.country_iso, - indicator: target.indicator, - period_date: point.period_date, - value: point.value, - }); - } - - for (country_iso, by_indicator) in &target_lags { - for (indicator, assignment) in by_indicator { - if let LagAssignment::Conflict { - min_class, - max_class, - } = *assignment - { - return Err(CurateMacroError::ConflictingLagClass { - country_iso: country_iso.clone(), - indicator: indicator.clone(), - first_lag_class: min_class, - second_lag_class: max_class, - }); - } - } - } - - let built = build_macro_rows(observations, |country_iso, indicator| { - target_lags - .get(country_iso.as_str()) - .and_then(|by_indicator| by_indicator.get(indicator.as_str())) - .and_then(LagAssignment::single) - })?; - - stats.builder = built.stats; - let rows: Vec = built.rows.iter().map(MacroParquetRow::from).collect(); - stats.rows_out = rows.len(); - - let mut last_series: Option<(&str, &str)> = None; - for row in &rows { - let series = (row.country_iso.as_ref(), row.indicator.as_ref()); - if last_series != Some(series) { - stats.series_out += 1; - last_series = Some(series); - } - } - - Ok(CurateMacroOutput { rows, stats }) -} - -/// Thin end-to-end wrapper running [`curate_macro`] and publishing the resulting contract rows -/// via [`write_macro_dataset`] to `/macro/part.parquet`. -/// -/// Any [`CurateMacroError`] returns before [`write_macro_dataset`] is invoked, leaving `out_dir` -/// and any pre-existing `macro/part.parquet` completely untouched. -pub fn curate_and_write_macro<'a, P, I, F>( - out_dir: P, - points: I, - series_for: F, - options: MacroWriteOptions, -) -> Result -where - P: AsRef, - I: IntoIterator>, - F: Fn(&str, &str, &str) -> Option, -{ - let curated = curate_macro(points, series_for)?; - let write_stats = write_macro_dataset(out_dir, &curated.rows, options)?; - Ok(CurateMacroWriteReport { - curate_stats: curated.stats, - write_stats, - }) -} - -#[cfg(test)] -#[path = "curate_macro_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/curate_macro_tests.rs b/tools/curate-etl/src/curate_macro_tests.rs deleted file mode 100644 index c7c6a291..00000000 --- a/tools/curate-etl/src/curate_macro_tests.rs +++ /dev/null @@ -1,1564 +0,0 @@ -use std::borrow::Cow; -use std::error::Error as StdError; -use std::fs::{self, File}; -use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; - -use bson::raw::{cstr, RawArrayBuf, RawDocumentBuf}; -use bson::DateTime; -use parquet::column::reader::ColumnReader; -use parquet::file::reader::{FileReader, SerializedFileReader}; - -use super::{ - curate_and_write_macro, curate_macro, CurateMacroError, CurateMacroStats, - CurateMacroWriteError, MacroSeriesTarget, -}; -use crate::bson_te_data::{decode_te_data_doc, TeDataPoint}; -use crate::macro_series::{ - MacroError, MacroLagClass, GDP65_LAG_DAYS, GDP90_LAG_DAYS, MACRO_KNOWN_AT_SOURCE, - MONTHLY_RELEASE_LAG_DAYS, POLICY_RATE_LAG_DAYS, -}; -use crate::parquet_macro::{ - write_macro_dataset, MacroParquetRow, MacroWriteOptions, MacroWriteStats, ParquetMacroError, -}; -use crate::split::ymd_to_epoch_days; - -const MICROS_PER_DAY: i64 = 86_400_000_000; - -static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0); - -struct TempDirGuard { - path: PathBuf, -} - -impl TempDirGuard { - fn new(label: &str) -> Self { - let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); - let pid = std::process::id(); - let path = - std::env::temp_dir().join(format!("curate-etl-curate-macro-test-{label}-{pid}-{seq}")); - let _ = fs::remove_dir_all(&path); - fs::create_dir_all(&path).expect("create test temp dir"); - Self { path } - } - - fn path(&self) -> &Path { - &self.path - } -} - -impl Drop for TempDirGuard { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.path); - } -} - -fn day(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).expect("valid date") -} - -fn make_point_doc(d: &str, v: f64) -> RawDocumentBuf { - let mut pt = RawDocumentBuf::new(); - pt.append(cstr!("d"), d); - pt.append(cstr!("v"), v); - pt -} - -fn make_te_data_doc( - te_symbol: &str, - country: &str, - category: &str, - data_points: &[(&str, f64)], - forecast_points: &[(&str, f64)], -) -> RawDocumentBuf { - let mut data_arr = RawArrayBuf::new(); - for &(d, v) in data_points { - data_arr.push(make_point_doc(d, v)); - } - - let mut forecast_arr = RawArrayBuf::new(); - for &(d, v) in forecast_points { - forecast_arr.push(make_point_doc(d, v)); - } - - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("teSymbol"), te_symbol); - doc.append(cstr!("name"), format!("{country} {category}")); - doc.append(cstr!("unit"), "percent"); - doc.append(cstr!("source"), "TradingEconomics"); - doc.append(cstr!("frequency"), "Monthly"); - doc.append(cstr!("country"), country); - doc.append(cstr!("category"), category); - doc.append(cstr!("data"), data_arr); - doc.append(cstr!("forecast"), forecast_arr); - doc.append( - cstr!("lastUpdated"), - DateTime::from_millis(1_710_000_000_000), - ); - doc.append(cstr!("createdAt"), DateTime::from_millis(1_700_000_000_000)); - doc -} - -fn target(country_iso: &str, indicator: &str, lag_class: MacroLagClass) -> MacroSeriesTarget { - MacroSeriesTarget { - country_iso: country_iso.to_owned(), - indicator: indicator.to_owned(), - lag_class, - } -} - -fn expected_row( - country_iso: &'static str, - indicator: &'static str, - period_date: i32, - lag_days: i32, - value: f64, -) -> MacroParquetRow { - MacroParquetRow { - country_iso: Cow::Borrowed(country_iso), - indicator: Cow::Borrowed(indicator), - period_date, - known_at_micros: i64::from(period_date + lag_days) * MICROS_PER_DAY, - known_at_source: Cow::Borrowed(MACRO_KNOWN_AT_SOURCE), - value, - } -} - -fn read_parquet_rows(path: &Path) -> Vec { - let file = File::open(path).expect("open parquet file"); - let reader = SerializedFileReader::new(file).expect("open parquet reader"); - let metadata = reader.metadata(); - let mut out = Vec::new(); - - for rg_idx in 0..metadata.num_row_groups() { - let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); - let num_rows = metadata.row_group(rg_idx).num_rows() as usize; - - let read_i32 = |col_idx: usize| -> Vec { - let mut vals = Vec::with_capacity(num_rows); - match rg_reader.get_column_reader(col_idx).expect("col reader") { - ColumnReader::Int32ColumnReader(mut r) => { - let (read, _, _) = r - .read_records(num_rows, None, None, &mut vals) - .expect("read i32"); - assert_eq!(read, num_rows); - } - _ => panic!("expected INT32 column at index {col_idx}"), - } - vals - }; - let read_i64 = |col_idx: usize| -> Vec { - let mut vals = Vec::with_capacity(num_rows); - match rg_reader.get_column_reader(col_idx).expect("col reader") { - ColumnReader::Int64ColumnReader(mut r) => { - let (read, _, _) = r - .read_records(num_rows, None, None, &mut vals) - .expect("read i64"); - assert_eq!(read, num_rows); - } - _ => panic!("expected INT64 column at index {col_idx}"), - } - vals - }; - let read_f64 = |col_idx: usize| -> Vec { - let mut vals = Vec::with_capacity(num_rows); - match rg_reader.get_column_reader(col_idx).expect("col reader") { - ColumnReader::DoubleColumnReader(mut r) => { - let (read, _, _) = r - .read_records(num_rows, None, None, &mut vals) - .expect("read f64"); - assert_eq!(read, num_rows); - } - _ => panic!("expected DOUBLE column at index {col_idx}"), - } - vals - }; - let read_str = |col_idx: usize| -> Vec { - let mut vals = Vec::with_capacity(num_rows); - match rg_reader.get_column_reader(col_idx).expect("col reader") { - ColumnReader::ByteArrayColumnReader(mut r) => { - let (read, _, _) = r - .read_records(num_rows, None, None, &mut vals) - .expect("read utf8"); - assert_eq!(read, num_rows); - } - _ => panic!("expected BYTE_ARRAY column at index {col_idx}"), - } - vals.into_iter() - .map(|b| { - std::str::from_utf8(b.data()) - .expect("valid utf8") - .to_owned() - }) - .collect() - }; - - let country_iso = read_str(0); - let indicator = read_str(1); - let period_date = read_i32(2); - let known_at_micros = read_i64(3); - let known_at_source = read_str(4); - let value = read_f64(5); - - for i in 0..num_rows { - out.push(MacroParquetRow { - country_iso: Cow::Owned(country_iso[i].clone()), - indicator: Cow::Owned(indicator[i].clone()), - period_date: period_date[i], - known_at_micros: known_at_micros[i], - known_at_source: Cow::Owned(known_at_source[i].clone()), - value: value[i], - }); - } - } - out -} - -fn assert_rows_bitwise_eq(actual: &[MacroParquetRow], expected: &[MacroParquetRow]) { - assert_eq!(actual.len(), expected.len(), "row count mismatch"); - for (idx, (a, e)) in actual.iter().zip(expected.iter()).enumerate() { - assert_eq!(a.country_iso, e.country_iso, "row {idx} country_iso"); - assert_eq!(a.indicator, e.indicator, "row {idx} indicator"); - assert_eq!(a.period_date, e.period_date, "row {idx} period_date"); - assert_eq!( - a.known_at_micros, e.known_at_micros, - "row {idx} known_at_micros" - ); - assert_eq!( - a.known_at_source, e.known_at_source, - "row {idx} known_at_source" - ); - assert_eq!( - a.value.to_bits(), - e.value.to_bits(), - "row {idx} value bits ({} vs {})", - a.value, - e.value - ); - } -} - -fn assert_strictly_ascending_unique(rows: &[MacroParquetRow]) { - for pair in rows.windows(2) { - let prev = ( - pair[0].country_iso.as_ref(), - pair[0].indicator.as_ref(), - pair[0].period_date, - ); - let next = ( - pair[1].country_iso.as_ref(), - pair[1].indicator.as_ref(), - pair[1].period_date, - ); - assert!( - prev < next, - "rows not strictly ascending and unique: {prev:?} >= {next:?}" - ); - } -} - -fn assert_stats_conserved(stats: &CurateMacroStats) { - assert_eq!( - stats.points_in, - stats.dropped_unmapped_series + stats.builder.input, - "stage input conservation failed: {stats:?}" - ); - assert_eq!( - stats.rows_out, stats.builder.emitted, - "stage output conservation failed: {stats:?}" - ); - assert_eq!( - stats.builder.skipped_unmapped_indicator, 0, - "builder should never observe unmapped indicators from stage: {stats:?}" - ); - assert_eq!( - stats.builder.input, - stats.builder.emitted - + stats.builder.skipped_unmapped_indicator - + stats.builder.skipped_non_finite_value - + stats.builder.skipped_duplicate, - "builder conservation failed: {stats:?}" - ); -} - -fn sorted_dir_entries(dir: &Path) -> Vec { - if !dir.exists() { - return Vec::new(); - } - let mut entries: Vec = fs::read_dir(dir) - .expect("read dir") - .map(|entry| { - entry - .expect("dir entry") - .file_name() - .to_string_lossy() - .into_owned() - }) - .collect(); - entries.sort(); - entries -} - -fn seed_existing_parquet(out_dir: &Path) -> (PathBuf, Vec, Vec) { - let seed = vec![ - expected_row( - "CA", - "policy_rate", - day(2024, 1, 24), - POLICY_RATE_LAG_DAYS, - 5.0, - ), - expected_row( - "US", - "cpi_yoy", - day(2024, 1, 31), - MONTHLY_RELEASE_LAG_DAYS, - 3.1, - ), - ]; - write_macro_dataset(out_dir, &seed, MacroWriteOptions::default()).expect("seed parquet"); - let part = out_dir.join("macro/part.parquet"); - let bytes = fs::read(&part).expect("read seeded parquet"); - let entries = sorted_dir_entries(&out_dir.join("macro")); - (part, bytes, entries) -} - -#[test] -fn decode_te_data_bson_curate_and_write_all_four_lag_classes_without_forecast_leakage() { - let docs = vec![ - make_te_data_doc( - "USGDPQOQ", - "United States", - "GDP Growth Rate", - &[("2024-03-31", 1.4), ("2024-06-30", -0.0)], - &[("2025-12-31", 99.9)], - ), - make_te_data_doc( - "CAGDPQOQ", - "Canada", - "GDP Growth Rate", - &[("2024-03-31", -0.25)], - &[("2026-03-31", 88.8)], - ), - make_te_data_doc( - "USCPIYOY", - "United States", - "Inflation Rate", - &[("2024-02-29", 3.2), ("2024-01-31", 3.1)], - &[("2025-06-30", 77.7)], - ), - make_te_data_doc( - "CABOCRATE", - "Canada", - "Interest Rate", - &[("2024-01-24", 5.0), ("2024-06-05", 0.0)], - &[("2025-09-30", 66.6)], - ), - make_te_data_doc( - "UKUNEMP", - "United Kingdom", - "Unemployment Rate", - &[("2024-01-31", 4.2)], - &[("2025-10-31", 55.5)], - ), - ]; - - let mut decoded_points: Vec> = Vec::new(); - let mut decode_errors = Vec::new(); - let mut total_points_in = 0usize; - let mut total_points_decoded = 0usize; - for doc in &docs { - let stats = decode_te_data_doc( - doc.as_ref(), - |pt| decoded_points.push(pt), - |err| decode_errors.push(err), - ); - assert_eq!(stats.docs_accepted, 1); - assert_eq!(stats.docs_rejected_total(), 0); - assert_eq!(stats.rejected_total(), 0); - total_points_in += stats.points_in; - total_points_decoded += stats.points_decoded; - } - assert!( - decode_errors.is_empty(), - "unexpected decode errors: {decode_errors:?}" - ); - // Only the 8 historical data points were decoded; none of the 5 forecast points leaked. - assert_eq!(total_points_in, 8); - assert_eq!(total_points_decoded, 8); - assert_eq!(decoded_points.len(), 8); - - let series_map = - |te_symbol: &str, country: &str, category: &str| match (te_symbol, country, category) { - ("CABOCRATE", "Canada", "Interest Rate") => { - Some(target("CA", "policy_rate", MacroLagClass::PolicyRate)) - } - ("USCPIYOY", "United States", "Inflation Rate") => { - Some(target("US", "cpi_yoy", MacroLagClass::MonthlyRelease)) - } - ("USGDPQOQ", "United States", "GDP Growth Rate") => { - Some(target("US", "gdp_qoq", MacroLagClass::Gdp65)) - } - ("CAGDPQOQ", "Canada", "GDP Growth Rate") => { - Some(target("CA", "gdp_qoq", MacroLagClass::Gdp90)) - } - _ => None, - }; - - let tmp = TempDirGuard::new("bson-roundtrip"); - let report = curate_and_write_macro( - tmp.path(), - decoded_points, - series_map, - MacroWriteOptions::default(), - ) - .expect("curate_and_write_macro should succeed"); - - assert_stats_conserved(&report.curate_stats); - assert_eq!(report.curate_stats.points_in, 8); - assert_eq!(report.curate_stats.dropped_unmapped_series, 1); - assert_eq!(report.curate_stats.builder.input, 7); - assert_eq!(report.curate_stats.builder.emitted, 7); - assert_eq!(report.curate_stats.rows_out, 7); - assert_eq!(report.curate_stats.series_out, 4); - assert_eq!(report.write_stats.rows_written, 7); - assert_eq!(report.write_stats.files_written, 1); - - let part_path = tmp.path().join("macro/part.parquet"); - assert!(part_path.exists()); - assert_eq!( - sorted_dir_entries(&tmp.path().join("macro")), - vec!["part.parquet"] - ); - - let read_back = read_parquet_rows(&part_path); - assert_strictly_ascending_unique(&read_back); - - let expected = vec![ - expected_row("CA", "gdp_qoq", day(2024, 3, 31), GDP90_LAG_DAYS, -0.25), - expected_row( - "CA", - "policy_rate", - day(2024, 1, 24), - POLICY_RATE_LAG_DAYS, - 5.0, - ), - expected_row( - "CA", - "policy_rate", - day(2024, 6, 5), - POLICY_RATE_LAG_DAYS, - 0.0, - ), - expected_row( - "US", - "cpi_yoy", - day(2024, 1, 31), - MONTHLY_RELEASE_LAG_DAYS, - 3.1, - ), - expected_row( - "US", - "cpi_yoy", - day(2024, 2, 29), - MONTHLY_RELEASE_LAG_DAYS, - 3.2, - ), - expected_row("US", "gdp_qoq", day(2024, 3, 31), GDP65_LAG_DAYS, 1.4), - expected_row("US", "gdp_qoq", day(2024, 6, 30), GDP65_LAG_DAYS, -0.0), - ]; - assert_rows_bitwise_eq(&read_back, &expected); - - // Explicitly verify each lag class UTC midnight timestamp and provenance label, and absence of - // all forecast dates. - let forecast_dates = [ - day(2025, 12, 31), - day(2026, 3, 31), - day(2025, 6, 30), - day(2025, 9, 30), - day(2025, 10, 31), - ]; - for row in &read_back { - assert_eq!(row.known_at_source.as_ref(), MACRO_KNOWN_AT_SOURCE); - assert_eq!(row.known_at_source.as_ref(), "publication_lag_estimate"); - assert_eq!(row.known_at_micros % MICROS_PER_DAY, 0); - assert!( - !forecast_dates.contains(&row.period_date), - "forecast date leaked into output: {row:?}" - ); - } - assert_eq!( - read_back[0].known_at_micros, - i64::from(day(2024, 3, 31) + 90) * MICROS_PER_DAY - ); - assert_eq!( - read_back[1].known_at_micros, - i64::from(day(2024, 1, 24) + 1) * MICROS_PER_DAY - ); - assert_eq!( - read_back[3].known_at_micros, - i64::from(day(2024, 1, 31) + 35) * MICROS_PER_DAY - ); - assert_eq!( - read_back[5].known_at_micros, - i64::from(day(2024, 3, 31) + 65) * MICROS_PER_DAY - ); -} - -#[test] -fn permutation_invariance_unmapped_duplicates_and_non_finite_accounting() { - let base_points = vec![ - // Mapped US cpi_yoy (+35d): two dates + exact duplicate + NaN + +inf - TeDataPoint { - te_symbol: "USCPIYOY", - country: "United States", - category: "Inflation Rate", - period_date: day(2024, 2, 29), - value: 3.2, - }, - TeDataPoint { - te_symbol: "USCPIYOY", - country: "United States", - category: "Inflation Rate", - period_date: day(2024, 1, 31), - value: 3.1, - }, - TeDataPoint { - te_symbol: "USCPIYOY", - country: "United States", - category: "Inflation Rate", - period_date: day(2024, 1, 31), - value: 3.1, - }, - TeDataPoint { - te_symbol: "USCPIYOY", - country: "United States", - category: "Inflation Rate", - period_date: day(2024, 3, 31), - value: f64::NAN, - }, - TeDataPoint { - te_symbol: "USCPIYOY", - country: "United States", - category: "Inflation Rate", - period_date: day(2024, 4, 30), - value: f64::INFINITY, - }, - // Mapped CA policy_rate (+1d): one finite + one -inf - TeDataPoint { - te_symbol: "CABOCRATE", - country: "Canada", - category: "Interest Rate", - period_date: day(2024, 1, 24), - value: 5.0, - }, - TeDataPoint { - te_symbol: "CABOCRATE", - country: "Canada", - category: "Interest Rate", - period_date: day(2024, 3, 6), - value: f64::NEG_INFINITY, - }, - // Unmapped tuples: case difference, whitespace difference, and unknown series - TeDataPoint { - te_symbol: "uscpiyoy", - country: "United States", - category: "Inflation Rate", - period_date: day(2024, 1, 31), - value: 9.9, - }, - TeDataPoint { - te_symbol: "USCPIYOY ", - country: "United States", - category: "Inflation Rate", - period_date: day(2024, 1, 31), - value: 9.9, - }, - TeDataPoint { - te_symbol: "DEUNEMP", - country: "Germany", - category: "Unemployment Rate", - period_date: day(2024, 1, 31), - value: 5.9, - }, - ]; - - let series_map = - |te_symbol: &str, country: &str, category: &str| match (te_symbol, country, category) { - ("USCPIYOY", "United States", "Inflation Rate") => { - Some(target("US", "cpi_yoy", MacroLagClass::MonthlyRelease)) - } - ("CABOCRATE", "Canada", "Interest Rate") => { - Some(target("CA", "policy_rate", MacroLagClass::PolicyRate)) - } - _ => None, - }; - - let mut reversed = base_points.clone(); - reversed.reverse(); - - let interleaved: Vec> = vec![ - base_points[9], - base_points[5], - base_points[2], - base_points[7], - base_points[4], - base_points[0], - base_points[8], - base_points[6], - base_points[3], - base_points[1], - ]; - - let out_base = curate_macro(base_points, series_map).expect("base ok"); - let out_rev = curate_macro(reversed, series_map).expect("reversed ok"); - let out_inter = curate_macro(interleaved, series_map).expect("interleaved ok"); - - for out in [&out_base, &out_rev, &out_inter] { - assert_strictly_ascending_unique(&out.rows); - assert_stats_conserved(&out.stats); - assert_eq!(out.stats.points_in, 10); - assert_eq!(out.stats.dropped_unmapped_series, 3); - assert_eq!(out.stats.builder.input, 7); - assert_eq!(out.stats.builder.emitted, 3); - assert_eq!(out.stats.builder.skipped_non_finite_value, 3); - assert_eq!(out.stats.builder.skipped_duplicate, 1); - assert_eq!(out.stats.rows_out, 3); - assert_eq!(out.stats.series_out, 2); - } - - assert_eq!(out_base.stats, out_rev.stats); - assert_eq!(out_base.stats, out_inter.stats); - assert_rows_bitwise_eq(&out_base.rows, &out_rev.rows); - assert_rows_bitwise_eq(&out_base.rows, &out_inter.rows); - - let expected = vec![ - expected_row( - "CA", - "policy_rate", - day(2024, 1, 24), - POLICY_RATE_LAG_DAYS, - 5.0, - ), - expected_row( - "US", - "cpi_yoy", - day(2024, 1, 31), - MONTHLY_RELEASE_LAG_DAYS, - 3.1, - ), - expected_row( - "US", - "cpi_yoy", - day(2024, 2, 29), - MONTHLY_RELEASE_LAG_DAYS, - 3.2, - ), - ]; - assert_rows_bitwise_eq(&out_base.rows, &expected); -} - -#[test] -fn empty_and_all_unmapped_inputs_produce_zero_rows_and_do_not_touch_out_dir() { - let never_map = |_: &str, _: &str, _: &str| -> Option { None }; - - // 1. Fresh directory with empty input - let fresh_empty = TempDirGuard::new("fresh-empty"); - let report = curate_and_write_macro( - fresh_empty.path(), - std::iter::empty::>(), - never_map, - MacroWriteOptions::default(), - ) - .expect("empty input succeeds"); - assert_stats_conserved(&report.curate_stats); - assert_eq!(report.curate_stats.points_in, 0); - assert_eq!(report.curate_stats.rows_out, 0); - assert_eq!(report.curate_stats.series_out, 0); - assert_eq!(report.write_stats, MacroWriteStats::default()); - assert!(!fresh_empty.path().join("macro").exists()); - - // 2. Fresh directory with all-unmapped input - let fresh_unmapped = TempDirGuard::new("fresh-unmapped"); - let unmapped = [TeDataPoint { - te_symbol: "UNKNOWN", - country: "Nowhere", - category: "Mystery", - period_date: day(2024, 1, 1), - value: 1.0, - }]; - let report = curate_and_write_macro( - fresh_unmapped.path(), - unmapped, - never_map, - MacroWriteOptions::default(), - ) - .expect("all-unmapped input succeeds"); - assert_stats_conserved(&report.curate_stats); - assert_eq!(report.curate_stats.points_in, 1); - assert_eq!(report.curate_stats.dropped_unmapped_series, 1); - assert_eq!(report.curate_stats.rows_out, 0); - assert_eq!(report.curate_stats.series_out, 0); - assert_eq!(report.write_stats, MacroWriteStats::default()); - assert!(!fresh_unmapped.path().join("macro").exists()); - - // 3. Pre-existing part.parquet is preserved byte-identical on all-unmapped input - let existing = TempDirGuard::new("existing-unmapped"); - let (part, before_bytes, before_entries) = seed_existing_parquet(existing.path()); - let report = curate_and_write_macro( - existing.path(), - unmapped, - never_map, - MacroWriteOptions::default(), - ) - .expect("all-unmapped against existing succeeds"); - assert_eq!(report.write_stats, MacroWriteStats::default()); - assert_eq!(fs::read(&part).expect("read after"), before_bytes); - assert_eq!( - sorted_dir_entries(&existing.path().join("macro")), - before_entries - ); -} - -#[test] -fn conflicting_duplicate_and_signed_zero_propagate_macro_error() { - let map_cpi = - |_: &str, _: &str, _: &str| Some(target("US", "cpi_yoy", MacroLagClass::MonthlyRelease)); - - // Unequal finite values at same (country_iso, indicator, period_date) - let unequal = [ - TeDataPoint { - te_symbol: "USCPIYOY", - country: "United States", - category: "Inflation Rate", - period_date: day(2024, 1, 31), - value: 3.1, - }, - TeDataPoint { - te_symbol: "USCPIYOY", - country: "United States", - category: "Inflation Rate", - period_date: day(2024, 1, 31), - value: 3.2, - }, - ]; - let err = curate_macro(unequal, map_cpi).expect_err("unequal duplicate must fail"); - assert_eq!( - err, - CurateMacroError::Macro(MacroError::ConflictingDuplicate { - country_iso: "US".to_owned(), - indicator: "cpi_yoy".to_owned(), - period_date: day(2024, 1, 31), - }) - ); - assert!(err.source().is_some()); - - // Opposite signed zeros (+0.0 vs -0.0) at same (country_iso, indicator, period_date) - let signed_zeros = [ - TeDataPoint { - te_symbol: "USCPIYOY", - country: "United States", - category: "Inflation Rate", - period_date: day(2024, 2, 29), - value: 0.0, - }, - TeDataPoint { - te_symbol: "USCPIYOY", - country: "United States", - category: "Inflation Rate", - period_date: day(2024, 2, 29), - value: -0.0, - }, - ]; - let err = curate_macro(signed_zeros, map_cpi).expect_err("signed zero conflict must fail"); - assert_eq!( - err, - CurateMacroError::Macro(MacroError::ConflictingDuplicate { - country_iso: "US".to_owned(), - indicator: "cpi_yoy".to_owned(), - period_date: day(2024, 2, 29), - }) - ); -} - -#[test] -fn conflicting_lag_class_is_order_independent_and_checks_before_non_finite_filtering() { - // Two distinct provider aliases targeting the same (country_iso, indicator) on different dates - // with different lag classes, including one non-finite point. - let p_gdp65 = TeDataPoint { - te_symbol: "USGDP_FAST", - country: "United States", - category: "GDP Growth Rate", - period_date: day(2024, 3, 31), - value: 1.4, - }; - let p_gdp90_nan = TeDataPoint { - te_symbol: "USGDP_SLOW", - country: "United States", - category: "GDP Growth Rate Revised", - period_date: day(2024, 6, 30), - value: f64::NAN, - }; - - let alias_map = |te_symbol: &str, _: &str, _: &str| match te_symbol { - "USGDP_FAST" => Some(target("US", "gdp_qoq", MacroLagClass::Gdp65)), - "USGDP_SLOW" => Some(target("US", "gdp_qoq", MacroLagClass::Gdp90)), - _ => None, - }; - - let err_ab = curate_macro([p_gdp65, p_gdp90_nan], alias_map).expect_err("order A must fail"); - let err_ba = curate_macro([p_gdp90_nan, p_gdp65], alias_map).expect_err("order B must fail"); - - let expected = CurateMacroError::ConflictingLagClass { - country_iso: "US".to_owned(), - indicator: "gdp_qoq".to_owned(), - first_lag_class: MacroLagClass::Gdp65, - second_lag_class: MacroLagClass::Gdp90, - }; - assert_eq!(err_ab, expected); - assert_eq!(err_ba, expected); - assert!(err_ab.source().is_none()); - - // Multiple conflicting targets: always report the lowest (country_iso, indicator) in key order. - let ca_rate_a = TeDataPoint { - te_symbol: "CA_A", - country: "Canada", - category: "Rate", - period_date: day(2024, 1, 1), - value: 5.0, - }; - let ca_rate_b = TeDataPoint { - te_symbol: "CA_B", - country: "Canada", - category: "Rate", - period_date: day(2024, 2, 1), - value: 5.0, - }; - let multi_map = |te_symbol: &str, _: &str, _: &str| match te_symbol { - "USGDP_FAST" => Some(target("US", "gdp_qoq", MacroLagClass::Gdp65)), - "USGDP_SLOW" => Some(target("US", "gdp_qoq", MacroLagClass::Gdp90)), - "CA_A" => Some(target("CA", "policy_rate", MacroLagClass::PolicyRate)), - "CA_B" => Some(target("CA", "policy_rate", MacroLagClass::MonthlyRelease)), - _ => None, - }; - - let err_multi_1 = curate_macro([p_gdp65, p_gdp90_nan, ca_rate_a, ca_rate_b], multi_map) - .expect_err("multi 1 must fail"); - let err_multi_2 = curate_macro([ca_rate_b, p_gdp90_nan, ca_rate_a, p_gdp65], multi_map) - .expect_err("multi 2 must fail"); - assert_eq!( - err_multi_1, - CurateMacroError::ConflictingLagClass { - country_iso: "CA".to_owned(), - indicator: "policy_rate".to_owned(), - first_lag_class: MacroLagClass::PolicyRate, - second_lag_class: MacroLagClass::MonthlyRelease, - } - ); - assert_eq!(err_multi_1, err_multi_2); -} - -#[test] -fn known_at_overflow_and_invalid_write_options_and_single_line_display() { - // 1. KnownAtOverflow propagated from build_macro_rows - let overflow_pt = [TeDataPoint { - te_symbol: "EXTREME", - country: "United States", - category: "GDP", - period_date: i32::MAX, - value: 1.0, - }]; - let map_gdp90 = |_: &str, _: &str, _: &str| Some(target("US", "gdp", MacroLagClass::Gdp90)); - let err = curate_macro(overflow_pt, map_gdp90).expect_err("overflow must fail"); - assert_eq!( - err, - CurateMacroError::Macro(MacroError::KnownAtOverflow { - period_date: i32::MAX, - lag_class: MacroLagClass::Gdp90, - }) - ); - assert!(err.source().is_some()); - let msg = err.to_string(); - assert!( - !msg.contains('\n') && !msg.contains('\r'), - "multi-line: {msg:?}" - ); - - // 2. InvalidRowGroupRows wrapped in CurateMacroWriteError::Parquet - let tmp = TempDirGuard::new("invalid-opts"); - let valid_pt = [TeDataPoint { - te_symbol: "CABOCRATE", - country: "Canada", - category: "Interest Rate", - period_date: day(2024, 1, 24), - value: 5.0, - }]; - let map_rate = - |_: &str, _: &str, _: &str| Some(target("CA", "policy_rate", MacroLagClass::PolicyRate)); - let write_err = curate_and_write_macro( - tmp.path(), - valid_pt, - map_rate, - MacroWriteOptions { - row_group_rows: 0, - ..MacroWriteOptions::default() - }, - ) - .expect_err("row_group_rows=0 must fail"); - assert!(matches!( - write_err, - CurateMacroWriteError::Parquet(ParquetMacroError::InvalidRowGroupRows) - )); - assert!(write_err.source().is_some()); - let msg = write_err.to_string(); - assert!( - !msg.contains('\n') && !msg.contains('\r'), - "multi-line: {msg:?}" - ); - - // 3. Newline-bearing diagnostic labels stay single-line in both CurateMacroError and - // CurateMacroWriteError (covering ConflictingLagClass, ConflictingDuplicate, and Parquet). - let nl_lag_err = CurateMacroWriteError::from(CurateMacroError::ConflictingLagClass { - country_iso: "US\nline2".to_owned(), - indicator: "cpi\r\nyoy".to_owned(), - first_lag_class: MacroLagClass::PolicyRate, - second_lag_class: MacroLagClass::MonthlyRelease, - }); - let nl_lag_msg = nl_lag_err.to_string(); - assert!( - !nl_lag_msg.contains('\n') && !nl_lag_msg.contains('\r'), - "ConflictingLagClass display must be single-line: {nl_lag_msg:?}" - ); - assert!(nl_lag_msg.contains("US\\nline2")); - assert!(nl_lag_msg.contains("cpi\\r\\nyoy")); - - let nl_dup_err = - CurateMacroWriteError::from(CurateMacroError::from(MacroError::ConflictingDuplicate { - country_iso: "CA\n2".to_owned(), - indicator: "gdp\r3".to_owned(), - period_date: day(2024, 1, 1), - })); - let nl_dup_msg = nl_dup_err.to_string(); - assert!( - !nl_dup_msg.contains('\n') && !nl_dup_msg.contains('\r'), - "ConflictingDuplicate display must be single-line: {nl_dup_msg:?}" - ); - - // ParquetMacroError::EmptyCountryIso displays `indicator` with `{indicator}`, so newlines - // would leak unless CurateMacroWriteError escapes them. - let nl_pq_err = curate_and_write_macro( - tmp.path(), - valid_pt, - |_: &str, _: &str, _: &str| { - Some(target( - " ", - "bad\nindicator\rname", - MacroLagClass::PolicyRate, - )) - }, - MacroWriteOptions::default(), - ) - .expect_err("blank country_iso must fail in writer"); - assert!(matches!( - nl_pq_err, - CurateMacroWriteError::Parquet(ParquetMacroError::EmptyCountryIso { .. }) - )); - let nl_pq_msg = nl_pq_err.to_string(); - assert!( - !nl_pq_msg.contains('\n') && !nl_pq_msg.contains('\r'), - "Parquet display must be single-line: {nl_pq_msg:?}" - ); - assert!(nl_pq_msg.contains("bad\\nindicator\\rname")); -} - -#[test] -fn curation_errors_never_write_or_modify_out_dir() { - // 1. ConflictingLagClass - let lag_conflict_points = [ - TeDataPoint { - te_symbol: "A", - country: "US", - category: "GDP", - period_date: day(2024, 3, 31), - value: 1.4, - }, - TeDataPoint { - te_symbol: "B", - country: "US", - category: "GDP", - period_date: day(2024, 6, 30), - value: 1.8, - }, - ]; - let lag_conflict_map = |sym: &str, _: &str, _: &str| match sym { - "A" => Some(target("US", "gdp", MacroLagClass::Gdp65)), - "B" => Some(target("US", "gdp", MacroLagClass::Gdp90)), - _ => None, - }; - - // 2. ConflictingDuplicate - let dup_conflict_points = [ - TeDataPoint { - te_symbol: "A", - country: "US", - category: "CPI", - period_date: day(2024, 1, 31), - value: 3.1, - }, - TeDataPoint { - te_symbol: "A", - country: "US", - category: "CPI", - period_date: day(2024, 1, 31), - value: 3.2, - }, - ]; - let cpi_map = - |_: &str, _: &str, _: &str| Some(target("US", "cpi_yoy", MacroLagClass::MonthlyRelease)); - - // 3. KnownAtOverflow - let overflow_points = [TeDataPoint { - te_symbol: "A", - country: "US", - category: "GDP", - period_date: i32::MAX, - value: 1.0, - }]; - let gdp_map = |_: &str, _: &str, _: &str| Some(target("US", "gdp", MacroLagClass::Gdp90)); - - // Fresh destination checks - for (label, result, dir) in [ - { - let dir = TempDirGuard::new("err-fresh-lag"); - let res = curate_and_write_macro( - dir.path(), - lag_conflict_points, - lag_conflict_map, - MacroWriteOptions::default(), - ); - ("ConflictingLagClass", res, dir) - }, - { - let dir = TempDirGuard::new("err-fresh-dup"); - let res = curate_and_write_macro( - dir.path(), - dup_conflict_points, - cpi_map, - MacroWriteOptions::default(), - ); - ("ConflictingDuplicate", res, dir) - }, - { - let dir = TempDirGuard::new("err-fresh-overflow"); - let res = curate_and_write_macro( - dir.path(), - overflow_points, - gdp_map, - MacroWriteOptions::default(), - ); - ("KnownAtOverflow", res, dir) - }, - ] { - let err = result.expect_err(&format!("{label} must fail")); - assert!( - matches!(err, CurateMacroWriteError::Curate(_)), - "{label} should be Curate error: {err}" - ); - assert!( - !dir.path().join("macro").exists(), - "{label} must not create macro/ dir" - ); - assert!( - sorted_dir_entries(dir.path()).is_empty(), - "{label} must leave fresh out_dir empty" - ); - } - - // Existing valid macro/part.parquet preservation checks - for (label, result, part, before_bytes, before_entries, dir) in [ - { - let dir = TempDirGuard::new("err-existing-lag"); - let (part, before_bytes, before_entries) = seed_existing_parquet(dir.path()); - let res = curate_and_write_macro( - dir.path(), - lag_conflict_points, - lag_conflict_map, - MacroWriteOptions::default(), - ); - ( - "ConflictingLagClass", - res, - part, - before_bytes, - before_entries, - dir, - ) - }, - { - let dir = TempDirGuard::new("err-existing-dup"); - let (part, before_bytes, before_entries) = seed_existing_parquet(dir.path()); - let res = curate_and_write_macro( - dir.path(), - dup_conflict_points, - cpi_map, - MacroWriteOptions::default(), - ); - ( - "ConflictingDuplicate", - res, - part, - before_bytes, - before_entries, - dir, - ) - }, - { - let dir = TempDirGuard::new("err-existing-overflow"); - let (part, before_bytes, before_entries) = seed_existing_parquet(dir.path()); - let res = curate_and_write_macro( - dir.path(), - overflow_points, - gdp_map, - MacroWriteOptions::default(), - ); - ( - "KnownAtOverflow", - res, - part, - before_bytes, - before_entries, - dir, - ) - }, - ] { - let err = result.expect_err(&format!("{label} must fail")); - assert!( - matches!(err, CurateMacroWriteError::Curate(_)), - "{label} should be Curate error: {err}" - ); - assert_eq!( - fs::read(&part).expect("read existing parquet"), - before_bytes, - "{label} must leave existing part.parquet byte-identical" - ); - assert_eq!( - sorted_dir_entries(&dir.path().join("macro")), - before_entries, - "{label} must leave macro/ directory entries unchanged" - ); - } -} - -fn te_point( - te_symbol: &'static str, - country: &'static str, - category: &'static str, - period_date: i32, - value: f64, -) -> TeDataPoint<'static> { - TeDataPoint { - te_symbol, - country, - category, - period_date, - value, - } -} - -#[test] -fn mapped_target_with_only_non_finite_values_does_not_count_as_emitted_series() { - let points = vec![ - te_point( - "USCPIYOY", - "United States", - "Inflation Rate", - day(2024, 1, 31), - 3.1, - ), - te_point( - "CABOCRATE", - "Canada", - "Interest Rate", - day(2024, 1, 24), - 5.0, - ), - te_point( - "DEGDP", - "Germany", - "GDP Growth Rate", - day(2024, 3, 31), - f64::NAN, - ), - te_point( - "DEGDP", - "Germany", - "GDP Growth Rate", - day(2024, 6, 30), - f64::INFINITY, - ), - te_point( - "DEGDP", - "Germany", - "GDP Growth Rate", - day(2024, 9, 30), - f64::NEG_INFINITY, - ), - ]; - let series_map = |te_symbol: &str, _: &str, _: &str| match te_symbol { - "USCPIYOY" => Some(target("US", "cpi_yoy", MacroLagClass::MonthlyRelease)), - "CABOCRATE" => Some(target("CA", "policy_rate", MacroLagClass::PolicyRate)), - "DEGDP" => Some(target("DE", "gdp_qoq", MacroLagClass::Gdp65)), - _ => None, - }; - - let mut reversed = points.clone(); - reversed.reverse(); - let rotated: Vec<_> = points[2..] - .iter() - .chain(points[..2].iter()) - .copied() - .collect(); - - let mut outputs = Vec::new(); - for perm in [points, reversed, rotated] { - let out = curate_macro(perm, series_map).expect("curation succeeds"); - assert_stats_conserved(&out.stats); - assert_eq!(out.stats.points_in, 5); - assert_eq!(out.stats.dropped_unmapped_series, 0); - assert_eq!(out.stats.builder.input, 5); - assert_eq!(out.stats.builder.skipped_non_finite_value, 3); - assert_eq!(out.stats.builder.emitted, 2); - assert_eq!(out.stats.rows_out, 2); - assert_eq!( - out.stats.series_out, 2, - "non-finite-only target must not count" - ); - assert!(out.rows.iter().all(|r| r.country_iso != "DE")); - outputs.push(out); - } - assert_eq!(outputs[0].stats, outputs[1].stats); - assert_eq!(outputs[0].stats, outputs[2].stats); - assert_rows_bitwise_eq(&outputs[0].rows, &outputs[1].rows); - assert_rows_bitwise_eq(&outputs[0].rows, &outputs[2].rows); -} - -#[test] -fn lookup_receives_verbatim_provider_labels_once_per_point() { - use std::cell::RefCell; - - let points = [ - te_point( - " USCPIYOY", - "United States ", - "Inflation\tRate", - day(2024, 1, 31), - 3.1, - ), - te_point( - "cabocrate", - "CANADA", - "Interest Rate", - day(2024, 1, 24), - 5.0, - ), - te_point( - "ÜMLAUT", - "Österreich", - "Kategorie", - day(2024, 2, 1), - f64::NAN, - ), - ]; - let calls: RefCell> = RefCell::new(Vec::new()); - let out = curate_macro(points, |s: &str, c: &str, k: &str| { - calls - .borrow_mut() - .push((s.to_owned(), c.to_owned(), k.to_owned())); - None - }) - .expect("all-unmapped succeeds"); - - assert_eq!( - calls.into_inner(), - vec![ - ( - " USCPIYOY".into(), - "United States ".into(), - "Inflation\tRate".into() - ), - ("cabocrate".into(), "CANADA".into(), "Interest Rate".into()), - ("ÜMLAUT".into(), "Österreich".into(), "Kategorie".into()), - ] - ); - assert_stats_conserved(&out.stats); - assert_eq!(out.stats.dropped_unmapped_series, 3); - assert_eq!(out.stats.builder.input, 0); - // Unmapped non-finite points never reach the builder's non-finite counter. - assert_eq!(out.stats.builder.skipped_non_finite_value, 0); - assert!(out.rows.is_empty()); -} - -#[test] -fn unmapped_points_never_trigger_builder_errors() { - // Unmapped points that would overflow known_at or conflict with a mapped value are dropped - // before build_macro_rows, so they cannot fail the stage. - let points = [ - te_point( - "USCPIYOY", - "United States", - "Inflation Rate", - day(2024, 1, 31), - 3.1, - ), - te_point( - "USCPIYOY_ALT", - "United States", - "Inflation Rate", - day(2024, 1, 31), - 9.9, - ), - te_point("EXTREME", "United States", "GDP", i32::MAX, 1.0), - ]; - let series_map = |te_symbol: &str, _: &str, _: &str| match te_symbol { - "USCPIYOY" => Some(target("US", "cpi_yoy", MacroLagClass::MonthlyRelease)), - _ => None, - }; - let out = curate_macro(points, series_map).expect("unmapped points must be ignored"); - assert_stats_conserved(&out.stats); - assert_eq!(out.stats.dropped_unmapped_series, 2); - assert_rows_bitwise_eq( - &out.rows, - &[expected_row( - "US", - "cpi_yoy", - day(2024, 1, 31), - MONTHLY_RELEASE_LAG_DAYS, - 3.1, - )], - ); -} - -#[test] -fn aliases_with_same_lag_class_merge_into_one_series_and_cross_alias_duplicates_collapse() { - let points = [ - te_point( - "USCPIYOY", - "United States", - "Inflation Rate", - day(2024, 1, 31), - 3.1, - ), - te_point("USCPI_ALT", "USA", "CPI YoY", day(2024, 1, 31), 3.1), - te_point("USCPI_ALT", "USA", "CPI YoY", day(2024, 2, 29), 3.2), - ]; - let series_map = |te_symbol: &str, _: &str, _: &str| match te_symbol { - "USCPIYOY" | "USCPI_ALT" => Some(target("US", "cpi_yoy", MacroLagClass::MonthlyRelease)), - _ => None, - }; - let out = curate_macro(points, series_map).expect("same lag class is not a conflict"); - assert_stats_conserved(&out.stats); - assert_eq!(out.stats.builder.skipped_duplicate, 1); - assert_eq!(out.stats.series_out, 1); - assert_rows_bitwise_eq( - &out.rows, - &[ - expected_row( - "US", - "cpi_yoy", - day(2024, 1, 31), - MONTHLY_RELEASE_LAG_DAYS, - 3.1, - ), - expected_row( - "US", - "cpi_yoy", - day(2024, 2, 29), - MONTHLY_RELEASE_LAG_DAYS, - 3.2, - ), - ], - ); - - // Cross-alias conflicting values on the same target/date are rejected by the builder. - let conflicting = [ - te_point( - "USCPIYOY", - "United States", - "Inflation Rate", - day(2024, 1, 31), - 3.1, - ), - te_point("USCPI_ALT", "USA", "CPI YoY", day(2024, 1, 31), 3.0), - ]; - assert_eq!( - curate_macro(conflicting, series_map).expect_err("cross-alias conflict"), - CurateMacroError::Macro(MacroError::ConflictingDuplicate { - country_iso: "US".to_owned(), - indicator: "cpi_yoy".to_owned(), - period_date: day(2024, 1, 31), - }) - ); -} - -#[test] -fn same_indicator_in_different_countries_may_use_different_lag_classes() { - let points = [ - te_point("USGDP", "United States", "GDP", day(2024, 3, 31), 1.4), - te_point("CAGDP", "Canada", "GDP", day(2024, 3, 31), 0.5), - ]; - let series_map = |te_symbol: &str, _: &str, _: &str| match te_symbol { - "USGDP" => Some(target("US", "gdp_qoq", MacroLagClass::Gdp65)), - "CAGDP" => Some(target("CA", "gdp_qoq", MacroLagClass::Gdp90)), - _ => None, - }; - let out = curate_macro(points, series_map).expect("per-country lag classes are independent"); - assert_eq!(out.stats.series_out, 2); - assert_rows_bitwise_eq( - &out.rows, - &[ - expected_row("CA", "gdp_qoq", day(2024, 3, 31), GDP90_LAG_DAYS, 0.5), - expected_row("US", "gdp_qoq", day(2024, 3, 31), GDP65_LAG_DAYS, 1.4), - ], - ); -} - -#[test] -fn three_way_lag_conflict_reports_min_and_max_class_for_every_order() { - let a = te_point("A", "X", "Y", day(2024, 1, 31), 1.0); - let b = te_point("B", "X", "Y", day(2024, 2, 29), 2.0); - let c = te_point("C", "X", "Y", day(2024, 3, 31), 3.0); - let series_map = |te_symbol: &str, _: &str, _: &str| match te_symbol { - "A" => Some(target("US", "mix", MacroLagClass::MonthlyRelease)), - "B" => Some(target("US", "mix", MacroLagClass::Gdp90)), - "C" => Some(target("US", "mix", MacroLagClass::PolicyRate)), - _ => None, - }; - let expected = CurateMacroError::ConflictingLagClass { - country_iso: "US".to_owned(), - indicator: "mix".to_owned(), - first_lag_class: MacroLagClass::PolicyRate, - second_lag_class: MacroLagClass::Gdp90, - }; - for perm in [ - [a, b, c], - [a, c, b], - [b, a, c], - [b, c, a], - [c, a, b], - [c, b, a], - ] { - assert_eq!( - curate_macro(perm, series_map).expect_err("conflict"), - expected - ); - } - let msg = expected.to_string(); - assert!(msg.contains("+1d") && msg.contains("+90d"), "{msg}"); -} - -#[test] -fn write_error_source_chain_reaches_macro_error() { - let points = [ - te_point("A", "US", "CPI", day(2024, 1, 31), 3.1), - te_point("A", "US", "CPI", day(2024, 1, 31), 3.2), - ]; - let tmp = TempDirGuard::new("source-chain"); - let err = curate_and_write_macro( - tmp.path(), - points, - |_: &str, _: &str, _: &str| Some(target("US", "cpi_yoy", MacroLagClass::MonthlyRelease)), - MacroWriteOptions::default(), - ) - .expect_err("duplicate conflict"); - let lvl1 = err.source().expect("curate error source"); - assert!(lvl1.downcast_ref::().is_some()); - let lvl2 = lvl1.source().expect("macro error source"); - assert!(lvl2.downcast_ref::>().is_some()); - assert!(err.to_string().starts_with("macro curation failed: ")); -} - -#[test] -fn successful_write_replaces_existing_part_parquet_with_curated_rows() { - let tmp = TempDirGuard::new("replace-existing"); - let (part, before_bytes, _) = seed_existing_parquet(tmp.path()); - - let points = [te_point( - "USGDP", - "United States", - "GDP", - day(2024, 6, 30), - 2.8, - )]; - let report = curate_and_write_macro( - tmp.path(), - points, - |_: &str, _: &str, _: &str| Some(target("US", "gdp_qoq", MacroLagClass::Gdp90)), - MacroWriteOptions::default(), - ) - .expect("write succeeds"); - assert_eq!(report.write_stats.rows_written, 1); - assert_ne!(fs::read(&part).expect("read after"), before_bytes); - assert_eq!( - sorted_dir_entries(&tmp.path().join("macro")), - vec!["part.parquet"] - ); - assert_rows_bitwise_eq( - &read_parquet_rows(&part), - &[expected_row( - "US", - "gdp_qoq", - day(2024, 6, 30), - GDP90_LAG_DAYS, - 2.8, - )], - ); -} - -#[test] -fn extreme_finite_values_and_pre_epoch_dates_round_trip_bitwise_through_write() { - // Arrange: one Monthly1 series with pre-1970 and extreme-but-finite values. - let subnormal = f64::from_bits(1); - let neg_subnormal = -f64::from_bits(1); - let cases: [(i32, f64); 6] = [ - (day(1950, 1, 31), -0.0), - (day(1969, 12, 31), subnormal), - (day(1970, 1, 1), neg_subnormal), - (day(1999, 12, 31), f64::MAX), - (day(2000, 1, 31), f64::MIN), - (day(2024, 2, 29), -f64::MIN_POSITIVE), - ]; - // Feed in reverse so the stage must rely on the builder's ordering. - let points: Vec> = cases - .iter() - .rev() - .map(|&(d, v)| te_point("USCPI", "United States", "Inflation Rate", d, v)) - .collect(); - let tmp = TempDirGuard::new("extreme-values"); - - // Act - let report = curate_and_write_macro( - tmp.path(), - points, - |_: &str, _: &str, _: &str| Some(target("US", "cpi_yoy", MacroLagClass::MonthlyRelease)), - MacroWriteOptions::default(), - ) - .expect("extreme finite values are valid"); - - // Assert - assert_eq!(report.curate_stats.points_in, cases.len()); - assert_eq!(report.curate_stats.rows_out, cases.len()); - assert_eq!(report.curate_stats.series_out, 1); - assert_eq!(report.curate_stats.builder.skipped_non_finite_value, 0); - assert_stats_conserved(&report.curate_stats); - let expected: Vec = cases - .iter() - .map(|&(d, v)| expected_row("US", "cpi_yoy", d, MONTHLY_RELEASE_LAG_DAYS, v)) - .collect(); - let actual = read_parquet_rows(&tmp.path().join("macro").join("part.parquet")); - assert_rows_bitwise_eq(&actual, &expected); - assert_eq!(actual[0].value.to_bits(), (-0.0f64).to_bits()); - assert!( - actual[0].known_at_micros < 0, - "pre-epoch known_at stays negative" - ); -} diff --git a/tools/curate-etl/src/curate_posts.rs b/tools/curate-etl/src/curate_posts.rs deleted file mode 100644 index 752ae9c9..00000000 --- a/tools/curate-etl/src/curate_posts.rs +++ /dev/null @@ -1,300 +0,0 @@ -//! Pure, in-memory `posts` curation stage joining [`crate::posts::build_posts`], -//! [`crate::provider_mapping::ProviderMappingTable`], [`crate::parquet_posts`], and -//! [`crate::parquet_events::write_events_dataset`] into contract [`EventsParquetRow`]s. -//! -//! # Contract & Point-in-Time Rules -//! - Calls [`build_posts`] unchanged on source keys so global `spiel_id` deduplication, -//! `bot == "1"` newswire vs. retail splitting, and the `edited` text `known_at` guard run -//! before `provider_mapping` resolution. -//! - **Eastern local posting date (`posted_at`, not UTC date or `known_at`):** resolves each -//! post's `(mapping_source, key, et_date)` to a permanent `listing_id: i32` where `et_date` is -//! the `America/Toronto` (Eastern) local calendar date of `posted_at` via -//! [`crate::session_close::utc_micros_to_et_local`]. Late edits never shift a post onto a -//! different listing, while text availability remains guarded by `known_at`. -//! - Timestamps outside the range supported by `utc_micros_to_et_local` (`1976-01-01..=2030-12-31` -//! Eastern) are dropped and counted in [`CuratePostsStats::dropped_unsupported_date`] before -//! checking mapping coverage, without aborting or panicking. -//! - Rows with no covering `provider_mapping` range are dropped into -//! [`CuratePostsStats::dropped_unmapped`]. Because `build_posts` sorts by -//! `(key, known_at, spiel_id)` rather than `posted_at`, per-key lookups rely on -//! [`ProviderMappingCursor::resolve`]'s binary-search fallback whenever `et_date` steps -//! backward. -//! - Converts each mapped [`PostRow`] via [`EventsParquetRow::from`] (reusing -//! [`crate::parquet_posts`] labels and payload encoding verbatim), frees builder vectors before -//! re-sorting in place by the exact 7-field writer key -//! `(listing_id, ts_micros, kind, subtype, payload_json, known_at_micros, known_at_source)`, -//! and collapses exact 7-field duplicates into [`CuratePostsStats::listing_duplicate_collapsed`] -//! as a defensive writer-key uniqueness guard. - -use std::cmp::Ordering; -use std::error::Error; -use std::fmt; -use std::path::Path; - -use crate::parquet_events::{ - write_events_dataset, EventsParquetRow, EventsWriteOptions, EventsWriteStats, - ParquetEventsError, -}; -use crate::parquet_posts::{POST_SUBTYPE_NEWSWIRE, POST_SUBTYPE_RETAIL}; -use crate::posts::{build_posts, CeoPost, PostRow, PostsBuild, PostsError, PostsStats}; -use crate::provider_mapping::{ProviderMappingCursor, ProviderMappingTable}; -use crate::session_close::utc_micros_to_et_local; - -/// Accounting summary produced alongside [`CuratePostsOutput::rows`]. -/// -/// Conservation invariants: -/// - `rows_in == builder.newswire + builder.retail` -/// - `rows_in == rows_out + dropped_unmapped + dropped_unsupported_date + listing_duplicate_collapsed` -/// - `rows_out == newswire_out + retail_out` -/// - `builder` independently satisfies all [`PostsStats`] conservation invariants. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct CuratePostsStats { - pub builder: PostsStats, - pub rows_in: usize, - pub rows_out: usize, - pub newswire_out: usize, - pub retail_out: usize, - pub listings_out: usize, - pub dropped_unmapped: usize, - pub dropped_unsupported_date: usize, - pub listing_duplicate_collapsed: usize, -} - -/// Output of [`curate_posts`]: contract Parquet rows strictly ascending in the 7-field writer -/// sort key and full stage + builder stats. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct CuratePostsOutput { - pub rows: Vec, - pub stats: CuratePostsStats, -} - -/// Typed caller errors returned by [`curate_posts`]. -/// -/// Unmapped rows and posts outside the supported Eastern calendar range are dropped and counted -/// in [`CuratePostsStats`] rather than aborting the stage. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum CuratePostsError { - /// Error propagated from [`build_posts`] (e.g., [`PostsError::TimestampOverflow`]). - Posts(PostsError), - /// Caller-supplied `mapping_source` was empty or contained only whitespace. - EmptyMappingSource, -} - -impl fmt::Display for CuratePostsError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Posts(err) => write!(f, "{err}"), - Self::EmptyMappingSource => { - write!(f, "mapping_source must not be empty or blank") - } - } - } -} - -impl Error for CuratePostsError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::Posts(err) => Some(err), - Self::EmptyMappingSource => None, - } - } -} - -impl From for CuratePostsError { - fn from(err: PostsError) -> Self { - Self::Posts(err) - } -} - -/// Combined stats returned by [`curate_and_write_posts`]. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct CuratePostsWriteReport { - pub curate_stats: CuratePostsStats, - pub write_stats: EventsWriteStats, -} - -/// Typed error returned by [`curate_and_write_posts`]. -#[derive(Debug)] -pub enum CuratePostsWriteError { - Curate(CuratePostsError), - Parquet(ParquetEventsError), -} - -impl fmt::Display for CuratePostsWriteError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Curate(err) => write!(f, "posts curation failed: {err}"), - Self::Parquet(err) => write!(f, "posts Parquet write failed: {err}"), - } - } -} - -impl Error for CuratePostsWriteError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::Curate(err) => Some(err), - Self::Parquet(err) => Some(err), - } - } -} - -impl From for CuratePostsWriteError { - fn from(err: CuratePostsError) -> Self { - Self::Curate(err) - } -} - -impl From for CuratePostsWriteError { - fn from(err: ParquetEventsError) -> Self { - Self::Parquet(err) - } -} - -#[inline] -fn compare_event_rows(a: &EventsParquetRow, b: &EventsParquetRow) -> Ordering { - a.listing_id - .cmp(&b.listing_id) - .then_with(|| a.ts_micros.cmp(&b.ts_micros)) - .then_with(|| a.kind.as_ref().cmp(b.kind.as_ref())) - .then_with(|| a.subtype.cmp(&b.subtype)) - .then_with(|| a.payload_json.cmp(&b.payload_json)) - .then_with(|| a.known_at_micros.cmp(&b.known_at_micros)) - .then_with(|| a.known_at_source.as_ref().cmp(b.known_at_source.as_ref())) -} - -fn resolve_and_finalize( - build: PostsBuild, - mapping_source: &str, - mapping: &ProviderMappingTable, -) -> CuratePostsOutput -where - K: Ord + Clone + AsRef, -{ - let rows_in = build.newswire.len() + build.retail.len(); - let mut stats = CuratePostsStats { - builder: build.stats, - rows_in, - ..CuratePostsStats::default() - }; - - let mut rows: Vec = Vec::with_capacity(rows_in); - - for stream in [build.newswire, build.retail] { - let mut current_key: Option = None; - let mut current_cursor: Option> = None; - - for row in stream { - if current_key.as_ref() != Some(&row.key) { - current_cursor = Some(mapping.cursor_for(mapping_source, row.key.as_ref())); - current_key = Some(row.key); - } - - let Ok(et_local) = utc_micros_to_et_local(row.posted_at) else { - stats.dropped_unsupported_date += 1; - continue; - }; - - let cursor = current_cursor - .as_mut() - .expect("cursor initialized for current key run"); - if cursor.ranges().is_empty() { - stats.dropped_unmapped += 1; - continue; - } - - let Some(listing_id) = cursor.resolve(et_local.session_date) else { - stats.dropped_unmapped += 1; - continue; - }; - - let mapped_row = PostRow { - key: listing_id, - spiel_id: row.spiel_id, - posted_at: row.posted_at, - known_at: row.known_at, - is_bot: row.is_bot, - is_edited: row.is_edited, - user_id: row.user_id, - text: row.text, - source: row.source, - }; - rows.push(EventsParquetRow::from(mapped_row)); - } - } - - rows.sort_unstable_by(compare_event_rows); - - let mapped_len = rows.len(); - rows.dedup(); - stats.listing_duplicate_collapsed = mapped_len - rows.len(); - - let mut last_listing_id: Option = None; - for row in &rows { - if last_listing_id != Some(row.listing_id) { - stats.listings_out += 1; - last_listing_id = Some(row.listing_id); - } - match row.subtype.as_str() { - POST_SUBTYPE_NEWSWIRE => stats.newswire_out += 1, - POST_SUBTYPE_RETAIL => stats.retail_out += 1, - other => unreachable!("unexpected post subtype from parquet_posts: {other:?}"), - } - } - stats.rows_out = rows.len(); - - CuratePostsOutput { rows, stats } -} - -/// Pure `posts` curation stage: builds point-in-time `ceoPosts` newswire and retail streams on -/// source keys via [`build_posts`], resolves `(mapping_source, key, et_date) -> listing_id` on -/// each post's `America/Toronto` (Eastern) local posting date via `provider_mapping`, and emits -/// contract [`EventsParquetRow`]s strictly ascending in the 7-field writer key. -/// -/// Mapping lookup always uses the Eastern local calendar date of `posted_at` (never UTC date and -/// never `known_at`). Posts outside the supported Eastern calendar range are dropped into -/// `dropped_unsupported_date`; unmapped posts are dropped into `dropped_unmapped`. -pub fn curate_posts( - posts: I, - mapping_source: &str, - mapping: &ProviderMappingTable, -) -> Result -where - K: Ord + Clone + AsRef, - I: IntoIterator>, -{ - if mapping_source.trim().is_empty() { - return Err(CuratePostsError::EmptyMappingSource); - } - - let built = build_posts(posts)?; - Ok(resolve_and_finalize(built, mapping_source, mapping)) -} - -/// Thin end-to-end wrapper running [`curate_posts`] and publishing the resulting contract rows -/// via [`write_events_dataset`] to `/events/year=YYYY/part.parquet`. -/// -/// Any [`CuratePostsError`] returns before [`write_events_dataset`] is invoked, leaving -/// `out_dir` untouched. -pub fn curate_and_write_posts( - out_dir: P, - posts: I, - mapping_source: &str, - mapping: &ProviderMappingTable, - options: EventsWriteOptions, -) -> Result -where - P: AsRef, - K: Ord + Clone + AsRef, - I: IntoIterator>, -{ - let curated = curate_posts(posts, mapping_source, mapping)?; - let write_stats = write_events_dataset(out_dir, &curated.rows, options)?; - Ok(CuratePostsWriteReport { - curate_stats: curated.stats, - write_stats, - }) -} - -#[cfg(test)] -#[path = "curate_posts_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/curate_posts_tests.rs b/tools/curate-etl/src/curate_posts_tests.rs deleted file mode 100644 index b58de460..00000000 --- a/tools/curate-etl/src/curate_posts_tests.rs +++ /dev/null @@ -1,1406 +0,0 @@ -use std::borrow::Cow; -use std::collections::HashSet; -use std::error::Error; -use std::fs::{self, File}; -use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; - -use parquet::basic::Compression; -use parquet::column::reader::ColumnReader; -use parquet::file::reader::{FileReader, SerializedFileReader}; - -use super::*; -use crate::events::partition_year_utc; -use crate::parquet_posts::{ - EVENT_KIND_POST, KNOWN_AT_SOURCE_POST_EDITED, KNOWN_AT_SOURCE_POST_TIMESTAMP, - POST_SUBTYPE_NEWSWIRE, POST_SUBTYPE_RETAIL, -}; -use crate::posts::{PostRow, PostsBuild, PostsError, PostsStats, POSTS_SOURCE_CEO}; -use crate::provider_mapping::{ProviderMappingRow, ProviderMappingTable}; -use crate::split::ymd_to_epoch_days; - -static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0); - -struct TempDirGuard { - path: PathBuf, -} - -impl TempDirGuard { - fn new(label: &str) -> Self { - let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); - let pid = std::process::id(); - let path = - std::env::temp_dir().join(format!("curate-etl-curate-posts-test-{label}-{pid}-{seq}")); - let _ = fs::remove_dir_all(&path); - fs::create_dir_all(&path).expect("create test temp dir"); - Self { path } - } - - fn new_uncreated(label: &str) -> Self { - let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); - let pid = std::process::id(); - let path = std::env::temp_dir().join(format!( - "curate-etl-curate-posts-uncreated-{label}-{pid}-{seq}" - )); - let _ = fs::remove_dir_all(&path); - Self { path } - } - - fn path(&self) -> &Path { - &self.path - } -} - -impl Drop for TempDirGuard { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.path); - } -} - -fn d(year: i32, month: u32, day: u32) -> i32 { - ymd_to_epoch_days(year, month, day).expect("valid test date") -} - -fn utc_ms(year: i32, month: u32, day: u32, hour: u8, minute: u8, second: u8) -> i64 { - let epoch_day = d(year, month, day); - let secs = i64::from(epoch_day) * 86_400 - + i64::from(hour) * 3_600 - + i64::from(minute) * 60 - + i64::from(second); - secs * 1_000 -} - -fn map_row( - source: &str, - source_id: &str, - valid_from: i32, - valid_to: Option, - listing_id: i32, -) -> ProviderMappingRow { - ProviderMappingRow { - source: source.to_string(), - source_id: source_id.to_string(), - valid_from, - valid_to, - listing_id, - } -} - -fn post( - key: &str, - spiel_id: &str, - timestamp_ms: i64, - edited_ms: Option, - bot: Option<&str>, - user_id: Option<&str>, - text: &str, -) -> CeoPost { - CeoPost { - key: key.to_string(), - spiel_id: spiel_id.to_string(), - timestamp_ms, - edited_ms, - bot: bot.map(str::to_string), - user_id: user_id.map(str::to_string), - text: text.to_string(), - } -} - -fn assert_stats_invariants(output: &CuratePostsOutput) { - let s = output.stats; - assert_eq!( - s.builder.input, - s.builder.newswire - + s.builder.retail - + s.builder.duplicates_dropped - + s.builder.rejected_invalid - ); - assert_eq!(s.rows_in, s.builder.newswire + s.builder.retail); - assert_eq!( - s.rows_in, - s.rows_out - + s.dropped_unmapped - + s.dropped_unsupported_date - + s.listing_duplicate_collapsed - ); - assert_eq!(s.rows_out, s.newswire_out + s.retail_out); - assert_eq!(s.rows_out, output.rows.len()); - - let distinct_listings: HashSet = output.rows.iter().map(|r| r.listing_id).collect(); - assert_eq!(s.listings_out, distinct_listings.len()); - - for pair in output.rows.windows(2) { - assert_eq!( - compare_event_rows(&pair[0], &pair[1]), - Ordering::Less, - "rows must be strictly ascending in 7-field writer key" - ); - } -} - -fn all_permutations(items: &[T]) -> Vec> { - let mut out = Vec::new(); - let mut arr = items.to_vec(); - let n = arr.len(); - let mut c = vec![0usize; n]; - out.push(arr.clone()); - - let mut i = 0; - while i < n { - if c[i] < i { - if i % 2 == 0 { - arr.swap(0, i); - } else { - arr.swap(c[i], i); - } - out.push(arr.clone()); - c[i] += 1; - i = 0; - } else { - c[i] = 0; - i += 1; - } - } - out -} - -fn read_events_parquet_and_verify_zstd(path: &Path) -> Vec { - let file = File::open(path).expect("open parquet file"); - let reader = SerializedFileReader::new(file).expect("open parquet reader"); - let meta = reader.metadata(); - let mut out = Vec::new(); - - for rg_idx in 0..meta.num_row_groups() { - let rg_meta = meta.row_group(rg_idx); - assert_eq!( - rg_meta.num_columns(), - 7, - "expected 7 columns in events schema" - ); - for col_idx in 0..rg_meta.num_columns() { - let compression = rg_meta.column(col_idx).compression(); - assert!( - matches!(compression, Compression::ZSTD(_)), - "expected ZSTD compression for row_group={rg_idx} col={col_idx}, got {compression:?}" - ); - } - - let rg_rows = rg_meta.num_rows() as usize; - let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); - - let read_i32_col = |col_idx: usize| -> Vec { - let mut vals = Vec::with_capacity(rg_rows); - match rg_reader.get_column_reader(col_idx).expect("col reader") { - ColumnReader::Int32ColumnReader(mut typed) => { - let mut read = 0usize; - while read < rg_rows { - let (n, _, _) = typed - .read_records(rg_rows - read, None, None, &mut vals) - .expect("read i32 records"); - assert!(n > 0, "unexpected short read in INT32 column {col_idx}"); - read += n; - } - } - _ => panic!("expected INT32 column at index {col_idx}"), - } - vals - }; - - let read_i64_col = |col_idx: usize| -> Vec { - let mut vals = Vec::with_capacity(rg_rows); - match rg_reader.get_column_reader(col_idx).expect("col reader") { - ColumnReader::Int64ColumnReader(mut typed) => { - let mut read = 0usize; - while read < rg_rows { - let (n, _, _) = typed - .read_records(rg_rows - read, None, None, &mut vals) - .expect("read i64 records"); - assert!(n > 0, "unexpected short read in INT64 column {col_idx}"); - read += n; - } - } - _ => panic!("expected INT64 column at index {col_idx}"), - } - vals - }; - - let read_str_col = |col_idx: usize| -> Vec { - let mut raw = Vec::with_capacity(rg_rows); - match rg_reader.get_column_reader(col_idx).expect("col reader") { - ColumnReader::ByteArrayColumnReader(mut typed) => { - let mut read = 0usize; - while read < rg_rows { - let (n, _, _) = typed - .read_records(rg_rows - read, None, None, &mut raw) - .expect("read byte_array records"); - assert!( - n > 0, - "unexpected short read in BYTE_ARRAY column {col_idx}" - ); - read += n; - } - } - _ => panic!("expected BYTE_ARRAY column at index {col_idx}"), - } - raw.iter() - .map(|b| { - std::str::from_utf8(b.data()) - .expect("valid utf8") - .to_string() - }) - .collect() - }; - - let listing_ids = read_i32_col(0); - let ts = read_i64_col(1); - let known_at = read_i64_col(2); - let known_at_source = read_str_col(3); - let kind = read_str_col(4); - let subtype = read_str_col(5); - let payload_json = read_str_col(6); - - for i in 0..rg_rows { - out.push(EventsParquetRow { - listing_id: listing_ids[i], - ts_micros: ts[i], - known_at_micros: known_at[i], - known_at_source: Cow::Owned(known_at_source[i].clone()), - kind: Cow::Owned(kind[i].clone()), - subtype: subtype[i].clone(), - payload_json: payload_json[i].clone(), - }); - } - } - - out -} - -#[test] -fn bot_and_retail_posts_map_to_listing_with_matching_subtypes_and_counts() { - let mapping = - ProviderMappingTable::from_rows(vec![map_row("ceo", "CEO_ABC", d(2024, 1, 1), None, 42)]) - .expect("valid mapping"); - - let t_wire = utc_ms(2024, 6, 15, 14, 0, 0); - let t_retail = utc_ms(2024, 6, 15, 14, 5, 0); - - let output = curate_posts( - vec![ - post( - "CEO_ABC", - "sp_wire", - t_wire, - None, - Some("1"), - Some("thenewswire"), - "Company announces drill results", - ), - post( - "CEO_ABC", - "sp_retail", - t_retail, - None, - Some("0"), - Some("retail_user"), - "Looking strong today", - ), - ], - "ceo", - &mapping, - ) - .expect("curate_posts should succeed"); - - assert_stats_invariants(&output); - assert_eq!(output.rows.len(), 2); - assert_eq!(output.stats.rows_in, 2); - assert_eq!(output.stats.rows_out, 2); - assert_eq!(output.stats.newswire_out, 1); - assert_eq!(output.stats.retail_out, 1); - assert_eq!(output.stats.listings_out, 1); - - assert_eq!(output.rows[0].listing_id, 42); - assert_eq!(output.rows[0].kind.as_ref(), EVENT_KIND_POST); - assert_eq!(output.rows[0].subtype, POST_SUBTYPE_NEWSWIRE); - assert_eq!( - output.rows[0].known_at_source.as_ref(), - KNOWN_AT_SOURCE_POST_TIMESTAMP - ); - - assert_eq!(output.rows[1].listing_id, 42); - assert_eq!(output.rows[1].kind.as_ref(), EVENT_KIND_POST); - assert_eq!(output.rows[1].subtype, POST_SUBTYPE_RETAIL); - assert_eq!( - output.rows[1].known_at_source.as_ref(), - KNOWN_AT_SOURCE_POST_TIMESTAMP - ); -} - -#[test] -fn eastern_boundary_late_edit_and_non_monotonic_cursor_resolve_to_posting_date_listing() { - // Adjacent Eastern ranges: - // 2024-06-14 -> listing 101 - // 2024-06-15.. -> listing 202 - let mapping = ProviderMappingTable::from_rows(vec![ - map_row( - "ceo", - "CEO_REUSE", - d(2024, 6, 14), - Some(d(2024, 6, 14)), - 101, - ), - map_row("ceo", "CEO_REUSE", d(2024, 6, 15), None, 202), - ]) - .expect("valid mapping"); - - // 2024-06-15T03:30:00Z is 2024-06-14 23:30 EDT (Eastern date = June 14 -> listing 101). - // Edited on 2024-06-17T15:00:00Z (well inside listing 202's range), so its builder known_at - // comes AFTER the later post, forcing backward posted_at lookup on the same key & subtype. - let t_early_utc_next_day = utc_ms(2024, 6, 15, 3, 30, 0); - let t_early_edit = utc_ms(2024, 6, 17, 15, 0, 0); - // 2024-06-15T04:30:00Z is 2024-06-15 00:30 EDT (Eastern date = June 15 -> listing 202). - let t_later_et_next_day = utc_ms(2024, 6, 15, 4, 30, 0); - - let inputs = vec![ - post( - "CEO_REUSE", - "sp_june14_et_edited_late", - t_early_utc_next_day, - Some(t_early_edit), - None, - Some("u1"), - "Posted late evening June 14 EDT, edited June 17", - ), - post( - "CEO_REUSE", - "sp_june15_et_unedited", - t_later_et_next_day, - None, - None, - Some("u2"), - "Posted early morning June 15 EDT", - ), - ]; - - // Confirm the builder really puts the June 15 post BEFORE the June 14 post in the same - // (key, subtype) stream so the cursor must step backward from June 15 to June 14. - let built = build_posts(inputs.clone()).expect("build_posts"); - assert_eq!(built.retail.len(), 2); - assert_eq!(built.retail[0].spiel_id, "sp_june15_et_unedited"); - assert_eq!(built.retail[1].spiel_id, "sp_june14_et_edited_late"); - - let output = curate_posts(inputs, "ceo", &mapping).expect("curate_posts"); - assert_stats_invariants(&output); - assert_eq!(output.rows.len(), 2); - assert_eq!(output.stats.listings_out, 2); - - // Output is sorted by listing_id ascending: listing 101 first, listing 202 second. - let early = &output.rows[0]; - assert_eq!(early.listing_id, 101); - assert_eq!(early.ts_micros, t_early_utc_next_day * 1_000); - assert_eq!(early.known_at_micros, t_early_edit * 1_000); - assert!(early.known_at_micros > early.ts_micros); - assert_eq!(early.known_at_source.as_ref(), KNOWN_AT_SOURCE_POST_EDITED); - assert!(early.payload_json.contains("\"sp_june14_et_edited_late\"")); - - let later = &output.rows[1]; - assert_eq!(later.listing_id, 202); - assert_eq!(later.ts_micros, t_later_et_next_day * 1_000); - assert_eq!(later.known_at_micros, t_later_et_next_day * 1_000); - assert_eq!( - later.known_at_source.as_ref(), - KNOWN_AT_SOURCE_POST_TIMESTAMP - ); - assert!(later.payload_json.contains("\"sp_june15_et_unedited\"")); - - // Point-in-time guard: immediately before the edit timestamp, the edited text is excluded. - let cutoff_before_edit = early.known_at_micros - 1; - let visible_before: Vec<&EventsParquetRow> = output - .rows - .iter() - .filter(|r| r.known_at_micros <= cutoff_before_edit) - .collect(); - assert_eq!(visible_before.len(), 1); - assert_eq!(visible_before[0].listing_id, 202); - - let visible_at_edit: Vec<&EventsParquetRow> = output - .rows - .iter() - .filter(|r| r.known_at_micros <= early.known_at_micros) - .collect(); - assert_eq!(visible_at_edit.len(), 2); -} - -#[test] -fn unmapped_keys_out_of_range_dates_and_unsupported_timestamps_are_dropped_cleanly() { - let mapping = ProviderMappingTable::from_rows(vec![map_row( - "ceo", - "CEO_MAPPED", - d(2024, 6, 1), - Some(d(2024, 6, 30)), - 77, - )]) - .expect("valid mapping"); - - let t_inside = utc_ms(2024, 6, 15, 15, 0, 0); - let t_before_range = utc_ms(2024, 5, 31, 15, 0, 0); - let t_after_range = utc_ms(2024, 7, 1, 15, 0, 0); - // 2032-01-01T00:00:00Z converts to micros without overflow but exceeds 2030-12-31 ET. - let t_unsupported_future = utc_ms(2032, 1, 1, 0, 0, 0); - - let output = curate_posts( - vec![ - post( - "CEO_MAPPED", - "sp_ok", - t_inside, - None, - None, - Some("u1"), - "in range", - ), - post( - "CEO_MAPPED", - "sp_before", - t_before_range, - None, - None, - None, - "before range", - ), - post( - "CEO_MAPPED", - "sp_after", - t_after_range, - None, - Some("1"), - None, - "after range", - ), - post( - "CEO_UNKNOWN", - "sp_unknown_key", - t_inside, - None, - None, - None, - "unknown key", - ), - post( - "CEO_MAPPED", - "sp_unsupported_mapped", - t_unsupported_future, - None, - None, - None, - "unsupported year on mapped key", - ), - post( - "CEO_UNKNOWN", - "sp_unsupported_unmapped", - t_unsupported_future, - None, - Some("1"), - None, - "unsupported year on unmapped key counted as unsupported date first", - ), - ], - "ceo", - &mapping, - ) - .expect("curate_posts should not error on unmapped or unsupported-date rows"); - - assert_stats_invariants(&output); - assert_eq!(output.stats.rows_in, 6); - assert_eq!(output.stats.rows_out, 1); - assert_eq!(output.stats.retail_out, 1); - assert_eq!(output.stats.newswire_out, 0); - assert_eq!(output.stats.dropped_unmapped, 3); - assert_eq!(output.stats.dropped_unsupported_date, 2); - assert_eq!(output.stats.listing_duplicate_collapsed, 0); - assert_eq!(output.rows[0].listing_id, 77); -} - -#[test] -fn resolve_and_finalize_collapses_exact_seven_field_duplicates_across_source_keys() { - let mapping = ProviderMappingTable::from_rows(vec![ - map_row("ceo", "CEO_ALIAS_A", d(2024, 1, 1), None, 500), - map_row("ceo", "CEO_ALIAS_B", d(2024, 1, 1), None, 500), - ]) - .expect("valid mapping"); - - let posted_at = utc_ms(2024, 8, 10, 14, 0, 0) * 1_000; - let known_at = utc_ms(2024, 8, 10, 14, 15, 0) * 1_000; - - let build = PostsBuild { - newswire: Vec::new(), - retail: vec![ - PostRow { - key: "CEO_ALIAS_A".to_string(), - spiel_id: "sp_shared".to_string(), - posted_at, - known_at, - is_bot: false, - is_edited: true, - user_id: Some("u_same".to_string()), - text: "Identical post body".to_string(), - source: POSTS_SOURCE_CEO, - }, - PostRow { - key: "CEO_ALIAS_B".to_string(), - spiel_id: "sp_shared".to_string(), - posted_at, - known_at, - is_bot: false, - is_edited: true, - user_id: Some("u_same".to_string()), - text: "Identical post body".to_string(), - source: POSTS_SOURCE_CEO, - }, - ], - stats: PostsStats { - input: 2, - newswire: 0, - retail: 2, - edited: 2, - edited_before_posted: 0, - duplicates_dropped: 0, - rejected_invalid: 0, - }, - }; - - let output = resolve_and_finalize(build, "ceo", &mapping); - assert_stats_invariants(&output); - assert_eq!(output.stats.rows_in, 2); - assert_eq!(output.stats.rows_out, 1); - assert_eq!(output.stats.retail_out, 1); - assert_eq!(output.stats.newswire_out, 0); - assert_eq!(output.stats.listings_out, 1); - assert_eq!(output.stats.listing_duplicate_collapsed, 1); - assert_eq!(output.rows[0].listing_id, 500); -} - -#[test] -fn public_curate_posts_dedups_repeated_spiel_id_in_builder_and_keeps_distinct_spiel_ids() { - let mapping = ProviderMappingTable::from_rows(vec![ - map_row("ceo", "CEO_ALIAS_A", d(2024, 1, 1), None, 500), - map_row("ceo", "CEO_ALIAS_B", d(2024, 1, 1), None, 500), - ]) - .expect("valid mapping"); - - let t_post = utc_ms(2024, 8, 10, 14, 0, 0); - - // Same spiel_id under two source keys mapping to the same listing -> builder dedups before - // mapping, so duplicates_dropped == 1 and listing_duplicate_collapsed == 0. - let same_spiel = curate_posts( - vec![ - post( - "CEO_ALIAS_A", - "sp_dup", - t_post, - None, - None, - Some("u1"), - "Same post", - ), - post( - "CEO_ALIAS_B", - "sp_dup", - t_post, - None, - None, - Some("u1"), - "Same post", - ), - ], - "ceo", - &mapping, - ) - .expect("curate_posts"); - - assert_stats_invariants(&same_spiel); - assert_eq!(same_spiel.stats.builder.duplicates_dropped, 1); - assert_eq!(same_spiel.stats.rows_in, 1); - assert_eq!(same_spiel.stats.rows_out, 1); - assert_eq!(same_spiel.stats.listing_duplicate_collapsed, 0); - assert_eq!(same_spiel.rows[0].listing_id, 500); - - // Distinct spiel_ids (everything else identical) under the two alias keys -> both survive. - let distinct_spiel = curate_posts( - vec![ - post( - "CEO_ALIAS_A", - "sp_one", - t_post, - None, - None, - Some("u1"), - "Same text", - ), - post( - "CEO_ALIAS_B", - "sp_two", - t_post, - None, - None, - Some("u1"), - "Same text", - ), - ], - "ceo", - &mapping, - ) - .expect("curate_posts"); - - assert_stats_invariants(&distinct_spiel); - assert_eq!(distinct_spiel.stats.builder.duplicates_dropped, 0); - assert_eq!(distinct_spiel.stats.rows_in, 2); - assert_eq!(distinct_spiel.stats.rows_out, 2); - assert_eq!(distinct_spiel.stats.listing_duplicate_collapsed, 0); - assert_eq!(distinct_spiel.stats.listings_out, 1); -} - -#[test] -fn permutation_invariance_strict_sort_order_and_empty_input_accounting() { - let mapping = ProviderMappingTable::from_rows(vec![ - map_row("ceo", "CEO_A", d(2024, 1, 1), None, 10), - map_row("ceo", "CEO_B", d(2024, 1, 1), None, 20), - ]) - .expect("valid mapping"); - - // Empty input -> empty rows and default stats. - let empty = curate_posts(Vec::>::new(), "ceo", &mapping).expect("empty"); - assert!(empty.rows.is_empty()); - assert_eq!(empty.stats, CuratePostsStats::default()); - assert_stats_invariants(&empty); - - // Mixed fixture: newswire, retail, edited, unmapped, unsupported date, invalid row. - let t0 = utc_ms(2024, 9, 10, 14, 0, 0); - let t1 = utc_ms(2024, 9, 10, 15, 0, 0); - let t_future = utc_ms(2035, 1, 1, 0, 0, 0); - - let fixture = vec![ - post( - "CEO_B", - "sp_b_wire", - t0, - None, - Some("1"), - Some("wire"), - "Newswire release", - ), - post( - "CEO_A", - "sp_a_retail", - t1, - Some(t1 + 60_000), - None, - Some("u_a"), - "Edited retail post", - ), - post( - "CEO_A", - "sp_a_wire", - t0, - None, - Some(" 1 "), - None, - "Another wire", - ), - post( - "CEO_UNKNOWN", - "sp_unmapped", - t0, - None, - None, - None, - "Unmapped", - ), - post( - "CEO_A", - "sp_unsupported", - t_future, - None, - None, - None, - "Future unsupported", - ), - post("CEO_A", "", t0, None, None, None, "Invalid empty spiel_id"), - ]; - - let baseline = curate_posts(fixture.clone(), "ceo", &mapping).expect("baseline"); - assert_stats_invariants(&baseline); - assert_eq!(baseline.stats.builder.input, 6); - assert_eq!(baseline.stats.builder.rejected_invalid, 1); - assert_eq!(baseline.stats.rows_in, 5); - assert_eq!(baseline.stats.rows_out, 3); - assert_eq!(baseline.stats.newswire_out, 2); - assert_eq!(baseline.stats.retail_out, 1); - assert_eq!(baseline.stats.listings_out, 2); - assert_eq!(baseline.stats.dropped_unmapped, 1); - assert_eq!(baseline.stats.dropped_unsupported_date, 1); - - let perms = all_permutations(&fixture); - assert_eq!(perms.len(), 720); - for perm in perms { - let got = curate_posts(perm, "ceo", &mapping).expect("permuted curate_posts"); - assert_eq!(got, baseline); - } -} - -struct PanicOnConsumeIter; - -impl Iterator for PanicOnConsumeIter { - type Item = CeoPost; - - fn next(&mut self) -> Option { - panic!("iterator must not be consumed when mapping_source is blank"); - } -} - -#[test] -fn typed_errors_for_blank_mapping_source_and_timestamp_overflow_leave_out_dir_untouched() { - let mapping = ProviderMappingTable::default(); - - for blank in ["", " ", "\t\n"] { - let err = curate_posts(PanicOnConsumeIter, blank, &mapping) - .expect_err("blank mapping_source must fail before consuming iterator"); - assert_eq!(err, CuratePostsError::EmptyMappingSource); - assert!(err.source().is_none()); - assert!(err.to_string().contains("mapping_source")); - - // Missing output path stays missing. - let missing_dir = TempDirGuard::new_uncreated("blank-missing"); - let write_err = curate_and_write_posts( - missing_dir.path(), - PanicOnConsumeIter, - blank, - &mapping, - EventsWriteOptions::default(), - ) - .expect_err("curate_and_write_posts must fail on blank mapping_source"); - assert!(matches!( - write_err, - CuratePostsWriteError::Curate(CuratePostsError::EmptyMappingSource) - )); - assert!(write_err.source().is_some()); - assert!(write_err.to_string().contains("posts curation failed")); - assert!(!missing_dir.path().exists()); - - // Existing empty output directory stays empty. - let empty_dir = TempDirGuard::new("blank-empty"); - let _ = curate_and_write_posts( - empty_dir.path(), - PanicOnConsumeIter, - blank, - &mapping, - EventsWriteOptions::default(), - ) - .expect_err("curate_and_write_posts must fail on blank mapping_source"); - assert_eq!(fs::read_dir(empty_dir.path()).expect("read dir").count(), 0); - } - - // TimestampOverflow propagates as CuratePostsError::Posts and leaves out_dir untouched. - let overflow_posts = vec![post( - "CEO_A", - "sp_overflow", - i64::MAX, - None, - None, - None, - "overflow timestamp", - )]; - - let err = curate_posts(overflow_posts.clone(), "ceo", &mapping) - .expect_err("overflow timestamp must fail"); - assert_eq!( - err, - CuratePostsError::Posts(PostsError::TimestampOverflow { - spiel_id: "sp_overflow".to_string(), - field: "timestamp_ms", - timestamp_ms: i64::MAX, - }) - ); - assert!(err.source().is_some()); - assert!(err.to_string().contains("sp_overflow")); - - let missing_dir = TempDirGuard::new_uncreated("overflow-missing"); - let write_err = curate_and_write_posts( - missing_dir.path(), - overflow_posts.clone(), - "ceo", - &mapping, - EventsWriteOptions::default(), - ) - .expect_err("curate_and_write_posts must fail on overflow"); - assert!(matches!( - write_err, - CuratePostsWriteError::Curate(CuratePostsError::Posts( - PostsError::TimestampOverflow { .. } - )) - )); - assert!(write_err.source().is_some()); - assert!(!missing_dir.path().exists()); - - let empty_dir = TempDirGuard::new("overflow-empty"); - let _ = curate_and_write_posts( - empty_dir.path(), - overflow_posts, - "ceo", - &mapping, - EventsWriteOptions::default(), - ) - .expect_err("curate_and_write_posts must fail on overflow"); - assert_eq!(fs::read_dir(empty_dir.path()).expect("read dir").count(), 0); -} - -#[test] -fn curate_and_write_posts_round_trips_zstd_parquet_field_for_field() { - let dir = TempDirGuard::new("round-trip"); - let mapping = ProviderMappingTable::from_rows(vec![ - map_row("ceo", "CEO_A", d(2024, 1, 1), None, 101), - map_row("ceo", "CEO_B", d(2024, 1, 1), None, 202), - ]) - .expect("valid mapping"); - - let t_2024 = utc_ms(2024, 12, 31, 23, 30, 0); - let t_2025_edit = utc_ms(2025, 1, 1, 0, 10, 0); - let t_2025 = utc_ms(2025, 2, 14, 15, 0, 0); - - let fixture = vec![ - post( - "CEO_A", - "sp_2024_special", - t_2024, - Some(t_2025_edit), - None, - Some("user\"1"), - "Quote \"here\", newline\nline2, non-ASCII café €", - ), - post( - "CEO_B", - "sp_2024_wire", - t_2024, - None, - Some("1"), - Some("thenewswire"), - "Year-end wire release", - ), - post( - "CEO_A", - "sp_2025_retail", - t_2025, - None, - None, - None, - "2025 commentary", - ), - post( - "CEO_UNMAPPED", - "sp_dropped", - t_2025, - None, - None, - None, - "Dropped unmapped", - ), - ]; - - let pure = curate_posts(fixture.clone(), "ceo", &mapping).expect("pure curate_posts"); - assert_stats_invariants(&pure); - assert_eq!(pure.rows.len(), 3); - - let report = curate_and_write_posts( - dir.path(), - fixture, - "ceo", - &mapping, - EventsWriteOptions::default(), - ) - .expect("curate_and_write_posts should succeed"); - - assert_eq!(report.curate_stats, pure.stats); - assert_eq!(report.write_stats.rows_written, pure.stats.rows_out); - assert_eq!(report.write_stats.files_written, 2); - assert_eq!(report.write_stats.rows_by_year.get(&2024), Some(&2)); - assert_eq!(report.write_stats.rows_by_year.get(&2025), Some(&1)); - - let path_2024 = dir.path().join("events/year=2024/part.parquet"); - let path_2025 = dir.path().join("events/year=2025/part.parquet"); - assert!(path_2024.exists()); - assert!(path_2025.exists()); - - let read_2024 = read_events_parquet_and_verify_zstd(&path_2024); - let read_2025 = read_events_parquet_and_verify_zstd(&path_2025); - - let expected_2024: Vec = pure - .rows - .iter() - .filter(|r| partition_year_utc(r.ts_micros) == 2024) - .cloned() - .collect(); - let expected_2025: Vec = pure - .rows - .iter() - .filter(|r| partition_year_utc(r.ts_micros) == 2025) - .cloned() - .collect(); - - assert_eq!(read_2024, expected_2024); - assert_eq!(read_2025, expected_2025); - assert!(read_2024[0].payload_json.contains("café €")); - assert!(read_2024[0].payload_json.contains("\\nline2")); - assert!(read_2024[0].payload_json.contains("\\\"here\\\"")); -} - -// --------------------------------------------------------------------------- -// QA edge cases (T-162). -// --------------------------------------------------------------------------- - -/// Independent 7-field writer key built from raw fields (does not reuse `compare_event_rows`). -fn writer_key(r: &EventsParquetRow) -> (i32, i64, String, String, String, i64, String) { - ( - r.listing_id, - r.ts_micros, - r.kind.to_string(), - r.subtype.clone(), - r.payload_json.clone(), - r.known_at_micros, - r.known_at_source.to_string(), - ) -} - -fn assert_strictly_ascending_by_tuple(rows: &[EventsParquetRow]) { - for pair in rows.windows(2) { - assert!( - writer_key(&pair[0]) < writer_key(&pair[1]), - "rows not strictly ascending by 7-field tuple: {:?} !< {:?}", - writer_key(&pair[0]), - writer_key(&pair[1]) - ); - } -} - -#[test] -fn supported_eastern_range_boundaries_are_inclusive_and_drop_outside_without_error() { - use crate::session_close::{ - SESSION_MAX_SUPPORTED_UTC_MICROS, SESSION_MIN_SUPPORTED_UTC_MICROS, - }; - - // Mapping covers the whole supported range for one key. - let mapping = - ProviderMappingTable::from_rows(vec![map_row("ceo", "CEO_EDGE", d(1976, 1, 1), None, 9)]) - .expect("valid mapping"); - - // `posted_at` = ms * 1000, so millisecond-aligned edges. - let min_ms = SESSION_MIN_SUPPORTED_UTC_MICROS / 1_000; - assert_eq!(min_ms * 1_000, SESSION_MIN_SUPPORTED_UTC_MICROS); - let max_ms = SESSION_MAX_SUPPORTED_UTC_MICROS / 1_000; // 2031-01-01T04:59:59.999Z - assert_eq!(min_ms, utc_ms(1976, 1, 1, 5, 0, 0)); - assert_eq!(max_ms + 1, utc_ms(2031, 1, 1, 5, 0, 0)); - - let output = curate_posts( - vec![ - post( - "CEO_EDGE", - "sp_min", - min_ms, - None, - None, - None, - "first supported ms", - ), - post( - "CEO_EDGE", - "sp_min_minus", - min_ms - 1, - None, - None, - None, - "1975 EST", - ), - post( - "CEO_EDGE", - "sp_max", - max_ms, - None, - Some("1"), - None, - "last supported ms", - ), - post( - "CEO_EDGE", - "sp_max_plus", - max_ms + 1, - None, - None, - None, - "2031 EST", - ), - // Positive but early (1970) timestamp passes the builder and must be dropped too. - post("CEO_EDGE", "sp_1970", 1, None, None, None, "epoch + 1ms"), - ], - "ceo", - &mapping, - ) - .expect("out-of-range dates must not error"); - - assert_stats_invariants(&output); - assert_eq!(output.stats.builder.rejected_invalid, 0); - assert_eq!(output.stats.rows_in, 5); - assert_eq!(output.stats.rows_out, 2); - assert_eq!(output.stats.dropped_unsupported_date, 3); - assert_eq!(output.stats.dropped_unmapped, 0); - let ts: Vec = output.rows.iter().map(|r| r.ts_micros).collect(); - assert_eq!(ts, vec![min_ms * 1_000, max_ms * 1_000]); - assert!(output.rows.iter().all(|r| r.listing_id == 9)); -} - -#[test] -fn winter_est_midnight_boundary_uses_eastern_date_not_utc_date() { - // EST (UTC-5) in January: 04:59:59Z is still the previous Eastern day, 05:00:00Z is not. - let mapping = ProviderMappingTable::from_rows(vec![ - map_row("ceo", "CEO_W", d(2024, 1, 1), Some(d(2024, 1, 14)), 31), - map_row("ceo", "CEO_W", d(2024, 1, 15), None, 32), - ]) - .expect("valid mapping"); - - let before_et_midnight = utc_ms(2024, 1, 15, 4, 59, 59); // 2024-01-14 23:59:59 EST - let at_et_midnight = utc_ms(2024, 1, 15, 5, 0, 0); // 2024-01-15 00:00:00 EST - let utc_prev_day_evening = utc_ms(2024, 1, 14, 23, 0, 0); // 2024-01-14 18:00 EST - - let output = curate_posts( - vec![ - post("CEO_W", "sp_a", before_et_midnight, None, None, None, "a"), - post("CEO_W", "sp_b", at_et_midnight, None, None, None, "b"), - post("CEO_W", "sp_c", utc_prev_day_evening, None, None, None, "c"), - ], - "ceo", - &mapping, - ) - .expect("curate_posts"); - assert_stats_invariants(&output); - - let listing_of = |spiel: &str| { - output - .rows - .iter() - .find(|r| r.payload_json.contains(&format!("\"{spiel}\""))) - .map(|r| r.listing_id) - .expect("row present") - }; - assert_eq!( - listing_of("sp_a"), - 31, - "UTC date is Jan 15 but Eastern date is Jan 14" - ); - assert_eq!(listing_of("sp_b"), 32); - assert_eq!(listing_of("sp_c"), 31); -} - -#[test] -fn multi_range_key_with_repeated_backward_date_jumps_matches_table_resolve() { - // Three ranges plus a gap; late edits scramble known_at order relative to posted_at. - let mapping = ProviderMappingTable::from_rows(vec![ - map_row("ceo", "CEO_M", d(2023, 1, 1), Some(d(2023, 3, 31)), 1), - map_row("ceo", "CEO_M", d(2023, 4, 1), Some(d(2023, 6, 30)), 2), - // gap 2023-07-01..=2023-07-31 - map_row("ceo", "CEO_M", d(2023, 8, 1), None, 3), - ]) - .expect("valid mapping"); - - // (spiel, posted, edited, expected listing or None for unmapped gap) - let cases: Vec<(&str, i64, Option, Option)> = vec![ - ( - "sp_feb", - utc_ms(2023, 2, 10, 15, 0, 0), - Some(utc_ms(2023, 12, 1, 15, 0, 0)), - Some(1), - ), - ( - "sp_may", - utc_ms(2023, 5, 10, 15, 0, 0), - Some(utc_ms(2023, 11, 1, 15, 0, 0)), - Some(2), - ), - ("sp_sep", utc_ms(2023, 9, 10, 15, 0, 0), None, Some(3)), - ( - "sp_jul_gap", - utc_ms(2023, 7, 10, 15, 0, 0), - Some(utc_ms(2023, 10, 1, 15, 0, 0)), - None, - ), - ( - "sp_jan", - utc_ms(2023, 1, 5, 15, 0, 0), - Some(utc_ms(2024, 1, 1, 15, 0, 0)), - Some(1), - ), - ("sp_jun", utc_ms(2023, 6, 30, 15, 0, 0), None, Some(2)), - // 2023-04-01T03:00Z = 2023-03-31 23:00 EDT -> listing 1, edited later. - ( - "sp_mar_et", - utc_ms(2023, 4, 1, 3, 0, 0), - Some(utc_ms(2023, 12, 15, 15, 0, 0)), - Some(1), - ), - ]; - - let inputs: Vec> = cases - .iter() - .map(|(s, p, e, _)| post("CEO_M", s, *p, *e, None, None, s)) - .collect(); - - // Prove the builder stream really is non-monotonic in posted_at. - let built = build_posts(inputs.clone()).expect("build"); - let posted: Vec = built.retail.iter().map(|r| r.posted_at).collect(); - assert!(posted.windows(2).filter(|w| w[1] < w[0]).count() >= 2); - - let output = curate_posts(inputs, "ceo", &mapping).expect("curate"); - assert_stats_invariants(&output); - assert_eq!(output.stats.dropped_unmapped, 1); - assert_eq!(output.stats.rows_out, 6); - - for (spiel, posted_ms, _, expected) in &cases { - let got = output - .rows - .iter() - .find(|r| { - r.payload_json - .contains(&format!("\"spiel_id\":\"{spiel}\"")) - }) - .map(|r| r.listing_id); - assert_eq!(got, *expected, "spiel {spiel}"); - // Oracle: fresh table-level binary search on the Eastern posting date. - let et = utc_micros_to_et_local(posted_ms * 1_000).expect("supported"); - assert_eq!(mapping.resolve("ceo", "CEO_M", et.session_date), *expected); - } -} - -#[test] -fn mapping_rows_for_another_source_do_not_resolve() { - let mapping = ProviderMappingTable::from_rows(vec![ - map_row("eod", "CEO_X", d(2024, 1, 1), None, 7), - map_row("ceo", "CEO_Y", d(2024, 1, 1), None, 8), - ]) - .expect("valid mapping"); - let t = utc_ms(2024, 5, 1, 15, 0, 0); - - let output = curate_posts( - vec![ - post("CEO_X", "sp_x", t, None, None, None, "x"), - post("CEO_Y", "sp_y", t, None, None, None, "y"), - ], - "ceo", - &mapping, - ) - .expect("curate"); - assert_stats_invariants(&output); - assert_eq!(output.stats.dropped_unmapped, 1); - assert_eq!(output.rows.len(), 1); - assert_eq!(output.rows[0].listing_id, 8); -} - -#[test] -fn same_key_in_newswire_and_retail_streams_resolves_both() { - // The key appears in both builder streams; each stream needs its own cursor run. - let mapping = ProviderMappingTable::from_rows(vec![ - map_row("ceo", "CEO_A", d(2024, 1, 1), Some(d(2024, 3, 31)), 1), - map_row("ceo", "CEO_A", d(2024, 4, 1), None, 2), - map_row("ceo", "CEO_Z", d(2024, 1, 1), None, 3), - ]) - .expect("valid mapping"); - - let output = curate_posts( - vec![ - post( - "CEO_A", - "w1", - utc_ms(2024, 5, 1, 15, 0, 0), - None, - Some("1"), - None, - "w1", - ), - post( - "CEO_Z", - "w2", - utc_ms(2024, 5, 1, 15, 0, 0), - None, - Some("1"), - None, - "w2", - ), - post( - "CEO_A", - "r1", - utc_ms(2024, 2, 1, 15, 0, 0), - None, - None, - None, - "r1", - ), - post( - "CEO_Z", - "r2", - utc_ms(2024, 2, 1, 15, 0, 0), - None, - None, - None, - "r2", - ), - ], - "ceo", - &mapping, - ) - .expect("curate"); - assert_stats_invariants(&output); - let got: Vec<(i32, &str)> = output - .rows - .iter() - .map(|r| (r.listing_id, r.subtype.as_str())) - .collect(); - assert_eq!( - got, - // Listing 3: Feb retail precedes May newswire by ts_micros. - vec![ - (1, "retail"), - (2, "newswire"), - (3, "retail"), - (3, "newswire") - ] - ); - assert_eq!(output.stats.listings_out, 3); -} - -#[test] -fn parquet_writer_error_is_wrapped_and_curate_stats_not_returned() { - let dir = TempDirGuard::new("writer-error"); - let mapping = - ProviderMappingTable::from_rows(vec![map_row("ceo", "CEO_A", d(2024, 1, 1), None, 1)]) - .expect("valid mapping"); - - let err = curate_and_write_posts( - dir.path(), - vec![post( - "CEO_A", - "sp", - utc_ms(2024, 5, 1, 15, 0, 0), - None, - None, - None, - "t", - )], - "ceo", - &mapping, - EventsWriteOptions { - row_group_rows: 0, - ..EventsWriteOptions::default() - }, - ) - .expect_err("invalid writer options must fail"); - assert!(matches!( - err, - CuratePostsWriteError::Parquet(ParquetEventsError::InvalidRowGroupRows) - )); - assert!(err.source().is_some()); - assert!(err.to_string().contains("posts Parquet write failed")); - assert!(!dir.path().join("events/year=2024/part.parquet").exists()); -} - -#[test] -fn same_listing_same_timestamp_tie_breaks_on_subtype_then_payload_and_round_trips() { - let dir = TempDirGuard::new("tie-break"); - let mapping = - ProviderMappingTable::from_rows(vec![map_row("ceo", "CEO_T", d(2024, 1, 1), None, 55)]) - .expect("valid mapping"); - - let t = utc_ms(2024, 7, 1, 14, 0, 0); - let fixture = vec![ - // Same listing + ts: two retail (payload differs via spiel_id) and two newswire. - post( - "CEO_T", - "sp_r_b", - t, - None, - None, - Some("u"), - "retail \"b\"\nné", - ), - post( - "CEO_T", - "sp_r_a", - t, - Some(t + 5_000), - None, - Some("u"), - "retail a", - ), - post("CEO_T", "sp_w_b", t, None, Some("1"), None, "wire b"), - post("CEO_T", "sp_w_a", t, None, Some("1"), None, "wire a"), - ]; - - let pure = curate_posts(fixture.clone(), "ceo", &mapping).expect("curate"); - assert_stats_invariants(&pure); - assert_strictly_ascending_by_tuple(&pure.rows); - - let order: Vec<(String, String)> = pure - .rows - .iter() - .map(|r| { - let spiel = r.payload_json[13..].split('"').next().unwrap().to_string(); - (r.subtype.clone(), spiel) - }) - .collect(); - assert_eq!( - order, - vec![ - ("newswire".to_string(), "sp_w_a".to_string()), - ("newswire".to_string(), "sp_w_b".to_string()), - ("retail".to_string(), "sp_r_a".to_string()), - ("retail".to_string(), "sp_r_b".to_string()), - ] - ); - assert_eq!( - pure.rows[2].known_at_source.as_ref(), - KNOWN_AT_SOURCE_POST_EDITED - ); - assert_eq!(pure.rows[2].known_at_micros, (t + 5_000) * 1_000); - - let report = curate_and_write_posts( - dir.path(), - fixture, - "ceo", - &mapping, - EventsWriteOptions::default(), - ) - .expect("write"); - assert_eq!(report.curate_stats, pure.stats); - assert_eq!(report.write_stats.rows_written, 4); - let read = - read_events_parquet_and_verify_zstd(&dir.path().join("events/year=2024/part.parquet")); - assert_eq!(read, pure.rows); - assert_strictly_ascending_by_tuple(&read); -} - -#[test] -fn permutation_fixture_is_strictly_ascending_by_independent_tuple() { - let mapping = ProviderMappingTable::from_rows(vec![ - map_row("ceo", "CEO_A", d(2024, 1, 1), None, 10), - map_row("ceo", "CEO_B", d(2024, 1, 1), None, 20), - ]) - .expect("valid mapping"); - let t0 = utc_ms(2024, 9, 10, 14, 0, 0); - let fixture = vec![ - post("CEO_B", "b1", t0, None, Some("1"), None, "x"), - post("CEO_A", "a1", t0, None, None, None, "x"), - post("CEO_A", "a2", t0, None, Some("1"), None, "x"), - post("CEO_A", "a3", t0, Some(t0 + 1), None, None, "x"), - post("CEO_B", "b2", t0 - 1, None, None, None, "x"), - ]; - let baseline = curate_posts(fixture.clone(), "ceo", &mapping).expect("baseline"); - assert_strictly_ascending_by_tuple(&baseline.rows); - for perm in all_permutations(&fixture) { - let got = curate_posts(perm, "ceo", &mapping).expect("perm"); - assert_eq!(got, baseline); - } -} diff --git a/tools/curate-etl/src/curate_qm_bars_1m.rs b/tools/curate-etl/src/curate_qm_bars_1m.rs deleted file mode 100644 index 19fb6e0c..00000000 --- a/tools/curate-etl/src/curate_qm_bars_1m.rs +++ /dev/null @@ -1,206 +0,0 @@ -//! Pure, in-memory `bars_1m` curation stage for raw QuoteMedia `qmIntraday` bars (`M2.3j`), -//! joining [`crate::bars_1m::build_bars_1m`], [`crate::provider_mapping::ProviderMappingTable`], -//! [`crate::ilp::IlpShardedWriter`], and [`crate::bson_stream::decode_qm_intraday_stream`]. -//! -//! # Contract & Point-in-Time Rules -//! - Uses [`EodIntradayBar`] as the existing source-keyed carrier for canonical raw QuoteMedia -//! OHLCV and `qmSearchCode`. -//! - **No split un-adjustment:** `qmIntraday` raw fields (`open`, `high`, `low`, `close`, -//! `sharevolume`) are already un-adjusted (`design/DATA-CONTRACTS.md` §1). This stage takes no -//! [`SplitTable`] and invokes [`build_bars_1m`] with an internal empty [`SplitTable`] so valid -//! OHLCV values pass through bit-identical while reusing Eastern Time session tagging, OHLCV -//! validation, and same-key deduplication. -//! - **Signed-zero volume normalization:** [`crate::bson_qm_intraday::decode_qm_intraday_doc`] -//! normalizes `-0.0` `sharevolume` to `+0.0` during BSON decode, and [`build_bars_1m`] applies -//! the same `-0.0 -> +0.0` normalization for direct in-memory inputs. -//! - Resolves each built row's `(mapping_source, qmSearchCode, session_date)` to a permanent -//! `listing_id: i32` on its Eastern Time `session_date`, stamps [`BARS_1M_SOURCE_QM`] -//! (`"qm_raw"`), re-sorts in place by `(listing_id, ts)`, and compacts cross-`source_id` -//! collisions using the same bitwise-equality / conflict-drop rule as [`crate::curate_bars_1m`]. -//! - Writes sorted `Bar1mRow` rows into a caller-owned [`IlpShardedWriter`] without calling -//! [`IlpShardedWriter::finish`], allowing multiple chunks to stream through one writer. - -use std::error::Error; -use std::fmt; -use std::hash::Hash; -use std::io::{self, Write}; - -use crate::bars_1m::{build_bars_1m, EodIntradayBar, BARS_1M_SOURCE_QM}; -use crate::bson_qm_intraday::BsonQmIntradayDecodeStats; -use crate::bson_stream::{decode_qm_intraday_stream, BsonStreamError, BsonStreamOptions}; -use crate::curate_bars_1m::{ - map_bars_1m, CurateBars1mError, CurateBars1mOutput, CurateBars1mWriteError, - CurateBars1mWriteReport, -}; -use crate::ilp::IlpShardedWriter; -use crate::provider_mapping::ProviderMappingTable; -use crate::split::SplitTable; - -/// Combined decode and write summary returned by [`curate_and_write_qm_bars_1m_from_bson`]. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct CurateQmBars1mBsonReport { - pub decode_stats: BsonQmIntradayDecodeStats, - pub write_report: CurateBars1mWriteReport, -} - -/// Typed error returned by [`curate_and_write_qm_bars_1m_from_bson`]. -#[derive(Debug)] -pub enum CurateQmBars1mBsonError { - Stream(BsonStreamError), - Write(CurateBars1mWriteError), -} - -impl fmt::Display for CurateQmBars1mBsonError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Stream(err) => write!(f, "qmIntraday bars_1m BSON stream failed: {err}"), - Self::Write(err) => write!(f, "{err}"), - } - } -} - -impl Error for CurateQmBars1mBsonError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::Stream(err) => Some(err), - Self::Write(err) => Some(err), - } - } -} - -impl From for CurateQmBars1mBsonError { - fn from(err: BsonStreamError) -> Self { - Self::Stream(err) - } -} - -impl From for CurateQmBars1mBsonError { - fn from(err: CurateBars1mWriteError) -> Self { - Self::Write(err) - } -} - -/// Pure `qmIntraday` -> `bars_1m` curation stage: validates, session-tags, and deduplicates -/// already-raw QuoteMedia 1-minute bars via [`build_bars_1m`] with an internal empty -/// [`SplitTable`] (no split un-adjustment), resolves -/// `(mapping_source, qmSearchCode, session_date) -> listing_id` on each bar's Eastern Time -/// `session_date`, stamps [`BARS_1M_SOURCE_QM`], and emits [`crate::bars_1m::Bar1mRow`] rows -/// sorted and unique by `(listing_id, ts)`. -/// -/// - Rejects empty or whitespace-only `mapping_source` with [`CurateBars1mError::EmptyMappingSource`] -/// before consuming `bars`. Non-blank `mapping_source` values are looked up verbatim. -/// - Accepts no [`SplitTable`]: raw `qmIntraday` OHLCV passes through bit-identical (aside from -/// `-0.0 -> +0.0` volume normalization). -/// - Shares [`CurateBars1mOutput`], [`crate::curate_bars_1m::CurateBars1mStats`], and -/// [`CurateBars1mError`] with [`crate::curate_bars_1m::curate_bars_1m`]. -pub fn curate_qm_bars_1m( - bars: B, - provider_mapping: &ProviderMappingTable, - mapping_source: &str, -) -> Result -where - K: Ord + Eq + Hash + Clone + AsRef, - B: IntoIterator>, -{ - if mapping_source.trim().is_empty() { - return Err(CurateBars1mError::EmptyMappingSource); - } - - let empty_splits = SplitTable::::default(); - let built = build_bars_1m(bars, &empty_splits); - Ok(map_bars_1m( - built, - provider_mapping, - mapping_source, - BARS_1M_SOURCE_QM, - )) -} - -/// Runs [`curate_qm_bars_1m`] and streams every curated row in `(listing_id, ts)` order into the -/// caller-owned [`IlpShardedWriter`] using `known_at_micros`. -/// -/// Intentionally does **not** call [`IlpShardedWriter::finish`], so callers may stream multiple -/// chunks through a single writer before flushing and collecting aggregate -/// [`crate::ilp::IlpWriteStats`]. -pub fn curate_and_write_qm_bars_1m( - bars: B, - provider_mapping: &ProviderMappingTable, - mapping_source: &str, - writer: &mut IlpShardedWriter, - known_at_micros: i64, -) -> Result -where - W: Write + Send, - K: Ord + Eq + Hash + Clone + AsRef, - B: IntoIterator>, -{ - let curated = curate_qm_bars_1m(bars, provider_mapping, mapping_source)?; - let mut rows_written = 0usize; - for row in &curated.rows { - writer.write_bar_1m(row, known_at_micros)?; - rows_written += 1; - } - - Ok(CurateBars1mWriteReport { - curate_stats: curated.stats, - rows_written, - }) -} - -/// Decodes a concatenated raw BSON `qmIntraday` stream via [`decode_qm_intraday_stream`], -/// converts each valid document via -/// [`crate::bson_qm_intraday::RawQmIntradayBar::into_eod_intraday_bar`], and runs -/// [`curate_and_write_qm_bars_1m`] against the caller-owned [`IlpShardedWriter`]. -/// -/// - Rejects empty or whitespace-only `mapping_source` before reading `reader` or writing to -/// `writer`. -/// - Per-document semantic decode errors are counted and skipped in [`BsonQmIntradayDecodeStats`]; -/// fatal stream framing or I/O errors abort before any row from this call is written to `writer`. -/// -/// # Memory note -/// This helper buffers all decoded [`EodIntradayBar`] rows for a single call in memory -/// before curating and writing. Bounded chunking by listing or calendar month is handled by -/// higher-level runner stages. -pub fn curate_and_write_qm_bars_1m_from_bson( - reader: R, - options: BsonStreamOptions, - provider_mapping: &ProviderMappingTable, - mapping_source: &str, - writer: &mut IlpShardedWriter, - known_at_micros: i64, -) -> Result -where - R: io::Read, - W: Write + Send, -{ - if mapping_source.trim().is_empty() { - return Err(CurateBars1mWriteError::Curate(CurateBars1mError::EmptyMappingSource).into()); - } - - let mut bars: Vec> = Vec::new(); - let decode_stats = decode_qm_intraday_stream( - reader, - options, - |raw| { - bars.push(raw.into_eod_intraday_bar(|code, _| code.to_owned())); - }, - |_offset, _err| {}, - )?; - - let write_report = curate_and_write_qm_bars_1m( - bars, - provider_mapping, - mapping_source, - writer, - known_at_micros, - )?; - - Ok(CurateQmBars1mBsonReport { - decode_stats, - write_report, - }) -} - -#[cfg(test)] -#[path = "curate_qm_bars_1m_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/curate_qm_bars_1m_tests.rs b/tools/curate-etl/src/curate_qm_bars_1m_tests.rs deleted file mode 100644 index 22a3eff9..00000000 --- a/tools/curate-etl/src/curate_qm_bars_1m_tests.rs +++ /dev/null @@ -1,823 +0,0 @@ -use std::error::Error; -use std::io::{self, Cursor, Read}; - -use bson::raw::{cstr, RawDocumentBuf}; -use bson::DateTime; - -use super::*; -use crate::bars_1m::{Bar1mRow, IntradaySession, BARS_1M_SOURCE_EOD, BARS_1M_SOURCE_QM}; -use crate::bson_qm_intraday::decode_qm_intraday_bytes; -use crate::curate_bars_1m::curate_bars_1m; -use crate::ilp::{encode_bar_1m, shard_for_listing_id, IlpWriterOptions, TABLE_BARS_1M}; -use crate::provider_mapping::ProviderMappingRow; -use crate::shorts::et_to_utc_micros; -use crate::split::{ymd_to_epoch_days, SplitEvent, SplitTable}; - -fn day(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).expect("valid date") -} - -fn et_ts(y: i32, m: u32, d: u32, hour: u8, minute: u8) -> i64 { - et_to_utc_micros(day(y, m, d), hour, minute, 0).expect("valid ET timestamp") -} - -fn bar_1m( - key: &str, - ts: i64, - open: f64, - high: f64, - low: f64, - close: f64, - volume: f64, -) -> EodIntradayBar { - EodIntradayBar { - key: key.to_string(), - ts, - open, - high, - low, - close, - volume, - } -} - -fn map_row( - source: &str, - source_id: &str, - valid_from: i32, - valid_to: Option, - listing_id: i32, -) -> ProviderMappingRow { - ProviderMappingRow { - source: source.to_string(), - source_id: source_id.to_string(), - valid_from, - valid_to, - listing_id, - } -} - -#[allow(clippy::too_many_arguments)] -fn make_qm_bson_doc( - code: &str, - ts_micros: i64, - open: f64, - high: f64, - low: f64, - close: f64, - sharevolume: f64, -) -> RawDocumentBuf { - assert_eq!(ts_micros % 1_000, 0, "qm timestamp must be millisecond-aligned"); - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), code); - doc.append(cstr!("timestamp"), DateTime::from_millis(ts_micros / 1_000)); - doc.append(cstr!("open"), open); - doc.append(cstr!("high"), high); - doc.append(cstr!("low"), low); - doc.append(cstr!("close"), close); - doc.append(cstr!("sharevolume"), sharevolume); - doc -} - -fn assert_conservation_and_order(out: &CurateBars1mOutput) { - let s = &out.stats; - assert_eq!( - s.rows_in, s.builder.rows_out, - "rows_in != builder.rows_out: {s:?}" - ); - assert_eq!(s.rows_out, out.rows.len(), "rows_out != rows.len(): {s:?}"); - assert_eq!( - s.rows_in, - s.rows_out - + s.dropped_unmapped - + s.listing_collision_collapsed - + s.listing_collision_dropped, - "curate_qm_bars_1m conservation invariant failed: {s:?}" - ); - assert_eq!( - s.rows_out, - s.pre_rows_out + s.rth_rows_out + s.post_rows_out, - "session breakdown != rows_out: {s:?}" - ); - - for pair in out.rows.windows(2) { - assert!( - (pair[0].key, pair[0].ts) < (pair[1].key, pair[1].ts), - "rows not strictly sorted and unique by (listing_id, ts): {:?} vs {:?}", - (pair[0].key, pair[0].ts), - (pair[1].key, pair[1].ts) - ); - } -} - -fn contains_subslice(haystack: &[u8], needle: &[u8]) -> bool { - !needle.is_empty() && haystack.windows(needle.len()).any(|w| w == needle) -} - -#[test] -fn raw_qm_passthrough_preserves_ohlcv_bits_across_future_split_unlike_eod_control() { - let pre_day = day(2024, 6, 7); - let ex_date = day(2024, 6, 10); - let nvda_listing_id = 77_001; - let pre_ts = et_ts(2024, 6, 7, 15, 59); - - // Pre-split NVDA raw values vs 10:1 retroactively split-adjusted values. - let raw_open = 1205.0_f64; - let raw_high = 1210.0_f64; - let raw_low = 1204.0_f64; - let raw_close = 1208.88_f64; - let raw_vol = 41_239.0_f64; - - let mut qm_doc = make_qm_bson_doc( - "NVDA", - pre_ts, - raw_open, - raw_high, - raw_low, - raw_close, - raw_vol, - ); - // Distinct adjusted fields in the same BSON document must be ignored. - qm_doc.append(cstr!("adjustedopen"), 120.50_f64); - qm_doc.append(cstr!("adjustedhigh"), 121.00_f64); - qm_doc.append(cstr!("adjustedlow"), 120.40_f64); - qm_doc.append(cstr!("adjustedclose"), 120.888_f64); - qm_doc.append(cstr!("avolume"), 412_390.0_f64); - - let decoded = decode_qm_intraday_bytes(qm_doc.as_bytes()).unwrap(); - let qm_bar = decoded.into_eod_intraday_bar(|code, _| code.to_owned()); - - let splits = SplitTable::from_events([( - "NVDA".to_string(), - SplitEvent { - ex_date, - ratio: 10.0, - }, - )]) - .unwrap(); - let mapping = ProviderMappingTable::from_rows([map_row( - "qm", - "NVDA", - day(2020, 1, 1), - None, - nvda_listing_id, - )]) - .unwrap(); - - // Control: EOD stage with the 10:1 split DOES scale OHLCV (and stamps BARS_1M_SOURCE_EOD). - let eod_control = curate_bars_1m([qm_bar.clone()], &splits, &mapping, "qm").unwrap(); - assert_eq!(eod_control.rows.len(), 1); - let eod_row = &eod_control.rows[0]; - assert_eq!(eod_row.source, BARS_1M_SOURCE_EOD); - assert_ne!(eod_row.open.to_bits(), qm_bar.open.to_bits()); - assert_ne!(eod_row.high.to_bits(), qm_bar.high.to_bits()); - assert_ne!(eod_row.low.to_bits(), qm_bar.low.to_bits()); - assert_ne!(eod_row.close.to_bits(), qm_bar.close.to_bits()); - assert_ne!(eod_row.volume.to_bits(), qm_bar.volume.to_bits()); - - // QuoteMedia stage accepts no SplitTable and preserves all five OHLCV fields bit-identically. - let qm_out = curate_qm_bars_1m([qm_bar.clone()], &mapping, "qm").unwrap(); - assert_conservation_and_order(&qm_out); - assert_eq!(qm_out.rows.len(), 1); - let row = &qm_out.rows[0]; - assert_eq!(row.key, nvda_listing_id); - assert_eq!(row.ts, pre_ts); - assert_eq!(row.session_date, pre_day); - assert_eq!(row.session, IntradaySession::Rth); - assert_eq!(row.source, BARS_1M_SOURCE_QM); - assert_ne!(row.source, BARS_1M_SOURCE_EOD); - assert_eq!(row.open.to_bits(), raw_open.to_bits()); - assert_eq!(row.high.to_bits(), raw_high.to_bits()); - assert_eq!(row.low.to_bits(), raw_low.to_bits()); - assert_eq!(row.close.to_bits(), raw_close.to_bits()); - assert_eq!(row.volume.to_bits(), raw_vol.to_bits()); -} - -#[test] -fn mapping_uses_eastern_time_session_date_boundaries_gaps_and_is_shuffle_invariant() { - // 2024-06-10 20:30 ET (EDT = UTC-4) is 2024-06-11 00:30 UTC (next UTC calendar day). - // Mapping ends inclusively on 2024-06-10, so ET session_date resolves while UTC date would drop. - let d_start = day(2024, 6, 10); - let d_gap = day(2024, 6, 11); - let d_resume = day(2024, 6, 12); - - let mapping = ProviderMappingTable::from_rows([ - map_row("qm", "ACME:CA", d_start, Some(d_start), 101), - map_row("qm", "ACME:CA", d_resume, None, 202), - map_row("qm", "BETA", d_start, Some(d_resume), 303), - ]) - .unwrap(); - - // PRE on inclusive valid_from (2024-06-10 08:00 ET) -> listing 101 - let b_pre = bar_1m("ACME:CA", et_ts(2024, 6, 10, 8, 0), 10.0, 10.2, 9.9, 10.1, 100.0); - // POST on inclusive valid_to whose UTC date is 2024-06-11 -> listing 101 - let b_post_utc_next = bar_1m("ACME:CA", et_ts(2024, 6, 10, 20, 30), 10.1, 10.3, 10.0, 10.2, 50.0); - // Date inside gap (2024-06-11) -> dropped_unmapped - let b_gap = bar_1m("ACME:CA", et_ts(2024, 6, 11, 10, 0), 10.5, 10.6, 10.4, 10.5, 200.0); - // RTH on inclusive second range valid_from (2024-06-12) -> listing 202 - let b_resumed = bar_1m("ACME:CA", et_ts(2024, 6, 12, 10, 0), 11.0, 11.2, 10.9, 11.1, 300.0); - // RTH for BETA on 2024-06-11 -> listing 303 - let b_beta = bar_1m("BETA", et_ts(2024, 6, 11, 14, 15), 25.0, 25.5, 24.8, 25.2, 400.0); - // Unknown qmSearchCode -> dropped_unmapped - let b_unknown = bar_1m("UNKNOWN", et_ts(2024, 6, 10, 10, 0), 5.0, 5.1, 4.9, 5.0, 10.0); - - let ordered = vec![ - b_pre.clone(), - b_post_utc_next.clone(), - b_gap.clone(), - b_resumed.clone(), - b_beta.clone(), - b_unknown.clone(), - ]; - let shuffled = vec![ - b_unknown, - b_resumed, - b_post_utc_next, - b_beta, - b_gap, - b_pre, - ]; - - let out_ordered = curate_qm_bars_1m(ordered, &mapping, "qm").unwrap(); - let out_shuffled = curate_qm_bars_1m(shuffled, &mapping, "qm").unwrap(); - - assert_conservation_and_order(&out_ordered); - assert_conservation_and_order(&out_shuffled); - assert_eq!(out_ordered, out_shuffled); - - assert_eq!(out_ordered.stats.rows_in, 6); - assert_eq!(out_ordered.stats.rows_out, 4); - assert_eq!(out_ordered.stats.dropped_unmapped, 2); - assert_eq!(out_ordered.stats.listings_out, 3); - assert_eq!(out_ordered.stats.pre_rows_out, 1); - assert_eq!(out_ordered.stats.rth_rows_out, 2); - assert_eq!(out_ordered.stats.post_rows_out, 1); - - // Verify exact ET session_date and listing assignment on the UTC-next-day POST bar. - let post_row = out_ordered - .rows - .iter() - .find(|r| r.session == IntradaySession::Post) - .expect("POST row present"); - assert_eq!(post_row.key, 101); - assert_eq!(post_row.session_date, d_start); - assert_ne!(post_row.session_date, d_gap); - assert!(out_ordered.rows.iter().all(|r| r.source == BARS_1M_SOURCE_QM)); -} - -#[test] -fn same_code_duplicates_and_cross_code_alias_collisions_enforce_conservation() { - let listing_id = 505; - let mapping = ProviderMappingTable::from_rows([ - map_row("qm", "OLD:CA", day(2024, 1, 1), None, listing_id), - map_row("qm", "NEW:CA", day(2024, 1, 1), None, listing_id), - map_row("qm", "ALT:CA", day(2024, 1, 1), None, listing_id), - ]) - .unwrap(); - - let ts_same_dup = et_ts(2024, 6, 10, 9, 30); - let ts_alias_ok = et_ts(2024, 6, 10, 9, 31); - let ts_alias_conflict = et_ts(2024, 6, 10, 9, 32); - let ts_unique_post = et_ts(2024, 6, 10, 16, 5); - - let bars = vec![ - // Same-code exact duplicate -> collapsed in builder (duplicate_collapsed = 1). - bar_1m("OLD:CA", ts_same_dup, 10.0, 10.5, 9.8, 10.2, 100.0), - bar_1m("OLD:CA", ts_same_dup, 10.0, 10.5, 9.8, 10.2, 100.0), - // Three distinct qmSearchCodes with bit-identical OHLCV -> group of 3 collapses by g-1 = 2. - bar_1m("OLD:CA", ts_alias_ok, 10.2, 10.6, 10.1, 10.4, 250.0), - bar_1m("NEW:CA", ts_alias_ok, 10.2, 10.6, 10.1, 10.4, 250.0), - bar_1m("ALT:CA", ts_alias_ok, 10.2, 10.6, 10.1, 10.4, 250.0), - // Two distinct qmSearchCodes with conflicting close -> entire group of g = 2 dropped. - bar_1m("OLD:CA", ts_alias_conflict, 10.4, 10.8, 10.3, 10.5, 300.0), - bar_1m("NEW:CA", ts_alias_conflict, 10.4, 10.8, 10.3, 10.6, 300.0), - // Clean POST row. - bar_1m("NEW:CA", ts_unique_post, 10.6, 10.7, 10.5, 10.65, 0.0), - ]; - - let out = curate_qm_bars_1m(bars, &mapping, "qm").unwrap(); - assert_conservation_and_order(&out); - - assert_eq!(out.stats.builder.bars_in, 8); - assert_eq!(out.stats.builder.duplicate_collapsed, 1); - assert_eq!(out.stats.builder.rows_out, 7); - assert_eq!(out.stats.rows_in, 7); - assert_eq!(out.stats.listing_collision_collapsed, 2); - assert_eq!(out.stats.listing_collision_dropped, 2); - assert_eq!(out.stats.dropped_unmapped, 0); - assert_eq!(out.stats.rows_out, 3); - assert_eq!(out.stats.listings_out, 1); - assert_eq!(out.stats.pre_rows_out, 0); - assert_eq!(out.stats.rth_rows_out, 2); - assert_eq!(out.stats.post_rows_out, 1); - - let emitted_ts: Vec = out.rows.iter().map(|r| r.ts).collect(); - assert_eq!(emitted_ts, vec![ts_same_dup, ts_alias_ok, ts_unique_post]); - assert!(out.rows.iter().all(|r| r.source == BARS_1M_SOURCE_QM)); -} - -#[test] -fn bson_to_ilp_streams_multi_chunk_writes_qm_raw_and_supports_writer_reuse() { - let known_at = 1_718_050_123_456_000_i64; - let mapping = ProviderMappingTable::from_rows([ - map_row("qm", "NVDA", day(2020, 1, 1), None, 101), - map_row("qm", "SHOP:CA", day(2020, 1, 1), None, 202), - ]) - .unwrap(); - - let ts1 = et_ts(2024, 6, 7, 15, 59); - let ts2 = et_ts(2024, 6, 10, 9, 30); - let ts3 = et_ts(2024, 6, 10, 16, 10); - - let doc1 = make_qm_bson_doc("NVDA", ts1, 1205.0, 1210.0, 1204.0, 1208.88, 41_239.0); - // Semantically invalid doc: missing required field `close`. - let mut bad_doc = RawDocumentBuf::new(); - bad_doc.append(cstr!("qmSearchCode"), "NVDA"); - bad_doc.append(cstr!("timestamp"), DateTime::from_millis(ts2 / 1_000)); - bad_doc.append(cstr!("open"), 120.0_f64); - bad_doc.append(cstr!("high"), 121.0_f64); - bad_doc.append(cstr!("low"), 119.5_f64); - bad_doc.append(cstr!("sharevolume"), 1_000.0_f64); - let doc2 = make_qm_bson_doc("SHOP:CA", ts2, 88.0, 89.0, 87.5, 88.4, 2_500.0); - - let mut chunk1_bytes = Vec::new(); - chunk1_bytes.extend_from_slice(doc1.as_bytes()); - chunk1_bytes.extend_from_slice(bad_doc.as_bytes()); - chunk1_bytes.extend_from_slice(doc2.as_bytes()); - - let doc3 = make_qm_bson_doc("NVDA", ts3, 121.0, 121.5, 120.8, 121.2, 5_000.0); - let chunk2_bytes = doc3.as_bytes().to_vec(); - - // Force multi-chunk streaming with a tiny chunk capacity smaller than two documents. - let stream_opts = BsonStreamOptions { - chunk_capacity_bytes: 64, - max_doc_bytes: 4096, - }; - - let mut s0 = Vec::new(); - let mut s1 = Vec::new(); - let mut s2 = Vec::new(); - let mut s3 = Vec::new(); - let (rep1, rep2, ilp_stats) = { - let mut writer = IlpShardedWriter::new( - vec![&mut s0, &mut s1, &mut s2, &mut s3], - IlpWriterOptions::default(), - ) - .unwrap(); - let rep1 = curate_and_write_qm_bars_1m_from_bson( - Cursor::new(&chunk1_bytes), - stream_opts, - &mapping, - "qm", - &mut writer, - known_at, - ) - .unwrap(); - // Reuse the same open writer for a second call. - let rep2 = curate_and_write_qm_bars_1m_from_bson( - Cursor::new(&chunk2_bytes), - stream_opts, - &mapping, - "qm", - &mut writer, - known_at, - ) - .unwrap(); - let stats = writer.finish().unwrap(); - (rep1, rep2, stats) - }; - - assert_eq!(rep1.decode_stats.docs_seen, 3); - assert_eq!(rep1.decode_stats.rows_decoded, 2); - assert_eq!(rep1.decode_stats.rejected_missing_field, 1); - assert_eq!( - rep1.decode_stats.docs_seen, - rep1.decode_stats.rows_decoded + rep1.decode_stats.rejected_total() - ); - assert_eq!(rep1.write_report.rows_written, 2); - assert_eq!( - rep1.write_report.rows_written, - rep1.write_report.curate_stats.rows_out - ); - - assert_eq!(rep2.decode_stats.docs_seen, 1); - assert_eq!(rep2.decode_stats.rows_decoded, 1); - assert_eq!(rep2.write_report.rows_written, 1); - assert_eq!( - ilp_stats.rows, - rep1.write_report.rows_written + rep2.write_report.rows_written - ); - assert_eq!(ilp_stats.rows, 3); - - // Build expected exact ILP lines for each emitted row and verify per-shard routing, - // `source=qm_raw`, exact `known_at`, and per-shard ordering. - let expected_row1 = Bar1mRow { - key: 101, - ts: ts1, - session_date: day(2024, 6, 7), - open: 1205.0, - high: 1210.0, - low: 1204.0, - close: 1208.88, - volume: 41_239.0, - session: IntradaySession::Rth, - source: BARS_1M_SOURCE_QM, - }; - let expected_row2 = Bar1mRow { - key: 202, - ts: ts2, - session_date: day(2024, 6, 10), - open: 88.0, - high: 89.0, - low: 87.5, - close: 88.4, - volume: 2_500.0, - session: IntradaySession::Rth, - source: BARS_1M_SOURCE_QM, - }; - let expected_row3 = Bar1mRow { - key: 101, - ts: ts3, - session_date: day(2024, 6, 10), - open: 121.0, - high: 121.5, - low: 120.8, - close: 121.2, - volume: 5_000.0, - session: IntradaySession::Post, - source: BARS_1M_SOURCE_QM, - }; - - let mut expected_shards = vec![Vec::::new(); 4]; - for row in [&expected_row1, &expected_row2, &expected_row3] { - let shard = shard_for_listing_id(row.key, 4); - encode_bar_1m(&mut expected_shards[shard], row, known_at).unwrap(); - } - - let actual_shards = [&s0, &s1, &s2, &s3]; - for (idx, (actual, expected)) in actual_shards.iter().zip(&expected_shards).enumerate() { - assert_eq!(*actual, expected, "shard {idx} ILP bytes mismatch"); - } - - let all_bytes: Vec = actual_shards.iter().flat_map(|s| s.iter().copied()).collect(); - assert!(contains_subslice(&all_bytes, TABLE_BARS_1M.as_bytes())); - assert!(contains_subslice( - &all_bytes, - format!("source={BARS_1M_SOURCE_QM}").as_bytes() - )); - assert!(!contains_subslice( - &all_bytes, - format!("source={BARS_1M_SOURCE_EOD}").as_bytes() - )); - assert!(contains_subslice( - &all_bytes, - format!("known_at={known_at}t").as_bytes() - )); -} - -struct CountingReader { - inner: R, - reads: usize, -} - -impl Read for CountingReader { - fn read(&mut self, buf: &mut [u8]) -> io::Result { - self.reads += 1; - self.inner.read(buf) - } -} - -#[test] -fn truncated_stream_and_blank_mapping_source_fail_closed_with_zero_writes() { - let mapping = ProviderMappingTable::from_rows([map_row( - "qm", - "NVDA", - day(2020, 1, 1), - None, - 101, - )]) - .unwrap(); - let known_at = 1_718_050_000_000_000_i64; - - let doc1 = make_qm_bson_doc( - "NVDA", - et_ts(2024, 6, 7, 15, 59), - 1205.0, - 1210.0, - 1204.0, - 1208.88, - 41_239.0, - ); - let doc2 = make_qm_bson_doc( - "NVDA", - et_ts(2024, 6, 10, 15, 59), - 121.0, - 121.5, - 120.8, - 121.2, - 5_000.0, - ); - - // Truncated tail after a valid document with max_batch_rows = 1 must write zero bytes. - let mut truncated_bytes = Vec::new(); - truncated_bytes.extend_from_slice(doc1.as_bytes()); - let doc2_bytes = doc2.as_bytes(); - truncated_bytes.extend_from_slice(&doc2_bytes[..doc2_bytes.len() / 2]); - - let mut s0 = Vec::new(); - let mut s1 = Vec::new(); - let (err, trunc_stats) = { - let mut writer = IlpShardedWriter::new( - vec![&mut s0, &mut s1], - IlpWriterOptions { - max_batch_bytes: 1024, - max_batch_rows: 1, - }, - ) - .unwrap(); - let err = curate_and_write_qm_bars_1m_from_bson( - Cursor::new(&truncated_bytes), - BsonStreamOptions::default(), - &mapping, - "qm", - &mut writer, - known_at, - ) - .unwrap_err(); - let stats = writer.finish().unwrap(); - (err, stats) - }; - assert!(matches!( - err, - CurateQmBars1mBsonError::Stream(BsonStreamError::TruncatedDocument { .. }) - )); - assert!(err.source().is_some()); - assert_eq!(trunc_stats.rows, 0); - assert!(s0.is_empty()); - assert!(s1.is_empty()); - - // Blank mapping_source on pure stage returns EmptyMappingSource. - let pure_err = curate_qm_bars_1m( - [bar_1m("NVDA", et_ts(2024, 6, 7, 15, 59), 10.0, 11.0, 9.0, 10.5, 100.0)], - &mapping, - " \t", - ) - .unwrap_err(); - assert_eq!(pure_err, CurateBars1mError::EmptyMappingSource); - - // Blank mapping_source on BSON stage rejects before any read or write. - let mut counting_reader = CountingReader { - inner: Cursor::new(doc1.as_bytes()), - reads: 0, - }; - let mut sink = Vec::new(); - let (blank_err, blank_stats) = { - let mut writer = IlpShardedWriter::new( - vec![&mut sink], - IlpWriterOptions { - max_batch_bytes: 1024, - max_batch_rows: 1, - }, - ) - .unwrap(); - let err = curate_and_write_qm_bars_1m_from_bson( - &mut counting_reader, - BsonStreamOptions::default(), - &mapping, - " \n\t ", - &mut writer, - known_at, - ) - .unwrap_err(); - let stats = writer.finish().unwrap(); - (err, stats) - }; - assert!(matches!( - blank_err, - CurateQmBars1mBsonError::Write(CurateBars1mWriteError::Curate( - CurateBars1mError::EmptyMappingSource - )) - )); - assert!(blank_err.source().is_some()); - assert_eq!(counting_reader.reads, 0); - assert_eq!(blank_stats.rows, 0); - assert!(sink.is_empty()); -} - -// --------------------------------------------------------------------------------------------- -// QA (T-152) additional coverage. -// --------------------------------------------------------------------------------------------- - -#[test] -fn qa_bson_to_ilp_reorders_reverse_ts_rows_within_one_shard_and_reuses_writer() { - // Two valid bars for the same listing in REVERSE timestamp order in one BSON call: the shard - // must receive them ascending by ts. A single shard makes every row share one sink. - let known_at = 1_718_100_000_000_000_i64; - let mapping = - ProviderMappingTable::from_rows([map_row("qm", "NVDA", day(2020, 1, 1), None, 101)]) - .unwrap(); - let ts_early = et_ts(2024, 6, 10, 9, 30); - let ts_late = et_ts(2024, 6, 10, 9, 45); - let ts_next = et_ts(2024, 6, 11, 9, 30); - - let late = make_qm_bson_doc("NVDA", ts_late, 121.0, 122.0, 120.5, 121.5, 900.0); - let early = make_qm_bson_doc("NVDA", ts_early, 120.0, 120.9, 119.8, 120.6, 700.0); - let mut call1 = Vec::new(); - call1.extend_from_slice(late.as_bytes()); - call1.extend_from_slice(early.as_bytes()); - let call2 = make_qm_bson_doc("NVDA", ts_next, 123.0, 123.5, 122.5, 123.1, 1_100.0) - .as_bytes() - .to_vec(); - - let opts = BsonStreamOptions { - chunk_capacity_bytes: 48, - max_doc_bytes: 4096, - }; - let mut sink = Vec::new(); - let (rep1, rep2, stats) = { - let mut writer = IlpShardedWriter::new( - vec![&mut sink], - IlpWriterOptions { - max_batch_bytes: 1 << 16, - max_batch_rows: 1, - }, - ) - .unwrap(); - let rep1 = curate_and_write_qm_bars_1m_from_bson( - Cursor::new(&call1), - opts, - &mapping, - "qm", - &mut writer, - known_at, - ) - .unwrap(); - let rep2 = curate_and_write_qm_bars_1m_from_bson( - Cursor::new(&call2), - opts, - &mapping, - "qm", - &mut writer, - known_at, - ) - .unwrap(); - (rep1, rep2, writer.finish().unwrap()) - }; - assert_eq!(rep1.write_report.rows_written, 2); - assert_eq!(rep2.write_report.rows_written, 1); - assert_eq!(stats.rows, 3); - - let row = |ts: i64, o: f64, h: f64, l: f64, c: f64, v: f64, date: i32| Bar1mRow { - key: 101, - ts, - session_date: date, - open: o, - high: h, - low: l, - close: c, - volume: v, - session: IntradaySession::Rth, - source: BARS_1M_SOURCE_QM, - }; - let mut expected = Vec::new(); - for r in [ - row(ts_early, 120.0, 120.9, 119.8, 120.6, 700.0, day(2024, 6, 10)), - row(ts_late, 121.0, 122.0, 120.5, 121.5, 900.0, day(2024, 6, 10)), - row(ts_next, 123.0, 123.5, 122.5, 123.1, 1_100.0, day(2024, 6, 11)), - ] { - encode_bar_1m(&mut expected, &r, known_at).unwrap(); - } - assert_eq!(sink, expected, "shard must receive rows ascending by ts across calls"); -} - -#[test] -fn qa_invalid_ohlcv_and_out_of_range_dates_are_accounted_and_volume_neg_zero_normalized() { - let mapping = ProviderMappingTable::from_rows([map_row( - "qm", - "ACME", - day(2024, 6, 10), - Some(day(2024, 6, 10)), - 9, - )]) - .unwrap(); - let bars = vec![ - // Valid, -0.0 volume -> +0.0. - bar_1m("ACME", et_ts(2024, 6, 10, 10, 0), 10.0, 10.5, 9.5, 10.2, -0.0), - // high < low -> builder drops (inconsistent). - bar_1m("ACME", et_ts(2024, 6, 10, 10, 1), 10.0, 9.0, 9.5, 10.2, 1.0), - // NaN close -> builder drops. - bar_1m("ACME", et_ts(2024, 6, 10, 10, 2), 10.0, 10.5, 9.5, f64::NAN, 1.0), - // Negative volume -> builder drops. - bar_1m("ACME", et_ts(2024, 6, 10, 10, 3), 10.0, 10.5, 9.5, 10.2, -5.0), - // Day before valid_from and day after valid_to -> dropped_unmapped. - bar_1m("ACME", et_ts(2024, 6, 7, 10, 0), 10.0, 10.5, 9.5, 10.2, 1.0), - bar_1m("ACME", et_ts(2024, 6, 11, 10, 0), 10.0, 10.5, 9.5, 10.2, 1.0), - ]; - let out = curate_qm_bars_1m(bars, &mapping, "qm").unwrap(); - assert_conservation_and_order(&out); - let b = &out.stats.builder; - assert_eq!(b.bars_in, 6); - assert_eq!( - b.dropped_invalid_ohlc + b.dropped_inconsistent_ohlc + b.dropped_invalid_volume, - 3, - "{b:?}" - ); - assert_eq!(out.stats.rows_in, 3); - assert_eq!(out.stats.dropped_unmapped, 2); - assert_eq!(out.rows.len(), 1); - assert_eq!(out.rows[0].volume.to_bits(), 0.0_f64.to_bits()); - assert_eq!(out.rows[0].source, BARS_1M_SOURCE_QM); -} - -#[test] -fn qa_mapping_source_is_namespace_scoped_and_matched_verbatim() { - // Same code under a different provider namespace (`eod`) must not resolve for `qm`. - let mapping = ProviderMappingTable::from_rows([ - map_row("eod", "NVDA", day(2020, 1, 1), None, 1), - map_row("qm", "NVDA", day(2020, 1, 1), None, 2), - ]) - .unwrap(); - let bars = || [bar_1m("NVDA", et_ts(2024, 6, 10, 10, 0), 1.0, 1.0, 1.0, 1.0, 1.0)]; - let qm = curate_qm_bars_1m(bars(), &mapping, "qm").unwrap(); - assert_eq!(qm.rows.len(), 1); - assert_eq!(qm.rows[0].key, 2); - // Padded namespace is non-blank and looked up verbatim -> nothing matches. - let padded = curate_qm_bars_1m(bars(), &mapping, " qm").unwrap(); - assert_conservation_and_order(&padded); - assert_eq!(padded.rows.len(), 0); - assert_eq!(padded.stats.dropped_unmapped, 1); -} - -#[test] -fn qa_curate_and_write_blank_namespace_and_multichunk_truncation_write_nothing() { - let mapping = - ProviderMappingTable::from_rows([map_row("qm", "NVDA", day(2020, 1, 1), None, 101)]) - .unwrap(); - let known_at = 1_718_000_000_000_000_i64; - - // In-memory write path: blank namespace -> Curate error, zero bytes. - let mut sink = Vec::new(); - { - let mut writer = IlpShardedWriter::new( - vec![&mut sink], - IlpWriterOptions { - max_batch_bytes: 1, - max_batch_rows: 1, - }, - ) - .unwrap(); - let err = curate_and_write_qm_bars_1m( - [bar_1m("NVDA", et_ts(2024, 6, 10, 10, 0), 1.0, 1.0, 1.0, 1.0, 1.0)], - &mapping, - "", - &mut writer, - known_at, - ) - .unwrap_err(); - assert!(matches!( - err, - CurateBars1mWriteError::Curate(CurateBars1mError::EmptyMappingSource) - )); - assert_eq!(writer.finish().unwrap().rows, 0); - } - assert!(sink.is_empty()); - - // Many valid docs streamed across many small chunks, then a truncated tail: zero bytes. - let mut bytes = Vec::new(); - for m in 0..20u8 { - let doc = make_qm_bson_doc("NVDA", et_ts(2024, 6, 10, 10, m), 1.0, 1.0, 1.0, 1.0, 1.0); - bytes.extend_from_slice(doc.as_bytes()); - } - bytes.extend_from_slice(&200_i32.to_le_bytes()); - bytes.extend_from_slice(&[0x02, b'x']); - let mut s0 = Vec::new(); - let mut s1 = Vec::new(); - { - let mut writer = IlpShardedWriter::new( - vec![&mut s0, &mut s1], - IlpWriterOptions { - max_batch_bytes: 1, - max_batch_rows: 1, - }, - ) - .unwrap(); - let err = curate_and_write_qm_bars_1m_from_bson( - Cursor::new(&bytes), - BsonStreamOptions { - chunk_capacity_bytes: 40, - max_doc_bytes: 4096, - }, - &mapping, - "qm", - &mut writer, - known_at, - ) - .unwrap_err(); - assert!(matches!( - err, - CurateQmBars1mBsonError::Stream(BsonStreamError::TruncatedDocument { .. }) - )); - assert_eq!(writer.finish().unwrap().rows, 0); - } - assert!(s0.is_empty() && s1.is_empty()); -} diff --git a/tools/curate-etl/src/events.rs b/tools/curate-etl/src/events.rs index a66653d5..e1f6b52b 100644 --- a/tools/curate-etl/src/events.rs +++ b/tools/curate-etl/src/events.rs @@ -494,7 +494,7 @@ fn sanitize_opt_f64(value: Option) -> Option { const HEX_LOWER: &[u8; 16] = b"0123456789abcdef"; -pub(crate) fn push_json_str(out: &mut String, s: &str) { +fn push_json_str(out: &mut String, s: &str) { out.push('"'); let bytes = s.as_bytes(); let mut start = 0usize; @@ -534,7 +534,7 @@ pub(crate) fn push_json_str(out: &mut String, s: &str) { } #[inline] -pub(crate) fn push_json_opt_str(out: &mut String, s: Option<&str>) { +fn push_json_opt_str(out: &mut String, s: Option<&str>) { match s { Some(v) => push_json_str(out, v), None => out.push_str("null"), diff --git a/tools/curate-etl/src/fundamentals.rs b/tools/curate-etl/src/fundamentals.rs deleted file mode 100644 index 7ac7cae6..00000000 --- a/tools/curate-etl/src/fundamentals.rs +++ /dev/null @@ -1,1030 +0,0 @@ -//! Pure, in-memory point-in-time `fundamentals` builder (`qmFinancials` × `qmFilings` → -//! `fundamentals_bitemporal` rows → 2D `fundamentals_pit` snapshots + 4-quarter TTM). -//! -//! Aligned with `design/DATA-CONTRACTS.md` (§1 `qmFinancials`/`qmFilings` and §3A -//! `fundamentals_bitemporal` / `fundamentals_pit`): -//! -//! ## Stage 1 — Bitemporal Rows (`build_fundamentals_rows`) -//! - **Filing classification & timestamp parsing:** reuses [`crate::events::classify_form_type`], -//! [`FilingFormGroup::is_periodic_financial_report`], and -//! [`crate::events::parse_filing_timefiled`]. `10-Q` and SEDAR `Interim financial statements` -//! map to [`FiscalPeriod::Quarterly`]; `10-K`, `40-F`, and SEDAR `Annual financial statements` -//! map to [`FiscalPeriod::Annual`]. Non-periodic forms (such as `8-K`, `4`, `144`, `MD&A`, -//! `News release`) are never linked. -//! - **Heuristic filing-link rules (sampled `qmFilings` carries no statement-period field):** -//! - **Dated observation (`report_date: Some(rd)`):** `report_date` is assumed to identify the -//! observation's Eastern Time filing/vintage date. Links to the earliest matching periodic -//! filing (amended or unamended) for the same `(key, fiscal_period)` with `et_date == rd` -//! (strictly after `period_end`, because `rd <= period_end` is rejected). A same-day match can -//! anchor a late restatement/amendment beyond the inference windows below. -//! - **Undated observation (`report_date: None`):** links to the earliest matching -//! **non-amended** periodic filing for the same `(key, fiscal_period)` strictly after -//! `period_end` and within an inclusive calendar-day window of -//! [`QUARTERLY_FILING_LINK_WINDOW_DAYS`] (`75` days) for quarterly reports or -//! [`ANNUAL_FILING_LINK_WINDOW_DAYS`] (`150` days) for annual reports. -//! - Linked rows carry `known_at_utc_micros = parsed.utc_micros` and -//! `known_at_source = "filing_timestamp"`. -//! - **Statutory-lag fallback (unlinked observations):** -//! - `lag_date = period_end + venue.lag_days(fiscal_period)`: -//! - US & TSX ([`StatutoryLagVenue::UsTsx`]): `+45` calendar days (Q) / `+90` calendar days (FY). -//! - TSXV & CSE ([`StatutoryLagVenue::TsxvCse`]): `+60` calendar days (Q) / `+120` calendar days (FY). -//! - If a dated observation (`report_date: Some(rd)`) has no same-day filing link and -//! `rd > lag_date`, it is dropped and counted as an unanchored vintage -//! (`observations_dropped_unanchored_vintage`) rather than backdating `known_at` before its -//! observed `report_date`. -//! - If a dated statutory-lag estimate (`report_date: Some(rd_a)`) for `(key, period_end, -//! fiscal_period)` would become visible at or after an accepted newer dated version -//! (`rd_b > rd_a`, `known_at_b <= lag_micros`) of the same statement, the stale estimate is -//! dropped and counted in `observations_dropped_stale_estimate` so an older vintage never rolls -//! a newer filing backward. -//! - Otherwise `known_at_utc_micros` is `lag_date` at `16:05:00 America/Toronto` -//! ([`FUNDAMENTALS_FALLBACK_HOUR_ET`]:[`FUNDAMENTALS_FALLBACK_MINUTE_ET`]) via -//! [`crate::shorts::et_to_utc_micros`], tagged `known_at_source = "statutory_lag_estimate"`. -//! - **Calendar bounds & bad-row resilience:** statement `period_end`, optional `report_date`, -//! periodic filing Eastern days, and computed `lag_date` are validated against -//! [`MIN_SUPPORTED_DATE`]..=[`MAX_SUPPORTED_DATE`] (`2008-01-01..=2030-12-31`). Periodic filings -//! with `et_date <= earliest_period_end` for that `(key, fiscal_period)` are excluded and counted -//! in `filings_dropped_before_period_end`. Bad rows never panic; each category is counted in -//! [`FundamentalsStats`]. -//! - **Normalization, deduplication & sort:** `-0.0` normalizes to `0.0`. Rows are sorted by -//! `(key, period_end, known_at_utc_micros)`. Bitwise-identical duplicates at the same -//! `(key, period_end, known_at_utc_micros)` collapse (`duplicate_collapsed`); conflicting groups -//! (differing values, currency, fiscal period, or provenance) are discarded entirely -//! (`duplicate_conflict_dropped`). Distinct `known_at_utc_micros` versions for the same -//! `(key, period_end)` are preserved as separate restatement versions. -//! -//! ## Stage 2 — 2D PIT Snapshots & TTM (`build_fundamentals_snapshots`, `as_of`) -//! - Sweeps rows in `(key, known_at_utc_micros, period_end)` order, applying all updates sharing -//! `(key, effective_known_at_utc_micros)` before emitting one [`FundamentalsSnapshot`]. -//! - Maintains the latest visible version per `period_end`, carrying `None` fields forward from -//! the previous visible version of the **same** `(period_end, fiscal_period, currency)` along -//! with per-field provenance. -//! - Emits the latest `k` visible periods in descending `period_end` order (annual rows may occupy -//! slots; stock fields remain reported period values). -//! - Independently of `k` and of annual (`FY`) rows sharing a `period_end` (such as a calendar -//! year-end `10-K` sharing December 31 with standalone `Q4`), resolves standalone quarterly -//! versions separately and computes 4-quarter TTM sums for flow fields (`revenue`, `net_income`, -//! `operating_cash_flow`) from the 4 latest visible standalone quarterly periods when adjacent -//! `period_end` spacing is within [`TTM_CONSECUTIVE_QUARTER_MIN_DAYS`]..=[`TTM_CONSECUTIVE_QUARTER_MAX_DAYS`] -//! (`77..=105` calendar days, a heuristic given the input lacks a fiscal-quarter ordinal) and -//! all 4 share one currency. Missing flow inputs or non-finite sums produce `None` for that -//! field. -//! - Flags `has_estimated_lag = true` (and `known_at_source = "statutory_lag_estimate"`) if any -//! visible period slot or any quarter contributing to `ttm` used `statutory_lag_estimate` -//! (directly or via an inherited field). - -use std::borrow::Borrow; -use std::cmp::Ordering; -use std::collections::BTreeMap; -use std::error::Error; -use std::fmt; - -use crate::events::{ - classify_form_type, parse_filing_timefiled, FilingFormGroup, QmFiling, - KNOWN_AT_SOURCE_FILING_TIMESTAMP, KNOWN_AT_SOURCE_STATUTORY_LAG, -}; -use crate::shorts::{et_to_utc_micros, MAX_SUPPORTED_DATE, MIN_SUPPORTED_DATE}; - -/// Statutory quarterly reporting lag (calendar days) for US & TSX listings (`design/DATA-CONTRACTS.md` §1). -pub const STATUTORY_LAG_US_TSX_QUARTERLY_DAYS: i32 = 45; - -/// Statutory annual reporting lag (calendar days) for US & TSX listings (`design/DATA-CONTRACTS.md` §1). -pub const STATUTORY_LAG_US_TSX_ANNUAL_DAYS: i32 = 90; - -/// Statutory quarterly reporting lag (calendar days) for TSXV & CSE listings (`design/DATA-CONTRACTS.md` §1). -pub const STATUTORY_LAG_TSXV_CSE_QUARTERLY_DAYS: i32 = 60; - -/// Statutory annual reporting lag (calendar days) for TSXV & CSE listings (`design/DATA-CONTRACTS.md` §1). -pub const STATUTORY_LAG_TSXV_CSE_ANNUAL_DAYS: i32 = 120; - -/// Conservative fallback hour (`16:05 America/Toronto`) for statutory-lag `known_at` timestamps. -pub const FUNDAMENTALS_FALLBACK_HOUR_ET: u8 = 16; - -/// Conservative fallback minute (`16:05 America/Toronto`) for statutory-lag `known_at` timestamps. -pub const FUNDAMENTALS_FALLBACK_MINUTE_ET: u8 = 5; - -/// Inclusive heuristic filing-link window (calendar days strictly after `period_end`) for undated -/// quarterly observations when `qmFilings` carries no statement-period field. -pub const QUARTERLY_FILING_LINK_WINDOW_DAYS: i32 = 75; - -/// Inclusive heuristic filing-link window (calendar days strictly after `period_end`) for undated -/// annual observations when `qmFilings` carries no statement-period field. -pub const ANNUAL_FILING_LINK_WINDOW_DAYS: i32 = 150; - -/// Minimum inclusive calendar-day gap between adjacent quarterly `period_end` dates to be treated -/// as consecutive for 4-quarter TTM summation. -pub const TTM_CONSECUTIVE_QUARTER_MIN_DAYS: i32 = 77; - -/// Maximum inclusive calendar-day gap between adjacent quarterly `period_end` dates to be treated -/// as consecutive for 4-quarter TTM summation. -pub const TTM_CONSECUTIVE_QUARTER_MAX_DAYS: i32 = 105; - -/// Number of consecutive standalone quarters required to compute TTM flow sums. -pub const TTM_QUARTER_COUNT: usize = 4; - -/// Fiscal statement period kind. -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub enum FiscalPeriod { - Quarterly, - Annual, -} - -impl FiscalPeriod { - /// Canonical contract label (`"Q"` or `"FY"`). - #[inline] - pub const fn as_str(self) -> &'static str { - match self { - Self::Quarterly => "Q", - Self::Annual => "FY", - } - } - - /// Inclusive heuristic link window in calendar days for undated observations. - #[inline] - pub const fn undated_link_window_days(self) -> i32 { - match self { - Self::Quarterly => QUARTERLY_FILING_LINK_WINDOW_DAYS, - Self::Annual => ANNUAL_FILING_LINK_WINDOW_DAYS, - } - } -} - -/// Per-listing venue class governing statutory deadline lag fallback. -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub enum StatutoryLagVenue { - /// US exchanges and Toronto Stock Exchange (`+45d` Q / `+90d` FY). - UsTsx, - /// TSX Venture Exchange and Canadian Securities Exchange (`+60d` Q / `+120d` FY). - TsxvCse, -} - -impl StatutoryLagVenue { - /// Exact calendar-day statutory deadline lag for `(self, fiscal_period)`. - #[inline] - pub const fn lag_days(self, fiscal_period: FiscalPeriod) -> i32 { - match (self, fiscal_period) { - (Self::UsTsx, FiscalPeriod::Quarterly) => STATUTORY_LAG_US_TSX_QUARTERLY_DAYS, - (Self::UsTsx, FiscalPeriod::Annual) => STATUTORY_LAG_US_TSX_ANNUAL_DAYS, - (Self::TsxvCse, FiscalPeriod::Quarterly) => STATUTORY_LAG_TSXV_CSE_QUARTERLY_DAYS, - (Self::TsxvCse, FiscalPeriod::Annual) => STATUTORY_LAG_TSXV_CSE_ANNUAL_DAYS, - } - } -} - -/// Standardized numeric statement fields (single source of truth for Stage 1 and Stage 2). -/// -/// Flow fields (`revenue`, `net_income`, `operating_cash_flow`) are summed across 4 consecutive -/// standalone quarters for TTM. Stock fields (`total_assets`, `total_equity`, `shares_outstanding`) -/// are point-in-time balance/count values and are never summed for TTM. -#[derive(Debug, Clone, Copy, Default, PartialEq)] -pub struct FundamentalsFields { - // Flow fields (TTM-eligible) - pub revenue: Option, - pub net_income: Option, - pub operating_cash_flow: Option, - // Stock fields (never TTM-summed) - pub total_assets: Option, - pub total_equity: Option, - pub shares_outstanding: Option, -} - -impl FundamentalsFields { - #[inline] - fn all_finite(&self) -> bool { - opt_is_finite(self.revenue) - && opt_is_finite(self.net_income) - && opt_is_finite(self.operating_cash_flow) - && opt_is_finite(self.total_assets) - && opt_is_finite(self.total_equity) - && opt_is_finite(self.shares_outstanding) - } - - #[inline] - fn normalize_zeros(self) -> Self { - Self { - revenue: self.revenue.map(normalize_zero), - net_income: self.net_income.map(normalize_zero), - operating_cash_flow: self.operating_cash_flow.map(normalize_zero), - total_assets: self.total_assets.map(normalize_zero), - total_equity: self.total_equity.map(normalize_zero), - shares_outstanding: self.shares_outstanding.map(normalize_zero), - } - } - - #[inline] - fn bit_eq(&self, other: &Self) -> bool { - self.revenue.map(f64::to_bits) == other.revenue.map(f64::to_bits) - && self.net_income.map(f64::to_bits) == other.net_income.map(f64::to_bits) - && self.operating_cash_flow.map(f64::to_bits) - == other.operating_cash_flow.map(f64::to_bits) - && self.total_assets.map(f64::to_bits) == other.total_assets.map(f64::to_bits) - && self.total_equity.map(f64::to_bits) == other.total_equity.map(f64::to_bits) - && self.shares_outstanding.map(f64::to_bits) - == other.shares_outstanding.map(f64::to_bits) - } -} - -/// 4-quarter trailing twelve months (TTM) sums for flow fields. -#[derive(Debug, Clone, Copy, Default, PartialEq)] -pub struct TtmFlowFields { - pub revenue: Option, - pub net_income: Option, - pub operating_cash_flow: Option, -} - -/// Precomputed 4-quarter TTM summary attached to a [`FundamentalsSnapshot`]. -#[derive(Debug, Clone, PartialEq)] -pub struct FundamentalsTtm { - /// `period_end` epoch day of the latest (4th) quarter in the TTM window. - pub ending_period_end: i32, - /// Shared currency across all 4 contributing quarters. - pub currency: String, - /// Trailing 4-quarter sums for each flow field (`None` if any quarter lacks the field or if - /// the sum overflows to non-finite). - pub flows: TtmFlowFields, - /// `true` if any of the 4 contributing quarters used `statutory_lag_estimate` (directly or via - /// an inherited field). - pub has_estimated_lag: bool, -} - -/// A single raw financial-statement observation input (`qmFinancials`-shaped, BSON-free). -#[derive(Debug, Clone, PartialEq)] -pub struct FinancialObservation { - pub key: K, - /// Fiscal period end date as days since `1970-01-01` (UTC Gregorian). - pub period_end: i32, - pub fiscal_period: FiscalPeriod, - /// ISO currency code (e.g. `"USD"`, `"CAD"`). - pub currency: String, - /// Optional Eastern Time report/vintage date as days since `1970-01-01`. - pub report_date: Option, - pub fields: FundamentalsFields, -} - -/// A single curated bitemporal fundamentals row matching `fundamentals_bitemporal` in -/// `design/DATA-CONTRACTS.md` §3A, sorted and unique by `(key, period_end, known_at_utc_micros)`. -#[derive(Debug, Clone, PartialEq)] -pub struct FundamentalsRow { - pub key: K, - pub period_end: i32, - pub fiscal_period: FiscalPeriod, - pub currency: String, - pub known_at_utc_micros: i64, - pub known_at_source: &'static str, - pub fields: FundamentalsFields, -} - -/// A single resolved period entry inside a [`FundamentalsSnapshot`]. -#[derive(Debug, Clone, PartialEq)] -pub struct FundamentalsPeriodSlot { - pub period_end: i32, - pub fiscal_period: FiscalPeriod, - pub currency: String, - pub known_at_utc_micros: i64, - pub known_at_source: &'static str, - /// `true` if this period's latest version used `statutory_lag_estimate` or any field was - /// carried forward from an earlier `statutory_lag_estimate` version. - pub has_estimated_lag: bool, - pub fields: FundamentalsFields, -} - -/// A single 2D point-in-time snapshot matching `fundamentals_pit` in `design/DATA-CONTRACTS.md` -/// §3A, keyed by `(key, effective_known_at_utc_micros)`. -#[derive(Debug, Clone, PartialEq)] -pub struct FundamentalsSnapshot { - pub key: K, - pub effective_known_at_utc_micros: i64, - /// `"statutory_lag_estimate"` if [`Self::has_estimated_lag`] is `true`, otherwise - /// `"filing_timestamp"`. - pub known_at_source: &'static str, - /// `true` if any visible period slot or any quarter contributing to [`Self::ttm`] used - /// `statutory_lag_estimate` (directly or via an inherited field). - pub has_estimated_lag: bool, - /// Latest `k` visible periods ordered by `period_end` descending (`periods[0]` is latest). - pub periods: Vec, - /// Precomputed 4-quarter TTM flow sums, computed independently of `k`. - pub ttm: Option, -} - -/// Summary accounting counters produced alongside [`FundamentalsBuild::rows`]. -/// -/// Conservation invariants: -/// - Observations: -/// `observations_in == rows_out + observations_dropped_unknown_key + observations_dropped_non_finite + observations_dropped_date_out_of_range + observations_dropped_report_date_not_after_period_end + observations_dropped_unanchored_vintage + observations_dropped_stale_estimate + duplicate_collapsed + duplicate_conflict_dropped` -/// - Output provenance: -/// `rows_out == rows_linked_to_filing + rows_statutory_lag_estimate` -/// - Filings: -/// `filings_in == filings_eligible + filings_dropped_unknown_key + filings_ignored_non_periodic + filings_dropped_invalid_timestamp + filings_dropped_date_out_of_range + filings_dropped_before_period_end` -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct FundamentalsStats { - pub observations_in: usize, - pub rows_out: usize, - pub keys_out: usize, - pub rows_linked_to_filing: usize, - pub rows_statutory_lag_estimate: usize, - pub observations_dropped_unknown_key: usize, - pub observations_dropped_non_finite: usize, - pub observations_dropped_date_out_of_range: usize, - pub observations_dropped_report_date_not_after_period_end: usize, - pub observations_dropped_unanchored_vintage: usize, - pub observations_dropped_stale_estimate: usize, - pub duplicate_collapsed: usize, - pub duplicate_conflict_dropped: usize, - pub filings_in: usize, - pub filings_eligible: usize, - pub filings_dropped_unknown_key: usize, - pub filings_ignored_non_periodic: usize, - pub filings_dropped_invalid_timestamp: usize, - pub filings_dropped_date_out_of_range: usize, - pub filings_dropped_before_period_end: usize, -} - -/// Output of [`build_fundamentals_rows`]: sorted, unique bitemporal rows and reconciling stats. -#[derive(Debug, Clone, PartialEq)] -pub struct FundamentalsBuild { - pub rows: Vec>, - pub stats: FundamentalsStats, -} - -/// Typed caller errors returned by [`build_fundamentals_snapshots`]. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum FundamentalsError { - /// Caller-supplied `k` (maximum periods retained per snapshot) was zero. - InvalidPeriodLimit { k: usize }, -} - -impl fmt::Display for FundamentalsError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match *self { - Self::InvalidPeriodLimit { k } => { - write!(f, "invalid snapshot period limit k={k}: must be >= 1") - } - } - } -} - -impl Error for FundamentalsError {} - -#[inline] -fn opt_is_finite(v: Option) -> bool { - v.is_none_or(f64::is_finite) -} - -#[inline] -fn normalize_zero(v: f64) -> f64 { - if v == 0.0 { - 0.0 - } else { - v - } -} - -#[inline] -fn is_supported_date(epoch_day: i32) -> bool { - (MIN_SUPPORTED_DATE..=MAX_SUPPORTED_DATE).contains(&epoch_day) -} - -#[inline] -fn periodic_group_to_fiscal_period(group: FilingFormGroup) -> Option { - if !group.is_periodic_financial_report() { - return None; - } - match group { - FilingFormGroup::Form10Q | FilingFormGroup::InterimFinancials => { - Some(FiscalPeriod::Quarterly) - } - FilingFormGroup::Form10K - | FilingFormGroup::Form40F - | FilingFormGroup::AnnualFinancials => Some(FiscalPeriod::Annual), - _ => None, - } -} - -struct EligibleObservation { - key: K, - period_end: i32, - fiscal_period: FiscalPeriod, - currency: String, - report_date: Option, - venue: StatutoryLagVenue, - fields: FundamentalsFields, -} - -#[derive(Debug, Clone, Copy)] -struct IndexedFiling { - et_date: i32, - utc_micros: i64, - is_amendment: bool, -} - -struct ParsedPeriodicFiling { - key: K, - fiscal_period: FiscalPeriod, - et_date: i32, - utc_micros: i64, - is_amendment: bool, -} - -struct CandidateRow { - row: FundamentalsRow, - report_date: Option, -} - -/// Builds sorted, unique bitemporal fundamentals rows from financial observations, periodic -/// filings, and per-listing statutory-lag venue classes. -/// -/// Any permutation of `observations` or `filings` yields bitwise-identical `rows` and `stats`. -pub fn build_fundamentals_rows( - observations: IO, - filings: IF, - venues: &BTreeMap, -) -> FundamentalsBuild -where - K: Ord + Clone, - IO: IntoIterator>, - IF: IntoIterator>, -{ - let obs_iter = observations.into_iter(); - let mut stats = FundamentalsStats::default(); - let mut eligible_obs: Vec> = Vec::with_capacity(obs_iter.size_hint().0); - let mut earliest_period_by_key_kind: BTreeMap<(K, FiscalPeriod), i32> = BTreeMap::new(); - - for obs in obs_iter { - stats.observations_in += 1; - - let Some(&venue) = venues.get(&obs.key) else { - stats.observations_dropped_unknown_key += 1; - continue; - }; - - if !obs.fields.all_finite() { - stats.observations_dropped_non_finite += 1; - continue; - } - - if !is_supported_date(obs.period_end) - || obs.report_date.is_some_and(|rd| !is_supported_date(rd)) - { - stats.observations_dropped_date_out_of_range += 1; - continue; - } - - if obs.report_date.is_some_and(|rd| rd <= obs.period_end) { - stats.observations_dropped_report_date_not_after_period_end += 1; - continue; - } - - earliest_period_by_key_kind - .entry((obs.key.clone(), obs.fiscal_period)) - .and_modify(|min_pe| { - if obs.period_end < *min_pe { - *min_pe = obs.period_end; - } - }) - .or_insert(obs.period_end); - - eligible_obs.push(EligibleObservation { - key: obs.key, - period_end: obs.period_end, - fiscal_period: obs.fiscal_period, - currency: obs.currency, - report_date: obs.report_date, - venue, - fields: obs.fields.normalize_zeros(), - }); - } - - let filings_iter = filings.into_iter(); - let mut parsed_filings: Vec> = Vec::new(); - - for filing in filings_iter { - stats.filings_in += 1; - - if !venues.contains_key(&filing.key) { - stats.filings_dropped_unknown_key += 1; - continue; - } - - let (group, is_amendment) = classify_form_type(&filing.form_type); - let Some(fiscal_period) = periodic_group_to_fiscal_period(group) else { - stats.filings_ignored_non_periodic += 1; - continue; - }; - - let Ok(parsed) = parse_filing_timefiled(&filing.timefiled) else { - stats.filings_dropped_invalid_timestamp += 1; - continue; - }; - - if !is_supported_date(parsed.et_date) { - stats.filings_dropped_date_out_of_range += 1; - continue; - } - - parsed_filings.push(ParsedPeriodicFiling { - key: filing.key, - fiscal_period, - et_date: parsed.et_date, - utc_micros: parsed.utc_micros, - is_amendment, - }); - } - - let mut filing_index: BTreeMap<(K, FiscalPeriod), Vec> = BTreeMap::new(); - for pf in parsed_filings { - let key_kind = (pf.key, pf.fiscal_period); - if let Some(&min_pe) = earliest_period_by_key_kind.get(&key_kind) { - if pf.et_date <= min_pe { - stats.filings_dropped_before_period_end += 1; - continue; - } - } - stats.filings_eligible += 1; - filing_index.entry(key_kind).or_default().push(IndexedFiling { - et_date: pf.et_date, - utc_micros: pf.utc_micros, - is_amendment: pf.is_amendment, - }); - } - - for bucket in filing_index.values_mut() { - bucket.sort_unstable_by(|a, b| { - a.et_date - .cmp(&b.et_date) - .then_with(|| a.utc_micros.cmp(&b.utc_micros)) - .then_with(|| a.is_amendment.cmp(&b.is_amendment)) - }); - } - - let mut candidates: Vec> = Vec::with_capacity(eligible_obs.len()); - - for obs in eligible_obs { - let linked_micros = filing_index - .get(&(obs.key.clone(), obs.fiscal_period)) - .and_then(|bucket| match obs.report_date { - Some(rd) => { - // Earliest matching periodic filing (amended or unamended) on Eastern day `rd`. - // `rd > obs.period_end` is guaranteed by validation above. - let pos = bucket.partition_point(|f| f.et_date < rd); - bucket - .get(pos) - .filter(|f| f.et_date == rd) - .map(|f| f.utc_micros) - } - None => { - // Earliest matching non-amended periodic filing strictly after `period_end` - // and within the inclusive calendar-day inference window. - let window_end = i64::from(obs.period_end) - + i64::from(obs.fiscal_period.undated_link_window_days()); - let pos = bucket.partition_point(|f| f.et_date <= obs.period_end); - bucket[pos..] - .iter() - .take_while(|f| i64::from(f.et_date) <= window_end) - .find(|f| !f.is_amendment) - .map(|f| f.utc_micros) - } - }); - - let (known_at_utc_micros, known_at_source) = if let Some(micros) = linked_micros { - (micros, KNOWN_AT_SOURCE_FILING_TIMESTAMP) - } else { - let lag_days = obs.venue.lag_days(obs.fiscal_period); - let lag_date_i64 = i64::from(obs.period_end) + i64::from(lag_days); - - if let Some(rd) = obs.report_date { - if i64::from(rd) > lag_date_i64 { - stats.observations_dropped_unanchored_vintage += 1; - continue; - } - } - - let Ok(lag_date) = i32::try_from(lag_date_i64) else { - stats.observations_dropped_date_out_of_range += 1; - continue; - }; - let Ok(micros) = et_to_utc_micros( - lag_date, - FUNDAMENTALS_FALLBACK_HOUR_ET, - FUNDAMENTALS_FALLBACK_MINUTE_ET, - 0, - ) else { - stats.observations_dropped_date_out_of_range += 1; - continue; - }; - (micros, KNOWN_AT_SOURCE_STATUTORY_LAG) - }; - - candidates.push(CandidateRow { - row: FundamentalsRow { - key: obs.key, - period_end: obs.period_end, - fiscal_period: obs.fiscal_period, - currency: obs.currency, - known_at_utc_micros, - known_at_source, - fields: obs.fields, - }, - report_date: obs.report_date, - }); - } - - candidates.sort_unstable_by(|a, b| { - a.row - .key - .cmp(&b.row.key) - .then_with(|| a.row.period_end.cmp(&b.row.period_end)) - .then_with(|| a.row.known_at_utc_micros.cmp(&b.row.known_at_utc_micros)) - }); - - let mut rows: Vec> = Vec::with_capacity(candidates.len()); - let mut survivors: Vec = Vec::new(); - let total = candidates.len(); - let mut pe_start = 0usize; - - while pe_start < total { - let mut pe_end = pe_start + 1; - while pe_end < total - && candidates[pe_end].row.key == candidates[pe_start].row.key - && candidates[pe_end].row.period_end == candidates[pe_start].row.period_end - { - pe_end += 1; - } - - // Track the newest accepted `report_date` seen at an earlier `known_at_utc_micros` for - // each `FiscalPeriod` so only accepted newer versions can suppress a stale statutory-lag - // estimate. - let mut max_accepted_rd_q: Option = None; - let mut max_accepted_rd_fy: Option = None; - - let mut g_start = pe_start; - while g_start < pe_end { - let group_ts = candidates[g_start].row.known_at_utc_micros; - let mut g_end = g_start + 1; - while g_end < pe_end && candidates[g_end].row.known_at_utc_micros == group_ts { - g_end += 1; - } - - // Filter out stale dated statutory-lag candidates before duplicate/conflict checks - // so a superseded estimate cannot cause an eligible estimate at the same fallback - // timestamp to be rejected as conflicting. - survivors.clear(); - for idx in g_start..g_end { - let cand = &candidates[idx]; - let prior_max_rd = match cand.row.fiscal_period { - FiscalPeriod::Quarterly => max_accepted_rd_q, - FiscalPeriod::Annual => max_accepted_rd_fy, - }; - let is_stale_estimate = cand.row.known_at_source == KNOWN_AT_SOURCE_STATUTORY_LAG - && cand - .report_date - .is_some_and(|rd_a| prior_max_rd.is_some_and(|rd_b| rd_b > rd_a)); - if is_stale_estimate { - stats.observations_dropped_stale_estimate += 1; - } else { - survivors.push(idx); - } - } - - if survivors.is_empty() { - g_start = g_end; - continue; - } - - let first = &candidates[survivors[0]].row; - let all_identical = survivors[1..].iter().all(|&idx| { - let other = &candidates[idx].row; - first.fiscal_period == other.fiscal_period - && first.currency == other.currency - && first.known_at_source == other.known_at_source - && first.fields.bit_eq(&other.fields) - }); - - if !all_identical { - stats.duplicate_conflict_dropped += survivors.len(); - g_start = g_end; - continue; - } - - let mut group_max_rd: Option = None; - for &idx in &survivors { - if let Some(rd) = candidates[idx].report_date { - group_max_rd = Some(group_max_rd.map_or(rd, |m| m.max(rd))); - } - } - if let Some(rd) = group_max_rd { - let slot = match first.fiscal_period { - FiscalPeriod::Quarterly => &mut max_accepted_rd_q, - FiscalPeriod::Annual => &mut max_accepted_rd_fy, - }; - *slot = Some(slot.map_or(rd, |m| m.max(rd))); - } - - stats.duplicate_collapsed += survivors.len() - 1; - if first.known_at_source == KNOWN_AT_SOURCE_FILING_TIMESTAMP { - stats.rows_linked_to_filing += 1; - } else { - stats.rows_statutory_lag_estimate += 1; - } - if rows.last().is_none_or(|prev| prev.key != first.key) { - stats.keys_out += 1; - } - rows.push(first.clone()); - - g_start = g_end; - } - - pe_start = pe_end; - } - - stats.rows_out = rows.len(); - FundamentalsBuild { rows, stats } -} - -#[derive(Clone)] -struct ResolvedPeriod { - period_end: i32, - fiscal_period: FiscalPeriod, - currency: String, - known_at_utc_micros: i64, - known_at_source: &'static str, - fields: FundamentalsFields, - /// Per-field flag: `true` iff that `Some` field originated from a `statutory_lag_estimate` row. - field_estimated: [bool; 6], -} - -impl ResolvedPeriod { - #[inline] - fn from_row(row: &FundamentalsRow) -> Self { - let est = row.known_at_source == KNOWN_AT_SOURCE_STATUTORY_LAG; - let fields = row.fields.normalize_zeros(); - let field_estimated = [ - est && fields.revenue.is_some(), - est && fields.net_income.is_some(), - est && fields.operating_cash_flow.is_some(), - est && fields.total_assets.is_some(), - est && fields.total_equity.is_some(), - est && fields.shares_outstanding.is_some(), - ]; - Self { - period_end: row.period_end, - fiscal_period: row.fiscal_period, - currency: row.currency.clone(), - known_at_utc_micros: row.known_at_utc_micros, - known_at_source: row.known_at_source, - fields, - field_estimated, - } - } - - #[inline] - fn apply_update(&mut self, row: &FundamentalsRow) { - if self.fiscal_period != row.fiscal_period || self.currency != row.currency { - *self = Self::from_row(row); - return; - } - - let est = row.known_at_source == KNOWN_AT_SOURCE_STATUTORY_LAG; - let incoming = row.fields.normalize_zeros(); - - if let Some(v) = incoming.revenue { - self.fields.revenue = Some(v); - self.field_estimated[0] = est; - } - if let Some(v) = incoming.net_income { - self.fields.net_income = Some(v); - self.field_estimated[1] = est; - } - if let Some(v) = incoming.operating_cash_flow { - self.fields.operating_cash_flow = Some(v); - self.field_estimated[2] = est; - } - if let Some(v) = incoming.total_assets { - self.fields.total_assets = Some(v); - self.field_estimated[3] = est; - } - if let Some(v) = incoming.total_equity { - self.fields.total_equity = Some(v); - self.field_estimated[4] = est; - } - if let Some(v) = incoming.shares_outstanding { - self.fields.shares_outstanding = Some(v); - self.field_estimated[5] = est; - } - - self.known_at_utc_micros = row.known_at_utc_micros; - self.known_at_source = row.known_at_source; - } - - #[inline] - fn has_estimated_lag(&self) -> bool { - self.known_at_source == KNOWN_AT_SOURCE_STATUTORY_LAG - || self.field_estimated.iter().any(|&e| e) - } - - #[inline] - fn to_slot(&self) -> FundamentalsPeriodSlot { - FundamentalsPeriodSlot { - period_end: self.period_end, - fiscal_period: self.fiscal_period, - currency: self.currency.clone(), - known_at_utc_micros: self.known_at_utc_micros, - known_at_source: self.known_at_source, - has_estimated_lag: self.has_estimated_lag(), - fields: self.fields, - } - } -} - -#[inline] -fn sum_4_flows(values: [Option; 4]) -> Option { - let [v0, v1, v2, v3] = values; - let sum = v3? + v2? + v1? + v0?; - if sum.is_finite() { - Some(normalize_zero(sum)) - } else { - None - } -} - -fn compute_ttm(visible_quarters: &BTreeMap) -> Option { - let quarters: [&ResolvedPeriod; TTM_QUARTER_COUNT] = { - let mut iter = visible_quarters.values().rev(); - let q0 = iter.next()?; - let q1 = iter.next()?; - let q2 = iter.next()?; - let q3 = iter.next()?; - [q0, q1, q2, q3] - }; - - let min_gap = i64::from(TTM_CONSECUTIVE_QUARTER_MIN_DAYS); - let max_gap = i64::from(TTM_CONSECUTIVE_QUARTER_MAX_DAYS); - for pair in quarters.windows(2) { - let gap = i64::from(pair[0].period_end) - i64::from(pair[1].period_end); - if gap < min_gap || gap > max_gap { - return None; - } - } - - let currency = &quarters[0].currency; - if !quarters[1..].iter().all(|q| &q.currency == currency) { - return None; - } - - let flows = TtmFlowFields { - revenue: sum_4_flows([ - quarters[0].fields.revenue, - quarters[1].fields.revenue, - quarters[2].fields.revenue, - quarters[3].fields.revenue, - ]), - net_income: sum_4_flows([ - quarters[0].fields.net_income, - quarters[1].fields.net_income, - quarters[2].fields.net_income, - quarters[3].fields.net_income, - ]), - operating_cash_flow: sum_4_flows([ - quarters[0].fields.operating_cash_flow, - quarters[1].fields.operating_cash_flow, - quarters[2].fields.operating_cash_flow, - quarters[3].fields.operating_cash_flow, - ]), - }; - - let has_estimated_lag = quarters.iter().any(|q| q.has_estimated_lag()); - - Some(FundamentalsTtm { - ending_period_end: quarters[0].period_end, - currency: currency.clone(), - flows, - has_estimated_lag, - }) -} - -/// Builds 2D point-in-time [`FundamentalsSnapshot`] records sorted by -/// `(key, effective_known_at_utc_micros)` from bitemporal [`FundamentalsRow`] inputs. -/// -/// Returns [`FundamentalsError::InvalidPeriodLimit`] if `k == 0`. -pub fn build_fundamentals_snapshots( - rows: &[FundamentalsRow], - k: usize, -) -> Result>, FundamentalsError> -where - K: Ord + Clone, -{ - if k == 0 { - return Err(FundamentalsError::InvalidPeriodLimit { k }); - } - if rows.is_empty() { - return Ok(Vec::new()); - } - - let mut order: Vec = (0..rows.len()).collect(); - order.sort_unstable_by(|&a, &b| { - rows[a] - .key - .cmp(&rows[b].key) - .then_with(|| rows[a].known_at_utc_micros.cmp(&rows[b].known_at_utc_micros)) - .then_with(|| rows[a].period_end.cmp(&rows[b].period_end)) - .then_with(|| rows[a].fiscal_period.cmp(&rows[b].fiscal_period)) - }); - - let mut snapshots: Vec> = Vec::new(); - let total = order.len(); - let mut idx = 0usize; - - while idx < total { - let key = &rows[order[idx]].key; - let mut visible_periods: BTreeMap = BTreeMap::new(); - let mut visible_quarters: BTreeMap = BTreeMap::new(); - let mut visible_annuals: BTreeMap = BTreeMap::new(); - - while idx < total && &rows[order[idx]].key == key { - let effective_ts = rows[order[idx]].known_at_utc_micros; - - while idx < total - && &rows[order[idx]].key == key - && rows[order[idx]].known_at_utc_micros == effective_ts - { - let row = &rows[order[idx]]; - let by_kind = match row.fiscal_period { - FiscalPeriod::Quarterly => &mut visible_quarters, - FiscalPeriod::Annual => &mut visible_annuals, - }; - let resolved = match by_kind.get_mut(&row.period_end) { - Some(existing) => { - existing.apply_update(row); - existing.clone() - } - None => { - let created = ResolvedPeriod::from_row(row); - by_kind.insert(row.period_end, created.clone()); - created - } - }; - visible_periods.insert(row.period_end, resolved); - idx += 1; - } - - let periods: Vec = visible_periods - .values() - .rev() - .take(k) - .map(ResolvedPeriod::to_slot) - .collect(); - let ttm = compute_ttm(&visible_quarters); - let has_estimated_lag = periods.iter().any(|p| p.has_estimated_lag) - || ttm.as_ref().is_some_and(|t| t.has_estimated_lag); - let known_at_source = if has_estimated_lag { - KNOWN_AT_SOURCE_STATUTORY_LAG - } else { - KNOWN_AT_SOURCE_FILING_TIMESTAMP - }; - - snapshots.push(FundamentalsSnapshot { - key: key.clone(), - effective_known_at_utc_micros: effective_ts, - known_at_source, - has_estimated_lag, - periods, - ttm, - }); - } - } - - Ok(snapshots) -} - -/// Returns the latest [`FundamentalsSnapshot`] for `key` with -/// `effective_known_at_utc_micros <= as_of_micros` (inclusive). -/// -/// Requires `snapshots` to be sorted by `(key, effective_known_at_utc_micros)` (as returned by -/// [`build_fundamentals_snapshots`]). -pub fn as_of<'a, K, Q>( - snapshots: &'a [FundamentalsSnapshot], - key: &Q, - as_of_micros: i64, -) -> Option<&'a FundamentalsSnapshot> -where - K: Borrow + Ord, - Q: Ord + ?Sized, -{ - let pos = snapshots.partition_point(|s| match s.key.borrow().cmp(key) { - Ordering::Less => true, - Ordering::Equal => s.effective_known_at_utc_micros <= as_of_micros, - Ordering::Greater => false, - }); - if pos == 0 { - return None; - } - let candidate = &snapshots[pos - 1]; - if candidate.key.borrow() == key { - Some(candidate) - } else { - None - } -} - -#[cfg(test)] -#[path = "fundamentals_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/fundamentals_tests.rs b/tools/curate-etl/src/fundamentals_tests.rs deleted file mode 100644 index a3919caf..00000000 --- a/tools/curate-etl/src/fundamentals_tests.rs +++ /dev/null @@ -1,1069 +0,0 @@ -use super::*; -use crate::split::ymd_to_epoch_days; - -fn day(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).expect("valid test date") -} - -fn utc_micros(y: i32, m: u32, d: u32, hour: u8, minute: u8, second: u8) -> i64 { - let epoch_day = day(y, m, d); - let secs = i64::from(epoch_day) * 86_400 - + i64::from(hour) * 3_600 - + i64::from(minute) * 60 - + i64::from(second); - secs * 1_000_000 -} - -fn filing(key: &str, timefiled: &str, form_type: &str) -> QmFiling { - QmFiling { - key: key.to_string(), - timefiled: timefiled.to_string(), - form_type: form_type.to_string(), - filing_id: None, - url: None, - } -} - -fn obs( - key: &str, - period_end: i32, - fiscal_period: FiscalPeriod, - currency: &str, - report_date: Option, - fields: FundamentalsFields, -) -> FinancialObservation { - FinancialObservation { - key: key.to_string(), - period_end, - fiscal_period, - currency: currency.to_string(), - report_date, - fields, - } -} - -fn fields_rev(rev: f64) -> FundamentalsFields { - FundamentalsFields { - revenue: Some(rev), - net_income: Some(rev * 0.1), - operating_cash_flow: Some(rev * 0.15), - total_assets: Some(rev * 5.0), - total_equity: Some(rev * 2.0), - shares_outstanding: Some(1_000.0), - } -} - -fn venues_map(entries: &[(&str, StatutoryLagVenue)]) -> BTreeMap { - entries - .iter() - .map(|&(k, v)| (k.to_string(), v)) - .collect() -} - -fn assert_reconciliation(build: &FundamentalsBuild) { - let s = &build.stats; - assert_eq!(s.rows_out, build.rows.len()); - assert_eq!( - s.rows_out, - s.rows_linked_to_filing + s.rows_statutory_lag_estimate, - "output provenance mismatch: {s:?}" - ); - assert_eq!( - s.observations_in, - s.rows_out - + s.observations_dropped_unknown_key - + s.observations_dropped_non_finite - + s.observations_dropped_date_out_of_range - + s.observations_dropped_report_date_not_after_period_end - + s.observations_dropped_unanchored_vintage - + s.observations_dropped_stale_estimate - + s.duplicate_collapsed - + s.duplicate_conflict_dropped, - "observation reconciliation failed: {s:?}" - ); - assert_eq!( - s.filings_in, - s.filings_eligible - + s.filings_dropped_unknown_key - + s.filings_ignored_non_periodic - + s.filings_dropped_invalid_timestamp - + s.filings_dropped_date_out_of_range - + s.filings_dropped_before_period_end, - "filing reconciliation failed: {s:?}" - ); - for pair in build.rows.windows(2) { - assert!( - (&pair[0].key, pair[0].period_end, pair[0].known_at_utc_micros) - < (&pair[1].key, pair[1].period_end, pair[1].known_at_utc_micros), - "rows must be strictly sorted and unique by (key, period_end, known_at_utc_micros)" - ); - } -} - -#[test] -fn restatement_of_q1_after_q2_updates_q1_and_ttm_without_overwriting_q2() { - let venues = venues_map(&[("ACME", StatutoryLagVenue::UsTsx)]); - - let p_2023_q3 = day(2023, 9, 30); - let p_2023_q4 = day(2023, 12, 31); - let p_2024_q1 = day(2024, 3, 31); - let p_2024_q2 = day(2024, 6, 30); - - let initial_filings = vec![ - filing("ACME", "2023-11-01T16:15:00 EDT", "10-Q"), - filing("ACME", "2024-02-01T16:15:00 EST", "10-Q"), - filing("ACME", "2024-05-01T16:15:00 EDT", "10-Q"), - filing("ACME", "2024-08-01T16:15:00 EDT", "10-Q"), - ]; - let amendment_filing = filing("ACME", "2024-09-15T17:00:00 EDT", "10-Q/A"); - - let initial_obs = vec![ - obs( - "ACME", - p_2023_q3, - FiscalPeriod::Quarterly, - "USD", - Some(day(2023, 11, 1)), - FundamentalsFields { - revenue: Some(70.0), - net_income: Some(7.0), - operating_cash_flow: Some(10.0), - total_assets: Some(500.0), - total_equity: Some(200.0), - shares_outstanding: Some(100.0), - }, - ), - obs( - "ACME", - p_2023_q4, - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 2, 1)), - FundamentalsFields { - revenue: Some(80.0), - net_income: Some(8.0), - operating_cash_flow: Some(12.0), - total_assets: Some(520.0), - total_equity: Some(210.0), - shares_outstanding: Some(100.0), - }, - ), - obs( - "ACME", - p_2024_q1, - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 5, 1)), - FundamentalsFields { - revenue: Some(100.0), - net_income: Some(10.0), - operating_cash_flow: Some(15.0), - total_assets: Some(540.0), - total_equity: Some(220.0), - shares_outstanding: Some(100.0), - }, - ), - obs( - "ACME", - p_2024_q2, - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 8, 1)), - FundamentalsFields { - revenue: Some(120.0), - net_income: Some(12.0), - operating_cash_flow: Some(18.0), - total_assets: Some(560.0), - total_equity: Some(230.0), - shares_outstanding: Some(100.0), - }, - ), - ]; - - // Q1 amendment filed on 2024-09-15 (168 days after Q1 period end, beyond 75d window) - // Restates revenue from 100 -> 110 and omits operating_cash_flow & total_assets (None). - let q1_amendment = obs( - "ACME", - p_2024_q1, - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 9, 15)), - FundamentalsFields { - revenue: Some(110.0), - net_income: Some(11.0), - operating_cash_flow: None, - total_assets: None, - total_equity: Some(225.0), - shares_outstanding: None, - }, - ); - - let mut full_obs = initial_obs.clone(); - full_obs.push(q1_amendment); - let mut full_filings = initial_filings.clone(); - full_filings.push(amendment_filing); - - let full_build = build_fundamentals_rows(full_obs, full_filings, &venues); - assert_reconciliation(&full_build); - assert_eq!(full_build.stats.rows_out, 5); - assert_eq!(full_build.stats.rows_linked_to_filing, 5); - assert_eq!(full_build.stats.rows_statutory_lag_estimate, 0); - - let full_snaps = build_fundamentals_snapshots(&full_build.rows, 4).unwrap(); - assert_eq!(full_snaps.len(), 5); - - let ts_q2 = utc_micros(2024, 8, 1, 20, 15, 0); - let ts_amend = utc_micros(2024, 9, 15, 21, 0, 0); - - // As-of strictly between Q2 filing and Q1 restatement (also check exact Q2 timestamp). - for probe in [ts_q2, ts_amend - 1] { - let snap = as_of(&full_snaps, "ACME", probe).expect("snapshot visible after Q2"); - assert_eq!(snap.effective_known_at_utc_micros, ts_q2); - assert_eq!(snap.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); - assert!(!snap.has_estimated_lag); - assert_eq!(snap.periods[0].period_end, p_2024_q2); - assert_eq!(snap.periods[0].fields.revenue, Some(120.0)); - assert_eq!(snap.periods[1].period_end, p_2024_q1); - assert_eq!(snap.periods[1].fields.revenue, Some(100.0)); - assert_eq!(snap.periods[1].fields.operating_cash_flow, Some(15.0)); - let ttm = snap.ttm.as_ref().expect("4 consecutive quarters"); - assert_eq!(ttm.ending_period_end, p_2024_q2); - assert_eq!(ttm.flows.revenue, Some(370.0)); - assert_eq!(ttm.flows.net_income, Some(37.0)); - assert_eq!(ttm.flows.operating_cash_flow, Some(55.0)); - } - - // As-of at and after the Q1 restatement: Q2 stays latest and unchanged, Q1 updated + inherited, TTM updated. - for probe in [ts_amend, ts_amend + 1_000_000] { - let snap = as_of(&full_snaps, "ACME", probe).expect("snapshot visible at/after amendment"); - assert_eq!(snap.effective_known_at_utc_micros, ts_amend); - assert_eq!(snap.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); - assert!(!snap.has_estimated_lag); - assert_eq!(snap.periods[0].period_end, p_2024_q2); - assert_eq!(snap.periods[0].fields.revenue, Some(120.0)); - assert_eq!(snap.periods[0].fields.total_assets, Some(560.0)); - assert_eq!(snap.periods[1].period_end, p_2024_q1); - assert_eq!(snap.periods[1].known_at_utc_micros, ts_amend); - assert_eq!(snap.periods[1].fields.revenue, Some(110.0)); - assert_eq!(snap.periods[1].fields.net_income, Some(11.0)); - // Omitted fields inherited from original Q1 - assert_eq!(snap.periods[1].fields.operating_cash_flow, Some(15.0)); - assert_eq!(snap.periods[1].fields.total_assets, Some(540.0)); - assert_eq!(snap.periods[1].fields.shares_outstanding, Some(100.0)); - assert_eq!(snap.periods[1].fields.total_equity, Some(225.0)); - let ttm = snap.ttm.as_ref().expect("4 consecutive quarters"); - assert_eq!(ttm.ending_period_end, p_2024_q2); - assert_eq!(ttm.flows.revenue, Some(380.0)); - assert_eq!(ttm.flows.net_income, Some(38.0)); - assert_eq!(ttm.flows.operating_cash_flow, Some(55.0)); - } - - // Truncation test: rebuild without future amendment and its filing; all earlier snapshots identical. - let trunc_build = build_fundamentals_rows(initial_obs, initial_filings, &venues); - assert_reconciliation(&trunc_build); - let trunc_snaps = build_fundamentals_snapshots(&trunc_build.rows, 4).unwrap(); - assert_eq!(trunc_snaps.len(), 4); - assert_eq!(&full_snaps[..4], &trunc_snaps[..]); -} - -#[test] -fn known_at_filing_linking_covers_all_periodic_forms_zones_windows_and_exclusions() { - let venues = venues_map(&[ - ("US_Q", StatutoryLagVenue::UsTsx), - ("US_A", StatutoryLagVenue::UsTsx), - ("CA_40F", StatutoryLagVenue::UsTsx), - ("SEDAR_Q", StatutoryLagVenue::TsxvCse), - ("SEDAR_A", StatutoryLagVenue::TsxvCse), - ("WIN_Q", StatutoryLagVenue::UsTsx), - ("WIN_A", StatutoryLagVenue::UsTsx), - ("NOISE", StatutoryLagVenue::UsTsx), - ]); - - let filings = vec![ - // Late-evening EDT filing whose UTC date is the next day (2024-05-11T01:30:00Z) - filing("US_Q", "2024-05-10T21:30:00 EDT", "10-Q"), - // EST annual 10-K - filing("US_A", "2024-03-01T08:15:30 EST", "10-K"), - // 40-F annual - filing("CA_40F", "2024-03-15T14:00:00 EDT", "40-F"), - // SEDAR interim & annual - filing("SEDAR_Q", "2024-05-20T18:00:00 EDT", "Interim financial statements/report - English"), - filing("SEDAR_A", "2024-04-20T12:30:00 EDT", "Annual financial statements - English"), - // Window boundary filings for undated quarterly (period_end = 2024-03-31 -> +75d = 2024-06-14, +76d = 2024-06-15) - // Also add an earlier 10-Q/A on 2024-05-01 which undated observation must ignore! - filing("WIN_Q", "2024-05-01T10:00:00 EDT", "10-Q/A"), - filing("WIN_Q", "2024-06-14T11:00:00 EDT", "10-Q"), - // Window boundary for undated annual (period_end = 2023-12-31 -> +150d = 2024-05-29, +151d = 2024-05-30) - filing("WIN_A", "2024-05-29T15:00:00 EDT", "10-K"), - // Non-periodic 8-K, wrong kind (10-K for quarterly), and wrong listing - filing("NOISE", "2024-05-05T09:00:00 EDT", "8-K"), - filing("NOISE", "2024-05-05T09:30:00 EDT", "News release"), - filing("NOISE", "2024-05-05T10:00:00 EDT", "10-K"), - ]; - - let observations = vec![ - // Same-day match across UTC midnight rollover (ET date = 2024-05-10) - obs("US_Q", day(2024, 3, 31), FiscalPeriod::Quarterly, "USD", Some(day(2024, 5, 10)), fields_rev(10.0)), - obs("US_A", day(2023, 12, 31), FiscalPeriod::Annual, "USD", None, fields_rev(20.0)), - obs("CA_40F", day(2023, 12, 31), FiscalPeriod::Annual, "CAD", None, fields_rev(30.0)), - obs("SEDAR_Q", day(2024, 3, 31), FiscalPeriod::Quarterly, "CAD", None, fields_rev(40.0)), - obs("SEDAR_A", day(2023, 12, 31), FiscalPeriod::Annual, "CAD", None, fields_rev(50.0)), - // Exact +75d inclusive boundary -> links to 2024-06-14 10-Q (skipping 2024-05-01 10-Q/A) - obs("WIN_Q", day(2024, 3, 31), FiscalPeriod::Quarterly, "USD", None, fields_rev(60.0)), - // Exact +76d (period_end = 2024-03-30 -> 2024-06-14 is +76d) -> outside window, falls back! - obs("WIN_Q", day(2024, 3, 30), FiscalPeriod::Quarterly, "USD", None, fields_rev(61.0)), - // Exact +150d inclusive boundary -> links to 2024-05-29 10-K - obs("WIN_A", day(2023, 12, 31), FiscalPeriod::Annual, "USD", None, fields_rev(70.0)), - // Exact +151d (period_end = 2023-12-30 -> 2024-05-29 is +151d) -> outside window, falls back! - obs("WIN_A", day(2023, 12, 30), FiscalPeriod::Annual, "USD", None, fields_rev(71.0)), - // NOISE quarterly: 8-K, News release, and 10-K must NOT link -> statutory lag fallback - obs("NOISE", day(2024, 3, 31), FiscalPeriod::Quarterly, "USD", None, fields_rev(80.0)), - ]; - - let built = build_fundamentals_rows(observations, filings, &venues); - assert_reconciliation(&built); - assert_eq!(built.stats.filings_ignored_non_periodic, 2); - assert_eq!(built.stats.rows_linked_to_filing, 7); - assert_eq!(built.stats.rows_statutory_lag_estimate, 3); - - let find = |k: &str, pe: i32| { - built - .rows - .iter() - .find(|r| r.key == k && r.period_end == pe) - .expect("row present") - }; - - assert_eq!(find("US_Q", day(2024, 3, 31)).known_at_utc_micros, utc_micros(2024, 5, 11, 1, 30, 0)); - assert_eq!(find("US_Q", day(2024, 3, 31)).known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); - assert_eq!(find("US_A", day(2023, 12, 31)).known_at_utc_micros, utc_micros(2024, 3, 1, 13, 15, 30)); - assert_eq!(find("CA_40F", day(2023, 12, 31)).known_at_utc_micros, utc_micros(2024, 3, 15, 18, 0, 0)); - assert_eq!(find("SEDAR_Q", day(2024, 3, 31)).known_at_utc_micros, utc_micros(2024, 5, 20, 22, 0, 0)); - assert_eq!(find("SEDAR_A", day(2023, 12, 31)).known_at_utc_micros, utc_micros(2024, 4, 20, 16, 30, 0)); - - // Window boundaries - assert_eq!(find("WIN_Q", day(2024, 3, 31)).known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); - assert_eq!(find("WIN_Q", day(2024, 3, 31)).known_at_utc_micros, utc_micros(2024, 6, 14, 15, 0, 0)); - assert_eq!(find("WIN_Q", day(2024, 3, 30)).known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); - assert_eq!(find("WIN_A", day(2023, 12, 31)).known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); - assert_eq!(find("WIN_A", day(2023, 12, 30)).known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); - - // 8-K and wrong-kind 10-K did not link - assert_eq!(find("NOISE", day(2024, 3, 31)).known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); -} - -#[test] -fn statutory_lag_fallback_exact_offsets_dst_boundary_and_unanchored_vintage() { - let venues = venues_map(&[ - ("US", StatutoryLagVenue::UsTsx), - ("VN", StatutoryLagVenue::TsxvCse), - ]); - - // Spring DST 2024 is Sunday 2024-03-10: - // - 2024-01-24 + 45d = 2024-03-09 (EST, UTC-5) -> 16:05 ET == 21:05 UTC - // - 2024-01-25 + 45d = 2024-03-10 (EDT, UTC-4) -> 16:05 ET == 20:05 UTC - let observations = vec![ - // US/TSX Quarterly (+45d) before DST - obs("US", day(2024, 1, 24), FiscalPeriod::Quarterly, "USD", None, fields_rev(10.0)), - // US/TSX Quarterly (+45d) on spring DST Sunday - obs("US", day(2024, 1, 25), FiscalPeriod::Quarterly, "USD", None, fields_rev(11.0)), - // US/TSX Annual (+90d): 2023-12-31 + 90d = 2024-03-30 (EDT, 2024 is leap year) - obs("US", day(2023, 12, 31), FiscalPeriod::Annual, "USD", None, fields_rev(20.0)), - // TSXV/CSE Quarterly (+60d): 2024-03-31 + 60d = 2024-05-30 (EDT) - obs("VN", day(2024, 3, 31), FiscalPeriod::Quarterly, "CAD", None, fields_rev(30.0)), - // TSXV/CSE Annual (+120d): 2023-12-31 + 120d = 2024-04-29 (EDT) - obs("VN", day(2023, 12, 31), FiscalPeriod::Annual, "CAD", None, fields_rev(40.0)), - // Dated record with no same-day filing and report_date == lag_date -> allowed fallback - obs( - "US", - day(2024, 6, 30), - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 6, 30) + 45), - fields_rev(50.0), - ), - // Dated record with no same-day filing and report_date > lag_date -> dropped as unanchored vintage! - obs( - "US", - day(2024, 9, 30), - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 9, 30) + 46), - fields_rev(60.0), - ), - ]; - - let built = build_fundamentals_rows(observations, Vec::>::new(), &venues); - assert_reconciliation(&built); - assert_eq!(built.stats.rows_out, 6); - assert_eq!(built.stats.rows_statutory_lag_estimate, 6); - assert_eq!(built.stats.observations_dropped_unanchored_vintage, 1); - - let find = |k: &str, pe: i32| { - built - .rows - .iter() - .find(|r| r.key == k && r.period_end == pe) - .expect("row present") - }; - - assert_eq!(find("US", day(2024, 1, 24)).known_at_utc_micros, utc_micros(2024, 3, 9, 21, 5, 0)); - assert_eq!(find("US", day(2024, 1, 25)).known_at_utc_micros, utc_micros(2024, 3, 10, 20, 5, 0)); - assert_eq!(find("US", day(2023, 12, 31)).known_at_utc_micros, utc_micros(2024, 3, 30, 20, 5, 0)); - assert_eq!(find("VN", day(2024, 3, 31)).known_at_utc_micros, utc_micros(2024, 5, 30, 20, 5, 0)); - assert_eq!(find("VN", day(2023, 12, 31)).known_at_utc_micros, utc_micros(2024, 4, 29, 20, 5, 0)); - assert_eq!( - find("US", day(2024, 6, 30)).known_at_utc_micros, - et_to_utc_micros(day(2024, 6, 30) + 45, 16, 5, 0).unwrap() - ); -} - -#[test] -fn ttm_handles_gaps_fy_rows_currency_missing_overflow_carry_forward_and_provenance() { - // 1. Quarter spacing boundaries (76 rejected, 77 accepted, 105 accepted, 106 rejected) - let make_row = |key: &str, pe: i32, kind: FiscalPeriod, curr: &str, ts: i64, src: &'static str, fields: FundamentalsFields| { - FundamentalsRow { - key: key.to_string(), - period_end: pe, - fiscal_period: kind, - currency: curr.to_string(), - known_at_utc_micros: ts, - known_at_source: src, - fields, - } - }; - - let base = day(2023, 1, 1); - // Exact 77-day spacing -> TTM computed - let rows_77 = vec![ - make_row("G77", base, FiscalPeriod::Quarterly, "USD", 1, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(10.0)), - make_row("G77", base + 77, FiscalPeriod::Quarterly, "USD", 2, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(20.0)), - make_row("G77", base + 154, FiscalPeriod::Quarterly, "USD", 3, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(30.0)), - make_row("G77", base + 231, FiscalPeriod::Quarterly, "USD", 4, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(40.0)), - ]; - let snaps_77 = build_fundamentals_snapshots(&rows_77, 2).unwrap(); - assert!(snaps_77[2].ttm.is_none()); // only 3 quarters - let ttm_77 = snaps_77[3].ttm.as_ref().expect("77d spacing is consecutive"); - assert_eq!(ttm_77.flows.revenue, Some(100.0)); - assert_eq!(ttm_77.ending_period_end, base + 231); - // Stock fields remain period values (not summed) - assert_eq!(snaps_77[3].periods[0].fields.total_assets, Some(200.0)); - assert_eq!(snaps_77[3].periods[0].fields.shares_outstanding, Some(1_000.0)); - - // 76-day gap -> None - let mut rows_76 = rows_77.clone(); - rows_76[3].period_end = base + 154 + 76; - assert!(build_fundamentals_snapshots(&rows_76, 4).unwrap()[3].ttm.is_none()); - - // 105-day spacing -> Some, 106-day gap -> None - let rows_105 = vec![ - make_row("G105", base, FiscalPeriod::Quarterly, "USD", 1, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(10.0)), - make_row("G105", base + 105, FiscalPeriod::Quarterly, "USD", 2, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(20.0)), - make_row("G105", base + 210, FiscalPeriod::Quarterly, "USD", 3, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(30.0)), - make_row("G105", base + 315, FiscalPeriod::Quarterly, "USD", 4, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(40.0)), - ]; - assert!(build_fundamentals_snapshots(&rows_105, 4).unwrap()[3].ttm.is_some()); - let mut rows_106 = rows_105.clone(); - rows_106[3].period_end = base + 210 + 106; - assert!(build_fundamentals_snapshots(&rows_106, 4).unwrap()[3].ttm.is_none()); - - // 2. Intervening FY row occupies a snapshot slot while TTM still uses the 4 standalone quarters - let rows_fy = vec![ - make_row("FY", day(2023, 3, 31), FiscalPeriod::Quarterly, "USD", 1, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(10.0)), - make_row("FY", day(2023, 6, 30), FiscalPeriod::Quarterly, "USD", 2, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(20.0)), - make_row("FY", day(2023, 9, 30), FiscalPeriod::Quarterly, "USD", 3, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(30.0)), - make_row("FY", day(2023, 12, 31), FiscalPeriod::Quarterly, "USD", 4, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(40.0)), - make_row("FY", day(2024, 1, 1), FiscalPeriod::Annual, "USD", 5, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(100.0)), - ]; - let snaps_fy = build_fundamentals_snapshots(&rows_fy, 2).unwrap(); - let last_fy = snaps_fy.last().unwrap(); - assert_eq!(last_fy.periods[0].fiscal_period, FiscalPeriod::Annual); - assert_eq!(last_fy.ttm.as_ref().unwrap().flows.revenue, Some(100.0)); - - // 3. Currency mismatch across 4 quarters -> TTM is None - let mut rows_curr = rows_77.clone(); - rows_curr[2].currency = "CAD".to_string(); - assert!(build_fundamentals_snapshots(&rows_curr, 4).unwrap()[3].ttm.is_none()); - - // 4. Missing flow input & overflow -> per-field None while other flow fields still sum - let mut rows_edge = rows_77.clone(); - rows_edge[1].fields.net_income = None; - rows_edge[0].fields.operating_cash_flow = Some(f64::MAX); - rows_edge[1].fields.operating_cash_flow = Some(f64::MAX); - let ttm_edge = build_fundamentals_snapshots(&rows_edge, 4).unwrap()[3] - .ttm - .clone() - .expect("ttm present"); - assert_eq!(ttm_edge.flows.revenue, Some(100.0)); - assert_eq!(ttm_edge.flows.net_income, None); - assert_eq!(ttm_edge.flows.operating_cash_flow, None); - - // 5. Carry-forward stays within same (period_end, kind, currency) and retains estimated provenance - let rows_cf = vec![ - // Initial Q1 with statutory_lag_estimate - make_row( - "CF", - day(2024, 3, 31), - FiscalPeriod::Quarterly, - "USD", - 10, - KNOWN_AT_SOURCE_STATUTORY_LAG, - FundamentalsFields { - revenue: Some(100.0), - net_income: Some(10.0), - operating_cash_flow: None, - total_assets: Some(500.0), - total_equity: None, - shares_outstanding: None, - }, - ), - // Filing restatement leaves net_income=None -> inherits net_income from estimated version -> still estimated! - make_row( - "CF", - day(2024, 3, 31), - FiscalPeriod::Quarterly, - "USD", - 20, - KNOWN_AT_SOURCE_FILING_TIMESTAMP, - FundamentalsFields { - revenue: Some(105.0), - net_income: None, - operating_cash_flow: Some(15.0), - total_assets: Some(505.0), - total_equity: None, - shares_outstanding: None, - }, - ), - // Currency change to CAD at t=30 -> does NOT carry forward USD fields; now purely filing_timestamp! - make_row( - "CF", - day(2024, 3, 31), - FiscalPeriod::Quarterly, - "CAD", - 30, - KNOWN_AT_SOURCE_FILING_TIMESTAMP, - FundamentalsFields { - revenue: Some(140.0), - net_income: None, - operating_cash_flow: None, - total_assets: None, - total_equity: None, - shares_outstanding: None, - }, - ), - ]; - let snaps_cf = build_fundamentals_snapshots(&rows_cf, 2).unwrap(); - assert!(snaps_cf[0].has_estimated_lag); - assert_eq!(snaps_cf[1].periods[0].fields.net_income, Some(10.0)); - assert!(snaps_cf[1].periods[0].has_estimated_lag); - assert!(snaps_cf[1].has_estimated_lag); - assert_eq!(snaps_cf[1].known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); - // After currency change, no carry-forward from USD estimated row - assert_eq!(snaps_cf[2].periods[0].fields.net_income, None); - assert!(!snaps_cf[2].periods[0].has_estimated_lag); - assert!(!snaps_cf[2].has_estimated_lag); - assert_eq!(snaps_cf[2].known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); - - // 6. Estimated TTM contributor outside displayed k=2 slots flags the snapshot as estimated - let rows_ttm_est = vec![ - make_row("EST", base, FiscalPeriod::Quarterly, "USD", 1, KNOWN_AT_SOURCE_STATUTORY_LAG, fields_rev(10.0)), - make_row("EST", base + 90, FiscalPeriod::Quarterly, "USD", 2, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(20.0)), - make_row("EST", base + 180, FiscalPeriod::Quarterly, "USD", 3, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(30.0)), - make_row("EST", base + 270, FiscalPeriod::Quarterly, "USD", 4, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(40.0)), - ]; - let snaps_est = build_fundamentals_snapshots(&rows_ttm_est, 2).unwrap(); - let s4 = &snaps_est[3]; - assert_eq!(s4.periods.len(), 2); - assert!(s4.periods.iter().all(|p| !p.has_estimated_lag)); - assert!(s4.ttm.as_ref().unwrap().has_estimated_lag); - assert!(s4.has_estimated_lag); - assert_eq!(s4.known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); - - // 7. Multiple updates at the same timestamp produce one combined snapshot + as_of edge cases - let rows_same_ts = vec![ - make_row("M", day(2024, 3, 31), FiscalPeriod::Quarterly, "USD", 100, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(10.0)), - make_row("M", day(2024, 6, 30), FiscalPeriod::Quarterly, "USD", 100, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(20.0)), - ]; - let snaps_same = build_fundamentals_snapshots(&rows_same_ts, 4).unwrap(); - assert_eq!(snaps_same.len(), 1); - assert_eq!(snaps_same[0].periods.len(), 2); - assert!(as_of(&snaps_same, "M", 99).is_none()); - assert_eq!(as_of(&snaps_same, "M", 100), Some(&snaps_same[0])); - assert!(as_of(&snaps_same, "UNKNOWN", 100).is_none()); - - // 8. k == 0 rejected with typed error - assert_eq!( - build_fundamentals_snapshots(&rows_same_ts, 0), - Err(FundamentalsError::InvalidPeriodLimit { k: 0 }) - ); -} - -#[test] -fn robustness_bad_rows_dedup_conflicts_and_input_order_determinism() { - let venues = venues_map(&[ - ("A", StatutoryLagVenue::UsTsx), - ("B", StatutoryLagVenue::TsxvCse), - ]); - - let observations = vec![ - // Valid linked observation (with -0.0 normalized to 0.0) + exact duplicate - obs( - "A", - day(2024, 3, 31), - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 5, 1)), - FundamentalsFields { - revenue: Some(-0.0), - net_income: Some(5.0), - operating_cash_flow: Some(6.0), - total_assets: Some(100.0), - total_equity: Some(50.0), - shares_outstanding: Some(10.0), - }, - ), - obs( - "A", - day(2024, 3, 31), - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 5, 1)), - FundamentalsFields { - revenue: Some(0.0), - net_income: Some(5.0), - operating_cash_flow: Some(6.0), - total_assets: Some(100.0), - total_equity: Some(50.0), - shares_outstanding: Some(10.0), - }, - ), - // Conflicting duplicate pair on B (same period_end & known_at, differing revenue) - obs("B", day(2024, 3, 31), FiscalPeriod::Quarterly, "CAD", None, fields_rev(10.0)), - obs("B", day(2024, 3, 31), FiscalPeriod::Quarterly, "CAD", None, fields_rev(11.0)), - // Unknown key - obs("UNKNOWN", day(2024, 3, 31), FiscalPeriod::Quarterly, "USD", None, fields_rev(1.0)), - // Non-finite values (NaN, +inf, -inf) - obs( - "A", - day(2024, 6, 30), - FiscalPeriod::Quarterly, - "USD", - None, - FundamentalsFields { - revenue: Some(f64::NAN), - ..Default::default() - }, - ), - obs( - "A", - day(2024, 6, 30), - FiscalPeriod::Quarterly, - "USD", - None, - FundamentalsFields { - total_assets: Some(f64::INFINITY), - ..Default::default() - }, - ), - // Out-of-range period_end, report_date, and lag_date - obs("A", day(2007, 12, 31), FiscalPeriod::Quarterly, "USD", None, fields_rev(1.0)), - obs("A", day(2024, 6, 30), FiscalPeriod::Quarterly, "USD", Some(day(2031, 1, 1)), fields_rev(1.0)), - obs("A", day(2030, 12, 1), FiscalPeriod::Quarterly, "USD", None, fields_rev(1.0)), - // Explicit report_date <= period_end - obs("A", day(2024, 6, 30), FiscalPeriod::Quarterly, "USD", Some(day(2024, 6, 30)), fields_rev(1.0)), - // Valid second period for A to verify early filing anchored earlier period, not dropped - obs("A", day(2024, 6, 30), FiscalPeriod::Quarterly, "USD", Some(day(2024, 8, 1)), fields_rev(25.0)), - ]; - - let filings = vec![ - // Legitimate filings for A Q1 and Q2 (Q1 filing predates Q2 period_end, must NOT be dropped!) - filing("A", "2024-05-01T16:10:00 EDT", "10-Q"), - filing("A", "2024-08-01T16:10:00 EDT", "10-Q"), - // Early filing on or before A's earliest quarterly period_end (2024-03-31) -> dropped - filing("A", "2024-03-31T16:00:00 EDT", "10-Q"), - // Unknown key - filing("UNKNOWN", "2024-05-01T16:10:00 EDT", "10-Q"), - // Non-periodic - filing("A", "2024-05-02T16:10:00 EDT", "8-K"), - // Invalid timestamps (malformed, unknown zone, invalid date) - filing("A", "not-a-date", "10-Q"), - filing("A", "2024-05-01T16:10:00 UTC", "10-Q"), - filing("A", "2024-02-30T16:10:00 EST", "10-Q"), - // Out-of-range Eastern filing date - filing("A", "2007-12-31T16:10:00 EST", "10-Q"), - ]; - - let built = build_fundamentals_rows(observations.clone(), filings.clone(), &venues); - assert_reconciliation(&built); - - assert_eq!(built.stats.observations_in, 12); - assert_eq!(built.stats.rows_out, 2); - assert_eq!(built.stats.keys_out, 1); - assert_eq!(built.stats.rows_linked_to_filing, 2); - assert_eq!(built.stats.rows_statutory_lag_estimate, 0); - assert_eq!(built.stats.observations_dropped_unknown_key, 1); - assert_eq!(built.stats.observations_dropped_non_finite, 2); - assert_eq!(built.stats.observations_dropped_date_out_of_range, 3); - assert_eq!(built.stats.observations_dropped_report_date_not_after_period_end, 1); - assert_eq!(built.stats.duplicate_collapsed, 1); - assert_eq!(built.stats.duplicate_conflict_dropped, 2); - - assert_eq!(built.stats.filings_in, 9); - assert_eq!(built.stats.filings_eligible, 2); - assert_eq!(built.stats.filings_dropped_unknown_key, 1); - assert_eq!(built.stats.filings_ignored_non_periodic, 1); - assert_eq!(built.stats.filings_dropped_invalid_timestamp, 3); - assert_eq!(built.stats.filings_dropped_date_out_of_range, 1); - assert_eq!(built.stats.filings_dropped_before_period_end, 1); - - // -0.0 normalized to +0.0 - assert_eq!(built.rows[0].fields.revenue.unwrap().to_bits(), 0.0_f64.to_bits()); - - // Input-order determinism: reversed and rotated inputs yield identical rows, snapshots, and stats - let mut obs_rev = observations.clone(); - obs_rev.reverse(); - let mut fil_rev = filings.clone(); - fil_rev.reverse(); - let built_rev = build_fundamentals_rows(obs_rev, fil_rev, &venues); - assert_eq!(built, built_rev); - - let mut obs_rot = observations; - obs_rot.rotate_left(5); - let mut fil_rot = filings; - fil_rot.rotate_left(4); - let built_rot = build_fundamentals_rows(obs_rot, fil_rot, &venues); - assert_eq!(built, built_rot); - - let snaps_a = build_fundamentals_snapshots(&built.rows, 4).unwrap(); - let snaps_b = build_fundamentals_snapshots(&built_rev.rows, 4).unwrap(); - assert_eq!(snaps_a, snaps_b); -} - -#[test] -fn stale_statutory_lag_estimate_does_not_overwrite_newer_filed_version() { - let venues = venues_map(&[("ACME", StatutoryLagVenue::UsTsx)]); - let q1_end = day(2024, 3, 31); - - // Apr 30 observation has no same-day periodic filing -> would fall back to May 15 16:05 ET. - // May 10 observation links to a 10-Q -> visible May 10 16:15 ET. - // Because Apr 30 is an older report vintage than May 10, the stale estimate must be dropped - // so revenue stays 110 at and after May 15 instead of reverting to 100. - let filings = vec![filing("ACME", "2024-05-10T16:15:00 EDT", "10-Q")]; - let observations = vec![ - obs( - "ACME", - q1_end, - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 4, 30)), - fields_rev(100.0), - ), - obs( - "ACME", - q1_end, - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 5, 10)), - fields_rev(110.0), - ), - ]; - - let built = build_fundamentals_rows(observations.clone(), filings.clone(), &venues); - assert_reconciliation(&built); - assert_eq!(built.stats.rows_out, 1); - assert_eq!(built.stats.rows_linked_to_filing, 1); - assert_eq!(built.stats.rows_statutory_lag_estimate, 0); - assert_eq!(built.stats.observations_dropped_stale_estimate, 1); - - // Input-order determinism with stale estimate present - let mut obs_rev = observations; - obs_rev.reverse(); - assert_eq!(built, build_fundamentals_rows(obs_rev, filings, &venues)); - - let snaps = build_fundamentals_snapshots(&built.rows, 4).unwrap(); - assert_eq!(snaps.len(), 1); - - let ts_may_10 = utc_micros(2024, 5, 10, 20, 15, 0); - let ts_may_15_fallback = et_to_utc_micros(day(2024, 5, 15), 16, 5, 0).unwrap(); - - for probe in [ts_may_10, ts_may_15_fallback, ts_may_15_fallback + 1_000_000] { - let snap = as_of(&snaps, "ACME", probe).expect("snapshot visible"); - assert_eq!(snap.effective_known_at_utc_micros, ts_may_10); - assert_eq!(snap.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); - assert!(!snap.has_estimated_lag); - assert_eq!(snap.periods[0].period_end, q1_end); - assert_eq!(snap.periods[0].fields.revenue, Some(110.0)); - } - - // Edge cases: - // (a) An earlier estimate (Apr 30 -> May 15) followed by a LATER filing (Jun 1) is NOT stale. - // (b) A linked FY filing sharing Dec 31 does NOT suppress a standalone Q4 estimate. - let edge_filings = vec![ - filing("ACME", "2024-06-01T17:00:00 EDT", "10-Q/A"), - filing("ACME", "2024-02-12T16:15:00 EST", "10-K"), - ]; - let dec_31 = day(2023, 12, 31); - let edge_obs = vec![ - obs("ACME", q1_end, FiscalPeriod::Quarterly, "USD", Some(day(2024, 4, 30)), fields_rev(100.0)), - obs("ACME", q1_end, FiscalPeriod::Quarterly, "USD", Some(day(2024, 6, 1)), fields_rev(115.0)), - obs("ACME", dec_31, FiscalPeriod::Quarterly, "USD", Some(day(2024, 2, 10)), fields_rev(40.0)), - obs("ACME", dec_31, FiscalPeriod::Annual, "USD", Some(day(2024, 2, 12)), fields_rev(160.0)), - ]; - let edge_built = build_fundamentals_rows(edge_obs, edge_filings, &venues); - assert_reconciliation(&edge_built); - assert_eq!(edge_built.stats.observations_dropped_stale_estimate, 0); - assert_eq!(edge_built.stats.rows_out, 4); -} - -#[test] -fn conflicting_newer_filing_does_not_suppress_eligible_statutory_lag_estimate() { - let venues = venues_map(&[("ACME", StatutoryLagVenue::UsTsx)]); - let q1_end = day(2024, 3, 31); - - // Apr 30 observation (rev 100) has no same-day filing -> May 15 16:05 ET fallback. - // Two May 10 observations link to the same 10-Q with conflicting revenues (110 vs 112). - // Because the May 10 group is rejected as a duplicate conflict, it must NOT suppress the - // eligible Apr 30 statutory-lag estimate. - let filings = vec![filing("ACME", "2024-05-10T16:15:00 EDT", "10-Q")]; - let observations = vec![ - obs( - "ACME", - q1_end, - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 4, 30)), - fields_rev(100.0), - ), - obs( - "ACME", - q1_end, - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 5, 10)), - fields_rev(110.0), - ), - obs( - "ACME", - q1_end, - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 5, 10)), - fields_rev(112.0), - ), - ]; - - let built = build_fundamentals_rows(observations.clone(), filings.clone(), &venues); - assert_reconciliation(&built); - assert_eq!(built.stats.duplicate_conflict_dropped, 2); - assert_eq!(built.stats.observations_dropped_stale_estimate, 0); - assert_eq!(built.stats.rows_out, 1); - assert_eq!(built.stats.rows_linked_to_filing, 0); - assert_eq!(built.stats.rows_statutory_lag_estimate, 1); - - // Input-order determinism - let mut obs_rev = observations; - obs_rev.reverse(); - assert_eq!(built, build_fundamentals_rows(obs_rev, filings, &venues)); - - let snaps = build_fundamentals_snapshots(&built.rows, 4).unwrap(); - let ts_may_10 = utc_micros(2024, 5, 10, 20, 15, 0); - let ts_may_15_fallback = et_to_utc_micros(day(2024, 5, 15), 16, 5, 0).unwrap(); - - assert!(as_of(&snaps, "ACME", ts_may_10).is_none()); - assert!(as_of(&snaps, "ACME", ts_may_15_fallback - 1).is_none()); - - let snap = as_of(&snaps, "ACME", ts_may_15_fallback).expect("fallback estimate must be visible"); - assert_eq!(snap.effective_known_at_utc_micros, ts_may_15_fallback); - assert_eq!(snap.known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); - assert!(snap.has_estimated_lag); - assert_eq!(snap.periods[0].period_end, q1_end); - assert_eq!(snap.periods[0].fields.revenue, Some(100.0)); -} - -#[test] -fn stale_estimate_at_same_fallback_timestamp_does_not_conflict_with_eligible_estimate() { - let venues = venues_map(&[("ACME", StatutoryLagVenue::UsTsx)]); - let q1_end = day(2024, 3, 31); - - // Apr 30 (rev 100) and May 12 (rev 115) have no same-day periodic filing -> both get the - // May 15 16:05 ET fallback timestamp. The accepted May 10 10-Q (rev 110) supersedes Apr 30, - // so Apr 30 must be dropped as a stale estimate before duplicate/conflict checks and must - // not cause the eligible May 12 estimate to be discarded as a conflict. - let filings = vec![filing("ACME", "2024-05-10T16:15:00 EDT", "10-Q")]; - let observations = vec![ - obs( - "ACME", - q1_end, - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 4, 30)), - fields_rev(100.0), - ), - obs( - "ACME", - q1_end, - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 5, 10)), - fields_rev(110.0), - ), - obs( - "ACME", - q1_end, - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 5, 12)), - fields_rev(115.0), - ), - ]; - - let built = build_fundamentals_rows(observations.clone(), filings.clone(), &venues); - assert_reconciliation(&built); - assert_eq!(built.stats.observations_dropped_stale_estimate, 1); - assert_eq!(built.stats.duplicate_conflict_dropped, 0); - assert_eq!(built.stats.rows_out, 2); - assert_eq!(built.stats.rows_linked_to_filing, 1); - assert_eq!(built.stats.rows_statutory_lag_estimate, 1); - - // Input-order determinism - let mut obs_rev = observations; - obs_rev.reverse(); - assert_eq!(built, build_fundamentals_rows(obs_rev, filings, &venues)); - - let snaps = build_fundamentals_snapshots(&built.rows, 4).unwrap(); - let ts_may_15_fallback = et_to_utc_micros(day(2024, 5, 15), 16, 5, 0).unwrap(); - - let before_fallback = as_of(&snaps, "ACME", ts_may_15_fallback - 1) - .expect("May 10 10-Q must be visible before fallback"); - assert_eq!(before_fallback.periods[0].period_end, q1_end); - assert_eq!(before_fallback.periods[0].fields.revenue, Some(110.0)); - assert_eq!(before_fallback.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); - assert!(!before_fallback.has_estimated_lag); - - let at_fallback = as_of(&snaps, "ACME", ts_may_15_fallback) - .expect("May 12 estimate must be visible at fallback cutoff"); - assert_eq!(at_fallback.effective_known_at_utc_micros, ts_may_15_fallback); - assert_eq!(at_fallback.periods[0].period_end, q1_end); - assert_eq!(at_fallback.periods[0].fields.revenue, Some(115.0)); - assert_eq!(at_fallback.known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); - assert!(at_fallback.has_estimated_lag); -} - -#[test] -fn annual_fy_sharing_q4_period_end_preserves_standalone_q4_for_ttm() { - let make_row = |pe: i32, kind: FiscalPeriod, ts: i64, src: &'static str, fields: FundamentalsFields| { - FundamentalsRow { - key: "CAL".to_string(), - period_end: pe, - fiscal_period: kind, - currency: "USD".to_string(), - known_at_utc_micros: ts, - known_at_source: src, - fields, - } - }; - - let q1 = day(2023, 3, 31); - let q2 = day(2023, 6, 30); - let q3 = day(2023, 9, 30); - let q4_fy = day(2023, 12, 31); - - let rows = vec![ - make_row(q1, FiscalPeriod::Quarterly, 100, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(10.0)), - make_row(q2, FiscalPeriod::Quarterly, 200, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(20.0)), - make_row(q3, FiscalPeriod::Quarterly, 300, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(30.0)), - make_row(q4_fy, FiscalPeriod::Quarterly, 400, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(40.0)), - // Later FY report sharing December 31 period_end - make_row(q4_fy, FiscalPeriod::Annual, 500, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(100.0)), - // Even later Q4 restatement omitting operating_cash_flow -> should inherit original Q4's OCF - make_row( - q4_fy, - FiscalPeriod::Quarterly, - 600, - KNOWN_AT_SOURCE_FILING_TIMESTAMP, - FundamentalsFields { - revenue: Some(45.0), - net_income: Some(4.5), - operating_cash_flow: None, - total_assets: Some(210.0), - total_equity: Some(85.0), - shares_outstanding: Some(1_000.0), - }, - ), - // Partial FY amendment after the Q4 amendment -> should inherit original FY's OCF (15.0) - make_row( - q4_fy, - FiscalPeriod::Annual, - 700, - KNOWN_AT_SOURCE_FILING_TIMESTAMP, - FundamentalsFields { - revenue: Some(102.0), - net_income: Some(10.2), - operating_cash_flow: None, - total_assets: Some(220.0), - total_equity: Some(90.0), - shares_outstanding: Some(1_000.0), - }, - ), - ]; - - let snaps = build_fundamentals_snapshots(&rows, 4).unwrap(); - assert_eq!(snaps.len(), 7); - - // At t=400 (Q4 visible): TTM ends 2023-12-31 with revenue 100 - let s4 = as_of(&snaps, "CAL", 400).unwrap(); - assert_eq!(s4.periods[0].period_end, q4_fy); - assert_eq!(s4.periods[0].fiscal_period, FiscalPeriod::Quarterly); - assert_eq!(s4.ttm.as_ref().unwrap().ending_period_end, q4_fy); - assert_eq!(s4.ttm.as_ref().unwrap().flows.revenue, Some(100.0)); - - // At t=500 (FY shares 2023-12-31): latest slot is FY, while TTM still uses all 4 standalone quarters - let s5 = as_of(&snaps, "CAL", 500).unwrap(); - assert_eq!(s5.periods[0].period_end, q4_fy); - assert_eq!(s5.periods[0].fiscal_period, FiscalPeriod::Annual); - assert_eq!(s5.periods[0].fields.revenue, Some(100.0)); - let ttm5 = s5.ttm.as_ref().expect("TTM must survive FY sharing Dec 31"); - assert_eq!(ttm5.ending_period_end, q4_fy); - assert_eq!(ttm5.flows.revenue, Some(100.0)); - assert_eq!(ttm5.flows.net_income, Some(10.0)); - assert_eq!(ttm5.flows.operating_cash_flow, Some(15.0)); - - // At t=600 (Q4 restatement after FY): inherits original Q4's operating_cash_flow (6.0), TTM updates to 105 - let s6 = as_of(&snaps, "CAL", 600).unwrap(); - assert_eq!(s6.periods[0].period_end, q4_fy); - assert_eq!(s6.periods[0].fiscal_period, FiscalPeriod::Quarterly); - assert_eq!(s6.periods[0].fields.revenue, Some(45.0)); - assert_eq!(s6.periods[0].fields.operating_cash_flow, Some(6.0)); - let ttm6 = s6.ttm.as_ref().expect("TTM after Q4 restatement"); - assert_eq!(ttm6.ending_period_end, q4_fy); - assert_eq!(ttm6.flows.revenue, Some(105.0)); - assert_eq!(ttm6.flows.operating_cash_flow, Some(15.0)); - - // At t=700 (partial FY amendment after Q4 amendment): inherits original FY's OCF (15.0) while - // TTM remains backed by the 4 standalone quarters (rev 105, OCF 15). - let s7 = as_of(&snaps, "CAL", 700).unwrap(); - assert_eq!(s7.periods[0].period_end, q4_fy); - assert_eq!(s7.periods[0].fiscal_period, FiscalPeriod::Annual); - assert_eq!(s7.periods[0].fields.revenue, Some(102.0)); - assert_eq!(s7.periods[0].fields.operating_cash_flow, Some(15.0)); - let ttm7 = s7.ttm.as_ref().expect("TTM after partial FY amendment"); - assert_eq!(ttm7.ending_period_end, q4_fy); - assert_eq!(ttm7.flows.revenue, Some(105.0)); - assert_eq!(ttm7.flows.operating_cash_flow, Some(15.0)); - - // Provenance check: if Q4 was statutory_lag_estimate and later FY (filing_timestamp) occupies - // periods[0] on Dec 31, TTM still uses estimated Q4 so snapshot stays flagged estimated. - let rows_est_q4 = vec![ - make_row(q1, FiscalPeriod::Quarterly, 100, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(10.0)), - make_row(q2, FiscalPeriod::Quarterly, 200, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(20.0)), - make_row(q3, FiscalPeriod::Quarterly, 300, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(30.0)), - make_row(q4_fy, FiscalPeriod::Quarterly, 400, KNOWN_AT_SOURCE_STATUTORY_LAG, fields_rev(40.0)), - make_row(q4_fy, FiscalPeriod::Annual, 500, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(100.0)), - ]; - let snaps_est = build_fundamentals_snapshots(&rows_est_q4, 4).unwrap(); - let fy_snap = as_of(&snaps_est, "CAL", 500).unwrap(); - assert!(!fy_snap.periods[0].has_estimated_lag); - assert!(fy_snap.ttm.as_ref().unwrap().has_estimated_lag); - assert!(fy_snap.has_estimated_lag); - assert_eq!(fy_snap.known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); -} diff --git a/tools/curate-etl/src/ilp.rs b/tools/curate-etl/src/ilp.rs deleted file mode 100644 index 6130adfa..00000000 --- a/tools/curate-etl/src/ilp.rs +++ /dev/null @@ -1,574 +0,0 @@ -//! Pure, socket-free QuestDB ILP v2 line encoder and sharded batch writer for -//! `bars_1m` and `fx_1m`. -//! -//! # Wire format (QuestDB ILP Protocol Version 2) -//! -//! Verified against the official `questdb-rs` client source in -//! `questdb/c-questdb-client` (`main` branch, `questdb-rs`): -//! - Binary `DOUBLE` type tag (`DOUBLE_TYPE = 16` / `0x10`): -//! `questdb-rs/src/ingress.rs` lines 157–159. -//! - Tag/field separators and binary `f64` field encoding (`==\x10<8 LE IEEE-754 bytes>`): -//! `questdb-rs/src/ingress/buffer/ilp.rs` lines 569–713. -//! - ILP escaping for `SYMBOL` values (space, `,`, `=`, `\n`, `\r`, and `\` prefixed with `\`): -//! `questdb-rs/src/ingress/buffer/ilp.rs` lines 36–84. -//! - Timestamp column microsecond suffix (`=t`): -//! `questdb-rs/src/ingress/buffer/ilp.rs` lines 1026–1047. -//! - Designated timestamp microsecond suffix (` t\n`, non-negative): -//! `questdb-rs/src/ingress/buffer/ilp.rs` lines 1087–1116. -//! -//! # Table contracts -//! -//! Column names and types match `M2_INTRADAY_SCHEMAS` in `libs/data/questdb/src/schema.ts` -//! and `design/DATA-CONTRACTS.md` §3.B: -//! - `bars_1m`: symbols `listing_id`, `session`, `source`; binary doubles `open`, `high`, `low`, -//! `close`, `volume` (`vwap` is omitted / NULL); timestamp column `known_at`; designated -//! timestamp `ts` (UTC microseconds). -//! - `fx_1m`: symbols `pair`, `source`; binary doubles `open`, `high`, `low`, `close`; -//! designated timestamp `ts` (UTC microseconds). -//! -//! # Deterministic sharding -//! -//! [`IlpShardedWriter`] routes rows deterministically using 64-bit FNV-1a modulo shard count -//! (`fnv1a_64(key_bytes) % shard_count`): -//! - `bars_1m` hashes `listing_id` as its 4-byte little-endian representation -//! (`listing_id.to_le_bytes()`). -//! - `fx_1m` hashes `pair` as its raw UTF-8 bytes (`pair.as_bytes()`). -//! -//! All rows for a given key always land on the same shard in their exact input order, preserving -//! the per-key ordering required by `DEDUP UPSERT KEYS(ts, listing_id)` / `KEYS(ts, pair)`. - -use std::error::Error; -use std::fmt; -use std::io::{self, Write}; - -use crate::bars_1m::Bar1mRow; - -/// QuestDB ILP v2 binary `DOUBLE` type byte (`16` / `0x10`). -pub const ILP_V2_DOUBLE_TYPE: u8 = 0x10; - -/// Canonical QuestDB table name for 1-minute equity bars. -pub const TABLE_BARS_1M: &str = "bars_1m"; - -/// Canonical QuestDB table name for 1-minute FX bars. -pub const TABLE_FX_1M: &str = "fx_1m"; - -/// 64-bit FNV-1a offset basis used for deterministic shard routing. -pub const FNV1A_64_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; - -/// 64-bit FNV-1a prime used for deterministic shard routing. -pub const FNV1A_64_PRIME: u64 = 0x0000_0100_0000_01b3; - -/// Default maximum buffered bytes per shard before flushing a batch (1 MiB). -pub const DEFAULT_ILP_MAX_BATCH_BYTES: usize = 1_048_576; - -/// Default maximum buffered rows per shard before flushing a batch. -pub const DEFAULT_ILP_MAX_BATCH_ROWS: usize = 10_000; - -/// A single `fx_1m` 1-minute FX bar input for QuestDB ILP v2 encoding. -/// -/// Matches `M2_INTRADAY_SCHEMAS.fx_1m` in `libs/data/questdb/src/schema.ts`: -/// `pair` (SYMBOL), `open`/`high`/`low`/`close` (DOUBLE), `source` (SYMBOL), `ts` (TIMESTAMP). -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct Fx1mRow<'a> { - pub pair: &'a str, - /// Bar start timestamp in UTC microseconds since the Unix epoch (must be `>= 0`). - pub ts: i64, - pub open: f64, - pub high: f64, - pub low: f64, - pub close: f64, - pub source: &'a str, -} - -/// Typed validation errors returned by [`encode_bar_1m`] and [`encode_fx_1m`]. -/// -/// Encoding is atomic: when an error is returned, the caller's destination buffer is left -/// completely unmodified. -#[derive(Debug, Clone, PartialEq)] -pub enum IlpEncodeError { - /// A `DOUBLE` field was non-finite (`NaN`, `+inf`, or `-inf`). - NonFiniteDouble { field: &'static str, value: f64 }, - /// The designated timestamp `ts` was negative (QuestDB ILP requires `ts >= 0`). - NegativeTimestamp { field: &'static str, value: i64 }, - /// A required `SYMBOL` column value was empty. - EmptySymbol { field: &'static str }, -} - -impl fmt::Display for IlpEncodeError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match *self { - Self::NonFiniteDouble { field, value } => { - write!(f, "non-finite ILP double field '{field}': {value}") - } - Self::NegativeTimestamp { field, value } => { - write!( - f, - "negative ILP designated timestamp '{field}': {value} (must be >= 0)" - ) - } - Self::EmptySymbol { field } => { - write!(f, "empty ILP symbol field '{field}'") - } - } - } -} - -impl Error for IlpEncodeError {} - -/// Batching limits for [`IlpShardedWriter`]. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct IlpWriterOptions { - /// Maximum buffered bytes per shard before flushing (must be `>= 1`). - pub max_batch_bytes: usize, - /// Maximum buffered rows per shard before flushing (must be `>= 1`). - pub max_batch_rows: usize, -} - -impl Default for IlpWriterOptions { - fn default() -> Self { - Self { - max_batch_bytes: DEFAULT_ILP_MAX_BATCH_BYTES, - max_batch_rows: DEFAULT_ILP_MAX_BATCH_ROWS, - } - } -} - -/// Summary statistics returned by [`IlpShardedWriter::finish`]. -/// -/// Conservation invariants: -/// - `per_shard_rows.iter().sum::() == rows` -/// - `bytes` equals the exact sum of bytes written across all successful shard `write_all` calls. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct IlpWriteStats { - pub rows: usize, - pub bytes: usize, - pub flushes: usize, - pub per_shard_rows: Vec, -} - -/// Typed errors returned by [`IlpShardedWriter`]. -#[derive(Debug)] -pub enum IlpWriterError { - /// No sinks were provided to [`IlpShardedWriter::new`]. - EmptySinks, - /// [`IlpWriterOptions::max_batch_bytes`] was `0`. - ZeroMaxBatchBytes, - /// [`IlpWriterOptions::max_batch_rows`] was `0`. - ZeroMaxBatchRows, - /// Row encoding failed before mutating any shard buffer. - Encode(IlpEncodeError), - /// A sink `write_all` or `flush` call failed on `shard`. - Io { shard: usize, source: io::Error }, - /// A previous I/O failure on `failed_shard` poisoned the writer; no further writes are allowed. - Poisoned { failed_shard: usize }, -} - -impl fmt::Display for IlpWriterError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::EmptySinks => write!(f, "ILP sharded writer requires at least one sink"), - Self::ZeroMaxBatchBytes => { - write!(f, "ILP writer max_batch_bytes must be >= 1") - } - Self::ZeroMaxBatchRows => { - write!(f, "ILP writer max_batch_rows must be >= 1") - } - Self::Encode(err) => write!(f, "ILP encode error: {err}"), - Self::Io { shard, source } => { - write!(f, "ILP writer I/O error on shard {shard}: {source}") - } - Self::Poisoned { failed_shard } => write!( - f, - "ILP writer is poisoned after prior I/O error on shard {failed_shard}" - ), - } - } -} - -impl Error for IlpWriterError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::Encode(err) => Some(err), - Self::Io { source, .. } => Some(source), - Self::EmptySinks - | Self::ZeroMaxBatchBytes - | Self::ZeroMaxBatchRows - | Self::Poisoned { .. } => None, - } - } -} - -impl From for IlpWriterError { - fn from(err: IlpEncodeError) -> Self { - Self::Encode(err) - } -} - -/// Computes the 64-bit FNV-1a hash of `bytes`. -#[inline] -pub fn fnv1a_64(bytes: &[u8]) -> u64 { - let mut hash = FNV1A_64_OFFSET_BASIS; - for &b in bytes { - hash ^= u64::from(b); - hash = hash.wrapping_mul(FNV1A_64_PRIME); - } - hash -} - -/// Deterministic shard index for an equity `listing_id` (`i32` hashed as 4 little-endian bytes). -#[inline] -pub fn shard_for_listing_id(listing_id: i32, shard_count: usize) -> usize { - debug_assert!(shard_count > 0); - (fnv1a_64(&listing_id.to_le_bytes()) % (shard_count as u64)) as usize -} - -/// Deterministic shard index for an FX `pair` (hashed as raw UTF-8 bytes). -#[inline] -pub fn shard_for_fx_pair(pair: &str, shard_count: usize) -> usize { - debug_assert!(shard_count > 0); - (fnv1a_64(pair.as_bytes()) % (shard_count as u64)) as usize -} - -#[inline] -fn validate_finite(field: &'static str, value: f64) -> Result<(), IlpEncodeError> { - if value.is_finite() { - Ok(()) - } else { - Err(IlpEncodeError::NonFiniteDouble { field, value }) - } -} - -#[inline] -fn validate_non_negative_ts(field: &'static str, value: i64) -> Result<(), IlpEncodeError> { - if value >= 0 { - Ok(()) - } else { - Err(IlpEncodeError::NegativeTimestamp { field, value }) - } -} - -/// Escapes an ILP tag/symbol value by prefixing space, `,`, `=`, `\n`, `\r`, and `\` with `\`. -#[inline] -fn write_escaped_symbol(buf: &mut Vec, value: &str) { - let bytes = value.as_bytes(); - let mut last = 0usize; - for (i, &b) in bytes.iter().enumerate() { - if matches!(b, b' ' | b',' | b'=' | b'\n' | b'\r' | b'\\') { - if last < i { - buf.extend_from_slice(&bytes[last..i]); - } - buf.push(b'\\'); - buf.push(b); - last = i + 1; - } - } - if last < bytes.len() { - buf.extend_from_slice(&bytes[last..]); - } -} - -#[inline] -fn write_i64_decimal(buf: &mut Vec, value: i64) { - let mut tmp = [0u8; 20]; - let negative = value < 0; - let mut mag = value.unsigned_abs(); - let mut pos = tmp.len(); - if mag == 0 { - pos -= 1; - tmp[pos] = b'0'; - } else { - while mag > 0 { - pos -= 1; - tmp[pos] = b'0' + (mag % 10) as u8; - mag /= 10; - } - } - if negative { - pos -= 1; - tmp[pos] = b'-'; - } - buf.extend_from_slice(&tmp[pos..]); -} - -#[inline] -fn write_binary_f64(buf: &mut Vec, name: &str, value: f64) { - buf.extend_from_slice(name.as_bytes()); - buf.extend_from_slice(&[b'=', b'=', ILP_V2_DOUBLE_TYPE]); - buf.extend_from_slice(&value.to_le_bytes()); -} - -/// Encodes one curated `bars_1m` row in QuestDB ILP v2 format into `buf`. -/// -/// Emits: -/// - Table `bars_1m` -/// - Symbols `listing_id` (decimal `row.key`), `session` (`PRE`/`RTH`/`POST`), `source` -/// - Binary `f64` columns `open`, `high`, `low`, `close`, `volume` (`vwap` omitted / NULL) -/// - Timestamp column `known_at=t` -/// - Designated timestamp ` t\n` -/// -/// Validates all doubles, `source`, and non-negative `row.ts` before appending any bytes so -/// `buf` is left untouched on error. -pub fn encode_bar_1m( - buf: &mut Vec, - row: &Bar1mRow, - known_at_micros: i64, -) -> Result<(), IlpEncodeError> { - if row.source.is_empty() { - return Err(IlpEncodeError::EmptySymbol { field: "source" }); - } - validate_finite("open", row.open)?; - validate_finite("high", row.high)?; - validate_finite("low", row.low)?; - validate_finite("close", row.close)?; - validate_finite("volume", row.volume)?; - validate_non_negative_ts("ts", row.ts)?; - - buf.extend_from_slice(TABLE_BARS_1M.as_bytes()); - buf.extend_from_slice(b",listing_id="); - write_i64_decimal(buf, i64::from(row.key)); - buf.extend_from_slice(b",session="); - buf.extend_from_slice(row.session.as_str().as_bytes()); - buf.extend_from_slice(b",source="); - write_escaped_symbol(buf, row.source); - - buf.push(b' '); - write_binary_f64(buf, "open", row.open); - buf.push(b','); - write_binary_f64(buf, "high", row.high); - buf.push(b','); - write_binary_f64(buf, "low", row.low); - buf.push(b','); - write_binary_f64(buf, "close", row.close); - buf.push(b','); - write_binary_f64(buf, "volume", row.volume); - buf.extend_from_slice(b",known_at="); - write_i64_decimal(buf, known_at_micros); - buf.extend_from_slice(b"t "); - - write_i64_decimal(buf, row.ts); - buf.extend_from_slice(b"t\n"); - Ok(()) -} - -/// Encodes one `fx_1m` row in QuestDB ILP v2 format into `buf`. -/// -/// Emits: -/// - Table `fx_1m` -/// - Symbols `pair`, `source` -/// - Binary `f64` columns `open`, `high`, `low`, `close` -/// - Designated timestamp ` t\n` -/// -/// Validates `pair`, `source`, all doubles, and non-negative `row.ts` before appending any bytes -/// so `buf` is left untouched on error. -pub fn encode_fx_1m(buf: &mut Vec, row: &Fx1mRow<'_>) -> Result<(), IlpEncodeError> { - if row.pair.is_empty() { - return Err(IlpEncodeError::EmptySymbol { field: "pair" }); - } - if row.source.is_empty() { - return Err(IlpEncodeError::EmptySymbol { field: "source" }); - } - validate_finite("open", row.open)?; - validate_finite("high", row.high)?; - validate_finite("low", row.low)?; - validate_finite("close", row.close)?; - validate_non_negative_ts("ts", row.ts)?; - - buf.extend_from_slice(TABLE_FX_1M.as_bytes()); - buf.extend_from_slice(b",pair="); - write_escaped_symbol(buf, row.pair); - buf.extend_from_slice(b",source="); - write_escaped_symbol(buf, row.source); - - buf.push(b' '); - write_binary_f64(buf, "open", row.open); - buf.push(b','); - write_binary_f64(buf, "high", row.high); - buf.push(b','); - write_binary_f64(buf, "low", row.low); - buf.push(b','); - write_binary_f64(buf, "close", row.close); - - buf.push(b' '); - write_i64_decimal(buf, row.ts); - buf.extend_from_slice(b"t\n"); - Ok(()) -} - -struct ShardState { - sink: W, - buf: Vec, - pending_rows: usize, - written_rows: usize, -} - -/// Deterministic, sink-agnostic sharded QuestDB ILP v2 batch writer. -/// -/// Buffers complete ILP lines per shard and flushes whole-line batches to injected [`Write`] -/// sinks when either `max_batch_rows` or `max_batch_bytes` is reached, or on [`Self::finish`]. -pub struct IlpShardedWriter { - shards: Vec>, - options: IlpWriterOptions, - scratch: Vec, - rows_written: usize, - bytes_written: usize, - flushes: usize, - poisoned_shard: Option, -} - -impl IlpShardedWriter { - /// Creates a new sharded writer over `sinks` with the given batching `options`. - /// - /// Returns an error if `sinks` is empty or either batch limit is zero. - pub fn new(sinks: Vec, options: IlpWriterOptions) -> Result { - if sinks.is_empty() { - return Err(IlpWriterError::EmptySinks); - } - if options.max_batch_bytes == 0 { - return Err(IlpWriterError::ZeroMaxBatchBytes); - } - if options.max_batch_rows == 0 { - return Err(IlpWriterError::ZeroMaxBatchRows); - } - - let initial_buf_cap = options.max_batch_bytes.min(DEFAULT_ILP_MAX_BATCH_BYTES); - let shards = sinks - .into_iter() - .map(|sink| ShardState { - sink, - buf: Vec::with_capacity(initial_buf_cap), - pending_rows: 0, - written_rows: 0, - }) - .collect(); - - Ok(Self { - shards, - options, - scratch: Vec::with_capacity(256), - rows_written: 0, - bytes_written: 0, - flushes: 0, - poisoned_shard: None, - }) - } - - /// Returns the number of configured shards. - #[inline] - pub fn shard_count(&self) -> usize { - self.shards.len() - } - - /// Returns `(flushed_rows, pending_rows)` across all shards. - #[inline] - pub(crate) fn row_counts(&self) -> (usize, usize) { - let pending = self.shards.iter().map(|s| s.pending_rows).sum(); - (self.rows_written, pending) - } - - /// Encodes and buffers one `bars_1m` row on the shard determined by `row.key`. - pub fn write_bar_1m( - &mut self, - row: &Bar1mRow, - known_at_micros: i64, - ) -> Result<(), IlpWriterError> { - if let Some(failed_shard) = self.poisoned_shard { - return Err(IlpWriterError::Poisoned { failed_shard }); - } - self.scratch.clear(); - encode_bar_1m(&mut self.scratch, row, known_at_micros)?; - let shard_idx = shard_for_listing_id(row.key, self.shards.len()); - self.enqueue_scratch_row(shard_idx) - } - - /// Encodes and buffers one `fx_1m` row on the shard determined by `row.pair`. - pub fn write_fx_1m(&mut self, row: &Fx1mRow<'_>) -> Result<(), IlpWriterError> { - if let Some(failed_shard) = self.poisoned_shard { - return Err(IlpWriterError::Poisoned { failed_shard }); - } - self.scratch.clear(); - encode_fx_1m(&mut self.scratch, row)?; - let shard_idx = shard_for_fx_pair(row.pair, self.shards.len()); - self.enqueue_scratch_row(shard_idx) - } - - /// Flushes all remaining buffered batches and underlying sinks, returning write statistics. - pub fn finish(mut self) -> Result { - if let Some(failed_shard) = self.poisoned_shard { - return Err(IlpWriterError::Poisoned { failed_shard }); - } - - for shard_idx in 0..self.shards.len() { - if !self.shards[shard_idx].buf.is_empty() { - self.flush_shard(shard_idx)?; - } - if let Err(source) = self.shards[shard_idx].sink.flush() { - self.poisoned_shard = Some(shard_idx); - return Err(IlpWriterError::Io { - shard: shard_idx, - source, - }); - } - } - - let per_shard_rows = self.shards.iter().map(|s| s.written_rows).collect(); - Ok(IlpWriteStats { - rows: self.rows_written, - bytes: self.bytes_written, - flushes: self.flushes, - per_shard_rows, - }) - } - - fn enqueue_scratch_row(&mut self, shard_idx: usize) -> Result<(), IlpWriterError> { - let row_len = self.scratch.len(); - let needs_preflush = { - let shard = &self.shards[shard_idx]; - !shard.buf.is_empty() - && shard.buf.len().saturating_add(row_len) > self.options.max_batch_bytes - }; - if needs_preflush { - self.flush_shard(shard_idx)?; - } - - let needs_postflush = { - let shard = &mut self.shards[shard_idx]; - shard.buf.extend_from_slice(&self.scratch); - shard.pending_rows += 1; - shard.pending_rows >= self.options.max_batch_rows - || shard.buf.len() >= self.options.max_batch_bytes - }; - if needs_postflush { - self.flush_shard(shard_idx)?; - } - - Ok(()) - } - - fn flush_shard(&mut self, shard_idx: usize) -> Result<(), IlpWriterError> { - let shard = &mut self.shards[shard_idx]; - if shard.buf.is_empty() { - return Ok(()); - } - if let Err(source) = shard.sink.write_all(&shard.buf) { - self.poisoned_shard = Some(shard_idx); - return Err(IlpWriterError::Io { - shard: shard_idx, - source, - }); - } - - let bytes = shard.buf.len(); - let rows = shard.pending_rows; - shard.buf.clear(); - shard.pending_rows = 0; - shard.written_rows += rows; - self.rows_written += rows; - self.bytes_written += bytes; - self.flushes += 1; - Ok(()) - } -} - -#[cfg(test)] -#[path = "ilp_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/ilp_send.rs b/tools/curate-etl/src/ilp_send.rs deleted file mode 100644 index 4c3d38e1..00000000 --- a/tools/curate-etl/src/ilp_send.rs +++ /dev/null @@ -1,871 +0,0 @@ -//! Multi-socket QuestDB ILP v2 shard-file sender (`M2.3p`). -//! -//! Streams published `.shard-.ilp` files (produced by [`crate::run_curate_bars_1m`], -//! [`crate::run_curate_qm_bars_1m`], or [`crate::run_curate_fx_1m`]) verbatim over one dedicated -//! sink/socket per shard using `std::thread::scope`. -//! -//! # Transport & Acknowledgement Semantics -//! -//! - **No server acknowledgement over TCP:** QuestDB's TCP ILP listener sends no per-row or -//! per-batch acknowledgement. A server-side parse error or schema rejection surfaces only as a -//! dropped connection or missing rows. A successful [`send_ilp_shard_files`] return therefore -//! means **"all bytes were accepted by the local socket and write-half shutdown succeeded"**, -//! not **"all rows were committed in QuestDB"**. Verify row counts and representative values -//! separately via PGWire after loading. -//! - **Protocol Version 2 binary doubles over TCP (unverified for QuestDB `10.2.0`):** QuestDB's -//! ILP transport documentation () -//! documents explicit client-side protocol-version-2 selection for TCP without autodetection. -//! Exact QuestDB `10.2.0` acceptance of this crate's ILP v2 binary `DOUBLE` payloads (`0x10` + -//! 8-byte LE IEEE-754) on the TCP ILP port (default `9009`) without a handshake is -//! **unverified** — confirm it in the manual `quant` load check using PGWire row counts and -//! spot-checked OHLCV/FX values before bulk ingestion. -//! -//! # Data Ownership, Discovery & Replay Semantics -//! -//! - **Completed publisher output required:** [`discover_ilp_shard_files`] consumes a completed, -//! immutable publisher output directory. Filenames alone cannot detect an in-progress -//! publication or a missing trailing shard. -//! - **Byte-for-byte streaming:** Bytes are streamed verbatim in fixed-size chunks -//! (`IlpSendOptions::buffer_bytes`) without loading whole files into RAM and without splitting, -//! re-framing, or re-encoding lines (binary `f64` fields may legitimately contain `0x0A`). -//! - **Per-key ordering & idempotent resend:** Quant data curation owns the curated shard files -//! as the durable replay baseline for OHLCV, FX values, timestamps, `known_at`, and per-key -//! ordering (`design/DATA-CONTRACTS.md` §3.B, `design/MILESTONES.md` M2). Because each shard -//! streams over a single dedicated sink in file order, per-key ordering is preserved. On any -//! shard failure, [`IlpSendError::ShardIo`] includes a partial [`IlpSendReport`] with per-shard -//! `bytes_sent` so operators can re-send the full, identical shard set against QuestDB's -//! configured `DEDUP UPSERT KEYS(ts, listing_id)` (`bars_1m`) or `DEDUP UPSERT KEYS(ts, pair)` -//! (`fx_1m`). Avoid replaying stale shard files after newer data sharing the same upsert keys -//! has been ingested. -//! - **Resource scaling:** Threads, open sockets, and read-buffer memory scale linearly with -//! shard count (`shard_count * buffer_bytes`). - -use std::error::Error; -use std::fmt; -use std::fs::{self, File}; -use std::io::{self, Read, Write}; -use std::net::{Shutdown, SocketAddr, TcpStream, ToSocketAddrs}; -use std::path::{Path, PathBuf}; -use std::sync::Mutex; -use std::thread; -use std::time::Duration; - -use crate::run_curate_bars_1m::is_final_shard_file_name_for_table; - -/// Default per-shard streaming read buffer size (64 KiB). -pub const DEFAULT_ILP_SEND_BUFFER_BYTES: usize = 64 * 1024; - -/// Default TCP connect timeout per shard socket (10 seconds). -pub const DEFAULT_ILP_TCP_CONNECT_TIMEOUT: Duration = Duration::from_secs(10); - -/// Default TCP write timeout per shard socket (30 seconds). -pub const DEFAULT_ILP_TCP_WRITE_TIMEOUT: Duration = Duration::from_secs(30); - -/// A discovered, validated published ILP shard file (`.shard-.ilp`). -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct IlpShardFile { - pub shard: usize, - pub path: PathBuf, -} - -/// Streaming options for [`send_ilp_shard_files`]. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct IlpSendOptions { - /// Fixed-size read buffer allocated per shard worker (must be `> 0`). - pub buffer_bytes: usize, -} - -impl Default for IlpSendOptions { - fn default() -> Self { - Self { - buffer_bytes: DEFAULT_ILP_SEND_BUFFER_BYTES, - } - } -} - -/// Socket options for [`tcp_ilp_connector`]. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct IlpTcpOptions { - /// Connect timeout applied to each shard socket (must be `> Duration::ZERO`). - pub connect_timeout: Duration, - /// Write timeout applied to each shard socket (must be `> Duration::ZERO`). - pub write_timeout: Duration, -} - -impl Default for IlpTcpOptions { - fn default() -> Self { - Self { - connect_timeout: DEFAULT_ILP_TCP_CONNECT_TIMEOUT, - write_timeout: DEFAULT_ILP_TCP_WRITE_TIMEOUT, - } - } -} - -/// Per-shard delivery summary recorded in [`IlpSendReport`]. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct IlpShardSendReport { - pub shard: usize, - pub path: PathBuf, - pub bytes_sent: u64, -} - -/// Delivery summary returned by [`send_ilp_shard_files`] (and attached as a partial report on -/// [`IlpSendError::ShardIo`]). -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct IlpSendReport { - pub shards: Vec, - pub total_shards: usize, - pub total_bytes_sent: u64, -} - -/// Operation stage in which a per-shard I/O failure occurred. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum IlpSendOp { - SpawnWorker, - OpenFile, - Connect, - Read, - Write, - Flush, -} - -impl fmt::Display for IlpSendOp { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match *self { - Self::SpawnWorker => f.write_str("spawn_worker"), - Self::OpenFile => f.write_str("open_file"), - Self::Connect => f.write_str("connect"), - Self::Read => f.write_str("read"), - Self::Write => f.write_str("write"), - Self::Flush => f.write_str("flush"), - } - } -} - -/// Typed errors returned by [`discover_ilp_shard_files`], [`send_ilp_shard_files`], and -/// [`tcp_ilp_connector`]. -#[derive(Debug)] -pub enum IlpSendError { - /// Shard prefix was empty or contained characters outside `[A-Za-z0-9_-]`. - InvalidPrefix { prefix: String }, - /// Target directory exists but is not a directory. - InvalidDirectory { path: PathBuf, detail: String }, - /// Failed to stat or read the shard directory. - ReadDir { path: PathBuf, source: io::Error }, - /// No `.shard-.ilp` files matched in `dir`. - NoShardFiles { dir: PathBuf, prefix: String }, - /// A matching shard file's numeric suffix overflowed `usize`. - ShardIndexOverflow { path: PathBuf, digits: String }, - /// A matching entry was not a regular file (for example, a directory or symlink). - NotRegularFile { path: PathBuf, detail: String }, - /// Two matching files resolved to the same numeric shard index (e.g. `shard-0` and `shard-00`). - DuplicateShardIndex { - shard: usize, - first: PathBuf, - second: PathBuf, - }, - /// Discovered shard indices did not form a contiguous `0..n` sequence. - MissingShardIndex { - expected: usize, - found: usize, - path: PathBuf, - }, - /// `IlpSendOptions::buffer_bytes` was zero. - ZeroBufferBytes, - /// TCP target address was empty, malformed, or could not be resolved. - InvalidAddress { addr: String, detail: String }, - /// A TCP timeout option was zero. - InvalidTimeout { field: &'static str }, - /// One or more shards failed during open, connect, read, write, or flush. - /// - /// `op`, `shard`, `path`, and `source` identify the lowest-index failing shard; - /// `partial_report` records `bytes_sent` for every shard after all workers finish. - ShardIo { - op: IlpSendOp, - shard: usize, - path: PathBuf, - source: io::Error, - partial_report: IlpSendReport, - }, -} - -impl IlpSendError { - /// Returns the partial delivery report when this error is [`IlpSendError::ShardIo`]. - pub fn partial_report(&self) -> Option<&IlpSendReport> { - match self { - Self::ShardIo { partial_report, .. } => Some(partial_report), - _ => None, - } - } -} - -impl fmt::Display for IlpSendError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::InvalidPrefix { prefix } => write!( - f, - "invalid ILP shard prefix {prefix:?}: must be non-empty ASCII [A-Za-z0-9_-]" - ), - Self::InvalidDirectory { path, detail } => { - write!(f, "invalid ILP shard directory '{}': {detail}", path.display()) - } - Self::ReadDir { path, source } => { - write!(f, "failed to read ILP shard directory '{}': {source}", path.display()) - } - Self::NoShardFiles { dir, prefix } => write!( - f, - "no ILP shard files matching '{prefix}.shard-.ilp' in '{}'", - dir.display() - ), - Self::ShardIndexOverflow { path, digits } => write!( - f, - "ILP shard index '{digits}' overflows usize in '{}'", - path.display() - ), - Self::NotRegularFile { path, detail } => write!( - f, - "ILP shard path '{}' is not a regular file: {detail}", - path.display() - ), - Self::DuplicateShardIndex { - shard, - first, - second, - } => write!( - f, - "duplicate ILP shard index {shard}: '{}' and '{}'", - first.display(), - second.display() - ), - Self::MissingShardIndex { - expected, - found, - path, - } => write!( - f, - "missing ILP shard index {expected}: next shard is {found} ('{}')", - path.display() - ), - Self::ZeroBufferBytes => write!(f, "ILP send buffer_bytes must be > 0"), - Self::InvalidAddress { addr, detail } => { - write!(f, "invalid ILP TCP address {addr:?}: {detail}") - } - Self::InvalidTimeout { field } => { - write!(f, "ILP TCP {field} must be > 0") - } - Self::ShardIo { - op, - shard, - path, - source, - partial_report, - } => write!( - f, - "ILP shard {shard} ('{}') failed during {op} ({source}; total_bytes_sent={})", - path.display(), - partial_report.total_bytes_sent - ), - } - } -} - -impl Error for IlpSendError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::ReadDir { source, .. } | Self::ShardIo { source, .. } => Some(source), - _ => None, - } - } -} - -/// Validates that `prefix` is non-empty and consists solely of ASCII letters, digits, `_`, or `-`. -fn validate_prefix(prefix: &str) -> Result<(), IlpSendError> { - if prefix.is_empty() - || !prefix - .bytes() - .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-') - { - return Err(IlpSendError::InvalidPrefix { - prefix: prefix.to_string(), - }); - } - Ok(()) -} - -/// Discovers published `.shard-.ilp` files in a completed output directory `dir`. -/// -/// Files are returned sorted by ascending numeric shard index `0..n`. Fails closed on: -/// - blank or invalid `prefix` (must match `[A-Za-z0-9_-]+`), -/// - missing or non-directory `dir`, -/// - zero matching files, -/// - any matching entry that is not a regular file (including symlinks and directories), -/// - numeric shard suffix overflowing `usize`, -/// - duplicate numeric shard indices (e.g. `shard-0` and `shard-00`), or -/// - any gap in `0..n`. -pub fn discover_ilp_shard_files( - dir: &Path, - prefix: &str, -) -> Result, IlpSendError> { - validate_prefix(prefix)?; - - let dir_meta = fs::metadata(dir).map_err(|source| IlpSendError::ReadDir { - path: dir.to_path_buf(), - source, - })?; - if !dir_meta.is_dir() { - return Err(IlpSendError::InvalidDirectory { - path: dir.to_path_buf(), - detail: "path exists and is not a directory".to_string(), - }); - } - - let entries = fs::read_dir(dir).map_err(|source| IlpSendError::ReadDir { - path: dir.to_path_buf(), - source, - })?; - - let mut discovered: Vec = Vec::new(); - for entry in entries { - let entry = entry.map_err(|source| IlpSendError::ReadDir { - path: dir.to_path_buf(), - source, - })?; - let file_name = entry.file_name(); - if !is_final_shard_file_name_for_table(prefix, &file_name) { - continue; - } - - let path = entry.path(); - let meta = fs::symlink_metadata(&path).map_err(|source| IlpSendError::ReadDir { - path: path.clone(), - source, - })?; - let file_type = meta.file_type(); - if file_type.is_symlink() { - return Err(IlpSendError::NotRegularFile { - path, - detail: "entry is a symlink".to_string(), - }); - } - if !file_type.is_file() { - let detail = if file_type.is_dir() { - "entry is a directory" - } else { - "entry is not a regular file" - }; - return Err(IlpSendError::NotRegularFile { - path, - detail: detail.to_string(), - }); - } - - let name_str = file_name - .to_str() - .expect("is_final_shard_file_name_for_table guarantees valid UTF-8"); - let digits = name_str - .strip_prefix(prefix) - .and_then(|s| s.strip_prefix(".shard-")) - .and_then(|s| s.strip_suffix(".ilp")) - .expect("is_final_shard_file_name_for_table guarantees shard filename shape"); - - let shard = digits - .parse::() - .map_err(|_| IlpSendError::ShardIndexOverflow { - path: path.clone(), - digits: digits.to_string(), - })?; - - discovered.push(IlpShardFile { shard, path }); - } - - if discovered.is_empty() { - return Err(IlpSendError::NoShardFiles { - dir: dir.to_path_buf(), - prefix: prefix.to_string(), - }); - } - - discovered.sort_by(|a, b| a.shard.cmp(&b.shard).then_with(|| a.path.cmp(&b.path))); - - for pair in discovered.windows(2) { - if pair[0].shard == pair[1].shard { - return Err(IlpSendError::DuplicateShardIndex { - shard: pair[0].shard, - first: pair[0].path.clone(), - second: pair[1].path.clone(), - }); - } - } - - for (expected, item) in discovered.iter().enumerate() { - if item.shard != expected { - return Err(IlpSendError::MissingShardIndex { - expected, - found: item.shard, - path: item.path.clone(), - }); - } - } - - Ok(discovered) -} - -/// Streams each shard file in `files` verbatim to its own sink opened via `connector`, running one -/// scoped worker thread per shard. -/// -/// Guarantees: -/// - Rejects `options.buffer_bytes == 0` before any file open or `connector` call. -/// - Opens each shard file before calling `connector(file.shard)`. -/// - Uses one reusable fixed-size read buffer per worker; never loads a whole file into memory and -/// never splits or re-encodes bytes. -/// - Calls `flush()` exactly once at EOF on every opened sink, including zero-length shard files. -/// - Joins every worker before returning; fails closed with [`IlpSendError::ShardIo`] carrying -/// the failing shard index, path, operation, `io::Error`, and full per-shard partial report if -/// any shard errors. -pub fn send_ilp_shard_files( - files: &[IlpShardFile], - connector: C, - options: IlpSendOptions, -) -> Result -where - W: Write + Send, - C: Fn(usize) -> io::Result + Sync, -{ - if options.buffer_bytes == 0 { - return Err(IlpSendError::ZeroBufferBytes); - } - - if files.is_empty() { - return Ok(IlpSendReport { - shards: Vec::new(), - total_shards: 0, - total_bytes_sent: 0, - }); - } - - let connector_ref = &connector; - let buffer_bytes = options.buffer_bytes; - - let outcomes: Vec = thread::scope(|scope| { - enum WorkerSlot<'scope> { - Running(thread::ScopedJoinHandle<'scope, ShardWorkerOutcome>), - SpawnFailed(io::Error), - } - - let mut slots = Vec::with_capacity(files.len()); - for shard_file in files { - let spawned = thread::Builder::new() - .name(format!("ilp-send-shard-{}", shard_file.shard)) - .spawn_scoped(scope, move || { - send_single_shard(shard_file, connector_ref, buffer_bytes) - }); - match spawned { - Ok(handle) => slots.push(WorkerSlot::Running(handle)), - Err(err) => slots.push(WorkerSlot::SpawnFailed(err)), - } - } - - let mut results = Vec::with_capacity(slots.len()); - let mut first_panic = None; - for slot in slots { - match slot { - WorkerSlot::Running(handle) => match handle.join() { - Ok(outcome) => results.push(outcome), - Err(payload) => { - if first_panic.is_none() { - first_panic = Some(payload); - } - } - }, - WorkerSlot::SpawnFailed(err) => results.push(ShardWorkerOutcome { - bytes_sent: 0, - failure: Some((IlpSendOp::SpawnWorker, err)), - }), - } - } - if let Some(payload) = first_panic { - std::panic::resume_unwind(payload); - } - results - }); - - let mut ordered: Vec<(&IlpShardFile, ShardWorkerOutcome)> = - files.iter().zip(outcomes).collect(); - ordered.sort_by(|(a, _), (b, _)| a.shard.cmp(&b.shard).then_with(|| a.path.cmp(&b.path))); - - let mut shard_reports = Vec::with_capacity(ordered.len()); - let mut total_bytes_sent: u64 = 0; - let mut first_failure: Option<(IlpSendOp, usize, PathBuf, io::Error)> = None; - - for (shard_file, outcome) in ordered { - total_bytes_sent = total_bytes_sent.saturating_add(outcome.bytes_sent); - shard_reports.push(IlpShardSendReport { - shard: shard_file.shard, - path: shard_file.path.clone(), - bytes_sent: outcome.bytes_sent, - }); - if first_failure.is_none() { - if let Some((op, source)) = outcome.failure { - first_failure = Some((op, shard_file.shard, shard_file.path.clone(), source)); - } - } - } - - let report = IlpSendReport { - total_shards: shard_reports.len(), - total_bytes_sent, - shards: shard_reports, - }; - - if let Some((op, shard, path, source)) = first_failure { - return Err(IlpSendError::ShardIo { - op, - shard, - path, - source, - partial_report: report, - }); - } - - Ok(report) -} - -struct ShardWorkerOutcome { - bytes_sent: u64, - failure: Option<(IlpSendOp, io::Error)>, -} - -fn send_single_shard( - shard_file: &IlpShardFile, - connector: &C, - buffer_bytes: usize, -) -> ShardWorkerOutcome -where - W: Write, - C: Fn(usize) -> io::Result, -{ - let mut file = match File::open(&shard_file.path) { - Ok(file) => file, - Err(err) => { - return ShardWorkerOutcome { - bytes_sent: 0, - failure: Some((IlpSendOp::OpenFile, err)), - }; - } - }; - - let mut sink = match connector(shard_file.shard) { - Ok(sink) => sink, - Err(err) => { - return ShardWorkerOutcome { - bytes_sent: 0, - failure: Some((IlpSendOp::Connect, err)), - }; - } - }; - - let mut buf = vec![0u8; buffer_bytes]; - let mut bytes_sent: u64 = 0; - - loop { - let read_len = match file.read(&mut buf) { - Ok(0) => break, - Ok(n) => n, - Err(err) if err.kind() == io::ErrorKind::Interrupted => continue, - Err(err) => { - return ShardWorkerOutcome { - bytes_sent, - failure: Some((IlpSendOp::Read, err)), - }; - } - }; - - let mut offset = 0usize; - while offset < read_len { - match sink.write(&buf[offset..read_len]) { - Ok(0) => { - return ShardWorkerOutcome { - bytes_sent, - failure: Some(( - IlpSendOp::Write, - io::Error::new( - io::ErrorKind::WriteZero, - "sink returned Ok(0) on non-empty write", - ), - )), - }; - } - Ok(written) => { - offset += written; - bytes_sent += written as u64; - } - Err(err) if err.kind() == io::ErrorKind::Interrupted => continue, - Err(err) => { - return ShardWorkerOutcome { - bytes_sent, - failure: Some((IlpSendOp::Write, err)), - }; - } - } - } - } - - loop { - match sink.flush() { - Ok(()) => break, - Err(err) if err.kind() == io::ErrorKind::Interrupted => continue, - Err(err) => { - return ShardWorkerOutcome { - bytes_sent, - failure: Some((IlpSendOp::Flush, err)), - }; - } - } - } - - ShardWorkerOutcome { - bytes_sent, - failure: None, - } -} - -/// [`TcpStream`] wrapper whose [`Write::flush`] flushes the stream and performs a write-side -/// half-close (`shutdown(Shutdown::Write)`) so the peer observes clean EOF. -#[derive(Debug)] -pub struct IlpTcpSink { - stream: TcpStream, -} - -impl IlpTcpSink { - /// Wraps a connected [`TcpStream`]. - pub fn new(stream: TcpStream) -> Self { - Self { stream } - } - - /// Borrows the underlying [`TcpStream`]. - pub fn inner(&self) -> &TcpStream { - &self.stream - } - - /// Unwraps and returns the underlying [`TcpStream`]. - pub fn into_inner(self) -> TcpStream { - self.stream - } -} - -impl Write for IlpTcpSink { - fn write(&mut self, buf: &[u8]) -> io::Result { - self.stream.write(buf) - } - - fn flush(&mut self) -> io::Result<()> { - self.stream.flush()?; - self.stream.shutdown(Shutdown::Write) - } -} - -/// Validates and resolves `addr` into one or more [`SocketAddr`]s without performing DNS lookups -/// on syntactically malformed inputs. -fn resolve_tcp_addr(addr: &str) -> Result, IlpSendError> { - if addr.is_empty() || addr.trim() != addr { - return Err(IlpSendError::InvalidAddress { - addr: addr.to_string(), - detail: "address must be non-empty without surrounding whitespace".to_string(), - }); - } - - if let Ok(sock_addr) = addr.parse::() { - return Ok(vec![sock_addr]); - } - - let Some((host, port_str)) = addr.rsplit_once(':') else { - return Err(IlpSendError::InvalidAddress { - addr: addr.to_string(), - detail: "expected 'host:port'".to_string(), - }); - }; - - if host.is_empty() - || host - .bytes() - .any(|b| b.is_ascii_whitespace() || b.is_ascii_control()) - { - return Err(IlpSendError::InvalidAddress { - addr: addr.to_string(), - detail: "host component is empty or contains invalid characters".to_string(), - }); - } - - if port_str.is_empty() || port_str.parse::().is_err() { - return Err(IlpSendError::InvalidAddress { - addr: addr.to_string(), - detail: "port must be a valid u16".to_string(), - }); - } - - let resolved: Vec = addr - .to_socket_addrs() - .map_err(|err| IlpSendError::InvalidAddress { - addr: addr.to_string(), - detail: format!("failed to resolve address: {err}"), - })? - .collect(); - - if resolved.is_empty() { - return Err(IlpSendError::InvalidAddress { - addr: addr.to_string(), - detail: "address resolved to zero socket addresses".to_string(), - }); - } - - Ok(resolved) -} - -fn connect_tcp_sink( - sock_addr: &SocketAddr, - connect_timeout: Duration, - write_timeout: Duration, -) -> io::Result { - let stream = TcpStream::connect_timeout(sock_addr, connect_timeout)?; - stream.set_nodelay(true)?; - stream.set_write_timeout(Some(write_timeout))?; - Ok(IlpTcpSink::new(stream)) -} - -fn tcp_ilp_connector_for_addrs( - resolved: Vec, - options: IlpTcpOptions, -) -> Result io::Result, IlpSendError> { - if options.connect_timeout.is_zero() { - return Err(IlpSendError::InvalidTimeout { - field: "connect_timeout", - }); - } - if options.write_timeout.is_zero() { - return Err(IlpSendError::InvalidTimeout { - field: "write_timeout", - }); - } - - let connect_timeout = options.connect_timeout; - let write_timeout = options.write_timeout; - // Pin one resolved endpoint for the lifetime of this connector so shards can never silently - // split a single load across two different QuestDB instances if a hostname resolves to - // multiple addresses. - let pinned_addr: Mutex> = Mutex::new(None); - - Ok(move |_shard: usize| -> io::Result { - let already_pinned = { - let guard = pinned_addr - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()); - *guard - }; - - if let Some(sock_addr) = already_pinned { - return connect_tcp_sink(&sock_addr, connect_timeout, write_timeout); - } - - let mut guard = pinned_addr - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()); - if let Some(sock_addr) = *guard { - drop(guard); - return connect_tcp_sink(&sock_addr, connect_timeout, write_timeout); - } - - let mut last_err: Option = None; - for sock_addr in &resolved { - match TcpStream::connect_timeout(sock_addr, connect_timeout) { - Ok(stream) => { - *guard = Some(*sock_addr); - drop(guard); - stream.set_nodelay(true)?; - stream.set_write_timeout(Some(write_timeout))?; - return Ok(IlpTcpSink::new(stream)); - } - Err(err) => { - last_err = Some(err); - } - } - } - Err(last_err.unwrap_or_else(|| { - io::Error::new( - io::ErrorKind::AddrNotAvailable, - "no resolved socket addresses available", - ) - })) - }) -} - -/// Builds a thread-safe TCP connector for [`send_ilp_shard_files`]. -/// -/// Validates `options` and resolves `addr` once before returning the connector closure so invalid -/// addresses fail closed before any connection attempt. Pins a single resolved [`SocketAddr`] for -/// all shards so a load can never split across multiple backend instances. Each shard invocation -/// opens a fresh [`TcpStream`] with `connect_timeout`, `set_nodelay(true)`, and `write_timeout`, -/// wrapped in [`IlpTcpSink`] so the sender's final `flush()` half-closes the write side -/// (`Shutdown::Write`). -pub fn tcp_ilp_connector( - addr: &str, - options: IlpTcpOptions, -) -> Result io::Result, IlpSendError> { - if options.connect_timeout.is_zero() { - return Err(IlpSendError::InvalidTimeout { - field: "connect_timeout", - }); - } - if options.write_timeout.is_zero() { - return Err(IlpSendError::InvalidTimeout { - field: "write_timeout", - }); - } - - let resolved = resolve_tcp_addr(addr)?; - tcp_ilp_connector_for_addrs(resolved, options) -} - -/// Arguments for the `send-ilp` CLI subcommand and [`run_send_ilp`]. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct SendIlpArgs { - pub dir: PathBuf, - pub prefix: String, - pub addr: String, -} - -/// Discovers published `.shard-.ilp` files in `args.dir`, validates and resolves -/// `args.addr` via [`tcp_ilp_connector`] with [`IlpTcpOptions::default()`], and streams all shards -/// via [`send_ilp_shard_files`] with [`IlpSendOptions::default()`]. -/// -/// Discovery runs before address resolution or any socket connection so a bad directory or -/// incomplete shard set never opens a socket. -pub fn run_send_ilp(args: &SendIlpArgs) -> Result { - let files = discover_ilp_shard_files(&args.dir, &args.prefix)?; - let connector = tcp_ilp_connector(&args.addr, IlpTcpOptions::default())?; - send_ilp_shard_files(&files, connector, IlpSendOptions::default()) -} - -/// Formats [`IlpSendReport`] into a deterministic machine-readable `key=value` summary in the -/// style of the crate's `format_curate_*_report` helpers. -pub fn format_ilp_send_report(report: &IlpSendReport) -> String { - let per_shard = if report.shards.is_empty() { - "none".to_string() - } else { - report - .shards - .iter() - .map(|entry| format!("{:02}={}", entry.shard, entry.bytes_sent)) - .collect::>() - .join(",") - }; - - format!( - "curate-etl ilp-send\n\ - \x20 ilp_send: shards={} total_bytes_sent={} per_shard_bytes={per_shard}", - report.total_shards, report.total_bytes_sent, - ) -} - -#[cfg(test)] -#[path = "ilp_send_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/ilp_send_tests.rs b/tools/curate-etl/src/ilp_send_tests.rs deleted file mode 100644 index 6d551fd3..00000000 --- a/tools/curate-etl/src/ilp_send_tests.rs +++ /dev/null @@ -1,1807 +0,0 @@ -use std::collections::{BTreeMap, HashSet}; -use std::fs::{self, File}; -use std::io::{self, Read, Write}; -use std::net::{SocketAddr, TcpListener, TcpStream}; -use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::{Arc, Condvar, Mutex}; -use std::thread; -use std::time::{Duration, Instant}; - -use super::*; -use crate::bars_1m::{Bar1mRow, IntradaySession, BARS_1M_SOURCE_EOD}; -use crate::ilp::{shard_for_listing_id, IlpShardedWriter, IlpWriterOptions}; -use crate::run_curate_bars_1m::tests::TempDirGuard; - -fn write_bytes(path: &Path, bytes: &[u8]) { - fs::write(path, bytes).expect("write test shard file"); -} - -#[test] -fn discovers_exact_prefix_in_numeric_order() { - let dir = TempDirGuard::new("ilp-send-discover"); - write_bytes(&dir.path().join("bars_1m.shard-01.ilp"), b"shard1"); - write_bytes(&dir.path().join("bars_1m.shard-00.ilp"), b"shard0"); - write_bytes(&dir.path().join("bars_1m_qm.shard-00.ilp"), b"qm0"); - write_bytes(&dir.path().join("fx_1m.shard-00.ilp"), b"fx0"); - write_bytes(&dir.path().join("unrelated.txt"), b"ignore"); - write_bytes(&dir.path().join(".bars_1m.shard-00.123.tmp"), b"staging"); - - let bars = discover_ilp_shard_files(dir.path(), "bars_1m").expect("discover bars_1m"); - assert_eq!( - bars, - vec![ - IlpShardFile { - shard: 0, - path: dir.path().join("bars_1m.shard-00.ilp"), - }, - IlpShardFile { - shard: 1, - path: dir.path().join("bars_1m.shard-01.ilp"), - }, - ] - ); - - let qm = discover_ilp_shard_files(dir.path(), "bars_1m_qm").expect("discover bars_1m_qm"); - assert_eq!(qm.len(), 1); - assert_eq!(qm[0].shard, 0); - assert_eq!(qm[0].path, dir.path().join("bars_1m_qm.shard-00.ilp")); - - let fx = discover_ilp_shard_files(dir.path(), "fx_1m").expect("discover fx_1m"); - assert_eq!(fx.len(), 1); - assert_eq!(fx[0].shard, 0); - assert_eq!(fx[0].path, dir.path().join("fx_1m.shard-00.ilp")); - - // Verify numeric ordering (not lexicographic) across 0..=10. - let multi = TempDirGuard::new("ilp-send-discover-numeric"); - for idx in [10usize, 2, 0, 9, 1, 8, 3, 7, 4, 6, 5] { - write_bytes(&multi.path().join(format!("bars_1m.shard-{idx}.ilp")), b"x"); - } - let ordered = discover_ilp_shard_files(multi.path(), "bars_1m").expect("numeric order"); - let indices: Vec = ordered.iter().map(|f| f.shard).collect(); - assert_eq!(indices, (0..=10).collect::>()); -} - -#[test] -fn rejects_invalid_shard_sets() { - // 1. Blank and invalid prefixes. - let empty_dir = TempDirGuard::new("ilp-send-empty"); - for bad in ["", " ", "bars.1m", "bars/1m", "bars 1m"] { - let err = discover_ilp_shard_files(empty_dir.path(), bad).unwrap_err(); - assert!( - matches!(err, IlpSendError::InvalidPrefix { .. }), - "expected InvalidPrefix for {bad:?}, got {err:?}" - ); - } - - // 2. Non-directory path. - let file_path = empty_dir.path().join("not_a_dir"); - write_bytes(&file_path, b"x"); - let err = discover_ilp_shard_files(&file_path, "bars_1m").unwrap_err(); - assert!( - matches!(err, IlpSendError::InvalidDirectory { .. }), - "expected InvalidDirectory, got {err:?}" - ); - - // 3. No matching files. - let err = discover_ilp_shard_files(empty_dir.path(), "bars_1m").unwrap_err(); - assert!( - matches!(err, IlpSendError::NoShardFiles { .. }), - "expected NoShardFiles, got {err:?}" - ); - - // 4. Gap in indices (00, 02). - let gap_dir = TempDirGuard::new("ilp-send-gap"); - write_bytes(&gap_dir.path().join("bars_1m.shard-00.ilp"), b"a"); - write_bytes(&gap_dir.path().join("bars_1m.shard-02.ilp"), b"c"); - let err = discover_ilp_shard_files(gap_dir.path(), "bars_1m").unwrap_err(); - assert!( - matches!( - err, - IlpSendError::MissingShardIndex { - expected: 1, - found: 2, - .. - } - ), - "expected MissingShardIndex(1, 2), got {err:?}" - ); - - // 5. Missing shard 0 (01, 02). - let no_zero_dir = TempDirGuard::new("ilp-send-no-zero"); - write_bytes(&no_zero_dir.path().join("bars_1m.shard-01.ilp"), b"b"); - write_bytes(&no_zero_dir.path().join("bars_1m.shard-02.ilp"), b"c"); - let err = discover_ilp_shard_files(no_zero_dir.path(), "bars_1m").unwrap_err(); - assert!( - matches!( - err, - IlpSendError::MissingShardIndex { - expected: 0, - found: 1, - .. - } - ), - "expected MissingShardIndex(0, 1), got {err:?}" - ); - - // 6. Duplicate numeric index (shard-0 and shard-00). - let dup_dir = TempDirGuard::new("ilp-send-dup"); - write_bytes(&dup_dir.path().join("bars_1m.shard-0.ilp"), b"a"); - write_bytes(&dup_dir.path().join("bars_1m.shard-00.ilp"), b"b"); - let err = discover_ilp_shard_files(dup_dir.path(), "bars_1m").unwrap_err(); - assert!( - matches!(err, IlpSendError::DuplicateShardIndex { shard: 0, .. }), - "expected DuplicateShardIndex(0), got {err:?}" - ); - - // 7. Numeric suffix overflow. - let overflow_dir = TempDirGuard::new("ilp-send-overflow"); - write_bytes( - &overflow_dir - .path() - .join("bars_1m.shard-999999999999999999999999999999999999999.ilp"), - b"x", - ); - let err = discover_ilp_shard_files(overflow_dir.path(), "bars_1m").unwrap_err(); - assert!( - matches!(err, IlpSendError::ShardIndexOverflow { .. }), - "expected ShardIndexOverflow, got {err:?}" - ); - - // 8. Directory named like a shard file. - let dir_shard = TempDirGuard::new("ilp-send-dir-shard"); - fs::create_dir(dir_shard.path().join("bars_1m.shard-00.ilp")).expect("create shard dir"); - let err = discover_ilp_shard_files(dir_shard.path(), "bars_1m").unwrap_err(); - assert!( - matches!(err, IlpSendError::NotRegularFile { .. }), - "expected NotRegularFile for directory, got {err:?}" - ); - - // 9. Symlink named like a shard file. - #[cfg(unix)] - { - let sym_dir = TempDirGuard::new("ilp-send-sym-shard"); - let target = sym_dir.path().join("real.ilp"); - write_bytes(&target, b"payload"); - std::os::unix::fs::symlink(&target, sym_dir.path().join("bars_1m.shard-00.ilp")) - .expect("create symlink"); - let err = discover_ilp_shard_files(sym_dir.path(), "bars_1m").unwrap_err(); - assert!( - matches!(err, IlpSendError::NotRegularFile { .. }), - "expected NotRegularFile for symlink, got {err:?}" - ); - } -} - -struct RecordingSinkState { - bytes: Vec, - flushes: usize, -} - -struct RecordingSink { - state: Arc>, -} - -impl Write for RecordingSink { - fn write(&mut self, buf: &[u8]) -> io::Result { - let mut guard = self.state.lock().expect("lock recording sink"); - guard.bytes.extend_from_slice(buf); - Ok(buf.len()) - } - - fn flush(&mut self) -> io::Result<()> { - let mut guard = self.state.lock().expect("lock recording sink"); - guard.flushes += 1; - Ok(()) - } -} - -#[test] -fn streams_writer_bytes_and_flushes_every_shard() { - let dir = TempDirGuard::new("ilp-send-fidelity"); - let shard_count = 3usize; - - // Pick two listing_ids that hash to shards 0 and 2 so shard 1 stays zero-length. - let id_shard_0 = (1..10_000i32) - .find(|&id| shard_for_listing_id(id, shard_count) == 0) - .expect("find listing_id for shard 0"); - let id_shard_2 = (1..10_000i32) - .find(|&id| shard_for_listing_id(id, shard_count) == 2) - .expect("find listing_id for shard 2"); - - // Construct a finite positive f64 whose IEEE-754 LE bytes include 0x0A ('\n'). - let close_with_lf = f64::from_le_bytes([0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x59, 0x40]); - assert!(close_with_lf.is_finite() && close_with_lf > 0.0); - assert!(close_with_lf.to_le_bytes().contains(&0x0A)); - - let shard_paths: Vec = (0..shard_count) - .map(|idx| dir.path().join(format!("bars_1m.shard-{idx:02}.ilp"))) - .collect(); - let sinks: Vec = shard_paths - .iter() - .map(|p| File::create(p).expect("create shard file")) - .collect(); - - let mut writer = - IlpShardedWriter::new(sinks, IlpWriterOptions::default()).expect("create ILP writer"); - let rows = [ - ( - Bar1mRow { - key: id_shard_0, - ts: 1_700_000_000_000_000, - session_date: 19_675, - open: 100.0, - high: 101.5, - low: 99.5, - close: close_with_lf, - volume: 12_345.0, - session: IntradaySession::Rth, - source: BARS_1M_SOURCE_EOD, - }, - 1_700_000_060_000_000i64, - ), - ( - Bar1mRow { - key: id_shard_0, - ts: 1_700_000_060_000_000, - session_date: 19_675, - open: close_with_lf, - high: 102.0, - low: 99.0, - close: 101.25, - volume: 6_789.0, - session: IntradaySession::Rth, - source: BARS_1M_SOURCE_EOD, - }, - 1_700_000_120_000_000i64, - ), - ( - Bar1mRow { - key: id_shard_2, - ts: 1_700_000_000_000_000, - session_date: 19_675, - open: 42.0, - high: 43.0, - low: 41.0, - close: close_with_lf, - volume: 999.0, - session: IntradaySession::Pre, - source: BARS_1M_SOURCE_EOD, - }, - 1_700_000_060_000_000i64, - ), - ]; - for (row, known_at) in &rows { - writer.write_bar_1m(row, *known_at).expect("write bar_1m"); - } - writer.finish().expect("finish ILP writer"); - - let expected_bytes: Vec> = shard_paths - .iter() - .map(|p| fs::read(p).expect("read written shard")) - .collect(); - assert!(!expected_bytes[0].is_empty()); - assert!(expected_bytes[1].is_empty(), "shard 1 must be zero-length"); - assert!(!expected_bytes[2].is_empty()); - assert!(expected_bytes[0].windows(8).any(|w| w == close_with_lf.to_le_bytes())); - - let files = discover_ilp_shard_files(dir.path(), "bars_1m").expect("discover shards"); - assert_eq!(files.len(), shard_count); - - // Bounded rendezvous to verify all 3 shard workers run concurrently. - let rendezvous = Arc::new((Mutex::new(0usize), Condvar::new())); - let connect_counts = Arc::new(Mutex::new(BTreeMap::::new())); - let recorded: Arc>>> = Arc::new( - (0..shard_count) - .map(|_| { - Arc::new(Mutex::new(RecordingSinkState { - bytes: Vec::new(), - flushes: 0, - })) - }) - .collect(), - ); - - let report = send_ilp_shard_files( - &files, - |shard| { - { - let mut counts = connect_counts.lock().expect("lock connect_counts"); - *counts.entry(shard).or_insert(0) += 1; - } - { - let (lock, cvar) = &*rendezvous; - let mut arrived = lock.lock().expect("lock rendezvous"); - *arrived += 1; - if *arrived == shard_count { - cvar.notify_all(); - } else { - let (guard, timeout) = cvar - .wait_timeout_while(arrived, Duration::from_secs(2), |n| *n < shard_count) - .expect("wait rendezvous"); - assert!( - !timeout.timed_out() && *guard == shard_count, - "expected all {shard_count} shard workers to overlap concurrently" - ); - } - } - Ok(RecordingSink { - state: Arc::clone(&recorded[shard]), - }) - }, - IlpSendOptions { buffer_bytes: 7 }, - ) - .expect("send shards"); - - // Verify connector called once per shard. - let counts = connect_counts.lock().expect("lock connect_counts"); - assert_eq!(counts.len(), shard_count); - for shard in 0..shard_count { - assert_eq!(counts.get(&shard), Some(&1)); - } - - // Verify exact byte fidelity, single flush per shard (including empty shard 1), and report. - assert_eq!(report.total_shards, shard_count); - let expected_total: u64 = expected_bytes.iter().map(|b| b.len() as u64).sum(); - assert_eq!(report.total_bytes_sent, expected_total); - - for shard in 0..shard_count { - let state = recorded[shard].lock().expect("lock recorded"); - assert_eq!(state.bytes, expected_bytes[shard], "byte mismatch on shard {shard}"); - assert_eq!(state.flushes, 1, "expected exactly one flush on shard {shard}"); - assert_eq!(report.shards[shard].shard, shard); - assert_eq!(report.shards[shard].path, files[shard].path); - assert_eq!(report.shards[shard].bytes_sent, expected_bytes[shard].len() as u64); - } - - let formatted = format_ilp_send_report(&report); - assert_eq!( - formatted, - format!( - "curate-etl ilp-send\n ilp_send: shards=3 total_bytes_sent={expected_total} per_shard_bytes=00={},01=0,02={}", - expected_bytes[0].len(), - expected_bytes[2].len() - ) - ); -} - -#[test] -fn reports_connect_failure() { - let dir = TempDirGuard::new("ilp-send-connect-fail"); - let p0 = dir.path().join("bars_1m.shard-00.ilp"); - let p1 = dir.path().join("bars_1m.shard-01.ilp"); - let p2 = dir.path().join("bars_1m.shard-02.ilp"); - write_bytes(&p0, b"0123456789"); - write_bytes(&p1, b"will-not-connect"); - write_bytes(&p2, b"abcdef"); - - let files = discover_ilp_shard_files(dir.path(), "bars_1m").expect("discover"); - let err = send_ilp_shard_files( - &files, - |shard| { - if shard == 1 { - Err(io::Error::new( - io::ErrorKind::ConnectionRefused, - "refused shard 1", - )) - } else { - Ok(Vec::::new()) - } - }, - IlpSendOptions { buffer_bytes: 4 }, - ) - .unwrap_err(); - - match err { - IlpSendError::ShardIo { - op, - shard, - path, - source, - partial_report, - } => { - assert_eq!(op, IlpSendOp::Connect); - assert_eq!(shard, 1); - assert_eq!(path, p1); - assert_eq!(source.kind(), io::ErrorKind::ConnectionRefused); - assert_eq!(partial_report.total_shards, 3); - assert_eq!(partial_report.shards[0].bytes_sent, 10); - assert_eq!(partial_report.shards[1].bytes_sent, 0); - assert_eq!(partial_report.shards[2].bytes_sent, 6); - assert_eq!(partial_report.total_bytes_sent, 16); - } - other => panic!("expected ShardIo(Connect), got {other:?}"), - } -} - -struct PartialFailWriter { - step: usize, - written: Vec, -} - -impl Write for PartialFailWriter { - fn write(&mut self, buf: &[u8]) -> io::Result { - self.step += 1; - match self.step { - 1 => { - let take = buf.len().min(5); - self.written.extend_from_slice(&buf[..take]); - Ok(take) - } - 2 => Err(io::Error::new( - io::ErrorKind::Interrupted, - "transient interrupt", - )), - 3 => { - let take = buf.len().min(4); - self.written.extend_from_slice(&buf[..take]); - Ok(take) - } - _ => Err(io::Error::new( - io::ErrorKind::BrokenPipe, - "peer closed mid-write", - )), - } - } - - fn flush(&mut self) -> io::Result<()> { - Ok(()) - } -} - -struct WriteZeroSink; - -impl Write for WriteZeroSink { - fn write(&mut self, _buf: &[u8]) -> io::Result { - Ok(0) - } - - fn flush(&mut self) -> io::Result<()> { - Ok(()) - } -} - -#[test] -fn reports_partial_write_failure() { - let dir = TempDirGuard::new("ilp-send-write-fail"); - let p0 = dir.path().join("bars_1m.shard-00.ilp"); - let p1 = dir.path().join("bars_1m.shard-01.ilp"); - let p2 = dir.path().join("bars_1m.shard-02.ilp"); - write_bytes(&p0, b"shard0-payload"); - write_bytes(&p1, &[b'B'; 32]); - write_bytes(&p2, b"shard2"); - - let files = discover_ilp_shard_files(dir.path(), "bars_1m").expect("discover"); - let err = send_ilp_shard_files( - &files, - |shard| -> io::Result> { - if shard == 1 { - Ok(Box::new(PartialFailWriter { - step: 0, - written: Vec::new(), - })) - } else { - Ok(Box::new(Vec::::new())) - } - }, - IlpSendOptions { buffer_bytes: 16 }, - ) - .unwrap_err(); - - match err { - IlpSendError::ShardIo { - op, - shard, - path, - source, - partial_report, - } => { - assert_eq!(op, IlpSendOp::Write); - assert_eq!(shard, 1); - assert_eq!(path, p1); - assert_eq!(source.kind(), io::ErrorKind::BrokenPipe); - assert_eq!(partial_report.shards[0].bytes_sent, 14); - assert_eq!(partial_report.shards[1].bytes_sent, 9); - assert_eq!(partial_report.shards[2].bytes_sent, 6); - assert_eq!(partial_report.total_bytes_sent, 29); - } - other => panic!("expected ShardIo(Write), got {other:?}"), - } - - // Also verify Ok(0) on a non-empty slice surfaces as WriteZero. - let err_zero = send_ilp_shard_files( - &files[..1], - |_shard| Ok(WriteZeroSink), - IlpSendOptions { buffer_bytes: 8 }, - ) - .unwrap_err(); - match err_zero { - IlpSendError::ShardIo { - op, - shard, - source, - partial_report, - .. - } => { - assert_eq!(op, IlpSendOp::Write); - assert_eq!(shard, 0); - assert_eq!(source.kind(), io::ErrorKind::WriteZero); - assert_eq!(partial_report.shards[0].bytes_sent, 0); - } - other => panic!("expected ShardIo(WriteZero), got {other:?}"), - } -} - -struct FlushFailWriter { - written: Vec, -} - -impl Write for FlushFailWriter { - fn write(&mut self, buf: &[u8]) -> io::Result { - self.written.extend_from_slice(buf); - Ok(buf.len()) - } - - fn flush(&mut self) -> io::Result<()> { - Err(io::Error::new(io::ErrorKind::TimedOut, "flush timed out")) - } -} - -#[test] -fn reports_flush_failure() { - let dir = TempDirGuard::new("ilp-send-flush-fail"); - let p0 = dir.path().join("bars_1m.shard-00.ilp"); - let p1 = dir.path().join("bars_1m.shard-01.ilp"); - let p2 = dir.path().join("bars_1m.shard-02.ilp"); - write_bytes(&p0, b"12345"); - write_bytes(&p1, b"678"); - write_bytes(&p2, b"abcdefghij"); - - let files = discover_ilp_shard_files(dir.path(), "bars_1m").expect("discover"); - let err = send_ilp_shard_files( - &files, - |shard| -> io::Result> { - if shard == 2 { - Ok(Box::new(FlushFailWriter { - written: Vec::new(), - })) - } else { - Ok(Box::new(Vec::::new())) - } - }, - IlpSendOptions { buffer_bytes: 4 }, - ) - .unwrap_err(); - - match err { - IlpSendError::ShardIo { - op, - shard, - path, - source, - partial_report, - } => { - assert_eq!(op, IlpSendOp::Flush); - assert_eq!(shard, 2); - assert_eq!(path, p2); - assert_eq!(source.kind(), io::ErrorKind::TimedOut); - assert_eq!(partial_report.shards[0].bytes_sent, 5); - assert_eq!(partial_report.shards[1].bytes_sent, 3); - assert_eq!(partial_report.shards[2].bytes_sent, 10); - assert_eq!(partial_report.total_bytes_sent, 18); - } - other => panic!("expected ShardIo(Flush), got {other:?}"), - } -} - -#[test] -fn reports_removed_shard() { - let dir = TempDirGuard::new("ilp-send-removed"); - let p0 = dir.path().join("bars_1m.shard-00.ilp"); - let p1 = dir.path().join("bars_1m.shard-01.ilp"); - let p2 = dir.path().join("bars_1m.shard-02.ilp"); - write_bytes(&p0, b"hello"); - write_bytes(&p1, b"disappearing"); - write_bytes(&p2, b"world!"); - - let files = discover_ilp_shard_files(dir.path(), "bars_1m").expect("discover"); - fs::remove_file(&p1).expect("remove shard 1 after discovery"); - - let connected_shards = Arc::new(Mutex::new(HashSet::::new())); - let err = send_ilp_shard_files( - &files, - |shard| { - connected_shards.lock().expect("lock").insert(shard); - Ok(Vec::::new()) - }, - IlpSendOptions { buffer_bytes: 4 }, - ) - .unwrap_err(); - - match err { - IlpSendError::ShardIo { - op, - shard, - path, - source, - partial_report, - } => { - assert_eq!(op, IlpSendOp::OpenFile); - assert_eq!(shard, 1); - assert_eq!(path, p1); - assert_eq!(source.kind(), io::ErrorKind::NotFound); - assert_eq!(partial_report.shards[0].bytes_sent, 5); - assert_eq!(partial_report.shards[1].bytes_sent, 0); - assert_eq!(partial_report.shards[2].bytes_sent, 6); - assert_eq!(partial_report.total_bytes_sent, 11); - } - other => panic!("expected ShardIo(OpenFile), got {other:?}"), - } - - let connected = connected_shards.lock().expect("lock"); - assert!( - !connected.contains(&1), - "connector must not be called when opening shard file fails" - ); -} - -#[test] -fn rejects_zero_buffer_before_connect() { - let dir = TempDirGuard::new("ilp-send-zero-buf"); - write_bytes(&dir.path().join("bars_1m.shard-00.ilp"), b"abc"); - write_bytes(&dir.path().join("bars_1m.shard-01.ilp"), b"def"); - - let files = discover_ilp_shard_files(dir.path(), "bars_1m").expect("discover"); - let calls = AtomicUsize::new(0); - let err = send_ilp_shard_files( - &files, - |_shard| { - calls.fetch_add(1, Ordering::SeqCst); - Ok(Vec::::new()) - }, - IlpSendOptions { buffer_bytes: 0 }, - ) - .unwrap_err(); - - assert!(matches!(err, IlpSendError::ZeroBufferBytes)); - assert_eq!(calls.load(Ordering::SeqCst), 0); -} - -fn accept_with_deadline( - listener: &TcpListener, - deadline: Instant, - accepted_so_far: usize, - expected_total: usize, -) -> (TcpStream, SocketAddr) { - loop { - match listener.accept() { - Ok((stream, peer)) => { - stream - .set_nonblocking(false) - .expect("set accepted stream blocking"); - return (stream, peer); - } - Err(err) if err.kind() == io::ErrorKind::WouldBlock => { - if Instant::now() >= deadline { - panic!( - "timed out waiting for shard TCP connection: received {accepted_so_far} of {expected_total} connections" - ); - } - thread::sleep(Duration::from_millis(5)); - } - Err(err) => panic!( - "accept failed after receiving {accepted_so_far} of {expected_total} connections: {err}" - ), - } - } -} - -#[test] -fn tcp_sends_separate_shards_and_half_closes() { - let dir = TempDirGuard::new("ilp-send-tcp"); - let payload0: Vec = b"bars_1m,listing_id=1 open==\x10\x0A\x00\x00\x00\x00\x00\x59\x40 1700000000000000t\n".to_vec(); - let payload1: Vec = Vec::new(); - let payload2: Vec = b"bars_1m,listing_id=2 open==\x10\x01\x02\x03\x04\x05\x06\x07\x40 1700000060000000t\n".to_vec(); - - write_bytes(&dir.path().join("bars_1m.shard-00.ilp"), &payload0); - write_bytes(&dir.path().join("bars_1m.shard-01.ilp"), &payload1); - write_bytes(&dir.path().join("bars_1m.shard-02.ilp"), &payload2); - - let files = discover_ilp_shard_files(dir.path(), "bars_1m").expect("discover"); - let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback listener"); - let listen_addr = listener.local_addr().expect("local addr"); - listener - .set_nonblocking(true) - .expect("set loopback listener nonblocking"); - - let server_handle = thread::spawn(move || { - let deadline = Instant::now() + Duration::from_secs(3); - let mut reader_handles = Vec::with_capacity(3); - for accepted in 0..3 { - let (mut stream, peer) = accept_with_deadline(&listener, deadline, accepted, 3); - stream - .set_read_timeout(Some(Duration::from_secs(3))) - .expect("set server read timeout"); - reader_handles.push(thread::spawn(move || { - let mut buf = Vec::new(); - stream - .read_to_end(&mut buf) - .expect("read shard stream to EOF via half-close"); - (peer, buf) - })); - } - reader_handles - .into_iter() - .map(|h| h.join().expect("join reader thread")) - .collect::)>>() - }); - - let base_connector = tcp_ilp_connector( - &listen_addr.to_string(), - IlpTcpOptions { - connect_timeout: Duration::from_secs(2), - write_timeout: Duration::from_secs(2), - }, - ) - .expect("create tcp connector"); - - // Keep a cloned handle of every client socket open until AFTER the server observes EOF. - // Because drop/close only sends FIN when the last fd closes, this proves IlpTcpSink::flush() - // explicitly invoked shutdown(Shutdown::Write). - let kept_handles = Mutex::new(Vec::::new()); - let report = send_ilp_shard_files( - &files, - |shard| { - let sink = base_connector(shard)?; - assert!(sink.inner().nodelay().expect("query nodelay")); - kept_handles - .lock() - .expect("lock kept_handles") - .push(sink.inner().try_clone().expect("clone client TcpStream")); - Ok(sink) - }, - IlpSendOptions { buffer_bytes: 13 }, - ) - .expect("send over loopback tcp"); - - // Wait for all 3 server readers to reach EOF while client socket clones are still alive. - let received = server_handle.join().expect("join server thread"); - assert_eq!(kept_handles.lock().expect("lock kept_handles").len(), 3); - drop(kept_handles); - - assert_eq!(received.len(), 3); - let distinct_peers: HashSet = received.iter().map(|(peer, _)| *peer).collect(); - assert_eq!( - distinct_peers.len(), - 3, - "expected 3 separate accepted TCP connections" - ); - - let mut received_payloads: Vec> = received.into_iter().map(|(_, buf)| buf).collect(); - received_payloads.sort(); - let mut expected_payloads = vec![payload0.clone(), payload1.clone(), payload2.clone()]; - expected_payloads.sort(); - assert_eq!(received_payloads, expected_payloads); - - assert_eq!(report.total_shards, 3); - assert_eq!(report.shards[0].bytes_sent, payload0.len() as u64); - assert_eq!(report.shards[1].bytes_sent, 0); - assert_eq!(report.shards[2].bytes_sent, payload2.len() as u64); - assert_eq!( - report.total_bytes_sent, - (payload0.len() + payload1.len() + payload2.len()) as u64 - ); -} - -#[test] -fn tcp_rejects_invalid_address_before_connect() { - for bad in [ - "", - " ", - "127.0.0.1", - "127.0.0.1:", - "127.0.0.1:notaport", - "127.0.0.1:99999", - ":9009", - "bad host:9009", - " 127.0.0.1:9009", - "127.0.0.1:9009 ", - ] { - let err = match tcp_ilp_connector(bad, IlpTcpOptions::default()) { - Ok(_) => panic!("expected InvalidAddress for {bad:?}"), - Err(err) => err, - }; - assert!( - matches!(err, IlpSendError::InvalidAddress { .. }), - "expected InvalidAddress for {bad:?}, got {err:?}" - ); - } - - let zero_connect = match tcp_ilp_connector( - "127.0.0.1:9009", - IlpTcpOptions { - connect_timeout: Duration::ZERO, - write_timeout: Duration::from_secs(1), - }, - ) { - Ok(_) => panic!("expected InvalidTimeout for zero connect_timeout"), - Err(err) => err, - }; - assert!(matches!( - zero_connect, - IlpSendError::InvalidTimeout { - field: "connect_timeout" - } - )); - - let zero_write = match tcp_ilp_connector( - "127.0.0.1:9009", - IlpTcpOptions { - connect_timeout: Duration::from_secs(1), - write_timeout: Duration::ZERO, - }, - ) { - Ok(_) => panic!("expected InvalidTimeout for zero write_timeout"), - Err(err) => err, - }; - assert!(matches!( - zero_write, - IlpSendError::InvalidTimeout { - field: "write_timeout" - } - )); -} - -#[test] -fn tcp_pins_single_endpoint_and_does_not_fail_over_mid_send() { - let dir = TempDirGuard::new("ilp-send-tcp-pin"); - let p0 = dir.path().join("bars_1m.shard-00.ilp"); - let p1 = dir.path().join("bars_1m.shard-01.ilp"); - let payload0 = b"bars_1m,listing_id=1 open=1.0 1700000000000000t\n"; - let payload1 = b"bars_1m,listing_id=2 open=2.0 1700000060000000t\n"; - write_bytes(&p0, payload0); - write_bytes(&p1, payload1); - - let files = discover_ilp_shard_files(dir.path(), "bars_1m").expect("discover"); - - let listener_a = TcpListener::bind("127.0.0.1:0").expect("bind endpoint A"); - let addr_a = listener_a.local_addr().expect("addr A"); - listener_a - .set_nonblocking(true) - .expect("set listener A nonblocking"); - - let listener_b = TcpListener::bind("127.0.0.1:0").expect("bind endpoint B"); - let addr_b = listener_b.local_addr().expect("addr B"); - listener_b - .set_nonblocking(true) - .expect("set listener B nonblocking"); - - let a_closed = Arc::new((Mutex::new(false), Condvar::new())); - let a_closed_server = Arc::clone(&a_closed); - - // Server A accepts shard 0, closes its listener (simulating restart/refusal for shard 1), - // signals shard 1 to attempt connect, and finishes reading shard 0 to EOF. - let server_a = thread::spawn(move || { - let deadline = Instant::now() + Duration::from_secs(3); - let (mut stream, _) = accept_with_deadline(&listener_a, deadline, 0, 1); - drop(listener_a); - { - let (lock, cvar) = &*a_closed_server; - let mut closed = lock.lock().expect("lock a_closed"); - *closed = true; - cvar.notify_all(); - } - stream - .set_read_timeout(Some(Duration::from_secs(3))) - .expect("set read timeout"); - let mut buf = Vec::new(); - stream.read_to_end(&mut buf).expect("read shard 0 to EOF"); - buf - }); - - let base_connector = tcp_ilp_connector_for_addrs( - vec![addr_a, addr_b], - IlpTcpOptions { - connect_timeout: Duration::from_secs(2), - write_timeout: Duration::from_secs(2), - }, - ) - .expect("create multi-addr tcp connector"); - - let err = send_ilp_shard_files( - &files, - |shard| { - if shard == 1 { - let (lock, cvar) = &*a_closed; - let closed = lock.lock().expect("lock a_closed"); - let (guard, timeout) = cvar - .wait_timeout_while(closed, Duration::from_secs(3), |c| !*c) - .expect("wait for listener A to close"); - assert!( - !timeout.timed_out() && *guard, - "timed out waiting for endpoint A listener to close" - ); - } - base_connector(shard) - }, - IlpSendOptions { buffer_bytes: 16 }, - ) - .unwrap_err(); - - let received_a = server_a.join().expect("join server A"); - assert_eq!(received_a, payload0); - - // Endpoint B must never have received a connection attempt. - match listener_b.accept() { - Err(err) if err.kind() == io::ErrorKind::WouldBlock => {} - Ok((_, peer)) => panic!("shard 1 unexpectedly failed over to endpoint B from {peer}"), - Err(err) => panic!("unexpected error checking endpoint B: {err}"), - } - - match err { - IlpSendError::ShardIo { - op, - shard, - path, - partial_report, - .. - } => { - assert_eq!(op, IlpSendOp::Connect); - assert_eq!(shard, 1); - assert_eq!(path, p1); - assert_eq!(partial_report.total_shards, 2); - assert_eq!(partial_report.shards[0].shard, 0); - assert_eq!(partial_report.shards[0].bytes_sent, payload0.len() as u64); - assert_eq!(partial_report.shards[1].shard, 1); - assert_eq!(partial_report.shards[1].bytes_sent, 0); - assert_eq!(partial_report.total_bytes_sent, payload0.len() as u64); - } - other => panic!("expected ShardIo(Connect) on shard 1, got {other:?}"), - } -} - -#[test] -fn orders_report_and_lowest_failure_for_unsorted_input() { - let dir = TempDirGuard::new("ilp-send-unsorted"); - let p0 = dir.path().join("bars_1m.shard-00.ilp"); - let p1 = dir.path().join("bars_1m.shard-01.ilp"); - let p2 = dir.path().join("bars_1m.shard-02.ilp"); - write_bytes(&p0, b"aaaa"); - write_bytes(&p1, b"bb"); - write_bytes(&p2, b"cccccc"); - - let unsorted = vec![ - IlpShardFile { - shard: 2, - path: p2.clone(), - }, - IlpShardFile { - shard: 0, - path: p0.clone(), - }, - IlpShardFile { - shard: 1, - path: p1.clone(), - }, - ]; - - let ok_report = send_ilp_shard_files( - &unsorted, - |_shard| Ok(Vec::::new()), - IlpSendOptions { buffer_bytes: 4 }, - ) - .expect("send unsorted slice"); - assert_eq!( - ok_report - .shards - .iter() - .map(|s| (s.shard, s.bytes_sent)) - .collect::>(), - vec![(0, 4), (1, 2), (2, 6)] - ); - - let err = send_ilp_shard_files( - &unsorted, - |shard| { - if shard == 1 || shard == 2 { - Err(io::Error::new( - io::ErrorKind::ConnectionRefused, - format!("refused shard {shard}"), - )) - } else { - Ok(Vec::::new()) - } - }, - IlpSendOptions { buffer_bytes: 4 }, - ) - .unwrap_err(); - - match err { - IlpSendError::ShardIo { - op, - shard, - path, - partial_report, - .. - } => { - assert_eq!(op, IlpSendOp::Connect); - assert_eq!(shard, 1, "must report lowest-index failing shard"); - assert_eq!(path, p1); - assert_eq!( - partial_report - .shards - .iter() - .map(|s| (s.shard, s.bytes_sent)) - .collect::>(), - vec![(0, 4), (1, 0), (2, 0)] - ); - assert_eq!(partial_report.total_bytes_sent, 4); - } - other => panic!("expected ShardIo(Connect) on shard 1, got {other:?}"), - } -} - -// --------------------------------------------------------------------------- -// QA (T-188) edge-case coverage. -// --------------------------------------------------------------------------- - -fn refused_loopback_addr() -> SocketAddr { - // Bind an ephemeral loopback port and immediately release it so connects are refused. - let listener = TcpListener::bind("127.0.0.1:0").expect("bind ephemeral loopback port"); - let addr = listener.local_addr().expect("ephemeral local addr"); - drop(listener); - addr -} - -#[test] -fn discovery_ignores_near_miss_shard_names_and_accepts_hyphen_prefix() { - let dir = TempDirGuard::new("ilp-send-near-miss"); - write_bytes(&dir.path().join("bars_1m.shard-00.ilp"), b"real"); - for near_miss in [ - "bars_1m.shard-.ilp", - "bars_1m.shard-0a.ilp", - "bars_1m.shard-+1.ilp", - "bars_1m.shard--1.ilp", - "bars_1m.shard-01.ilp.tmp", - "bars_1m.shard-01.ILP", - "BARS_1M.shard-01.ilp", - "xbars_1m.shard-01.ilp", - "bars_1m.shard01.ilp", - "bars_1m_qm.shard-01.ilp", - ] { - write_bytes(&dir.path().join(near_miss), b"ignored"); - } - - let found = discover_ilp_shard_files(dir.path(), "bars_1m").expect("discover bars_1m"); - assert_eq!( - found, - vec![IlpShardFile { - shard: 0, - path: dir.path().join("bars_1m.shard-00.ilp"), - }] - ); - - let hyphen = TempDirGuard::new("ilp-send-hyphen-prefix"); - write_bytes(&hyphen.path().join("fx-1m.shard-00.ilp"), b"fx"); - let found = discover_ilp_shard_files(hyphen.path(), "fx-1m").expect("hyphen prefix"); - assert_eq!(found.len(), 1); - assert_eq!(found[0].shard, 0); - - let missing = dir.path().join("does-not-exist"); - match discover_ilp_shard_files(&missing, "bars_1m").unwrap_err() { - IlpSendError::ReadDir { path, source } => { - assert_eq!(path, missing); - assert_eq!(source.kind(), io::ErrorKind::NotFound); - } - other => panic!("expected ReadDir(NotFound), got {other:?}"), - } -} - -#[test] -fn streams_multi_chunk_file_with_one_byte_buffer_and_handles_empty_slice() { - let dir = TempDirGuard::new("ilp-send-one-byte"); - // Deterministic pseudo-random payload covering every byte value, including 0x0A. - let mut state: u32 = 0x1234_5678; - let payload: Vec = (0..4099) - .map(|_| { - state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); - (state >> 24) as u8 - }) - .chain(0u8..=255) - .collect(); - let path = dir.path().join("fx_1m.shard-00.ilp"); - write_bytes(&path, &payload); - - let files = discover_ilp_shard_files(dir.path(), "fx_1m").expect("discover"); - let state_cell = Arc::new(Mutex::new(RecordingSinkState { - bytes: Vec::new(), - flushes: 0, - })); - let report = send_ilp_shard_files( - &files, - |_shard| { - Ok(RecordingSink { - state: Arc::clone(&state_cell), - }) - }, - IlpSendOptions { buffer_bytes: 1 }, - ) - .expect("send one-byte buffer"); - let recorded = state_cell.lock().expect("lock recorded"); - assert_eq!(recorded.bytes, payload); - assert_eq!(recorded.flushes, 1); - assert_eq!(report.total_bytes_sent, payload.len() as u64); - - let calls = AtomicUsize::new(0); - let empty = send_ilp_shard_files( - &[], - |_shard| { - calls.fetch_add(1, Ordering::SeqCst); - Ok(Vec::::new()) - }, - IlpSendOptions::default(), - ) - .expect("empty slice is a no-op"); - assert_eq!(calls.load(Ordering::SeqCst), 0); - assert_eq!(empty.total_shards, 0); - assert_eq!(empty.total_bytes_sent, 0); - assert_eq!( - format_ilp_send_report(&empty), - "curate-etl ilp-send\n ilp_send: shards=0 total_bytes_sent=0 per_shard_bytes=none" - ); - assert_eq!(IlpSendOptions::default().buffer_bytes, 64 * 1024); -} - -#[test] -fn shard_io_error_display_and_source_name_shard_path_and_op() { - let dir = TempDirGuard::new("ilp-send-display"); - let p0 = dir.path().join("bars_1m.shard-00.ilp"); - let p1 = dir.path().join("bars_1m.shard-01.ilp"); - write_bytes(&p0, b"abc"); - write_bytes(&p1, b"defg"); - let files = discover_ilp_shard_files(dir.path(), "bars_1m").expect("discover"); - - let err = send_ilp_shard_files( - &files, - |shard| { - if shard == 1 { - Err(io::Error::new(io::ErrorKind::ConnectionRefused, "refused")) - } else { - Ok(Vec::::new()) - } - }, - IlpSendOptions { buffer_bytes: 2 }, - ) - .unwrap_err(); - - let text = err.to_string(); - assert!(text.contains("ILP shard 1"), "{text}"); - assert!(text.contains(&p1.display().to_string()), "{text}"); - assert!(text.contains("during connect"), "{text}"); - assert!(text.contains("total_bytes_sent=3"), "{text}"); - - let source = std::error::Error::source(&err).expect("ShardIo exposes io::Error source"); - let io_source = source - .downcast_ref::() - .expect("source is io::Error"); - assert_eq!(io_source.kind(), io::ErrorKind::ConnectionRefused); - - let partial = err.partial_report().expect("ShardIo carries partial report"); - assert_eq!( - format_ilp_send_report(partial), - "curate-etl ilp-send\n ilp_send: shards=2 total_bytes_sent=3 per_shard_bytes=00=3,01=0" - ); - assert!(IlpSendError::ZeroBufferBytes.partial_report().is_none()); -} - -#[test] -fn tcp_reports_refused_connection_as_connect_failure() { - let dir = TempDirGuard::new("ilp-send-tcp-refused"); - let p0 = dir.path().join("bars_1m.shard-00.ilp"); - write_bytes(&p0, b"bars_1m,listing_id=1 open=1.0 1700000000000000t\n"); - let files = discover_ilp_shard_files(dir.path(), "bars_1m").expect("discover"); - - let dead = refused_loopback_addr(); - let connector = tcp_ilp_connector( - &dead.to_string(), - IlpTcpOptions { - connect_timeout: Duration::from_secs(2), - write_timeout: Duration::from_secs(2), - }, - ) - .expect("connector creation must not connect"); - - match send_ilp_shard_files(&files, connector, IlpSendOptions::default()).unwrap_err() { - IlpSendError::ShardIo { - op, - shard, - path, - source, - partial_report, - } => { - assert_eq!(op, IlpSendOp::Connect); - assert_eq!(shard, 0); - assert_eq!(path, p0); - assert_eq!(source.kind(), io::ErrorKind::ConnectionRefused); - assert_eq!(partial_report.total_bytes_sent, 0); - } - other => panic!("expected ShardIo(Connect), got {other:?}"), - } -} - -#[test] -fn tcp_connector_skips_unreachable_address_then_pins_reachable_one_for_all_shards() { - let dir = TempDirGuard::new("ilp-send-tcp-pin-first-live"); - let payloads: Vec> = (0..3) - .map(|i| format!("bars_1m,listing_id={i} open=1.0 170000000000000{i}t\n").into_bytes()) - .collect(); - for (i, payload) in payloads.iter().enumerate() { - write_bytes(&dir.path().join(format!("bars_1m.shard-{i:02}.ilp")), payload); - } - let files = discover_ilp_shard_files(dir.path(), "bars_1m").expect("discover"); - - let dead = refused_loopback_addr(); - let live = TcpListener::bind("127.0.0.1:0").expect("bind live endpoint"); - let live_addr = live.local_addr().expect("live addr"); - live.set_nonblocking(true).expect("nonblocking live"); - - let server = thread::spawn(move || { - let deadline = Instant::now() + Duration::from_secs(3); - let mut readers = Vec::new(); - for accepted in 0..3 { - let (mut stream, _) = accept_with_deadline(&live, deadline, accepted, 3); - stream - .set_read_timeout(Some(Duration::from_secs(3))) - .expect("read timeout"); - readers.push(thread::spawn(move || { - let mut buf = Vec::new(); - stream.read_to_end(&mut buf).expect("read to EOF"); - buf - })); - } - readers - .into_iter() - .map(|h| h.join().expect("join reader")) - .collect::>() - }); - - let connector = tcp_ilp_connector_for_addrs( - vec![dead, live_addr], - IlpTcpOptions { - connect_timeout: Duration::from_secs(2), - write_timeout: Duration::from_secs(2), - }, - ) - .expect("connector"); - let peers = Mutex::new(Vec::::new()); - let report = send_ilp_shard_files( - &files, - |shard| { - let sink = connector(shard)?; - peers - .lock() - .expect("lock peers") - .push(sink.inner().peer_addr().expect("peer addr")); - Ok(sink) - }, - IlpSendOptions { buffer_bytes: 5 }, - ) - .expect("send via first reachable address"); - - let mut received = server.join().expect("join server"); - received.sort(); - let mut expected = payloads.clone(); - expected.sort(); - assert_eq!(received, expected); - let peers = peers.into_inner().expect("peers"); - assert_eq!(peers.len(), 3); - assert!(peers.iter().all(|p| *p == live_addr), "{peers:?}"); - assert_eq!( - report.total_bytes_sent, - payloads.iter().map(|p| p.len() as u64).sum::() - ); -} - -// --------------------------------------------------------------------------- -// `run_send_ilp` wrapper tests (`M2.3q`). -// --------------------------------------------------------------------------- - -#[test] -fn run_send_ilp_end_to_end_over_loopback() { - let dir = TempDirGuard::new("run-send-ilp-e2e"); - let payload0: Vec = vec![ - b'f', b'x', b'_', b'1', b'm', b',', b'p', b'a', b'i', b'r', b'=', b'U', b'S', b'D', b'C', - b'A', b'D', b' ', b'c', b'=', b'=', 0x10, 0x0A, 0xFF, 0xFE, 0x80, 0x00, 0x00, 0xF0, 0x3F, - b' ', b'1', b'7', b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0', - b'0', b'0', b't', b'\n', - ]; - let payload1: Vec = Vec::new(); - let payload2: Vec = vec![ - b'f', b'x', b'_', b'1', b'm', b',', b'p', b'a', b'i', b'r', b'=', b'U', b'S', b'D', b'C', - b'A', b'D', b' ', b'c', b'=', b'=', 0x10, 0xC0, 0x81, 0x0A, 0x0A, 0x01, 0x02, 0xF5, 0x3F, - b' ', b'1', b'7', b'0', b'0', b'0', b'0', b'0', b'0', b'6', b'0', b'0', b'0', b'0', b'0', - b'0', b'0', b't', b'\n', - ]; - assert!(std::str::from_utf8(&payload0).is_err()); - assert!(std::str::from_utf8(&payload2).is_err()); - assert!(payload0.contains(&0x0A)); - assert!(payload2.contains(&0x0A)); - - write_bytes(&dir.path().join("fx_1m.shard-00.ilp"), &payload0); - write_bytes(&dir.path().join("fx_1m.shard-01.ilp"), &payload1); - write_bytes(&dir.path().join("fx_1m.shard-02.ilp"), &payload2); - - let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback listener"); - let listen_addr = listener.local_addr().expect("local addr"); - listener - .set_nonblocking(true) - .expect("set loopback listener nonblocking"); - - let server_handle = thread::spawn(move || { - let deadline = Instant::now() + Duration::from_secs(3); - let mut reader_handles = Vec::with_capacity(3); - for accepted in 0..3 { - let (mut stream, peer) = accept_with_deadline(&listener, deadline, accepted, 3); - stream - .set_read_timeout(Some(Duration::from_secs(3))) - .expect("set server read timeout"); - reader_handles.push(thread::spawn(move || { - let mut buf = Vec::new(); - stream - .read_to_end(&mut buf) - .expect("read shard stream to EOF"); - (peer, buf) - })); - } - let received: Vec<(SocketAddr, Vec)> = reader_handles - .into_iter() - .map(|h| h.join().expect("join reader thread")) - .collect(); - (listener, received) - }); - - let report = run_send_ilp(&SendIlpArgs { - dir: dir.path().to_path_buf(), - prefix: "fx_1m".to_string(), - addr: listen_addr.to_string(), - }) - .expect("run_send_ilp should succeed over loopback"); - - let (listener, received) = server_handle.join().expect("join server thread"); - - // Verify no extra 4th connection was opened. - match listener.accept() { - Err(err) if err.kind() == io::ErrorKind::WouldBlock => {} - Ok((_, peer)) => panic!("unexpected extra connection from {peer}"), - Err(err) => panic!("unexpected error checking accept queue: {err}"), - } - - assert_eq!(received.len(), 3); - let distinct_peers: HashSet = received.iter().map(|(peer, _)| *peer).collect(); - assert_eq!(distinct_peers.len(), 3, "expected 3 separate connections"); - - let mut received_payloads: Vec> = received.into_iter().map(|(_, buf)| buf).collect(); - received_payloads.sort(); - let mut expected_payloads = vec![payload0.clone(), payload1.clone(), payload2.clone()]; - expected_payloads.sort(); - assert_eq!(received_payloads, expected_payloads); - - let expected_total = (payload0.len() + payload1.len() + payload2.len()) as u64; - assert_eq!(report.total_shards, 3); - assert_eq!(report.shards[0].shard, 0); - assert_eq!(report.shards[0].bytes_sent, payload0.len() as u64); - assert_eq!(report.shards[1].shard, 1); - assert_eq!(report.shards[1].bytes_sent, 0); - assert_eq!(report.shards[2].shard, 2); - assert_eq!(report.shards[2].bytes_sent, payload2.len() as u64); - assert_eq!(report.total_bytes_sent, expected_total); - - assert_eq!( - format_ilp_send_report(&report), - format!( - "curate-etl ilp-send\n ilp_send: shards=3 total_bytes_sent={expected_total} per_shard_bytes=00={},01=0,02={}", - payload0.len(), - payload2.len() - ) - ); -} - -#[test] -fn run_send_ilp_fails_closed_on_discovery_and_address_errors_with_zero_connections() { - let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback listener"); - let listen_addr = listener.local_addr().expect("local addr"); - listener - .set_nonblocking(true) - .expect("set listener nonblocking"); - - let assert_zero_accepts = |label: &str| match listener.accept() { - Err(err) if err.kind() == io::ErrorKind::WouldBlock => {} - Ok((_, peer)) => panic!("{label}: unexpectedly accepted connection from {peer}"), - Err(err) => panic!("{label}: unexpected accept error: {err}"), - }; - - // (a) Missing directory -> ReadDir(NotFound), zero connections. - let base = TempDirGuard::new("run-send-ilp-fail-closed"); - let missing_dir = base.path().join("does-not-exist"); - let err = run_send_ilp(&SendIlpArgs { - dir: missing_dir.clone(), - prefix: "fx_1m".to_string(), - addr: listen_addr.to_string(), - }) - .unwrap_err(); - assert!( - matches!(err, IlpSendError::ReadDir { ref source, .. } if source.kind() == io::ErrorKind::NotFound), - "expected ReadDir(NotFound), got {err:?}" - ); - assert_zero_accepts("missing directory"); - - // (b) Empty directory -> NoShardFiles, zero connections. - let empty_dir = TempDirGuard::new("run-send-ilp-empty"); - let err = run_send_ilp(&SendIlpArgs { - dir: empty_dir.path().to_path_buf(), - prefix: "fx_1m".to_string(), - addr: listen_addr.to_string(), - }) - .unwrap_err(); - assert!( - matches!(err, IlpSendError::NoShardFiles { .. }), - "expected NoShardFiles, got {err:?}" - ); - assert_zero_accepts("empty directory"); - - // (c) Discovery failure paired with malformed address -> discovery error takes precedence. - let err = run_send_ilp(&SendIlpArgs { - dir: empty_dir.path().to_path_buf(), - prefix: "fx_1m".to_string(), - addr: "not-an-addr".to_string(), - }) - .unwrap_err(); - assert!( - matches!(err, IlpSendError::NoShardFiles { .. }), - "expected discovery error before address validation, got {err:?}" - ); - assert_zero_accepts("empty directory with malformed address"); - - // (d) Shard gap (00 + 02) -> MissingShardIndex, zero connections. - let gap_dir = TempDirGuard::new("run-send-ilp-gap"); - write_bytes(&gap_dir.path().join("fx_1m.shard-00.ilp"), b"a"); - write_bytes(&gap_dir.path().join("fx_1m.shard-02.ilp"), b"c"); - let err = run_send_ilp(&SendIlpArgs { - dir: gap_dir.path().to_path_buf(), - prefix: "fx_1m".to_string(), - addr: listen_addr.to_string(), - }) - .unwrap_err(); - assert!( - matches!( - err, - IlpSendError::MissingShardIndex { - expected: 1, - found: 2, - .. - } - ), - "expected MissingShardIndex(1, 2), got {err:?}" - ); - assert_zero_accepts("shard gap"); - - // (e) Valid shards + malformed address -> InvalidAddress before any connect. - let valid_dir = TempDirGuard::new("run-send-ilp-bad-addr"); - write_bytes(&valid_dir.path().join("fx_1m.shard-00.ilp"), b"ok"); - for bad_addr in ["not-an-addr", "127.0.0.1", "127.0.0.1:notaport"] { - let err = run_send_ilp(&SendIlpArgs { - dir: valid_dir.path().to_path_buf(), - prefix: "fx_1m".to_string(), - addr: bad_addr.to_string(), - }) - .unwrap_err(); - assert!( - matches!(err, IlpSendError::InvalidAddress { .. }), - "expected InvalidAddress for {bad_addr:?}, got {err:?}" - ); - } - assert_zero_accepts("malformed address"); -} - -#[test] -fn run_send_ilp_refused_connection_returns_connect_error_and_zero_partial_report() { - let dir = TempDirGuard::new("run-send-ilp-refused"); - let p0 = dir.path().join("fx_1m.shard-00.ilp"); - let p1 = dir.path().join("fx_1m.shard-01.ilp"); - let p2 = dir.path().join("fx_1m.shard-02.ilp"); - write_bytes(&p0, b"shard0"); - write_bytes(&p1, b""); - write_bytes(&p2, b"shard2"); - - let dead = refused_loopback_addr(); - let err = run_send_ilp(&SendIlpArgs { - dir: dir.path().to_path_buf(), - prefix: "fx_1m".to_string(), - addr: dead.to_string(), - }) - .unwrap_err(); - - match err { - IlpSendError::ShardIo { - op, - shard, - path, - source, - partial_report, - } => { - assert_eq!(op, IlpSendOp::Connect); - assert_eq!(shard, 0); - assert_eq!(path, p0); - assert_eq!(source.kind(), io::ErrorKind::ConnectionRefused); - assert_eq!(partial_report.total_shards, 3); - assert_eq!(partial_report.total_bytes_sent, 0); - assert_eq!(partial_report.shards.len(), 3); - for (idx, entry) in partial_report.shards.iter().enumerate() { - assert_eq!(entry.shard, idx); - assert_eq!(entry.bytes_sent, 0); - } - } - other => panic!("expected ShardIo(Connect), got {other:?}"), - } -} - -#[test] -fn run_send_ilp_mixed_folder_isolates_bars_1m_bars_1m_qm_and_fx_1m() { - let dir = TempDirGuard::new("run-send-ilp-mixed-folder"); - let bars0 = b"bars_1m,listing_id=1 close=10.0 1700000000000000t\n".to_vec(); - let bars1 = b"bars_1m,listing_id=2 close=20.0 1700000060000000t\n".to_vec(); - let qm0 = b"bars_1m,listing_id=1,source=qm_raw close=10.5 1700000000000000t\n".to_vec(); - let fx0 = b"fx_1m,pair=USDCAD close=1.38 1700000000000000t\n".to_vec(); - - write_bytes(&dir.path().join("bars_1m.shard-00.ilp"), &bars0); - write_bytes(&dir.path().join("bars_1m.shard-01.ilp"), &bars1); - write_bytes(&dir.path().join("bars_1m_qm.shard-00.ilp"), &qm0); - write_bytes(&dir.path().join("fx_1m.shard-00.ilp"), &fx0); - write_bytes(&dir.path().join("notes.txt"), b"unrelated"); - - let cases: [(&str, Vec>); 3] = [ - ("bars_1m", vec![bars0.clone(), bars1.clone()]), - ("bars_1m_qm", vec![qm0.clone()]), - ("fx_1m", vec![fx0.clone()]), - ]; - - for (prefix, mut expected) in cases { - let count = expected.len(); - let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback listener"); - let listen_addr = listener.local_addr().expect("local addr"); - listener - .set_nonblocking(true) - .expect("set loopback listener nonblocking"); - - let server_handle = thread::spawn(move || { - let deadline = Instant::now() + Duration::from_secs(3); - let mut readers = Vec::with_capacity(count); - for accepted in 0..count { - let (mut stream, _) = accept_with_deadline(&listener, deadline, accepted, count); - stream - .set_read_timeout(Some(Duration::from_secs(3))) - .expect("set server read timeout"); - readers.push(thread::spawn(move || { - let mut buf = Vec::new(); - stream.read_to_end(&mut buf).expect("read shard to EOF"); - buf - })); - } - let received: Vec> = readers - .into_iter() - .map(|h| h.join().expect("join reader")) - .collect(); - (listener, received) - }); - - let report = run_send_ilp(&SendIlpArgs { - dir: dir.path().to_path_buf(), - prefix: prefix.to_string(), - addr: listen_addr.to_string(), - }) - .expect("run_send_ilp should send only matching prefix"); - - let (listener, mut received) = server_handle.join().expect("join server"); - match listener.accept() { - Err(err) if err.kind() == io::ErrorKind::WouldBlock => {} - Ok((_, peer)) => panic!("{prefix}: unexpected extra connection from {peer}"), - Err(err) => panic!("{prefix}: unexpected accept error: {err}"), - } - - received.sort(); - expected.sort(); - assert_eq!(received, expected, "payload mismatch for prefix {prefix}"); - assert_eq!(report.total_shards, count); - let expected_bytes: u64 = expected.iter().map(|b| b.len() as u64).sum(); - assert_eq!(report.total_bytes_sent, expected_bytes); - } -} - -#[test] -fn run_send_ilp_gap_precedes_malformed_addr_and_file_as_dir_rejected_with_zero_connections() { - let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback listener"); - let listen_addr = listener.local_addr().expect("local addr"); - listener - .set_nonblocking(true) - .expect("set listener nonblocking"); - - let assert_zero_accepts = |label: &str| match listener.accept() { - Err(err) if err.kind() == io::ErrorKind::WouldBlock => {} - Ok((_, peer)) => panic!("{label}: unexpectedly accepted connection from {peer}"), - Err(err) => panic!("{label}: unexpected accept error: {err}"), - }; - - // Shard gap paired with malformed address -> MissingShardIndex precedes InvalidAddress. - let gap_dir = TempDirGuard::new("run-send-ilp-gap-precedence"); - write_bytes(&gap_dir.path().join("bars_1m.shard-00.ilp"), b"a"); - write_bytes(&gap_dir.path().join("bars_1m.shard-02.ilp"), b"c"); - let err = run_send_ilp(&SendIlpArgs { - dir: gap_dir.path().to_path_buf(), - prefix: "bars_1m".to_string(), - addr: "not-an-addr".to_string(), - }) - .unwrap_err(); - assert!( - matches!( - err, - IlpSendError::MissingShardIndex { - expected: 1, - found: 2, - .. - } - ), - "expected MissingShardIndex(1, 2) before InvalidAddress, got {err:?}" - ); - assert_zero_accepts("shard gap with malformed addr"); - - // Regular file passed as --dir -> InvalidDirectory, zero connections. - let file_dir = TempDirGuard::new("run-send-ilp-file-as-dir"); - let file_path = file_dir.path().join("not_a_dir.ilp"); - write_bytes(&file_path, b"not a directory"); - let err = run_send_ilp(&SendIlpArgs { - dir: file_path, - prefix: "bars_1m".to_string(), - addr: listen_addr.to_string(), - }) - .unwrap_err(); - assert!( - matches!(err, IlpSendError::InvalidDirectory { .. }), - "expected InvalidDirectory, got {err:?}" - ); - assert_zero_accepts("file passed as dir"); -} - -#[test] -fn run_send_ilp_streams_payloads_larger_than_default_buffer_byte_for_byte() { - // Arrange: two shards spanning several DEFAULT_ILP_SEND_BUFFER_BYTES chunks with a - // non-aligned tail, filled from a fixed-seed LCG so contents are deterministic. - let dir = TempDirGuard::new("run-send-ilp-large"); - let mut state: u64 = 0x5EED_1234_ABCD_0001; - let mut next_byte = || { - state = state - .wrapping_mul(6_364_136_223_846_793_005) - .wrapping_add(1_442_695_040_888_963_407); - (state >> 56) as u8 - }; - let len0 = DEFAULT_ILP_SEND_BUFFER_BYTES * 3 + 17; - let len1 = DEFAULT_ILP_SEND_BUFFER_BYTES + 1; - let payload0: Vec = (0..len0).map(|_| next_byte()).collect(); - let payload1: Vec = (0..len1).map(|_| next_byte()).collect(); - assert_ne!(payload0[..len1], payload1[..]); - write_bytes(&dir.path().join("bars_1m_qm.shard-00.ilp"), &payload0); - write_bytes(&dir.path().join("bars_1m_qm.shard-01.ilp"), &payload1); - - let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback listener"); - let listen_addr = listener.local_addr().expect("local addr"); - listener - .set_nonblocking(true) - .expect("set loopback listener nonblocking"); - let server = thread::spawn(move || { - let deadline = Instant::now() + Duration::from_secs(5); - let mut readers = Vec::with_capacity(2); - for accepted in 0..2 { - let (mut stream, _) = accept_with_deadline(&listener, deadline, accepted, 2); - stream - .set_read_timeout(Some(Duration::from_secs(5))) - .expect("set server read timeout"); - readers.push(thread::spawn(move || { - let mut buf = Vec::new(); - stream.read_to_end(&mut buf).expect("read shard to EOF"); - buf - })); - } - let received: Vec> = readers - .into_iter() - .map(|h| h.join().expect("join reader")) - .collect(); - (listener, received) - }); - - // Act - let report = run_send_ilp(&SendIlpArgs { - dir: dir.path().to_path_buf(), - prefix: "bars_1m_qm".to_string(), - addr: listen_addr.to_string(), - }) - .expect("run_send_ilp should stream multi-chunk shards"); - let (listener, mut received) = server.join().expect("join server"); - - // Assert - match listener.accept() { - Err(err) if err.kind() == io::ErrorKind::WouldBlock => {} - Ok((_, peer)) => panic!("unexpected extra connection from {peer}"), - Err(err) => panic!("unexpected accept error: {err}"), - } - received.sort(); - let mut expected = vec![payload0.clone(), payload1.clone()]; - expected.sort(); - assert!( - received == expected, - "received payloads differ from shard files" - ); - assert_eq!(report.total_shards, 2); - assert_eq!(report.shards[0].bytes_sent, len0 as u64); - assert_eq!(report.shards[1].bytes_sent, len1 as u64); - assert_eq!(report.total_bytes_sent, (len0 + len1) as u64); -} - -#[test] -fn run_send_ilp_resolves_hostname_addr_and_delivers_every_shard() { - // Arrange: `--addr` is passed through as `host:port`, so a hostname (not only an IP - // literal) must resolve and pin the reachable loopback address for every shard. - let dir = TempDirGuard::new("run-send-ilp-hostname"); - let payload0 = b"bars_1m,listing_id=7 close=1.5 1700000000000000t\n".to_vec(); - let payload1 = b"bars_1m,listing_id=8 close=2.5 1700000060000000t\n".to_vec(); - write_bytes(&dir.path().join("bars_1m.shard-00.ilp"), &payload0); - write_bytes(&dir.path().join("bars_1m.shard-01.ilp"), &payload1); - - let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback listener"); - let port = listener.local_addr().expect("local addr").port(); - listener - .set_nonblocking(true) - .expect("set loopback listener nonblocking"); - let server = thread::spawn(move || { - let deadline = Instant::now() + Duration::from_secs(5); - let mut readers = Vec::with_capacity(2); - for accepted in 0..2 { - let (mut stream, _) = accept_with_deadline(&listener, deadline, accepted, 2); - stream - .set_read_timeout(Some(Duration::from_secs(5))) - .expect("set server read timeout"); - readers.push(thread::spawn(move || { - let mut buf = Vec::new(); - stream.read_to_end(&mut buf).expect("read shard to EOF"); - buf - })); - } - let received: Vec> = readers - .into_iter() - .map(|h| h.join().expect("join reader")) - .collect(); - (listener, received) - }); - - // Act - let report = run_send_ilp(&SendIlpArgs { - dir: dir.path().to_path_buf(), - prefix: "bars_1m".to_string(), - addr: format!("localhost:{port}"), - }) - .expect("run_send_ilp should resolve localhost and deliver"); - let (listener, mut received) = server.join().expect("join server"); - - // Assert - match listener.accept() { - Err(err) if err.kind() == io::ErrorKind::WouldBlock => {} - Ok((_, peer)) => panic!("unexpected extra connection from {peer}"), - Err(err) => panic!("unexpected accept error: {err}"), - } - received.sort(); - let mut expected = vec![payload0.clone(), payload1.clone()]; - expected.sort(); - assert_eq!(received, expected); - assert_eq!(report.total_shards, 2); - assert_eq!( - report.total_bytes_sent, - (payload0.len() + payload1.len()) as u64 - ); -} diff --git a/tools/curate-etl/src/ilp_tests.rs b/tools/curate-etl/src/ilp_tests.rs deleted file mode 100644 index 775d1686..00000000 --- a/tools/curate-etl/src/ilp_tests.rs +++ /dev/null @@ -1,903 +0,0 @@ -use std::collections::HashMap; -use std::io::{self, Write}; -use std::sync::{Arc, Mutex}; - -use crate::bars_1m::{Bar1mRow, IntradaySession, BARS_1M_SOURCE_EOD}; - -use super::{ - encode_bar_1m, encode_fx_1m, fnv1a_64, shard_for_fx_pair, shard_for_listing_id, Fx1mRow, - IlpEncodeError, IlpShardedWriter, IlpWriterError, IlpWriterOptions, ILP_V2_DOUBLE_TYPE, -}; - -fn sample_bar(listing_id: i32, ts: i64) -> Bar1mRow { - Bar1mRow { - key: listing_id, - ts, - session_date: 20_100, - open: 123.45, - high: 125.75, - low: 122.125, - close: 124.5, - volume: 98_765.0, - session: IntradaySession::Rth, - source: BARS_1M_SOURCE_EOD, - } -} - -fn sample_fx(pair: &'static str, ts: i64) -> Fx1mRow<'static> { - Fx1mRow { - pair, - ts, - open: 1.3625, - high: 1.3650, - low: 1.3610, - close: 1.3642, - source: "eod", - } -} - -/// Minimal ILP v2 frame splitter that respects escaped symbols and fixed-width 8-byte binary -/// `DOUBLE` payloads (`==\x10<8 bytes>`), so embedded `0x0a` bytes inside binary doubles or -/// escaped `\n` in symbols never falsely split a row. -fn split_ilp_v2_rows(data: &[u8]) -> Vec<&[u8]> { - let mut rows = Vec::new(); - let mut i = 0usize; - let len = data.len(); - - while i < len { - let start = i; - // 1. Tag set (table + symbols) ends at unescaped ASCII space. - while i < len { - match data[i] { - b'\\' => { - assert!(i + 1 < len, "dangling backslash in ILP tag set"); - i += 2; - } - b' ' => { - i += 1; - break; - } - _ => i += 1, - } - } - assert!(i < len, "unexpected EOF after ILP tag set"); - - // 2. Field set ends at ASCII space; skip fixed 8-byte binary double payloads after `==\x10`. - while i < len { - if data[i] == b' ' { - i += 1; - break; - } - if data[i] == b'=' && i + 2 < len && data[i + 1] == b'=' && data[i + 2] == ILP_V2_DOUBLE_TYPE - { - assert!( - i + 3 + 8 <= len, - "truncated binary DOUBLE payload in ILP field set" - ); - i += 3 + 8; - } else { - i += 1; - } - } - assert!(i < len, "unexpected EOF after ILP field set"); - - // 3. Designated timestamp runs to unescaped LF. - while i < len && data[i] != b'\n' { - i += 1; - } - assert!(i < len && data[i] == b'\n', "ILP row missing trailing LF"); - i += 1; - rows.push(&data[start..i]); - } - - rows -} - -fn extract_tag_value<'a>(row: &'a [u8], tag_prefix: &[u8]) -> &'a [u8] { - let mut i = 0usize; - let tag_end = loop { - assert!(i < row.len(), "missing space after tag set"); - match row[i] { - b'\\' => i += 2, - b' ' => break i, - _ => i += 1, - } - }; - let tag_section = &row[..tag_end]; - let pos = tag_section - .windows(tag_prefix.len()) - .position(|w| w == tag_prefix) - .expect("expected tag prefix in row"); - let val_start = pos + tag_prefix.len(); - let mut j = val_start; - while j < tag_end { - match tag_section[j] { - b'\\' => j += 2, - b',' => break, - _ => j += 1, - } - } - &tag_section[val_start..j] -} - -#[derive(Clone, Default)] -struct RecordingSink { - writes: Arc>>>, - flush_calls: Arc>, - fail_on_write_call: Option, - /// `(call_index, prefix_bytes)`: on `call_index`, accept only `prefix_bytes` and then fail - /// on the subsequent `write()` call inside `write_all()`. - partial_then_fail_on_write_call: Option<(usize, usize)>, - fail_on_flush: bool, -} - -impl RecordingSink { - fn new() -> Self { - Self::default() - } - - fn failing_on_write(call_index: usize) -> Self { - Self { - fail_on_write_call: Some(call_index), - ..Self::default() - } - } - - fn failing_after_partial_write(call_index: usize, prefix_bytes: usize) -> Self { - Self { - partial_then_fail_on_write_call: Some((call_index, prefix_bytes)), - ..Self::default() - } - } - - fn failing_on_flush() -> Self { - Self { - fail_on_flush: true, - ..Self::default() - } - } - - fn captured_writes(&self) -> Vec> { - self.writes.lock().unwrap().clone() - } - - fn captured_bytes(&self) -> Vec { - self.writes - .lock() - .unwrap() - .iter() - .flat_map(|w| w.iter().copied()) - .collect() - } - - fn captured_flushes(&self) -> usize { - *self.flush_calls.lock().unwrap() - } -} - -impl Write for RecordingSink { - fn write(&mut self, buf: &[u8]) -> io::Result { - let mut writes = self.writes.lock().unwrap(); - let call_idx = writes.len(); - if self.fail_on_write_call == Some(call_idx) { - return Err(io::Error::new( - io::ErrorKind::BrokenPipe, - format!("injected write failure on call {call_idx}"), - )); - } - if let Some((partial_call, prefix_bytes)) = self.partial_then_fail_on_write_call { - if call_idx == partial_call { - let n = prefix_bytes.min(buf.len()); - writes.push(buf[..n].to_vec()); - return Ok(n); - } - if call_idx > partial_call { - return Err(io::Error::new( - io::ErrorKind::BrokenPipe, - format!("injected write failure after partial write on call {call_idx}"), - )); - } - } - writes.push(buf.to_vec()); - Ok(buf.len()) - } - - fn flush(&mut self) -> io::Result<()> { - let mut flushes = self.flush_calls.lock().unwrap(); - *flushes += 1; - if self.fail_on_flush { - return Err(io::Error::new( - io::ErrorKind::ConnectionReset, - "injected flush failure", - )); - } - Ok(()) - } -} - -#[test] -fn golden_bytes_encode_bar_1m_matches_ilp_v2_wire_contract() { - let row = Bar1mRow { - key: 42, - ts: 1_736_951_400_000_000, - session_date: 20_103, - open: 150.25, - high: 151.75, - low: 149.5, - close: 151.125, - volume: 12_345.0, - session: IntradaySession::Rth, - source: BARS_1M_SOURCE_EOD, - }; - let known_at_micros = 1_736_951_460_123_456_i64; - - let mut actual = Vec::new(); - encode_bar_1m(&mut actual, &row, known_at_micros).expect("encode bar_1m"); - - let mut expected = Vec::new(); - expected.extend_from_slice(b"bars_1m,listing_id=42,session=RTH,source=eod_unadj "); - expected.extend_from_slice(b"open==\x10"); - expected.extend_from_slice(&150.25_f64.to_le_bytes()); - expected.extend_from_slice(b",high==\x10"); - expected.extend_from_slice(&151.75_f64.to_le_bytes()); - expected.extend_from_slice(b",low==\x10"); - expected.extend_from_slice(&149.5_f64.to_le_bytes()); - expected.extend_from_slice(b",close==\x10"); - expected.extend_from_slice(&151.125_f64.to_le_bytes()); - expected.extend_from_slice(b",volume==\x10"); - expected.extend_from_slice(&12_345.0_f64.to_le_bytes()); - expected.extend_from_slice(b",known_at=1736951460123456t 1736951400000000t\n"); - - assert_eq!(actual, expected); - assert!( - !actual.windows(4).any(|w| w == b"vwap"), - "vwap must be omitted for bars_1m" - ); - - // Round-trip every binary DOUBLE payload bit-exactly via f64::from_le_bytes. - for (prefix, expected_val) in [ - (&b"open==\x10"[..], row.open), - (&b",high==\x10"[..], row.high), - (&b",low==\x10"[..], row.low), - (&b",close==\x10"[..], row.close), - (&b",volume==\x10"[..], row.volume), - ] { - let pos = actual - .windows(prefix.len()) - .position(|w| w == prefix) - .expect("binary double column present"); - let raw: [u8; 8] = actual[pos + prefix.len()..pos + prefix.len() + 8] - .try_into() - .unwrap(); - let decoded = f64::from_le_bytes(raw); - assert_eq!(decoded.to_bits(), expected_val.to_bits()); - } - - // Verify PRE and POST session tags as well. - let mut pre_buf = Vec::new(); - let mut pre_row = row.clone(); - pre_row.session = IntradaySession::Pre; - encode_bar_1m(&mut pre_buf, &pre_row, known_at_micros).unwrap(); - assert!(pre_buf.starts_with(b"bars_1m,listing_id=42,session=PRE,source=eod_unadj ")); - - let mut post_buf = Vec::new(); - let mut post_row = row; - post_row.session = IntradaySession::Post; - encode_bar_1m(&mut post_buf, &post_row, known_at_micros).unwrap(); - assert!(post_buf.starts_with(b"bars_1m,listing_id=42,session=POST,source=eod_unadj ")); -} - -#[test] -fn golden_bytes_encode_fx_1m_matches_ilp_v2_wire_contract() { - let row = Fx1mRow { - pair: "USD.CAD", - ts: 1_736_951_400_000_000, - open: 1.3625, - high: 1.365, - low: 1.36125, - close: 1.364375, - source: "eod", - }; - - let mut actual = Vec::new(); - encode_fx_1m(&mut actual, &row).expect("encode fx_1m"); - - let mut expected = Vec::new(); - expected.extend_from_slice(b"fx_1m,pair=USD.CAD,source=eod "); - expected.extend_from_slice(b"open==\x10"); - expected.extend_from_slice(&1.3625_f64.to_le_bytes()); - expected.extend_from_slice(b",high==\x10"); - expected.extend_from_slice(&1.365_f64.to_le_bytes()); - expected.extend_from_slice(b",low==\x10"); - expected.extend_from_slice(&1.36125_f64.to_le_bytes()); - expected.extend_from_slice(b",close==\x10"); - expected.extend_from_slice(&1.364375_f64.to_le_bytes()); - expected.extend_from_slice(b" 1736951400000000t\n"); - - assert_eq!(actual, expected); - assert!(!actual.windows(8).any(|w| w == b"known_at")); - assert!(!actual.windows(6).any(|w| w == b"volume")); - - for (prefix, expected_val) in [ - (&b"open==\x10"[..], row.open), - (&b",high==\x10"[..], row.high), - (&b",low==\x10"[..], row.low), - (&b",close==\x10"[..], row.close), - ] { - let pos = actual - .windows(prefix.len()) - .position(|w| w == prefix) - .expect("binary double column present"); - let raw: [u8; 8] = actual[pos + prefix.len()..pos + prefix.len() + 8] - .try_into() - .unwrap(); - assert_eq!(f64::from_le_bytes(raw).to_bits(), expected_val.to_bits()); - } -} - -#[test] -fn symbol_escaping_and_non_finite_or_negative_ts_atomic_rejection() { - // Escaping: space, comma, '=', backslash, LF, CR, and UTF-8. - let raw_sym = "a b,c=d\\e\nf\rg caf\u{00e9}"; - let expected_escaped = b"a\\ b\\,c\\=d\\\\e\\\nf\\\rg\\ caf\xc3\xa9"; - - let mut bar = sample_bar(7, 0); - bar.source = raw_sym; - let mut bar_buf = Vec::new(); - encode_bar_1m(&mut bar_buf, &bar, -500).expect("encode escaped bar_1m"); - let mut expected_prefix = b"bars_1m,listing_id=7,session=RTH,source=".to_vec(); - expected_prefix.extend_from_slice(expected_escaped); - expected_prefix.push(b' '); - assert!(bar_buf.starts_with(&expected_prefix)); - assert!(bar_buf.ends_with(b",known_at=-500t 0t\n")); - - let fx = Fx1mRow { - pair: raw_sym, - source: "src=1,2 3\\4\n\r", - ..sample_fx("USD.CAD", 123) - }; - let mut fx_buf = Vec::new(); - encode_fx_1m(&mut fx_buf, &fx).expect("encode escaped fx_1m"); - let mut expected_fx_prefix = b"fx_1m,pair=".to_vec(); - expected_fx_prefix.extend_from_slice(expected_escaped); - expected_fx_prefix.extend_from_slice(b",source=src\\=1\\,2\\ 3\\\\4\\\n\\\r "); - assert!(fx_buf.starts_with(&expected_fx_prefix)); - assert!(fx_buf.ends_with(b" 123t\n")); - - // Non-finite doubles in a late field must fail atomically and preserve existing buffer bytes. - let sentinel = b"EXISTING_PREFIX_BYTES".to_vec(); - for bad_val in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { - let mut buf = sentinel.clone(); - let mut bad_bar = sample_bar(1, 100); - bad_bar.volume = bad_val; - let err = encode_bar_1m(&mut buf, &bad_bar, 200).unwrap_err(); - assert!(matches!( - err, - IlpEncodeError::NonFiniteDouble { - field: "volume", - .. - } - )); - assert_eq!(buf, sentinel, "buffer must be untouched on bars_1m error"); - - let mut fx_buf = sentinel.clone(); - let mut bad_fx = sample_fx("USD.CAD", 100); - bad_fx.close = bad_val; - let err = encode_fx_1m(&mut fx_buf, &bad_fx).unwrap_err(); - assert!(matches!( - err, - IlpEncodeError::NonFiniteDouble { field: "close", .. } - )); - assert_eq!(fx_buf, sentinel, "buffer must be untouched on fx_1m error"); - } - - // Negative designated timestamp fails atomically. - let mut buf = sentinel.clone(); - let bad_ts_bar = sample_bar(1, -1); - assert_eq!( - encode_bar_1m(&mut buf, &bad_ts_bar, 500), - Err(IlpEncodeError::NegativeTimestamp { - field: "ts", - value: -1 - }) - ); - assert_eq!(buf, sentinel); - - let mut fx_buf = sentinel.clone(); - let bad_ts_fx = sample_fx("USD.CAD", -42); - assert_eq!( - encode_fx_1m(&mut fx_buf, &bad_ts_fx), - Err(IlpEncodeError::NegativeTimestamp { - field: "ts", - value: -42 - }) - ); - assert_eq!(fx_buf, sentinel); - - // Empty symbol fails atomically. - let mut buf = sentinel.clone(); - let mut empty_src = sample_bar(1, 100); - empty_src.source = ""; - assert_eq!( - encode_bar_1m(&mut buf, &empty_src, 100), - Err(IlpEncodeError::EmptySymbol { field: "source" }) - ); - assert_eq!(buf, sentinel); - - let mut fx_buf = sentinel.clone(); - let empty_pair = sample_fx("", 100); - assert_eq!( - encode_fx_1m(&mut fx_buf, &empty_pair), - Err(IlpEncodeError::EmptySymbol { field: "pair" }) - ); - assert_eq!(fx_buf, sentinel); -} - -#[test] -fn sharded_writer_routes_deterministically_preserves_per_key_order_and_handles_embedded_lf() { - // Build a finite double whose IEEE-754 little-endian representation contains 0x0a (LF). - let double_with_lf = f64::from_le_bytes([0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x24, 0x40]); - assert!(double_with_lf.is_finite()); - - let num_shards = 4usize; - let num_listings = 64i32; - let rows_per_listing = 20usize; // 64 * 20 = 1,280 interleaved rows >= 1,000 - - let mut input_rows: Vec<(Bar1mRow, i64)> = - Vec::with_capacity(num_listings as usize * rows_per_listing + 2); - for step in 0..rows_per_listing { - for listing_id in 1..=num_listings { - let ts = 1_700_000_000_000_000 + (step as i64) * 60_000_000 + i64::from(listing_id); - let known_at = ts + 60_000_000; - let mut row = sample_bar(listing_id, ts); - row.open = double_with_lf; - row.close = 100.0 + (step as f64) * 0.25 + f64::from(listing_id) * 0.01; - row.volume = (step as f64 + 1.0) * 100.0; - if step == 5 && listing_id == 10 { - row.source = "eod\nwith_lf"; - } - input_rows.push((row, known_at)); - } - } - // Append a second version of an existing (ts, listing_id) to verify DEDUP UPSERT ordering. - let (mut revision, rev_known_at) = input_rows[0].clone(); - revision.close += 0.5; - input_rows.push((revision, rev_known_at + 120_000_000)); - - // Expected per-listing byte sequences in input order. - let mut expected_by_listing: HashMap>> = HashMap::new(); - for (row, known_at) in &input_rows { - let mut line = Vec::new(); - encode_bar_1m(&mut line, row, *known_at).unwrap(); - expected_by_listing.entry(row.key).or_default().push(line); - } - - let opts = IlpWriterOptions { - max_batch_bytes: 2048, - max_batch_rows: 17, - }; - - let run_once = || { - let mut sinks: Vec> = (0..num_shards).map(|_| Vec::new()).collect(); - let stats = { - let sink_refs: Vec<&mut Vec> = sinks.iter_mut().collect(); - let mut writer = IlpShardedWriter::new(sink_refs, opts).unwrap(); - for (row, known_at) in &input_rows { - writer.write_bar_1m(row, *known_at).unwrap(); - } - writer.finish().unwrap() - }; - (sinks, stats) - }; - - let (sinks_a, stats_a) = run_once(); - let (sinks_b, stats_b) = run_once(); - - // Byte-for-byte determinism across runs. - assert_eq!(sinks_a, sinks_b); - assert_eq!(stats_a, stats_b); - - // Conservation invariants. - assert_eq!(stats_a.rows, input_rows.len()); - assert_eq!( - stats_a.per_shard_rows.iter().sum::(), - stats_a.rows - ); - let total_sink_bytes: usize = sinks_a.iter().map(Vec::len).sum(); - assert_eq!(stats_a.bytes, total_sink_bytes); - - // Parse every shard with the binary-aware ILP v2 splitter and verify routing + order. - let mut seen_shard_for_listing: HashMap = HashMap::new(); - let mut observed_by_listing: HashMap>> = HashMap::new(); - let mut total_parsed_rows = 0usize; - - for (shard_idx, shard_bytes) in sinks_a.iter().enumerate() { - let parsed = split_ilp_v2_rows(shard_bytes); - assert_eq!(parsed.len(), stats_a.per_shard_rows[shard_idx]); - total_parsed_rows += parsed.len(); - - for row_bytes in parsed { - let id_bytes = extract_tag_value(row_bytes, b",listing_id="); - let listing_id: i32 = std::str::from_utf8(id_bytes).unwrap().parse().unwrap(); - assert_eq!( - shard_idx, - shard_for_listing_id(listing_id, num_shards), - "listing_id {listing_id} routed to unexpected shard" - ); - if let Some(&prev_shard) = seen_shard_for_listing.get(&listing_id) { - assert_eq!(prev_shard, shard_idx); - } else { - seen_shard_for_listing.insert(listing_id, shard_idx); - } - observed_by_listing - .entry(listing_id) - .or_default() - .push(row_bytes.to_vec()); - } - } - - assert_eq!(total_parsed_rows, input_rows.len()); - assert_eq!(seen_shard_for_listing.len(), num_listings as usize); - assert_eq!(observed_by_listing, expected_by_listing); - - // Repeated FX pairs across batches route by `pair` and preserve order. - let pairs = ["USD.CAD", "EUR.USD", "GBP.USD", "USD.JPY", "AUD.USD", "USD.CHF"]; - let mut fx_sinks: Vec> = (0..num_shards).map(|_| Vec::new()).collect(); - let mut expected_by_pair: HashMap<&str, Vec>> = HashMap::new(); - let fx_stats = { - let refs: Vec<&mut Vec> = fx_sinks.iter_mut().collect(); - let mut writer = IlpShardedWriter::new( - refs, - IlpWriterOptions { - max_batch_bytes: 512, - max_batch_rows: 3, - }, - ) - .unwrap(); - for step in 0..10 { - for &pair in &pairs { - let mut row = sample_fx(pair, 1_700_000_000_000_000 + step * 60_000_000); - row.close += (step as f64) * 0.0001; - let mut line = Vec::new(); - encode_fx_1m(&mut line, &row).unwrap(); - expected_by_pair.entry(pair).or_default().push(line); - writer.write_fx_1m(&row).unwrap(); - } - } - writer.finish().unwrap() - }; - assert_eq!(fx_stats.rows, pairs.len() * 10); - assert_eq!(fx_stats.per_shard_rows.iter().sum::(), fx_stats.rows); - assert_eq!(fx_stats.bytes, fx_sinks.iter().map(Vec::len).sum::()); - - let mut observed_by_pair: HashMap>> = HashMap::new(); - for (shard_idx, shard_bytes) in fx_sinks.iter().enumerate() { - for row_bytes in split_ilp_v2_rows(shard_bytes) { - let pair_str = - std::str::from_utf8(extract_tag_value(row_bytes, b",pair=")).unwrap(); - assert_eq!(shard_idx, shard_for_fx_pair(pair_str, num_shards)); - observed_by_pair - .entry(pair_str.to_string()) - .or_default() - .push(row_bytes.to_vec()); - } - } - for (pair, expected) in expected_by_pair { - assert_eq!(observed_by_pair.get(pair).unwrap(), &expected); - } -} - -#[test] -fn batching_limits_oversized_lines_remainder_and_whole_line_boundaries() { - let row = sample_bar(42, 1_736_951_400_000_000); - let known_at = 1_736_951_460_000_000; - let mut one_line = Vec::new(); - encode_bar_1m(&mut one_line, &row, known_at).unwrap(); - let row_len = one_line.len(); - - // 1. Exact row limit (max_batch_rows = 3) + 1 remainder row. - let sink = RecordingSink::new(); - let mut writer = IlpShardedWriter::new( - vec![sink.clone()], - IlpWriterOptions { - max_batch_bytes: 100_000, - max_batch_rows: 3, - }, - ) - .unwrap(); - for _ in 0..7 { - writer.write_bar_1m(&row, known_at).unwrap(); - } - let stats = writer.finish().unwrap(); - let writes = sink.captured_writes(); - assert_eq!(writes.len(), 3); - assert_eq!(stats.flushes, 3); - assert_eq!(stats.rows, 7); - assert_eq!(stats.bytes, 7 * row_len); - assert_eq!(sink.captured_flushes(), 1); - assert_eq!(split_ilp_v2_rows(&writes[0]).len(), 3); - assert_eq!(split_ilp_v2_rows(&writes[1]).len(), 3); - assert_eq!(split_ilp_v2_rows(&writes[2]).len(), 1); - assert!(writes.iter().all(|w| w.ends_with(b"\n"))); - - // 2. Exact byte limit (2 * row_len): flushes after every 2 rows. - let sink = RecordingSink::new(); - let mut writer = IlpShardedWriter::new( - vec![sink.clone()], - IlpWriterOptions { - max_batch_bytes: 2 * row_len, - max_batch_rows: 100, - }, - ) - .unwrap(); - for _ in 0..5 { - writer.write_bar_1m(&row, known_at).unwrap(); - } - let stats = writer.finish().unwrap(); - let writes = sink.captured_writes(); - assert_eq!(writes.len(), 3); - assert_eq!(stats.flushes, 3); - assert_eq!(split_ilp_v2_rows(&writes[0]).len(), 2); - assert_eq!(split_ilp_v2_rows(&writes[1]).len(), 2); - assert_eq!(split_ilp_v2_rows(&writes[2]).len(), 1); - - // 3. Next line would exceed remaining capacity (2 * row_len - 1): flushes before appending. - let sink = RecordingSink::new(); - let mut writer = IlpShardedWriter::new( - vec![sink.clone()], - IlpWriterOptions { - max_batch_bytes: 2 * row_len - 1, - max_batch_rows: 100, - }, - ) - .unwrap(); - for _ in 0..3 { - writer.write_bar_1m(&row, known_at).unwrap(); - } - let stats = writer.finish().unwrap(); - let writes = sink.captured_writes(); - assert_eq!(writes.len(), 3); - assert_eq!(stats.flushes, 3); - for w in &writes { - assert_eq!(w.len(), row_len); - assert_eq!(split_ilp_v2_rows(w).len(), 1); - } - - // 4. Individually oversized line (max_batch_bytes = 16 < row_len) sent alone, never split. - let sink = RecordingSink::new(); - let mut writer = IlpShardedWriter::new( - vec![sink.clone()], - IlpWriterOptions { - max_batch_bytes: 16, - max_batch_rows: 100, - }, - ) - .unwrap(); - writer.write_bar_1m(&row, known_at).unwrap(); - writer.write_bar_1m(&row, known_at).unwrap(); - let stats = writer.finish().unwrap(); - let writes = sink.captured_writes(); - assert_eq!(writes.len(), 2); - assert_eq!(stats.flushes, 2); - assert_eq!(writes[0], one_line); - assert_eq!(writes[1], one_line); -} - -#[test] -fn writer_validates_options_handles_zero_rows_and_poisons_on_io_error() { - assert!(matches!( - IlpShardedWriter::>::new(Vec::new(), IlpWriterOptions::default()), - Err(IlpWriterError::EmptySinks) - )); - assert!(matches!( - IlpShardedWriter::new( - vec![Vec::new()], - IlpWriterOptions { - max_batch_bytes: 0, - max_batch_rows: 10, - } - ), - Err(IlpWriterError::ZeroMaxBatchBytes) - )); - assert!(matches!( - IlpShardedWriter::new( - vec![Vec::new()], - IlpWriterOptions { - max_batch_bytes: 1024, - max_batch_rows: 0, - } - ), - Err(IlpWriterError::ZeroMaxBatchRows) - )); - - // Zero rows written -> clean stats and sink flush still called. - let s0 = RecordingSink::new(); - let s1 = RecordingSink::new(); - let writer = IlpShardedWriter::new(vec![s0.clone(), s1.clone()], IlpWriterOptions::default()) - .unwrap(); - let stats = writer.finish().unwrap(); - assert_eq!(stats.rows, 0); - assert_eq!(stats.bytes, 0); - assert_eq!(stats.flushes, 0); - assert_eq!(stats.per_shard_rows, vec![0, 0]); - assert_eq!(s0.captured_flushes(), 1); - assert_eq!(s1.captured_flushes(), 1); - - // Find a listing_id that routes to shard 2 out of 4. - let target_listing = (1..1000) - .find(|&id| shard_for_listing_id(id, 4) == 2) - .expect("listing for shard 2"); - - // Failing write_all on shard 2 after 1 successful batch: returns Io { shard: 2 } and poisons. - let failing_sink = RecordingSink::failing_on_write(1); - let mut writer = IlpShardedWriter::new( - vec![ - RecordingSink::new(), - RecordingSink::new(), - failing_sink.clone(), - RecordingSink::new(), - ], - IlpWriterOptions { - max_batch_bytes: 100_000, - max_batch_rows: 1, - }, - ) - .unwrap(); - let row = sample_bar(target_listing, 1_700_000_000_000_000); - writer.write_bar_1m(&row, 1_700_000_060_000_000).unwrap(); - let err = writer - .write_bar_1m(&row, 1_700_000_120_000_000) - .unwrap_err(); - assert!(matches!(err, IlpWriterError::Io { shard: 2, .. })); - - // Subsequent writes and finish fail with Poisoned { failed_shard: 2 }. - let err2 = writer - .write_bar_1m(&row, 1_700_000_180_000_000) - .unwrap_err(); - assert!(matches!(err2, IlpWriterError::Poisoned { failed_shard: 2 })); - let err3 = writer.write_fx_1m(&sample_fx("USD.CAD", 100)).unwrap_err(); - assert!(matches!(err3, IlpWriterError::Poisoned { failed_shard: 2 })); - let err4 = writer.finish().unwrap_err(); - assert!(matches!(err4, IlpWriterError::Poisoned { failed_shard: 2 })); - assert_eq!(failing_sink.captured_writes().len(), 1); - - // Failing flush() during finish() reports shard index. - let mut writer = IlpShardedWriter::new( - vec![RecordingSink::new(), RecordingSink::failing_on_flush()], - IlpWriterOptions::default(), - ) - .unwrap(); - writer.write_bar_1m(&row, 1_700_000_060_000_000).unwrap(); - let flush_err = writer.finish().unwrap_err(); - assert!(matches!(flush_err, IlpWriterError::Io { shard: 1, .. })); - - // Encode error does not poison the writer. - let mut sinks = [Vec::new(), Vec::new()]; - let stats = { - let refs: Vec<&mut Vec> = sinks.iter_mut().collect(); - let mut writer = IlpShardedWriter::new(refs, IlpWriterOptions::default()).unwrap(); - let mut bad = sample_bar(42, 100); - bad.close = f64::NAN; - assert!(matches!( - writer.write_bar_1m(&bad, 200), - Err(IlpWriterError::Encode(IlpEncodeError::NonFiniteDouble { - field: "close", - .. - })) - )); - writer - .write_bar_1m(&sample_bar(42, 100), 200) - .expect("writer still healthy after encode error"); - writer.finish().unwrap() - }; - assert_eq!(stats.rows, 1); - - // Sanity check FNV-1a 64-bit known test vector ("foobar" -> 0x85944171f73967e8). - assert_eq!(fnv1a_64(b"foobar"), 0x8594_4171_f739_67e8); -} - -#[test] -fn partial_write_failure_poisons_writer_and_freezes_sink_bytes() { - let target_listing = (1..1000) - .find(|&id| shard_for_listing_id(id, 4) == 2) - .expect("listing for shard 2"); - let other_listing = (1..1000) - .find(|&id| shard_for_listing_id(id, 4) == 0) - .expect("listing for shard 0"); - - let row1 = sample_bar(target_listing, 1_700_000_000_000_000); - let row2 = sample_bar(target_listing, 1_700_000_060_000_000); - let other_row = sample_bar(other_listing, 1_700_000_000_000_000); - let known_at = 1_700_000_120_000_000; - - let mut expected_row1 = Vec::new(); - encode_bar_1m(&mut expected_row1, &row1, known_at).unwrap(); - let mut expected_row2 = Vec::new(); - encode_bar_1m(&mut expected_row2, &row2, known_at).unwrap(); - let partial_prefix_len = 32; - assert!(partial_prefix_len < expected_row2.len()); - - let healthy_sink = RecordingSink::new(); - let failing_sink = RecordingSink::failing_after_partial_write(1, partial_prefix_len); - let mut writer = IlpShardedWriter::new( - vec![ - healthy_sink.clone(), - RecordingSink::new(), - failing_sink.clone(), - RecordingSink::new(), - ], - IlpWriterOptions { - max_batch_bytes: 100_000, - max_batch_rows: 1, - }, - ) - .unwrap(); - - // First batch on shard 2 succeeds completely. - writer.write_bar_1m(&row1, known_at).unwrap(); - - // Second batch on shard 2 writes a partial prefix, then hits BrokenPipe. - let err = writer.write_bar_1m(&row2, known_at).unwrap_err(); - assert!(matches!(err, IlpWriterError::Io { shard: 2, .. })); - - let mut expected_captured = expected_row1.clone(); - expected_captured.extend_from_slice(&expected_row2[..partial_prefix_len]); - assert_eq!(failing_sink.captured_bytes(), expected_captured); - - // Subsequent writes (both on the failed shard and on another shard) and finish() are rejected, - // leaving all sink bytes frozen without replaying or appending anything. - assert!(matches!( - writer.write_bar_1m(&row2, known_at), - Err(IlpWriterError::Poisoned { failed_shard: 2 }) - )); - assert!(matches!( - writer.write_bar_1m(&other_row, known_at), - Err(IlpWriterError::Poisoned { failed_shard: 2 }) - )); - assert!(matches!( - writer.write_fx_1m(&sample_fx("USD.CAD", 100)), - Err(IlpWriterError::Poisoned { failed_shard: 2 }) - )); - assert!(matches!( - writer.finish(), - Err(IlpWriterError::Poisoned { failed_shard: 2 }) - )); - - assert_eq!(failing_sink.captured_bytes(), expected_captured); - assert!(healthy_sink.captured_bytes().is_empty()); -} - -#[test] -fn golden_bytes_literal_ieee754_little_endian_without_to_le_bytes() { - let row = Bar1mRow { - key: 7, - ts: 1_700_000_000_000_000, - session_date: 20_000, - open: 1.0, - high: 2.0, - low: 0.5, - close: 1.5, - volume: 0.0, - session: IntradaySession::Rth, - source: BARS_1M_SOURCE_EOD, - }; - let mut actual = Vec::new(); - encode_bar_1m(&mut actual, &row, 1_700_000_060_000_000).unwrap(); - - // Hand-written little-endian IEEE-754 bytes (no f64::to_le_bytes): - // 1.0 -> 00 00 00 00 00 00 f0 3f - // 2.0 -> 00 00 00 00 00 00 00 40 - // 0.5 -> 00 00 00 00 00 00 e0 3f - // 1.5 -> 00 00 00 00 00 00 f8 3f - // 0.0 -> 00 00 00 00 00 00 00 00 - let mut expected: Vec = Vec::new(); - expected.extend_from_slice(b"bars_1m,listing_id=7,session=RTH,source=eod_unadj "); - expected.extend_from_slice(b"open==\x10\x00\x00\x00\x00\x00\x00\xf0\x3f"); - expected.extend_from_slice(b",high==\x10\x00\x00\x00\x00\x00\x00\x00\x40"); - expected.extend_from_slice(b",low==\x10\x00\x00\x00\x00\x00\x00\xe0\x3f"); - expected.extend_from_slice(b",close==\x10\x00\x00\x00\x00\x00\x00\xf8\x3f"); - expected.extend_from_slice(b",volume==\x10\x00\x00\x00\x00\x00\x00\x00\x00"); - expected.extend_from_slice(b",known_at=1700000060000000t 1700000000000000t\n"); - - assert_eq!(actual, expected); -} diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index a16d00be..0fffc229 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -2,41 +2,19 @@ pub mod adj; pub mod bars; -pub mod bars_1m; pub mod bench; -pub mod bson_ceo_posts; -pub mod bson_ceo_shorts; -pub mod bson_eod_intraday; pub mod bson_eod_prices; -pub mod bson_qm_actions; -pub mod bson_qm_events; -pub mod bson_qm_financials; -pub mod bson_qm_intraday; -pub mod bson_qm_prices; -pub mod bson_stream; -pub mod bson_te_data; -pub mod bson_te_market_data; pub mod cli; pub mod corporate_actions; pub mod events; -pub mod fundamentals; pub mod fx; -pub mod ilp; -pub mod ilp_send; -pub mod macro_series; -pub mod mongo_safety; -pub mod mongo_stream; pub mod parquet_adj; pub mod parquet_bars; pub mod parquet_corporate_actions; pub mod parquet_events; -pub mod parquet_fundamentals; pub mod parquet_fx; -pub mod parquet_macro; -pub mod parquet_posts; mod parquet_publish; pub mod parquet_shorts; -pub mod posts; pub mod provider_mapping; pub mod session_close; pub mod shorts; @@ -50,79 +28,10 @@ pub use bars::{ build_bars_1d, Bar1dRow, Bars1dBuild, Bars1dStats, BarsError, EodDailyBar, QmRawVolume, VolumeMismatchSample, MAX_MISMATCH_SAMPLES, }; -pub use bars_1m::{ - build_bars_1m, check_session_closes, check_session_closes_against_bars_1d, Bar1mRow, - Bars1mBuild, Bars1mError, Bars1mStats, DailySessionClose, EodIntradayBar, IntradaySession, - SessionCloseCheck, SessionCloseCutoffPolicy, SessionCloseMismatchSample, SessionCloseStats, - BARS_1M_SOURCE_EOD, BARS_1M_SOURCE_QM, RTH_END_MINUTE_ET, RTH_START_MINUTE_ET, -}; -pub use bson_ceo_posts::{ - decode_ceo_posts_buffer, decode_ceo_posts_bytes, decode_ceo_posts_doc, - BsonCeoPostsDecodeStats, BsonCeoPostsError, CeoPostsFieldNames, CeoPostsTimestampUnit, -}; -pub use bson_ceo_shorts::{ - decode_ceo_shorts_buffer, decode_ceo_shorts_bytes, decode_ceo_shorts_doc, - BsonCeoShortsDecodeStats, BsonCeoShortsError, CeoShortsFieldNames, DEFAULT_KEY_FIELD, - DEFAULT_REPORT_DATE_FIELD, -}; -pub use bson_eod_intraday::{ - decode_eod_intraday_buffer, decode_eod_intraday_bytes, decode_eod_intraday_doc, - BsonEodIntradayDecodeStats, BsonEodIntradayError, RawEodIntradayBar, -}; pub use bson_eod_prices::{ decode_eod_price_buffer, decode_eod_price_bytes, decode_eod_price_doc, iter_raw_bson_docs, BsonEodDecodeStats, BsonEodPriceError, RawBsonDocIter, RawEodDailyBar, }; -pub use bson_qm_actions::{ - decode_qm_dividend_buffer, decode_qm_dividend_bytes, decode_qm_dividend_doc, - decode_qm_split_buffer, decode_qm_split_bytes, decode_qm_split_doc, BsonQmActionDecodeStats, - BsonQmActionError, RawQmDividend, RawQmSplit, FIELD_DATE, FIELD_DECLARED, FIELD_DIVIDEND_CASH, - FIELD_DIVIDEND_CURRENCY, FIELD_QM_SEARCH_CODE, FIELD_SPLIT_RATIO, FIELD_USD_FX_RATE, -}; -pub use bson_qm_events::{ - decode_qm_earning_buffer, decode_qm_earning_bytes, decode_qm_earning_doc, - decode_qm_filing_buffer, decode_qm_filing_bytes, decode_qm_filing_doc, - BsonQmEarningsDecodeStats, BsonQmEventsError, BsonQmFilingsDecodeStats, QmEarningsFieldNames, - QmFilingsFieldNames, RawQmEarning, RawQmFiling, DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD, - DEFAULT_EARNINGS_KEY_FIELD, DEFAULT_EARNINGS_REPORT_DATE_FIELD, DEFAULT_FILINGS_KEY_FIELD, - DEFAULT_FILINGS_TIMEFILED_FIELD, -}; -pub use bson_qm_financials::{ - decode_qm_financials_buffer, decode_qm_financials_bytes, decode_qm_financials_doc, - BsonQmFinancialsDecodeStats, BsonQmFinancialsError, QmFinancialsFieldNames, - QmFinancialsFiscalPeriod, DEFAULT_QM_FINANCIALS_KEY_FIELD, - DEFAULT_QM_FINANCIALS_PERIOD_END_FIELD, DEFAULT_QM_FINANCIALS_REPORT_DATE_FIELD, - DEFAULT_QM_FINANCIALS_REPORT_PERIOD_FIELD, -}; -pub use bson_qm_prices::{ - decode_qm_price_buffer, decode_qm_price_bytes, decode_qm_price_doc, BsonQmPriceDecodeStats, - BsonQmPriceError, RawQmPrice, FIELD_SHARE_VOLUME, -}; -pub use bson_stream::{ - decode_ceo_posts_chunks, decode_ceo_posts_stream, decode_ceo_shorts_chunks, - decode_ceo_shorts_stream, decode_eod_intraday_chunks, decode_eod_intraday_stream, - decode_eod_price_chunks, decode_eod_price_stream, decode_qm_dividend_chunks, - decode_qm_dividend_stream, decode_qm_earnings_chunks, decode_qm_earnings_stream, - decode_qm_filings_chunks, decode_qm_filings_stream, decode_qm_financials_chunks, - decode_qm_financials_stream, decode_qm_intraday_chunks, decode_qm_intraday_stream, - decode_qm_price_chunks, decode_qm_price_stream, decode_qm_split_chunks, - decode_qm_split_stream, decode_te_data_chunks, decode_te_data_stream, - decode_te_market_data_chunks, decode_te_market_data_stream, - BsonCeoPostsStreamError, BsonCeoShortsStreamError, BsonQmEventsStreamError, - BsonQmFinancialsStreamError, BsonStreamError, BsonStreamOptions, RawBsonChunk, - RawBsonChunkReader, DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES, -}; -pub use bson_te_data::{ - decode_te_data_buffer, decode_te_data_bytes, decode_te_data_doc, BsonTeDataDecodeStats, - BsonTeDataError, TeDataPoint, -}; -pub use bson_te_market_data::{ - decode_te_market_data_buffer, decode_te_market_data_bytes, decode_te_market_data_doc, - te_epoch_i64_to_session_date, BsonTeMarketDataDecodeStats, BsonTeMarketDataError, FIELD_DAILY, - FIELD_MONTHLY, FIELD_POINT_C, FIELD_POINT_H, FIELD_POINT_L, FIELD_POINT_O, FIELD_POINT_T, - FIELD_TE_SYMBOL, MILLIS_PER_DAY as TE_MILLIS_PER_DAY, SECONDS_PER_DAY as TE_SECONDS_PER_DAY, - TE_EPOCH_MILLIS_THRESHOLD, -}; pub use corporate_actions::{ build_corporate_actions, CorporateActionError, CorporateActionKind, CorporateActionRow, CorporateActionsBuild, CorporateActionsStats, DelistingOutcomeEvent, DividendActionEvent, @@ -136,59 +45,18 @@ pub use events::{ EVENT_KIND_EARNINGS, EVENT_KIND_FILING, KNOWN_AT_SOURCE_FILING_TIMESTAMP, KNOWN_AT_SOURCE_STATUTORY_LAG, }; -pub use fundamentals::{ - as_of as fundamentals_as_of, build_fundamentals_rows, build_fundamentals_snapshots, - FinancialObservation, FiscalPeriod, FundamentalsBuild, FundamentalsError, FundamentalsFields, - FundamentalsPeriodSlot, FundamentalsRow, FundamentalsSnapshot, FundamentalsStats, - FundamentalsTtm, StatutoryLagVenue, TtmFlowFields, ANNUAL_FILING_LINK_WINDOW_DAYS, - FUNDAMENTALS_FALLBACK_HOUR_ET, FUNDAMENTALS_FALLBACK_MINUTE_ET, - QUARTERLY_FILING_LINK_WINDOW_DAYS, STATUTORY_LAG_TSXV_CSE_ANNUAL_DAYS, - STATUTORY_LAG_TSXV_CSE_QUARTERLY_DAYS, STATUTORY_LAG_US_TSX_ANNUAL_DAYS, - STATUTORY_LAG_US_TSX_QUARTERLY_DAYS, TTM_CONSECUTIVE_QUARTER_MAX_DAYS, - TTM_CONSECUTIVE_QUARTER_MIN_DAYS, TTM_QUARTER_COUNT, -}; pub use fx::{ build_fx_1d, fx_rate_on_or_before, Fx1dBuild, Fx1dRow, Fx1dStats, FxDailyBar, FxSource, FxSourceStats, FX_OVERLAP_REL_TOLERANCE, FX_PAIR_USDCAD, }; -pub use ilp::{ - encode_bar_1m, encode_fx_1m, fnv1a_64, shard_for_fx_pair, shard_for_listing_id, Fx1mRow, - IlpEncodeError, IlpShardedWriter, IlpWriteStats, IlpWriterError, IlpWriterOptions, - DEFAULT_ILP_MAX_BATCH_BYTES, DEFAULT_ILP_MAX_BATCH_ROWS, FNV1A_64_OFFSET_BASIS, - FNV1A_64_PRIME, ILP_V2_DOUBLE_TYPE, TABLE_BARS_1M, TABLE_FX_1M, -}; -pub use ilp_send::{ - discover_ilp_shard_files, format_ilp_send_report, run_send_ilp, send_ilp_shard_files, - tcp_ilp_connector, IlpSendError, IlpSendOp, IlpSendOptions, IlpSendReport, IlpShardFile, - IlpShardSendReport, IlpTcpOptions, IlpTcpSink, SendIlpArgs, DEFAULT_ILP_SEND_BUFFER_BYTES, - DEFAULT_ILP_TCP_CONNECT_TIMEOUT, DEFAULT_ILP_TCP_WRITE_TIMEOUT, -}; -pub use macro_series::{ - build_macro_rows, MacroBuild, MacroBuildStats, MacroError, MacroLagClass, MacroObservation, - MacroRow, GDP65_LAG_DAYS, GDP90_LAG_DAYS, MACRO_KNOWN_AT_SOURCE, MONTHLY_RELEASE_LAG_DAYS, - POLICY_RATE_LAG_DAYS, -}; -pub use mongo_safety::{ - assert_read_only_mongo_uri, is_qa_mongo_target, parse_mongo_target, LocalHosts, - MongoSafetyError, MongoScheme, MongoTarget, MongoTargetHost, ReadOnlyPolicy, - ValidatedReadOnlyMongoUri, DEFAULT_ALLOWED_READ_USER, FORBIDDEN_ADMIN_USER, QA_MONGO_PORT, -}; -pub use mongo_stream::{ - build_filter_document, open_read_only_mongo_from_env, open_read_only_mongo_uri, - FilterDateValue, MongoCliOptions, MongoDateRange, MongoRawDocumentSource, MongoReadSpec, - MongoStreamError, MongoUriSource, RawBsonCursorReader, RawDocumentSource, ReadOnlyMongoClient, - SliceRawDocumentSource, SourceCollection, VecRawDocumentSource, DEFAULT_MONGO_BATCH_SIZE, - DEFAULT_MONGO_URI_ENV, MAX_MONGO_BATCH_SIZE, -}; pub use parquet_adj::{ adj_factors_parquet_schema, write_adj_factors_dataset, AdjFactorsParquetRow, AdjFactorsWriteOptions, AdjFactorsWriteStats, ParquetAdjError, }; pub use parquet_bars::{ - bars_1d_parquet_schema, default_parallel_threads, write_bars_1d_dataset, Bars1dParquetRow, - Bars1dWriteOptions, Bars1dWriteStats, ParquetBarsError, RollbackFailure, - DEFAULT_ROW_GROUP_ROWS, DEFAULT_WRITE_THREADS, DEFAULT_ZSTD_LEVEL, MAX_PARQUET_YEAR, - MIN_PARQUET_YEAR, + 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 parquet_corporate_actions::{ corporate_actions_parquet_schema, write_corporate_actions_dataset, CorporateActionsParquetRow, @@ -199,39 +67,22 @@ pub use parquet_events::{ events_parquet_schema, write_events_dataset, EventsParquetRow, EventsWriteOptions, EventsWriteStats, ParquetEventsError, }; -pub use parquet_fundamentals::{ - fundamentals_pit_parquet_schema, write_fundamentals_pit_dataset, FundamentalsPitLatestPeriod, - FundamentalsPitParquetRow, FundamentalsPitWriteOptions, FundamentalsPitWriteStats, - ParquetFundamentalsError, -}; pub use parquet_fx::{ fx_1d_parquet_schema, write_fx_1d_dataset, Fx1dParquetRow, Fx1dWriteOptions, Fx1dWriteStats, ParquetFxError, }; -pub use parquet_macro::{ - macro_parquet_schema, write_macro_dataset, MacroParquetRow, MacroWriteOptions, MacroWriteStats, - ParquetMacroError, -}; -pub use parquet_posts::{ - posts_to_event_rows, EVENT_KIND_POST, KNOWN_AT_SOURCE_POST_EDITED, - KNOWN_AT_SOURCE_POST_TIMESTAMP, POST_SUBTYPE_NEWSWIRE, POST_SUBTYPE_RETAIL, -}; pub use parquet_shorts::{ shorts_parquet_schema, write_shorts_dataset, ParquetShortsError, ShortsParquetRow, ShortsWriteOptions, ShortsWriteStats, }; -pub use posts::{ - build_posts, CeoPost, PostRow, PostsBuild, PostsError, PostsStats, POSTS_SOURCE_CEO, -}; pub use provider_mapping::{ MappingRange, ProviderMappingCursor, ProviderMappingError, ProviderMappingRow, ProviderMappingTable, }; pub use session_close::{ - et_session_close_utc_micros, utc_micros_to_et_local, EtLocalDateTime, SessionCloseError, - SESSION_CLOSE_MAX_SUPPORTED_DATE, SESSION_CLOSE_MAX_SUPPORTED_YEAR, - SESSION_CLOSE_MIN_SUPPORTED_DATE, SESSION_CLOSE_MIN_SUPPORTED_YEAR, - SESSION_MAX_SUPPORTED_UTC_MICROS, SESSION_MIN_SUPPORTED_UTC_MICROS, + et_session_close_utc_micros, SessionCloseError, SESSION_CLOSE_MAX_SUPPORTED_DATE, + SESSION_CLOSE_MAX_SUPPORTED_YEAR, SESSION_CLOSE_MIN_SUPPORTED_DATE, + SESSION_CLOSE_MIN_SUPPORTED_YEAR, }; pub use shorts::{ add_canadian_business_days, build_shorts, epoch_days_to_ymd, et_to_utc_micros, @@ -264,160 +115,9 @@ pub use curate_events::{ CurateEventsStats, CurateEventsWriteError, CurateEventsWriteReport, }; -pub mod curate_posts; -pub use curate_posts::{ - curate_and_write_posts, curate_posts, CuratePostsError, CuratePostsOutput, CuratePostsStats, - CuratePostsWriteError, CuratePostsWriteReport, -}; - -pub mod curate_fundamentals; -pub use curate_fundamentals::{ - curate_and_write_fundamentals, curate_fundamentals, CurateFundamentalsError, - CurateFundamentalsOutput, CurateFundamentalsStats, CurateFundamentalsWriteError, - CurateFundamentalsWriteReport, -}; - -pub mod curate_macro; -pub use curate_macro::{ - curate_and_write_macro, curate_macro, CurateMacroError, CurateMacroOutput, CurateMacroStats, - CurateMacroWriteError, CurateMacroWriteReport, MacroSeriesTarget, -}; - pub mod curate_fx; pub use curate_fx::{ curate_and_write_fx_1d, curate_fx_1d, fx_1d_utc_day_end_micros, CurateFx1dOutput, CurateFx1dStats, CurateFx1dWriteReport, CurateFxError, CurateFxWriteError, FX_1D_MICROS_PER_DAY, FX_1D_TS_OFFSET_MICROS_FROM_DAY_START, }; - -pub mod curate_adj; -pub use curate_adj::{ - adj_factors_for_bar, curate_adj_factors, curate_adj_factors_as_of, - curate_and_write_adj_factors, curate_and_write_adj_factors_as_of, read_adj_factors_dataset, - read_adj_factors_dataset_as_of, AdjFactorsSnapshot, AdjPointInTimeFence, AdjSnapshotKind, - CurateAdjError, CurateAdjFactorsOutput, CurateAdjFactorsStats, CurateAdjFactorsWriteReport, - CurateAdjReadError, CurateAdjWriteError, ADJ_SNAPSHOT_FORMAT_VERSION, -}; - -pub mod curate_corporate_actions; -pub use curate_corporate_actions::{ - curate_and_write_corporate_actions, curate_corporate_actions, CurateCorporateActionsError, - CurateCorporateActionsOutput, CurateCorporateActionsStats, CurateCorporateActionsWriteError, - CurateCorporateActionsWriteReport, CurateDelistingInput, -}; - -pub mod curate_bars_1m; -pub use curate_bars_1m::{ - check_curated_session_closes, curate_and_write_bars_1m, curate_and_write_bars_1m_from_bson, - curate_bars_1m, CurateBars1mBsonError, CurateBars1mBsonReport, CurateBars1mError, - CurateBars1mOutput, CurateBars1mStats, CurateBars1mWriteError, CurateBars1mWriteReport, -}; - -pub mod curate_qm_bars_1m; -pub use curate_qm_bars_1m::{ - curate_and_write_qm_bars_1m, curate_and_write_qm_bars_1m_from_bson, curate_qm_bars_1m, - CurateQmBars1mBsonError, CurateQmBars1mBsonReport, -}; - -pub mod curate_fx_1m; -pub use curate_fx_1m::{ - build_fx_1m, curate_and_write_fx_1m, curate_and_write_fx_1m_from_bson, CurateFx1mBsonError, - CurateFx1mBsonReport, CurateFx1mOutput, CurateFx1mStats, CurateFx1mWriteReport, - FX_1M_SOURCE_EOD, -}; - -pub mod run_curate_bars; -pub use run_curate_bars::{ - default_curate_bars_threads, format_curate_bars_report, load_listing_currencies_tsv, - load_provider_mapping_tsv, run_curate_bars_1d, run_curate_bars_1d_with_readers, - CurateBars1dArgs, CurateBars1dRunReport, QmVolumeRekeyStats, RunCurateBarsError, - SplitRekeyStats, DEFAULT_CURATE_BARS_REL_TOLERANCE, -}; - -pub mod run_curate_bars_1m; -pub use run_curate_bars_1m::{ - format_curate_bars_1m_report, run_curate_bars_1m, run_curate_bars_1m_with_readers, - CurateBars1mArgs, CurateBars1mRunReport, RunCurateBars1mError, - DEFAULT_BARS_1M_MAPPING_SOURCE, -}; - -pub mod run_curate_fx_1m; -pub use run_curate_fx_1m::{ - format_curate_fx_1m_report, run_curate_fx_1m, run_curate_fx_1m_with_readers, CurateFx1mArgs, - CurateFx1mRunReport, RunCurateFx1mError, -}; - -pub mod run_curate_qm_bars_1m; -pub use run_curate_qm_bars_1m::{ - format_curate_qm_bars_1m_report, run_curate_qm_bars_1m, run_curate_qm_bars_1m_with_readers, - CurateQmBars1mArgs, CurateQmBars1mRunReport, RunCurateQmBars1mError, - DEFAULT_QM_BARS_1M_MAPPING_SOURCE, -}; - -pub mod run_curate_adj; -pub use run_curate_adj::{ - format_curate_adj_report, run_curate_adj_factors, run_curate_adj_factors_fenced, - run_curate_adj_factors_with_readers, CurateAdjFactorsArgs, CurateAdjFactorsRunReport, - RunCurateAdjError, -}; - -pub mod run_curate_corporate_actions; -pub use run_curate_corporate_actions::{ - format_curate_corporate_actions_report, load_delistings_tsv, run_curate_corporate_actions, - run_curate_corporate_actions_with_readers, CurateCorporateActionsArgs, - CurateCorporateActionsRunReport, RunCurateCorporateActionsError, -}; - -pub mod run_curate_fx; -pub use run_curate_fx::{ - format_curate_fx_report, is_supported_te_symbol, run_curate_fx_1d, - run_curate_fx_1d_with_readers, CurateFx1dArgs, CurateFx1dRunReport, RunCurateFxError, - ALLOWED_TE_SYMBOLS, DEFAULT_TE_SYMBOL, EOD_CAD_FOREX_CODE, -}; - -pub mod run_curate_posts; -pub use run_curate_posts::{ - format_curate_posts_report, run_curate_posts, run_curate_posts_with_reader, CuratePostsArgs, - CuratePostsRunReport, RunCuratePostsError, -}; - -pub mod run_curate_fundamentals; -pub use run_curate_fundamentals::{ - format_curate_fundamentals_report, load_listing_venues_tsv, run_curate_fundamentals, - run_curate_fundamentals_with_readers, CurateFundamentalsArgs, CurateFundamentalsFiscalPeriod, - CurateFundamentalsRunReport, RunCurateFundamentalsError, DEFAULT_FUNDAMENTALS_MAPPING_SOURCE, -}; - -pub mod run_curate_macro; -pub use run_curate_macro::{ - format_curate_macro_report, load_macro_series_map_tsv, run_curate_macro, - run_curate_macro_with_readers, CurateMacroArgs, CurateMacroRunReport, MacroSeriesMap, - RunCurateMacroError, MACRO_SERIES_MAP_HEADER, -}; - -pub mod run_curate_shorts; -pub use run_curate_shorts::{ - format_curate_shorts_report, run_curate_shorts, run_curate_shorts_with_reader, - CurateShortsArgs, CurateShortsRunReport, RunCurateShortsError, DEFAULT_MAPPING_SOURCE, -}; - -pub mod run_curate_events; -pub use run_curate_events::{ - format_curate_events_report, run_curate_events, run_curate_events_with_readers, - CurateEventsArgs, CurateEventsRunReport, RunCurateEventsError, DEFAULT_EVENTS_MAPPING_SOURCE, -}; - -pub mod run_mongo; -pub use run_mongo::{ - run_curate_adj_factors_mongo, run_curate_bars_1d_mongo, run_curate_corporate_actions_mongo, - run_curate_events_mongo, run_curate_fx_1d_mongo, run_curate_shorts_mongo, - CurateAdjFactorsMongoArgs, CurateBars1dMongoArgs, CurateCorporateActionsMongoArgs, - CurateEventsMongoArgs, CurateFx1dMongoArgs, CurateShortsMongoArgs, RunMongoCurateError, -}; - -#[cfg(test)] -mod parquet_posts_tests; -#[cfg(test)] -mod posts_tests; -#[cfg(test)] -mod tsv_fixture_tests; diff --git a/tools/curate-etl/src/macro_series.rs b/tools/curate-etl/src/macro_series.rs deleted file mode 100644 index 247ec0d9..00000000 --- a/tools/curate-etl/src/macro_series.rs +++ /dev/null @@ -1,284 +0,0 @@ -//! Pure, in-memory `macro` builder for lagged `teData` regime series (`MacroObservation` + -//! caller-supplied [`MacroLagClass`] → sorted, unique [`MacroRow`]s matching -//! `macro/part.parquet` in `design/DATA-CONTRACTS.md` §1 and §3A). -//! -//! ## Governance & Provenance Assumptions -//! - **Regime-use policy owner:** Quant Research owns which macro indicators are admissible for -//! coarse regime filters and how estimated publication lags are stress-tested. -//! - **Lag-mapping owner:** The caller owns the explicit `(country_iso, indicator) -> Option` -//! lookup. Indicator names are **not** hardcoded here because live TradingEconomics indicator -//! names in `teIndicators` / `teData` are unverified in this crate (unverified assumption). -//! - **Final-revised source data:** `teData` stores `{d, v}` final-revised values only, with no -//! verified release timestamps or historical revision vintages. Every emitted row carries -//! [`MACRO_KNOWN_AT_SOURCE`] (`"publication_lag_estimate"`) and becomes available strictly at -//! its estimated `known_at` (`00:00:00 UTC` on `period_date + lag_days`). -//! -//! ## Builder Rules -//! 1. **Fail-closed mapping & validation:** Each input observation is counted once in -//! [`MacroBuildStats::input`]. Unmapped `(country_iso, indicator)` pairs are skipped first -//! (`skipped_unmapped_indicator`) and never given a default lag. Mapped observations with -//! non-finite `value` (`NaN` / `±inf`) are skipped (`skipped_non_finite_value`). -//! 2. **Deterministic deduplication:** Surviving observations are sorted by -//! `(country_iso, indicator, period_date)`. Bitwise-identical duplicates (`f64::to_bits()`) -//! collapse to one row and count each extra copy in `skipped_duplicate`. Any conflicting value -//! for the same `(country_iso, indicator, period_date)`—including opposite signed zeros (`+0.0` -//! vs. `-0.0`)—fails the build with [`MacroError::ConflictingDuplicate`], independent of input -//! order. -//! 3. **Checked `known_at` arithmetic:** `known_at` is computed as -//! `00:00:00 UTC` on `period_date + lag_days` using checked `i32` date addition and checked -//! `i64` microsecond scaling (`86_400_000_000` µs/day). Overflow returns -//! [`MacroError::KnownAtOverflow`] rather than panicking. -//! 4. **Accounting invariant:** -//! `input == emitted + skipped_unmapped_indicator + skipped_non_finite_value + skipped_duplicate`. - -use std::error::Error; -use std::fmt; - -use crate::shorts::epoch_days_to_ymd; - -/// Locked publication lag (calendar days) for central-bank policy rates (`design/DATA-CONTRACTS.md` §1). -pub const POLICY_RATE_LAG_DAYS: i32 = 1; - -/// Locked publication lag (calendar days) for monthly releases such as CPI / NFP (`design/DATA-CONTRACTS.md` §1). -pub const MONTHLY_RELEASE_LAG_DAYS: i32 = 35; - -/// Locked publication lag (calendar days) for 65-day GDP releases (`design/DATA-CONTRACTS.md` §1). -pub const GDP65_LAG_DAYS: i32 = 65; - -/// Locked publication lag (calendar days) for 90-day GDP releases (`design/DATA-CONTRACTS.md` §1). -pub const GDP90_LAG_DAYS: i32 = 90; - -/// Canonical provenance label written to [`MacroRow::known_at_source`]. -pub const MACRO_KNOWN_AT_SOURCE: &str = "publication_lag_estimate"; - -const MICROS_PER_DAY: i64 = 86_400_000_000; - -/// Caller-assigned publication lag class from `design/DATA-CONTRACTS.md` §1. -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub enum MacroLagClass { - /// Central-bank policy rates (`+1` calendar day). - PolicyRate, - /// Monthly macro releases such as CPI / NFP (`+35` calendar days). - MonthlyRelease, - /// Faster GDP releases (`+65` calendar days). - Gdp65, - /// Conservative / slower GDP releases (`+90` calendar days). - Gdp90, -} - -impl MacroLagClass { - /// Returns the locked publication lag in calendar days. - #[inline] - pub const fn lag_days(self) -> i32 { - match self { - Self::PolicyRate => POLICY_RATE_LAG_DAYS, - Self::MonthlyRelease => MONTHLY_RELEASE_LAG_DAYS, - Self::Gdp65 => GDP65_LAG_DAYS, - Self::Gdp90 => GDP90_LAG_DAYS, - } - } -} - -/// A single raw `teData` macro observation input (BSON-free). -#[derive(Debug, Clone, PartialEq)] -pub struct MacroObservation { - pub country_iso: K, - pub indicator: K, - /// Observation period date as days since `1970-01-01` (UTC Gregorian). - pub period_date: i32, - pub value: f64, -} - -/// A single curated `macro` row matching `macro/part.parquet` in `design/DATA-CONTRACTS.md` §3A, -/// sorted and unique by `(country_iso, indicator, period_date)`. -#[derive(Debug, Clone, PartialEq)] -pub struct MacroRow { - pub country_iso: K, - pub indicator: K, - /// Observation period date as days since `1970-01-01` (UTC Gregorian). - pub period_date: i32, - /// Estimated point-in-time availability timestamp (`00:00:00 UTC` of `period_date + lag_days`) - /// in UTC microseconds since `1970-01-01T00:00:00Z`. - pub known_at: i64, - pub known_at_source: &'static str, - pub value: f64, -} - -/// Summary accounting counters produced alongside [`MacroBuild::rows`]. -/// -/// Conservation invariant: -/// `input == emitted + skipped_unmapped_indicator + skipped_non_finite_value + skipped_duplicate` -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct MacroBuildStats { - pub input: usize, - pub emitted: usize, - pub skipped_unmapped_indicator: usize, - pub skipped_non_finite_value: usize, - pub skipped_duplicate: usize, -} - -/// Output of [`build_macro_rows`]: sorted, unique lagged macro rows and reconciling stats. -#[derive(Debug, Clone, PartialEq)] -pub struct MacroBuild { - pub rows: Vec>, - pub stats: MacroBuildStats, -} - -/// Typed errors returned by [`build_macro_rows`]. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum MacroError { - /// Two or more mapped, finite observations shared `(country_iso, indicator, period_date)` with - /// non-identical `f64::to_bits()` values (including opposite signed zeros `+0.0` vs. `-0.0`). - ConflictingDuplicate { - country_iso: K, - indicator: K, - period_date: i32, - }, - /// Computing `00:00:00 UTC` for `period_date + lag_class.lag_days()` overflowed `i32` day - /// addition or `i64` microsecond scaling. - KnownAtOverflow { - period_date: i32, - lag_class: MacroLagClass, - }, -} - -impl fmt::Display for MacroError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::ConflictingDuplicate { - country_iso, - indicator, - period_date, - } => { - let (y, m, d) = epoch_days_to_ymd(*period_date); - write!( - f, - "conflicting duplicate macro observation for ({country_iso:?}, {indicator:?}, {y:04}-{m:02}-{d:02} [epoch_day={period_date}])" - ) - } - Self::KnownAtOverflow { - period_date, - lag_class, - } => write!( - f, - "known_at timestamp overflow for period_date={period_date} with lag_class={lag_class:?} (+{} days)", - lag_class.lag_days() - ), - } - } -} - -impl Error for MacroError {} - -struct MappedObservation { - country_iso: K, - indicator: K, - period_date: i32, - lag_class: MacroLagClass, - value: f64, -} - -/// Builds sorted, unique lagged `macro` rows from raw observations and a caller-supplied -/// `(country_iso, indicator) -> Option` lookup. -/// -/// The caller lookup `lag_for` must be deterministic/stable for each exact `(country_iso, indicator)` -/// pair. Any permutation of `observations` produces identical `rows` (including `f64` bit patterns) -/// and `stats`, or the same [`MacroError`]. -pub fn build_macro_rows( - observations: I, - lag_for: F, -) -> Result, MacroError> -where - K: Ord, - I: IntoIterator>, - F: Fn(&K, &K) -> Option, -{ - let iter = observations.into_iter(); - let (lower, _) = iter.size_hint(); - let mut stats = MacroBuildStats::default(); - let mut mapped: Vec> = Vec::with_capacity(lower); - - for obs in iter { - stats.input += 1; - - let Some(lag_class) = lag_for(&obs.country_iso, &obs.indicator) else { - stats.skipped_unmapped_indicator += 1; - continue; - }; - - if !obs.value.is_finite() { - stats.skipped_non_finite_value += 1; - continue; - } - - mapped.push(MappedObservation { - country_iso: obs.country_iso, - indicator: obs.indicator, - period_date: obs.period_date, - lag_class, - value: obs.value, - }); - } - - mapped.sort_unstable_by(|a, b| { - a.country_iso - .cmp(&b.country_iso) - .then_with(|| a.indicator.cmp(&b.indicator)) - .then_with(|| a.period_date.cmp(&b.period_date)) - }); - - let mut rows: Vec> = Vec::with_capacity(mapped.len()); - let mut sorted = mapped.into_iter().peekable(); - - while let Some(first) = sorted.next() { - while let Some(next) = sorted.peek() { - if next.country_iso == first.country_iso - && next.indicator == first.indicator - && next.period_date == first.period_date - { - if next.value.to_bits() != first.value.to_bits() { - return Err(MacroError::ConflictingDuplicate { - country_iso: first.country_iso, - indicator: first.indicator, - period_date: first.period_date, - }); - } - stats.skipped_duplicate += 1; - sorted.next(); - } else { - break; - } - } - - let known_at_day = first - .period_date - .checked_add(first.lag_class.lag_days()) - .ok_or(MacroError::KnownAtOverflow { - period_date: first.period_date, - lag_class: first.lag_class, - })?; - let known_at = i64::from(known_at_day) - .checked_mul(MICROS_PER_DAY) - .ok_or(MacroError::KnownAtOverflow { - period_date: first.period_date, - lag_class: first.lag_class, - })?; - - rows.push(MacroRow { - country_iso: first.country_iso, - indicator: first.indicator, - period_date: first.period_date, - known_at, - known_at_source: MACRO_KNOWN_AT_SOURCE, - value: first.value, - }); - } - - stats.emitted = rows.len(); - - Ok(MacroBuild { rows, stats }) -} - -#[cfg(test)] -#[path = "macro_series_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/macro_series_tests.rs b/tools/curate-etl/src/macro_series_tests.rs deleted file mode 100644 index 464f2f56..00000000 --- a/tools/curate-etl/src/macro_series_tests.rs +++ /dev/null @@ -1,601 +0,0 @@ -use super::*; -use crate::split::ymd_to_epoch_days; - -fn day(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).expect("valid test date") -} - -fn obs( - country_iso: &str, - indicator: &str, - period_date: i32, - value: f64, -) -> MacroObservation { - MacroObservation { - country_iso: country_iso.to_string(), - indicator: indicator.to_string(), - period_date, - value, - } -} - -fn assert_accounting_and_order(build: &MacroBuild) { - let s = &build.stats; - assert_eq!(s.emitted, build.rows.len()); - assert_eq!( - s.input, - s.emitted + s.skipped_unmapped_indicator + s.skipped_non_finite_value + s.skipped_duplicate, - "accounting invariant failed: {s:?}" - ); - for pair in build.rows.windows(2) { - assert!( - ( - &pair[0].country_iso, - &pair[0].indicator, - pair[0].period_date - ) < ( - &pair[1].country_iso, - &pair[1].indicator, - pair[1].period_date - ), - "rows must be strictly sorted and unique by (country_iso, indicator, period_date)" - ); - } - for row in &build.rows { - assert_eq!(row.known_at_source, MACRO_KNOWN_AT_SOURCE); - let period_midnight = i64::from(row.period_date) * 86_400_000_000; - assert!( - row.known_at > period_midnight, - "look-ahead violation: known_at {} <= period midnight {}", - row.known_at, - period_midnight - ); - } -} - -fn assert_rows_bit_eq(left: &[MacroRow], right: &[MacroRow]) { - assert_eq!(left.len(), right.len()); - for (a, b) in left.iter().zip(right.iter()) { - assert_eq!(a.country_iso, b.country_iso); - assert_eq!(a.indicator, b.indicator); - assert_eq!(a.period_date, b.period_date); - assert_eq!(a.known_at, b.known_at); - assert_eq!(a.known_at_source, b.known_at_source); - assert_eq!(a.value.to_bits(), b.value.to_bits()); - } -} - -#[test] -fn lag_classes_produce_exact_utc_midnights() { - assert_eq!(POLICY_RATE_LAG_DAYS, 1); - assert_eq!(MONTHLY_RELEASE_LAG_DAYS, 35); - assert_eq!(GDP65_LAG_DAYS, 65); - assert_eq!(GDP90_LAG_DAYS, 90); - assert_eq!(MacroLagClass::PolicyRate.lag_days(), 1); - assert_eq!(MacroLagClass::MonthlyRelease.lag_days(), 35); - assert_eq!(MacroLagClass::Gdp65.lag_days(), 65); - assert_eq!(MacroLagClass::Gdp90.lag_days(), 90); - assert_eq!(MACRO_KNOWN_AT_SOURCE, "publication_lag_estimate"); - - let jan31 = day(2024, 1, 31); - let inputs = vec![ - obs("US", "ind_policy", jan31, 5.50), - obs("US", "ind_monthly", jan31, 3.10), - obs("US", "ind_gdp65", jan31, 2.25), - obs("US", "ind_gdp90", jan31, 1.80), - ]; - - let build = build_macro_rows(inputs, |country, indicator| { - match (country.as_str(), indicator.as_str()) { - ("US", "ind_policy") => Some(MacroLagClass::PolicyRate), - ("US", "ind_monthly") => Some(MacroLagClass::MonthlyRelease), - ("US", "ind_gdp65") => Some(MacroLagClass::Gdp65), - ("US", "ind_gdp90") => Some(MacroLagClass::Gdp90), - _ => None, - } - }) - .expect("lag class fixture should succeed"); - - assert_accounting_and_order(&build); - assert_eq!( - build.stats, - MacroBuildStats { - input: 4, - emitted: 4, - skipped_unmapped_indicator: 0, - skipped_non_finite_value: 0, - skipped_duplicate: 0, - } - ); - - // Sorted alphabetically by indicator: ind_gdp65, ind_gdp90, ind_monthly, ind_policy - let expected: [(&str, i64, f64); 4] = [ - ("ind_gdp65", 1_712_275_200_000_000, 2.25), // 2024-04-05T00:00:00Z - ("ind_gdp90", 1_714_435_200_000_000, 1.80), // 2024-04-30T00:00:00Z - ("ind_monthly", 1_709_683_200_000_000, 3.10), // 2024-03-06T00:00:00Z (+35d across 2024-02-29) - ("ind_policy", 1_706_745_600_000_000, 5.50), // 2024-02-01T00:00:00Z - ]; - - assert_eq!(build.rows.len(), expected.len()); - for (row, (indicator, known_at, value)) in build.rows.iter().zip(expected.iter()) { - assert_eq!(row.country_iso, "US"); - assert_eq!(row.indicator, *indicator); - assert_eq!(row.period_date, jan31); - assert_eq!(row.known_at, *known_at); - assert_eq!(row.known_at_source, MACRO_KNOWN_AT_SOURCE); - assert_eq!(row.value.to_bits(), value.to_bits()); - } -} - -#[test] -fn skips_unmapped_and_non_finite_once() { - let d = day(2024, 6, 30); - let inputs = vec![ - // Mapped indicator for US, valid value -> emitted - obs("US", "cpi_yoy", d, 3.0), - // Same indicator in unmapped country -> skipped_unmapped_indicator (pair-keyed lookup) - obs("CA", "cpi_yoy", d, 2.7), - // Unmapped indicator with NaN -> counted once as skipped_unmapped_indicator (precedence) - obs("CA", "cpi_yoy", day(2024, 7, 31), f64::NAN), - // Mapped pair with NaN, +inf, -inf -> skipped_non_finite_value - obs("US", "cpi_yoy", day(2024, 7, 31), f64::NAN), - obs("US", "cpi_yoy", day(2024, 8, 31), f64::INFINITY), - obs("US", "cpi_yoy", day(2024, 9, 30), f64::NEG_INFINITY), - ]; - - let build = build_macro_rows(inputs, |country, indicator| { - if country == "US" && indicator == "cpi_yoy" { - Some(MacroLagClass::MonthlyRelease) - } else { - None - } - }) - .expect("skips should not fail the build"); - - assert_accounting_and_order(&build); - assert_eq!( - build.stats, - MacroBuildStats { - input: 6, - emitted: 1, - skipped_unmapped_indicator: 2, - skipped_non_finite_value: 3, - skipped_duplicate: 0, - } - ); - assert_eq!(build.rows[0].country_iso, "US"); - assert_eq!(build.rows[0].indicator, "cpi_yoy"); - assert_eq!(build.rows[0].period_date, d); - assert_eq!(build.rows[0].value.to_bits(), 3.0_f64.to_bits()); -} - -#[test] -fn sorts_deduplicates_and_accounts_for_all_inputs() { - let empty: Vec> = Vec::new(); - let empty_build = - build_macro_rows(empty, |_, _| Some(MacroLagClass::PolicyRate)).expect("empty succeeds"); - assert!(empty_build.rows.is_empty()); - assert_eq!(empty_build.stats, MacroBuildStats::default()); - assert_accounting_and_order(&empty_build); - - let d1 = day(2024, 1, 31); - let d2 = day(2024, 2, 29); - - let fixture_a = vec![ - obs("US", "rate", d2, 5.25), - obs("CA", "gdp", d1, 1.50), - obs("US", "rate", d1, 5.50), - obs("CA", "gdp", d1, 1.50), // exact duplicate - obs("CA", "gdp", d1, 1.50), // second exact duplicate - obs("US", "unmapped_ind", d1, 42.0), - obs("US", "rate", day(2024, 3, 31), f64::NAN), - obs("CA", "rate", d1, -0.0), // signed zero preserved identically - obs("CA", "rate", d1, -0.0), // bitwise-identical -0.0 duplicate collapses - ]; - - let fixture_b = vec![ - obs("CA", "rate", d1, -0.0), - obs("US", "rate", day(2024, 3, 31), f64::NAN), - obs("CA", "gdp", d1, 1.50), - obs("US", "unmapped_ind", d1, 42.0), - obs("US", "rate", d1, 5.50), - obs("CA", "rate", d1, -0.0), - obs("CA", "gdp", d1, 1.50), - obs("US", "rate", d2, 5.25), - obs("CA", "gdp", d1, 1.50), - ]; - - let lag_for = - |country: &String, indicator: &String| match (country.as_str(), indicator.as_str()) { - ("CA", "gdp") => Some(MacroLagClass::Gdp65), - ("CA", "rate") | ("US", "rate") => Some(MacroLagClass::PolicyRate), - _ => None, - }; - - let build_a = build_macro_rows(fixture_a, lag_for).expect("fixture_a succeeds"); - let build_b = build_macro_rows(fixture_b, lag_for).expect("fixture_b succeeds"); - - assert_accounting_and_order(&build_a); - assert_accounting_and_order(&build_b); - assert_rows_bit_eq(&build_a.rows, &build_b.rows); - assert_eq!(build_a.stats, build_b.stats); - assert_eq!( - build_a.stats, - MacroBuildStats { - input: 9, - emitted: 4, - skipped_unmapped_indicator: 1, - skipped_non_finite_value: 1, - skipped_duplicate: 3, - } - ); - - let keys: Vec<(&str, &str, i32)> = build_a - .rows - .iter() - .map(|r| (r.country_iso.as_str(), r.indicator.as_str(), r.period_date)) - .collect(); - assert_eq!( - keys, - vec![ - ("CA", "gdp", d1), - ("CA", "rate", d1), - ("US", "rate", d1), - ("US", "rate", d2), - ] - ); - assert_eq!(build_a.rows[1].value.to_bits(), (-0.0_f64).to_bits()); -} - -#[test] -fn rejects_conflicting_duplicates_in_either_order() { - let d = day(2024, 3, 31); - let lag_for = |_: &String, _: &String| Some(MacroLagClass::MonthlyRelease); - - // Distinct finite values in both orders - let err_ab = build_macro_rows( - vec![obs("US", "cpi", d, 3.1), obs("US", "cpi", d, 3.2)], - lag_for, - ) - .expect_err("distinct duplicate values must fail"); - let err_ba = build_macro_rows( - vec![obs("US", "cpi", d, 3.2), obs("US", "cpi", d, 3.1)], - lag_for, - ) - .expect_err("distinct duplicate values in reverse order must fail"); - - let expected = MacroError::ConflictingDuplicate { - country_iso: "US".to_string(), - indicator: "cpi".to_string(), - period_date: d, - }; - assert_eq!(err_ab, expected); - assert_eq!(err_ba, expected); - assert!(err_ab.to_string().contains("2024-03-31")); - - // Opposite signed zeros (+0.0 vs -0.0) in both orders - let err_pos_neg = build_macro_rows( - vec![obs("CA", "cpi", d, 0.0), obs("CA", "cpi", d, -0.0)], - lag_for, - ) - .expect_err("+0.0 vs -0.0 must be treated as conflicting"); - let err_neg_pos = build_macro_rows( - vec![obs("CA", "cpi", d, -0.0), obs("CA", "cpi", d, 0.0)], - lag_for, - ) - .expect_err("-0.0 vs +0.0 must be treated as conflicting"); - - let expected_zero = MacroError::ConflictingDuplicate { - country_iso: "CA".to_string(), - indicator: "cpi".to_string(), - period_date: d, - }; - assert_eq!(err_pos_neg, expected_zero); - assert_eq!(err_neg_pos, expected_zero); -} - -#[test] -fn returns_typed_known_at_overflow() { - // 1. i32 day addition overflow: i32::MAX + 1 - let err_add = build_macro_rows(vec![obs("US", "rate", i32::MAX, 5.0)], |_, _| { - Some(MacroLagClass::PolicyRate) - }) - .expect_err("i32::MAX + PolicyRate must overflow"); - assert_eq!( - err_add, - MacroError::KnownAtOverflow { - period_date: i32::MAX, - lag_class: MacroLagClass::PolicyRate, - } - ); - assert!(err_add.to_string().contains("known_at timestamp overflow")); - - // 2. i64 microsecond multiplication overflow after valid i32 addition: - // (106_751_991 + 1) * 86_400_000_000 > i64::MAX - let err_mul = build_macro_rows(vec![obs("US", "rate", 106_751_991, 5.0)], |_, _| { - Some(MacroLagClass::PolicyRate) - }) - .expect_err("106_751_991 + PolicyRate must overflow microsecond scaling"); - assert_eq!( - err_mul, - MacroError::KnownAtOverflow { - period_date: 106_751_991, - lag_class: MacroLagClass::PolicyRate, - } - ); - - // 3. Adjacent representable PolicyRate case succeeds: - // (106_751_990 + 1) * 86_400_000_000 == 9_223_372_020_000_000_000 <= i64::MAX - let ok = build_macro_rows(vec![obs("US", "rate", 106_751_990, 5.0)], |_, _| { - Some(MacroLagClass::PolicyRate) - }) - .expect("adjacent representable policy-rate date must succeed"); - assert_accounting_and_order(&ok); - assert_eq!(ok.rows.len(), 1); - assert_eq!(ok.rows[0].period_date, 106_751_990); - assert_eq!(ok.rows[0].known_at, 106_751_991_i64 * 86_400_000_000); -} - -// ---- QA edge cases (T-172) ---- - -// `build_macro_rows` passes `&K`, so with `K = String` the lookup must take `&String`. -#[allow(clippy::ptr_arg)] -fn qa_lag(country: &String, indicator: &String) -> Option { - match (country.as_str(), indicator.as_str()) { - ("CA", "gdp") => Some(MacroLagClass::Gdp90), - ("CA", "rate") => Some(MacroLagClass::PolicyRate), - ("US", "cpi") => Some(MacroLagClass::MonthlyRelease), - ("US", "gdp") => Some(MacroLagClass::Gdp65), - _ => None, - } -} - -fn permutations(items: &[T]) -> Vec> { - if items.len() <= 1 { - return vec![items.to_vec()]; - } - let mut out = Vec::new(); - for i in 0..items.len() { - let mut rest = items.to_vec(); - let head = rest.remove(i); - for mut tail in permutations(&rest) { - tail.insert(0, head.clone()); - out.push(tail); - } - } - out -} - -#[test] -fn every_permutation_of_mixed_fixture_yields_identical_build() { - let d1 = day(2023, 12, 31); - let d2 = day(2024, 3, 31); - let base = vec![ - obs("US", "cpi", d2, 3.5), - obs("CA", "gdp", d1, -0.0), - obs("CA", "gdp", d1, -0.0), - obs("US", "cpi", d1, f64::NAN), - obs("XX", "cpi", d1, 1.0), - obs("CA", "rate", d2, 5.0), - obs("US", "gdp", d1, 2.1), - ]; - - let reference = build_macro_rows(base.clone(), qa_lag).expect("reference build"); - assert_accounting_and_order(&reference); - assert_eq!( - reference.stats, - MacroBuildStats { - input: 7, - emitted: 4, - skipped_unmapped_indicator: 1, - skipped_non_finite_value: 1, - skipped_duplicate: 1, - } - ); - - let perms = permutations(&base); - assert_eq!(perms.len(), 5040); - for perm in perms { - let build = build_macro_rows(perm, qa_lag).expect("permutation build"); - assert_eq!(build.stats, reference.stats); - assert_rows_bit_eq(&build.rows, &reference.rows); - } -} - -#[test] -fn conflict_anywhere_in_duplicate_group_fails_in_every_order() { - let d = day(2024, 1, 31); - let base = vec![ - obs("US", "cpi", d, 3.1), - obs("US", "cpi", d, 3.1), - obs("US", "cpi", d, 3.2), - obs("CA", "rate", d, 5.0), - ]; - let expected = MacroError::ConflictingDuplicate { - country_iso: "US".to_string(), - indicator: "cpi".to_string(), - period_date: d, - }; - for perm in permutations(&base) { - assert_eq!(build_macro_rows(perm, qa_lag), Err(expected.clone())); - } -} - -#[test] -fn non_finite_copy_of_a_key_is_skipped_not_treated_as_conflict() { - let d = day(2024, 1, 31); - for inputs in [ - vec![obs("US", "cpi", d, f64::NAN), obs("US", "cpi", d, 3.1)], - vec![obs("US", "cpi", d, 3.1), obs("US", "cpi", d, f64::INFINITY)], - ] { - let build = build_macro_rows(inputs, qa_lag).expect("non-finite copy is skipped"); - assert_accounting_and_order(&build); - assert_eq!(build.rows.len(), 1); - assert_eq!(build.rows[0].value.to_bits(), 3.1_f64.to_bits()); - assert_eq!(build.stats.skipped_non_finite_value, 1); - assert_eq!(build.stats.skipped_duplicate, 0); - } -} - -#[test] -fn unmapped_duplicates_and_conflicts_are_counted_as_unmapped_only() { - let d = day(2024, 1, 31); - let build = build_macro_rows( - vec![ - obs("XX", "cpi", d, 1.0), - obs("XX", "cpi", d, 1.0), - obs("XX", "cpi", d, 2.0), - ], - qa_lag, - ) - .expect("unmapped conflicts must not error"); - assert!(build.rows.is_empty()); - assert_eq!( - build.stats, - MacroBuildStats { - input: 3, - emitted: 0, - skipped_unmapped_indicator: 3, - skipped_non_finite_value: 0, - skipped_duplicate: 0, - } - ); -} - -#[test] -fn lookup_receives_country_then_indicator() { - let d = day(2024, 1, 31); - let build = build_macro_rows( - vec![obs("US", "cpi", d, 3.0), obs("cpi", "US", d, 4.0)], - |country: &String, indicator: &String| { - (country == "US" && indicator == "cpi").then_some(MacroLagClass::MonthlyRelease) - }, - ) - .expect("build"); - assert_eq!(build.rows.len(), 1); - assert_eq!(build.rows[0].country_iso, "US"); - assert_eq!(build.rows[0].indicator, "cpi"); - assert_eq!(build.stats.skipped_unmapped_indicator, 1); -} - -#[test] -fn sorts_by_country_before_indicator_and_applies_per_pair_lag() { - let d = day(2024, 1, 31); - let build = build_macro_rows( - vec![ - obs("US", "cpi", d, 3.0), - obs("CA", "rate", d, 5.0), - obs("US", "gdp", d, 2.0), - obs("CA", "gdp", d, 1.0), - ], - qa_lag, - ) - .expect("build"); - assert_accounting_and_order(&build); - let got: Vec<(&str, &str, i64)> = build - .rows - .iter() - .map(|r| (r.country_iso.as_str(), r.indicator.as_str(), r.known_at)) - .collect(); - let micros = |days: i32| i64::from(days) * 86_400_000_000; - assert_eq!( - got, - vec![ - ("CA", "gdp", micros(day(2024, 4, 30))), - ("CA", "rate", micros(day(2024, 2, 1))), - ("US", "cpi", micros(day(2024, 3, 6))), - ("US", "gdp", micros(day(2024, 4, 5))), - ] - ); -} - -#[test] -fn pre_epoch_period_dates_produce_correct_known_at() { - let dec31_1969 = day(1969, 12, 31); - assert_eq!(dec31_1969, -1); - let build = build_macro_rows( - vec![ - obs("CA", "rate", dec31_1969, 7.5), - obs("US", "cpi", day(1950, 1, 31), 1.2), - ], - qa_lag, - ) - .expect("pre-epoch dates are valid"); - assert_accounting_and_order(&build); - // 1969-12-31 + 1d = 1970-01-01T00:00:00Z - assert_eq!(build.rows[0].known_at, 0); - // 1950-01-31 + 35d = 1950-03-07T00:00:00Z - assert_eq!( - build.rows[1].known_at, - i64::from(day(1950, 3, 7)) * 86_400_000_000 - ); - assert_eq!(build.rows[1].known_at, -625_536_000_000_000); -} - -#[test] -fn negative_microsecond_overflow_is_typed_error() { - let err = build_macro_rows(vec![obs("US", "cpi", i32::MIN, 1.0)], qa_lag) - .expect_err("i32::MIN days scaled to micros underflows i64"); - assert_eq!( - err, - MacroError::KnownAtOverflow { - period_date: i32::MIN, - lag_class: MacroLagClass::MonthlyRelease, - } - ); -} - -#[test] -fn overflow_boundary_for_each_lag_class() { - // Largest representable known_at day is i64::MAX / 86_400_000_000 = 106_751_991. - let max_day: i32 = 106_751_991; - for class in [ - MacroLagClass::PolicyRate, - MacroLagClass::MonthlyRelease, - MacroLagClass::Gdp65, - MacroLagClass::Gdp90, - ] { - let ok_date = max_day - class.lag_days(); - let ok = build_macro_rows(vec![obs("US", "x", ok_date, 1.0)], |_, _| Some(class)) - .expect("boundary date succeeds"); - assert_eq!(ok.rows[0].known_at, i64::from(max_day) * 86_400_000_000); - - let err = build_macro_rows(vec![obs("US", "x", ok_date + 1, 1.0)], |_, _| Some(class)) - .expect_err("one day past boundary overflows"); - assert_eq!( - err, - MacroError::KnownAtOverflow { - period_date: ok_date + 1, - lag_class: class, - } - ); - } -} - -#[test] -fn borrowed_str_keys_are_supported() { - let d = day(2024, 1, 31); - let inputs: Vec> = vec![ - MacroObservation { - country_iso: "US", - indicator: "cpi", - period_date: d, - value: 3.0, - }, - MacroObservation { - country_iso: "CA", - indicator: "rate", - period_date: d, - value: 5.0, - }, - ]; - let build = build_macro_rows(inputs, |c: &&str, i: &&str| match (*c, *i) { - ("US", "cpi") => Some(MacroLagClass::MonthlyRelease), - ("CA", "rate") => Some(MacroLagClass::PolicyRate), - _ => None, - }) - .expect("build"); - assert_accounting_and_order(&build); - assert_eq!(build.rows[0].country_iso, "CA"); - assert_eq!(build.rows[1].country_iso, "US"); -} diff --git a/tools/curate-etl/src/main.rs b/tools/curate-etl/src/main.rs index e01d58a2..fc5eca9e 100644 --- a/tools/curate-etl/src/main.rs +++ b/tools/curate-etl/src/main.rs @@ -4,44 +4,14 @@ use std::env; use std::process::ExitCode; use curate_etl::bench::{ - run_adj_benchmark, run_bars_1m_benchmark, run_bars_benchmark, run_bson_eod_prices_benchmark, - run_bson_qm_actions_benchmark, run_bson_stream_benchmark, run_corporate_actions_benchmark, - run_curate_adj_benchmark, run_curate_adj_cmd_benchmark, run_curate_bars_benchmark, - run_curate_bars_cmd_benchmark, run_curate_corporate_actions_benchmark, - run_curate_corporate_actions_cmd_benchmark, run_curate_events_benchmark, - run_curate_events_cmd_benchmark, run_curate_fx_benchmark, run_curate_fx_cmd_benchmark, - run_curate_shorts_benchmark, run_curate_shorts_command_benchmark, run_events_benchmark, - run_fundamentals_benchmark, run_fx_benchmark, run_ilp_bars_1m_benchmark, - run_mongo_stream_benchmark, run_parquet_adj_benchmark, - run_parquet_bars_benchmark, - run_parquet_corporate_actions_benchmark, run_parquet_events_benchmark, - run_parquet_fx_benchmark, run_parquet_shorts_benchmark, run_provider_mapping_benchmark, - run_shorts_benchmark, run_split_benchmark, + run_adj_benchmark, run_bars_benchmark, run_bson_eod_prices_benchmark, + run_corporate_actions_benchmark, run_curate_bars_benchmark, run_curate_events_benchmark, + run_curate_fx_benchmark, run_curate_shorts_benchmark, run_events_benchmark, run_fx_benchmark, + run_parquet_adj_benchmark, run_parquet_bars_benchmark, run_parquet_corporate_actions_benchmark, + run_parquet_events_benchmark, run_parquet_fx_benchmark, run_parquet_shorts_benchmark, + run_provider_mapping_benchmark, run_shorts_benchmark, run_split_benchmark, }; use curate_etl::cli::{format_usage, format_usage_stderr, parse_args, CliAction}; -use curate_etl::ilp_send::{format_ilp_send_report, run_send_ilp}; -use curate_etl::run_curate_adj::{ - format_curate_adj_report, run_curate_adj_factors, run_curate_adj_factors_fenced, -}; -use curate_etl::run_curate_bars::{format_curate_bars_report, run_curate_bars_1d}; -use curate_etl::run_curate_bars_1m::{format_curate_bars_1m_report, run_curate_bars_1m}; -use curate_etl::run_curate_corporate_actions::{ - format_curate_corporate_actions_report, run_curate_corporate_actions, -}; -use curate_etl::run_curate_events::{format_curate_events_report, run_curate_events}; -use curate_etl::run_curate_fundamentals::{ - format_curate_fundamentals_report, run_curate_fundamentals, -}; -use curate_etl::run_curate_fx::{format_curate_fx_report, run_curate_fx_1d}; -use curate_etl::run_curate_fx_1m::{format_curate_fx_1m_report, run_curate_fx_1m}; -use curate_etl::run_curate_macro::{format_curate_macro_report, run_curate_macro}; -use curate_etl::run_curate_posts::{format_curate_posts_report, run_curate_posts}; -use curate_etl::run_curate_qm_bars_1m::{format_curate_qm_bars_1m_report, run_curate_qm_bars_1m}; -use curate_etl::run_curate_shorts::{format_curate_shorts_report, run_curate_shorts}; -use curate_etl::run_mongo::{ - run_curate_adj_factors_mongo, run_curate_bars_1d_mongo, run_curate_corporate_actions_mongo, - run_curate_events_mongo, run_curate_fx_1d_mongo, run_curate_shorts_mongo, -}; const NAME: &str = env!("CARGO_PKG_NAME"); const VERSION: &str = env!("CARGO_PKG_VERSION"); @@ -58,230 +28,6 @@ fn main() -> ExitCode { println!("{NAME} {VERSION}"); ExitCode::SUCCESS } - Ok(CliAction::CurateBars1d(curate_args)) => match run_curate_bars_1d(&curate_args) { - Ok(report) => { - println!("{}", format_curate_bars_report(&report)); - ExitCode::SUCCESS - } - Err(err) => { - eprintln!("error: {err}"); - ExitCode::FAILURE - } - }, - Ok(CliAction::CurateBars1dMongo(curate_args)) => { - match run_curate_bars_1d_mongo(&curate_args) { - Ok(report) => { - println!("{}", format_curate_bars_report(&report)); - ExitCode::SUCCESS - } - Err(err) => { - eprintln!("error: {err}"); - ExitCode::FAILURE - } - } - } - Ok(CliAction::CurateAdjFactors(curate_args)) => { - match run_curate_adj_factors(&curate_args) { - Ok(report) => { - println!("{}", format_curate_adj_report(&report)); - ExitCode::SUCCESS - } - Err(err) => { - eprintln!("error: {err}"); - ExitCode::FAILURE - } - } - } - Ok(CliAction::CurateAdjFactorsFenced(curate_args, fence)) => { - match run_curate_adj_factors_fenced(&curate_args, Some(fence)) { - Ok(report) => { - println!("{}", format_curate_adj_report(&report)); - ExitCode::SUCCESS - } - Err(err) => { - eprintln!("error: {err}"); - ExitCode::FAILURE - } - } - } - Ok(CliAction::CurateAdjFactorsMongo(curate_args)) => { - match run_curate_adj_factors_mongo(&curate_args) { - Ok(report) => { - println!("{}", format_curate_adj_report(&report)); - ExitCode::SUCCESS - } - Err(err) => { - eprintln!("error: {err}"); - ExitCode::FAILURE - } - } - } - Ok(CliAction::CurateCorporateActions(curate_args)) => { - match run_curate_corporate_actions(&curate_args) { - Ok(report) => { - println!("{}", format_curate_corporate_actions_report(&report)); - ExitCode::SUCCESS - } - Err(err) => { - eprintln!("error: {err}"); - ExitCode::FAILURE - } - } - } - Ok(CliAction::CurateCorporateActionsMongo(curate_args)) => { - match run_curate_corporate_actions_mongo(&curate_args) { - Ok(report) => { - println!("{}", format_curate_corporate_actions_report(&report)); - ExitCode::SUCCESS - } - Err(err) => { - eprintln!("error: {err}"); - ExitCode::FAILURE - } - } - } - Ok(CliAction::CurateFx1d(curate_args)) => match run_curate_fx_1d(&curate_args) { - Ok(report) => { - println!("{}", format_curate_fx_report(&report)); - ExitCode::SUCCESS - } - Err(err) => { - eprintln!("error: {err}"); - ExitCode::FAILURE - } - }, - Ok(CliAction::CurateFx1dMongo(curate_args)) => { - match run_curate_fx_1d_mongo(&curate_args) { - Ok(report) => { - println!("{}", format_curate_fx_report(&report)); - ExitCode::SUCCESS - } - Err(err) => { - eprintln!("error: {err}"); - ExitCode::FAILURE - } - } - } - Ok(CliAction::CurateShorts(curate_args)) => match run_curate_shorts(&curate_args) { - Ok(report) => { - println!("{}", format_curate_shorts_report(&report)); - ExitCode::SUCCESS - } - Err(err) => { - eprintln!("error: {err}"); - ExitCode::FAILURE - } - }, - Ok(CliAction::CurateShortsMongo(curate_args)) => { - match run_curate_shorts_mongo(&curate_args) { - Ok(report) => { - println!("{}", format_curate_shorts_report(&report)); - ExitCode::SUCCESS - } - Err(err) => { - eprintln!("error: {err}"); - ExitCode::FAILURE - } - } - } - Ok(CliAction::CurateEvents(curate_args)) => match run_curate_events(&curate_args) { - Ok(report) => { - println!("{}", format_curate_events_report(&report)); - ExitCode::SUCCESS - } - Err(err) => { - eprintln!("error: {err}"); - ExitCode::FAILURE - } - }, - Ok(CliAction::CurateEventsMongo(curate_args)) => { - match run_curate_events_mongo(&curate_args) { - Ok(report) => { - println!("{}", format_curate_events_report(&report)); - ExitCode::SUCCESS - } - Err(err) => { - eprintln!("error: {err}"); - ExitCode::FAILURE - } - } - } - Ok(CliAction::CurateBars1m(curate_args)) => match run_curate_bars_1m(&curate_args) { - Ok(report) => { - println!("{}", format_curate_bars_1m_report(&report)); - ExitCode::SUCCESS - } - Err(err) => { - eprintln!("error: {err}"); - ExitCode::FAILURE - } - }, - Ok(CliAction::CurateQmBars1m(curate_args)) => match run_curate_qm_bars_1m(&curate_args) { - Ok(report) => { - println!("{}", format_curate_qm_bars_1m_report(&report)); - ExitCode::SUCCESS - } - Err(err) => { - let msg = err.to_string().replace('\r', "\\r").replace('\n', "\\n"); - eprintln!("error: {msg}"); - ExitCode::FAILURE - } - }, - Ok(CliAction::CurateFx1m(curate_args)) => match run_curate_fx_1m(&curate_args) { - Ok(report) => { - println!("{}", format_curate_fx_1m_report(&report)); - ExitCode::SUCCESS - } - Err(err) => { - eprintln!("error: {err}"); - ExitCode::FAILURE - } - }, - Ok(CliAction::CuratePosts(curate_args)) => match run_curate_posts(&curate_args) { - Ok(report) => { - println!("{}", format_curate_posts_report(&report)); - ExitCode::SUCCESS - } - Err(err) => { - eprintln!("error: {err}"); - ExitCode::FAILURE - } - }, - Ok(CliAction::CurateFundamentals(curate_args)) => { - match run_curate_fundamentals(&curate_args) { - Ok(report) => { - println!("{}", format_curate_fundamentals_report(&report)); - ExitCode::SUCCESS - } - Err(err) => { - eprintln!("error: {err}"); - ExitCode::FAILURE - } - } - } - Ok(CliAction::CurateMacro(curate_args)) => match run_curate_macro(&curate_args) { - Ok(report) => { - println!("{}", format_curate_macro_report(&report)); - ExitCode::SUCCESS - } - Err(err) => { - eprintln!("error: {err}"); - ExitCode::FAILURE - } - }, - Ok(CliAction::SendIlp(send_args)) => match run_send_ilp(&send_args) { - Ok(report) => { - println!("{}", format_ilp_send_report(&report)); - ExitCode::SUCCESS - } - Err(err) => { - eprintln!("error: {err}"); - if let Some(partial) = err.partial_report() { - eprintln!("{}", format_ilp_send_report(partial)); - } - ExitCode::FAILURE - } - }, Ok(CliAction::BenchSplit(rows)) => { let report = match run_split_benchmark(rows) { Ok(report) => report, @@ -419,78 +165,6 @@ fn main() -> ExitCode { ); ExitCode::SUCCESS } - Ok(CliAction::BenchBars1m(rows)) => { - let report = match run_bars_1m_benchmark(rows) { - Ok(report) => report, - Err(err) => { - eprintln!("error: bars_1m benchmark failed: {err}"); - return ExitCode::FAILURE; - } - }; - println!("curate-etl bench-bars-1m"); - println!( - " input: rows={} daily_closes={} splits={} keys={}", - report.rows, report.daily_rows_in, report.split_event_count, report.key_count - ); - println!( - " build: rows_out={} keys_out={} (pre={} rth={} post={}) build={:.2} ms check={:.2} ms total={:.2} ms throughput={:.0} rows/s latency={:.2} ns/row checksum=0x{:016x}", - report.rows_out, - report.keys_out, - report.build_stats.pre_rows_out, - report.build_stats.rth_rows_out, - report.build_stats.post_rows_out, - report.build_elapsed_ms, - report.check_elapsed_ms, - report.total_elapsed_ms, - report.rows_per_sec, - report.ns_per_row, - report.checksum - ); - println!( - " stats: invalid_ohlc={} inconsistent_ohlc={} invalid_vol={} ts_oor={} dup_collapsed={} dup_conflict={} rth_sessions={} checked={} within_tol={} mismatched={} unchecked={} max_rel_diff={:.6} samples={}", - report.build_stats.dropped_invalid_ohlc, - report.build_stats.dropped_inconsistent_ohlc, - report.build_stats.dropped_invalid_volume, - report.build_stats.dropped_ts_out_of_range, - report.build_stats.duplicate_collapsed, - report.build_stats.duplicate_conflict_dropped, - report.close_stats.rth_sessions, - report.close_stats.checked, - report.close_stats.within_tolerance, - report.close_stats.mismatched, - report.close_stats.unchecked, - report.close_stats.max_rel_diff, - report.mismatch_samples_out - ); - ExitCode::SUCCESS - } - Ok(CliAction::BenchIlpBars1m(rows)) => { - let report = match run_ilp_bars_1m_benchmark(rows) { - Ok(report) => report, - Err(err) => { - eprintln!("error: ilp bars_1m benchmark failed: {err}"); - return ExitCode::FAILURE; - } - }; - println!("curate-etl bench-ilp-bars-1m"); - println!( - " input: rows={} keys={} shards={}", - report.rows, report.key_count, report.shards - ); - println!( - " output: rows_encoded={} bytes={} flushes={} per_shard_rows={:?}", - report.rows_encoded, report.bytes, report.flushes, report.per_shard_rows - ); - println!( - " perf: elapsed={:.2} ms throughput={:.0} rows/s latency={:.2} ns/row size={:.2} bytes/row write={:.2} MB/s", - report.elapsed_ms, - report.rows_per_sec, - report.ns_per_row, - report.bytes_per_row, - report.mb_per_sec - ); - ExitCode::SUCCESS - } Ok(CliAction::BenchFx(rows)) => { let report = run_fx_benchmark(rows); println!("curate-etl bench-fx"); @@ -595,51 +269,6 @@ fn main() -> ExitCode { ); ExitCode::SUCCESS } - Ok(CliAction::BenchFundamentals(rows)) => { - let report = match run_fundamentals_benchmark(rows) { - Ok(report) => report, - Err(err) => { - eprintln!("error: fundamentals benchmark failed: {err}"); - return ExitCode::FAILURE; - } - }; - println!("curate-etl bench-fundamentals"); - println!( - " input: rows={} filings={} keys={}", - report.rows, report.filings_in, report.key_count - ); - println!( - " build: rows_out={} keys_out={} snapshots_out={} rows={:.2} ms snapshots={:.2} ms total={:.2} ms throughput={:.0} rows/s latency={:.2} ns/row checksum=0x{:016x}", - report.rows_out, - report.keys_out, - report.snapshots_out, - report.rows_elapsed_ms, - report.snapshots_elapsed_ms, - report.total_elapsed_ms, - report.rows_per_sec, - report.ns_per_row, - report.checksum - ); - println!( - " stats: linked={} statutory_lag={} dup_collapsed={} dup_conflict={} obs_unknown_key={} obs_non_finite={} obs_oor={} obs_rd_le_pe={} obs_unanchored={} obs_stale_est={} filings_eligible={} filings_non_periodic={} filings_bad_ts={} filings_oor={} filings_before_pe={}", - report.stats.rows_linked_to_filing, - report.stats.rows_statutory_lag_estimate, - report.stats.duplicate_collapsed, - report.stats.duplicate_conflict_dropped, - report.stats.observations_dropped_unknown_key, - report.stats.observations_dropped_non_finite, - report.stats.observations_dropped_date_out_of_range, - report.stats.observations_dropped_report_date_not_after_period_end, - report.stats.observations_dropped_unanchored_vintage, - report.stats.observations_dropped_stale_estimate, - report.stats.filings_eligible, - report.stats.filings_ignored_non_periodic, - report.stats.filings_dropped_invalid_timestamp, - report.stats.filings_dropped_date_out_of_range, - report.stats.filings_dropped_before_period_end - ); - ExitCode::SUCCESS - } Ok(CliAction::BenchProviderMapping(lookups)) => { let report = match run_provider_mapping_benchmark(lookups) { Ok(report) => report, @@ -874,118 +503,6 @@ fn main() -> ExitCode { ); ExitCode::SUCCESS } - Ok(CliAction::BenchBsonQmActions(rows)) => { - let report = run_bson_qm_actions_benchmark(rows); - println!("curate-etl bench-bson-qm-actions"); - println!( - " input: rows={} splits={} dividends={} bytes={}", - report.rows, report.split_rows, report.dividend_rows, report.bytes - ); - println!( - " splits: decoded={} noop_ratio_one={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={})", - report.split_stats.decoded, - report.split_stats.split_noop_ratio_one, - report.split_stats.rejected_total(), - report.split_stats.rejected_missing_field, - report.split_stats.rejected_empty_field, - report.split_stats.rejected_wrong_type, - report.split_stats.rejected_malformed_date, - report.split_stats.rejected_invalid_number, - report.split_stats.rejected_corrupt_document - ); - println!( - " dividends: decoded={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={})", - report.dividend_stats.decoded, - report.dividend_stats.rejected_total(), - report.dividend_stats.rejected_missing_field, - report.dividend_stats.rejected_empty_field, - report.dividend_stats.rejected_wrong_type, - report.dividend_stats.rejected_malformed_date, - report.dividend_stats.rejected_invalid_number, - report.dividend_stats.rejected_corrupt_document - ); - println!( - " perf: elapsed={:.2} ms throughput={:.0} docs/s scan={:.2} MB/s latency={:.2} ns/doc checksum=0x{:016x}", - report.elapsed_ms, - report.docs_per_sec, - report.mb_per_sec, - report.ns_per_doc, - report.checksum - ); - ExitCode::SUCCESS - } - Ok(CliAction::BenchBsonStream(rows)) => { - let report = match run_bson_stream_benchmark(rows) { - Ok(report) => report, - Err(err) => { - eprintln!("error: bson-stream benchmark failed: {err}"); - return ExitCode::FAILURE; - } - }; - println!("curate-etl bench-bson-stream"); - println!(" input: rows={} bytes={}", report.rows, report.bytes); - println!( - " decode: decoded={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={}) checksum=0x{:016x}", - report.stats.decoded, - report.stats.rejected_total(), - report.stats.rejected_missing_field, - report.stats.rejected_empty_field, - report.stats.rejected_wrong_type, - report.stats.rejected_malformed_date, - report.stats.rejected_invalid_number, - report.stats.rejected_corrupt_document, - report.checksum - ); - println!( - " buffer: elapsed={:.2} ms throughput={:.0} rows/s scan={:.2} MiB/s", - report.buffer_elapsed_ms, report.buffer_rows_per_sec, report.buffer_mib_per_sec - ); - println!( - " stream: elapsed={:.2} ms throughput={:.0} rows/s scan={:.2} MiB/s ratio={:.3}x peak_buffer_capacity={} bytes", - report.stream_elapsed_ms, - report.stream_rows_per_sec, - report.stream_mib_per_sec, - report.stream_to_buffer_ratio, - report.peak_buffer_capacity - ); - ExitCode::SUCCESS - } - Ok(CliAction::BenchMongoStream(rows)) => { - let report = match run_mongo_stream_benchmark(rows) { - Ok(report) => report, - Err(err) => { - eprintln!("error: mongo-stream benchmark failed: {err}"); - return ExitCode::FAILURE; - } - }; - println!("curate-etl bench-mongo-stream"); - println!(" input: rows={} bytes={}", report.rows, report.bytes); - println!( - " decode: decoded={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={}) checksum=0x{:016x}", - report.stats.decoded, - report.stats.rejected_total(), - report.stats.rejected_missing_field, - report.stats.rejected_empty_field, - report.stats.rejected_wrong_type, - report.stats.rejected_malformed_date, - report.stats.rejected_invalid_number, - report.stats.rejected_corrupt_document, - report.checksum - ); - println!( - " plain: elapsed={:.2} ms throughput={:.0} docs/s scan={:.2} MiB/s", - report.plain_elapsed_ms, report.plain_docs_per_sec, report.plain_mib_per_sec - ); - println!( - " cursor: elapsed={:.2} ms throughput={:.0} docs/s scan={:.2} MiB/s ratio={:.3}x peak_pending_capacity={} bytes", - report.cursor_elapsed_ms, - report.cursor_docs_per_sec, - report.cursor_mib_per_sec, - report.cursor_to_plain_ratio, - report.peak_pending_capacity - ); - ExitCode::SUCCESS - } Ok(CliAction::BenchCurateBars(rows)) => { let report = match run_curate_bars_benchmark(rows) { Ok(report) => report, @@ -1055,104 +572,6 @@ fn main() -> ExitCode { ); ExitCode::SUCCESS } - Ok(CliAction::BenchCurateBarsCmd(rows)) => { - let report = match run_curate_bars_cmd_benchmark(rows) { - Ok(report) => report, - Err(err) => { - eprintln!("error: curate-bars-cmd benchmark failed: {err}"); - return ExitCode::FAILURE; - } - }; - let retention_pct = if report.rows > 0 { - (report.rows_out as f64 / report.rows as f64) * 100.0 - } else { - 0.0 - }; - println!("curate-etl bench-curate-bars-cmd"); - println!( - " input: rows={} eod_bytes={} splits_docs={} splits_bytes={} qm_docs={} qm_bytes={} keys={}", - report.rows, - report.eod_bytes_read, - report.splits_docs_framed, - report.splits_bytes_read, - report.qm_docs_framed, - report.qm_bytes_read, - report.key_count - ); - println!( - " decode: elapsed={:.2} ms throughput={:.0} rows/s scan={:.2} MB/s unmapped_dropped={} buffered_bars={} buffered_bytes={} ({:.1} bytes/bar)", - report.decode_elapsed_ms, - report.decode_rows_per_sec, - report.input_mb_per_sec, - report.bars_unmapped_source_dropped, - report.buffered_bars, - report.buffered_bar_bytes, - report.bytes_per_buffered_bar - ); - println!( - " qm: elapsed={:.2} ms throughput={:.0} docs/s scan={:.2} MB/s attached={} unmapped={} no_eod_partner={} rejected={} checked={} within_tol={} mismatched={} (injected={}) unchecked={} samples={}", - report.qm_decode_rekey_elapsed_ms, - report.qm_decode_rekey_docs_per_sec, - report.qm_input_mb_per_sec, - report.qm_rekey.qm_attached, - report.qm_rekey.qm_unmapped_qm, - report.qm_rekey.qm_no_eod_partner, - report.qm_prices_decode.rejected_total(), - report.curate_stats.builder.volume_checked, - report.curate_stats.builder.volume_within_tolerance, - report.curate_stats.builder.volume_mismatched, - report.injected_mismatches, - report.curate_stats.builder.volume_unchecked, - report.mismatch_samples_out - ); - println!( - " curate: elapsed={:.2} ms throughput={:.0} rows/s rows_out={} ({:.2}% retained) listings_out={} unmapped={} missing_curr={} ts_oor={} coll_collapsed={} coll_dropped={}", - report.curate_elapsed_ms, - report.curate_rows_per_sec, - report.rows_out, - retention_pct, - report.listings_out, - report.curate_stats.dropped_unmapped, - report.curate_stats.dropped_missing_currency, - report.curate_stats.dropped_ts_out_of_range, - report.curate_stats.listing_collision_collapsed, - report.curate_stats.listing_collision_dropped - ); - println!( - " write_1: threads=1 elapsed={:.2} ms throughput={:.0} rows/s write={:.2} MB/s files={} row_groups={} bytes={} read_back_rows={}", - report.write_seq_elapsed_ms, - report.write_seq_rows_per_sec, - report.write_seq_mb_per_sec, - report.files_written, - report.row_groups_written, - report.bytes_written, - report.read_back_rows_seq - ); - println!( - " write: threads={} elapsed={:.2} ms throughput={:.0} rows/s write={:.2} MB/s speedup={:.2}x files={} row_groups={} bytes={} read_back_rows={}", - report.parallel_threads, - report.write_elapsed_ms, - report.write_rows_per_sec, - report.write_mb_per_sec, - report.write_speedup, - report.files_written, - report.row_groups_written, - report.bytes_written, - report.read_back_rows - ); - println!( - " total: elapsed={:.2} ms throughput={:.0} rows/s throughput_mb={:.2} MB/s splits_applied={} splits_coll_collapsed={} splits_unmapped_qm={} splits_no_eod_partner={} splits_noop={}", - report.total_elapsed_ms, - report.total_rows_per_sec, - report.total_mb_per_sec, - report.split_rekey.splits_applied, - report.split_rekey.splits_collision_collapsed, - report.split_rekey.splits_unmapped_qm, - report.split_rekey.splits_no_eod_partner, - report.split_rekey.splits_noop_dropped - ); - ExitCode::SUCCESS - } Ok(CliAction::BenchCurateShorts(rows)) => { let report = match run_curate_shorts_benchmark(rows) { Ok(report) => report, @@ -1275,74 +694,6 @@ fn main() -> ExitCode { ); ExitCode::SUCCESS } - Ok(CliAction::BenchCurateEventsCmd(rows)) => { - let report = match run_curate_events_cmd_benchmark(rows) { - Ok(report) => report, - Err(err) => { - eprintln!("error: curate-events-cmd benchmark failed: {err}"); - return ExitCode::FAILURE; - } - }; - let retention_pct = if report.rows > 0 { - (report.rows_out as f64 / report.rows as f64) * 100.0 - } else { - 0.0 - }; - println!("curate-etl bench-curate-events-cmd"); - println!( - " input: rows={} filings_docs={} filings_bytes={} earnings_docs={} earnings_bytes={} keys={} peak_chunk_bytes={}", - report.rows, - report.filings_docs_framed, - report.filings_bytes_read, - report.earnings_docs_framed, - report.earnings_bytes_read, - report.key_count, - report.peak_chunk_bytes - ); - println!( - " decode: elapsed={:.2} ms throughput={:.0} rows/s scan={:.2} MB/s filings_out={} filings_skipped={} earnings_out={} earnings_skipped={}", - report.decode_elapsed_ms, - report.decode_rows_per_sec, - report.input_mb_per_sec, - report.filings_decode.rows_out, - report.filings_decode.skipped_total(), - report.earnings_decode.rows_out, - report.earnings_decode.skipped_total() - ); - println!( - " curate: elapsed={:.2} ms throughput={:.0} rows/s rows_out={} ({:.2}% retained) filings_out={} earnings_out={} listings_out={} linked={} lagged_1605={} unmapped={} listing_dup={}", - report.curate_elapsed_ms, - report.curate_rows_per_sec, - report.rows_out, - retention_pct, - report.filings_out, - report.earnings_out, - report.listings_out, - report.curate_stats.builder.earnings_linked_to_filing, - report.curate_stats.builder.earnings_lagged_1605, - report.curate_stats.dropped_unmapped, - report.curate_stats.listing_duplicate_collapsed - ); - println!( - " write: elapsed={:.2} ms throughput={:.0} rows/s write={:.2} MB/s files={} row_groups={} bytes={} read_back_rows={}", - report.write_elapsed_ms, - report.write_rows_per_sec, - report.write_mb_per_sec, - report.files_written, - report.row_groups_written, - report.bytes_written, - report.read_back_rows - ); - println!( - " total: elapsed={:.2} ms throughput={:.0} rows/s proj_30.96M={:.1}s ({:.2}m) checksum=0x{:016x}", - report.total_elapsed_ms, - report.total_rows_per_sec, - report.total_extrap_full_secs, - report.total_extrap_full_secs / 60.0, - report.checksum - ); - ExitCode::SUCCESS - } Ok(CliAction::BenchCurateFx(rows)) => { let report = match run_curate_fx_benchmark(rows) { Ok(report) => report, @@ -1407,407 +758,6 @@ fn main() -> ExitCode { ); ExitCode::SUCCESS } - Ok(CliAction::BenchCurateAdj(events)) => { - let report = match run_curate_adj_benchmark(events) { - Ok(report) => report, - Err(err) => { - eprintln!("error: curate-adj benchmark failed: {err}"); - return ExitCode::FAILURE; - } - }; - let retention_pct = if report.events > 0 { - (report.rows_out as f64 / report.events as f64) * 100.0 - } else { - 0.0 - }; - println!("curate-etl bench-curate-adj"); - println!( - " input: events={} splits={} dividends={} keys={}", - report.events, report.splits_in, report.dividends_in, report.key_count - ); - println!( - " builder: rows_out={} keys_out={} split_noops={} zero_div={} missing_prev_close={} currency_mismatch={} not_below_prev_close={}", - report.stats.builder.rows_out, - report.stats.builder.keys_out, - report.stats.builder.split_noops_dropped, - report.stats.builder.dividend_zero_cash_dropped, - report.stats.builder.dividends_missing_prev_close, - report.stats.builder.dividends_currency_mismatch, - report.stats.builder.dividends_not_below_prev_close - ); - println!( - " stage: rows_out={} ({:.2}% retained) listings_out={} elapsed={:.2} ms throughput={:.0} events/s latency={:.2} ns/event checksum=0x{:016x}", - report.rows_out, - retention_pct, - report.listings_out, - report.stage_elapsed_ms, - report.stage_events_per_sec, - report.stage_ns_per_event, - report.checksum - ); - println!( - " parquet: files={} row_groups={} bytes={} read_back_rows={} elapsed={:.2} ms throughput={:.0} rows/s", - report.files_written, - report.row_groups_written, - report.bytes_written, - report.read_back_rows, - report.parquet_elapsed_ms, - report.parquet_rows_per_sec - ); - println!( - " total: elapsed={:.2} ms throughput={:.0} events/s", - report.total_elapsed_ms, report.total_events_per_sec - ); - println!( - " curate: splits_unmapped={} divs_unmapped={} splits_coll_collapsed={} divs_coll_collapsed={} coll_collapsed={}", - report.stats.splits_dropped_unmapped, - report.stats.dividends_dropped_unmapped, - report.stats.splits_collision_collapsed, - report.stats.dividends_collision_collapsed, - report.stats.listing_collision_collapsed - ); - ExitCode::SUCCESS - } - Ok(CliAction::BenchCurateAdjCmd(events)) => { - let report = match run_curate_adj_cmd_benchmark(events) { - Ok(report) => report, - Err(err) => { - eprintln!("error: curate-adj-cmd benchmark failed: {err}"); - return ExitCode::FAILURE; - } - }; - let retention_pct = if report.events > 0 { - (report.rows_out as f64 / report.events as f64) * 100.0 - } else { - 0.0 - }; - println!("curate-etl bench-curate-adj-cmd"); - println!( - " input: events={} splits_docs={} splits_bytes={} dividends_docs={} dividends_bytes={} bars_files={} bars_rows={} keys={}", - report.events, - report.splits_docs_framed, - report.splits_bytes_read, - report.dividends_docs_framed, - report.dividends_bytes_read, - report.bars_files_read, - report.bars_rows_loaded, - report.key_count - ); - println!( - " bars_load: elapsed={:.2} ms throughput={:.0} bars/s files={} rows={} listings={}", - report.bars_load_elapsed_ms, - report.bars_load_rows_per_sec, - report.bars_files_read, - report.bars_rows_loaded, - report.bars_listings_indexed - ); - println!( - " decode: elapsed={:.2} ms throughput={:.0} events/s scan={:.2} MB/s splits_rejected={} divs_rejected={} with_prev_close={} without_prev_close={}", - report.decode_elapsed_ms, - report.decode_events_per_sec, - report.input_mb_per_sec, - report.splits_decode.rejected_total(), - report.dividends_decode.rejected_total(), - report.dividends_with_prev_close, - report.dividends_without_prev_close - ); - println!( - " curate: elapsed={:.2} ms throughput={:.0} events/s rows_out={} ({:.2}% retained) listings_out={} splits_unmapped={} divs_unmapped={} splits_coll_collapsed={} divs_coll_collapsed={} split_noops={} zero_div={} missing_prev_close={} curr_mismatch={} checksum=0x{:016x}", - report.curate_elapsed_ms, - report.curate_events_per_sec, - report.rows_out, - retention_pct, - report.listings_out, - report.curate_stats.splits_dropped_unmapped, - report.curate_stats.dividends_dropped_unmapped, - report.curate_stats.splits_collision_collapsed, - report.curate_stats.dividends_collision_collapsed, - report.curate_stats.builder.split_noops_dropped, - report.curate_stats.builder.dividend_zero_cash_dropped, - report.curate_stats.builder.dividends_missing_prev_close, - report.curate_stats.builder.dividends_currency_mismatch, - report.checksum - ); - println!( - " write: elapsed={:.2} ms throughput={:.0} rows/s write={:.2} MB/s files={} row_groups={} bytes={} read_back_rows={}", - report.write_elapsed_ms, - report.write_rows_per_sec, - report.write_mb_per_sec, - report.files_written, - report.row_groups_written, - report.bytes_written, - report.read_back_rows - ); - println!( - " total: elapsed={:.2} ms throughput={:.0} events/s checksum=0x{:016x}", - report.total_elapsed_ms, report.total_events_per_sec, report.checksum - ); - ExitCode::SUCCESS - } - Ok(CliAction::BenchCurateCorporateActions(events)) => { - let report = match run_curate_corporate_actions_benchmark(events) { - Ok(report) => report, - Err(err) => { - eprintln!("error: curate-corporate-actions benchmark failed: {err}"); - return ExitCode::FAILURE; - } - }; - let retention_pct = if report.events > 0 { - (report.rows_out as f64 / report.events as f64) * 100.0 - } else { - 0.0 - }; - println!("curate-etl bench-curate-corporate-actions"); - println!( - " input: events={} splits={} dividends={} delistings={} keys={}", - report.events, - report.splits_in, - report.dividends_in, - report.delistings_in, - report.key_count - ); - println!( - " builder: rows_out={} splits_out={} split_noops={} divs_out={} zero_div={} otc_out={} delist_out={} delist_no_outcome={}", - report.stats.builder.rows_out, - report.stats.builder.splits_out, - report.stats.builder.split_noops_dropped, - report.stats.builder.dividends_out, - report.stats.builder.dividend_zero_cash_dropped, - report.stats.builder.otc_delist_transfers_out, - report.stats.builder.delistings_out, - report.stats.builder.delist_without_outcome - ); - println!( - " stage: rows_out={} ({:.2}% retained) listings_out={} elapsed={:.2} ms throughput={:.0} events/s latency={:.2} ns/event checksum=0x{:016x}", - report.rows_out, - retention_pct, - report.listings_out, - report.stage_elapsed_ms, - report.stage_events_per_sec, - report.stage_ns_per_event, - report.checksum - ); - println!( - " parquet: files={} row_groups={} bytes={} read_back_rows={} elapsed={:.2} ms throughput={:.0} rows/s", - report.files_written, - report.row_groups_written, - report.bytes_written, - report.read_back_rows, - report.parquet_elapsed_ms, - report.parquet_rows_per_sec - ); - println!( - " total: elapsed={:.2} ms throughput={:.0} events/s", - report.total_elapsed_ms, report.total_events_per_sec - ); - println!( - " curate: unmapped={} unmapped_succ={} self_succ={} known_at_oor={} coll_collapsed={} coll_dropped={}", - report.stats.dropped_unmapped, - report.stats.dropped_unmapped_successor, - report.stats.dropped_self_successor, - report.stats.dropped_known_at_out_of_range, - report.stats.listing_collision_collapsed, - report.stats.listing_collision_dropped - ); - ExitCode::SUCCESS - } - Ok(CliAction::BenchCurateCorporateActionsCmd(events)) => { - let report = match run_curate_corporate_actions_cmd_benchmark(events) { - Ok(report) => report, - Err(err) => { - eprintln!("error: curate-corporate-actions-cmd benchmark failed: {err}"); - return ExitCode::FAILURE; - } - }; - let retention_pct = if report.events > 0 { - (report.rows_out as f64 / report.events as f64) * 100.0 - } else { - 0.0 - }; - println!("curate-etl bench-curate-corporate-actions-cmd"); - println!( - " input: events={} splits_docs={} splits_bytes={} dividends_docs={} dividends_bytes={} delistings_rows={} delistings_bytes={} keys={}", - report.events, - report.splits_docs_framed, - report.splits_bytes_read, - report.dividends_docs_framed, - report.dividends_bytes_read, - report.delistings_rows_loaded, - report.delistings_bytes_read, - report.key_count - ); - println!( - " decode: elapsed={:.2} ms throughput={:.0} events/s scan={:.2} MB/s splits_rejected={} divs_rejected={}", - report.decode_elapsed_ms, - report.decode_events_per_sec, - report.input_mb_per_sec, - report.splits_decode.rejected_total(), - report.dividends_decode.rejected_total() - ); - println!( - " curate: elapsed={:.2} ms throughput={:.0} events/s rows_out={} ({:.2}% retained) listings_out={} unmapped={} unmapped_succ={} self_succ={} known_at_oor={} coll_collapsed={} coll_dropped={} split_noops={} zero_div={} checksum=0x{:016x}", - report.curate_elapsed_ms, - report.curate_events_per_sec, - report.rows_out, - retention_pct, - report.listings_out, - report.curate_stats.dropped_unmapped, - report.curate_stats.dropped_unmapped_successor, - report.curate_stats.dropped_self_successor, - report.curate_stats.dropped_known_at_out_of_range, - report.curate_stats.listing_collision_collapsed, - report.curate_stats.listing_collision_dropped, - report.curate_stats.builder.split_noops_dropped, - report.curate_stats.builder.dividend_zero_cash_dropped, - report.checksum - ); - println!( - " write: elapsed={:.2} ms throughput={:.0} rows/s write={:.2} MB/s files={} row_groups={} bytes={} read_back_rows={}", - report.write_elapsed_ms, - report.write_rows_per_sec, - report.write_mb_per_sec, - report.files_written, - report.row_groups_written, - report.bytes_written, - report.read_back_rows - ); - println!( - " total: elapsed={:.2} ms throughput={:.0} events/s checksum=0x{:016x}", - report.total_elapsed_ms, report.total_events_per_sec, report.checksum - ); - ExitCode::SUCCESS - } - Ok(CliAction::BenchCurateFxCmd(rows)) => { - let report = match run_curate_fx_cmd_benchmark(rows) { - Ok(report) => report, - Err(err) => { - eprintln!("error: curate-fx-cmd benchmark failed: {err}"); - return ExitCode::FAILURE; - } - }; - let b = &report.curate_stats.builder; - println!("curate-etl bench-curate-fx-cmd"); - println!( - " input: rows={} eod_docs={} eod_bytes={} te_docs={} te_points={} te_bytes={}", - report.rows, - report.eod_docs_framed, - report.eod_bytes_read, - report.te_docs_framed, - report.te_decode.points_in, - report.te_bytes_read - ); - println!( - " decode: elapsed={:.2} ms throughput={:.0} rows/s scan={:.2} MB/s eod_kept={} eod_other={} eod_rejected={} te_matched={} te_other={} te_decoded={} te_rejected={}", - report.decode_elapsed_ms, - report.decode_rows_per_sec, - report.input_mb_per_sec, - report.eod_cad_forex_kept, - report.eod_other_symbol_skipped, - report.eod_decode.rejected_total(), - report.te_decode.docs_matched, - report.te_decode.docs_other_symbol, - report.te_decode.points_decoded, - report.te_decode.rejected_total() - ); - println!( - " curate: elapsed={:.2} ms throughput={:.0} rows/s rows_out={} eod_out={} te_out={} te_superseded={} checksum=0x{:016x}", - report.curate_elapsed_ms, - report.curate_rows_per_sec, - report.rows_out, - b.eod_rows_out, - b.te_rows_out, - b.te_superseded_by_eod, - report.checksum - ); - println!( - " write: elapsed={:.2} ms throughput={:.0} rows/s write={:.2} MB/s files={} row_groups={} bytes={} read_back_rows={}", - report.write_elapsed_ms, - report.write_rows_per_sec, - report.write_mb_per_sec, - report.files_written, - report.row_groups_written, - report.bytes_written, - report.read_back_rows - ); - println!( - " total: elapsed={:.2} ms throughput={:.0} rows/s checksum=0x{:016x}", - report.total_elapsed_ms, report.total_rows_per_sec, report.checksum - ); - println!( - " overlap: checked={} within_tol={} mismatched={} max_rel={:.6}", - b.overlap_checked, - b.overlap_within_tolerance, - b.overlap_mismatched, - b.max_overlap_rel - ); - ExitCode::SUCCESS - } - Ok(CliAction::BenchCurateShortsCommand(rows)) => { - let report = match run_curate_shorts_command_benchmark(rows) { - Ok(report) => report, - Err(err) => { - eprintln!("error: curate-shorts-command benchmark failed: {err}"); - return ExitCode::FAILURE; - } - }; - let retention_pct = if report.rows > 0 { - (report.rows_out as f64 / report.rows as f64) * 100.0 - } else { - 0.0 - }; - println!("curate-etl bench-curate-shorts-command"); - println!( - " input: rows={} docs_framed={} bytes_read={} keys={} peak_chunk_bytes={}", - report.rows, - report.docs_framed, - report.bytes_read, - report.key_count, - report.peak_chunk_bytes - ); - println!( - " decode: elapsed={:.2} ms throughput={:.0} rows/s scan={:.2} MB/s rows_out={} skipped={} nulled_net_change={} nulled_pct_float={}", - report.decode_elapsed_ms, - report.decode_rows_per_sec, - report.input_mb_per_sec, - report.decode.rows_out, - report.decode.skipped_total(), - report.decode.nulled_wrong_type_net_change, - report.decode.nulled_wrong_type_pct_float - ); - println!( - " curate: elapsed={:.2} ms throughput={:.0} rows/s rows_out={} ({:.2}% retained) listings_out={} dropped_unmapped={} dup_collapsed={} dup_conflict={} coll_collapsed={} coll_dropped={} invalid_shares={} checksum=0x{:016x}", - report.curate_elapsed_ms, - report.curate_rows_per_sec, - report.rows_out, - retention_pct, - report.listings_out, - report.curate_stats.dropped_unmapped, - report.curate_stats.builder.duplicate_collapsed, - report.curate_stats.builder.duplicate_conflict_dropped, - report.curate_stats.listing_collision_collapsed, - report.curate_stats.listing_collision_dropped, - report.curate_stats.builder.dropped_invalid_shares_short, - report.checksum - ); - println!( - " write: elapsed={:.2} ms throughput={:.0} rows/s write={:.2} MB/s files={} row_groups={} bytes={} read_back_rows={}", - report.write_elapsed_ms, - report.write_rows_per_sec, - report.write_mb_per_sec, - report.files_written, - report.row_groups_written, - report.bytes_written, - report.read_back_rows - ); - println!( - " total: elapsed={:.2} ms throughput={:.0} rows/s peak_chunk_bytes={} checksum=0x{:016x}", - report.total_elapsed_ms, - report.total_rows_per_sec, - report.peak_chunk_bytes, - report.checksum - ); - ExitCode::SUCCESS - } Err(msg) => { eprintln!("error: {msg}"); eprintln!("{}", format_usage_stderr(NAME)); diff --git a/tools/curate-etl/src/mongo_safety.rs b/tools/curate-etl/src/mongo_safety.rs deleted file mode 100644 index 32ead4fc..00000000 --- a/tools/curate-etl/src/mongo_safety.rs +++ /dev/null @@ -1,1068 +0,0 @@ -//! Pure, offline, `std`-only read-only MongoDB URI safety guard. -//! -//! This module ports the MongoDB target-classification rules from -//! `apps/stock/config/src/env-safety.ts` (and the authority/remainder `@` check -//! from `libs/core/config/src/schemas/database.schema.ts`) to Rust, and adds -//! stricter read-only enforcement for `curate-etl`: -//! -//! 1. Rejects malformed URIs, ASCII control characters, Unicode whitespace, -//! unencoded `#` or multiple `@` in authority, `@` in path/query when -//! authority has no credentials, invalid percent-encoding, and forbidden -//! decoded host characters. -//! 2. Rejects `trading_admin` (percent-decoded, ASCII case-insensitive) on -//! **any** host regardless of [`ReadOnlyPolicy::allowed_read_users`]. -//! 3. Classifies any loopback or local-machine host on port `27017` (or omitted -//! default port) as a QA MongoDB target, and requires an allowlisted -//! read-only username (default: `["studio_stock_bot_read"]`) with explicit -//! credentials on QA targets. -//! 4. Produces a [`ValidatedReadOnlyMongoUri`] token with private fields and no -//! public constructor other than [`assert_read_only_mongo_uri`], so future -//! MongoDB cursor modules can require validated URIs by type. -//! -//! # Non-goals & boundaries -//! - **No I/O or network:** never opens sockets, never resolves DNS, and never -//! spawns subprocesses. -//! - **No URI query-option parsing:** beyond authority/remainder splitting and -//! the no-credentials remainder-`@` check, query parameters are not parsed or -//! validated (no invented option rules). - -use std::collections::BTreeSet; -use std::error::Error; -use std::fmt; - -/// Default allowlisted read-only MongoDB username for QA targets. -pub const DEFAULT_ALLOWED_READ_USER: &str = "studio_stock_bot_read"; - -/// Admin username forbidden on any MongoDB host (ASCII case-insensitive). -pub const FORBIDDEN_ADMIN_USER: &str = "trading_admin"; - -/// Default QA MongoDB port. -pub const QA_MONGO_PORT: u16 = 27017; - -const MAX_MONGO_HOST_DECODE_PASSES: usize = 8; - -/// Supported MongoDB URI schemes. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum MongoScheme { - /// `mongodb://` (default port `27017`, allows `.sock` Unix domain sockets). - Standard, - /// `mongodb+srv://` (no default port, single seed host, no explicit port, - /// no Unix domain sockets). - Srv, -} - -/// A single decoded host/port seed entry from a MongoDB URI. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct MongoTargetHost { - pub host: String, - pub port: Option, -} - -/// Parsed MongoDB URI target metadata (never stores the raw URI or password). -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct MongoTarget { - pub scheme: MongoScheme, - pub hosts: Vec, - pub database: Option, - pub username: Option, - has_invalid_host_segment: bool, - has_explicit_port: bool, -} - -impl MongoTarget { - /// Returns `true` if any comma-separated host segment was empty or had - /// malformed port/bracket syntax while at least one other host parsed. - pub fn has_invalid_host_segment(&self) -> bool { - self.has_invalid_host_segment - } - - /// Returns `true` if any host segment included an explicit `:` port suffix - /// (including a trailing `:` with an empty port). - pub fn has_explicit_port(&self) -> bool { - self.has_explicit_port - } -} - -/// Set of local-machine hostnames and IP addresses treated as local for QA -/// MongoDB target classification. -/// -/// Injecting this set explicitly keeps tests deterministic and offline. -#[derive(Debug, Clone, Default, PartialEq, Eq)] -pub struct LocalHosts { - hosts: BTreeSet, -} - -impl LocalHosts { - /// Returns an empty set (only loopback addresses will match as local). - pub fn empty() -> Self { - Self::default() - } - - /// Builds a `LocalHosts` set from raw hostnames or IP strings. - pub fn new(hosts: I) -> Self - where - I: IntoIterator, - S: AsRef, - { - let mut set = Self::empty(); - for host in hosts { - if let Some(normalized) = normalize_local_host_entry(host.as_ref()) { - set.hosts.insert(normalized); - } - } - set - } - - /// Builds a `LocalHosts` set from an optional machine hostname and a list - /// of local interface IP addresses, matching `getLocalMachineHosts` in - /// `apps/stock/config/src/env-safety.ts`: - /// - /// - Adds the trimmed, trailing-dot-stripped, lowercased full hostname, - /// its short label before the first `.`, and `.local`. - /// - Adds each IP with outer brackets and `%zone` suffixes stripped and - /// lowercased. - pub fn from_hostname_and_ips(hostname: Option<&str>, ips: I) -> Self - where - I: IntoIterator, - S: AsRef, - { - let mut set = Self::empty(); - if let Some(name) = hostname { - set.insert_hostname(name); - } - for ip in ips { - if let Some(normalized) = normalize_local_host_entry(ip.as_ref()) { - set.hosts.insert(normalized); - } - } - set - } - - /// Adds a single normalized host or IP entry and returns `self`. - pub fn with_host(mut self, host: &str) -> Self { - if let Some(normalized) = normalize_local_host_entry(host) { - self.hosts.insert(normalized); - } - self - } - - /// Returns `true` if the normalized host or IP is present in this set. - pub fn contains(&self, host: &str) -> bool { - normalize_local_host_entry(host) - .map(|normalized| self.hosts.contains(&normalized)) - .unwrap_or(false) - } - - /// Best-effort local host detection using only the Rust standard library. - /// - /// Reads `HOSTNAME` from the environment and `/etc/hostname` (when - /// readable). Because this module is strictly `std`-only and performs no - /// network-interface enumeration or DNS lookups, multi-homed LAN IPs are - /// **not** discovered automatically; callers on multi-homed hosts should - /// inject LAN IPs explicitly via [`LocalHosts::from_hostname_and_ips`]. - pub fn detect() -> Self { - let env_hostname = std::env::var("HOSTNAME").ok(); - let etc_hostname = std::fs::read_to_string("/etc/hostname").ok(); - Self::detect_from_sources(env_hostname.as_deref(), etc_hostname.as_deref()) - } - - fn detect_from_sources(env_hostname: Option<&str>, etc_hostname: Option<&str>) -> Self { - let mut set = Self::empty(); - if let Some(name) = env_hostname { - set.insert_hostname(name); - } - if let Some(contents) = etc_hostname { - if let Some(first_line) = contents.lines().find(|line| !line.trim().is_empty()) { - set.insert_hostname(first_line); - } - } - set - } - - fn insert_hostname(&mut self, raw: &str) { - let normalized = raw.trim().trim_end_matches('.').to_lowercase(); - if normalized.is_empty() { - return; - } - self.hosts.insert(normalized.clone()); - if let Some(short_name) = normalized.split('.').next() { - if !short_name.is_empty() { - self.hosts.insert(short_name.to_owned()); - self.hosts.insert(format!("{short_name}.local")); - } - } - } -} - -/// Policy controlling which usernames are permitted to read a QA MongoDB target. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct ReadOnlyPolicy { - /// Exact allowlisted usernames for QA MongoDB targets. - /// - /// Note: [`FORBIDDEN_ADMIN_USER`] (`"trading_admin"`) is always rejected on - /// every host even if a caller adds it to this list. - pub allowed_read_users: Vec, -} - -impl Default for ReadOnlyPolicy { - fn default() -> Self { - Self { - allowed_read_users: vec![DEFAULT_ALLOWED_READ_USER.to_owned()], - } - } -} - -/// Proof token that a MongoDB URI passed [`assert_read_only_mongo_uri`]. -/// -/// All fields are private and there is no public constructor other than -/// [`assert_read_only_mongo_uri`]. Both [`fmt::Debug`] and [`fmt::Display`] -/// redact the password in userinfo. -#[derive(Clone, PartialEq, Eq)] -pub struct ValidatedReadOnlyMongoUri { - uri: String, - target: MongoTarget, - is_qa: bool, -} - -impl ValidatedReadOnlyMongoUri { - /// Returns the original validated URI string for passing to a MongoDB - /// driver. Callers must not log this string directly; use [`Self::redacted`] - /// or `Display`/`Debug` instead. - pub fn as_str(&self) -> &str { - &self.uri - } - - /// Returns the parsed target metadata. - pub fn target(&self) -> &MongoTarget { - &self.target - } - - /// Returns `true` if this URI targets a local QA MongoDB instance. - pub fn is_qa_target(&self) -> bool { - self.is_qa - } - - /// Returns a copy of the URI with any userinfo password replaced by - /// `[REDACTED]`. - pub fn redacted(&self) -> String { - redact_mongo_uri_password(&self.uri) - } -} - -impl fmt::Display for ValidatedReadOnlyMongoUri { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str(&self.redacted()) - } -} - -impl fmt::Debug for ValidatedReadOnlyMongoUri { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("ValidatedReadOnlyMongoUri") - .field("uri", &self.redacted()) - .field("target", &self.target) - .field("is_qa", &self.is_qa) - .finish() - } -} - -/// Failure reasons returned by [`parse_mongo_target`] and -/// [`assert_read_only_mongo_uri`]. -/// -/// Variants intentionally never store raw URIs, raw authorities, or passwords -/// so neither `Debug` nor `Display` can leak credentials. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum MongoSafetyError { - EmptyUri, - ControlCharacters, - ForbiddenWhitespace, - UnsupportedScheme, - EmptyAuthority, - UnencodedHashInAuthority, - EmptyUserinfo, - MultipleAtInAuthority, - UnencodedAtInRemainderWithoutCredentials, - EmptyHostList, - InvalidUsernameEncoding, - InvalidHostEncoding, - ForbiddenHostCharacters, - NoValidHosts, - MalformedHostSegment, - InvalidSrvTarget, - ForbiddenAdminUser, - MissingCredentialsForQaTarget, - UnauthorizedQaUser, -} - -impl fmt::Display for MongoSafetyError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::EmptyUri => f.write_str("Safety guard: MongoDB URI is missing or empty."), - Self::ControlCharacters => f.write_str( - "Safety guard: MongoDB URI contains forbidden ASCII control characters.", - ), - Self::ForbiddenWhitespace => { - f.write_str("Safety guard: MongoDB URI contains forbidden whitespace.") - } - Self::UnsupportedScheme => f.write_str( - "Safety guard: MongoDB URI must use the mongodb:// or mongodb+srv:// scheme.", - ), - Self::EmptyAuthority => f.write_str("Safety guard: MongoDB URI authority is empty."), - Self::UnencodedHashInAuthority => f.write_str( - "Safety guard: MongoDB URI authority cannot contain an unencoded \"#\" character.", - ), - Self::EmptyUserinfo => f.write_str( - "Safety guard: MongoDB URI authority cannot have empty userinfo before \"@\".", - ), - Self::MultipleAtInAuthority => f.write_str( - "Safety guard: MongoDB URI authority cannot contain multiple unencoded \"@\" characters.", - ), - Self::UnencodedAtInRemainderWithoutCredentials => f.write_str( - "Safety guard: MongoDB URI cannot contain an unencoded \"@\" in path or query without credentials in authority.", - ), - Self::EmptyHostList => f.write_str("Safety guard: MongoDB URI host list is empty."), - Self::InvalidUsernameEncoding => f.write_str( - "Safety guard: invalid percent-encoding in MongoDB URI username.", - ), - Self::InvalidHostEncoding => { - f.write_str("Safety guard: invalid percent-encoding in MongoDB host.") - } - Self::ForbiddenHostCharacters => { - f.write_str("Safety guard: invalid characters in MongoDB host.") - } - Self::NoValidHosts => { - f.write_str("Safety guard: MongoDB URI did not contain any valid host.") - } - Self::MalformedHostSegment => f.write_str( - "Safety guard: MongoDB URI contains an empty or malformed host segment.", - ), - Self::InvalidSrvTarget => f.write_str( - "Safety guard: mongodb+srv:// URI must contain exactly one host and no explicit port.", - ), - Self::ForbiddenAdminUser => f.write_str( - "Safety guard: MongoDB admin user \"trading_admin\" is forbidden in read-only mode.", - ), - Self::MissingCredentialsForQaTarget => f.write_str( - "Safety guard: QA MongoDB target requires explicit read-only credentials.", - ), - Self::UnauthorizedQaUser => f.write_str( - "Safety guard: QA MongoDB target requires an allowlisted read-only username.", - ), - } - } -} - -impl Error for MongoSafetyError {} - -/// Parses a MongoDB connection URI into its target scheme, decoded hosts/ports, -/// optional database path, and optional percent-decoded username. -/// -/// Mirrors `parseMongoTarget` / `parseMongoHostPort` / `decodeMongoHost` in -/// `apps/stock/config/src/env-safety.ts` plus the no-credentials remainder-`@` -/// check from `libs/core/config/src/schemas/database.schema.ts`. -pub fn parse_mongo_target(uri: &str) -> Result { - if uri.is_empty() { - return Err(MongoSafetyError::EmptyUri); - } - if has_ascii_control_char(uri) { - return Err(MongoSafetyError::ControlCharacters); - } - if has_forbidden_whitespace(uri) { - return Err(MongoSafetyError::ForbiddenWhitespace); - } - - let Some((raw_scheme, rest)) = uri.split_once("://") else { - return Err(MongoSafetyError::UnsupportedScheme); - }; - let scheme = if raw_scheme.eq_ignore_ascii_case("mongodb") { - MongoScheme::Standard - } else if raw_scheme.eq_ignore_ascii_case("mongodb+srv") { - MongoScheme::Srv - } else { - return Err(MongoSafetyError::UnsupportedScheme); - }; - - let default_port = match scheme { - MongoScheme::Standard => Some(QA_MONGO_PORT), - MongoScheme::Srv => None, - }; - let allow_unix_socket = matches!(scheme, MongoScheme::Standard); - - // Match mongodb-connection-string-url: authority ends at '/' or '?', never '#' - let (authority, remainder) = match rest.find(['/', '?']) { - Some(idx) => (&rest[..idx], &rest[idx..]), - None => (rest, ""), - }; - if authority.is_empty() { - return Err(MongoSafetyError::EmptyAuthority); - } - if authority.contains('#') { - return Err(MongoSafetyError::UnencodedHashInAuthority); - } - - let database = if remainder.starts_with('/') { - let path_part = remainder.split(['?', '#']).next().unwrap_or(""); - let first_segment = path_part - .trim_start_matches('/') - .split('/') - .next() - .unwrap_or(""); - if first_segment.is_empty() { - None - } else { - Some(first_segment.to_owned()) - } - } else { - None - }; - - let (userinfo, host_list) = match authority.find('@') { - Some(0) => return Err(MongoSafetyError::EmptyUserinfo), - Some(at_idx) => { - if authority[at_idx + 1..].contains('@') { - return Err(MongoSafetyError::MultipleAtInAuthority); - } - (&authority[..at_idx], &authority[at_idx + 1..]) - } - None => { - if remainder.contains('@') { - return Err(MongoSafetyError::UnencodedAtInRemainderWithoutCredentials); - } - ("", authority) - } - }; - - if host_list.is_empty() { - return Err(MongoSafetyError::EmptyHostList); - } - - let username = if !userinfo.is_empty() { - let raw_username = match userinfo.find(':') { - Some(colon_idx) => &userinfo[..colon_idx], - None => userinfo, - }; - if raw_username.is_empty() { - None - } else { - Some( - percent_decode_utf8(raw_username) - .map_err(|()| MongoSafetyError::InvalidUsernameEncoding)?, - ) - } - } else { - None - }; - - let mut hosts = Vec::new(); - let mut has_invalid_host_segment = false; - let mut has_explicit_port = false; - - for segment in host_list.split(',') { - match parse_mongo_host_port(segment, default_port, allow_unix_socket)? { - Some((parsed_host, segment_has_explicit_port)) => { - hosts.push(parsed_host); - if segment_has_explicit_port { - has_explicit_port = true; - } - } - None => { - has_invalid_host_segment = true; - } - } - } - - if hosts.is_empty() { - return Err(MongoSafetyError::NoValidHosts); - } - - Ok(MongoTarget { - scheme, - hosts, - database, - username, - has_invalid_host_segment, - has_explicit_port, - }) -} - -/// Returns `true` if any seed host in `target` resolves to loopback or a host -/// in `local_hosts` on port `27017` (or with an omitted/default port), -/// regardless of database path. -/// -/// Mirrors `isQaMongoTargetHosts` in `apps/stock/config/src/env-safety.ts`. -pub fn is_qa_mongo_target(target: &MongoTarget, local_hosts: &LocalHosts) -> bool { - target.hosts.iter().any(|entry| { - is_local_machine_host(&entry.host, local_hosts) - && matches!(entry.port, None | Some(QA_MONGO_PORT)) - }) -} - -/// Validates a MongoDB URI for read-only use and returns a -/// [`ValidatedReadOnlyMongoUri`] proof token. -/// -/// Enforces fail-closed parsing, forbids `trading_admin` (ASCII -/// case-insensitive, percent-decoded) on **any** host, and requires explicit -/// allowlisted credentials when targeting QA MongoDB. -/// -/// URI query options are intentionally not parsed beyond authority/remainder -/// splitting (matching `apps/stock/config/src/env-safety.ts`). -pub fn assert_read_only_mongo_uri( - uri: &str, - policy: &ReadOnlyPolicy, - local_hosts: &LocalHosts, -) -> Result { - let target = parse_mongo_target(uri)?; - - if target.has_invalid_host_segment { - return Err(MongoSafetyError::MalformedHostSegment); - } - if target.scheme == MongoScheme::Srv && (target.hosts.len() != 1 || target.has_explicit_port) { - return Err(MongoSafetyError::InvalidSrvTarget); - } - - if target - .username - .as_deref() - .is_some_and(|user| user.eq_ignore_ascii_case(FORBIDDEN_ADMIN_USER)) - { - return Err(MongoSafetyError::ForbiddenAdminUser); - } - - let is_qa = is_qa_mongo_target(&target, local_hosts); - if is_qa { - let Some(user) = target.username.as_deref() else { - return Err(MongoSafetyError::MissingCredentialsForQaTarget); - }; - if !policy - .allowed_read_users - .iter() - .any(|allowed| allowed == user) - { - return Err(MongoSafetyError::UnauthorizedQaUser); - } - } - - Ok(ValidatedReadOnlyMongoUri { - uri: uri.to_owned(), - target, - is_qa, - }) -} - -pub(crate) fn redact_mongo_uri_password(uri: &str) -> String { - let Some(scheme_end) = uri.find("://") else { - return uri.to_owned(); - }; - let rest_start = scheme_end + 3; - let rest = &uri[rest_start..]; - let authority_end = rest.find(['/', '?']).unwrap_or(rest.len()); - let authority = &rest[..authority_end]; - let Some(at_idx) = authority.find('@') else { - return uri.to_owned(); - }; - let userinfo = &authority[..at_idx]; - let Some(colon_idx) = userinfo.find(':') else { - return uri.to_owned(); - }; - - let pass_start = rest_start + colon_idx + 1; - let pass_end = rest_start + at_idx; - let mut out = String::with_capacity(uri.len() + 10); - out.push_str(&uri[..pass_start]); - out.push_str("[REDACTED]"); - out.push_str(&uri[pass_end..]); - out -} - -fn has_ascii_control_char(value: &str) -> bool { - value.bytes().any(|b| b <= 0x1f || b == 0x7f) -} - -fn has_forbidden_whitespace(value: &str) -> bool { - value.chars().any(|c| c.is_whitespace() || c == '\u{FEFF}') -} - -fn hex_nibble(byte: u8) -> Option { - match byte { - b'0'..=b'9' => Some(byte - b'0'), - b'a'..=b'f' => Some(byte - b'a' + 10), - b'A'..=b'F' => Some(byte - b'A' + 10), - _ => None, - } -} - -/// Strictly percent-decodes UTF-8 without turning `+` into space. -fn percent_decode_utf8(input: &str) -> Result { - let bytes = input.as_bytes(); - let mut out = Vec::with_capacity(bytes.len()); - let mut i = 0; - while i < bytes.len() { - if bytes[i] == b'%' { - if i + 2 >= bytes.len() { - return Err(()); - } - let hi = hex_nibble(bytes[i + 1]).ok_or(())?; - let lo = hex_nibble(bytes[i + 2]).ok_or(())?; - out.push((hi << 4) | lo); - i += 3; - } else { - out.push(bytes[i]); - i += 1; - } - } - String::from_utf8(out).map_err(|_| ()) -} - -fn is_valid_ipv6_zone_id_char(b: u8) -> bool { - b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'~' | b'-') -} - -fn is_valid_ipv6_with_zone_id(host: &str) -> bool { - let Some(zone_idx) = host.find('%') else { - return false; - }; - if zone_idx == 0 || host[zone_idx + 1..].contains('%') { - return false; - } - let addr = &host[..zone_idx]; - let zone = &host[zone_idx + 1..]; - !zone.is_empty() - && zone.bytes().all(is_valid_ipv6_zone_id_char) - && parse_ipv6_hextets(addr).is_some() -} - -fn has_forbidden_unix_socket_char(value: &str) -> bool { - value.chars().any(|c| { - matches!(c, '?' | '#' | '@' | ':' | '\\' | '[' | ']' | ',') - || c.is_whitespace() - || c == '\u{FEFF}' - }) -} - -fn is_unix_domain_socket_host(decoded_host: &str) -> bool { - decoded_host.starts_with('/') - && decoded_host.ends_with(".sock") - && !has_ascii_control_char(decoded_host) - && !has_forbidden_unix_socket_char(decoded_host) -} - -fn has_forbidden_host_char(value: &str, is_bracketed_ipv6: bool) -> bool { - value.chars().any(|c| { - matches!(c, '/' | '?' | '#' | '@' | '\\' | '[' | ']' | ',') - || (!is_bracketed_ipv6 && c == ':') - || c.is_whitespace() - || c == '\u{FEFF}' - }) -} - -fn decode_mongo_host( - raw_host: &str, - is_bracketed_ipv6: bool, - allow_unix_socket: bool, -) -> Result { - let mut current = raw_host.to_owned(); - for pass in 0..MAX_MONGO_HOST_DECODE_PASSES { - match percent_decode_utf8(¤t) { - Ok(decoded) => { - if decoded == current { - break; - } - current = decoded; - if is_bracketed_ipv6 && is_valid_ipv6_with_zone_id(¤t) { - break; - } - } - Err(()) => { - if is_bracketed_ipv6 && pass > 0 && is_valid_ipv6_with_zone_id(¤t) { - break; - } - return Err(MongoSafetyError::InvalidHostEncoding); - } - } - } - - if current.contains('%') && !(is_bracketed_ipv6 && is_valid_ipv6_with_zone_id(¤t)) { - return Err(MongoSafetyError::InvalidHostEncoding); - } - if !is_bracketed_ipv6 && allow_unix_socket && is_unix_domain_socket_host(¤t) { - return Ok(current); - } - if has_ascii_control_char(¤t) || has_forbidden_host_char(¤t, is_bracketed_ipv6) { - return Err(MongoSafetyError::ForbiddenHostCharacters); - } - Ok(current.to_lowercase()) -} - -fn parse_port(port_str: &str) -> Option { - if port_str.is_empty() || !port_str.bytes().all(|b| b.is_ascii_digit()) { - return None; - } - let port: u16 = port_str.parse().ok()?; - if port == 0 { None } else { Some(port) } -} - -fn is_valid_bracketed_ipv6(host: &str) -> bool { - if host.contains('%') { - is_valid_ipv6_with_zone_id(host) - } else { - parse_ipv6_hextets(host).is_some() - } -} - -fn parse_mongo_host_port( - segment: &str, - default_port: Option, - allow_unix_socket: bool, -) -> Result, MongoSafetyError> { - let trimmed = segment.trim(); - if trimmed.is_empty() { - return Ok(None); - } - - if let Some(after_open) = trimmed.strip_prefix('[') { - let Some(close_rel) = after_open.find(']') else { - return Ok(None); - }; - if close_rel == 0 { - return Ok(None); - } - let raw_host = after_open[..close_rel].trim(); - if raw_host.is_empty() { - return Ok(None); - } - let host = decode_mongo_host(raw_host, true, false)?.trim().to_owned(); - if host.is_empty() || !is_valid_bracketed_ipv6(&host) { - return Ok(None); - } - let after = after_open[close_rel + 1..].trim(); - if after.is_empty() { - return Ok(Some(( - MongoTargetHost { - host, - port: default_port, - }, - false, - ))); - } - let Some(port_part) = after.strip_prefix(':') else { - return Ok(None); - }; - let port_str = port_part.trim(); - if port_str.is_empty() { - return Ok(Some(( - MongoTargetHost { - host, - port: default_port, - }, - true, - ))); - } - let Some(port) = parse_port(port_str) else { - return Ok(None); - }; - return Ok(Some(( - MongoTargetHost { - host, - port: Some(port), - }, - true, - ))); - } - - let Some(colon_idx) = trimmed.find(':') else { - let host = decode_mongo_host(trimmed, false, allow_unix_socket)? - .trim() - .to_owned(); - if host.is_empty() { - return Ok(None); - } - if allow_unix_socket && is_unix_domain_socket_host(&host) { - return Ok(Some((MongoTargetHost { host, port: None }, false))); - } - return Ok(Some(( - MongoTargetHost { - host, - port: default_port, - }, - false, - ))); - }; - - if trimmed[colon_idx + 1..].contains(':') { - return Ok(None); - } - - let raw_host = trimmed[..colon_idx].trim(); - let port_str = trimmed[colon_idx + 1..].trim(); - if raw_host.is_empty() { - return Ok(None); - } - let host = decode_mongo_host(raw_host, false, false)?.trim().to_owned(); - if host.is_empty() { - return Ok(None); - } - if port_str.is_empty() { - return Ok(Some(( - MongoTargetHost { - host, - port: default_port, - }, - true, - ))); - } - let Some(port) = parse_port(port_str) else { - return Ok(None); - }; - Ok(Some(( - MongoTargetHost { - host, - port: Some(port), - }, - true, - ))) -} - -fn normalize_host(host: &str) -> String { - let s = host.trim(); - let s = s.strip_prefix('[').unwrap_or(s); - let s = s.strip_suffix(']').unwrap_or(s); - s.trim_end_matches('.').to_lowercase() -} - -fn normalize_local_host_entry(raw: &str) -> Option { - let s = raw.trim(); - let s = s.strip_prefix('[').unwrap_or(s); - let s = s.strip_suffix(']').unwrap_or(s); - let s = s.split('%').next().unwrap_or(""); - let normalized = s.trim().trim_end_matches('.').to_lowercase(); - if normalized.is_empty() { - None - } else { - Some(normalized) - } -} - -fn parse_ipv4_octets(host: &str) -> Option<[u8; 4]> { - let mut parts = host.split('.'); - let mut out = [0u8; 4]; - for slot in &mut out { - let part = parts.next()?; - if part.is_empty() || part.len() > 3 || !part.bytes().all(|b| b.is_ascii_digit()) { - return None; - } - *slot = part.parse::().ok()?; - } - if parts.next().is_some() { - return None; - } - Some(out) -} - -fn parse_ipv4_part(part: &str) -> Option { - if let Some(hex_digits) = part.strip_prefix("0x").or_else(|| part.strip_prefix("0X")) { - if hex_digits.is_empty() { - return Some(0); - } - if !hex_digits.bytes().all(|b| b.is_ascii_hexdigit()) { - return None; - } - return u32::from_str_radix(hex_digits, 16).ok(); - } - if part.len() >= 2 && part.starts_with('0') && part.bytes().all(|b| (b'0'..=b'7').contains(&b)) { - return u32::from_str_radix(part, 8).ok(); - } - if part == "0" - || (!part.is_empty() - && !part.starts_with('0') - && part.bytes().all(|b| b.is_ascii_digit())) - { - return part.parse::().ok(); - } - None -} - -fn parse_numeric_ipv4_octets(host: &str) -> Option<[u8; 4]> { - let parts: Vec<&str> = host.split('.').collect(); - if parts.is_empty() || parts.len() > 4 { - return None; - } - let mut parsed = [0u32; 4]; - for (idx, part) in parts.iter().enumerate() { - parsed[idx] = parse_ipv4_part(part)?; - } - - match parts.len() { - 1 => { - let p0 = parsed[0]; - Some([ - ((p0 >> 24) & 0xff) as u8, - ((p0 >> 16) & 0xff) as u8, - ((p0 >> 8) & 0xff) as u8, - (p0 & 0xff) as u8, - ]) - } - 2 => { - let (p0, p1) = (parsed[0], parsed[1]); - if p0 > 0xff || p1 > 0x00ff_ffff { - return None; - } - Some([ - p0 as u8, - ((p1 >> 16) & 0xff) as u8, - ((p1 >> 8) & 0xff) as u8, - (p1 & 0xff) as u8, - ]) - } - 3 => { - let (p0, p1, p2) = (parsed[0], parsed[1], parsed[2]); - if p0 > 0xff || p1 > 0xff || p2 > 0xffff { - return None; - } - Some([ - p0 as u8, - p1 as u8, - ((p2 >> 8) & 0xff) as u8, - (p2 & 0xff) as u8, - ]) - } - 4 => { - let (p0, p1, p2, p3) = (parsed[0], parsed[1], parsed[2], parsed[3]); - if p0 > 0xff || p1 > 0xff || p2 > 0xff || p3 > 0xff { - return None; - } - Some([p0 as u8, p1 as u8, p2 as u8, p3 as u8]) - } - _ => None, - } -} - -fn parse_decimal_ipv4_octets(host: &str) -> Option<[u8; 4]> { - let mut parts = host.split('.'); - let mut out = [0u8; 4]; - for slot in &mut out { - let part = parts.next()?; - if part.is_empty() || !part.bytes().all(|b| b.is_ascii_digit()) { - return None; - } - *slot = part.parse::().ok()?; - } - if parts.next().is_some() { - return None; - } - Some(out) -} - -fn is_ipv4_loopback_octets(octets: [u8; 4]) -> bool { - octets[0] == 127 || octets == [0, 0, 0, 0] -} - -fn is_ipv4_loopback(host: &str) -> bool { - parse_numeric_ipv4_octets(host).is_some_and(is_ipv4_loopback_octets) - || parse_decimal_ipv4_octets(host).is_some_and(is_ipv4_loopback_octets) -} - -fn parse_ipv6_side(side: &str, allow_ipv4_tail: bool) -> Option> { - if side.is_empty() { - return Some(Vec::new()); - } - let parts: Vec<&str> = side.split(':').collect(); - let mut groups = Vec::with_capacity(parts.len() + 1); - for (idx, part) in parts.iter().enumerate() { - if idx + 1 == parts.len() && allow_ipv4_tail && part.contains('.') { - let octets = parse_ipv4_octets(part)?; - groups.push(((octets[0] as u16) << 8) | (octets[1] as u16)); - groups.push(((octets[2] as u16) << 8) | (octets[3] as u16)); - continue; - } - if part.is_empty() || part.len() > 4 || !part.bytes().all(|b| b.is_ascii_hexdigit()) { - return None; - } - groups.push(u16::from_str_radix(part, 16).ok()?); - } - Some(groups) -} - -fn parse_ipv6_hextets(host: &str) -> Option<[u16; 8]> { - if !host.contains(':') { - return None; - } - let addr = match host.find('%') { - Some(zone_idx) => &host[..zone_idx], - None => host, - }; - let halves: Vec<&str> = addr.split("::").collect(); - if halves.len() > 2 { - return None; - } - if halves.len() == 1 { - let groups = parse_ipv6_side(halves[0], true)?; - return groups.try_into().ok(); - } - - let left = parse_ipv6_side(halves[0], false)?; - let right = parse_ipv6_side(halves[1], true)?; - let total = left.len() + right.len(); - if total >= 8 { - return None; - } - let missing = 8 - total; - let mut out = [0u16; 8]; - out[..left.len()].copy_from_slice(&left); - out[left.len() + missing..].copy_from_slice(&right); - Some(out) -} - -fn is_ipv6_loopback(host: &str) -> bool { - let Some(hextets) = parse_ipv6_hextets(host) else { - return false; - }; - if hextets[..7] == [0; 7] { - return hextets[7] == 0 || hextets[7] == 1; - } - if hextets[..5] == [0; 5] && hextets[5] == 0xffff { - let first_octet = (hextets[6] >> 8) & 0xff; - return first_octet == 127 || (hextets[6] == 0 && hextets[7] == 0); - } - false -} - -fn is_loopback_normalized(normalized: &str) -> bool { - normalized == "localhost" - || normalized == "0.0.0.0" - || is_ipv4_loopback(normalized) - || is_ipv6_loopback(normalized) -} - -fn is_local_machine_host(host: &str, local_hosts: &LocalHosts) -> bool { - if host.is_empty() { - return false; - } - let normalized = normalize_host(host); - if is_loopback_normalized(&normalized) { - return true; - } - if local_hosts.hosts.contains(&normalized) { - return true; - } - if let Some(zone_idx) = normalized.find('%') { - if local_hosts.hosts.contains(&normalized[..zone_idx]) { - return true; - } - } - if let Some([a, b, c, d]) = parse_numeric_ipv4_octets(&normalized) { - let dotted = format!("{a}.{b}.{c}.{d}"); - if local_hosts.hosts.contains(&dotted) { - return true; - } - } - if let Some([a, b, c, d]) = parse_decimal_ipv4_octets(&normalized) { - let dotted = format!("{a}.{b}.{c}.{d}"); - if local_hosts.hosts.contains(&dotted) { - return true; - } - } - false -} - -#[cfg(test)] -#[path = "mongo_safety_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/mongo_safety_tests.rs b/tools/curate-etl/src/mongo_safety_tests.rs deleted file mode 100644 index dbc12fe8..00000000 --- a/tools/curate-etl/src/mongo_safety_tests.rs +++ /dev/null @@ -1,2580 +0,0 @@ -use super::*; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum ExpectedTargetOutcome { - Qa, - NotQa, - Rejected, -} - -fn injected_local_hosts() -> LocalHosts { - LocalHosts::from_hostname_and_ips( - Some("quant.lan.local."), - ["192.168.1.50", "fe80::1234:5678%eth0"], - ) -} - -#[test] -fn parity_table_mirrors_all_five_ts_environment_safety_test_suites() { - let local_hosts = injected_local_hosts(); - - // Every MongoDB target classification vector from: - // 1. test/unit/environment-safety.test.ts - // 2. test/unit/environment-safety-authority-split.test.ts - // 3. test/unit/environment-safety-edge-cases.test.ts - // 4. test/unit/environment-safety-encoded-host.test.ts - // 5. test/unit/environment-safety-multi-host.test.ts - let vectors: &[(&str, ExpectedTargetOutcome, &str)] = &[ - // --- 1. test/unit/environment-safety.test.ts --- - ( - "mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSource=admin", - ExpectedTargetOutcome::NotQa, - "environment-safety.test.ts: dev port 27018", - ), - ( - "mongodb://studio_stock_bot_read:secret@localhost:27017/stock?authSource=stock", - ExpectedTargetOutcome::Qa, - "environment-safety.test.ts: QA localhost:27017", - ), - ( - "mongodb://trading_admin:trading_mongo_dev@localhost:27017/stock?authSource=admin", - ExpectedTargetOutcome::Qa, - "environment-safety.test.ts: QA trading_admin localhost:27017", - ), - ( - "mongodb://trading_admin:pass@localhost:27017", - ExpectedTargetOutcome::Qa, - "environment-safety.test.ts: omitted /stock path", - ), - ( - "mongodb://trading_admin:pass@[::1]:27017", - ExpectedTargetOutcome::Qa, - "environment-safety.test.ts: IPv6 loopback omitted path", - ), - ( - "mongodb://studio_stock_bot_read:secret@localhost:27017", - ExpectedTargetOutcome::Qa, - "environment-safety.test.ts: read user omitted path", - ), - ( - "mongodb://trading_admin:pass@0127.0.0.1:27017/stock", - ExpectedTargetOutcome::Qa, - "environment-safety.test.ts: T-37 leading-zero decimal 0127.0.0.1", - ), - ( - "mongodb://trading_admin:pass@00127.0.0.1:27017/stock", - ExpectedTargetOutcome::Qa, - "environment-safety.test.ts: T-37 leading-zero decimal 00127.0.0.1", - ), - ( - "mongodb://trading_admin:pass@0177.0.0.1:27017/stock", - ExpectedTargetOutcome::Qa, - "environment-safety.test.ts: T-37 octal 0177.0.0.1", - ), - ( - "mongodb://trading_admin:pass@00.00.00.00:27017/stock", - ExpectedTargetOutcome::Qa, - "environment-safety.test.ts: T-37 leading-zero 00.00.00.00", - ), - ( - "mongodb://prod_user:strong-prod-mongo-pass@%2Fvar%2Frun%2Fmongodb%2Fmongod.sock/stock", - ExpectedTargetOutcome::NotQa, - "environment-safety.test.ts: T-27 Unix domain socket", - ), - ( - "mongodb://trading_admin:pass@quant.lan.local:27017/stock", - ExpectedTargetOutcome::Qa, - "environment-safety.test.ts: T-15 local machine hostname", - ), - ( - "mongodb://trading_admin:pass@192.168.1.50:27017/stock", - ExpectedTargetOutcome::Qa, - "environment-safety.test.ts: T-15 local machine LAN IP", - ), - ( - "mongodb://u:p@localhost:27017,localhost:27018/stock", - ExpectedTargetOutcome::Qa, - "environment-safety.test.ts: multi-host QA first", - ), - ( - "mongodb://u:p@localhost:27018,localhost:27017/stock_dev", - ExpectedTargetOutcome::Qa, - "environment-safety.test.ts: multi-host QA second", - ), - ( - "mongodb://studio_stock_bot_read:secret@localhost:27018,localhost:27017/stock_dev", - ExpectedTargetOutcome::Qa, - "environment-safety.test.ts: multi-host read user QA second", - ), - ( - "mongodb://studio_stock_bot_read:secret@localhost:27018,localhost:27017/stock", - ExpectedTargetOutcome::Qa, - "environment-safety.test.ts: multi-host fallback uri QA second", - ), - ( - "mongodb://trading_admin:pass@localhost:27017,localhost:27018/stock", - ExpectedTargetOutcome::Qa, - "environment-safety.test.ts: multi-host admin QA first", - ), - ( - "mongodb://studio_stock_bot_read:secret@localhost:27017,localhost:27018/stock", - ExpectedTargetOutcome::Qa, - "environment-safety.test.ts: multi-host read user QA first", - ), - ( - "mongodb://studio_stock_bot_read:secret@localhost:27017,localhost:27018/stock?authSource=stock", - ExpectedTargetOutcome::Qa, - "environment-safety.test.ts: multi-host read user QA first with authSource", - ), - ( - "mongodb://trading_admin:trading_mongo_dev@[::ffff:7f00:1]:27017/stock?authSource=admin", - ExpectedTargetOutcome::Qa, - "environment-safety.test.ts: initializeStockConfig IPv4-mapped loopback", - ), - ( - "mongodb://prod:strongpass@mongo.prod.internal:27017/stock", - ExpectedTargetOutcome::NotQa, - "environment-safety.test.ts: prod single remote host", - ), - ( - "mongodb://trading%5Fadmin:pass@localhost:27018,localhost:27017/stock", - ExpectedTargetOutcome::Qa, - "environment-safety.test.ts: multi-host encoded trading_admin", - ), - ( - "mongodb://u:p@localhost:27018,localhost/stock_dev", - ExpectedTargetOutcome::Qa, - "environment-safety.test.ts: omitted port on second host", - ), - ( - "mongodb://u:p@localhost:27018,127.0.0.1/stock_dev", - ExpectedTargetOutcome::Qa, - "environment-safety.test.ts: omitted port IPv4 loopback", - ), - ( - "mongodb://u:p@localhost:27018,[::1]:27017/stock_dev", - ExpectedTargetOutcome::Qa, - "environment-safety.test.ts: multi-host IPv6 loopback", - ), - ( - "mongodb://u:p@localhost:27018,[::1]/stock_dev", - ExpectedTargetOutcome::Qa, - "environment-safety.test.ts: multi-host IPv6 omitted port", - ), - ( - "mongodb://u:p@[0:0:0:0:0:0:0:0001]:27017/stock", - ExpectedTargetOutcome::Qa, - "environment-safety.test.ts: expanded IPv6 loopback", - ), - ( - "mongodb://u:p@[::ffff:7f00:1]:27017/stock", - ExpectedTargetOutcome::Qa, - "environment-safety.test.ts: IPv4-mapped IPv6 hex 7f00:1", - ), - ( - "mongodb://u:p@[::ffff:7f00:0001]/stock", - ExpectedTargetOutcome::Qa, - "environment-safety.test.ts: IPv4-mapped IPv6 omitted port", - ), - ( - "mongodb://u:p@[::ffff:7f01:0203]:27017/stock", - ExpectedTargetOutcome::Qa, - "environment-safety.test.ts: IPv4-mapped IPv6 127.1.2.3", - ), - ( - "mongodb://u:p@[0:0:0:0:0:ffff:7f00:1]:27017/stock", - ExpectedTargetOutcome::Qa, - "environment-safety.test.ts: expanded IPv4-mapped IPv6", - ), - ( - "mongodb://u:p@[::ffff:127.0.0.2]:27017/stock", - ExpectedTargetOutcome::Qa, - "environment-safety.test.ts: IPv4-mapped IPv6 dotted 127.0.0.2", - ), - ( - "mongodb://u:p@localhost:27018,LOCALHOST.:27017/stock_dev", - ExpectedTargetOutcome::Qa, - "environment-safety.test.ts: uppercase trailing dot LOCALHOST.", - ), - ( - "mongodb://u:p@127.0.0.2:27017/stock_dev", - ExpectedTargetOutcome::Qa, - "environment-safety.test.ts: 127.0.0.2 loopback", - ), - ( - "mongodb+srv://u:p@localhost/stock", - ExpectedTargetOutcome::Qa, - "environment-safety.test.ts: mongodb+srv localhost", - ), - ( - "mongodb://u:p@[::ffff:0a00:1]:27017/stock_dev", - ExpectedTargetOutcome::NotQa, - "environment-safety.test.ts: non-loopback IPv4-mapped IPv6", - ), - ( - "mongodb://trading_admin:p%40ss@localhost:27018,localhost:27017/stock", - ExpectedTargetOutcome::Qa, - "environment-safety.test.ts: %40 in password", - ), - ( - "mongodb://trading_admin:p@ss@localhost:27018,localhost:27017/stock", - ExpectedTargetOutcome::Rejected, - "environment-safety.test.ts: unencoded double @", - ), - ( - "mongodb://localhost:27017,localhost:27018/stock", - ExpectedTargetOutcome::Qa, - "environment-safety.test.ts: no userinfo multi-host QA", - ), - ( - "mongodb://u:p@localhost:/stock", - ExpectedTargetOutcome::Qa, - "environment-safety.test.ts: trailing colon default port", - ), - ( - "mongodb://u:p@[::1]:/stock", - ExpectedTargetOutcome::Qa, - "environment-safety.test.ts: IPv6 trailing colon default port", - ), - ( - "mongodb://u:p@bad:port,localhost:27017/stock", - ExpectedTargetOutcome::Qa, - "environment-safety.test.ts: bad segment + valid QA host still classifies QA", - ), - ( - "mongodb://localhost:27018#,localhost/stock", - ExpectedTargetOutcome::Rejected, - "environment-safety.test.ts: T-28 raw # in authority", - ), - ( - "mongodb://dev_admin:dev_mongo_pass@localhost:27018#,localhost:27017/stock_dev?authSource=admin", - ExpectedTargetOutcome::Rejected, - "environment-safety.test.ts: T-28 raw # with credentials", - ), - ( - "mongodb://u:p@localhost:27018#x,127.0.0.1/stock", - ExpectedTargetOutcome::Rejected, - "environment-safety.test.ts: T-28 raw # before second host", - ), - ( - "mongodb://u:p@localhost:27017@x:27018/stock", - ExpectedTargetOutcome::Rejected, - "environment-safety.test.ts: T-28 second @ in authority", - ), - ( - "mongodb://localhost#x:27018/stock", - ExpectedTargetOutcome::Rejected, - "environment-safety.test.ts: T-28 raw # before port", - ), - ( - "mongodb://u@localhost:27017@x:27018/stock", - ExpectedTargetOutcome::Rejected, - "environment-safety.test.ts: T-28 passwordless user + second @", - ), - ( - "mongodb://u:p@local\nhost:27017/stock", - ExpectedTargetOutcome::Rejected, - "environment-safety.test.ts: T-28 newline control char", - ), - ( - "mongodb://u:p@local\thost:27017/stock", - ExpectedTargetOutcome::Rejected, - "environment-safety.test.ts: T-28 tab control char", - ), - ( - "mongodb:///stock", - ExpectedTargetOutcome::Rejected, - "environment-safety.test.ts: empty authority", - ), - ( - "mongodb://u:p@/stock", - ExpectedTargetOutcome::Rejected, - "environment-safety.test.ts: empty host list", - ), - ( - "mongodb://u:p@bad:port/stock", - ExpectedTargetOutcome::Rejected, - "environment-safety.test.ts: zero valid hosts", - ), - ( - "mongodb://,/stock", - ExpectedTargetOutcome::Rejected, - "environment-safety.test.ts: comma-only host list", - ), - ( - "mongodb+srv:///stock", - ExpectedTargetOutcome::Rejected, - "environment-safety.test.ts: srv empty authority", - ), - ( - "", - ExpectedTargetOutcome::Rejected, - "environment-safety.test.ts: empty string", - ), - ( - " ", - ExpectedTargetOutcome::Rejected, - "environment-safety.test.ts: whitespace-only string", - ), - ( - "http://localhost:27017/stock", - ExpectedTargetOutcome::Rejected, - "environment-safety.test.ts: non-mongodb scheme", - ), - ( - "mongodb://@localhost:27018/stock", - ExpectedTargetOutcome::Rejected, - "environment-safety.test.ts: empty userinfo before @", - ), - ( - "mongodb://u:p@localhost:27017/stock?a=1\nb=2", - ExpectedTargetOutcome::Rejected, - "environment-safety.test.ts: newline in query", - ), - ( - "mongodb://u:p@localhost:27018/stock\x00", - ExpectedTargetOutcome::Rejected, - "environment-safety.test.ts: NUL byte", - ), - ( - "mongodb://u:p@localhost:27018/stock\r\n", - ExpectedTargetOutcome::Rejected, - "environment-safety.test.ts: CRLF", - ), - ( - "mongodb://localhost:27018#frag", - ExpectedTargetOutcome::Rejected, - "environment-safety.test.ts: raw # without / or ?", - ), - ( - "mongodb+srv://u:p@cluster.example.com#x/stock", - ExpectedTargetOutcome::Rejected, - "environment-safety.test.ts: srv raw # in authority", - ), - ( - "mongodb+srv://u:p@cluster.example.com@other.example.com/stock", - ExpectedTargetOutcome::Rejected, - "environment-safety.test.ts: srv multiple @", - ), - ( - "mongodb://dev_admin:p%40ss@localhost:27018/stock_dev", - ExpectedTargetOutcome::NotQa, - "environment-safety.test.ts: %40 in credentials on dev port", - ), - ( - "mongodb://dev_admin:p%40ss@localhost:27018/stock_dev?appName=a@b#note", - ExpectedTargetOutcome::NotQa, - "environment-safety.test.ts: @/# in query with credentials", - ), - ( - "mongodb://localhost:27018?authSource=admin#frag", - ExpectedTargetOutcome::NotQa, - "environment-safety.test.ts: # after ? without credentials", - ), - ( - "mongodb://dev_user@localhost:27018/stock_dev", - ExpectedTargetOutcome::NotQa, - "environment-safety.test.ts: passwordless user on dev port", - ), - ( - "mongodb+srv://prod:strongpass@cluster.prod.internal/stock?appName=a@b#note", - ExpectedTargetOutcome::NotQa, - "environment-safety.test.ts: srv prod remote", - ), - ( - "mongodb://dev_admin:dev_mongo_pass@localhost:27018,127.0.0.1:27019/stock_dev?authSource=admin", - ExpectedTargetOutcome::NotQa, - "environment-safety.test.ts: non-QA multi-host dev", - ), - ( - "mongodb://prod:strongpass@mongo1.prod.internal:27017,mongo2.prod.internal:27017/stock", - ExpectedTargetOutcome::NotQa, - "environment-safety.test.ts: prod multi-host remote", - ), - // --- 2. test/unit/environment-safety-authority-split.test.ts --- - ( - "mongodb://\nlocalhost", - ExpectedTargetOutcome::Rejected, - "authority-split.test.ts: leading newline", - ), - ( - "mongodb://trading_admin:x@localhost:27018#,localhost:27017/stock", - ExpectedTargetOutcome::Rejected, - "authority-split.test.ts: smuggled trading_admin behind #", - ), - ( - "mongodb://dev_admin:p%23ss@localhost:27018/stock_dev", - ExpectedTargetOutcome::NotQa, - "authority-split.test.ts: %23 in password", - ), - ( - "mongodb://u:p@localhost:27018/stock_dev#frag@x", - ExpectedTargetOutcome::NotQa, - "authority-split.test.ts: @ in fragment with credentials", - ), - ( - "mongodb://dev_user@localhost:27018,127.0.0.1:27019/stock_dev", - ExpectedTargetOutcome::NotQa, - "authority-split.test.ts: passwordless non-QA multi-seed URI", - ), - ( - "mongodb://u:p@[::1]:27018/stock_dev", - ExpectedTargetOutcome::NotQa, - "authority-split.test.ts: IPv6 dev port 27018", - ), - ( - "mongodb://u:p@local\u{00A0}host:27017/stock", - ExpectedTargetOutcome::Rejected, - "authority-split.test.ts: NBSP in host", - ), - ( - "mongodb://u:p@local\u{2028}host:27017/stock", - ExpectedTargetOutcome::Rejected, - "authority-split.test.ts: line separator in host", - ), - ( - "mongodb://u:p@localhost:27018,\u{3000}localhost/stock", - ExpectedTargetOutcome::Rejected, - "authority-split.test.ts: ideographic space in host list", - ), - ( - "mongodb://u:p@[::1]#:27018/stock", - ExpectedTargetOutcome::Rejected, - "authority-split.test.ts: IPv6 loopback behind raw #", - ), - // --- 3. test/unit/environment-safety-edge-cases.test.ts --- - ( - "mongodb://studio_stock_bot_read:secret@127.0.0.1:27017/stock", - ExpectedTargetOutcome::Qa, - "edge-cases.test.ts: 127.0.0.1:27017", - ), - ( - "mongodb://studio_stock_bot_read:secret@0.0.0.0:27017/stock", - ExpectedTargetOutcome::Qa, - "edge-cases.test.ts: 0.0.0.0:27017", - ), - ( - "mongodb://studio_stock_bot_read:secret@[::1]:27017/stock", - ExpectedTargetOutcome::Qa, - "edge-cases.test.ts: [::1]:27017", - ), - ( - "mongodb://studio_stock_bot_read:secret@LOCALHOST:27017/stock", - ExpectedTargetOutcome::Qa, - "edge-cases.test.ts: LOCALHOST:27017", - ), - ( - "mongodb://studio_stock_bot_read:secret@localhost/stock", - ExpectedTargetOutcome::Qa, - "edge-cases.test.ts: omitted port", - ), - ( - "mongodb://studio_stock_bot_read:secret@localhost:27017/other", - ExpectedTargetOutcome::Qa, - "edge-cases.test.ts: different db name on QA server", - ), - ( - "mongodb://writer:pw@10.0.0.51:27017/stock", - ExpectedTargetOutcome::NotQa, - "edge-cases.test.ts: remote host 10.0.0.51:27017", - ), - ( - "mongodb://reader:pw@10.0.0.51:27017/stock", - ExpectedTargetOutcome::NotQa, - "edge-cases.test.ts: remote reader 10.0.0.51:27017", - ), - ( - "mongodb://trading%5Fadmin:pw@localhost:27017/stock", - ExpectedTargetOutcome::Qa, - "edge-cases.test.ts: percent-encoded trading_admin on QA", - ), - ( - "mongodb://trading_admin:pw@localhost:27017/stock", - ExpectedTargetOutcome::Qa, - "edge-cases.test.ts: fallback uri trading_admin on QA", - ), - // --- 4. test/unit/environment-safety-encoded-host.test.ts --- - ( - "mongodb://u:p@%6cocalhost:27017/stock", - ExpectedTargetOutcome::Qa, - "encoded-host.test.ts: %6cocalhost:27017", - ), - ( - "mongodb://trading_admin:pass@%6cocalhost:27017/stock", - ExpectedTargetOutcome::Qa, - "encoded-host.test.ts: trading_admin on %6cocalhost:27017", - ), - ( - "mongodb://studio_stock_bot_read:secret@%6cocalhost:27017/stock?authSource=stock", - ExpectedTargetOutcome::Qa, - "encoded-host.test.ts: read user on %6cocalhost:27017", - ), - ( - "mongodb://dev_admin:dev_mongo_pass@%6cocalhost:27017/stock?authSource=admin", - ExpectedTargetOutcome::Qa, - "encoded-host.test.ts: schema-validated encoded QA seed", - ), - ( - "mongodb://u:p@%31%32%37%2e%30%2e%30%2e%31:27017/stock", - ExpectedTargetOutcome::Qa, - "encoded-host.test.ts: fully encoded 127.0.0.1", - ), - ( - "mongodb://u:p@127%2E0.0.1:27017/stock", - ExpectedTargetOutcome::Qa, - "encoded-host.test.ts: encoded dot in 127.0.0.1", - ), - ( - "mongodb://u:p@%4C%6fCalHost:27017/stock", - ExpectedTargetOutcome::Qa, - "encoded-host.test.ts: mixed-case encoded localhost", - ), - ( - "mongodb://u:p@%4C%4F%43%41%4C%48%4F%53%54:27017/stock", - ExpectedTargetOutcome::Qa, - "encoded-host.test.ts: uppercase encoded LOCALHOST", - ), - ( - "mongodb://u:p@%6cocalhost%2e:27017/stock", - ExpectedTargetOutcome::Qa, - "encoded-host.test.ts: encoded trailing dot", - ), - ( - "mongodb://u:p@%6cocalhost/stock", - ExpectedTargetOutcome::Qa, - "encoded-host.test.ts: encoded localhost omitted port", - ), - ( - "mongodb+srv://u:p@%6cocalhost/stock", - ExpectedTargetOutcome::Qa, - "encoded-host.test.ts: srv encoded localhost", - ), - ( - "mongodb://u:p@[::1%25lo]:27017/stock", - ExpectedTargetOutcome::Qa, - "encoded-host.test.ts: IPv6 loopback with zone ID", - ), - ( - "mongodb://u:p@[::ffff:%37%66%30%30:1]:27017/stock", - ExpectedTargetOutcome::Qa, - "encoded-host.test.ts: encoded IPv4-mapped IPv6", - ), - ( - "mongodb://u:p@localhost:27018,%6cocalhost:27017/stock_dev", - ExpectedTargetOutcome::Qa, - "encoded-host.test.ts: multi-host encoded localhost", - ), - ( - "mongodb://u:p@localhost:27018,%31%32%37.0.0.1/stock_dev", - ExpectedTargetOutcome::Qa, - "encoded-host.test.ts: multi-host encoded 127.0.0.1 omitted port", - ), - ( - "mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev", - ExpectedTargetOutcome::NotQa, - "encoded-host.test.ts: safe dev localhost:27018", - ), - ( - "mongodb://dev_admin:dev_mongo_pass@%6cocalhost:27018/stock_dev", - ExpectedTargetOutcome::NotQa, - "encoded-host.test.ts: encoded localhost on dev port 27018", - ), - ( - "mongodb://dev_admin:dev_mongo_pass@localhost:27018,127.0.0.1:27019/stock_dev", - ExpectedTargetOutcome::NotQa, - "encoded-host.test.ts: safe dev multi-host", - ), - ( - "mongodb://u:p@%zz:27017/stock", - ExpectedTargetOutcome::Rejected, - "encoded-host.test.ts: malformed %zz", - ), - ( - "mongodb://u:p@%zz:27018/stock_dev", - ExpectedTargetOutcome::Rejected, - "encoded-host.test.ts: malformed %zz on dev port", - ), - ( - "mongodb://u:p@localhost:27018,%zz:27017/stock_dev", - ExpectedTargetOutcome::Rejected, - "encoded-host.test.ts: malformed %zz second seed rejects entire URI", - ), - ( - "mongodb://u:p@local%2:27017/stock", - ExpectedTargetOutcome::Rejected, - "encoded-host.test.ts: truncated %2", - ), - ( - "mongodb://u:p@localhost%:27017/stock", - ExpectedTargetOutcome::Rejected, - "encoded-host.test.ts: trailing %", - ), - ( - "mongodb://u:p@[::1%zz]:27017/stock", - ExpectedTargetOutcome::Rejected, - "encoded-host.test.ts: IPv6 malformed %zz", - ), - ( - "mongodb://u:p@[not-ipv6%25zz]:27017/stock", - ExpectedTargetOutcome::Rejected, - "encoded-host.test.ts: non-IPv6 with %25", - ), - ( - "mongodb://u:p@[::1%25]:27017/stock", - ExpectedTargetOutcome::Rejected, - "encoded-host.test.ts: IPv6 empty zone ID", - ), - ( - "mongodb://u:p@[::1%25lo%2f]:27017/stock", - ExpectedTargetOutcome::Rejected, - "encoded-host.test.ts: IPv6 zone ID with %2f", - ), - ( - "mongodb://u:p@%256cocalhost:27017/stock", - ExpectedTargetOutcome::Qa, - "encoded-host.test.ts: double-encoded localhost", - ), - ( - "mongodb://u:p@%2531%2532%2537.0.0.1:27017/stock", - ExpectedTargetOutcome::Qa, - "encoded-host.test.ts: double-encoded 127.0.0.1", - ), - ( - "mongodb://u:p@localhost:27018,%256cocalhost:27017/stock_dev", - ExpectedTargetOutcome::Qa, - "encoded-host.test.ts: multi-host double-encoded localhost", - ), - ( - "mongodb://u:p@%25256cocalhost:27017/stock", - ExpectedTargetOutcome::Qa, - "encoded-host.test.ts: triple-encoded localhost", - ), - ( - "mongodb://trading_admin:pass@%256cocalhost:27017/stock", - ExpectedTargetOutcome::Qa, - "encoded-host.test.ts: trading_admin on double-encoded localhost", - ), - ( - "mongodb://studio_stock_bot_read:secret@%256cocalhost:27017/stock?authSource=stock", - ExpectedTargetOutcome::Qa, - "encoded-host.test.ts: read user on double-encoded localhost", - ), - ( - "mongodb://dev_admin:dev_mongo_pass@%256cocalhost:27018/stock_dev", - ExpectedTargetOutcome::NotQa, - "encoded-host.test.ts: double-encoded localhost on 27018", - ), - ( - "mongodb://u:p@localhost:27018/stock_dev", - ExpectedTargetOutcome::NotQa, - "encoded-host.test.ts: parityCase dev localhost:27018", - ), - ( - "mongodb://u:p@%6cocalhost:27018/stock_dev", - ExpectedTargetOutcome::NotQa, - "encoded-host.test.ts: parityCase encoded dev localhost:27018", - ), - ( - "mongodb://u:p@%256cocalhost:27018/stock_dev", - ExpectedTargetOutcome::NotQa, - "encoded-host.test.ts: parityCase double-encoded dev localhost:27018", - ), - ( - "mongodb://u:p@mongo.internal:27017/stock", - ExpectedTargetOutcome::NotQa, - "encoded-host.test.ts: parityCase remote mongo.internal:27017", - ), - ( - "mongodb://u:p@%25zz:27017/stock", - ExpectedTargetOutcome::Rejected, - "encoded-host.test.ts: double-encoded malformed %25zz", - ), - ( - "mongodb://u:p@%2525252525252525256cocalhost:27017/stock", - ExpectedTargetOutcome::Rejected, - "encoded-host.test.ts: excessive percent-encoding nesting (>8 passes)", - ), - ( - "mongodb://u:p@localhost%2f:27018/stock_dev", - ExpectedTargetOutcome::Rejected, - "encoded-host.test.ts: delimiter smuggling %2f", - ), - ( - "mongodb://u:p@%6cocalhost%2f:27018/stock_dev", - ExpectedTargetOutcome::Rejected, - "encoded-host.test.ts: delimiter smuggling %6cocalhost%2f", - ), - ( - "mongodb://u:p@localhost:27018,localhost%2f:27019/stock_dev", - ExpectedTargetOutcome::Rejected, - "encoded-host.test.ts: multi-host delimiter smuggling second seed", - ), - ( - "mongodb://u:p@localhost%3f:27018/stock_dev", - ExpectedTargetOutcome::Rejected, - "encoded-host.test.ts: delimiter smuggling %3f", - ), - ( - "mongodb://u:p@localhost%23:27018/stock_dev", - ExpectedTargetOutcome::Rejected, - "encoded-host.test.ts: delimiter smuggling %23", - ), - ( - "mongodb://u:p@%6cocalhost%3a27017%2f:27018/stock_dev", - ExpectedTargetOutcome::Rejected, - "encoded-host.test.ts: delimiter smuggling %3a + %2f", - ), - ( - "mongodb://u:p@x%40localhost%3a27017%2f:27018/stock_dev", - ExpectedTargetOutcome::Rejected, - "encoded-host.test.ts: delimiter smuggling %40", - ), - ( - "mongodb://u:p@%5b%3a%3a1%5d%3a27017%2f:27018/stock_dev", - ExpectedTargetOutcome::Rejected, - "encoded-host.test.ts: delimiter smuggling brackets", - ), - ( - "mongodb://u:p@localhost%252f:27018/stock_dev", - ExpectedTargetOutcome::Rejected, - "encoded-host.test.ts: double-encoded %252f", - ), - ( - "mongodb://u:p@localhost%5c:27018/stock_dev", - ExpectedTargetOutcome::Rejected, - "encoded-host.test.ts: encoded backslash %5c", - ), - ( - "mongodb://u:p@localhost%20:27018/stock_dev", - ExpectedTargetOutcome::Rejected, - "encoded-host.test.ts: encoded space %20", - ), - ( - "mongodb://u:p@[::1%2f]:27018/stock_dev", - ExpectedTargetOutcome::Rejected, - "encoded-host.test.ts: IPv6 with %2f", - ), - ( - "mongodb://u:p@localhost%00:27018/stock_dev", - ExpectedTargetOutcome::Rejected, - "encoded-host.test.ts: encoded NUL %00", - ), - ( - "mongodb://u:p@loc%0aalhost:27018/stock_dev", - ExpectedTargetOutcome::Rejected, - "encoded-host.test.ts: encoded LF %0a", - ), - ( - "mongodb://u:p@localhost%1f:27018/stock_dev", - ExpectedTargetOutcome::Rejected, - "encoded-host.test.ts: encoded 0x1f", - ), - ( - "mongodb://u:p@localhost%7f:27018/stock_dev", - ExpectedTargetOutcome::Rejected, - "encoded-host.test.ts: encoded DEL %7f", - ), - ( - "mongodb://u:p@localhost%7F:27018/stock_dev", - ExpectedTargetOutcome::Rejected, - "encoded-host.test.ts: encoded DEL %7F uppercase", - ), - ( - "mongodb://u:p@local%01host:27018/stock_dev", - ExpectedTargetOutcome::Rejected, - "encoded-host.test.ts: encoded SOH %01", - ), - ( - "mongodb://u:p@localhost%2500:27018/stock_dev", - ExpectedTargetOutcome::Rejected, - "encoded-host.test.ts: double-encoded NUL %2500", - ), - ( - "mongodb://u:p@localhost%257f:27018/stock_dev", - ExpectedTargetOutcome::Rejected, - "encoded-host.test.ts: double-encoded DEL %257f", - ), - ( - "mongodb://u:p@mongo.internal:27018,localhost%1f:27018/stock_dev", - ExpectedTargetOutcome::Rejected, - "encoded-host.test.ts: multi-host encoded 0x1f second seed", - ), - ( - "mongodb://u:p@[::1%00]:27018/stock_dev", - ExpectedTargetOutcome::Rejected, - "encoded-host.test.ts: IPv6 encoded NUL", - ), - ( - "mongodb://u:p@[::1%7f]:27018/stock_dev", - ExpectedTargetOutcome::Rejected, - "encoded-host.test.ts: IPv6 encoded DEL", - ), - ( - "mongodb://u:p@mongo%7einternal:27018/stock_dev", - ExpectedTargetOutcome::NotQa, - "encoded-host.test.ts: printable non-delimiter 0x7e (~) allowed", - ), - ( - "mongodb://dev_admin:dev_mongo_pass@%6C%4F%63%61%6C%68%6F%73%74:27018/stock_dev", - ExpectedTargetOutcome::NotQa, - "encoded-host.test.ts: mixed-case encoded dev port 27018", - ), - ( - "mongodb://dev_admin:dev_mongo_pass@%2531%2532%2537.0.0.1:27018/stock_dev", - ExpectedTargetOutcome::NotQa, - "encoded-host.test.ts: double-encoded 127.0.0.1 on dev port 27018", - ), - ( - "mongodb://dev_admin:dev_mongo_pass@[::1]:27018/stock_dev", - ExpectedTargetOutcome::NotQa, - "encoded-host.test.ts: IPv6 loopback on dev port 27018", - ), - ( - "mongodb://dev_admin:dev_mongo_pass@%6cocalhost:27018,127%2e0.0.1:27019/stock_dev", - ExpectedTargetOutcome::NotQa, - "encoded-host.test.ts: encoded dev multi-host 27018/27019", - ), - ( - "mongodb+srv://prod_user:Str0ngProdSecret@cluster0.prod-db.example.net/stock?retryWrites=true", - ExpectedTargetOutcome::NotQa, - "encoded-host.test.ts: prod SRV host", - ), - ( - "mongodb://prod_user:Str0ngProdSecret@mongo-0.prod.internal:27017,mongo-1.prod.internal:27017/stock?replicaSet=rs0", - ExpectedTargetOutcome::NotQa, - "encoded-host.test.ts: prod TCP multi-host", - ), - ( - "mongodb://prod_user:Str0ngProdSecret@%6dongo-0.prod.internal:27017/stock", - ExpectedTargetOutcome::NotQa, - "encoded-host.test.ts: encoded remote host", - ), - // --- 5. test/unit/environment-safety-multi-host.test.ts --- - ( - "mongodb://u:p@db1.dev.internal:27018,db2.dev.internal:27018,127.0.0.1:27017/stock_dev", - ExpectedTargetOutcome::Qa, - "multi-host.test.ts: 3-host list ending in 127.0.0.1:27017", - ), - ( - "mongodb://u:p@localhost:27018,localhost:27019,localhost/stock_dev?replicaSet=rs0", - ExpectedTargetOutcome::Qa, - "multi-host.test.ts: 3-host list ending in omitted-port localhost", - ), - ( - "mongodb://u:p@localhost:27018,0.0.0.0:27017/stock_dev", - ExpectedTargetOutcome::Qa, - "multi-host.test.ts: 0.0.0.0:27017 second host", - ), - ( - "mongodb://u:p@localhost:27018,localhost:027017/stock_dev", - ExpectedTargetOutcome::Qa, - "multi-host.test.ts: leading-zero port 027017", - ), - ( - "mongodb://u:p,w@localhost:27018,localhost:27017/stock", - ExpectedTargetOutcome::Qa, - "multi-host.test.ts: comma in password", - ), - ( - "mongodb://localhost:27018,localhost:27017", - ExpectedTargetOutcome::Qa, - "multi-host.test.ts: no userinfo no path", - ), - ( - "mongodb://u:p@localhost:27018,localhost:27019/stock_dev?appName=localhost:27017", - ExpectedTargetOutcome::NotQa, - "multi-host.test.ts: localhost:27017 only in query string", - ), - ( - "mongodb://u:p@10.0.0.51:27017,10.0.0.52:27017/stock", - ExpectedTargetOutcome::NotQa, - "multi-host.test.ts: remote multi-host on 27017", - ), - ( - "mongodb://u:p@localhost:27018,localhost:27017/stock", - ExpectedTargetOutcome::Qa, - "multi-host.test.ts: non-pipeline dev service QA seed list", - ), - ( - "mongodb://trading_admin:pw@localhost:27018,localhost:27017/stock", - ExpectedTargetOutcome::Qa, - "multi-host.test.ts: pipeline fallback trading_admin seed list", - ), - ( - "mongodb://studio_stock_bot_read:pw@localhost:27018,localhost:27017/stock", - ExpectedTargetOutcome::Qa, - "multi-host.test.ts: pipeline fallback read user seed list", - ), - ( - "mongodb://u:p@localhost:27018,,localhost:27017/stock", - ExpectedTargetOutcome::Qa, - "multi-host.test.ts: empty middle seed still classifies QA in parse_mongo_target", - ), - ( - "mongodb://u:p@localhost:27018,localhost:27017,/stock", - ExpectedTargetOutcome::Qa, - "multi-host.test.ts: trailing comma seed still classifies QA in parse_mongo_target", - ), - ( - "mongodb://r:pw@localhost:27017,localhost:27018/stock?authSource=stock", - ExpectedTargetOutcome::Qa, - "multi-host.test.ts: container db selection QA multi-host", - ), - ( - "mongodb://r:pw@h1.internal:27017,h2.internal/stock%5Fqa?authSource=admin", - ExpectedTargetOutcome::NotQa, - "multi-host.test.ts: container db selection remote encoded db", - ), - ( - "mongodb://r:pw@h1.internal,h2.internal/stock#frag", - ExpectedTargetOutcome::NotQa, - "multi-host.test.ts: container db selection remote with fragment", - ), - ( - "mongodb://r:pw@h1.internal:27017,h2.internal:27018/?replicaSet=rs0", - ExpectedTargetOutcome::NotQa, - "multi-host.test.ts: container db selection remote empty db", - ), - ( - "mongodb://r:pw@h1.internal,h2.internal", - ExpectedTargetOutcome::NotQa, - "multi-host.test.ts: container db selection remote no path", - ), - ]; - - assert!( - vectors.len() >= 100, - "expected >= 100 parity vectors, got {}", - vectors.len() - ); - - for (uri, expected, label) in vectors { - match (parse_mongo_target(uri), expected) { - (Ok(target), ExpectedTargetOutcome::Qa) => { - assert!( - is_qa_mongo_target(&target, &local_hosts), - "expected QA target for {label} ({uri:?}), parsed: {target:?}" - ); - } - (Ok(target), ExpectedTargetOutcome::NotQa) => { - assert!( - !is_qa_mongo_target(&target, &local_hosts), - "expected NotQa target for {label} ({uri:?}), parsed: {target:?}" - ); - } - (Err(_), ExpectedTargetOutcome::Rejected) => {} - (other, exp) => { - panic!("mismatch for {label} ({uri:?}): expected {exp:?}, got {other:?}"); - } - } - } -} - -#[test] -fn qa_target_classification_covers_all_required_host_forms() { - let local_hosts = injected_local_hosts(); - - let required_qa_uris = [ - "mongodb://studio_stock_bot_read:pw@localhost:27017/stock", - "mongodb://studio_stock_bot_read:pw@LOCALHOST.:27017/stock", - "mongodb://studio_stock_bot_read:pw@127.0.0.1:27017/stock", - "mongodb://studio_stock_bot_read:pw@127.1:27017/stock", - "mongodb://studio_stock_bot_read:pw@2130706433:27017/stock", - "mongodb://studio_stock_bot_read:pw@0x7f000001:27017/stock", - "mongodb://studio_stock_bot_read:pw@0177.0.0.1:27017/stock", - "mongodb://studio_stock_bot_read:pw@0127.0.0.1:27017/stock", - "mongodb://studio_stock_bot_read:pw@[::1]:27017/stock", - "mongodb://studio_stock_bot_read:pw@[::ffff:127.0.0.1]:27017/stock", - "mongodb://studio_stock_bot_read:pw@%6c%6f%63%61%6c%68%6f%73%74:27017/stock", - // Injected LAN IP (plain, hex, leading-zero decimal) and hostnames (full, short, .local) - "mongodb://studio_stock_bot_read:pw@192.168.1.50:27017/stock", - "mongodb://studio_stock_bot_read:pw@0xc0a80132:27017/stock", - "mongodb://studio_stock_bot_read:pw@192.168.001.050:27017/stock", - "mongodb://studio_stock_bot_read:pw@quant.lan.local:27017/stock", - "mongodb://studio_stock_bot_read:pw@quant:27017/stock", - "mongodb://studio_stock_bot_read:pw@quant.local:27017/stock", - "mongodb://studio_stock_bot_read:pw@[fe80::1234:5678%25eth0]:27017/stock", - // Omitted port - "mongodb://studio_stock_bot_read:pw@localhost/stock", - // Multi-host where only the second host is loopback - "mongodb://studio_stock_bot_read:pw@mongo.remote.internal:27018,127.0.0.1:27017/stock", - ]; - - for uri in required_qa_uris { - let target = parse_mongo_target(uri).unwrap_or_else(|e| panic!("failed to parse {uri}: {e}")); - assert!( - is_qa_mongo_target(&target, &local_hosts), - "expected QA target for {uri}" - ); - } -} - -#[test] -fn assert_read_only_rejects_trading_admin_on_any_host_and_any_casing_or_encoding() { - let local_hosts = injected_local_hosts(); - // Even if a caller mistakenly puts trading_admin in allowed_read_users, it must still be rejected. - let permissive_policy = ReadOnlyPolicy { - allowed_read_users: vec![ - DEFAULT_ALLOWED_READ_USER.to_owned(), - FORBIDDEN_ADMIN_USER.to_owned(), - "TRADING_ADMIN".to_owned(), - ], - }; - - let admin_uris = [ - // QA hosts - "mongodb://trading_admin:pw@localhost:27017/stock", - "mongodb://TRADING_ADMIN:pw@localhost:27017/stock", - "mongodb://TrAdInG_aDmIn:pw@127.0.0.1:27017/stock", - "mongodb://trading%5Fadmin:pw@localhost:27017/stock", - "mongodb://%74%72%61%64%69%6e%67%5f%61%64%6d%69%6e:pw@[::1]:27017/stock", - // Non-QA hosts (dev port 27018, remote host, srv) - "mongodb://trading_admin:pw@localhost:27018/stock_dev", - "mongodb://TRADING_ADMIN:pw@10.0.0.51:27017/stock", - "mongodb://TrAdInG_aDmIn:pw@mongo.prod.internal:27017/stock", - "mongodb://trading%5Fadmin:pw@localhost:27018/stock_dev", - "mongodb+srv://trading_admin:pw@cluster.example.com/stock", - ]; - - for uri in admin_uris { - assert_eq!( - assert_read_only_mongo_uri(uri, &ReadOnlyPolicy::default(), &local_hosts), - Err(MongoSafetyError::ForbiddenAdminUser), - "default policy must reject {uri}" - ); - assert_eq!( - assert_read_only_mongo_uri(uri, &permissive_policy, &local_hosts), - Err(MongoSafetyError::ForbiddenAdminUser), - "permissive policy must still reject {uri}" - ); - } -} - -#[test] -fn assert_read_only_enforces_qa_credentials_and_allowlist() { - let local_hosts = injected_local_hosts(); - let policy = ReadOnlyPolicy::default(); - - // Missing credentials on QA targets - for uri in [ - "mongodb://localhost:27017/stock", - "mongodb://127.0.0.1/stock", - "mongodb://:secret_pw@localhost:27017/stock", - "mongodb://quant.lan.local:27017/stock", - ] { - assert_eq!( - assert_read_only_mongo_uri(uri, &policy, &local_hosts), - Err(MongoSafetyError::MissingCredentialsForQaTarget), - "expected MissingCredentialsForQaTarget for {uri}" - ); - } - - // Non-allowlisted usernames on QA targets (including case mismatch) - for uri in [ - "mongodb://dev_admin:pw@localhost:27017/stock", - "mongodb://STUDIO_STOCK_BOT_READ:pw@localhost:27017/stock", - "mongodb://other_reader:pw@127.1:27017/stock", - "mongodb://reader:pw@localhost:27018,localhost:27017/stock", - ] { - assert_eq!( - assert_read_only_mongo_uri(uri, &policy, &local_hosts), - Err(MongoSafetyError::UnauthorizedQaUser), - "expected UnauthorizedQaUser for {uri}" - ); - } - - // Custom allowlist accepts a custom read user on QA - let custom_policy = ReadOnlyPolicy { - allowed_read_users: vec!["custom_ro".to_owned()], - }; - let validated = assert_read_only_mongo_uri( - "mongodb://custom_ro:s3cr3t@localhost:27017/stock", - &custom_policy, - &local_hosts, - ) - .expect("custom allowlisted user should pass"); - assert!(validated.is_qa_target()); - assert_eq!(validated.target().username.as_deref(), Some("custom_ro")); -} - -#[test] -fn assert_read_only_rejects_authority_splits_control_chars_malformed_segments_and_bad_srv() { - let local_hosts = injected_local_hosts(); - let policy = ReadOnlyPolicy::default(); - - let cases: &[(&str, MongoSafetyError)] = &[ - ("", MongoSafetyError::EmptyUri), - (" ", MongoSafetyError::ForbiddenWhitespace), - ("http://localhost:27017/stock", MongoSafetyError::UnsupportedScheme), - ("postgres://localhost:5432/db", MongoSafetyError::UnsupportedScheme), - ("not-a-uri", MongoSafetyError::UnsupportedScheme), - ( - "mongodb://studio_stock_bot_read:pw@localhost:27018#,localhost:27017/stock", - MongoSafetyError::UnencodedHashInAuthority, - ), - ( - "mongodb://studio_stock_bot_read:pw@localhost:27017@x:27018/stock", - MongoSafetyError::MultipleAtInAuthority, - ), - ( - "mongodb://localhost:27018/stock_dev?appName=a@b", - MongoSafetyError::UnencodedAtInRemainderWithoutCredentials, - ), - ( - "mongodb://localhost:27018/stock_dev#frag@x", - MongoSafetyError::UnencodedAtInRemainderWithoutCredentials, - ), - ( - "mongodb://studio_stock_bot_read:pw@local\nhost:27017/stock", - MongoSafetyError::ControlCharacters, - ), - ( - "mongodb://studio_stock_bot_read:pw@localhost:27017/stock\x00", - MongoSafetyError::ControlCharacters, - ), - ( - "mongodb://studio_stock_bot_read:pw@localhost:27017/stock\x7f", - MongoSafetyError::ControlCharacters, - ), - ( - "mongodb://studio_stock_bot_read:pw@local\u{00A0}host:27017/stock", - MongoSafetyError::ForbiddenWhitespace, - ), - ( - "mongodb://studio_stock_bot_read:pw@localhost:27017/stock\u{FEFF}", - MongoSafetyError::ForbiddenWhitespace, - ), - ( - "mongodb://studio_stock_bot_read:pw@bad:port,localhost:27017/stock", - MongoSafetyError::MalformedHostSegment, - ), - ( - "mongodb://studio_stock_bot_read:pw@localhost:27018,,localhost:27017/stock", - MongoSafetyError::MalformedHostSegment, - ), - ( - "mongodb://studio_stock_bot_read:pw@localhost:27018,localhost:27017,/stock", - MongoSafetyError::MalformedHostSegment, - ), - ( - "mongodb+srv://studio_stock_bot_read:pw@cluster.example.com:27017/stock", - MongoSafetyError::InvalidSrvTarget, - ), - ( - "mongodb+srv://studio_stock_bot_read:pw@cluster.example.com:/stock", - MongoSafetyError::InvalidSrvTarget, - ), - ( - "mongodb+srv://studio_stock_bot_read:pw@a.example.com,b.example.com/stock", - MongoSafetyError::InvalidSrvTarget, - ), - ( - "mongodb://bad%zzuser:pw@localhost:27018/stock_dev", - MongoSafetyError::InvalidUsernameEncoding, - ), - // Malformed bracketed IPv6 literals (single-seed and multi-seed) - ( - "mongodb://studio_stock_bot_read:pw@[fe80::g]:27017/stock", - MongoSafetyError::NoValidHosts, - ), - ( - "mongodb://studio_stock_bot_read:pw@[::1::2]:27017/stock", - MongoSafetyError::NoValidHosts, - ), - ( - "mongodb://studio_stock_bot_read:pw@[1:2:3]:27017/stock", - MongoSafetyError::NoValidHosts, - ), - ( - "mongodb://studio_stock_bot_read:pw@[not-an-ipv6]:27017/stock", - MongoSafetyError::NoValidHosts, - ), - ( - "mongodb://studio_stock_bot_read:pw@[localhost]:27017/stock", - MongoSafetyError::NoValidHosts, - ), - ( - "mongodb://studio_stock_bot_read:pw@localhost:27018,[fe80::g]:27017/stock", - MongoSafetyError::MalformedHostSegment, - ), - ( - "mongodb://studio_stock_bot_read:pw@[fe80::g]:27017,localhost:27017/stock", - MongoSafetyError::MalformedHostSegment, - ), - ]; - - for (uri, expected_err) in cases { - assert_eq!( - assert_read_only_mongo_uri(uri, &policy, &local_hosts), - Err(expected_err.clone()), - "unexpected outcome for {uri:?}" - ); - } - - // Multi-seed URI with a malformed bracketed IPv6 and a valid QA seed still classifies as QA in - // parse_mongo_target + is_qa_mongo_target (preserving TS classifier behavior), while - // assert_read_only_mongo_uri above fails closed with MalformedHostSegment. - let mixed_target = parse_mongo_target( - "mongodb://studio_stock_bot_read:pw@[fe80::g]:27017,localhost:27017/stock", - ) - .expect("valid second seed should survive parse_mongo_target"); - assert!(mixed_target.has_invalid_host_segment()); - assert!(is_qa_mongo_target(&mixed_target, &local_hosts)); - - // Valid non-loopback bracketed IPv6 literals are still accepted. - for valid_ipv6_uri in [ - "mongodb://reader:pw@[fe80::1]:27017/stock", - "mongodb://reader:pw@[2001:db8::1]:27017/stock", - "mongodb://reader:pw@[::ffff:0a00:1]:27017/stock", - ] { - let validated = assert_read_only_mongo_uri(valid_ipv6_uri, &policy, &local_hosts) - .unwrap_or_else(|e| panic!("valid non-loopback IPv6 should pass ({valid_ipv6_uri}): {e}")); - assert!(!validated.is_qa_target()); - } -} - -#[test] -fn valid_qa_read_only_uri_is_accepted_and_passwords_are_redacted_everywhere() { - let local_hosts = injected_local_hosts(); - let policy = ReadOnlyPolicy::default(); - let secret = "SuperSecret_Pass:With:Colons%21"; - let uri = format!( - "mongodb://studio_stock_bot_read:{secret}@localhost:27017/stock?authSource=stock" - ); - - let validated = assert_read_only_mongo_uri(&uri, &policy, &local_hosts) - .expect("studio_stock_bot_read on QA localhost:27017 should be accepted"); - - assert_eq!(validated.as_str(), uri); - assert!(validated.is_qa_target()); - assert_eq!(validated.target().scheme, MongoScheme::Standard); - assert_eq!(validated.target().database.as_deref(), Some("stock")); - assert_eq!( - validated.target().username.as_deref(), - Some("studio_stock_bot_read") - ); - assert_eq!( - validated.redacted(), - "mongodb://studio_stock_bot_read:[REDACTED]@localhost:27017/stock?authSource=stock" - ); - - let display_out = format!("{validated}"); - let debug_out = format!("{validated:?}"); - assert!(!display_out.contains(secret), "Display leaked password: {display_out}"); - assert!(!debug_out.contains(secret), "Debug leaked password: {debug_out}"); - assert!(display_out.contains("[REDACTED]")); - assert!(debug_out.contains("[REDACTED]")); - - // Passwordless non-QA URI remains unchanged by redaction - let no_pass = assert_read_only_mongo_uri( - "mongodb://dev_user@localhost:27018/stock_dev", - &policy, - &local_hosts, - ) - .expect("passwordless non-QA URI should be accepted"); - assert!(!no_pass.is_qa_target()); - assert_eq!( - no_pass.redacted(), - "mongodb://dev_user@localhost:27018/stock_dev" - ); - - // Exhaustive redaction check across EVERY MongoSafetyError variant. - // The match below has no wildcard arm so adding a new variant forces test coverage. - fn error_variant_index(err: &MongoSafetyError) -> usize { - match err { - MongoSafetyError::EmptyUri => 0, - MongoSafetyError::ControlCharacters => 1, - MongoSafetyError::ForbiddenWhitespace => 2, - MongoSafetyError::UnsupportedScheme => 3, - MongoSafetyError::EmptyAuthority => 4, - MongoSafetyError::UnencodedHashInAuthority => 5, - MongoSafetyError::EmptyUserinfo => 6, - MongoSafetyError::MultipleAtInAuthority => 7, - MongoSafetyError::UnencodedAtInRemainderWithoutCredentials => 8, - MongoSafetyError::EmptyHostList => 9, - MongoSafetyError::InvalidUsernameEncoding => 10, - MongoSafetyError::InvalidHostEncoding => 11, - MongoSafetyError::ForbiddenHostCharacters => 12, - MongoSafetyError::NoValidHosts => 13, - MongoSafetyError::MalformedHostSegment => 14, - MongoSafetyError::InvalidSrvTarget => 15, - MongoSafetyError::ForbiddenAdminUser => 16, - MongoSafetyError::MissingCredentialsForQaTarget => 17, - MongoSafetyError::UnauthorizedQaUser => 18, - } - } - const VARIANT_COUNT: usize = 19; - - let err_secret = "LeakCheck_Pw98765"; - let error_cases: Vec<(String, MongoSafetyError)> = vec![ - (String::new(), MongoSafetyError::EmptyUri), - ( - format!("mongodb://studio_stock_bot_read:{err_secret}@local\nhost:27017/stock"), - MongoSafetyError::ControlCharacters, - ), - ( - format!("mongodb://studio_stock_bot_read:{err_secret}@local\u{00A0}host:27017/stock"), - MongoSafetyError::ForbiddenWhitespace, - ), - ( - format!("http://studio_stock_bot_read:{err_secret}@localhost:27017/stock"), - MongoSafetyError::UnsupportedScheme, - ), - ( - format!("mongodb:///stock?pw={err_secret}"), - MongoSafetyError::EmptyAuthority, - ), - ( - format!( - "mongodb://studio_stock_bot_read:{err_secret}@localhost:27018#,localhost:27017/stock" - ), - MongoSafetyError::UnencodedHashInAuthority, - ), - ( - format!("mongodb://@localhost:27018/stock?pw={err_secret}"), - MongoSafetyError::EmptyUserinfo, - ), - ( - format!( - "mongodb://studio_stock_bot_read:{err_secret}@localhost:27017@x:27018/stock" - ), - MongoSafetyError::MultipleAtInAuthority, - ), - ( - format!("mongodb://localhost:27018/stock?pw={err_secret}@x"), - MongoSafetyError::UnencodedAtInRemainderWithoutCredentials, - ), - ( - format!("mongodb://studio_stock_bot_read:{err_secret}@/stock"), - MongoSafetyError::EmptyHostList, - ), - ( - format!("mongodb://bad%zz:{err_secret}@localhost:27018/stock_dev"), - MongoSafetyError::InvalidUsernameEncoding, - ), - ( - format!("mongodb://studio_stock_bot_read:{err_secret}@%zz:27017/stock"), - MongoSafetyError::InvalidHostEncoding, - ), - ( - format!("mongodb://studio_stock_bot_read:{err_secret}@localhost%2f:27018/stock"), - MongoSafetyError::ForbiddenHostCharacters, - ), - ( - format!("mongodb://studio_stock_bot_read:{err_secret}@bad:port/stock"), - MongoSafetyError::NoValidHosts, - ), - ( - format!("mongodb://studio_stock_bot_read:{err_secret}@bad:port,localhost:27017/stock"), - MongoSafetyError::MalformedHostSegment, - ), - ( - format!("mongodb+srv://studio_stock_bot_read:{err_secret}@a.example.com:27017/stock"), - MongoSafetyError::InvalidSrvTarget, - ), - ( - format!("mongodb://trading_admin:{err_secret}@localhost:27017/stock"), - MongoSafetyError::ForbiddenAdminUser, - ), - ( - format!("mongodb://:{err_secret}@localhost:27017/stock"), - MongoSafetyError::MissingCredentialsForQaTarget, - ), - ( - format!("mongodb://other_user:{err_secret}@localhost:27017/stock"), - MongoSafetyError::UnauthorizedQaUser, - ), - // Extra malformed inputs where missing '@' pushes user:secret into host position - ( - format!("mongodb://studio_stock_bot_read:{err_secret}/stock"), - MongoSafetyError::NoValidHosts, - ), - ( - format!("mongodb://{err_secret}%zz:27017/stock"), - MongoSafetyError::InvalidHostEncoding, - ), - ]; - - let mut covered = [false; VARIANT_COUNT]; - for (bad_uri, expected_variant) in error_cases { - let err = assert_read_only_mongo_uri(&bad_uri, &policy, &local_hosts) - .expect_err("expected error for redaction test case"); - assert_eq!( - err, expected_variant, - "unexpected error variant for redaction input" - ); - covered[error_variant_index(&err)] = true; - let err_display = format!("{err}"); - let err_debug = format!("{err:?}"); - assert!( - !err_display.contains(err_secret), - "error Display leaked password for {expected_variant:?}: {err_display}" - ); - assert!( - !err_debug.contains(err_secret), - "error Debug leaked password for {expected_variant:?}: {err_debug}" - ); - } - assert!( - covered.iter().all(|&seen| seen), - "redaction test missed one or more MongoSafetyError variants: {covered:?}" - ); -} - -#[test] -fn deterministic_generated_parity_sweeps_match_ts_suites() { - let local_hosts = injected_local_hosts(); - let policy = ReadOnlyPolicy::default(); - - // 1. environment-safety-encoded-host.test.ts: 14 hostSpellings x 3 ports = 42 cases. - let host_spellings: &[(&str, &str)] = &[ - ("localhost", "loopback"), - ("%6cocalhost", "loopback"), - ("%256cocalhost", "loopback"), - ("127.0.0.1", "loopback"), - ("%31%32%37.0.0.1", "loopback"), - ("[::1]", "loopback"), - ("localhost%2f", "rejected"), - ("localhost%3f", "rejected"), - ("localhost%23", "rejected"), - ("localhost%3a27017%2f", "rejected"), - ("localhost%3a27017", "rejected"), - ("localhost%2c127.0.0.1", "rejected"), - ("mongo.internal", "remote"), - ("mongo.internal%2f", "rejected"), - ]; - let ports = [":27017", ":27018", ""]; - - let mut generated_count = 0usize; - for &(host, kind) in host_spellings { - for &port in &ports { - let uri = format!("mongodb://u:p@{host}{port}/stock_dev"); - generated_count += 1; - let expected = match (kind, port) { - ("rejected", _) => ExpectedTargetOutcome::Rejected, - ("remote", _) => ExpectedTargetOutcome::NotQa, - ("loopback", ":27018") => ExpectedTargetOutcome::NotQa, - ("loopback", ":27017" | "") => ExpectedTargetOutcome::Qa, - _ => unreachable!(), - }; - match (parse_mongo_target(&uri), expected) { - (Ok(target), ExpectedTargetOutcome::Qa) => { - assert!( - is_qa_mongo_target(&target, &local_hosts), - "expected Qa for generated URI {uri}" - ); - assert_eq!( - assert_read_only_mongo_uri(&uri, &policy, &local_hosts), - Err(MongoSafetyError::UnauthorizedQaUser), - "read-only guard must reject unauthorized user on QA {uri}" - ); - } - (Ok(target), ExpectedTargetOutcome::NotQa) => { - assert!( - !is_qa_mongo_target(&target, &local_hosts), - "expected NotQa for generated URI {uri}" - ); - } - (Err(_), ExpectedTargetOutcome::Rejected) => { - assert!(assert_read_only_mongo_uri(&uri, &policy, &local_hosts).is_err()); - } - (other, exp) => { - panic!("generated sweep mismatch for {uri}: expected {exp:?}, got {other:?}"); - } - } - } - } - assert_eq!(generated_count, 42); - - // 2. environment-safety-encoded-host.test.ts: deterministic 3,000-iteration seeded - // percent-encoding sweep (seed = 20261127, identical LCG formula). - // Pinned against the independent TypeScript env-safety.ts reference: - // qa = 885, not_qa = 479, rejected = 1636, FNV-1a64 = 0xf88a38ce1b8f844e (0 diffs). - fn fnv1a_update(hash: u64, byte: u8) -> u64 { - (hash ^ u64::from(byte)).wrapping_mul(0x0000_0100_0000_01b3) - } - const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325; - const OUTCOME_QA: u8 = 1; - const OUTCOME_NOT_QA: u8 = 2; - const OUTCOME_REJECTED: u8 = 3; - - let classify_rust = |uri: &str| -> (u8, Option) { - match parse_mongo_target(uri) { - Ok(target) => { - if is_qa_mongo_target(&target, &local_hosts) { - (OUTCOME_QA, None) - } else { - (OUTCOME_NOT_QA, None) - } - } - Err(err) => (OUTCOME_REJECTED, Some(err)), - } - }; - - let mut enc_state: u32 = 20261127; - let mut next_enc = || -> f64 { - enc_state = enc_state.wrapping_mul(1103515245).wrapping_add(12345) & 0x7fff_ffff; - (enc_state as f64) / (0x7fff_ffffu32 as f64) - }; - let base_hosts: &[(&str, &str)] = &[ - ("localhost", "loopback"), - ("LocalHost", "loopback"), - ("localhost.", "loopback"), - ("127.0.0.1", "loopback"), - ("127.1.2.3", "loopback"), - ("0.0.0.0", "loopback"), - ("[::1]", "bracketed_loopback"), - ("localhost/", "smuggled"), - ("localhost?", "smuggled"), - ("localhost#", "smuggled"), - ("localhost:27017", "smuggled"), - ("localhost:27017/", "smuggled"), - ("[::1]:27017/", "smuggled"), - ("localhost,localhost", "smuggled"), - ("loc%0aalhost", "smuggled"), - ("localhost%09", "smuggled"), - ("loc%00alhost", "smuggled"), - ("x%40localhost", "smuggled"), - ("%5b::1%5d", "smuggled"), - ("mongo.internal", "remote"), - ]; - let mut enc_qa = 0usize; - let mut enc_not_qa = 0usize; - let mut enc_rejected = 0usize; - let mut enc_hash = FNV_OFFSET; - for _ in 0..3000 { - let base_idx = - ((next_enc() * (base_hosts.len() as f64)) as usize).min(base_hosts.len() - 1); - let port_idx = ((next_enc() * (ports.len() as f64)) as usize).min(ports.len() - 1); - let depth = 1 + ((next_enc() * 3.0) as usize).min(2); - let (base, kind) = base_hosts[base_idx]; - let port = ports[port_idx]; - - let mut encoded = String::new(); - for ch in base.chars() { - if next_enc() < 0.4 { - let code = ch as u32; - let upper = next_enc() < 0.5; - if upper { - encoded.push_str(&format!("%{code:02X}")); - } else { - encoded.push_str(&format!("%{code:02x}")); - } - } else { - encoded.push(ch); - } - } - for _ in 1..depth { - encoded = encoded.replace('%', "%25"); - } - - let uri = format!("mongodb://u:p@{encoded}{port}/stock_dev"); - let (outcome, err) = classify_rust(&uri); - match outcome { - OUTCOME_QA => enc_qa += 1, - OUTCOME_NOT_QA => enc_not_qa += 1, - OUTCOME_REJECTED => enc_rejected += 1, - _ => unreachable!(), - } - enc_hash = fnv1a_update(enc_hash, outcome); - - match (kind, port) { - ("loopback", ":27017" | "") => { - assert_eq!( - outcome, OUTCOME_QA, - "encoded loopback QA URI must classify as Qa: {uri} (err={err:?})" - ); - assert_eq!( - assert_read_only_mongo_uri(&uri, &policy, &local_hosts), - Err(MongoSafetyError::UnauthorizedQaUser), - "read-only guard must reject unauthorized loopback QA URI: {uri}" - ); - } - ("loopback", ":27018") => { - // Valid percent-encoded loopback on dev port 27018 must NEVER be rejected. - assert_eq!( - outcome, OUTCOME_NOT_QA, - "encoded loopback dev-port URI must classify as NotQa: {uri} (err={err:?})" - ); - assert!( - assert_read_only_mongo_uri(&uri, &policy, &local_hosts).is_ok(), - "read-only guard must accept encoded loopback dev-port URI: {uri}" - ); - } - ("bracketed_loopback", ":27017" | "") => { - let brackets_intact = encoded.starts_with('[') && encoded.ends_with(']'); - if brackets_intact { - assert_eq!( - outcome, OUTCOME_QA, - "bracket-intact encoded [::1] QA URI must classify as Qa: {uri}" - ); - assert_eq!( - assert_read_only_mongo_uri(&uri, &policy, &local_hosts), - Err(MongoSafetyError::UnauthorizedQaUser) - ); - } else { - assert_eq!( - outcome, OUTCOME_REJECTED, - "bracket-encoded [::1] URI must be rejected: {uri}" - ); - } - } - ("bracketed_loopback", ":27018") => { - let brackets_intact = encoded.starts_with('[') && encoded.ends_with(']'); - if brackets_intact { - assert_eq!( - outcome, OUTCOME_NOT_QA, - "bracket-intact encoded [::1]:27018 must classify as NotQa: {uri}" - ); - assert!(assert_read_only_mongo_uri(&uri, &policy, &local_hosts).is_ok()); - } else { - assert_eq!( - outcome, OUTCOME_REJECTED, - "bracket-encoded [::1]:27018 must be rejected: {uri}" - ); - } - } - ("remote", _) => { - assert_eq!( - outcome, OUTCOME_NOT_QA, - "remote encoded URI must classify as NotQa: {uri} (err={err:?})" - ); - assert!(assert_read_only_mongo_uri(&uri, &policy, &local_hosts).is_ok()); - } - ("smuggled", _) => { - assert_ne!( - outcome, OUTCOME_NOT_QA, - "smuggled URI must never classify as NotQa: {uri}" - ); - } - _ => unreachable!(), - } - } - // Exact independent TypeScript env-safety.ts reference counts and 64-bit FNV-1a checksum. - assert_eq!(enc_qa, 885); - assert_eq!(enc_not_qa, 479); - assert_eq!(enc_rejected, 1636); - assert_eq!(enc_hash, 0xf88a_38ce_1b8f_844e); - - // 3. environment-safety-authority-split.test.ts: full 30,000-iteration deterministic LCG - // fuzz corpora for BOTH seeds (0x7e28 and 0x28e7), pinned against the independent - // TypeScript env-safety.ts reference. - // Every difference between Rust parse_mongo_target/is_qa_mongo_target and TS env-safety.ts - // is strictly one of three documented intentional stricter-than-TS rules (never permissive): - // (a) leading/trailing whitespace rejected without trimming (ForbiddenWhitespace) - // (b) unencoded '@' in remainder without credentials (UnencodedAtInRemainderWithoutCredentials) - // (c) malformed bracketed IPv6 hosts rejected (NoValidHosts) - let fuzz_tokens = [ - "localhost", - "127.0.0.1", - "[::1]", - ":27017", - ":27018", - "#", - "@", - "/", - "?", - ",", - "u", - "p", - ":", - "x", - "%40", - "%23", - "\\", - ";", - "[", - "]", - "%2C", - ".", - "LOCALHOST", - "\u{0000}", - "\n", - "\t", - " ", - "27017", - "%3A", - "dev_admin:dev_mongo_pass", - ]; - // Reference-generation command (run from repo root using Bun against a temp copy of - // apps/stock/config/src/env-safety.ts with `getLocalMachineHosts` stubbed to - // `["quant-host.lan", "quant-host", "quant-host.local", "10.0.0.51", "fe80::1"]` - // and `export { parseMongoTarget, isQaMongoTargetHosts };` appended): - // bun -e ' - // import { readFileSync, writeFileSync, unlinkSync } from "node:fs"; - // const src = readFileSync("./apps/stock/config/src/env-safety.ts", "utf8"); - // const tmp = "/tmp/env_safety_ref.ts"; - // writeFileSync(tmp, src.replace(/function getLocalMachineHosts\([\s\S]*?\n\}/, - // `function getLocalMachineHosts(){return new Set(["quant-host.lan","quant-host","quant-host.local","10.0.0.51","fe80::1"]);}`) - // + "\nexport { parseMongoTarget, isQaMongoTargetHosts };\n"); - // try { - // const { parseMongoTarget, isQaMongoTargetHosts } = await import(tmp); - // // Replay the exact LCG + token table above for seed 0x7e28 / 0x28e7 (30_000 iterations) - // // or seed 20261127 (3_000 iterations). Classify each URI as: - // // 1 = Qa (parseMongoTarget succeeds && hosts.length > 0 && isQaMongoTargetHosts(t)) - // // 2 = NotQa (parseMongoTarget succeeds && hosts.length > 0 && !isQaMongoTargetHosts(t)) - // // 3 = Rejected (parseMongoTarget throws or hosts.length === 0) - // // Hash the ordered outcome bytes with FNV-1a64 (offset 0xcbf29ce484222325n, prime 0x100000001b3n). - // // To print the first differing URI on a future mismatch, write `\t\t` - // // from both this script and a temporary println! in this test loop, then run `diff -u` or scan for the first line diff. - // } finally { unlinkSync(tmp); } - // ' - struct FuzzParitySpec { - seed: u32, - // Direct Rust parse_mongo_target + is_qa_mongo_target - rust_qa: usize, - rust_not_qa: usize, - rust_rejected: usize, - rust_hash: u64, - // Independent TypeScript env-safety.ts reference (all 30,000 cases) - ts_qa: usize, - ts_not_qa: usize, - ts_rejected: usize, - ts_hash: u64, - // Documented intentional stricter-than-TS difference counts - diff_total: usize, - diff_ws: usize, - diff_remainder_at: usize, - diff_invalid_bracketed_ipv6: usize, - // assert_read_only_mongo_uri (all 30,000 cases) - ro_accepted: usize, - ro_rejected: usize, - ro_hash: u64, - } - let fuzz_specs = [ - FuzzParitySpec { - seed: 0x7e28, - rust_qa: 886, - rust_not_qa: 2093, - rust_rejected: 27021, - rust_hash: 0xca8b_51fb_09b0_0a54, - ts_qa: 924, - ts_not_qa: 2201, - ts_rejected: 26875, - ts_hash: 0x3016_07f9_04a5_278a, - diff_total: 146, - diff_ws: 85, - diff_remainder_at: 54, - diff_invalid_bracketed_ipv6: 9, - ro_accepted: 1861, - ro_rejected: 28139, - ro_hash: 0x0e79_7c66_e47f_7a08, - }, - FuzzParitySpec { - seed: 0x28e7, - rust_qa: 873, - rust_not_qa: 2049, - rust_rejected: 27078, - rust_hash: 0xdfd6_7d8d_36a8_ce4e, - ts_qa: 916, - ts_not_qa: 2161, - ts_rejected: 26923, - ts_hash: 0x7067_39bb_7273_326c, - diff_total: 155, - diff_ws: 109, - diff_remainder_at: 44, - diff_invalid_bracketed_ipv6: 6, - ro_accepted: 1775, - ro_rejected: 28225, - ro_hash: 0x17fc_8004_407c_98d8, - }, - ]; - - for spec in &fuzz_specs { - let mut state = spec.seed; - let mut next = || -> f64 { - state = state.wrapping_mul(1103515245).wrapping_add(12345) & 0x7fff_ffff; - (state as f64) / (0x8000_0000u32 as f64) - }; - let mut rust_qa = 0usize; - let mut rust_not_qa = 0usize; - let mut rust_rejected = 0usize; - let mut rust_hash = FNV_OFFSET; - - let mut ts_qa = 0usize; - let mut ts_not_qa = 0usize; - let mut ts_rejected = 0usize; - let mut ts_equiv_hash = FNV_OFFSET; - - let mut diff_total = 0usize; - let mut diff_ws = 0usize; - let mut diff_remainder_at = 0usize; - let mut diff_invalid_bracketed_ipv6 = 0usize; - - let mut ro_accepted = 0usize; - let mut ro_rejected = 0usize; - let mut ro_hash = FNV_OFFSET; - - for _ in 0..30_000 { - let length = 1 + ((next() * 8.0) as usize).min(7); - let mut body = String::new(); - for _ in 0..length { - let idx = - ((next() * (fuzz_tokens.len() as f64)) as usize).min(fuzz_tokens.len() - 1); - body.push_str(fuzz_tokens[idx]); - } - let prefix = if next() < 0.85 { - "mongodb://" - } else { - "mongodb+srv://" - }; - let uri = format!("{prefix}{body}"); - - let (r, err) = classify_rust(&uri); - match r { - OUTCOME_QA => rust_qa += 1, - OUTCOME_NOT_QA => rust_not_qa += 1, - OUTCOME_REJECTED => rust_rejected += 1, - _ => unreachable!(), - } - rust_hash = fnv1a_update(rust_hash, r); - - // Fold only the three documented intentional stricter-than-TS parser rules - // back to TS's permissive behavior to prove 1-to-1 parity with the - // independent env-safety.ts reference across all 30,000 cases. - let mut candidate = uri.clone(); - let mut used_ws = false; - let mut used_at = false; - let mut used_ipv6 = false; - if matches!(err, Some(MongoSafetyError::ForbiddenWhitespace)) - && candidate != candidate.trim() - { - candidate = candidate.trim().to_owned(); - used_ws = true; - } - let (mut ts_equiv, mut cur_err) = if used_ws { - classify_rust(&candidate) - } else { - (r, err.clone()) - }; - if matches!( - cur_err, - Some(MongoSafetyError::UnencodedAtInRemainderWithoutCredentials) - ) { - if let Some((sch, rest)) = candidate.split_once("://") { - candidate = format!("{sch}://u:p@{rest}"); - used_at = true; - (ts_equiv, cur_err) = classify_rust(&candidate); - } - } - if matches!(cur_err, Some(MongoSafetyError::NoValidHosts)) { - if let Some((sch, rest)) = candidate.split_once("://") { - let split_at = rest.find(['/', '?']).unwrap_or(rest.len()); - let (auth, rem) = rest.split_at(split_at); - let (userinfo_prefix, host_list) = match auth.find('@') { - Some(idx) => (&auth[..=idx], &auth[idx + 1..]), - None => ("", auth), - }; - let mut changed = false; - let rewritten_hosts: Vec = host_list - .split(',') - .map(|seg| { - let t = seg.trim(); - if let Some(after_open) = t.strip_prefix('[') { - if let Some(close_rel) = after_open.find(']') { - let raw_host = after_open[..close_rel].trim(); - let after = after_open[close_rel + 1..].trim(); - let decoded_ok = decode_mongo_host(raw_host, true, false).is_ok(); - if close_rel > 0 - && !raw_host.is_empty() - && (after.is_empty() || after.starts_with(':')) - && decoded_ok - { - changed = true; - let lower = - raw_host.trim_end_matches('.').to_ascii_lowercase(); - let repl = if lower == "localhost" || lower == "127.0.0.1" { - "localhost" - } else { - "nonqa" - }; - return format!("{repl}{after}"); - } - } - } - seg.to_owned() - }) - .collect(); - if changed { - let rewritten = - format!("{sch}://{userinfo_prefix}{}{rem}", rewritten_hosts.join(",")); - let (rew_r, _) = classify_rust(&rewritten); - if rew_r != OUTCOME_REJECTED { - used_ipv6 = true; - ts_equiv = rew_r; - } - } - } - } - if ts_equiv != r { - assert_eq!( - r, OUTCOME_REJECTED, - "Rust may only differ from TS by failing closed (Rejected), never more permissively: {uri:?}" - ); - diff_total += 1; - if used_ws { - diff_ws += 1; - } - if used_at { - diff_remainder_at += 1; - } - if used_ipv6 { - diff_invalid_bracketed_ipv6 += 1; - } - } - match ts_equiv { - OUTCOME_QA => ts_qa += 1, - OUTCOME_NOT_QA => ts_not_qa += 1, - OUTCOME_REJECTED => ts_rejected += 1, - _ => unreachable!(), - } - ts_equiv_hash = fnv1a_update(ts_equiv_hash, ts_equiv); - - match assert_read_only_mongo_uri(&uri, &policy, &local_hosts) { - Ok(validated) => { - ro_accepted += 1; - ro_hash = fnv1a_update(ro_hash, 1); - // None of the fuzz tokens contain studio_stock_bot_read, so no accepted URI - // can ever be a QA target (neither under Rust nor under TS classification). - assert!( - !validated.is_qa_target(), - "fuzz corpus URI accepted as QA without allowlisted user: {uri:?}" - ); - assert_eq!( - ts_equiv, OUTCOME_NOT_QA, - "read-only guard must never accept a URI that TS classifies as Qa/Rejected: {uri:?}" - ); - } - Err(_) => { - ro_rejected += 1; - ro_hash = fnv1a_update(ro_hash, 2); - } - } - } - - assert_eq!(rust_qa, spec.rust_qa, "seed 0x{:x} rust_qa", spec.seed); - assert_eq!( - rust_not_qa, spec.rust_not_qa, - "seed 0x{:x} rust_not_qa", - spec.seed - ); - assert_eq!( - rust_rejected, spec.rust_rejected, - "seed 0x{:x} rust_rejected", - spec.seed - ); - assert_eq!( - rust_hash, spec.rust_hash, - "seed 0x{:x} rust_hash", - spec.seed - ); - - assert_eq!(ts_qa, spec.ts_qa, "seed 0x{:x} ts_qa", spec.seed); - assert_eq!(ts_not_qa, spec.ts_not_qa, "seed 0x{:x} ts_not_qa", spec.seed); - assert_eq!( - ts_rejected, spec.ts_rejected, - "seed 0x{:x} ts_rejected", - spec.seed - ); - assert_eq!( - ts_equiv_hash, spec.ts_hash, - "seed 0x{:x} ts_equiv_hash must match independent env-safety.ts reference", - spec.seed - ); - - assert_eq!(diff_total, spec.diff_total, "seed 0x{:x} diff_total", spec.seed); - assert_eq!(diff_ws, spec.diff_ws, "seed 0x{:x} diff_ws", spec.seed); - assert_eq!( - diff_remainder_at, spec.diff_remainder_at, - "seed 0x{:x} diff_remainder_at", - spec.seed - ); - assert_eq!( - diff_invalid_bracketed_ipv6, spec.diff_invalid_bracketed_ipv6, - "seed 0x{:x} diff_invalid_bracketed_ipv6", - spec.seed - ); - - assert_eq!( - ro_accepted, spec.ro_accepted, - "seed 0x{:x} ro_accepted", - spec.seed - ); - assert_eq!( - ro_rejected, spec.ro_rejected, - "seed 0x{:x} ro_rejected", - spec.seed - ); - assert_eq!(ro_hash, spec.ro_hash, "seed 0x{:x} ro_hash", spec.seed); - } -} - -#[test] -fn local_hosts_builders_and_detect_parse_hostnames_and_ips_offline() { - let hosts = LocalHosts::from_hostname_and_ips( - Some(" Quant-Box.Home.LAN.. "), - ["10.0.0.51", "[fe80::1%eth0]", " 192.168.10.20 "], - ) - .with_host("EXTRA.LOCAL."); - - assert!(hosts.contains("quant-box.home.lan")); - assert!(hosts.contains("quant-box")); - assert!(hosts.contains("quant-box.local")); - assert!(hosts.contains("10.0.0.51")); - assert!(hosts.contains("fe80::1")); - assert!(hosts.contains("fe80::1%eth0")); - assert!(hosts.contains("192.168.10.20")); - assert!(hosts.contains("extra.local")); - assert!(!hosts.contains("other-host")); - - let detected = LocalHosts::detect_from_sources( - Some("worker-01.corp.internal"), - Some("\n# comment-not-empty\n"), - ); - assert!(detected.contains("worker-01.corp.internal")); - assert!(detected.contains("worker-01")); - assert!(detected.contains("worker-01.local")); - - let from_etc = LocalHosts::detect_from_sources(None, Some(" studio-host.lan\n")); - assert!(from_etc.contains("studio-host.lan")); - assert!(from_etc.contains("studio-host")); - assert!(from_etc.contains("studio-host.local")); - - // Best-effort detect() must never panic in any environment. - let _ = LocalHosts::detect(); -} - -#[test] -fn numeric_ipv4_port_scheme_unix_socket_and_encoding_edge_cases() { - let local_hosts = LocalHosts::empty(); - let policy = ReadOnlyPolicy::default(); - - // Numeric IPv4 / IPv6 host edge cases on port 27017. - let host_cases: &[(&str, &str, ExpectedTargetOutcome)] = &[ - ("zero_short_ipv4", "mongodb://u:p@0:27017/stock", ExpectedTargetOutcome::Qa), - ("hex_empty_ipv4", "mongodb://u:p@0x:27017/stock", ExpectedTargetOutcome::Qa), - ("hex_short_loopback", "mongodb://u:p@0x7f.1:27017/stock", ExpectedTargetOutcome::Qa), - ("three_part_loopback", "mongodb://u:p@127.0.1:27017/stock", ExpectedTargetOutcome::Qa), - ("ipv6_unspecified", "mongodb://u:p@[::]:27017/stock", ExpectedTargetOutcome::Qa), - ( - "ipv6_ipv4_compatible_not_mapped", - "mongodb://u:p@[::127.0.0.1]:27017/stock", - ExpectedTargetOutcome::NotQa, - ), - ( - "out_of_range_octet_first", - "mongodb://u:p@256.0.0.1:27017/stock", - ExpectedTargetOutcome::NotQa, - ), - ( - "out_of_range_octet_last", - "mongodb://u:p@127.0.0.256:27017/stock", - ExpectedTargetOutcome::NotQa, - ), - ( - "out_of_range_decimal_u32", - "mongodb://u:p@4294967296:27017/stock", - ExpectedTargetOutcome::NotQa, - ), - ( - "out_of_range_hex_u32", - "mongodb://u:p@0x100000000:27017/stock", - ExpectedTargetOutcome::NotQa, - ), - ( - "out_of_range_octal_last", - "mongodb://u:p@0177.0.0.256:27017/stock", - ExpectedTargetOutcome::NotQa, - ), - ( - "out_of_range_three_part_last", - "mongodb://u:p@127.0.65536:27017/stock", - ExpectedTargetOutcome::NotQa, - ), - // Leading-zero port 27017 still resolves to QA port 27017. - ( - "leading_zero_port_27017", - "mongodb://u:p@localhost:0000027017/stock", - ExpectedTargetOutcome::Qa, - ), - // Uppercase schemes. - ( - "uppercase_mongodb_qa", - "MONGODB://studio_stock_bot_read:pw@localhost:27017/stock", - ExpectedTargetOutcome::Qa, - ), - ( - "uppercase_mongodb_srv_remote", - "MONGODB+SRV://u:p@cluster.example.com/stock", - ExpectedTargetOutcome::NotQa, - ), - ( - "uppercase_mongodb_srv_qa", - "MONGODB+SRV://u:p@localhost/stock", - ExpectedTargetOutcome::Qa, - ), - // Unix domain socket hosts are never classified as QA (same as TS). - ( - "unix_socket_tmp_27017_with_creds", - "mongodb://u:p@%2Ftmp%2Fmongodb-27017.sock/stock", - ExpectedTargetOutcome::NotQa, - ), - ( - "unix_socket_var_run_no_creds", - "mongodb://%2Fvar%2Frun%2Fmongodb-27017.sock/stock", - ExpectedTargetOutcome::NotQa, - ), - ]; - - for &(label, uri, expected) in host_cases { - let target = parse_mongo_target(uri) - .unwrap_or_else(|e| panic!("{label}: expected parse Ok for {uri}, got {e:?}")); - let is_qa = is_qa_mongo_target(&target, &local_hosts); - match expected { - ExpectedTargetOutcome::Qa => assert!(is_qa, "{label}: expected QA for {uri}"), - ExpectedTargetOutcome::NotQa => assert!(!is_qa, "{label}: expected NotQa for {uri}"), - ExpectedTargetOutcome::Rejected => unreachable!(), - } - } - - // Uppercase MONGODB:// with allowlisted QA user is accepted; unauthorized user is rejected. - let ok_upper = assert_read_only_mongo_uri( - "MONGODB://studio_stock_bot_read:pw@localhost:27017/stock", - &policy, - &local_hosts, - ) - .expect("uppercase MONGODB:// with allowlisted user must pass"); - assert!(ok_upper.is_qa_target()); - assert_eq!( - assert_read_only_mongo_uri("MONGODB://u:p@localhost:27017/stock", &policy, &local_hosts), - Err(MongoSafetyError::UnauthorizedQaUser) - ); - assert!( - assert_read_only_mongo_uri( - "MONGODB+SRV://u:p@cluster.example.com/stock", - &policy, - &local_hosts, - ) - .is_ok() - ); - assert!( - assert_read_only_mongo_uri( - "mongodb://u:p@%2Ftmp%2Fmongodb-27017.sock/stock", - &policy, - &local_hosts, - ) - .is_ok() - ); - - // Exact MongoSafetyError variants for rejected port, scheme, socket, and encoding edge cases. - let rejection_cases: &[(&str, &str, MongoSafetyError)] = &[ - ( - "port_zero", - "mongodb://u:p@localhost:0/stock", - MongoSafetyError::NoValidHosts, - ), - ( - "port_65536", - "mongodb://u:p@localhost:65536/stock", - MongoSafetyError::NoValidHosts, - ), - ( - "port_plus_27017", - "mongodb://u:p@localhost:+27017/stock", - MongoSafetyError::NoValidHosts, - ), - ( - "unix_socket_on_srv_rejected", - "mongodb+srv://u:p@%2Ftmp%2Fmongodb-27017.sock/stock", - MongoSafetyError::ForbiddenHostCharacters, - ), - ( - "encoded_u2028_line_separator_in_host", - "mongodb://u:p@localhost%e2%80%a8:27017/stock", - MongoSafetyError::ForbiddenHostCharacters, - ), - ( - "invalid_utf8_percent_ff_in_host", - "mongodb://u:p@local%ffhost:27017/stock", - MongoSafetyError::InvalidHostEncoding, - ), - ( - "invalid_utf8_percent_ff_in_username", - "mongodb://u%ff:p@localhost:27018/stock", - MongoSafetyError::InvalidUsernameEncoding, - ), - ( - "invalid_utf8_percent_ff_username_remote", - "mongodb://%ff:p@mongo.internal:27017/stock", - MongoSafetyError::InvalidUsernameEncoding, - ), - ]; - - for &(label, uri, ref expected_err) in rejection_cases { - assert_eq!( - parse_mongo_target(uri), - Err(expected_err.clone()), - "{label}: parse_mongo_target mismatch for {uri}" - ); - assert_eq!( - assert_read_only_mongo_uri(uri, &policy, &local_hosts), - Err(expected_err.clone()), - "{label}: assert_read_only_mongo_uri mismatch for {uri}" - ); - } -} - -#[test] -fn conservative_local_host_matching_flags_leading_zero_lan_and_zoned_link_local() { - let local_hosts = LocalHosts::from_hostname_and_ips( - Some("quant.lan.local."), - ["192.168.1.50", "fe80::1234:5678%eth0"], - ); - let policy = ReadOnlyPolicy::default(); - - // Rust is intentionally stricter than TS here: leading-zero decimal LAN IPs and - // the machine's own zoned link-local IPv6 on port 27017 (or omitted port) are QA. - let qa_uris = [ - "mongodb://u:p@quant.lan.local:27017/stock", - "mongodb://u:p@QUANT.LAN.LOCAL.:27017/stock", - "mongodb://u:p@quant:27017/stock", - "mongodb://u:p@quant.local:27017/stock", - "mongodb://u:p@192.168.1.50:27017/stock", - "mongodb://u:p@192.168.001.050:27017/stock", - "mongodb://u:p@192.168.001.050/stock", - "mongodb://u:p@0xc0a80132:27017/stock", - "mongodb://u:p@0300.0250.0001.0062:27017/stock", - "mongodb://u:p@[fe80::1234:5678%25eth0]:27017/stock", - "mongodb://u:p@[fe80::1234:5678%25en0]:27017/stock", - "mongodb://u:p@[fe80::1234:5678]:27017/stock", - "mongodb://u:p@[FE80::1234:5678%25ETH0]/stock", - ]; - for uri in qa_uris { - let target = parse_mongo_target(uri).expect("expected valid local host URI"); - assert!( - is_qa_mongo_target(&target, &local_hosts), - "expected QA classification for local host URI: {uri}" - ); - assert_eq!( - assert_read_only_mongo_uri(uri, &policy, &local_hosts), - Err(MongoSafetyError::UnauthorizedQaUser), - "expected UnauthorizedQaUser for {uri}" - ); - } - - let non_qa_uris = [ - "mongodb://u:p@192.168.001.050:27018/stock", - "mongodb://u:p@[fe80::1234:5678%25eth0]:27018/stock", - "mongodb://u:p@192.168.001.051:27017/stock", - "mongodb://u:p@[fe80::1234:5679%25eth0]:27017/stock", - "mongodb://u:p@other.lan.local:27017/stock", - ]; - for uri in non_qa_uris { - let target = parse_mongo_target(uri).expect("expected valid non-QA URI"); - assert!( - !is_qa_mongo_target(&target, &local_hosts), - "expected NotQa for {uri}" - ); - assert!( - assert_read_only_mongo_uri(uri, &policy, &local_hosts).is_ok(), - "expected read-only acceptance for non-QA {uri}" - ); - } -} - -#[test] -fn exact_allowlist_after_decoding_and_srv_rules() { - let local_hosts = LocalHosts::empty(); - let policy = ReadOnlyPolicy::default(); - - // Exact match after percent-decoding succeeds. - for ok_uri in [ - "mongodb://studio_stock_bot_read:pw@localhost:27017/stock", - "mongodb://studio%5fstock%5fbot%5fread:pw@localhost:27017/stock", - "mongodb://studio%5Fstock%5Fbot%5Fread:pw@127.0.0.1:27017/stock", - ] { - let validated = assert_read_only_mongo_uri(ok_uri, &policy, &local_hosts) - .unwrap_or_else(|e| panic!("expected exact allowlist match for {ok_uri}, got {e:?}")); - assert!(validated.is_qa_target()); - assert_eq!( - validated.target().username.as_deref(), - Some(DEFAULT_ALLOWED_READ_USER) - ); - } - - // No case-folding, prefix, suffix, or '+'-to-space substitution for allowlist match. - for rejected_user in [ - "STUDIO_STOCK_BOT_READ", - "Studio_Stock_Bot_Read", - "studio_stock_bot_read_extra", - "studio_stock_bot_rea", - "pre_studio_stock_bot_read", - "studio+stock+bot+read", - ] { - let uri = format!("mongodb://{rejected_user}:pw@localhost:27017/stock"); - assert_eq!( - assert_read_only_mongo_uri(&uri, &policy, &local_hosts), - Err(MongoSafetyError::UnauthorizedQaUser), - "expected exact allowlist rejection for {uri}" - ); - } - - // mongodb+srv:// single-host and no-explicit-port rules. - let srv_remote = assert_read_only_mongo_uri( - "mongodb+srv://reader:pw@cluster.example.com/stock", - &policy, - &local_hosts, - ) - .expect("single remote SRV host without port must pass"); - assert!(!srv_remote.is_qa_target()); - - let srv_qa = assert_read_only_mongo_uri( - "mongodb+srv://studio_stock_bot_read:pw@localhost/stock", - &policy, - &local_hosts, - ) - .expect("single QA SRV host with allowlisted user must pass"); - assert!(srv_qa.is_qa_target()); - - assert_eq!( - assert_read_only_mongo_uri("mongodb+srv://localhost/stock", &policy, &local_hosts), - Err(MongoSafetyError::MissingCredentialsForQaTarget) - ); - assert_eq!( - assert_read_only_mongo_uri( - "mongodb+srv://u:p@a.example.com,b.example.com/stock", - &policy, - &local_hosts, - ), - Err(MongoSafetyError::InvalidSrvTarget) - ); - assert_eq!( - assert_read_only_mongo_uri( - "mongodb+srv://u:p@a.example.com:27017/stock", - &policy, - &local_hosts, - ), - Err(MongoSafetyError::InvalidSrvTarget) - ); - assert_eq!( - assert_read_only_mongo_uri( - "mongodb+srv://u:p@a.example.com:/stock", - &policy, - &local_hosts, - ), - Err(MongoSafetyError::InvalidSrvTarget) - ); -} - -#[test] -fn password_redaction_covers_odd_passwords_and_boxed_dyn_error() { - let local_hosts = LocalHosts::empty(); - let policy = ReadOnlyPolicy::default(); - - let odd_passwords = [ - ("with_colons", "part1:part2:part3"), - ("percent_encoded_at_and_pct", "p%40ss%25word%3A99"), - ("unicode_secret", "pässwörd🔒secret"), - ("empty_password", ""), - ]; - - for (label, pw) in odd_passwords { - let uri = format!("mongodb://studio_stock_bot_read:{pw}@localhost:27017/stock"); - let validated = assert_read_only_mongo_uri(&uri, &policy, &local_hosts) - .unwrap_or_else(|e| panic!("{label}: expected valid URI, got {e:?}")); - - let display = format!("{validated}"); - let debug = format!("{validated:?}"); - let redacted = validated.redacted(); - - assert_eq!( - redacted, - "mongodb://studio_stock_bot_read:[REDACTED]@localhost:27017/stock", - "{label}: unexpected redacted form" - ); - assert_eq!(display, redacted, "{label}: Display must match redacted()"); - assert!(debug.contains("[REDACTED]"), "{label}: Debug must contain [REDACTED]"); - if !pw.is_empty() { - assert!(!display.contains(pw), "{label}: Display leaked password"); - assert!(!debug.contains(pw), "{label}: Debug leaked password"); - assert!(!redacted.contains(pw), "{label}: redacted() leaked password"); - } - - // Verify password never leaks through Box on error paths. - let error_uris = [ - ( - format!("mongodb://trading_admin:{pw}@mongo.internal:27017/stock"), - MongoSafetyError::ForbiddenAdminUser, - ), - ( - format!("mongodb://other_user:{pw}@localhost:27017/stock"), - MongoSafetyError::UnauthorizedQaUser, - ), - ( - format!("mongodb://u:{pw}@localhost:27017#frag/stock"), - MongoSafetyError::UnencodedHashInAuthority, - ), - ( - format!("mongodb://u:{pw}@local%ffhost:27017/stock"), - MongoSafetyError::InvalidHostEncoding, - ), - ( - format!("mongodb://u:{pw}@/stock"), - MongoSafetyError::EmptyHostList, - ), - ]; - for (bad_uri, expected_err) in error_uris { - let err = assert_read_only_mongo_uri(&bad_uri, &policy, &local_hosts) - .expect_err("expected error for malformed/unauthorized URI"); - assert_eq!(err, expected_err, "{label}: unexpected error variant"); - let boxed: Box = Box::new(err); - let boxed_display = format!("{boxed}"); - let boxed_debug = format!("{boxed:?}"); - if !pw.is_empty() { - assert!( - !boxed_display.contains(pw), - "{label}: Box Display leaked password: {boxed_display}" - ); - assert!( - !boxed_debug.contains(pw), - "{label}: Box Debug leaked password: {boxed_debug}" - ); - } - } - } -} - -#[test] -fn adversarial_seeded_fuzz_40k_enforces_invariants() { - let local_hosts = LocalHosts::from_hostname_and_ips( - Some("quant.lan.local."), - ["192.168.1.50", "fe80::1234:5678%eth0"], - ); - let policy = ReadOnlyPolicy::default(); - - let schemes = ["mongodb://", "mongodb+srv://", "MONGODB://", "http://"]; - let userinfos = [ - "", - "studio_stock_bot_read:pw@", - "studio%5fstock%5fbot%5fread:pw@", - "trading_admin:pw@", - "TrAdInG%5fAdMiN:pw@", - "other_user:pw@", - "bad%ff:pw@", - "@", - ]; - let hosts = [ - "localhost", - "LOCALHOST.", - "%6cocalhost", - "127.0.0.1", - "127.1", - "2130706433", - "0x7f000001", - "0177.0.0.1", - "0127.0.0.1", - "[::1]", - "[::ffff:127.0.0.1]", - "quant.lan.local.", - "192.168.1.50", - "192.168.001.050", - "[fe80::1234:5678%25eth0]", - "mongo.internal", - "[fe80::g]", - "%2Ftmp%2Fmongodb-27017.sock", - "local%ffhost", - "localhost%e2%80%a8", - ]; - let ports = ["", ":27017", ":27018", ":0", ":65536", ":027017"]; - let tails = [ - "/stock", - "/stock_dev?replicaSet=rs0", - "/stock?user=a@b", - "#frag/stock", - "", - ]; - let prefixes = ["", " ", "\t"]; - - let mut state: u32 = 0x51a7e; - let mut next_idx = |len: usize| -> usize { - state = state.wrapping_mul(1103515245).wrapping_add(12345) & 0x7fff_ffff; - (state as usize) % len - }; - - let mut parsed_qa = 0usize; - let mut parsed_not_qa = 0usize; - let mut parsed_rejected = 0usize; - let mut accepted_total = 0usize; - let mut accepted_qa = 0usize; - let mut accepted_non_qa = 0usize; - - for _ in 0..40_000 { - let prefix = if next_idx(12) == 0 { - prefixes[next_idx(prefixes.len())] - } else { - "" - }; - let scheme = schemes[next_idx(schemes.len())]; - let userinfo = userinfos[next_idx(userinfos.len())]; - let h1 = hosts[next_idx(hosts.len())]; - let p1 = ports[next_idx(ports.len())]; - let seed_list = if next_idx(4) == 0 { - let h2 = hosts[next_idx(hosts.len())]; - let p2 = ports[next_idx(ports.len())]; - format!("{h1}{p1},{h2}{p2}") - } else { - format!("{h1}{p1}") - }; - let tail = tails[next_idx(tails.len())]; - let uri = format!("{prefix}{scheme}{userinfo}{seed_list}{tail}"); - - match parse_mongo_target(&uri) { - Ok(target) => { - if is_qa_mongo_target(&target, &local_hosts) { - parsed_qa += 1; - } else { - parsed_not_qa += 1; - } - } - Err(_) => parsed_rejected += 1, - } - - if let Ok(validated) = assert_read_only_mongo_uri(&uri, &policy, &local_hosts) { - accepted_total += 1; - if let Some(user) = validated.target().username.as_deref() { - assert!( - !user.eq_ignore_ascii_case(FORBIDDEN_ADMIN_USER), - "fuzz accepted forbidden admin user: {uri:?}" - ); - } - if validated.is_qa_target() { - accepted_qa += 1; - let user = validated - .target() - .username - .as_deref() - .expect("accepted QA token must carry a username"); - assert!( - policy.allowed_read_users.iter().any(|allowed| allowed == user), - "fuzz accepted QA token with non-allowlisted user {user:?}: {uri:?}" - ); - } else { - accepted_non_qa += 1; - } - } - } - - assert_eq!(parsed_qa + parsed_not_qa + parsed_rejected, 40_000); - assert_eq!(accepted_qa + accepted_non_qa, accepted_total); - // Pinned Rust counts for seed 0x51a7e (40,000 adversarial URIs). - // Independent Bun cross-check against apps/stock/config/src/env-safety.ts on the same - // 40,000 URIs produced tsQa = 10_125, tsNotQa = 7_349, tsRejected = 22_526; Rust is - // strictly more conservative (more QA flags via leading-zero LAN / zoned link-local, - // more rejections via bad %ff usernames, leading whitespace, remainder '@', [fe80::g]). - assert_eq!(parsed_qa, 10_439); - assert_eq!(parsed_not_qa, 5_437); - assert_eq!(parsed_rejected, 24_124); - assert_eq!(accepted_total, 3_393); - assert_eq!(accepted_qa, 2_518); - assert_eq!(accepted_non_qa, 875); -} diff --git a/tools/curate-etl/src/mongo_stream.rs b/tools/curate-etl/src/mongo_stream.rs deleted file mode 100644 index 35564c58..00000000 --- a/tools/curate-etl/src/mongo_stream.rs +++ /dev/null @@ -1,1237 +0,0 @@ -//! Sealed read-only MongoDB raw-BSON cursor adapter (`M1.2al`). -//! -//! Provides the closed [`SourceCollection`] allowlist, typed [`MongoReadSpec`] -//! filter validation/builder, driver-independent [`RawDocumentSource`] trait, -//! bounded-memory [`RawBsonCursorReader`] implementing [`std::io::Read`] for -//! the existing zero-copy [`crate::bson_stream`] decoders, password-redacted -//! [`MongoStreamError`] sanitization reusing [`crate::mongo_safety`], and the -//! sealed [`ReadOnlyMongoClient`] / [`MongoRawDocumentSource`] driver adapter -//! backed by `mongodb::sync`. -//! -//! # Safety & Sealing Guarantees -//! - Closed [`SourceCollection`] allowlist matching the 8 M1 collections in -//! `apps/stock/data-pipeline/src/security-master/export-raw-bson.ts`. No API -//! accepts a free-form collection name string. -//! - Sealed read-only driver surface: [`ReadOnlyMongoClient`] requires a -//! [`ValidatedReadOnlyMongoUri`] proof token and exposes strictly -//! [`ReadOnlyMongoClient::open_raw_cursor`] (`find` returning raw BSON bytes). -//! No `mongodb::sync::Client`, `Database`, `Collection`, write, index, admin, -//! or aggregation handle is ever exposed outside this module. -//! - Password redaction: [`MongoStreamError`] never stores raw URIs or -//! passwords; every driver error is sanitized at the boundary via -//! [`MongoStreamError::redacted_source`]. - -use std::error::Error; -use std::fmt; -use std::io; - -use bson::raw::RawDocumentBuf; -use bson::{Bson, DateTime, Document}; - -use crate::bson_eod_prices::{parse_ymd_strict_days, MILLIS_PER_DAY}; -use crate::bson_stream::{DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES}; -use crate::events::parse_filing_timefiled; -use crate::mongo_safety::{ - assert_read_only_mongo_uri, redact_mongo_uri_password, LocalHosts, ReadOnlyPolicy, - ValidatedReadOnlyMongoUri, -}; - -/// Default environment variable name holding the read-only MongoDB connection URI. -pub const DEFAULT_MONGO_URI_ENV: &str = "MONGODB_READ_URI"; - -/// Default MongoDB cursor batch size (matches `DEFAULT_RAW_BSON_BATCH_SIZE`). -pub const DEFAULT_MONGO_BATCH_SIZE: u32 = 4_096; - -/// Maximum permitted MongoDB cursor batch size (matches `MAX_RAW_BSON_BATCH_SIZE`). -pub const MAX_MONGO_BATCH_SIZE: u32 = 100_000; - -/// Closed allowlist of the 8 M1 MongoDB source collections consumed by `curate-etl`. -/// -/// Order and names match `RAW_BSON_EXPORT_COLLECTIONS` in -/// `apps/stock/data-pipeline/src/security-master/export-raw-bson.ts`. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub enum SourceCollection { - EodPrices, - QmSplits, - QmDividends, - QmPrices, - TeMarketData, - CeoShorts, - QmFilings, - QmEarnings, -} - -impl SourceCollection { - /// All 8 allowlisted M1 source collections in canonical order. - pub const ALL: [SourceCollection; 8] = [ - Self::EodPrices, - Self::QmSplits, - Self::QmDividends, - Self::QmPrices, - Self::TeMarketData, - Self::CeoShorts, - Self::QmFilings, - Self::QmEarnings, - ]; - - /// Exact MongoDB collection name. - pub const fn as_str(self) -> &'static str { - match self { - Self::EodPrices => "eodPrices", - Self::QmSplits => "qmSplits", - Self::QmDividends => "qmDividends", - Self::QmPrices => "qmPrices", - Self::TeMarketData => "teMarketData", - Self::CeoShorts => "ceoShorts", - Self::QmFilings => "qmFilings", - Self::QmEarnings => "qmEarnings", - } - } - - /// Primary provider key field used for exact equality filters (`key_eq`). - pub const fn key_field(self) -> &'static str { - match self { - Self::EodPrices => "eodSearchCode", - Self::QmSplits => "qmSearchCode", - Self::QmDividends => "qmSearchCode", - Self::QmPrices => "qmSearchCode", - Self::TeMarketData => "teSymbol", - Self::CeoShorts => "symbol", - Self::QmFilings => "symbol", - Self::QmEarnings => "qmSearchCode", - } - } - - /// Date/timestamp field used for range filters (`date_range`), or `None` - /// for document-per-symbol collections (`teMarketData`). - pub const fn date_field(self) -> Option<&'static str> { - match self { - Self::EodPrices => Some("date"), - Self::QmSplits => Some("date"), - Self::QmDividends => Some("date"), - Self::QmPrices => Some("date"), - Self::TeMarketData => None, - Self::CeoShorts => Some("timestamp"), - Self::QmFilings => Some("timefiled"), - Self::QmEarnings => Some("reportDate"), - } - } - - /// Returns `true` when the collection's [`Self::date_field`] is stored as a - /// BSON `DateTime` rather than a `YYYY-MM-DD` / ISO UTF-8 string. - /// - /// Verified empirically against live QA MongoDB (`m1-source-field-shapes.md`): - /// `qmEarnings.reportDate` (100% BSON `DateTime`) and `ceoShorts.timestamp` - /// (BSON `DateTime`), while `eodPrices.date`, `qmPrices.date`, `qmSplits.date`, - /// `qmDividends.date`, and `qmFilings.timefiled` are UTF-8 strings. - pub const fn date_field_is_bson_datetime(self) -> bool { - matches!(self, Self::QmEarnings | Self::CeoShorts) - } -} - -impl fmt::Display for SourceCollection { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str(self.as_str()) - } -} - -/// Typed date bound value for [`MongoDateRange`]. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum FilterDateValue { - /// Lexicographically ordered ISO-8601 date/timestamp string (e.g. `"2024-01-01"`). - IsoString(String), - /// BSON UTC `DateTime` expressed as milliseconds since the Unix epoch. - BsonDateTimeMillis(i64), -} - -impl FilterDateValue { - fn to_bson(&self) -> Bson { - match self { - Self::IsoString(s) => Bson::String(s.clone()), - Self::BsonDateTimeMillis(ms) => Bson::DateTime(DateTime::from_millis(*ms)), - } - } -} - -/// Half-open `[gte, lt)` date filter for a [`SourceCollection`] with a date field. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct MongoDateRange { - pub gte: Option, - pub lt: Option, -} - -/// Typed read specification for a read-only MongoDB cursor query. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct MongoReadSpec { - /// Optional exact match on [`SourceCollection::key_field`]. - pub key_eq: Option, - /// Optional `[gte, lt)` range on [`SourceCollection::date_field`]. - pub date_range: Option, - /// MongoDB cursor `batchSize` (in `1..=MAX_MONGO_BATCH_SIZE`). - pub batch_size: u32, - /// Optional maximum number of documents to return (in `1..=i64::MAX`). - pub limit: Option, - /// Maximum allowed single raw BSON document length in bytes (`>= MIN_BSON_DOC_BYTES`). - pub max_doc_bytes: usize, -} - -impl Default for MongoReadSpec { - fn default() -> Self { - Self { - key_eq: None, - date_range: None, - batch_size: DEFAULT_MONGO_BATCH_SIZE, - limit: None, - max_doc_bytes: DEFAULT_MAX_DOC_BYTES, - } - } -} - -impl MongoReadSpec { - /// Validates all read specification invariants for `collection`. - pub fn validate(&self, collection: SourceCollection) -> Result<(), MongoStreamError> { - if self.batch_size == 0 || self.batch_size > MAX_MONGO_BATCH_SIZE { - return Err(MongoStreamError::InvalidBatchSize { - batch_size: self.batch_size, - max_batch_size: MAX_MONGO_BATCH_SIZE, - }); - } - if let Some(limit) = self.limit { - if limit == 0 || limit > i64::MAX as u64 { - return Err(MongoStreamError::InvalidLimit { limit }); - } - } - if self.max_doc_bytes < MIN_BSON_DOC_BYTES { - return Err(MongoStreamError::InvalidMaxDocBytes { - max_doc_bytes: self.max_doc_bytes, - min_doc_bytes: MIN_BSON_DOC_BYTES, - }); - } - if let Some(key) = &self.key_eq { - if key.trim().is_empty() { - return Err(MongoStreamError::InvalidKeyFilter { collection }); - } - } - if let Some(range) = &self.date_range { - if collection.date_field().is_none() { - return Err(MongoStreamError::DateRangeNotSupported { collection }); - } - if range.gte.is_none() && range.lt.is_none() { - return Err(MongoStreamError::InvalidDateRange { - collection, - detail: "at least one of gte or lt must be set".to_owned(), - }); - } - if let Some(FilterDateValue::IsoString(s)) = &range.gte { - if s.trim().is_empty() { - return Err(MongoStreamError::InvalidDateRange { - collection, - detail: "gte ISO string must not be empty or blank".to_owned(), - }); - } - } - if let Some(FilterDateValue::IsoString(s)) = &range.lt { - if s.trim().is_empty() { - return Err(MongoStreamError::InvalidDateRange { - collection, - detail: "lt ISO string must not be empty or blank".to_owned(), - }); - } - } - if collection == SourceCollection::QmFilings { - let validate_et_calendar_day = - |bound: Option<&FilterDateValue>, label: &str| match bound { - Some(FilterDateValue::IsoString(s)) => { - let is_calendar_day = s.len() == 10 - && s.is_ascii() - && parse_filing_timefiled(&format!("{s}T00:00:00 EST")).is_ok(); - if !is_calendar_day { - return Err(MongoStreamError::InvalidDateRange { - collection, - detail: format!( - "qmFilings.timefiled {label} must be an Eastern \ - calendar-day boundary (YYYY-MM-DD); intra-day local \ - timestamps are not monotonic across the fall-back DST \ - transition and UTC strings do not match stored Eastern \ - Time strings" - ), - }); - } - Ok(()) - } - Some(FilterDateValue::BsonDateTimeMillis(_)) => { - Err(MongoStreamError::InvalidDateRange { - collection, - detail: "qmFilings.timefiled is stored as an Eastern Time string; \ - only Eastern calendar-day boundaries (YYYY-MM-DD) are \ - supported for server-side ranges" - .to_owned(), - }) - } - None => Ok(()), - }; - validate_et_calendar_day(range.gte.as_ref(), "gte")?; - validate_et_calendar_day(range.lt.as_ref(), "lt")?; - } - if let (Some(gte), Some(lt)) = (&range.gte, &range.lt) { - match (gte, lt) { - (FilterDateValue::IsoString(a), FilterDateValue::IsoString(b)) => { - if a >= b { - return Err(MongoStreamError::InvalidDateRange { - collection, - detail: format!("gte ({a:?}) must be strictly less than lt ({b:?})"), - }); - } - } - ( - FilterDateValue::BsonDateTimeMillis(a), - FilterDateValue::BsonDateTimeMillis(b), - ) => { - if a >= b { - return Err(MongoStreamError::InvalidDateRange { - collection, - detail: format!("gte ({a}) must be strictly less than lt ({b})"), - }); - } - } - _ => { - return Err(MongoStreamError::InvalidDateRange { - collection, - detail: "gte and lt must use the same FilterDateValue variant" - .to_owned(), - }); - } - } - } - } - Ok(()) - } -} - -/// Validates `spec` and constructs the corresponding MongoDB `find` filter [`Document`]. -pub fn build_filter_document( - collection: SourceCollection, - spec: &MongoReadSpec, -) -> Result { - spec.validate(collection)?; - - let mut entries: Vec<(String, Bson)> = Vec::with_capacity(2); - if let Some(key) = &spec.key_eq { - entries.push((collection.key_field().to_owned(), Bson::String(key.clone()))); - } - if let Some(range) = &spec.date_range { - if let Some(date_field) = collection.date_field() { - let mut range_entries: Vec<(String, Bson)> = Vec::with_capacity(2); - if let Some(gte) = &range.gte { - range_entries.push(("$gte".to_owned(), gte.to_bson())); - } - if let Some(lt) = &range.lt { - range_entries.push(("$lt".to_owned(), lt.to_bson())); - } - entries.push(( - date_field.to_owned(), - Bson::Document(Document::from_iter(range_entries)), - )); - } - } - - Ok(Document::from_iter(entries)) -} - -/// Redacted error type for MongoDB raw-BSON cursor streaming. -/// -/// Intentionally never stores raw URIs or passwords. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum MongoStreamError { - InvalidBatchSize { - batch_size: u32, - max_batch_size: u32, - }, - InvalidLimit { - limit: u64, - }, - InvalidMaxDocBytes { - max_doc_bytes: usize, - min_doc_bytes: usize, - }, - InvalidKeyFilter { - collection: SourceCollection, - }, - DateRangeNotSupported { - collection: SourceCollection, - }, - InvalidDateRange { - collection: SourceCollection, - detail: String, - }, - InvalidBsonFrame { - doc_index: u64, - detail: String, - }, - Source { - detail: String, - }, -} - -impl MongoStreamError { - /// Constructs a [`MongoStreamError::Source`] after stripping any raw URI, - /// raw password, percent-decoded password, or embedded MongoDB userinfo - /// password from `raw_message`. - pub fn redacted_source(raw_message: &str, uri: &ValidatedReadOnlyMongoUri) -> Self { - Self::Source { - detail: sanitize_driver_error_message(raw_message, uri), - } - } -} - -impl fmt::Display for MongoStreamError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::InvalidBatchSize { - batch_size, - max_batch_size, - } => write!( - f, - "invalid MongoDB batch_size {batch_size}: must be in 1..={max_batch_size}" - ), - Self::InvalidLimit { limit } => write!( - f, - "invalid MongoDB limit {limit}: must be in 1..={}", - i64::MAX - ), - Self::InvalidMaxDocBytes { - max_doc_bytes, - min_doc_bytes, - } => write!( - f, - "invalid max_doc_bytes {max_doc_bytes}: must be >= {min_doc_bytes}" - ), - Self::InvalidKeyFilter { collection } => write!( - f, - "invalid key_eq filter for collection {collection}: must not be empty or blank" - ), - Self::DateRangeNotSupported { collection } => write!( - f, - "date_range filter is not supported for collection {collection}" - ), - Self::InvalidDateRange { collection, detail } => { - write!(f, "invalid date_range for collection {collection}: {detail}") - } - Self::InvalidBsonFrame { doc_index, detail } => { - write!(f, "invalid raw BSON frame at doc #{doc_index}: {detail}") - } - Self::Source { detail } => write!(f, "raw BSON source error: {detail}"), - } - } -} - -impl Error for MongoStreamError {} - -/// Driver-independent seam yielding one raw length-prefixed BSON document at a time. -pub trait RawDocumentSource { - /// Advances to the next raw BSON document and returns its byte slice, - /// or `Ok(None)` when the source is exhausted. - fn next_raw_document(&mut self) -> Result, MongoStreamError>; -} - -/// Zero-copy in-memory [`RawDocumentSource`] over a slice of borrowed raw BSON frames. -#[derive(Debug, Clone)] -pub struct SliceRawDocumentSource<'a> { - docs: &'a [&'a [u8]], - index: usize, -} - -impl<'a> SliceRawDocumentSource<'a> { - pub fn new(docs: &'a [&'a [u8]]) -> Self { - Self { docs, index: 0 } - } -} - -impl<'a> RawDocumentSource for SliceRawDocumentSource<'a> { - #[inline] - fn next_raw_document(&mut self) -> Result, MongoStreamError> { - let Some(&doc) = self.docs.get(self.index) else { - return Ok(None); - }; - self.index += 1; - Ok(Some(doc)) - } -} - -/// Owned in-memory [`RawDocumentSource`] over a `Vec>` of raw BSON frames. -#[derive(Debug, Clone)] -pub struct VecRawDocumentSource { - docs: Vec>, - index: usize, -} - -impl VecRawDocumentSource { - pub fn new(docs: Vec>) -> Self { - Self { docs, index: 0 } - } -} - -impl RawDocumentSource for VecRawDocumentSource { - #[inline] - fn next_raw_document(&mut self) -> Result, MongoStreamError> { - if self.index >= self.docs.len() { - return Ok(None); - } - let doc = self.docs[self.index].as_slice(); - self.index += 1; - Ok(Some(doc)) - } -} - -fn validate_raw_bson_frame( - doc: &[u8], - doc_index: u64, - max_doc_bytes: usize, -) -> Result<(), MongoStreamError> { - if doc.len() < MIN_BSON_DOC_BYTES { - return Err(MongoStreamError::InvalidBsonFrame { - doc_index, - detail: format!( - "frame length {} is below minimum BSON document size ({MIN_BSON_DOC_BYTES})", - doc.len() - ), - }); - } - if doc.len() > max_doc_bytes { - return Err(MongoStreamError::InvalidBsonFrame { - doc_index, - detail: format!( - "frame length {} exceeds max_doc_bytes ({max_doc_bytes})", - doc.len() - ), - }); - } - let declared_len = i32::from_le_bytes([doc[0], doc[1], doc[2], doc[3]]); - if declared_len < MIN_BSON_DOC_BYTES as i32 || (declared_len as usize) != doc.len() { - return Err(MongoStreamError::InvalidBsonFrame { - doc_index, - detail: format!( - "4-byte LE length prefix ({declared_len}) disagrees with byte length ({})", - doc.len() - ), - }); - } - let last_byte = doc[doc.len() - 1]; - if last_byte != 0x00 { - return Err(MongoStreamError::InvalidBsonFrame { - doc_index, - detail: format!("missing trailing 0x00 terminator (got 0x{last_byte:02x})"), - }); - } - Ok(()) -} - -/// Bounded-memory [`io::Read`] adapter that turns any [`RawDocumentSource`] -/// into a concatenated raw BSON byte stream for [`crate::bson_stream::RawBsonChunkReader`] -/// and `decode_*_stream`. -/// -/// Copies documents directly into the caller's buffer whenever they fit, -/// spilling only the unread tail of a single current document into a reused -/// `pending` buffer when the caller's buffer is smaller. -pub struct RawBsonCursorReader { - source: S, - max_doc_bytes: usize, - pending: Vec, - pending_pos: usize, - docs_read: u64, - bytes_read: u64, - eof: bool, - stashed_error: Option, - sticky_error: Option, -} - -impl RawBsonCursorReader { - /// Wraps `source` with the default maximum BSON document size ([`DEFAULT_MAX_DOC_BYTES`]). - pub fn new(source: S) -> Self { - Self { - source, - max_doc_bytes: DEFAULT_MAX_DOC_BYTES, - pending: Vec::new(), - pending_pos: 0, - docs_read: 0, - bytes_read: 0, - eof: false, - stashed_error: None, - sticky_error: None, - } - } - - /// Wraps `source` with an explicit `max_doc_bytes` ceiling (`>= MIN_BSON_DOC_BYTES`). - pub fn with_max_doc_bytes(source: S, max_doc_bytes: usize) -> Result { - if max_doc_bytes < MIN_BSON_DOC_BYTES { - return Err(MongoStreamError::InvalidMaxDocBytes { - max_doc_bytes, - min_doc_bytes: MIN_BSON_DOC_BYTES, - }); - } - Ok(Self { - source, - max_doc_bytes, - pending: Vec::new(), - pending_pos: 0, - docs_read: 0, - bytes_read: 0, - eof: false, - stashed_error: None, - sticky_error: None, - }) - } - - /// Number of valid raw BSON documents accepted from the underlying source. - #[inline] - pub fn docs_read(&self) -> u64 { - self.docs_read - } - - /// Total bytes across all valid raw BSON documents accepted from the underlying source. - #[inline] - pub fn bytes_read(&self) -> u64 { - self.bytes_read - } - - /// Current allocated capacity of the single-document tail spill buffer. - #[inline] - pub fn pending_capacity(&self) -> usize { - self.pending.capacity() - } - - /// Consumes the adapter and returns the underlying source. - pub fn into_inner(self) -> S { - self.source - } -} - -impl io::Read for RawBsonCursorReader { - fn read(&mut self, buf: &mut [u8]) -> io::Result { - if buf.is_empty() { - return Ok(0); - } - if let Some(err) = &self.sticky_error { - return Err(io::Error::other(err.clone())); - } - if let Some(err) = self.stashed_error.take() { - self.sticky_error = Some(err.clone()); - return Err(io::Error::other(err)); - } - - let mut written = 0usize; - while written < buf.len() { - if self.pending_pos < self.pending.len() { - let avail = self.pending.len() - self.pending_pos; - let take = avail.min(buf.len() - written); - buf[written..written + take] - .copy_from_slice(&self.pending[self.pending_pos..self.pending_pos + take]); - self.pending_pos += take; - written += take; - if self.pending_pos == self.pending.len() { - self.pending.clear(); - self.pending_pos = 0; - } - continue; - } - - if self.eof { - break; - } - - match self.source.next_raw_document() { - Ok(None) => { - self.eof = true; - break; - } - Ok(Some(doc)) => { - if let Err(err) = - validate_raw_bson_frame(doc, self.docs_read, self.max_doc_bytes) - { - if written > 0 { - self.stashed_error = Some(err); - return Ok(written); - } - self.sticky_error = Some(err.clone()); - return Err(io::Error::other(err)); - } - - self.docs_read += 1; - self.bytes_read += doc.len() as u64; - - let remaining = buf.len() - written; - if doc.len() <= remaining { - buf[written..written + doc.len()].copy_from_slice(doc); - written += doc.len(); - } else { - buf[written..written + remaining].copy_from_slice(&doc[..remaining]); - written += remaining; - let tail = &doc[remaining..]; - self.pending.clear(); - if self.pending.capacity() < tail.len() { - self.pending.reserve_exact(tail.len()); - } - self.pending.extend_from_slice(tail); - self.pending_pos = 0; - break; - } - } - Err(err) => { - if written > 0 { - self.stashed_error = Some(err); - return Ok(written); - } - self.sticky_error = Some(err.clone()); - return Err(io::Error::other(err)); - } - } - } - - Ok(written) - } -} - -fn extract_raw_uri_password(uri: &str) -> Option<&str> { - let scheme_end = uri.find("://")?; - let rest = &uri[scheme_end + 3..]; - let authority_end = rest.find(['/', '?']).unwrap_or(rest.len()); - let authority = &rest[..authority_end]; - let at_idx = authority.find('@')?; - let userinfo = &authority[..at_idx]; - let colon_idx = userinfo.find(':')?; - let pass = &userinfo[colon_idx + 1..]; - if pass.is_empty() { - None - } else { - Some(pass) - } -} - -fn percent_decode_best_effort(input: &str) -> Option { - let bytes = input.as_bytes(); - let mut out = Vec::with_capacity(bytes.len()); - let mut i = 0; - while i < bytes.len() { - if bytes[i] == b'%' && i + 2 < bytes.len() { - let hi = hex_nibble(bytes[i + 1])?; - let lo = hex_nibble(bytes[i + 2])?; - out.push((hi << 4) | lo); - i += 3; - } else { - out.push(bytes[i]); - i += 1; - } - } - String::from_utf8(out).ok() -} - -fn hex_nibble(b: u8) -> Option { - match b { - b'0'..=b'9' => Some(b - b'0'), - b'a'..=b'f' => Some(b - b'a' + 10), - b'A'..=b'F' => Some(b - b'A' + 10), - _ => None, - } -} - -fn find_next_mongo_scheme(lower_slice: &str) -> Option<(usize, usize)> { - let next_std = lower_slice - .find("mongodb://") - .map(|i| (i, "mongodb://".len())); - let next_srv = lower_slice - .find("mongodb+srv://") - .map(|i| (i, "mongodb+srv://".len())); - match (next_std, next_srv) { - (Some(a), Some(b)) => Some(if a.0 <= b.0 { a } else { b }), - (Some(a), None) => Some(a), - (None, Some(b)) => Some(b), - (None, None) => None, - } -} - -fn redact_embedded_mongo_uris(text: &str) -> String { - let mut result = String::with_capacity(text.len()); - let mut cursor = 0usize; - let lower = text.to_ascii_lowercase(); - - while cursor < text.len() { - let Some((rel_start, scheme_len)) = find_next_mongo_scheme(&lower[cursor..]) else { - result.push_str(&text[cursor..]); - break; - }; - - let start = cursor + rel_start; - result.push_str(&text[cursor..start]); - - let tail = &text[start..]; - let after_scheme = &tail[scheme_len..]; - let after_scheme_lower = &lower[start + scheme_len..]; - // Authority ends at `/`, `?`, whitespace, or the start of a subsequent - // MongoDB URI scheme (e.g., compact JSON `["mongodb://host","mongodb://u:p@host"]`). - // Do not stop on punctuation such as `,`, `;`, `)`, `]`, `}`, `"`, `'` before - // locating `@`, because embedded passwords (or replica-set host lists) may contain them. - let delim_end = after_scheme - .find(|c: char| c.is_whitespace() || matches!(c, '/' | '?')) - .unwrap_or(after_scheme.len()); - let next_scheme_end = find_next_mongo_scheme(after_scheme_lower) - .map(|(idx, _)| idx) - .unwrap_or(after_scheme.len()); - let authority_end = delim_end.min(next_scheme_end); - let authority_region = &after_scheme[..authority_end]; - - if let Some(at_idx) = authority_region.rfind('@') { - let userinfo = &authority_region[..at_idx]; - if let Some(colon_idx) = userinfo.find(':') { - let prefix_with_at = &tail[..scheme_len + at_idx + 1]; - if !userinfo.contains('@') { - result.push_str(&redact_mongo_uri_password(prefix_with_at)); - } else { - result.push_str(&tail[..scheme_len + colon_idx + 1]); - result.push_str("[REDACTED]@"); - } - cursor = start + scheme_len + at_idx + 1; - continue; - } - } - - let advance = scheme_len + authority_end; - result.push_str(&tail[..advance]); - cursor = start + advance; - } - - result -} - -/// Strips raw URI, raw password, percent-decoded password, and any embedded -/// `mongodb://` / `mongodb+srv://` userinfo passwords from driver error text. -pub(crate) fn sanitize_driver_error_message( - raw_message: &str, - uri: &ValidatedReadOnlyMongoUri, -) -> String { - let redacted_uri = uri.redacted(); - let mut sanitized = raw_message.split(uri.as_str()).collect::>().join(&redacted_uri); - - if let Some(raw_pass) = extract_raw_uri_password(uri.as_str()) { - sanitized = sanitized.split(raw_pass).collect::>().join("[REDACTED]"); - if let Some(decoded_pass) = percent_decode_best_effort(raw_pass) { - if !decoded_pass.is_empty() && decoded_pass != raw_pass { - sanitized = sanitized - .split(&decoded_pass) - .collect::>() - .join("[REDACTED]"); - } - } - } - - redact_embedded_mongo_uris(&sanitized) -} - -/// Sealed read-only raw-BSON document source backed by a `mongodb::sync::Cursor`. -/// -/// Advances one document at a time directly over the driver's wire batch buffer -/// (`cursor.current().as_bytes()`) with zero per-document heap allocation or -/// BSON object deserialization. Exposes no write, admin, or underlying driver -/// handle. -pub struct MongoRawDocumentSource { - cursor: mongodb::sync::Cursor, - uri: ValidatedReadOnlyMongoUri, - exhausted: bool, -} - -impl fmt::Debug for MongoRawDocumentSource { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("MongoRawDocumentSource") - .field("uri", &self.uri.redacted()) - .field("exhausted", &self.exhausted) - .finish() - } -} - -impl RawDocumentSource for MongoRawDocumentSource { - fn next_raw_document(&mut self) -> Result, MongoStreamError> { - if self.exhausted { - return Ok(None); - } - match self.cursor.advance() { - Ok(true) => Ok(Some(self.cursor.current().as_bytes())), - Ok(false) => { - self.exhausted = true; - Ok(None) - } - Err(err) => { - self.exhausted = true; - Err(MongoStreamError::redacted_source( - &err.to_string(), - &self.uri, - )) - } - } - } -} - -/// Sealed read-only raw-BSON document source that streams a sequence of -/// key-partitioned `$in` queries over an allowlisted collection so indexed -/// per-symbol scans (`eodSearchCode`, `qmSearchCode`) skip out-of-scope global -/// symbols and avoid random-I/O date-index fetches. -pub struct ChunkedMongoRawDocumentSource { - coll: mongodb::sync::Collection, - uri: ValidatedReadOnlyMongoUri, - key_field: &'static str, - date_filter: Option<(String, Bson)>, - batch_size: u32, - chunks: std::vec::IntoIter>, - current: Option>, - exhausted: bool, -} - -impl fmt::Debug for ChunkedMongoRawDocumentSource { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("ChunkedMongoRawDocumentSource") - .field("uri", &self.uri.redacted()) - .field("key_field", &self.key_field) - .field("exhausted", &self.exhausted) - .finish() - } -} - -impl RawDocumentSource for ChunkedMongoRawDocumentSource { - fn next_raw_document(&mut self) -> Result, MongoStreamError> { - if self.exhausted { - return Ok(None); - } - loop { - if self.current.is_some() { - let advanced = { - let cursor = self.current.as_mut().expect("checked is_some"); - cursor.advance() - }; - match advanced { - Ok(true) => { - let cursor = self.current.as_ref().expect("checked is_some"); - return Ok(Some(cursor.current().as_bytes())); - } - Ok(false) => { - self.current = None; - } - Err(err) => { - self.exhausted = true; - self.current = None; - return Err(MongoStreamError::redacted_source( - &err.to_string(), - &self.uri, - )); - } - } - } - let Some(chunk) = self.chunks.next() else { - self.exhausted = true; - return Ok(None); - }; - let mut entries: Vec<(String, Bson)> = Vec::with_capacity(2); - entries.push(( - self.key_field.to_owned(), - Bson::Document(Document::from_iter([("$in".to_owned(), Bson::Array(chunk))])), - )); - if let Some((df, dv)) = &self.date_filter { - entries.push((df.clone(), dv.clone())); - } - let filter = Document::from_iter(entries); - let cursor = self - .coll - .find(filter) - .batch_size(self.batch_size) - .run() - .map_err(|err| { - self.exhausted = true; - MongoStreamError::redacted_source(&err.to_string(), &self.uri) - })?; - self.current = Some(cursor); - } - } -} - -/// Sealed read-only MongoDB client constructed exclusively from a -/// [`ValidatedReadOnlyMongoUri`] proof token. -/// -/// Intentionally exposes **only** allowlisted raw-BSON `find` cursor opening -/// via [`Self::open_raw_cursor`] and clean shutdown via [`Self::shutdown`]. -/// No `mongodb::sync::Client`, `Database`, `Collection`, write, index, admin, -/// or aggregation surface is accessible outside this module. -pub struct ReadOnlyMongoClient { - client: mongodb::sync::Client, - uri: ValidatedReadOnlyMongoUri, - database_name: String, -} - -impl fmt::Debug for ReadOnlyMongoClient { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("ReadOnlyMongoClient") - .field("uri", &self.uri.redacted()) - .field("database", &self.database_name) - .finish() - } -} - -impl ReadOnlyMongoClient { - /// Connects a sealed read-only MongoDB client using a pre-validated - /// [`ValidatedReadOnlyMongoUri`] proof token. - /// - /// Fails closed if the URI omits a database name in its path. - pub fn connect(uri: ValidatedReadOnlyMongoUri) -> Result { - let Some(database_name) = uri.target().database.clone() else { - return Err(MongoStreamError::Source { - detail: "validated MongoDB URI must specify a database name in its path (e.g. /stock)" - .to_owned(), - }); - }; - let client = mongodb::sync::Client::with_uri_str(uri.as_str()) - .map_err(|err| MongoStreamError::redacted_source(&err.to_string(), &uri))?; - Ok(Self { - client, - uri, - database_name, - }) - } - - /// Returns the target database name parsed from the validated URI. - #[inline] - pub fn database_name(&self) -> &str { - &self.database_name - } - - /// Returns the validated URI with its password replaced by `[REDACTED]`. - #[inline] - pub fn redacted_uri(&self) -> String { - self.uri.redacted() - } - - /// Opens a read-only raw-BSON `find` cursor over an allowlisted - /// [`SourceCollection`] and wraps it in a bounded-memory - /// [`RawBsonCursorReader`] implementing [`io::Read`]. - pub fn open_raw_cursor( - &self, - collection: SourceCollection, - spec: &MongoReadSpec, - ) -> Result, MongoStreamError> { - let filter = build_filter_document(collection, spec)?; - let coll = self - .client - .database(&self.database_name) - .collection::(collection.as_str()); - - let mut find = coll.find(filter).batch_size(spec.batch_size); - if let Some(limit) = spec.limit { - find = find.limit(limit as i64); - } - - let cursor = find - .run() - .map_err(|err| MongoStreamError::redacted_source(&err.to_string(), &self.uri))?; - - let source = MongoRawDocumentSource { - cursor, - uri: self.uri.clone(), - exhausted: false, - }; - RawBsonCursorReader::with_max_doc_bytes(source, spec.max_doc_bytes) - } - - /// Opens a read-only raw-BSON stream partitioned into `$in` chunks over - /// `keys` on `collection.key_field()`, avoiding random-I/O date-index - /// scans when reading a known security-master key universe (e.g. US+CA - /// `eodPrices` / `qmPrices`). - pub fn open_raw_cursor_for_keys( - &self, - collection: SourceCollection, - spec: &MongoReadSpec, - keys: &[String], - chunk_size: usize, - ) -> Result, MongoStreamError> { - spec.validate(collection)?; - let effective_chunk = chunk_size.clamp(1, 2000); - let date_filter = if let (Some(range), Some(date_field)) = - (&spec.date_range, collection.date_field()) - { - let mut range_entries: Vec<(String, Bson)> = Vec::with_capacity(2); - if let Some(gte) = &range.gte { - range_entries.push(("$gte".to_owned(), gte.to_bson())); - } - if let Some(lt) = &range.lt { - range_entries.push(("$lt".to_owned(), lt.to_bson())); - } - if range_entries.is_empty() { - None - } else { - Some(( - date_field.to_owned(), - Bson::Document(Document::from_iter(range_entries)), - )) - } - } else { - None - }; - - let chunks: Vec> = keys - .chunks(effective_chunk) - .map(|c| c.iter().cloned().map(Bson::String).collect()) - .collect(); - - let coll = self - .client - .database(&self.database_name) - .collection::(collection.as_str()); - - let source = ChunkedMongoRawDocumentSource { - coll, - uri: self.uri.clone(), - key_field: collection.key_field(), - date_filter, - batch_size: spec.batch_size, - chunks: chunks.into_iter(), - current: None, - exhausted: false, - }; - RawBsonCursorReader::with_max_doc_bytes(source, spec.max_doc_bytes) - } - - /// Cleanly terminates background driver tasks once all open cursors have - /// been dropped. - pub fn shutdown(self) { - self.client.shutdown().run(); - } -} - -/// Validates `raw_uri` against [`ReadOnlyPolicy::default`] and `local_hosts` -/// and opens a sealed [`ReadOnlyMongoClient`]. -pub fn open_read_only_mongo_uri( - raw_uri: &str, - local_hosts: &LocalHosts, -) -> Result { - let validated = assert_read_only_mongo_uri(raw_uri, &ReadOnlyPolicy::default(), local_hosts) - .map_err(|err| MongoStreamError::Source { - detail: err.to_string(), - })?; - ReadOnlyMongoClient::connect(validated) -} - -/// Reads a MongoDB URI from environment variable `env_var`, validates it -/// against [`ReadOnlyPolicy::default`] and `local_hosts`, and opens a sealed -/// [`ReadOnlyMongoClient`]. -pub fn open_read_only_mongo_from_env( - env_var: &str, - local_hosts: &LocalHosts, -) -> Result { - if env_var.trim().is_empty() { - return Err(MongoStreamError::Source { - detail: "MongoDB URI environment variable name must not be empty".to_owned(), - }); - } - let raw_uri = std::env::var(env_var).map_err(|_| MongoStreamError::Source { - detail: format!("environment variable '{env_var}' is not set or not valid UTF-8"), - })?; - open_read_only_mongo_uri(&raw_uri, local_hosts) -} - -/// Configured source for a read-only MongoDB URI in CLI invocations. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum MongoUriSource { - /// Read URI from an environment variable (default [`DEFAULT_MONGO_URI_ENV`]). - EnvVar(String), - /// Explicit URI passed via `--mongo-uri`. - Literal(String), -} - -impl MongoUriSource { - /// Validates and connects a sealed [`ReadOnlyMongoClient`] using - /// [`LocalHosts::detect`]. - pub fn connect(&self) -> Result { - let local_hosts = LocalHosts::detect(); - match self { - Self::EnvVar(var) => open_read_only_mongo_from_env(var, &local_hosts), - Self::Literal(raw) => open_read_only_mongo_uri(raw, &local_hosts), - } - } -} - -/// Shared MongoDB streaming options parsed by `--from-mongo` CLI commands. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct MongoCliOptions { - pub uri_source: MongoUriSource, - pub batch_size: u32, - pub limit: Option, - pub date_gte: Option, - pub date_lt: Option, -} - -impl Default for MongoCliOptions { - fn default() -> Self { - Self { - uri_source: MongoUriSource::EnvVar(DEFAULT_MONGO_URI_ENV.to_owned()), - batch_size: DEFAULT_MONGO_BATCH_SIZE, - limit: None, - date_gte: None, - date_lt: None, - } - } -} - -impl MongoCliOptions { - /// Builds a [`MongoReadSpec`] for string-dated collections, attaching `key_eq` - /// and optional ISO string date bounds when `apply_date_range` is `true`. - pub fn to_read_spec(&self, key_eq: Option, apply_date_range: bool) -> MongoReadSpec { - let date_range = if apply_date_range && (self.date_gte.is_some() || self.date_lt.is_some()) - { - Some(MongoDateRange { - gte: self.date_gte.clone().map(FilterDateValue::IsoString), - lt: self.date_lt.clone().map(FilterDateValue::IsoString), - }) - } else { - None - }; - MongoReadSpec { - key_eq, - date_range, - batch_size: self.batch_size, - limit: self.limit, - max_doc_bytes: DEFAULT_MAX_DOC_BYTES, - } - } - - /// Builds a [`MongoReadSpec`] using the collection's native BSON date representation: - /// `BsonDateTimeMillis` (UTC midnight) for BSON `DateTime` collections (`qmEarnings`, - /// `ceoShorts`) and `IsoString` for string-dated collections (`eodPrices`, `qmPrices`, - /// `qmSplits`, `qmDividends`, `qmFilings`). - pub fn to_read_spec_for_collection( - &self, - collection: SourceCollection, - key_eq: Option, - apply_date_range: bool, - ) -> MongoReadSpec { - if !apply_date_range || (self.date_gte.is_none() && self.date_lt.is_none()) { - return self.to_read_spec(key_eq, false); - } - if !collection.date_field_is_bson_datetime() { - return self.to_read_spec(key_eq, true); - } - let to_dt = |raw: &String| -> FilterDateValue { - match parse_ymd_strict_days(raw) { - Some(days) => FilterDateValue::BsonDateTimeMillis(i64::from(days) * MILLIS_PER_DAY), - None => FilterDateValue::IsoString(raw.clone()), - } - }; - MongoReadSpec { - key_eq, - date_range: Some(MongoDateRange { - gte: self.date_gte.as_ref().map(to_dt), - lt: self.date_lt.as_ref().map(to_dt), - }), - batch_size: self.batch_size, - limit: self.limit, - max_doc_bytes: DEFAULT_MAX_DOC_BYTES, - } - } -} - -#[cfg(test)] -#[path = "mongo_stream_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/mongo_stream_tests.rs b/tools/curate-etl/src/mongo_stream_tests.rs deleted file mode 100644 index 41fa6da4..00000000 --- a/tools/curate-etl/src/mongo_stream_tests.rs +++ /dev/null @@ -1,1941 +0,0 @@ -use std::fs; -use std::io::{self, Cursor, Read}; -use std::path::PathBuf; - -use bson::raw::{cstr, RawDocumentBuf}; -use bson::{Bson, DateTime}; - -use crate::bson_qm_events::QmFilingsFieldNames; -use crate::bson_stream::{ - decode_eod_price_stream, decode_qm_dividend_stream, decode_qm_filings_stream, - decode_qm_split_stream, BsonStreamError, BsonStreamOptions, MIN_BSON_DOC_BYTES, -}; -use crate::mongo_safety::{ - assert_read_only_mongo_uri, LocalHosts, ReadOnlyPolicy, ValidatedReadOnlyMongoUri, -}; -use crate::mongo_stream::{ - build_filter_document, sanitize_driver_error_message, FilterDateValue, MongoDateRange, - MongoReadSpec, MongoStreamError, RawBsonCursorReader, RawDocumentSource, - SliceRawDocumentSource, SourceCollection, VecRawDocumentSource, DEFAULT_MONGO_BATCH_SIZE, - MAX_MONGO_BATCH_SIZE, -}; - -fn build_eod_doc(code: &str, date: &str, close: f64, volume: f64) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), code); - doc.append(cstr!("date"), date); - doc.append(cstr!("open"), close); - doc.append(cstr!("high"), close + 1.0); - doc.append(cstr!("low"), (close - 1.0).max(0.1)); - doc.append(cstr!("close"), close); - doc.append(cstr!("volume"), volume); - doc.into_bytes() -} - -fn build_eod_reject_doc(code: &str) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), code); - doc.append(cstr!("date"), "not-a-date"); - doc.append(cstr!("open"), 10.0); - doc.append(cstr!("high"), 11.0); - doc.append(cstr!("low"), 9.0); - doc.append(cstr!("close"), 10.5); - doc.append(cstr!("volume"), 100.0); - doc.into_bytes() -} - -fn build_qm_split_doc(code: &str, date: &str, ratio: f64) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), code); - doc.append(cstr!("date"), date); - doc.append(cstr!("splitratio"), ratio); - doc.into_bytes() -} - -fn build_qm_split_reject_doc(code: &str) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), code); - doc.append(cstr!("date"), "2024-06-10"); - doc.append(cstr!("splitratio"), "bad-type"); - doc.into_bytes() -} - -fn build_qm_dividend_doc(code: &str, date: &str, cash: f64, currency: &str) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), code); - doc.append(cstr!("date"), date); - doc.append(cstr!("amount"), cash); - doc.append(cstr!("currency"), currency); - doc.into_bytes() -} - -fn build_qm_dividend_reject_doc(code: &str) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), code); - doc.append(cstr!("date"), "2024-06-10"); - doc.append(cstr!("amount"), -1.0); - doc.append(cstr!("currency"), "USD"); - doc.into_bytes() -} - -fn build_qm_filing_doc( - symbol: &str, - timefiled: &str, - form_type: &str, - filing_id: Option<&str>, -) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("symbol"), symbol); - doc.append(cstr!("timefiled"), timefiled); - doc.append(cstr!("formtype"), form_type); - if let Some(id) = filing_id { - doc.append(cstr!("filingid"), id); - } - doc.into_bytes() -} - -fn build_qm_filing_reject_doc(symbol: &str) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("symbol"), symbol); - doc.append(cstr!("timefiled"), "2024-06-10T16:30:00 EDT"); - // Missing required formtype -> semantic skip - doc.into_bytes() -} - -fn concat_docs(docs: &[Vec]) -> Vec { - let total: usize = docs.iter().map(Vec::len).sum(); - let mut out = Vec::with_capacity(total); - for doc in docs { - out.extend_from_slice(doc); - } - out -} - -/// Wraps any `io::Read` and caps every single `read()` call to `max_step` bytes, -/// exercising tiny (1-byte) and odd-sized (`3`, `7`, `13`, `37` B) read buffers. -struct CappedRead { - inner: R, - max_step: usize, -} - -impl CappedRead { - fn new(inner: R, max_step: usize) -> Self { - Self { inner, max_step } - } -} - -impl Read for CappedRead { - fn read(&mut self, buf: &mut [u8]) -> io::Result { - let cap = buf.len().min(self.max_step); - self.inner.read(&mut buf[..cap]) - } -} - -fn read_all_with_step(reader: &mut R, step: usize) -> io::Result> { - let mut out = Vec::new(); - let mut buf = vec![0u8; step]; - loop { - let n = reader.read(&mut buf)?; - if n == 0 { - break; - } - out.extend_from_slice(&buf[..n]); - } - Ok(out) -} - -fn validate_uri(raw: &str) -> ValidatedReadOnlyMongoUri { - assert_read_only_mongo_uri(raw, &ReadOnlyPolicy::default(), &LocalHosts::empty()) - .expect("test URI must pass read-only safety guard") -} - -struct FailingSource { - docs: Vec>, - index: usize, - fail_at: usize, - err: MongoStreamError, -} - -impl RawDocumentSource for FailingSource { - fn next_raw_document(&mut self) -> Result, MongoStreamError> { - if self.index == self.fail_at { - return Err(self.err.clone()); - } - if self.index >= self.docs.len() { - return Ok(None); - } - let doc = self.docs[self.index].as_slice(); - self.index += 1; - Ok(Some(doc)) - } -} - -// --------------------------------------------------------------------------- -// 1. Allowlist parity against export-raw-bson.ts -// --------------------------------------------------------------------------- - -#[test] -fn source_collection_allowlist_matches_export_raw_bson_ts_exactly() { - let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let ts_path = manifest_dir - .join("..") - .join("..") - .join("apps") - .join("stock") - .join("data-pipeline") - .join("src") - .join("security-master") - .join("export-raw-bson.ts"); - - let contents = fs::read_to_string(&ts_path) - .unwrap_or_else(|err| panic!("failed to read {}: {err}", ts_path.display())); - - let anchor = "export const RAW_BSON_EXPORT_COLLECTIONS = Object.freeze(["; - let start = contents - .find(anchor) - .expect("RAW_BSON_EXPORT_COLLECTIONS declaration not found in export-raw-bson.ts") - + anchor.len(); - let rest = &contents[start..]; - let end = rest - .find("] as const") - .expect("closing `] as const` not found for RAW_BSON_EXPORT_COLLECTIONS"); - let block = &rest[..end]; - - let ts_names: Vec = block - .lines() - .filter_map(|line| { - let trimmed = line.trim(); - let first_quote = trimmed.find('\'')?; - let after_first = &trimmed[first_quote + 1..]; - let second_quote = after_first.find('\'')?; - Some(after_first[..second_quote].to_owned()) - }) - .collect(); - - let rust_names: Vec<&str> = SourceCollection::ALL.iter().map(|c| c.as_str()).collect(); - let expected = vec![ - "eodPrices", - "qmSplits", - "qmDividends", - "qmPrices", - "teMarketData", - "ceoShorts", - "qmFilings", - "qmEarnings", - ]; - - assert_eq!(rust_names, expected); - assert_eq!( - ts_names, - rust_names - .iter() - .map(|s| (*s).to_owned()) - .collect::>(), - "SourceCollection::ALL must match RAW_BSON_EXPORT_COLLECTIONS in exact names and order" - ); - assert_eq!(SourceCollection::ALL.len(), 8); -} - -// --------------------------------------------------------------------------- -// 2. Decoder parity across 4 collections + 1-byte and odd-sized buffers -// --------------------------------------------------------------------------- - -#[test] -fn parity_eod_prices_stream_across_default_and_odd_buffers() { - let docs = vec![ - build_eod_doc("AAPL.US", "2024-01-02", 185.5, 1000.0), - build_eod_reject_doc("BAD.US"), - build_eod_doc("NVDA.US", "2024-06-10", 121.75, 50_000.0), - build_eod_doc("RY.TO", "2024-12-31", 173.25, 250_000.0), - ]; - let concat = concat_docs(&docs); - let total_bytes = concat.len() as u64; - - let mut expected_rows = Vec::new(); - let mut expected_errs = Vec::new(); - let expected_stats = decode_eod_price_stream( - Cursor::new(&concat), - BsonStreamOptions::default(), - |bar| { - expected_rows.push(( - bar.eod_search_code.to_owned(), - bar.session_date, - bar.open.to_bits(), - bar.high.to_bits(), - bar.low.to_bits(), - bar.close.to_bits(), - bar.adj_volume.to_bits(), - )); - }, - |offset, err| expected_errs.push((offset, err)), - ) - .expect("baseline cursor decode must succeed"); - assert_eq!(expected_rows.len(), 3, "baseline eodPrices must decode 3 valid rows"); - assert_eq!(expected_errs.len(), 1, "baseline eodPrices must reject 1 invalid doc"); - assert_eq!(expected_stats.decoded, 3); - assert_eq!(expected_stats.rejected_total(), 1); - - for step in [usize::MAX, 1, 3, 7, 13, 37] { - let mut cursor_reader = RawBsonCursorReader::new(VecRawDocumentSource::new(docs.clone())); - let mut rows = Vec::new(); - let mut errs = Vec::new(); - let stats = if step == usize::MAX { - decode_eod_price_stream( - &mut cursor_reader, - BsonStreamOptions::default(), - |bar| { - rows.push(( - bar.eod_search_code.to_owned(), - bar.session_date, - bar.open.to_bits(), - bar.high.to_bits(), - bar.low.to_bits(), - bar.close.to_bits(), - bar.adj_volume.to_bits(), - )); - }, - |offset, err| errs.push((offset, err)), - ) - .expect("stream decode must succeed") - } else { - decode_eod_price_stream( - CappedRead::new(&mut cursor_reader, step), - BsonStreamOptions::default(), - |bar| { - rows.push(( - bar.eod_search_code.to_owned(), - bar.session_date, - bar.open.to_bits(), - bar.high.to_bits(), - bar.low.to_bits(), - bar.close.to_bits(), - bar.adj_volume.to_bits(), - )); - }, - |offset, err| errs.push((offset, err)), - ) - .expect("capped stream decode must succeed") - }; - - assert_eq!(stats, expected_stats, "eodPrices stats mismatch at step={step}"); - assert_eq!(rows, expected_rows, "eodPrices rows mismatch at step={step}"); - assert_eq!(errs, expected_errs, "eodPrices errors mismatch at step={step}"); - assert_eq!(cursor_reader.docs_read(), docs.len() as u64); - assert_eq!(cursor_reader.bytes_read(), total_bytes); - } -} - -#[test] -fn parity_qm_splits_stream_across_default_and_odd_buffers() { - let docs = vec![ - build_qm_split_doc("NVDA:US", "2024-06-10", 10.0), - build_qm_split_reject_doc("BAD:US"), - build_qm_split_doc("NEXM:CA", "2025-06-18", 0.05), - ]; - let concat = concat_docs(&docs); - - let mut expected_rows = Vec::new(); - let mut expected_errs = Vec::new(); - let expected_stats = decode_qm_split_stream( - Cursor::new(&concat), - BsonStreamOptions::default(), - |row| { - expected_rows.push(( - row.qm_search_code.to_owned(), - row.ex_date, - row.ratio.to_bits(), - row.declared_date, - )); - }, - |offset, err| expected_errs.push((offset, err)), - ) - .expect("baseline qmSplits decode must succeed"); - assert_eq!(expected_rows.len(), 2, "baseline qmSplits must decode 2 valid rows"); - assert_eq!(expected_errs.len(), 1, "baseline qmSplits must reject 1 invalid doc"); - assert_eq!(expected_stats.decoded, 2); - assert_eq!(expected_stats.rejected_total(), 1); - - for step in [usize::MAX, 1, 3, 7, 13, 37] { - let mut cursor_reader = RawBsonCursorReader::new(VecRawDocumentSource::new(docs.clone())); - let mut rows = Vec::new(); - let mut errs = Vec::new(); - let stats = if step == usize::MAX { - decode_qm_split_stream( - &mut cursor_reader, - BsonStreamOptions::default(), - |row| { - rows.push(( - row.qm_search_code.to_owned(), - row.ex_date, - row.ratio.to_bits(), - row.declared_date, - )); - }, - |offset, err| errs.push((offset, err)), - ) - .expect("qmSplits stream decode must succeed") - } else { - decode_qm_split_stream( - CappedRead::new(&mut cursor_reader, step), - BsonStreamOptions::default(), - |row| { - rows.push(( - row.qm_search_code.to_owned(), - row.ex_date, - row.ratio.to_bits(), - row.declared_date, - )); - }, - |offset, err| errs.push((offset, err)), - ) - .expect("capped qmSplits stream decode must succeed") - }; - - assert_eq!(stats, expected_stats, "qmSplits stats mismatch at step={step}"); - assert_eq!(rows, expected_rows, "qmSplits rows mismatch at step={step}"); - assert_eq!(errs, expected_errs, "qmSplits errors mismatch at step={step}"); - assert_eq!(cursor_reader.docs_read(), docs.len() as u64); - assert_eq!(cursor_reader.bytes_read(), concat.len() as u64); - } -} - -#[test] -fn parity_qm_dividends_stream_across_default_and_odd_buffers() { - let docs = vec![ - build_qm_dividend_doc("AAPL:US", "2024-05-10", 0.25, "USD"), - build_qm_dividend_reject_doc("BAD:US"), - build_qm_dividend_doc("RY:CA", "2024-07-25", 1.42, "CAD"), - ]; - let concat = concat_docs(&docs); - - let mut expected_rows = Vec::new(); - let mut expected_errs = Vec::new(); - let expected_stats = decode_qm_dividend_stream( - Cursor::new(&concat), - BsonStreamOptions::default(), - |row| { - expected_rows.push(( - row.qm_search_code.to_owned(), - row.ex_date, - row.cash.to_bits(), - row.currency.to_owned(), - row.declared_date, - )); - }, - |offset, err| expected_errs.push((offset, err)), - ) - .expect("baseline qmDividends decode must succeed"); - assert_eq!(expected_rows.len(), 2, "baseline qmDividends must decode 2 valid rows"); - assert_eq!(expected_errs.len(), 1, "baseline qmDividends must reject 1 invalid doc"); - assert_eq!(expected_stats.decoded, 2); - assert_eq!(expected_stats.rejected_total(), 1); - - for step in [usize::MAX, 1, 3, 7, 13, 37] { - let mut cursor_reader = RawBsonCursorReader::new(VecRawDocumentSource::new(docs.clone())); - let mut rows = Vec::new(); - let mut errs = Vec::new(); - let stats = if step == usize::MAX { - decode_qm_dividend_stream( - &mut cursor_reader, - BsonStreamOptions::default(), - |row| { - rows.push(( - row.qm_search_code.to_owned(), - row.ex_date, - row.cash.to_bits(), - row.currency.to_owned(), - row.declared_date, - )); - }, - |offset, err| errs.push((offset, err)), - ) - .expect("qmDividends stream decode must succeed") - } else { - decode_qm_dividend_stream( - CappedRead::new(&mut cursor_reader, step), - BsonStreamOptions::default(), - |row| { - rows.push(( - row.qm_search_code.to_owned(), - row.ex_date, - row.cash.to_bits(), - row.currency.to_owned(), - row.declared_date, - )); - }, - |offset, err| errs.push((offset, err)), - ) - .expect("capped qmDividends stream decode must succeed") - }; - - assert_eq!(stats, expected_stats, "qmDividends stats mismatch at step={step}"); - assert_eq!(rows, expected_rows, "qmDividends rows mismatch at step={step}"); - assert_eq!(errs, expected_errs, "qmDividends errors mismatch at step={step}"); - assert_eq!(cursor_reader.docs_read(), docs.len() as u64); - assert_eq!(cursor_reader.bytes_read(), concat.len() as u64); - } -} - -#[test] -fn parity_qm_filings_stream_across_default_and_odd_buffers() { - let docs = vec![ - build_qm_filing_doc("AAPL:US", "2024-05-03T16:30:00 EDT", "10-Q", Some("F-101")), - build_qm_filing_reject_doc("BAD:US"), - build_qm_filing_doc("RY:CA", "2024-12-04T08:05:00 EST", "Annual financial statements", None), - ]; - let concat = concat_docs(&docs); - let fields = QmFilingsFieldNames { - key: "symbol", - timefiled: "timefiled", - form_type: "formtype", - filing_id: Some("filingid"), - url: None, - }; - - let mut expected_rows = Vec::new(); - let expected_stats = decode_qm_filings_stream( - Cursor::new(&concat), - BsonStreamOptions::default(), - &fields, - |row| { - expected_rows.push(( - row.key.to_owned(), - row.timefiled.to_owned(), - row.form_type.to_owned(), - row.filing_id.map(str::to_owned), - row.url.map(str::to_owned), - )); - }, - ) - .expect("baseline qmFilings decode must succeed"); - assert_eq!(expected_rows.len(), 2, "baseline qmFilings must decode 2 valid rows"); - assert_eq!(expected_stats.rows_out, 2); - assert_eq!(expected_stats.skipped_total(), 1); - - for step in [usize::MAX, 1, 3, 7, 13, 37] { - let mut cursor_reader = RawBsonCursorReader::new(VecRawDocumentSource::new(docs.clone())); - let mut rows = Vec::new(); - let stats = if step == usize::MAX { - decode_qm_filings_stream( - &mut cursor_reader, - BsonStreamOptions::default(), - &fields, - |row| { - rows.push(( - row.key.to_owned(), - row.timefiled.to_owned(), - row.form_type.to_owned(), - row.filing_id.map(str::to_owned), - row.url.map(str::to_owned), - )); - }, - ) - .expect("qmFilings stream decode must succeed") - } else { - decode_qm_filings_stream( - CappedRead::new(&mut cursor_reader, step), - BsonStreamOptions::default(), - &fields, - |row| { - rows.push(( - row.key.to_owned(), - row.timefiled.to_owned(), - row.form_type.to_owned(), - row.filing_id.map(str::to_owned), - row.url.map(str::to_owned), - )); - }, - ) - .expect("capped qmFilings stream decode must succeed") - }; - - assert_eq!(stats, expected_stats, "qmFilings stats mismatch at step={step}"); - assert_eq!(rows, expected_rows, "qmFilings rows mismatch at step={step}"); - assert_eq!(cursor_reader.docs_read(), docs.len() as u64); - assert_eq!(cursor_reader.bytes_read(), concat.len() as u64); - } -} - -// --------------------------------------------------------------------------- -// 3. Bounded memory, counters, framing validation & error handling -// --------------------------------------------------------------------------- - -#[test] -fn empty_source_yields_eof_with_zero_counts() { - let empty: [&[u8]; 0] = []; - let mut reader = RawBsonCursorReader::new(SliceRawDocumentSource::new(&empty)); - let mut buf = [0u8; 64]; - assert_eq!(reader.read(&mut buf).expect("empty read must succeed"), 0); - assert_eq!(reader.read(&mut buf).expect("repeated EOF must succeed"), 0); - assert_eq!(reader.docs_read(), 0); - assert_eq!(reader.bytes_read(), 0); - assert_eq!(reader.pending_capacity(), 0); -} - -#[test] -fn zero_length_read_buffer_returns_zero_without_advancing() { - let docs = vec![build_eod_doc("AAPL.US", "2024-01-02", 100.0, 50.0)]; - let mut reader = RawBsonCursorReader::new(VecRawDocumentSource::new(docs.clone())); - assert_eq!(reader.read(&mut []).expect("empty buf read must succeed"), 0); - assert_eq!(reader.docs_read(), 0); - assert_eq!(reader.bytes_read(), 0); - - let got = read_all_with_step(&mut reader, 64).expect("full read must succeed"); - assert_eq!(got, docs[0]); - assert_eq!(reader.docs_read(), 1); - assert_eq!(reader.bytes_read(), docs[0].len() as u64); -} - -#[test] -fn pending_capacity_stays_bounded_to_single_document_under_one_byte_reads() { - let docs: Vec> = (0..50) - .map(|i| build_eod_doc(&format!("SYM{i:03}.US"), "2024-01-02", 10.0 + i as f64, 100.0)) - .collect(); - let max_doc_len = docs.iter().map(Vec::len).max().unwrap(); - let expected = concat_docs(&docs); - - let mut reader = RawBsonCursorReader::new(VecRawDocumentSource::new(docs)); - let got = read_all_with_step(&mut reader, 1).expect("1-byte read must succeed"); - - assert_eq!(got, expected); - assert_eq!(reader.docs_read(), 50); - assert_eq!(reader.bytes_read(), expected.len() as u64); - assert!( - reader.pending_capacity() <= max_doc_len, - "pending_capacity ({}) exceeded max single doc length ({max_doc_len})", - reader.pending_capacity() - ); -} - -#[test] -fn mid_stream_source_error_delivers_prior_docs_then_surfaces_sticky_mongo_stream_error() { - let doc0 = build_eod_doc("AAPL.US", "2024-01-02", 100.0, 10.0); - let doc1 = build_eod_doc("MSFT.US", "2024-01-03", 200.0, 20.0); - let expected_err = MongoStreamError::Source { - detail: "simulated cursor drop mid-stream".to_owned(), - }; - let source = FailingSource { - docs: vec![doc0.clone(), doc1.clone()], - index: 0, - fail_at: 2, - err: expected_err.clone(), - }; - - let mut reader = RawBsonCursorReader::new(source); - let mut big_buf = vec![0u8; 4096]; - let n = reader - .read(&mut big_buf) - .expect("first read must return bytes from prior valid docs"); - assert_eq!(n, doc0.len() + doc1.len()); - assert_eq!(&big_buf[..doc0.len()], doc0.as_slice()); - assert_eq!(&big_buf[doc0.len()..n], doc1.as_slice()); - assert_eq!(reader.docs_read(), 2); - assert_eq!(reader.bytes_read(), (doc0.len() + doc1.len()) as u64); - - // Next read surfaces the stashed MongoStreamError wrapped in io::Error. - let io_err = reader - .read(&mut big_buf) - .expect_err("next read must surface stashed error"); - let downcast = io_err - .get_ref() - .and_then(|e| e.downcast_ref::()) - .expect("io::Error must carry MongoStreamError"); - assert_eq!(downcast, &expected_err); - - // Subsequent reads stay sticky with the same MongoStreamError. - let io_err2 = reader - .read(&mut big_buf) - .expect_err("reader must remain in sticky error state"); - let downcast2 = io_err2 - .get_ref() - .and_then(|e| e.downcast_ref::()) - .expect("sticky io::Error must carry MongoStreamError"); - assert_eq!(downcast2, &expected_err); -} - -#[test] -fn first_doc_source_error_surfaces_through_bson_stream_error_io() { - let expected_err = MongoStreamError::Source { - detail: "initial cursor failure".to_owned(), - }; - let source = FailingSource { - docs: vec![], - index: 0, - fail_at: 0, - err: expected_err.clone(), - }; - let reader = RawBsonCursorReader::new(source); - let err = decode_eod_price_stream(reader, BsonStreamOptions::default(), |_| {}, |_, _| {}) - .expect_err("decode_eod_price_stream must propagate source error"); - - match err { - BsonStreamError::Io { offset, source } => { - assert_eq!(offset, 0); - let inner = source - .get_ref() - .and_then(|e| e.downcast_ref::()) - .expect("BsonStreamError::Io must wrap MongoStreamError"); - assert_eq!(inner, &expected_err); - } - other => panic!("expected BsonStreamError::Io, got {other:?}"), - } -} - -#[test] -fn malformed_bson_frames_are_rejected_without_incrementing_counters() { - let valid_doc = build_eod_doc("AAPL.US", "2024-01-02", 100.0, 10.0); - - // 1. Shorter than MIN_BSON_DOC_BYTES (5) - let too_short = vec![4u8, 0, 0, 0]; - // 2. Negative declared length - let negative_len = vec![0xff, 0xff, 0xff, 0xff, 0x00]; - // 3. Declared length < actual byte length - let mut declared_lt_actual = valid_doc.clone(); - declared_lt_actual.push(0x00); - // 4. Declared length > actual byte length - let mut declared_gt_actual = valid_doc.clone(); - let bad_len = (valid_doc.len() as i32 + 4).to_le_bytes(); - declared_gt_actual[..4].copy_from_slice(&bad_len); - // 5. Missing trailing 0x00 terminator - let mut missing_null = valid_doc.clone(); - *missing_null.last_mut().unwrap() = 0x7f; - - let bad_cases = [ - ("too_short", too_short), - ("negative_len", negative_len), - ("declared_lt_actual", declared_lt_actual), - ("declared_gt_actual", declared_gt_actual), - ("missing_null", missing_null), - ]; - - for (label, bad_frame) in bad_cases { - let mut reader = RawBsonCursorReader::new(VecRawDocumentSource::new(vec![ - valid_doc.clone(), - bad_frame, - ])); - let mut buf = vec![0u8; 4096]; - let n = reader - .read(&mut buf) - .unwrap_or_else(|e| panic!("{label}: first doc should succeed, got {e}")); - assert_eq!(n, valid_doc.len(), "{label}"); - assert_eq!(reader.docs_read(), 1, "{label}"); - assert_eq!(reader.bytes_read(), valid_doc.len() as u64, "{label}"); - - let err = reader - .read(&mut buf) - .expect_err(&format!("{label}: bad frame must fail")); - let mongo_err = err - .get_ref() - .and_then(|e| e.downcast_ref::()) - .expect("must downcast to MongoStreamError"); - match mongo_err { - MongoStreamError::InvalidBsonFrame { doc_index, .. } => { - assert_eq!(*doc_index, 1, "{label}: doc_index must be 1"); - } - other => panic!("{label}: expected InvalidBsonFrame, got {other:?}"), - } - assert_eq!(reader.docs_read(), 1, "{label}: counters must not advance"); - assert_eq!(reader.bytes_read(), valid_doc.len() as u64, "{label}"); - } - - // 6. Exceeds max_doc_bytes - let mut reader = RawBsonCursorReader::with_max_doc_bytes( - VecRawDocumentSource::new(vec![valid_doc.clone()]), - valid_doc.len() - 1, - ) - .expect("with_max_doc_bytes >= 5 must succeed"); - let mut buf = vec![0u8; 4096]; - let err = reader.read(&mut buf).expect_err("oversized doc must fail"); - let mongo_err = err - .get_ref() - .and_then(|e| e.downcast_ref::()) - .expect("must downcast to MongoStreamError"); - assert!(matches!( - mongo_err, - MongoStreamError::InvalidBsonFrame { doc_index: 0, .. } - )); - assert_eq!(reader.docs_read(), 0); - assert_eq!(reader.bytes_read(), 0); - - // 7. with_max_doc_bytes < MIN_BSON_DOC_BYTES rejected - let err = RawBsonCursorReader::with_max_doc_bytes( - VecRawDocumentSource::new(vec![]), - MIN_BSON_DOC_BYTES - 1, - ) - .err() - .expect("max_doc_bytes < 5 must fail"); - assert!(matches!(err, MongoStreamError::InvalidMaxDocBytes { .. })); -} - -// --------------------------------------------------------------------------- -// 4. Filter & spec validation + lazy non-connecting open() -// --------------------------------------------------------------------------- - -#[test] -fn build_filter_document_and_spec_validation() { - // Empty spec -> empty filter document - let empty_filter = - build_filter_document(SourceCollection::EodPrices, &MongoReadSpec::default()) - .expect("default spec must be valid"); - assert!(empty_filter.is_empty()); - - // Key + ISO date range - let spec = MongoReadSpec { - key_eq: Some("AAPL.US".to_owned()), - date_range: Some(MongoDateRange { - gte: Some(FilterDateValue::IsoString("2024-01-01".to_owned())), - lt: Some(FilterDateValue::IsoString("2025-01-01".to_owned())), - }), - batch_size: DEFAULT_MONGO_BATCH_SIZE, - limit: Some(500), - ..MongoReadSpec::default() - }; - let doc = build_filter_document(SourceCollection::EodPrices, &spec) - .expect("valid key + date_range spec must succeed"); - assert_eq!( - doc.get("eodSearchCode"), - Some(&Bson::String("AAPL.US".to_owned())) - ); - let date_sub = doc - .get_document("date") - .expect("date range subdocument must exist"); - assert_eq!( - date_sub.get("$gte"), - Some(&Bson::String("2024-01-01".to_owned())) - ); - assert_eq!( - date_sub.get("$lt"), - Some(&Bson::String("2025-01-01".to_owned())) - ); - - // BSON DateTime millis range - let dt_spec = MongoReadSpec { - date_range: Some(MongoDateRange { - gte: Some(FilterDateValue::BsonDateTimeMillis(1_704_067_200_000)), - lt: Some(FilterDateValue::BsonDateTimeMillis(1_735_689_600_000)), - }), - ..MongoReadSpec::default() - }; - let dt_doc = build_filter_document(SourceCollection::QmEarnings, &dt_spec) - .expect("valid DateTime range must succeed"); - let rd = dt_doc - .get_document("reportDate") - .expect("reportDate subdocument must exist"); - assert_eq!( - rd.get("$gte"), - Some(&Bson::DateTime(DateTime::from_millis(1_704_067_200_000))) - ); - - // Invalid batch_size == 0 and > MAX_MONGO_BATCH_SIZE - assert!(matches!( - build_filter_document( - SourceCollection::EodPrices, - &MongoReadSpec { - batch_size: 0, - ..MongoReadSpec::default() - } - ), - Err(MongoStreamError::InvalidBatchSize { batch_size: 0, .. }) - )); - assert!(matches!( - build_filter_document( - SourceCollection::EodPrices, - &MongoReadSpec { - batch_size: MAX_MONGO_BATCH_SIZE + 1, - ..MongoReadSpec::default() - } - ), - Err(MongoStreamError::InvalidBatchSize { .. }) - )); - - // Invalid limit == Some(0) and > i64::MAX - assert!(matches!( - build_filter_document( - SourceCollection::EodPrices, - &MongoReadSpec { - limit: Some(0), - ..MongoReadSpec::default() - } - ), - Err(MongoStreamError::InvalidLimit { limit: 0 }) - )); - assert!(matches!( - build_filter_document( - SourceCollection::EodPrices, - &MongoReadSpec { - limit: Some(i64::MAX as u64 + 1), - ..MongoReadSpec::default() - } - ), - Err(MongoStreamError::InvalidLimit { .. }) - )); - - // Blank key_eq - assert!(matches!( - build_filter_document( - SourceCollection::EodPrices, - &MongoReadSpec { - key_eq: Some(" ".to_owned()), - ..MongoReadSpec::default() - } - ), - Err(MongoStreamError::InvalidKeyFilter { - collection: SourceCollection::EodPrices - }) - )); - - // date_range on TeMarketData - assert!(matches!( - build_filter_document( - SourceCollection::TeMarketData, - &MongoReadSpec { - date_range: Some(MongoDateRange { - gte: Some(FilterDateValue::IsoString("2024-01-01".to_owned())), - lt: None, - }), - ..MongoReadSpec::default() - } - ), - Err(MongoStreamError::DateRangeNotSupported { - collection: SourceCollection::TeMarketData - }) - )); - - // Empty date_range (neither gte nor lt) - assert!(matches!( - build_filter_document( - SourceCollection::EodPrices, - &MongoReadSpec { - date_range: Some(MongoDateRange { - gte: None, - lt: None, - }), - ..MongoReadSpec::default() - } - ), - Err(MongoStreamError::InvalidDateRange { .. }) - )); - - // Inverted date_range (gte >= lt) - assert!(matches!( - build_filter_document( - SourceCollection::EodPrices, - &MongoReadSpec { - date_range: Some(MongoDateRange { - gte: Some(FilterDateValue::IsoString("2025-01-01".to_owned())), - lt: Some(FilterDateValue::IsoString("2024-01-01".to_owned())), - }), - ..MongoReadSpec::default() - } - ), - Err(MongoStreamError::InvalidDateRange { .. }) - )); - - // Mismatched FilterDateValue variants - assert!(matches!( - build_filter_document( - SourceCollection::EodPrices, - &MongoReadSpec { - date_range: Some(MongoDateRange { - gte: Some(FilterDateValue::IsoString("2024-01-01".to_owned())), - lt: Some(FilterDateValue::BsonDateTimeMillis(1_735_689_600_000)), - }), - ..MongoReadSpec::default() - } - ), - Err(MongoStreamError::InvalidDateRange { .. }) - )); -} - -#[test] -fn qm_filings_date_range_requires_eastern_calendar_day_boundaries_and_handles_fall_back_dst() { - // UTC ISO string must be rejected: a filing stored as "2024-12-31T21:30:00 EST" - // (= 2025-01-01T02:30:00Z) would lexicographically sort before "2025-01-01T00:00:00Z". - assert!(matches!( - build_filter_document( - SourceCollection::QmFilings, - &MongoReadSpec { - date_range: Some(MongoDateRange { - gte: Some(FilterDateValue::IsoString("2025-01-01T00:00:00Z".to_owned())), - lt: Some(FilterDateValue::IsoString("2025-01-02T00:00:00Z".to_owned())), - }), - ..MongoReadSpec::default() - } - ), - Err(MongoStreamError::InvalidDateRange { - collection: SourceCollection::QmFilings, - .. - }) - )); - - // Intra-day Eastern timestamps must also be rejected for server-side string ranges: - // on fall-back DST day (2024-11-03), "2024-11-03T01:15:00 EST" occurred 45 minutes - // AFTER "2024-11-03T01:30:00 EDT" but sorts lexicographically BEFORE it. - assert!(matches!( - build_filter_document( - SourceCollection::QmFilings, - &MongoReadSpec { - date_range: Some(MongoDateRange { - gte: Some(FilterDateValue::IsoString( - "2024-11-03T01:30:00 EDT".to_owned() - )), - lt: Some(FilterDateValue::IsoString( - "2024-11-03T02:00:00 EST".to_owned() - )), - }), - ..MongoReadSpec::default() - } - ), - Err(MongoStreamError::InvalidDateRange { - collection: SourceCollection::QmFilings, - .. - }) - )); - - // Invalid calendar dates and BsonDateTimeMillis bounds must be rejected. - assert!(matches!( - build_filter_document( - SourceCollection::QmFilings, - &MongoReadSpec { - date_range: Some(MongoDateRange { - gte: Some(FilterDateValue::IsoString("2024-02-30".to_owned())), - lt: None, - }), - ..MongoReadSpec::default() - } - ), - Err(MongoStreamError::InvalidDateRange { - collection: SourceCollection::QmFilings, - .. - }) - )); - assert!(matches!( - build_filter_document( - SourceCollection::QmFilings, - &MongoReadSpec { - date_range: Some(MongoDateRange { - gte: Some(FilterDateValue::BsonDateTimeMillis(1_735_689_600_000)), - lt: None, - }), - ..MongoReadSpec::default() - } - ), - Err(MongoStreamError::InvalidDateRange { - collection: SourceCollection::QmFilings, - .. - }) - )); - - // Eastern calendar-day boundaries (YYYY-MM-DD) are monotonic even across fall-back DST - // (2024-11-03): both 01:30:00 EDT and 01:15:00 EST fall inside ["2024-11-03", "2024-11-04"), - // while the previous and next days stay cleanly outside. - let gte_day = "2024-11-03"; - let lt_day = "2024-11-04"; - let filter = build_filter_document( - SourceCollection::QmFilings, - &MongoReadSpec { - date_range: Some(MongoDateRange { - gte: Some(FilterDateValue::IsoString(gte_day.to_owned())), - lt: Some(FilterDateValue::IsoString(lt_day.to_owned())), - }), - ..MongoReadSpec::default() - }, - ) - .expect("valid Eastern calendar-day bounds for qmFilings must succeed"); - - let tf = filter - .get_document("timefiled") - .expect("timefiled range subdocument must exist"); - assert_eq!(tf.get("$gte"), Some(&Bson::String(gte_day.to_owned()))); - assert_eq!(tf.get("$lt"), Some(&Bson::String(lt_day.to_owned()))); - - let before_day = "2024-11-02T23:59:59 EDT"; - let dst_first_pass = "2024-11-03T01:30:00 EDT"; - let dst_second_pass = "2024-11-03T01:15:00 EST"; - let next_day_midnight = "2024-11-04T00:00:00 EST"; - - assert!(before_day < gte_day); - assert!(dst_first_pass >= gte_day && dst_first_pass < lt_day); - assert!(dst_second_pass >= gte_day && dst_second_pass < lt_day); - assert!(next_day_midnight >= lt_day); -} - -// --------------------------------------------------------------------------- -// 5. Password redaction (plain and percent-encoded sentinel passwords) -// --------------------------------------------------------------------------- - -#[test] -fn error_display_and_debug_never_leak_plain_or_percent_encoded_passwords() { - // Plain sentinel password - let plain_sentinel = "SENTINEL_PLAIN_PASS_998877"; - let plain_uri_str = format!( - "mongodb://studio_stock_bot_read:{plain_sentinel}@localhost:27017/stock?authSource=stock" - ); - let plain_uri = validate_uri(&plain_uri_str); - let simulated_raw = format!( - "connection failed for {plain_uri_str} (auth token {plain_sentinel}) secondary mongodb://other:{plain_sentinel}@10.0.0.51:27017/stock" - ); - let err = MongoStreamError::redacted_source(&simulated_raw, &plain_uri); - let display_out = format!("{err}"); - let debug_out = format!("{err:?}"); - assert!( - !display_out.contains(plain_sentinel), - "Display leaked plain password: {display_out}" - ); - assert!( - !debug_out.contains(plain_sentinel), - "Debug leaked plain password: {debug_out}" - ); - assert!(display_out.contains("[REDACTED]")); - assert!(debug_out.contains("[REDACTED]")); - - // Percent-encoded sentinel password (contains %40 -> @ and %21 -> !) - let encoded_sentinel = "SENTINEL%40ENC%21PASS_554433"; - let decoded_sentinel = "SENTINEL@ENC!PASS_554433"; - let enc_uri_str = format!( - "mongodb://studio_stock_bot_read:{encoded_sentinel}@localhost:27017/stock" - ); - let enc_uri = validate_uri(&enc_uri_str); - let simulated_enc_raw = format!( - "failed parsing {enc_uri_str}; raw={encoded_sentinel}; decoded={decoded_sentinel}" - ); - let sanitized = sanitize_driver_error_message(&simulated_enc_raw, &enc_uri); - assert!( - !sanitized.contains(encoded_sentinel), - "leaked encoded password: {sanitized}" - ); - assert!( - !sanitized.contains(decoded_sentinel), - "leaked decoded password: {sanitized}" - ); - assert!(sanitized.contains("[REDACTED]")); - - let enc_err = MongoStreamError::redacted_source(&simulated_enc_raw, &enc_uri); - let enc_display = format!("{enc_err}"); - let enc_debug = format!("{enc_err:?}"); - assert!(!enc_display.contains(encoded_sentinel)); - assert!(!enc_display.contains(decoded_sentinel)); - assert!(!enc_debug.contains(encoded_sentinel)); - assert!(!enc_debug.contains(decoded_sentinel)); - assert!(enc_display.contains("[REDACTED]")); -} - -#[test] -fn error_redaction_covers_distinct_secondary_uri_passwords_with_punctuation() { - let primary_uri = validate_uri( - "mongodb://studio_stock_bot_read:PRIMARY_PASS_111@localhost:27017/stock?authSource=stock", - ); - let secondary_pass_comma = "SEC_ALPHA,BETA;GAMMA)DELTA"; - let secondary_pass_srv = "SRV_PASS\"QUOTE]BRACKET@AT"; - let diagnostic = format!( - "primary timed out; fallback mongodb://secondary:{secondary_pass_comma}@10.0.0.51:27017,10.0.0.52:27017/stock, \ - and srv \"mongodb+srv://reader:{secondary_pass_srv}@cluster.internal/stock?retryReads=true\"" - ); - - let err = MongoStreamError::redacted_source(&diagnostic, &primary_uri); - let display_out = format!("{err}"); - let debug_out = format!("{err:?}"); - - for secret in [ - "PRIMARY_PASS_111", - secondary_pass_comma, - "SEC_ALPHA", - "BETA", - "GAMMA", - "DELTA", - secondary_pass_srv, - "SRV_PASS", - "QUOTE", - "BRACKET", - ] { - assert!( - !display_out.contains(secret), - "Display leaked secondary password fragment `{secret}`: {display_out}" - ); - assert!( - !debug_out.contains(secret), - "Debug leaked secondary password fragment `{secret}`: {debug_out}" - ); - } - - assert!( - display_out.contains("mongodb://secondary:[REDACTED]@10.0.0.51:27017,10.0.0.52:27017/stock"), - "unexpected redacted secondary URI in Display: {display_out}" - ); - assert!( - display_out.contains("mongodb+srv://reader:[REDACTED]@cluster.internal/stock?retryReads=true"), - "unexpected redacted srv URI in Display: {display_out}" - ); -} - -#[test] -fn error_redaction_covers_adjacent_uris_in_compact_json_list() { - let primary_uri = validate_uri( - "mongodb://studio_stock_bot_read:PRIMARY_PASS_222@localhost:27017/stock?authSource=stock", - ); - let second_pass = "ADJACENT_JSON_SECRET_999"; - let third_pass = "ADJACENT_SRV_SECRET,COMMA;SEMI"; - // Compact JSON array with no whitespace between an unauthenticated URI lacking a `/db` path - // and subsequent authenticated URIs carrying distinct passwords. - let diagnostic = format!( - r#"{{"uris":["mongodb://localhost:27017","mongodb://secondary:{second_pass}@10.0.0.51:27017/stock","mongodb+srv://reader:{third_pass}@cluster.internal"]}}"# - ); - - let err = MongoStreamError::redacted_source(&diagnostic, &primary_uri); - let display_out = format!("{err}"); - let debug_out = format!("{err:?}"); - - for secret in [ - "PRIMARY_PASS_222", - second_pass, - third_pass, - "ADJACENT_SRV_SECRET", - "COMMA", - "SEMI", - ] { - assert!( - !display_out.contains(secret), - "Display leaked adjacent JSON URI secret `{secret}`: {display_out}" - ); - assert!( - !debug_out.contains(secret), - "Debug leaked adjacent JSON URI secret `{secret}`: {debug_out}" - ); - } - - assert!( - display_out.contains( - r#"["mongodb://localhost:27017","mongodb://secondary:[REDACTED]@10.0.0.51:27017/stock","mongodb+srv://reader:[REDACTED]@cluster.internal"]"# - ), - "unexpected redacted compact JSON list in Display: {display_out}" - ); -} - -// --------------------------------------------------------------------------- -// 6. Sealed-surface source scan (zero driver paths or mutating calls) -// --------------------------------------------------------------------------- - -#[test] -fn sealed_surface_source_scan() { - let src_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("src") - .join("mongo_stream.rs"); - let raw_src = fs::read_to_string(&src_path) - .unwrap_or_else(|err| panic!("failed to read {}: {err}", src_path.display())); - - // Strip line comments (`//...`) so documentation prose does not produce false positives, - // while keeping all code lines verbatim. - let code_only: String = raw_src - .lines() - .map(|line| match line.find("//") { - Some(idx) => &line[..idx], - None => line, - }) - .collect::>() - .join("\n"); - - // Driver usage in `mongo_stream.rs` is sealed to `mongodb::sync::` read-only cursor operations. - assert!( - code_only.contains("mongodb::sync::Client") && code_only.contains("mongodb::sync::Cursor"), - "mongo_stream.rs must wire the sealed mongodb::sync driver adapter" - ); - - let forbidden_calls = [ - "insert", - "update", - "delete", - "replace", - "drop", - "aggregate", - "create_index", - "run_command", - "bulk_write", - ]; - - for word in forbidden_calls { - // Check for `.word(` or `word(` identifier calls in code. - let method_pat = format!(".{word}"); - let call_pat = format!("{word}("); - assert!( - !code_only.contains(&method_pat) && !code_only.contains(&call_pat), - "forbidden driver/mutation call `{word}` found in mongo_stream.rs" - ); - } - - // Check that no `pub` item exposes `mongodb::Client`, `Database`, or `Collection`. - let lines: Vec<&str> = code_only.lines().collect(); - for (idx, line) in lines.iter().enumerate() { - let trimmed = line.trim(); - if trimmed.starts_with("pub ") && !trimmed.starts_with("pub(crate)") { - // Gather signature up to `{` or `;` - let mut sig = String::new(); - for next_line in &lines[idx..] { - sig.push_str(next_line.trim()); - sig.push(' '); - if next_line.contains('{') || next_line.contains(';') { - break; - } - } - for forbidden_type in [ - "mongodb::Client", - "mongodb::sync::Client", - "mongodb::Database", - "mongodb::sync::Database", - "mongodb::Collection", - "mongodb::sync::Collection", - "-> Client", - "-> Database", - "-> Collection", - ] { - assert!( - !sig.contains(forbidden_type), - "public item exposes forbidden MongoDB handle `{forbidden_type}`: {sig}" - ); - } - } - } -} - -// --------------------------------------------------------------------------- -// 7. Additional edge-case coverage -// --------------------------------------------------------------------------- - -struct CountingSource { - docs: Vec>, - index: usize, - polls: usize, -} - -impl CountingSource { - fn new(docs: Vec>) -> Self { - Self { - docs, - index: 0, - polls: 0, - } - } -} - -impl RawDocumentSource for CountingSource { - fn next_raw_document(&mut self) -> Result, MongoStreamError> { - self.polls += 1; - if self.index >= self.docs.len() { - return Ok(None); - } - let doc = self.docs[self.index].as_slice(); - self.index += 1; - Ok(Some(doc)) - } -} - -#[test] -fn source_is_not_polled_again_after_eof_across_repeated_reads() { - let docs = vec![ - build_eod_doc("AAPL.US", "2024-01-02", 185.5, 1000.0), - build_eod_doc("MSFT.US", "2024-01-03", 370.0, 2000.0), - ]; - let expected = concat_docs(&docs); - let mut reader = RawBsonCursorReader::new(CountingSource::new(docs)); - - let got = read_all_with_step(&mut reader, 64).expect("initial read must succeed"); - assert_eq!(got, expected); - assert_eq!(reader.docs_read(), 2); - assert_eq!(reader.bytes_read(), expected.len() as u64); - - let mut buf = [0u8; 32]; - for _ in 0..5 { - assert_eq!( - reader.read(&mut buf).expect("post-EOF read must return Ok(0)"), - 0 - ); - } - - let inner = reader.into_inner(); - assert_eq!( - inner.polls, 3, - "source must be polled only once per doc plus one EOF poll" - ); -} - -#[test] -fn source_error_after_split_document_delivers_all_doc_bytes_then_sticky_error() { - let doc0 = build_eod_doc("AAPL.US", "2024-01-02", 185.5, 1000.0); - assert!(doc0.len() > 25, "test doc must span multiple small reads"); - let expected_err = MongoStreamError::Source { - detail: "cursor dropped after split doc".to_owned(), - }; - let source = FailingSource { - docs: vec![doc0.clone()], - index: 0, - fail_at: 1, - err: expected_err.clone(), - }; - - let mut reader = RawBsonCursorReader::new(source); - let mut received = Vec::new(); - let mut buf = [0u8; 13]; - - let first_err = loop { - match reader.read(&mut buf) { - Ok(0) => panic!("expected source error after split document, got EOF"), - Ok(n) => received.extend_from_slice(&buf[..n]), - Err(err) => break err, - } - }; - - assert_eq!(received, doc0, "all split document bytes must be delivered before error"); - assert_eq!(reader.docs_read(), 1); - assert_eq!(reader.bytes_read(), doc0.len() as u64); - - let downcast = first_err - .get_ref() - .and_then(|e| e.downcast_ref::()) - .expect("io::Error must wrap MongoStreamError"); - assert_eq!(downcast, &expected_err); - - // Subsequent reads stay sticky with the same error. - let second_err = reader - .read(&mut buf) - .expect_err("reader must remain in sticky error state"); - let downcast2 = second_err - .get_ref() - .and_then(|e| e.downcast_ref::()) - .expect("sticky io::Error must wrap MongoStreamError"); - assert_eq!(downcast2, &expected_err); -} - -#[test] -fn malformed_first_document_fails_immediately_with_zero_counts_and_stays_sticky() { - let valid_doc = build_eod_doc("AAPL.US", "2024-01-02", 100.0, 10.0); - let mut bad_first = valid_doc.clone(); - *bad_first.last_mut().unwrap() = 0x42; // missing trailing 0x00 - - let mut reader = - RawBsonCursorReader::new(VecRawDocumentSource::new(vec![bad_first, valid_doc])); - let mut buf = [0u8; 256]; - - let first_err = reader - .read(&mut buf) - .expect_err("malformed doc #0 must fail on first read"); - let first_mongo_err = first_err - .get_ref() - .and_then(|e| e.downcast_ref::()) - .expect("must downcast to MongoStreamError") - .clone(); - assert!( - matches!( - first_mongo_err, - MongoStreamError::InvalidBsonFrame { doc_index: 0, .. } - ), - "expected InvalidBsonFrame at doc_index 0, got {first_mongo_err:?}" - ); - assert_eq!(reader.docs_read(), 0); - assert_eq!(reader.bytes_read(), 0); - - for _ in 0..3 { - let sticky_err = reader - .read(&mut buf) - .expect_err("subsequent reads must stay sticky after malformed doc #0"); - let sticky_mongo_err = sticky_err - .get_ref() - .and_then(|e| e.downcast_ref::()) - .expect("sticky error must downcast to MongoStreamError"); - assert_eq!(sticky_mongo_err, &first_mongo_err); - assert_eq!(reader.docs_read(), 0); - assert_eq!(reader.bytes_read(), 0); - } -} - -#[test] -fn boundary_document_sizes_min_five_bytes_and_exact_max_doc_bytes() { - // Minimum valid 5-byte empty BSON document succeeds at max_doc_bytes == MIN_BSON_DOC_BYTES. - let empty_bson = vec![5u8, 0, 0, 0, 0]; - assert_eq!(empty_bson.len(), MIN_BSON_DOC_BYTES); - let mut min_reader = RawBsonCursorReader::with_max_doc_bytes( - VecRawDocumentSource::new(vec![empty_bson.clone()]), - MIN_BSON_DOC_BYTES, - ) - .expect("MIN_BSON_DOC_BYTES must be accepted"); - let min_out = read_all_with_step(&mut min_reader, 2).expect("5-byte doc must succeed"); - assert_eq!(min_out, empty_bson); - assert_eq!(min_reader.docs_read(), 1); - assert_eq!(min_reader.bytes_read(), MIN_BSON_DOC_BYTES as u64); - - // Exact max_doc_bytes succeeds while max_doc_bytes + 1 fails with InvalidBsonFrame. - let exact_doc = build_eod_doc("AAPL.US", "2024-01-02", 185.5, 1000.0); - let one_byte_larger = build_eod_doc("AAPLX.US", "2024-01-02", 185.5, 1000.0); - assert_eq!(one_byte_larger.len(), exact_doc.len() + 1); - let ceiling = exact_doc.len(); - - let mut exact_reader = RawBsonCursorReader::with_max_doc_bytes( - VecRawDocumentSource::new(vec![exact_doc.clone()]), - ceiling, - ) - .expect("exact ceiling must be valid"); - let exact_out = read_all_with_step(&mut exact_reader, 37).expect("exact-size doc must succeed"); - assert_eq!(exact_out, exact_doc); - assert_eq!(exact_reader.docs_read(), 1); - assert_eq!(exact_reader.bytes_read(), ceiling as u64); - - let mut over_reader = RawBsonCursorReader::with_max_doc_bytes( - VecRawDocumentSource::new(vec![one_byte_larger]), - ceiling, - ) - .expect("ceiling must be valid"); - let mut buf = [0u8; 512]; - let err = over_reader - .read(&mut buf) - .expect_err("max_doc_bytes + 1 must fail"); - let mongo_err = err - .get_ref() - .and_then(|e| e.downcast_ref::()) - .expect("must downcast to MongoStreamError"); - assert!(matches!( - mongo_err, - MongoStreamError::InvalidBsonFrame { doc_index: 0, .. } - )); - assert_eq!(over_reader.docs_read(), 0); - assert_eq!(over_reader.bytes_read(), 0); -} - -#[test] -fn large_200kib_document_parity_and_bounded_pending_capacity() { - let payload = "X".repeat(200 * 1024); - let mut large_doc = RawDocumentBuf::new(); - large_doc.append(cstr!("eodSearchCode"), "BIG.US"); - large_doc.append(cstr!("date"), "2024-08-15"); - large_doc.append(cstr!("open"), 42.0_f64); - large_doc.append(cstr!("high"), 43.0_f64); - large_doc.append(cstr!("low"), 41.0_f64); - large_doc.append(cstr!("close"), 42.5_f64); - large_doc.append(cstr!("volume"), 999.0_f64); - large_doc.append(cstr!("padding"), payload.as_str()); - let large_bytes = large_doc.into_bytes(); - assert!(large_bytes.len() > 200 * 1024); - - let small_doc = build_eod_doc("SMALL.US", "2024-08-16", 12.25, 50.0); - let docs = vec![large_bytes.clone(), small_doc]; - let concat = concat_docs(&docs); - let max_doc_len = docs.iter().map(Vec::len).max().unwrap(); - - let mut expected_rows = Vec::new(); - let expected_stats = decode_eod_price_stream( - Cursor::new(&concat), - BsonStreamOptions::default(), - |bar| { - expected_rows.push(( - bar.eod_search_code.to_owned(), - bar.session_date, - bar.close.to_bits(), - )); - }, - |offset, err| panic!("unexpected baseline error at {offset}: {err:?}"), - ) - .expect("baseline large-doc decode must succeed"); - assert_eq!(expected_rows.len(), 2); - - for step in [13usize, 37, 4099] { - let mut cursor_reader = RawBsonCursorReader::new(VecRawDocumentSource::new(docs.clone())); - let mut rows = Vec::new(); - let stats = decode_eod_price_stream( - CappedRead::new(&mut cursor_reader, step), - BsonStreamOptions::default(), - |bar| { - rows.push(( - bar.eod_search_code.to_owned(), - bar.session_date, - bar.close.to_bits(), - )); - }, - |offset, err| panic!("unexpected stream error at {offset} (step={step}): {err:?}"), - ) - .expect("large-doc stream decode must succeed"); - - assert_eq!(stats, expected_stats, "stats mismatch at step={step}"); - assert_eq!(rows, expected_rows, "rows mismatch at step={step}"); - assert_eq!(cursor_reader.docs_read(), 2); - assert_eq!(cursor_reader.bytes_read(), concat.len() as u64); - assert!( - cursor_reader.pending_capacity() <= max_doc_len, - "pending_capacity ({}) exceeded single large doc length ({max_doc_len}) at step={step}", - cursor_reader.pending_capacity() - ); - } -} - -#[test] -fn read_spec_validate_accepts_all_boundary_limits() { - let min_spec = MongoReadSpec { - batch_size: 1, - limit: Some(1), - max_doc_bytes: MIN_BSON_DOC_BYTES, - ..MongoReadSpec::default() - }; - min_spec - .validate(SourceCollection::EodPrices) - .expect("min boundary spec must validate"); - assert!( - build_filter_document(SourceCollection::EodPrices, &min_spec) - .expect("min boundary filter must succeed") - .is_empty() - ); - - let max_spec = MongoReadSpec { - batch_size: MAX_MONGO_BATCH_SIZE, - limit: Some(i64::MAX as u64), - max_doc_bytes: MIN_BSON_DOC_BYTES, - ..MongoReadSpec::default() - }; - max_spec - .validate(SourceCollection::EodPrices) - .expect("max boundary spec must validate"); - assert!( - build_filter_document(SourceCollection::EodPrices, &max_spec) - .expect("max boundary filter must succeed") - .is_empty() - ); -} - -#[test] -fn one_sided_date_range_bounds_and_equal_bound_rejection() { - // ISO string: gte-only - let iso_gte = build_filter_document( - SourceCollection::EodPrices, - &MongoReadSpec { - date_range: Some(MongoDateRange { - gte: Some(FilterDateValue::IsoString("2024-01-01".to_owned())), - lt: None, - }), - ..MongoReadSpec::default() - }, - ) - .expect("ISO gte-only must succeed"); - let sub = iso_gte.get_document("date").unwrap(); - assert_eq!(sub.get("$gte"), Some(&Bson::String("2024-01-01".to_owned()))); - assert_eq!(sub.get("$lt"), None); - - // ISO string: lt-only - let iso_lt = build_filter_document( - SourceCollection::EodPrices, - &MongoReadSpec { - date_range: Some(MongoDateRange { - gte: None, - lt: Some(FilterDateValue::IsoString("2025-01-01".to_owned())), - }), - ..MongoReadSpec::default() - }, - ) - .expect("ISO lt-only must succeed"); - let sub = iso_lt.get_document("date").unwrap(); - assert_eq!(sub.get("$gte"), None); - assert_eq!(sub.get("$lt"), Some(&Bson::String("2025-01-01".to_owned()))); - - // BSON DateTime millis: gte-only - let dt_gte = build_filter_document( - SourceCollection::CeoShorts, - &MongoReadSpec { - date_range: Some(MongoDateRange { - gte: Some(FilterDateValue::BsonDateTimeMillis(1_704_067_200_000)), - lt: None, - }), - ..MongoReadSpec::default() - }, - ) - .expect("DateTime gte-only must succeed"); - let sub = dt_gte.get_document("timestamp").unwrap(); - assert_eq!( - sub.get("$gte"), - Some(&Bson::DateTime(DateTime::from_millis(1_704_067_200_000))) - ); - assert_eq!(sub.get("$lt"), None); - - // BSON DateTime millis: lt-only - let dt_lt = build_filter_document( - SourceCollection::CeoShorts, - &MongoReadSpec { - date_range: Some(MongoDateRange { - gte: None, - lt: Some(FilterDateValue::BsonDateTimeMillis(1_735_689_600_000)), - }), - ..MongoReadSpec::default() - }, - ) - .expect("DateTime lt-only must succeed"); - let sub = dt_lt.get_document("timestamp").unwrap(); - assert_eq!(sub.get("$gte"), None); - assert_eq!( - sub.get("$lt"), - Some(&Bson::DateTime(DateTime::from_millis(1_735_689_600_000))) - ); - - // Equal bounds (gte == lt) must be rejected for both variants. - assert!(matches!( - build_filter_document( - SourceCollection::EodPrices, - &MongoReadSpec { - date_range: Some(MongoDateRange { - gte: Some(FilterDateValue::IsoString("2024-06-01".to_owned())), - lt: Some(FilterDateValue::IsoString("2024-06-01".to_owned())), - }), - ..MongoReadSpec::default() - } - ), - Err(MongoStreamError::InvalidDateRange { - collection: SourceCollection::EodPrices, - .. - }) - )); - assert!(matches!( - build_filter_document( - SourceCollection::CeoShorts, - &MongoReadSpec { - date_range: Some(MongoDateRange { - gte: Some(FilterDateValue::BsonDateTimeMillis(1_704_067_200_000)), - lt: Some(FilterDateValue::BsonDateTimeMillis(1_704_067_200_000)), - }), - ..MongoReadSpec::default() - } - ), - Err(MongoStreamError::InvalidDateRange { - collection: SourceCollection::CeoShorts, - .. - }) - )); -} - -#[test] -fn qm_filings_rejects_invalid_eastern_calendar_day_bounds() { - let invalid_days = [ - "2023-02-29", // non-leap year Feb 29 - "2024-13-01", // month > 12 - "2024-00-10", // month == 0 - "2024-01-00", // day == 0 - "2024-04-31", // April has 30 days - "2024-01-01 ", // trailing space - "2024-01-01Z", // trailing UTC marker - "2024-01-0é", // non-ASCII byte - "2024-01-01", // fullwidth digits (non-ASCII) - ]; - - for bad in invalid_days { - assert!( - matches!( - build_filter_document( - SourceCollection::QmFilings, - &MongoReadSpec { - date_range: Some(MongoDateRange { - gte: Some(FilterDateValue::IsoString(bad.to_owned())), - lt: None, - }), - ..MongoReadSpec::default() - } - ), - Err(MongoStreamError::InvalidDateRange { - collection: SourceCollection::QmFilings, - .. - }) - ), - "expected gte={bad:?} to be rejected for qmFilings" - ); - assert!( - matches!( - build_filter_document( - SourceCollection::QmFilings, - &MongoReadSpec { - date_range: Some(MongoDateRange { - gte: None, - lt: Some(FilterDateValue::IsoString(bad.to_owned())), - }), - ..MongoReadSpec::default() - } - ), - Err(MongoStreamError::InvalidDateRange { - collection: SourceCollection::QmFilings, - .. - }) - ), - "expected lt={bad:?} to be rejected for qmFilings" - ); - } - - // Leap-year Feb 29 is valid. - build_filter_document( - SourceCollection::QmFilings, - &MongoReadSpec { - date_range: Some(MongoDateRange { - gte: Some(FilterDateValue::IsoString("2024-02-29".to_owned())), - lt: Some(FilterDateValue::IsoString("2024-03-01".to_owned())), - }), - ..MongoReadSpec::default() - }, - ) - .expect("valid leap-year calendar day 2024-02-29 must succeed"); -} - -#[test] -fn source_collection_exhaustive_key_date_and_display_mappings() { - let expected: [(SourceCollection, &str, &str, Option<&str>); 8] = [ - ( - SourceCollection::EodPrices, - "eodPrices", - "eodSearchCode", - Some("date"), - ), - ( - SourceCollection::QmSplits, - "qmSplits", - "qmSearchCode", - Some("date"), - ), - ( - SourceCollection::QmDividends, - "qmDividends", - "qmSearchCode", - Some("date"), - ), - ( - SourceCollection::QmPrices, - "qmPrices", - "qmSearchCode", - Some("date"), - ), - ( - SourceCollection::TeMarketData, - "teMarketData", - "teSymbol", - None, - ), - ( - SourceCollection::CeoShorts, - "ceoShorts", - "symbol", - Some("timestamp"), - ), - ( - SourceCollection::QmFilings, - "qmFilings", - "symbol", - Some("timefiled"), - ), - ( - SourceCollection::QmEarnings, - "qmEarnings", - "qmSearchCode", - Some("reportDate"), - ), - ]; - - assert_eq!(SourceCollection::ALL.len(), expected.len()); - for (actual, (exp_variant, exp_name, exp_key, exp_date)) in - SourceCollection::ALL.into_iter().zip(expected) - { - assert_eq!(actual, exp_variant); - assert_eq!(actual.as_str(), exp_name); - assert_eq!(format!("{actual}"), exp_name); - assert_eq!(actual.key_field(), exp_key); - assert_eq!(actual.date_field(), exp_date); - } -} - -#[test] -fn error_redaction_handles_uppercase_and_mixed_case_mongo_schemes() { - let primary_uri = validate_uri( - "mongodb://studio_stock_bot_read:PRIMARY_CASE_PASS@localhost:27017/stock?authSource=stock", - ); - let upper_secret = "UPPER_SCHEME_SECRET_777"; - let mixed_secret = "MIXED_SRV_SECRET_888"; - let diagnostic = format!( - "tried MONGODB://reader:{upper_secret}@10.0.0.51:27017/stock then MongoDB+SRV://srvuser:{mixed_secret}@cluster.internal/stock" - ); - - let err = MongoStreamError::redacted_source(&diagnostic, &primary_uri); - let display_out = format!("{err}"); - let debug_out = format!("{err:?}"); - - for secret in ["PRIMARY_CASE_PASS", upper_secret, mixed_secret] { - assert!( - !display_out.contains(secret), - "Display leaked `{secret}` under uppercase/mixed-case scheme: {display_out}" - ); - assert!( - !debug_out.contains(secret), - "Debug leaked `{secret}` under uppercase/mixed-case scheme: {debug_out}" - ); - } - assert!( - display_out.contains("[REDACTED]@10.0.0.51:27017/stock"), - "expected redacted MONGODB:// URI in Display: {display_out}" - ); - assert!( - display_out.contains("[REDACTED]@cluster.internal/stock"), - "expected redacted MongoDB+SRV:// URI in Display: {display_out}" - ); - assert!(debug_out.contains("[REDACTED]")); -} - -#[test] -fn error_redaction_scrubs_repeated_password_occurrences_across_message() { - let repeated_pass = "REPEATED_SENTINEL_PASS_4242"; - let primary_uri_str = format!( - "mongodb://studio_stock_bot_read:{repeated_pass}@localhost:27017/stock?authSource=stock" - ); - let primary_uri = validate_uri(&primary_uri_str); - let diagnostic = format!( - "attempt1={primary_uri_str}; raw1={repeated_pass}; fallback=mongodb://alt:{repeated_pass}@10.0.0.51:27017/stock; raw2={repeated_pass}; attempt2={primary_uri_str}" - ); - - let err = MongoStreamError::redacted_source(&diagnostic, &primary_uri); - let display_out = format!("{err}"); - let debug_out = format!("{err:?}"); - - assert!( - !display_out.contains(repeated_pass), - "Display leaked repeated password: {display_out}" - ); - assert!( - !debug_out.contains(repeated_pass), - "Debug leaked repeated password: {debug_out}" - ); - assert!( - display_out.matches("[REDACTED]").count() >= 5, - "expected every occurrence to be redacted in Display: {display_out}" - ); - assert!( - debug_out.matches("[REDACTED]").count() >= 5, - "expected every occurrence to be redacted in Debug: {debug_out}" - ); -} - -#[test] -fn cli_to_read_spec_for_collection_uses_bson_datetime_for_qm_earnings_and_iso_string_for_filings() { - let opts = super::MongoCliOptions { - date_gte: Some("2017-01-01".to_owned()), - date_lt: Some("2025-02-13".to_owned()), - ..super::MongoCliOptions::default() - }; - - let filings_spec = opts.to_read_spec_for_collection(SourceCollection::QmFilings, None, true); - let filings_doc = build_filter_document(SourceCollection::QmFilings, &filings_spec) - .expect("qmFilings string filter must succeed"); - let tf = filings_doc - .get_document("timefiled") - .expect("timefiled subdocument"); - assert_eq!(tf.get("$gte"), Some(&Bson::String("2017-01-01".to_owned()))); - assert_eq!(tf.get("$lt"), Some(&Bson::String("2025-02-13".to_owned()))); - - let earnings_spec = opts.to_read_spec_for_collection(SourceCollection::QmEarnings, None, true); - let earnings_doc = build_filter_document(SourceCollection::QmEarnings, &earnings_spec) - .expect("qmEarnings DateTime filter must succeed"); - let rd = earnings_doc - .get_document("reportDate") - .expect("reportDate subdocument"); - // 2017-01-01T00:00:00Z = 1483228800000 ms; 2025-02-13T00:00:00Z = 1739404800000 ms - assert_eq!( - rd.get("$gte"), - Some(&Bson::DateTime(DateTime::from_millis(1_483_228_800_000))) - ); - assert_eq!( - rd.get("$lt"), - Some(&Bson::DateTime(DateTime::from_millis(1_739_404_800_000))) - ); -} diff --git a/tools/curate-etl/src/parquet_bars.rs b/tools/curate-etl/src/parquet_bars.rs index ebfa4643..5367748e 100644 --- a/tools/curate-etl/src/parquet_bars.rs +++ b/tools/curate-etl/src/parquet_bars.rs @@ -16,7 +16,6 @@ //! 11. `source` (`BYTE_ARRAY`, `REQUIRED`, `STRING`) //! 12. `known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`) -use std::any::Any; use std::borrow::{Borrow, Cow}; use std::cmp::Ordering; use std::collections::BTreeMap; @@ -24,10 +23,8 @@ use std::error::Error; use std::fmt; use std::fs::{self, File}; use std::io::{self, BufWriter, Write}; -use std::num::NonZeroUsize; -use std::panic::{catch_unwind, AssertUnwindSafe}; use std::path::{Path, PathBuf}; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; use std::time::Duration; use parquet::basic::{Compression, LogicalType, Repetition, TimeUnit, Type as PhysicalType, ZstdLevel}; @@ -36,7 +33,6 @@ use parquet::errors::ParquetError; use parquet::file::properties::{WriterProperties, WriterPropertiesPtr}; use parquet::file::writer::SerializedFileWriter; use parquet::schema::types::{ColumnPath, Type, TypePtr}; -use rayon::prelude::*; use crate::parquet_publish::{ cleanup_owned_files, create_backup_preserving_live, create_exclusive_tmp_file, dataset_mutex, @@ -53,18 +49,6 @@ pub const MIN_PARQUET_YEAR: i32 = 1900; /// Maximum allowed calendar year for `session_date` partitioning. pub const MAX_PARQUET_YEAR: i32 = 2200; -/// Default worker thread count for [`Bars1dWriteOptions::default`] (`1` keeps bounded streaming -/// memory for library callers). -pub const DEFAULT_WRITE_THREADS: usize = 1; - -/// Default parallel worker thread count (`std::thread::available_parallelism()`, falling back to -/// `1` if unavailable). -pub fn default_parallel_threads() -> usize { - std::thread::available_parallelism() - .map(NonZeroUsize::get) - .unwrap_or(1) -} - /// Single `bars_1d` row matching the `design/DATA-CONTRACTS.md` Parquet schema. #[derive(Debug, Clone, PartialEq)] pub struct Bars1dParquetRow { @@ -87,7 +71,6 @@ pub struct Bars1dParquetRow { pub struct Bars1dWriteOptions { pub row_group_rows: usize, pub zstd_level: i32, - pub threads: usize, } impl Default for Bars1dWriteOptions { @@ -95,7 +78,6 @@ impl Default for Bars1dWriteOptions { Self { row_group_rows: DEFAULT_ROW_GROUP_ROWS, zstd_level: DEFAULT_ZSTD_LEVEL, - threads: DEFAULT_WRITE_THREADS, } } } @@ -117,15 +99,6 @@ pub enum ParquetBarsError { InvalidZstdLevel { level: i32, }, - InvalidThreads, - ThreadPoolBuild { - threads: usize, - detail: String, - }, - WorkerPanicked { - year: i32, - detail: String, - }, UnsortedInput { prev_listing_id: i32, prev_session_date: i32, @@ -170,16 +143,6 @@ impl fmt::Display for ParquetBarsError { Self::InvalidZstdLevel { level } => { write!(f, "invalid Zstd compression level: {level}") } - Self::InvalidThreads => { - write!(f, "invalid threads: must be greater than 0") - } - Self::ThreadPoolBuild { threads, detail } => write!( - f, - "failed to build rayon thread pool with {threads} thread(s): {detail}" - ), - Self::WorkerPanicked { year, detail } => { - write!(f, "worker panicked while encoding year={year:04}: {detail}") - } Self::UnsortedInput { prev_listing_id, prev_session_date, @@ -428,22 +391,6 @@ impl YearWriter { props: &WriterPropertiesPtr, owned_tmp_paths: &mut Vec, ) -> Result { - Self::open_with_tmp_recorder(bars_dir, year, run_id, schema, props, |tmp_path| { - owned_tmp_paths.push(tmp_path); - }) - } - - fn open_with_tmp_recorder( - bars_dir: &Path, - year: i32, - run_id: &str, - schema: &TypePtr, - props: &WriterPropertiesPtr, - mut record_tmp: F, - ) -> Result - where - F: FnMut(PathBuf), - { let year_dir = bars_dir.join(format!("year={year:04}")); fs::create_dir_all(&year_dir).map_err(|source| ParquetBarsError::Io { path: year_dir.clone(), @@ -451,7 +398,7 @@ impl YearWriter { })?; let (tmp_path, file) = create_exclusive_tmp_file(&year_dir, run_id)?; - record_tmp(tmp_path.clone()); + owned_tmp_paths.push(tmp_path.clone()); let final_path = year_dir.join("part.parquet"); let buf_writer = BufWriter::with_capacity(FILE_BUF_CAPACITY_BYTES, file); @@ -640,52 +587,17 @@ where ) } -fn format_panic_payload(payload: Box) -> String { - if let Some(s) = payload.downcast_ref::<&str>() { - (*s).to_string() - } else if let Some(s) = payload.downcast_ref::() { - s.clone() - } else { - "unknown panic payload".to_string() - } -} - fn write_bars_1d_dataset_with_hooks( out_dir: P, rows: I, options: Bars1dWriteOptions, lock_timeout: Duration, - on_after_backup: F, -) -> Result -where - P: AsRef, - I: IntoIterator, - R: Borrow, - F: FnMut(i32, &Path, Option<&Path>), -{ - write_bars_1d_dataset_internal( - out_dir, - rows, - options, - lock_timeout, - |_, _| Ok(()), - on_after_backup, - ) -} - -fn write_bars_1d_dataset_internal( - out_dir: P, - rows: I, - options: Bars1dWriteOptions, - lock_timeout: Duration, - on_stage_year: S, mut on_after_backup: F, ) -> Result where P: AsRef, I: IntoIterator, R: Borrow, - S: Fn(i32, &Path) -> Result<(), ParquetBarsError> + Sync, F: FnMut(i32, &Path, Option<&Path>), { if options.row_group_rows == 0 { @@ -696,9 +608,6 @@ where level: options.zstd_level, } })?; - if options.threads == 0 { - return Err(ParquetBarsError::InvalidThreads); - } let mut row_iter = rows.into_iter(); let Some(first_item) = row_iter.next() else { @@ -739,229 +648,86 @@ where let _file_lock = DatasetFileLock::acquire_with_timeout(&bars_dir, lock_timeout)?; let run_id = next_run_id(); + let mut writers: BTreeMap = BTreeMap::new(); + let mut owned_tmp_paths: Vec = Vec::new(); + let mut scratch: Vec = Vec::with_capacity(STRING_WRITE_BATCH_ROWS); - let (synced_files, owned_tmp_paths) = if options.threads == 1 { - let mut owned_tmp_paths: Vec = Vec::new(); - let mut writers: BTreeMap = BTreeMap::new(); - let mut scratch: Vec = Vec::with_capacity(STRING_WRITE_BATCH_ROWS); + let write_result: Result, ParquetBarsError> = (|| { + let mut prev_key: Option<(i32, i32)> = None; - let write_result: Result, ParquetBarsError> = (|| { - let mut prev_key: Option<(i32, i32)> = None; - - for item in std::iter::once(first_item).chain(row_iter) { - let row = item.borrow(); - if let Some((prev_listing_id, prev_session_date)) = prev_key { - match (row.listing_id, row.session_date) - .cmp(&(prev_listing_id, prev_session_date)) - { - Ordering::Equal => { - return Err(ParquetBarsError::DuplicateKey { - listing_id: row.listing_id, - session_date: row.session_date, - }); - } - Ordering::Less => { - return Err(ParquetBarsError::UnsortedInput { - prev_listing_id, - prev_session_date, - listing_id: row.listing_id, - session_date: row.session_date, - }); - } - Ordering::Greater => {} - } - } - prev_key = Some((row.listing_id, row.session_date)); - - let (year, _, _) = epoch_days_to_ymd(row.session_date); - if !(MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR).contains(&year) { - return Err(ParquetBarsError::SessionYearOutOfRange { - listing_id: row.listing_id, - session_date: row.session_date, - year, - min_year: MIN_PARQUET_YEAR, - max_year: MAX_PARQUET_YEAR, - }); - } - - let yw = match writers.entry(year) { - std::collections::btree_map::Entry::Occupied(entry) => entry.into_mut(), - std::collections::btree_map::Entry::Vacant(entry) => { - let opened = YearWriter::open( - &bars_dir, - year, - &run_id, - &schema, - &props, - &mut owned_tmp_paths, - )?; - entry.insert(opened) - } - }; - - yw.buf.push(row); - if yw.buf.len() == options.row_group_rows { - yw.flush_row_group(&mut scratch)?; - } - } - - let mut synced = Vec::with_capacity(writers.len()); - let drained: Vec<(i32, YearWriter)> = std::mem::take(&mut writers).into_iter().collect(); - for (year, yw) in drained { - on_stage_year(year, &yw.tmp_path)?; - let file = yw.finish_and_sync(&mut scratch)?; - synced.push((year, file)); - } - Ok(synced) - })(); - - match write_result { - Ok(files) => (files, owned_tmp_paths), - Err(err) => { - // Drop all open writers before unlinking temporary files owned by this run. - drop(writers); - cleanup_owned_files(&owned_tmp_paths); - return Err(err); - } - } - } else { - // Pass 1: single sequential global validation pass enforcing exact error precedence while - // bucketing rows by year in preserved order. - let mut buckets: BTreeMap> = BTreeMap::new(); - { - let mut prev_key: Option<(i32, i32)> = None; - for item in std::iter::once(first_item).chain(row_iter) { - let row = item.borrow(); - if let Some((prev_listing_id, prev_session_date)) = prev_key { - match (row.listing_id, row.session_date) - .cmp(&(prev_listing_id, prev_session_date)) - { - Ordering::Equal => { - return Err(ParquetBarsError::DuplicateKey { - listing_id: row.listing_id, - session_date: row.session_date, - }); - } - Ordering::Less => { - return Err(ParquetBarsError::UnsortedInput { - prev_listing_id, - prev_session_date, - listing_id: row.listing_id, - session_date: row.session_date, - }); - } - Ordering::Greater => {} - } - } - prev_key = Some((row.listing_id, row.session_date)); - - let (year, _, _) = epoch_days_to_ymd(row.session_date); - if !(MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR).contains(&year) { - return Err(ParquetBarsError::SessionYearOutOfRange { - listing_id: row.listing_id, - session_date: row.session_date, - year, - min_year: MIN_PARQUET_YEAR, - max_year: MAX_PARQUET_YEAR, - }); - } - - buckets.entry(year).or_default().push(row.clone()); - } - } - - // Schedule largest years first for load balance; tie-break by ascending year. - let mut work_items: Vec<(i32, Vec)> = buckets.into_iter().collect(); - work_items.sort_unstable_by(|(year_a, rows_a), (year_b, rows_b)| { - rows_b.len().cmp(&rows_a.len()).then_with(|| year_a.cmp(year_b)) - }); - - let pool_threads = options.threads.clamp(1, work_items.len().max(1)); - let pool = rayon::ThreadPoolBuilder::new() - .num_threads(pool_threads) - .build() - .map_err(|err| ParquetBarsError::ThreadPoolBuild { - threads: pool_threads, - detail: err.to_string(), - })?; - - let shared_tmp_paths: Mutex> = Mutex::new(Vec::with_capacity(work_items.len())); - let bars_dir_ref = bars_dir.as_path(); - let run_id_ref = run_id.as_str(); - let schema_ref = &schema; - let props_ref = &props; - let on_stage_ref = &on_stage_year; - let shared_tmp_ref = &shared_tmp_paths; - let row_group_rows = options.row_group_rows; - - let mut outcomes: Vec<(i32, Result)> = - pool.install(|| { - work_items - .into_par_iter() - .map(|(year, year_rows)| { - let res = catch_unwind(AssertUnwindSafe(|| { - let mut yw = YearWriter::open_with_tmp_recorder( - bars_dir_ref, - year, - run_id_ref, - schema_ref, - props_ref, - |tmp_path| { - shared_tmp_ref - .lock() - .unwrap_or_else(|err| err.into_inner()) - .push(tmp_path); - }, - )?; - let mut scratch: Vec = - Vec::with_capacity(STRING_WRITE_BATCH_ROWS); - for row in &year_rows { - yw.buf.push(row); - if yw.buf.len() == row_group_rows { - yw.flush_row_group(&mut scratch)?; - } - } - drop(year_rows); - on_stage_ref(year, &yw.tmp_path)?; - yw.finish_and_sync(&mut scratch) - })) - .unwrap_or_else(|payload| { - Err(ParquetBarsError::WorkerPanicked { - year, - detail: format_panic_payload(payload), - }) + for item in std::iter::once(first_item).chain(row_iter) { + let row = item.borrow(); + if let Some((prev_listing_id, prev_session_date)) = prev_key { + match (row.listing_id, row.session_date).cmp(&(prev_listing_id, prev_session_date)) + { + Ordering::Equal => { + return Err(ParquetBarsError::DuplicateKey { + listing_id: row.listing_id, + session_date: row.session_date, }); - (year, res) - }) - .collect() - }); - - let owned_tmp_paths = shared_tmp_paths - .into_inner() - .unwrap_or_else(|err| err.into_inner()); - outcomes.sort_unstable_by_key(|(year, _)| *year); - - let mut synced = Vec::with_capacity(outcomes.len()); - let mut first_err: Option = None; - for (year, res) in outcomes { - match res { - Ok(file) => { - if first_err.is_none() { - synced.push((year, file)); } - } - Err(err) => { - if first_err.is_none() { - first_err = Some(err); + Ordering::Less => { + return Err(ParquetBarsError::UnsortedInput { + prev_listing_id, + prev_session_date, + listing_id: row.listing_id, + session_date: row.session_date, + }); } + Ordering::Greater => {} } } + prev_key = Some((row.listing_id, row.session_date)); + + let (year, _, _) = epoch_days_to_ymd(row.session_date); + if !(MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR).contains(&year) { + return Err(ParquetBarsError::SessionYearOutOfRange { + listing_id: row.listing_id, + session_date: row.session_date, + year, + min_year: MIN_PARQUET_YEAR, + max_year: MAX_PARQUET_YEAR, + }); + } + + let yw = match writers.entry(year) { + std::collections::btree_map::Entry::Occupied(entry) => entry.into_mut(), + std::collections::btree_map::Entry::Vacant(entry) => { + let opened = YearWriter::open( + &bars_dir, + year, + &run_id, + &schema, + &props, + &mut owned_tmp_paths, + )?; + entry.insert(opened) + } + }; + + yw.buf.push(row); + if yw.buf.len() == options.row_group_rows { + yw.flush_row_group(&mut scratch)?; + } } - if let Some(err) = first_err { + + let mut synced = Vec::with_capacity(writers.len()); + let drained: Vec<(i32, YearWriter)> = std::mem::take(&mut writers).into_iter().collect(); + for (year, yw) in drained { + let file = yw.finish_and_sync(&mut scratch)?; + synced.push((year, file)); + } + Ok(synced) + })(); + + let synced_files = match write_result { + Ok(files) => files, + Err(err) => { + // Drop all open writers before unlinking temporary files owned by this run. + drop(writers); cleanup_owned_files(&owned_tmp_paths); return Err(err); } - (synced, owned_tmp_paths) }; let mut stats = Bars1dWriteStats::default(); @@ -1496,7 +1262,6 @@ mod tests { let options = Bars1dWriteOptions { row_group_rows: 1_000, zstd_level: DEFAULT_ZSTD_LEVEL, - ..Bars1dWriteOptions::default() }; let stats = write_bars_1d_dataset(tmp.path(), &rows, options).unwrap(); assert_eq!(stats.rows_written, 2_500); @@ -1577,7 +1342,6 @@ mod tests { Bars1dWriteOptions { row_group_rows: 0, zstd_level: DEFAULT_ZSTD_LEVEL, - ..Bars1dWriteOptions::default() }, ) .unwrap_err(); @@ -1592,7 +1356,6 @@ mod tests { Bars1dWriteOptions { row_group_rows: 100, zstd_level: 99, - ..Bars1dWriteOptions::default() }, ) .unwrap_err(); @@ -1703,7 +1466,6 @@ mod tests { Bars1dWriteOptions { row_group_rows: 2, zstd_level: DEFAULT_ZSTD_LEVEL, - ..Bars1dWriteOptions::default() }, ) .unwrap_err(); diff --git a/tools/curate-etl/src/parquet_bars_tests.rs b/tools/curate-etl/src/parquet_bars_tests.rs index 84ad961d..53c42789 100644 --- a/tools/curate-etl/src/parquet_bars_tests.rs +++ b/tools/curate-etl/src/parquet_bars_tests.rs @@ -1,7 +1,5 @@ use std::borrow::Cow; -use std::error::Error as _; use std::fs::{self, File}; -use std::io; use std::time::Duration; use parquet::basic::Encoding; @@ -11,10 +9,9 @@ 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_internal, write_bars_1d_dataset_with_hooks, - Bars1dParquetRow, Bars1dWriteOptions, ParquetBarsError, MAX_PARQUET_YEAR, MIN_PARQUET_YEAR, + write_bars_1d_dataset, write_bars_1d_dataset_with_hooks, Bars1dParquetRow, Bars1dWriteOptions, + ParquetBarsError, MAX_PARQUET_YEAR, MIN_PARQUET_YEAR, }; -use crate::parquet_publish::DEFAULT_LOCK_TIMEOUT; use crate::split::ymd_to_epoch_days; #[test] @@ -887,406 +884,3 @@ fn active_external_write_lock_times_out_without_deleting_lock_or_modifying_exist assert_eq!(fs::read(&lock_path).unwrap(), lock_contents); assert_eq!(fs::read(&path_2024).unwrap(), orig_2024_bytes); } - -fn splitmix64_next(state: &mut u64) -> u64 { - *state = state.wrapping_add(0x9E37_79B9_7F4A_7C15); - let mut z = *state; - z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); - z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); - z ^ (z >> 31) -} - -#[test] -fn parallel_write_multi_year_200k_rows_is_byte_identical_across_thread_counts() { - // 20 years (2006..=2025) x 100 listings x 100 sessions/year = 200,000 rows. - // row_group_rows = 3_500 -> 3 row groups per year (60 row groups total). - let mut rng: u64 = 0x570C_4B07_0012_0001; - let mut rows = Vec::with_capacity(200_000); - for listing_id in 1..=100_i32 { - let currency = if listing_id % 3 == 0 { "CAD" } else { "USD" }; - for year in 2006..=2025_i32 { - let jan1 = ymd_to_epoch_days(year, 1, 1).unwrap(); - for offset in 0..100_i32 { - let session_date = jan1 + offset * 3; - let r = splitmix64_next(&mut rng); - let close = 5.0 + ((r & 0xFFFF) as f64) * 0.01; - let volume = 1_000.0 + (((r >> 16) & 0xFFFF) as f64) * 10.0; - let vwap = if (r >> 32) & 3 == 0 { - None - } else { - Some(close - 0.125) - }; - let ts_micros = i64::from(session_date) * 86_400_000_000 + 21 * 3_600_000_000; - rows.push(Bars1dParquetRow { - listing_id, - ts_micros, - session_date, - open: close - 0.5, - high: close + 1.0, - low: close - 0.75, - close, - volume, - vwap, - currency: Cow::Borrowed(currency), - source: Cow::Borrowed("eod_unadj"), - known_at_micros: ts_micros, - }); - } - } - } - assert_eq!(rows.len(), 200_000); - - let dir_1 = TempDirGuard::new("par-parity-t1"); - let dir_2 = TempDirGuard::new("par-parity-t2"); - let dir_8 = TempDirGuard::new("par-parity-t8"); - - let opts = |threads| Bars1dWriteOptions { - row_group_rows: 3_500, - threads, - ..Bars1dWriteOptions::default() - }; - - let stats_1 = write_bars_1d_dataset(dir_1.path(), &rows, opts(1)).unwrap(); - let stats_2 = write_bars_1d_dataset(dir_2.path(), &rows, opts(2)).unwrap(); - let stats_8 = write_bars_1d_dataset(dir_8.path(), &rows, opts(8)).unwrap(); - - assert_eq!(stats_1.rows_written, 200_000); - assert_eq!(stats_1.files_written, 20); - assert_eq!(stats_1.row_groups_written, 60); - assert_eq!(stats_1, stats_2); - assert_eq!(stats_1, stats_8); - - for year in 2006..=2025_i32 { - let rel = format!("bars_1d/year={year:04}/part.parquet"); - let b1 = fs::read(dir_1.path().join(&rel)).unwrap(); - let b2 = fs::read(dir_2.path().join(&rel)).unwrap(); - let b8 = fs::read(dir_8.path().join(&rel)).unwrap(); - assert_eq!(b1, b2, "threads=1 vs threads=2 diverged for {rel}"); - assert_eq!(b1, b8, "threads=1 vs threads=8 diverged for {rel}"); - } - - assert_no_transient_files(&dir_1.path().join("bars_1d")); - assert_no_transient_files(&dir_2.path().join("bars_1d")); - assert_no_transient_files(&dir_8.path().join("bars_1d")); -} - -fn assert_no_parquet_or_tmp_under(root: &std::path::Path) { - if !root.exists() { - return; - } - let mut stack = vec![root.to_path_buf()]; - while let Some(dir) = stack.pop() { - for entry in fs::read_dir(&dir).unwrap() { - let entry = entry.unwrap(); - let path = entry.path(); - if path.is_dir() { - stack.push(path); - } else { - let name = entry.file_name().to_string_lossy().into_owned(); - assert!( - name != "part.parquet" - && !name.ends_with(".tmp") - && !name.ends_with(".bak") - && name != ".write.lock", - "unexpected leftover file '{}'", - path.display() - ); - } - } - } -} - -#[test] -fn parallel_write_error_parity_and_clean_directory() { - let valid_row = make_row(1, 2024, 1, 2, 10.0, 100.0, None, "USD", "eod_unadj"); - let opts_par = |row_group_rows, zstd_level, threads| Bars1dWriteOptions { - row_group_rows, - zstd_level, - threads, - }; - - // 1. InvalidRowGroupRows - { - let d_seq = TempDirGuard::new("par-err-rg-seq"); - let d_par = TempDirGuard::new("par-err-rg-par"); - let e1 = write_bars_1d_dataset( - d_seq.path(), - std::slice::from_ref(&valid_row), - opts_par(0, 3, 1), - ) - .unwrap_err(); - let e4 = write_bars_1d_dataset( - d_par.path(), - std::slice::from_ref(&valid_row), - opts_par(0, 3, 4), - ) - .unwrap_err(); - assert!(matches!(e1, ParquetBarsError::InvalidRowGroupRows)); - assert!(matches!(e4, ParquetBarsError::InvalidRowGroupRows)); - assert_no_parquet_or_tmp_under(d_par.path()); - } - - // 2. InvalidZstdLevel - { - let d_seq = TempDirGuard::new("par-err-zstd-seq"); - let d_par = TempDirGuard::new("par-err-zstd-par"); - let e1 = write_bars_1d_dataset( - d_seq.path(), - std::slice::from_ref(&valid_row), - opts_par(100, 99, 1), - ) - .unwrap_err(); - let e4 = write_bars_1d_dataset( - d_par.path(), - std::slice::from_ref(&valid_row), - opts_par(100, 99, 4), - ) - .unwrap_err(); - assert!(matches!( - e1, - ParquetBarsError::InvalidZstdLevel { level: 99 } - )); - assert!(matches!( - e4, - ParquetBarsError::InvalidZstdLevel { level: 99 } - )); - assert_no_parquet_or_tmp_under(d_par.path()); - } - - // 3. InvalidThreads (threads = 0) - { - let d_zero = TempDirGuard::new("par-err-threads-0"); - let err = write_bars_1d_dataset( - d_zero.path(), - std::slice::from_ref(&valid_row), - opts_par(100, 3, 0), - ) - .unwrap_err(); - assert!(matches!(err, ParquetBarsError::InvalidThreads)); - assert!(err.to_string().contains("threads")); - assert!(err.source().is_none()); - assert_no_parquet_or_tmp_under(d_zero.path()); - } - - // 4. UnsortedInput - { - let rows = vec![ - make_row(1, 2024, 1, 5, 10.0, 100.0, None, "USD", "eod_unadj"), - make_row(1, 2024, 1, 4, 10.0, 100.0, None, "USD", "eod_unadj"), - ]; - let d_seq = TempDirGuard::new("par-err-unsorted-seq"); - let d_par = TempDirGuard::new("par-err-unsorted-par"); - let e1 = write_bars_1d_dataset(d_seq.path(), &rows, opts_par(100, 3, 1)).unwrap_err(); - let e4 = write_bars_1d_dataset(d_par.path(), &rows, opts_par(100, 3, 4)).unwrap_err(); - assert_eq!(e1.to_string(), e4.to_string()); - assert!(matches!(e4, ParquetBarsError::UnsortedInput { .. })); - assert_no_parquet_or_tmp_under(d_par.path()); - } - - // 5. DuplicateKey - { - let rows = vec![ - make_row(1, 2024, 1, 5, 10.0, 100.0, None, "USD", "eod_unadj"), - make_row(1, 2024, 1, 5, 11.0, 200.0, None, "USD", "eod_unadj"), - ]; - let d_seq = TempDirGuard::new("par-err-dup-seq"); - let d_par = TempDirGuard::new("par-err-dup-par"); - let e1 = write_bars_1d_dataset(d_seq.path(), &rows, opts_par(100, 3, 1)).unwrap_err(); - let e4 = write_bars_1d_dataset(d_par.path(), &rows, opts_par(100, 3, 4)).unwrap_err(); - assert_eq!(e1.to_string(), e4.to_string()); - assert!(matches!(e4, ParquetBarsError::DuplicateKey { .. })); - assert_no_parquet_or_tmp_under(d_par.path()); - } - - // 6. SessionYearOutOfRange (later row) - { - let rows = vec![ - make_row(1, 2024, 1, 5, 10.0, 100.0, None, "USD", "eod_unadj"), - make_row( - 1, - MAX_PARQUET_YEAR + 1, - 1, - 2, - 10.0, - 100.0, - None, - "USD", - "eod_unadj", - ), - ]; - let d_seq = TempDirGuard::new("par-err-year-seq"); - let d_par = TempDirGuard::new("par-err-year-par"); - let e1 = write_bars_1d_dataset(d_seq.path(), &rows, opts_par(100, 3, 1)).unwrap_err(); - let e4 = write_bars_1d_dataset(d_par.path(), &rows, opts_par(100, 3, 4)).unwrap_err(); - assert_eq!(e1.to_string(), e4.to_string()); - assert!(matches!( - e4, - ParquetBarsError::SessionYearOutOfRange { year, .. } if year == MAX_PARQUET_YEAR + 1 - )); - assert_no_parquet_or_tmp_under(d_par.path()); - } -} - -#[test] -fn parallel_injected_single_year_failure_preserves_existing_and_cleans_staging() { - let tmp = TempDirGuard::new("par-single-year-fail"); - let seed = vec![ - make_row(1, 2023, 6, 15, 20.0, 200.0, None, "USD", "eod_unadj"), - make_row(1, 2024, 6, 15, 30.0, 300.0, None, "USD", "eod_unadj"), - ]; - write_bars_1d_dataset(tmp.path(), &seed, Bars1dWriteOptions::default()).unwrap(); - - let p2023 = tmp.path().join("bars_1d/year=2023/part.parquet"); - let p2024 = tmp.path().join("bars_1d/year=2024/part.parquet"); - let orig_2023 = fs::read(&p2023).unwrap(); - let orig_2024 = fs::read(&p2024).unwrap(); - - // Unowned foreign temp file must not be removed by our cleanup. - let foreign_tmp = tmp - .path() - .join("bars_1d/year=2024/part.parquet.foreign.tmp"); - fs::write(&foreign_tmp, b"foreign-tmp").unwrap(); - - let refresh = vec![ - make_row(1, 2022, 6, 15, 15.0, 150.0, None, "USD", "eod_unadj"), - make_row(1, 2023, 6, 15, 25.0, 250.0, None, "USD", "eod_unadj"), - make_row(1, 2024, 6, 15, 35.0, 350.0, None, "USD", "eod_unadj"), - make_row(1, 2025, 6, 15, 45.0, 450.0, None, "USD", "eod_unadj"), - ]; - - let err = write_bars_1d_dataset_internal( - tmp.path(), - &refresh, - Bars1dWriteOptions { - threads: 4, - ..Bars1dWriteOptions::default() - }, - DEFAULT_LOCK_TIMEOUT, - |year, tmp_path| { - if year == 2024 { - Err(ParquetBarsError::Io { - path: tmp_path.to_path_buf(), - source: io::Error::other("injected-year-2024"), - }) - } else { - Ok(()) - } - }, - |_, _, _| {}, - ) - .unwrap_err(); - - assert!( - matches!(err, ParquetBarsError::Io { .. }) - && err.to_string().contains("injected-year-2024"), - "unexpected error: {err:?}" - ); - assert_eq!(fs::read(&p2023).unwrap(), orig_2023); - assert_eq!(fs::read(&p2024).unwrap(), orig_2024); - assert!(!tmp.path().join("bars_1d/year=2022/part.parquet").exists()); - assert!(!tmp.path().join("bars_1d/year=2025/part.parquet").exists()); - assert!(!tmp.path().join("bars_1d/.write.lock").exists()); - assert_eq!(fs::read(&foreign_tmp).unwrap(), b"foreign-tmp"); - - // Remove the intentional foreign tmp, then confirm zero transient files remain. - fs::remove_file(&foreign_tmp).unwrap(); - assert_no_transient_files(&tmp.path().join("bars_1d")); -} - -#[test] -fn parallel_multi_year_failures_return_lowest_year_error_deterministically() { - let rows = vec![ - make_row(1, 2021, 5, 1, 10.0, 100.0, None, "USD", "eod_unadj"), - make_row(1, 2022, 5, 1, 20.0, 200.0, None, "USD", "eod_unadj"), - make_row(1, 2023, 5, 1, 30.0, 300.0, None, "USD", "eod_unadj"), - make_row(1, 2024, 5, 1, 40.0, 400.0, None, "USD", "eod_unadj"), - make_row(1, 2025, 5, 1, 50.0, 500.0, None, "USD", "eod_unadj"), - ]; - - for iter in 0..5 { - let tmp = TempDirGuard::new(&format!("par-multi-fail-{iter}")); - let err = write_bars_1d_dataset_internal( - tmp.path(), - &rows, - Bars1dWriteOptions { - threads: 4, - ..Bars1dWriteOptions::default() - }, - DEFAULT_LOCK_TIMEOUT, - |year, tmp_path| { - if year == 2022 || year == 2024 { - Err(ParquetBarsError::Io { - path: tmp_path.to_path_buf(), - source: io::Error::other(format!("injected-year-{year}")), - }) - } else { - Ok(()) - } - }, - |_, _, _| {}, - ) - .unwrap_err(); - - assert!( - err.to_string().contains("injected-year-2022"), - "iteration {iter}: expected lowest failing year 2022 error, got {err}" - ); - assert_no_parquet_or_tmp_under(tmp.path()); - } -} - -#[test] -fn parallel_worker_panic_returns_typed_error_cleans_up_and_does_not_poison_lock() { - let tmp = TempDirGuard::new("par-worker-panic"); - let rows = 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, None, "USD", "eod_unadj"), - make_row(1, 2024, 5, 1, 30.0, 300.0, None, "USD", "eod_unadj"), - make_row(1, 2025, 5, 1, 40.0, 400.0, None, "USD", "eod_unadj"), - ]; - - let err = write_bars_1d_dataset_internal( - tmp.path(), - &rows, - Bars1dWriteOptions { - threads: 4, - ..Bars1dWriteOptions::default() - }, - DEFAULT_LOCK_TIMEOUT, - |year, _| { - if year == 2023 { - panic!("boom-2023"); - } - Ok(()) - }, - |_, _, _| {}, - ) - .unwrap_err(); - - match &err { - ParquetBarsError::WorkerPanicked { year, detail } => { - assert_eq!(*year, 2023); - assert!(detail.contains("boom-2023"), "unexpected detail: {detail}"); - } - other => panic!("expected WorkerPanicked, got {other:?}"), - } - assert!(err.to_string().contains("2023")); - assert!(err.source().is_none()); - assert_no_parquet_or_tmp_under(tmp.path()); - - // Subsequent write to the same directory must succeed without lock poisoning or timeout. - let stats = write_bars_1d_dataset_with_hooks( - tmp.path(), - &rows, - Bars1dWriteOptions { - threads: 4, - ..Bars1dWriteOptions::default() - }, - Duration::from_millis(50), - |_, _, _| {}, - ) - .unwrap(); - assert_eq!(stats.rows_written, 4); - assert_eq!(stats.files_written, 4); - assert_no_transient_files(&tmp.path().join("bars_1d")); -} diff --git a/tools/curate-etl/src/parquet_corporate_actions.rs b/tools/curate-etl/src/parquet_corporate_actions.rs index 84e6def3..b5abbb7a 100644 --- a/tools/curate-etl/src/parquet_corporate_actions.rs +++ b/tools/curate-etl/src/parquet_corporate_actions.rs @@ -1146,7 +1146,7 @@ where } #[cfg(test)] -pub(crate) mod tests { +mod tests { use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; use parquet::basic::ConvertedType; @@ -1306,7 +1306,7 @@ pub(crate) mod tests { } } - pub(crate) fn read_parquet_rows(path: &Path) -> Vec { + pub(super) fn read_parquet_rows(path: &Path) -> Vec { let file = File::open(path).expect("open parquet file"); let reader = SerializedFileReader::new(file).expect("open parquet reader"); let metadata = reader.metadata(); @@ -1484,7 +1484,7 @@ pub(crate) mod tests { assert_eq!(actual.map(f64::to_bits), expected.map(f64::to_bits)); } - pub(crate) fn assert_row_bitwise_eq( + pub(super) fn assert_row_bitwise_eq( actual: &CorporateActionsParquetRow, expected: &CorporateActionsParquetRow, ) { @@ -1501,7 +1501,7 @@ pub(crate) mod tests { assert_eq!(actual.known_at_source, expected.known_at_source); } - pub(crate) fn assert_no_transient_files(dir: &Path) { + pub(super) fn assert_no_transient_files(dir: &Path) { if !dir.exists() { return; } diff --git a/tools/curate-etl/src/parquet_fundamentals.rs b/tools/curate-etl/src/parquet_fundamentals.rs deleted file mode 100644 index 38000652..00000000 --- a/tools/curate-etl/src/parquet_fundamentals.rs +++ /dev/null @@ -1,1354 +0,0 @@ -//! Streaming, atomic, year-partitioned Zstd Parquet writer for `fundamentals_pit`. -//! -//! Writes `/fundamentals_pit/year=YYYY/part.parquet` files matching the 20-column -//! contract schema in `design/DATA-CONTRACTS.md` (§3A): -//! -//! 1. `listing_id` (`INT32`, `REQUIRED`) -//! 2. `effective_known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`) -//! 3. `known_at_source` (`BYTE_ARRAY`, `REQUIRED`, `STRING`) -//! 4. `has_estimated_lag` (`BOOLEAN`, `REQUIRED`) -//! 5. `period_end` (`INT32`, `REQUIRED`, `DATE`) -//! 6. `fiscal_period` (`BYTE_ARRAY`, `REQUIRED`, `STRING`) -//! 7. `currency` (`BYTE_ARRAY`, `REQUIRED`, `STRING`) -//! 8. `period_known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`) -//! 9. `revenue` (`DOUBLE`, `OPTIONAL`) -//! 10. `net_income` (`DOUBLE`, `OPTIONAL`) -//! 11. `operating_cash_flow` (`DOUBLE`, `OPTIONAL`) -//! 12. `total_assets` (`DOUBLE`, `OPTIONAL`) -//! 13. `total_equity` (`DOUBLE`, `OPTIONAL`) -//! 14. `shares_outstanding` (`DOUBLE`, `OPTIONAL`) -//! 15. `ttm_revenue` (`DOUBLE`, `OPTIONAL`) -//! 16. `ttm_net_income` (`DOUBLE`, `OPTIONAL`) -//! 17. `ttm_operating_cash_flow` (`DOUBLE`, `OPTIONAL`) -//! 18. `ttm_period_end` (`INT32`, `OPTIONAL`, `DATE`) -//! 19. `ttm_currency` (`BYTE_ARRAY`, `OPTIONAL`, `STRING`) -//! 20. `ttm_has_estimated_lag` (`BOOLEAN`, `OPTIONAL`) -//! -//! Each physical row flattens `periods[0]` (the latest visible resolved period) and the -//! builder-provided 4-quarter `ttm` summary from a [`FundamentalsSnapshot`]. Lagged period slots -//! (`periods[1..]`) are intentionally omitted from the flat Parquet representation; TTM values -//! computed by [`crate::fundamentals::build_fundamentals_snapshots`] are preserved as-is. - -use std::borrow::{Borrow, Cow}; -use std::cmp::Ordering; -use std::collections::BTreeMap; -use std::error::Error; -use std::fmt; -use std::fs::{self, File}; -use std::io::{self, BufWriter, Write}; -use std::path::{Path, PathBuf}; -use std::sync::Arc; -use std::time::Duration; - -use parquet::basic::{ - Compression, LogicalType, Repetition, TimeUnit, Type as PhysicalType, ZstdLevel, -}; -use parquet::data_type::ByteArray; -use parquet::errors::ParquetError; -use parquet::file::properties::{WriterProperties, WriterPropertiesPtr}; -use parquet::file::writer::SerializedFileWriter; -use parquet::schema::types::{ColumnPath, Type, TypePtr}; - -use crate::events::{ - partition_year_utc, KNOWN_AT_SOURCE_FILING_TIMESTAMP, KNOWN_AT_SOURCE_STATUTORY_LAG, -}; -use crate::fundamentals::{FundamentalsFields, FundamentalsSnapshot, FundamentalsTtm}; -pub use crate::parquet_bars::{MAX_PARQUET_YEAR, MIN_PARQUET_YEAR}; -use crate::parquet_publish::{ - create_backup_preserving_live, create_exclusive_tmp_file, dataset_mutex, next_run_id, - rollback_published, write_bool_col, write_i32_col, write_i64_col, write_interned_str_col, - write_optional_f64_col, write_optional_i32_col, write_optional_interned_str_col, - DatasetFileLock, PublishIoError, PublishedPartition, StagingFileGuard, StringInterner, - DEFAULT_LOCK_TIMEOUT, FILE_BUF_CAPACITY_BYTES, STRING_WRITE_BATCH_ROWS, -}; -pub use crate::parquet_publish::{RollbackFailure, DEFAULT_ROW_GROUP_ROWS, DEFAULT_ZSTD_LEVEL}; - -/// Latest visible period projection flattened into a [`FundamentalsPitParquetRow`]. -#[derive(Debug, Clone, PartialEq)] -pub struct FundamentalsPitLatestPeriod { - pub period_end: i32, - pub fiscal_period: Cow<'static, str>, - pub currency: String, - pub period_known_at_micros: i64, - pub fields: FundamentalsFields, -} - -/// Single `fundamentals_pit` row matching the `design/DATA-CONTRACTS.md` (§3A) Parquet schema. -/// -/// Only `periods[0]` (the latest visible period) and `ttm` are stored; lagged slots -/// (`periods[1..]`) are intentionally omitted. -#[derive(Debug, Clone, PartialEq)] -pub struct FundamentalsPitParquetRow { - pub listing_id: i32, - pub effective_known_at_micros: i64, - pub known_at_source: Cow<'static, str>, - pub has_estimated_lag: bool, - latest_period: Option, - pub ttm: Option, -} - -impl FundamentalsPitParquetRow { - /// Constructs a valid `fundamentals_pit` Parquet row with an explicit latest visible period. - pub fn new( - listing_id: i32, - effective_known_at_micros: i64, - known_at_source: Cow<'static, str>, - has_estimated_lag: bool, - latest_period: FundamentalsPitLatestPeriod, - ttm: Option, - ) -> Self { - Self { - listing_id, - effective_known_at_micros, - known_at_source, - has_estimated_lag, - latest_period: Some(latest_period), - ttm, - } - } - - /// Returns the flattened latest visible period (`periods[0]`), or `None` if converted from a - /// malformed snapshot with an empty `periods` vector. - #[inline] - pub fn latest_period(&self) -> Option<&FundamentalsPitLatestPeriod> { - self.latest_period.as_ref() - } -} - -impl From<&FundamentalsSnapshot> for FundamentalsPitParquetRow { - fn from(snapshot: &FundamentalsSnapshot) -> Self { - let latest_period = snapshot.periods.first().map(|slot| FundamentalsPitLatestPeriod { - period_end: slot.period_end, - fiscal_period: Cow::Borrowed(slot.fiscal_period.as_str()), - currency: slot.currency.clone(), - period_known_at_micros: slot.known_at_utc_micros, - fields: slot.fields, - }); - Self { - listing_id: snapshot.key, - effective_known_at_micros: snapshot.effective_known_at_utc_micros, - known_at_source: Cow::Borrowed(snapshot.known_at_source), - has_estimated_lag: snapshot.has_estimated_lag, - latest_period, - ttm: snapshot.ttm.clone(), - } - } -} - -impl From> for FundamentalsPitParquetRow { - fn from(snapshot: FundamentalsSnapshot) -> Self { - let latest_period = snapshot - .periods - .into_iter() - .next() - .map(|slot| FundamentalsPitLatestPeriod { - period_end: slot.period_end, - fiscal_period: Cow::Borrowed(slot.fiscal_period.as_str()), - currency: slot.currency, - period_known_at_micros: slot.known_at_utc_micros, - fields: slot.fields, - }); - Self { - listing_id: snapshot.key, - effective_known_at_micros: snapshot.effective_known_at_utc_micros, - known_at_source: Cow::Borrowed(snapshot.known_at_source), - has_estimated_lag: snapshot.has_estimated_lag, - latest_period, - ttm: snapshot.ttm, - } - } -} - -/// Configuration for [`write_fundamentals_pit_dataset`]. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct FundamentalsPitWriteOptions { - pub row_group_rows: usize, - pub zstd_level: i32, -} - -impl Default for FundamentalsPitWriteOptions { - fn default() -> Self { - Self { - row_group_rows: DEFAULT_ROW_GROUP_ROWS, - zstd_level: DEFAULT_ZSTD_LEVEL, - } - } -} - -/// Accounting summary returned by [`write_fundamentals_pit_dataset`]. -#[derive(Debug, Clone, Default, PartialEq, Eq)] -pub struct FundamentalsPitWriteStats { - pub rows_written: usize, - pub files_written: usize, - pub row_groups_written: usize, - pub bytes_written: u64, - pub rows_by_year: BTreeMap, -} - -/// Typed error returned by [`write_fundamentals_pit_dataset`]. -#[derive(Debug)] -pub enum ParquetFundamentalsError { - InvalidRowGroupRows, - InvalidZstdLevel { - level: i32, - }, - EmptyPeriods { - row_index: usize, - listing_id: i32, - effective_known_at_micros: i64, - }, - UnsortedInput { - row_index: usize, - prev_listing_id: i32, - prev_effective_known_at_micros: i64, - listing_id: i32, - effective_known_at_micros: i64, - }, - DuplicateRow { - row_index: usize, - listing_id: i32, - effective_known_at_micros: i64, - }, - PartitionYearOutOfRange { - row_index: usize, - listing_id: i32, - effective_known_at_micros: i64, - year: i32, - min_year: i32, - max_year: i32, - }, - EmptyKnownAtSource { - row_index: usize, - listing_id: i32, - effective_known_at_micros: i64, - }, - InvalidKnownAtSource { - row_index: usize, - listing_id: i32, - effective_known_at_micros: i64, - value: String, - }, - EmptyFiscalPeriod { - row_index: usize, - listing_id: i32, - effective_known_at_micros: i64, - }, - EmptyCurrency { - row_index: usize, - listing_id: i32, - effective_known_at_micros: i64, - }, - EmptyTtmCurrency { - row_index: usize, - listing_id: i32, - effective_known_at_micros: i64, - }, - NonFiniteValue { - row_index: usize, - listing_id: i32, - effective_known_at_micros: i64, - field: &'static str, - value: f64, - }, - LockTimeout { - path: PathBuf, - waited: Duration, - }, - RollbackFailed { - cause: Box, - failures: Vec, - }, - Io { - path: PathBuf, - source: io::Error, - }, - Parquet { - path: PathBuf, - source: ParquetError, - }, -} - -impl fmt::Display for ParquetFundamentalsError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::InvalidRowGroupRows => { - write!(f, "invalid row_group_rows: must be greater than 0") - } - Self::InvalidZstdLevel { level } => { - write!(f, "invalid Zstd compression level: {level}") - } - Self::EmptyPeriods { - row_index, - listing_id, - effective_known_at_micros, - } => write!( - f, - "snapshot has empty periods at row {row_index} for (listing_id={listing_id}, effective_known_at={effective_known_at_micros})" - ), - Self::UnsortedInput { - row_index, - prev_listing_id, - prev_effective_known_at_micros, - listing_id, - effective_known_at_micros, - } => write!( - f, - "unsorted input at row {row_index}: ({listing_id}, {effective_known_at_micros}) follows ({prev_listing_id}, {prev_effective_known_at_micros})" - ), - Self::DuplicateRow { - row_index, - listing_id, - effective_known_at_micros, - } => write!( - f, - "duplicate fundamentals_pit row at row {row_index}: (listing_id={listing_id}, effective_known_at={effective_known_at_micros})" - ), - Self::PartitionYearOutOfRange { - row_index, - listing_id, - effective_known_at_micros, - year, - min_year, - max_year, - } => write!( - f, - "partition year {year} (effective_known_at {effective_known_at_micros}) at row {row_index} for listing_id {listing_id} is outside allowed range {min_year}..={max_year}" - ), - Self::EmptyKnownAtSource { - row_index, - listing_id, - effective_known_at_micros, - } => write!( - f, - "empty known_at_source at row {row_index} for ({listing_id}, {effective_known_at_micros}): must be non-empty" - ), - Self::InvalidKnownAtSource { - row_index, - listing_id, - effective_known_at_micros, - value, - } => write!( - f, - "invalid known_at_source {value:?} at row {row_index} for ({listing_id}, {effective_known_at_micros}): expected {KNOWN_AT_SOURCE_FILING_TIMESTAMP:?} or {KNOWN_AT_SOURCE_STATUTORY_LAG:?}" - ), - Self::EmptyFiscalPeriod { - row_index, - listing_id, - effective_known_at_micros, - } => write!( - f, - "empty fiscal_period at row {row_index} for ({listing_id}, {effective_known_at_micros}): must be non-empty" - ), - Self::EmptyCurrency { - row_index, - listing_id, - effective_known_at_micros, - } => write!( - f, - "empty currency at row {row_index} for ({listing_id}, {effective_known_at_micros}): must be non-empty" - ), - Self::EmptyTtmCurrency { - row_index, - listing_id, - effective_known_at_micros, - } => write!( - f, - "empty ttm_currency at row {row_index} for ({listing_id}, {effective_known_at_micros}): must be non-empty" - ), - Self::NonFiniteValue { - row_index, - listing_id, - effective_known_at_micros, - field, - value, - } => write!( - f, - "non-finite {field} value {value} at row {row_index} for ({listing_id}, {effective_known_at_micros})" - ), - Self::LockTimeout { path, waited } => write!( - f, - "timed out after {}ms waiting for dataset write lock '{}' (if no writer is active, remove the stale lock file and retry)", - waited.as_millis(), - path.display() - ), - Self::RollbackFailed { cause, failures } => { - write!( - f, - "publication failed ({cause}) and rollback encountered {} error(s) requiring manual recovery:", - failures.len() - )?; - for failure in failures { - write!(f, " [{failure}]")?; - } - Ok(()) - } - Self::Io { path, source } => { - write!(f, "I/O error at '{}': {source}", path.display()) - } - Self::Parquet { path, source } => { - write!(f, "Parquet error at '{}': {source}", path.display()) - } - } - } -} - -impl Error for ParquetFundamentalsError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::RollbackFailed { cause, .. } => Some(cause.as_ref()), - Self::Io { source, .. } => Some(source), - Self::Parquet { source, .. } => Some(source), - _ => None, - } - } -} - -impl From for ParquetFundamentalsError { - fn from(err: PublishIoError) -> Self { - match err { - PublishIoError::LockTimeout { path, waited } => Self::LockTimeout { path, waited }, - PublishIoError::Io { path, source } => Self::Io { path, source }, - } - } -} - -/// Builds the exact 20-column Parquet schema for `fundamentals_pit` per `design/DATA-CONTRACTS.md` (§3A). -pub fn fundamentals_pit_parquet_schema() -> Result { - let fields: Vec = vec![ - // 1. listing_id INT32 REQUIRED - Arc::new( - Type::primitive_type_builder("listing_id", PhysicalType::INT32) - .with_repetition(Repetition::REQUIRED) - .build()?, - ), - // 2. effective_known_at INT64 REQUIRED TIMESTAMP(MICROS, UTC) - Arc::new( - Type::primitive_type_builder("effective_known_at", PhysicalType::INT64) - .with_repetition(Repetition::REQUIRED) - .with_logical_type(Some(LogicalType::timestamp(true, TimeUnit::MICROS))) - .build()?, - ), - // 3. known_at_source STRING REQUIRED - Arc::new( - Type::primitive_type_builder("known_at_source", PhysicalType::BYTE_ARRAY) - .with_repetition(Repetition::REQUIRED) - .with_logical_type(Some(LogicalType::String)) - .build()?, - ), - // 4. has_estimated_lag BOOLEAN REQUIRED - Arc::new( - Type::primitive_type_builder("has_estimated_lag", PhysicalType::BOOLEAN) - .with_repetition(Repetition::REQUIRED) - .build()?, - ), - // 5. period_end INT32 DATE REQUIRED - Arc::new( - Type::primitive_type_builder("period_end", PhysicalType::INT32) - .with_repetition(Repetition::REQUIRED) - .with_logical_type(Some(LogicalType::Date)) - .build()?, - ), - // 6. fiscal_period STRING REQUIRED - Arc::new( - Type::primitive_type_builder("fiscal_period", PhysicalType::BYTE_ARRAY) - .with_repetition(Repetition::REQUIRED) - .with_logical_type(Some(LogicalType::String)) - .build()?, - ), - // 7. currency STRING REQUIRED - Arc::new( - Type::primitive_type_builder("currency", PhysicalType::BYTE_ARRAY) - .with_repetition(Repetition::REQUIRED) - .with_logical_type(Some(LogicalType::String)) - .build()?, - ), - // 8. period_known_at INT64 REQUIRED TIMESTAMP(MICROS, UTC) - Arc::new( - Type::primitive_type_builder("period_known_at", PhysicalType::INT64) - .with_repetition(Repetition::REQUIRED) - .with_logical_type(Some(LogicalType::timestamp(true, TimeUnit::MICROS))) - .build()?, - ), - // 9-14. latest-period financial metrics DOUBLE OPTIONAL - Arc::new( - Type::primitive_type_builder("revenue", PhysicalType::DOUBLE) - .with_repetition(Repetition::OPTIONAL) - .build()?, - ), - Arc::new( - Type::primitive_type_builder("net_income", PhysicalType::DOUBLE) - .with_repetition(Repetition::OPTIONAL) - .build()?, - ), - Arc::new( - Type::primitive_type_builder("operating_cash_flow", PhysicalType::DOUBLE) - .with_repetition(Repetition::OPTIONAL) - .build()?, - ), - Arc::new( - Type::primitive_type_builder("total_assets", PhysicalType::DOUBLE) - .with_repetition(Repetition::OPTIONAL) - .build()?, - ), - Arc::new( - Type::primitive_type_builder("total_equity", PhysicalType::DOUBLE) - .with_repetition(Repetition::OPTIONAL) - .build()?, - ), - Arc::new( - Type::primitive_type_builder("shares_outstanding", PhysicalType::DOUBLE) - .with_repetition(Repetition::OPTIONAL) - .build()?, - ), - // 15-17. TTM flow sums DOUBLE OPTIONAL - Arc::new( - Type::primitive_type_builder("ttm_revenue", PhysicalType::DOUBLE) - .with_repetition(Repetition::OPTIONAL) - .build()?, - ), - Arc::new( - Type::primitive_type_builder("ttm_net_income", PhysicalType::DOUBLE) - .with_repetition(Repetition::OPTIONAL) - .build()?, - ), - Arc::new( - Type::primitive_type_builder("ttm_operating_cash_flow", PhysicalType::DOUBLE) - .with_repetition(Repetition::OPTIONAL) - .build()?, - ), - // 18. ttm_period_end INT32 DATE OPTIONAL - Arc::new( - Type::primitive_type_builder("ttm_period_end", PhysicalType::INT32) - .with_repetition(Repetition::OPTIONAL) - .with_logical_type(Some(LogicalType::Date)) - .build()?, - ), - // 19. ttm_currency STRING OPTIONAL - Arc::new( - Type::primitive_type_builder("ttm_currency", PhysicalType::BYTE_ARRAY) - .with_repetition(Repetition::OPTIONAL) - .with_logical_type(Some(LogicalType::String)) - .build()?, - ), - // 20. ttm_has_estimated_lag BOOLEAN OPTIONAL - Arc::new( - Type::primitive_type_builder("ttm_has_estimated_lag", PhysicalType::BOOLEAN) - .with_repetition(Repetition::OPTIONAL) - .build()?, - ), - ]; - - Ok(Arc::new( - Type::group_type_builder("fundamentals_pit") - .with_fields(fields) - .build()?, - )) -} - -fn build_writer_properties(zstd_level: ZstdLevel) -> WriterPropertiesPtr { - Arc::new( - WriterProperties::builder() - .set_compression(Compression::ZSTD(zstd_level)) - .set_column_dictionary_enabled(ColumnPath::from("known_at_source"), true) - .set_column_dictionary_enabled(ColumnPath::from("fiscal_period"), true) - .set_column_dictionary_enabled(ColumnPath::from("currency"), true) - .set_column_dictionary_enabled(ColumnPath::from("ttm_currency"), true) - .set_created_by(format!("curate-etl {}", env!("CARGO_PKG_VERSION"))) - .build(), - ) -} - -#[inline] -fn check_opt_finite( - row: &FundamentalsPitParquetRow, - row_index: usize, - field: &'static str, - val: Option, -) -> Result<(), ParquetFundamentalsError> { - if let Some(value) = val { - if !value.is_finite() { - return Err(ParquetFundamentalsError::NonFiniteValue { - row_index, - listing_id: row.listing_id, - effective_known_at_micros: row.effective_known_at_micros, - field, - value, - }); - } - } - Ok(()) -} - -#[inline] -fn validate_row( - row: &FundamentalsPitParquetRow, - row_index: usize, -) -> Result<(i32, &FundamentalsPitLatestPeriod), ParquetFundamentalsError> { - let Some(latest) = row.latest_period.as_ref() else { - return Err(ParquetFundamentalsError::EmptyPeriods { - row_index, - listing_id: row.listing_id, - effective_known_at_micros: row.effective_known_at_micros, - }); - }; - - let year = partition_year_utc(row.effective_known_at_micros); - if !(MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR).contains(&year) { - return Err(ParquetFundamentalsError::PartitionYearOutOfRange { - row_index, - listing_id: row.listing_id, - effective_known_at_micros: row.effective_known_at_micros, - year, - min_year: MIN_PARQUET_YEAR, - max_year: MAX_PARQUET_YEAR, - }); - } - - if row.known_at_source.trim().is_empty() { - return Err(ParquetFundamentalsError::EmptyKnownAtSource { - row_index, - listing_id: row.listing_id, - effective_known_at_micros: row.effective_known_at_micros, - }); - } - if row.known_at_source.as_ref() != KNOWN_AT_SOURCE_FILING_TIMESTAMP - && row.known_at_source.as_ref() != KNOWN_AT_SOURCE_STATUTORY_LAG - { - return Err(ParquetFundamentalsError::InvalidKnownAtSource { - row_index, - listing_id: row.listing_id, - effective_known_at_micros: row.effective_known_at_micros, - value: row.known_at_source.to_string(), - }); - } - if latest.fiscal_period.trim().is_empty() { - return Err(ParquetFundamentalsError::EmptyFiscalPeriod { - row_index, - listing_id: row.listing_id, - effective_known_at_micros: row.effective_known_at_micros, - }); - } - if latest.currency.trim().is_empty() { - return Err(ParquetFundamentalsError::EmptyCurrency { - row_index, - listing_id: row.listing_id, - effective_known_at_micros: row.effective_known_at_micros, - }); - } - - check_opt_finite(row, row_index, "revenue", latest.fields.revenue)?; - check_opt_finite(row, row_index, "net_income", latest.fields.net_income)?; - check_opt_finite( - row, - row_index, - "operating_cash_flow", - latest.fields.operating_cash_flow, - )?; - check_opt_finite(row, row_index, "total_assets", latest.fields.total_assets)?; - check_opt_finite(row, row_index, "total_equity", latest.fields.total_equity)?; - check_opt_finite( - row, - row_index, - "shares_outstanding", - latest.fields.shares_outstanding, - )?; - - if let Some(ttm) = row.ttm.as_ref() { - if ttm.currency.trim().is_empty() { - return Err(ParquetFundamentalsError::EmptyTtmCurrency { - row_index, - listing_id: row.listing_id, - effective_known_at_micros: row.effective_known_at_micros, - }); - } - check_opt_finite(row, row_index, "ttm_revenue", ttm.flows.revenue)?; - check_opt_finite(row, row_index, "ttm_net_income", ttm.flows.net_income)?; - check_opt_finite( - row, - row_index, - "ttm_operating_cash_flow", - ttm.flows.operating_cash_flow, - )?; - } - - Ok((year, latest)) -} - -#[inline] -fn push_opt_f64(values: &mut Vec, defs: &mut Vec, val: Option) { - match val { - Some(v) => { - values.push(v); - defs.push(1); - } - None => { - defs.push(0); - } - } -} - -#[derive(Default)] -struct RowGroupBuffer { - listing_id: Vec, - effective_known_at_micros: Vec, - known_at_source_ids: Vec, - known_at_source_interner: StringInterner, - has_estimated_lag: Vec, - period_end: Vec, - fiscal_period_ids: Vec, - fiscal_period_interner: StringInterner, - currency_ids: Vec, - currency_interner: StringInterner, - period_known_at_micros: Vec, - revenue_values: Vec, - revenue_def: Vec, - net_income_values: Vec, - net_income_def: Vec, - operating_cash_flow_values: Vec, - operating_cash_flow_def: Vec, - total_assets_values: Vec, - total_assets_def: Vec, - total_equity_values: Vec, - total_equity_def: Vec, - shares_outstanding_values: Vec, - shares_outstanding_def: Vec, - ttm_period_end_values: Vec, - ttm_period_end_def: Vec, - ttm_currency_ids: Vec, - ttm_currency_def: Vec, - ttm_currency_interner: StringInterner, - ttm_revenue_values: Vec, - ttm_revenue_def: Vec, - ttm_net_income_values: Vec, - ttm_net_income_def: Vec, - ttm_operating_cash_flow_values: Vec, - ttm_operating_cash_flow_def: Vec, - ttm_has_estimated_lag_values: Vec, - ttm_has_estimated_lag_def: Vec, -} - -impl RowGroupBuffer { - #[inline] - fn len(&self) -> usize { - self.listing_id.len() - } - - fn push(&mut self, row: &FundamentalsPitParquetRow, latest: &FundamentalsPitLatestPeriod) { - self.listing_id.push(row.listing_id); - self.effective_known_at_micros - .push(row.effective_known_at_micros); - let kas_id = self - .known_at_source_interner - .intern(row.known_at_source.as_ref()); - self.known_at_source_ids.push(kas_id); - self.has_estimated_lag.push(row.has_estimated_lag); - self.period_end.push(latest.period_end); - let fp_id = self - .fiscal_period_interner - .intern(latest.fiscal_period.as_ref()); - self.fiscal_period_ids.push(fp_id); - let cur_id = self.currency_interner.intern(latest.currency.as_str()); - self.currency_ids.push(cur_id); - self.period_known_at_micros - .push(latest.period_known_at_micros); - - push_opt_f64( - &mut self.revenue_values, - &mut self.revenue_def, - latest.fields.revenue, - ); - push_opt_f64( - &mut self.net_income_values, - &mut self.net_income_def, - latest.fields.net_income, - ); - push_opt_f64( - &mut self.operating_cash_flow_values, - &mut self.operating_cash_flow_def, - latest.fields.operating_cash_flow, - ); - push_opt_f64( - &mut self.total_assets_values, - &mut self.total_assets_def, - latest.fields.total_assets, - ); - push_opt_f64( - &mut self.total_equity_values, - &mut self.total_equity_def, - latest.fields.total_equity, - ); - push_opt_f64( - &mut self.shares_outstanding_values, - &mut self.shares_outstanding_def, - latest.fields.shares_outstanding, - ); - - match row.ttm.as_ref() { - Some(ttm) => { - self.ttm_period_end_values.push(ttm.ending_period_end); - self.ttm_period_end_def.push(1); - let ttm_cur_id = self.ttm_currency_interner.intern(ttm.currency.as_str()); - self.ttm_currency_ids.push(ttm_cur_id); - self.ttm_currency_def.push(1); - push_opt_f64( - &mut self.ttm_revenue_values, - &mut self.ttm_revenue_def, - ttm.flows.revenue, - ); - push_opt_f64( - &mut self.ttm_net_income_values, - &mut self.ttm_net_income_def, - ttm.flows.net_income, - ); - push_opt_f64( - &mut self.ttm_operating_cash_flow_values, - &mut self.ttm_operating_cash_flow_def, - ttm.flows.operating_cash_flow, - ); - self.ttm_has_estimated_lag_values - .push(ttm.has_estimated_lag); - self.ttm_has_estimated_lag_def.push(1); - } - None => { - self.ttm_period_end_def.push(0); - self.ttm_currency_def.push(0); - self.ttm_revenue_def.push(0); - self.ttm_net_income_def.push(0); - self.ttm_operating_cash_flow_def.push(0); - self.ttm_has_estimated_lag_def.push(0); - } - } - } - - fn clear(&mut self) { - self.listing_id.clear(); - self.effective_known_at_micros.clear(); - self.known_at_source_ids.clear(); - self.known_at_source_interner.clear(); - self.has_estimated_lag.clear(); - self.period_end.clear(); - self.fiscal_period_ids.clear(); - self.fiscal_period_interner.clear(); - self.currency_ids.clear(); - self.currency_interner.clear(); - self.period_known_at_micros.clear(); - self.revenue_values.clear(); - self.revenue_def.clear(); - self.net_income_values.clear(); - self.net_income_def.clear(); - self.operating_cash_flow_values.clear(); - self.operating_cash_flow_def.clear(); - self.total_assets_values.clear(); - self.total_assets_def.clear(); - self.total_equity_values.clear(); - self.total_equity_def.clear(); - self.shares_outstanding_values.clear(); - self.shares_outstanding_def.clear(); - self.ttm_period_end_values.clear(); - self.ttm_period_end_def.clear(); - self.ttm_currency_ids.clear(); - self.ttm_currency_def.clear(); - self.ttm_currency_interner.clear(); - self.ttm_revenue_values.clear(); - self.ttm_revenue_def.clear(); - self.ttm_net_income_values.clear(); - self.ttm_net_income_def.clear(); - self.ttm_operating_cash_flow_values.clear(); - self.ttm_operating_cash_flow_def.clear(); - self.ttm_has_estimated_lag_values.clear(); - self.ttm_has_estimated_lag_def.clear(); - } -} - -struct YearWriter { - tmp_path: PathBuf, - final_path: PathBuf, - writer: SerializedFileWriter>, - buf: RowGroupBuffer, - rows_written: usize, - row_groups_written: usize, -} - -impl YearWriter { - fn open( - dataset_dir: &Path, - year: i32, - run_id: &str, - schema: &TypePtr, - props: &WriterPropertiesPtr, - staging_guards: &mut BTreeMap, - ) -> Result { - let year_dir = dataset_dir.join(format!("year={year:04}")); - fs::create_dir_all(&year_dir).map_err(|source| ParquetFundamentalsError::Io { - path: year_dir.clone(), - source, - })?; - - let (tmp_path, file) = create_exclusive_tmp_file(&year_dir, run_id)?; - staging_guards.insert(year, StagingFileGuard::new(tmp_path.clone())); - let final_path = year_dir.join("part.parquet"); - - let buf_writer = BufWriter::with_capacity(FILE_BUF_CAPACITY_BYTES, file); - let writer = SerializedFileWriter::new(buf_writer, schema.clone(), props.clone()).map_err( - |source| ParquetFundamentalsError::Parquet { - path: tmp_path.clone(), - source, - }, - )?; - - Ok(Self { - tmp_path, - final_path, - writer, - buf: RowGroupBuffer::default(), - rows_written: 0, - row_groups_written: 0, - }) - } - - fn flush_row_group( - &mut self, - scratch: &mut Vec, - ) -> Result<(), ParquetFundamentalsError> { - let row_count = self.buf.len(); - if row_count == 0 { - return Ok(()); - } - - let map_pq = |source: ParquetError| ParquetFundamentalsError::Parquet { - path: self.tmp_path.clone(), - source, - }; - - let mut rg_writer = self.writer.next_row_group().map_err(map_pq)?; - - // 1. listing_id (INT32, REQUIRED) - write_i32_col(&mut rg_writer, &self.buf.listing_id).map_err(map_pq)?; - // 2. effective_known_at (INT64, REQUIRED, TIMESTAMP MICROS UTC) - write_i64_col(&mut rg_writer, &self.buf.effective_known_at_micros).map_err(map_pq)?; - // 3. known_at_source (BYTE_ARRAY, REQUIRED, STRING) - write_interned_str_col( - &mut rg_writer, - &self.buf.known_at_source_ids, - &self.buf.known_at_source_interner, - scratch, - ) - .map_err(map_pq)?; - // 4. has_estimated_lag (BOOLEAN, REQUIRED) - write_bool_col(&mut rg_writer, &self.buf.has_estimated_lag, None).map_err(map_pq)?; - // 5. period_end (INT32, REQUIRED, DATE) - write_i32_col(&mut rg_writer, &self.buf.period_end).map_err(map_pq)?; - // 6. fiscal_period (BYTE_ARRAY, REQUIRED, STRING) - write_interned_str_col( - &mut rg_writer, - &self.buf.fiscal_period_ids, - &self.buf.fiscal_period_interner, - scratch, - ) - .map_err(map_pq)?; - // 7. currency (BYTE_ARRAY, REQUIRED, STRING) - write_interned_str_col( - &mut rg_writer, - &self.buf.currency_ids, - &self.buf.currency_interner, - scratch, - ) - .map_err(map_pq)?; - // 8. period_known_at (INT64, REQUIRED, TIMESTAMP MICROS UTC) - write_i64_col(&mut rg_writer, &self.buf.period_known_at_micros).map_err(map_pq)?; - // 9. revenue (DOUBLE, OPTIONAL) - write_optional_f64_col( - &mut rg_writer, - &self.buf.revenue_values, - &self.buf.revenue_def, - ) - .map_err(map_pq)?; - // 10. net_income (DOUBLE, OPTIONAL) - write_optional_f64_col( - &mut rg_writer, - &self.buf.net_income_values, - &self.buf.net_income_def, - ) - .map_err(map_pq)?; - // 11. operating_cash_flow (DOUBLE, OPTIONAL) - write_optional_f64_col( - &mut rg_writer, - &self.buf.operating_cash_flow_values, - &self.buf.operating_cash_flow_def, - ) - .map_err(map_pq)?; - // 12. total_assets (DOUBLE, OPTIONAL) - write_optional_f64_col( - &mut rg_writer, - &self.buf.total_assets_values, - &self.buf.total_assets_def, - ) - .map_err(map_pq)?; - // 13. total_equity (DOUBLE, OPTIONAL) - write_optional_f64_col( - &mut rg_writer, - &self.buf.total_equity_values, - &self.buf.total_equity_def, - ) - .map_err(map_pq)?; - // 14. shares_outstanding (DOUBLE, OPTIONAL) - write_optional_f64_col( - &mut rg_writer, - &self.buf.shares_outstanding_values, - &self.buf.shares_outstanding_def, - ) - .map_err(map_pq)?; - // 15. ttm_revenue (DOUBLE, OPTIONAL) - write_optional_f64_col( - &mut rg_writer, - &self.buf.ttm_revenue_values, - &self.buf.ttm_revenue_def, - ) - .map_err(map_pq)?; - // 16. ttm_net_income (DOUBLE, OPTIONAL) - write_optional_f64_col( - &mut rg_writer, - &self.buf.ttm_net_income_values, - &self.buf.ttm_net_income_def, - ) - .map_err(map_pq)?; - // 17. ttm_operating_cash_flow (DOUBLE, OPTIONAL) - write_optional_f64_col( - &mut rg_writer, - &self.buf.ttm_operating_cash_flow_values, - &self.buf.ttm_operating_cash_flow_def, - ) - .map_err(map_pq)?; - // 18. ttm_period_end (INT32, OPTIONAL, DATE) - write_optional_i32_col( - &mut rg_writer, - &self.buf.ttm_period_end_values, - &self.buf.ttm_period_end_def, - ) - .map_err(map_pq)?; - // 19. ttm_currency (BYTE_ARRAY, OPTIONAL, STRING) - write_optional_interned_str_col( - &mut rg_writer, - &self.buf.ttm_currency_ids, - &self.buf.ttm_currency_def, - &self.buf.ttm_currency_interner, - scratch, - ) - .map_err(map_pq)?; - // 20. ttm_has_estimated_lag (BOOLEAN, OPTIONAL) - write_bool_col( - &mut rg_writer, - &self.buf.ttm_has_estimated_lag_values, - Some(&self.buf.ttm_has_estimated_lag_def), - ) - .map_err(map_pq)?; - - rg_writer.close().map_err(map_pq)?; - - self.rows_written += row_count; - self.row_groups_written += 1; - self.buf.clear(); - Ok(()) - } - - fn finish_and_sync( - mut self, - scratch: &mut Vec, - ) -> Result { - self.flush_row_group(scratch)?; - - let mut buf_writer = - self.writer - .into_inner() - .map_err(|source| ParquetFundamentalsError::Parquet { - path: self.tmp_path.clone(), - source, - })?; - buf_writer - .flush() - .map_err(|source| ParquetFundamentalsError::Io { - path: self.tmp_path.clone(), - source, - })?; - let file = buf_writer - .into_inner() - .map_err(|err| ParquetFundamentalsError::Io { - path: self.tmp_path.clone(), - source: err.into_error(), - })?; - file.sync_all() - .map_err(|source| ParquetFundamentalsError::Io { - path: self.tmp_path.clone(), - source, - })?; - let bytes = file - .metadata() - .map_err(|source| ParquetFundamentalsError::Io { - path: self.tmp_path.clone(), - source, - })? - .len(); - drop(file); - - Ok(SyncedYearFile { - tmp_path: self.tmp_path, - final_path: self.final_path, - rows_written: self.rows_written, - row_groups_written: self.row_groups_written, - bytes, - }) - } -} - -struct SyncedYearFile { - tmp_path: PathBuf, - final_path: PathBuf, - rows_written: usize, - row_groups_written: usize, - bytes: u64, -} - -fn finish_with_rollback( - cause: ParquetFundamentalsError, - published: &[PublishedPartition], - extra_failure: Option, -) -> ParquetFundamentalsError { - let mut failures = Vec::new(); - if let Some(failure) = extra_failure { - failures.push(failure); - } - failures.extend(rollback_published(published)); - if failures.is_empty() { - cause - } else { - ParquetFundamentalsError::RollbackFailed { - cause: Box::new(cause), - failures, - } - } -} - -/// Streams strictly ascending `(listing_id, effective_known_at)` snapshot rows into -/// year-partitioned Zstd Parquet files at `/fundamentals_pit/year=YYYY/part.parquet`, -/// partitioned by the UTC year of `effective_known_at`. -/// -/// # Sort Order & Validation -/// Input rows must be strictly ascending and unique by `(listing_id, effective_known_at)`. -/// Out-of-order rows, duplicate keys, snapshots with empty `periods`, partition years outside -/// `MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR`, empty string metadata fields, and non-finite numeric -/// values return typed [`ParquetFundamentalsError`] variants with nothing published. Empty input -/// returns `Ok(FundamentalsPitWriteStats::default())` without creating -/// `/fundamentals_pit` or touching pre-existing partitions. -/// -/// # Concurrency & Atomicity -/// Concurrent writers targeting the same `/fundamentals_pit` directory are serialized via -/// an in-process per-dataset mutex and a bounded-wait exclusive `.write.lock` file. Every year -/// partition is written to an exclusively created per-run staging file (`part.parquet..tmp`), -/// flushed, and `sync_all`'d before publication. Pre-existing `part.parquet` files are backed up -/// in place (hard link with exclusive copy fallback) so the live path remains readable until -/// replaced by a single atomic `rename`; on any error or unwind, all open writers close before -/// owned staging files are unlinked, replaced partitions are restored from backup, and newly -/// published partitions are removed (reporting rollback errors via -/// [`ParquetFundamentalsError::RollbackFailed`]). -pub fn write_fundamentals_pit_dataset( - out_dir: P, - rows: I, - options: FundamentalsPitWriteOptions, -) -> Result -where - P: AsRef, - I: IntoIterator, - R: Borrow, -{ - write_fundamentals_pit_dataset_with_hooks( - out_dir, - rows, - options, - DEFAULT_LOCK_TIMEOUT, - |_, _, _| {}, - ) -} - -fn write_fundamentals_pit_dataset_with_hooks( - out_dir: P, - rows: I, - options: FundamentalsPitWriteOptions, - lock_timeout: Duration, - mut on_after_backup: F, -) -> Result -where - P: AsRef, - I: IntoIterator, - R: Borrow, - F: FnMut(i32, &Path, Option<&Path>), -{ - if options.row_group_rows == 0 { - return Err(ParquetFundamentalsError::InvalidRowGroupRows); - } - let zstd_level = ZstdLevel::try_new(options.zstd_level).map_err(|_| { - ParquetFundamentalsError::InvalidZstdLevel { - level: options.zstd_level, - } - })?; - - let mut row_iter = rows.into_iter(); - let Some(first_item) = row_iter.next() else { - return Ok(FundamentalsPitWriteStats::default()); - }; - validate_row(first_item.borrow(), 0)?; - - let out_dir = out_dir.as_ref(); - let dataset_dir = out_dir.join("fundamentals_pit"); - let schema = - fundamentals_pit_parquet_schema().map_err(|source| ParquetFundamentalsError::Parquet { - path: dataset_dir.clone(), - source, - })?; - let props = build_writer_properties(zstd_level); - - fs::create_dir_all(&dataset_dir).map_err(|source| ParquetFundamentalsError::Io { - path: dataset_dir.clone(), - source, - })?; - - let dataset_mu = dataset_mutex(&dataset_dir); - let _in_process_guard = dataset_mu.lock().unwrap_or_else(|err| err.into_inner()); - let _file_lock = DatasetFileLock::acquire_with_timeout(&dataset_dir, lock_timeout)?; - - let run_id = next_run_id(); - // Declared before `writers` so Rust's reverse drop order closes all Parquet file handles - // before unlinking owned `.tmp` staging files on error or panic unwind. - let mut staging_guards: BTreeMap = BTreeMap::new(); - let mut writers: BTreeMap = BTreeMap::new(); - let mut scratch: Vec = Vec::with_capacity(STRING_WRITE_BATCH_ROWS); - - let synced_files: Vec<(i32, SyncedYearFile)> = { - let mut prev_key: Option<(i32, i64)> = None; - - for (row_index, item) in std::iter::once(first_item).chain(row_iter).enumerate() { - let row = item.borrow(); - let key = (row.listing_id, row.effective_known_at_micros); - if let Some((prev_listing_id, prev_effective_known_at_micros)) = prev_key { - match key.cmp(&(prev_listing_id, prev_effective_known_at_micros)) { - Ordering::Equal => { - return Err(ParquetFundamentalsError::DuplicateRow { - row_index, - listing_id: row.listing_id, - effective_known_at_micros: row.effective_known_at_micros, - }); - } - Ordering::Less => { - return Err(ParquetFundamentalsError::UnsortedInput { - row_index, - prev_listing_id, - prev_effective_known_at_micros, - listing_id: row.listing_id, - effective_known_at_micros: row.effective_known_at_micros, - }); - } - Ordering::Greater => {} - } - } - - let (year, latest) = validate_row(row, row_index)?; - - let yw = match writers.entry(year) { - std::collections::btree_map::Entry::Occupied(entry) => entry.into_mut(), - std::collections::btree_map::Entry::Vacant(entry) => { - let opened = YearWriter::open( - &dataset_dir, - year, - &run_id, - &schema, - &props, - &mut staging_guards, - )?; - entry.insert(opened) - } - }; - - yw.buf.push(row, latest); - if yw.buf.len() == options.row_group_rows { - yw.flush_row_group(&mut scratch)?; - } - prev_key = Some(key); - } - - let mut synced = Vec::with_capacity(writers.len()); - let drained: Vec<(i32, YearWriter)> = std::mem::take(&mut writers).into_iter().collect(); - for (year, yw) in drained { - let file = yw.finish_and_sync(&mut scratch)?; - synced.push((year, file)); - } - synced - }; - - let mut stats = FundamentalsPitWriteStats::default(); - let mut published: Vec = Vec::with_capacity(synced_files.len()); - for (year, file) in synced_files { - let backup_path = match fs::symlink_metadata(&file.final_path) { - Ok(meta) if !meta.is_dir() => { - match create_backup_preserving_live(&file.final_path, &run_id) { - Ok(bak) => Some(bak), - Err(err) => { - return Err(finish_with_rollback(err.into(), &published, None)); - } - } - } - // Directory occupying final_path: leave it in place so the rename below fails - // cleanly and triggers rollback of all earlier partitions. - Ok(_) => None, - Err(err) if err.kind() == io::ErrorKind::NotFound => None, - Err(source) => { - let err = ParquetFundamentalsError::Io { - path: file.final_path, - source, - }; - return Err(finish_with_rollback(err, &published, None)); - } - }; - - on_after_backup(year, &file.final_path, backup_path.as_deref()); - - if let Err(source) = fs::rename(&file.tmp_path, &file.final_path) { - let extra_failure = backup_path.and_then(|bak| { - fs::remove_file(&bak).err().map(|remove_err| RollbackFailure { - final_path: file.final_path.clone(), - backup_path: Some(bak), - source: remove_err, - }) - }); - let err = ParquetFundamentalsError::Io { - path: file.final_path, - source, - }; - return Err(finish_with_rollback(err, &published, extra_failure)); - } - - if let Some(guard) = staging_guards.get_mut(&year) { - guard.disarm(); - } - - published.push(PublishedPartition { - final_path: file.final_path, - backup_path, - }); - stats.rows_written += file.rows_written; - stats.files_written += 1; - stats.row_groups_written += file.row_groups_written; - stats.bytes_written += file.bytes; - stats.rows_by_year.insert(year, file.rows_written); - } - - for part in &published { - if let Some(bak) = &part.backup_path { - let _ = fs::remove_file(bak); - } - } - - Ok(stats) -} - -#[cfg(test)] -#[path = "parquet_fundamentals_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/parquet_fundamentals_tests.rs b/tools/curate-etl/src/parquet_fundamentals_tests.rs deleted file mode 100644 index 922f4435..00000000 --- a/tools/curate-etl/src/parquet_fundamentals_tests.rs +++ /dev/null @@ -1,2243 +0,0 @@ -//! Round-trip, schema, partitioning, validation, and atomic rollback tests for -//! `parquet_fundamentals`. - -use std::borrow::Cow; -use std::collections::BTreeMap; -use std::fs::{self, File}; -use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; - -use parquet::basic::{ - Compression, ConvertedType, LogicalType, Repetition, TimeUnit, Type as PhysicalType, -}; -use parquet::column::reader::ColumnReader; -use parquet::file::reader::{FileReader, SerializedFileReader}; - -use super::{ - fundamentals_pit_parquet_schema, write_fundamentals_pit_dataset, FundamentalsPitLatestPeriod, - FundamentalsPitParquetRow, FundamentalsPitWriteOptions, FundamentalsPitWriteStats, - ParquetFundamentalsError, DEFAULT_ZSTD_LEVEL, -}; -use crate::events::{ - partition_year_utc, QmFiling, KNOWN_AT_SOURCE_FILING_TIMESTAMP, KNOWN_AT_SOURCE_STATUTORY_LAG, -}; -use crate::fundamentals::{ - build_fundamentals_rows, build_fundamentals_snapshots, FinancialObservation, FiscalPeriod, - FundamentalsFields, FundamentalsPeriodSlot, FundamentalsSnapshot, FundamentalsTtm, - StatutoryLagVenue, TtmFlowFields, -}; -use crate::split::ymd_to_epoch_days; - -static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0); - -struct TempDirGuard { - path: PathBuf, -} - -impl TempDirGuard { - fn new(label: &str) -> Self { - let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); - let pid = std::process::id(); - let path = std::env::temp_dir().join(format!( - "curate-etl-pq-fundamentals-test-{label}-{pid}-{seq}" - )); - let _ = fs::remove_dir_all(&path); - fs::create_dir_all(&path).expect("create test temp dir"); - Self { path } - } - - fn path(&self) -> &Path { - &self.path - } -} - -impl Drop for TempDirGuard { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.path); - } -} - -fn day(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).expect("valid test date") -} - -fn utc_micros(y: i32, m: u32, d: u32, hour: u8, minute: u8, second: u8, micro: i64) -> i64 { - let epoch_day = day(y, m, d); - let secs = i64::from(epoch_day) * 86_400 - + i64::from(hour) * 3_600 - + i64::from(minute) * 60 - + i64::from(second); - secs * 1_000_000 + micro -} - -fn filing(key: i32, timefiled: &str, form_type: &str) -> QmFiling { - QmFiling { - key, - timefiled: timefiled.to_string(), - form_type: form_type.to_string(), - filing_id: None, - url: None, - } -} - -fn obs( - key: i32, - period_end: i32, - fiscal_period: FiscalPeriod, - currency: &str, - report_date: Option, - fields: FundamentalsFields, -) -> FinancialObservation { - FinancialObservation { - key, - period_end, - fiscal_period, - currency: currency.to_string(), - report_date, - fields, - } -} - -#[derive(Debug, Clone, PartialEq)] -struct DecodedFundamentalsPitRow { - listing_id: i32, - effective_known_at: i64, - known_at_source: String, - has_estimated_lag: bool, - period_end: i32, - fiscal_period: String, - currency: String, - period_known_at: i64, - revenue: Option, - net_income: Option, - operating_cash_flow: Option, - total_assets: Option, - total_equity: Option, - shares_outstanding: Option, - ttm_revenue: Option, - ttm_net_income: Option, - ttm_operating_cash_flow: Option, - ttm_period_end: Option, - ttm_currency: Option, - ttm_has_estimated_lag: Option, -} - -fn read_parquet_rows(path: &Path) -> Vec { - let file = File::open(path).expect("open parquet file"); - let reader = SerializedFileReader::new(file).expect("open parquet reader"); - let meta = reader.metadata(); - let mut out = Vec::new(); - - for rg_idx in 0..meta.num_row_groups() { - let rg_rows = meta.row_group(rg_idx).num_rows() as usize; - let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); - - let read_req_i32 = |col_idx: usize| -> Vec { - let mut vals = Vec::with_capacity(rg_rows); - match rg_reader.get_column_reader(col_idx).expect("col reader") { - ColumnReader::Int32ColumnReader(mut typed) => { - let mut read = 0usize; - while read < rg_rows { - let (n, _, _) = typed - .read_records(rg_rows - read, None, None, &mut vals) - .expect("read req i32"); - assert!(n > 0); - read += n; - } - } - _ => panic!("expected INT32 at col {col_idx}"), - } - vals - }; - - let read_opt_i32 = |col_idx: usize| -> Vec> { - let mut vals = Vec::with_capacity(rg_rows); - let mut defs = Vec::with_capacity(rg_rows); - match rg_reader.get_column_reader(col_idx).expect("col reader") { - ColumnReader::Int32ColumnReader(mut typed) => { - let mut read = 0usize; - while read < rg_rows { - let (n, _, _) = typed - .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) - .expect("read opt i32"); - assert!(n > 0); - read += n; - } - } - _ => panic!("expected INT32 at col {col_idx}"), - } - let mut vi = 0usize; - defs.into_iter() - .map(|d| { - if d == 1 { - let v = vals[vi]; - vi += 1; - Some(v) - } else { - assert_eq!(d, 0); - None - } - }) - .collect() - }; - - let read_req_i64 = |col_idx: usize| -> Vec { - let mut vals = Vec::with_capacity(rg_rows); - match rg_reader.get_column_reader(col_idx).expect("col reader") { - ColumnReader::Int64ColumnReader(mut typed) => { - let mut read = 0usize; - while read < rg_rows { - let (n, _, _) = typed - .read_records(rg_rows - read, None, None, &mut vals) - .expect("read req i64"); - assert!(n > 0); - read += n; - } - } - _ => panic!("expected INT64 at col {col_idx}"), - } - vals - }; - - let read_req_bool = |col_idx: usize| -> Vec { - let mut vals = Vec::with_capacity(rg_rows); - match rg_reader.get_column_reader(col_idx).expect("col reader") { - ColumnReader::BoolColumnReader(mut typed) => { - let mut read = 0usize; - while read < rg_rows { - let (n, _, _) = typed - .read_records(rg_rows - read, None, None, &mut vals) - .expect("read req bool"); - assert!(n > 0); - read += n; - } - } - _ => panic!("expected BOOLEAN at col {col_idx}"), - } - vals - }; - - let read_opt_bool = |col_idx: usize| -> Vec> { - let mut vals = Vec::with_capacity(rg_rows); - let mut defs = Vec::with_capacity(rg_rows); - match rg_reader.get_column_reader(col_idx).expect("col reader") { - ColumnReader::BoolColumnReader(mut typed) => { - let mut read = 0usize; - while read < rg_rows { - let (n, _, _) = typed - .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) - .expect("read opt bool"); - assert!(n > 0); - read += n; - } - } - _ => panic!("expected BOOLEAN at col {col_idx}"), - } - let mut vi = 0usize; - defs.into_iter() - .map(|d| { - if d == 1 { - let v = vals[vi]; - vi += 1; - Some(v) - } else { - assert_eq!(d, 0); - None - } - }) - .collect() - }; - - let read_opt_f64 = |col_idx: usize| -> Vec> { - let mut vals = Vec::with_capacity(rg_rows); - let mut defs = Vec::with_capacity(rg_rows); - match rg_reader.get_column_reader(col_idx).expect("col reader") { - ColumnReader::DoubleColumnReader(mut typed) => { - let mut read = 0usize; - while read < rg_rows { - let (n, _, _) = typed - .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) - .expect("read opt f64"); - assert!(n > 0); - read += n; - } - } - _ => panic!("expected DOUBLE at col {col_idx}"), - } - let mut vi = 0usize; - defs.into_iter() - .map(|d| { - if d == 1 { - let v = vals[vi]; - vi += 1; - Some(v) - } else { - assert_eq!(d, 0); - None - } - }) - .collect() - }; - - let read_req_str = |col_idx: usize| -> Vec { - let mut raw = Vec::with_capacity(rg_rows); - match rg_reader.get_column_reader(col_idx).expect("col reader") { - ColumnReader::ByteArrayColumnReader(mut typed) => { - let mut read = 0usize; - while read < rg_rows { - let (n, _, _) = typed - .read_records(rg_rows - read, None, None, &mut raw) - .expect("read req str"); - assert!(n > 0); - read += n; - } - } - _ => panic!("expected BYTE_ARRAY at col {col_idx}"), - } - raw.iter() - .map(|b| std::str::from_utf8(b.data()).expect("valid utf8").to_string()) - .collect() - }; - - let read_opt_str = |col_idx: usize| -> Vec> { - let mut raw = Vec::with_capacity(rg_rows); - let mut defs = Vec::with_capacity(rg_rows); - match rg_reader.get_column_reader(col_idx).expect("col reader") { - ColumnReader::ByteArrayColumnReader(mut typed) => { - let mut read = 0usize; - while read < rg_rows { - let (n, _, _) = typed - .read_records(rg_rows - read, Some(&mut defs), None, &mut raw) - .expect("read opt str"); - assert!(n > 0); - read += n; - } - } - _ => panic!("expected BYTE_ARRAY at col {col_idx}"), - } - let mut vi = 0usize; - defs.into_iter() - .map(|d| { - if d == 1 { - let s = std::str::from_utf8(raw[vi].data()) - .expect("valid utf8") - .to_string(); - vi += 1; - Some(s) - } else { - assert_eq!(d, 0); - None - } - }) - .collect() - }; - - let listing_id = read_req_i32(0); - let effective_known_at = read_req_i64(1); - let known_at_source = read_req_str(2); - let has_estimated_lag = read_req_bool(3); - let period_end = read_req_i32(4); - let fiscal_period = read_req_str(5); - let currency = read_req_str(6); - let period_known_at = read_req_i64(7); - let revenue = read_opt_f64(8); - let net_income = read_opt_f64(9); - let operating_cash_flow = read_opt_f64(10); - let total_assets = read_opt_f64(11); - let total_equity = read_opt_f64(12); - let shares_outstanding = read_opt_f64(13); - let ttm_revenue = read_opt_f64(14); - let ttm_net_income = read_opt_f64(15); - let ttm_operating_cash_flow = read_opt_f64(16); - let ttm_period_end = read_opt_i32(17); - let ttm_currency = read_opt_str(18); - let ttm_has_estimated_lag = read_opt_bool(19); - - for i in 0..rg_rows { - out.push(DecodedFundamentalsPitRow { - listing_id: listing_id[i], - effective_known_at: effective_known_at[i], - known_at_source: known_at_source[i].clone(), - has_estimated_lag: has_estimated_lag[i], - period_end: period_end[i], - fiscal_period: fiscal_period[i].clone(), - currency: currency[i].clone(), - period_known_at: period_known_at[i], - revenue: revenue[i], - net_income: net_income[i], - operating_cash_flow: operating_cash_flow[i], - total_assets: total_assets[i], - total_equity: total_equity[i], - shares_outstanding: shares_outstanding[i], - ttm_revenue: ttm_revenue[i], - ttm_net_income: ttm_net_income[i], - ttm_operating_cash_flow: ttm_operating_cash_flow[i], - ttm_period_end: ttm_period_end[i], - ttm_currency: ttm_currency[i].clone(), - ttm_has_estimated_lag: ttm_has_estimated_lag[i], - }); - } - } - - out -} - -fn assert_decoded_matches_snapshot_bit_for_bit( - actual: &DecodedFundamentalsPitRow, - snapshot: &FundamentalsSnapshot, -) { - let latest = snapshot - .periods - .first() - .expect("snapshot must have at least one period"); - assert_eq!(actual.listing_id, snapshot.key); - assert_eq!( - actual.effective_known_at, - snapshot.effective_known_at_utc_micros - ); - assert_eq!(actual.known_at_source, snapshot.known_at_source); - assert_eq!(actual.has_estimated_lag, snapshot.has_estimated_lag); - assert_eq!(actual.period_end, latest.period_end); - assert_eq!(actual.fiscal_period, latest.fiscal_period.as_str()); - assert_eq!(actual.currency, latest.currency); - assert_eq!(actual.period_known_at, latest.known_at_utc_micros); - - assert_eq!( - actual.revenue.map(f64::to_bits), - latest.fields.revenue.map(f64::to_bits) - ); - assert_eq!( - actual.net_income.map(f64::to_bits), - latest.fields.net_income.map(f64::to_bits) - ); - assert_eq!( - actual.operating_cash_flow.map(f64::to_bits), - latest.fields.operating_cash_flow.map(f64::to_bits) - ); - assert_eq!( - actual.total_assets.map(f64::to_bits), - latest.fields.total_assets.map(f64::to_bits) - ); - assert_eq!( - actual.total_equity.map(f64::to_bits), - latest.fields.total_equity.map(f64::to_bits) - ); - assert_eq!( - actual.shares_outstanding.map(f64::to_bits), - latest.fields.shares_outstanding.map(f64::to_bits) - ); - - match &snapshot.ttm { - Some(ttm) => { - assert_eq!( - actual.ttm_revenue.map(f64::to_bits), - ttm.flows.revenue.map(f64::to_bits) - ); - assert_eq!( - actual.ttm_net_income.map(f64::to_bits), - ttm.flows.net_income.map(f64::to_bits) - ); - assert_eq!( - actual.ttm_operating_cash_flow.map(f64::to_bits), - ttm.flows.operating_cash_flow.map(f64::to_bits) - ); - assert_eq!(actual.ttm_period_end, Some(ttm.ending_period_end)); - assert_eq!(actual.ttm_currency.as_deref(), Some(ttm.currency.as_str())); - assert_eq!(actual.ttm_has_estimated_lag, Some(ttm.has_estimated_lag)); - } - None => { - assert_eq!(actual.ttm_revenue, None); - assert_eq!(actual.ttm_net_income, None); - assert_eq!(actual.ttm_operating_cash_flow, None); - assert_eq!(actual.ttm_period_end, None); - assert_eq!(actual.ttm_currency, None); - assert_eq!(actual.ttm_has_estimated_lag, None); - } - } -} - -fn assert_no_transient_files(dir: &Path) { - if !dir.exists() { - return; - } - fn walk(dir: &Path) { - for entry in fs::read_dir(dir).expect("read_dir") { - let path = entry.expect("dir entry").path(); - if path.is_dir() { - walk(&path); - } else { - let name = path - .file_name() - .and_then(|s| s.to_str()) - .unwrap_or_default(); - assert!( - !name.ends_with(".tmp") && !name.ends_with(".bak") && name != ".write.lock", - "unexpected transient file left behind: {}", - path.display() - ); - } - } - } - walk(dir); -} - -fn make_row( - listing_id: i32, - effective_known_at_micros: i64, - period_end: i32, - revenue: Option, - ttm: Option, -) -> FundamentalsPitParquetRow { - FundamentalsPitParquetRow::new( - listing_id, - effective_known_at_micros, - Cow::Borrowed(KNOWN_AT_SOURCE_FILING_TIMESTAMP), - false, - FundamentalsPitLatestPeriod { - period_end, - fiscal_period: Cow::Borrowed("Q"), - currency: "USD".to_string(), - period_known_at_micros: effective_known_at_micros, - fields: FundamentalsFields { - revenue, - net_income: revenue.map(|r| r * 0.1), - operating_cash_flow: revenue.map(|r| r * 0.15), - total_assets: Some(500.0), - total_equity: Some(200.0), - shares_outstanding: Some(100.0), - }, - }, - ttm, - ) -} - -#[test] -fn schema_matches_contract_zstd_null_ttm_and_nullable_booleans() { - let tmp = TempDirGuard::new("schema"); - - // 1) Row with no TTM (all 6 ttm_* columns must be null) and some null latest-period fields. - let row_no_ttm = FundamentalsPitParquetRow::new( - 10, - utc_micros(2024, 5, 1, 20, 15, 0, 0), - Cow::Borrowed(KNOWN_AT_SOURCE_FILING_TIMESTAMP), - false, - FundamentalsPitLatestPeriod { - period_end: day(2024, 3, 31), - fiscal_period: Cow::Borrowed("Q"), - currency: "USD".to_string(), - period_known_at_micros: utc_micros(2024, 5, 1, 20, 15, 0, 0), - fields: FundamentalsFields { - revenue: Some(100.0), - net_income: None, - operating_cash_flow: Some(15.0), - total_assets: None, - total_equity: Some(220.0), - shares_outstanding: None, - }, - }, - None, - ); - - // 2) Row with TTM where ttm_has_estimated_lag = Some(false) and all flows present. - let row_ttm_false = FundamentalsPitParquetRow::new( - 10, - utc_micros(2024, 8, 1, 20, 15, 0, 0), - Cow::Borrowed(KNOWN_AT_SOURCE_FILING_TIMESTAMP), - false, - FundamentalsPitLatestPeriod { - period_end: day(2024, 6, 30), - fiscal_period: Cow::Borrowed("Q"), - currency: "USD".to_string(), - period_known_at_micros: utc_micros(2024, 8, 1, 20, 15, 0, 0), - fields: FundamentalsFields { - revenue: Some(120.0), - net_income: Some(12.0), - operating_cash_flow: Some(18.0), - total_assets: Some(560.0), - total_equity: Some(230.0), - shares_outstanding: Some(100.0), - }, - }, - Some(FundamentalsTtm { - ending_period_end: day(2024, 6, 30), - currency: "USD".to_string(), - flows: TtmFlowFields { - revenue: Some(370.0), - net_income: Some(37.0), - operating_cash_flow: Some(55.0), - }, - has_estimated_lag: false, - }), - ); - - // 3) Row with TTM where ttm_has_estimated_lag = Some(true), FY latest period, and partial null TTM flow. - let row_ttm_true = FundamentalsPitParquetRow::new( - 10, - utc_micros(2024, 11, 15, 21, 5, 0, 0), - Cow::Borrowed(KNOWN_AT_SOURCE_STATUTORY_LAG), - true, - FundamentalsPitLatestPeriod { - period_end: day(2024, 9, 30), - fiscal_period: Cow::Borrowed("FY"), - currency: "CAD".to_string(), - period_known_at_micros: utc_micros(2024, 11, 15, 21, 5, 0, 0), - fields: FundamentalsFields { - revenue: Some(450.0), - net_income: Some(45.0), - operating_cash_flow: None, - total_assets: Some(600.0), - total_equity: Some(250.0), - shares_outstanding: Some(105.0), - }, - }, - Some(FundamentalsTtm { - ending_period_end: day(2024, 9, 30), - currency: "CAD".to_string(), - flows: TtmFlowFields { - revenue: Some(450.0), - net_income: None, - operating_cash_flow: Some(60.0), - }, - has_estimated_lag: true, - }), - ); - - let rows = vec![row_no_ttm, row_ttm_false, row_ttm_true]; - let stats = write_fundamentals_pit_dataset( - tmp.path(), - &rows, - FundamentalsPitWriteOptions::default(), - ) - .expect("write schema test dataset"); - assert_eq!(stats.rows_written, 3); - assert_eq!(stats.files_written, 1); - assert_eq!(stats.rows_by_year, BTreeMap::from([(2024, 3)])); - - let path = tmp.path().join("fundamentals_pit/year=2024/part.parquet"); - let reader = SerializedFileReader::new(File::open(&path).expect("open parquet")) - .expect("open parquet reader"); - let meta = reader.metadata(); - let expected_schema = fundamentals_pit_parquet_schema().expect("schema"); - assert_eq!(meta.file_metadata().schema(), expected_schema.as_ref()); - assert_eq!(expected_schema.name(), "fundamentals_pit"); - - let fields = meta.file_metadata().schema().get_fields(); - assert_eq!(fields.len(), 20); - - let expected_cols: [( - &str, - PhysicalType, - Repetition, - Option, - ConvertedType, - ); 20] = [ - ( - "listing_id", - PhysicalType::INT32, - Repetition::REQUIRED, - None, - ConvertedType::NONE, - ), - ( - "effective_known_at", - PhysicalType::INT64, - Repetition::REQUIRED, - Some(LogicalType::timestamp(true, TimeUnit::MICROS)), - ConvertedType::TIMESTAMP_MICROS, - ), - ( - "known_at_source", - PhysicalType::BYTE_ARRAY, - Repetition::REQUIRED, - Some(LogicalType::String), - ConvertedType::UTF8, - ), - ( - "has_estimated_lag", - PhysicalType::BOOLEAN, - Repetition::REQUIRED, - None, - ConvertedType::NONE, - ), - ( - "period_end", - PhysicalType::INT32, - Repetition::REQUIRED, - Some(LogicalType::Date), - ConvertedType::DATE, - ), - ( - "fiscal_period", - PhysicalType::BYTE_ARRAY, - Repetition::REQUIRED, - Some(LogicalType::String), - ConvertedType::UTF8, - ), - ( - "currency", - PhysicalType::BYTE_ARRAY, - Repetition::REQUIRED, - Some(LogicalType::String), - ConvertedType::UTF8, - ), - ( - "period_known_at", - PhysicalType::INT64, - Repetition::REQUIRED, - Some(LogicalType::timestamp(true, TimeUnit::MICROS)), - ConvertedType::TIMESTAMP_MICROS, - ), - ( - "revenue", - PhysicalType::DOUBLE, - Repetition::OPTIONAL, - None, - ConvertedType::NONE, - ), - ( - "net_income", - PhysicalType::DOUBLE, - Repetition::OPTIONAL, - None, - ConvertedType::NONE, - ), - ( - "operating_cash_flow", - PhysicalType::DOUBLE, - Repetition::OPTIONAL, - None, - ConvertedType::NONE, - ), - ( - "total_assets", - PhysicalType::DOUBLE, - Repetition::OPTIONAL, - None, - ConvertedType::NONE, - ), - ( - "total_equity", - PhysicalType::DOUBLE, - Repetition::OPTIONAL, - None, - ConvertedType::NONE, - ), - ( - "shares_outstanding", - PhysicalType::DOUBLE, - Repetition::OPTIONAL, - None, - ConvertedType::NONE, - ), - ( - "ttm_revenue", - PhysicalType::DOUBLE, - Repetition::OPTIONAL, - None, - ConvertedType::NONE, - ), - ( - "ttm_net_income", - PhysicalType::DOUBLE, - Repetition::OPTIONAL, - None, - ConvertedType::NONE, - ), - ( - "ttm_operating_cash_flow", - PhysicalType::DOUBLE, - Repetition::OPTIONAL, - None, - ConvertedType::NONE, - ), - ( - "ttm_period_end", - PhysicalType::INT32, - Repetition::OPTIONAL, - Some(LogicalType::Date), - ConvertedType::DATE, - ), - ( - "ttm_currency", - PhysicalType::BYTE_ARRAY, - Repetition::OPTIONAL, - Some(LogicalType::String), - ConvertedType::UTF8, - ), - ( - "ttm_has_estimated_lag", - PhysicalType::BOOLEAN, - Repetition::OPTIONAL, - None, - ConvertedType::NONE, - ), - ]; - - for (idx, (name, phys, rep, logical, converted)) in expected_cols.into_iter().enumerate() { - let field = &fields[idx]; - assert_eq!(field.name(), name, "column {idx} name"); - assert_eq!(field.get_physical_type(), phys, "column {idx} physical type"); - assert_eq!( - field.get_basic_info().repetition(), - rep, - "column {idx} repetition" - ); - assert_eq!( - field.get_basic_info().logical_type_ref().cloned(), - logical, - "column {idx} logical type" - ); - assert_eq!( - field.get_basic_info().converted_type(), - converted, - "column {idx} converted type" - ); - } - - for rg in meta.row_groups() { - for col in rg.columns() { - assert!( - matches!(col.compression(), Compression::ZSTD(_)), - "column {} must use ZSTD compression", - col.column_path() - ); - } - } - - let decoded = read_parquet_rows(&path); - assert_eq!(decoded.len(), 3); - - // Row 0: no TTM -> all 6 ttm_* columns are None. - assert_eq!(decoded[0].known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); - assert!(!decoded[0].has_estimated_lag); - assert_eq!(decoded[0].revenue, Some(100.0)); - assert_eq!(decoded[0].net_income, None); - assert_eq!(decoded[0].operating_cash_flow, Some(15.0)); - assert_eq!(decoded[0].total_assets, None); - assert_eq!(decoded[0].total_equity, Some(220.0)); - assert_eq!(decoded[0].shares_outstanding, None); - assert_eq!(decoded[0].ttm_revenue, None); - assert_eq!(decoded[0].ttm_net_income, None); - assert_eq!(decoded[0].ttm_operating_cash_flow, None); - assert_eq!(decoded[0].ttm_period_end, None); - assert_eq!(decoded[0].ttm_currency, None); - assert_eq!(decoded[0].ttm_has_estimated_lag, None); - - // Row 1: ttm_has_estimated_lag = Some(false) - assert_eq!(decoded[1].ttm_revenue, Some(370.0)); - assert_eq!(decoded[1].ttm_net_income, Some(37.0)); - assert_eq!(decoded[1].ttm_operating_cash_flow, Some(55.0)); - assert_eq!(decoded[1].ttm_period_end, Some(day(2024, 6, 30))); - assert_eq!(decoded[1].ttm_currency.as_deref(), Some("USD")); - assert_eq!(decoded[1].ttm_has_estimated_lag, Some(false)); - - // Row 2: ttm_has_estimated_lag = Some(true), partial missing TTM flow, statutory lag source. - assert_eq!(decoded[2].known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); - assert!(decoded[2].has_estimated_lag); - assert_eq!(decoded[2].fiscal_period, "FY"); - assert_eq!(decoded[2].currency, "CAD"); - assert_eq!(decoded[2].ttm_revenue, Some(450.0)); - assert_eq!(decoded[2].ttm_net_income, None); - assert_eq!(decoded[2].ttm_operating_cash_flow, Some(60.0)); - assert_eq!(decoded[2].ttm_period_end, Some(day(2024, 9, 30))); - assert_eq!(decoded[2].ttm_currency.as_deref(), Some("CAD")); - assert_eq!(decoded[2].ttm_has_estimated_lag, Some(true)); - - assert_no_transient_files(&tmp.path().join("fundamentals_pit")); -} - -#[test] -fn builder_snapshots_round_trip_bit_for_bit_including_nulls_ttm_and_signed_zero() { - let tmp = TempDirGuard::new("builder-roundtrip-bits"); - - let venues = BTreeMap::from([ - (10_i32, StatutoryLagVenue::UsTsx), - (20_i32, StatutoryLagVenue::TsxvCse), - ]); - - let observations = vec![ - // Listing 10: 5 consecutive quarters (Q1 2023 .. Q1 2024). - // Q1..Q4 2023 all have distinct non-null flow values so Q4 2023's snapshot carries - // three distinct non-null TTM flows (catching any positional TTM column transposition). - // Q1 2024 omits operating_cash_flow so its snapshot has ttm_operating_cash_flow = None - // while ttm_revenue and ttm_net_income remain populated and distinct. - obs( - 10, - day(2023, 3, 31), - FiscalPeriod::Quarterly, - "USD", - Some(day(2023, 5, 2)), - FundamentalsFields { - revenue: Some(95.5), - net_income: Some(9.25), - operating_cash_flow: Some(17.75), - total_assets: Some(960.0), - total_equity: Some(380.0), - shares_outstanding: Some(49_500_000.0), - }, - ), - obs( - 10, - day(2023, 6, 30), - FiscalPeriod::Quarterly, - "USD", - Some(day(2023, 8, 2)), - FundamentalsFields { - revenue: Some(101.25), - net_income: Some(11.5), - operating_cash_flow: Some(19.75), - total_assets: Some(1_000.0), - total_equity: Some(400.0), - shares_outstanding: Some(50_000_000.0), - }, - ), - obs( - 10, - day(2023, 9, 30), - FiscalPeriod::Quarterly, - "USD", - Some(day(2023, 11, 3)), - FundamentalsFields { - revenue: Some(110.5), - net_income: Some(12.25), - operating_cash_flow: Some(21.0), - total_assets: None, - total_equity: Some(415.0), - shares_outstanding: Some(50_100_000.0), - }, - ), - obs( - 10, - day(2023, 12, 31), - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 2, 14)), - FundamentalsFields { - revenue: Some(125.0), - net_income: Some(14.0), - operating_cash_flow: Some(22.5), - total_assets: Some(1_120.0), - total_equity: None, - shares_outstanding: Some(50_200_000.0), - }, - ), - obs( - 10, - day(2024, 3, 31), - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 5, 1)), - FundamentalsFields { - revenue: Some(130.75), - net_income: Some(16.5), - operating_cash_flow: None, - total_assets: Some(1_150.0), - total_equity: Some(440.0), - shares_outstanding: None, - }, - ), - // Listing 20: unlinked observation -> statutory_lag_estimate (+60d for TSXV/CSE), - // ttm == None. - obs( - 20, - day(2024, 3, 31), - FiscalPeriod::Quarterly, - "CAD", - None, - FundamentalsFields { - revenue: Some(42.5), - net_income: Some(-3.5), - operating_cash_flow: None, - total_assets: Some(25.0), - total_equity: Some(12.5), - shares_outstanding: Some(8_000_000.0), - }, - ), - ]; - - let filings = vec![ - filing(10, "2023-05-02T16:05:00 EDT", "10-Q"), - filing(10, "2023-08-02T16:10:00 EDT", "10-Q"), - filing(10, "2023-11-03T16:05:00 EDT", "10-Q"), - filing(10, "2024-02-14T16:15:00 EST", "10-Q"), - filing(10, "2024-05-01T16:20:00 EDT", "10-Q"), - ]; - - let built = build_fundamentals_rows(observations, filings, &venues); - let mut snapshots = build_fundamentals_snapshots(&built.rows, 4).expect("build snapshots"); - assert_eq!(snapshots.len(), 6); - - // Append a direct snapshot carrying signed negative zero (-0.0) vs positive zero (+0.0) in - // statement fields (builder normalizes -0.0; this verifies the Parquet writer preserves exact - // IEEE-754 bit patterns without altering them). - snapshots.push(FundamentalsSnapshot { - key: 30_i32, - effective_known_at_utc_micros: utc_micros(2024, 6, 15, 20, 5, 0, 0), - known_at_source: KNOWN_AT_SOURCE_STATUTORY_LAG, - has_estimated_lag: true, - periods: vec![FundamentalsPeriodSlot { - period_end: day(2024, 3, 31), - fiscal_period: FiscalPeriod::Quarterly, - currency: "CAD".to_string(), - known_at_utc_micros: utc_micros(2024, 6, 15, 20, 5, 0, 0), - known_at_source: KNOWN_AT_SOURCE_STATUTORY_LAG, - has_estimated_lag: true, - fields: FundamentalsFields { - revenue: Some(-0.0_f64), - net_income: Some(0.0_f64), - operating_cash_flow: None, - total_assets: Some(10.0), - total_equity: None, - shares_outstanding: Some(1_000_000.0), - }, - }], - ttm: None, - }); - - let rows_from_ref: Vec = snapshots - .iter() - .map(FundamentalsPitParquetRow::from) - .collect(); - let rows_from_owned: Vec = snapshots - .clone() - .into_iter() - .map(FundamentalsPitParquetRow::from) - .collect(); - assert_eq!(rows_from_ref, rows_from_owned); - - let stats = write_fundamentals_pit_dataset( - tmp.path(), - &rows_from_ref, - FundamentalsPitWriteOptions { - row_group_rows: 2, - zstd_level: DEFAULT_ZSTD_LEVEL, - }, - ) - .expect("write builder snapshots"); - - let expected_by_year = BTreeMap::from([(2023, 3), (2024, 4)]); - assert_eq!(stats.rows_written, 7); - assert_eq!(stats.files_written, 2); - assert_eq!(stats.row_groups_written, 4); - assert_eq!(stats.rows_by_year, expected_by_year); - - let mut total_bytes = 0u64; - for (&year, &expected_count) in &expected_by_year { - let path = tmp - .path() - .join(format!("fundamentals_pit/year={year:04}/part.parquet")); - assert!(path.is_file(), "missing {}", path.display()); - total_bytes += fs::metadata(&path).expect("metadata").len(); - - let decoded = read_parquet_rows(&path); - let expected_snapshots: Vec<&FundamentalsSnapshot> = snapshots - .iter() - .filter(|s| partition_year_utc(s.effective_known_at_utc_micros) == year) - .collect(); - assert_eq!(decoded.len(), expected_count); - assert_eq!(decoded.len(), expected_snapshots.len()); - for (actual_row, snap) in decoded.iter().zip(expected_snapshots.iter()) { - assert_decoded_matches_snapshot_bit_for_bit(actual_row, snap); - } - - if year == 2024 { - // Q4 2023 snapshot (filed 2024-02-14): all three TTM flows present and distinct. - let full_ttm = decoded - .iter() - .find(|r| r.listing_id == 10 && r.period_end == day(2023, 12, 31)) - .expect("listing 10 Q4 2023 row"); - assert_eq!(full_ttm.ttm_revenue, Some(432.25)); - assert_eq!(full_ttm.ttm_net_income, Some(47.0)); - assert_eq!(full_ttm.ttm_operating_cash_flow, Some(81.0)); - assert_eq!(full_ttm.ttm_period_end, Some(day(2023, 12, 31))); - assert_eq!(full_ttm.ttm_currency.as_deref(), Some("USD")); - assert_eq!(full_ttm.ttm_has_estimated_lag, Some(false)); - - // Q1 2024 snapshot (filed 2024-05-01): partial null TTM flow. - let partial_ttm = decoded - .iter() - .find(|r| r.listing_id == 10 && r.period_end == day(2024, 3, 31)) - .expect("listing 10 Q1 2024 row"); - assert_eq!(partial_ttm.ttm_revenue, Some(467.5)); - assert_eq!(partial_ttm.ttm_net_income, Some(54.25)); - assert_eq!(partial_ttm.ttm_operating_cash_flow, None); - assert_eq!(partial_ttm.ttm_period_end, Some(day(2024, 3, 31))); - assert_eq!(partial_ttm.ttm_currency.as_deref(), Some("USD")); - assert_eq!(partial_ttm.ttm_has_estimated_lag, Some(false)); - - // Listing 20: statutory lag provenance and ttm == None. - let est_row = decoded - .iter() - .find(|r| r.listing_id == 20) - .expect("listing 20 row"); - assert_eq!(est_row.known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); - assert!(est_row.has_estimated_lag); - assert_eq!(est_row.ttm_revenue, None); - assert_eq!(est_row.ttm_net_income, None); - assert_eq!(est_row.ttm_operating_cash_flow, None); - assert_eq!(est_row.ttm_period_end, None); - assert_eq!(est_row.ttm_currency, None); - assert_eq!(est_row.ttm_has_estimated_lag, None); - - // Listing 30: exact IEEE-754 -0.0 vs +0.0 bit preservation across Parquet write/read. - let signed_zero_row = decoded - .iter() - .find(|r| r.listing_id == 30) - .expect("listing 30 row"); - assert_eq!( - signed_zero_row.revenue.map(f64::to_bits), - Some((-0.0_f64).to_bits()) - ); - assert_ne!( - signed_zero_row.revenue.map(f64::to_bits), - Some(0.0_f64.to_bits()) - ); - assert_eq!( - signed_zero_row.net_income.map(f64::to_bits), - Some(0.0_f64.to_bits()) - ); - } - } - - assert_eq!(stats.bytes_written, total_bytes); - assert_no_transient_files(&tmp.path().join("fundamentals_pit")); -} - -#[test] -fn restatement_of_q1_after_q2_preserves_q2_on_disk_and_updates_ttm() { - let listing_id = 42_i32; - let venues = BTreeMap::from([(listing_id, StatutoryLagVenue::UsTsx)]); - - let p_2023_q3 = day(2023, 9, 30); - let p_2023_q4 = day(2023, 12, 31); - let p_2024_q1 = day(2024, 3, 31); - let p_2024_q2 = day(2024, 6, 30); - - let initial_filings = vec![ - filing(listing_id, "2023-11-01T16:15:00 EDT", "10-Q"), - filing(listing_id, "2024-02-01T16:15:00 EST", "10-Q"), - filing(listing_id, "2024-05-01T16:15:00 EDT", "10-Q"), - filing(listing_id, "2024-08-01T16:15:00 EDT", "10-Q"), - ]; - let amendment_filing = filing(listing_id, "2024-09-15T17:00:00 EDT", "10-Q/A"); - - let initial_obs = vec![ - obs( - listing_id, - p_2023_q3, - FiscalPeriod::Quarterly, - "USD", - Some(day(2023, 11, 1)), - FundamentalsFields { - revenue: Some(70.0), - net_income: Some(7.0), - operating_cash_flow: Some(10.0), - total_assets: Some(500.0), - total_equity: Some(200.0), - shares_outstanding: Some(100.0), - }, - ), - obs( - listing_id, - p_2023_q4, - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 2, 1)), - FundamentalsFields { - revenue: Some(80.0), - net_income: Some(8.0), - operating_cash_flow: Some(12.0), - total_assets: Some(520.0), - total_equity: Some(210.0), - shares_outstanding: Some(100.0), - }, - ), - obs( - listing_id, - p_2024_q1, - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 5, 1)), - FundamentalsFields { - revenue: Some(100.0), - net_income: Some(10.0), - operating_cash_flow: Some(15.0), - total_assets: Some(540.0), - total_equity: Some(220.0), - shares_outstanding: Some(100.0), - }, - ), - obs( - listing_id, - p_2024_q2, - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 8, 1)), - FundamentalsFields { - revenue: Some(120.0), - net_income: Some(12.0), - operating_cash_flow: Some(18.0), - total_assets: Some(560.0), - total_equity: Some(230.0), - shares_outstanding: Some(100.0), - }, - ), - ]; - - // Late Q1 amendment filed on 2024-09-15 (after Q2's 2024-08-01 filing). - // Restates revenue 100 -> 110 and net_income 10 -> 11, while omitting operating_cash_flow. - let q1_amendment = obs( - listing_id, - p_2024_q1, - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 9, 15)), - FundamentalsFields { - revenue: Some(110.0), - net_income: Some(11.0), - operating_cash_flow: None, - total_assets: None, - total_equity: Some(225.0), - shares_outstanding: None, - }, - ); - - let mut full_obs = initial_obs.clone(); - full_obs.push(q1_amendment); - let mut full_filings = initial_filings.clone(); - full_filings.push(amendment_filing); - - let full_build = build_fundamentals_rows(full_obs, full_filings, &venues); - let full_snaps = build_fundamentals_snapshots(&full_build.rows, 4).expect("full snapshots"); - assert_eq!(full_snaps.len(), 5); - - let baseline_build = build_fundamentals_rows(initial_obs, initial_filings, &venues); - let baseline_snaps = - build_fundamentals_snapshots(&baseline_build.rows, 4).expect("baseline snapshots"); - assert_eq!(baseline_snaps.len(), 4); - - let full_rows_from_ref: Vec = - full_snaps.iter().map(FundamentalsPitParquetRow::from).collect(); - let full_rows_from_owned: Vec = full_snaps - .into_iter() - .map(FundamentalsPitParquetRow::from) - .collect(); - assert_eq!(full_rows_from_ref, full_rows_from_owned); - - let baseline_rows: Vec = baseline_snaps - .iter() - .map(FundamentalsPitParquetRow::from) - .collect(); - - let tmp_full = TempDirGuard::new("restatement-full"); - let tmp_base = TempDirGuard::new("restatement-baseline"); - - let full_stats = write_fundamentals_pit_dataset( - tmp_full.path(), - &full_rows_from_ref, - FundamentalsPitWriteOptions::default(), - ) - .expect("write full dataset"); - assert_eq!(full_stats.rows_written, 5); - assert_eq!(full_stats.files_written, 2); - assert_eq!(full_stats.rows_by_year, BTreeMap::from([(2023, 1), (2024, 4)])); - - let base_stats = write_fundamentals_pit_dataset( - tmp_base.path(), - &baseline_rows, - FundamentalsPitWriteOptions::default(), - ) - .expect("write baseline dataset"); - assert_eq!(base_stats.rows_written, 4); - assert_eq!(base_stats.files_written, 2); - assert_eq!(base_stats.rows_by_year, BTreeMap::from([(2023, 1), (2024, 3)])); - - let mut full_decoded = read_parquet_rows( - &tmp_full - .path() - .join("fundamentals_pit/year=2023/part.parquet"), - ); - full_decoded.extend(read_parquet_rows( - &tmp_full - .path() - .join("fundamentals_pit/year=2024/part.parquet"), - )); - assert_eq!(full_decoded.len(), 5); - - let mut base_decoded = read_parquet_rows( - &tmp_base - .path() - .join("fundamentals_pit/year=2023/part.parquet"), - ); - base_decoded.extend(read_parquet_rows( - &tmp_base - .path() - .join("fundamentals_pit/year=2024/part.parquet"), - )); - assert_eq!(base_decoded.len(), 4); - - let ts_q2 = utc_micros(2024, 8, 1, 20, 15, 0, 0); - let ts_amend = utc_micros(2024, 9, 15, 21, 0, 0, 0); - - // Every earlier row (before the amendment) must match the unamended baseline identically. - assert_eq!(&full_decoded[..4], &base_decoded[..]); - - // Every row at or after Q2 filing must keep Q2 as the latest visible period with unchanged fields. - let post_q2_rows: Vec<&DecodedFundamentalsPitRow> = full_decoded - .iter() - .filter(|r| r.effective_known_at >= ts_q2) - .collect(); - assert_eq!(post_q2_rows.len(), 2); - assert_eq!(post_q2_rows[0].effective_known_at, ts_q2); - assert_eq!(post_q2_rows[1].effective_known_at, ts_amend); - - for row in &post_q2_rows { - assert_eq!(row.listing_id, listing_id); - assert_eq!(row.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); - assert!(!row.has_estimated_lag); - assert_eq!(row.period_end, p_2024_q2); - assert_eq!(row.period_known_at, ts_q2); - assert_eq!(row.fiscal_period, "Q"); - assert_eq!(row.currency, "USD"); - assert_eq!(row.revenue, Some(120.0)); - assert_eq!(row.net_income, Some(12.0)); - assert_eq!(row.operating_cash_flow, Some(18.0)); - assert_eq!(row.total_assets, Some(560.0)); - assert_eq!(row.total_equity, Some(230.0)); - assert_eq!(row.shares_outstanding, Some(100.0)); - assert_eq!(row.ttm_period_end, Some(p_2024_q2)); - assert_eq!(row.ttm_currency.as_deref(), Some("USD")); - assert_eq!(row.ttm_has_estimated_lag, Some(false)); - } - - // At Q2 filing (before amendment): TTM uses original Q1 (revenue=100, net_income=10, ocf=15). - assert_eq!(post_q2_rows[0].ttm_revenue, Some(370.0)); - assert_eq!(post_q2_rows[0].ttm_net_income, Some(37.0)); - assert_eq!(post_q2_rows[0].ttm_operating_cash_flow, Some(55.0)); - - // At Q1 amendment: TTM revenue & net_income update (+10, +1); TTM OCF preserves prior Q1's 15.0. - assert_eq!(post_q2_rows[1].ttm_revenue, Some(380.0)); - assert_eq!(post_q2_rows[1].ttm_net_income, Some(38.0)); - assert_eq!(post_q2_rows[1].ttm_operating_cash_flow, Some(55.0)); - - assert_no_transient_files(&tmp_full.path().join("fundamentals_pit")); - assert_no_transient_files(&tmp_base.path().join("fundamentals_pit")); -} - -#[test] -fn utc_year_partitioning_interleaved_listings_and_midnight_boundary() { - let tmp = TempDirGuard::new("partitioning"); - - // Globally ordered by (listing_id, effective_known_at), with interleaved UTC years across - // multiple listings and timestamps 1 microsecond apart across midnight UTC. - let ts_2023_end = utc_micros(2023, 12, 31, 23, 59, 59, 999_999); - let ts_2024_start = utc_micros(2024, 1, 1, 0, 0, 0, 0); - assert_eq!(partition_year_utc(ts_2023_end), 2023); - assert_eq!(partition_year_utc(ts_2024_start), 2024); - - let rows = vec![ - make_row(1, utc_micros(2023, 5, 1, 14, 0, 0, 0), day(2023, 3, 31), Some(10.0), None), - make_row(1, ts_2023_end, day(2023, 9, 30), Some(11.0), None), - make_row(1, ts_2024_start, day(2023, 12, 31), Some(12.0), None), - make_row(2, utc_micros(2023, 8, 1, 14, 0, 0, 0), day(2023, 6, 30), Some(20.0), None), - make_row(2, utc_micros(2024, 2, 1, 14, 0, 0, 0), day(2023, 12, 31), Some(21.0), None), - make_row(3, utc_micros(2023, 11, 1, 14, 0, 0, 0), day(2023, 9, 30), Some(30.0), None), - make_row(3, utc_micros(2024, 5, 1, 14, 0, 0, 0), day(2024, 3, 31), Some(31.0), None), - ]; - - let stats = write_fundamentals_pit_dataset( - tmp.path(), - &rows, - FundamentalsPitWriteOptions { - row_group_rows: 2, - zstd_level: DEFAULT_ZSTD_LEVEL, - }, - ) - .expect("write partitioned dataset"); - - assert_eq!(stats.rows_written, 7); - assert_eq!(stats.files_written, 2); - // 2023: 4 rows -> 2 row groups; 2024: 3 rows -> 2 row groups - assert_eq!(stats.row_groups_written, 4); - assert_eq!(stats.rows_by_year, BTreeMap::from([(2023, 4), (2024, 3)])); - - let path_2023 = tmp.path().join("fundamentals_pit/year=2023/part.parquet"); - let path_2024 = tmp.path().join("fundamentals_pit/year=2024/part.parquet"); - assert!(path_2023.is_file()); - assert!(path_2024.is_file()); - assert_eq!( - stats.bytes_written, - fs::metadata(&path_2023).expect("meta 2023").len() - + fs::metadata(&path_2024).expect("meta 2024").len() - ); - - let decoded_2023 = read_parquet_rows(&path_2023); - let decoded_2024 = read_parquet_rows(&path_2024); - - assert_eq!(decoded_2023.len(), 4); - assert_eq!(decoded_2024.len(), 3); - - // Verify exact membership and strict sort order by (listing_id, effective_known_at). - for (year, decoded) in [(2023, &decoded_2023), (2024, &decoded_2024)] { - for r in decoded { - assert_eq!(partition_year_utc(r.effective_known_at), year); - } - for pair in decoded.windows(2) { - assert!( - (pair[0].listing_id, pair[0].effective_known_at) - < (pair[1].listing_id, pair[1].effective_known_at), - "year {year} rows must be strictly increasing by (listing_id, effective_known_at)" - ); - } - } - - assert_eq!(decoded_2023[1].effective_known_at, ts_2023_end); - assert_eq!(decoded_2024[0].effective_known_at, ts_2024_start); - assert_no_transient_files(&tmp.path().join("fundamentals_pit")); -} - -#[test] -fn invalid_inputs_return_typed_errors_and_preserve_existing_partitions() { - let tmp = TempDirGuard::new("errors"); - - // Seed an existing 2024 partition and snapshot its exact bytes. - let seed = vec![make_row( - 1, - utc_micros(2024, 3, 1, 15, 0, 0, 0), - day(2023, 12, 31), - Some(50.0), - None, - )]; - write_fundamentals_pit_dataset( - tmp.path(), - &seed, - FundamentalsPitWriteOptions::default(), - ) - .expect("seed existing partition"); - let part_2024 = tmp.path().join("fundamentals_pit/year=2024/part.parquet"); - let before_bytes = fs::read(&part_2024).expect("read seed bytes"); - - let rg1 = FundamentalsPitWriteOptions { - row_group_rows: 1, - zstd_level: DEFAULT_ZSTD_LEVEL, - }; - - // 1. Duplicate (listing_id, effective_known_at) with different payload after a valid row. - let ts_a = utc_micros(2024, 5, 1, 20, 0, 0, 0); - let dup_rows = vec![ - make_row(1, ts_a, day(2024, 3, 31), Some(100.0), None), - make_row(1, ts_a, day(2024, 3, 31), Some(999.0), None), - ]; - let err = write_fundamentals_pit_dataset(tmp.path(), &dup_rows, rg1).unwrap_err(); - assert!( - matches!( - err, - ParquetFundamentalsError::DuplicateRow { - row_index: 1, - listing_id: 1, - effective_known_at_micros, - } if effective_known_at_micros == ts_a - ), - "expected DuplicateRow, got {err:?}" - ); - assert_eq!(fs::read(&part_2024).unwrap(), before_bytes); - assert_no_transient_files(&tmp.path().join("fundamentals_pit")); - - // 2. Unsorted (descending effective_known_at for same listing) after a valid row. - let ts_b = utc_micros(2024, 8, 1, 20, 0, 0, 0); - let unsorted_ts = vec![ - make_row(1, ts_b, day(2024, 6, 30), Some(120.0), None), - make_row(1, ts_a, day(2024, 3, 31), Some(100.0), None), - ]; - let err = write_fundamentals_pit_dataset(tmp.path(), &unsorted_ts, rg1).unwrap_err(); - assert!( - matches!( - err, - ParquetFundamentalsError::UnsortedInput { - row_index: 1, - prev_listing_id: 1, - prev_effective_known_at_micros, - listing_id: 1, - effective_known_at_micros, - } if prev_effective_known_at_micros == ts_b && effective_known_at_micros == ts_a - ), - "expected UnsortedInput, got {err:?}" - ); - assert_eq!(fs::read(&part_2024).unwrap(), before_bytes); - assert_no_transient_files(&tmp.path().join("fundamentals_pit")); - - // 3. Unsorted (descending listing_id) after a valid row. - let unsorted_lid = vec![ - make_row(2, ts_a, day(2024, 3, 31), Some(100.0), None), - make_row(1, ts_b, day(2024, 6, 30), Some(120.0), None), - ]; - let err = write_fundamentals_pit_dataset(tmp.path(), &unsorted_lid, rg1).unwrap_err(); - assert!( - matches!( - err, - ParquetFundamentalsError::UnsortedInput { - row_index: 1, - prev_listing_id: 2, - listing_id: 1, - .. - } - ), - "expected UnsortedInput for descending listing_id, got {err:?}" - ); - assert_eq!(fs::read(&part_2024).unwrap(), before_bytes); - assert_no_transient_files(&tmp.path().join("fundamentals_pit")); - - // 4. Empty periods snapshot (at row_index 0 and at row_index 1 after a flushed row group). - let empty_snap = FundamentalsSnapshot { - key: 1_i32, - effective_known_at_utc_micros: ts_b, - known_at_source: KNOWN_AT_SOURCE_FILING_TIMESTAMP, - has_estimated_lag: false, - periods: Vec::new(), - ttm: None, - }; - let empty_row = FundamentalsPitParquetRow::from(&empty_snap); - assert!(empty_row.latest_period().is_none()); - - let tmp_fresh = TempDirGuard::new("empty-periods-first"); - let err_first = write_fundamentals_pit_dataset(tmp_fresh.path(), &[empty_row.clone()], rg1) - .unwrap_err(); - assert!( - matches!( - err_first, - ParquetFundamentalsError::EmptyPeriods { - row_index: 0, - listing_id: 1, - effective_known_at_micros, - } if effective_known_at_micros == ts_b - ), - "expected EmptyPeriods at row 0, got {err_first:?}" - ); - assert!(!tmp_fresh.path().join("fundamentals_pit").exists()); - - let mixed = vec![ - make_row(1, ts_a, day(2024, 3, 31), Some(100.0), None), - empty_row, - ]; - let err_second = write_fundamentals_pit_dataset(tmp.path(), &mixed, rg1).unwrap_err(); - assert!( - matches!( - err_second, - ParquetFundamentalsError::EmptyPeriods { - row_index: 1, - listing_id: 1, - effective_known_at_micros, - } if effective_known_at_micros == ts_b - ), - "expected EmptyPeriods at row 1, got {err_second:?}" - ); - assert_eq!(fs::read(&part_2024).unwrap(), before_bytes); - assert_no_transient_files(&tmp.path().join("fundamentals_pit")); - - // 5. Empty input does not create directory or touch existing partitions. - let tmp_empty = TempDirGuard::new("empty-input"); - let empty_stats = write_fundamentals_pit_dataset( - tmp_empty.path(), - std::iter::empty::(), - FundamentalsPitWriteOptions::default(), - ) - .expect("empty input succeeds"); - assert_eq!(empty_stats, FundamentalsPitWriteStats::default()); - assert!(!tmp_empty.path().join("fundamentals_pit").exists()); -} - -#[test] -fn publish_failure_on_later_year_rolls_back_replaced_and_new_partitions() { - let tmp = TempDirGuard::new("rollback"); - - // Seed an existing 2023 partition. - let seed = vec![make_row( - 1, - utc_micros(2023, 5, 1, 14, 0, 0, 0), - day(2023, 3, 31), - Some(50.0), - None, - )]; - write_fundamentals_pit_dataset( - tmp.path(), - &seed, - FundamentalsPitWriteOptions::default(), - ) - .expect("seed 2023"); - - let part_2023 = tmp.path().join("fundamentals_pit/year=2023/part.parquet"); - let part_2024 = tmp.path().join("fundamentals_pit/year=2024/part.parquet"); - let part_2025 = tmp.path().join("fundamentals_pit/year=2025/part.parquet"); - let before_2023 = fs::read(&part_2023).expect("read seed 2023"); - - // Occupy year=2025/part.parquet with a directory so rename fails after 2023 (replaced) - // and 2024 (newly created) have been renamed into place. - fs::create_dir_all(&part_2025).expect("create blocking directory at year=2025/part.parquet"); - - let rows = vec![ - make_row(1, utc_micros(2023, 8, 1, 14, 0, 0, 0), day(2023, 6, 30), Some(75.0), None), - make_row(1, utc_micros(2024, 5, 1, 14, 0, 0, 0), day(2024, 3, 31), Some(100.0), None), - make_row(1, utc_micros(2025, 5, 1, 14, 0, 0, 0), day(2025, 3, 31), Some(125.0), None), - ]; - - let err = write_fundamentals_pit_dataset( - tmp.path(), - &rows, - FundamentalsPitWriteOptions::default(), - ) - .unwrap_err(); - assert!( - matches!(err, ParquetFundamentalsError::Io { ref path, .. } if path == &part_2025), - "expected Io error at year=2025/part.parquet, got {err:?}" - ); - - // 2023 must be restored byte for byte; 2024 must be removed; no transient files remain. - assert_eq!(fs::read(&part_2023).expect("read restored 2023"), before_2023); - assert!( - !part_2024.exists(), - "newly published 2024 partition must be removed on rollback" - ); - assert!(part_2025.is_dir()); - assert_no_transient_files(&tmp.path().join("fundamentals_pit")); -} - -// --------------------------------------------------------------------------------------------- -// QA additions (T-143): full-row round-trip equality, builder estimated-lag provenance, -// partial-rewrite semantics, deterministic bytes, and remaining typed validation errors. -// --------------------------------------------------------------------------------------------- - -/// Expected decoded form of a row: what the reader must see after a write/read round trip. -fn expected_decoded(row: &FundamentalsPitParquetRow) -> DecodedFundamentalsPitRow { - let latest = row - .latest_period() - .expect("expected row must have a latest period"); - let ttm = row.ttm.as_ref(); - DecodedFundamentalsPitRow { - listing_id: row.listing_id, - effective_known_at: row.effective_known_at_micros, - known_at_source: row.known_at_source.to_string(), - has_estimated_lag: row.has_estimated_lag, - period_end: latest.period_end, - fiscal_period: latest.fiscal_period.to_string(), - currency: latest.currency.clone(), - period_known_at: latest.period_known_at_micros, - revenue: latest.fields.revenue, - net_income: latest.fields.net_income, - operating_cash_flow: latest.fields.operating_cash_flow, - total_assets: latest.fields.total_assets, - total_equity: latest.fields.total_equity, - shares_outstanding: latest.fields.shares_outstanding, - ttm_revenue: ttm.and_then(|t| t.flows.revenue), - ttm_net_income: ttm.and_then(|t| t.flows.net_income), - ttm_operating_cash_flow: ttm.and_then(|t| t.flows.operating_cash_flow), - ttm_period_end: ttm.map(|t| t.ending_period_end), - ttm_currency: ttm.map(|t| t.currency.clone()), - ttm_has_estimated_lag: ttm.map(|t| t.has_estimated_lag), - } -} - -fn read_year(out_dir: &Path, year: i32) -> Vec { - read_parquet_rows(&out_dir.join(format!("fundamentals_pit/year={year}/part.parquet"))) -} - -fn list_year_dirs(out_dir: &Path) -> Vec { - let mut names: Vec = fs::read_dir(out_dir.join("fundamentals_pit")) - .expect("read dataset dir") - .map(|e| e.expect("entry").file_name().to_string_lossy().into_owned()) - .filter(|n| n.starts_with("year=")) - .collect(); - names.sort(); - names -} - -/// Deterministic LCG so fixtures are reproducible without an RNG crate. -struct Lcg(u64); - -impl Lcg { - fn next_u32(&mut self) -> u32 { - self.0 = self - .0 - .wrapping_mul(6_364_136_223_846_793_005) - .wrapping_add(1_442_695_040_888_963_407); - (self.0 >> 33) as u32 - } - fn chance(&mut self, pct: u32) -> bool { - self.next_u32() % 100 < pct - } - fn opt(&mut self, pct_null: u32, v: f64) -> Option { - if self.chance(pct_null) { - None - } else { - Some(v) - } - } -} - -#[test] -fn partition_files_contain_exact_expected_row_sequence_per_year() { - let tmp = TempDirGuard::new("qa-partition-exact"); - let ttm = |end: i32, rev: f64| FundamentalsTtm { - ending_period_end: end, - currency: "USD".to_string(), - flows: TtmFlowFields { - revenue: Some(rev), - net_income: None, - operating_cash_flow: Some(rev / 2.0), - }, - has_estimated_lag: false, - }; - let ts_2023_end = utc_micros(2023, 12, 31, 23, 59, 59, 999_999); - let ts_2024_start = utc_micros(2024, 1, 1, 0, 0, 0, 0); - let rows = vec![ - make_row( - 1, - utc_micros(2023, 5, 1, 14, 0, 0, 0), - day(2023, 3, 31), - Some(10.0), - None, - ), - make_row( - 1, - ts_2023_end, - day(2023, 9, 30), - Some(11.0), - Some(ttm(day(2023, 9, 30), 40.0)), - ), - make_row( - 1, - ts_2024_start, - day(2023, 12, 31), - Some(12.0), - Some(ttm(day(2023, 12, 31), 44.0)), - ), - make_row( - 2, - utc_micros(2023, 8, 1, 14, 0, 0, 0), - day(2023, 6, 30), - None, - None, - ), - make_row( - 2, - utc_micros(2024, 2, 1, 14, 0, 0, 0), - day(2023, 12, 31), - Some(21.0), - None, - ), - make_row( - 3, - utc_micros(2023, 11, 1, 14, 0, 0, 0), - day(2023, 9, 30), - Some(30.0), - None, - ), - make_row( - 3, - utc_micros(2024, 5, 1, 14, 0, 0, 0), - day(2024, 3, 31), - Some(31.0), - Some(ttm(day(2024, 3, 31), 120.0)), - ), - ]; - - write_fundamentals_pit_dataset( - tmp.path(), - &rows, - FundamentalsPitWriteOptions { - row_group_rows: 2, - zstd_level: DEFAULT_ZSTD_LEVEL, - }, - ) - .expect("write"); - - let expected_2023: Vec<_> = [0, 1, 3, 5] - .iter() - .map(|&i| expected_decoded(&rows[i])) - .collect(); - let expected_2024: Vec<_> = [2, 4, 6] - .iter() - .map(|&i| expected_decoded(&rows[i])) - .collect(); - assert_eq!(list_year_dirs(tmp.path()), vec!["year=2023", "year=2024"]); - assert_eq!(read_year(tmp.path(), 2023), expected_2023); - assert_eq!(read_year(tmp.path(), 2024), expected_2024); -} - -#[test] -fn seeded_mixed_null_patterns_round_trip_across_many_row_groups() { - let tmp = TempDirGuard::new("qa-seeded"); - let mut rng = Lcg(0x5EED_1430); - let mut rows = Vec::new(); - for listing_id in 1..=9_i32 { - for q in 0..12_i32 { - // One quarter apart; spans 2021..=2023 so multiple partitions get interleaved. - let ts = utc_micros( - 2021 + q / 4, - (q % 4) as u32 * 3 + 2, - 10, - 20, - 30, - 0, - i64::from(listing_id), - ); - let period_end = day(2021 + q / 4, (q % 4) as u32 * 3 + 1, 1); - let base = f64::from(listing_id * 1000 + q); - let estimated = rng.chance(30); - let currency = if rng.chance(20) { "CAD" } else { "USD" }; - let ttm = if rng.chance(40) { - None - } else { - Some(FundamentalsTtm { - ending_period_end: period_end, - currency: currency.to_string(), - flows: TtmFlowFields { - revenue: rng.opt(25, base * 4.0), - net_income: rng.opt(25, -base * 0.25), - operating_cash_flow: rng.opt(25, 0.0), - }, - has_estimated_lag: rng.chance(50), - }) - }; - rows.push(FundamentalsPitParquetRow::new( - listing_id, - ts, - Cow::Borrowed(if estimated { - KNOWN_AT_SOURCE_STATUTORY_LAG - } else { - KNOWN_AT_SOURCE_FILING_TIMESTAMP - }), - estimated, - FundamentalsPitLatestPeriod { - period_end, - fiscal_period: Cow::Borrowed(if q % 4 == 3 { "FY" } else { "Q" }), - currency: currency.to_string(), - period_known_at_micros: ts - 1, - fields: FundamentalsFields { - revenue: rng.opt(20, base), - net_income: rng.opt(20, -base / 10.0), - operating_cash_flow: rng.opt(20, base / 7.0), - total_assets: rng.opt(20, base * 5.0), - total_equity: rng.opt(20, base * 2.0), - shares_outstanding: rng.opt(20, 1.0e9), - }, - }, - ttm, - )); - } - } - // Sanity: the fixture really exercises all-null and all-present TTM in the same file. - assert!(rows.iter().any(|r| r.ttm.is_none())); - assert!(rows - .iter() - .any(|r| r.ttm.as_ref().is_some_and(|t| t.flows.revenue.is_none()))); - - let stats = write_fundamentals_pit_dataset( - tmp.path(), - &rows, - FundamentalsPitWriteOptions { - row_group_rows: 5, - zstd_level: 1, - }, - ) - .expect("write seeded dataset"); - assert_eq!(stats.rows_written, rows.len()); - assert_eq!( - stats.rows_by_year, - BTreeMap::from([(2021, 36), (2022, 36), (2023, 36)]) - ); - // 36 rows per year at 5 rows per group -> 8 groups per year. - assert_eq!(stats.row_groups_written, 24); - - for year in 2021..=2023 { - let expected: Vec<_> = rows - .iter() - .filter(|r| partition_year_utc(r.effective_known_at_micros) == year) - .map(expected_decoded) - .collect(); - assert_eq!(read_year(tmp.path(), year), expected, "year {year}"); - } - assert_no_transient_files(&tmp.path().join("fundamentals_pit")); -} - -#[test] -fn builder_statutory_lag_snapshots_keep_estimated_provenance_on_disk() { - // Listing 7 (TSXV/CSE venue) files Q1 via a 10-Q; Q2 has no filing and no report date, - // so its known_at falls back to period_end + 60d at 16:05 America/Toronto. - let listing_id = 7_i32; - let venues = BTreeMap::from([(listing_id, StatutoryLagVenue::TsxvCse)]); - let p_q1 = day(2024, 3, 31); - let p_q2 = day(2024, 6, 30); - let fields = |rev: f64| FundamentalsFields { - revenue: Some(rev), - net_income: Some(rev / 10.0), - operating_cash_flow: None, - total_assets: Some(900.0), - total_equity: Some(400.0), - shares_outstanding: Some(50.0), - }; - let observations = vec![ - obs( - listing_id, - p_q1, - FiscalPeriod::Quarterly, - "CAD", - None, - fields(100.0), - ), - obs( - listing_id, - p_q2, - FiscalPeriod::Quarterly, - "CAD", - None, - fields(130.0), - ), - ]; - let filings = vec![filing(listing_id, "2024-05-10T16:30:00 EDT", "10-Q")]; - - let build = build_fundamentals_rows(observations, filings, &venues); - let snaps = build_fundamentals_snapshots(&build.rows, 4).expect("snapshots"); - assert_eq!(snaps.len(), 2); - let rows: Vec = - snaps.iter().map(FundamentalsPitParquetRow::from).collect(); - - let tmp = TempDirGuard::new("qa-estimated"); - write_fundamentals_pit_dataset(tmp.path(), &rows, FundamentalsPitWriteOptions::default()) - .expect("write"); - let decoded = read_year(tmp.path(), 2024); - assert_eq!( - decoded, - rows.iter().map(expected_decoded).collect::>() - ); - - // Q1: filing-backed, at the 10-Q's UTC timestamp. - let ts_q1 = utc_micros(2024, 5, 10, 20, 30, 0, 0); - assert_eq!(decoded[0].effective_known_at, ts_q1); - assert_eq!(decoded[0].known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); - assert!(!decoded[0].has_estimated_lag); - assert_eq!(decoded[0].period_end, p_q1); - assert_eq!(decoded[0].period_known_at, ts_q1); - assert_eq!(decoded[0].currency, "CAD"); - - // Q2: estimated, 2024-06-30 + 60d = 2024-08-29 16:05 EDT = 20:05 UTC. - let ts_q2_est = utc_micros(2024, 8, 29, 20, 5, 0, 0); - assert_eq!(decoded[1].effective_known_at, ts_q2_est); - assert_eq!(decoded[1].known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); - assert!(decoded[1].has_estimated_lag); - assert_eq!(decoded[1].period_end, p_q2); - assert_eq!(decoded[1].period_known_at, ts_q2_est); - assert_eq!(decoded[1].revenue, Some(130.0)); - assert_eq!(decoded[1].operating_cash_flow, None); - // Only two quarters exist, so TTM is unavailable and every ttm_* column is null. - for r in &decoded { - assert_eq!(r.ttm_revenue, None); - assert_eq!(r.ttm_net_income, None); - assert_eq!(r.ttm_operating_cash_flow, None); - assert_eq!(r.ttm_period_end, None); - assert_eq!(r.ttm_currency, None); - assert_eq!(r.ttm_has_estimated_lag, None); - } -} - -#[test] -fn rewrite_replaces_only_years_present_in_new_input() { - let tmp = TempDirGuard::new("qa-rewrite"); - let first = vec![ - make_row( - 1, - utc_micros(2023, 5, 1, 14, 0, 0, 0), - day(2023, 3, 31), - Some(10.0), - None, - ), - make_row( - 1, - utc_micros(2024, 5, 1, 14, 0, 0, 0), - day(2024, 3, 31), - Some(20.0), - None, - ), - ]; - write_fundamentals_pit_dataset(tmp.path(), &first, FundamentalsPitWriteOptions::default()) - .expect("first write"); - let part_2023 = tmp.path().join("fundamentals_pit/year=2023/part.parquet"); - let bytes_2023 = fs::read(&part_2023).expect("read 2023"); - - let second = vec![ - make_row( - 5, - utc_micros(2024, 2, 1, 14, 0, 0, 0), - day(2023, 12, 31), - Some(55.0), - None, - ), - make_row( - 5, - utc_micros(2024, 6, 1, 14, 0, 0, 0), - day(2024, 3, 31), - Some(56.0), - None, - ), - ]; - let stats = - write_fundamentals_pit_dataset(tmp.path(), &second, FundamentalsPitWriteOptions::default()) - .expect("second write"); - assert_eq!(stats.rows_by_year, BTreeMap::from([(2024, 2)])); - - // 2024 is fully replaced (no merge with old rows); 2023 is untouched byte for byte. - assert_eq!( - read_year(tmp.path(), 2024), - second.iter().map(expected_decoded).collect::>() - ); - assert_eq!(fs::read(&part_2023).expect("reread 2023"), bytes_2023); - assert_no_transient_files(&tmp.path().join("fundamentals_pit")); -} - -#[test] -fn identical_input_produces_byte_identical_partitions() { - let rows = vec![ - make_row( - 1, - utc_micros(2023, 5, 1, 14, 0, 0, 0), - day(2023, 3, 31), - Some(10.0), - None, - ), - make_row( - 2, - utc_micros(2024, 5, 1, 14, 0, 0, 0), - day(2024, 3, 31), - None, - None, - ), - ]; - let a = TempDirGuard::new("qa-determinism-a"); - let b = TempDirGuard::new("qa-determinism-b"); - let opts = FundamentalsPitWriteOptions { - row_group_rows: 1, - zstd_level: DEFAULT_ZSTD_LEVEL, - }; - write_fundamentals_pit_dataset(a.path(), &rows, opts).expect("write a"); - write_fundamentals_pit_dataset(b.path(), &rows, opts).expect("write b"); - for year in [2023, 2024] { - let rel = format!("fundamentals_pit/year={year}/part.parquet"); - assert_eq!( - fs::read(a.path().join(&rel)).expect("read a"), - fs::read(b.path().join(&rel)).expect("read b"), - "year {year} bytes differ between identical runs" - ); - } -} - -#[test] -fn remaining_validation_errors_are_typed_and_publish_nothing() { - let ts = utc_micros(2024, 5, 1, 20, 0, 0, 0); - let valid = make_row(1, ts - 1, day(2024, 3, 31), Some(1.0), None); - let defaults = FundamentalsPitWriteOptions::default(); - - let run = |label: &str, bad: FundamentalsPitParquetRow, opts: FundamentalsPitWriteOptions| { - let tmp = TempDirGuard::new(label); - let err = write_fundamentals_pit_dataset(tmp.path(), [valid.clone(), bad], opts) - .expect_err("invalid input must fail"); - let year_dir = tmp.path().join("fundamentals_pit/year=2024"); - assert!( - !year_dir.join("part.parquet").exists(), - "{label}: partial file published" - ); - assert_no_transient_files(&tmp.path().join("fundamentals_pit")); - err - }; - - let mut nan_row = make_row(1, ts, day(2024, 3, 31), Some(f64::NAN), None); - nan_row.has_estimated_lag = true; - let err = run("qa-nan", nan_row, defaults); - assert!( - matches!( - err, - ParquetFundamentalsError::NonFiniteValue { - row_index: 1, - field: "revenue", - .. - } - ), - "got {err:?}" - ); - - let inf_ttm = make_row( - 1, - ts, - day(2024, 3, 31), - Some(1.0), - Some(FundamentalsTtm { - ending_period_end: day(2024, 3, 31), - currency: "USD".to_string(), - flows: TtmFlowFields { - revenue: Some(1.0), - net_income: None, - operating_cash_flow: Some(f64::INFINITY), - }, - has_estimated_lag: false, - }), - ); - let err = run("qa-inf-ttm", inf_ttm, defaults); - assert!( - matches!( - err, - ParquetFundamentalsError::NonFiniteValue { - field: "ttm_operating_cash_flow", - .. - } - ), - "got {err:?}" - ); - - let mut blank_source = make_row(1, ts, day(2024, 3, 31), Some(1.0), None); - blank_source.known_at_source = Cow::Borrowed(" "); - let err = run("qa-blank-source", blank_source, defaults); - assert!( - matches!( - err, - ParquetFundamentalsError::EmptyKnownAtSource { row_index: 1, .. } - ), - "got {err:?}" - ); - - let mut invalid_source = make_row(1, ts, day(2024, 3, 31), Some(1.0), None); - invalid_source.known_at_source = Cow::Borrowed("manual_override"); - let err = run("qa-invalid-source", invalid_source, defaults); - assert!( - matches!( - err, - ParquetFundamentalsError::InvalidKnownAtSource { - row_index: 1, - ref value, - .. - } if value == "manual_override" - ), - "got {err:?}" - ); - - let mut padded_source = make_row(1, ts, day(2024, 3, 31), Some(1.0), None); - padded_source.known_at_source = Cow::Borrowed(" filing_timestamp "); - let err = run("qa-padded-source", padded_source, defaults); - assert!( - matches!( - err, - ParquetFundamentalsError::InvalidKnownAtSource { - row_index: 1, - ref value, - .. - } if value == " filing_timestamp " - ), - "got {err:?}" - ); - - let blank_ttm_currency = make_row( - 1, - ts, - day(2024, 3, 31), - Some(1.0), - Some(FundamentalsTtm { - ending_period_end: day(2024, 3, 31), - currency: String::new(), - flows: TtmFlowFields { - revenue: None, - net_income: None, - operating_cash_flow: None, - }, - has_estimated_lag: false, - }), - ); - let err = run("qa-blank-ttm-ccy", blank_ttm_currency, defaults); - assert!( - matches!( - err, - ParquetFundamentalsError::EmptyTtmCurrency { row_index: 1, .. } - ), - "got {err:?}" - ); - - let blank_currency = FundamentalsPitParquetRow::new( - 1, - ts, - Cow::Borrowed(KNOWN_AT_SOURCE_FILING_TIMESTAMP), - false, - FundamentalsPitLatestPeriod { - period_end: day(2024, 3, 31), - fiscal_period: Cow::Borrowed("Q"), - currency: String::new(), - period_known_at_micros: ts, - fields: FundamentalsFields { - revenue: None, - net_income: None, - operating_cash_flow: None, - total_assets: None, - total_equity: None, - shares_outstanding: None, - }, - }, - None, - ); - let err = run("qa-blank-ccy", blank_currency, defaults); - assert!( - matches!( - err, - ParquetFundamentalsError::EmptyCurrency { row_index: 1, .. } - ), - "got {err:?}" - ); - - // Year 2201 is above MAX_PARQUET_YEAR (2200). - let far_future = make_row( - 1, - utc_micros(2201, 1, 1, 0, 0, 0, 0), - day(2024, 3, 31), - Some(1.0), - None, - ); - let err = run("qa-year-range", far_future, defaults); - assert!( - matches!( - err, - ParquetFundamentalsError::PartitionYearOutOfRange { - row_index: 1, - year: 2201, - .. - } - ), - "got {err:?}" - ); - - // Option validation happens before any filesystem side effects. - let tmp = TempDirGuard::new("qa-bad-options"); - let err = write_fundamentals_pit_dataset( - tmp.path(), - [valid.clone()], - FundamentalsPitWriteOptions { - row_group_rows: 0, - zstd_level: DEFAULT_ZSTD_LEVEL, - }, - ) - .unwrap_err(); - assert!( - matches!(err, ParquetFundamentalsError::InvalidRowGroupRows), - "got {err:?}" - ); - let err = write_fundamentals_pit_dataset( - tmp.path(), - [valid], - FundamentalsPitWriteOptions { - row_group_rows: 1, - zstd_level: 99, - }, - ) - .unwrap_err(); - assert!( - matches!( - err, - ParquetFundamentalsError::InvalidZstdLevel { level: 99 } - ), - "got {err:?}" - ); - assert!(!tmp.path().join("fundamentals_pit").exists()); -} diff --git a/tools/curate-etl/src/parquet_macro.rs b/tools/curate-etl/src/parquet_macro.rs deleted file mode 100644 index d2a21f3e..00000000 --- a/tools/curate-etl/src/parquet_macro.rs +++ /dev/null @@ -1,776 +0,0 @@ -//! Streaming, atomic Zstd Parquet writer for `macro`. -//! -//! Writes `/macro/part.parquet` matching the 6-column contract schema in -//! `design/DATA-CONTRACTS.md` (§3A): -//! -//! 1. `country_iso` (`BYTE_ARRAY`, `REQUIRED`, `STRING`) -//! 2. `indicator` (`BYTE_ARRAY`, `REQUIRED`, `STRING`) -//! 3. `period_date` (`INT32`, `REQUIRED`, `DATE`) -//! 4. `known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`) -//! 5. `known_at_source` (`BYTE_ARRAY`, `REQUIRED`, `STRING`) -//! 6. `value` (`DOUBLE`, `REQUIRED`) -//! -//! ## Timestamp Units & Provenance -//! [`crate::macro_series::MacroRow::known_at`] is already in UTC microseconds since -//! `1970-01-01T00:00:00Z` (`00:00:00 UTC` of `period_date + lag_days`), so -//! `From<&MacroRow>` copies it directly into [`MacroParquetRow::known_at_micros`] -//! without unit conversion and preserves `known_at_source` and `value` bit-for-bit. - -use std::borrow::{Borrow, Cow}; -use std::cmp::Ordering; -use std::error::Error; -use std::fmt; -use std::fs::{self, File}; -use std::io::{self, BufWriter, Write}; -use std::path::{Path, PathBuf}; -use std::sync::Arc; -use std::time::Duration; - -use parquet::basic::{Compression, LogicalType, Repetition, TimeUnit, Type as PhysicalType, ZstdLevel}; -use parquet::data_type::ByteArray; -use parquet::errors::ParquetError; -use parquet::file::properties::{WriterProperties, WriterPropertiesPtr}; -use parquet::file::writer::SerializedFileWriter; -use parquet::schema::types::{ColumnPath, Type, TypePtr}; - -use crate::macro_series::MacroRow; -use crate::parquet_publish::{ - create_backup_preserving_live, create_exclusive_tmp_file, dataset_mutex, next_run_id, - write_f64_col, write_i32_col, write_i64_col, write_interned_str_col, DatasetFileLock, - PublishIoError, StagingFileGuard, StringInterner, DEFAULT_LOCK_TIMEOUT, - FILE_BUF_CAPACITY_BYTES, STRING_WRITE_BATCH_ROWS, -}; -pub use crate::parquet_publish::{RollbackFailure, DEFAULT_ROW_GROUP_ROWS, DEFAULT_ZSTD_LEVEL}; - -/// Single `macro` row matching the `design/DATA-CONTRACTS.md` (§3A) Parquet schema. -#[derive(Debug, Clone, PartialEq)] -pub struct MacroParquetRow { - pub country_iso: Cow<'static, str>, - pub indicator: Cow<'static, str>, - /// Observation period date as days since `1970-01-01` (UTC Gregorian). - pub period_date: i32, - /// Estimated point-in-time availability timestamp in UTC microseconds since - /// `1970-01-01T00:00:00Z`. - pub known_at_micros: i64, - pub known_at_source: Cow<'static, str>, - pub value: f64, -} - -impl> From<&MacroRow> for MacroParquetRow { - #[inline] - fn from(row: &MacroRow) -> Self { - Self { - country_iso: Cow::Owned(row.country_iso.as_ref().to_owned()), - indicator: Cow::Owned(row.indicator.as_ref().to_owned()), - period_date: row.period_date, - // MacroRow.known_at is already UTC epoch microseconds. - known_at_micros: row.known_at, - known_at_source: Cow::Borrowed(row.known_at_source), - value: row.value, - } - } -} - -/// Configuration for [`write_macro_dataset`]. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct MacroWriteOptions { - pub row_group_rows: usize, - pub zstd_level: i32, -} - -impl Default for MacroWriteOptions { - fn default() -> Self { - Self { - row_group_rows: DEFAULT_ROW_GROUP_ROWS, - zstd_level: DEFAULT_ZSTD_LEVEL, - } - } -} - -/// Accounting summary returned by [`write_macro_dataset`]. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct MacroWriteStats { - pub rows_written: usize, - pub files_written: usize, - pub row_groups_written: usize, - pub bytes_written: u64, -} - -/// Typed error returned by [`write_macro_dataset`]. -#[derive(Debug)] -pub enum ParquetMacroError { - InvalidRowGroupRows, - InvalidZstdLevel { - level: i32, - }, - UnsortedInput { - prev_country_iso: String, - prev_indicator: String, - prev_period_date: i32, - country_iso: String, - indicator: String, - period_date: i32, - }, - DuplicateKey { - country_iso: String, - indicator: String, - period_date: i32, - }, - EmptyCountryIso { - indicator: String, - period_date: i32, - }, - EmptyIndicator { - country_iso: String, - period_date: i32, - }, - EmptyKnownAtSource { - country_iso: String, - indicator: String, - period_date: i32, - }, - InvalidValue { - country_iso: String, - indicator: String, - period_date: i32, - value: f64, - }, - LockTimeout { - path: PathBuf, - waited: Duration, - }, - RollbackFailed { - cause: Box, - failures: Vec, - }, - Io { - path: PathBuf, - source: io::Error, - }, - Parquet { - path: PathBuf, - source: ParquetError, - }, -} - -impl fmt::Display for ParquetMacroError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::InvalidRowGroupRows => { - write!(f, "invalid row_group_rows: must be greater than 0") - } - Self::InvalidZstdLevel { level } => { - write!(f, "invalid Zstd compression level: {level}") - } - Self::UnsortedInput { - prev_country_iso, - prev_indicator, - prev_period_date, - country_iso, - indicator, - period_date, - } => write!( - f, - "unsorted input: ({country_iso}, {indicator}, {period_date}) follows ({prev_country_iso}, {prev_indicator}, {prev_period_date})" - ), - Self::DuplicateKey { - country_iso, - indicator, - period_date, - } => write!( - f, - "duplicate (country_iso, indicator, period_date) key: ({country_iso}, {indicator}, {period_date})" - ), - Self::EmptyCountryIso { - indicator, - period_date, - } => write!( - f, - "empty country_iso for ({indicator}, {period_date}): must be non-empty" - ), - Self::EmptyIndicator { - country_iso, - period_date, - } => write!( - f, - "empty indicator for ({country_iso}, {period_date}): must be non-empty" - ), - Self::EmptyKnownAtSource { - country_iso, - indicator, - period_date, - } => write!( - f, - "empty known_at_source for ({country_iso}, {indicator}, {period_date}): must be non-empty" - ), - Self::InvalidValue { - country_iso, - indicator, - period_date, - value, - } => write!( - f, - "invalid value ({value}) for ({country_iso}, {indicator}, {period_date}): must be finite" - ), - Self::LockTimeout { path, waited } => write!( - f, - "timed out after {}ms waiting for dataset write lock '{}' (if no writer is active, remove the stale lock file and retry)", - waited.as_millis(), - path.display() - ), - Self::RollbackFailed { cause, failures } => { - write!( - f, - "publication failed ({cause}) and rollback encountered {} error(s) requiring manual recovery:", - failures.len() - )?; - for failure in failures { - write!(f, " [{failure}]")?; - } - Ok(()) - } - Self::Io { path, source } => { - write!(f, "I/O error at '{}': {source}", path.display()) - } - Self::Parquet { path, source } => { - write!(f, "Parquet error at '{}': {source}", path.display()) - } - } - } -} - -impl Error for ParquetMacroError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::RollbackFailed { cause, .. } => Some(cause.as_ref()), - Self::Io { source, .. } => Some(source), - Self::Parquet { source, .. } => Some(source), - _ => None, - } - } -} - -impl From for ParquetMacroError { - fn from(err: PublishIoError) -> Self { - match err { - PublishIoError::LockTimeout { path, waited } => Self::LockTimeout { path, waited }, - PublishIoError::Io { path, source } => Self::Io { path, source }, - } - } -} - -/// Builds the exact 6-column Parquet schema for `macro` per `design/DATA-CONTRACTS.md` (§3A). -pub fn macro_parquet_schema() -> Result { - let fields: Vec = vec![ - Arc::new( - Type::primitive_type_builder("country_iso", PhysicalType::BYTE_ARRAY) - .with_repetition(Repetition::REQUIRED) - .with_logical_type(Some(LogicalType::String)) - .build()?, - ), - Arc::new( - Type::primitive_type_builder("indicator", PhysicalType::BYTE_ARRAY) - .with_repetition(Repetition::REQUIRED) - .with_logical_type(Some(LogicalType::String)) - .build()?, - ), - Arc::new( - Type::primitive_type_builder("period_date", PhysicalType::INT32) - .with_repetition(Repetition::REQUIRED) - .with_logical_type(Some(LogicalType::Date)) - .build()?, - ), - Arc::new( - Type::primitive_type_builder("known_at", PhysicalType::INT64) - .with_repetition(Repetition::REQUIRED) - .with_logical_type(Some(LogicalType::timestamp(true, TimeUnit::MICROS))) - .build()?, - ), - Arc::new( - Type::primitive_type_builder("known_at_source", PhysicalType::BYTE_ARRAY) - .with_repetition(Repetition::REQUIRED) - .with_logical_type(Some(LogicalType::String)) - .build()?, - ), - Arc::new( - Type::primitive_type_builder("value", PhysicalType::DOUBLE) - .with_repetition(Repetition::REQUIRED) - .build()?, - ), - ]; - - Ok(Arc::new( - Type::group_type_builder("macro") - .with_fields(fields) - .build()?, - )) -} - -fn build_writer_properties(zstd_level: ZstdLevel) -> WriterPropertiesPtr { - Arc::new( - WriterProperties::builder() - .set_compression(Compression::ZSTD(zstd_level)) - .set_column_dictionary_enabled(ColumnPath::from("country_iso"), true) - .set_column_dictionary_enabled(ColumnPath::from("indicator"), true) - .set_column_dictionary_enabled(ColumnPath::from("known_at_source"), true) - .set_created_by(format!("curate-etl {}", env!("CARGO_PKG_VERSION"))) - .build(), - ) -} - -#[inline] -fn validate_row(row: &MacroParquetRow) -> Result<(), ParquetMacroError> { - if row.country_iso.trim().is_empty() { - return Err(ParquetMacroError::EmptyCountryIso { - indicator: row.indicator.as_ref().to_owned(), - period_date: row.period_date, - }); - } - if row.indicator.trim().is_empty() { - return Err(ParquetMacroError::EmptyIndicator { - country_iso: row.country_iso.as_ref().to_owned(), - period_date: row.period_date, - }); - } - if row.known_at_source.trim().is_empty() { - return Err(ParquetMacroError::EmptyKnownAtSource { - country_iso: row.country_iso.as_ref().to_owned(), - indicator: row.indicator.as_ref().to_owned(), - period_date: row.period_date, - }); - } - if !row.value.is_finite() { - return Err(ParquetMacroError::InvalidValue { - country_iso: row.country_iso.as_ref().to_owned(), - indicator: row.indicator.as_ref().to_owned(), - period_date: row.period_date, - value: row.value, - }); - } - Ok(()) -} - -#[derive(Default)] -struct RowGroupBuffer { - country_iso_ids: Vec, - country_iso_interner: StringInterner, - indicator_ids: Vec, - indicator_interner: StringInterner, - period_date: Vec, - known_at_micros: Vec, - known_at_source_ids: Vec, - known_at_source_interner: StringInterner, - value: Vec, -} - -impl RowGroupBuffer { - #[inline] - fn len(&self) -> usize { - self.period_date.len() - } - - fn push(&mut self, row: &MacroParquetRow) { - let country_iso_id = self.country_iso_interner.intern(row.country_iso.as_ref()); - self.country_iso_ids.push(country_iso_id); - let indicator_id = self.indicator_interner.intern(row.indicator.as_ref()); - self.indicator_ids.push(indicator_id); - self.period_date.push(row.period_date); - self.known_at_micros.push(row.known_at_micros); - let known_at_source_id = self - .known_at_source_interner - .intern(row.known_at_source.as_ref()); - self.known_at_source_ids.push(known_at_source_id); - self.value.push(row.value); - } - - fn clear(&mut self) { - self.country_iso_ids.clear(); - self.country_iso_interner.clear(); - self.indicator_ids.clear(); - self.indicator_interner.clear(); - self.period_date.clear(); - self.known_at_micros.clear(); - self.known_at_source_ids.clear(); - self.known_at_source_interner.clear(); - self.value.clear(); - } -} - -struct MacroFileWriter { - tmp_path: PathBuf, - final_path: PathBuf, - writer: SerializedFileWriter>, - buf: RowGroupBuffer, - rows_written: usize, - row_groups_written: usize, -} - -impl MacroFileWriter { - fn from_file( - tmp_path: PathBuf, - final_path: PathBuf, - file: File, - schema: &TypePtr, - props: &WriterPropertiesPtr, - ) -> Result { - let buf_writer = BufWriter::with_capacity(FILE_BUF_CAPACITY_BYTES, file); - let writer = SerializedFileWriter::new(buf_writer, schema.clone(), props.clone()).map_err( - |source| ParquetMacroError::Parquet { - path: tmp_path.clone(), - source, - }, - )?; - - Ok(Self { - tmp_path, - final_path, - writer, - buf: RowGroupBuffer::default(), - rows_written: 0, - row_groups_written: 0, - }) - } - - fn flush_row_group(&mut self, scratch: &mut Vec) -> Result<(), ParquetMacroError> { - let row_count = self.buf.len(); - if row_count == 0 { - return Ok(()); - } - - let map_pq = |source: ParquetError| ParquetMacroError::Parquet { - path: self.tmp_path.clone(), - source, - }; - - let mut rg_writer = self.writer.next_row_group().map_err(map_pq)?; - - // 1. country_iso (BYTE_ARRAY, REQUIRED, STRING) - write_interned_str_col( - &mut rg_writer, - &self.buf.country_iso_ids, - &self.buf.country_iso_interner, - scratch, - ) - .map_err(map_pq)?; - // 2. indicator (BYTE_ARRAY, REQUIRED, STRING) - write_interned_str_col( - &mut rg_writer, - &self.buf.indicator_ids, - &self.buf.indicator_interner, - scratch, - ) - .map_err(map_pq)?; - // 3. period_date (INT32, REQUIRED, DATE) - write_i32_col(&mut rg_writer, &self.buf.period_date).map_err(map_pq)?; - // 4. known_at (INT64, REQUIRED, TIMESTAMP MICROS UTC) - write_i64_col(&mut rg_writer, &self.buf.known_at_micros).map_err(map_pq)?; - // 5. known_at_source (BYTE_ARRAY, REQUIRED, STRING) - write_interned_str_col( - &mut rg_writer, - &self.buf.known_at_source_ids, - &self.buf.known_at_source_interner, - scratch, - ) - .map_err(map_pq)?; - // 6. value (DOUBLE, REQUIRED) - write_f64_col(&mut rg_writer, &self.buf.value, None).map_err(map_pq)?; - - rg_writer.close().map_err(map_pq)?; - - self.rows_written += row_count; - self.row_groups_written += 1; - self.buf.clear(); - Ok(()) - } - - fn finish_and_sync( - mut self, - scratch: &mut Vec, - ) -> Result { - self.flush_row_group(scratch)?; - - let mut buf_writer = - self.writer - .into_inner() - .map_err(|source| ParquetMacroError::Parquet { - path: self.tmp_path.clone(), - source, - })?; - buf_writer.flush().map_err(|source| ParquetMacroError::Io { - path: self.tmp_path.clone(), - source, - })?; - let file = buf_writer - .into_inner() - .map_err(|err| ParquetMacroError::Io { - path: self.tmp_path.clone(), - source: err.into_error(), - })?; - file.sync_all().map_err(|source| ParquetMacroError::Io { - path: self.tmp_path.clone(), - source, - })?; - let bytes = file - .metadata() - .map_err(|source| ParquetMacroError::Io { - path: self.tmp_path.clone(), - source, - })? - .len(); - drop(file); - - Ok(SyncedMacroFile { - tmp_path: self.tmp_path, - final_path: self.final_path, - rows_written: self.rows_written, - row_groups_written: self.row_groups_written, - bytes, - }) - } -} - -struct SyncedMacroFile { - tmp_path: PathBuf, - final_path: PathBuf, - rows_written: usize, - row_groups_written: usize, - bytes: u64, -} - -/// Streams strictly ascending `(country_iso, indicator, period_date)` rows into a single Zstd -/// Parquet file at `/macro/part.parquet`. -/// -/// # Empty Input -/// Empty input (with valid options) returns `Ok(MacroWriteStats::default())` without creating -/// `/macro` and without modifying or removing any pre-existing `part.parquet`. -/// -/// # Concurrency & Atomicity -/// Concurrent writers targeting the same `/macro` directory are serialized via an -/// in-process per-dataset mutex and a bounded-wait exclusive `.write.lock` file. The file is -/// written to an exclusively created per-run staging file (`part.parquet..tmp`), flushed, -/// and `sync_all`'d before publication. If a pre-existing `part.parquet` regular file exists, -/// a live-preserving backup (`part.parquet..bak`) is created via hard link (or exclusive -/// copy fallback) so readers never observe a missing `part.parquet` before replacement by a -/// single atomic `rename`. On any error, the writer is dropped, any backup created by this run -/// is cleaned up (reporting cleanup failures via [`ParquetMacroError::RollbackFailed`]), and -/// only staging files owned by this run are unlinked. -pub fn write_macro_dataset( - out_dir: P, - rows: I, - options: MacroWriteOptions, -) -> Result -where - P: AsRef, - I: IntoIterator, - R: Borrow, -{ - write_macro_dataset_with_hooks( - out_dir, - rows, - options, - DEFAULT_LOCK_TIMEOUT, - |_, _| {}, - |path| fs::remove_file(path), - ) -} - -fn write_macro_dataset_with_hooks( - out_dir: P, - rows: I, - options: MacroWriteOptions, - lock_timeout: Duration, - mut on_after_backup: F, - mut remove_backup: Rm, -) -> Result -where - P: AsRef, - I: IntoIterator, - R: Borrow, - F: FnMut(&Path, Option<&Path>), - Rm: FnMut(&Path) -> io::Result<()>, -{ - if options.row_group_rows == 0 { - return Err(ParquetMacroError::InvalidRowGroupRows); - } - let zstd_level = ZstdLevel::try_new(options.zstd_level).map_err(|_| { - ParquetMacroError::InvalidZstdLevel { - level: options.zstd_level, - } - })?; - - let mut row_iter = rows.into_iter(); - let Some(first_item) = row_iter.next() else { - return Ok(MacroWriteStats::default()); - }; - validate_row(first_item.borrow())?; - - let out_dir = out_dir.as_ref(); - let macro_dir = out_dir.join("macro"); - let schema = macro_parquet_schema().map_err(|source| ParquetMacroError::Parquet { - path: macro_dir.clone(), - source, - })?; - let props = build_writer_properties(zstd_level); - - fs::create_dir_all(¯o_dir).map_err(|source| ParquetMacroError::Io { - path: macro_dir.clone(), - source, - })?; - - // Serialize writers targeting the same dataset directory across threads and processes. - // Drop order guarantees `.write.lock` is removed while `_in_process_guard` is still held, - // and only after all staging/publication/rollback work has finished. - let dataset_mu = dataset_mutex(¯o_dir); - let _in_process_guard = dataset_mu.lock().unwrap_or_else(|err| err.into_inner()); - let _file_lock = DatasetFileLock::acquire_with_timeout(¯o_dir, lock_timeout)?; - - let run_id = next_run_id(); - let (tmp_path, tmp_file) = create_exclusive_tmp_file(¯o_dir, &run_id)?; - // Declared before `file_writer` so Rust's reverse drop order closes the file handle - // before the guard unlinks the staging file on error or panic unwind, while `_file_lock` - // and `_in_process_guard` are still held. - let mut staging_guard = StagingFileGuard::new(tmp_path.clone()); - let mut scratch: Vec = Vec::with_capacity(STRING_WRITE_BATCH_ROWS); - - let mut file_writer = Some(MacroFileWriter::from_file( - tmp_path, - macro_dir.join("part.parquet"), - tmp_file, - &schema, - &props, - )?); - - let synced = { - let mut has_prev = false; - let mut prev_country_iso = String::new(); - let mut prev_indicator = String::new(); - let mut prev_period_date = 0i32; - let writer = file_writer.as_mut().expect("writer initialized"); - - for item in std::iter::once(first_item).chain(row_iter) { - let row = item.borrow(); - // Validate row fields before checking sort order so e.g. an empty country_iso - // or indicator is reported as EmptyCountryIso/EmptyIndicator rather than UnsortedInput. - validate_row(row)?; - let country_iso = row.country_iso.as_ref(); - let indicator = row.indicator.as_ref(); - if has_prev { - match (country_iso, indicator, row.period_date).cmp(&( - prev_country_iso.as_str(), - prev_indicator.as_str(), - prev_period_date, - )) { - Ordering::Equal => { - return Err(ParquetMacroError::DuplicateKey { - country_iso: country_iso.to_owned(), - indicator: indicator.to_owned(), - period_date: row.period_date, - }); - } - Ordering::Less => { - return Err(ParquetMacroError::UnsortedInput { - prev_country_iso, - prev_indicator, - prev_period_date, - country_iso: country_iso.to_owned(), - indicator: indicator.to_owned(), - period_date: row.period_date, - }); - } - Ordering::Greater => {} - } - } - if !has_prev || country_iso != prev_country_iso.as_str() { - prev_country_iso.clear(); - prev_country_iso.push_str(country_iso); - } - if !has_prev || indicator != prev_indicator.as_str() { - prev_indicator.clear(); - prev_indicator.push_str(indicator); - } - prev_period_date = row.period_date; - has_prev = true; - - writer.buf.push(row); - if writer.buf.len() == options.row_group_rows { - writer.flush_row_group(&mut scratch)?; - } - } - - let writer = file_writer.take().expect("writer still present"); - writer.finish_and_sync(&mut scratch)? - }; - - let backup_path = match fs::symlink_metadata(&synced.final_path) { - Ok(meta) if !meta.is_dir() => { - Some(create_backup_preserving_live(&synced.final_path, &run_id)?) - } - // Directory occupying final_path: leave it in place so the rename below fails cleanly. - Ok(_) => None, - Err(err) if err.kind() == io::ErrorKind::NotFound => None, - Err(source) => { - return Err(ParquetMacroError::Io { - path: synced.final_path, - source, - }); - } - }; - - on_after_backup(&synced.final_path, backup_path.as_deref()); - - if let Err(source) = fs::rename(&synced.tmp_path, &synced.final_path) { - // `synced.final_path` was never moved during backup creation, so it remains intact; - // remove the backup created for this run. `staging_guard` unlinks our staging file on drop. - let backup_remove_failure = backup_path.and_then(|bak| { - fs::remove_file(&bak).err().map(|remove_err| RollbackFailure { - final_path: synced.final_path.clone(), - backup_path: Some(bak), - source: remove_err, - }) - }); - let cause = ParquetMacroError::Io { - path: synced.final_path, - source, - }; - return match backup_remove_failure { - Some(failure) => Err(ParquetMacroError::RollbackFailed { - cause: Box::new(cause), - failures: vec![failure], - }), - None => Err(cause), - }; - } - - staging_guard.disarm(); - - if let Some(bak) = backup_path { - if let Err(remove_err) = remove_backup(&bak) { - let cause = ParquetMacroError::Io { - path: bak.clone(), - source: remove_err, - }; - return match fs::rename(&bak, &synced.final_path) { - Ok(()) => Err(cause), - Err(restore_err) => Err(ParquetMacroError::RollbackFailed { - cause: Box::new(cause), - failures: vec![RollbackFailure { - final_path: synced.final_path, - backup_path: Some(bak), - source: restore_err, - }], - }), - }; - } - } - - Ok(MacroWriteStats { - rows_written: synced.rows_written, - files_written: 1, - row_groups_written: synced.row_groups_written, - bytes_written: synced.bytes, - }) -} - -#[cfg(test)] -#[path = "parquet_macro_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/parquet_macro_tests.rs b/tools/curate-etl/src/parquet_macro_tests.rs deleted file mode 100644 index e3865b0b..00000000 --- a/tools/curate-etl/src/parquet_macro_tests.rs +++ /dev/null @@ -1,1391 +0,0 @@ -use std::borrow::Cow; -use std::error::Error as StdError; -use std::fs::{self, File}; -use std::io; -use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; -use std::sync::{Arc, Mutex}; -use std::time::Duration; - -use parquet::basic::{Compression, ConvertedType, Encoding, LogicalType, Repetition, TimeUnit, Type as PhysicalType}; -use parquet::column::reader::ColumnReader; -use parquet::file::reader::{FileReader, SerializedFileReader}; - -use super::{ - macro_parquet_schema, write_macro_dataset, write_macro_dataset_with_hooks, MacroParquetRow, - MacroWriteOptions, MacroWriteStats, ParquetMacroError, -}; -use crate::macro_series::{ - build_macro_rows, MacroLagClass, MacroObservation, MacroRow, MACRO_KNOWN_AT_SOURCE, - MONTHLY_RELEASE_LAG_DAYS, POLICY_RATE_LAG_DAYS, -}; -use crate::split::ymd_to_epoch_days; - -const MICROS_PER_DAY: i64 = 86_400_000_000; - -static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0); - -struct TempDirGuard { - path: PathBuf, -} - -impl TempDirGuard { - fn new(label: &str) -> Self { - let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); - let pid = std::process::id(); - let path = - std::env::temp_dir().join(format!("curate-etl-pq-macro-test-{label}-{pid}-{seq}")); - let _ = fs::remove_dir_all(&path); - fs::create_dir_all(&path).expect("create test temp dir"); - Self { path } - } - - fn path(&self) -> &Path { - &self.path - } -} - -impl Drop for TempDirGuard { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.path); - } -} - -fn day(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).expect("valid date") -} - -fn make_row( - country_iso: &'static str, - indicator: &'static str, - period_date: i32, - lag_days: i32, - value: f64, -) -> MacroParquetRow { - MacroParquetRow { - country_iso: Cow::Borrowed(country_iso), - indicator: Cow::Borrowed(indicator), - period_date, - known_at_micros: i64::from(period_date + lag_days) * MICROS_PER_DAY, - known_at_source: Cow::Borrowed(MACRO_KNOWN_AT_SOURCE), - value, - } -} - -fn read_parquet_rows(path: &Path) -> Vec { - let file = File::open(path).expect("open parquet file"); - let reader = SerializedFileReader::new(file).expect("open parquet reader"); - let metadata = reader.metadata(); - let mut out = Vec::new(); - - for rg_idx in 0..metadata.num_row_groups() { - let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); - let num_rows = metadata.row_group(rg_idx).num_rows() as usize; - - let read_i32 = |col_idx: usize| -> Vec { - let mut vals = Vec::with_capacity(num_rows); - match rg_reader.get_column_reader(col_idx).expect("col reader") { - ColumnReader::Int32ColumnReader(mut r) => { - let (read, _, _) = r - .read_records(num_rows, None, None, &mut vals) - .expect("read i32"); - assert_eq!(read, num_rows); - } - _ => panic!("expected INT32 column at index {col_idx}"), - } - vals - }; - let read_i64 = |col_idx: usize| -> Vec { - let mut vals = Vec::with_capacity(num_rows); - match rg_reader.get_column_reader(col_idx).expect("col reader") { - ColumnReader::Int64ColumnReader(mut r) => { - let (read, _, _) = r - .read_records(num_rows, None, None, &mut vals) - .expect("read i64"); - assert_eq!(read, num_rows); - } - _ => panic!("expected INT64 column at index {col_idx}"), - } - vals - }; - let read_f64 = |col_idx: usize| -> Vec { - let mut vals = Vec::with_capacity(num_rows); - match rg_reader.get_column_reader(col_idx).expect("col reader") { - ColumnReader::DoubleColumnReader(mut r) => { - let (read, _, _) = r - .read_records(num_rows, None, None, &mut vals) - .expect("read f64"); - assert_eq!(read, num_rows); - } - _ => panic!("expected DOUBLE column at index {col_idx}"), - } - vals - }; - let read_str = |col_idx: usize| -> Vec { - let mut vals = Vec::with_capacity(num_rows); - match rg_reader.get_column_reader(col_idx).expect("col reader") { - ColumnReader::ByteArrayColumnReader(mut r) => { - let (read, _, _) = r - .read_records(num_rows, None, None, &mut vals) - .expect("read utf8"); - assert_eq!(read, num_rows); - } - _ => panic!("expected BYTE_ARRAY column at index {col_idx}"), - } - vals.into_iter() - .map(|b| std::str::from_utf8(b.data()).expect("valid utf8").to_owned()) - .collect() - }; - - let country_iso = read_str(0); - let indicator = read_str(1); - let period_date = read_i32(2); - let known_at_micros = read_i64(3); - let known_at_source = read_str(4); - let value = read_f64(5); - - for i in 0..num_rows { - out.push(MacroParquetRow { - country_iso: Cow::Owned(country_iso[i].clone()), - indicator: Cow::Owned(indicator[i].clone()), - period_date: period_date[i], - known_at_micros: known_at_micros[i], - known_at_source: Cow::Owned(known_at_source[i].clone()), - value: value[i], - }); - } - } - out -} - -fn assert_row_bitwise_eq(actual: &MacroParquetRow, expected: &MacroParquetRow) { - assert_eq!(actual.country_iso, expected.country_iso); - assert_eq!(actual.indicator, expected.indicator); - assert_eq!(actual.period_date, expected.period_date); - assert_eq!(actual.known_at_micros, expected.known_at_micros); - assert_eq!(actual.known_at_source, expected.known_at_source); - assert_eq!(actual.value.to_bits(), expected.value.to_bits()); -} - -fn assert_no_transient_files(dir: &Path) { - if !dir.exists() { - return; - } - for entry in fs::read_dir(dir).expect("read dir") { - let entry = entry.expect("dir entry"); - let name = entry.file_name().to_string_lossy().into_owned(); - assert!( - !name.ends_with(".tmp") && !name.ends_with(".bak") && name != ".write.lock", - "unexpected transient file remaining: {}", - entry.path().display() - ); - } -} - -fn seed_existing(out_dir: &Path) -> (PathBuf, Vec) { - let seed = vec![ - make_row("CA", "policy_rate", day(2024, 1, 24), POLICY_RATE_LAG_DAYS, 5.0), - make_row("US", "cpi_yoy", day(2024, 1, 31), MONTHLY_RELEASE_LAG_DAYS, 3.1), - ]; - write_macro_dataset(out_dir, &seed, MacroWriteOptions::default()).unwrap(); - let part = out_dir.join("macro/part.parquet"); - let before = fs::read(&part).unwrap(); - (part, before) -} - -/// Pinned `build_macro_rows` fixture with 2 countries (`CA`, `US`), 2 indicators -/// (`cpi_yoy`, `policy_rate`), 2 lag classes (`MonthlyRelease`, `PolicyRate`), -/// negative values, and both `-0.0` and `+0.0` at distinct keys. -fn pinned_builder_fixture() -> Vec> { - let observations = vec![ - // Intentionally unsorted so `build_macro_rows` establishes canonical sort order. - MacroObservation { - country_iso: "US".to_string(), - indicator: "policy_rate".to_string(), - period_date: day(2024, 3, 20), - value: 5.5, - }, - MacroObservation { - country_iso: "CA".to_string(), - indicator: "cpi_yoy".to_string(), - period_date: day(2024, 2, 29), - value: 0.0_f64, - }, - MacroObservation { - country_iso: "CA".to_string(), - indicator: "cpi_yoy".to_string(), - period_date: day(2024, 1, 31), - value: -0.0_f64, - }, - MacroObservation { - country_iso: "US".to_string(), - indicator: "cpi_yoy".to_string(), - period_date: day(2024, 1, 31), - value: -0.25, - }, - MacroObservation { - country_iso: "CA".to_string(), - indicator: "policy_rate".to_string(), - period_date: day(2024, 3, 6), - value: 5.0, - }, - ]; - - let built = build_macro_rows(observations, |country, indicator| match ( - country.as_str(), - indicator.as_str(), - ) { - ("CA" | "US", "policy_rate") => Some(MacroLagClass::PolicyRate), - ("CA" | "US", "cpi_yoy") => Some(MacroLagClass::MonthlyRelease), - _ => None, - }) - .expect("build_macro_rows fixture"); - - assert_eq!(built.rows.len(), 5); - assert_eq!(built.stats.emitted, 5); - built.rows -} - -#[test] -fn schema_matches_contract_names_types_nullability_and_order() { - let schema = macro_parquet_schema().expect("build schema"); - assert_eq!(schema.name(), "macro"); - let fields = schema.get_fields(); - assert_eq!(fields.len(), 6); - - let expected: [( - &str, - PhysicalType, - Repetition, - Option, - ConvertedType, - ); 6] = [ - ( - "country_iso", - PhysicalType::BYTE_ARRAY, - Repetition::REQUIRED, - Some(LogicalType::String), - ConvertedType::UTF8, - ), - ( - "indicator", - PhysicalType::BYTE_ARRAY, - Repetition::REQUIRED, - Some(LogicalType::String), - ConvertedType::UTF8, - ), - ( - "period_date", - PhysicalType::INT32, - Repetition::REQUIRED, - Some(LogicalType::Date), - ConvertedType::DATE, - ), - ( - "known_at", - PhysicalType::INT64, - Repetition::REQUIRED, - Some(LogicalType::timestamp(true, TimeUnit::MICROS)), - ConvertedType::TIMESTAMP_MICROS, - ), - ( - "known_at_source", - PhysicalType::BYTE_ARRAY, - Repetition::REQUIRED, - Some(LogicalType::String), - ConvertedType::UTF8, - ), - ( - "value", - PhysicalType::DOUBLE, - Repetition::REQUIRED, - None, - ConvertedType::NONE, - ), - ]; - - for (idx, (name, phys, rep, logical, converted)) in expected.into_iter().enumerate() { - let f = &fields[idx]; - assert_eq!(f.name(), name, "field {idx} name"); - assert_eq!(f.get_physical_type(), phys, "field {name} physical type"); - assert_eq!( - f.get_basic_info().repetition(), - rep, - "field {name} repetition" - ); - assert_eq!( - f.get_basic_info().logical_type_ref().cloned(), - logical, - "field {name} logical type" - ); - assert_eq!( - f.get_basic_info().converted_type(), - converted, - "field {name} converted type" - ); - } -} - -#[test] -fn build_macro_rows_round_trip_bitwise_and_written_file_schema_zstd() { - let tmp = TempDirGuard::new("round-trip"); - let builder_rows = pinned_builder_fixture(); - - let parquet_rows: Vec = builder_rows - .iter() - .map(|r| { - let row = MacroParquetRow::from(r); - assert!(matches!(row.known_at_source, Cow::Borrowed(_))); - row - }) - .collect(); - - // Verify `From<&MacroRow<&str>>` compiles and matches as well. - let borrowed_macro_row = MacroRow { - country_iso: "US", - indicator: "policy_rate", - period_date: day(2024, 3, 20), - known_at: i64::from(day(2024, 3, 21)) * MICROS_PER_DAY, - known_at_source: MACRO_KNOWN_AT_SOURCE, - value: 5.5, - }; - let converted = MacroParquetRow::from(&borrowed_macro_row); - assert_eq!(converted.country_iso.as_ref(), "US"); - assert_eq!(converted.known_at_micros, borrowed_macro_row.known_at); - - let stats = write_macro_dataset(tmp.path(), &parquet_rows, MacroWriteOptions::default()).unwrap(); - assert_eq!(stats.rows_written, 5); - assert_eq!(stats.files_written, 1); - assert_eq!(stats.row_groups_written, 1); - assert!(stats.bytes_written > 0); - - let path = tmp.path().join("macro/part.parquet"); - assert_eq!(fs::metadata(&path).unwrap().len(), stats.bytes_written); - - let reader = SerializedFileReader::new(File::open(&path).unwrap()).unwrap(); - let meta = reader.metadata(); - assert_eq!(meta.file_metadata().num_rows(), 5); - assert_eq!(meta.num_row_groups(), 1); - - // Inspect written file schema directly. - let file_fields = meta.file_metadata().schema().get_fields(); - assert_eq!(file_fields.len(), 6); - assert_eq!(file_fields[0].name(), "country_iso"); - assert_eq!(file_fields[1].name(), "indicator"); - assert_eq!(file_fields[2].name(), "period_date"); - assert_eq!(file_fields[3].name(), "known_at"); - assert_eq!(file_fields[4].name(), "known_at_source"); - assert_eq!(file_fields[5].name(), "value"); - for f in file_fields { - assert_eq!(f.get_basic_info().repetition(), Repetition::REQUIRED); - } - assert_eq!( - file_fields[2].get_basic_info().logical_type_ref().cloned(), - Some(LogicalType::Date) - ); - assert_eq!( - file_fields[3].get_basic_info().logical_type_ref().cloned(), - Some(LogicalType::timestamp(true, TimeUnit::MICROS)) - ); - assert_eq!(file_fields[5].get_physical_type(), PhysicalType::DOUBLE); - - // Every column chunk must use Zstd compression. - for rg in meta.row_groups() { - for col in rg.columns() { - assert!( - matches!(col.compression(), Compression::ZSTD(_)), - "column {} expected ZSTD, got {:?}", - col.column_path(), - col.compression() - ); - } - } - - // Bitwise round-trip against `build_macro_rows` baseline. - let actual = read_parquet_rows(&path); - assert_eq!(actual.len(), builder_rows.len()); - for (a, b) in actual.iter().zip(&builder_rows) { - assert_eq!(a.country_iso.as_ref(), b.country_iso.as_str()); - assert_eq!(a.indicator.as_ref(), b.indicator.as_str()); - assert_eq!(a.period_date, b.period_date); - assert_eq!(a.known_at_micros, b.known_at); - assert_eq!(a.known_at_source.as_ref(), MACRO_KNOWN_AT_SOURCE); - assert_eq!(a.value.to_bits(), b.value.to_bits()); - } - - // Explicitly verify `-0.0` vs `+0.0` bit preservation in the same row group, - // and exact UTC microseconds at expected lagged midnights. - assert_eq!(actual[0].country_iso.as_ref(), "CA"); - assert_eq!(actual[0].indicator.as_ref(), "cpi_yoy"); - assert_eq!(actual[0].value.to_bits(), (-0.0_f64).to_bits()); - assert_eq!( - actual[0].known_at_micros, - i64::from(day(2024, 1, 31) + MONTHLY_RELEASE_LAG_DAYS) * MICROS_PER_DAY - ); - - assert_eq!(actual[1].country_iso.as_ref(), "CA"); - assert_eq!(actual[1].indicator.as_ref(), "cpi_yoy"); - assert_eq!(actual[1].value.to_bits(), (0.0_f64).to_bits()); - assert_eq!( - actual[1].known_at_micros, - i64::from(day(2024, 2, 29) + MONTHLY_RELEASE_LAG_DAYS) * MICROS_PER_DAY - ); - - assert_eq!(actual[2].country_iso.as_ref(), "CA"); - assert_eq!(actual[2].indicator.as_ref(), "policy_rate"); - assert_eq!( - actual[2].known_at_micros, - i64::from(day(2024, 3, 6) + POLICY_RATE_LAG_DAYS) * MICROS_PER_DAY - ); - - assert_no_transient_files(&tmp.path().join("macro")); -} - -#[test] -fn multi_row_group_with_partial_final_group_matches_baseline_and_metadata() { - let tmp = TempDirGuard::new("multi-rg"); - let builder_rows = pinned_builder_fixture(); - let parquet_rows: Vec = builder_rows.iter().map(MacroParquetRow::from).collect(); - - // 5 rows with row_group_rows = 2 => 3 row groups: [2, 2, 1] - let opts = MacroWriteOptions { - row_group_rows: 2, - ..MacroWriteOptions::default() - }; - let stats = write_macro_dataset(tmp.path(), &parquet_rows, opts).unwrap(); - assert_eq!(stats.rows_written, 5); - assert_eq!(stats.files_written, 1); - assert_eq!(stats.row_groups_written, 3); - - let path = tmp.path().join("macro/part.parquet"); - assert_eq!(fs::metadata(&path).unwrap().len(), stats.bytes_written); - - let reader = SerializedFileReader::new(File::open(&path).unwrap()).unwrap(); - let meta = reader.metadata(); - assert_eq!(meta.file_metadata().num_rows(), 5); - assert_eq!(meta.num_row_groups(), 3); - let rg_sizes: Vec = (0..meta.num_row_groups()) - .map(|i| meta.row_group(i).num_rows()) - .collect(); - assert_eq!(rg_sizes, vec![2, 2, 1]); - - for rg in meta.row_groups() { - for col in rg.columns() { - assert!( - matches!(col.compression(), Compression::ZSTD(_)), - "column {} expected ZSTD, got {:?}", - col.column_path(), - col.compression() - ); - } - } - - let actual = read_parquet_rows(&path); - assert_eq!(actual.len(), parquet_rows.len()); - for (a, e) in actual.iter().zip(&parquet_rows) { - assert_row_bitwise_eq(a, e); - } - assert_no_transient_files(&tmp.path().join("macro")); -} - -#[test] -fn string_columns_use_dictionary_encoding_and_output_is_deterministic() { - let tmp = TempDirGuard::new("dict-determinism"); - let base = day(2024, 1, 1); - let rows: Vec = (0..64_i32) - .map(|i| { - let country = if i < 32 { "CA" } else { "US" }; - let indicator = if (i % 32) < 16 { "cpi_yoy" } else { "policy_rate" }; - make_row( - country, - indicator, - base + (i % 16), - POLICY_RATE_LAG_DAYS, - f64::from(i) * 0.125, - ) - }) - .collect(); - - let out_a = tmp.path().join("a"); - let out_b = tmp.path().join("b"); - let opts = MacroWriteOptions { - row_group_rows: 32, - ..MacroWriteOptions::default() - }; - write_macro_dataset(&out_a, &rows, opts).unwrap(); - write_macro_dataset(&out_b, &rows, opts).unwrap(); - - let path_a = out_a.join("macro/part.parquet"); - let path_b = out_b.join("macro/part.parquet"); - assert_eq!(fs::read(&path_a).unwrap(), fs::read(&path_b).unwrap()); - - let reader = SerializedFileReader::new(File::open(&path_a).unwrap()).unwrap(); - let rg0 = reader.metadata().row_group(0); - for (col_idx, name) in [ - (0usize, "country_iso"), - (1usize, "indicator"), - (4usize, "known_at_source"), - ] { - let col = rg0.column(col_idx); - assert!( - col.encodings().any(|e| { - matches!(e, Encoding::RLE_DICTIONARY | Encoding::PLAIN_DICTIONARY) - }), - "expected dictionary encoding on {name}, got {:?}", - col.encodings().collect::>() - ); - } -} - -#[test] -fn empty_input_returns_default_stats_and_preserves_fresh_and_seeded_destinations() { - let tmp = TempDirGuard::new("empty"); - let fresh = tmp.path().join("fresh"); - let stats = write_macro_dataset( - &fresh, - std::iter::empty::(), - MacroWriteOptions::default(), - ) - .unwrap(); - assert_eq!(stats, MacroWriteStats::default()); - assert!(!fresh.exists(), "empty input must not create out_dir"); - - let seeded = tmp.path().join("seeded"); - let (part, before) = seed_existing(&seeded); - let empty_stats = write_macro_dataset( - &seeded, - std::iter::empty::(), - MacroWriteOptions::default(), - ) - .unwrap(); - assert_eq!(empty_stats, MacroWriteStats::default()); - assert_eq!(fs::read(&part).unwrap(), before); - assert_no_transient_files(&seeded.join("macro")); -} - -#[test] -fn invalid_options_fail_closed_in_fresh_and_seeded_dirs() { - let tmp = TempDirGuard::new("bad-opts"); - let fresh = tmp.path().join("fresh"); - let seeded = tmp.path().join("seeded"); - let (part, before) = seed_existing(&seeded); - let rows = vec![make_row( - "US", - "policy_rate", - day(2024, 3, 20), - POLICY_RATE_LAG_DAYS, - 5.5, - )]; - - for (dir, is_fresh) in [(&fresh, true), (&seeded, false)] { - assert!(matches!( - write_macro_dataset( - dir, - &rows, - MacroWriteOptions { - row_group_rows: 0, - ..MacroWriteOptions::default() - } - ), - Err(ParquetMacroError::InvalidRowGroupRows) - )); - // Even with empty input, invalid options must fail before returning default stats. - assert!(matches!( - write_macro_dataset( - dir, - std::iter::empty::(), - MacroWriteOptions { - row_group_rows: 0, - ..MacroWriteOptions::default() - } - ), - Err(ParquetMacroError::InvalidRowGroupRows) - )); - assert!(matches!( - write_macro_dataset( - dir, - &rows, - MacroWriteOptions { - zstd_level: 23, - ..MacroWriteOptions::default() - } - ), - Err(ParquetMacroError::InvalidZstdLevel { level: 23 }) - )); - assert!(matches!( - write_macro_dataset( - dir, - &rows, - MacroWriteOptions { - zstd_level: 99, - ..MacroWriteOptions::default() - } - ), - Err(ParquetMacroError::InvalidZstdLevel { level: 99 }) - )); - - if is_fresh { - assert!(!dir.exists(), "invalid options must not create out_dir"); - } else { - assert_eq!(fs::read(&part).unwrap(), before); - assert_no_transient_files(&dir.join("macro")); - } - } -} - -#[test] -fn invalid_inputs_return_typed_errors_in_fresh_and_seeded_dirs() { - let tmp = TempDirGuard::new("invalid-inputs"); - let fresh = tmp.path().join("fresh"); - let seeded = tmp.path().join("seeded"); - let (part, before) = seed_existing(&seeded); - let d1 = day(2024, 1, 31); - let d2 = day(2024, 2, 29); - - let check_both = |rows: &[MacroParquetRow], check: &dyn Fn(&ParquetMacroError)| { - let err_fresh = - write_macro_dataset(&fresh, rows, MacroWriteOptions::default()).unwrap_err(); - check(&err_fresh); - assert!( - !fresh.join("macro/part.parquet").exists(), - "fresh dir must not contain part.parquet after error: {err_fresh}" - ); - assert_no_transient_files(&fresh.join("macro")); - - let err_seeded = - write_macro_dataset(&seeded, rows, MacroWriteOptions::default()).unwrap_err(); - check(&err_seeded); - assert_eq!(fs::read(&part).unwrap(), before); - assert_no_transient_files(&seeded.join("macro")); - }; - - // 1. Non-finite values: NaN, +inf, -inf - for bad_val in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { - let rows = vec![make_row("US", "cpi_yoy", d1, MONTHLY_RELEASE_LAG_DAYS, bad_val)]; - check_both(&rows, &|err| { - assert!( - matches!( - err, - ParquetMacroError::InvalidValue { - country_iso, - indicator, - period_date, - .. - } if country_iso == "US" && indicator == "cpi_yoy" && *period_date == d1 - ), - "expected InvalidValue for {bad_val}, got {err:?}" - ); - }); - } - - // 2. Empty / whitespace-only country_iso (first row and second row) - for bad_country in ["", " ", "\t\n"] { - let first_bad = vec![MacroParquetRow { - country_iso: Cow::Owned(bad_country.to_string()), - ..make_row("US", "cpi_yoy", d1, MONTHLY_RELEASE_LAG_DAYS, 3.0) - }]; - check_both(&first_bad, &|err| { - assert!( - matches!( - err, - ParquetMacroError::EmptyCountryIso { indicator, period_date } - if indicator == "cpi_yoy" && *period_date == d1 - ), - "expected EmptyCountryIso for {bad_country:?}, got {err:?}" - ); - }); - - let second_bad = vec![ - make_row("US", "cpi_yoy", d1, MONTHLY_RELEASE_LAG_DAYS, 3.0), - MacroParquetRow { - country_iso: Cow::Owned(bad_country.to_string()), - ..make_row("US", "cpi_yoy", d2, MONTHLY_RELEASE_LAG_DAYS, 3.1) - }, - ]; - check_both(&second_bad, &|err| { - assert!( - matches!( - err, - ParquetMacroError::EmptyCountryIso { indicator, period_date } - if indicator == "cpi_yoy" && *period_date == d2 - ), - "expected EmptyCountryIso on row 2 for {bad_country:?}, got {err:?}" - ); - }); - } - - // 3. Empty / whitespace-only indicator (first row and second row) - for bad_indicator in ["", " ", "\t\n"] { - let first_bad = vec![MacroParquetRow { - indicator: Cow::Owned(bad_indicator.to_string()), - ..make_row("US", "cpi_yoy", d1, MONTHLY_RELEASE_LAG_DAYS, 3.0) - }]; - check_both(&first_bad, &|err| { - assert!( - matches!( - err, - ParquetMacroError::EmptyIndicator { country_iso, period_date } - if country_iso == "US" && *period_date == d1 - ), - "expected EmptyIndicator for {bad_indicator:?}, got {err:?}" - ); - }); - - let second_bad = vec![ - make_row("US", "cpi_yoy", d1, MONTHLY_RELEASE_LAG_DAYS, 3.0), - MacroParquetRow { - indicator: Cow::Owned(bad_indicator.to_string()), - ..make_row("US", "cpi_yoy", d2, MONTHLY_RELEASE_LAG_DAYS, 3.1) - }, - ]; - check_both(&second_bad, &|err| { - assert!( - matches!( - err, - ParquetMacroError::EmptyIndicator { country_iso, period_date } - if country_iso == "US" && *period_date == d2 - ), - "expected EmptyIndicator on row 2 for {bad_indicator:?}, got {err:?}" - ); - }); - } - - // 4. Empty / whitespace-only known_at_source - for bad_source in ["", " ", "\t\n"] { - let rows = vec![MacroParquetRow { - known_at_source: Cow::Owned(bad_source.to_string()), - ..make_row("US", "cpi_yoy", d1, MONTHLY_RELEASE_LAG_DAYS, 3.0) - }]; - check_both(&rows, &|err| { - assert!( - matches!( - err, - ParquetMacroError::EmptyKnownAtSource { - country_iso, - indicator, - period_date, - } if country_iso == "US" && indicator == "cpi_yoy" && *period_date == d1 - ), - "expected EmptyKnownAtSource for {bad_source:?}, got {err:?}" - ); - }); - } - - // 5. Descending country_iso - let unsorted_country = vec![ - make_row("US", "cpi_yoy", d1, MONTHLY_RELEASE_LAG_DAYS, 3.0), - make_row("CA", "cpi_yoy", d2, MONTHLY_RELEASE_LAG_DAYS, 2.8), - ]; - check_both(&unsorted_country, &|err| { - assert!( - matches!( - err, - ParquetMacroError::UnsortedInput { - prev_country_iso, - prev_indicator, - prev_period_date, - country_iso, - indicator, - period_date, - } if prev_country_iso == "US" - && prev_indicator == "cpi_yoy" - && *prev_period_date == d1 - && country_iso == "CA" - && indicator == "cpi_yoy" - && *period_date == d2 - ), - "expected UnsortedInput for descending country_iso, got {err:?}" - ); - }); - - // 6. Descending indicator within same country_iso - let unsorted_indicator = vec![ - make_row("CA", "policy_rate", d1, POLICY_RATE_LAG_DAYS, 5.0), - make_row("CA", "cpi_yoy", d2, MONTHLY_RELEASE_LAG_DAYS, 2.8), - ]; - check_both(&unsorted_indicator, &|err| { - assert!( - matches!( - err, - ParquetMacroError::UnsortedInput { - prev_country_iso, - prev_indicator, - prev_period_date, - country_iso, - indicator, - period_date, - } if prev_country_iso == "CA" - && prev_indicator == "policy_rate" - && *prev_period_date == d1 - && country_iso == "CA" - && indicator == "cpi_yoy" - && *period_date == d2 - ), - "expected UnsortedInput for descending indicator, got {err:?}" - ); - }); - - // 7. Descending period_date within same (country_iso, indicator) - let unsorted_date = vec![ - make_row("US", "cpi_yoy", d2, MONTHLY_RELEASE_LAG_DAYS, 3.1), - make_row("US", "cpi_yoy", d1, MONTHLY_RELEASE_LAG_DAYS, 3.0), - ]; - check_both(&unsorted_date, &|err| { - assert!( - matches!( - err, - ParquetMacroError::UnsortedInput { - prev_country_iso, - prev_indicator, - prev_period_date, - country_iso, - indicator, - period_date, - } if prev_country_iso == "US" - && prev_indicator == "cpi_yoy" - && *prev_period_date == d2 - && country_iso == "US" - && indicator == "cpi_yoy" - && *period_date == d1 - ), - "expected UnsortedInput for descending period_date, got {err:?}" - ); - }); - - // 8. Duplicate (country_iso, indicator, period_date) - let duplicate = vec![ - make_row("US", "cpi_yoy", d1, MONTHLY_RELEASE_LAG_DAYS, 3.0), - make_row("US", "cpi_yoy", d1, MONTHLY_RELEASE_LAG_DAYS, 3.0), - ]; - check_both(&duplicate, &|err| { - assert!( - matches!( - err, - ParquetMacroError::DuplicateKey { - country_iso, - indicator, - period_date, - } if country_iso == "US" && indicator == "cpi_yoy" && *period_date == d1 - ), - "expected DuplicateKey, got {err:?}" - ); - }); -} - -#[test] -fn mid_stream_failures_after_flushed_row_groups_preserve_state_and_clean_staging() { - let tmp = TempDirGuard::new("mid-stream-fail"); - let fresh = tmp.path().join("fresh"); - let seeded = tmp.path().join("seeded"); - let (part, before) = seed_existing(&seeded); - let base = day(2024, 1, 1); - - let prefix = vec![ - make_row("CA", "cpi_yoy", base, MONTHLY_RELEASE_LAG_DAYS, 2.5), - make_row("CA", "cpi_yoy", base + 1, MONTHLY_RELEASE_LAG_DAYS, 2.6), - make_row("CA", "policy_rate", base, POLICY_RATE_LAG_DAYS, 5.0), - make_row("CA", "policy_rate", base + 1, POLICY_RATE_LAG_DAYS, 5.0), - ]; - - let opts = MacroWriteOptions { - row_group_rows: 2, - ..MacroWriteOptions::default() - }; - - // Case A: Non-finite value on row 5 after 2 row groups have flushed. - let mut bad_val_rows = prefix.clone(); - bad_val_rows.push(make_row( - "US", - "cpi_yoy", - base, - MONTHLY_RELEASE_LAG_DAYS, - f64::NAN, - )); - - // Case B: Descending key across row-group flush boundary. - let mut unsorted_rows = prefix.clone(); - unsorted_rows.push(make_row( - "CA", - "policy_rate", - base, - POLICY_RATE_LAG_DAYS, - 4.75, - )); - - // Case C: Duplicate key across row-group flush boundary. - let mut dup_rows = prefix; - dup_rows.push(make_row( - "CA", - "policy_rate", - base + 1, - POLICY_RATE_LAG_DAYS, - 5.0, - )); - - for (rows, expected_kind) in [ - (&bad_val_rows, "invalid_value"), - (&unsorted_rows, "unsorted"), - (&dup_rows, "duplicate"), - ] { - let err_fresh = write_macro_dataset(&fresh, rows, opts).unwrap_err(); - let err_seeded = write_macro_dataset(&seeded, rows, opts).unwrap_err(); - - for err in [&err_fresh, &err_seeded] { - match expected_kind { - "invalid_value" => assert!(matches!(err, ParquetMacroError::InvalidValue { .. })), - "unsorted" => assert!(matches!(err, ParquetMacroError::UnsortedInput { .. })), - "duplicate" => assert!(matches!(err, ParquetMacroError::DuplicateKey { .. })), - _ => unreachable!(), - } - } - - assert!( - !fresh.join("macro/part.parquet").exists(), - "fresh dir must not publish part.parquet on {expected_kind}" - ); - assert_no_transient_files(&fresh.join("macro")); - assert_eq!(fs::read(&part).unwrap(), before); - assert_no_transient_files(&seeded.join("macro")); - } -} - -#[test] -fn overwrite_replaces_existing_part_parquet_and_cleans_backup() { - let tmp = TempDirGuard::new("overwrite"); - let (part, before) = seed_existing(tmp.path()); - - let replacement = vec![ - make_row("CA", "cpi_yoy", day(2025, 1, 31), MONTHLY_RELEASE_LAG_DAYS, 1.9), - make_row("US", "policy_rate", day(2025, 1, 29), POLICY_RATE_LAG_DAYS, 4.5), - ]; - let stats = write_macro_dataset(tmp.path(), &replacement, MacroWriteOptions::default()).unwrap(); - assert_eq!(stats.rows_written, 2); - assert_eq!(stats.files_written, 1); - assert_eq!(stats.row_groups_written, 1); - - let after = fs::read(&part).unwrap(); - assert_ne!(after, before); - let actual = read_parquet_rows(&part); - assert_eq!(actual.len(), replacement.len()); - for (a, e) in actual.iter().zip(&replacement) { - assert_row_bitwise_eq(a, e); - } - assert_no_transient_files(&tmp.path().join("macro")); -} - -#[test] -fn live_part_parquet_stays_readable_between_backup_and_rename() { - let tmp = TempDirGuard::new("live-readable"); - let (part, before) = seed_existing(tmp.path()); - - let replacement = vec![make_row( - "US", - "policy_rate", - day(2025, 3, 19), - POLICY_RATE_LAG_DAYS, - 4.25, - )]; - let observed_live = Arc::new(Mutex::new(false)); - let observed_clone = Arc::clone(&observed_live); - - write_macro_dataset_with_hooks( - tmp.path(), - &replacement, - MacroWriteOptions::default(), - Duration::from_secs(5), - |final_path, backup_path| { - assert_eq!(final_path, part.as_path()); - let bak = backup_path.expect("backup must be created for existing file"); - assert!(bak.exists()); - assert_eq!(fs::read(final_path).unwrap(), before); - assert_eq!(fs::read(bak).unwrap(), before); - *observed_clone.lock().unwrap() = true; - }, - |path| fs::remove_file(path), - ) - .unwrap(); - - assert!(*observed_live.lock().unwrap()); - let actual = read_parquet_rows(&part); - assert_eq!(actual.len(), 1); - assert_row_bitwise_eq(&actual[0], &replacement[0]); - assert_no_transient_files(&tmp.path().join("macro")); -} - -#[test] -fn stale_lock_times_out_and_backup_cleanup_failure_restores_previous_file() { - let tmp = TempDirGuard::new("lock-and-rollback"); - let (part, before) = seed_existing(tmp.path()); - let lock_path = tmp.path().join("macro/.write.lock"); - fs::write(&lock_path, b"999999\n").unwrap(); - - let rows = vec![make_row( - "US", - "policy_rate", - day(2025, 5, 7), - POLICY_RATE_LAG_DAYS, - 4.5, - )]; - let err = write_macro_dataset_with_hooks( - tmp.path(), - &rows, - MacroWriteOptions::default(), - Duration::from_millis(30), - |_, _| {}, - |path| fs::remove_file(path), - ) - .unwrap_err(); - assert!( - matches!(err, ParquetMacroError::LockTimeout { ref path, .. } if path == &lock_path), - "expected LockTimeout, got {err:?}" - ); - assert!(lock_path.exists(), "stale lock must remain untouched"); - assert_eq!(fs::read(&part).unwrap(), before); - fs::remove_file(&lock_path).unwrap(); - - // Simulate backup removal failure: previous file must be restored from backup. - let err2 = write_macro_dataset_with_hooks( - tmp.path(), - &rows, - MacroWriteOptions::default(), - Duration::from_secs(5), - |_, _| {}, - |_bak| Err(io::Error::new(io::ErrorKind::PermissionDenied, "injected")), - ) - .unwrap_err(); - assert!(matches!(err2, ParquetMacroError::Io { .. })); - assert!(StdError::source(&err2).is_some()); - assert_eq!(fs::read(&part).unwrap(), before); - assert_no_transient_files(&tmp.path().join("macro")); -} - -// --------------------------------------------------------------------------- -// QA (T-173) edge cases: builder/writer ordering agreement, extreme values, -// owned iterators, I/O blockers, rename failure, concurrency, panic unwind, -// and rollback failure reporting. -// --------------------------------------------------------------------------- - -/// `build_macro_rows` sorts by `K: Ord` (byte order for `String`); the writer must accept -/// every builder output, including prefix keys (`US` < `USA`), uppercase before lowercase, -/// and non-ASCII UTF-8, and round-trip it bit-for-bit across all four lag classes. -#[test] -fn builder_byte_order_keys_and_all_lag_classes_are_accepted_and_round_trip() { - let tmp = TempDirGuard::new("builder-order"); - let base = day(2023, 12, 31); - let obs = |c: &str, i: &str, d: i32, v: f64| MacroObservation { - country_iso: c.to_string(), - indicator: i.to_string(), - period_date: d, - value: v, - }; - let observations = vec![ - obs("USA", "gdp_q", base, 1.0), - obs("US", "gdp_q", base, 2.0), - obs("US", "Gdp_q", base, 3.0), - obs("US", "gdp_q_é", base, 4.0), - obs("US", "gdp_q", base - 1, f64::MIN_POSITIVE / 2.0), // subnormal - obs("CA", "rate", base, f64::MAX), - obs("CA", "rate", base + 1, -f64::MAX), - ]; - let built = build_macro_rows(observations, |_, indicator| match indicator.as_str() { - "gdp_q" => Some(MacroLagClass::Gdp65), - "Gdp_q" => Some(MacroLagClass::Gdp90), - "gdp_q_é" => Some(MacroLagClass::MonthlyRelease), - "rate" => Some(MacroLagClass::PolicyRate), - _ => None, - }) - .expect("builder"); - assert_eq!(built.rows.len(), 7); - - let rows: Vec = built.rows.iter().map(MacroParquetRow::from).collect(); - // row_group_rows = 3 so ordering is checked across flush boundaries too. - let opts = MacroWriteOptions { - row_group_rows: 3, - ..MacroWriteOptions::default() - }; - let stats = write_macro_dataset(tmp.path(), &rows, opts).expect("builder output accepted"); - assert_eq!(stats.rows_written, 7); - assert_eq!(stats.row_groups_written, 3); - - let actual = read_parquet_rows(&tmp.path().join("macro/part.parquet")); - assert_eq!(actual.len(), built.rows.len()); - for (a, b) in actual.iter().zip(&built.rows) { - assert_eq!(a.country_iso.as_ref(), b.country_iso.as_str()); - assert_eq!(a.indicator.as_ref(), b.indicator.as_str()); - assert_eq!(a.period_date, b.period_date); - assert_eq!(a.known_at_micros, b.known_at); - assert_eq!(a.known_at_source.as_ref(), b.known_at_source); - assert_eq!(a.value.to_bits(), b.value.to_bits()); - } - let order: Vec<(&str, &str)> = actual - .iter() - .map(|r| (r.country_iso.as_ref(), r.indicator.as_ref())) - .collect(); - assert_eq!( - order, - vec![ - ("CA", "rate"), - ("CA", "rate"), - ("US", "Gdp_q"), - ("US", "gdp_q"), - ("US", "gdp_q"), - ("US", "gdp_q_é"), - ("USA", "gdp_q"), - ] - ); - // Gdp90 lag preserved exactly. - assert_eq!( - actual[2].known_at_micros, - i64::from(base + 90) * MICROS_PER_DAY - ); - assert_no_transient_files(&tmp.path().join("macro")); -} - -/// The writer stores `period_date`/`known_at` verbatim; it must not reject or alter -/// pre-1970 or extreme integers (bounds are the builder's job). -#[test] -fn extreme_dates_and_timestamps_round_trip_verbatim_with_owned_iterator() { - let tmp = TempDirGuard::new("extremes"); - let rows = vec![ - MacroParquetRow { - period_date: i32::MIN, - known_at_micros: i64::MIN, - ..make_row("AA", "x", 0, 0, 1.5) - }, - MacroParquetRow { - known_at_micros: -1, - ..make_row("AA", "x", -1, 0, -1.5) - }, - MacroParquetRow { - period_date: i32::MAX, - known_at_micros: i64::MAX, - ..make_row("AA", "x", 0, 0, 0.1) - }, - ]; - // Owned (by-value) iterator path. - let stats = - write_macro_dataset(tmp.path(), rows.clone().into_iter(), MacroWriteOptions::default()) - .unwrap(); - assert_eq!(stats.rows_written, 3); - let actual = read_parquet_rows(&tmp.path().join("macro/part.parquet")); - assert_eq!(actual.len(), 3); - for (a, e) in actual.iter().zip(&rows) { - assert_row_bitwise_eq(a, e); - } -} - -#[test] -fn out_dir_or_macro_dir_occupied_by_regular_file_returns_io_error() { - let tmp = TempDirGuard::new("io-blocker"); - let rows = vec![make_row("US", "policy_rate", day(2024, 3, 20), POLICY_RATE_LAG_DAYS, 5.5)]; - - let file_as_out = tmp.path().join("not-a-dir"); - fs::write(&file_as_out, b"sentinel").unwrap(); - let err = write_macro_dataset(&file_as_out, &rows, MacroWriteOptions::default()).unwrap_err(); - assert!(matches!(err, ParquetMacroError::Io { .. }), "got {err:?}"); - assert!(StdError::source(&err).is_some()); - assert_eq!(fs::read(&file_as_out).unwrap(), b"sentinel"); - - let out = tmp.path().join("macro-is-file"); - fs::create_dir_all(&out).unwrap(); - let macro_file = out.join("macro"); - fs::write(¯o_file, b"file-not-dir").unwrap(); - let err2 = write_macro_dataset(&out, &rows, MacroWriteOptions::default()).unwrap_err(); - assert!(matches!(err2, ParquetMacroError::Io { .. }), "got {err2:?}"); - assert_eq!(fs::read(¯o_file).unwrap(), b"file-not-dir"); -} - -#[test] -fn rename_failure_over_directory_blocker_cleans_up_staging_and_preserves_unowned_tmp() { - let tmp = TempDirGuard::new("rename-blocker"); - let macro_dir = tmp.path().join("macro"); - let blocking_dir = macro_dir.join("part.parquet"); - fs::create_dir_all(&blocking_dir).unwrap(); - let unowned_tmp = macro_dir.join("part.parquet.unowned-other-run.tmp"); - fs::write(&unowned_tmp, b"keep-me").unwrap(); - - let rows = vec![make_row("US", "policy_rate", day(2024, 3, 20), POLICY_RATE_LAG_DAYS, 5.5)]; - let err = write_macro_dataset(tmp.path(), &rows, MacroWriteOptions::default()).unwrap_err(); - assert!(matches!(err, ParquetMacroError::Io { .. }), "got {err:?}"); - assert!(blocking_dir.is_dir(), "directory blocker must remain intact"); - assert_eq!(fs::read(&unowned_tmp).unwrap(), b"keep-me"); - - let mut entries: Vec = fs::read_dir(¯o_dir) - .unwrap() - .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) - .collect(); - entries.sort(); - assert_eq!( - entries, - vec![ - "part.parquet".to_string(), - "part.parquet.unowned-other-run.tmp".to_string(), - ] - ); -} - -#[test] -fn concurrent_in_process_writers_serialize_to_one_generation() { - let tmp = TempDirGuard::new("concurrent"); - let out = Arc::new(tmp.path().to_path_buf()); - let base = day(2024, 1, 31); - - let out_1 = Arc::clone(&out); - let h1 = std::thread::spawn(move || { - let iter = (0..2_i32).map(move |i| { - if i == 1 { - std::thread::sleep(Duration::from_millis(30)); - } - make_row("CA", "cpi_yoy", base + i, MONTHLY_RELEASE_LAG_DAYS, 2.0) - }); - write_macro_dataset(out_1.as_path(), iter, MacroWriteOptions::default()) - }); - std::thread::sleep(Duration::from_millis(5)); - let out_2 = Arc::clone(&out); - let h2 = std::thread::spawn(move || { - let iter = (0..2_i32) - .map(move |i| make_row("US", "policy_rate", base + i, POLICY_RATE_LAG_DAYS, 5.5)); - write_macro_dataset(out_2.as_path(), iter, MacroWriteOptions::default()) - }); - - assert_eq!(h1.join().unwrap().unwrap().rows_written, 2); - assert_eq!(h2.join().unwrap().unwrap().rows_written, 2); - - let got = read_parquet_rows(&tmp.path().join("macro/part.parquet")); - assert_eq!(got.len(), 2); - assert!( - got.iter().all(|r| r.country_iso == "CA") || got.iter().all(|r| r.country_iso == "US"), - "output must come entirely from one writer generation" - ); - assert_no_transient_files(&tmp.path().join("macro")); -} - -#[test] -fn panicking_iterator_after_flush_cleans_staging_releases_lock_and_preserves_live_file() { - let tmp = TempDirGuard::new("panic-unwind"); - let (part, before) = seed_existing(tmp.path()); - let out = tmp.path().to_path_buf(); - let opts = MacroWriteOptions { - row_group_rows: 2, - ..MacroWriteOptions::default() - }; - let result = std::panic::catch_unwind(move || { - let base = day(2024, 1, 31); - let iter = (0..5_i32).map(move |i| { - if i == 3 { - panic!("simulated iterator panic after row-group flush"); - } - make_row("US", "cpi_yoy", base + i, MONTHLY_RELEASE_LAG_DAYS, 3.0) - }); - let _ = write_macro_dataset(&out, iter, opts); - }); - assert!(result.is_err(), "iterator must have panicked"); - assert_eq!(fs::read(&part).unwrap(), before); - assert_no_transient_files(&tmp.path().join("macro")); - - // Next writer proceeds without hitting a stale lock. - let replacement = vec![make_row("US", "policy_rate", day(2025, 1, 29), POLICY_RATE_LAG_DAYS, 4.5)]; - let stats = write_macro_dataset(tmp.path(), &replacement, MacroWriteOptions::default()).unwrap(); - assert_eq!(stats.rows_written, 1); - let got = read_parquet_rows(&part); - assert_eq!(got.len(), 1); - assert_row_bitwise_eq(&got[0], &replacement[0]); - assert_no_transient_files(&tmp.path().join("macro")); -} - -#[test] -fn backup_unlink_and_restore_failure_reports_rollback_failed() { - let tmp = TempDirGuard::new("rollback-failed"); - let (part, _before) = seed_existing(tmp.path()); - let replacement = vec![make_row("US", "policy_rate", day(2025, 1, 29), POLICY_RATE_LAG_DAYS, 4.5)]; - let observed_bak: Arc>> = Arc::new(Mutex::new(None)); - let observed_clone = Arc::clone(&observed_bak); - - let err = write_macro_dataset_with_hooks( - tmp.path(), - &replacement, - MacroWriteOptions::default(), - Duration::from_secs(5), - |_, _| {}, - move |bak| { - *observed_clone.lock().unwrap() = Some(bak.to_path_buf()); - // Remove the backup so the restore rename also fails. - let _ = fs::remove_file(bak); - Err(io::Error::new(io::ErrorKind::PermissionDenied, "injected")) - }, - ) - .unwrap_err(); - - let expected_bak = observed_bak.lock().unwrap().clone().expect("hook called"); - match err { - ParquetMacroError::RollbackFailed { cause, failures } => { - assert!( - matches!( - *cause, - ParquetMacroError::Io { ref path, ref source } - if path == &expected_bak - && source.kind() == io::ErrorKind::PermissionDenied - ), - "unexpected cause: {cause:?}" - ); - assert_eq!(failures.len(), 1); - assert_eq!(failures[0].final_path, part); - assert_eq!(failures[0].backup_path.as_deref(), Some(expected_bak.as_path())); - assert_eq!(failures[0].source.kind(), io::ErrorKind::NotFound); - } - other => panic!("expected RollbackFailed, got {other:?}"), - } - assert_no_transient_files(&tmp.path().join("macro")); -} - -#[test] -fn backup_unlink_failure_error_names_backup_path_and_restores_live_bytes() { - let tmp = TempDirGuard::new("bak-unlink-path"); - let (part, before) = seed_existing(tmp.path()); - let replacement = vec![make_row("US", "policy_rate", day(2025, 1, 29), POLICY_RATE_LAG_DAYS, 4.5)]; - let observed_bak: Arc>> = Arc::new(Mutex::new(None)); - let observed_clone = Arc::clone(&observed_bak); - - let err = write_macro_dataset_with_hooks( - tmp.path(), - &replacement, - MacroWriteOptions::default(), - Duration::from_secs(5), - |_, _| {}, - move |bak| { - *observed_clone.lock().unwrap() = Some(bak.to_path_buf()); - Err(io::Error::new(io::ErrorKind::PermissionDenied, "injected")) - }, - ) - .unwrap_err(); - let expected_bak = observed_bak.lock().unwrap().clone().expect("hook called"); - assert!( - matches!( - err, - ParquetMacroError::Io { ref path, ref source } - if path == &expected_bak && source.kind() == io::ErrorKind::PermissionDenied - ), - "got {err:?}" - ); - assert_eq!(fs::read(&part).unwrap(), before); - assert_no_transient_files(&tmp.path().join("macro")); -} - -#[test] -fn error_display_messages_name_offending_key() { - let e = ParquetMacroError::DuplicateKey { - country_iso: "US".into(), - indicator: "cpi_yoy".into(), - period_date: 19_753, - }; - assert!(e.to_string().contains("(US, cpi_yoy, 19753)"), "{e}"); - let e = ParquetMacroError::InvalidValue { - country_iso: "CA".into(), - indicator: "rate".into(), - period_date: 1, - value: f64::NAN, - }; - let msg = e.to_string(); - assert!(msg.contains("NaN") && msg.contains("must be finite"), "{msg}"); - assert!(StdError::source(&e).is_none()); -} diff --git a/tools/curate-etl/src/parquet_posts.rs b/tools/curate-etl/src/parquet_posts.rs deleted file mode 100644 index 07500644..00000000 --- a/tools/curate-etl/src/parquet_posts.rs +++ /dev/null @@ -1,109 +0,0 @@ -//! Adapter mapping curated `ceoPosts` rows ([`PostRow`] / [`PostsBuild`]) into the -//! 7-column `events` Parquet contract ([`EventsParquetRow`], `events/year=YYYY/part.parquet`). -//! -//! Aligned with `design/DATA-CONTRACTS.md` §1 & §3A and `design/PLATFORM-PLAN.md`: -//! - `kind` is always [`EVENT_KIND_POST`] (`"post"`). -//! - `subtype` is [`POST_SUBTYPE_NEWSWIRE`] (`"newswire"`) when `is_bot` is `true`, and -//! [`POST_SUBTYPE_RETAIL`] (`"retail"`) otherwise, so wire releases are never pooled with crowd -//! chat. -//! - `ts` is the posting timestamp (`posted_at`) and `known_at` is the point-in-time text -//! availability timestamp (`known_at >= posted_at`). -//! - `known_at_source` is [`KNOWN_AT_SOURCE_POST_EDITED`] (`"post_edited"`) iff -//! `known_at > posted_at`, and [`KNOWN_AT_SOURCE_POST_TIMESTAMP`] (`"post_timestamp"`) otherwise -//! (including when an edit timestamp before `posted_at` was clamped back to `posted_at`). - -use std::borrow::Cow; - -use crate::events::{push_json_opt_str, push_json_str}; -use crate::parquet_events::EventsParquetRow; -use crate::posts::{PostRow, PostsBuild}; - -/// Canonical `events.kind` label for curated `ceoPosts` rows. -pub const EVENT_KIND_POST: &str = "post"; - -/// Canonical `events.subtype` label for `bot == "1"` newswire posts. -pub const POST_SUBTYPE_NEWSWIRE: &str = "newswire"; - -/// Canonical `events.subtype` label for non-bot retail posts. -pub const POST_SUBTYPE_RETAIL: &str = "retail"; - -/// Provenance label when `known_at` equals the post's creation timestamp (`posted_at`). -pub const KNOWN_AT_SOURCE_POST_TIMESTAMP: &str = "post_timestamp"; - -/// Provenance label when `known_at` reflects a post-creation edit timestamp (`known_at > posted_at`). -pub const KNOWN_AT_SOURCE_POST_EDITED: &str = "post_edited"; - -/// Encodes a curated post's `payload_json` as a compact RFC 8259 JSON object with fixed key order: -/// `{"spiel_id":...,"user_id":...,"is_edited":...,"source":...,"text":...}`. -fn encode_post_payload_json(row: &PostRow) -> String { - let cap = 72 - + row.spiel_id.len() - + row.user_id.as_deref().map_or(4, str::len) - + row.source.len() - + row.text.len(); - let mut out = String::with_capacity(cap); - out.push_str("{\"spiel_id\":"); - push_json_str(&mut out, &row.spiel_id); - out.push_str(",\"user_id\":"); - push_json_opt_str(&mut out, row.user_id.as_deref()); - out.push_str(",\"is_edited\":"); - out.push_str(if row.is_edited { "true" } else { "false" }); - out.push_str(",\"source\":"); - push_json_str(&mut out, row.source); - out.push_str(",\"text\":"); - push_json_str(&mut out, &row.text); - out.push('}'); - out -} - -impl From<&PostRow> for EventsParquetRow { - fn from(row: &PostRow) -> Self { - let known_at_source = if row.known_at > row.posted_at { - KNOWN_AT_SOURCE_POST_EDITED - } else { - KNOWN_AT_SOURCE_POST_TIMESTAMP - }; - let subtype = if row.is_bot { - POST_SUBTYPE_NEWSWIRE - } else { - POST_SUBTYPE_RETAIL - }; - - Self { - listing_id: row.key, - ts_micros: row.posted_at, - known_at_micros: row.known_at, - known_at_source: Cow::Borrowed(known_at_source), - kind: Cow::Borrowed(EVENT_KIND_POST), - subtype: subtype.to_string(), - payload_json: encode_post_payload_json(row), - } - } -} - -impl From> for EventsParquetRow { - fn from(row: PostRow) -> Self { - Self::from(&row) - } -} - -/// Converts both `newswire` and `retail` streams of a [`PostsBuild`] into -/// [`EventsParquetRow`] records sorted in the exact order required by -/// [`crate::parquet_events::write_events_dataset`]: -/// `(listing_id, ts_micros, kind, subtype, payload_json, known_at_micros, known_at_source)`. -pub fn posts_to_event_rows(build: &PostsBuild) -> Vec { - let mut rows = Vec::with_capacity(build.newswire.len() + build.retail.len()); - rows.extend(build.newswire.iter().map(EventsParquetRow::from)); - rows.extend(build.retail.iter().map(EventsParquetRow::from)); - rows.sort_unstable_by(|a, b| { - a.listing_id - .cmp(&b.listing_id) - .then_with(|| a.ts_micros.cmp(&b.ts_micros)) - .then_with(|| a.kind.as_ref().cmp(b.kind.as_ref())) - .then_with(|| a.subtype.cmp(&b.subtype)) - .then_with(|| a.payload_json.cmp(&b.payload_json)) - .then_with(|| a.known_at_micros.cmp(&b.known_at_micros)) - .then_with(|| a.known_at_source.as_ref().cmp(b.known_at_source.as_ref())) - }); - rows -} diff --git a/tools/curate-etl/src/parquet_posts_tests.rs b/tools/curate-etl/src/parquet_posts_tests.rs deleted file mode 100644 index 69812e00..00000000 --- a/tools/curate-etl/src/parquet_posts_tests.rs +++ /dev/null @@ -1,816 +0,0 @@ -use std::borrow::Cow; -use std::collections::HashSet; -use std::fs::{self, File}; -use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; - -use parquet::basic::Compression; -use parquet::column::reader::ColumnReader; -use parquet::file::reader::{FileReader, SerializedFileReader}; - -use crate::parquet_events::{write_events_dataset, EventsParquetRow, EventsWriteOptions}; -use crate::parquet_posts::{ - posts_to_event_rows, EVENT_KIND_POST, KNOWN_AT_SOURCE_POST_EDITED, - KNOWN_AT_SOURCE_POST_TIMESTAMP, POST_SUBTYPE_NEWSWIRE, POST_SUBTYPE_RETAIL, -}; -use crate::posts::{build_posts, CeoPost, POSTS_SOURCE_CEO}; -use crate::split::ymd_to_epoch_days; - -static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0); - -struct TempDirGuard { - path: PathBuf, -} - -impl TempDirGuard { - fn new(label: &str) -> Self { - let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); - let pid = std::process::id(); - let path = - std::env::temp_dir().join(format!("curate-etl-pq-posts-test-{label}-{pid}-{seq}")); - let _ = fs::remove_dir_all(&path); - fs::create_dir_all(&path).expect("create test temp dir"); - Self { path } - } - - fn path(&self) -> &Path { - &self.path - } -} - -impl Drop for TempDirGuard { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.path); - } -} - -fn utc_ms(year: i32, month: u32, day: u32, hour: u8, minute: u8, second: u8) -> i64 { - let epoch_day = ymd_to_epoch_days(year, month, day).expect("valid test date"); - let secs = i64::from(epoch_day) * 86_400 - + i64::from(hour) * 3_600 - + i64::from(minute) * 60 - + i64::from(second); - secs * 1_000 -} - -fn post( - listing_id: i32, - spiel_id: &str, - timestamp_ms: i64, - edited_ms: Option, - bot: Option<&str>, - user_id: Option<&str>, - text: &str, -) -> CeoPost { - CeoPost { - key: listing_id, - spiel_id: spiel_id.to_string(), - timestamp_ms, - edited_ms, - bot: bot.map(str::to_string), - user_id: user_id.map(str::to_string), - text: text.to_string(), - } -} - -/// Generates all permutations of `items` via Heap's algorithm. -fn all_permutations(items: &[T]) -> Vec> { - let mut out = Vec::new(); - let mut arr = items.to_vec(); - let n = arr.len(); - let mut c = vec![0usize; n]; - out.push(arr.clone()); - - let mut i = 0; - while i < n { - if c[i] < i { - if i % 2 == 0 { - arr.swap(0, i); - } else { - arr.swap(c[i], i); - } - out.push(arr.clone()); - c[i] += 1; - i = 0; - } else { - c[i] = 0; - i += 1; - } - } - out -} - -fn read_events_parquet_and_verify_zstd(path: &Path) -> Vec { - let file = File::open(path).expect("open parquet file"); - let reader = SerializedFileReader::new(file).expect("open parquet reader"); - let meta = reader.metadata(); - let mut out = Vec::new(); - - for rg_idx in 0..meta.num_row_groups() { - let rg_meta = meta.row_group(rg_idx); - assert_eq!( - rg_meta.num_columns(), - 7, - "expected 7 columns in events schema" - ); - for col_idx in 0..rg_meta.num_columns() { - let compression = rg_meta.column(col_idx).compression(); - assert!( - matches!(compression, Compression::ZSTD(_)), - "expected ZSTD compression for row_group={rg_idx} col={col_idx}, got {compression:?}" - ); - } - - let rg_rows = rg_meta.num_rows() as usize; - let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); - - let read_i32_col = |col_idx: usize| -> Vec { - let mut vals = Vec::with_capacity(rg_rows); - match rg_reader.get_column_reader(col_idx).expect("col reader") { - ColumnReader::Int32ColumnReader(mut typed) => { - let mut read = 0usize; - while read < rg_rows { - let (n, _, _) = typed - .read_records(rg_rows - read, None, None, &mut vals) - .expect("read i32 records"); - assert!(n > 0, "unexpected short read in INT32 column {col_idx}"); - read += n; - } - } - _ => panic!("expected INT32 column at index {col_idx}"), - } - vals - }; - - let read_i64_col = |col_idx: usize| -> Vec { - let mut vals = Vec::with_capacity(rg_rows); - match rg_reader.get_column_reader(col_idx).expect("col reader") { - ColumnReader::Int64ColumnReader(mut typed) => { - let mut read = 0usize; - while read < rg_rows { - let (n, _, _) = typed - .read_records(rg_rows - read, None, None, &mut vals) - .expect("read i64 records"); - assert!(n > 0, "unexpected short read in INT64 column {col_idx}"); - read += n; - } - } - _ => panic!("expected INT64 column at index {col_idx}"), - } - vals - }; - - let read_str_col = |col_idx: usize| -> Vec { - let mut raw = Vec::with_capacity(rg_rows); - match rg_reader.get_column_reader(col_idx).expect("col reader") { - ColumnReader::ByteArrayColumnReader(mut typed) => { - let mut read = 0usize; - while read < rg_rows { - let (n, _, _) = typed - .read_records(rg_rows - read, None, None, &mut raw) - .expect("read byte_array records"); - assert!( - n > 0, - "unexpected short read in BYTE_ARRAY column {col_idx}" - ); - read += n; - } - } - _ => panic!("expected BYTE_ARRAY column at index {col_idx}"), - } - raw.iter() - .map(|b| { - std::str::from_utf8(b.data()) - .expect("valid utf8") - .to_string() - }) - .collect() - }; - - let listing_ids = read_i32_col(0); - let ts = read_i64_col(1); - let known_at = read_i64_col(2); - let known_at_source = read_str_col(3); - let kind = read_str_col(4); - let subtype = read_str_col(5); - let payload_json = read_str_col(6); - - for i in 0..rg_rows { - out.push(EventsParquetRow { - listing_id: listing_ids[i], - ts_micros: ts[i], - known_at_micros: known_at[i], - known_at_source: Cow::Owned(known_at_source[i].clone()), - kind: Cow::Owned(kind[i].clone()), - subtype: subtype[i].clone(), - payload_json: payload_json[i].clone(), - }); - } - } - - out -} - -#[test] -fn maps_retail_unedited_edited_newswire_and_clamped_edit_for_borrowed_and_owned() { - let t_post = utc_ms(2024, 6, 15, 14, 30, 0); - let t_edit_later = t_post + 600_000; // +10 minutes - let t_edit_earlier = t_post - 5_000; // -5 seconds (clamped to posted_at) - - let build = build_posts(vec![ - post( - 101, - "sp_retail_unedited", - t_post, - None, - None, - Some("u_retail"), - "Retail baseline", - ), - post( - 102, - "sp_retail_edited", - t_post, - Some(t_edit_later), - Some("0"), - Some("u_editor"), - "Edited retail text", - ), - post( - 103, - "sp_newswire", - t_post, - None, - Some("1"), - Some("thenewswire"), - "Company announces drill results", - ), - post( - 104, - "sp_edit_clamped", - t_post, - Some(t_edit_earlier), - None, - None, - "Clock-skewed edit", - ), - ]) - .expect("build_posts should succeed"); - - // Verify borrowed and owned From impls agree on every row. - for row in build.newswire.iter().chain(build.retail.iter()) { - let from_ref = EventsParquetRow::from(row); - let from_owned = EventsParquetRow::from(row.clone()); - assert_eq!(from_ref, from_owned); - } - - let mapped = posts_to_event_rows(&build); - assert_eq!(mapped.len(), 4); - - // 101: retail unedited - assert_eq!( - mapped[0], - EventsParquetRow { - listing_id: 101, - ts_micros: t_post * 1_000, - known_at_micros: t_post * 1_000, - known_at_source: Cow::Borrowed(KNOWN_AT_SOURCE_POST_TIMESTAMP), - kind: Cow::Borrowed(EVENT_KIND_POST), - subtype: POST_SUBTYPE_RETAIL.to_string(), - payload_json: format!( - "{{\"spiel_id\":\"sp_retail_unedited\",\"user_id\":\"u_retail\",\"is_edited\":false,\"source\":\"{POSTS_SOURCE_CEO}\",\"text\":\"Retail baseline\"}}" - ), - } - ); - - // 102: retail edited (known_at > posted_at) - assert_eq!( - mapped[1], - EventsParquetRow { - listing_id: 102, - ts_micros: t_post * 1_000, - known_at_micros: t_edit_later * 1_000, - known_at_source: Cow::Borrowed(KNOWN_AT_SOURCE_POST_EDITED), - kind: Cow::Borrowed(EVENT_KIND_POST), - subtype: POST_SUBTYPE_RETAIL.to_string(), - payload_json: format!( - "{{\"spiel_id\":\"sp_retail_edited\",\"user_id\":\"u_editor\",\"is_edited\":true,\"source\":\"{POSTS_SOURCE_CEO}\",\"text\":\"Edited retail text\"}}" - ), - } - ); - - // 103: newswire (bot == "1") - assert_eq!( - mapped[2], - EventsParquetRow { - listing_id: 103, - ts_micros: t_post * 1_000, - known_at_micros: t_post * 1_000, - known_at_source: Cow::Borrowed(KNOWN_AT_SOURCE_POST_TIMESTAMP), - kind: Cow::Borrowed(EVENT_KIND_POST), - subtype: POST_SUBTYPE_NEWSWIRE.to_string(), - payload_json: format!( - "{{\"spiel_id\":\"sp_newswire\",\"user_id\":\"thenewswire\",\"is_edited\":false,\"source\":\"{POSTS_SOURCE_CEO}\",\"text\":\"Company announces drill results\"}}" - ), - } - ); - - // 104: edit-before-post clamped -> known_at == ts, known_at_source == "post_timestamp", - // payload preserves is_edited: true and user_id: null. - assert_eq!( - mapped[3], - EventsParquetRow { - listing_id: 104, - ts_micros: t_post * 1_000, - known_at_micros: t_post * 1_000, - known_at_source: Cow::Borrowed(KNOWN_AT_SOURCE_POST_TIMESTAMP), - kind: Cow::Borrowed(EVENT_KIND_POST), - subtype: POST_SUBTYPE_RETAIL.to_string(), - payload_json: format!( - "{{\"spiel_id\":\"sp_edit_clamped\",\"user_id\":null,\"is_edited\":true,\"source\":\"{POSTS_SOURCE_CEO}\",\"text\":\"Clock-skewed edit\"}}" - ), - } - ); -} - -#[test] -fn payload_json_escapes_special_chars_control_chars_non_ascii_and_preserves_key_order() { - let t_post = utc_ms(2024, 7, 1, 12, 0, 0); - let build = build_posts(vec![ - post( - 10, - "sp\"with\\slash", - t_post, - None, - None, - Some("user\"1"), - "Quote \"here\", backslash \\, newline\nctrl\x01, non-ASCII café €", - ), - post( - 11, - "sp_null_user", - t_post, - Some(t_post + 1_000), - Some("1"), - None, - "Simple wire text", - ), - ]) - .expect("build_posts should succeed"); - - let rows = posts_to_event_rows(&build); - assert_eq!(rows.len(), 2); - - assert_eq!( - rows[0].payload_json, - "{\"spiel_id\":\"sp\\\"with\\\\slash\",\"user_id\":\"user\\\"1\",\"is_edited\":false,\"source\":\"ceo_posts\",\"text\":\"Quote \\\"here\\\", backslash \\\\, newline\\nctrl\\u0001, non-ASCII café €\"}" - ); - - assert_eq!( - rows[1].payload_json, - "{\"spiel_id\":\"sp_null_user\",\"user_id\":null,\"is_edited\":true,\"source\":\"ceo_posts\",\"text\":\"Simple wire text\"}" - ); -} - -#[test] -fn round_trip_writes_two_years_via_events_writer_with_zstd_and_exact_readback() { - let dir = TempDirGuard::new("round-trip"); - let t_2024_a = utc_ms(2024, 5, 10, 15, 0, 0); - let t_2024_dec = utc_ms(2024, 12, 31, 23, 55, 0); - let t_2025_jan_edit = utc_ms(2025, 1, 1, 0, 15, 0); // edited across UTC year boundary - let t_2025_feb = utc_ms(2025, 2, 20, 13, 30, 0); - - let build = build_posts(vec![ - // Two distinct posts sharing the exact same (listing_id=200, ts=t_2024_a), one newswire and one retail. - post( - 200, - "sp_2024_wire", - t_2024_a, - None, - Some("1"), - Some("thenewswire"), - "Newswire release at identical ts", - ), - post( - 200, - "sp_2024_retail_1", - t_2024_a, - None, - None, - Some("u1"), - "Retail reply 1 at identical ts", - ), - post( - 200, - "sp_2024_retail_2", - t_2024_a, - None, - None, - Some("u2"), - "Retail reply 2 at identical ts", - ), - // December 2024 post edited in January 2025: partitions by ts -> year=2024, known_at in 2025. - post( - 201, - "sp_2024_dec_edited_2025", - t_2024_dec, - Some(t_2025_jan_edit), - None, - Some("u3"), - "Edited after New Year", - ), - // 2025 newswire and retail posts. - post( - 200, - "sp_2025_wire", - t_2025_feb, - None, - Some("1"), - Some("thenewswire"), - "2025 quarterly update", - ), - post( - 202, - "sp_2025_retail", - t_2025_feb, - None, - Some("0"), - None, - "2025 retail commentary", - ), - ]) - .expect("build_posts should succeed"); - - let event_rows = posts_to_event_rows(&build); - assert_eq!(event_rows.len(), 6); - - let stats = write_events_dataset(dir.path(), &event_rows, EventsWriteOptions::default()) - .expect("write_events_dataset should accept posts_to_event_rows output"); - assert_eq!(stats.rows_written, 6); - assert_eq!(stats.files_written, 2); - assert_eq!(stats.rows_by_year.get(&2024), Some(&4)); - assert_eq!(stats.rows_by_year.get(&2025), Some(&2)); - - let path_2024 = dir.path().join("events/year=2024/part.parquet"); - let path_2025 = dir.path().join("events/year=2025/part.parquet"); - assert!(path_2024.exists(), "expected {}", path_2024.display()); - assert!(path_2025.exists(), "expected {}", path_2025.display()); - - let read_2024 = read_events_parquet_and_verify_zstd(&path_2024); - let read_2025 = read_events_parquet_and_verify_zstd(&path_2025); - - let expected_2024: Vec = event_rows - .iter() - .filter(|r| crate::events::partition_year_utc(r.ts_micros) == 2024) - .cloned() - .collect(); - let expected_2025: Vec = event_rows - .iter() - .filter(|r| crate::events::partition_year_utc(r.ts_micros) == 2025) - .cloned() - .collect(); - - assert_eq!(read_2024, expected_2024); - assert_eq!(read_2025, expected_2025); - - // Verify all read-back rows have kind == "post", both subtypes are present, and newswire vs - // retail spiel_ids are strictly disjoint (never sharing a subtype). - let mut newswire_payloads = HashSet::new(); - let mut retail_payloads = HashSet::new(); - for row in read_2024.iter().chain(read_2025.iter()) { - assert_eq!(row.kind.as_ref(), EVENT_KIND_POST); - match row.subtype.as_str() { - POST_SUBTYPE_NEWSWIRE => { - assert!(newswire_payloads.insert(row.payload_json.clone())); - } - POST_SUBTYPE_RETAIL => { - assert!(retail_payloads.insert(row.payload_json.clone())); - } - other => panic!("unexpected post subtype: {other}"), - } - } - assert_eq!(newswire_payloads.len(), 2); - assert_eq!(retail_payloads.len(), 4); - assert!(newswire_payloads.is_disjoint(&retail_payloads)); - - // Confirm the Dec 2024 post edited in Jan 2025 landed in year=2024 with 2025 known_at. - let dec_row = read_2024 - .iter() - .find(|r| r.listing_id == 201) - .expect("December post must be in year=2024 partition"); - assert_eq!(dec_row.ts_micros, t_2024_dec * 1_000); - assert_eq!(dec_row.known_at_micros, t_2025_jan_edit * 1_000); - assert_eq!( - dec_row.known_at_source.as_ref(), - KNOWN_AT_SOURCE_POST_EDITED - ); -} - -#[test] -fn posts_to_event_rows_is_permutation_invariant_and_handles_empty_input() { - let empty_build = build_posts(Vec::>::new()).expect("empty build"); - assert!(posts_to_event_rows(&empty_build).is_empty()); - - let t0 = utc_ms(2024, 9, 1, 14, 0, 0); - let t1 = t0 + 30_000; - let fixture = vec![ - // Conflicting duplicate spiel_id: later edit wins regardless of input order. - post(50, "sp_dup", t0, None, None, Some("u1"), "Original text"), - post( - 50, - "sp_dup", - t0, - Some(t1), - None, - Some("u1"), - "Edited duplicate survivor", - ), - // Two distinct posts sharing (listing_id=50, ts=t0), one newswire and one retail. - post( - 50, - "sp_same_ts_wire", - t0, - None, - Some("1"), - Some("thenewswire"), - "Wire at t0", - ), - post( - 50, - "sp_same_ts_retail", - t0, - None, - None, - Some("u2"), - "Retail at t0", - ), - // Separate listing. - post( - 40, - "sp_other_listing", - t1, - None, - None, - None, - "Earlier listing", - ), - ]; - - let reference = posts_to_event_rows(&build_posts(fixture.clone()).expect("reference build")); - assert_eq!(reference.len(), 4); - let reference_payload_bytes: Vec<&[u8]> = reference - .iter() - .map(|r| r.payload_json.as_bytes()) - .collect(); - - let perms = all_permutations(&fixture); - assert_eq!(perms.len(), 120); - for perm in perms { - let got = posts_to_event_rows(&build_posts(perm).expect("permuted build")); - assert_eq!(got, reference); - let got_payload_bytes: Vec<&[u8]> = got.iter().map(|r| r.payload_json.as_bytes()).collect(); - assert_eq!(got_payload_bytes, reference_payload_bytes); - } -} - -#[test] -fn point_in_time_guard_excludes_edited_post_until_edit_timestamp() { - let t_post = utc_ms(2024, 8, 12, 13, 30, 0); - let t_edit = t_post + 900_000; // +15 minutes - - let build = build_posts(vec![ - post( - 300, - "sp_unedited", - t_post, - None, - None, - Some("u1"), - "Posted at open", - ), - post( - 300, - "sp_edited", - t_post, - Some(t_edit), - None, - Some("u2"), - "Edited 15m later with hindsight", - ), - ]) - .expect("build_posts should succeed"); - - let rows = posts_to_event_rows(&build); - let edited = rows - .iter() - .find(|r| r.payload_json.contains("\"sp_edited\"")) - .expect("edited row present"); - - assert_eq!(edited.ts_micros, t_post * 1_000); - assert_eq!(edited.known_at_micros, t_edit * 1_000); - assert_ne!(edited.known_at_micros, edited.ts_micros); - assert_eq!(edited.known_at_source.as_ref(), KNOWN_AT_SOURCE_POST_EDITED); - - // As-of cutoff between posting and editing must exclude the edited post. - let cutoff_between = (t_post + 300_000) * 1_000; - let visible_between: Vec<&EventsParquetRow> = rows - .iter() - .filter(|r| r.known_at_micros <= cutoff_between) - .collect(); - assert_eq!(visible_between.len(), 1); - assert!(visible_between[0].payload_json.contains("\"sp_unedited\"")); - - // As-of cutoff at the exact edit timestamp includes both. - let visible_at_edit: Vec<&EventsParquetRow> = rows - .iter() - .filter(|r| r.known_at_micros <= t_edit * 1_000) - .collect(); - assert_eq!(visible_at_edit.len(), 2); -} - -// --------------------------------------------------------------------------------------------- -// QA edge cases (T-157) -// --------------------------------------------------------------------------------------------- - -#[test] -fn same_listing_and_ts_rows_are_ordered_by_payload_not_builder_known_at_order() { - // `build_posts` orders by (key, known_at, spiel_id), so the later-edited `retail_1` comes - // after `retail_2`. The writer orders by payload before known_at, so the adapter must flip it. - let dir = TempDirGuard::new("payload-tiebreak"); - let t_post = utc_ms(2024, 3, 4, 15, 0, 0); - let build = build_posts(vec![ - post( - 7, - "sp_retail_1", - t_post, - Some(t_post + 120_000), - None, - Some("u1"), - "first by payload, edited later", - ), - post( - 7, - "sp_retail_2", - t_post, - None, - None, - Some("u2"), - "second by payload", - ), - ]) - .expect("build_posts"); - assert_eq!( - build.retail[0].spiel_id, "sp_retail_2", - "builder sorts by known_at first" - ); - - let rows = posts_to_event_rows(&build); - assert!(rows[0].payload_json.contains("\"sp_retail_1\"")); - assert!(rows[1].payload_json.contains("\"sp_retail_2\"")); - assert_eq!(rows[0].known_at_micros, (t_post + 120_000) * 1_000); - assert_eq!( - rows[0].known_at_source.as_ref(), - KNOWN_AT_SOURCE_POST_EDITED - ); - - write_events_dataset(dir.path(), &rows, EventsWriteOptions::default()) - .expect("writer accepts payload-ordered rows"); - let back = - read_events_parquet_and_verify_zstd(&dir.path().join("events/year=2024/part.parquet")); - assert_eq!(back, rows); -} - -#[test] -fn rows_are_reordered_by_ts_when_an_earlier_post_was_edited_after_a_later_post() { - // Builder order is by known_at; the writer needs ts order within a listing. - let dir = TempDirGuard::new("ts-reorder"); - let t1 = utc_ms(2023, 11, 1, 10, 0, 0); - let t2 = utc_ms(2023, 11, 1, 11, 0, 0); - let t1_edit = utc_ms(2023, 11, 2, 9, 0, 0); - let build = build_posts(vec![ - post(5, "sp_late", t2, None, Some("1"), None, "later wire"), - post( - 5, - "sp_early_edited", - t1, - Some(t1_edit), - None, - Some("u"), - "early, edited next day", - ), - post(4, "sp_other", t2, None, None, None, "lower listing"), - ]) - .expect("build_posts"); - - let rows = posts_to_event_rows(&build); - let order: Vec<(i32, i64)> = rows.iter().map(|r| (r.listing_id, r.ts_micros)).collect(); - assert_eq!( - order, - vec![(4, t2 * 1_000), (5, t1 * 1_000), (5, t2 * 1_000)] - ); - - let stats = write_events_dataset(dir.path(), &rows, EventsWriteOptions::default()) - .expect("writer accepts ts-ordered rows"); - assert_eq!(stats.rows_written, 3); -} - -#[test] -fn newswire_requires_trimmed_bot_one_and_everything_else_is_retail() { - let t = utc_ms(2024, 1, 2, 12, 0, 0); - let build = build_posts(vec![ - post(1, "sp_ws", t, None, Some(" 1 "), None, "wire padded"), - post(1, "sp_true", t, None, Some("true"), None, "not wire"), - post(1, "sp_empty", t, None, Some(""), None, "not wire"), - post(1, "sp_two", t, None, Some("2"), None, "not wire"), - ]) - .expect("build_posts"); - - let rows = posts_to_event_rows(&build); - assert_eq!(rows.len(), 4); - for row in &rows { - assert_eq!(row.kind.as_ref(), EVENT_KIND_POST); - let expected = if row.payload_json.contains("\"sp_ws\"") { - POST_SUBTYPE_NEWSWIRE - } else { - POST_SUBTYPE_RETAIL - }; - assert_eq!(row.subtype, expected, "payload={}", row.payload_json); - } -} - -#[test] -fn edit_exactly_at_posting_time_is_post_timestamp_and_keeps_is_edited() { - let t = utc_ms(2024, 2, 29, 23, 59, 59); - let build = build_posts(vec![post(9, "sp_same", t, Some(t), None, None, "x")]).expect("build"); - let row = EventsParquetRow::from(&build.retail[0]); - assert_eq!(row.known_at_micros, row.ts_micros); - assert_eq!(row.known_at_source.as_ref(), KNOWN_AT_SOURCE_POST_TIMESTAMP); - assert!(row.payload_json.contains("\"is_edited\":true")); -} - -#[test] -fn multiple_row_groups_round_trip_and_rewrite_is_byte_identical() { - let t0 = utc_ms(2022, 6, 1, 0, 0, 0); - let fixture: Vec> = (0..11) - .map(|i| { - post( - i % 3, - &format!("sp_{i:02}"), - t0 + i64::from(i) * 60_000, - if i % 4 == 0 { - Some(t0 + 86_400_000) - } else { - None - }, - if i % 2 == 0 { Some("1") } else { None }, - Some("u"), - "row-group text", - ) - }) - .collect(); - let rows = posts_to_event_rows(&build_posts(fixture).expect("build")); - let options = EventsWriteOptions { - row_group_rows: 3, - ..EventsWriteOptions::default() - }; - - let dir_a = TempDirGuard::new("rg-a"); - let dir_b = TempDirGuard::new("rg-b"); - write_events_dataset(dir_a.path(), &rows, options).expect("write a"); - write_events_dataset(dir_b.path(), &rows, options).expect("write b"); - - let path_a = dir_a.path().join("events/year=2022/part.parquet"); - let path_b = dir_b.path().join("events/year=2022/part.parquet"); - let reader = SerializedFileReader::new(File::open(&path_a).expect("open")).expect("reader"); - assert_eq!(reader.metadata().num_row_groups(), 4); - drop(reader); - - assert_eq!(read_events_parquet_and_verify_zstd(&path_a), rows); - assert_eq!( - fs::read(&path_a).expect("read a"), - fs::read(&path_b).expect("read b"), - "same posts must produce byte-identical Parquet" - ); -} - -#[test] -fn post_2200_timestamp_is_preserved_by_adapter_and_rejected_by_writer() { - let dir = TempDirGuard::new("year-range"); - // `build_posts` rejects `timestamp_ms <= 0`, so the reachable out-of-range side is > 2200. - let t = utc_ms(2201, 1, 1, 12, 0, 0); - let rows = posts_to_event_rows( - &build_posts(vec![post(1, "sp_old", t, None, None, None, "old")]).expect("build"), - ); - assert_eq!(rows[0].ts_micros, t * 1_000); - - let err = write_events_dataset(dir.path(), &rows, EventsWriteOptions::default()) - .expect_err("writer must reject year 2201"); - assert!( - matches!( - err, - crate::parquet_events::ParquetEventsError::PartitionYearOutOfRange { year: 2201, .. } - ), - "got {err:?}" - ); - assert!(!dir.path().join("events/year=2201").exists()); -} diff --git a/tools/curate-etl/src/parquet_publish.rs b/tools/curate-etl/src/parquet_publish.rs index 358bbf27..fd9b89c2 100644 --- a/tools/curate-etl/src/parquet_publish.rs +++ b/tools/curate-etl/src/parquet_publish.rs @@ -310,10 +310,6 @@ impl StagingFileGuard { pub(crate) fn disarm(&mut self) { self.path = None; } - - pub(crate) fn is_armed(&self) -> bool { - self.path.is_some() - } } impl Drop for StagingFileGuard { @@ -367,25 +363,6 @@ fn next_column<'a>( } } -pub(crate) fn write_bool_col( - rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter>, - values: &[bool], - def_levels: Option<&[i16]>, -) -> Result<(), ParquetError> { - let mut col = next_column(rg_writer)?; - match col.untyped() { - ColumnWriter::BoolColumnWriter(typed) => { - typed.write_batch(values, def_levels, None)?; - } - _ => { - return Err(ParquetError::General( - "expected BOOLEAN column writer".to_string(), - )); - } - } - col.close() -} - pub(crate) fn write_i32_col( rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter>, values: &[i32], diff --git a/tools/curate-etl/src/posts.rs b/tools/curate-etl/src/posts.rs deleted file mode 100644 index a4af96cb..00000000 --- a/tools/curate-etl/src/posts.rs +++ /dev/null @@ -1,250 +0,0 @@ -//! Pure, in-memory `posts` builder for `ceoPosts` (`bot == "1"` newswire vs. retail split, -//! `edited` text point-in-time `known_at` guard, and deterministic global `spielId` deduplication). -//! -//! Aligned with `design/DATA-CONTRACTS.md` §1 (`ceoSymbols`, `ceoPosts`, `ceoShorts` row): -//! - Separates `bot == "1"` newswire posts (e.g. `@thenewswire`) from retail posts so wire -//! releases are never pooled with crowd chat. -//! - Computes text availability as `known_at = COALESCE(edited, timestamp)` in UTC microseconds, -//! clamped so `known_at >= posted_at` always holds. -//! - **Point-in-time rule:** any text-based feature or sentiment model MUST join on `known_at`, -//! never `posted_at`. In `ceoPosts`, an edit overwrites `spiel` in place without version -//! history, so the builder retains one supplied version per `spiel_id` and cannot recover -//! earlier pre-edit text. -//! - See [`crate::parquet_posts`] for mapping [`PostRow`] / [`PostsBuild`] into the -//! `events` Parquet contract (`kind = "post"`, `subtype = "newswire" | "retail"`). - -use std::error::Error; -use std::fmt; - -/// Canonical provenance label written to [`PostRow::source`]. -pub const POSTS_SOURCE_CEO: &str = "ceo_posts"; - -/// Typed errors returned by [`build_posts`]. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum PostsError { - /// Converting a millisecond timestamp (`timestamp_ms` or `edited_ms`) to UTC microseconds - /// overflowed `i64`. - TimestampOverflow { - spiel_id: String, - field: &'static str, - timestamp_ms: i64, - }, -} - -impl fmt::Display for PostsError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::TimestampOverflow { - spiel_id, - field, - timestamp_ms, - } => write!( - f, - "timestamp overflow converting {field}={timestamp_ms} ms to UTC microseconds for spiel_id '{spiel_id}'" - ), - } - } -} - -impl Error for PostsError {} - -/// A single already-decoded `ceoPosts` input row. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct CeoPost { - /// Channel / `ceoId` (or resolved listing key). - pub key: K, - /// Provider post identifier (`spielId`, MongoDB upsert key). - pub spiel_id: String, - /// Provider post creation time in epoch milliseconds (`timestamp`). - pub timestamp_ms: i64, - /// Optional provider last-edit time in epoch milliseconds (`edited`). - pub edited_ms: Option, - /// Raw provider bot flag (`bot`; only `"1"` after trim classifies as newswire). - pub bot: Option, - /// Optional provider author identifier (`userId`). - pub user_id: Option, - /// Post text (`spiel`). - pub text: String, -} - -/// A single curated `ceoPosts` output row. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct PostRow { - pub key: K, - pub spiel_id: String, - /// Post creation timestamp in UTC microseconds (`timestamp_ms * 1_000`). - pub posted_at: i64, - /// Point-in-time text availability timestamp in UTC microseconds (`max(posted_at, edited_at)`). - /// Downstream text features MUST join on `known_at`, never `posted_at`. - pub known_at: i64, - pub is_bot: bool, - pub is_edited: bool, - pub user_id: Option, - pub text: String, - pub source: &'static str, -} - -/// Summary accounting counters produced alongside [`PostsBuild::newswire`] and -/// [`PostsBuild::retail`]. -/// -/// Conservation invariant: -/// `input == newswire + retail + duplicates_dropped + rejected_invalid` -/// -/// Accounting note: `edited` and `edited_before_posted` are counted on valid input rows before -/// `spiel_id` deduplication (so they include valid duplicates and exclude `rejected_invalid`). -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct PostsStats { - pub input: usize, - pub newswire: usize, - pub retail: usize, - pub edited: usize, - pub edited_before_posted: usize, - pub duplicates_dropped: usize, - pub rejected_invalid: usize, -} - -/// Output of [`build_posts`]: disjoint, deterministically sorted `newswire` and `retail` streams -/// plus exact accounting stats. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct PostsBuild { - pub newswire: Vec>, - pub retail: Vec>, - pub stats: PostsStats, -} - -/// Builds disjoint, deterministically sorted `newswire` and `retail` post streams from raw -/// `ceoPosts` inputs. -/// -/// Rules: -/// - Rejects (counts in [`PostsStats::rejected_invalid`] without aborting) rows with an empty -/// `spiel_id` or `timestamp_ms <= 0` before timestamp conversion. -/// - Classifies `is_bot` as `true` iff `bot` is `"1"` after trimming whitespace; all other values -/// (`None`, `"0"`, `""`, etc.) route to `retail`. -/// - Sets `is_edited = edited_ms.is_some()`, counts valid edited rows in [`PostsStats::edited`], -/// and guards against look-ahead / clock-skew edits earlier than posting (`edited_ms < -/// timestamp_ms`) by clamping `known_at` to `posted_at` and incrementing -/// [`PostsStats::edited_before_posted`]. Both edit counters are recorded on valid rows prior to -/// deduplication. -/// - Converts `timestamp_ms` and the selected `known_at` millisecond value to UTC microseconds via -/// `checked_mul(1_000)`, returning [`PostsError::TimestampOverflow`] on overflow. -/// - Deduplicates globally on `spiel_id` before splitting into `newswire` and `retail` (keeping -/// one supplied version per `spiel_id`; earlier pre-edit versions cannot be recovered). Within a -/// `spiel_id` group, the survivor is the row with the greatest `known_at`, breaking ties -/// deterministically by the maximum lexicographic tuple -/// `(posted_at, is_edited, is_bot, key, user_id, text)` (`None < Some` for `user_id`), with zero -/// dependence on input order. All other `group_len - 1` rows are counted in -/// [`PostsStats::duplicates_dropped`]. -/// - Sorts both `newswire` and `retail` strictly ascending by `(key, known_at, spiel_id)`. -/// - Any permutation of `rows` produces identical `newswire`, `retail`, and `stats`. -pub fn build_posts(rows: I) -> Result, PostsError> -where - K: Ord + Clone, - I: IntoIterator>, -{ - let iter = rows.into_iter(); - let (lower, _) = iter.size_hint(); - let mut stats = PostsStats::default(); - let mut normalized: Vec> = Vec::with_capacity(lower); - - for row in iter { - stats.input += 1; - - if row.spiel_id.is_empty() || row.timestamp_ms <= 0 { - stats.rejected_invalid += 1; - continue; - } - - let is_bot = row.bot.as_deref().map(str::trim) == Some("1"); - let is_edited = row.edited_ms.is_some(); - - let known_at_ms = match row.edited_ms { - Some(edited_ms) => { - stats.edited += 1; - if edited_ms < row.timestamp_ms { - stats.edited_before_posted += 1; - row.timestamp_ms - } else { - edited_ms - } - } - None => row.timestamp_ms, - }; - - let posted_at = - row.timestamp_ms - .checked_mul(1_000) - .ok_or_else(|| PostsError::TimestampOverflow { - spiel_id: row.spiel_id.clone(), - field: "timestamp_ms", - timestamp_ms: row.timestamp_ms, - })?; - - let known_at = if known_at_ms == row.timestamp_ms { - posted_at - } else { - known_at_ms - .checked_mul(1_000) - .ok_or_else(|| PostsError::TimestampOverflow { - spiel_id: row.spiel_id.clone(), - field: "edited_ms", - timestamp_ms: known_at_ms, - })? - }; - - normalized.push(PostRow { - key: row.key, - spiel_id: row.spiel_id, - posted_at, - known_at, - is_bot, - is_edited, - user_id: row.user_id, - text: row.text, - source: POSTS_SOURCE_CEO, - }); - } - - normalized.sort_unstable_by(|a, b| { - a.spiel_id - .cmp(&b.spiel_id) - .then_with(|| b.known_at.cmp(&a.known_at)) - .then_with(|| b.posted_at.cmp(&a.posted_at)) - .then_with(|| b.is_edited.cmp(&a.is_edited)) - .then_with(|| b.is_bot.cmp(&a.is_bot)) - .then_with(|| b.key.cmp(&a.key)) - .then_with(|| b.user_id.cmp(&a.user_id)) - .then_with(|| b.text.cmp(&a.text)) - }); - - let before_dedup = normalized.len(); - normalized.dedup_by(|a, b| a.spiel_id == b.spiel_id); - stats.duplicates_dropped = before_dedup - normalized.len(); - - let mut newswire: Vec> = Vec::new(); - let mut retail: Vec> = Vec::new(); - for row in normalized { - if row.is_bot { - newswire.push(row); - } else { - retail.push(row); - } - } - - let output_order = |a: &PostRow, b: &PostRow| { - a.key - .cmp(&b.key) - .then_with(|| a.known_at.cmp(&b.known_at)) - .then_with(|| a.spiel_id.cmp(&b.spiel_id)) - }; - newswire.sort_unstable_by(output_order); - retail.sort_unstable_by(output_order); - - stats.newswire = newswire.len(); - stats.retail = retail.len(); - - Ok(PostsBuild { - newswire, - retail, - stats, - }) -} diff --git a/tools/curate-etl/src/posts_tests.rs b/tools/curate-etl/src/posts_tests.rs deleted file mode 100644 index 53f0f91d..00000000 --- a/tools/curate-etl/src/posts_tests.rs +++ /dev/null @@ -1,988 +0,0 @@ -use std::collections::HashSet; - -use crate::posts::{ - build_posts, CeoPost, PostRow, PostsBuild, PostsError, PostsStats, POSTS_SOURCE_CEO, -}; - -fn post( - key: &str, - spiel_id: &str, - timestamp_ms: i64, - edited_ms: Option, - bot: Option<&str>, - user_id: Option<&str>, - text: &str, -) -> CeoPost { - CeoPost { - key: key.to_string(), - spiel_id: spiel_id.to_string(), - timestamp_ms, - edited_ms, - bot: bot.map(str::to_string), - user_id: user_id.map(str::to_string), - text: text.to_string(), - } -} - -fn assert_invariants(build: &PostsBuild) { - let s = &build.stats; - assert_eq!( - s.input, - s.newswire + s.retail + s.duplicates_dropped + s.rejected_invalid, - "accounting invariant failed: {s:?}" - ); - assert_eq!(s.newswire, build.newswire.len()); - assert_eq!(s.retail, build.retail.len()); - assert!(s.edited_before_posted <= s.edited); - - let mut seen_ids = HashSet::with_capacity(s.newswire + s.retail); - for (stream_name, rows, expected_bot) in [ - ("newswire", &build.newswire, true), - ("retail", &build.retail, false), - ] { - for pair in rows.windows(2) { - assert!( - (&pair[0].key, pair[0].known_at, &pair[0].spiel_id) - < (&pair[1].key, pair[1].known_at, &pair[1].spiel_id), - "{stream_name} must be strictly sorted by (key, known_at, spiel_id)" - ); - } - for row in rows { - assert_eq!(row.is_bot, expected_bot); - assert_eq!(row.source, POSTS_SOURCE_CEO); - assert!( - row.known_at >= row.posted_at, - "look-ahead violation in {stream_name}: known_at {} < posted_at {}", - row.known_at, - row.posted_at - ); - assert!( - seen_ids.insert(row.spiel_id.as_str()), - "spiel_id '{}' appeared more than once across streams", - row.spiel_id - ); - } - } -} - -/// Deterministic SplitMix64 PRNG for fixture generation and shuffles. -struct SplitMix64(u64); - -impl SplitMix64 { - fn next_u64(&mut self) -> u64 { - self.0 = self.0.wrapping_add(0x9e37_79b9_7f4a_7c15); - let mut z = self.0; - z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); - z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); - z ^ (z >> 31) - } - - fn shuffle(&mut self, slice: &mut [T]) { - for i in (1..slice.len()).rev() { - let j = (self.next_u64() as usize) % (i + 1); - slice.swap(i, j); - } - } -} - -/// Generates all permutations of `items` via Heap's algorithm. -fn all_permutations(items: &[T]) -> Vec> { - let mut out = Vec::new(); - let mut arr = items.to_vec(); - let n = arr.len(); - let mut c = vec![0usize; n]; - out.push(arr.clone()); - - let mut i = 0; - while i < n { - if c[i] < i { - if i % 2 == 0 { - arr.swap(0, i); - } else { - arr.swap(c[i], i); - } - out.push(arr.clone()); - c[i] += 1; - i = 0; - } else { - c[i] = 0; - i += 1; - } - } - out -} - -#[test] -fn bot_split_routes_only_trimmed_one_to_newswire_and_preserves_fields() { - let input = vec![ - post( - "chan_a", - "sp_bot_exact", - 1_700_000_000_000, - None, - Some("1"), - Some("wire_user"), - "News release headline", - ), - post( - "chan_b", - "sp_bot_trimmed", - 1_700_000_001_000, - None, - Some(" 1 "), - None, - "Trimmed bot flag release", - ), - post( - "chan_a", - "sp_retail_zero", - 1_700_000_002_000, - None, - Some("0"), - Some("u1"), - "Retail zero flag", - ), - post( - "chan_a", - "sp_retail_empty", - 1_700_000_003_000, - None, - Some(""), - Some("u2"), - "Retail empty flag", - ), - post( - "chan_b", - "sp_retail_none", - 1_700_000_004_000, - None, - None, - None, - "Retail missing flag", - ), - post( - "chan_b", - "sp_retail_other", - 1_700_000_005_000, - None, - Some("true"), - Some("u3"), - "Non-1 string is retail", - ), - ]; - - let built = build_posts(input).expect("valid posts should build"); - assert_invariants(&built); - - assert_eq!( - built.stats, - PostsStats { - input: 6, - newswire: 2, - retail: 4, - edited: 0, - edited_before_posted: 0, - duplicates_dropped: 0, - rejected_invalid: 0, - } - ); - - assert_eq!( - built.newswire, - vec![ - PostRow { - key: "chan_a".to_string(), - spiel_id: "sp_bot_exact".to_string(), - posted_at: 1_700_000_000_000_000, - known_at: 1_700_000_000_000_000, - is_bot: true, - is_edited: false, - user_id: Some("wire_user".to_string()), - text: "News release headline".to_string(), - source: POSTS_SOURCE_CEO, - }, - PostRow { - key: "chan_b".to_string(), - spiel_id: "sp_bot_trimmed".to_string(), - posted_at: 1_700_000_001_000_000, - known_at: 1_700_000_001_000_000, - is_bot: true, - is_edited: false, - user_id: None, - text: "Trimmed bot flag release".to_string(), - source: POSTS_SOURCE_CEO, - }, - ] - ); - - let retail_ids: Vec<&str> = built.retail.iter().map(|r| r.spiel_id.as_str()).collect(); - assert_eq!( - retail_ids, - vec![ - "sp_retail_zero", - "sp_retail_empty", - "sp_retail_none", - "sp_retail_other" - ] - ); - assert_eq!(built.retail[0].user_id.as_deref(), Some("u1")); - assert_eq!(built.retail[0].text, "Retail zero flag"); - assert_eq!(built.retail[2].user_id, None); - assert_eq!(built.retail[2].source, POSTS_SOURCE_CEO); -} - -#[test] -fn edited_timestamps_guard_known_at_and_availability_cutoff() { - let t_post = 1_710_000_000_000_i64; - let t_edit_later = t_post + 720_000; // +12 minutes - let t_edit_earlier = t_post - 5_000; // -5 seconds (clock skew) - - let input = vec![ - post( - "TSX:ABC", - "sp_unedited", - t_post, - None, - None, - Some("u1"), - "Unedited baseline", - ), - post( - "TSX:ABC", - "sp_edited_equal", - t_post, - Some(t_post), - None, - Some("u2"), - "Edited at exact post ms", - ), - post( - "TSX:ABC", - "sp_edited_later", - t_post, - Some(t_edit_later), - None, - Some("u3"), - "Rewritten after move", - ), - post( - "TSX:ABC", - "sp_edited_earlier", - t_post, - Some(t_edit_earlier), - None, - Some("u4"), - "Skewed edit timestamp", - ), - ]; - - let built = build_posts(input).expect("valid posts should build"); - assert_invariants(&built); - - assert_eq!(built.stats.edited, 3); - assert_eq!(built.stats.edited_before_posted, 1); - - let by_id = |id: &str| { - built - .retail - .iter() - .find(|r| r.spiel_id == id) - .expect("expected row in retail") - }; - - let unedited = by_id("sp_unedited"); - assert_eq!(unedited.posted_at, t_post * 1_000); - assert_eq!(unedited.known_at, t_post * 1_000); - assert!(!unedited.is_edited); - - let equal = by_id("sp_edited_equal"); - assert_eq!(equal.posted_at, t_post * 1_000); - assert_eq!(equal.known_at, t_post * 1_000); - assert!(equal.is_edited); - - let later = by_id("sp_edited_later"); - assert_eq!(later.posted_at, t_post * 1_000); - assert_eq!(later.known_at, t_edit_later * 1_000); - assert!(later.is_edited); - - // Point-in-time availability check: at a cutoff strictly between posted_at and edited_at, - // the unedited post is visible (known_at < cutoff) while the edited post is NOT yet visible. - let cutoff = (t_post + 300_000) * 1_000; // +5 minutes after post - assert!(unedited.known_at < cutoff); - assert!(later.posted_at < cutoff); - assert!(later.known_at > cutoff); - - let earlier = by_id("sp_edited_earlier"); - assert_eq!(earlier.posted_at, t_post * 1_000); - assert_eq!(earlier.known_at, t_post * 1_000); - assert!(earlier.is_edited); -} - -#[test] -fn generated_fixture_preserves_known_at_ge_posted_at_and_edit_accounting() { - let mut rng = SplitMix64(0x5eed_cafe_1234_5678); - let mut input = Vec::with_capacity(220); - let mut expected_edited = 0usize; - let mut expected_edited_before_posted = 0usize; - let mut expected_rejected = 0usize; - - // 200 valid rows (including intentional duplicate spiel_ids across 120 buckets). - for i in 0..200usize { - let key = format!("CH_{:02}", rng.next_u64() % 10); - let spiel_id = format!("sp_{:03}", rng.next_u64() % 120); - let timestamp_ms = 1_700_000_000_000 + (rng.next_u64() % 10_000_000) as i64; - let edit_mode = rng.next_u64() % 4; - let edited_ms = match edit_mode { - 0 => None, - 1 => { - expected_edited += 1; - Some(timestamp_ms + (rng.next_u64() % 900_000) as i64 + 1) - } - 2 => { - expected_edited += 1; - expected_edited_before_posted += 1; - Some(timestamp_ms - (rng.next_u64() % 60_000) as i64 - 1) - } - _ => { - expected_edited += 1; - Some(timestamp_ms) - } - }; - let bot = match rng.next_u64() % 5 { - 0 => Some("1"), - 1 => Some(" 1 "), - 2 => Some("0"), - 3 => Some(""), - _ => None, - }; - input.push(post( - &key, - &spiel_id, - timestamp_ms, - edited_ms, - bot, - Some(&format!("u{}", i % 17)), - &format!("generated post {i}"), - )); - } - - // 20 rejected rows (some carrying edited_ms that must NOT count toward edited stats). - for i in 0..20usize { - expected_rejected += 1; - if i % 2 == 0 { - input.push(post( - "CH_BAD", - "", - 1_700_000_000_000, - Some(1_699_999_999_000), - Some("1"), - None, - "empty id", - )); - } else { - input.push(post( - "CH_BAD", - &format!("bad_ts_{i}"), - -(i as i64), - Some(-(i as i64) - 100), - None, - None, - "non-positive ts", - )); - } - } - - let built = build_posts(input).expect("generated fixture should build"); - assert_invariants(&built); - assert_eq!(built.stats.input, 220); - assert_eq!(built.stats.rejected_invalid, expected_rejected); - assert_eq!(built.stats.edited, expected_edited); - assert_eq!( - built.stats.edited_before_posted, - expected_edited_before_posted - ); - assert!(built.stats.duplicates_dropped > 0); -} - -#[test] -fn dedup_keeps_greatest_known_at_globally_across_channels_and_streams() { - let base_ms = 1_720_000_000_000_i64; - let input = vec![ - post( - "chan_a", - "shared_id", - base_ms, - None, - Some("1"), - Some("wire"), - "v1 newswire", - ), - post( - "chan_b", - "shared_id", - base_ms, - Some(base_ms + 120_000), - Some("0"), - Some("retail_u"), - "v2 edited later in another channel/stream", - ), - post( - "chan_c", - "shared_id", - base_ms + 60_000, - None, - Some("1"), - Some("wire"), - "v1.5 intermediate known_at", - ), - ]; - - let built = build_posts(input).expect("valid posts should build"); - assert_invariants(&built); - - assert_eq!(built.stats.input, 3); - assert_eq!(built.stats.newswire, 0); - assert_eq!(built.stats.retail, 1); - assert_eq!(built.stats.duplicates_dropped, 2); - assert_eq!(built.retail[0].key, "chan_b"); - assert_eq!(built.retail[0].known_at, (base_ms + 120_000) * 1_000); - assert_eq!( - built.retail[0].text, - "v2 edited later in another channel/stream" - ); -} - -fn conflicting_tie_group() -> Vec> { - let t = 1_725_000_000_000_i64; - vec![ - // Same spiel_id & same known_at = t * 1_000, differing in text and bot flag. - post( - "chan_m", - "tie_spiel", - t, - None, - Some("0"), - Some("u_b"), - "alpha text", - ), - post( - "chan_m", - "tie_spiel", - t, - None, - Some("0"), - Some("u_b"), - "zeta text", - ), - // is_bot = true beats is_bot = false on same (known_at, posted_at, is_edited). - post( - "chan_m", - "tie_spiel", - t, - None, - Some("1"), - Some("u_a"), - "bot winner text", - ), - // is_edited = true beats is_edited = false on same (known_at, posted_at), even with bot="0". - post( - "chan_a", - "tie_spiel", - t, - Some(t), - Some("0"), - None, - "edited winner text", - ), - ] -} - -#[test] -fn dedup_conflicting_known_at_ties_pick_exact_tuple_winner_across_all_permutations() { - let group = conflicting_tie_group(); - let expected_drops = group.len() - 1; - let perms = all_permutations(&group); - assert_eq!(perms.len(), 24); - - let baseline = build_posts(group).expect("tie group should build"); - assert_invariants(&baseline); - assert_eq!(baseline.stats.duplicates_dropped, expected_drops); - assert_eq!(baseline.newswire.len(), 0); - assert_eq!(baseline.retail.len(), 1); - assert_eq!(baseline.retail[0].text, "edited winner text"); - assert!(baseline.retail[0].is_edited); - assert!(!baseline.retail[0].is_bot); - - for perm in perms { - let built = build_posts(perm).expect("permutation should build"); - assert_eq!(built, baseline); - } - - // Also verify each individual tie-break field in exact precedence order: - // (posted_at, is_edited, is_bot, key, user_id [None < Some], text). - let t = 1_725_000_100_000_i64; - // 1. posted_at beats is_edited - let b1 = build_posts(vec![ - post( - "z", - "tb1", - t - 1_000, - Some(t), - Some("1"), - Some("z"), - "earlier post edited to t", - ), - post( - "a", - "tb1", - t, - None, - Some("0"), - None, - "later posted_at wins", - ), - ]) - .unwrap(); - assert_eq!(b1.retail[0].text, "later posted_at wins"); - - // 2. is_bot beats key - let b2 = build_posts(vec![ - post("zzz", "tb2", t, None, Some("0"), Some("z"), "retail"), - post("aaa", "tb2", t, None, Some("1"), None, "bot wins"), - ]) - .unwrap(); - assert_eq!(b2.newswire[0].text, "bot wins"); - - // 3. key beats user_id - let b3 = build_posts(vec![ - post("chan_a", "tb3", t, None, Some("0"), Some("zzz"), "low key"), - post("chan_z", "tb3", t, None, Some("0"), None, "high key wins"), - ]) - .unwrap(); - assert_eq!(b3.retail[0].text, "high key wins"); - - // 4. user_id (None < Some) beats text - let b4 = build_posts(vec![ - post("chan_a", "tb4", t, None, Some("0"), None, "zzz text"), - post( - "chan_a", - "tb4", - t, - None, - Some("0"), - Some("a"), - "some user_id wins", - ), - ]) - .unwrap(); - assert_eq!(b4.retail[0].text, "some user_id wins"); - - // 5. text breaks final tie - let b5 = build_posts(vec![ - post("chan_a", "tb5", t, None, Some("0"), Some("u1"), "alpha"), - post("chan_a", "tb5", t, None, Some("0"), Some("u1"), "omega"), - ]) - .unwrap(); - assert_eq!(b5.retail[0].text, "omega"); -} - -#[test] -fn shuffle_invariance_with_conflicting_ties_and_sort_order() { - let mut fixture = conflicting_tie_group(); - fixture.extend([ - post( - "chan_b", - "sp_10", - 1_725_000_010_000, - None, - Some("1"), - Some("wire"), - "wire 10", - ), - post( - "chan_a", - "sp_02", - 1_725_000_020_000, - None, - Some("1"), - Some("wire"), - "wire 02", - ), - post( - "chan_a", - "sp_01", - 1_725_000_020_000, - None, - Some("1"), - Some("wire"), - "wire 01 same known_at", - ), - post( - "chan_b", - "sp_20", - 1_725_000_005_000, - Some(1_725_000_030_000), - None, - Some("u20"), - "retail edited later", - ), - post( - "chan_b", - "sp_20", - 1_725_000_005_000, - None, - None, - Some("u20"), - "retail older version", - ), - post( - "chan_a", - "sp_03", - 1_725_000_001_000, - Some(1_725_000_000_000), - Some("0"), - Some("u03"), - "retail edited before posted", - ), - post( - "chan_a", - "", - 1_725_000_001_000, - None, - Some("1"), - None, - "invalid empty id", - ), - post( - "chan_a", - "sp_bad_ts", - 0, - None, - None, - None, - "invalid zero ts", - ), - ]); - - let baseline = build_posts(fixture.clone()).expect("fixture should build"); - assert_invariants(&baseline); - - // Reversed order. - let mut reversed = fixture.clone(); - reversed.reverse(); - assert_eq!(build_posts(reversed).unwrap(), baseline); - - // Multiple deterministic shuffles. - let mut rng = SplitMix64(0x1234_5678_9abc_def0); - for _ in 0..16 { - let mut shuffled = fixture.clone(); - rng.shuffle(&mut shuffled); - let built = build_posts(shuffled).expect("shuffled fixture should build"); - assert_eq!(built, baseline); - } - - // Verify generic non-String key (e.g., listing_id: i32) works identically. - let int_keyed = build_posts(vec![ - CeoPost { - key: 200_i32, - spiel_id: "s2".to_string(), - timestamp_ms: 1_700_000_000_000, - edited_ms: None, - bot: None, - user_id: None, - text: "listing 200".to_string(), - }, - CeoPost { - key: 100_i32, - spiel_id: "s1".to_string(), - timestamp_ms: 1_700_000_000_000, - edited_ms: None, - bot: Some("1".to_string()), - user_id: None, - text: "listing 100".to_string(), - }, - ]) - .expect("i32 keys should build"); - assert_invariants(&int_keyed); - assert_eq!(int_keyed.newswire[0].key, 100); - assert_eq!(int_keyed.retail[0].key, 200); -} - -#[test] -fn empty_invalid_and_timestamp_overflow_boundaries() { - // Empty input. - let empty = build_posts(Vec::>::new()).expect("empty input should succeed"); - assert!(empty.newswire.is_empty()); - assert!(empty.retail.is_empty()); - assert_eq!(empty.stats, PostsStats::default()); - - // Empty spiel_id, zero timestamp_ms, negative timestamp_ms (including i64::MIN). - let invalid = build_posts(vec![ - post("c", "", 1_700_000_000_000, None, Some("1"), None, "empty id"), - post("c", "sp_zero", 0, None, None, None, "zero ts"), - post("c", "sp_neg", -1, None, None, None, "negative ts"), - post("c", "sp_min", i64::MIN, None, None, None, "i64 min ts"), - ]) - .expect("invalid rows should be rejected, not error"); - assert_invariants(&invalid); - assert_eq!(invalid.stats.input, 4); - assert_eq!(invalid.stats.rejected_invalid, 4); - assert_eq!(invalid.stats.newswire, 0); - assert_eq!(invalid.stats.retail, 0); - - // Greatest convertible millisecond value succeeds for both timestamp_ms and edited_ms. - let max_ms = i64::MAX / 1_000; - let boundary_ok = build_posts(vec![ - post("c", "sp_max_post", max_ms, None, None, None, "max posted"), - post( - "c", - "sp_max_edit", - max_ms - 1, - Some(max_ms), - None, - None, - "max edited", - ), - // Clamped earlier edited_ms = i64::MIN must not overflow when rejected in favor of timestamp_ms. - post( - "c", - "sp_clamped_min_edit", - 1_000, - Some(i64::MIN), - None, - None, - "clamped min edit", - ), - ]) - .expect("max convertible ms should succeed"); - assert_invariants(&boundary_ok); - assert_eq!(boundary_ok.stats.retail, 3); - assert_eq!(boundary_ok.stats.edited, 2); - assert_eq!(boundary_ok.stats.edited_before_posted, 1); - - // Overflow on timestamp_ms returns typed PostsError::TimestampOverflow. - let err_post = build_posts(vec![post( - "c", - "sp_overflow_post", - max_ms + 1, - None, - None, - None, - "overflow post", - )]) - .expect_err("timestamp_ms overflow should error"); - assert_eq!( - err_post, - PostsError::TimestampOverflow { - spiel_id: "sp_overflow_post".to_string(), - field: "timestamp_ms", - timestamp_ms: max_ms + 1, - } - ); - assert!(err_post.to_string().contains("timestamp_ms")); - assert!(err_post.to_string().contains("sp_overflow_post")); - - // Overflow on selected edited_ms returns typed PostsError::TimestampOverflow. - let err_edit = build_posts(vec![post( - "c", - "sp_overflow_edit", - 1_700_000_000_000, - Some(max_ms + 1), - None, - None, - "overflow edit", - )]) - .expect_err("edited_ms overflow should error"); - assert_eq!( - err_edit, - PostsError::TimestampOverflow { - spiel_id: "sp_overflow_edit".to_string(), - field: "edited_ms", - timestamp_ms: max_ms + 1, - } - ); - assert!(err_edit.to_string().contains("edited_ms")); - assert!(err_edit.to_string().contains("sp_overflow_edit")); -} - -#[test] -fn bot_flag_whitespace_and_near_miss_values() { - let base = 1_730_000_000_000_i64; - let input = vec![ - post("c", "b_exact", base, None, Some("1"), None, "exact"), - post("c", "b_tabs", base + 1, None, Some("\t1\r\n"), None, "tabs"), - post("c", "r_leading_zero", base + 2, None, Some("01"), None, "01"), - post("c", "r_decimal", base + 3, None, Some("1.0"), None, "1.0"), - post("c", "r_plus", base + 4, None, Some("+1"), None, "+1"), - post("c", "r_ten", base + 5, None, Some("10"), None, "10"), - post("c", "r_two_ones", base + 6, None, Some("1 1"), None, "1 1"), - post("c", "r_spaces", base + 7, None, Some(" "), None, "spaces"), - ]; - - let built = build_posts(input).expect("valid posts should build"); - assert_invariants(&built); - - let wire_ids: Vec<&str> = built.newswire.iter().map(|r| r.spiel_id.as_str()).collect(); - let retail_ids: Vec<&str> = built.retail.iter().map(|r| r.spiel_id.as_str()).collect(); - assert_eq!(wire_ids, vec!["b_exact", "b_tabs"]); - assert_eq!( - retail_ids, - vec![ - "r_leading_zero", - "r_decimal", - "r_plus", - "r_ten", - "r_two_ones", - "r_spaces", - ] - ); -} - -#[test] -fn exact_duplicate_rows_collapse_and_preserve_pre_dedup_edit_counts() { - let t = 1_730_100_000_000_i64; - let edited_dup = post( - "TSXV:XYZ", - "dup_edited", - t, - Some(t + 60_000), - Some("0"), - Some("u1"), - "exact same edited text", - ); - let skewed_dup = post( - "TSXV:XYZ", - "dup_skewed", - t + 1_000, - Some(t), - Some("1"), - Some("wire"), - "exact same skewed wire", - ); - - let input = vec![ - edited_dup.clone(), - edited_dup.clone(), - edited_dup, - skewed_dup.clone(), - skewed_dup, - ]; - - let built = build_posts(input).expect("exact duplicates should build"); - assert_invariants(&built); - assert_eq!( - built.stats, - PostsStats { - input: 5, - newswire: 1, - retail: 1, - edited: 5, - edited_before_posted: 2, - duplicates_dropped: 3, - rejected_invalid: 0, - } - ); - assert_eq!(built.retail[0].spiel_id, "dup_edited"); - assert_eq!(built.newswire[0].spiel_id, "dup_skewed"); -} - -#[test] -fn dedup_alternating_stream_winners_and_losers_across_shuffles() { - let t = 1_730_200_000_000_i64; - let fixture = vec![ - // Group 1: newswire wins over retail via higher known_at. - post("c1", "sp_01", t, None, Some("0"), Some("r1"), "retail v1"), - post("c1", "sp_01", t, Some(t + 5_000), Some("1"), Some("w1"), "wire v2"), - // Group 2: retail wins over newswire via higher known_at. - post("c1", "sp_02", t, None, Some("1"), Some("w2"), "wire v1"), - post("c1", "sp_02", t, Some(t + 5_000), Some("0"), Some("r2"), "retail v2"), - // Group 3: newswire wins over retail via tie-break (is_bot = true > false). - post("c1", "sp_03", t, None, Some("0"), Some("r3"), "retail tie"), - post("c1", "sp_03", t, None, Some("1"), Some("w3"), "wire tie"), - // Group 4: retail wins over newswire via tie-break (is_edited = true > false). - post("c1", "sp_04", t, None, Some("1"), Some("w4"), "wire unedited"), - post("c1", "sp_04", t, Some(t), Some("0"), Some("r4"), "retail edited"), - ]; - - let baseline = build_posts(fixture.clone()).expect("alternating fixture should build"); - assert_invariants(&baseline); - assert_eq!(baseline.stats.newswire, 2); - assert_eq!(baseline.stats.retail, 2); - assert_eq!(baseline.stats.duplicates_dropped, 4); - - let wire_ids: Vec<&str> = baseline - .newswire - .iter() - .map(|r| r.spiel_id.as_str()) - .collect(); - let retail_ids: Vec<&str> = baseline - .retail - .iter() - .map(|r| r.spiel_id.as_str()) - .collect(); - assert_eq!(wire_ids, vec!["sp_03", "sp_01"]); - assert_eq!(retail_ids, vec!["sp_04", "sp_02"]); - - let mut rng = SplitMix64(0xdead_beef_cafe_babe); - for _ in 0..32 { - let mut shuffled = fixture.clone(); - rng.shuffle(&mut shuffled); - let built = build_posts(shuffled).expect("shuffled alternating fixture should build"); - assert_eq!(built, baseline); - } -} - -#[test] -fn cutoff_filter_on_known_at_hides_post_edited_after_cutoff() { - // Mirrors the worked example: cutoff at 15:45, six retail posts (one posted at 15:40 and - // rewritten at 15:52 after the stock drops), plus three unedited wire releases. - let t_1530 = 1_730_300_000_000_i64; - let t_1540 = t_1530 + 10 * 60_000; - let t_1545_cutoff_us = (t_1530 + 15 * 60_000) * 1_000; - let t_1552 = t_1530 + 22 * 60_000; - - let input = vec![ - post("TSXV:EX", "r1", t_1530, None, None, Some("u1"), "+1"), - post("TSXV:EX", "r2", t_1530 + 60_000, None, None, Some("u2"), "+1"), - post("TSXV:EX", "r3", t_1530 + 120_000, None, None, Some("u3"), "0"), - post("TSXV:EX", "r4", t_1530 + 180_000, None, None, Some("u4"), "-1"), - post("TSXV:EX", "r5", t_1530 + 240_000, None, None, Some("u5"), "0"), - post( - "TSXV:EX", - "r6_edited_after_cutoff", - t_1540, - Some(t_1552), - None, - Some("u6"), - "-1 rewritten after drop", - ), - post("TSXV:EX", "w1", t_1530 + 30_000, None, Some("1"), Some("wire"), "+1"), - post("TSXV:EX", "w2", t_1530 + 90_000, None, Some("1"), Some("wire"), "+1"), - post("TSXV:EX", "w3", t_1530 + 150_000, None, Some("1"), Some("wire"), "+1"), - ]; - - let built = build_posts(input).expect("worked example should build"); - assert_invariants(&built); - assert_eq!(built.retail.len(), 6); - assert_eq!(built.newswire.len(), 3); - - // Filtering retail on known_at < cutoff excludes the post edited at 15:52. - let visible_by_known_at: Vec<&str> = built - .retail - .iter() - .filter(|r| r.known_at < t_1545_cutoff_us) - .map(|r| r.spiel_id.as_str()) - .collect(); - assert_eq!(visible_by_known_at.len(), 5); - assert!(!visible_by_known_at.contains(&"r6_edited_after_cutoff")); - - // Filtering on posted_at < cutoff would leak the post edited at 15:52. - let leaked_by_posted_at: Vec<&str> = built - .retail - .iter() - .filter(|r| r.posted_at < t_1545_cutoff_us) - .map(|r| r.spiel_id.as_str()) - .collect(); - assert_eq!(leaked_by_posted_at.len(), 6); - assert!(leaked_by_posted_at.contains(&"r6_edited_after_cutoff")); -} diff --git a/tools/curate-etl/src/run_curate_adj.rs b/tools/curate-etl/src/run_curate_adj.rs deleted file mode 100644 index 7e0f5ef4..00000000 --- a/tools/curate-etl/src/run_curate_adj.rs +++ /dev/null @@ -1,1151 +0,0 @@ -//! File-to-file `curate-adj-factors` command runner (`M1.2aa`). -//! -//! Streams concatenated raw BSON `qmSplits` and `qmDividends` dump files alongside -//! `provider_mapping.tsv` and a curated `bars_1d/year=YYYY/part.parquet` dataset into an -//! atomically published retrospective `/adj_factors/part.parquet` snapshot via -//! [`curate_and_write_adj_factors`]. -//! -//! # `prev_close` Information Boundary -//! - Loads only 4 of the 12 `bars_1d` columns (`listing_id`, `session_date`, `close`, `currency`) -//! in bounded `65_536`-row batches into a compact in-RAM [`PrevCloseIndex`] (`16 bytes/bar`, -//! currency strings interned to `u16`). -//! - For each decoded `qmDividends` document, resolves `("qm", qmSearchCode, ex_date)` via -//! [`ProviderMappingTable`]. When mapped, attaches the raw `close` and `currency` of the last -//! `bars_1d` session **strictly before** `ex_date` (`session_date < ex_date`); a bar on -//! `ex_date` itself is never used. When no earlier bar exists (or the dividend is unmapped), -//! `prev_close` and `prev_close_currency` are `None`. -//! - `usdFxRate` stays ignored per `design/DATA-CONTRACTS.md` §1; `splitratio == 1` no-op -//! handling stays delegated unchanged to [`curate_and_write_adj_factors`]. -//! -//! # Counter Conservation Invariants -//! Every successful [`CurateAdjFactorsRunReport`] satisfies: -//! - Splits: -//! `splits_docs_framed as usize == splits_decode.docs_in` -//! `splits_decode.docs_in == splits_decode.rejected_total() + curate_stats.splits_dropped_unmapped + curate_stats.splits_dropped_fenced + curate_stats.splits_collision_collapsed + curate_stats.builder.split_events_in` -//! - Dividends: -//! `dividends_docs_framed as usize == dividends_decode.docs_in` -//! `dividends_decode.docs_in == dividends_decode.rejected_total() + curate_stats.dividends_dropped_unmapped + curate_stats.dividends_dropped_fenced + curate_stats.dividends_collision_collapsed + curate_stats.builder.dividend_events_in` -//! `dividends_decode.decoded == dividends_with_prev_close + dividends_without_prev_close + curate_stats.dividends_dropped_unmapped` -//! -//! # Retrospective Snapshot Caveat -//! `curate-adj-factors` publishes an unfenced [`crate::curate_adj::AdjSnapshotKind::RetrospectiveSnapshot`] -//! whose earlier cumulative factors embed later splits/dividends. Point-in-time readers -//! (`read_adj_factors_dataset_as_of`) reject retrospective snapshots automatically. - -use std::collections::{HashMap, HashSet}; -use std::error::Error; -use std::fmt; -use std::fs::{self, File}; -use std::io; -use std::path::{Path, PathBuf}; -use std::sync::Arc; -use std::time::Instant; - -use parquet::column::reader::ColumnReader; -use parquet::data_type::ByteArray; -use parquet::errors::ParquetError; -use parquet::file::reader::{FileReader, SerializedFileReader}; - -use crate::adj::DividendEvent; -use crate::bson_qm_actions::BsonQmActionDecodeStats; -use crate::bson_stream::{ - decode_qm_dividend_chunks, decode_qm_split_chunks, BsonStreamError, BsonStreamOptions, - RawBsonChunkReader, -}; -use crate::curate_adj::{ - curate_adj_factors, curate_and_write_adj_factors, curate_and_write_adj_factors_as_of, - write_adj_factors_snapshot_parquet, AdjPointInTimeFence, CurateAdjError, - CurateAdjFactorsStats, CurateAdjWriteError, -}; -use crate::parquet_adj::{AdjFactorsParquetRow, AdjFactorsWriteOptions, AdjFactorsWriteStats}; -use crate::parquet_bars::bars_1d_parquet_schema; -use crate::provider_mapping::{ProviderMappingError, ProviderMappingTable}; -use crate::run_curate_bars::{load_provider_mapping_tsv, RunCurateBarsError}; -use crate::split::SplitEvent; - -/// Bounded per-batch row count for column-projected `bars_1d` Parquet reads. -const BARS_READ_BATCH_ROWS: usize = 65_536; - -/// Column indices in [`bars_1d_parquet_schema`]. -const COL_BARS_LISTING_ID: usize = 0; -const COL_BARS_SESSION_DATE: usize = 2; -const COL_BARS_CLOSE: usize = 6; -const COL_BARS_CURRENCY: usize = 9; - -/// Parsed arguments for the `curate-adj-factors` CLI command. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct CurateAdjFactorsArgs { - pub qm_splits: PathBuf, - pub qm_dividends: PathBuf, - pub provider_mapping: PathBuf, - pub bars_1d_dir: PathBuf, - pub out_dir: PathBuf, -} - -/// Full run report produced by [`run_curate_adj_factors`]. -/// -/// Conservation invariants: -/// - `splits_docs_framed as usize == splits_decode.docs_in == splits_decode.rejected_total() + curate_stats.splits_dropped_unmapped + curate_stats.splits_dropped_fenced + curate_stats.splits_collision_collapsed + curate_stats.builder.split_events_in` -/// - `dividends_docs_framed as usize == dividends_decode.docs_in == dividends_decode.rejected_total() + curate_stats.dividends_dropped_unmapped + curate_stats.dividends_dropped_fenced + curate_stats.dividends_collision_collapsed + curate_stats.builder.dividend_events_in` -/// - `dividends_decode.decoded == dividends_with_prev_close + dividends_without_prev_close + curate_stats.dividends_dropped_unmapped` -#[derive(Debug, Clone, PartialEq)] -pub struct CurateAdjFactorsRunReport { - pub bars_files_read: usize, - pub bars_rows_loaded: usize, - pub bars_listings_indexed: usize, - pub splits_docs_framed: u64, - pub splits_bytes_read: u64, - pub splits_decode: BsonQmActionDecodeStats, - pub dividends_docs_framed: u64, - pub dividends_bytes_read: u64, - pub dividends_decode: BsonQmActionDecodeStats, - pub dividends_with_prev_close: usize, - pub dividends_without_prev_close: usize, - pub curate_stats: CurateAdjFactorsStats, - pub write_stats: AdjFactorsWriteStats, - pub elapsed_secs: f64, -} - -/// Stage-timed run output used internally by `bench-curate-adj-cmd`. -#[derive(Debug, Clone, PartialEq)] -pub(crate) struct CurateAdjFactorsTimedRun { - pub report: CurateAdjFactorsRunReport, - pub bars_load_elapsed_secs: f64, - pub decode_elapsed_secs: f64, - pub curate_elapsed_secs: f64, - pub write_elapsed_secs: f64, - pub checksum: u64, -} - -/// Typed errors returned by [`run_curate_adj_factors`]. -/// -/// Every variant's `Display` output is a single line naming the offending path (and 1-based line -/// number for TSV parse errors). -#[derive(Debug)] -pub enum RunCurateAdjError { - InvalidOutDir { - path: PathBuf, - detail: String, - }, - InvalidBars1dDir { - path: PathBuf, - detail: String, - }, - OpenInput { - label: &'static str, - path: PathBuf, - source: io::Error, - }, - ReadInput { - label: &'static str, - path: PathBuf, - source: io::Error, - }, - TsvParse { - path: PathBuf, - line: usize, - detail: String, - }, - ProviderMapping { - path: PathBuf, - source: ProviderMappingError, - }, - BarsParquetSchemaMismatch { - path: PathBuf, - }, - BarsParquetRead { - path: PathBuf, - source: ParquetError, - }, - BarsParquetIntegrity { - path: PathBuf, - detail: String, - }, - BsonStream { - label: &'static str, - path: PathBuf, - source: BsonStreamError, - }, - CurateWrite { - out_dir: PathBuf, - input_path: Option, - source: CurateAdjWriteError, - }, -} - -impl fmt::Display for RunCurateAdjError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::InvalidOutDir { path, detail } => { - write!(f, "invalid --out '{}': {detail}", path.display()) - } - Self::InvalidBars1dDir { path, detail } => { - write!(f, "invalid --bars-1d '{}': {detail}", path.display()) - } - Self::OpenInput { - label, - path, - source, - } => write!(f, "failed to open {label} '{}': {source}", path.display()), - Self::ReadInput { - label, - path, - source, - } => write!(f, "failed to read {label} '{}': {source}", path.display()), - Self::TsvParse { path, line, detail } => { - write!(f, "{}:{line}: {detail}", path.display()) - } - Self::ProviderMapping { path, source } => { - write!(f, "invalid provider_mapping '{}': {source}", path.display()) - } - Self::BarsParquetSchemaMismatch { path } => { - write!(f, "bars_1d Parquet schema mismatch at '{}'", path.display()) - } - Self::BarsParquetRead { path, source } => { - write!( - f, - "failed reading bars_1d Parquet '{}': {source}", - path.display() - ) - } - Self::BarsParquetIntegrity { path, detail } => { - write!( - f, - "bars_1d Parquet integrity error at '{}': {detail}", - path.display() - ) - } - Self::BsonStream { - label, - path, - source, - } => write!(f, "failed reading {label} '{}': {source}", path.display()), - Self::CurateWrite { - out_dir, - input_path, - source, - } => match input_path { - Some(path) => write!( - f, - "curate failed for '{}' (out '{}'): {source}", - path.display(), - out_dir.display() - ), - None => write!(f, "curate/write to '{}' failed: {source}", out_dir.display()), - }, - } - } -} - -impl Error for RunCurateAdjError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::OpenInput { source, .. } | Self::ReadInput { source, .. } => Some(source), - Self::ProviderMapping { source, .. } => Some(source), - Self::BarsParquetRead { source, .. } => Some(source), - Self::BsonStream { source, .. } => Some(source), - Self::CurateWrite { source, .. } => Some(source), - Self::InvalidOutDir { .. } - | Self::InvalidBars1dDir { .. } - | Self::TsvParse { .. } - | Self::BarsParquetSchemaMismatch { .. } - | Self::BarsParquetIntegrity { .. } => None, - } - } -} - -#[derive(Debug, Clone, Copy)] -struct BarCloseEntry { - close: f64, - session_date: i32, - currency_id: u16, -} - -const _: () = assert!(std::mem::size_of::() == 16); - -#[derive(Default)] -struct CurrencyInterner { - to_id: HashMap, - strings: Vec, -} - -impl CurrencyInterner { - fn intern(&mut self, value: &str, path: &Path) -> Result { - if let Some(&id) = self.to_id.get(value) { - return Ok(id); - } - let next_id = u16::try_from(self.strings.len()).map_err(|_| { - RunCurateAdjError::BarsParquetIntegrity { - path: path.to_path_buf(), - detail: "more than 65536 distinct currencies in bars_1d".to_string(), - } - })?; - self.strings.push(value.to_owned()); - self.to_id.insert(value.to_owned(), next_id); - Ok(next_id) - } - - #[inline] - fn get(&self, id: u16) -> &str { - self.strings[usize::from(id)].as_str() - } -} - -struct PrevCloseIndex { - by_listing: HashMap>, - currencies: CurrencyInterner, - files_read: usize, - rows_loaded: usize, -} - -impl PrevCloseIndex { - /// Returns `(close, currency)` of the last `bars_1d` session strictly before `ex_date` - /// (`session_date < ex_date`) for `listing_id`, or `None` if no earlier bar exists. - #[inline] - fn lookup(&self, listing_id: i32, ex_date: i32) -> Option<(f64, &str)> { - let entries = self.by_listing.get(&listing_id)?; - let idx = entries.partition_point(|e| e.session_date < ex_date); - if idx == 0 { - return None; - } - let entry = entries[idx - 1]; - Some((entry.close, self.currencies.get(entry.currency_id))) - } -} - -fn validate_out_dir(out_dir: &Path) -> Result<(), RunCurateAdjError> { - if out_dir.exists() && !out_dir.is_dir() { - return Err(RunCurateAdjError::InvalidOutDir { - path: out_dir.to_path_buf(), - detail: "path exists and is not a directory".to_string(), - }); - } - Ok(()) -} - -fn parse_year_partition_name(name: &str) -> Option { - let suffix = name.strip_prefix("year=")?; - if suffix.len() != 4 || !suffix.bytes().all(|b| b.is_ascii_digit()) { - return None; - } - suffix.parse::().ok() -} - -fn collect_year_partitions(dir: &Path) -> Result, RunCurateAdjError> { - let read_dir = fs::read_dir(dir).map_err(|source| RunCurateAdjError::ReadInput { - label: "bars-1d", - path: dir.to_path_buf(), - source, - })?; - let mut partitions = Vec::new(); - for entry_res in read_dir { - let entry = entry_res.map_err(|source| RunCurateAdjError::ReadInput { - label: "bars-1d", - path: dir.to_path_buf(), - source, - })?; - let file_name = entry.file_name(); - let Some(name_str) = file_name.to_str() else { - continue; - }; - if let Some(year) = parse_year_partition_name(name_str) { - partitions.push((year, entry.path())); - } - } - partitions.sort_unstable_by_key(|(year, _)| *year); - Ok(partitions) -} - -fn discover_bars_1d_part_files(bars_1d_dir: &Path) -> Result, RunCurateAdjError> { - if !bars_1d_dir.exists() { - return Err(RunCurateAdjError::InvalidBars1dDir { - path: bars_1d_dir.to_path_buf(), - detail: "directory does not exist".to_string(), - }); - } - if !bars_1d_dir.is_dir() { - return Err(RunCurateAdjError::InvalidBars1dDir { - path: bars_1d_dir.to_path_buf(), - detail: "path is not a directory".to_string(), - }); - } - - let mut partitions = collect_year_partitions(bars_1d_dir)?; - if partitions.is_empty() { - let nested = bars_1d_dir.join("bars_1d"); - if nested.is_dir() { - partitions = collect_year_partitions(&nested)?; - } - } - - if partitions.is_empty() { - return Err(RunCurateAdjError::InvalidBars1dDir { - path: bars_1d_dir.to_path_buf(), - detail: "no year=YYYY partitions found (expected year=YYYY/part.parquet or bars_1d/year=YYYY/part.parquet)".to_string(), - }); - } - - let mut files = Vec::with_capacity(partitions.len()); - for (_year, part_dir) in partitions { - if !part_dir.is_dir() { - return Err(RunCurateAdjError::InvalidBars1dDir { - path: part_dir, - detail: "year partition entry is not a directory".to_string(), - }); - } - let part_file = part_dir.join("part.parquet"); - if !part_file.is_file() { - return Err(RunCurateAdjError::InvalidBars1dDir { - path: part_file, - detail: "missing part.parquet in year partition".to_string(), - }); - } - files.push(part_file); - } - - Ok(files) -} - -fn load_prev_close_index(bars_1d_dir: &Path) -> Result { - let part_files = discover_bars_1d_part_files(bars_1d_dir)?; - let expected_schema = - bars_1d_parquet_schema().map_err(|source| RunCurateAdjError::BarsParquetRead { - path: bars_1d_dir.to_path_buf(), - source, - })?; - - let mut by_listing: HashMap> = HashMap::new(); - let mut currencies = CurrencyInterner::default(); - let mut rows_loaded: usize = 0; - - let mut batch_listing_ids: Vec = Vec::with_capacity(BARS_READ_BATCH_ROWS); - let mut batch_session_dates: Vec = Vec::with_capacity(BARS_READ_BATCH_ROWS); - let mut batch_closes: Vec = Vec::with_capacity(BARS_READ_BATCH_ROWS); - let mut batch_currencies: Vec = Vec::with_capacity(BARS_READ_BATCH_ROWS); - - for part_path in &part_files { - let file = File::open(part_path).map_err(|source| RunCurateAdjError::OpenInput { - label: "bars-1d", - path: part_path.clone(), - source, - })?; - let reader = - SerializedFileReader::new(file).map_err(|source| RunCurateAdjError::BarsParquetRead { - path: part_path.clone(), - source, - })?; - - if reader.metadata().file_metadata().schema_descr().root_schema() - != expected_schema.as_ref() - { - return Err(RunCurateAdjError::BarsParquetSchemaMismatch { - path: part_path.clone(), - }); - } - - let file_meta = reader.metadata(); - for rg_idx in 0..file_meta.num_row_groups() { - let rg_reader = reader.get_row_group(rg_idx).map_err(|source| { - RunCurateAdjError::BarsParquetRead { - path: part_path.clone(), - source, - } - })?; - let num_rows = usize::try_from(file_meta.row_group(rg_idx).num_rows()).map_err(|_| { - RunCurateAdjError::BarsParquetIntegrity { - path: part_path.clone(), - detail: "negative or overflowing row-group row count".to_string(), - } - })?; - - let mut listing_col = match rg_reader - .get_column_reader(COL_BARS_LISTING_ID) - .map_err(|source| RunCurateAdjError::BarsParquetRead { - path: part_path.clone(), - source, - })? { - ColumnReader::Int32ColumnReader(r) => r, - _ => { - return Err(RunCurateAdjError::BarsParquetSchemaMismatch { - path: part_path.clone(), - }); - } - }; - let mut date_col = match rg_reader - .get_column_reader(COL_BARS_SESSION_DATE) - .map_err(|source| RunCurateAdjError::BarsParquetRead { - path: part_path.clone(), - source, - })? { - ColumnReader::Int32ColumnReader(r) => r, - _ => { - return Err(RunCurateAdjError::BarsParquetSchemaMismatch { - path: part_path.clone(), - }); - } - }; - let mut close_col = match rg_reader - .get_column_reader(COL_BARS_CLOSE) - .map_err(|source| RunCurateAdjError::BarsParquetRead { - path: part_path.clone(), - source, - })? { - ColumnReader::DoubleColumnReader(r) => r, - _ => { - return Err(RunCurateAdjError::BarsParquetSchemaMismatch { - path: part_path.clone(), - }); - } - }; - let mut curr_col = match rg_reader - .get_column_reader(COL_BARS_CURRENCY) - .map_err(|source| RunCurateAdjError::BarsParquetRead { - path: part_path.clone(), - source, - })? { - ColumnReader::ByteArrayColumnReader(r) => r, - _ => { - return Err(RunCurateAdjError::BarsParquetSchemaMismatch { - path: part_path.clone(), - }); - } - }; - - let mut remaining = num_rows; - while remaining > 0 { - let batch = remaining.min(BARS_READ_BATCH_ROWS); - batch_listing_ids.clear(); - batch_session_dates.clear(); - batch_closes.clear(); - batch_currencies.clear(); - - let (n_lid, _, _) = listing_col - .read_records(batch, None, None, &mut batch_listing_ids) - .map_err(|source| RunCurateAdjError::BarsParquetRead { - path: part_path.clone(), - source, - })?; - let (n_date, _, _) = date_col - .read_records(batch, None, None, &mut batch_session_dates) - .map_err(|source| RunCurateAdjError::BarsParquetRead { - path: part_path.clone(), - source, - })?; - let (n_close, _, _) = close_col - .read_records(batch, None, None, &mut batch_closes) - .map_err(|source| RunCurateAdjError::BarsParquetRead { - path: part_path.clone(), - source, - })?; - let (n_curr, _, _) = curr_col - .read_records(batch, None, None, &mut batch_currencies) - .map_err(|source| RunCurateAdjError::BarsParquetRead { - path: part_path.clone(), - source, - })?; - - if n_lid != batch - || n_date != batch - || n_close != batch - || n_curr != batch - || batch_listing_ids.len() != batch - || batch_session_dates.len() != batch - || batch_closes.len() != batch - || batch_currencies.len() != batch - { - return Err(RunCurateAdjError::BarsParquetIntegrity { - path: part_path.clone(), - detail: format!( - "column batch length mismatch: expected {batch}, got ({n_lid}, {n_date}, {n_close}, {n_curr})" - ), - }); - } - - for i in 0..batch { - let curr_str = - std::str::from_utf8(batch_currencies[i].data()).map_err(|_| { - RunCurateAdjError::BarsParquetIntegrity { - path: part_path.clone(), - detail: "non-UTF8 currency value in bars_1d Parquet".to_string(), - } - })?; - let currency_id = currencies.intern(curr_str, part_path)?; - by_listing - .entry(batch_listing_ids[i]) - .or_default() - .push(BarCloseEntry { - close: batch_closes[i], - session_date: batch_session_dates[i], - currency_id, - }); - } - - rows_loaded += batch; - remaining -= batch; - } - } - } - - for (&listing_id, entries) in &mut by_listing { - entries.sort_unstable_by_key(|e| e.session_date); - for pair in entries.windows(2) { - if pair[0].session_date == pair[1].session_date { - return Err(RunCurateAdjError::BarsParquetIntegrity { - path: bars_1d_dir.to_path_buf(), - detail: format!( - "duplicate (listing_id={listing_id}, session_date={}) across bars_1d partitions", - pair[0].session_date - ), - }); - } - } - } - - Ok(PrevCloseIndex { - by_listing, - currencies, - files_read: part_files.len(), - rows_loaded, - }) -} - -fn load_provider_mapping_table(path: &Path) -> Result { - let mapping_rows = load_provider_mapping_tsv(path).map_err(|err| match err { - RunCurateBarsError::OpenInput { - label, - path, - source, - } => RunCurateAdjError::OpenInput { - label, - path, - source, - }, - RunCurateBarsError::ReadInput { - label, - path, - source, - } => RunCurateAdjError::ReadInput { - label, - path, - source, - }, - RunCurateBarsError::TsvParse { path, line, detail } => { - RunCurateAdjError::TsvParse { path, line, detail } - } - RunCurateBarsError::ProviderMapping { path, source } => { - RunCurateAdjError::ProviderMapping { path, source } - } - other => RunCurateAdjError::TsvParse { - path: path.to_path_buf(), - line: 0, - detail: other.to_string(), - }, - })?; - - ProviderMappingTable::from_rows(mapping_rows).map_err(|source| { - RunCurateAdjError::ProviderMapping { - path: path.to_path_buf(), - source, - } - }) -} - -struct DecodedAdjInputs { - mapping: ProviderMappingTable, - splits: Vec<(Arc, SplitEvent)>, - dividends: Vec<(Arc, DividendEvent)>, - splits_docs_framed: u64, - splits_bytes_read: u64, - splits_decode: BsonQmActionDecodeStats, - dividends_docs_framed: u64, - dividends_bytes_read: u64, - dividends_decode: BsonQmActionDecodeStats, - dividends_with_prev_close: usize, - dividends_without_prev_close: usize, -} - -#[inline] -fn intern_qm_key(keys: &mut HashSet>, raw: &str) -> Arc { - if let Some(existing) = keys.get(raw) { - return Arc::clone(existing); - } - let arc: Arc = Arc::from(raw); - keys.insert(Arc::clone(&arc)); - arc -} - -fn decode_mapping_and_bson_inputs( - args: &CurateAdjFactorsArgs, - prev_close_index: &PrevCloseIndex, -) -> Result { - decode_mapping_and_bson_from_openers( - &args.provider_mapping, - &args.qm_splits, - || { - File::open(&args.qm_splits).map_err(|source| RunCurateAdjError::OpenInput { - label: "qm-splits", - path: args.qm_splits.clone(), - source, - }) - }, - &args.qm_dividends, - || { - File::open(&args.qm_dividends).map_err(|source| RunCurateAdjError::OpenInput { - label: "qm-dividends", - path: args.qm_dividends.clone(), - source, - }) - }, - prev_close_index, - ) -} - -fn decode_mapping_and_bson_from_openers( - provider_mapping_path: &Path, - qm_splits_path: &Path, - open_splits: FS, - qm_dividends_path: &Path, - open_dividends: FD, - prev_close_index: &PrevCloseIndex, -) -> Result -where - RS: io::Read, - FS: FnOnce() -> Result, - RD: io::Read, - FD: FnOnce() -> Result, -{ - let mapping = load_provider_mapping_table(provider_mapping_path)?; - let mut qm_keys: HashSet> = HashSet::new(); - - // Stream `qmSplits`. - let splits_stream = open_splits()?; - let mut splits_reader = - RawBsonChunkReader::with_options(splits_stream, BsonStreamOptions::default()).map_err( - |source| RunCurateAdjError::BsonStream { - label: "qm-splits", - path: qm_splits_path.to_path_buf(), - source, - }, - )?; - let mut splits: Vec<(Arc, SplitEvent)> = Vec::new(); - let splits_decode = decode_qm_split_chunks( - &mut splits_reader, - |split| { - let key = intern_qm_key(&mut qm_keys, split.qm_search_code); - splits.push((key, split.to_split_event())); - }, - |_offset, _err| {}, - ) - .map_err(|source| RunCurateAdjError::BsonStream { - label: "qm-splits", - path: qm_splits_path.to_path_buf(), - source, - })?; - let splits_docs_framed = splits_reader.docs_framed(); - let splits_bytes_read = splits_reader.bytes_read(); - - // Stream `qmDividends` and attach strict pre-ex-date `prev_close` from `bars_1d`. - let dividends_stream = open_dividends()?; - let mut dividends_reader = - RawBsonChunkReader::with_options(dividends_stream, BsonStreamOptions::default()).map_err( - |source| RunCurateAdjError::BsonStream { - label: "qm-dividends", - path: qm_dividends_path.to_path_buf(), - source, - }, - )?; - let mut dividends: Vec<(Arc, DividendEvent)> = Vec::new(); - let mut dividends_with_prev_close: usize = 0; - let mut dividends_without_prev_close: usize = 0; - let dividends_decode = decode_qm_dividend_chunks( - &mut dividends_reader, - |div| { - let key = intern_qm_key(&mut qm_keys, div.qm_search_code); - let (prev_close, prev_close_currency) = - match mapping.resolve("qm", div.qm_search_code, div.ex_date) { - Some(listing_id) => match prev_close_index.lookup(listing_id, div.ex_date) { - Some((close, curr)) => { - dividends_with_prev_close += 1; - (Some(close), Some(curr.to_owned())) - } - None => { - dividends_without_prev_close += 1; - (None, None) - } - }, - None => (None, None), - }; - dividends.push((key, div.to_dividend_event(prev_close, prev_close_currency))); - }, - |_offset, _err| {}, - ) - .map_err(|source| RunCurateAdjError::BsonStream { - label: "qm-dividends", - path: qm_dividends_path.to_path_buf(), - source, - })?; - let dividends_docs_framed = dividends_reader.docs_framed(); - let dividends_bytes_read = dividends_reader.bytes_read(); - - Ok(DecodedAdjInputs { - mapping, - splits, - dividends, - splits_docs_framed, - splits_bytes_read, - splits_decode, - dividends_docs_framed, - dividends_bytes_read, - dividends_decode, - dividends_with_prev_close, - dividends_without_prev_close, - }) -} - -fn map_curate_write_error_paths( - out_dir: &Path, - qm_splits_path: &Path, - qm_dividends_path: &Path, - source: CurateAdjWriteError, -) -> RunCurateAdjError { - let input_path = match &source { - CurateAdjWriteError::Curate(CurateAdjError::ConflictingCrossKeySplit { .. }) => { - Some(qm_splits_path.to_path_buf()) - } - CurateAdjWriteError::Curate(CurateAdjError::ConflictingCrossKeyDividend { .. }) => { - Some(qm_dividends_path.to_path_buf()) - } - _ => None, - }; - RunCurateAdjError::CurateWrite { - out_dir: out_dir.to_path_buf(), - input_path, - source, - } -} - -/// Runs the end-to-end `curate-adj-factors` file-to-Parquet pipeline via -/// [`curate_and_write_adj_factors`]. -/// -/// Any input, schema, mapping, or curation error returns before touching `args.out_dir`, -/// leaving any pre-existing `/adj_factors/part.parquet` byte-identical. -pub fn run_curate_adj_factors( - args: &CurateAdjFactorsArgs, -) -> Result { - run_curate_adj_factors_fenced(args, None) -} - -/// Runs the end-to-end `curate-adj-factors` file-to-Parquet pipeline with an optional -/// [`AdjPointInTimeFence`] (publishing a verified `point_in_time_fenced` snapshot when `Some`). -pub fn run_curate_adj_factors_fenced( - args: &CurateAdjFactorsArgs, - fence: Option, -) -> Result { - let start = Instant::now(); - validate_out_dir(&args.out_dir)?; - - let prev_close_index = load_prev_close_index(&args.bars_1d_dir)?; - let bars_files_read = prev_close_index.files_read; - let bars_rows_loaded = prev_close_index.rows_loaded; - let bars_listings_indexed = prev_close_index.by_listing.len(); - - let decoded = decode_mapping_and_bson_inputs(args, &prev_close_index)?; - drop(prev_close_index); - - finish_curate_adj_factors( - decoded, - &args.out_dir, - &args.qm_splits, - &args.qm_dividends, - fence, - bars_files_read, - bars_rows_loaded, - bars_listings_indexed, - start, - ) -} - -/// Runs `curate-adj-factors` from arbitrary raw-BSON [`io::Read`] streams. -#[allow(clippy::too_many_arguments)] -pub fn run_curate_adj_factors_with_readers( - provider_mapping_path: &Path, - bars_1d_dir: &Path, - qm_splits_input: (&Path, RS), - qm_dividends_input: (&Path, RD), - out_dir: &Path, - fence: Option, -) -> Result { - let start = Instant::now(); - validate_out_dir(out_dir)?; - - let prev_close_index = load_prev_close_index(bars_1d_dir)?; - let bars_files_read = prev_close_index.files_read; - let bars_rows_loaded = prev_close_index.rows_loaded; - let bars_listings_indexed = prev_close_index.by_listing.len(); - - let (qm_splits_path, splits_stream) = qm_splits_input; - let (qm_dividends_path, dividends_stream) = qm_dividends_input; - let decoded = decode_mapping_and_bson_from_openers( - provider_mapping_path, - qm_splits_path, - || Ok(splits_stream), - qm_dividends_path, - || Ok(dividends_stream), - &prev_close_index, - )?; - drop(prev_close_index); - - finish_curate_adj_factors( - decoded, - out_dir, - qm_splits_path, - qm_dividends_path, - fence, - bars_files_read, - bars_rows_loaded, - bars_listings_indexed, - start, - ) -} - -#[allow(clippy::too_many_arguments)] -fn finish_curate_adj_factors( - decoded: DecodedAdjInputs, - out_dir: &Path, - qm_splits_path: &Path, - qm_dividends_path: &Path, - fence: Option, - bars_files_read: usize, - bars_rows_loaded: usize, - bars_listings_indexed: usize, - start: Instant, -) -> Result { - let write_report = match fence { - Some(f) => curate_and_write_adj_factors_as_of( - out_dir, - &decoded.mapping, - "qm", - decoded.splits, - decoded.dividends, - f, - AdjFactorsWriteOptions::default(), - ), - None => curate_and_write_adj_factors( - out_dir, - &decoded.mapping, - "qm", - decoded.splits, - decoded.dividends, - AdjFactorsWriteOptions::default(), - ), - } - .map_err(|source| map_curate_write_error_paths(out_dir, qm_splits_path, qm_dividends_path, source))?; - - Ok(CurateAdjFactorsRunReport { - bars_files_read, - bars_rows_loaded, - bars_listings_indexed, - splits_docs_framed: decoded.splits_docs_framed, - splits_bytes_read: decoded.splits_bytes_read, - splits_decode: decoded.splits_decode, - dividends_docs_framed: decoded.dividends_docs_framed, - dividends_bytes_read: decoded.dividends_bytes_read, - dividends_decode: decoded.dividends_decode, - dividends_with_prev_close: decoded.dividends_with_prev_close, - dividends_without_prev_close: decoded.dividends_without_prev_close, - curate_stats: write_report.curate_stats, - write_stats: write_report.write_stats, - elapsed_secs: start.elapsed().as_secs_f64(), - }) -} - -fn compute_rows_checksum(rows: &[AdjFactorsParquetRow]) -> u64 { - let mut hash = 0xcbf2_9ce4_8422_2325_u64; - let mix = |mut h: u64, v: u64| -> u64 { - h ^= v; - h = h.wrapping_mul(0x0000_0100_0000_01b3); - h - }; - for row in rows { - hash = mix(hash, row.listing_id as u64); - hash = mix(hash, row.ex_date as u64); - hash = mix(hash, row.split_factor.to_bits()); - hash = mix(hash, row.div_cash.to_bits()); - match row.div_currency.as_deref() { - Some(c) => { - hash = mix(hash, 1); - for &b in c.as_bytes() { - hash = mix(hash, u64::from(b)); - } - } - None => { - hash = mix(hash, 0); - } - } - hash = mix(hash, row.cum_split_factor.to_bits()); - hash = mix(hash, row.cum_total_factor.to_bits()); - hash = mix(hash, row.known_at_micros as u64); - } - hash -} - -/// Stage-timed variant of [`run_curate_adj_factors`] used internally by `bench-curate-adj-cmd`. -/// -/// Times `bars_load`, `decode` (mapping + BSON streams + `prev_close` attach), `curate`, and -/// `write` (`write_adj_factors_snapshot_parquet`, identical footer-verified snapshot as -/// [`curate_and_write_adj_factors`]) separately. -pub(crate) fn run_curate_adj_factors_timed( - args: &CurateAdjFactorsArgs, -) -> Result { - let total_start = Instant::now(); - validate_out_dir(&args.out_dir)?; - - let bars_start = Instant::now(); - let prev_close_index = load_prev_close_index(&args.bars_1d_dir)?; - let bars_load_elapsed_secs = bars_start.elapsed().as_secs_f64(); - let bars_files_read = prev_close_index.files_read; - let bars_rows_loaded = prev_close_index.rows_loaded; - let bars_listings_indexed = prev_close_index.by_listing.len(); - - let decode_start = Instant::now(); - let decoded = decode_mapping_and_bson_inputs(args, &prev_close_index)?; - let decode_elapsed_secs = decode_start.elapsed().as_secs_f64(); - drop(prev_close_index); - - let curate_start = Instant::now(); - let curated = curate_adj_factors( - &decoded.mapping, - "qm", - decoded.splits, - decoded.dividends, - ) - .map_err(|source| { - map_curate_write_error_paths( - &args.out_dir, - &args.qm_splits, - &args.qm_dividends, - CurateAdjWriteError::Curate(source), - ) - })?; - let curate_elapsed_secs = curate_start.elapsed().as_secs_f64(); - - let checksum = compute_rows_checksum(&curated.rows); - - let write_start = Instant::now(); - let write_stats = write_adj_factors_snapshot_parquet( - &args.out_dir, - &curated.rows, - curated.snapshot_kind, - AdjFactorsWriteOptions::default(), - ) - .map_err(|source| { - map_curate_write_error_paths( - &args.out_dir, - &args.qm_splits, - &args.qm_dividends, - CurateAdjWriteError::Parquet(source), - ) - })?; - let write_elapsed_secs = write_start.elapsed().as_secs_f64(); - - let report = CurateAdjFactorsRunReport { - bars_files_read, - bars_rows_loaded, - bars_listings_indexed, - splits_docs_framed: decoded.splits_docs_framed, - splits_bytes_read: decoded.splits_bytes_read, - splits_decode: decoded.splits_decode, - dividends_docs_framed: decoded.dividends_docs_framed, - dividends_bytes_read: decoded.dividends_bytes_read, - dividends_decode: decoded.dividends_decode, - dividends_with_prev_close: decoded.dividends_with_prev_close, - dividends_without_prev_close: decoded.dividends_without_prev_close, - curate_stats: curated.stats, - write_stats, - elapsed_secs: total_start.elapsed().as_secs_f64(), - }; - - Ok(CurateAdjFactorsTimedRun { - report, - bars_load_elapsed_secs, - decode_elapsed_secs, - curate_elapsed_secs, - write_elapsed_secs, - checksum, - }) -} - -/// Formats [`CurateAdjFactorsRunReport`] into a deterministic machine-readable `key=value` summary. -/// -/// Only the final `timing:` line contains wall-clock time (`elapsed_secs`). -pub fn format_curate_adj_report(report: &CurateAdjFactorsRunReport) -> String { - format!( - "curate-etl curate-adj-factors\n\ - \x20 bars_1d: files_read={} rows_loaded={} listings_indexed={}\n\ - \x20 splits_bson: docs_framed={} bytes_read={} docs_in={} decoded={} noop_ratio_one={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={})\n\ - \x20 dividends_bson: docs_framed={} bytes_read={} docs_in={} decoded={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={})\n\ - \x20 prev_close: with_prev_close={} without_prev_close={} unmapped={}\n\ - \x20 builder: splits_in={} dividends_in={} rows_out={} keys_out={} split_noops={} zero_div={} missing_prev_close={} currency_mismatch={} not_below_prev_close={}\n\ - \x20 curate: splits_in={} dividends_in={} rows_out={} listings_out={} splits_unmapped={} divs_unmapped={} splits_fenced={} divs_fenced={} splits_coll_collapsed={} divs_coll_collapsed={} coll_collapsed={}\n\ - \x20 write: rows_written={} files_written={} row_groups_written={} bytes_written={}\n\ - \x20 timing: elapsed_secs={:.6}", - report.bars_files_read, - report.bars_rows_loaded, - report.bars_listings_indexed, - report.splits_docs_framed, - report.splits_bytes_read, - report.splits_decode.docs_in, - report.splits_decode.decoded, - report.splits_decode.split_noop_ratio_one, - report.splits_decode.rejected_total(), - report.splits_decode.rejected_missing_field, - report.splits_decode.rejected_empty_field, - report.splits_decode.rejected_wrong_type, - report.splits_decode.rejected_malformed_date, - report.splits_decode.rejected_invalid_number, - report.splits_decode.rejected_corrupt_document, - report.dividends_docs_framed, - report.dividends_bytes_read, - report.dividends_decode.docs_in, - report.dividends_decode.decoded, - report.dividends_decode.rejected_total(), - report.dividends_decode.rejected_missing_field, - report.dividends_decode.rejected_empty_field, - report.dividends_decode.rejected_wrong_type, - report.dividends_decode.rejected_malformed_date, - report.dividends_decode.rejected_invalid_number, - report.dividends_decode.rejected_corrupt_document, - report.dividends_with_prev_close, - report.dividends_without_prev_close, - report.curate_stats.dividends_dropped_unmapped, - report.curate_stats.builder.split_events_in, - report.curate_stats.builder.dividend_events_in, - report.curate_stats.builder.rows_out, - report.curate_stats.builder.keys_out, - report.curate_stats.builder.split_noops_dropped, - report.curate_stats.builder.dividend_zero_cash_dropped, - report.curate_stats.builder.dividends_missing_prev_close, - report.curate_stats.builder.dividends_currency_mismatch, - report.curate_stats.builder.dividends_not_below_prev_close, - report.curate_stats.splits_in, - report.curate_stats.dividends_in, - report.curate_stats.rows_out, - report.curate_stats.listings_out, - report.curate_stats.splits_dropped_unmapped, - report.curate_stats.dividends_dropped_unmapped, - report.curate_stats.splits_dropped_fenced, - report.curate_stats.dividends_dropped_fenced, - report.curate_stats.splits_collision_collapsed, - report.curate_stats.dividends_collision_collapsed, - report.curate_stats.listing_collision_collapsed, - report.write_stats.rows_written, - report.write_stats.files_written, - report.write_stats.row_groups_written, - report.write_stats.bytes_written, - report.elapsed_secs, - ) -} - -#[cfg(test)] -#[path = "run_curate_adj_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/run_curate_adj_tests.rs b/tools/curate-etl/src/run_curate_adj_tests.rs deleted file mode 100644 index a448a673..00000000 --- a/tools/curate-etl/src/run_curate_adj_tests.rs +++ /dev/null @@ -1,1044 +0,0 @@ -use std::borrow::Cow; -use std::fs::{self, File}; -use std::io::Write; -use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering}; - -use bson::raw::{cstr, RawDocumentBuf}; - -use super::*; -use crate::bson_stream::DEFAULT_MAX_DOC_BYTES; -use crate::curate_adj::{ - adj_factors_for_bar, read_adj_factors_dataset, read_adj_factors_dataset_as_of, - AdjPointInTimeFence, AdjSnapshotKind, CurateAdjReadError, -}; -use crate::curate_bars::BARS_1D_SOURCE_EOD; -use crate::parquet_bars::{write_bars_1d_dataset, Bars1dParquetRow, Bars1dWriteOptions}; -use crate::session_close::et_session_close_utc_micros; -use crate::split::ymd_to_epoch_days; - -static TEST_DIR_SEQ: AtomicU64 = AtomicU64::new(0); - -struct TestTempDir { - path: PathBuf, -} - -impl TestTempDir { - fn new(tag: &str) -> Self { - let pid = std::process::id(); - let seq = TEST_DIR_SEQ.fetch_add(1, Ordering::Relaxed); - let path = std::env::temp_dir().join(format!("curate-etl-run-adj-{tag}-{pid}-{seq}")); - fs::create_dir_all(&path).expect("create test temp dir"); - Self { path } - } - - fn path(&self) -> &Path { - &self.path - } -} - -impl Drop for TestTempDir { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.path); - } -} - -fn write_bytes(path: &Path, bytes: &[u8]) { - if let Some(parent) = path.parent() { - fs::create_dir_all(parent).expect("create parent dirs"); - } - let mut f = File::create(path).expect("create fixture file"); - f.write_all(bytes).expect("write fixture bytes"); -} - -fn split_doc(code: &str, date: &str, ratio: f64) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), code); - doc.append(cstr!("date"), date); - if ratio.is_finite() && ratio > 0.0 { - doc.append(cstr!("splitratio"), 1.0 / ratio); - doc.append(cstr!("forfactor"), 1.0_f64); - doc.append(cstr!("tofactor"), ratio); - } else { - doc.append(cstr!("splitratio"), ratio); - } - doc.into_bytes() -} - -fn div_doc(code: &str, date: &str, cash: f64, currency: &str, usd_fx_rate: Option) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), code); - doc.append(cstr!("date"), date); - doc.append(cstr!("amount"), cash); - doc.append(cstr!("currency"), currency); - if let Some(fx) = usd_fx_rate { - doc.append(cstr!("usdFxRate"), fx); - } - doc.into_bytes() -} - -fn bar_row(listing_id: i32, y: i32, m: u32, d: u32, close: f64, currency: &'static str) -> Bars1dParquetRow { - let session_date = ymd_to_epoch_days(y, m, d).expect("valid bar date"); - let ts_micros = et_session_close_utc_micros(session_date).expect("valid ts"); - Bars1dParquetRow { - listing_id, - ts_micros, - session_date, - open: close - 0.5, - high: close + 1.0, - low: close - 1.0, - close, - volume: 100_000.0, - vwap: None, - currency: Cow::Borrowed(currency), - source: Cow::Borrowed(BARS_1D_SOURCE_EOD), - known_at_micros: ts_micros, - } -} - -fn assert_row_bit_eq(a: &AdjFactorsParquetRow, b: &AdjFactorsParquetRow) { - assert_eq!(a.listing_id, b.listing_id); - assert_eq!(a.ex_date, b.ex_date); - assert_eq!(a.split_factor.to_bits(), b.split_factor.to_bits()); - assert_eq!(a.div_cash.to_bits(), b.div_cash.to_bits()); - assert_eq!(a.div_currency, b.div_currency); - assert_eq!(a.cum_split_factor.to_bits(), b.cum_split_factor.to_bits()); - assert_eq!(a.cum_total_factor.to_bits(), b.cum_total_factor.to_bits()); - assert_eq!(a.known_at_micros, b.known_at_micros); -} - -fn assert_conservation(report: &CurateAdjFactorsRunReport) { - assert_eq!( - report.splits_docs_framed as usize, report.splits_decode.docs_in, - "splits_docs_framed must equal splits_decode.docs_in" - ); - assert_eq!( - report.splits_decode.docs_in, - report.splits_decode.rejected_total() - + report.curate_stats.splits_dropped_unmapped - + report.curate_stats.splits_dropped_fenced - + report.curate_stats.splits_collision_collapsed - + report.curate_stats.builder.split_events_in, - "split conservation invariant failed: {report:?}" - ); - assert_eq!( - report.dividends_docs_framed as usize, report.dividends_decode.docs_in, - "dividends_docs_framed must equal dividends_decode.docs_in" - ); - assert_eq!( - report.dividends_decode.docs_in, - report.dividends_decode.rejected_total() - + report.curate_stats.dividends_dropped_unmapped - + report.curate_stats.dividends_dropped_fenced - + report.curate_stats.dividends_collision_collapsed - + report.curate_stats.builder.dividend_events_in, - "dividend conservation invariant failed: {report:?}" - ); - assert_eq!( - report.dividends_decode.decoded, - report.dividends_with_prev_close - + report.dividends_without_prev_close - + report.curate_stats.dividends_dropped_unmapped, - "dividend prev_close conservation invariant failed: {report:?}" - ); -} - -fn strip_timing_line(report: &str) -> String { - report - .lines() - .filter(|line| !line.trim_start().starts_with("timing:")) - .collect::>() - .join("\n") -} - -#[test] -fn end_to_end_round_trip_matches_direct_curate_adj_factors_bitwise_and_is_deterministic() { - let dir = TestTempDir::new("e2e-roundtrip"); - let splits_a = dir.path().join("splits_a.bson"); - let splits_b = dir.path().join("splits_b.bson"); - let divs_a = dir.path().join("divs_a.bson"); - let divs_b = dir.path().join("divs_b.bson"); - let map_path = dir.path().join("provider_mapping.tsv"); - let bars_root = dir.path().join("bars_root"); - let out_a = dir.path().join("out_a"); - let out_b = dir.path().join("out_b"); - let out_timed = dir.path().join("out_timed"); - - write_bytes( - &map_path, - b"qm\tNVDA:US\t2010-01-01\t\t100\n\ - qm\tRY:CA\t2010-01-01\t\t200\n\ - qm\tRY_ALT:CA\t2010-01-01\t\t200\n", - ); - - // Write multi-year bars_1d dataset via write_bars_1d_dataset. - let bar_rows = vec![ - bar_row(100, 2021, 7, 19, 751.19, "USD"), - bar_row(100, 2021, 7, 20, 186.12, "USD"), - bar_row(100, 2024, 6, 7, 1208.88, "USD"), - bar_row(100, 2024, 6, 10, 121.79, "USD"), - bar_row(100, 2024, 6, 11, 120.91, "USD"), - bar_row(200, 2024, 4, 24, 136.50, "CAD"), - bar_row(200, 2024, 4, 25, 135.00, "CAD"), - ]; - write_bars_1d_dataset(&bars_root, &bar_rows, Bars1dWriteOptions::default()).unwrap(); - - // Splits: NVDA 4:1 (2021-07-20) + 10:1 (2024-06-10) + 1:1 no-op + unmapped. - let s1 = split_doc("NVDA:US", "2021-07-20", 4.0); - let s2 = split_doc("NVDA:US", "2024-06-10", 10.0); - let s3 = split_doc("NVDA:US", "2022-03-01", 1.0); - let s4 = split_doc("UNKNOWN:US", "2023-01-05", 2.0); - write_bytes(&splits_a, &[&s1[..], &s2[..], &s3[..], &s4[..]].concat()); - write_bytes(&splits_b, &[&s4[..], &s2[..], &s3[..], &s1[..]].concat()); - - // Dividends: NVDA USD div on 2024-06-11 (prev_close = 121.79 on 2024-06-10), - // RY:CA + RY_ALT:CA identical CAD div on 2024-04-25 with bogus usdFxRate: 1 (prev_close = 136.50 on 2024-04-24). - let d1 = div_doc("NVDA:US", "2024-06-11", 0.01, "USD", Some(1.0)); - let d2 = div_doc("RY:CA", "2024-04-25", 1.38, "CAD", Some(1.0)); - let d3 = div_doc("RY_ALT:CA", "2024-04-25", 1.38, "CAD", Some(1.0)); - write_bytes(&divs_a, &[&d1[..], &d2[..], &d3[..]].concat()); - write_bytes(&divs_b, &[&d3[..], &d1[..], &d2[..]].concat()); - - let args_a = CurateAdjFactorsArgs { - qm_splits: splits_a, - qm_dividends: divs_a, - provider_mapping: map_path.clone(), - bars_1d_dir: bars_root.join("bars_1d"), - out_dir: out_a.clone(), - }; - let report_a = run_curate_adj_factors(&args_a).expect("run_curate_adj_factors A"); - assert_conservation(&report_a); - - // Compare against calling curate_adj_factors directly on the same in-memory events. - let mapping = load_provider_mapping_table(&map_path).unwrap(); - let direct = curate_adj_factors( - &mapping, - "qm", - vec![ - ( - "NVDA:US", - SplitEvent { - ex_date: ymd_to_epoch_days(2021, 7, 20).unwrap(), - ratio: 4.0, - }, - ), - ( - "NVDA:US", - SplitEvent { - ex_date: ymd_to_epoch_days(2024, 6, 10).unwrap(), - ratio: 10.0, - }, - ), - ( - "NVDA:US", - SplitEvent { - ex_date: ymd_to_epoch_days(2022, 3, 1).unwrap(), - ratio: 1.0, - }, - ), - ( - "UNKNOWN:US", - SplitEvent { - ex_date: ymd_to_epoch_days(2023, 1, 5).unwrap(), - ratio: 2.0, - }, - ), - ], - vec![ - ( - "NVDA:US", - DividendEvent { - ex_date: ymd_to_epoch_days(2024, 6, 11).unwrap(), - cash: 0.01, - currency: "USD".to_string(), - prev_close: Some(121.79), - prev_close_currency: Some("USD".to_string()), - }, - ), - ( - "RY:CA", - DividendEvent { - ex_date: ymd_to_epoch_days(2024, 4, 25).unwrap(), - cash: 1.38, - currency: "CAD".to_string(), - prev_close: Some(136.50), - prev_close_currency: Some("CAD".to_string()), - }, - ), - ( - "RY_ALT:CA", - DividendEvent { - ex_date: ymd_to_epoch_days(2024, 4, 25).unwrap(), - cash: 1.38, - currency: "CAD".to_string(), - prev_close: Some(136.50), - prev_close_currency: Some("CAD".to_string()), - }, - ), - ], - ) - .expect("direct curate_adj_factors"); - - let snap_a = read_adj_factors_dataset(&out_a).expect("read_adj_factors_dataset"); - assert_eq!(snap_a.snapshot_kind, AdjSnapshotKind::RetrospectiveSnapshot); - assert_eq!(snap_a.rows.len(), direct.rows.len()); - for (got, expected) in snap_a.rows.iter().zip(direct.rows.iter()) { - assert_row_bit_eq(got, expected); - } - - // Point-in-time reader must reject the retrospective snapshot automatically. - let pit_err = read_adj_factors_dataset_as_of( - &out_a, - AdjPointInTimeFence::as_of(et_session_close_utc_micros(ymd_to_epoch_days(2024, 6, 11).unwrap()).unwrap()), - ) - .unwrap_err(); - assert!(matches!( - pit_err, - CurateAdjReadError::RetrospectiveSnapshotRejected { .. } - )); - - // Shuffled BSON + root bars_1d dir layout produces byte-identical Parquet and identical non-timing report. - let args_b = CurateAdjFactorsArgs { - qm_splits: splits_b, - qm_dividends: divs_b, - provider_mapping: map_path, - bars_1d_dir: bars_root, // parent root containing `bars_1d/` - out_dir: out_b.clone(), - }; - let report_b = run_curate_adj_factors(&args_b).expect("run_curate_adj_factors B"); - assert_conservation(&report_b); - assert_eq!( - strip_timing_line(&format_curate_adj_report(&report_a)), - strip_timing_line(&format_curate_adj_report(&report_b)) - ); - assert_eq!( - fs::read(out_a.join("adj_factors/part.parquet")).unwrap(), - fs::read(out_b.join("adj_factors/part.parquet")).unwrap() - ); - - // Stage-timed helper produces byte-identical Parquet as well. - let args_timed = CurateAdjFactorsArgs { - out_dir: out_timed.clone(), - ..args_a - }; - let timed = run_curate_adj_factors_timed(&args_timed).expect("run_curate_adj_factors_timed"); - assert_conservation(&timed.report); - assert_eq!( - fs::read(out_a.join("adj_factors/part.parquet")).unwrap(), - fs::read(out_timed.join("adj_factors/part.parquet")).unwrap() - ); -} - -#[test] -fn prev_close_strictly_before_ex_date_and_none_when_missing_or_unmapped() { - let dir = TestTempDir::new("prev-close-boundary"); - let splits_path = dir.path().join("splits.bson"); - let divs_path = dir.path().join("divs.bson"); - let map_path = dir.path().join("map.tsv"); - let bars_root = dir.path().join("bars_root"); - let out_dir = dir.path().join("out"); - - write_bytes( - &map_path, - b"qm\tAAA:US\t2020-01-01\t\t1\n\ - qm\tNOBAR:US\t2020-01-01\t\t2\n", - ); - - // Listing 1 has bars on Friday 2024-05-03 (close=100.0) and Monday 2024-05-06 (close=50.0). - // Listing 2 has no bars at all. - let bar_rows = vec![ - bar_row(1, 2024, 5, 3, 100.0, "USD"), - bar_row(1, 2024, 5, 6, 50.0, "USD"), - ]; - write_bars_1d_dataset(&bars_root, &bar_rows, Bars1dWriteOptions::default()).unwrap(); - - write_bytes(&splits_path, b""); - let mut divs = Vec::new(); - // 1. Ex-date 2024-05-06 (Monday): bar on 2024-05-06 (close=50.0) MUST NOT be used; - // must use Friday 2024-05-03 (close=100.0) -> div_factor = 1 - 2.0 / 100.0 = 0.98. - divs.extend_from_slice(&div_doc("AAA:US", "2024-05-06", 2.0, "USD", None)); - // 2. Ex-date 2024-05-03 (same day as earliest bar): no bar strictly before -> prev_close = None -> factor 1.0. - divs.extend_from_slice(&div_doc("AAA:US", "2024-05-03", 1.0, "USD", None)); - // 3. Listing 2 has no bars -> prev_close = None -> factor 1.0. - divs.extend_from_slice(&div_doc("NOBAR:US", "2024-05-10", 1.0, "USD", None)); - // 4. Unmapped dividend -> dropped as unmapped, not counted in with/without prev_close. - divs.extend_from_slice(&div_doc("UNMAPPED:US", "2024-05-10", 1.0, "USD", None)); - write_bytes(&divs_path, &divs); - - let report = run_curate_adj_factors(&CurateAdjFactorsArgs { - qm_splits: splits_path, - qm_dividends: divs_path, - provider_mapping: map_path, - bars_1d_dir: bars_root.join("bars_1d"), - out_dir: out_dir.clone(), - }) - .expect("run_curate_adj_factors"); - assert_conservation(&report); - - assert_eq!(report.dividends_with_prev_close, 1); - assert_eq!(report.dividends_without_prev_close, 2); - assert_eq!(report.curate_stats.dividends_dropped_unmapped, 1); - assert_eq!(report.curate_stats.builder.dividends_missing_prev_close, 2); - - let snap = read_adj_factors_dataset(&out_dir).unwrap(); - assert_eq!(snap.rows.len(), 3); - - let d_may03 = ymd_to_epoch_days(2024, 5, 3).unwrap(); - let d_may06 = ymd_to_epoch_days(2024, 5, 6).unwrap(); - let row_may03 = snap - .rows - .iter() - .find(|r| r.listing_id == 1 && r.ex_date == d_may03) - .unwrap(); - let row_may06 = snap - .rows - .iter() - .find(|r| r.listing_id == 1 && r.ex_date == d_may06) - .unwrap(); - - // If 2024-05-06 had wrongly used its own close (50.0), factor would be 50 / (50 - 2) = 50 / 48. - // Using strictly prior close (100.0) gives 100 / (100 - 2) = 100 / 98. - let expected_factor = 100.0 / 98.0; - assert!((row_may06.cum_total_factor - expected_factor).abs() < 1e-12); - // 2024-05-03 had no earlier bar (div factor = 1.0), compounded with 2024-05-06 -> 100 / 98. - assert!((row_may03.cum_total_factor - expected_factor).abs() < 1e-12); - - let row_nobar = snap.rows.iter().find(|r| r.listing_id == 2).unwrap(); - assert_eq!(row_nobar.cum_total_factor, 1.0); -} - -#[test] -fn financial_invariants_nvda_chain_noop_cad_fx_ignore_mismatch_and_malformed_bson_rejects() { - let dir = TestTempDir::new("financial-invariants"); - let splits_path = dir.path().join("splits.bson"); - let divs_path = dir.path().join("divs.bson"); - let map_path = dir.path().join("map.tsv"); - let bars_root = dir.path().join("bars_root"); - let out_dir = dir.path().join("out"); - - write_bytes( - &map_path, - b"qm\tNVDA:US\t2015-01-01\t\t10\n\ - qm\tSHOP:CA\t2015-01-01\t\t20\n\ - qm\tMISMATCH:CA\t2015-01-01\t\t30\n", - ); - - let bar_rows = vec![ - bar_row(20, 2024, 5, 1, 100.0, "CAD"), - bar_row(30, 2024, 5, 1, 100.0, "CAD"), - ]; - write_bars_1d_dataset(&bars_root, &bar_rows, Bars1dWriteOptions::default()).unwrap(); - - // Splits: NVDA 4:1 (2021-07-20), NVDA 10:1 (2024-06-10), 1:1 no-op, plus 2 malformed BSON docs - // (one invalid date, one internally-corrupt length-framed doc). - let mut splits = Vec::new(); - splits.extend_from_slice(&split_doc("NVDA:US", "2021-07-20", 4.0)); - splits.extend_from_slice(&split_doc("NVDA:US", "2024-06-10", 10.0)); - splits.extend_from_slice(&split_doc("NVDA:US", "2023-01-10", 1.0)); - splits.extend_from_slice(&split_doc("NVDA:US", "2023-02-29", 2.0)); // malformed date reject - // Valid outer 4-byte length prefix (12 bytes), invalid interior BSON bytes -> CorruptBson reject. - let mut corrupt_doc = Vec::from(12_i32.to_le_bytes()); - corrupt_doc.extend_from_slice(&[0x7f, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x01]); - splits.extend_from_slice(&corrupt_doc); - write_bytes(&splits_path, &splits); - - // Dividends: - // - CAD dividend with bogus usdFxRate: 1 -> curated in CAD using CAD prev_close=100.0 -> factor = 0.95. - // - USD dividend on CAD bar -> currency mismatch -> factor = 1.0. - // - Malformed dividend (negative cash) -> decode reject without aborting. - let mut divs = Vec::new(); - divs.extend_from_slice(&div_doc("SHOP:CA", "2024-05-02", 5.0, "CAD", Some(1.0))); - divs.extend_from_slice(&div_doc("MISMATCH:CA", "2024-05-02", 5.0, "USD", Some(1.0))); - divs.extend_from_slice(&div_doc("SHOP:CA", "2024-05-03", -1.0, "CAD", Some(1.0))); - write_bytes(&divs_path, &divs); - - let report = run_curate_adj_factors(&CurateAdjFactorsArgs { - qm_splits: splits_path, - qm_dividends: divs_path, - provider_mapping: map_path, - bars_1d_dir: bars_root.join("bars_1d"), - out_dir: out_dir.clone(), - }) - .expect("run_curate_adj_factors"); - assert_conservation(&report); - - assert_eq!(report.splits_docs_framed, 5); - assert_eq!(report.splits_decode.rejected_total(), 2); - assert_eq!(report.splits_decode.split_noop_ratio_one, 1); - assert_eq!(report.curate_stats.builder.split_noops_dropped, 1); - assert_eq!(report.dividends_docs_framed, 3); - assert_eq!(report.dividends_decode.rejected_total(), 1); - assert_eq!(report.curate_stats.builder.dividends_currency_mismatch, 1); - - let snap = read_adj_factors_dataset(&out_dir).unwrap(); - - // NVDA 4:1 then 10:1 chain: cum_split_factor 40 -> 10 on rows, and 40 -> 10 -> 1 across dates. - let d_2021 = ymd_to_epoch_days(2021, 7, 20).unwrap(); - let d_2024 = ymd_to_epoch_days(2024, 6, 10).unwrap(); - let nvda_rows: Vec<&AdjFactorsParquetRow> = - snap.rows.iter().filter(|r| r.listing_id == 10).collect(); - assert_eq!(nvda_rows.len(), 2, "1:1 no-op must not emit a row"); - assert_eq!(nvda_rows[0].ex_date, d_2021); - assert_eq!(nvda_rows[0].cum_split_factor, 40.0); - assert_eq!(nvda_rows[1].ex_date, d_2024); - assert_eq!(nvda_rows[1].cum_split_factor, 10.0); - - assert_eq!(adj_factors_for_bar(&snap.rows, 10, d_2021 - 1), (40.0, 40.0)); - assert_eq!(adj_factors_for_bar(&snap.rows, 10, d_2021), (10.0, 10.0)); - assert_eq!(adj_factors_for_bar(&snap.rows, 10, d_2024 - 1), (10.0, 10.0)); - assert_eq!(adj_factors_for_bar(&snap.rows, 10, d_2024), (1.0, 1.0)); - - // CAD dividend ignores bogus usdFxRate: 1 and uses CAD prev_close = 100.0 -> 100 / 95. - let shop_row = snap.rows.iter().find(|r| r.listing_id == 20).unwrap(); - assert_eq!(shop_row.div_currency.as_deref(), Some("CAD")); - assert!((shop_row.cum_total_factor - (100.0 / 95.0)).abs() < 1e-12); - - // Currency-mismatched dividend falls back to factor 1.0. - let mismatch_row = snap.rows.iter().find(|r| r.listing_id == 30).unwrap(); - assert_eq!(mismatch_row.div_currency.as_deref(), Some("USD")); - assert_eq!(mismatch_row.cum_total_factor, 1.0); -} - -#[test] -fn failure_modes_preserve_preexisting_adj_factors_snapshot_byte_for_byte() { - let dir = TestTempDir::new("atomicity-failures"); - let splits_ok = dir.path().join("splits_ok.bson"); - let divs_ok = dir.path().join("divs_ok.bson"); - let map_ok = dir.path().join("map_ok.tsv"); - let bars_ok = dir.path().join("bars_ok"); - let out_dir = dir.path().join("out"); - - write_bytes(&map_ok, b"qm\tNVDA:US\t2015-01-01\t\t10\n"); - write_bars_1d_dataset( - &bars_ok, - &[bar_row(10, 2024, 6, 7, 1200.0, "USD")], - Bars1dWriteOptions::default(), - ) - .unwrap(); - write_bytes(&splits_ok, &split_doc("NVDA:US", "2024-06-10", 10.0)); - write_bytes(&divs_ok, b""); - - // Seed a valid pre-existing snapshot at `/adj_factors/part.parquet`. - run_curate_adj_factors(&CurateAdjFactorsArgs { - qm_splits: splits_ok.clone(), - qm_dividends: divs_ok.clone(), - provider_mapping: map_ok.clone(), - bars_1d_dir: bars_ok.join("bars_1d"), - out_dir: out_dir.clone(), - }) - .expect("seed baseline snapshot"); - let live_part = out_dir.join("adj_factors/part.parquet"); - let baseline_bytes = fs::read(&live_part).expect("read baseline snapshot"); - assert!(!baseline_bytes.is_empty()); - - let assert_failed_atomically_all = |args: CurateAdjFactorsArgs, expected_substrs: &[&str]| { - let err = run_curate_adj_factors(&args).expect_err("expected failure"); - let msg = err.to_string(); - assert_eq!(msg.lines().count(), 1, "error must be single-line: {msg}"); - for expected_substr in expected_substrs { - assert!( - msg.contains(expected_substr), - "expected error containing '{expected_substr}', got: {msg}" - ); - } - assert_eq!( - fs::read(&live_part).expect("live snapshot still exists"), - baseline_bytes, - "pre-existing adj_factors/part.parquet must remain byte-identical after failure ({msg})" - ); - }; - let assert_failed_atomically = |args: CurateAdjFactorsArgs, expected_substr: &str| { - assert_failed_atomically_all(args, &[expected_substr]); - }; - - // 1. Missing qmSplits file. - assert_failed_atomically( - CurateAdjFactorsArgs { - qm_splits: dir.path().join("missing_splits.bson"), - qm_dividends: divs_ok.clone(), - provider_mapping: map_ok.clone(), - bars_1d_dir: bars_ok.join("bars_1d"), - out_dir: out_dir.clone(), - }, - "missing_splits.bson", - ); - - // 2. Missing qmDividends file. - assert_failed_atomically( - CurateAdjFactorsArgs { - qm_splits: splits_ok.clone(), - qm_dividends: dir.path().join("missing_divs.bson"), - provider_mapping: map_ok.clone(), - bars_1d_dir: bars_ok.join("bars_1d"), - out_dir: out_dir.clone(), - }, - "missing_divs.bson", - ); - - // 3. Missing provider_mapping file. - assert_failed_atomically( - CurateAdjFactorsArgs { - qm_splits: splits_ok.clone(), - qm_dividends: divs_ok.clone(), - provider_mapping: dir.path().join("missing_map.tsv"), - bars_1d_dir: bars_ok.join("bars_1d"), - out_dir: out_dir.clone(), - }, - "missing_map.tsv", - ); - - // 4. Missing bars_1d dir. - assert_failed_atomically( - CurateAdjFactorsArgs { - qm_splits: splits_ok.clone(), - qm_dividends: divs_ok.clone(), - provider_mapping: map_ok.clone(), - bars_1d_dir: dir.path().join("missing_bars_dir"), - out_dir: out_dir.clone(), - }, - "missing_bars_dir", - ); - - // 5. Non-directory bars_1d path. - let not_a_dir = dir.path().join("bars_file.txt"); - write_bytes(¬_a_dir, b"nope"); - assert_failed_atomically( - CurateAdjFactorsArgs { - qm_splits: splits_ok.clone(), - qm_dividends: divs_ok.clone(), - provider_mapping: map_ok.clone(), - bars_1d_dir: not_a_dir, - out_dir: out_dir.clone(), - }, - "bars_file.txt", - ); - - // 5b. Existing root directory with no year=YYYY partitions and no bars_1d/ dataset. - let empty_root_bars = dir.path().join("empty_root_no_bars"); - fs::create_dir_all(&empty_root_bars).unwrap(); - assert_failed_atomically_all( - CurateAdjFactorsArgs { - qm_splits: splits_ok.clone(), - qm_dividends: divs_ok.clone(), - provider_mapping: map_ok.clone(), - bars_1d_dir: empty_root_bars, - out_dir: out_dir.clone(), - }, - &["empty_root_no_bars", "no year=YYYY partitions"], - ); - - // 5c. Existing root directory with an empty nested bars_1d/ directory (no year=YYYY partitions). - let empty_nested_bars = dir.path().join("empty_nested_bars"); - fs::create_dir_all(empty_nested_bars.join("bars_1d")).unwrap(); - assert_failed_atomically_all( - CurateAdjFactorsArgs { - qm_splits: splits_ok.clone(), - qm_dividends: divs_ok.clone(), - provider_mapping: map_ok.clone(), - bars_1d_dir: empty_nested_bars, - out_dir: out_dir.clone(), - }, - &["empty_nested_bars", "no year=YYYY partitions"], - ); - - // 6. Wrong-schema bars_1d part.parquet (place adj_factors part.parquet inside year=2024/). - let wrong_schema_bars = dir.path().join("wrong_schema_bars"); - write_bytes( - &wrong_schema_bars.join("year=2024/part.parquet"), - &baseline_bytes, - ); - assert_failed_atomically( - CurateAdjFactorsArgs { - qm_splits: splits_ok.clone(), - qm_dividends: divs_ok.clone(), - provider_mapping: map_ok.clone(), - bars_1d_dir: wrong_schema_bars, - out_dir: out_dir.clone(), - }, - "schema mismatch", - ); - - // 7. Corrupt bars_1d part.parquet. - let corrupt_bars = dir.path().join("corrupt_bars"); - write_bytes(&corrupt_bars.join("year=2024/part.parquet"), b"not parquet"); - assert_failed_atomically( - CurateAdjFactorsArgs { - qm_splits: splits_ok.clone(), - qm_dividends: divs_ok.clone(), - provider_mapping: map_ok.clone(), - bars_1d_dir: corrupt_bars, - out_dir: out_dir.clone(), - }, - "part.parquet", - ); - - // 8. Missing part.parquet in year=YYYY partition. - let missing_part_bars = dir.path().join("missing_part_bars"); - fs::create_dir_all(missing_part_bars.join("year=2024")).unwrap(); - assert_failed_atomically( - CurateAdjFactorsArgs { - qm_splits: splits_ok.clone(), - qm_dividends: divs_ok.clone(), - provider_mapping: map_ok.clone(), - bars_1d_dir: missing_part_bars, - out_dir: out_dir.clone(), - }, - "part.parquet", - ); - - // 9. Malformed provider_mapping.tsv (reports 1-based line number). - let bad_map = dir.path().join("bad_map.tsv"); - write_bytes(&bad_map, b"qm\tNVDA:US\t2015-01-01\t\t10\nbad_row\n"); - assert_failed_atomically( - CurateAdjFactorsArgs { - qm_splits: splits_ok.clone(), - qm_dividends: divs_ok.clone(), - provider_mapping: bad_map, - bars_1d_dir: bars_ok.join("bars_1d"), - out_dir: out_dir.clone(), - }, - "bad_map.tsv:2:", - ); - - // 10. Truncated BSON stream. - let trunc_splits = dir.path().join("trunc_splits.bson"); - let mut doc = split_doc("NVDA:US", "2024-06-10", 10.0); - doc.truncate(doc.len() - 3); - write_bytes(&trunc_splits, &doc); - assert_failed_atomically( - CurateAdjFactorsArgs { - qm_splits: trunc_splits, - qm_dividends: divs_ok.clone(), - provider_mapping: map_ok.clone(), - bars_1d_dir: bars_ok.join("bars_1d"), - out_dir: out_dir.clone(), - }, - "trunc_splits.bson", - ); - - // 11. Oversized BSON document (> DEFAULT_MAX_DOC_BYTES). - let huge_divs = dir.path().join("huge_divs.bson"); - let huge_len = (DEFAULT_MAX_DOC_BYTES as i32) + 512; - let mut huge_bytes = Vec::from(huge_len.to_le_bytes()); - huge_bytes.push(0); - write_bytes(&huge_divs, &huge_bytes); - assert_failed_atomically( - CurateAdjFactorsArgs { - qm_splits: splits_ok.clone(), - qm_dividends: huge_divs, - provider_mapping: map_ok.clone(), - bars_1d_dir: bars_ok.join("bars_1d"), - out_dir: out_dir.clone(), - }, - "huge_divs.bson", - ); - - // 12. Conflicting cross-key split curation error (must name qmSplits input path). - let alias_map = dir.path().join("alias_map.tsv"); - write_bytes( - &alias_map, - b"qm\tNVDA:US\t2015-01-01\t\t10\nqm\tNVDA_ALT:US\t2015-01-01\t\t10\n", - ); - let conflict_splits = dir.path().join("conflict_splits.bson"); - write_bytes( - &conflict_splits, - &[ - &split_doc("NVDA:US", "2024-06-10", 10.0)[..], - &split_doc("NVDA_ALT:US", "2024-06-10", 4.0)[..], - ] - .concat(), - ); - assert_failed_atomically_all( - CurateAdjFactorsArgs { - qm_splits: conflict_splits, - qm_dividends: divs_ok.clone(), - provider_mapping: alias_map.clone(), - bars_1d_dir: bars_ok.join("bars_1d"), - out_dir: out_dir.clone(), - }, - &["conflict_splits.bson", "conflicting cross-key splits"], - ); - - // 13. Conflicting cross-key dividend curation error (must name qmDividends input path). - let conflict_divs = dir.path().join("conflict_divs.bson"); - write_bytes( - &conflict_divs, - &[ - &div_doc("NVDA:US", "2024-06-11", 0.10, "USD", None)[..], - &div_doc("NVDA_ALT:US", "2024-06-11", 0.20, "USD", None)[..], - ] - .concat(), - ); - assert_failed_atomically_all( - CurateAdjFactorsArgs { - qm_splits: splits_ok, - qm_dividends: conflict_divs, - provider_mapping: alias_map, - bars_1d_dir: bars_ok.join("bars_1d"), - out_dir, - }, - &["conflict_divs.bson", "conflicting cross-key dividends"], - ); -} - -#[test] -fn prev_close_cross_year_multi_row_group_and_layout_parity() { - let dir = TestTempDir::new("cross-year-rg"); - let bars_root = dir.path().join("bars_root"); - let bars = vec![ - bar_row(10, 2023, 12, 27, 98.0, "USD"), - bar_row(10, 2023, 12, 28, 99.0, "USD"), - bar_row(10, 2023, 12, 29, 100.0, "USD"), - bar_row(10, 2024, 1, 2, 105.0, "USD"), - bar_row(10, 2024, 1, 3, 106.0, "USD"), - ]; - let write_stats = write_bars_1d_dataset( - &bars_root, - bars, - Bars1dWriteOptions { - row_group_rows: 2, - ..Bars1dWriteOptions::default() - }, - ) - .unwrap(); - assert!(write_stats.row_groups_written >= 3); - - let map_path = dir.path().join("map.tsv"); - write_bytes(&map_path, b"qm\tX:US\t2020-01-01\t\t10\n"); - - let splits_path = dir.path().join("splits.bson"); - write_bytes(&splits_path, b""); - - let divs_path = dir.path().join("divs.bson"); - // Ex-date 2024-01-02 must use 2023-12-29 close (100.0), not 2024-01-02 close (105.0). - write_bytes(&divs_path, &div_doc("X:US", "2024-01-02", 2.0, "USD", None)); - - let out_direct = dir.path().join("out_direct"); - let report_direct = run_curate_adj_factors(&CurateAdjFactorsArgs { - qm_splits: splits_path.clone(), - qm_dividends: divs_path.clone(), - provider_mapping: map_path.clone(), - bars_1d_dir: bars_root.join("bars_1d"), - out_dir: out_direct.clone(), - }) - .unwrap(); - assert_conservation(&report_direct); - assert_eq!(report_direct.dividends_with_prev_close, 1); - - let out_parent = dir.path().join("out_parent"); - let report_parent = run_curate_adj_factors(&CurateAdjFactorsArgs { - qm_splits: splits_path, - qm_dividends: divs_path, - provider_mapping: map_path, - bars_1d_dir: bars_root, - out_dir: out_parent.clone(), - }) - .unwrap(); - assert_conservation(&report_parent); - - // Both --bars-1d layouts produce byte-identical Parquet output. - let bytes_direct = fs::read(out_direct.join("adj_factors/part.parquet")).unwrap(); - let bytes_parent = fs::read(out_parent.join("adj_factors/part.parquet")).unwrap(); - assert_eq!(bytes_direct, bytes_parent); - - let read_back = read_adj_factors_dataset(&out_direct).unwrap(); - assert_eq!(read_back.rows.len(), 1); - let expected_factor = 100.0_f64 / (100.0_f64 - 2.0_f64); - assert!((read_back.rows[0].cum_total_factor - expected_factor).abs() < 1e-12); -} - -#[test] -fn ticker_reuse_resolves_prev_close_per_mapping_window_and_gap_is_unmapped() { - let dir = TestTempDir::new("ticker-reuse"); - let bars_root = dir.path().join("bars_root"); - write_bars_1d_dataset( - &bars_root, - vec![ - bar_row(101, 2021, 6, 14, 50.0, "USD"), - bar_row(202, 2023, 6, 14, 200.0, "USD"), - ], - Bars1dWriteOptions::default(), - ) - .unwrap(); - - let map_path = dir.path().join("map.tsv"); - write_bytes( - &map_path, - b"qm\tREUSED:US\t2020-01-01\t2021-12-31\t101\nqm\tREUSED:US\t2023-01-01\t\t202\n", - ); - - let splits_path = dir.path().join("splits.bson"); - write_bytes(&splits_path, b""); - - let divs_path = dir.path().join("divs.bson"); - let mut div_bytes = Vec::new(); - // Window 1 -> listing 101 (prev_close = 50.0) - div_bytes.extend_from_slice(&div_doc("REUSED:US", "2021-06-15", 1.0, "USD", None)); - // Gap -> unmapped - div_bytes.extend_from_slice(&div_doc("REUSED:US", "2022-06-15", 1.0, "USD", None)); - // Window 2 -> listing 202 (prev_close = 200.0) - div_bytes.extend_from_slice(&div_doc("REUSED:US", "2023-06-15", 4.0, "USD", None)); - write_bytes(&divs_path, &div_bytes); - - let out_dir = dir.path().join("out"); - let report = run_curate_adj_factors(&CurateAdjFactorsArgs { - qm_splits: splits_path, - qm_dividends: divs_path, - provider_mapping: map_path, - bars_1d_dir: bars_root.join("bars_1d"), - out_dir: out_dir.clone(), - }) - .unwrap(); - assert_conservation(&report); - assert_eq!(report.dividends_with_prev_close, 2); - assert_eq!(report.dividends_without_prev_close, 0); - assert_eq!(report.curate_stats.dividends_dropped_unmapped, 1); - - let read_back = read_adj_factors_dataset(&out_dir).unwrap(); - assert_eq!(read_back.rows.len(), 2); - let r101 = read_back.rows.iter().find(|r| r.listing_id == 101).unwrap(); - let r202 = read_back.rows.iter().find(|r| r.listing_id == 202).unwrap(); - assert!((r101.cum_total_factor - (50.0_f64 / 49.0_f64)).abs() < 1e-12); - assert!((r202.cum_total_factor - (200.0_f64 / 196.0_f64)).abs() < 1e-12); -} - -#[test] -fn dividend_at_or_above_prev_close_falls_back_to_unit_factor() { - let dir = TestTempDir::new("div-ge-close"); - let bars_root = dir.path().join("bars_root"); - write_bars_1d_dataset( - &bars_root, - vec![bar_row(10, 2024, 5, 1, 10.0, "USD")], - Bars1dWriteOptions::default(), - ) - .unwrap(); - - let map_path = dir.path().join("map.tsv"); - write_bytes(&map_path, b"qm\tBIG:US\t2020-01-01\t\t10\n"); - - let splits_path = dir.path().join("splits.bson"); - write_bytes(&splits_path, b""); - - let divs_path = dir.path().join("divs.bson"); - write_bytes(&divs_path, &div_doc("BIG:US", "2024-05-02", 10.0, "USD", None)); - - let out_dir = dir.path().join("out"); - let report = run_curate_adj_factors(&CurateAdjFactorsArgs { - qm_splits: splits_path, - qm_dividends: divs_path, - provider_mapping: map_path, - bars_1d_dir: bars_root.join("bars_1d"), - out_dir: out_dir.clone(), - }) - .unwrap(); - assert_conservation(&report); - assert_eq!(report.dividends_with_prev_close, 1); - - let read_back = read_adj_factors_dataset(&out_dir).unwrap(); - assert_eq!(read_back.rows.len(), 1); - assert_eq!(read_back.rows[0].cum_total_factor.to_bits(), 1.0_f64.to_bits()); -} - -#[test] -fn empty_inputs_publish_readable_empty_snapshot() { - let dir = TestTempDir::new("empty-inputs"); - let bars_root = dir.path().join("bars_root"); - write_bars_1d_dataset( - &bars_root, - vec![bar_row(10, 2024, 1, 2, 100.0, "USD")], - Bars1dWriteOptions::default(), - ) - .unwrap(); - - let map_path = dir.path().join("map.tsv"); - let splits_path = dir.path().join("splits.bson"); - let divs_path = dir.path().join("divs.bson"); - write_bytes(&map_path, b""); - write_bytes(&splits_path, b""); - write_bytes(&divs_path, b""); - - let out_dir = dir.path().join("out"); - let report = run_curate_adj_factors(&CurateAdjFactorsArgs { - qm_splits: splits_path, - qm_dividends: divs_path, - provider_mapping: map_path, - bars_1d_dir: bars_root.join("bars_1d"), - out_dir: out_dir.clone(), - }) - .unwrap(); - assert_conservation(&report); - assert_eq!(report.write_stats.rows_written, 0); - - let read_back = read_adj_factors_dataset(&out_dir).unwrap(); - assert!(read_back.rows.is_empty()); - assert_eq!( - read_back.snapshot_kind, - AdjSnapshotKind::RetrospectiveSnapshot - ); -} - -#[test] -fn duplicate_bar_across_partitions_and_out_file_fail_atomically() { - let dir = TestTempDir::new("dup-bar-and-out-file"); - let bars_root = dir.path().join("bars_root"); - write_bars_1d_dataset( - &bars_root, - vec![bar_row(10, 2024, 1, 2, 100.0, "USD")], - Bars1dWriteOptions::default(), - ) - .unwrap(); - - let map_path = dir.path().join("map.tsv"); - let splits_path = dir.path().join("splits.bson"); - let divs_path = dir.path().join("divs.bson"); - write_bytes(&map_path, b"qm\tNVDA:US\t2015-01-01\t\t10\n"); - write_bytes(&splits_path, &split_doc("NVDA:US", "2024-06-10", 10.0)); - write_bytes(&divs_path, b""); - - let out_dir = dir.path().join("out"); - run_curate_adj_factors(&CurateAdjFactorsArgs { - qm_splits: splits_path.clone(), - qm_dividends: divs_path.clone(), - provider_mapping: map_path.clone(), - bars_1d_dir: bars_root.join("bars_1d"), - out_dir: out_dir.clone(), - }) - .unwrap(); - let baseline_path = out_dir.join("adj_factors/part.parquet"); - let baseline_bytes = fs::read(&baseline_path).unwrap(); - - // Copy year=2024/part.parquet into year=2025/part.parquet to create duplicate (listing_id, session_date). - let dup_bars = dir.path().join("dup_bars"); - let part_bytes = fs::read(bars_root.join("bars_1d/year=2024/part.parquet")).unwrap(); - write_bytes(&dup_bars.join("year=2024/part.parquet"), &part_bytes); - write_bytes(&dup_bars.join("year=2025/part.parquet"), &part_bytes); - - let err = run_curate_adj_factors(&CurateAdjFactorsArgs { - qm_splits: splits_path.clone(), - qm_dividends: divs_path.clone(), - provider_mapping: map_path.clone(), - bars_1d_dir: dup_bars, - out_dir: out_dir.clone(), - }) - .unwrap_err(); - let msg = err.to_string(); - assert!(!msg.contains('\n'), "error must be single-line: {msg}"); - assert!(msg.contains("duplicate"), "unexpected error: {msg}"); - assert_eq!(fs::read(&baseline_path).unwrap(), baseline_bytes); - - // --out pointing at an existing regular file must fail without modifying the file. - let out_file = dir.path().join("out_is_file"); - write_bytes(&out_file, b"untouched"); - let err = run_curate_adj_factors(&CurateAdjFactorsArgs { - qm_splits: splits_path, - qm_dividends: divs_path, - provider_mapping: map_path, - bars_1d_dir: bars_root.join("bars_1d"), - out_dir: out_file.clone(), - }) - .unwrap_err(); - let msg = err.to_string(); - assert!(!msg.contains('\n'), "error must be single-line: {msg}"); - assert!(msg.contains("out_is_file"), "unexpected error: {msg}"); - assert_eq!(fs::read(&out_file).unwrap(), b"untouched"); -} diff --git a/tools/curate-etl/src/run_curate_bars.rs b/tools/curate-etl/src/run_curate_bars.rs deleted file mode 100644 index c45eec76..00000000 --- a/tools/curate-etl/src/run_curate_bars.rs +++ /dev/null @@ -1,1489 +0,0 @@ -//! File-to-file `curate-bars-1d` command runner (`M1.2z`). -//! -//! Streams concatenated raw BSON `eodPrices` and `qmSplits` dump files alongside -//! `provider_mapping` and `listing_currencies` TSV files into an atomically published -//! `/bars_1d/year=YYYY/part.parquet` dataset via [`curate_and_write_bars_1d`]. -//! -//! # TSV Formats (strict, headerless, `\t`-separated) -//! - `provider_mapping`: -//! `source \t source_id \t valid_from(YYYY-MM-DD) \t valid_to(YYYY-MM-DD or empty) \t listing_id` -//! (`source` and `source_id` are preserved verbatim — never trimmed). -//! - `listing_currencies`: -//! `listing_id \t currency` -//! (unique positive `listing_id` per row; non-blank currency code). -//! - Both TSVs accept `\n` or `\r\n` line endings and at most one trailing blank line. -//! -//! # Missing-Currency Behavior -//! Delegated unchanged to [`curate_bars_1d`]: any mapped `listing_id` absent from -//! `listing_currencies` (or mapping to a blank string) is dropped and counted in -//! [`CurateBars1dStats::dropped_missing_currency`] rather than failing the run. - -use std::borrow::Cow; -use std::collections::{HashMap, HashSet}; -use std::error::Error; -use std::fmt; -use std::fs::File; -use std::io::{self, BufRead, BufReader}; -use std::mem::size_of; -use std::path::{Path, PathBuf}; -use std::sync::Arc; -use std::time::Instant; - -use crate::bars::{EodDailyBar, QmRawVolume, VolumeMismatchSample}; -use crate::bson_eod_prices::{parse_ymd_strict_days, BsonEodDecodeStats}; -use crate::bson_qm_actions::BsonQmActionDecodeStats; -use crate::bson_qm_prices::BsonQmPriceDecodeStats; -use crate::bson_stream::{ - decode_eod_price_chunks, decode_qm_price_chunks, decode_qm_split_chunks, BsonStreamError, - RawBsonChunkReader, -}; -use crate::curate_bars::{ - curate_and_write_bars_1d, curate_bars_1d, CurateBars1dStats, CurateBarsWriteError, -}; -use crate::parquet_bars::{ - default_parallel_threads, write_bars_1d_dataset, Bars1dWriteOptions, Bars1dWriteStats, - ParquetBarsError, -}; -use crate::provider_mapping::{ProviderMappingError, ProviderMappingRow, ProviderMappingTable}; -use crate::shorts::epoch_days_to_ymd; -use crate::split::{SplitError, SplitEvent, SplitTable}; - -/// Default relative volume tolerance passed to `curate_bars_1d` (matches `bench-curate-bars`). -pub const DEFAULT_CURATE_BARS_REL_TOLERANCE: f64 = 0.01; - -/// Default Parquet writer thread count for `curate-bars-1d` (`std::thread::available_parallelism()`, -/// falling back to `1`). -pub fn default_curate_bars_threads() -> usize { - default_parallel_threads() -} - -/// Parsed arguments for the `curate-bars-1d` CLI command. -#[derive(Debug, Clone, PartialEq)] -pub struct CurateBars1dArgs { - pub eod_prices: PathBuf, - pub qm_splits: PathBuf, - pub qm_prices: Option, - pub provider_mapping: PathBuf, - pub listing_currencies: PathBuf, - pub out_dir: PathBuf, - pub rel_tolerance: f64, - pub threads: usize, -} - -/// Accounting counters for re-keying `qmSplits` (`qmSearchCode` -> `listing_id` -> `eodSearchCode`). -/// -/// Conservation invariant (paired with `splits_decode: BsonQmActionDecodeStats`): -/// `splits_in == splits_applied + splits_collision_collapsed + splits_unmapped_qm + splits_no_eod_partner + splits_noop_dropped + splits_decode.rejected_total()`. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct SplitRekeyStats { - /// Total `qmSplits` documents framed and fed into the decoder (`== splits_decode.docs_in`). - pub splits_in: usize, - /// Decoded `qmSplits` rows with `ratio == 1.0` dropped as no-ops before re-keying. - pub splits_noop_dropped: usize, - /// Non-no-op decoded splits whose `("qm", qm_search_code, ex_date)` had no mapping. - pub splits_unmapped_qm: usize, - /// Mapped splits whose `listing_id` had no `"eod"` `source_id` partner in `provider_mapping`. - pub splits_no_eod_partner: usize, - /// Cross-key QM alias split documents on the same `(listing_id, ex_date)` with bitwise - /// identical ratio collapsed before fanning out to `"eod"` partners. - pub splits_collision_collapsed: usize, - /// Non-no-op splits attached to at least one `"eod"` `source_id` after cross-key compaction. - pub splits_applied: usize, - /// Total `(eod_source_id, SplitEvent)` pairs pushed into `SplitTable` (may exceed - /// `splits_applied` when a listing has multiple `"eod"` `source_id`s). - pub split_events_attached: usize, -} - -/// Accounting counters for date-aware re-keying of `qmPrices` -/// (`qmSearchCode` -> `listing_id` -> `eodSearchCode`). -/// -/// Conservation invariants (paired with `qm_prices_decode: BsonQmPriceDecodeStats` and -/// `curate_stats.builder: Bars1dStats`): -/// - `qm_in == qm_attached + qm_unmapped_qm + qm_no_eod_partner + qm_prices_decode.rejected_total()` -/// - `qm_volumes_attached == curate_stats.builder.qm_rows_in` -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct QmVolumeRekeyStats { - /// Total `qmPrices` documents framed and fed into the decoder (`== qm_prices_decode.docs_in`). - pub qm_in: usize, - /// Decoded `qmPrices` rows whose `("qm", qm_search_code, session_date)` had no mapping. - pub qm_unmapped_qm: usize, - /// Mapped `qmPrices` rows whose `listing_id` had no `"eod"` mapping covering `session_date`. - pub qm_no_eod_partner: usize, - /// Decoded `qmPrices` rows attached to at least one date-covering `"eod"` `source_id`. - pub qm_attached: usize, - /// Total `QmRawVolume>` observations pushed into `build_bars_1d` (`== builder.qm_rows_in`). - pub qm_volumes_attached: usize, -} - -/// Full run report produced by [`run_curate_bars_1d`]. -#[derive(Debug, Clone, PartialEq)] -pub struct CurateBars1dRunReport { - pub eod_docs_framed: u64, - pub eod_bytes_read: u64, - pub eod_decode: BsonEodDecodeStats, - pub splits_docs_framed: u64, - pub splits_bytes_read: u64, - pub splits_decode: BsonQmActionDecodeStats, - pub split_rekey: SplitRekeyStats, - pub qm_prices_present: bool, - pub qm_prices_docs_framed: u64, - pub qm_prices_bytes_read: u64, - pub qm_prices_decode: BsonQmPriceDecodeStats, - pub qm_rekey: QmVolumeRekeyStats, - pub buffered_qm_bytes: usize, - pub bars_unmapped_source_dropped: usize, - pub buffered_bars: usize, - /// Approximate heap bytes occupied by the buffered `Vec>>` capacity plus - /// the interned `"eod"` `Arc` key allocations. - pub buffered_bar_bytes: usize, - pub curate_stats: CurateBars1dStats, - pub write_stats: Bars1dWriteStats, - pub mismatch_samples: Vec>>, - pub threads: usize, - pub elapsed_secs: f64, -} - -/// Stage-timed run output used internally by `bench-curate-bars-cmd`. -#[allow(dead_code)] -#[derive(Debug, Clone, PartialEq)] -pub(crate) struct CurateBars1dTimedRun { - pub report: CurateBars1dRunReport, - pub decode_elapsed_secs: f64, - pub qm_decode_rekey_elapsed_secs: f64, - pub curate_elapsed_secs: f64, - pub write_elapsed_secs: f64, -} - -/// Stage-timed run output comparing sequential (`threads=1`) vs parallel (`threads=par_threads`) -/// Parquet writes on the same curated rows for `bench-curate-bars-cmd`. -#[derive(Debug, Clone, PartialEq)] -pub(crate) struct CurateBars1dTimedCompareRun { - pub report: CurateBars1dRunReport, - pub decode_elapsed_secs: f64, - pub qm_decode_rekey_elapsed_secs: f64, - pub curate_elapsed_secs: f64, - pub write_seq_elapsed_secs: f64, - pub write_par_elapsed_secs: f64, - pub write_stats_seq: Bars1dWriteStats, -} - -/// Typed errors returned by [`run_curate_bars_1d`] and its TSV loaders. -/// -/// Every variant's `Display` output is a single line naming the offending path (and 1-based line -/// number for TSV parse errors). -#[derive(Debug)] -pub enum RunCurateBarsError { - InvalidOutDir { - path: PathBuf, - detail: String, - }, - OpenInput { - label: &'static str, - path: PathBuf, - source: io::Error, - }, - ReadInput { - label: &'static str, - path: PathBuf, - source: io::Error, - }, - TsvParse { - path: PathBuf, - line: usize, - detail: String, - }, - ProviderMapping { - path: PathBuf, - source: ProviderMappingError, - }, - BsonStream { - label: &'static str, - path: PathBuf, - source: BsonStreamError, - }, - SplitTable { - path: PathBuf, - source: SplitError, - }, - ConflictingCrossKeySplit { - path: PathBuf, - listing_id: i32, - ex_date: i32, - first_key: String, - first_ratio: f64, - second_key: String, - second_ratio: f64, - }, - CurateWrite { - out_dir: PathBuf, - source: CurateBarsWriteError, - }, -} - -impl fmt::Display for RunCurateBarsError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::InvalidOutDir { path, detail } => { - write!(f, "invalid --out '{}': {detail}", path.display()) - } - Self::OpenInput { - label, - path, - source, - } => write!(f, "failed to open {label} '{}': {source}", path.display()), - Self::ReadInput { - label, - path, - source, - } => write!(f, "failed to read {label} '{}': {source}", path.display()), - Self::TsvParse { path, line, detail } => { - write!(f, "{}:{line}: {detail}", path.display()) - } - Self::ProviderMapping { path, source } => { - write!(f, "invalid provider_mapping '{}': {source}", path.display()) - } - Self::BsonStream { - label, - path, - source, - } => write!(f, "failed reading {label} '{}': {source}", path.display()), - Self::SplitTable { path, source } => { - write!(f, "invalid split table from '{}': {source}", path.display()) - } - Self::ConflictingCrossKeySplit { - path, - listing_id, - ex_date, - first_key, - first_ratio, - second_key, - second_ratio, - } => write!( - f, - "conflicting cross-key split in '{}': listing_id={listing_id} ex_date={ex_date} '{first_key}' ({first_ratio}) vs '{second_key}' ({second_ratio})", - path.display() - ), - Self::CurateWrite { out_dir, source } => { - write!(f, "curate/write to '{}' failed: {source}", out_dir.display()) - } - } - } -} - -impl Error for RunCurateBarsError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::OpenInput { source, .. } | Self::ReadInput { source, .. } => Some(source), - Self::ProviderMapping { source, .. } => Some(source), - Self::BsonStream { source, .. } => Some(source), - Self::SplitTable { source, .. } => Some(source), - Self::CurateWrite { source, .. } => Some(source), - Self::InvalidOutDir { .. } - | Self::TsvParse { .. } - | Self::ConflictingCrossKeySplit { .. } => None, - } - } -} - -/// Parses a strictly positive ASCII base-10 `i32` (no leading/trailing whitespace or sign). -pub(crate) fn parse_strict_positive_i32(raw: &str) -> Option { - if raw.is_empty() || !raw.bytes().all(|b| b.is_ascii_digit()) { - return None; - } - let val = raw.parse::().ok()?; - if val > 0 { - Some(val) - } else { - None - } -} - -/// Streams a strict headerless TSV file line by line, enforcing `\n`/`\r\n` endings, valid UTF-8, -/// and at most one trailing blank line. -pub(crate) fn read_tsv_lines( - path: &Path, - label: &'static str, - mut on_line: F, -) -> Result<(), RunCurateBarsError> -where - F: FnMut(usize, &str) -> Result<(), String>, -{ - let file = File::open(path).map_err(|source| RunCurateBarsError::OpenInput { - label, - path: path.to_path_buf(), - source, - })?; - let mut reader = BufReader::new(file); - let mut raw_buf: Vec = Vec::with_capacity(256); - let mut line_no: usize = 0; - let mut pending_blank_line: Option = None; - - loop { - raw_buf.clear(); - let bytes_read = - reader - .read_until(b'\n', &mut raw_buf) - .map_err(|source| RunCurateBarsError::ReadInput { - label, - path: path.to_path_buf(), - source, - })?; - if bytes_read == 0 { - break; - } - line_no += 1; - - let mut slice = raw_buf.as_slice(); - if slice.ends_with(b"\n") { - slice = &slice[..slice.len() - 1]; - if slice.ends_with(b"\r") { - slice = &slice[..slice.len() - 1]; - } - } - if slice.contains(&b'\r') { - return Err(RunCurateBarsError::TsvParse { - path: path.to_path_buf(), - line: line_no, - detail: "unexpected carriage return inside TSV line".to_string(), - }); - } - - let text = std::str::from_utf8(slice).map_err(|_| RunCurateBarsError::TsvParse { - path: path.to_path_buf(), - line: line_no, - detail: "invalid UTF-8 in TSV line".to_string(), - })?; - - if text.is_empty() { - if pending_blank_line.is_some() { - return Err(RunCurateBarsError::TsvParse { - path: path.to_path_buf(), - line: line_no, - detail: "multiple trailing blank lines are not allowed".to_string(), - }); - } - pending_blank_line = Some(line_no); - continue; - } - - if let Some(blank_line) = pending_blank_line.take() { - return Err(RunCurateBarsError::TsvParse { - path: path.to_path_buf(), - line: blank_line, - detail: "blank line is only allowed as a single trailing line".to_string(), - }); - } - - on_line(line_no, text).map_err(|detail| RunCurateBarsError::TsvParse { - path: path.to_path_buf(), - line: line_no, - detail, - })?; - } - - Ok(()) -} - -/// Loads `provider_mapping.tsv` into raw [`ProviderMappingRow`] records. -/// -/// Format (no header, 5 `\t`-separated columns): -/// `source \t source_id \t valid_from(YYYY-MM-DD) \t valid_to(YYYY-MM-DD or empty) \t listing_id` -/// -/// `source` and `source_id` are preserved verbatim (never trimmed). -pub fn load_provider_mapping_tsv( - path: &Path, -) -> Result, RunCurateBarsError> { - let mut rows = Vec::new(); - read_tsv_lines(path, "provider-mapping", |_line_no, line| { - let mut fields = line.split('\t'); - let source = fields - .next() - .ok_or_else(|| "expected 5 tab-separated columns".to_string())?; - let source_id = fields - .next() - .ok_or_else(|| "expected 5 tab-separated columns (got 1)".to_string())?; - let valid_from_str = fields - .next() - .ok_or_else(|| "expected 5 tab-separated columns (got 2)".to_string())?; - let valid_to_str = fields - .next() - .ok_or_else(|| "expected 5 tab-separated columns (got 3)".to_string())?; - let listing_id_str = fields - .next() - .ok_or_else(|| "expected 5 tab-separated columns (got 4)".to_string())?; - if fields.next().is_some() { - return Err("expected 5 tab-separated columns (got more than 5)".to_string()); - } - - if source.trim().is_empty() { - return Err("source column must not be empty or blank".to_string()); - } - if source_id.trim().is_empty() { - return Err("source_id column must not be empty or blank".to_string()); - } - - let valid_from = parse_ymd_strict_days(valid_from_str).ok_or_else(|| { - format!("invalid valid_from date '{valid_from_str}' (expected YYYY-MM-DD)") - })?; - let valid_to = if valid_to_str.is_empty() { - None - } else { - Some(parse_ymd_strict_days(valid_to_str).ok_or_else(|| { - format!("invalid valid_to date '{valid_to_str}' (expected YYYY-MM-DD or empty)") - })?) - }; - let listing_id = parse_strict_positive_i32(listing_id_str).ok_or_else(|| { - format!("invalid listing_id '{listing_id_str}' (expected positive integer)") - })?; - - rows.push(ProviderMappingRow { - source: source.to_owned(), - source_id: source_id.to_owned(), - valid_from, - valid_to, - listing_id, - }); - Ok(()) - })?; - Ok(rows) -} - -/// Loads `listing_currencies.tsv` into a `listing_id -> currency` map. -/// -/// Format (no header, 2 `\t`-separated columns): -/// `listing_id \t currency` -pub fn load_listing_currencies_tsv( - path: &Path, -) -> Result>, RunCurateBarsError> { - let mut currencies: HashMap> = HashMap::new(); - read_tsv_lines(path, "listing-currencies", |_line_no, line| { - let mut fields = line.split('\t'); - let listing_id_str = fields - .next() - .ok_or_else(|| "expected 2 tab-separated columns".to_string())?; - let currency_str = fields - .next() - .ok_or_else(|| "expected 2 tab-separated columns (got 1)".to_string())?; - if fields.next().is_some() { - return Err("expected 2 tab-separated columns (got more than 2)".to_string()); - } - - let listing_id = parse_strict_positive_i32(listing_id_str).ok_or_else(|| { - format!("invalid listing_id '{listing_id_str}' (expected positive integer)") - })?; - if currency_str.trim().is_empty() { - return Err("currency column must not be empty or blank".to_string()); - } - - let currency: Cow<'static, str> = match currency_str { - "USD" => Cow::Borrowed("USD"), - "CAD" => Cow::Borrowed("CAD"), - other => Cow::Owned(other.to_owned()), - }; - - if currencies.insert(listing_id, currency).is_some() { - return Err(format!( - "duplicate listing_id {listing_id} in listing_currencies" - )); - } - Ok(()) - })?; - Ok(currencies) -} - -struct LoadedCurateBarsInputs { - mapping: ProviderMappingTable, - currencies: HashMap>, - splits: SplitTable>, - bars: Vec>>, - qm_volumes: Vec>>, - eod_docs_framed: u64, - eod_bytes_read: u64, - eod_decode: BsonEodDecodeStats, - splits_docs_framed: u64, - splits_bytes_read: u64, - splits_decode: BsonQmActionDecodeStats, - split_rekey: SplitRekeyStats, - qm_prices_present: bool, - qm_prices_docs_framed: u64, - qm_prices_bytes_read: u64, - qm_prices_decode: BsonQmPriceDecodeStats, - qm_rekey: QmVolumeRekeyStats, - buffered_qm_bytes: usize, - qm_decode_rekey_elapsed_secs: f64, - bars_unmapped_source_dropped: usize, - buffered_bars: usize, - buffered_bar_bytes: usize, -} - -pub(crate) struct EodListingRange { - valid_from: i32, - valid_to: Option, - key: Arc, -} - -pub(crate) struct EodMappingIndex { - pub(crate) eod_keys: HashSet>, - pub(crate) eod_by_listing: HashMap>>, - pub(crate) eod_ranges_by_listing: HashMap>, -} - -pub(crate) struct DecodedQmSplits { - pub(crate) compacted_splits: Vec<(i32, SplitEvent)>, - pub(crate) splits_docs_framed: u64, - pub(crate) splits_bytes_read: u64, - pub(crate) splits_decode: BsonQmActionDecodeStats, - pub(crate) split_rekey: SplitRekeyStats, -} - -pub(crate) struct LoadedQmSplits { - pub(crate) splits: SplitTable>, - pub(crate) splits_docs_framed: u64, - pub(crate) splits_bytes_read: u64, - pub(crate) splits_decode: BsonQmActionDecodeStats, - pub(crate) split_rekey: SplitRekeyStats, -} - -#[inline] -fn valid_to_sort_key(valid_to: Option) -> (u8, i32) { - match valid_to { - Some(to) => (0, to), - None => (1, i32::MAX), - } -} - -/// Builds the interned `"eod"` key set and reverse `listing_id -> [eod source_id]` index once. -/// When `track_eod_ranges` is true, also builds a date-aware reverse index -/// `listing_id -> [(valid_from, valid_to, Arc)]` so reused EOD tickers never receive -/// cross-check observations outside their mapping range. -pub(crate) fn build_eod_mapping_index( - mapping_rows: &[ProviderMappingRow], - track_eod_ranges: bool, -) -> EodMappingIndex { - let mut eod_keys: HashSet> = HashSet::new(); - let mut eod_by_listing: HashMap>> = HashMap::new(); - let mut eod_ranges_by_listing: HashMap> = HashMap::new(); - for row in mapping_rows { - if row.source == "eod" { - let key = match eod_keys.get(row.source_id.as_str()) { - Some(existing) => Arc::clone(existing), - None => { - let arc: Arc = Arc::from(row.source_id.as_str()); - eod_keys.insert(Arc::clone(&arc)); - arc - } - }; - if track_eod_ranges { - eod_ranges_by_listing - .entry(row.listing_id) - .or_default() - .push(EodListingRange { - valid_from: row.valid_from, - valid_to: row.valid_to, - key: Arc::clone(&key), - }); - } - eod_by_listing.entry(row.listing_id).or_default().push(key); - } - } - for partners in eod_by_listing.values_mut() { - partners.sort_unstable(); - partners.dedup(); - } - for ranges in eod_ranges_by_listing.values_mut() { - ranges.sort_unstable_by(|a, b| { - a.valid_from - .cmp(&b.valid_from) - .then_with(|| valid_to_sort_key(a.valid_to).cmp(&valid_to_sort_key(b.valid_to))) - .then_with(|| a.key.cmp(&b.key)) - }); - } - EodMappingIndex { - eod_keys, - eod_by_listing, - eod_ranges_by_listing, - } -} - -/// Streams `qmSplits` BSON, resolves `("qm", qmSearchCode, ex_date) -> listing_id`, filters out -/// listings without an `"eod"` partner, and compacts cross-key QM aliases per `(listing_id, ex_date)` -/// while retaining permanent `listing_id` identity. -pub(crate) fn decode_and_compact_qm_splits_from_reader( - splits_stream: R, - qm_splits_path: &Path, - mapping: &ProviderMappingTable, - eod_by_listing: &HashMap>>, -) -> Result { - let mut splits_reader = RawBsonChunkReader::new(splits_stream); - let mut split_rekey = SplitRekeyStats::default(); - let mut mapped_splits: Vec = Vec::new(); - let splits_decode = decode_qm_split_chunks( - &mut splits_reader, - |split| { - if split.ratio == 1.0 { - split_rekey.splits_noop_dropped += 1; - return; - } - let Some(listing_id) = mapping.resolve("qm", split.qm_search_code, split.ex_date) - else { - split_rekey.splits_unmapped_qm += 1; - return; - }; - let has_eod_partner = eod_by_listing - .get(&listing_id) - .is_some_and(|partners| !partners.is_empty()); - if !has_eod_partner { - split_rekey.splits_no_eod_partner += 1; - return; - } - mapped_splits.push(MappedQmSplit { - listing_id, - ex_date: split.ex_date, - qm_key: split.qm_search_code.to_owned(), - ratio: split.ratio, - }); - }, - |_offset, _err| {}, - ) - .map_err(|source| RunCurateBarsError::BsonStream { - label: "qm-splits", - path: qm_splits_path.to_path_buf(), - source, - })?; - let splits_docs_framed = splits_reader.docs_framed(); - let splits_bytes_read = splits_reader.bytes_read(); - split_rekey.splits_in = splits_decode.docs_in; - - // Compact cross-key QM aliases per `(listing_id, ex_date)`. - let (compacted_splits, splits_collision_collapsed) = - compact_mapped_qm_splits(qm_splits_path, mapped_splits)?; - split_rekey.splits_collision_collapsed = splits_collision_collapsed; - - Ok(DecodedQmSplits { - compacted_splits, - splits_docs_framed, - splits_bytes_read, - splits_decode, - split_rekey, - }) -} - -/// Streams `qmSplits` BSON, resolves `("qm", qmSearchCode, ex_date) -> listing_id`, compacts -/// cross-key QM aliases per `(listing_id, ex_date)`, fans out to `"eod"` partners, and builds -/// [`SplitTable>`]. -pub(crate) fn load_qm_splits_from_reader( - splits_stream: R, - qm_splits_path: &Path, - mapping: &ProviderMappingTable, - eod_by_listing: &HashMap>>, -) -> Result { - let DecodedQmSplits { - compacted_splits, - splits_docs_framed, - splits_bytes_read, - splits_decode, - mut split_rekey, - } = decode_and_compact_qm_splits_from_reader( - splits_stream, - qm_splits_path, - mapping, - eod_by_listing, - )?; - - let mut split_events: Vec<(Arc, SplitEvent)> = Vec::with_capacity(compacted_splits.len()); - for (listing_id, event) in compacted_splits { - let partners = &eod_by_listing[&listing_id]; - split_rekey.splits_applied += 1; - for eod_key in partners { - split_events.push((Arc::clone(eod_key), event)); - } - split_rekey.split_events_attached += partners.len(); - } - - let splits = SplitTable::>::from_events(split_events).map_err(|source| { - RunCurateBarsError::SplitTable { - path: qm_splits_path.to_path_buf(), - source, - } - })?; - - Ok(LoadedQmSplits { - splits, - splits_docs_framed, - splits_bytes_read, - splits_decode, - split_rekey, - }) -} - -fn validate_out_dir(out_dir: &Path) -> Result<(), RunCurateBarsError> { - if out_dir.exists() && !out_dir.is_dir() { - return Err(RunCurateBarsError::InvalidOutDir { - path: out_dir.to_path_buf(), - detail: "path exists and is not a directory".to_string(), - }); - } - Ok(()) -} - -struct MappedQmSplit { - listing_id: i32, - ex_date: i32, - qm_key: String, - ratio: f64, -} - -/// Applies the `curate_adj` cross-key split policy by `(listing_id, ex_date)` before fanning out -/// to `"eod"` partners: -/// - Single-QM-key groups pass through unchanged (preserving `SplitTable` same-day multiplication). -/// - Multi-QM-key groups with bitwise-identical ratios collapse to one event (`collapsed += n - 1`). -/// - Multi-QM-key groups with conflicting ratios fail closed with `ConflictingCrossKeySplit`. -fn compact_mapped_qm_splits( - path: &Path, - mut mapped: Vec, -) -> Result<(Vec<(i32, SplitEvent)>, usize), RunCurateBarsError> { - mapped.sort_unstable_by(|a, b| { - a.listing_id - .cmp(&b.listing_id) - .then_with(|| a.ex_date.cmp(&b.ex_date)) - .then_with(|| a.qm_key.cmp(&b.qm_key)) - .then_with(|| a.ratio.total_cmp(&b.ratio)) - }); - - let mut out: Vec<(i32, SplitEvent)> = Vec::with_capacity(mapped.len()); - let mut collapsed_total = 0usize; - let mut iter = mapped.into_iter().peekable(); - let mut group: Vec = Vec::with_capacity(4); - - while let Some(first) = iter.next() { - let listing_id = first.listing_id; - let ex_date = first.ex_date; - group.clear(); - group.push(first); - while let Some(next) = iter.peek() { - if next.listing_id == listing_id && next.ex_date == ex_date { - group.push(iter.next().expect("peeked split")); - } else { - break; - } - } - - let group_len = group.len(); - if group_len == 1 { - let item = group.pop().expect("single split"); - out.push(( - listing_id, - SplitEvent { - ex_date, - ratio: item.ratio, - }, - )); - continue; - } - - let first_key = group[0].qm_key.as_str(); - let last_key = group[group_len - 1].qm_key.as_str(); - if first_key == last_key { - for item in group.drain(..) { - out.push(( - listing_id, - SplitEvent { - ex_date, - ratio: item.ratio, - }, - )); - } - continue; - } - - let first_ratio = group[0].ratio; - let first_ratio_bits = first_ratio.to_bits(); - let all_identical = group[1..] - .iter() - .all(|other| other.ratio.to_bits() == first_ratio_bits); - - if all_identical { - collapsed_total += group_len - 1; - out.push(( - listing_id, - SplitEvent { - ex_date, - ratio: first_ratio, - }, - )); - } else { - let (lhs, rhs) = if let Some(other) = group[1..] - .iter() - .find(|e| e.qm_key.as_str() != first_key && e.ratio.to_bits() != first_ratio_bits) - { - (&group[0], other) - } else { - let bad = group[1..] - .iter() - .find(|e| e.ratio.to_bits() != first_ratio_bits) - .expect("non-identical split exists"); - let other_key = group[1..] - .iter() - .find(|e| e.qm_key.as_str() != first_key) - .expect("distinct source key exists"); - (bad, other_key) - }; - return Err(RunCurateBarsError::ConflictingCrossKeySplit { - path: path.to_path_buf(), - listing_id, - ex_date, - first_key: lhs.qm_key.clone(), - first_ratio: lhs.ratio, - second_key: rhs.qm_key.clone(), - second_ratio: rhs.ratio, - }); - } - } - - Ok((out, collapsed_total)) -} - -fn load_and_decode_inputs( - args: &CurateBars1dArgs, -) -> Result { - validate_out_dir(&args.out_dir)?; - - let qm_prices_path = args.qm_prices.clone(); - load_and_decode_from_openers( - &args.provider_mapping, - &args.listing_currencies, - &args.qm_splits, - || { - File::open(&args.qm_splits).map_err(|source| RunCurateBarsError::OpenInput { - label: "qm-splits", - path: args.qm_splits.clone(), - source, - }) - }, - &args.eod_prices, - || { - File::open(&args.eod_prices).map_err(|source| RunCurateBarsError::OpenInput { - label: "eod-prices", - path: args.eod_prices.clone(), - source, - }) - }, - qm_prices_path.as_deref(), - || match &qm_prices_path { - Some(path) => Ok(Some(File::open(path).map_err(|source| { - RunCurateBarsError::OpenInput { - label: "qm-prices", - path: path.clone(), - source, - } - })?)), - None => Ok(None), - }, - ) -} - -#[allow(clippy::too_many_arguments)] -fn load_and_decode_from_openers( - provider_mapping_path: &Path, - listing_currencies_path: &Path, - qm_splits_path: &Path, - open_splits: FS, - eod_prices_path: &Path, - open_eod: FE, - qm_prices_path: Option<&Path>, - open_qm: FQ, -) -> Result -where - RS: io::Read, - FS: FnOnce() -> Result, - RE: io::Read, - FE: FnOnce() -> Result, - RQ: io::Read, - FQ: FnOnce() -> Result, RunCurateBarsError>, -{ - let mapping_rows = load_provider_mapping_tsv(provider_mapping_path)?; - let currencies = load_listing_currencies_tsv(listing_currencies_path)?; - - let EodMappingIndex { - eod_keys, - eod_by_listing, - eod_ranges_by_listing, - } = build_eod_mapping_index(&mapping_rows, qm_prices_path.is_some()); - - let mapping = ProviderMappingTable::from_rows(mapping_rows).map_err(|source| { - RunCurateBarsError::ProviderMapping { - path: provider_mapping_path.to_path_buf(), - source, - } - })?; - - // Stream `qmSplits` and resolve `("qm", qmSearchCode, ex_date) -> listing_id`. - let splits_stream = open_splits()?; - let LoadedQmSplits { - splits, - splits_docs_framed, - splits_bytes_read, - splits_decode, - split_rekey, - } = load_qm_splits_from_reader(splits_stream, qm_splits_path, &mapping, &eod_by_listing)?; - - // Stream `eodPrices`, dropping unmapped `"eod"` keys before buffering and interning keys. - let eod_stream = open_eod()?; - let mut eod_reader = RawBsonChunkReader::new(eod_stream); - let mut bars: Vec>> = Vec::new(); - let mut bars_unmapped_source_dropped: usize = 0; - let eod_decode = decode_eod_price_chunks( - &mut eod_reader, - |raw_bar| { - if let Some(key) = eod_keys.get(raw_bar.eod_search_code) { - bars.push(raw_bar.into_eod_daily_bar(|_, _| Arc::clone(key))); - } else { - bars_unmapped_source_dropped += 1; - } - }, - |_offset, _err| {}, - ) - .map_err(|source| RunCurateBarsError::BsonStream { - label: "eod-prices", - path: eod_prices_path.to_path_buf(), - source, - })?; - let eod_docs_framed = eod_reader.docs_framed(); - let eod_bytes_read = eod_reader.bytes_read(); - let buffered_bars = bars.len(); - let interned_key_bytes: usize = eod_keys - .iter() - .map(|k| 2 * size_of::() + k.len()) - .sum(); - let buffered_bar_bytes = - bars.capacity() * size_of::>>() + interned_key_bytes; - - // Optionally stream `qmPrices` and date-aware re-key into interned `"eod"` keys. - let mut qm_volumes: Vec>> = Vec::new(); - let mut qm_prices_present = false; - let mut qm_prices_docs_framed = 0u64; - let mut qm_prices_bytes_read = 0u64; - let mut qm_prices_decode = BsonQmPriceDecodeStats::default(); - let mut qm_rekey = QmVolumeRekeyStats::default(); - let mut qm_decode_rekey_elapsed_secs = 0.0f64; - - if let Some(qm_prices_path) = qm_prices_path { - if let Some(qm_stream) = open_qm()? { - qm_prices_present = true; - let qm_start = Instant::now(); - let mut qm_reader = RawBsonChunkReader::new(qm_stream); - qm_prices_decode = decode_qm_price_chunks( - &mut qm_reader, - |raw_price| { - let Some(listing_id) = - mapping.resolve("qm", raw_price.qm_search_code, raw_price.session_date) - else { - qm_rekey.qm_unmapped_qm += 1; - return; - }; - let mut matched_eod = 0usize; - if let Some(ranges) = eod_ranges_by_listing.get(&listing_id) { - for range in ranges { - if raw_price.session_date >= range.valid_from - && range - .valid_to - .is_none_or(|to| raw_price.session_date <= to) - { - qm_volumes.push(QmRawVolume { - key: Arc::clone(&range.key), - session_date: raw_price.session_date, - share_volume: raw_price.share_volume, - }); - matched_eod += 1; - } - } - } - if matched_eod == 0 { - qm_rekey.qm_no_eod_partner += 1; - } else { - qm_rekey.qm_attached += 1; - qm_rekey.qm_volumes_attached += matched_eod; - } - }, - |_offset, _err| {}, - ) - .map_err(|source| RunCurateBarsError::BsonStream { - label: "qm-prices", - path: qm_prices_path.to_path_buf(), - source, - })?; - qm_prices_docs_framed = qm_reader.docs_framed(); - qm_prices_bytes_read = qm_reader.bytes_read(); - qm_rekey.qm_in = qm_prices_decode.docs_in; - qm_decode_rekey_elapsed_secs = qm_start.elapsed().as_secs_f64(); - } - } - let buffered_qm_bytes = qm_volumes.capacity() * size_of::>>(); - - Ok(LoadedCurateBarsInputs { - mapping, - currencies, - splits, - bars, - qm_volumes, - eod_docs_framed, - eod_bytes_read, - eod_decode, - splits_docs_framed, - splits_bytes_read, - splits_decode, - split_rekey, - qm_prices_present, - qm_prices_docs_framed, - qm_prices_bytes_read, - qm_prices_decode, - qm_rekey, - buffered_qm_bytes, - qm_decode_rekey_elapsed_secs, - bars_unmapped_source_dropped, - buffered_bars, - buffered_bar_bytes, - }) -} - -/// Runs the end-to-end `curate-bars-1d` file-to-Parquet pipeline via [`curate_and_write_bars_1d`]. -pub fn run_curate_bars_1d( - args: &CurateBars1dArgs, -) -> Result { - if args.threads == 0 { - return Err(RunCurateBarsError::CurateWrite { - out_dir: args.out_dir.clone(), - source: CurateBarsWriteError::Parquet(ParquetBarsError::InvalidThreads), - }); - } - let start = Instant::now(); - let loaded = load_and_decode_inputs(args)?; - finish_curate_bars_1d(loaded, &args.out_dir, args.rel_tolerance, args.threads, start) -} - -/// Runs `curate-bars-1d` from arbitrary raw-BSON [`io::Read`] streams (such as -/// [`crate::RawBsonCursorReader`] backed by read-only MongoDB cursors). -#[allow(clippy::too_many_arguments)] -pub fn run_curate_bars_1d_with_readers( - provider_mapping_path: &Path, - listing_currencies_path: &Path, - qm_splits_input: (&Path, RS), - eod_prices_input: (&Path, RE), - qm_prices_input: Option<(PathBuf, RQ)>, - out_dir: &Path, - rel_tolerance: f64, - threads: usize, -) -> Result { - if threads == 0 { - return Err(RunCurateBarsError::CurateWrite { - out_dir: out_dir.to_path_buf(), - source: CurateBarsWriteError::Parquet(ParquetBarsError::InvalidThreads), - }); - } - let start = Instant::now(); - validate_out_dir(out_dir)?; - let (qm_splits_path, splits_stream) = qm_splits_input; - let (eod_prices_path, eod_stream) = eod_prices_input; - let (qm_prices_path, qm_stream) = match qm_prices_input { - Some((p, r)) => (Some(p), Some(r)), - None => (None, None), - }; - let loaded = load_and_decode_from_openers( - provider_mapping_path, - listing_currencies_path, - qm_splits_path, - || Ok(splits_stream), - eod_prices_path, - || Ok(eod_stream), - qm_prices_path.as_deref(), - || Ok(qm_stream), - )?; - finish_curate_bars_1d(loaded, out_dir, rel_tolerance, threads, start) -} - -fn finish_curate_bars_1d( - loaded: LoadedCurateBarsInputs, - out_dir: &Path, - rel_tolerance: f64, - threads: usize, - start: Instant, -) -> Result { - let write_report = curate_and_write_bars_1d( - out_dir, - loaded.bars, - &loaded.splits, - loaded.qm_volumes, - rel_tolerance, - &loaded.mapping, - "eod", - &loaded.currencies, - Bars1dWriteOptions { - threads, - ..Bars1dWriteOptions::default() - }, - ) - .map_err(|source| RunCurateBarsError::CurateWrite { - out_dir: out_dir.to_path_buf(), - source, - })?; - - Ok(CurateBars1dRunReport { - eod_docs_framed: loaded.eod_docs_framed, - eod_bytes_read: loaded.eod_bytes_read, - eod_decode: loaded.eod_decode, - splits_docs_framed: loaded.splits_docs_framed, - splits_bytes_read: loaded.splits_bytes_read, - splits_decode: loaded.splits_decode, - split_rekey: loaded.split_rekey, - qm_prices_present: loaded.qm_prices_present, - qm_prices_docs_framed: loaded.qm_prices_docs_framed, - qm_prices_bytes_read: loaded.qm_prices_bytes_read, - qm_prices_decode: loaded.qm_prices_decode, - qm_rekey: loaded.qm_rekey, - buffered_qm_bytes: loaded.buffered_qm_bytes, - bars_unmapped_source_dropped: loaded.bars_unmapped_source_dropped, - buffered_bars: loaded.buffered_bars, - buffered_bar_bytes: loaded.buffered_bar_bytes, - curate_stats: write_report.curate_stats, - write_stats: write_report.write_stats, - mismatch_samples: write_report.mismatch_samples, - threads, - elapsed_secs: start.elapsed().as_secs_f64(), - }) -} - -/// Stage-timed variant of [`run_curate_bars_1d`] sharing [`load_and_decode_inputs`] and calling -/// [`curate_bars_1d`] + [`write_bars_1d_dataset`] separately. -#[allow(dead_code)] -pub(crate) fn run_curate_bars_1d_timed( - args: &CurateBars1dArgs, -) -> Result { - if args.threads == 0 { - return Err(RunCurateBarsError::CurateWrite { - out_dir: args.out_dir.clone(), - source: CurateBarsWriteError::Parquet(ParquetBarsError::InvalidThreads), - }); - } - let total_start = Instant::now(); - - let decode_start = Instant::now(); - let loaded = load_and_decode_inputs(args)?; - let decode_elapsed_secs = decode_start.elapsed().as_secs_f64(); - - let curate_start = Instant::now(); - let curated = curate_bars_1d( - loaded.bars, - &loaded.splits, - loaded.qm_volumes, - args.rel_tolerance, - &loaded.mapping, - "eod", - &loaded.currencies, - ) - .map_err(|source| RunCurateBarsError::CurateWrite { - out_dir: args.out_dir.clone(), - source: CurateBarsWriteError::Curate(source), - })?; - let curate_elapsed_secs = curate_start.elapsed().as_secs_f64(); - - let write_start = Instant::now(); - let write_stats = write_bars_1d_dataset( - &args.out_dir, - curated.rows, - Bars1dWriteOptions { - threads: args.threads, - ..Bars1dWriteOptions::default() - }, - ) - .map_err(|source| RunCurateBarsError::CurateWrite { - out_dir: args.out_dir.clone(), - source: CurateBarsWriteError::Parquet(source), - })?; - let write_elapsed_secs = write_start.elapsed().as_secs_f64(); - - let report = CurateBars1dRunReport { - eod_docs_framed: loaded.eod_docs_framed, - eod_bytes_read: loaded.eod_bytes_read, - eod_decode: loaded.eod_decode, - splits_docs_framed: loaded.splits_docs_framed, - splits_bytes_read: loaded.splits_bytes_read, - splits_decode: loaded.splits_decode, - split_rekey: loaded.split_rekey, - qm_prices_present: loaded.qm_prices_present, - qm_prices_docs_framed: loaded.qm_prices_docs_framed, - qm_prices_bytes_read: loaded.qm_prices_bytes_read, - qm_prices_decode: loaded.qm_prices_decode, - qm_rekey: loaded.qm_rekey, - buffered_qm_bytes: loaded.buffered_qm_bytes, - bars_unmapped_source_dropped: loaded.bars_unmapped_source_dropped, - buffered_bars: loaded.buffered_bars, - buffered_bar_bytes: loaded.buffered_bar_bytes, - curate_stats: curated.stats, - write_stats, - mismatch_samples: curated.mismatch_samples, - threads: args.threads, - elapsed_secs: total_start.elapsed().as_secs_f64(), - }; - - Ok(CurateBars1dTimedRun { - report, - decode_elapsed_secs, - qm_decode_rekey_elapsed_secs: loaded.qm_decode_rekey_elapsed_secs, - curate_elapsed_secs, - write_elapsed_secs, - }) -} - -/// Stage-timed variant for `bench-curate-bars-cmd`: decodes and curates once, then times -/// `write_bars_1d_dataset` on the exact same curated rows at `threads = 1` (into `seq_out_dir`) -/// and `threads = par_threads` (into `par_out_dir`). -pub(crate) fn run_curate_bars_1d_timed_compare( - args: &CurateBars1dArgs, - seq_out_dir: &Path, - par_out_dir: &Path, - par_threads: usize, -) -> Result { - if par_threads == 0 { - return Err(RunCurateBarsError::CurateWrite { - out_dir: par_out_dir.to_path_buf(), - source: CurateBarsWriteError::Parquet(ParquetBarsError::InvalidThreads), - }); - } - validate_out_dir(seq_out_dir)?; - validate_out_dir(par_out_dir)?; - let total_start = Instant::now(); - - let decode_start = Instant::now(); - let loaded = load_and_decode_inputs(args)?; - let decode_elapsed_secs = decode_start.elapsed().as_secs_f64(); - - let curate_start = Instant::now(); - let curated = curate_bars_1d( - loaded.bars, - &loaded.splits, - loaded.qm_volumes, - args.rel_tolerance, - &loaded.mapping, - "eod", - &loaded.currencies, - ) - .map_err(|source| RunCurateBarsError::CurateWrite { - out_dir: par_out_dir.to_path_buf(), - source: CurateBarsWriteError::Curate(source), - })?; - let curate_elapsed_secs = curate_start.elapsed().as_secs_f64(); - - let write_seq_start = Instant::now(); - let write_stats_seq = write_bars_1d_dataset( - seq_out_dir, - &curated.rows, - Bars1dWriteOptions { - threads: 1, - ..Bars1dWriteOptions::default() - }, - ) - .map_err(|source| RunCurateBarsError::CurateWrite { - out_dir: seq_out_dir.to_path_buf(), - source: CurateBarsWriteError::Parquet(source), - })?; - let write_seq_elapsed_secs = write_seq_start.elapsed().as_secs_f64(); - - let write_par_start = Instant::now(); - let write_stats_par = write_bars_1d_dataset( - par_out_dir, - &curated.rows, - Bars1dWriteOptions { - threads: par_threads, - ..Bars1dWriteOptions::default() - }, - ) - .map_err(|source| RunCurateBarsError::CurateWrite { - out_dir: par_out_dir.to_path_buf(), - source: CurateBarsWriteError::Parquet(source), - })?; - let write_par_elapsed_secs = write_par_start.elapsed().as_secs_f64(); - - assert_eq!( - write_stats_seq, write_stats_par, - "sequential and parallel write_bars_1d_dataset stats must match identically" - ); - - let report = CurateBars1dRunReport { - eod_docs_framed: loaded.eod_docs_framed, - eod_bytes_read: loaded.eod_bytes_read, - eod_decode: loaded.eod_decode, - splits_docs_framed: loaded.splits_docs_framed, - splits_bytes_read: loaded.splits_bytes_read, - splits_decode: loaded.splits_decode, - split_rekey: loaded.split_rekey, - qm_prices_present: loaded.qm_prices_present, - qm_prices_docs_framed: loaded.qm_prices_docs_framed, - qm_prices_bytes_read: loaded.qm_prices_bytes_read, - qm_prices_decode: loaded.qm_prices_decode, - qm_rekey: loaded.qm_rekey, - buffered_qm_bytes: loaded.buffered_qm_bytes, - bars_unmapped_source_dropped: loaded.bars_unmapped_source_dropped, - buffered_bars: loaded.buffered_bars, - buffered_bar_bytes: loaded.buffered_bar_bytes, - curate_stats: curated.stats, - write_stats: write_stats_par, - mismatch_samples: curated.mismatch_samples, - threads: par_threads, - elapsed_secs: total_start.elapsed().as_secs_f64(), - }; - - Ok(CurateBars1dTimedCompareRun { - report, - decode_elapsed_secs, - qm_decode_rekey_elapsed_secs: loaded.qm_decode_rekey_elapsed_secs, - curate_elapsed_secs, - write_seq_elapsed_secs, - write_par_elapsed_secs, - write_stats_seq, - }) -} - -/// Formats [`CurateBars1dRunReport`] into a deterministic machine-readable `key=value` summary. -/// -/// Only the final `timing:` line contains wall-clock time (`elapsed_secs`). -pub fn format_curate_bars_report(report: &CurateBars1dRunReport) -> String { - use std::fmt::Write as _; - - let years = if report.write_stats.rows_by_year.is_empty() { - "none".to_string() - } else { - report - .write_stats - .rows_by_year - .iter() - .map(|(year, count)| format!("{year:04}={count}")) - .collect::>() - .join(" ") - }; - - let mut out = format!( - "curate-etl curate-bars-1d\n\ - \x20 eod_bson: docs_framed={} bytes_read={} docs_in={} decoded={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={})\n\ - \x20 splits_bson: docs_framed={} bytes_read={} docs_in={} decoded={} noop_ratio_one={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={})\n\ - \x20 splits: splits_in={} splits_applied={} splits_collision_collapsed={} splits_unmapped_qm={} splits_no_eod_partner={} splits_noop_dropped={} split_events_attached={}\n\ - \x20 filter: bars_unmapped_source_dropped={} buffered_bars={} buffered_bar_bytes={}\n\ - \x20 builder: bars_in={} rows_out={} keys_out={} invalid_ohlc={} inconsistent_ohlc={} invalid_vol={} dup_collapsed={} dup_conflict_dropped={}\n\ - \x20 curate: rows_in={} rows_out={} listings_out={} dropped_unmapped={} dropped_missing_currency={} dropped_ts_out_of_range={} listing_collision_collapsed={} listing_collision_dropped={}\n\ - \x20 write: rows_written={} files_written={} row_groups_written={} bytes_written={}\n\ - \x20 years: {years}\n", - report.eod_docs_framed, - report.eod_bytes_read, - report.eod_decode.docs_in, - report.eod_decode.decoded, - report.eod_decode.rejected_total(), - report.eod_decode.rejected_missing_field, - report.eod_decode.rejected_empty_field, - report.eod_decode.rejected_wrong_type, - report.eod_decode.rejected_malformed_date, - report.eod_decode.rejected_invalid_number, - report.eod_decode.rejected_corrupt_document, - report.splits_docs_framed, - report.splits_bytes_read, - report.splits_decode.docs_in, - report.splits_decode.decoded, - report.splits_decode.split_noop_ratio_one, - report.splits_decode.rejected_total(), - report.splits_decode.rejected_missing_field, - report.splits_decode.rejected_empty_field, - report.splits_decode.rejected_wrong_type, - report.splits_decode.rejected_malformed_date, - report.splits_decode.rejected_invalid_number, - report.splits_decode.rejected_corrupt_document, - report.split_rekey.splits_in, - report.split_rekey.splits_applied, - report.split_rekey.splits_collision_collapsed, - report.split_rekey.splits_unmapped_qm, - report.split_rekey.splits_no_eod_partner, - report.split_rekey.splits_noop_dropped, - report.split_rekey.split_events_attached, - report.bars_unmapped_source_dropped, - report.buffered_bars, - report.buffered_bar_bytes, - report.curate_stats.builder.bars_in, - report.curate_stats.builder.rows_out, - report.curate_stats.builder.keys_out, - report.curate_stats.builder.dropped_invalid_ohlc, - report.curate_stats.builder.dropped_inconsistent_ohlc, - report.curate_stats.builder.dropped_invalid_volume, - report.curate_stats.builder.duplicate_collapsed, - report.curate_stats.builder.duplicate_conflict_dropped, - report.curate_stats.rows_in, - report.curate_stats.rows_out, - report.curate_stats.listings_out, - report.curate_stats.dropped_unmapped, - report.curate_stats.dropped_missing_currency, - report.curate_stats.dropped_ts_out_of_range, - report.curate_stats.listing_collision_collapsed, - report.curate_stats.listing_collision_dropped, - report.write_stats.rows_written, - report.write_stats.files_written, - report.write_stats.row_groups_written, - report.write_stats.bytes_written, - ); - - if report.qm_prices_present { - let b = &report.curate_stats.builder; - let _ = writeln!( - out, - " qm_bson: docs_framed={} bytes_read={} docs_in={} decoded={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} corrupt={})", - report.qm_prices_docs_framed, - report.qm_prices_bytes_read, - report.qm_prices_decode.docs_in, - report.qm_prices_decode.decoded, - report.qm_prices_decode.rejected_total(), - report.qm_prices_decode.rejected_missing_field, - report.qm_prices_decode.rejected_empty_field, - report.qm_prices_decode.rejected_wrong_type, - report.qm_prices_decode.rejected_malformed_date, - report.qm_prices_decode.rejected_corrupt_document, - ); - let _ = writeln!( - out, - " qm_rekey: qm_in={} qm_attached={} qm_unmapped_qm={} qm_no_eod_partner={} qm_volumes_attached={} buffered_qm_bytes={}", - report.qm_rekey.qm_in, - report.qm_rekey.qm_attached, - report.qm_rekey.qm_unmapped_qm, - report.qm_rekey.qm_no_eod_partner, - report.qm_rekey.qm_volumes_attached, - report.buffered_qm_bytes, - ); - let _ = writeln!( - out, - " qm_check: qm_rows_in={} qm_unique_partners={} qm_invalid_vol={} qm_dup_collapsed={} qm_dup_conflict={} volume_checked={} volume_within_tolerance={} volume_mismatched={} volume_unchecked={} max_rel_diff={:.6} mismatch_samples={}", - b.qm_rows_in, - b.qm_unique_partners, - b.qm_invalid_volume_dropped, - b.qm_duplicate_collapsed, - b.qm_duplicate_conflict_dropped, - b.volume_checked, - b.volume_within_tolerance, - b.volume_mismatched, - b.volume_unchecked, - b.max_rel_diff, - report.mismatch_samples.len(), - ); - for sample in &report.mismatch_samples { - let (y, m, d) = epoch_days_to_ymd(sample.session_date); - let _ = writeln!( - out, - " qm_mismatch: key={} session_date={y:04}-{m:02}-{d:02} volume={:.6} share_volume={:.6} rel={:.6}", - sample.key, sample.volume, sample.share_volume, sample.rel, - ); - } - } else { - out.push_str(" qm_check: qm_prices=absent\n"); - } - - let _ = writeln!(out, " config: threads={}", report.threads); - let _ = write!(out, " timing: elapsed_secs={:.6}", report.elapsed_secs); - out -} - -#[cfg(test)] -#[path = "run_curate_bars_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/run_curate_bars_1m.rs b/tools/curate-etl/src/run_curate_bars_1m.rs deleted file mode 100644 index 86c6c8e5..00000000 --- a/tools/curate-etl/src/run_curate_bars_1m.rs +++ /dev/null @@ -1,892 +0,0 @@ -//! Bounded-memory file-to-file `bars_1m` runner (`M2.3k`). -//! -//! Streams a concatenated raw BSON `eodIntraday1M` dump alongside a `qmSplits` BSON dump and a -//! headerless 5-column `provider_mapping.tsv` into per-shard QuestDB ILP v2 files -//! (`/bars_1m.shard-.ilp`) via listing-keyed [`crate::curate_bars_1m`] curation. -//! -//! # Bounded-Memory Chunking -//! - Drives [`RawBsonChunkReader::with_options`], [`RawBsonChunkReader::next_chunk`], and -//! [`decode_eod_intraday_buffer`] directly—the exact reader and buffer decoder wrapped by -//! `crate::bson_stream::decode_eod_intraday_chunks`, whose callback API hides chunk boundaries. -//! - Each framed chunk is decoded into a chunk-local `Vec>>` (reusing -//! interned `"eod"` keys from `provider_mapping.tsv` and retaining unknown codes so -//! `curate_bars_1m` counts them in `dropped_unmapped`) and curated per chunk against one shared -//! [`IlpShardedWriter`] (resolving `listing_id` on each bar's Eastern Time `session_date` before -//! applying listing-keyed splits). -//! - [`IlpShardedWriter::finish`] is called exactly once after clean EOF. -//! - Peak memory is bounded by the reference tables (`provider_mapping` + `SplitTable`), the -//! current BSON chunk (`BsonStreamOptions::chunk_capacity_bytes`, growing only for a single -//! document up to `max_doc_bytes`), that chunk's curation buffers, and one ILP batch buffer per -//! shard—independent of the total `eodIntraday1M` input size. -//! -//! # Cross-Chunk Semantics & Reporting -//! - Collision collapse/drop in `curate_bars_1m` and row ordering apply **per chunk**: output is -//! sorted by `(listing_id, ts)` within each chunk, and the same `(listing_id, ts)` appearing in -//! two different chunks is emitted twice (with zero within-chunk collapse between them) and -//! relies on QuestDB `DEDUP UPSERT KEYS(ts, listing_id)`. -//! - `CurateBars1mRunReport::curate_stats` sums every field of [`CurateBars1mStats`] and its -//! nested [`Bars1mStats`] across chunks. In particular, `curate_stats.listings_out` and -//! `curate_stats.builder.keys_out` are **sums of per-chunk counts**, not global distinct counts. -//! - `mapping_source` must be `"eod"` because the shared `qmSplits` loader -//! (`run_curate_bars::decode_and_compact_qm_splits_from_reader`) filters to listings with `"eod"` -//! partners. Split events retain permanent `listing_id: i32` identity (`SplitTable`), and -//! each bar's listing is resolved via `provider_mapping` on its Eastern Time `session_date` -//! **before** choosing the split factor so reused tickers cannot leak splits across listings. -//! - `known_at_micros` is a caller-supplied run timestamp written verbatim to every ILP row's -//! `known_at` column; it supplies no evidence of earlier market availability. -//! -//! # File Publication & Fail-Closed Guarantees -//! - Preflight scans `out_dir` for **any** pre-existing `bars_1m.shard-.ilp` file -//! (regardless of the requested `shard_count`) and fails closed before staging so stale shards -//! from a prior larger-shard-count run cannot survive alongside a new export. -//! - Each shard writes into an exclusively created staging file in `out_dir` -//! (`.bars_1m.shard-..tmp`), flushes and `sync_all`s on `finish`, and publishes to -//! `bars_1m.shard-.ilp` via same-directory `hard_link` followed by removing the staged name -//! (preserving no-overwrite semantics even if a final file appears after preflight). -//! - Any error (validation, missing/malformed inputs, fatal BSON framing/I/O, ILP write/flush, or -//! publication collision) rolls back only final files created by this run, removes this run's -//! staging files, and leaves pre-existing files untouched. Per-document semantic decode errors -//! stay counted-and-skipped in [`BsonEodIntradayDecodeStats`]. - -use std::collections::{HashMap, HashSet}; -use std::error::Error; -use std::ffi::OsStr; -use std::fmt; -use std::fs::{self, File, OpenOptions}; -use std::io::{self, BufWriter, Write}; -use std::path::{Path, PathBuf}; -use std::sync::Arc; -use std::time::Instant; - -use crate::bars_1m::{Bars1mStats, EodIntradayBar}; -use crate::bson_eod_intraday::{decode_eod_intraday_buffer, BsonEodIntradayDecodeStats}; -use crate::bson_qm_actions::BsonQmActionDecodeStats; -use crate::bson_stream::{BsonStreamError, BsonStreamOptions, RawBsonChunkReader}; -use crate::curate_bars_1m::{ - curate_and_write_bars_1m_by_listing, CurateBars1mStats, CurateBars1mWriteError, -}; -use crate::ilp::{ - IlpShardedWriter, IlpWriteStats, IlpWriterError, IlpWriterOptions, TABLE_BARS_1M, -}; -use crate::parquet_bars::RollbackFailure; -use crate::parquet_publish::{ - next_run_id, rollback_published, PublishedPartition, StagingFileGuard, FILE_BUF_CAPACITY_BYTES, -}; -use crate::provider_mapping::ProviderMappingTable; -use crate::run_curate_bars::{ - build_eod_mapping_index, decode_and_compact_qm_splits_from_reader, load_provider_mapping_tsv, - DecodedQmSplits, EodMappingIndex, RunCurateBarsError, SplitRekeyStats, -}; -use crate::split::SplitTable; - -/// Required `provider_mapping` source namespace for `eodIntraday1M` bars. -pub const DEFAULT_BARS_1M_MAPPING_SOURCE: &str = "eod"; - -/// Arguments for [`run_curate_bars_1m`] and [`run_curate_bars_1m_with_readers`]. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct CurateBars1mArgs { - pub intraday_path: PathBuf, - pub splits_path: PathBuf, - pub provider_mapping_path: PathBuf, - pub out_dir: PathBuf, - pub mapping_source: String, - pub shard_count: usize, - pub known_at_micros: i64, - pub stream_options: BsonStreamOptions, - pub ilp_options: IlpWriterOptions, -} - -/// Full run report produced by [`run_curate_bars_1m`] and [`run_curate_bars_1m_with_readers`]. -/// -/// Conservation invariants: -/// - `intraday_docs_framed as usize == intraday_decode.docs_seen` -/// - `intraday_decode.docs_seen == intraday_decode.rows_decoded + intraday_decode.rejected_total()` -/// - `intraday_decode.rows_decoded == curate_stats.builder.bars_in` -/// - `curate_stats.rows_in == curate_stats.builder.rows_out` -/// - `curate_stats.rows_in == curate_stats.rows_out + curate_stats.dropped_unmapped + curate_stats.listing_collision_collapsed + curate_stats.listing_collision_dropped` -/// - `curate_stats.pre_rows_out + curate_stats.rth_rows_out + curate_stats.post_rows_out == curate_stats.rows_out` -/// - `rows_written == curate_stats.rows_out == ilp_stats.rows == ilp_stats.per_shard_rows.iter().sum::()` -/// -/// Note: `curate_stats.listings_out` and `curate_stats.builder.keys_out` are summed across chunks -/// (not global distinct counts). -#[derive(Debug, Clone, PartialEq)] -pub struct CurateBars1mRunReport { - pub intraday_docs_framed: u64, - pub intraday_bytes_read: u64, - pub intraday_decode: BsonEodIntradayDecodeStats, - pub splits_docs_framed: u64, - pub splits_bytes_read: u64, - pub splits_decode: BsonQmActionDecodeStats, - pub split_rekey: SplitRekeyStats, - pub chunks: usize, - pub max_rows_per_chunk: usize, - pub curate_stats: CurateBars1mStats, - pub rows_written: usize, - pub ilp_stats: IlpWriteStats, - pub shard_count: usize, - pub elapsed_secs: f64, -} - -/// Typed errors returned by [`run_curate_bars_1m`] and [`run_curate_bars_1m_with_readers`]. -#[derive(Debug)] -pub enum RunCurateBars1mError { - /// `mapping_source` was empty or contained only whitespace. - EmptyMappingSource, - /// `mapping_source` was non-blank but not `"eod"`. - UnsupportedMappingSource { mapping_source: String }, - /// `shard_count` was `0`. - ZeroShardCount, - /// Caller-supplied `IlpShardedWriter` shard count did not match `args.shard_count`. - ShardCountMismatch { expected: usize, actual: usize }, - /// `out_dir` exists and is not a directory. - InvalidOutDir { path: PathBuf, detail: String }, - /// A final shard output file (`bars_1m.shard-.ilp`) already existed. - OutputFileExists { path: PathBuf }, - /// Failed to open an input dump file. - OpenInput { - label: &'static str, - path: PathBuf, - source: io::Error, - }, - /// Failed to load `provider_mapping.tsv` or `qmSplits` via the shared reference loader. - LoadReference(RunCurateBarsError), - /// Fatal BSON framing, option validation, or I/O error while reading `eodIntraday1M`. - BsonStream { - label: &'static str, - path: PathBuf, - source: BsonStreamError, - }, - /// Curation or per-row ILP write error inside the per-chunk `bars_1m` curation stage. - CurateWrite(CurateBars1mWriteError), - /// ILP writer initialization or final flush error. - Ilp(IlpWriterError), - /// Filesystem I/O error while creating, syncing, linking, or cleaning up shard files. - Io { path: PathBuf, source: io::Error }, - /// Publication failed and rolling back one or more already-published shards also failed. - RollbackFailed { - cause: Box, - failures: Vec, - }, -} - -impl fmt::Display for RunCurateBars1mError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::EmptyMappingSource => write!(f, "mapping_source must not be empty or blank"), - Self::UnsupportedMappingSource { mapping_source } => write!( - f, - "unsupported mapping_source '{mapping_source}': only '{DEFAULT_BARS_1M_MAPPING_SOURCE}' is supported" - ), - Self::ZeroShardCount => write!(f, "shard_count must be >= 1"), - Self::ShardCountMismatch { expected, actual } => write!( - f, - "ILP writer shard count mismatch: expected {expected}, got {actual}" - ), - Self::InvalidOutDir { path, detail } => { - write!(f, "invalid out_dir '{}': {detail}", path.display()) - } - Self::OutputFileExists { path } => write!( - f, - "refusing to overwrite existing output file '{}'", - path.display() - ), - Self::OpenInput { - label, - path, - source, - } => write!(f, "failed to open {label} '{}': {source}", path.display()), - Self::LoadReference(err) => write!(f, "failed loading reference inputs: {err}"), - Self::BsonStream { - label, - path, - source, - } => write!(f, "failed reading {label} '{}': {source}", path.display()), - Self::CurateWrite(err) => write!(f, "{err}"), - Self::Ilp(err) => write!(f, "bars_1m ILP writer failed: {err}"), - Self::Io { path, source } => { - write!(f, "I/O error on '{}': {source}", path.display()) - } - Self::RollbackFailed { cause, failures } => { - write!(f, "{cause}; rollback also failed for: ")?; - for (i, failure) in failures.iter().enumerate() { - if i > 0 { - write!(f, ", ")?; - } - write!(f, "{failure}")?; - } - Ok(()) - } - } - } -} - -impl Error for RunCurateBars1mError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::OpenInput { source, .. } | Self::Io { source, .. } => Some(source), - Self::LoadReference(err) => Some(err), - Self::BsonStream { source, .. } => Some(source), - Self::CurateWrite(err) => Some(err), - Self::Ilp(err) => Some(err), - Self::RollbackFailed { cause, .. } => Some(cause.as_ref()), - Self::EmptyMappingSource - | Self::UnsupportedMappingSource { .. } - | Self::ZeroShardCount - | Self::ShardCountMismatch { .. } - | Self::InvalidOutDir { .. } - | Self::OutputFileExists { .. } => None, - } - } -} - -struct LoadedReferenceInputs { - mapping: ProviderMappingTable, - eod_keys: HashSet>, - splits: SplitTable, - splits_docs_framed: u64, - splits_bytes_read: u64, - splits_decode: BsonQmActionDecodeStats, - split_rekey: SplitRekeyStats, -} - -fn validate_common_args(args: &CurateBars1mArgs) -> Result<(), RunCurateBars1mError> { - if args.mapping_source.trim().is_empty() { - return Err(RunCurateBars1mError::EmptyMappingSource); - } - if args.mapping_source != DEFAULT_BARS_1M_MAPPING_SOURCE { - return Err(RunCurateBars1mError::UnsupportedMappingSource { - mapping_source: args.mapping_source.clone(), - }); - } - if args.shard_count == 0 { - return Err(RunCurateBars1mError::ZeroShardCount); - } - args.stream_options - .validate() - .map_err(|source| RunCurateBars1mError::BsonStream { - label: "eod-intraday", - path: args.intraday_path.clone(), - source, - })?; - Ok(()) -} - -pub(crate) enum ShardPublishError { - InvalidOutDir { path: PathBuf, detail: String }, - OutputFileExists { path: PathBuf }, - Io { path: PathBuf, source: io::Error }, - RollbackFailed { - cause: Box, - failures: Vec, - }, -} - -impl From for RunCurateBars1mError { - fn from(err: ShardPublishError) -> Self { - match err { - ShardPublishError::InvalidOutDir { path, detail } => { - Self::InvalidOutDir { path, detail } - } - ShardPublishError::OutputFileExists { path } => Self::OutputFileExists { path }, - ShardPublishError::Io { path, source } => Self::Io { path, source }, - ShardPublishError::RollbackFailed { cause, failures } => Self::RollbackFailed { - cause: Box::new((*cause).into()), - failures, - }, - } - } -} - -fn validate_file_mode_args(args: &CurateBars1mArgs) -> Result<(), RunCurateBars1mError> { - validate_common_args(args)?; - if args.ilp_options.max_batch_bytes == 0 { - return Err(RunCurateBars1mError::Ilp(IlpWriterError::ZeroMaxBatchBytes)); - } - if args.ilp_options.max_batch_rows == 0 { - return Err(RunCurateBars1mError::Ilp(IlpWriterError::ZeroMaxBatchRows)); - } - preflight_shard_out_dir(&args.out_dir, TABLE_BARS_1M)?; - Ok(()) -} - -pub(crate) fn preflight_shard_out_dir( - out_dir: &Path, - table: &str, -) -> Result<(), ShardPublishError> { - if out_dir.exists() { - if !out_dir.is_dir() { - return Err(ShardPublishError::InvalidOutDir { - path: out_dir.to_path_buf(), - detail: "path exists and is not a directory".to_string(), - }); - } - let entries = fs::read_dir(out_dir).map_err(|source| ShardPublishError::Io { - path: out_dir.to_path_buf(), - source, - })?; - let mut existing_shards: Vec = Vec::new(); - for entry in entries { - let entry = entry.map_err(|source| ShardPublishError::Io { - path: out_dir.to_path_buf(), - source, - })?; - if is_final_shard_file_name_for_table(table, &entry.file_name()) { - existing_shards.push(entry.path()); - } - } - if !existing_shards.is_empty() { - existing_shards.sort(); - return Err(ShardPublishError::OutputFileExists { - path: existing_shards.remove(0), - }); - } - } - Ok(()) -} - -#[inline] -pub(crate) fn is_final_shard_file_name_for_table(table: &str, name: &OsStr) -> bool { - let Some(s) = name.to_str() else { - return false; - }; - let Some(after_table) = s.strip_prefix(table) else { - return false; - }; - let Some(rest) = after_table.strip_prefix(".shard-") else { - return false; - }; - let Some(digits) = rest.strip_suffix(".ilp") else { - return false; - }; - !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit()) -} - -#[inline] -pub(crate) fn final_shard_path_for_table( - out_dir: &Path, - table: &str, - shard_idx: usize, -) -> PathBuf { - out_dir.join(format!("{table}.shard-{shard_idx:02}.ilp")) -} - -fn load_reference_inputs( - provider_mapping_path: &Path, - splits_path: &Path, - splits_reader: RS, -) -> Result { - let mapping_rows = - load_provider_mapping_tsv(provider_mapping_path).map_err(RunCurateBars1mError::LoadReference)?; - let EodMappingIndex { - eod_keys, - eod_by_listing, - .. - } = build_eod_mapping_index(&mapping_rows, false); - - let mapping = ProviderMappingTable::from_rows(mapping_rows).map_err(|source| { - RunCurateBars1mError::LoadReference(RunCurateBarsError::ProviderMapping { - path: provider_mapping_path.to_path_buf(), - source, - }) - })?; - - let DecodedQmSplits { - compacted_splits, - splits_docs_framed, - splits_bytes_read, - splits_decode, - mut split_rekey, - } = decode_and_compact_qm_splits_from_reader( - splits_reader, - splits_path, - &mapping, - &eod_by_listing, - ) - .map_err(RunCurateBars1mError::LoadReference)?; - - split_rekey.splits_applied = compacted_splits.len(); - split_rekey.split_events_attached = compacted_splits.len(); - - let splits = SplitTable::::from_events(compacted_splits).map_err(|source| { - RunCurateBars1mError::LoadReference(RunCurateBarsError::SplitTable { - path: splits_path.to_path_buf(), - source, - }) - })?; - - Ok(LoadedReferenceInputs { - mapping, - eod_keys, - splits, - splits_docs_framed, - splits_bytes_read, - splits_decode, - split_rekey, - }) -} - -#[inline] -fn add_bars_1m_stats(total: &mut Bars1mStats, chunk: &Bars1mStats) { - total.bars_in += chunk.bars_in; - total.rows_out += chunk.rows_out; - total.keys_out += chunk.keys_out; - total.pre_rows_out += chunk.pre_rows_out; - total.rth_rows_out += chunk.rth_rows_out; - total.post_rows_out += chunk.post_rows_out; - total.dropped_invalid_ohlc += chunk.dropped_invalid_ohlc; - total.dropped_inconsistent_ohlc += chunk.dropped_inconsistent_ohlc; - total.dropped_invalid_volume += chunk.dropped_invalid_volume; - total.dropped_ts_out_of_range += chunk.dropped_ts_out_of_range; - total.duplicate_collapsed += chunk.duplicate_collapsed; - total.duplicate_conflict_dropped += chunk.duplicate_conflict_dropped; -} - -#[inline] -pub(crate) fn add_curate_bars_1m_stats(total: &mut CurateBars1mStats, chunk: &CurateBars1mStats) { - add_bars_1m_stats(&mut total.builder, &chunk.builder); - total.rows_in += chunk.rows_in; - total.rows_out += chunk.rows_out; - total.listings_out += chunk.listings_out; - total.pre_rows_out += chunk.pre_rows_out; - total.rth_rows_out += chunk.rth_rows_out; - total.post_rows_out += chunk.post_rows_out; - total.dropped_unmapped += chunk.dropped_unmapped; - total.listing_collision_collapsed += chunk.listing_collision_collapsed; - total.listing_collision_dropped += chunk.listing_collision_dropped; -} - -fn stream_intraday_chunks_to_writer( - args: &CurateBars1mArgs, - reference: LoadedReferenceInputs, - intraday: RI, - mut writer: IlpShardedWriter, - start: Instant, -) -> Result -where - RI: io::Read, - W: Write + Send, -{ - let mut reader = RawBsonChunkReader::with_options(intraday, args.stream_options).map_err( - |source| RunCurateBars1mError::BsonStream { - label: "eod-intraday", - path: args.intraday_path.clone(), - source, - }, - )?; - - let mut intraday_decode = BsonEodIntradayDecodeStats::default(); - let mut curate_stats = CurateBars1mStats::default(); - let mut chunks: usize = 0; - let mut max_rows_per_chunk: usize = 0; - let mut rows_written: usize = 0; - - // Reusable per-chunk buffers; cleared before each chunk so peak RAM stays bounded by chunk size. - let mut chunk_bars: Vec>> = Vec::new(); - let mut unknown_keys: HashMap> = HashMap::new(); - - while let Some(chunk) = - reader - .next_chunk() - .map_err(|source| RunCurateBars1mError::BsonStream { - label: "eod-intraday", - path: args.intraday_path.clone(), - source, - })? - { - chunk_bars.clear(); - unknown_keys.clear(); - - let chunk_decode = decode_eod_intraday_buffer( - chunk.bytes, - |raw| { - let key = if let Some(existing) = reference.eod_keys.get(raw.eod_search_code) { - Arc::clone(existing) - } else if let Some(existing) = unknown_keys.get(raw.eod_search_code) { - Arc::clone(existing) - } else { - let arc: Arc = Arc::from(raw.eod_search_code); - unknown_keys.insert(raw.eod_search_code.to_owned(), Arc::clone(&arc)); - arc - }; - chunk_bars.push(raw.into_eod_intraday_bar(|_, _| key)); - }, - |_local_offset, _err| {}, - ); - intraday_decode += chunk_decode; - - chunks += 1; - let chunk_len = chunk_bars.len(); - if chunk_len > max_rows_per_chunk { - max_rows_per_chunk = chunk_len; - } - - let write_report = curate_and_write_bars_1m_by_listing( - chunk_bars.drain(..), - &reference.splits, - &reference.mapping, - &args.mapping_source, - &mut writer, - args.known_at_micros, - ) - .map_err(RunCurateBars1mError::CurateWrite)?; - - add_curate_bars_1m_stats(&mut curate_stats, &write_report.curate_stats); - rows_written += write_report.rows_written; - } - - let intraday_docs_framed = reader.docs_framed(); - let intraday_bytes_read = reader.bytes_read(); - let ilp_stats = writer.finish().map_err(RunCurateBars1mError::Ilp)?; - - Ok(CurateBars1mRunReport { - intraday_docs_framed, - intraday_bytes_read, - intraday_decode, - splits_docs_framed: reference.splits_docs_framed, - splits_bytes_read: reference.splits_bytes_read, - splits_decode: reference.splits_decode, - split_rekey: reference.split_rekey, - chunks, - max_rows_per_chunk, - curate_stats, - rows_written, - ilp_stats, - shard_count: args.shard_count, - elapsed_secs: start.elapsed().as_secs_f64(), - }) -} - -/// Runs the bounded-memory `bars_1m` curation pipeline from arbitrary [`io::Read`] streams into a -/// caller-owned [`IlpShardedWriter`]. -/// -/// Validates `args`, loads `provider_mapping.tsv` from `args.provider_mapping_path` and `qmSplits` -/// from `splits`, streams `intraday` through [`RawBsonChunkReader::with_options`] + -/// [`decode_eod_intraday_buffer`] curating and writing once per chunk with listing-keyed splits, -/// and calls [`IlpShardedWriter::finish`] exactly once after EOF. -pub fn run_curate_bars_1m_with_readers( - args: &CurateBars1mArgs, - intraday: RI, - splits: RS, - writer: IlpShardedWriter, -) -> Result -where - RI: io::Read, - RS: io::Read, - W: Write + Send, -{ - let start = Instant::now(); - validate_common_args(args)?; - if writer.shard_count() != args.shard_count { - return Err(RunCurateBars1mError::ShardCountMismatch { - expected: args.shard_count, - actual: writer.shard_count(), - }); - } - - let reference = load_reference_inputs(&args.provider_mapping_path, &args.splits_path, splits)?; - stream_intraday_chunks_to_writer(args, reference, intraday, writer, start) -} - -/// Buffered file sink that flushes and calls `File::sync_all()` on [`Write::flush`] (invoked once -/// per shard by [`IlpShardedWriter::finish`]). -pub(crate) struct SyncedBufFile { - inner: BufWriter, -} - -impl SyncedBufFile { - pub(crate) fn new(file: File) -> Self { - Self { - inner: BufWriter::with_capacity(FILE_BUF_CAPACITY_BYTES, file), - } - } -} - -impl Write for SyncedBufFile { - fn write(&mut self, buf: &[u8]) -> io::Result { - self.inner.write(buf) - } - - fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { - self.inner.write_all(buf) - } - - fn flush(&mut self) -> io::Result<()> { - self.inner.flush()?; - self.inner.get_ref().sync_all() - } -} - -pub(crate) fn create_exclusive_shard_tmp_file_for_table( - out_dir: &Path, - table: &str, - shard_idx: usize, - run_id: &str, -) -> Result<(PathBuf, File), ShardPublishError> { - for attempt in 0..1024u32 { - let file_name = if attempt == 0 { - format!(".{table}.shard-{shard_idx:02}.{run_id}.tmp") - } else { - format!(".{table}.shard-{shard_idx:02}.{run_id}.{attempt}.tmp") - }; - let tmp_path = out_dir.join(file_name); - match OpenOptions::new() - .write(true) - .create_new(true) - .open(&tmp_path) - { - Ok(file) => return Ok((tmp_path, file)), - Err(err) if err.kind() == io::ErrorKind::AlreadyExists => continue, - Err(source) => { - return Err(ShardPublishError::Io { - path: tmp_path, - source, - }); - } - } - } - Err(ShardPublishError::Io { - path: out_dir.join(format!(".{table}.shard-{shard_idx:02}.{run_id}.tmp")), - source: io::Error::new( - io::ErrorKind::AlreadyExists, - "exhausted unique staging file names", - ), - }) -} - -pub(crate) fn publish_staged_shards_for_table( - out_dir: &Path, - table: &str, - staged: &mut [(PathBuf, StagingFileGuard)], - mut before_link: F, -) -> Result<(), ShardPublishError> -where - F: FnMut(usize, &Path), -{ - let mut published: Vec = Vec::with_capacity(staged.len()); - - for (shard_idx, (tmp_path, guard)) in staged.iter_mut().enumerate() { - let final_path = final_shard_path_for_table(out_dir, table, shard_idx); - before_link(shard_idx, &final_path); - - if let Err(source) = fs::hard_link(&tmp_path, &final_path) { - let cause = if source.kind() == io::ErrorKind::AlreadyExists { - ShardPublishError::OutputFileExists { path: final_path } - } else { - ShardPublishError::Io { - path: final_path, - source, - } - }; - let rollback_failures = rollback_published(&published); - if !rollback_failures.is_empty() { - return Err(ShardPublishError::RollbackFailed { - cause: Box::new(cause), - failures: rollback_failures, - }); - } - return Err(cause); - } - - published.push(PublishedPartition { - final_path, - backup_path: None, - }); - - if let Err(source) = fs::remove_file(&tmp_path) { - let cause = ShardPublishError::Io { - path: tmp_path.clone(), - source, - }; - let rollback_failures = rollback_published(&published); - if !rollback_failures.is_empty() { - return Err(ShardPublishError::RollbackFailed { - cause: Box::new(cause), - failures: rollback_failures, - }); - } - return Err(cause); - } - guard.disarm(); - } - - Ok(()) -} - -/// Private file-mode seam accepting injected readers, sink factory, and pre-link hook so tests can -/// exercise staging, writer failure, and post-preflight publication rollback through the exact -/// file publication path. -fn run_curate_bars_1m_to_dir_with_hooks( - args: &CurateBars1mArgs, - intraday: RI, - splits: RS, - mut make_sink: SF, - before_link: BL, -) -> Result -where - RI: io::Read, - RS: io::Read, - W: Write + Send, - SF: FnMut(usize, File) -> W, - BL: FnMut(usize, &Path), -{ - let start = Instant::now(); - validate_file_mode_args(args)?; - - let reference = load_reference_inputs(&args.provider_mapping_path, &args.splits_path, splits)?; - - fs::create_dir_all(&args.out_dir).map_err(|source| RunCurateBars1mError::Io { - path: args.out_dir.clone(), - source, - })?; - - let run_id = next_run_id(); - let mut staged: Vec<(PathBuf, StagingFileGuard)> = Vec::with_capacity(args.shard_count); - let mut sinks: Vec = Vec::with_capacity(args.shard_count); - for shard_idx in 0..args.shard_count { - let (tmp_path, file) = create_exclusive_shard_tmp_file_for_table( - &args.out_dir, - TABLE_BARS_1M, - shard_idx, - &run_id, - )?; - let guard = StagingFileGuard::new(tmp_path.clone()); - staged.push((tmp_path, guard)); - sinks.push(make_sink(shard_idx, file)); - } - - let writer = IlpShardedWriter::new(sinks, args.ilp_options).map_err(RunCurateBars1mError::Ilp)?; - let report = stream_intraday_chunks_to_writer(args, reference, intraday, writer, start)?; - - publish_staged_shards_for_table(&args.out_dir, TABLE_BARS_1M, &mut staged, before_link)?; - Ok(report) -} - -/// Runs the bounded-memory file-to-file `bars_1m` curation pipeline, publishing exactly -/// `args.shard_count` QuestDB ILP v2 files (`/bars_1m.shard-.ilp`). -pub fn run_curate_bars_1m( - args: &CurateBars1mArgs, -) -> Result { - validate_file_mode_args(args)?; - - let splits_file = File::open(&args.splits_path).map_err(|source| { - RunCurateBars1mError::OpenInput { - label: "qm-splits", - path: args.splits_path.clone(), - source, - } - })?; - let intraday_file = File::open(&args.intraday_path).map_err(|source| { - RunCurateBars1mError::OpenInput { - label: "eod-intraday", - path: args.intraday_path.clone(), - source, - } - })?; - - run_curate_bars_1m_to_dir_with_hooks( - args, - intraday_file, - splits_file, - |_shard_idx, file| SyncedBufFile::new(file), - |_shard_idx, _final_path| {}, - ) -} - -/// Formats [`CurateBars1mRunReport`] into a deterministic machine-readable `key=value` summary. -/// -/// Only the final `timing:` line contains wall-clock time (`elapsed_secs`). -pub fn format_curate_bars_1m_report(report: &CurateBars1mRunReport) -> String { - let per_shard = if report.ilp_stats.per_shard_rows.is_empty() { - "none".to_string() - } else { - report - .ilp_stats - .per_shard_rows - .iter() - .enumerate() - .map(|(idx, count)| format!("{idx:02}={count}")) - .collect::>() - .join(",") - }; - - let b = &report.curate_stats.builder; - let c = &report.curate_stats; - let d = &report.intraday_decode; - let sd = &report.splits_decode; - let sr = &report.split_rekey; - - format!( - "curate-etl curate-bars-1m\n\ - \x20 intraday_bson: docs_framed={} bytes_read={} docs_seen={} rows_decoded={} rejected={} (missing={} empty={} wrong_type={} invalid_ts={} invalid_num={} corrupt={})\n\ - \x20 splits_bson: docs_framed={} bytes_read={} docs_in={} decoded={} noop_ratio_one={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={})\n\ - \x20 splits: splits_in={} splits_applied={} splits_collision_collapsed={} splits_unmapped_qm={} splits_no_eod_partner={} splits_noop_dropped={} split_events_attached={}\n\ - \x20 chunking: chunks={} max_rows_per_chunk={} cross_chunk_dedup=questdb_dedup_upsert_keys(ts,listing_id)\n\ - \x20 builder: bars_in={} rows_out={} keys_out_per_chunk_sum={} pre={} rth={} post={} invalid_ohlc={} inconsistent_ohlc={} invalid_vol={} ts_out_of_range={} dup_collapsed={} dup_conflict_dropped={}\n\ - \x20 curate: rows_in={} rows_out={} listings_out_per_chunk_sum={} pre={} rth={} post={} dropped_unmapped={} listing_collision_collapsed={} listing_collision_dropped={}\n\ - \x20 ilp: shards={} rows_written={} ilp_rows={} bytes={} flushes={} per_shard_rows={per_shard}\n\ - \x20 timing: elapsed_secs={:.6}", - report.intraday_docs_framed, - report.intraday_bytes_read, - d.docs_seen, - d.rows_decoded, - d.rejected_total(), - d.rejected_missing_field, - d.rejected_empty_field, - d.rejected_wrong_type, - d.rejected_invalid_timestamp, - d.rejected_invalid_number, - d.rejected_corrupt_document, - report.splits_docs_framed, - report.splits_bytes_read, - sd.docs_in, - sd.decoded, - sd.split_noop_ratio_one, - sd.rejected_total(), - sd.rejected_missing_field, - sd.rejected_empty_field, - sd.rejected_wrong_type, - sd.rejected_malformed_date, - sd.rejected_invalid_number, - sd.rejected_corrupt_document, - sr.splits_in, - sr.splits_applied, - sr.splits_collision_collapsed, - sr.splits_unmapped_qm, - sr.splits_no_eod_partner, - sr.splits_noop_dropped, - sr.split_events_attached, - report.chunks, - report.max_rows_per_chunk, - b.bars_in, - b.rows_out, - b.keys_out, - b.pre_rows_out, - b.rth_rows_out, - b.post_rows_out, - b.dropped_invalid_ohlc, - b.dropped_inconsistent_ohlc, - b.dropped_invalid_volume, - b.dropped_ts_out_of_range, - b.duplicate_collapsed, - b.duplicate_conflict_dropped, - c.rows_in, - c.rows_out, - c.listings_out, - c.pre_rows_out, - c.rth_rows_out, - c.post_rows_out, - c.dropped_unmapped, - c.listing_collision_collapsed, - c.listing_collision_dropped, - report.shard_count, - report.rows_written, - report.ilp_stats.rows, - report.ilp_stats.bytes, - report.ilp_stats.flushes, - report.elapsed_secs, - ) -} - -#[cfg(test)] -#[path = "run_curate_bars_1m_tests.rs"] -pub(crate) mod tests; diff --git a/tools/curate-etl/src/run_curate_bars_1m_tests.rs b/tools/curate-etl/src/run_curate_bars_1m_tests.rs deleted file mode 100644 index 6cf6c065..00000000 --- a/tools/curate-etl/src/run_curate_bars_1m_tests.rs +++ /dev/null @@ -1,1998 +0,0 @@ -use std::collections::BTreeMap; -use std::error::Error; -use std::fs; -use std::io::{self, Cursor, Write}; -use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering}; - -use bson::raw::{cstr, RawDocumentBuf}; - -use super::*; -use crate::bars::Bar1dRow; -use crate::bars_1m::{ - Bar1mRow, IntradaySession, SessionCloseCutoffPolicy, BARS_1M_SOURCE_EOD, -}; -use crate::curate_bars_1m::check_curated_session_closes; -use crate::ilp::{shard_for_listing_id, ILP_V2_DOUBLE_TYPE, TABLE_BARS_1M}; -use crate::session_close::utc_micros_to_et_local; -use crate::shorts::et_to_utc_micros; -use crate::split::ymd_to_epoch_days; - -static TEST_DIR_SEQ: AtomicU64 = AtomicU64::new(0); - -pub(crate) struct TempDirGuard { - path: PathBuf, -} - -impl TempDirGuard { - pub(crate) fn new(prefix: &str) -> Self { - let seq = TEST_DIR_SEQ.fetch_add(1, Ordering::Relaxed); - let path = std::env::temp_dir().join(format!( - "curate-etl-{prefix}-{}-{seq}", - std::process::id() - )); - fs::create_dir_all(&path).expect("create temp test dir"); - Self { path } - } - - pub(crate) fn path(&self) -> &Path { - &self.path - } -} - -impl Drop for TempDirGuard { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.path); - } -} - -fn day(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).expect("valid date") -} - -fn et_ts_sec(y: i32, m: u32, d: u32, hour: u8, minute: u8) -> i64 { - let micros = et_to_utc_micros(day(y, m, d), hour, minute, 0).expect("valid ET timestamp"); - assert_eq!(micros % 1_000_000, 0); - micros / 1_000_000 -} - -fn make_intraday_doc( - code: &str, - timestamp_sec: i64, - open: f64, - high: f64, - low: f64, - close: f64, - volume: f64, -) -> RawDocumentBuf { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), code); - doc.append(cstr!("timestamp"), timestamp_sec); - doc.append(cstr!("open"), open); - doc.append(cstr!("high"), high); - doc.append(cstr!("low"), low); - doc.append(cstr!("close"), close); - doc.append(cstr!("volume"), volume); - doc -} - -fn make_split_doc( - qm_search_code: &str, - ex_date: &str, - for_factor: f64, - to_factor: f64, -) -> RawDocumentBuf { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), qm_search_code); - doc.append(cstr!("date"), ex_date); - doc.append(cstr!("forfactor"), for_factor); - doc.append(cstr!("tofactor"), to_factor); - doc.append(cstr!("splitratio"), for_factor / to_factor); - doc -} - -fn concat_docs(docs: &[RawDocumentBuf]) -> Vec { - let mut out = Vec::new(); - for doc in docs { - out.extend_from_slice(doc.as_bytes()); - } - out -} - -fn write_mapping_tsv(dir: &Path, lines: &[&str]) -> PathBuf { - let path = dir.join("provider_mapping.tsv"); - let mut body = lines.join("\n"); - if !body.is_empty() { - body.push('\n'); - } - fs::write(&path, body).expect("write provider_mapping.tsv"); - path -} - -fn make_args( - mapping_path: PathBuf, - splits_path: PathBuf, - intraday_path: PathBuf, - out_dir: PathBuf, - shard_count: usize, - known_at_micros: i64, - stream_options: BsonStreamOptions, -) -> CurateBars1mArgs { - CurateBars1mArgs { - intraday_path, - splits_path, - provider_mapping_path: mapping_path, - out_dir, - mapping_source: DEFAULT_BARS_1M_MAPPING_SOURCE.to_string(), - shard_count, - known_at_micros, - stream_options, - ilp_options: IlpWriterOptions::default(), - } -} - -#[derive(Debug, Clone, PartialEq)] -struct DecodedIlpBar1m { - listing_id: i32, - session: IntradaySession, - source: String, - open: f64, - high: f64, - low: f64, - close: f64, - volume: f64, - known_at: i64, - ts: i64, -} - -impl DecodedIlpBar1m { - fn to_bar_1m_row(&self) -> Bar1mRow { - let et = utc_micros_to_et_local(self.ts).expect("valid ET timestamp"); - Bar1mRow { - key: self.listing_id, - ts: self.ts, - session_date: et.session_date, - open: self.open, - high: self.high, - low: self.low, - close: self.close, - volume: self.volume, - session: self.session, - source: match self.source.as_str() { - BARS_1M_SOURCE_EOD => BARS_1M_SOURCE_EOD, - other => panic!("unexpected source '{other}'"), - }, - } - } - - fn sort_key(&self) -> (i32, i64, u64, u64, u64, u64, u64, i64) { - ( - self.listing_id, - self.ts, - self.open.to_bits(), - self.high.to_bits(), - self.low.to_bits(), - self.close.to_bits(), - self.volume.to_bits(), - self.known_at, - ) - } -} - -/// Decodes QuestDB ILP v2 `bars_1m` records respecting fixed-width 8-byte binary `DOUBLE` -/// payloads (`==\x10<8 LE bytes>`) so embedded `0x0a` bytes inside doubles never split rows. -fn decode_ilp_bars_1m(data: &[u8]) -> Vec { - let mut rows = Vec::new(); - let mut i = 0usize; - let len = data.len(); - - while i < len { - // 1. Tag set ends at unescaped space. - let tag_start = i; - while i < len { - match data[i] { - b'\\' => { - assert!(i + 1 < len, "dangling backslash in ILP tag set"); - i += 2; - } - b' ' => break, - _ => i += 1, - } - } - assert!(i < len && data[i] == b' ', "missing space after ILP tag set"); - let tag_str = std::str::from_utf8(&data[tag_start..i]).expect("valid UTF-8 tag set"); - i += 1; - - let mut tags = tag_str.split(','); - assert_eq!(tags.next(), Some(TABLE_BARS_1M), "expected bars_1m table"); - let listing_tag = tags.next().expect("listing_id tag"); - let session_tag = tags.next().expect("session tag"); - let source_tag = tags.next().expect("source tag"); - assert!(tags.next().is_none(), "unexpected extra ILP tag"); - - let listing_id: i32 = listing_tag - .strip_prefix("listing_id=") - .expect("listing_id= prefix") - .parse() - .expect("i32 listing_id"); - let session = match session_tag - .strip_prefix("session=") - .expect("session= prefix") - { - "PRE" => IntradaySession::Pre, - "RTH" => IntradaySession::Rth, - "POST" => IntradaySession::Post, - other => panic!("unexpected session '{other}'"), - }; - let source = source_tag - .strip_prefix("source=") - .expect("source= prefix") - .to_string(); - - // 2. Fixed-width binary f64 fields: open, high, low, close, volume, then known_at=t. - let read_bin_f64 = |pos: &mut usize, name: &str| -> f64 { - let prefix = format!("{name}=="); - assert!( - data[*pos..].starts_with(prefix.as_bytes()), - "expected field prefix '{prefix}' at offset {}", - *pos - ); - *pos += prefix.len(); - assert_eq!( - data[*pos], ILP_V2_DOUBLE_TYPE, - "expected binary DOUBLE type tag for '{name}'" - ); - *pos += 1; - let bytes: [u8; 8] = data[*pos..*pos + 8] - .try_into() - .expect("8 bytes for binary double"); - *pos += 8; - f64::from_le_bytes(bytes) - }; - - let open = read_bin_f64(&mut i, "open"); - assert_eq!(data[i], b','); - i += 1; - let high = read_bin_f64(&mut i, "high"); - assert_eq!(data[i], b','); - i += 1; - let low = read_bin_f64(&mut i, "low"); - assert_eq!(data[i], b','); - i += 1; - let close = read_bin_f64(&mut i, "close"); - assert_eq!(data[i], b','); - i += 1; - let volume = read_bin_f64(&mut i, "volume"); - assert!( - data[i..].starts_with(b",known_at="), - "expected ,known_at= field" - ); - i += b",known_at=".len(); - - let known_start = i; - while i < len && data[i] != b' ' { - i += 1; - } - assert!(i < len && data[i] == b' ', "missing space after known_at"); - let known_str = std::str::from_utf8(&data[known_start..i]).expect("valid UTF-8 known_at"); - let known_at: i64 = known_str - .strip_suffix('t') - .expect("known_at trailing t") - .parse() - .expect("i64 known_at"); - i += 1; - - // 3. Designated timestamp `t\n`. - let ts_start = i; - while i < len && data[i] != b'\n' { - i += 1; - } - assert!(i < len && data[i] == b'\n', "missing trailing LF"); - let ts_str = std::str::from_utf8(&data[ts_start..i]).expect("valid UTF-8 ts"); - let ts: i64 = ts_str - .strip_suffix('t') - .expect("ts trailing t") - .parse() - .expect("i64 ts"); - i += 1; - - rows.push(DecodedIlpBar1m { - listing_id, - session, - source, - open, - high, - low, - close, - volume, - known_at, - ts, - }); - } - - rows -} - -fn assert_report_conservation(report: &CurateBars1mRunReport) { - assert_eq!( - report.intraday_docs_framed as usize, report.intraday_decode.docs_seen, - "docs_framed != docs_seen" - ); - assert_eq!( - report.intraday_decode.docs_seen, - report.intraday_decode.rows_decoded + report.intraday_decode.rejected_total(), - "decode conservation failed" - ); - let b = &report.curate_stats.builder; - assert_eq!( - report.intraday_decode.rows_decoded, b.bars_in, - "rows_decoded != builder.bars_in" - ); - assert_eq!( - b.bars_in, - b.rows_out - + b.dropped_invalid_ohlc - + b.dropped_inconsistent_ohlc - + b.dropped_invalid_volume - + b.dropped_ts_out_of_range - + b.duplicate_collapsed - + b.duplicate_conflict_dropped, - "builder conservation failed: {b:?}" - ); - assert_eq!( - b.pre_rows_out + b.rth_rows_out + b.post_rows_out, - b.rows_out, - "builder session breakdown failed" - ); - - let c = &report.curate_stats; - assert_eq!(c.rows_in, b.rows_out, "curate.rows_in != builder.rows_out"); - assert_eq!( - c.rows_in, - c.rows_out - + c.dropped_unmapped - + c.listing_collision_collapsed - + c.listing_collision_dropped, - "curate conservation failed: {c:?}" - ); - assert_eq!( - c.pre_rows_out + c.rth_rows_out + c.post_rows_out, - c.rows_out, - "curate session breakdown failed" - ); - - assert_eq!(report.rows_written, c.rows_out, "rows_written != rows_out"); - assert_eq!( - report.rows_written, report.ilp_stats.rows, - "rows_written != ilp_stats.rows" - ); - assert_eq!( - report.ilp_stats.per_shard_rows.iter().sum::(), - report.ilp_stats.rows, - "sum(per_shard_rows) != ilp_stats.rows" - ); - assert_eq!(report.ilp_stats.per_shard_rows.len(), report.shard_count); -} - -/// Split-boundary replay fixture (`run_curate_bars_1m_tests::split_boundary_nvda_and_nexm_match_raw_bars_1d_closes`): -/// -/// SYNTHETIC fixture built from the figures in `REVIEW.md:88` and `design/DATA-CONTRACTS.md` §1 -/// (lines 13, 15, 25): -/// - `NVDA.US` (`listing_id=1001`, `eod: NVDA.US`, `qm: NVDA`, 10:1 forward split ex-date -/// `2024-06-10`, `forfactor=1, tofactor=10, splitratio=0.1`): -/// - `2024-06-07` (pre-split): adj 1m close `120.888`, adj vol `412_390.0` -> raw `1208.88`, -/// vol `41_239.0`; synthetic daily baseline `1208.88`. -/// - `2024-06-10` (ex-date): 1m close `121.79`, vol `350_000.0` (unchanged); synthetic daily -/// baseline `121.79`. -/// - `NEXM.V` (`listing_id=2002`, `eod: NEXM.V`, `qm: NEXM:CA`, 1:20 reverse split ex-date -/// `2025-06-20`, `forfactor=20, tofactor=1, splitratio=20.0`, aligned to `REVIEW.md:88`): -/// - `2025-06-18` (pre-split): adj 1m close `24.29`, adj vol `5_000.0` -> raw `1.2145`, -/// vol `100_000.0`; synthetic daily baseline `1.215` (~0.041% rel diff, matching `~1.21`). -/// - `2025-06-19` (intervening pre-split session): adj 1m close `24.40`, adj vol `4_000.0` -> -/// raw `1.22`, vol `80_000.0`; synthetic daily baseline `1.22`. -/// - `2025-06-20` (ex-date): 1m close `24.28` (`REVIEW.md:88` records `24.2799`), vol `12_500.0` -/// (unchanged); synthetic daily baseline `24.28`. -/// -/// Scope of this test: -/// - Proves split arithmetic, listing resolution, and ex-date boundary handling in the runner. -/// - Does NOT prove provider mapping, ex-date, or RTH close against retained `bars_1d` data. -/// - Open item: M2 exit criterion 3 observed-data split-boundary check (NEXM.V, NVDA.US vs -/// retained raw `bars_1d` closes) — open, owned by the live-host `bars_1m` load verification task. -#[test] -fn split_boundary_nvda_and_nexm_match_raw_bars_1d_closes() { - let dir = TempDirGuard::new("bars1m-split"); - let nvda_id = 1001; - let nexm_id = 2002; - let known_at_micros: i64 = 1_750_500_000_000_000; - - let mapping_path = write_mapping_tsv( - dir.path(), - &[ - &format!("eod\tNVDA.US\t2020-01-01\t\t{nvda_id}"), - &format!("qm\tNVDA\t2020-01-01\t\t{nvda_id}"), - &format!("eod\tNEXM.V\t2020-01-01\t\t{nexm_id}"), - &format!("qm\tNEXM:CA\t2020-01-01\t\t{nexm_id}"), - ], - ); - - let splits_bytes = concat_docs(&[ - // NVDA 10:1 forward split on 2024-06-10 (QM: forfactor=1, tofactor=10, splitratio=0.1 -> ratio=10.0) - make_split_doc("NVDA", "2024-06-10", 1.0, 10.0), - // NEXM.V / NEXM:CA 1:20 reverse split on 2025-06-20 (QM: forfactor=20, tofactor=1, splitratio=20.0 -> ratio=0.05) - make_split_doc("NEXM:CA", "2025-06-20", 20.0, 1.0), - ]); - - let intraday_bytes = concat_docs(&[ - make_intraday_doc( - "NVDA.US", - et_ts_sec(2024, 6, 7, 15, 58), - 120.45, - 120.95, - 120.35, - 120.75, - 300_000.0, - ), - make_intraday_doc( - "NVDA.US", - et_ts_sec(2024, 6, 7, 15, 59), - 120.50, - 121.00, - 120.40, - 120.888, - 412_390.0, - ), - make_intraday_doc( - "NVDA.US", - et_ts_sec(2024, 6, 10, 15, 59), - 121.50, - 121.95, - 121.40, - 121.79, - 350_000.0, - ), - make_intraday_doc( - "NEXM.V", - et_ts_sec(2025, 6, 18, 9, 30), - 24.00, - 24.60, - 23.80, - 24.20, - 2_000.0, - ), - make_intraday_doc( - "NEXM.V", - et_ts_sec(2025, 6, 18, 15, 59), - 24.20, - 24.40, - 24.10, - 24.29, - 5_000.0, - ), - make_intraday_doc( - "NEXM.V", - et_ts_sec(2025, 6, 19, 15, 59), - 24.30, - 24.50, - 24.10, - 24.40, - 4_000.0, - ), - make_intraday_doc( - "NEXM.V", - et_ts_sec(2025, 6, 20, 15, 59), - 24.10, - 24.50, - 23.90, - 24.28, - 12_500.0, - ), - ]); - - let mut sink0 = Vec::new(); - let mut sink1 = Vec::new(); - let writer = - IlpShardedWriter::new(vec![&mut sink0, &mut sink1], IlpWriterOptions::default()).unwrap(); - - let args = make_args( - mapping_path.clone(), - dir.path().join("qmSplits.bson"), - dir.path().join("eodIntraday1M.bson"), - dir.path().join("out"), - 2, - known_at_micros, - BsonStreamOptions::default(), - ); - - let report = run_curate_bars_1m_with_readers( - &args, - Cursor::new(&intraday_bytes), - Cursor::new(&splits_bytes), - writer, - ) - .expect("split-boundary run should succeed"); - - assert_report_conservation(&report); - assert_eq!(report.rows_written, 7); - assert_eq!(report.split_rekey.splits_applied, 2); - - let mut decoded = decode_ilp_bars_1m(&sink0); - decoded.extend(decode_ilp_bars_1m(&sink1)); - assert_eq!(decoded.len(), 7); - for row in &decoded { - assert_eq!(row.known_at, known_at_micros); - assert_eq!(row.source, BARS_1M_SOURCE_EOD); - } - - // Verify inverse volume scaling on pre-split bars (including intervening session 2025-06-19) - // and unchanged OHLCV on ex-date bars. - let find_row = |id: i32, ts_sec: i64| -> &DecodedIlpBar1m { - decoded - .iter() - .find(|r| r.listing_id == id && r.ts == ts_sec * 1_000_000) - .expect("expected row") - }; - - let nvda_pre = find_row(nvda_id, et_ts_sec(2024, 6, 7, 15, 59)); - assert!((nvda_pre.close - 1208.88).abs() < 1e-9); - assert!((nvda_pre.volume - 41_239.0).abs() < 1e-9); - - let nvda_ex = find_row(nvda_id, et_ts_sec(2024, 6, 10, 15, 59)); - assert_eq!(nvda_ex.open.to_bits(), 121.50_f64.to_bits()); - assert_eq!(nvda_ex.high.to_bits(), 121.95_f64.to_bits()); - assert_eq!(nvda_ex.low.to_bits(), 121.40_f64.to_bits()); - assert_eq!(nvda_ex.close.to_bits(), 121.79_f64.to_bits()); - assert_eq!(nvda_ex.volume.to_bits(), 350_000.0_f64.to_bits()); - - let nexm_pre_18 = find_row(nexm_id, et_ts_sec(2025, 6, 18, 15, 59)); - assert!((nexm_pre_18.close - 1.2145).abs() < 1e-9); - assert!((nexm_pre_18.volume - 100_000.0).abs() < 1e-9); - - let nexm_pre_19 = find_row(nexm_id, et_ts_sec(2025, 6, 19, 15, 59)); - assert!((nexm_pre_19.open - 1.215).abs() < 1e-9); - assert!((nexm_pre_19.high - 1.225).abs() < 1e-9); - assert!((nexm_pre_19.low - 1.205).abs() < 1e-9); - assert!((nexm_pre_19.close - 1.22).abs() < 1e-9); - assert!((nexm_pre_19.volume - 80_000.0).abs() < 1e-9); - - let nexm_ex = find_row(nexm_id, et_ts_sec(2025, 6, 20, 15, 59)); - assert_eq!(nexm_ex.open.to_bits(), 24.10_f64.to_bits()); - assert_eq!(nexm_ex.high.to_bits(), 24.50_f64.to_bits()); - assert_eq!(nexm_ex.low.to_bits(), 23.90_f64.to_bits()); - assert_eq!(nexm_ex.close.to_bits(), 24.28_f64.to_bits()); - assert_eq!(nexm_ex.volume.to_bits(), 12_500.0_f64.to_bits()); - - // Check all five synthetic RTH session closes against synthetic daily baselines within 0.5%. - let mut rows_1m: Vec> = decoded.iter().map(DecodedIlpBar1m::to_bar_1m_row).collect(); - rows_1m.sort_by_key(|r| (r.key, r.ts)); - - let bars_1d = vec![ - Bar1dRow { - key: nvda_id, - session_date: day(2024, 6, 7), - open: 1197.7, - high: 1216.92, - low: 1180.22, - close: 1208.88, - volume: 41_239_000.0, - }, - Bar1dRow { - key: nvda_id, - session_date: day(2024, 6, 10), - open: 120.37, - high: 123.10, - low: 117.01, - close: 121.79, - volume: 314_162_700.0, - }, - Bar1dRow { - key: nexm_id, - session_date: day(2025, 6, 18), - open: 1.20, - high: 1.23, - low: 1.19, - close: 1.215, // ~0.041% rel diff vs 1.2145 (REVIEW.md:88 / DATA-CONTRACTS.md §1: ~1.21 raw) - volume: 100_000.0, - }, - Bar1dRow { - key: nexm_id, - session_date: day(2025, 6, 19), - open: 1.215, - high: 1.225, - low: 1.205, - close: 1.22, - volume: 80_000.0, - }, - Bar1dRow { - key: nexm_id, - session_date: day(2025, 6, 20), - open: 24.10, - high: 24.50, - low: 23.90, - close: 24.28, - volume: 12_500.0, - }, - ]; - - let check = check_curated_session_closes( - &rows_1m, - &bars_1d, - &SessionCloseCutoffPolicy::standard_rth(), - 0.005, - ) - .expect("session close check should succeed"); - assert_eq!(check.stats.checked, 5); - assert_eq!(check.stats.within_tolerance, 5); - assert_eq!(check.stats.mismatched, 0); - assert!(check.stats.max_rel_diff < 0.005); - - // Negative control: omitting qmSplits leaves pre-split bars retroactively adjusted and fails - // the 0.5% check on all three pre-split sessions (NVDA 2024-06-07, NEXM 2025-06-18, and - // intervening NEXM 2025-06-19). - let mut neg_sink = Vec::new(); - let neg_writer = - IlpShardedWriter::new(vec![&mut neg_sink], IlpWriterOptions::default()).unwrap(); - let neg_args = make_args( - mapping_path, - dir.path().join("empty_splits.bson"), - dir.path().join("eodIntraday1M.bson"), - dir.path().join("out-neg"), - 1, - known_at_micros, - BsonStreamOptions::default(), - ); - let _ = run_curate_bars_1m_with_readers( - &neg_args, - Cursor::new(&intraday_bytes), - Cursor::new(Vec::::new()), - neg_writer, - ) - .expect("negative-control run should succeed"); - let mut neg_rows: Vec> = decode_ilp_bars_1m(&neg_sink) - .iter() - .map(DecodedIlpBar1m::to_bar_1m_row) - .collect(); - neg_rows.sort_by_key(|r| (r.key, r.ts)); - let neg_check = check_curated_session_closes( - &neg_rows, - &bars_1d, - &SessionCloseCutoffPolicy::standard_rth(), - 0.005, - ) - .expect("negative-control close check should succeed"); - assert_eq!(neg_check.stats.checked, 5); - assert_eq!(neg_check.stats.within_tolerance, 2); - assert_eq!(neg_check.stats.mismatched, 3); -} - -#[test] -fn reused_ticker_does_not_leak_later_listing_split_to_earlier_listing() { - let dir = TempDirGuard::new("bars1m-reused-ticker"); - let known_at_micros: i64 = 1_750_550_000_000_000; - - // Same non-overlapping FB.US reuse layout as the daily runner fixture: - // listing 10 through 2022-06-08, gap, listing 20 starting 2025-01-01. - let mapping_path = write_mapping_tsv( - dir.path(), - &[ - "eod\tFB.US\t2012-01-01\t2022-06-08\t10", - "qm\tFB:US\t2012-01-01\t2022-06-08\t10", - "eod\tFB.US\t2025-01-01\t\t20", - "qm\tFBETF:US\t2025-01-01\t\t20", - ], - ); - - // 2:1 forward split belonging strictly to listing 20 (ex-date 2025-06-02). - let splits_bytes = concat_docs(&[make_split_doc("FBETF:US", "2025-06-02", 1.0, 2.0)]); - - let ts_old = et_ts_sec(2022, 6, 8, 15, 59); - let ts_new_pre = et_ts_sec(2025, 5, 30, 15, 59); - let ts_new_ex = et_ts_sec(2025, 6, 2, 15, 59); - - let intraday_bytes = concat_docs(&[ - // Listing 10 bar in 2022: must NOT receive listing 20's 2025 2:1 split. - make_intraday_doc("FB.US", ts_old, 190.0, 195.0, 188.0, 192.0, 1_000.0), - // Listing 20 pre-split bar in May 2025: MUST be un-adjusted by 2:1 (price * 2, vol / 2). - make_intraday_doc("FB.US", ts_new_pre, 25.0, 26.0, 24.5, 25.5, 5_000.0), - // Listing 20 ex-date bar on 2025-06-02: MUST remain unchanged. - make_intraday_doc("FB.US", ts_new_ex, 25.5, 26.5, 25.0, 26.0, 4_000.0), - ]); - - let mut sink = Vec::new(); - let writer = IlpShardedWriter::new(vec![&mut sink], IlpWriterOptions::default()).unwrap(); - let args = make_args( - mapping_path, - dir.path().join("qmSplits.bson"), - dir.path().join("eodIntraday1M.bson"), - dir.path().join("out"), - 1, - known_at_micros, - BsonStreamOptions::default(), - ); - - let report = run_curate_bars_1m_with_readers( - &args, - Cursor::new(&intraday_bytes), - Cursor::new(&splits_bytes), - writer, - ) - .expect("reused-ticker run should succeed"); - - assert_report_conservation(&report); - assert_eq!(report.rows_written, 3); - assert_eq!(report.split_rekey.splits_applied, 1); - - let rows = decode_ilp_bars_1m(&sink); - assert_eq!(rows.len(), 3); - - // Listing 10 (2022): bitwise unchanged — no split leakage from listing 20. - let old_row = rows - .iter() - .find(|r| r.listing_id == 10 && r.ts == ts_old * 1_000_000) - .expect("listing 10 row"); - assert_eq!(old_row.open.to_bits(), 190.0_f64.to_bits()); - assert_eq!(old_row.high.to_bits(), 195.0_f64.to_bits()); - assert_eq!(old_row.low.to_bits(), 188.0_f64.to_bits()); - assert_eq!(old_row.close.to_bits(), 192.0_f64.to_bits()); - assert_eq!(old_row.volume.to_bits(), 1_000.0_f64.to_bits()); - - // Listing 20 (2025-05-30 pre-split): un-adjusted by 2:1. - let new_pre = rows - .iter() - .find(|r| r.listing_id == 20 && r.ts == ts_new_pre * 1_000_000) - .expect("listing 20 pre-split row"); - assert!((new_pre.open - 50.0).abs() < 1e-9); - assert!((new_pre.high - 52.0).abs() < 1e-9); - assert!((new_pre.low - 49.0).abs() < 1e-9); - assert!((new_pre.close - 51.0).abs() < 1e-9); - assert!((new_pre.volume - 2_500.0).abs() < 1e-9); - - // Listing 20 (2025-06-02 ex-date): bitwise unchanged. - let new_ex = rows - .iter() - .find(|r| r.listing_id == 20 && r.ts == ts_new_ex * 1_000_000) - .expect("listing 20 ex-date row"); - assert_eq!(new_ex.open.to_bits(), 25.5_f64.to_bits()); - assert_eq!(new_ex.high.to_bits(), 26.5_f64.to_bits()); - assert_eq!(new_ex.low.to_bits(), 25.0_f64.to_bits()); - assert_eq!(new_ex.close.to_bits(), 26.0_f64.to_bits()); - assert_eq!(new_ex.volume.to_bits(), 4_000.0_f64.to_bits()); -} - -#[test] -fn chunking_equivalence_and_bounded_memory_across_small_and_large_chunks() { - let dir = TempDirGuard::new("bars1m-chunk-eq"); - let known_at_micros: i64 = 1_750_600_000_000_000; - - let mapping_path = write_mapping_tsv( - dir.path(), - &[ - "eod\tAAA.US\t2020-01-01\t\t101", - "eod\tBBB.US\t2020-01-01\t\t102", - "eod\tCCC.US\t2020-01-01\t\t103", - "eod\tDDD.US\t2020-01-01\t\t104", - ], - ); - - let mut docs = Vec::new(); - let codes = ["AAA.US", "BBB.US", "CCC.US", "DDD.US", "UNMAPPED.US"]; - for idx in 0..15i64 { - let code = codes[(idx as usize) % codes.len()]; - let ts = et_ts_sec(2025, 3, 10, 10, (idx % 60) as u8); - let px = 10.0 + idx as f64; - let doc = make_intraday_doc( - code, - ts, - px, - px + 0.5, - px - 0.5, - px + 0.25, - 100.0 + idx as f64, - ); - docs.push(doc); - } - - let min_doc_bytes = docs.iter().map(|d| d.as_bytes().len()).min().unwrap(); - let max_doc_bytes_in_fixture = docs.iter().map(|d| d.as_bytes().len()).max().unwrap(); - let intraday_bytes = concat_docs(&docs); - let splits_bytes: Vec = Vec::new(); - - // Small chunk capacity: holds at most 2 documents per chunk, forcing >= 3 chunks. - let small_cap = min_doc_bytes * 2 + 16; - let small_opts = BsonStreamOptions { - chunk_capacity_bytes: small_cap, - max_doc_bytes: max_doc_bytes_in_fixture + 64, - }; - let large_opts = BsonStreamOptions { - chunk_capacity_bytes: intraday_bytes.len() + 1024, - max_doc_bytes: intraday_bytes.len() + 1024, - }; - - let run_with = |opts: BsonStreamOptions| -> (CurateBars1mRunReport, Vec>) { - let mut s0 = Vec::new(); - let mut s1 = Vec::new(); - let mut s2 = Vec::new(); - let writer = IlpShardedWriter::new( - vec![&mut s0, &mut s1, &mut s2], - IlpWriterOptions::default(), - ) - .unwrap(); - let args = make_args( - mapping_path.clone(), - dir.path().join("qmSplits.bson"), - dir.path().join("eodIntraday1M.bson"), - dir.path().join("out"), - 3, - known_at_micros, - opts, - ); - let report = run_curate_bars_1m_with_readers( - &args, - Cursor::new(&intraday_bytes), - Cursor::new(&splits_bytes), - writer, - ) - .expect("run should succeed"); - assert_report_conservation(&report); - let mut per_shard = vec![ - decode_ilp_bars_1m(&s0), - decode_ilp_bars_1m(&s1), - decode_ilp_bars_1m(&s2), - ]; - for shard_rows in &mut per_shard { - shard_rows.sort_by_key(DecodedIlpBar1m::sort_key); - } - (report, per_shard) - }; - - let (small_report, small_shards) = run_with(small_opts); - let (large_report, large_shards) = run_with(large_opts); - - assert_eq!(large_report.chunks, 1); - assert!( - small_report.chunks >= 3, - "expected >= 3 chunks, got {}", - small_report.chunks - ); - // Bounded-memory invariant: max rows per chunk <= small_cap / min_doc_bytes and < total decoded. - assert!( - small_report.max_rows_per_chunk <= small_cap / min_doc_bytes, - "max_rows_per_chunk={} exceeded bound {}", - small_report.max_rows_per_chunk, - small_cap / min_doc_bytes - ); - assert!(small_report.max_rows_per_chunk < small_report.intraday_decode.rows_decoded); - - // Equivalence on duplicate-free fixture. - assert_eq!(small_report.rows_written, large_report.rows_written); - assert_eq!( - small_report.curate_stats.dropped_unmapped, - large_report.curate_stats.dropped_unmapped - ); - assert_eq!(small_report.curate_stats.dropped_unmapped, 3); - assert_eq!(small_report.rows_written, 12); - assert_eq!(small_shards, large_shards); - - // Also exercise an oversized single document (> chunk_capacity_bytes, <= max_doc_bytes). - let mut big_doc = make_intraday_doc( - "AAA.US", - et_ts_sec(2025, 3, 10, 11, 0), - 25.0, - 25.5, - 24.5, - 25.25, - 900.0, - ); - let pad = "x".repeat(small_cap + 256); - big_doc.append(cstr!("_note"), pad.as_str()); - let big_doc_len = big_doc.as_bytes().len(); - assert!(big_doc_len > small_cap); - let big_bytes = concat_docs(&[big_doc]); - - let mut big_sink = Vec::new(); - let big_writer = IlpShardedWriter::new(vec![&mut big_sink], IlpWriterOptions::default()).unwrap(); - let big_args = make_args( - mapping_path, - dir.path().join("qmSplits.bson"), - dir.path().join("eodIntraday1M.bson"), - dir.path().join("out-big"), - 1, - known_at_micros, - BsonStreamOptions { - chunk_capacity_bytes: small_cap, - max_doc_bytes: big_doc_len + 64, - }, - ); - let big_report = run_curate_bars_1m_with_readers( - &big_args, - Cursor::new(&big_bytes), - Cursor::new(&splits_bytes), - big_writer, - ) - .expect("oversized single document within max_doc_bytes should succeed"); - assert_report_conservation(&big_report); - assert_eq!(big_report.chunks, 1); - assert_eq!(big_report.rows_written, 1); -} - -#[test] -fn cross_chunk_duplicate_is_emitted_twice_and_reported() { - let dir = TempDirGuard::new("bars1m-cross-chunk-dup"); - let known_at_micros: i64 = 1_750_700_000_000_000; - let mapping_path = write_mapping_tsv(dir.path(), &["eod\tDUP.US\t2020-01-01\t\t505"]); - - let ts = et_ts_sec(2025, 4, 15, 11, 0); - let doc1 = make_intraday_doc("DUP.US", ts, 50.0, 51.0, 49.0, 50.5, 1_000.0); - let doc2 = make_intraday_doc("DUP.US", ts, 50.0, 51.0, 49.0, 50.5, 1_000.0); - let doc_len = doc1.as_bytes().len(); - let intraday_bytes = concat_docs(&[doc1, doc2]); - - // Capacity fits exactly 1 doc per chunk so doc1 and doc2 land in separate chunks. - let stream_opts = BsonStreamOptions { - chunk_capacity_bytes: doc_len, - max_doc_bytes: doc_len + 64, - }; - - let mut sink = Vec::new(); - let writer = IlpShardedWriter::new(vec![&mut sink], IlpWriterOptions::default()).unwrap(); - let args = make_args( - mapping_path, - dir.path().join("qmSplits.bson"), - dir.path().join("eodIntraday1M.bson"), - dir.path().join("out"), - 1, - known_at_micros, - stream_opts, - ); - - let report = run_curate_bars_1m_with_readers( - &args, - Cursor::new(&intraday_bytes), - Cursor::new(Vec::::new()), - writer, - ) - .expect("cross-chunk duplicate run should succeed"); - - assert_report_conservation(&report); - assert_eq!(report.chunks, 2); - assert_eq!(report.max_rows_per_chunk, 1); - assert_eq!(report.curate_stats.builder.duplicate_collapsed, 0); - assert_eq!(report.curate_stats.listing_collision_collapsed, 0); - assert_eq!(report.curate_stats.listings_out, 2); - assert_eq!(report.curate_stats.builder.keys_out, 2); - assert_eq!(report.rows_written, 2); - - let rows = decode_ilp_bars_1m(&sink); - assert_eq!(rows.len(), 2); - assert_eq!(rows[0], rows[1]); - assert_eq!(rows[0].listing_id, 505); - assert_eq!(rows[0].ts, ts * 1_000_000); - - let formatted = format_curate_bars_1m_report(&report); - assert!(formatted.contains("cross_chunk_dedup=questdb_dedup_upsert_keys(ts,listing_id)")); - assert!(formatted.contains("listings_out_per_chunk_sum=2")); - assert!(formatted.contains("keys_out_per_chunk_sum=2")); -} - -#[test] -fn stats_conservation_with_within_chunk_collisions_and_malformed_docs() { - let dir = TempDirGuard::new("bars1m-conservation"); - let known_at_micros: i64 = 1_750_800_000_000_000; - - let mapping_path = write_mapping_tsv( - dir.path(), - &[ - "eod\tA1.US\t2020-01-01\t\t701", - "eod\tA2.US\t2020-01-01\t\t701", - "eod\tB.US\t2020-01-01\t\t702", - ], - ); - - let ts_pre = et_ts_sec(2025, 5, 1, 8, 15); - let ts_rth = et_ts_sec(2025, 5, 1, 10, 30); - let ts_post = et_ts_sec(2025, 5, 1, 16, 45); - let ts_conflict = et_ts_sec(2025, 5, 1, 11, 0); - - // Malformed document: missing `close` field. - let mut bad_missing = RawDocumentBuf::new(); - bad_missing.append(cstr!("eodSearchCode"), "B.US"); - bad_missing.append(cstr!("timestamp"), ts_rth); - bad_missing.append(cstr!("open"), 10.0); - bad_missing.append(cstr!("high"), 11.0); - bad_missing.append(cstr!("low"), 9.0); - bad_missing.append(cstr!("volume"), 100.0); - - // Malformed document: negative timestamp. - let bad_ts = make_intraday_doc("B.US", -10, 10.0, 11.0, 9.0, 10.5, 100.0); - - let docs = vec![ - // PRE bar on B.US - make_intraday_doc("B.US", ts_pre, 20.0, 20.5, 19.8, 20.2, 500.0), - // POST bar on B.US - make_intraday_doc("B.US", ts_post, 21.0, 21.2, 20.9, 21.1, 300.0), - // Identical cross-source_id alias collision on listing 701 at ts_rth -> collapses to 1 - make_intraday_doc("A1.US", ts_rth, 10.0, 10.5, 9.9, 10.2, 1_000.0), - make_intraday_doc("A2.US", ts_rth, 10.0, 10.5, 9.9, 10.2, 1_000.0), - // Conflicting cross-source_id alias collision on listing 701 at ts_conflict -> drops both (2) - make_intraday_doc("A1.US", ts_conflict, 10.0, 10.5, 9.9, 10.2, 1_000.0), - make_intraday_doc("A2.US", ts_conflict, 10.0, 10.5, 9.9, 10.4, 1_000.0), - // Unmapped code -> dropped_unmapped = 1 - make_intraday_doc("GHOST.US", ts_rth, 5.0, 5.2, 4.9, 5.1, 50.0), - // Malformed docs -> counted in intraday_decode.rejected_total() = 2 - bad_missing, - bad_ts, - ]; - let intraday_bytes = concat_docs(&docs); - - let mut sink = Vec::new(); - let writer = IlpShardedWriter::new(vec![&mut sink], IlpWriterOptions::default()).unwrap(); - let args = make_args( - mapping_path, - dir.path().join("qmSplits.bson"), - dir.path().join("eodIntraday1M.bson"), - dir.path().join("out"), - 1, - known_at_micros, - BsonStreamOptions::default(), - ); - - let report = run_curate_bars_1m_with_readers( - &args, - Cursor::new(&intraday_bytes), - Cursor::new(Vec::::new()), - writer, - ) - .expect("conservation test run should succeed"); - - assert_report_conservation(&report); - assert_eq!(report.intraday_docs_framed, 9); - assert_eq!(report.intraday_decode.rows_decoded, 7); - assert_eq!(report.intraday_decode.rejected_total(), 2); - assert_eq!(report.intraday_decode.rejected_missing_field, 1); - assert_eq!(report.intraday_decode.rejected_invalid_timestamp, 1); - - assert_eq!(report.curate_stats.rows_in, 7); - assert_eq!(report.curate_stats.rows_out, 3); - assert_eq!(report.curate_stats.pre_rows_out, 1); - assert_eq!(report.curate_stats.rth_rows_out, 1); - assert_eq!(report.curate_stats.post_rows_out, 1); - assert_eq!(report.curate_stats.dropped_unmapped, 1); - assert_eq!(report.curate_stats.listing_collision_collapsed, 1); - assert_eq!(report.curate_stats.listing_collision_dropped, 2); -} - -struct FailingWriteSink { - fail_on_write: bool, - fail_on_flush: bool, -} - -impl Write for FailingWriteSink { - fn write(&mut self, buf: &[u8]) -> io::Result { - if self.fail_on_write { - Err(io::Error::new(io::ErrorKind::BrokenPipe, "injected write failure")) - } else { - Ok(buf.len()) - } - } - - fn flush(&mut self) -> io::Result<()> { - if self.fail_on_flush { - Err(io::Error::new(io::ErrorKind::BrokenPipe, "injected flush failure")) - } else { - Ok(()) - } - } -} - -struct FailingReader; - -impl io::Read for FailingReader { - fn read(&mut self, _buf: &mut [u8]) -> io::Result { - Err(io::Error::new(io::ErrorKind::UnexpectedEof, "injected read I/O failure")) - } -} - -fn list_dir_names(dir: &Path) -> Vec { - if !dir.exists() { - return Vec::new(); - } - let mut names: Vec = fs::read_dir(dir) - .expect("read_dir") - .map(|entry| { - entry - .expect("dir entry") - .file_name() - .to_string_lossy() - .into_owned() - }) - .collect(); - names.sort(); - names -} - -#[test] -fn fail_closed_validation_and_stream_and_writer_errors() { - let dir = TempDirGuard::new("bars1m-fail-closed"); - let mapping_path = write_mapping_tsv(dir.path(), &["eod\tAAA.US\t2020-01-01\t\t101"]); - let ts = et_ts_sec(2025, 5, 2, 10, 0); - let doc1 = make_intraday_doc("AAA.US", ts, 10.0, 11.0, 9.0, 10.5, 100.0); - let doc2 = make_intraday_doc("AAA.US", ts + 60, 10.5, 11.5, 10.0, 11.0, 200.0); - - // 1. Blank mapping_source - { - let mut sink = Vec::new(); - let writer = IlpShardedWriter::new(vec![&mut sink], IlpWriterOptions::default()).unwrap(); - let mut args = make_args( - mapping_path.clone(), - dir.path().join("splits.bson"), - dir.path().join("intraday.bson"), - dir.path().join("out-blank"), - 1, - 1_750_000_000_000_000, - BsonStreamOptions::default(), - ); - args.mapping_source = " ".to_string(); - let err = run_curate_bars_1m_with_readers( - &args, - Cursor::new(Vec::::new()), - Cursor::new(Vec::::new()), - writer, - ) - .unwrap_err(); - assert!(matches!(err, RunCurateBars1mError::EmptyMappingSource)); - } - - // 2. Unsupported mapping_source - { - let mut sink = Vec::new(); - let writer = IlpShardedWriter::new(vec![&mut sink], IlpWriterOptions::default()).unwrap(); - let mut args = make_args( - mapping_path.clone(), - dir.path().join("splits.bson"), - dir.path().join("intraday.bson"), - dir.path().join("out-unsup"), - 1, - 1_750_000_000_000_000, - BsonStreamOptions::default(), - ); - args.mapping_source = "qm".to_string(); - let err = run_curate_bars_1m_with_readers( - &args, - Cursor::new(Vec::::new()), - Cursor::new(Vec::::new()), - writer, - ) - .unwrap_err(); - assert!(matches!( - err, - RunCurateBars1mError::UnsupportedMappingSource { ref mapping_source } if mapping_source == "qm" - )); - } - - // 3. Zero shard_count - { - let args = make_args( - mapping_path.clone(), - dir.path().join("splits.bson"), - dir.path().join("intraday.bson"), - dir.path().join("out-zero"), - 0, - 1_750_000_000_000_000, - BsonStreamOptions::default(), - ); - let err = run_curate_bars_1m(&args).unwrap_err(); - assert!(matches!(err, RunCurateBars1mError::ZeroShardCount)); - assert!(!args.out_dir.exists()); - } - - // 4. Writer shard count mismatch - { - let mut sink = Vec::new(); - let writer = IlpShardedWriter::new(vec![&mut sink], IlpWriterOptions::default()).unwrap(); - let args = make_args( - mapping_path.clone(), - dir.path().join("splits.bson"), - dir.path().join("intraday.bson"), - dir.path().join("out-mismatch"), - 2, - 1_750_000_000_000_000, - BsonStreamOptions::default(), - ); - let err = run_curate_bars_1m_with_readers( - &args, - Cursor::new(Vec::::new()), - Cursor::new(Vec::::new()), - writer, - ) - .unwrap_err(); - assert!(matches!( - err, - RunCurateBars1mError::ShardCountMismatch { expected: 2, actual: 1 } - )); - } - - // 5. Missing input file - { - let args = make_args( - mapping_path.clone(), - dir.path().join("does-not-exist-splits.bson"), - dir.path().join("does-not-exist-intraday.bson"), - dir.path().join("out-missing"), - 1, - 1_750_000_000_000_000, - BsonStreamOptions::default(), - ); - let err = run_curate_bars_1m(&args).unwrap_err(); - assert!(matches!(err, RunCurateBars1mError::OpenInput { label: "qm-splits", .. })); - assert!(err.source().is_some()); - assert!(!args.out_dir.exists()); - } - - // 6. Truncated BSON tail after a successful first chunk -> BsonStream, no published files - { - let mut truncated = concat_docs(&[doc1.clone()]); - let partial = &doc2.as_bytes()[..doc2.as_bytes().len() - 5]; - truncated.extend_from_slice(partial); - - let splits_file = dir.path().join("empty_splits.bson"); - fs::write(&splits_file, []).unwrap(); - let intraday_file = dir.path().join("truncated_intraday.bson"); - fs::write(&intraday_file, &truncated).unwrap(); - let out_dir = dir.path().join("out-trunc"); - - let args = make_args( - mapping_path.clone(), - splits_file, - intraday_file, - out_dir.clone(), - 2, - 1_750_000_000_000_000, - BsonStreamOptions { - chunk_capacity_bytes: doc1.as_bytes().len(), - max_doc_bytes: doc1.as_bytes().len() + 64, - }, - ); - let err = run_curate_bars_1m(&args).unwrap_err(); - assert!(matches!(err, RunCurateBars1mError::BsonStream { label: "eod-intraday", .. })); - assert!(err.source().is_some()); - assert!(list_dir_names(&out_dir).is_empty(), "no final or staging files should remain"); - } - - // 7. Fatal read I/O error -> BsonStream, no published files - { - let out_dir = dir.path().join("out-io-read"); - let args = make_args( - mapping_path.clone(), - dir.path().join("splits.bson"), - dir.path().join("intraday.bson"), - out_dir.clone(), - 2, - 1_750_000_000_000_000, - BsonStreamOptions::default(), - ); - let err = run_curate_bars_1m_to_dir_with_hooks( - &args, - FailingReader, - Cursor::new(Vec::::new()), - |_idx, file| SyncedBufFile::new(file), - |_idx, _path| {}, - ) - .unwrap_err(); - assert!(matches!(err, RunCurateBars1mError::BsonStream { label: "eod-intraday", .. })); - assert!(err.source().is_some()); - assert!(list_dir_names(&out_dir).is_empty()); - } - - // 8. Failing sink on write -> CurateWrite(Ilp), no published files - { - let out_dir = dir.path().join("out-write-fail"); - let mut args = make_args( - mapping_path.clone(), - dir.path().join("splits.bson"), - dir.path().join("intraday.bson"), - out_dir.clone(), - 1, - 1_750_000_000_000_000, - BsonStreamOptions::default(), - ); - args.ilp_options.max_batch_rows = 1; - let err = run_curate_bars_1m_to_dir_with_hooks( - &args, - Cursor::new(concat_docs(&[doc1.clone()])), - Cursor::new(Vec::::new()), - |_idx, _file| FailingWriteSink { - fail_on_write: true, - fail_on_flush: false, - }, - |_idx, _path| {}, - ) - .unwrap_err(); - assert!(matches!( - err, - RunCurateBars1mError::CurateWrite(CurateBars1mWriteError::Ilp(IlpWriterError::Io { .. })) - )); - assert!(err.source().is_some()); - assert!(list_dir_names(&out_dir).is_empty()); - } - - // 9. Failing sink on finish flush -> Ilp(Io), no published files - { - let out_dir = dir.path().join("out-flush-fail"); - let args = make_args( - mapping_path.clone(), - dir.path().join("splits.bson"), - dir.path().join("intraday.bson"), - out_dir.clone(), - 1, - 1_750_000_000_000_000, - BsonStreamOptions::default(), - ); - let err = run_curate_bars_1m_to_dir_with_hooks( - &args, - Cursor::new(concat_docs(&[doc1.clone()])), - Cursor::new(Vec::::new()), - |_idx, _file| FailingWriteSink { - fail_on_write: false, - fail_on_flush: true, - }, - |_idx, _path| {}, - ) - .unwrap_err(); - assert!(matches!( - err, - RunCurateBars1mError::Ilp(IlpWriterError::Io { .. }) - )); - assert!(err.source().is_some()); - assert!(list_dir_names(&out_dir).is_empty()); - } -} - -#[test] -fn fail_closed_preexisting_and_post_preflight_rollback() { - let dir = TempDirGuard::new("bars1m-no-overwrite"); - let mapping_path = write_mapping_tsv(dir.path(), &["eod\tAAA.US\t2020-01-01\t\t101"]); - let ts = et_ts_sec(2025, 5, 2, 10, 0); - let intraday_bytes = concat_docs(&[make_intraday_doc("AAA.US", ts, 10.0, 11.0, 9.0, 10.5, 100.0)]); - let splits_file = dir.path().join("splits.bson"); - let intraday_file = dir.path().join("intraday.bson"); - fs::write(&splits_file, []).unwrap(); - fs::write(&intraday_file, &intraday_bytes).unwrap(); - - // Case A: pre-existing final shard file detected at preflight. - let out_preexisting = dir.path().join("out-preexisting"); - fs::create_dir_all(&out_preexisting).unwrap(); - let sentinel = b"existing-shard-bytes-must-not-change"; - let existing_path = out_preexisting.join("bars_1m.shard-01.ilp"); - fs::write(&existing_path, sentinel).unwrap(); - - let args_a = make_args( - mapping_path.clone(), - splits_file.clone(), - intraday_file.clone(), - out_preexisting.clone(), - 3, - 1_750_000_000_000_000, - BsonStreamOptions::default(), - ); - let err_a = run_curate_bars_1m(&args_a).unwrap_err(); - assert!(matches!( - err_a, - RunCurateBars1mError::OutputFileExists { ref path } if path == &existing_path - )); - assert_eq!(fs::read(&existing_path).unwrap(), sentinel); - assert_eq!(list_dir_names(&out_preexisting), vec!["bars_1m.shard-01.ilp"]); - - // Case B: destination appears AFTER preflight on shard 1 (after shard 0 has been linked). - // Shard 0 must be rolled back, shard 1's external file must remain intact, and no .tmp survives. - let out_race = dir.path().join("out-race"); - let args_b = make_args( - mapping_path, - splits_file, - intraday_file, - out_race.clone(), - 3, - 1_750_000_000_000_000, - BsonStreamOptions::default(), - ); - let race_sentinel = b"concurrent-writer-shard-01"; - let err_b = run_curate_bars_1m_to_dir_with_hooks( - &args_b, - Cursor::new(&intraday_bytes), - Cursor::new(Vec::::new()), - |_idx, file| SyncedBufFile::new(file), - |shard_idx, final_path| { - if shard_idx == 1 { - fs::write(final_path, race_sentinel).expect("inject concurrent final shard"); - } - }, - ) - .unwrap_err(); - let expected_race_path = out_race.join("bars_1m.shard-01.ilp"); - assert!(matches!( - err_b, - RunCurateBars1mError::OutputFileExists { ref path } if path == &expected_race_path - )); - assert_eq!(fs::read(&expected_race_path).unwrap(), race_sentinel); - assert_eq!(list_dir_names(&out_race), vec!["bars_1m.shard-01.ilp"]); - - // Case C: stale final shard OUTSIDE the requested shard_count range (e.g. bars_1m.shard-03.ilp - // left over from a prior 4-shard export when retrying with shard_count = 2). Preflight must - // reject it, preserve its bytes, and create no new files. - let out_stale = dir.path().join("out-stale-shard"); - fs::create_dir_all(&out_stale).unwrap(); - let stale_sentinel = b"stale-shard-03-from-prior-four-shard-export"; - let stale_path = out_stale.join("bars_1m.shard-03.ilp"); - fs::write(&stale_path, stale_sentinel).unwrap(); - - let args_c = make_args( - dir.path().join("provider_mapping.tsv"), - dir.path().join("splits.bson"), - dir.path().join("intraday.bson"), - out_stale.clone(), - 2, - 1_750_000_000_000_000, - BsonStreamOptions::default(), - ); - let err_c = run_curate_bars_1m(&args_c).unwrap_err(); - assert!(matches!( - err_c, - RunCurateBars1mError::OutputFileExists { ref path } if path == &stale_path - )); - assert_eq!(fs::read(&stale_path).unwrap(), stale_sentinel); - assert_eq!(list_dir_names(&out_stale), vec!["bars_1m.shard-03.ilp"]); -} - -#[test] -fn file_mode_publishes_exact_zero_padded_shards_including_empty_shards() { - let dir = TempDirGuard::new("bars1m-file-mode"); - let known_at_micros: i64 = 1_750_900_000_000_000; - let shard_count = 4usize; - - let mapping_path = write_mapping_tsv( - dir.path(), - &[ - "eod\tAAA.US\t2020-01-01\t\t1001", - "eod\tBBB.US\t2020-01-01\t\t2002", - ], - ); - let splits_file = dir.path().join("qmSplits.bson"); - fs::write(&splits_file, []).unwrap(); - - let intraday_bytes = concat_docs(&[ - make_intraday_doc("AAA.US", et_ts_sec(2025, 5, 5, 9, 30), 10.0, 10.5, 9.9, 10.2, 100.0), - make_intraday_doc("AAA.US", et_ts_sec(2025, 5, 5, 9, 31), 10.2, 10.6, 10.1, 10.4, 150.0), - make_intraday_doc("BBB.US", et_ts_sec(2025, 5, 5, 9, 30), 25.0, 25.4, 24.8, 25.1, 500.0), - ]); - let intraday_file = dir.path().join("eodIntraday1M.bson"); - fs::write(&intraday_file, &intraday_bytes).unwrap(); - - let out_dir = dir.path().join("shards_out"); - let args = make_args( - mapping_path, - splits_file, - intraday_file, - out_dir.clone(), - shard_count, - known_at_micros, - BsonStreamOptions::default(), - ); - - let report = run_curate_bars_1m(&args).expect("file-mode run should succeed"); - assert_report_conservation(&report); - assert_eq!(report.rows_written, 3); - - assert_eq!( - list_dir_names(&out_dir), - vec![ - "bars_1m.shard-00.ilp", - "bars_1m.shard-01.ilp", - "bars_1m.shard-02.ilp", - "bars_1m.shard-03.ilp", - ] - ); - - let mut total_rows = 0usize; - let mut total_bytes = 0usize; - let mut empty_shards = 0usize; - let mut listing_counts: BTreeMap = BTreeMap::new(); - - for shard_idx in 0..shard_count { - let path = out_dir.join(format!("bars_1m.shard-{shard_idx:02}.ilp")); - let bytes = fs::read(&path).expect("read shard file"); - total_bytes += bytes.len(); - let rows = decode_ilp_bars_1m(&bytes); - if rows.is_empty() { - empty_shards += 1; - } - assert_eq!( - rows.len(), - report.ilp_stats.per_shard_rows[shard_idx], - "shard {shard_idx} row count mismatch" - ); - for row in &rows { - assert_eq!( - shard_for_listing_id(row.listing_id, shard_count), - shard_idx, - "row landed on wrong shard" - ); - assert_eq!(row.known_at, known_at_micros); - *listing_counts.entry(row.listing_id).or_default() += 1; - } - total_rows += rows.len(); - } - - assert!(empty_shards >= 2, "expected at least 2 empty shards with 2 listings across 4 shards"); - assert_eq!(total_rows, report.rows_written); - assert_eq!(total_bytes, report.ilp_stats.bytes); - assert_eq!(listing_counts.get(&1001), Some(&2)); - assert_eq!(listing_counts.get(&2002), Some(&1)); -} - -// --------------------------------------------------------------------------------------------- -// QA (T-179) edge cases: legacy-path equivalence, ET-vs-UTC ex-date boundary, replay determinism. -// --------------------------------------------------------------------------------------------- - -/// Pinned fixture for the QA equivalence test. Non-reused tickers only, so the legacy -/// source-keyed `curate_bars_1m` (splits keyed by EOD ticker, un-adjusted inside the builder) and -/// the runner's listing-keyed path must agree bitwise on rows and on every stats counter, -/// including rows dropped only *after* un-adjustment (overflow to inf, volume underflow to 0) and -/// a key whose every row is dropped after un-adjustment (`builder.keys_out` decrement). -#[test] -fn qa_listing_keyed_runner_matches_legacy_source_keyed_curation_including_post_unadjust_drops() { - let dir = TempDirGuard::new("bars1m-qa-legacy-eq"); - let known_at_micros: i64 = 1_760_000_000_000_000; - - let mapping_path = write_mapping_tsv( - dir.path(), - &[ - "eod\tNVDA.US\t2020-01-01\t\t1001", - "qm\tNVDA\t2020-01-01\t\t1001", - "eod\tOVF.US\t2020-01-01\t\t1002", - "qm\tOVF\t2020-01-01\t\t1002", - "eod\tREV.US\t2020-01-01\t\t1003", - "qm\tREV\t2020-01-01\t\t1003", - ], - ); - let splits_bytes = concat_docs(&[ - make_split_doc("NVDA", "2024-06-10", 1.0, 10.0), - make_split_doc("OVF", "2024-06-10", 1.0, 10.0), - make_split_doc("REV", "2024-06-10", 20.0, 1.0), - ]); - - let t = |d: u32, h: u8, m: u8| et_ts_sec(2024, 6, d, h, m); - let docs = vec![ - // NVDA: normal pre-split bar, pre-split overflow bar (price * 10 -> inf), pre-split - // volume underflow (5e-324 / 10 -> 0), identical duplicate, conflicting duplicate, ex-date bar. - make_intraday_doc("NVDA.US", t(7, 10, 0), 120.0, 121.0, 119.0, 120.5, 1_000.0), - make_intraday_doc("NVDA.US", t(7, 10, 1), 1e308, 1e308, 1e308, 1e308, 10.0), - make_intraday_doc("NVDA.US", t(7, 10, 2), 120.0, 121.0, 119.0, 120.5, 5e-324), - make_intraday_doc("NVDA.US", t(7, 10, 3), 120.0, 121.0, 119.0, 120.5, 7.0), - make_intraday_doc("NVDA.US", t(7, 10, 3), 120.0, 121.0, 119.0, 120.5, 7.0), - make_intraday_doc("NVDA.US", t(7, 10, 4), 120.0, 121.0, 119.0, 120.5, 7.0), - make_intraday_doc("NVDA.US", t(7, 10, 4), 120.0, 121.0, 119.0, 120.6, 7.0), - make_intraday_doc("NVDA.US", t(10, 10, 0), 121.0, 122.0, 120.0, 121.5, 3_000.0), - // OVF: every row overflows after un-adjustment -> key contributes nothing. - make_intraday_doc("OVF.US", t(7, 9, 45), 1e308, 1e308, 1e308, 1e308, 1.0), - make_intraday_doc("OVF.US", t(7, 16, 30), 1.5e308, 1.5e308, 1.5e308, 1.5e308, 1.0), - // REV: reverse split (factor 0.05) scales prices down / volume up. - make_intraday_doc("REV.US", t(7, 8, 0), 24.0, 24.6, 23.8, 24.2, 2_000.0), - make_intraday_doc("REV.US", t(10, 15, 59), 1.2, 1.3, 1.1, 1.25, 40_000.0), - // Unmapped code. - make_intraday_doc("ZZZ.US", t(7, 10, 0), 5.0, 5.0, 5.0, 5.0, 1.0), - ]; - let intraday_bytes = concat_docs(&docs); - - // Runner path. - let mut sink0 = Vec::new(); - let mut sink1 = Vec::new(); - let mut sink2 = Vec::new(); - let writer = IlpShardedWriter::new( - vec![&mut sink0, &mut sink1, &mut sink2], - IlpWriterOptions::default(), - ) - .unwrap(); - let args = make_args( - mapping_path.clone(), - dir.path().join("qmSplits.bson"), - dir.path().join("eodIntraday1M.bson"), - dir.path().join("out"), - 3, - known_at_micros, - BsonStreamOptions::default(), - ); - let report = run_curate_bars_1m_with_readers( - &args, - Cursor::new(&intraday_bytes), - Cursor::new(&splits_bytes), - writer, - ) - .expect("runner should succeed"); - assert_report_conservation(&report); - assert_eq!(report.chunks, 1, "fixture must fit one default chunk for a 1:1 comparison"); - - // Legacy path: splits keyed by EOD ticker, un-adjusted inside `build_bars_1m`. - let mapping_rows = load_provider_mapping_tsv(&mapping_path).unwrap(); - let mapping = ProviderMappingTable::from_rows(mapping_rows).unwrap(); - let ex = day(2024, 6, 10); - let legacy_splits = SplitTable::>::from_events(vec![ - (Arc::::from("NVDA.US"), crate::split::SplitEvent { ex_date: ex, ratio: 10.0 }), - (Arc::::from("OVF.US"), crate::split::SplitEvent { ex_date: ex, ratio: 10.0 }), - (Arc::::from("REV.US"), crate::split::SplitEvent { ex_date: ex, ratio: 0.05 }), - ]) - .unwrap(); - let mut legacy_bars: Vec>> = Vec::new(); - crate::bson_eod_intraday::decode_eod_intraday_buffer( - &intraday_bytes, - |raw| { - let key: Arc = Arc::from(raw.eod_search_code); - legacy_bars.push(raw.into_eod_intraday_bar(|_, _| key)); - }, - |_, _| {}, - ); - let legacy = crate::curate_bars_1m::curate_bars_1m( - legacy_bars, - &legacy_splits, - &mapping, - DEFAULT_BARS_1M_MAPPING_SOURCE, - ) - .unwrap(); - - // Stats: every counter identical (single chunk, so per-chunk sums are exact). - assert_eq!(report.curate_stats, legacy.stats); - let b = &report.curate_stats.builder; - assert_eq!(b.dropped_invalid_ohlc, 3, "NVDA overflow + 2 OVF overflow rows"); - assert_eq!(b.dropped_invalid_volume, 1, "NVDA volume underflow"); - assert_eq!(b.duplicate_collapsed, 1); - assert_eq!(b.duplicate_conflict_dropped, 2); - assert_eq!(b.keys_out, 3, "NVDA, REV, ZZZ keep rows; OVF must not be counted"); - assert_eq!(report.curate_stats.dropped_unmapped, 1); - assert_eq!(report.curate_stats.listings_out, 2); - assert_eq!(report.rows_written, 5); - - // Rows: bitwise identical multiset. - let mut runner_rows: Vec<_> = [&sink0, &sink1, &sink2] - .iter() - .flat_map(|s| decode_ilp_bars_1m(s)) - .map(|r| { - assert_eq!(r.known_at, known_at_micros); - r.sort_key() - }) - .collect(); - runner_rows.sort_unstable(); - let mut legacy_rows: Vec<_> = legacy - .rows - .iter() - .map(|r| { - ( - r.key, - r.ts, - r.open.to_bits(), - r.high.to_bits(), - r.low.to_bits(), - r.close.to_bits(), - r.volume.to_bits(), - known_at_micros, - ) - }) - .collect(); - legacy_rows.sort_unstable(); - assert_eq!(runner_rows, legacy_rows); -} - -/// The split factor is chosen from the bar's Eastern Time `session_date`, not its UTC date. -/// A POST bar at 21:00 ET on 2024-06-07 (Friday) is 01:00 UTC on 2024-06-08, and a POST bar at -/// 20:30 ET on Sunday 2024-06-09 is 00:30 UTC on the 2024-06-10 ex-date: both belong to pre-split -/// ET sessions and must be un-adjusted. A PRE bar at 04:00 ET on the ex-date (08:00 UTC) must be -/// left unchanged. -#[test] -fn qa_split_factor_uses_eastern_session_date_not_utc_date_around_ex_date() { - let dir = TempDirGuard::new("bars1m-qa-et-boundary"); - let mapping_path = write_mapping_tsv( - dir.path(), - &["eod\tNVDA.US\t2020-01-01\t\t1001", "qm\tNVDA\t2020-01-01\t\t1001"], - ); - let splits_bytes = concat_docs(&[make_split_doc("NVDA", "2024-06-10", 1.0, 10.0)]); - - let fri_late = et_ts_sec(2024, 6, 7, 21, 0); - let sun_late = et_ts_sec(2024, 6, 9, 20, 30); - let ex_pre = et_ts_sec(2024, 6, 10, 4, 0); - // Sanity: the UTC calendar date of the late bars is later than their ET session date. - assert_eq!(fri_late.div_euclid(86_400) as i32, day(2024, 6, 8)); - assert_eq!(sun_late.div_euclid(86_400) as i32, day(2024, 6, 10)); - - let intraday_bytes = concat_docs(&[ - make_intraday_doc("NVDA.US", fri_late, 120.0, 121.0, 119.0, 120.5, 500.0), - make_intraday_doc("NVDA.US", sun_late, 120.0, 121.0, 119.0, 120.5, 500.0), - make_intraday_doc("NVDA.US", ex_pre, 120.0, 121.0, 119.0, 120.5, 500.0), - ]); - - let mut sink = Vec::new(); - let writer = IlpShardedWriter::new(vec![&mut sink], IlpWriterOptions::default()).unwrap(); - let args = make_args( - mapping_path, - dir.path().join("qmSplits.bson"), - dir.path().join("eodIntraday1M.bson"), - dir.path().join("out"), - 1, - 1_760_000_000_000_000, - BsonStreamOptions::default(), - ); - let report = run_curate_bars_1m_with_readers( - &args, - Cursor::new(&intraday_bytes), - Cursor::new(&splits_bytes), - writer, - ) - .unwrap(); - assert_report_conservation(&report); - assert_eq!(report.rows_written, 3); - - let rows = decode_ilp_bars_1m(&sink); - let by_ts = |ts_sec: i64| rows.iter().find(|r| r.ts == ts_sec * 1_000_000).unwrap(); - - for ts in [fri_late, sun_late] { - let r = by_ts(ts); - assert_eq!(r.session, IntradaySession::Post); - assert_eq!(r.close.to_bits(), (120.5_f64 * 10.0).to_bits(), "ts={ts}"); - assert_eq!(r.volume.to_bits(), (500.0_f64 / 10.0).to_bits(), "ts={ts}"); - } - let r = by_ts(ex_pre); - assert_eq!(r.session, IntradaySession::Pre); - assert_eq!(r.close.to_bits(), 120.5_f64.to_bits()); - assert_eq!(r.volume.to_bits(), 500.0_f64.to_bits()); -} - -/// Replay: the same pinned inputs and settings run twice through the public file-mode entry -/// produce byte-identical shard files and an identical report (ignoring wall-clock -/// `elapsed_secs`), and the formatted report is identical apart from its `timing:` line. -#[test] -fn qa_file_mode_replay_is_byte_identical_and_report_deterministic() { - let dir = TempDirGuard::new("bars1m-qa-replay"); - let mapping_path = write_mapping_tsv( - dir.path(), - &[ - "eod\tAAA.US\t2020-01-01\t\t11", - "eod\tBBB.US\t2020-01-01\t\t12", - "eod\tCCC.US\t2020-01-01\t\t13", - "qm\tAAA\t2020-01-01\t\t11", - ], - ); - let splits_path = dir.path().join("qmSplits.bson"); - fs::write(&splits_path, concat_docs(&[make_split_doc("AAA", "2025-03-11", 1.0, 4.0)])).unwrap(); - - let mut docs = Vec::new(); - for (i, code) in ["AAA.US", "BBB.US", "CCC.US", "NOPE.US"].iter().enumerate() { - for m in 0..6u8 { - let px = 10.0 + i as f64 + f64::from(m) * 0.01; - docs.push(make_intraday_doc( - code, - et_ts_sec(2025, 3, 10 + u32::from(m % 2), 9 + m, 30), - px, - px + 0.1, - px - 0.1, - px, - 100.0 + f64::from(m), - )); - } - } - let intraday_path = dir.path().join("eodIntraday1M.bson"); - fs::write(&intraday_path, concat_docs(&docs)).unwrap(); - - let small = BsonStreamOptions { - chunk_capacity_bytes: docs[0].as_bytes().len() * 5, - ..BsonStreamOptions::default() - }; - - let run = |out: &str| { - let out_dir = dir.path().join(out); - let args = make_args( - mapping_path.clone(), - splits_path.clone(), - intraday_path.clone(), - out_dir.clone(), - 3, - 1_760_000_000_000_000, - small, - ); - let report = run_curate_bars_1m(&args).expect("file-mode run"); - let files: Vec<(String, Vec)> = list_dir_names(&out_dir) - .into_iter() - .map(|name| { - let bytes = fs::read(out_dir.join(&name)).unwrap(); - (name, bytes) - }) - .collect(); - (report, files) - }; - - let (mut r1, f1) = run("out-a"); - let (mut r2, f2) = run("out-b"); - assert!(r1.chunks >= 3, "fixture must span several chunks, got {}", r1.chunks); - assert_report_conservation(&r1); - assert_eq!(f1.len(), 3); - assert_eq!(f1, f2, "replayed shard files differ"); - - let strip_timing = |s: String| { - s.lines() - .filter(|l| !l.trim_start().starts_with("timing:")) - .collect::>() - .join("\n") - }; - let fmt1 = strip_timing(format_curate_bars_1m_report(&r1)); - let fmt2 = strip_timing(format_curate_bars_1m_report(&r2)); - assert_eq!(fmt1, fmt2); - assert!(fmt1.contains(&format!("chunks={}", r1.chunks))); - assert!(fmt1.contains("cross_chunk_dedup=questdb_dedup_upsert_keys(ts,listing_id)")); - assert!(fmt1.contains(&format!("rows_written={}", r1.rows_written))); - assert!(fmt1.contains("listings_out_per_chunk_sum=")); - - r1.elapsed_secs = 0.0; - r2.elapsed_secs = 0.0; - assert_eq!(r1, r2); - - // Shard bytes match the report and every row lives on its assigned shard. - let mut total_rows = 0usize; - for (idx, (name, bytes)) in f1.iter().enumerate() { - assert_eq!(name, &format!("bars_1m.shard-{idx:02}.ilp")); - let rows = decode_ilp_bars_1m(bytes); - assert_eq!(rows.len(), r1.ilp_stats.per_shard_rows[idx]); - for row in &rows { - assert_eq!(shard_for_listing_id(row.listing_id, 3), idx); - } - total_rows += rows.len(); - } - assert_eq!(total_rows, r1.rows_written); - assert_eq!(f1.iter().map(|(_, b)| b.len()).sum::(), r1.ilp_stats.bytes); -} - -/// A missing intraday input on the public file-mode entry fails before `out_dir` is created. -#[test] -fn qa_missing_intraday_input_fails_before_creating_out_dir() { - let dir = TempDirGuard::new("bars1m-qa-missing-intraday"); - let mapping_path = write_mapping_tsv(dir.path(), &["eod\tAAA.US\t2020-01-01\t\t11"]); - let splits_path = dir.path().join("qmSplits.bson"); - fs::write(&splits_path, b"").unwrap(); - let out_dir = dir.path().join("never-created"); - let args = make_args( - mapping_path, - splits_path, - dir.path().join("missing-eodIntraday1M.bson"), - out_dir.clone(), - 2, - 1, - BsonStreamOptions::default(), - ); - let err = run_curate_bars_1m(&args).unwrap_err(); - assert!( - matches!(err, RunCurateBars1mError::OpenInput { label: "eod-intraday", .. }), - "{err:?}" - ); - assert!(err.source().is_some()); - assert!(!out_dir.exists()); -} - -/// QA (T-179): a truncated `qmSplits` tail is a fatal reference-load error in file mode. The run -/// must return `LoadReference(BsonStream { label: "qm-splits" })` and publish nothing: no final -/// `bars_1m.shard-*.ilp` and no staging file, and a pre-existing unrelated file is untouched. -#[test] -fn qa_truncated_qm_splits_fails_closed_in_file_mode_without_outputs() { - let dir = TempDirGuard::new("bars1m-qa-trunc-splits"); - let mapping_path = write_mapping_tsv( - dir.path(), - &["eod\tAAA.US\t2020-01-01\t\t11", "qm\tAAA\t2020-01-01\t\t11"], - ); - let mut splits_bytes = concat_docs(&[ - make_split_doc("AAA", "2025-05-06", 1.0, 2.0), - make_split_doc("AAA", "2025-07-01", 1.0, 3.0), - ]); - splits_bytes.truncate(splits_bytes.len() - 5); - let splits_path = dir.path().join("qmSplits.bson"); - fs::write(&splits_path, &splits_bytes).unwrap(); - - let intraday_path = dir.path().join("eodIntraday1M.bson"); - fs::write( - &intraday_path, - concat_docs(&[make_intraday_doc( - "AAA.US", - et_ts_sec(2025, 5, 5, 10, 0), - 10.0, - 10.5, - 9.5, - 10.2, - 100.0, - )]), - ) - .unwrap(); - - let out_dir = dir.path().join("out"); - fs::create_dir_all(&out_dir).unwrap(); - fs::write(out_dir.join("keep.txt"), b"keep").unwrap(); - - let args = make_args( - mapping_path, - splits_path, - intraday_path, - out_dir.clone(), - 2, - 1, - BsonStreamOptions::default(), - ); - let err = run_curate_bars_1m(&args).unwrap_err(); - assert!( - matches!( - err, - RunCurateBars1mError::LoadReference(RunCurateBarsError::BsonStream { - label: "qm-splits", - .. - }) - ), - "{err:?}" - ); - assert!(err.source().is_some()); - assert_eq!(list_dir_names(&out_dir), vec!["keep.txt"]); - assert_eq!(fs::read(out_dir.join("keep.txt")).unwrap(), b"keep"); -} - -/// QA (T-179): listing-keyed splits apply to every `"eod"` alias of the same listing. Two EOD -/// tickers mapped to listing 77 over consecutive ranges both receive the 2:1 split (ex-date -/// 2025-06-02); an unrelated listing without splits is untouched. -#[test] -fn qa_listing_split_applies_to_all_eod_aliases_of_the_listing() { - let dir = TempDirGuard::new("bars1m-qa-aliases"); - let mapping_path = write_mapping_tsv( - dir.path(), - &[ - "eod\tOLD.US\t2020-01-01\t2025-05-15\t77", - "eod\tNEW.US\t2025-05-16\t\t77", - "qm\tNEWQ\t2020-01-01\t\t77", - "eod\tOTH.US\t2020-01-01\t\t88", - ], - ); - let splits_bytes = concat_docs(&[make_split_doc("NEWQ", "2025-06-02", 1.0, 2.0)]); - let intraday_bytes = concat_docs(&[ - make_intraday_doc("OLD.US", et_ts_sec(2025, 5, 14, 10, 0), 10.0, 11.0, 9.0, 10.5, 200.0), - make_intraday_doc("NEW.US", et_ts_sec(2025, 5, 20, 10, 0), 12.0, 13.0, 11.0, 12.5, 400.0), - make_intraday_doc("NEW.US", et_ts_sec(2025, 6, 2, 10, 0), 6.0, 6.5, 5.5, 6.25, 800.0), - make_intraday_doc("OTH.US", et_ts_sec(2025, 5, 20, 10, 0), 20.0, 21.0, 19.0, 20.5, 50.0), - // OLD.US after its mapping range closed: unmapped, never mis-attributed. - make_intraday_doc("OLD.US", et_ts_sec(2025, 5, 20, 10, 0), 1.0, 1.0, 1.0, 1.0, 1.0), - ]); - - let mut sink = Vec::new(); - let writer = IlpShardedWriter::new(vec![&mut sink], IlpWriterOptions::default()).unwrap(); - let args = make_args( - mapping_path, - dir.path().join("qmSplits.bson"), - dir.path().join("eodIntraday1M.bson"), - dir.path().join("out"), - 1, - 42, - BsonStreamOptions::default(), - ); - let report = run_curate_bars_1m_with_readers( - &args, - Cursor::new(&intraday_bytes), - Cursor::new(&splits_bytes), - writer, - ) - .expect("alias run should succeed"); - assert_report_conservation(&report); - assert_eq!(report.split_rekey.splits_applied, 1); - assert_eq!(report.curate_stats.dropped_unmapped, 1); - assert_eq!(report.rows_written, 4); - - let rows = decode_ilp_bars_1m(&sink); - let get = |id: i32, ts: i64| { - rows.iter() - .find(|r| r.listing_id == id && r.ts == ts * 1_000_000) - .expect("row") - .clone() - }; - let old = get(77, et_ts_sec(2025, 5, 14, 10, 0)); - assert_eq!((old.close, old.volume), (21.0, 100.0)); - let new_pre = get(77, et_ts_sec(2025, 5, 20, 10, 0)); - assert_eq!((new_pre.close, new_pre.volume), (25.0, 200.0)); - let new_ex = get(77, et_ts_sec(2025, 6, 2, 10, 0)); - assert_eq!((new_ex.close, new_ex.volume), (6.25, 800.0)); - let oth = get(88, et_ts_sec(2025, 5, 20, 10, 0)); - assert_eq!((oth.close, oth.volume), (20.5, 50.0)); -} diff --git a/tools/curate-etl/src/run_curate_bars_tests.rs b/tools/curate-etl/src/run_curate_bars_tests.rs deleted file mode 100644 index 7faf57f2..00000000 --- a/tools/curate-etl/src/run_curate_bars_tests.rs +++ /dev/null @@ -1,1775 +0,0 @@ -use std::fs::{self, File}; -use std::io::Write; -use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering}; - -use bson::raw::{cstr, RawDocumentBuf}; -use parquet::file::reader::{FileReader, SerializedFileReader}; -use parquet::record::{Field, RowAccessor}; - -use super::*; -use crate::bson_stream::DEFAULT_MAX_DOC_BYTES; -use crate::curate_bars::BARS_1D_SOURCE_EOD; -use crate::session_close::et_session_close_utc_micros; -use crate::split::ymd_to_epoch_days; - -static TEST_DIR_SEQ: AtomicU64 = AtomicU64::new(0); - -struct TestTempDir { - path: PathBuf, -} - -impl TestTempDir { - fn new(tag: &str) -> Self { - let pid = std::process::id(); - let seq = TEST_DIR_SEQ.fetch_add(1, Ordering::Relaxed); - let path = std::env::temp_dir().join(format!("curate-etl-run-bars-{tag}-{pid}-{seq}")); - fs::create_dir_all(&path).expect("create test temp dir"); - Self { path } - } - - fn path(&self) -> &Path { - &self.path - } -} - -impl Drop for TestTempDir { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.path); - } -} - -fn eod_doc( - code: &str, - date: &str, - open: f64, - high: f64, - low: f64, - close: f64, - volume: f64, -) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), code); - doc.append(cstr!("date"), date); - doc.append(cstr!("open"), open); - doc.append(cstr!("high"), high); - doc.append(cstr!("low"), low); - doc.append(cstr!("close"), close); - doc.append(cstr!("volume"), volume); - doc.into_bytes() -} - -fn split_doc(code: &str, date: &str, ratio: f64) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), code); - doc.append(cstr!("date"), date); - if ratio.is_finite() && ratio > 0.0 { - doc.append(cstr!("splitratio"), 1.0 / ratio); - doc.append(cstr!("forfactor"), 1.0_f64); - doc.append(cstr!("tofactor"), ratio); - } else { - doc.append(cstr!("splitratio"), ratio); - } - doc.into_bytes() -} - -fn write_bytes(path: &Path, bytes: &[u8]) { - let mut f = File::create(path).expect("create fixture file"); - f.write_all(bytes).expect("write fixture bytes"); -} - -#[derive(Debug, PartialEq)] -struct ReadBarRow { - listing_id: i32, - ts_micros: i64, - session_date: i32, - open: f64, - high: f64, - low: f64, - close: f64, - volume: f64, - vwap: Option, - currency: String, - source: String, - known_at_micros: i64, -} - -fn read_parquet_bars(path: &Path) -> Vec { - let file = File::open(path).expect("open parquet file"); - let reader = SerializedFileReader::new(file).expect("open parquet reader"); - let iter = reader.get_row_iter(None).expect("row iter"); - let mut rows = Vec::new(); - for row_res in iter { - let row = row_res.expect("read row"); - let vwap = row.get_double(8).ok(); - let session_date = match row.get_column_iter().nth(2).expect("session_date col").1 { - Field::Date(d) => *d, - other => panic!("expected Field::Date for session_date, got {other:?}"), - }; - rows.push(ReadBarRow { - listing_id: row.get_int(0).expect("listing_id"), - ts_micros: row.get_timestamp_micros(1).expect("ts"), - session_date, - open: row.get_double(3).expect("open"), - high: row.get_double(4).expect("high"), - low: row.get_double(5).expect("low"), - close: row.get_double(6).expect("close"), - volume: row.get_double(7).expect("volume"), - vwap, - currency: row.get_string(9).expect("currency").to_owned(), - source: row.get_string(10).expect("source").to_owned(), - known_at_micros: row.get_timestamp_micros(11).expect("known_at"), - }); - } - rows -} - -fn strip_timing_line(report: &str) -> String { - report - .lines() - .filter(|line| !line.trim_start().starts_with("timing:")) - .collect::>() - .join("\n") -} - -#[test] -fn end_to_end_happy_path_nvda_cross_provider_split() { - let dir = TestTempDir::new("happy-nvda"); - let eod_path = dir.path().join("eodPrices.bson"); - let splits_path = dir.path().join("qmSplits.bson"); - let map_path = dir.path().join("provider_mapping.tsv"); - let curr_path = dir.path().join("listing_currencies.tsv"); - let out_dir = dir.path().join("out"); - - // NVDA: qmSearchCode = "NVDA:US", eodSearchCode = "NVDA.US", both -> listing_id 100. - // SHOP: CAD listing in 2023 -> listing_id 200. - write_bytes( - &map_path, - b"eod\tNVDA.US\t2010-01-01\t\t100\n\ - qm\tNVDA:US\t2010-01-01\t\t100\n\ - eod\tSHOP.TO\t2015-01-01\t\t200\n", - ); - write_bytes(&curr_path, b"100\tUSD\n200\tCAD\n"); - - // 10:1 forward split on 2024-06-10 keyed by qmSearchCode. - write_bytes(&splits_path, &split_doc("NVDA:US", "2024-06-10", 10.0)); - - // Pre-split 2024-06-07: raw OHLC ~$1208, adj_volume = 410_000_000 (10x raw 41_000_000). - // Ex-date 2024-06-10: raw OHLC ~$121, volume = 310_000_000 (not divided). - // Post-split 2024-06-11: raw OHLC ~$121, volume = 220_000_000 (not divided). - // 2023 bar for SHOP.TO. - let mut eod_bytes = Vec::new(); - eod_bytes.extend_from_slice(&eod_doc( - "NVDA.US", - "2024-06-07", - 1197.70, - 1216.92, - 1180.22, - 1208.88, - 410_000_000.0, - )); - eod_bytes.extend_from_slice(&eod_doc( - "NVDA.US", - "2024-06-10", - 120.37, - 123.10, - 117.01, - 121.79, - 310_000_000.0, - )); - eod_bytes.extend_from_slice(&eod_doc( - "NVDA.US", - "2024-06-11", - 121.77, - 122.87, - 118.74, - 120.91, - 220_000_000.0, - )); - eod_bytes.extend_from_slice(&eod_doc( - "SHOP.TO", - "2023-12-29", - 103.0, - 104.5, - 102.0, - 103.5, - 1_500_000.0, - )); - write_bytes(&eod_path, &eod_bytes); - - let args = CurateBars1dArgs { - eod_prices: eod_path, - qm_splits: splits_path, - qm_prices: None, - provider_mapping: map_path, - listing_currencies: curr_path, - out_dir: out_dir.clone(), - rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, - threads: 1, - }; - - let report = run_curate_bars_1d(&args).expect("curate-bars-1d happy path"); - assert_eq!(report.eod_docs_framed, 4); - assert_eq!(report.eod_decode.decoded, 4); - assert_eq!(report.splits_docs_framed, 1); - assert_eq!(report.split_rekey.splits_applied, 1); - assert_eq!(report.write_stats.rows_written, 4); - assert_eq!(report.write_stats.files_written, 2); - assert_eq!(report.write_stats.rows_by_year.get(&2023), Some(&1)); - assert_eq!(report.write_stats.rows_by_year.get(&2024), Some(&3)); - - let rows_2024 = read_parquet_bars(&out_dir.join("bars_1d/year=2024/part.parquet")); - assert_eq!(rows_2024.len(), 3); - - let d_pre = ymd_to_epoch_days(2024, 6, 7).unwrap(); - let d_ex = ymd_to_epoch_days(2024, 6, 10).unwrap(); - let d_post = ymd_to_epoch_days(2024, 6, 11).unwrap(); - - // Pre-split: volume divided by 10, OHLC bit-identical, raw dollar volume exact. - assert_eq!(rows_2024[0].listing_id, 100); - assert_eq!(rows_2024[0].session_date, d_pre); - assert_eq!(rows_2024[0].ts_micros, et_session_close_utc_micros(d_pre).unwrap()); - assert_eq!(rows_2024[0].known_at_micros, rows_2024[0].ts_micros); - assert_eq!(rows_2024[0].open.to_bits(), 1197.70_f64.to_bits()); - assert_eq!(rows_2024[0].high.to_bits(), 1216.92_f64.to_bits()); - assert_eq!(rows_2024[0].low.to_bits(), 1180.22_f64.to_bits()); - assert_eq!(rows_2024[0].close.to_bits(), 1208.88_f64.to_bits()); - assert_eq!(rows_2024[0].volume.to_bits(), 41_000_000.0_f64.to_bits()); - assert!((rows_2024[0].close * rows_2024[0].volume - 1208.88 * 41_000_000.0).abs() < 1e-6); - assert_eq!(rows_2024[0].vwap, None); - assert_eq!(rows_2024[0].currency, "USD"); - assert_eq!(rows_2024[0].source, BARS_1D_SOURCE_EOD); - - // Ex-date: NOT divided. - assert_eq!(rows_2024[1].session_date, d_ex); - assert_eq!(rows_2024[1].close.to_bits(), 121.79_f64.to_bits()); - assert_eq!(rows_2024[1].volume.to_bits(), 310_000_000.0_f64.to_bits()); - assert!((rows_2024[1].close * rows_2024[1].volume - 121.79 * 310_000_000.0).abs() < 1e-6); - - // Post-split: NOT divided. - assert_eq!(rows_2024[2].session_date, d_post); - assert_eq!(rows_2024[2].volume.to_bits(), 220_000_000.0_f64.to_bits()); - - let rows_2023 = read_parquet_bars(&out_dir.join("bars_1d/year=2023/part.parquet")); - assert_eq!(rows_2023.len(), 1); - assert_eq!(rows_2023[0].listing_id, 200); - assert_eq!(rows_2023[0].currency, "CAD"); - assert_eq!(rows_2023[0].source, BARS_1D_SOURCE_EOD); -} - -#[test] -fn split_rekey_edge_cases_and_conservation_invariants() { - let dir = TestTempDir::new("split-rekey"); - let eod_path = dir.path().join("eodPrices.bson"); - let splits_path = dir.path().join("qmSplits.bson"); - let map_path = dir.path().join("provider_mapping.tsv"); - let curr_path = dir.path().join("listing_currencies.tsv"); - let out_dir = dir.path().join("out"); - - // Listing 1: two distinct EOD source_ids ("DUAL1.US", "DUAL2.US") -> split applies to both. - // Listing 2: two date ranges for the SAME EOD source_id ("MULTI.US") -> deduped, no squaring. - // Listing 3: QM-only, no EOD partner -> splits_no_eod_partner. - // Listing 4: QM mapped only for 2020-01-01..=2020-12-31; split in 2024 -> splits_unmapped_qm. - write_bytes( - &map_path, - b"eod\tDUAL1.US\t2020-01-01\t2023-12-31\t1\n\ - eod\tDUAL2.US\t2024-01-01\t\t1\n\ - qm\tDUAL:US\t2020-01-01\t\t1\n\ - eod\tMULTI.US\t2020-01-01\t2021-12-31\t2\n\ - eod\tMULTI.US\t2022-01-01\t\t2\n\ - qm\tMULTI:US\t2020-01-01\t\t2\n\ - qm\tQMONLY:US\t2020-01-01\t\t3\n\ - eod\tEXPIRED.US\t2020-01-01\t\t4\n\ - qm\tEXPIRED:US\t2020-01-01\t2020-12-31\t4\n", - ); - write_bytes(&curr_path, b"1\tUSD\n2\tUSD\n3\tUSD\n4\tUSD\n"); - - let mut splits_bytes = Vec::new(); - // 1. Applied to listing 1 (2 EOD partners) - splits_bytes.extend_from_slice(&split_doc("DUAL:US", "2024-06-10", 4.0)); - // 2. Applied to listing 2 (1 EOD partner across 2 ranges -> must NOT square 2.0 into 4.0) - splits_bytes.extend_from_slice(&split_doc("MULTI:US", "2024-06-10", 2.0)); - // 3. Unmapped QM code - splits_bytes.extend_from_slice(&split_doc("UNKNOWN:US", "2024-06-10", 3.0)); - // 4. QM mapped only outside ex_date - splits_bytes.extend_from_slice(&split_doc("EXPIRED:US", "2024-06-10", 3.0)); - // 5. No EOD partner - splits_bytes.extend_from_slice(&split_doc("QMONLY:US", "2024-06-10", 2.0)); - // 6. 1:1 no-op - splits_bytes.extend_from_slice(&split_doc("DUAL:US", "2024-05-01", 1.0)); - // 7. Malformed split (missing splitratio) -> decoder rejection - let mut bad_split = RawDocumentBuf::new(); - bad_split.append(cstr!("qmSearchCode"), "DUAL:US"); - bad_split.append(cstr!("date"), "2024-05-02"); - splits_bytes.extend_from_slice(bad_split.as_bytes()); - write_bytes(&splits_path, &splits_bytes); - - let mut eod_bytes = Vec::new(); - // Pre-split bars for both EOD partners of listing 1: - eod_bytes.extend_from_slice(&eod_doc("DUAL1.US", "2023-12-29", 10.0, 11.0, 9.0, 10.5, 400.0)); - eod_bytes.extend_from_slice(&eod_doc("DUAL2.US", "2024-06-07", 10.0, 11.0, 9.0, 10.5, 800.0)); - // Pre-split bar for listing 2 (multi-range same EOD key): - eod_bytes.extend_from_slice(&eod_doc("MULTI.US", "2024-06-07", 20.0, 21.0, 19.0, 20.5, 200.0)); - write_bytes(&eod_path, &eod_bytes); - - let args = CurateBars1dArgs { - eod_prices: eod_path, - qm_splits: splits_path, - qm_prices: None, - provider_mapping: map_path, - listing_currencies: curr_path, - out_dir: out_dir.clone(), - rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, - threads: 1, - }; - - let report = run_curate_bars_1d(&args).expect("split rekey test"); - assert_eq!(report.split_rekey.splits_in, 7); - assert_eq!(report.split_rekey.splits_applied, 2); - assert_eq!(report.split_rekey.splits_collision_collapsed, 0); - assert_eq!(report.split_rekey.split_events_attached, 3); // 2 for listing 1 + 1 for listing 2 - assert_eq!(report.split_rekey.splits_unmapped_qm, 2); - assert_eq!(report.split_rekey.splits_no_eod_partner, 1); - assert_eq!(report.split_rekey.splits_noop_dropped, 1); - assert_eq!(report.splits_decode.rejected_total(), 1); - assert_eq!( - report.split_rekey.splits_in, - report.split_rekey.splits_applied - + report.split_rekey.splits_collision_collapsed - + report.split_rekey.splits_unmapped_qm - + report.split_rekey.splits_no_eod_partner - + report.split_rekey.splits_noop_dropped - + report.splits_decode.rejected_total() - ); - - let rows_2023 = read_parquet_bars(&out_dir.join("bars_1d/year=2023/part.parquet")); - assert_eq!(rows_2023.len(), 1); - assert_eq!(rows_2023[0].listing_id, 1); - assert_eq!(rows_2023[0].volume, 100.0); // 400 / 4 - - let rows_2024 = read_parquet_bars(&out_dir.join("bars_1d/year=2024/part.parquet")); - assert_eq!(rows_2024.len(), 2); - assert_eq!(rows_2024[0].listing_id, 1); - assert_eq!(rows_2024[0].volume, 200.0); // 800 / 4 - assert_eq!(rows_2024[1].listing_id, 2); - assert_eq!(rows_2024[1].volume, 100.0); // 200 / 2 (NOT 200 / 4!) -} - -#[test] -fn qm_alias_splits_collapse_identical_and_reject_conflicting_with_parquet_readback() { - let dir = TestTempDir::new("qm-alias-splits"); - let eod_path = dir.path().join("eodPrices.bson"); - let map_path = dir.path().join("provider_mapping.tsv"); - let curr_path = dir.path().join("listing_currencies.tsv"); - - // Listing 100: two QM aliases ("NVDA:US", "NVDA_ALT:US") -> one EOD key ("NVDA.US"). - // Listing 200: single QM key ("COMBO:US") -> one EOD key ("COMBO.US") for same-day multi-split check. - write_bytes( - &map_path, - b"eod\tNVDA.US\t2010-01-01\t\t100\n\ - qm\tNVDA:US\t2010-01-01\t\t100\n\ - qm\tNVDA_ALT:US\t2010-01-01\t\t100\n\ - eod\tCOMBO.US\t2010-01-01\t\t200\n\ - qm\tCOMBO:US\t2010-01-01\t\t200\n", - ); - write_bytes(&curr_path, b"100\tUSD\n200\tUSD\n"); - - let mut eod_bytes = Vec::new(); - eod_bytes.extend_from_slice(&eod_doc( - "NVDA.US", - "2024-06-07", - 1197.70, - 1216.92, - 1180.22, - 1208.88, - 410_000_000.0, - )); - eod_bytes.extend_from_slice(&eod_doc( - "NVDA.US", - "2024-06-10", - 120.37, - 123.10, - 117.01, - 121.79, - 310_000_000.0, - )); - eod_bytes.extend_from_slice(&eod_doc( - "COMBO.US", - "2024-06-07", - 50.0, - 52.0, - 49.0, - 51.0, - 300.0, - )); - write_bytes(&eod_path, &eod_bytes); - - // 1. Identical cross-key QM alias splits (10:1 under both NVDA:US and NVDA_ALT:US) must - // collapse to a single 10:1 split rather than multiplying to 100:1, while two same-day - // splits under one QM key (COMBO:US 2:1 and 1.5:1) still multiply to 3:1. - let splits_ok = dir.path().join("splits_alias_ok.bson"); - let mut splits_ok_bytes = Vec::new(); - splits_ok_bytes.extend_from_slice(&split_doc("NVDA:US", "2024-06-10", 10.0)); - splits_ok_bytes.extend_from_slice(&split_doc("NVDA_ALT:US", "2024-06-10", 10.0)); - splits_ok_bytes.extend_from_slice(&split_doc("COMBO:US", "2024-06-10", 2.0)); - splits_ok_bytes.extend_from_slice(&split_doc("COMBO:US", "2024-06-10", 1.5)); - write_bytes(&splits_ok, &splits_ok_bytes); - - let out_ok = dir.path().join("out_ok"); - let report = run_curate_bars_1d(&CurateBars1dArgs { - eod_prices: eod_path.clone(), - qm_splits: splits_ok, - qm_prices: None, - provider_mapping: map_path.clone(), - listing_currencies: curr_path.clone(), - out_dir: out_ok.clone(), - rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, - threads: 1, - }) - .expect("identical QM alias splits should collapse cleanly"); - - assert_eq!(report.split_rekey.splits_in, 4); - assert_eq!(report.split_rekey.splits_collision_collapsed, 1); - assert_eq!(report.split_rekey.splits_applied, 3); // 1 collapsed NVDA + 2 same-key COMBO - assert_eq!(report.split_rekey.split_events_attached, 3); - assert_eq!( - report.split_rekey.splits_in, - report.split_rekey.splits_applied - + report.split_rekey.splits_collision_collapsed - + report.split_rekey.splits_unmapped_qm - + report.split_rekey.splits_no_eod_partner - + report.split_rekey.splits_noop_dropped - + report.splits_decode.rejected_total() - ); - - let rows_2024 = read_parquet_bars(&out_ok.join("bars_1d/year=2024/part.parquet")); - assert_eq!(rows_2024.len(), 3); - // NVDA pre-split: 410M / 10 = 41M (NOT 4.1M!). - assert_eq!(rows_2024[0].listing_id, 100); - assert_eq!(rows_2024[0].open.to_bits(), 1197.70_f64.to_bits()); - assert_eq!(rows_2024[0].close.to_bits(), 1208.88_f64.to_bits()); - assert_eq!(rows_2024[0].volume.to_bits(), 41_000_000.0_f64.to_bits()); - assert!((rows_2024[0].close * rows_2024[0].volume - 1208.88 * 41_000_000.0).abs() < 1e-6); - // NVDA ex-date untouched: - assert_eq!(rows_2024[1].listing_id, 100); - assert_eq!(rows_2024[1].volume.to_bits(), 310_000_000.0_f64.to_bits()); - // COMBO single-key same-day splits (2.0 * 1.5 = 3.0): 300 / 3 = 100. - assert_eq!(rows_2024[2].listing_id, 200); - assert_eq!(rows_2024[2].volume.to_bits(), 100.0_f64.to_bits()); - - // 2. Conflicting cross-key QM alias splits (10:1 vs 4:1) must fail closed and write nothing. - let splits_conflict = dir.path().join("splits_alias_conflict.bson"); - let mut splits_conflict_bytes = Vec::new(); - splits_conflict_bytes.extend_from_slice(&split_doc("NVDA:US", "2024-06-10", 10.0)); - splits_conflict_bytes.extend_from_slice(&split_doc("NVDA_ALT:US", "2024-06-10", 4.0)); - write_bytes(&splits_conflict, &splits_conflict_bytes); - - let out_conflict = dir.path().join("out_conflict"); - let err = run_curate_bars_1d(&CurateBars1dArgs { - eod_prices: eod_path, - qm_splits: splits_conflict, - qm_prices: None, - provider_mapping: map_path, - listing_currencies: curr_path, - out_dir: out_conflict.clone(), - rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, - threads: 1, - }) - .unwrap_err(); - match &err { - RunCurateBarsError::ConflictingCrossKeySplit { - listing_id, - first_key, - first_ratio, - second_key, - second_ratio, - .. - } => { - assert_eq!(*listing_id, 100); - assert_eq!(first_key, "NVDA:US"); - assert_eq!(*first_ratio, 10.0); - assert_eq!(second_key, "NVDA_ALT:US"); - assert_eq!(*second_ratio, 4.0); - } - other => panic!("expected ConflictingCrossKeySplit, got {other:?}"), - } - let msg = err.to_string(); - assert!(!msg.contains('\n'), "error must be single-line: {msg}"); - assert!(msg.contains("splits_alias_conflict.bson"), "{msg}"); - assert!(!out_conflict.join("bars_1d").exists()); -} - -#[test] -fn early_filter_missing_currency_and_full_bar_accounting() { - let dir = TestTempDir::new("accounting"); - let eod_path = dir.path().join("eodPrices.bson"); - let splits_path = dir.path().join("qmSplits.bson"); - let map_path = dir.path().join("provider_mapping.tsv"); - let curr_path = dir.path().join("listing_currencies.tsv"); - let out_dir = dir.path().join("out"); - - write_bytes( - &map_path, - b"eod\tKEEP.US\t2020-01-01\t\t1\n\ - eod\tNOCURR.US\t2020-01-01\t\t2\n", - ); - // Listing 2 intentionally absent from listing_currencies.tsv. - write_bytes(&curr_path, b"1\tUSD\n"); - write_bytes(&splits_path, b""); - - let mut eod_bytes = Vec::new(); - // 1. Kept bar - eod_bytes.extend_from_slice(&eod_doc("KEEP.US", "2024-01-02", 10.0, 11.0, 9.0, 10.5, 100.0)); - // 2. Unmapped EOD source_id -> early-filtered - eod_bytes.extend_from_slice(&eod_doc("GHOST.US", "2024-01-02", 10.0, 11.0, 9.0, 10.5, 100.0)); - // 3. Mapped EOD source_id, date before valid_from -> dropped_unmapped in curate_bars_1d - eod_bytes.extend_from_slice(&eod_doc("KEEP.US", "2019-12-31", 10.0, 11.0, 9.0, 10.5, 100.0)); - // 4. Mapped listing missing currency -> dropped_missing_currency without error - eod_bytes.extend_from_slice(&eod_doc("NOCURR.US", "2024-01-02", 10.0, 11.0, 9.0, 10.5, 100.0)); - // 5. Decoder rejection (missing volume) - let mut bad = RawDocumentBuf::new(); - bad.append(cstr!("eodSearchCode"), "KEEP.US"); - bad.append(cstr!("date"), "2024-01-03"); - bad.append(cstr!("open"), 10.0); - bad.append(cstr!("high"), 11.0); - bad.append(cstr!("low"), 9.0); - bad.append(cstr!("close"), 10.5); - eod_bytes.extend_from_slice(bad.as_bytes()); - write_bytes(&eod_path, &eod_bytes); - - let args = CurateBars1dArgs { - eod_prices: eod_path, - qm_splits: splits_path, - qm_prices: None, - provider_mapping: map_path, - listing_currencies: curr_path, - out_dir: out_dir.clone(), - rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, - threads: 1, - }; - - let report = run_curate_bars_1d(&args).expect("accounting run"); - assert_eq!(report.eod_docs_framed, 5); - assert_eq!(report.eod_decode.docs_in, 5); - assert_eq!(report.eod_decode.decoded, 4); - assert_eq!(report.eod_decode.rejected_total(), 1); - assert_eq!(report.bars_unmapped_source_dropped, 1); - assert_eq!(report.buffered_bars, 3); - assert_eq!(report.curate_stats.dropped_unmapped, 1); - assert_eq!(report.curate_stats.dropped_missing_currency, 1); - assert_eq!(report.write_stats.rows_written, 1); - - let total_accounted = report.write_stats.rows_written - + report.bars_unmapped_source_dropped - + report.curate_stats.builder.dropped_invalid_ohlc - + report.curate_stats.builder.dropped_inconsistent_ohlc - + report.curate_stats.builder.dropped_invalid_volume - + report.curate_stats.builder.duplicate_collapsed - + report.curate_stats.builder.duplicate_conflict_dropped - + report.curate_stats.dropped_unmapped - + report.curate_stats.dropped_missing_currency - + report.curate_stats.dropped_ts_out_of_range - + report.curate_stats.listing_collision_collapsed - + report.curate_stats.listing_collision_dropped; - assert_eq!(report.eod_decode.decoded, total_accounted); -} - -#[test] -fn tsv_loaders_accept_crlf_trailing_blank_and_verbatim_whitespace_and_reject_malformed() { - let dir = TestTempDir::new("tsv"); - - // Valid: CRLF, single trailing blank line, verbatim whitespace in source_id. - let valid_map = dir.path().join("valid_map.tsv"); - write_bytes( - &valid_map, - b"eod\t SPACED.US \t2020-01-01\t2024-12-31\t42\r\n\r\n", - ); - let rows = load_provider_mapping_tsv(&valid_map).expect("valid CRLF map"); - assert_eq!(rows.len(), 1); - assert_eq!(rows[0].source_id, " SPACED.US "); - assert_eq!(rows[0].listing_id, 42); - - let valid_curr = dir.path().join("valid_curr.tsv"); - write_bytes(&valid_curr, b"42\tUSD\r\n43\tCAD\r\n\r\n"); - let curr = load_listing_currencies_tsv(&valid_curr).expect("valid CRLF curr"); - assert_eq!(curr.get(&42).map(AsRef::as_ref), Some("USD")); - assert_eq!(curr.get(&43).map(AsRef::as_ref), Some("CAD")); - - // Invalid UTF-8 on line 2 -> reports line 2. - let bad_utf8 = dir.path().join("bad_utf8.tsv"); - write_bytes(&bad_utf8, b"1\tUSD\n2\t\xFF\xFE\n"); - let err = load_listing_currencies_tsv(&bad_utf8).unwrap_err(); - match &err { - RunCurateBarsError::TsvParse { line, .. } => assert_eq!(*line, 2), - other => panic!("expected TsvParse, got {other:?}"), - } - assert!(err.to_string().contains(":2:")); - - // Header row on line 1 rejected. - let header_map = dir.path().join("header.tsv"); - write_bytes( - &header_map, - b"source\tsource_id\tvalid_from\tvalid_to\tlisting_id\n", - ); - let err = load_provider_mapping_tsv(&header_map).unwrap_err(); - assert!(matches!(err, RunCurateBarsError::TsvParse { line: 1, .. })); - - // Interior blank line rejected with blank line's 1-based line number. - let interior_blank = dir.path().join("interior_blank.tsv"); - write_bytes(&interior_blank, b"1\tUSD\n\n2\tCAD\n"); - let err = load_listing_currencies_tsv(&interior_blank).unwrap_err(); - assert!(matches!(err, RunCurateBarsError::TsvParse { line: 2, .. })); - - // Multiple trailing blank lines rejected. - let double_blank = dir.path().join("double_blank.tsv"); - write_bytes(&double_blank, b"1\tUSD\n\n\n"); - let err = load_listing_currencies_tsv(&double_blank).unwrap_err(); - assert!(matches!(err, RunCurateBarsError::TsvParse { line: 3, .. })); - - // Duplicate listing_id in currencies rejected on line 2. - let dup_curr = dir.path().join("dup_curr.tsv"); - write_bytes(&dup_curr, b"1\tUSD\n1\tCAD\n"); - let err = load_listing_currencies_tsv(&dup_curr).unwrap_err(); - assert!(matches!(err, RunCurateBarsError::TsvParse { line: 2, .. })); - - // Non-positive / signed listing_id rejected. - for bad_id in ["0", "-1", "+1", " 1"] { - let p = dir.path().join(format!("bad_id_{}.tsv", bad_id.trim())); - write_bytes(&p, format!("{bad_id}\tUSD\n").as_bytes()); - let err = load_listing_currencies_tsv(&p).unwrap_err(); - assert!(matches!(err, RunCurateBarsError::TsvParse { line: 1, .. })); - } -} - -#[test] -fn failure_modes_return_typed_errors_and_leave_no_partial_dataset() { - let dir = TestTempDir::new("failures"); - let valid_eod = dir.path().join("valid_eod.bson"); - let valid_splits = dir.path().join("valid_splits.bson"); - let valid_map = dir.path().join("valid_map.tsv"); - let valid_curr = dir.path().join("valid_curr.tsv"); - - write_bytes( - &valid_eod, - &eod_doc("AAPL.US", "2024-01-02", 100.0, 101.0, 99.0, 100.5, 1000.0), - ); - write_bytes(&valid_splits, b""); - write_bytes(&valid_map, b"eod\tAAPL.US\t2020-01-01\t\t1\n"); - write_bytes(&valid_curr, b"1\tUSD\n"); - - let assert_single_line_and_no_dataset = |err: &RunCurateBarsError, out: &Path| { - let msg = err.to_string(); - assert!(!msg.contains('\n'), "error must be single-line: {msg}"); - assert!( - !out.join("bars_1d").exists(), - "no bars_1d dataset should exist under {}", - out.display() - ); - }; - - // 1. Missing input file. - let out1 = dir.path().join("out_missing"); - let err = run_curate_bars_1d(&CurateBars1dArgs { - eod_prices: dir.path().join("does_not_exist.bson"), - qm_splits: valid_splits.clone(), - qm_prices: None, - provider_mapping: valid_map.clone(), - listing_currencies: valid_curr.clone(), - out_dir: out1.clone(), - rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, - threads: 1, - }) - .unwrap_err(); - assert!(matches!(err, RunCurateBarsError::OpenInput { .. })); - assert_single_line_and_no_dataset(&err, &out1); - - // 2. Truncated BSON mid-document. - let trunc_eod = dir.path().join("trunc_eod.bson"); - let mut full_doc = eod_doc("AAPL.US", "2024-01-02", 100.0, 101.0, 99.0, 100.5, 1000.0); - full_doc.truncate(full_doc.len() - 5); - write_bytes(&trunc_eod, &full_doc); - let out2 = dir.path().join("out_trunc"); - let err = run_curate_bars_1d(&CurateBars1dArgs { - eod_prices: trunc_eod, - qm_splits: valid_splits.clone(), - qm_prices: None, - provider_mapping: valid_map.clone(), - listing_currencies: valid_curr.clone(), - out_dir: out2.clone(), - rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, - threads: 1, - }) - .unwrap_err(); - assert!(matches!( - err, - RunCurateBarsError::BsonStream { - source: BsonStreamError::TruncatedDocument { .. }, - .. - } - )); - assert_single_line_and_no_dataset(&err, &out2); - - // 3. Oversized BSON document (> DEFAULT_MAX_DOC_BYTES). - let huge_eod = dir.path().join("huge_eod.bson"); - let huge_len = (DEFAULT_MAX_DOC_BYTES as i32) + 1024; - let mut huge_bytes = Vec::from(huge_len.to_le_bytes()); - huge_bytes.push(0); - write_bytes(&huge_eod, &huge_bytes); - let out3 = dir.path().join("out_huge"); - let err = run_curate_bars_1d(&CurateBars1dArgs { - eod_prices: huge_eod, - qm_splits: valid_splits.clone(), - qm_prices: None, - provider_mapping: valid_map.clone(), - listing_currencies: valid_curr.clone(), - out_dir: out3.clone(), - rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, - threads: 1, - }) - .unwrap_err(); - assert!(matches!( - err, - RunCurateBarsError::BsonStream { - source: BsonStreamError::CorruptDocumentLength { .. }, - .. - } - )); - assert_single_line_and_no_dataset(&err, &out3); - - // 4. Malformed TSV line (names 1-based line number). - let bad_map = dir.path().join("bad_map.tsv"); - write_bytes( - &bad_map, - b"eod\tAAPL.US\t2020-01-01\t\t1\neod\tBAD.US\tnot-a-date\t\t2\n", - ); - let out4 = dir.path().join("out_bad_tsv"); - let err = run_curate_bars_1d(&CurateBars1dArgs { - eod_prices: valid_eod.clone(), - qm_splits: valid_splits.clone(), - qm_prices: None, - provider_mapping: bad_map, - listing_currencies: valid_curr.clone(), - out_dir: out4.clone(), - rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, - threads: 1, - }) - .unwrap_err(); - assert!(matches!(err, RunCurateBarsError::TsvParse { line: 2, .. })); - assert!(err.to_string().contains(":2:")); - assert_single_line_and_no_dataset(&err, &out4); - - // 5. Overlapping mapping ranges. - let overlap_map = dir.path().join("overlap_map.tsv"); - write_bytes( - &overlap_map, - b"eod\tAAPL.US\t2020-01-01\t2022-12-31\t1\n\ - eod\tAAPL.US\t2022-06-01\t2024-12-31\t2\n", - ); - let out5 = dir.path().join("out_overlap"); - let err = run_curate_bars_1d(&CurateBars1dArgs { - eod_prices: valid_eod.clone(), - qm_splits: valid_splits.clone(), - qm_prices: None, - provider_mapping: overlap_map, - listing_currencies: valid_curr.clone(), - out_dir: out5.clone(), - rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, - threads: 1, - }) - .unwrap_err(); - assert!(matches!( - err, - RunCurateBarsError::ProviderMapping { - source: ProviderMappingError::OverlappingRanges { .. }, - .. - } - )); - assert_single_line_and_no_dataset(&err, &out5); - - // 6. Unwritable --out (existing regular file fails fast in validate_out_dir). - let out_file = dir.path().join("out_is_a_file"); - write_bytes(&out_file, b"blocker"); - let err = run_curate_bars_1d(&CurateBars1dArgs { - eod_prices: valid_eod.clone(), - qm_splits: valid_splits.clone(), - qm_prices: None, - provider_mapping: valid_map.clone(), - listing_currencies: valid_curr.clone(), - out_dir: out_file.clone(), - rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, - threads: 1, - }) - .unwrap_err(); - assert!(matches!(err, RunCurateBarsError::InvalidOutDir { .. })); - assert!(!err.to_string().contains('\n')); - - // 7. Writer-reaching output obstruction: --out is a valid directory, but `/bars_1d` - // is occupied by a regular file so curation completes and the Parquet writer fails. - let out_obstructed = dir.path().join("out_obstructed"); - fs::create_dir_all(&out_obstructed).expect("create obstructed out dir"); - let bars_1d_blocker = out_obstructed.join("bars_1d"); - write_bytes(&bars_1d_blocker, b"sentinel"); - let err = run_curate_bars_1d(&CurateBars1dArgs { - eod_prices: valid_eod, - qm_splits: valid_splits, - qm_prices: None, - provider_mapping: valid_map, - listing_currencies: valid_curr, - out_dir: out_obstructed.clone(), - rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, - threads: 1, - }) - .unwrap_err(); - assert!(matches!( - err, - RunCurateBarsError::CurateWrite { - source: CurateBarsWriteError::Parquet(_), - .. - } - )); - let msg = err.to_string(); - assert!(!msg.contains('\n'), "error must be single-line: {msg}"); - assert!(msg.contains("out_obstructed"), "{msg}"); - assert!(bars_1d_blocker.is_file()); - assert_eq!(fs::read(&bars_1d_blocker).unwrap(), b"sentinel"); -} - -#[test] -fn deterministic_parquet_and_report_across_runs_and_shuffled_inputs_and_timed_parity() { - let dir = TestTempDir::new("determinism"); - let map_path = dir.path().join("provider_mapping.tsv"); - let curr_path = dir.path().join("listing_currencies.tsv"); - write_bytes( - &map_path, - b"eod\tNVDA.US\t2010-01-01\t\t10\n\ - qm\tNVDA:US\t2010-01-01\t\t10\n\ - eod\tSHOP.TO\t2015-01-01\t\t20\n\ - qm\tSHOP:TO\t2015-01-01\t\t20\n", - ); - write_bytes(&curr_path, b"10\tUSD\n20\tCAD\n"); - - let eod_docs = [ - eod_doc("NVDA.US", "2023-12-28", 490.0, 498.0, 488.0, 495.0, 200_000_000.0), - eod_doc("NVDA.US", "2024-06-07", 1197.0, 1216.0, 1180.0, 1208.0, 400_000_000.0), - eod_doc("NVDA.US", "2024-06-10", 120.0, 123.0, 117.0, 121.0, 300_000_000.0), - eod_doc("SHOP.TO", "2023-12-29", 103.0, 105.0, 102.0, 104.0, 1_000_000.0), - eod_doc("SHOP.TO", "2024-01-03", 104.0, 106.0, 103.0, 105.0, 1_200_000.0), - ]; - let split_docs = [ - split_doc("NVDA:US", "2024-06-10", 10.0), - split_doc("SHOP:TO", "2024-06-01", 2.0), - ]; - - let eod_a = dir.path().join("eod_a.bson"); - let splits_a = dir.path().join("splits_a.bson"); - write_bytes(&eod_a, &eod_docs.concat()); - write_bytes(&splits_a, &split_docs.concat()); - - let eod_shuf = dir.path().join("eod_shuf.bson"); - let splits_shuf = dir.path().join("splits_shuf.bson"); - let mut eod_rev = Vec::new(); - for doc in eod_docs.iter().rev() { - eod_rev.extend_from_slice(doc); - } - let mut split_rev = Vec::new(); - for doc in split_docs.iter().rev() { - split_rev.extend_from_slice(doc); - } - write_bytes(&eod_shuf, &eod_rev); - write_bytes(&splits_shuf, &split_rev); - - let out1 = dir.path().join("out1"); - let out2 = dir.path().join("out2"); - let out3 = dir.path().join("out3"); - let out_timed = dir.path().join("out_timed"); - - let r1 = run_curate_bars_1d(&CurateBars1dArgs { - eod_prices: eod_a.clone(), - qm_splits: splits_a.clone(), - qm_prices: None, - provider_mapping: map_path.clone(), - listing_currencies: curr_path.clone(), - out_dir: out1.clone(), - rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, - threads: 1, - }) - .unwrap(); - let r2 = run_curate_bars_1d(&CurateBars1dArgs { - eod_prices: eod_a.clone(), - qm_splits: splits_a.clone(), - qm_prices: None, - provider_mapping: map_path.clone(), - listing_currencies: curr_path.clone(), - out_dir: out2.clone(), - rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, - threads: 1, - }) - .unwrap(); - let r3 = run_curate_bars_1d(&CurateBars1dArgs { - eod_prices: eod_shuf, - qm_splits: splits_shuf, - qm_prices: None, - provider_mapping: map_path.clone(), - listing_currencies: curr_path.clone(), - out_dir: out3.clone(), - rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, - threads: 1, - }) - .unwrap(); - let rt = run_curate_bars_1d_timed(&CurateBars1dArgs { - eod_prices: eod_a, - qm_splits: splits_a, - qm_prices: None, - provider_mapping: map_path, - listing_currencies: curr_path, - out_dir: out_timed.clone(), - rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, - threads: 1, - }) - .unwrap(); - - let s1 = strip_timing_line(&format_curate_bars_report(&r1)); - let s2 = strip_timing_line(&format_curate_bars_report(&r2)); - let s3 = strip_timing_line(&format_curate_bars_report(&r3)); - let st = strip_timing_line(&format_curate_bars_report(&rt.report)); - assert_eq!(s1, s2); - assert_eq!(s1, s3); - assert_eq!(s1, st); - - for year in [2023, 2024] { - let rel = format!("bars_1d/year={year:04}/part.parquet"); - let b1 = fs::read(out1.join(&rel)).unwrap(); - let b2 = fs::read(out2.join(&rel)).unwrap(); - let b3 = fs::read(out3.join(&rel)).unwrap(); - let bt = fs::read(out_timed.join(&rel)).unwrap(); - assert_eq!(b1, b2, "run 1 vs run 2 mismatch for {rel}"); - assert_eq!(b1, b3, "run 1 vs shuffled mismatch for {rel}"); - assert_eq!(b1, bt, "run 1 vs timed parity mismatch for {rel}"); - } -} - -#[test] -fn rerun_with_narrower_year_range_replaces_emitted_year_and_leaves_older_year_untouched() { - let dir = TestTempDir::new("narrower-rerun"); - let eod_full = dir.path().join("eod_full.bson"); - let eod_2024 = dir.path().join("eod_2024.bson"); - let splits_path = dir.path().join("splits.bson"); - let map_path = dir.path().join("provider_mapping.tsv"); - let curr_path = dir.path().join("listing_currencies.tsv"); - let out_dir = dir.path().join("out"); - - write_bytes(&map_path, b"eod\tAAPL.US\t2020-01-01\t\t1\n"); - write_bytes(&curr_path, b"1\tUSD\n"); - write_bytes(&splits_path, b""); - - let mut full_bytes = Vec::new(); - full_bytes.extend_from_slice(&eod_doc("AAPL.US", "2023-12-29", 190.0, 192.0, 189.0, 191.0, 1_000.0)); - full_bytes.extend_from_slice(&eod_doc("AAPL.US", "2024-01-02", 185.0, 188.0, 184.0, 186.0, 2_000.0)); - write_bytes(&eod_full, &full_bytes); - - let r1 = run_curate_bars_1d(&CurateBars1dArgs { - eod_prices: eod_full, - qm_splits: splits_path.clone(), - qm_prices: None, - provider_mapping: map_path.clone(), - listing_currencies: curr_path.clone(), - out_dir: out_dir.clone(), - rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, - threads: 1, - }) - .expect("initial 2023+2024 run"); - assert_eq!(r1.write_stats.rows_by_year.get(&2023), Some(&1)); - assert_eq!(r1.write_stats.rows_by_year.get(&2024), Some(&1)); - - let p2023 = out_dir.join("bars_1d/year=2023/part.parquet"); - let p2024 = out_dir.join("bars_1d/year=2024/part.parquet"); - let bytes_2023_before = fs::read(&p2023).expect("read initial 2023"); - - // Rerun into the same --out with only 2024 data (updated close/volume). - write_bytes( - &eod_2024, - &eod_doc("AAPL.US", "2024-01-02", 185.0, 189.0, 184.0, 188.5, 2_500.0), - ); - let r2 = run_curate_bars_1d(&CurateBars1dArgs { - eod_prices: eod_2024, - qm_splits: splits_path, - qm_prices: None, - provider_mapping: map_path, - listing_currencies: curr_path, - out_dir: out_dir.clone(), - rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, - threads: 1, - }) - .expect("narrower 2024-only rerun"); - assert_eq!(r2.write_stats.rows_by_year.len(), 1); - assert_eq!(r2.write_stats.rows_by_year.get(&2024), Some(&1)); - - // 2024 partition is replaced; 2023 partition remains byte-identical on disk. - let rows_2024 = read_parquet_bars(&p2024); - assert_eq!(rows_2024.len(), 1); - assert_eq!(rows_2024[0].close.to_bits(), 188.5_f64.to_bits()); - assert_eq!(rows_2024[0].volume.to_bits(), 2_500.0_f64.to_bits()); - assert_eq!(fs::read(&p2023).expect("read 2023 after rerun"), bytes_2023_before); -} - -#[test] -fn failed_rerun_over_existing_dataset_leaves_published_partitions_byte_identical() { - let dir = TestTempDir::new("failed-rerun"); - let valid_eod = dir.path().join("valid_eod.bson"); - let valid_splits = dir.path().join("valid_splits.bson"); - let valid_map = dir.path().join("valid_map.tsv"); - let valid_curr = dir.path().join("valid_curr.tsv"); - let out_dir = dir.path().join("out"); - - write_bytes( - &valid_map, - b"eod\tNVDA.US\t2010-01-01\t\t10\n\ - qm\tNVDA:US\t2010-01-01\t\t10\n\ - qm\tNVDA_ALT:US\t2010-01-01\t\t10\n", - ); - write_bytes(&valid_curr, b"10\tUSD\n"); - write_bytes(&valid_splits, &split_doc("NVDA:US", "2024-06-10", 10.0)); - write_bytes( - &valid_eod, - &eod_doc("NVDA.US", "2024-06-07", 1197.0, 1216.0, 1180.0, 1208.0, 400_000_000.0), - ); - - run_curate_bars_1d(&CurateBars1dArgs { - eod_prices: valid_eod.clone(), - qm_splits: valid_splits.clone(), - qm_prices: None, - provider_mapping: valid_map.clone(), - listing_currencies: valid_curr.clone(), - out_dir: out_dir.clone(), - rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, - threads: 1, - }) - .expect("seed existing dataset"); - - let published = out_dir.join("bars_1d/year=2024/part.parquet"); - let snapshot_before = fs::read(&published).expect("read published parquet"); - - let assert_unchanged_and_clean = || { - assert_eq!(fs::read(&published).expect("re-read published"), snapshot_before); - let year_dir = out_dir.join("bars_1d/year=2024"); - let entries: Vec = fs::read_dir(&year_dir) - .unwrap() - .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) - .collect(); - assert_eq!(entries, vec!["part.parquet".to_string()]); - assert!(!out_dir.join("bars_1d/.write.lock").exists()); - }; - - // 1. Truncated BSON rerun - let trunc_eod = dir.path().join("trunc.bson"); - let mut bytes = eod_doc("NVDA.US", "2024-06-07", 100.0, 101.0, 99.0, 100.5, 1000.0); - bytes.truncate(bytes.len() - 4); - write_bytes(&trunc_eod, &bytes); - assert!(run_curate_bars_1d(&CurateBars1dArgs { - eod_prices: trunc_eod, - qm_splits: valid_splits.clone(), - qm_prices: None, - provider_mapping: valid_map.clone(), - listing_currencies: valid_curr.clone(), - out_dir: out_dir.clone(), - rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, - threads: 1, - }) - .is_err()); - assert_unchanged_and_clean(); - - // 2. Conflicting QM alias split rerun - let conflict_splits = dir.path().join("conflict_splits.bson"); - let mut split_bytes = Vec::new(); - split_bytes.extend_from_slice(&split_doc("NVDA:US", "2024-06-10", 10.0)); - split_bytes.extend_from_slice(&split_doc("NVDA_ALT:US", "2024-06-10", 5.0)); - write_bytes(&conflict_splits, &split_bytes); - assert!(run_curate_bars_1d(&CurateBars1dArgs { - eod_prices: valid_eod.clone(), - qm_splits: conflict_splits, - qm_prices: None, - provider_mapping: valid_map.clone(), - listing_currencies: valid_curr.clone(), - out_dir: out_dir.clone(), - rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, - threads: 1, - }) - .is_err()); - assert_unchanged_and_clean(); - - // 3. Malformed currencies TSV rerun - let bad_curr = dir.path().join("bad_curr.tsv"); - write_bytes(&bad_curr, b"not_an_id\tUSD\n"); - assert!(run_curate_bars_1d(&CurateBars1dArgs { - eod_prices: valid_eod, - qm_splits: valid_splits, - qm_prices: None, - provider_mapping: valid_map, - listing_currencies: bad_curr, - out_dir: out_dir.clone(), - rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, - threads: 1, - }) - .is_err()); - assert_unchanged_and_clean(); -} - -#[test] -fn empty_and_all_unmapped_inputs_publish_nothing_and_account_cleanly() { - let dir = TestTempDir::new("empty-unmapped"); - let empty_eod = dir.path().join("empty_eod.bson"); - let empty_splits = dir.path().join("empty_splits.bson"); - let empty_map = dir.path().join("empty_map.tsv"); - let empty_curr = dir.path().join("empty_curr.tsv"); - write_bytes(&empty_eod, b""); - write_bytes(&empty_splits, b""); - write_bytes(&empty_map, b""); - write_bytes(&empty_curr, b""); - - let out_empty = dir.path().join("out_empty"); - let report_empty = run_curate_bars_1d(&CurateBars1dArgs { - eod_prices: empty_eod, - qm_splits: empty_splits.clone(), - qm_prices: None, - provider_mapping: empty_map, - listing_currencies: empty_curr, - out_dir: out_empty.clone(), - rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, - threads: 1, - }) - .expect("zero-byte inputs succeed"); - assert_eq!(report_empty.eod_docs_framed, 0); - assert_eq!(report_empty.write_stats.rows_written, 0); - assert_eq!(report_empty.write_stats.files_written, 0); - assert!(format_curate_bars_report(&report_empty).contains("years: none")); - assert!(!out_empty.join("bars_1d").exists()); - - // Case-sensitive source ("EOD" != "eod") and lowercase ticker ("aapl.us" != "AAPL.US") - // must all drop at early filter and publish nothing. - let map_path = dir.path().join("case_map.tsv"); - let curr_path = dir.path().join("case_curr.tsv"); - let unmapped_eod = dir.path().join("unmapped_eod.bson"); - write_bytes(&map_path, b"EOD\tAAPL.US\t2020-01-01\t\t1\neod\tMSFT.US\t2020-01-01\t\t2\n"); - write_bytes(&curr_path, b"1\tUSD\n2\tUSD\n"); - let mut eod_bytes = Vec::new(); - eod_bytes.extend_from_slice(&eod_doc("AAPL.US", "2024-01-02", 100.0, 101.0, 99.0, 100.5, 1000.0)); - eod_bytes.extend_from_slice(&eod_doc("msft.us", "2024-01-02", 200.0, 202.0, 199.0, 201.0, 2000.0)); - write_bytes(&unmapped_eod, &eod_bytes); - - let out_unmapped = dir.path().join("out_unmapped"); - let report_unmapped = run_curate_bars_1d(&CurateBars1dArgs { - eod_prices: unmapped_eod, - qm_splits: empty_splits, - qm_prices: None, - provider_mapping: map_path, - listing_currencies: curr_path, - out_dir: out_unmapped.clone(), - rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, - threads: 1, - }) - .expect("all-unmapped inputs succeed"); - assert_eq!(report_unmapped.eod_docs_framed, 2); - assert_eq!(report_unmapped.eod_decode.decoded, 2); - assert_eq!(report_unmapped.bars_unmapped_source_dropped, 2); - assert_eq!(report_unmapped.buffered_bars, 0); - assert_eq!(report_unmapped.write_stats.rows_written, 0); - assert!(!out_unmapped.join("bars_1d").exists()); -} - -#[test] -fn multi_forward_and_reverse_split_math_preserves_ohlc() { - let dir = TestTempDir::new("split-math"); - let eod_path = dir.path().join("eod.bson"); - let splits_path = dir.path().join("splits.bson"); - let map_path = dir.path().join("map.tsv"); - let curr_path = dir.path().join("curr.tsv"); - let out_dir = dir.path().join("out"); - - write_bytes( - &map_path, - b"eod\tFWD.US\t2020-01-01\t\t1\n\ - qm\tFWD:US\t2020-01-01\t\t1\n\ - eod\tREV.V\t2020-01-01\t\t2\n\ - qm\tREV:CA\t2020-01-01\t\t2\n", - ); - write_bytes(&curr_path, b"1\tUSD\n2\tCAD\n"); - - // FWD: 2:1 on 2024-03-01 then 3:1 on 2024-06-01 (pre-March /6, March..May /3, June+ /1). - // REV: 1-for-4 reverse split (ratio 0.25) on 2024-05-01 (pre-May *4, May+ *1). - let mut split_bytes = Vec::new(); - split_bytes.extend_from_slice(&split_doc("FWD:US", "2024-03-01", 2.0)); - split_bytes.extend_from_slice(&split_doc("FWD:US", "2024-06-01", 3.0)); - split_bytes.extend_from_slice(&split_doc("REV:CA", "2024-05-01", 0.25)); - write_bytes(&splits_path, &split_bytes); - - let mut eod_bytes = Vec::new(); - eod_bytes.extend_from_slice(&eod_doc("FWD.US", "2024-02-28", 60.0, 62.0, 59.0, 61.0, 600.0)); - eod_bytes.extend_from_slice(&eod_doc("FWD.US", "2024-03-01", 30.0, 31.0, 29.0, 30.5, 300.0)); - eod_bytes.extend_from_slice(&eod_doc("FWD.US", "2024-06-01", 10.0, 11.0, 9.5, 10.5, 100.0)); - eod_bytes.extend_from_slice(&eod_doc("REV.V", "2024-04-30", 0.50, 0.55, 0.45, 0.52, 250.0)); - eod_bytes.extend_from_slice(&eod_doc("REV.V", "2024-05-01", 2.00, 2.10, 1.90, 2.05, 500.0)); - write_bytes(&eod_path, &eod_bytes); - - let report = run_curate_bars_1d(&CurateBars1dArgs { - eod_prices: eod_path, - qm_splits: splits_path, - qm_prices: None, - provider_mapping: map_path, - listing_currencies: curr_path, - out_dir: out_dir.clone(), - rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, - threads: 1, - }) - .expect("multi-split math"); - assert_eq!(report.write_stats.rows_written, 5); - - let rows = read_parquet_bars(&out_dir.join("bars_1d/year=2024/part.parquet")); - assert_eq!(rows.len(), 5); - // FWD pre-March: 600 / 6 = 100, OHLC bit-identical. - assert_eq!(rows[0].listing_id, 1); - assert_eq!(rows[0].open.to_bits(), 60.0_f64.to_bits()); - assert_eq!(rows[0].close.to_bits(), 61.0_f64.to_bits()); - assert_eq!(rows[0].volume.to_bits(), 100.0_f64.to_bits()); - // FWD on 2024-03-01 (ex-date of 2:1, pre-3:1): 300 / 3 = 100. - assert_eq!(rows[1].volume.to_bits(), 100.0_f64.to_bits()); - // FWD on 2024-06-01 (ex-date of 3:1): untouched = 100. - assert_eq!(rows[2].volume.to_bits(), 100.0_f64.to_bits()); - // REV pre-May: 250 / 0.25 = 1000, OHLC bit-identical. - assert_eq!(rows[3].listing_id, 2); - assert_eq!(rows[3].open.to_bits(), 0.50_f64.to_bits()); - assert_eq!(rows[3].close.to_bits(), 0.52_f64.to_bits()); - assert_eq!(rows[3].volume.to_bits(), 1_000.0_f64.to_bits()); - // REV on ex-date 2024-05-01: untouched = 500. - assert_eq!(rows[4].volume.to_bits(), 500.0_f64.to_bits()); -} - -#[test] -fn tsv_loaders_reject_strict_edge_cases_and_accept_no_trailing_newline() { - let dir = TestTempDir::new("tsv-strict"); - - // Last line without trailing newline is accepted. - let no_nl_map = dir.path().join("no_nl_map.tsv"); - write_bytes(&no_nl_map, b"eod\tAAPL.US\t2020-01-01\t\t1"); - let rows = load_provider_mapping_tsv(&no_nl_map).expect("no trailing newline map"); - assert_eq!(rows.len(), 1); - assert_eq!(rows[0].listing_id, 1); - - let no_nl_curr = dir.path().join("no_nl_curr.tsv"); - write_bytes(&no_nl_curr, b"1\tUSD"); - let curr = load_listing_currencies_tsv(&no_nl_curr).expect("no trailing newline curr"); - assert_eq!(curr.get(&1).map(AsRef::as_ref), Some("USD")); - - let bad_map_cases: &[(&str, &[u8])] = &[ - ("four_cols", b"eod\tAAPL.US\t2020-01-01\t1\n"), - ("six_cols", b"eod\tAAPL.US\t2020-01-01\t\t1\textra\n"), - ("feb30", b"eod\tAAPL.US\t2024-02-30\t\t1\n"), - ("slash_date", b"eod\tAAPL.US\t2024/01/02\t\t1\n"), - ("blank_valid_to", b"eod\tAAPL.US\t2020-01-01\t \t1\n"), - ("i32_overflow", b"eod\tAAPL.US\t2020-01-01\t\t2147483648\n"), - ("empty_source", b"\tAAPL.US\t2020-01-01\t\t1\n"), - ("blank_source_id", b"eod\t \t2020-01-01\t\t1\n"), - ("interior_cr", b"eod\tAA\rPL.US\t2020-01-01\t\t1\n"), - ("comma_sep", b"eod,AAPL.US,2020-01-01,,1\n"), - ]; - for (name, content) in bad_map_cases { - let p = dir.path().join(format!("bad_map_{name}.tsv")); - write_bytes(&p, content); - let err = load_provider_mapping_tsv(&p).unwrap_err(); - assert!( - matches!(err, RunCurateBarsError::TsvParse { line: 1, .. }), - "case {name}: expected TsvParse line 1, got {err:?}" - ); - assert!(err.to_string().contains(":1:"), "case {name}: {err}"); - } - - let bad_curr_cases: &[(&str, &[u8])] = &[ - ("empty_curr", b"1\t\n"), - ("blank_curr", b"1\t \n"), - ("extra_col", b"1\tUSD\textra\n"), - ("interior_cr", b"1\tUS\rD\n"), - ]; - for (name, content) in bad_curr_cases { - let p = dir.path().join(format!("bad_curr_{name}.tsv")); - write_bytes(&p, content); - let err = load_listing_currencies_tsv(&p).unwrap_err(); - assert!( - matches!(err, RunCurateBarsError::TsvParse { line: 1, .. }), - "case {name}: expected TsvParse line 1, got {err:?}" - ); - assert!(err.to_string().contains(":1:"), "case {name}: {err}"); - } - - // valid_to < valid_from fails with ProviderMappingError::InvalidRange. - let inv_range_map = dir.path().join("inv_range_map.tsv"); - write_bytes(&inv_range_map, b"eod\tAAPL.US\t2024-06-01\t2024-05-01\t1\n"); - let empty_eod = dir.path().join("empty_eod.bson"); - let empty_splits = dir.path().join("empty_splits.bson"); - write_bytes(&empty_eod, b""); - write_bytes(&empty_splits, b""); - let err = run_curate_bars_1d(&CurateBars1dArgs { - eod_prices: empty_eod, - qm_splits: empty_splits, - qm_prices: None, - provider_mapping: inv_range_map, - listing_currencies: no_nl_curr, - out_dir: dir.path().join("out_inv_range"), - rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, - threads: 1, - }) - .unwrap_err(); - assert!(matches!( - err, - RunCurateBarsError::ProviderMapping { - source: ProviderMappingError::InvalidRange { .. }, - .. - } - )); -} - -fn qm_price_doc_f64(code: &str, date: &str, share_volume: f64) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), code); - doc.append(cstr!("date"), date); - doc.append(cstr!("sharevolume"), share_volume); - doc.into_bytes() -} - -fn qm_price_doc_i32(code: &str, date: &str, share_volume: i32) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), code); - doc.append(cstr!("date"), date); - doc.append(cstr!("sharevolume"), share_volume); - doc.into_bytes() -} - -fn qm_price_doc_i64(code: &str, date: &str, share_volume: i64) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), code); - doc.append(cstr!("date"), date); - doc.append(cstr!("sharevolume"), share_volume); - doc.into_bytes() -} - -fn assert_qm_accounting_invariants(report: &CurateBars1dRunReport) { - assert_eq!( - report.qm_prices_decode.docs_in, - report.qm_prices_decode.decoded + report.qm_prices_decode.rejected_total(), - "qm_prices_decode conservation violated: {:?}", - report.qm_prices_decode - ); - assert_eq!( - report.qm_rekey.qm_in, report.qm_prices_decode.docs_in, - "qm_in must match qm_prices_decode.docs_in" - ); - assert_eq!( - report.qm_rekey.qm_in, - report.qm_rekey.qm_attached - + report.qm_rekey.qm_unmapped_qm - + report.qm_rekey.qm_no_eod_partner - + report.qm_prices_decode.rejected_total(), - "qm_rekey conservation violated: {:?}", - report.qm_rekey - ); - let b = &report.curate_stats.builder; - assert_eq!( - report.qm_rekey.qm_volumes_attached, b.qm_rows_in, - "qm_volumes_attached must equal builder.qm_rows_in" - ); - assert_eq!( - b.volume_checked + b.volume_unchecked, - b.rows_out, - "volume_checked + volume_unchecked != rows_out" - ); - assert_eq!( - b.volume_within_tolerance + b.volume_mismatched, - b.volume_checked, - "volume_within_tolerance + volume_mismatched != volume_checked" - ); - assert_eq!( - b.qm_rows_in, - b.qm_unique_partners - + b.qm_invalid_volume_dropped - + b.qm_duplicate_collapsed - + b.qm_duplicate_conflict_dropped, - "builder qm conservation violated" - ); -} - -#[test] -fn qm_prices_nvda_split_cross_check_mismatch_samples_and_readonly_parquet_invariance() { - let dir = TestTempDir::new("qm-nvda-split"); - let eod_path = dir.path().join("eodPrices.bson"); - let splits_path = dir.path().join("qmSplits.bson"); - let qm_path = dir.path().join("qmPrices.bson"); - let qm_shuf_path = dir.path().join("qmPrices_shuf.bson"); - let map_path = dir.path().join("provider_mapping.tsv"); - let curr_path = dir.path().join("listing_currencies.tsv"); - - write_bytes( - &map_path, - b"eod\tNVDA.US\t2020-01-01\t\t101\n\ - qm\tNVDA\t2020-01-01\t\t101\n", - ); - write_bytes(&curr_path, b"101\tUSD\n"); - - // 10:1 forward split on 2024-06-10. - write_bytes(&splits_path, &split_doc("NVDA", "2024-06-10", 10.0)); - - // 5 EOD bars across 2023 and 2024. - let eod_docs = [ - // 2023-12-29 (pre-split, factor=10 -> raw vol 30_000_000): conflicting QM dups -> unchecked - eod_doc("NVDA.US", "2023-12-29", 495.0, 500.0, 490.0, 495.22, 300_000_000.0), - // 2024-06-06 (pre-split, factor=10 -> raw vol 40_000_000): injected >1% mismatch (38_000_000 -> ~5.26%) - eod_doc("NVDA.US", "2024-06-06", 1200.0, 1220.0, 1190.0, 1210.0, 400_000_000.0), - // 2024-06-07 (pre-split, factor=10 -> raw vol 41_239_000): matches QM within 1% - eod_doc("NVDA.US", "2024-06-07", 1197.7, 1216.92, 1180.22, 1208.88, 412_390_000.0), - // 2024-06-10 (exact ex-date, factor=1 -> raw vol 314_162_700): matches QM exact (Int64) - eod_doc("NVDA.US", "2024-06-10", 120.37, 123.10, 117.01, 121.79, 314_162_700.0), - // 2024-06-11 (post-split, factor=1 -> raw vol 222_551_200): matches QM exact (Int32) - eod_doc("NVDA.US", "2024-06-11", 121.77, 122.87, 118.74, 120.91, 222_551_200.0), - ]; - write_bytes(&eod_path, &eod_docs.concat()); - - let mut wrong_type_doc = RawDocumentBuf::new(); - wrong_type_doc.append(cstr!("qmSearchCode"), "NVDA"); - wrong_type_doc.append(cstr!("date"), "2024-06-07"); - wrong_type_doc.append(cstr!("sharevolume"), "not-numeric"); - - let qm_docs: Vec> = vec![ - qm_price_doc_f64("NVDA", "2023-12-29", 30_000_000.0), - qm_price_doc_f64("NVDA", "2023-12-29", 30_500_000.0), // conflict -> both dropped -> unchecked - qm_price_doc_f64("NVDA", "2024-06-06", 38_000_000.0), // >1% divergence - qm_price_doc_f64("NVDA", "2024-06-07", 41_300_000.0), // ~0.148% diff -> within 1% - qm_price_doc_i64("NVDA", "2024-06-10", 314_162_700), // exact Int64 - qm_price_doc_i32("NVDA", "2024-06-11", 222_551_200), // exact Int32 - qm_price_doc_f64("NVDA", "2024-06-07", -5.0), // invalid volume dropped by builder - qm_price_doc_f64("NVDA", "2024-06-07", f64::NAN), // invalid volume dropped by builder - wrong_type_doc.into_bytes(), // rejected by decoder - ]; - write_bytes(&qm_path, &qm_docs.concat()); - let mut shuf = qm_docs.clone(); - shuf.reverse(); - write_bytes(&qm_shuf_path, &shuf.concat()); - - let out_without = dir.path().join("out_without"); - let out_with = dir.path().join("out_with"); - let out_shuf = dir.path().join("out_shuf"); - let out_timed = dir.path().join("out_timed"); - - let r_without = run_curate_bars_1d(&CurateBars1dArgs { - eod_prices: eod_path.clone(), - qm_splits: splits_path.clone(), - qm_prices: None, - provider_mapping: map_path.clone(), - listing_currencies: curr_path.clone(), - out_dir: out_without.clone(), - rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, - threads: 1, - }) - .unwrap(); - - let r_with = run_curate_bars_1d(&CurateBars1dArgs { - eod_prices: eod_path.clone(), - qm_splits: splits_path.clone(), - qm_prices: Some(qm_path.clone()), - provider_mapping: map_path.clone(), - listing_currencies: curr_path.clone(), - out_dir: out_with.clone(), - rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, - threads: 1, - }) - .unwrap(); - - let r_shuf = run_curate_bars_1d(&CurateBars1dArgs { - eod_prices: eod_path.clone(), - qm_splits: splits_path.clone(), - qm_prices: Some(qm_shuf_path), - provider_mapping: map_path.clone(), - listing_currencies: curr_path.clone(), - out_dir: out_shuf.clone(), - rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, - threads: 1, - }) - .unwrap(); - - let r_timed = run_curate_bars_1d_timed(&CurateBars1dArgs { - eod_prices: eod_path, - qm_splits: splits_path, - qm_prices: Some(qm_path), - provider_mapping: map_path, - listing_currencies: curr_path, - out_dir: out_timed.clone(), - rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, - threads: 1, - }) - .unwrap(); - - assert!(!r_without.qm_prices_present); - assert!(r_with.qm_prices_present); - assert_qm_accounting_invariants(&r_with); - assert_qm_accounting_invariants(&r_shuf); - assert_qm_accounting_invariants(&r_timed.report); - - assert_eq!(r_with.qm_prices_decode.docs_in, 9); - assert_eq!(r_with.qm_prices_decode.decoded, 8); - assert_eq!(r_with.qm_prices_decode.rejected_wrong_type, 1); - assert_eq!(r_with.qm_rekey.qm_attached, 8); - assert_eq!(r_with.qm_rekey.qm_volumes_attached, 8); - - let b = &r_with.curate_stats.builder; - assert_eq!(b.rows_out, 5); - assert_eq!(b.qm_rows_in, 8); - assert_eq!(b.qm_invalid_volume_dropped, 2); - assert_eq!(b.qm_duplicate_conflict_dropped, 2); - assert_eq!(b.qm_unique_partners, 4); - assert_eq!(b.volume_checked, 4); - assert_eq!(b.volume_within_tolerance, 3); - assert_eq!(b.volume_mismatched, 1); - assert_eq!(b.volume_unchecked, 1); - - assert_eq!(r_with.mismatch_samples.len(), 1); - let sample = &r_with.mismatch_samples[0]; - assert_eq!(sample.key.as_ref(), "NVDA.US"); - assert_eq!(sample.session_date, ymd_to_epoch_days(2024, 6, 6).unwrap()); - assert!((sample.volume - 40_000_000.0).abs() < 1e-6); - assert!((sample.share_volume - 38_000_000.0).abs() < 1e-6); - assert!(sample.rel > 0.05 && sample.rel < 0.06); - - // Cross-check is strictly read-only: emitted Parquet files are byte-identical across all runs. - for year in [2023, 2024] { - let rel_path = format!("bars_1d/year={year}/part.parquet"); - let bytes_without = fs::read(out_without.join(&rel_path)).unwrap(); - let bytes_with = fs::read(out_with.join(&rel_path)).unwrap(); - let bytes_shuf = fs::read(out_shuf.join(&rel_path)).unwrap(); - let bytes_timed = fs::read(out_timed.join(&rel_path)).unwrap(); - assert_eq!(bytes_without, bytes_with, "Parquet bytes differed for {year}"); - assert_eq!(bytes_with, bytes_shuf, "Shuffled QM altered Parquet for {year}"); - assert_eq!(bytes_with, bytes_timed, "Timed run altered Parquet for {year}"); - } - - // Report formatting assertions + determinism across shuffled qmPrices and timed run. - let strip_timing = |s: &str| { - s.lines() - .filter(|l| !l.trim_start().starts_with("timing:")) - .collect::>() - .join("\n") - }; - let text_without = format_curate_bars_report(&r_without); - let text_with = format_curate_bars_report(&r_with); - let text_shuf = format_curate_bars_report(&r_shuf); - let text_timed = format_curate_bars_report(&r_timed.report); - - assert!(text_without.contains("qm_check: qm_prices=absent"), "{text_without}"); - assert!(text_with.contains("qm_bson:"), "{text_with}"); - assert!(text_with.contains("qm_rekey:"), "{text_with}"); - assert!( - text_with.contains("volume_checked=4 volume_within_tolerance=3 volume_mismatched=1 volume_unchecked=1"), - "{text_with}" - ); - assert!( - text_with.contains("qm_mismatch: key=NVDA.US session_date=2024-06-06"), - "{text_with}" - ); - assert_eq!(strip_timing(&text_with), strip_timing(&text_shuf)); - assert_eq!(strip_timing(&text_with), strip_timing(&text_timed)); -} - -#[test] -fn qm_prices_date_aware_rekey_reused_ticker_rename_alias_fanout_and_unmapped_counts() { - let dir = TestTempDir::new("qm-date-aware-rekey"); - let eod_path = dir.path().join("eodPrices.bson"); - let splits_path = dir.path().join("qmSplits.bson"); - let qm_path = dir.path().join("qmPrices.bson"); - let map_path = dir.path().join("provider_mapping.tsv"); - let curr_path = dir.path().join("listing_currencies.tsv"); - - // Reused EOD ticker FB.US: listing 10 (2012-01-01..=2022-06-08), listing 20 (2025-01-01..). - // Rename on listing 10: META.US (2022-06-09..). - // Multi-EOD alias on listing 30: ALIAS_A.US & ALIAS_B.US both cover 2024-01-01.. - // QM-only listing 40: QMONLY:US has no EOD partner at all. - // Date-gap partner test on listing 20: QM FBETF:US starts 2024-01-01 while EOD FB.US starts 2025-01-01. - write_bytes( - &map_path, - b"eod\tFB.US\t2012-01-01\t2022-06-08\t10\n\ - eod\tMETA.US\t2022-06-09\t\t10\n\ - qm\tFB:US\t2012-01-01\t2022-06-08\t10\n\ - qm\tMETA:US\t2022-06-09\t\t10\n\ - eod\tFB.US\t2025-01-01\t\t20\n\ - qm\tFBETF:US\t2024-01-01\t\t20\n\ - eod\tALIAS_A.US\t2024-01-01\t\t30\n\ - eod\tALIAS_B.US\t2024-01-01\t\t30\n\ - qm\tALIAS:US\t2024-01-01\t\t30\n\ - qm\tQMONLY:US\t2024-01-01\t\t40\n", - ); - write_bytes(&curr_path, b"10\tUSD\n20\tUSD\n30\tUSD\n40\tUSD\n"); - write_bytes(&splits_path, b""); - - let eod_docs = [ - // Listing 10 pre-rename on FB.US (vol 1_000) - eod_doc("FB.US", "2022-06-08", 190.0, 195.0, 188.0, 192.0, 1_000.0), - // Listing 10 post-rename on META.US (vol 2_000) - eod_doc("META.US", "2022-06-09", 191.0, 194.0, 189.0, 193.0, 2_000.0), - // Listing 20 on reused ticker FB.US (vol 5_000) - eod_doc("FB.US", "2025-01-02", 25.0, 26.0, 24.5, 25.5, 5_000.0), - // Listing 30 on both EOD aliases (identical OHLCV -> collapses in curate_bars_1d, both checked in builder) - eod_doc("ALIAS_A.US", "2024-05-01", 50.0, 52.0, 49.0, 51.0, 7_000.0), - eod_doc("ALIAS_B.US", "2024-05-01", 50.0, 52.0, 49.0, 51.0, 7_000.0), - ]; - write_bytes(&eod_path, &eod_docs.concat()); - - let qm_docs = [ - // 1. Listing 10 on 2022-06-08 -> attaches ONLY to FB.US (matches 1_000) - qm_price_doc_f64("FB:US", "2022-06-08", 1_000.0), - // 2. Listing 10 on 2022-06-09 -> attaches ONLY to META.US (matches 2_000) - qm_price_doc_f64("META:US", "2022-06-09", 2_000.0), - // 3. Listing 20 on 2025-01-02 -> attaches ONLY to FB.US (matches 5_000) - qm_price_doc_f64("FBETF:US", "2025-01-02", 5_000.0), - // 4. Listing 30 on 2024-05-01 -> fans out to BOTH ALIAS_A.US and ALIAS_B.US (2 volumes attached) - qm_price_doc_f64("ALIAS:US", "2024-05-01", 7_000.0), - // 5. Unmapped QM key -> qm_unmapped_qm - qm_price_doc_f64("UNKNOWN:US", "2024-05-01", 999.0), - // 6. Expired QM key outside its range -> qm_unmapped_qm - qm_price_doc_f64("FB:US", "2025-01-02", 999.0), - // 7. QM-only listing (no EOD mapping at all) -> qm_no_eod_partner - qm_price_doc_f64("QMONLY:US", "2024-05-01", 333.0), - // 8. Listing 20 date before EOD mapping starts -> date-aware lookup finds no EOD partner -> qm_no_eod_partner - qm_price_doc_f64("FBETF:US", "2024-06-01", 444.0), - ]; - write_bytes(&qm_path, &qm_docs.concat()); - - let report = run_curate_bars_1d(&CurateBars1dArgs { - eod_prices: eod_path, - qm_splits: splits_path, - qm_prices: Some(qm_path), - provider_mapping: map_path, - listing_currencies: curr_path, - out_dir: dir.path().join("out"), - rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, - threads: 1, - }) - .unwrap(); - - assert_qm_accounting_invariants(&report); - assert_eq!(report.qm_rekey.qm_in, 8); - assert_eq!(report.qm_rekey.qm_attached, 4); - assert_eq!(report.qm_rekey.qm_volumes_attached, 5); // 1 + 1 + 1 + 2 (alias fan-out) - assert_eq!(report.qm_rekey.qm_unmapped_qm, 2); - assert_eq!(report.qm_rekey.qm_no_eod_partner, 2); - - let b = &report.curate_stats.builder; - assert_eq!(b.rows_out, 5); - assert_eq!(b.volume_checked, 5); - assert_eq!(b.volume_within_tolerance, 5); - assert_eq!(b.volume_mismatched, 0); - assert_eq!(b.volume_unchecked, 0); -} - -#[test] -fn run_curate_bars_1d_threads_1_and_4_produce_byte_identical_parquet_and_matching_report() { - let dir = TestTempDir::new("threads-parity"); - let map_path = dir.path().join("provider_mapping.tsv"); - let curr_path = dir.path().join("listing_currencies.tsv"); - let splits_path = dir.path().join("qmSplits.bson"); - let eod_path = dir.path().join("eodPrices.bson"); - - write_bytes( - &map_path, - b"eod\tAAA.US\t2020-01-01\t\t10\n\ - eod\tBBB.TO\t2020-01-01\t\t20\n\ - qm\tAAA:US\t2020-01-01\t\t10\n", - ); - write_bytes(&curr_path, b"10\tUSD\n20\tCAD\n"); - write_bytes(&splits_path, &split_doc("AAA:US", "2023-06-01", 2.0)); - - let eod_docs = [ - eod_doc("AAA.US", "2021-03-10", 10.0, 11.0, 9.5, 10.5, 2000.0), - eod_doc("AAA.US", "2022-04-12", 12.0, 13.0, 11.5, 12.5, 2400.0), - eod_doc("AAA.US", "2023-07-14", 14.0, 15.0, 13.5, 14.5, 1500.0), - eod_doc("BBB.TO", "2022-05-02", 20.0, 21.0, 19.5, 20.5, 3000.0), - eod_doc("BBB.TO", "2024-08-08", 22.0, 23.0, 21.5, 22.5, 3200.0), - ]; - write_bytes(&eod_path, &eod_docs.concat()); - - let out_1 = dir.path().join("out_t1"); - let out_4 = dir.path().join("out_t4"); - - let r1 = run_curate_bars_1d(&CurateBars1dArgs { - eod_prices: eod_path.clone(), - qm_splits: splits_path.clone(), - qm_prices: None, - provider_mapping: map_path.clone(), - listing_currencies: curr_path.clone(), - out_dir: out_1.clone(), - rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, - threads: 1, - }) - .unwrap(); - let r4 = run_curate_bars_1d(&CurateBars1dArgs { - eod_prices: eod_path.clone(), - qm_splits: splits_path.clone(), - qm_prices: None, - provider_mapping: map_path.clone(), - listing_currencies: curr_path.clone(), - out_dir: out_4.clone(), - rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, - threads: 4, - }) - .unwrap(); - - assert_eq!(r1.threads, 1); - assert_eq!(r4.threads, 4); - assert_eq!(r1.write_stats, r4.write_stats); - assert_eq!(r1.curate_stats, r4.curate_stats); - - for year in [2021_i32, 2022, 2023, 2024] { - let rel = format!("bars_1d/year={year:04}/part.parquet"); - assert_eq!( - fs::read(out_1.join(&rel)).unwrap(), - fs::read(out_4.join(&rel)).unwrap(), - "byte mismatch for {rel}" - ); - } - - let strip_config_and_timing = |text: &str| -> String { - text.lines() - .filter(|line| { - let t = line.trim_start(); - !t.starts_with("config:") && !t.starts_with("timing:") - }) - .collect::>() - .join("\n") - }; - let rep1 = format_curate_bars_report(&r1); - let rep4 = format_curate_bars_report(&r4); - assert!(rep1.contains(" config: threads=1\n"), "{rep1}"); - assert!(rep4.contains(" config: threads=4\n"), "{rep4}"); - assert_eq!( - strip_config_and_timing(&rep1), - strip_config_and_timing(&rep4) - ); - - // Zero threads fails closed before touching --out. - let out_0 = dir.path().join("out_t0"); - let err = run_curate_bars_1d(&CurateBars1dArgs { - eod_prices: eod_path, - qm_splits: splits_path, - qm_prices: None, - provider_mapping: map_path, - listing_currencies: curr_path, - out_dir: out_0.clone(), - rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, - threads: 0, - }) - .unwrap_err(); - assert!( - matches!( - err, - RunCurateBarsError::CurateWrite { - source: CurateBarsWriteError::Parquet(crate::parquet_bars::ParquetBarsError::InvalidThreads), - .. - } - ), - "unexpected error: {err:?}" - ); - assert!(!out_0.exists()); -} diff --git a/tools/curate-etl/src/run_curate_corporate_actions.rs b/tools/curate-etl/src/run_curate_corporate_actions.rs deleted file mode 100644 index df9f8f05..00000000 --- a/tools/curate-etl/src/run_curate_corporate_actions.rs +++ /dev/null @@ -1,923 +0,0 @@ -//! File-to-file `curate-corporate-actions` command runner (`M1.2ab`). -//! -//! Streams concatenated raw BSON `qmSplits` and `qmDividends` dump files alongside -//! `provider_mapping.tsv` and an optional Pass 6 `delistings.tsv` into an atomically published -//! `/corporate_actions/part.parquet` dataset via [`curate_and_write_corporate_actions`]. -//! -//! # TSV Formats (strict, headerless, `\t`-separated) -//! - `provider_mapping` (5 columns; reused verbatim from [`crate::run_curate_bars`]): -//! `source \t source_id \t valid_from(YYYY-MM-DD) \t valid_to(YYYY-MM-DD or empty) \t listing_id` -//! - `delistings` (optional file; 5 columns when supplied): -//! `source_id \t delist_date(YYYY-MM-DD) \t from_listing_id(int or empty) \t successor_source_id(or empty) \t terminal_return(float or empty)` -//! - `source_id` is preserved verbatim (never trimmed) and must not be empty or whitespace-only. -//! - `delist_date` is parsed strictly as `YYYY-MM-DD` Gregorian. -//! - `from_listing_id` is empty (`None`) or a strict positive ASCII base-10 `i32`. -//! - `successor_source_id` is empty (`None`) or a non-blank string preserved verbatim. -//! - `terminal_return` is empty (`None`) or a finite `f64` in `[-1.0, 0.0]` with no leading or -//! trailing whitespace (`-0.0` is normalized to `0.0`). -//! - Exactly one of `successor_source_id` or `terminal_return` must be set on every row. -//! - Any row with `successor_source_id` set (OTC transfer) requires `from_listing_id` to be set. -//! - Both TSVs accept `\n` or `\r\n` line endings and at most one trailing blank line. -//! -//! # `declared_date` / `known_at` & Contract Rules -//! - `RawQmSplit::to_split_action_event` and `RawQmDividend::to_dividend_action_event` already -//! carry `declared_date` (`Option`) from the raw BSON `declared` field when present. -//! - Downstream [`crate::corporate_actions::build_corporate_actions`] clamps late declarations -//! (`declared_date > ex_date`) to `ex_date` with `KnownAtSource::ExDateFallback`, and -//! [`curate_corporate_actions`] stamps `known_at = 16:00:00 ET` of `known_at_date`. -//! - `usdFxRate` stays ignored per `design/DATA-CONTRACTS.md` §1; `splitratio == 1.0` no-op drops -//! and `cash == 0.0` dividend drops stay delegated unchanged to -//! [`curate_and_write_corporate_actions`]. -//! - **Empty-input behavior:** delegated unchanged to [`curate_and_write_corporate_actions`] / -//! [`write_corporate_actions_dataset`], which returns `Ok` with `rows_written == 0` and -//! `files_written == 0` without creating `/corporate_actions` or modifying any -//! pre-existing `part.parquet` (matching `curate-bars-1d`). -//! -//! # Counter Conservation Invariants -//! Every successful [`CurateCorporateActionsRunReport`] satisfies: -//! - Splits: -//! `splits_docs_framed as usize == splits_decode.docs_in == splits_decode.decoded + splits_decode.rejected_total()` -//! `splits_decode.decoded == curate_stats.builder.splits_in == curate_stats.builder.splits_out + curate_stats.builder.split_noops_dropped` -//! - Dividends: -//! `dividends_docs_framed as usize == dividends_decode.docs_in == dividends_decode.decoded + dividends_decode.rejected_total()` -//! `dividends_decode.decoded == curate_stats.builder.dividends_in == curate_stats.builder.dividends_out + curate_stats.builder.dividend_zero_cash_dropped` -//! - Delistings: -//! `delistings_rows_loaded == curate_stats.builder.delistings_in == curate_stats.builder.otc_delist_transfers_out + curate_stats.builder.delistings_out` -//! (`curate_stats.builder.delist_without_outcome == 0` because strict TSV validation requires -//! exactly one outcome per row) -//! - Stage & Write: -//! `curate_stats.rows_in == curate_stats.builder.rows_out == curate_stats.rows_out + curate_stats.dropped_unmapped + curate_stats.dropped_unmapped_successor + curate_stats.dropped_self_successor + curate_stats.dropped_known_at_out_of_range + curate_stats.listing_collision_collapsed + curate_stats.listing_collision_dropped` -//! `write_stats.rows_written == curate_stats.rows_out` - -use std::collections::HashSet; -use std::error::Error; -use std::fmt; -use std::fs::{self, File}; -use std::io; -use std::path::{Path, PathBuf}; -use std::sync::Arc; -use std::time::Instant; - -use crate::bson_eod_prices::parse_ymd_strict_days; -use crate::bson_qm_actions::{BsonQmActionDecodeStats, BsonQmActionError}; -use crate::bson_stream::{ - decode_qm_dividend_chunks, decode_qm_split_chunks, BsonStreamError, BsonStreamOptions, - RawBsonChunkReader, -}; -use crate::corporate_actions::{DelistingOutcomeEvent, DividendActionEvent, SplitActionEvent}; -use crate::curate_corporate_actions::{ - curate_and_write_corporate_actions, curate_corporate_actions, CurateCorporateActionsStats, - CurateCorporateActionsWriteError, CurateDelistingInput, -}; -use crate::parquet_corporate_actions::{ - write_corporate_actions_dataset, CorporateActionsParquetRow, CorporateActionsWriteOptions, - CorporateActionsWriteStats, -}; -use crate::provider_mapping::{ProviderMappingError, ProviderMappingTable}; -use crate::run_curate_bars::{ - load_provider_mapping_tsv, parse_strict_positive_i32, read_tsv_lines, RunCurateBarsError, -}; - -/// Parsed arguments for the `curate-corporate-actions` CLI command. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct CurateCorporateActionsArgs { - pub qm_splits: PathBuf, - pub qm_dividends: PathBuf, - pub provider_mapping: PathBuf, - pub delistings: Option, - pub out_dir: PathBuf, -} - -/// Full run report produced by [`run_curate_corporate_actions`]. -/// -/// Conservation invariants: -/// - `splits_docs_framed as usize == splits_decode.docs_in == splits_decode.decoded + splits_decode.rejected_total()` -/// - `splits_decode.decoded == curate_stats.builder.splits_in == curate_stats.builder.splits_out + curate_stats.builder.split_noops_dropped` -/// - `dividends_docs_framed as usize == dividends_decode.docs_in == dividends_decode.decoded + dividends_decode.rejected_total()` -/// - `dividends_decode.decoded == curate_stats.builder.dividends_in == curate_stats.builder.dividends_out + curate_stats.builder.dividend_zero_cash_dropped` -/// - `delistings_rows_loaded == curate_stats.builder.delistings_in == curate_stats.builder.otc_delist_transfers_out + curate_stats.builder.delistings_out` -/// - `curate_stats.rows_in == curate_stats.builder.rows_out == curate_stats.rows_out + curate_stats.dropped_unmapped + curate_stats.dropped_unmapped_successor + curate_stats.dropped_self_successor + curate_stats.dropped_known_at_out_of_range + curate_stats.listing_collision_collapsed + curate_stats.listing_collision_dropped` -/// - `write_stats.rows_written == curate_stats.rows_out` -#[derive(Debug, Clone, PartialEq)] -pub struct CurateCorporateActionsRunReport { - pub splits_docs_framed: u64, - pub splits_bytes_read: u64, - pub splits_decode: BsonQmActionDecodeStats, - pub dividends_docs_framed: u64, - pub dividends_bytes_read: u64, - pub dividends_decode: BsonQmActionDecodeStats, - pub delistings_rows_loaded: usize, - pub delistings_bytes_read: u64, - pub curate_stats: CurateCorporateActionsStats, - pub write_stats: CorporateActionsWriteStats, - pub elapsed_secs: f64, -} - -/// Stage-timed run output used internally by `bench-curate-corporate-actions-cmd`. -#[derive(Debug, Clone, PartialEq)] -pub(crate) struct CurateCorporateActionsTimedRun { - pub report: CurateCorporateActionsRunReport, - pub decode_elapsed_secs: f64, - pub curate_elapsed_secs: f64, - pub write_elapsed_secs: f64, - pub checksum: u64, -} - -/// Typed errors returned by [`run_curate_corporate_actions`] and [`load_delistings_tsv`]. -/// -/// Every variant's `Display` output is a single line naming the offending path (and 1-based line -/// number for TSV parse errors, or absolute stream byte offset via [`BsonStreamError`] / -/// `CorruptBson`). -#[derive(Debug)] -pub enum RunCurateCorporateActionsError { - InvalidOutDir { - path: PathBuf, - detail: String, - }, - OpenInput { - label: &'static str, - path: PathBuf, - source: io::Error, - }, - ReadInput { - label: &'static str, - path: PathBuf, - source: io::Error, - }, - TsvParse { - path: PathBuf, - line: usize, - detail: String, - }, - ProviderMapping { - path: PathBuf, - source: ProviderMappingError, - }, - BsonStream { - label: &'static str, - path: PathBuf, - source: BsonStreamError, - }, - CorruptBson { - label: &'static str, - path: PathBuf, - offset: u64, - source: BsonQmActionError, - }, - CurateWrite { - out_dir: PathBuf, - source: CurateCorporateActionsWriteError, - }, -} - -impl fmt::Display for RunCurateCorporateActionsError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::InvalidOutDir { path, detail } => { - write!(f, "invalid --out '{}': {detail}", path.display()) - } - Self::OpenInput { - label, - path, - source, - } => write!(f, "failed to open {label} '{}': {source}", path.display()), - Self::ReadInput { - label, - path, - source, - } => write!(f, "failed to read {label} '{}': {source}", path.display()), - Self::TsvParse { path, line, detail } => { - write!(f, "{}:{line}: {detail}", path.display()) - } - Self::ProviderMapping { path, source } => { - write!(f, "invalid provider_mapping '{}': {source}", path.display()) - } - Self::BsonStream { - label, - path, - source, - } => write!(f, "failed reading {label} '{}': {source}", path.display()), - Self::CorruptBson { - label, - path, - offset, - source, - } => write!( - f, - "corrupt {label} BSON '{}' at byte offset {offset}: {source}", - path.display() - ), - Self::CurateWrite { out_dir, source } => { - write!(f, "curate/write to '{}' failed: {source}", out_dir.display()) - } - } - } -} - -impl Error for RunCurateCorporateActionsError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::OpenInput { source, .. } | Self::ReadInput { source, .. } => Some(source), - Self::ProviderMapping { source, .. } => Some(source), - Self::BsonStream { source, .. } => Some(source), - Self::CorruptBson { source, .. } => Some(source), - Self::CurateWrite { source, .. } => Some(source), - Self::InvalidOutDir { .. } | Self::TsvParse { .. } => None, - } - } -} - -fn map_tsv_io_error(path: &Path, err: RunCurateBarsError) -> RunCurateCorporateActionsError { - match err { - RunCurateBarsError::OpenInput { - label, - path, - source, - } => RunCurateCorporateActionsError::OpenInput { - label, - path, - source, - }, - RunCurateBarsError::ReadInput { - label, - path, - source, - } => RunCurateCorporateActionsError::ReadInput { - label, - path, - source, - }, - RunCurateBarsError::TsvParse { path, line, detail } => { - RunCurateCorporateActionsError::TsvParse { path, line, detail } - } - RunCurateBarsError::ProviderMapping { path, source } => { - RunCurateCorporateActionsError::ProviderMapping { path, source } - } - other => RunCurateCorporateActionsError::TsvParse { - path: path.to_path_buf(), - line: 0, - detail: other.to_string(), - }, - } -} - -/// Loads Pass 6 delisting outcomes from a strict headerless 5-column TSV file. -/// -/// Format (`\t`-separated, no header): -/// `source_id \t delist_date(YYYY-MM-DD) \t from_listing_id(int or empty) \t successor_source_id(or empty) \t terminal_return(float or empty)` -/// -/// Enforces: -/// - `source_id` preserved verbatim and non-blank. -/// - `delist_date` strict Gregorian `YYYY-MM-DD`. -/// - `from_listing_id` empty or strict positive ASCII `i32`. -/// - `successor_source_id` empty or non-blank (preserved verbatim). -/// - `terminal_return` empty or finite `f64` in `[-1.0, 0.0]` with no surrounding whitespace -/// (`-0.0` normalized to `0.0`). -/// - Exactly one of `successor_source_id` or `terminal_return` set. -/// - `successor_source_id` requires `from_listing_id` to be set. -pub fn load_delistings_tsv( - path: &Path, -) -> Result>, RunCurateCorporateActionsError> { - let mut rows = Vec::new(); - read_tsv_lines(path, "delistings", |_line_no, line| { - let mut fields = line.split('\t'); - let source_id = fields - .next() - .ok_or_else(|| "expected 5 tab-separated columns".to_string())?; - let delist_date_str = fields - .next() - .ok_or_else(|| "expected 5 tab-separated columns (got 1)".to_string())?; - let from_listing_id_str = fields - .next() - .ok_or_else(|| "expected 5 tab-separated columns (got 2)".to_string())?; - let successor_source_id_str = fields - .next() - .ok_or_else(|| "expected 5 tab-separated columns (got 3)".to_string())?; - let terminal_return_str = fields - .next() - .ok_or_else(|| "expected 5 tab-separated columns (got 4)".to_string())?; - if fields.next().is_some() { - return Err("expected 5 tab-separated columns (got more than 5)".to_string()); - } - - if source_id.trim().is_empty() { - return Err("source_id column must not be empty or blank".to_string()); - } - - let delist_date = parse_ymd_strict_days(delist_date_str).ok_or_else(|| { - format!("invalid delist_date '{delist_date_str}' (expected YYYY-MM-DD)") - })?; - - let from_listing_id = if from_listing_id_str.is_empty() { - None - } else { - Some(parse_strict_positive_i32(from_listing_id_str).ok_or_else(|| { - format!( - "invalid from_listing_id '{from_listing_id_str}' (expected positive integer or empty)" - ) - })?) - }; - - let successor_key = if successor_source_id_str.is_empty() { - None - } else { - if successor_source_id_str.trim().is_empty() { - return Err( - "successor_source_id column must be empty or non-blank".to_string(), - ); - } - Some(successor_source_id_str.to_owned()) - }; - - let terminal_return = if terminal_return_str.is_empty() { - None - } else { - if terminal_return_str.trim() != terminal_return_str { - return Err(format!( - "invalid terminal_return '{terminal_return_str}' (leading/trailing whitespace not allowed)" - )); - } - let parsed = terminal_return_str.parse::().map_err(|_| { - format!( - "invalid terminal_return '{terminal_return_str}' (expected finite float in [-1.0, 0.0])" - ) - })?; - if !parsed.is_finite() || !(-1.0..=0.0).contains(&parsed) { - return Err(format!( - "invalid terminal_return '{terminal_return_str}' (expected finite float in [-1.0, 0.0])" - )); - } - let normalized = if parsed == 0.0 { 0.0 } else { parsed }; - Some(normalized) - }; - - match (successor_key.is_some(), terminal_return.is_some()) { - (true, true) => { - return Err( - "delisting row must set exactly one of successor_source_id or terminal_return (got both)" - .to_string(), - ); - } - (false, false) => { - return Err( - "delisting row must set exactly one of successor_source_id or terminal_return (got neither)" - .to_string(), - ); - } - (true, false) => { - if from_listing_id.is_none() { - return Err( - "delisting row with successor_source_id requires from_listing_id" - .to_string(), - ); - } - } - (false, true) => {} - } - - let event = DelistingOutcomeEvent { - delist_date, - successor_key, - terminal_return, - }; - let input = match from_listing_id { - Some(id) => CurateDelistingInput::with_from_listing_id(source_id.to_owned(), id, event), - None => CurateDelistingInput::new(source_id.to_owned(), event), - }; - rows.push(input); - Ok(()) - }) - .map_err(|err| map_tsv_io_error(path, err))?; - - Ok(rows) -} - -fn validate_out_dir(out_dir: &Path) -> Result<(), RunCurateCorporateActionsError> { - if out_dir.exists() && !out_dir.is_dir() { - return Err(RunCurateCorporateActionsError::InvalidOutDir { - path: out_dir.to_path_buf(), - detail: "path exists and is not a directory".to_string(), - }); - } - Ok(()) -} - -fn load_provider_mapping_table( - path: &Path, -) -> Result { - let mapping_rows = - load_provider_mapping_tsv(path).map_err(|err| map_tsv_io_error(path, err))?; - - ProviderMappingTable::from_rows(mapping_rows).map_err(|source| { - RunCurateCorporateActionsError::ProviderMapping { - path: path.to_path_buf(), - source, - } - }) -} - -#[inline] -fn is_structural_bson_error(err: &BsonQmActionError) -> bool { - matches!( - err, - BsonQmActionError::TruncatedDocument { .. } - | BsonQmActionError::CorruptDocumentLength { .. } - | BsonQmActionError::CorruptBson { .. } - ) -} - -#[inline] -fn intern_qm_key(keys: &mut HashSet>, raw: &str) -> Arc { - if let Some(existing) = keys.get(raw) { - return Arc::clone(existing); - } - let arc: Arc = Arc::from(raw); - keys.insert(Arc::clone(&arc)); - arc -} - -struct DecodedCorporateActionInputs { - mapping: ProviderMappingTable, - splits: Vec<(Arc, SplitActionEvent)>, - dividends: Vec<(Arc, DividendActionEvent)>, - delistings: Vec>>, - splits_docs_framed: u64, - splits_bytes_read: u64, - splits_decode: BsonQmActionDecodeStats, - dividends_docs_framed: u64, - dividends_bytes_read: u64, - dividends_decode: BsonQmActionDecodeStats, - delistings_rows_loaded: usize, - delistings_bytes_read: u64, -} - -fn decode_all_inputs( - args: &CurateCorporateActionsArgs, -) -> Result { - decode_inputs_from_openers( - &args.provider_mapping, - args.delistings.as_deref(), - &args.qm_splits, - || { - File::open(&args.qm_splits).map_err(|source| { - RunCurateCorporateActionsError::OpenInput { - label: "qm-splits", - path: args.qm_splits.clone(), - source, - } - }) - }, - &args.qm_dividends, - || { - File::open(&args.qm_dividends).map_err(|source| { - RunCurateCorporateActionsError::OpenInput { - label: "qm-dividends", - path: args.qm_dividends.clone(), - source, - } - }) - }, - ) -} - -fn decode_inputs_from_openers( - provider_mapping_path: &Path, - delistings_path: Option<&Path>, - qm_splits_path: &Path, - open_splits: FS, - qm_dividends_path: &Path, - open_dividends: FD, -) -> Result -where - RS: io::Read, - FS: FnOnce() -> Result, - RD: io::Read, - FD: FnOnce() -> Result, -{ - let mapping = load_provider_mapping_table(provider_mapping_path)?; - let mut qm_keys: HashSet> = HashSet::new(); - - let (delistings, delistings_rows_loaded, delistings_bytes_read) = match delistings_path { - Some(path) => { - let raw_delistings = load_delistings_tsv(path)?; - let bytes_read = fs::metadata(path) - .map_err(|source| RunCurateCorporateActionsError::ReadInput { - label: "delistings", - path: path.to_path_buf(), - source, - })? - .len(); - let count = raw_delistings.len(); - let mut interned = Vec::with_capacity(count); - for item in raw_delistings { - let key = intern_qm_key(&mut qm_keys, &item.key); - let successor_key = item - .event - .successor_key - .as_deref() - .map(|s| intern_qm_key(&mut qm_keys, s)); - let event = DelistingOutcomeEvent { - delist_date: item.event.delist_date, - successor_key, - terminal_return: item.event.terminal_return, - }; - let input = match item.from_listing_id { - Some(id) => CurateDelistingInput::with_from_listing_id(key, id, event), - None => CurateDelistingInput::new(key, event), - }; - interned.push(input); - } - (interned, count, bytes_read) - } - None => (Vec::new(), 0, 0), - }; - - // Stream `qmSplits`. - let splits_stream = open_splits()?; - let mut splits_reader = - RawBsonChunkReader::with_options(splits_stream, BsonStreamOptions::default()).map_err( - |source| RunCurateCorporateActionsError::BsonStream { - label: "qm-splits", - path: qm_splits_path.to_path_buf(), - source, - }, - )?; - let mut splits: Vec<(Arc, SplitActionEvent)> = Vec::new(); - let mut splits_corrupt_err: Option<(u64, BsonQmActionError)> = None; - let splits_decode_res = decode_qm_split_chunks( - &mut splits_reader, - |split| { - let key = intern_qm_key(&mut qm_keys, split.qm_search_code); - splits.push((key, split.to_split_action_event())); - }, - |offset, err| { - if splits_corrupt_err.is_none() && is_structural_bson_error(&err) { - splits_corrupt_err = Some((offset, err)); - } - }, - ); - if let Some((offset, source)) = splits_corrupt_err { - return Err(RunCurateCorporateActionsError::CorruptBson { - label: "qm-splits", - path: qm_splits_path.to_path_buf(), - offset, - source, - }); - } - let splits_decode = splits_decode_res.map_err(|source| { - RunCurateCorporateActionsError::BsonStream { - label: "qm-splits", - path: qm_splits_path.to_path_buf(), - source, - } - })?; - let splits_docs_framed = splits_reader.docs_framed(); - let splits_bytes_read = splits_reader.bytes_read(); - - // Stream `qmDividends`. - let dividends_stream = open_dividends()?; - let mut dividends_reader = - RawBsonChunkReader::with_options(dividends_stream, BsonStreamOptions::default()).map_err( - |source| RunCurateCorporateActionsError::BsonStream { - label: "qm-dividends", - path: qm_dividends_path.to_path_buf(), - source, - }, - )?; - let mut dividends: Vec<(Arc, DividendActionEvent)> = Vec::new(); - let mut dividends_corrupt_err: Option<(u64, BsonQmActionError)> = None; - let dividends_decode_res = decode_qm_dividend_chunks( - &mut dividends_reader, - |div| { - let key = intern_qm_key(&mut qm_keys, div.qm_search_code); - dividends.push((key, div.to_dividend_action_event())); - }, - |offset, err| { - if dividends_corrupt_err.is_none() && is_structural_bson_error(&err) { - dividends_corrupt_err = Some((offset, err)); - } - }, - ); - if let Some((offset, source)) = dividends_corrupt_err { - return Err(RunCurateCorporateActionsError::CorruptBson { - label: "qm-dividends", - path: qm_dividends_path.to_path_buf(), - offset, - source, - }); - } - let dividends_decode = dividends_decode_res.map_err(|source| { - RunCurateCorporateActionsError::BsonStream { - label: "qm-dividends", - path: qm_dividends_path.to_path_buf(), - source, - } - })?; - let dividends_docs_framed = dividends_reader.docs_framed(); - let dividends_bytes_read = dividends_reader.bytes_read(); - - Ok(DecodedCorporateActionInputs { - mapping, - splits, - dividends, - delistings, - splits_docs_framed, - splits_bytes_read, - splits_decode, - dividends_docs_framed, - dividends_bytes_read, - dividends_decode, - delistings_rows_loaded, - delistings_bytes_read, - }) -} - -/// Runs the end-to-end `curate-corporate-actions` file-to-Parquet pipeline via -/// [`curate_and_write_corporate_actions`]. -/// -/// Any input, TSV, BSON framing, mapping, or curation error returns before touching -/// `args.out_dir`, leaving any pre-existing `/corporate_actions/part.parquet` -/// byte-identical. -pub fn run_curate_corporate_actions( - args: &CurateCorporateActionsArgs, -) -> Result { - let start = Instant::now(); - validate_out_dir(&args.out_dir)?; - - let decoded = decode_all_inputs(args)?; - finish_curate_corporate_actions(decoded, &args.out_dir, start) -} - -/// Runs `curate-corporate-actions` from arbitrary raw-BSON [`io::Read`] streams. -pub fn run_curate_corporate_actions_with_readers( - provider_mapping_path: &Path, - delistings_path: Option<&Path>, - qm_splits_input: (&Path, RS), - qm_dividends_input: (&Path, RD), - out_dir: &Path, -) -> Result { - let start = Instant::now(); - validate_out_dir(out_dir)?; - - let (qm_splits_path, splits_stream) = qm_splits_input; - let (qm_dividends_path, dividends_stream) = qm_dividends_input; - let decoded = decode_inputs_from_openers( - provider_mapping_path, - delistings_path, - qm_splits_path, - || Ok(splits_stream), - qm_dividends_path, - || Ok(dividends_stream), - )?; - finish_curate_corporate_actions(decoded, out_dir, start) -} - -fn finish_curate_corporate_actions( - decoded: DecodedCorporateActionInputs, - out_dir: &Path, - start: Instant, -) -> Result { - let write_report = curate_and_write_corporate_actions( - out_dir, - decoded.splits, - decoded.dividends, - decoded.delistings, - "qm", - &decoded.mapping, - CorporateActionsWriteOptions::default(), - ) - .map_err(|source| RunCurateCorporateActionsError::CurateWrite { - out_dir: out_dir.to_path_buf(), - source, - })?; - - Ok(CurateCorporateActionsRunReport { - splits_docs_framed: decoded.splits_docs_framed, - splits_bytes_read: decoded.splits_bytes_read, - splits_decode: decoded.splits_decode, - dividends_docs_framed: decoded.dividends_docs_framed, - dividends_bytes_read: decoded.dividends_bytes_read, - dividends_decode: decoded.dividends_decode, - delistings_rows_loaded: decoded.delistings_rows_loaded, - delistings_bytes_read: decoded.delistings_bytes_read, - curate_stats: write_report.curate_stats, - write_stats: write_report.write_stats, - elapsed_secs: start.elapsed().as_secs_f64(), - }) -} - -fn compute_rows_checksum(rows: &[CorporateActionsParquetRow]) -> u64 { - let mut hash = 0xcbf2_9ce4_8422_2325_u64; - let mix = |mut h: u64, v: u64| -> u64 { - h ^= v; - h = h.wrapping_mul(0x0000_0100_0000_01b3); - h - }; - for row in rows { - hash = mix(hash, row.listing_id as u64); - hash = mix(hash, row.ex_date as u64); - match row.declared_date { - Some(d) => { - hash = mix(hash, 1); - hash = mix(hash, d as u64); - } - None => { - hash = mix(hash, 0); - } - } - hash = mix(hash, row.kind as u64); - match row.ratio { - Some(r) => { - hash = mix(hash, 1); - hash = mix(hash, r.to_bits()); - } - None => { - hash = mix(hash, 0); - } - } - match row.cash_amount { - Some(c) => { - hash = mix(hash, 1); - hash = mix(hash, c.to_bits()); - } - None => { - hash = mix(hash, 0); - } - } - match row.currency.as_deref() { - Some(curr) => { - hash = mix(hash, 1); - hash = mix(hash, curr.len() as u64); - for &b in curr.as_bytes() { - hash = mix(hash, u64::from(b)); - } - } - None => { - hash = mix(hash, 0); - } - } - match row.successor_listing_id { - Some(id) => { - hash = mix(hash, 1); - hash = mix(hash, id as u64); - } - None => { - hash = mix(hash, 0); - } - } - match row.terminal_return { - Some(tr) => { - hash = mix(hash, 1); - hash = mix(hash, tr.to_bits()); - } - None => { - hash = mix(hash, 0); - } - } - hash = mix(hash, row.known_at_micros as u64); - hash = mix(hash, row.known_at_source as u64); - } - hash -} - -/// Stage-timed variant of [`run_curate_corporate_actions`] used internally by -/// `bench-curate-corporate-actions-cmd`. -/// -/// Times `decode` (mapping + optional delistings TSV + BSON streams), `curate` -/// (`curate_corporate_actions`), and `write` (`write_corporate_actions_dataset`) separately. -pub(crate) fn run_curate_corporate_actions_timed( - args: &CurateCorporateActionsArgs, -) -> Result { - let total_start = Instant::now(); - validate_out_dir(&args.out_dir)?; - - let decode_start = Instant::now(); - let decoded = decode_all_inputs(args)?; - let decode_elapsed_secs = decode_start.elapsed().as_secs_f64(); - - let curate_start = Instant::now(); - let curated = curate_corporate_actions( - decoded.splits, - decoded.dividends, - decoded.delistings, - "qm", - &decoded.mapping, - ) - .map_err(|source| RunCurateCorporateActionsError::CurateWrite { - out_dir: args.out_dir.clone(), - source: CurateCorporateActionsWriteError::Curate(source), - })?; - let curate_elapsed_secs = curate_start.elapsed().as_secs_f64(); - - let checksum = compute_rows_checksum(&curated.rows); - - let write_start = Instant::now(); - let write_stats = write_corporate_actions_dataset( - &args.out_dir, - &curated.rows, - CorporateActionsWriteOptions::default(), - ) - .map_err(|source| RunCurateCorporateActionsError::CurateWrite { - out_dir: args.out_dir.clone(), - source: CurateCorporateActionsWriteError::Parquet(source), - })?; - let write_elapsed_secs = write_start.elapsed().as_secs_f64(); - - let report = CurateCorporateActionsRunReport { - splits_docs_framed: decoded.splits_docs_framed, - splits_bytes_read: decoded.splits_bytes_read, - splits_decode: decoded.splits_decode, - dividends_docs_framed: decoded.dividends_docs_framed, - dividends_bytes_read: decoded.dividends_bytes_read, - dividends_decode: decoded.dividends_decode, - delistings_rows_loaded: decoded.delistings_rows_loaded, - delistings_bytes_read: decoded.delistings_bytes_read, - curate_stats: curated.stats, - write_stats, - elapsed_secs: total_start.elapsed().as_secs_f64(), - }; - - Ok(CurateCorporateActionsTimedRun { - report, - decode_elapsed_secs, - curate_elapsed_secs, - write_elapsed_secs, - checksum, - }) -} - -/// Formats [`CurateCorporateActionsRunReport`] into a deterministic machine-readable `key=value` -/// summary. -/// -/// Only the final `timing:` line contains wall-clock time (`elapsed_secs`). -pub fn format_curate_corporate_actions_report(report: &CurateCorporateActionsRunReport) -> String { - format!( - "curate-etl curate-corporate-actions\n\ - \x20 splits_bson: docs_framed={} bytes_read={} docs_in={} decoded={} noop_ratio_one={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={})\n\ - \x20 dividends_bson: docs_framed={} bytes_read={} docs_in={} decoded={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={})\n\ - \x20 delistings_tsv: rows_loaded={} bytes_read={}\n\ - \x20 builder: splits_in={} splits_out={} split_noops={} dividends_in={} dividends_out={} zero_div={} delistings_in={} otc_out={} delistings_out={} delist_no_outcome={} rows_out={} keys_out={} declared={} ex_fallback={} declared_after_ex={} delist_date={}\n\ - \x20 curate: rows_in={} rows_out={} listings_out={} unmapped={} unmapped_succ={} self_succ={} known_at_oor={} coll_collapsed={} coll_dropped={}\n\ - \x20 write: rows_written={} files_written={} row_groups_written={} bytes_written={}\n\ - \x20 timing: elapsed_secs={:.6}", - report.splits_docs_framed, - report.splits_bytes_read, - report.splits_decode.docs_in, - report.splits_decode.decoded, - report.splits_decode.split_noop_ratio_one, - report.splits_decode.rejected_total(), - report.splits_decode.rejected_missing_field, - report.splits_decode.rejected_empty_field, - report.splits_decode.rejected_wrong_type, - report.splits_decode.rejected_malformed_date, - report.splits_decode.rejected_invalid_number, - report.splits_decode.rejected_corrupt_document, - report.dividends_docs_framed, - report.dividends_bytes_read, - report.dividends_decode.docs_in, - report.dividends_decode.decoded, - report.dividends_decode.rejected_total(), - report.dividends_decode.rejected_missing_field, - report.dividends_decode.rejected_empty_field, - report.dividends_decode.rejected_wrong_type, - report.dividends_decode.rejected_malformed_date, - report.dividends_decode.rejected_invalid_number, - report.dividends_decode.rejected_corrupt_document, - report.delistings_rows_loaded, - report.delistings_bytes_read, - report.curate_stats.builder.splits_in, - report.curate_stats.builder.splits_out, - report.curate_stats.builder.split_noops_dropped, - report.curate_stats.builder.dividends_in, - report.curate_stats.builder.dividends_out, - report.curate_stats.builder.dividend_zero_cash_dropped, - report.curate_stats.builder.delistings_in, - report.curate_stats.builder.otc_delist_transfers_out, - report.curate_stats.builder.delistings_out, - report.curate_stats.builder.delist_without_outcome, - report.curate_stats.builder.rows_out, - report.curate_stats.builder.keys_out, - report.curate_stats.builder.known_at_declared_date, - report.curate_stats.builder.known_at_ex_date_fallback, - report.curate_stats.builder.declared_after_ex_date, - report.curate_stats.builder.known_at_delist_date, - report.curate_stats.rows_in, - report.curate_stats.rows_out, - report.curate_stats.listings_out, - report.curate_stats.dropped_unmapped, - report.curate_stats.dropped_unmapped_successor, - report.curate_stats.dropped_self_successor, - report.curate_stats.dropped_known_at_out_of_range, - report.curate_stats.listing_collision_collapsed, - report.curate_stats.listing_collision_dropped, - report.write_stats.rows_written, - report.write_stats.files_written, - report.write_stats.row_groups_written, - report.write_stats.bytes_written, - report.elapsed_secs, - ) -} - -#[cfg(test)] -#[path = "run_curate_corporate_actions_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/run_curate_corporate_actions_tests.rs b/tools/curate-etl/src/run_curate_corporate_actions_tests.rs deleted file mode 100644 index 359c1023..00000000 --- a/tools/curate-etl/src/run_curate_corporate_actions_tests.rs +++ /dev/null @@ -1,1558 +0,0 @@ -use std::fs::{self, File}; -use std::io::Write; -use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering}; - -use bson::raw::{cstr, RawDocumentBuf}; - -use super::*; -use crate::bson_stream::DEFAULT_MAX_DOC_BYTES; -use crate::corporate_actions::{CorporateActionKind, KnownAtSource}; -use crate::parquet_corporate_actions::tests::read_parquet_rows; -use crate::split::ymd_to_epoch_days; - -static TEST_DIR_SEQ: AtomicU64 = AtomicU64::new(0); - -struct TestTempDir { - path: PathBuf, -} - -impl TestTempDir { - fn new(tag: &str) -> Self { - let pid = std::process::id(); - let seq = TEST_DIR_SEQ.fetch_add(1, Ordering::Relaxed); - let path = - std::env::temp_dir().join(format!("curate-etl-run-corp-actions-{tag}-{pid}-{seq}")); - fs::create_dir_all(&path).expect("create test temp dir"); - Self { path } - } - - fn path(&self) -> &Path { - &self.path - } -} - -impl Drop for TestTempDir { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.path); - } -} - -fn write_bytes(path: &Path, bytes: &[u8]) { - if let Some(parent) = path.parent() { - fs::create_dir_all(parent).expect("create parent dirs"); - } - let mut f = File::create(path).expect("create fixture file"); - f.write_all(bytes).expect("write fixture bytes"); -} - -fn split_doc(code: &str, date: &str, ratio: f64, declared: Option<&str>) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), code); - doc.append(cstr!("date"), date); - if ratio.is_finite() && ratio > 0.0 { - doc.append(cstr!("splitratio"), 1.0 / ratio); - doc.append(cstr!("forfactor"), 1.0_f64); - doc.append(cstr!("tofactor"), ratio); - } else { - doc.append(cstr!("splitratio"), ratio); - } - if let Some(d) = declared { - doc.append(cstr!("declared"), d); - } - doc.into_bytes() -} - -fn div_doc( - code: &str, - date: &str, - cash: f64, - currency: &str, - declared: Option<&str>, - usd_fx_rate: Option, -) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), code); - doc.append(cstr!("date"), date); - doc.append(cstr!("amount"), cash); - doc.append(cstr!("currency"), currency); - if let Some(d) = declared { - doc.append(cstr!("declared"), d); - } - if let Some(fx) = usd_fx_rate { - doc.append(cstr!("usdFxRate"), fx); - } - doc.into_bytes() -} - -fn assert_row_bit_eq(a: &CorporateActionsParquetRow, b: &CorporateActionsParquetRow) { - assert_eq!(a.listing_id, b.listing_id); - assert_eq!(a.ex_date, b.ex_date); - assert_eq!(a.declared_date, b.declared_date); - assert_eq!(a.kind, b.kind); - assert_eq!(a.ratio.map(f64::to_bits), b.ratio.map(f64::to_bits)); - assert_eq!( - a.cash_amount.map(f64::to_bits), - b.cash_amount.map(f64::to_bits) - ); - assert_eq!(a.currency, b.currency); - assert_eq!(a.successor_listing_id, b.successor_listing_id); - assert_eq!( - a.terminal_return.map(f64::to_bits), - b.terminal_return.map(f64::to_bits) - ); - assert_eq!(a.known_at_micros, b.known_at_micros); - assert_eq!(a.known_at_source, b.known_at_source); -} - -fn assert_conservation(report: &CurateCorporateActionsRunReport) { - assert_eq!( - report.splits_docs_framed as usize, report.splits_decode.docs_in, - "splits_docs_framed must equal splits_decode.docs_in" - ); - assert_eq!( - report.splits_decode.docs_in, - report.splits_decode.decoded + report.splits_decode.rejected_total(), - "splits decode conservation failed: {report:?}" - ); - assert_eq!( - report.splits_decode.decoded, report.curate_stats.builder.splits_in, - "splits_decode.decoded must equal builder.splits_in" - ); - assert_eq!( - report.curate_stats.builder.splits_in, - report.curate_stats.builder.splits_out + report.curate_stats.builder.split_noops_dropped, - "splits builder conservation failed: {report:?}" - ); - - assert_eq!( - report.dividends_docs_framed as usize, report.dividends_decode.docs_in, - "dividends_docs_framed must equal dividends_decode.docs_in" - ); - assert_eq!( - report.dividends_decode.docs_in, - report.dividends_decode.decoded + report.dividends_decode.rejected_total(), - "dividends decode conservation failed: {report:?}" - ); - assert_eq!( - report.dividends_decode.decoded, report.curate_stats.builder.dividends_in, - "dividends_decode.decoded must equal builder.dividends_in" - ); - assert_eq!( - report.curate_stats.builder.dividends_in, - report.curate_stats.builder.dividends_out - + report.curate_stats.builder.dividend_zero_cash_dropped, - "dividends builder conservation failed: {report:?}" - ); - - assert_eq!( - report.delistings_rows_loaded, report.curate_stats.builder.delistings_in, - "delistings_rows_loaded must equal builder.delistings_in" - ); - assert_eq!( - report.curate_stats.builder.delist_without_outcome, 0, - "strict delistings TSV must never emit delist_without_outcome" - ); - assert_eq!( - report.curate_stats.builder.delistings_in, - report.curate_stats.builder.otc_delist_transfers_out - + report.curate_stats.builder.delistings_out, - "delistings builder conservation failed: {report:?}" - ); - - assert_eq!( - report.curate_stats.rows_in, report.curate_stats.builder.rows_out, - "curate_stats.rows_in must equal builder.rows_out" - ); - assert_eq!( - report.curate_stats.rows_in, - report.curate_stats.rows_out - + report.curate_stats.dropped_unmapped - + report.curate_stats.dropped_unmapped_successor - + report.curate_stats.dropped_self_successor - + report.curate_stats.dropped_known_at_out_of_range - + report.curate_stats.listing_collision_collapsed - + report.curate_stats.listing_collision_dropped, - "curate stage conservation failed: {report:?}" - ); - assert_eq!( - report.write_stats.rows_written, report.curate_stats.rows_out, - "write_stats.rows_written must equal curate_stats.rows_out" - ); -} - -fn strip_timing_line(report: &str) -> String { - report - .lines() - .filter(|line| !line.trim_start().starts_with("timing:")) - .collect::>() - .join("\n") -} - -fn assert_single_line_err(err: &RunCurateCorporateActionsError) -> String { - let msg = err.to_string(); - assert_eq!( - msg.lines().count(), - 1, - "expected single-line error message, got: {msg:?}" - ); - msg -} - -fn assert_no_corporate_actions_artifacts(out_dir: &Path) { - let ds_dir = out_dir.join("corporate_actions"); - assert!( - !ds_dir.exists(), - "expected no corporate_actions dir under {}", - out_dir.display() - ); -} - -#[test] -fn end_to_end_round_trip_matches_direct_curate_corporate_actions_and_is_deterministic() { - let dir = TestTempDir::new("e2e-roundtrip"); - let splits_a = dir.path().join("splits_a.bson"); - let splits_b = dir.path().join("splits_b.bson"); - let divs_a = dir.path().join("divs_a.bson"); - let divs_b = dir.path().join("divs_b.bson"); - let divs_fx_alt = dir.path().join("divs_fx_alt.bson"); - let map_a = dir.path().join("provider_mapping_a.tsv"); - let map_b = dir.path().join("provider_mapping_b.tsv"); - let delist_a = dir.path().join("delistings_a.tsv"); - let delist_b = dir.path().join("delistings_b.tsv"); - let out_a = dir.path().join("out_a"); - let out_b = dir.path().join("out_b"); - let out_fx_alt = dir.path().join("out_fx_alt"); - let out_timed = dir.path().join("out_timed"); - - // Mapping includes: - // - 100: NVDA:US (forward split + USD dividend) - // - 200: RY:CA + RY_ALT:CA (CAD dividend with bogus usdFxRate + alias collapse) - // - 250: RVS:US (reverse split 1-for-20, missing declared_date + late declared_date split) - // - 300: SIVB:US ended 2023-03-10, reused by listing 999 on 2023-03-20.. -> OTC transfer to 301 (SIVBQ:US) on 2023-03-28 - // - 400: DEL30:US (-0.3 terminal delisting) - // - 500: DEL100:US (-1.0 terminal delisting) - let map_rows_a = [ - "qm\tNVDA:US\t2010-01-01\t\t100\n", - "qm\tRY:CA\t2010-01-01\t\t200\n", - "qm\tRY_ALT:CA\t2010-01-01\t\t200\n", - "qm\tRVS:US\t2010-01-01\t\t250\n", - "qm\tSIVB:US\t2010-01-01\t2023-03-10\t300\n", - "qm\tSIVB:US\t2023-03-20\t\t999\n", - "qm\tSIVBQ:US\t2023-03-28\t\t301\n", - "qm\tDEL30:US\t2015-01-01\t\t400\n", - "qm\tDEL100:US\t2015-01-01\t\t500\n", - ]; - let map_rows_b = [ - map_rows_a[8], - map_rows_a[5], - map_rows_a[2], - map_rows_a[6], - map_rows_a[0], - map_rows_a[4], - map_rows_a[7], - map_rows_a[1], - map_rows_a[3], - ]; - let map_bytes_a = map_rows_a.concat(); - let map_bytes_b = map_rows_b.concat(); - assert_eq!(map_bytes_a.len(), map_bytes_b.len()); - write_bytes(&map_a, map_bytes_a.as_bytes()); - write_bytes(&map_b, map_bytes_b.as_bytes()); - - // Splits: - // - NVDA 10:1 with declared_date < ex_date (DeclaredDate) - // - RVS 1:20 reverse split (0.05) with no declared_date (ExDateFallback) - // - RVS 2:1 split with late declared_date > ex_date (clamped to ex_date, ExDateFallback) - // - NVDA 1:1 no-op (must be excluded) - let s1 = split_doc("NVDA:US", "2024-06-10", 10.0, Some("2024-05-22")); - let s2 = split_doc("RVS:US", "2023-08-15", 0.05, None); - let s3 = split_doc("RVS:US", "2024-01-10", 2.0, Some("2024-01-15")); - let s4_noop = split_doc("NVDA:US", "2022-03-01", 1.0, Some("2022-02-01")); - write_bytes(&splits_a, &[&s1[..], &s2[..], &s3[..], &s4_noop[..]].concat()); - write_bytes(&splits_b, &[&s4_noop[..], &s3[..], &s1[..], &s2[..]].concat()); - - // Dividends: - // - NVDA USD 0.01 with declared_date & bogus usdFxRate: 1.0 - // - RY:CA CAD 1.38 with bogus usdFxRate: 1.0 + identical RY_ALT:CA alias - // - NVDA 0.0 cash dividend (must be excluded) - let d1 = div_doc("NVDA:US", "2024-06-11", 0.01, "USD", Some("2024-05-22"), Some(1.0)); - let d2 = div_doc("RY:CA", "2024-04-25", 1.38, "CAD", Some("2024-03-01"), Some(1.0)); - let d3 = div_doc("RY_ALT:CA", "2024-04-25", 1.38, "CAD", Some("2024-03-01"), Some(1.0)); - let d4_zero = div_doc("NVDA:US", "2023-05-01", 0.0, "USD", None, Some(1.0)); - write_bytes(&divs_a, &[&d1[..], &d2[..], &d3[..], &d4_zero[..]].concat()); - write_bytes(&divs_b, &[&d4_zero[..], &d3[..], &d1[..], &d2[..]].concat()); - - // Alternate dividend file with completely different / absent usdFxRate proving it has no effect. - let d1_alt = div_doc("NVDA:US", "2024-06-11", 0.01, "USD", Some("2024-05-22"), None); - let d2_alt = div_doc("RY:CA", "2024-04-25", 1.38, "CAD", Some("2024-03-01"), Some(0.73)); - let d3_alt = div_doc("RY_ALT:CA", "2024-04-25", 1.38, "CAD", Some("2024-03-01"), Some(999.0)); - write_bytes( - &divs_fx_alt, - &[&d1_alt[..], &d2_alt[..], &d3_alt[..], &d4_zero[..]].concat(), - ); - - // Delistings: - // - SIVB:US -> SIVBQ:US on 2023-03-28 with from_listing_id=300 (across ended range & reuse!) - // - DEL30:US -0.3 on 2023-09-15 (no from_listing_id) - // - DEL100:US -1.0 on 2024-02-01 (with explicit from_listing_id=500) - let delist_rows_a = [ - "SIVB:US\t2023-03-28\t300\tSIVBQ:US\t\n", - "DEL30:US\t2023-09-15\t\t\t-0.3\n", - "DEL100:US\t2024-02-01\t500\t\t-1.0\n", - ]; - let delist_rows_b = [delist_rows_a[2], delist_rows_a[0], delist_rows_a[1]]; - let delist_bytes_a = delist_rows_a.concat(); - let delist_bytes_b = delist_rows_b.concat(); - assert_eq!(delist_bytes_a.len(), delist_bytes_b.len()); - write_bytes(&delist_a, delist_bytes_a.as_bytes()); - write_bytes(&delist_b, delist_bytes_b.as_bytes()); - - let args_a = CurateCorporateActionsArgs { - qm_splits: splits_a.clone(), - qm_dividends: divs_a.clone(), - provider_mapping: map_a.clone(), - delistings: Some(delist_a.clone()), - out_dir: out_a.clone(), - }; - let report_a = run_curate_corporate_actions(&args_a).expect("run A"); - assert_conservation(&report_a); - - let args_b = CurateCorporateActionsArgs { - qm_splits: splits_b, - qm_dividends: divs_b, - provider_mapping: map_b, - delistings: Some(delist_b), - out_dir: out_b.clone(), - }; - let report_b = run_curate_corporate_actions(&args_b).expect("run B"); - assert_conservation(&report_b); - - let args_fx = CurateCorporateActionsArgs { - qm_splits: splits_a.clone(), - qm_dividends: divs_fx_alt, - provider_mapping: map_a.clone(), - delistings: Some(delist_a.clone()), - out_dir: out_fx_alt.clone(), - }; - let report_fx = run_curate_corporate_actions(&args_fx).expect("run fx alt"); - assert_conservation(&report_fx); - - let args_timed = CurateCorporateActionsArgs { - qm_splits: splits_a, - qm_dividends: divs_a, - provider_mapping: map_a.clone(), - delistings: Some(delist_a), - out_dir: out_timed.clone(), - }; - let timed = run_curate_corporate_actions_timed(&args_timed).expect("run timed"); - assert_conservation(&timed.report); - - // Direct in-memory curate_corporate_actions comparison. - let mapping = load_provider_mapping_table(&map_a).unwrap(); - let direct = curate_corporate_actions( - vec![ - ( - "NVDA:US", - SplitActionEvent { - ex_date: ymd_to_epoch_days(2024, 6, 10).unwrap(), - ratio: 10.0, - declared_date: Some(ymd_to_epoch_days(2024, 5, 22).unwrap()), - }, - ), - ( - "RVS:US", - SplitActionEvent { - ex_date: ymd_to_epoch_days(2023, 8, 15).unwrap(), - ratio: 0.05, - declared_date: None, - }, - ), - ( - "RVS:US", - SplitActionEvent { - ex_date: ymd_to_epoch_days(2024, 1, 10).unwrap(), - ratio: 2.0, - declared_date: Some(ymd_to_epoch_days(2024, 1, 15).unwrap()), - }, - ), - ( - "NVDA:US", - SplitActionEvent { - ex_date: ymd_to_epoch_days(2022, 3, 1).unwrap(), - ratio: 1.0, - declared_date: Some(ymd_to_epoch_days(2022, 2, 1).unwrap()), - }, - ), - ], - vec![ - ( - "NVDA:US", - DividendActionEvent { - ex_date: ymd_to_epoch_days(2024, 6, 11).unwrap(), - cash: 0.01, - currency: "USD".to_string(), - declared_date: Some(ymd_to_epoch_days(2024, 5, 22).unwrap()), - }, - ), - ( - "RY:CA", - DividendActionEvent { - ex_date: ymd_to_epoch_days(2024, 4, 25).unwrap(), - cash: 1.38, - currency: "CAD".to_string(), - declared_date: Some(ymd_to_epoch_days(2024, 3, 1).unwrap()), - }, - ), - ( - "RY_ALT:CA", - DividendActionEvent { - ex_date: ymd_to_epoch_days(2024, 4, 25).unwrap(), - cash: 1.38, - currency: "CAD".to_string(), - declared_date: Some(ymd_to_epoch_days(2024, 3, 1).unwrap()), - }, - ), - ( - "NVDA:US", - DividendActionEvent { - ex_date: ymd_to_epoch_days(2023, 5, 1).unwrap(), - cash: 0.0, - currency: "USD".to_string(), - declared_date: None, - }, - ), - ], - vec![ - CurateDelistingInput::with_from_listing_id( - "SIVB:US", - 300, - DelistingOutcomeEvent { - delist_date: ymd_to_epoch_days(2023, 3, 28).unwrap(), - successor_key: Some("SIVBQ:US"), - terminal_return: None, - }, - ), - CurateDelistingInput::new( - "DEL30:US", - DelistingOutcomeEvent { - delist_date: ymd_to_epoch_days(2023, 9, 15).unwrap(), - successor_key: None, - terminal_return: Some(-0.3), - }, - ), - CurateDelistingInput::with_from_listing_id( - "DEL100:US", - 500, - DelistingOutcomeEvent { - delist_date: ymd_to_epoch_days(2024, 2, 1).unwrap(), - successor_key: None, - terminal_return: Some(-1.0), - }, - ), - ], - "qm", - &mapping, - ) - .expect("direct curate"); - - let pq_a_path = out_a.join("corporate_actions/part.parquet"); - let pq_b_path = out_b.join("corporate_actions/part.parquet"); - let pq_fx_path = out_fx_alt.join("corporate_actions/part.parquet"); - let pq_timed_path = out_timed.join("corporate_actions/part.parquet"); - - let read_rows = read_parquet_rows(&pq_a_path); - assert_eq!(read_rows.len(), 8); - assert_eq!(read_rows.len(), direct.rows.len()); - for (actual, expected) in read_rows.iter().zip(direct.rows.iter()) { - assert_row_bit_eq(actual, expected); - } - - // Verify sorted non-decreasing by (listing_id, ex_date, kind). - for pair in read_rows.windows(2) { - let a = (pair[0].listing_id, pair[0].ex_date, pair[0].kind); - let b = (pair[1].listing_id, pair[1].ex_date, pair[1].kind); - assert!(a <= b, "rows not sorted by (listing_id, ex_date, kind): {a:?} > {b:?}"); - } - - // Spot-check key semantic properties. - assert_eq!(read_rows[0].listing_id, 100); - assert_eq!(read_rows[0].kind, CorporateActionKind::Split); - assert_eq!(read_rows[0].ratio, Some(10.0)); - assert_eq!(read_rows[0].known_at_source, KnownAtSource::DeclaredDate); - - assert_eq!(read_rows[1].listing_id, 100); - assert_eq!(read_rows[1].kind, CorporateActionKind::Dividend); - assert_eq!(read_rows[1].cash_amount, Some(0.01)); - assert_eq!(read_rows[1].currency.as_deref(), Some("USD")); - - assert_eq!(read_rows[2].listing_id, 200); - assert_eq!(read_rows[2].kind, CorporateActionKind::Dividend); - assert_eq!(read_rows[2].cash_amount, Some(1.38)); - assert_eq!(read_rows[2].currency.as_deref(), Some("CAD")); - - // Reverse split 0.05 with missing declared -> ExDateFallback. - assert_eq!(read_rows[3].listing_id, 250); - assert_eq!(read_rows[3].kind, CorporateActionKind::Split); - assert_eq!(read_rows[3].ratio, Some(0.05)); - assert_eq!(read_rows[3].declared_date, None); - assert_eq!(read_rows[3].known_at_source, KnownAtSource::ExDateFallback); - - // Late declared split -> declared_date preserved, known_at_source = ExDateFallback. - assert_eq!(read_rows[4].listing_id, 250); - assert_eq!(read_rows[4].kind, CorporateActionKind::Split); - assert_eq!(read_rows[4].ratio, Some(2.0)); - assert_eq!( - read_rows[4].declared_date, - Some(ymd_to_epoch_days(2024, 1, 15).unwrap()) - ); - assert_eq!(read_rows[4].known_at_source, KnownAtSource::ExDateFallback); - - // OTC transfer SIVB (300) -> SIVBQ (301), not reused occupant 999. - assert_eq!(read_rows[5].listing_id, 300); - assert_eq!(read_rows[5].kind, CorporateActionKind::OtcDelistTransfer); - assert_eq!(read_rows[5].successor_listing_id, Some(301)); - assert_eq!(read_rows[5].known_at_source, KnownAtSource::DelistDate); - - // Terminal delistings -0.3 and -1.0. - assert_eq!(read_rows[6].listing_id, 400); - assert_eq!(read_rows[6].kind, CorporateActionKind::Delisting); - assert_eq!(read_rows[6].terminal_return, Some(-0.3)); - - assert_eq!(read_rows[7].listing_id, 500); - assert_eq!(read_rows[7].kind, CorporateActionKind::Delisting); - assert_eq!(read_rows[7].terminal_return, Some(-1.0)); - - // Byte-identical Parquet across shuffled inputs, altered usdFxRate, and timed runner. - let bytes_a = fs::read(&pq_a_path).unwrap(); - let bytes_b = fs::read(&pq_b_path).unwrap(); - let bytes_fx = fs::read(&pq_fx_path).unwrap(); - let bytes_timed = fs::read(&pq_timed_path).unwrap(); - assert_eq!(bytes_a, bytes_b, "shuffled inputs must produce byte-identical Parquet"); - assert_eq!(bytes_a, bytes_fx, "usdFxRate must have zero effect on Parquet output"); - assert_eq!(bytes_a, bytes_timed, "timed runner must produce byte-identical Parquet"); - - // Complete non-timing report must be identical across shuffled inputs (with preserved byte - // lengths) and between run_a and timed. - let formatted_a = strip_timing_line(&format_curate_corporate_actions_report(&report_a)); - let formatted_b = strip_timing_line(&format_curate_corporate_actions_report(&report_b)); - let formatted_timed = strip_timing_line(&format_curate_corporate_actions_report(&timed.report)); - assert_eq!( - formatted_a, formatted_b, - "shuffled inputs must produce identical non-timing report" - ); - assert_eq!( - formatted_a, formatted_timed, - "timed runner must produce identical non-timing report" - ); - assert_ne!(timed.checksum, 0); -} - -#[test] -fn counter_conservation_holds_on_mixed_fixture_with_all_drop_and_collapse_paths() { - let dir = TestTempDir::new("conservation"); - let splits_path = dir.path().join("splits.bson"); - let divs_path = dir.path().join("divs.bson"); - let map_path = dir.path().join("provider_mapping.tsv"); - let delist_path = dir.path().join("delistings.tsv"); - let out_dir = dir.path().join("out"); - - write_bytes( - &map_path, - b"qm\tA:US\t1970-01-01\t\t10\n\ - qm\tA_ALT:US\t1970-01-01\t\t10\n\ - qm\tB:US\t2000-01-01\t\t20\n\ - qm\tB_OTC:US\t2000-01-01\t\t21\n", - ); - - // Splits: - // 1. valid A:US 2:1 (2020-05-01) - // 2. identical alias A_ALT:US 2:1 (2020-05-01) -> listing_collision_collapsed += 1 - // 3. conflicting alias pair A:US 3:1 + A_ALT:US 4:1 (2021-05-01) -> listing_collision_dropped += 2 - // 4. 1:1 no-op A:US -> split_noops_dropped += 1 - // 5. unmapped key UNMAP:US -> dropped_unmapped += 1 - // 6. pre-1976 A:US (1975-06-01) -> dropped_known_at_out_of_range += 1 - // 7. malformed BSON doc (invalid date) -> splits_decode.rejected_malformed_date += 1 - let mut bad_split = RawDocumentBuf::new(); - bad_split.append(cstr!("qmSearchCode"), "A:US"); - bad_split.append(cstr!("date"), "2023-02-29"); - bad_split.append(cstr!("splitratio"), 2.0_f64); - - let splits_bytes = [ - split_doc("A:US", "2020-05-01", 2.0, Some("2020-04-01")).as_slice(), - split_doc("A_ALT:US", "2020-05-01", 2.0, Some("2020-04-01")).as_slice(), - split_doc("A:US", "2021-05-01", 3.0, Some("2021-04-01")).as_slice(), - split_doc("A_ALT:US", "2021-05-01", 4.0, Some("2021-04-01")).as_slice(), - split_doc("A:US", "2022-05-01", 1.0, None).as_slice(), - split_doc("UNMAP:US", "2022-06-01", 2.0, None).as_slice(), - split_doc("A:US", "1975-06-01", 2.0, None).as_slice(), - bad_split.as_bytes(), - ] - .concat(); - write_bytes(&splits_path, &splits_bytes); - - // Dividends: - // 1. valid A:US 0.50 USD + identical alias A_ALT:US 0.50 USD -> listing_collision_collapsed += 1 - // 2. 0.0 cash dividend -> dividend_zero_cash_dropped += 1 - // 3. unmapped key -> dropped_unmapped += 1 - // 4. malformed BSON doc (negative cash) -> dividends_decode.rejected_invalid_number += 1 - let mut bad_div = RawDocumentBuf::new(); - bad_div.append(cstr!("qmSearchCode"), "A:US"); - bad_div.append(cstr!("date"), "2023-06-15"); - bad_div.append(cstr!("amount"), -1.0_f64); - bad_div.append(cstr!("currency"), "USD"); - - let divs_bytes = [ - div_doc("A:US", "2023-03-15", 0.50, "USD", Some("2023-02-15"), Some(1.0)).as_slice(), - div_doc("A_ALT:US", "2023-03-15", 0.50, "USD", Some("2023-02-15"), Some(1.0)).as_slice(), - div_doc("A:US", "2023-04-15", 0.0, "USD", None, Some(1.0)).as_slice(), - div_doc("UNMAP:US", "2023-05-15", 0.25, "USD", None, Some(1.0)).as_slice(), - bad_div.as_bytes(), - ] - .concat(); - write_bytes(&divs_path, &divs_bytes); - - // Delistings: - // 1. valid OTC transfer B:US -> B_OTC:US - // 2. unmapped successor B:US -> NO_SUCC:US -> dropped_unmapped_successor += 1 - // 3. self successor A:US -> A_ALT:US (both listing 10) -> dropped_self_successor += 1 - // 4. valid terminal delisting B:US -1.0 - write_bytes( - &delist_path, - b"B:US\t2023-07-01\t20\tB_OTC:US\t\n\ - B:US\t2023-08-01\t20\tNO_SUCC:US\t\n\ - A:US\t2023-09-01\t10\tA_ALT:US\t\n\ - B:US\t2024-01-15\t\t\t-1.0\n", - ); - - let report = run_curate_corporate_actions(&CurateCorporateActionsArgs { - qm_splits: splits_path, - qm_dividends: divs_path, - provider_mapping: map_path, - delistings: Some(delist_path), - out_dir: out_dir.clone(), - }) - .expect("mixed fixture run"); - - assert_conservation(&report); - assert_eq!(report.splits_decode.rejected_malformed_date, 1); - assert_eq!(report.dividends_decode.rejected_invalid_number, 1); - assert_eq!(report.curate_stats.builder.split_noops_dropped, 1); - assert_eq!(report.curate_stats.builder.dividend_zero_cash_dropped, 1); - assert_eq!(report.curate_stats.dropped_unmapped, 2); - assert_eq!(report.curate_stats.dropped_unmapped_successor, 1); - assert_eq!(report.curate_stats.dropped_self_successor, 1); - assert_eq!(report.curate_stats.dropped_known_at_out_of_range, 1); - assert_eq!(report.curate_stats.listing_collision_collapsed, 2); - assert_eq!(report.curate_stats.listing_collision_dropped, 2); - assert_eq!(report.write_stats.rows_written, 4); -} - -#[test] -fn omitted_delistings_produces_splits_and_dividends_only() { - let dir = TestTempDir::new("no-delistings"); - let splits_path = dir.path().join("splits.bson"); - let divs_path = dir.path().join("divs.bson"); - let map_path = dir.path().join("provider_mapping.tsv"); - let out_dir = dir.path().join("out"); - - write_bytes(&map_path, b"qm\tNVDA:US\t2010-01-01\t\t100\n"); - write_bytes( - &splits_path, - &split_doc("NVDA:US", "2024-06-10", 10.0, Some("2024-05-22")), - ); - write_bytes( - &divs_path, - &div_doc("NVDA:US", "2024-06-11", 0.01, "USD", Some("2024-05-22"), Some(1.0)), - ); - - let report = run_curate_corporate_actions(&CurateCorporateActionsArgs { - qm_splits: splits_path, - qm_dividends: divs_path, - provider_mapping: map_path, - delistings: None, - out_dir: out_dir.clone(), - }) - .expect("run without delistings"); - - assert_conservation(&report); - assert_eq!(report.delistings_rows_loaded, 0); - assert_eq!(report.delistings_bytes_read, 0); - assert_eq!(report.curate_stats.builder.delistings_in, 0); - assert_eq!(report.write_stats.rows_written, 2); - assert_eq!(report.write_stats.files_written, 1); - - let rows = read_parquet_rows(&out_dir.join("corporate_actions/part.parquet")); - assert_eq!(rows.len(), 2); - assert_eq!(rows[0].kind, CorporateActionKind::Split); - assert_eq!(rows[1].kind, CorporateActionKind::Dividend); -} - -#[test] -fn empty_inputs_return_ok_with_zero_rows_and_do_not_touch_out_dir() { - let dir = TestTempDir::new("empty"); - let splits_path = dir.path().join("splits.bson"); - let divs_path = dir.path().join("divs.bson"); - let map_path = dir.path().join("provider_mapping.tsv"); - let delist_path = dir.path().join("delistings.tsv"); - let out_fresh = dir.path().join("out_fresh"); - let out_existing = dir.path().join("out_existing"); - - write_bytes(&splits_path, b""); - write_bytes(&divs_path, b""); - write_bytes(&map_path, b""); - write_bytes(&delist_path, b""); - - // 1. Fresh out_dir, --delistings omitted -> Ok, 0 rows, corporate_actions dir not created. - let report = run_curate_corporate_actions(&CurateCorporateActionsArgs { - qm_splits: splits_path.clone(), - qm_dividends: divs_path.clone(), - provider_mapping: map_path.clone(), - delistings: None, - out_dir: out_fresh.clone(), - }) - .expect("empty run without delistings"); - assert_conservation(&report); - assert_eq!(report.write_stats.rows_written, 0); - assert_eq!(report.write_stats.files_written, 0); - assert_no_corporate_actions_artifacts(&out_fresh); - - // 2. Pre-existing part.parquet + empty delistings.tsv -> pre-existing file stays untouched. - let existing_pq = out_existing.join("corporate_actions/part.parquet"); - write_bytes(&existing_pq, b"preexisting-sentinel"); - let report2 = run_curate_corporate_actions(&CurateCorporateActionsArgs { - qm_splits: splits_path, - qm_dividends: divs_path, - provider_mapping: map_path, - delistings: Some(delist_path), - out_dir: out_existing, - }) - .expect("empty run with empty delistings"); - assert_conservation(&report2); - assert_eq!(report2.write_stats.rows_written, 0); - assert_eq!(report2.write_stats.files_written, 0); - assert_eq!(fs::read(&existing_pq).unwrap(), b"preexisting-sentinel"); -} - -#[test] -fn load_delistings_tsv_accepts_valid_edge_cases() { - let dir = TestTempDir::new("delist-valid"); - let path = dir.path().join("delistings.tsv"); - // Verbatim whitespace-bearing keys, -0.0 normalized to +0.0, CRLF, single trailing blank line. - write_bytes( - &path, - b" A:US\t2023-03-28\t10\t B:US\t\r\n\ - C:US\t2023-04-01\t\t\t-0.0\r\n\ - D:US\t2023-04-02\t42\t\t-1.0\r\n\r\n", - ); - let rows = load_delistings_tsv(&path).expect("valid delistings"); - assert_eq!(rows.len(), 3); - assert_eq!(rows[0].key, " A:US"); - assert_eq!(rows[0].from_listing_id, Some(10)); - assert_eq!(rows[0].event.successor_key.as_deref(), Some(" B:US")); - assert_eq!(rows[0].event.terminal_return, None); - - assert_eq!(rows[1].key, "C:US"); - assert_eq!(rows[1].from_listing_id, None); - assert_eq!(rows[1].event.successor_key, None); - assert_eq!( - rows[1].event.terminal_return.map(f64::to_bits), - Some(0.0_f64.to_bits()) - ); - - assert_eq!(rows[2].key, "D:US"); - assert_eq!(rows[2].from_listing_id, Some(42)); - assert_eq!(rows[2].event.terminal_return, Some(-1.0)); -} - -#[test] -fn delistings_tsv_rejects_every_violation_with_path_and_line_and_leaves_out_untouched() { - let dir = TestTempDir::new("delist-invalid"); - let splits_ok = dir.path().join("splits.bson"); - let divs_ok = dir.path().join("divs.bson"); - let map_ok = dir.path().join("provider_mapping.tsv"); - write_bytes( - &splits_ok, - &split_doc("NVDA:US", "2024-06-10", 10.0, None), - ); - write_bytes(&divs_ok, b""); - write_bytes(&map_ok, b"qm\tNVDA:US\t2010-01-01\t\t100\n"); - - let cases: &[(&str, &[u8], usize)] = &[ - ("col_count_1", b"ONLYONE\n", 1), - ("col_count_2", b"A\t2023-01-01\n", 1), - ("col_count_3", b"A\t2023-01-01\t1\n", 1), - ("col_count_4", b"A\t2023-01-01\t1\tB\n", 1), - ("col_count_6", b"A\t2023-01-01\t1\tB\t\textra\n", 1), - ("empty_source_id", b"\t2023-01-01\t\t\t-0.3\n", 1), - ("blank_source_id", b" \t2023-01-01\t\t\t-0.3\n", 1), - ("bad_date_format", b"A:US\t2023/01/01\t\t\t-0.3\n", 1), - ("bad_date_leap", b"A:US\t2023-02-29\t\t\t-0.3\n", 1), - ("from_lid_zero", b"A:US\t2023-01-01\t0\tB:US\t\n", 1), - ("from_lid_neg", b"A:US\t2023-01-01\t-5\tB:US\t\n", 1), - ("from_lid_ws", b"A:US\t2023-01-01\t 5\tB:US\t\n", 1), - ("from_lid_alpha", b"A:US\t2023-01-01\tabc\tB:US\t\n", 1), - ("from_lid_overflow", b"A:US\t2023-01-01\t999999999999\tB:US\t\n", 1), - ("blank_successor", b"A:US\t2023-01-01\t10\t \t\n", 1), - ("both_set", b"A:US\t2023-01-01\t10\tB:US\t-0.3\n", 1), - ("neither_set", b"A:US\t2023-01-01\t10\t\t\n", 1), - ("succ_without_from_lid", b"A:US\t2023-01-01\t\tB:US\t\n", 1), - ("ret_below_neg1", b"A:US\t2023-01-01\t\t\t-1.01\n", 1), - ("ret_above_zero", b"A:US\t2023-01-01\t\t\t0.01\n", 1), - ("ret_nan", b"A:US\t2023-01-01\t\t\tNaN\n", 1), - ("ret_inf", b"A:US\t2023-01-01\t\t\tinf\n", 1), - ("ret_neg_inf", b"A:US\t2023-01-01\t\t\t-inf\n", 1), - ("ret_leading_ws", b"A:US\t2023-01-01\t\t\t -0.3\n", 1), - ("ret_trailing_ws", b"A:US\t2023-01-01\t\t\t-0.3 \n", 1), - ("ret_non_numeric", b"A:US\t2023-01-01\t\t\tabc\n", 1), - ( - "interior_blank_line", - b"A:US\t2023-01-01\t\t\t-0.3\n\nB:US\t2023-01-02\t\t\t-1.0\n", - 2, - ), - ( - "multi_trailing_blank", - b"A:US\t2023-01-01\t\t\t-0.3\n\n\n", - 3, - ), - ("interior_cr", b"A:US\t2023-01-01\t\r\t\t-0.3\n", 1), - ("invalid_utf8", b"A:US\xff\t2023-01-01\t\t\t-0.3\n", 1), - ]; - - for (name, bytes, expected_line) in cases { - let bad_delist = dir.path().join(format!("bad_{name}.tsv")); - write_bytes(&bad_delist, bytes); - let out_dir = dir.path().join(format!("out_{name}")); - - let err = run_curate_corporate_actions(&CurateCorporateActionsArgs { - qm_splits: splits_ok.clone(), - qm_dividends: divs_ok.clone(), - provider_mapping: map_ok.clone(), - delistings: Some(bad_delist.clone()), - out_dir: out_dir.clone(), - }) - .expect_err(&format!("case {name} must fail")); - - assert!( - matches!(err, RunCurateCorporateActionsError::TsvParse { line, .. } if line == *expected_line), - "case {name}: expected TsvParse at line {expected_line}, got {err:?}" - ); - let msg = assert_single_line_err(&err); - let expected_needle = format!("bad_{name}.tsv:{expected_line}:"); - assert!( - msg.contains(&expected_needle), - "case {name}: expected '{expected_needle}' in '{msg}'" - ); - assert_no_corporate_actions_artifacts(&out_dir); - } -} - -#[test] -fn failure_modes_return_typed_errors_and_preserve_existing_output() { - let dir = TestTempDir::new("failures"); - let splits_ok = dir.path().join("splits.bson"); - let divs_ok = dir.path().join("divs.bson"); - let map_ok = dir.path().join("provider_mapping.tsv"); - write_bytes(&splits_ok, &split_doc("NVDA:US", "2024-06-10", 10.0, None)); - write_bytes( - &divs_ok, - &div_doc("NVDA:US", "2024-06-11", 0.01, "USD", None, Some(1.0)), - ); - write_bytes(&map_ok, b"qm\tNVDA:US\t2010-01-01\t\t100\n"); - - // Pre-existing sentinel part.parquet that must stay byte-identical across all failures. - let out_existing = dir.path().join("out_existing"); - let existing_pq = out_existing.join("corporate_actions/part.parquet"); - write_bytes(&existing_pq, b"keep-me-intact"); - - // 1. Missing input files (splits, dividends, provider_mapping, optional delistings). - for (label, args) in [ - ( - "missing_splits", - CurateCorporateActionsArgs { - qm_splits: dir.path().join("missing_splits.bson"), - qm_dividends: divs_ok.clone(), - provider_mapping: map_ok.clone(), - delistings: None, - out_dir: out_existing.clone(), - }, - ), - ( - "missing_divs", - CurateCorporateActionsArgs { - qm_splits: splits_ok.clone(), - qm_dividends: dir.path().join("missing_divs.bson"), - provider_mapping: map_ok.clone(), - delistings: None, - out_dir: out_existing.clone(), - }, - ), - ( - "missing_map", - CurateCorporateActionsArgs { - qm_splits: splits_ok.clone(), - qm_dividends: divs_ok.clone(), - provider_mapping: dir.path().join("missing_map.tsv"), - delistings: None, - out_dir: out_existing.clone(), - }, - ), - ( - "missing_delist", - CurateCorporateActionsArgs { - qm_splits: splits_ok.clone(), - qm_dividends: divs_ok.clone(), - provider_mapping: map_ok.clone(), - delistings: Some(dir.path().join("missing_delist.tsv")), - out_dir: out_existing.clone(), - }, - ), - ] { - let err = run_curate_corporate_actions(&args).expect_err(label); - assert!( - matches!(err, RunCurateCorporateActionsError::OpenInput { .. }), - "{label}: got {err:?}" - ); - let msg = assert_single_line_err(&err); - assert!(msg.contains(label), "{label}: {msg}"); - assert_eq!(fs::read(&existing_pq).unwrap(), b"keep-me-intact"); - } - - // 2. Truncated BSON after one valid doc -> error carries exact byte offset. - let valid_doc = split_doc("NVDA:US", "2024-06-10", 10.0, None); - let offset = valid_doc.len(); - let mut trunc_bytes = valid_doc.clone(); - trunc_bytes.extend_from_slice(&valid_doc[..valid_doc.len() - 4]); - let trunc_splits = dir.path().join("trunc_splits.bson"); - write_bytes(&trunc_splits, &trunc_bytes); - let err = run_curate_corporate_actions(&CurateCorporateActionsArgs { - qm_splits: trunc_splits, - qm_dividends: divs_ok.clone(), - provider_mapping: map_ok.clone(), - delistings: None, - out_dir: out_existing.clone(), - }) - .expect_err("truncated BSON must fail"); - assert!(matches!( - err, - RunCurateCorporateActionsError::BsonStream { .. } - )); - let msg = assert_single_line_err(&err); - assert!(msg.contains("trunc_splits.bson"), "{msg}"); - assert!( - msg.contains(&offset.to_string()), - "expected byte offset {offset} in '{msg}'" - ); - assert_eq!(fs::read(&existing_pq).unwrap(), b"keep-me-intact"); - - // 3. Corrupt BSON length (< 5) in dividends -> error carries byte offset 0. - let corrupt_divs = dir.path().join("corrupt_divs.bson"); - write_bytes(&corrupt_divs, &3_i32.to_le_bytes()); - let err = run_curate_corporate_actions(&CurateCorporateActionsArgs { - qm_splits: splits_ok.clone(), - qm_dividends: corrupt_divs, - provider_mapping: map_ok.clone(), - delistings: None, - out_dir: out_existing.clone(), - }) - .expect_err("corrupt BSON must fail"); - assert!(matches!( - err, - RunCurateCorporateActionsError::BsonStream { .. } - )); - let msg = assert_single_line_err(&err); - assert!(msg.contains("corrupt_divs.bson"), "{msg}"); - assert!(msg.contains("offset 0"), "{msg}"); - assert_eq!(fs::read(&existing_pq).unwrap(), b"keep-me-intact"); - - // 4. Oversized BSON document (> DEFAULT_MAX_DOC_BYTES). - let huge_divs = dir.path().join("huge_divs.bson"); - let huge_len = (DEFAULT_MAX_DOC_BYTES as i32) + 512; - let mut huge_bytes = Vec::from(huge_len.to_le_bytes()); - huge_bytes.push(0); - write_bytes(&huge_divs, &huge_bytes); - let err = run_curate_corporate_actions(&CurateCorporateActionsArgs { - qm_splits: splits_ok.clone(), - qm_dividends: huge_divs, - provider_mapping: map_ok.clone(), - delistings: None, - out_dir: out_existing.clone(), - }) - .expect_err("oversized BSON must fail"); - assert!(matches!( - err, - RunCurateCorporateActionsError::BsonStream { .. } - )); - let msg = assert_single_line_err(&err); - assert!(msg.contains("huge_divs.bson"), "{msg}"); - assert_eq!(fs::read(&existing_pq).unwrap(), b"keep-me-intact"); - - // 5. Malformed provider_mapping TSV -> path + line number. - let bad_map = dir.path().join("bad_map.tsv"); - write_bytes(&bad_map, b"qm\tNVDA:US\t2010-01-01\t\t100\nbad_row\n"); - let err = run_curate_corporate_actions(&CurateCorporateActionsArgs { - qm_splits: splits_ok.clone(), - qm_dividends: divs_ok.clone(), - provider_mapping: bad_map, - delistings: None, - out_dir: out_existing.clone(), - }) - .expect_err("malformed provider_mapping must fail"); - assert!(matches!( - err, - RunCurateCorporateActionsError::TsvParse { line: 2, .. } - )); - let msg = assert_single_line_err(&err); - assert!(msg.contains("bad_map.tsv:2:"), "{msg}"); - assert_eq!(fs::read(&existing_pq).unwrap(), b"keep-me-intact"); - - // 6. Overlapping provider_mapping ranges. - let overlap_map = dir.path().join("overlap_map.tsv"); - write_bytes( - &overlap_map, - b"qm\tNVDA:US\t2020-01-01\t2022-12-31\t100\n\ - qm\tNVDA:US\t2022-06-01\t2024-12-31\t101\n", - ); - let err = run_curate_corporate_actions(&CurateCorporateActionsArgs { - qm_splits: splits_ok.clone(), - qm_dividends: divs_ok.clone(), - provider_mapping: overlap_map, - delistings: None, - out_dir: out_existing.clone(), - }) - .expect_err("overlapping provider_mapping must fail"); - assert!(matches!( - err, - RunCurateCorporateActionsError::ProviderMapping { .. } - )); - let msg = assert_single_line_err(&err); - assert!(msg.contains("overlap_map.tsv"), "{msg}"); - assert_eq!(fs::read(&existing_pq).unwrap(), b"keep-me-intact"); - - // 7. `--out` is a regular file -> InvalidOutDir. - let out_file = dir.path().join("out_is_file"); - write_bytes(&out_file, b"not-a-dir"); - let err = run_curate_corporate_actions(&CurateCorporateActionsArgs { - qm_splits: splits_ok.clone(), - qm_dividends: divs_ok.clone(), - provider_mapping: map_ok.clone(), - delistings: None, - out_dir: out_file.clone(), - }) - .expect_err("--out file must fail"); - assert!(matches!( - err, - RunCurateCorporateActionsError::InvalidOutDir { .. } - )); - let msg = assert_single_line_err(&err); - assert!(msg.contains("out_is_file"), "{msg}"); - assert_eq!(fs::read(&out_file).unwrap(), b"not-a-dir"); - - // 8. Obstructed `/corporate_actions` (regular file where dataset dir should be). - let out_obstructed = dir.path().join("out_obstructed"); - fs::create_dir_all(&out_obstructed).unwrap(); - let blocker = out_obstructed.join("corporate_actions"); - write_bytes(&blocker, b"blocker"); - let err = run_curate_corporate_actions(&CurateCorporateActionsArgs { - qm_splits: splits_ok, - qm_dividends: divs_ok, - provider_mapping: map_ok, - delistings: None, - out_dir: out_obstructed, - }) - .expect_err("obstructed corporate_actions path must fail"); - assert!(matches!( - err, - RunCurateCorporateActionsError::CurateWrite { .. } - )); - let msg = assert_single_line_err(&err); - assert!(msg.contains("out_obstructed"), "{msg}"); - assert_eq!(fs::read(&blocker).unwrap(), b"blocker"); -} - -#[test] -fn structurally_corrupt_bson_with_intact_length_fails_with_offset_and_preserves_existing_parquet() { - let dir = TestTempDir::new("corrupt-bson-body"); - let splits_ok = dir.path().join("splits_ok.bson"); - let divs_ok = dir.path().join("divs_ok.bson"); - let map_ok = dir.path().join("provider_mapping.tsv"); - let out_dir = dir.path().join("out"); - - let valid_split_1 = split_doc("NVDA:US", "2024-06-10", 10.0, Some("2024-05-22")); - let valid_split_2 = split_doc("NVDA:US", "2021-07-20", 4.0, Some("2021-05-21")); - let valid_div_1 = div_doc("NVDA:US", "2024-06-11", 0.01, "USD", Some("2024-05-22"), Some(1.0)); - let valid_div_2 = div_doc("NVDA:US", "2024-09-12", 0.01, "USD", Some("2024-08-28"), Some(1.0)); - let valid_div_3 = div_doc("NVDA:US", "2024-12-05", 0.01, "USD", Some("2024-11-20"), Some(1.0)); - - write_bytes(&map_ok, b"qm\tNVDA:US\t2010-01-01\t\t100\n"); - write_bytes(&splits_ok, &[&valid_split_1[..], &valid_split_2[..]].concat()); - write_bytes( - &divs_ok, - &[&valid_div_1[..], &valid_div_2[..], &valid_div_3[..]].concat(), - ); - - // Publish an initial valid dataset so we can verify rebuild failures leave it byte-identical. - let initial = run_curate_corporate_actions(&CurateCorporateActionsArgs { - qm_splits: splits_ok.clone(), - qm_dividends: divs_ok.clone(), - provider_mapping: map_ok.clone(), - delistings: None, - out_dir: out_dir.clone(), - }) - .expect("initial publish"); - assert_eq!(initial.write_stats.rows_written, 5); - let pq_path = out_dir.join("corporate_actions/part.parquet"); - let prev_parquet_bytes = fs::read(&pq_path).expect("read initial parquet"); - - // 1. Dividend document with intact 4-byte length prefix but damaged trailing null terminator - // (0x00 -> 0xFF) at absolute byte offset `valid_div_1.len()`, followed by a valid 3rd doc. - let mut damaged_div = valid_div_2.clone(); - *damaged_div.last_mut().unwrap() = 0xFF; - let corrupt_divs_path = dir.path().join("damaged_null_divs.bson"); - write_bytes( - &corrupt_divs_path, - &[&valid_div_1[..], &damaged_div[..], &valid_div_3[..]].concat(), - ); - let expected_div_offset = valid_div_1.len() as u64; - - let err = run_curate_corporate_actions(&CurateCorporateActionsArgs { - qm_splits: splits_ok.clone(), - qm_dividends: corrupt_divs_path, - provider_mapping: map_ok.clone(), - delistings: None, - out_dir: out_dir.clone(), - }) - .expect_err("damaged null terminator in dividends must fail"); - assert!( - matches!( - err, - RunCurateCorporateActionsError::CorruptBson { - label: "qm-dividends", - offset, - .. - } if offset == expected_div_offset - ), - "expected CorruptBson for qm-dividends at offset {expected_div_offset}, got {err:?}" - ); - let msg = assert_single_line_err(&err); - assert!(msg.contains("damaged_null_divs.bson"), "{msg}"); - assert!( - msg.contains(&format!("offset {expected_div_offset}")), - "expected offset {expected_div_offset} in '{msg}'" - ); - assert_eq!( - fs::read(&pq_path).unwrap(), - prev_parquet_bytes, - "pre-existing Parquet must stay byte-identical after corrupt dividend BSON" - ); - - // 2. Split document with intact length prefix and trailing null terminator, but corrupt - // element bytes (invalid UTF-8 inside the `qmSearchCode` string value) at non-zero offset. - let mut damaged_split = valid_split_2.clone(); - let needle = b"NVDA:US"; - let pos = damaged_split - .windows(needle.len()) - .position(|w| w == needle) - .expect("find qmSearchCode bytes"); - damaged_split[pos] = 0xFF; - let corrupt_splits_path = dir.path().join("damaged_elem_splits.bson"); - write_bytes( - &corrupt_splits_path, - &[&valid_split_1[..], &damaged_split[..]].concat(), - ); - let expected_split_offset = valid_split_1.len() as u64; - - let err = run_curate_corporate_actions(&CurateCorporateActionsArgs { - qm_splits: corrupt_splits_path, - qm_dividends: divs_ok, - provider_mapping: map_ok, - delistings: None, - out_dir: out_dir.clone(), - }) - .expect_err("corrupt element bytes in splits must fail"); - assert!( - matches!( - err, - RunCurateCorporateActionsError::CorruptBson { - label: "qm-splits", - offset, - .. - } if offset == expected_split_offset - ), - "expected CorruptBson for qm-splits at offset {expected_split_offset}, got {err:?}" - ); - let msg = assert_single_line_err(&err); - assert!(msg.contains("damaged_elem_splits.bson"), "{msg}"); - assert!( - msg.contains(&format!("offset {expected_split_offset}")), - "expected offset {expected_split_offset} in '{msg}'" - ); - assert_eq!( - fs::read(&pq_path).unwrap(), - prev_parquet_bytes, - "pre-existing Parquet must stay byte-identical after corrupt split BSON" - ); -} - -#[test] -fn rerun_is_idempotent_and_new_inputs_fully_replace_existing_parquet() { - let dir = TestTempDir::new("rerun-replace"); - let splits_a = dir.path().join("splits_a.bson"); - let divs_a = dir.path().join("divs_a.bson"); - let map_path = dir.path().join("provider_mapping.tsv"); - let out_dir = dir.path().join("out"); - - write_bytes( - &map_path, - b"qm\tNVDA:US\t2010-01-01\t\t100\nqm\tAAPL:US\t2010-01-01\t\t200\n", - ); - write_bytes( - &splits_a, - &split_doc("NVDA:US", "2024-06-10", 10.0, Some("2024-05-22")), - ); - write_bytes( - &divs_a, - &div_doc("NVDA:US", "2024-06-11", 0.01, "USD", Some("2024-05-22"), None), - ); - - let args_a = CurateCorporateActionsArgs { - qm_splits: splits_a, - qm_dividends: divs_a, - provider_mapping: map_path.clone(), - delistings: None, - out_dir: out_dir.clone(), - }; - - let first = run_curate_corporate_actions(&args_a).expect("first publish"); - assert_conservation(&first); - assert_eq!(first.write_stats.rows_written, 2); - let pq_path = out_dir.join("corporate_actions/part.parquet"); - let first_bytes = fs::read(&pq_path).expect("read first parquet"); - - // Re-running with identical inputs produces byte-identical output. - let second = run_curate_corporate_actions(&args_a).expect("idempotent rerun"); - assert_conservation(&second); - assert_eq!(second.write_stats.rows_written, 2); - assert_eq!( - fs::read(&pq_path).expect("read second parquet"), - first_bytes, - "idempotent re-run must produce byte-identical Parquet" - ); - - // Re-running with new inputs fully replaces the previous dataset. - let splits_b = dir.path().join("splits_b.bson"); - let divs_b = dir.path().join("divs_b.bson"); - write_bytes( - &splits_b, - &split_doc("AAPL:US", "2020-08-31", 4.0, Some("2020-07-30")), - ); - write_bytes(&divs_b, b""); - - let third = run_curate_corporate_actions(&CurateCorporateActionsArgs { - qm_splits: splits_b, - qm_dividends: divs_b, - provider_mapping: map_path, - delistings: None, - out_dir: out_dir.clone(), - }) - .expect("replacement publish"); - assert_conservation(&third); - assert_eq!(third.write_stats.rows_written, 1); - - let rows = read_parquet_rows(&pq_path); - assert_eq!(rows.len(), 1); - assert_eq!(rows[0].listing_id, 200); - assert_eq!(rows[0].ex_date, ymd_to_epoch_days(2020, 8, 31).unwrap()); - assert_eq!(rows[0].kind, CorporateActionKind::Split); - - let entries: Vec<_> = fs::read_dir(out_dir.join("corporate_actions")) - .expect("read dataset dir") - .map(|e| e.unwrap().file_name()) - .collect(); - assert_eq!(entries.len(), 1, "no leftover temp/lock files: {entries:?}"); -} - -#[test] -fn delistings_only_run_stamps_exact_1600_et_known_at_in_winter_and_summer() { - let dir = TestTempDir::new("delistings-only-dst"); - let splits_path = dir.path().join("splits.bson"); - let divs_path = dir.path().join("divs.bson"); - let map_path = dir.path().join("provider_mapping.tsv"); - let delist_path = dir.path().join("delistings.tsv"); - let out_dir = dir.path().join("out"); - - write_bytes(&splits_path, b""); - write_bytes(&divs_path, b""); - write_bytes( - &map_path, - b"qm\tWINT:US\t2020-01-01\t2024-01-15\t101\nqm\tSUMM:US\t2020-01-01\t2024-07-15\t102\n", - ); - write_bytes( - &delist_path, - b"WINT:US\t2024-01-15\t\t\t-0.3\nSUMM:US\t2024-07-15\t\t\t-1.0\n", - ); - - let report = run_curate_corporate_actions(&CurateCorporateActionsArgs { - qm_splits: splits_path, - qm_dividends: divs_path, - provider_mapping: map_path, - delistings: Some(delist_path), - out_dir: out_dir.clone(), - }) - .expect("delistings-only run"); - assert_conservation(&report); - assert_eq!(report.delistings_rows_loaded, 2); - assert_eq!(report.write_stats.rows_written, 2); - - let rows = read_parquet_rows(&out_dir.join("corporate_actions/part.parquet")); - assert_eq!(rows.len(), 2); - - // 2024-01-15 16:00:00 EST (UTC-5) = 2024-01-15 21:00:00 UTC. - let winter_day = ymd_to_epoch_days(2024, 1, 15).unwrap(); - let expected_winter_micros = i64::from(winter_day) * 86_400_000_000 + 21 * 3_600_000_000; - assert_eq!(rows[0].listing_id, 101); - assert_eq!(rows[0].ex_date, winter_day); - assert_eq!(rows[0].declared_date, None); - assert_eq!(rows[0].kind, CorporateActionKind::Delisting); - assert_eq!(rows[0].terminal_return, Some(-0.3)); - assert_eq!(rows[0].known_at_micros, expected_winter_micros); - assert_eq!(rows[0].known_at_source, KnownAtSource::DelistDate); - - // 2024-07-15 16:00:00 EDT (UTC-4) = 2024-07-15 20:00:00 UTC. - let summer_day = ymd_to_epoch_days(2024, 7, 15).unwrap(); - let expected_summer_micros = i64::from(summer_day) * 86_400_000_000 + 20 * 3_600_000_000; - assert_eq!(rows[1].listing_id, 102); - assert_eq!(rows[1].ex_date, summer_day); - assert_eq!(rows[1].declared_date, None); - assert_eq!(rows[1].kind, CorporateActionKind::Delisting); - assert_eq!(rows[1].terminal_return, Some(-1.0)); - assert_eq!(rows[1].known_at_micros, expected_summer_micros); - assert_eq!(rows[1].known_at_source, KnownAtSource::DelistDate); -} - -#[test] -fn mapping_rows_from_non_qm_sources_are_ignored() { - let dir = TestTempDir::new("non-qm-sources"); - let splits_path = dir.path().join("splits.bson"); - let divs_path = dir.path().join("divs.bson"); - let map_path = dir.path().join("provider_mapping.tsv"); - let out_dir = dir.path().join("out"); - - write_bytes( - &map_path, - b"eod\tAAPL:US\t2000-01-01\t\t100\npolygon\tMSFT:US\t2000-01-01\t\t200\nqm\tNVDA:US\t2000-01-01\t\t300\n", - ); - write_bytes( - &splits_path, - &[ - split_doc("AAPL:US", "2020-08-31", 4.0, None), - split_doc("MSFT:US", "2021-01-15", 2.0, None), - split_doc("NVDA:US", "2024-06-10", 10.0, Some("2024-05-22")), - ] - .concat(), - ); - write_bytes(&divs_path, b""); - - let report = run_curate_corporate_actions(&CurateCorporateActionsArgs { - qm_splits: splits_path, - qm_dividends: divs_path, - provider_mapping: map_path, - delistings: None, - out_dir: out_dir.clone(), - }) - .expect("run with mixed mapping sources"); - assert_conservation(&report); - assert_eq!(report.curate_stats.dropped_unmapped, 2); - assert_eq!(report.write_stats.rows_written, 1); - - let rows = read_parquet_rows(&out_dir.join("corporate_actions/part.parquet")); - assert_eq!(rows.len(), 1); - assert_eq!(rows[0].listing_id, 300); -} - -#[test] -fn non_empty_inputs_curating_to_zero_rows_write_nothing_and_preserve_existing_parquet() { - let dir = TestTempDir::new("non-empty-zero-out"); - let splits_ok = dir.path().join("splits_ok.bson"); - let divs_ok = dir.path().join("divs_ok.bson"); - let splits_unmapped = dir.path().join("splits_unmapped.bson"); - let divs_unmapped = dir.path().join("divs_unmapped.bson"); - let map_path = dir.path().join("provider_mapping.tsv"); - let out_fresh = dir.path().join("out_fresh"); - let out_existing = dir.path().join("out_existing"); - - write_bytes(&map_path, b"qm\tNVDA:US\t2010-01-01\t\t100\n"); - write_bytes( - &splits_ok, - &split_doc("NVDA:US", "2024-06-10", 10.0, Some("2024-05-22")), - ); - write_bytes(&divs_ok, b""); - write_bytes( - &splits_unmapped, - &[ - split_doc("UNMAPPED:US", "2024-06-10", 2.0, None), - split_doc("NVDA:US", "2024-06-11", 1.0, None), - ] - .concat(), - ); - write_bytes( - &divs_unmapped, - &[ - div_doc("UNMAPPED:US", "2024-06-12", 0.25, "USD", None, None), - div_doc("NVDA:US", "2024-06-13", 0.0, "USD", None, None), - ] - .concat(), - ); - - // Fresh output dir: returns Ok with 0 rows written and creates no corporate_actions dir. - let fresh_report = run_curate_corporate_actions(&CurateCorporateActionsArgs { - qm_splits: splits_unmapped.clone(), - qm_dividends: divs_unmapped.clone(), - provider_mapping: map_path.clone(), - delistings: None, - out_dir: out_fresh.clone(), - }) - .expect("zero-output run on fresh out_dir"); - assert_conservation(&fresh_report); - assert_eq!(fresh_report.splits_docs_framed, 2); - assert_eq!(fresh_report.dividends_docs_framed, 2); - assert_eq!(fresh_report.curate_stats.rows_out, 0); - assert_eq!(fresh_report.write_stats.rows_written, 0); - assert_eq!(fresh_report.write_stats.files_written, 0); - assert_no_corporate_actions_artifacts(&out_fresh); - - // Existing output dir: writer's documented zero-row behavior leaves prior part.parquet in place. - let initial = run_curate_corporate_actions(&CurateCorporateActionsArgs { - qm_splits: splits_ok, - qm_dividends: divs_ok, - provider_mapping: map_path.clone(), - delistings: None, - out_dir: out_existing.clone(), - }) - .expect("initial publish"); - assert_eq!(initial.write_stats.rows_written, 1); - let pq_path = out_existing.join("corporate_actions/part.parquet"); - let prev_bytes = fs::read(&pq_path).expect("read initial parquet"); - - let zero_report = run_curate_corporate_actions(&CurateCorporateActionsArgs { - qm_splits: splits_unmapped, - qm_dividends: divs_unmapped, - provider_mapping: map_path, - delistings: None, - out_dir: out_existing, - }) - .expect("zero-output run on existing out_dir"); - assert_conservation(&zero_report); - assert_eq!(zero_report.write_stats.rows_written, 0); - assert_eq!(zero_report.write_stats.files_written, 0); - assert_eq!( - fs::read(&pq_path).expect("read preserved parquet"), - prev_bytes - ); -} - -#[test] -fn delistings_path_pointing_to_directory_fails_cleanly() { - let dir = TestTempDir::new("delistings-is-dir"); - let splits_path = dir.path().join("splits.bson"); - let divs_path = dir.path().join("divs.bson"); - let map_path = dir.path().join("provider_mapping.tsv"); - let delist_dir = dir.path().join("delistings_dir"); - let out_dir = dir.path().join("out"); - - write_bytes(&splits_path, b""); - write_bytes(&divs_path, b""); - write_bytes(&map_path, b"qm\tNVDA:US\t2010-01-01\t\t100\n"); - fs::create_dir_all(&delist_dir).expect("create delistings dir"); - - let err = run_curate_corporate_actions(&CurateCorporateActionsArgs { - qm_splits: splits_path, - qm_dividends: divs_path, - provider_mapping: map_path, - delistings: Some(delist_dir), - out_dir: out_dir.clone(), - }) - .expect_err("directory as --delistings must fail"); - assert!( - matches!( - err, - RunCurateCorporateActionsError::ReadInput { - label: "delistings", - .. - } | RunCurateCorporateActionsError::OpenInput { - label: "delistings", - .. - } - ), - "unexpected error variant: {err:?}" - ); - let msg = assert_single_line_err(&err); - assert!(msg.contains("delistings_dir"), "{msg}"); - assert_no_corporate_actions_artifacts(&out_dir); -} - -#[test] -fn delistings_terminal_return_edge_values_round_trip_accurately() { - let dir = TestTempDir::new("terminal-return-edges"); - let splits_path = dir.path().join("splits.bson"); - let divs_path = dir.path().join("divs.bson"); - let map_path = dir.path().join("provider_mapping.tsv"); - let delist_path = dir.path().join("delistings.tsv"); - let out_dir = dir.path().join("out"); - - write_bytes(&splits_path, b""); - write_bytes(&divs_path, b""); - write_bytes( - &map_path, - concat!( - "qm\tE0:US\t2020-01-01\t2024-01-10\t10\n", - "qm\tE1:US\t2020-01-01\t2024-01-11\t11\n", - "qm\tE2:US\t2020-01-01\t2024-01-12\t12\n", - "qm\tE3:US\t2020-01-01\t2024-01-13\t13\n", - "qm\tE4:US\t2020-01-01\t2024-01-14\t14\n", - ) - .as_bytes(), - ); - write_bytes( - &delist_path, - concat!( - "E0:US\t2024-01-10\t\t\t0.0\n", - "E1:US\t2024-01-11\t\t\t-0.0\n", - "E2:US\t2024-01-12\t\t\t-1e-9\n", - "E3:US\t2024-01-13\t\t\t-0.999999\n", - "E4:US\t2024-01-14\t\t\t-1.0\n", - ) - .as_bytes(), - ); - - let report = run_curate_corporate_actions(&CurateCorporateActionsArgs { - qm_splits: splits_path, - qm_dividends: divs_path, - provider_mapping: map_path, - delistings: Some(delist_path), - out_dir: out_dir.clone(), - }) - .expect("terminal_return edge values run"); - assert_conservation(&report); - assert_eq!(report.write_stats.rows_written, 5); - - let rows = read_parquet_rows(&out_dir.join("corporate_actions/part.parquet")); - assert_eq!(rows.len(), 5); - let expected = [ - (10, 0.0_f64), - (11, 0.0_f64), // -0.0 normalized to +0.0 - (12, -1e-9_f64), - (13, -0.999999_f64), - (14, -1.0_f64), - ]; - for (row, (listing_id, ret)) in rows.iter().zip(expected) { - assert_eq!(row.listing_id, listing_id); - assert_eq!(row.kind, CorporateActionKind::Delisting); - assert_eq!( - row.terminal_return.map(f64::to_bits), - Some(ret.to_bits()), - "listing {listing_id}: expected {ret:?}, got {:?}", - row.terminal_return - ); - } -} diff --git a/tools/curate-etl/src/run_curate_events.rs b/tools/curate-etl/src/run_curate_events.rs deleted file mode 100644 index 0e069c07..00000000 --- a/tools/curate-etl/src/run_curate_events.rs +++ /dev/null @@ -1,970 +0,0 @@ -//! File-to-file `curate-events` command runner (`M1.2ae`). -//! -//! Streams concatenated raw BSON `qmFilings` and `qmEarnings` dump files alongside -//! `provider_mapping.tsv` into atomically published `/events/year=YYYY/part.parquet` -//! partitions via [`curate_events`] and [`write_events_dataset`]. -//! -//! # Contract & Point-in-Time Rules -//! - Verified defaults match in-repo evidence (`symbol` / `timefiled` on `qmFilings`; -//! `qmSearchCode` / `reportDate` / `announceTime` on `qmEarnings`). Unverified fields -//! (`--filings-form-type-field`, plus optional `filing_id`, `url`, `fiscal_period_end`, -//! `actual_eps`, `revenue`) have no defaults and are validated up front before touching disk. -//! - `consensusEps` is structurally excluded from decoding and explicitly rejected by -//! [`QmEarningsFieldNames::validate`] on any earnings field flag. -//! - `provider_mapping.tsv` uses the strict headerless 5-column TSV format from -//! [`crate::run_curate_bars::load_provider_mapping_tsv`]. -//! - All decoded [`QmFiling`] and [`QmEarning`] rows are passed directly to -//! [`curate_events`], which links same-day `8-K` / `News release` filings to -//! earnings, falls back unlinked earnings to `16:05 ET`, resolves `provider_mapping` on each -//! event's exact Eastern local calendar date (never UTC or `known_at` date), and counts -//! unmapped keys in [`CurateEventsStats::dropped_unmapped`]. -//! - **Empty / all-unmapped behavior:** delegated unchanged to [`curate_events`] / -//! [`write_events_dataset`], returning `Ok` with `rows_written == 0` and `files_written == 0` -//! without creating `/events` or modifying any pre-existing partitions. -//! - **Fail-closed safety:** invalid `--out` (including `--out` or `/events` being a regular -//! file, any input path resolving to `--out` or inside `/events`, or a destination -//! `year=YYYY` partition directory symlink resolving a `part.parquet` output onto an input), -//! invalid field names, empty `--mapping-source`, unreadable inputs, malformed/overlapping -//! `provider_mapping.tsv`, and truncated/corrupt BSON framing or element bytes return a typed -//! [`RunCurateEventsError`] before touching `args.out_dir`. -//! -//! # Counter Conservation Invariants -//! Every successful [`CurateEventsRunReport`] satisfies: -//! - `filings_docs_framed as usize == filings_decode.docs_in == filings_decode.rows_out + filings_decode.skipped_total()` -//! - `earnings_docs_framed as usize == earnings_decode.docs_in == earnings_decode.rows_out + earnings_decode.skipped_total()` -//! - `filings_decode.rows_out == curate_stats.builder.filings_in` -//! - `earnings_decode.rows_out == curate_stats.builder.earnings_in` -//! - `curate_stats.rows_in == curate_stats.builder.rows_out == curate_stats.rows_out + curate_stats.dropped_unmapped + curate_stats.listing_duplicate_collapsed` -//! - `write_stats.rows_written == curate_stats.rows_out` - -use std::collections::{BTreeSet, HashSet}; -use std::error::Error; -use std::fmt::{self, Write as _}; -use std::fs::File; -use std::io; -use std::path::{Component, Path, PathBuf}; -use std::sync::Arc; -use std::time::Instant; - -use crate::bson_qm_events::{ - BsonQmEarningsDecodeStats, BsonQmEventsError, BsonQmFilingsDecodeStats, QmEarningsFieldNames, - QmFilingsFieldNames, -}; -use crate::bson_stream::{ - decode_qm_earnings_chunks, decode_qm_filings_chunks, BsonQmEventsStreamError, BsonStreamError, - BsonStreamOptions, RawBsonChunkReader, -}; -use crate::curate_events::{curate_events, CurateEventsStats, CurateEventsWriteError}; -use crate::events::{partition_year_utc, QmEarning, QmFiling}; -use crate::parquet_events::{ - write_events_dataset, EventsParquetRow, EventsWriteOptions, EventsWriteStats, -}; -use crate::provider_mapping::{ProviderMappingError, ProviderMappingTable}; -use crate::run_curate_bars::{load_provider_mapping_tsv, RunCurateBarsError}; - -/// Default `--mapping-source` passed to `provider_mapping` lookups for `qmFilings` / `qmEarnings`. -pub const DEFAULT_EVENTS_MAPPING_SOURCE: &str = "qm"; - -/// Parsed arguments for the `curate-events` CLI command. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct CurateEventsArgs { - pub qm_filings: PathBuf, - pub qm_earnings: PathBuf, - pub provider_mapping: PathBuf, - pub out_dir: PathBuf, - pub filings_key_field: String, - pub filings_timefiled_field: String, - pub filings_form_type_field: String, - pub filings_filing_id_field: Option, - pub filings_url_field: Option, - pub earnings_key_field: String, - pub earnings_report_date_field: String, - pub earnings_announce_time_field: String, - pub earnings_fiscal_period_end_field: Option, - pub earnings_actual_eps_field: Option, - pub earnings_revenue_field: Option, - pub mapping_source: String, -} - -impl CurateEventsArgs { - /// Borrows the configured `qmFilings` BSON field names as [`QmFilingsFieldNames`]. - #[inline] - pub fn filings_field_names(&self) -> QmFilingsFieldNames<'_> { - QmFilingsFieldNames { - key: self.filings_key_field.as_str(), - timefiled: self.filings_timefiled_field.as_str(), - form_type: self.filings_form_type_field.as_str(), - filing_id: self.filings_filing_id_field.as_deref(), - url: self.filings_url_field.as_deref(), - } - } - - /// Borrows the configured `qmEarnings` BSON field names as [`QmEarningsFieldNames`]. - #[inline] - pub fn earnings_field_names(&self) -> QmEarningsFieldNames<'_> { - QmEarningsFieldNames { - key: self.earnings_key_field.as_str(), - report_date: self.earnings_report_date_field.as_str(), - announce_time: self.earnings_announce_time_field.as_str(), - fiscal_period_end: self.earnings_fiscal_period_end_field.as_deref(), - actual_eps: self.earnings_actual_eps_field.as_deref(), - revenue: self.earnings_revenue_field.as_deref(), - } - } -} - -/// Full run report produced by [`run_curate_events`]. -#[derive(Debug, Clone, PartialEq)] -pub struct CurateEventsRunReport { - pub filings_docs_framed: u64, - pub filings_bytes_read: u64, - pub filings_peak_chunk_bytes: usize, - pub filings_decode: BsonQmFilingsDecodeStats, - pub earnings_docs_framed: u64, - pub earnings_bytes_read: u64, - pub earnings_peak_chunk_bytes: usize, - pub earnings_decode: BsonQmEarningsDecodeStats, - pub curate_stats: CurateEventsStats, - pub write_stats: EventsWriteStats, - pub elapsed_secs: f64, -} - -/// Stage-timed run output used internally by `bench-curate-events-cmd`. -#[derive(Debug, Clone, PartialEq)] -pub(crate) struct CurateEventsTimedRun { - pub report: CurateEventsRunReport, - pub decode_elapsed_secs: f64, - pub curate_elapsed_secs: f64, - pub write_elapsed_secs: f64, - pub checksum: u64, -} - -/// Typed errors returned by [`run_curate_events`]. -/// -/// Every variant's `Display` output is a single line naming the offending path (and line number or -/// byte offset where applicable). -#[derive(Debug)] -pub enum RunCurateEventsError { - InvalidOutDir { - path: PathBuf, - detail: String, - }, - InvalidFieldNames { - source: BsonQmEventsError, - }, - EmptyMappingSource, - OpenInput { - label: &'static str, - path: PathBuf, - source: io::Error, - }, - ReadInput { - label: &'static str, - path: PathBuf, - source: io::Error, - }, - TsvParse { - path: PathBuf, - line: usize, - detail: String, - }, - ProviderMapping { - path: PathBuf, - source: ProviderMappingError, - }, - BsonStream { - label: &'static str, - path: PathBuf, - source: BsonStreamError, - }, - CorruptBson { - label: &'static str, - path: PathBuf, - offset: u64, - source: BsonQmEventsError, - }, - CurateWrite { - out_dir: PathBuf, - source: CurateEventsWriteError, - }, -} - -impl fmt::Display for RunCurateEventsError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::InvalidOutDir { path, detail } => { - write!(f, "invalid --out '{}': {detail}", path.display()) - } - Self::InvalidFieldNames { source } => write!(f, "{source}"), - Self::EmptyMappingSource => { - write!(f, "invalid --mapping-source: must not be empty or blank") - } - Self::OpenInput { - label, - path, - source, - } => write!(f, "failed to open {label} '{}': {source}", path.display()), - Self::ReadInput { - label, - path, - source, - } => write!(f, "failed to read {label} '{}': {source}", path.display()), - Self::TsvParse { path, line, detail } => { - write!(f, "{}:{line}: {detail}", path.display()) - } - Self::ProviderMapping { path, source } => { - write!(f, "invalid provider_mapping '{}': {source}", path.display()) - } - Self::BsonStream { - label, - path, - source, - } => write!(f, "failed reading {label} '{}': {source}", path.display()), - Self::CorruptBson { - label, - path, - offset, - source, - } => write!( - f, - "corrupt {label} BSON '{}' at byte offset {offset}: {source}", - path.display() - ), - Self::CurateWrite { out_dir, source } => { - write!(f, "curate/write to '{}' failed: {source}", out_dir.display()) - } - } - } -} - -impl Error for RunCurateEventsError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::InvalidFieldNames { source } => Some(source), - Self::OpenInput { source, .. } | Self::ReadInput { source, .. } => Some(source), - Self::ProviderMapping { source, .. } => Some(source), - Self::BsonStream { source, .. } => Some(source), - Self::CorruptBson { source, .. } => Some(source), - Self::CurateWrite { source, .. } => Some(source), - Self::InvalidOutDir { .. } | Self::EmptyMappingSource | Self::TsvParse { .. } => None, - } - } -} - -/// Resolves `path` to an absolute normalized path while preserving OS symlink-before-`..` -/// semantics: if `path` exists it is canonicalized directly; otherwise components are walked -/// left-to-right, canonicalizing each existing prefix before resolving `..`, and only lexically -/// normalizing `..` within any non-existent suffix. -fn resolve_normalized_path(path: &Path) -> PathBuf { - if let Ok(canon) = path.canonicalize() { - return canon; - } - - let abs = if path.is_absolute() { - path.to_path_buf() - } else if let Ok(cwd) = std::env::current_dir() { - cwd.join(path) - } else { - path.to_path_buf() - }; - - if let Ok(canon) = abs.canonicalize() { - return canon; - } - - let mut resolved = PathBuf::new(); - for comp in abs.components() { - match comp { - Component::Prefix(prefix) => resolved.push(prefix.as_os_str()), - Component::RootDir => resolved.push(Component::RootDir.as_os_str()), - Component::CurDir => {} - Component::Normal(seg) => { - resolved.push(seg); - if let Ok(canon) = resolved.canonicalize() { - resolved = canon; - } - } - Component::ParentDir => { - resolved.push(Component::ParentDir.as_os_str()); - if let Ok(canon) = resolved.canonicalize() { - resolved = canon; - } else { - // Remove the `..` we just pushed, then lexically pop a non-existent normal segment. - resolved.pop(); - if matches!(resolved.components().next_back(), Some(Component::Normal(_))) { - resolved.pop(); - } - } - } - } - } - - resolved -} - -fn validate_out_dir_and_inputs(args: &CurateEventsArgs) -> Result<(), RunCurateEventsError> { - if args.out_dir.exists() && !args.out_dir.is_dir() { - return Err(RunCurateEventsError::InvalidOutDir { - path: args.out_dir.clone(), - detail: "path exists and is not a directory".to_string(), - }); - } - - let events_dir = args.out_dir.join("events"); - if events_dir.exists() && !events_dir.is_dir() { - return Err(RunCurateEventsError::InvalidOutDir { - path: events_dir, - detail: "events output path exists and is not a directory".to_string(), - }); - } - - let resolved_out = resolve_normalized_path(&args.out_dir); - let resolved_events = resolve_normalized_path(&events_dir); - - for (label, input_path) in [ - ("qm-filings", &args.qm_filings), - ("qm-earnings", &args.qm_earnings), - ("provider-mapping", &args.provider_mapping), - ] { - let resolved_in = resolve_normalized_path(input_path); - if resolved_in == resolved_out - || resolved_in == resolved_events - || resolved_in.starts_with(&resolved_events) - { - return Err(RunCurateEventsError::InvalidOutDir { - path: args.out_dir.clone(), - detail: format!( - "output directory would overlap {label} input '{}'", - input_path.display() - ), - }); - } - } - - Ok(()) -} - -/// Checks each destination `year=YYYY` partition directory and its `part.parquet` path against -/// all resolved input paths before publishing. -/// -/// This catches symlinked year directories (e.g. `/events/year=2025 -> /external/dir`) -/// whose resolved target lies outside `/events` and would otherwise let `write_events_dataset` -/// overwrite an input located at `/external/dir/part.parquet`. -fn validate_partition_outputs_and_inputs( - args: &CurateEventsArgs, - rows: &[EventsParquetRow], -) -> Result<(), RunCurateEventsError> { - if rows.is_empty() { - return Ok(()); - } - - let mut years = BTreeSet::new(); - for row in rows { - years.insert(partition_year_utc(row.ts_micros)); - } - - let resolved_inputs = [ - ("qm-filings", &args.qm_filings, resolve_normalized_path(&args.qm_filings)), - ("qm-earnings", &args.qm_earnings, resolve_normalized_path(&args.qm_earnings)), - ( - "provider-mapping", - &args.provider_mapping, - resolve_normalized_path(&args.provider_mapping), - ), - ]; - - let events_dir = args.out_dir.join("events"); - for year in years { - let year_dir = events_dir.join(format!("year={year:04}")); - let resolved_year_dir = resolve_normalized_path(&year_dir); - let resolved_part_via_dir = resolved_year_dir.join("part.parquet"); - let resolved_part = resolve_normalized_path(&year_dir.join("part.parquet")); - - for (label, input_path, resolved_in) in &resolved_inputs { - if *resolved_in == resolved_year_dir - || *resolved_in == resolved_part_via_dir - || *resolved_in == resolved_part - { - return Err(RunCurateEventsError::InvalidOutDir { - path: year_dir, - detail: format!( - "partition output '{}' would overlap {label} input '{}'", - resolved_part_via_dir.display(), - input_path.display() - ), - }); - } - } - } - - Ok(()) -} - -fn map_tsv_error(path: &Path, err: RunCurateBarsError) -> RunCurateEventsError { - match err { - RunCurateBarsError::OpenInput { - label, - path, - source, - } => RunCurateEventsError::OpenInput { - label, - path, - source, - }, - RunCurateBarsError::ReadInput { - label, - path, - source, - } => RunCurateEventsError::ReadInput { - label, - path, - source, - }, - RunCurateBarsError::TsvParse { path, line, detail } => { - RunCurateEventsError::TsvParse { path, line, detail } - } - RunCurateBarsError::ProviderMapping { path, source } => { - RunCurateEventsError::ProviderMapping { path, source } - } - other => RunCurateEventsError::TsvParse { - path: path.to_path_buf(), - line: 0, - detail: other.to_string(), - }, - } -} - -fn bson_error_offset(err: &BsonQmEventsError) -> u64 { - match err { - BsonQmEventsError::TruncatedDocument { offset, .. } - | BsonQmEventsError::CorruptDocumentLength { offset, .. } - | BsonQmEventsError::CorruptBson { offset, .. } => *offset, - BsonQmEventsError::InvalidFieldNames { .. } => 0, - } -} - -fn map_stream_error( - label: &'static str, - path: &Path, - err: BsonQmEventsStreamError, -) -> RunCurateEventsError { - match err { - BsonQmEventsStreamError::Stream(source) => RunCurateEventsError::BsonStream { - label, - path: path.to_path_buf(), - source, - }, - BsonQmEventsStreamError::Decode(source) => match &source { - BsonQmEventsError::InvalidFieldNames { .. } => { - RunCurateEventsError::InvalidFieldNames { source } - } - _ => { - let offset = bson_error_offset(&source); - RunCurateEventsError::CorruptBson { - label, - path: path.to_path_buf(), - offset, - source, - } - } - }, - } -} - -#[inline] -fn is_canadian_qm_exchange(exchange: &str) -> bool { - matches!( - exchange.trim().to_ascii_uppercase().as_str(), - "TSX" - | "TSXC" - | "CDX" - | "TSXVC" - | "CNQ" - | "CNX" - | "CSE" - | "CVE" - | "AQL" - | "AQLL" - | "NEO" - | "NEOE" - | "MOE" - ) -} - -#[inline] -fn intern_key(interner: &mut HashSet>, key: &str) -> Arc { - if let Some(existing) = interner.get(key) { - Arc::clone(existing) - } else { - let arc: Arc = Arc::from(key); - interner.insert(Arc::clone(&arc)); - arc - } -} - -struct DecodedEventsInputs { - mapping: ProviderMappingTable, - filings: Vec>>, - earnings: Vec>>, - filings_docs_framed: u64, - filings_bytes_read: u64, - filings_peak_chunk_bytes: usize, - filings_decode: BsonQmFilingsDecodeStats, - earnings_docs_framed: u64, - earnings_bytes_read: u64, - earnings_peak_chunk_bytes: usize, - earnings_decode: BsonQmEarningsDecodeStats, -} - -fn decode_all_inputs(args: &CurateEventsArgs) -> Result { - decode_inputs_from_openers( - &args.provider_mapping, - &args.mapping_source, - &args.filings_field_names(), - &args.earnings_field_names(), - &args.qm_filings, - || { - File::open(&args.qm_filings).map_err(|source| RunCurateEventsError::OpenInput { - label: "qm-filings", - path: args.qm_filings.clone(), - source, - }) - }, - &args.qm_earnings, - || { - File::open(&args.qm_earnings).map_err(|source| RunCurateEventsError::OpenInput { - label: "qm-earnings", - path: args.qm_earnings.clone(), - source, - }) - }, - ) -} - -#[allow(clippy::too_many_arguments)] -fn decode_inputs_from_openers( - provider_mapping_path: &Path, - mapping_source: &str, - filings_fields: &QmFilingsFieldNames<'_>, - earnings_fields: &QmEarningsFieldNames<'_>, - qm_filings_path: &Path, - open_filings: FF, - qm_earnings_path: &Path, - open_earnings: FE, -) -> Result -where - RF: io::Read, - FF: FnOnce() -> Result, - RE: io::Read, - FE: FnOnce() -> Result, -{ - filings_fields - .validate() - .map_err(|source| RunCurateEventsError::InvalidFieldNames { source })?; - - earnings_fields - .validate() - .map_err(|source| RunCurateEventsError::InvalidFieldNames { source })?; - - if mapping_source.trim().is_empty() { - return Err(RunCurateEventsError::EmptyMappingSource); - } - - let mapping_rows = load_provider_mapping_tsv(provider_mapping_path) - .map_err(|err| map_tsv_error(provider_mapping_path, err))?; - let mapping = ProviderMappingTable::from_rows(mapping_rows).map_err(|source| { - RunCurateEventsError::ProviderMapping { - path: provider_mapping_path.to_path_buf(), - source, - } - })?; - - let mut key_interner: HashSet> = HashSet::new(); - - // Stream and decode qmFilings. - let filings_stream = open_filings()?; - let mut filings_reader = - RawBsonChunkReader::with_options(filings_stream, BsonStreamOptions::default()).map_err( - |source| RunCurateEventsError::BsonStream { - label: "qm-filings", - path: qm_filings_path.to_path_buf(), - source, - }, - )?; - - let mut filings: Vec>> = Vec::new(); - let mut ca_key_buf = String::with_capacity(32); - let filings_decode = - decode_qm_filings_chunks(&mut filings_reader, filings_fields, |raw| { - let resolved_key_str = if !raw.key.contains(':') - && raw.exchange.is_some_and(is_canadian_qm_exchange) - { - ca_key_buf.clear(); - ca_key_buf.push_str(raw.key); - ca_key_buf.push_str(":CA"); - if !mapping - .cursor_for(mapping_source, ca_key_buf.as_str()) - .ranges() - .is_empty() - { - ca_key_buf.as_str() - } else { - raw.key - } - } else { - raw.key - }; - let key = intern_key(&mut key_interner, resolved_key_str); - filings.push(raw.to_qm_filing(key)); - }) - .map_err(|err| map_stream_error("qm-filings", qm_filings_path, err))?; - - // Stream and decode qmEarnings (reusing the same key interner). - let earnings_stream = open_earnings()?; - let mut earnings_reader = - RawBsonChunkReader::with_options(earnings_stream, BsonStreamOptions::default()).map_err( - |source| RunCurateEventsError::BsonStream { - label: "qm-earnings", - path: qm_earnings_path.to_path_buf(), - source, - }, - )?; - - let mut earnings: Vec>> = Vec::new(); - let earnings_decode = - decode_qm_earnings_chunks(&mut earnings_reader, earnings_fields, |raw| { - let key = intern_key(&mut key_interner, raw.key); - earnings.push(raw.to_qm_earning(key)); - }) - .map_err(|err| map_stream_error("qm-earnings", qm_earnings_path, err))?; - - Ok(DecodedEventsInputs { - mapping, - filings, - earnings, - filings_docs_framed: filings_reader.docs_framed(), - filings_bytes_read: filings_reader.bytes_read(), - filings_peak_chunk_bytes: filings_reader.buffer_capacity(), - filings_decode, - earnings_docs_framed: earnings_reader.docs_framed(), - earnings_bytes_read: earnings_reader.bytes_read(), - earnings_peak_chunk_bytes: earnings_reader.buffer_capacity(), - earnings_decode, - }) -} - -/// Runs the end-to-end `curate-events` file-to-Parquet pipeline via [`curate_events`] and -/// [`write_events_dataset`]. -/// -/// Any validation, I/O, TSV, mapping, BSON framing/corruption, or curation error returns before -/// touching `args.out_dir`, leaving any pre-existing `/events/` partitions -/// byte-identical. -pub fn run_curate_events( - args: &CurateEventsArgs, -) -> Result { - let start = Instant::now(); - validate_out_dir_and_inputs(args)?; - - let decoded = decode_all_inputs(args)?; - - let curated = curate_events( - decoded.filings, - decoded.earnings, - &args.mapping_source, - &decoded.mapping, - ) - .map_err(|source| RunCurateEventsError::CurateWrite { - out_dir: args.out_dir.clone(), - source: CurateEventsWriteError::Curate(source), - })?; - - validate_partition_outputs_and_inputs(args, &curated.rows)?; - - let write_stats = - write_events_dataset(&args.out_dir, &curated.rows, EventsWriteOptions::default()).map_err( - |source| RunCurateEventsError::CurateWrite { - out_dir: args.out_dir.clone(), - source: CurateEventsWriteError::Parquet(source), - }, - )?; - - Ok(CurateEventsRunReport { - filings_docs_framed: decoded.filings_docs_framed, - filings_bytes_read: decoded.filings_bytes_read, - filings_peak_chunk_bytes: decoded.filings_peak_chunk_bytes, - filings_decode: decoded.filings_decode, - earnings_docs_framed: decoded.earnings_docs_framed, - earnings_bytes_read: decoded.earnings_bytes_read, - earnings_peak_chunk_bytes: decoded.earnings_peak_chunk_bytes, - earnings_decode: decoded.earnings_decode, - curate_stats: curated.stats, - write_stats, - elapsed_secs: start.elapsed().as_secs_f64(), - }) -} - -/// Runs `curate-events` from arbitrary raw-BSON [`io::Read`] streams. -#[allow(clippy::too_many_arguments)] -pub fn run_curate_events_with_readers( - provider_mapping_path: &Path, - mapping_source: &str, - filings_fields: &QmFilingsFieldNames<'_>, - earnings_fields: &QmEarningsFieldNames<'_>, - qm_filings_input: (&Path, RF), - qm_earnings_input: (&Path, RE), - out_dir: &Path, -) -> Result { - let start = Instant::now(); - if out_dir.exists() && !out_dir.is_dir() { - return Err(RunCurateEventsError::InvalidOutDir { - path: out_dir.to_path_buf(), - detail: "path exists and is not a directory".to_string(), - }); - } - let events_dir = out_dir.join("events"); - if events_dir.exists() && !events_dir.is_dir() { - return Err(RunCurateEventsError::InvalidOutDir { - path: events_dir, - detail: "events output path exists and is not a directory".to_string(), - }); - } - - let (filings_path, filings_stream) = qm_filings_input; - let (earnings_path, earnings_stream) = qm_earnings_input; - let decoded = decode_inputs_from_openers( - provider_mapping_path, - mapping_source, - filings_fields, - earnings_fields, - filings_path, - || Ok(filings_stream), - earnings_path, - || Ok(earnings_stream), - )?; - - let curated = curate_events( - decoded.filings, - decoded.earnings, - mapping_source, - &decoded.mapping, - ) - .map_err(|source| RunCurateEventsError::CurateWrite { - out_dir: out_dir.to_path_buf(), - source: CurateEventsWriteError::Curate(source), - })?; - - let write_stats = - write_events_dataset(out_dir, &curated.rows, EventsWriteOptions::default()).map_err( - |source| RunCurateEventsError::CurateWrite { - out_dir: out_dir.to_path_buf(), - source: CurateEventsWriteError::Parquet(source), - }, - )?; - - Ok(CurateEventsRunReport { - filings_docs_framed: decoded.filings_docs_framed, - filings_bytes_read: decoded.filings_bytes_read, - filings_peak_chunk_bytes: decoded.filings_peak_chunk_bytes, - filings_decode: decoded.filings_decode, - earnings_docs_framed: decoded.earnings_docs_framed, - earnings_bytes_read: decoded.earnings_bytes_read, - earnings_peak_chunk_bytes: decoded.earnings_peak_chunk_bytes, - earnings_decode: decoded.earnings_decode, - curate_stats: curated.stats, - write_stats, - elapsed_secs: start.elapsed().as_secs_f64(), - }) -} - -fn compute_rows_checksum(rows: &[EventsParquetRow]) -> u64 { - let mut hash = 0xcbf2_9ce4_8422_2325_u64; - let mix = |mut h: u64, v: u64| -> u64 { - h ^= v; - h = h.wrapping_mul(0x0000_0100_0000_01b3); - h - }; - let mix_str = |mut h: u64, s: &str| -> u64 { - h = mix(h, s.len() as u64); - for &b in s.as_bytes() { - h = mix(h, u64::from(b)); - } - h - }; - for row in rows { - hash = mix(hash, row.listing_id as u64); - hash = mix(hash, row.ts_micros as u64); - hash = mix(hash, row.known_at_micros as u64); - hash = mix_str(hash, row.known_at_source.as_ref()); - hash = mix_str(hash, row.kind.as_ref()); - hash = mix_str(hash, &row.subtype); - hash = mix_str(hash, &row.payload_json); - } - hash -} - -/// Stage-timed variant of [`run_curate_events`] used internally by `bench-curate-events-cmd`. -/// -/// Separately times `decode` (TSV load + both BSON streams), `curate` (`curate_events`), and -/// `write` (`write_events_dataset`), and computes a deterministic FNV-1a checksum over all 7 -/// columns of the curated rows. -pub(crate) fn run_curate_events_timed( - args: &CurateEventsArgs, -) -> Result { - let total_start = Instant::now(); - validate_out_dir_and_inputs(args)?; - - let decode_start = Instant::now(); - let decoded = decode_all_inputs(args)?; - let decode_elapsed_secs = decode_start.elapsed().as_secs_f64(); - - let curate_start = Instant::now(); - let curated = curate_events( - decoded.filings, - decoded.earnings, - &args.mapping_source, - &decoded.mapping, - ) - .map_err(|source| RunCurateEventsError::CurateWrite { - out_dir: args.out_dir.clone(), - source: CurateEventsWriteError::Curate(source), - })?; - let curate_elapsed_secs = curate_start.elapsed().as_secs_f64(); - - validate_partition_outputs_and_inputs(args, &curated.rows)?; - - let checksum = compute_rows_checksum(&curated.rows); - - let write_start = Instant::now(); - let write_stats = - write_events_dataset(&args.out_dir, &curated.rows, EventsWriteOptions::default()).map_err( - |source| RunCurateEventsError::CurateWrite { - out_dir: args.out_dir.clone(), - source: CurateEventsWriteError::Parquet(source), - }, - )?; - let write_elapsed_secs = write_start.elapsed().as_secs_f64(); - - let report = CurateEventsRunReport { - filings_docs_framed: decoded.filings_docs_framed, - filings_bytes_read: decoded.filings_bytes_read, - filings_peak_chunk_bytes: decoded.filings_peak_chunk_bytes, - filings_decode: decoded.filings_decode, - earnings_docs_framed: decoded.earnings_docs_framed, - earnings_bytes_read: decoded.earnings_bytes_read, - earnings_peak_chunk_bytes: decoded.earnings_peak_chunk_bytes, - earnings_decode: decoded.earnings_decode, - curate_stats: curated.stats, - write_stats, - elapsed_secs: total_start.elapsed().as_secs_f64(), - }; - - Ok(CurateEventsTimedRun { - report, - decode_elapsed_secs, - curate_elapsed_secs, - write_elapsed_secs, - checksum, - }) -} - -/// Formats [`CurateEventsRunReport`] into a deterministic machine-readable `key=value` summary. -/// -/// Only the final `timing:` line contains wall-clock time (`elapsed_secs`). -pub fn format_curate_events_report(report: &CurateEventsRunReport) -> String { - let fd = &report.filings_decode; - let ed = &report.earnings_decode; - let b = &report.curate_stats.builder; - let c = &report.curate_stats; - let w = &report.write_stats; - - let mut years = String::new(); - for (idx, (year, count)) in w.rows_by_year.iter().enumerate() { - if idx > 0 { - years.push(' '); - } - let _ = write!(years, "{year:04}={count}"); - } - if years.is_empty() { - years.push_str("none"); - } - - format!( - "curate-etl curate-events\n\ - \x20 filings_bson: docs_framed={} bytes_read={} peak_chunk_bytes={} docs_in={} rows_out={} skipped={} (missing_key={} wrong_key_type={} empty_key={} missing_timefiled={} wrong_timefiled_type={} empty_timefiled={} missing_form_type={} wrong_form_type_type={} empty_form_type={}) nulled_wrong_type=(filing_id={} url={})\n\ - \x20 earnings_bson: docs_framed={} bytes_read={} peak_chunk_bytes={} docs_in={} rows_out={} skipped={} (missing_key={} wrong_key_type={} empty_key={} missing_date={} wrong_date_type={} invalid_date={} date_oor={} missing_announce={} wrong_announce_type={} empty_announce={}) nulled=(wrong_fiscal_end={} invalid_fiscal_end={} wrong_eps={} wrong_revenue={})\n\ - \x20 builder: filings_in={} filings_out={} malformed_ts={} unknown_zone={} invalid_dt={} filing_dup={} earnings_in={} earnings_out={} linked={} lagged_1605={} earnings_oor={} earnings_dup={} earnings_conflict={} rows_out={} keys_out={}\n\ - \x20 curate: rows_in={} rows_out={} filings_out={} earnings_out={} listings_out={} dropped_unmapped={} listing_dup_collapsed={}\n\ - \x20 write: files={} row_groups={} rows_written={} bytes_written={}\n\ - \x20 years: {}\n\ - \x20 timing: elapsed_secs={:.6}", - report.filings_docs_framed, - report.filings_bytes_read, - report.filings_peak_chunk_bytes, - fd.docs_in, - fd.rows_out, - fd.skipped_total(), - fd.skipped_missing_key, - fd.skipped_wrong_key_type, - fd.skipped_empty_key, - fd.skipped_missing_timefiled, - fd.skipped_wrong_timefiled_type, - fd.skipped_empty_timefiled, - fd.skipped_missing_form_type, - fd.skipped_wrong_form_type_type, - fd.skipped_empty_form_type, - fd.nulled_wrong_type_filing_id, - fd.nulled_wrong_type_url, - report.earnings_docs_framed, - report.earnings_bytes_read, - report.earnings_peak_chunk_bytes, - ed.docs_in, - ed.rows_out, - ed.skipped_total(), - ed.skipped_missing_key, - ed.skipped_wrong_key_type, - ed.skipped_empty_key, - ed.skipped_missing_report_date, - ed.skipped_wrong_report_date_type, - ed.skipped_invalid_report_date, - ed.skipped_report_date_out_of_range, - ed.skipped_missing_announce_time, - ed.skipped_wrong_announce_time_type, - ed.skipped_empty_announce_time, - ed.nulled_wrong_type_fiscal_period_end, - ed.nulled_invalid_fiscal_period_end, - ed.nulled_wrong_type_actual_eps, - ed.nulled_wrong_type_revenue, - b.filings_in, - b.filings_out, - b.filings_skipped_malformed_timestamp, - b.filings_skipped_unknown_zone, - b.filings_skipped_invalid_date_time, - b.filings_duplicate_collapsed, - b.earnings_in, - b.earnings_out, - b.earnings_linked_to_filing, - b.earnings_lagged_1605, - b.earnings_skipped_out_of_range, - b.earnings_duplicate_collapsed, - b.earnings_duplicate_conflict_dropped, - b.rows_out, - b.keys_out, - c.rows_in, - c.rows_out, - c.filings_out, - c.earnings_out, - c.listings_out, - c.dropped_unmapped, - c.listing_duplicate_collapsed, - w.files_written, - w.row_groups_written, - w.rows_written, - w.bytes_written, - years, - report.elapsed_secs, - ) -} - -#[cfg(test)] -#[path = "run_curate_events_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/run_curate_events_tests.rs b/tools/curate-etl/src/run_curate_events_tests.rs deleted file mode 100644 index 3429d6bb..00000000 --- a/tools/curate-etl/src/run_curate_events_tests.rs +++ /dev/null @@ -1,773 +0,0 @@ -use std::borrow::Cow; -use std::collections::BTreeMap; -use std::fs::{self, File}; -use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering}; - -use bson::{rawdoc, DateTime, RawDocumentBuf}; -use parquet::column::reader::ColumnReader; -use parquet::file::reader::{FileReader, SerializedFileReader}; - -use super::*; -use crate::bson_eod_prices::MILLIS_PER_DAY; -use crate::bson_qm_events::{ - DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD, DEFAULT_EARNINGS_KEY_FIELD, - DEFAULT_EARNINGS_REPORT_DATE_FIELD, DEFAULT_FILINGS_KEY_FIELD, DEFAULT_FILINGS_TIMEFILED_FIELD, -}; -use crate::events::{ - EVENT_KIND_EARNINGS, EVENT_KIND_FILING, KNOWN_AT_SOURCE_FILING_TIMESTAMP, - KNOWN_AT_SOURCE_STATUTORY_LAG, -}; -use crate::shorts::et_to_utc_micros; -use crate::split::ymd_to_epoch_days; - -static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0); - -struct TempDirGuard { - path: PathBuf, -} - -impl TempDirGuard { - fn new(label: &str) -> Self { - let seq = TEMP_DIR_SEQ.fetch_add(1, Ordering::Relaxed); - let pid = std::process::id(); - let path = - std::env::temp_dir().join(format!("curate-etl-run-events-{label}-{pid}-{seq}")); - let _ = fs::remove_dir_all(&path); - fs::create_dir_all(&path).expect("create test temp dir"); - Self { path } - } - - fn path(&self) -> &Path { - &self.path - } -} - -impl Drop for TempDirGuard { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.path); - } -} - -fn day(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).expect("valid date") -} - -fn utc_micros(y: i32, m: u32, d: u32, hh: u32, mm: u32, ss: u32) -> i64 { - let days = i64::from(day(y, m, d)); - let secs = days * 86_400 + i64::from(hh) * 3_600 + i64::from(mm) * 60 + i64::from(ss); - secs * 1_000_000 -} - -fn concat_docs(docs: &[RawDocumentBuf]) -> Vec { - let mut out = Vec::new(); - for d in docs { - out.extend_from_slice(d.as_bytes()); - } - out -} - -fn default_args(dir: &Path) -> CurateEventsArgs { - CurateEventsArgs { - qm_filings: dir.join("qmFilings.bson"), - qm_earnings: dir.join("qmEarnings.bson"), - provider_mapping: dir.join("provider_mapping.tsv"), - out_dir: dir.join("out"), - filings_key_field: DEFAULT_FILINGS_KEY_FIELD.to_string(), - filings_timefiled_field: DEFAULT_FILINGS_TIMEFILED_FIELD.to_string(), - filings_form_type_field: "formtype".to_string(), - filings_filing_id_field: Some("filingId".to_string()), - filings_url_field: Some("url".to_string()), - earnings_key_field: DEFAULT_EARNINGS_KEY_FIELD.to_string(), - earnings_report_date_field: DEFAULT_EARNINGS_REPORT_DATE_FIELD.to_string(), - earnings_announce_time_field: DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD.to_string(), - earnings_fiscal_period_end_field: Some("periodEndDate".to_string()), - earnings_actual_eps_field: Some("actualEps".to_string()), - earnings_revenue_field: Some("revenue".to_string()), - mapping_source: DEFAULT_EVENTS_MAPPING_SOURCE.to_string(), - } -} - -fn read_i32_col(reader: ColumnReader, expected: usize) -> Vec { - let mut values = Vec::with_capacity(expected); - match reader { - ColumnReader::Int32ColumnReader(mut r) => { - let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap(); - assert_eq!(records, expected); - } - _ => panic!("expected Int32ColumnReader"), - } - values -} - -fn read_i64_col(reader: ColumnReader, expected: usize) -> Vec { - let mut values = Vec::with_capacity(expected); - match reader { - ColumnReader::Int64ColumnReader(mut r) => { - let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap(); - assert_eq!(records, expected); - } - _ => panic!("expected Int64ColumnReader"), - } - values -} - -fn read_str_col(reader: ColumnReader, expected: usize) -> Vec { - let mut values = Vec::with_capacity(expected); - match reader { - ColumnReader::ByteArrayColumnReader(mut r) => { - let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap(); - assert_eq!(records, expected); - } - _ => panic!("expected ByteArrayColumnReader"), - } - values - .into_iter() - .map(|ba| String::from_utf8(ba.data().to_vec()).expect("valid utf8")) - .collect() -} - -fn read_events_parquet_file(path: &Path) -> (usize, Vec) { - let file = File::open(path).expect("open parquet file"); - let reader = SerializedFileReader::new(file).expect("open parquet reader"); - let metadata = reader.metadata(); - let footer_rows = metadata.file_metadata().num_rows() as usize; - let mut out = Vec::with_capacity(footer_rows); - - for rg_idx in 0..metadata.num_row_groups() { - let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); - let num_rows = metadata.row_group(rg_idx).num_rows() as usize; - - let listing_id = read_i32_col(rg_reader.get_column_reader(0).unwrap(), num_rows); - let ts_micros = read_i64_col(rg_reader.get_column_reader(1).unwrap(), num_rows); - let known_at_micros = read_i64_col(rg_reader.get_column_reader(2).unwrap(), num_rows); - let known_at_source = read_str_col(rg_reader.get_column_reader(3).unwrap(), num_rows); - let kind = read_str_col(rg_reader.get_column_reader(4).unwrap(), num_rows); - let subtype = read_str_col(rg_reader.get_column_reader(5).unwrap(), num_rows); - let payload_json = read_str_col(rg_reader.get_column_reader(6).unwrap(), num_rows); - - for i in 0..num_rows { - out.push(EventsParquetRow { - listing_id: listing_id[i], - ts_micros: ts_micros[i], - known_at_micros: known_at_micros[i], - known_at_source: Cow::Owned(known_at_source[i].clone()), - kind: Cow::Owned(kind[i].clone()), - subtype: subtype[i].clone(), - payload_json: payload_json[i].clone(), - }); - } - } - (footer_rows, out) -} - -fn read_all_events_partitions(out_dir: &Path) -> BTreeMap> { - let events_dir = out_dir.join("events"); - let mut by_year: BTreeMap> = BTreeMap::new(); - for entry in fs::read_dir(&events_dir).expect("read events dir") { - let entry = entry.unwrap(); - let name = entry.file_name(); - let name_str = name.to_string_lossy(); - let Some(year_str) = name_str.strip_prefix("year=") else { - continue; - }; - let year: i32 = year_str.parse().expect("valid year partition"); - let part_path = entry.path().join("part.parquet"); - let (footer_rows, rows) = read_events_parquet_file(&part_path); - assert_eq!(footer_rows, rows.len()); - by_year.insert(year, rows); - } - by_year -} - -fn assert_report_conservation(report: &CurateEventsRunReport) { - assert_eq!(report.filings_docs_framed as usize, report.filings_decode.docs_in); - assert_eq!( - report.filings_decode.docs_in, - report.filings_decode.rows_out + report.filings_decode.skipped_total() - ); - assert_eq!(report.earnings_docs_framed as usize, report.earnings_decode.docs_in); - assert_eq!( - report.earnings_decode.docs_in, - report.earnings_decode.rows_out + report.earnings_decode.skipped_total() - ); - assert_eq!( - report.filings_decode.rows_out, - report.curate_stats.builder.filings_in - ); - assert_eq!( - report.earnings_decode.rows_out, - report.curate_stats.builder.earnings_in - ); - assert_eq!( - report.curate_stats.rows_in, - report.curate_stats.builder.rows_out - ); - assert_eq!( - report.curate_stats.rows_in, - report.curate_stats.rows_out - + report.curate_stats.dropped_unmapped - + report.curate_stats.listing_duplicate_collapsed - ); - assert_eq!( - report.write_stats.rows_written, - report.curate_stats.rows_out - ); -} - -#[test] -fn end_to_end_curate_events_partitions_linking_lag_rollover_and_determinism() { - let tmp = TempDirGuard::new("e2e"); - let dir = tmp.path(); - - // provider_mapping.tsv: - // - AAPL -> listing 101 (2020-01-01..open) - // - SHOP:CA -> listing 202 (2020-01-01..open) - // - ROLL -> listing 303 (2020-01-01..2024-12-31) — ends on Dec 31 ET! - let mapping_tsv = concat!( - "qm\tAAPL\t2020-01-01\t\t101\n", - "qm\tSHOP:CA\t2020-01-01\t\t202\n", - "qm\tROLL\t2020-01-01\t2024-12-31\t303\n", - ); - fs::write(dir.join("provider_mapping.tsv"), mapping_tsv).unwrap(); - - let filing_docs = vec![ - // 1. EST filing (2025-01-31 06:01:27 EST = 2025-01-31 11:01:27 UTC), 8-K linking AAPL earnings - rawdoc! { - "symbol": "AAPL", - "timefiled": "2025-01-31T06:01:27 EST", - "formtype": "8-K", - "filingId": "EDGAR-8K-001", - "url": "https://sec.gov/8k-001", - }, - // 2. EDT filing (2025-07-15 16:30:00 EDT = 2025-07-15 20:30:00 UTC), 10-Q - rawdoc! { - "symbol": "AAPL", - "timefiled": "2025-07-15T16:30:00 EDT", - "formtype": "10-Q", - "filingId": "EDGAR-10Q-002", - }, - // 3. Late-evening Dec 31 ET rollover: 2024-12-31 21:30:00 EST = 2025-01-01 02:30:00 UTC - // Mapping for ROLL ends 2024-12-31, so ET-date mapping succeeds while UTC year is 2025! - rawdoc! { - "symbol": "ROLL", - "timefiled": "2024-12-31T21:30:00 EST", - "formtype": "10-K", - "filingId": "ROLL-10K", - }, - // 4. 2024 filing for SHOP:CA -> lands in year=2024 - rawdoc! { - "symbol": "SHOP:CA", - "timefiled": "2024-11-12T07:00:00 EST", - "formtype": "News release", - "filingId": "SEDAR-NR-001", - }, - // 5. Unmapped filing -> dropped_unmapped - rawdoc! { - "symbol": "UNMAPPED", - "timefiled": "2025-03-01T09:00:00 EST", - "formtype": "8-K", - "filingId": "UNM-1", - }, - // 6. Semantically skipped filing (blank formtype) - rawdoc! { - "symbol": "AAPL", - "timefiled": "2025-03-02T09:00:00 EST", - "formtype": " ", - }, - ]; - - let earning_docs = vec![ - // 1. AAPL same-day earnings linked to EDGAR-8K-001 (with consensusEps that must NOT appear) - rawdoc! { - "qmSearchCode": "AAPL", - "reportDate": DateTime::from_millis(i64::from(day(2025, 1, 31)) * MILLIS_PER_DAY), - "announceTime": "BTO", - "periodEndDate": "2024-12-28", - "actualEps": 2.40_f64, - "revenue": 124_300_000_000_i64, - "consensusEps": 2.35_f64, - }, - // 2. SHOP:CA unlinked N/A earnings on 2025-02-11 -> lagged to 16:05 EST (21:05 UTC) - rawdoc! { - "qmSearchCode": "SHOP:CA", - "reportDate": "2025-02-11", - "announceTime": "N/A", - "periodEndDate": "2024-12-31", - "actualEps": 0.44_f64, - "revenue": 2_810_000_000_i64, - "consensusEps": 0.42_f64, - }, - // 3. Unmapped earnings -> dropped_unmapped - rawdoc! { - "qmSearchCode": "NOPE", - "reportDate": "2025-04-01", - "announceTime": "AMC", - "consensusEps": 1.0_f64, - }, - ]; - - fs::write(dir.join("qmFilings.bson"), concat_docs(&filing_docs)).unwrap(); - fs::write(dir.join("qmEarnings.bson"), concat_docs(&earning_docs)).unwrap(); - - let args = default_args(dir); - let report = run_curate_events(&args).expect("curate-events succeeds"); - assert_report_conservation(&report); - - assert_eq!(report.filings_decode.docs_in, 6); - assert_eq!(report.filings_decode.rows_out, 5); - assert_eq!(report.filings_decode.skipped_empty_form_type, 1); - assert_eq!(report.earnings_decode.docs_in, 3); - assert_eq!(report.earnings_decode.rows_out, 3); - assert_eq!(report.curate_stats.dropped_unmapped, 2); - assert_eq!(report.curate_stats.rows_out, 6); - assert_eq!(report.curate_stats.filings_out, 4); - assert_eq!(report.curate_stats.earnings_out, 2); - assert_eq!(report.curate_stats.builder.earnings_linked_to_filing, 1); - assert_eq!(report.curate_stats.builder.earnings_lagged_1605, 2); - assert_eq!(report.write_stats.files_written, 2); - assert_eq!(report.write_stats.rows_by_year.get(&2024), Some(&1)); - assert_eq!(report.write_stats.rows_by_year.get(&2025), Some(&5)); - - let by_year = read_all_events_partitions(&args.out_dir); - assert_eq!(by_year.keys().copied().collect::>(), vec![2024, 2025]); - - // Check consensusEps is absent from every emitted payload_json across all partitions. - for rows in by_year.values() { - for r in rows { - assert!( - !r.payload_json.to_ascii_lowercase().contains("consensus"), - "consensusEps leaked into payload_json: {}", - r.payload_json - ); - } - } - - // 2024 partition: SHOP:CA News release - let y2024 = &by_year[&2024]; - assert_eq!(y2024.len(), 1); - assert_eq!(y2024[0].listing_id, 202); - assert_eq!(y2024[0].ts_micros, utc_micros(2024, 11, 12, 12, 0, 0)); - assert_eq!(y2024[0].known_at_micros, utc_micros(2024, 11, 12, 12, 0, 0)); - assert_eq!(y2024[0].known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); - assert_eq!(y2024[0].kind, EVENT_KIND_FILING); - assert_eq!(y2024[0].subtype, "news_release"); - - // 2025 partition: - let y2025 = &by_year[&2025]; - assert_eq!(y2025.len(), 5); - - // 101 AAPL linked earnings + EST 8-K at 2025-01-31 11:01:27 UTC ("earnings" < "filing") - let est_ts = utc_micros(2025, 1, 31, 11, 1, 27); - assert_eq!(y2025[0].listing_id, 101); - assert_eq!(y2025[0].kind, EVENT_KIND_EARNINGS); - assert_eq!(y2025[0].ts_micros, est_ts); - assert_eq!(y2025[0].known_at_micros, est_ts); - assert_eq!(y2025[0].known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); - assert_eq!(y2025[0].subtype, "bto"); - assert!(y2025[0].payload_json.contains("\"linked_filing_id\":\"EDGAR-8K-001\"")); - - assert_eq!(y2025[1].listing_id, 101); - assert_eq!(y2025[1].kind, EVENT_KIND_FILING); - assert_eq!(y2025[1].ts_micros, est_ts); - assert_eq!(y2025[1].known_at_micros, est_ts); - assert_eq!(y2025[1].subtype, "8-k"); - - // 101 AAPL EDT 10-Q at 2025-07-15 20:30:00 UTC - let edt_ts = utc_micros(2025, 7, 15, 20, 30, 0); - assert_eq!(y2025[2].listing_id, 101); - assert_eq!(y2025[2].kind, EVENT_KIND_FILING); - assert_eq!(y2025[2].ts_micros, edt_ts); - assert_eq!(y2025[2].known_at_micros, edt_ts); - assert_eq!(y2025[2].subtype, "10-q"); - - // 202 SHOP:CA unlinked N/A earnings lagged to 2025-02-11 16:05 EST - let expected_lag = et_to_utc_micros(day(2025, 2, 11), 16, 5, 0).unwrap(); - assert_eq!(y2025[3].listing_id, 202); - assert_eq!(y2025[3].kind, EVENT_KIND_EARNINGS); - assert_eq!(y2025[3].ts_micros, expected_lag); - assert_eq!(y2025[3].known_at_micros, expected_lag); - assert_eq!(y2025[3].known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); - assert_eq!(y2025[3].subtype, "unknown"); - - // 303 ROLL Dec 31 late-evening ET rollover -> year=2025 UTC partition - assert_eq!(y2025[4].listing_id, 303); - assert_eq!(y2025[4].kind, EVENT_KIND_FILING); - assert_eq!(y2025[4].ts_micros, utc_micros(2025, 1, 1, 2, 30, 0)); - assert_eq!(y2025[4].subtype, "10-k"); - - // Report formatting smoke check - let formatted = format_curate_events_report(&report); - assert!(formatted.contains("curate-etl curate-events")); - assert!(formatted.contains("years: 2024=1 2025=5")); - - // Reversed input order must yield byte-identical Parquet files. - let tmp_rev = TempDirGuard::new("e2e-rev"); - let dir_rev = tmp_rev.path(); - fs::write(dir_rev.join("provider_mapping.tsv"), mapping_tsv).unwrap(); - let mut f_rev = filing_docs.clone(); - f_rev.reverse(); - let mut e_rev = earning_docs.clone(); - e_rev.reverse(); - fs::write(dir_rev.join("qmFilings.bson"), concat_docs(&f_rev)).unwrap(); - fs::write(dir_rev.join("qmEarnings.bson"), concat_docs(&e_rev)).unwrap(); - - let args_rev = default_args(dir_rev); - let report_rev = run_curate_events(&args_rev).expect("reversed run succeeds"); - assert_eq!(report_rev.write_stats, report.write_stats); - for year in [2024, 2025] { - let a = fs::read(args.out_dir.join(format!("events/year={year}/part.parquet"))).unwrap(); - let b = fs::read(args_rev.out_dir.join(format!("events/year={year}/part.parquet"))).unwrap(); - assert_eq!(a, b, "year={year} parquet must be byte-identical under reversed input"); - } -} - -#[test] -fn failure_modes_publish_nothing_and_preserve_sentinel() { - let tmp = TempDirGuard::new("failures"); - let dir = tmp.path(); - - let valid_mapping = "qm\tAAPL\t2020-01-01\t\t101\n"; - let valid_filing = rawdoc! { - "symbol": "AAPL", - "timefiled": "2025-01-31T06:01:27 EST", - "formtype": "10-K", - }; - let valid_earning = rawdoc! { - "qmSearchCode": "AAPL", - "reportDate": "2025-01-31", - "announceTime": "AMC", - }; - - fs::write(dir.join("provider_mapping.tsv"), valid_mapping).unwrap(); - fs::write(dir.join("qmFilings.bson"), valid_filing.as_bytes()).unwrap(); - fs::write(dir.join("qmEarnings.bson"), valid_earning.as_bytes()).unwrap(); - - // Plant a sentinel file under out/events/year=2025/part.parquet - let sentinel_path = dir.join("out/events/year=2025/part.parquet"); - fs::create_dir_all(sentinel_path.parent().unwrap()).unwrap(); - let sentinel_bytes = b"PREEXISTING_SENTINEL_BYTES"; - fs::write(&sentinel_path, sentinel_bytes).unwrap(); - - let assert_sentinel_untouched = || { - assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel_bytes); - }; - - // 1. Missing qmFilings - let mut a = default_args(dir); - a.qm_filings = dir.join("does_not_exist_filings.bson"); - let err = run_curate_events(&a).unwrap_err(); - assert!(matches!(err, RunCurateEventsError::OpenInput { label: "qm-filings", .. })); - assert!(!err.to_string().contains('\n')); - assert_sentinel_untouched(); - - // 2. Missing qmEarnings - let mut a = default_args(dir); - a.qm_earnings = dir.join("does_not_exist_earnings.bson"); - let err = run_curate_events(&a).unwrap_err(); - assert!(matches!(err, RunCurateEventsError::OpenInput { label: "qm-earnings", .. })); - assert!(!err.to_string().contains('\n')); - assert_sentinel_untouched(); - - // 3. Missing provider_mapping - let mut a = default_args(dir); - a.provider_mapping = dir.join("does_not_exist_mapping.tsv"); - let err = run_curate_events(&a).unwrap_err(); - assert!(matches!(err, RunCurateEventsError::OpenInput { .. })); - assert!(!err.to_string().contains('\n')); - assert_sentinel_untouched(); - - // 4. Malformed provider_mapping.tsv - let bad_tsv = dir.join("bad_mapping.tsv"); - fs::write(&bad_tsv, "only_two_cols\tbad\n").unwrap(); - let mut a = default_args(dir); - a.provider_mapping = bad_tsv; - let err = run_curate_events(&a).unwrap_err(); - assert!(matches!(err, RunCurateEventsError::TsvParse { line: 1, .. })); - assert_sentinel_untouched(); - - // 5. Overlapping provider_mapping.tsv - let overlap_tsv = dir.join("overlap_mapping.tsv"); - fs::write( - &overlap_tsv, - "qm\tAAPL\t2020-01-01\t2024-06-01\t101\nqm\tAAPL\t2024-06-01\t\t102\n", - ) - .unwrap(); - let mut a = default_args(dir); - a.provider_mapping = overlap_tsv; - let err = run_curate_events(&a).unwrap_err(); - assert!(matches!(err, RunCurateEventsError::ProviderMapping { .. })); - assert_sentinel_untouched(); - - // 6. Truncated BSON in qmFilings - let trunc_f = dir.join("trunc_filings.bson"); - fs::write(&trunc_f, &valid_filing.as_bytes()[..10]).unwrap(); - let mut a = default_args(dir); - a.qm_filings = trunc_f; - let err = run_curate_events(&a).unwrap_err(); - assert!(matches!(err, RunCurateEventsError::BsonStream { label: "qm-filings", .. })); - assert_sentinel_untouched(); - - // 7. Truncated BSON in qmEarnings - let trunc_e = dir.join("trunc_earnings.bson"); - fs::write(&trunc_e, &valid_earning.as_bytes()[..10]).unwrap(); - let mut a = default_args(dir); - a.qm_earnings = trunc_e; - let err = run_curate_events(&a).unwrap_err(); - assert!(matches!(err, RunCurateEventsError::BsonStream { label: "qm-earnings", .. })); - assert_sentinel_untouched(); - - // 8. Corrupt BSON element in qmFilings and qmEarnings - let mut corrupt = rawdoc! { "symbol": "AAPL", "z": 1_i32 }.into_bytes(); - let z_pos = corrupt - .windows(3) - .position(|w| w == [0x10, b'z', 0x00]) - .unwrap(); - corrupt[z_pos] = 0x7e; - let corrupt_path = dir.join("corrupt.bson"); - fs::write(&corrupt_path, &corrupt).unwrap(); - - let mut a = default_args(dir); - a.qm_filings = corrupt_path.clone(); - assert!(matches!( - run_curate_events(&a), - Err(RunCurateEventsError::CorruptBson { - label: "qm-filings", - offset: 0, - .. - }) - )); - assert_sentinel_untouched(); - - let mut a = default_args(dir); - a.qm_earnings = corrupt_path; - assert!(matches!( - run_curate_events(&a), - Err(RunCurateEventsError::CorruptBson { - label: "qm-earnings", - offset: 0, - .. - }) - )); - assert_sentinel_untouched(); - - // 9. Blank, colliding, and consensusEps field configs + empty mapping_source - let mut a = default_args(dir); - a.filings_form_type_field = " ".to_string(); - assert!(matches!( - run_curate_events(&a), - Err(RunCurateEventsError::InvalidFieldNames { .. }) - )); - - let mut a = default_args(dir); - a.filings_form_type_field = DEFAULT_FILINGS_KEY_FIELD.to_string(); - assert!(matches!( - run_curate_events(&a), - Err(RunCurateEventsError::InvalidFieldNames { .. }) - )); - - let mut a = default_args(dir); - a.earnings_actual_eps_field = Some("consensusEps".to_string()); - assert!(matches!( - run_curate_events(&a), - Err(RunCurateEventsError::InvalidFieldNames { .. }) - )); - - let mut a = default_args(dir); - a.mapping_source = " ".to_string(); - assert!(matches!( - run_curate_events(&a), - Err(RunCurateEventsError::EmptyMappingSource) - )); - assert_sentinel_untouched(); - - // 10. --out as regular file - let reg_file = dir.join("not_a_dir"); - fs::write(®_file, b"x").unwrap(); - let mut a = default_args(dir); - a.out_dir = reg_file; - assert!(matches!( - run_curate_events(&a), - Err(RunCurateEventsError::InvalidOutDir { .. }) - )); - - // 11. /events as regular file - let out_blocked = dir.join("out_blocked"); - fs::create_dir_all(&out_blocked).unwrap(); - fs::write(out_blocked.join("events"), b"x").unwrap(); - let mut a = default_args(dir); - a.out_dir = out_blocked; - assert!(matches!( - run_curate_events(&a), - Err(RunCurateEventsError::InvalidOutDir { .. }) - )); - - // 12. Input file inside /events/ (clobber protection, including via `..`) - let mut a = default_args(dir); - a.qm_filings = dir.join("out/events/year=2025/../year=2025/part.parquet"); - assert!(matches!( - run_curate_events(&a), - Err(RunCurateEventsError::InvalidOutDir { .. }) - )); - assert_sentinel_untouched(); -} - -#[cfg(unix)] -#[test] -fn symlink_followed_by_parent_dir_into_events_output_is_rejected_without_modifying_input() { - use std::os::unix::fs::symlink; - - let tmp = TempDirGuard::new("symlink_parent_clobber"); - let dir = tmp.path(); - - fs::write( - dir.join("provider_mapping.tsv"), - "qm\tAAPL\t2020-01-01\t\t101\n", - ) - .unwrap(); - let valid_filing = rawdoc! { - "symbol": "AAPL", - "timefiled": "2025-02-10 16:30:00 EST", - "formType": "10-K", - }; - let filing_bytes = valid_filing.as_bytes().to_vec(); - let valid_earning = rawdoc! { - "qmSearchCode": "AAPL", - "reportDate": "2025-02-10", - "announceTime": "AMC", - }; - fs::write(dir.join("qmEarnings.bson"), valid_earning.as_bytes()).unwrap(); - - // Place the real input at `/events/year=2025/part.parquet` and expose it via - // `exports/latest/../part.parquet`, where `exports/latest` symlinks to - // `/events/year=2025/staging`. - let year_dir = dir.join("out/events/year=2025"); - let staging_dir = year_dir.join("staging"); - fs::create_dir_all(&staging_dir).unwrap(); - let real_input = year_dir.join("part.parquet"); - fs::write(&real_input, &filing_bytes).unwrap(); - - let exports_dir = dir.join("exports"); - fs::create_dir_all(&exports_dir).unwrap(); - let latest_link = exports_dir.join("latest"); - symlink(&staging_dir, &latest_link).unwrap(); - - let mut args = default_args(dir); - args.qm_filings = latest_link.join("../part.parquet"); - - let err = run_curate_events(&args).unwrap_err(); - assert!( - matches!(err, RunCurateEventsError::InvalidOutDir { .. }), - "expected InvalidOutDir for symlink+`..` input inside events/, got: {err:?}" - ); - assert!(!err.to_string().contains('\n')); - assert_eq!( - fs::read(&real_input).unwrap(), - filing_bytes, - "input file bytes must remain untouched" - ); - - // Also verify a non-existent file reached through the same symlink+`..` is rejected as - // InvalidOutDir before opening inputs. - args.qm_filings = latest_link.join("../future.parquet"); - let err = run_curate_events(&args).unwrap_err(); - assert!( - matches!(err, RunCurateEventsError::InvalidOutDir { .. }), - "expected InvalidOutDir for non-existent symlink+`..` path inside events/, got: {err:?}" - ); - assert_eq!(fs::read(&real_input).unwrap(), filing_bytes); -} - -#[cfg(unix)] -#[test] -fn symlinked_year_partition_directory_overlapping_input_is_rejected_without_modifying_input() { - use std::os::unix::fs::symlink; - - let tmp = TempDirGuard::new("symlink_year_dir_clobber"); - let dir = tmp.path(); - - fs::write( - dir.join("provider_mapping.tsv"), - "qm\tAAPL\t2020-01-01\t\t101\n", - ) - .unwrap(); - let valid_filing = rawdoc! { - "symbol": "AAPL", - "timefiled": "2025-02-10 16:30:00 EST", - "formType": "10-K", - }; - let filing_bytes = valid_filing.as_bytes().to_vec(); - let valid_earning = rawdoc! { - "qmSearchCode": "AAPL", - "reportDate": "2025-02-10", - "announceTime": "AMC", - }; - fs::write(dir.join("qmEarnings.bson"), valid_earning.as_bytes()).unwrap(); - - // Case 1: `/events/year=2025` is a symlink to an external directory whose `part.parquet` - // is passed as `--qm-filings`. - let external_dir = dir.join("external_inputs"); - fs::create_dir_all(&external_dir).unwrap(); - let external_part = external_dir.join("part.parquet"); - fs::write(&external_part, &filing_bytes).unwrap(); - - let events_dir = dir.join("out/events"); - fs::create_dir_all(&events_dir).unwrap(); - symlink(&external_dir, events_dir.join("year=2025")).unwrap(); - - let mut args = default_args(dir); - args.qm_filings = external_part.clone(); - - let err = run_curate_events(&args).unwrap_err(); - assert!( - matches!(err, RunCurateEventsError::InvalidOutDir { .. }), - "expected InvalidOutDir for symlinked year=2025 overlapping input, got: {err:?}" - ); - assert!(!err.to_string().contains('\n')); - assert_eq!( - fs::read(&external_part).unwrap(), - filing_bytes, - "external input bytes must remain untouched" - ); - - let timed_err = run_curate_events_timed(&args).unwrap_err(); - assert!( - matches!(timed_err, RunCurateEventsError::InvalidOutDir { .. }), - "expected InvalidOutDir from timed runner, got: {timed_err:?}" - ); - assert_eq!(fs::read(&external_part).unwrap(), filing_bytes); - - // Case 2: `/events/year=2025` is a real directory, but `part.parquet` inside it is a - // symlink pointing to an external input file. - fs::remove_file(events_dir.join("year=2025")).unwrap(); - let real_year_dir = events_dir.join("year=2025"); - fs::create_dir_all(&real_year_dir).unwrap(); - let external_bson = external_dir.join("qmFilings.bson"); - fs::write(&external_bson, &filing_bytes).unwrap(); - symlink(&external_bson, real_year_dir.join("part.parquet")).unwrap(); - - args.qm_filings = external_bson.clone(); - let err = run_curate_events(&args).unwrap_err(); - assert!( - matches!(err, RunCurateEventsError::InvalidOutDir { .. }), - "expected InvalidOutDir for symlinked part.parquet overlapping input, got: {err:?}" - ); - assert!(!err.to_string().contains('\n')); - assert_eq!(fs::read(&external_bson).unwrap(), filing_bytes); -} - -#[test] -fn empty_inputs_return_ok_without_creating_events_dir() { - let tmp = TempDirGuard::new("empty"); - let dir = tmp.path(); - fs::write(dir.join("provider_mapping.tsv"), "qm\tAAPL\t2020-01-01\t\t101\n").unwrap(); - fs::write(dir.join("qmFilings.bson"), b"").unwrap(); - fs::write(dir.join("qmEarnings.bson"), b"").unwrap(); - - let args = default_args(dir); - let report = run_curate_events(&args).expect("empty inputs succeed"); - assert_report_conservation(&report); - assert_eq!(report.write_stats.rows_written, 0); - assert_eq!(report.write_stats.files_written, 0); - assert!(!args.out_dir.join("events").exists()); -} diff --git a/tools/curate-etl/src/run_curate_fundamentals.rs b/tools/curate-etl/src/run_curate_fundamentals.rs deleted file mode 100644 index f62c9e70..00000000 --- a/tools/curate-etl/src/run_curate_fundamentals.rs +++ /dev/null @@ -1,1200 +0,0 @@ -//! File-to-file `curate-fundamentals` runner (`M2.2m`). -//! -//! Streams concatenated raw BSON `qmFinancials` and `qmFilings` dump files alongside -//! `provider_mapping.tsv` and `listing_venues.tsv` into atomically published -//! `/fundamentals_pit/year=YYYY/part.parquet` partitions via -//! [`curate_and_write_fundamentals`]. -//! -//! # Contract & Point-in-Time Rules -//! - `qmFinancials` field defaults are restricted strictly to repo-evidenced top-level names -//! (`qmSearchCode`, `periodEndDate`, `reportDate`, `reportPeriod`). The `currency` path, all six -//! numeric metric paths (`Option`), and [`CurateFundamentalsFiscalPeriod`] have **no -//! defaults** and must be supplied explicitly. -//! - `qmFilings` field defaults match `run_curate_events` (`symbol`, `timefiled`), while -//! `form_type` has no default and `filing_id` / `url` are optional. -//! - `provider_mapping.tsv` uses the strict headerless 5-column TSV format from -//! [`crate::run_curate_bars::load_provider_mapping_tsv`]. -//! - `listing_venues.tsv` uses a strict headerless 2-column TSV format `listing_idvenue` -//! where `venue` is exactly `us_tsx` or `tsxv_cse` ([`load_listing_venues_tsv`]). -//! - Decoded provider keys are preserved verbatim (no trimming or suffix rewriting) and resolved -//! to permanent `listing_id`s inside [`curate_and_write_fundamentals`]. -//! - **In-memory accumulation:** [`RawBsonChunkReader`] bounds only the raw BSON framing buffer -//! (`*_peak_chunk_bytes`); decoded observations and filings accumulate in memory before -//! [`curate_and_write_fundamentals`] runs. -//! - **Empty / all-unmapped behavior:** delegated unchanged to [`curate_and_write_fundamentals`], -//! returning `Ok` with `rows_written == 0` and `files_written == 0` without creating -//! `/fundamentals_pit` or modifying any pre-existing partitions. -//! - **Fail-closed safety:** invalid field/fiscal config, blank `mapping_source`, `k == 0`, -//! unreadable inputs, malformed/overlapping `provider_mapping.tsv`, malformed/duplicate -//! `listing_venues.tsv`, truncated/corrupt BSON, `out_dir` or `/fundamentals_pit` -//! occupied by a regular file, or any input path resolving to `out_dir`, `/fundamentals_pit`, -//! or an existing `year=YYYY` partition target all return a typed [`RunCurateFundamentalsError`] -//! before anything is created or modified under `out_dir`. -//! -//! # Counter Conservation Invariants -//! Every successful [`CurateFundamentalsRunReport`] satisfies: -//! - `financials_docs_framed as usize == financials_decode.docs_in == financials_decode.rows_out + financials_decode.skipped_total()` -//! - `filings_docs_framed as usize == filings_decode.docs_in == filings_decode.rows_out + filings_decode.skipped_total()` -//! - `financials_decode.rows_out == curate_stats.observations_in` -//! - `filings_decode.rows_out == curate_stats.filings_in` -//! - `write_stats.rows_written == curate_stats.rows_out` - -use std::collections::{BTreeMap, HashSet}; -use std::error::Error; -use std::fmt::{self, Write as _}; -use std::fs::{self, File}; -use std::io; -use std::path::{Component, Path, PathBuf}; -use std::sync::Arc; -use std::time::Instant; - -use crate::bson_qm_events::{ - BsonQmEventsError, BsonQmFilingsDecodeStats, QmFilingsFieldNames, DEFAULT_FILINGS_KEY_FIELD, - DEFAULT_FILINGS_TIMEFILED_FIELD, -}; -use crate::bson_qm_financials::{ - BsonQmFinancialsDecodeStats, BsonQmFinancialsError, QmFinancialsFieldNames, - QmFinancialsFiscalPeriod, DEFAULT_QM_FINANCIALS_KEY_FIELD, - DEFAULT_QM_FINANCIALS_PERIOD_END_FIELD, DEFAULT_QM_FINANCIALS_REPORT_DATE_FIELD, - DEFAULT_QM_FINANCIALS_REPORT_PERIOD_FIELD, -}; -use crate::bson_stream::{ - decode_qm_filings_chunks, decode_qm_financials_chunks, BsonQmEventsStreamError, - BsonQmFinancialsStreamError, BsonStreamError, BsonStreamOptions, RawBsonChunkReader, -}; -use crate::curate_fundamentals::{ - curate_and_write_fundamentals, CurateFundamentalsStats, CurateFundamentalsWriteError, -}; -use crate::events::QmFiling; -use crate::fundamentals::{FinancialObservation, FiscalPeriod, StatutoryLagVenue}; -use crate::parquet_fundamentals::{FundamentalsPitWriteOptions, FundamentalsPitWriteStats}; -use crate::provider_mapping::{ProviderMappingError, ProviderMappingTable}; -use crate::run_curate_bars::{ - load_provider_mapping_tsv, parse_strict_positive_i32, read_tsv_lines, RunCurateBarsError, -}; - -/// Default `mapping_source` passed to `provider_mapping` lookups for `qmFinancials` / `qmFilings`. -pub const DEFAULT_FUNDAMENTALS_MAPPING_SOURCE: &str = "qm"; - -/// Owned fiscal-period resolution policy for [`CurateFundamentalsArgs`]. -/// -/// Mirrors [`QmFinancialsFiscalPeriod`] without borrowing lifetimes so arguments can be stored -/// and passed cleanly to [`run_curate_fundamentals`]. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum CurateFundamentalsFiscalPeriod { - /// Assign a fixed [`FiscalPeriod`] to every decoded `qmFinancials` document. - Fixed(FiscalPeriod), - /// Match exact `report_period` BSON string values against explicit quarterly and annual lists. - ByTokens { - quarterly: Vec, - annual: Vec, - }, -} - -impl CurateFundamentalsFiscalPeriod { - /// Borrows this policy as [`QmFinancialsFiscalPeriod`] for validation or decoding. - pub fn with_borrowed(&self, f: impl FnOnce(QmFinancialsFiscalPeriod<'_>) -> R) -> R { - match self { - Self::Fixed(period) => f(QmFinancialsFiscalPeriod::Fixed(*period)), - Self::ByTokens { quarterly, annual } => { - let q_refs: Vec<&str> = quarterly.iter().map(String::as_str).collect(); - let a_refs: Vec<&str> = annual.iter().map(String::as_str).collect(); - f(QmFinancialsFiscalPeriod::ByTokens { - quarterly: &q_refs, - annual: &a_refs, - }) - } - } - } -} - -/// Arguments for [`run_curate_fundamentals`] and [`run_curate_fundamentals_with_readers`]. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct CurateFundamentalsArgs { - pub qm_financials: PathBuf, - pub qm_filings: PathBuf, - pub provider_mapping: PathBuf, - pub listing_venues: PathBuf, - pub out_dir: PathBuf, - pub financials_key_field: String, - pub financials_period_end_field: String, - pub financials_report_date_field: String, - pub financials_report_period_field: String, - pub financials_currency_field: String, - pub financials_revenue_field: Option, - pub financials_net_income_field: Option, - pub financials_operating_cash_flow_field: Option, - pub financials_total_assets_field: Option, - pub financials_total_equity_field: Option, - pub financials_shares_outstanding_field: Option, - pub fiscal_period: CurateFundamentalsFiscalPeriod, - pub filings_key_field: String, - pub filings_timefiled_field: String, - pub filings_form_type_field: String, - pub filings_filing_id_field: Option, - pub filings_url_field: Option, - pub mapping_source: String, - pub k: usize, -} - -impl CurateFundamentalsArgs { - /// Constructs arguments pre-populated with the four repo-evidenced `qmFinancials` defaults - /// (`qmSearchCode`, `periodEndDate`, `reportDate`, `reportPeriod`), the two verified - /// `qmFilings` defaults (`symbol`, `timefiled`), and `mapping_source = "qm"`. - /// - /// Unverified fields (`financials_currency_field`, all six numeric `Option` paths, - /// `fiscal_period`, `filings_form_type_field`, and snapshot period limit `k`) must be supplied - /// explicitly. `filings_filing_id_field` and `filings_url_field` default to `None`. - #[allow(clippy::too_many_arguments)] - pub fn with_verified_defaults( - qm_financials: PathBuf, - qm_filings: PathBuf, - provider_mapping: PathBuf, - listing_venues: PathBuf, - out_dir: PathBuf, - financials_currency_field: impl Into, - financials_revenue_field: Option, - financials_net_income_field: Option, - financials_operating_cash_flow_field: Option, - financials_total_assets_field: Option, - financials_total_equity_field: Option, - financials_shares_outstanding_field: Option, - fiscal_period: CurateFundamentalsFiscalPeriod, - filings_form_type_field: impl Into, - k: usize, - ) -> Self { - Self { - qm_financials, - qm_filings, - provider_mapping, - listing_venues, - out_dir, - financials_key_field: DEFAULT_QM_FINANCIALS_KEY_FIELD.to_string(), - financials_period_end_field: DEFAULT_QM_FINANCIALS_PERIOD_END_FIELD.to_string(), - financials_report_date_field: DEFAULT_QM_FINANCIALS_REPORT_DATE_FIELD.to_string(), - financials_report_period_field: DEFAULT_QM_FINANCIALS_REPORT_PERIOD_FIELD.to_string(), - financials_currency_field: financials_currency_field.into(), - financials_revenue_field, - financials_net_income_field, - financials_operating_cash_flow_field, - financials_total_assets_field, - financials_total_equity_field, - financials_shares_outstanding_field, - fiscal_period, - filings_key_field: DEFAULT_FILINGS_KEY_FIELD.to_string(), - filings_timefiled_field: DEFAULT_FILINGS_TIMEFILED_FIELD.to_string(), - filings_form_type_field: filings_form_type_field.into(), - filings_filing_id_field: None, - filings_url_field: None, - mapping_source: DEFAULT_FUNDAMENTALS_MAPPING_SOURCE.to_string(), - k, - } - } - - /// Borrows the configured `qmFinancials` BSON field paths as [`QmFinancialsFieldNames`]. - #[inline] - pub fn financials_field_names(&self) -> QmFinancialsFieldNames<'_> { - QmFinancialsFieldNames { - key: self.financials_key_field.as_str(), - period_end: self.financials_period_end_field.as_str(), - report_date: self.financials_report_date_field.as_str(), - report_period: self.financials_report_period_field.as_str(), - currency: self.financials_currency_field.as_str(), - revenue: self.financials_revenue_field.as_deref(), - net_income: self.financials_net_income_field.as_deref(), - operating_cash_flow: self.financials_operating_cash_flow_field.as_deref(), - total_assets: self.financials_total_assets_field.as_deref(), - total_equity: self.financials_total_equity_field.as_deref(), - shares_outstanding: self.financials_shares_outstanding_field.as_deref(), - } - } - - /// Borrows the configured `qmFilings` BSON field names as [`QmFilingsFieldNames`]. - #[inline] - pub fn filings_field_names(&self) -> QmFilingsFieldNames<'_> { - QmFilingsFieldNames { - key: self.filings_key_field.as_str(), - timefiled: self.filings_timefiled_field.as_str(), - form_type: self.filings_form_type_field.as_str(), - filing_id: self.filings_filing_id_field.as_deref(), - url: self.filings_url_field.as_deref(), - } - } -} - -/// Full run report produced by [`run_curate_fundamentals`] and -/// [`run_curate_fundamentals_with_readers`]. -#[derive(Debug, Clone, PartialEq)] -pub struct CurateFundamentalsRunReport { - pub financials_docs_framed: u64, - pub financials_bytes_read: u64, - pub financials_peak_chunk_bytes: usize, - pub financials_decode: BsonQmFinancialsDecodeStats, - pub filings_docs_framed: u64, - pub filings_bytes_read: u64, - pub filings_peak_chunk_bytes: usize, - pub filings_decode: BsonQmFilingsDecodeStats, - pub curate_stats: CurateFundamentalsStats, - pub write_stats: FundamentalsPitWriteStats, - pub elapsed_secs: f64, -} - -/// Typed errors returned by [`load_listing_venues_tsv`], [`run_curate_fundamentals`], and -/// [`run_curate_fundamentals_with_readers`]. -/// -/// Every variant's `Display` output is a single line naming the offending path (and line number or -/// byte offset where applicable). -#[derive(Debug)] -pub enum RunCurateFundamentalsError { - InvalidOutDir { - path: PathBuf, - detail: String, - }, - InspectOutDir { - path: PathBuf, - source: io::Error, - }, - InvalidFinancialsConfig { - path: PathBuf, - source: BsonQmFinancialsError, - }, - InvalidFilingsFieldNames { - path: PathBuf, - source: BsonQmEventsError, - }, - EmptyMappingSource, - InvalidPeriodLimit { - k: usize, - }, - OpenInput { - label: &'static str, - path: PathBuf, - source: io::Error, - }, - ReadInput { - label: &'static str, - path: PathBuf, - source: io::Error, - }, - TsvParse { - path: PathBuf, - line: usize, - detail: String, - }, - ProviderMapping { - path: PathBuf, - source: ProviderMappingError, - }, - BsonStream { - label: &'static str, - path: PathBuf, - source: BsonStreamError, - }, - CorruptFinancialsBson { - path: PathBuf, - offset: u64, - source: BsonQmFinancialsError, - }, - CorruptFilingsBson { - path: PathBuf, - offset: u64, - source: BsonQmEventsError, - }, - CurateWrite { - out_dir: PathBuf, - source: CurateFundamentalsWriteError, - }, -} - -struct SingleLineWriter<'a, 'b> { - f: &'a mut fmt::Formatter<'b>, -} - -impl fmt::Write for SingleLineWriter<'_, '_> { - fn write_str(&mut self, s: &str) -> fmt::Result { - let mut rest = s; - while let Some(idx) = rest.find(['\n', '\r']) { - let (head, tail) = rest.split_at(idx); - if !head.is_empty() { - self.f.write_str(head)?; - } - let mut chars = tail.chars(); - match chars.next() { - Some('\n') => self.f.write_str("\\n")?, - Some('\r') => self.f.write_str("\\r")?, - _ => unreachable!(), - } - rest = chars.as_str(); - } - if !rest.is_empty() { - self.f.write_str(rest)?; - } - Ok(()) - } -} - -impl fmt::Display for RunCurateFundamentalsError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let mut w = SingleLineWriter { f }; - match self { - Self::InvalidOutDir { path, detail } => { - write!(w, "invalid --out '{}': {detail}", path.display()) - } - Self::InspectOutDir { path, source } => { - write!( - w, - "failed to inspect output path '{}': {source}", - path.display() - ) - } - Self::InvalidFinancialsConfig { path, source } => { - write!( - w, - "invalid qm-financials config for '{}': {source}", - path.display() - ) - } - Self::InvalidFilingsFieldNames { path, source } => { - write!( - w, - "invalid qm-filings field config for '{}': {source}", - path.display() - ) - } - Self::EmptyMappingSource => { - write!(w, "invalid --mapping-source: must not be empty or blank") - } - Self::InvalidPeriodLimit { k } => { - write!(w, "invalid snapshot period limit k={k}: must be >= 1") - } - Self::OpenInput { - label, - path, - source, - } => write!(w, "failed to open {label} '{}': {source}", path.display()), - Self::ReadInput { - label, - path, - source, - } => write!(w, "failed to read {label} '{}': {source}", path.display()), - Self::TsvParse { path, line, detail } => { - write!(w, "{}:{line}: {detail}", path.display()) - } - Self::ProviderMapping { path, source } => { - write!(w, "invalid provider_mapping '{}': {source}", path.display()) - } - Self::BsonStream { - label, - path, - source, - } => write!(w, "failed reading {label} '{}': {source}", path.display()), - Self::CorruptFinancialsBson { - path, - offset, - source, - } => write!( - w, - "corrupt qm-financials BSON '{}' at byte offset {offset}: {source}", - path.display() - ), - Self::CorruptFilingsBson { - path, - offset, - source, - } => write!( - w, - "corrupt qm-filings BSON '{}' at byte offset {offset}: {source}", - path.display() - ), - Self::CurateWrite { out_dir, source } => { - write!(w, "curate/write to '{}' failed: {source}", out_dir.display()) - } - } - } -} - -impl Error for RunCurateFundamentalsError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::InspectOutDir { source, .. } => Some(source), - Self::InvalidFinancialsConfig { source, .. } => Some(source), - Self::InvalidFilingsFieldNames { source, .. } => Some(source), - Self::OpenInput { source, .. } | Self::ReadInput { source, .. } => Some(source), - Self::ProviderMapping { source, .. } => Some(source), - Self::BsonStream { source, .. } => Some(source), - Self::CorruptFinancialsBson { source, .. } => Some(source), - Self::CorruptFilingsBson { source, .. } => Some(source), - Self::CurateWrite { source, .. } => Some(source), - Self::InvalidOutDir { .. } - | Self::EmptyMappingSource - | Self::InvalidPeriodLimit { .. } - | Self::TsvParse { .. } => None, - } - } -} - -fn map_tsv_error(path: &Path, err: RunCurateBarsError) -> RunCurateFundamentalsError { - match err { - RunCurateBarsError::OpenInput { - label, - path, - source, - } => RunCurateFundamentalsError::OpenInput { - label, - path, - source, - }, - RunCurateBarsError::ReadInput { - label, - path, - source, - } => RunCurateFundamentalsError::ReadInput { - label, - path, - source, - }, - RunCurateBarsError::TsvParse { path, line, detail } => { - RunCurateFundamentalsError::TsvParse { path, line, detail } - } - RunCurateBarsError::ProviderMapping { path, source } => { - RunCurateFundamentalsError::ProviderMapping { path, source } - } - other => RunCurateFundamentalsError::TsvParse { - path: path.to_path_buf(), - line: 0, - detail: other.to_string(), - }, - } -} - -/// Loads `listing_venues.tsv` into an ordered `listing_id -> StatutoryLagVenue` map. -/// -/// Format (no header, 2 `\t`-separated columns): -/// `listing_id \t venue` -/// -/// `listing_id` must be a strictly positive ASCII base-10 `i32` (no sign or surrounding -/// whitespace). `venue` must be exact `"us_tsx"` or `"tsxv_cse"`. Duplicate `listing_id`s, -/// wrong column counts, unknown venues, and interior blank lines fail closed with a typed -/// single-line error naming `path` and the 1-based line number. -pub fn load_listing_venues_tsv( - path: &Path, -) -> Result, RunCurateFundamentalsError> { - let mut venues = BTreeMap::new(); - read_tsv_lines(path, "listing-venues", |_line_no, line| { - let mut cols = line.split('\t'); - let id_str = cols - .next() - .ok_or_else(|| "expected 2 tab-separated columns (listing_id, venue)".to_string())?; - let venue_str = cols.next().ok_or_else(|| { - "expected 2 tab-separated columns (listing_id, venue), got 1".to_string() - })?; - if cols.next().is_some() { - let count = line.split('\t').count(); - return Err(format!( - "expected 2 tab-separated columns (listing_id, venue), got {count}" - )); - } - - let listing_id = parse_strict_positive_i32(id_str).ok_or_else(|| { - format!("invalid listing_id '{id_str}': expected strictly positive integer") - })?; - - let venue = match venue_str { - "us_tsx" => StatutoryLagVenue::UsTsx, - "tsxv_cse" => StatutoryLagVenue::TsxvCse, - other => { - return Err(format!( - "unknown venue '{other}': expected 'us_tsx' or 'tsxv_cse'" - )); - } - }; - - if venues.insert(listing_id, venue).is_some() { - return Err(format!("duplicate listing_id {listing_id}")); - } - - Ok(()) - }) - .map_err(|err| map_tsv_error(path, err))?; - - Ok(venues) -} - -/// Resolves `path` to an absolute normalized path while preserving OS symlink-before-`..` -/// semantics: if `path` exists it is canonicalized directly; otherwise components are walked -/// left-to-right, canonicalizing each existing prefix before resolving `..`, and only lexically -/// normalizing `..` within any non-existent suffix. -fn resolve_normalized_path(path: &Path) -> PathBuf { - if let Ok(canon) = path.canonicalize() { - return canon; - } - - let abs = if path.is_absolute() { - path.to_path_buf() - } else if let Ok(cwd) = std::env::current_dir() { - cwd.join(path) - } else { - path.to_path_buf() - }; - - if let Ok(canon) = abs.canonicalize() { - return canon; - } - - let mut resolved = PathBuf::new(); - for comp in abs.components() { - match comp { - Component::Prefix(prefix) => resolved.push(prefix.as_os_str()), - Component::RootDir => resolved.push(Component::RootDir.as_os_str()), - Component::CurDir => {} - Component::Normal(seg) => { - resolved.push(seg); - if let Ok(canon) = resolved.canonicalize() { - resolved = canon; - } - } - Component::ParentDir => { - resolved.push(Component::ParentDir.as_os_str()); - if let Ok(canon) = resolved.canonicalize() { - resolved = canon; - } else { - resolved.pop(); - if matches!(resolved.components().next_back(), Some(Component::Normal(_))) { - resolved.pop(); - } - } - } - } - } - - resolved -} - -fn validate_out_dir_and_inputs( - args: &CurateFundamentalsArgs, -) -> Result<(), RunCurateFundamentalsError> { - if args.out_dir.as_os_str().is_empty() { - return Err(RunCurateFundamentalsError::InvalidOutDir { - path: args.out_dir.clone(), - detail: "output directory path must not be empty".to_string(), - }); - } - - match fs::metadata(&args.out_dir) { - Ok(meta) if !meta.is_dir() => { - return Err(RunCurateFundamentalsError::InvalidOutDir { - path: args.out_dir.clone(), - detail: "path exists and is not a directory".to_string(), - }); - } - Ok(_) => {} - Err(err) if err.kind() == io::ErrorKind::NotFound => {} - Err(source) => { - return Err(RunCurateFundamentalsError::InspectOutDir { - path: args.out_dir.clone(), - source, - }); - } - } - - let fundamentals_dir = args.out_dir.join("fundamentals_pit"); - let fundamentals_dir_exists = match fs::metadata(&fundamentals_dir) { - Ok(meta) if !meta.is_dir() => { - return Err(RunCurateFundamentalsError::InvalidOutDir { - path: fundamentals_dir, - detail: "fundamentals_pit output path exists and is not a directory".to_string(), - }); - } - Ok(_) => true, - Err(err) if err.kind() == io::ErrorKind::NotFound => false, - Err(source) => { - return Err(RunCurateFundamentalsError::InspectOutDir { - path: fundamentals_dir, - source, - }); - } - }; - - let resolved_out = resolve_normalized_path(&args.out_dir); - let resolved_fundamentals = resolve_normalized_path(&fundamentals_dir); - - let resolved_inputs = [ - ( - "qm-financials", - &args.qm_financials, - resolve_normalized_path(&args.qm_financials), - ), - ( - "qm-filings", - &args.qm_filings, - resolve_normalized_path(&args.qm_filings), - ), - ( - "provider-mapping", - &args.provider_mapping, - resolve_normalized_path(&args.provider_mapping), - ), - ( - "listing-venues", - &args.listing_venues, - resolve_normalized_path(&args.listing_venues), - ), - ]; - - for (label, input_path, resolved_in) in &resolved_inputs { - if *resolved_in == resolved_out - || *resolved_in == resolved_fundamentals - || resolved_in.starts_with(&resolved_fundamentals) - { - return Err(RunCurateFundamentalsError::InvalidOutDir { - path: args.out_dir.clone(), - detail: format!( - "output directory would overlap {label} input '{}'", - input_path.display() - ), - }); - } - } - - // Check existing `year=YYYY` partition directories and their `part.parquet` targets for: - // 1. unresolvable / dangling `year=*` symlinks (whose target could be created mid-run and - // silently alias another year's partition), - // 2. two distinct `year=*` entries resolving to the same directory or `part.parquet` file - // (which would cause publishing one year to silently overwrite another year's data), and - // 3. aliases to any input path, catching symlinked year directories whose resolved targets - // live outside `/fundamentals_pit`. - if fundamentals_dir_exists { - let entries = fs::read_dir(&fundamentals_dir).map_err(|source| { - RunCurateFundamentalsError::InspectOutDir { - path: fundamentals_dir.clone(), - source, - } - })?; - let mut year_dirs: Vec = Vec::new(); - for entry_res in entries { - let entry = entry_res.map_err(|source| RunCurateFundamentalsError::InspectOutDir { - path: fundamentals_dir.clone(), - source, - })?; - let name = entry.file_name(); - if name.to_string_lossy().starts_with("year=") { - year_dirs.push(entry.path()); - } - } - year_dirs.sort(); - - let mut seen_year_dirs: BTreeMap = BTreeMap::new(); - let mut seen_part_files: BTreeMap = BTreeMap::new(); - - for year_dir in year_dirs { - let entry_meta = fs::symlink_metadata(&year_dir).map_err(|source| { - RunCurateFundamentalsError::InspectOutDir { - path: year_dir.clone(), - source, - } - })?; - let resolved_year_dir = if entry_meta.file_type().is_symlink() { - fs::canonicalize(&year_dir).map_err(|err| { - RunCurateFundamentalsError::InvalidOutDir { - path: year_dir.clone(), - detail: format!("partition symlink target cannot be resolved: {err}"), - } - })? - } else { - resolve_normalized_path(&year_dir) - }; - let resolved_part_via_dir = resolved_year_dir.join("part.parquet"); - let resolved_part = resolve_normalized_path(&year_dir.join("part.parquet")); - - if let Some(prev_year_dir) = - seen_year_dirs.insert(resolved_year_dir.clone(), year_dir.clone()) - { - return Err(RunCurateFundamentalsError::InvalidOutDir { - path: year_dir, - detail: format!( - "partition directory aliases '{}' via shared target '{}'", - prev_year_dir.display(), - resolved_year_dir.display() - ), - }); - } - - if let Some(prev_year_dir) = - seen_part_files.insert(resolved_part.clone(), year_dir.clone()) - { - return Err(RunCurateFundamentalsError::InvalidOutDir { - path: year_dir, - detail: format!( - "partition file aliases '{}' via shared target '{}'", - prev_year_dir.display(), - resolved_part.display() - ), - }); - } - - for (label, input_path, resolved_in) in &resolved_inputs { - if *resolved_in == resolved_year_dir - || *resolved_in == resolved_part_via_dir - || *resolved_in == resolved_part - || resolved_in.starts_with(&resolved_year_dir) - { - return Err(RunCurateFundamentalsError::InvalidOutDir { - path: year_dir, - detail: format!( - "partition output '{}' would overlap {label} input '{}'", - resolved_part_via_dir.display(), - input_path.display() - ), - }); - } - } - } - } - - Ok(()) -} - -fn financials_bson_error_offset(err: &BsonQmFinancialsError) -> u64 { - match err { - BsonQmFinancialsError::TruncatedDocument { offset, .. } - | BsonQmFinancialsError::CorruptDocumentLength { offset, .. } - | BsonQmFinancialsError::CorruptBson { offset, .. } => *offset, - BsonQmFinancialsError::InvalidFieldNames { .. } - | BsonQmFinancialsError::InvalidFiscalPeriodConfig { .. } => 0, - } -} - -fn filings_bson_error_offset(err: &BsonQmEventsError) -> u64 { - match err { - BsonQmEventsError::TruncatedDocument { offset, .. } - | BsonQmEventsError::CorruptDocumentLength { offset, .. } - | BsonQmEventsError::CorruptBson { offset, .. } => *offset, - BsonQmEventsError::InvalidFieldNames { .. } => 0, - } -} - -fn map_financials_stream_error( - path: &Path, - err: BsonQmFinancialsStreamError, -) -> RunCurateFundamentalsError { - match err { - BsonQmFinancialsStreamError::Stream(source) => RunCurateFundamentalsError::BsonStream { - label: "qm-financials", - path: path.to_path_buf(), - source, - }, - BsonQmFinancialsStreamError::Decode(source) => match &source { - BsonQmFinancialsError::InvalidFieldNames { .. } - | BsonQmFinancialsError::InvalidFiscalPeriodConfig { .. } => { - RunCurateFundamentalsError::InvalidFinancialsConfig { - path: path.to_path_buf(), - source, - } - } - _ => { - let offset = financials_bson_error_offset(&source); - RunCurateFundamentalsError::CorruptFinancialsBson { - path: path.to_path_buf(), - offset, - source, - } - } - }, - } -} - -fn map_filings_stream_error( - path: &Path, - err: BsonQmEventsStreamError, -) -> RunCurateFundamentalsError { - match err { - BsonQmEventsStreamError::Stream(source) => RunCurateFundamentalsError::BsonStream { - label: "qm-filings", - path: path.to_path_buf(), - source, - }, - BsonQmEventsStreamError::Decode(source) => match &source { - BsonQmEventsError::InvalidFieldNames { .. } => { - RunCurateFundamentalsError::InvalidFilingsFieldNames { - path: path.to_path_buf(), - source, - } - } - _ => { - let offset = filings_bson_error_offset(&source); - RunCurateFundamentalsError::CorruptFilingsBson { - path: path.to_path_buf(), - offset, - source, - } - } - }, - } -} - -#[inline] -fn intern_key(interner: &mut HashSet>, key: &str) -> Arc { - if let Some(existing) = interner.get(key) { - Arc::clone(existing) - } else { - let arc: Arc = Arc::from(key); - interner.insert(Arc::clone(&arc)); - arc - } -} - -struct DecodedFundamentalsInputs { - mapping: ProviderMappingTable, - venues: BTreeMap, - observations: Vec>>, - filings: Vec>>, - financials_docs_framed: u64, - financials_bytes_read: u64, - financials_peak_chunk_bytes: usize, - financials_decode: BsonQmFinancialsDecodeStats, - filings_docs_framed: u64, - filings_bytes_read: u64, - filings_peak_chunk_bytes: usize, - filings_decode: BsonQmFilingsDecodeStats, -} - -fn decode_inputs_from_openers( - args: &CurateFundamentalsArgs, - open_financials: FF, - open_filings: FL, -) -> Result -where - RF: io::Read, - FF: FnOnce() -> Result, - RL: io::Read, - FL: FnOnce() -> Result, -{ - let financials_fields = args.financials_field_names(); - financials_fields.validate().map_err(|source| { - RunCurateFundamentalsError::InvalidFinancialsConfig { - path: args.qm_financials.clone(), - source, - } - })?; - - args.fiscal_period - .with_borrowed(|fp| fp.validate()) - .map_err(|source| RunCurateFundamentalsError::InvalidFinancialsConfig { - path: args.qm_financials.clone(), - source, - })?; - - let filings_fields = args.filings_field_names(); - filings_fields.validate().map_err(|source| { - RunCurateFundamentalsError::InvalidFilingsFieldNames { - path: args.qm_filings.clone(), - source, - } - })?; - - if args.mapping_source.trim().is_empty() { - return Err(RunCurateFundamentalsError::EmptyMappingSource); - } - - if args.k == 0 { - return Err(RunCurateFundamentalsError::InvalidPeriodLimit { k: args.k }); - } - - let mapping_rows = load_provider_mapping_tsv(&args.provider_mapping) - .map_err(|err| map_tsv_error(&args.provider_mapping, err))?; - let mapping = ProviderMappingTable::from_rows(mapping_rows).map_err(|source| { - RunCurateFundamentalsError::ProviderMapping { - path: args.provider_mapping.clone(), - source, - } - })?; - - let venues = load_listing_venues_tsv(&args.listing_venues)?; - - let mut key_interner: HashSet> = HashSet::new(); - - // Stream and decode qmFinancials, releasing the chunk reader immediately afterward. - let ( - observations, - financials_docs_framed, - financials_bytes_read, - financials_peak_chunk_bytes, - financials_decode, - ) = { - let financials_stream = open_financials()?; - let mut financials_reader = - RawBsonChunkReader::with_options(financials_stream, BsonStreamOptions::default()) - .map_err(|source| RunCurateFundamentalsError::BsonStream { - label: "qm-financials", - path: args.qm_financials.clone(), - source, - })?; - - let mut observations: Vec>> = Vec::new(); - let decode = args.fiscal_period.with_borrowed(|fp| { - decode_qm_financials_chunks(&mut financials_reader, &financials_fields, fp, |obs| { - let key = intern_key(&mut key_interner, obs.key); - observations.push(FinancialObservation { - key, - period_end: obs.period_end, - fiscal_period: obs.fiscal_period, - currency: obs.currency, - report_date: obs.report_date, - fields: obs.fields, - }); - }) - }) - .map_err(|err| map_financials_stream_error(&args.qm_financials, err))?; - - ( - observations, - financials_reader.docs_framed(), - financials_reader.bytes_read(), - financials_reader.buffer_capacity(), - decode, - ) - }; - - // Stream and decode qmFilings, reusing the same key interner and releasing the chunk reader. - let (filings, filings_docs_framed, filings_bytes_read, filings_peak_chunk_bytes, filings_decode) = { - let filings_stream = open_filings()?; - let mut filings_reader = - RawBsonChunkReader::with_options(filings_stream, BsonStreamOptions::default()) - .map_err(|source| RunCurateFundamentalsError::BsonStream { - label: "qm-filings", - path: args.qm_filings.clone(), - source, - })?; - - let mut filings: Vec>> = Vec::new(); - let decode = decode_qm_filings_chunks(&mut filings_reader, &filings_fields, |raw| { - let key = intern_key(&mut key_interner, raw.key); - filings.push(raw.to_qm_filing(key)); - }) - .map_err(|err| map_filings_stream_error(&args.qm_filings, err))?; - - ( - filings, - filings_reader.docs_framed(), - filings_reader.bytes_read(), - filings_reader.buffer_capacity(), - decode, - ) - }; - - Ok(DecodedFundamentalsInputs { - mapping, - venues, - observations, - filings, - financials_docs_framed, - financials_bytes_read, - financials_peak_chunk_bytes, - financials_decode, - filings_docs_framed, - filings_bytes_read, - filings_peak_chunk_bytes, - filings_decode, - }) -} - -fn run_curate_fundamentals_from_openers( - args: &CurateFundamentalsArgs, - open_financials: FF, - open_filings: FL, -) -> Result -where - RF: io::Read, - FF: FnOnce() -> Result, - RL: io::Read, - FL: FnOnce() -> Result, -{ - let start = Instant::now(); - validate_out_dir_and_inputs(args)?; - - let decoded = decode_inputs_from_openers(args, open_financials, open_filings)?; - - let write_report = curate_and_write_fundamentals( - &args.out_dir, - decoded.observations, - decoded.filings, - &args.mapping_source, - &decoded.mapping, - &decoded.venues, - args.k, - FundamentalsPitWriteOptions::default(), - ) - .map_err(|source| RunCurateFundamentalsError::CurateWrite { - out_dir: args.out_dir.clone(), - source, - })?; - - Ok(CurateFundamentalsRunReport { - financials_docs_framed: decoded.financials_docs_framed, - financials_bytes_read: decoded.financials_bytes_read, - financials_peak_chunk_bytes: decoded.financials_peak_chunk_bytes, - financials_decode: decoded.financials_decode, - filings_docs_framed: decoded.filings_docs_framed, - filings_bytes_read: decoded.filings_bytes_read, - filings_peak_chunk_bytes: decoded.filings_peak_chunk_bytes, - filings_decode: decoded.filings_decode, - curate_stats: write_report.curate_stats, - write_stats: write_report.write_stats, - elapsed_secs: start.elapsed().as_secs_f64(), - }) -} - -/// Runs the end-to-end `curate-fundamentals` file-to-Parquet pipeline via -/// [`curate_and_write_fundamentals`]. -/// -/// Any validation, path-alias, I/O, TSV, mapping, BSON framing/corruption, or curation error -/// returns before touching `args.out_dir`, leaving any pre-existing -/// `/fundamentals_pit/` partitions byte-identical. -pub fn run_curate_fundamentals( - args: &CurateFundamentalsArgs, -) -> Result { - run_curate_fundamentals_from_openers( - args, - || { - File::open(&args.qm_financials).map_err(|source| { - RunCurateFundamentalsError::OpenInput { - label: "qm-financials", - path: args.qm_financials.clone(), - source, - } - }) - }, - || { - File::open(&args.qm_filings).map_err(|source| RunCurateFundamentalsError::OpenInput { - label: "qm-filings", - path: args.qm_filings.clone(), - source, - }) - }, - ) -} - -/// Runs `curate-fundamentals` from arbitrary raw-BSON [`io::Read`] streams while still running -/// full preflight validation (including output/input path safety against the diagnostic paths in -/// `args`) and loading `provider_mapping.tsv` / `listing_venues.tsv` from disk. -pub fn run_curate_fundamentals_with_readers( - args: &CurateFundamentalsArgs, - financials_reader: RF, - filings_reader: RL, -) -> Result { - run_curate_fundamentals_from_openers(args, || Ok(financials_reader), || Ok(filings_reader)) -} - -/// Formats [`CurateFundamentalsRunReport`] into a deterministic machine-readable `key=value` -/// summary. -/// -/// Only the final `timing:` line contains wall-clock time (`elapsed_secs`). -pub fn format_curate_fundamentals_report(report: &CurateFundamentalsRunReport) -> String { - let fin = &report.financials_decode; - let fil = &report.filings_decode; - let b = &report.curate_stats.build; - let c = &report.curate_stats; - let w = &report.write_stats; - - let mut years = String::new(); - for (idx, (year, count)) in w.rows_by_year.iter().enumerate() { - if idx > 0 { - years.push(' '); - } - let _ = write!(years, "{year:04}={count}"); - } - if years.is_empty() { - years.push_str("none"); - } - - format!( - "curate-etl curate-fundamentals\n\ - \x20 financials_bson: docs_framed={} bytes_read={} peak_chunk_bytes={} docs_in={} rows_out={} skipped={} (missing_key={} wrong_key_type={} empty_key={} missing_period_end={} wrong_period_end_type={} invalid_period_end={} period_end_oor={} missing_report_period={} wrong_report_period_type={} unmapped_report_period={} wrong_report_date_type={} invalid_report_date={} report_date_oor={} missing_currency={} wrong_currency_type={} empty_currency={}) nulled=(missing_path={} wrong_type={} unparsable_string={} non_finite={})\n\ - \x20 filings_bson: docs_framed={} bytes_read={} peak_chunk_bytes={} docs_in={} rows_out={} skipped={} (missing_key={} wrong_key_type={} empty_key={} missing_timefiled={} wrong_timefiled_type={} empty_timefiled={} missing_form_type={} wrong_form_type_type={} empty_form_type={}) nulled_wrong_type=(filing_id={} url={})\n\ - \x20 builder: observations_in={} rows_out={} keys_out={} linked={} statutory_lag={} dropped=(unknown_key={} non_finite={} date_oor={} report_date_not_after_period_end={} unanchored_vintage={} stale_estimate={}) dup_collapsed={} dup_conflict={} filings_in={} filings_eligible={} filings_dropped=(unknown_key={} non_periodic={} invalid_ts={} date_oor={} before_period_end={})\n\ - \x20 curate: observations_in={} obs_unmapped={} filings_in={} filings_unmapped={} filings_invalid_ts={} rows_out={} listings_out={}\n\ - \x20 write: files={} row_groups={} rows_written={} bytes_written={}\n\ - \x20 years: {}\n\ - \x20 timing: elapsed_secs={:.6}", - report.financials_docs_framed, - report.financials_bytes_read, - report.financials_peak_chunk_bytes, - fin.docs_in, - fin.rows_out, - fin.skipped_total(), - fin.skipped_missing_key, - fin.skipped_wrong_key_type, - fin.skipped_empty_key, - fin.skipped_missing_period_end, - fin.skipped_wrong_period_end_type, - fin.skipped_invalid_period_end, - fin.skipped_period_end_out_of_range, - fin.skipped_missing_report_period, - fin.skipped_wrong_report_period_type, - fin.skipped_unmapped_report_period, - fin.skipped_wrong_report_date_type, - fin.skipped_invalid_report_date, - fin.skipped_report_date_out_of_range, - fin.skipped_missing_currency, - fin.skipped_wrong_currency_type, - fin.skipped_empty_currency, - fin.nulled_missing_path, - fin.nulled_wrong_type, - fin.nulled_unparsable_string, - fin.nulled_non_finite, - report.filings_docs_framed, - report.filings_bytes_read, - report.filings_peak_chunk_bytes, - fil.docs_in, - fil.rows_out, - fil.skipped_total(), - fil.skipped_missing_key, - fil.skipped_wrong_key_type, - fil.skipped_empty_key, - fil.skipped_missing_timefiled, - fil.skipped_wrong_timefiled_type, - fil.skipped_empty_timefiled, - fil.skipped_missing_form_type, - fil.skipped_wrong_form_type_type, - fil.skipped_empty_form_type, - fil.nulled_wrong_type_filing_id, - fil.nulled_wrong_type_url, - b.observations_in, - b.rows_out, - b.keys_out, - b.rows_linked_to_filing, - b.rows_statutory_lag_estimate, - b.observations_dropped_unknown_key, - b.observations_dropped_non_finite, - b.observations_dropped_date_out_of_range, - b.observations_dropped_report_date_not_after_period_end, - b.observations_dropped_unanchored_vintage, - b.observations_dropped_stale_estimate, - b.duplicate_collapsed, - b.duplicate_conflict_dropped, - b.filings_in, - b.filings_eligible, - b.filings_dropped_unknown_key, - b.filings_ignored_non_periodic, - b.filings_dropped_invalid_timestamp, - b.filings_dropped_date_out_of_range, - b.filings_dropped_before_period_end, - c.observations_in, - c.observations_dropped_unmapped, - c.filings_in, - c.filings_dropped_unmapped, - c.filings_dropped_invalid_timestamp, - c.rows_out, - c.listings_out, - w.files_written, - w.row_groups_written, - w.rows_written, - w.bytes_written, - years, - report.elapsed_secs, - ) -} - -#[cfg(test)] -#[path = "run_curate_fundamentals_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/run_curate_fundamentals_tests.rs b/tools/curate-etl/src/run_curate_fundamentals_tests.rs deleted file mode 100644 index 37afd1bf..00000000 --- a/tools/curate-etl/src/run_curate_fundamentals_tests.rs +++ /dev/null @@ -1,2759 +0,0 @@ -//! End-to-end fixture, PIT restatement, venue-lag, conservation, fail-closed, alias-safety, -//! empty-input, and TSV parser tests for `run_curate_fundamentals`. - -use std::collections::{BTreeMap, HashMap}; -use std::error::Error as _; -use std::fs::{self, File}; -use std::io::{self, Cursor, Read}; -use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; - -use bson::raw::{cstr, RawDocumentBuf}; -use parquet::basic::Compression; -use parquet::column::reader::ColumnReader; -use parquet::file::reader::{FileReader, SerializedFileReader}; - -use super::{ - format_curate_fundamentals_report, load_listing_venues_tsv, run_curate_fundamentals, - run_curate_fundamentals_with_readers, CurateFundamentalsArgs, CurateFundamentalsFiscalPeriod, - CurateFundamentalsRunReport, RunCurateFundamentalsError, DEFAULT_FUNDAMENTALS_MAPPING_SOURCE, -}; -use crate::bson_qm_events::decode_qm_filing_buffer; -use crate::bson_qm_financials::decode_qm_financials_buffer; -use crate::bson_stream::BsonStreamError; -use crate::curate_fundamentals::curate_fundamentals; -use crate::events::{ - partition_year_utc, KNOWN_AT_SOURCE_FILING_TIMESTAMP, KNOWN_AT_SOURCE_STATUTORY_LAG, -}; -use crate::fundamentals::{ - FinancialObservation, FundamentalsFields, FUNDAMENTALS_FALLBACK_HOUR_ET, - FUNDAMENTALS_FALLBACK_MINUTE_ET, STATUTORY_LAG_TSXV_CSE_ANNUAL_DAYS, - STATUTORY_LAG_TSXV_CSE_QUARTERLY_DAYS, STATUTORY_LAG_US_TSX_ANNUAL_DAYS, - STATUTORY_LAG_US_TSX_QUARTERLY_DAYS, -}; -use crate::parquet_fundamentals::FundamentalsPitParquetRow; -use crate::provider_mapping::{ProviderMappingError, ProviderMappingTable}; -use crate::run_curate_bars::load_provider_mapping_tsv; -use crate::shorts::et_to_utc_micros; -use crate::split::ymd_to_epoch_days; - -static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0); - -struct TempDirGuard { - path: PathBuf, -} - -impl TempDirGuard { - fn new(label: &str) -> Self { - let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); - let pid = std::process::id(); - let path = std::env::temp_dir().join(format!( - "curate-etl-run-curate-fundamentals-{label}-{pid}-{seq}" - )); - let _ = fs::remove_dir_all(&path); - fs::create_dir_all(&path).expect("create test temp dir"); - Self { path } - } - - fn path(&self) -> &Path { - &self.path - } -} - -impl Drop for TempDirGuard { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.path); - } -} - -#[derive(Debug, Clone, PartialEq, Eq)] -enum TreeEntry { - Dir, - File(Vec), - Symlink(PathBuf), -} - -fn snapshot_tree(root: &Path) -> BTreeMap { - let mut out = BTreeMap::new(); - if !root.exists() && fs::symlink_metadata(root).is_err() { - return out; - } - fn walk(base: &Path, cur: &Path, out: &mut BTreeMap) { - let meta = fs::symlink_metadata(cur).expect("symlink_metadata"); - let rel = cur.strip_prefix(base).unwrap_or(cur).to_path_buf(); - if meta.file_type().is_symlink() { - let target = fs::read_link(cur).expect("read_link"); - out.insert(rel, TreeEntry::Symlink(target)); - } else if meta.is_dir() { - out.insert(rel, TreeEntry::Dir); - let mut children: Vec = fs::read_dir(cur) - .expect("read_dir") - .map(|e| e.expect("dir entry").path()) - .collect(); - children.sort(); - for child in children { - walk(base, &child, out); - } - } else { - let bytes = fs::read(cur).expect("read file"); - out.insert(rel, TreeEntry::File(bytes)); - } - } - walk(root, root, &mut out); - out -} - -fn day(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).expect("valid test date") -} - -fn make_financials_doc( - key: Option<&str>, - period_end: &str, - report_date: Option<&str>, - report_period: &str, - currency: &str, - fields: FundamentalsFields, -) -> Vec { - let mut doc = RawDocumentBuf::new(); - if let Some(k) = key { - doc.append(cstr!("qmSearchCode"), k); - } - doc.append(cstr!("periodEndDate"), period_end); - if let Some(rd) = report_date { - doc.append(cstr!("reportDate"), rd); - } - doc.append(cstr!("reportPeriod"), report_period); - doc.append(cstr!("currency"), currency); - - let mut income = RawDocumentBuf::new(); - if let Some(v) = fields.revenue { - income.append(cstr!("revenue"), v); - } - if let Some(v) = fields.net_income { - income.append(cstr!("netIncome"), v); - } - doc.append(cstr!("IncomeStatement"), income); - - let mut cashflow = RawDocumentBuf::new(); - if let Some(v) = fields.operating_cash_flow { - cashflow.append(cstr!("operatingCashFlow"), v); - } - doc.append(cstr!("CashFlow"), cashflow); - - let mut balance = RawDocumentBuf::new(); - if let Some(v) = fields.total_assets { - balance.append(cstr!("totalAssets"), v); - } - if let Some(v) = fields.total_equity { - balance.append(cstr!("totalEquity"), v); - } - if let Some(v) = fields.shares_outstanding { - balance.append(cstr!("sharesOutstanding"), v); - } - doc.append(cstr!("BalanceSheet"), balance); - - doc.into_bytes() -} - -fn make_filing_doc( - key: Option<&str>, - timefiled: &str, - form_type: &str, - filing_id: Option<&str>, - url: Option<&str>, -) -> Vec { - let mut doc = RawDocumentBuf::new(); - if let Some(k) = key { - doc.append(cstr!("symbol"), k); - } - doc.append(cstr!("timefiled"), timefiled); - doc.append(cstr!("formType"), form_type); - if let Some(id) = filing_id { - doc.append(cstr!("filingId"), id); - } - if let Some(u) = url { - doc.append(cstr!("url"), u); - } - doc.into_bytes() -} - -fn default_test_args( - qm_financials: PathBuf, - qm_filings: PathBuf, - provider_mapping: PathBuf, - listing_venues: PathBuf, - out_dir: PathBuf, -) -> CurateFundamentalsArgs { - let mut args = CurateFundamentalsArgs::with_verified_defaults( - qm_financials, - qm_filings, - provider_mapping, - listing_venues, - out_dir, - "currency", - Some("IncomeStatement.revenue".to_string()), - Some("IncomeStatement.netIncome".to_string()), - Some("CashFlow.operatingCashFlow".to_string()), - Some("BalanceSheet.totalAssets".to_string()), - Some("BalanceSheet.totalEquity".to_string()), - Some("BalanceSheet.sharesOutstanding".to_string()), - CurateFundamentalsFiscalPeriod::ByTokens { - quarterly: vec![ - "Q1".to_string(), - "Q2".to_string(), - "Q3".to_string(), - "Q4".to_string(), - ], - annual: vec!["FY".to_string()], - }, - "formType", - 4, - ); - args.filings_filing_id_field = Some("filingId".to_string()); - args.filings_url_field = Some("url".to_string()); - args -} - -#[derive(Debug, Clone, PartialEq)] -struct DecodedParquetRow { - listing_id: i32, - effective_known_at: i64, - known_at_source: String, - has_estimated_lag: bool, - period_end: i32, - fiscal_period: String, - currency: String, - period_known_at: i64, - revenue: Option, - net_income: Option, - operating_cash_flow: Option, - total_assets: Option, - total_equity: Option, - shares_outstanding: Option, - ttm_period_end: Option, - ttm_currency: Option, - ttm_revenue: Option, - ttm_net_income: Option, - ttm_operating_cash_flow: Option, - ttm_has_estimated_lag: Option, -} - -fn from_stage_row(row: &FundamentalsPitParquetRow) -> DecodedParquetRow { - let lp = row.latest_period().expect("latest_period"); - DecodedParquetRow { - listing_id: row.listing_id, - effective_known_at: row.effective_known_at_micros, - known_at_source: row.known_at_source.as_ref().to_string(), - has_estimated_lag: row.has_estimated_lag, - period_end: lp.period_end, - fiscal_period: lp.fiscal_period.as_ref().to_string(), - currency: lp.currency.clone(), - period_known_at: lp.period_known_at_micros, - revenue: lp.fields.revenue, - net_income: lp.fields.net_income, - operating_cash_flow: lp.fields.operating_cash_flow, - total_assets: lp.fields.total_assets, - total_equity: lp.fields.total_equity, - shares_outstanding: lp.fields.shares_outstanding, - ttm_period_end: row.ttm.as_ref().map(|t| t.ending_period_end), - ttm_currency: row.ttm.as_ref().map(|t| t.currency.clone()), - ttm_revenue: row.ttm.as_ref().and_then(|t| t.flows.revenue), - ttm_net_income: row.ttm.as_ref().and_then(|t| t.flows.net_income), - ttm_operating_cash_flow: row.ttm.as_ref().and_then(|t| t.flows.operating_cash_flow), - ttm_has_estimated_lag: row.ttm.as_ref().map(|t| t.has_estimated_lag), - } -} - -fn read_parquet_rows_by_name(path: &Path) -> Vec { - let file = File::open(path).expect("open parquet file"); - let reader = SerializedFileReader::new(file).expect("open parquet reader"); - let meta = reader.metadata(); - let schema_descr = meta.file_metadata().schema_descr(); - - let mut col_idx_by_name: HashMap<&str, usize> = HashMap::new(); - for (idx, col) in schema_descr.columns().iter().enumerate() { - col_idx_by_name.insert(col.name(), idx); - } - let col_idx = |name: &str| -> usize { - *col_idx_by_name - .get(name) - .unwrap_or_else(|| panic!("missing expected Parquet column '{name}'")) - }; - - let mut out = Vec::new(); - for rg_idx in 0..meta.num_row_groups() { - let rg_meta = meta.row_group(rg_idx); - for c in 0..rg_meta.num_columns() { - assert_eq!( - rg_meta.column(c).compression(), - Compression::ZSTD(Default::default()), - "expected Zstd compression on column {c}" - ); - } - - let rg_rows = rg_meta.num_rows() as usize; - let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); - - let read_req_i32 = |name: &str| -> Vec { - let mut vals = Vec::with_capacity(rg_rows); - match rg_reader.get_column_reader(col_idx(name)).unwrap() { - ColumnReader::Int32ColumnReader(mut typed) => { - let mut read = 0usize; - while read < rg_rows { - let (n, _, _) = typed - .read_records(rg_rows - read, None, None, &mut vals) - .unwrap(); - assert!(n > 0); - read += n; - } - } - _ => panic!("expected INT32 for '{name}'"), - } - vals - }; - - let read_opt_i32 = |name: &str| -> Vec> { - let mut vals = Vec::with_capacity(rg_rows); - let mut defs = Vec::with_capacity(rg_rows); - match rg_reader.get_column_reader(col_idx(name)).unwrap() { - ColumnReader::Int32ColumnReader(mut typed) => { - let mut read = 0usize; - while read < rg_rows { - let (n, _, _) = typed - .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) - .unwrap(); - assert!(n > 0); - read += n; - } - } - _ => panic!("expected INT32 for '{name}'"), - } - let mut vi = 0usize; - defs.into_iter() - .map(|d| { - if d == 1 { - let v = vals[vi]; - vi += 1; - Some(v) - } else { - assert_eq!(d, 0); - None - } - }) - .collect() - }; - - let read_req_i64 = |name: &str| -> Vec { - let mut vals = Vec::with_capacity(rg_rows); - match rg_reader.get_column_reader(col_idx(name)).unwrap() { - ColumnReader::Int64ColumnReader(mut typed) => { - let mut read = 0usize; - while read < rg_rows { - let (n, _, _) = typed - .read_records(rg_rows - read, None, None, &mut vals) - .unwrap(); - assert!(n > 0); - read += n; - } - } - _ => panic!("expected INT64 for '{name}'"), - } - vals - }; - - let read_req_bool = |name: &str| -> Vec { - let mut vals = Vec::with_capacity(rg_rows); - match rg_reader.get_column_reader(col_idx(name)).unwrap() { - ColumnReader::BoolColumnReader(mut typed) => { - let mut read = 0usize; - while read < rg_rows { - let (n, _, _) = typed - .read_records(rg_rows - read, None, None, &mut vals) - .unwrap(); - assert!(n > 0); - read += n; - } - } - _ => panic!("expected BOOLEAN for '{name}'"), - } - vals - }; - - let read_opt_bool = |name: &str| -> Vec> { - let mut vals = Vec::with_capacity(rg_rows); - let mut defs = Vec::with_capacity(rg_rows); - match rg_reader.get_column_reader(col_idx(name)).unwrap() { - ColumnReader::BoolColumnReader(mut typed) => { - let mut read = 0usize; - while read < rg_rows { - let (n, _, _) = typed - .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) - .unwrap(); - assert!(n > 0); - read += n; - } - } - _ => panic!("expected BOOLEAN for '{name}'"), - } - let mut vi = 0usize; - defs.into_iter() - .map(|d| { - if d == 1 { - let v = vals[vi]; - vi += 1; - Some(v) - } else { - assert_eq!(d, 0); - None - } - }) - .collect() - }; - - let read_opt_f64 = |name: &str| -> Vec> { - let mut vals = Vec::with_capacity(rg_rows); - let mut defs = Vec::with_capacity(rg_rows); - match rg_reader.get_column_reader(col_idx(name)).unwrap() { - ColumnReader::DoubleColumnReader(mut typed) => { - let mut read = 0usize; - while read < rg_rows { - let (n, _, _) = typed - .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) - .unwrap(); - assert!(n > 0); - read += n; - } - } - _ => panic!("expected DOUBLE for '{name}'"), - } - let mut vi = 0usize; - defs.into_iter() - .map(|d| { - if d == 1 { - let v = vals[vi]; - vi += 1; - Some(v) - } else { - assert_eq!(d, 0); - None - } - }) - .collect() - }; - - let read_req_str = |name: &str| -> Vec { - let mut vals = Vec::with_capacity(rg_rows); - match rg_reader.get_column_reader(col_idx(name)).unwrap() { - ColumnReader::ByteArrayColumnReader(mut typed) => { - let mut read = 0usize; - while read < rg_rows { - let (n, _, _) = typed - .read_records(rg_rows - read, None, None, &mut vals) - .unwrap(); - assert!(n > 0); - read += n; - } - } - _ => panic!("expected BYTE_ARRAY for '{name}'"), - } - vals.into_iter() - .map(|ba| String::from_utf8(ba.data().to_vec()).unwrap()) - .collect() - }; - - let read_opt_str = |name: &str| -> Vec> { - let mut vals = Vec::with_capacity(rg_rows); - let mut defs = Vec::with_capacity(rg_rows); - match rg_reader.get_column_reader(col_idx(name)).unwrap() { - ColumnReader::ByteArrayColumnReader(mut typed) => { - let mut read = 0usize; - while read < rg_rows { - let (n, _, _) = typed - .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) - .unwrap(); - assert!(n > 0); - read += n; - } - } - _ => panic!("expected BYTE_ARRAY for '{name}'"), - } - let mut vi = 0usize; - defs.into_iter() - .map(|d| { - if d == 1 { - let v = String::from_utf8(vals[vi].data().to_vec()).unwrap(); - vi += 1; - Some(v) - } else { - assert_eq!(d, 0); - None - } - }) - .collect() - }; - - let listing_id = read_req_i32("listing_id"); - let effective_known_at = read_req_i64("effective_known_at"); - let known_at_source = read_req_str("known_at_source"); - let has_estimated_lag = read_req_bool("has_estimated_lag"); - let period_end = read_req_i32("period_end"); - let fiscal_period = read_req_str("fiscal_period"); - let currency = read_req_str("currency"); - let period_known_at = read_req_i64("period_known_at"); - let revenue = read_opt_f64("revenue"); - let net_income = read_opt_f64("net_income"); - let operating_cash_flow = read_opt_f64("operating_cash_flow"); - let total_assets = read_opt_f64("total_assets"); - let total_equity = read_opt_f64("total_equity"); - let shares_outstanding = read_opt_f64("shares_outstanding"); - let ttm_period_end = read_opt_i32("ttm_period_end"); - let ttm_currency = read_opt_str("ttm_currency"); - let ttm_revenue = read_opt_f64("ttm_revenue"); - let ttm_net_income = read_opt_f64("ttm_net_income"); - let ttm_operating_cash_flow = read_opt_f64("ttm_operating_cash_flow"); - let ttm_has_estimated_lag = read_opt_bool("ttm_has_estimated_lag"); - - for i in 0..rg_rows { - out.push(DecodedParquetRow { - listing_id: listing_id[i], - effective_known_at: effective_known_at[i], - known_at_source: known_at_source[i].clone(), - has_estimated_lag: has_estimated_lag[i], - period_end: period_end[i], - fiscal_period: fiscal_period[i].clone(), - currency: currency[i].clone(), - period_known_at: period_known_at[i], - revenue: revenue[i], - net_income: net_income[i], - operating_cash_flow: operating_cash_flow[i], - total_assets: total_assets[i], - total_equity: total_equity[i], - shares_outstanding: shares_outstanding[i], - ttm_period_end: ttm_period_end[i], - ttm_currency: ttm_currency[i].clone(), - ttm_revenue: ttm_revenue[i], - ttm_net_income: ttm_net_income[i], - ttm_operating_cash_flow: ttm_operating_cash_flow[i], - ttm_has_estimated_lag: ttm_has_estimated_lag[i], - }); - } - } - out -} - -fn read_dataset_by_year(out_dir: &Path) -> BTreeMap> { - let dataset_dir = out_dir.join("fundamentals_pit"); - let mut by_year = BTreeMap::new(); - if !dataset_dir.exists() { - return by_year; - } - for entry in fs::read_dir(&dataset_dir).expect("read dataset dir") { - let entry = entry.expect("dir entry"); - let name = entry.file_name().to_string_lossy().to_string(); - if let Some(year_str) = name.strip_prefix("year=") { - let year: i32 = year_str.parse().expect("valid year dir"); - let part = entry.path().join("part.parquet"); - assert!(part.is_file(), "expected part.parquet in {}", entry.path().display()); - by_year.insert(year, read_parquet_rows_by_name(&part)); - } - } - by_year -} - -fn assert_single_line(msg: &str) { - assert!( - !msg.contains('\n') && !msg.contains('\r'), - "error Display must be single-line, got: {msg:?}" - ); -} - -fn assert_reports_eq_ignoring_timing( - a: &CurateFundamentalsRunReport, - b: &CurateFundamentalsRunReport, -) { - assert_eq!(a.financials_docs_framed, b.financials_docs_framed); - assert_eq!(a.financials_bytes_read, b.financials_bytes_read); - assert_eq!(a.financials_peak_chunk_bytes, b.financials_peak_chunk_bytes); - assert_eq!(a.financials_decode, b.financials_decode); - assert_eq!(a.filings_docs_framed, b.filings_docs_framed); - assert_eq!(a.filings_bytes_read, b.filings_bytes_read); - assert_eq!(a.filings_peak_chunk_bytes, b.filings_peak_chunk_bytes); - assert_eq!(a.filings_decode, b.filings_decode); - assert_eq!(a.curate_stats, b.curate_stats); - assert_eq!(a.write_stats, b.write_stats); -} - -fn assert_conservation(report: &CurateFundamentalsRunReport) { - assert_eq!( - report.financials_docs_framed as usize, - report.financials_decode.docs_in - ); - assert_eq!( - report.financials_decode.docs_in, - report.financials_decode.rows_out + report.financials_decode.skipped_total() - ); - assert_eq!( - report.filings_docs_framed as usize, - report.filings_decode.docs_in - ); - assert_eq!( - report.filings_decode.docs_in, - report.filings_decode.rows_out + report.filings_decode.skipped_total() - ); - assert_eq!( - report.financials_decode.rows_out, - report.curate_stats.observations_in - ); - assert_eq!( - report.filings_decode.rows_out, - report.curate_stats.filings_in - ); - assert_eq!( - report.write_stats.rows_written, - report.curate_stats.rows_out - ); -} - -#[test] -fn fundamentals_two_listing_parquet_matches_stage() { - let tmp = TempDirGuard::new("two-listing"); - let fin_path = tmp.path().join("qmFinancials.bson"); - let fil_path = tmp.path().join("qmFilings.bson"); - let map_path = tmp.path().join("provider_mapping.tsv"); - let venues_path = tmp.path().join("listing_venues.tsv"); - let out_file_api = tmp.path().join("out_file"); - let out_reader_api = tmp.path().join("out_reader"); - - // 2 listings: 101 (NVDA, us_tsx, USD) with 4 consecutive quarters spanning 2023-2024 so TTM - // is populated, plus 202 (MINE:V, tsxv_cse, CAD) with a nullable stock metric and unlinked FY. - fs::write( - &map_path, - "qm\tNVDA\t2020-01-01\t\t101\nqm\tMINE:V\t2020-01-01\t\t202\n", - ) - .unwrap(); - // Include both LF and CRLF line endings in the valid venue fixture. - fs::write(&venues_path, "101\tus_tsx\r\n202\ttsxv_cse\n").unwrap(); - - let mut fin_bytes = Vec::new(); - // 4 consecutive quarters for NVDA (Q1 2023 .. Q4 2023), filed across 2023 and 2024. - fin_bytes.extend_from_slice(&make_financials_doc( - Some("NVDA"), - "2023-03-31", - Some("2023-05-02"), - "Q1", - "USD", - FundamentalsFields { - revenue: Some(100.0), - net_income: Some(20.0), - operating_cash_flow: Some(25.0), - total_assets: Some(1000.0), - total_equity: Some(600.0), - shares_outstanding: Some(50.0), - }, - )); - fin_bytes.extend_from_slice(&make_financials_doc( - Some("NVDA"), - "2023-06-30", - Some("2023-08-03"), - "Q2", - "USD", - FundamentalsFields { - revenue: Some(110.0), - net_income: Some(22.0), - operating_cash_flow: Some(28.0), - total_assets: Some(1050.0), - total_equity: Some(620.0), - shares_outstanding: Some(50.0), - }, - )); - fin_bytes.extend_from_slice(&make_financials_doc( - Some("NVDA"), - "2023-09-30", - Some("2023-11-04"), - "Q3", - "USD", - FundamentalsFields { - revenue: Some(120.0), - net_income: Some(24.0), - operating_cash_flow: Some(30.0), - total_assets: Some(1100.0), - total_equity: Some(640.0), - shares_outstanding: Some(51.0), - }, - )); - fin_bytes.extend_from_slice(&make_financials_doc( - Some("NVDA"), - "2023-12-31", - Some("2024-02-10"), - "Q4", - "USD", - FundamentalsFields { - revenue: Some(130.0), - net_income: Some(26.0), - operating_cash_flow: Some(32.0), - total_assets: Some(1150.0), - total_equity: Some(660.0), - shares_outstanding: Some(51.0), - }, - )); - // Listing 202 (MINE:V): Q1 2024 linked to SEDAR interim filing, with nullable total_equity. - fin_bytes.extend_from_slice(&make_financials_doc( - Some("MINE:V"), - "2024-03-31", - Some("2024-05-20"), - "Q1", - "CAD", - FundamentalsFields { - revenue: Some(5.5), - net_income: Some(-1.2), - operating_cash_flow: None, - total_assets: Some(40.0), - total_equity: None, - shares_outstanding: Some(120.0), - }, - )); - fs::write(&fin_path, &fin_bytes).unwrap(); - - let mut fil_bytes = Vec::new(); - fil_bytes.extend_from_slice(&make_filing_doc( - Some("NVDA"), - "2023-05-02T16:15:00 EDT", - "10-Q", - Some("f-q1"), - Some("https://example.test/q1"), - )); - fil_bytes.extend_from_slice(&make_filing_doc( - Some("NVDA"), - "2023-08-03T16:20:00 EDT", - "10-Q", - Some("f-q2"), - None, - )); - fil_bytes.extend_from_slice(&make_filing_doc( - Some("NVDA"), - "2023-11-04T16:30:00 EDT", - "10-Q", - Some("f-q3"), - None, - )); - fil_bytes.extend_from_slice(&make_filing_doc( - Some("NVDA"), - "2024-02-10T16:05:00 EST", - "10-Q", - Some("f-q4"), - None, - )); - fil_bytes.extend_from_slice(&make_filing_doc( - Some("MINE:V"), - "2024-05-20T09:00:00 EDT", - "Interim financial statements/report - English", - Some("f-mine-q1"), - None, - )); - fs::write(&fil_path, &fil_bytes).unwrap(); - - // Run via public file API. - let file_args = default_test_args( - fin_path.clone(), - fil_path.clone(), - map_path.clone(), - venues_path.clone(), - out_file_api.clone(), - ); - let file_report = run_curate_fundamentals(&file_args).expect("file API run"); - assert_conservation(&file_report); - assert_eq!(file_report.curate_stats.listings_out, 2); - assert_eq!(file_report.write_stats.rows_written, 5); - - // Build expected rows directly via curate_fundamentals on the same decoded inputs. - let mut direct_obs = Vec::new(); - file_args.fiscal_period.with_borrowed(|fp| { - decode_qm_financials_buffer(&fin_bytes, &file_args.financials_field_names(), fp, |o| { - direct_obs.push(FinancialObservation { - key: o.key.to_owned(), - period_end: o.period_end, - fiscal_period: o.fiscal_period, - currency: o.currency, - report_date: o.report_date, - fields: o.fields, - }); - }) - .unwrap(); - }); - let mut direct_filings = Vec::new(); - decode_qm_filing_buffer(&fil_bytes, &file_args.filings_field_names(), |raw| { - direct_filings.push(raw.to_qm_filing(raw.key.to_owned())); - }) - .unwrap(); - let mapping = ProviderMappingTable::from_rows(load_provider_mapping_tsv(&map_path).unwrap()) - .unwrap(); - let venues = load_listing_venues_tsv(&venues_path).unwrap(); - let stage_out = curate_fundamentals( - direct_obs, - direct_filings, - DEFAULT_FUNDAMENTALS_MAPPING_SOURCE, - &mapping, - &venues, - file_args.k, - ) - .unwrap(); - - let mut expected_by_year: BTreeMap> = BTreeMap::new(); - for row in &stage_out.rows { - let year = partition_year_utc(row.effective_known_at_micros); - expected_by_year - .entry(year) - .or_default() - .push(from_stage_row(row)); - } - - let got_by_year = read_dataset_by_year(&out_file_api); - assert_eq!(got_by_year.keys().copied().collect::>(), vec![2023, 2024]); - assert_eq!(got_by_year, expected_by_year); - - // Verify 4-quarter TTM is populated on the 2024 NVDA Q4 row and nulls are preserved on MINE:V. - let rows_2024 = &got_by_year[&2024]; - let nvda_q4 = rows_2024 - .iter() - .find(|r| r.listing_id == 101) - .expect("NVDA 2024 row"); - assert_eq!(nvda_q4.currency, "USD"); - assert_eq!(nvda_q4.ttm_period_end, Some(day(2023, 12, 31))); - assert_eq!(nvda_q4.ttm_currency.as_deref(), Some("USD")); - assert_eq!(nvda_q4.ttm_revenue, Some(460.0)); - assert_eq!(nvda_q4.ttm_net_income, Some(92.0)); - assert_eq!(nvda_q4.ttm_operating_cash_flow, Some(115.0)); - assert_eq!(nvda_q4.ttm_has_estimated_lag, Some(false)); - assert_eq!(nvda_q4.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); - - let mine_q1 = rows_2024 - .iter() - .find(|r| r.listing_id == 202) - .expect("MINE:V 2024 row"); - assert_eq!(mine_q1.currency, "CAD"); - assert_eq!(mine_q1.operating_cash_flow, None); - assert_eq!(mine_q1.total_equity, None); - assert_eq!(mine_q1.ttm_period_end, None); - - // Run the exact same pinned fixture through the injected-reader entry point. - let reader_args = default_test_args( - fin_path, - fil_path, - map_path, - venues_path, - out_reader_api.clone(), - ); - let reader_report = run_curate_fundamentals_with_readers( - &reader_args, - Cursor::new(fin_bytes.as_slice()), - Cursor::new(fil_bytes.as_slice()), - ) - .expect("reader API run"); - assert_reports_eq_ignoring_timing(&file_report, &reader_report); - assert_eq!(read_dataset_by_year(&out_reader_api), got_by_year); -} - -#[test] -fn fundamentals_late_q1_restatement_preserves_q2() { - let tmp = TempDirGuard::new("restatement"); - let map_path = tmp.path().join("provider_mapping.tsv"); - let venues_path = tmp.path().join("listing_venues.tsv"); - fs::write(&map_path, "qm\tACME\t2020-01-01\t\t301\n").unwrap(); - fs::write(&venues_path, "301\tus_tsx\n").unwrap(); - - // Four contiguous quarters ending in Q2 2024 so Q2 and the late Q1 amendment both carry - // a 4-quarter TTM sum; the Q1 revenue revision (-12.0) must show up in TTM revenue first - // at the amendment timestamp while leaving all earlier rows and Q2's latest fields intact. - let q3_2023 = make_financials_doc( - Some("ACME"), - "2023-09-30", - Some("2023-11-05"), - "Q3", - "USD", - FundamentalsFields { - revenue: Some(90.0), - net_income: Some(8.0), - operating_cash_flow: Some(10.0), - total_assets: Some(460.0), - total_equity: Some(275.0), - shares_outstanding: Some(20.0), - }, - ); - let q4_2023 = make_financials_doc( - Some("ACME"), - "2023-12-31", - Some("2024-02-20"), - "Q4", - "USD", - FundamentalsFields { - revenue: Some(110.0), - net_income: Some(11.0), - operating_cash_flow: Some(14.0), - total_assets: Some(480.0), - total_equity: Some(288.0), - shares_outstanding: Some(20.0), - }, - ); - let q1_orig = make_financials_doc( - Some("ACME"), - "2024-03-31", - Some("2024-05-05"), - "Q1", - "USD", - FundamentalsFields { - revenue: Some(100.0), - net_income: Some(10.0), - operating_cash_flow: Some(12.0), - total_assets: Some(500.0), - total_equity: Some(300.0), - shares_outstanding: Some(20.0), - }, - ); - let q2_orig = make_financials_doc( - Some("ACME"), - "2024-06-30", - Some("2024-08-05"), - "Q2", - "USD", - FundamentalsFields { - revenue: Some(250.0), - net_income: Some(30.0), - operating_cash_flow: Some(35.0), - total_assets: Some(550.0), - total_equity: Some(330.0), - shares_outstanding: Some(20.0), - }, - ); - let q1_restated = make_financials_doc( - Some("ACME"), - "2024-03-31", - Some("2024-09-15"), - "Q1", - "USD", - FundamentalsFields { - revenue: Some(88.0), - net_income: Some(4.0), - operating_cash_flow: Some(9.0), - total_assets: Some(490.0), - total_equity: Some(294.0), - shares_outstanding: Some(20.0), - }, - ); - - let f_q3_2023 = make_filing_doc( - Some("ACME"), - "2023-11-05T16:10:00 EST", - "10-Q", - Some("q3-2023-1"), - None, - ); - let f_q4_2023 = make_filing_doc( - Some("ACME"), - "2024-02-20T16:10:00 EST", - "10-Q", - Some("q4-2023-1"), - None, - ); - let f_q1 = make_filing_doc( - Some("ACME"), - "2024-05-05T16:10:00 EDT", - "10-Q", - Some("q1-1"), - None, - ); - let f_q2 = make_filing_doc( - Some("ACME"), - "2024-08-05T16:15:00 EDT", - "10-Q", - Some("q2-1"), - None, - ); - let f_q1_amend = make_filing_doc( - Some("ACME"), - "2024-09-15T17:00:00 EDT", - "10-Q/A", - Some("q1-2"), - None, - ); - - // Run 1: Q3 2023 + Q4 2023 + Q1 2024 + Q2 2024 only. - let fin_before = tmp.path().join("fin_before.bson"); - let fil_before = tmp.path().join("fil_before.bson"); - let out_before = tmp.path().join("out_before"); - fs::write( - &fin_before, - [&q3_2023[..], &q4_2023[..], &q1_orig[..], &q2_orig[..]].concat(), - ) - .unwrap(); - fs::write( - &fil_before, - [&f_q3_2023[..], &f_q4_2023[..], &f_q1[..], &f_q2[..]].concat(), - ) - .unwrap(); - let args_before = default_test_args( - fin_before, - fil_before, - map_path.clone(), - venues_path.clone(), - out_before.clone(), - ); - let rep_before = run_curate_fundamentals(&args_before).unwrap(); - assert_eq!(rep_before.write_stats.rows_written, 4); - let by_year_before = read_dataset_by_year(&out_before); - let rows_2023_before = by_year_before.get(&2023).expect("2023 partition"); - let rows_2024_before = by_year_before.get(&2024).expect("2024 partition"); - assert_eq!(rows_2023_before.len(), 1); - assert_eq!(rows_2024_before.len(), 3); - - // Run 2: same four quarters + late Q1 2024 restatement (known_at > Q2's known_at). - let fin_after = tmp.path().join("fin_after.bson"); - let fil_after = tmp.path().join("fil_after.bson"); - let out_after = tmp.path().join("out_after"); - fs::write( - &fin_after, - [ - &q3_2023[..], - &q4_2023[..], - &q1_orig[..], - &q2_orig[..], - &q1_restated[..], - ] - .concat(), - ) - .unwrap(); - fs::write( - &fil_after, - [ - &f_q3_2023[..], - &f_q4_2023[..], - &f_q1[..], - &f_q2[..], - &f_q1_amend[..], - ] - .concat(), - ) - .unwrap(); - let args_after = default_test_args( - fin_after, - fil_after, - map_path, - venues_path, - out_after.clone(), - ); - let rep_after = run_curate_fundamentals(&args_after).unwrap(); - assert_eq!(rep_after.write_stats.rows_written, 5); - let by_year_after = read_dataset_by_year(&out_after); - let rows_2023_after = by_year_after.get(&2023).expect("2023 partition"); - let rows_2024_after = by_year_after.get(&2024).expect("2024 partition"); - assert_eq!(rows_2023_after.len(), 1); - assert_eq!(rows_2024_after.len(), 4); - - // Entire pre-amendment prefix across both years is byte/value-identical (zero leakage). - assert_eq!(rows_2023_after, rows_2023_before); - assert_eq!(&rows_2024_after[..3], &rows_2024_before[..]); - - // Fourth 2024 snapshot is at the amendment's UTC known_at (2024-09-15 17:00 EDT = 21:00 UTC), - // Q2 remains the latest period (period_end, values, and period_known_at unchanged), and - // 4-quarter TTM revenue changes first at this snapshot by exactly the Q1 revision (-12.0). - let q2_row = &rows_2024_before[2]; - let amend_row = &rows_2024_after[3]; - let expected_amend_utc = et_to_utc_micros(day(2024, 9, 15), 17, 0, 0).unwrap(); - assert_eq!(amend_row.effective_known_at, expected_amend_utc); - assert!(amend_row.effective_known_at > q2_row.effective_known_at); - assert_eq!(amend_row.period_end, day(2024, 6, 30)); - assert_eq!(amend_row.period_end, q2_row.period_end); - assert_eq!(amend_row.period_known_at, q2_row.period_known_at); - assert_eq!(amend_row.revenue, q2_row.revenue); - assert_eq!(amend_row.net_income, q2_row.net_income); - assert_eq!(amend_row.operating_cash_flow, q2_row.operating_cash_flow); - assert_eq!(amend_row.total_assets, q2_row.total_assets); - assert_eq!(amend_row.total_equity, q2_row.total_equity); - assert_eq!(amend_row.shares_outstanding, q2_row.shares_outstanding); - - // TTM assertions: 90 + 110 + 100 + 250 = 550 before amendment; 90 + 110 + 88 + 250 = 538 after. - assert_eq!(q2_row.ttm_period_end, Some(day(2024, 6, 30))); - assert_eq!(amend_row.ttm_period_end, Some(day(2024, 6, 30))); - assert_eq!(q2_row.ttm_revenue, Some(550.0)); - assert_eq!(amend_row.ttm_revenue, Some(538.0)); - assert_eq!( - amend_row.ttm_revenue.unwrap() - q2_row.ttm_revenue.unwrap(), - 88.0 - 100.0 - ); - assert_eq!(q2_row.ttm_net_income, Some(59.0)); - assert_eq!(amend_row.ttm_net_income, Some(53.0)); - assert_eq!(q2_row.ttm_operating_cash_flow, Some(71.0)); - assert_eq!(amend_row.ttm_operating_cash_flow, Some(68.0)); -} - -#[test] -fn fundamentals_unlinked_uses_venue_lag() { - let tmp = TempDirGuard::new("venue-lag"); - let fin_path = tmp.path().join("qmFinancials.bson"); - let fil_path = tmp.path().join("qmFilings.bson"); - let map_path = tmp.path().join("provider_mapping.tsv"); - let venues_path = tmp.path().join("listing_venues.tsv"); - let out_dir = tmp.path().join("out"); - - fs::write( - &map_path, - "qm\tUSCO\t2020-01-01\t\t10\nqm\tVNCO:V\t2020-01-01\t\t20\n", - ) - .unwrap(); - fs::write(&venues_path, "10\tus_tsx\n20\ttsxv_cse\n").unwrap(); - - let q_end = day(2024, 3, 31); - let fy_end = day(2024, 12, 31); - let mut fin_bytes = Vec::new(); - for (sym, ccy) in [("USCO", "USD"), ("VNCO:V", "CAD")] { - fin_bytes.extend_from_slice(&make_financials_doc( - Some(sym), - "2024-03-31", - None, - "Q1", - ccy, - FundamentalsFields { - revenue: Some(50.0), - ..Default::default() - }, - )); - fin_bytes.extend_from_slice(&make_financials_doc( - Some(sym), - "2024-12-31", - None, - "FY", - ccy, - FundamentalsFields { - revenue: Some(200.0), - ..Default::default() - }, - )); - } - fs::write(&fin_path, &fin_bytes).unwrap(); - // Empty filings dump -> all 4 observations must use statutory_lag_estimate. - fs::write(&fil_path, []).unwrap(); - - let args = default_test_args(fin_path, fil_path, map_path, venues_path, out_dir.clone()); - let report = run_curate_fundamentals(&args).unwrap(); - assert_conservation(&report); - assert_eq!(report.curate_stats.build.rows_linked_to_filing, 0); - assert_eq!(report.curate_stats.build.rows_statutory_lag_estimate, 4); - - let by_year = read_dataset_by_year(&out_dir); - let rows_2024 = &by_year[&2024]; - let rows_2025 = &by_year[&2025]; - - let expected_us_q = et_to_utc_micros( - q_end + STATUTORY_LAG_US_TSX_QUARTERLY_DAYS, - FUNDAMENTALS_FALLBACK_HOUR_ET, - FUNDAMENTALS_FALLBACK_MINUTE_ET, - 0, - ) - .unwrap(); - let expected_tsxv_q = et_to_utc_micros( - q_end + STATUTORY_LAG_TSXV_CSE_QUARTERLY_DAYS, - FUNDAMENTALS_FALLBACK_HOUR_ET, - FUNDAMENTALS_FALLBACK_MINUTE_ET, - 0, - ) - .unwrap(); - let expected_us_fy = et_to_utc_micros( - fy_end + STATUTORY_LAG_US_TSX_ANNUAL_DAYS, - FUNDAMENTALS_FALLBACK_HOUR_ET, - FUNDAMENTALS_FALLBACK_MINUTE_ET, - 0, - ) - .unwrap(); - let expected_tsxv_fy = et_to_utc_micros( - fy_end + STATUTORY_LAG_TSXV_CSE_ANNUAL_DAYS, - FUNDAMENTALS_FALLBACK_HOUR_ET, - FUNDAMENTALS_FALLBACK_MINUTE_ET, - 0, - ) - .unwrap(); - - assert_ne!(expected_us_q, expected_tsxv_q); - assert_ne!(expected_us_fy, expected_tsxv_fy); - - let us_q = rows_2024.iter().find(|r| r.listing_id == 10).unwrap(); - let tsxv_q = rows_2024.iter().find(|r| r.listing_id == 20).unwrap(); - let us_fy = rows_2025.iter().find(|r| r.listing_id == 10).unwrap(); - let tsxv_fy = rows_2025.iter().find(|r| r.listing_id == 20).unwrap(); - - for (row, expected_ts) in [ - (us_q, expected_us_q), - (tsxv_q, expected_tsxv_q), - (us_fy, expected_us_fy), - (tsxv_fy, expected_tsxv_fy), - ] { - assert_eq!(row.effective_known_at, expected_ts); - assert_eq!(row.period_known_at, expected_ts); - assert_eq!(row.known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); - assert!(row.has_estimated_lag); - } -} - -#[test] -fn fundamentals_report_conserves_counters() { - let tmp = TempDirGuard::new("conservation"); - let fin_path = tmp.path().join("qmFinancials.bson"); - let fil_path = tmp.path().join("qmFilings.bson"); - let map_path = tmp.path().join("provider_mapping.tsv"); - let venues_path = tmp.path().join("listing_venues.tsv"); - let out_dir = tmp.path().join("out"); - - fs::write(&map_path, "qm\tKNOWN\t2020-01-01\t\t401\n").unwrap(); - fs::write(&venues_path, "401\tus_tsx\n").unwrap(); - - let mut fin_bytes = Vec::new(); - // 1. Emitted & mapped - fin_bytes.extend_from_slice(&make_financials_doc( - Some("KNOWN"), - "2024-03-31", - Some("2024-05-01"), - "Q1", - "USD", - FundamentalsFields { - revenue: Some(10.0), - ..Default::default() - }, - )); - // 2. Skipped at BSON decode (missing key) - fin_bytes.extend_from_slice(&make_financials_doc( - None, - "2024-03-31", - Some("2024-05-01"), - "Q1", - "USD", - FundamentalsFields::default(), - )); - // 3. Emitted at BSON decode, dropped unmapped at stage - fin_bytes.extend_from_slice(&make_financials_doc( - Some("UNMAPPED"), - "2024-03-31", - Some("2024-05-01"), - "Q1", - "USD", - FundamentalsFields { - revenue: Some(20.0), - ..Default::default() - }, - )); - fs::write(&fin_path, &fin_bytes).unwrap(); - - let mut fil_bytes = Vec::new(); - // 1. Emitted & mapped - fil_bytes.extend_from_slice(&make_filing_doc( - Some("KNOWN"), - "2024-05-01T16:10:00 EDT", - "10-Q", - Some("f1"), - None, - )); - // 2. Skipped at BSON decode (missing key) - fil_bytes.extend_from_slice(&make_filing_doc( - None, - "2024-05-01T16:10:00 EDT", - "10-Q", - None, - None, - )); - // 3. Emitted at BSON decode, dropped unmapped at stage - fil_bytes.extend_from_slice(&make_filing_doc( - Some("UNMAPPED"), - "2024-05-01T16:10:00 EDT", - "10-Q", - None, - None, - )); - // 4. Emitted at BSON decode, dropped invalid timestamp at stage - fil_bytes.extend_from_slice(&make_filing_doc( - Some("KNOWN"), - "not-a-timestamp", - "10-Q", - None, - None, - )); - fs::write(&fil_path, &fil_bytes).unwrap(); - - let args = default_test_args(fin_path, fil_path, map_path, venues_path, out_dir); - let report = run_curate_fundamentals(&args).unwrap(); - - assert_conservation(&report); - assert_eq!(report.financials_docs_framed, 3); - assert_eq!(report.financials_bytes_read, fin_bytes.len() as u64); - assert_eq!(report.financials_decode.rows_out, 2); - assert_eq!(report.financials_decode.skipped_missing_key, 1); - assert_eq!(report.curate_stats.observations_in, 2); - assert_eq!(report.curate_stats.observations_dropped_unmapped, 1); - - assert_eq!(report.filings_docs_framed, 4); - assert_eq!(report.filings_bytes_read, fil_bytes.len() as u64); - assert_eq!(report.filings_decode.rows_out, 3); - assert_eq!(report.filings_decode.skipped_missing_key, 1); - assert_eq!(report.curate_stats.filings_in, 3); - assert_eq!(report.curate_stats.filings_dropped_unmapped, 1); - assert_eq!(report.curate_stats.filings_dropped_invalid_timestamp, 1); - - assert_eq!(report.curate_stats.rows_out, 1); - assert_eq!(report.write_stats.rows_written, 1); - - let formatted = format_curate_fundamentals_report(&report); - for section in [ - "curate-etl curate-fundamentals", - "financials_bson:", - "filings_bson:", - "builder:", - "curate:", - "write:", - "years:", - "timing:", - "2024=1", - ] { - assert!( - formatted.contains(section), - "formatted report missing '{section}':\n{formatted}" - ); - } -} - -#[test] -fn fundamentals_failures_preserve_output_tree() { - let tmp = TempDirGuard::new("fail-closed"); - let valid_fin = tmp.path().join("valid_fin.bson"); - let valid_fil = tmp.path().join("valid_fil.bson"); - let valid_map = tmp.path().join("valid_map.tsv"); - let valid_venues = tmp.path().join("valid_venues.tsv"); - - fs::write(&valid_map, "qm\tNVDA\t2020-01-01\t\t101\n").unwrap(); - fs::write(&valid_venues, "101\tus_tsx\n").unwrap(); - let fin_doc = make_financials_doc( - Some("NVDA"), - "2024-03-31", - Some("2024-05-01"), - "Q1", - "USD", - FundamentalsFields { - revenue: Some(100.0), - ..Default::default() - }, - ); - let fil_doc = make_filing_doc( - Some("NVDA"), - "2024-05-01T16:10:00 EDT", - "10-Q", - Some("f1"), - None, - ); - fs::write(&valid_fin, &fin_doc).unwrap(); - fs::write(&valid_fil, &fil_doc).unwrap(); - - // Seed a pre-existing partition in out_existing so we verify byte-for-byte preservation. - let out_existing = tmp.path().join("out_existing"); - let seed_args = default_test_args( - valid_fin.clone(), - valid_fil.clone(), - valid_map.clone(), - valid_venues.clone(), - out_existing.clone(), - ); - run_curate_fundamentals(&seed_args).expect("seed existing output"); - let existing_before = snapshot_tree(&out_existing); - assert!(existing_before.len() >= 3); - - // Also test against a missing output directory that must remain absent. - let out_missing = tmp.path().join("out_missing"); - assert!(!out_missing.exists()); - - let assert_preserved = |out_dir: &Path, expected: &BTreeMap| { - assert_eq!( - &snapshot_tree(out_dir), - expected, - "output tree {} was mutated on failure", - out_dir.display() - ); - }; - - for (out_dir, before) in [ - (out_existing.as_path(), existing_before.clone()), - (out_missing.as_path(), BTreeMap::new()), - ] { - let base = || { - default_test_args( - valid_fin.clone(), - valid_fil.clone(), - valid_map.clone(), - valid_venues.clone(), - out_dir.to_path_buf(), - ) - }; - - // 1. Invalid financials field path - let mut a = base(); - a.financials_revenue_field = Some("IncomeStatement..revenue".to_string()); - let err = run_curate_fundamentals(&a).unwrap_err(); - assert!(matches!( - err, - RunCurateFundamentalsError::InvalidFinancialsConfig { ref path, .. } - if path == &valid_fin - )); - assert!(err.to_string().contains(&valid_fin.display().to_string())); - assert_single_line(&err.to_string()); - assert_preserved(out_dir, &before); - - // 2. Invalid filings field name - let mut a = base(); - a.filings_form_type_field = " ".to_string(); - let err = run_curate_fundamentals(&a).unwrap_err(); - assert!(matches!( - err, - RunCurateFundamentalsError::InvalidFilingsFieldNames { ref path, .. } - if path == &valid_fil - )); - assert!(err.to_string().contains(&valid_fil.display().to_string())); - assert_single_line(&err.to_string()); - assert_preserved(out_dir, &before); - - // 3. Invalid fiscal policy (blank token & overlapping tokens) - let mut a = base(); - a.fiscal_period = CurateFundamentalsFiscalPeriod::ByTokens { - quarterly: vec!["Q1".to_string(), " ".to_string()], - annual: vec!["FY".to_string()], - }; - let err = run_curate_fundamentals(&a).unwrap_err(); - assert!(matches!( - err, - RunCurateFundamentalsError::InvalidFinancialsConfig { ref path, .. } - if path == &valid_fin - )); - assert!(err.to_string().contains(&valid_fin.display().to_string())); - assert_single_line(&err.to_string()); - assert_preserved(out_dir, &before); - - let mut a = base(); - a.fiscal_period = CurateFundamentalsFiscalPeriod::ByTokens { - quarterly: vec!["FY".to_string()], - annual: vec!["FY".to_string()], - }; - let err = run_curate_fundamentals(&a).unwrap_err(); - assert!(matches!( - err, - RunCurateFundamentalsError::InvalidFinancialsConfig { ref path, .. } - if path == &valid_fin - )); - assert!(err.to_string().contains(&valid_fin.display().to_string())); - assert_single_line(&err.to_string()); - assert_preserved(out_dir, &before); - - // 4. Blank mapping source - let mut a = base(); - a.mapping_source = " \t ".to_string(); - let err = run_curate_fundamentals(&a).unwrap_err(); - assert!(matches!( - err, - RunCurateFundamentalsError::EmptyMappingSource - )); - assert_single_line(&err.to_string()); - assert_preserved(out_dir, &before); - - // 5. Zero k - let mut a = base(); - a.k = 0; - let err = run_curate_fundamentals(&a).unwrap_err(); - assert!(matches!( - err, - RunCurateFundamentalsError::InvalidPeriodLimit { k: 0 } - )); - assert_single_line(&err.to_string()); - assert_preserved(out_dir, &before); - - // 6. Unreadable / missing files for all four inputs - let missing_fin = tmp.path().join("no_such_fin.bson"); - let mut a = base(); - a.qm_financials = missing_fin.clone(); - let err = run_curate_fundamentals(&a).unwrap_err(); - assert!(matches!( - err, - RunCurateFundamentalsError::OpenInput { - label: "qm-financials", - ref path, - .. - } if path == &missing_fin - )); - assert!(err.to_string().contains(&missing_fin.display().to_string())); - assert_single_line(&err.to_string()); - assert_preserved(out_dir, &before); - - let missing_fil = tmp.path().join("no_such_fil.bson"); - let mut a = base(); - a.qm_filings = missing_fil.clone(); - let err = run_curate_fundamentals(&a).unwrap_err(); - assert!(matches!( - err, - RunCurateFundamentalsError::OpenInput { - label: "qm-filings", - ref path, - .. - } if path == &missing_fil - )); - assert!(err.to_string().contains(&missing_fil.display().to_string())); - assert_single_line(&err.to_string()); - assert_preserved(out_dir, &before); - - let missing_map = tmp.path().join("no_such_map.tsv"); - let mut a = base(); - a.provider_mapping = missing_map.clone(); - let err = run_curate_fundamentals(&a).unwrap_err(); - assert!(matches!( - err, - RunCurateFundamentalsError::OpenInput { ref path, .. } if path == &missing_map - )); - assert!(err.to_string().contains(&missing_map.display().to_string())); - assert_single_line(&err.to_string()); - assert_preserved(out_dir, &before); - - let missing_venues = tmp.path().join("no_such_venues.tsv"); - let mut a = base(); - a.listing_venues = missing_venues.clone(); - let err = run_curate_fundamentals(&a).unwrap_err(); - assert!(matches!( - err, - RunCurateFundamentalsError::OpenInput { - label: "listing-venues", - ref path, - .. - } if path == &missing_venues - )); - assert!(err.to_string().contains(&missing_venues.display().to_string())); - assert_single_line(&err.to_string()); - assert_preserved(out_dir, &before); - - // 7. Injected BSON read failures for both readers - struct FailingReader; - impl Read for FailingReader { - fn read(&mut self, _buf: &mut [u8]) -> io::Result { - Err(io::Error::new(io::ErrorKind::BrokenPipe, "synthetic read failure")) - } - } - let a = base(); - let err = run_curate_fundamentals_with_readers( - &a, - FailingReader, - Cursor::new(fil_doc.as_slice()), - ) - .unwrap_err(); - assert!(matches!( - err, - RunCurateFundamentalsError::BsonStream { - label: "qm-financials", - ref path, - source: BsonStreamError::Io { offset: 0, .. }, - } if path == &valid_fin - )); - assert!(err.source().is_some()); - assert_single_line(&err.to_string()); - assert_preserved(out_dir, &before); - - let err = run_curate_fundamentals_with_readers( - &a, - Cursor::new(fin_doc.as_slice()), - FailingReader, - ) - .unwrap_err(); - assert!(matches!( - err, - RunCurateFundamentalsError::BsonStream { - label: "qm-filings", - ref path, - source: BsonStreamError::Io { offset: 0, .. }, - } if path == &valid_fil - )); - assert!(err.source().is_some()); - assert_single_line(&err.to_string()); - assert_preserved(out_dir, &before); - - // 8. Malformed mapping TSV - let bad_map = tmp.path().join("bad_map.tsv"); - fs::write(&bad_map, "qm\tNVDA\t2020-01-01\t\t101\nbad_line_only_one_col\n").unwrap(); - let mut a = base(); - a.provider_mapping = bad_map.clone(); - let err = run_curate_fundamentals(&a).unwrap_err(); - assert!(matches!( - err, - RunCurateFundamentalsError::TsvParse { - ref path, - line: 2, - .. - } if path == &bad_map - )); - assert!(err.to_string().contains(&format!("{}:2:", bad_map.display()))); - assert_single_line(&err.to_string()); - assert_preserved(out_dir, &before); - - // 9. Malformed venue TSV - let bad_venues = tmp.path().join("bad_venues.tsv"); - fs::write(&bad_venues, "101\tus_tsx\n202\tunknown_exchange\n").unwrap(); - let mut a = base(); - a.listing_venues = bad_venues.clone(); - let err = run_curate_fundamentals(&a).unwrap_err(); - assert!(matches!( - err, - RunCurateFundamentalsError::TsvParse { - ref path, - line: 2, - .. - } if path == &bad_venues - )); - assert!(err.to_string().contains(&format!("{}:2:", bad_venues.display()))); - assert_single_line(&err.to_string()); - assert_preserved(out_dir, &before); - - // 10. Mapping range conflict - let conflict_map = tmp.path().join("conflict_map.tsv"); - fs::write( - &conflict_map, - "qm\tNVDA\t2020-01-01\t2024-06-01\t101\nqm\tNVDA\t2024-06-01\t\t102\n", - ) - .unwrap(); - let mut a = base(); - a.provider_mapping = conflict_map.clone(); - let err = run_curate_fundamentals(&a).unwrap_err(); - assert!(matches!( - err, - RunCurateFundamentalsError::ProviderMapping { - ref path, - source: ProviderMappingError::OverlappingRanges { .. }, - } if path == &conflict_map - )); - assert!(err.to_string().contains(&conflict_map.display().to_string())); - assert_single_line(&err.to_string()); - assert_preserved(out_dir, &before); - - // 11. Truncated BSON in financials and filings - let trunc_fin = tmp.path().join("trunc_fin.bson"); - let mut trunc_fin_bytes = fin_doc.clone(); - trunc_fin_bytes.extend_from_slice(&fin_doc[..10]); - fs::write(&trunc_fin, &trunc_fin_bytes).unwrap(); - let mut a = base(); - a.qm_financials = trunc_fin.clone(); - let err = run_curate_fundamentals(&a).unwrap_err(); - assert!(matches!( - err, - RunCurateFundamentalsError::BsonStream { - label: "qm-financials", - ref path, - source: BsonStreamError::TruncatedDocument { offset, .. }, - } if path == &trunc_fin && offset == fin_doc.len() as u64 - )); - assert_single_line(&err.to_string()); - assert_preserved(out_dir, &before); - - let trunc_fil = tmp.path().join("trunc_fil.bson"); - let mut trunc_fil_bytes = fil_doc.clone(); - trunc_fil_bytes.extend_from_slice(&fil_doc[..7]); - fs::write(&trunc_fil, &trunc_fil_bytes).unwrap(); - let mut a = base(); - a.qm_filings = trunc_fil.clone(); - let err = run_curate_fundamentals(&a).unwrap_err(); - assert!(matches!( - err, - RunCurateFundamentalsError::BsonStream { - label: "qm-filings", - ref path, - source: BsonStreamError::TruncatedDocument { offset, .. }, - } if path == &trunc_fil && offset == fil_doc.len() as u64 - )); - assert_single_line(&err.to_string()); - assert_preserved(out_dir, &before); - - // 12. Corrupt BSON in financials and filings (valid framing, invalid element tag) - let corrupt_fin = tmp.path().join("corrupt_fin.bson"); - let mut bad_fin_doc = fin_doc.clone(); - bad_fin_doc[4] = 0x7E; - let mut corrupt_fin_bytes = fin_doc.clone(); - let expected_fin_off = corrupt_fin_bytes.len() as u64; - corrupt_fin_bytes.extend_from_slice(&bad_fin_doc); - fs::write(&corrupt_fin, &corrupt_fin_bytes).unwrap(); - let mut a = base(); - a.qm_financials = corrupt_fin.clone(); - let err = run_curate_fundamentals(&a).unwrap_err(); - assert!(matches!( - err, - RunCurateFundamentalsError::CorruptFinancialsBson { - ref path, - offset, - .. - } if path == &corrupt_fin && offset == expected_fin_off - )); - assert!(err.to_string().contains(&expected_fin_off.to_string())); - assert_single_line(&err.to_string()); - assert_preserved(out_dir, &before); - - let corrupt_fil = tmp.path().join("corrupt_fil.bson"); - let mut bad_fil_doc = fil_doc.clone(); - bad_fil_doc[4] = 0x7E; - let mut corrupt_fil_bytes = fil_doc.clone(); - let expected_fil_off = corrupt_fil_bytes.len() as u64; - corrupt_fil_bytes.extend_from_slice(&bad_fil_doc); - fs::write(&corrupt_fil, &corrupt_fil_bytes).unwrap(); - let mut a = base(); - a.qm_filings = corrupt_fil.clone(); - let err = run_curate_fundamentals(&a).unwrap_err(); - assert!(matches!( - err, - RunCurateFundamentalsError::CorruptFilingsBson { - ref path, - offset, - .. - } if path == &corrupt_fil && offset == expected_fil_off - )); - assert!(err.to_string().contains(&expected_fil_off.to_string())); - assert_single_line(&err.to_string()); - assert_preserved(out_dir, &before); - } -} - -#[test] -fn fundamentals_rejects_output_files_and_input_aliases() { - let tmp = TempDirGuard::new("path-safety"); - let valid_fin = tmp.path().join("fin.bson"); - let valid_fil = tmp.path().join("fil.bson"); - let valid_map = tmp.path().join("map.tsv"); - let valid_venues = tmp.path().join("venues.tsv"); - - let fin_bytes = make_financials_doc( - Some("NVDA"), - "2024-03-31", - Some("2024-05-01"), - "Q1", - "USD", - FundamentalsFields { - revenue: Some(100.0), - ..Default::default() - }, - ); - let fil_bytes = make_filing_doc( - Some("NVDA"), - "2024-05-01T16:10:00 EDT", - "10-Q", - Some("f1"), - None, - ); - fs::write(&valid_fin, &fin_bytes).unwrap(); - fs::write(&valid_fil, &fil_bytes).unwrap(); - fs::write(&valid_map, "qm\tNVDA\t2020-01-01\t\t101\n").unwrap(); - fs::write(&valid_venues, "101\tus_tsx\n").unwrap(); - - // 1. Regular file at out_dir - let file_as_out = tmp.path().join("out_is_file"); - let sentinel = b"do-not-overwrite-out-file".to_vec(); - fs::write(&file_as_out, &sentinel).unwrap(); - let args = default_test_args( - valid_fin.clone(), - valid_fil.clone(), - valid_map.clone(), - valid_venues.clone(), - file_as_out.clone(), - ); - assert!(matches!( - run_curate_fundamentals(&args).unwrap_err(), - RunCurateFundamentalsError::InvalidOutDir { .. } - )); - assert!(matches!( - run_curate_fundamentals_with_readers( - &args, - Cursor::new(fin_bytes.as_slice()), - Cursor::new(fil_bytes.as_slice()), - ) - .unwrap_err(), - RunCurateFundamentalsError::InvalidOutDir { .. } - )); - assert_eq!(fs::read(&file_as_out).unwrap(), sentinel); - - // 2. Regular file at /fundamentals_pit - let out_with_file = tmp.path().join("out_with_dataset_file"); - fs::create_dir_all(&out_with_file).unwrap(); - let dataset_file = out_with_file.join("fundamentals_pit"); - fs::write(&dataset_file, b"dataset-file-sentinel").unwrap(); - let before = snapshot_tree(&out_with_file); - let args = default_test_args( - valid_fin.clone(), - valid_fil.clone(), - valid_map.clone(), - valid_venues.clone(), - out_with_file.clone(), - ); - assert!(matches!( - run_curate_fundamentals(&args).unwrap_err(), - RunCurateFundamentalsError::InvalidOutDir { .. } - )); - assert!(matches!( - run_curate_fundamentals_with_readers( - &args, - Cursor::new(fin_bytes.as_slice()), - Cursor::new(fil_bytes.as_slice()), - ) - .unwrap_err(), - RunCurateFundamentalsError::InvalidOutDir { .. } - )); - assert_eq!(snapshot_tree(&out_with_file), before); - - // 3. All four inputs resolving to out_dir or inside /fundamentals_pit - let alias_out = tmp.path().join("alias_out"); - let inside_ds = alias_out.join("fundamentals_pit").join("year=2024"); - fs::create_dir_all(&inside_ds).unwrap(); - let inside_fin = inside_ds.join("fin.bson"); - let inside_fil = inside_ds.join("fil.bson"); - let inside_map = inside_ds.join("map.tsv"); - let inside_venues = inside_ds.join("venues.tsv"); - fs::write(&inside_fin, &fin_bytes).unwrap(); - fs::write(&inside_fil, &fil_bytes).unwrap(); - fs::write(&inside_map, "qm\tNVDA\t2020-01-01\t\t101\n").unwrap(); - fs::write(&inside_venues, "101\tus_tsx\n").unwrap(); - let alias_before = snapshot_tree(&alias_out); - - for bad_args in [ - default_test_args( - inside_fin.clone(), - valid_fil.clone(), - valid_map.clone(), - valid_venues.clone(), - alias_out.clone(), - ), - default_test_args( - valid_fin.clone(), - inside_fil.clone(), - valid_map.clone(), - valid_venues.clone(), - alias_out.clone(), - ), - default_test_args( - valid_fin.clone(), - valid_fil.clone(), - inside_map.clone(), - valid_venues.clone(), - alias_out.clone(), - ), - default_test_args( - valid_fin.clone(), - valid_fil.clone(), - valid_map.clone(), - inside_venues.clone(), - alias_out.clone(), - ), - // Input equal to out_dir itself - default_test_args( - alias_out.clone(), - valid_fil.clone(), - valid_map.clone(), - valid_venues.clone(), - alias_out.clone(), - ), - ] { - assert!(matches!( - run_curate_fundamentals(&bad_args).unwrap_err(), - RunCurateFundamentalsError::InvalidOutDir { .. } - )); - assert!(matches!( - run_curate_fundamentals_with_readers( - &bad_args, - Cursor::new(fin_bytes.as_slice()), - Cursor::new(fil_bytes.as_slice()), - ) - .unwrap_err(), - RunCurateFundamentalsError::InvalidOutDir { .. } - )); - assert_eq!(snapshot_tree(&alias_out), alias_before); - } - - // 4. Unix symlink-before-`..` resolution and symlinked year=2024 partition aliasing an external input - #[cfg(unix)] - { - use std::os::unix::fs::symlink; - - // Symlink-before-`..`: link_dir -> real_parent/child; link_dir/../out_target resolves to - // real_parent/out_target (NOT tmp/out_target). - let real_parent = tmp.path().join("real_parent"); - let real_child = real_parent.join("child"); - fs::create_dir_all(&real_child).unwrap(); - let real_out = real_parent.join("out_target"); - let real_ds = real_out.join("fundamentals_pit"); - fs::create_dir_all(&real_ds).unwrap(); - let ext_input = real_ds.join("aliased_fin.bson"); - fs::write(&ext_input, &fin_bytes).unwrap(); - let ext_before = fs::read(&ext_input).unwrap(); - let real_out_before = snapshot_tree(&real_out); - - let link_dir = tmp.path().join("link_dir"); - symlink(&real_child, &link_dir).unwrap(); - let symlink_dotdot_out = link_dir.join("..").join("out_target"); - - let args = default_test_args( - ext_input.clone(), - valid_fil.clone(), - valid_map.clone(), - valid_venues.clone(), - symlink_dotdot_out, - ); - assert!(matches!( - run_curate_fundamentals(&args).unwrap_err(), - RunCurateFundamentalsError::InvalidOutDir { .. } - )); - assert!(matches!( - run_curate_fundamentals_with_readers( - &args, - Cursor::new(fin_bytes.as_slice()), - Cursor::new(fil_bytes.as_slice()), - ) - .unwrap_err(), - RunCurateFundamentalsError::InvalidOutDir { .. } - )); - assert_eq!(snapshot_tree(&real_out), real_out_before); - assert_eq!(fs::read(&ext_input).unwrap(), ext_before); - - // Symlinked year=2024 partition pointing to external dir containing an input file. - let ext_dir = tmp.path().join("external_year_target"); - fs::create_dir_all(&ext_dir).unwrap(); - let ext_part_input = ext_dir.join("part.parquet"); - fs::write(&ext_part_input, &fin_bytes).unwrap(); - let ext_part_before = fs::read(&ext_part_input).unwrap(); - - let sym_out = tmp.path().join("sym_year_out"); - let sym_ds = sym_out.join("fundamentals_pit"); - fs::create_dir_all(&sym_ds).unwrap(); - symlink(&ext_dir, sym_ds.join("year=2024")).unwrap(); - let sym_out_before = snapshot_tree(&sym_out); - - let args = default_test_args( - ext_part_input.clone(), - valid_fil.clone(), - valid_map.clone(), - valid_venues.clone(), - sym_out.clone(), - ); - assert!(matches!( - run_curate_fundamentals(&args).unwrap_err(), - RunCurateFundamentalsError::InvalidOutDir { .. } - )); - assert!(matches!( - run_curate_fundamentals_with_readers( - &args, - Cursor::new(fin_bytes.as_slice()), - Cursor::new(fil_bytes.as_slice()), - ) - .unwrap_err(), - RunCurateFundamentalsError::InvalidOutDir { .. } - )); - assert_eq!(snapshot_tree(&sym_out), sym_out_before); - assert_eq!(fs::read(&ext_part_input).unwrap(), ext_part_before); - } -} - -#[cfg(unix)] -#[test] -fn fundamentals_rejects_aliased_year_partitions() { - use std::os::unix::fs::symlink; - - let tmp = TempDirGuard::new("aliased-years"); - let map_path = tmp.path().join("map.tsv"); - let venues_path = tmp.path().join("venues.tsv"); - fs::write(&map_path, "qm\tNVDA\t2020-01-01\t\t101\n").unwrap(); - fs::write(&venues_path, "101\tus_tsx\n").unwrap(); - - // Seed a valid 2023 partition in a shared target directory. - let fin_2023 = tmp.path().join("fin_2023.bson"); - let fil_2023 = tmp.path().join("fil_2023.bson"); - fs::write( - &fin_2023, - make_financials_doc( - Some("NVDA"), - "2023-03-31", - Some("2023-05-01"), - "Q1", - "USD", - FundamentalsFields { - revenue: Some(80.0), - ..Default::default() - }, - ), - ) - .unwrap(); - fs::write( - &fil_2023, - make_filing_doc( - Some("NVDA"), - "2023-05-01T16:10:00 EDT", - "10-Q", - Some("f2023"), - None, - ), - ) - .unwrap(); - - let seed_out = tmp.path().join("seed_out"); - let seed_args = default_test_args( - fin_2023, - fil_2023, - map_path.clone(), - venues_path.clone(), - seed_out.clone(), - ); - let seed_report = run_curate_fundamentals(&seed_args).expect("seed 2023 partition"); - assert_eq!(seed_report.write_stats.rows_written, 1); - - let shared_target = tmp.path().join("shared_archive"); - fs::create_dir_all(&shared_target).unwrap(); - let seeded_part = seed_out - .join("fundamentals_pit") - .join("year=2023") - .join("part.parquet"); - let shared_part = shared_target.join("part.parquet"); - fs::copy(&seeded_part, &shared_part).unwrap(); - let shared_target_before = snapshot_tree(&shared_target); - let shared_part_bytes_before = fs::read(&shared_part).unwrap(); - - // Point both year=2023 and year=2024 at the same shared target directory. - let aliased_out = tmp.path().join("aliased_out"); - let aliased_ds = aliased_out.join("fundamentals_pit"); - fs::create_dir_all(&aliased_ds).unwrap(); - symlink(&shared_target, aliased_ds.join("year=2023")).unwrap(); - symlink(&shared_target, aliased_ds.join("year=2024")).unwrap(); - let aliased_out_before = snapshot_tree(&aliased_out); - - // Prepare a 2024-only rerun that would overwrite 2023's part.parquet if allowed. - let fin_2024 = tmp.path().join("fin_2024.bson"); - let fil_2024 = tmp.path().join("fil_2024.bson"); - let fin_2024_bytes = make_financials_doc( - Some("NVDA"), - "2024-03-31", - Some("2024-05-01"), - "Q1", - "USD", - FundamentalsFields { - revenue: Some(120.0), - ..Default::default() - }, - ); - let fil_2024_bytes = make_filing_doc( - Some("NVDA"), - "2024-05-01T16:10:00 EDT", - "10-Q", - Some("f2024"), - None, - ); - fs::write(&fin_2024, &fin_2024_bytes).unwrap(); - fs::write(&fil_2024, &fil_2024_bytes).unwrap(); - - let rerun_args = default_test_args( - fin_2024.clone(), - fil_2024.clone(), - map_path.clone(), - venues_path.clone(), - aliased_out.clone(), - ); - - let err_file = run_curate_fundamentals(&rerun_args).unwrap_err(); - assert!(matches!( - err_file, - RunCurateFundamentalsError::InvalidOutDir { .. } - )); - let msg_file = err_file.to_string(); - assert_single_line(&msg_file); - assert!(msg_file.contains("year=2024") && msg_file.contains("year=2023")); - assert_eq!(snapshot_tree(&aliased_out), aliased_out_before); - assert_eq!(snapshot_tree(&shared_target), shared_target_before); - assert_eq!(fs::read(&shared_part).unwrap(), shared_part_bytes_before); - - let err_reader = run_curate_fundamentals_with_readers( - &rerun_args, - Cursor::new(fin_2024_bytes.as_slice()), - Cursor::new(fil_2024_bytes.as_slice()), - ) - .unwrap_err(); - assert!(matches!( - err_reader, - RunCurateFundamentalsError::InvalidOutDir { .. } - )); - assert_single_line(&err_reader.to_string()); - assert_eq!(snapshot_tree(&aliased_out), aliased_out_before); - assert_eq!(snapshot_tree(&shared_target), shared_target_before); - assert_eq!(fs::read(&shared_part).unwrap(), shared_part_bytes_before); -} - -#[cfg(unix)] -#[test] -fn fundamentals_rejects_dangling_year_symlink() { - use std::os::unix::fs::symlink; - - let tmp = TempDirGuard::new("dangling-year-symlink"); - let map_path = tmp.path().join("map.tsv"); - let venues_path = tmp.path().join("venues.tsv"); - fs::write(&map_path, "qm\tNVDA\t2020-01-01\t\t101\n").unwrap(); - fs::write(&venues_path, "101\tus_tsx\n").unwrap(); - - // Two-year backfill with 2023 and 2024 snapshots for the same listing. - let mut fin_bytes = make_financials_doc( - Some("NVDA"), - "2023-03-31", - Some("2023-05-01"), - "Q1", - "USD", - FundamentalsFields { - revenue: Some(80.0), - ..Default::default() - }, - ); - fin_bytes.extend_from_slice(&make_financials_doc( - Some("NVDA"), - "2024-03-31", - Some("2024-05-01"), - "Q1", - "USD", - FundamentalsFields { - revenue: Some(120.0), - ..Default::default() - }, - )); - - let mut fil_bytes = make_filing_doc( - Some("NVDA"), - "2023-05-01T16:10:00 EDT", - "10-Q", - Some("f2023"), - None, - ); - fil_bytes.extend_from_slice(&make_filing_doc( - Some("NVDA"), - "2024-05-01T16:10:00 EDT", - "10-Q", - Some("f2024"), - None, - )); - - let fin_path = tmp.path().join("fin_backfill.bson"); - let fil_path = tmp.path().join("fil_backfill.bson"); - fs::write(&fin_path, &fin_bytes).unwrap(); - fs::write(&fil_path, &fil_bytes).unwrap(); - - // Stale year=2024 symlink pointing to the not-yet-created year=2023 directory. - let dangling_out = tmp.path().join("dangling_out"); - let dangling_ds = dangling_out.join("fundamentals_pit"); - fs::create_dir_all(&dangling_ds).unwrap(); - let dangling_link = dangling_ds.join("year=2024"); - symlink(Path::new("year=2023"), &dangling_link).unwrap(); - let before = snapshot_tree(&dangling_out); - - let args = default_test_args( - fin_path, - fil_path, - map_path, - venues_path, - dangling_out.clone(), - ); - - let err_file = run_curate_fundamentals(&args).unwrap_err(); - assert!(matches!( - err_file, - RunCurateFundamentalsError::InvalidOutDir { ref path, .. } if path == &dangling_link - )); - let msg_file = err_file.to_string(); - assert_single_line(&msg_file); - assert!(msg_file.contains("year=2024")); - assert_eq!(snapshot_tree(&dangling_out), before); - - let err_reader = run_curate_fundamentals_with_readers( - &args, - Cursor::new(fin_bytes.as_slice()), - Cursor::new(fil_bytes.as_slice()), - ) - .unwrap_err(); - assert!(matches!( - err_reader, - RunCurateFundamentalsError::InvalidOutDir { ref path, .. } if path == &dangling_link - )); - let msg_reader = err_reader.to_string(); - assert_single_line(&msg_reader); - assert!(msg_reader.contains("year=2024")); - assert_eq!(snapshot_tree(&dangling_out), before); -} - -#[test] -fn fundamentals_empty_inputs_publish_nothing() { - let tmp = TempDirGuard::new("empty"); - let fin_path = tmp.path().join("empty_fin.bson"); - let fil_path = tmp.path().join("empty_fil.bson"); - let map_path = tmp.path().join("map.tsv"); - let venues_path = tmp.path().join("venues.tsv"); - fs::write(&fin_path, []).unwrap(); - fs::write(&fil_path, []).unwrap(); - fs::write(&map_path, "qm\tNVDA\t2020-01-01\t\t101\n").unwrap(); - fs::write(&venues_path, "101\tus_tsx\n").unwrap(); - - // Fresh output directory: dataset directory must not be created. - let fresh_out = tmp.path().join("fresh_out"); - let args = default_test_args( - fin_path.clone(), - fil_path.clone(), - map_path.clone(), - venues_path.clone(), - fresh_out.clone(), - ); - let report = run_curate_fundamentals(&args).unwrap(); - assert_conservation(&report); - assert_eq!(report.write_stats.rows_written, 0); - assert_eq!(report.write_stats.files_written, 0); - assert!(!fresh_out.join("fundamentals_pit").exists()); - - // Pre-existing partition: rerun with empty inputs must leave it byte-identical. - let seeded_out = tmp.path().join("seeded_out"); - let seed_fin = tmp.path().join("seed_fin.bson"); - fs::write( - &seed_fin, - make_financials_doc( - Some("NVDA"), - "2024-03-31", - None, - "Q1", - "USD", - FundamentalsFields { - revenue: Some(50.0), - ..Default::default() - }, - ), - ) - .unwrap(); - let seed_args = default_test_args( - seed_fin, - fil_path.clone(), - map_path.clone(), - venues_path.clone(), - seeded_out.clone(), - ); - run_curate_fundamentals(&seed_args).unwrap(); - let before = snapshot_tree(&seeded_out); - - let empty_rerun = default_test_args(fin_path, fil_path, map_path, venues_path, seeded_out.clone()); - let rerun_report = run_curate_fundamentals(&empty_rerun).unwrap(); - assert_eq!(rerun_report.write_stats.rows_written, 0); - assert_eq!(rerun_report.write_stats.files_written, 0); - assert_eq!(snapshot_tree(&seeded_out), before); -} - -#[test] -fn fundamentals_all_unmapped_publish_nothing() { - let tmp = TempDirGuard::new("unmapped"); - let fin_path = tmp.path().join("unmapped_fin.bson"); - let fil_path = tmp.path().join("unmapped_fil.bson"); - let map_path = tmp.path().join("map.tsv"); - let venues_path = tmp.path().join("venues.tsv"); - - fs::write(&map_path, "qm\tKNOWN\t2020-01-01\t\t101\n").unwrap(); - fs::write(&venues_path, "101\tus_tsx\n").unwrap(); - fs::write( - &fin_path, - make_financials_doc( - Some("OTHER"), - "2024-03-31", - Some("2024-05-01"), - "Q1", - "USD", - FundamentalsFields { - revenue: Some(10.0), - ..Default::default() - }, - ), - ) - .unwrap(); - fs::write( - &fil_path, - make_filing_doc( - Some("OTHER"), - "2024-05-01T16:10:00 EDT", - "10-Q", - Some("f1"), - None, - ), - ) - .unwrap(); - - // Fresh output directory: dataset directory must not be created. - let fresh_out = tmp.path().join("fresh_out"); - let args = default_test_args( - fin_path.clone(), - fil_path.clone(), - map_path.clone(), - venues_path.clone(), - fresh_out.clone(), - ); - let report = run_curate_fundamentals(&args).unwrap(); - assert_conservation(&report); - assert_eq!(report.curate_stats.observations_in, 1); - assert_eq!(report.curate_stats.observations_dropped_unmapped, 1); - assert_eq!(report.write_stats.rows_written, 0); - assert_eq!(report.write_stats.files_written, 0); - assert!(!fresh_out.join("fundamentals_pit").exists()); - - // Pre-existing partition: rerun with all-unmapped inputs leaves it byte-identical. - let seeded_out = tmp.path().join("seeded_out"); - let seed_fin = tmp.path().join("seed_fin.bson"); - fs::write( - &seed_fin, - make_financials_doc( - Some("KNOWN"), - "2024-03-31", - None, - "Q1", - "USD", - FundamentalsFields { - revenue: Some(50.0), - ..Default::default() - }, - ), - ) - .unwrap(); - run_curate_fundamentals(&default_test_args( - seed_fin, - fil_path.clone(), - map_path.clone(), - venues_path.clone(), - seeded_out.clone(), - )) - .unwrap(); - let before = snapshot_tree(&seeded_out); - - let rerun = run_curate_fundamentals(&default_test_args( - fin_path, - fil_path, - map_path, - venues_path, - seeded_out.clone(), - )) - .unwrap(); - assert_eq!(rerun.write_stats.rows_written, 0); - assert_eq!(rerun.write_stats.files_written, 0); - assert_eq!(snapshot_tree(&seeded_out), before); -} - -#[test] -fn listing_venues_rejects_wrong_column_count() { - let tmp = TempDirGuard::new("venues-cols"); - let path = tmp.path().join("listing_venues.tsv"); - fs::write(&path, "101\tus_tsx\n202\n").unwrap(); - let err = load_listing_venues_tsv(&path).unwrap_err(); - assert!(matches!( - err, - RunCurateFundamentalsError::TsvParse { - path: ref p, - line: 2, - .. - } if p == &path - )); - let msg = err.to_string(); - assert!(msg.contains(&format!("{}:2:", path.display()))); - assert_single_line(&msg); - - // Too many columns (3 columns on line 2) - fs::write(&path, "101\tus_tsx\r\n202\ttsxv_cse\textra\r\n").unwrap(); - let err = load_listing_venues_tsv(&path).unwrap_err(); - assert!(matches!( - err, - RunCurateFundamentalsError::TsvParse { - path: ref p, - line: 2, - .. - } if p == &path - )); - let msg = err.to_string(); - assert!(msg.contains(&format!("{}:2:", path.display()))); - assert_single_line(&msg); -} - -#[test] -fn listing_venues_rejects_non_integer_id() { - let tmp = TempDirGuard::new("venues-non-int"); - let path = tmp.path().join("listing_venues.tsv"); - fs::write(&path, "101\tus_tsx\nabc\ttsxv_cse\n").unwrap(); - let err = load_listing_venues_tsv(&path).unwrap_err(); - assert!(matches!( - err, - RunCurateFundamentalsError::TsvParse { - path: ref p, - line: 2, - .. - } if p == &path - )); - let msg = err.to_string(); - assert!(msg.contains(&format!("{}:2:", path.display()))); - assert_single_line(&msg); -} - -#[test] -fn listing_venues_rejects_non_positive_id() { - let tmp = TempDirGuard::new("venues-non-pos"); - let path = tmp.path().join("listing_venues.tsv"); - for (content, expected_line) in [ - ("101\tus_tsx\n0\ttsxv_cse\n", 2), - ("101\tus_tsx\n202\ttsxv_cse\n-5\tus_tsx\n", 3), - ] { - fs::write(&path, content).unwrap(); - let err = load_listing_venues_tsv(&path).unwrap_err(); - assert!(matches!( - err, - RunCurateFundamentalsError::TsvParse { - path: ref p, - line, - .. - } if p == &path && line == expected_line - )); - let msg = err.to_string(); - assert!(msg.contains(&format!("{}:{expected_line}:", path.display()))); - assert_single_line(&msg); - } -} - -#[test] -fn listing_venues_rejects_unknown_venue() { - let tmp = TempDirGuard::new("venues-unknown"); - let path = tmp.path().join("listing_venues.tsv"); - fs::write(&path, "101\tus_tsx\n202\tUS_TSX\n").unwrap(); - let err = load_listing_venues_tsv(&path).unwrap_err(); - assert!(matches!( - err, - RunCurateFundamentalsError::TsvParse { - path: ref p, - line: 2, - .. - } if p == &path - )); - let msg = err.to_string(); - assert!(msg.contains(&format!("{}:2:", path.display()))); - assert_single_line(&msg); -} - -#[test] -fn listing_venues_rejects_duplicate_id() { - let tmp = TempDirGuard::new("venues-dup"); - let path = tmp.path().join("listing_venues.tsv"); - fs::write(&path, "101\tus_tsx\n202\ttsxv_cse\n101\ttsxv_cse\n").unwrap(); - let err = load_listing_venues_tsv(&path).unwrap_err(); - assert!(matches!( - err, - RunCurateFundamentalsError::TsvParse { - path: ref p, - line: 3, - .. - } if p == &path - )); - let msg = err.to_string(); - assert!(msg.contains(&format!("{}:3:", path.display()))); - assert_single_line(&msg); -} - -#[test] -fn listing_venues_rejects_interior_blank() { - let tmp = TempDirGuard::new("venues-blank"); - let path = tmp.path().join("listing_venues.tsv"); - fs::write(&path, "101\tus_tsx\n\n202\ttsxv_cse\n").unwrap(); - let err = load_listing_venues_tsv(&path).unwrap_err(); - assert!(matches!( - err, - RunCurateFundamentalsError::TsvParse { - path: ref p, - line: 2, - .. - } if p == &path - )); - let msg = err.to_string(); - assert!(msg.contains(&format!("{}:2:", path.display()))); - assert_single_line(&msg); -} - -// --------------------------------------------------------------------------------------------- -// QA additions (T-171): replay determinism, missing-venue fail-closed drop, regular-file year -// entry, and strict venue-token parsing edge cases. -// --------------------------------------------------------------------------------------------- - -fn write_qa_replay_fixture(dir: &Path) -> (PathBuf, PathBuf, PathBuf, PathBuf) { - let fin_path = dir.join("qmFinancials.bson"); - let fil_path = dir.join("qmFilings.bson"); - let map_path = dir.join("provider_mapping.tsv"); - let venues_path = dir.join("listing_venues.tsv"); - fs::write( - &map_path, - "qm\tNVDA\t2020-01-01\t\t101\nqm\tMINE:V\t2020-01-01\t\t202\n", - ) - .unwrap(); - fs::write(&venues_path, "101\tus_tsx\n202\ttsxv_cse\n").unwrap(); - - let mut fin = Vec::new(); - for (end, rd, period, rev) in [ - ("2023-09-30", "2023-11-04", "Q3", 120.0), - ("2023-12-31", "2024-02-10", "Q4", 130.0), - ("2024-03-31", "2024-05-02", "Q1", 140.0), - ] { - fin.extend_from_slice(&make_financials_doc( - Some("NVDA"), - end, - Some(rd), - period, - "USD", - FundamentalsFields { - revenue: Some(rev), - net_income: Some(rev / 5.0), - total_assets: Some(1000.0), - ..Default::default() - }, - )); - } - fin.extend_from_slice(&make_financials_doc( - Some("MINE:V"), - "2024-06-30", - None, - "Q2", - "CAD", - FundamentalsFields { - revenue: Some(5.0), - ..Default::default() - }, - )); - fs::write(&fin_path, &fin).unwrap(); - - let mut fil = Vec::new(); - for (ts, id) in [ - ("2023-11-04T16:30:00 EDT", "f-q3"), - ("2024-02-10T16:05:00 EST", "f-q4"), - ("2024-05-02T16:15:00 EDT", "f-q1"), - ] { - fil.extend_from_slice(&make_filing_doc(Some("NVDA"), ts, "10-Q", Some(id), None)); - } - fs::write(&fil_path, &fil).unwrap(); - (fin_path, fil_path, map_path, venues_path) -} - -#[test] -fn fundamentals_rerun_same_inputs_is_byte_identical() { - // Arrange: one pinned fixture, two fresh output roots. - let tmp = TempDirGuard::new("qa-replay"); - let (fin, fil, map, venues) = write_qa_replay_fixture(tmp.path()); - let out_a = tmp.path().join("out_a"); - let out_b = tmp.path().join("out_b"); - - // Act: file API into A, injected-reader API into B. - let report_a = run_curate_fundamentals(&default_test_args( - fin.clone(), - fil.clone(), - map.clone(), - venues.clone(), - out_a.clone(), - )) - .unwrap(); - let report_b = run_curate_fundamentals_with_readers( - &default_test_args(fin.clone(), fil.clone(), map, venues, out_b.clone()), - File::open(&fin).unwrap(), - File::open(&fil).unwrap(), - ) - .unwrap(); - - // Assert: identical counters and byte-identical Parquet partitions. - assert_conservation(&report_a); - assert_reports_eq_ignoring_timing(&report_a, &report_b); - assert!(report_a.write_stats.rows_written > 0); - let tree_a = snapshot_tree(&out_a.join("fundamentals_pit")); - let tree_b = snapshot_tree(&out_b.join("fundamentals_pit")); - assert!(!tree_a.is_empty()); - assert_eq!(tree_a, tree_b, "replay must produce byte-identical partitions"); - // No staging/backup leftovers after a successful publish. - for path in tree_a.keys() { - let name = path.to_string_lossy(); - assert!( - !name.ends_with(".tmp") && !name.contains(".bak"), - "unexpected leftover {name}" - ); - } -} - -#[test] -fn fundamentals_rerun_into_existing_output_replaces_partitions_identically() { - // Arrange - let tmp = TempDirGuard::new("qa-rerun-same-out"); - let (fin, fil, map, venues) = write_qa_replay_fixture(tmp.path()); - let out = tmp.path().join("out"); - let args = default_test_args(fin, fil, map, venues, out.clone()); - - // Act - let first = run_curate_fundamentals(&args).unwrap(); - let before = snapshot_tree(&out); - let second = run_curate_fundamentals(&args).unwrap(); - - // Assert - assert_reports_eq_ignoring_timing(&first, &second); - assert_eq!(snapshot_tree(&out), before); -} - -#[test] -fn fundamentals_mapped_listing_without_venue_is_dropped_not_guessed() { - // Arrange: listing 303 is mapped but absent from listing_venues.tsv; it has a filing-linked - // quarter and an unlinked one. Neither may be published with a guessed venue lag. - let tmp = TempDirGuard::new("qa-missing-venue"); - let fin_path = tmp.path().join("qmFinancials.bson"); - let fil_path = tmp.path().join("qmFilings.bson"); - let map_path = tmp.path().join("provider_mapping.tsv"); - let venues_path = tmp.path().join("listing_venues.tsv"); - let out = tmp.path().join("out"); - fs::write( - &map_path, - "qm\tUSCO\t2020-01-01\t\t10\nqm\tNOVEN\t2020-01-01\t\t303\n", - ) - .unwrap(); - fs::write(&venues_path, "10\tus_tsx\n").unwrap(); - let mut fin = Vec::new(); - for sym in ["USCO", "NOVEN"] { - fin.extend_from_slice(&make_financials_doc( - Some(sym), - "2024-03-31", - Some("2024-05-02"), - "Q1", - "USD", - FundamentalsFields { - revenue: Some(10.0), - ..Default::default() - }, - )); - fin.extend_from_slice(&make_financials_doc( - Some(sym), - "2024-06-30", - None, - "Q2", - "USD", - FundamentalsFields { - revenue: Some(11.0), - ..Default::default() - }, - )); - } - fs::write(&fin_path, &fin).unwrap(); - let mut fil = Vec::new(); - for sym in ["USCO", "NOVEN"] { - fil.extend_from_slice(&make_filing_doc( - Some(sym), - "2024-05-02T16:15:00 EDT", - "10-Q", - None, - None, - )); - } - fs::write(&fil_path, &fil).unwrap(); - - // Act - let report = run_curate_fundamentals(&default_test_args( - fin_path, - fil_path, - map_path, - venues_path, - out.clone(), - )) - .unwrap(); - - // Assert - assert_conservation(&report); - assert_eq!(report.curate_stats.observations_dropped_unmapped, 0); - assert_eq!(report.curate_stats.build.observations_dropped_unknown_key, 2); - assert_eq!(report.curate_stats.listings_out, 1); - let by_year = read_dataset_by_year(&out); - let all: Vec<_> = by_year.values().flatten().collect(); - assert!(!all.is_empty()); - assert!(all.iter().all(|r| r.listing_id == 10)); -} - -#[test] -fn fundamentals_regular_file_year_entry_fails_without_partial_publish() { - // Arrange: a backfill writing 2023 and 2024, where `year=2024` is occupied by a regular file. - // A pre-existing 2023 partition must survive the failed run byte-for-byte. - let tmp = TempDirGuard::new("qa-file-year"); - let (fin, fil, map, venues) = write_qa_replay_fixture(tmp.path()); - let out = tmp.path().join("out"); - let dataset = out.join("fundamentals_pit"); - fs::create_dir_all(dataset.join("year=2023")).unwrap(); - fs::write(dataset.join("year=2023").join("part.parquet"), b"seed-2023").unwrap(); - fs::write(dataset.join("year=2024"), b"not-a-directory").unwrap(); - let before = snapshot_tree(&out); - - for use_readers in [false, true] { - // Act - let args = default_test_args( - fin.clone(), - fil.clone(), - map.clone(), - venues.clone(), - out.clone(), - ); - let result = if use_readers { - run_curate_fundamentals_with_readers( - &args, - File::open(&fin).unwrap(), - File::open(&fil).unwrap(), - ) - } else { - run_curate_fundamentals(&args) - }; - - // Assert - let err = result.expect_err("regular-file year entry must fail"); - assert_single_line(&err.to_string()); - assert_eq!(snapshot_tree(&out), before, "output tree must be unchanged"); - } -} - -#[test] -fn listing_venues_accepts_crlf_and_single_trailing_blank() { - let tmp = TempDirGuard::new("qa-venues-ok"); - let path = tmp.path().join("venues.tsv"); - fs::write(&path, "7\ttsxv_cse\r\n3\tus_tsx\n\n").unwrap(); - let venues = load_listing_venues_tsv(&path).unwrap(); - assert_eq!(venues.len(), 2); - assert_eq!(venues[&3], crate::fundamentals::StatutoryLagVenue::UsTsx); - assert_eq!(venues[&7], crate::fundamentals::StatutoryLagVenue::TsxvCse); - - let empty = tmp.path().join("empty.tsv"); - fs::write(&empty, "").unwrap(); - assert!(load_listing_venues_tsv(&empty).unwrap().is_empty()); -} - -#[test] -fn listing_venues_rejects_padded_signed_and_case_variant_tokens() { - let tmp = TempDirGuard::new("qa-venues-strict"); - let path = tmp.path().join("venues.tsv"); - for (content, line) in [ - ("1\tus_tsx\n2\t us_tsx\n", 2usize), - ("1\tus_tsx\n2\tUS_TSX\n", 2), - ("1\tus_tsx \n", 1), - ("+5\tus_tsx\n", 1), - (" 5\tus_tsx\n", 1), - ("2147483648\tus_tsx\n", 1), - ("1\tus_tsx\n2\t\n", 2), - // Shared `read_tsv_lines` reports the second trailing blank line. - ("1\tus_tsx\n\n\n", 3), - ] { - fs::write(&path, content).unwrap(); - let err = load_listing_venues_tsv(&path).expect_err(content); - let msg = err.to_string(); - assert_single_line(&msg); - match &err { - RunCurateFundamentalsError::TsvParse { path: p, line: l, .. } => { - assert_eq!(p, &path, "{content:?}"); - assert_eq!(*l, line, "{content:?}: {msg}"); - } - other => panic!("expected TsvParse for {content:?}, got {other:?}"), - } - assert!(msg.contains(&format!("{}:{line}:", path.display())), "{msg}"); - } -} - -#[test] -fn listing_venues_missing_file_reports_open_error_with_path() { - let tmp = TempDirGuard::new("qa-venues-missing"); - let path = tmp.path().join("nope.tsv"); - let err = load_listing_venues_tsv(&path).unwrap_err(); - assert!(matches!(err, RunCurateFundamentalsError::OpenInput { ref path, .. } if path.ends_with("nope.tsv"))); - assert!(err.to_string().contains(&path.display().to_string())); -} diff --git a/tools/curate-etl/src/run_curate_fx.rs b/tools/curate-etl/src/run_curate_fx.rs deleted file mode 100644 index f85b2712..00000000 --- a/tools/curate-etl/src/run_curate_fx.rs +++ /dev/null @@ -1,708 +0,0 @@ -//! File-to-file `curate-fx-1d` command runner (`M1.2ac`). -//! -//! Streams concatenated raw BSON `eodPrices` (`CAD.FOREX`) and `teMarketData` (`USDCAD`, -//! configurable via `--te-symbol`) dump files into an atomically published -//! `/fx_1d/part.parquet` dataset via [`curate_and_write_fx_1d`]. -//! -//! # Source Filtering & Contract Rules -//! - `--eod-prices`: streams via [`RawBsonChunkReader`] + [`decode_eod_price_chunks`], keeping -//! only documents whose `eodSearchCode` is exactly [`EOD_CAD_FOREX_CODE`] (`"CAD.FOREX"`). -//! Other symbols are counted in `eod_other_symbol_skipped`; `eodPrices.volume` is ignored when -//! mapping to [`FxDailyBar`]. -//! - `--te-market-data`: streams via [`RawBsonChunkReader`] + [`decode_te_market_data_chunks`], -//! keeping only documents whose `teSymbol` matches `--te-symbol` (ASCII case-insensitive, -//! default [`DEFAULT_TE_SYMBOL`] = `"USDCAD"`). `monthly`, `pc`, `ac`, and unknown fields are -//! ignored. -//! - Delegates merge precedence (`CAD.FOREX` wins on overlap, `teMarketData` fills interior gaps -//! and post-EOD tail), read-only 1% overlap cross-check, conservative `23:59:59.999999 UTC` -//! `ts`/`known_at` stamping, and atomic Zstd Parquet publication unchanged to -//! [`curate_and_write_fx_1d`]. -//! - **Fail-closed safety:** invalid `--out`, unsupported/blank `--te-symbol`, unreadable input -//! files, corrupt/truncated BSON framing or element bytes, zero decoded bars across both -//! sources, and zero publishable rows after FX curation each return a typed [`RunCurateFxError`] -//! without modifying any pre-existing `/fx_1d/part.parquet`. -//! -//! # Counter Conservation Invariants -//! Every successful [`CurateFx1dRunReport`] satisfies: -//! - EOD BSON: -//! `eod_docs_framed as usize == eod_decode.docs_in == eod_decode.decoded + eod_decode.rejected_total()` -//! `eod_decode.decoded == eod_cad_forex_kept + eod_other_symbol_skipped` -//! `eod_cad_forex_kept == curate_stats.builder.eod.rows_in` -//! - TE BSON: -//! `te_docs_framed as usize == te_decode.docs_in == te_decode.docs_matched + te_decode.docs_other_symbol + te_decode.docs_rejected_total()` -//! `te_decode.points_in == te_decode.points_decoded + te_decode.rejected_total()` -//! `te_decode.points_decoded == curate_stats.builder.te.rows_in` -//! - Stage & Write: -//! `curate_stats.rows_in == curate_stats.builder.rows_out == curate_stats.rows_out == write_stats.rows_written` - -use std::error::Error; -use std::fmt; -use std::fs::File; -use std::io; -use std::path::{Path, PathBuf}; -use std::time::Instant; - -use crate::bson_eod_prices::{BsonEodDecodeStats, BsonEodPriceError}; -use crate::bson_stream::{ - decode_eod_price_chunks, decode_te_market_data_chunks, BsonStreamError, BsonStreamOptions, - RawBsonChunkReader, -}; -use crate::bson_te_market_data::{BsonTeMarketDataDecodeStats, BsonTeMarketDataError}; -use crate::curate_fx::{ - curate_and_write_fx_1d, curate_fx_1d, CurateFx1dStats, CurateFxWriteError, -}; -use crate::fx::FxDailyBar; -use crate::parquet_fx::{ - write_fx_1d_dataset, Fx1dParquetRow, Fx1dWriteOptions, Fx1dWriteStats, -}; - -/// Exact `eodPrices.eodSearchCode` kept for USD/CAD FX curation. -pub const EOD_CAD_FOREX_CODE: &str = "CAD.FOREX"; -/// Default `--te-symbol` matched (ASCII case-insensitive) against `teMarketData.teSymbol`. -pub const DEFAULT_TE_SYMBOL: &str = "USDCAD"; -/// Verified USD/CAD `teMarketData.teSymbol` selectors accepted by `curate-fx-1d` -/// (matched ASCII case-insensitively). -pub const ALLOWED_TE_SYMBOLS: &[&str] = &[DEFAULT_TE_SYMBOL]; - -/// Returns `true` if `te_symbol` is an allowed USD/CAD `teMarketData` selector -/// (ASCII case-insensitive match against [`ALLOWED_TE_SYMBOLS`]). -#[inline] -pub fn is_supported_te_symbol(te_symbol: &str) -> bool { - ALLOWED_TE_SYMBOLS - .iter() - .any(|allowed| te_symbol.eq_ignore_ascii_case(allowed)) -} - -/// Parsed arguments for the `curate-fx-1d` CLI command. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct CurateFx1dArgs { - pub eod_prices: PathBuf, - pub te_market_data: PathBuf, - pub te_symbol: String, - pub out_dir: PathBuf, -} - -/// Full run report produced by [`run_curate_fx_1d`]. -/// -/// Conservation invariants: -/// - `eod_docs_framed as usize == eod_decode.docs_in == eod_decode.decoded + eod_decode.rejected_total()` -/// - `eod_decode.decoded == eod_cad_forex_kept + eod_other_symbol_skipped` -/// - `eod_cad_forex_kept == curate_stats.builder.eod.rows_in` -/// - `te_docs_framed as usize == te_decode.docs_in == te_decode.docs_matched + te_decode.docs_other_symbol + te_decode.docs_rejected_total()` -/// - `te_decode.points_in == te_decode.points_decoded + te_decode.rejected_total()` -/// - `te_decode.points_decoded == curate_stats.builder.te.rows_in` -/// - `curate_stats.rows_in == curate_stats.builder.rows_out == curate_stats.rows_out == write_stats.rows_written` -#[derive(Debug, Clone, PartialEq)] -pub struct CurateFx1dRunReport { - pub eod_docs_framed: u64, - pub eod_bytes_read: u64, - pub eod_decode: BsonEodDecodeStats, - pub eod_cad_forex_kept: usize, - pub eod_other_symbol_skipped: usize, - pub te_docs_framed: u64, - pub te_bytes_read: u64, - pub te_decode: BsonTeMarketDataDecodeStats, - pub curate_stats: CurateFx1dStats, - pub write_stats: Fx1dWriteStats, - pub elapsed_secs: f64, -} - -/// Stage-timed run output used internally by `bench-curate-fx-cmd`. -#[derive(Debug, Clone, PartialEq)] -pub(crate) struct CurateFx1dTimedRun { - pub report: CurateFx1dRunReport, - pub decode_elapsed_secs: f64, - pub curate_elapsed_secs: f64, - pub write_elapsed_secs: f64, - pub checksum: u64, -} - -/// Typed errors returned by [`run_curate_fx_1d`]. -/// -/// Every variant's `Display` output is a single line naming the offending path (and byte offset -/// for BSON framing/corruption errors). -#[derive(Debug)] -pub enum RunCurateFxError { - InvalidOutDir { - path: PathBuf, - detail: String, - }, - InvalidTeSymbol { - value: String, - }, - OpenInput { - label: &'static str, - path: PathBuf, - source: io::Error, - }, - BsonStream { - label: &'static str, - path: PathBuf, - source: BsonStreamError, - }, - CorruptEodBson { - path: PathBuf, - offset: u64, - source: BsonEodPriceError, - }, - CorruptTeBson { - path: PathBuf, - offset: u64, - source: BsonTeMarketDataError, - }, - NoDecodedBars { - eod_path: PathBuf, - te_path: PathBuf, - te_symbol: String, - }, - NoCuratedRows { - eod_path: PathBuf, - te_path: PathBuf, - eod_bars_in: usize, - te_bars_in: usize, - }, - CurateWrite { - out_dir: PathBuf, - source: CurateFxWriteError, - }, -} - -impl fmt::Display for RunCurateFxError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::InvalidOutDir { path, detail } => { - write!(f, "invalid --out '{}': {detail}", path.display()) - } - Self::InvalidTeSymbol { value } => { - write!( - f, - "invalid --te-symbol '{value}': only USD/CAD selector '{DEFAULT_TE_SYMBOL}' (case-insensitive) is supported for fx_1d" - ) - } - Self::OpenInput { - label, - path, - source, - } => write!(f, "failed to open {label} '{}': {source}", path.display()), - Self::BsonStream { - label, - path, - source, - } => write!(f, "failed reading {label} '{}': {source}", path.display()), - Self::CorruptEodBson { - path, - offset, - source, - } => write!( - f, - "corrupt eod-prices BSON '{}' at byte offset {offset}: {source}", - path.display() - ), - Self::CorruptTeBson { - path, - offset, - source, - } => write!( - f, - "corrupt te-market-data BSON '{}' at byte offset {offset}: {source}", - path.display() - ), - Self::NoDecodedBars { - eod_path, - te_path, - te_symbol, - } => write!( - f, - "no FX bars decoded for '{EOD_CAD_FOREX_CODE}' in '{}' or '{te_symbol}' in '{}'", - eod_path.display(), - te_path.display() - ), - Self::NoCuratedRows { - eod_path, - te_path, - eod_bars_in, - te_bars_in, - } => write!( - f, - "no publishable fx_1d rows survived curation (eod_bars_in={eod_bars_in} from '{}', te_bars_in={te_bars_in} from '{}')", - eod_path.display(), - te_path.display() - ), - Self::CurateWrite { out_dir, source } => { - write!(f, "curate/write to '{}' failed: {source}", out_dir.display()) - } - } - } -} - -impl Error for RunCurateFxError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::OpenInput { source, .. } => Some(source), - Self::BsonStream { source, .. } => Some(source), - Self::CorruptEodBson { source, .. } => Some(source), - Self::CorruptTeBson { source, .. } => Some(source), - Self::CurateWrite { source, .. } => Some(source), - Self::InvalidOutDir { .. } - | Self::InvalidTeSymbol { .. } - | Self::NoDecodedBars { .. } - | Self::NoCuratedRows { .. } => None, - } - } -} - -fn validate_out_dir(out_dir: &Path) -> Result<(), RunCurateFxError> { - if out_dir.exists() && !out_dir.is_dir() { - return Err(RunCurateFxError::InvalidOutDir { - path: out_dir.to_path_buf(), - detail: "path exists and is not a directory".to_string(), - }); - } - Ok(()) -} - -fn validate_te_symbol(te_symbol: &str) -> Result<(), RunCurateFxError> { - if !is_supported_te_symbol(te_symbol) { - return Err(RunCurateFxError::InvalidTeSymbol { - value: te_symbol.to_string(), - }); - } - Ok(()) -} - -#[inline] -fn is_structural_eod_bson_error(err: &BsonEodPriceError) -> bool { - matches!( - err, - BsonEodPriceError::TruncatedDocument { .. } - | BsonEodPriceError::CorruptDocumentLength { .. } - | BsonEodPriceError::CorruptBson { .. } - ) -} - -#[inline] -fn is_structural_te_bson_error(err: &BsonTeMarketDataError) -> bool { - matches!( - err, - BsonTeMarketDataError::TruncatedDocument { .. } - | BsonTeMarketDataError::CorruptDocumentLength { .. } - | BsonTeMarketDataError::CorruptBson { .. } - | BsonTeMarketDataError::CorruptPointBson { .. } - ) -} - -struct DecodedFxInputs { - eod_bars: Vec, - te_bars: Vec, - eod_docs_framed: u64, - eod_bytes_read: u64, - eod_decode: BsonEodDecodeStats, - eod_cad_forex_kept: usize, - eod_other_symbol_skipped: usize, - te_docs_framed: u64, - te_bytes_read: u64, - te_decode: BsonTeMarketDataDecodeStats, -} - -fn decode_all_inputs(args: &CurateFx1dArgs) -> Result { - decode_inputs_from_openers( - &args.eod_prices, - || { - File::open(&args.eod_prices).map_err(|source| RunCurateFxError::OpenInput { - label: "eod-prices", - path: args.eod_prices.clone(), - source, - }) - }, - &args.te_market_data, - || { - File::open(&args.te_market_data).map_err(|source| RunCurateFxError::OpenInput { - label: "te-market-data", - path: args.te_market_data.clone(), - source, - }) - }, - &args.te_symbol, - ) -} - -fn decode_inputs_from_openers( - eod_prices_path: &Path, - open_eod: FE, - te_market_data_path: &Path, - open_te: FT, - te_symbol: &str, -) -> Result -where - RE: io::Read, - FE: FnOnce() -> Result, - RT: io::Read, - FT: FnOnce() -> Result, -{ - // 1. Stream `eodPrices` and retain exact `CAD.FOREX` bars. - let eod_stream = open_eod()?; - let mut eod_reader = - RawBsonChunkReader::with_options(eod_stream, BsonStreamOptions::default()).map_err( - |source| RunCurateFxError::BsonStream { - label: "eod-prices", - path: eod_prices_path.to_path_buf(), - source, - }, - )?; - let mut eod_bars: Vec = Vec::new(); - let mut eod_cad_forex_kept = 0usize; - let mut eod_other_symbol_skipped = 0usize; - let mut eod_corrupt_err: Option<(u64, BsonEodPriceError)> = None; - - let eod_decode_res = decode_eod_price_chunks( - &mut eod_reader, - |raw| { - if raw.eod_search_code == EOD_CAD_FOREX_CODE { - eod_cad_forex_kept += 1; - eod_bars.push(FxDailyBar { - session_date: raw.session_date, - open: raw.open, - high: raw.high, - low: raw.low, - close: raw.close, - }); - } else { - eod_other_symbol_skipped += 1; - } - }, - |offset, err| { - if eod_corrupt_err.is_none() && is_structural_eod_bson_error(&err) { - eod_corrupt_err = Some((offset, err)); - } - }, - ); - if let Some((offset, source)) = eod_corrupt_err { - return Err(RunCurateFxError::CorruptEodBson { - path: eod_prices_path.to_path_buf(), - offset, - source, - }); - } - let eod_decode = eod_decode_res.map_err(|source| RunCurateFxError::BsonStream { - label: "eod-prices", - path: eod_prices_path.to_path_buf(), - source, - })?; - let eod_docs_framed = eod_reader.docs_framed(); - let eod_bytes_read = eod_reader.bytes_read(); - - // 2. Stream `teMarketData` and retain points for `te_symbol` (ASCII case-insensitive). - let te_stream = open_te()?; - let mut te_reader = - RawBsonChunkReader::with_options(te_stream, BsonStreamOptions::default()).map_err( - |source| RunCurateFxError::BsonStream { - label: "te-market-data", - path: te_market_data_path.to_path_buf(), - source, - }, - )?; - let mut te_bars: Vec = Vec::new(); - let mut te_corrupt_err: Option<(u64, BsonTeMarketDataError)> = None; - - let te_decode_res = decode_te_market_data_chunks( - &mut te_reader, - te_symbol, - |bar| { - te_bars.push(bar); - }, - |offset, err| { - if te_corrupt_err.is_none() && is_structural_te_bson_error(&err) { - te_corrupt_err = Some((offset, err)); - } - }, - ); - if let Some((offset, source)) = te_corrupt_err { - return Err(RunCurateFxError::CorruptTeBson { - path: te_market_data_path.to_path_buf(), - offset, - source, - }); - } - let te_decode = te_decode_res.map_err(|source| RunCurateFxError::BsonStream { - label: "te-market-data", - path: te_market_data_path.to_path_buf(), - source, - })?; - let te_docs_framed = te_reader.docs_framed(); - let te_bytes_read = te_reader.bytes_read(); - - if eod_bars.is_empty() && te_bars.is_empty() { - return Err(RunCurateFxError::NoDecodedBars { - eod_path: eod_prices_path.to_path_buf(), - te_path: te_market_data_path.to_path_buf(), - te_symbol: te_symbol.to_owned(), - }); - } - - Ok(DecodedFxInputs { - eod_bars, - te_bars, - eod_docs_framed, - eod_bytes_read, - eod_decode, - eod_cad_forex_kept, - eod_other_symbol_skipped, - te_docs_framed, - te_bytes_read, - te_decode, - }) -} - -/// Runs the end-to-end `curate-fx-1d` file-to-Parquet pipeline via [`curate_and_write_fx_1d`]. -/// -/// Any validation, I/O, BSON framing/corruption, zero-bar, or curation error returns before -/// touching `args.out_dir`, leaving any pre-existing `/fx_1d/part.parquet` -/// byte-identical. -pub fn run_curate_fx_1d(args: &CurateFx1dArgs) -> Result { - let start = Instant::now(); - validate_out_dir(&args.out_dir)?; - validate_te_symbol(&args.te_symbol)?; - - let decoded = decode_all_inputs(args)?; - finish_curate_fx_1d( - decoded, - &args.eod_prices, - &args.te_market_data, - &args.out_dir, - start, - ) -} - -/// Runs `curate-fx-1d` from arbitrary raw-BSON [`io::Read`] streams. -pub fn run_curate_fx_1d_with_readers( - eod_prices_input: (&Path, RE), - te_market_data_input: (&Path, RT), - te_symbol: &str, - out_dir: &Path, -) -> Result { - let start = Instant::now(); - validate_out_dir(out_dir)?; - validate_te_symbol(te_symbol)?; - - let (eod_path, eod_stream) = eod_prices_input; - let (te_path, te_stream) = te_market_data_input; - let decoded = decode_inputs_from_openers( - eod_path, - || Ok(eod_stream), - te_path, - || Ok(te_stream), - te_symbol, - )?; - finish_curate_fx_1d(decoded, eod_path, te_path, out_dir, start) -} - -fn finish_curate_fx_1d( - decoded: DecodedFxInputs, - eod_path: &Path, - te_path: &Path, - out_dir: &Path, - start: Instant, -) -> Result { - let write_report = curate_and_write_fx_1d( - out_dir, - &decoded.eod_bars, - &decoded.te_bars, - Fx1dWriteOptions::default(), - ) - .map_err(|source| RunCurateFxError::CurateWrite { - out_dir: out_dir.to_path_buf(), - source, - })?; - if write_report.curate_stats.rows_out == 0 { - return Err(RunCurateFxError::NoCuratedRows { - eod_path: eod_path.to_path_buf(), - te_path: te_path.to_path_buf(), - eod_bars_in: decoded.eod_cad_forex_kept, - te_bars_in: decoded.te_decode.points_decoded, - }); - } - - Ok(CurateFx1dRunReport { - eod_docs_framed: decoded.eod_docs_framed, - eod_bytes_read: decoded.eod_bytes_read, - eod_decode: decoded.eod_decode, - eod_cad_forex_kept: decoded.eod_cad_forex_kept, - eod_other_symbol_skipped: decoded.eod_other_symbol_skipped, - te_docs_framed: decoded.te_docs_framed, - te_bytes_read: decoded.te_bytes_read, - te_decode: decoded.te_decode, - curate_stats: write_report.curate_stats, - write_stats: write_report.write_stats, - elapsed_secs: start.elapsed().as_secs_f64(), - }) -} - -fn compute_rows_checksum(rows: &[Fx1dParquetRow]) -> u64 { - let mut hash = 0xcbf2_9ce4_8422_2325_u64; - let mix = |mut h: u64, v: u64| -> u64 { - h ^= v; - h = h.wrapping_mul(0x0000_0100_0000_01b3); - h - }; - let mix_str = |mut h: u64, s: &str| -> u64 { - h = mix(h, s.len() as u64); - for &b in s.as_bytes() { - h = mix(h, u64::from(b)); - } - h - }; - for row in rows { - hash = mix_str(hash, row.pair.as_ref()); - hash = mix(hash, row.session_date as u64); - hash = mix(hash, row.ts_micros as u64); - hash = mix(hash, row.open.to_bits()); - hash = mix(hash, row.high.to_bits()); - hash = mix(hash, row.low.to_bits()); - hash = mix(hash, row.close.to_bits()); - hash = mix_str(hash, row.source.as_ref()); - hash = mix(hash, row.known_at_micros as u64); - } - hash -} - -/// Stage-timed variant of [`run_curate_fx_1d`] used internally by `bench-curate-fx-cmd`. -/// -/// Separately times `decode` (both BSON streams), `curate` (`curate_fx_1d`), and `write` -/// (`write_fx_1d_dataset`), and computes a deterministic FNV-1a checksum over all 9 columns of -/// the curated rows. -pub(crate) fn run_curate_fx_1d_timed( - args: &CurateFx1dArgs, -) -> Result { - let total_start = Instant::now(); - validate_out_dir(&args.out_dir)?; - validate_te_symbol(&args.te_symbol)?; - - let decode_start = Instant::now(); - let decoded = decode_all_inputs(args)?; - let decode_elapsed_secs = decode_start.elapsed().as_secs_f64(); - - let curate_start = Instant::now(); - let curated = curate_fx_1d(&decoded.eod_bars, &decoded.te_bars).map_err(|source| { - RunCurateFxError::CurateWrite { - out_dir: args.out_dir.clone(), - source: CurateFxWriteError::Curate(source), - } - })?; - let curate_elapsed_secs = curate_start.elapsed().as_secs_f64(); - if curated.rows.is_empty() { - return Err(RunCurateFxError::NoCuratedRows { - eod_path: args.eod_prices.clone(), - te_path: args.te_market_data.clone(), - eod_bars_in: decoded.eod_cad_forex_kept, - te_bars_in: decoded.te_decode.points_decoded, - }); - } - - let checksum = compute_rows_checksum(&curated.rows); - - let write_start = Instant::now(); - let write_stats = - write_fx_1d_dataset(&args.out_dir, &curated.rows, Fx1dWriteOptions::default()).map_err( - |source| RunCurateFxError::CurateWrite { - out_dir: args.out_dir.clone(), - source: CurateFxWriteError::Parquet(source), - }, - )?; - let write_elapsed_secs = write_start.elapsed().as_secs_f64(); - - let report = CurateFx1dRunReport { - eod_docs_framed: decoded.eod_docs_framed, - eod_bytes_read: decoded.eod_bytes_read, - eod_decode: decoded.eod_decode, - eod_cad_forex_kept: decoded.eod_cad_forex_kept, - eod_other_symbol_skipped: decoded.eod_other_symbol_skipped, - te_docs_framed: decoded.te_docs_framed, - te_bytes_read: decoded.te_bytes_read, - te_decode: decoded.te_decode, - curate_stats: curated.stats, - write_stats, - elapsed_secs: total_start.elapsed().as_secs_f64(), - }; - - Ok(CurateFx1dTimedRun { - report, - decode_elapsed_secs, - curate_elapsed_secs, - write_elapsed_secs, - checksum, - }) -} - -/// Formats [`CurateFx1dRunReport`] into a deterministic machine-readable `key=value` summary. -/// -/// Only the final `timing:` line contains wall-clock time (`elapsed_secs`). -pub fn format_curate_fx_report(report: &CurateFx1dRunReport) -> String { - let b = &report.curate_stats.builder; - format!( - "curate-etl curate-fx-1d\n\ - \x20 eod_bson: docs_framed={} bytes_read={} docs_in={} decoded={} cad_forex_kept={} other_symbol_skipped={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={})\n\ - \x20 te_bson: docs_framed={} bytes_read={} docs_in={} matched={} other_symbol={} docs_rejected={} points_in={} points_decoded={} points_rejected={} (not_doc={} missing={} wrong_type={} non_finite={} date_oor={} corrupt={})\n\ - \x20 builder: eod_in={} eod_kept={} eod_invalid={} eod_inconsistent={} eod_dup_collapsed={} eod_dup_conflict={} te_in={} te_kept={} te_invalid={} te_inconsistent={} te_dup_collapsed={} te_dup_conflict={}\n\ - \x20 curate: rows_in={} rows_out={} eod_rows_out={} te_rows_out={} te_superseded={} overlap_checked={} within_tol={} mismatched={} max_overlap_rel={:.6}\n\ - \x20 write: files={} row_groups={} rows_written={} bytes_written={}\n\ - \x20 timing: elapsed_secs={:.6}", - report.eod_docs_framed, - report.eod_bytes_read, - report.eod_decode.docs_in, - report.eod_decode.decoded, - report.eod_cad_forex_kept, - report.eod_other_symbol_skipped, - report.eod_decode.rejected_total(), - report.eod_decode.rejected_missing_field, - report.eod_decode.rejected_empty_field, - report.eod_decode.rejected_wrong_type, - report.eod_decode.rejected_malformed_date, - report.eod_decode.rejected_invalid_number, - report.eod_decode.rejected_corrupt_document, - report.te_docs_framed, - report.te_bytes_read, - report.te_decode.docs_in, - report.te_decode.docs_matched, - report.te_decode.docs_other_symbol, - report.te_decode.docs_rejected_total(), - report.te_decode.points_in, - report.te_decode.points_decoded, - report.te_decode.rejected_total(), - report.te_decode.rejected_point_not_document, - report.te_decode.rejected_missing_field, - report.te_decode.rejected_wrong_type, - report.te_decode.rejected_non_finite, - report.te_decode.rejected_date_out_of_range, - report.te_decode.rejected_corrupt_point, - b.eod.rows_in, - b.eod.rows_kept, - b.eod.dropped_invalid_ohlc, - b.eod.dropped_inconsistent_ohlc, - b.eod.duplicate_collapsed, - b.eod.duplicate_conflict_dropped, - b.te.rows_in, - b.te.rows_kept, - b.te.dropped_invalid_ohlc, - b.te.dropped_inconsistent_ohlc, - b.te.duplicate_collapsed, - b.te.duplicate_conflict_dropped, - report.curate_stats.rows_in, - report.curate_stats.rows_out, - b.eod_rows_out, - b.te_rows_out, - b.te_superseded_by_eod, - b.overlap_checked, - b.overlap_within_tolerance, - b.overlap_mismatched, - b.max_overlap_rel, - report.write_stats.files_written, - report.write_stats.row_groups_written, - report.write_stats.rows_written, - report.write_stats.bytes_written, - report.elapsed_secs, - ) -} - -#[cfg(test)] -#[path = "run_curate_fx_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/run_curate_fx_1m.rs b/tools/curate-etl/src/run_curate_fx_1m.rs deleted file mode 100644 index 7c938c0b..00000000 --- a/tools/curate-etl/src/run_curate_fx_1m.rs +++ /dev/null @@ -1,555 +0,0 @@ -//! File-to-file `fx_1m` runner (`M2.3l`). -//! -//! Streams a concatenated raw BSON `eodIntraday1M` dump into per-shard QuestDB ILP v2 files -//! (`/fx_1m.shard-.ilp`) via [`crate::curate_fx_1m::curate_and_write_fx_1m_from_bson`]. -//! -//! # Global Sort, Deduplication & Memory Bound -//! - Calls [`curate_and_write_fx_1m_from_bson`] **once** over the entire input stream so timestamp -//! sorting and `ts` deduplication (bitwise-identical OHLC collapse vs. conflicting-group drop) -//! are global across all BSON stream chunks, then calls [`IlpShardedWriter::finish`] exactly -//! once after clean EOF. -//! - **Memory bound:** `Fx1mAccumulator::push` in `src/curate_fx_1m.rs` counts non-`CAD.FOREX` -//! rows in `dropped_wrong_code` and returns immediately without appending or allocating. Peak -//! memory is therefore bounded by: -//! - accepted `CAD.FOREX` rows (`Vec>`), -//! - the configured BSON stream chunk buffer (`BsonStreamOptions::chunk_capacity_bytes`, -//! growing only for a single document up to `max_doc_bytes`), and -//! - bounded ILP output batch buffers per shard (`IlpWriterOptions`) plus per-shard file -//! buffering in file mode. -//! -//! Non-`CAD.FOREX` rows from the full `eodIntraday1M` dump are never buffered. -//! - **Single-pair sharding:** every curated row carries `pair = "USDCAD"` and `source = "eod"`, -//! so [`IlpShardedWriter`] routes all rows deterministically to -//! `shard_for_fx_pair("USDCAD", shard_count)` while publishing all other shards as empty files. -//! - **Timestamp provenance:** preserves EODHD's UTC microsecond bar-start `ts` and CAD-per-USD -//! OHLC bits verbatim; bar-start `ts` alone does not establish when the bar's close was -//! observable. -//! - **Omitted framing counters:** [`CurateFx1mRunReport`] omits `intraday_docs_framed` and -//! `intraday_bytes_read` because [`curate_and_write_fx_1m_from_bson`] owns the underlying -//! `RawBsonChunkReader` internally and returns [`BsonEodIntradayDecodeStats`] only. -//! -//! # File Publication & Fail-Closed Guarantees -//! - Preflight scans `out_dir` for **any** pre-existing `fx_1m.shard-.ilp` file -//! (regardless of the requested `shard_count`) and fails closed before staging so stale shards -//! from a prior run cannot survive alongside a new export. -//! - Each shard writes into an exclusively created staging file in `out_dir` -//! (`.fx_1m.shard-..tmp`), flushes and `sync_all`s on `finish`, and publishes to -//! `fx_1m.shard-.ilp` via same-directory `hard_link` followed by removing the staged name -//! (preserving no-overwrite semantics even if a final file appears after preflight). -//! - Any error (validation, missing input, fatal BSON framing/I/O, ILP write/flush, or -//! publication collision) rolls back only final files created by this run, removes this run's -//! staging files, and leaves pre-existing files untouched. Per-document semantic decode errors -//! stay counted-and-skipped in [`BsonEodIntradayDecodeStats`]. - -use std::error::Error; -use std::fmt; -use std::fs::{self, File}; -use std::io::{self, Write}; -use std::path::{Path, PathBuf}; -use std::time::Instant; - -use crate::bson_eod_intraday::BsonEodIntradayDecodeStats; -use crate::bson_stream::{BsonStreamError, BsonStreamOptions}; -use crate::curate_fx_1m::{ - curate_and_write_fx_1m_from_bson, CurateFx1mBsonError, CurateFx1mStats, -}; -use crate::ilp::{ - IlpShardedWriter, IlpWriteStats, IlpWriterError, IlpWriterOptions, TABLE_FX_1M, -}; -use crate::parquet_bars::RollbackFailure; -use crate::parquet_publish::{next_run_id, StagingFileGuard}; -use crate::run_curate_bars_1m::{ - create_exclusive_shard_tmp_file_for_table, preflight_shard_out_dir, - publish_staged_shards_for_table, ShardPublishError, SyncedBufFile, -}; - -/// Arguments for [`run_curate_fx_1m`] and [`run_curate_fx_1m_with_readers`]. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct CurateFx1mArgs { - pub intraday_path: PathBuf, - pub out_dir: PathBuf, - pub shard_count: usize, - pub stream_options: BsonStreamOptions, - pub ilp_options: IlpWriterOptions, -} - -/// Full run report produced by [`run_curate_fx_1m`] and [`run_curate_fx_1m_with_readers`]. -/// -/// `intraday_docs_framed` and `intraday_bytes_read` are intentionally omitted because -/// [`curate_and_write_fx_1m_from_bson`] owns the underlying `RawBsonChunkReader` and returns -/// [`BsonEodIntradayDecodeStats`] only. -/// -/// Conservation invariants: -/// - `decode.docs_seen == decode.rows_decoded + decode.rejected_total()` -/// - `decode.rows_decoded == curate_stats.bars_in` -/// - `curate_stats.bars_in == curate_stats.rows_out + curate_stats.dropped_wrong_code + curate_stats.dropped_negative_ts + curate_stats.dropped_invalid_ohlc + curate_stats.dropped_high_below_bound + curate_stats.dropped_low_above_bound + curate_stats.duplicate_collapsed + curate_stats.duplicate_conflict_dropped` -/// - `rows_written == curate_stats.rows_out == ilp_stats.rows == ilp_stats.per_shard_rows.iter().sum::()` -#[derive(Debug, Clone, PartialEq)] -pub struct CurateFx1mRunReport { - pub decode: BsonEodIntradayDecodeStats, - pub curate_stats: CurateFx1mStats, - pub rows_written: usize, - pub ilp_stats: IlpWriteStats, - pub shard_count: usize, - pub elapsed_secs: f64, -} - -/// Typed errors returned by [`run_curate_fx_1m`] and [`run_curate_fx_1m_with_readers`]. -#[derive(Debug)] -pub enum RunCurateFx1mError { - /// `shard_count` was `0`. - ZeroShardCount, - /// Caller-supplied `IlpShardedWriter` shard count did not match `args.shard_count`. - ShardCountMismatch { expected: usize, actual: usize }, - /// Caller-supplied `IlpShardedWriter` already had queued or flushed rows before the run. - NonEmptyWriter { - flushed_rows: usize, - pending_rows: usize, - }, - /// `out_dir` exists and is not a directory. - InvalidOutDir { path: PathBuf, detail: String }, - /// A final shard output file (`fx_1m.shard-.ilp`) already existed. - OutputFileExists { path: PathBuf }, - /// Failed to open the input `eodIntraday1M` dump file. - OpenInput { - label: &'static str, - path: PathBuf, - source: io::Error, - }, - /// Fatal BSON framing, option validation, or I/O error while reading `eodIntraday1M`. - BsonStream { - label: &'static str, - path: PathBuf, - source: BsonStreamError, - }, - /// ILP writer initialization, per-row write, or final flush error. - Ilp(IlpWriterError), - /// Filesystem I/O error while creating, syncing, linking, or cleaning up shard files. - Io { path: PathBuf, source: io::Error }, - /// Publication or failure cleanup failed and removing one or more final or staging files also failed. - RollbackFailed { - cause: Box, - failures: Vec, - }, -} - -impl From for RunCurateFx1mError { - fn from(err: ShardPublishError) -> Self { - match err { - ShardPublishError::InvalidOutDir { path, detail } => { - Self::InvalidOutDir { path, detail } - } - ShardPublishError::OutputFileExists { path } => Self::OutputFileExists { path }, - ShardPublishError::Io { path, source } => Self::Io { path, source }, - ShardPublishError::RollbackFailed { cause, failures } => Self::RollbackFailed { - cause: Box::new((*cause).into()), - failures, - }, - } - } -} - -impl fmt::Display for RunCurateFx1mError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::ZeroShardCount => write!(f, "shard_count must be >= 1"), - Self::ShardCountMismatch { expected, actual } => write!( - f, - "ILP writer shard count mismatch: expected {expected}, got {actual}" - ), - Self::NonEmptyWriter { - flushed_rows, - pending_rows, - } => write!( - f, - "ILP writer must be fresh before running fx_1m (found {flushed_rows} flushed and {pending_rows} pending rows)" - ), - Self::InvalidOutDir { path, detail } => { - write!(f, "invalid out_dir '{}': {detail}", path.display()) - } - Self::OutputFileExists { path } => write!( - f, - "refusing to overwrite existing output file '{}'", - path.display() - ), - Self::OpenInput { - label, - path, - source, - } => write!(f, "failed to open {label} '{}': {source}", path.display()), - Self::BsonStream { - label, - path, - source, - } => write!(f, "failed reading {label} '{}': {source}", path.display()), - Self::Ilp(err) => write!(f, "fx_1m ILP writer failed: {err}"), - Self::Io { path, source } => { - write!(f, "I/O error on '{}': {source}", path.display()) - } - Self::RollbackFailed { cause, failures } => { - write!(f, "{cause}; rollback also failed for: ")?; - for (i, failure) in failures.iter().enumerate() { - if i > 0 { - write!(f, ", ")?; - } - write!(f, "{failure}")?; - } - Ok(()) - } - } - } -} - -impl Error for RunCurateFx1mError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::OpenInput { source, .. } | Self::Io { source, .. } => Some(source), - Self::BsonStream { source, .. } => Some(source), - Self::Ilp(err) => Some(err), - Self::RollbackFailed { cause, .. } => Some(cause.as_ref()), - Self::ZeroShardCount - | Self::ShardCountMismatch { .. } - | Self::NonEmptyWriter { .. } - | Self::InvalidOutDir { .. } - | Self::OutputFileExists { .. } => None, - } - } -} - -fn validate_common_args(args: &CurateFx1mArgs) -> Result<(), RunCurateFx1mError> { - if args.shard_count == 0 { - return Err(RunCurateFx1mError::ZeroShardCount); - } - args.stream_options - .validate() - .map_err(|source| RunCurateFx1mError::BsonStream { - label: "eod-intraday", - path: args.intraday_path.clone(), - source, - })?; - Ok(()) -} - -fn validate_file_mode_args(args: &CurateFx1mArgs) -> Result<(), RunCurateFx1mError> { - validate_common_args(args)?; - if args.ilp_options.max_batch_bytes == 0 { - return Err(RunCurateFx1mError::Ilp(IlpWriterError::ZeroMaxBatchBytes)); - } - if args.ilp_options.max_batch_rows == 0 { - return Err(RunCurateFx1mError::Ilp(IlpWriterError::ZeroMaxBatchRows)); - } - preflight_shard_out_dir(&args.out_dir, TABLE_FX_1M)?; - Ok(()) -} - -fn run_curate_fx_1m_with_readers_inner( - args: &CurateFx1mArgs, - intraday: R, - mut writer: IlpShardedWriter, - start: Instant, -) -> Result -where - R: io::Read, - W: Write + Send, -{ - let bson_report = - curate_and_write_fx_1m_from_bson(intraday, args.stream_options, &mut writer).map_err( - |err| match err { - CurateFx1mBsonError::Stream(source) => RunCurateFx1mError::BsonStream { - label: "eod-intraday", - path: args.intraday_path.clone(), - source, - }, - CurateFx1mBsonError::Write(err) => RunCurateFx1mError::Ilp(err), - }, - )?; - - let ilp_stats = writer.finish().map_err(RunCurateFx1mError::Ilp)?; - - Ok(CurateFx1mRunReport { - decode: bson_report.decode_stats, - curate_stats: bson_report.write_report.curate_stats, - rows_written: bson_report.write_report.rows_written, - ilp_stats, - shard_count: args.shard_count, - elapsed_secs: start.elapsed().as_secs_f64(), - }) -} - -/// Runs the `fx_1m` curation pipeline from an arbitrary [`io::Read`] stream into a caller-owned -/// [`IlpShardedWriter`]. -/// -/// Validates `args`, writer shard-count agreement, and that `writer` is fresh (zero queued or -/// flushed rows) before reading `intraday`. Calls [`curate_and_write_fx_1m_from_bson`] once over -/// the entire stream for global sort and `ts` deduplication, and calls [`IlpShardedWriter::finish`] -/// exactly once after clean EOF. -pub fn run_curate_fx_1m_with_readers( - args: &CurateFx1mArgs, - intraday: R, - writer: IlpShardedWriter, -) -> Result -where - R: io::Read, - W: Write + Send, -{ - let start = Instant::now(); - validate_common_args(args)?; - if writer.shard_count() != args.shard_count { - return Err(RunCurateFx1mError::ShardCountMismatch { - expected: args.shard_count, - actual: writer.shard_count(), - }); - } - let (flushed_rows, pending_rows) = writer.row_counts(); - if flushed_rows > 0 || pending_rows > 0 { - return Err(RunCurateFx1mError::NonEmptyWriter { - flushed_rows, - pending_rows, - }); - } - - run_curate_fx_1m_with_readers_inner(args, intraday, writer, start) -} - -pub(crate) fn cleanup_armed_staged_shards( - staged: &mut [(PathBuf, StagingFileGuard)], - remove_file: &mut RF, -) -> Vec -where - RF: FnMut(&Path) -> io::Result<()>, -{ - let mut failures = Vec::new(); - for (tmp_path, guard) in staged.iter_mut() { - if !guard.is_armed() { - continue; - } - match remove_file(tmp_path) { - Ok(()) => guard.disarm(), - Err(err) if err.kind() == io::ErrorKind::NotFound => guard.disarm(), - Err(source) => { - guard.disarm(); - failures.push(RollbackFailure { - final_path: tmp_path.clone(), - backup_path: None, - source, - }); - } - } - } - failures -} - -fn fail_with_staging_cleanup( - cause: RunCurateFx1mError, - staged: &mut [(PathBuf, StagingFileGuard)], - remove_file: &mut RF, -) -> RunCurateFx1mError -where - RF: FnMut(&Path) -> io::Result<()>, -{ - let staging_failures = cleanup_armed_staged_shards(staged, remove_file); - if staging_failures.is_empty() { - return cause; - } - match cause { - RunCurateFx1mError::RollbackFailed { - cause: inner_cause, - mut failures, - } => { - failures.extend(staging_failures); - RunCurateFx1mError::RollbackFailed { - cause: inner_cause, - failures, - } - } - other => RunCurateFx1mError::RollbackFailed { - cause: Box::new(other), - failures: staging_failures, - }, - } -} - -/// Private file-mode seam accepting an injected reader, sink factory, pre-link hook, and staging -/// unlink hook so tests can exercise staging, writer failure, publication rollback, and staging -/// unlink failure reporting deterministically. -fn run_curate_fx_1m_to_dir_with_cleanup_hook( - args: &CurateFx1mArgs, - intraday: R, - mut make_sink: SF, - before_link: BL, - mut remove_staged_file: RF, -) -> Result -where - R: io::Read, - W: Write + Send, - SF: FnMut(usize, File) -> W, - BL: FnMut(usize, &Path), - RF: FnMut(&Path) -> io::Result<()>, -{ - let start = Instant::now(); - validate_file_mode_args(args)?; - - fs::create_dir_all(&args.out_dir).map_err(|source| RunCurateFx1mError::Io { - path: args.out_dir.clone(), - source, - })?; - - let run_id = next_run_id(); - let mut staged: Vec<(PathBuf, StagingFileGuard)> = Vec::with_capacity(args.shard_count); - let mut sinks: Vec = Vec::with_capacity(args.shard_count); - for shard_idx in 0..args.shard_count { - let (tmp_path, file) = match create_exclusive_shard_tmp_file_for_table( - &args.out_dir, - TABLE_FX_1M, - shard_idx, - &run_id, - ) { - Ok(pair) => pair, - Err(err) => { - drop(sinks); - return Err(fail_with_staging_cleanup( - err.into(), - &mut staged, - &mut remove_staged_file, - )); - } - }; - let guard = StagingFileGuard::new(tmp_path.clone()); - staged.push((tmp_path, guard)); - sinks.push(make_sink(shard_idx, file)); - } - - let writer = match IlpShardedWriter::new(sinks, args.ilp_options) { - Ok(writer) => writer, - Err(err) => { - return Err(fail_with_staging_cleanup( - RunCurateFx1mError::Ilp(err), - &mut staged, - &mut remove_staged_file, - )); - } - }; - let report = match run_curate_fx_1m_with_readers_inner(args, intraday, writer, start) { - Ok(report) => report, - Err(err) => { - return Err(fail_with_staging_cleanup( - err, - &mut staged, - &mut remove_staged_file, - )); - } - }; - - if let Err(err) = - publish_staged_shards_for_table(&args.out_dir, TABLE_FX_1M, &mut staged, before_link) - { - return Err(fail_with_staging_cleanup( - err.into(), - &mut staged, - &mut remove_staged_file, - )); - } - Ok(report) -} - -/// Private file-mode seam accepting an injected reader, sink factory, and pre-link hook so tests -/// can exercise staging, writer failure, and post-preflight publication rollback through the exact -/// file publication path. -fn run_curate_fx_1m_to_dir_with_hooks( - args: &CurateFx1mArgs, - intraday: R, - make_sink: SF, - before_link: BL, -) -> Result -where - R: io::Read, - W: Write + Send, - SF: FnMut(usize, File) -> W, - BL: FnMut(usize, &Path), -{ - run_curate_fx_1m_to_dir_with_cleanup_hook( - args, - intraday, - make_sink, - before_link, - |path| fs::remove_file(path), - ) -} - -/// Runs the file-to-file `fx_1m` curation pipeline, publishing exactly `args.shard_count` QuestDB -/// ILP v2 files (`/fx_1m.shard-.ilp`). -pub fn run_curate_fx_1m(args: &CurateFx1mArgs) -> Result { - validate_file_mode_args(args)?; - - let intraday_file = File::open(&args.intraday_path).map_err(|source| { - RunCurateFx1mError::OpenInput { - label: "eod-intraday", - path: args.intraday_path.clone(), - source, - } - })?; - - run_curate_fx_1m_to_dir_with_hooks( - args, - intraday_file, - |_shard_idx, file| SyncedBufFile::new(file), - |_shard_idx, _final_path| {}, - ) -} - -/// Formats [`CurateFx1mRunReport`] into a deterministic machine-readable `key=value` summary. -/// -/// Only the final `timing:` line contains wall-clock time (`elapsed_secs`). -pub fn format_curate_fx_1m_report(report: &CurateFx1mRunReport) -> String { - let per_shard = if report.ilp_stats.per_shard_rows.is_empty() { - "none".to_string() - } else { - report - .ilp_stats - .per_shard_rows - .iter() - .enumerate() - .map(|(idx, count)| format!("{idx:02}={count}")) - .collect::>() - .join(",") - }; - - let d = &report.decode; - let c = &report.curate_stats; - - format!( - "curate-etl curate-fx-1m\n\ - \x20 intraday_bson: docs_seen={} rows_decoded={} rejected={} (missing={} empty={} wrong_type={} invalid_ts={} invalid_num={} corrupt={})\n\ - \x20 curate: bars_in={} rows_out={} wrong_code={} negative_ts={} invalid_ohlc={} high_below_bound={} low_above_bound={} dup_collapsed={} dup_conflict_dropped={}\n\ - \x20 ilp: shards={} rows_written={} ilp_rows={} bytes={} flushes={} per_shard_rows={per_shard}\n\ - \x20 timing: elapsed_secs={:.6}", - d.docs_seen, - d.rows_decoded, - d.rejected_total(), - d.rejected_missing_field, - d.rejected_empty_field, - d.rejected_wrong_type, - d.rejected_invalid_timestamp, - d.rejected_invalid_number, - d.rejected_corrupt_document, - c.bars_in, - c.rows_out, - c.dropped_wrong_code, - c.dropped_negative_ts, - c.dropped_invalid_ohlc, - c.dropped_high_below_bound, - c.dropped_low_above_bound, - c.duplicate_collapsed, - c.duplicate_conflict_dropped, - report.shard_count, - report.rows_written, - report.ilp_stats.rows, - report.ilp_stats.bytes, - report.ilp_stats.flushes, - report.elapsed_secs, - ) -} - -#[cfg(test)] -#[path = "run_curate_fx_1m_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/run_curate_fx_1m_tests.rs b/tools/curate-etl/src/run_curate_fx_1m_tests.rs deleted file mode 100644 index b35a7e34..00000000 --- a/tools/curate-etl/src/run_curate_fx_1m_tests.rs +++ /dev/null @@ -1,1728 +0,0 @@ -use std::error::Error; -use std::fs; -use std::io::{self, Cursor, Write}; -use std::path::{Path, PathBuf}; - -use bson::raw::{cstr, RawDocumentBuf}; - -use super::*; -use crate::bson_eod_intraday::decode_eod_intraday_buffer; -use crate::bson_stream::{RawBsonChunkReader, MIN_BSON_DOC_BYTES}; -use crate::curate_fx_1m::{curate_and_write_fx_1m, FX_1M_SOURCE_EOD}; -use crate::fx::FX_PAIR_USDCAD; -use crate::ilp::{shard_for_fx_pair, ILP_V2_DOUBLE_TYPE, TABLE_FX_1M}; -use crate::run_curate_bars_1m::tests::TempDirGuard; -use crate::run_curate_fx::EOD_CAD_FOREX_CODE; - -fn make_intraday_doc( - code: &str, - timestamp_sec: i64, - open: f64, - high: f64, - low: f64, - close: f64, - volume: f64, -) -> RawDocumentBuf { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), code); - doc.append(cstr!("timestamp"), timestamp_sec); - doc.append(cstr!("open"), open); - doc.append(cstr!("high"), high); - doc.append(cstr!("low"), low); - doc.append(cstr!("close"), close); - doc.append(cstr!("volume"), volume); - doc -} - -fn make_malformed_missing_open_doc(code: &str, timestamp_sec: i64) -> RawDocumentBuf { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), code); - doc.append(cstr!("timestamp"), timestamp_sec); - doc.append(cstr!("high"), 1.3755_f64); - doc.append(cstr!("low"), 1.3745_f64); - doc.append(cstr!("close"), 1.3752_f64); - doc.append(cstr!("volume"), 0.0_f64); - doc -} - -fn concat_docs(docs: &[RawDocumentBuf]) -> Vec { - let mut out = Vec::new(); - for doc in docs { - out.extend_from_slice(doc.as_bytes()); - } - out -} - -fn make_args( - intraday_path: PathBuf, - out_dir: PathBuf, - shard_count: usize, - stream_options: BsonStreamOptions, -) -> CurateFx1mArgs { - CurateFx1mArgs { - intraday_path, - out_dir, - shard_count, - stream_options, - ilp_options: IlpWriterOptions::default(), - } -} - -fn list_dir_names(dir: &Path) -> Vec { - if !dir.exists() { - return Vec::new(); - } - let mut names: Vec = fs::read_dir(dir) - .expect("read_dir") - .map(|entry| { - entry - .expect("dir entry") - .file_name() - .to_string_lossy() - .into_owned() - }) - .collect(); - names.sort(); - names -} - -#[derive(Debug, Clone, PartialEq)] -struct DecodedIlpFx1m { - pair: String, - source: String, - open: f64, - high: f64, - low: f64, - close: f64, - ts: i64, -} - -/// Decodes QuestDB ILP v2 `fx_1m` records respecting fixed-width 8-byte binary `DOUBLE` payloads -/// (`==\x10<8 LE bytes>`) so embedded `0x0a` bytes inside doubles never split rows. -fn decode_ilp_fx_1m(data: &[u8]) -> Vec { - let mut rows = Vec::new(); - let mut i = 0usize; - let len = data.len(); - - while i < len { - let tag_start = i; - while i < len { - match data[i] { - b'\\' => { - assert!(i + 1 < len, "dangling backslash in ILP tag set"); - i += 2; - } - b' ' => break, - _ => i += 1, - } - } - assert!(i < len && data[i] == b' ', "missing space after ILP tag set"); - let tag_str = std::str::from_utf8(&data[tag_start..i]).expect("valid UTF-8 tag set"); - i += 1; - - let mut tags = tag_str.split(','); - assert_eq!(tags.next(), Some(TABLE_FX_1M), "expected fx_1m table"); - let pair_tag = tags.next().expect("pair tag"); - let source_tag = tags.next().expect("source tag"); - assert!(tags.next().is_none(), "unexpected extra ILP tag"); - - let pair = pair_tag - .strip_prefix("pair=") - .expect("pair= prefix") - .to_string(); - let source = source_tag - .strip_prefix("source=") - .expect("source= prefix") - .to_string(); - - let read_bin_f64 = |pos: &mut usize, name: &str| -> f64 { - let prefix = format!("{name}=="); - assert!( - data[*pos..].starts_with(prefix.as_bytes()), - "expected field prefix '{prefix}' at offset {}", - *pos - ); - *pos += prefix.len(); - assert_eq!( - data[*pos], ILP_V2_DOUBLE_TYPE, - "expected binary DOUBLE type tag for '{name}'" - ); - *pos += 1; - let bytes: [u8; 8] = data[*pos..*pos + 8] - .try_into() - .expect("8 bytes for binary double"); - *pos += 8; - f64::from_le_bytes(bytes) - }; - - let open = read_bin_f64(&mut i, "open"); - assert_eq!(data[i], b','); - i += 1; - let high = read_bin_f64(&mut i, "high"); - assert_eq!(data[i], b','); - i += 1; - let low = read_bin_f64(&mut i, "low"); - assert_eq!(data[i], b','); - i += 1; - let close = read_bin_f64(&mut i, "close"); - assert_eq!(data[i], b' ', "missing space after close field"); - i += 1; - - let ts_start = i; - while i < len && data[i] != b'\n' { - i += 1; - } - assert!(i < len && data[i] == b'\n', "missing trailing LF"); - let ts_str = std::str::from_utf8(&data[ts_start..i]).expect("valid UTF-8 ts"); - let ts: i64 = ts_str - .strip_suffix('t') - .expect("ts trailing t") - .parse() - .expect("i64 ts"); - i += 1; - - rows.push(DecodedIlpFx1m { - pair, - source, - open, - high, - low, - close, - ts, - }); - } - - rows -} - -fn assert_report_conservation(report: &CurateFx1mRunReport) { - let d = &report.decode; - assert_eq!( - d.docs_seen, - d.rows_decoded + d.rejected_total(), - "decode conservation failed: {d:?}" - ); - - let c = &report.curate_stats; - assert_eq!( - d.rows_decoded, c.bars_in, - "rows_decoded != curate_stats.bars_in" - ); - assert_eq!( - c.bars_in, - c.rows_out - + c.dropped_wrong_code - + c.dropped_negative_ts - + c.dropped_invalid_ohlc - + c.dropped_high_below_bound - + c.dropped_low_above_bound - + c.duplicate_collapsed - + c.duplicate_conflict_dropped, - "curate_stats conservation failed: {c:?}" - ); - assert_eq!(report.rows_written, c.rows_out, "rows_written != rows_out"); - assert_eq!( - report.rows_written, report.ilp_stats.rows, - "rows_written != ilp_stats.rows" - ); - assert_eq!( - report.ilp_stats.per_shard_rows.iter().sum::(), - report.ilp_stats.rows, - "sum(per_shard_rows) != ilp_stats.rows" - ); - assert_eq!(report.ilp_stats.per_shard_rows.len(), report.shard_count); -} - -struct FailingWriteSink { - fail_on_write: bool, - fail_on_flush: bool, -} - -impl Write for FailingWriteSink { - fn write(&mut self, buf: &[u8]) -> io::Result { - if self.fail_on_write { - Err(io::Error::new(io::ErrorKind::BrokenPipe, "injected write failure")) - } else { - Ok(buf.len()) - } - } - - fn flush(&mut self) -> io::Result<()> { - if self.fail_on_flush { - Err(io::Error::new(io::ErrorKind::BrokenPipe, "injected flush failure")) - } else { - Ok(()) - } - } -} - -#[test] -fn happy_path_matches_curate_and_write_fx_1m_bytes_and_preserves_conservation() { - let dir = TempDirGuard::new("fx1m-happy"); - let ts1 = 1_717_971_300_i64; // 2024-06-09 22:15:00 UTC - let ts2 = 1_717_971_360_i64; - let ts3 = 1_717_988_400_i64; - - let docs = vec![ - // Out-of-order valid CAD.FOREX bars - make_intraday_doc(EOD_CAD_FOREX_CODE, ts3, 1.37654321, 1.37712345, 1.37611111, 1.37689012, 0.0), - make_intraday_doc("AAPL.US", ts1, 195.0, 196.0, 194.5, 195.5, 1000.0), - make_malformed_missing_open_doc(EOD_CAD_FOREX_CODE, ts1 + 10), - make_intraday_doc(EOD_CAD_FOREX_CODE, ts1, 1.3750, 1.3755, 1.3745, 1.3752, 5.0), - make_intraday_doc("cad.forex", ts2, 1.3750, 1.3755, 1.3745, 1.3752, 0.0), - make_intraday_doc(EOD_CAD_FOREX_CODE, ts2, 1.3752, 1.3760, 1.3750, 1.3758, 12.0), - // Valid BSON bar that fails FX builder high-below-bound rule - make_intraday_doc(EOD_CAD_FOREX_CODE, ts3 + 60, 1.3800, 1.3750, 1.3700, 1.3720, 0.0), - // Valid BSON bar that fails FX builder low-above-bound rule - make_intraday_doc(EOD_CAD_FOREX_CODE, ts3 + 120, 1.3700, 1.3800, 1.3750, 1.3780, 0.0), - ]; - let intraday_bytes = concat_docs(&docs); - let intraday_path = dir.path().join("eodIntraday1M.bson"); - fs::write(&intraday_path, &intraday_bytes).unwrap(); - - // Run file-mode runner with 4 shards. - let out_dir = dir.path().join("out"); - let args = make_args( - intraday_path, - out_dir.clone(), - 4, - BsonStreamOptions::default(), - ); - let report = run_curate_fx_1m(&args).expect("happy-path run should succeed"); - assert_report_conservation(&report); - - assert_eq!(report.decode.docs_seen, 8); - assert_eq!(report.decode.rows_decoded, 7); - assert_eq!(report.decode.rejected_missing_field, 1); - assert_eq!(report.curate_stats.bars_in, 7); - assert_eq!(report.curate_stats.rows_out, 3); - assert_eq!(report.curate_stats.dropped_wrong_code, 2); - assert_eq!(report.curate_stats.dropped_high_below_bound, 1); - assert_eq!(report.curate_stats.dropped_low_above_bound, 1); - assert_eq!(report.rows_written, 3); - - // Reference output from `curate_and_write_fx_1m` on the fixture's decoded bars. - let mut ref_sinks = [Vec::new(), Vec::new(), Vec::new(), Vec::new()]; - let mut ref_writer = IlpShardedWriter::new( - ref_sinks.iter_mut().collect(), - IlpWriterOptions::default(), - ) - .unwrap(); - let mut decoded_bars = Vec::new(); - let ref_decode = decode_eod_intraday_buffer( - &intraday_bytes, - |raw| decoded_bars.push(raw), - |_offset, _err| {}, - ); - assert_eq!(ref_decode, report.decode); - let ref_write = curate_and_write_fx_1m(decoded_bars, &mut ref_writer).unwrap(); - let ref_ilp = ref_writer.finish().unwrap(); - assert_eq!(ref_write.curate_stats, report.curate_stats); - assert_eq!(ref_write.rows_written, report.rows_written); - assert_eq!(ref_ilp, report.ilp_stats); - - let mut total_file_bytes = 0usize; - let mut all_decoded = Vec::new(); - for (shard_idx, expected_bytes) in ref_sinks.iter().enumerate() { - let path = out_dir.join(format!("fx_1m.shard-{shard_idx:02}.ilp")); - let file_bytes = fs::read(&path).expect("read shard file"); - assert_eq!( - &file_bytes, expected_bytes, - "shard {shard_idx:02} bytes differ from curate_and_write_fx_1m" - ); - total_file_bytes += file_bytes.len(); - all_decoded.extend(decode_ilp_fx_1m(&file_bytes)); - } - assert_eq!(total_file_bytes, report.ilp_stats.bytes); - - // Verify decoded fields, ascending ts, and exact OHLC bits. - assert_eq!(all_decoded.len(), 3); - let expected = [ - (ts1 * 1_000_000, 1.3750_f64, 1.3755_f64, 1.3745_f64, 1.3752_f64), - (ts2 * 1_000_000, 1.3752_f64, 1.3760_f64, 1.3750_f64, 1.3758_f64), - (ts3 * 1_000_000, 1.37654321_f64, 1.37712345_f64, 1.37611111_f64, 1.37689012_f64), - ]; - for (row, (ts, o, h, l, c)) in all_decoded.iter().zip(expected) { - assert_eq!(row.pair, FX_PAIR_USDCAD); - assert_eq!(row.source, FX_1M_SOURCE_EOD); - assert_eq!(row.ts, ts); - assert_eq!(row.open.to_bits(), o.to_bits()); - assert_eq!(row.high.to_bits(), h.to_bits()); - assert_eq!(row.low.to_bits(), l.to_bits()); - assert_eq!(row.close.to_bits(), c.to_bits()); - } - for pair in all_decoded.windows(2) { - assert!(pair[0].ts < pair[1].ts, "rows not strictly ascending by ts"); - } -} - -#[test] -fn cross_chunk_global_dedup_collapses_identical_and_drops_conflicts() { - let ts_collapse = 1_718_000_000_i64; - let ts_conflict = 1_718_000_060_i64; - let ts_unique = 1_718_000_120_i64; - - let docs = vec![ - // Chunk 1: first copy of collapse + first copy of conflict - make_intraday_doc(EOD_CAD_FOREX_CODE, ts_collapse, 1.3700, 1.3710, 1.3690, 1.3705, 0.0), - make_intraday_doc(EOD_CAD_FOREX_CODE, ts_conflict, 1.3705, 1.3715, 1.3700, 1.3710, 0.0), - // Intervening filler docs to push second copies into later chunks - make_intraday_doc("MSFT.US", ts_unique, 420.0, 421.0, 419.0, 420.5, 500.0), - make_intraday_doc(EOD_CAD_FOREX_CODE, ts_unique, 1.3710, 1.3720, 1.3705, 1.3715, 0.0), - // Later chunks: identical duplicate of ts_collapse + conflicting duplicate of ts_conflict - make_intraday_doc(EOD_CAD_FOREX_CODE, ts_collapse, 1.3700, 1.3710, 1.3690, 1.3705, 99.0), - make_intraday_doc(EOD_CAD_FOREX_CODE, ts_conflict, 1.3705, 1.3715, 1.3700, 1.3712, 0.0), - ]; - let intraday_bytes = concat_docs(&docs); - let doc_size = docs[0].as_bytes().len(); - - // Force at most 1 document per chunk so every document sits in its own BSON chunk. - let tiny_opts = BsonStreamOptions { - chunk_capacity_bytes: doc_size, - ..BsonStreamOptions::default() - }; - - // Explicitly verify that the duplicate pairs occupy distinct BSON chunks. - let mut chunk_reader = - RawBsonChunkReader::with_options(Cursor::new(&intraday_bytes), tiny_opts).unwrap(); - let mut chunk_idx = 0usize; - let mut collapse_chunks = Vec::new(); - let mut conflict_chunks = Vec::new(); - while let Some(chunk) = chunk_reader.next_chunk().unwrap() { - decode_eod_intraday_buffer( - chunk.bytes, - |raw| { - if raw.ts == ts_collapse * 1_000_000 { - collapse_chunks.push(chunk_idx); - } else if raw.ts == ts_conflict * 1_000_000 { - conflict_chunks.push(chunk_idx); - } - }, - |_offset, _err| {}, - ); - chunk_idx += 1; - } - assert!( - chunk_idx >= 5, - "expected >= 5 chunks for 6 docs with tiny chunk_capacity_bytes={doc_size}, got {chunk_idx}" - ); - assert_eq!(collapse_chunks.len(), 2); - assert_ne!( - collapse_chunks[0], collapse_chunks[1], - "identical duplicates must sit in distinct BSON chunks" - ); - assert_eq!(conflict_chunks.len(), 2); - assert_ne!( - conflict_chunks[0], conflict_chunks[1], - "conflicting duplicates must sit in distinct BSON chunks" - ); - - let mut sink = Vec::new(); - let writer = IlpShardedWriter::new(vec![&mut sink], IlpWriterOptions::default()).unwrap(); - let args = make_args( - PathBuf::from("in-memory-eodIntraday1M.bson"), - PathBuf::from("unused-out"), - 1, - tiny_opts, - ); - - let report = run_curate_fx_1m_with_readers(&args, Cursor::new(&intraday_bytes), writer) - .expect("cross-chunk dedup run should succeed"); - assert_report_conservation(&report); - assert_eq!(report.curate_stats.bars_in, 6); - assert_eq!(report.curate_stats.dropped_wrong_code, 1); - assert_eq!(report.curate_stats.duplicate_collapsed, 1); - assert_eq!(report.curate_stats.duplicate_conflict_dropped, 2); - assert_eq!(report.curate_stats.rows_out, 2); - assert_eq!(report.rows_written, 2); - - let decoded = decode_ilp_fx_1m(&sink); - assert_eq!(decoded.len(), 2); - assert_eq!(decoded[0].ts, ts_collapse * 1_000_000); - assert_eq!(decoded[0].close.to_bits(), 1.3705_f64.to_bits()); - assert_eq!(decoded[1].ts, ts_unique * 1_000_000); - assert_eq!(decoded[1].close.to_bits(), 1.3715_f64.to_bits()); -} - -#[test] -fn shuffled_input_produces_byte_identical_shards_and_identical_report() { - let dir = TempDirGuard::new("fx1m-shuffle"); - let ts1 = 1_718_100_000_i64; - let ts2 = 1_718_100_060_i64; - let ts3 = 1_718_100_120_i64; - let ts4 = 1_718_100_180_i64; - - let docs = vec![ - make_intraday_doc(EOD_CAD_FOREX_CODE, ts1, 1.3600, 1.3610, 1.3595, 1.3605, 0.0), - make_intraday_doc(EOD_CAD_FOREX_CODE, ts1, 1.3600, 1.3610, 1.3595, 1.3605, 10.0), - make_intraday_doc(EOD_CAD_FOREX_CODE, ts2, 1.3605, 1.3615, 1.3600, 1.3610, 0.0), - make_intraday_doc(EOD_CAD_FOREX_CODE, ts2, 1.3605, 1.3615, 1.3600, 1.3611, 0.0), - make_intraday_doc(EOD_CAD_FOREX_CODE, ts3, 1.3610, 1.3620, 1.3605, 1.3615, 0.0), - make_intraday_doc("NVDA.US", ts3, 120.0, 121.0, 119.0, 120.5, 1000.0), - make_intraday_doc(EOD_CAD_FOREX_CODE, ts4, 1.3615, 1.3625, 1.3610, 1.3620, 0.0), - make_malformed_missing_open_doc(EOD_CAD_FOREX_CODE, ts4 + 60), - ]; - // Deterministic permutation. - let perm = [6, 3, 7, 1, 5, 0, 4, 2]; - let shuffled_docs: Vec = perm.iter().map(|&idx| docs[idx].clone()).collect(); - - let in_a = dir.path().join("in_a.bson"); - let in_b = dir.path().join("in_b.bson"); - fs::write(&in_a, concat_docs(&docs)).unwrap(); - fs::write(&in_b, concat_docs(&shuffled_docs)).unwrap(); - - let tiny_opts = BsonStreamOptions { - chunk_capacity_bytes: docs[0].as_bytes().len() * 2, - ..BsonStreamOptions::default() - }; - - let run = |input: PathBuf, out_name: &str| { - let out_dir = dir.path().join(out_name); - let args = make_args(input, out_dir.clone(), 4, tiny_opts); - let report = run_curate_fx_1m(&args).expect("run should succeed"); - let files: Vec<(String, Vec)> = list_dir_names(&out_dir) - .into_iter() - .map(|name| { - let bytes = fs::read(out_dir.join(&name)).unwrap(); - (name, bytes) - }) - .collect(); - (report, files) - }; - - let (mut r_a, f_a) = run(in_a, "out_a"); - let (mut r_b, f_b) = run(in_b, "out_b"); - assert_report_conservation(&r_a); - assert_eq!(f_a, f_b, "shuffled input produced different shard bytes"); - - r_a.elapsed_secs = 0.0; - r_b.elapsed_secs = 0.0; - assert_eq!(r_a, r_b, "shuffled input produced different report counters"); -} - -#[test] -fn shard_file_sets_for_one_and_four_shards_route_usdcad_deterministically() { - let dir = TempDirGuard::new("fx1m-shards"); - let intraday_path = dir.path().join("eodIntraday1M.bson"); - fs::write( - &intraday_path, - concat_docs(&[ - make_intraday_doc(EOD_CAD_FOREX_CODE, 1_718_200_000, 1.3700, 1.3710, 1.3690, 1.3705, 0.0), - make_intraday_doc(EOD_CAD_FOREX_CODE, 1_718_200_060, 1.3705, 1.3715, 1.3700, 1.3710, 0.0), - ]), - ) - .unwrap(); - - // 1 shard: all USDCAD rows land in shard 00. - assert_eq!(shard_for_fx_pair(FX_PAIR_USDCAD, 1), 0); - let out1 = dir.path().join("out-1"); - let rep1 = run_curate_fx_1m(&make_args( - intraday_path.clone(), - out1.clone(), - 1, - BsonStreamOptions::default(), - )) - .unwrap(); - assert_report_conservation(&rep1); - assert_eq!(list_dir_names(&out1), vec!["fx_1m.shard-00.ilp"]); - assert_eq!(rep1.ilp_stats.per_shard_rows, vec![2]); - assert_eq!( - fs::read(out1.join("fx_1m.shard-00.ilp")).unwrap().len(), - rep1.ilp_stats.bytes - ); - - // 4 shards: all USDCAD rows land in shard 01; shards 00, 02, 03 exist and are empty. - assert_eq!(shard_for_fx_pair(FX_PAIR_USDCAD, 4), 1); - let out4 = dir.path().join("out-4"); - let rep4 = run_curate_fx_1m(&make_args( - intraday_path, - out4.clone(), - 4, - BsonStreamOptions::default(), - )) - .unwrap(); - assert_report_conservation(&rep4); - assert_eq!( - list_dir_names(&out4), - vec![ - "fx_1m.shard-00.ilp", - "fx_1m.shard-01.ilp", - "fx_1m.shard-02.ilp", - "fx_1m.shard-03.ilp", - ] - ); - assert_eq!(rep4.ilp_stats.per_shard_rows, vec![0, 2, 0, 0]); - for shard_idx in 0..4usize { - let bytes = fs::read(out4.join(format!("fx_1m.shard-{shard_idx:02}.ilp"))).unwrap(); - if shard_idx == 1 { - assert_eq!(bytes.len(), rep4.ilp_stats.bytes); - assert_eq!(decode_ilp_fx_1m(&bytes).len(), 2); - } else { - assert!(bytes.is_empty(), "shard {shard_idx:02} should be empty"); - } - } -} - -#[test] -fn empty_and_wrong_code_only_inputs_publish_empty_shard_files() { - let dir = TempDirGuard::new("fx1m-empty"); - - // 1. Empty BSON input - let empty_in = dir.path().join("empty.bson"); - fs::write(&empty_in, []).unwrap(); - let out_empty = dir.path().join("out-empty"); - let rep_empty = run_curate_fx_1m(&make_args( - empty_in, - out_empty.clone(), - 3, - BsonStreamOptions::default(), - )) - .expect("empty input should succeed"); - assert_report_conservation(&rep_empty); - assert_eq!(rep_empty.decode.docs_seen, 0); - assert_eq!(rep_empty.curate_stats.bars_in, 0); - assert_eq!(rep_empty.rows_written, 0); - assert_eq!(rep_empty.ilp_stats.bytes, 0); - assert_eq!(rep_empty.ilp_stats.per_shard_rows, vec![0, 0, 0]); - assert_eq!( - list_dir_names(&out_empty), - vec![ - "fx_1m.shard-00.ilp", - "fx_1m.shard-01.ilp", - "fx_1m.shard-02.ilp", - ] - ); - for idx in 0..3usize { - assert!( - fs::read(out_empty.join(format!("fx_1m.shard-{idx:02}.ilp"))) - .unwrap() - .is_empty() - ); - } - - // 2. Valid dump with zero CAD.FOREX rows - let other_in = dir.path().join("other_only.bson"); - fs::write( - &other_in, - concat_docs(&[ - make_intraday_doc("AAPL.US", 1_718_200_000, 195.0, 196.0, 194.5, 195.5, 100.0), - make_intraday_doc("EURUSD.FOREX", 1_718_200_060, 1.08, 1.09, 1.07, 1.085, 0.0), - ]), - ) - .unwrap(); - let out_other = dir.path().join("out-other"); - let rep_other = run_curate_fx_1m(&make_args( - other_in, - out_other.clone(), - 2, - BsonStreamOptions::default(), - )) - .expect("wrong-code-only input should succeed"); - assert_report_conservation(&rep_other); - assert_eq!(rep_other.decode.docs_seen, 2); - assert_eq!(rep_other.decode.rows_decoded, 2); - assert_eq!(rep_other.curate_stats.bars_in, 2); - assert_eq!(rep_other.curate_stats.dropped_wrong_code, 2); - assert_eq!(rep_other.rows_written, 0); - assert_eq!(rep_other.ilp_stats.bytes, 0); - assert_eq!( - list_dir_names(&out_other), - vec!["fx_1m.shard-00.ilp", "fx_1m.shard-01.ilp"] - ); - for idx in 0..2usize { - assert!( - fs::read(out_other.join(format!("fx_1m.shard-{idx:02}.ilp"))) - .unwrap() - .is_empty() - ); - } -} - -#[test] -fn fail_closed_validation_missing_input_truncated_bson_and_sink_errors() { - let dir = TempDirGuard::new("fx1m-fail-closed"); - let valid_doc = - make_intraday_doc(EOD_CAD_FOREX_CODE, 1_718_300_000, 1.3700, 1.3710, 1.3690, 1.3705, 0.0); - let valid_in = dir.path().join("valid.bson"); - fs::write(&valid_in, concat_docs(&[valid_doc.clone()])).unwrap(); - - // 1. shard_count == 0 - { - let out_dir = dir.path().join("out-zero-shards"); - let err = run_curate_fx_1m(&make_args( - valid_in.clone(), - out_dir.clone(), - 0, - BsonStreamOptions::default(), - )) - .unwrap_err(); - assert!(matches!(err, RunCurateFx1mError::ZeroShardCount), "{err:?}"); - assert!(!out_dir.exists()); - } - - // 2. Invalid BsonStreamOptions (chunk_capacity_bytes == 0, max_doc_bytes < MIN_BSON_DOC_BYTES) - { - let out_dir = dir.path().join("out-zero-chunk-cap"); - let err = run_curate_fx_1m(&make_args( - valid_in.clone(), - out_dir.clone(), - 2, - BsonStreamOptions { - chunk_capacity_bytes: 0, - ..BsonStreamOptions::default() - }, - )) - .unwrap_err(); - assert!( - matches!( - err, - RunCurateFx1mError::BsonStream { - label: "eod-intraday", - source: BsonStreamError::InvalidChunkCapacity, - .. - } - ), - "{err:?}" - ); - assert!(err.source().is_some()); - assert!(!out_dir.exists()); - } - { - let out_dir = dir.path().join("out-small-max-doc"); - let err = run_curate_fx_1m(&make_args( - valid_in.clone(), - out_dir.clone(), - 2, - BsonStreamOptions { - max_doc_bytes: MIN_BSON_DOC_BYTES - 1, - ..BsonStreamOptions::default() - }, - )) - .unwrap_err(); - assert!( - matches!( - err, - RunCurateFx1mError::BsonStream { - label: "eod-intraday", - source: BsonStreamError::InvalidMaxDocBytes, - .. - } - ), - "{err:?}" - ); - assert!(err.source().is_some()); - assert!(!out_dir.exists()); - } - - // 3. Invalid IlpWriterOptions (max_batch_bytes == 0, max_batch_rows == 0) - { - let out_dir = dir.path().join("out-zero-batch-bytes"); - let mut args = make_args( - valid_in.clone(), - out_dir.clone(), - 2, - BsonStreamOptions::default(), - ); - args.ilp_options.max_batch_bytes = 0; - let err = run_curate_fx_1m(&args).unwrap_err(); - assert!( - matches!(err, RunCurateFx1mError::Ilp(IlpWriterError::ZeroMaxBatchBytes)), - "{err:?}" - ); - assert!(err.source().is_some()); - assert!(!out_dir.exists()); - } - { - let out_dir = dir.path().join("out-zero-batch-rows"); - let mut args = make_args( - valid_in.clone(), - out_dir.clone(), - 2, - BsonStreamOptions::default(), - ); - args.ilp_options.max_batch_rows = 0; - let err = run_curate_fx_1m(&args).unwrap_err(); - assert!( - matches!(err, RunCurateFx1mError::Ilp(IlpWriterError::ZeroMaxBatchRows)), - "{err:?}" - ); - assert!(err.source().is_some()); - assert!(!out_dir.exists()); - } - - // 4. Writer shard_count mismatch in with_readers - { - let mut sink0 = Vec::new(); - let writer = IlpShardedWriter::new(vec![&mut sink0], IlpWriterOptions::default()).unwrap(); - let args = make_args( - valid_in.clone(), - dir.path().join("unused"), - 2, - BsonStreamOptions::default(), - ); - let err = run_curate_fx_1m_with_readers(&args, Cursor::new(b""), writer).unwrap_err(); - assert!( - matches!( - err, - RunCurateFx1mError::ShardCountMismatch { - expected: 2, - actual: 1 - } - ), - "{err:?}" - ); - } - - // 5. Missing input file fails before creating out_dir - { - let out_dir = dir.path().join("out-missing-input"); - let err = run_curate_fx_1m(&make_args( - dir.path().join("does-not-exist.bson"), - out_dir.clone(), - 2, - BsonStreamOptions::default(), - )) - .unwrap_err(); - assert!( - matches!(err, RunCurateFx1mError::OpenInput { label: "eod-intraday", .. }), - "{err:?}" - ); - assert!(err.source().is_some()); - assert!(!out_dir.exists()); - } - - // 6. out_dir exists as a regular file - { - let out_file = dir.path().join("out-is-file"); - fs::write(&out_file, b"not a dir").unwrap(); - let err = run_curate_fx_1m(&make_args( - valid_in.clone(), - out_file.clone(), - 2, - BsonStreamOptions::default(), - )) - .unwrap_err(); - assert!(matches!(err, RunCurateFx1mError::InvalidOutDir { .. }), "{err:?}"); - assert_eq!(fs::read(&out_file).unwrap(), b"not a dir"); - } - - // 7. Truncated BSON mid-document after a valid CAD.FOREX bar - { - let doc2 = make_intraday_doc( - EOD_CAD_FOREX_CODE, - 1_718_300_060, - 1.3705, - 1.3715, - 1.3700, - 1.3710, - 0.0, - ); - let mut trunc_bytes = concat_docs(&[valid_doc.clone(), doc2]); - trunc_bytes.truncate(trunc_bytes.len() - 7); - let trunc_in = dir.path().join("truncated.bson"); - fs::write(&trunc_in, &trunc_bytes).unwrap(); - - let out_dir = dir.path().join("out-trunc"); - fs::create_dir_all(&out_dir).unwrap(); - let keep_path = out_dir.join("keep.txt"); - fs::write(&keep_path, b"keep-me").unwrap(); - - let err = run_curate_fx_1m(&make_args( - trunc_in, - out_dir.clone(), - 2, - BsonStreamOptions::default(), - )) - .unwrap_err(); - assert!( - matches!(err, RunCurateFx1mError::BsonStream { label: "eod-intraday", .. }), - "{err:?}" - ); - assert!(err.source().is_some()); - assert_eq!(list_dir_names(&out_dir), vec!["keep.txt"]); - assert_eq!(fs::read(&keep_path).unwrap(), b"keep-me"); - } - - // 8. Sink failure on write -> Ilp(Io), no final or temp files left - { - let out_dir = dir.path().join("out-write-fail"); - let mut args = make_args( - valid_in.clone(), - out_dir.clone(), - 1, - BsonStreamOptions::default(), - ); - args.ilp_options.max_batch_rows = 1; - let err = run_curate_fx_1m_to_dir_with_hooks( - &args, - Cursor::new(concat_docs(&[valid_doc.clone()])), - |_idx, _file| FailingWriteSink { - fail_on_write: true, - fail_on_flush: false, - }, - |_idx, _path| {}, - ) - .unwrap_err(); - assert!( - matches!(err, RunCurateFx1mError::Ilp(IlpWriterError::Io { .. })), - "{err:?}" - ); - assert!(err.source().is_some()); - assert!(list_dir_names(&out_dir).is_empty()); - } - - // 9. Sink failure on flush during finish() -> Ilp(Io), no final or temp files left - { - let out_dir = dir.path().join("out-flush-fail"); - let args = make_args( - valid_in, - out_dir.clone(), - 1, - BsonStreamOptions::default(), - ); - let err = run_curate_fx_1m_to_dir_with_hooks( - &args, - Cursor::new(concat_docs(&[valid_doc])), - |_idx, _file| FailingWriteSink { - fail_on_write: false, - fail_on_flush: true, - }, - |_idx, _path| {}, - ) - .unwrap_err(); - assert!( - matches!(err, RunCurateFx1mError::Ilp(IlpWriterError::Io { .. })), - "{err:?}" - ); - assert!(err.source().is_some()); - assert!(list_dir_names(&out_dir).is_empty()); - } -} - -#[test] -fn fail_closed_preexisting_shards_coexistence_and_post_preflight_rollback() { - let dir = TempDirGuard::new("fx1m-no-overwrite"); - let intraday_bytes = concat_docs(&[make_intraday_doc( - EOD_CAD_FOREX_CODE, - 1_718_400_000, - 1.3700, - 1.3710, - 1.3690, - 1.3705, - 0.0, - )]); - let intraday_path = dir.path().join("eodIntraday1M.bson"); - fs::write(&intraday_path, &intraday_bytes).unwrap(); - - // Case A: pre-existing fx_1m.shard-07.ilp with shard_count = 2 -> rejected, bytes preserved. - { - let out_dir = dir.path().join("out-stale-07"); - fs::create_dir_all(&out_dir).unwrap(); - let sentinel = b"stale-fx-shard-07"; - let stale_path = out_dir.join("fx_1m.shard-07.ilp"); - fs::write(&stale_path, sentinel).unwrap(); - - let err = run_curate_fx_1m(&make_args( - intraday_path.clone(), - out_dir.clone(), - 2, - BsonStreamOptions::default(), - )) - .unwrap_err(); - assert!( - matches!(err, RunCurateFx1mError::OutputFileExists { ref path } if path == &stale_path), - "{err:?}" - ); - assert_eq!(fs::read(&stale_path).unwrap(), sentinel); - assert_eq!(list_dir_names(&out_dir), vec!["fx_1m.shard-07.ilp"]); - } - - // Case B: pre-existing digit-only name of another width (fx_1m.shard-3.ilp) -> rejected. - { - let out_dir = dir.path().join("out-stale-width1"); - fs::create_dir_all(&out_dir).unwrap(); - let sentinel = b"stale-fx-shard-width1"; - let stale_path = out_dir.join("fx_1m.shard-3.ilp"); - fs::write(&stale_path, sentinel).unwrap(); - - let err = run_curate_fx_1m(&make_args( - intraday_path.clone(), - out_dir.clone(), - 2, - BsonStreamOptions::default(), - )) - .unwrap_err(); - assert!( - matches!(err, RunCurateFx1mError::OutputFileExists { ref path } if path == &stale_path), - "{err:?}" - ); - assert_eq!(fs::read(&stale_path).unwrap(), sentinel); - assert_eq!(list_dir_names(&out_dir), vec!["fx_1m.shard-3.ilp"]); - } - - // Case C: a pre-existing bars_1m shard in out_dir coexists untouched. - { - let out_dir = dir.path().join("out-coexist-bars"); - fs::create_dir_all(&out_dir).unwrap(); - let bars_sentinel = b"bars-1m-shard-00-untouched"; - let bars_path = out_dir.join("bars_1m.shard-00.ilp"); - fs::write(&bars_path, bars_sentinel).unwrap(); - - let rep = run_curate_fx_1m(&make_args( - intraday_path.clone(), - out_dir.clone(), - 2, - BsonStreamOptions::default(), - )) - .expect("bars_1m shard should coexist untouched"); - assert_report_conservation(&rep); - assert_eq!(rep.rows_written, 1); - assert_eq!(fs::read(&bars_path).unwrap(), bars_sentinel); - assert_eq!( - list_dir_names(&out_dir), - vec![ - "bars_1m.shard-00.ilp", - "fx_1m.shard-00.ilp", - "fx_1m.shard-01.ilp", - ] - ); - } - - // Case D: post-preflight collision on shard 01 after shard 00 is linked. - // Shard 00 must be rolled back, staging files removed, external shard 01 untouched. - { - let out_dir = dir.path().join("out-race"); - let args = make_args( - intraday_path, - out_dir.clone(), - 3, - BsonStreamOptions::default(), - ); - let race_sentinel = b"concurrent-writer-fx-shard-01"; - let err = run_curate_fx_1m_to_dir_with_hooks( - &args, - Cursor::new(&intraday_bytes), - |_idx, file| SyncedBufFile::new(file), - |shard_idx, final_path| { - if shard_idx == 1 { - fs::write(final_path, race_sentinel).expect("inject concurrent final shard"); - } - }, - ) - .unwrap_err(); - let expected_race_path = out_dir.join("fx_1m.shard-01.ilp"); - assert!( - matches!(err, RunCurateFx1mError::OutputFileExists { ref path } if path == &expected_race_path), - "{err:?}" - ); - assert_eq!(fs::read(&expected_race_path).unwrap(), race_sentinel); - assert_eq!(list_dir_names(&out_dir), vec!["fx_1m.shard-01.ilp"]); - } -} - -#[test] -fn format_curate_fx_1m_report_includes_every_counter_and_isolates_timing() { - let report = CurateFx1mRunReport { - decode: BsonEodIntradayDecodeStats { - docs_seen: 100, - rows_decoded: 90, - rejected_missing_field: 1, - rejected_empty_field: 2, - rejected_wrong_type: 3, - rejected_invalid_timestamp: 1, - rejected_invalid_number: 2, - rejected_corrupt_document: 1, - }, - curate_stats: CurateFx1mStats { - bars_in: 90, - rows_out: 50, - dropped_wrong_code: 20, - dropped_negative_ts: 1, - dropped_invalid_ohlc: 2, - dropped_high_below_bound: 3, - dropped_low_above_bound: 4, - duplicate_collapsed: 5, - duplicate_conflict_dropped: 5, - }, - rows_written: 50, - ilp_stats: IlpWriteStats { - rows: 50, - bytes: 4096, - flushes: 2, - per_shard_rows: vec![0, 50, 0, 0], - }, - shard_count: 4, - elapsed_secs: 0.123456, - }; - assert_report_conservation(&report); - - let formatted = format_curate_fx_1m_report(&report); - let lines: Vec<&str> = formatted.lines().collect(); - assert_eq!(lines.len(), 5, "expected 5 report lines, got:\n{formatted}"); - assert_eq!(lines[0], "curate-etl curate-fx-1m"); - assert!( - lines[1].contains("docs_seen=100") - && lines[1].contains("rows_decoded=90") - && lines[1].contains("rejected=10") - && lines[1].contains("missing=1") - && lines[1].contains("empty=2") - && lines[1].contains("wrong_type=3") - && lines[1].contains("invalid_ts=1") - && lines[1].contains("invalid_num=2") - && lines[1].contains("corrupt=1"), - "missing decode counters in line 1: {}", - lines[1] - ); - assert!( - lines[2].contains("bars_in=90") - && lines[2].contains("rows_out=50") - && lines[2].contains("wrong_code=20") - && lines[2].contains("negative_ts=1") - && lines[2].contains("invalid_ohlc=2") - && lines[2].contains("high_below_bound=3") - && lines[2].contains("low_above_bound=4") - && lines[2].contains("dup_collapsed=5") - && lines[2].contains("dup_conflict_dropped=5"), - "missing curate counters in line 2: {}", - lines[2] - ); - assert!( - lines[3].contains("shards=4") - && lines[3].contains("rows_written=50") - && lines[3].contains("ilp_rows=50") - && lines[3].contains("bytes=4096") - && lines[3].contains("flushes=2") - && lines[3].contains("per_shard_rows=00=0,01=50,02=0,03=0"), - "missing ilp counters in line 3: {}", - lines[3] - ); - assert_eq!(lines[4].trim(), "timing: elapsed_secs=0.123456"); - // Ensure elapsed_secs appears only on the timing line. - for line in &lines[..4] { - assert!(!line.contains("elapsed_secs"), "timing leaked into: {line}"); - } -} - -struct PanicOnRead; - -impl io::Read for PanicOnRead { - fn read(&mut self, _buf: &mut [u8]) -> io::Result { - panic!("intraday reader must not be read when writer preflight fails"); - } -} - -#[test] -fn with_readers_rejects_preloaded_writer_with_queued_or_flushed_rows_before_reading() { - use crate::bson_eod_intraday::RawEodIntradayBar; - - let make_bar = |ts_sec: i64| RawEodIntradayBar { - eod_search_code: EOD_CAD_FOREX_CODE, - ts: ts_sec * 1_000_000, - open: 1.3700, - high: 1.3710, - low: 1.3690, - close: 1.3705, - volume: 0.0, - }; - - let args = make_args( - PathBuf::from("preloaded-check.bson"), - PathBuf::from("unused-out"), - 1, - BsonStreamOptions::default(), - ); - - // Case 1: queued-only row (buffered, not yet flushed). - { - let mut sink = Vec::new(); - let mut writer = - IlpShardedWriter::new(vec![&mut sink], IlpWriterOptions::default()).unwrap(); - curate_and_write_fx_1m([make_bar(1_718_500_000)], &mut writer).unwrap(); - - let err = run_curate_fx_1m_with_readers(&args, PanicOnRead, writer).unwrap_err(); - assert!( - matches!( - err, - RunCurateFx1mError::NonEmptyWriter { - flushed_rows: 0, - pending_rows: 1 - } - ), - "{err:?}" - ); - assert!(err.source().is_none()); - let msg = err.to_string(); - assert!(msg.contains("0 flushed") && msg.contains("1 pending"), "{msg}"); - } - - // Case 2: flushed-only row (max_batch_rows = 1 flushes immediately, pending == 0). - { - let mut sink = Vec::new(); - let mut writer = IlpShardedWriter::new( - vec![&mut sink], - IlpWriterOptions { - max_batch_rows: 1, - ..IlpWriterOptions::default() - }, - ) - .unwrap(); - curate_and_write_fx_1m([make_bar(1_718_500_000)], &mut writer).unwrap(); - - let err = run_curate_fx_1m_with_readers(&args, PanicOnRead, writer).unwrap_err(); - assert!( - matches!( - err, - RunCurateFx1mError::NonEmptyWriter { - flushed_rows: 1, - pending_rows: 0 - } - ), - "{err:?}" - ); - } - - // Case 3: both flushed and queued rows (max_batch_rows = 2 with 3 bars -> 2 flushed, 1 pending). - { - let mut sink = Vec::new(); - let mut writer = IlpShardedWriter::new( - vec![&mut sink], - IlpWriterOptions { - max_batch_rows: 2, - ..IlpWriterOptions::default() - }, - ) - .unwrap(); - curate_and_write_fx_1m( - [ - make_bar(1_718_500_000), - make_bar(1_718_500_060), - make_bar(1_718_500_120), - ], - &mut writer, - ) - .unwrap(); - - let err = run_curate_fx_1m_with_readers(&args, PanicOnRead, writer).unwrap_err(); - assert!( - matches!( - err, - RunCurateFx1mError::NonEmptyWriter { - flushed_rows: 2, - pending_rows: 1 - } - ), - "{err:?}" - ); - } -} - -#[test] -fn file_mode_reports_staging_unlink_failures_with_paths_on_flush_error() { - let dir = TempDirGuard::new("fx1m-staging-unlink-fail"); - let valid_doc = - make_intraday_doc(EOD_CAD_FOREX_CODE, 1_718_600_000, 1.3700, 1.3710, 1.3690, 1.3705, 0.0); - let out_dir = dir.path().join("out"); - let args = make_args( - dir.path().join("in-memory.bson"), - out_dir.clone(), - 2, - BsonStreamOptions::default(), - ); - - let err = run_curate_fx_1m_to_dir_with_cleanup_hook( - &args, - Cursor::new(concat_docs(&[valid_doc])), - |shard_idx, file| { - if shard_idx == 0 { - Box::new(FailingWriteSink { - fail_on_write: false, - fail_on_flush: true, - }) as Box - } else { - Box::new(SyncedBufFile::new(file)) as Box - } - }, - |_shard_idx, _final_path| {}, - |tmp_path| { - let name = tmp_path - .file_name() - .and_then(|n| n.to_str()) - .unwrap_or_default(); - if name.starts_with(".fx_1m.shard-01.") { - Err(io::Error::new( - io::ErrorKind::PermissionDenied, - "injected staging unlink failure", - )) - } else { - fs::remove_file(tmp_path) - } - }, - ) - .unwrap_err(); - - let rendered = err.to_string(); - assert!(err.source().is_some(), "RollbackFailed must expose original cause"); - - match err { - RunCurateFx1mError::RollbackFailed { cause, failures } => { - assert!( - matches!( - cause.as_ref(), - RunCurateFx1mError::Ilp(IlpWriterError::Io { shard: 0, .. }) - ), - "unexpected original cause: {cause:?}" - ); - assert_eq!(failures.len(), 1, "expected 1 staging unlink failure: {failures:?}"); - let failure = &failures[0]; - assert!(failure.backup_path.is_none()); - assert_eq!(failure.source.kind(), io::ErrorKind::PermissionDenied); - - let surviving_name = failure - .final_path - .file_name() - .and_then(|n| n.to_str()) - .expect("staging file name"); - assert!( - surviving_name.starts_with(".fx_1m.shard-01.") && surviving_name.ends_with(".tmp"), - "unexpected surviving staging name: {surviving_name}" - ); - assert!( - failure.final_path.exists(), - "surviving staging file should still exist on disk" - ); - // Shard 0's staging file was cleaned up and zero final shard files were created. - assert_eq!(list_dir_names(&out_dir), vec![surviving_name]); - - assert!( - rendered.contains("injected flush failure"), - "rendered error missing original flush cause: {rendered}" - ); - assert!( - rendered.contains(&failure.final_path.display().to_string()), - "rendered error missing surviving staging path: {rendered}" - ); - assert!( - rendered.contains("injected staging unlink failure"), - "rendered error missing unlink failure detail: {rendered}" - ); - } - other => panic!("expected RollbackFailed, got {other:?}"), - } -} - -// --------------------------------------------------------------------------------------------- -// QA edge cases (T-183) -// --------------------------------------------------------------------------------------------- - -fn snapshot_dir(dir: &Path) -> Vec<(String, Vec)> { - list_dir_names(dir) - .into_iter() - .map(|name| { - let bytes = fs::read(dir.join(&name)).unwrap(); - (name, bytes) - }) - .collect() -} - -#[test] -fn rerun_into_published_out_dir_fails_closed_and_preserves_first_run_bytes() { - let dir = TempDirGuard::new("fx1m-qa-rerun"); - let intraday_path = dir.path().join("eodIntraday1M.bson"); - fs::write( - &intraday_path, - concat_docs(&[ - make_intraday_doc(EOD_CAD_FOREX_CODE, 1_718_700_000, 1.37, 1.371, 1.369, 1.3705, 0.0), - make_intraday_doc(EOD_CAD_FOREX_CODE, 1_718_700_060, 1.3705, 1.3715, 1.37, 1.371, 0.0), - ]), - ) - .unwrap(); - let out_dir = dir.path().join("out"); - let args = make_args(intraday_path, out_dir.clone(), 2, BsonStreamOptions::default()); - - let first = run_curate_fx_1m(&args).expect("first run succeeds"); - assert_eq!(first.rows_written, 2); - let before = snapshot_dir(&out_dir); - assert_eq!( - before.iter().map(|(n, _)| n.as_str()).collect::>(), - vec!["fx_1m.shard-00.ilp", "fx_1m.shard-01.ilp"] - ); - - let err = run_curate_fx_1m(&args).unwrap_err(); - let expected = out_dir.join("fx_1m.shard-00.ilp"); - assert!( - matches!(err, RunCurateFx1mError::OutputFileExists { ref path } if path == &expected), - "{err:?}" - ); - assert_eq!(snapshot_dir(&out_dir), before, "rerun must not touch published shards"); -} - -#[test] -fn preflight_is_table_scoped_and_ignores_non_shard_names() { - let dir = TempDirGuard::new("fx1m-qa-preflight-scope"); - let intraday_path = dir.path().join("eodIntraday1M.bson"); - fs::write( - &intraday_path, - concat_docs(&[make_intraday_doc( - EOD_CAD_FOREX_CODE, - 1_718_800_000, - 1.37, - 1.371, - 1.369, - 1.3705, - 0.0, - )]), - ) - .unwrap(); - let out_dir = dir.path().join("out"); - fs::create_dir_all(&out_dir).unwrap(); - // None of these are `fx_1m.shard-.ilp`, so they must not block the run. - let bystanders = [ - "fx_1m.shard-.ilp", - "fx_1m.shard-0a.ilp", - "fx_1m.shard-00.ilp.bak", - "xfx_1m.shard-00.ilp", - ".fx_1m.shard-00.stale.tmp", - "bars_1m.shard-00.ilp", - "bars_1m.shard-7.ilp", - ]; - for name in bystanders { - fs::write(out_dir.join(name), name.as_bytes()).unwrap(); - } - - let report = run_curate_fx_1m(&make_args( - intraday_path, - out_dir.clone(), - 1, - BsonStreamOptions::default(), - )) - .expect("non-shard names must not trip fx_1m preflight"); - assert_eq!(report.rows_written, 1); - for name in bystanders { - assert_eq!(fs::read(out_dir.join(name)).unwrap(), name.as_bytes(), "{name} touched"); - } - let mut expected: Vec = bystanders.iter().map(|s| s.to_string()).collect(); - expected.push("fx_1m.shard-00.ilp".to_string()); - expected.sort(); - assert_eq!(list_dir_names(&out_dir), expected); - - // The parameterised matcher must not leak across tables (bars_1m regression guard). - use crate::ilp::TABLE_BARS_1M; - use crate::run_curate_bars_1m::is_final_shard_file_name_for_table; - use std::ffi::OsStr; - assert!(is_final_shard_file_name_for_table(TABLE_FX_1M, OsStr::new("fx_1m.shard-123.ilp"))); - assert!(!is_final_shard_file_name_for_table(TABLE_BARS_1M, OsStr::new("fx_1m.shard-00.ilp"))); - assert!(!is_final_shard_file_name_for_table(TABLE_FX_1M, OsStr::new("bars_1m.shard-00.ilp"))); - assert!(preflight_shard_out_dir(&out_dir, TABLE_BARS_1M).is_err()); - let fx_only = dir.path().join("fx-only"); - fs::create_dir_all(&fx_only).unwrap(); - fs::write(fx_only.join("fx_1m.shard-00.ilp"), b"x").unwrap(); - assert!( - preflight_shard_out_dir(&fx_only, TABLE_BARS_1M).is_ok(), - "fx_1m shards must not block a bars_1m run" - ); -} - -#[test] -fn with_readers_truncated_dump_keeps_path_and_emits_nothing_to_sinks() { - let valid = make_intraday_doc(EOD_CAD_FOREX_CODE, 1_718_900_000, 1.37, 1.371, 1.369, 1.3705, 0.0); - let mut bytes = concat_docs(&[valid.clone(), valid]); - let first_len = bytes.len() / 2; - bytes.truncate(bytes.len() - 3); - - let mut sink0 = Vec::new(); - let mut sink1 = Vec::new(); - let writer = - IlpShardedWriter::new(vec![&mut sink0, &mut sink1], IlpWriterOptions::default()).unwrap(); - let path = PathBuf::from("/dumps/eodIntraday1M.bson"); - let args = make_args(path.clone(), PathBuf::from("unused"), 2, BsonStreamOptions::default()); - - let err = run_curate_fx_1m_with_readers(&args, Cursor::new(bytes), writer).unwrap_err(); - match &err { - RunCurateFx1mError::BsonStream { label, path: p, .. } => { - assert_eq!(*label, "eod-intraday"); - assert_eq!(p, &path); - } - other => panic!("expected BsonStream, got {other:?}"), - } - let rendered = err.to_string(); - assert!(rendered.contains("/dumps/eodIntraday1M.bson"), "{rendered}"); - assert!(rendered.contains(&first_len.to_string()), "offset missing: {rendered}"); - // The stage only writes after clean EOF, so a fatal stream error leaves sinks untouched. - assert!(sink0.is_empty() && sink1.is_empty()); -} - -#[test] -fn three_digit_shard_indices_keep_min_width_two_naming() { - let dir = TempDirGuard::new("fx1m-qa-wide"); - let intraday_path = dir.path().join("eodIntraday1M.bson"); - fs::write( - &intraday_path, - concat_docs(&[make_intraday_doc( - EOD_CAD_FOREX_CODE, - 1_719_000_000, - 1.37, - 1.371, - 1.369, - 1.3705, - 0.0, - )]), - ) - .unwrap(); - let out_dir = dir.path().join("out"); - let shard_count = 101usize; - let report = run_curate_fx_1m(&make_args( - intraday_path, - out_dir.clone(), - shard_count, - BsonStreamOptions::default(), - )) - .unwrap(); - assert_report_conservation(&report); - - let mut expected: Vec = - (0..shard_count).map(|i| format!("fx_1m.shard-{i:02}.ilp")).collect(); - expected.sort(); - assert_eq!(list_dir_names(&out_dir), expected); - assert!(list_dir_names(&out_dir).contains(&"fx_1m.shard-100.ilp".to_string())); - - let target = shard_for_fx_pair(FX_PAIR_USDCAD, shard_count); - for i in 0..shard_count { - let len = fs::metadata(out_dir.join(format!("fx_1m.shard-{i:02}.ilp"))).unwrap().len(); - assert_eq!(len > 0, i == target, "shard {i} non-empty mismatch (target {target})"); - assert_eq!(report.ilp_stats.per_shard_rows[i], usize::from(i == target)); - } -} - -/// Streams `n` generated non-FX docs followed by FX docs without materialising the dump. -struct GeneratedDump { - docs: std::vec::IntoIter>, - current: Vec, - pos: usize, -} - -impl io::Read for GeneratedDump { - fn read(&mut self, buf: &mut [u8]) -> io::Result { - while self.pos == self.current.len() { - match self.docs.next() { - Some(next) => { - self.current = next; - self.pos = 0; - } - None => return Ok(0), - } - } - let n = buf.len().min(self.current.len() - self.pos); - buf[..n].copy_from_slice(&self.current[self.pos..self.pos + n]); - self.pos += n; - Ok(n) - } -} - -#[test] -fn many_wrong_code_docs_across_tiny_chunks_are_only_counted() { - let wrong = make_intraday_doc("AAPL.US", 1_719_100_000, 195.0, 196.0, 194.5, 195.5, 1.0); - let fx_a = make_intraday_doc(EOD_CAD_FOREX_CODE, 1_719_100_060, 1.37, 1.371, 1.369, 1.3705, 0.0); - let fx_b = make_intraday_doc(EOD_CAD_FOREX_CODE, 1_719_100_000, 1.36, 1.361, 1.359, 1.3605, 0.0); - let n_wrong = 20_000usize; - let mut docs: Vec> = vec![fx_a.as_bytes().to_vec()]; - docs.extend(std::iter::repeat_n(wrong.as_bytes().to_vec(), n_wrong)); - docs.push(fx_b.as_bytes().to_vec()); - let reader = GeneratedDump { - docs: docs.into_iter(), - current: Vec::new(), - pos: 0, - }; - - let mut sink = Vec::new(); - let writer = IlpShardedWriter::new(vec![&mut sink], IlpWriterOptions::default()).unwrap(); - let opts = BsonStreamOptions { - chunk_capacity_bytes: wrong.as_bytes().len() * 4, - ..BsonStreamOptions::default() - }; - let args = make_args(PathBuf::from("gen.bson"), PathBuf::from("unused"), 1, opts); - let report = run_curate_fx_1m_with_readers(&args, reader, writer).unwrap(); - assert_report_conservation(&report); - assert_eq!(report.decode.docs_seen, n_wrong + 2); - assert_eq!(report.curate_stats.dropped_wrong_code, n_wrong); - assert_eq!(report.rows_written, 2); - - // Rows separated by 20k wrong-code docs across many chunks are still globally sorted. - let rows = decode_ilp_fx_1m(&sink); - assert_eq!( - rows.iter().map(|r| r.ts).collect::>(), - vec![1_719_100_000_000_000, 1_719_100_060_000_000] - ); -} - -#[test] -fn error_display_is_single_line_and_names_paths() { - let errs = [ - RunCurateFx1mError::ZeroShardCount, - RunCurateFx1mError::ShardCountMismatch { expected: 2, actual: 1 }, - RunCurateFx1mError::NonEmptyWriter { flushed_rows: 3, pending_rows: 4 }, - RunCurateFx1mError::InvalidOutDir { - path: PathBuf::from("/o/d"), - detail: "not a dir".into(), - }, - RunCurateFx1mError::OutputFileExists { path: PathBuf::from("/o/fx_1m.shard-00.ilp") }, - RunCurateFx1mError::OpenInput { - label: "eod-intraday", - path: PathBuf::from("/i/x.bson"), - source: io::Error::new(io::ErrorKind::NotFound, "nf"), - }, - RunCurateFx1mError::Io { - path: PathBuf::from("/o/tmp"), - source: io::Error::other("boom"), - }, - ]; - for err in &errs { - let s = err.to_string(); - assert!(!s.is_empty() && !s.contains('\n'), "bad display: {s:?}"); - } - assert!(errs[2].to_string().contains("3 flushed") && errs[2].to_string().contains("4 pending")); - assert!(errs[3].to_string().contains("/o/d")); - assert!(errs[4].to_string().contains("/o/fx_1m.shard-00.ilp")); - assert!(errs[5].to_string().contains("/i/x.bson")); - assert!(errs[6].to_string().contains("/o/tmp")); -} - -// --------------------------------------------------------------------------------------------- -// QA: CLI wiring parity (T-187) -// --------------------------------------------------------------------------------------------- - -fn run_via_cli(argv: &[&str]) -> CurateFx1mRunReport { - let args: Vec = argv.iter().map(|s| (*s).to_string()).collect(); - match crate::cli::parse_args(&args).expect("curate-fx-1m argv should parse") { - crate::cli::CliAction::CurateFx1m(parsed) => { - run_curate_fx_1m(&parsed).expect("CLI-parsed run should succeed") - } - other => panic!("expected CliAction::CurateFx1m, got {other:?}"), - } -} - -fn assert_reports_equal_ignoring_elapsed(a: &CurateFx1mRunReport, b: &CurateFx1mRunReport) { - assert_eq!(a.decode, b.decode); - assert_eq!(a.curate_stats, b.curate_stats); - assert_eq!(a.rows_written, b.rows_written); - assert_eq!(a.ilp_stats, b.ilp_stats); - assert_eq!(a.shard_count, b.shard_count); -} - -#[test] -fn cli_parsed_curate_fx_1m_matches_direct_runner_bytes_and_counters() { - let dir = TempDirGuard::new("fx1m-qa-cli-parity"); - let ts1 = 1_718_700_000_i64; // 2024-06-18 08:40:00 UTC - let ts2 = ts1 + 60; - let intraday_path = dir.path().join("eodIntraday1M.bson"); - fs::write( - &intraday_path, - concat_docs(&[ - make_intraday_doc(EOD_CAD_FOREX_CODE, ts2, 1.3705, 1.3715, 1.37, 1.371, 0.0), - make_intraday_doc("AAPL.US", ts1, 195.0, 196.0, 194.5, 195.5, 1000.0), - make_intraday_doc(EOD_CAD_FOREX_CODE, ts1, 1.37, 1.371, 1.369, 1.3705, 0.0), - // Bitwise-identical duplicate collapses. - make_intraday_doc(EOD_CAD_FOREX_CODE, ts1, 1.37, 1.371, 1.369, 1.3705, 0.0), - ]), - ) - .unwrap(); - let intraday = intraday_path.to_str().unwrap().to_string(); - - // Reference: runner with hand-built args and default options. - let direct_out = dir.path().join("direct"); - let direct = run_curate_fx_1m(&make_args( - intraday_path.clone(), - direct_out.clone(), - 4, - BsonStreamOptions::default(), - )) - .expect("direct run succeeds"); - assert_eq!(direct.rows_written, 2); - assert_eq!(direct.curate_stats.dropped_wrong_code, 1); - - // CLI space form. - let space_out = dir.path().join("cli-space"); - let space_out_s = space_out.to_str().unwrap().to_string(); - let via_space = run_via_cli(&[ - "curate-fx-1m", - "--eod-intraday", - &intraday, - "--out", - &space_out_s, - "--shards", - "4", - ]); - - // CLI equals form, flags reordered. - let eq_out = dir.path().join("cli-eq"); - let shards_tok = "--shards=4".to_string(); - let out_tok = format!("--out={}", eq_out.to_str().unwrap()); - let intraday_tok = format!("--eod-intraday={intraday}"); - let via_eq = run_via_cli(&["curate-fx-1m", &shards_tok, &out_tok, &intraday_tok]); - - assert_reports_equal_ignoring_elapsed(&via_space, &direct); - assert_reports_equal_ignoring_elapsed(&via_eq, &direct); - - let expected_names: Vec = (0..4).map(|i| format!("fx_1m.shard-{i:02}.ilp")).collect(); - let direct_snapshot = snapshot_dir(&direct_out); - assert_eq!( - direct_snapshot - .iter() - .map(|(n, _)| n.clone()) - .collect::>(), - expected_names - ); - assert_eq!(snapshot_dir(&space_out), direct_snapshot); - assert_eq!(snapshot_dir(&eq_out), direct_snapshot); - - // Exactly one populated shard carrying USDCAD/eod rows at UTC bar-start micros. - let rows: Vec = direct_snapshot - .iter() - .flat_map(|(_, bytes)| decode_ilp_fx_1m(bytes)) - .collect(); - let populated = direct_snapshot - .iter() - .filter(|(_, b)| !b.is_empty()) - .count(); - assert_eq!(populated, 1); - assert_eq!( - rows.iter().map(|r| r.ts).collect::>(), - vec![ts1 * 1_000_000, ts2 * 1_000_000] - ); - for row in &rows { - assert_eq!(row.pair, FX_PAIR_USDCAD); - assert_eq!(row.source, FX_1M_SOURCE_EOD); - } - assert_eq!(rows[0].close.to_bits(), 1.3705_f64.to_bits()); -} - -#[test] -fn cli_parsed_curate_fx_1m_missing_input_fails_without_publishing_shards() { - let dir = TempDirGuard::new("fx1m-qa-cli-missing"); - let missing = dir.path().join("does-not-exist.bson"); - let out_dir = dir.path().join("out"); - let args: Vec = [ - "curate-fx-1m", - "--eod-intraday", - missing.to_str().unwrap(), - "--out", - out_dir.to_str().unwrap(), - "--shards", - "2", - ] - .iter() - .map(|s| (*s).to_string()) - .collect(); - let crate::cli::CliAction::CurateFx1m(parsed) = crate::cli::parse_args(&args).unwrap() else { - panic!("expected CliAction::CurateFx1m"); - }; - let err = run_curate_fx_1m(&parsed).unwrap_err(); - assert!(err.to_string().contains("does-not-exist.bson"), "{err}"); - let leftover: Vec = list_dir_names(&out_dir) - .into_iter() - .filter(|n| n.starts_with("fx_1m.")) - .collect(); - assert!( - leftover.is_empty(), - "no shard output expected: {leftover:?}" - ); -} diff --git a/tools/curate-etl/src/run_curate_fx_tests.rs b/tools/curate-etl/src/run_curate_fx_tests.rs deleted file mode 100644 index 319f0dd5..00000000 --- a/tools/curate-etl/src/run_curate_fx_tests.rs +++ /dev/null @@ -1,986 +0,0 @@ -use std::fs::{self, File}; -use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering}; - -use bson::raw::{cstr, RawArrayBuf, RawDocumentBuf}; -use parquet::file::reader::{FileReader, SerializedFileReader}; -use parquet::record::{Field, RowAccessor}; - -use super::*; -use crate::bson_te_market_data::{MILLIS_PER_DAY, SECONDS_PER_DAY}; -use crate::curate_fx::fx_1d_utc_day_end_micros; -use crate::fx::{FxSource, FX_PAIR_USDCAD}; -use crate::split::ymd_to_epoch_days; - -static TEST_DIR_SEQ: AtomicU64 = AtomicU64::new(0); - -struct TestTempDir { - path: PathBuf, -} - -impl TestTempDir { - fn new(prefix: &str) -> Self { - let pid = std::process::id(); - let base = std::env::temp_dir(); - loop { - let seq = TEST_DIR_SEQ.fetch_add(1, Ordering::Relaxed); - let candidate = base.join(format!("curate-etl-{prefix}-{pid}-{seq}")); - match fs::create_dir(&candidate) { - Ok(()) => return Self { path: candidate }, - Err(err) if err.kind() == io::ErrorKind::AlreadyExists => continue, - Err(err) => panic!("failed to create temp dir {}: {err}", candidate.display()), - } - } - } -} - -impl Drop for TestTempDir { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.path); - } -} - -fn day(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).expect("valid date") -} - -fn eod_doc(code: &str, date: &str, o: f64, h: f64, l: f64, c: f64, vol: f64) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), code); - doc.append(cstr!("date"), date); - doc.append(cstr!("open"), o); - doc.append(cstr!("high"), h); - doc.append(cstr!("low"), l); - doc.append(cstr!("close"), c); - doc.append(cstr!("volume"), vol); - doc.as_bytes().to_vec() -} - -fn te_point_secs(d: i32, o: f64, h: f64, l: f64, c: f64) -> RawDocumentBuf { - let mut pt = RawDocumentBuf::new(); - pt.append(cstr!("t"), i64::from(d) * SECONDS_PER_DAY + 3_600); - pt.append(cstr!("o"), o); - pt.append(cstr!("h"), h); - pt.append(cstr!("l"), l); - pt.append(cstr!("c"), c); - pt -} - -fn te_point_ms(d: i32, o: f64, h: f64, l: f64, c: f64) -> RawDocumentBuf { - let mut pt = RawDocumentBuf::new(); - pt.append(cstr!("t"), i64::from(d) * MILLIS_PER_DAY + 43_200_000); - pt.append(cstr!("o"), o); - pt.append(cstr!("h"), h); - pt.append(cstr!("l"), l); - pt.append(cstr!("c"), c); - pt -} - -fn assert_report_invariants(report: &CurateFx1dRunReport) { - assert_eq!(report.eod_docs_framed as usize, report.eod_decode.docs_in); - assert_eq!( - report.eod_decode.docs_in, - report.eod_decode.decoded + report.eod_decode.rejected_total() - ); - assert_eq!( - report.eod_decode.decoded, - report.eod_cad_forex_kept + report.eod_other_symbol_skipped - ); - assert_eq!( - report.eod_cad_forex_kept, - report.curate_stats.builder.eod.rows_in - ); - - assert_eq!(report.te_docs_framed as usize, report.te_decode.docs_in); - assert_eq!( - report.te_decode.docs_in, - report.te_decode.docs_matched - + report.te_decode.docs_other_symbol - + report.te_decode.docs_rejected_total() - ); - assert_eq!( - report.te_decode.points_in, - report.te_decode.points_decoded + report.te_decode.rejected_total() - ); - assert_eq!( - report.te_decode.points_decoded, - report.curate_stats.builder.te.rows_in - ); - - assert_eq!( - report.curate_stats.rows_in, - report.curate_stats.builder.rows_out - ); - assert_eq!(report.curate_stats.rows_out, report.curate_stats.rows_in); - assert_eq!(report.write_stats.rows_written, report.curate_stats.rows_out); -} - -#[derive(Debug, PartialEq)] -struct ReadFxRow { - pair: String, - session_date: i32, - ts_micros: i64, - open: f64, - high: f64, - low: f64, - close: f64, - source: String, - known_at_micros: i64, -} - -fn read_fx_parquet(path: &Path) -> Vec { - let file = File::open(path).expect("open fx_1d/part.parquet"); - let reader = SerializedFileReader::new(file).expect("parquet reader"); - let mut rows = Vec::new(); - for row_res in reader.get_row_iter(None).expect("row iter") { - let row = row_res.expect("row"); - let session_date = match row.get_column_iter().nth(1).unwrap().1 { - Field::Date(d) => *d, - other => panic!("expected Date field at col 1, got {other:?}"), - }; - rows.push(ReadFxRow { - pair: row.get_string(0).unwrap().clone(), - session_date, - ts_micros: row.get_timestamp_micros(2).unwrap(), - open: row.get_double(3).unwrap(), - high: row.get_double(4).unwrap(), - low: row.get_double(5).unwrap(), - close: row.get_double(6).unwrap(), - source: row.get_string(7).unwrap().clone(), - known_at_micros: row.get_timestamp_micros(8).unwrap(), - }); - } - rows -} - -fn strip_timing_line(report_text: &str) -> String { - report_text - .lines() - .filter(|l| !l.trim_start().starts_with("timing:")) - .collect::>() - .join("\n") -} - -#[test] -fn end_to_end_curation_precedence_gap_tail_and_permutation_invariance() { - let tmp = TestTempDir::new("fx-e2e"); - let eod_path = tmp.path.join("eodPrices.bson"); - let te_path = tmp.path.join("teMarketData.bson"); - let out_a = tmp.path.join("out_a"); - let out_b = tmp.path.join("out_b"); - - let d1 = day(2025, 1, 2); - let d2 = day(2025, 1, 3); // interior gap in EOD -> TE fills - let d3 = day(2025, 1, 6); - let d4 = day(2026, 1, 2); // post-EOD tail -> TE fills - - // Build EOD docs: CAD.FOREX (d1, d3), wrong-case "cad.forex" (must be skipped!), - // other symbol "AAPL.US" (skipped), and 1 malformed doc (missing close -> rejected). - let mut malformed_eod = RawDocumentBuf::new(); - malformed_eod.append(cstr!("eodSearchCode"), "CAD.FOREX"); - malformed_eod.append(cstr!("date"), "2025-01-07"); - malformed_eod.append(cstr!("open"), 1.43_f64); - malformed_eod.append(cstr!("high"), 1.44_f64); - malformed_eod.append(cstr!("low"), 1.42_f64); - malformed_eod.append(cstr!("volume"), 0.0_f64); - - let eod_docs = vec![ - eod_doc("CAD.FOREX", "2025-01-02", 1.430, 1.440, 1.425, 1.435, 0.0), - eod_doc("cad.forex", "2025-01-03", 9.990, 9.995, 9.985, 9.990, 0.0), - eod_doc("AAPL.US", "2025-01-02", 240.0, 245.0, 239.0, 244.0, 1000.0), - eod_doc("CAD.FOREX", "2025-01-06", 1.436, 1.442, 1.430, 1.438, 12.0), - malformed_eod.as_bytes().to_vec(), - ]; - - // Build TE docs: other symbol ("EURUSD"), uppercase "USDCAD" (overlap d1 + gap d2 + bad point), - // lowercase "usdcad" (tail d4 + ignored `monthly`). - let mut other_te_daily = RawArrayBuf::new(); - other_te_daily.push(te_point_secs(d1, 1.05, 1.06, 1.04, 1.055)); - let mut other_te_doc = RawDocumentBuf::new(); - other_te_doc.append(cstr!("teSymbol"), "EURUSD"); - other_te_doc.append(cstr!("daily"), other_te_daily); - - let mut bad_te_pt = RawDocumentBuf::new(); - bad_te_pt.append(cstr!("t"), i64::from(d4) * MILLIS_PER_DAY); - bad_te_pt.append(cstr!("o"), f64::NAN); - bad_te_pt.append(cstr!("h"), 1.39_f64); - bad_te_pt.append(cstr!("l"), 1.37_f64); - bad_te_pt.append(cstr!("c"), 1.38_f64); - - let mut te_daily_1 = RawArrayBuf::new(); - te_daily_1.push(te_point_secs(d1, 1.431, 1.441, 1.426, 1.436)); // overlaps d1 -> EOD wins - te_daily_1.push(te_point_ms(d2, 1.434, 1.439, 1.431, 1.437)); // interior gap -> TE fills - te_daily_1.push(bad_te_pt); - let mut te_doc_1 = RawDocumentBuf::new(); - te_doc_1.append(cstr!("teSymbol"), "USDCAD"); - te_doc_1.append(cstr!("daily"), te_daily_1); - - let mut te_daily_2 = RawArrayBuf::new(); - te_daily_2.push(te_point_ms(d4, 1.380, 1.390, 1.375, 1.385)); // tail -> TE fills - let mut ignored_monthly = RawArrayBuf::new(); - ignored_monthly.push("bad-monthly-ignored"); - let mut te_doc_2 = RawDocumentBuf::new(); - te_doc_2.append(cstr!("monthly"), ignored_monthly); - te_doc_2.append(cstr!("daily"), te_daily_2); - te_doc_2.append(cstr!("teSymbol"), "usdcad"); - - let te_docs = [ - other_te_doc.as_bytes().to_vec(), - te_doc_1.as_bytes().to_vec(), - te_doc_2.as_bytes().to_vec(), - ]; - - // Write run A in forward order - fs::write(&eod_path, eod_docs.concat()).unwrap(); - fs::write(&te_path, te_docs.concat()).unwrap(); - - let args_a = CurateFx1dArgs { - eod_prices: eod_path.clone(), - te_market_data: te_path.clone(), - te_symbol: DEFAULT_TE_SYMBOL.to_string(), - out_dir: out_a.clone(), - }; - let report_a = run_curate_fx_1d(&args_a).expect("run A succeeds"); - assert_report_invariants(&report_a); - - assert_eq!(report_a.eod_docs_framed, 5); - assert_eq!(report_a.eod_cad_forex_kept, 2); - assert_eq!(report_a.eod_other_symbol_skipped, 2); // "cad.forex" + "AAPL.US" - assert_eq!(report_a.eod_decode.rejected_missing_field, 1); - - assert_eq!(report_a.te_docs_framed, 3); - assert_eq!(report_a.te_decode.docs_matched, 2); - assert_eq!(report_a.te_decode.docs_other_symbol, 1); - assert_eq!(report_a.te_decode.points_in, 4); - assert_eq!(report_a.te_decode.points_decoded, 3); - assert_eq!(report_a.te_decode.rejected_non_finite, 1); - - assert_eq!(report_a.curate_stats.rows_out, 4); - assert_eq!(report_a.curate_stats.builder.eod_rows_out, 2); - assert_eq!(report_a.curate_stats.builder.te_rows_out, 2); - assert_eq!(report_a.curate_stats.builder.te_superseded_by_eod, 1); - assert_eq!(report_a.curate_stats.builder.overlap_checked, 1); - assert_eq!(report_a.curate_stats.builder.overlap_within_tolerance, 1); - assert_eq!(report_a.write_stats.rows_written, 4); - assert_eq!(report_a.write_stats.files_written, 1); - - let parquet_a = out_a.join("fx_1d/part.parquet"); - let rows = read_fx_parquet(&parquet_a); - assert_eq!(rows.len(), 4); - - let expected_dates = [d1, d2, d3, d4]; - let expected_sources = [ - FxSource::EodCadForex.as_str(), - FxSource::TeUsdCad.as_str(), - FxSource::EodCadForex.as_str(), - FxSource::TeUsdCad.as_str(), - ]; - for (i, row) in rows.iter().enumerate() { - assert_eq!(row.pair, FX_PAIR_USDCAD); - assert_eq!(row.session_date, expected_dates[i]); - let expected_ts = fx_1d_utc_day_end_micros(expected_dates[i]).unwrap(); - assert_eq!(row.ts_micros, expected_ts); - assert_eq!(row.known_at_micros, expected_ts); - assert_eq!(row.source, expected_sources[i]); - } - // Strictly ascending & unique - for w in rows.windows(2) { - assert!(w[0].session_date < w[1].session_date); - } - // d1 EOD bitwise OHLC preserved - assert_eq!(rows[0].open.to_bits(), 1.430_f64.to_bits()); - assert_eq!(rows[0].high.to_bits(), 1.440_f64.to_bits()); - assert_eq!(rows[0].low.to_bits(), 1.425_f64.to_bits()); - assert_eq!(rows[0].close.to_bits(), 1.435_f64.to_bits()); - // d2 TE gap fill - assert_eq!(rows[1].close.to_bits(), 1.437_f64.to_bits()); - // d4 TE tail fill - assert_eq!(rows[3].close.to_bits(), 1.385_f64.to_bits()); - - // Write run B with reversed doc order AND shuffled `daily` point order inside `te_doc_1` -> - // byte-identical Parquet and identical report (sans timing). - let mut te_daily_1_shuffled = RawArrayBuf::new(); - let mut bad_te_pt_b = RawDocumentBuf::new(); - bad_te_pt_b.append(cstr!("t"), i64::from(d4) * MILLIS_PER_DAY); - bad_te_pt_b.append(cstr!("o"), f64::NAN); - bad_te_pt_b.append(cstr!("h"), 1.39_f64); - bad_te_pt_b.append(cstr!("l"), 1.37_f64); - bad_te_pt_b.append(cstr!("c"), 1.38_f64); - te_daily_1_shuffled.push(bad_te_pt_b); - te_daily_1_shuffled.push(te_point_ms(d2, 1.434, 1.439, 1.431, 1.437)); - te_daily_1_shuffled.push(te_point_secs(d1, 1.431, 1.441, 1.426, 1.436)); - let mut te_doc_1_shuffled = RawDocumentBuf::new(); - te_doc_1_shuffled.append(cstr!("teSymbol"), "USDCAD"); - te_doc_1_shuffled.append(cstr!("daily"), te_daily_1_shuffled); - - let te_docs_shuffled = [ - te_doc_2.as_bytes().to_vec(), - te_doc_1_shuffled.as_bytes().to_vec(), - other_te_doc.as_bytes().to_vec(), - ]; - - let eod_rev: Vec = eod_docs.into_iter().rev().flatten().collect(); - let te_rev: Vec = te_docs_shuffled.into_iter().flatten().collect(); - let eod_rev_path = tmp.path.join("eodPrices_rev.bson"); - let te_rev_path = tmp.path.join("teMarketData_rev.bson"); - fs::write(&eod_rev_path, eod_rev).unwrap(); - fs::write(&te_rev_path, te_rev).unwrap(); - - let args_b = CurateFx1dArgs { - eod_prices: eod_rev_path, - te_market_data: te_rev_path, - te_symbol: "usdcad".to_string(), - out_dir: out_b.clone(), - }; - let report_b = run_curate_fx_1d(&args_b).expect("run B succeeds"); - assert_report_invariants(&report_b); - - let parquet_b = out_b.join("fx_1d/part.parquet"); - assert_eq!( - fs::read(&parquet_a).unwrap(), - fs::read(&parquet_b).unwrap(), - "shuffled BSON input must yield byte-identical fx_1d/part.parquet" - ); - assert_eq!( - strip_timing_line(&format_curate_fx_report(&report_a)), - strip_timing_line(&format_curate_fx_report(&report_b)) - ); -} - -#[test] -fn failure_modes_return_typed_errors_and_preserve_existing_parquet() { - let tmp = TestTempDir::new("fx-fail"); - let out_dir = tmp.path.join("out"); - let fx_dir = out_dir.join("fx_1d"); - fs::create_dir_all(&fx_dir).unwrap(); - let live_parquet = fx_dir.join("part.parquet"); - let sentinel = b"EXISTING-FX-PARQUET-SENTINEL-BYTES"; - fs::write(&live_parquet, sentinel).unwrap(); - - let valid_eod = tmp.path.join("valid_eod.bson"); - fs::write( - &valid_eod, - eod_doc("CAD.FOREX", "2025-01-02", 1.43, 1.44, 1.42, 1.435, 0.0), - ) - .unwrap(); - - let valid_te = tmp.path.join("valid_te.bson"); - let mut valid_te_daily = RawArrayBuf::new(); - valid_te_daily.push(te_point_secs(day(2025, 1, 2), 1.43, 1.44, 1.42, 1.435)); - let mut valid_te_doc = RawDocumentBuf::new(); - valid_te_doc.append(cstr!("teSymbol"), "USDCAD"); - valid_te_doc.append(cstr!("daily"), valid_te_daily); - fs::write(&valid_te, valid_te_doc.as_bytes()).unwrap(); - - let check_sentinel = || { - assert_eq!( - fs::read(&live_parquet).unwrap(), - sentinel, - "existing fx_1d/part.parquet must remain byte-identical on failure" - ); - }; - - // 1. Truncated BSON in eodPrices - let trunc_eod = tmp.path.join("trunc_eod.bson"); - fs::write(&trunc_eod, [20, 0, 0, 0, 1, 2]).unwrap(); - let err = run_curate_fx_1d(&CurateFx1dArgs { - eod_prices: trunc_eod, - te_market_data: valid_te.clone(), - te_symbol: "USDCAD".to_string(), - out_dir: out_dir.clone(), - }) - .unwrap_err(); - assert!(matches!(err, RunCurateFxError::BsonStream { label: "eod-prices", .. }), "{err:?}"); - check_sentinel(); - - // 2. Truncated BSON in teMarketData - let trunc_te = tmp.path.join("trunc_te.bson"); - fs::write(&trunc_te, [20, 0, 0, 0, 1, 2]).unwrap(); - let err = run_curate_fx_1d(&CurateFx1dArgs { - eod_prices: valid_eod.clone(), - te_market_data: trunc_te, - te_symbol: "USDCAD".to_string(), - out_dir: out_dir.clone(), - }) - .unwrap_err(); - assert!( - matches!(err, RunCurateFxError::BsonStream { label: "te-market-data", .. }), - "{err:?}" - ); - check_sentinel(); - - // 3. Corrupt framed BSON bytes in eodPrices - let corrupt_eod = tmp.path.join("corrupt_eod.bson"); - fs::write(&corrupt_eod, [12, 0, 0, 0, 0xFF, b'a', 0, 0, 0, 0, 0, 0]).unwrap(); - let err = run_curate_fx_1d(&CurateFx1dArgs { - eod_prices: corrupt_eod, - te_market_data: valid_te.clone(), - te_symbol: "USDCAD".to_string(), - out_dir: out_dir.clone(), - }) - .unwrap_err(); - assert!(matches!(err, RunCurateFxError::CorruptEodBson { .. }), "{err:?}"); - check_sentinel(); - - // 4. Corrupt BSON inside teMarketData `daily` array - let corrupt_te = tmp.path.join("corrupt_te.bson"); - let mut bad_te_bytes = valid_te_doc.as_bytes().to_vec(); - // Corrupt the element type byte of the first element inside `daily` array. - // Find `daily\0` in raw bytes; the array starts right after `daily\0` (4-byte len, then elem type). - let daily_pos = bad_te_bytes - .windows(6) - .position(|w| w == b"daily\0") - .expect("find daily key"); - let first_array_elem_type_idx = daily_pos + 6 + 4; - bad_te_bytes[first_array_elem_type_idx] = 0xFF; - fs::write(&corrupt_te, &bad_te_bytes).unwrap(); - let err = run_curate_fx_1d(&CurateFx1dArgs { - eod_prices: valid_eod.clone(), - te_market_data: corrupt_te, - te_symbol: "USDCAD".to_string(), - out_dir: out_dir.clone(), - }) - .unwrap_err(); - assert!( - matches!( - err, - RunCurateFxError::CorruptTeBson { - source: BsonTeMarketDataError::CorruptPointBson { .. }, - .. - } - ), - "{err:?}" - ); - check_sentinel(); - - // 5. Missing eodPrices file - let err = run_curate_fx_1d(&CurateFx1dArgs { - eod_prices: tmp.path.join("does_not_exist_eod.bson"), - te_market_data: valid_te.clone(), - te_symbol: "USDCAD".to_string(), - out_dir: out_dir.clone(), - }) - .unwrap_err(); - assert!(matches!(err, RunCurateFxError::OpenInput { label: "eod-prices", .. }), "{err:?}"); - check_sentinel(); - - // 6. Missing teMarketData file - let err = run_curate_fx_1d(&CurateFx1dArgs { - eod_prices: valid_eod.clone(), - te_market_data: tmp.path.join("does_not_exist_te.bson"), - te_symbol: "USDCAD".to_string(), - out_dir: out_dir.clone(), - }) - .unwrap_err(); - assert!( - matches!(err, RunCurateFxError::OpenInput { label: "te-market-data", .. }), - "{err:?}" - ); - check_sentinel(); - - // 7. --out pointing at an existing regular file - let out_file = tmp.path.join("regular_file"); - fs::write(&out_file, b"not-a-dir").unwrap(); - let err = run_curate_fx_1d(&CurateFx1dArgs { - eod_prices: valid_eod.clone(), - te_market_data: valid_te.clone(), - te_symbol: "USDCAD".to_string(), - out_dir: out_file, - }) - .unwrap_err(); - assert!(matches!(err, RunCurateFxError::InvalidOutDir { .. }), "{err:?}"); - check_sentinel(); - - // 8. Blank and non-USD/CAD te_symbol selectors rejected before reading dumps - for bad_sym in [" ", "EURUSD", "CADUSD", " usdcad "] { - let err = run_curate_fx_1d(&CurateFx1dArgs { - eod_prices: valid_eod.clone(), - te_market_data: valid_te.clone(), - te_symbol: bad_sym.to_string(), - out_dir: out_dir.clone(), - }) - .unwrap_err(); - assert!( - matches!(err, RunCurateFxError::InvalidTeSymbol { .. }), - "expected InvalidTeSymbol for '{bad_sym}', got {err:?}" - ); - check_sentinel(); - } - - // 9. Zero decoded bars across both inputs (only non-matching symbols / empty daily) - let other_eod = tmp.path.join("other_eod.bson"); - fs::write( - &other_eod, - eod_doc("EUR.FOREX", "2025-01-02", 1.10, 1.11, 1.09, 1.105, 0.0), - ) - .unwrap(); - let empty_te = tmp.path.join("empty_te.bson"); - let mut empty_te_doc = RawDocumentBuf::new(); - empty_te_doc.append(cstr!("teSymbol"), "USDCAD"); - empty_te_doc.append(cstr!("daily"), RawArrayBuf::new()); - fs::write(&empty_te, empty_te_doc.as_bytes()).unwrap(); - let err = run_curate_fx_1d(&CurateFx1dArgs { - eod_prices: other_eod, - te_market_data: empty_te.clone(), - te_symbol: "USDCAD".to_string(), - out_dir: out_dir.clone(), - }) - .unwrap_err(); - assert!(matches!(err, RunCurateFxError::NoDecodedBars { .. }), "{err:?}"); - check_sentinel(); - - // 10. Corruption after a semantic reject in TE point must fail with CorruptTeBson - // and preserve existing Parquet even when valid bars exist alongside it. - let corrupt_after_semantic_te = tmp.path.join("corrupt_after_semantic_te.bson"); - let mut bad_pt = RawDocumentBuf::new(); - bad_pt.append(cstr!("t"), f64::NAN); - bad_pt.append(cstr!("o"), 1.43_f64); - bad_pt.append(cstr!("h"), 1.44_f64); - bad_pt.append(cstr!("l"), 1.42_f64); - bad_pt.append(cstr!("c"), 1.435_f64); - let mut mixed_daily = RawArrayBuf::new(); - mixed_daily.push(te_point_secs(day(2025, 1, 3), 1.43, 1.44, 1.42, 1.435)); - mixed_daily.push(bad_pt); - let mut mixed_te_doc = RawDocumentBuf::new(); - mixed_te_doc.append(cstr!("teSymbol"), "USDCAD"); - mixed_te_doc.append(cstr!("daily"), mixed_daily); - let mut mixed_te_bytes = mixed_te_doc.as_bytes().to_vec(); - // Corrupt element type of `c` in the second point (after `t: NaN`). - let second_c_pos = mixed_te_bytes - .windows(3) - .rposition(|w| w == b"\x01c\0") - .expect("find double element 'c' in second point"); - mixed_te_bytes[second_c_pos] = 0xFF; - fs::write(&corrupt_after_semantic_te, &mixed_te_bytes).unwrap(); - let err = run_curate_fx_1d(&CurateFx1dArgs { - eod_prices: valid_eod.clone(), - te_market_data: corrupt_after_semantic_te, - te_symbol: "USDCAD".to_string(), - out_dir: out_dir.clone(), - }) - .unwrap_err(); - assert!( - matches!( - err, - RunCurateFxError::CorruptTeBson { - source: BsonTeMarketDataError::CorruptPointBson { point_index: 1, .. }, - .. - } - ), - "expected CorruptTeBson after semantic point reject, got {err:?}" - ); - check_sentinel(); - - // 11. Corruption after a semantic reject in EOD doc must fail with CorruptEodBson - // and preserve existing Parquet even when valid bars exist alongside it. - let corrupt_after_semantic_eod = tmp.path.join("corrupt_after_semantic_eod.bson"); - let mut bad_eod_bytes = - eod_doc("CAD.FOREX", "2025-01-03", f64::NAN, 1.44, 1.42, 1.435, 0.0); - let close_pos = bad_eod_bytes - .windows(7) - .position(|w| w == b"\x01close\0") - .expect("find double element 'close'"); - bad_eod_bytes[close_pos] = 0xFF; - let mut combined_eod = eod_doc("CAD.FOREX", "2025-01-02", 1.43, 1.44, 1.42, 1.435, 0.0); - combined_eod.extend_from_slice(&bad_eod_bytes); - fs::write(&corrupt_after_semantic_eod, &combined_eod).unwrap(); - let err = run_curate_fx_1d(&CurateFx1dArgs { - eod_prices: corrupt_after_semantic_eod, - te_market_data: valid_te.clone(), - te_symbol: "USDCAD".to_string(), - out_dir: out_dir.clone(), - }) - .unwrap_err(); - assert!( - matches!( - err, - RunCurateFxError::CorruptEodBson { - source: BsonEodPriceError::CorruptBson { .. }, - .. - } - ), - "expected CorruptEodBson after semantic EOD reject, got {err:?}" - ); - check_sentinel(); - - // 12. Zero publishable rows after FX builder filtering (e.g. zero close) returns NoCuratedRows - // and preserves existing Parquet byte-identically. - let zero_close_eod = tmp.path.join("zero_close_eod.bson"); - fs::write( - &zero_close_eod, - eod_doc("CAD.FOREX", "2025-01-02", 1.43, 1.44, 1.42, 0.0, 0.0), - ) - .unwrap(); - let err = run_curate_fx_1d(&CurateFx1dArgs { - eod_prices: zero_close_eod, - te_market_data: empty_te.clone(), - te_symbol: "USDCAD".to_string(), - out_dir: out_dir.clone(), - }) - .unwrap_err(); - assert!( - matches!( - err, - RunCurateFxError::NoCuratedRows { - eod_bars_in: 1, - te_bars_in: 0, - .. - } - ), - "expected NoCuratedRows when builder drops all bars, got {err:?}" - ); - check_sentinel(); - - // 13. Conflicting duplicates dropping all bars also returns NoCuratedRows and preserves sentinel. - let conflict_eod = tmp.path.join("conflict_eod.bson"); - let mut conflict_bytes = eod_doc("CAD.FOREX", "2025-01-02", 1.43, 1.44, 1.42, 1.435, 0.0); - conflict_bytes.extend_from_slice(&eod_doc( - "CAD.FOREX", - "2025-01-02", - 1.43, - 1.44, - 1.42, - 1.436, - 0.0, - )); - fs::write(&conflict_eod, &conflict_bytes).unwrap(); - let err = run_curate_fx_1d(&CurateFx1dArgs { - eod_prices: conflict_eod, - te_market_data: empty_te, - te_symbol: "USDCAD".to_string(), - out_dir: out_dir.clone(), - }) - .unwrap_err(); - assert!( - matches!( - err, - RunCurateFxError::NoCuratedRows { - eod_bars_in: 2, - te_bars_in: 0, - .. - } - ), - "expected NoCuratedRows on conflicting duplicates, got {err:?}" - ); - check_sentinel(); -} - -#[test] -fn single_source_runs_succeed_and_rerun_fully_replaces_previous_output() { - let tmp = TestTempDir::new("fx-single-source"); - let out_dir = tmp.path.join("out"); - let empty_file = tmp.path.join("empty.bson"); - fs::write(&empty_file, []).unwrap(); - - // Run 1: EOD-only (TE file is zero bytes). - let eod_path = tmp.path.join("eod.bson"); - let mut eod_bytes = Vec::new(); - eod_bytes.extend_from_slice(&eod_doc( - "CAD.FOREX", - "2025-01-02", - 1.430, - 1.440, - 1.425, - 1.435, - 0.0, - )); - eod_bytes.extend_from_slice(&eod_doc( - "CAD.FOREX", - "2025-01-03", - 1.435, - 1.445, - 1.430, - 1.440, - 0.0, - )); - fs::write(&eod_path, &eod_bytes).unwrap(); - - let report1 = run_curate_fx_1d(&CurateFx1dArgs { - eod_prices: eod_path, - te_market_data: empty_file.clone(), - te_symbol: "USDCAD".to_string(), - out_dir: out_dir.clone(), - }) - .expect("EOD-only run should succeed"); - assert_report_invariants(&report1); - let parquet_path = out_dir.join("fx_1d").join("part.parquet"); - let rows1 = read_fx_parquet(&parquet_path); - assert_eq!(rows1.len(), 2); - assert!(rows1 - .iter() - .all(|r| r.source == FxSource::EodCadForex.as_str())); - - // Run 2: TE-only (EOD file is zero bytes) into the same out_dir must fully replace output. - let te_path = tmp.path.join("te.bson"); - let mut daily = RawArrayBuf::new(); - daily.push(te_point_secs(day(2025, 2, 10), 1.420, 1.430, 1.415, 1.425)); - let mut te_doc = RawDocumentBuf::new(); - te_doc.append(cstr!("teSymbol"), "USDCAD"); - te_doc.append(cstr!("daily"), daily); - fs::write(&te_path, te_doc.as_bytes()).unwrap(); - - let report2 = run_curate_fx_1d(&CurateFx1dArgs { - eod_prices: empty_file, - te_market_data: te_path, - te_symbol: "USDCAD".to_string(), - out_dir, - }) - .expect("TE-only rerun should succeed"); - assert_report_invariants(&report2); - let rows2 = read_fx_parquet(&parquet_path); - assert_eq!(rows2.len(), 1); - assert_eq!(rows2[0].session_date, day(2025, 2, 10)); - assert_eq!(rows2[0].source, FxSource::TeUsdCad.as_str()); -} - -#[test] -fn truncated_dump_after_valid_documents_fails_and_preserves_existing_parquet() { - let tmp = TestTempDir::new("fx-trunc-tail"); - let out_dir = tmp.path.join("out"); - let fx_dir = out_dir.join("fx_1d"); - fs::create_dir_all(&fx_dir).unwrap(); - let parquet_path = fx_dir.join("part.parquet"); - let sentinel = b"SENTINEL_PARQUET_TAIL_TRUNC"; - fs::write(&parquet_path, sentinel).unwrap(); - - let valid_eod = tmp.path.join("valid_eod.bson"); - fs::write( - &valid_eod, - eod_doc("CAD.FOREX", "2025-01-02", 1.43, 1.44, 1.42, 1.435, 0.0), - ) - .unwrap(); - - let valid_te = tmp.path.join("valid_te.bson"); - let mut daily = RawArrayBuf::new(); - daily.push(te_point_secs(day(2025, 1, 3), 1.43, 1.44, 1.42, 1.435)); - let mut te_doc = RawDocumentBuf::new(); - te_doc.append(cstr!("teSymbol"), "USDCAD"); - te_doc.append(cstr!("daily"), daily); - fs::write(&valid_te, te_doc.as_bytes()).unwrap(); - - // 1. EOD dump truncated mid-document after two valid documents. - let trunc_eod = tmp.path.join("trunc_after_valid_eod.bson"); - let mut eod_bytes = Vec::new(); - eod_bytes.extend_from_slice(&eod_doc( - "CAD.FOREX", - "2025-01-02", - 1.43, - 1.44, - 1.42, - 1.435, - 0.0, - )); - eod_bytes.extend_from_slice(&eod_doc( - "CAD.FOREX", - "2025-01-03", - 1.435, - 1.445, - 1.43, - 1.44, - 0.0, - )); - let third = eod_doc("CAD.FOREX", "2025-01-06", 1.44, 1.45, 1.435, 1.445, 0.0); - eod_bytes.extend_from_slice(&third[..third.len() / 2]); - fs::write(&trunc_eod, &eod_bytes).unwrap(); - - let err = run_curate_fx_1d(&CurateFx1dArgs { - eod_prices: trunc_eod, - te_market_data: valid_te.clone(), - te_symbol: "USDCAD".to_string(), - out_dir: out_dir.clone(), - }) - .unwrap_err(); - assert!( - matches!(err, RunCurateFxError::BsonStream { .. }), - "expected BsonStream for truncated EOD tail, got {err:?}" - ); - assert_eq!(fs::read(&parquet_path).unwrap(), sentinel); - - // 2. TE dump truncated mid-document after a valid document. - let trunc_te = tmp.path.join("trunc_after_valid_te.bson"); - let mut te_bytes = te_doc.as_bytes().to_vec(); - let half = te_doc.as_bytes().len() / 2; - te_bytes.extend_from_slice(&te_doc.as_bytes()[..half]); - fs::write(&trunc_te, &te_bytes).unwrap(); - - let err = run_curate_fx_1d(&CurateFx1dArgs { - eod_prices: valid_eod, - te_market_data: trunc_te, - te_symbol: "USDCAD".to_string(), - out_dir, - }) - .unwrap_err(); - assert!( - matches!(err, RunCurateFxError::BsonStream { .. }), - "expected BsonStream for truncated TE tail, got {err:?}" - ); - assert_eq!(fs::read(&parquet_path).unwrap(), sentinel); -} - -#[test] -fn corrupt_bytes_in_non_usdcad_te_document_abort_run_with_exact_offset() { - let tmp = TestTempDir::new("fx-corrupt-other-te"); - let out_dir = tmp.path.join("out"); - let fx_dir = out_dir.join("fx_1d"); - fs::create_dir_all(&fx_dir).unwrap(); - let parquet_path = fx_dir.join("part.parquet"); - let sentinel = b"SENTINEL_PARQUET_OTHER_TE"; - fs::write(&parquet_path, sentinel).unwrap(); - - let empty_eod = tmp.path.join("empty_eod.bson"); - fs::write(&empty_eod, []).unwrap(); - - // First doc: valid USDCAD. - let mut daily1 = RawArrayBuf::new(); - daily1.push(te_point_secs(day(2025, 1, 3), 1.43, 1.44, 1.42, 1.435)); - let mut doc1 = RawDocumentBuf::new(); - doc1.append(cstr!("teSymbol"), "USDCAD"); - doc1.append(cstr!("daily"), daily1); - let doc1_len = doc1.as_bytes().len(); - - // Second doc: non-USDCAD (EURUSD) with a corrupted element tag after teSymbol. - let mut doc2 = RawDocumentBuf::new(); - doc2.append(cstr!("teSymbol"), "EURUSD"); - doc2.append(cstr!("extra"), 42_i32); - let mut doc2_bytes = doc2.as_bytes().to_vec(); - let extra_pos = doc2_bytes - .windows(7) - .position(|w| w == b"\x10extra\0") - .expect("find int32 element 'extra'"); - doc2_bytes[extra_pos] = 0xFF; - - let mut te_bytes = doc1.as_bytes().to_vec(); - te_bytes.extend_from_slice(&doc2_bytes); - let te_path = tmp.path.join("te.bson"); - fs::write(&te_path, &te_bytes).unwrap(); - - let err = run_curate_fx_1d(&CurateFx1dArgs { - eod_prices: empty_eod, - te_market_data: te_path, - te_symbol: "USDCAD".to_string(), - out_dir, - }) - .unwrap_err(); - match err { - RunCurateFxError::CorruptTeBson { - source: BsonTeMarketDataError::CorruptBson { offset, .. }, - .. - } => assert_eq!(offset, doc1_len), - other => panic!("expected CorruptTeBson at offset {doc1_len}, got {other:?}"), - } - assert_eq!(fs::read(&parquet_path).unwrap(), sentinel); -} - -#[test] -fn te_data_quality_doc_rejects_are_counted_and_run_continues() { - let tmp = TestTempDir::new("fx-te-doc-rejects"); - let out_dir = tmp.path.join("out"); - let empty_eod = tmp.path.join("empty_eod.bson"); - fs::write(&empty_eod, []).unwrap(); - - let mut te_bytes = Vec::new(); - // 1. Missing `daily` on matched symbol. - let mut missing_daily = RawDocumentBuf::new(); - missing_daily.append(cstr!("teSymbol"), "USDCAD"); - te_bytes.extend_from_slice(missing_daily.as_bytes()); - - // 2. Non-array `daily` on matched symbol. - let mut bad_daily = RawDocumentBuf::new(); - bad_daily.append(cstr!("teSymbol"), "USDCAD"); - bad_daily.append(cstr!("daily"), "not-an-array"); - te_bytes.extend_from_slice(bad_daily.as_bytes()); - - // 3. Blank `teSymbol`. - let mut blank_sym = RawDocumentBuf::new(); - blank_sym.append(cstr!("teSymbol"), " "); - blank_sym.append(cstr!("daily"), RawArrayBuf::new()); - te_bytes.extend_from_slice(blank_sym.as_bytes()); - - // 4. Valid USDCAD document. - let mut valid_daily = RawArrayBuf::new(); - valid_daily.push(te_point_secs(day(2025, 1, 6), 1.43, 1.44, 1.42, 1.435)); - let mut valid_doc = RawDocumentBuf::new(); - valid_doc.append(cstr!("teSymbol"), "USDCAD"); - valid_doc.append(cstr!("daily"), valid_daily); - te_bytes.extend_from_slice(valid_doc.as_bytes()); - - let te_path = tmp.path.join("te.bson"); - fs::write(&te_path, &te_bytes).unwrap(); - - let report = run_curate_fx_1d(&CurateFx1dArgs { - eod_prices: empty_eod, - te_market_data: te_path, - te_symbol: "USDCAD".to_string(), - out_dir, - }) - .expect("data-quality rejects should be counted without aborting"); - assert_report_invariants(&report); - assert_eq!(report.te_decode.docs_in, 4); - assert_eq!(report.te_decode.docs_matched, 1); - assert_eq!(report.te_decode.rejected_daily_missing, 1); - assert_eq!(report.te_decode.rejected_daily_not_array, 1); - assert_eq!(report.te_decode.rejected_empty_symbol, 1); - assert_eq!(report.write_stats.rows_written, 1); -} - -#[test] -fn te_utc_day_edge_timestamps_never_have_known_at_before_raw_t() { - let tmp = TestTempDir::new("fx-no-lookahead"); - let out_dir = tmp.path.join("out"); - let empty_eod = tmp.path.join("empty_eod.bson"); - fs::write(&empty_eod, []).unwrap(); - - // (raw_t, expected_session_date, raw_t_micros) sorted by expected_session_date across - // pre-1970 and post-1970 UTC day edges in both seconds and milliseconds. - let cases: &[(i64, i32, i64)] = &[ - (-100_000_000_001, -1158, -100_000_000_001_000), // 1966-10-30 14:13:19.999 UTC (ms) - (-86_401, -2, -86_401_000_000), // 1969-12-30 23:59:59 UTC (s) - (-1, -1, -1_000_000), // 1969-12-31 23:59:59 UTC (s) - (0, 0, 0), // 1970-01-01 00:00:00 UTC (s) - (86_400, 1, 86_400_000_000), // 1970-01-02 00:00:00 UTC (s) - (1_735_689_599_999, day(2024, 12, 31), 1_735_689_599_999_000), // 2024-12-31 23:59:59.999 UTC (ms) - (1_735_689_600_000, day(2025, 1, 1), 1_735_689_600_000_000), // 2025-01-01 00:00:00.000 UTC (ms) - ]; - - let mut daily = RawArrayBuf::new(); - for &(raw_t, _, _) in cases { - let mut pt = RawDocumentBuf::new(); - pt.append(cstr!("t"), raw_t); - pt.append(cstr!("o"), 1.35_f64); - pt.append(cstr!("h"), 1.36_f64); - pt.append(cstr!("l"), 1.34_f64); - pt.append(cstr!("c"), 1.355_f64); - daily.push(pt); - } - let mut te_doc = RawDocumentBuf::new(); - te_doc.append(cstr!("teSymbol"), "USDCAD"); - te_doc.append(cstr!("daily"), daily); - let te_path = tmp.path.join("te.bson"); - fs::write(&te_path, te_doc.as_bytes()).unwrap(); - - let report = run_curate_fx_1d(&CurateFx1dArgs { - eod_prices: empty_eod, - te_market_data: te_path, - te_symbol: "USDCAD".to_string(), - out_dir: out_dir.clone(), - }) - .expect("day-edge run should succeed"); - assert_report_invariants(&report); - - let rows = read_fx_parquet(&out_dir.join("fx_1d").join("part.parquet")); - assert_eq!(rows.len(), cases.len()); - for (row, &(_, expected_day, raw_t_micros)) in rows.iter().zip(cases.iter()) { - assert_eq!(row.session_date, expected_day); - assert_eq!( - row.known_at_micros, - fx_1d_utc_day_end_micros(expected_day).expect("valid day-end micros") - ); - assert!( - row.known_at_micros >= raw_t_micros, - "look-ahead violation: session_date={} known_at={} < raw_t={}", - row.session_date, - row.known_at_micros, - raw_t_micros - ); - } -} diff --git a/tools/curate-etl/src/run_curate_macro.rs b/tools/curate-etl/src/run_curate_macro.rs deleted file mode 100644 index 6d2320b8..00000000 --- a/tools/curate-etl/src/run_curate_macro.rs +++ /dev/null @@ -1,657 +0,0 @@ -//! File-to-file `curate-macro` runner (`M2.2s`). -//! -//! Reads a concatenated length-prefixed raw BSON `teData` dump and a caller-supplied -//! series-map TSV into an atomically published `/macro/part.parquet` dataset via -//! [`curate_and_write_macro`]. -//! -//! # Governance & Series-Map Contract -//! - **Caller-owned mapping (no defaults):** Every row in the series-map TSV maps a verbatim -//! `(te_symbol, country, category)` triple (no trimming, no case folding) to a -//! [`MacroSeriesTarget`] (`country_iso`, `indicator`, `lag_class`). No country-to-ISO, -//! indicator-name, or lag-class mapping is hardcoded here because live `teData` labels are -//! unverified and Quant Research owns the coarse regime-use policy. -//! - **Strict TSV format (`load_macro_series_map_tsv`):** -//! - Required exact line-1 header: -//! `te_symbol\tcountry\tcategory\tcountry_iso\tindicator\tlag_class` -//! - LF (`\n`) and CRLF (`\r\n`) line endings are accepted; bare/embedded `\r` and invalid UTF-8 -//! fail closed with the 1-based physical line number. -//! - Every data row must have exactly 6 nonempty tab-separated fields, verbatim keys, an exact -//! `lag_class` token in `{policy_rate, monthly_release, gdp65, gdp90}`, and unique -//! `(te_symbol, country, category)` triples (duplicates fail closed even when targets match). -//! -//! # Decode, Buffering & Fail-Closed Policy -//! - **Series-map validation first:** The entire series map is parsed and validated before any -//! `teData` bytes are decoded or `out_dir` is touched. -//! - **In-memory file-mode buffering:** `run_curate_macro_with_readers` buffers the concatenated -//! `teData` BSON input and collects borrowed [`TeDataPoint`] views from -//! [`decode_te_data_buffer`] before calling [`curate_and_write_macro`], so memory usage grows -//! with input size. -//! - **Decode error policy (matching `run_curate_fx.rs`):** Per-document and per-point semantic -//! rejects (missing/empty/wrong-type `teSymbol`, `country`, `category`, `data`, non-document -//! points, invalid point dates/values) are counted in [`BsonTeDataDecodeStats`] and skipped so -//! valid points continue. Structural BSON framing or element corruption -//! ([`BsonTeDataError::TruncatedDocument`], [`BsonTeDataError::CorruptDocumentLength`], -//! [`BsonTeDataError::CorruptBson`], [`BsonTeDataError::CorruptPointBson`]) is captured on the -//! first occurrence and returned as [`RunCurateMacroError::CorruptTeDataBson`] before publishing, -//! preventing partial datasets from a truncated or corrupt tail. -//! - **Atomic publish & zero-row preservation:** Any series-map, I/O, structural BSON, or curation -//! error (such as [`crate::curate_macro::CurateMacroError::ConflictingLagClass`]) returns before -//! writing, leaving `out_dir` and any pre-existing `/macro/part.parquet` byte-identical. -//! Empty or all-unmapped inputs preserve [`curate_and_write_macro`]'s zero-row success no-op. -//! -//! # Counter Conservation Invariants -//! Every successful [`CurateMacroRunReport`] satisfies: -//! - `decode_stats.docs_in == decode_stats.docs_accepted + decode_stats.docs_rejected_total()` -//! - `decode_stats.points_in == decode_stats.points_decoded + decode_stats.rejected_total()` -//! - `decode_stats.points_decoded == curate_stats.points_in` -//! - `curate_stats.points_in == curate_stats.dropped_unmapped_series + curate_stats.builder.input` -//! - `curate_stats.rows_out == curate_stats.builder.emitted == write_stats.rows_written` - -use std::collections::BTreeMap; -use std::error::Error; -use std::fmt::{self, Write as _}; -use std::fs::File; -use std::io::{self, BufRead, BufReader}; -use std::path::{Path, PathBuf}; - -use crate::bson_te_data::{ - decode_te_data_buffer, BsonTeDataDecodeStats, BsonTeDataError, TeDataPoint, -}; -use crate::curate_macro::{ - curate_and_write_macro, CurateMacroError, CurateMacroStats, CurateMacroWriteError, - MacroSeriesTarget, -}; -use crate::macro_series::MacroLagClass; -use crate::parquet_macro::{MacroWriteOptions, MacroWriteStats, ParquetMacroError}; - -/// Required exact header line (line 1) for the macro series-map TSV. -pub const MACRO_SERIES_MAP_HEADER: &str = - "te_symbol\tcountry\tcategory\tcountry_iso\tindicator\tlag_class"; - -const ROLE_TE_DATA: &str = "te-data"; -const ROLE_SERIES_MAP: &str = "series-map"; -const SERIES_MAP_COLUMN_COUNT: usize = 6; -const SERIES_MAP_COLUMNS: [&str; SERIES_MAP_COLUMN_COUNT] = [ - "te_symbol", - "country", - "category", - "country_iso", - "indicator", - "lag_class", -]; - -/// File-mode arguments for [`run_curate_macro`]. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct CurateMacroArgs { - pub te_data: PathBuf, - pub series_map: PathBuf, - pub out_dir: PathBuf, -} - -/// Validated caller-owned lookup from verbatim `(te_symbol, country, category)` triples to -/// [`MacroSeriesTarget`], loaded by [`load_macro_series_map_tsv`]. -/// -/// Backed by nested [`BTreeMap`]s so lookups accept borrowed `&str` slices with zero allocation. -#[derive(Debug, Clone, Default, PartialEq, Eq)] -pub struct MacroSeriesMap { - entries: BTreeMap>>, - len: usize, -} - -impl MacroSeriesMap { - /// Returns the number of mapped series entries. - #[inline] - pub fn len(&self) -> usize { - self.len - } - - /// Returns `true` if the series map contains no entries. - #[inline] - pub fn is_empty(&self) -> bool { - self.len == 0 - } - - /// Looks up a verbatim `(te_symbol, country, category)` triple without trimming or case folding. - #[inline] - pub fn get( - &self, - te_symbol: &str, - country: &str, - category: &str, - ) -> Option<&MacroSeriesTarget> { - self.entries - .get(te_symbol) - .and_then(|by_country| by_country.get(country)) - .and_then(|by_category| by_category.get(category)) - } - - fn insert( - &mut self, - te_symbol: String, - country: String, - category: String, - target: MacroSeriesTarget, - ) -> bool { - let by_category = self - .entries - .entry(te_symbol) - .or_default() - .entry(country) - .or_default(); - if by_category.contains_key(&category) { - return false; - } - by_category.insert(category, target); - self.len += 1; - true - } -} - -/// Full run report produced by [`run_curate_macro`] and [`run_curate_macro_with_readers`]. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct CurateMacroRunReport { - pub series_map_entries: usize, - pub decode_stats: BsonTeDataDecodeStats, - pub curate_stats: CurateMacroStats, - pub write_stats: MacroWriteStats, -} - -/// Typed errors returned by [`load_macro_series_map_tsv`], [`run_curate_macro`], and -/// [`run_curate_macro_with_readers`]. -/// -/// Every variant's `Display` output is guaranteed to be a single line (CR and LF in dynamic -/// strings, paths, and wrapped error messages are escaped as `\r` and `\n`). -#[derive(Debug)] -pub enum RunCurateMacroError { - /// Failed to open a file-mode input (`te-data` or `series-map`). - OpenInput { - role: &'static str, - path: PathBuf, - source: io::Error, - }, - /// Failed to read bytes from an input stream (`te-data` or `series-map`). - ReadInput { - role: &'static str, - path: Option, - source: io::Error, - }, - /// Series-map TSV line contained invalid UTF-8 or a bare/embedded carriage return. - SeriesMapMalformedLine { line: usize, detail: &'static str }, - /// Series-map TSV was empty or line 1 did not match [`MACRO_SERIES_MAP_HEADER`] verbatim. - SeriesMapBadHeader { line: usize, found: Option }, - /// Series-map TSV data row did not contain exactly 6 tab-separated columns. - SeriesMapWrongColumnCount { - line: usize, - expected: usize, - actual: usize, - }, - /// Series-map TSV data row contained an empty (or blank) required field. - SeriesMapEmptyField { line: usize, column: &'static str }, - /// Series-map TSV data row contained an unknown `lag_class` token. - SeriesMapUnknownLagClass { line: usize, value: String }, - /// Series-map TSV contained a duplicate `(te_symbol, country, category)` triple. - SeriesMapDuplicateKey { - line: usize, - te_symbol: String, - country: String, - category: String, - }, - /// Structural BSON framing or element corruption in `teData` input. - CorruptTeDataBson { - path: Option, - offset: usize, - source: BsonTeDataError, - }, - /// Error returned by [`curate_and_write_macro`] (curation or Parquet write). - CurateWrite(CurateMacroWriteError), -} - -impl RunCurateMacroError { - fn with_input_paths(self, te_data: &Path, series_map: &Path) -> Self { - match self { - Self::ReadInput { - role, - path: None, - source, - } => { - let path = match role { - ROLE_TE_DATA => Some(te_data.to_path_buf()), - ROLE_SERIES_MAP => Some(series_map.to_path_buf()), - _ => None, - }; - Self::ReadInput { role, path, source } - } - Self::CorruptTeDataBson { - path: None, - offset, - source, - } => Self::CorruptTeDataBson { - path: Some(te_data.to_path_buf()), - offset, - source, - }, - other => other, - } - } -} - -struct SingleLineWriter<'a, 'b> { - f: &'a mut fmt::Formatter<'b>, -} - -impl fmt::Write for SingleLineWriter<'_, '_> { - fn write_str(&mut self, s: &str) -> fmt::Result { - let mut rest = s; - while let Some(idx) = rest.find(['\n', '\r']) { - let (head, tail) = rest.split_at(idx); - if !head.is_empty() { - self.f.write_str(head)?; - } - let mut chars = tail.chars(); - match chars.next() { - Some('\n') => self.f.write_str("\\n")?, - Some('\r') => self.f.write_str("\\r")?, - _ => unreachable!(), - } - rest = chars.as_str(); - } - if !rest.is_empty() { - self.f.write_str(rest)?; - } - Ok(()) - } -} - -impl fmt::Display for RunCurateMacroError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let mut w = SingleLineWriter { f }; - match self { - Self::OpenInput { role, path, source } => { - write!(w, "failed to open {role} '{}': {source}", path.display()) - } - Self::ReadInput { role, path, source } => match path { - Some(path) => write!(w, "failed to read {role} '{}': {source}", path.display()), - None => write!(w, "failed to read {role}: {source}"), - }, - Self::SeriesMapMalformedLine { line, detail } => { - write!(w, "series-map TSV line {line}: {detail}") - } - Self::SeriesMapBadHeader { line, found } => match found { - Some(found) => write!( - w, - "series-map TSV line {line}: invalid header {found:?}; expected exact {MACRO_SERIES_MAP_HEADER:?}" - ), - None => write!( - w, - "series-map TSV line {line}: missing required header {MACRO_SERIES_MAP_HEADER:?}" - ), - }, - Self::SeriesMapWrongColumnCount { - line, - expected, - actual, - } => write!( - w, - "series-map TSV line {line}: expected {expected} tab-separated columns, got {actual}" - ), - Self::SeriesMapEmptyField { line, column } => { - write!( - w, - "series-map TSV line {line}: field '{column}' must not be empty" - ) - } - Self::SeriesMapUnknownLagClass { line, value } => write!( - w, - "series-map TSV line {line}: unknown lag_class {value:?}; expected one of 'policy_rate', 'monthly_release', 'gdp65', 'gdp90'" - ), - Self::SeriesMapDuplicateKey { - line, - te_symbol, - country, - category, - } => write!( - w, - "series-map TSV line {line}: duplicate series key ({te_symbol:?}, {country:?}, {category:?})" - ), - Self::CorruptTeDataBson { - path, - offset, - source, - } => match path { - Some(path) => write!( - w, - "corrupt {ROLE_TE_DATA} BSON '{}' at byte offset {offset}: {source}", - path.display() - ), - None => write!( - w, - "corrupt {ROLE_TE_DATA} BSON at byte offset {offset}: {source}" - ), - }, - Self::CurateWrite(source) => write!(w, "{source}"), - } - } -} - -impl Error for RunCurateMacroError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::OpenInput { source, .. } | Self::ReadInput { source, .. } => Some(source), - Self::CorruptTeDataBson { source, .. } => Some(source), - Self::CurateWrite(source) => Some(source), - Self::SeriesMapMalformedLine { .. } - | Self::SeriesMapBadHeader { .. } - | Self::SeriesMapWrongColumnCount { .. } - | Self::SeriesMapEmptyField { .. } - | Self::SeriesMapUnknownLagClass { .. } - | Self::SeriesMapDuplicateKey { .. } => None, - } - } -} - -impl From for RunCurateMacroError { - fn from(err: CurateMacroWriteError) -> Self { - Self::CurateWrite(err) - } -} - -impl From for RunCurateMacroError { - fn from(err: CurateMacroError) -> Self { - Self::CurateWrite(CurateMacroWriteError::Curate(err)) - } -} - -impl From for RunCurateMacroError { - fn from(err: ParquetMacroError) -> Self { - Self::CurateWrite(CurateMacroWriteError::Parquet(err)) - } -} - -#[inline] -fn parse_lag_class_token(token: &str) -> Option { - match token { - "policy_rate" => Some(MacroLagClass::PolicyRate), - "monthly_release" => Some(MacroLagClass::MonthlyRelease), - "gdp65" => Some(MacroLagClass::Gdp65), - "gdp90" => Some(MacroLagClass::Gdp90), - _ => None, - } -} - -#[inline] -fn is_structural_te_data_bson_error(err: &BsonTeDataError) -> bool { - matches!( - err, - BsonTeDataError::TruncatedDocument { .. } - | BsonTeDataError::CorruptDocumentLength { .. } - | BsonTeDataError::CorruptBson { .. } - | BsonTeDataError::CorruptPointBson { .. } - ) -} - -/// Parses and validates a caller-supplied macro series-map TSV into a [`MacroSeriesMap`]. -/// -/// Format: -/// - Line 1 must be the exact header -/// `te_symbol\tcountry\tcategory\tcountry_iso\tindicator\tlag_class`. -/// - Each subsequent line must have 6 nonempty tab-separated fields, preserved verbatim (no -/// trimming or case folding), with `lag_class` in -/// `{"policy_rate", "monthly_release", "gdp65", "gdp90"}` and unique -/// `(te_symbol, country, category)` keys. -pub fn load_macro_series_map_tsv( - reader: R, -) -> Result { - let mut buf_reader = BufReader::new(reader); - let mut raw_buf: Vec = Vec::with_capacity(256); - let mut line_no: usize = 0; - let mut map = MacroSeriesMap::default(); - let mut saw_header = false; - - loop { - raw_buf.clear(); - let bytes_read = buf_reader.read_until(b'\n', &mut raw_buf).map_err(|source| { - RunCurateMacroError::ReadInput { - role: ROLE_SERIES_MAP, - path: None, - source, - } - })?; - if bytes_read == 0 { - break; - } - line_no += 1; - - let mut slice = raw_buf.as_slice(); - if slice.ends_with(b"\n") { - slice = &slice[..slice.len() - 1]; - if slice.ends_with(b"\r") { - slice = &slice[..slice.len() - 1]; - } - } - if slice.contains(&b'\r') { - return Err(RunCurateMacroError::SeriesMapMalformedLine { - line: line_no, - detail: "unexpected carriage return inside TSV line", - }); - } - - let line = std::str::from_utf8(slice).map_err(|_| { - RunCurateMacroError::SeriesMapMalformedLine { - line: line_no, - detail: "invalid UTF-8 in TSV line", - } - })?; - - if !saw_header { - if line != MACRO_SERIES_MAP_HEADER { - return Err(RunCurateMacroError::SeriesMapBadHeader { - line: 1, - found: Some(line.to_owned()), - }); - } - saw_header = true; - continue; - } - - let cols: Vec<&str> = line.split('\t').collect(); - if cols.len() != SERIES_MAP_COLUMN_COUNT { - return Err(RunCurateMacroError::SeriesMapWrongColumnCount { - line: line_no, - expected: SERIES_MAP_COLUMN_COUNT, - actual: cols.len(), - }); - } - - for (idx, (&col, &col_name)) in cols.iter().zip(SERIES_MAP_COLUMNS.iter()).enumerate() { - let is_empty = if idx == 5 { - col.is_empty() - } else { - col.trim().is_empty() - }; - if is_empty { - return Err(RunCurateMacroError::SeriesMapEmptyField { - line: line_no, - column: col_name, - }); - } - } - - let te_symbol = cols[0]; - let country = cols[1]; - let category = cols[2]; - let country_iso = cols[3]; - let indicator = cols[4]; - let lag_token = cols[5]; - - let lag_class = parse_lag_class_token(lag_token).ok_or_else(|| { - RunCurateMacroError::SeriesMapUnknownLagClass { - line: line_no, - value: lag_token.to_owned(), - } - })?; - - let target = MacroSeriesTarget { - country_iso: country_iso.to_owned(), - indicator: indicator.to_owned(), - lag_class, - }; - - if !map.insert( - te_symbol.to_owned(), - country.to_owned(), - category.to_owned(), - target, - ) { - return Err(RunCurateMacroError::SeriesMapDuplicateKey { - line: line_no, - te_symbol: te_symbol.to_owned(), - country: country.to_owned(), - category: category.to_owned(), - }); - } - } - - if !saw_header { - return Err(RunCurateMacroError::SeriesMapBadHeader { - line: 1, - found: None, - }); - } - - Ok(map) -} - -/// Runs file-mode `curate-macro` from arbitrary [`io::Read`] streams for `teData` BSON and -/// the series-map TSV, publishing `/macro/part.parquet` via [`curate_and_write_macro`]. -/// -/// The series map is validated in full before `te_data` is decoded or `out_dir` is touched. Any -/// map, I/O, structural BSON, or curation error returns before publishing and leaves `out_dir` and -/// any pre-existing `/macro/part.parquet` untouched. -pub fn run_curate_macro_with_readers( - mut te_data: RT, - series_map: RM, - out_dir: &Path, -) -> Result { - let map = load_macro_series_map_tsv(series_map)?; - - let mut te_data_buf = Vec::new(); - te_data - .read_to_end(&mut te_data_buf) - .map_err(|source| RunCurateMacroError::ReadInput { - role: ROLE_TE_DATA, - path: None, - source, - })?; - - let mut points: Vec> = Vec::new(); - let mut structural_err: Option<(usize, BsonTeDataError)> = None; - let decode_stats = decode_te_data_buffer( - &te_data_buf, - |point| points.push(point), - |offset, err| { - if structural_err.is_none() && is_structural_te_data_bson_error(&err) { - structural_err = Some((offset, err)); - } - }, - ); - if let Some((offset, source)) = structural_err { - return Err(RunCurateMacroError::CorruptTeDataBson { - path: None, - offset, - source, - }); - } - - let write_report = curate_and_write_macro( - out_dir, - points, - |te_symbol, country, category| map.get(te_symbol, country, category).cloned(), - MacroWriteOptions::default(), - )?; - - Ok(CurateMacroRunReport { - series_map_entries: map.len(), - decode_stats, - curate_stats: write_report.curate_stats, - write_stats: write_report.write_stats, - }) -} - -/// Runs file-mode `curate-macro` by opening `args.series_map` and `args.te_data` and delegating -/// to [`run_curate_macro_with_readers`]. -/// -/// File open, read, and structural BSON errors attach the offending role (`te-data` or -/// `series-map`) and path. Any error returns before writing to `args.out_dir`. -pub fn run_curate_macro(args: &CurateMacroArgs) -> Result { - let series_map_file = - File::open(&args.series_map).map_err(|source| RunCurateMacroError::OpenInput { - role: ROLE_SERIES_MAP, - path: args.series_map.clone(), - source, - })?; - let te_data_file = - File::open(&args.te_data).map_err(|source| RunCurateMacroError::OpenInput { - role: ROLE_TE_DATA, - path: args.te_data.clone(), - source, - })?; - - run_curate_macro_with_readers(te_data_file, series_map_file, &args.out_dir) - .map_err(|err| err.with_input_paths(&args.te_data, &args.series_map)) -} - -/// Formats [`CurateMacroRunReport`] into deterministic multi-line `key=value` text. -pub fn format_curate_macro_report(report: &CurateMacroRunReport) -> String { - let d = &report.decode_stats; - let c = &report.curate_stats; - let b = &c.builder; - let w = &report.write_stats; - format!( - "curate-etl curate-macro\n\ - \x20 map: entries={}\n\ - \x20 decode: docs_in={} docs_accepted={} docs_rejected={} (missing_symbol={} empty_symbol={} wrong_symbol_type={} missing_country={} empty_country={} wrong_country_type={} missing_category={} empty_category={} wrong_category_type={} data_missing={} data_not_array={} corrupt_doc={}) points_in={} points_decoded={} points_rejected={} (not_doc={} invalid_date={} invalid_value={} corrupt_point={})\n\ - \x20 builder: input={} emitted={} skipped_unmapped_indicator={} skipped_non_finite_value={} skipped_duplicate={}\n\ - \x20 curate: points_in={} rows_out={} dropped_unmapped_series={} series_out={}\n\ - \x20 write: files={} row_groups={} rows_written={} bytes_written={}", - report.series_map_entries, - d.docs_in, - d.docs_accepted, - d.docs_rejected_total(), - d.rejected_missing_symbol, - d.rejected_empty_symbol, - d.rejected_wrong_symbol_type, - d.rejected_missing_country, - d.rejected_empty_country, - d.rejected_wrong_country_type, - d.rejected_missing_category, - d.rejected_empty_category, - d.rejected_wrong_category_type, - d.rejected_data_missing, - d.rejected_data_not_array, - d.rejected_corrupt_document, - d.points_in, - d.points_decoded, - d.rejected_total(), - d.rejected_point_not_document, - d.rejected_invalid_date, - d.rejected_invalid_value, - d.rejected_corrupt_point, - b.input, - b.emitted, - b.skipped_unmapped_indicator, - b.skipped_non_finite_value, - b.skipped_duplicate, - c.points_in, - c.rows_out, - c.dropped_unmapped_series, - c.series_out, - w.files_written, - w.row_groups_written, - w.rows_written, - w.bytes_written, - ) -} - -#[cfg(test)] -#[path = "run_curate_macro_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/run_curate_macro_tests.rs b/tools/curate-etl/src/run_curate_macro_tests.rs deleted file mode 100644 index 6399ef2e..00000000 --- a/tools/curate-etl/src/run_curate_macro_tests.rs +++ /dev/null @@ -1,1328 +0,0 @@ -use std::borrow::Cow; -use std::error::Error as StdError; -use std::fs::{self, File}; -use std::io; -use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; - -use bson::raw::{cstr, RawArrayBuf, RawDocumentBuf}; -use bson::DateTime; -use parquet::column::reader::ColumnReader; -use parquet::file::reader::{FileReader, SerializedFileReader}; - -use super::{ - format_curate_macro_report, load_macro_series_map_tsv, run_curate_macro, - run_curate_macro_with_readers, CurateMacroArgs, CurateMacroRunReport, RunCurateMacroError, - MACRO_SERIES_MAP_HEADER, -}; -use crate::bson_te_data::BsonTeDataError; -use crate::curate_macro::{CurateMacroError, CurateMacroWriteError, MacroSeriesTarget}; -use crate::macro_series::{ - MacroLagClass, GDP65_LAG_DAYS, GDP90_LAG_DAYS, MACRO_KNOWN_AT_SOURCE, - MONTHLY_RELEASE_LAG_DAYS, POLICY_RATE_LAG_DAYS, -}; -use crate::parquet_macro::{MacroParquetRow, ParquetMacroError}; -use crate::split::ymd_to_epoch_days; - -const MICROS_PER_DAY: i64 = 86_400_000_000; - -static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0); - -struct TempDirGuard { - path: PathBuf, -} - -impl TempDirGuard { - fn new(label: &str) -> Self { - let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); - let pid = std::process::id(); - let path = std::env::temp_dir().join(format!( - "curate-etl-run-curate-macro-test-{label}-{pid}-{seq}" - )); - let _ = fs::remove_dir_all(&path); - fs::create_dir_all(&path).expect("create test temp dir"); - Self { path } - } - - fn path(&self) -> &Path { - &self.path - } -} - -impl Drop for TempDirGuard { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.path); - } -} - -struct FailingReader { - message: &'static str, -} - -impl io::Read for FailingReader { - fn read(&mut self, _buf: &mut [u8]) -> io::Result { - Err(io::Error::other(self.message)) - } -} - -fn day(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).expect("valid date") -} - -fn make_point_doc(d: &str, v: f64) -> RawDocumentBuf { - let mut pt = RawDocumentBuf::new(); - pt.append(cstr!("d"), d); - pt.append(cstr!("v"), v); - pt -} - -fn make_te_data_doc( - te_symbol: &str, - country: &str, - category: &str, - data_points: &[(&str, f64)], - forecast_points: &[(&str, f64)], -) -> RawDocumentBuf { - let mut data_arr = RawArrayBuf::new(); - for &(d, v) in data_points { - data_arr.push(make_point_doc(d, v)); - } - - let mut forecast_arr = RawArrayBuf::new(); - for &(d, v) in forecast_points { - forecast_arr.push(make_point_doc(d, v)); - } - - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("teSymbol"), te_symbol); - doc.append(cstr!("name"), format!("{country} {category}")); - doc.append(cstr!("unit"), "percent"); - doc.append(cstr!("source"), "TradingEconomics"); - doc.append(cstr!("frequency"), "Monthly"); - doc.append(cstr!("country"), country); - doc.append(cstr!("category"), category); - doc.append(cstr!("data"), data_arr); - doc.append(cstr!("forecast"), forecast_arr); - doc.append( - cstr!("lastUpdated"), - DateTime::from_millis(1_710_000_000_000), - ); - doc.append(cstr!("createdAt"), DateTime::from_millis(1_700_000_000_000)); - doc -} - -fn concat_docs(docs: &[RawDocumentBuf]) -> Vec { - let mut buf = Vec::new(); - for doc in docs { - buf.extend_from_slice(doc.as_bytes()); - } - buf -} - -fn expected_row( - country_iso: &'static str, - indicator: &'static str, - period_date: i32, - lag_days: i32, - value: f64, -) -> MacroParquetRow { - MacroParquetRow { - country_iso: Cow::Borrowed(country_iso), - indicator: Cow::Borrowed(indicator), - period_date, - known_at_micros: i64::from(period_date + lag_days) * MICROS_PER_DAY, - known_at_source: Cow::Borrowed(MACRO_KNOWN_AT_SOURCE), - value, - } -} - -fn read_parquet_rows(path: &Path) -> Vec { - let file = File::open(path).expect("open parquet file"); - let reader = SerializedFileReader::new(file).expect("open parquet reader"); - let metadata = reader.metadata(); - let mut out = Vec::new(); - - for rg_idx in 0..metadata.num_row_groups() { - let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); - let num_rows = metadata.row_group(rg_idx).num_rows() as usize; - - let read_i32 = |col_idx: usize| -> Vec { - let mut vals = Vec::with_capacity(num_rows); - match rg_reader.get_column_reader(col_idx).expect("col reader") { - ColumnReader::Int32ColumnReader(mut r) => { - let (read, _, _) = r - .read_records(num_rows, None, None, &mut vals) - .expect("read i32"); - assert_eq!(read, num_rows); - } - _ => panic!("expected INT32 column at index {col_idx}"), - } - vals - }; - let read_i64 = |col_idx: usize| -> Vec { - let mut vals = Vec::with_capacity(num_rows); - match rg_reader.get_column_reader(col_idx).expect("col reader") { - ColumnReader::Int64ColumnReader(mut r) => { - let (read, _, _) = r - .read_records(num_rows, None, None, &mut vals) - .expect("read i64"); - assert_eq!(read, num_rows); - } - _ => panic!("expected INT64 column at index {col_idx}"), - } - vals - }; - let read_f64 = |col_idx: usize| -> Vec { - let mut vals = Vec::with_capacity(num_rows); - match rg_reader.get_column_reader(col_idx).expect("col reader") { - ColumnReader::DoubleColumnReader(mut r) => { - let (read, _, _) = r - .read_records(num_rows, None, None, &mut vals) - .expect("read f64"); - assert_eq!(read, num_rows); - } - _ => panic!("expected DOUBLE column at index {col_idx}"), - } - vals - }; - let read_str = |col_idx: usize| -> Vec { - let mut vals = Vec::with_capacity(num_rows); - match rg_reader.get_column_reader(col_idx).expect("col reader") { - ColumnReader::ByteArrayColumnReader(mut r) => { - let (read, _, _) = r - .read_records(num_rows, None, None, &mut vals) - .expect("read utf8"); - assert_eq!(read, num_rows); - } - _ => panic!("expected BYTE_ARRAY column at index {col_idx}"), - } - vals.into_iter() - .map(|b| { - std::str::from_utf8(b.data()) - .expect("valid utf8") - .to_owned() - }) - .collect() - }; - - let country_iso = read_str(0); - let indicator = read_str(1); - let period_date = read_i32(2); - let known_at_micros = read_i64(3); - let known_at_source = read_str(4); - let value = read_f64(5); - - for i in 0..num_rows { - out.push(MacroParquetRow { - country_iso: Cow::Owned(country_iso[i].clone()), - indicator: Cow::Owned(indicator[i].clone()), - period_date: period_date[i], - known_at_micros: known_at_micros[i], - known_at_source: Cow::Owned(known_at_source[i].clone()), - value: value[i], - }); - } - } - out -} - -fn assert_rows_bitwise_eq(actual: &[MacroParquetRow], expected: &[MacroParquetRow]) { - assert_eq!(actual.len(), expected.len(), "row count mismatch"); - for (idx, (a, e)) in actual.iter().zip(expected.iter()).enumerate() { - assert_eq!(a.country_iso, e.country_iso, "row {idx} country_iso"); - assert_eq!(a.indicator, e.indicator, "row {idx} indicator"); - assert_eq!(a.period_date, e.period_date, "row {idx} period_date"); - assert_eq!( - a.known_at_micros, e.known_at_micros, - "row {idx} known_at_micros" - ); - assert_eq!( - a.known_at_source, e.known_at_source, - "row {idx} known_at_source" - ); - assert_eq!( - a.value.to_bits(), - e.value.to_bits(), - "row {idx} value bits ({} vs {})", - a.value, - e.value - ); - } -} - -fn assert_single_line(msg: &str) { - assert!( - !msg.contains('\n') && !msg.contains('\r'), - "expected single-line message without CR/LF, got: {msg:?}" - ); -} - -fn assert_report_conservation(report: &CurateMacroRunReport, parquet_rows: usize) { - let d = &report.decode_stats; - let c = &report.curate_stats; - let b = &c.builder; - let w = &report.write_stats; - - assert_eq!(d.docs_in, d.docs_accepted + d.docs_rejected_total()); - assert_eq!(d.points_in, d.points_decoded + d.rejected_total()); - assert_eq!(d.points_decoded, c.points_in); - assert_eq!(c.points_in, c.dropped_unmapped_series + b.input); - assert_eq!(c.rows_out, b.emitted); - assert_eq!(b.skipped_unmapped_indicator, 0); - assert_eq!( - b.input, - b.emitted + b.skipped_unmapped_indicator + b.skipped_non_finite_value + b.skipped_duplicate - ); - assert_eq!(c.rows_out, w.rows_written); - assert_eq!(w.rows_written, parquet_rows); -} - -fn seed_existing_parquet(out_dir: &Path) -> (PathBuf, Vec) { - let macro_dir = out_dir.join("macro"); - fs::create_dir_all(¯o_dir).expect("create macro dir"); - let part_path = macro_dir.join("part.parquet"); - let sentinel = b"PREEXISTING_MACRO_PARQUET_SENTINEL_BYTES_v1".to_vec(); - fs::write(&part_path, &sentinel).expect("write sentinel parquet"); - (part_path, sentinel) -} - -#[test] -fn end_to_end_pinned_fixture_curates_sorts_filters_and_conserves_stats() { - // Out-of-order BSON fixture with: - // - 2 mapped series with different lag classes (policy_rate +1d, monthly_release +35d), - // multiple out-of-order dates, a forecast sentinel, and 1 invalid point date - // - 1 unmapped series - // - 1 semantic document reject (missing `country`) - let mut cpi_doc = make_te_data_doc( - "USCPIYOY", - "United States", - "Inflation Rate", - &[ - ("2024-03-31", 3.5), - ("2024-02-30", 9.9), // invalid Gregorian date -> point reject - ("2024-01-31", 3.1), - ], - &[("2025-12-31", 999.0)], // forecast sentinel must never leak - ); - // Re-check doc is valid RawDocumentBuf - let _ = &mut cpi_doc; - - let rate_doc = make_te_data_doc( - "CABOC", - "Canada", - "Interest Rate", - &[("2024-04-10", 5.0), ("2024-01-24", 5.0)], - &[("2026-06-01", 888.0)], - ); - - let unmapped_doc = make_te_data_doc( - "UKPMI", - "United Kingdom", - "Manufacturing PMI", - &[("2024-03-31", 50.3)], - &[], - ); - - let mut bad_doc = RawDocumentBuf::new(); - bad_doc.append(cstr!("teSymbol"), "MISSING_COUNTRY"); - bad_doc.append(cstr!("category"), "Interest Rate"); - bad_doc.append(cstr!("data"), RawArrayBuf::new()); - - let bson_bytes = concat_docs(&[cpi_doc, unmapped_doc, bad_doc, rate_doc]); - - let series_map_tsv = format!( - "{MACRO_SERIES_MAP_HEADER}\n\ - CABOC\tCanada\tInterest Rate\tCA\tpolicy_rate\tpolicy_rate\n\ - USCPIYOY\tUnited States\tInflation Rate\tUS\tcpi_yoy\tmonthly_release\n" - ); - - let expected = vec![ - expected_row("CA", "policy_rate", day(2024, 1, 24), POLICY_RATE_LAG_DAYS, 5.0), - expected_row("CA", "policy_rate", day(2024, 4, 10), POLICY_RATE_LAG_DAYS, 5.0), - expected_row( - "US", - "cpi_yoy", - day(2024, 1, 31), - MONTHLY_RELEASE_LAG_DAYS, - 3.1, - ), - expected_row( - "US", - "cpi_yoy", - day(2024, 3, 31), - MONTHLY_RELEASE_LAG_DAYS, - 3.5, - ), - ]; - - // Run 1 via readers - let out1 = TempDirGuard::new("e2e-run1"); - let report1 = run_curate_macro_with_readers( - bson_bytes.as_slice(), - series_map_tsv.as_bytes(), - out1.path(), - ) - .expect("run 1 should succeed"); - - let parquet_path1 = out1.path().join("macro").join("part.parquet"); - let rows1 = read_parquet_rows(&parquet_path1); - assert_rows_bitwise_eq(&rows1, &expected); - assert_report_conservation(&report1, rows1.len()); - - assert_eq!(report1.series_map_entries, 2); - assert_eq!(report1.decode_stats.docs_in, 4); - assert_eq!(report1.decode_stats.docs_accepted, 3); - assert_eq!(report1.decode_stats.rejected_missing_country, 1); - assert_eq!(report1.decode_stats.points_in, 6); - assert_eq!(report1.decode_stats.points_decoded, 5); - assert_eq!(report1.decode_stats.rejected_invalid_date, 1); - assert_eq!(report1.curate_stats.points_in, 5); - assert_eq!(report1.curate_stats.dropped_unmapped_series, 1); - assert_eq!(report1.curate_stats.rows_out, 4); - assert_eq!(report1.curate_stats.series_out, 2); - assert_eq!(report1.write_stats.files_written, 1); - - // Run 2 with identical inputs via readers -> reproducible logical rows and counters - let out2 = TempDirGuard::new("e2e-run2"); - let report2 = run_curate_macro_with_readers( - bson_bytes.as_slice(), - series_map_tsv.as_bytes(), - out2.path(), - ) - .expect("run 2 should succeed"); - let rows2 = read_parquet_rows(&out2.path().join("macro").join("part.parquet")); - assert_rows_bitwise_eq(&rows2, &rows1); - assert_eq!(report2, report1); - - // File-mode run_curate_macro matches reader-mode results - let file_dir = TempDirGuard::new("e2e-file"); - let te_data_path = file_dir.path().join("teData.bson"); - let map_path = file_dir.path().join("series_map.tsv"); - let file_out = file_dir.path().join("out"); - fs::write(&te_data_path, &bson_bytes).expect("write bson fixture"); - fs::write(&map_path, &series_map_tsv).expect("write tsv fixture"); - - let file_report = run_curate_macro(&CurateMacroArgs { - te_data: te_data_path, - series_map: map_path, - out_dir: file_out.clone(), - }) - .expect("file-mode run should succeed"); - let file_rows = read_parquet_rows(&file_out.join("macro").join("part.parquet")); - assert_rows_bitwise_eq(&file_rows, &rows1); - assert_eq!(file_report, report1); -} - -#[test] -fn tsv_loader_accepts_all_four_lag_classes_and_preserves_verbatim_keys_and_crlf() { - let tsv = format!( - "{MACRO_SERIES_MAP_HEADER}\r\n\ - FDTR\tUnited States\tInterest Rate\tUS\tpolicy_rate\tpolicy_rate\r\n\ - USCPI\tUnited States\tInflation Rate\tUS\tcpi_yoy\tmonthly_release\n\ - USGDP\tUnited States\tGDP Growth Rate\tUS\tgdp_qoq\tgdp65\r\n\ - \x20CAGDP \tcanada\tGDP Annual\tCA\tgdp_yoy\tgdp90" - ); - - let map = load_macro_series_map_tsv(tsv.as_bytes()).expect("valid TSV should parse"); - assert_eq!(map.len(), 4); - assert!(!map.is_empty()); - - assert_eq!( - map.get("FDTR", "United States", "Interest Rate"), - Some(&MacroSeriesTarget { - country_iso: "US".to_owned(), - indicator: "policy_rate".to_owned(), - lag_class: MacroLagClass::PolicyRate, - }) - ); - assert_eq!( - map.get("USCPI", "United States", "Inflation Rate"), - Some(&MacroSeriesTarget { - country_iso: "US".to_owned(), - indicator: "cpi_yoy".to_owned(), - lag_class: MacroLagClass::MonthlyRelease, - }) - ); - assert_eq!( - map.get("USGDP", "United States", "GDP Growth Rate"), - Some(&MacroSeriesTarget { - country_iso: "US".to_owned(), - indicator: "gdp_qoq".to_owned(), - lag_class: MacroLagClass::Gdp65, - }) - ); - assert_eq!( - map.get(" CAGDP ", "canada", "GDP Annual"), - Some(&MacroSeriesTarget { - country_iso: "CA".to_owned(), - indicator: "gdp_yoy".to_owned(), - lag_class: MacroLagClass::Gdp90, - }) - ); - - // Verbatim key checks: no trimming, no case folding - assert_eq!(map.get("CAGDP", "canada", "GDP Annual"), None); - assert_eq!(map.get(" CAGDP ", "Canada", "GDP Annual"), None); - assert_eq!(map.get("fdtr", "United States", "Interest Rate"), None); - assert_eq!(MacroLagClass::Gdp65.lag_days(), GDP65_LAG_DAYS); - assert_eq!(MacroLagClass::Gdp90.lag_days(), GDP90_LAG_DAYS); -} - -#[test] -fn tsv_loader_rejects_bad_headers_wrong_columns_empty_fields_unknown_lag_and_duplicates() { - // 1. Empty input -> missing header at line 1 - let err = load_macro_series_map_tsv(&b""[..]).expect_err("empty TSV must fail"); - assert!(matches!( - err, - RunCurateMacroError::SeriesMapBadHeader { - line: 1, - found: None - } - )); - let msg = err.to_string(); - assert_single_line(&msg); - assert!(msg.contains("line 1"), "msg: {msg}"); - - // 2. Wrong header at line 1 - let err = load_macro_series_map_tsv( - b"te_symbol\tcountry\tcategory\tcountry_iso\tindicator\tlag\n".as_slice(), - ) - .expect_err("wrong header must fail"); - assert!(matches!( - err, - RunCurateMacroError::SeriesMapBadHeader { - line: 1, - found: Some(_) - } - )); - let msg = err.to_string(); - assert_single_line(&msg); - assert!(msg.contains("line 1"), "msg: {msg}"); - - // 3. Wrong column count (too few on line 2, too many on line 3, blank line on line 3) - let too_few = format!("{MACRO_SERIES_MAP_HEADER}\nFDTR\tUS\tRate\tUS\tpolicy_rate\n"); - let err = load_macro_series_map_tsv(too_few.as_bytes()).expect_err("5 cols must fail"); - assert!(matches!( - err, - RunCurateMacroError::SeriesMapWrongColumnCount { - line: 2, - expected: 6, - actual: 5 - } - )); - let msg = err.to_string(); - assert_single_line(&msg); - assert!(msg.contains("line 2"), "msg: {msg}"); - - let too_many = format!( - "{MACRO_SERIES_MAP_HEADER}\n\ - FDTR\tUnited States\tInterest Rate\tUS\tpolicy_rate\tpolicy_rate\n\ - A\tB\tC\tD\tE\tpolicy_rate\textra\n" - ); - let err = load_macro_series_map_tsv(too_many.as_bytes()).expect_err("7 cols must fail"); - assert!(matches!( - err, - RunCurateMacroError::SeriesMapWrongColumnCount { - line: 3, - expected: 6, - actual: 7 - } - )); - let msg = err.to_string(); - assert_single_line(&msg); - assert!(msg.contains("line 3"), "msg: {msg}"); - - let blank_line = format!( - "{MACRO_SERIES_MAP_HEADER}\n\ - FDTR\tUnited States\tInterest Rate\tUS\tpolicy_rate\tpolicy_rate\n\ - \n" - ); - let err = load_macro_series_map_tsv(blank_line.as_bytes()).expect_err("blank line must fail"); - assert!(matches!( - err, - RunCurateMacroError::SeriesMapWrongColumnCount { - line: 3, - expected: 6, - actual: 1 - } - )); - assert_single_line(&err.to_string()); - - // 4. Empty field in each column position - let empty_cases = [ - ("\tUnited States\tInterest Rate\tUS\tpolicy_rate\tpolicy_rate", "te_symbol"), - ("FDTR\t\tInterest Rate\tUS\tpolicy_rate\tpolicy_rate", "country"), - ("FDTR\tUnited States\t\tUS\tpolicy_rate\tpolicy_rate", "category"), - ("FDTR\tUnited States\tInterest Rate\t\tpolicy_rate\tpolicy_rate", "country_iso"), - ("FDTR\tUnited States\tInterest Rate\tUS\t\tpolicy_rate", "indicator"), - ("FDTR\tUnited States\tInterest Rate\tUS\tpolicy_rate\t", "lag_class"), - (" \tUnited States\tInterest Rate\tUS\tpolicy_rate\tpolicy_rate", "te_symbol"), - ]; - for (row, expected_col) in empty_cases { - let input = format!("{MACRO_SERIES_MAP_HEADER}\n{row}\n"); - let err = load_macro_series_map_tsv(input.as_bytes()) - .expect_err("empty field must fail"); - assert!( - matches!( - err, - RunCurateMacroError::SeriesMapEmptyField { line: 2, column } - if column == expected_col - ), - "unexpected error for {expected_col}: {err:?}" - ); - let msg = err.to_string(); - assert_single_line(&msg); - assert!(msg.contains("line 2"), "msg: {msg}"); - } - - // 5. Unknown or whitespace-padded lag_class - for bad_lag in ["unknown", "PolicyRate", " policy_rate", "gdp65 ", "gdp30"] { - let input = format!( - "{MACRO_SERIES_MAP_HEADER}\n\ - FDTR\tUnited States\tInterest Rate\tUS\tpolicy_rate\t{bad_lag}\n" - ); - let err = load_macro_series_map_tsv(input.as_bytes()) - .expect_err("unknown lag_class must fail"); - assert!( - matches!( - &err, - RunCurateMacroError::SeriesMapUnknownLagClass { line: 2, value } - if value == bad_lag - ), - "unexpected error for lag_class {bad_lag:?}: {err:?}" - ); - let msg = err.to_string(); - assert_single_line(&msg); - assert!(msg.contains("line 2"), "msg: {msg}"); - } - - // 6. Duplicate key triple (even when target is identical) - let dup_identical = format!( - "{MACRO_SERIES_MAP_HEADER}\n\ - FDTR\tUnited States\tInterest Rate\tUS\tpolicy_rate\tpolicy_rate\n\ - FDTR\tUnited States\tInterest Rate\tUS\tpolicy_rate\tpolicy_rate\n" - ); - let err = load_macro_series_map_tsv(dup_identical.as_bytes()) - .expect_err("identical duplicate key must fail"); - assert!(matches!( - err, - RunCurateMacroError::SeriesMapDuplicateKey { line: 3, .. } - )); - let msg = err.to_string(); - assert_single_line(&msg); - assert!(msg.contains("line 3"), "msg: {msg}"); - - // 7. Bare CR and invalid UTF-8 - let bare_cr = format!("{MACRO_SERIES_MAP_HEADER}\nFDTR\tUS\rX\tRate\tUS\tind\tpolicy_rate\n"); - let err = load_macro_series_map_tsv(bare_cr.as_bytes()).expect_err("bare CR must fail"); - assert!(matches!( - err, - RunCurateMacroError::SeriesMapMalformedLine { line: 2, .. } - )); - assert_single_line(&err.to_string()); - - let mut invalid_utf8 = format!("{MACRO_SERIES_MAP_HEADER}\n").into_bytes(); - invalid_utf8.extend_from_slice(&[0xff, 0xfe, b'\n']); - let err = load_macro_series_map_tsv(invalid_utf8.as_slice()).expect_err("bad UTF-8 must fail"); - assert!(matches!( - err, - RunCurateMacroError::SeriesMapMalformedLine { line: 2, .. } - )); - assert_single_line(&err.to_string()); -} - -#[test] -fn invalid_map_conflicting_lag_class_and_corrupt_bson_leave_outputs_untouched() { - let valid_doc = make_te_data_doc( - "FDTR", - "United States", - "Interest Rate", - &[("2024-03-20", 5.5)], - &[], - ); - let second_doc = make_te_data_doc( - "FDTR_ALT", - "United States", - "Fed Funds", - &[("2024-03-21", 5.5)], - &[], - ); - - // Case A: Invalid series map - let bad_map = format!( - "{MACRO_SERIES_MAP_HEADER}\n\ - FDTR\tUnited States\tInterest Rate\tUS\tpolicy_rate\tnot_a_lag\n" - ); - for seeded in [false, true] { - let out = TempDirGuard::new("fail-bad-map"); - let existing = seeded.then(|| seed_existing_parquet(out.path())); - - let err = run_curate_macro_with_readers(valid_doc.as_bytes(), bad_map.as_bytes(), out.path()) - .expect_err("invalid map must fail"); - assert!(matches!( - err, - RunCurateMacroError::SeriesMapUnknownLagClass { line: 2, .. } - )); - assert_single_line(&err.to_string()); - - if let Some((part_path, sentinel)) = existing { - assert_eq!(fs::read(&part_path).expect("read sentinel"), sentinel); - } else { - assert!(!out.path().join("macro").exists()); - } - } - - // Case B: ConflictingLagClass across two mapped series targeting the same (country_iso, indicator) - let conflict_bson = concat_docs(&[valid_doc.clone(), second_doc]); - let conflict_map = format!( - "{MACRO_SERIES_MAP_HEADER}\n\ - FDTR\tUnited States\tInterest Rate\tUS\tpolicy_rate\tpolicy_rate\n\ - FDTR_ALT\tUnited States\tFed Funds\tUS\tpolicy_rate\tmonthly_release\n" - ); - for seeded in [false, true] { - let out = TempDirGuard::new("fail-conflict-lag"); - let existing = seeded.then(|| seed_existing_parquet(out.path())); - - let err = run_curate_macro_with_readers( - conflict_bson.as_slice(), - conflict_map.as_bytes(), - out.path(), - ) - .expect_err("conflicting lag class must fail"); - assert!(matches!( - err, - RunCurateMacroError::CurateWrite(CurateMacroWriteError::Curate( - CurateMacroError::ConflictingLagClass { .. } - )) - )); - assert_single_line(&err.to_string()); - - if let Some((part_path, sentinel)) = existing { - assert_eq!(fs::read(&part_path).expect("read sentinel"), sentinel); - } else { - assert!(!out.path().join("macro").exists()); - } - } - - // Case C: Valid BSON prefix followed by a truncated BSON tail - let valid_map = format!( - "{MACRO_SERIES_MAP_HEADER}\n\ - FDTR\tUnited States\tInterest Rate\tUS\tpolicy_rate\tpolicy_rate\n" - ); - let mut truncated_bson = valid_doc.as_bytes().to_vec(); - let corrupt_offset = truncated_bson.len(); - // Append a 4-byte length declaring 64 bytes with only 2 trailing bytes present - truncated_bson.extend_from_slice(&64_i32.to_le_bytes()); - truncated_bson.extend_from_slice(&[0x01, 0x02]); - - for seeded in [false, true] { - let out = TempDirGuard::new("fail-truncated-bson"); - let existing = seeded.then(|| seed_existing_parquet(out.path())); - - let err = run_curate_macro_with_readers( - truncated_bson.as_slice(), - valid_map.as_bytes(), - out.path(), - ) - .expect_err("truncated BSON tail must fail"); - assert!(matches!( - err, - RunCurateMacroError::CorruptTeDataBson { - path: None, - offset, - source: BsonTeDataError::TruncatedDocument { .. } - } if offset == corrupt_offset - )); - assert_single_line(&err.to_string()); - - if let Some((part_path, sentinel)) = existing { - assert_eq!(fs::read(&part_path).expect("read sentinel"), sentinel); - } else { - assert!(!out.path().join("macro").exists()); - } - } -} - -#[test] -fn empty_and_all_unmapped_inputs_preserve_zero_row_noop() { - let header_only_map = format!("{MACRO_SERIES_MAP_HEADER}\n"); - let unmapped_doc = make_te_data_doc( - "UNMAPPED", - "Canada", - "CPI", - &[("2024-03-31", 2.9)], - &[], - ); - - for (label, bson_bytes, expected_dropped) in [ - ("empty-bson", Vec::new(), 0usize), - ("all-unmapped", unmapped_doc.as_bytes().to_vec(), 1usize), - ] { - for seeded in [false, true] { - let out = TempDirGuard::new(label); - let existing = seeded.then(|| seed_existing_parquet(out.path())); - - let report = run_curate_macro_with_readers( - bson_bytes.as_slice(), - header_only_map.as_bytes(), - out.path(), - ) - .expect("zero-row input should succeed"); - - assert_eq!(report.series_map_entries, 0); - assert_eq!(report.curate_stats.dropped_unmapped_series, expected_dropped); - assert_eq!(report.curate_stats.rows_out, 0); - assert_eq!(report.write_stats.rows_written, 0); - assert_eq!(report.write_stats.files_written, 0); - assert_report_conservation(&report, 0); - - if let Some((part_path, sentinel)) = existing { - assert_eq!(fs::read(&part_path).expect("read sentinel"), sentinel); - } else { - assert!(!out.path().join("macro").exists()); - } - } - } -} - -#[test] -fn missing_file_paths_and_reader_io_errors_report_role_and_path_without_writing() { - let dir = TempDirGuard::new("io-errors"); - let valid_map_path = dir.path().join("series_map.tsv"); - let valid_bson_path = dir.path().join("teData.bson"); - fs::write(&valid_map_path, format!("{MACRO_SERIES_MAP_HEADER}\n")).expect("write map"); - fs::write(&valid_bson_path, b"").expect("write bson"); - - // 1. Missing te_data with series_map present - let missing_te_data = dir.path().join("does-not-exist-teData.bson"); - let out1 = dir.path().join("out1"); - let err = run_curate_macro(&CurateMacroArgs { - te_data: missing_te_data.clone(), - series_map: valid_map_path.clone(), - out_dir: out1.clone(), - }) - .expect_err("missing te_data must fail"); - assert!(matches!( - &err, - RunCurateMacroError::OpenInput { - role: "te-data", - path, - .. - } if path == &missing_te_data - )); - let msg = err.to_string(); - assert_single_line(&msg); - assert!(msg.contains("te-data"), "msg: {msg}"); - assert!( - msg.contains(&missing_te_data.display().to_string()), - "msg: {msg}" - ); - assert!(!out1.exists()); - - // 2. Missing series_map with te_data present - let missing_map = dir.path().join("does-not-exist-series-map.tsv"); - let out2 = dir.path().join("out2"); - let err = run_curate_macro(&CurateMacroArgs { - te_data: valid_bson_path, - series_map: missing_map.clone(), - out_dir: out2.clone(), - }) - .expect_err("missing series_map must fail"); - assert!(matches!( - &err, - RunCurateMacroError::OpenInput { - role: "series-map", - path, - .. - } if path == &missing_map - )); - let msg = err.to_string(); - assert_single_line(&msg); - assert!(msg.contains("series-map"), "msg: {msg}"); - assert!( - msg.contains(&missing_map.display().to_string()), - "msg: {msg}" - ); - assert!(!out2.exists()); - - // 3. Reader I/O failures in reader mode - let out3 = dir.path().join("out3"); - let err = run_curate_macro_with_readers( - &b""[..], - FailingReader { - message: "map read boom\nline2", - }, - &out3, - ) - .expect_err("failing series_map reader must fail"); - assert!(matches!( - err, - RunCurateMacroError::ReadInput { - role: "series-map", - path: None, - .. - } - )); - assert_single_line(&err.to_string()); - assert!(!out3.exists()); - - let err = run_curate_macro_with_readers( - FailingReader { - message: "bson read boom\r\nline2", - }, - format!("{MACRO_SERIES_MAP_HEADER}\n").as_bytes(), - &out3, - ) - .expect_err("failing te_data reader must fail"); - assert!(matches!( - err, - RunCurateMacroError::ReadInput { - role: "te-data", - path: None, - .. - } - )); - assert_single_line(&err.to_string()); - assert!(!out3.exists()); -} - -#[test] -fn report_formatting_is_deterministic_and_all_error_variants_are_single_line() { - let doc = make_te_data_doc( - "FDTR", - "United States", - "Interest Rate", - &[("2024-03-20", 5.5)], - &[], - ); - let map = format!( - "{MACRO_SERIES_MAP_HEADER}\n\ - FDTR\tUnited States\tInterest Rate\tUS\tpolicy_rate\tpolicy_rate\n" - ); - let out = TempDirGuard::new("report-format"); - let report = run_curate_macro_with_readers(doc.as_bytes(), map.as_bytes(), out.path()) - .expect("run should succeed"); - - let formatted_a = format_curate_macro_report(&report); - let formatted_b = format_curate_macro_report(&report); - assert_eq!(formatted_a, formatted_b); - let lines: Vec<&str> = formatted_a.lines().collect(); - assert_eq!(lines.len(), 6); - assert_eq!(lines[0], "curate-etl curate-macro"); - assert!(lines[1].contains("map:") && lines[1].contains("entries=1")); - assert!( - lines[2].contains("decode:") - && lines[2].contains("docs_in=1") - && lines[2].contains("points_decoded=1") - ); - assert!( - lines[3].contains("builder:") - && lines[3].contains("input=1") - && lines[3].contains("emitted=1") - ); - assert!( - lines[4].contains("curate:") - && lines[4].contains("points_in=1") - && lines[4].contains("rows_out=1") - && lines[4].contains("dropped_unmapped_series=0") - && lines[4].contains("series_out=1") - ); - assert!( - lines[5].contains("write:") - && lines[5].contains("files=1") - && lines[5].contains("rows_written=1") - ); - - // Exhaustive single-line Display + Error::source check across every RunCurateMacroError variant - let adversarial_path = PathBuf::from("dir/bad\npath\rname"); - let variants: Vec<(RunCurateMacroError, bool)> = vec![ - ( - RunCurateMacroError::OpenInput { - role: "te-data", - path: adversarial_path.clone(), - source: io::Error::other("open\nerr\rdetail"), - }, - true, - ), - ( - RunCurateMacroError::ReadInput { - role: "series-map", - path: Some(adversarial_path.clone()), - source: io::Error::other("read\nerr\rdetail"), - }, - true, - ), - ( - RunCurateMacroError::ReadInput { - role: "te-data", - path: None, - source: io::Error::other("read\nno-path"), - }, - true, - ), - ( - RunCurateMacroError::SeriesMapMalformedLine { - line: 4, - detail: "invalid UTF-8 in TSV line", - }, - false, - ), - ( - RunCurateMacroError::SeriesMapBadHeader { - line: 1, - found: Some("bad\nheader\r".to_owned()), - }, - false, - ), - ( - RunCurateMacroError::SeriesMapBadHeader { - line: 1, - found: None, - }, - false, - ), - ( - RunCurateMacroError::SeriesMapWrongColumnCount { - line: 2, - expected: 6, - actual: 3, - }, - false, - ), - ( - RunCurateMacroError::SeriesMapEmptyField { - line: 3, - column: "indicator", - }, - false, - ), - ( - RunCurateMacroError::SeriesMapUnknownLagClass { - line: 5, - value: "bad\nlag\r".to_owned(), - }, - false, - ), - ( - RunCurateMacroError::SeriesMapDuplicateKey { - line: 6, - te_symbol: "SYM\n1".to_owned(), - country: "US\r".to_owned(), - category: "CPI\n".to_owned(), - }, - false, - ), - ( - RunCurateMacroError::CorruptTeDataBson { - path: Some(adversarial_path), - offset: 42, - source: BsonTeDataError::CorruptBson { - offset: 42, - detail: "bad\nbson\rbytes".to_owned(), - }, - }, - true, - ), - ( - RunCurateMacroError::from(CurateMacroError::ConflictingLagClass { - country_iso: "US\n".to_owned(), - indicator: "cpi\r".to_owned(), - first_lag_class: MacroLagClass::PolicyRate, - second_lag_class: MacroLagClass::MonthlyRelease, - }), - true, - ), - ( - RunCurateMacroError::from(ParquetMacroError::InvalidRowGroupRows), - true, - ), - ]; - - for (err, expect_source) in &variants { - let msg = err.to_string(); - assert!(!msg.is_empty()); - assert_single_line(&msg); - assert_eq!(err.source().is_some(), *expect_source, "source for {err:?}"); - } -} - -// --------------------------------------------------------------------------------------------- -// QA additions (T-199): contract literals pinned independently of production constants, extra -// structural-corruption shapes, file-mode path attachment, and builder fail-closed paths. -// --------------------------------------------------------------------------------------------- - -#[test] -fn published_rows_match_literal_contract_timestamps_and_source_tag_for_all_lag_classes() { - // Literal expectations so a change to lag constants or `MACRO_KNOWN_AT_SOURCE` is caught here - // rather than silently moving the fixture with the output. - // 2024-01-24 +1d -> 2024-01-25T00:00:00Z = 1_706_140_800_000_000 us - // 2024-01-31 +35d -> 2024-03-06T00:00:00Z = 1_709_683_200_000_000 us - // 2023-12-31 +65d -> 2024-03-05T00:00:00Z = 1_709_596_800_000_000 us - // 2023-09-30 +90d -> 2023-12-29T00:00:00Z = 1_703_808_000_000_000 us - let bson_bytes = concat_docs(&[ - make_te_data_doc("USGDPQ", "United States", "GDP Growth Rate", &[("2023-09-30", 4.9)], &[]), - make_te_data_doc("CABOC", "Canada", "Interest Rate", &[("2024-01-24", 5.0)], &[]), - make_te_data_doc("USCPIYOY", "United States", "Inflation Rate", &[("2024-01-31", 3.1)], &[]), - make_te_data_doc("CAGDPQ", "Canada", "GDP Growth Rate", &[("2023-12-31", 1.0)], &[]), - ]); - let map = format!( - "{MACRO_SERIES_MAP_HEADER}\n\ - USGDPQ\tUnited States\tGDP Growth Rate\tUS\tgdp_qoq\tgdp90\n\ - CABOC\tCanada\tInterest Rate\tCA\tpolicy_rate\tpolicy_rate\n\ - USCPIYOY\tUnited States\tInflation Rate\tUS\tcpi_yoy\tmonthly_release\n\ - CAGDPQ\tCanada\tGDP Growth Rate\tCA\tgdp_qoq\tgdp65\n" - ); - - let out = TempDirGuard::new("literal-contract"); - let report = run_curate_macro_with_readers(bson_bytes.as_slice(), map.as_bytes(), out.path()) - .expect("run should succeed"); - let rows = read_parquet_rows(&out.path().join("macro").join("part.parquet")); - assert_report_conservation(&report, rows.len()); - - let actual: Vec<(String, String, i32, i64, String, f64)> = rows - .iter() - .map(|r| { - ( - r.country_iso.to_string(), - r.indicator.to_string(), - r.period_date, - r.known_at_micros, - r.known_at_source.to_string(), - r.value, - ) - }) - .collect(); - let src = "publication_lag_estimate".to_owned(); - let expected = vec![ - ("CA".to_owned(), "gdp_qoq".to_owned(), 19_722, 1_709_596_800_000_000_i64, src.clone(), 1.0), - ("CA".to_owned(), "policy_rate".to_owned(), 19_746, 1_706_140_800_000_000, src.clone(), 5.0), - ("US".to_owned(), "cpi_yoy".to_owned(), 19_753, 1_709_683_200_000_000, src.clone(), 3.1), - ("US".to_owned(), "gdp_qoq".to_owned(), 19_630, 1_703_808_000_000_000, src, 4.9), - ]; - assert_eq!(actual, expected); - for (_, _, _, known_at, _, _) in &actual { - assert_eq!(known_at % MICROS_PER_DAY, 0, "known_at must be 00:00:00 UTC"); - } -} - -#[test] -fn file_mode_structural_bson_error_names_te_data_path_and_preserves_existing_output() { - let dir = TempDirGuard::new("file-corrupt-bson"); - let te_data_path = dir.path().join("teData.bson"); - let map_path = dir.path().join("series_map.tsv"); - let out_dir = dir.path().join("out"); - - let mut bson_bytes = make_te_data_doc( - "FDTR", - "United States", - "Interest Rate", - &[("2024-03-20", 5.5)], - &[], - ) - .as_bytes() - .to_vec(); - let corrupt_offset = bson_bytes.len(); - // Declared length below the 5-byte BSON minimum. - bson_bytes.extend_from_slice(&2_i32.to_le_bytes()); - bson_bytes.extend_from_slice(&[0u8; 8]); - fs::write(&te_data_path, &bson_bytes).expect("write bson"); - fs::write( - &map_path, - format!( - "{MACRO_SERIES_MAP_HEADER}\n\ - FDTR\tUnited States\tInterest Rate\tUS\tpolicy_rate\tpolicy_rate\n" - ), - ) - .expect("write map"); - let (part_path, sentinel) = seed_existing_parquet(&out_dir); - - let err = run_curate_macro(&CurateMacroArgs { - te_data: te_data_path.clone(), - series_map: map_path, - out_dir: out_dir.clone(), - }) - .expect_err("corrupt document length must fail closed"); - - assert!( - matches!( - &err, - RunCurateMacroError::CorruptTeDataBson { - path: Some(p), - offset, - source: BsonTeDataError::CorruptDocumentLength { .. } - | BsonTeDataError::TruncatedDocument { .. } - | BsonTeDataError::CorruptBson { .. }, - } if p == &te_data_path && *offset == corrupt_offset - ), - "unexpected error: {err:?}" - ); - let msg = err.to_string(); - assert_single_line(&msg); - assert!(msg.contains("te-data"), "msg: {msg}"); - assert!(msg.contains(&te_data_path.display().to_string()), "msg: {msg}"); - assert_eq!(fs::read(&part_path).expect("read sentinel"), sentinel); -} - -#[test] -fn trailing_partial_length_prefix_after_valid_doc_fails_closed_without_publishing() { - let valid = make_te_data_doc( - "FDTR", - "United States", - "Interest Rate", - &[("2024-03-20", 5.5)], - &[], - ); - let mut bson_bytes = valid.as_bytes().to_vec(); - // Fewer than 4 bytes left: cannot even read a length prefix. - bson_bytes.extend_from_slice(&[0x10, 0x00]); - let map = format!( - "{MACRO_SERIES_MAP_HEADER}\n\ - FDTR\tUnited States\tInterest Rate\tUS\tpolicy_rate\tpolicy_rate\n" - ); - - let out = TempDirGuard::new("partial-length-prefix"); - let err = run_curate_macro_with_readers(bson_bytes.as_slice(), map.as_bytes(), out.path()) - .expect_err("partial trailing length prefix must fail closed"); - assert!( - matches!(err, RunCurateMacroError::CorruptTeDataBson { .. }), - "unexpected error: {err:?}" - ); - assert_single_line(&err.to_string()); - assert!(!out.path().join("macro").exists()); -} - -#[test] -fn file_mode_series_map_error_is_reported_before_te_data_is_read() { - // A bad map must fail closed even when te_data is garbage: map validation runs first. - let dir = TempDirGuard::new("file-bad-map-first"); - let te_data_path = dir.path().join("teData.bson"); - let map_path = dir.path().join("series_map.tsv"); - let out_dir = dir.path().join("out"); - fs::write(&te_data_path, [0xffu8; 3]).expect("write garbage bson"); - fs::write(&map_path, "not a header\n").expect("write bad map"); - - let err = run_curate_macro(&CurateMacroArgs { - te_data: te_data_path, - series_map: map_path, - out_dir: out_dir.clone(), - }) - .expect_err("bad map must fail"); - assert!( - matches!( - err, - RunCurateMacroError::SeriesMapBadHeader { - line: 1, - found: Some(_) - } - ), - "unexpected error: {err:?}" - ); - assert!(!out_dir.exists()); -} - -#[test] -fn tsv_header_with_utf8_bom_or_trailing_tab_is_rejected_at_line_1() { - for header in [ - format!("\u{feff}{MACRO_SERIES_MAP_HEADER}\n"), - format!("{MACRO_SERIES_MAP_HEADER}\t\n"), - format!("{}\n", MACRO_SERIES_MAP_HEADER.to_uppercase()), - ] { - let err = load_macro_series_map_tsv(header.as_bytes()).expect_err("header must fail"); - assert!( - matches!(err, RunCurateMacroError::SeriesMapBadHeader { line: 1, .. }), - "unexpected error for {header:?}: {err:?}" - ); - assert_single_line(&err.to_string()); - } -} - -#[test] -fn duplicate_key_detected_on_later_physical_line_with_crlf_endings() { - let tsv = format!( - "{MACRO_SERIES_MAP_HEADER}\r\n\ - A\tB\tC\tUS\tx\tpolicy_rate\r\n\ - D\tE\tF\tUS\ty\tgdp65\r\n\ - A\tB\tC\tCA\tz\tgdp90\r\n" - ); - let err = load_macro_series_map_tsv(tsv.as_bytes()).expect_err("duplicate must fail"); - assert!( - matches!( - &err, - RunCurateMacroError::SeriesMapDuplicateKey { line: 4, te_symbol, country, category } - if te_symbol == "A" && country == "B" && category == "C" - ), - "unexpected error: {err:?}" - ); - // Same symbol + country but a different category is a distinct key. - let ok = format!( - "{MACRO_SERIES_MAP_HEADER}\n\ - A\tB\tC\tUS\tx\tpolicy_rate\n\ - A\tB\tc\tUS\tx2\tpolicy_rate\n" - ); - assert_eq!(load_macro_series_map_tsv(ok.as_bytes()).expect("distinct keys").len(), 2); -} - -#[test] -fn split_series_duplicates_collapse_and_conflicting_values_fail_closed() { - let map = format!( - "{MACRO_SERIES_MAP_HEADER}\n\ - FDTR\tUnited States\tInterest Rate\tUS\tpolicy_rate\tpolicy_rate\n\ - FDTR2\tUnited States\tFed Funds\tUS\tpolicy_rate\tpolicy_rate\n" - ); - - // Two provider series mapping to the same target with bitwise-identical values collapse. - let same = concat_docs(&[ - make_te_data_doc("FDTR", "United States", "Interest Rate", &[("2024-03-20", 5.5), ("2024-01-31", f64::NAN)], &[]), - make_te_data_doc("FDTR2", "United States", "Fed Funds", &[("2024-03-20", 5.5)], &[]), - ]); - let out = TempDirGuard::new("dup-collapse"); - let report = run_curate_macro_with_readers(same.as_slice(), map.as_bytes(), out.path()) - .expect("identical duplicates should collapse"); - let rows = read_parquet_rows(&out.path().join("macro").join("part.parquet")); - assert_eq!(rows.len(), 1); - assert_eq!(report.curate_stats.builder.skipped_duplicate, 1); - assert_eq!(report.curate_stats.builder.skipped_non_finite_value, 1); - assert_report_conservation(&report, rows.len()); - - // Conflicting values on the same (country_iso, indicator, period_date) fail before publishing. - let conflict = concat_docs(&[ - make_te_data_doc("FDTR", "United States", "Interest Rate", &[("2024-03-20", 5.5)], &[]), - make_te_data_doc("FDTR2", "United States", "Fed Funds", &[("2024-03-20", 5.25)], &[]), - ]); - for seeded in [false, true] { - let out = TempDirGuard::new("dup-conflict"); - let existing = seeded.then(|| seed_existing_parquet(out.path())); - let err = run_curate_macro_with_readers(conflict.as_slice(), map.as_bytes(), out.path()) - .expect_err("conflicting duplicate must fail"); - assert!( - matches!( - err, - RunCurateMacroError::CurateWrite(CurateMacroWriteError::Curate(_)) - ), - "unexpected error: {err:?}" - ); - assert_single_line(&err.to_string()); - if let Some((part_path, sentinel)) = existing { - assert_eq!(fs::read(&part_path).expect("read sentinel"), sentinel); - } else { - assert!(!out.path().join("macro").exists()); - } - } -} - -#[test] -fn successful_run_replaces_preexisting_part_parquet() { - let out = TempDirGuard::new("replace-existing"); - let (part_path, sentinel) = seed_existing_parquet(out.path()); - let doc = make_te_data_doc("FDTR", "United States", "Interest Rate", &[("2024-03-20", 5.5)], &[]); - let map = format!( - "{MACRO_SERIES_MAP_HEADER}\n\ - FDTR\tUnited States\tInterest Rate\tUS\tpolicy_rate\tpolicy_rate\n" - ); - run_curate_macro_with_readers(doc.as_bytes(), map.as_bytes(), out.path()) - .expect("run should succeed"); - assert_ne!(fs::read(&part_path).expect("read part"), sentinel); - let rows = read_parquet_rows(&part_path); - assert_eq!(rows.len(), 1); - assert_eq!(rows[0].indicator, "policy_rate"); -} diff --git a/tools/curate-etl/src/run_curate_posts.rs b/tools/curate-etl/src/run_curate_posts.rs deleted file mode 100644 index 9f7e6c2e..00000000 --- a/tools/curate-etl/src/run_curate_posts.rs +++ /dev/null @@ -1,692 +0,0 @@ -//! File-to-file `curate-posts` runner (`M2.2i`). -//! -//! Streams a concatenated raw BSON `ceoPosts` dump file alongside `provider_mapping.tsv` into an -//! atomically published `/events/year=YYYY/part.parquet` dataset via -//! [`curate_and_write_posts`]. -//! -//! # Dedicated Output Directory & Clobber Guard -//! `write_events_dataset` replaces whole `/events/year=YYYY/part.parquet` files, and -//! [`crate::run_curate_events`] (filings + earnings) publishes to the same `/events` -//! directory. To prevent silently clobbering another stage's partitions, this runner **requires a -//! dedicated output directory** and fails closed with [`RunCuratePostsError::EventsDatasetExists`] -//! before any write whenever `/events` already contains any `year=*` entry. Combining -//! filings, earnings, and posts into one `events` dataset is a separate follow-up. -//! -//! # Contract & Point-in-Time Rules -//! - Field names are supplied via [`CuratePostsArgs`] (validated via -//! [`CeoPostsFieldNames::validate`] before reading inputs). -//! - Numeric timestamp unit ([`CeoPostsTimestampUnit`]) has **no default** and must be chosen -//! explicitly by the caller because the live MongoDB `ceoPosts` numeric unit (`Seconds` vs. -//! `Millis`) is unverified in the repository. BSON `DateTime` values are always epoch -//! milliseconds regardless of unit. -//! - `provider_mapping.tsv` uses the strict headerless 5-column TSV format from -//! [`crate::run_curate_bars::load_provider_mapping_tsv`]. -//! - All decoded [`CeoPost`] rows are passed directly to [`curate_and_write_posts`] (which splits -//! `bot == "1"` newswire vs. retail, enforces the `edited` text `known_at` guard, resolves -//! `provider_mapping` on the Eastern local posting date of `posted_at`, and drops unmapped or -//! unsupported-date rows into stats). -//! - **In-memory accumulation:** [`RawBsonChunkReader`] bounds only the raw BSON chunk buffer -//! (`peak_chunk_bytes`); decoded posts and their text accumulate in memory before -//! [`curate_and_write_posts`] runs, as [`crate::curate_posts::curate_posts`] requires. -//! - **Empty / all-unmapped behavior:** returns `Ok` with `rows_written == 0` and -//! `files_written == 0` without creating `/events`. -//! - **Fail-closed safety:** invalid `out_dir`, pre-existing `/events/year=*` entries, -//! invalid field names, blank `mapping_source`, unreadable inputs, malformed/overlapping -//! `provider_mapping.tsv`, truncated/corrupt BSON framing or element bytes, and curation -//! timestamp overflow errors return a typed [`RunCuratePostsError`] before touching `out_dir`. -//! -//! # Counter Conservation Invariants -//! Every successful [`CuratePostsRunReport`] satisfies: -//! - `docs_framed as usize == decode.docs_in == decode.rows_out + decode.skipped_total()` -//! - `decode.rows_out == curate_stats.builder.input` -//! - `curate_stats.builder.input == curate_stats.builder.newswire + curate_stats.builder.retail + curate_stats.builder.duplicates_dropped + curate_stats.builder.rejected_invalid` -//! - `curate_stats.rows_in == curate_stats.builder.newswire + curate_stats.builder.retail == curate_stats.rows_out + curate_stats.dropped_unmapped + curate_stats.dropped_unsupported_date + curate_stats.listing_duplicate_collapsed` -//! - `write_stats.rows_written == curate_stats.rows_out` - -use std::collections::HashSet; -use std::error::Error; -use std::fmt::{self, Write as _}; -use std::fs::{self, File}; -use std::io; -use std::path::{Component, Path, PathBuf}; -use std::sync::Arc; -use std::time::Instant; - -use crate::bson_ceo_posts::{ - BsonCeoPostsDecodeStats, BsonCeoPostsError, CeoPostsFieldNames, CeoPostsTimestampUnit, -}; -use crate::bson_stream::{ - decode_ceo_posts_chunks, BsonCeoPostsStreamError, BsonStreamError, BsonStreamOptions, - RawBsonChunkReader, -}; -use crate::curate_posts::{curate_and_write_posts, CuratePostsStats, CuratePostsWriteError}; -use crate::parquet_events::{EventsWriteOptions, EventsWriteStats}; -use crate::posts::CeoPost; -use crate::provider_mapping::{ProviderMappingError, ProviderMappingTable}; -use crate::run_curate_bars::{load_provider_mapping_tsv, RunCurateBarsError}; - -/// Default `mapping_source` passed to `provider_mapping` lookups for `ceoPosts`. -pub const DEFAULT_MAPPING_SOURCE: &str = "ceo"; - -/// Arguments for [`run_curate_posts`]. -/// -/// `timestamp_unit` intentionally has no default: callers must explicitly choose -/// [`CeoPostsTimestampUnit::Seconds`] or [`CeoPostsTimestampUnit::Millis`]. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct CuratePostsArgs { - pub ceo_posts: PathBuf, - pub provider_mapping: PathBuf, - pub out_dir: PathBuf, - pub timestamp_unit: CeoPostsTimestampUnit, - pub key_field: String, - pub spiel_id_field: String, - pub timestamp_field: String, - pub edited_field: String, - pub bot_field: String, - pub user_id_field: String, - pub text_field: String, - pub mapping_source: String, -} - -impl CuratePostsArgs { - /// Borrows the configured BSON field names as [`CeoPostsFieldNames`]. - #[inline] - pub fn field_names(&self) -> CeoPostsFieldNames<'_> { - CeoPostsFieldNames { - key: self.key_field.as_str(), - spiel_id: self.spiel_id_field.as_str(), - timestamp: self.timestamp_field.as_str(), - edited: self.edited_field.as_str(), - bot: self.bot_field.as_str(), - user_id: self.user_id_field.as_str(), - text: self.text_field.as_str(), - } - } -} - -/// Full run report produced by [`run_curate_posts`] and [`run_curate_posts_with_reader`]. -#[derive(Debug, Clone, PartialEq)] -pub struct CuratePostsRunReport { - pub docs_framed: u64, - pub bytes_read: u64, - pub peak_chunk_bytes: usize, - pub decode: BsonCeoPostsDecodeStats, - pub curate_stats: CuratePostsStats, - pub write_stats: EventsWriteStats, - pub elapsed_secs: f64, -} - -/// Typed errors returned by [`run_curate_posts`] and [`run_curate_posts_with_reader`]. -/// -/// Every variant's `Display` output is a single line naming the offending path (and line number or -/// byte offset where applicable). -#[derive(Debug)] -pub enum RunCuratePostsError { - InvalidOutDir { - path: PathBuf, - detail: String, - }, - InspectOutDir { - path: PathBuf, - source: io::Error, - }, - EventsDatasetExists { - path: PathBuf, - }, - InvalidFieldNames { - source: BsonCeoPostsError, - }, - EmptyMappingSource, - OpenInput { - label: &'static str, - path: PathBuf, - source: io::Error, - }, - ReadInput { - label: &'static str, - path: PathBuf, - source: io::Error, - }, - TsvParse { - path: PathBuf, - line: usize, - detail: String, - }, - ProviderMapping { - path: PathBuf, - source: ProviderMappingError, - }, - BsonStream { - path: PathBuf, - source: BsonStreamError, - }, - CorruptBson { - path: PathBuf, - offset: u64, - source: BsonCeoPostsError, - }, - CurateWrite { - out_dir: PathBuf, - source: CuratePostsWriteError, - }, -} - -struct SingleLineWriter<'a, 'b> { - f: &'a mut fmt::Formatter<'b>, -} - -impl fmt::Write for SingleLineWriter<'_, '_> { - fn write_str(&mut self, s: &str) -> fmt::Result { - let mut rest = s; - while let Some(idx) = rest.find(['\n', '\r']) { - let (head, tail) = rest.split_at(idx); - if !head.is_empty() { - self.f.write_str(head)?; - } - let mut chars = tail.chars(); - match chars.next() { - Some('\n') => self.f.write_str("\\n")?, - Some('\r') => self.f.write_str("\\r")?, - _ => unreachable!(), - } - rest = chars.as_str(); - } - if !rest.is_empty() { - self.f.write_str(rest)?; - } - Ok(()) - } -} - -impl fmt::Display for RunCuratePostsError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let mut w = SingleLineWriter { f }; - match self { - Self::InvalidOutDir { path, detail } => { - write!(w, "invalid --out '{}': {detail}", path.display()) - } - Self::InspectOutDir { path, source } => { - write!( - w, - "failed to inspect output path '{}': {source}", - path.display() - ) - } - Self::EventsDatasetExists { path } => write!( - w, - "refusing to overwrite existing events partition '{}': use a dedicated --out directory for ceoPosts", - path.display() - ), - Self::InvalidFieldNames { source } => write!(w, "{source}"), - Self::EmptyMappingSource => { - write!(w, "invalid --mapping-source: must not be empty or blank") - } - Self::OpenInput { - label, - path, - source, - } => write!(w, "failed to open {label} '{}': {source}", path.display()), - Self::ReadInput { - label, - path, - source, - } => write!(w, "failed to read {label} '{}': {source}", path.display()), - Self::TsvParse { path, line, detail } => { - write!(w, "{}:{line}: {detail}", path.display()) - } - Self::ProviderMapping { path, source } => { - write!(w, "invalid provider_mapping '{}': {source}", path.display()) - } - Self::BsonStream { path, source } => { - write!(w, "failed reading ceo-posts '{}': {source}", path.display()) - } - Self::CorruptBson { - path, - offset, - source, - } => write!( - w, - "corrupt ceo-posts BSON '{}' at byte offset {offset}: {source}", - path.display() - ), - Self::CurateWrite { out_dir, source } => { - write!(w, "curate/write to '{}' failed: {source}", out_dir.display()) - } - } - } -} - -impl Error for RunCuratePostsError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::InspectOutDir { source, .. } => Some(source), - Self::InvalidFieldNames { source } => Some(source), - Self::OpenInput { source, .. } | Self::ReadInput { source, .. } => Some(source), - Self::ProviderMapping { source, .. } => Some(source), - Self::BsonStream { source, .. } => Some(source), - Self::CorruptBson { source, .. } => Some(source), - Self::CurateWrite { source, .. } => Some(source), - Self::InvalidOutDir { .. } - | Self::EventsDatasetExists { .. } - | Self::EmptyMappingSource - | Self::TsvParse { .. } => None, - } - } -} - -fn validate_out_dir_and_events_guard(out_dir: &Path) -> Result<(), RunCuratePostsError> { - if out_dir.as_os_str().is_empty() { - return Err(RunCuratePostsError::InvalidOutDir { - path: out_dir.to_path_buf(), - detail: "output directory path must not be empty".to_string(), - }); - } - - // Reject `..` after a missing path component: `fs::metadata` reports `NotFound` for the - // unresolved path, but `create_dir_all` would create the missing component and then traverse - // `..` into an existing directory, bypassing the events clobber guard. - let mut prefix = PathBuf::new(); - let mut saw_missing = false; - for component in out_dir.components() { - match component { - Component::ParentDir => { - if saw_missing { - return Err(RunCuratePostsError::InvalidOutDir { - path: out_dir.to_path_buf(), - detail: "output path must not contain '..' after a missing component" - .to_string(), - }); - } - prefix.push(component); - } - Component::CurDir => { - if !saw_missing { - prefix.push(component); - } - } - Component::RootDir | Component::Prefix(_) => { - prefix.push(component); - } - Component::Normal(_) => { - prefix.push(component); - if !saw_missing { - match fs::metadata(&prefix) { - Ok(_) => {} - Err(err) if err.kind() == io::ErrorKind::NotFound => { - saw_missing = true; - } - Err(source) => { - return Err(RunCuratePostsError::InspectOutDir { - path: prefix, - source, - }); - } - } - } - } - } - } - - match fs::metadata(out_dir) { - Ok(meta) if !meta.is_dir() => { - return Err(RunCuratePostsError::InvalidOutDir { - path: out_dir.to_path_buf(), - detail: "path exists and is not a directory".to_string(), - }); - } - Ok(_) => {} - Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(()), - Err(source) => { - return Err(RunCuratePostsError::InspectOutDir { - path: out_dir.to_path_buf(), - source, - }); - } - } - - let events_dir = out_dir.join("events"); - match fs::metadata(&events_dir) { - Ok(meta) if !meta.is_dir() => { - return Err(RunCuratePostsError::InvalidOutDir { - path: events_dir, - detail: "events output path exists and is not a directory".to_string(), - }); - } - Ok(_) => {} - Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(()), - Err(source) => { - return Err(RunCuratePostsError::InspectOutDir { - path: events_dir, - source, - }); - } - } - - let entries = fs::read_dir(&events_dir).map_err(|source| RunCuratePostsError::InspectOutDir { - path: events_dir.clone(), - source, - })?; - - let mut existing_year_entry: Option = None; - for entry_res in entries { - let entry = entry_res.map_err(|source| RunCuratePostsError::InspectOutDir { - path: events_dir.clone(), - source, - })?; - let name = entry.file_name(); - if name.to_string_lossy().starts_with("year=") { - let candidate = entry.path(); - if existing_year_entry - .as_ref() - .is_none_or(|current| candidate < *current) - { - existing_year_entry = Some(candidate); - } - } - } - - if let Some(path) = existing_year_entry { - return Err(RunCuratePostsError::EventsDatasetExists { path }); - } - - Ok(()) -} - -fn map_tsv_error(path: &Path, err: RunCurateBarsError) -> RunCuratePostsError { - match err { - RunCurateBarsError::OpenInput { - label, - path, - source, - } => RunCuratePostsError::OpenInput { - label, - path, - source, - }, - RunCurateBarsError::ReadInput { - label, - path, - source, - } => RunCuratePostsError::ReadInput { - label, - path, - source, - }, - RunCurateBarsError::TsvParse { path, line, detail } => { - RunCuratePostsError::TsvParse { path, line, detail } - } - RunCurateBarsError::ProviderMapping { path, source } => { - RunCuratePostsError::ProviderMapping { path, source } - } - other => RunCuratePostsError::TsvParse { - path: path.to_path_buf(), - line: 0, - detail: other.to_string(), - }, - } -} - -fn bson_error_offset(err: &BsonCeoPostsError) -> u64 { - match err { - BsonCeoPostsError::TruncatedDocument { offset, .. } - | BsonCeoPostsError::CorruptDocumentLength { offset, .. } - | BsonCeoPostsError::CorruptBson { offset, .. } => *offset, - BsonCeoPostsError::InvalidFieldNames { .. } => 0, - } -} - -struct DecodedPostsInputs { - mapping: ProviderMappingTable, - posts: Vec>>, - docs_framed: u64, - bytes_read: u64, - peak_chunk_bytes: usize, - decode: BsonCeoPostsDecodeStats, -} - -fn decode_inputs_from_opener( - provider_mapping_path: &Path, - mapping_source: &str, - fields: &CeoPostsFieldNames<'_>, - timestamp_unit: CeoPostsTimestampUnit, - ceo_posts_path: &Path, - open_posts: F, -) -> Result -where - R: io::Read, - F: FnOnce() -> Result, -{ - fields - .validate() - .map_err(|source| RunCuratePostsError::InvalidFieldNames { source })?; - - if mapping_source.trim().is_empty() { - return Err(RunCuratePostsError::EmptyMappingSource); - } - - let mapping_rows = load_provider_mapping_tsv(provider_mapping_path) - .map_err(|err| map_tsv_error(provider_mapping_path, err))?; - let mapping = ProviderMappingTable::from_rows(mapping_rows).map_err(|source| { - RunCuratePostsError::ProviderMapping { - path: provider_mapping_path.to_path_buf(), - source, - } - })?; - - let stream = open_posts()?; - let mut reader = RawBsonChunkReader::with_options(stream, BsonStreamOptions::default()) - .map_err(|source| RunCuratePostsError::BsonStream { - path: ceo_posts_path.to_path_buf(), - source, - })?; - - let mut key_interner: HashSet> = HashSet::new(); - let mut posts: Vec>> = Vec::new(); - - let decode = decode_ceo_posts_chunks(&mut reader, fields, timestamp_unit, |raw| { - let key = if let Some(existing) = key_interner.get(raw.key) { - Arc::clone(existing) - } else { - let arc: Arc = Arc::from(raw.key); - key_interner.insert(Arc::clone(&arc)); - arc - }; - posts.push(CeoPost { - key, - spiel_id: raw.spiel_id, - timestamp_ms: raw.timestamp_ms, - edited_ms: raw.edited_ms, - bot: raw.bot, - user_id: raw.user_id, - text: raw.text, - }); - }) - .map_err(|err| match err { - BsonCeoPostsStreamError::Stream(source) => RunCuratePostsError::BsonStream { - path: ceo_posts_path.to_path_buf(), - source, - }, - BsonCeoPostsStreamError::Decode(source) => match &source { - BsonCeoPostsError::InvalidFieldNames { .. } => { - RunCuratePostsError::InvalidFieldNames { source } - } - _ => { - let offset = bson_error_offset(&source); - RunCuratePostsError::CorruptBson { - path: ceo_posts_path.to_path_buf(), - offset, - source, - } - } - }, - })?; - - Ok(DecodedPostsInputs { - mapping, - posts, - docs_framed: reader.docs_framed(), - bytes_read: reader.bytes_read(), - peak_chunk_bytes: reader.buffer_capacity(), - decode, - }) -} - -fn run_curate_posts_from_opener( - provider_mapping_path: &Path, - mapping_source: &str, - fields: &CeoPostsFieldNames<'_>, - timestamp_unit: CeoPostsTimestampUnit, - ceo_posts_path: &Path, - open_posts: F, - out_dir: &Path, -) -> Result -where - R: io::Read, - F: FnOnce() -> Result, -{ - let start = Instant::now(); - validate_out_dir_and_events_guard(out_dir)?; - - let decoded = decode_inputs_from_opener( - provider_mapping_path, - mapping_source, - fields, - timestamp_unit, - ceo_posts_path, - open_posts, - )?; - - // Re-check output directory and clobber guard immediately before curating/writing. - validate_out_dir_and_events_guard(out_dir)?; - - let write_report = curate_and_write_posts( - out_dir, - decoded.posts, - mapping_source, - &decoded.mapping, - EventsWriteOptions::default(), - ) - .map_err(|source| RunCuratePostsError::CurateWrite { - out_dir: out_dir.to_path_buf(), - source, - })?; - - Ok(CuratePostsRunReport { - docs_framed: decoded.docs_framed, - bytes_read: decoded.bytes_read, - peak_chunk_bytes: decoded.peak_chunk_bytes, - decode: decoded.decode, - curate_stats: write_report.curate_stats, - write_stats: write_report.write_stats, - elapsed_secs: start.elapsed().as_secs_f64(), - }) -} - -/// Runs the end-to-end `curate-posts` file-to-Parquet pipeline via [`curate_and_write_posts`]. -/// -/// Any validation, clobber-guard, I/O, TSV, mapping, BSON framing/corruption, or curation error -/// returns before touching `args.out_dir`. -pub fn run_curate_posts( - args: &CuratePostsArgs, -) -> Result { - run_curate_posts_from_opener( - &args.provider_mapping, - &args.mapping_source, - &args.field_names(), - args.timestamp_unit, - &args.ceo_posts, - || { - File::open(&args.ceo_posts).map_err(|source| RunCuratePostsError::OpenInput { - label: "ceo-posts", - path: args.ceo_posts.clone(), - source, - }) - }, - &args.out_dir, - ) -} - -/// Runs `curate-posts` from an arbitrary raw-BSON [`io::Read`] stream. -pub fn run_curate_posts_with_reader( - provider_mapping_path: &Path, - mapping_source: &str, - fields: &CeoPostsFieldNames<'_>, - timestamp_unit: CeoPostsTimestampUnit, - ceo_posts_input: (&Path, R), - out_dir: &Path, -) -> Result { - let (ceo_path, stream) = ceo_posts_input; - run_curate_posts_from_opener( - provider_mapping_path, - mapping_source, - fields, - timestamp_unit, - ceo_path, - || Ok(stream), - out_dir, - ) -} - -/// Formats [`CuratePostsRunReport`] into a deterministic machine-readable `key=value` summary. -/// -/// Only the final `timing:` line contains wall-clock time (`elapsed_secs`). -pub fn format_curate_posts_report(report: &CuratePostsRunReport) -> String { - let d = &report.decode; - let b = &report.curate_stats.builder; - let c = &report.curate_stats; - let w = &report.write_stats; - format!( - "curate-etl curate-posts\n\ - \x20 ceo_bson: docs_framed={} bytes_read={} peak_chunk_bytes={} docs_in={} rows_out={} skipped={} (missing_key={} wrong_key_type={} empty_key={} missing_spiel_id={} wrong_spiel_id_type={} empty_spiel_id={} missing_ts={} wrong_ts_type={} invalid_ts={} ts_oor={} invalid_edited={} wrong_text_type={}) emitted=(edited_zero_or_false={} nulled_bot={} nulled_user_id={} empty_text={})\n\ - \x20 builder: input={} newswire={} retail={} edited={} edited_before_posted={} dup_dropped={} rejected_invalid={}\n\ - \x20 curate: rows_in={} rows_out={} newswire_out={} retail_out={} listings_out={} dropped_unmapped={} dropped_unsupported_date={} listing_dup_collapsed={}\n\ - \x20 write: files={} row_groups={} rows_written={} bytes_written={}\n\ - \x20 timing: elapsed_secs={:.6}", - report.docs_framed, - report.bytes_read, - report.peak_chunk_bytes, - d.docs_in, - d.rows_out, - d.skipped_total(), - d.skipped_missing_key, - d.skipped_wrong_key_type, - d.skipped_empty_key, - d.skipped_missing_spiel_id, - d.skipped_wrong_spiel_id_type, - d.skipped_empty_spiel_id, - d.skipped_missing_timestamp, - d.skipped_wrong_timestamp_type, - d.skipped_invalid_timestamp, - d.skipped_timestamp_out_of_range, - d.skipped_invalid_edited, - d.skipped_wrong_text_type, - d.edited_zero_or_false, - d.nulled_wrong_type_bot, - d.nulled_wrong_type_user_id, - d.empty_text, - b.input, - b.newswire, - b.retail, - b.edited, - b.edited_before_posted, - b.duplicates_dropped, - b.rejected_invalid, - c.rows_in, - c.rows_out, - c.newswire_out, - c.retail_out, - c.listings_out, - c.dropped_unmapped, - c.dropped_unsupported_date, - c.listing_duplicate_collapsed, - w.files_written, - w.row_groups_written, - w.rows_written, - w.bytes_written, - report.elapsed_secs, - ) -} - -#[cfg(test)] -#[path = "run_curate_posts_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/run_curate_posts_tests.rs b/tools/curate-etl/src/run_curate_posts_tests.rs deleted file mode 100644 index 7456672b..00000000 --- a/tools/curate-etl/src/run_curate_posts_tests.rs +++ /dev/null @@ -1,1450 +0,0 @@ -use std::borrow::Cow; -use std::fs::{self, File}; -use std::io::{self, Cursor, Read, Write}; -use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering}; - -use bson::raw::{cstr, RawDocumentBuf}; -use parquet::basic::Compression; -use parquet::column::reader::ColumnReader; -use parquet::file::reader::{FileReader, SerializedFileReader}; - -use super::*; -use crate::bson_ceo_posts::{ - DEFAULT_BOT_FIELD, DEFAULT_EDITED_FIELD, DEFAULT_KEY_FIELD, DEFAULT_SPIEL_ID_FIELD, - DEFAULT_TEXT_FIELD, DEFAULT_TIMESTAMP_FIELD, DEFAULT_USER_ID_FIELD, -}; -use crate::curate_posts::{curate_posts, CuratePostsError, CuratePostsWriteError}; -use crate::parquet_events::EventsParquetRow; -use crate::parquet_posts::{ - EVENT_KIND_POST, KNOWN_AT_SOURCE_POST_EDITED, KNOWN_AT_SOURCE_POST_TIMESTAMP, - POST_SUBTYPE_NEWSWIRE, POST_SUBTYPE_RETAIL, -}; -use crate::posts::PostsError; -use crate::provider_mapping::ProviderMappingRow; -use crate::split::ymd_to_epoch_days; - -static TEMP_SEQ: AtomicU64 = AtomicU64::new(0); - -struct TempDirGuard { - path: PathBuf, -} - -impl TempDirGuard { - fn new(label: &str) -> Self { - let seq = TEMP_SEQ.fetch_add(1, Ordering::Relaxed); - let pid = std::process::id(); - let path = - std::env::temp_dir().join(format!("curate-etl-run-posts-test-{label}-{pid}-{seq}")); - let _ = fs::remove_dir_all(&path); - fs::create_dir_all(&path).expect("create temp dir"); - Self { path } - } - - fn path(&self) -> &Path { - &self.path - } -} - -impl Drop for TempDirGuard { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.path); - } -} - -fn day(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).expect("valid date") -} - -fn utc_ms(year: i32, month: u32, day_num: u32, hour: u8, minute: u8, second: u8) -> i64 { - let epoch_day = day(year, month, day_num); - let secs = i64::from(epoch_day) * 86_400 - + i64::from(hour) * 3_600 - + i64::from(minute) * 60 - + i64::from(second); - secs * 1_000 -} - -fn write_bytes(path: &Path, bytes: &[u8]) { - let mut f = File::create(path).expect("create file"); - f.write_all(bytes).expect("write file"); -} - -fn default_args( - ceo_posts: PathBuf, - provider_mapping: PathBuf, - out_dir: PathBuf, - timestamp_unit: CeoPostsTimestampUnit, -) -> CuratePostsArgs { - CuratePostsArgs { - ceo_posts, - provider_mapping, - out_dir, - timestamp_unit, - key_field: DEFAULT_KEY_FIELD.to_string(), - spiel_id_field: DEFAULT_SPIEL_ID_FIELD.to_string(), - timestamp_field: DEFAULT_TIMESTAMP_FIELD.to_string(), - edited_field: DEFAULT_EDITED_FIELD.to_string(), - bot_field: DEFAULT_BOT_FIELD.to_string(), - user_id_field: DEFAULT_USER_ID_FIELD.to_string(), - text_field: DEFAULT_TEXT_FIELD.to_string(), - mapping_source: DEFAULT_MAPPING_SOURCE.to_string(), - } -} - -#[allow(clippy::too_many_arguments)] -fn make_post_doc( - fields: &CeoPostsFieldNames<'_>, - key: &str, - spiel_id: &str, - timestamp: i64, - edited: Option, - bot: Option<&str>, - user_id: Option<&str>, - text: &str, -) -> Vec { - let cstring = |s: &str| bson::raw::CString::try_from(s.to_owned()).expect("valid BSON key"); - let mut doc = RawDocumentBuf::new(); - doc.append(cstring(fields.key), key); - doc.append(cstring(fields.spiel_id), spiel_id); - doc.append(cstring(fields.timestamp), timestamp); - if let Some(ed) = edited { - doc.append(cstring(fields.edited), ed); - } - if let Some(b) = bot { - doc.append(cstring(fields.bot), b); - } - if let Some(u) = user_id { - doc.append(cstring(fields.user_id), u); - } - doc.append(cstring(fields.text), text); - doc.into_bytes() -} - -fn assert_report_invariants(report: &CuratePostsRunReport) { - assert_eq!(report.docs_framed as usize, report.decode.docs_in); - assert_eq!( - report.decode.docs_in, - report.decode.rows_out + report.decode.skipped_total() - ); - let b = &report.curate_stats.builder; - assert_eq!(report.decode.rows_out, b.input); - assert_eq!( - b.input, - b.newswire + b.retail + b.duplicates_dropped + b.rejected_invalid - ); - let c = &report.curate_stats; - assert_eq!(c.rows_in, b.newswire + b.retail); - assert_eq!( - c.rows_in, - c.rows_out - + c.dropped_unmapped - + c.dropped_unsupported_date - + c.listing_duplicate_collapsed - ); - assert_eq!(c.rows_out, c.newswire_out + c.retail_out); - assert_eq!(report.write_stats.rows_written, c.rows_out); -} - -fn read_events_parquet_and_verify_zstd(path: &Path) -> Vec { - let file = File::open(path).expect("open parquet file"); - let reader = SerializedFileReader::new(file).expect("open parquet reader"); - let meta = reader.metadata(); - let mut out = Vec::new(); - - for rg_idx in 0..meta.num_row_groups() { - let rg_meta = meta.row_group(rg_idx); - assert_eq!( - rg_meta.num_columns(), - 7, - "expected 7 columns in events schema" - ); - for col_idx in 0..rg_meta.num_columns() { - let compression = rg_meta.column(col_idx).compression(); - assert!( - matches!(compression, Compression::ZSTD(_)), - "expected ZSTD compression for row_group={rg_idx} col={col_idx}, got {compression:?}" - ); - } - - let rg_rows = rg_meta.num_rows() as usize; - let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); - - let read_i32_col = |col_idx: usize| -> Vec { - let mut vals = Vec::with_capacity(rg_rows); - match rg_reader.get_column_reader(col_idx).expect("col reader") { - ColumnReader::Int32ColumnReader(mut typed) => { - let mut read = 0usize; - while read < rg_rows { - let (n, _, _) = typed - .read_records(rg_rows - read, None, None, &mut vals) - .expect("read i32 records"); - assert!(n > 0); - read += n; - } - } - _ => panic!("expected INT32 column at index {col_idx}"), - } - vals - }; - - let read_i64_col = |col_idx: usize| -> Vec { - let mut vals = Vec::with_capacity(rg_rows); - match rg_reader.get_column_reader(col_idx).expect("col reader") { - ColumnReader::Int64ColumnReader(mut typed) => { - let mut read = 0usize; - while read < rg_rows { - let (n, _, _) = typed - .read_records(rg_rows - read, None, None, &mut vals) - .expect("read i64 records"); - assert!(n > 0); - read += n; - } - } - _ => panic!("expected INT64 column at index {col_idx}"), - } - vals - }; - - let read_str_col = |col_idx: usize| -> Vec { - let mut raw = Vec::with_capacity(rg_rows); - match rg_reader.get_column_reader(col_idx).expect("col reader") { - ColumnReader::ByteArrayColumnReader(mut typed) => { - let mut read = 0usize; - while read < rg_rows { - let (n, _, _) = typed - .read_records(rg_rows - read, None, None, &mut raw) - .expect("read byte_array records"); - assert!(n > 0); - read += n; - } - } - _ => panic!("expected BYTE_ARRAY column at index {col_idx}"), - } - raw.iter() - .map(|b| { - std::str::from_utf8(b.data()) - .expect("valid utf8") - .to_string() - }) - .collect() - }; - - let listing_ids = read_i32_col(0); - let ts = read_i64_col(1); - let known_at = read_i64_col(2); - let known_at_source = read_str_col(3); - let kind = read_str_col(4); - let subtype = read_str_col(5); - let payload_json = read_str_col(6); - - for i in 0..rg_rows { - out.push(EventsParquetRow { - listing_id: listing_ids[i], - ts_micros: ts[i], - known_at_micros: known_at[i], - known_at_source: Cow::Owned(known_at_source[i].clone()), - kind: Cow::Owned(kind[i].clone()), - subtype: subtype[i].clone(), - payload_json: payload_json[i].clone(), - }); - } - } - - out -} - -fn read_all_event_partitions(out_dir: &Path) -> Vec { - let events_dir = out_dir.join("events"); - let mut year_dirs: Vec = fs::read_dir(&events_dir) - .expect("read events dir") - .map(|e| e.expect("dir entry").path()) - .filter(|p| { - p.file_name() - .and_then(|n| n.to_str()) - .is_some_and(|n| n.starts_with("year=")) - }) - .collect(); - year_dirs.sort(); - - let mut all = Vec::new(); - for yd in year_dirs { - all.extend(read_events_parquet_and_verify_zstd( - &yd.join("part.parquet"), - )); - } - all.sort_by(|a, b| { - a.listing_id - .cmp(&b.listing_id) - .then_with(|| a.ts_micros.cmp(&b.ts_micros)) - .then_with(|| a.kind.as_ref().cmp(b.kind.as_ref())) - .then_with(|| a.subtype.cmp(&b.subtype)) - .then_with(|| a.payload_json.cmp(&b.payload_json)) - .then_with(|| a.known_at_micros.cmp(&b.known_at_micros)) - .then_with(|| a.known_at_source.as_ref().cmp(b.known_at_source.as_ref())) - }); - all -} - -fn assert_single_line_err(err: &RunCuratePostsError) -> String { - let msg = err.to_string(); - assert!(!msg.is_empty(), "error message must not be empty"); - assert!( - !msg.contains('\n') && !msg.contains('\r'), - "error message must be single-line, got: {msg:?}" - ); - msg -} - -struct FailingReader { - prefix: Vec, - pos: usize, - error_message: String, -} - -impl Read for FailingReader { - fn read(&mut self, buf: &mut [u8]) -> io::Result { - if self.pos < self.prefix.len() { - let n = (self.prefix.len() - self.pos).min(buf.len()); - buf[..n].copy_from_slice(&self.prefix[self.pos..self.pos + n]); - self.pos += n; - return Ok(n); - } - Err(io::Error::new( - io::ErrorKind::BrokenPipe, - self.error_message.clone(), - )) - } -} - -#[test] -fn happy_path_matches_curate_posts_verifies_zstd_edit_time_and_invariants() { - let dir = TempDirGuard::new("happy"); - let bson_path = dir.path().join("ceoPosts.bson"); - let map_path = dir.path().join("provider_mapping.tsv"); - let out_a = dir.path().join("out_a"); - let out_b = dir.path().join("out_b"); - - let mapping_tsv = concat!( - "ceo\tCEO_RY\t2020-01-01\t\t101\n", - "ceo\tCEO_SHOP\t2024-01-01\t\t202\n", - ); - write_bytes(&map_path, mapping_tsv.as_bytes()); - - let fields = CeoPostsFieldNames::default(); - let t_wire = utc_ms(2024, 6, 15, 14, 0, 0); - let t_retail = utc_ms(2024, 6, 15, 14, 5, 0); - let t_edited_post = utc_ms(2024, 6, 15, 15, 0, 0); - let t_edited_at = utc_ms(2024, 6, 15, 18, 30, 0); - let t_2025 = utc_ms(2025, 1, 10, 16, 0, 0); - - // Semantic skip doc: invalid edited (boolean true) - let mut skipped_doc = RawDocumentBuf::new(); - skipped_doc.append(cstr!("ceoId"), "CEO_RY"); - skipped_doc.append(cstr!("spielId"), "sp-skip"); - skipped_doc.append(cstr!("timestamp"), t_wire); - skipped_doc.append(cstr!("edited"), true); - skipped_doc.append(cstr!("spiel"), "should skip"); - - let docs = vec![ - // 1. Newswire (bot == "1") - make_post_doc( - &fields, - "CEO_RY", - "sp-wire-1", - t_wire, - None, - Some("1"), - Some("thenewswire"), - "Royal Bank quarterly release", - ), - // 2. Retail (bot == "0") - make_post_doc( - &fields, - "CEO_RY", - "sp-retail-1", - t_retail, - None, - Some("0"), - Some("trader42"), - "Looking strong today", - ), - // 3. Edited retail post: posted at t_edited_post, edited at t_edited_at - make_post_doc( - &fields, - "CEO_SHOP", - "sp-edited-1", - t_edited_post, - Some(t_edited_at), - None, - Some("analyst99"), - "Updated guidance notes", - ), - // 4. Duplicate spielId (earlier version of sp-edited-1 -> dropped by dedup) - make_post_doc( - &fields, - "CEO_SHOP", - "sp-edited-1", - t_edited_post, - None, - None, - Some("analyst99"), - "Initial draft", - ), - // 5. Unmapped key -> dropped_unmapped - make_post_doc( - &fields, - "UNKNOWN_CH", - "sp-unmapped-1", - t_retail, - None, - None, - Some("anon"), - "Unmapped channel post", - ), - // 6. Second partition year (2025) - make_post_doc( - &fields, - "CEO_SHOP", - "sp-2025-1", - t_2025, - None, - Some("1"), - Some("globenewswire"), - "2025 update", - ), - // 7. Semantic skip - skipped_doc.into_bytes(), - ]; - - let mut forward_bytes = Vec::new(); - for d in &docs { - forward_bytes.extend_from_slice(d); - } - write_bytes(&bson_path, &forward_bytes); - - let args_a = default_args( - bson_path.clone(), - map_path.clone(), - out_a.clone(), - CeoPostsTimestampUnit::Millis, - ); - let report_a = run_curate_posts(&args_a).expect("run forward"); - assert_report_invariants(&report_a); - assert_eq!(report_a.docs_framed, 7); - assert_eq!(report_a.decode.docs_in, 7); - assert_eq!(report_a.decode.rows_out, 6); - assert_eq!(report_a.decode.skipped_invalid_edited, 1); - assert_eq!(report_a.curate_stats.builder.input, 6); - assert_eq!(report_a.curate_stats.builder.duplicates_dropped, 1); - assert_eq!(report_a.curate_stats.dropped_unmapped, 1); - assert_eq!(report_a.curate_stats.rows_out, 4); - assert_eq!(report_a.curate_stats.newswire_out, 2); - assert_eq!(report_a.curate_stats.retail_out, 2); - assert_eq!(report_a.write_stats.files_written, 2); - assert_eq!(report_a.write_stats.rows_written, 4); - - // Baseline comparison against pure curate_posts on equivalent typed inputs. - let baseline_mapping = ProviderMappingTable::from_rows(vec![ - ProviderMappingRow { - source: "ceo".to_string(), - source_id: "CEO_RY".to_string(), - valid_from: day(2020, 1, 1), - valid_to: None, - listing_id: 101, - }, - ProviderMappingRow { - source: "ceo".to_string(), - source_id: "CEO_SHOP".to_string(), - valid_from: day(2024, 1, 1), - valid_to: None, - listing_id: 202, - }, - ]) - .expect("valid mapping"); - let baseline_posts = vec![ - CeoPost { - key: "CEO_RY".to_string(), - spiel_id: "sp-wire-1".to_string(), - timestamp_ms: t_wire, - edited_ms: None, - bot: Some("1".to_string()), - user_id: Some("thenewswire".to_string()), - text: "Royal Bank quarterly release".to_string(), - }, - CeoPost { - key: "CEO_RY".to_string(), - spiel_id: "sp-retail-1".to_string(), - timestamp_ms: t_retail, - edited_ms: None, - bot: Some("0".to_string()), - user_id: Some("trader42".to_string()), - text: "Looking strong today".to_string(), - }, - CeoPost { - key: "CEO_SHOP".to_string(), - spiel_id: "sp-edited-1".to_string(), - timestamp_ms: t_edited_post, - edited_ms: Some(t_edited_at), - bot: None, - user_id: Some("analyst99".to_string()), - text: "Updated guidance notes".to_string(), - }, - CeoPost { - key: "CEO_SHOP".to_string(), - spiel_id: "sp-edited-1".to_string(), - timestamp_ms: t_edited_post, - edited_ms: None, - bot: None, - user_id: Some("analyst99".to_string()), - text: "Initial draft".to_string(), - }, - CeoPost { - key: "UNKNOWN_CH".to_string(), - spiel_id: "sp-unmapped-1".to_string(), - timestamp_ms: t_retail, - edited_ms: None, - bot: None, - user_id: Some("anon".to_string()), - text: "Unmapped channel post".to_string(), - }, - CeoPost { - key: "CEO_SHOP".to_string(), - spiel_id: "sp-2025-1".to_string(), - timestamp_ms: t_2025, - edited_ms: None, - bot: Some("1".to_string()), - user_id: Some("globenewswire".to_string()), - text: "2025 update".to_string(), - }, - ]; - let baseline = curate_posts(baseline_posts, "ceo", &baseline_mapping).expect("baseline"); - let read_back = read_all_event_partitions(&out_a); - assert_eq!(read_back, baseline.rows); - assert_eq!(report_a.curate_stats, baseline.stats); - - // Independent checks on kind, subtype, and edited post's ts vs known_at. - assert!(read_back.iter().all(|r| r.kind.as_ref() == EVENT_KIND_POST)); - let wire_row = read_back - .iter() - .find(|r| r.payload_json.contains("sp-wire-1")) - .expect("newswire row"); - assert_eq!(wire_row.subtype, POST_SUBTYPE_NEWSWIRE); - assert_eq!( - wire_row.known_at_source.as_ref(), - KNOWN_AT_SOURCE_POST_TIMESTAMP - ); - assert_eq!(wire_row.ts_micros, t_wire * 1_000); - assert_eq!(wire_row.known_at_micros, t_wire * 1_000); - - let edited_row = read_back - .iter() - .find(|r| r.payload_json.contains("sp-edited-1")) - .expect("edited row"); - assert_eq!(edited_row.subtype, POST_SUBTYPE_RETAIL); - assert_eq!(edited_row.ts_micros, t_edited_post * 1_000); - assert_eq!(edited_row.known_at_micros, t_edited_at * 1_000); - assert_eq!( - edited_row.known_at_source.as_ref(), - KNOWN_AT_SOURCE_POST_EDITED - ); - - // Reversed input order must yield byte-identical Parquet files and deterministic report. - let bson_rev = dir.path().join("ceoPosts_rev.bson"); - let mut rev_bytes = Vec::new(); - for d in docs.iter().rev() { - rev_bytes.extend_from_slice(d); - } - write_bytes(&bson_rev, &rev_bytes); - - let args_b = CuratePostsArgs { - ceo_posts: bson_rev, - out_dir: out_b.clone(), - ..args_a - }; - let report_b = run_curate_posts(&args_b).expect("run reversed"); - assert_report_invariants(&report_b); - assert_eq!(report_a.curate_stats, report_b.curate_stats); - assert_eq!(report_a.write_stats, report_b.write_stats); - - for year in ["year=2024", "year=2025"] { - let a = fs::read(out_a.join("events").join(year).join("part.parquet")).expect("read a"); - let b = fs::read(out_b.join("events").join(year).join("part.parquet")).expect("read b"); - assert_eq!( - a, b, - "reversed input must produce byte-identical {year}/part.parquet" - ); - } - - let strip_timing = |s: &str| { - s.lines() - .filter(|l| !l.trim_start().starts_with("timing:")) - .collect::>() - .join("\n") - }; - assert_eq!( - strip_timing(&format_curate_posts_report(&report_a)), - strip_timing(&format_curate_posts_report(&report_b)) - ); -} - -#[test] -fn seconds_vs_millis_and_custom_fields_with_reader_work_end_to_end() { - let dir = TempDirGuard::new("units"); - let map_path = dir.path().join("mapping.tsv"); - write_bytes(&map_path, b"ceo_alt\tCH_1\t2020-01-01\t\t555\n"); - - let custom_fields = CeoPostsFieldNames { - key: "channel", - spiel_id: "id", - timestamp: "ts", - edited: "ed", - bot: "isBot", - user_id: "author", - text: "body", - }; - - let ts_sec = 1_718_460_000_i64; // 2024-06-15 14:00:00 UTC - let ed_sec = 1_718_463_600_i64; // 2024-06-15 15:00:00 UTC - let doc_sec = make_post_doc( - &custom_fields, - "CH_1", - "p-1", - ts_sec, - Some(ed_sec), - None, - Some("u1"), - "hello", - ); - let doc_ms = make_post_doc( - &custom_fields, - "CH_1", - "p-1", - ts_sec * 1_000, - Some(ed_sec * 1_000), - None, - Some("u1"), - "hello", - ); - - let out_sec = dir.path().join("out_sec"); - let out_ms = dir.path().join("out_ms"); - - let rep_sec = run_curate_posts_with_reader( - &map_path, - "ceo_alt", - &custom_fields, - CeoPostsTimestampUnit::Seconds, - (Path::new("in-mem-sec.bson"), Cursor::new(doc_sec)), - &out_sec, - ) - .expect("run seconds"); - let rep_ms = run_curate_posts_with_reader( - &map_path, - "ceo_alt", - &custom_fields, - CeoPostsTimestampUnit::Millis, - (Path::new("in-mem-ms.bson"), Cursor::new(doc_ms)), - &out_ms, - ) - .expect("run millis"); - - assert_report_invariants(&rep_sec); - assert_report_invariants(&rep_ms); - let rows_sec = read_all_event_partitions(&out_sec); - let rows_ms = read_all_event_partitions(&out_ms); - assert_eq!(rows_sec, rows_ms); - assert_eq!(rows_sec.len(), 1); - assert_eq!(rows_sec[0].ts_micros, ts_sec * 1_000_000); - assert_eq!(rows_sec[0].known_at_micros, ed_sec * 1_000_000); -} - -#[test] -fn clobber_guard_rejects_existing_year_partitions_and_preserves_bytes() { - let dir = TempDirGuard::new("clobber"); - let map_path = dir.path().join("mapping.tsv"); - write_bytes(&map_path, b"ceo\tCEO_RY\t2020-01-01\t\t101\n"); - - let fields = CeoPostsFieldNames::default(); - let bson_path = dir.path().join("posts.bson"); - write_bytes( - &bson_path, - &make_post_doc( - &fields, - "CEO_RY", - "sp-1", - utc_ms(2024, 6, 15, 14, 0, 0), - None, - None, - None, - "hi", - ), - ); - - // 1. Pre-existing events/year=2024/part.parquet with sentinel bytes - let out_a = dir.path().join("out_existing_parquet"); - let year_2024 = out_a.join("events/year=2024"); - fs::create_dir_all(&year_2024).unwrap(); - let sentinel_path = year_2024.join("part.parquet"); - let sentinel_bytes = b"SENTINEL-FILINGS-EARNINGS-EVENTS-PARQUET".to_vec(); - write_bytes(&sentinel_path, &sentinel_bytes); - - let args_a = default_args( - bson_path.clone(), - map_path.clone(), - out_a.clone(), - CeoPostsTimestampUnit::Millis, - ); - let err = run_curate_posts(&args_a).unwrap_err(); - assert!(matches!( - err, - RunCuratePostsError::EventsDatasetExists { .. } - )); - let msg = assert_single_line_err(&err); - assert!(msg.contains("year=2024"), "expected year=2024 in {msg}"); - assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel_bytes); - let entries: Vec<_> = fs::read_dir(out_a.join("events")) - .unwrap() - .map(|e| e.unwrap().file_name()) - .collect(); - assert_eq!(entries.len(), 1); - - // 2. Pre-existing year=* directory without a Parquet file must also fail closed - let out_b = dir.path().join("out_empty_year_dir"); - let year_2025 = out_b.join("events/year=2025"); - fs::create_dir_all(&year_2025).unwrap(); - let args_b = default_args( - bson_path, - map_path, - out_b.clone(), - CeoPostsTimestampUnit::Millis, - ); - let err = run_curate_posts(&args_b).unwrap_err(); - assert!(matches!( - err, - RunCuratePostsError::EventsDatasetExists { .. } - )); - let msg = assert_single_line_err(&err); - assert!(msg.contains("year=2025"), "expected year=2025 in {msg}"); - assert_eq!(fs::read_dir(&year_2025).unwrap().count(), 0); -} - -#[test] -fn clobber_guard_rejects_parent_dir_after_missing_component_and_preserves_tree() { - let dir = TempDirGuard::new("clobber-parent-dir"); - let map_path = dir.path().join("mapping.tsv"); - write_bytes(&map_path, b"ceo\tCEO_RY\t2020-01-01\t\t101\n"); - - let fields = CeoPostsFieldNames::default(); - let bson_path = dir.path().join("posts.bson"); - write_bytes( - &bson_path, - &make_post_doc( - &fields, - "CEO_RY", - "sp-1", - utc_ms(2024, 6, 15, 14, 0, 0), - None, - None, - None, - "hi", - ), - ); - - // Seed exports/shared/events/year=2024/part.parquet while exports/scratch is absent. - let exports_dir = dir.path().join("exports"); - let shared_dir = exports_dir.join("shared"); - let year_2024 = shared_dir.join("events/year=2024"); - fs::create_dir_all(&year_2024).unwrap(); - let sentinel_path = year_2024.join("part.parquet"); - let sentinel_bytes = b"SENTINEL-FILINGS-EARNINGS-2024".to_vec(); - write_bytes(&sentinel_path, &sentinel_bytes); - - let bypass_out = exports_dir.join("scratch").join("..").join("shared"); - assert!(!exports_dir.join("scratch").exists()); - - let args = default_args( - bson_path, - map_path, - bypass_out, - CeoPostsTimestampUnit::Millis, - ); - let err = run_curate_posts(&args).unwrap_err(); - assert!(matches!(err, RunCuratePostsError::InvalidOutDir { .. })); - let msg = assert_single_line_err(&err); - assert!(msg.contains(".."), "expected '..' detail in {msg}"); - - // The missing scratch component must not have been created, and the target partition - // and surrounding directory tree must be completely unchanged. - assert!(!exports_dir.join("scratch").exists()); - assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel_bytes); - - let list_names = |p: &Path| -> Vec { - let mut names: Vec = fs::read_dir(p) - .unwrap() - .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) - .collect(); - names.sort(); - names - }; - assert_eq!(list_names(&exports_dir), vec!["shared"]); - assert_eq!(list_names(&shared_dir), vec!["events"]); - assert_eq!(list_names(&shared_dir.join("events")), vec!["year=2024"]); - assert_eq!(list_names(&year_2024), vec!["part.parquet"]); -} - -#[test] -fn fail_closed_errors_are_typed_single_line_and_leave_out_dir_untouched() { - let dir = TempDirGuard::new("fail-closed"); - let out_dir = dir.path().join("out"); - fs::create_dir_all(&out_dir).unwrap(); - let marker = out_dir.join("keep.txt"); - let marker_bytes = b"DO-NOT-TOUCH".to_vec(); - write_bytes(&marker, &marker_bytes); - - let assert_out_untouched = || { - assert!( - !out_dir.join("events").exists(), - "events dir must not be created" - ); - assert_eq!(fs::read(&marker).unwrap(), marker_bytes); - let entries: Vec<_> = fs::read_dir(&out_dir) - .unwrap() - .map(|e| e.unwrap().file_name()) - .collect(); - assert_eq!(entries.len(), 1); - }; - - let valid_map = dir.path().join("valid_map.tsv"); - write_bytes(&valid_map, b"ceo\tCEO_RY\t2020-01-01\t\t101\n"); - - let fields = CeoPostsFieldNames::default(); - let valid_doc = make_post_doc( - &fields, - "CEO_RY", - "sp-valid", - utc_ms(2024, 6, 15, 14, 0, 0), - None, - None, - None, - "valid post", - ); - let valid_bson = dir.path().join("valid.bson"); - write_bytes(&valid_bson, &valid_doc); - - let base_args = default_args( - valid_bson.clone(), - valid_map.clone(), - out_dir.clone(), - CeoPostsTimestampUnit::Millis, - ); - - // 1. Invalid output paths: regular file as out_dir, empty out_dir, regular file as out/events - let file_as_out = dir.path().join("file_out"); - write_bytes(&file_as_out, b"not-a-dir"); - let err = run_curate_posts(&CuratePostsArgs { - out_dir: file_as_out.clone(), - ..base_args.clone() - }) - .unwrap_err(); - assert!(matches!(err, RunCuratePostsError::InvalidOutDir { .. })); - assert_single_line_err(&err); - assert_eq!(fs::read(&file_as_out).unwrap(), b"not-a-dir"); - - let err = run_curate_posts(&CuratePostsArgs { - out_dir: PathBuf::new(), - ..base_args.clone() - }) - .unwrap_err(); - assert!(matches!(err, RunCuratePostsError::InvalidOutDir { .. })); - assert_single_line_err(&err); - - let out_with_file_events = dir.path().join("out_file_events"); - fs::create_dir_all(&out_with_file_events).unwrap(); - write_bytes(&out_with_file_events.join("events"), b"file-not-dir"); - let err = run_curate_posts(&CuratePostsArgs { - out_dir: out_with_file_events.clone(), - ..base_args.clone() - }) - .unwrap_err(); - assert!(matches!(err, RunCuratePostsError::InvalidOutDir { .. })); - assert_single_line_err(&err); - assert_eq!( - fs::read(out_with_file_events.join("events")).unwrap(), - b"file-not-dir" - ); - - // 2. Blank field name - let err = run_curate_posts(&CuratePostsArgs { - key_field: " ".to_string(), - ..base_args.clone() - }) - .unwrap_err(); - assert!(matches!(err, RunCuratePostsError::InvalidFieldNames { .. })); - assert_single_line_err(&err); - assert_out_untouched(); - - // 3. Duplicate field names - let err = run_curate_posts(&CuratePostsArgs { - spiel_id_field: DEFAULT_KEY_FIELD.to_string(), - ..base_args.clone() - }) - .unwrap_err(); - assert!(matches!(err, RunCuratePostsError::InvalidFieldNames { .. })); - assert_single_line_err(&err); - assert_out_untouched(); - - // 4. Blank mapping_source - let err = run_curate_posts(&CuratePostsArgs { - mapping_source: " \t ".to_string(), - ..base_args.clone() - }) - .unwrap_err(); - assert!(matches!(err, RunCuratePostsError::EmptyMappingSource)); - assert_single_line_err(&err); - assert_out_untouched(); - - // 5. Missing input file - let err = run_curate_posts(&CuratePostsArgs { - ceo_posts: dir.path().join("missing.bson"), - ..base_args.clone() - }) - .unwrap_err(); - assert!(matches!(err, RunCuratePostsError::OpenInput { .. })); - assert_single_line_err(&err); - assert_out_untouched(); - - // 6. Injected reader I/O error (valid doc followed by multiline BrokenPipe) - let multiline_cause = "decompression failed\ncaused by: corrupt zstd frame\r\nstream aborted"; - let err = run_curate_posts_with_reader( - &valid_map, - DEFAULT_MAPPING_SOURCE, - &fields, - CeoPostsTimestampUnit::Millis, - ( - Path::new("failing.bson"), - FailingReader { - prefix: valid_doc.clone(), - pos: 0, - error_message: multiline_cause.to_string(), - }, - ), - &out_dir, - ) - .unwrap_err(); - match &err { - RunCuratePostsError::BsonStream { - source: BsonStreamError::Io { offset, source }, - .. - } => { - assert_eq!(*offset, valid_doc.len() as u64); - // Typed cause is preserved intact. - assert_eq!(source.kind(), io::ErrorKind::BrokenPipe); - assert_eq!(source.to_string(), multiline_cause); - } - other => panic!("expected BsonStream::Io, got {other:?}"), - } - let msg = assert_single_line_err(&err); - assert!(msg.contains("failing.bson"), "expected path in {msg}"); - assert!( - msg.contains(&valid_doc.len().to_string()), - "expected byte offset in {msg}" - ); - assert!( - msg.contains("decompression failed\\ncaused by: corrupt zstd frame\\r\\nstream aborted"), - "expected escaped multiline cause in {msg}" - ); - assert_out_untouched(); - - // 6b. Path containing a newline is also escaped to a single line - let err = run_curate_posts_with_reader( - &valid_map, - DEFAULT_MAPPING_SOURCE, - &fields, - CeoPostsTimestampUnit::Millis, - ( - Path::new("dir/bad\nname.bson"), - FailingReader { - prefix: Vec::new(), - pos: 0, - error_message: "boom\nline2".to_string(), - }, - ), - &out_dir, - ) - .unwrap_err(); - assert!(matches!( - err, - RunCuratePostsError::BsonStream { - source: BsonStreamError::Io { offset: 0, .. }, - .. - } - )); - let msg = assert_single_line_err(&err); - assert!( - msg.contains("dir/bad\\nname.bson"), - "expected escaped path in {msg}" - ); - assert!( - msg.contains("boom\\nline2"), - "expected escaped cause in {msg}" - ); - assert_out_untouched(); - - // 7. Malformed TSV (line 2) - let bad_tsv = dir.path().join("bad.tsv"); - write_bytes( - &bad_tsv, - b"ceo\tCEO_RY\t2020-01-01\t\t101\nceo\tCEO_SHOP\tnot-a-date\t\t202\n", - ); - let err = run_curate_posts(&CuratePostsArgs { - provider_mapping: bad_tsv, - ..base_args.clone() - }) - .unwrap_err(); - assert!(matches!(err, RunCuratePostsError::TsvParse { line: 2, .. })); - let msg = assert_single_line_err(&err); - assert!(msg.contains(":2:"), "expected :2: in {msg}"); - assert_out_untouched(); - - // 8. Overlapping provider_mapping.tsv - let overlap_tsv = dir.path().join("overlap.tsv"); - write_bytes( - &overlap_tsv, - b"ceo\tCEO_RY\t2020-01-01\t2024-06-01\t101\nceo\tCEO_RY\t2024-06-01\t\t102\n", - ); - let err = run_curate_posts(&CuratePostsArgs { - provider_mapping: overlap_tsv, - ..base_args.clone() - }) - .unwrap_err(); - assert!(matches!(err, RunCuratePostsError::ProviderMapping { .. })); - let msg = assert_single_line_err(&err); - assert!(msg.contains("CEO_RY"), "expected conflicting key in {msg}"); - assert_out_untouched(); - - // 9. Truncated BSON after valid doc - let trunc_bson = dir.path().join("trunc.bson"); - let mut trunc_bytes = valid_doc.clone(); - let trunc_offset = trunc_bytes.len() as u64; - trunc_bytes.extend_from_slice(&[30, 0, 0, 0, 0x02, b'a']); - write_bytes(&trunc_bson, &trunc_bytes); - let err = run_curate_posts(&CuratePostsArgs { - ceo_posts: trunc_bson, - ..base_args.clone() - }) - .unwrap_err(); - assert!(matches!( - err, - RunCuratePostsError::BsonStream { - source: BsonStreamError::TruncatedDocument { offset, .. }, - .. - } if offset == trunc_offset - )); - let msg = assert_single_line_err(&err); - assert!(msg.contains(&trunc_offset.to_string())); - assert_out_untouched(); - - // 10. Corrupt BSON element after valid doc - let corrupt_bson = dir.path().join("corrupt.bson"); - let mut corrupt_doc = RawDocumentBuf::new(); - corrupt_doc.append(cstr!("ceoId"), "CEO_RY"); - corrupt_doc.append(cstr!("z"), 1_i32); - let mut bad_doc_bytes = corrupt_doc.into_bytes(); - let z_pos = bad_doc_bytes - .windows(3) - .position(|w| w == [0x10, b'z', 0x00]) - .unwrap(); - bad_doc_bytes[z_pos] = 0x7e; - - let mut combined_corrupt = valid_doc.clone(); - let corrupt_offset = combined_corrupt.len() as u64; - combined_corrupt.extend_from_slice(&bad_doc_bytes); - write_bytes(&corrupt_bson, &combined_corrupt); - let err = run_curate_posts(&CuratePostsArgs { - ceo_posts: corrupt_bson, - ..base_args.clone() - }) - .unwrap_err(); - assert!(matches!( - err, - RunCuratePostsError::CorruptBson { offset, .. } if offset == corrupt_offset - )); - let msg = assert_single_line_err(&err); - assert!(msg.contains(&corrupt_offset.to_string())); - assert_out_untouched(); - - // 11. Curation timestamp overflow after valid doc -> late failure publishes nothing - let overflow_bson = dir.path().join("overflow.bson"); - let mut overflow_bytes = valid_doc; - overflow_bytes.extend_from_slice(&make_post_doc( - &fields, - "CEO_RY", - "sp-overflow", - i64::MAX, - None, - None, - None, - "overflow ts", - )); - write_bytes(&overflow_bson, &overflow_bytes); - let err = run_curate_posts(&CuratePostsArgs { - ceo_posts: overflow_bson, - ..base_args - }) - .unwrap_err(); - assert!(matches!( - err, - RunCuratePostsError::CurateWrite { - source: CuratePostsWriteError::Curate(CuratePostsError::Posts( - PostsError::TimestampOverflow { .. } - )), - .. - } - )); - assert_single_line_err(&err); - assert_out_untouched(); -} - -#[test] -fn empty_and_all_unmapped_inputs_return_zero_rows_without_creating_events_dir() { - let dir = TempDirGuard::new("zero-rows"); - let map_path = dir.path().join("mapping.tsv"); - write_bytes(&map_path, b"ceo\tCEO_RY\t2020-01-01\t\t101\n"); - - // 1. Empty BSON input - let empty_bson = dir.path().join("empty.bson"); - write_bytes(&empty_bson, &[]); - let out_empty = dir.path().join("out_empty"); - let rep_empty = run_curate_posts(&default_args( - empty_bson, - map_path.clone(), - out_empty.clone(), - CeoPostsTimestampUnit::Millis, - )) - .expect("empty succeeds"); - assert_report_invariants(&rep_empty); - assert_eq!(rep_empty.docs_framed, 0); - assert_eq!(rep_empty.write_stats.rows_written, 0); - assert_eq!(rep_empty.write_stats.files_written, 0); - assert!(!out_empty.join("events").exists()); - - // 2. All-unmapped BSON input - let fields = CeoPostsFieldNames::default(); - let unmapped_bson = dir.path().join("unmapped.bson"); - write_bytes( - &unmapped_bson, - &make_post_doc( - &fields, - "NO_MATCH", - "sp-unmapped", - utc_ms(2024, 6, 15, 14, 0, 0), - None, - None, - None, - "unmapped", - ), - ); - let out_unmapped = dir.path().join("out_unmapped"); - let rep_unmapped = run_curate_posts(&default_args( - unmapped_bson, - map_path, - out_unmapped.clone(), - CeoPostsTimestampUnit::Millis, - )) - .expect("all-unmapped succeeds"); - assert_report_invariants(&rep_unmapped); - assert_eq!(rep_unmapped.docs_framed, 1); - assert_eq!(rep_unmapped.curate_stats.dropped_unmapped, 1); - assert_eq!(rep_unmapped.write_stats.rows_written, 0); - assert_eq!(rep_unmapped.write_stats.files_written, 0); - assert!(!out_unmapped.join("events").exists()); -} - -/// Reader that serves `bytes` and, on the first EOF, runs `on_eof` once (used to simulate another -/// publisher creating an `events/year=*` partition while the dump is still being decoded). -struct EofHookReader { - bytes: Vec, - pos: usize, - on_eof: Option, -} - -impl Read for EofHookReader { - fn read(&mut self, buf: &mut [u8]) -> io::Result { - if self.pos < self.bytes.len() { - let n = (self.bytes.len() - self.pos).min(buf.len()); - buf[..n].copy_from_slice(&self.bytes[self.pos..self.pos + n]); - self.pos += n; - return Ok(n); - } - if let Some(mut hook) = self.on_eof.take() { - hook(); - } - Ok(0) - } -} - -fn sorted_names(p: &Path) -> Vec { - let mut names: Vec = fs::read_dir(p) - .expect("read dir") - .map(|e| e.expect("entry").file_name().to_string_lossy().into_owned()) - .collect(); - names.sort(); - names -} - -#[test] -fn post_decode_guard_rejects_partition_created_during_decode_and_preserves_bytes() { - let dir = TempDirGuard::new("guard-recheck"); - let map_path = dir.path().join("mapping.tsv"); - write_bytes(&map_path, b"ceo\tCEO_RY\t2020-01-01\t\t101\n"); - let fields = CeoPostsFieldNames::default(); - let doc = make_post_doc( - &fields, - "CEO_RY", - "sp-1", - utc_ms(2024, 6, 15, 14, 0, 0), - None, - None, - None, - "hi", - ); - - let out_dir = dir.path().join("out"); - let partition = out_dir.join("events").join("year=2024"); - let sentinel_path = partition.join("part.parquet"); - let sentinel = b"SENTINEL-CONCURRENT-FILINGS".to_vec(); - assert!( - !out_dir.exists(), - "first guard must see a fresh output root" - ); - - let hook_partition = partition.clone(); - let hook_sentinel_path = sentinel_path.clone(); - let hook_sentinel = sentinel.clone(); - let err = run_curate_posts_with_reader( - &map_path, - DEFAULT_MAPPING_SOURCE, - &fields, - CeoPostsTimestampUnit::Millis, - ( - Path::new("hooked.bson"), - EofHookReader { - bytes: doc, - pos: 0, - on_eof: Some(move || { - fs::create_dir_all(&hook_partition).expect("create concurrent partition"); - write_bytes(&hook_sentinel_path, &hook_sentinel); - }), - }, - ), - &out_dir, - ) - .unwrap_err(); - - assert!( - matches!(&err, RunCuratePostsError::EventsDatasetExists { path } if path == &partition), - "expected EventsDatasetExists for {partition:?}, got {err:?}" - ); - assert_single_line_err(&err); - assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel); - assert_eq!(sorted_names(&out_dir.join("events")), vec!["year=2024"]); - assert_eq!(sorted_names(&partition), vec!["part.parquet"]); -} - -#[test] -fn events_dir_with_only_non_year_entries_is_published_and_non_year_entries_preserved() { - let dir = TempDirGuard::new("non-year-entries"); - let map_path = dir.path().join("mapping.tsv"); - write_bytes(&map_path, b"ceo\tCEO_RY\t2020-01-01\t\t101\n"); - let fields = CeoPostsFieldNames::default(); - let bson_path = dir.path().join("posts.bson"); - write_bytes( - &bson_path, - &make_post_doc( - &fields, - "CEO_RY", - "sp-1", - utc_ms(2024, 6, 15, 14, 0, 0), - None, - None, - None, - "hi", - ), - ); - - let out_dir = dir.path().join("out"); - let events_dir = out_dir.join("events"); - fs::create_dir_all(&events_dir).unwrap(); - let readme = events_dir.join("README.txt"); - write_bytes(&readme, b"not a partition"); - - let report = run_curate_posts(&default_args( - bson_path, - map_path, - out_dir.clone(), - CeoPostsTimestampUnit::Millis, - )) - .expect("non-year entries must not trip the clobber guard"); - - assert_report_invariants(&report); - assert_eq!(report.write_stats.rows_written, 1); - assert_eq!(fs::read(&readme).unwrap(), b"not a partition"); - assert_eq!(sorted_names(&events_dir), vec!["README.txt", "year=2024"]); -} - -#[test] -fn parent_dir_through_existing_components_still_hits_events_guard() { - let dir = TempDirGuard::new("parent-existing"); - let map_path = dir.path().join("mapping.tsv"); - write_bytes(&map_path, b"ceo\tCEO_RY\t2020-01-01\t\t101\n"); - let fields = CeoPostsFieldNames::default(); - let bson_path = dir.path().join("posts.bson"); - write_bytes( - &bson_path, - &make_post_doc( - &fields, - "CEO_RY", - "sp-1", - utc_ms(2024, 6, 15, 14, 0, 0), - None, - None, - None, - "hi", - ), - ); - - let exports = dir.path().join("exports"); - let shared_partition = exports.join("shared/events/year=2024"); - fs::create_dir_all(&shared_partition).unwrap(); - fs::create_dir_all(exports.join("scratch")).unwrap(); - let sentinel_path = shared_partition.join("part.parquet"); - write_bytes(&sentinel_path, b"SENTINEL"); - - // `scratch` exists, so `..` resolves consistently and the guard must inspect `shared`. - let out = exports.join("scratch").join("..").join("shared"); - let err = run_curate_posts(&default_args( - bson_path, - map_path, - out, - CeoPostsTimestampUnit::Millis, - )) - .unwrap_err(); - assert!( - matches!(err, RunCuratePostsError::EventsDatasetExists { .. }), - "got {err:?}" - ); - assert_single_line_err(&err); - assert_eq!(fs::read(&sentinel_path).unwrap(), b"SENTINEL"); - assert_eq!(sorted_names(&exports), vec!["scratch", "shared"]); - assert!(sorted_names(&exports.join("scratch")).is_empty()); -} - -#[test] -fn eastern_posting_date_mapping_and_edit_clamp_match_curate_posts_baseline() { - let dir = TempDirGuard::new("eastern-pit"); - let map_path = dir.path().join("mapping.tsv"); - // Listing switch at the Eastern calendar boundary 2023-12-31 -> 2024-01-01 (valid_to inclusive). - write_bytes( - &map_path, - b"ceo\tCEO_RY\t2020-01-01\t2023-12-31\t101\nceo\tCEO_RY\t2024-01-01\t\t102\n", - ); - let fields = CeoPostsFieldNames::default(); - - // 2024-01-01 03:00 UTC == 2023-12-31 22:00 EST -> listing 101 (UTC date would give 102). - let t_late_eve = utc_ms(2024, 1, 1, 3, 0, 0); - // 2024-01-01 06:00 UTC == 2024-01-01 01:00 EST -> listing 102. - let t_new_year = utc_ms(2024, 1, 1, 6, 0, 0); - // Posted 2023-12-31 23:30 EST, edited after the switch: mapping must follow posted date. - let t_edit_posted = utc_ms(2024, 1, 1, 4, 30, 0); - let t_edit_at = utc_ms(2024, 1, 2, 15, 0, 0); - // Edit earlier than posting (clock skew): known_at clamps to posted_at. - let t_skew_posted = utc_ms(2024, 3, 5, 15, 0, 0); - let t_skew_edit = utc_ms(2024, 3, 5, 14, 0, 0); - - let inputs: Vec<(&str, i64, Option, Option<&str>)> = vec![ - ("sp-eve", t_late_eve, None, Some("1")), - ("sp-ny", t_new_year, None, None), - ("sp-edit", t_edit_posted, Some(t_edit_at), None), - ("sp-skew", t_skew_posted, Some(t_skew_edit), Some("0")), - ]; - let mut bytes = Vec::new(); - let mut baseline_posts = Vec::new(); - for (spiel, ts, ed, bot) in &inputs { - bytes.extend_from_slice(&make_post_doc( - &fields, - "CEO_RY", - spiel, - *ts, - *ed, - *bot, - Some("u"), - spiel, - )); - baseline_posts.push(CeoPost { - key: "CEO_RY".to_string(), - spiel_id: spiel.to_string(), - timestamp_ms: *ts, - edited_ms: *ed, - bot: bot.map(str::to_string), - user_id: Some("u".to_string()), - text: spiel.to_string(), - }); - } - let bson_path = dir.path().join("posts.bson"); - write_bytes(&bson_path, &bytes); - let out_dir = dir.path().join("out"); - - let report = run_curate_posts(&default_args( - bson_path, - map_path.clone(), - out_dir.clone(), - CeoPostsTimestampUnit::Millis, - )) - .expect("run"); - assert_report_invariants(&report); - assert_eq!(report.curate_stats.builder.edited, 2); - assert_eq!(report.curate_stats.builder.edited_before_posted, 1); - assert_eq!(report.write_stats.rows_written, 4); - - let mapping = ProviderMappingTable::from_rows(vec![ - ProviderMappingRow { - source: "ceo".to_string(), - source_id: "CEO_RY".to_string(), - valid_from: day(2020, 1, 1), - valid_to: Some(day(2023, 12, 31)), - listing_id: 101, - }, - ProviderMappingRow { - source: "ceo".to_string(), - source_id: "CEO_RY".to_string(), - valid_from: day(2024, 1, 1), - valid_to: None, - listing_id: 102, - }, - ]) - .unwrap(); - let baseline = curate_posts(baseline_posts, "ceo", &mapping).expect("baseline"); - let rows = read_all_event_partitions(&out_dir); - assert_eq!(rows, baseline.rows); - assert_eq!(report.curate_stats, baseline.stats); - - let find = |spiel: &str| { - rows.iter() - .find(|r| r.payload_json.contains(spiel)) - .unwrap_or_else(|| panic!("row {spiel}")) - }; - assert_eq!(find("sp-eve").listing_id, 101); - assert_eq!(find("sp-ny").listing_id, 102); - let edit = find("sp-edit"); - assert_eq!(edit.listing_id, 101); - assert_eq!(edit.ts_micros, t_edit_posted * 1_000); - assert_eq!(edit.known_at_micros, t_edit_at * 1_000); - let skew = find("sp-skew"); - assert_eq!(skew.ts_micros, t_skew_posted * 1_000); - assert_eq!(skew.known_at_micros, t_skew_posted * 1_000); - // No row may become visible before it was posted. - assert!(rows.iter().all(|r| r.known_at_micros >= r.ts_micros)); - // All four posts land in the UTC-2024 partition only. - assert_eq!(sorted_names(&out_dir.join("events")), vec!["year=2024"]); -} diff --git a/tools/curate-etl/src/run_curate_qm_bars_1m.rs b/tools/curate-etl/src/run_curate_qm_bars_1m.rs deleted file mode 100644 index 0d6ec861..00000000 --- a/tools/curate-etl/src/run_curate_qm_bars_1m.rs +++ /dev/null @@ -1,643 +0,0 @@ -//! Bounded-memory file-to-file `qmIntraday` -> `bars_1m` runner (`M2.3m`). -//! -//! Streams a concatenated raw BSON `qmIntraday` dump alongside a headerless 5-column -//! `provider_mapping.tsv` into per-shard QuestDB ILP v2 files -//! (`/bars_1m_qm.shard-.ilp`) via [`crate::curate_qm_bars_1m`]. -//! -//! # Bounded-Memory Chunking & Zero Split Un-Adjustment -//! - Drives [`RawBsonChunkReader::with_options`], [`RawBsonChunkReader::next_chunk`], and -//! [`decode_qm_intraday_buffer`] directly—the exact reader and buffer decoder wrapped by -//! `crate::bson_stream::decode_qm_intraday_chunks`, whose callback API hides chunk boundaries. -//! - Each framed chunk is decoded into a chunk-local `Vec>` borrowing -//! `qmSearchCode` directly from the chunk slice, then curated per chunk via -//! [`curate_and_write_qm_bars_1m`] against one shared [`IlpShardedWriter`]. Borrows are -//! consumed before advancing the chunk reader. -//! - Takes no splits input: `qmIntraday` raw fields (`open..close`, `sharevolume`) are already -//! un-adjusted (`design/DATA-CONTRACTS.md` §1) and pass through bit-identical (aside from -//! `-0.0 -> +0.0` volume normalization). -//! - [`IlpShardedWriter::finish`] is called exactly once after clean EOF. -//! - Peak memory is bounded by the `provider_mapping` table, the current BSON chunk -//! (`BsonStreamOptions::chunk_capacity_bytes`, growing only for a single document up to -//! `max_doc_bytes`), that chunk's curation buffers, and one ILP batch buffer per shard— -//! independent of the total `qmIntraday` input size. -//! -//! # Cross-Chunk Semantics, Output Naming & Reporting -//! - Collision collapse/drop in `curate_qm_bars_1m` and row ordering apply **per chunk**: output -//! is sorted by `(listing_id, ts)` within each chunk, and the same `(listing_id, ts)` appearing -//! in two different chunks is emitted twice (with zero within-chunk collapse between them) and -//! relies on QuestDB `DEDUP UPSERT KEYS(ts, listing_id)`. -//! - `CurateQmBars1mRunReport::curate_stats` sums every field of [`CurateBars1mStats`] and its -//! nested [`crate::bars_1m::Bars1mStats`] across chunks. In particular, -//! `curate_stats.listings_out` and `curate_stats.builder.keys_out` are **sums of per-chunk -//! counts**, not global distinct counts. -//! - Output files use the distinct shard prefix `bars_1m_qm` (`bars_1m_qm.shard-.ilp`) so a -//! QM run can share `out_dir` with `run_curate_bars_1m` (`bars_1m.shard-.ilp`) without -//! tripping either preflight, while every emitted ILP v2 row still targets QuestDB table -//! `bars_1m` (`TABLE_BARS_1M`) with `source=qm_raw` (`BARS_1M_SOURCE_QM`). -//! - `mapping_source` is caller-supplied and forwarded verbatim to `curate_and_write_qm_bars_1m` -//! after rejecting empty or whitespace-only values (`DEFAULT_QM_BARS_1M_MAPPING_SOURCE = "qm"`). -//! - `known_at_micros` is a caller-supplied run timestamp written verbatim to every ILP row's -//! `known_at` column; it supplies no evidence of earlier market availability. -//! -//! # File Publication & Fail-Closed Guarantees -//! - Preflight scans `out_dir` for **any** pre-existing `bars_1m_qm.shard-.ilp` file -//! (regardless of the requested `shard_count`) and fails closed before staging so stale shards -//! from a prior larger-shard-count run cannot survive alongside a new export. -//! - Each shard writes into an exclusively created staging file in `out_dir` -//! (`.bars_1m_qm.shard-..tmp`), flushes and `sync_all`s on `finish`, and publishes -//! to `bars_1m_qm.shard-.ilp` via same-directory `hard_link` followed by removing the staged -//! name (preserving no-overwrite semantics even if a final file appears after preflight). -//! - Any error (validation, missing/malformed inputs, fatal BSON framing/I/O, ILP write/flush, or -//! publication collision) drops open sinks, rolls back only final files created by this run, -//! removes this run's staging files, and leaves pre-existing files untouched. Per-document -//! semantic decode errors stay counted-and-skipped in [`BsonQmIntradayDecodeStats`]. - -use std::error::Error; -use std::fmt; -use std::fs::{self, File}; -use std::io::{self, Write}; -use std::path::{Path, PathBuf}; -use std::time::Instant; - -use crate::bars_1m::EodIntradayBar; -use crate::bson_qm_intraday::{decode_qm_intraday_buffer, BsonQmIntradayDecodeStats}; -use crate::bson_stream::{BsonStreamError, BsonStreamOptions, RawBsonChunkReader}; -use crate::curate_bars_1m::{CurateBars1mStats, CurateBars1mWriteError}; -use crate::curate_qm_bars_1m::curate_and_write_qm_bars_1m; -use crate::ilp::{IlpShardedWriter, IlpWriteStats, IlpWriterError, IlpWriterOptions}; -use crate::parquet_bars::RollbackFailure; -use crate::parquet_publish::{next_run_id, StagingFileGuard}; -use crate::provider_mapping::ProviderMappingTable; -use crate::run_curate_bars::{load_provider_mapping_tsv, RunCurateBarsError}; -use crate::run_curate_bars_1m::{ - add_curate_bars_1m_stats, create_exclusive_shard_tmp_file_for_table, preflight_shard_out_dir, - publish_staged_shards_for_table, ShardPublishError, SyncedBufFile, -}; -use crate::run_curate_fx_1m::cleanup_armed_staged_shards; - -/// Default `provider_mapping` source namespace for `qmSearchCode` rows in `qmIntraday`. -pub const DEFAULT_QM_BARS_1M_MAPPING_SOURCE: &str = "qm"; - -/// Output filename prefix for QM intraday shard files (`bars_1m_qm.shard-.ilp`). -/// -/// Distinct from `TABLE_BARS_1M` (`bars_1m`) so QM and EOD intraday exports can share `out_dir` -/// without colliding in preflight or publication while both emit ILP v2 rows into `bars_1m`. -const QM_BARS_1M_SHARD_PREFIX: &str = "bars_1m_qm"; - -/// Arguments for [`run_curate_qm_bars_1m`] and [`run_curate_qm_bars_1m_with_readers`]. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct CurateQmBars1mArgs { - pub intraday_path: PathBuf, - pub provider_mapping_path: PathBuf, - pub out_dir: PathBuf, - pub mapping_source: String, - pub shard_count: usize, - pub known_at_micros: i64, - pub stream_options: BsonStreamOptions, - pub ilp_options: IlpWriterOptions, -} - -/// Full run report produced by [`run_curate_qm_bars_1m`] and -/// [`run_curate_qm_bars_1m_with_readers`]. -/// -/// Conservation invariants: -/// - `intraday_docs_framed as usize == intraday_decode.docs_seen` -/// - `intraday_decode.docs_seen == intraday_decode.rows_decoded + intraday_decode.rejected_total()` -/// - `intraday_decode.rows_decoded == curate_stats.builder.bars_in` -/// - `curate_stats.rows_in == curate_stats.builder.rows_out` -/// - `curate_stats.rows_in == curate_stats.rows_out + curate_stats.dropped_unmapped + curate_stats.listing_collision_collapsed + curate_stats.listing_collision_dropped` -/// - `curate_stats.pre_rows_out + curate_stats.rth_rows_out + curate_stats.post_rows_out == curate_stats.rows_out` -/// - `rows_written == curate_stats.rows_out == ilp_stats.rows == ilp_stats.per_shard_rows.iter().sum::()` -/// -/// Note: `curate_stats.listings_out` and `curate_stats.builder.keys_out` are summed across chunks -/// (not global distinct counts). -#[derive(Debug, Clone, PartialEq)] -pub struct CurateQmBars1mRunReport { - pub intraday_docs_framed: u64, - pub intraday_bytes_read: u64, - pub intraday_decode: BsonQmIntradayDecodeStats, - pub chunks: usize, - pub max_rows_per_chunk: usize, - pub curate_stats: CurateBars1mStats, - pub rows_written: usize, - pub ilp_stats: IlpWriteStats, - pub shard_count: usize, - pub elapsed_secs: f64, -} - -/// Typed errors returned by [`run_curate_qm_bars_1m`] and [`run_curate_qm_bars_1m_with_readers`]. -#[derive(Debug)] -pub enum RunCurateQmBars1mError { - /// `mapping_source` was empty or contained only whitespace. - EmptyMappingSource, - /// `shard_count` was `0`. - ZeroShardCount, - /// `out_dir` exists and is not a directory. - InvalidOutDir { path: PathBuf, detail: String }, - /// A final shard output file (`bars_1m_qm.shard-.ilp`) already existed. - OutputFileExists { path: PathBuf }, - /// Failed to open the input `qmIntraday` dump file. - OpenInput { - label: &'static str, - path: PathBuf, - source: io::Error, - }, - /// Failed to load `provider_mapping.tsv` via the shared reference loader. - LoadReference(RunCurateBarsError), - /// Fatal BSON framing, option validation, or I/O error while reading `qmIntraday`. - BsonStream { - label: &'static str, - path: PathBuf, - source: BsonStreamError, - }, - /// Curation or per-row ILP write error inside the per-chunk `qmIntraday` curation stage. - CurateWrite(CurateBars1mWriteError), - /// ILP writer initialization or final flush error. - Ilp(IlpWriterError), - /// Filesystem I/O error while creating, syncing, linking, or cleaning up shard files. - Io { path: PathBuf, source: io::Error }, - /// Publication or failure cleanup failed and removing one or more final or staging files also - /// failed. - RollbackFailed { - cause: Box, - failures: Vec, - }, -} - -impl From for RunCurateQmBars1mError { - fn from(err: ShardPublishError) -> Self { - match err { - ShardPublishError::InvalidOutDir { path, detail } => { - Self::InvalidOutDir { path, detail } - } - ShardPublishError::OutputFileExists { path } => Self::OutputFileExists { path }, - ShardPublishError::Io { path, source } => Self::Io { path, source }, - ShardPublishError::RollbackFailed { cause, failures } => Self::RollbackFailed { - cause: Box::new((*cause).into()), - failures, - }, - } - } -} - -impl fmt::Display for RunCurateQmBars1mError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::EmptyMappingSource => write!(f, "mapping_source must not be empty or blank"), - Self::ZeroShardCount => write!(f, "shard_count must be >= 1"), - Self::InvalidOutDir { path, detail } => { - write!(f, "invalid out_dir '{}': {detail}", path.display()) - } - Self::OutputFileExists { path } => write!( - f, - "refusing to overwrite existing output file '{}'", - path.display() - ), - Self::OpenInput { - label, - path, - source, - } => write!(f, "failed to open {label} '{}': {source}", path.display()), - Self::LoadReference(err) => write!(f, "failed loading reference inputs: {err}"), - Self::BsonStream { - label, - path, - source, - } => write!(f, "failed reading {label} '{}': {source}", path.display()), - Self::CurateWrite(err) => write!(f, "{err}"), - Self::Ilp(err) => write!(f, "qm bars_1m ILP writer failed: {err}"), - Self::Io { path, source } => { - write!(f, "I/O error on '{}': {source}", path.display()) - } - Self::RollbackFailed { cause, failures } => { - write!(f, "{cause}; rollback also failed for: ")?; - for (i, failure) in failures.iter().enumerate() { - if i > 0 { - write!(f, ", ")?; - } - write!(f, "{failure}")?; - } - Ok(()) - } - } - } -} - -impl Error for RunCurateQmBars1mError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::OpenInput { source, .. } | Self::Io { source, .. } => Some(source), - Self::LoadReference(err) => Some(err), - Self::BsonStream { source, .. } => Some(source), - Self::CurateWrite(err) => Some(err), - Self::Ilp(err) => Some(err), - Self::RollbackFailed { cause, .. } => Some(cause.as_ref()), - Self::EmptyMappingSource - | Self::ZeroShardCount - | Self::InvalidOutDir { .. } - | Self::OutputFileExists { .. } => None, - } - } -} - -fn validate_common_args(args: &CurateQmBars1mArgs) -> Result<(), RunCurateQmBars1mError> { - if args.mapping_source.trim().is_empty() { - return Err(RunCurateQmBars1mError::EmptyMappingSource); - } - if args.shard_count == 0 { - return Err(RunCurateQmBars1mError::ZeroShardCount); - } - args.stream_options - .validate() - .map_err(|source| RunCurateQmBars1mError::BsonStream { - label: "qm-intraday", - path: args.intraday_path.clone(), - source, - })?; - if args.ilp_options.max_batch_bytes == 0 { - return Err(RunCurateQmBars1mError::Ilp( - IlpWriterError::ZeroMaxBatchBytes, - )); - } - if args.ilp_options.max_batch_rows == 0 { - return Err(RunCurateQmBars1mError::Ilp( - IlpWriterError::ZeroMaxBatchRows, - )); - } - Ok(()) -} - -fn validate_file_mode_args(args: &CurateQmBars1mArgs) -> Result<(), RunCurateQmBars1mError> { - validate_common_args(args)?; - preflight_shard_out_dir(&args.out_dir, QM_BARS_1M_SHARD_PREFIX)?; - Ok(()) -} - -fn load_provider_mapping_table( - provider_mapping_path: &Path, -) -> Result { - let mapping_rows = load_provider_mapping_tsv(provider_mapping_path) - .map_err(RunCurateQmBars1mError::LoadReference)?; - ProviderMappingTable::from_rows(mapping_rows).map_err(|source| { - RunCurateQmBars1mError::LoadReference(RunCurateBarsError::ProviderMapping { - path: provider_mapping_path.to_path_buf(), - source, - }) - }) -} - -fn stream_qm_intraday_chunks_to_writer( - args: &CurateQmBars1mArgs, - mapping: &ProviderMappingTable, - intraday: R, - mut writer: IlpShardedWriter, - start: Instant, -) -> Result -where - R: io::Read, - W: Write + Send, -{ - let mut reader = RawBsonChunkReader::with_options(intraday, args.stream_options).map_err( - |source| RunCurateQmBars1mError::BsonStream { - label: "qm-intraday", - path: args.intraday_path.clone(), - source, - }, - )?; - - let mut intraday_decode = BsonQmIntradayDecodeStats::default(); - let mut curate_stats = CurateBars1mStats::default(); - let mut chunks: usize = 0; - let mut max_rows_per_chunk: usize = 0; - let mut rows_written: usize = 0; - - while let Some(chunk) = - reader - .next_chunk() - .map_err(|source| RunCurateQmBars1mError::BsonStream { - label: "qm-intraday", - path: args.intraday_path.clone(), - source, - })? - { - let mut chunk_bars: Vec> = Vec::new(); - let chunk_decode = decode_qm_intraday_buffer( - chunk.bytes, - |raw| { - chunk_bars.push(raw.into_eod_intraday_bar(|key, _| key)); - }, - |_local_offset, _err| {}, - ); - intraday_decode.merge(&chunk_decode); - - chunks += 1; - let chunk_len = chunk_bars.len(); - if chunk_len > max_rows_per_chunk { - max_rows_per_chunk = chunk_len; - } - - let write_report = curate_and_write_qm_bars_1m( - chunk_bars, - mapping, - &args.mapping_source, - &mut writer, - args.known_at_micros, - ) - .map_err(RunCurateQmBars1mError::CurateWrite)?; - - add_curate_bars_1m_stats(&mut curate_stats, &write_report.curate_stats); - rows_written += write_report.rows_written; - } - - let intraday_docs_framed = reader.docs_framed(); - let intraday_bytes_read = reader.bytes_read(); - let ilp_stats = writer.finish().map_err(RunCurateQmBars1mError::Ilp)?; - - Ok(CurateQmBars1mRunReport { - intraday_docs_framed, - intraday_bytes_read, - intraday_decode, - chunks, - max_rows_per_chunk, - curate_stats, - rows_written, - ilp_stats, - shard_count: args.shard_count, - elapsed_secs: start.elapsed().as_secs_f64(), - }) -} - -/// Runs the bounded-memory `qmIntraday` -> `bars_1m` curation pipeline from an arbitrary -/// [`io::Read`] stream into per-shard sinks created by `make_sink`. -/// -/// Validates `args` (rejecting blank `mapping_source` first, then `shard_count`, stream options, -/// and ILP options) and loads `provider_mapping.tsv` from `args.provider_mapping_path` before -/// calling `make_sink` once per shard (`0..args.shard_count`). Streams `intraday` through -/// [`RawBsonChunkReader::with_options`] + [`decode_qm_intraday_buffer`], curating and writing once -/// per chunk without split un-adjustment, and calls [`IlpShardedWriter::finish`] exactly once -/// after clean EOF. -pub fn run_curate_qm_bars_1m_with_readers( - args: &CurateQmBars1mArgs, - intraday: R, - mut make_sink: F, -) -> Result -where - R: io::Read, - W: Write + Send, - F: FnMut(usize) -> W, -{ - let start = Instant::now(); - validate_common_args(args)?; - - let mapping = load_provider_mapping_table(&args.provider_mapping_path)?; - - let mut sinks = Vec::with_capacity(args.shard_count); - for shard_idx in 0..args.shard_count { - sinks.push(make_sink(shard_idx)); - } - let writer = - IlpShardedWriter::new(sinks, args.ilp_options).map_err(RunCurateQmBars1mError::Ilp)?; - - stream_qm_intraday_chunks_to_writer(args, &mapping, intraday, writer, start) -} - -fn fail_with_staging_cleanup( - cause: RunCurateQmBars1mError, - staged: &mut [(PathBuf, StagingFileGuard)], - remove_file: &mut RF, -) -> RunCurateQmBars1mError -where - RF: FnMut(&Path) -> io::Result<()>, -{ - let staging_failures = cleanup_armed_staged_shards(staged, remove_file); - if staging_failures.is_empty() { - return cause; - } - match cause { - RunCurateQmBars1mError::RollbackFailed { - cause: inner_cause, - mut failures, - } => { - failures.extend(staging_failures); - RunCurateQmBars1mError::RollbackFailed { - cause: inner_cause, - failures, - } - } - other => RunCurateQmBars1mError::RollbackFailed { - cause: Box::new(other), - failures: staging_failures, - }, - } -} - -/// Private file-mode seam accepting an injected reader, sink factory, pre-link hook, and staging -/// unlink hook so tests can exercise staging, writer failure, publication rollback, and staging -/// unlink failure reporting deterministically. -fn run_curate_qm_bars_1m_to_dir_with_cleanup_hook( - args: &CurateQmBars1mArgs, - intraday: R, - mut make_sink: SF, - before_link: BL, - mut remove_staged_file: RF, -) -> Result -where - R: io::Read, - W: Write + Send, - SF: FnMut(usize, File) -> W, - BL: FnMut(usize, &Path), - RF: FnMut(&Path) -> io::Result<()>, -{ - let start = Instant::now(); - validate_file_mode_args(args)?; - - let mapping = load_provider_mapping_table(&args.provider_mapping_path)?; - - fs::create_dir_all(&args.out_dir).map_err(|source| RunCurateQmBars1mError::Io { - path: args.out_dir.clone(), - source, - })?; - - let run_id = next_run_id(); - let mut staged: Vec<(PathBuf, StagingFileGuard)> = Vec::with_capacity(args.shard_count); - let mut sinks: Vec = Vec::with_capacity(args.shard_count); - for shard_idx in 0..args.shard_count { - let (tmp_path, file) = match create_exclusive_shard_tmp_file_for_table( - &args.out_dir, - QM_BARS_1M_SHARD_PREFIX, - shard_idx, - &run_id, - ) { - Ok(pair) => pair, - Err(err) => { - drop(sinks); - return Err(fail_with_staging_cleanup( - err.into(), - &mut staged, - &mut remove_staged_file, - )); - } - }; - let guard = StagingFileGuard::new(tmp_path.clone()); - staged.push((tmp_path, guard)); - sinks.push(make_sink(shard_idx, file)); - } - - let writer = match IlpShardedWriter::new(sinks, args.ilp_options) { - Ok(writer) => writer, - Err(err) => { - return Err(fail_with_staging_cleanup( - RunCurateQmBars1mError::Ilp(err), - &mut staged, - &mut remove_staged_file, - )); - } - }; - let report = match stream_qm_intraday_chunks_to_writer(args, &mapping, intraday, writer, start) - { - Ok(report) => report, - Err(err) => { - return Err(fail_with_staging_cleanup( - err, - &mut staged, - &mut remove_staged_file, - )); - } - }; - - if let Err(err) = publish_staged_shards_for_table( - &args.out_dir, - QM_BARS_1M_SHARD_PREFIX, - &mut staged, - before_link, - ) { - return Err(fail_with_staging_cleanup( - err.into(), - &mut staged, - &mut remove_staged_file, - )); - } - Ok(report) -} - -/// Private file-mode seam accepting an injected reader, sink factory, and pre-link hook so tests -/// can exercise staging, writer failure, and post-preflight publication rollback through the exact -/// file publication path. -fn run_curate_qm_bars_1m_to_dir_with_hooks( - args: &CurateQmBars1mArgs, - intraday: R, - make_sink: SF, - before_link: BL, -) -> Result -where - R: io::Read, - W: Write + Send, - SF: FnMut(usize, File) -> W, - BL: FnMut(usize, &Path), -{ - run_curate_qm_bars_1m_to_dir_with_cleanup_hook( - args, - intraday, - make_sink, - before_link, - |path| fs::remove_file(path), - ) -} - -/// Runs the bounded-memory file-to-file `qmIntraday` -> `bars_1m` curation pipeline, publishing -/// exactly `args.shard_count` QuestDB ILP v2 files (`/bars_1m_qm.shard-.ilp`). -pub fn run_curate_qm_bars_1m( - args: &CurateQmBars1mArgs, -) -> Result { - validate_file_mode_args(args)?; - - let intraday_file = - File::open(&args.intraday_path).map_err(|source| RunCurateQmBars1mError::OpenInput { - label: "qm-intraday", - path: args.intraday_path.clone(), - source, - })?; - - run_curate_qm_bars_1m_to_dir_with_hooks( - args, - intraday_file, - |_shard_idx, file| SyncedBufFile::new(file), - |_shard_idx, _final_path| {}, - ) -} - -/// Formats [`CurateQmBars1mRunReport`] into a deterministic machine-readable `key=value` summary. -/// -/// Only the final `timing:` line contains wall-clock time (`elapsed_secs`). -pub fn format_curate_qm_bars_1m_report(report: &CurateQmBars1mRunReport) -> String { - let per_shard = if report.ilp_stats.per_shard_rows.is_empty() { - "none".to_string() - } else { - report - .ilp_stats - .per_shard_rows - .iter() - .enumerate() - .map(|(idx, count)| format!("{idx:02}={count}")) - .collect::>() - .join(",") - }; - - let b = &report.curate_stats.builder; - let c = &report.curate_stats; - let d = &report.intraday_decode; - - format!( - "curate-etl curate-qm-bars-1m\n\ - \x20 intraday_bson: docs_framed={} bytes_read={} docs_seen={} rows_decoded={} rejected={} (missing={} empty={} wrong_type={} invalid_ts={} invalid_num={} corrupt={})\n\ - \x20 chunking: chunks={} max_rows_per_chunk={} cross_chunk_dedup=questdb_dedup_upsert_keys(ts,listing_id)\n\ - \x20 builder: bars_in={} rows_out={} keys_out_per_chunk_sum={} pre={} rth={} post={} invalid_ohlc={} inconsistent_ohlc={} invalid_vol={} ts_out_of_range={} dup_collapsed={} dup_conflict_dropped={}\n\ - \x20 curate: rows_in={} rows_out={} listings_out_per_chunk_sum={} pre={} rth={} post={} dropped_unmapped={} listing_collision_collapsed={} listing_collision_dropped={}\n\ - \x20 ilp: shards={} rows_written={} ilp_rows={} bytes={} flushes={} per_shard_rows={per_shard}\n\ - \x20 timing: elapsed_secs={:.6}", - report.intraday_docs_framed, - report.intraday_bytes_read, - d.docs_seen, - d.rows_decoded, - d.rejected_total(), - d.rejected_missing_field, - d.rejected_empty_field, - d.rejected_wrong_type, - d.rejected_invalid_timestamp, - d.rejected_invalid_number, - d.rejected_corrupt_document, - report.chunks, - report.max_rows_per_chunk, - b.bars_in, - b.rows_out, - b.keys_out, - b.pre_rows_out, - b.rth_rows_out, - b.post_rows_out, - b.dropped_invalid_ohlc, - b.dropped_inconsistent_ohlc, - b.dropped_invalid_volume, - b.dropped_ts_out_of_range, - b.duplicate_collapsed, - b.duplicate_conflict_dropped, - c.rows_in, - c.rows_out, - c.listings_out, - c.pre_rows_out, - c.rth_rows_out, - c.post_rows_out, - c.dropped_unmapped, - c.listing_collision_collapsed, - c.listing_collision_dropped, - report.shard_count, - report.rows_written, - report.ilp_stats.rows, - report.ilp_stats.bytes, - report.ilp_stats.flushes, - report.elapsed_secs, - ) -} - -#[cfg(test)] -#[path = "run_curate_qm_bars_1m_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/run_curate_qm_bars_1m_tests.rs b/tools/curate-etl/src/run_curate_qm_bars_1m_tests.rs deleted file mode 100644 index 39245692..00000000 --- a/tools/curate-etl/src/run_curate_qm_bars_1m_tests.rs +++ /dev/null @@ -1,1746 +0,0 @@ -use std::error::Error; -use std::fs; -use std::io::{self, Cursor, Read, Write}; -use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::{Arc, Mutex}; - -use bson::raw::{cstr, RawDocumentBuf}; -use bson::DateTime as BsonDateTime; - -use super::*; -use crate::bars_1m::{IntradaySession, BARS_1M_SOURCE_QM}; -use crate::bson_stream::MIN_BSON_DOC_BYTES; -use crate::ilp::{shard_for_listing_id, ILP_V2_DOUBLE_TYPE, TABLE_BARS_1M}; -use crate::run_curate_bars_1m::tests::TempDirGuard; -use crate::shorts::et_to_utc_micros; -use crate::split::ymd_to_epoch_days; - -fn day(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).expect("valid date") -} - -fn et_ts_millis(y: i32, m: u32, d: u32, hour: u8, minute: u8) -> i64 { - let micros = et_to_utc_micros(day(y, m, d), hour, minute, 0).expect("valid ET timestamp"); - assert_eq!(micros % 1_000, 0); - micros / 1_000 -} - -fn make_qm_intraday_doc( - code: &str, - timestamp_ms: i64, - open: f64, - high: f64, - low: f64, - close: f64, - sharevolume: f64, -) -> RawDocumentBuf { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), code); - doc.append(cstr!("timestamp"), BsonDateTime::from_millis(timestamp_ms)); - doc.append(cstr!("open"), open); - doc.append(cstr!("high"), high); - doc.append(cstr!("low"), low); - doc.append(cstr!("close"), close); - doc.append(cstr!("sharevolume"), sharevolume); - doc -} - -/// Builds a `qmIntraday` document that also carries distinct split-adjusted fields -/// (`adjustedopen..adjustedclose`, `avolume`) to prove the runner ignores them and preserves raw -/// OHLCV bit-identically. -#[allow(clippy::too_many_arguments)] -fn make_qm_intraday_doc_with_adjusted( - code: &str, - timestamp_ms: i64, - open: f64, - high: f64, - low: f64, - close: f64, - sharevolume: f64, - adj_scale: f64, -) -> RawDocumentBuf { - let mut doc = make_qm_intraday_doc(code, timestamp_ms, open, high, low, close, sharevolume); - doc.append(cstr!("adjustedopen"), open / adj_scale); - doc.append(cstr!("adjustedhigh"), high / adj_scale); - doc.append(cstr!("adjustedlow"), low / adj_scale); - doc.append(cstr!("adjustedclose"), close / adj_scale); - doc.append(cstr!("avolume"), sharevolume * adj_scale); - doc -} - -fn make_malformed_missing_open_doc(code: &str, timestamp_ms: i64) -> RawDocumentBuf { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), code); - doc.append(cstr!("timestamp"), BsonDateTime::from_millis(timestamp_ms)); - doc.append(cstr!("high"), 102.0_f64); - doc.append(cstr!("low"), 99.0_f64); - doc.append(cstr!("close"), 101.0_f64); - doc.append(cstr!("sharevolume"), 500.0_f64); - doc -} - -fn concat_docs(docs: &[RawDocumentBuf]) -> Vec { - let mut out = Vec::new(); - for doc in docs { - out.extend_from_slice(doc.as_bytes()); - } - out -} - -fn write_mapping_tsv(dir: &Path, lines: &[&str]) -> PathBuf { - let path = dir.join("provider_mapping.tsv"); - let mut body = lines.join("\n"); - if !body.is_empty() { - body.push('\n'); - } - fs::write(&path, body).expect("write provider_mapping.tsv"); - path -} - -fn list_dir_names(dir: &Path) -> Vec { - if !dir.exists() { - return Vec::new(); - } - let mut names: Vec = fs::read_dir(dir) - .expect("read_dir") - .map(|entry| { - entry - .expect("dir entry") - .file_name() - .to_string_lossy() - .into_owned() - }) - .collect(); - names.sort(); - names -} - -fn make_args( - intraday_path: PathBuf, - provider_mapping_path: PathBuf, - out_dir: PathBuf, - mapping_source: &str, - shard_count: usize, - known_at_micros: i64, - stream_options: BsonStreamOptions, -) -> CurateQmBars1mArgs { - CurateQmBars1mArgs { - intraday_path, - provider_mapping_path, - out_dir, - mapping_source: mapping_source.to_string(), - shard_count, - known_at_micros, - stream_options, - ilp_options: IlpWriterOptions::default(), - } -} - -#[derive(Debug, Clone, PartialEq)] -struct DecodedIlpBar1m { - listing_id: i32, - session: IntradaySession, - source: String, - open: f64, - high: f64, - low: f64, - close: f64, - volume: f64, - known_at: i64, - ts: i64, -} - -impl DecodedIlpBar1m { - fn sort_key(&self) -> (i32, i64, u64, u64, u64, u64, u64, i64) { - ( - self.listing_id, - self.ts, - self.open.to_bits(), - self.high.to_bits(), - self.low.to_bits(), - self.close.to_bits(), - self.volume.to_bits(), - self.known_at, - ) - } -} - -/// Decodes QuestDB ILP v2 `bars_1m` records respecting fixed-width 8-byte binary `DOUBLE` -/// payloads (`==\x10<8 LE bytes>`) so embedded `0x0a` bytes inside doubles never split rows. -fn decode_ilp_bars_1m(data: &[u8]) -> Vec { - let mut rows = Vec::new(); - let mut i = 0usize; - let len = data.len(); - - while i < len { - let tag_start = i; - while i < len { - match data[i] { - b'\\' => { - assert!(i + 1 < len, "dangling backslash in ILP tag set"); - i += 2; - } - b' ' => break, - _ => i += 1, - } - } - assert!( - i < len && data[i] == b' ', - "missing space after ILP tag set" - ); - let tag_str = std::str::from_utf8(&data[tag_start..i]).expect("valid UTF-8 tag set"); - i += 1; - - let mut tags = tag_str.split(','); - assert_eq!(tags.next(), Some(TABLE_BARS_1M), "expected bars_1m table"); - let listing_tag = tags.next().expect("listing_id tag"); - let session_tag = tags.next().expect("session tag"); - let source_tag = tags.next().expect("source tag"); - assert!(tags.next().is_none(), "unexpected extra ILP tag"); - - let listing_id: i32 = listing_tag - .strip_prefix("listing_id=") - .expect("listing_id= prefix") - .parse() - .expect("i32 listing_id"); - let session = match session_tag - .strip_prefix("session=") - .expect("session= prefix") - { - "PRE" => IntradaySession::Pre, - "RTH" => IntradaySession::Rth, - "POST" => IntradaySession::Post, - other => panic!("unexpected session '{other}'"), - }; - let source = source_tag - .strip_prefix("source=") - .expect("source= prefix") - .to_string(); - - let read_bin_f64 = |pos: &mut usize, name: &str| -> f64 { - let prefix = format!("{name}=="); - assert!( - data[*pos..].starts_with(prefix.as_bytes()), - "expected field prefix '{prefix}' at offset {}", - *pos - ); - *pos += prefix.len(); - assert_eq!( - data[*pos], ILP_V2_DOUBLE_TYPE, - "expected binary DOUBLE type tag for '{name}'" - ); - *pos += 1; - let bytes: [u8; 8] = data[*pos..*pos + 8] - .try_into() - .expect("8 bytes for binary double"); - *pos += 8; - f64::from_le_bytes(bytes) - }; - - let open = read_bin_f64(&mut i, "open"); - assert_eq!(data[i], b','); - i += 1; - let high = read_bin_f64(&mut i, "high"); - assert_eq!(data[i], b','); - i += 1; - let low = read_bin_f64(&mut i, "low"); - assert_eq!(data[i], b','); - i += 1; - let close = read_bin_f64(&mut i, "close"); - assert_eq!(data[i], b','); - i += 1; - let volume = read_bin_f64(&mut i, "volume"); - assert_eq!(data[i], b','); - i += 1; - - let ka_prefix = b"known_at="; - assert!( - data[i..].starts_with(ka_prefix), - "expected known_at= at offset {i}" - ); - i += ka_prefix.len(); - let ka_start = i; - while i < len && data[i] != b' ' { - i += 1; - } - assert!(i < len && data[i] == b' ', "missing space after known_at"); - let ka_str = std::str::from_utf8(&data[ka_start..i]).expect("valid UTF-8 known_at"); - let known_at: i64 = ka_str - .strip_suffix('t') - .expect("known_at trailing t") - .parse() - .expect("i64 known_at"); - i += 1; - - let ts_start = i; - while i < len && data[i] != b'\n' { - i += 1; - } - assert!(i < len && data[i] == b'\n', "missing trailing LF"); - let ts_str = std::str::from_utf8(&data[ts_start..i]).expect("valid UTF-8 ts"); - let ts: i64 = ts_str - .strip_suffix('t') - .expect("ts trailing t") - .parse() - .expect("i64 ts"); - i += 1; - - rows.push(DecodedIlpBar1m { - listing_id, - session, - source, - open, - high, - low, - close, - volume, - known_at, - ts, - }); - } - - rows -} - -fn assert_report_conservation(report: &CurateQmBars1mRunReport) { - let d = &report.intraday_decode; - assert_eq!( - report.intraday_docs_framed as usize, d.docs_seen, - "docs_framed != docs_seen" - ); - assert_eq!( - d.docs_seen, - d.rows_decoded + d.rejected_total(), - "decode conservation failed: {d:?}" - ); - - let c = &report.curate_stats; - let b = &c.builder; - assert_eq!(d.rows_decoded, b.bars_in, "rows_decoded != builder.bars_in"); - assert_eq!(c.rows_in, b.rows_out, "curate.rows_in != builder.rows_out"); - assert_eq!( - c.rows_in, - c.rows_out - + c.dropped_unmapped - + c.listing_collision_collapsed - + c.listing_collision_dropped, - "curate_stats conservation failed: {c:?}" - ); - assert_eq!( - c.pre_rows_out + c.rth_rows_out + c.post_rows_out, - c.rows_out, - "session breakdown != rows_out" - ); - assert_eq!(report.rows_written, c.rows_out, "rows_written != rows_out"); - assert_eq!( - report.rows_written, report.ilp_stats.rows, - "rows_written != ilp_stats.rows" - ); - assert_eq!( - report.ilp_stats.per_shard_rows.iter().sum::(), - report.ilp_stats.rows, - "sum(per_shard_rows) != ilp_stats.rows" - ); - assert_eq!(report.ilp_stats.per_shard_rows.len(), report.shard_count); -} - -#[derive(Clone)] -struct RecordingSink { - bytes: Arc>>, - flushes: Arc, -} - -impl RecordingSink { - fn new() -> Self { - Self { - bytes: Arc::new(Mutex::new(Vec::new())), - flushes: Arc::new(AtomicUsize::new(0)), - } - } -} - -impl Write for RecordingSink { - fn write(&mut self, buf: &[u8]) -> io::Result { - self.bytes.lock().unwrap().extend_from_slice(buf); - Ok(buf.len()) - } - - fn flush(&mut self) -> io::Result<()> { - self.flushes.fetch_add(1, Ordering::SeqCst); - Ok(()) - } -} - -struct FailingWriteSink { - fail_on_write: bool, - fail_on_flush: bool, -} - -impl Write for FailingWriteSink { - fn write(&mut self, buf: &[u8]) -> io::Result { - if self.fail_on_write { - Err(io::Error::new( - io::ErrorKind::BrokenPipe, - "injected write failure", - )) - } else { - Ok(buf.len()) - } - } - - fn flush(&mut self) -> io::Result<()> { - if self.fail_on_flush { - Err(io::Error::new( - io::ErrorKind::BrokenPipe, - "injected flush failure", - )) - } else { - Ok(()) - } - } -} - -struct PanicReader; - -impl Read for PanicReader { - fn read(&mut self, _buf: &mut [u8]) -> io::Result { - panic!("reader must not be called when validation fails"); - } -} - -struct PrefixThenIoErrorReader { - prefix: Vec, - pos: usize, - failed: bool, -} - -impl PrefixThenIoErrorReader { - fn new(prefix: Vec) -> Self { - Self { - prefix, - pos: 0, - failed: false, - } - } -} - -impl Read for PrefixThenIoErrorReader { - fn read(&mut self, buf: &mut [u8]) -> io::Result { - if self.pos < self.prefix.len() { - let n = (self.prefix.len() - self.pos).min(buf.len()); - buf[..n].copy_from_slice(&self.prefix[self.pos..self.pos + n]); - self.pos += n; - return Ok(n); - } - if !self.failed { - self.failed = true; - return Err(io::Error::new( - io::ErrorKind::ConnectionReset, - "injected reader failure after prefix", - )); - } - Ok(0) - } -} - -#[test] -fn happy_path_file_mode_decodes_bit_identical_raw_ohlcv_date_boundary_and_deterministic_replay() { - let dir = TempDirGuard::new("qm-bars1m-happy"); - - // Date-effective mapping boundary for QM code "REUSE": - // 2024-06-01..=2024-06-10 -> listing 101 - // 2024-06-11.. -> listing 202 - // Plus a second symbol "AAPL" -> listing 303. - let mapping_path = write_mapping_tsv( - dir.path(), - &[ - "qm\tREUSE\t2024-06-01\t2024-06-10\t101", - "qm\tREUSE\t2024-06-11\t\t202", - "qm\tAAPL\t2024-01-01\t\t303", - ], - ); - - // Choose a raw close whose LE IEEE-754 bytes include 0x0a to prove binary ILP decoding does - // not split on embedded newlines. - let raw_close_with_lf = f64::from_le_bytes([0x0a, 0x11, 0x22, 0x33, 0x44, 0x55, 0x59, 0x40]); - assert!( - raw_close_with_lf.is_finite() && raw_close_with_lf > 100.0 && raw_close_with_lf < 102.0 - ); - - let ts_pre = et_ts_millis(2024, 6, 10, 8, 15); - let ts_rth_old = et_ts_millis(2024, 6, 10, 10, 30); - let ts_rth_new = et_ts_millis(2024, 6, 11, 9, 30); - let ts_post = et_ts_millis(2024, 6, 11, 17, 5); - let known_at_micros = et_to_utc_micros(day(2024, 6, 12), 18, 0, 0).unwrap(); - - // Include distinct adjusted fields (scale 10.0) to verify raw fields pass through bit-identical - // with no split un-adjustment, and include -0.0 sharevolume to verify +0.0 normalization. - let docs = vec![ - make_qm_intraday_doc_with_adjusted( - "REUSE", - ts_rth_old, - 100.125, - 102.5, - 99.75, - raw_close_with_lf, - 12_345.0, - 10.0, - ), - make_qm_intraday_doc_with_adjusted("REUSE", ts_pre, 99.5, 100.0, 99.0, 99.8, -0.0, 10.0), - make_qm_intraday_doc_with_adjusted( - "REUSE", ts_rth_new, 15.25, 15.75, 15.0, 15.5, 8_000.0, 4.0, - ), - make_qm_intraday_doc_with_adjusted( - "AAPL", ts_post, 210.0, 211.25, 209.5, 210.75, 4_200.0, 2.0, - ), - ]; - let intraday_bytes = concat_docs(&docs); - let intraday_path = dir.path().join("qmIntraday.bson"); - fs::write(&intraday_path, &intraday_bytes).unwrap(); - - let shard_count = 4; - let out_dir_1 = dir.path().join("out-1"); - let args_1 = make_args( - intraday_path.clone(), - mapping_path.clone(), - out_dir_1.clone(), - DEFAULT_QM_BARS_1M_MAPPING_SOURCE, - shard_count, - known_at_micros, - BsonStreamOptions::default(), - ); - - let report_1 = run_curate_qm_bars_1m(&args_1).expect("happy-path run should succeed"); - assert_report_conservation(&report_1); - assert_eq!(report_1.intraday_docs_framed, 4); - assert_eq!(report_1.intraday_bytes_read, intraday_bytes.len() as u64); - assert_eq!(report_1.chunks, 1); - assert_eq!(report_1.max_rows_per_chunk, 4); - assert_eq!(report_1.rows_written, 4); - - // Output directory contains exactly bars_1m_qm.shard-00..03.ilp and no staging .tmp files. - assert_eq!( - list_dir_names(&out_dir_1), - vec![ - "bars_1m_qm.shard-00.ilp", - "bars_1m_qm.shard-01.ilp", - "bars_1m_qm.shard-02.ilp", - "bars_1m_qm.shard-03.ilp", - ] - ); - - // Decode every shard and assert shard routing, table, source, timestamps, known_at, and raw OHLCV bits. - let mut decoded_all = Vec::new(); - for shard_idx in 0..shard_count { - let path = out_dir_1.join(format!("bars_1m_qm.shard-{shard_idx:02}.ilp")); - let bytes = fs::read(&path).expect("read shard file"); - let shard_rows = decode_ilp_bars_1m(&bytes); - assert_eq!( - shard_rows.len(), - report_1.ilp_stats.per_shard_rows[shard_idx] - ); - for row in &shard_rows { - assert_eq!(row.source, BARS_1M_SOURCE_QM); - assert_eq!(row.known_at, known_at_micros); - assert_eq!(shard_for_listing_id(row.listing_id, shard_count), shard_idx); - } - decoded_all.extend(shard_rows); - } - decoded_all.sort_by_key(DecodedIlpBar1m::sort_key); - - assert_eq!(decoded_all.len(), 4); - // Listing 101 PRE bar (2024-06-10, -0.0 volume normalized to +0.0) - assert_eq!(decoded_all[0].listing_id, 101); - assert_eq!(decoded_all[0].ts, ts_pre * 1_000); - assert_eq!(decoded_all[0].session, IntradaySession::Pre); - assert_eq!(decoded_all[0].open.to_bits(), 99.5_f64.to_bits()); - assert_eq!(decoded_all[0].high.to_bits(), 100.0_f64.to_bits()); - assert_eq!(decoded_all[0].low.to_bits(), 99.0_f64.to_bits()); - assert_eq!(decoded_all[0].close.to_bits(), 99.8_f64.to_bits()); - assert_eq!(decoded_all[0].volume.to_bits(), 0.0_f64.to_bits()); - - // Listing 101 RTH bar (2024-06-10, raw close with embedded 0x0a byte) - assert_eq!(decoded_all[1].listing_id, 101); - assert_eq!(decoded_all[1].ts, ts_rth_old * 1_000); - assert_eq!(decoded_all[1].session, IntradaySession::Rth); - assert_eq!(decoded_all[1].open.to_bits(), 100.125_f64.to_bits()); - assert_eq!(decoded_all[1].high.to_bits(), 102.5_f64.to_bits()); - assert_eq!(decoded_all[1].low.to_bits(), 99.75_f64.to_bits()); - assert_eq!(decoded_all[1].close.to_bits(), raw_close_with_lf.to_bits()); - assert_eq!(decoded_all[1].volume.to_bits(), 12_345.0_f64.to_bits()); - - // Listing 202 RTH bar (2024-06-11, after mapping boundary) - assert_eq!(decoded_all[2].listing_id, 202); - assert_eq!(decoded_all[2].ts, ts_rth_new * 1_000); - assert_eq!(decoded_all[2].session, IntradaySession::Rth); - assert_eq!(decoded_all[2].open.to_bits(), 15.25_f64.to_bits()); - assert_eq!(decoded_all[2].high.to_bits(), 15.75_f64.to_bits()); - assert_eq!(decoded_all[2].low.to_bits(), 15.0_f64.to_bits()); - assert_eq!(decoded_all[2].close.to_bits(), 15.5_f64.to_bits()); - assert_eq!(decoded_all[2].volume.to_bits(), 8_000.0_f64.to_bits()); - - // Listing 303 POST bar - assert_eq!(decoded_all[3].listing_id, 303); - assert_eq!(decoded_all[3].ts, ts_post * 1_000); - assert_eq!(decoded_all[3].session, IntradaySession::Post); - assert_eq!(decoded_all[3].open.to_bits(), 210.0_f64.to_bits()); - assert_eq!(decoded_all[3].high.to_bits(), 211.25_f64.to_bits()); - assert_eq!(decoded_all[3].low.to_bits(), 209.5_f64.to_bits()); - assert_eq!(decoded_all[3].close.to_bits(), 210.75_f64.to_bits()); - assert_eq!(decoded_all[3].volume.to_bits(), 4_200.0_f64.to_bits()); - - // Compare against pure single-chunk baseline `curate_and_write_qm_bars_1m`. - let mapping = load_provider_mapping_table(&mapping_path).unwrap(); - let baseline_sinks: Vec> = (0..shard_count).map(|_| Vec::new()).collect(); - let mut baseline_writer = - IlpShardedWriter::new(baseline_sinks, IlpWriterOptions::default()).unwrap(); - let mut baseline_bars = Vec::new(); - decode_qm_intraday_buffer( - &intraday_bytes, - |raw| baseline_bars.push(raw.into_eod_intraday_bar(|k, _| k)), - |_, _| {}, - ); - curate_and_write_qm_bars_1m( - baseline_bars, - &mapping, - DEFAULT_QM_BARS_1M_MAPPING_SOURCE, - &mut baseline_writer, - known_at_micros, - ) - .unwrap(); - let baseline_stats = baseline_writer.finish().unwrap(); - assert_eq!(report_1.ilp_stats, baseline_stats); - - // Deterministic replay: identical settings into a second out_dir yield byte-identical shards - // and identical report fields (excluding elapsed_secs). - let out_dir_2 = dir.path().join("out-2"); - let args_2 = make_args( - intraday_path, - mapping_path, - out_dir_2.clone(), - DEFAULT_QM_BARS_1M_MAPPING_SOURCE, - shard_count, - known_at_micros, - BsonStreamOptions::default(), - ); - let report_2 = run_curate_qm_bars_1m(&args_2).expect("replay run should succeed"); - for shard_idx in 0..shard_count { - let b1 = fs::read(out_dir_1.join(format!("bars_1m_qm.shard-{shard_idx:02}.ilp"))).unwrap(); - let b2 = fs::read(out_dir_2.join(format!("bars_1m_qm.shard-{shard_idx:02}.ilp"))).unwrap(); - assert_eq!(b1, b2, "shard {shard_idx} bytes differed across replay"); - } - let mut r1 = report_1; - let mut r2 = report_2; - r1.elapsed_secs = 0.0; - r2.elapsed_secs = 0.0; - assert_eq!(r1, r2); -} - -#[test] -fn bounded_chunk_streaming_matches_single_chunk_and_calls_finish_flush_once_per_shard() { - let dir = TempDirGuard::new("qm-bars1m-chunked"); - let mapping_path = write_mapping_tsv( - dir.path(), - &["qm\tAAA\t2024-01-01\t\t11", "qm\tBBB\t2024-01-01\t\t22"], - ); - - let known_at_micros = et_to_utc_micros(day(2024, 7, 2), 18, 0, 0).unwrap(); - let mut docs = Vec::new(); - for minute in 0..12u8 { - let code = if minute % 2 == 0 { "AAA" } else { "BBB" }; - let base = 50.0 + f64::from(minute); - docs.push(make_qm_intraday_doc( - code, - et_ts_millis(2024, 7, 1, 9, 30 + minute), - base, - base + 0.5, - base - 0.25, - base + 0.25, - 100.0 + f64::from(minute), - )); - } - let single_doc_len = docs[0].as_bytes().len(); - let intraday_bytes = concat_docs(&docs); - - // Use 4 shards so at least 2 shards are empty (only 2 listings), verifying finish() flushes - // empty shards once too. - let shard_count = 4; - - let run_with_capacity = |chunk_capacity_bytes: usize| { - let sinks: Vec = (0..shard_count).map(|_| RecordingSink::new()).collect(); - let sinks_ref = sinks.clone(); - let args = make_args( - dir.path().join("in-memory.bson"), - mapping_path.clone(), - dir.path().join("unused-out"), - DEFAULT_QM_BARS_1M_MAPPING_SOURCE, - shard_count, - known_at_micros, - BsonStreamOptions { - chunk_capacity_bytes, - max_doc_bytes: 1024 * 1024, - }, - ); - let report = run_curate_qm_bars_1m_with_readers( - &args, - Cursor::new(intraday_bytes.as_slice()), - |shard_idx| sinks_ref[shard_idx].clone(), - ) - .expect("stream run should succeed"); - assert_report_conservation(&report); - - let mut rows = Vec::new(); - for (idx, sink) in sinks.iter().enumerate() { - assert_eq!( - sink.flushes.load(Ordering::SeqCst), - 1, - "shard {idx} must observe exactly one finish() flush" - ); - rows.extend(decode_ilp_bars_1m(&sink.bytes.lock().unwrap())); - } - rows.sort_by_key(DecodedIlpBar1m::sort_key); - (report, rows) - }; - - let (single_report, single_rows) = run_with_capacity(64 * 1024); - let (tiny_report, tiny_rows) = run_with_capacity(single_doc_len * 2 + 4); - - assert_eq!(single_report.chunks, 1); - assert_eq!(single_report.max_rows_per_chunk, 12); - assert!( - tiny_report.chunks > 1, - "expected multiple chunks, got {}", - tiny_report.chunks - ); - assert!( - tiny_report.max_rows_per_chunk < single_report.max_rows_per_chunk, - "expected lower high-water mark: tiny={} vs single={}", - tiny_report.max_rows_per_chunk, - single_report.max_rows_per_chunk - ); - assert_eq!(single_rows, tiny_rows); - assert_eq!(single_report.rows_written, tiny_report.rows_written); - assert_eq!(single_report.ilp_stats.rows, tiny_report.ilp_stats.rows); - assert_eq!( - single_report.ilp_stats.per_shard_rows, - tiny_report.ilp_stats.per_shard_rows - ); -} - -#[test] -fn conservation_counts_unmapped_semantic_decode_errors_collisions_and_cross_chunk_duplicates() { - let dir = TempDirGuard::new("qm-bars1m-conservation"); - // ALIAS_A and ALIAS_B both map to listing 500 to test identical collapse and conflict drop. - let mapping_path = write_mapping_tsv( - dir.path(), - &[ - "qm\tALIAS_A\t2024-01-01\t\t500", - "qm\tALIAS_B\t2024-01-01\t\t500", - ], - ); - - let known_at_micros = et_to_utc_micros(day(2024, 8, 2), 18, 0, 0).unwrap(); - let ts_pre = et_ts_millis(2024, 8, 1, 8, 0); - let ts_rth_same = et_ts_millis(2024, 8, 1, 10, 0); - let ts_rth_conflict = et_ts_millis(2024, 8, 1, 10, 1); - let ts_post = et_ts_millis(2024, 8, 1, 16, 30); - let ts_bad_ohlc = et_ts_millis(2024, 8, 1, 10, 2); - - let docs = vec![ - // 1. Valid PRE bar - make_qm_intraday_doc("ALIAS_A", ts_pre, 10.0, 10.5, 9.8, 10.2, 100.0), - // 2. Semantically invalid BSON doc (missing `open`) -> counted and skipped - make_malformed_missing_open_doc("ALIAS_A", ts_pre + 60_000), - // 3. Unmapped qmSearchCode -> dropped_unmapped - make_qm_intraday_doc("UNKNOWN_CODE", ts_rth_same, 20.0, 21.0, 19.5, 20.5, 50.0), - // 4 & 5. Identical alias collision -> 1 row emitted, 1 listing_collision_collapsed - make_qm_intraday_doc("ALIAS_A", ts_rth_same, 11.0, 11.5, 10.8, 11.2, 200.0), - make_qm_intraday_doc("ALIAS_B", ts_rth_same, 11.0, 11.5, 10.8, 11.2, 200.0), - // 6 & 7. Conflicting alias collision -> both dropped (2 listing_collision_dropped) - make_qm_intraday_doc("ALIAS_A", ts_rth_conflict, 12.0, 12.5, 11.8, 12.2, 300.0), - make_qm_intraday_doc("ALIAS_B", ts_rth_conflict, 12.0, 12.6, 11.8, 12.2, 300.0), - // 8. Builder-inconsistent OHLC (high < low) -> dropped_inconsistent_ohlc - make_qm_intraday_doc("ALIAS_A", ts_bad_ohlc, 10.0, 9.0, 11.0, 10.0, 10.0), - // 9. Valid POST bar - make_qm_intraday_doc("ALIAS_A", ts_post, 13.0, 13.4, 12.9, 13.1, 400.0), - ]; - let intraday_bytes = concat_docs(&docs); - let args = make_args( - dir.path().join("conservation.bson"), - mapping_path.clone(), - dir.path().join("unused-out"), - DEFAULT_QM_BARS_1M_MAPPING_SOURCE, - 2, - known_at_micros, - BsonStreamOptions::default(), - ); - - let report = run_curate_qm_bars_1m_with_readers( - &args, - Cursor::new(intraday_bytes.as_slice()), - |_shard_idx| Vec::::new(), - ) - .expect("conservation run should succeed"); - assert_report_conservation(&report); - - assert_eq!(report.intraday_docs_framed, 9); - assert_eq!(report.intraday_decode.docs_seen, 9); - assert_eq!(report.intraday_decode.rows_decoded, 8); - assert_eq!(report.intraday_decode.rejected_missing_field, 1); - assert_eq!(report.curate_stats.builder.bars_in, 8); - assert_eq!(report.curate_stats.builder.dropped_inconsistent_ohlc, 1); - assert_eq!(report.curate_stats.rows_in, 7); - assert_eq!(report.curate_stats.dropped_unmapped, 1); - assert_eq!(report.curate_stats.listing_collision_collapsed, 1); - assert_eq!(report.curate_stats.listing_collision_dropped, 2); - assert_eq!(report.curate_stats.rows_out, 3); - assert_eq!(report.curate_stats.pre_rows_out, 1); - assert_eq!(report.curate_stats.rth_rows_out, 1); - assert_eq!(report.curate_stats.post_rows_out, 1); - assert_eq!(report.rows_written, 3); - - // Cross-chunk duplicate semantics: the same (listing_id, ts) in two separate chunks emits both - // rows (relying on QuestDB DEDUP UPSERT KEYS(ts, listing_id)) and sums listings_out/keys_out. - let dup_doc = make_qm_intraday_doc("ALIAS_A", ts_rth_same, 11.0, 11.5, 10.8, 11.2, 200.0); - let doc_len = dup_doc.as_bytes().len(); - let cross_chunk_bytes = concat_docs(&[dup_doc.clone(), dup_doc]); - let sinks = vec![RecordingSink::new()]; - let sinks_ref = sinks.clone(); - let cross_args = make_args( - dir.path().join("cross-chunk.bson"), - mapping_path, - dir.path().join("unused-out-2"), - DEFAULT_QM_BARS_1M_MAPPING_SOURCE, - 1, - known_at_micros, - BsonStreamOptions { - chunk_capacity_bytes: doc_len, - max_doc_bytes: 1024 * 1024, - }, - ); - let cross_report = run_curate_qm_bars_1m_with_readers( - &cross_args, - Cursor::new(cross_chunk_bytes.as_slice()), - |idx| sinks_ref[idx].clone(), - ) - .expect("cross-chunk duplicate run should succeed"); - assert_report_conservation(&cross_report); - assert_eq!(cross_report.chunks, 2); - assert_eq!(cross_report.rows_written, 2); - assert_eq!(cross_report.curate_stats.listings_out, 2); - assert_eq!(cross_report.curate_stats.builder.keys_out, 2); - let emitted = decode_ilp_bars_1m(&sinks[0].bytes.lock().unwrap()); - assert_eq!(emitted.len(), 2); - assert_eq!(emitted[0], emitted[1]); -} - -#[test] -fn blank_mapping_source_rejected_before_opening_inputs_or_creating_out_dir_and_custom_namespace_works( -) { - let dir = TempDirGuard::new("qm-bars1m-source"); - let known_at_micros = et_to_utc_micros(day(2024, 6, 12), 18, 0, 0).unwrap(); - - for blank in ["", " ", "\t\n "] { - let out_dir = dir.path().join(format!("should-not-exist-{}", blank.len())); - let args = make_args( - dir.path().join("nonexistent-intraday.bson"), - dir.path().join("nonexistent-mapping.tsv"), - out_dir.clone(), - blank, - 2, - known_at_micros, - BsonStreamOptions::default(), - ); - - let file_err = run_curate_qm_bars_1m(&args).expect_err("blank source must fail file mode"); - assert!( - matches!(file_err, RunCurateQmBars1mError::EmptyMappingSource), - "expected EmptyMappingSource, got {file_err:?}" - ); - assert!( - !out_dir.exists(), - "out_dir must not be created on blank mapping_source" - ); - - let reader_err = - run_curate_qm_bars_1m_with_readers(&args, PanicReader, |_idx| -> Vec { - panic!("sink factory must not be called on blank mapping_source"); - }) - .expect_err("blank source must fail reader mode"); - assert!(matches!( - reader_err, - RunCurateQmBars1mError::EmptyMappingSource - )); - } - - // Custom nonblank namespace forwarded verbatim alongside "qm" in the same TSV. - let mapping_path = write_mapping_tsv( - dir.path(), - &[ - "qm\tSYM\t2024-01-01\t\t10", - "qm_custom\tSYM\t2024-01-01\t\t99", - ], - ); - let docs = vec![make_qm_intraday_doc( - "SYM", - et_ts_millis(2024, 6, 10, 10, 0), - 10.0, - 10.5, - 9.9, - 10.2, - 100.0, - )]; - let intraday_bytes = concat_docs(&docs); - let sinks = vec![RecordingSink::new()]; - let sinks_ref = sinks.clone(); - let custom_args = make_args( - dir.path().join("custom.bson"), - mapping_path, - dir.path().join("unused"), - "qm_custom", - 1, - known_at_micros, - BsonStreamOptions::default(), - ); - let report = run_curate_qm_bars_1m_with_readers( - &custom_args, - Cursor::new(intraday_bytes.as_slice()), - |idx| sinks_ref[idx].clone(), - ) - .expect("custom mapping_source should succeed"); - assert_report_conservation(&report); - let decoded = decode_ilp_bars_1m(&sinks[0].bytes.lock().unwrap()); - assert_eq!(decoded.len(), 1); - assert_eq!(decoded[0].listing_id, 99); -} - -#[test] -fn missing_inputs_and_invalid_options_fail_closed_without_creating_out_dir() { - let dir = TempDirGuard::new("qm-bars1m-missing"); - let known_at_micros = et_to_utc_micros(day(2024, 6, 12), 18, 0, 0).unwrap(); - let valid_mapping = write_mapping_tsv(dir.path(), &["qm\tAAA\t2024-01-01\t\t1"]); - let valid_bson = dir.path().join("valid.bson"); - fs::write(&valid_bson, b"").unwrap(); - - // Missing BSON input - let out_missing_bson = dir.path().join("out-missing-bson"); - let err = run_curate_qm_bars_1m(&make_args( - dir.path().join("does-not-exist.bson"), - valid_mapping.clone(), - out_missing_bson.clone(), - DEFAULT_QM_BARS_1M_MAPPING_SOURCE, - 2, - known_at_micros, - BsonStreamOptions::default(), - )) - .expect_err("missing BSON must fail"); - assert!(matches!( - err, - RunCurateQmBars1mError::OpenInput { - label: "qm-intraday", - .. - } - )); - assert!(err.source().is_some()); - assert!(!out_missing_bson.exists()); - - // Missing provider_mapping.tsv - let out_missing_map = dir.path().join("out-missing-map"); - let err = run_curate_qm_bars_1m(&make_args( - valid_bson.clone(), - dir.path().join("does-not-exist.tsv"), - out_missing_map.clone(), - DEFAULT_QM_BARS_1M_MAPPING_SOURCE, - 2, - known_at_micros, - BsonStreamOptions::default(), - )) - .expect_err("missing mapping must fail"); - assert!(matches!(err, RunCurateQmBars1mError::LoadReference(_))); - assert!(!out_missing_map.exists()); - - // Zero shard_count - let err = run_curate_qm_bars_1m(&make_args( - valid_bson.clone(), - valid_mapping.clone(), - dir.path().join("out-zero-shard"), - DEFAULT_QM_BARS_1M_MAPPING_SOURCE, - 0, - known_at_micros, - BsonStreamOptions::default(), - )) - .expect_err("zero shard_count must fail"); - assert!(matches!(err, RunCurateQmBars1mError::ZeroShardCount)); - - // Invalid stream_options - let err = run_curate_qm_bars_1m(&make_args( - valid_bson.clone(), - valid_mapping.clone(), - dir.path().join("out-bad-stream"), - DEFAULT_QM_BARS_1M_MAPPING_SOURCE, - 2, - known_at_micros, - BsonStreamOptions { - chunk_capacity_bytes: 0, - max_doc_bytes: MIN_BSON_DOC_BYTES, - }, - )) - .expect_err("zero chunk_capacity_bytes must fail"); - assert!(matches!(err, RunCurateQmBars1mError::BsonStream { .. })); - - // out_dir exists as a regular file - let file_as_dir = dir.path().join("not-a-dir"); - fs::write(&file_as_dir, b"file").unwrap(); - let err = run_curate_qm_bars_1m(&make_args( - valid_bson, - valid_mapping, - file_as_dir, - DEFAULT_QM_BARS_1M_MAPPING_SOURCE, - 2, - known_at_micros, - BsonStreamOptions::default(), - )) - .expect_err("file out_dir must fail"); - assert!(matches!(err, RunCurateQmBars1mError::InvalidOutDir { .. })); -} - -#[test] -fn preflight_rejects_high_numbered_qm_shard_and_allows_eod_bars_1m_shard_coexistence() { - let dir = TempDirGuard::new("qm-bars1m-preflight"); - let mapping_path = write_mapping_tsv(dir.path(), &["qm\tAAA\t2024-01-01\t\t7"]); - let known_at_micros = et_to_utc_micros(day(2024, 6, 12), 18, 0, 0).unwrap(); - let intraday_bytes = concat_docs(&[make_qm_intraday_doc( - "AAA", - et_ts_millis(2024, 6, 10, 10, 0), - 10.0, - 10.5, - 9.8, - 10.2, - 100.0, - )]); - let intraday_path = dir.path().join("qmIntraday.bson"); - fs::write(&intraday_path, &intraday_bytes).unwrap(); - - // (a) Pre-existing bars_1m_qm.shard-07.ilp (index >= requested shard_count=2) fails preflight - // and stays byte-identical. - let out_conflict = dir.path().join("out-conflict"); - fs::create_dir_all(&out_conflict).unwrap(); - let stale_qm_shard = out_conflict.join("bars_1m_qm.shard-07.ilp"); - let stale_bytes = b"pre-existing-stale-qm-shard\n"; - fs::write(&stale_qm_shard, stale_bytes).unwrap(); - - let err = run_curate_qm_bars_1m(&make_args( - intraday_path.clone(), - mapping_path.clone(), - out_conflict.clone(), - DEFAULT_QM_BARS_1M_MAPPING_SOURCE, - 2, - known_at_micros, - BsonStreamOptions::default(), - )) - .expect_err("pre-existing high-numbered QM shard must fail preflight"); - assert!(matches!( - err, - RunCurateQmBars1mError::OutputFileExists { ref path } if path == &stale_qm_shard - )); - assert_eq!(fs::read(&stale_qm_shard).unwrap(), stale_bytes); - assert_eq!( - list_dir_names(&out_conflict), - vec!["bars_1m_qm.shard-07.ilp"] - ); - - // (b) Pre-existing bars_1m.shard-00.ilp (EOD runner output) does NOT block the QM run and is - // left byte-identical. - let out_shared = dir.path().join("out-shared"); - fs::create_dir_all(&out_shared).unwrap(); - let eod_shard = out_shared.join("bars_1m.shard-00.ilp"); - let eod_bytes = b"pre-existing-eod-bars-1m-shard-bytes\n"; - fs::write(&eod_shard, eod_bytes).unwrap(); - - let report = run_curate_qm_bars_1m(&make_args( - intraday_path, - mapping_path, - out_shared.clone(), - DEFAULT_QM_BARS_1M_MAPPING_SOURCE, - 2, - known_at_micros, - BsonStreamOptions::default(), - )) - .expect("QM run should coexist with EOD bars_1m.shard-00.ilp"); - assert_report_conservation(&report); - assert_eq!(report.rows_written, 1); - assert_eq!(fs::read(&eod_shard).unwrap(), eod_bytes); - assert_eq!( - list_dir_names(&out_shared), - vec![ - "bars_1m.shard-00.ilp", - "bars_1m_qm.shard-00.ilp", - "bars_1m_qm.shard-01.ilp", - ] - ); -} - -#[test] -fn fatal_bson_framing_and_reader_io_errors_report_absolute_offset_and_leave_out_dir_clean() { - let dir = TempDirGuard::new("qm-bars1m-bson-errors"); - let mapping_path = write_mapping_tsv(dir.path(), &["qm\tAAA\t2024-01-01\t\t7"]); - let known_at_micros = et_to_utc_micros(day(2024, 6, 12), 18, 0, 0).unwrap(); - - let valid_prefix = make_qm_intraday_doc( - "AAA", - et_ts_millis(2024, 6, 10, 10, 0), - 10.0, - 10.5, - 9.8, - 10.2, - 100.0, - ); - let prefix_len = valid_prefix.as_bytes().len() as u64; - - // 1. Truncated document after valid prefix. - let mut truncated_bytes = valid_prefix.as_bytes().to_vec(); - truncated_bytes.extend_from_slice(&20_i32.to_le_bytes()); - truncated_bytes.extend_from_slice(&[0u8; 4]); - let trunc_path = dir.path().join("truncated.bson"); - fs::write(&trunc_path, &truncated_bytes).unwrap(); - let out_trunc = dir.path().join("out-trunc"); - let err = run_curate_qm_bars_1m(&make_args( - trunc_path, - mapping_path.clone(), - out_trunc.clone(), - DEFAULT_QM_BARS_1M_MAPPING_SOURCE, - 2, - known_at_micros, - BsonStreamOptions { - chunk_capacity_bytes: prefix_len as usize, - max_doc_bytes: 1024 * 1024, - }, - )) - .expect_err("truncated BSON must fail"); - assert!( - matches!( - err, - RunCurateQmBars1mError::BsonStream { - source: BsonStreamError::TruncatedDocument { offset, .. }, - .. - } if offset == prefix_len - ), - "expected TruncatedDocument at offset {prefix_len}, got {err:?}" - ); - assert!( - list_dir_names(&out_trunc).is_empty(), - "staging/final files leaked on truncated BSON: {:?}", - list_dir_names(&out_trunc) - ); - - // 2. Corrupt declared document length (< 5) after valid prefix. - let mut corrupt_bytes = valid_prefix.as_bytes().to_vec(); - corrupt_bytes.extend_from_slice(&3_i32.to_le_bytes()); - corrupt_bytes.push(0); - let corrupt_path = dir.path().join("corrupt.bson"); - fs::write(&corrupt_path, &corrupt_bytes).unwrap(); - let out_corrupt = dir.path().join("out-corrupt"); - let err = run_curate_qm_bars_1m(&make_args( - corrupt_path, - mapping_path.clone(), - out_corrupt.clone(), - DEFAULT_QM_BARS_1M_MAPPING_SOURCE, - 2, - known_at_micros, - BsonStreamOptions { - chunk_capacity_bytes: prefix_len as usize, - max_doc_bytes: 1024 * 1024, - }, - )) - .expect_err("corrupt document length must fail"); - assert!( - matches!( - err, - RunCurateQmBars1mError::BsonStream { - source: BsonStreamError::CorruptDocumentLength { offset, declared_len: 3, .. }, - .. - } if offset == prefix_len - ), - "expected CorruptDocumentLength at offset {prefix_len}, got {err:?}" - ); - assert!(list_dir_names(&out_corrupt).is_empty()); - - // 3. Reader I/O failure after valid prefix. - let out_io = dir.path().join("out-io"); - let err = run_curate_qm_bars_1m_to_dir_with_hooks( - &make_args( - dir.path().join("io-fail.bson"), - mapping_path, - out_io.clone(), - DEFAULT_QM_BARS_1M_MAPPING_SOURCE, - 2, - known_at_micros, - BsonStreamOptions { - chunk_capacity_bytes: prefix_len as usize, - max_doc_bytes: 1024 * 1024, - }, - ), - PrefixThenIoErrorReader::new(valid_prefix.as_bytes().to_vec()), - |_idx, file| SyncedBufFile::new(file), - |_idx, _path| {}, - ) - .expect_err("reader I/O error must fail"); - assert!( - matches!( - err, - RunCurateQmBars1mError::BsonStream { - source: BsonStreamError::Io { offset, .. }, - .. - } if offset == prefix_len - ), - "expected BsonStreamError::Io at offset {prefix_len}, got {err:?}" - ); - assert!(list_dir_names(&out_io).is_empty()); -} - -#[test] -fn injected_sink_write_flush_and_post_preflight_hard_link_collision_roll_back_cleanly() { - let dir = TempDirGuard::new("qm-bars1m-rollback"); - let mapping_path = write_mapping_tsv(dir.path(), &["qm\tAAA\t2024-01-01\t\t7"]); - let known_at_micros = et_to_utc_micros(day(2024, 6, 12), 18, 0, 0).unwrap(); - let intraday_bytes = concat_docs(&[make_qm_intraday_doc( - "AAA", - et_ts_millis(2024, 6, 10, 10, 0), - 10.0, - 10.5, - 9.8, - 10.2, - 100.0, - )]); - - // 1. Injected sink write failure (tiny batch triggers write during chunk curation). - let out_write_fail = dir.path().join("out-write-fail"); - let mut write_fail_args = make_args( - dir.path().join("in.bson"), - mapping_path.clone(), - out_write_fail.clone(), - DEFAULT_QM_BARS_1M_MAPPING_SOURCE, - 2, - known_at_micros, - BsonStreamOptions::default(), - ); - write_fail_args.ilp_options.max_batch_rows = 1; - let err = run_curate_qm_bars_1m_to_dir_with_hooks( - &write_fail_args, - Cursor::new(intraday_bytes.as_slice()), - |_idx, _file| FailingWriteSink { - fail_on_write: true, - fail_on_flush: false, - }, - |_idx, _path| {}, - ) - .expect_err("injected write failure must abort"); - assert!(matches!(err, RunCurateQmBars1mError::CurateWrite(_))); - assert!(list_dir_names(&out_write_fail).is_empty()); - - // 2. Injected final flush failure during IlpShardedWriter::finish(). - let out_flush_fail = dir.path().join("out-flush-fail"); - let flush_fail_args = make_args( - dir.path().join("in.bson"), - mapping_path.clone(), - out_flush_fail.clone(), - DEFAULT_QM_BARS_1M_MAPPING_SOURCE, - 2, - known_at_micros, - BsonStreamOptions::default(), - ); - let err = run_curate_qm_bars_1m_to_dir_with_hooks( - &flush_fail_args, - Cursor::new(intraday_bytes.as_slice()), - |_idx, _file| FailingWriteSink { - fail_on_write: false, - fail_on_flush: true, - }, - |_idx, _path| {}, - ) - .expect_err("injected flush failure must abort"); - assert!(matches!(err, RunCurateQmBars1mError::Ilp(_))); - assert!(list_dir_names(&out_flush_fail).is_empty()); - - // 3. Post-preflight hard-link collision on shard 1 after shard 0 already published. - // Verify shard 0 is rolled back, competing shard 1 and unrelated bars_1m.shard-00.ilp stay - // byte-identical, and no .tmp files remain. - let out_link_collision = dir.path().join("out-link-collision"); - fs::create_dir_all(&out_link_collision).unwrap(); - let eod_existing = out_link_collision.join("bars_1m.shard-00.ilp"); - fs::write(&eod_existing, b"keep-eod-shard").unwrap(); - let competing_shard_1 = out_link_collision.join("bars_1m_qm.shard-01.ilp"); - let competing_bytes = b"competing-writer-shard-1"; - - let err = run_curate_qm_bars_1m_to_dir_with_hooks( - &make_args( - dir.path().join("in.bson"), - mapping_path.clone(), - out_link_collision.clone(), - DEFAULT_QM_BARS_1M_MAPPING_SOURCE, - 3, - known_at_micros, - BsonStreamOptions::default(), - ), - Cursor::new(intraday_bytes.as_slice()), - |_idx, file| SyncedBufFile::new(file), - |shard_idx, final_path| { - if shard_idx == 1 { - fs::write(final_path, competing_bytes).expect("create competing shard 1"); - } - }, - ) - .expect_err("post-preflight collision must fail"); - assert!(matches!( - err, - RunCurateQmBars1mError::OutputFileExists { ref path } if path == &competing_shard_1 - )); - assert_eq!(fs::read(&competing_shard_1).unwrap(), competing_bytes); - assert_eq!(fs::read(&eod_existing).unwrap(), b"keep-eod-shard"); - assert_eq!( - list_dir_names(&out_link_collision), - vec!["bars_1m.shard-00.ilp", "bars_1m_qm.shard-01.ilp"] - ); - - // 4. Staging unlink failure preserves original cause and reports failed staging paths. - let out_cleanup_fail = dir.path().join("out-cleanup-fail"); - let err = run_curate_qm_bars_1m_to_dir_with_cleanup_hook( - &make_args( - dir.path().join("in.bson"), - mapping_path, - out_cleanup_fail.clone(), - DEFAULT_QM_BARS_1M_MAPPING_SOURCE, - 2, - known_at_micros, - BsonStreamOptions::default(), - ), - Cursor::new(intraday_bytes.as_slice()), - |_idx, _file| FailingWriteSink { - fail_on_write: false, - fail_on_flush: true, - }, - |_idx, _path| {}, - |path| { - // Simulate permission denied on cleanup while still cleaning up in TempDirGuard drop. - Err(io::Error::new( - io::ErrorKind::PermissionDenied, - format!("injected unlink failure for {}", path.display()), - )) - }, - ) - .expect_err("cleanup failure must surface RollbackFailed"); - match err { - RunCurateQmBars1mError::RollbackFailed { cause, failures } => { - assert!(matches!(*cause, RunCurateQmBars1mError::Ilp(_))); - assert_eq!(failures.len(), 2); - for failure in &failures { - assert!(failure.final_path.starts_with(&out_cleanup_fail)); - } - } - other => panic!("expected RollbackFailed, got {other:?}"), - } -} - -#[test] -fn report_formatter_exposes_every_counter_and_isolates_elapsed_secs_on_timing_line() { - let dir = TempDirGuard::new("qm-bars1m-format"); - let mapping_path = write_mapping_tsv(dir.path(), &["qm\tAAA\t2024-01-01\t\t7"]); - let known_at_micros = et_to_utc_micros(day(2024, 6, 12), 18, 0, 0).unwrap(); - let intraday_bytes = concat_docs(&[make_qm_intraday_doc( - "AAA", - et_ts_millis(2024, 6, 10, 10, 0), - 10.0, - 10.5, - 9.8, - 10.2, - 100.0, - )]); - let args = make_args( - dir.path().join("fmt.bson"), - mapping_path, - dir.path().join("unused"), - DEFAULT_QM_BARS_1M_MAPPING_SOURCE, - 2, - known_at_micros, - BsonStreamOptions::default(), - ); - - let report = - run_curate_qm_bars_1m_with_readers(&args, Cursor::new(intraday_bytes.as_slice()), |_idx| { - Vec::::new() - }) - .expect("format run should succeed"); - - let text = format_curate_qm_bars_1m_report(&report); - let lines: Vec<&str> = text.lines().collect(); - assert_eq!(lines.len(), 7, "unexpected report line count:\n{text}"); - assert_eq!(lines[0], "curate-etl curate-qm-bars-1m"); - - for token in [ - "docs_framed=1", - &format!("bytes_read={}", intraday_bytes.len()), - "docs_seen=1", - "rows_decoded=1", - "rejected=0", - "missing=0", - "empty=0", - "wrong_type=0", - "invalid_ts=0", - "invalid_num=0", - "corrupt=0", - "chunks=1", - "max_rows_per_chunk=1", - "cross_chunk_dedup=questdb_dedup_upsert_keys(ts,listing_id)", - "bars_in=1", - "keys_out_per_chunk_sum=1", - "invalid_ohlc=0", - "inconsistent_ohlc=0", - "invalid_vol=0", - "ts_out_of_range=0", - "dup_collapsed=0", - "dup_conflict_dropped=0", - "rows_in=1", - "rows_out=1", - "listings_out_per_chunk_sum=1", - "dropped_unmapped=0", - "listing_collision_collapsed=0", - "listing_collision_dropped=0", - "shards=2", - "rows_written=1", - "ilp_rows=1", - &format!("bytes={}", report.ilp_stats.bytes), - "flushes=1", - "per_shard_rows=", - ] { - assert!(text.contains(token), "report missing '{token}':\n{text}"); - } - - // Only the final timing: line carries elapsed_secs. - for line in &lines[..lines.len() - 1] { - assert!( - !line.contains("elapsed_secs"), - "non-timing line must not contain elapsed_secs: {line}" - ); - } - assert!(lines.last().unwrap().trim_start().starts_with("timing:")); - assert!(lines.last().unwrap().contains("elapsed_secs=")); -} - -// --------------------------------------------------------------------------------------------- -// QA additions (T-185): byte-level baselines, empty input, verbatim namespace, oversized docs. -// --------------------------------------------------------------------------------------------- - -/// Runs the pure `curate_and_write_qm_bars_1m` stage once per given byte slice (each slice treated -/// as one chunk) against one shared writer, returning per-shard bytes. -fn pure_stage_shard_bytes( - chunks: &[&[u8]], - mapping: &ProviderMappingTable, - mapping_source: &str, - shard_count: usize, - known_at_micros: i64, -) -> Vec> { - let sinks: Vec = (0..shard_count).map(|_| RecordingSink::new()).collect(); - let mut writer = IlpShardedWriter::new(sinks.clone(), IlpWriterOptions::default()).unwrap(); - for chunk in chunks { - let mut bars = Vec::new(); - decode_qm_intraday_buffer( - chunk, - |raw| bars.push(raw.into_eod_intraday_bar(|k, _| k)), - |_, _| {}, - ); - curate_and_write_qm_bars_1m(bars, mapping, mapping_source, &mut writer, known_at_micros) - .unwrap(); - } - writer.finish().unwrap(); - sinks - .iter() - .map(|sink| sink.bytes.lock().unwrap().clone()) - .collect() -} - -fn read_qm_shards(out_dir: &Path, shard_count: usize) -> Vec> { - (0..shard_count) - .map(|idx| fs::read(out_dir.join(format!("bars_1m_qm.shard-{idx:02}.ilp"))).unwrap()) - .collect() -} - -#[test] -fn file_mode_single_chunk_shards_match_pure_stage_byte_for_byte() { - let dir = TempDirGuard::new("qm-bars1m-qa-bytes"); - let mapping_path = write_mapping_tsv( - dir.path(), - &[ - "qm\tAAA\t2024-01-01\t\t11", - "qm\tBBB\t2024-01-01\t\t22", - "qm\tCCC\t2024-01-01\t\t33", - "qm\tDDD\t2024-01-01\t\t44", - ], - ); - let known_at_micros = et_to_utc_micros(day(2025, 3, 4), 18, 0, 0).unwrap(); - // Unsorted input across several listings/sessions with irregular (non-round) doubles so a wrong - // fixed-width encoding of any single OHLCV field would change bytes even if aggregates match. - let mut docs = Vec::new(); - for (i, code) in ["DDD", "AAA", "CCC", "BBB", "AAA", "DDD", "CCC", "BBB"] - .iter() - .enumerate() - { - let i = i as u8; - let base = 17.0 + f64::from(i) * 1.337; - docs.push(make_qm_intraday_doc_with_adjusted( - code, - et_ts_millis(2025, 3, 3, 7 + i, 3 * i), - base, - base + 0.123_456_789, - base - 0.987_654_321, - base + 0.000_001, - 1_000.5 + f64::from(i), - 3.0, - )); - } - let bytes = concat_docs(&docs); - let intraday_path = dir.path().join("qm.bson"); - fs::write(&intraday_path, &bytes).unwrap(); - - let shard_count = 3; - let out_dir = dir.path().join("out"); - let report = run_curate_qm_bars_1m(&make_args( - intraday_path, - mapping_path.clone(), - out_dir.clone(), - DEFAULT_QM_BARS_1M_MAPPING_SOURCE, - shard_count, - known_at_micros, - BsonStreamOptions::default(), - )) - .unwrap(); - assert_report_conservation(&report); - assert_eq!(report.chunks, 1); - assert_eq!(report.rows_written, 8); - - let mapping = load_provider_mapping_table(&mapping_path).unwrap(); - let expected = pure_stage_shard_bytes( - &[bytes.as_slice()], - &mapping, - DEFAULT_QM_BARS_1M_MAPPING_SOURCE, - shard_count, - known_at_micros, - ); - let actual = read_qm_shards(&out_dir, shard_count); - for idx in 0..shard_count { - assert_eq!( - actual[idx], expected[idx], - "shard {idx} bytes differ from pure stage" - ); - } - assert!(expected.iter().filter(|b| !b.is_empty()).count() >= 2); -} - -#[test] -fn file_mode_multi_chunk_shards_match_pure_stage_applied_per_document_chunk() { - let dir = TempDirGuard::new("qm-bars1m-qa-chunk-bytes"); - let mapping_path = write_mapping_tsv( - dir.path(), - &["qm\tAAA\t2024-01-01\t\t11", "qm\tBBB\t2024-01-01\t\t22"], - ); - let known_at_micros = et_to_utc_micros(day(2024, 9, 4), 18, 0, 0).unwrap(); - // Equal-size docs (same code length) so chunk_capacity == doc_len yields one doc per chunk. - let docs: Vec = (0..6u8) - .map(|m| { - let code = if m % 2 == 0 { "AAA" } else { "BBB" }; - let base = 30.0 + f64::from(m) * 0.25; - make_qm_intraday_doc( - code, - et_ts_millis(2024, 9, 3, 15, 59 - m), - base, - base + 1.0, - base - 1.0, - base, - 10.0, - ) - }) - .collect(); - let doc_len = docs[0].as_bytes().len(); - assert!(docs.iter().all(|d| d.as_bytes().len() == doc_len)); - let bytes = concat_docs(&docs); - let intraday_path = dir.path().join("qm.bson"); - fs::write(&intraday_path, &bytes).unwrap(); - - let out_dir = dir.path().join("out"); - let report = run_curate_qm_bars_1m(&make_args( - intraday_path, - mapping_path.clone(), - out_dir.clone(), - DEFAULT_QM_BARS_1M_MAPPING_SOURCE, - 2, - known_at_micros, - BsonStreamOptions { - chunk_capacity_bytes: doc_len, - max_doc_bytes: 1024 * 1024, - }, - )) - .unwrap(); - assert_report_conservation(&report); - assert_eq!(report.chunks, 6); - assert_eq!(report.max_rows_per_chunk, 1); - assert_eq!( - report.curate_stats.listings_out, 6, - "per-chunk sum, not distinct" - ); - - let mapping = load_provider_mapping_table(&mapping_path).unwrap(); - let chunks: Vec<&[u8]> = bytes.chunks(doc_len).collect(); - let expected = pure_stage_shard_bytes( - &chunks, - &mapping, - DEFAULT_QM_BARS_1M_MAPPING_SOURCE, - 2, - known_at_micros, - ); - assert_eq!(read_qm_shards(&out_dir, 2), expected); -} - -#[test] -fn empty_input_publishes_all_empty_shards_with_zero_counters() { - let dir = TempDirGuard::new("qm-bars1m-qa-empty"); - let mapping_path = write_mapping_tsv(dir.path(), &["qm\tAAA\t2024-01-01\t\t1"]); - let intraday_path = dir.path().join("empty.bson"); - fs::write(&intraday_path, b"").unwrap(); - let out_dir = dir.path().join("out"); - - let report = run_curate_qm_bars_1m(&make_args( - intraday_path, - mapping_path, - out_dir.clone(), - DEFAULT_QM_BARS_1M_MAPPING_SOURCE, - 3, - 123, - BsonStreamOptions::default(), - )) - .expect("empty input should succeed"); - assert_report_conservation(&report); - assert_eq!(report.intraday_docs_framed, 0); - assert_eq!(report.intraday_bytes_read, 0); - assert_eq!(report.chunks, 0); - assert_eq!(report.max_rows_per_chunk, 0); - assert_eq!(report.rows_written, 0); - assert_eq!(report.ilp_stats.per_shard_rows, vec![0, 0, 0]); - assert_eq!( - list_dir_names(&out_dir), - vec![ - "bars_1m_qm.shard-00.ilp", - "bars_1m_qm.shard-01.ilp", - "bars_1m_qm.shard-02.ilp", - ] - ); - assert!(read_qm_shards(&out_dir, 3).iter().all(Vec::is_empty)); -} - -#[test] -fn nonblank_mapping_source_is_forwarded_verbatim_without_trimming() { - let dir = TempDirGuard::new("qm-bars1m-qa-verbatim"); - let mapping_path = write_mapping_tsv(dir.path(), &["qm\tAAA\t2024-01-01\t\t1"]); - let bytes = concat_docs(&[make_qm_intraday_doc( - "AAA", - et_ts_millis(2024, 6, 10, 10, 0), - 10.0, - 10.5, - 9.8, - 10.2, - 100.0, - )]); - let args = make_args( - dir.path().join("in.bson"), - mapping_path, - dir.path().join("unused"), - " qm ", - 1, - 0, - BsonStreamOptions::default(), - ); - let report = run_curate_qm_bars_1m_with_readers(&args, Cursor::new(bytes.as_slice()), |_| { - Vec::::new() - }) - .expect("padded nonblank namespace is accepted"); - assert_report_conservation(&report); - // " qm " is not "qm": the row must be unmapped, proving the value was not trimmed. - assert_eq!(report.curate_stats.dropped_unmapped, 1); - assert_eq!(report.rows_written, 0); -} - -#[test] -fn doc_larger_than_chunk_capacity_succeeds_and_doc_over_max_doc_bytes_fails_clean() { - let dir = TempDirGuard::new("qm-bars1m-qa-oversize"); - let mapping_path = write_mapping_tsv(dir.path(), &["qm\tAAA\t2024-01-01\t\t7"]); - let docs = vec![ - make_qm_intraday_doc( - "AAA", - et_ts_millis(2024, 6, 10, 10, 0), - 10.0, - 10.5, - 9.8, - 10.2, - 1.0, - ), - make_qm_intraday_doc( - "AAA", - et_ts_millis(2024, 6, 10, 10, 1), - 10.0, - 10.5, - 9.8, - 10.2, - 2.0, - ), - ]; - let doc_len = docs[0].as_bytes().len(); - let bytes = concat_docs(&docs); - let intraday_path = dir.path().join("in.bson"); - fs::write(&intraday_path, &bytes).unwrap(); - - // Chunk capacity smaller than one document: reader grows for a single doc up to max_doc_bytes. - let out_ok = dir.path().join("out-ok"); - let report = run_curate_qm_bars_1m(&make_args( - intraday_path.clone(), - mapping_path.clone(), - out_ok.clone(), - DEFAULT_QM_BARS_1M_MAPPING_SOURCE, - 1, - 0, - BsonStreamOptions { - chunk_capacity_bytes: 8, - max_doc_bytes: 1024 * 1024, - }, - )) - .expect("doc larger than chunk capacity must still stream"); - assert_report_conservation(&report); - assert_eq!(report.rows_written, 2); - assert!(report.chunks >= 2); - assert_eq!(report.max_rows_per_chunk, 1); - - // max_doc_bytes below the doc length: fatal at offset 0, nothing left behind. - let out_bad = dir.path().join("out-bad"); - let err = run_curate_qm_bars_1m(&make_args( - intraday_path, - mapping_path, - out_bad.clone(), - DEFAULT_QM_BARS_1M_MAPPING_SOURCE, - 2, - 0, - BsonStreamOptions { - chunk_capacity_bytes: 64 * 1024, - max_doc_bytes: doc_len - 1, - }, - )) - .expect_err("doc over max_doc_bytes must fail"); - assert!( - matches!( - err, - RunCurateQmBars1mError::BsonStream { - source: BsonStreamError::CorruptDocumentLength { offset: 0, .. }, - .. - } - ), - "got {err:?}" - ); - assert!(list_dir_names(&out_bad).is_empty()); -} diff --git a/tools/curate-etl/src/run_curate_shorts.rs b/tools/curate-etl/src/run_curate_shorts.rs deleted file mode 100644 index b5726115..00000000 --- a/tools/curate-etl/src/run_curate_shorts.rs +++ /dev/null @@ -1,589 +0,0 @@ -//! File-to-file `curate-shorts` command runner (`M1.2ad`). -//! -//! Streams a concatenated raw BSON `ceoShorts` dump file alongside `provider_mapping.tsv` into an -//! atomically published `/shorts/part.parquet` dataset via [`curate_and_write_shorts`]. -//! -//! # Contract & Point-in-Time Rules -//! - Field names are supplied explicitly via [`CurateShortsArgs`] (validated via -//! [`CeoShortsFieldNames::validate`] before touching disk) because live MongoDB `ceoShorts` -//! value field names are unverified in the repository. -//! - `provider_mapping.tsv` uses the strict headerless 5-column TSV format from -//! [`crate::run_curate_bars::load_provider_mapping_tsv`]. -//! - All decoded [`CeoShortReport`] rows are passed directly to [`curate_and_write_shorts`] (which -//! resolves `provider_mapping` strictly on `report_date`, not `known_at_date`, stamps -//! `known_at = report_date + 4` Canadian TSX business days at `17:00 America/Toronto`, and -//! counts unmapped keys in [`CurateShortsStats::dropped_unmapped`]). -//! - **Empty / all-unmapped behavior:** delegated unchanged to [`curate_and_write_shorts`] / -//! [`write_shorts_dataset`], returning `Ok` with `rows_written == 0` and `files_written == 0` -//! without creating `/shorts` or modifying any pre-existing `part.parquet`. -//! - **Fail-closed safety:** invalid `--out`, invalid field names, empty `--mapping-source`, -//! unreadable inputs, malformed/overlapping `provider_mapping.tsv`, truncated/corrupt BSON -//! framing or element bytes, and out-of-range `report_date` errors return a typed -//! [`RunCurateShortsError`] before touching `args.out_dir`. -//! -//! # Counter Conservation Invariants -//! Every successful [`CurateShortsRunReport`] satisfies: -//! - `docs_framed as usize == decode.docs_in == decode.rows_out + decode.skipped_total()` -//! - `decode.rows_out == curate_stats.builder.rows_in` -//! - `curate_stats.builder.rows_in == curate_stats.builder.rows_out + curate_stats.builder.dropped_invalid_shares_short + curate_stats.builder.duplicate_collapsed + curate_stats.builder.duplicate_conflict_dropped` -//! - `curate_stats.rows_in == curate_stats.builder.rows_out == curate_stats.rows_out + curate_stats.dropped_unmapped + curate_stats.listing_collision_collapsed + curate_stats.listing_collision_dropped` -//! - `write_stats.rows_written == curate_stats.rows_out` - -use std::collections::HashSet; -use std::error::Error; -use std::fmt; -use std::fs::File; -use std::io; -use std::path::{Path, PathBuf}; -use std::sync::Arc; -use std::time::Instant; - -use crate::bson_ceo_shorts::{ - BsonCeoShortsDecodeStats, BsonCeoShortsError, CeoShortsFieldNames, -}; -use crate::bson_stream::{ - decode_ceo_shorts_chunks, BsonCeoShortsStreamError, BsonStreamError, BsonStreamOptions, - RawBsonChunkReader, -}; -use crate::curate_shorts::{ - curate_and_write_shorts, curate_shorts, CurateShortsStats, CurateShortsWriteError, -}; -use crate::parquet_shorts::{ - write_shorts_dataset, ShortsParquetRow, ShortsWriteOptions, ShortsWriteStats, -}; -use crate::provider_mapping::{ProviderMappingError, ProviderMappingTable}; -use crate::run_curate_bars::{load_provider_mapping_tsv, RunCurateBarsError}; -use crate::shorts::CeoShortReport; - -/// Default `--mapping-source` passed to `provider_mapping` lookups for `ceoShorts`. -pub const DEFAULT_MAPPING_SOURCE: &str = "ceo"; - -/// Parsed arguments for the `curate-shorts` CLI command. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct CurateShortsArgs { - pub ceo_shorts: PathBuf, - pub provider_mapping: PathBuf, - pub out_dir: PathBuf, - pub key_field: String, - pub report_date_field: String, - pub shares_short_field: String, - pub net_change_field: Option, - pub pct_float_field: Option, - pub mapping_source: String, -} - -impl CurateShortsArgs { - /// Borrows the configured BSON field names as [`CeoShortsFieldNames`]. - #[inline] - pub fn field_names(&self) -> CeoShortsFieldNames<'_> { - CeoShortsFieldNames { - key: self.key_field.as_str(), - report_date: self.report_date_field.as_str(), - shares_short: self.shares_short_field.as_str(), - net_change: self.net_change_field.as_deref(), - pct_float: self.pct_float_field.as_deref(), - } - } -} - -/// Full run report produced by [`run_curate_shorts`]. -#[derive(Debug, Clone, PartialEq)] -pub struct CurateShortsRunReport { - pub docs_framed: u64, - pub bytes_read: u64, - pub peak_chunk_bytes: usize, - pub decode: BsonCeoShortsDecodeStats, - pub curate_stats: CurateShortsStats, - pub write_stats: ShortsWriteStats, - pub elapsed_secs: f64, -} - -/// Stage-timed run output used internally by `bench-curate-shorts-command`. -#[derive(Debug, Clone, PartialEq)] -pub(crate) struct CurateShortsTimedRun { - pub report: CurateShortsRunReport, - pub decode_elapsed_secs: f64, - pub curate_elapsed_secs: f64, - pub write_elapsed_secs: f64, - pub checksum: u64, -} - -/// Typed errors returned by [`run_curate_shorts`]. -/// -/// Every variant's `Display` output is a single line naming the offending path (and line number or -/// byte offset where applicable). -#[derive(Debug)] -pub enum RunCurateShortsError { - InvalidOutDir { - path: PathBuf, - detail: String, - }, - InvalidFieldNames { - source: BsonCeoShortsError, - }, - EmptyMappingSource, - OpenInput { - label: &'static str, - path: PathBuf, - source: io::Error, - }, - ReadInput { - label: &'static str, - path: PathBuf, - source: io::Error, - }, - TsvParse { - path: PathBuf, - line: usize, - detail: String, - }, - ProviderMapping { - path: PathBuf, - source: ProviderMappingError, - }, - BsonStream { - path: PathBuf, - source: BsonStreamError, - }, - CorruptBson { - path: PathBuf, - offset: u64, - source: BsonCeoShortsError, - }, - CurateWrite { - out_dir: PathBuf, - source: CurateShortsWriteError, - }, -} - -impl fmt::Display for RunCurateShortsError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::InvalidOutDir { path, detail } => { - write!(f, "invalid --out '{}': {detail}", path.display()) - } - Self::InvalidFieldNames { source } => write!(f, "{source}"), - Self::EmptyMappingSource => { - write!(f, "invalid --mapping-source: must not be empty or blank") - } - Self::OpenInput { - label, - path, - source, - } => write!(f, "failed to open {label} '{}': {source}", path.display()), - Self::ReadInput { - label, - path, - source, - } => write!(f, "failed to read {label} '{}': {source}", path.display()), - Self::TsvParse { path, line, detail } => { - write!(f, "{}:{line}: {detail}", path.display()) - } - Self::ProviderMapping { path, source } => { - write!(f, "invalid provider_mapping '{}': {source}", path.display()) - } - Self::BsonStream { path, source } => { - write!(f, "failed reading ceo-shorts '{}': {source}", path.display()) - } - Self::CorruptBson { - path, - offset, - source, - } => write!( - f, - "corrupt ceo-shorts BSON '{}' at byte offset {offset}: {source}", - path.display() - ), - Self::CurateWrite { out_dir, source } => { - write!(f, "curate/write to '{}' failed: {source}", out_dir.display()) - } - } - } -} - -impl Error for RunCurateShortsError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::InvalidFieldNames { source } => Some(source), - Self::OpenInput { source, .. } | Self::ReadInput { source, .. } => Some(source), - Self::ProviderMapping { source, .. } => Some(source), - Self::BsonStream { source, .. } => Some(source), - Self::CorruptBson { source, .. } => Some(source), - Self::CurateWrite { source, .. } => Some(source), - Self::InvalidOutDir { .. } | Self::EmptyMappingSource | Self::TsvParse { .. } => None, - } - } -} - -fn validate_out_dir(out_dir: &Path) -> Result<(), RunCurateShortsError> { - if out_dir.exists() && !out_dir.is_dir() { - return Err(RunCurateShortsError::InvalidOutDir { - path: out_dir.to_path_buf(), - detail: "path exists and is not a directory".to_string(), - }); - } - Ok(()) -} - -fn map_tsv_error(path: &Path, err: RunCurateBarsError) -> RunCurateShortsError { - match err { - RunCurateBarsError::OpenInput { - label, - path, - source, - } => RunCurateShortsError::OpenInput { - label, - path, - source, - }, - RunCurateBarsError::ReadInput { - label, - path, - source, - } => RunCurateShortsError::ReadInput { - label, - path, - source, - }, - RunCurateBarsError::TsvParse { path, line, detail } => { - RunCurateShortsError::TsvParse { path, line, detail } - } - RunCurateBarsError::ProviderMapping { path, source } => { - RunCurateShortsError::ProviderMapping { path, source } - } - other => RunCurateShortsError::TsvParse { - path: path.to_path_buf(), - line: 0, - detail: other.to_string(), - }, - } -} - -fn bson_error_offset(err: &BsonCeoShortsError) -> u64 { - match err { - BsonCeoShortsError::TruncatedDocument { offset, .. } - | BsonCeoShortsError::CorruptDocumentLength { offset, .. } - | BsonCeoShortsError::CorruptBson { offset, .. } => *offset, - BsonCeoShortsError::InvalidFieldNames { .. } => 0, - } -} - -struct DecodedShortsInputs { - mapping: ProviderMappingTable, - reports: Vec>>, - docs_framed: u64, - bytes_read: u64, - peak_chunk_bytes: usize, - decode: BsonCeoShortsDecodeStats, -} - -fn decode_all_inputs(args: &CurateShortsArgs) -> Result { - decode_inputs_from_opener( - &args.provider_mapping, - &args.mapping_source, - &args.field_names(), - &args.ceo_shorts, - || { - File::open(&args.ceo_shorts).map_err(|source| RunCurateShortsError::OpenInput { - label: "ceo-shorts", - path: args.ceo_shorts.clone(), - source, - }) - }, - ) -} - -fn decode_inputs_from_opener( - provider_mapping_path: &Path, - mapping_source: &str, - fields: &CeoShortsFieldNames<'_>, - ceo_shorts_path: &Path, - open_shorts: F, -) -> Result -where - R: io::Read, - F: FnOnce() -> Result, -{ - fields - .validate() - .map_err(|source| RunCurateShortsError::InvalidFieldNames { source })?; - - if mapping_source.trim().is_empty() { - return Err(RunCurateShortsError::EmptyMappingSource); - } - - let mapping_rows = load_provider_mapping_tsv(provider_mapping_path) - .map_err(|err| map_tsv_error(provider_mapping_path, err))?; - let mapping = ProviderMappingTable::from_rows(mapping_rows).map_err(|source| { - RunCurateShortsError::ProviderMapping { - path: provider_mapping_path.to_path_buf(), - source, - } - })?; - - let stream = open_shorts()?; - let mut reader = RawBsonChunkReader::with_options(stream, BsonStreamOptions::default()) - .map_err(|source| RunCurateShortsError::BsonStream { - path: ceo_shorts_path.to_path_buf(), - source, - })?; - - let mut key_interner: HashSet> = HashSet::new(); - let mut reports: Vec>> = Vec::new(); - - let decode = decode_ceo_shorts_chunks(&mut reader, fields, |raw| { - let key = if let Some(existing) = key_interner.get(raw.key) { - Arc::clone(existing) - } else { - let arc: Arc = Arc::from(raw.key); - key_interner.insert(Arc::clone(&arc)); - arc - }; - reports.push(CeoShortReport { - key, - report_date: raw.report_date, - shares_short: raw.shares_short, - net_change: raw.net_change, - pct_float: raw.pct_float, - }); - }) - .map_err(|err| match err { - BsonCeoShortsStreamError::Stream(source) => RunCurateShortsError::BsonStream { - path: ceo_shorts_path.to_path_buf(), - source, - }, - BsonCeoShortsStreamError::Decode(source) => match &source { - BsonCeoShortsError::InvalidFieldNames { .. } => { - RunCurateShortsError::InvalidFieldNames { source } - } - _ => { - let offset = bson_error_offset(&source); - RunCurateShortsError::CorruptBson { - path: ceo_shorts_path.to_path_buf(), - offset, - source, - } - } - }, - })?; - - Ok(DecodedShortsInputs { - mapping, - reports, - docs_framed: reader.docs_framed(), - bytes_read: reader.bytes_read(), - peak_chunk_bytes: reader.buffer_capacity(), - decode, - }) -} - -/// Runs the end-to-end `curate-shorts` file-to-Parquet pipeline via [`curate_and_write_shorts`]. -/// -/// Any validation, I/O, TSV, mapping, BSON framing/corruption, or curation error returns before -/// touching `args.out_dir`, leaving any pre-existing `/shorts/part.parquet` -/// byte-identical. -pub fn run_curate_shorts( - args: &CurateShortsArgs, -) -> Result { - let start = Instant::now(); - validate_out_dir(&args.out_dir)?; - - let decoded = decode_all_inputs(args)?; - finish_curate_shorts(decoded, &args.mapping_source, &args.out_dir, start) -} - -/// Runs `curate-shorts` from an arbitrary raw-BSON [`io::Read`] stream. -pub fn run_curate_shorts_with_reader( - provider_mapping_path: &Path, - mapping_source: &str, - fields: &CeoShortsFieldNames<'_>, - ceo_shorts_input: (&Path, R), - out_dir: &Path, -) -> Result { - let start = Instant::now(); - validate_out_dir(out_dir)?; - - let (ceo_path, stream) = ceo_shorts_input; - let decoded = decode_inputs_from_opener( - provider_mapping_path, - mapping_source, - fields, - ceo_path, - || Ok(stream), - )?; - finish_curate_shorts(decoded, mapping_source, out_dir, start) -} - -fn finish_curate_shorts( - decoded: DecodedShortsInputs, - mapping_source: &str, - out_dir: &Path, - start: Instant, -) -> Result { - let write_report = curate_and_write_shorts( - out_dir, - decoded.reports, - mapping_source, - &decoded.mapping, - ShortsWriteOptions::default(), - ) - .map_err(|source| RunCurateShortsError::CurateWrite { - out_dir: out_dir.to_path_buf(), - source, - })?; - - Ok(CurateShortsRunReport { - docs_framed: decoded.docs_framed, - bytes_read: decoded.bytes_read, - peak_chunk_bytes: decoded.peak_chunk_bytes, - decode: decoded.decode, - curate_stats: write_report.curate_stats, - write_stats: write_report.write_stats, - elapsed_secs: start.elapsed().as_secs_f64(), - }) -} - -fn compute_rows_checksum(rows: &[ShortsParquetRow]) -> u64 { - let mut hash = 0xcbf2_9ce4_8422_2325_u64; - let mix = |mut h: u64, v: u64| -> u64 { - h ^= v; - h = h.wrapping_mul(0x0000_0100_0000_01b3); - h - }; - let mix_str = |mut h: u64, s: &str| -> u64 { - h = mix(h, s.len() as u64); - for &b in s.as_bytes() { - h = mix(h, u64::from(b)); - } - h - }; - for row in rows { - hash = mix(hash, row.listing_id as u64); - hash = mix(hash, row.report_date as u64); - hash = mix(hash, row.known_at_micros as u64); - hash = mix(hash, row.shares_short.to_bits()); - hash = match row.net_change { - Some(v) => mix(mix(hash, 1), v.to_bits()), - None => mix(hash, 0), - }; - hash = match row.pct_float { - Some(v) => mix(mix(hash, 1), v.to_bits()), - None => mix(hash, 0), - }; - hash = mix_str(hash, row.source.as_ref()); - } - hash -} - -/// Stage-timed variant of [`run_curate_shorts`] used internally by `bench-curate-shorts-command`. -/// -/// Separately times `decode` (TSV load + BSON stream), `curate` (`curate_shorts`), and `write` -/// (`write_shorts_dataset`), and computes a deterministic FNV-1a checksum over all 7 columns of the -/// curated rows. -pub(crate) fn run_curate_shorts_timed( - args: &CurateShortsArgs, -) -> Result { - let total_start = Instant::now(); - validate_out_dir(&args.out_dir)?; - - let decode_start = Instant::now(); - let decoded = decode_all_inputs(args)?; - let decode_elapsed_secs = decode_start.elapsed().as_secs_f64(); - - let curate_start = Instant::now(); - let curated = curate_shorts(decoded.reports, &args.mapping_source, &decoded.mapping).map_err( - |source| RunCurateShortsError::CurateWrite { - out_dir: args.out_dir.clone(), - source: CurateShortsWriteError::Curate(source), - }, - )?; - let curate_elapsed_secs = curate_start.elapsed().as_secs_f64(); - - let checksum = compute_rows_checksum(&curated.rows); - - let write_start = Instant::now(); - let write_stats = - write_shorts_dataset(&args.out_dir, &curated.rows, ShortsWriteOptions::default()).map_err( - |source| RunCurateShortsError::CurateWrite { - out_dir: args.out_dir.clone(), - source: CurateShortsWriteError::Parquet(source), - }, - )?; - let write_elapsed_secs = write_start.elapsed().as_secs_f64(); - - let report = CurateShortsRunReport { - docs_framed: decoded.docs_framed, - bytes_read: decoded.bytes_read, - peak_chunk_bytes: decoded.peak_chunk_bytes, - decode: decoded.decode, - curate_stats: curated.stats, - write_stats, - elapsed_secs: total_start.elapsed().as_secs_f64(), - }; - - Ok(CurateShortsTimedRun { - report, - decode_elapsed_secs, - curate_elapsed_secs, - write_elapsed_secs, - checksum, - }) -} - -/// Formats [`CurateShortsRunReport`] into a deterministic machine-readable `key=value` summary. -/// -/// Only the final `timing:` line contains wall-clock time (`elapsed_secs`). -pub fn format_curate_shorts_report(report: &CurateShortsRunReport) -> String { - let d = &report.decode; - let b = &report.curate_stats.builder; - let c = &report.curate_stats; - let w = &report.write_stats; - format!( - "curate-etl curate-shorts\n\ - \x20 ceo_bson: docs_framed={} bytes_read={} peak_chunk_bytes={} docs_in={} rows_out={} skipped={} (missing_key={} wrong_key_type={} empty_key={} missing_date={} wrong_date_type={} invalid_date={} date_oor={} missing_shares={} wrong_shares_type={}) nulled_wrong_type=(net_change={} pct_float={})\n\ - \x20 builder: rows_in={} rows_out={} keys_out={} invalid_shares={} nulled_net_change={} nulled_pct_float={} dup_collapsed={} dup_conflict={}\n\ - \x20 curate: rows_in={} rows_out={} listings_out={} dropped_unmapped={} coll_collapsed={} coll_dropped={}\n\ - \x20 write: files={} row_groups={} rows_written={} bytes_written={}\n\ - \x20 timing: elapsed_secs={:.6}", - report.docs_framed, - report.bytes_read, - report.peak_chunk_bytes, - d.docs_in, - d.rows_out, - d.skipped_total(), - d.skipped_missing_key, - d.skipped_wrong_key_type, - d.skipped_empty_key, - d.skipped_missing_report_date, - d.skipped_wrong_report_date_type, - d.skipped_invalid_report_date, - d.skipped_report_date_out_of_range, - d.skipped_missing_shares_short, - d.skipped_wrong_shares_short_type, - d.nulled_wrong_type_net_change, - d.nulled_wrong_type_pct_float, - b.rows_in, - b.rows_out, - b.keys_out, - b.dropped_invalid_shares_short, - b.nulled_invalid_net_change, - b.nulled_invalid_pct_float, - b.duplicate_collapsed, - b.duplicate_conflict_dropped, - c.rows_in, - c.rows_out, - c.listings_out, - c.dropped_unmapped, - c.listing_collision_collapsed, - c.listing_collision_dropped, - w.files_written, - w.row_groups_written, - w.rows_written, - w.bytes_written, - report.elapsed_secs, - ) -} - -#[cfg(test)] -#[path = "run_curate_shorts_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/run_curate_shorts_tests.rs b/tools/curate-etl/src/run_curate_shorts_tests.rs deleted file mode 100644 index 02b46574..00000000 --- a/tools/curate-etl/src/run_curate_shorts_tests.rs +++ /dev/null @@ -1,395 +0,0 @@ -use std::fs::{self, File}; -use std::io::Write; -use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering}; - -use bson::raw::{cstr, RawDocumentBuf}; -use bson::DateTime as BsonDateTime; - -use super::*; -use crate::bson_ceo_shorts::{DEFAULT_KEY_FIELD, DEFAULT_REPORT_DATE_FIELD}; -use crate::split::ymd_to_epoch_days; - -static TEMP_SEQ: AtomicU64 = AtomicU64::new(0); - -struct TempDirGuard { - path: PathBuf, -} - -impl TempDirGuard { - fn new(label: &str) -> Self { - let seq = TEMP_SEQ.fetch_add(1, Ordering::Relaxed); - let pid = std::process::id(); - let path = - std::env::temp_dir().join(format!("curate-etl-run-shorts-test-{label}-{pid}-{seq}")); - let _ = fs::remove_dir_all(&path); - fs::create_dir_all(&path).expect("create temp dir"); - Self { path } - } - - fn path(&self) -> &Path { - &self.path - } -} - -impl Drop for TempDirGuard { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.path); - } -} - -fn day(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).expect("valid date") -} - -fn write_bytes(path: &Path, bytes: &[u8]) { - let mut f = File::create(path).expect("create file"); - f.write_all(bytes).expect("write file"); -} - -fn make_short_doc( - fields: &CeoShortsFieldNames<'_>, - key: &str, - report_date: i32, - shares_short: f64, - net_change: Option, - pct_float: Option, -) -> Vec { - let cstring = |s: &str| bson::raw::CString::try_from(s.to_owned()).expect("valid BSON key"); - let mut doc = RawDocumentBuf::new(); - doc.append(cstring(fields.key), key); - let millis = i64::from(report_date) * 86_400_000; - doc.append(cstring(fields.report_date), BsonDateTime::from_millis(millis)); - doc.append(cstring(fields.shares_short), shares_short); - if let (Some(f), Some(v)) = (fields.net_change, net_change) { - doc.append(cstring(f), v); - } - if let (Some(f), Some(v)) = (fields.pct_float, pct_float) { - doc.append(cstring(f), v); - } - doc.into_bytes() -} - -fn default_test_fields() -> CeoShortsFieldNames<'static> { - CeoShortsFieldNames { - key: DEFAULT_KEY_FIELD, - report_date: DEFAULT_REPORT_DATE_FIELD, - shares_short: "sharesShort", - net_change: Some("netChange"), - pct_float: Some("pctFloat"), - } -} - -fn assert_report_invariants(report: &CurateShortsRunReport) { - assert_eq!(report.docs_framed as usize, report.decode.docs_in); - assert_eq!( - report.decode.docs_in, - report.decode.rows_out + report.decode.skipped_total() - ); - assert_eq!(report.decode.rows_out, report.curate_stats.builder.rows_in); - let b = &report.curate_stats.builder; - assert_eq!( - b.rows_in, - b.rows_out - + b.dropped_invalid_shares_short - + b.duplicate_collapsed - + b.duplicate_conflict_dropped - ); - let c = &report.curate_stats; - assert_eq!(c.rows_in, b.rows_out); - assert_eq!( - c.rows_in, - c.rows_out - + c.dropped_unmapped - + c.listing_collision_collapsed - + c.listing_collision_dropped - ); - assert_eq!(report.write_stats.rows_written, c.rows_out); -} - -#[test] -fn end_to_end_curation_anchors_on_report_date_and_enforces_invariants() { - let dir = TempDirGuard::new("e2e"); - let bson_path = dir.path().join("ceoShorts.bson"); - let map_path = dir.path().join("provider_mapping.tsv"); - let out_a = dir.path().join("out_a"); - let out_b = dir.path().join("out_b"); - - // Listing 101 active on 2024-03-15, ends 2024-03-16 (before known_at_date 2024-03-21). - // Reuse gap on SYM_REUSE: 2020-01-01..=2022-12-31 -> 201, 2024-01-01.. -> 202. - // Alias SYM_ALIAS maps to 101 as well for cross-key collision test. - let mapping_tsv = concat!( - "ceo\tRY\t2020-01-01\t2024-03-16\t101\n", - "ceo\tRY_ALIAS\t2020-01-01\t2024-03-16\t101\n", - "ceo\tREUSE\t2020-01-01\t2022-12-31\t201\n", - "ceo\tREUSE\t2024-01-01\t\t202\n", - ); - write_bytes(&map_path, mapping_tsv.as_bytes()); - - let fields = default_test_fields(); - let docs = vec![ - // Mapped on report_date 2024-03-15 even though listing ends 2024-03-16 (< known_at 2024-03-21) - make_short_doc( - &fields, - "RY", - day(2024, 3, 15), - 100_000.0, - Some(1_000.0), - Some(1.5), - ), - // Identical cross-key collision via RY_ALIAS -> collapsed - make_short_doc( - &fields, - "RY_ALIAS", - day(2024, 3, 15), - 100_000.0, - Some(1_000.0), - Some(1.5), - ), - // Conflicting cross-key collision on 2024-02-29 -> both dropped - make_short_doc(&fields, "RY", day(2024, 2, 29), 90_000.0, None, None), - make_short_doc(&fields, "RY_ALIAS", day(2024, 2, 29), 91_000.0, None, None), - // Reuse gap date 2023-06-15 -> dropped_unmapped - make_short_doc(&fields, "REUSE", day(2023, 6, 15), 50_000.0, None, None), - // Reuse post-gap 2024-03-28 -> listing 202 - make_short_doc(&fields, "REUSE", day(2024, 3, 28), 60_000.0, None, None), - // Unmapped key -> dropped_unmapped - make_short_doc(&fields, "UNKNOWN", day(2024, 3, 15), 10_000.0, None, None), - ]; - - let mut forward_bytes = Vec::new(); - for d in &docs { - forward_bytes.extend_from_slice(d); - } - write_bytes(&bson_path, &forward_bytes); - - let args_a = CurateShortsArgs { - ceo_shorts: bson_path.clone(), - provider_mapping: map_path.clone(), - out_dir: out_a.clone(), - key_field: DEFAULT_KEY_FIELD.to_string(), - report_date_field: DEFAULT_REPORT_DATE_FIELD.to_string(), - shares_short_field: "sharesShort".to_string(), - net_change_field: Some("netChange".to_string()), - pct_float_field: Some("pctFloat".to_string()), - mapping_source: DEFAULT_MAPPING_SOURCE.to_string(), - }; - - let report_a = run_curate_shorts(&args_a).expect("run forward"); - assert_report_invariants(&report_a); - assert_eq!(report_a.curate_stats.rows_out, 2); // listing 101 (2024-03-15) and listing 202 (2024-03-28) - assert_eq!(report_a.curate_stats.listings_out, 2); - assert_eq!(report_a.curate_stats.dropped_unmapped, 2); - assert_eq!(report_a.curate_stats.listing_collision_collapsed, 1); - assert_eq!(report_a.curate_stats.listing_collision_dropped, 2); - assert_eq!(report_a.write_stats.files_written, 1); - assert_eq!(report_a.write_stats.rows_written, 2); - - // Reversed input order must yield byte-identical shorts/part.parquet. - let bson_rev = dir.path().join("ceoShorts_rev.bson"); - let mut rev_bytes = Vec::new(); - for d in docs.iter().rev() { - rev_bytes.extend_from_slice(d); - } - write_bytes(&bson_rev, &rev_bytes); - - let args_b = CurateShortsArgs { - ceo_shorts: bson_rev, - out_dir: out_b.clone(), - ..args_a - }; - let report_b = run_curate_shorts(&args_b).expect("run reversed"); - assert_report_invariants(&report_b); - assert_eq!(report_a.curate_stats, report_b.curate_stats); - assert_eq!(report_a.write_stats, report_b.write_stats); - - let bytes_a = fs::read(out_a.join("shorts/part.parquet")).expect("read a"); - let bytes_b = fs::read(out_b.join("shorts/part.parquet")).expect("read b"); - assert_eq!(bytes_a, bytes_b, "reversed input must produce byte-identical Parquet"); - - // Check report formatting determinism (ignoring final timing line). - let text_a = format_curate_shorts_report(&report_a); - let text_b = format_curate_shorts_report(&report_b); - let strip_timing = |s: &str| { - s.lines() - .filter(|l| !l.trim_start().starts_with("timing:")) - .collect::>() - .join("\n") - }; - assert_eq!(strip_timing(&text_a), strip_timing(&text_b)); -} - -#[test] -fn custom_mapping_source_and_custom_fields_work_end_to_end() { - let dir = TempDirGuard::new("custom"); - let bson_path = dir.path().join("custom.bson"); - let map_path = dir.path().join("mapping.tsv"); - let out_dir = dir.path().join("out"); - - write_bytes(&map_path, b"ceo_custom\tSHOP\t2020-01-01\t\t777\n"); - let custom_fields = CeoShortsFieldNames { - key: "ticker", - report_date: "asOf", - shares_short: "shortQty", - net_change: None, - pct_float: None, - }; - let doc = make_short_doc(&custom_fields, "SHOP", day(2024, 7, 15), 12_345.0, None, None); - write_bytes(&bson_path, &doc); - - let args = CurateShortsArgs { - ceo_shorts: bson_path, - provider_mapping: map_path, - out_dir, - key_field: "ticker".to_string(), - report_date_field: "asOf".to_string(), - shares_short_field: "shortQty".to_string(), - net_change_field: None, - pct_float_field: None, - mapping_source: "ceo_custom".to_string(), - }; - let report = run_curate_shorts(&args).expect("custom run"); - assert_report_invariants(&report); - assert_eq!(report.curate_stats.rows_out, 1); - assert_eq!(report.write_stats.rows_written, 1); -} - -#[test] -fn failure_modes_and_all_unmapped_preserve_preexisting_output_byte_identically() { - let dir = TempDirGuard::new("failures"); - let out_dir = dir.path().join("out"); - let shorts_dir = out_dir.join("shorts"); - fs::create_dir_all(&shorts_dir).unwrap(); - let sentinel_path = shorts_dir.join("part.parquet"); - let sentinel_bytes = b"SENTINEL-PREEXISTING-SHORTS-PARQUET".to_vec(); - write_bytes(&sentinel_path, &sentinel_bytes); - - let valid_map = dir.path().join("valid_map.tsv"); - write_bytes(&valid_map, b"ceo\tRY\t2020-01-01\t\t101\n"); - - let fields = default_test_fields(); - let valid_bson = dir.path().join("valid.bson"); - write_bytes( - &valid_bson, - &make_short_doc(&fields, "RY", day(2024, 3, 15), 100.0, None, None), - ); - - let base_args = CurateShortsArgs { - ceo_shorts: valid_bson.clone(), - provider_mapping: valid_map.clone(), - out_dir: out_dir.clone(), - key_field: DEFAULT_KEY_FIELD.to_string(), - report_date_field: DEFAULT_REPORT_DATE_FIELD.to_string(), - shares_short_field: "sharesShort".to_string(), - net_change_field: None, - pct_float_field: None, - mapping_source: DEFAULT_MAPPING_SOURCE.to_string(), - }; - - // 1. Missing input file - let err = run_curate_shorts(&CurateShortsArgs { - ceo_shorts: dir.path().join("does_not_exist.bson"), - ..base_args.clone() - }) - .unwrap_err(); - assert!(matches!(err, RunCurateShortsError::OpenInput { .. })); - assert!(!err.to_string().contains('\n')); - assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel_bytes); - - // 2. Malformed TSV - let bad_tsv = dir.path().join("bad.tsv"); - write_bytes(&bad_tsv, b"ceo\tRY\tnot-a-date\t\t101\n"); - let err = run_curate_shorts(&CurateShortsArgs { - provider_mapping: bad_tsv, - ..base_args.clone() - }) - .unwrap_err(); - assert!(matches!(err, RunCurateShortsError::TsvParse { line: 1, .. })); - assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel_bytes); - - // 3. Overlapping mapping TSV - let overlap_tsv = dir.path().join("overlap.tsv"); - write_bytes( - &overlap_tsv, - b"ceo\tRY\t2020-01-01\t2024-06-01\t101\nceo\tRY\t2024-06-01\t\t102\n", - ); - let err = run_curate_shorts(&CurateShortsArgs { - provider_mapping: overlap_tsv, - ..base_args.clone() - }) - .unwrap_err(); - assert!(matches!(err, RunCurateShortsError::ProviderMapping { .. })); - assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel_bytes); - - // 4. Truncated BSON - let trunc_bson = dir.path().join("trunc.bson"); - write_bytes(&trunc_bson, &[20, 0, 0, 0, 1, 2]); - let err = run_curate_shorts(&CurateShortsArgs { - ceo_shorts: trunc_bson, - ..base_args.clone() - }) - .unwrap_err(); - assert!(matches!(err, RunCurateShortsError::BsonStream { .. })); - assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel_bytes); - - // 5. Corrupt BSON element - let corrupt_bson = dir.path().join("corrupt.bson"); - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("symbol"), "RY"); - doc.append(cstr!("z"), 1_i32); - let mut bytes = doc.into_bytes(); - let z_pos = bytes - .windows(3) - .position(|w| w == [0x10, b'z', 0x00]) - .unwrap(); - bytes[z_pos] = 0x7e; - write_bytes(&corrupt_bson, &bytes); - let err = run_curate_shorts(&CurateShortsArgs { - ceo_shorts: corrupt_bson, - ..base_args.clone() - }) - .unwrap_err(); - assert!(matches!(err, RunCurateShortsError::CorruptBson { offset: 0, .. })); - assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel_bytes); - - // 6. Out-of-range report_date (< 2008) - let oor_bson = dir.path().join("oor.bson"); - write_bytes( - &oor_bson, - &make_short_doc(&fields, "RY", day(2007, 12, 15), 100.0, None, None), - ); - let err = run_curate_shorts(&CurateShortsArgs { - ceo_shorts: oor_bson, - ..base_args.clone() - }) - .unwrap_err(); - assert!(matches!(err, RunCurateShortsError::CurateWrite { .. })); - assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel_bytes); - - // 7. Obstructed --out (regular file) - let file_as_out = dir.path().join("file_out"); - write_bytes(&file_as_out, b"not-a-dir"); - let err = run_curate_shorts(&CurateShortsArgs { - out_dir: file_as_out, - ..base_args.clone() - }) - .unwrap_err(); - assert!(matches!(err, RunCurateShortsError::InvalidOutDir { .. })); - - // 8. All-unmapped input succeeds with rows_written == 0 and leaves sentinel untouched - let unmapped_bson = dir.path().join("unmapped.bson"); - write_bytes( - &unmapped_bson, - &make_short_doc(&fields, "NO_MATCH", day(2024, 3, 15), 100.0, None, None), - ); - let rep = run_curate_shorts(&CurateShortsArgs { - ceo_shorts: unmapped_bson, - ..base_args - }) - .expect("all-unmapped succeeds"); - assert_report_invariants(&rep); - assert_eq!(rep.curate_stats.dropped_unmapped, 1); - assert_eq!(rep.write_stats.rows_written, 0); - assert_eq!(rep.write_stats.files_written, 0); - assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel_bytes); -} diff --git a/tools/curate-etl/src/run_mongo.rs b/tools/curate-etl/src/run_mongo.rs deleted file mode 100644 index b36af63e..00000000 --- a/tools/curate-etl/src/run_mongo.rs +++ /dev/null @@ -1,503 +0,0 @@ -//! Direct read-only MongoDB streaming runners for all six M1 `curate-*` CLI commands. -//! -//! Uses [`ReadOnlyMongoClient`] (constructed strictly from [`crate::ValidatedReadOnlyMongoUri`]) -//! to open zero-copy raw-BSON cursors over allowlisted [`SourceCollection`]s and feeds them -//! directly into the shared `run_curate_*_with_readers` pipelines with zero intermediate `.bson` -//! scratch files. - -use std::collections::BTreeSet; -use std::error::Error; -use std::fmt; -use std::path::{Path, PathBuf}; - -use crate::bson_ceo_shorts::CeoShortsFieldNames; -use crate::bson_qm_events::{QmEarningsFieldNames, QmFilingsFieldNames}; -use crate::curate_adj::AdjPointInTimeFence; -use crate::mongo_stream::{ - MongoCliOptions, MongoReadSpec, MongoStreamError, ReadOnlyMongoClient, SourceCollection, -}; -use crate::run_curate_adj::{ - run_curate_adj_factors_with_readers, CurateAdjFactorsRunReport, RunCurateAdjError, -}; -use crate::run_curate_bars::{ - load_provider_mapping_tsv, run_curate_bars_1d_with_readers, CurateBars1dRunReport, - RunCurateBarsError, -}; -use crate::run_curate_corporate_actions::{ - run_curate_corporate_actions_with_readers, CurateCorporateActionsRunReport, - RunCurateCorporateActionsError, -}; -use crate::run_curate_events::{ - run_curate_events_with_readers, CurateEventsRunReport, RunCurateEventsError, -}; -use crate::run_curate_fx::{ - run_curate_fx_1d_with_readers, CurateFx1dRunReport, RunCurateFxError, EOD_CAD_FOREX_CODE, -}; -use crate::run_curate_shorts::{ - run_curate_shorts_with_reader, CurateShortsRunReport, RunCurateShortsError, -}; - -/// Error returned by direct MongoDB streaming curation commands. -#[derive(Debug)] -pub enum RunMongoCurateError { - Mongo(MongoStreamError), - Bars(RunCurateBarsError), - Adj(RunCurateAdjError), - CorporateActions(RunCurateCorporateActionsError), - Fx(RunCurateFxError), - Shorts(RunCurateShortsError), - Events(RunCurateEventsError), -} - -impl fmt::Display for RunMongoCurateError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Mongo(e) => write!(f, "{e}"), - Self::Bars(e) => write!(f, "{e}"), - Self::Adj(e) => write!(f, "{e}"), - Self::CorporateActions(e) => write!(f, "{e}"), - Self::Fx(e) => write!(f, "{e}"), - Self::Shorts(e) => write!(f, "{e}"), - Self::Events(e) => write!(f, "{e}"), - } - } -} - -impl Error for RunMongoCurateError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::Mongo(e) => Some(e), - Self::Bars(e) => Some(e), - Self::Adj(e) => Some(e), - Self::CorporateActions(e) => Some(e), - Self::Fx(e) => Some(e), - Self::Shorts(e) => Some(e), - Self::Events(e) => Some(e), - } - } -} - -/// Parsed arguments for `curate-bars-1d --from-mongo`. -#[derive(Debug, Clone, PartialEq)] -pub struct CurateBars1dMongoArgs { - pub mongo: MongoCliOptions, - pub with_qm_prices: bool, - pub provider_mapping: PathBuf, - pub listing_currencies: PathBuf, - pub out_dir: PathBuf, - pub rel_tolerance: f64, - pub threads: usize, -} - -/// Parsed arguments for `curate-adj-factors --from-mongo`. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct CurateAdjFactorsMongoArgs { - pub mongo: MongoCliOptions, - pub provider_mapping: PathBuf, - pub bars_1d_dir: PathBuf, - pub out_dir: PathBuf, - pub fence: Option, -} - -/// Parsed arguments for `curate-corporate-actions --from-mongo`. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct CurateCorporateActionsMongoArgs { - pub mongo: MongoCliOptions, - pub provider_mapping: PathBuf, - pub delistings: Option, - pub out_dir: PathBuf, -} - -/// Parsed arguments for `curate-fx-1d --from-mongo`. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct CurateFx1dMongoArgs { - pub mongo: MongoCliOptions, - pub te_symbol: String, - pub out_dir: PathBuf, -} - -/// Parsed arguments for `curate-shorts --from-mongo`. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct CurateShortsMongoArgs { - pub mongo: MongoCliOptions, - pub provider_mapping: PathBuf, - pub out_dir: PathBuf, - pub key_field: String, - pub report_date_field: String, - pub shares_short_field: String, - pub net_change_field: Option, - pub pct_float_field: Option, - pub mapping_source: String, -} - -/// Parsed arguments for `curate-events --from-mongo`. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct CurateEventsMongoArgs { - pub mongo: MongoCliOptions, - pub provider_mapping: PathBuf, - pub out_dir: PathBuf, - pub filings_key_field: String, - pub filings_timefiled_field: String, - pub filings_form_type_field: String, - pub filings_filing_id_field: Option, - pub filings_url_field: Option, - pub earnings_key_field: String, - pub earnings_report_date_field: String, - pub earnings_announce_time_field: String, - pub earnings_fiscal_period_end_field: Option, - pub earnings_actual_eps_field: Option, - pub earnings_revenue_field: Option, - pub mapping_source: String, -} - -fn mongo_virtual_path(collection: SourceCollection) -> PathBuf { - PathBuf::from(format!("mongodb://{}", collection.as_str())) -} - -fn connect_and_validate_specs( - mongo: &MongoCliOptions, - checks: &[(SourceCollection, MongoReadSpec)], -) -> Result { - for (collection, spec) in checks { - spec.validate(*collection) - .map_err(RunMongoCurateError::Mongo)?; - } - mongo.uri_source.connect().map_err(RunMongoCurateError::Mongo) -} - -fn unique_mapping_keys_for_source( - provider_mapping_path: &Path, - source: &str, -) -> Result, RunCurateBarsError> { - let rows = load_provider_mapping_tsv(provider_mapping_path)?; - let mut keys = BTreeSet::new(); - for row in rows { - if row.source == source { - keys.insert(row.source_id); - } - } - Ok(keys.into_iter().collect()) -} - -/// Streams `qmSplits`, `eodPrices`, and optional `qmPrices` directly from read-only MongoDB into -/// `bars_1d/year=YYYY/part.parquet`. -/// -/// Note: `qmSplits` is always read without a date-range filter so cumulative post-bar split -/// factors remain exact even when `--date-gte` / `--date-lt` bounds `eodPrices`. -/// When `--limit` is not set, `eodPrices` and `qmPrices` are streamed in indexed `$in` key chunks -/// from `provider_mapping.tsv` so MongoDB scans only mapped US/CA symbols sequentially. -pub fn run_curate_bars_1d_mongo( - args: &CurateBars1dMongoArgs, -) -> Result { - let splits_spec = MongoReadSpec { - batch_size: args.mongo.batch_size, - ..MongoReadSpec::default() - }; - let eod_spec = args.mongo.to_read_spec(None, true); - let qm_spec = args.mongo.to_read_spec(None, true); - - let mut checks = vec![ - (SourceCollection::QmSplits, splits_spec.clone()), - (SourceCollection::EodPrices, eod_spec.clone()), - ]; - if args.with_qm_prices { - checks.push((SourceCollection::QmPrices, qm_spec.clone())); - } - let client = connect_and_validate_specs(&args.mongo, &checks)?; - - let use_key_chunks = args.mongo.limit.is_none(); - let eod_keys = if use_key_chunks { - unique_mapping_keys_for_source(&args.provider_mapping, "eod") - .map_err(RunMongoCurateError::Bars)? - } else { - Vec::new() - }; - let qm_keys = if use_key_chunks && args.with_qm_prices { - unique_mapping_keys_for_source(&args.provider_mapping, "qm") - .map_err(RunMongoCurateError::Bars)? - } else { - Vec::new() - }; - - let result = { - let splits_reader = client - .open_raw_cursor(SourceCollection::QmSplits, &splits_spec) - .map_err(RunMongoCurateError::Mongo)?; - let splits_path = mongo_virtual_path(SourceCollection::QmSplits); - let eod_path = mongo_virtual_path(SourceCollection::EodPrices); - - if use_key_chunks { - let eod_reader = client - .open_raw_cursor_for_keys(SourceCollection::EodPrices, &eod_spec, &eod_keys, 250) - .map_err(RunMongoCurateError::Mongo)?; - let qm_input = if args.with_qm_prices { - let reader = client - .open_raw_cursor_for_keys(SourceCollection::QmPrices, &qm_spec, &qm_keys, 250) - .map_err(RunMongoCurateError::Mongo)?; - Some((mongo_virtual_path(SourceCollection::QmPrices), reader)) - } else { - None - }; - run_curate_bars_1d_with_readers( - &args.provider_mapping, - &args.listing_currencies, - (&splits_path, splits_reader), - (&eod_path, eod_reader), - qm_input, - &args.out_dir, - args.rel_tolerance, - args.threads, - ) - .map_err(RunMongoCurateError::Bars) - } else { - let eod_reader = client - .open_raw_cursor(SourceCollection::EodPrices, &eod_spec) - .map_err(RunMongoCurateError::Mongo)?; - let qm_input = if args.with_qm_prices { - let reader = client - .open_raw_cursor(SourceCollection::QmPrices, &qm_spec) - .map_err(RunMongoCurateError::Mongo)?; - Some((mongo_virtual_path(SourceCollection::QmPrices), reader)) - } else { - None - }; - run_curate_bars_1d_with_readers( - &args.provider_mapping, - &args.listing_currencies, - (&splits_path, splits_reader), - (&eod_path, eod_reader), - qm_input, - &args.out_dir, - args.rel_tolerance, - args.threads, - ) - .map_err(RunMongoCurateError::Bars) - } - }; - - client.shutdown(); - result -} - -/// Streams `qmSplits` and `qmDividends` directly from read-only MongoDB into -/// `adj_factors/part.parquet` (retrospective or point-in-time fenced). -pub fn run_curate_adj_factors_mongo( - args: &CurateAdjFactorsMongoArgs, -) -> Result { - let splits_spec = args.mongo.to_read_spec(None, true); - let dividends_spec = args.mongo.to_read_spec(None, true); - let client = connect_and_validate_specs( - &args.mongo, - &[ - (SourceCollection::QmSplits, splits_spec.clone()), - (SourceCollection::QmDividends, dividends_spec.clone()), - ], - )?; - - let result = { - let splits_reader = client - .open_raw_cursor(SourceCollection::QmSplits, &splits_spec) - .map_err(RunMongoCurateError::Mongo)?; - let dividends_reader = client - .open_raw_cursor(SourceCollection::QmDividends, ÷nds_spec) - .map_err(RunMongoCurateError::Mongo)?; - - let splits_path = mongo_virtual_path(SourceCollection::QmSplits); - let dividends_path = mongo_virtual_path(SourceCollection::QmDividends); - run_curate_adj_factors_with_readers( - &args.provider_mapping, - &args.bars_1d_dir, - (&splits_path, splits_reader), - (÷nds_path, dividends_reader), - &args.out_dir, - args.fence, - ) - .map_err(RunMongoCurateError::Adj) - }; - - client.shutdown(); - result -} - -/// Streams `qmSplits` and `qmDividends` directly from read-only MongoDB alongside optional -/// Pass 6 `delistings.tsv` into `corporate_actions/part.parquet`. -pub fn run_curate_corporate_actions_mongo( - args: &CurateCorporateActionsMongoArgs, -) -> Result { - let splits_spec = args.mongo.to_read_spec(None, false); - let dividends_spec = args.mongo.to_read_spec(None, false); - let client = connect_and_validate_specs( - &args.mongo, - &[ - (SourceCollection::QmSplits, splits_spec.clone()), - (SourceCollection::QmDividends, dividends_spec.clone()), - ], - )?; - - let result = { - let splits_reader = client - .open_raw_cursor(SourceCollection::QmSplits, &splits_spec) - .map_err(RunMongoCurateError::Mongo)?; - let dividends_reader = client - .open_raw_cursor(SourceCollection::QmDividends, ÷nds_spec) - .map_err(RunMongoCurateError::Mongo)?; - - let splits_path = mongo_virtual_path(SourceCollection::QmSplits); - let dividends_path = mongo_virtual_path(SourceCollection::QmDividends); - run_curate_corporate_actions_with_readers( - &args.provider_mapping, - args.delistings.as_deref(), - (&splits_path, splits_reader), - (÷nds_path, dividends_reader), - &args.out_dir, - ) - .map_err(RunMongoCurateError::CorporateActions) - }; - - client.shutdown(); - result -} - -/// Streams `eodPrices` (`eodSearchCode == "CAD.FOREX"`) and `teMarketData` (`teSymbol == te_symbol`) -/// directly from read-only MongoDB into `fx_1d/part.parquet`. -pub fn run_curate_fx_1d_mongo( - args: &CurateFx1dMongoArgs, -) -> Result { - let eod_spec = args - .mongo - .to_read_spec(Some(EOD_CAD_FOREX_CODE.to_owned()), false); - let te_spec = args.mongo.to_read_spec(Some(args.te_symbol.clone()), false); - let client = connect_and_validate_specs( - &args.mongo, - &[ - (SourceCollection::EodPrices, eod_spec.clone()), - (SourceCollection::TeMarketData, te_spec.clone()), - ], - )?; - - let result = { - let eod_reader = client - .open_raw_cursor(SourceCollection::EodPrices, &eod_spec) - .map_err(RunMongoCurateError::Mongo)?; - let te_reader = client - .open_raw_cursor(SourceCollection::TeMarketData, &te_spec) - .map_err(RunMongoCurateError::Mongo)?; - - let eod_path = mongo_virtual_path(SourceCollection::EodPrices); - let te_path = mongo_virtual_path(SourceCollection::TeMarketData); - run_curate_fx_1d_with_readers( - (&eod_path, eod_reader), - (&te_path, te_reader), - &args.te_symbol, - &args.out_dir, - ) - .map_err(RunMongoCurateError::Fx) - }; - - client.shutdown(); - result -} - -/// Streams `ceoShorts` directly from read-only MongoDB into `shorts/part.parquet`. -pub fn run_curate_shorts_mongo( - args: &CurateShortsMongoArgs, -) -> Result { - let shorts_spec = args.mongo.to_read_spec(None, false); - let client = connect_and_validate_specs( - &args.mongo, - &[(SourceCollection::CeoShorts, shorts_spec.clone())], - )?; - - let fields = CeoShortsFieldNames { - key: args.key_field.as_str(), - report_date: args.report_date_field.as_str(), - shares_short: args.shares_short_field.as_str(), - net_change: args.net_change_field.as_deref(), - pct_float: args.pct_float_field.as_deref(), - }; - - let result = { - let shorts_reader = client - .open_raw_cursor(SourceCollection::CeoShorts, &shorts_spec) - .map_err(RunMongoCurateError::Mongo)?; - let shorts_path = mongo_virtual_path(SourceCollection::CeoShorts); - run_curate_shorts_with_reader( - &args.provider_mapping, - &args.mapping_source, - &fields, - (&shorts_path, shorts_reader), - &args.out_dir, - ) - .map_err(RunMongoCurateError::Shorts) - }; - - client.shutdown(); - result -} - -/// Streams `qmFilings` and `qmEarnings` directly from read-only MongoDB into -/// `events/year=YYYY/part.parquet`. -pub fn run_curate_events_mongo( - args: &CurateEventsMongoArgs, -) -> Result { - let filings_spec = args - .mongo - .to_read_spec_for_collection(SourceCollection::QmFilings, None, true); - let earnings_spec = args - .mongo - .to_read_spec_for_collection(SourceCollection::QmEarnings, None, true); - let client = connect_and_validate_specs( - &args.mongo, - &[ - (SourceCollection::QmFilings, filings_spec.clone()), - (SourceCollection::QmEarnings, earnings_spec.clone()), - ], - )?; - - let filings_fields = QmFilingsFieldNames { - key: args.filings_key_field.as_str(), - timefiled: args.filings_timefiled_field.as_str(), - form_type: args.filings_form_type_field.as_str(), - filing_id: args.filings_filing_id_field.as_deref(), - url: args.filings_url_field.as_deref(), - }; - let earnings_fields = QmEarningsFieldNames { - key: args.earnings_key_field.as_str(), - report_date: args.earnings_report_date_field.as_str(), - announce_time: args.earnings_announce_time_field.as_str(), - fiscal_period_end: args.earnings_fiscal_period_end_field.as_deref(), - actual_eps: args.earnings_actual_eps_field.as_deref(), - revenue: args.earnings_revenue_field.as_deref(), - }; - - let result = { - let filings_reader = client - .open_raw_cursor(SourceCollection::QmFilings, &filings_spec) - .map_err(RunMongoCurateError::Mongo)?; - let earnings_reader = client - .open_raw_cursor(SourceCollection::QmEarnings, &earnings_spec) - .map_err(RunMongoCurateError::Mongo)?; - - let filings_path = mongo_virtual_path(SourceCollection::QmFilings); - let earnings_path = mongo_virtual_path(SourceCollection::QmEarnings); - run_curate_events_with_readers( - &args.provider_mapping, - &args.mapping_source, - &filings_fields, - &earnings_fields, - (&filings_path, filings_reader), - (&earnings_path, earnings_reader), - &args.out_dir, - ) - .map_err(RunMongoCurateError::Events) - }; - - client.shutdown(); - result -} - -/// Formats a virtual path label for diagnostics (keeps `Path` import used cleanly). -#[allow(dead_code)] -fn _assert_path_ref(path: &Path) -> &Path { - path -} diff --git a/tools/curate-etl/src/session_close.rs b/tools/curate-etl/src/session_close.rs index 1969073a..49630836 100644 --- a/tools/curate-etl/src/session_close.rs +++ b/tools/curate-etl/src/session_close.rs @@ -42,37 +42,10 @@ pub const SESSION_CLOSE_MIN_SUPPORTED_DATE: i32 = 2_191; /// Epoch day for `2030-12-31` (inclusive upper bound of [`et_session_close_utc_micros`]). pub const SESSION_CLOSE_MAX_SUPPORTED_DATE: i32 = 22_279; -const MICROS_PER_SECOND: i64 = 1_000_000; -const MICROS_PER_MINUTE: i64 = 60 * MICROS_PER_SECOND; -const MICROS_PER_HOUR: i64 = 3_600 * MICROS_PER_SECOND; -const MICROS_PER_DAY: i64 = 86_400 * MICROS_PER_SECOND; - -/// Inclusive lower bound in UTC microseconds for [`utc_micros_to_et_local`] -/// (`1976-01-01T00:00:00.000000 EST` = `1976-01-01T05:00:00.000000Z`). -pub const SESSION_MIN_SUPPORTED_UTC_MICROS: i64 = - SESSION_CLOSE_MIN_SUPPORTED_DATE as i64 * MICROS_PER_DAY + 5 * MICROS_PER_HOUR; - -/// Inclusive upper bound in UTC microseconds for [`utc_micros_to_et_local`] -/// (`2030-12-31T23:59:59.999999 EST` = `2031-01-01T04:59:59.999999Z`). -pub const SESSION_MAX_SUPPORTED_UTC_MICROS: i64 = - (SESSION_CLOSE_MAX_SUPPORTED_DATE as i64 + 1) * MICROS_PER_DAY + 5 * MICROS_PER_HOUR - 1; - const SUPPORTED_YEAR_COUNT: usize = (SESSION_CLOSE_MAX_SUPPORTED_YEAR - SESSION_CLOSE_MIN_SUPPORTED_YEAR + 1) as usize; -/// Eastern Time (`America/New_York` / `America/Toronto`) calendar date, minute-of-day, and DST -/// state returned by [`utc_micros_to_et_local`]. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct EtLocalDateTime { - /// Local Eastern calendar date as days since `1970-01-01`. - pub session_date: i32, - /// Local Eastern minute of day (`0..=1439`, i.e., `hour * 60 + minute`). - pub minute_of_day: u16, - /// `true` during EDT (`UTC-4`), `false` during EST (`UTC-5`). - pub is_edt: bool, -} - -/// Typed error returned by [`et_session_close_utc_micros`] and [`utc_micros_to_et_local`]. +/// Typed error returned by [`et_session_close_utc_micros`]. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SessionCloseError { /// The requested epoch day fell outside `[SESSION_CLOSE_MIN_SUPPORTED_DATE, SESSION_CLOSE_MAX_SUPPORTED_DATE]`. @@ -81,12 +54,6 @@ pub enum SessionCloseError { min_supported: i32, max_supported: i32, }, - /// The requested UTC timestamp fell outside `[SESSION_MIN_SUPPORTED_UTC_MICROS, SESSION_MAX_SUPPORTED_UTC_MICROS]`. - TimestampOutOfRange { - utc_micros: i64, - min_supported: i64, - max_supported: i64, - }, } impl fmt::Display for SessionCloseError { @@ -100,14 +67,6 @@ impl fmt::Display for SessionCloseError { f, "epoch day {epoch_day} is outside supported session-close range [{min_supported}, {max_supported}] ({SESSION_CLOSE_MIN_SUPPORTED_YEAR}-01-01..={SESSION_CLOSE_MAX_SUPPORTED_YEAR}-12-31)" ), - Self::TimestampOutOfRange { - utc_micros, - min_supported, - max_supported, - } => write!( - f, - "UTC timestamp {utc_micros} us is outside supported Eastern Time range [{min_supported}, {max_supported}] ({SESSION_CLOSE_MIN_SUPPORTED_YEAR}-01-01T05:00:00Z..=2031-01-01T04:59:59.999999Z)" - ), } } } @@ -193,52 +152,6 @@ pub fn et_session_close_utc_micros(epoch_day: i32) -> Result Result { - if !(SESSION_MIN_SUPPORTED_UTC_MICROS..=SESSION_MAX_SUPPORTED_UTC_MICROS).contains(&utc_micros) { - return Err(SessionCloseError::TimestampOutOfRange { - utc_micros, - min_supported: SESSION_MIN_SUPPORTED_UTC_MICROS, - max_supported: SESSION_MAX_SUPPORTED_UTC_MICROS, - }); - } - - // Bounds check above guarantees `est_micros >= 2191 * MICROS_PER_DAY > 0` without overflow. - let est_micros = utc_micros - 5 * MICROS_PER_HOUR; - let est_day = (est_micros / MICROS_PER_DAY) as i32; - let (year, _, _) = epoch_days_to_ymd(est_day); - let (dst_start, dst_end) = dst_bounds()[(year - SESSION_CLOSE_MIN_SUPPORTED_YEAR) as usize]; - - // Spring forward: 02:00:00 EST = 07:00:00 UTC on `dst_start`. - // Fall back: 02:00:00 EDT = 06:00:00 UTC on `dst_end`. - let dst_start_utc = i64::from(dst_start) * MICROS_PER_DAY + 7 * MICROS_PER_HOUR; - let dst_end_utc = i64::from(dst_end) * MICROS_PER_DAY + 6 * MICROS_PER_HOUR; - let is_edt = utc_micros >= dst_start_utc && utc_micros < dst_end_utc; - - let local_micros = if is_edt { - est_micros + MICROS_PER_HOUR - } else { - est_micros - }; - let session_date = (local_micros / MICROS_PER_DAY) as i32; - let rem_micros = local_micros - i64::from(session_date) * MICROS_PER_DAY; - let minute_of_day = (rem_micros / MICROS_PER_MINUTE) as u16; - - Ok(EtLocalDateTime { - session_date, - minute_of_day, - is_edt, - }) -} - #[cfg(test)] mod tests { use super::*; @@ -394,207 +307,4 @@ mod tests { ); } } - - fn utc_micros(y: i32, m: u32, d: u32, h: i64, min: i64, sec: i64, us: i64) -> i64 { - let ep = day(y, m, d); - ((i64::from(ep) * 86_400 + h * 3_600 + min * 60 + sec) * 1_000_000) + us - } - - #[test] - fn utc_micros_to_et_local_round_trips_et_session_close_across_all_supported_days() { - for d in SESSION_CLOSE_MIN_SUPPORTED_DATE..=SESSION_CLOSE_MAX_SUPPORTED_DATE { - let close_utc = et_session_close_utc_micros(d).expect("in-range date"); - let local = utc_micros_to_et_local(close_utc).expect("in-range timestamp"); - assert_eq!(local.session_date, d, "session_date mismatch on day={d}"); - assert_eq!( - local.minute_of_day, - 16 * 60, - "16:00 ET minute mismatch on day={d}" - ); - let expected_edt = - (close_utc - i64::from(d) * MICROS_PER_DAY) == 20 * MICROS_PER_HOUR; - assert_eq!(local.is_edt, expected_edt, "DST flag mismatch on day={d}"); - } - } - - #[test] - fn utc_micros_to_et_local_handles_dst_transitions_across_all_three_eras() { - // (year, spring_month, spring_day, fall_month, fall_day) - let eras = [ - // Era 1 (1976..=1986): last Sun Apr -> last Sun Oct - (1976, 4, 25, 10, 31), - (1986, 4, 27, 10, 26), - // Era 2 (1987..=2006): 1st Sun Apr -> last Sun Oct (including 2003) - (1987, 4, 5, 10, 25), - (2003, 4, 6, 10, 26), - (2006, 4, 2, 10, 29), - // Era 3 (2007..=2030): 2nd Sun Mar -> 1st Sun Nov - (2007, 3, 11, 11, 4), - (2024, 3, 10, 11, 3), - (2030, 3, 10, 11, 3), - ]; - - for (y, sm, sd, fm, fd) in eras { - let spring_day = day(y, sm, sd); - // 06:59:59.999999 UTC -> 01:59:59.999999 EST - let before_spring = utc_micros(y, sm, sd, 6, 59, 59, 999_999); - assert_eq!( - utc_micros_to_et_local(before_spring).unwrap(), - EtLocalDateTime { - session_date: spring_day, - minute_of_day: 60 + 59, - is_edt: false, - }, - "before spring-forward in {y}" - ); - // 07:00:00.000000 UTC -> 03:00:00.000000 EDT (skips 02:xx) - let at_spring = utc_micros(y, sm, sd, 7, 0, 0, 0); - assert_eq!( - utc_micros_to_et_local(at_spring).unwrap(), - EtLocalDateTime { - session_date: spring_day, - minute_of_day: 3 * 60, - is_edt: true, - }, - "at spring-forward in {y}" - ); - - let fall_day = day(y, fm, fd); - // 05:59:59.999999 UTC -> 01:59:59.999999 EDT (first 01:59) - let before_fall = utc_micros(y, fm, fd, 5, 59, 59, 999_999); - assert_eq!( - utc_micros_to_et_local(before_fall).unwrap(), - EtLocalDateTime { - session_date: fall_day, - minute_of_day: 60 + 59, - is_edt: true, - }, - "before fall-back in {y}" - ); - // 06:00:00.000000 UTC -> 01:00:00.000000 EST (repeated 01:00) - let at_fall = utc_micros(y, fm, fd, 6, 0, 0, 0); - assert_eq!( - utc_micros_to_et_local(at_fall).unwrap(), - EtLocalDateTime { - session_date: fall_day, - minute_of_day: 60, - is_edt: false, - }, - "at fall-back in {y}" - ); - } - } - - #[test] - fn utc_micros_to_et_local_handles_utc_vs_et_midnight_crossovers() { - // Summer (EDT, UTC-4): 2024-06-10 00:30 UTC == 2024-06-09 20:30 EDT (previous calendar day) - assert_eq!( - utc_micros_to_et_local(utc_micros(2024, 6, 10, 0, 30, 0, 0)).unwrap(), - EtLocalDateTime { - session_date: day(2024, 6, 9), - minute_of_day: 20 * 60 + 30, - is_edt: true, - } - ); - // 2024-06-10 03:59:59.999999 UTC == 2024-06-09 23:59 EDT - assert_eq!( - utc_micros_to_et_local(utc_micros(2024, 6, 10, 3, 59, 59, 999_999)).unwrap(), - EtLocalDateTime { - session_date: day(2024, 6, 9), - minute_of_day: 23 * 60 + 59, - is_edt: true, - } - ); - // 2024-06-10 04:00:00.000000 UTC == 2024-06-10 00:00 EDT - assert_eq!( - utc_micros_to_et_local(utc_micros(2024, 6, 10, 4, 0, 0, 0)).unwrap(), - EtLocalDateTime { - session_date: day(2024, 6, 10), - minute_of_day: 0, - is_edt: true, - } - ); - - // Winter (EST, UTC-5): 2025-01-16 00:30 UTC == 2025-01-15 19:30 EST - assert_eq!( - utc_micros_to_et_local(utc_micros(2025, 1, 16, 0, 30, 0, 0)).unwrap(), - EtLocalDateTime { - session_date: day(2025, 1, 15), - minute_of_day: 19 * 60 + 30, - is_edt: false, - } - ); - // 2025-01-16 04:59:59.999999 UTC == 2025-01-15 23:59 EST - assert_eq!( - utc_micros_to_et_local(utc_micros(2025, 1, 16, 4, 59, 59, 999_999)).unwrap(), - EtLocalDateTime { - session_date: day(2025, 1, 15), - minute_of_day: 23 * 60 + 59, - is_edt: false, - } - ); - // 2025-01-16 05:00:00.000000 UTC == 2025-01-16 00:00 EST - assert_eq!( - utc_micros_to_et_local(utc_micros(2025, 1, 16, 5, 0, 0, 0)).unwrap(), - EtLocalDateTime { - session_date: day(2025, 1, 16), - minute_of_day: 0, - is_edt: false, - } - ); - } - - #[test] - fn utc_micros_to_et_local_bounds_and_out_of_range_errors() { - // Exact inclusive bounds - assert_eq!( - SESSION_MIN_SUPPORTED_UTC_MICROS, - utc_micros(1976, 1, 1, 5, 0, 0, 0) - ); - assert_eq!( - SESSION_MAX_SUPPORTED_UTC_MICROS, - utc_micros(2031, 1, 1, 4, 59, 59, 999_999) - ); - assert_eq!( - utc_micros_to_et_local(SESSION_MIN_SUPPORTED_UTC_MICROS).unwrap(), - EtLocalDateTime { - session_date: SESSION_CLOSE_MIN_SUPPORTED_DATE, - minute_of_day: 0, - is_edt: false, - } - ); - assert_eq!( - utc_micros_to_et_local(SESSION_MAX_SUPPORTED_UTC_MICROS).unwrap(), - EtLocalDateTime { - session_date: SESSION_CLOSE_MAX_SUPPORTED_DATE, - minute_of_day: 23 * 60 + 59, - is_edt: false, - } - ); - - let bad_ts = [ - SESSION_MIN_SUPPORTED_UTC_MICROS - 1, - SESSION_MAX_SUPPORTED_UTC_MICROS + 1, - 0, - i64::MIN, - i64::MAX, - ]; - for ts in bad_ts { - let err = utc_micros_to_et_local(ts).unwrap_err(); - assert_eq!( - err, - SessionCloseError::TimestampOutOfRange { - utc_micros: ts, - min_supported: SESSION_MIN_SUPPORTED_UTC_MICROS, - max_supported: SESSION_MAX_SUPPORTED_UTC_MICROS, - } - ); - assert!(err.source().is_none()); - let msg = err.to_string(); - assert!( - msg.contains(&ts.to_string()) && msg.contains("1976-01-01T05:00:00Z"), - "unexpected Display message: {msg}" - ); - } - } } diff --git a/tools/curate-etl/src/tsv_fixture_tests.rs b/tools/curate-etl/src/tsv_fixture_tests.rs deleted file mode 100644 index 8512761d..00000000 --- a/tools/curate-etl/src/tsv_fixture_tests.rs +++ /dev/null @@ -1,359 +0,0 @@ -//! Cross-language golden fixture tests verifying that TSV files emitted by the TypeScript -//! security-master exporter (`apps/stock/data-pipeline/src/security-master/export-curate-inputs.ts`) -//! load cleanly through the real Rust TSV loaders and curate with zero drops. - -use std::fs; -use std::path::{Path, PathBuf}; -use std::time::{SystemTime, UNIX_EPOCH}; - -use crate::bson_eod_prices::parse_ymd_strict_days; -use crate::cli::{parse_args, CliAction}; -use crate::corporate_actions::{CorporateActionKind, DividendActionEvent, SplitActionEvent}; -use crate::curate_corporate_actions::curate_corporate_actions; -use crate::provider_mapping::ProviderMappingTable; -use crate::run_curate_bars::{load_listing_currencies_tsv, load_provider_mapping_tsv}; -use crate::run_curate_corporate_actions::{load_delistings_tsv, run_curate_corporate_actions}; - -fn fixture_dir() -> PathBuf { - PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("tests") - .join("fixtures") - .join("curate-inputs") -} - -#[test] -fn loads_ts_golden_curate_inputs_and_curates_delistings_with_zero_drops() { - let dir = fixture_dir(); - - // 1. Load provider_mapping.tsv and build ProviderMappingTable. - let pm_rows = load_provider_mapping_tsv(&dir.join("provider_mapping.tsv")) - .expect("provider_mapping.tsv fixture should load"); - assert_eq!(pm_rows.len(), 16); - let mapping = ProviderMappingTable::from_rows(pm_rows) - .expect("provider_mapping.tsv fixture should build a valid ProviderMappingTable"); - - let fb_old_date = parse_ymd_strict_days("2022-06-08").unwrap(); - let fb_new_date = parse_ymd_strict_days("2022-06-09").unwrap(); - assert_eq!(mapping.resolve("eod", "FB.US", fb_old_date), Some(2)); - assert_eq!(mapping.resolve("eod", "FB.US", fb_new_date), Some(3)); - assert_eq!(mapping.resolve("qm", "SHOP:CA", fb_new_date), Some(8)); - - // 2. Load listing_currencies.tsv. - let currencies = load_listing_currencies_tsv(&dir.join("listing_currencies.tsv")) - .expect("listing_currencies.tsv fixture should load"); - assert_eq!(currencies.len(), 8); - assert_eq!(currencies.get(&1).map(|c| c.as_ref()), Some("USD")); - assert_eq!(currencies.get(&6).map(|c| c.as_ref()), Some("USD")); - assert_eq!(currencies.get(&8).map(|c| c.as_ref()), Some("CAD")); - - // 3. Load delistings.tsv and run curate_corporate_actions against "qm". - let delistings = load_delistings_tsv(&dir.join("delistings.tsv")) - .expect("delistings.tsv fixture should load"); - assert_eq!(delistings.len(), 3); - - let curated = curate_corporate_actions( - Vec::<(String, SplitActionEvent)>::new(), - Vec::<(String, DividendActionEvent)>::new(), - delistings, - "qm", - &mapping, - ) - .expect("curate_corporate_actions should succeed on golden fixtures"); - - assert_eq!(curated.stats.rows_in, 3); - assert_eq!(curated.stats.rows_out, 3); - assert_eq!(curated.stats.dropped_unmapped, 0); - assert_eq!(curated.stats.dropped_unmapped_successor, 0); - assert_eq!(curated.stats.dropped_self_successor, 0); - assert_eq!(curated.stats.dropped_known_at_out_of_range, 0); - assert_eq!(curated.stats.listing_collision_collapsed, 0); - assert_eq!(curated.stats.listing_collision_dropped, 0); - - // Curated rows are sorted by (listing_id, ex_date, kind): - // listing 4: SIVB -> SIVBQ OTC transfer on 2023-03-28 (despite SIVB reuse on 2023-03-20!) - // listing 6: SIVBQ bankruptcy cancellation (-1.0) on 2024-11-07 - // listing 7: DEL30 Shumway terminal delisting (-0.3) on 2023-06-15 - assert_eq!(curated.rows.len(), 3); - - let otc = &curated.rows[0]; - assert_eq!(otc.listing_id, 4); - assert_eq!(otc.ex_date, parse_ymd_strict_days("2023-03-28").unwrap()); - assert_eq!(otc.kind, CorporateActionKind::OtcDelistTransfer); - assert_eq!(otc.successor_listing_id, Some(6)); - assert_eq!(otc.terminal_return, None); - - let sivbq_term = &curated.rows[1]; - assert_eq!(sivbq_term.listing_id, 6); - assert_eq!(sivbq_term.ex_date, parse_ymd_strict_days("2024-11-07").unwrap()); - assert_eq!(sivbq_term.kind, CorporateActionKind::Delisting); - assert_eq!(sivbq_term.successor_listing_id, None); - assert_eq!(sivbq_term.terminal_return, Some(-1.0)); - - let del30_term = &curated.rows[2]; - assert_eq!(del30_term.listing_id, 7); - assert_eq!(del30_term.ex_date, parse_ymd_strict_days("2023-06-15").unwrap()); - assert_eq!(del30_term.kind, CorporateActionKind::Delisting); - assert_eq!(del30_term.successor_listing_id, None); - assert_eq!(del30_term.terminal_return, Some(-0.3)); -} - -#[cfg(unix)] -fn make_temp_dir(prefix: &str) -> PathBuf { - let nanos = SystemTime::now() - .duration_since(UNIX_EPOCH) - .expect("system clock after epoch") - .as_nanos(); - let dir = std::env::temp_dir().join(format!("{prefix}-{}-{nanos}", std::process::id())); - fs::create_dir_all(&dir).expect("create temp dir"); - dir -} - -#[cfg(unix)] -fn atomic_swap_current_link(inputs_dir: &Path, relative_gen: &str) { - use std::os::unix::fs::symlink; - let tmp = inputs_dir.join(format!(".current.swap.{}.tmp", std::process::id())); - let _ = fs::remove_file(&tmp); - symlink(relative_gen, &tmp).expect("create temp current symlink"); - fs::rename(&tmp, inputs_dir.join("current")).expect("atomically swap current symlink"); -} - -#[cfg(unix)] -#[test] -fn curate_corporate_actions_with_curate_inputs_pins_generation_across_refresh() { - use std::os::unix::fs::symlink; - - let root = make_temp_dir("curate-inputs-pin-ca"); - let inputs_dir = root.join("curate-inputs"); - let gen1 = inputs_dir.join("generations").join("gen-1"); - let gen2 = inputs_dir.join("generations").join("gen-2"); - fs::create_dir_all(&gen1).unwrap(); - fs::create_dir_all(&gen2).unwrap(); - - // Generation 1: SIVB active only (no SIVBQ successor, empty delistings.tsv). - fs::write( - gen1.join("provider_mapping.tsv"), - "qm\tSIVB\t1988-01-04\t\t4\n", - ) - .unwrap(); - fs::write(gen1.join("listing_currencies.tsv"), "4\tUSD\n").unwrap(); - fs::write(gen1.join("delistings.tsv"), "").unwrap(); - - // Generation 2: SIVB -> SIVBQ OTC transfer added to both provider_mapping.tsv and delistings.tsv. - fs::write( - gen2.join("provider_mapping.tsv"), - "qm\tSIVB\t1988-01-04\t2023-03-10\t4\nqm\tSIVBQ\t2023-03-28\t\t6\n", - ) - .unwrap(); - fs::write(gen2.join("listing_currencies.tsv"), "4\tUSD\n6\tUSD\n").unwrap(); - fs::write(gen2.join("delistings.tsv"), "SIVB\t2023-03-28\t4\tSIVBQ\t\n").unwrap(); - - symlink("generations/gen-1", inputs_dir.join("current")).unwrap(); - symlink( - "current/provider_mapping.tsv", - inputs_dir.join("provider_mapping.tsv"), - ) - .unwrap(); - symlink( - "current/listing_currencies.tsv", - inputs_dir.join("listing_currencies.tsv"), - ) - .unwrap(); - symlink("current/delistings.tsv", inputs_dir.join("delistings.tsv")).unwrap(); - - let empty_splits = root.join("qmSplits.bson"); - let empty_divs = root.join("qmDividends.bson"); - fs::write(&empty_splits, b"").unwrap(); - fs::write(&empty_divs, b"").unwrap(); - let out1 = root.join("out-1"); - let out2 = root.join("out-2"); - - // 1. Parse invocation while `current` points to gen-1: pins gen-1 before opening any TSV. - let argv1 = vec![ - "curate-corporate-actions".to_string(), - "--qm-splits".to_string(), - empty_splits.display().to_string(), - "--qm-dividends".to_string(), - empty_divs.display().to_string(), - "--curate-inputs".to_string(), - inputs_dir.display().to_string(), - "--out".to_string(), - out1.display().to_string(), - ]; - let action1 = parse_args(&argv1).expect("parse --curate-inputs on gen-1"); - let CliAction::CurateCorporateActions(args1) = action1 else { - panic!("expected CurateCorporateActions action"); - }; - assert_eq!(args1.provider_mapping, fs::canonicalize(&gen1).unwrap().join("provider_mapping.tsv")); - assert_eq!( - args1.delistings, - Some(fs::canonicalize(&gen1).unwrap().join("delistings.tsv")) - ); - - // 2. Refresh `current` -> gen-2 BEFORE `run_curate_corporate_actions` opens either TSV! - atomic_swap_current_link(&inputs_dir, "generations/gen-2"); - - // Invocation 1 still reads both TSVs from pinned gen-1 (zero mixed snapshot, zero drops). - let report1 = run_curate_corporate_actions(&args1).expect("run pinned gen-1 after refresh"); - assert_eq!(report1.delistings_rows_loaded, 0); - assert_eq!(report1.curate_stats.dropped_unmapped_successor, 0); - assert_eq!(report1.curate_stats.rows_out, 0); - - // 3. A new invocation after the refresh pins gen-2 and curates SIVB -> SIVBQ with 0 drops. - let argv2 = vec![ - "curate-corporate-actions".to_string(), - "--qm-splits".to_string(), - empty_splits.display().to_string(), - "--qm-dividends".to_string(), - empty_divs.display().to_string(), - "--curate-inputs".to_string(), - inputs_dir.display().to_string(), - "--out".to_string(), - out2.display().to_string(), - ]; - let action2 = parse_args(&argv2).expect("parse --curate-inputs on gen-2"); - let CliAction::CurateCorporateActions(args2) = action2 else { - panic!("expected CurateCorporateActions action"); - }; - let report2 = run_curate_corporate_actions(&args2).expect("run pinned gen-2"); - assert_eq!(report2.delistings_rows_loaded, 1); - assert_eq!(report2.curate_stats.builder.otc_delist_transfers_out, 1); - assert_eq!(report2.curate_stats.dropped_unmapped, 0); - assert_eq!(report2.curate_stats.dropped_unmapped_successor, 0); - assert_eq!(report2.curate_stats.rows_out, 1); - - // 4. Combining --curate-inputs with individual TSV flags is rejected. - let bad_argv = vec![ - "curate-corporate-actions".to_string(), - "--qm-splits".to_string(), - empty_splits.display().to_string(), - "--qm-dividends".to_string(), - empty_divs.display().to_string(), - "--curate-inputs".to_string(), - inputs_dir.display().to_string(), - "--delistings".to_string(), - gen2.join("delistings.tsv").display().to_string(), - "--out".to_string(), - out2.display().to_string(), - ]; - let err = parse_args(&bad_argv).unwrap_err(); - assert!(err.contains("cannot combine '--curate-inputs' with '--delistings'")); - - let _ = fs::remove_dir_all(&root); -} - -#[cfg(unix)] -#[test] -fn curate_bars_1d_with_curate_inputs_pins_generation_across_refresh() { - use std::os::unix::fs::symlink; - - let root = make_temp_dir("curate-inputs-pin-bars"); - let inputs_dir = root.join("curate-inputs"); - let gen1 = inputs_dir.join("generations").join("gen-1"); - let gen2 = inputs_dir.join("generations").join("gen-2"); - fs::create_dir_all(&gen1).unwrap(); - fs::create_dir_all(&gen2).unwrap(); - fs::write(gen1.join("provider_mapping.tsv"), "eod\tAAPL.US\t2020-01-01\t\t1\n").unwrap(); - fs::write(gen1.join("listing_currencies.tsv"), "1\tUSD\n").unwrap(); - fs::write(gen2.join("provider_mapping.tsv"), "eod\tSHOP.TO\t2020-01-01\t\t2\n").unwrap(); - fs::write(gen2.join("listing_currencies.tsv"), "2\tCAD\n").unwrap(); - symlink("generations/gen-1", inputs_dir.join("current")).unwrap(); - - let argv = vec![ - "curate-bars-1d".to_string(), - "--eod-prices".to_string(), - root.join("eodPrices.bson").display().to_string(), - "--qm-splits".to_string(), - root.join("qmSplits.bson").display().to_string(), - "--curate-inputs".to_string(), - inputs_dir.display().to_string(), - "--out".to_string(), - root.join("out").display().to_string(), - ]; - let action1 = parse_args(&argv).expect("parse curate-bars-1d --curate-inputs gen-1"); - let CliAction::CurateBars1d(args1) = action1 else { - panic!("expected CurateBars1d action"); - }; - let canon_gen1 = fs::canonicalize(&gen1).unwrap(); - assert_eq!(args1.provider_mapping, canon_gen1.join("provider_mapping.tsv")); - assert_eq!(args1.listing_currencies, canon_gen1.join("listing_currencies.tsv")); - - // Swap `current` -> gen-2 and verify pinned paths from args1 still load gen-1 consistently. - atomic_swap_current_link(&inputs_dir, "generations/gen-2"); - let pm1 = load_provider_mapping_tsv(&args1.provider_mapping).unwrap(); - let lc1 = load_listing_currencies_tsv(&args1.listing_currencies).unwrap(); - assert_eq!(pm1.len(), 1); - assert_eq!(pm1[0].source_id, "AAPL.US"); - assert_eq!(lc1.get(&1).map(|c| c.as_ref()), Some("USD")); - assert!(!lc1.contains_key(&2)); - - // A subsequent parse pins gen-2. - let action2 = parse_args(&argv).expect("parse curate-bars-1d --curate-inputs gen-2"); - let CliAction::CurateBars1d(args2) = action2 else { - panic!("expected CurateBars1d action"); - }; - let canon_gen2 = fs::canonicalize(&gen2).unwrap(); - assert_eq!(args2.provider_mapping, canon_gen2.join("provider_mapping.tsv")); - assert_eq!(args2.listing_currencies, canon_gen2.join("listing_currencies.tsv")); - - // Combining --curate-inputs with --listing-currencies is rejected. - let mut bad_argv = argv.clone(); - bad_argv.push("--listing-currencies".to_string()); - bad_argv.push(gen2.join("listing_currencies.tsv").display().to_string()); - let err = parse_args(&bad_argv).unwrap_err(); - assert!(err.contains("cannot combine '--curate-inputs' with '--listing-currencies'")); - - let _ = fs::remove_dir_all(&root); -} - -#[cfg(unix)] -#[test] -fn curate_inputs_rejects_flat_directory_without_committed_current_link() { - let root = make_temp_dir("curate-inputs-flat-reject"); - let flat_dir = root.join("flat-inputs"); - fs::create_dir_all(&flat_dir).unwrap(); - fs::write( - flat_dir.join("provider_mapping.tsv"), - "qm\tSIVB\t1988-01-04\t\t4\n", - ) - .unwrap(); - fs::write(flat_dir.join("listing_currencies.tsv"), "4\tUSD\n").unwrap(); - fs::write(flat_dir.join("delistings.tsv"), "").unwrap(); - - let ca_argv = vec![ - "curate-corporate-actions".to_string(), - "--qm-splits".to_string(), - root.join("qmSplits.bson").display().to_string(), - "--qm-dividends".to_string(), - root.join("qmDividends.bson").display().to_string(), - "--curate-inputs".to_string(), - flat_dir.display().to_string(), - "--out".to_string(), - root.join("out-ca").display().to_string(), - ]; - let ca_err = parse_args(&ca_argv).unwrap_err(); - assert!( - ca_err.contains("requires a committed 'current' link"), - "unexpected error for curate-corporate-actions: {ca_err}" - ); - assert!(ca_err.contains("--provider-mapping")); - - let bars_argv = vec![ - "curate-bars-1d".to_string(), - "--eod-prices".to_string(), - root.join("eodPrices.bson").display().to_string(), - "--qm-splits".to_string(), - root.join("qmSplits.bson").display().to_string(), - "--curate-inputs".to_string(), - flat_dir.display().to_string(), - "--out".to_string(), - root.join("out-bars").display().to_string(), - ]; - let bars_err = parse_args(&bars_argv).unwrap_err(); - assert!( - bars_err.contains("requires a committed 'current' link"), - "unexpected error for curate-bars-1d: {bars_err}" - ); - assert!(bars_err.contains("--listing-currencies")); - - let _ = fs::remove_dir_all(&root); -} diff --git a/tools/curate-etl/tests/bars_1m_qa_contract.rs b/tools/curate-etl/tests/bars_1m_qa_contract.rs deleted file mode 100644 index 0ffcc1ef..00000000 --- a/tools/curate-etl/tests/bars_1m_qa_contract.rs +++ /dev/null @@ -1,584 +0,0 @@ -//! QA contract tests for `bars_1m::build_bars_1m` / `check_session_closes` (T-130 / M2.3a). -//! -//! Uses only the public crate API. Expected Eastern session dates and minutes come from how the -//! fixtures are generated (`et_to_utc_micros(date, hh, mm)`), not from `utc_micros_to_et_local`, -//! and expected split factors come from `SplitTable::cum_factor_after`, so the builder's -//! two-pointer split cursor and ET conversion are checked against independent oracles. - -use std::cmp::Ordering; -use std::collections::{HashMap, HashSet}; - -use curate_etl::{ - build_bars_1m, check_session_closes, check_session_closes_against_bars_1d, et_to_utc_micros, - unadjust_ohlcv, ymd_to_epoch_days, Bar1dRow, Bar1mRow, Bars1mStats, DailySessionClose, - EodIntradayBar, IntradaySession, OhlcvBar, SessionCloseCutoffPolicy, SessionCloseStats, - SplitEvent, SplitTable, BARS_1M_SOURCE_EOD, MAX_MISMATCH_SAMPLES, -}; - -/// Deterministic SplitMix64 so every run sees identical fixtures. -struct Rng(u64); - -impl Rng { - fn next_u64(&mut self) -> u64 { - self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); - let mut z = self.0; - z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); - z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); - z ^ (z >> 31) - } - - fn below(&mut self, n: u64) -> u64 { - self.next_u64() % n - } -} - -fn day(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).expect("valid date") -} - -fn et(date: i32, hour: u8, minute: u8) -> i64 { - et_to_utc_micros(date, hour, minute, 0).expect("valid ET timestamp") -} - -fn bar(key: &str, ts: i64, o: f64, h: f64, l: f64, c: f64, v: f64) -> EodIntradayBar { - EodIntradayBar { - key: key.to_string(), - ts, - open: o, - high: h, - low: l, - close: c, - volume: v, - } -} - -fn flat(key: &str, ts: i64, price: f64, volume: f64) -> EodIntradayBar { - bar(key, ts, price, price, price, price, volume) -} - -fn expected_session(minute_of_day: u16) -> IntradaySession { - if minute_of_day < 570 { - IntradaySession::Pre - } else if minute_of_day < 960 { - IntradaySession::Rth - } else { - IntradaySession::Post - } -} - -fn assert_conservation(stats: &Bars1mStats) { - assert_eq!( - stats.bars_in, - stats.rows_out - + stats.dropped_invalid_ohlc - + stats.dropped_inconsistent_ohlc - + stats.dropped_invalid_volume - + stats.dropped_ts_out_of_range - + stats.duplicate_collapsed - + stats.duplicate_conflict_dropped, - "conservation invariant failed: {stats:?}" - ); - assert_eq!( - stats.rows_out, - stats.pre_rows_out + stats.rth_rows_out + stats.post_rows_out - ); -} - -fn assert_close_invariants(stats: &SessionCloseStats) { - assert_eq!( - stats.checked + stats.unchecked, - stats.rth_sessions, - "{stats:?}" - ); - assert_eq!( - stats.within_tolerance + stats.mismatched, - stats.checked, - "{stats:?}" - ); - assert_eq!( - stats.daily_rows_in, - stats.daily_unique_partners - + stats.daily_invalid_close_dropped - + stats.daily_duplicate_collapsed - + stats.daily_duplicate_conflict_dropped, - "{stats:?}" - ); -} - -fn assert_strictly_sorted(rows: &[Bar1mRow]) { - for w in rows.windows(2) { - let ord = w[0].key.cmp(&w[1].key).then_with(|| w[0].ts.cmp(&w[1].ts)); - assert_eq!( - ord, - Ordering::Less, - "rows not strictly sorted: {:?} / {:?}", - w[0], - w[1] - ); - } -} - -#[test] -fn seeded_clean_bars_match_independent_et_and_cum_factor_oracle_bitwise() { - // Arrange: 40 keys, 0-3 splits each (forward/reverse, some on weekends), bars spread across - // 2023-2025 at arbitrary ET minutes (including 00:00 and 23:59) so EST, EDT and DST-transition - // days are all exercised. - let mut rng = Rng(0x0B45_1A11_7E57_0001); - let ratios = [0.05, 0.1, 0.25, 0.5, 2.0, 3.0, 4.0, 10.0, 1.5]; - let min_date = day(2023, 1, 1); - let span = (day(2025, 12, 31) - min_date + 1) as u64; - - let mut events = Vec::new(); - for k in 0..40 { - for _ in 0..rng.below(4) { - events.push(( - format!("K{k:02}"), - SplitEvent { - ex_date: min_date + rng.below(span) as i32, - ratio: ratios[rng.below(ratios.len() as u64) as usize], - }, - )); - } - } - let splits = SplitTable::from_events(events).expect("valid splits"); - - let mut inputs = Vec::new(); - let mut expected: HashMap<(String, i64), (i32, u16, EodIntradayBar)> = HashMap::new(); - while inputs.len() < 5_000 { - let key = format!("K{:02}", rng.below(40)); - let date = min_date + rng.below(span) as i32; - let minute = rng.below(1_440) as u16; - let (hh, mm) = ((minute / 60) as u8, (minute % 60) as u8); - // Skip wall-clock times that do not exist on spring-forward day. - let Ok(ts) = et_to_utc_micros(date, hh, mm, 0) else { - continue; - }; - if expected.contains_key(&(key.clone(), ts)) { - continue; - } - let low = 1.0 + rng.below(10_000) as f64 / 100.0; - let high = low * (1.0 + rng.below(500) as f64 / 10_000.0); - let open = low + (high - low) * 0.25; - let close = low + (high - low) * 0.75; - let volume = rng.below(1_000_000) as f64; - let b = bar(&key, ts, open, high, low, close, volume); - // Fall-back day repeats 01:xx; keep only the first occurrence's ET minute oracle. - expected.insert((key, ts), (date, minute, b.clone())); - inputs.push(b); - } - - // Act - let built = build_bars_1m(inputs.clone(), &splits); - - // Assert - assert_conservation(&built.stats); - assert_eq!(built.stats.rows_out, inputs.len()); - assert_strictly_sorted(&built.rows); - let mut applied_non_unit = 0usize; - for row in &built.rows { - let (date, minute, ref input) = expected[&(row.key.clone(), row.ts)]; - assert_eq!(row.session_date, date, "ET session_date for {row:?}"); - assert_eq!(row.session, expected_session(minute), "session for {row:?}"); - assert_eq!(row.source, BARS_1M_SOURCE_EOD); - let factor = splits.cum_factor_after(row.key.as_str(), date); - if factor != 1.0 { - applied_non_unit += 1; - } - let want = unadjust_ohlcv( - OhlcvBar { - open: input.open, - high: input.high, - low: input.low, - close: input.close, - volume: input.volume, - }, - factor, - ); - assert_eq!(row.open.to_bits(), want.open.to_bits(), "{row:?}"); - assert_eq!(row.high.to_bits(), want.high.to_bits(), "{row:?}"); - assert_eq!(row.low.to_bits(), want.low.to_bits(), "{row:?}"); - assert_eq!(row.close.to_bits(), want.close.to_bits(), "{row:?}"); - assert_eq!(row.volume.to_bits(), want.volume.to_bits(), "{row:?}"); - } - assert!( - applied_non_unit > 500, - "fixture must exercise splits: {applied_non_unit}" - ); -} - -#[test] -fn et_midnight_is_the_split_boundary_not_utc_midnight_in_est_and_edt() { - // Arrange: 2:1 splits; ex-dates in EDT (2024-06-10) and EST (2025-01-16). - for ex in [day(2024, 6, 10), day(2025, 1, 16)] { - let splits = SplitTable::from_events([( - "S".to_string(), - SplitEvent { - ex_date: ex, - ratio: 2.0, - }, - )]) - .unwrap(); - let last_pre_minute = et(ex - 1, 23, 59); - let first_ex_minute = et(ex, 0, 0); - - // Act - let built = build_bars_1m( - [ - flat("S", first_ex_minute, 10.0, 100.0), - flat("S", last_pre_minute, 10.0, 100.0), - ], - &splits, - ); - - // Assert: 23:59 ET (already the next UTC day) still gets the pre-split factor. - assert_conservation(&built.stats); - assert_eq!(built.rows.len(), 2); - assert_eq!(built.rows[0].session_date, ex - 1); - assert_eq!(built.rows[0].session, IntradaySession::Post); - assert_eq!(built.rows[0].close, 20.0); - assert_eq!(built.rows[0].volume, 50.0); - assert_eq!(built.rows[1].session_date, ex); - assert_eq!(built.rows[1].session, IntradaySession::Pre); - assert_eq!(built.rows[1].close.to_bits(), 10.0_f64.to_bits()); - assert_eq!(built.rows[1].volume.to_bits(), 100.0_f64.to_bits()); - } -} - -#[test] -fn cumulative_factor_spans_multiple_splits_and_weekend_ex_dates() { - // Arrange: 2:1 ex Saturday 2024-03-02, then 1:4 reverse ex Monday 2024-03-11. - let splits = SplitTable::from_events([ - ( - "M".to_string(), - SplitEvent { - ex_date: day(2024, 3, 2), - ratio: 2.0, - }, - ), - ( - "M".to_string(), - SplitEvent { - ex_date: day(2024, 3, 11), - ratio: 0.25, - }, - ), - ]) - .unwrap(); - - // Act - let built = build_bars_1m( - [ - flat("M", et(day(2024, 3, 1), 15, 59), 8.0, 1_000.0), // Fri: both splits ahead - flat("M", et(day(2024, 3, 4), 15, 59), 8.0, 1_000.0), // Mon: only reverse ahead - flat("M", et(day(2024, 3, 11), 15, 59), 8.0, 1_000.0), // ex-date of reverse - ], - &splits, - ); - - // Assert: factor 2*0.25 = 0.5, then 0.25, then 1. - assert_conservation(&built.stats); - let closes: Vec = built.rows.iter().map(|r| r.close).collect(); - let volumes: Vec = built.rows.iter().map(|r| r.volume).collect(); - assert_eq!(closes, vec![4.0, 2.0, 8.0]); - assert_eq!(volumes, vec![2_000.0, 4_000.0, 1_000.0]); -} - -#[test] -fn rth_boundaries_hold_on_dst_transition_sundays() { - // Arrange: spring-forward 2024-03-10 and fall-back 2024-11-03 (EDT->EST). - let splits: SplitTable = SplitTable::default(); - let mut inputs = Vec::new(); - for d in [day(2024, 3, 10), day(2024, 11, 3)] { - for (h, m) in [(9, 29), (9, 30), (15, 59), (16, 0)] { - inputs.push(flat("D", et(d, h, m), 10.0, 1.0)); - } - } - - // Act - let built = build_bars_1m(inputs, &splits); - - // Assert - let sessions: Vec<&str> = built.rows.iter().map(|r| r.session.as_str()).collect(); - assert_eq!( - sessions, - vec!["PRE", "RTH", "RTH", "POST", "PRE", "RTH", "RTH", "POST"] - ); -} - -#[test] -fn seeded_dirty_input_conserves_counts_and_is_permutation_invariant() { - // Arrange: mix of valid bars, every bad-row category, exact and conflicting duplicates. - let mut rng = Rng(0x0B45_1A11_D127_0002); - let splits = SplitTable::from_events([ - ( - "A".to_string(), - SplitEvent { - ex_date: day(2024, 6, 10), - ratio: 10.0, - }, - ), - ( - "B".to_string(), - SplitEvent { - ex_date: day(2024, 6, 12), - ratio: 0.05, - }, - ), - ]) - .unwrap(); - let keys = ["A", "B", "C"]; - let base = et(day(2024, 6, 7), 4, 0); - let mut inputs = Vec::new(); - for _ in 0..3_000 { - let key = keys[rng.below(3) as usize]; - let ts = base + rng.below(8 * 1_440) as i64 * 60_000_000; - let p = 10.0 + rng.below(100) as f64 / 10.0; - let b = match rng.below(12) { - 0 => bar(key, ts, f64::NAN, p, p, p, 1.0), - 1 => bar(key, ts, p, p, p, -p, 1.0), - 2 => bar(key, ts, p, p - 1.0, p, p, 1.0), - 3 => bar(key, ts, p, p, p, p, f64::NEG_INFINITY), - 4 => bar(key, i64::MAX - rng.below(10) as i64, p, p, p, p, 1.0), - 5 => bar(key, ts, p, p, p, p, -0.0), - _ => bar(key, ts, p, p + 0.5, p - 0.5, p, rng.below(1_000) as f64), - }; - inputs.push(b.clone()); - // ~10% exact duplicates, ~5% conflicting duplicates. - match rng.below(20) { - 0 | 1 => inputs.push(b), - 2 => { - let mut c = b; - c.volume += 1.0; - inputs.push(c); - } - _ => {} - } - } - - // Act - let forward = build_bars_1m(inputs.clone(), &splits); - let mut shuffled = inputs.clone(); - for i in (1..shuffled.len()).rev() { - shuffled.swap(i, rng.below(i as u64 + 1) as usize); - } - let permuted = build_bars_1m(shuffled, &splits); - - // Assert - assert_conservation(&forward.stats); - assert_eq!(forward, permuted, "output must not depend on input order"); - assert_strictly_sorted(&forward.rows); - for counter in [ - forward.stats.dropped_invalid_ohlc, - forward.stats.dropped_inconsistent_ohlc, - forward.stats.dropped_invalid_volume, - forward.stats.dropped_ts_out_of_range, - forward.stats.duplicate_collapsed, - forward.stats.duplicate_conflict_dropped, - ] { - assert!( - counter > 0, - "every category must be exercised: {:?}", - forward.stats - ); - } - let unique: HashSet<(String, i64)> = - forward.rows.iter().map(|r| (r.key.clone(), r.ts)).collect(); - assert_eq!(unique.len(), forward.rows.len()); - assert!(forward - .rows - .iter() - .all(|r| r.volume.to_bits() != (-0.0_f64).to_bits())); -} - -#[test] -fn keys_out_ignores_keys_whose_every_bar_is_dropped() { - let splits: SplitTable = SplitTable::default(); - let ts = et(day(2024, 6, 10), 10, 0); - let built = build_bars_1m( - [ - flat("GONE", ts, 10.0, 1.0), - flat("GONE", ts, 10.5, 1.0), // conflict drops the whole group - flat("NAN", ts, f64::NAN, 1.0), - flat("KEEP", ts, 10.0, 1.0), - ], - &splits, - ); - assert_conservation(&built.stats); - assert_eq!(built.stats.keys_out, 1); - assert_eq!(built.rows.len(), 1); - assert_eq!(built.rows[0].key, "KEEP"); -} - -#[test] -fn session_close_tolerance_is_inclusive_and_zero_tolerance_is_accepted() { - let d = day(2024, 6, 10); - let splits: SplitTable = SplitTable::default(); - let built = build_bars_1m([flat("T", et(d, 15, 59), 100.5, 1.0)], &splits); - let daily = [DailySessionClose::new("T".to_string(), d, 100.0)]; - - // rel == 0.5 / 100 == 0.005 exactly -> within tolerance. - let at_edge = check_session_closes(&built.rows, daily.clone(), 0.005).unwrap(); - assert_close_invariants(&at_edge.stats); - assert_eq!(at_edge.stats.within_tolerance, 1); - assert_eq!(at_edge.stats.mismatched, 0); - - let zero = check_session_closes(&built.rows, daily.clone(), 0.0).unwrap(); - assert_eq!(zero.stats.mismatched, 1); - let neg_zero = check_session_closes(&built.rows, daily, -0.0).unwrap(); - assert_eq!(neg_zero.stats.mismatched, 1); -} - -#[test] -fn daily_partner_without_intraday_rows_and_post_only_sessions_are_not_rth_sessions() { - let d1 = day(2024, 6, 10); - let d2 = day(2024, 6, 11); - let splits: SplitTable = SplitTable::default(); - let built = build_bars_1m( - [ - flat("X", et(d1, 15, 59), 50.0, 1.0), - flat("X", et(d2, 16, 30), 99.0, 1.0), // POST only - ], - &splits, - ); - let rows_1d = [ - Bar1dRow { - key: "X".to_string(), - session_date: d1, - open: 50.0, - high: 50.0, - low: 50.0, - close: 50.0, - volume: 1.0, - }, - Bar1dRow { - key: "X".to_string(), - session_date: d2, - open: 50.0, - high: 50.0, - low: 50.0, - close: 50.0, - volume: 1.0, - }, - Bar1dRow { - key: "Y".to_string(), - session_date: d1, - open: 7.0, - high: 7.0, - low: 7.0, - close: 7.0, - volume: 1.0, - }, - ]; - let check = check_session_closes_against_bars_1d( - &built.rows, - &rows_1d, - &SessionCloseCutoffPolicy::standard_rth(), - 0.005, - ) - .unwrap(); - assert_close_invariants(&check.stats); - assert_eq!(check.stats.rth_sessions, 1); - assert_eq!(check.stats.checked, 1); - assert_eq!(check.stats.within_tolerance, 1); - assert_eq!(check.stats.daily_unique_partners, 3); -} - -#[test] -fn early_close_date_cutoff_applies_to_listings_without_override() { - // Arrange: Friday after US Thanksgiving 2024 (13:00 ET close); policy sets only a date cutoff. - let d = day(2024, 11, 29); - let splits: SplitTable = SplitTable::default(); - let built = build_bars_1m( - [ - flat("U", et(d, 12, 59), 40.0, 1.0), - flat("U", et(d, 13, 15), 44.0, 1.0), - flat("V", et(d, 12, 59), 70.0, 1.0), - flat("V", et(d, 15, 59), 77.0, 1.0), - ], - &splits, - ); - let policy = SessionCloseCutoffPolicy::standard_rth().with_date_cutoff(d, et(d, 13, 0)); - let rows_1d = [ - Bar1dRow { - key: "U".to_string(), - session_date: d, - open: 40.0, - high: 40.0, - low: 40.0, - close: 40.0, - volume: 1.0, - }, - Bar1dRow { - key: "V".to_string(), - session_date: d, - open: 70.0, - high: 70.0, - low: 70.0, - close: 70.0, - volume: 1.0, - }, - ]; - - // Act - let check = check_session_closes_against_bars_1d(&built.rows, rows_1d, &policy, 0.005).unwrap(); - - // Assert: both listings resolve to their 12:59 ET bar. - assert_close_invariants(&check.stats); - assert_eq!(check.stats.checked, 2); - assert_eq!(check.stats.mismatched, 0); - assert_eq!(check.stats.max_rel_diff, 0.0); -} - -#[test] -fn split_fixture_cross_check_is_order_independent_and_samples_are_capped() { - // Arrange: 150 sessions on one 1:20 reverse-split key; feed adjusted (empty split table) and - // un-adjusted builds against the same raw daily closes. - let ex = day(2025, 6, 18); - let splits = SplitTable::from_events([( - "NEXM.V".to_string(), - SplitEvent { - ex_date: ex, - ratio: 0.05, - }, - )]) - .unwrap(); - let empty: SplitTable = SplitTable::default(); - let mut bars = Vec::new(); - let mut daily = Vec::new(); - for i in 0..150 { - let d = ex - 150 + i; - let adj_close = 20.0 + f64::from(i) * 0.01; - bars.push(flat("NEXM.V", et(d, 15, 59), adj_close, 1_000.0)); - bars.push(flat("NEXM.V", et(d, 16, 5), adj_close * 1.1, 10.0)); // POST noise - daily.push(DailySessionClose::new( - "NEXM.V".to_string(), - d, - adj_close * 0.05, - )); - } - - // Act - let unadj = build_bars_1m(bars.clone(), &splits); - let still_adj = build_bars_1m(bars, &empty); - let good = check_session_closes(&unadj.rows, daily.clone(), 0.005).unwrap(); - let bad = check_session_closes(&still_adj.rows, daily.clone(), 0.005).unwrap(); - let mut reversed = still_adj.rows.clone(); - reversed.reverse(); - let bad_reversed = check_session_closes(&reversed, daily, 0.005).unwrap(); - - // Assert - assert_close_invariants(&good.stats); - assert_eq!(good.stats.checked, 150); - assert_eq!(good.stats.mismatched, 0); - assert!(good.stats.max_rel_diff < 1e-12); - - assert_close_invariants(&bad.stats); - assert_eq!(bad.stats.mismatched, 150); - assert!(bad.stats.max_rel_diff > 0.005); - assert_eq!(bad.mismatch_samples.len(), MAX_MISMATCH_SAMPLES); - assert_eq!(bad, bad_reversed); - for s in &bad.mismatch_samples { - assert!((s.rel - 19.0).abs() < 1e-9, "rel {s:?}"); - assert_eq!(s.last_rth_ts, et(s.session_date, 15, 59)); - } -} diff --git a/tools/curate-etl/tests/bson_eod_intraday_qa_contract.rs b/tools/curate-etl/tests/bson_eod_intraday_qa_contract.rs deleted file mode 100644 index 5fe00412..00000000 --- a/tools/curate-etl/tests/bson_eod_intraday_qa_contract.rs +++ /dev/null @@ -1,438 +0,0 @@ -//! QA contract tests for the public `eodIntraday1M` raw BSON decoder (T-141 / M2.3d). -//! -//! Covers gaps left by the in-crate `bson_eod_intraday_tests.rs`, using only the public API: -//! - field-order independence, case-sensitive keys, nested look-alike keys ignored; -//! - error precedence: corrupt skipped payload beats an earlier semantic error, and the first -//! semantic error in document order wins over later ones; -//! - timestamp edge values (`i32::MAX`, subnormal / half-second / huge doubles); -//! - `Display` names the offending field; empty buffer; `i32::MAX` declared length; -//! - seeded byte-mutation fuzz: never panics, conservation always holds, every buffer row equals -//! the single-document decode of the same frame, and the stream decode reproduces the buffer -//! rows, per-document errors, and terminal framing offset; -//! - stream: empty input, `max_doc_bytes` overflow, and invalid options; -//! - UTC bar-start micros map to the right `build_bars_1m` session date across the UTC midnight. - -use std::io::{self, Cursor, Read}; - -use bson::raw::{cstr, RawBsonRef, RawDocumentBuf}; -use curate_etl::{ - build_bars_1m, decode_eod_intraday_buffer, decode_eod_intraday_bytes, - decode_eod_intraday_doc, decode_eod_intraday_stream, iter_raw_bson_docs, ymd_to_epoch_days, - BsonEodIntradayDecodeStats, BsonEodIntradayError, BsonStreamError, BsonStreamOptions, - RawEodIntradayBar, SplitTable, -}; - -const TS: i64 = 1_717_767_000; - -struct SplitMix64(u64); - -impl SplitMix64 { - fn next_u64(&mut self) -> u64 { - self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); - let mut z = self.0; - z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); - z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); - z ^ (z >> 31) - } -} - -/// Reader returning seeded pseudo-random short reads of 1..=61 bytes. -struct JitterReader<'a> { - data: &'a [u8], - pos: usize, - rng: SplitMix64, -} - -impl Read for JitterReader<'_> { - fn read(&mut self, buf: &mut [u8]) -> io::Result { - let remaining = self.data.len() - self.pos; - if remaining == 0 { - return Ok(0); - } - let step = (self.rng.next_u64() % 61) as usize + 1; - let take = remaining.min(step).min(buf.len()); - buf[..take].copy_from_slice(&self.data[self.pos..self.pos + take]); - self.pos += take; - Ok(take) - } -} - -fn valid_doc(code: &str, ts: i64, close: f64, volume: f64) -> RawDocumentBuf { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("symbol"), "X"); - doc.append(cstr!("eodSearchCode"), code); - doc.append(cstr!("datetime"), "2024-06-07 13:30:00"); - doc.append(cstr!("timestamp"), ts); - doc.append(cstr!("gmtoffset"), 0_i32); - doc.append(cstr!("open"), close - 0.25); - doc.append(cstr!("high"), close + 0.5); - doc.append(cstr!("low"), close - 0.5); - doc.append(cstr!("close"), close); - doc.append(cstr!("volume"), volume); - doc -} - -fn with_timestamp(ts: RawBsonRef<'_>) -> RawDocumentBuf { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), "NVDA.US"); - doc.append(cstr!("timestamp"), ts); - doc.append(cstr!("open"), 10.0_f64); - doc.append(cstr!("high"), 11.0_f64); - doc.append(cstr!("low"), 9.0_f64); - doc.append(cstr!("close"), 10.5_f64); - doc.append(cstr!("volume"), 1.0_f64); - doc -} - -type Row = (String, i64, [u64; 5]); - -fn row(b: RawEodIntradayBar<'_>) -> Row { - ( - b.eod_search_code.to_owned(), - b.ts, - [ - b.open.to_bits(), - b.high.to_bits(), - b.low.to_bits(), - b.close.to_bits(), - b.volume.to_bits(), - ], - ) -} - -#[test] -fn field_order_does_not_change_the_decoded_bar() { - let forward = valid_doc("NVDA.US", TS, 120.5, 1_000.0); - let mut reversed = RawDocumentBuf::new(); - reversed.append(cstr!("volume"), 1_000.0_f64); - reversed.append(cstr!("close"), 120.5_f64); - reversed.append(cstr!("low"), 120.0_f64); - reversed.append(cstr!("high"), 121.0_f64); - reversed.append(cstr!("open"), 120.25_f64); - reversed.append(cstr!("timestamp"), TS); - reversed.append(cstr!("eodSearchCode"), "NVDA.US"); - - assert_eq!( - decode_eod_intraday_doc(&forward).unwrap(), - decode_eod_intraday_doc(&reversed).unwrap() - ); -} - -#[test] -fn keys_are_case_sensitive_and_nested_look_alikes_are_ignored() { - // `Timestamp` (capital T) is not `timestamp`; a nested `timestamp` must not satisfy it either. - let mut nested = RawDocumentBuf::new(); - nested.append(cstr!("timestamp"), TS); - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), "NVDA.US"); - doc.append(cstr!("Timestamp"), TS); - doc.append(cstr!("meta"), RawBsonRef::Document(nested.as_ref())); - doc.append(cstr!("open"), 10.0_f64); - doc.append(cstr!("high"), 11.0_f64); - doc.append(cstr!("low"), 9.0_f64); - doc.append(cstr!("close"), 10.5_f64); - doc.append(cstr!("volume"), 1.0_f64); - - assert_eq!( - decode_eod_intraday_doc(&doc), - Err(BsonEodIntradayError::MissingField { field: "timestamp" }) - ); -} - -#[test] -fn eod_search_code_is_borrowed_verbatim_without_trimming() { - let doc = valid_doc(" NVDA.US ", TS, 10.0, 1.0); - let bar = decode_eod_intraday_bytes(doc.as_bytes()).unwrap(); - assert_eq!(bar.eod_search_code, " NVDA.US "); -} - -#[test] -fn first_semantic_error_in_document_order_wins() { - // close is invalid before eodSearchCode is blank: close error must be reported. - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("close"), -1.0_f64); - doc.append(cstr!("eodSearchCode"), ""); - doc.append(cstr!("timestamp"), -5_i64); - doc.append(cstr!("open"), 10.0_f64); - doc.append(cstr!("high"), 11.0_f64); - doc.append(cstr!("low"), 9.0_f64); - doc.append(cstr!("volume"), 1.0_f64); - - match decode_eod_intraday_doc(&doc) { - Err(BsonEodIntradayError::InvalidNumber { field: "close", value }) => { - assert_eq!(value, -1.0) - } - other => panic!("expected InvalidNumber(close), got {other:?}"), - } - - // A semantic error plus a missing field: the semantic error wins over MissingField. - let mut doc2 = RawDocumentBuf::new(); - doc2.append(cstr!("eodSearchCode"), "NVDA.US"); - doc2.append(cstr!("timestamp"), RawBsonRef::Null); - assert!(matches!( - decode_eod_intraday_doc(&doc2), - Err(BsonEodIntradayError::WrongType { field: "timestamp", .. }) - )); -} - -#[test] -fn corrupt_skipped_payload_after_semantic_error_is_reported_as_corrupt_bson() { - // Blank key (semantic) first, then a later `datetime` string with invalid UTF-8. - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), " "); - doc.append(cstr!("timestamp"), TS); - doc.append(cstr!("open"), 10.0_f64); - doc.append(cstr!("high"), 11.0_f64); - doc.append(cstr!("low"), 9.0_f64); - doc.append(cstr!("close"), 10.5_f64); - doc.append(cstr!("volume"), 1.0_f64); - doc.append(cstr!("datetime"), "ZZZZ"); - let mut bytes = doc.into_bytes(); - let pos = bytes.windows(4).position(|w| w == b"ZZZZ").unwrap(); - bytes[pos + 1] = 0xFF; - - let mut stats = BsonEodIntradayDecodeStats::default(); - let mut errs = Vec::new(); - let s = decode_eod_intraday_buffer(&bytes, |_| panic!("no row"), |o, e| errs.push((o, e))); - stats.merge(&s); - assert_eq!(errs.len(), 1); - assert!(matches!(errs[0], (0, BsonEodIntradayError::CorruptBson { offset: 0, .. }))); - assert_eq!(stats.rejected_corrupt_document, 1); - assert_eq!(stats.rejected_empty_field, 0); - assert_eq!(stats.rejected_total(), 1); -} - -#[test] -fn timestamp_edge_values_are_accepted_or_rejected_exactly() { - // i32::MAX seconds (2038-01-19) is valid in Int32 form. - let bar_doc = with_timestamp(RawBsonRef::Int32(i32::MAX)); - let bar = decode_eod_intraday_doc(&bar_doc).unwrap(); - assert_eq!(bar.ts, i64::from(i32::MAX) * 1_000_000); - - let max_secs = i64::MAX / 1_000_000; - for bad in [ - RawBsonRef::Double(f64::MIN_POSITIVE), - RawBsonRef::Double(5e-324), - RawBsonRef::Double(max_secs as f64 + 0.5), - RawBsonRef::Double(1e300), - RawBsonRef::Double(f64::MAX), - RawBsonRef::Int32(i32::MIN), - RawBsonRef::Int64(i64::MIN), - ] { - let doc = with_timestamp(bad); - assert_eq!( - decode_eod_intraday_doc(&doc), - Err(BsonEodIntradayError::InvalidTimestamp { field: "timestamp" }), - "timestamp {bad:?}" - ); - } -} - -#[test] -fn display_messages_name_the_offending_field_and_offset() { - let cases = [ - (BsonEodIntradayError::MissingField { field: "eodSearchCode" }, "eodSearchCode"), - (BsonEodIntradayError::EmptyField { field: "eodSearchCode" }, "eodSearchCode"), - (BsonEodIntradayError::InvalidTimestamp { field: "timestamp" }, "timestamp"), - (BsonEodIntradayError::InvalidNumber { field: "volume", value: -1.0 }, ">= 0"), - (BsonEodIntradayError::InvalidNumber { field: "close", value: 0.0 }, "> 0"), - ( - BsonEodIntradayError::CorruptBson { offset: 77, detail: "x".into() }, - "77", - ), - ]; - for (err, needle) in cases { - let msg = err.to_string(); - assert!(msg.contains(needle), "{msg:?} should contain {needle:?}"); - } -} - -#[test] -fn empty_buffer_and_huge_declared_length_never_panic() { - let stats = decode_eod_intraday_buffer(&[], |_| panic!(), |_, _| panic!()); - assert_eq!(stats, BsonEodIntradayDecodeStats::default()); - - let mut bytes = valid_doc("NVDA.US", TS, 10.0, 1.0).into_bytes(); - let first_len = bytes.len(); - bytes.extend_from_slice(&i32::MAX.to_le_bytes()); - bytes.extend_from_slice(&[0u8; 8]); - let mut rows = 0usize; - let mut errs = Vec::new(); - let stats = decode_eod_intraday_buffer(&bytes, |_| rows += 1, |o, e| errs.push((o, e))); - assert_eq!(rows, 1); - assert_eq!(stats.docs_seen, 2); - assert_eq!(stats.rejected_corrupt_document, 1); - assert_eq!(errs.len(), 1); - assert_eq!(errs[0].0, first_len); - assert!(matches!( - errs[0].1, - BsonEodIntradayError::TruncatedDocument { declared_len: Some(i32::MAX), .. } - )); -} - -fn is_framing(e: &BsonEodIntradayError) -> bool { - matches!( - e, - BsonEodIntradayError::TruncatedDocument { .. } - | BsonEodIntradayError::CorruptDocumentLength { .. } - ) -} - -#[test] -fn seeded_mutation_fuzz_buffer_and_stream_agree_and_conserve_counts() { - let mut clean = Vec::new(); - for i in 0..20i64 { - let doc = valid_doc(&format!("S{i:02}.US"), TS + 60 * i, 10.0 + i as f64, 100.0 * i as f64); - clean.extend_from_slice(doc.as_bytes()); - } - let mut rng = SplitMix64(0x7141_B50E); - let (mut framing_cases, mut ok_cases, mut rows_seen) = (0usize, 0usize, 0usize); - - for case in 0..400u64 { - let mut bytes = clean.clone(); - for _ in 0..1 + (rng.next_u64() % 4) as usize { - let idx = (rng.next_u64() as usize) % bytes.len(); - bytes[idx] = rng.next_u64() as u8; - } - if rng.next_u64() % 5 == 0 { - let cut = (rng.next_u64() as usize) % bytes.len(); - bytes.truncate(cut); - } - - // Buffer decode: every row must equal the single-frame decode of the same bytes. - let mut frames = Vec::new(); - let mut it = iter_raw_bson_docs(&bytes); - while let Some(item) = it.next_with_offset() { - if let Ok((off, doc)) = item { - frames.push((off, doc.as_bytes().len())); - } - } - let mut exp_rows = Vec::new(); - let mut exp_errs = Vec::new(); - let stats = decode_eod_intraday_buffer( - &bytes, - |b| { - let start = b.eod_search_code.as_ptr() as usize - bytes.as_ptr() as usize; - let &(off, len) = frames - .iter() - .find(|(o, l)| start >= *o && start < o + l) - .expect("row borrows from a framed doc"); - assert_eq!(decode_eod_intraday_bytes(&bytes[off..off + len]).unwrap(), b); - exp_rows.push(row(b)); - }, - |o, e| exp_errs.push((o as u64, e)), - ); - assert_eq!(stats.docs_seen, stats.rows_decoded + stats.rejected_total(), "case={case}"); - assert_eq!(stats.rows_decoded, exp_rows.len()); - assert_eq!(stats.rejected_total(), exp_errs.len()); - rows_seen += exp_rows.len(); - - let exp_framing = match exp_errs.last() { - Some((off, e)) if is_framing(e) => { - let off = *off; - exp_errs.pop(); - Some(off) - } - _ => None, - }; - - let cap = [1usize, 5, 41, 300, 4096][(case % 5) as usize]; - let mut rows = Vec::new(); - let mut errs = Vec::new(); - let result = decode_eod_intraday_stream( - JitterReader { data: &bytes, pos: 0, rng: SplitMix64(case) }, - BsonStreamOptions { chunk_capacity_bytes: cap, max_doc_bytes: 1 << 20 }, - |b| rows.push(row(b)), - |o, e| errs.push((o, e)), - ); - assert_eq!(rows, exp_rows, "case={case} cap={cap}"); - assert_eq!(errs, exp_errs, "case={case} cap={cap}"); - match (exp_framing, result) { - (None, Ok(s)) => { - ok_cases += 1; - assert_eq!(s, stats, "case={case}"); - } - (Some(off), Err(BsonStreamError::CorruptDocumentLength { offset, .. })) - | (Some(off), Err(BsonStreamError::TruncatedDocument { offset, .. })) => { - framing_cases += 1; - assert_eq!(offset, off, "case={case} cap={cap}"); - } - (exp, got) => panic!("case={case}: expected framing={exp:?}, got {got:?}"), - } - } - assert!(framing_cases >= 20, "framing_cases={framing_cases}"); - assert!(ok_cases >= 20, "ok_cases={ok_cases}"); - assert!(rows_seen > 1000, "rows_seen={rows_seen}"); -} - -#[test] -fn stream_handles_empty_input_oversized_docs_and_invalid_options() { - let stats = decode_eod_intraday_stream( - Cursor::new(Vec::::new()), - BsonStreamOptions::default(), - |_| panic!(), - |_, _| panic!(), - ) - .unwrap(); - assert_eq!(stats, BsonEodIntradayDecodeStats::default()); - - let first = valid_doc("NVDA.US", TS, 10.0, 1.0).into_bytes(); - let mut big = valid_doc("BIG.US", TS, 10.0, 1.0); - big.append(cstr!("pad"), "p".repeat(256).as_str()); - let mut input = first.clone(); - input.extend_from_slice(big.as_bytes()); - - let mut rows = Vec::new(); - let err = decode_eod_intraday_stream( - Cursor::new(&input), - BsonStreamOptions { chunk_capacity_bytes: 16, max_doc_bytes: 200 }, - |b| rows.push(row(b)), - |_, e| panic!("unexpected per-doc error {e:?}"), - ) - .unwrap_err(); - assert_eq!(rows.len(), 1); - assert!(matches!( - err, - BsonStreamError::CorruptDocumentLength { offset, max_doc_bytes: 200, .. } - if offset == first.len() as u64 - )); - - for (opts, want_cap) in [ - (BsonStreamOptions { chunk_capacity_bytes: 0, max_doc_bytes: 4096 }, true), - (BsonStreamOptions { chunk_capacity_bytes: 16, max_doc_bytes: 4 }, false), - ] { - let err = decode_eod_intraday_stream(Cursor::new(&input), opts, |_| {}, |_, _| {}) - .unwrap_err(); - if want_cap { - assert!(matches!(err, BsonStreamError::InvalidChunkCapacity)); - } else { - assert!(matches!(err, BsonStreamError::InvalidMaxDocBytes)); - } - } -} - -#[test] -fn utc_bar_start_micros_assign_late_et_bars_to_the_correct_session_date() { - // 2024-06-07 19:59 EDT = 2024-06-07 23:59 UTC (same UTC date) and - // 2024-06-07 20:00 EDT = 2024-06-08 00:00 UTC (next UTC date) both belong to the 06-07 - // US session; a seconds/micros unit slip would push them to 1970 or far future dates. - let late = 1_717_804_740_i64; // 2024-06-07T23:59:00Z - let after_midnight = 1_717_804_800_i64; // 2024-06-08T00:00:00Z - let mut buf = Vec::new(); - buf.extend_from_slice(valid_doc("NVDA.US", late, 120.0, 10.0).as_bytes()); - buf.extend_from_slice(valid_doc("NVDA.US", after_midnight, 120.1, 10.0).as_bytes()); - - let mut bars = Vec::new(); - decode_eod_intraday_buffer( - &buf, - |b| bars.push(b.into_eod_intraday_bar(|c, _| c.to_owned())), - |_, e| panic!("{e:?}"), - ); - let built = build_bars_1m(bars, &SplitTable::::default()); - let june7 = ymd_to_epoch_days(2024, 6, 7).unwrap(); - let dates: Vec = built.rows.iter().map(|r| r.session_date).collect(); - assert_eq!(built.rows.len(), 2); - assert_eq!(dates, vec![june7, june7]); - assert_eq!(built.rows[0].ts, late * 1_000_000); - assert_eq!(built.rows[1].ts, after_midnight * 1_000_000); -} diff --git a/tools/curate-etl/tests/bson_qm_actions_contract.rs b/tools/curate-etl/tests/bson_qm_actions_contract.rs deleted file mode 100644 index 85c15861..00000000 --- a/tools/curate-etl/tests/bson_qm_actions_contract.rs +++ /dev/null @@ -1,209 +0,0 @@ -//! Public-API integration contract test for `qmSplits` and `qmDividends` raw BSON decoders (`M1.2w`). - -use bson::raw::{cstr, RawBsonRef, RawDocumentBuf}; -use bson::DateTime; -use curate_etl::{ - build_corporate_actions, curate_adj_factors, decode_qm_dividend_buffer, - decode_qm_dividend_bytes, decode_qm_dividend_doc, decode_qm_split_buffer, - decode_qm_split_bytes, decode_qm_split_doc, ymd_to_epoch_days, BsonQmActionError, - CorporateActionKind, KnownAtSource, ProviderMappingRow, ProviderMappingTable, SplitTable, - FIELD_DATE, FIELD_DECLARED, FIELD_DIVIDEND_CASH, FIELD_DIVIDEND_CURRENCY, FIELD_QM_SEARCH_CODE, - FIELD_SPLIT_RATIO, FIELD_USD_FX_RATE, -}; - -fn day(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).unwrap() -} - -#[test] -fn public_field_constants_and_single_doc_decoders_match_contract() { - assert_eq!(FIELD_QM_SEARCH_CODE, "qmSearchCode"); - assert_eq!(FIELD_DATE, "date"); - assert_eq!(FIELD_DECLARED, "declared"); - assert_eq!(FIELD_SPLIT_RATIO, "splitratio"); - assert_eq!(FIELD_USD_FX_RATE, "usdFxRate"); - assert_eq!(FIELD_DIVIDEND_CASH, "amount"); - assert_eq!(FIELD_DIVIDEND_CURRENCY, "currency"); - - let mut split_doc = RawDocumentBuf::new(); - split_doc.append(cstr!("qmSearchCode"), "NVDA"); - split_doc.append(cstr!("date"), "2024-06-10"); - split_doc.append(cstr!("declared"), "2024-05-22"); - split_doc.append(cstr!("forfactor"), 1_i32); - split_doc.append(cstr!("tofactor"), 10_i32); - split_doc.append(cstr!("splitratio"), 0.1_f64); - split_doc.append(cstr!("usdFxRate"), 1_i32); - - let split = decode_qm_split_doc(&split_doc).unwrap(); - assert_eq!(decode_qm_split_bytes(split_doc.as_bytes()).unwrap(), split); - assert_eq!(split.qm_search_code, "NVDA"); - assert_eq!(split.ex_date, day(2024, 6, 10)); - assert_eq!(split.ratio, 10.0); - assert_eq!(split.declared_date, Some(day(2024, 5, 22))); - - let mut div_doc = RawDocumentBuf::new(); - div_doc.append(cstr!("qmSearchCode"), "RY:CA"); - div_doc.append( - cstr!("date"), - DateTime::from_millis(i64::from(day(2024, 11, 15)) * 86_400_000), - ); - div_doc.append(cstr!("declared"), RawBsonRef::Null); - div_doc.append(cstr!("amount"), 1.42_f64); - div_doc.append(cstr!("currency"), "CAD"); - div_doc.append(cstr!("usdFxRate"), 1_i32); - - let div = decode_qm_dividend_doc(&div_doc).unwrap(); - assert_eq!(decode_qm_dividend_bytes(div_doc.as_bytes()).unwrap(), div); - assert_eq!(div.qm_search_code, "RY:CA"); - assert_eq!(div.ex_date, day(2024, 11, 15)); - assert_eq!(div.cash, 1.42); - assert_eq!(div.currency, "CAD"); - assert_eq!(div.declared_date, None); -} - -#[test] -fn public_buffer_decoders_reconcile_and_feed_all_downstream_builders() { - let mut split_buf = Vec::new(); - - let mut s_nvda = RawDocumentBuf::new(); - s_nvda.append(cstr!("qmSearchCode"), "NVDA"); - s_nvda.append(cstr!("date"), "2024-06-10"); - s_nvda.append(cstr!("declared"), "2024-05-22"); - s_nvda.append(cstr!("forfactor"), 1_i32); - s_nvda.append(cstr!("tofactor"), 10_i32); - s_nvda.append(cstr!("splitratio"), 0.1_f64); - split_buf.extend_from_slice(s_nvda.as_bytes()); - - let mut s_noop = RawDocumentBuf::new(); - s_noop.append(cstr!("qmSearchCode"), "NVDA"); - s_noop.append(cstr!("date"), "2024-07-01"); - s_noop.append(cstr!("splitratio"), 1_i64); - split_buf.extend_from_slice(s_noop.as_bytes()); - - let mut s_bad = RawDocumentBuf::new(); - s_bad.append(cstr!("qmSearchCode"), "NVDA"); - s_bad.append(cstr!("date"), "2024-07-02"); - s_bad.append(cstr!("splitratio"), -3.0_f64); - split_buf.extend_from_slice(s_bad.as_bytes()); - - let mut div_buf = Vec::new(); - - let mut d_ry = RawDocumentBuf::new(); - d_ry.append(cstr!("qmSearchCode"), "RY:CA"); - d_ry.append(cstr!("date"), "2024-11-15"); - d_ry.append(cstr!("declared"), "2024-10-30"); - d_ry.append(cstr!("amount"), 1.42_f64); - d_ry.append(cstr!("currency"), "CAD"); - d_ry.append(cstr!("usdFxRate"), 1_i32); - div_buf.extend_from_slice(d_ry.as_bytes()); - - let mut d_bad = RawDocumentBuf::new(); - d_bad.append(cstr!("qmSearchCode"), "RY:CA"); - d_bad.append(cstr!("date"), "2023-02-29"); - d_bad.append(cstr!("amount"), 1.0_f64); - d_bad.append(cstr!("currency"), "CAD"); - div_buf.extend_from_slice(d_bad.as_bytes()); - - let mapping = ProviderMappingTable::from_rows([ - ProviderMappingRow { - source: "qm".to_string(), - source_id: "NVDA".to_string(), - listing_id: 101, - valid_from: day(2020, 1, 1), - valid_to: None, - }, - ProviderMappingRow { - source: "qm".to_string(), - source_id: "RY:CA".to_string(), - listing_id: 303, - valid_from: day(2020, 1, 1), - valid_to: None, - }, - ]) - .unwrap(); - - let mut split_events = Vec::new(); - let mut split_actions = Vec::new(); - let mut split_errs = Vec::new(); - let split_stats = decode_qm_split_buffer( - &split_buf, - |s| { - split_events.push((s.qm_search_code.to_owned(), s.to_split_event())); - if let Some(pair) = - s.try_into_split_action_event(|code, date| mapping.resolve("qm", code, date)) - { - split_actions.push(pair); - } - }, - |_, err| split_errs.push(err), - ); - - assert_eq!(split_stats.docs_in, 3); - assert_eq!(split_stats.decoded, 2); - assert_eq!(split_stats.split_noop_ratio_one, 1); - assert_eq!(split_stats.rejected_invalid_number, 1); - assert_eq!( - split_stats.decoded + split_stats.rejected_total(), - split_stats.docs_in - ); - assert!(matches!( - split_errs.as_slice(), - [BsonQmActionError::InvalidNumber { - field: FIELD_SPLIT_RATIO, - .. - }] - )); - - let mut div_events = Vec::new(); - let mut div_actions = Vec::new(); - let mut div_errs = Vec::new(); - let div_stats = decode_qm_dividend_buffer( - &div_buf, - |d| { - div_events.push(( - d.qm_search_code.to_owned(), - d.to_dividend_event(Some(142.0), Some("CAD".to_string())), - )); - if let Some(pair) = - d.try_into_dividend_action_event(|code, date| mapping.resolve("qm", code, date)) - { - div_actions.push(pair); - } - }, - |_, err| div_errs.push(err), - ); - - assert_eq!(div_stats.docs_in, 2); - assert_eq!(div_stats.decoded, 1); - assert_eq!(div_stats.rejected_malformed_date, 1); - assert_eq!( - div_stats.decoded + div_stats.rejected_total(), - div_stats.docs_in - ); - assert!(matches!( - div_errs.as_slice(), - [BsonQmActionError::MalformedDate { field: FIELD_DATE }] - )); - - // Feed SplitTable. - let split_table = SplitTable::from_events(split_events.iter().cloned()).unwrap(); - assert_eq!(split_table.cum_factor_after("NVDA", day(2024, 6, 7)), 10.0); - - // Feed curate_adj_factors. - let adj = curate_adj_factors(&mapping, "qm", split_events, div_events).unwrap(); - assert_eq!(adj.rows.len(), 2); - assert_eq!(adj.stats.builder.split_noops_dropped, 1); - assert_eq!(adj.rows[0].listing_id, 101); - assert_eq!(adj.rows[0].split_factor, 10.0); - assert_eq!(adj.rows[1].listing_id, 303); - assert_eq!(adj.rows[1].div_cash, 1.42); - assert_eq!(adj.rows[1].div_currency.as_deref(), Some("CAD")); - - // Feed build_corporate_actions. - let ca = build_corporate_actions(split_actions, div_actions, std::iter::empty()).unwrap(); - assert_eq!(ca.rows.len(), 2); - assert_eq!(ca.rows[0].kind, CorporateActionKind::Split); - assert_eq!(ca.rows[0].known_at_source, KnownAtSource::DeclaredDate); - assert_eq!(ca.rows[1].kind, CorporateActionKind::Dividend); - assert_eq!(ca.rows[1].known_at_source, KnownAtSource::DeclaredDate); -} diff --git a/tools/curate-etl/tests/bson_qm_actions_qa_contract.rs b/tools/curate-etl/tests/bson_qm_actions_qa_contract.rs deleted file mode 100644 index b95b7152..00000000 --- a/tools/curate-etl/tests/bson_qm_actions_qa_contract.rs +++ /dev/null @@ -1,526 +0,0 @@ -//! QA contract tests for the public `qmSplits` / `qmDividends` raw BSON decoders (T-107 / M1.2w). -//! -//! Covers gaps left by `src/bson_qm_actions_tests.rs` and `tests/bson_qm_actions_contract.rs`, -//! using only the public API: -//! - zero-copy: `qm_search_code` / `currency` borrow from the input buffer; -//! - field-order independence, case-sensitive keys, nested look-alike keys ignored; -//! - `usdFxRate` / unknown fields with corrupt payloads are skipped without decoding, while the -//! same corruption inside a known field is a typed `CorruptBson` naming that field; -//! - `DateTime` day boundaries (last ms of a day, -1 ms before epoch); -//! - `split_noop_ratio_one` counts exactly `1.0`, not near-one ratios; -//! - error callbacks receive the exact byte offset of the rejected document; empty buffer, -//! truncated tail after good docs, `i32::MAX` declared length; -//! - seeded byte-mutation fuzz for both collections: never panics, always reconciles, and every -//! streamed row equals the single-document decode of the same bytes; -//! - benchmark guard: synthetic docs actually decode (rejections stay near the injected ~0.5%), -//! so a field-constant change cannot silently turn the benchmark into a rejection-path timing; -//! - `bench-bson-qm-actions` binary: identical checksum across two runs, invalid args exit 1. - -use std::process::{Command, Output}; - -use bson::raw::{cstr, RawBsonRef, RawDocumentBuf}; -use bson::DateTime; -use curate_etl::bench::run_bson_qm_actions_benchmark; -use curate_etl::{ - decode_qm_dividend_buffer, decode_qm_dividend_bytes, decode_qm_dividend_doc, - decode_qm_split_buffer, decode_qm_split_bytes, decode_qm_split_doc, iter_raw_bson_docs, - ymd_to_epoch_days, BsonQmActionError, RawQmDividend, RawQmSplit, FIELD_DIVIDEND_CASH, - FIELD_DIVIDEND_CURRENCY, FIELD_QM_SEARCH_CODE, FIELD_SPLIT_RATIO, -}; - -const MILLIS_PER_DAY: i64 = 86_400_000; - -fn day(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).unwrap() -} - -fn split_doc(code: &str, date: &str, ratio: f64) -> RawDocumentBuf { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("_id"), "ignored"); - doc.append(cstr!("qmSearchCode"), code); - doc.append(cstr!("date"), date); - if ratio.is_finite() && ratio > 0.0 { - doc.append(cstr!("splitratio"), 1.0 / ratio); - doc.append(cstr!("forfactor"), 1.0_f64); - doc.append(cstr!("tofactor"), ratio); - } else { - doc.append(cstr!("splitratio"), ratio); - } - doc.append(cstr!("usdFxRate"), 1_i32); - doc -} - -fn dividend_doc(code: &str, date: &str, cash: f64, currency: &str) -> RawDocumentBuf { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("_id"), "ignored"); - doc.append(cstr!("qmSearchCode"), code); - doc.append(cstr!("date"), date); - doc.append(cstr!("declared"), "2024-05-01"); - doc.append(cstr!("amount"), cash); - doc.append(cstr!("currency"), currency); - doc.append(cstr!("usdFxRate"), 1_i32); - doc -} - -fn ptr_within(s: &str, buf: &[u8]) -> bool { - let range = buf.as_ptr_range(); - let p = s.as_ptr(); - range.contains(&p) && (p as usize + s.len()) <= range.end as usize -} - -/// Overwrites the first occurrence of `needle` in `bytes` with `replacement` (same length). -fn patch(bytes: &mut [u8], needle: &[u8], replacement: &[u8]) { - assert_eq!(needle.len(), replacement.len()); - let pos = bytes - .windows(needle.len()) - .position(|w| w == needle) - .expect("needle present"); - bytes[pos..pos + needle.len()].copy_from_slice(replacement); -} - -#[test] -fn decoded_strings_borrow_directly_from_the_input_buffer() { - let s = split_doc("NVDA", "2024-06-10", 10.0); - let split = decode_qm_split_bytes(s.as_bytes()).unwrap(); - assert!(ptr_within(split.qm_search_code, s.as_bytes())); - - let d = dividend_doc("RY:CA", "2024-11-15", 1.42, "CAD"); - let mut buf = Vec::new(); - buf.extend_from_slice(d.as_bytes()); - let mut seen = Vec::new(); - decode_qm_dividend_buffer(&buf, |div| seen.push(div), |_, e| panic!("{e}")); - assert_eq!(seen.len(), 1); - assert!(ptr_within(seen[0].qm_search_code, &buf)); - assert!(ptr_within(seen[0].currency, &buf)); -} - -#[test] -fn field_order_is_irrelevant_keys_are_case_sensitive_and_nested_lookalikes_are_ignored() { - // Reverse field order decodes identically. - let mut rev = RawDocumentBuf::new(); - rev.append(cstr!("usdFxRate"), 1.0_f64); - rev.append(cstr!("currency"), "CAD"); - rev.append(cstr!("amount"), 1.42_f64); - rev.append(cstr!("declared"), "2024-05-01"); - rev.append(cstr!("date"), "2024-11-15"); - rev.append(cstr!("qmSearchCode"), "RY:CA"); - let fwd = dividend_doc("RY:CA", "2024-11-15", 1.42, "CAD"); - assert_eq!( - decode_qm_dividend_doc(&rev).unwrap(), - decode_qm_dividend_doc(&fwd).unwrap() - ); - - // Differently-cased keys are unknown fields, so the required field is missing. - let mut cased = RawDocumentBuf::new(); - cased.append(cstr!("QmSearchCode"), "NVDA"); - cased.append(cstr!("date"), "2024-06-10"); - cased.append(cstr!("splitratio"), 10.0_f64); - assert_eq!( - decode_qm_split_doc(&cased).unwrap_err(), - BsonQmActionError::MissingField { - field: FIELD_QM_SEARCH_CODE - } - ); - let mut cased_ratio = RawDocumentBuf::new(); - cased_ratio.append(cstr!("qmSearchCode"), "NVDA"); - cased_ratio.append(cstr!("date"), "2024-06-10"); - cased_ratio.append(cstr!("splitRatio"), 10.0_f64); - assert_eq!( - decode_qm_split_doc(&cased_ratio).unwrap_err(), - BsonQmActionError::MissingField { - field: FIELD_SPLIT_RATIO - } - ); - - // A nested sub-document carrying look-alike keys must neither satisfy nor poison the decode. - let mut nested = RawDocumentBuf::new(); - nested.append(cstr!("splitratio"), -99.0_f64); - nested.append(cstr!("amount"), "bad"); - nested.append(cstr!("currency"), 7_i32); - nested.append(cstr!("date"), "not-a-date"); - let mut outer = split_doc("NVDA", "2024-06-10", 10.0); - outer.append(cstr!("raw"), RawBsonRef::Document(nested.as_ref())); - let split = decode_qm_split_doc(&outer).unwrap(); - assert_eq!(split.ratio, 10.0); - - let mut outer_div = dividend_doc("RY:CA", "2024-11-15", 1.42, "CAD"); - outer_div.append(cstr!("raw"), RawBsonRef::Document(nested.as_ref())); - let div = decode_qm_dividend_doc(&outer_div).unwrap(); - assert_eq!((div.cash, div.currency), (1.42, "CAD")); - - let mut only_nested = RawDocumentBuf::new(); - only_nested.append(cstr!("qmSearchCode"), "NVDA"); - only_nested.append(cstr!("date"), "2024-06-10"); - only_nested.append(cstr!("raw"), RawBsonRef::Document(nested.as_ref())); - assert_eq!( - decode_qm_split_doc(&only_nested).unwrap_err(), - BsonQmActionError::MissingField { - field: FIELD_SPLIT_RATIO - } - ); -} - -#[test] -fn corrupt_payload_in_ignored_field_is_skipped_but_in_known_field_names_that_field() { - // Unknown field / `usdFxRate` with invalid UTF-8 string bytes: framing is valid, payload is - // never decoded. - let mut d = dividend_doc("RY:CA", "2024-11-15", 1.42, "CAD"); - d.append(cstr!("zzExtra"), "XYZW"); - let mut bytes = d.as_bytes().to_vec(); - patch(&mut bytes, b"XYZW", &[0xFF, 0xFE, 0xFD, 0xFC]); - let div = decode_qm_dividend_bytes(&bytes).unwrap(); - assert_eq!(div.currency, "CAD"); - - let mut s = split_doc("NVDA", "2024-06-10", 10.0); - s.append(cstr!("usdFxRate"), "QQQQ"); - let mut bytes = s.as_bytes().to_vec(); - patch(&mut bytes, b"QQQQ", &[0xC3, 0x28, 0xA0, 0xA1]); - assert_eq!(decode_qm_split_bytes(&bytes).unwrap().ratio, 10.0); - - // Same corruption inside `currency` is a typed CorruptBson naming the field (no panic). - let d = dividend_doc("RY:CA", "2024-11-15", 1.42, "QQQ"); - let mut bytes = d.as_bytes().to_vec(); - patch(&mut bytes, b"QQQ", &[0xFF, 0xFE, 0xFD]); - match decode_qm_dividend_bytes(&bytes).unwrap_err() { - BsonQmActionError::CorruptBson { offset, detail } => { - assert_eq!(offset, 0); - assert!(detail.contains(FIELD_DIVIDEND_CURRENCY), "{detail}"); - } - other => panic!("expected CorruptBson, got {other:?}"), - } -} - -#[test] -fn datetime_dates_floor_to_utc_day_at_boundaries() { - let cases = [ - (-1_i64, -1_i32), - (0, 0), - (-MILLIS_PER_DAY, -1), - (-MILLIS_PER_DAY - 1, -2), - ( - i64::from(day(2024, 6, 10)) * MILLIS_PER_DAY + MILLIS_PER_DAY - 1, - day(2024, 6, 10), - ), - ( - i64::from(day(2024, 6, 11)) * MILLIS_PER_DAY, - day(2024, 6, 11), - ), - ]; - for (ms, expected) in cases { - let mut s = RawDocumentBuf::new(); - s.append(cstr!("qmSearchCode"), "IBM"); - s.append(cstr!("date"), DateTime::from_millis(ms)); - s.append(cstr!("declared"), DateTime::from_millis(ms)); - s.append(cstr!("splitratio"), 2_i64); - let split = decode_qm_split_doc(&s).unwrap(); - assert_eq!(split.ex_date, expected, "ms={ms}"); - assert_eq!(split.declared_date, Some(expected), "ms={ms}"); - - let mut d = RawDocumentBuf::new(); - d.append(cstr!("qmSearchCode"), "IBM"); - d.append(cstr!("date"), DateTime::from_millis(ms)); - d.append(cstr!("amount"), 1_i32); - d.append(cstr!("currency"), "USD"); - assert_eq!( - decode_qm_dividend_doc(&d).unwrap().ex_date, - expected, - "ms={ms}" - ); - } -} - -#[test] -fn noop_counter_counts_only_exact_ratio_one() { - let mut buf = Vec::new(); - for ratio in [1.0, 1.000_000_000_1, 0.999_999_999_9, 1.0, 2.0] { - buf.extend_from_slice(split_doc("X", "2024-03-15", ratio).as_bytes()); - } - let mut n = 0; - let stats = decode_qm_split_buffer(&buf, |_| n += 1, |_, e| panic!("{e}")); - assert_eq!(n, 5); - assert_eq!(stats.decoded, 5); - assert_eq!(stats.split_noop_ratio_one, 2); - assert_eq!(stats.rejected_total(), 0); - - // Dividends never touch the split no-op counter. - let d = dividend_doc("X", "2024-03-15", 1.0, "USD"); - let stats = decode_qm_dividend_buffer(d.as_bytes(), |_| {}, |_, e| panic!("{e}")); - assert_eq!(stats.split_noop_ratio_one, 0); -} - -#[test] -fn error_callbacks_report_exact_offsets_and_framing_failures_stop_cleanly() { - // Empty buffer: nothing in, nothing out. - let stats = decode_qm_split_buffer(&[], |_| panic!(), |_, _| panic!()); - assert_eq!(stats, Default::default()); - let stats = decode_qm_dividend_buffer(&[], |_| panic!(), |_, _| panic!()); - assert_eq!(stats, Default::default()); - - let good = dividend_doc("A", "2024-06-10", 0.5, "USD"); - let bad_cash = dividend_doc("B", "2024-06-10", -0.5, "USD"); - let bad_date = dividend_doc("C", "2024-13-01", 0.5, "USD"); - let mut buf = Vec::new(); - let mut expected_err_offsets = Vec::new(); - buf.extend_from_slice(good.as_bytes()); - expected_err_offsets.push(buf.len()); - buf.extend_from_slice(bad_cash.as_bytes()); - expected_err_offsets.push(buf.len()); - buf.extend_from_slice(bad_date.as_bytes()); - buf.extend_from_slice(good.as_bytes()); - // Truncated tail: declares a full doc but only half is present. - expected_err_offsets.push(buf.len()); - let tail_start = buf.len(); - buf.extend_from_slice(&good.as_bytes()[..good.as_bytes().len() / 2]); - - let mut errs = Vec::new(); - let mut codes = Vec::new(); - let stats = decode_qm_dividend_buffer( - &buf, - |d: RawQmDividend<'_>| codes.push(d.qm_search_code), - |off, e| errs.push((off, e)), - ); - assert_eq!(codes, vec!["A", "A"]); - assert_eq!( - errs.iter().map(|(o, _)| *o).collect::>(), - expected_err_offsets - ); - assert!(matches!( - errs[0].1, - BsonQmActionError::InvalidNumber { - field: FIELD_DIVIDEND_CASH, - .. - } - )); - assert!(matches!( - errs[2].1, - BsonQmActionError::TruncatedDocument { - offset, - declared_len: Some(_), - .. - } if offset == tail_start - )); - assert_eq!(stats.docs_in, 5); - assert_eq!(stats.decoded, 2); - assert_eq!(stats.rejected_corrupt_document, 1); - assert_eq!(stats.decoded + stats.rejected_total(), stats.docs_in); - - // i32::MAX declared length after a good split doc terminates without panicking. - let mut buf = split_doc("S", "2024-06-10", 2.0).as_bytes().to_vec(); - let bad_at = buf.len(); - buf.extend_from_slice(&i32::MAX.to_le_bytes()); - buf.extend_from_slice(&[0u8; 8]); - let mut errs = Vec::new(); - let stats = decode_qm_split_buffer(&buf, |_| {}, |off, e| errs.push((off, e))); - assert_eq!(stats.docs_in, 2); - assert_eq!(stats.decoded, 1); - assert_eq!(errs.len(), 1); - assert_eq!(errs[0].0, bad_at); - assert!(matches!( - errs[0].1, - BsonQmActionError::TruncatedDocument { .. } - )); - - // Single-doc decoder: trailing bytes are rejected as a length mismatch, not silently ignored. - let mut trailing = split_doc("S", "2024-06-10", 2.0).as_bytes().to_vec(); - trailing.push(0); - assert!(matches!( - decode_qm_split_bytes(&trailing).unwrap_err(), - BsonQmActionError::CorruptDocumentLength { .. } - )); -} - -/// `std`-only SplitMix64 so the fuzz corpus is fixed across runs. -struct SplitMix64(u64); - -impl SplitMix64 { - 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 mutate(rng: &mut SplitMix64, base: &[u8]) -> Vec { - let mut buf = base.to_vec(); - let flips = 1 + (rng.next() % 4) as usize; - for _ in 0..flips { - let pos = (rng.next() as usize) % buf.len(); - buf[pos] = rng.next() as u8; - } - if rng.next() % 4 == 0 { - let cut = (rng.next() as usize) % buf.len(); - buf.truncate(cut); - } - buf -} - -fn framed_slices(buf: &[u8]) -> Vec<(usize, usize)> { - let mut out = Vec::new(); - let mut iter = iter_raw_bson_docs(buf); - while let Some(item) = iter.next_with_offset() { - if let Ok((off, doc)) = item { - out.push((off, doc.as_bytes().len())); - } - } - out -} - -#[test] -fn seeded_byte_mutation_fuzz_never_panics_and_always_reconciles_for_both_collections() { - let mut split_base = Vec::new(); - let mut div_base = Vec::new(); - for i in 0..8 { - let code = format!("Q{i}:CA"); - split_base.extend_from_slice(split_doc(&code, "2024-06-07", 1.0 + i as f64).as_bytes()); - div_base - .extend_from_slice(dividend_doc(&code, "2024-06-07", 0.1 * i as f64, "CAD").as_bytes()); - } - - let split_key = |s: &RawQmSplit<'_>| { - ( - s.qm_search_code.to_string(), - s.ex_date, - s.ratio.to_bits(), - s.declared_date, - ) - }; - let div_key = |d: &RawQmDividend<'_>| { - ( - d.qm_search_code.to_string(), - d.ex_date, - d.cash.to_bits(), - d.currency.to_string(), - d.declared_date, - ) - }; - - let mut rng = SplitMix64(0x0B50_7E57_0A11_0107); - for _ in 0..2_000 { - let buf = mutate(&mut rng, &split_base); - let mut rows = Vec::new(); - let stats = decode_qm_split_buffer(&buf, |s| rows.push(s), |_, _| {}); - assert_eq!(stats.decoded + stats.rejected_total(), stats.docs_in); - assert_eq!(stats.decoded, rows.len()); - assert_eq!( - stats.split_noop_ratio_one, - rows.iter().filter(|s| s.ratio == 1.0).count() - ); - let expected: Vec<_> = framed_slices(&buf) - .into_iter() - .filter_map(|(o, l)| decode_qm_split_bytes(&buf[o..o + l]).ok()) - .collect(); - assert_eq!( - rows.iter().map(split_key).collect::>(), - expected.iter().map(split_key).collect::>() - ); - for s in &rows { - assert!(s.ratio.is_finite() && s.ratio > 0.0); - assert!(!s.qm_search_code.trim().is_empty()); - } - - let buf = mutate(&mut rng, &div_base); - let mut rows = Vec::new(); - let stats = decode_qm_dividend_buffer(&buf, |d| rows.push(d), |_, _| {}); - assert_eq!(stats.decoded + stats.rejected_total(), stats.docs_in); - assert_eq!(stats.decoded, rows.len()); - assert_eq!(stats.split_noop_ratio_one, 0); - let expected: Vec<_> = framed_slices(&buf) - .into_iter() - .filter_map(|(o, l)| decode_qm_dividend_bytes(&buf[o..o + l]).ok()) - .collect(); - assert_eq!( - rows.iter().map(div_key).collect::>(), - expected.iter().map(div_key).collect::>() - ); - for d in &rows { - assert!(d.cash.is_finite() && d.cash >= 0.0 && !d.cash.is_sign_negative()); - assert!(!d.currency.trim().is_empty()); - } - } -} - -#[test] -fn benchmark_corpus_mostly_decodes_so_it_times_the_happy_path() { - let report = run_bson_qm_actions_benchmark(20_000); - let s = report.split_stats; - let d = report.dividend_stats; - assert_eq!(s.docs_in + d.docs_in, 20_000); - // Injected errors are ~0.5% per collection; allow generous headroom but fail if a renamed - // field constant makes the corpus reject en masse. - assert!( - s.rejected_total() * 50 < s.docs_in, - "split rejections too high: {s:?}" - ); - assert!( - d.rejected_total() * 50 < d.docs_in, - "dividend rejections too high: {d:?}" - ); - assert_eq!(s.rejected_corrupt_document + d.rejected_corrupt_document, 0); -} - -fn run_bin(args: &[&str]) -> Output { - Command::new(env!("CARGO_BIN_EXE_curate-etl")) - .args(args) - .output() - .expect("spawn curate-etl binary") -} - -fn stable_output(out: &Output) -> String { - let text = String::from_utf8_lossy(&out.stdout); - let checksum = text - .split_whitespace() - .find(|t| t.starts_with("checksum=0x")) - .unwrap_or_else(|| panic!("no checksum in output: {text}")); - let stats: Vec<&str> = text - .lines() - .map(str::trim_start) - .filter(|l| { - l.starts_with("input:") || l.starts_with("splits:") || l.starts_with("dividends:") - }) - .collect(); - assert_eq!(stats.len(), 3, "missing stats lines: {text}"); - format!("{checksum} {}", stats.join(" | ")) -} - -#[test] -fn bench_binary_prints_identical_checksum_and_stats_across_runs() { - let a = run_bin(&["bench-bson-qm-actions", "5000"]); - let b = run_bin(&["bench-bson-qm-actions", "5000"]); - assert!(a.status.success(), "{}", String::from_utf8_lossy(&a.stderr)); - assert!(b.status.success(), "{}", String::from_utf8_lossy(&b.stderr)); - - let text = String::from_utf8_lossy(&a.stdout); - assert!(text.contains("rows=5000"), "{text}"); - for needle in [ - "elapsed=", - "docs/s", - "MB/s", - "noop_ratio_one=", - "checksum=0x", - ] { - assert!(text.contains(needle), "missing {needle}: {text}"); - } - assert_eq!(stable_output(&a), stable_output(&b)); -} - -#[test] -fn bench_binary_rejects_invalid_row_counts_and_is_listed_in_usage() { - for args in [ - &["bench-bson-qm-actions", "0"][..], - &["bench-bson-qm-actions", "-5"][..], - &["bench-bson-qm-actions", "abc"][..], - &["bench-bson-qm-actions", "10", "20"][..], - ] { - let out = run_bin(args); - assert_eq!(out.status.code(), Some(1), "{args:?}"); - let err = String::from_utf8_lossy(&out.stderr); - assert!(err.contains("error:"), "{args:?}: {err}"); - assert!(out.stdout.is_empty(), "{args:?} wrote to stdout"); - } - - let out = run_bin(&["--help"]); - assert!(out.status.success()); - assert!(String::from_utf8_lossy(&out.stdout).contains("bench-bson-qm-actions")); -} diff --git a/tools/curate-etl/tests/bson_stream_qa_contract.rs b/tools/curate-etl/tests/bson_stream_qa_contract.rs deleted file mode 100644 index 63532041..00000000 --- a/tools/curate-etl/tests/bson_stream_qa_contract.rs +++ /dev/null @@ -1,273 +0,0 @@ -//! QA contract tests for the public `bson_stream` API (T-109 / M1.2y). -//! -//! Covers gaps left by `src/bson_stream_tests.rs`, using only the public crate API: -//! - seeded byte-mutation fuzz: for every mutated `eodPrices` stream the streamed decode never -//! panics, yields exactly the buffer decoder's rows and per-document errors in order, and a -//! buffer framing error maps to a stream `Err` at the same absolute offset; -//! - `RawBsonChunkReader::new` (default options) frames a multi-document stream end to end; -//! - `decode_*_chunks` resumed on a reader that already failed returns the sticky error at once; -//! - `BsonStreamError` `Display` names the offset and `source()` exposes the original I/O error; -//! - `bench-bson-stream` binary: completes on a small row count with a ratio and peak buffer -//! line, identical checksum across two runs, invalid args exit non-zero. - -use std::error::Error as _; -use std::io::{self, Cursor, Read}; -use std::process::{Command, Output}; - -use bson::raw::{cstr, RawDocumentBuf}; -use curate_etl::{ - decode_eod_price_buffer, decode_eod_price_chunks, decode_eod_price_stream, - decode_qm_split_chunks, BsonEodPriceError, BsonStreamError, BsonStreamOptions, - RawBsonChunkReader, DEFAULT_CHUNK_CAPACITY_BYTES, -}; - -struct SplitMix64(u64); - -impl SplitMix64 { - fn next_u64(&mut self) -> u64 { - self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); - let mut z = self.0; - z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); - z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); - z ^ (z >> 31) - } -} - -/// Reader returning seeded pseudo-random short reads of 1..=97 bytes. -struct JitterReader<'a> { - data: &'a [u8], - pos: usize, - rng: SplitMix64, -} - -impl Read for JitterReader<'_> { - fn read(&mut self, buf: &mut [u8]) -> io::Result { - let remaining = self.data.len() - self.pos; - if remaining == 0 { - return Ok(0); - } - let step = (self.rng.next_u64() % 97) as usize + 1; - let take = remaining.min(step).min(buf.len()); - buf[..take].copy_from_slice(&self.data[self.pos..self.pos + take]); - self.pos += take; - Ok(take) - } -} - -/// Reader that yields its data once and then fails every subsequent read. -struct FailAfterData { - data: Vec, - pos: usize, - reads_after_fail: usize, -} - -impl Read for FailAfterData { - fn read(&mut self, buf: &mut [u8]) -> io::Result { - if self.pos == self.data.len() { - self.reads_after_fail += 1; - return Err(io::Error::new(io::ErrorKind::ConnectionReset, "cursor dropped")); - } - let take = (self.data.len() - self.pos).min(buf.len()); - buf[..take].copy_from_slice(&self.data[self.pos..self.pos + take]); - self.pos += take; - Ok(take) - } -} - -fn eod_doc(code: &str, day: u32, close: f64) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), code); - doc.append(cstr!("date"), format!("2024-06-{day:02}")); - doc.append(cstr!("open"), close - 0.5); - doc.append(cstr!("high"), close + 1.0); - doc.append(cstr!("low"), close - 1.0); - doc.append(cstr!("close"), close); - doc.append(cstr!("volume"), 1_000_i64 + day as i64); - doc.append(cstr!("exchange"), "TSX"); - doc.into_bytes() -} - -fn eod_fixture(count: usize) -> Vec { - let mut out = Vec::new(); - for i in 0..count { - out.extend_from_slice(&eod_doc(&format!("Q{i:03}.TO"), 1 + (i % 28) as u32, 10.0 + i as f64)); - } - out -} - -type Row = (String, i32, u64, u64); - -fn buffer_decode(bytes: &[u8]) -> (Vec, Vec<(u64, String)>) { - let mut rows = Vec::new(); - let mut errs = Vec::new(); - decode_eod_price_buffer( - bytes, - |b| rows.push((b.eod_search_code.to_owned(), b.session_date, b.close.to_bits(), b.adj_volume.to_bits())), - |off, e| errs.push((off as u64, format!("{e:?}"))), - ); - (rows, errs) -} - -fn is_framing_error(debug: &str) -> bool { - debug.starts_with("CorruptDocumentLength") || debug.starts_with("TruncatedDocument") -} - -#[test] -fn seeded_mutation_fuzz_stream_matches_buffer_rows_errors_and_framing_offset() { - let clean = eod_fixture(24); - let mut rng = SplitMix64(0x5EED_B50E); - let mut framing_cases = 0usize; - let mut ok_cases = 0usize; - - for case in 0..400u64 { - let mut bytes = clean.clone(); - let flips = 1 + (rng.next_u64() % 4) as usize; - for _ in 0..flips { - let idx = (rng.next_u64() as usize) % bytes.len(); - bytes[idx] = rng.next_u64() as u8; - } - if rng.next_u64() % 5 == 0 { - let cut = (rng.next_u64() as usize) % bytes.len(); - bytes.truncate(cut); - } - - let (exp_rows, mut exp_errs) = buffer_decode(&bytes); - let exp_framing = match exp_errs.last() { - Some((off, dbg)) if is_framing_error(dbg) => { - let off = *off; - exp_errs.pop(); - Some(off) - } - _ => None, - }; - - let cap = [1usize, 4, 37, 256, 4096][(case % 5) as usize]; - let mut rows = Vec::new(); - let mut errs = Vec::new(); - let result = decode_eod_price_stream( - JitterReader { data: &bytes, pos: 0, rng: SplitMix64(case) }, - BsonStreamOptions { chunk_capacity_bytes: cap, max_doc_bytes: 1 << 20 }, - |b| rows.push((b.eod_search_code.to_owned(), b.session_date, b.close.to_bits(), b.adj_volume.to_bits())), - |off, e: BsonEodPriceError| errs.push((off, format!("{e:?}"))), - ); - - assert_eq!(rows, exp_rows, "case={case} cap={cap}: rows diverge"); - assert_eq!(errs, exp_errs, "case={case} cap={cap}: per-doc errors diverge"); - match (exp_framing, result) { - (None, Ok(stats)) => { - ok_cases += 1; - assert_eq!(stats.decoded, exp_rows.len(), "case={case}"); - assert_eq!(stats.decoded + stats.rejected_total(), stats.docs_in, "case={case}"); - } - (Some(off), Err(BsonStreamError::CorruptDocumentLength { offset, .. })) - | (Some(off), Err(BsonStreamError::TruncatedDocument { offset, .. })) => { - framing_cases += 1; - assert_eq!(offset, off, "case={case} cap={cap}: framing offset"); - } - (exp, got) => panic!("case={case} cap={cap}: expected framing={exp:?}, got {got:?}"), - } - } - // The sweep must exercise both outcomes, or it proves nothing. - assert!(framing_cases >= 20, "framing_cases={framing_cases}"); - assert!(ok_cases >= 20, "ok_cases={ok_cases}"); -} - -#[test] -fn default_reader_frames_whole_stream_with_default_capacity() { - let input = eod_fixture(50); - let mut reader = RawBsonChunkReader::new(JitterReader { data: &input, pos: 0, rng: SplitMix64(7) }); - let mut joined = Vec::new(); - while let Some(chunk) = reader.next_chunk().expect("valid stream") { - assert_eq!(chunk.start_offset, joined.len() as u64); - joined.extend_from_slice(chunk.bytes); - } - assert_eq!(joined, input); - assert_eq!(reader.docs_framed(), 50); - assert_eq!(reader.bytes_read(), input.len() as u64); - assert_eq!(reader.buffer_capacity(), DEFAULT_CHUNK_CAPACITY_BYTES); -} - -#[test] -fn chunk_helpers_on_failed_reader_return_sticky_error_without_rereading() { - let input = eod_fixture(3); - let len = input.len() as u64; - let mut reader = RawBsonChunkReader::with_options( - FailAfterData { data: input, pos: 0, reads_after_fail: 0 }, - BsonStreamOptions { chunk_capacity_bytes: 64, max_doc_bytes: 4096 }, - ) - .unwrap(); - - let mut bars = 0usize; - let err = decode_eod_price_chunks(&mut reader, |_| bars += 1, |_, _| panic!("no per-doc errors")) - .expect_err("I/O failure must surface"); - assert_eq!(bars, 3, "all complete docs delivered before the I/O error"); - let BsonStreamError::Io { offset, ref source } = err else { panic!("expected Io, got {err:?}") }; - assert_eq!(offset, len); - assert_eq!(source.kind(), io::ErrorKind::ConnectionReset); - - // A different helper resumed on the same failed reader must fail immediately. - let again = decode_qm_split_chunks(&mut reader, |_| panic!("no rows"), |_, _| panic!("no errors")) - .expect_err("sticky error"); - assert!(matches!(again, BsonStreamError::Io { offset, .. } if offset == len)); - assert_eq!(reader.into_inner().reads_after_fail, 1, "source read exactly once after data"); -} - -#[test] -fn error_display_names_offset_and_io_source_is_exposed() { - let mut bytes = eod_doc("A.TO", 3, 5.0); - let first_len = bytes.len(); - bytes.extend_from_slice(&2_i32.to_le_bytes()); - let err = decode_eod_price_stream(Cursor::new(bytes), BsonStreamOptions::default(), |_| {}, |_, _| {}) - .expect_err("corrupt length"); - assert!(err.source().is_none()); - let text = err.to_string(); - assert!(text.contains(&format!("offset {first_len}")), "{text}"); - assert!(text.contains("length 2"), "{text}"); - - let io_err = decode_eod_price_stream( - FailAfterData { data: Vec::new(), pos: 0, reads_after_fail: 0 }, - BsonStreamOptions::default(), - |_| {}, - |_, _| {}, - ) - .expect_err("io"); - let src = io_err.source().expect("Io exposes source"); - assert!(src.to_string().contains("cursor dropped"), "{src}"); - assert!(io_err.to_string().contains("offset 0"), "{io_err}"); - - assert!(BsonStreamError::InvalidChunkCapacity.to_string().contains("chunk_capacity_bytes")); - assert!(BsonStreamError::InvalidMaxDocBytes.to_string().contains("max_doc_bytes")); -} - -fn run_bin(args: &[&str]) -> Output { - Command::new(env!("CARGO_BIN_EXE_curate-etl")) - .args(args) - .output() - .expect("spawn curate-etl binary") -} - -fn checksum_of(out: &Output) -> String { - let text = String::from_utf8_lossy(&out.stdout); - text.split_whitespace() - .find(|t| t.starts_with("checksum=0x")) - .unwrap_or_else(|| panic!("no checksum in output: {text}")) - .to_owned() -} - -#[test] -fn bench_bson_stream_binary_is_deterministic_and_rejects_bad_args() { - let a = run_bin(&["bench-bson-stream", "5000"]); - let b = run_bin(&["bench-bson-stream", "5000"]); - assert!(a.status.success(), "stderr: {}", String::from_utf8_lossy(&a.stderr)); - assert!(b.status.success()); - assert_eq!(checksum_of(&a), checksum_of(&b)); - let text = String::from_utf8_lossy(&a.stdout).to_lowercase(); - assert!(text.contains("rows=5000"), "{text}"); - assert!(text.contains("ratio"), "{text}"); - assert!(text.contains("peak_buffer_capacity"), "{text}"); - - for bad in [&["bench-bson-stream", "abc"][..], &["bench-bson-stream", "1", "2"][..]] { - let out = run_bin(bad); - assert!(!out.status.success(), "args {bad:?} must fail"); - } -} diff --git a/tools/curate-etl/tests/cli.rs b/tools/curate-etl/tests/cli.rs index 3d5cb7e7..109e9e42 100644 --- a/tools/curate-etl/tests/cli.rs +++ b/tools/curate-etl/tests/cli.rs @@ -1,12 +1,6 @@ //! QA end-to-end tests for the `curate-etl` binary (T-47 / M1.2a CLI contract). -use std::fs::{self, File}; -use std::io::Write; -use std::path::PathBuf; use std::process::{Command, Output}; -use std::sync::atomic::{AtomicU64, Ordering}; - -use bson::raw::{cstr, RawDocumentBuf}; fn run(args: &[&str]) -> Output { Command::new(env!("CARGO_BIN_EXE_curate-etl")) @@ -30,23 +24,7 @@ fn no_args_and_help_print_usage_and_succeed() { assert!(out.status.success(), "{args:?}: {}", stderr(&out)); let text = stdout(&out); assert!(text.contains("Usage:"), "{args:?}: {text}"); - assert!(text.contains("curate-bars-1d"), "{args:?}: {text}"); - assert!(text.contains("curate-adj-factors"), "{args:?}: {text}"); - assert!(text.contains("curate-corporate-actions"), "{args:?}: {text}"); - assert!(text.contains("curate-fx-1d"), "{args:?}: {text}"); - assert!(text.contains("curate-shorts"), "{args:?}: {text}"); - assert!(text.contains("bench-curate-bars-cmd"), "{args:?}: {text}"); - assert!(text.contains("bench-curate-adj-cmd"), "{args:?}: {text}"); - assert!( - text.contains("bench-curate-corporate-actions-cmd"), - "{args:?}: {text}" - ); - assert!( - text.contains("bench-curate-shorts-command"), - "{args:?}: {text}" - ); assert!(text.contains("bench-split"), "{args:?}: {text}"); - assert!(text.contains("bench-ilp-bars-1m"), "{args:?}: {text}"); assert!(text.contains("bench-corporate-actions"), "{args:?}: {text}"); assert!(text.contains("bench-fx"), "{args:?}: {text}"); assert!(text.contains("bench-events"), "{args:?}: {text}"); @@ -91,10 +69,6 @@ fn invalid_invocations_exit_nonzero_with_usage_on_stderr() { &["bench-curate-fx", "0"][..], &["bench-curate-fx", "-5"][..], &["bench-curate-fx", "10", "20"][..], - &["bench-ilp-bars-1m", "abc"][..], - &["bench-ilp-bars-1m", "0"][..], - &["bench-ilp-bars-1m", "-5"][..], - &["bench-ilp-bars-1m", "10", "20"][..], &["--unknown"][..], &["export"][..], ] { @@ -264,1719 +238,3 @@ fn bench_curate_fx_small_run_is_headless_deterministic_and_reports_rates() { assert_eq!(field(&text_a, "rows_out="), field(&text_b, "rows_out=")); assert_eq!(field(&text_a, "bytes="), field(&text_b, "bytes=")); } - -#[test] -fn bench_ilp_bars_1m_small_run_is_headless_deterministic_and_reports_rates() { - let a = run(&["bench-ilp-bars-1m", "2000"]); - let b = run(&["bench-ilp-bars-1m", "2000"]); - assert!(a.status.success(), "{}", stderr(&a)); - assert!(b.status.success(), "{}", stderr(&b)); - assert!(stderr(&a).is_empty(), "unexpected stderr: {}", stderr(&a)); - assert!(stderr(&b).is_empty(), "unexpected stderr: {}", stderr(&b)); - - let text_a = stdout(&a); - let text_b = stdout(&b); - assert!(text_a.contains("curate-etl bench-ilp-bars-1m"), "{text_a}"); - assert!(text_a.contains("rows=2000 "), "{text_a}"); - assert!(text_a.contains("rows_encoded=2000 "), "{text_a}"); - assert!(text_a.contains("rows/s"), "{text_a}"); - assert!(text_a.contains("bytes/row"), "{text_a}"); - assert!(text_a.contains("MB/s"), "{text_a}"); - - let field = |s: &str, prefix: &str| { - s.split_whitespace() - .find(|t| t.starts_with(prefix)) - .map(str::to_owned) - }; - assert_eq!(field(&text_a, "bytes="), field(&text_b, "bytes=")); - assert_eq!(field(&text_a, "flushes="), field(&text_b, "flushes=")); -} - -static CLI_TEST_DIR_SEQ: AtomicU64 = AtomicU64::new(0); - -struct CliTempDir { - path: PathBuf, -} - -impl CliTempDir { - fn new(tag: &str) -> Self { - let pid = std::process::id(); - let seq = CLI_TEST_DIR_SEQ.fetch_add(1, Ordering::Relaxed); - let path = std::env::temp_dir().join(format!("curate-etl-cli-{tag}-{pid}-{seq}")); - fs::create_dir_all(&path).expect("create cli test temp dir"); - Self { path } - } -} - -impl Drop for CliTempDir { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.path); - } -} - -fn write_file(path: &std::path::Path, bytes: &[u8]) { - let mut f = File::create(path).expect("create file"); - f.write_all(bytes).expect("write file"); -} - -fn make_eod_doc(code: &str, date: &str, close: f64, volume: f64) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), code); - doc.append(cstr!("date"), date); - doc.append(cstr!("open"), close); - doc.append(cstr!("high"), close + 1.0); - doc.append(cstr!("low"), close - 1.0); - doc.append(cstr!("close"), close); - doc.append(cstr!("volume"), volume); - doc.into_bytes() -} - -fn make_split_doc(code: &str, date: &str, ratio: f64) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), code); - doc.append(cstr!("date"), date); - if ratio.is_finite() && ratio > 0.0 { - doc.append(cstr!("splitratio"), 1.0 / ratio); - doc.append(cstr!("forfactor"), 1.0_f64); - doc.append(cstr!("tofactor"), ratio); - } else { - doc.append(cstr!("splitratio"), ratio); - } - doc.into_bytes() -} - -#[test] -fn curate_bars_1d_cli_flag_errors_exit_nonzero_with_usage() { - for args in [ - &["curate-bars-1d"][..], - &[ - "curate-bars-1d", - "--eod-prices", - "e.bson", - "--qm-splits", - "s.bson", - "--provider-mapping", - "m.tsv", - "--listing-currencies", - "c.tsv", - ][..], - &[ - "curate-bars-1d", - "--eod-prices", - "e.bson", - "--eod-prices", - "e2.bson", - "--qm-splits", - "s.bson", - "--provider-mapping", - "m.tsv", - "--listing-currencies", - "c.tsv", - "--out", - "o", - ][..], - &[ - "curate-bars-1d", - "--eod-prices", - "e.bson", - "--qm-splits", - "s.bson", - "--provider-mapping", - "m.tsv", - "--listing-currencies", - "c.tsv", - "--out", - "o", - "--bogus", - "1", - ][..], - &[ - "curate-bars-1d", - "--eod-prices", - "e.bson", - "--qm-splits", - "s.bson", - "--provider-mapping", - "m.tsv", - "--listing-currencies", - "c.tsv", - "--out", - "o", - "--rel-tolerance", - "not-a-number", - ][..], - ] { - let out = run(args); - assert!(!out.status.success(), "{args:?} should fail"); - assert_eq!(out.status.code(), Some(1), "{args:?}"); - assert!(stdout(&out).is_empty(), "{args:?} wrote to stdout"); - let err = stderr(&out); - assert!(err.contains("error:"), "{args:?}: {err}"); - assert!(err.contains("Usage:"), "{args:?}: {err}"); - } -} - -#[test] -fn curate_bars_1d_cli_happy_path_and_determinism_with_shuffled_bson() { - let dir = CliTempDir::new("happy"); - let eod_a = dir.path.join("eod_a.bson"); - let eod_b = dir.path.join("eod_b.bson"); - let splits_a = dir.path.join("splits_a.bson"); - let splits_b = dir.path.join("splits_b.bson"); - let map_path = dir.path.join("provider_mapping.tsv"); - let curr_path = dir.path.join("listing_currencies.tsv"); - let out_a = dir.path.join("out_a"); - let out_b = dir.path.join("out_b"); - - write_file( - &map_path, - b"eod\tNVDA.US\t2010-01-01\t\t100\nqm\tNVDA:US\t2010-01-01\t\t100\n", - ); - write_file(&curr_path, b"100\tUSD\n"); - - let d1 = make_eod_doc("NVDA.US", "2024-06-07", 1208.88, 410_000_000.0); - let d2 = make_eod_doc("NVDA.US", "2024-06-10", 121.79, 310_000_000.0); - write_file(&eod_a, &[d1.as_slice(), d2.as_slice()].concat()); - write_file(&eod_b, &[d2.as_slice(), d1.as_slice()].concat()); - - let s1 = make_split_doc("NVDA:US", "2024-06-10", 10.0); - write_file(&splits_a, &s1); - write_file(&splits_b, &s1); - - let run_a = run(&[ - "curate-bars-1d", - "--eod-prices", - eod_a.to_str().unwrap(), - "--qm-splits", - splits_a.to_str().unwrap(), - "--provider-mapping", - map_path.to_str().unwrap(), - "--listing-currencies", - curr_path.to_str().unwrap(), - "--out", - out_a.to_str().unwrap(), - ]); - assert!(run_a.status.success(), "{}", stderr(&run_a)); - assert!(stderr(&run_a).is_empty(), "{}", stderr(&run_a)); - - let run_b = run(&[ - "curate-bars-1d", - "--eod-prices", - eod_b.to_str().unwrap(), - "--qm-splits", - splits_b.to_str().unwrap(), - "--provider-mapping", - map_path.to_str().unwrap(), - "--listing-currencies", - curr_path.to_str().unwrap(), - "--out", - out_b.to_str().unwrap(), - ]); - assert!(run_b.status.success(), "{}", stderr(&run_b)); - assert!(stderr(&run_b).is_empty(), "{}", stderr(&run_b)); - - let strip_timing = |s: &str| { - s.lines() - .filter(|l| !l.trim_start().starts_with("timing:")) - .collect::>() - .join("\n") - }; - let text_a = stdout(&run_a); - let text_b = stdout(&run_b); - assert!(text_a.contains("curate-etl curate-bars-1d"), "{text_a}"); - assert!(text_a.contains("rows_written=2"), "{text_a}"); - assert!(text_a.contains("2024=2"), "{text_a}"); - assert_eq!(strip_timing(&text_a), strip_timing(&text_b)); - - let pq_a = fs::read(out_a.join("bars_1d/year=2024/part.parquet")).unwrap(); - let pq_b = fs::read(out_b.join("bars_1d/year=2024/part.parquet")).unwrap(); - assert_eq!(pq_a, pq_b); - assert!(text_a.contains("qm_check: qm_prices=absent"), "{text_a}"); -} - -#[test] -fn curate_bars_1d_cli_threads_flag_parity_and_validation() { - let dir = CliTempDir::new("bars-threads-cli"); - let map_path = dir.path.join("provider_mapping.tsv"); - let curr_path = dir.path.join("listing_currencies.tsv"); - let eod_path = dir.path.join("eod.bson"); - let splits_path = dir.path.join("splits.bson"); - - fs::write( - &map_path, - "eod\tAAPL.US\t2020-01-01\t\t10\neod\tSHOP.TO\t2020-01-01\t\t20\nqm\tAAPL:US\t2020-01-01\t\t10\n", - ) - .unwrap(); - fs::write(&curr_path, "10\tUSD\n20\tCAD\n").unwrap(); - - let mut eod_bytes = Vec::new(); - eod_bytes.extend_from_slice(&make_eod_doc("AAPL.US", "2022-05-03", 150.0, 2_000.0)); - eod_bytes.extend_from_slice(&make_eod_doc("AAPL.US", "2023-06-05", 170.0, 1_500.0)); - eod_bytes.extend_from_slice(&make_eod_doc("SHOP.TO", "2024-07-08", 80.0, 3_000.0)); - eod_bytes.extend_from_slice(&make_eod_doc("SHOP.TO", "2025-02-10", 90.0, 2_500.0)); - fs::write(&eod_path, &eod_bytes).unwrap(); - fs::write(&splits_path, make_split_doc("AAPL:US", "2023-01-10", 2.0)).unwrap(); - - let out_t1 = dir.path.join("out_t1"); - let out_t4 = dir.path.join("out_t4"); - - let run_1 = run(&[ - "curate-bars-1d", - "--eod-prices", - eod_path.to_str().unwrap(), - "--qm-splits", - splits_path.to_str().unwrap(), - "--provider-mapping", - map_path.to_str().unwrap(), - "--listing-currencies", - curr_path.to_str().unwrap(), - "--out", - out_t1.to_str().unwrap(), - "--threads", - "1", - ]); - assert!(run_1.status.success(), "{}", stderr(&run_1)); - assert!(stderr(&run_1).is_empty(), "{}", stderr(&run_1)); - - let run_4 = run(&[ - "curate-bars-1d", - "--eod-prices", - eod_path.to_str().unwrap(), - "--qm-splits", - splits_path.to_str().unwrap(), - "--provider-mapping", - map_path.to_str().unwrap(), - "--listing-currencies", - curr_path.to_str().unwrap(), - "--out", - out_t4.to_str().unwrap(), - "--threads", - "4", - ]); - assert!(run_4.status.success(), "{}", stderr(&run_4)); - assert!(stderr(&run_4).is_empty(), "{}", stderr(&run_4)); - - let text_1 = stdout(&run_1); - let text_4 = stdout(&run_4); - assert!(text_1.contains(" config: threads=1\n"), "{text_1}"); - assert!(text_4.contains(" config: threads=4\n"), "{text_4}"); - - let strip_threads_and_timing = |s: &str| { - s.lines() - .filter(|l| { - let t = l.trim_start(); - !t.starts_with("config:") && !t.starts_with("timing:") - }) - .collect::>() - .join("\n") - }; - assert_eq!( - strip_threads_and_timing(&text_1), - strip_threads_and_timing(&text_4) - ); - - for year in [2022_i32, 2023, 2024, 2025] { - let rel = format!("bars_1d/year={year:04}/part.parquet"); - assert_eq!( - fs::read(out_t1.join(&rel)).unwrap(), - fs::read(out_t4.join(&rel)).unwrap(), - "CLI --threads 1 vs --threads 4 diverged on {rel}" - ); - } - - // Invalid --threads invocations must exit non-zero, print usage on stderr, and write nothing. - for (label, extra) in [ - ("zero", vec!["--threads", "0"]), - ("alpha", vec!["--threads", "abc"]), - ("neg", vec!["--threads=-1"]), - ("missing", vec!["--threads"]), - ("dup", vec!["--threads", "2", "--threads", "4"]), - ] { - let bad_out = dir.path.join(format!("out_bad_{label}")); - let mut argv = vec![ - "curate-bars-1d", - "--eod-prices", - eod_path.to_str().unwrap(), - "--qm-splits", - splits_path.to_str().unwrap(), - "--provider-mapping", - map_path.to_str().unwrap(), - "--listing-currencies", - curr_path.to_str().unwrap(), - "--out", - bad_out.to_str().unwrap(), - ]; - argv.extend(extra); - let res = run(&argv); - assert!( - !res.status.success(), - "{label}: expected non-zero exit, stdout={}", - stdout(&res) - ); - let err_text = stderr(&res); - assert!(err_text.contains("Usage:"), "{label}: missing usage in {err_text}"); - assert!( - !bad_out.exists(), - "{label}: invalid --threads must not create '{}'", - bad_out.display() - ); - } -} - -fn make_qm_price_doc(code: &str, date: &str, share_volume: f64) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), code); - doc.append(cstr!("date"), date); - doc.append(cstr!("sharevolume"), share_volume); - doc.into_bytes() -} - -#[test] -fn curate_bars_1d_cli_qm_prices_cross_check_and_framing_failures() { - let dir = CliTempDir::new("qm-prices-cli"); - let eod_path = dir.path.join("eod.bson"); - let splits_path = dir.path.join("splits.bson"); - let qm_path = dir.path.join("qm.bson"); - let map_path = dir.path.join("map.tsv"); - let curr_path = dir.path.join("curr.tsv"); - - write_file( - &map_path, - b"eod\tNVDA.US\t2020-01-01\t\t1\nqm\tNVDA:US\t2020-01-01\t\t1\n", - ); - write_file(&curr_path, b"1\tUSD\n"); - write_file(&splits_path, &make_split_doc("NVDA:US", "2024-06-10", 10.0)); - let d1 = make_eod_doc("NVDA.US", "2024-06-07", 1208.88, 412_390_000.0); - let d2 = make_eod_doc("NVDA.US", "2024-06-10", 121.79, 310_000_000.0); - write_file(&eod_path, &[d1.as_slice(), d2.as_slice()].concat()); - - // 2024-06-07 matches (41_239_000), 2024-06-10 has an injected >1% mismatch (300_000_000 vs 310_000_000). - let q1 = make_qm_price_doc("NVDA:US", "2024-06-07", 41_239_000.0); - let q2 = make_qm_price_doc("NVDA:US", "2024-06-10", 300_000_000.0); - write_file(&qm_path, &[q1.as_slice(), q2.as_slice()].concat()); - - let out_no_qm = dir.path.join("out_no_qm"); - let out_with_qm = dir.path.join("out_with_qm"); - let out_eq_qm = dir.path.join("out_eq_qm"); - - let run_no_qm = run(&[ - "curate-bars-1d", - "--eod-prices", - eod_path.to_str().unwrap(), - "--qm-splits", - splits_path.to_str().unwrap(), - "--provider-mapping", - map_path.to_str().unwrap(), - "--listing-currencies", - curr_path.to_str().unwrap(), - "--out", - out_no_qm.to_str().unwrap(), - ]); - assert!(run_no_qm.status.success(), "{}", stderr(&run_no_qm)); - assert!(stdout(&run_no_qm).contains("qm_check: qm_prices=absent")); - - // Mismatch still exits 0 and emits byte-identical Parquet. - let run_with_qm = run(&[ - "curate-bars-1d", - "--eod-prices", - eod_path.to_str().unwrap(), - "--qm-splits", - splits_path.to_str().unwrap(), - "--qm-prices", - qm_path.to_str().unwrap(), - "--provider-mapping", - map_path.to_str().unwrap(), - "--listing-currencies", - curr_path.to_str().unwrap(), - "--out", - out_with_qm.to_str().unwrap(), - ]); - assert!(run_with_qm.status.success(), "{}", stderr(&run_with_qm)); - assert!(stderr(&run_with_qm).is_empty(), "{}", stderr(&run_with_qm)); - let out_text = stdout(&run_with_qm); - assert!(out_text.contains("qm_bson:"), "{out_text}"); - assert!(out_text.contains("qm_rekey:"), "{out_text}"); - assert!( - out_text.contains("volume_checked=2 volume_within_tolerance=1 volume_mismatched=1 volume_unchecked=0"), - "{out_text}" - ); - assert!( - out_text.contains("qm_mismatch: key=NVDA.US session_date=2024-06-10"), - "{out_text}" - ); - - let pq_no_qm = fs::read(out_no_qm.join("bars_1d/year=2024/part.parquet")).unwrap(); - let pq_with_qm = fs::read(out_with_qm.join("bars_1d/year=2024/part.parquet")).unwrap(); - assert_eq!(pq_no_qm, pq_with_qm); - - // Equals syntax (`--qm-prices=`) via the documented `--curate-inputs ` - // directory + `current` symlink also succeeds, prints identical check counters/mismatches, - // and emits byte-identical Parquet. - let curate_inputs_dir = dir.path.join("curate_inputs"); - let gen_dir = curate_inputs_dir.join("gen-001"); - fs::create_dir_all(&gen_dir).unwrap(); - write_file( - &gen_dir.join("provider_mapping.tsv"), - b"eod\tNVDA.US\t2020-01-01\t\t1\nqm\tNVDA:US\t2020-01-01\t\t1\n", - ); - write_file(&gen_dir.join("listing_currencies.tsv"), b"1\tUSD\n"); - #[cfg(unix)] - std::os::unix::fs::symlink(&gen_dir, curate_inputs_dir.join("current")).unwrap(); - #[cfg(not(unix))] - { - fs::create_dir_all(curate_inputs_dir.join("current")).unwrap(); - write_file( - &curate_inputs_dir.join("current/provider_mapping.tsv"), - b"eod\tNVDA.US\t2020-01-01\t\t1\nqm\tNVDA:US\t2020-01-01\t\t1\n", - ); - write_file( - &curate_inputs_dir.join("current/listing_currencies.tsv"), - b"1\tUSD\n", - ); - } - - let eq_flag = format!("--qm-prices={}", qm_path.to_str().unwrap()); - let run_eq = run(&[ - "curate-bars-1d", - "--eod-prices", - eod_path.to_str().unwrap(), - "--qm-splits", - splits_path.to_str().unwrap(), - &eq_flag, - "--curate-inputs", - curate_inputs_dir.to_str().unwrap(), - "--out", - out_eq_qm.to_str().unwrap(), - ]); - assert!(run_eq.status.success(), "{}", stderr(&run_eq)); - assert!(stderr(&run_eq).is_empty(), "{}", stderr(&run_eq)); - let eq_out_text = stdout(&run_eq); - assert!(eq_out_text.contains("qm_bson:"), "{eq_out_text}"); - assert!(eq_out_text.contains("qm_rekey:"), "{eq_out_text}"); - assert!( - eq_out_text.contains( - "volume_checked=2 volume_within_tolerance=1 volume_mismatched=1 volume_unchecked=0" - ), - "{eq_out_text}" - ); - assert!( - eq_out_text.contains("qm_mismatch: key=NVDA.US session_date=2024-06-10"), - "{eq_out_text}" - ); - assert_eq!( - fs::read(out_eq_qm.join("bars_1d/year=2024/part.parquet")).unwrap(), - pq_no_qm - ); - - // Truncated --qm-prices fails closed with single-line stderr naming path, publishes nothing, - // and preserves a pre-existing dataset. - let trunc_qm = dir.path.join("trunc_qm.bson"); - let mut trunc_bytes = q1.clone(); - trunc_bytes.truncate(trunc_bytes.len() - 4); - write_file(&trunc_qm, &trunc_bytes); - - let out_trunc_fresh = dir.path.join("out_trunc_fresh"); - let res_trunc = run(&[ - "curate-bars-1d", - "--eod-prices", - eod_path.to_str().unwrap(), - "--qm-splits", - splits_path.to_str().unwrap(), - "--qm-prices", - trunc_qm.to_str().unwrap(), - "--provider-mapping", - map_path.to_str().unwrap(), - "--listing-currencies", - curr_path.to_str().unwrap(), - "--out", - out_trunc_fresh.to_str().unwrap(), - ]); - assert!(!res_trunc.status.success()); - assert!(stdout(&res_trunc).is_empty()); - let err_trunc = stderr(&res_trunc); - assert_eq!(err_trunc.lines().count(), 1, "{err_trunc}"); - assert!(err_trunc.contains("trunc_qm.bson"), "{err_trunc}"); - assert!(!out_trunc_fresh.join("bars_1d").exists()); - - // Pre-existing published output is untouched on failure. - let res_preserve = run(&[ - "curate-bars-1d", - "--eod-prices", - eod_path.to_str().unwrap(), - "--qm-splits", - splits_path.to_str().unwrap(), - "--qm-prices", - trunc_qm.to_str().unwrap(), - "--provider-mapping", - map_path.to_str().unwrap(), - "--listing-currencies", - curr_path.to_str().unwrap(), - "--out", - out_with_qm.to_str().unwrap(), - ]); - assert!(!res_preserve.status.success()); - assert_eq!( - fs::read(out_with_qm.join("bars_1d/year=2024/part.parquet")).unwrap(), - pq_with_qm - ); - - // Missing --qm-prices file fails closed. - let missing_qm = dir.path.join("missing_qm.bson"); - let res_missing = run(&[ - "curate-bars-1d", - "--eod-prices", - eod_path.to_str().unwrap(), - "--qm-splits", - splits_path.to_str().unwrap(), - "--qm-prices", - missing_qm.to_str().unwrap(), - "--provider-mapping", - map_path.to_str().unwrap(), - "--listing-currencies", - curr_path.to_str().unwrap(), - "--out", - dir.path.join("out_missing").to_str().unwrap(), - ]); - assert!(!res_missing.status.success()); - let err_missing = stderr(&res_missing); - assert_eq!(err_missing.lines().count(), 1, "{err_missing}"); - assert!(err_missing.contains("missing_qm.bson"), "{err_missing}"); -} - -#[test] -fn curate_bars_1d_cli_runtime_failures_single_line_stderr_and_no_partial_dataset() { - let dir = CliTempDir::new("fail"); - let eod_ok = dir.path.join("eod.bson"); - let splits_ok = dir.path.join("splits.bson"); - let map_ok = dir.path.join("map.tsv"); - let curr_ok = dir.path.join("curr.tsv"); - write_file(&eod_ok, &make_eod_doc("NVDA.US", "2024-06-07", 100.0, 1000.0)); - write_file(&splits_ok, b""); - write_file(&map_ok, b"eod\tNVDA.US\t2020-01-01\t\t1\n"); - write_file(&curr_ok, b"1\tUSD\n"); - - // 1. Malformed TSV line -> names path and 1-based line number, single-line stderr, no bars_1d. - let bad_map = dir.path.join("bad_map.tsv"); - write_file(&bad_map, b"eod\tNVDA.US\t2020-01-01\t\t1\nbad_line\n"); - let out1 = dir.path.join("out1"); - let res = run(&[ - "curate-bars-1d", - "--eod-prices", - eod_ok.to_str().unwrap(), - "--qm-splits", - splits_ok.to_str().unwrap(), - "--provider-mapping", - bad_map.to_str().unwrap(), - "--listing-currencies", - curr_ok.to_str().unwrap(), - "--out", - out1.to_str().unwrap(), - ]); - assert!(!res.status.success()); - assert!(stdout(&res).is_empty()); - let err = stderr(&res); - assert_eq!(err.lines().count(), 1, "expected single-line stderr: {err}"); - assert!(err.contains("bad_map.tsv:2:"), "{err}"); - assert!(!out1.join("bars_1d").exists()); - - // 2. Truncated BSON -> single-line stderr naming path, no bars_1d. - let trunc_eod = dir.path.join("trunc.bson"); - let mut doc = make_eod_doc("NVDA.US", "2024-06-07", 100.0, 1000.0); - doc.truncate(doc.len() - 4); - write_file(&trunc_eod, &doc); - let out2 = dir.path.join("out2"); - let res2 = run(&[ - "curate-bars-1d", - "--eod-prices", - trunc_eod.to_str().unwrap(), - "--qm-splits", - splits_ok.to_str().unwrap(), - "--provider-mapping", - map_ok.to_str().unwrap(), - "--listing-currencies", - curr_ok.to_str().unwrap(), - "--out", - out2.to_str().unwrap(), - ]); - assert!(!res2.status.success()); - assert!(stdout(&res2).is_empty()); - let err2 = stderr(&res2); - assert_eq!(err2.lines().count(), 1, "expected single-line stderr: {err2}"); - assert!(err2.contains("trunc.bson"), "{err2}"); - assert!(!out2.join("bars_1d").exists()); - - // 3. Missing input file -> single-line stderr naming path, no bars_1d. - let missing_eod = dir.path.join("missing_eod.bson"); - let out3 = dir.path.join("out3"); - let res3 = run(&[ - "curate-bars-1d", - "--eod-prices", - missing_eod.to_str().unwrap(), - "--qm-splits", - splits_ok.to_str().unwrap(), - "--provider-mapping", - map_ok.to_str().unwrap(), - "--listing-currencies", - curr_ok.to_str().unwrap(), - "--out", - out3.to_str().unwrap(), - ]); - assert!(!res3.status.success()); - assert!(stdout(&res3).is_empty()); - let err3 = stderr(&res3); - assert_eq!(err3.lines().count(), 1, "expected single-line stderr: {err3}"); - assert!(err3.contains("missing_eod.bson"), "{err3}"); - assert!(!out3.join("bars_1d").exists()); - - // 4. Oversized BSON document (> DEFAULT_MAX_DOC_BYTES) -> single-line stderr naming path, no bars_1d. - let huge_eod = dir.path.join("huge_eod.bson"); - let huge_len = (curate_etl::bson_stream::DEFAULT_MAX_DOC_BYTES as i32) + 1024; - let mut huge_bytes = Vec::from(huge_len.to_le_bytes()); - huge_bytes.push(0); - write_file(&huge_eod, &huge_bytes); - let out4 = dir.path.join("out4"); - let res4 = run(&[ - "curate-bars-1d", - "--eod-prices", - huge_eod.to_str().unwrap(), - "--qm-splits", - splits_ok.to_str().unwrap(), - "--provider-mapping", - map_ok.to_str().unwrap(), - "--listing-currencies", - curr_ok.to_str().unwrap(), - "--out", - out4.to_str().unwrap(), - ]); - assert!(!res4.status.success()); - assert!(stdout(&res4).is_empty()); - let err4 = stderr(&res4); - assert_eq!(err4.lines().count(), 1, "expected single-line stderr: {err4}"); - assert!(err4.contains("huge_eod.bson"), "{err4}"); - assert!(!out4.join("bars_1d").exists()); - - // 5. Overlapping mapping ranges -> single-line stderr naming path, no bars_1d. - let overlap_map = dir.path.join("overlap_map.tsv"); - write_file( - &overlap_map, - b"eod\tNVDA.US\t2020-01-01\t2022-12-31\t1\neod\tNVDA.US\t2022-06-01\t2024-12-31\t2\n", - ); - let out5 = dir.path.join("out5"); - let res5 = run(&[ - "curate-bars-1d", - "--eod-prices", - eod_ok.to_str().unwrap(), - "--qm-splits", - splits_ok.to_str().unwrap(), - "--provider-mapping", - overlap_map.to_str().unwrap(), - "--listing-currencies", - curr_ok.to_str().unwrap(), - "--out", - out5.to_str().unwrap(), - ]); - assert!(!res5.status.success()); - assert!(stdout(&res5).is_empty()); - let err5 = stderr(&res5); - assert_eq!(err5.lines().count(), 1, "expected single-line stderr: {err5}"); - assert!(err5.contains("overlap_map.tsv"), "{err5}"); - assert!(!out5.join("bars_1d").exists()); - - // 6. Conflicting cross-key QM alias splits -> single-line stderr naming path, no bars_1d. - let alias_map = dir.path.join("alias_map.tsv"); - write_file( - &alias_map, - b"eod\tNVDA.US\t2020-01-01\t\t1\nqm\tNVDA:US\t2020-01-01\t\t1\nqm\tNVDA_ALT:US\t2020-01-01\t\t1\n", - ); - let conflict_splits = dir.path.join("conflict_splits.bson"); - let c1 = make_split_doc("NVDA:US", "2024-06-10", 10.0); - let c2 = make_split_doc("NVDA_ALT:US", "2024-06-10", 4.0); - write_file(&conflict_splits, &[c1.as_slice(), c2.as_slice()].concat()); - let out6 = dir.path.join("out6"); - let res6 = run(&[ - "curate-bars-1d", - "--eod-prices", - eod_ok.to_str().unwrap(), - "--qm-splits", - conflict_splits.to_str().unwrap(), - "--provider-mapping", - alias_map.to_str().unwrap(), - "--listing-currencies", - curr_ok.to_str().unwrap(), - "--out", - out6.to_str().unwrap(), - ]); - assert!(!res6.status.success()); - assert!(stdout(&res6).is_empty()); - let err6 = stderr(&res6); - assert_eq!(err6.lines().count(), 1, "expected single-line stderr: {err6}"); - assert!(err6.contains("conflict_splits.bson"), "{err6}"); - assert!(!out6.join("bars_1d").exists()); - - // 7. Output write failure reaching the Parquet writer: `--out` is a valid directory, but - // `/bars_1d` is occupied by a regular file. - let out7 = dir.path.join("out7_obstructed"); - fs::create_dir_all(&out7).expect("create out7 dir"); - let bars_1d_file = out7.join("bars_1d"); - write_file(&bars_1d_file, b"sentinel"); - let res7 = run(&[ - "curate-bars-1d", - "--eod-prices", - eod_ok.to_str().unwrap(), - "--qm-splits", - splits_ok.to_str().unwrap(), - "--provider-mapping", - map_ok.to_str().unwrap(), - "--listing-currencies", - curr_ok.to_str().unwrap(), - "--out", - out7.to_str().unwrap(), - ]); - assert!(!res7.status.success()); - assert!(stdout(&res7).is_empty()); - let err7 = stderr(&res7); - assert_eq!(err7.lines().count(), 1, "expected single-line stderr: {err7}"); - assert!(err7.contains("out7_obstructed"), "{err7}"); - assert!(bars_1d_file.is_file()); - assert_eq!(fs::read(&bars_1d_file).unwrap(), b"sentinel"); - assert!(!out7.join("bars_1d/year=2024/part.parquet").exists()); -} - -#[test] -fn curate_bars_1d_cli_rejects_following_option_token_as_out_value_without_writing() { - let dir = CliTempDir::new("missing-out-opt"); - let eod_ok = dir.path.join("eod.bson"); - let splits_ok = dir.path.join("splits.bson"); - let map_ok = dir.path.join("map.tsv"); - let curr_ok = dir.path.join("curr.tsv"); - write_file(&eod_ok, &make_eod_doc("NVDA.US", "2024-06-07", 100.0, 1000.0)); - write_file(&splits_ok, b""); - write_file(&map_ok, b"eod\tNVDA.US\t2020-01-01\t\t1\n"); - write_file(&curr_ok, b"1\tUSD\n"); - - let res = Command::new(env!("CARGO_BIN_EXE_curate-etl")) - .current_dir(&dir.path) - .args([ - "curate-bars-1d", - "--eod-prices", - eod_ok.to_str().unwrap(), - "--qm-splits", - splits_ok.to_str().unwrap(), - "--provider-mapping", - map_ok.to_str().unwrap(), - "--listing-currencies", - curr_ok.to_str().unwrap(), - "--out", - "--rel-tolerence=0.01", - ]) - .output() - .expect("spawn curate-etl binary"); - - assert!(!res.status.success()); - assert_eq!(res.status.code(), Some(1)); - assert!(stdout(&res).is_empty()); - let err = stderr(&res); - assert!(err.contains("missing value for flag '--out'"), "{err}"); - assert!(err.contains("Usage:"), "{err}"); - assert!( - !dir.path.join("--rel-tolerence=0.01").exists(), - "must not create output directory named after following option token" - ); -} - -#[test] -fn bench_curate_bars_cmd_small_run_succeeds_and_reports_splits() { - let out = run(&["bench-curate-bars-cmd", "2000"]); - assert!(out.status.success(), "{}", stderr(&out)); - assert!(stderr(&out).is_empty(), "{}", stderr(&out)); - let text = stdout(&out); - assert!(text.contains("curate-etl bench-curate-bars-cmd"), "{text}"); - assert!(text.contains("rows=2000 "), "{text}"); - assert!(text.contains("qm_docs="), "{text}"); - assert!(text.contains("decode:"), "{text}"); - assert!(text.contains("qm:"), "{text}"); - assert!(text.contains("injected="), "{text}"); - assert!(text.contains("curate:"), "{text}"); - assert!(text.contains("write_1: threads=1 "), "{text}"); - assert!(text.contains("write:"), "{text}"); - assert!(text.contains("speedup="), "{text}"); - assert!(text.contains("total:"), "{text}"); - assert!(text.contains("bytes/bar"), "{text}"); -} - -fn make_div_doc(code: &str, date: &str, cash: f64, currency: &str) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), code); - doc.append(cstr!("date"), date); - doc.append(cstr!("amount"), cash); - doc.append(cstr!("currency"), currency); - doc.append(cstr!("usdFxRate"), 1_i32); - doc.into_bytes() -} - -#[test] -fn curate_adj_factors_cli_flag_errors_exit_nonzero_with_usage() { - for args in [ - &["curate-adj-factors"][..], - &[ - "curate-adj-factors", - "--qm-splits", - "s.bson", - "--qm-dividends", - "d.bson", - "--provider-mapping", - "m.tsv", - "--bars-1d", - "bars", - ][..], - &[ - "curate-adj-factors", - "--qm-splits", - "s.bson", - "--qm-splits", - "s2.bson", - "--qm-dividends", - "d.bson", - "--provider-mapping", - "m.tsv", - "--bars-1d", - "bars", - "--out", - "out", - ][..], - &[ - "curate-adj-factors", - "--qm-splits", - "s.bson", - "--qm-dividends", - "d.bson", - "--provider-mapping", - "m.tsv", - "--bars-1d", - "bars", - "--out", - "out", - "--unknown", - "1", - ][..], - ] { - let out = run(args); - assert!(!out.status.success(), "{args:?} should fail"); - assert_eq!(out.status.code(), Some(1), "{args:?}"); - assert!(stdout(&out).is_empty(), "{args:?} wrote to stdout"); - let err = stderr(&out); - assert!(err.contains("error:"), "{args:?}: {err}"); - assert!(err.contains("Usage:"), "{args:?}: {err}"); - } -} - -#[test] -fn curate_adj_factors_cli_happy_path_publishes_verified_snapshot() { - let dir = CliTempDir::new("adj-happy"); - let eod_path = dir.path.join("eod.bson"); - let splits_path = dir.path.join("splits.bson"); - let divs_path = dir.path.join("divs.bson"); - let map_path = dir.path.join("provider_mapping.tsv"); - let curr_path = dir.path.join("listing_currencies.tsv"); - let bars_out = dir.path.join("bars_out"); - let adj_out = dir.path.join("adj_out"); - - write_file( - &map_path, - b"eod\tNVDA.US\t2015-01-01\t\t100\nqm\tNVDA:US\t2015-01-01\t\t100\n", - ); - write_file(&curr_path, b"100\tUSD\n"); - write_file( - &eod_path, - &[ - make_eod_doc("NVDA.US", "2024-06-07", 1208.88, 410_000_000.0).as_slice(), - make_eod_doc("NVDA.US", "2024-06-10", 121.79, 310_000_000.0).as_slice(), - ] - .concat(), - ); - write_file(&splits_path, &make_split_doc("NVDA:US", "2024-06-10", 10.0)); - write_file( - &divs_path, - &make_div_doc("NVDA:US", "2024-06-11", 0.01, "USD"), - ); - - // First produce curated bars_1d via curate-bars-1d. - let bars_res = run(&[ - "curate-bars-1d", - "--eod-prices", - eod_path.to_str().unwrap(), - "--qm-splits", - splits_path.to_str().unwrap(), - "--provider-mapping", - map_path.to_str().unwrap(), - "--listing-currencies", - curr_path.to_str().unwrap(), - "--out", - bars_out.to_str().unwrap(), - ]); - assert!(bars_res.status.success(), "{}", stderr(&bars_res)); - - // Then run curate-adj-factors against that bars_1d dataset. - let adj_res = run(&[ - "curate-adj-factors", - "--qm-splits", - splits_path.to_str().unwrap(), - "--qm-dividends", - divs_path.to_str().unwrap(), - "--provider-mapping", - map_path.to_str().unwrap(), - "--bars-1d", - bars_out.join("bars_1d").to_str().unwrap(), - "--out", - adj_out.to_str().unwrap(), - ]); - assert!(adj_res.status.success(), "{}", stderr(&adj_res)); - assert!(stderr(&adj_res).is_empty(), "{}", stderr(&adj_res)); - let text = stdout(&adj_res); - assert!(text.contains("curate-etl curate-adj-factors"), "{text}"); - assert!(text.contains("with_prev_close=1"), "{text}"); - assert!(text.contains("rows_written=2"), "{text}"); - assert!(adj_out.join("adj_factors/part.parquet").is_file()); -} - -#[test] -fn bench_curate_adj_cmd_small_run_is_deterministic_and_reports_stages() { - let a = run(&["bench-curate-adj-cmd", "2000"]); - let b = run(&["bench-curate-adj-cmd", "2000"]); - assert!(a.status.success(), "{}", stderr(&a)); - assert!(b.status.success(), "{}", stderr(&b)); - assert!(stderr(&a).is_empty(), "{}", stderr(&a)); - assert!(stderr(&b).is_empty(), "{}", stderr(&b)); - - let text_a = stdout(&a); - let text_b = stdout(&b); - assert!(text_a.contains("curate-etl bench-curate-adj-cmd"), "{text_a}"); - assert!(text_a.contains("events=2000 "), "{text_a}"); - assert!(text_a.contains("bars_load:"), "{text_a}"); - assert!(text_a.contains("decode:"), "{text_a}"); - assert!(text_a.contains("curate:"), "{text_a}"); - assert!(text_a.contains("write:"), "{text_a}"); - assert!(text_a.contains("total:"), "{text_a}"); - assert!(text_a.contains("checksum=0x"), "{text_a}"); - - let field = |s: &str, prefix: &str| { - s.split_whitespace() - .find(|t| t.starts_with(prefix)) - .map(str::to_owned) - }; - assert_eq!(field(&text_a, "checksum="), field(&text_b, "checksum=")); - assert_eq!(field(&text_a, "rows_out="), field(&text_b, "rows_out=")); -} - -#[test] -fn curate_corporate_actions_cli_flag_errors_exit_nonzero_with_usage() { - for args in [ - &["curate-corporate-actions"][..], - &[ - "curate-corporate-actions", - "--qm-splits", - "s.bson", - "--qm-dividends", - "d.bson", - "--provider-mapping", - "m.tsv", - ][..], - &[ - "curate-corporate-actions", - "--qm-splits", - "s.bson", - "--qm-splits", - "s2.bson", - "--qm-dividends", - "d.bson", - "--provider-mapping", - "m.tsv", - "--out", - "out", - ][..], - &[ - "curate-corporate-actions", - "--qm-splits", - "s.bson", - "--qm-dividends", - "d.bson", - "--provider-mapping", - "m.tsv", - "--delistings", - "a.tsv", - "--delistings=b.tsv", - "--out", - "out", - ][..], - &[ - "curate-corporate-actions", - "--qm-splits", - "s.bson", - "--qm-dividends", - "d.bson", - "--provider-mapping", - "m.tsv", - "--out", - "out", - "--unknown", - "1", - ][..], - ] { - let out = run(args); - assert!(!out.status.success(), "{args:?} should fail"); - assert_eq!(out.status.code(), Some(1), "{args:?}"); - assert!(stdout(&out).is_empty(), "{args:?} wrote to stdout"); - let err = stderr(&out); - assert!(err.contains("error:"), "{args:?}: {err}"); - assert!(err.contains("Usage:"), "{args:?}: {err}"); - } -} - -#[test] -fn curate_corporate_actions_cli_happy_path_and_single_line_runtime_error() { - let dir = CliTempDir::new("corp-actions-cli"); - let splits_path = dir.path.join("splits.bson"); - let divs_path = dir.path.join("divs.bson"); - let map_path = dir.path.join("provider_mapping.tsv"); - let delist_path = dir.path.join("delistings.tsv"); - let bad_delist_path = dir.path.join("bad_delistings.tsv"); - let out_with_delist = dir.path.join("out_with"); - let out_without_delist = dir.path.join("out_without"); - let out_fail = dir.path.join("out_fail"); - - write_file( - &map_path, - b"qm\tNVDA:US\t2015-01-01\t\t100\n\ - qm\tSIVB:US\t2015-01-01\t2023-03-10\t300\n\ - qm\tSIVBQ:US\t2023-03-28\t\t301\n", - ); - write_file(&splits_path, &make_split_doc("NVDA:US", "2024-06-10", 10.0)); - write_file( - &divs_path, - &make_div_doc("NVDA:US", "2024-06-11", 0.01, "USD"), - ); - write_file(&delist_path, b"SIVB:US\t2023-03-28\t300\tSIVBQ:US\t\n"); - write_file(&bad_delist_path, b"SIVB:US\t2023-03-28\t\tSIVBQ:US\t\n"); - - // 1. Happy path with --delistings. - let res = run(&[ - "curate-corporate-actions", - "--qm-splits", - splits_path.to_str().unwrap(), - "--qm-dividends", - divs_path.to_str().unwrap(), - "--provider-mapping", - map_path.to_str().unwrap(), - "--delistings", - delist_path.to_str().unwrap(), - "--out", - out_with_delist.to_str().unwrap(), - ]); - assert!(res.status.success(), "{}", stderr(&res)); - assert!(stderr(&res).is_empty(), "{}", stderr(&res)); - let text = stdout(&res); - assert!(text.contains("curate-etl curate-corporate-actions"), "{text}"); - assert!(text.contains("rows_loaded=1"), "{text}"); - assert!(text.contains("rows_written=3"), "{text}"); - assert!(out_with_delist.join("corporate_actions/part.parquet").is_file()); - - // 2. Happy path without --delistings. - let res_no = run(&[ - "curate-corporate-actions", - "--qm-splits", - splits_path.to_str().unwrap(), - "--qm-dividends", - divs_path.to_str().unwrap(), - "--provider-mapping", - map_path.to_str().unwrap(), - "--out", - out_without_delist.to_str().unwrap(), - ]); - assert!(res_no.status.success(), "{}", stderr(&res_no)); - assert!(stderr(&res_no).is_empty(), "{}", stderr(&res_no)); - let text_no = stdout(&res_no); - assert!(text_no.contains("rows_loaded=0"), "{text_no}"); - assert!(text_no.contains("rows_written=2"), "{text_no}"); - assert!(out_without_delist - .join("corporate_actions/part.parquet") - .is_file()); - - // 3. Runtime error (malformed delistings TSV) -> single-line stderr, no Usage, no output. - let res_fail = run(&[ - "curate-corporate-actions", - "--qm-splits", - splits_path.to_str().unwrap(), - "--qm-dividends", - divs_path.to_str().unwrap(), - "--provider-mapping", - map_path.to_str().unwrap(), - "--delistings", - bad_delist_path.to_str().unwrap(), - "--out", - out_fail.to_str().unwrap(), - ]); - assert!(!res_fail.status.success()); - assert_eq!(res_fail.status.code(), Some(1)); - assert!(stdout(&res_fail).is_empty()); - let err = stderr(&res_fail); - assert_eq!(err.lines().count(), 1, "expected single-line stderr: {err}"); - assert!(err.contains("bad_delistings.tsv:1:"), "{err}"); - assert!(!err.contains("Usage:"), "{err}"); - assert!(!out_fail.join("corporate_actions").exists()); -} - -#[test] -fn bench_curate_corporate_actions_cmd_small_run_is_deterministic_and_reports_stages() { - let a = run(&["bench-curate-corporate-actions-cmd", "2000"]); - let b = run(&["bench-curate-corporate-actions-cmd", "2000"]); - assert!(a.status.success(), "{}", stderr(&a)); - assert!(b.status.success(), "{}", stderr(&b)); - assert!(stderr(&a).is_empty(), "{}", stderr(&a)); - assert!(stderr(&b).is_empty(), "{}", stderr(&b)); - - let text_a = stdout(&a); - let text_b = stdout(&b); - assert!( - text_a.contains("curate-etl bench-curate-corporate-actions-cmd"), - "{text_a}" - ); - assert!(text_a.contains("events=2000 "), "{text_a}"); - assert!(text_a.contains("decode:"), "{text_a}"); - assert!(text_a.contains("curate:"), "{text_a}"); - assert!(text_a.contains("write:"), "{text_a}"); - assert!(text_a.contains("total:"), "{text_a}"); - assert!(text_a.contains("checksum=0x"), "{text_a}"); - - let field = |s: &str, prefix: &str| { - s.split_whitespace() - .find(|t| t.starts_with(prefix)) - .map(str::to_owned) - }; - assert_eq!(field(&text_a, "checksum="), field(&text_b, "checksum=")); - assert_eq!(field(&text_a, "rows_out="), field(&text_b, "rows_out=")); -} - -#[test] -fn curate_fx_1d_cli_flag_errors_exit_nonzero_with_usage() { - for args in [ - &["curate-fx-1d"][..], - &[ - "curate-fx-1d", - "--eod-prices", - "e.bson", - "--te-market-data", - "t.bson", - ][..], - &[ - "curate-fx-1d", - "--eod-prices", - "e.bson", - "--te-market-data", - "t.bson", - "--te-symbol", - "USDCAD", - "--te-symbol=USDCAD", - "--out", - "out", - ][..], - &[ - "curate-fx-1d", - "--eod-prices", - "e.bson", - "--te-market-data", - "t.bson", - "--te-symbol", - "EURUSD", - "--out", - "out", - ][..], - &[ - "curate-fx-1d", - "--eod-prices", - "e.bson", - "--te-market-data", - "t.bson", - "--out", - "out", - "--unknown", - "1", - ][..], - ] { - let out = run(args); - assert!(!out.status.success(), "{args:?} should fail"); - assert_eq!(out.status.code(), Some(1), "{args:?}"); - assert!(stdout(&out).is_empty(), "{args:?} wrote to stdout"); - let err = stderr(&out); - assert!(err.contains("error:"), "{args:?}: {err}"); - assert!(err.contains("Usage:"), "{args:?}: {err}"); - assert!(err.contains("curate-fx-1d"), "{args:?}: {err}"); - } -} - -#[test] -fn curate_fx_1d_cli_happy_path_and_single_line_runtime_error() { - use bson::raw::{cstr, RawArrayBuf, RawDocumentBuf}; - - let dir = CliTempDir::new("fx-1d-cli"); - let eod_path = dir.path.join("eodPrices.bson"); - let te_path = dir.path.join("teMarketData.bson"); - let empty_eod_path = dir.path.join("empty_eod.bson"); - let empty_te_path = dir.path.join("empty_te.bson"); - let out_dir = dir.path.join("out"); - let out_fail = dir.path.join("out_fail"); - - let mut eod_doc = RawDocumentBuf::new(); - eod_doc.append(cstr!("eodSearchCode"), "CAD.FOREX"); - eod_doc.append(cstr!("date"), "2025-01-02"); - eod_doc.append(cstr!("open"), 1.430_f64); - eod_doc.append(cstr!("high"), 1.440_f64); - eod_doc.append(cstr!("low"), 1.425_f64); - eod_doc.append(cstr!("close"), 1.435_f64); - eod_doc.append(cstr!("volume"), 0.0_f64); - write_file(&eod_path, eod_doc.as_bytes()); - - let mut daily = RawArrayBuf::new(); - let mut pt = RawDocumentBuf::new(); - pt.append(cstr!("t"), 1_767_312_000_000_i64); // 2026-01-02 UTC in ms - pt.append(cstr!("o"), 1.380_f64); - pt.append(cstr!("h"), 1.390_f64); - pt.append(cstr!("l"), 1.375_f64); - pt.append(cstr!("c"), 1.385_f64); - daily.push(pt); - let mut te_doc = RawDocumentBuf::new(); - te_doc.append(cstr!("teSymbol"), "USDCAD"); - te_doc.append(cstr!("daily"), daily); - write_file(&te_path, te_doc.as_bytes()); - - write_file(&empty_eod_path, b""); - write_file(&empty_te_path, b""); - - // 1. Happy path - let res = run(&[ - "curate-fx-1d", - "--eod-prices", - eod_path.to_str().unwrap(), - "--te-market-data", - te_path.to_str().unwrap(), - "--out", - out_dir.to_str().unwrap(), - ]); - assert!(res.status.success(), "{}", stderr(&res)); - assert!(stderr(&res).is_empty(), "{}", stderr(&res)); - let text = stdout(&res); - assert!(text.contains("curate-etl curate-fx-1d"), "{text}"); - assert!(text.contains("rows_written=2"), "{text}"); - assert!(out_dir.join("fx_1d/part.parquet").is_file()); - - // 2. Runtime error (zero decoded bars) -> single-line stderr, no Usage, no output - let res_fail = run(&[ - "curate-fx-1d", - "--eod-prices", - empty_eod_path.to_str().unwrap(), - "--te-market-data", - empty_te_path.to_str().unwrap(), - "--out", - out_fail.to_str().unwrap(), - ]); - assert!(!res_fail.status.success()); - assert_eq!(res_fail.status.code(), Some(1)); - assert!(stdout(&res_fail).is_empty()); - let err = stderr(&res_fail); - assert_eq!(err.lines().count(), 1, "expected single-line stderr: {err}"); - assert!(err.contains("no FX bars decoded"), "{err}"); - assert!(!err.contains("Usage:"), "{err}"); - assert!(!out_fail.join("fx_1d").exists()); -} - -#[test] -fn bench_curate_fx_cmd_small_run_is_deterministic_and_reports_stages() { - let a = run(&["bench-curate-fx-cmd", "1000"]); - let b = run(&["bench-curate-fx-cmd", "1000"]); - assert!(a.status.success(), "{}", stderr(&a)); - assert!(b.status.success(), "{}", stderr(&b)); - assert!(stderr(&a).is_empty(), "{}", stderr(&a)); - assert!(stderr(&b).is_empty(), "{}", stderr(&b)); - - let text_a = stdout(&a); - let text_b = stdout(&b); - assert!(text_a.contains("curate-etl bench-curate-fx-cmd"), "{text_a}"); - assert!(text_a.contains("rows=1000 "), "{text_a}"); - assert!(text_a.contains("decode:"), "{text_a}"); - assert!(text_a.contains("curate:"), "{text_a}"); - assert!(text_a.contains("write:"), "{text_a}"); - assert!(text_a.contains("total:"), "{text_a}"); - assert!(text_a.contains("overlap:"), "{text_a}"); - assert!(text_a.contains("checksum=0x"), "{text_a}"); - - let field = |s: &str, prefix: &str| { - s.split_whitespace() - .find(|t| t.starts_with(prefix)) - .map(str::to_owned) - }; - assert_eq!(field(&text_a, "checksum="), field(&text_b, "checksum=")); - assert_eq!(field(&text_a, "rows_out="), field(&text_b, "rows_out=")); -} - -#[test] -fn curate_shorts_usage_errors_exit_nonzero_with_usage_on_stderr() { - let cases: &[(&[&str], &str)] = &[ - // Missing --shares-short-field - ( - &[ - "curate-shorts", - "--ceo-shorts", - "s.bson", - "--provider-mapping", - "m.tsv", - "--out", - "out", - ], - "--shares-short-field", - ), - // Duplicate flag - ( - &[ - "curate-shorts", - "--ceo-shorts", - "s.bson", - "--ceo-shorts", - "s2.bson", - "--provider-mapping", - "m.tsv", - "--out", - "out", - "--shares-short-field", - "sharesShort", - ], - "duplicate flag", - ), - // Unknown flag - ( - &[ - "curate-shorts", - "--ceo-shorts", - "s.bson", - "--provider-mapping", - "m.tsv", - "--out", - "out", - "--shares-short-field", - "sharesShort", - "--unknown-flag", - "x", - ], - "unknown flag", - ), - // Empty field name - ( - &[ - "curate-shorts", - "--ceo-shorts", - "s.bson", - "--provider-mapping", - "m.tsv", - "--out", - "out", - "--shares-short-field=", - ], - "empty value", - ), - // Two roles sharing one field name (collision with default 'timestamp') - ( - &[ - "curate-shorts", - "--ceo-shorts", - "s.bson", - "--provider-mapping", - "m.tsv", - "--out", - "out", - "--shares-short-field", - "timestamp", - ], - "cannot share BSON field", - ), - ]; - - for &(args, expected_substr) in cases { - let out = run(args); - assert!(!out.status.success(), "{args:?} should fail"); - assert_eq!(out.status.code(), Some(1), "{args:?}"); - assert!(stdout(&out).is_empty(), "{args:?} wrote to stdout"); - let err = stderr(&out); - assert!(err.contains("error:"), "{args:?}: {err}"); - assert!(err.contains(expected_substr), "{args:?}: {err}"); - assert!(err.contains("Usage:"), "{args:?}: {err}"); - } -} - -#[test] -fn bench_curate_shorts_command_small_run_is_deterministic_and_reports_stages() { - let a = run(&["bench-curate-shorts-command", "2000"]); - let b = run(&["bench-curate-shorts-command", "2000"]); - assert!(a.status.success(), "{}", stderr(&a)); - assert!(b.status.success(), "{}", stderr(&b)); - assert!(stderr(&a).is_empty(), "{}", stderr(&a)); - assert!(stderr(&b).is_empty(), "{}", stderr(&b)); - - let text_a = stdout(&a); - let text_b = stdout(&b); - assert!( - text_a.contains("curate-etl bench-curate-shorts-command"), - "{text_a}" - ); - assert!(text_a.contains("rows=2000 "), "{text_a}"); - assert!(text_a.contains("peak_chunk_bytes="), "{text_a}"); - assert!(text_a.contains("decode:"), "{text_a}"); - assert!(text_a.contains("curate:"), "{text_a}"); - assert!(text_a.contains("write:"), "{text_a}"); - assert!(text_a.contains("total:"), "{text_a}"); - assert!(text_a.contains("rows/s"), "{text_a}"); - assert!(text_a.contains("checksum=0x"), "{text_a}"); - - let field = |s: &str, prefix: &str| { - s.split_whitespace() - .find(|t| t.starts_with(prefix)) - .map(str::to_owned) - }; - assert_eq!(field(&text_a, "checksum="), field(&text_b, "checksum=")); - assert_eq!(field(&text_a, "rows_out="), field(&text_b, "rows_out=")); -} - -#[test] -fn send_ilp_cli_help_missing_flag_success_and_partial_error_routing() { - use std::io::{self, Read}; - use std::net::TcpListener; - use std::thread; - use std::time::{Duration, Instant}; - - // 1. --help lists send-ilp, required flags, and delivery caveat. - let help = run(&["--help"]); - assert!(help.status.success(), "{}", stderr(&help)); - let help_text = stdout(&help); - assert!(help_text.contains("send-ilp"), "{help_text}"); - assert!( - help_text.contains("--dir") - && help_text.contains("--prefix") - && help_text.contains("--addr"), - "{help_text}" - ); - assert!(help_text.contains("PGWire"), "{help_text}"); - assert!(help_text.contains("10.2.0"), "{help_text}"); - - // 2. Missing --addr exits non-zero with error + Usage on stderr and empty stdout. - let missing_addr = run(&["send-ilp", "--dir", "/tmp/shards", "--prefix", "fx_1m"]); - assert!(!missing_addr.status.success()); - assert_eq!(missing_addr.status.code(), Some(1)); - assert!(stdout(&missing_addr).is_empty()); - let missing_err = stderr(&missing_addr); - assert!( - missing_err.contains("error: missing required flag '--addr'"), - "{missing_err}" - ); - assert!(missing_err.contains("Usage:"), "{missing_err}"); - assert!(missing_err.contains("send-ilp"), "{missing_err}"); - - // 3. Binary success path over loopback prints format_ilp_send_report to stdout. - let dir = CliTempDir::new("send-ilp-bin"); - let payload0 = b"fx_1m,pair=USDCAD close=1.38 1700000000000000t\n"; - let payload1 = b""; - write_file(&dir.path.join("fx_1m.shard-00.ilp"), payload0); - write_file(&dir.path.join("fx_1m.shard-01.ilp"), payload1); - - let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback listener"); - let listen_addr = listener.local_addr().expect("local addr"); - listener - .set_nonblocking(true) - .expect("set loopback listener nonblocking"); - let server = thread::spawn(move || { - let deadline = Instant::now() + Duration::from_secs(5); - let mut received = Vec::with_capacity(2); - for accepted in 0..2 { - let mut stream = loop { - match listener.accept() { - Ok((s, _)) => { - s.set_nonblocking(false).expect("set stream blocking"); - break s; - } - Err(err) if err.kind() == io::ErrorKind::WouldBlock => { - assert!( - Instant::now() < deadline, - "timed out waiting for connection {accepted}/2" - ); - thread::sleep(Duration::from_millis(5)); - } - Err(err) => panic!("accept failed: {err}"), - } - }; - stream - .set_read_timeout(Some(Duration::from_secs(3))) - .expect("set read timeout"); - let mut buf = Vec::new(); - stream.read_to_end(&mut buf).expect("read shard to EOF"); - received.push(buf); - } - received - }); - - let ok_out = run(&[ - "send-ilp", - "--dir", - dir.path.to_str().unwrap(), - "--prefix", - "fx_1m", - "--addr", - &listen_addr.to_string(), - ]); - let mut received = server.join().expect("join server"); - received.sort(); - let mut expected_payloads = vec![payload0.to_vec(), payload1.to_vec()]; - expected_payloads.sort(); - assert_eq!(received, expected_payloads); - - assert!(ok_out.status.success(), "{}", stderr(&ok_out)); - assert!(stderr(&ok_out).is_empty(), "{}", stderr(&ok_out)); - assert_eq!( - stdout(&ok_out), - format!( - "curate-etl ilp-send\n ilp_send: shards=2 total_bytes_sent={} per_shard_bytes=00={},01=0\n", - payload0.len(), - payload0.len() - ) - ); - - // 4. Runtime connect failure prints error + formatted partial report to stderr, empty stdout. - let dead_listener = TcpListener::bind("127.0.0.1:0").expect("bind ephemeral port"); - let dead_addr = dead_listener.local_addr().expect("ephemeral addr"); - drop(dead_listener); - - let fail_out = run(&[ - "send-ilp", - "--dir", - dir.path.to_str().unwrap(), - "--prefix", - "fx_1m", - "--addr", - &dead_addr.to_string(), - ]); - assert!(!fail_out.status.success()); - assert_eq!(fail_out.status.code(), Some(1)); - assert!(stdout(&fail_out).is_empty()); - let fail_err = stderr(&fail_out); - assert!(fail_err.contains("error: ILP shard 0"), "{fail_err}"); - assert!( - fail_err.contains( - "curate-etl ilp-send\n ilp_send: shards=2 total_bytes_sent=0 per_shard_bytes=00=0,01=0" - ), - "{fail_err}" - ); - assert!(!fail_err.contains("Usage:"), "{fail_err}"); -} - -#[test] -fn send_ilp_cli_shard_gap_exits_without_partial_report_or_connect_and_bad_prefix_prints_usage() { - use std::io; - use std::net::TcpListener; - - // 1. Shard gap -> exits 1, empty stdout, error on stderr, no partial report, zero connections. - let gap_dir = CliTempDir::new("send-ilp-bin-gap"); - write_file(&gap_dir.path.join("bars_1m.shard-00.ilp"), b"a"); - write_file(&gap_dir.path.join("bars_1m.shard-02.ilp"), b"c"); - - let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback listener"); - let listen_addr = listener.local_addr().expect("local addr"); - listener - .set_nonblocking(true) - .expect("set listener nonblocking"); - - let gap_out = run(&[ - "send-ilp", - "--dir", - gap_dir.path.to_str().unwrap(), - "--prefix", - "bars_1m", - "--addr", - &listen_addr.to_string(), - ]); - assert!(!gap_out.status.success()); - assert_eq!(gap_out.status.code(), Some(1)); - assert!(stdout(&gap_out).is_empty()); - let gap_err = stderr(&gap_out); - assert!(gap_err.contains("error:"), "{gap_err}"); - assert!(!gap_err.contains("curate-etl ilp-send"), "{gap_err}"); - assert!(!gap_err.contains("Usage:"), "{gap_err}"); - match listener.accept() { - Err(err) if err.kind() == io::ErrorKind::WouldBlock => {} - Ok((_, peer)) => panic!("shard gap unexpectedly connected from {peer}"), - Err(err) => panic!("unexpected accept error: {err}"), - } - - // 2. Bad prefix -> exits 1, empty stdout, error + Usage on stderr. - let bad_prefix_out = run(&[ - "send-ilp", - "--dir", - gap_dir.path.to_str().unwrap(), - "--prefix", - "bars_1d", - "--addr", - &listen_addr.to_string(), - ]); - assert!(!bad_prefix_out.status.success()); - assert_eq!(bad_prefix_out.status.code(), Some(1)); - assert!(stdout(&bad_prefix_out).is_empty()); - let bad_prefix_err = stderr(&bad_prefix_out); - assert!(bad_prefix_err.contains("error:"), "{bad_prefix_err}"); - assert!( - bad_prefix_err.contains("bars_1m") - && bad_prefix_err.contains("bars_1m_qm") - && bad_prefix_err.contains("fx_1m"), - "{bad_prefix_err}" - ); - assert!(bad_prefix_err.contains("Usage:"), "{bad_prefix_err}"); -} - -#[test] -fn send_ilp_cli_ignores_questdb_env_vars_and_requires_explicit_addr() { - use std::io; - use std::net::TcpListener; - - // Arrange: a valid shard set plus a live loopback listener advertised through every - // plausible env name. If the binary ever fell back to env, it would connect here. - let dir = CliTempDir::new("send-ilp-bin-env"); - write_file(&dir.path.join("fx_1m.shard-00.ilp"), b"x\n"); - let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback listener"); - let listen_addr = listener.local_addr().expect("local addr").to_string(); - listener - .set_nonblocking(true) - .expect("set listener nonblocking"); - - // Act - let out = Command::new(env!("CARGO_BIN_EXE_curate-etl")) - .args([ - "send-ilp", - "--dir", - dir.path.to_str().unwrap(), - "--prefix", - "fx_1m", - ]) - .env("QUESTDB_ILP_ADDR", &listen_addr) - .env("QUESTDB_ADDR", &listen_addr) - .env("ILP_ADDR", &listen_addr) - .env("QDB_CLIENT_CONF", format!("tcp::addr={listen_addr};")) - .output() - .expect("spawn curate-etl binary"); - - // Assert - assert_eq!(out.status.code(), Some(1)); - assert!(stdout(&out).is_empty(), "{}", stdout(&out)); - assert!( - stderr(&out).contains("missing required flag '--addr'"), - "{}", - stderr(&out) - ); - match listener.accept() { - Err(err) if err.kind() == io::ErrorKind::WouldBlock => {} - Ok((_, peer)) => panic!("env-derived address was used: connection from {peer}"), - Err(err) => panic!("unexpected accept error: {err}"), - } -} diff --git a/tools/curate-etl/tests/curate_adj_qa_contract.rs b/tools/curate-etl/tests/curate_adj_qa_contract.rs deleted file mode 100644 index de5164d4..00000000 --- a/tools/curate-etl/tests/curate_adj_qa_contract.rs +++ /dev/null @@ -1,418 +0,0 @@ -//! QA contract tests for the public `adj_factors` curation stage (T-106 / M1.2v). -//! -//! Complements the in-crate `curate_adj_tests.rs` with checks against independent references -//! built only from the public API: -//! - seeded differential test: per-bar split factors across ticker renames, ticker reuse and -//! unmapped gaps equal a naive per-listing product of later split ratios; -//! - fenced publish → separate reopen equals the naive reference over only the events whose -//! conservative `16:00 ET` known_at is `<= as_of`, and every reopened row honours the fence; -//! - re-publishing a smaller fenced snapshot over a larger retrospective one leaves exactly one -//! `part.parquet` whose footer carries the `stock_bot.adj_factors.*` keys and contract schema; -//! - `bench-curate-adj` binary run: checksum/bytes/rows pinned to the README values, temp dir -//! cleaned. - -use std::collections::{BTreeMap, HashSet}; -use std::fs::{self, File}; -use std::path::PathBuf; -use std::process::Command; -use std::sync::atomic::{AtomicU64, Ordering}; - -use curate_etl::{ - adj_factors_for_bar, adj_factors_parquet_schema, curate_adj_factors, - curate_and_write_adj_factors, curate_and_write_adj_factors_as_of, et_session_close_utc_micros, - read_adj_factors_dataset, read_adj_factors_dataset_as_of, ymd_to_epoch_days, - AdjFactorsWriteOptions, AdjPointInTimeFence, AdjSnapshotKind, CurateAdjReadError, - DividendEvent, ProviderMappingRow, ProviderMappingTable, SplitEvent, -}; -use parquet::file::reader::{FileReader, SerializedFileReader}; - -static SEQ: AtomicU64 = AtomicU64::new(0); - -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-curate-adj-qa-{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); - } -} - -struct SplitMix64(u64); - -impl SplitMix64 { - 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 day(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).expect("valid date") -} - -fn map_row(key: &str, from: i32, to: Option, listing_id: i32) -> ProviderMappingRow { - ProviderMappingRow { - source: "qm".to_string(), - source_id: key.to_string(), - valid_from: from, - valid_to: to, - listing_id, - } -} - -/// Exactly representable ratios so the naive product is order-independent. -const RATIOS: [f64; 6] = [2.0, 0.5, 4.0, 0.25, 3.0, 1.0]; - -struct Fixture { - mapping: ProviderMappingTable, - splits: Vec<(String, SplitEvent)>, - /// Naive reference: listing_id -> (ex_date -> ratio) for every mapped split (incl. 1:1). - reference: BTreeMap>, - min: i32, - max: i32, -} - -/// Layout per listing group `g` (deterministic): -/// - listing `3g+1`: single key `S{g}` for the whole span; -/// - listing `3g+2`: key `OLD{g}` until 2012-12-31, renamed to `NEW{g}` from 2013-01-01; -/// - key `RE{g}` maps to listing `3g+3` until 2015-06-30, unmapped through 2015, then to listing -/// `100_000 + g` from 2016-01-01 (ticker reuse with a gap). -fn seeded_fixture(seed: u64, groups: i32, events: usize) -> Fixture { - let min = day(2000, 1, 1); - let max = day(2025, 12, 31); - let rename = day(2012, 12, 31); - let reuse_old_end = day(2015, 6, 30); - let reuse_new_start = day(2016, 1, 1); - - let mut rows = Vec::new(); - for g in 0..groups { - rows.push(map_row(&format!("S{g}"), min, None, 3 * g + 1)); - rows.push(map_row(&format!("OLD{g}"), min, Some(rename), 3 * g + 2)); - rows.push(map_row(&format!("NEW{g}"), rename + 1, None, 3 * g + 2)); - rows.push(map_row( - &format!("RE{g}"), - min, - Some(reuse_old_end), - 3 * g + 3, - )); - rows.push(map_row( - &format!("RE{g}"), - reuse_new_start, - None, - 100_000 + g, - )); - } - let mapping = ProviderMappingTable::from_rows(rows).expect("valid mapping"); - - let mut rng = SplitMix64(seed); - let mut seen: HashSet<(String, i32)> = HashSet::new(); - let mut splits = Vec::new(); - let mut reference: BTreeMap> = BTreeMap::new(); - while splits.len() < events { - let g = rng.below(groups as u64) as i32; - let ex_date = min + rng.below((max - min + 1) as u64) as i32; - let (key, listing) = match rng.below(4) { - 0 => (format!("S{g}"), Some(3 * g + 1)), - 1 if ex_date <= rename => (format!("OLD{g}"), Some(3 * g + 2)), - 1 => (format!("NEW{g}"), Some(3 * g + 2)), - 2 if ex_date <= reuse_old_end => (format!("RE{g}"), Some(3 * g + 3)), - 2 if ex_date < reuse_new_start => (format!("RE{g}"), None), - 2 => (format!("RE{g}"), Some(100_000 + g)), - _ => (format!("UNMAPPED{g}"), None), - }; - // One event per (key, ex_date): same-key same-day multiplication is the builder's own - // contract and is covered in-crate. - if !seen.insert((key.clone(), ex_date)) { - continue; - } - let ratio = RATIOS[rng.below(RATIOS.len() as u64) as usize]; - if let Some(listing_id) = listing { - reference - .entry(listing_id) - .or_default() - .insert(ex_date, ratio); - } - splits.push((key, SplitEvent { ex_date, ratio })); - } - Fixture { - mapping, - splits, - reference, - min, - max, - } -} - -/// Product of every reference split ratio with `ex_date > bar_date` for `listing_id`. -fn naive_factor( - reference: &BTreeMap>, - listing_id: i32, - bar_date: i32, - admit: impl Fn(i32) -> bool, -) -> f64 { - reference.get(&listing_id).map_or(1.0, |events| { - events - .range(bar_date + 1..) - .filter(|(ex, _)| admit(**ex)) - .map(|(_, r)| *r) - .product() - }) -} - -const NO_DIVIDENDS: [(String, DividendEvent); 0] = []; - -#[test] -fn seeded_split_factors_match_naive_per_listing_reference_across_rename_reuse_and_gaps() { - let fx = seeded_fixture(0xAD0A_115E_ED00, 40, 3_000); - let out = - curate_adj_factors(&fx.mapping, "qm", fx.splits.clone(), NO_DIVIDENDS).expect("curate"); - - assert_eq!(out.snapshot_kind, AdjSnapshotKind::RetrospectiveSnapshot); - let mapped: usize = fx.reference.values().map(BTreeMap::len).sum(); - assert_eq!(out.stats.splits_in, fx.splits.len()); - assert_eq!( - out.stats.splits_dropped_unmapped, - fx.splits.len() - mapped, - "unmapped count must equal events with no covering range" - ); - assert_eq!(out.stats.splits_collision_collapsed, 0); - assert_eq!(out.stats.builder.split_events_in, mapped); - let noops = fx - .reference - .values() - .flat_map(BTreeMap::values) - .filter(|r| **r == 1.0) - .count(); - assert_eq!(out.stats.builder.split_noops_dropped, noops); - assert_eq!(out.stats.rows_out, mapped - noops); - assert!(out.stats.splits_dropped_unmapped > 0 && noops > 0); - - let mut rng = SplitMix64(0x0B5E_55ED); - let listings: Vec = fx.reference.keys().copied().collect(); - for _ in 0..5_000 { - let listing_id = listings[rng.below(listings.len() as u64) as usize]; - let bar = fx.min - 5 + rng.below((fx.max - fx.min + 10) as u64) as i32; - let expected = naive_factor(&fx.reference, listing_id, bar, |_| true); - let (split, _total) = adj_factors_for_bar(&out.rows, listing_id, bar); - assert_eq!( - split.to_bits(), - expected.to_bits(), - "listing {listing_id} bar {bar}: got {split}, expected {expected}" - ); - } - // Unknown listing never picks up another listing's chain. - assert_eq!(adj_factors_for_bar(&out.rows, 99_999, fx.min), (1.0, 1.0)); -} - -#[test] -fn fenced_publish_then_separate_reopen_matches_naive_filtered_reference() { - let fx = seeded_fixture(0xFE11_CE00, 25, 2_000); - let tmp = TempDir::new("fenced-reopen"); - // As of 2018-03-14 12:00 UTC: an ex-date of 2018-03-14 (close 20:00 UTC) is still unknown. - let as_of = et_session_close_utc_micros(day(2018, 3, 14)).unwrap() - 8 * 3_600_000_000; - let fence = AdjPointInTimeFence::as_of(as_of); - - let report = curate_and_write_adj_factors_as_of( - &tmp.0, - &fx.mapping, - "qm", - fx.splits.clone(), - NO_DIVIDENDS, - fence, - AdjFactorsWriteOptions { - row_group_rows: 11, - ..Default::default() - }, - ) - .expect("fenced publish"); - assert_eq!( - report.snapshot_kind, - AdjSnapshotKind::PointInTimeFenced(fence) - ); - assert!(report.curate_stats.splits_dropped_fenced > 0); - - // Separate read step: only the published artifact is consulted. - let snap = read_adj_factors_dataset_as_of(&tmp.0, fence).expect("reopen"); - assert_eq!( - snap.snapshot_kind, - AdjSnapshotKind::PointInTimeFenced(fence) - ); - assert_eq!(snap.rows.len(), report.write_stats.rows_written); - for row in &snap.rows { - assert!(row.known_at_micros <= as_of, "row beyond as_of: {row:?}"); - } - for w in snap.rows.windows(2) { - assert!((w[0].listing_id, w[0].ex_date) < (w[1].listing_id, w[1].ex_date)); - } - - let admitted = |ex: i32| et_session_close_utc_micros(ex).unwrap() <= as_of; - let mut rng = SplitMix64(0xA5_0F); - let listings: Vec = fx.reference.keys().copied().collect(); - for _ in 0..3_000 { - let listing_id = listings[rng.below(listings.len() as u64) as usize]; - let bar = fx.min + rng.below((day(2018, 3, 14) - fx.min) as u64) as i32; - let expected = naive_factor(&fx.reference, listing_id, bar, admitted); - let (split, _) = snap.factors_for_bar(listing_id, bar); - assert_eq!( - split.to_bits(), - expected.to_bits(), - "listing {listing_id} bar {bar} as_of {as_of}" - ); - } - - // A neighbouring fence one microsecond later is a different artifact and must be refused. - let other = AdjPointInTimeFence::as_of(as_of + 1); - assert!(matches!( - read_adj_factors_dataset_as_of(&tmp.0, other), - Err(CurateAdjReadError::IncompatibleFence { .. }) - )); -} - -#[test] -fn smaller_fenced_republish_supersedes_larger_retrospective_snapshot_in_one_file() { - let fx = seeded_fixture(0x5_0BE5, 30, 2_500); - let tmp = TempDir::new("republish"); - - let retro = curate_and_write_adj_factors( - &tmp.0, - &fx.mapping, - "qm", - fx.splits.clone(), - NO_DIVIDENDS, - AdjFactorsWriteOptions::default(), - ) - .expect("retrospective publish"); - let fence = AdjPointInTimeFence::as_of_with_vault_cutoff( - et_session_close_utc_micros(day(2024, 6, 28)).unwrap(), - et_session_close_utc_micros(day(2005, 1, 3)).unwrap(), - ); - assert!(matches!( - read_adj_factors_dataset_as_of(&tmp.0, fence), - Err(CurateAdjReadError::RetrospectiveSnapshotRejected { .. }) - )); - - let fenced = curate_and_write_adj_factors_as_of( - &tmp.0, - &fx.mapping, - "qm", - fx.splits.clone(), - NO_DIVIDENDS, - fence, - AdjFactorsWriteOptions::default(), - ) - .expect("fenced publish"); - assert!(fenced.write_stats.rows_written < retro.write_stats.rows_written); - - let names: Vec = fs::read_dir(tmp.0.join("adj_factors")) - .unwrap() - .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) - .collect(); - assert_eq!(names, vec!["part.parquet".to_string()]); - - // Vault cutoff wins over the later as_of: every row is strictly before the vault boundary. - let snap = read_adj_factors_dataset(&tmp.0).expect("reopen"); - assert_eq!( - snap.snapshot_kind, - AdjSnapshotKind::PointInTimeFenced(fence) - ); - assert_eq!(snap.rows.len(), fenced.write_stats.rows_written); - let vault = fence.vault_cutoff_micros.unwrap(); - assert!(snap.rows.iter().all(|r| r.known_at_micros < vault)); - - // A generic Parquet reader sees the contract schema and the bound footer keys. - let path = tmp.0.join("adj_factors").join("part.parquet"); - let reader = SerializedFileReader::new(File::open(&path).unwrap()).unwrap(); - let file_meta = reader.metadata().file_metadata(); - assert_eq!( - file_meta.schema(), - adj_factors_parquet_schema().unwrap().as_ref() - ); - assert_eq!(file_meta.num_rows() as usize, snap.rows.len()); - let kv: BTreeMap> = file_meta - .key_value_metadata() - .expect("footer key_value_metadata") - .iter() - .map(|kv| (kv.key.clone(), kv.value.clone())) - .filter(|(k, _)| k.starts_with("stock_bot.adj_factors.")) - .collect(); - let get = |k: &str| kv[&format!("stock_bot.adj_factors.{k}")].as_deref(); - assert_eq!(kv.len(), 6, "{kv:?}"); - assert_eq!(get("format_version"), Some("1")); - assert_eq!(get("snapshot_kind"), Some("point_in_time_fenced")); - assert_eq!( - get("as_of_micros"), - Some(fence.as_of_micros.unwrap().to_string().as_str()) - ); - assert_eq!(get("vault_cutoff_micros"), Some(vault.to_string().as_str())); - assert_eq!( - get("rows_written"), - Some(snap.rows.len().to_string().as_str()) - ); -} - -fn field<'a>(text: &'a str, prefix: &str) -> Option<&'a str> { - text.split_whitespace() - .find(|t| t.starts_with(prefix)) - .map(|t| &t[prefix.len()..]) -} - -#[test] -fn bench_curate_adj_default_run_matches_readme_values_and_cleans_temp_dir() { - let tmp = TempDir::new("bench-tmpdir"); - let output = Command::new(env!("CARGO_BIN_EXE_curate-etl")) - .arg("bench-curate-adj") - .env("TMPDIR", &tmp.0) - .output() - .expect("run curate-etl"); - let stdout = String::from_utf8_lossy(&output.stdout); - assert!( - output.status.success(), - "stderr: {}", - String::from_utf8_lossy(&output.stderr) - ); - - // Values recorded in tools/curate-etl/README.md (`bench-curate-adj`, default 1,000,000). - assert_eq!(field(&stdout, "events="), Some("1000000"), "{stdout}"); - assert_eq!(field(&stdout, "splits="), Some("40221"), "{stdout}"); - assert_eq!(field(&stdout, "dividends="), Some("959779"), "{stdout}"); - assert_eq!( - field(&stdout, "checksum="), - Some("0x024ec73a1afe7e6b"), - "{stdout}" - ); - assert_eq!(field(&stdout, "bytes="), Some("11872037"), "{stdout}"); - assert_eq!( - field(&stdout, "read_back_rows="), - Some("946414"), - "{stdout}" - ); - assert_eq!(field(&stdout, "rows_out="), Some("946414"), "{stdout}"); - assert_eq!(field(&stdout, "coll_collapsed="), Some("4930"), "{stdout}"); - - let leftovers: Vec<_> = fs::read_dir(&tmp.0) - .unwrap() - .map(|e| e.unwrap().file_name()) - .collect(); - assert!( - leftovers.is_empty(), - "bench left temp entries: {leftovers:?}" - ); -} diff --git a/tools/curate-etl/tests/curate_bars_1m.rs b/tools/curate-etl/tests/curate_bars_1m.rs deleted file mode 100644 index f1b43972..00000000 --- a/tools/curate-etl/tests/curate_bars_1m.rs +++ /dev/null @@ -1,635 +0,0 @@ -//! End-to-end binary integration tests for `curate-etl curate-bars-1m` (`M2.3n`). - -use std::collections::BTreeMap; -use std::fs; -use std::path::{Path, PathBuf}; -use std::process::{Command, Output}; -use std::sync::atomic::{AtomicU64, Ordering}; - -use bson::raw::{cstr, RawDocumentBuf}; -use curate_etl::{ - et_to_utc_micros, format_curate_bars_1m_report, run_curate_bars_1m, ymd_to_epoch_days, - BsonStreamOptions, CurateBars1mArgs, IlpWriterOptions, DEFAULT_BARS_1M_MAPPING_SOURCE, -}; - -static TEST_DIR_SEQ: AtomicU64 = AtomicU64::new(0); - -struct TempDir { - path: PathBuf, -} - -impl TempDir { - fn new(tag: &str) -> Self { - let pid = std::process::id(); - let seq = TEST_DIR_SEQ.fetch_add(1, Ordering::Relaxed); - let path = - std::env::temp_dir().join(format!("curate-etl-it-bars-1m-{tag}-{pid}-{seq}")); - let _ = fs::remove_dir_all(&path); - fs::create_dir_all(&path).expect("create integration test temp dir"); - Self { path } - } - - fn path(&self) -> &Path { - &self.path - } -} - -impl Drop for TempDir { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.path); - } -} - -fn run_bin(args: &[&str]) -> Output { - Command::new(env!("CARGO_BIN_EXE_curate-etl")) - .args(args) - .output() - .expect("spawn curate-etl binary") -} - -fn day(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).expect("valid date") -} - -fn et_ts_sec(y: i32, m: u32, d: u32, hour: u8, minute: u8) -> i64 { - let micros = et_to_utc_micros(day(y, m, d), hour, minute, 0).expect("valid ET timestamp"); - assert_eq!(micros % 1_000_000, 0); - micros / 1_000_000 -} - -fn make_intraday_doc( - code: &str, - timestamp_sec: i64, - open: f64, - high: f64, - low: f64, - close: f64, - volume: f64, -) -> RawDocumentBuf { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), code); - doc.append(cstr!("timestamp"), timestamp_sec); - doc.append(cstr!("open"), open); - doc.append(cstr!("high"), high); - doc.append(cstr!("low"), low); - doc.append(cstr!("close"), close); - doc.append(cstr!("volume"), volume); - doc -} - -fn make_split_doc( - qm_search_code: &str, - ex_date: &str, - for_factor: f64, - to_factor: f64, -) -> RawDocumentBuf { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), qm_search_code); - doc.append(cstr!("date"), ex_date); - doc.append(cstr!("forfactor"), for_factor); - doc.append(cstr!("tofactor"), to_factor); - doc.append(cstr!("splitratio"), for_factor / to_factor); - doc -} - -fn concat_docs(docs: &[RawDocumentBuf]) -> Vec { - let mut out = Vec::new(); - for doc in docs { - out.extend_from_slice(doc.as_bytes()); - } - out -} - -fn read_dir_files(dir: &Path) -> BTreeMap> { - let mut out = BTreeMap::new(); - for entry in fs::read_dir(dir).expect("read output dir") { - let entry = entry.expect("dir entry"); - let name = entry - .file_name() - .into_string() - .expect("UTF-8 file name in output dir"); - let bytes = fs::read(entry.path()).expect("read output file"); - out.insert(name, bytes); - } - out -} - -fn strip_timing_line(report: &str) -> Vec<&str> { - report - .lines() - .filter(|line| !line.trim_start().starts_with("timing:")) - .collect() -} - -#[test] -fn curate_bars_1m_binary_matches_direct_runner_bytes_and_report() { - let tmp = TempDir::new("parity"); - - // Pin NVDA 10:1 forward split (2024-06-10) and NEXM 1:20 reverse split (2025-06-20) - // fixtures in the style of src/run_curate_bars_1m_tests.rs. - let intraday_path = tmp.path().join("eodIntraday1M.bson"); - let intraday_bytes = concat_docs(&[ - // NVDA pre-split (2024-06-07): 10:1 split un-adjusts prices x10 and volume /10. - make_intraday_doc( - "NVDA.US", - et_ts_sec(2024, 6, 7, 15, 59), - 120.50, - 121.00, - 120.40, - 120.888, - 412_390.0, - ), - // NVDA ex-date (2024-06-10): already post-split (factor = 1.0). - make_intraday_doc( - "NVDA.US", - et_ts_sec(2024, 6, 10, 15, 59), - 121.50, - 122.00, - 121.20, - 121.79, - 350_000.0, - ), - // NEXM pre-split (2025-06-18): 1:20 reverse split un-adjusts prices x0.05 and volume x20. - make_intraday_doc( - "NEXM.V", - et_ts_sec(2025, 6, 18, 15, 59), - 24.20, - 24.40, - 24.10, - 24.29, - 5_000.0, - ), - // NEXM ex-date (2025-06-20): already post-split (factor = 1.0). - make_intraday_doc( - "NEXM.V", - et_ts_sec(2025, 6, 20, 15, 59), - 24.10, - 24.35, - 24.00, - 24.28, - 12_500.0, - ), - ]); - fs::write(&intraday_path, &intraday_bytes).expect("write intraday bson"); - - let splits_path = tmp.path().join("qmSplits.bson"); - let splits_bytes = concat_docs(&[ - make_split_doc("NVDA", "2024-06-10", 1.0, 10.0), - make_split_doc("NEXM:CA", "2025-06-20", 20.0, 1.0), - ]); - fs::write(&splits_path, &splits_bytes).expect("write splits bson"); - - let mapping_path = tmp.path().join("provider_mapping.tsv"); - fs::write( - &mapping_path, - "eod\tNVDA.US\t2000-01-01\t\t1001\n\ - qm\tNVDA\t2000-01-01\t\t1001\n\ - eod\tNEXM.V\t2000-01-01\t\t2002\n\ - qm\tNEXM:CA\t2000-01-01\t\t2002\n", - ) - .expect("write provider_mapping.tsv"); - - let known_at_micros: i64 = 1_750_000_000_000_000; - let shard_count: usize = 2; - - let bin_out = tmp.path().join("out-bin"); - let direct_out = tmp.path().join("out-direct"); - - let output = run_bin(&[ - "curate-bars-1m", - "--eod-intraday", - intraday_path.to_str().unwrap(), - "--qm-splits", - splits_path.to_str().unwrap(), - "--provider-mapping", - mapping_path.to_str().unwrap(), - "--out", - bin_out.to_str().unwrap(), - "--shards", - "2", - "--known-at-micros", - "1750000000000000", - ]); - - let stdout = String::from_utf8_lossy(&output.stdout); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!( - output.status.success(), - "expected exit 0, got {:?}; stderr:\n{stderr}\nstdout:\n{stdout}", - output.status.code() - ); - assert!( - stderr.is_empty(), - "expected empty stderr on success, got:\n{stderr}" - ); - - let direct_args = CurateBars1mArgs { - intraday_path, - splits_path, - provider_mapping_path: mapping_path, - out_dir: direct_out.clone(), - mapping_source: DEFAULT_BARS_1M_MAPPING_SOURCE.to_string(), - shard_count, - known_at_micros, - stream_options: BsonStreamOptions::default(), - ilp_options: IlpWriterOptions::default(), - }; - let direct_report = run_curate_bars_1m(&direct_args).expect("direct run_curate_bars_1m"); - assert_eq!( - direct_report.rows_written, 4, - "expected 4 emitted bars_1m rows" - ); - - let direct_formatted = format_curate_bars_1m_report(&direct_report); - assert_eq!( - strip_timing_line(&stdout), - strip_timing_line(&direct_formatted), - "binary stdout report should match direct runner report excluding timing line" - ); - assert!( - stdout - .lines() - .any(|line| line.trim_start().starts_with("timing: elapsed_secs=")), - "expected timing line in stdout:\n{stdout}" - ); - - let bin_files = read_dir_files(&bin_out); - let direct_files = read_dir_files(&direct_out); - - let expected_names: Vec = vec![ - "bars_1m.shard-00.ilp".to_string(), - "bars_1m.shard-01.ilp".to_string(), - ]; - assert_eq!( - bin_files.keys().cloned().collect::>(), - expected_names, - "unexpected files in binary output dir" - ); - assert_eq!( - bin_files, direct_files, - "binary shard files must be byte-identical to direct runner output" - ); - assert!( - bin_files.values().map(Vec::len).sum::() > 0, - "expected non-empty ILP output across shards" - ); -} - -#[test] -fn curate_bars_1m_binary_missing_input_exits_nonzero_and_leaves_out_clean() { - let tmp = TempDir::new("missing-input"); - - let missing_intraday = tmp.path().join("does-not-exist.bson"); - let splits_path = tmp.path().join("qmSplits.bson"); - fs::write(&splits_path, concat_docs(&[])).expect("write empty splits bson"); - - let mapping_path = tmp.path().join("provider_mapping.tsv"); - fs::write(&mapping_path, "eod\tNVDA.US\t2000-01-01\t\t1001\n") - .expect("write provider_mapping.tsv"); - - let out_dir = tmp.path().join("out-empty"); - fs::create_dir_all(&out_dir).expect("create empty out dir"); - - let output = run_bin(&[ - "curate-bars-1m", - "--eod-intraday", - missing_intraday.to_str().unwrap(), - "--qm-splits", - splits_path.to_str().unwrap(), - "--provider-mapping", - mapping_path.to_str().unwrap(), - "--out", - out_dir.to_str().unwrap(), - "--shards", - "2", - "--known-at-micros", - "1750000000000000", - ]); - - let stdout = String::from_utf8_lossy(&output.stdout); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!( - !output.status.success(), - "expected non-zero exit when intraday file is missing" - ); - assert!( - stdout.is_empty(), - "expected no success report on stdout, got:\n{stdout}" - ); - assert!( - stderr.contains("error:") && stderr.contains("failed to open eod-intraday"), - "expected input-open error on stderr, got:\n{stderr}" - ); - - let remaining = read_dir_files(&out_dir); - assert!( - remaining.is_empty(), - "expected no shard or staging files in output dir, found: {:?}", - remaining.keys().collect::>() - ); -} - -// --------------------------------------------------------------------------- -// QA edge cases (T-186): binary-level behaviour not covered by the parity tests. -// --------------------------------------------------------------------------- - -struct Fixture { - intraday: PathBuf, - splits: PathBuf, - mapping: PathBuf, -} - -/// NVDA 10:1 split fixture: one pre-split bar (2024-06-07) and one ex-date bar (2024-06-10). -fn write_nvda_fixture(dir: &Path) -> Fixture { - let intraday = dir.join("eodIntraday1M.bson"); - fs::write( - &intraday, - concat_docs(&[ - make_intraday_doc( - "NVDA.US", - et_ts_sec(2024, 6, 7, 15, 59), - 120.50, - 121.00, - 120.40, - 120.75, - 412_390.0, - ), - make_intraday_doc( - "NVDA.US", - et_ts_sec(2024, 6, 10, 15, 59), - 121.50, - 122.00, - 121.20, - 121.75, - 350_000.0, - ), - ]), - ) - .expect("write intraday bson"); - let splits = dir.join("qmSplits.bson"); - fs::write(&splits, concat_docs(&[make_split_doc("NVDA", "2024-06-10", 1.0, 10.0)])) - .expect("write splits bson"); - let mapping = dir.join("provider_mapping.tsv"); - fs::write( - &mapping, - "eod\tNVDA.US\t2000-01-01\t\t1001\nqm\tNVDA\t2000-01-01\t\t1001\n", - ) - .expect("write provider_mapping.tsv"); - Fixture { - intraday, - splits, - mapping, - } -} - -fn bin_args<'a>( - fx: &'a Fixture, - out: &'a Path, - known_at: &'a str, - extra: &[&'a str], -) -> Vec<&'a str> { - let mut argv = vec![ - "curate-bars-1m", - "--eod-intraday", - fx.intraday.to_str().unwrap(), - "--qm-splits", - fx.splits.to_str().unwrap(), - "--provider-mapping", - fx.mapping.to_str().unwrap(), - "--out", - out.to_str().unwrap(), - "--shards", - "2", - "--known-at-micros", - known_at, - ]; - argv.extend_from_slice(extra); - argv -} - -#[derive(Debug)] -struct IlpRow { - listing_id: i32, - open: f64, - high: f64, - low: f64, - close: f64, - volume: f64, - known_at: i64, - ts: i64, -} - -/// Minimal ILP v2 `bars_1m` decoder (binary DOUBLE fields, `known_at=t`, `t\n`). -fn decode_rows(data: &[u8]) -> Vec { - let mut rows = Vec::new(); - let mut i = 0usize; - while i < data.len() { - let tag_start = i; - while data[i] != b' ' { - i += 1; - } - let tags = std::str::from_utf8(&data[tag_start..i]).unwrap(); - i += 1; - let listing_id: i32 = tags - .split(',') - .find_map(|t| t.strip_prefix("listing_id=")) - .expect("listing_id tag") - .parse() - .unwrap(); - let mut read_f64 = |name: &str| -> f64 { - let prefix = format!("{name}=="); - assert!(data[i..].starts_with(prefix.as_bytes()), "expected {prefix}"); - i += prefix.len() + 1; // skip binary DOUBLE type tag - let v = f64::from_le_bytes(data[i..i + 8].try_into().unwrap()); - i += 8; - if data[i] == b',' { - i += 1; - } - v - }; - let open = read_f64("open"); - let high = read_f64("high"); - let low = read_f64("low"); - let close = read_f64("close"); - let volume = read_f64("volume"); - assert!(data[i..].starts_with(b"known_at="), "expected known_at="); - i += b"known_at=".len(); - let ks = i; - while data[i] != b' ' { - i += 1; - } - let known_at: i64 = std::str::from_utf8(&data[ks..i]) - .unwrap() - .strip_suffix('t') - .unwrap() - .parse() - .unwrap(); - i += 1; - let ts_start = i; - while data[i] != b'\n' { - i += 1; - } - let ts: i64 = std::str::from_utf8(&data[ts_start..i]) - .unwrap() - .strip_suffix('t') - .unwrap() - .parse() - .unwrap(); - i += 1; - rows.push(IlpRow { - listing_id, - open, - high, - low, - close, - volume, - known_at, - ts, - }); - } - rows -} - -fn assert_close(actual: f64, expected: f64, what: &str) { - assert!( - (actual - expected).abs() <= 1e-9 * expected.abs().max(1.0), - "{what}: expected {expected}, got {actual}" - ); -} - -fn shard_and_staging_files(dir: &Path) -> Vec { - if !dir.exists() { - return Vec::new(); - } - read_dir_files(dir).into_keys().collect() -} - -#[test] -fn curate_bars_1m_binary_writes_known_at_verbatim_and_unadjusts_nvda_split() { - let tmp = TempDir::new("values"); - let fx = write_nvda_fixture(tmp.path()); - let out = tmp.path().join("out"); - - let output = run_bin(&bin_args(&fx, &out, "1700000000123456", &[])); - assert!( - output.status.success(), - "stderr: {}", - String::from_utf8_lossy(&output.stderr) - ); - - let mut rows: Vec = read_dir_files(&out) - .values() - .flat_map(|bytes| decode_rows(bytes)) - .collect(); - rows.sort_by_key(|r| r.ts); - assert_eq!(rows.len(), 2, "rows: {rows:?}"); - - for row in &rows { - assert_eq!(row.listing_id, 1001); - assert_eq!(row.known_at, 1_700_000_000_123_456, "known_at must be verbatim"); - } - - let pre = &rows[0]; - assert_eq!(pre.ts, et_ts_sec(2024, 6, 7, 15, 59) * 1_000_000); - assert_close(pre.open, 1205.0, "pre-split open x10"); - assert_close(pre.high, 1210.0, "pre-split high x10"); - assert_close(pre.low, 1204.0, "pre-split low x10"); - assert_close(pre.close, 1207.5, "pre-split close x10"); - assert_close(pre.volume, 41_239.0, "pre-split volume /10"); - - let ex = &rows[1]; - assert_eq!(ex.ts, et_ts_sec(2024, 6, 10, 15, 59) * 1_000_000); - assert_close(ex.close, 121.75, "ex-date close unchanged"); - assert_close(ex.volume, 350_000.0, "ex-date volume unchanged"); -} - -#[test] -fn curate_bars_1m_binary_is_deterministic_across_runs() { - let tmp = TempDir::new("determinism"); - let fx = write_nvda_fixture(tmp.path()); - let out_a = tmp.path().join("out-a"); - let out_b = tmp.path().join("out-b"); - - let a = run_bin(&bin_args(&fx, &out_a, "1750000000000000", &[])); - let b = run_bin(&bin_args(&fx, &out_b, "1750000000000000", &[])); - assert!(a.status.success() && b.status.success()); - - let files_a = read_dir_files(&out_a); - assert!(!files_a.is_empty()); - assert_eq!(files_a, read_dir_files(&out_b), "repeat runs must be byte-identical"); - assert_eq!( - strip_timing_line(&String::from_utf8_lossy(&a.stdout)), - strip_timing_line(&String::from_utf8_lossy(&b.stdout)), - ); -} - -#[test] -fn curate_bars_1m_binary_refuses_to_overwrite_existing_shards() { - let tmp = TempDir::new("overwrite"); - let fx = write_nvda_fixture(tmp.path()); - let out = tmp.path().join("out"); - - let first = run_bin(&bin_args(&fx, &out, "1750000000000000", &[])); - assert!(first.status.success()); - let before = read_dir_files(&out); - - // Different known_at so any overwrite would change bytes. - let second = run_bin(&bin_args(&fx, &out, "1760000000000000", &[])); - assert!(!second.status.success(), "second run into populated --out must fail"); - assert!(second.stdout.is_empty(), "no success report expected"); - assert!(String::from_utf8_lossy(&second.stderr).starts_with("error:")); - assert_eq!( - read_dir_files(&out), - before, - "existing shards must be untouched and no staging files left" - ); -} - -#[test] -fn curate_bars_1m_binary_rejects_non_eod_mapping_source_without_output() { - let tmp = TempDir::new("mapping-source"); - let fx = write_nvda_fixture(tmp.path()); - let out = tmp.path().join("out"); - - let output = run_bin(&bin_args( - &fx, - &out, - "1750000000000000", - &["--mapping-source", "qm"], - )); - assert!(!output.status.success()); - assert!(output.stdout.is_empty()); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!(stderr.contains("error:") && stderr.contains("qm"), "stderr: {stderr}"); - assert!( - shard_and_staging_files(&out).is_empty(), - "no files expected in --out: {:?}", - shard_and_staging_files(&out) - ); -} - -#[test] -fn curate_bars_1m_binary_parse_error_prints_usage_hides_secret_and_writes_nothing() { - let tmp = TempDir::new("parse-error"); - let fx = write_nvda_fixture(tmp.path()); - let out = tmp.path().join("out"); - - let secret = "--mongo-uri=mongodb://user:s3cr3t_pw@localhost:27017/stock"; - let output = run_bin(&bin_args(&fx, &out, "1750000000000000", &[secret])); - assert!(!output.status.success()); - assert!(output.stdout.is_empty()); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!(stderr.contains("file mode only"), "stderr: {stderr}"); - assert!(stderr.contains("curate-bars-1m --eod-intraday"), "usage expected: {stderr}"); - assert!(!stderr.contains("s3cr3t_pw"), "secret leaked: {stderr}"); - assert!(!out.exists(), "parse failure must not create --out"); - - // Missing --known-at-micros: no clock fallback, nothing written. - let mut argv = bin_args(&fx, &out, "1", &[]); - argv.truncate(argv.len() - 2); - let output = run_bin(&argv); - assert!(!output.status.success()); - assert!(String::from_utf8_lossy(&output.stderr) - .contains("missing required flag '--known-at-micros'")); - assert!(!out.exists()); -} diff --git a/tools/curate-etl/tests/curate_fundamentals.rs b/tools/curate-etl/tests/curate_fundamentals.rs deleted file mode 100644 index b5fef7b5..00000000 --- a/tools/curate-etl/tests/curate_fundamentals.rs +++ /dev/null @@ -1,718 +0,0 @@ -//! End-to-end tests for the file-mode `curate-fundamentals` CLI. - -use std::collections::BTreeMap; -use std::fs::{self, File}; -use std::path::{Path, PathBuf}; -use std::process::Command; -use std::sync::atomic::{AtomicU64, Ordering}; - -use bson::raw::{cstr, RawDocumentBuf}; -use curate_etl::fundamentals::FundamentalsFields; -use curate_etl::run_curate_fundamentals::{ - format_curate_fundamentals_report, run_curate_fundamentals, CurateFundamentalsArgs, - CurateFundamentalsFiscalPeriod, -}; -use curate_etl::shorts::et_to_utc_micros; -use curate_etl::split::ymd_to_epoch_days; -use parquet::file::reader::{FileReader, SerializedFileReader}; -use parquet::record::{Field, Row}; - -static TEMP_SEQ: AtomicU64 = AtomicU64::new(0); - -struct TempDir(PathBuf); - -impl TempDir { - fn new(label: &str) -> Self { - let seq = TEMP_SEQ.fetch_add(1, Ordering::Relaxed); - let path = std::env::temp_dir().join(format!( - "curate-fundamentals-cli-{label}-{}-{seq}", - std::process::id() - )); - let _ = fs::remove_dir_all(&path); - fs::create_dir_all(&path).expect("create isolated test directory"); - Self(path) - } -} - -impl Drop for TempDir { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.0); - } -} - -fn cli() -> Command { - let mut command = Command::new(env!("CARGO_BIN_EXE_curate-etl")); - command.arg("curate-fundamentals"); - command -} - -fn make_financials_doc( - key: &str, - period_end: &str, - report_date: &str, - report_period: &str, - currency: &str, - fields: FundamentalsFields, -) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), key); - doc.append(cstr!("periodEndDate"), period_end); - doc.append(cstr!("reportDate"), report_date); - doc.append(cstr!("reportPeriod"), report_period); - doc.append(cstr!("currency"), currency); - - let mut income = RawDocumentBuf::new(); - if let Some(v) = fields.revenue { - income.append(cstr!("revenue"), v); - } - if let Some(v) = fields.net_income { - income.append(cstr!("netIncome"), v); - } - doc.append(cstr!("IncomeStatement"), income); - - let mut cashflow = RawDocumentBuf::new(); - if let Some(v) = fields.operating_cash_flow { - cashflow.append(cstr!("operatingCashFlow"), v); - } - doc.append(cstr!("CashFlow"), cashflow); - - let mut balance = RawDocumentBuf::new(); - if let Some(v) = fields.total_assets { - balance.append(cstr!("totalAssets"), v); - } - if let Some(v) = fields.total_equity { - balance.append(cstr!("totalEquity"), v); - } - if let Some(v) = fields.shares_outstanding { - balance.append(cstr!("sharesOutstanding"), v); - } - doc.append(cstr!("BalanceSheet"), balance); - - doc.into_bytes() -} - -fn make_filing_doc(key: &str, timefiled: &str, form_type: &str, filing_id: &str) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("symbol"), key); - doc.append(cstr!("timefiled"), timefiled); - doc.append(cstr!("formType"), form_type); - doc.append(cstr!("filingId"), filing_id); - doc.into_bytes() -} - -fn read_parquet_partitions(out_dir: &Path) -> BTreeMap> { - let dataset_root = out_dir.join("fundamentals_pit"); - let mut files = BTreeMap::new(); - for entry in fs::read_dir(&dataset_root).expect("read fundamentals_pit dir") { - let entry = entry.expect("dir entry"); - let name = entry.file_name(); - let part_path = entry.path().join("part.parquet"); - assert!( - part_path.is_file(), - "expected part.parquet in {}", - entry.path().display() - ); - let rel = PathBuf::from(&name).join("part.parquet"); - files.insert(rel, fs::read(&part_path).expect("read parquet bytes")); - } - files -} - -fn write_restatement_fixture(dir: &Path) -> (PathBuf, PathBuf, PathBuf, PathBuf) { - let fin_path = dir.join("qmFinancials.bson"); - let fil_path = dir.join("qmFilings.bson"); - let map_path = dir.join("provider_mapping.tsv"); - let venues_path = dir.join("listing_venues.tsv"); - - fs::write(&map_path, "qm\tACME\t2020-01-01\t\t301\n").unwrap(); - fs::write(&venues_path, "301\tus_tsx\n").unwrap(); - - // Specimen dates and field shapes from `run_curate_fundamentals_tests`: - // four contiguous quarters (Q3 2023 .. Q2 2024) plus a late Q1 2024 restatement (10-Q/A on - // 2024-09-15) and an unmapped observation. - let mut fin_bytes = Vec::new(); - for (key, pe, rd, rp, rev, ni, ocf, ta, te, sh) in [ - ( - "ACME", - "2023-09-30", - "2023-11-05", - "Q3", - 90.0, - 8.0, - 10.0, - 460.0, - 275.0, - 20.0, - ), - ( - "ACME", - "2023-12-31", - "2024-02-20", - "Q4", - 110.0, - 11.0, - 14.0, - 480.0, - 288.0, - 20.0, - ), - ( - "ACME", - "2024-03-31", - "2024-05-05", - "Q1", - 100.0, - 10.0, - 12.0, - 500.0, - 300.0, - 20.0, - ), - ( - "ACME", - "2024-06-30", - "2024-08-05", - "Q2", - 250.0, - 30.0, - 35.0, - 550.0, - 330.0, - 20.0, - ), - ( - "ACME", - "2024-03-31", - "2024-09-15", - "Q1", - 88.0, - 4.0, - 9.0, - 490.0, - 294.0, - 20.0, - ), - ( - "UNMAPPED", - "2024-06-30", - "2024-08-05", - "Q2", - 50.0, - 5.0, - 6.0, - 100.0, - 60.0, - 10.0, - ), - ] { - fin_bytes.extend_from_slice(&make_financials_doc( - key, - pe, - rd, - rp, - "USD", - FundamentalsFields { - revenue: Some(rev), - net_income: Some(ni), - operating_cash_flow: Some(ocf), - total_assets: Some(ta), - total_equity: Some(te), - shares_outstanding: Some(sh), - }, - )); - } - fs::write(&fin_path, fin_bytes).unwrap(); - - let mut fil_bytes = Vec::new(); - for (key, ts, form, id) in [ - ("ACME", "2023-11-05T16:10:00 EST", "10-Q", "q3-2023-1"), - ("ACME", "2024-02-20T16:10:00 EST", "10-Q", "q4-2023-1"), - ("ACME", "2024-05-05T16:10:00 EDT", "10-Q", "q1-2024-1"), - ("ACME", "2024-08-05T16:15:00 EDT", "10-Q", "q2-2024-1"), - ("ACME", "2024-09-15T16:20:00 EDT", "10-Q/A", "q1-2024-a"), - ] { - fil_bytes.extend_from_slice(&make_filing_doc(key, ts, form, id)); - } - fs::write(&fil_path, fil_bytes).unwrap(); - - (fin_path, fil_path, map_path, venues_path) -} - -#[test] -fn cli_publishes_runner_equivalent_fundamentals_and_preserves_pit_restatement() { - let dir = TempDir::new("e2e"); - let (fin_path, fil_path, map_path, venues_path) = write_restatement_fixture(&dir.0); - - let baseline_dir = dir.0.join("baseline"); - let mut baseline_args = CurateFundamentalsArgs::with_verified_defaults( - fin_path.clone(), - fil_path.clone(), - map_path.clone(), - venues_path.clone(), - baseline_dir.clone(), - "currency", - Some("IncomeStatement.revenue".to_string()), - Some("IncomeStatement.netIncome".to_string()), - Some("CashFlow.operatingCashFlow".to_string()), - Some("BalanceSheet.totalAssets".to_string()), - Some("BalanceSheet.totalEquity".to_string()), - Some("BalanceSheet.sharesOutstanding".to_string()), - CurateFundamentalsFiscalPeriod::ByTokens { - quarterly: vec![ - "Q1".to_string(), - "Q2".to_string(), - "Q3".to_string(), - "Q4".to_string(), - ], - annual: vec!["FY".to_string()], - }, - "formType", - 4, - ); - baseline_args.filings_filing_id_field = Some("filingId".to_string()); - - let baseline_report = run_curate_fundamentals(&baseline_args).expect("run library baseline"); - let expected_report = format_curate_fundamentals_report(&baseline_report); - let baseline_partitions = read_parquet_partitions(&baseline_dir); - assert!( - baseline_partitions.contains_key(Path::new("year=2024/part.parquet")), - "expected nonempty 2024 partition" - ); - - let cli_out = dir.0.join("cli_out"); - let result = cli() - .current_dir(&dir.0) - .args([ - "--qm-financials", - "qmFinancials.bson", - "--qm-filings=qmFilings.bson", - "--provider-mapping", - "provider_mapping.tsv", - "--listing-venues=listing_venues.tsv", - "--out", - "cli_out", - "--currency-field=currency", - "--filings-form-type-field", - "formType", - "--filings-filing-id-field=filingId", - "--k", - "4", - "--quarterly-tokens=Q1,Q2,Q3,Q4", - "--annual-tokens", - "FY", - "--revenue-field", - "IncomeStatement.revenue", - "--net-income-field=IncomeStatement.netIncome", - "--operating-cash-flow-field", - "CashFlow.operatingCashFlow", - "--total-assets-field=BalanceSheet.totalAssets", - "--total-equity-field", - "BalanceSheet.totalEquity", - "--shares-outstanding-field=BalanceSheet.sharesOutstanding", - ]) - .output() - .expect("run curate-fundamentals"); - - assert!(result.status.success(), "{result:?}"); - assert!( - result.stderr.is_empty(), - "unexpected stderr: {}", - String::from_utf8_lossy(&result.stderr) - ); - - let stdout = String::from_utf8(result.stdout).expect("utf-8 stdout"); - let actual_lines: Vec<&str> = stdout.lines().collect(); - let expected_lines: Vec<&str> = expected_report.lines().collect(); - assert_eq!(actual_lines.len(), expected_lines.len(), "{stdout}"); - assert_eq!( - &actual_lines[..actual_lines.len() - 1], - &expected_lines[..expected_lines.len() - 1], - "deterministic report lines must match library baseline" - ); - let timing_line = *actual_lines.last().unwrap(); - let elapsed_str = timing_line - .strip_prefix(" timing: elapsed_secs=") - .unwrap_or_else(|| panic!("unexpected timing line: {timing_line:?}")); - let elapsed: f64 = elapsed_str.parse().expect("valid elapsed_secs float"); - assert!(elapsed.is_finite() && elapsed >= 0.0, "{timing_line}"); - - let cli_partitions = read_parquet_partitions(&cli_out); - assert_eq!( - cli_partitions.keys().collect::>(), - baseline_partitions.keys().collect::>(), - "partition paths must match baseline" - ); - for (rel, expected_bytes) in &baseline_partitions { - assert_eq!( - cli_partitions.get(rel).unwrap(), - expected_bytes, - "Parquet bytes differ for {}", - rel.display() - ); - } - - // Read the 2024 partition and verify listing, currency, metric value, filing-derived known_at, - // and PIT restatement isolation (Q1 restatement only visible at 2024-09-15). - let part_2024 = cli_out.join("fundamentals_pit/year=2024/part.parquet"); - let reader = SerializedFileReader::new(File::open(&part_2024).unwrap()).unwrap(); - let rows: Vec<_> = reader - .get_row_iter(None) - .unwrap() - .map(Result::unwrap) - .collect(); - assert_eq!( - rows.len(), - 4, - "expected Q4-23, Q1-24, Q2-24, and Q1-24/A snapshots in 2024" - ); - - let q2_filed_micros = - et_to_utc_micros(ymd_to_epoch_days(2024, 8, 5).unwrap(), 16, 15, 0).unwrap(); - let restate_filed_micros = - et_to_utc_micros(ymd_to_epoch_days(2024, 9, 15).unwrap(), 16, 20, 0).unwrap(); - - fn col<'a>(row: &'a Row, name: &str) -> &'a Field { - row.get_column_iter() - .find(|(col_name, _)| col_name.as_str() == name) - .unwrap_or_else(|| panic!("missing Parquet column '{name}'")) - .1 - } - - let q2_row = &rows[2]; - assert_eq!(col(q2_row, "listing_id"), &Field::Int(301)); - assert_eq!( - col(q2_row, "effective_known_at"), - &Field::TimestampMicros(q2_filed_micros) - ); - assert_eq!( - col(q2_row, "known_at_source"), - &Field::Str("filing_timestamp".to_string()) - ); - assert_eq!( - col(q2_row, "period_end"), - &Field::Date(ymd_to_epoch_days(2024, 6, 30).unwrap()) - ); - assert_eq!(col(q2_row, "currency"), &Field::Str("USD".to_string())); - assert_eq!(col(q2_row, "revenue"), &Field::Double(250.0)); - assert_eq!(col(q2_row, "ttm_revenue"), &Field::Double(550.0)); - - let restated_row = &rows[3]; - assert_eq!(col(restated_row, "listing_id"), &Field::Int(301)); - assert_eq!( - col(restated_row, "effective_known_at"), - &Field::TimestampMicros(restate_filed_micros) - ); - assert_eq!( - col(restated_row, "known_at_source"), - &Field::Str("filing_timestamp".to_string()) - ); - // Latest period remains Q2 2024 (250.0 revenue) while TTM revenue reflects the -12.0 Q1 restatement. - assert_eq!( - col(restated_row, "period_end"), - &Field::Date(ymd_to_epoch_days(2024, 6, 30).unwrap()) - ); - assert_eq!( - col(restated_row, "currency"), - &Field::Str("USD".to_string()) - ); - assert_eq!(col(restated_row, "revenue"), &Field::Double(250.0)); - assert_eq!(col(restated_row, "ttm_revenue"), &Field::Double(538.0)); -} - -#[test] -fn cli_fails_closed_without_creating_out_dir_on_invalid_flags() { - let dir = TempDir::new("fail-closed"); - let (_fin_path, _fil_path, _map_path, _venues_path) = write_restatement_fixture(&dir.0); - - let out_missing_k = dir.0.join("out_missing_k"); - let res_missing_k = cli() - .current_dir(&dir.0) - .args([ - "--qm-financials", - "qmFinancials.bson", - "--qm-filings", - "qmFilings.bson", - "--provider-mapping", - "provider_mapping.tsv", - "--listing-venues", - "listing_venues.tsv", - "--out", - "out_missing_k", - "--currency-field", - "currency", - "--filings-form-type-field", - "formType", - "--fiscal-period", - "quarterly", - ]) - .output() - .expect("run curate-fundamentals missing --k"); - - assert_eq!(res_missing_k.status.code(), Some(1)); - assert!(res_missing_k.stdout.is_empty()); - let stderr_k = String::from_utf8(res_missing_k.stderr).unwrap(); - let mut lines_k = stderr_k.lines(); - assert_eq!(lines_k.next(), Some("error: missing required flag '--k'")); - assert_eq!(lines_k.next(), Some("Usage:")); - assert!( - stderr_k.contains("curate-fundamentals --qm-financials"), - "{stderr_k}" - ); - assert!(!out_missing_k.exists(), "out_missing_k must not be created"); - - let out_from_mongo = dir.0.join("out_from_mongo"); - let res_mongo = cli() - .current_dir(&dir.0) - .args([ - "--from-mongo", - "--qm-financials", - "qmFinancials.bson", - "--qm-filings", - "qmFilings.bson", - "--provider-mapping", - "provider_mapping.tsv", - "--listing-venues", - "listing_venues.tsv", - "--out", - "out_from_mongo", - "--currency-field", - "currency", - "--filings-form-type-field", - "formType", - "--k", - "4", - "--fiscal-period", - "quarterly", - ]) - .output() - .expect("run curate-fundamentals with --from-mongo"); - - assert_eq!(res_mongo.status.code(), Some(1)); - assert!(res_mongo.stdout.is_empty()); - let stderr_mongo = String::from_utf8(res_mongo.stderr).unwrap(); - let mut lines_mongo = stderr_mongo.lines(); - assert_eq!( - lines_mongo.next(), - Some("error: unknown flag '--from-mongo' for curate-fundamentals") - ); - assert_eq!(lines_mongo.next(), Some("Usage:")); - assert!( - stderr_mongo.contains("curate-fundamentals --qm-financials"), - "{stderr_mongo}" - ); - assert!( - !out_from_mongo.exists(), - "out_from_mongo must not be created" - ); -} - -const FIXTURE_REQUIRED_ARGS: [&str; 14] = [ - "--qm-financials", - "qmFinancials.bson", - "--qm-filings", - "qmFilings.bson", - "--provider-mapping", - "provider_mapping.tsv", - "--listing-venues", - "listing_venues.tsv", - "--currency-field", - "currency", - "--filings-form-type-field", - "formType", - "--k", - "4", -]; - -fn assert_single_line_error_then_usage(stderr: &[u8], expected_error: &str) { - let text = String::from_utf8(stderr.to_vec()).expect("utf-8 stderr"); - let mut lines = text.lines(); - assert_eq!(lines.next(), Some(expected_error), "{text}"); - assert_eq!(lines.next(), Some("Usage:"), "{text}"); - assert!( - text.contains("curate-fundamentals --qm-financials"), - "{text}" - ); -} - -#[test] -fn cli_fixed_fiscal_period_without_metric_fields_matches_runner_and_writes_null_metrics() { - let dir = TempDir::new("fixed-null-metrics"); - let (fin_path, fil_path, map_path, venues_path) = write_restatement_fixture(&dir.0); - - let baseline_dir = dir.0.join("baseline"); - let baseline_args = CurateFundamentalsArgs::with_verified_defaults( - fin_path, - fil_path, - map_path, - venues_path, - baseline_dir.clone(), - "currency", - None, - None, - None, - None, - None, - None, - CurateFundamentalsFiscalPeriod::Fixed(curate_etl::fundamentals::FiscalPeriod::Quarterly), - "formType", - 4, - ); - let baseline_report = run_curate_fundamentals(&baseline_args).expect("run library baseline"); - let expected_report = format_curate_fundamentals_report(&baseline_report); - let baseline_partitions = read_parquet_partitions(&baseline_dir); - - let result = cli() - .current_dir(&dir.0) - .args(FIXTURE_REQUIRED_ARGS) - .args(["--out=cli_out", "--fiscal-period=quarterly"]) - .output() - .expect("run curate-fundamentals"); - assert!(result.status.success(), "{result:?}"); - assert!(result.stderr.is_empty(), "{result:?}"); - - let stdout = String::from_utf8(result.stdout).expect("utf-8 stdout"); - let actual: Vec<&str> = stdout.lines().collect(); - let expected: Vec<&str> = expected_report.lines().collect(); - assert_eq!(actual.len(), expected.len(), "{stdout}"); - assert_eq!(actual[..actual.len() - 1], expected[..expected.len() - 1]); - - let cli_partitions = read_parquet_partitions(&dir.0.join("cli_out")); - assert_eq!(cli_partitions, baseline_partitions); - - let part_2024 = dir - .0 - .join("cli_out/fundamentals_pit/year=2024/part.parquet"); - let reader = SerializedFileReader::new(File::open(&part_2024).unwrap()).unwrap(); - let rows: Vec = reader - .get_row_iter(None) - .unwrap() - .map(Result::unwrap) - .collect(); - assert!(!rows.is_empty(), "expected nonempty 2024 partition"); - for row in &rows { - let revenue = row - .get_column_iter() - .find(|(name, _)| name.as_str() == "revenue") - .expect("revenue column") - .1; - assert_eq!(revenue, &Field::Null, "unconfigured metric must be NULL"); - let currency = row - .get_column_iter() - .find(|(name, _)| name.as_str() == "currency") - .expect("currency column") - .1; - assert_eq!(currency, &Field::Str("USD".to_string())); - } -} - -#[test] -fn cli_rerun_into_fresh_out_dir_is_byte_deterministic() { - let dir = TempDir::new("rerun"); - write_restatement_fixture(&dir.0); - - for out in ["run_a", "run_b"] { - let result = cli() - .current_dir(&dir.0) - .args(FIXTURE_REQUIRED_ARGS) - .args(["--out", out, "--quarterly-tokens", "Q1,Q2,Q3,Q4"]) - .args(["--revenue-field", "IncomeStatement.revenue"]) - .output() - .expect("run curate-fundamentals"); - assert!(result.status.success(), "{result:?}"); - } - - let a = read_parquet_partitions(&dir.0.join("run_a")); - let b = read_parquet_partitions(&dir.0.join("run_b")); - assert!(!a.is_empty()); - assert_eq!( - a, b, - "identical inputs must publish identical Parquet bytes" - ); -} - -#[test] -fn cli_runner_failure_on_missing_input_exits_nonzero_single_line_without_usage_or_output() { - let dir = TempDir::new("missing-input"); - write_restatement_fixture(&dir.0); - fs::remove_file(dir.0.join("qmFilings.bson")).unwrap(); - - let result = cli() - .current_dir(&dir.0) - .args(FIXTURE_REQUIRED_ARGS) - .args(["--out", "out", "--fiscal-period", "quarterly"]) - .output() - .expect("run curate-fundamentals"); - - assert_eq!(result.status.code(), Some(1)); - assert!(result.stdout.is_empty()); - let stderr = String::from_utf8(result.stderr).unwrap(); - assert_eq!(stderr.lines().count(), 1, "{stderr}"); - assert!(stderr.starts_with("error: "), "{stderr}"); - assert!(stderr.contains("qmFilings.bson"), "{stderr}"); - assert!(!stderr.contains("Usage:"), "{stderr}"); - assert!(!dir.0.join("out").exists(), "out must not be created"); -} - -#[test] -fn cli_truncated_financials_dump_fails_closed_without_publishing() { - let dir = TempDir::new("truncated"); - write_restatement_fixture(&dir.0); - fs::write(dir.0.join("qmFinancials.bson"), [0x10u8, 0x00, 0x00]).unwrap(); - - let result = cli() - .current_dir(&dir.0) - .args(FIXTURE_REQUIRED_ARGS) - .args(["--out", "out", "--fiscal-period", "quarterly"]) - .output() - .expect("run curate-fundamentals"); - - assert_eq!(result.status.code(), Some(1)); - assert!(result.stdout.is_empty()); - let stderr = String::from_utf8(result.stderr).unwrap(); - assert_eq!(stderr.lines().count(), 1, "{stderr}"); - assert!(stderr.starts_with("error: "), "{stderr}"); - assert!(!dir.0.join("out/fundamentals_pit").exists()); -} - -#[test] -fn cli_parse_time_config_errors_fail_closed_before_touching_out() { - let dir = TempDir::new("config-errors"); - write_restatement_fixture(&dir.0); - - let cases: [(&[&str], &str); 4] = [ - ( - &["--quarterly-tokens", "Q1,FY", "--annual-tokens", "FY"], - "error: invalid qmFinancials fiscal period configuration: report_period token 'FY' cannot appear in both quarterly and annual lists", - ), - ( - &["--fiscal-period", "quarterly", "--quarterly-tokens", "Q1"], - "error: cannot combine '--fiscal-period' with '--quarterly-tokens' or '--annual-tokens'", - ), - ( - &["--fiscal-period", "quarterly", "--mongo-uri", "mongodb://localhost:27017/stock"], - "error: unknown flag '--mongo-uri' for curate-fundamentals", - ), - ( - &["--fiscal-period", "quarterly", "--k", "0"], - "error: duplicate flag '--k'", - ), - ]; - - for (idx, (extra, expected_error)) in cases.iter().enumerate() { - let out = format!("out_{idx}"); - let result = cli() - .current_dir(&dir.0) - .args(FIXTURE_REQUIRED_ARGS) - .args(["--out", out.as_str()]) - .args(*extra) - .output() - .expect("run curate-fundamentals"); - assert_eq!(result.status.code(), Some(1), "case {idx}"); - assert!(result.stdout.is_empty(), "case {idx}"); - assert_single_line_error_then_usage(&result.stderr, expected_error); - assert!( - !dir.0.join(&out).exists(), - "case {idx}: out must not be created" - ); - } -} diff --git a/tools/curate-etl/tests/curate_macro.rs b/tools/curate-etl/tests/curate_macro.rs deleted file mode 100644 index c35eefbf..00000000 --- a/tools/curate-etl/tests/curate_macro.rs +++ /dev/null @@ -1,776 +0,0 @@ -//! End-to-end tests for the file-mode `curate-macro` CLI. - -use std::fs::{self, File}; -use std::path::{Path, PathBuf}; -use std::process::Command; -use std::sync::atomic::{AtomicU64, Ordering}; - -use bson::raw::{cstr, RawArrayBuf, RawDocumentBuf}; -use bson::DateTime; -use curate_etl::macro_series::{ - MACRO_KNOWN_AT_SOURCE, MONTHLY_RELEASE_LAG_DAYS, POLICY_RATE_LAG_DAYS, -}; -use curate_etl::run_curate_macro::{ - format_curate_macro_report, run_curate_macro, CurateMacroArgs, MACRO_SERIES_MAP_HEADER, -}; -use curate_etl::split::ymd_to_epoch_days; -use parquet::file::reader::{FileReader, SerializedFileReader}; -use parquet::record::{Field, Row}; - -const MICROS_PER_DAY: i64 = 86_400_000_000; - -static TEMP_SEQ: AtomicU64 = AtomicU64::new(0); - -struct TempDir(PathBuf); - -impl TempDir { - fn new(label: &str) -> Self { - let seq = TEMP_SEQ.fetch_add(1, Ordering::Relaxed); - let path = std::env::temp_dir().join(format!( - "curate-macro-cli-{label}-{}-{seq}", - std::process::id() - )); - let _ = fs::remove_dir_all(&path); - fs::create_dir_all(&path).expect("create isolated test directory"); - Self(path) - } -} - -impl Drop for TempDir { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.0); - } -} - -fn cli() -> Command { - let mut command = Command::new(env!("CARGO_BIN_EXE_curate-etl")); - command.arg("curate-macro"); - command -} - -fn day(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).expect("valid date") -} - -fn make_point_doc(d: &str, v: f64) -> RawDocumentBuf { - let mut pt = RawDocumentBuf::new(); - pt.append(cstr!("d"), d); - pt.append(cstr!("v"), v); - pt -} - -fn make_te_data_doc( - te_symbol: &str, - country: &str, - category: &str, - data_points: &[(&str, f64)], - forecast_points: &[(&str, f64)], -) -> RawDocumentBuf { - let mut data_arr = RawArrayBuf::new(); - for &(d, v) in data_points { - data_arr.push(make_point_doc(d, v)); - } - - let mut forecast_arr = RawArrayBuf::new(); - for &(d, v) in forecast_points { - forecast_arr.push(make_point_doc(d, v)); - } - - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("teSymbol"), te_symbol); - doc.append(cstr!("name"), format!("{country} {category}")); - doc.append(cstr!("unit"), "percent"); - doc.append(cstr!("source"), "TradingEconomics"); - doc.append(cstr!("frequency"), "Monthly"); - doc.append(cstr!("country"), country); - doc.append(cstr!("category"), category); - doc.append(cstr!("data"), data_arr); - doc.append(cstr!("forecast"), forecast_arr); - doc.append( - cstr!("lastUpdated"), - DateTime::from_millis(1_710_000_000_000), - ); - doc.append(cstr!("createdAt"), DateTime::from_millis(1_700_000_000_000)); - doc -} - -fn write_macro_fixture(dir: &Path) -> (PathBuf, PathBuf) { - let te_data_path = dir.join("teData.bson"); - let series_map_path = dir.join("series-map.tsv"); - - let map_tsv = format!( - "{MACRO_SERIES_MAP_HEADER}\n\ - USIR\tUnited States\tInterest Rate\tUS\tpolicy_rate\tpolicy_rate\n\ - CACPI\tCanada\tInflation Rate\tCA\tcpi_yoy\tmonthly_release\n" - ); - fs::write(&series_map_path, map_tsv).unwrap(); - - // Fixture covers: - // - US policy_rate (+1d lag) with 2 valid points + 1 invalid date + forecast sentinel points - // - CA monthly_release (+35d lag) with 2 valid points + forecast sentinel points - // - One unmapped series whose points must be dropped into `dropped_unmapped_series` - let docs = [ - make_te_data_doc( - "USIR", - "United States", - "Interest Rate", - &[ - ("2024-03-20", 5.5), - ("not-a-date", 99.0), - ("2024-01-31", 5.25), - ], - &[("2025-12-31", 999.25)], - ), - make_te_data_doc( - "CACPI", - "Canada", - "Inflation Rate", - &[("2024-02-29", 2.8), ("2024-01-31", 2.9)], - &[("2025-06-30", 888.5)], - ), - make_te_data_doc( - "UNMAPPED", - "Germany", - "GDP", - &[("2024-03-31", 1.2)], - &[("2025-03-31", 777.0)], - ), - ]; - - let mut raw_bson = Vec::new(); - for doc in &docs { - raw_bson.extend_from_slice(doc.as_bytes()); - } - fs::write(&te_data_path, raw_bson).unwrap(); - - (te_data_path, series_map_path) -} - -fn write_policy_rate_fixture(dir: &Path) -> (PathBuf, PathBuf) { - let te_data_path = dir.join("teData.bson"); - let series_map_path = dir.join("macro_series_map.tsv"); - - let doc = make_te_data_doc( - "FDTR", - "United States", - "Interest Rate", - &[("2024-03-20", 5.5)], - &[("2025-01-01", 99.0)], - ); - fs::write(&te_data_path, doc.as_bytes()).expect("write teData.bson"); - - let tsv = format!( - "{MACRO_SERIES_MAP_HEADER}\nFDTR\tUnited States\tInterest Rate\tUS\tfed_funds_rate\tpolicy_rate\n" - ); - fs::write(&series_map_path, tsv).expect("write macro_series_map.tsv"); - - (te_data_path, series_map_path) -} - -fn col<'a>(row: &'a Row, name: &str) -> &'a Field { - row.get_column_iter() - .find(|(col_name, _)| col_name.as_str() == name) - .unwrap_or_else(|| panic!("missing Parquet column '{name}'")) - .1 -} - -#[test] -fn cli_publishes_runner_equivalent_macro_parquet_with_pit_lag_and_no_forecast_leakage() { - let dir = TempDir::new("e2e"); - let (te_data_path, series_map_path) = write_macro_fixture(&dir.0); - - let baseline_dir = dir.0.join("baseline"); - let baseline_args = CurateMacroArgs { - te_data: te_data_path, - series_map: series_map_path, - out_dir: baseline_dir.clone(), - }; - let baseline_report = run_curate_macro(&baseline_args).expect("run library baseline"); - - // Verify fixture counts and conservation equations. - assert_eq!(baseline_report.series_map_entries, 2); - let d = &baseline_report.decode_stats; - let c = &baseline_report.curate_stats; - let w = &baseline_report.write_stats; - assert_eq!(d.docs_in, 3); - assert_eq!(d.docs_accepted, 3); - assert_eq!(d.docs_rejected_total(), 0); - assert_eq!(d.docs_in, d.docs_accepted + d.docs_rejected_total()); - assert_eq!(d.points_in, 6); - assert_eq!(d.points_decoded, 5); - assert_eq!(d.rejected_invalid_date, 1); - assert_eq!(d.points_in, d.points_decoded + d.rejected_total()); - assert_eq!(d.points_decoded, c.points_in); - assert_eq!(c.dropped_unmapped_series, 1); - assert_eq!(c.builder.input, 4); - assert_eq!(c.points_in, c.dropped_unmapped_series + c.builder.input); - assert_eq!(c.rows_out, 4); - assert_eq!(c.rows_out, c.builder.emitted); - assert_eq!(c.rows_out, w.rows_written); - assert_eq!(c.series_out, 2); - assert_eq!(w.files_written, 1); - - let expected_stdout = format!("{}\n", format_curate_macro_report(&baseline_report)); - let baseline_parquet = fs::read(baseline_dir.join("macro/part.parquet")) - .expect("read baseline macro/part.parquet"); - - // First CLI run (mixed space and `=` flag forms). - let cli_out = dir.0.join("cli_out"); - let result = cli() - .current_dir(&dir.0) - .args([ - "--te-data", - "teData.bson", - "--series-map=series-map.tsv", - "--out", - "cli_out", - ]) - .output() - .expect("run curate-macro"); - - assert!(result.status.success(), "{result:?}"); - assert!( - result.stderr.is_empty(), - "unexpected stderr: {}", - String::from_utf8_lossy(&result.stderr) - ); - let stdout = String::from_utf8(result.stdout).expect("utf-8 stdout"); - assert_eq!(stdout, expected_stdout); - - let cli_parquet_path = cli_out.join("macro/part.parquet"); - assert!(cli_parquet_path.is_file(), "expected macro/part.parquet"); - let cli_parquet = fs::read(&cli_parquet_path).expect("read cli macro/part.parquet"); - assert_eq!( - cli_parquet, baseline_parquet, - "CLI Parquet output must be byte-identical to library baseline" - ); - - // Second fresh CLI run must also be byte-identical. - let cli_out_2 = dir.0.join("cli_out_2"); - let result_2 = cli() - .current_dir(&dir.0) - .args([ - "--out=cli_out_2", - "--series-map", - "series-map.tsv", - "--te-data=teData.bson", - ]) - .output() - .expect("run curate-macro second time"); - assert!(result_2.status.success(), "{result_2:?}"); - assert!(result_2.stderr.is_empty()); - assert_eq!( - String::from_utf8(result_2.stdout).unwrap(), - expected_stdout - ); - let cli_parquet_2 = - fs::read(cli_out_2.join("macro/part.parquet")).expect("read second macro/part.parquet"); - assert_eq!( - cli_parquet_2, cli_parquet, - "repeat CLI run must publish byte-identical Parquet" - ); - - // Verify exact 6-column schema, ascending order, PIT lag math, and zero forecast leakage. - let reader = SerializedFileReader::new(File::open(&cli_parquet_path).unwrap()).unwrap(); - let rows: Vec = reader - .get_row_iter(None) - .unwrap() - .map(Result::unwrap) - .collect(); - assert_eq!(rows.len(), 4); - - let expected_rows: [(&str, &str, i32, i32, f64); 4] = [ - ("CA", "cpi_yoy", day(2024, 1, 31), MONTHLY_RELEASE_LAG_DAYS, 2.9), - ("CA", "cpi_yoy", day(2024, 2, 29), MONTHLY_RELEASE_LAG_DAYS, 2.8), - ("US", "policy_rate", day(2024, 1, 31), POLICY_RATE_LAG_DAYS, 5.25), - ("US", "policy_rate", day(2024, 3, 20), POLICY_RATE_LAG_DAYS, 5.5), - ]; - - for (row, &(country, indicator, period_date, lag_days, value)) in - rows.iter().zip(expected_rows.iter()) - { - assert_eq!(row.len(), 6, "expected 6 columns in macro/part.parquet"); - assert_eq!(col(row, "country_iso"), &Field::Str(country.to_string())); - assert_eq!(col(row, "indicator"), &Field::Str(indicator.to_string())); - assert_eq!(col(row, "period_date"), &Field::Date(period_date)); - let expected_known_at = i64::from(period_date + lag_days) * MICROS_PER_DAY; - assert_eq!( - col(row, "known_at"), - &Field::TimestampMicros(expected_known_at) - ); - assert_eq!( - col(row, "known_at_source"), - &Field::Str(MACRO_KNOWN_AT_SOURCE.to_string()) - ); - assert_eq!(col(row, "value"), &Field::Double(value)); - // Sentinel forecast values (999.25, 888.5, 777.0) must never appear. - assert!(value < 100.0, "unexpected forecast sentinel value {value}"); - } -} - -#[test] -fn cli_runner_failures_fail_closed_without_creating_or_modifying_output() { - let dir = TempDir::new("runner-failures"); - write_macro_fixture(&dir.0); - - // Pre-seed a sentinel macro/part.parquet to prove failed runs never overwrite existing output. - let seeded_out = dir.0.join("seeded_out"); - let seeded_parquet = seeded_out.join("macro/part.parquet"); - fs::create_dir_all(seeded_parquet.parent().unwrap()).unwrap(); - let sentinel_bytes = b"pre-existing-macro-parquet-sentinel".to_vec(); - fs::write(&seeded_parquet, &sentinel_bytes).unwrap(); - - // Case 1: missing --te-data file (fresh --out not created). - let missing_te_out = dir.0.join("out_missing_te"); - let res_missing_te = cli() - .current_dir(&dir.0) - .args([ - "--te-data", - "does-not-exist.bson", - "--series-map", - "series-map.tsv", - "--out", - "out_missing_te", - ]) - .output() - .expect("run curate-macro missing teData"); - assert_eq!(res_missing_te.status.code(), Some(1)); - assert!(res_missing_te.stdout.is_empty()); - let stderr_te = String::from_utf8(res_missing_te.stderr).unwrap(); - assert_eq!(stderr_te.lines().count(), 1, "{stderr_te}"); - assert!(stderr_te.starts_with("error: "), "{stderr_te}"); - assert!(stderr_te.contains("does-not-exist.bson"), "{stderr_te}"); - assert!(!stderr_te.contains("Usage:"), "{stderr_te}"); - assert!(!missing_te_out.exists(), "out dir must not be created"); - - // Case 2: missing --series-map file (pre-seeded output preserved). - let res_missing_map = cli() - .current_dir(&dir.0) - .args([ - "--te-data", - "teData.bson", - "--series-map", - "missing-map.tsv", - "--out", - "seeded_out", - ]) - .output() - .expect("run curate-macro missing series-map"); - assert_eq!(res_missing_map.status.code(), Some(1)); - assert!(res_missing_map.stdout.is_empty()); - let stderr_map = String::from_utf8(res_missing_map.stderr).unwrap(); - assert_eq!(stderr_map.lines().count(), 1, "{stderr_map}"); - assert!(stderr_map.starts_with("error: "), "{stderr_map}"); - assert!(stderr_map.contains("missing-map.tsv"), "{stderr_map}"); - assert!(!stderr_map.contains("Usage:"), "{stderr_map}"); - assert_eq!( - fs::read(&seeded_parquet).unwrap(), - sentinel_bytes, - "pre-seeded macro/part.parquet must remain byte-identical" - ); - - // Case 3: truncated/corrupt BSON (pre-seeded output preserved, fresh out not created). - let corrupt_path = dir.0.join("corrupt.bson"); - fs::write(&corrupt_path, [0x10u8, 0x00, 0x00]).unwrap(); - let corrupt_out = dir.0.join("out_corrupt"); - let res_corrupt = cli() - .current_dir(&dir.0) - .args([ - "--te-data", - "corrupt.bson", - "--series-map", - "series-map.tsv", - "--out", - "out_corrupt", - ]) - .output() - .expect("run curate-macro corrupt BSON"); - assert_eq!(res_corrupt.status.code(), Some(1)); - assert!(res_corrupt.stdout.is_empty()); - let stderr_corrupt = String::from_utf8(res_corrupt.stderr).unwrap(); - assert_eq!(stderr_corrupt.lines().count(), 1, "{stderr_corrupt}"); - assert!(stderr_corrupt.starts_with("error: "), "{stderr_corrupt}"); - assert!(!stderr_corrupt.contains("Usage:"), "{stderr_corrupt}"); - assert!(!corrupt_out.exists(), "out dir must not be created"); - - let res_corrupt_seeded = cli() - .current_dir(&dir.0) - .args([ - "--te-data", - "corrupt.bson", - "--series-map", - "series-map.tsv", - "--out", - "seeded_out", - ]) - .output() - .expect("run curate-macro corrupt BSON against seeded out"); - assert_eq!(res_corrupt_seeded.status.code(), Some(1)); - assert!(res_corrupt_seeded.stdout.is_empty()); - assert_eq!( - fs::read(&seeded_parquet).unwrap(), - sentinel_bytes, - "pre-seeded macro/part.parquet must remain byte-identical on corrupt BSON" - ); -} - -#[test] -fn cli_invalid_flags_print_error_and_usage_without_touching_out() { - let dir = TempDir::new("invalid-flags"); - write_macro_fixture(&dir.0); - - let cases: [(&[&str], &str); 2] = [ - ( - &[ - "--from-mongo", - "--te-data", - "teData.bson", - "--series-map", - "series-map.tsv", - "--out", - "out_from_mongo", - ], - "error: unknown flag '--from-mongo' for curate-macro", - ), - ( - &[ - "--te-data", - "teData.bson", - "--series-map", - "series-map.tsv", - ], - "error: missing required flag '--out'", - ), - ]; - - for (idx, (argv, expected_error)) in cases.iter().enumerate() { - let result = cli() - .current_dir(&dir.0) - .args(*argv) - .output() - .expect("run curate-macro invalid flags"); - assert_eq!(result.status.code(), Some(1), "case {idx}"); - assert!(result.stdout.is_empty(), "case {idx}"); - let stderr = String::from_utf8(result.stderr).expect("utf-8 stderr"); - let mut lines = stderr.lines(); - assert_eq!(lines.next(), Some(*expected_error), "{stderr}"); - assert_eq!(lines.next(), Some("Usage:"), "{stderr}"); - assert!( - stderr.contains("curate-macro --te-data --series-map --out "), - "{stderr}" - ); - } - - assert!( - !dir.0.join("out_from_mongo").exists(), - "out_from_mongo must not be created" - ); -} - -#[test] -fn cli_publishes_runner_equivalent_macro_parquet_and_excludes_forecast_sentinel() { - let dir = TempDir::new("e2e-policy-rate"); - let (te_data_path, series_map_path) = write_policy_rate_fixture(&dir.0); - - let baseline_out = dir.0.join("baseline_out"); - let baseline_report = run_curate_macro(&CurateMacroArgs { - te_data: te_data_path.clone(), - series_map: series_map_path.clone(), - out_dir: baseline_out.clone(), - }) - .expect("run library baseline"); - let expected_stdout = format!("{}\n", format_curate_macro_report(&baseline_report)); - - let cli_out = dir.0.join("cli_out"); - let result = cli() - .current_dir(&dir.0) - .args([ - "--te-data", - "teData.bson", - "--series-map=macro_series_map.tsv", - "--out", - "cli_out", - ]) - .output() - .expect("run curate-macro"); - - assert!(result.status.success(), "{result:?}"); - assert!( - result.stderr.is_empty(), - "unexpected stderr: {}", - String::from_utf8_lossy(&result.stderr) - ); - let stdout = String::from_utf8(result.stdout).expect("utf-8 stdout"); - assert_eq!(stdout, expected_stdout); - - let cli_parquet = cli_out.join("macro/part.parquet"); - let baseline_parquet = baseline_out.join("macro/part.parquet"); - assert!(cli_parquet.is_file(), "expected {}", cli_parquet.display()); - assert_eq!( - fs::read(&cli_parquet).expect("read cli parquet"), - fs::read(&baseline_parquet).expect("read baseline parquet"), - "CLI Parquet output must match library runner bytes" - ); - - let reader = SerializedFileReader::new(File::open(&cli_parquet).expect("open parquet")) - .expect("open parquet reader"); - let rows: Vec = reader - .get_row_iter(None) - .expect("row iter") - .map(|row| row.expect("decode row")) - .collect(); - assert_eq!( - rows.len(), - 1, - "expected exactly one mapped policy-rate row and no forecast sentinel row" - ); - - let expected_period_date = ymd_to_epoch_days(2024, 3, 20).expect("valid date"); - let expected_known_at = i64::from(expected_period_date + POLICY_RATE_LAG_DAYS) * MICROS_PER_DAY; - assert_eq!(POLICY_RATE_LAG_DAYS, 1); - - let row = &rows[0]; - assert_eq!(col(row, "country_iso"), &Field::Str("US".to_string())); - assert_eq!( - col(row, "indicator"), - &Field::Str("fed_funds_rate".to_string()) - ); - assert_eq!(col(row, "period_date"), &Field::Date(expected_period_date)); - assert_eq!( - col(row, "known_at"), - &Field::TimestampMicros(expected_known_at) - ); - assert_eq!( - col(row, "known_at_source"), - &Field::Str("publication_lag_estimate".to_string()) - ); - assert_eq!(col(row, "value"), &Field::Double(5.5)); -} - -#[test] -fn cli_missing_te_data_exits_nonzero_with_single_line_escaped_error_and_no_parquet() { - let dir = TempDir::new("missing-te-data"); - let (_, series_map_path) = write_policy_rate_fixture(&dir.0); - - let missing_path = dir.0.join("missing\nte_data\r.bson"); - let cli_out = dir.0.join("cli_out"); - - let result = cli() - .arg("--te-data") - .arg(&missing_path) - .arg("--series-map") - .arg(&series_map_path) - .arg("--out") - .arg(&cli_out) - .output() - .expect("run curate-macro"); - - assert_eq!(result.status.code(), Some(1), "{result:?}"); - assert!( - result.stdout.is_empty(), - "unexpected stdout: {}", - String::from_utf8_lossy(&result.stdout) - ); - - let stderr = String::from_utf8(result.stderr).expect("utf-8 stderr"); - assert_eq!( - stderr.lines().count(), - 1, - "expected 1 stderr line: {stderr:?}" - ); - assert!(!stderr.contains('\r'), "stderr must escape CR: {stderr:?}"); - assert!(stderr.starts_with("error: "), "{stderr:?}"); - assert!(stderr.contains("te-data"), "{stderr:?}"); - assert!( - stderr.contains("missing\\nte_data\\r.bson"), - "expected escaped path in stderr: {stderr:?}" - ); - assert!(!stderr.contains("Usage:"), "{stderr:?}"); - assert!( - !cli_out.join("macro/part.parquet").exists(), - "macro/part.parquet must not be written on failure" - ); - assert!(!cli_out.exists(), "out dir must not be created on failure"); -} - -// ---- QA edge cases (T-202) ---- - -fn run_cli_paths(te_data: &Path, series_map: &Path, out: &Path) -> std::process::Output { - cli() - .arg("--te-data") - .arg(te_data) - .arg("--series-map") - .arg(series_map) - .arg("--out") - .arg(out) - .output() - .expect("run curate-macro") -} - -#[test] -fn cli_help_lists_curate_macro_and_parse_errors_print_usage_without_writing() { - let help = Command::new(env!("CARGO_BIN_EXE_curate-etl")) - .arg("--help") - .output() - .expect("run --help"); - assert!(help.status.success(), "{help:?}"); - let help_text = String::from_utf8(help.stdout).expect("utf-8 help"); - assert!( - help_text.contains("curate-macro --te-data --series-map --out "), - "{help_text}" - ); - - let dir = TempDir::new("parse-error"); - let (te_data_path, series_map_path) = write_policy_rate_fixture(&dir.0); - let cli_out = dir.0.join("cli_out"); - - // `--mongo-uri` is not a file-mode flag; it must be rejected before any run. - let result = cli() - .arg("--te-data") - .arg(&te_data_path) - .arg("--series-map") - .arg(&series_map_path) - .arg("--out") - .arg(&cli_out) - .args(["--mongo-uri", "mongodb://user:secret@host:27017/stock"]) - .output() - .expect("run curate-macro"); - - assert_eq!(result.status.code(), Some(1), "{result:?}"); - assert!(result.stdout.is_empty(), "{result:?}"); - let stderr = String::from_utf8(result.stderr).expect("utf-8 stderr"); - assert!( - stderr.starts_with("error: unknown flag '--mongo-uri' for curate-macro\n"), - "{stderr:?}" - ); - assert!(stderr.contains("Usage:"), "{stderr:?}"); - assert!( - !stderr.contains("secret"), - "rejected flag value must not be echoed: {stderr:?}" - ); - assert!( - !cli_out.exists(), - "out dir must not be created on parse error" - ); -} - -#[test] -fn cli_runtime_failures_keep_existing_parquet_byte_identical() { - let dir = TempDir::new("preserve"); - let (te_data_path, series_map_path) = write_policy_rate_fixture(&dir.0); - let out = dir.0.join("out"); - - let first = run_cli_paths(&te_data_path, &series_map_path, &out); - assert!(first.status.success(), "{first:?}"); - let parquet = out.join("macro/part.parquet"); - let original = fs::read(&parquet).expect("read published parquet"); - - let bad_header = dir.0.join("bad_header.tsv"); - fs::write(&bad_header, "not\ta\theader\n").expect("write bad tsv"); - let corrupt_bson = dir.0.join("corrupt.bson"); - // Declares a 64-byte document but provides only 8 bytes. - fs::write(&corrupt_bson, [64u8, 0, 0, 0, 1, 2, 3, 4]).expect("write corrupt bson"); - let missing_map = dir.0.join("missing_map.tsv"); - - for (label, te, map, role) in [ - ("bad series-map header", &te_data_path, &bad_header, None), - ( - "truncated teData", - &corrupt_bson, - &series_map_path, - Some("te-data"), - ), - ( - "missing series-map", - &te_data_path, - &missing_map, - Some("series-map"), - ), - ] { - let result = run_cli_paths(te, map, &out); - assert_eq!(result.status.code(), Some(1), "{label}: {result:?}"); - assert!(result.stdout.is_empty(), "{label}: {result:?}"); - let stderr = String::from_utf8(result.stderr).expect("utf-8 stderr"); - assert_eq!(stderr.lines().count(), 1, "{label}: {stderr:?}"); - assert!(stderr.starts_with("error: "), "{label}: {stderr:?}"); - assert!(!stderr.contains("Usage:"), "{label}: {stderr:?}"); - if let Some(role) = role { - assert!(stderr.contains(role), "{label}: {stderr:?}"); - } - assert_eq!( - fs::read(&parquet).expect("re-read parquet"), - original, - "{label}: failed run must not touch the published parquet" - ); - } -} - -#[test] -fn cli_rerun_on_same_inputs_is_byte_deterministic() { - let dir = TempDir::new("rerun"); - let (te_data_path, series_map_path) = write_policy_rate_fixture(&dir.0); - let out_a = dir.0.join("out_a"); - let out_b = dir.0.join("out_b"); - - let a = run_cli_paths(&te_data_path, &series_map_path, &out_a); - let b = run_cli_paths(&te_data_path, &series_map_path, &out_b); - assert!(a.status.success() && b.status.success(), "{a:?} {b:?}"); - assert_eq!(a.stdout, b.stdout); - assert_eq!( - fs::read(out_a.join("macro/part.parquet")).expect("read a"), - fs::read(out_b.join("macro/part.parquet")).expect("read b") - ); - - // Republishing into the same directory replaces the file with identical bytes. - let again = run_cli_paths(&te_data_path, &series_map_path, &out_a); - assert!(again.status.success(), "{again:?}"); - assert_eq!( - fs::read(out_a.join("macro/part.parquet")).expect("read a again"), - fs::read(out_b.join("macro/part.parquet")).expect("read b") - ); -} - -#[test] -fn cli_unmapped_only_input_succeeds_and_matches_runner_report() { - let dir = TempDir::new("unmapped"); - let te_data_path = dir.0.join("teData.bson"); - let series_map_path = dir.0.join("macro_series_map.tsv"); - let doc = make_te_data_doc( - "UNMAPPED", - "Atlantis", - "Interest Rate", - &[("2024-03-20", 1.25)], - &[], - ); - fs::write(&te_data_path, doc.as_bytes()).expect("write teData"); - fs::write( - &series_map_path, - format!( - "{MACRO_SERIES_MAP_HEADER}\nFDTR\tUnited States\tInterest Rate\tUS\tfed_funds_rate\tpolicy_rate\n" - ), - ) - .expect("write tsv"); - - let baseline_out = dir.0.join("baseline_out"); - let baseline = run_curate_macro(&CurateMacroArgs { - te_data: te_data_path.clone(), - series_map: series_map_path.clone(), - out_dir: baseline_out.clone(), - }) - .expect("library run"); - assert_eq!(baseline.curate_stats.rows_out, 0); - - let cli_out = dir.0.join("cli_out"); - let result = run_cli_paths(&te_data_path, &series_map_path, &cli_out); - assert!(result.status.success(), "{result:?}"); - assert!(result.stderr.is_empty(), "{result:?}"); - assert_eq!( - String::from_utf8(result.stdout).expect("utf-8 stdout"), - format!("{}\n", format_curate_macro_report(&baseline)) - ); - assert_eq!( - cli_out.join("macro/part.parquet").exists(), - baseline_out.join("macro/part.parquet").exists(), - "CLI and runner must agree on zero-row publication" - ); -} diff --git a/tools/curate-etl/tests/curate_posts.rs b/tools/curate-etl/tests/curate_posts.rs deleted file mode 100644 index c349ceec..00000000 --- a/tools/curate-etl/tests/curate_posts.rs +++ /dev/null @@ -1,191 +0,0 @@ -//! End-to-end tests for the file-mode curate-posts CLI. - -use std::fs::{self, File}; -use std::path::{Path, PathBuf}; -use std::process::{Command, Output}; - -use bson::{doc, Document}; -use curate_etl::bson_ceo_posts::CeoPostsTimestampUnit; -use curate_etl::run_curate_posts::{format_curate_posts_report, run_curate_posts, CuratePostsArgs}; -use parquet::file::reader::{FileReader, SerializedFileReader}; -use parquet::record::RowAccessor; - -const POSTED: i64 = 1_718_460_000; -const EDITED: i64 = POSTED + 3_600; -const PARTITION: &str = "events/year=2024/part.parquet"; -const MAPPING: &str = "ceo_alt\tCH_1\t2020-01-01\t\t555\nceo_alt\tCH_2\t2020-01-01\t\t556\n"; -const CUSTOM_FLAGS: &[&str] = &[ - "--key-field=channel", - "--spiel-id-field=id", - "--timestamp-field=ts", - "--edited-field=ed", - "--bot-field=isBot", - "--user-id-field=author", - "--text-field=body", - "--mapping-source=ceo_alt", -]; - -struct TempDir(PathBuf); - -impl Drop for TempDir { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.0); - } -} - -fn cli() -> Command { - let mut command = Command::new(env!("CARGO_BIN_EXE_curate-etl")); - command.arg("curate-posts"); - command -} - -fn curate(dir: &Path, out: &str, unit: &str) -> Output { - cli() - .current_dir(dir) - .args([ - "--ceo-posts", - "posts.bson", - "--provider-mapping=mapping.tsv", - ]) - .args(["--out", out, "--timestamp-unit", unit]) - .args(CUSTOM_FLAGS) - .output() - .expect("run curate-posts") -} - -fn write_posts(path: &Path, scale: i64, edited_text: &str) { - let posts: [Document; 3] = [ - doc! { - "channel": "CH_1", "id": "p-1", "ts": POSTED * scale, - "ed": EDITED * scale, "author": "u1", "body": edited_text, - }, - doc! { - "channel": "CH_2", "id": "wire-1", "ts": POSTED * scale, - "isBot": "1", "body": "wire release", - }, - doc! { - "channel": "unmapped", "id": "p-2", "ts": POSTED * scale, - "body": "unmapped post", - }, - ]; - let bytes: Vec = posts - .iter() - .flat_map(|post| post.to_vec().unwrap()) - .collect(); - fs::write(path, bytes).expect("write concatenated BSON"); -} - -#[test] -fn cli_publishes_runner_equivalent_posts_and_preserves_an_existing_partition() { - // Use the runner's fixed custom-field and edited-post fixture, plus a wire and an unmapped row. - let path = std::env::temp_dir().join(format!("curate-posts-cli-{}", std::process::id())); - fs::create_dir(&path).expect("create isolated test directory"); - let dir = TempDir(path); - let bson = dir.0.join("posts.bson"); - let mapping = dir.0.join("mapping.tsv"); - write_posts(&bson, 1, "hello"); - fs::write(&mapping, MAPPING).unwrap(); - - let baseline_dir = dir.0.join("baseline"); - let baseline_report = run_curate_posts(&CuratePostsArgs { - ceo_posts: bson.clone(), - provider_mapping: mapping, - out_dir: baseline_dir.clone(), - timestamp_unit: CeoPostsTimestampUnit::Seconds, - key_field: "channel".into(), - spiel_id_field: "id".into(), - timestamp_field: "ts".into(), - edited_field: "ed".into(), - bot_field: "isBot".into(), - user_id_field: "author".into(), - text_field: "body".into(), - mapping_source: "ceo_alt".into(), - }) - .expect("run library baseline"); - let baseline = fs::read(baseline_dir.join(PARTITION)).unwrap(); - let expected_report = format_curate_posts_report(&baseline_report); - - for (unit, scale) in [("seconds", 1), ("millis", 1_000)] { - write_posts(&bson, scale, "hello"); - let result = curate(&dir.0, unit, unit); - assert!(result.status.success(), "{unit}: {:?}", result); - assert!(result.stderr.is_empty()); - let stdout = String::from_utf8(result.stdout).unwrap(); - assert_eq!( - stdout.lines().take(5).collect::>(), - expected_report.lines().take(5).collect::>() - ); - assert!(stdout.contains("docs_framed=3")); - assert!(stdout.contains("dropped_unmapped=1")); - assert!(stdout.contains("rows_written=2")); - assert!(stdout.lines().last().unwrap().contains("timing:")); - assert_eq!( - fs::read(dir.0.join(unit).join(PARTITION)).unwrap(), - baseline - ); - } - - let partition = dir.0.join("millis").join(PARTITION); - let reader = SerializedFileReader::new(File::open(&partition).unwrap()).unwrap(); - let rows: Vec<_> = reader - .get_row_iter(None) - .unwrap() - .map(Result::unwrap) - .collect(); - assert_eq!(rows.len(), 2); - for (row, listing, subtype, known_at) in [ - (&rows[0], 555, "retail", EDITED), - (&rows[1], 556, "newswire", POSTED), - ] { - assert_eq!(row.get_int(0).unwrap(), listing); - assert_eq!(row.get_timestamp_micros(1).unwrap(), POSTED * 1_000_000); - assert_eq!(row.get_timestamp_micros(2).unwrap(), known_at * 1_000_000); - assert_eq!(row.get_string(4).unwrap(), "post"); - assert_eq!(row.get_string(5).unwrap(), subtype); - } - - let edited_text_visible = |cutoff| { - rows.iter().any(|row| { - row.get_timestamp_micros(2).unwrap() <= cutoff - && row.get_string(6).unwrap().contains(r#""text":"hello""#) - }) - }; - assert!(!edited_text_visible(EDITED * 1_000_000 - 1)); - assert!(edited_text_visible(EDITED * 1_000_000)); - - write_posts(&bson, 1_000, "replacement"); - let retry = curate(&dir.0, "millis", "millis"); - assert_eq!(retry.status.code(), Some(1)); - assert!(retry.stdout.is_empty()); - assert!(String::from_utf8_lossy(&retry.stderr) - .starts_with("error: refusing to overwrite existing events partition")); - assert_eq!(fs::read(partition).unwrap(), baseline); -} - -#[test] -fn cli_reports_usage_for_invalid_posts_flags() { - for (args, error) in [ - ( - &["--from-mongo"][..], - "unknown flag '--from-mongo' for curate-posts", - ), - ( - &["--timestamp-unit", "--out=x"][..], - "missing value for flag '--timestamp-unit'", - ), - ( - &["--text-field=first", "--text-field", "second"][..], - "duplicate flag '--text-field'", - ), - ] { - let result = cli().args(args).output().expect("run curate-posts"); - assert_eq!(result.status.code(), Some(1), "{args:?}"); - assert!(result.stdout.is_empty(), "{args:?}"); - let stderr = String::from_utf8(result.stderr).unwrap(); - assert_eq!( - stderr.lines().next(), - Some(format!("error: {error}").as_str()) - ); - assert!(stderr.contains("curate-posts --ceo-posts"), "{stderr}"); - } -} diff --git a/tools/curate-etl/tests/curate_qm_bars_1m.rs b/tools/curate-etl/tests/curate_qm_bars_1m.rs deleted file mode 100644 index 48eca37a..00000000 --- a/tools/curate-etl/tests/curate_qm_bars_1m.rs +++ /dev/null @@ -1,684 +0,0 @@ -//! End-to-end binary integration tests for `curate-etl curate-qm-bars-1m` (`M2.3r`). - -use std::collections::BTreeMap; -use std::fs; -use std::path::{Path, PathBuf}; -use std::process::{Command, Output}; -use std::sync::atomic::{AtomicU64, Ordering}; - -use bson::raw::{cstr, RawDocumentBuf}; -use bson::DateTime as BsonDateTime; -use curate_etl::bars_1m::BARS_1M_SOURCE_QM; -use curate_etl::ilp::{ILP_V2_DOUBLE_TYPE, TABLE_BARS_1M}; -use curate_etl::{ - et_to_utc_micros, format_curate_qm_bars_1m_report, run_curate_qm_bars_1m, ymd_to_epoch_days, - BsonStreamOptions, CurateQmBars1mArgs, IlpWriterOptions, DEFAULT_QM_BARS_1M_MAPPING_SOURCE, -}; - -static TEST_DIR_SEQ: AtomicU64 = AtomicU64::new(0); - -struct TempDir { - path: PathBuf, -} - -impl TempDir { - fn new(tag: &str) -> Self { - let pid = std::process::id(); - let seq = TEST_DIR_SEQ.fetch_add(1, Ordering::Relaxed); - let path = - std::env::temp_dir().join(format!("curate-etl-it-qm-bars-1m-{tag}-{pid}-{seq}")); - let _ = fs::remove_dir_all(&path); - fs::create_dir_all(&path).expect("create integration test temp dir"); - Self { path } - } - - fn path(&self) -> &Path { - &self.path - } -} - -impl Drop for TempDir { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.path); - } -} - -fn run_bin(args: &[&str]) -> Output { - Command::new(env!("CARGO_BIN_EXE_curate-etl")) - .args(args) - .output() - .expect("spawn curate-etl binary") -} - -fn day(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).expect("valid date") -} - -fn et_ts_millis(y: i32, m: u32, d: u32, hour: u8, minute: u8) -> i64 { - let micros = et_to_utc_micros(day(y, m, d), hour, minute, 0).expect("valid ET timestamp"); - assert_eq!(micros % 1_000, 0); - micros / 1_000 -} - -fn make_qm_intraday_doc( - code: &str, - timestamp_ms: i64, - open: f64, - high: f64, - low: f64, - close: f64, - sharevolume: f64, -) -> RawDocumentBuf { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), code); - doc.append(cstr!("timestamp"), BsonDateTime::from_millis(timestamp_ms)); - doc.append(cstr!("open"), open); - doc.append(cstr!("high"), high); - doc.append(cstr!("low"), low); - doc.append(cstr!("close"), close); - doc.append(cstr!("sharevolume"), sharevolume); - doc -} - -#[allow(clippy::too_many_arguments)] -fn make_qm_intraday_doc_with_adjusted( - code: &str, - timestamp_ms: i64, - open: f64, - high: f64, - low: f64, - close: f64, - sharevolume: f64, - adj_scale: f64, -) -> RawDocumentBuf { - let mut doc = make_qm_intraday_doc(code, timestamp_ms, open, high, low, close, sharevolume); - doc.append(cstr!("adjustedopen"), open / adj_scale); - doc.append(cstr!("adjustedhigh"), high / adj_scale); - doc.append(cstr!("adjustedlow"), low / adj_scale); - doc.append(cstr!("adjustedclose"), close / adj_scale); - doc.append(cstr!("avolume"), sharevolume * adj_scale); - doc -} - -fn concat_docs(docs: &[RawDocumentBuf]) -> Vec { - let mut out = Vec::new(); - for doc in docs { - out.extend_from_slice(doc.as_bytes()); - } - out -} - -fn read_dir_files(dir: &Path) -> BTreeMap> { - let mut out = BTreeMap::new(); - for entry in fs::read_dir(dir).expect("read output dir") { - let entry = entry.expect("dir entry"); - let name = entry - .file_name() - .into_string() - .expect("UTF-8 file name in output dir"); - let bytes = fs::read(entry.path()).expect("read output file"); - out.insert(name, bytes); - } - out -} - -fn strip_timing_line(report: &str) -> Vec<&str> { - report - .lines() - .filter(|line| !line.trim_start().starts_with("timing:")) - .collect() -} - -fn shard_and_staging_files(dir: &Path) -> Vec { - if !dir.exists() { - return Vec::new(); - } - read_dir_files(dir).into_keys().collect() -} - -#[derive(Debug)] -struct IlpRow { - table: String, - listing_id: i32, - source: String, - open: f64, - high: f64, - low: f64, - close: f64, - volume: f64, - known_at: i64, - ts: i64, -} - -/// Minimal ILP v2 `bars_1m` decoder respecting 8-byte binary `DOUBLE` payloads (`==\x10<8 LE>`) -/// so embedded `0x0a` bytes inside doubles never split rows. -fn decode_rows(data: &[u8]) -> Vec { - let mut rows = Vec::new(); - let mut i = 0usize; - while i < data.len() { - let tag_start = i; - while data[i] != b' ' { - i += 1; - } - let tags = std::str::from_utf8(&data[tag_start..i]).expect("valid UTF-8 tags"); - i += 1; - - let mut parts = tags.split(','); - let table = parts.next().expect("table name").to_string(); - let listing_id: i32 = parts - .next() - .expect("listing_id tag") - .strip_prefix("listing_id=") - .expect("listing_id= prefix") - .parse() - .expect("i32 listing_id"); - let _session = parts.next().expect("session tag"); - let source = parts - .next() - .expect("source tag") - .strip_prefix("source=") - .expect("source= prefix") - .to_string(); - assert!(parts.next().is_none(), "unexpected extra ILP tag"); - - let mut read_f64 = |name: &str| -> f64 { - let prefix = format!("{name}=="); - assert!( - data[i..].starts_with(prefix.as_bytes()), - "expected {prefix} at offset {i}" - ); - i += prefix.len(); - assert_eq!( - data[i], ILP_V2_DOUBLE_TYPE, - "expected binary DOUBLE type tag for {name}" - ); - i += 1; - let v = f64::from_le_bytes(data[i..i + 8].try_into().unwrap()); - i += 8; - if data[i] == b',' { - i += 1; - } - v - }; - let open = read_f64("open"); - let high = read_f64("high"); - let low = read_f64("low"); - let close = read_f64("close"); - let volume = read_f64("volume"); - assert!(data[i..].starts_with(b"known_at="), "expected known_at="); - i += b"known_at=".len(); - let ks = i; - while data[i] != b' ' { - i += 1; - } - let known_at: i64 = std::str::from_utf8(&data[ks..i]) - .unwrap() - .strip_suffix('t') - .unwrap() - .parse() - .unwrap(); - i += 1; - let ts_start = i; - while data[i] != b'\n' { - i += 1; - } - let ts: i64 = std::str::from_utf8(&data[ts_start..i]) - .unwrap() - .strip_suffix('t') - .unwrap() - .parse() - .unwrap(); - i += 1; - rows.push(IlpRow { - table, - listing_id, - source, - open, - high, - low, - close, - volume, - known_at, - ts, - }); - } - rows -} - -struct Fixture { - intraday: PathBuf, - mapping: PathBuf, -} - -/// Synthetic `qmIntraday` fixture: -/// - `NVDA` pre-split bar with distinct `adjusted*`/`avolume` fields (ignored) and embedded `0x0a` -/// float byte in `close`. -/// - `NEXM:CA` bar with `-0.0` `sharevolume` (normalized to `+0.0`). -fn write_qm_fixture(dir: &Path, mapping_source: &str) -> (Fixture, f64) { - let close_with_lf_byte = f64::from_le_bytes([0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x59, 0x40]); - assert!(close_with_lf_byte.to_le_bytes().contains(&b'\n')); - - let intraday = dir.join("qmIntraday.bson"); - fs::write( - &intraday, - concat_docs(&[ - make_qm_intraday_doc_with_adjusted( - "NVDA", - et_ts_millis(2024, 6, 7, 15, 59), - 100.0, - 101.0, - 99.5, - close_with_lf_byte, - 412_390.0, - 10.0, - ), - make_qm_intraday_doc_with_adjusted( - "NVDA", - et_ts_millis(2024, 6, 10, 15, 59), - 121.50, - 122.00, - 121.20, - 121.79, - 350_000.0, - 1.0, - ), - make_qm_intraday_doc_with_adjusted( - "NEXM:CA", - et_ts_millis(2025, 6, 18, 15, 59), - 1.21, - 1.22, - 1.20, - 1.215, - -0.0, - 0.05, - ), - ]), - ) - .expect("write qmIntraday.bson"); - - let mapping = dir.join("provider_mapping.tsv"); - fs::write( - &mapping, - format!( - "{mapping_source}\tNVDA\t2000-01-01\t\t1001\n\ - {mapping_source}\tNEXM:CA\t2000-01-01\t\t1002\n" - ), - ) - .expect("write provider_mapping.tsv"); - - (Fixture { intraday, mapping }, close_with_lf_byte) -} - -fn bin_args<'a>( - fx: &'a Fixture, - out: &'a Path, - known_at: &'a str, - extra: &[&'a str], -) -> Vec<&'a str> { - let mut argv = vec![ - "curate-qm-bars-1m", - "--qm-intraday", - fx.intraday.to_str().unwrap(), - "--provider-mapping", - fx.mapping.to_str().unwrap(), - "--out", - out.to_str().unwrap(), - "--shards", - "2", - "--known-at-micros", - known_at, - ]; - argv.extend_from_slice(extra); - argv -} - -#[test] -fn curate_qm_bars_1m_binary_matches_direct_runner_bytes_report_and_invariants() { - let tmp = TempDir::new("parity"); - let (fx, close_with_lf_byte) = write_qm_fixture(tmp.path(), DEFAULT_QM_BARS_1M_MAPPING_SOURCE); - - let known_at_micros: i64 = 1_750_000_000_123_456; - let shard_count: usize = 2; - - let bin_out = tmp.path().join("out-bin"); - let bin_out_repeat = tmp.path().join("out-bin-repeat"); - let direct_out = tmp.path().join("out-direct"); - - let output = run_bin(&bin_args(&fx, &bin_out, "1750000000123456", &[])); - let stdout = String::from_utf8_lossy(&output.stdout); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!( - output.status.success(), - "expected exit 0, got {:?}; stderr:\n{stderr}\nstdout:\n{stdout}", - output.status.code() - ); - assert!( - stderr.is_empty(), - "expected empty stderr on success, got:\n{stderr}" - ); - - let direct_args = CurateQmBars1mArgs { - intraday_path: fx.intraday.clone(), - provider_mapping_path: fx.mapping.clone(), - out_dir: direct_out.clone(), - mapping_source: DEFAULT_QM_BARS_1M_MAPPING_SOURCE.to_string(), - shard_count, - known_at_micros, - stream_options: BsonStreamOptions::default(), - ilp_options: IlpWriterOptions::default(), - }; - let direct_report = run_curate_qm_bars_1m(&direct_args).expect("direct run_curate_qm_bars_1m"); - assert_eq!(direct_report.rows_written, 3, "expected 3 emitted rows"); - assert_eq!( - direct_report.intraday_decode.rejected_total(), - 0, - "expected zero rejected BSON documents" - ); - - let direct_formatted = format_curate_qm_bars_1m_report(&direct_report); - assert_eq!( - strip_timing_line(&stdout), - strip_timing_line(&direct_formatted), - "binary stdout report must match direct runner report excluding timing line" - ); - assert!( - stdout - .lines() - .any(|line| line.trim_start().starts_with("timing: elapsed_secs=")), - "expected timing line in stdout:\n{stdout}" - ); - - let bin_files = read_dir_files(&bin_out); - let direct_files = read_dir_files(&direct_out); - let expected_names = vec![ - "bars_1m_qm.shard-00.ilp".to_string(), - "bars_1m_qm.shard-01.ilp".to_string(), - ]; - assert_eq!( - bin_files.keys().cloned().collect::>(), - expected_names, - "unexpected files in binary output dir" - ); - assert_eq!( - bin_files, direct_files, - "binary shard files must be byte-identical to direct runner output" - ); - - // Determinism across repeat runs. - let repeat = run_bin(&bin_args(&fx, &bin_out_repeat, "1750000000123456", &[])); - assert!(repeat.status.success()); - assert_eq!( - bin_files, - read_dir_files(&bin_out_repeat), - "repeat runs must be byte-identical" - ); - assert_eq!( - strip_timing_line(&stdout), - strip_timing_line(&String::from_utf8_lossy(&repeat.stdout)), - ); - - // Decode all ILP rows across shards and verify row count + financial invariants. - let mut rows: Vec = bin_files - .values() - .flat_map(|bytes| decode_rows(bytes)) - .collect(); - assert_eq!( - rows.len(), - direct_report.rows_written, - "decoded ILP row count must equal reported rows_written" - ); - rows.sort_by_key(|r| (r.listing_id, r.ts)); - - for row in &rows { - assert_eq!(row.table, TABLE_BARS_1M); - assert_eq!(row.source, BARS_1M_SOURCE_QM); - assert_eq!(row.known_at, known_at_micros); - } - - // NVDA pre-split row: raw OHLCV bit-identical (adjusted* fields ignored), embedded 0x0a intact. - let nvda_pre = &rows[0]; - assert_eq!(nvda_pre.listing_id, 1001); - assert_eq!(nvda_pre.ts, et_ts_millis(2024, 6, 7, 15, 59) * 1_000); - assert_eq!(nvda_pre.open.to_bits(), 100.0_f64.to_bits()); - assert_eq!(nvda_pre.high.to_bits(), 101.0_f64.to_bits()); - assert_eq!(nvda_pre.low.to_bits(), 99.5_f64.to_bits()); - assert_eq!(nvda_pre.close.to_bits(), close_with_lf_byte.to_bits()); - assert_eq!(nvda_pre.volume.to_bits(), 412_390.0_f64.to_bits()); - - // NVDA post-split row (adj_scale 1.0): raw OHLCV bit-identical, no un-adjustment applied. - let nvda_post = &rows[1]; - assert_eq!(nvda_post.listing_id, 1001); - assert_eq!(nvda_post.ts, et_ts_millis(2024, 6, 10, 15, 59) * 1_000); - assert_eq!(nvda_post.open.to_bits(), 121.50_f64.to_bits()); - assert_eq!(nvda_post.high.to_bits(), 122.00_f64.to_bits()); - assert_eq!(nvda_post.low.to_bits(), 121.20_f64.to_bits()); - assert_eq!(nvda_post.close.to_bits(), 121.79_f64.to_bits()); - assert_eq!(nvda_post.volume.to_bits(), 350_000.0_f64.to_bits()); - - // NEXM:CA row: raw OHLC bit-identical, -0.0 sharevolume normalized to +0.0. - let nexm = &rows[2]; - assert_eq!(nexm.listing_id, 1002); - assert_eq!(nexm.ts, et_ts_millis(2025, 6, 18, 15, 59) * 1_000); - assert_eq!(nexm.open.to_bits(), 1.21_f64.to_bits()); - assert_eq!(nexm.high.to_bits(), 1.22_f64.to_bits()); - assert_eq!(nexm.low.to_bits(), 1.20_f64.to_bits()); - assert_eq!(nexm.close.to_bits(), 1.215_f64.to_bits()); - assert_eq!(nexm.volume.to_bits(), 0.0_f64.to_bits()); -} - -#[test] -fn curate_qm_bars_1m_binary_missing_input_exits_nonzero_single_line_stderr_and_clean_out() { - let tmp = TempDir::new("missing-input"); - let (fx, _) = write_qm_fixture(tmp.path(), DEFAULT_QM_BARS_1M_MAPPING_SOURCE); - let missing_intraday = tmp.path().join("does-not-exist.bson"); - let missing_mapping = tmp.path().join("does-not-exist.tsv"); - - for (tag, intraday_path, mapping_path) in [ - ("intraday", &missing_intraday, &fx.mapping), - ("mapping", &fx.intraday, &missing_mapping), - ] { - let out_dir = tmp.path().join(format!("out-empty-{tag}")); - fs::create_dir_all(&out_dir).expect("create empty out dir"); - - let output = run_bin(&[ - "curate-qm-bars-1m", - "--qm-intraday", - intraday_path.to_str().unwrap(), - "--provider-mapping", - mapping_path.to_str().unwrap(), - "--out", - out_dir.to_str().unwrap(), - "--shards", - "2", - "--known-at-micros", - "1750000000000000", - ]); - - let stdout = String::from_utf8_lossy(&output.stdout); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!( - !output.status.success(), - "expected non-zero exit when {tag} file is missing" - ); - assert!( - stdout.is_empty(), - "expected no success report on stdout for missing {tag}, got:\n{stdout}" - ); - let lines: Vec<&str> = stderr.lines().collect(); - assert_eq!( - lines.len(), - 1, - "expected strictly single-line stderr (no usage block) for missing {tag}, got:\n{stderr}" - ); - assert!( - lines[0].starts_with("error:"), - "expected 'error:' prefix on stderr for missing {tag}, got: {}", - lines[0] - ); - assert!( - shard_and_staging_files(&out_dir).is_empty(), - "expected no shard or staging files in output dir for missing {tag}, found: {:?}", - shard_and_staging_files(&out_dir) - ); - } -} - -#[test] -fn curate_qm_bars_1m_binary_refuses_overwrite_and_coexists_with_eod_bars_1m_shards() { - let tmp = TempDir::new("overwrite-coexist"); - let (fx, _) = write_qm_fixture(tmp.path(), DEFAULT_QM_BARS_1M_MAPPING_SOURCE); - let out = tmp.path().join("out"); - fs::create_dir_all(&out).expect("create out dir"); - - // Pre-populate an EOD bars_1m shard in the same directory; QM run must not collide with it. - let eod_sentinel = b"sentinel-eod-bars-1m-shard\n".to_vec(); - fs::write(out.join("bars_1m.shard-00.ilp"), &eod_sentinel).expect("write eod sentinel"); - - let first = run_bin(&bin_args(&fx, &out, "1750000000000000", &[])); - assert!( - first.status.success(), - "QM run should coexist with bars_1m.shard-00.ilp; stderr:\n{}", - String::from_utf8_lossy(&first.stderr) - ); - let before = read_dir_files(&out); - assert_eq!( - before.get("bars_1m.shard-00.ilp"), - Some(&eod_sentinel), - "co-located EOD shard must remain untouched" - ); - assert!(before.contains_key("bars_1m_qm.shard-00.ilp")); - assert!(before.contains_key("bars_1m_qm.shard-01.ilp")); - - // Second run with different known_at must refuse to overwrite existing bars_1m_qm shards. - let second = run_bin(&bin_args(&fx, &out, "1760000000000000", &[])); - assert!( - !second.status.success(), - "second run into populated --out must fail" - ); - assert!(second.stdout.is_empty(), "no success report expected"); - let stderr = String::from_utf8_lossy(&second.stderr); - assert_eq!(stderr.lines().count(), 1, "single-line stderr expected: {stderr}"); - assert!(stderr.starts_with("error:"), "stderr: {stderr}"); - assert_eq!( - read_dir_files(&out), - before, - "existing shards must be untouched and no staging files left" - ); -} - -#[test] -fn curate_qm_bars_1m_binary_supports_custom_mapping_source() { - let tmp = TempDir::new("custom-source"); - let (fx, _) = write_qm_fixture(tmp.path(), "qm_alt"); - let out = tmp.path().join("out"); - - let output = run_bin(&bin_args( - &fx, - &out, - "1750000000000000", - &["--mapping-source=qm_alt"], - )); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!(output.status.success(), "stderr:\n{stderr}"); - assert!(stderr.is_empty()); - - let rows: Vec = read_dir_files(&out) - .values() - .flat_map(|bytes| decode_rows(bytes)) - .collect(); - assert_eq!(rows.len(), 3, "custom --mapping-source should map all 3 rows"); -} - -#[test] -fn curate_qm_bars_1m_binary_parse_error_prints_usage_hides_secret_and_writes_nothing() { - let tmp = TempDir::new("parse-error"); - let (fx, _) = write_qm_fixture(tmp.path(), DEFAULT_QM_BARS_1M_MAPPING_SOURCE); - let out = tmp.path().join("out"); - - let secret = "--mongo-uri=mongodb://user:s3cr3t_pw@localhost:27017/stock"; - let output = run_bin(&bin_args(&fx, &out, "1750000000000000", &[secret])); - assert!(!output.status.success()); - assert!(output.stdout.is_empty()); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!(stderr.contains("file mode only"), "stderr: {stderr}"); - assert!( - stderr.contains("curate-qm-bars-1m --qm-intraday"), - "usage expected: {stderr}" - ); - assert!(!stderr.contains("s3cr3t_pw"), "secret leaked: {stderr}"); - assert!(!out.exists(), "parse failure must not create --out"); - - // Missing --known-at-micros: no clock fallback, nothing written. - let mut argv = bin_args(&fx, &out, "1", &[]); - argv.truncate(argv.len() - 2); - let output = run_bin(&argv); - assert!(!output.status.success()); - assert!(String::from_utf8_lossy(&output.stderr) - .contains("missing required flag '--known-at-micros'")); - assert!(!out.exists()); -} - -#[test] -fn curate_qm_bars_1m_binary_applies_date_effective_mapping_and_reports_dropped_unmapped() { - let tmp = TempDir::new("pit-mapping"); - // "REUSE" maps to listing 101 through 2024-06-10 and to listing 202 from 2024-06-11; - // "GHOST" has no mapping row and must be dropped (never assigned a listing). - let mapping = tmp.path().join("provider_mapping.tsv"); - fs::write( - &mapping, - "qm\tREUSE\t2024-06-01\t2024-06-10\t101\n\ - qm\tREUSE\t2024-06-11\t\t202\n", - ) - .expect("write provider_mapping.tsv"); - let intraday = tmp.path().join("qmIntraday.bson"); - let ts_old = et_ts_millis(2024, 6, 10, 10, 30); - let ts_new = et_ts_millis(2024, 6, 11, 10, 30); - fs::write( - &intraday, - concat_docs(&[ - make_qm_intraday_doc("REUSE", ts_old, 50.0, 51.0, 49.0, 50.5, 1_000.0), - make_qm_intraday_doc("REUSE", ts_new, 60.0, 61.0, 59.0, 60.5, 2_000.0), - make_qm_intraday_doc("GHOST", ts_new, 1.0, 1.0, 1.0, 1.0, 10.0), - ]), - ) - .expect("write qmIntraday.bson"); - let fx = Fixture { intraday, mapping }; - let out = tmp.path().join("out"); - - let output = run_bin(&bin_args(&fx, &out, "1718236800000000", &[])); - let stdout = String::from_utf8_lossy(&output.stdout); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!(output.status.success(), "stderr:\n{stderr}"); - assert!(stderr.is_empty(), "stderr:\n{stderr}"); - assert!( - stdout.contains("dropped_unmapped=1"), - "expected one unmapped row reported:\n{stdout}" - ); - assert!(stdout.contains("rows_written=2"), "stdout:\n{stdout}"); - - let mut rows: Vec = read_dir_files(&out) - .values() - .flat_map(|bytes| decode_rows(bytes)) - .collect(); - rows.sort_by_key(|r| r.ts); - assert_eq!(rows.len(), 2); - assert_eq!((rows[0].listing_id, rows[0].ts), (101, ts_old * 1_000)); - assert_eq!((rows[1].listing_id, rows[1].ts), (202, ts_new * 1_000)); - assert_eq!(rows[1].open.to_bits(), 60.0_f64.to_bits()); - assert!(rows.iter().all(|r| r.known_at == 1_718_236_800_000_000)); - - // Reported per-shard counts must sum to the rows actually written in the shard files. - let per_shard_line = stdout - .lines() - .find(|l| l.contains("per_shard_rows=")) - .expect("per_shard_rows in report"); - let per_shard_sum: usize = per_shard_line - .split("per_shard_rows=") - .nth(1) - .unwrap() - .trim() - .split(',') - .map(|kv| kv.split_once('=').unwrap().1.parse::().unwrap()) - .sum(); - assert_eq!(per_shard_sum, rows.len()); -} diff --git a/tools/curate-etl/tests/curate_shorts.rs b/tools/curate-etl/tests/curate_shorts.rs deleted file mode 100644 index 5b2eeca8..00000000 --- a/tools/curate-etl/tests/curate_shorts.rs +++ /dev/null @@ -1,538 +0,0 @@ -//! End-to-end binary integration tests for `curate-etl curate-shorts` (`M1.2ad`). - -use std::fs::{self, File}; -use std::io::Write; -use std::path::{Path, PathBuf}; -use std::process::{Command, Output}; -use std::sync::atomic::{AtomicU64, Ordering}; - -use bson::raw::{cstr, RawDocumentBuf}; -use bson::DateTime as BsonDateTime; -use curate_etl::{ymd_to_epoch_days, SHORTS_SOURCE_CEO}; -use parquet::basic::{LogicalType, Repetition, TimeUnit, Type as PhysicalType}; -use parquet::file::reader::{FileReader, SerializedFileReader}; -use parquet::record::RowAccessor; - -static TEST_DIR_SEQ: AtomicU64 = AtomicU64::new(0); - -struct TempDir { - path: PathBuf, -} - -impl TempDir { - fn new(tag: &str) -> Self { - let pid = std::process::id(); - let seq = TEST_DIR_SEQ.fetch_add(1, Ordering::Relaxed); - let path = std::env::temp_dir().join(format!("curate-etl-it-shorts-{tag}-{pid}-{seq}")); - let _ = fs::remove_dir_all(&path); - fs::create_dir_all(&path).expect("create integration test temp dir"); - Self { path } - } -} - -impl Drop for TempDir { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.path); - } -} - -fn run(args: &[&str]) -> Output { - Command::new(env!("CARGO_BIN_EXE_curate-etl")) - .args(args) - .output() - .expect("spawn curate-etl binary") -} - -fn stdout(o: &Output) -> String { - String::from_utf8_lossy(&o.stdout).into_owned() -} - -fn stderr(o: &Output) -> String { - String::from_utf8_lossy(&o.stderr).into_owned() -} - -fn write_bytes(path: &Path, bytes: &[u8]) { - let mut f = File::create(path).expect("create file"); - f.write_all(bytes).expect("write file"); -} - -fn day(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).expect("valid 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 make_doc( - sym: &str, - report_date: i32, - shares_short: f64, - net_change: Option, - pct_float: Option, -) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("symbol"), sym); - doc.append( - cstr!("timestamp"), - BsonDateTime::from_millis(i64::from(report_date) * 86_400_000), - ); - doc.append(cstr!("sharesShort"), shares_short); - if let Some(v) = net_change { - doc.append(cstr!("netChange"), v); - } - if let Some(v) = pct_float { - doc.append(cstr!("pctFloat"), v); - } - doc.into_bytes() -} - -#[derive(Debug, PartialEq)] -struct ReadRow { - listing_id: i32, - report_date: i32, - known_at: i64, - shares_short: f64, - net_change: Option, - pct_float: Option, - source: String, -} - -fn read_shorts_parquet(path: &Path) -> Vec { - let file = File::open(path).expect("open shorts/part.parquet"); - let reader = SerializedFileReader::new(file).expect("parse parquet"); - let schema = reader.metadata().file_metadata().schema(); - let fields = schema.get_fields(); - assert_eq!(fields.len(), 7, "expected 7 contract columns"); - - let expected_cols: [(&str, PhysicalType, Repetition, Option); 7] = [ - ("listing_id", PhysicalType::INT32, Repetition::REQUIRED, None), - ( - "report_date", - PhysicalType::INT32, - Repetition::REQUIRED, - Some(LogicalType::Date), - ), - ( - "known_at", - PhysicalType::INT64, - Repetition::REQUIRED, - Some(LogicalType::timestamp(true, TimeUnit::MICROS)), - ), - ( - "shares_short", - PhysicalType::DOUBLE, - Repetition::REQUIRED, - None, - ), - ( - "net_change", - PhysicalType::DOUBLE, - Repetition::OPTIONAL, - None, - ), - ( - "pct_float", - PhysicalType::DOUBLE, - Repetition::OPTIONAL, - None, - ), - ( - "source", - PhysicalType::BYTE_ARRAY, - Repetition::REQUIRED, - Some(LogicalType::String), - ), - ]; - - for (field, (name, phys, rep, logical)) in fields.iter().zip(expected_cols) { - assert_eq!(field.name(), name); - assert_eq!(field.get_physical_type(), phys); - assert_eq!(field.get_basic_info().repetition(), rep); - assert_eq!(field.get_basic_info().logical_type_ref(), logical.as_ref()); - } - - let mut out = Vec::new(); - let iter = reader.get_row_iter(None).expect("row iter"); - for row_res in iter { - let row = row_res.expect("row"); - let listing_id = row.get_int(0).expect("listing_id"); - let report_date = match row.get_column_iter().nth(1).expect("report_date").1 { - parquet::record::Field::Date(d) => *d, - other => panic!("expected Date for report_date, got {other:?}"), - }; - let known_at = row.get_timestamp_micros(2).expect("known_at"); - let shares_short = row.get_double(3).expect("shares_short"); - let net_change = row.get_double(4).ok(); - let pct_float = row.get_double(5).ok(); - let source = row.get_string(6).expect("source").to_owned(); - out.push(ReadRow { - listing_id, - report_date, - known_at, - shares_short, - net_change, - pct_float, - source, - }); - } - out -} - -#[test] -fn end_to_end_est_edt_holiday_known_at_sorting_and_determinism() { - let dir = TempDir::new("e2e"); - let map_path = dir.path.join("provider_mapping.tsv"); - let bson_fwd = dir.path.join("shorts_fwd.bson"); - let bson_rev = dir.path.join("shorts_rev.bson"); - let out_1 = dir.path.join("out_1"); - let out_2 = dir.path.join("out_2"); - let out_rev = dir.path.join("out_rev"); - - write_bytes( - &map_path, - concat!( - "ceo\tRY\t2015-01-01\t\t200\n", - "ceo\tTD\t2015-01-01\t\t100\n", - ) - .as_bytes(), - ); - - // Three cases: - // 1. EST: 2024-01-15 (Mon) + 4 TSX bdays -> 2024-01-19 (Fri) 17:00 EST = 22:00 UTC - // 2. EDT: 2024-07-15 (Mon) + 4 TSX bdays -> 2024-07-19 (Fri) 17:00 EDT = 21:00 UTC - // 3. Holiday crossing (Good Friday 2024-03-29): - // 2024-03-28 (Thu) + 4 TSX bdays -> Mon Apr 1 (1), Tue Apr 2 (2), Wed Apr 3 (3), Thu Apr 4 (4) - // = 2024-04-04 17:00 EDT = 21:00 UTC - // Deliberately emitted unsorted (listing 200 before 100, later dates before earlier) + 1 unmapped key. - let docs = vec![ - make_doc("RY", day(2024, 7, 15), 250_000.0, Some(5_000.0), Some(1.2)), - make_doc("TD", day(2024, 3, 28), 300_000.0, Some(-2_500.0), None), - make_doc("TD", day(2024, 1, 15), 180_000.0, None, Some(0.8)), - make_doc("UNMAPPED", day(2024, 1, 15), 10_000.0, None, None), - ]; - - let mut fwd_bytes = Vec::new(); - for d in &docs { - fwd_bytes.extend_from_slice(d); - } - write_bytes(&bson_fwd, &fwd_bytes); - - let mut rev_bytes = Vec::new(); - for d in docs.iter().rev() { - rev_bytes.extend_from_slice(d); - } - write_bytes(&bson_rev, &rev_bytes); - - let invoke = |bson: &Path, out: &Path| { - run(&[ - "curate-shorts", - "--ceo-shorts", - bson.to_str().unwrap(), - "--provider-mapping", - map_path.to_str().unwrap(), - "--out", - out.to_str().unwrap(), - "--shares-short-field", - "sharesShort", - "--net-change-field", - "netChange", - "--pct-float-field", - "pctFloat", - ]) - }; - - let res1 = invoke(&bson_fwd, &out_1); - assert!(res1.status.success(), "{}", stderr(&res1)); - assert!(stderr(&res1).is_empty(), "{}", stderr(&res1)); - let out_text = stdout(&res1); - assert!(out_text.contains("curate-etl curate-shorts"), "{out_text}"); - assert!(out_text.contains("dropped_unmapped=1"), "{out_text}"); - assert!(out_text.contains("rows_written=3"), "{out_text}"); - - let rows = read_shorts_parquet(&out_1.join("shorts/part.parquet")); - assert_eq!( - rows, - vec![ - ReadRow { - listing_id: 100, - report_date: day(2024, 1, 15), - known_at: utc_micros(2024, 1, 19, 22, 0, 0), // EST 17:00 = 22:00 UTC - shares_short: 180_000.0, - net_change: None, - pct_float: Some(0.8), - source: SHORTS_SOURCE_CEO.to_string(), - }, - ReadRow { - listing_id: 100, - report_date: day(2024, 3, 28), - known_at: utc_micros(2024, 4, 4, 21, 0, 0), // crosses Good Friday -> EDT 17:00 = 21:00 UTC - shares_short: 300_000.0, - net_change: Some(-2_500.0), - pct_float: None, - source: SHORTS_SOURCE_CEO.to_string(), - }, - ReadRow { - listing_id: 200, - report_date: day(2024, 7, 15), - known_at: utc_micros(2024, 7, 19, 21, 0, 0), // EDT 17:00 = 21:00 UTC - shares_short: 250_000.0, - net_change: Some(5_000.0), - pct_float: Some(1.2), - source: SHORTS_SOURCE_CEO.to_string(), - }, - ] - ); - - // Determinism: repeated run and reversed BSON order must produce byte-identical Parquet. - let res2 = invoke(&bson_fwd, &out_2); - assert!(res2.status.success(), "{}", stderr(&res2)); - let res_rev = invoke(&bson_rev, &out_rev); - assert!(res_rev.status.success(), "{}", stderr(&res_rev)); - - let bytes_1 = fs::read(out_1.join("shorts/part.parquet")).unwrap(); - let bytes_2 = fs::read(out_2.join("shorts/part.parquet")).unwrap(); - let bytes_rev = fs::read(out_rev.join("shorts/part.parquet")).unwrap(); - assert_eq!(bytes_1, bytes_2, "repeated run must be byte-identical"); - assert_eq!(bytes_1, bytes_rev, "reversed input must be byte-identical"); -} - -#[test] -fn failure_modes_exit_nonzero_without_usage_and_preserve_preexisting_parquet() { - let dir = TempDir::new("failures"); - let out_dir = dir.path.join("out"); - let shorts_dir = out_dir.join("shorts"); - fs::create_dir_all(&shorts_dir).unwrap(); - let sentinel_path = shorts_dir.join("part.parquet"); - let sentinel = b"PREEXISTING-SHORTS-SENTINEL".to_vec(); - write_bytes(&sentinel_path, &sentinel); - - let valid_map = dir.path.join("valid_map.tsv"); - write_bytes(&valid_map, b"ceo\tRY\t2020-01-01\t\t101\n"); - - let valid_bson = dir.path.join("valid.bson"); - write_bytes(&valid_bson, &make_doc("RY", day(2024, 3, 15), 100.0, None, None)); - - // 1. Missing input file - let missing = dir.path.join("missing.bson"); - let res = run(&[ - "curate-shorts", - "--ceo-shorts", - missing.to_str().unwrap(), - "--provider-mapping", - valid_map.to_str().unwrap(), - "--out", - out_dir.to_str().unwrap(), - "--shares-short-field", - "sharesShort", - ]); - assert!(!res.status.success()); - assert!(stdout(&res).is_empty()); - let err = stderr(&res); - assert_eq!(err.lines().count(), 1, "single-line stderr expected: {err}"); - assert!(!err.contains("Usage:"), "{err}"); - assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel); - - // 2. Truncated BSON - let trunc_bson = dir.path.join("trunc.bson"); - write_bytes(&trunc_bson, &[25, 0, 0, 0, 0x02, b'a']); - let res = run(&[ - "curate-shorts", - "--ceo-shorts", - trunc_bson.to_str().unwrap(), - "--provider-mapping", - valid_map.to_str().unwrap(), - "--out", - out_dir.to_str().unwrap(), - "--shares-short-field", - "sharesShort", - ]); - assert!(!res.status.success()); - let err = stderr(&res); - assert_eq!(err.lines().count(), 1, "single-line stderr expected: {err}"); - assert!(!err.contains("Usage:"), "{err}"); - assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel); - - // 3. Malformed mapping TSV - let bad_map = dir.path.join("bad_map.tsv"); - write_bytes(&bad_map, b"ceo\tRY\tbad-date\t\t101\n"); - let res = run(&[ - "curate-shorts", - "--ceo-shorts", - valid_bson.to_str().unwrap(), - "--provider-mapping", - bad_map.to_str().unwrap(), - "--out", - out_dir.to_str().unwrap(), - "--shares-short-field", - "sharesShort", - ]); - assert!(!res.status.success()); - let err = stderr(&res); - assert_eq!(err.lines().count(), 1, "single-line stderr expected: {err}"); - assert!(!err.contains("Usage:"), "{err}"); - assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel); - - // 4. All-unmapped keys -> exits 0, counts dropped_unmapped=1, preserves sentinel - let unmapped_bson = dir.path.join("unmapped.bson"); - write_bytes( - &unmapped_bson, - &make_doc("NO_SUCH_KEY", day(2024, 3, 15), 100.0, None, None), - ); - let res = run(&[ - "curate-shorts", - "--ceo-shorts", - unmapped_bson.to_str().unwrap(), - "--provider-mapping", - valid_map.to_str().unwrap(), - "--out", - out_dir.to_str().unwrap(), - "--shares-short-field", - "sharesShort", - ]); - assert!(res.status.success(), "{}", stderr(&res)); - let out = stdout(&res); - assert!(out.contains("dropped_unmapped=1"), "{out}"); - assert!(out.contains("rows_written=0"), "{out}"); - assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel); - - // 5. Corrupt UTF-8 in an unused text field of an otherwise valid, mapped report -> - // must fail closed with non-zero exit and preserve pre-existing shorts/part.parquet. - let mut unused_corrupt_doc = RawDocumentBuf::new(); - unused_corrupt_doc.append(cstr!("symbol"), "RY"); - unused_corrupt_doc.append( - cstr!("timestamp"), - BsonDateTime::from_millis(i64::from(day(2024, 3, 15)) * 86_400_000), - ); - unused_corrupt_doc.append(cstr!("sharesShort"), 100.0_f64); - unused_corrupt_doc.append(cstr!("unusedNote"), "CORRUPT"); - let mut unused_corrupt_bytes = unused_corrupt_doc.into_bytes(); - let pos = unused_corrupt_bytes - .windows(7) - .position(|w| w == b"CORRUPT") - .expect("locate CORRUPT marker"); - unused_corrupt_bytes[pos] = 0xff; - unused_corrupt_bytes[pos + 1] = 0xfe; - - let unused_corrupt_bson = dir.path.join("unused_corrupt.bson"); - write_bytes(&unused_corrupt_bson, &unused_corrupt_bytes); - let res = run(&[ - "curate-shorts", - "--ceo-shorts", - unused_corrupt_bson.to_str().unwrap(), - "--provider-mapping", - valid_map.to_str().unwrap(), - "--out", - out_dir.to_str().unwrap(), - "--shares-short-field", - "sharesShort", - ]); - assert!(!res.status.success(), "corrupt unused string must fail closed"); - assert!(stdout(&res).is_empty()); - let err = stderr(&res); - assert_eq!(err.lines().count(), 1, "single-line stderr expected: {err}"); - assert!(!err.contains("Usage:"), "{err}"); - assert_eq!( - fs::read(&sentinel_path).unwrap(), - sentinel, - "existing shorts/part.parquet must remain byte-identical" - ); - - // 6. Malformed element inside an unused embedded document -> must also fail closed. - let mut inner = RawDocumentBuf::new(); - inner.append(cstr!("k"), 7_i32); - let mut nested_corrupt_doc = RawDocumentBuf::new(); - nested_corrupt_doc.append(cstr!("symbol"), "RY"); - nested_corrupt_doc.append( - cstr!("timestamp"), - BsonDateTime::from_millis(i64::from(day(2024, 3, 15)) * 86_400_000), - ); - nested_corrupt_doc.append(cstr!("sharesShort"), 100.0_f64); - nested_corrupt_doc.append(cstr!("meta"), inner); - let mut nested_corrupt_bytes = nested_corrupt_doc.into_bytes(); - let k_pos = nested_corrupt_bytes - .windows(3) - .position(|w| w == [0x10, b'k', 0x00]) - .expect("locate nested int32 element"); - nested_corrupt_bytes[k_pos] = 0x7e; - - let nested_corrupt_bson = dir.path.join("nested_corrupt.bson"); - write_bytes(&nested_corrupt_bson, &nested_corrupt_bytes); - let res = run(&[ - "curate-shorts", - "--ceo-shorts", - nested_corrupt_bson.to_str().unwrap(), - "--provider-mapping", - valid_map.to_str().unwrap(), - "--out", - out_dir.to_str().unwrap(), - "--shares-short-field", - "sharesShort", - ]); - assert!(!res.status.success(), "corrupt embedded doc must fail closed"); - assert!(stdout(&res).is_empty()); - let err = stderr(&res); - assert_eq!(err.lines().count(), 1, "single-line stderr expected: {err}"); - assert!(!err.contains("Usage:"), "{err}"); - assert_eq!( - fs::read(&sentinel_path).unwrap(), - sentinel, - "existing shorts/part.parquet must remain byte-identical" - ); - - // 7. Damaged BSON array index in an unused array field ("0" -> "8") -> - // must fail closed with non-zero exit and preserve pre-existing shorts/part.parquet. - let mut arr = bson::RawArrayBuf::new(); - arr.push(10_i32); - arr.push(20_i32); - let mut arr_corrupt_doc = RawDocumentBuf::new(); - arr_corrupt_doc.append(cstr!("symbol"), "RY"); - arr_corrupt_doc.append( - cstr!("timestamp"), - BsonDateTime::from_millis(i64::from(day(2024, 3, 15)) * 86_400_000), - ); - arr_corrupt_doc.append(cstr!("sharesShort"), 100.0_f64); - arr_corrupt_doc.append(cstr!("tags"), arr); - let mut arr_corrupt_bytes = arr_corrupt_doc.into_bytes(); - let idx0_pos = arr_corrupt_bytes - .windows(3) - .position(|w| w == [0x10, b'0', 0x00]) - .expect("locate array index 0 int32 element"); - arr_corrupt_bytes[idx0_pos + 1] = b'8'; - - let arr_corrupt_bson = dir.path.join("array_index_corrupt.bson"); - write_bytes(&arr_corrupt_bson, &arr_corrupt_bytes); - let res = run(&[ - "curate-shorts", - "--ceo-shorts", - arr_corrupt_bson.to_str().unwrap(), - "--provider-mapping", - valid_map.to_str().unwrap(), - "--out", - out_dir.to_str().unwrap(), - "--shares-short-field", - "sharesShort", - ]); - assert!( - !res.status.success(), - "damaged BSON array index must fail closed" - ); - assert!(stdout(&res).is_empty()); - let err = stderr(&res); - assert_eq!(err.lines().count(), 1, "single-line stderr expected: {err}"); - assert!(!err.contains("Usage:"), "{err}"); - assert!( - err.contains("array index"), - "expected array index corruption detail in stderr, got: {err}" - ); - assert_eq!( - fs::read(&sentinel_path).unwrap(), - sentinel, - "existing shorts/part.parquet must remain byte-identical" - ); -} diff --git a/tools/curate-etl/tests/fixtures/curate-inputs/delistings.tsv b/tools/curate-etl/tests/fixtures/curate-inputs/delistings.tsv deleted file mode 100644 index cbf74348..00000000 --- a/tools/curate-etl/tests/fixtures/curate-inputs/delistings.tsv +++ /dev/null @@ -1,3 +0,0 @@ -DEL30 2023-06-15 7 -0.3 -SIVB 2023-03-28 4 SIVBQ -SIVBQ 2024-11-07 6 -1 diff --git a/tools/curate-etl/tests/fixtures/curate-inputs/listing_currencies.tsv b/tools/curate-etl/tests/fixtures/curate-inputs/listing_currencies.tsv deleted file mode 100644 index b52375e1..00000000 --- a/tools/curate-etl/tests/fixtures/curate-inputs/listing_currencies.tsv +++ /dev/null @@ -1,8 +0,0 @@ -1 USD -2 USD -3 USD -4 USD -5 USD -6 USD -7 USD -8 CAD diff --git a/tools/curate-etl/tests/fixtures/curate-inputs/provider_mapping.tsv b/tools/curate-etl/tests/fixtures/curate-inputs/provider_mapping.tsv deleted file mode 100644 index 480fde57..00000000 --- a/tools/curate-etl/tests/fixtures/curate-inputs/provider_mapping.tsv +++ /dev/null @@ -1,16 +0,0 @@ -eod AAPL.US 1980-12-12 1 -eod DEL30.US 2018-01-02 2023-06-15 7 -eod FB.US 2012-05-18 2022-06-08 2 -eod FB.US 2022-06-09 3 -eod SHOP.TO 2015-05-21 8 -eod SIVB.US 1988-01-04 2023-03-10 4 -eod SIVB.US 2023-03-20 5 -eod SIVBQ.US 2023-03-28 2024-11-07 6 -qm AAPL 1980-12-12 1 -qm DEL30 2018-01-02 2023-06-15 7 -qm FB 2012-05-18 2022-06-08 2 -qm FB 2022-06-09 3 -qm SHOP:CA 2015-05-21 8 -qm SIVB 1988-01-04 2023-03-10 4 -qm SIVB 2023-03-20 5 -qm SIVBQ 2023-03-28 2024-11-07 6 diff --git a/tools/curate-etl/tests/ilp_qa_contract.rs b/tools/curate-etl/tests/ilp_qa_contract.rs deleted file mode 100644 index 36f053ac..00000000 --- a/tools/curate-etl/tests/ilp_qa_contract.rs +++ /dev/null @@ -1,381 +0,0 @@ -//! QA contract tests for the QuestDB ILP v2 encoder and sharded writer (T-137 / M2.3c). -//! -//! Uses only the public crate API. Expected wire bytes are written out by hand (decimal -//! timestamps, hex IEEE-754 payloads) and shard routing is checked against an independently -//! written FNV-1a reference, so the encoder is not used as its own oracle. - -use std::io::{self, Write}; -use std::sync::{Arc, Mutex}; - -use curate_etl::{ - encode_bar_1m, encode_fx_1m, fnv1a_64, shard_for_fx_pair, shard_for_listing_id, Bar1mRow, - Fx1mRow, IlpEncodeError, IlpShardedWriter, IlpWriterError, IlpWriterOptions, - IntradaySession, BARS_1M_SOURCE_EOD, ILP_V2_DOUBLE_TYPE, TABLE_BARS_1M, TABLE_FX_1M, -}; - -fn bar(key: i32, ts: i64) -> Bar1mRow { - Bar1mRow { - key, - ts, - session_date: 20_000, - open: 1.0, - high: 2.0, - low: 0.5, - close: 1.5, - volume: 0.0, - session: IntradaySession::Rth, - source: BARS_1M_SOURCE_EOD, - } -} - -fn fx(pair: &'static str, ts: i64) -> Fx1mRow<'static> { - Fx1mRow { - pair, - ts, - open: 1.0, - high: 2.0, - low: 0.5, - close: 1.5, - source: "eod", - } -} - -type BarSetter = fn(&mut Bar1mRow, f64); -type FxSetter = fn(&mut Fx1mRow<'static>, f64); - -fn encoded_bar(row: &Bar1mRow, known_at: i64) -> Vec { - let mut v = Vec::new(); - encode_bar_1m(&mut v, row, known_at).unwrap(); - v -} - -/// Independent FNV-1a 64 reference (spec constants written inline). -fn ref_fnv1a(bytes: &[u8]) -> u64 { - bytes.iter().fold(0xcbf2_9ce4_8422_2325_u64, |h, &b| { - (h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3) - }) -} - -/// Sink that records every `write` call and flush, optionally failing a numbered write. -#[derive(Clone, Default)] -struct Rec { - writes: Arc>>>, - flushes: Arc>, - fail_write_call: Option, -} - -impl Rec { - fn writes(&self) -> Vec> { - self.writes.lock().unwrap().clone() - } - fn bytes(&self) -> Vec { - self.writes().concat() - } - fn flushes(&self) -> usize { - *self.flushes.lock().unwrap() - } -} - -impl Write for Rec { - fn write(&mut self, buf: &[u8]) -> io::Result { - let mut w = self.writes.lock().unwrap(); - if self.fail_write_call == Some(w.len()) { - return Err(io::Error::new(io::ErrorKind::BrokenPipe, "injected")); - } - w.push(buf.to_vec()); - Ok(buf.len()) - } - fn flush(&mut self) -> io::Result<()> { - *self.flushes.lock().unwrap() += 1; - Ok(()) - } -} - -#[test] -fn table_names_and_double_marker_match_contract() { - assert_eq!(TABLE_BARS_1M, "bars_1m"); - assert_eq!(TABLE_FX_1M, "fx_1m"); - assert_eq!(ILP_V2_DOUBLE_TYPE, 16); -} - -#[test] -fn fx_1m_golden_bytes_use_hand_written_little_endian_payloads() { - let row = Fx1mRow { - pair: "USD.CAD", - ts: 1_700_000_000_000_000, - open: 1.0, - high: 2.0, - low: 0.5, - close: -1.5, - source: "eod", - }; - let mut actual = Vec::new(); - encode_fx_1m(&mut actual, &row).unwrap(); - - let mut expected = b"fx_1m,pair=USD.CAD,source=eod ".to_vec(); - expected.extend_from_slice(b"open==\x10\x00\x00\x00\x00\x00\x00\xf0\x3f"); - expected.extend_from_slice(b",high==\x10\x00\x00\x00\x00\x00\x00\x00\x40"); - expected.extend_from_slice(b",low==\x10\x00\x00\x00\x00\x00\x00\xe0\x3f"); - expected.extend_from_slice(b",close==\x10\x00\x00\x00\x00\x00\x00\xf8\xbf"); - expected.extend_from_slice(b" 1700000000000000t\n"); - assert_eq!(actual, expected); -} - -#[test] -fn encoder_appends_to_existing_buffer_without_clearing_it() { - let mut buf = b"prior-line\n".to_vec(); - encode_bar_1m(&mut buf, &bar(1, 10), 20).unwrap(); - encode_fx_1m(&mut buf, &fx("EUR.USD", 30)).unwrap(); - - let mut expected = b"prior-line\n".to_vec(); - expected.extend(encoded_bar(&bar(1, 10), 20)); - let mut fx_line = Vec::new(); - encode_fx_1m(&mut fx_line, &fx("EUR.USD", 30)).unwrap(); - expected.extend(fx_line); - assert_eq!(buf, expected); -} - -#[test] -fn integer_extremes_encode_as_exact_decimal_without_overflow() { - // i32::MIN listing id, i64::MIN known_at, i64::MAX designated ts. - let row = bar(i32::MIN, i64::MAX); - let line = encoded_bar(&row, i64::MIN); - assert!(line.starts_with(b"bars_1m,listing_id=-2147483648,session=RTH,source=eod_unadj ")); - assert!(line.ends_with(b",known_at=-9223372036854775808t 9223372036854775807t\n")); - - // Zero designated ts and zero known_at are valid boundaries. - let zero = encoded_bar(&bar(0, 0), 0); - assert!(zero.starts_with(b"bars_1m,listing_id=0,")); - assert!(zero.ends_with(b",known_at=0t 0t\n")); - - let mut buf = Vec::new(); - encode_fx_1m(&mut buf, &fx("X", i64::MAX)).unwrap(); - assert!(buf.ends_with(b" 9223372036854775807t\n")); -} - -#[test] -fn extreme_finite_doubles_round_trip_bit_exactly() { - for v in [ - -0.0_f64, - f64::MIN_POSITIVE, - f64::from_bits(1), // smallest subnormal - f64::MAX, - f64::MIN, - f64::EPSILON, - ] { - let mut row = bar(5, 1); - row.low = v; - let line = encoded_bar(&row, 2); - let prefix = b",low==\x10"; - let pos = line.windows(prefix.len()).position(|w| w == prefix).unwrap() + prefix.len(); - let raw: [u8; 8] = line[pos..pos + 8].try_into().unwrap(); - assert_eq!(f64::from_le_bytes(raw).to_bits(), v.to_bits(), "value {v:e}"); - } -} - -#[test] -fn every_double_field_rejects_each_non_finite_value_atomically() { - let sentinel = b"keep".to_vec(); - let bar_fields: [(&str, BarSetter); 5] = [ - ("open", |r, v| r.open = v), - ("high", |r, v| r.high = v), - ("low", |r, v| r.low = v), - ("close", |r, v| r.close = v), - ("volume", |r, v| r.volume = v), - ]; - let fx_fields: [(&str, FxSetter); 4] = [ - ("open", |r, v| r.open = v), - ("high", |r, v| r.high = v), - ("low", |r, v| r.low = v), - ("close", |r, v| r.close = v), - ]; - for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { - for (name, set) in bar_fields { - let mut row = bar(1, 1); - set(&mut row, bad); - let mut buf = sentinel.clone(); - match encode_bar_1m(&mut buf, &row, 1) { - Err(IlpEncodeError::NonFiniteDouble { field, .. }) => assert_eq!(field, name), - other => panic!("bars_1m {name}={bad}: unexpected {other:?}"), - } - assert_eq!(buf, sentinel); - } - for (name, set) in fx_fields { - let mut row = fx("USD.CAD", 1); - set(&mut row, bad); - let mut buf = sentinel.clone(); - match encode_fx_1m(&mut buf, &row) { - Err(IlpEncodeError::NonFiniteDouble { field, .. }) => assert_eq!(field, name), - other => panic!("fx_1m {name}={bad}: unexpected {other:?}"), - } - assert_eq!(buf, sentinel); - } - } - - let mut buf = sentinel.clone(); - assert_eq!( - encode_fx_1m(&mut buf, &Fx1mRow { source: "", ..fx("USD.CAD", 1) }), - Err(IlpEncodeError::EmptySymbol { field: "source" }) - ); - assert_eq!(buf, sentinel); -} - -#[test] -fn routing_matches_independent_fnv1a_reference_and_published_vectors() { - // Published FNV-1a 64 test vectors. - assert_eq!(fnv1a_64(b""), 0xcbf2_9ce4_8422_2325); - assert_eq!(fnv1a_64(b"a"), 0xaf63_dc4c_8601_ec8c); - assert_eq!(fnv1a_64(b"foobar"), 0x8594_4171_f739_67e8); - - for shards in [1usize, 2, 3, 4, 7, 16] { - for id in [-1_000_000, -1, 0, 1, 42, 65_535, i32::MAX, i32::MIN] { - let expected = (ref_fnv1a(&id.to_le_bytes()) % shards as u64) as usize; - assert_eq!(shard_for_listing_id(id, shards), expected, "id {id} shards {shards}"); - } - for pair in ["USD.CAD", "EUR.USD", "a b", "caf\u{e9}"] { - let expected = (ref_fnv1a(pair.as_bytes()) % shards as u64) as usize; - assert_eq!(shard_for_fx_pair(pair, shards), expected); - } - } -} - -#[test] -fn fx_routing_hashes_raw_pair_not_escaped_wire_form() { - // A pair that needs escaping must route by its raw bytes. - let pair = "US D"; - let shards = 8; - let sinks: Vec = (0..shards).map(|_| Rec::default()).collect(); - let mut w = IlpShardedWriter::new(sinks.clone(), IlpWriterOptions::default()).unwrap(); - w.write_fx_1m(&fx(pair, 1)).unwrap(); - let stats = w.finish().unwrap(); - - let target = (ref_fnv1a(pair.as_bytes()) % shards as u64) as usize; - assert_eq!(stats.per_shard_rows[target], 1); - assert!(sinks[target].bytes().starts_with(b"fx_1m,pair=US\\ D,source=eod ")); -} - -#[test] -fn single_shard_writer_preserves_global_input_order() { - let sink = Rec::default(); - let mut w = IlpShardedWriter::new( - vec![sink.clone()], - IlpWriterOptions { max_batch_bytes: 1 << 20, max_batch_rows: 7 }, - ) - .unwrap(); - let mut expected = Vec::new(); - for i in 0..50i64 { - let row = bar((i % 9) as i32 - 4, 1_000 + i); - expected.extend(encoded_bar(&row, 2_000 + i)); - w.write_bar_1m(&row, 2_000 + i).unwrap(); - } - let stats = w.finish().unwrap(); - assert_eq!(sink.bytes(), expected); - assert_eq!(stats.rows, 50); - assert_eq!(stats.per_shard_rows, vec![50]); - assert_eq!(stats.flushes, 8); // 7 full batches of 7 + one remainder of 1 - assert_eq!(stats.bytes, expected.len()); -} - -#[test] -fn row_and_byte_limits_hit_on_same_row_produce_one_flush() { - let row = bar(3, 100); - let len = encoded_bar(&row, 200).len(); - let sink = Rec::default(); - let mut w = IlpShardedWriter::new( - vec![sink.clone()], - IlpWriterOptions { max_batch_bytes: 2 * len, max_batch_rows: 2 }, - ) - .unwrap(); - for _ in 0..4 { - w.write_bar_1m(&row, 200).unwrap(); - } - let stats = w.finish().unwrap(); - let writes = sink.writes(); - assert_eq!(writes.len(), 2); - assert!(writes.iter().all(|b| b.len() == 2 * len)); - assert_eq!(stats.flushes, 2); - assert_eq!(sink.flushes(), 1); -} - -#[test] -fn bytes_and_rows_are_counted_only_after_a_successful_batch() { - // Interleave two shards; shard holding the failing sink fails on its 2nd batch. - let a = (1..1000).find(|&id| shard_for_listing_id(id, 2) == 0).unwrap(); - let b = (1..1000).find(|&id| shard_for_listing_id(id, 2) == 1).unwrap(); - let ok = Rec::default(); - let bad = Rec { fail_write_call: Some(1), ..Rec::default() }; - let mut w = IlpShardedWriter::new( - vec![ok.clone(), bad.clone()], - IlpWriterOptions { max_batch_bytes: 1 << 20, max_batch_rows: 2 }, - ) - .unwrap(); - for i in 0..3 { - w.write_bar_1m(&bar(a, i), i).unwrap(); - } - w.write_bar_1m(&bar(b, 1), 1).unwrap(); - w.write_bar_1m(&bar(b, 2), 2).unwrap(); // first batch on shard 1 succeeds - w.write_bar_1m(&bar(b, 3), 3).unwrap(); - let err = w.write_bar_1m(&bar(b, 4), 4).unwrap_err(); - assert!(matches!(err, IlpWriterError::Io { shard: 1, .. })); - assert!(err.to_string().contains("shard 1"), "{err}"); - assert!(std::error::Error::source(&err).is_some()); - - // Healthy shard got exactly its one full batch; buffered remainder is never sent. - assert_eq!(ok.writes().len(), 1); - assert_eq!(bad.writes().len(), 1); - assert!(matches!(w.finish(), Err(IlpWriterError::Poisoned { failed_shard: 1 }))); - assert_eq!(ok.writes().len(), 1); - assert_eq!(ok.flushes(), 0); -} - -#[test] -fn encode_error_inside_writer_leaves_pending_batch_and_stats_intact() { - let sink = Rec::default(); - let mut w = IlpShardedWriter::new( - vec![sink.clone()], - IlpWriterOptions { max_batch_bytes: 1 << 20, max_batch_rows: 3 }, - ) - .unwrap(); - let good1 = bar(9, 1); - let good2 = bar(9, 2); - let good3 = bar(9, 3); - w.write_bar_1m(&good1, 10).unwrap(); - let mut bad = bar(9, -5); - bad.close = 3.0; - assert!(matches!( - w.write_bar_1m(&bad, 10), - Err(IlpWriterError::Encode(IlpEncodeError::NegativeTimestamp { field: "ts", value: -5 })) - )); - w.write_bar_1m(&good2, 10).unwrap(); - w.write_bar_1m(&good3, 10).unwrap(); // third valid row hits the row limit - let writes = sink.writes(); - assert_eq!(writes.len(), 1); - let mut expected = encoded_bar(&good1, 10); - expected.extend(encoded_bar(&good2, 10)); - expected.extend(encoded_bar(&good3, 10)); - assert_eq!(writes[0], expected); - - let stats = w.finish().unwrap(); - assert_eq!(stats.rows, 3); - assert_eq!(stats.bytes, expected.len()); -} - -#[test] -fn bars_and_fx_rows_can_share_a_writer_with_independent_routing() { - let shards = 4; - let sinks: Vec = (0..shards).map(|_| Rec::default()).collect(); - let mut w = IlpShardedWriter::new(sinks.clone(), IlpWriterOptions::default()).unwrap(); - w.write_bar_1m(&bar(42, 1), 2).unwrap(); - w.write_fx_1m(&fx("USD.CAD", 3)).unwrap(); - let stats = w.finish().unwrap(); - assert_eq!(stats.rows, 2); - - let bar_shard = shard_for_listing_id(42, shards); - let fx_shard = shard_for_fx_pair("USD.CAD", shards); - let total: usize = sinks.iter().map(|s| s.bytes().len()).sum(); - assert_eq!(stats.bytes, total); - let bar_bytes = sinks[bar_shard].bytes(); - let fx_bytes = sinks[fx_shard].bytes(); - assert!(bar_bytes.windows(8).any(|w| w == b"bars_1m,")); - assert!(fx_bytes.windows(6).any(|w| w == b"fx_1m,")); -} diff --git a/tools/curate-etl/tests/mongo_driver_cli_contract.rs b/tools/curate-etl/tests/mongo_driver_cli_contract.rs deleted file mode 100644 index 891c9bac..00000000 --- a/tools/curate-etl/tests/mongo_driver_cli_contract.rs +++ /dev/null @@ -1,407 +0,0 @@ -//! Offline contract tests for the sealed MongoDB driver adapter, CLI `--from-mongo` -//! wiring, and byte-identical file-vs-cursor Parquet parity. - -use std::fs::{self, File}; -use std::io::Write; -use std::path::PathBuf; -use std::sync::atomic::{AtomicU64, Ordering}; - -use bson::raw::{cstr, RawDocumentBuf}; -use curate_etl::cli::{parse_args, CliAction}; -use curate_etl::{ - assert_read_only_mongo_uri, open_read_only_mongo_from_env, open_read_only_mongo_uri, - run_curate_adj_factors_fenced, run_curate_bars_1d, run_curate_bars_1d_with_readers, - run_curate_fx_1d, run_curate_fx_1d_with_readers, AdjPointInTimeFence, CurateAdjFactorsArgs, - CurateBars1dArgs, CurateFx1dArgs, LocalHosts, MongoUriSource, RawBsonCursorReader, - ReadOnlyMongoClient, ReadOnlyPolicy, VecRawDocumentSource, DEFAULT_MONGO_BATCH_SIZE, - DEFAULT_MONGO_URI_ENV, -}; - -static COUNTER: AtomicU64 = AtomicU64::new(0); - -struct TempDir(PathBuf); - -impl TempDir { - fn new(tag: &str) -> Self { - let id = COUNTER.fetch_add(1, Ordering::Relaxed); - let dir = std::env::temp_dir().join(format!( - "curate-etl-mongo-cli-{tag}-{}-{id}", - std::process::id() - )); - let _ = fs::remove_dir_all(&dir); - fs::create_dir_all(&dir).expect("create temp dir"); - Self(dir) - } - - fn path(&self) -> &PathBuf { - &self.0 - } -} - -impl Drop for TempDir { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.0); - } -} - -fn s(items: &[&str]) -> Vec { - items.iter().map(|v| (*v).to_owned()).collect() -} - -fn make_eod_doc(code: &str, date: &str, open: f64, high: f64, low: f64, close: f64, volume: f64) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), code); - doc.append(cstr!("date"), date); - doc.append(cstr!("open"), open); - doc.append(cstr!("high"), high); - doc.append(cstr!("low"), low); - doc.append(cstr!("close"), close); - doc.append(cstr!("volume"), volume); - doc.into_bytes() -} - -fn make_split_doc(code: &str, date: &str, ratio: f64) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), code); - doc.append(cstr!("date"), date); - if ratio.is_finite() && ratio > 0.0 { - doc.append(cstr!("splitratio"), 1.0 / ratio); - doc.append(cstr!("forfactor"), 1.0_f64); - doc.append(cstr!("tofactor"), ratio); - } else { - doc.append(cstr!("splitratio"), ratio); - } - doc.into_bytes() -} - -fn make_div_doc(code: &str, date: &str, amount: f64, currency: &str) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), code); - doc.append(cstr!("date"), date); - doc.append(cstr!("amount"), amount); - doc.append(cstr!("currency"), currency); - doc.into_bytes() -} - -#[test] -fn read_only_mongo_client_rejects_missing_database_and_unsafe_uris() { - let local = LocalHosts::empty(); - let validated_no_db = assert_read_only_mongo_uri( - "mongodb://studio_stock_bot_read:SECRET_PW_99@localhost:27017", - &ReadOnlyPolicy::default(), - &local, - ) - .expect("valid host/user"); - let err = ReadOnlyMongoClient::connect(validated_no_db) - .expect_err("URI without database path must fail closed"); - let msg = err.to_string(); - assert!(msg.contains("database name"), "{msg}"); - assert!(!msg.contains("SECRET_PW_99"), "password leaked: {msg}"); - - let admin_err = open_read_only_mongo_uri( - "mongodb://trading_admin:ADMIN_PW_99@localhost:27017/stock", - &local, - ) - .expect_err("trading_admin must always be rejected"); - let admin_msg = admin_err.to_string(); - assert!(admin_msg.contains("trading_admin"), "{admin_msg}"); - assert!(!admin_msg.contains("ADMIN_PW_99"), "password leaked: {admin_msg}"); - - let unauth_err = open_read_only_mongo_uri("mongodb://localhost:27017/stock", &local) - .expect_err("unauthenticated QA URI must be rejected"); - assert!( - unauth_err.to_string().contains("credentials"), - "{unauth_err}" - ); - - let env_err = open_read_only_mongo_from_env("__STOCK_BOT_NONEXISTENT_ENV_VAR__", &local) - .expect_err("missing env var must fail closed"); - assert!(env_err.to_string().contains("not set"), "{env_err}"); -} - -#[test] -fn cli_parses_from_mongo_for_all_six_curate_commands_and_rejects_mixing() { - let action = parse_args(&s(&[ - "curate-bars-1d", - "--from-mongo", - "--with-qm-prices", - "--batch-size", - "2048", - "--limit", - "500", - "--date-gte", - "2005-01-01", - "--date-lt", - "2026-01-01", - "--provider-mapping", - "/tmp/pm.tsv", - "--listing-currencies", - "/tmp/lc.tsv", - "--out", - "/tmp/out", - "--threads", - "2", - ])) - .expect("valid curate-bars-1d --from-mongo"); - match action { - CliAction::CurateBars1dMongo(a) => { - assert_eq!( - a.mongo.uri_source, - MongoUriSource::EnvVar(DEFAULT_MONGO_URI_ENV.to_owned()) - ); - assert_eq!(a.mongo.batch_size, 2048); - assert_eq!(a.mongo.limit, Some(500)); - assert_eq!(a.mongo.date_gte.as_deref(), Some("2005-01-01")); - assert_eq!(a.mongo.date_lt.as_deref(), Some("2026-01-01")); - assert!(a.with_qm_prices); - assert_eq!(a.threads, 2); - } - other => panic!("unexpected action: {other:?}"), - } - - let mix_err = parse_args(&s(&[ - "curate-bars-1d", - "--from-mongo", - "--eod-prices", - "/tmp/eod.bson", - "--provider-mapping", - "/tmp/pm.tsv", - "--listing-currencies", - "/tmp/lc.tsv", - "--out", - "/tmp/out", - ])) - .expect_err("mixing --from-mongo with --eod-prices must fail"); - assert!(mix_err.contains("cannot combine"), "{mix_err}"); - - let stray_mongo_flag = parse_args(&s(&[ - "curate-fx-1d", - "--mongo-uri-env", - "MONGODB_READ_URI", - "--eod-prices", - "/tmp/eod.bson", - "--te-market-data", - "/tmp/te.bson", - "--out", - "/tmp/out", - ])) - .expect_err("--mongo-uri-env without --from-mongo must fail"); - assert!( - stray_mongo_flag.contains("require '--from-mongo'"), - "{stray_mongo_flag}" - ); - - let fx_action = parse_args(&s(&[ - "curate-fx-1d", - "--from-mongo", - "--mongo-uri-env", - "CUSTOM_MONGO_URI", - "--out", - "/tmp/out", - ])) - .expect("valid curate-fx-1d --from-mongo"); - match fx_action { - CliAction::CurateFx1dMongo(a) => { - assert_eq!( - a.mongo.uri_source, - MongoUriSource::EnvVar("CUSTOM_MONGO_URI".to_owned()) - ); - assert_eq!(a.mongo.batch_size, DEFAULT_MONGO_BATCH_SIZE); - assert_eq!(a.te_symbol, "USDCAD"); - } - other => panic!("unexpected action: {other:?}"), - } - - let adj_action = parse_args(&s(&[ - "curate-adj-factors", - "--from-mongo", - "--provider-mapping", - "/tmp/pm.tsv", - "--bars-1d", - "/tmp/bars_1d", - "--out", - "/tmp/out", - "--vault-cutoff", - "2025-10-01", - ])) - .expect("valid curate-adj-factors --from-mongo --vault-cutoff"); - match adj_action { - CliAction::CurateAdjFactorsMongo(a) => { - assert!(a.fence.is_some()); - assert!(a.fence.unwrap().vault_cutoff_micros.is_some()); - assert!(a.fence.unwrap().as_of_micros.is_none()); - } - other => panic!("unexpected action: {other:?}"), - } - - let ca_action = parse_args(&s(&[ - "curate-corporate-actions", - "--from-mongo", - "--provider-mapping", - "/tmp/pm.tsv", - "--out", - "/tmp/out", - ])) - .expect("valid curate-corporate-actions --from-mongo"); - assert!(matches!(ca_action, CliAction::CurateCorporateActionsMongo(_))); - - let shorts_action = parse_args(&s(&[ - "curate-shorts", - "--from-mongo", - "--provider-mapping", - "/tmp/pm.tsv", - "--out", - "/tmp/out", - "--shares-short-field", - "number_of_shares", - "--net-change-field", - "net_change", - ])) - .expect("valid curate-shorts --from-mongo"); - assert!(matches!(shorts_action, CliAction::CurateShortsMongo(_))); - - let events_action = parse_args(&s(&[ - "curate-events", - "--from-mongo", - "--provider-mapping", - "/tmp/pm.tsv", - "--out", - "/tmp/out", - "--filings-form-type-field", - "formdescription", - "--date-gte", - "2020-01-01", - ])) - .expect("valid curate-events --from-mongo"); - assert!(matches!(events_action, CliAction::CurateEventsMongo(_))); -} - -#[test] -fn file_mode_and_cursor_reader_mode_produce_byte_identical_parquet_outputs() { - let tmp = TempDir::new("parity"); - let pm_path = tmp.path().join("provider_mapping.tsv"); - let lc_path = tmp.path().join("listing_currencies.tsv"); - let eod_path = tmp.path().join("eod.bson"); - let splits_path = tmp.path().join("splits.bson"); - let divs_path = tmp.path().join("divs.bson"); - let te_path = tmp.path().join("te.bson"); - - fs::write( - &pm_path, - "eod\tNVDA.US\t2000-01-01\t\t101\nqm\tNVDA\t2000-01-01\t\t101\n", - ) - .expect("write pm"); - fs::write(&lc_path, "101\tUSD\n").expect("write lc"); - - let eod_docs = vec![ - make_eod_doc("NVDA.US", "2024-06-07", 1200.0, 1215.0, 1190.0, 1208.88, 412_390_000.0), - make_eod_doc("NVDA.US", "2024-06-10", 120.5, 123.0, 119.0, 121.79, 314_160_000.0), - make_eod_doc("CAD.FOREX", "2024-06-07", 1.368, 1.375, 1.365, 1.374, 0.0), - ]; - let split_docs = vec![make_split_doc("NVDA", "2024-06-10", 10.0)]; - let div_docs = vec![make_div_doc("NVDA", "2024-06-11", 0.01, "USD")]; - - { - let mut f = File::create(&eod_path).unwrap(); - for d in &eod_docs { - f.write_all(d).unwrap(); - } - let mut f = File::create(&splits_path).unwrap(); - for d in &split_docs { - f.write_all(d).unwrap(); - } - let mut f = File::create(&divs_path).unwrap(); - for d in &div_docs { - f.write_all(d).unwrap(); - } - let _ = File::create(&te_path).unwrap(); - } - - let out_file = tmp.path().join("out_file"); - let out_cursor = tmp.path().join("out_cursor"); - - let file_rep = run_curate_bars_1d(&CurateBars1dArgs { - eod_prices: eod_path.clone(), - qm_splits: splits_path.clone(), - qm_prices: None, - provider_mapping: pm_path.clone(), - listing_currencies: lc_path.clone(), - out_dir: out_file.clone(), - rel_tolerance: 0.01, - threads: 1, - }) - .expect("file curate-bars-1d"); - - let cursor_rep = run_curate_bars_1d_with_readers( - &pm_path, - &lc_path, - ( - &splits_path, - RawBsonCursorReader::new(VecRawDocumentSource::new(split_docs.clone())), - ), - ( - &eod_path, - RawBsonCursorReader::new(VecRawDocumentSource::new(eod_docs.clone())), - ), - None::<(PathBuf, std::io::Empty)>, - &out_cursor, - 0.01, - 1, - ) - .expect("cursor curate-bars-1d"); - - assert_eq!(file_rep.write_stats.rows_written, 2); - assert_eq!(cursor_rep.write_stats.rows_written, 2); - let file_bytes = fs::read(out_file.join("bars_1d/year=2024/part.parquet")).unwrap(); - let cursor_bytes = fs::read(out_cursor.join("bars_1d/year=2024/part.parquet")).unwrap(); - assert_eq!( - file_bytes, cursor_bytes, - "bars_1d Parquet bytes must be identical between file mode and RawBsonCursorReader mode" - ); - - // Verify fenced adj_factors snapshot via CLI helper - let fence = AdjPointInTimeFence { - as_of_micros: None, - vault_cutoff_micros: Some(1_759_276_800_000_000), // 2025-10-01T00:00:00Z - }; - let adj_rep = run_curate_adj_factors_fenced( - &CurateAdjFactorsArgs { - qm_splits: splits_path, - qm_dividends: divs_path, - provider_mapping: pm_path, - bars_1d_dir: out_file.join("bars_1d"), - out_dir: out_file.clone(), - }, - Some(fence), - ) - .expect("fenced adj_factors"); - assert_eq!(adj_rep.write_stats.rows_written, 2); - - // Verify fx_1d byte-identical parity - let fx_file = run_curate_fx_1d(&CurateFx1dArgs { - eod_prices: eod_path.clone(), - te_market_data: te_path.clone(), - te_symbol: "USDCAD".to_owned(), - out_dir: out_file.clone(), - }) - .expect("file fx_1d"); - let fx_cursor = run_curate_fx_1d_with_readers( - ( - &eod_path, - RawBsonCursorReader::new(VecRawDocumentSource::new(eod_docs)), - ), - ( - &te_path, - RawBsonCursorReader::new(VecRawDocumentSource::new(Vec::new())), - ), - "USDCAD", - &out_cursor, - ) - .expect("cursor fx_1d"); - assert_eq!(fx_file.write_stats.rows_written, 1); - assert_eq!(fx_cursor.write_stats.rows_written, 1); - assert_eq!( - fs::read(out_file.join("fx_1d/part.parquet")).unwrap(), - fs::read(out_cursor.join("fx_1d/part.parquet")).unwrap() - ); -} diff --git a/tools/curate-etl/tests/mongo_stream_qa_contract.rs b/tools/curate-etl/tests/mongo_stream_qa_contract.rs deleted file mode 100644 index 507a3271..00000000 --- a/tools/curate-etl/tests/mongo_stream_qa_contract.rs +++ /dev/null @@ -1,322 +0,0 @@ -//! QA contract tests for the public `mongo_stream` API (T-126 / M1.2al). -//! -//! Covers gaps left by `src/mongo_stream_tests.rs`, using only the public crate API and -//! in-memory sources (no MongoDB, no network): -//! - a source that fails exactly once is never polled again; the reader replays the same -//! sticky error (stashed-after-partial-write path and split-document path); -//! - an invalid frame after a valid one in the same `read()` is deferred, then sticky, and -//! never counted; -//! - seeded random documents + random read sizes: concatenated output is byte-identical to -//! the inputs, counters match, and `pending` never exceeds the largest single document; -//! - `RawBsonChunkReader` frames the adapter's output with the same chunks as a plain cursor; -//! - `with_max_doc_bytes` rejects ceilings below the BSON minimum; `into_inner` returns the -//! source at its current position; -//! - `build_filter_document` emits the exact key / `$gte` / `$lt` shape, and an empty spec -//! yields an empty filter; -//! - `MongoStreamError::redacted_source` (public path) hides the validated URI's password in -//! `Display` and `Debug` even when the raw URI is absent from the message. - -use std::io::{self, Cursor, Read}; - -use bson::raw::{cstr, RawDocumentBuf}; -use bson::{doc, Bson, DateTime}; -use curate_etl::{ - assert_read_only_mongo_uri, build_filter_document, FilterDateValue, LocalHosts, MongoDateRange, - MongoReadSpec, MongoStreamError, RawBsonChunkReader, RawBsonCursorReader, RawDocumentSource, - ReadOnlyPolicy, SliceRawDocumentSource, SourceCollection, VecRawDocumentSource, - MIN_BSON_DOC_BYTES, -}; - -struct SplitMix64(u64); - -impl SplitMix64 { - fn next_u64(&mut self) -> u64 { - self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); - let mut z = self.0; - z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); - z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); - z ^ (z >> 31) - } - - fn below(&mut self, n: u64) -> u64 { - self.next_u64() % n - } -} - -fn doc_with_payload(tag: u64, payload_len: usize) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("tag"), tag as i64); - doc.append(cstr!("payload"), "x".repeat(payload_len)); - doc.into_bytes() -} - -/// Yields `docs`, fails exactly once at `fail_at`, and counts every poll. -struct FailOnceSource { - docs: Vec>, - index: usize, - fail_at: usize, - failed: bool, - polls: usize, -} - -impl FailOnceSource { - fn new(docs: Vec>, fail_at: usize) -> Self { - Self { - docs, - index: 0, - fail_at, - failed: false, - polls: 0, - } - } -} - -impl RawDocumentSource for FailOnceSource { - fn next_raw_document(&mut self) -> Result, MongoStreamError> { - self.polls += 1; - if self.index == self.fail_at && !self.failed { - self.failed = true; - return Err(MongoStreamError::Source { - detail: "simulated cursor failure".to_owned(), - }); - } - if self.index >= self.docs.len() { - return Ok(None); - } - let doc = self.docs[self.index].as_slice(); - self.index += 1; - Ok(Some(doc)) - } -} - -fn downcast_stream_err(err: &io::Error) -> MongoStreamError { - err.get_ref() - .and_then(|e| e.downcast_ref::()) - .cloned() - .expect("io::Error must carry MongoStreamError") -} - -#[test] -fn fail_once_source_after_split_document_is_not_repolled_and_error_is_sticky() { - let doc0 = doc_with_payload(0, 40); - let docs = vec![doc0.clone(), doc_with_payload(1, 40)]; - let mut reader = RawBsonCursorReader::new(FailOnceSource::new(docs, 1)); - - let mut out = Vec::new(); - let mut buf = [0u8; 7]; - let err = loop { - match reader.read(&mut buf) { - Ok(0) => panic!("reader must not report EOF after a source failure"), - Ok(n) => out.extend_from_slice(&buf[..n]), - Err(err) => break err, - } - }; - assert_eq!( - out, doc0, - "split document must be fully delivered before the error" - ); - let first = downcast_stream_err(&err); - assert!(matches!(first, MongoStreamError::Source { .. })); - - for _ in 0..3 { - let again = reader.read(&mut buf).expect_err("error must stay sticky"); - assert_eq!(downcast_stream_err(&again), first); - } - assert_eq!(reader.docs_read(), 1); - assert_eq!(reader.bytes_read(), doc0.len() as u64); - assert_eq!( - reader.into_inner().polls, - 2, - "sticky error must be replayed without polling the source again" - ); -} - -#[test] -fn fail_once_source_after_whole_document_returns_partial_then_sticky_without_repoll() { - let doc0 = doc_with_payload(0, 10); - let mut reader = RawBsonCursorReader::new(FailOnceSource::new(vec![doc0.clone()], 1)); - - let mut buf = [0u8; 4096]; - let n = reader - .read(&mut buf) - .expect("first read returns the bytes already written"); - assert_eq!(&buf[..n], doc0.as_slice()); - - let err = reader - .read(&mut buf) - .expect_err("stashed error surfaces on the next read"); - let first = downcast_stream_err(&err); - let err2 = reader.read(&mut buf).expect_err("error stays sticky"); - assert_eq!(downcast_stream_err(&err2), first); - assert_eq!(reader.docs_read(), 1); - assert_eq!(reader.into_inner().polls, 2); -} - -#[test] -fn invalid_frame_after_valid_frame_is_deferred_sticky_and_uncounted() { - let good = doc_with_payload(7, 3); - let mut bad = doc_with_payload(8, 3); - let last = bad.len() - 1; - bad[last] = 0x01; - let docs: Vec<&[u8]> = vec![&good, &bad, &good]; - let mut reader = RawBsonCursorReader::new(SliceRawDocumentSource::new(&docs)); - - let mut buf = [0u8; 4096]; - let n = reader.read(&mut buf).expect("valid prefix delivered first"); - assert_eq!(&buf[..n], good.as_slice()); - - let err = reader.read(&mut buf).expect_err("bad frame surfaces next"); - match downcast_stream_err(&err) { - MongoStreamError::InvalidBsonFrame { doc_index, .. } => assert_eq!(doc_index, 1), - other => panic!("unexpected error: {other:?}"), - } - assert!(reader.read(&mut buf).is_err(), "error must stay sticky"); - assert_eq!(reader.docs_read(), 1); - assert_eq!(reader.bytes_read(), good.len() as u64); -} - -#[test] -fn seeded_random_documents_and_read_sizes_round_trip_byte_identically() { - let mut rng = SplitMix64(0x5EED_126A); - for _round in 0..40 { - let doc_count = rng.below(12) as usize; - let docs: Vec> = (0..doc_count) - .map(|i| doc_with_payload(i as u64, rng.below(600) as usize)) - .collect(); - let expected: Vec = docs.concat(); - let largest = docs.iter().map(Vec::len).max().unwrap_or(0); - - let mut reader = RawBsonCursorReader::new(VecRawDocumentSource::new(docs.clone())); - let mut out = Vec::new(); - loop { - let step = 1 + rng.below(700) as usize; - let mut buf = vec![0u8; step]; - let n = reader.read(&mut buf).expect("valid stream must read"); - if n == 0 { - break; - } - out.extend_from_slice(&buf[..n]); - assert!( - reader.pending_capacity() <= largest, - "pending {} exceeds largest doc {largest}", - reader.pending_capacity() - ); - } - assert_eq!(out, expected); - assert_eq!(reader.docs_read(), doc_count as u64); - assert_eq!(reader.bytes_read(), expected.len() as u64); - } -} - -#[test] -fn chunk_reader_frames_cursor_output_identically_to_plain_cursor() { - let docs: Vec> = (0..50) - .map(|i| doc_with_payload(i, (i as usize * 37) % 900)) - .collect(); - let concat = docs.concat(); - - let collect = |mut chunker: RawBsonChunkReader>| { - let mut chunks = Vec::new(); - while let Some(chunk) = chunker.next_chunk().expect("framing must succeed") { - chunks.push((chunk.start_offset, chunk.bytes.to_vec())); - } - chunks - }; - let plain = collect(RawBsonChunkReader::new(Box::new(Cursor::new( - concat.clone(), - )))); - let via_cursor = collect(RawBsonChunkReader::new(Box::new(RawBsonCursorReader::new( - VecRawDocumentSource::new(docs), - )))); - - let flatten = - |chunks: &[(u64, Vec)]| chunks.iter().flat_map(|c| c.1.clone()).collect::>(); - assert_eq!(flatten(&plain), concat); - assert_eq!(flatten(&via_cursor), concat); - assert_eq!(via_cursor.first().map(|c| c.0), Some(0)); -} - -#[test] -fn with_max_doc_bytes_rejects_ceiling_below_bson_minimum() { - let empty: [&[u8]; 0] = []; - let err = RawBsonCursorReader::with_max_doc_bytes( - SliceRawDocumentSource::new(&empty), - MIN_BSON_DOC_BYTES - 1, - ) - .err() - .expect("ceiling below minimum must be rejected"); - assert!(matches!(err, MongoStreamError::InvalidMaxDocBytes { .. })); - assert!(RawBsonCursorReader::with_max_doc_bytes( - SliceRawDocumentSource::new(&empty), - MIN_BSON_DOC_BYTES - ) - .is_ok()); -} - -#[test] -fn into_inner_returns_source_at_current_position() { - let docs = vec![doc_with_payload(0, 1), doc_with_payload(1, 1)]; - let mut reader = RawBsonCursorReader::new(VecRawDocumentSource::new(docs.clone())); - let mut buf = vec![0u8; docs[0].len()]; - reader.read_exact(&mut buf).expect("first doc"); - let mut source = reader.into_inner(); - let next = source - .next_raw_document() - .expect("source ok") - .map(<[u8]>::to_vec); - assert_eq!(next, Some(docs[1].clone())); - assert!(source.next_raw_document().expect("source ok").is_none()); -} - -#[test] -fn build_filter_document_emits_exact_key_and_range_shape() { - let spec = MongoReadSpec { - key_eq: Some("AAPL.US".to_owned()), - date_range: Some(MongoDateRange { - gte: Some(FilterDateValue::IsoString("2024-01-01".to_owned())), - lt: Some(FilterDateValue::IsoString("2025-01-01".to_owned())), - }), - ..MongoReadSpec::default() - }; - let filter = build_filter_document(SourceCollection::EodPrices, &spec).expect("valid spec"); - assert_eq!( - filter, - doc! { "eodSearchCode": "AAPL.US", "date": { "$gte": "2024-01-01", "$lt": "2025-01-01" } } - ); - - let ms_spec = MongoReadSpec { - date_range: Some(MongoDateRange { - gte: None, - lt: Some(FilterDateValue::BsonDateTimeMillis(1_700_000_000_000)), - }), - ..MongoReadSpec::default() - }; - let ms_filter = build_filter_document(SourceCollection::CeoShorts, &ms_spec).expect("valid"); - assert_eq!( - ms_filter.get("timestamp"), - Some(&Bson::Document( - doc! { "$lt": DateTime::from_millis(1_700_000_000_000) } - )) - ); - - let empty = build_filter_document(SourceCollection::TeMarketData, &MongoReadSpec::default()) - .expect("default spec is valid"); - assert!(empty.is_empty()); -} - -#[test] -fn redacted_source_hides_validated_password_even_without_full_uri_in_message() { - let sentinel = "QA_SENTINEL_PW_4242"; - let uri = assert_read_only_mongo_uri( - &format!("mongodb://studio_stock_bot_read:{sentinel}@localhost:27017/stock"), - &ReadOnlyPolicy::default(), - &LocalHosts::empty(), - ) - .expect("valid read-only URI"); - let raw = format!("SCRAM failure: password={sentinel}; retry with '{sentinel}'"); - let err = MongoStreamError::redacted_source(&raw, &uri); - for rendered in [format!("{err}"), format!("{err:?}")] { - assert!(!rendered.contains(sentinel), "leaked: {rendered}"); - assert!(rendered.contains("[REDACTED]")); - } -} diff --git a/tools/curate-etl/tests/posts_qa_contract.rs b/tools/curate-etl/tests/posts_qa_contract.rs deleted file mode 100644 index 06bb8a27..00000000 --- a/tools/curate-etl/tests/posts_qa_contract.rs +++ /dev/null @@ -1,332 +0,0 @@ -//! QA contract tests for the public `posts` builder (T-140 / M2.2b). -//! -//! Covers gaps left by the in-crate `posts_tests.rs`, checking against independent references -//! rather than the builder's own logic: -//! - seeded differential test against a naive reference (group by `spiel_id`, `max_by` winner -//! tuple, route, sort) on high-collision fixtures that force `known_at` ties; -//! - truncation test: every row visible at a cutoff in the full build is reproduced unchanged by a -//! build over only the inputs available before that cutoff; -//! - poison test: absurd future edits to existing posts never change what is visible before the -//! cutoff, except that the poisoned posts stop being visible (latest-only text, no recovery); -//! - an overflow row anywhere in the batch fails the whole build for every input order. - -use std::collections::{BTreeMap, BTreeSet}; - -use curate_etl::{build_posts, CeoPost, PostRow, PostsBuild, PostsError, POSTS_SOURCE_CEO}; - -/// Deterministic SplitMix64 PRNG (seeded; no wall clock). -struct Rng(u64); - -impl Rng { - fn next(&mut self) -> u64 { - self.0 = self.0.wrapping_add(0x9e37_79b9_7f4a_7c15); - let mut z = self.0; - z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); - z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); - z ^ (z >> 31) - } - - fn below(&mut self, n: u64) -> u64 { - self.next() % n - } - - fn shuffle(&mut self, v: &mut [T]) { - for i in (1..v.len()).rev() { - let j = self.below(i as u64 + 1) as usize; - v.swap(i, j); - } - } -} - -const BASE_MS: i64 = 1_735_000_000_000; - -/// High-collision fixture: few ids, few channels, coarse timestamps, so ties on `known_at` and on -/// several tie-break fields are frequent. Includes invalid rows. -fn collision_fixture(seed: u64, n: usize, ids: u64) -> Vec> { - let mut rng = Rng(seed); - let bots = [ - Some("1"), - Some(" 1"), - Some("0"), - Some(""), - None, - Some("yes"), - ]; - let users = [None, Some("u_a"), Some("u_b")]; - let texts = ["a", "b", "c"]; - (0..n) - .map(|_| { - let spiel_id = match rng.below(25) { - 0 => String::new(), - _ => format!("sp_{}", rng.below(ids)), - }; - let timestamp_ms = match rng.below(20) { - 0 => 0, - 1 => -5, - _ => BASE_MS + 1_000 * rng.below(4) as i64, - }; - let edited_ms = match rng.below(4) { - 0 => None, - 1 => Some(timestamp_ms), - 2 => Some(timestamp_ms - 1_000), - _ => Some(BASE_MS + 1_000 * rng.below(6) as i64), - }; - CeoPost { - key: format!("ch_{}", rng.below(3)), - spiel_id, - timestamp_ms, - edited_ms, - bot: bots[rng.below(bots.len() as u64) as usize].map(str::to_string), - user_id: users[rng.below(users.len() as u64) as usize].map(str::to_string), - text: texts[rng.below(texts.len() as u64) as usize].to_string(), - } - }) - .collect() -} - -/// Independent reference written from the task's rules, not from `posts.rs`. -fn reference(rows: &[CeoPost]) -> (Vec, Vec, usize, usize) { - let mut rejected = 0usize; - let mut groups: BTreeMap> = BTreeMap::new(); - for r in rows { - if r.spiel_id.is_empty() || r.timestamp_ms <= 0 { - rejected += 1; - continue; - } - let posted_at = r.timestamp_ms * 1_000; - let known_at = r - .edited_ms - .map_or(r.timestamp_ms, |e| e.max(r.timestamp_ms)) - * 1_000; - groups.entry(r.spiel_id.clone()).or_default().push(PostRow { - key: r.key.clone(), - spiel_id: r.spiel_id.clone(), - posted_at, - known_at, - is_bot: r.bot.as_deref().map(str::trim) == Some("1"), - is_edited: r.edited_ms.is_some(), - user_id: r.user_id.clone(), - text: r.text.clone(), - source: POSTS_SOURCE_CEO, - }); - } - let mut dropped = 0usize; - let (mut wire, mut retail) = (Vec::new(), Vec::new()); - for (_, group) in groups { - dropped += group.len() - 1; - let winner = group - .into_iter() - .max_by(|a, b| { - ( - a.known_at, - a.posted_at, - a.is_edited, - a.is_bot, - &a.key, - &a.user_id, - &a.text, - ) - .cmp(&( - b.known_at, - b.posted_at, - b.is_edited, - b.is_bot, - &b.key, - &b.user_id, - &b.text, - )) - }) - .unwrap(); - if winner.is_bot { - wire.push(winner); - } else { - retail.push(winner); - } - } - let order = |r: &PostRow| (r.key.clone(), r.known_at, r.spiel_id.clone()); - wire.sort_by_key(order); - retail.sort_by_key(order); - (wire, retail, dropped, rejected) -} - -#[test] -fn seeded_differential_matches_naive_reference_on_high_collision_fixtures() { - for seed in 0..40u64 { - let input = collision_fixture(0xC0FF_EE00 + seed, 120, 8); - let built = build_posts(input.clone()).expect("fixture has no overflow"); - let (wire, retail, dropped, rejected) = reference(&input); - - assert_eq!(built.newswire, wire, "seed {seed}: newswire mismatch"); - assert_eq!(built.retail, retail, "seed {seed}: retail mismatch"); - assert_eq!(built.stats.duplicates_dropped, dropped, "seed {seed}"); - assert_eq!(built.stats.rejected_invalid, rejected, "seed {seed}"); - assert_eq!(built.stats.input, input.len()); - assert_eq!( - built.stats.input, - built.stats.newswire - + built.stats.retail - + built.stats.duplicates_dropped - + built.stats.rejected_invalid - ); - let valid = input - .iter() - .filter(|r| !r.spiel_id.is_empty() && r.timestamp_ms > 0); - assert_eq!( - built.stats.edited, - valid.clone().filter(|r| r.edited_ms.is_some()).count() - ); - assert_eq!( - built.stats.edited_before_posted, - valid - .filter(|r| r.edited_ms.is_some_and(|e| e < r.timestamp_ms)) - .count() - ); - } -} - -/// Ordered projection of a `PostRow` (which is not `Ord`) for set comparisons. -type RowKey = (String, String, i64, i64, bool, bool, Option, String); - -fn row_key(r: &PostRow) -> RowKey { - ( - r.spiel_id.clone(), - r.key.clone(), - r.posted_at, - r.known_at, - r.is_bot, - r.is_edited, - r.user_id.clone(), - r.text.clone(), - ) -} - -fn visible(build: &PostsBuild, cutoff_us: i64) -> BTreeSet { - build - .newswire - .iter() - .chain(build.retail.iter()) - .filter(|r| r.known_at < cutoff_us) - .map(row_key) - .collect() -} - -fn known_at_us(r: &CeoPost) -> i64 { - r.edited_ms - .map_or(r.timestamp_ms, |e| e.max(r.timestamp_ms)) - * 1_000 -} - -#[test] -fn truncation_rows_visible_at_cutoff_are_reproduced_from_pre_cutoff_inputs_only() { - for seed in 0..20u64 { - let input = collision_fixture(0x7A0C_0000 + seed, 150, 60); - let full = build_posts(input.clone()).unwrap(); - assert!(!visible(&full, (BASE_MS + 2_000) * 1_000).is_empty()); - for step in 0..=6i64 { - let cutoff_us = (BASE_MS + 1_000 * step) * 1_000; - let truncated_input: Vec<_> = input - .iter() - .filter(|r| r.timestamp_ms > 0 && known_at_us(r) < cutoff_us) - .cloned() - .collect(); - let truncated = build_posts(truncated_input).unwrap(); - - let full_visible = visible(&full, cutoff_us); - let trunc_visible = visible(&truncated, cutoff_us); - // Every row the full build exposes before the cutoff must be derivable from data - // available before the cutoff (no future-dependent winner selection). - assert!( - full_visible.is_subset(&trunc_visible), - "seed {seed} cutoff step {step}: full build exposes rows not reproducible pre-cutoff: {:?}", - full_visible.difference(&trunc_visible).collect::>() - ); - // Truncated build never exposes anything at/after the cutoff. - assert!(truncated - .newswire - .iter() - .chain(truncated.retail.iter()) - .all(|r| r.known_at < cutoff_us)); - } - } -} - -#[test] -fn poison_future_edits_never_change_pre_cutoff_view_except_hiding_poisoned_ids() { - let cutoff_us = (BASE_MS + 3_000) * 1_000; - let far_future_ms = BASE_MS + 10 * 365 * 86_400_000; - for seed in 0..20u64 { - let input = collision_fixture(0x9015_0000 + seed, 120, 60); - let base = build_posts(input.clone()).unwrap(); - let base_visible = visible(&base, cutoff_us); - - // Poison half of the ids that are visible before the cutoff with an absurd future edit - // flagged as a wire release in a different channel. - let poisoned: BTreeSet = base_visible - .iter() - .map(|r| r.0.clone()) - .enumerate() - .filter(|(i, _)| i % 2 == 0) - .map(|(_, id)| id) - .collect(); - assert!( - !poisoned.is_empty(), - "seed {seed}: fixture must expose pre-cutoff rows" - ); - let mut poisoned_input = input.clone(); - for id in &poisoned { - poisoned_input.push(CeoPost { - key: "ch_poison".to_string(), - spiel_id: id.clone(), - timestamp_ms: BASE_MS, - edited_ms: Some(far_future_ms), - bot: Some("1".to_string()), - user_id: Some("poison".to_string()), - text: "POISON: future restatement".to_string(), - }); - } - let mut rng = Rng(seed); - rng.shuffle(&mut poisoned_input); - let after = build_posts(poisoned_input).unwrap(); - let after_visible = visible(&after, cutoff_us); - - let expected: BTreeSet<_> = base_visible - .iter() - .filter(|r| !poisoned.contains(&r.0)) - .cloned() - .collect(); - assert_eq!(after_visible, expected, "seed {seed}"); - assert!(after_visible.iter().all(|r| !r.7.starts_with("POISON"))); - assert_eq!( - after.stats.duplicates_dropped, - base.stats.duplicates_dropped + poisoned.len() - ); - } -} - -#[test] -fn overflow_row_anywhere_fails_build_for_every_input_order() { - let mut input = collision_fixture(0x0F10_0001, 40, 8); - input.push(CeoPost { - key: "ch_x".to_string(), - spiel_id: "sp_overflow".to_string(), - timestamp_ms: BASE_MS, - edited_ms: Some(i64::MAX / 1_000 + 1), - bot: None, - user_id: None, - text: "overflow".to_string(), - }); - let mut rng = Rng(7); - for _ in 0..16 { - let mut shuffled = input.clone(); - rng.shuffle(&mut shuffled); - let err = build_posts(shuffled).expect_err("overflow must fail the build"); - assert_eq!( - err, - PostsError::TimestampOverflow { - spiel_id: "sp_overflow".to_string(), - field: "edited_ms", - timestamp_ms: i64::MAX / 1_000 + 1, - } - ); - } -} diff --git a/tools/curate-etl/tests/run_curate_adj_qa_contract.rs b/tools/curate-etl/tests/run_curate_adj_qa_contract.rs deleted file mode 100644 index 0a96ca02..00000000 --- a/tools/curate-etl/tests/run_curate_adj_qa_contract.rs +++ /dev/null @@ -1,526 +0,0 @@ -//! QA contract tests for the `curate-adj-factors` command (T-111 / M1.2aa). -//! -//! Covers gaps left by `src/run_curate_adj_tests.rs` and `tests/cli.rs`, checking the runner -//! against independent references instead of its own logic: -//! - seeded randomized differential: file -> Parquet command output vs a naive in-test linear-scan -//! `prev_close` reference (last bar with `session_date < ex_date` for the listing the code maps -//! to on `ex_date`) feeding the public `curate_adj_factors` stage directly; -//! - `bars_1d` partition discovery: non-`year=YYYY` entries are ignored, a `year=YYYY` directory -//! without `part.parquet` fails closed and leaves the previous snapshot byte-identical; -//! - rerun semantics: the same inputs republish a byte-identical snapshot, and new inputs replace -//! it in place; -//! - binary runtime failure: single-line stderr naming the path, exit code 1, `--out` not created. - -use std::borrow::Cow; -use std::collections::BTreeSet; -use std::fs::{self, File}; -use std::io::Write; -use std::path::{Path, PathBuf}; -use std::process::Command; -use std::sync::atomic::{AtomicU64, Ordering}; - -use bson::raw::{cstr, RawDocumentBuf}; - -use curate_etl::{ - curate_adj_factors, epoch_days_to_ymd, et_session_close_utc_micros, read_adj_factors_dataset, - run_curate_adj_factors, write_bars_1d_dataset, ymd_to_epoch_days, AdjFactorsParquetRow, - Bars1dParquetRow, Bars1dWriteOptions, CurateAdjFactorsArgs, CurateAdjFactorsRunReport, - DividendEvent, ProviderMappingRow, ProviderMappingTable, SplitEvent, -}; - -static SEQ: AtomicU64 = AtomicU64::new(0); - -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-run-adj-qa-{tag}-{}-{seq}", - std::process::id() - )); - let _ = fs::remove_dir_all(&path); - fs::create_dir_all(&path).expect("create temp dir"); - Self(path) - } - - fn join(&self, name: &str) -> PathBuf { - self.0.join(name) - } -} - -impl Drop for TempDir { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.0); - } -} - -/// Deterministic SplitMix64 (fixed seed per test). -struct Rng(u64); - -impl Rng { - fn next_u64(&mut self) -> u64 { - self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); - let mut z = self.0; - z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); - z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); - z ^ (z >> 31) - } - - fn below(&mut self, n: u64) -> u64 { - self.next_u64() % n - } -} - -fn write_file(path: &Path, bytes: &[u8]) { - if let Some(parent) = path.parent() { - fs::create_dir_all(parent).expect("create parent dirs"); - } - File::create(path) - .and_then(|mut f| f.write_all(bytes)) - .expect("write fixture"); -} - -fn ymd_string(days: i32) -> String { - let (y, m, d) = epoch_days_to_ymd(days); - format!("{y:04}-{m:02}-{d:02}") -} - -fn days(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).expect("valid date") -} - -fn is_weekday(day: i32) -> bool { - // 1970-01-01 was a Thursday. - !matches!((day + 4).rem_euclid(7), 0 | 6) -} - -fn split_doc(code: &str, date: &str, ratio: f64) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), code); - doc.append(cstr!("date"), date); - if ratio.is_finite() && ratio > 0.0 { - doc.append(cstr!("splitratio"), 1.0 / ratio); - doc.append(cstr!("forfactor"), 1.0_f64); - doc.append(cstr!("tofactor"), ratio); - } else { - doc.append(cstr!("splitratio"), ratio); - } - doc.into_bytes() -} - -fn div_doc(code: &str, date: &str, cash: f64, currency: &str) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), code); - doc.append(cstr!("date"), date); - doc.append(cstr!("amount"), cash); - doc.append(cstr!("currency"), currency); - doc.append(cstr!("usdFxRate"), 1_i32); - doc.into_bytes() -} - -fn bar(listing_id: i32, session_date: i32, close: f64, currency: &'static str) -> Bars1dParquetRow { - let ts_micros = et_session_close_utc_micros(session_date).expect("valid ts"); - Bars1dParquetRow { - listing_id, - ts_micros, - session_date, - open: close, - high: close + 1.0, - low: close - 1.0, - close, - volume: 10_000.0, - vwap: None, - currency: Cow::Borrowed(currency), - source: Cow::Borrowed("eod"), - known_at_micros: ts_micros, - } -} - -fn assert_rows_bit_eq(got: &[AdjFactorsParquetRow], expected: &[AdjFactorsParquetRow]) { - assert_eq!(got.len(), expected.len(), "row count"); - for (i, (a, b)) in got.iter().zip(expected).enumerate() { - assert_eq!(a.listing_id, b.listing_id, "row {i} listing_id"); - assert_eq!(a.ex_date, b.ex_date, "row {i} ex_date"); - assert_eq!( - a.split_factor.to_bits(), - b.split_factor.to_bits(), - "row {i} split_factor" - ); - assert_eq!( - a.div_cash.to_bits(), - b.div_cash.to_bits(), - "row {i} div_cash" - ); - assert_eq!(a.div_currency, b.div_currency, "row {i} div_currency"); - assert_eq!( - a.cum_split_factor.to_bits(), - b.cum_split_factor.to_bits(), - "row {i} cum_split_factor" - ); - assert_eq!( - a.cum_total_factor.to_bits(), - b.cum_total_factor.to_bits(), - "row {i} cum_total_factor" - ); - assert_eq!( - a.known_at_micros, b.known_at_micros, - "row {i} known_at_micros" - ); - } -} - -fn assert_conservation(r: &CurateAdjFactorsRunReport) { - assert_eq!(r.splits_docs_framed as usize, r.splits_decode.docs_in); - assert_eq!( - r.splits_decode.docs_in, - r.splits_decode.rejected_total() - + r.curate_stats.splits_dropped_unmapped - + r.curate_stats.splits_dropped_fenced - + r.curate_stats.splits_collision_collapsed - + r.curate_stats.builder.split_events_in - ); - assert_eq!(r.dividends_docs_framed as usize, r.dividends_decode.docs_in); - assert_eq!( - r.dividends_decode.docs_in, - r.dividends_decode.rejected_total() - + r.curate_stats.dividends_dropped_unmapped - + r.curate_stats.dividends_dropped_fenced - + r.curate_stats.dividends_collision_collapsed - + r.curate_stats.builder.dividend_events_in - ); - assert_eq!( - r.dividends_decode.decoded, - r.dividends_with_prev_close - + r.dividends_without_prev_close - + r.curate_stats.dividends_dropped_unmapped - ); -} - -fn currency_of(listing_id: i32) -> &'static str { - if listing_id % 2 == 0 { - "CAD" - } else { - "USD" - } -} - -fn mapping_tsv(rows: &[ProviderMappingRow]) -> String { - rows.iter() - .map(|r| { - format!( - "{}\t{}\t{}\t{}\t{}\n", - r.source, - r.source_id, - ymd_string(r.valid_from), - r.valid_to.map(ymd_string).unwrap_or_default(), - r.listing_id - ) - }) - .collect() -} - -#[test] -fn seeded_differential_prev_close_matches_naive_linear_scan_reference() { - let tmp = TempDir::new("diff"); - let mut rng = Rng(0x0A0D_1111_C0DE_F00D); - - // Listings 1..=10 each own code `Q{lid}:US` open-ended; `REUSE:US` maps to 11 during 2019 - // and to 12 from 2020-06-01 (gap 2020-01-01..2020-05-31 is unmapped). - let mut mapping_rows: Vec = (1..=10) - .map(|lid| ProviderMappingRow { - source: "qm".to_string(), - source_id: format!("Q{lid}:US"), - valid_from: days(2015, 1, 1), - valid_to: None, - listing_id: lid, - }) - .collect(); - mapping_rows.push(ProviderMappingRow { - source: "qm".to_string(), - source_id: "REUSE:US".to_string(), - valid_from: days(2019, 1, 1), - valid_to: Some(days(2019, 12, 31)), - listing_id: 11, - }); - mapping_rows.push(ProviderMappingRow { - source: "qm".to_string(), - source_id: "REUSE:US".to_string(), - valid_from: days(2020, 6, 1), - valid_to: None, - listing_id: 12, - }); - let map_path = tmp.join("provider_mapping.tsv"); - write_file(&map_path, mapping_tsv(&mapping_rows).as_bytes()); - let mapping = ProviderMappingTable::from_rows(mapping_rows.clone()).expect("mapping"); - - // Bars: random weekday sessions in 2018..=2021 per listing (listing 7 has no bars at all). - let bar_lo = days(2018, 1, 1); - let bar_hi = days(2021, 12, 31); - let mut bars: Vec<(i32, i32, f64)> = Vec::new(); - for lid in 1..=12 { - if lid == 7 { - continue; - } - let mut dates = BTreeSet::new(); - while dates.len() < 60 { - let d = bar_lo + rng.below((bar_hi - bar_lo + 1) as u64) as i32; - if is_weekday(d) { - dates.insert(d); - } - } - for d in dates { - let close = 20.0 + (rng.below(18_000) as f64) / 100.0; - bars.push((lid, d, close)); - } - } - let bar_rows: Vec = bars - .iter() - .map(|&(lid, d, close)| bar(lid, d, close, currency_of(lid))) - .collect(); - let bars_root = tmp.join("bars_root"); - write_bars_1d_dataset(&bars_root, &bar_rows, Bars1dWriteOptions::default()).expect("bars"); - - // Dividends + splits: distinct dates per code in 2017..=2022; ~35% land exactly on a bar date - // of the mapped listing so the strict `<` boundary is exercised many times. - let ev_lo = days(2017, 1, 1); - let ev_hi = days(2022, 12, 31); - let mut codes: Vec = (1..=10).map(|lid| format!("Q{lid}:US")).collect(); - codes.push("REUSE:US".to_string()); - codes.push("NOPE:US".to_string()); - - let mut div_events: Vec<(String, DividendEvent)> = Vec::new(); - let mut split_events: Vec<(String, SplitEvent)> = Vec::new(); - let mut div_bytes = Vec::new(); - let mut split_bytes = Vec::new(); - let mut on_bar_date_hits = 0usize; - - for code in &codes { - // Bar dates owned by the listing this code maps to on that same date. - let own_bar_dates: Vec = bars - .iter() - .filter(|&&(bl, bd, _)| mapping.resolve("qm", code, bd) == Some(bl)) - .map(|&(_, bd, _)| bd) - .collect(); - let mut used = BTreeSet::new(); - for _ in 0..40 { - let ex_date = if !own_bar_dates.is_empty() && rng.below(100) < 35 { - on_bar_date_hits += 1; - own_bar_dates[rng.below(own_bar_dates.len() as u64) as usize] - } else { - ev_lo + rng.below((ev_hi - ev_lo + 1) as u64) as i32 - }; - if !used.insert(ex_date) { - continue; - } - let lid = mapping.resolve("qm", code, ex_date); - let natural_ccy = lid.map(currency_of).unwrap_or("USD"); - let ccy = if rng.below(10) == 0 { - if natural_ccy == "USD" { - "CAD" - } else { - "USD" - } - } else { - natural_ccy - }; - let cash = (1 + rng.below(150)) as f64 / 100.0; - - // Naive reference: linear scan for the max session_date < ex_date of the mapped listing. - let (prev_close, prev_ccy) = match lid { - Some(l) => bars - .iter() - .filter(|&&(bl, bd, _)| bl == l && bd < ex_date) - .max_by_key(|&&(_, bd, _)| bd) - .map(|&(_, _, c)| (Some(c), Some(currency_of(l).to_string()))) - .unwrap_or((None, None)), - None => (None, None), - }; - div_bytes.extend(div_doc(code, &ymd_string(ex_date), cash, ccy)); - div_events.push(( - code.clone(), - DividendEvent { - ex_date, - cash, - currency: ccy.to_string(), - prev_close, - prev_close_currency: prev_ccy, - }, - )); - - if rng.below(8) == 0 { - let ratio = [2.0, 3.0, 0.5, 1.0][rng.below(4) as usize]; - split_bytes.extend(split_doc(code, &ymd_string(ex_date), ratio)); - split_events.push((code.clone(), SplitEvent { ex_date, ratio })); - } - } - } - assert!( - on_bar_date_hits > 20, - "fixture must exercise ex_date == bar date" - ); - - let splits_path = tmp.join("qmSplits.bson"); - let divs_path = tmp.join("qmDividends.bson"); - write_file(&splits_path, &split_bytes); - write_file(&divs_path, &div_bytes); - - let out = tmp.join("out"); - let report = run_curate_adj_factors(&CurateAdjFactorsArgs { - qm_splits: splits_path, - qm_dividends: divs_path, - provider_mapping: map_path, - bars_1d_dir: bars_root.join("bars_1d"), - out_dir: out.clone(), - }) - .expect("run_curate_adj_factors"); - assert_conservation(&report); - - let expected_with = div_events - .iter() - .filter(|(_, e)| e.prev_close.is_some()) - .count(); - let expected_unmapped = div_events - .iter() - .filter(|(c, e)| mapping.resolve("qm", c, e.ex_date).is_none()) - .count(); - assert_eq!(report.dividends_with_prev_close, expected_with); - assert_eq!( - report.dividends_without_prev_close, - div_events.len() - expected_with - expected_unmapped - ); - assert_eq!( - report.curate_stats.dividends_dropped_unmapped, - expected_unmapped - ); - assert!(expected_unmapped > 0 && report.dividends_without_prev_close > 0); - assert!(report.curate_stats.builder.dividends_currency_mismatch > 0); - - let direct = curate_adj_factors(&mapping, "qm", split_events, div_events).expect("direct"); - let snap = read_adj_factors_dataset(&out).expect("read back"); - assert_rows_bit_eq(&snap.rows, &direct.rows); - assert_eq!(report.curate_stats, direct.stats); -} - -fn simple_fixture(tmp: &TempDir) -> CurateAdjFactorsArgs { - let map_path = tmp.join("provider_mapping.tsv"); - write_file(&map_path, b"qm\tAAA:US\t2015-01-01\t\t1\n"); - let bars_root = tmp.join("bars_root"); - write_bars_1d_dataset( - &bars_root, - &[ - bar(1, days(2023, 12, 29), 50.0, "USD"), - bar(1, days(2024, 3, 14), 60.0, "USD"), - ], - Bars1dWriteOptions::default(), - ) - .expect("bars"); - let splits = tmp.join("qmSplits.bson"); - let divs = tmp.join("qmDividends.bson"); - write_file(&splits, &split_doc("AAA:US", "2024-06-03", 2.0)); - write_file(&divs, &div_doc("AAA:US", "2024-03-15", 0.6, "USD")); - CurateAdjFactorsArgs { - qm_splits: splits, - qm_dividends: divs, - provider_mapping: map_path, - bars_1d_dir: bars_root.join("bars_1d"), - out_dir: tmp.join("out"), - } -} - -#[test] -fn non_year_entries_are_ignored_and_year_dir_without_part_file_fails_atomically() { - let tmp = TempDir::new("partitions"); - let args = simple_fixture(&tmp); - - // Stray entries that are not `year=YYYY` partitions must be skipped. - write_file(&args.bars_1d_dir.join("README.txt"), b"not a partition"); - fs::create_dir_all(args.bars_1d_dir.join("year=20x4")).unwrap(); - fs::create_dir_all(args.bars_1d_dir.join("year=12345")).unwrap(); - fs::create_dir_all(args.bars_1d_dir.join("tmp")).unwrap(); - let report = run_curate_adj_factors(&args).expect("stray entries ignored"); - assert_eq!(report.bars_files_read, 2); - assert_eq!(report.bars_rows_loaded, 2); - assert_eq!(report.dividends_with_prev_close, 1); - let published = args.out_dir.join("adj_factors/part.parquet"); - let before = fs::read(&published).unwrap(); - - // A real `year=YYYY` directory with no `part.parquet` must fail closed, naming the path. - let empty_year = args.bars_1d_dir.join("year=2022"); - fs::create_dir_all(&empty_year).unwrap(); - let err = run_curate_adj_factors(&args).expect_err("missing part.parquet must fail"); - let msg = err.to_string(); - assert!(!msg.contains('\n'), "single-line error: {msg}"); - assert!(msg.contains("year=2022"), "error names partition: {msg}"); - assert_eq!(fs::read(&published).unwrap(), before, "snapshot untouched"); -} - -#[test] -fn rerun_same_inputs_is_byte_identical_and_new_inputs_replace_snapshot() { - let tmp = TempDir::new("rerun"); - let args = simple_fixture(&tmp); - let published = args.out_dir.join("adj_factors/part.parquet"); - - run_curate_adj_factors(&args).expect("first run"); - let first = fs::read(&published).unwrap(); - let first_rows = read_adj_factors_dataset(&args.out_dir).unwrap().rows; - assert_eq!(first_rows.len(), 2); - - run_curate_adj_factors(&args).expect("second run"); - assert_eq!( - fs::read(&published).unwrap(), - first, - "rerun is byte-identical" - ); - - // New dividend export with an extra event replaces the snapshot. - let mut divs = div_doc("AAA:US", "2024-03-15", 0.6, "USD"); - divs.extend(div_doc("AAA:US", "2024-01-02", 0.5, "USD")); - write_file(&args.qm_dividends, &divs); - let report = run_curate_adj_factors(&args).expect("third run"); - assert_eq!(report.dividends_with_prev_close, 2); - let rows = read_adj_factors_dataset(&args.out_dir).unwrap().rows; - assert_eq!(rows.len(), 3); - assert!(rows.iter().any(|r| r.ex_date == days(2024, 1, 2))); - // No leftover temp files next to the published snapshot. - let entries: Vec<_> = fs::read_dir(args.out_dir.join("adj_factors")) - .unwrap() - .map(|e| e.unwrap().file_name().into_string().unwrap()) - .collect(); - assert_eq!(entries, vec!["part.parquet".to_string()], "{entries:?}"); -} - -#[test] -fn binary_runtime_failure_prints_single_line_error_and_creates_no_out_dir() { - let tmp = TempDir::new("bin-fail"); - let args = simple_fixture(&tmp); - let missing_bars = tmp.join("no_such_bars"); - - let output = Command::new(env!("CARGO_BIN_EXE_curate-etl")) - .args([ - "curate-adj-factors", - "--qm-splits", - args.qm_splits.to_str().unwrap(), - "--qm-dividends", - args.qm_dividends.to_str().unwrap(), - "--provider-mapping", - args.provider_mapping.to_str().unwrap(), - "--bars-1d", - missing_bars.to_str().unwrap(), - "--out", - args.out_dir.to_str().unwrap(), - ]) - .output() - .expect("spawn curate-etl"); - - assert_eq!(output.status.code(), Some(1)); - assert!(output.stdout.is_empty()); - let stderr = String::from_utf8_lossy(&output.stderr); - assert_eq!(stderr.trim_end().lines().count(), 1, "{stderr}"); - assert!(stderr.starts_with("error: "), "{stderr}"); - assert!(stderr.contains("no_such_bars"), "{stderr}"); - assert!( - !args.out_dir.exists(), - "--out must not be created on failure" - ); -} diff --git a/tools/curate-etl/tests/run_curate_bars_merge_qa.rs b/tools/curate-etl/tests/run_curate_bars_merge_qa.rs deleted file mode 100644 index a01708c8..00000000 --- a/tools/curate-etl/tests/run_curate_bars_merge_qa.rs +++ /dev/null @@ -1,300 +0,0 @@ -//! Post-merge QA for `curate-bars-1d` (T-110 / M1.2z after the `dev` merge with M1.2u). -//! -//! Gaps not covered by `tests/cli.rs`, `tests/run_curate_bars_qa_contract.rs`, or -//! `src/run_curate_bars_tests.rs`: -//! - merged `--help` still lists both the M1.2z commands and dev's M1.2u corporate-actions -//! commands, and `bench-curate-corporate-actions` still dispatches; -//! - duplicate `--rel-tolerance` at the binary level; -//! - `--rel-tolerance` has no effect on output while `qm_volumes` is empty (pins the README's -//! "qmPrices cross-check not wired" limit so a later wiring change is noticed); -//! - trailing bytes after the last BSON document fail closed with no published dataset; -//! - bar keys are matched verbatim (no trimming) against `source_id` in the mapping TSV; -//! - an empty `qmSplits` file leaves volumes untouched. - -use std::fs::{self, File}; -use std::io::Write; -use std::path::{Path, PathBuf}; -use std::process::{Command, Output}; -use std::sync::atomic::{AtomicU64, Ordering}; - -use bson::raw::{cstr, RawDocumentBuf}; -use parquet::file::reader::{FileReader, SerializedFileReader}; -use parquet::record::RowAccessor; - -use curate_etl::{run_curate_bars_1d, CurateBars1dArgs, RunCurateBarsError}; - -static SEQ: AtomicU64 = AtomicU64::new(0); - -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-bars-merge-qa-{tag}-{}-{seq}", - std::process::id() - )); - let _ = fs::remove_dir_all(&path); - fs::create_dir_all(&path).expect("create temp dir"); - Self(path) - } - - fn join(&self, name: &str) -> PathBuf { - self.0.join(name) - } -} - -impl Drop for TempDir { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.0); - } -} - -fn eod_doc(code: &str, date: &str, close: f64, volume: f64) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), code); - doc.append(cstr!("date"), date); - doc.append(cstr!("open"), close); - doc.append(cstr!("high"), close + 1.0); - doc.append(cstr!("low"), close - 1.0); - doc.append(cstr!("close"), close); - doc.append(cstr!("volume"), volume); - doc.into_bytes() -} - -fn split_doc(code: &str, date: &str, ratio: f64) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), code); - doc.append(cstr!("date"), date); - if ratio.is_finite() && ratio > 0.0 { - doc.append(cstr!("splitratio"), 1.0 / ratio); - doc.append(cstr!("forfactor"), 1.0_f64); - doc.append(cstr!("tofactor"), ratio); - } else { - doc.append(cstr!("splitratio"), ratio); - } - doc.into_bytes() -} - -fn write(path: &Path, bytes: &[u8]) { - File::create(path) - .and_then(|mut f| f.write_all(bytes)) - .expect("write fixture"); -} - -fn args_for(dir: &TempDir, out: &str, rel_tolerance: f64) -> CurateBars1dArgs { - CurateBars1dArgs { - eod_prices: dir.join("eodPrices.bson"), - qm_splits: dir.join("qmSplits.bson"), - qm_prices: None, - provider_mapping: dir.join("provider_mapping.tsv"), - listing_currencies: dir.join("listing_currencies.tsv"), - out_dir: dir.join(out), - rel_tolerance, - threads: 1, - } -} - -fn bars_1d_files(out_dir: &Path) -> Vec { - let root = out_dir.join("bars_1d"); - let mut files: Vec = match fs::read_dir(&root) { - Ok(rd) => rd - .flatten() - .map(|e| e.path().join("part.parquet")) - .filter(|p| p.is_file()) - .collect(), - Err(_) => Vec::new(), - }; - files.sort(); - files -} - -/// `(listing_id, close, volume)` per row in file order. -fn read_rows(out_dir: &Path) -> Vec<(i32, f64, f64)> { - let mut rows = Vec::new(); - for path in bars_1d_files(out_dir) { - let reader = SerializedFileReader::new(File::open(&path).unwrap()).unwrap(); - for row in reader.get_row_iter(None).unwrap() { - let row = row.unwrap(); - rows.push(( - row.get_int(0).unwrap(), - row.get_double(6).unwrap(), - row.get_double(7).unwrap(), - )); - } - } - rows -} - -fn run_bin(args: &[&str]) -> Output { - Command::new(env!("CARGO_BIN_EXE_curate-etl")) - .args(args) - .output() - .expect("spawn curate-etl") -} - -fn write_basic_fixture(dir: &TempDir) { - write( - &dir.join("provider_mapping.tsv"), - b"eod\tA.US\t2020-01-01\t\t1\nqm\tA:US\t2020-01-01\t\t1\n", - ); - write(&dir.join("listing_currencies.tsv"), b"1\tUSD\n"); - let mut eod = Vec::new(); - eod.extend(eod_doc("A.US", "2024-06-06", 10.0, 1_000.0)); - eod.extend(eod_doc("A.US", "2024-06-07", 10.5, 2_000.0)); - write(&dir.join("eodPrices.bson"), &eod); - write(&dir.join("qmSplits.bson"), &split_doc("A:US", "2024-06-07", 2.0)); -} - -#[test] -fn merged_help_lists_bars_and_corporate_actions_commands() { - let out = run_bin(&["--help"]); - assert!(out.status.success()); - let text = String::from_utf8(out.stdout).unwrap(); - for cmd in [ - "curate-bars-1d", - "bench-curate-bars-cmd", - "bench-curate-bars", - "bench-curate-corporate-actions", - "bench-corporate-actions", - ] { - assert!(text.contains(cmd), "--help missing '{cmd}':\n{text}"); - } -} - -#[test] -fn merged_bench_curate_corporate_actions_still_dispatches() { - let out = run_bin(&["bench-curate-corporate-actions", "200"]); - assert!( - out.status.success(), - "stderr: {}", - String::from_utf8_lossy(&out.stderr) - ); - assert!(!out.stdout.is_empty()); -} - -#[test] -fn binary_duplicate_rel_tolerance_is_usage_error_without_output() { - let dir = TempDir::new("dup-tol"); - write_basic_fixture(&dir); - let out_dir = dir.join("out"); - let p = |n: &str| dir.join(n).to_str().unwrap().to_owned(); - let (e, s, m, c, o) = ( - p("eodPrices.bson"), - p("qmSplits.bson"), - p("provider_mapping.tsv"), - p("listing_currencies.tsv"), - out_dir.to_str().unwrap().to_owned(), - ); - let out = run_bin(&[ - "curate-bars-1d", - "--eod-prices", - &e, - "--qm-splits", - &s, - "--provider-mapping", - &m, - "--listing-currencies", - &c, - "--out", - &o, - "--rel-tolerance", - "0.01", - "--rel-tolerance=0.02", - ]); - assert!(!out.status.success()); - assert!(out.stdout.is_empty()); - let stderr = String::from_utf8_lossy(&out.stderr); - assert!(stderr.contains("duplicate flag '--rel-tolerance'"), "{stderr}"); - assert!(!out_dir.exists(), "usage error must not create --out"); -} - -#[test] -fn rel_tolerance_does_not_change_output_while_qm_volumes_are_empty() { - let dir = TempDir::new("tol-noop"); - write_basic_fixture(&dir); - - let a = run_curate_bars_1d(&args_for(&dir, "out_a", 0.0)).expect("tol 0"); - let b = run_curate_bars_1d(&args_for(&dir, "out_b", 1e9)).expect("tol huge"); - - assert_eq!(a.curate_stats, b.curate_stats); - assert_eq!(a.write_stats.rows_written, 2); - let fa = bars_1d_files(&dir.join("out_a")); - let fb = bars_1d_files(&dir.join("out_b")); - assert_eq!(fa.len(), 1); - assert_eq!(fs::read(&fa[0]).unwrap(), fs::read(&fb[0]).unwrap()); - // 2:1 split on 2024-06-07: the prior bar's volume is halved, the ex-date bar untouched. - assert_eq!( - read_rows(&dir.join("out_a")), - vec![(1, 10.0, 500.0), (1, 10.5, 2_000.0)] - ); -} - -#[test] -fn trailing_partial_bytes_after_last_bson_doc_fail_without_publishing() { - for (label, trailer) in [ - ("three-byte-tail", vec![0x10u8, 0x00, 0x00]), - ("length-only-tail", 64i32.to_le_bytes().to_vec()), - ] { - let dir = TempDir::new(label); - write_basic_fixture(&dir); - let mut eod = fs::read(dir.join("eodPrices.bson")).unwrap(); - eod.extend(&trailer); - write(&dir.join("eodPrices.bson"), &eod); - - let err = run_curate_bars_1d(&args_for(&dir, "out", 0.01)).unwrap_err(); - assert!( - matches!(err, RunCurateBarsError::BsonStream { .. }), - "{label}: unexpected error {err:?}" - ); - let msg = err.to_string(); - assert!(!msg.contains('\n'), "{label}: multi-line error: {msg}"); - assert!(msg.contains("eodPrices.bson"), "{label}: {msg}"); - assert!( - bars_1d_files(&dir.join("out")).is_empty(), - "{label}: partial dataset published" - ); - } -} - -#[test] -fn bar_keys_match_mapping_source_id_verbatim_without_trimming() { - let dir = TempDir::new("verbatim"); - write( - &dir.join("provider_mapping.tsv"), - b"eod\t A.US\t2020-01-01\t\t1\neod\tB.US\t2020-01-01\t\t2\n", - ); - write(&dir.join("listing_currencies.tsv"), b"1\tUSD\n2\tUSD\n"); - let mut eod = Vec::new(); - eod.extend(eod_doc(" A.US", "2024-06-07", 10.0, 100.0)); // exact match -> kept - eod.extend(eod_doc("A.US", "2024-06-07", 11.0, 200.0)); // trimmed form -> unmapped - eod.extend(eod_doc("b.us", "2024-06-07", 12.0, 300.0)); // case differs -> unmapped - eod.extend(eod_doc("B.US", "2024-06-07", 13.0, 400.0)); // exact match -> kept - write(&dir.join("eodPrices.bson"), &eod); - write(&dir.join("qmSplits.bson"), b""); - - let report = run_curate_bars_1d(&args_for(&dir, "out", 0.01)).expect("run"); - assert_eq!(report.eod_decode.decoded, 4); - assert_eq!(report.bars_unmapped_source_dropped, 2); - assert_eq!(report.write_stats.rows_written, 2); - assert_eq!( - read_rows(&dir.join("out")), - vec![(1, 10.0, 100.0), (2, 13.0, 400.0)] - ); -} - -#[test] -fn empty_qm_splits_file_leaves_volumes_untouched() { - let dir = TempDir::new("no-splits"); - write_basic_fixture(&dir); - write(&dir.join("qmSplits.bson"), b""); - - let report = run_curate_bars_1d(&args_for(&dir, "out", 0.01)).expect("run"); - assert_eq!(report.splits_docs_framed, 0); - assert_eq!(report.split_rekey.splits_in, 0); - assert_eq!(report.split_rekey.split_events_attached, 0); - assert_eq!( - read_rows(&dir.join("out")), - vec![(1, 10.0, 1_000.0), (1, 10.5, 2_000.0)] - ); -} diff --git a/tools/curate-etl/tests/run_curate_bars_qa_contract.rs b/tools/curate-etl/tests/run_curate_bars_qa_contract.rs deleted file mode 100644 index 1e146458..00000000 --- a/tools/curate-etl/tests/run_curate_bars_qa_contract.rs +++ /dev/null @@ -1,957 +0,0 @@ -//! QA contract tests for the `curate-bars-1d` command (T-110 / M1.2z). -//! -//! Covers gaps left by `src/run_curate_bars_tests.rs` and `tests/cli.rs`, checking against -//! independent references rather than the runner's own logic: -//! - seeded randomized differential: file -> Parquet command output vs a naive in-test -//! `qmSearchCode -> listing_id -> eodSearchCode` re-key + early filter feeding the public -//! `curate_bars_1d` stage directly (bars built from generator values, not the decoder); -//! - inclusive mapping-boundary semantics for split re-keying (`valid_to == ex_date` applies, -//! `valid_from == ex_date + 1` is unmapped) and splits before / after all bars; -//! - binary stdout summary parsed as `key=value` and checked against the README conservation -//! invariants with every drop class populated; -//! - binary failure on a read-only `--out` directory and success on a not-yet-existing nested -//! `--out` directory. - -use std::borrow::Cow; -use std::collections::{BTreeMap, BTreeSet, HashMap}; -use std::fs::{self, File}; -use std::io::Write; -use std::path::{Path, PathBuf}; -use std::process::{Command, Output}; -use std::sync::atomic::{AtomicU64, Ordering}; - -use bson::raw::{cstr, RawDocumentBuf}; -use parquet::file::reader::{FileReader, SerializedFileReader}; -use parquet::record::{Field, RowAccessor}; - -use curate_etl::{ - curate_bars_1d, epoch_days_to_ymd, run_curate_bars_1d, ymd_to_epoch_days, Bars1dParquetRow, - CurateBars1dArgs, EodDailyBar, ProviderMappingRow, ProviderMappingTable, QmRawVolume, - SplitEvent, SplitTable, DEFAULT_CURATE_BARS_REL_TOLERANCE, -}; - -static SEQ: AtomicU64 = AtomicU64::new(0); - -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-run-bars-qa-{tag}-{}-{seq}", - std::process::id() - )); - let _ = fs::remove_dir_all(&path); - fs::create_dir_all(&path).expect("create temp dir"); - Self(path) - } - - fn join(&self, name: &str) -> PathBuf { - self.0.join(name) - } -} - -impl Drop for TempDir { - fn drop(&mut self) { - restore_writable(&self.0); - let _ = fs::remove_dir_all(&self.0); - } -} - -#[cfg(unix)] -fn restore_writable(path: &Path) { - use std::os::unix::fs::PermissionsExt; - if let Ok(entries) = fs::read_dir(path) { - for entry in entries.flatten() { - let p = entry.path(); - if p.is_dir() { - let _ = fs::set_permissions(&p, fs::Permissions::from_mode(0o755)); - restore_writable(&p); - } - } - } -} - -#[cfg(not(unix))] -fn restore_writable(_path: &Path) {} - -/// Deterministic SplitMix64 (fixed seed per test). -struct Rng(u64); - -impl Rng { - fn next_u64(&mut self) -> u64 { - self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); - let mut z = self.0; - z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); - z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); - z ^ (z >> 31) - } - - fn below(&mut self, n: u64) -> u64 { - self.next_u64() % n - } -} - -fn day(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).expect("valid date") -} - -fn ymd(epoch_day: i32) -> String { - let (y, m, d) = epoch_days_to_ymd(epoch_day); - format!("{y:04}-{m:02}-{d:02}") -} - -fn eod_doc(code: &str, date: &str, o: f64, h: f64, l: f64, c: f64, v: f64) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), code); - doc.append(cstr!("date"), date); - doc.append(cstr!("open"), o); - doc.append(cstr!("high"), h); - doc.append(cstr!("low"), l); - doc.append(cstr!("close"), c); - doc.append(cstr!("volume"), v); - doc.into_bytes() -} - -fn split_doc(code: &str, date: &str, ratio: f64) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), code); - doc.append(cstr!("date"), date); - if ratio.is_finite() && ratio > 0.0 { - doc.append(cstr!("splitratio"), 1.0 / ratio); - doc.append(cstr!("forfactor"), 1.0_f64); - doc.append(cstr!("tofactor"), ratio); - } else { - doc.append(cstr!("splitratio"), ratio); - } - doc.into_bytes() -} - -fn write(path: &Path, bytes: &[u8]) { - File::create(path) - .and_then(|mut f| f.write_all(bytes)) - .expect("write fixture"); -} - -fn args_for(dir: &TempDir, out: &str) -> CurateBars1dArgs { - CurateBars1dArgs { - eod_prices: dir.join("eodPrices.bson"), - qm_splits: dir.join("qmSplits.bson"), - qm_prices: None, - provider_mapping: dir.join("provider_mapping.tsv"), - listing_currencies: dir.join("listing_currencies.tsv"), - out_dir: dir.join(out), - rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, - threads: 1, - } -} - -/// Reads every `bars_1d/year=*/part.parquet` under `out_dir` in ascending year order. -fn read_dataset(out_dir: &Path) -> Vec { - let root = out_dir.join("bars_1d"); - let mut files: Vec = match fs::read_dir(&root) { - Ok(rd) => rd - .flatten() - .map(|e| e.path().join("part.parquet")) - .filter(|p| p.is_file()) - .collect(), - Err(_) => Vec::new(), - }; - files.sort(); - let mut rows = Vec::new(); - for path in files { - let reader = SerializedFileReader::new(File::open(&path).unwrap()).unwrap(); - for row in reader.get_row_iter(None).unwrap() { - let row = row.unwrap(); - let session_date = match row.get_column_iter().nth(2).unwrap().1 { - Field::Date(d) => *d, - other => panic!("expected date, got {other:?}"), - }; - rows.push(Bars1dParquetRow { - listing_id: row.get_int(0).unwrap(), - ts_micros: row.get_timestamp_micros(1).unwrap(), - session_date, - open: row.get_double(3).unwrap(), - high: row.get_double(4).unwrap(), - low: row.get_double(5).unwrap(), - close: row.get_double(6).unwrap(), - volume: row.get_double(7).unwrap(), - vwap: row.get_double(8).ok(), - currency: Cow::Owned(row.get_string(9).unwrap().to_owned()), - source: Cow::Owned(row.get_string(10).unwrap().to_owned()), - known_at_micros: row.get_timestamp_micros(11).unwrap(), - }); - } - } - rows -} - -fn row_key(r: &Bars1dParquetRow) -> (i32, i64) { - (r.listing_id, r.ts_micros) -} - -fn assert_rows_bit_identical( - actual: &[Bars1dParquetRow], - expected: &[Bars1dParquetRow], - ctx: &str, -) { - assert_eq!(actual.len(), expected.len(), "{ctx}: row count"); - for (a, e) in actual.iter().zip(expected) { - assert_eq!(row_key(a), row_key(e), "{ctx}"); - assert_eq!(a.session_date, e.session_date, "{ctx}"); - 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(), - "{ctx}: {name} for {:?}", - row_key(a) - ); - } - assert_eq!(a.vwap.map(f64::to_bits), e.vwap.map(f64::to_bits), "{ctx}"); - assert_eq!(a.currency, e.currency, "{ctx}"); - assert_eq!(a.source, e.source, "{ctx}"); - assert_eq!(a.known_at_micros, e.known_at_micros, "{ctx}"); - } -} - -// --------------------------------------------------------------------------------------------- -// 1. Seeded randomized differential vs naive reference re-key. -// --------------------------------------------------------------------------------------------- - -struct GenBar { - code: String, - date: i32, - o: f64, - h: f64, - l: f64, - c: f64, - v: f64, -} - -struct GenSplit { - code: String, - date: i32, - ratio: f64, -} - -struct Universe { - mapping: Vec, - currencies: BTreeMap, - bars: Vec, - splits: Vec, -} - -fn mrow(source: &str, id: &str, from: i32, to: Option, listing: i32) -> ProviderMappingRow { - ProviderMappingRow { - source: source.to_string(), - source_id: id.to_string(), - valid_from: from, - valid_to: to, - listing_id: listing, - } -} - -fn generate_universe(seed: u64) -> Universe { - const LISTINGS: i32 = 12; - const RATIOS: [f64; 6] = [2.0, 3.0, 4.0, 10.0, 0.5, 0.25]; - let mut rng = Rng(seed); - let open = day(2010, 1, 1); - let alias_end = day(2020, 12, 31); - - let mut mapping = Vec::new(); - let mut currencies = BTreeMap::new(); - let mut eod_codes: Vec = Vec::new(); - for l in 1..=LISTINGS { - if l != 12 { - // Listing 7's eod range starts mid-sample: earlier bars reach curate as `dropped_unmapped`. - let from = if l == 7 { day(2019, 1, 1) } else { open }; - let code = format!("E{l}.US"); - mapping.push(mrow("eod", &code, from, None, l)); - eod_codes.push(code); - if l % 4 == 0 { - let alias = format!("E{l}B.US"); - mapping.push(mrow("eod", &alias, open, None, l)); - eod_codes.push(alias); - } - } - mapping.push(mrow("qm", &format!("Q{l}:US"), open, None, l)); - if l % 3 == 0 { - mapping.push(mrow("qm", &format!("Q{l}X:US"), open, Some(alias_end), l)); - } - if l != 5 { - currencies.insert(l, if l % 2 == 0 { "CAD" } else { "USD" }); - } - } - for n in 0..3 { - eod_codes.push(format!("ZZ{n}.US")); - } - - let lo = day(2015, 1, 1); - let span = (day(2024, 12, 31) - lo + 1) as u64; - let pick_weekday = |rng: &mut Rng| loop { - let d = lo + rng.below(span) as i32; - let dow = (d + 4).rem_euclid(7); - if dow != 0 && dow != 6 { - return d; - } - }; - - let mut bars = Vec::new(); - for _ in 0..600 { - let code = eod_codes[rng.below(eod_codes.len() as u64) as usize].clone(); - let date = pick_weekday(&mut rng); - let o = (100 + rng.below(50_000)) as f64 / 100.0; - let spread = (1 + rng.below(300)) as f64 / 100.0; - let h = o + spread; - let l = (o - spread / 2.0).max(0.01); - let c = l + (h - l) * (rng.below(100) as f64 / 100.0); - let v = (1_000 + rng.below(50_000_000)) as f64; - bars.push(GenBar { - code, - date, - o, - h, - l, - c, - v, - }); - } - - let mut splits = Vec::new(); - let mut used: BTreeSet<(i32, i32)> = BTreeSet::new(); - while used.len() < 40 { - let l = 1 + rng.below(LISTINGS as u64) as i32; - let date = pick_weekday(&mut rng); - if !used.insert((l, date)) { - continue; - } - let ratio = RATIOS[rng.below(RATIOS.len() as u64) as usize]; - splits.push(GenSplit { - code: format!("Q{l}:US"), - date, - ratio, - }); - if l % 3 == 0 && rng.below(2) == 0 { - splits.push(GenSplit { - code: format!("Q{l}X:US"), - date, - ratio, - }); - } - } - for _ in 0..4 { - let date = pick_weekday(&mut rng); - splits.push(GenSplit { - code: "QNONE:US".to_string(), - date, - ratio: 2.0, - }); - let l = 1 + rng.below(LISTINGS as u64) as i32; - splits.push(GenSplit { - code: format!("Q{l}:US"), - date, - ratio: 1.0, - }); - } - - Universe { - mapping, - currencies, - bars, - splits, - } -} - -/// Fisher-Yates with the test RNG so on-disk document order is seeded and independent of -/// generation order. -fn shuffled_order(n: usize, rng: &mut Rng) -> Vec { - let mut idx: Vec = (0..n).collect(); - for i in (1..n).rev() { - let j = rng.below((i + 1) as u64) as usize; - idx.swap(i, j); - } - idx -} - -fn write_universe(dir: &TempDir, u: &Universe, rng: &mut Rng) { - let mut tsv = String::new(); - for r in &u.mapping { - let to = r.valid_to.map(ymd).unwrap_or_default(); - tsv.push_str(&format!( - "{}\t{}\t{}\t{}\t{}\n", - r.source, - r.source_id, - ymd(r.valid_from), - to, - r.listing_id - )); - } - write(&dir.join("provider_mapping.tsv"), tsv.as_bytes()); - let curr: String = u - .currencies - .iter() - .map(|(l, c)| format!("{l}\t{c}\n")) - .collect(); - write(&dir.join("listing_currencies.tsv"), curr.as_bytes()); - - let mut eod = Vec::new(); - for i in shuffled_order(u.bars.len(), rng) { - let b = &u.bars[i]; - eod.extend(eod_doc(&b.code, &ymd(b.date), b.o, b.h, b.l, b.c, b.v)); - } - write(&dir.join("eodPrices.bson"), &eod); - let mut sp = Vec::new(); - for i in shuffled_order(u.splits.len(), rng) { - let s = &u.splits[i]; - sp.extend(split_doc(&s.code, &ymd(s.date), s.ratio)); - } - write(&dir.join("qmSplits.bson"), &sp); -} - -#[derive(Debug, Default, PartialEq)] -struct RefSplitCounts { - noop: usize, - unmapped_qm: usize, - no_eod_partner: usize, - collapsed: usize, - applied: usize, - attached: usize, -} - -/// Naive linear-scan resolver (independent of `ProviderMappingTable` cursor logic). -fn naive_resolve(rows: &[ProviderMappingRow], source: &str, id: &str, date: i32) -> Option { - rows.iter() - .find(|r| { - r.source == source - && r.source_id == id - && r.valid_from <= date - && r.valid_to.is_none_or(|to| date <= to) - }) - .map(|r| r.listing_id) -} - -fn reference_rekey(u: &Universe) -> (Vec<(String, SplitEvent)>, RefSplitCounts) { - let mut counts = RefSplitCounts::default(); - let mut eod_partners: BTreeMap> = BTreeMap::new(); - for r in u.mapping.iter().filter(|r| r.source == "eod") { - eod_partners - .entry(r.listing_id) - .or_default() - .insert(r.source_id.clone()); - } - // (listing, ex_date) -> [(qm_key, ratio)] - let mut groups: BTreeMap<(i32, i32), Vec<(String, f64)>> = BTreeMap::new(); - for s in &u.splits { - if s.ratio == 1.0 { - counts.noop += 1; - continue; - } - let Some(listing) = naive_resolve(&u.mapping, "qm", &s.code, s.date) else { - counts.unmapped_qm += 1; - continue; - }; - if !eod_partners.contains_key(&listing) { - counts.no_eod_partner += 1; - continue; - } - groups - .entry((listing, s.date)) - .or_default() - .push((s.code.clone(), s.ratio)); - } - let mut events = Vec::new(); - for ((listing, ex_date), members) in groups { - let distinct: BTreeSet<&str> = members.iter().map(|(k, _)| k.as_str()).collect(); - let ratios: Vec = if distinct.len() > 1 { - assert!( - members - .iter() - .all(|(_, r)| r.to_bits() == members[0].1.to_bits()), - "generator must not emit conflicting alias ratios" - ); - counts.collapsed += members.len() - 1; - vec![members[0].1] - } else { - members.iter().map(|(_, r)| *r).collect() - }; - for ratio in ratios { - counts.applied += 1; - for key in &eod_partners[&listing] { - counts.attached += 1; - events.push((key.clone(), SplitEvent { ex_date, ratio })); - } - } - } - (events, counts) -} - -#[test] -fn seeded_differential_command_output_matches_naive_rekey_reference() { - for seed in [0x5EED_0001_u64, 0x5EED_0002, 0x5EED_0003, 0xC0FF_EE11] { - let u = generate_universe(seed); - let dir = TempDir::new("diff"); - let mut order_rng = Rng(seed ^ 0xA5A5_A5A5); - write_universe(&dir, &u, &mut order_rng); - - // Act: real command path (files -> Parquet). - let args = args_for(&dir, "out"); - let report = run_curate_bars_1d(&args).unwrap_or_else(|e| panic!("seed {seed:#x}: {e}")); - let mut actual = read_dataset(&args.out_dir); - actual.sort_by_key(row_key); - - // Reference: naive re-key + naive early filter, bars built from generator values. - let (events, ref_counts) = reference_rekey(&u); - let ref_splits = SplitTable::::from_events(events).unwrap(); - let eod_ids: BTreeSet<&str> = u - .mapping - .iter() - .filter(|r| r.source == "eod") - .map(|r| r.source_id.as_str()) - .collect(); - let ref_bars: Vec> = u - .bars - .iter() - .filter(|b| eod_ids.contains(b.code.as_str())) - .map(|b| EodDailyBar { - key: b.code.clone(), - session_date: b.date, - open: b.o, - high: b.h, - low: b.l, - close: b.c, - adj_volume: b.v, - }) - .collect(); - let ref_dropped = u.bars.len() - ref_bars.len(); - let table = ProviderMappingTable::from_rows(u.mapping.clone()).unwrap(); - let currencies: HashMap> = u - .currencies - .iter() - .map(|(l, c)| (*l, Cow::Borrowed(*c))) - .collect(); - let reference = curate_bars_1d( - ref_bars, - &ref_splits, - std::iter::empty::>(), - DEFAULT_CURATE_BARS_REL_TOLERANCE, - &table, - "eod", - ¤cies, - ) - .unwrap(); - let mut expected = reference.rows; - expected.sort_by_key(row_key); - - // Assert: rows bit-identical, stats and re-key counters agree. - let ctx = format!("seed {seed:#x}"); - assert!(!expected.is_empty(), "{ctx}: fixture must produce rows"); - assert_rows_bit_identical(&actual, &expected, &ctx); - assert_eq!(report.curate_stats, reference.stats, "{ctx}"); - assert_eq!(report.bars_unmapped_source_dropped, ref_dropped, "{ctx}"); - let rk = report.split_rekey; - assert_eq!( - RefSplitCounts { - noop: rk.splits_noop_dropped, - unmapped_qm: rk.splits_unmapped_qm, - no_eod_partner: rk.splits_no_eod_partner, - collapsed: rk.splits_collision_collapsed, - applied: rk.splits_applied, - attached: rk.split_events_attached, - }, - ref_counts, - "{ctx}" - ); - assert_eq!(rk.splits_in, u.splits.len(), "{ctx}"); - // Coverage guards: the seed must exercise every re-key branch it claims to. - assert!( - ref_counts.collapsed > 0 || seed == 0xC0FF_EE11, - "{ctx}: no alias collapse" - ); - assert!( - ref_counts.no_eod_partner + ref_counts.unmapped_qm > 0, - "{ctx}" - ); - assert!( - ref_counts.attached > ref_counts.applied, - "{ctx}: no two-partner listing" - ); - assert!(reference.stats.dropped_missing_currency > 0, "{ctx}"); - assert!(reference.stats.dropped_unmapped > 0, "{ctx}"); - } -} - -// --------------------------------------------------------------------------------------------- -// 2. Mapping boundaries and split placement relative to bars. -// --------------------------------------------------------------------------------------------- - -#[test] -fn split_rekey_respects_inclusive_mapping_boundaries_and_split_placement() { - let dir = TempDir::new("bounds"); - // Listing 1: qm range ends exactly on the split's ex-date (inclusive -> applied). - // Listing 2: qm range starts the day after the split's ex-date (-> unmapped). - // Listing 3: split after every bar (all bars un-adjusted); split before every bar (no-op). - write( - &dir.join("provider_mapping.tsv"), - b"eod\tA.US\t2020-01-01\t\t1\n\ - qm\tA:US\t2020-01-01\t2024-06-10\t1\n\ - eod\tB.US\t2020-01-01\t\t2\n\ - qm\tB:US\t2024-06-11\t\t2\n\ - eod\tC.US\t2020-01-01\t\t3\n\ - qm\tC:US\t2020-01-01\t\t3\n", - ); - write( - &dir.join("listing_currencies.tsv"), - b"1\tUSD\n2\tUSD\n3\tCAD\n", - ); - let mut eod = Vec::new(); - for code in ["A.US", "B.US", "C.US"] { - eod.extend(eod_doc(code, "2024-06-07", 10.0, 11.0, 9.0, 10.5, 8_000.0)); - eod.extend(eod_doc(code, "2024-06-10", 10.0, 11.0, 9.0, 10.5, 8_000.0)); - } - write(&dir.join("eodPrices.bson"), &eod); - let sp = [ - split_doc("A:US", "2024-06-10", 2.0), - split_doc("B:US", "2024-06-10", 2.0), - split_doc("C:US", "2024-12-02", 4.0), - split_doc("C:US", "2021-03-01", 8.0), - ] - .concat(); - write(&dir.join("qmSplits.bson"), &sp); - - let args = args_for(&dir, "out"); - let report = run_curate_bars_1d(&args).unwrap(); - let rows = read_dataset(&args.out_dir); - - assert_eq!(report.split_rekey.splits_in, 4); - assert_eq!(report.split_rekey.splits_applied, 3); - assert_eq!(report.split_rekey.splits_unmapped_qm, 1); - let vol = |listing: i32, date: i32| { - rows.iter() - .find(|r| r.listing_id == listing && r.session_date == date) - .unwrap_or_else(|| panic!("row {listing}/{date}")) - .volume - }; - let (d7, d10) = (day(2024, 6, 7), day(2024, 6, 10)); - assert_eq!(vol(1, d7), 4_000.0, "valid_to == ex_date is inclusive"); - assert_eq!(vol(1, d10), 8_000.0, "ex-date bar not divided"); - assert_eq!( - vol(2, d7), - 8_000.0, - "qm range starting after ex_date must not apply" - ); - assert_eq!( - vol(3, d7), - 2_000.0, - "split after all bars divides every bar" - ); - assert_eq!(vol(3, d10), 2_000.0); - assert_eq!(rows.len(), 6); - for r in &rows { - assert_eq!((r.open, r.high, r.low, r.close), (10.0, 11.0, 9.0, 10.5)); - } -} - -// --------------------------------------------------------------------------------------------- -// 3. Binary stdout summary vs README conservation invariants. -// --------------------------------------------------------------------------------------------- - -fn run_bin(args: &[&str]) -> Output { - Command::new(env!("CARGO_BIN_EXE_curate-etl")) - .args(args) - .output() - .expect("spawn curate-etl") -} - -fn bin_args(paths: &[PathBuf; 5]) -> Vec<&str> { - vec![ - "curate-bars-1d", - "--eod-prices", - paths[0].to_str().unwrap(), - "--qm-splits", - paths[1].to_str().unwrap(), - "--provider-mapping", - paths[2].to_str().unwrap(), - "--listing-currencies", - paths[3].to_str().unwrap(), - "--out", - paths[4].to_str().unwrap(), - ] -} - -fn paths(dir: &TempDir, out: &Path) -> [PathBuf; 5] { - [ - dir.join("eodPrices.bson"), - dir.join("qmSplits.bson"), - dir.join("provider_mapping.tsv"), - dir.join("listing_currencies.tsv"), - out.to_path_buf(), - ] -} - -/// Parses `section: k=v k=v` lines into `"section.k" -> v` (numeric values only). -fn parse_summary(stdout: &str) -> HashMap { - let mut map = HashMap::new(); - for line in stdout.lines() { - let Some((section, rest)) = line.trim().split_once(':') else { - continue; - }; - for tok in rest.split_whitespace() { - let tok = tok.trim_start_matches('(').trim_end_matches(')'); - if let Some((k, v)) = tok.split_once('=') { - if let Ok(n) = v.parse::() { - map.insert(format!("{section}.{k}"), n); - } - } - } - } - map -} - -fn write_every_drop_class_fixture(dir: &TempDir) { - write( - &dir.join("provider_mapping.tsv"), - b"eod\tGOOD.US\t1970-01-01\t\t1\n\ - eod\tALIAS.US\t1970-01-01\t\t1\n\ - eod\tNOCUR.US\t2020-01-01\t\t2\n\ - eod\tLATE.US\t2024-06-10\t\t3\n\ - qm\tGOOD:US\t1970-01-01\t\t1\n\ - qm\tGOODX:US\t1970-01-01\t\t1\n\ - qm\tQMONLY:US\t2020-01-01\t\t9\n", - ); - write( - &dir.join("listing_currencies.tsv"), - b"1\tUSD\n3\tUSD\n9\tUSD\n", - ); - - let mut missing_close = RawDocumentBuf::new(); - missing_close.append(cstr!("eodSearchCode"), "GOOD.US"); - missing_close.append(cstr!("date"), "2024-06-03"); - missing_close.append(cstr!("open"), 1.0); - missing_close.append(cstr!("high"), 1.0); - missing_close.append(cstr!("low"), 1.0); - missing_close.append(cstr!("volume"), 1.0); - - let eod = [ - eod_doc("GOOD.US", "2024-06-07", 10.0, 11.0, 9.0, 10.5, 1_000.0), // written - eod_doc("GOOD.US", "2024-06-10", 10.0, 11.0, 9.0, 10.5, 1_000.0), // written - eod_doc("GOOD.US", "2024-06-11", 10.0, 11.0, 9.0, 10.5, 1_000.0), // dup collapsed - eod_doc("GOOD.US", "2024-06-11", 10.0, 11.0, 9.0, 10.5, 1_000.0), - eod_doc("GOOD.US", "2024-06-12", 10.0, 11.0, 9.0, 10.5, 1_000.0), // dup conflict - eod_doc("GOOD.US", "2024-06-12", 12.0, 13.0, 9.0, 10.5, 1_000.0), - eod_doc("GOOD.US", "2024-06-13", 10.0, 9.0, 11.0, 10.5, 1_000.0), // high < low - eod_doc("GOOD.US", "1975-06-02", 10.0, 11.0, 9.0, 10.5, 1_000.0), // ts out of range - eod_doc("ALIAS.US", "2024-06-07", 10.0, 11.0, 9.0, 10.5, 1_000.0), // collision collapse - eod_doc("ALIAS.US", "2024-06-14", 10.0, 11.0, 9.0, 10.5, 1_000.0), // collision vs GOOD below - eod_doc("GOOD.US", "2024-06-14", 20.0, 21.0, 19.0, 20.5, 1_000.0), - eod_doc("NOCUR.US", "2024-06-07", 10.0, 11.0, 9.0, 10.5, 1_000.0), // missing currency - eod_doc("LATE.US", "2024-06-07", 10.0, 11.0, 9.0, 10.5, 1_000.0), // dropped_unmapped - eod_doc("LATE.US", "2024-06-10", 10.0, 11.0, 9.0, 10.5, 1_000.0), // written - eod_doc("ZZZ.US", "2024-06-07", 10.0, 11.0, 9.0, 10.5, 1_000.0), // early filter - missing_close.into_bytes(), // decoder reject - ] - .concat(); - write(&dir.join("eodPrices.bson"), &eod); - - let mut missing_ratio = RawDocumentBuf::new(); - missing_ratio.append(cstr!("qmSearchCode"), "GOOD:US"); - missing_ratio.append(cstr!("date"), "2024-06-10"); - let sp = [ - split_doc("GOOD:US", "2024-06-10", 2.0), - split_doc("GOODX:US", "2024-06-10", 2.0), // alias collapse - split_doc("GOOD:US", "2023-01-03", 1.0), // no-op - split_doc("NOPE:US", "2024-06-10", 2.0), // unmapped qm - split_doc("QMONLY:US", "2024-06-10", 2.0), // no eod partner - missing_ratio.into_bytes(), // decoder reject - ] - .concat(); - write(&dir.join("qmSplits.bson"), &sp); -} - -#[test] -fn binary_summary_parses_and_satisfies_readme_conservation_invariants() { - let dir = TempDir::new("summary"); - write_every_drop_class_fixture(&dir); - let out = dir.join("out"); - let p = paths(&dir, &out); - - let res = run_bin(&bin_args(&p)); - let stdout = String::from_utf8_lossy(&res.stdout).into_owned(); - assert!( - res.status.success(), - "{}", - String::from_utf8_lossy(&res.stderr) - ); - assert!(res.stderr.is_empty()); - let s = parse_summary(&stdout); - let g = |k: &str| { - *s.get(k) - .unwrap_or_else(|| panic!("missing {k} in:\n{stdout}")) - }; - - // Splits: every branch hit exactly once and the README equation holds. - assert_eq!(g("splits.splits_in"), 6); - for k in [ - "splits.splits_applied", - "splits.splits_collision_collapsed", - "splits.splits_unmapped_qm", - "splits.splits_no_eod_partner", - "splits.splits_noop_dropped", - "splits_bson.rejected", - ] { - assert_eq!(g(k), 1, "{k}\n{stdout}"); - } - assert_eq!( - g("splits.splits_in"), - g("splits.splits_applied") - + g("splits.splits_collision_collapsed") - + g("splits.splits_unmapped_qm") - + g("splits.splits_no_eod_partner") - + g("splits.splits_noop_dropped") - + g("splits_bson.rejected") - ); - // Two eod partners on listing 1 -> one applied split attached twice. - assert_eq!(g("splits.split_events_attached"), 2); - - // EOD framing/decoding. - assert_eq!(g("eod_bson.docs_framed"), 16); - assert_eq!(g("eod_bson.docs_framed"), g("eod_bson.docs_in")); - assert_eq!( - g("eod_bson.docs_in"), - g("eod_bson.decoded") + g("eod_bson.rejected") - ); - assert_eq!(g("eod_bson.rejected"), 1); - - // Every drop class populated. - for k in [ - "filter.bars_unmapped_source_dropped", - "builder.inconsistent_ohlc", - "builder.dup_collapsed", - "builder.dup_conflict_dropped", - "curate.dropped_unmapped", - "curate.dropped_missing_currency", - "curate.dropped_ts_out_of_range", - "curate.listing_collision_collapsed", - "curate.listing_collision_dropped", - ] { - assert!(g(k) > 0, "{k} should be exercised\n{stdout}"); - } - - let drops = g("filter.bars_unmapped_source_dropped") - + g("builder.invalid_ohlc") - + g("builder.inconsistent_ohlc") - + g("builder.invalid_vol") - + g("builder.dup_collapsed") - + g("builder.dup_conflict_dropped") - + g("curate.dropped_unmapped") - + g("curate.dropped_missing_currency") - + g("curate.dropped_ts_out_of_range") - + g("curate.listing_collision_collapsed") - + g("curate.listing_collision_dropped"); - assert_eq!( - g("eod_bson.decoded"), - g("write.rows_written") + drops, - "README bar conservation\n{stdout}" - ); - assert_eq!(g("years.2024"), g("write.rows_written")); - assert_eq!(g("filter.buffered_bars"), g("builder.bars_in")); - - // Parquet agrees with the summary, and the split is applied to the surviving pre-ex bar. - let rows = read_dataset(&out); - assert_eq!(rows.len() as u64, g("write.rows_written")); - let pre = rows - .iter() - .find(|r| r.listing_id == 1 && r.session_date == day(2024, 6, 7)) - .expect("listing 1 pre-split bar"); - assert_eq!( - pre.volume, 500.0, - "2:1 split applied once despite QM alias + EOD alias" - ); -} - -// --------------------------------------------------------------------------------------------- -// 4. Output directory handling through the binary. -// --------------------------------------------------------------------------------------------- - -fn write_minimal_fixture(dir: &TempDir) { - write( - &dir.join("provider_mapping.tsv"), - b"eod\tA.US\t2020-01-01\t\t1\n", - ); - write(&dir.join("listing_currencies.tsv"), b"1\tUSD\n"); - write( - &dir.join("eodPrices.bson"), - &eod_doc("A.US", "2024-06-07", 10.0, 11.0, 9.0, 10.5, 1_000.0), - ); - write(&dir.join("qmSplits.bson"), b""); -} - -#[cfg(unix)] -#[test] -fn binary_read_only_out_dir_fails_single_line_and_publishes_nothing() { - use std::os::unix::fs::PermissionsExt; - - let dir = TempDir::new("ro"); - write_minimal_fixture(&dir); - let out = dir.join("ro_out"); - fs::create_dir_all(&out).unwrap(); - fs::set_permissions(&out, fs::Permissions::from_mode(0o555)).unwrap(); - // Skip silently if the process can still write (e.g. running as root). - if fs::create_dir(out.join("probe")).is_ok() { - let _ = fs::remove_dir(out.join("probe")); - return; - } - - let p = paths(&dir, &out); - let res = run_bin(&bin_args(&p)); - - let err = String::from_utf8_lossy(&res.stderr).into_owned(); - assert_eq!(res.status.code(), Some(1), "{err}"); - assert!(res.stdout.is_empty()); - assert_eq!(err.lines().count(), 1, "{err}"); - assert!(err.starts_with("error: "), "{err}"); - assert!(err.contains("ro_out"), "stderr names the --out path: {err}"); - fs::set_permissions(&out, fs::Permissions::from_mode(0o755)).unwrap(); - assert_eq!( - fs::read_dir(&out).unwrap().count(), - 0, - "nothing left under --out" - ); -} - -#[test] -fn binary_creates_missing_nested_out_dir_on_success() { - let dir = TempDir::new("nested"); - write_minimal_fixture(&dir); - let out = dir.join("a").join("b").join("c"); - assert!(!out.exists()); - - let p = paths(&dir, &out); - let res = run_bin(&bin_args(&p)); - - assert!( - res.status.success(), - "{}", - String::from_utf8_lossy(&res.stderr) - ); - let rows = read_dataset(&out); - assert_eq!(rows.len(), 1); - assert_eq!(rows[0].listing_id, 1); - assert_eq!(rows[0].currency, "USD"); - assert_eq!(rows[0].source, "eod_unadj"); - let leftovers: Vec<_> = fs::read_dir(out.join("bars_1d")) - .unwrap() - .flatten() - .map(|e| e.file_name().to_string_lossy().into_owned()) - .collect(); - assert_eq!( - leftovers, - vec!["year=2024".to_string()], - "no staging/lock residue" - ); -} diff --git a/tools/curate-etl/tests/run_curate_bars_qm_qa_contract.rs b/tools/curate-etl/tests/run_curate_bars_qm_qa_contract.rs deleted file mode 100644 index a0e37954..00000000 --- a/tools/curate-etl/tests/run_curate_bars_qm_qa_contract.rs +++ /dev/null @@ -1,814 +0,0 @@ -//! QA contract tests for the `curate-bars-1d --qm-prices` volume cross-check (T-118 / M1.2ah). -//! -//! Covers gaps left by `src/run_curate_bars_tests.rs` and `tests/cli.rs`, checking the runner -//! against independent in-test references rather than its own logic: -//! - seeded randomized differential: `QmVolumeRekeyStats`, builder cross-check counters and the -//! full mismatch-sample list vs a naive linear-scan `qmSearchCode -> listing_id -> eodSearchCode` -//! re-key (reused EOD ticker, EOD rename, EOD alias, QM rename, late QM mapping, QM-only listing, -//! unmapped QM key, decoder rejects, shuffled input order) plus byte-identical Parquet; -//! - inclusive date boundaries on both the `"qm"` and `"eod"` mapping ranges; -//! - `--rel-tolerance` is honoured by the cross-check without changing Parquet bytes; -//! - an empty (0-byte) `--qm-prices` file is a valid "ran, saw nothing" input; -//! - a validly framed but corrupt `qmPrices` document is counted, not fatal; -//! - binary stdout: every pre-existing report line is byte-identical with and without -//! `--qm-prices` (only `qm_*` lines and `timing:` differ), README invariants hold on the parsed -//! `key=value` summary, and the hand-calculated NVDA-style `qm_mismatch:` line is exact. - -use std::collections::{BTreeMap, HashMap}; -use std::fs::{self, File}; -use std::io::Write; -use std::path::{Path, PathBuf}; -use std::process::{Command, Output}; -use std::sync::atomic::{AtomicU64, Ordering}; - -use bson::raw::{cstr, RawDocumentBuf}; - -use curate_etl::{ - epoch_days_to_ymd, run_curate_bars_1d, ymd_to_epoch_days, CurateBars1dArgs, - CurateBars1dRunReport, DEFAULT_CURATE_BARS_REL_TOLERANCE, -}; - -static SEQ: AtomicU64 = AtomicU64::new(0); - -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-run-bars-qm-qa-{tag}-{}-{seq}", - std::process::id() - )); - let _ = fs::remove_dir_all(&path); - fs::create_dir_all(&path).expect("create temp dir"); - Self(path) - } - - fn join(&self, name: &str) -> PathBuf { - self.0.join(name) - } -} - -impl Drop for TempDir { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.0); - } -} - -/// Deterministic SplitMix64 (fixed seed per test). -struct Rng(u64); - -impl Rng { - fn next_u64(&mut self) -> u64 { - self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); - let mut z = self.0; - z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); - z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); - z ^ (z >> 31) - } - - fn below(&mut self, n: u64) -> u64 { - self.next_u64() % n - } -} - -fn day(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).expect("valid date") -} - -fn ymd(epoch_day: i32) -> String { - let (y, m, d) = epoch_days_to_ymd(epoch_day); - format!("{y:04}-{m:02}-{d:02}") -} - -fn eod_doc(code: &str, date: &str, c: f64, v: f64) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), code); - doc.append(cstr!("date"), date); - doc.append(cstr!("open"), c); - doc.append(cstr!("high"), c + 1.0); - doc.append(cstr!("low"), c - 1.0); - doc.append(cstr!("close"), c); - doc.append(cstr!("volume"), v); - doc.into_bytes() -} - -fn split_doc(code: &str, date: &str, ratio: f64) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), code); - doc.append(cstr!("date"), date); - if ratio.is_finite() && ratio > 0.0 { - doc.append(cstr!("splitratio"), 1.0 / ratio); - doc.append(cstr!("forfactor"), 1.0_f64); - doc.append(cstr!("tofactor"), ratio); - } else { - doc.append(cstr!("splitratio"), ratio); - } - doc.into_bytes() -} - -fn qm_doc(code: &str, date: &str, share_volume: f64) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), code); - doc.append(cstr!("date"), date); - doc.append(cstr!("sharevolume"), share_volume); - doc.into_bytes() -} - -fn qm_doc_str_volume(code: &str, date: &str) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), code); - doc.append(cstr!("date"), date); - doc.append(cstr!("sharevolume"), "123"); - doc.into_bytes() -} - -fn write(path: &Path, bytes: &[u8]) { - File::create(path) - .and_then(|mut f| f.write_all(bytes)) - .expect("write fixture"); -} - -struct MapRow { - source: &'static str, - id: String, - from: i32, - to: Option, - listing: i32, -} - -fn mrow(source: &'static str, id: &str, from: i32, to: Option, listing: i32) -> MapRow { - MapRow { - source, - id: id.to_string(), - from, - to, - listing, - } -} - -fn mapping_tsv(rows: &[MapRow]) -> String { - rows.iter() - .map(|r| { - format!( - "{}\t{}\t{}\t{}\t{}\n", - r.source, - r.id, - ymd(r.from), - r.to.map(ymd).unwrap_or_default(), - r.listing - ) - }) - .collect() -} - -fn covers(r: &MapRow, d: i32) -> bool { - d >= r.from && r.to.is_none_or(|to| d <= to) -} - -fn args_for(dir: &TempDir, out: &str, qm: Option<&str>) -> CurateBars1dArgs { - CurateBars1dArgs { - eod_prices: dir.join("eodPrices.bson"), - qm_splits: dir.join("qmSplits.bson"), - qm_prices: qm.map(|name| dir.join(name)), - provider_mapping: dir.join("provider_mapping.tsv"), - listing_currencies: dir.join("listing_currencies.tsv"), - out_dir: dir.join(out), - rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, - threads: 1, - } -} - -/// Every `bars_1d/year=*/part.parquet` under `out_dir` as `(relative path, bytes)`, sorted. -fn dataset_bytes(out_dir: &Path) -> Vec<(String, Vec)> { - let root = out_dir.join("bars_1d"); - let mut files: Vec<(String, Vec)> = fs::read_dir(&root) - .expect("bars_1d dir") - .flatten() - .map(|e| e.path().join("part.parquet")) - .filter(|p| p.is_file()) - .map(|p| { - let rel = p.strip_prefix(out_dir).unwrap().display().to_string(); - (rel, fs::read(&p).unwrap()) - }) - .collect(); - files.sort(); - assert!(!files.is_empty(), "expected at least one partition"); - files -} - -fn assert_readme_qm_invariants(r: &CurateBars1dRunReport, ctx: &str) { - let b = &r.curate_stats.builder; - assert!(r.qm_prices_present, "{ctx}"); - assert_eq!(r.qm_prices_docs_framed as usize, r.qm_prices_decode.docs_in, "{ctx}"); - assert_eq!( - r.qm_prices_decode.docs_in, - r.qm_prices_decode.decoded + r.qm_prices_decode.rejected_total(), - "{ctx}" - ); - assert_eq!( - r.qm_rekey.qm_in, - r.qm_rekey.qm_attached - + r.qm_rekey.qm_unmapped_qm - + r.qm_rekey.qm_no_eod_partner - + r.qm_prices_decode.rejected_total(), - "{ctx}: rekey conservation" - ); - assert_eq!(r.qm_rekey.qm_volumes_attached, b.qm_rows_in, "{ctx}"); - assert_eq!(b.volume_checked + b.volume_unchecked, b.rows_out, "{ctx}"); - assert_eq!( - b.volume_within_tolerance + b.volume_mismatched, - b.volume_checked, - "{ctx}" - ); - assert_eq!( - r.mismatch_samples.len(), - b.volume_mismatched.min(100), - "{ctx}: sample count" - ); -} - -// --------------------------------------------------------------------------------------------- -// 1. Seeded randomized differential vs a naive linear-scan reference re-key. -// --------------------------------------------------------------------------------------------- - -struct Universe { - mapping: Vec, - /// `(eod_key, session_date) -> adjusted volume` (no splits, so raw == adjusted). - bars: BTreeMap<(String, i32), f64>, - /// Encoded `qmPrices` docs (shuffled) plus decoded intent for the valid ones. - qm_docs: Vec>, - qm_valid: Vec<(String, i32, f64)>, - qm_rejected: usize, -} - -const DELTAS: [f64; 6] = [0.0, 0.004, -0.008, 0.03, -0.25, 0.5]; - -fn generate_universe(seed: u64) -> Universe { - let mut rng = Rng(seed); - let d0 = day(2022, 1, 3); - const N: i32 = 60; - let cut = |rng: &mut Rng| d0 + 10 + rng.below(40) as i32; - - let reuse_cut = cut(&mut rng); - let rename_cut = cut(&mut rng); - let alias_from = d0 + rng.below(20) as i32; - let alias_to = alias_from + 5 + rng.below(30) as i32; - let qm_rename_cut = cut(&mut rng); - let qm_late_from = cut(&mut rng); - - let mut mapping = vec![ - mrow("eod", "E1.US", d0, None, 1), - mrow("eod", "E2.US", d0, None, 2), - // EOD alias: second ticker on the same listing for part of the window. - mrow("eod", "E2B.US", alias_from, Some(alias_to), 2), - // EOD rename. - mrow("eod", "E3.US", d0, Some(rename_cut - 1), 3), - mrow("eod", "E3N.US", rename_cut, None, 3), - mrow("eod", "E4.US", d0, None, 4), - mrow("eod", "E5.US", d0, None, 5), - // Reused EOD ticker: two different listings over disjoint ranges. - mrow("eod", "R.US", d0, Some(reuse_cut - 1), 7), - mrow("eod", "R.US", reuse_cut, None, 8), - mrow("qm", "Q1", d0, None, 1), - mrow("qm", "Q2", d0, None, 2), - mrow("qm", "Q3", d0, None, 3), - // QM rename. - mrow("qm", "Q4", d0, Some(qm_rename_cut - 1), 4), - mrow("qm", "Q4N", qm_rename_cut, None, 4), - // QM mapping starting late: earlier rows are unmapped. - mrow("qm", "Q5", qm_late_from, None, 5), - mrow("qm", "Q7", d0, None, 7), - mrow("qm", "Q8", d0, None, 8), - // QM-only listing: never has an EOD partner. - mrow("qm", "Q9", d0, None, 9), - ]; - // Shuffle mapping row order so index construction cannot depend on TSV order. - for i in (1..mapping.len()).rev() { - let j = rng.below(i as u64 + 1) as usize; - mapping.swap(i, j); - } - - let eod_keys = ["E1.US", "E2.US", "E2B.US", "E3.US", "E3N.US", "E4.US", "E5.US", "R.US"]; - let mut bars = BTreeMap::new(); - for key in eod_keys { - for d in d0..d0 + N { - // Bars also exist outside a key's mapping range (renamed/reused tickers keep - // publishing); they must never receive a QM partner on uncovered dates. - if rng.below(100) < 85 { - let vol = (1_000 + rng.below(1_000_000)) as f64; - bars.insert((key.to_string(), d), vol); - } - } - } - - let qm_codes = ["Q1", "Q2", "Q3", "Q4", "Q4N", "Q5", "Q7", "Q8", "Q9", "QX_UNMAPPED"]; - let mut qm_docs = Vec::new(); - let mut qm_valid = Vec::new(); - let mut qm_rejected = 0usize; - for code in qm_codes { - for d in d0..d0 + N { - if rng.below(100) >= 70 { - continue; - } - if rng.below(40) == 0 { - qm_docs.push(qm_doc_str_volume(code, &ymd(d))); - qm_rejected += 1; - continue; - } - if rng.below(40) == 0 { - qm_docs.push(qm_doc(code, "2022-02-30", 1.0)); - qm_rejected += 1; - continue; - } - // Anchor the share volume on any EOD bar for this listing/date so a meaningful share - // of rows lands within tolerance; the reference re-derives everything independently. - let listing = mapping - .iter() - .find(|r| r.source == "qm" && r.id == code && covers(r, d)) - .map(|r| r.listing); - let anchor = listing.and_then(|l| { - mapping - .iter() - .filter(|r| r.source == "eod" && r.listing == l && covers(r, d)) - .filter_map(|r| bars.get(&(r.id.clone(), d)).copied()) - .min_by(f64::total_cmp) - }); - let share = match anchor { - Some(v) => v * (1.0 + DELTAS[rng.below(DELTAS.len() as u64) as usize]), - None => (1_000 + rng.below(1_000_000)) as f64, - }; - qm_docs.push(qm_doc(code, &ymd(d), share)); - qm_valid.push((code.to_string(), d, share)); - } - } - for i in (1..qm_docs.len()).rev() { - let j = rng.below(i as u64 + 1) as usize; - qm_docs.swap(i, j); - } - - Universe { - mapping, - bars, - qm_docs, - qm_valid, - qm_rejected, - } -} - -#[derive(Debug, Default, PartialEq)] -struct RefStats { - qm_attached: usize, - qm_unmapped_qm: usize, - qm_no_eod_partner: usize, - qm_volumes_attached: usize, - volume_checked: usize, - volume_within_tolerance: usize, - volume_mismatched: usize, -} - -/// Naive reference: linear scans over mapping rows, no indexes, no early filtering shortcuts. -fn reference(u: &Universe, tol: f64) -> (RefStats, Vec<(String, i32, f64)>) { - let mut s = RefStats::default(); - let mut partners: Vec<(String, i32, f64)> = Vec::new(); - for (code, d, share) in &u.qm_valid { - let listings: Vec = u - .mapping - .iter() - .filter(|r| r.source == "qm" && &r.id == code && covers(r, *d)) - .map(|r| r.listing) - .collect(); - assert!(listings.len() <= 1, "fixture must not overlap QM ranges"); - let Some(&l) = listings.first() else { - s.qm_unmapped_qm += 1; - continue; - }; - let keys: Vec<&str> = u - .mapping - .iter() - .filter(|r| r.source == "eod" && r.listing == l && covers(r, *d)) - .map(|r| r.id.as_str()) - .collect(); - if keys.is_empty() { - s.qm_no_eod_partner += 1; - continue; - } - s.qm_attached += 1; - s.qm_volumes_attached += keys.len(); - for k in keys { - partners.push((k.to_string(), *d, *share)); - } - } - - let mut mismatches = Vec::new(); - for (k, d, share) in partners { - let Some(&vol) = u.bars.get(&(k.clone(), d)) else { - continue; - }; - s.volume_checked += 1; - let rel = (vol - share).abs() / share; - if rel <= tol { - s.volume_within_tolerance += 1; - } else { - s.volume_mismatched += 1; - mismatches.push((k, d, rel)); - } - } - // Builder order: (rel DESC, key ASC, session_date ASC). - mismatches.sort_by(|a, b| { - b.2.total_cmp(&a.2) - .then_with(|| a.0.cmp(&b.0)) - .then_with(|| a.1.cmp(&b.1)) - }); - (s, mismatches) -} - -fn write_universe(dir: &TempDir, u: &Universe) { - write( - &dir.join("provider_mapping.tsv"), - mapping_tsv(&u.mapping).as_bytes(), - ); - write( - &dir.join("listing_currencies.tsv"), - b"1\tUSD\n2\tUSD\n3\tCAD\n4\tUSD\n5\tUSD\n7\tUSD\n8\tCAD\n9\tUSD\n", - ); - let eod: Vec = u - .bars - .iter() - .flat_map(|((k, d), v)| eod_doc(k, &ymd(*d), 50.0, *v)) - .collect(); - write(&dir.join("eodPrices.bson"), &eod); - write(&dir.join("qmSplits.bson"), b""); - write(&dir.join("qmPrices.bson"), &u.qm_docs.concat()); - let mut rev = u.qm_docs.clone(); - rev.reverse(); - write(&dir.join("qmPrices_rev.bson"), &rev.concat()); -} - -#[test] -fn seeded_randomized_qm_rekey_and_cross_check_match_naive_reference() { - for seed in [0x5EED_0001_u64, 0x5EED_0002, 0x5EED_0003, 0xC0FF_EE00] { - let ctx = format!("seed={seed:#x}"); - let dir = TempDir::new("diff"); - let u = generate_universe(seed); - write_universe(&dir, &u); - - let base = run_curate_bars_1d(&args_for(&dir, "out_base", None)).expect("base run"); - let with = run_curate_bars_1d(&args_for(&dir, "out_qm", Some("qmPrices.bson"))) - .unwrap_or_else(|e| panic!("{ctx}: qm run failed: {e}")); - let rev = run_curate_bars_1d(&args_for(&dir, "out_rev", Some("qmPrices_rev.bson"))) - .unwrap_or_else(|e| panic!("{ctx}: reversed qm run failed: {e}")); - - let (exp, exp_mismatches) = reference(&u, DEFAULT_CURATE_BARS_REL_TOLERANCE); - let b = &with.curate_stats.builder; - let actual = RefStats { - qm_attached: with.qm_rekey.qm_attached, - qm_unmapped_qm: with.qm_rekey.qm_unmapped_qm, - qm_no_eod_partner: with.qm_rekey.qm_no_eod_partner, - qm_volumes_attached: with.qm_rekey.qm_volumes_attached, - volume_checked: b.volume_checked, - volume_within_tolerance: b.volume_within_tolerance, - volume_mismatched: b.volume_mismatched, - }; - assert_eq!(actual, exp, "{ctx}: rekey / cross-check counters"); - assert_eq!(with.qm_rekey.qm_in, u.qm_docs.len(), "{ctx}"); - assert_eq!(with.qm_prices_decode.rejected_total(), u.qm_rejected, "{ctx}"); - assert_eq!(b.rows_out, u.bars.len(), "{ctx}: every bar is a mapped EOD source"); - assert_readme_qm_invariants(&with, &ctx); - - // Every class must actually be exercised, or the differential proves little. - assert!(exp.qm_unmapped_qm > 0 && exp.qm_no_eod_partner > 0, "{ctx}"); - assert!(exp.volume_within_tolerance > 0 && exp.volume_mismatched > 0, "{ctx}"); - assert!(exp.qm_volumes_attached > exp.qm_attached, "{ctx}: alias fan-out"); - assert!(u.qm_rejected > 0, "{ctx}"); - - // Worst-100 mismatch-sample list in builder order (cap applied to the reference too). - let mut exp_mismatches = exp_mismatches; - exp_mismatches.truncate(100); - let got: Vec<(String, i32, f64)> = with - .mismatch_samples - .iter() - .map(|s| (s.key.to_string(), s.session_date, s.rel)) - .collect(); - assert_eq!(got.len(), exp_mismatches.len(), "{ctx}"); - for (g, e) in got.iter().zip(&exp_mismatches) { - assert_eq!((&g.0, g.1), (&e.0, e.1), "{ctx}: sample order"); - assert_eq!(g.2.to_bits(), e.2.to_bits(), "{ctx}: rel for {}@{}", e.0, e.1); - } - for s in &with.mismatch_samples { - let vol = u.bars[&(s.key.to_string(), s.session_date)]; - assert_eq!(s.volume.to_bits(), vol.to_bits(), "{ctx}: sample volume"); - } - - // Input order does not matter. - assert_eq!(rev.qm_rekey, with.qm_rekey, "{ctx}"); - assert_eq!(rev.curate_stats, with.curate_stats, "{ctx}"); - assert_eq!(rev.mismatch_samples, with.mismatch_samples, "{ctx}"); - - // Read-only: Parquet bytes identical with, without, and with reversed QM input. - let base_bytes = dataset_bytes(&dir.join("out_base")); - assert_eq!(dataset_bytes(&dir.join("out_qm")), base_bytes, "{ctx}"); - assert_eq!(dataset_bytes(&dir.join("out_rev")), base_bytes, "{ctx}"); - assert_eq!(base.write_stats, with.write_stats, "{ctx}"); - assert!(!base.qm_prices_present); - assert_eq!(base.curate_stats.builder.qm_rows_in, 0); - assert_eq!(base.curate_stats.builder.volume_checked, 0); - } -} - -// --------------------------------------------------------------------------------------------- -// 2. Inclusive date boundaries on both mapping ranges. -// --------------------------------------------------------------------------------------------- - -#[test] -fn qm_and_eod_mapping_boundaries_are_inclusive() { - let dir = TempDir::new("bounds"); - let d = |n: i32| day(2023, 3, 1) + n; - // EOD key covers [d(2), d(5)]; QM key covers [d(1), d(4)]. - write( - &dir.join("provider_mapping.tsv"), - mapping_tsv(&[ - mrow("eod", "B.US", d(2), Some(d(5)), 11), - mrow("qm", "QB", d(1), Some(d(4)), 11), - ]) - .as_bytes(), - ); - write(&dir.join("listing_currencies.tsv"), b"11\tUSD\n"); - let eod: Vec = (0..8).flat_map(|n| eod_doc("B.US", &ymd(d(n)), 10.0, 1_000.0)).collect(); - write(&dir.join("eodPrices.bson"), &eod); - write(&dir.join("qmSplits.bson"), b""); - let qm: Vec = (0..8).flat_map(|n| qm_doc("QB", &ymd(d(n)), 1_000.0)).collect(); - write(&dir.join("qmPrices.bson"), &qm); - - let r = run_curate_bars_1d(&args_for(&dir, "out", Some("qmPrices.bson"))).unwrap(); - // d0, d5, d6, d7 outside QM range -> unmapped (4); - // d1 mapped but before EOD valid_from -> no partner (1); - // d2..=d4 attached (3). - assert_eq!(r.qm_rekey.qm_in, 8); - assert_eq!(r.qm_rekey.qm_unmapped_qm, 4); - assert_eq!(r.qm_rekey.qm_no_eod_partner, 1); - assert_eq!(r.qm_rekey.qm_attached, 3); - assert_eq!(r.qm_rekey.qm_volumes_attached, 3); - let b = &r.curate_stats.builder; - assert_eq!(b.rows_out, 8); - assert_eq!(b.volume_checked, 3); - assert_eq!(b.volume_within_tolerance, 3); - assert_eq!(b.volume_unchecked, 5); - assert_readme_qm_invariants(&r, "bounds"); -} - -// --------------------------------------------------------------------------------------------- -// 3. `--rel-tolerance`, empty file and validly framed corrupt document. -// --------------------------------------------------------------------------------------------- - -fn write_single_listing(dir: &TempDir, qm: &[u8]) { - write( - &dir.join("provider_mapping.tsv"), - b"eod\tT.US\t2020-01-01\t\t21\nqm\tQT\t2020-01-01\t\t21\n", - ); - write(&dir.join("listing_currencies.tsv"), b"21\tUSD\n"); - let eod = [ - eod_doc("T.US", "2024-01-02", 10.0, 1_000.0), - eod_doc("T.US", "2024-01-03", 10.0, 1_000.0), - eod_doc("T.US", "2024-01-04", 10.0, 1_000.0), - ] - .concat(); - write(&dir.join("eodPrices.bson"), &eod); - write(&dir.join("qmSplits.bson"), b""); - write(&dir.join("qmPrices.bson"), qm); -} - -#[test] -fn rel_tolerance_flag_governs_cross_check_without_touching_parquet() { - let dir = TempDir::new("tol"); - // rel = |1000 - 980| / 980 = 0.020408...; rel = |1000 - 1060| / 1060 = 0.056603... - let qm = [ - qm_doc("QT", "2024-01-02", 1_000.0), - qm_doc("QT", "2024-01-03", 980.0), - qm_doc("QT", "2024-01-04", 1_060.0), - ] - .concat(); - write_single_listing(&dir, &qm); - - let default = run_curate_bars_1d(&args_for(&dir, "out_default", Some("qmPrices.bson"))).unwrap(); - let mut loose_args = args_for(&dir, "out_loose", Some("qmPrices.bson")); - loose_args.rel_tolerance = 0.05; - let loose = run_curate_bars_1d(&loose_args).unwrap(); - - let bd = &default.curate_stats.builder; - assert_eq!((bd.volume_within_tolerance, bd.volume_mismatched), (1, 2)); - let bl = &loose.curate_stats.builder; - assert_eq!((bl.volume_within_tolerance, bl.volume_mismatched), (2, 1)); - assert_eq!(loose.mismatch_samples.len(), 1); - assert_eq!(loose.mismatch_samples[0].session_date, day(2024, 1, 4)); - assert_eq!( - loose.mismatch_samples[0].rel.to_bits(), - (60.0_f64 / 1_060.0).to_bits() - ); - assert_eq!(bl.max_rel_diff.to_bits(), (60.0_f64 / 1_060.0).to_bits()); - assert_readme_qm_invariants(&default, "tol default"); - assert_readme_qm_invariants(&loose, "tol loose"); - assert_eq!( - dataset_bytes(&dir.join("out_default")), - dataset_bytes(&dir.join("out_loose")) - ); -} - -#[test] -fn empty_qm_prices_file_runs_check_with_zero_observations() { - let dir = TempDir::new("empty"); - write_single_listing(&dir, b""); - let base = run_curate_bars_1d(&args_for(&dir, "out_base", None)).unwrap(); - let r = run_curate_bars_1d(&args_for(&dir, "out_qm", Some("qmPrices.bson"))).unwrap(); - assert!(r.qm_prices_present, "an empty file is a supplied input, not absent"); - assert_eq!(r.qm_prices_docs_framed, 0); - assert_eq!(r.qm_prices_bytes_read, 0); - assert_eq!(r.qm_rekey.qm_in, 0); - assert_eq!(r.curate_stats.builder.volume_checked, 0); - assert_eq!(r.curate_stats.builder.volume_unchecked, 3); - assert!(r.mismatch_samples.is_empty()); - assert_readme_qm_invariants(&r, "empty"); - assert_eq!(r.curate_stats, base.curate_stats); - assert_eq!(dataset_bytes(&dir.join("out_qm")), dataset_bytes(&dir.join("out_base"))); -} - -#[test] -fn validly_framed_corrupt_qm_document_is_counted_not_fatal() { - let dir = TempDir::new("corrupt-doc"); - let good = qm_doc("QT", "2024-01-02", 1_000.0); - let mut bad = RawDocumentBuf::new(); - bad.append(cstr!("qmSearchCode"), "QT"); - bad.append(cstr!("date"), "2024-01-03"); - bad.append(cstr!("sharevolume"), 1_000.0_f64); - bad.append(cstr!("zz"), "x"); - let mut bad = bad.into_bytes(); - let pos = bad.windows(3).position(|w| w == b"zz\0").expect("zz key"); - bad[pos - 1] = 0x7E; // invalid element type; outer length prefix still valid - let tail = qm_doc("QT", "2024-01-04", 1_000.0); - write_single_listing(&dir, &[good, bad, tail].concat()); - - let r = run_curate_bars_1d(&args_for(&dir, "out", Some("qmPrices.bson"))).unwrap(); - assert_eq!(r.qm_prices_decode.docs_in, 3); - assert_eq!(r.qm_prices_decode.rejected_corrupt_document, 1); - assert_eq!(r.qm_rekey.qm_attached, 2); - assert_eq!(r.curate_stats.builder.volume_within_tolerance, 2); - assert_readme_qm_invariants(&r, "corrupt-doc"); -} - -// --------------------------------------------------------------------------------------------- -// 4. Binary stdout: pre-existing lines unchanged, README invariants, exact mismatch line. -// --------------------------------------------------------------------------------------------- - -fn run_bin(args: &[&str]) -> Output { - Command::new(env!("CARGO_BIN_EXE_curate-etl")) - .args(args) - .output() - .expect("spawn curate-etl") -} - -fn bin_args<'a>(dir: &'a TempDir, out: &'a Path, qm: Option<&'a Path>) -> Vec { - let mut v: Vec = vec![ - "curate-bars-1d".into(), - "--eod-prices".into(), - dir.join("eodPrices.bson").display().to_string(), - "--qm-splits".into(), - dir.join("qmSplits.bson").display().to_string(), - "--provider-mapping".into(), - dir.join("provider_mapping.tsv").display().to_string(), - "--listing-currencies".into(), - dir.join("listing_currencies.tsv").display().to_string(), - "--out".into(), - out.display().to_string(), - ]; - if let Some(q) = qm { - v.push("--qm-prices".into()); - v.push(q.display().to_string()); - } - v -} - -/// Parses `section: k=v k=v` lines into `"section.k" -> v` (integer values only). -fn parse_summary(stdout: &str) -> HashMap { - let mut map = HashMap::new(); - for line in stdout.lines() { - let Some((section, rest)) = line.trim().split_once(':') else { - continue; - }; - if section == "qm_mismatch" { - continue; - } - for tok in rest.split_whitespace() { - let tok = tok.trim_start_matches('(').trim_end_matches(')'); - if let Some((k, v)) = tok.split_once('=') { - if let Ok(n) = v.parse::() { - map.insert(format!("{section}.{k}"), n); - } - } - } - } - map -} - -#[test] -fn binary_report_keeps_existing_lines_and_prints_exact_hand_calculated_mismatch() { - let dir = TempDir::new("bin"); - write( - &dir.join("provider_mapping.tsv"), - b"eod\tNVDA.US\t2020-01-01\t\t101\nqm\tNVDA\t2020-01-01\t\t101\n", - ); - write(&dir.join("listing_currencies.tsv"), b"101\tUSD\n"); - // 10:1 forward split effective 2024-06-10. - write(&dir.join("qmSplits.bson"), &split_doc("NVDA", "2024-06-10", 10.0)); - // Adjusted volumes; hand ledger of raw = adjusted / 10 before the ex-date: - // 2024-06-06: 400_000_000 / 10 = 40_000_000 vs QM 38_000_000 -> rel 2/38 = 0.052632 (mismatch) - // 2024-06-07: 412_390_000 / 10 = 41_239_000 vs QM 41_239_000 -> rel 0 (within) - // 2024-06-10: 314_162_700 (ex-date, factor 1) vs QM 314_162_700 -> within - let eod = [ - eod_doc("NVDA.US", "2024-06-06", 1210.0, 400_000_000.0), - eod_doc("NVDA.US", "2024-06-07", 1208.88, 412_390_000.0), - eod_doc("NVDA.US", "2024-06-10", 121.79, 314_162_700.0), - ] - .concat(); - write(&dir.join("eodPrices.bson"), &eod); - let qm = [ - qm_doc("NVDA", "2024-06-06", 38_000_000.0), - qm_doc("NVDA", "2024-06-07", 41_239_000.0), - qm_doc("NVDA", "2024-06-10", 314_162_700.0), - qm_doc("UNKNOWN", "2024-06-10", 1.0), - qm_doc_str_volume("NVDA", "2024-06-11"), - ] - .concat(); - let qm_path = dir.join("qmPrices.bson"); - write(&qm_path, &qm); - - let out_a = dir.join("out_a"); - let out_b = dir.join("out_b"); - let a = run_bin( - &bin_args(&dir, &out_a, None) - .iter() - .map(String::as_str) - .collect::>(), - ); - let b = run_bin( - &bin_args(&dir, &out_b, Some(&qm_path)) - .iter() - .map(String::as_str) - .collect::>(), - ); - assert!(a.status.success(), "stderr: {}", String::from_utf8_lossy(&a.stderr)); - assert!(b.status.success(), "mismatch must not fail the run: {}", String::from_utf8_lossy(&b.stderr)); - let sa = String::from_utf8(a.stdout).unwrap(); - let sb = String::from_utf8(b.stdout).unwrap(); - - // Pre-existing lines are byte-identical; output paths differ only by out dir name. - let keep = |s: &str, out: &Path| -> Vec { - s.lines() - .filter(|l| { - let t = l.trim_start(); - !t.starts_with("qm_") && !t.starts_with("timing:") - }) - .map(|l| l.replace(&out.display().to_string(), "")) - .collect() - }; - assert_eq!(keep(&sa, &out_a), keep(&sb, &out_b)); - assert!(sa.contains(" qm_check: qm_prices=absent\n"), "{sa}"); - assert!(!sb.contains("qm_prices=absent"), "{sb}"); - assert!(!sa.contains("qm_mismatch:") && !sa.contains("qm_rekey:"), "{sa}"); - - let m = parse_summary(&sb); - let g = |k: &str| *m.get(k).unwrap_or_else(|| panic!("missing {k} in:\n{sb}")); - assert_eq!(g("qm_bson.docs_framed"), 5); - assert_eq!(g("qm_bson.docs_in"), g("qm_bson.decoded") + g("qm_bson.rejected")); - assert_eq!(g("qm_bson.wrong_type"), 1); - assert_eq!( - g("qm_rekey.qm_in"), - g("qm_rekey.qm_attached") - + g("qm_rekey.qm_unmapped_qm") - + g("qm_rekey.qm_no_eod_partner") - + g("qm_bson.rejected") - ); - assert_eq!(g("qm_rekey.qm_unmapped_qm"), 1); - assert_eq!(g("qm_rekey.qm_volumes_attached"), g("qm_check.qm_rows_in")); - assert_eq!( - g("qm_check.volume_checked") + g("qm_check.volume_unchecked"), - g("builder.rows_out") - ); - assert_eq!( - g("qm_check.volume_within_tolerance") + g("qm_check.volume_mismatched"), - g("qm_check.volume_checked") - ); - assert_eq!(g("qm_check.volume_within_tolerance"), 2); - assert_eq!(g("qm_check.volume_mismatched"), 1); - assert_eq!(g("qm_check.mismatch_samples"), 1); - - let mismatch_lines: Vec<&str> = sb.lines().filter(|l| l.contains("qm_mismatch:")).collect(); - assert_eq!( - mismatch_lines, - vec![ - " qm_mismatch: key=NVDA.US session_date=2024-06-06 volume=40000000.000000 share_volume=38000000.000000 rel=0.052632" - ] - ); - assert!(sb.contains("max_rel_diff=0.052632"), "{sb}"); - - assert_eq!(dataset_bytes(&out_a), dataset_bytes(&out_b)); -} diff --git a/tools/curate-etl/tests/run_curate_corporate_actions_qa_contract.rs b/tools/curate-etl/tests/run_curate_corporate_actions_qa_contract.rs deleted file mode 100644 index 7a0c1c2a..00000000 --- a/tools/curate-etl/tests/run_curate_corporate_actions_qa_contract.rs +++ /dev/null @@ -1,610 +0,0 @@ -//! QA contract tests for the `curate-corporate-actions` command (T-112 / M1.2ab). -//! -//! Exercises only the public crate API and the built binary, and checks the runner against a -//! hand-computed oracle instead of the crate's own stage: -//! - file -> Parquet output equals hand-written expected rows (all 11 columns, bit-exact), with -//! `known_at` checked against literal UTC instants for 16:00 ET in EST and EDT, late declarations -//! clamped to `ex_date` (no look-ahead), `usdFxRate` ignored, `1:1` / `0.0` cash dropped, an OTC -//! transfer across an ended outgoing range, ticker reuse, foreign mapping sources ignored, and a -//! delisting whose `from_listing_id` disagrees with the mapping dropped; -//! - the binary prints the deterministic report, exits 0, and the report counters agree with the -//! oracle fixture; -//! - binary runtime failure on a bad delistings TSV row: single-line stderr with `path:line:`, -//! exit 1, no usage text, `--out` not created; -//! - a corrupt BSON document in the middle of `qmSplits` fails the binary and leaves the previous -//! dataset byte-identical. - -use std::borrow::Cow; -use std::fs::{self, File}; -use std::io::Write; -use std::path::{Path, PathBuf}; -use std::process::Command; -use std::sync::atomic::{AtomicU64, Ordering}; - -use bson::raw::{cstr, RawDocumentBuf}; -use parquet::column::reader::ColumnReader; -use parquet::file::reader::{FileReader, SerializedFileReader}; - -use curate_etl::{ - run_curate_corporate_actions, ymd_to_epoch_days, CorporateActionKind, - CorporateActionsParquetRow, CurateCorporateActionsArgs, KnownAtSource, -}; - -const MICROS_PER_DAY: i64 = 86_400_000_000; -const MICROS_PER_HOUR: i64 = 3_600_000_000; - -static SEQ: AtomicU64 = AtomicU64::new(0); - -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-run-ca-qa-{tag}-{}-{seq}", - std::process::id() - )); - let _ = fs::remove_dir_all(&path); - fs::create_dir_all(&path).expect("create temp dir"); - Self(path) - } - - fn join(&self, name: &str) -> PathBuf { - self.0.join(name) - } -} - -impl Drop for TempDir { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.0); - } -} - -fn write_file(path: &Path, bytes: &[u8]) { - File::create(path) - .and_then(|mut f| f.write_all(bytes)) - .expect("write fixture"); -} - -fn days(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).expect("valid date") -} - -/// 16:00 EST == 21:00 UTC. -fn close_est(day: i32) -> i64 { - i64::from(day) * MICROS_PER_DAY + 21 * MICROS_PER_HOUR -} - -/// 16:00 EDT == 20:00 UTC. -fn close_edt(day: i32) -> i64 { - i64::from(day) * MICROS_PER_DAY + 20 * MICROS_PER_HOUR -} - -fn split_doc(code: &str, date: &str, declared: Option<&str>, ratio: f64) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), code); - doc.append(cstr!("date"), date); - if let Some(d) = declared { - doc.append(cstr!("declared"), d); - } - if ratio.is_finite() && ratio > 0.0 { - doc.append(cstr!("splitratio"), 1.0 / ratio); - doc.append(cstr!("forfactor"), 1.0_f64); - doc.append(cstr!("tofactor"), ratio); - } else { - doc.append(cstr!("splitratio"), ratio); - } - doc.append(cstr!("usdFxRate"), 1_i32); - doc.into_bytes() -} - -fn div_doc(code: &str, date: &str, declared: Option<&str>, cash: f64, currency: &str) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), code); - doc.append(cstr!("date"), date); - if let Some(d) = declared { - doc.append(cstr!("declared"), d); - } - doc.append(cstr!("amount"), cash); - doc.append(cstr!("currency"), currency); - // Deliberately bogus for CAD: must have no effect on the output. - doc.append(cstr!("usdFxRate"), 1_i32); - doc.into_bytes() -} - -const MAPPING_TSV: &str = "\ -qm\tAAPL:US\t1970-01-01\t\t1\n\ -qm\tXYZ:CA\t1970-01-01\t\t2\n\ -qm\tSIVB:US\t1970-01-01\t2023-03-27\t3\n\ -qm\tSIVB:US\t2024-01-01\t\t30\n\ -qm\tSIVBQ:US\t2023-03-28\t\t4\n\ -qm\tDEAD:US\t1970-01-01\t\t5\n\ -qm\tGONE:US\t1970-01-01\t\t6\n\ -eod\tAAPL:US\t1970-01-01\t\t99\n\ -eod\tNOTQM:US\t1970-01-01\t\t98\n"; - -const DELISTINGS_TSV: &str = "\ -SIVB:US\t2023-03-28\t3\tSIVBQ:US\t\n\ -DEAD:US\t2021-11-10\t\t\t-0.3\n\ -GONE:US\t2022-03-01\t6\t\t-1.0\n\ -SIVB:US\t2024-06-03\t\t\t-1.0\n\ -AAPL:US\t2022-05-02\t7\t\t-0.5\n\ -NOTQM:US\t2022-05-02\t\t\t-1.0\n"; - -struct Fixture { - _dir: TempDir, - args: CurateCorporateActionsArgs, -} - -fn oracle_fixture(tag: &str) -> Fixture { - let dir = TempDir::new(tag); - let mut splits = Vec::new(); - splits.extend(split_doc("AAPL:US", "2020-08-31", Some("2020-07-30"), 4.0)); - splits.extend(split_doc("XYZ:CA", "2020-01-15", None, 0.05)); - splits.extend(split_doc("AAPL:US", "2021-01-04", Some("2020-12-01"), 1.0)); - splits.extend(split_doc("UNMAPPED:US", "2020-05-05", None, 2.0)); - let mut divs = Vec::new(); - divs.extend(div_doc( - "AAPL:US", - "2020-02-07", - Some("2020-01-28"), - 0.77, - "USD", - )); - divs.extend(div_doc( - "XYZ:CA", - "2020-06-15", - Some("2020-06-20"), - 0.5, - "CAD", - )); - divs.extend(div_doc("AAPL:US", "2020-05-08", None, 0.0, "USD")); - - let args = CurateCorporateActionsArgs { - qm_splits: dir.join("qmSplits.bson"), - qm_dividends: dir.join("qmDividends.bson"), - provider_mapping: dir.join("provider_mapping.tsv"), - delistings: Some(dir.join("delistings.tsv")), - out_dir: dir.join("out"), - }; - write_file(&args.qm_splits, &splits); - write_file(&args.qm_dividends, &divs); - write_file(&args.provider_mapping, MAPPING_TSV.as_bytes()); - write_file(args.delistings.as_ref().unwrap(), DELISTINGS_TSV.as_bytes()); - Fixture { _dir: dir, args } -} - -fn row( - listing_id: i32, - ex_date: i32, - declared_date: Option, - kind: CorporateActionKind, -) -> CorporateActionsParquetRow { - CorporateActionsParquetRow { - listing_id, - ex_date, - declared_date, - kind, - ratio: None, - cash_amount: None, - currency: None, - successor_listing_id: None, - terminal_return: None, - known_at_micros: 0, - known_at_source: KnownAtSource::ExDateFallback, - } -} - -/// Hand-computed expected output for [`oracle_fixture`], sorted by `(listing_id, ex_date, kind)`. -fn oracle_rows() -> Vec { - use CorporateActionKind::*; - vec![ - // AAPL dividend, declared 2020-01-28 (EST). - CorporateActionsParquetRow { - cash_amount: Some(0.77), - currency: Some(Cow::Borrowed("USD")), - known_at_micros: close_est(days(2020, 1, 28)), - known_at_source: KnownAtSource::DeclaredDate, - ..row(1, days(2020, 2, 7), Some(days(2020, 1, 28)), Dividend) - }, - // AAPL 4:1 split, declared 2020-07-30 (EDT). - CorporateActionsParquetRow { - ratio: Some(4.0), - known_at_micros: close_edt(days(2020, 7, 30)), - known_at_source: KnownAtSource::DeclaredDate, - ..row(1, days(2020, 8, 31), Some(days(2020, 7, 30)), Split) - }, - // XYZ 1:20 reverse split, no declared -> ex_date fallback (EST). - CorporateActionsParquetRow { - ratio: Some(0.05), - known_at_micros: close_est(days(2020, 1, 15)), - known_at_source: KnownAtSource::ExDateFallback, - ..row(2, days(2020, 1, 15), None, Split) - }, - // XYZ CAD dividend declared after ex_date -> clamped to ex_date (EDT), no look-ahead. - CorporateActionsParquetRow { - cash_amount: Some(0.5), - currency: Some(Cow::Borrowed("CAD")), - known_at_micros: close_edt(days(2020, 6, 15)), - known_at_source: KnownAtSource::ExDateFallback, - ..row(2, days(2020, 6, 15), Some(days(2020, 6, 20)), Dividend) - }, - // SIVB -> SIVBQ OTC transfer across the ended outgoing range (EDT; DST began 2023-03-12). - CorporateActionsParquetRow { - successor_listing_id: Some(4), - known_at_micros: close_edt(days(2023, 3, 28)), - known_at_source: KnownAtSource::DelistDate, - ..row(3, days(2023, 3, 28), None, OtcDelistTransfer) - }, - // DEAD -0.3 terminal (EST; DST ended 2021-11-07). - CorporateActionsParquetRow { - terminal_return: Some(-0.3), - known_at_micros: close_est(days(2021, 11, 10)), - known_at_source: KnownAtSource::DelistDate, - ..row(5, days(2021, 11, 10), None, Delisting) - }, - // GONE -1.0 terminal with matching from_listing_id (EST). - CorporateActionsParquetRow { - terminal_return: Some(-1.0), - known_at_micros: close_est(days(2022, 3, 1)), - known_at_source: KnownAtSource::DelistDate, - ..row(6, days(2022, 3, 1), None, Delisting) - }, - // Reused SIVB ticker resolves to the new occupant on 2024-06-03 (EDT). - CorporateActionsParquetRow { - terminal_return: Some(-1.0), - known_at_micros: close_edt(days(2024, 6, 3)), - known_at_source: KnownAtSource::DelistDate, - ..row(30, days(2024, 6, 3), None, Delisting) - }, - ] -} - -fn expand(vals: Vec, defs: Vec, n: usize) -> Vec> { - if defs.is_empty() { - assert_eq!(vals.len(), n); - return vals.into_iter().map(Some).collect(); - } - assert_eq!(defs.len(), n); - let mut it = vals.into_iter(); - let out = defs - .iter() - .map(|&d| if d == 0 { None } else { it.next() }) - .collect(); - assert!(it.next().is_none(), "every value consumed"); - out -} - -fn parse_kind(s: &str) -> CorporateActionKind { - match s { - "split" => CorporateActionKind::Split, - "dividend" => CorporateActionKind::Dividend, - "otc_delist_transfer" => CorporateActionKind::OtcDelistTransfer, - "delisting" => CorporateActionKind::Delisting, - other => panic!("unexpected kind {other:?}"), - } -} - -fn parse_source(s: &str) -> KnownAtSource { - match s { - "declared_date" => KnownAtSource::DeclaredDate, - "ex_date_fallback" => KnownAtSource::ExDateFallback, - "delist_date" => KnownAtSource::DelistDate, - other => panic!("unexpected known_at_source {other:?}"), - } -} - -fn read_rows(path: &Path) -> Vec { - let reader = SerializedFileReader::new(File::open(path).expect("open")).expect("reader"); - let meta = reader.metadata(); - let mut out = Vec::new(); - for rg in 0..meta.num_row_groups() { - let rg_reader = reader.get_row_group(rg).expect("rg"); - let n = meta.row_group(rg).num_rows() as usize; - let i32s = |idx: usize| -> Vec> { - let (mut v, mut d) = (Vec::new(), Vec::new()); - let ColumnReader::Int32ColumnReader(mut r) = - rg_reader.get_column_reader(idx).expect("col") - else { - panic!("expected INT32 at {idx}"); - }; - r.read_records(n, Some(&mut d), None, &mut v).expect("read"); - expand(v, d, n) - }; - let f64s = |idx: usize| -> Vec> { - let (mut v, mut d) = (Vec::new(), Vec::new()); - let ColumnReader::DoubleColumnReader(mut r) = - rg_reader.get_column_reader(idx).expect("col") - else { - panic!("expected DOUBLE at {idx}"); - }; - r.read_records(n, Some(&mut d), None, &mut v).expect("read"); - expand(v, d, n) - }; - let i64s = |idx: usize| -> Vec> { - let (mut v, mut d) = (Vec::new(), Vec::new()); - let ColumnReader::Int64ColumnReader(mut r) = - rg_reader.get_column_reader(idx).expect("col") - else { - panic!("expected INT64 at {idx}"); - }; - r.read_records(n, Some(&mut d), None, &mut v).expect("read"); - expand(v, d, n) - }; - let strs = |idx: usize| -> Vec> { - let (mut v, mut d) = (Vec::new(), Vec::new()); - let ColumnReader::ByteArrayColumnReader(mut r) = - rg_reader.get_column_reader(idx).expect("col") - else { - panic!("expected BYTE_ARRAY at {idx}"); - }; - r.read_records(n, Some(&mut d), None, &mut v).expect("read"); - let v = v - .into_iter() - .map(|b| String::from_utf8(b.data().to_vec()).expect("utf8")) - .collect(); - expand(v, d, n) - }; - let (lid, ed, decl, kind) = (i32s(0), i32s(1), i32s(2), strs(3)); - let (ratio, cash, cur, succ) = (f64s(4), f64s(5), strs(6), i32s(7)); - let (tr, ka, src) = (f64s(8), i64s(9), strs(10)); - for i in 0..n { - out.push(CorporateActionsParquetRow { - listing_id: lid[i].expect("listing_id"), - ex_date: ed[i].expect("ex_date"), - declared_date: decl[i], - kind: parse_kind(kind[i].as_deref().expect("kind")), - ratio: ratio[i], - cash_amount: cash[i], - currency: cur[i].clone().map(Cow::Owned), - successor_listing_id: succ[i], - terminal_return: tr[i], - known_at_micros: ka[i].expect("known_at"), - known_at_source: parse_source(src[i].as_deref().expect("source")), - }); - } - } - out -} - -fn bits(v: Option) -> Option { - v.map(f64::to_bits) -} - -fn assert_rows_bitwise( - actual: &[CorporateActionsParquetRow], - expected: &[CorporateActionsParquetRow], -) { - assert_eq!(actual.len(), expected.len(), "row count: {actual:#?}"); - 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.ex_date, e.ex_date, "row {i} ex_date"); - assert_eq!(a.declared_date, e.declared_date, "row {i} declared_date"); - assert_eq!(a.kind, e.kind, "row {i} kind"); - assert_eq!(bits(a.ratio), bits(e.ratio), "row {i} ratio"); - assert_eq!( - bits(a.cash_amount), - bits(e.cash_amount), - "row {i} cash_amount" - ); - assert_eq!(a.currency, e.currency, "row {i} currency"); - assert_eq!( - a.successor_listing_id, e.successor_listing_id, - "row {i} successor" - ); - assert_eq!( - bits(a.terminal_return), - bits(e.terminal_return), - "row {i} terminal_return" - ); - assert_eq!( - a.known_at_micros, e.known_at_micros, - "row {i} known_at_micros" - ); - assert_eq!( - a.known_at_source, e.known_at_source, - "row {i} known_at_source" - ); - } -} - -fn part_path(out_dir: &Path) -> PathBuf { - out_dir.join("corporate_actions").join("part.parquet") -} - -fn dir_names(dir: &Path) -> Vec { - let mut names: Vec = fs::read_dir(dir) - .expect("read dir") - .map(|e| e.expect("entry").file_name().to_string_lossy().into_owned()) - .collect(); - names.sort(); - names -} - -fn bin() -> Command { - Command::new(env!("CARGO_BIN_EXE_curate-etl")) -} - -fn cli_args(args: &CurateCorporateActionsArgs) -> Vec { - let mut v = vec![ - "curate-corporate-actions".to_string(), - format!("--qm-splits={}", args.qm_splits.display()), - format!("--qm-dividends={}", args.qm_dividends.display()), - format!("--provider-mapping={}", args.provider_mapping.display()), - format!("--out={}", args.out_dir.display()), - ]; - if let Some(d) = &args.delistings { - v.push(format!("--delistings={}", d.display())); - } - v -} - -#[test] -fn run_output_matches_hand_computed_oracle_rows_bit_for_bit() { - let fx = oracle_fixture("oracle"); - - let report = run_curate_corporate_actions(&fx.args).expect("run succeeds"); - - let actual = read_rows(&part_path(&fx.args.out_dir)); - assert_rows_bitwise(&actual, &oracle_rows()); - assert_eq!(report.write_stats.rows_written, 8); - assert_eq!(report.curate_stats.rows_out, 8); - // Only `part.parquet` is left in the dataset dir: no temp/lock/backup files. - assert_eq!( - dir_names(&fx.args.out_dir.join("corporate_actions")), - vec!["part.parquet".to_string()] - ); -} - -#[test] -fn run_report_counters_match_oracle_fixture_drops() { - let fx = oracle_fixture("counters"); - - let r = run_curate_corporate_actions(&fx.args).expect("run succeeds"); - - assert_eq!(r.splits_docs_framed, 4); - assert_eq!(r.splits_decode.decoded, 4); - assert_eq!(r.splits_decode.rejected_total(), 0); - assert_eq!(r.dividends_docs_framed, 3); - assert_eq!(r.dividends_decode.decoded, 3); - assert_eq!(r.delistings_rows_loaded, 6); - assert_eq!(r.delistings_bytes_read, DELISTINGS_TSV.len() as u64); - let b = &r.curate_stats.builder; - assert_eq!( - (b.splits_in, b.splits_out, b.split_noops_dropped), - (4, 3, 1) - ); - assert_eq!( - ( - b.dividends_in, - b.dividends_out, - b.dividend_zero_cash_dropped - ), - (3, 2, 1) - ); - assert_eq!( - ( - b.delistings_in, - b.otc_delist_transfers_out, - b.delistings_out - ), - (6, 1, 5) - ); - assert_eq!(b.delist_without_outcome, 0); - let c = &r.curate_stats; - assert_eq!(c.rows_in, 11); - // UNMAPPED:US split, AAPL delisting with mismatched from_listing_id 7, and NOTQM:US - // (mapped only under the foreign `eod` source). - assert_eq!(c.dropped_unmapped, 3); - assert_eq!(c.dropped_unmapped_successor, 0); - assert_eq!(c.dropped_self_successor, 0); - assert_eq!(c.dropped_known_at_out_of_range, 0); - assert_eq!( - c.listing_collision_collapsed + c.listing_collision_dropped, - 0 - ); - assert_eq!(c.rows_out, 8); - assert_eq!(c.listings_out, 6); -} - -#[test] -fn binary_happy_path_prints_report_and_writes_oracle_rows() { - let fx = oracle_fixture("bin-ok"); - - let res = bin().args(cli_args(&fx.args)).output().expect("spawn"); - - assert!( - res.status.success(), - "stderr: {}", - String::from_utf8_lossy(&res.stderr) - ); - assert!( - res.stderr.is_empty(), - "stderr: {}", - String::from_utf8_lossy(&res.stderr) - ); - let stdout = String::from_utf8(res.stdout).expect("utf8"); - assert!( - stdout.starts_with("curate-etl curate-corporate-actions\n"), - "{stdout}" - ); - for needle in [ - "delistings_tsv: rows_loaded=6", - "builder: splits_in=4 splits_out=3 split_noops=1 dividends_in=3 dividends_out=2 zero_div=1 delistings_in=6 otc_out=1 delistings_out=5 delist_no_outcome=0", - "curate: rows_in=11 rows_out=8 listings_out=6 unmapped=3", - "write: rows_written=8 files_written=1", - "timing: elapsed_secs=", - ] { - assert!(stdout.contains(needle), "missing {needle:?} in:\n{stdout}"); - } - assert_rows_bitwise(&read_rows(&part_path(&fx.args.out_dir)), &oracle_rows()); -} - -#[test] -fn binary_bad_delistings_row_fails_single_line_with_path_and_line_and_leaves_out_absent() { - let fx = oracle_fixture("bin-bad-delist"); - let delist = fx.args.delistings.clone().unwrap(); - // Line 3 sets both successor and terminal_return. - write_file( - &delist, - b"DEAD:US\t2021-11-10\t\t\t-0.3\nGONE:US\t2022-03-01\t6\t\t-1.0\nSIVB:US\t2023-03-28\t3\tSIVBQ:US\t-1.0\n", - ); - - let res = bin().args(cli_args(&fx.args)).output().expect("spawn"); - - assert_eq!(res.status.code(), Some(1)); - assert!(res.stdout.is_empty()); - let stderr = String::from_utf8(res.stderr).expect("utf8"); - assert_eq!(stderr.lines().count(), 1, "single line: {stderr}"); - assert!(stderr.starts_with("error: "), "{stderr}"); - assert!( - stderr.contains(&format!("{}:3:", delist.display())), - "path:line in {stderr}" - ); - assert!( - !stderr.contains("Usage") && !stderr.contains("usage"), - "{stderr}" - ); - assert!(!fx.args.out_dir.exists(), "--out must not be created"); -} - -#[test] -fn binary_corrupt_mid_stream_split_doc_fails_and_keeps_previous_dataset_byte_identical() { - let fx = oracle_fixture("bin-corrupt"); - run_curate_corporate_actions(&fx.args).expect("seed run"); - let before = fs::read(part_path(&fx.args.out_dir)).expect("read seeded part"); - - // Rewrite qmSplits: valid doc, then a doc whose trailing NUL is damaged (length intact), - // then another valid doc that would otherwise change the output. - let first = split_doc("AAPL:US", "2020-08-31", Some("2020-07-30"), 4.0); - let mut bad = split_doc("XYZ:CA", "2020-01-15", None, 0.05); - let last = bad.len() - 1; - bad[last] = 0x7F; - let third = split_doc("DEAD:US", "2021-01-04", None, 3.0); - let mut bytes = first.clone(); - bytes.extend(&bad); - bytes.extend(&third); - write_file(&fx.args.qm_splits, &bytes); - - let res = bin().args(cli_args(&fx.args)).output().expect("spawn"); - - assert_eq!(res.status.code(), Some(1)); - let stderr = String::from_utf8(res.stderr).expect("utf8"); - assert_eq!(stderr.lines().count(), 1, "single line: {stderr}"); - assert!( - stderr.contains(&fx.args.qm_splits.display().to_string()), - "{stderr}" - ); - assert!( - stderr.contains(&format!("byte offset {}", first.len())), - "offset of the corrupt doc in: {stderr}" - ); - assert_eq!( - fs::read(part_path(&fx.args.out_dir)).expect("read part"), - before - ); - assert_eq!( - dir_names(&fx.args.out_dir.join("corporate_actions")), - vec!["part.parquet".to_string()] - ); -} diff --git a/tools/curate-etl/tests/run_curate_events_qa_contract.rs b/tools/curate-etl/tests/run_curate_events_qa_contract.rs deleted file mode 100644 index a376eb0f..00000000 --- a/tools/curate-etl/tests/run_curate_events_qa_contract.rs +++ /dev/null @@ -1,666 +0,0 @@ -//! QA contract tests for the `curate-events` runner and the `qmFilings` / `qmEarnings` stream -//! decoders (T-115 / M1.2ae), via the public crate API and the built binary only. -//! -//! Covers gaps left by the in-crate `run_curate_events_tests.rs` / `bson_qm_events_tests.rs`: -//! - poison look-ahead through real dump files: appending absurd future filings, a restatement of -//! an earlier quarter and an inflated `consensusEps` leaves every earlier partition -//! byte-identical, and a future filing never links to an earlier earnings date; -//! - truncation: dropping every document on/after a cutoff yields exactly the earlier rows; -//! - earnings link only to a same-ET-day `8-K` / `News release` (a next-day 8-K or a same-day -//! 10-Q does not link); `known_at >= ts` and `known_at` is never earlier than the event; -//! - reruns replace partitions without leaving staging files; all-unmapped runs keep existing -//! output; non-default `--mapping-source` and key fields are honoured; -//! - wrong-type / invalid optional fields surface as JSON `null` with their counters bumped; -//! - small-chunk streaming equals the buffer decode and reports absolute corruption offsets; -//! - binary stdout counters satisfy the documented conservation invariants and runtime / usage -//! errors exit non-zero with a single-line `error:` on stderr. - -use std::fs::{self, File}; -use std::path::{Path, PathBuf}; -use std::process::{Command, Output}; -use std::sync::atomic::{AtomicU64, Ordering}; - -use bson::{rawdoc, DateTime as BsonDateTime, RawDocumentBuf}; -use curate_etl::{ - decode_qm_earning_buffer, decode_qm_earnings_stream, decode_qm_filing_buffer, - decode_qm_filings_stream, run_curate_events, ymd_to_epoch_days, BsonQmEventsError, - BsonQmEventsStreamError, BsonStreamOptions, CurateEventsArgs, CurateEventsRunReport, - QmEarningsFieldNames, QmFilingsFieldNames, RunCurateEventsError, -}; -use parquet::file::reader::{FileReader, SerializedFileReader}; -use parquet::record::RowAccessor; - -static SEQ: AtomicU64 = AtomicU64::new(0); - -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-run-curate-events-qa-{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); - } -} - -const MILLIS_PER_DAY: i64 = 86_400_000; - -fn day(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).expect("valid date") -} - -fn utc_micros(y: i32, m: u32, d: u32, hh: i64, mm: i64, ss: i64) -> i64 { - (i64::from(day(y, m, d)) * 86_400 + hh * 3_600 + mm * 60 + ss) * 1_000_000 -} - -fn bson_day(y: i32, m: u32, d: u32) -> BsonDateTime { - BsonDateTime::from_millis(i64::from(day(y, m, d)) * MILLIS_PER_DAY) -} - -fn concat(docs: &[RawDocumentBuf]) -> Vec { - docs.iter().flat_map(|d| d.as_bytes().to_vec()).collect() -} - -fn filing(key: &str, timefiled: &str, form: &str, id: &str) -> RawDocumentBuf { - rawdoc! { "symbol": key, "timefiled": timefiled, "formtype": form, "filingId": id } -} - -fn earning(key: &str, report: BsonDateTime, announce: &str, eps: f64, consensus: f64) -> RawDocumentBuf { - rawdoc! { - "qmSearchCode": key, - "reportDate": report, - "announceTime": announce, - "actualEps": eps, - "consensusEps": consensus, - } -} - -const MAPPING_TSV: &str = "qm\tAAPL\t2015-01-01\t\t101\nqm\tSHOP:CA\t2015-01-01\t\t202\n"; - -fn args(dir: &Path) -> CurateEventsArgs { - CurateEventsArgs { - qm_filings: dir.join("qmFilings.bson"), - qm_earnings: dir.join("qmEarnings.bson"), - provider_mapping: dir.join("provider_mapping.tsv"), - out_dir: dir.join("out"), - filings_key_field: "symbol".to_string(), - filings_timefiled_field: "timefiled".to_string(), - filings_form_type_field: "formtype".to_string(), - filings_filing_id_field: Some("filingId".to_string()), - filings_url_field: Some("url".to_string()), - earnings_key_field: "qmSearchCode".to_string(), - earnings_report_date_field: "reportDate".to_string(), - earnings_announce_time_field: "announceTime".to_string(), - earnings_fiscal_period_end_field: Some("periodEndDate".to_string()), - earnings_actual_eps_field: Some("actualEps".to_string()), - earnings_revenue_field: Some("revenue".to_string()), - mapping_source: "qm".to_string(), - } -} - -fn write_inputs(a: &CurateEventsArgs, mapping: &str, filings: &[RawDocumentBuf], earnings: &[RawDocumentBuf]) { - fs::write(&a.provider_mapping, mapping).expect("write mapping"); - fs::write(&a.qm_filings, concat(filings)).expect("write filings"); - fs::write(&a.qm_earnings, concat(earnings)).expect("write earnings"); -} - -#[derive(Debug, Clone, PartialEq)] -struct Row { - listing_id: i32, - ts: i64, - known_at: i64, - known_at_source: String, - kind: String, - subtype: String, - payload: String, -} - -fn part_path(out: &Path, year: i32) -> PathBuf { - out.join(format!("events/year={year}/part.parquet")) -} - -fn read_part(path: &Path) -> Vec { - let reader = SerializedFileReader::new(File::open(path).expect("open part")).expect("reader"); - let footer = reader.metadata().file_metadata().num_rows() as usize; - let rows: Vec = reader - .get_row_iter(None) - .expect("row iter") - .map(|r| { - let r = r.expect("row"); - Row { - listing_id: r.get_int(0).expect("listing_id"), - ts: r.get_timestamp_micros(1).expect("ts"), - known_at: r.get_timestamp_micros(2).expect("known_at"), - known_at_source: r.get_string(3).expect("known_at_source").clone(), - kind: r.get_string(4).expect("kind").clone(), - subtype: r.get_string(5).expect("subtype").clone(), - payload: r.get_string(6).expect("payload").clone(), - } - }) - .collect(); - assert_eq!(rows.len(), footer, "footer row count mismatch for {}", path.display()); - rows -} - -fn read_all(out: &Path) -> Vec<(i32, Row)> { - let mut years: Vec = fs::read_dir(out.join("events")) - .expect("events dir") - .filter_map(|e| { - let name = e.ok()?.file_name().to_string_lossy().into_owned(); - name.strip_prefix("year=")?.parse().ok() - }) - .collect(); - years.sort_unstable(); - years - .into_iter() - .flat_map(|y| read_part(&part_path(out, y)).into_iter().map(move |r| (y, r))) - .collect() -} - -fn assert_invariants(r: &CurateEventsRunReport) { - let b = &r.curate_stats.builder; - let c = &r.curate_stats; - assert_eq!(r.filings_docs_framed as usize, r.filings_decode.docs_in); - assert_eq!(r.filings_decode.docs_in, r.filings_decode.rows_out + r.filings_decode.skipped_total()); - assert_eq!(r.earnings_docs_framed as usize, r.earnings_decode.docs_in); - assert_eq!(r.earnings_decode.docs_in, r.earnings_decode.rows_out + r.earnings_decode.skipped_total()); - assert_eq!(r.filings_decode.rows_out, b.filings_in); - assert_eq!(r.earnings_decode.rows_out, b.earnings_in); - assert_eq!(b.earnings_out, b.earnings_linked_to_filing + b.earnings_lagged_1605); - assert_eq!(b.rows_out, b.filings_out + b.earnings_out); - assert_eq!(c.rows_in, b.rows_out); - assert_eq!(c.rows_in, c.rows_out + c.dropped_unmapped + c.listing_duplicate_collapsed); - assert_eq!(c.rows_out, c.filings_out + c.earnings_out); - assert_eq!(r.write_stats.rows_written, c.rows_out); - assert_eq!(r.write_stats.rows_by_year.values().sum::(), c.rows_out); -} - -fn base_filings() -> Vec { - vec![ - filing("AAPL", "2025-01-30T16:31:00 EST", "8-K", "A-8K-Q1"), - filing("AAPL", "2025-05-01T16:30:00 EDT", "10-Q", "A-10Q-Q2"), - filing("SHOP:CA", "2025-02-11T07:00:00 EST", "News release", "S-NR-1"), - filing("SHOP:CA", "2024-11-12T07:00:00 EST", "News release", "S-NR-0"), - ] -} - -fn base_earnings() -> Vec { - vec![ - earning("AAPL", bson_day(2025, 1, 30), "AMC", 2.40, 2.35), - earning("SHOP:CA", bson_day(2025, 2, 11), "BTO", 0.44, 0.42), - earning("AAPL", bson_day(2025, 5, 1), "AMC", 1.65, 1.60), - ] -} - -#[test] -fn poison_future_filings_restatement_and_consensus_leave_earlier_partitions_byte_identical() { - let base = TempDir::new("poison-base"); - let a = args(&base.0); - write_inputs(&a, MAPPING_TSV, &base_filings(), &base_earnings()); - let base_report = run_curate_events(&a).expect("base run"); - assert_invariants(&base_report); - assert_eq!( - base_report.write_stats.rows_by_year.keys().copied().collect::>(), - vec![2024, 2025] - ); - - let poisoned = TempDir::new("poison"); - let p = args(&poisoned.0); - let mut filings = base_filings(); - // Next-day 8-K for the 2026-03-04 earnings must not link backwards; absurd future filings. - filings.push(filing("AAPL", "2026-03-05T08:00:00 EST", "8-K", "FUTURE-8K")); - filings.push(filing("AAPL", "2026-06-01T09:00:00 EDT", "10-K/A", "RESTATE-Q1")); - filings.push(filing("SHOP:CA", "2026-01-02T09:00:00 EST", "News release", "FUTURE-NR")); - let mut earnings = base_earnings(); - earnings.push(earning("AAPL", bson_day(2026, 3, 4), "BTO", 99_999.0, -99_999.0)); - // Restated EPS for a 2025 quarter re-reported in 2026 lands on its own 2026 row only. - earnings.push(earning("SHOP:CA", bson_day(2026, 1, 2), "BTO", -42.0, 1e12)); - write_inputs(&p, MAPPING_TSV, &filings, &earnings); - let report = run_curate_events(&p).expect("poisoned run"); - assert_invariants(&report); - - for year in [2024, 2025] { - assert_eq!( - fs::read(part_path(&a.out_dir, year)).unwrap(), - fs::read(part_path(&p.out_dir, year)).unwrap(), - "year={year} changed after appending future data" - ); - } - - let rows_2026 = read_part(&part_path(&p.out_dir, 2026)); - let aapl_future_earning = rows_2026 - .iter() - .find(|r| r.kind == "earnings" && r.listing_id == 101) - .expect("2026 AAPL earnings row"); - assert_eq!(aapl_future_earning.known_at_source, "statutory_lag_estimate"); - // 2026-03-04 is EST (DST starts 2026-03-08): 16:05 EST == 21:05 UTC. - assert_eq!(aapl_future_earning.known_at, utc_micros(2026, 3, 4, 21, 5, 0)); - assert!(aapl_future_earning.payload.contains("\"linked_filing_id\":null")); - - let shop_future_earning = rows_2026 - .iter() - .find(|r| r.kind == "earnings" && r.listing_id == 202) - .expect("2026 SHOP earnings row"); - assert_eq!(shop_future_earning.known_at, utc_micros(2026, 1, 2, 14, 0, 0)); - assert!(shop_future_earning.payload.contains("\"linked_filing_id\":\"FUTURE-NR\"")); - - for (_, r) in read_all(&p.out_dir) { - assert!(!r.payload.to_ascii_lowercase().contains("consensus"), "{}", r.payload); - assert!(!r.payload.contains("99999") || r.payload.contains("\"actual_eps\":99999")); - } -} - -#[test] -fn truncation_at_cutoff_yields_exactly_the_earlier_rows() { - let full = TempDir::new("trunc-full"); - let f = args(&full.0); - let mut filings = base_filings(); - filings.push(filing("AAPL", "2025-07-31T16:30:00 EDT", "8-K", "A-8K-Q3")); - filings.push(filing("AAPL", "2025-10-30T16:30:00 EDT", "8-K", "A-8K-Q4")); - let mut earnings = base_earnings(); - earnings.push(earning("AAPL", bson_day(2025, 7, 31), "AMC", 1.57, 1.43)); - earnings.push(earning("AAPL", bson_day(2025, 10, 30), "AMC", 1.85, 1.77)); - write_inputs(&f, MAPPING_TSV, &filings, &earnings); - run_curate_events(&f).expect("full run"); - - let cutoff = utc_micros(2025, 7, 1, 0, 0, 0); - let truncated = TempDir::new("trunc"); - let t = args(&truncated.0); - write_inputs(&t, MAPPING_TSV, &base_filings(), &base_earnings()); - run_curate_events(&t).expect("truncated run"); - - let full_before: Vec<(i32, Row)> = - read_all(&f.out_dir).into_iter().filter(|(_, r)| r.ts < cutoff).collect(); - assert_eq!(full_before, read_all(&t.out_dir)); - assert_eq!(read_all(&f.out_dir).len(), full_before.len() + 4); -} - -#[test] -fn earnings_link_only_to_same_et_day_8k_or_news_release_and_known_at_never_precedes_ts() { - let tmp = TempDir::new("link-rules"); - let a = args(&tmp.0); - let filings = vec![ - // Same-ET-day periodic report: not a link candidate. - filing("AAPL", "2025-03-03T08:00:00 EST", "10-Q", "Q-SAMEDAY"), - // Next-day 8-K must not link back to 2025-03-03. - filing("AAPL", "2025-03-04T07:00:00 EST", "8-K", "8K-NEXTDAY"), - // Two same-day 8-Ks: earliest wins; amendment counts as candidate. - filing("SHOP:CA", "2025-08-06T10:00:00 EDT", "8-K", "8K-LATE"), - filing("SHOP:CA", "2025-08-06T06:45:00 EDT", "8-K/A", "8K-EARLY-A"), - // 23:30 EDT on 2025-08-07 is 03:30 UTC on 08-08: links to ET date 08-07, not 08-08. - filing("AAPL", "2025-08-07T23:30:00 EDT", "News release", "NR-LATE-ET"), - ]; - let earnings = vec![ - earning("AAPL", bson_day(2025, 3, 3), "BTO", 1.0, 1.0), - earning("SHOP:CA", bson_day(2025, 8, 6), "BTO", 0.3, 0.3), - earning("AAPL", bson_day(2025, 8, 7), "N/A", 2.0, 2.0), - earning("AAPL", bson_day(2025, 8, 8), "BTO", 3.0, 3.0), - ]; - write_inputs(&a, MAPPING_TSV, &filings, &earnings); - let report = run_curate_events(&a).expect("run"); - assert_invariants(&report); - assert_eq!(report.curate_stats.builder.earnings_linked_to_filing, 2); - assert_eq!(report.curate_stats.builder.earnings_lagged_1605, 2); - - let rows = read_all(&a.out_dir); - let earn = |date: &str| { - rows.iter() - .map(|(_, r)| r) - .find(|r| r.kind == "earnings" && r.payload.contains(&format!("\"report_date\":\"{date}\""))) - .unwrap_or_else(|| panic!("earnings {date}")) - .clone() - }; - - let mar3 = earn("2025-03-03"); - assert_eq!(mar3.known_at_source, "statutory_lag_estimate"); - assert_eq!(mar3.known_at, utc_micros(2025, 3, 3, 21, 5, 0)); - - let aug6 = earn("2025-08-06"); - assert_eq!(aug6.known_at_source, "filing_timestamp"); - assert_eq!(aug6.known_at, utc_micros(2025, 8, 6, 10, 45, 0)); - assert!(aug6.payload.contains("\"linked_filing_id\":\"8K-EARLY-A\"")); - - let aug7 = earn("2025-08-07"); - assert_eq!(aug7.known_at_source, "filing_timestamp"); - assert_eq!(aug7.known_at, utc_micros(2025, 8, 8, 3, 30, 0)); - - let aug8 = earn("2025-08-08"); - assert_eq!(aug8.known_at_source, "statutory_lag_estimate"); - assert_eq!(aug8.known_at, utc_micros(2025, 8, 8, 20, 5, 0)); - - for (year, r) in &rows { - assert!(r.known_at >= r.ts, "known_at before ts: {r:?}"); - let year_start = utc_micros(*year, 1, 1, 0, 0, 0); - let next_year_start = utc_micros(*year + 1, 1, 1, 0, 0, 0); - assert!(r.ts >= year_start && r.ts < next_year_start, "wrong UTC partition: {r:?}"); - } -} - -#[test] -fn rerun_replaces_partition_without_leftover_staging_files() { - let tmp = TempDir::new("rerun"); - let a = args(&tmp.0); - write_inputs(&a, MAPPING_TSV, &base_filings(), &base_earnings()); - run_curate_events(&a).expect("first run"); - let first_2025 = read_part(&part_path(&a.out_dir, 2025)); - - let mut filings = base_filings(); - filings.push(filing("AAPL", "2025-09-09T13:00:00 EDT", "News release", "A-NR-EVENT")); - write_inputs(&a, MAPPING_TSV, &filings, &base_earnings()); - let report = run_curate_events(&a).expect("second run"); - assert_invariants(&report); - let second_2025 = read_part(&part_path(&a.out_dir, 2025)); - assert_eq!(second_2025.len(), first_2025.len() + 1); - - for year in [2024, 2025] { - let names: Vec = fs::read_dir(a.out_dir.join(format!("events/year={year}"))) - .unwrap() - .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) - .collect(); - assert_eq!(names, vec!["part.parquet".to_string()], "year={year} leftovers: {names:?}"); - } -} - -#[test] -fn all_unmapped_run_returns_ok_and_leaves_existing_partitions_untouched() { - let tmp = TempDir::new("unmapped"); - let a = args(&tmp.0); - write_inputs(&a, MAPPING_TSV, &base_filings(), &base_earnings()); - run_curate_events(&a).expect("seed run"); - let before = fs::read(part_path(&a.out_dir, 2025)).unwrap(); - - let filings = vec![filing("ZZZ", "2025-01-30T16:31:00 EST", "8-K", "Z-1")]; - let earnings = vec![earning("ZZZ", bson_day(2025, 1, 30), "AMC", 1.0, 1.0)]; - write_inputs(&a, MAPPING_TSV, &filings, &earnings); - let report = run_curate_events(&a).expect("all unmapped run"); - assert_invariants(&report); - assert_eq!(report.curate_stats.dropped_unmapped, 2); - assert_eq!(report.write_stats.rows_written, 0); - assert_eq!(report.write_stats.files_written, 0); - assert_eq!(fs::read(part_path(&a.out_dir, 2025)).unwrap(), before); -} - -#[test] -fn custom_mapping_source_and_key_fields_resolve_only_that_namespace() { - let tmp = TempDir::new("custom-keys"); - let mut a = args(&tmp.0); - a.mapping_source = "quotemedia".to_string(); - a.filings_key_field = "qmId".to_string(); - a.earnings_key_field = "qmId".to_string(); - let mapping = "qm\tVOY:CNX\t2015-01-01\t\t999\nquotemedia\tVOY:CNX\t2015-01-01\t\t11\nquotemedia\tVOY:CC\t2015-01-01\t\t12\n"; - let filings = vec![ - rawdoc! { "qmId": "VOY:CNX", "symbol": "VOY", "timefiled": "2025-04-02T07:30:00 EDT", "formtype": "News release" }, - rawdoc! { "qmId": "VOY:CC", "symbol": "VOY", "timefiled": "2025-04-02T08:30:00 EDT", "formtype": "News release" }, - ]; - let earnings = vec![ - rawdoc! { "qmId": "VOY:CNX", "qmSearchCode": "IGNORED", "reportDate": "2025-04-02", "announceTime": "BTO" }, - rawdoc! { "qmId": "VOY:CC", "reportDate": "2025-04-02", "announceTime": "BTO" }, - ]; - write_inputs(&a, mapping, &filings, &earnings); - let report = run_curate_events(&a).expect("run"); - assert_invariants(&report); - assert_eq!(report.curate_stats.dropped_unmapped, 0); - assert_eq!(report.curate_stats.builder.earnings_linked_to_filing, 2); - - let rows = read_all(&a.out_dir); - assert!(rows.iter().all(|(_, r)| r.listing_id == 11 || r.listing_id == 12)); - let e11 = rows.iter().find(|(_, r)| r.listing_id == 11 && r.kind == "earnings").unwrap(); - let e12 = rows.iter().find(|(_, r)| r.listing_id == 12 && r.kind == "earnings").unwrap(); - assert_eq!(e11.1.known_at, utc_micros(2025, 4, 2, 11, 30, 0)); - assert_eq!(e12.1.known_at, utc_micros(2025, 4, 2, 12, 30, 0)); -} - -#[test] -fn wrong_type_and_invalid_optionals_emit_json_null_and_bump_counters() { - let tmp = TempDir::new("optionals"); - let a = args(&tmp.0); - let filings = vec![ - rawdoc! { "symbol": "AAPL", "timefiled": "2025-01-30T16:31:00 EST", "formtype": "10-K", "filingId": 42_i32, "url": true }, - ]; - let earnings = vec![ - rawdoc! { - "qmSearchCode": "AAPL", "reportDate": "2025-02-14", "announceTime": "AMC", - "periodEndDate": "2024-13-40", "actualEps": "1.23", "revenue": [1_i32], "consensusEps": 9.9, - }, - rawdoc! { - "qmSearchCode": "AAPL", "reportDate": "2025-03-14", "announceTime": "AMC", - "periodEndDate": 20_241_231_i32, "actualEps": 1_i32, "revenue": 5_i64, - }, - ]; - write_inputs(&a, MAPPING_TSV, &filings, &earnings); - let report = run_curate_events(&a).expect("run"); - assert_invariants(&report); - assert_eq!(report.filings_decode.nulled_wrong_type_filing_id, 1); - assert_eq!(report.filings_decode.nulled_wrong_type_url, 1); - assert_eq!(report.earnings_decode.nulled_invalid_fiscal_period_end, 1); - assert_eq!(report.earnings_decode.nulled_wrong_type_fiscal_period_end, 1); - assert_eq!(report.earnings_decode.nulled_wrong_type_actual_eps, 1); - assert_eq!(report.earnings_decode.nulled_wrong_type_revenue, 1); - assert_eq!(report.earnings_decode.rows_out, 2); - - let rows = read_all(&a.out_dir); - let filing_row = rows.iter().find(|(_, r)| r.kind == "filing").unwrap(); - assert!(filing_row.1.payload.contains("\"filing_id\":null"), "{}", filing_row.1.payload); - assert!(filing_row.1.payload.contains("\"url\":null"), "{}", filing_row.1.payload); - let feb = rows - .iter() - .find(|(_, r)| r.payload.contains("\"report_date\":\"2025-02-14\"")) - .unwrap(); - assert!(feb.1.payload.contains("\"actual_eps\":null"), "{}", feb.1.payload); - assert!(feb.1.payload.contains("\"fiscal_period_end\":null"), "{}", feb.1.payload); - assert!(feb.1.payload.contains("\"revenue\":null"), "{}", feb.1.payload); - assert!(!feb.1.payload.contains("9.9")); -} - -#[test] -fn small_chunk_streaming_matches_buffer_decode_and_reports_absolute_corruption_offset() { - let ff = QmFilingsFieldNames { - key: "symbol", - timefiled: "timefiled", - form_type: "formtype", - filing_id: Some("filingId"), - url: None, - }; - let ef = QmEarningsFieldNames { - key: "qmSearchCode", - report_date: "reportDate", - announce_time: "announceTime", - fiscal_period_end: None, - actual_eps: Some("actualEps"), - revenue: None, - }; - let fbytes = concat(&base_filings()); - let ebytes = concat(&base_earnings()); - - let mut buf_f = Vec::new(); - let buf_fs = decode_qm_filing_buffer(&fbytes, &ff, |r| buf_f.push(format!("{r:?}"))).unwrap(); - let mut buf_e = Vec::new(); - let buf_es = decode_qm_earning_buffer(&ebytes, &ef, |r| buf_e.push(format!("{r:?}"))).unwrap(); - - let opts = BsonStreamOptions { chunk_capacity_bytes: 64, ..BsonStreamOptions::default() }; - let mut st_f = Vec::new(); - let st_fs = - decode_qm_filings_stream(fbytes.as_slice(), opts, &ff, |r| st_f.push(format!("{r:?}"))) - .unwrap(); - let mut st_e = Vec::new(); - let st_es = - decode_qm_earnings_stream(ebytes.as_slice(), opts, &ef, |r| st_e.push(format!("{r:?}"))) - .unwrap(); - assert_eq!((buf_fs, buf_f), (st_fs, st_f)); - assert_eq!((buf_es, buf_e), (st_es, st_e)); - - // Corrupt the second filing doc: rewrite its first element type byte to an invalid tag. - let first_len = base_filings()[0].as_bytes().len(); - let mut corrupt = fbytes.clone(); - corrupt[first_len + 4] = 0xEE; - let err = decode_qm_filings_stream(corrupt.as_slice(), opts, &ff, |_| {}).unwrap_err(); - match err { - BsonQmEventsStreamError::Decode(BsonQmEventsError::CorruptBson { offset, .. }) => { - assert_eq!(offset, first_len as u64); - } - other => panic!("expected CorruptBson decode error, got {other:?}"), - } -} - -#[test] -fn corrupt_second_earnings_doc_fails_run_with_offset_and_publishes_nothing() { - let tmp = TempDir::new("corrupt-run"); - let a = args(&tmp.0); - write_inputs(&a, MAPPING_TSV, &base_filings(), &base_earnings()); - let first_len = base_earnings()[0].as_bytes().len(); - let mut bytes = concat(&base_earnings()); - bytes[first_len + 4] = 0xEE; - fs::write(&a.qm_earnings, bytes).unwrap(); - - let err = run_curate_events(&a).unwrap_err(); - match &err { - RunCurateEventsError::CorruptBson { offset, .. } => assert_eq!(*offset, first_len as u64), - other => panic!("expected CorruptBson, got {other:?}"), - } - assert_eq!(err.to_string().lines().count(), 1); - assert!(!a.out_dir.join("events").exists()); -} - -fn run_bin(args: &[&str]) -> Output { - Command::new(env!("CARGO_BIN_EXE_curate-etl")) - .args(args) - .output() - .expect("spawn curate-etl") -} - -fn counter(line: &str, key: &str) -> usize { - let needle = format!("{key}="); - line.split_whitespace() - .find_map(|tok| tok.trim_start_matches('(').strip_prefix(needle.as_str())) - .unwrap_or_else(|| panic!("missing {key} in {line}")) - .trim_end_matches(')') - .parse() - .unwrap_or_else(|_| panic!("bad {key} in {line}")) -} - -fn line<'a>(stdout: &'a str, prefix: &str) -> &'a str { - stdout - .lines() - .find(|l| l.trim_start().starts_with(prefix)) - .unwrap_or_else(|| panic!("missing {prefix} in {stdout}")) -} - -fn bin_args(a: &CurateEventsArgs) -> Vec { - vec![ - "curate-events".into(), - "--qm-filings".into(), - a.qm_filings.display().to_string(), - "--qm-earnings".into(), - a.qm_earnings.display().to_string(), - "--provider-mapping".into(), - a.provider_mapping.display().to_string(), - format!("--out={}", a.out_dir.display()), - "--filings-form-type-field=formtype".into(), - "--filings-filing-id-field".into(), - "filingId".into(), - "--earnings-actual-eps-field".into(), - "actualEps".into(), - ] -} - -#[test] -fn binary_stdout_counters_satisfy_conservation() { - let tmp = TempDir::new("bin"); - let a = args(&tmp.0); - let mut filings = base_filings(); - filings.push(filing("ZZZ", "2025-03-01T09:00:00 EST", "8-K", "Z")); - filings.push(rawdoc! { "symbol": "AAPL", "timefiled": "2025-03-01T09:00:00 PST", "formtype": "8-K" }); - filings.push(rawdoc! { "symbol": "AAPL", "timefiled": "2025-03-01T09:00:00 EST" }); - let mut earnings = base_earnings(); - earnings.push(rawdoc! { "qmSearchCode": "AAPL", "reportDate": "2025-13-01", "announceTime": "AMC" }); - write_inputs(&a, MAPPING_TSV, &filings, &earnings); - - let argv = bin_args(&a); - let out = run_bin(&argv.iter().map(String::as_str).collect::>()); - let stdout = String::from_utf8_lossy(&out.stdout).into_owned(); - assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr)); - - let fb = line(&stdout, "filings_bson:"); - assert_eq!(counter(fb, "docs_framed"), 7); - assert_eq!(counter(fb, "docs_in"), counter(fb, "rows_out") + counter(fb, "skipped")); - assert_eq!(counter(fb, "missing_form_type"), 1); - let eb = line(&stdout, "earnings_bson:"); - assert_eq!(counter(eb, "docs_in"), counter(eb, "rows_out") + counter(eb, "skipped")); - assert_eq!(counter(eb, "invalid_date"), 1); - let b = line(&stdout, "builder:"); - assert_eq!(counter(b, "filings_in"), counter(fb, "rows_out")); - assert_eq!(counter(b, "earnings_in"), counter(eb, "rows_out")); - assert_eq!(counter(b, "unknown_zone"), 1); - assert_eq!( - counter(b, "filings_in"), - counter(b, "filings_out") - + counter(b, "malformed_ts") - + counter(b, "unknown_zone") - + counter(b, "invalid_dt") - + counter(b, "filing_dup") - ); - assert_eq!(counter(b, "earnings_out"), counter(b, "linked") + counter(b, "lagged_1605")); - let c = line(&stdout, "curate:"); - assert_eq!(counter(c, "rows_in"), counter(b, "rows_out")); - assert_eq!( - counter(c, "rows_in"), - counter(c, "rows_out") + counter(c, "dropped_unmapped") + counter(c, "listing_dup_collapsed") - ); - assert_eq!(counter(c, "dropped_unmapped"), 1); - let w = line(&stdout, "write:"); - assert_eq!(counter(w, "rows_written"), counter(c, "rows_out")); - assert_eq!(read_all(&a.out_dir).len(), counter(w, "rows_written")); -} - -#[test] -fn binary_runtime_and_usage_errors_exit_nonzero_and_keep_existing_output() { - let tmp = TempDir::new("bin-errors"); - let a = args(&tmp.0); - write_inputs(&a, MAPPING_TSV, &base_filings(), &base_earnings()); - run_curate_events(&a).expect("seed run"); - let before = fs::read(part_path(&a.out_dir, 2025)).unwrap(); - - // Truncated filings file. - let mut bytes = concat(&base_filings()); - bytes.truncate(bytes.len() - 3); - fs::write(&a.qm_filings, &bytes).unwrap(); - let argv = bin_args(&a); - let out = run_bin(&argv.iter().map(String::as_str).collect::>()); - assert!(!out.status.success()); - let stderr = String::from_utf8_lossy(&out.stderr); - assert!(stderr.starts_with("error: "), "{stderr}"); - assert_eq!(stderr.trim_end().lines().count(), 1, "{stderr}"); - assert!(out.stdout.is_empty()); - assert_eq!(fs::read(part_path(&a.out_dir, 2025)).unwrap(), before); - - // Overlapping provider_mapping ranges. - fs::write(&a.qm_filings, concat(&base_filings())).unwrap(); - fs::write( - &a.provider_mapping, - "qm\tAAPL\t2015-01-01\t\t101\nqm\tAAPL\t2020-01-01\t\t102\n", - ) - .unwrap(); - let out = run_bin(&argv.iter().map(String::as_str).collect::>()); - assert!(!out.status.success()); - assert!(String::from_utf8_lossy(&out.stderr).starts_with("error: ")); - assert_eq!(fs::read(part_path(&a.out_dir, 2025)).unwrap(), before); - - // Usage error: consensusEps mapped on an earnings role. - fs::write(&a.provider_mapping, MAPPING_TSV).unwrap(); - let mut bad = argv.clone(); - bad.push("--earnings-revenue-field=consensus_EPS".into()); - let out = run_bin(&bad.iter().map(String::as_str).collect::>()); - assert!(!out.status.success()); - assert!(out.stdout.is_empty()); - assert_eq!(fs::read(part_path(&a.out_dir, 2025)).unwrap(), before); -} diff --git a/tools/curate-etl/tests/run_curate_fx_qa_contract.rs b/tools/curate-etl/tests/run_curate_fx_qa_contract.rs deleted file mode 100644 index 3ac417b8..00000000 --- a/tools/curate-etl/tests/run_curate_fx_qa_contract.rs +++ /dev/null @@ -1,416 +0,0 @@ -//! QA contract tests for the `curate-fx-1d` runner and the `teMarketData` stream decoder -//! (T-113 / M1.2ac), via the public crate API only. -//! -//! Covers gaps left by the in-crate `run_curate_fx_tests.rs` / `bson_te_market_data_tests.rs`: -//! - poison look-ahead through real dump files: appending absurd future EOD docs and TE points -//! leaves every earlier published row bit-identical; -//! - small-chunk streaming (`decode_te_market_data_stream`) yields the same bars and stats as a -//! one-shot buffer decode, and a corrupt point in a later document reports its absolute offset; -//! - `--te-symbol` validation runs before any input is opened and never creates `--out`; -//! - a selector given in lower case still matches a mixed-case `teSymbol` in the dump; -//! - non-numeric `t` (BSON `DateTime`) is a counted point reject, not a silent date guess; -//! - documented Known Limit: `CAD.FOREX` docs without `volume` are rejected, TE still publishes. - -use std::fs::{self, File}; -use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering}; - -use bson::raw::{cstr, RawArrayBuf, RawDocumentBuf}; -use bson::DateTime; -use curate_etl::{ - decode_te_market_data_buffer, decode_te_market_data_stream, run_curate_fx_1d, - ymd_to_epoch_days, BsonStreamOptions, BsonTeMarketDataError, CurateFx1dArgs, - CurateFx1dRunReport, FxDailyBar, RunCurateFxError, TE_MILLIS_PER_DAY, TE_SECONDS_PER_DAY, -}; -use parquet::file::reader::{FileReader, SerializedFileReader}; -use parquet::record::{Field, RowAccessor}; - -static SEQ: AtomicU64 = AtomicU64::new(0); - -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-run-curate-fx-qa-{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 date") -} - -fn ymd(d: i32) -> String { - // Civil-from-days (Howard Hinnant), sufficient for fixture date strings. - let z = i64::from(d) + 719_468; - let era = z.div_euclid(146_097); - let doe = z - era * 146_097; - let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; - let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); - let mp = (5 * doy + 2) / 153; - let dd = doy - (153 * mp + 2) / 5 + 1; - let mm = if mp < 10 { mp + 3 } else { mp - 9 }; - let yy = yoe + era * 400 + i64::from(mm <= 2); - format!("{yy:04}-{mm:02}-{dd:02}") -} - -fn eod_doc(code: &str, d: i32, c: f64, with_volume: bool) -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), code); - doc.append(cstr!("date"), ymd(d).as_str()); - doc.append(cstr!("open"), c); - doc.append(cstr!("high"), c + 0.004); - doc.append(cstr!("low"), c - 0.004); - doc.append(cstr!("close"), c); - if with_volume { - doc.append(cstr!("volume"), 0.0_f64); - } - doc.as_bytes().to_vec() -} - -fn te_point(d: i32, c: f64, millis: bool) -> RawDocumentBuf { - let mut pt = RawDocumentBuf::new(); - if millis { - pt.append(cstr!("t"), i64::from(d) * TE_MILLIS_PER_DAY + 79_200_000); - } else { - pt.append(cstr!("t"), (i64::from(d) * TE_SECONDS_PER_DAY + 7_200) as f64); - } - pt.append(cstr!("o"), c); - pt.append(cstr!("h"), c + 0.004); - pt.append(cstr!("l"), c - 0.004); - pt.append(cstr!("c"), c); - pt -} - -fn te_doc(symbol: &str, points: Vec) -> Vec { - let mut daily = RawArrayBuf::new(); - for p in points { - daily.push(p); - } - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("teSymbol"), symbol); - doc.append(cstr!("daily"), daily); - doc.as_bytes().to_vec() -} - -fn write_file(path: &Path, docs: &[Vec]) { - let bytes: Vec = docs.iter().flatten().copied().collect(); - fs::write(path, bytes).expect("write fixture"); -} - -fn args(dir: &Path, te_symbol: &str) -> CurateFx1dArgs { - CurateFx1dArgs { - eod_prices: dir.join("eodPrices.bson"), - te_market_data: dir.join("teMarketData.bson"), - te_symbol: te_symbol.to_string(), - out_dir: dir.join("out"), - } -} - -#[derive(Debug, Clone, PartialEq)] -struct Row { - session_date: i32, - ts: i64, - bits: [u64; 4], - source: String, - known_at: i64, -} - -fn read_rows(out_dir: &Path) -> Vec { - let file = File::open(out_dir.join("fx_1d/part.parquet")).expect("open part.parquet"); - let reader = SerializedFileReader::new(file).expect("parquet reader"); - reader - .get_row_iter(None) - .expect("row iter") - .map(|r| { - let r = r.expect("row"); - let session_date = match r.get_column_iter().nth(1).unwrap().1 { - Field::Date(d) => *d, - other => panic!("expected Date, got {other:?}"), - }; - Row { - session_date, - ts: r.get_timestamp_micros(2).unwrap(), - bits: [ - r.get_double(3).unwrap().to_bits(), - r.get_double(4).unwrap().to_bits(), - r.get_double(5).unwrap().to_bits(), - r.get_double(6).unwrap().to_bits(), - ], - source: r.get_string(7).unwrap().clone(), - known_at: r.get_timestamp_micros(8).unwrap(), - } - }) - .collect() -} - -fn assert_conserved(report: &CurateFx1dRunReport) { - assert_eq!(report.eod_docs_framed as usize, report.eod_decode.docs_in); - assert_eq!( - report.eod_decode.docs_in, - report.eod_decode.decoded + report.eod_decode.rejected_total() - ); - assert_eq!( - report.eod_decode.decoded, - report.eod_cad_forex_kept + report.eod_other_symbol_skipped - ); - assert_eq!(report.te_docs_framed as usize, report.te_decode.docs_in); - assert_eq!( - report.te_decode.docs_in, - report.te_decode.docs_matched - + report.te_decode.docs_other_symbol - + report.te_decode.docs_rejected_total() - ); - assert_eq!( - report.te_decode.points_in, - report.te_decode.points_decoded + report.te_decode.rejected_total() - ); - assert_eq!( - report.te_decode.points_decoded, - report.curate_stats.builder.te.rows_in - ); - assert_eq!(report.write_stats.rows_written, report.curate_stats.rows_out); -} - -#[test] -fn poison_future_eod_and_te_rows_leave_earlier_published_rows_bit_identical() { - // Arrange: EOD 2024-01-02..2024-01-11 with a gap on 01-05, TE overlap + gap fill + tail. - let tmp = TempDir::new("poison"); - let d0 = day(2024, 1, 2); - let mut eod: Vec> = Vec::new(); - for i in 0..10 { - if i == 3 { - continue; - } - eod.push(eod_doc("CAD.FOREX", d0 + i, 1.34 + f64::from(i) * 0.001, true)); - } - let te_points: Vec = (0..14) - .map(|i| te_point(d0 + i, 1.35 + f64::from(i) * 0.001, i % 2 == 0)) - .collect(); - let base_te = vec![te_doc("USDCAD", te_points.clone())]; - write_file(&tmp.0.join("eodPrices.bson"), &eod); - write_file(&tmp.0.join("teMarketData.bson"), &base_te); - let a = args(&tmp.0, "USDCAD"); - - // Act 1: baseline publish. - let base_report = run_curate_fx_1d(&a).expect("baseline run"); - let base_rows = read_rows(&a.out_dir); - assert_conserved(&base_report); - assert_eq!(base_rows.len(), 14); - - // Act 2: append absurd future facts in both sources (EOD on a later date, TE far tail). - let far = day(2030, 6, 3); - eod.push(eod_doc("CAD.FOREX", far, 99.0, true)); - let mut poisoned_points = te_points; - poisoned_points.push(te_point(far + 1, 77.0, true)); - poisoned_points.push(te_point(far + 2, 55.0, false)); - write_file(&tmp.0.join("eodPrices.bson"), &eod); - write_file( - &tmp.0.join("teMarketData.bson"), - &[te_doc("USDCAD", poisoned_points)], - ); - let poison_report = run_curate_fx_1d(&a).expect("poisoned run"); - let poison_rows = read_rows(&a.out_dir); - - // Assert: earlier rows unchanged bit-for-bit; only the 3 future rows are new. - assert_conserved(&poison_report); - assert_eq!(poison_rows.len(), base_rows.len() + 3); - assert_eq!(&poison_rows[..base_rows.len()], &base_rows[..]); - for r in &poison_rows { - assert_eq!(r.ts, r.known_at); - assert_eq!(r.ts, (i64::from(r.session_date) + 1) * 86_400_000_000 - 1); - } - let tail: Vec<(i32, &str)> = poison_rows[base_rows.len()..] - .iter() - .map(|r| (r.session_date, r.source.as_str())) - .collect(); - assert_eq!( - tail, - vec![ - (far, "eod_cad_forex"), - (far + 1, "te_usdcad"), - (far + 2, "te_usdcad") - ] - ); -} - -#[test] -fn small_chunk_te_stream_matches_buffer_decode_and_rebases_corrupt_point_offset() { - // Arrange: three docs (other symbol, USDCAD, usdcad) concatenated. - let d0 = day(2025, 3, 3); - let doc_a = te_doc("EURUSD", vec![te_point(d0, 1.08, true)]); - let doc_b = te_doc( - "USDCAD", - (0..20).map(|i| te_point(d0 + i, 1.40, i % 3 == 0)).collect(), - ); - let doc_c = te_doc("usdcad", vec![te_point(d0 + 30, 1.41, false)]); - let mut buf = Vec::new(); - buf.extend_from_slice(&doc_a); - buf.extend_from_slice(&doc_b); - buf.extend_from_slice(&doc_c); - let tiny = BsonStreamOptions { - chunk_capacity_bytes: 16, - ..BsonStreamOptions::default() - }; - - // Act - let mut buf_bars: Vec = Vec::new(); - let buf_stats = decode_te_market_data_buffer(&buf, "USDCAD", |b| buf_bars.push(b), |_, e| { - panic!("unexpected buffer error {e:?}") - }); - let mut stream_bars: Vec = Vec::new(); - let stream_stats = decode_te_market_data_stream( - &buf[..], - tiny, - "USDCAD", - |b| stream_bars.push(b), - |_, e| panic!("unexpected stream error {e:?}"), - ) - .expect("stream decode"); - - // Assert: identical stats and bars regardless of chunking. - assert_eq!(stream_stats, buf_stats); - assert_eq!(stream_stats.docs_in, 3); - assert_eq!(stream_stats.docs_matched, 2); - assert_eq!(stream_stats.docs_other_symbol, 1); - assert_eq!(stream_stats.points_decoded, 21); - assert_eq!(stream_bars, buf_bars); - - // Arrange: corrupt the element type byte of `c` inside the last doc's point. - let mut corrupt = buf.clone(); - let doc_c_offset = doc_a.len() + doc_b.len(); - let rel = doc_c - .windows(3) - .rposition(|w| w == b"\x01c\0") - .expect("find 'c' double element"); - corrupt[doc_c_offset + rel] = 0xEE; - - // Act - let mut errs: Vec<(u64, BsonTeMarketDataError)> = Vec::new(); - decode_te_market_data_stream(&corrupt[..], tiny, "USDCAD", |_| {}, |o, e| errs.push((o, e))) - .expect("framing still valid"); - - // Assert: the structural point error is reported at the absolute offset of doc C. - assert_eq!(errs.len(), 1, "{errs:?}"); - assert_eq!(errs[0].0, doc_c_offset as u64); - match &errs[0].1 { - BsonTeMarketDataError::CorruptPointBson { offset, point_index, .. } => { - assert_eq!(*offset, doc_c_offset); - assert_eq!(*point_index, 0); - } - other => panic!("expected CorruptPointBson, got {other:?}"), - } -} - -#[test] -fn unsupported_te_selector_is_rejected_before_opening_inputs_or_creating_out() { - let tmp = TempDir::new("selector"); - // Inputs deliberately absent: validation must fire first (InvalidTeSymbol, not OpenInput). - for bad in [" USDCAD", "USDCAD ", "USD/CAD", "USDCAD:CUR", "EURUSD", "CADUSD", ""] { - let a = args(&tmp.0, bad); - match run_curate_fx_1d(&a) { - Err(RunCurateFxError::InvalidTeSymbol { value }) => assert_eq!(value, bad), - other => panic!("selector {bad:?}: expected InvalidTeSymbol, got {other:?}"), - } - assert!(!a.out_dir.exists(), "selector {bad:?} created --out"); - } -} - -#[test] -fn lower_case_selector_matches_mixed_case_te_symbol_and_skips_whitespace_padded_symbol() { - let tmp = TempDir::new("case"); - let d0 = day(2026, 2, 2); - write_file(&tmp.0.join("eodPrices.bson"), &[]); - write_file( - &tmp.0.join("teMarketData.bson"), - &[ - te_doc("UsdCad", vec![te_point(d0, 1.36, true)]), - te_doc(" USDCAD", vec![te_point(d0 + 1, 9.99, true)]), - ], - ); - let a = args(&tmp.0, "usdcad"); - - let report = run_curate_fx_1d(&a).expect("run"); - let rows = read_rows(&a.out_dir); - - assert_conserved(&report); - assert_eq!(report.te_decode.docs_matched, 1); - assert_eq!(report.te_decode.docs_other_symbol, 1); - assert_eq!(rows.len(), 1); - assert_eq!(rows[0].session_date, d0); - assert_eq!(rows[0].source, "te_usdcad"); - assert_eq!(rows[0].bits[3], 1.36_f64.to_bits()); -} - -#[test] -fn te_point_with_datetime_t_is_counted_wrong_type_and_not_published() { - let tmp = TempDir::new("datetime-t"); - let d0 = day(2026, 3, 2); - let mut dt_point = RawDocumentBuf::new(); - dt_point.append( - cstr!("t"), - DateTime::from_millis(i64::from(d0 + 1) * TE_MILLIS_PER_DAY), - ); - dt_point.append(cstr!("o"), 1.37_f64); - dt_point.append(cstr!("h"), 1.38_f64); - dt_point.append(cstr!("l"), 1.36_f64); - dt_point.append(cstr!("c"), 1.37_f64); - write_file(&tmp.0.join("eodPrices.bson"), &[]); - write_file( - &tmp.0.join("teMarketData.bson"), - &[te_doc("USDCAD", vec![te_point(d0, 1.36, false), dt_point])], - ); - let a = args(&tmp.0, "USDCAD"); - - let report = run_curate_fx_1d(&a).expect("run"); - let rows = read_rows(&a.out_dir); - - assert_conserved(&report); - assert_eq!(report.te_decode.points_in, 2); - assert_eq!(report.te_decode.points_decoded, 1); - assert_eq!(report.te_decode.rejected_wrong_type, 1); - assert_eq!(rows.iter().map(|r| r.session_date).collect::>(), vec![d0]); -} - -#[test] -fn cad_forex_without_volume_is_rejected_as_missing_field_and_te_still_publishes() { - // Pins the README Known Limit: the reused eodPrices decoder requires `volume`. - let tmp = TempDir::new("no-volume"); - let d0 = day(2025, 12, 1); - write_file( - &tmp.0.join("eodPrices.bson"), - &[ - eod_doc("CAD.FOREX", d0, 1.40, false), - eod_doc("CAD.FOREX", d0 + 1, 1.41, true), - ], - ); - write_file( - &tmp.0.join("teMarketData.bson"), - &[te_doc("USDCAD", vec![te_point(d0, 1.39, true)])], - ); - let a = args(&tmp.0, "USDCAD"); - - let report = run_curate_fx_1d(&a).expect("run"); - let rows = read_rows(&a.out_dir); - - assert_conserved(&report); - assert_eq!(report.eod_decode.rejected_missing_field, 1); - assert_eq!(report.eod_cad_forex_kept, 1); - let got: Vec<(i32, &str)> = rows - .iter() - .map(|r| (r.session_date, r.source.as_str())) - .collect(); - assert_eq!(got, vec![(d0, "te_usdcad"), (d0 + 1, "eod_cad_forex")]); -} diff --git a/tools/curate-etl/tests/run_curate_shorts_qa_contract.rs b/tools/curate-etl/tests/run_curate_shorts_qa_contract.rs deleted file mode 100644 index 987d30ba..00000000 --- a/tools/curate-etl/tests/run_curate_shorts_qa_contract.rs +++ /dev/null @@ -1,555 +0,0 @@ -//! QA contract tests for the `curate-shorts` runner and the `ceoShorts` stream decoder -//! (T-114 / M1.2ad), via the public crate API and the built binary only. -//! -//! Covers gaps left by the in-crate `run_curate_shorts_tests.rs` / `bson_ceo_shorts_tests.rs` and -//! `tests/curate_shorts.rs`: -//! - poison look-ahead through real dump files: appending absurd future reports (same key, later -//! dates) leaves every earlier published row bit-identical; -//! - truncation: dropping every report on/after a cutoff yields exactly the earlier prefix; -//! - recycled ticker: one key mapped to two listings in different years resolves on -//! `report_date` (not `known_at`), the gap year is `dropped_unmapped`, and a report on the -//! last mapped day whose `known_at` lands after the range end still maps (New Year holiday); -//! - ticker change: two keys → one listing over disjoint ranges are kept, no collision counted; -//! - small-chunk streaming (`decode_ceo_shorts_stream`) equals the one-shot buffer decode, and a -//! corrupt later document reports its absolute byte offset; -//! - binary stdout counters satisfy the documented conservation invariants; -//! - out-of-range `report_date` (< 2008) and an `--out` that is a file fail non-zero and leave the -//! pre-existing output byte-identical. - -use std::fs::{self, File}; -use std::io::Write; -use std::path::{Path, PathBuf}; -use std::process::{Command, Output}; -use std::sync::atomic::{AtomicU64, Ordering}; - -use bson::raw::{cstr, RawDocumentBuf}; -use bson::DateTime as BsonDateTime; -use curate_etl::{ - decode_ceo_shorts_buffer, decode_ceo_shorts_stream, run_curate_shorts, ymd_to_epoch_days, - BsonCeoShortsError, BsonCeoShortsStreamError, BsonStreamOptions, CeoShortsFieldNames, - CurateShortsArgs, CurateShortsRunReport, RunCurateShortsError, -}; -use parquet::file::reader::{FileReader, SerializedFileReader}; -use parquet::record::{Field, RowAccessor}; - -static SEQ: AtomicU64 = AtomicU64::new(0); - -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-run-curate-shorts-qa-{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 date") -} - -fn utc_micros(y: i32, m: u32, d: u32, hour: i64) -> i64 { - (i64::from(day(y, m, d)) * 86_400 + hour * 3_600) * 1_000_000 -} - -fn doc(sym: &str, report_date: i32, shares: f64, net_change: Option) -> Vec { - let mut d = RawDocumentBuf::new(); - d.append(cstr!("symbol"), sym); - d.append( - cstr!("timestamp"), - BsonDateTime::from_millis(i64::from(report_date) * 86_400_000), - ); - d.append(cstr!("shortQty"), shares); - if let Some(v) = net_change { - d.append(cstr!("chg"), v); - } - d.into_bytes() -} - -fn write_file(path: &Path, bytes: &[u8]) { - File::create(path) - .and_then(|mut f| f.write_all(bytes)) - .expect("write fixture"); -} - -fn args(dir: &Path) -> CurateShortsArgs { - CurateShortsArgs { - ceo_shorts: dir.join("ceoShorts.bson"), - provider_mapping: dir.join("provider_mapping.tsv"), - out_dir: dir.join("out"), - key_field: "symbol".to_string(), - report_date_field: "timestamp".to_string(), - shares_short_field: "shortQty".to_string(), - net_change_field: Some("chg".to_string()), - pct_float_field: None, - mapping_source: "ceo".to_string(), - } -} - -fn fields() -> CeoShortsFieldNames<'static> { - CeoShortsFieldNames { - key: "symbol", - report_date: "timestamp", - shares_short: "shortQty", - net_change: Some("chg"), - pct_float: None, - } -} - -#[derive(Debug, Clone, PartialEq)] -struct Row { - listing_id: i32, - report_date: i32, - known_at: i64, - shares_short: f64, - net_change: Option, - source: String, -} - -fn read_rows(out_dir: &Path) -> Vec { - let file = File::open(out_dir.join("shorts/part.parquet")).expect("open part.parquet"); - let reader = SerializedFileReader::new(file).expect("parquet reader"); - reader - .get_row_iter(None) - .expect("row iter") - .map(|r| { - let r = r.expect("row"); - let report_date = match r.get_column_iter().nth(1).expect("col 1").1 { - Field::Date(d) => *d, - other => panic!("report_date not Date: {other:?}"), - }; - Row { - listing_id: r.get_int(0).expect("listing_id"), - report_date, - known_at: r.get_timestamp_micros(2).expect("known_at"), - shares_short: r.get_double(3).expect("shares_short"), - net_change: r.get_double(4).ok(), - source: r.get_string(6).expect("source").clone(), - } - }) - .collect() -} - -fn assert_invariants(r: &CurateShortsRunReport) { - let b = &r.curate_stats.builder; - let c = &r.curate_stats; - assert_eq!(r.docs_framed as usize, r.decode.docs_in); - assert_eq!( - r.decode.docs_in, - r.decode.rows_out + r.decode.skipped_total() - ); - assert_eq!(r.decode.rows_out, b.rows_in); - assert_eq!( - b.rows_in, - b.rows_out - + b.dropped_invalid_shares_short - + b.duplicate_collapsed - + b.duplicate_conflict_dropped - ); - assert_eq!(c.rows_in, b.rows_out); - assert_eq!( - c.rows_in, - c.rows_out - + c.dropped_unmapped - + c.listing_collision_collapsed - + c.listing_collision_dropped - ); - assert_eq!(r.write_stats.rows_written, c.rows_out); -} - -/// Semi-monthly 15th / month-end report dates for 2023 (24 dates, includes weekends). -fn report_dates_2023() -> Vec { - let month_end = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; - let mut out = Vec::new(); - for (m, &last) in month_end.iter().enumerate() { - out.push(day(2023, m as u32 + 1, 15)); - out.push(day(2023, m as u32 + 1, last)); - } - out -} - -fn baseline_docs(dates: &[i32]) -> Vec<(i32, Vec)> { - let mut docs = Vec::new(); - for (i, &d) in dates.iter().enumerate() { - for (k, sym) in ["AAA", "BBB", "CCC"].iter().enumerate() { - let shares = 10_000.0 + (i * 100 + k) as f64; - docs.push((d, doc(sym, d, shares, Some((i as f64) - 5.0)))); - } - } - docs -} - -const MAPPING_TSV: &str = - "ceo\tAAA\t2015-01-01\t\t1\nceo\tBBB\t2015-01-01\t\t2\nceo\tCCC\t2015-01-01\t\t3\n"; - -#[test] -fn poison_future_reports_leave_earlier_rows_bit_identical() { - let tmp = TempDir::new("poison"); - let a = args(&tmp.0); - write_file(&a.provider_mapping, MAPPING_TSV.as_bytes()); - - let docs = baseline_docs(&report_dates_2023()); - let clean: Vec = docs.iter().flat_map(|(_, b)| b.clone()).collect(); - write_file(&a.ceo_shorts, &clean); - let base = run_curate_shorts(&a).expect("baseline run"); - assert_invariants(&base); - let base_rows = read_rows(&a.out_dir); - assert_eq!(base_rows.len(), 24 * 3); - - // Poison: absurd future reports for every key, interleaved at the front of the file. - let mut poisoned = Vec::new(); - for sym in ["AAA", "BBB", "CCC"] { - poisoned.extend(doc(sym, day(2024, 1, 15), 9.9e12, Some(-9.9e12))); - poisoned.extend(doc(sym, day(2025, 6, 30), 1.0, None)); - } - poisoned.extend_from_slice(&clean); - write_file(&a.ceo_shorts, &poisoned); - let poisoned_report = run_curate_shorts(&a).expect("poisoned run"); - assert_invariants(&poisoned_report); - let poisoned_rows = read_rows(&a.out_dir); - - let cutoff = day(2024, 1, 1); - let earlier: Vec = poisoned_rows - .iter() - .filter(|r| r.report_date < cutoff) - .cloned() - .collect(); - assert_eq!(earlier, base_rows, "future reports moved earlier rows"); - assert_eq!(poisoned_rows.len(), base_rows.len() + 6); -} - -#[test] -fn truncation_at_cutoffs_yields_exact_prefix_of_full_run() { - let tmp = TempDir::new("truncate"); - let a = args(&tmp.0); - write_file(&a.provider_mapping, MAPPING_TSV.as_bytes()); - - let dates = report_dates_2023(); - let docs = baseline_docs(&dates); - write_file( - &a.ceo_shorts, - &docs - .iter() - .flat_map(|(_, b)| b.clone()) - .collect::>(), - ); - run_curate_shorts(&a).expect("full run"); - let full = read_rows(&a.out_dir); - - for cutoff in [dates[3], dates[11], dates[20]] { - let truncated: Vec = docs - .iter() - .filter(|(d, _)| *d < cutoff) - .flat_map(|(_, b)| b.clone()) - .collect(); - write_file(&a.ceo_shorts, &truncated); - let report = run_curate_shorts(&a).expect("truncated run"); - assert_invariants(&report); - let got = read_rows(&a.out_dir); - let want: Vec = full - .iter() - .filter(|r| r.report_date < cutoff) - .cloned() - .collect(); - assert!(!want.is_empty()); - assert_eq!(got, want, "truncation at {cutoff} changed earlier rows"); - } -} - -#[test] -fn recycled_ticker_resolves_on_report_date_and_gap_is_unmapped() { - let tmp = TempDir::new("recycled"); - let a = args(&tmp.0); - // Same key "REC" used by two unrelated listings; 2020 is a gap. - write_file( - &a.provider_mapping, - b"ceo\tREC\t2017-01-01\t2019-12-31\t10\nceo\tREC\t2021-01-01\t\t20\n", - ); - let mut bytes = Vec::new(); - bytes.extend(doc("REC", day(2021, 1, 15), 300.0, None)); // -> 20 - bytes.extend(doc("REC", day(2020, 6, 15), 200.0, None)); // gap -> unmapped - bytes.extend(doc("REC", day(2019, 12, 31), 100.0, None)); // last mapped day of listing 10 - write_file(&a.ceo_shorts, &bytes); - - let report = run_curate_shorts(&a).expect("run"); - assert_invariants(&report); - assert_eq!(report.curate_stats.dropped_unmapped, 1); - assert_eq!(report.curate_stats.rows_out, 2); - - let rows = read_rows(&a.out_dir); - // 2019-12-31 (Tue) +4 TSX days skipping New Year's Day: Jan 2, 3, 6, 7 -> 2020-01-07 17:00 EST. - // known_at falls after listing 10's range end, but mapping is anchored on report_date. - assert_eq!( - rows, - vec![ - Row { - listing_id: 10, - report_date: day(2019, 12, 31), - known_at: utc_micros(2020, 1, 7, 22), - shares_short: 100.0, - net_change: None, - source: "ceo_shorts".to_string(), - }, - Row { - listing_id: 20, - report_date: day(2021, 1, 15), - // 2021-01-15 (Fri): Jan 18, 19, 20, 21 -> 2021-01-21 17:00 EST. - known_at: utc_micros(2021, 1, 21, 22), - shares_short: 300.0, - net_change: None, - source: "ceo_shorts".to_string(), - }, - ] - ); -} - -#[test] -fn ticker_change_two_keys_one_listing_disjoint_ranges_kept_without_collision() { - let tmp = TempDir::new("ticker-change"); - let a = args(&tmp.0); - write_file( - &a.provider_mapping, - b"ceo\tOLD\t2017-01-01\t2022-06-08\t7\nceo\tNEW\t2022-06-09\t\t7\n", - ); - let mut bytes = Vec::new(); - bytes.extend(doc("NEW", day(2022, 6, 15), 2_000.0, Some(1_000.0))); - bytes.extend(doc("OLD", day(2022, 5, 31), 1_000.0, None)); - // Stale old ticker after the change must not resolve. - bytes.extend(doc("OLD", day(2022, 6, 30), 5.0, None)); - write_file(&a.ceo_shorts, &bytes); - - let report = run_curate_shorts(&a).expect("run"); - assert_invariants(&report); - assert_eq!(report.curate_stats.listing_collision_collapsed, 0); - assert_eq!(report.curate_stats.listing_collision_dropped, 0); - assert_eq!(report.curate_stats.dropped_unmapped, 1); - let rows = read_rows(&a.out_dir); - assert_eq!( - rows.iter() - .map(|r| (r.listing_id, r.report_date, r.shares_short)) - .collect::>(), - vec![ - (7, day(2022, 5, 31), 1_000.0), - (7, day(2022, 6, 15), 2_000.0) - ] - ); - // 2022-05-31 (Tue) EDT: Jun 1, 2, 3, 6 -> 21:00 UTC. - assert_eq!(rows[0].known_at, utc_micros(2022, 6, 6, 21)); -} - -#[test] -fn small_chunk_stream_matches_buffer_and_reports_absolute_offset() { - let docs = baseline_docs(&report_dates_2023()); - let buf: Vec = docs.iter().flat_map(|(_, b)| b.clone()).collect(); - - let collect = |out: &mut Vec<(String, i32, u64, Option)>, - r: curate_etl::CeoShortReport<&str>| { - out.push(( - r.key.to_string(), - r.report_date, - r.shares_short.to_bits(), - r.net_change.map(f64::to_bits), - )); - }; - - let mut want = Vec::new(); - let want_stats = - decode_ceo_shorts_buffer(&buf, &fields(), |r| collect(&mut want, r)).expect("buffer"); - - for cap in [1usize, 7, 64, 1024] { - let mut got = Vec::new(); - let opts = BsonStreamOptions { - chunk_capacity_bytes: cap, - ..BsonStreamOptions::default() - }; - let stats = - decode_ceo_shorts_stream(buf.as_slice(), opts, &fields(), |r| collect(&mut got, r)) - .expect("stream"); - assert_eq!(stats, want_stats, "cap={cap}"); - assert_eq!(got, want, "cap={cap}"); - } - - // Corrupt the element type byte of `shortQty` in the 40th document. - let target = 39; - let offset: usize = docs[..target].iter().map(|(_, b)| b.len()).sum(); - let mut corrupt = buf.clone(); - let rel = docs[target] - .1 - .windows(10) - .position(|w| w == b"\x01shortQty\x00") - .expect("locate shortQty"); - corrupt[offset + rel] = 0x7e; - - for cap in [16usize, 64, 4096] { - let opts = BsonStreamOptions { - chunk_capacity_bytes: cap, - ..BsonStreamOptions::default() - }; - let err = - decode_ceo_shorts_stream(corrupt.as_slice(), opts, &fields(), |_| {}).unwrap_err(); - match err { - BsonCeoShortsStreamError::Decode(BsonCeoShortsError::CorruptBson { - offset: got, - .. - }) => { - assert_eq!(got, offset as u64, "cap={cap}"); - } - other => panic!("cap={cap}: expected CorruptBson, got {other:?}"), - } - } -} - -fn run_bin(args: &[&str]) -> Output { - Command::new(env!("CARGO_BIN_EXE_curate-etl")) - .args(args) - .output() - .expect("spawn curate-etl") -} - -fn counter(line: &str, key: &str) -> usize { - let needle = format!("{key}="); - let start = line - .split_whitespace() - .find_map(|tok| tok.trim_start_matches('(').strip_prefix(needle.as_str())) - .unwrap_or_else(|| panic!("missing {key} in {line}")); - start - .trim_end_matches(')') - .parse() - .unwrap_or_else(|_| panic!("bad {key} in {line}")) -} - -fn report_line<'a>(stdout: &'a str, prefix: &str) -> &'a str { - stdout - .lines() - .find(|l| l.trim_start().starts_with(prefix)) - .unwrap_or_else(|| panic!("missing {prefix} line in {stdout}")) -} - -#[test] -fn binary_stdout_counters_satisfy_conservation() { - let tmp = TempDir::new("bin-counters"); - let a = args(&tmp.0); - write_file(&a.provider_mapping, MAPPING_TSV.as_bytes()); - - let d = day(2023, 3, 15); - let mut bytes = Vec::new(); - bytes.extend(doc("AAA", d, 100.0, Some(1.0))); - bytes.extend(doc("AAA", d, 100.0, Some(1.0))); // identical duplicate - bytes.extend(doc("BBB", d, 5.0, None)); - bytes.extend(doc("BBB", d, 6.0, None)); // conflicting duplicate - bytes.extend(doc("CCC", d, -1.0, None)); // invalid shares - bytes.extend(doc("ZZZ", d, 1.0, None)); // unmapped - bytes.extend(doc("", d, 1.0, None)); // skipped empty key - write_file(&a.ceo_shorts, &bytes); - - let out = run_bin(&[ - "curate-shorts", - "--ceo-shorts", - a.ceo_shorts.to_str().unwrap(), - "--provider-mapping", - a.provider_mapping.to_str().unwrap(), - "--out", - a.out_dir.to_str().unwrap(), - "--shares-short-field=shortQty", - "--net-change-field", - "chg", - ]); - let stdout = String::from_utf8_lossy(&out.stdout).into_owned(); - assert!( - out.status.success(), - "stderr: {}", - String::from_utf8_lossy(&out.stderr) - ); - - let bson = report_line(&stdout, "ceo_bson:"); - let builder = report_line(&stdout, "builder:"); - let curate = report_line(&stdout, "curate:"); - let write = report_line(&stdout, "write:"); - - assert_eq!(counter(bson, "docs_framed"), 7); - assert_eq!(counter(bson, "docs_in"), 7); - assert_eq!(counter(bson, "rows_out"), 6); - assert_eq!(counter(bson, "skipped"), 1); - assert_eq!(counter(bson, "empty_key"), 1); - assert_eq!(counter(builder, "rows_in"), 6); - assert_eq!(counter(builder, "invalid_shares"), 1); - assert_eq!(counter(builder, "dup_collapsed"), 1); - assert_eq!(counter(builder, "dup_conflict"), 2); - assert_eq!( - counter(builder, "rows_in"), - counter(builder, "rows_out") - + counter(builder, "invalid_shares") - + counter(builder, "dup_collapsed") - + counter(builder, "dup_conflict") - ); - assert_eq!(counter(curate, "rows_in"), counter(builder, "rows_out")); - assert_eq!(counter(curate, "dropped_unmapped"), 1); - assert_eq!(counter(curate, "rows_out"), 1); - assert_eq!(counter(write, "rows_written"), 1); - assert_eq!(read_rows(&a.out_dir).len(), 1); -} - -#[test] -fn pre_2008_report_date_and_file_out_fail_and_preserve_existing_output() { - let tmp = TempDir::new("oor"); - let a = args(&tmp.0); - write_file(&a.provider_mapping, MAPPING_TSV.as_bytes()); - write_file(&a.ceo_shorts, &doc("AAA", day(2023, 6, 15), 50.0, None)); - run_curate_shorts(&a).expect("seed run"); - let part = a.out_dir.join("shorts/part.parquet"); - let before = fs::read(&part).expect("read part"); - - // Mapped report dated 2007-12-31 is outside the TSX calendar: typed error, no publish. - let mut bytes = doc("AAA", day(2024, 3, 15), 60.0, None); - bytes.extend(doc("BBB", day(2007, 12, 31), 70.0, None)); - write_file(&a.ceo_shorts, &bytes); - let mapping_old = MAPPING_TSV.replace("2015-01-01", "2000-01-01"); - write_file(&a.provider_mapping, mapping_old.as_bytes()); - let err = run_curate_shorts(&a).unwrap_err(); - assert!( - matches!(err, RunCurateShortsError::CurateWrite { .. }), - "got {err:?}" - ); - assert!(!err.to_string().contains('\n')); - assert_eq!(fs::read(&part).expect("read part"), before); - - // Same via binary: non-zero exit, single-line stderr, output untouched. - let o = run_bin(&[ - "curate-shorts", - "--ceo-shorts", - a.ceo_shorts.to_str().unwrap(), - "--provider-mapping", - a.provider_mapping.to_str().unwrap(), - "--out", - a.out_dir.to_str().unwrap(), - "--shares-short-field", - "shortQty", - ]); - assert!(!o.status.success()); - let stderr = String::from_utf8_lossy(&o.stderr); - assert_eq!(stderr.trim_end().lines().count(), 1, "stderr: {stderr}"); - assert_eq!(fs::read(&part).expect("read part"), before); - - // --out pointing at a regular file is rejected before anything is read or written. - let file_out = tmp.0.join("not-a-dir"); - write_file(&file_out, b"keep"); - let mut b = a.clone(); - b.out_dir = file_out.clone(); - let err = run_curate_shorts(&b).unwrap_err(); - assert!( - matches!(err, RunCurateShortsError::InvalidOutDir { .. }), - "got {err:?}" - ); - assert_eq!(fs::read(&file_out).unwrap(), b"keep"); -} diff --git a/tools/curate-etl/tests/session_close_qa_contract.rs b/tools/curate-etl/tests/session_close_qa_contract.rs index d0a04c43..7c93a8d4 100644 --- a/tools/curate-etl/tests/session_close_qa_contract.rs +++ b/tools/curate-etl/tests/session_close_qa_contract.rs @@ -204,10 +204,7 @@ fn pre_1976_divergent_emergency_dst_years_and_post_2030_are_out_of_range() { epoch_day, min_supported, max_supported, - } = err - else { - panic!("expected SessionCloseError::DateOutOfRange, got {err:?}"); - }; + } = err; assert_eq!(epoch_day, d); assert_eq!(min_supported, SESSION_CLOSE_MIN_SUPPORTED_DATE); assert_eq!(max_supported, SESSION_CLOSE_MAX_SUPPORTED_DATE); diff --git a/tsconfig.check.json b/tsconfig.check.json index 74f157e6..d67c308a 100644 --- a/tsconfig.check.json +++ b/tsconfig.check.json @@ -32,8 +32,7 @@ "apps/stock/**/src/**/*.tsx", "tools/**/src/**/*.ts", "apps/stock/orchestrator/examples/canonical-regime-research.ts", - "libs/core/services/test/contracts.type-test.ts", - "libs/data/postgres/test/research-copilot-executor.type-test.ts" + "libs/core/services/test/contracts.type-test.ts" ], "exclude": ["node_modules", "**/dist/**", "**/*.test.ts", "**/*.spec.ts"] }