diff --git a/.gitignore b/.gitignore index e3ebee38..3fa889bd 100644 --- a/.gitignore +++ b/.gitignore @@ -121,3 +121,10 @@ docs/configuration-standardization.md # Rust target/ + +# Python +__pycache__/ +*.py[cod] +*.egg-info/ +.pytest_cache/ +.venv/ diff --git a/Cargo.lock b/Cargo.lock index 11d01203..6899374a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -50,6 +50,12 @@ 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" @@ -97,6 +103,15 @@ 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" @@ -111,6 +126,7 @@ dependencies = [ "indexmap", "js-sys", "rand 0.9.5", + "serde", "serde_bytes", "simdutf8", "thiserror 2.0.21", @@ -154,6 +170,17 @@ 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" @@ -168,6 +195,28 @@ 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" @@ -196,12 +245,37 @@ 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" @@ -264,6 +338,15 @@ 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" @@ -274,12 +357,57 @@ 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]] @@ -295,12 +423,69 @@ 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" @@ -344,7 +529,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -353,18 +538,59 @@ 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" @@ -378,7 +604,10 @@ 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", ] @@ -418,6 +647,7 @@ dependencies = [ "js-sys", "libc", "r-efi 6.0.0", + "rand_core 0.10.1", "wasm-bindgen", ] @@ -451,6 +681,94 @@ 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" @@ -475,6 +793,116 @@ 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" @@ -485,12 +913,83 @@ 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" @@ -540,6 +1039,12 @@ 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" @@ -555,6 +1060,54 @@ 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" @@ -565,6 +1118,16 @@ 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" @@ -579,7 +1142,99 @@ checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" dependencies = [ "libc", "wasi", - "windows-sys", + "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", ] [[package]] @@ -699,13 +1354,19 @@ 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", + "windows-sys 0.61.2", ] [[package]] @@ -778,6 +1439,10 @@ 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" @@ -827,6 +1492,21 @@ 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" @@ -839,6 +1519,21 @@ 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" @@ -854,6 +1549,19 @@ 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" @@ -911,6 +1619,17 @@ 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" @@ -949,6 +1668,12 @@ 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" @@ -965,6 +1690,26 @@ 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" @@ -1003,6 +1748,26 @@ 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" @@ -1013,6 +1778,60 @@ 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" @@ -1028,6 +1847,15 @@ 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" @@ -1099,6 +1927,50 @@ 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" @@ -1150,6 +2022,16 @@ 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" @@ -1175,9 +2057,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.61.2", ] +[[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" @@ -1191,6 +2079,29 @@ 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" @@ -1224,6 +2135,50 @@ 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" @@ -1318,6 +2273,22 @@ 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" @@ -1332,7 +2303,7 @@ dependencies = [ "signal-hook-registry", "socket2", "tokio-macros", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -1346,6 +2317,31 @@ 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" @@ -1409,24 +2405,98 @@ 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" @@ -1451,6 +2521,16 @@ 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" @@ -1510,6 +2590,15 @@ 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" @@ -1520,6 +2609,21 @@ 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" @@ -1561,6 +2665,17 @@ 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" @@ -1579,6 +2694,15 @@ 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" @@ -1588,12 +2712,82 @@ 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" @@ -1603,6 +2797,29 @@ 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" @@ -1623,6 +2840,66 @@ 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 6664a2b0..bca66ac1 100644 --- a/apps/stock/data-pipeline/README.md +++ b/apps/stock/data-pipeline/README.md @@ -206,3 +206,128 @@ 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 new file mode 100644 index 00000000..f23a8a02 --- /dev/null +++ b/apps/stock/data-pipeline/benchmarks/export-curate-inputs-benchmark.ts @@ -0,0 +1,292 @@ +/** + * 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 new file mode 100644 index 00000000..7b3b86e6 --- /dev/null +++ b/apps/stock/data-pipeline/benchmarks/export-raw-bson-benchmark.ts @@ -0,0 +1,140 @@ +/** + * 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 new file mode 100644 index 00000000..ddb6ba75 --- /dev/null +++ b/apps/stock/data-pipeline/benchmarks/source-field-shapes-benchmark.ts @@ -0,0 +1,167 @@ +/** + * 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 3da51d81..b6387b72 100644 --- a/apps/stock/data-pipeline/src/security-master/delisting-chains.ts +++ b/apps/stock/data-pipeline/src/security-master/delisting-chains.ts @@ -175,6 +175,49 @@ 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, @@ -693,13 +736,24 @@ export function linkDelistingChains( otc.listedToDay === null || otc.listedToDay > maxWindowDay ? maxWindowDay : otc.listedToDay; - if (lowDay > highDay) { - continue; + 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; + } } - const startIdx = lowerBoundPrimaryByListedToDay(primaries, lowDay); - const endExclusive = upperBoundPrimaryByListedToDay(primaries, highDay); - if (startIdx < endExclusive) { - intervals.push({ startIdx, endIdx: endExclusive - 1, otcIdx: oIdx }); + // 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 }); + } } } @@ -730,13 +784,16 @@ 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) so - // downstream backtests and curation never back-date OTC availability before - // OTC trading/quoting actually began. + // 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; continuities.push({ fromListingKey: cloneListingKey(primary.key), toListingKey: cloneListingKey(otc.key), - effectiveDate: otc.listedFrom, + effectiveDate, 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 24ec1fab..b4ebb785 100644 --- a/apps/stock/data-pipeline/src/security-master/exchange-pass1.ts +++ b/apps/stock/data-pipeline/src/security-master/exchange-pass1.ts @@ -71,6 +71,7 @@ export interface ExchangeClassificationResult { export interface ClassifySourceExchangesOptions { knownExchanges?: readonly ExchangeSeedRow[]; + reviewedRows?: readonly ExchangeSourceMapRow[]; } const VALID_EXCHANGE_SOURCE_SET: ReadonlySet = new Set(EXCHANGE_SOURCES); @@ -293,9 +294,15 @@ 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' }, @@ -305,19 +312,63 @@ 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' }, @@ -332,16 +383,23 @@ 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' }, @@ -357,6 +415,7 @@ 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' }, @@ -364,7 +423,9 @@ 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, @@ -423,6 +484,12 @@ 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[] = []; @@ -495,6 +562,20 @@ 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 new file mode 100644 index 00000000..299bac4d --- /dev/null +++ b/apps/stock/data-pipeline/src/security-master/export-curate-inputs.ts @@ -0,0 +1,2040 @@ +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 new file mode 100644 index 00000000..8ba7e632 --- /dev/null +++ b/apps/stock/data-pipeline/src/security-master/export-raw-bson.ts @@ -0,0 +1,670 @@ +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 7dbcd44c..85707ca8 100644 --- a/apps/stock/data-pipeline/src/security-master/index.ts +++ b/apps/stock/data-pipeline/src/security-master/index.ts @@ -47,6 +47,100 @@ 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, @@ -265,6 +359,47 @@ 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 f840113e..5a0acb60 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,9 +9,15 @@ 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'; +export type StageAMatchMethod = 'tier1_isin' | 'tier2_cusip' | 'tier3_ticker_span'; export type StageAConflictKind = 'isin_cusip_mismatch' | 'duplicate_source_id'; @@ -64,6 +70,7 @@ export interface StageASourceStats { total: number; tier1Isin: number; tier2Cusip: number; + tier3Synthetic?: number; unresolved: number; conflict: number; } @@ -76,6 +83,7 @@ export interface StageAStats { export interface MatchInstrumentsStageAOptions { readonly nameSourcePrecedence?: readonly StageASource[]; + readonly allowIdentifierlessEod?: boolean; } export interface StageAMatchResult { @@ -93,6 +101,7 @@ interface BestSourceName { interface InstrumentAccumulator { members: StageAInstrumentMember[]; bestNameBySource: Record; + fallbackCountry: string | null; } export function isStageASource(value: unknown): value is StageASource { @@ -230,6 +239,45 @@ 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, @@ -286,6 +334,7 @@ export function matchInstrumentsStageA( ib: null, eod: null, }, + fallbackCountry: null, }; instrumentsByIsin.set(resolved.isin, acc); } @@ -313,10 +362,13 @@ export function matchInstrumentsStageA( const instruments: StageAInstrumentCandidate[] = []; for (const [primaryIsin, acc] of instrumentsByIsin.entries()) { - const issuerCountry = primaryIsin.slice(0, 2); - const embeddedCusip = primaryIsin.slice(2, 11); + const isSynthetic = isSyntheticInstrumentKey(primaryIsin); + const issuerCountry = isSynthetic ? (acc.fallbackCountry ?? 'US') : primaryIsin.slice(0, 2); + const embeddedCusip = isSynthetic ? '' : primaryIsin.slice(2, 11); const primaryCusip = - isNorthAmericaCountry(issuerCountry) && isValidCusip(embeddedCusip) ? embeddedCusip : null; + !isSynthetic && 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 69a816e5..1d3fdec2 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,10 +6,11 @@ import { } from '../normalization/bar-spans'; import { parseTickerDetailed } from '../normalization/ticker'; import { compareAscii, type ExchangeRole } from './exchange-pass1'; -import type { - StageAInstrumentCandidate, - StageAMatchMethod, - StageASource, +import { + isSyntheticInstrumentKey, + type StageAInstrumentCandidate, + type StageAMatchMethod, + type StageASource, } from './instrument-stage-a'; export const MAX_TICKER_ROOT_LENGTH = 24; @@ -44,6 +45,9 @@ export interface StageBIbContractInput { conid: number; currency?: string | null; primaryExchange: string | null; + ticker?: string | null; + name?: string | null; + exchangeId?: string | null; } export interface StageBTickerSourceInput { @@ -54,6 +58,7 @@ export interface StageBTickerSourceInput { role: ExchangeRole | null; currency?: string | null; span: SpanDateRange | null; + name?: string | null; } export interface StageBSymbolChangeInput { @@ -77,6 +82,8 @@ export interface StageBInput { export interface MatchListingsStageBOptions { readonly spanOverlapToleranceDays?: number; + readonly enableIbTickerDisambiguation?: boolean; + readonly allowUniqueTickerFallbackForCrawlOnlyCeo?: boolean; } export interface StageBListingCandidate extends ListingNaturalKey { @@ -201,7 +208,7 @@ interface StagedIbCandidate { currency: string; conid: number; primaryExchange: string | null; - method: StageAMatchMethod; + method: StageBMatchMethod; } const ISO_MIC_PATTERN = /^[A-Z0-9]{4}$/; @@ -216,8 +223,15 @@ function isStageASourceValue(value: unknown): value is StageASource { return value === 'ib' || value === 'eod'; } -function isStageAMatchMethodValue(value: unknown): value is StageAMatchMethod { - return value === 'tier1_isin' || value === 'tier2_cusip'; +function isStageAMatchMethodValue( + value: unknown, + allowSyntheticTier3 = false +): value is StageAMatchMethod { + return ( + value === 'tier1_isin' || + value === 'tier2_cusip' || + (allowSyntheticTier3 && value === 'tier3_ticker_span') + ); } function isStageBTickerSourceValue(value: unknown): value is StageBTickerSource { @@ -658,7 +672,8 @@ export function matchListingsStageB( `Invalid empty or non-string sourceId at instruments[${i}].members[${j}]` ); } - if (!isStageAMatchMethodValue(member.method)) { + const isSyntheticInst = isSyntheticInstrumentKey(inst.primaryIsin); + if (!isStageAMatchMethodValue(member.method, isSyntheticInst)) { throw new Error( `Unknown Stage A member method "${String(member.method)}" at instruments[${i}].members[${j}]` ); @@ -865,7 +880,11 @@ 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[] = []; @@ -1006,6 +1025,14 @@ 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) { @@ -1143,7 +1170,84 @@ export function matchListingsStageB( } const primaryExchange = normalizeOptionalExchangeLabel(contract.primaryExchange); - const candidates = listingsByInstrumentCurrency.get(inst.primaryIsin)?.get(currency); + 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'; + } + } + } + } if (candidates === undefined || candidates.length === 0) { unresolved.push({ @@ -1190,7 +1294,7 @@ export function matchListingsStageB( currency, conid: contract.conid, primaryExchange, - method: member.method, + method: matchMethod, }); } } @@ -1483,6 +1587,29 @@ 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 3e9ab06a..7163a077 100644 --- a/apps/stock/data-pipeline/src/security-master/match-report.ts +++ b/apps/stock/data-pipeline/src/security-master/match-report.ts @@ -36,6 +36,13 @@ 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; @@ -43,10 +50,13 @@ 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 { @@ -73,6 +83,7 @@ export interface SourceResolutionSummary { unresolved: number; conflict: number; excludedByDesign: number; + outOfGateScope?: number; eligibleTotal: number; resolvedPct: number | null; eligibleResolvedPct: number | null; @@ -141,6 +152,8 @@ export interface MatchReport { resolutionBySource: SourceResolutionSummary[]; resolutionByCountry: CountryResolutionSummary[]; unresolvedByReason: UnresolvedBreakdown; + outOfGateScopeByReason?: UnresolvedBreakdownRow[]; + gateDenominatorNote?: string; conflicts: UnifiedConflictRow[]; conflictsByPassKind: ConflictCountRow[]; priceCrossCheck: PriceCrossCheckSummary | null; @@ -504,16 +517,62 @@ 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 eligibleTotal = Math.max(0, stats.total - excludedByDesign); + const outOfGateScope = outOfGateScopeBySource[source]; + const eligibleTotal = Math.max(0, stats.total - excludedByDesign - outOfGateScope); return { source, total: stats.total, @@ -521,6 +580,7 @@ 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, @@ -615,6 +675,10 @@ export function buildMatchReport( resolutionBySource, resolutionByCountry, unresolvedByReason, + ...(hasGateOutOfScope ? { outOfGateScopeByReason } : {}), + ...(input.gateDenominatorNote !== undefined + ? { gateDenominatorNote: input.gateDenominatorNote } + : {}), conflicts, conflictsByPassKind, priceCrossCheck, @@ -669,18 +733,48 @@ 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', '', - '| Source | Total | Matched | Unresolved | Conflict | Excluded by Design | Eligible Total | Resolved % | Eligible Resolved % |', - '| --- | --- | --- | --- | --- | --- | --- | --- | --- |' + 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 + ? '| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |' + : '| --- | --- | --- | --- | --- | --- | --- | --- | --- |' ); 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( - `| ${escapeMarkdownCell(row.source)} | ${row.total} | ${row.matched} | ${row.unresolved} | ${row.conflict} | ${row.excludedByDesign} | ${row.eligibleTotal} | ${formatPct(row.resolvedPct)} | ${formatPct(row.eligibleResolvedPct)} |` + '', + '## Out-of-Gate-Scope Breakdown', + '', + '| Source | Reason | Count |', + '| --- | --- | --- |' ); + 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 5fbce262..88c80003 100644 --- a/apps/stock/data-pipeline/src/security-master/persist.ts +++ b/apps/stock/data-pipeline/src/security-master/persist.ts @@ -16,11 +16,13 @@ import type { Pass6DelistReason, } from './delisting-chains'; import { compareAscii } from './exchange-pass1'; -import type { - StageAInstrumentCandidate, - StageAInstrumentMember, - StageAMatchResult, - StageASource, +import { + isSyntheticInstrumentKey, + SYNTHETIC_EOD_ISIN_PREFIX, + type StageAInstrumentCandidate, + type StageAInstrumentMember, + type StageAMatchResult, + type StageASource, } from './instrument-stage-a'; import type { ListingNaturalKey, @@ -243,6 +245,8 @@ interface ExistingPass4ConflictRow { interface PreparedInstrument { readonly primaryIsin: string; + readonly isSynthetic: boolean; + readonly syntheticSourceId: string | null; readonly primaryCusip: string | null; readonly canonicalName: string; readonly securityType: SecurityType; @@ -660,9 +664,16 @@ 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, - primaryCusip: candidate.primaryCusip, + isSynthetic, + syntheticSourceId, + primaryCusip: isSynthetic ? null : candidate.primaryCusip, canonicalName: trimmedName, securityType, issuerCountry: candidate.issuerCountry, @@ -672,8 +683,11 @@ async function persistWithinTransaction( if (preparedInstruments.length > 0) { const existingByIsin = new Map(); - for (let offset = 0; offset < preparedInstruments.length; offset += chunkSize) { - const slice = preparedInstruments.slice(offset, offset + chunkSize); + const 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); const isins = slice.map(item => item.primaryIsin); const res = await client.query( `SELECT @@ -692,13 +706,70 @@ async function persistWithinTransaction( } } - const toInsert: PreparedInstrument[] = []; + 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 toUpdate: Array<{ instrumentId: number; item: PreparedInstrument }> = []; for (const item of preparedInstruments) { const existing = existingByIsin.get(item.primaryIsin); if (existing === undefined) { - toInsert.push(item); + if (item.isSynthetic) { + toInsertSynthetic.push(item); + } else { + toInsertReal.push(item); + } continue; } instrumentIdByIsin.set(item.primaryIsin, existing.instrument_id); @@ -714,8 +785,8 @@ async function persistWithinTransaction( } } - for (let offset = 0; offset < toInsert.length; offset += chunkSize) { - const slice = toInsert.slice(offset, offset + chunkSize); + for (let offset = 0; offset < toInsertReal.length; offset += chunkSize) { + const slice = toInsertReal.slice(offset, offset + chunkSize); const res = await client.query( `INSERT INTO instrument ( primary_isin, @@ -747,6 +818,39 @@ 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( @@ -784,6 +888,9 @@ 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 new file mode 100644 index 00000000..b3fbcfca --- /dev/null +++ b/apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts @@ -0,0 +1,291 @@ +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 new file mode 100644 index 00000000..38d15920 --- /dev/null +++ b/apps/stock/data-pipeline/src/security-master/run-export-curate-inputs.ts @@ -0,0 +1,345 @@ +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 new file mode 100644 index 00000000..17ba87cf --- /dev/null +++ b/apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts @@ -0,0 +1,477 @@ +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 ce107fa7..82c220fb 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,6 +21,7 @@ import { EXCHANGE_SOURCES, ISO_EXCHANGE_SEEDS, normalizeRawExchangeDoc, + REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS, type ExchangeClassificationResult, type ExchangeSource, type SourceExchangeRecord, @@ -51,6 +52,8 @@ import { import { createExchangeSourceLookup, createReadOnlyMongoSourceSymbolReader, + DEFAULT_SOURCE_COUNTRIES, + normalizeCountryIso2, readSecurityMasterSources, type ExchangeSourceLookup, type ReadOnlyMongoCollectionClient, @@ -72,7 +75,9 @@ 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..${MAX_SAMPLE_DATES}, default: ${DEFAULT_SAMPLE_DATE_COUNT}).`, + ' --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).', ' --help Show this help message and exit.', ].join('\n'); @@ -85,6 +90,8 @@ export type ParsedRunSecurityMasterArgs = readonly persist: boolean; readonly skipPriceCrossCheck: boolean; readonly sampleDateCount: number; + readonly useReviewedUsCaExchanges?: boolean; + readonly allowIdentifierlessEod?: boolean; }; export interface RunSecurityMasterPass4Options { @@ -134,6 +141,8 @@ export interface RunSecurityMasterOptions { readonly batchSize?: number; readonly barSpans?: Omit; readonly pass4?: RunSecurityMasterPass4Options; + readonly useReviewedUsCaExchanges?: boolean; + readonly allowIdentifierlessEod?: boolean; } export interface RunSecurityMasterOutput { @@ -351,6 +360,8 @@ 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]; @@ -366,6 +377,14 @@ 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('--')) { @@ -443,6 +462,8 @@ export function parseRunSecurityMasterArgs(argv: readonly string[]): ParsedRunSe persist, skipPriceCrossCheck, sampleDateCount, + ...(useReviewedUsCaExchanges ? { useReviewedUsCaExchanges: true } : {}), + ...(allowIdentifierlessEod ? { allowIdentifierlessEod: true } : {}), }; } @@ -627,8 +648,31 @@ export async function runSecurityMaster( } exchangeCountsByCollection[source] = count; } - exchanges = classifySourceExchanges(normalizedRecords, { + 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, { knownExchanges: ISO_EXCHANGE_SEEDS, + ...(options.useReviewedUsCaExchanges === true + ? { reviewedRows: REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS } + : {}), }); } @@ -644,6 +688,7 @@ export async function runSecurityMaster( exchangeLookup, countries: options.countries, batchSize: options.batchSize, + ...(options.allowIdentifierlessEod === true ? { includeExtendedMetadata: true } : {}), }); } catch (error) { throw wrapStepError('read-sources', error); @@ -673,6 +718,41 @@ 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 { @@ -682,9 +762,7 @@ export async function runSecurityMaster( barSpans, exchanges, }, - { - asOfDate: options.asOfDate, - } + composeOptions ); } catch (error) { throw wrapStepError('compose', error); @@ -758,9 +836,7 @@ export async function runSecurityMaster( sampleCloses: sampleCloses.closes, fxRates: sampleCloses.fxRates, }, - { - asOfDate: options.asOfDate, - } + composeOptions ); } catch (error) { throw wrapStepError('compose', error); @@ -1025,6 +1101,8 @@ 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 182ca474..6087833e 100644 --- a/apps/stock/data-pipeline/src/security-master/run.ts +++ b/apps/stock/data-pipeline/src/security-master/run.ts @@ -22,10 +22,12 @@ 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, @@ -46,6 +48,8 @@ import { sourceCountryKey, type BuildMatchReportOptions, type CountryResolutionSummary, + type GateOutOfScopeLookup, + type GateOutOfScopeReason, type MatchReport, type RenderMatchReportMarkdownOptions, type SourceCountryLookup, @@ -933,7 +937,8 @@ function applyEndToEndStageACoverage( const unresolved = row.unresolved + d.unresolved; const conflict = row.conflict + d.conflict; const excludedByDesign = row.excludedByDesign + d.excludedByDesign; - const eligibleTotal = Math.max(0, total - excludedByDesign); + const outOfGateScope = row.outOfGateScope ?? 0; + const eligibleTotal = Math.max(0, total - excludedByDesign - outOfGateScope); return { source: row.source, total, @@ -941,6 +946,7 @@ function applyEndToEndStageACoverage( unresolved, conflict, excludedByDesign, + ...(row.outOfGateScope !== undefined ? { outOfGateScope } : {}), eligibleTotal, resolvedPct: total > 0 ? row.matched / total : null, eligibleResolvedPct: eligibleTotal > 0 ? row.matched / eligibleTotal : null, @@ -1175,6 +1181,143 @@ 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 } : {}), @@ -1183,6 +1326,12 @@ export function composeSecurityMasterRun( ...(pass4 !== null ? { priceCrossCheck: pass4 } : {}), delistingChains: pass6, sourceCountries, + ...(gateOutOfScope !== undefined + ? { + gateOutOfScope, + gateDenominatorNote: US_CA_EQUITY_GATE_DENOMINATOR_NOTE, + } + : {}), }, options.report ); @@ -1208,6 +1357,29 @@ export function composeSecurityMasterRun( 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, @@ -1222,7 +1394,7 @@ export function composeSecurityMasterRun( let stageAUnresolved = 0; for (const source of STAGE_A_SOURCES) { const s = stageA.stats.bySource[source]; - stageAResolved += s.tier1Isin + s.tier2Cusip; + stageAResolved += s.tier1Isin + s.tier2Cusip + (s.tier3Synthetic ?? 0); 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 new file mode 100644 index 00000000..da009d68 --- /dev/null +++ b/apps/stock/data-pipeline/src/security-master/source-field-shapes.ts @@ -0,0 +1,915 @@ +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 58b7ea6a..4397339e 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,6 +53,9 @@ export const DEFAULT_SOURCE_COUNTRIES: readonly string[] = Object.freeze(['US', export interface SourceSymbolFindOptions { projection?: Record; batchSize?: number; + limit?: number; + promoteValues?: boolean; + promoteLongs?: boolean; } /** @@ -161,6 +164,7 @@ export interface ReadSourceCollectionOptions { readonly knownExchanges?: readonly ExchangeSeedRow[]; readonly batchSize?: number; readonly maxSecurityTypeConflicts?: number; + readonly includeExtendedMetadata?: boolean; } export type ReadSecurityMasterSourcesOptions = ReadSourceCollectionOptions; @@ -175,6 +179,7 @@ export interface AdaptEodSymbolContext { export interface AdaptIbSymbolContext { readonly exchangeLookup: ExchangeSourceLookup; readonly allowedCountries: ReadonlySet | null; + readonly includeExtendedMetadata?: boolean; } export interface AdaptQmSymbolContext { @@ -182,6 +187,7 @@ export interface AdaptQmSymbolContext { readonly barSpans?: Pick | null; readonly allowedCountries: ReadonlySet | null; readonly micCurrencyMap: ReadonlyMap; + readonly includeExtendedMetadata?: boolean; } export interface AdaptCeoSymbolContext { @@ -189,6 +195,7 @@ export interface AdaptCeoSymbolContext { readonly ceoSpans?: ReadonlyMap | null; readonly allowedCountries: ReadonlySet | null; readonly micCurrencyMap: ReadonlyMap; + readonly includeExtendedMetadata?: boolean; } export interface AdaptEodSymbolChangeContext { @@ -439,7 +446,9 @@ 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, @@ -1353,6 +1362,13 @@ export function adaptIbSymbolDoc( conid: rawConid, currency, primaryExchange, + ...(context.includeExtendedMetadata === true + ? { + ticker: symbolField.value, + name, + exchangeId: exchangeIdField.value !== null ? exchangeIdField.value.toUpperCase() : null, + } + : {}), }, invalidIdentifiersNulled, }; @@ -1433,6 +1449,11 @@ 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, @@ -1444,6 +1465,7 @@ export function adaptQmSymbolDoc( role: exchangeEntry.role, currency, span, + ...(context.includeExtendedMetadata === true ? { name: qmName } : {}), }, }; } @@ -1536,6 +1558,10 @@ 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: { @@ -1546,6 +1572,7 @@ export function adaptCeoSymbolDoc( role: exchangeEntry.role, currency, span, + ...(context.includeExtendedMetadata === true ? { name: ceoName } : {}), }, }; } @@ -1562,8 +1589,8 @@ export function adaptEodSymbolChangeDoc( return { ok: false, skipReason: 'invalidFieldType' }; } - const oldSymbolField = readOptionalString(doc, 'oldSymbol'); - const newSymbolField = readOptionalString(doc, 'newSymbol'); + const oldSymbolField = readFirstOptionalString(doc, ['oldSymbol', 'old_symbol']); + const newSymbolField = readFirstOptionalString(doc, ['newSymbol', 'new_symbol']); const exchangeField = readOptionalString(doc, 'exchange'); const eodExchangeField = readOptionalString(doc, 'eodExchange'); const eodSearchCodeField = readOptionalString(doc, 'eodSearchCode'); @@ -1763,6 +1790,7 @@ export async function readIbSymbols( const context: AdaptIbSymbolContext = { exchangeLookup: options.exchangeLookup, allowedCountries, + includeExtendedMetadata: options.includeExtendedMetadata, }; const stageARecords: StageASourceRecord[] = []; @@ -1811,6 +1839,7 @@ export async function readQmSymbols( barSpans: options.barSpans, allowedCountries, micCurrencyMap, + includeExtendedMetadata: options.includeExtendedMetadata, }; const tickerSources: StageBTickerSourceInput[] = []; @@ -1843,6 +1872,26 @@ 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, @@ -1855,9 +1904,15 @@ 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 = { @@ -1877,11 +1932,59 @@ export async function readCeoSymbols( stats.skips[adapted.skipReason] += 1; return; } - tickerSources.push(adapted.tickerSource); - stats.emitted += 1; + 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, + }); } ); + // 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 new file mode 100644 index 00000000..ce74b95f --- /dev/null +++ b/apps/stock/data-pipeline/test/export-raw-bson-qa.test.ts @@ -0,0 +1,293 @@ +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 new file mode 100644 index 00000000..e1fc3b59 --- /dev/null +++ b/apps/stock/data-pipeline/test/export-raw-bson.test.ts @@ -0,0 +1,667 @@ +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 new file mode 100644 index 00000000..a0c6ab21 --- /dev/null +++ b/apps/stock/data-pipeline/test/run-export-raw-bson.test.ts @@ -0,0 +1,399 @@ +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 new file mode 100644 index 00000000..a035b01f --- /dev/null +++ b/apps/stock/data-pipeline/test/source-field-shapes-qa.test.ts @@ -0,0 +1,364 @@ +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 new file mode 100644 index 00000000..47e150e9 --- /dev/null +++ b/apps/stock/data-pipeline/test/source-field-shapes.test.ts @@ -0,0 +1,812 @@ +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 b91d5c52..9a537c0b 100644 --- a/bun.lock +++ b/bun.lock @@ -355,6 +355,17 @@ "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", @@ -540,6 +551,22 @@ "@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=="], @@ -704,6 +731,8 @@ "@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/design/DATA-CONTRACTS.md b/design/DATA-CONTRACTS.md index bec7f246..9f973afe 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`. `eodSymbolChange`: only `230` US rows (`2024-08..2025-07`). | Filter `splitratio == 1`; ignore `usdFxRate`; 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`; 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. | | `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,6 +184,16 @@ 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). + --- ## 3. Curated Storage Schemas diff --git a/design/README.md b/design/README.md index 0157ab05..978b8c69 100644 --- a/design/README.md +++ b/design/README.md @@ -13,6 +13,7 @@ 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 | --- diff --git a/design/data-pipeline/m1-ca-study-result.json b/design/data-pipeline/m1-ca-study-result.json new file mode 100644 index 00000000..1817e036 --- /dev/null +++ b/design/data-pipeline/m1-ca-study-result.json @@ -0,0 +1,78 @@ +{ + "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 new file mode 100644 index 00000000..06059bc2 --- /dev/null +++ b/design/data-pipeline/m1-quant-benchmark-result.json @@ -0,0 +1,117 @@ +{ + "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 new file mode 100644 index 00000000..429b3236 --- /dev/null +++ b/design/data-pipeline/m1-source-field-shapes.md @@ -0,0 +1,167 @@ +# 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 new file mode 100644 index 00000000..c92ce767 --- /dev/null +++ b/design/data-pipeline/m1-us-ca-match-report.md @@ -0,0 +1,332 @@ +# 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 new file mode 100644 index 00000000..2039d470 --- /dev/null +++ b/design/data-pipeline/rust-migration-evaluation.md @@ -0,0 +1,294 @@ +# 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/libs/data/duckdb/package.json b/libs/data/duckdb/package.json new file mode 100644 index 00000000..7636fd30 --- /dev/null +++ b/libs/data/duckdb/package.json @@ -0,0 +1,23 @@ +{ + "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 new file mode 100644 index 00000000..2d3bf3d9 --- /dev/null +++ b/libs/data/duckdb/src/index.ts @@ -0,0 +1,266 @@ +/** + * 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); + const connection: DuckDBConnection = await instance.connect(); + 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, +}; diff --git a/libs/data/duckdb/test/duckdb-market-data-store.test.ts b/libs/data/duckdb/test/duckdb-market-data-store.test.ts new file mode 100644 index 00000000..d43bd44c --- /dev/null +++ b/libs/data/duckdb/test/duckdb-market-data-store.test.ts @@ -0,0 +1,250 @@ +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(); + } + }); +}); diff --git a/libs/data/duckdb/tsconfig.json b/libs/data/duckdb/tsconfig.json new file mode 100644 index 00000000..49cb7b59 --- /dev/null +++ b/libs/data/duckdb/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "../../../tsconfig.json", + "compilerOptions": { + "outDir": "./dist", + "rootDir": "./src", + "composite": true + }, + "include": ["src/**/*"], + "references": [ + { + "path": "../../research" + } + ] +} diff --git a/libs/research/README.md b/libs/research/README.md index 8f0d6452..919c2b6d 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -74,3 +74,125 @@ 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 <= ?`. +- **`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`, `fundamentalsAsOf`, `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`) + +## 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`) diff --git a/libs/research/package.json b/libs/research/package.json index dd8dd698..89c29140 100644 --- a/libs/research/package.json +++ b/libs/research/package.json @@ -10,8 +10,11 @@ ".": "./src/index.ts", "./dataset-contracts": "./src/dataset-contracts.ts", "./datasets": "./src/datasets.ts", + "./event-panel": "./src/event-panel.ts", "./market-data-store": "./src/market-data-store.ts", + "./market-data-store-duckdb": "./src/market-data-store-duckdb.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 new file mode 100644 index 00000000..de8e2c60 --- /dev/null +++ b/libs/research/scripts/benchmark-event-panel.ts @@ -0,0 +1,230 @@ +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 new file mode 100644 index 00000000..172f91b6 --- /dev/null +++ b/libs/research/scripts/benchmark-market-data-store-duckdb.ts @@ -0,0 +1,352 @@ +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 new file mode 100644 index 00000000..b6b41fb4 --- /dev/null +++ b/libs/research/scripts/benchmark-signal-panel.ts @@ -0,0 +1,196 @@ +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 new file mode 100644 index 00000000..53928a35 --- /dev/null +++ b/libs/research/src/event-panel.ts @@ -0,0 +1,1069 @@ +/** + * 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/index.ts b/libs/research/src/index.ts index fd3691a2..3d57d822 100644 --- a/libs/research/src/index.ts +++ b/libs/research/src/index.ts @@ -1,5 +1,8 @@ // The default entrypoint is browser safe; server validation is an explicit subpath. export * from './dataset-contracts'; +export * from './event-panel'; export * from './market-data-store'; +export * from './market-data-store-duckdb'; +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 new file mode 100644 index 00000000..0d3013ba --- /dev/null +++ b/libs/research/src/market-data-store-duckdb.ts @@ -0,0 +1,2056 @@ +/** + * 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` + * + * `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, + 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; + +type ColumnScalarKind = 'int32' | 'safe_int' | 'number' | 'string'; + +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 }, +]; + +/** 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]; + +/** + * 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 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, + }, + }; +} + +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; + } +} + +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')); + }, + + fundamentalsAsOf(): Promise
{ + return Promise.reject(new MarketDataStoreNotImplementedError('fundamentalsAsOf')); + }, + + 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/panel-shared.ts b/libs/research/src/panel-shared.ts new file mode 100644 index 00000000..8e540224 --- /dev/null +++ b/libs/research/src/panel-shared.ts @@ -0,0 +1,172 @@ +/** + * 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/signal-panel.ts b/libs/research/src/signal-panel.ts new file mode 100644 index 00000000..60d5f82a --- /dev/null +++ b/libs/research/src/signal-panel.ts @@ -0,0 +1,825 @@ +/** + * 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/test/event-panel-e2e.test.ts b/libs/research/test/event-panel-e2e.test.ts new file mode 100644 index 00000000..4ac07daa --- /dev/null +++ b/libs/research/test/event-panel-e2e.test.ts @@ -0,0 +1,729 @@ +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 new file mode 100644 index 00000000..23ef342a --- /dev/null +++ b/libs/research/test/event-panel-qa.test.ts @@ -0,0 +1,672 @@ +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 new file mode 100644 index 00000000..a5979670 --- /dev/null +++ b/libs/research/test/event-panel.test.ts @@ -0,0 +1,1181 @@ +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/market-data-store-duckdb-universe.qa.test.ts b/libs/research/test/market-data-store-duckdb-universe.qa.test.ts new file mode 100644 index 00000000..c98578fb --- /dev/null +++ b/libs/research/test/market-data-store-duckdb-universe.qa.test.ts @@ -0,0 +1,420 @@ +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 new file mode 100644 index 00000000..ed8ba65a --- /dev/null +++ b/libs/research/test/market-data-store-duckdb.qa.test.ts @@ -0,0 +1,318 @@ +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 new file mode 100644 index 00000000..fe7922b0 --- /dev/null +++ b/libs/research/test/market-data-store-duckdb.test.ts @@ -0,0 +1,2870 @@ +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, + FX_1D_COLUMNS, + FX_PAIR_MAP, + MarketDataStoreNotImplementedError, + MarketDataStoreValidationError, + type PinnedAdjFactorsArtifact, + SHORTS_COLUMNS, + type TableRow, + UNIVERSE_REFS, + VaultHoldoutFenceError, + VaultScopeNotAuthorizedError, + createDuckDbMarketDataStore, + parseAdjFactorsSnapshotMetadata, + planAdjFactorsMetadataQuery, + planBars1dQuery, + planEventsQuery, + 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, + 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, + 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(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: 'fundamentalsAsOf', + run: () => + store.fundamentalsAsOf({ + listingIds: [1], + fields: ['revenue'], + asOf: '2025-01-15', + }), + }, + { + 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 + ); + } + }); +}); diff --git a/libs/research/test/signal-panel-e2e.test.ts b/libs/research/test/signal-panel-e2e.test.ts new file mode 100644 index 00000000..379e3c42 --- /dev/null +++ b/libs/research/test/signal-panel-e2e.test.ts @@ -0,0 +1,403 @@ +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 new file mode 100644 index 00000000..2ba94a03 --- /dev/null +++ b/libs/research/test/signal-panel-qa.test.ts @@ -0,0 +1,540 @@ +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 new file mode 100644 index 00000000..6f4ca1c5 --- /dev/null +++ b/libs/research/test/signal-panel.test.ts @@ -0,0 +1,766 @@ +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/python/benchmarks/m1_quant_scan_benchmark.py b/python/benchmarks/m1_quant_scan_benchmark.py new file mode 100644 index 00000000..6173d936 --- /dev/null +++ b/python/benchmarks/m1_quant_scan_benchmark.py @@ -0,0 +1,599 @@ +"""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 new file mode 100644 index 00000000..0e5315d0 --- /dev/null +++ b/python/pyproject.toml @@ -0,0 +1,29 @@ +[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 new file mode 100644 index 00000000..c61316f0 --- /dev/null +++ b/python/stockbot/__init__.py @@ -0,0 +1,80 @@ +"""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 new file mode 100644 index 00000000..c898b69a --- /dev/null +++ b/python/stockbot/calculations.py @@ -0,0 +1,494 @@ +"""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 new file mode 100644 index 00000000..5fca1827 --- /dev/null +++ b/python/stockbot/data.py @@ -0,0 +1,295 @@ +"""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 new file mode 100644 index 00000000..ecd89305 --- /dev/null +++ b/python/stockbot/ledger.py @@ -0,0 +1,269 @@ +"""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 new file mode 100644 index 00000000..da18fbb4 --- /dev/null +++ b/python/stockbot/signals.py @@ -0,0 +1,137 @@ +"""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 new file mode 100644 index 00000000..b3e714dc --- /dev/null +++ b/python/stockbot/vault.py @@ -0,0 +1,226 @@ +"""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 new file mode 100644 index 00000000..55ba8fbe --- /dev/null +++ b/python/tests/test_stockbot_sdk.py @@ -0,0 +1,153 @@ +"""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 new file mode 100644 index 00000000..e673a52e --- /dev/null +++ b/python/uv.lock @@ -0,0 +1,1308 @@ +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 new file mode 100644 index 00000000..f116355e --- /dev/null +++ b/research/notebooks/ca_shorts_filings_study.py @@ -0,0 +1,251 @@ +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/test/postgres/security-master-export-curate-inputs.test.ts b/test/postgres/security-master-export-curate-inputs.test.ts new file mode 100644 index 00000000..51705ecd --- /dev/null +++ b/test/postgres/security-master-export-curate-inputs.test.ts @@ -0,0 +1,493 @@ +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 new file mode 100644 index 00000000..aa5f1489 --- /dev/null +++ b/test/unit/data-pipeline-rust-evaluation-doc.test.ts @@ -0,0 +1,192 @@ +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/mongodb-read-only.test.ts b/test/unit/mongodb-read-only.test.ts index 27e94434..4fc604aa 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 { MongoClient } from 'mongodb'; +import { BSON, MongoClient } from 'mongodb'; import { getLogger, setLoggerConfig } from '@stock-bot/logger'; import { MongoDBClient } from '@stock-bot/mongodb'; @@ -1196,4 +1196,82 @@ 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 new file mode 100644 index 00000000..88052c91 --- /dev/null +++ b/test/unit/security-master-export-curate-inputs-parity.test.ts @@ -0,0 +1,740 @@ +/** + * 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 new file mode 100644 index 00000000..9d3f728d --- /dev/null +++ b/test/unit/security-master-export-curate-inputs.test.ts @@ -0,0 +1,1619 @@ +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 new file mode 100644 index 00000000..f911a21e --- /dev/null +++ b/test/unit/security-master-m1-gate-denominator.test.ts @@ -0,0 +1,288 @@ +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 2f81cd3a..b4755d02 100644 --- a/tools/curate-etl/Cargo.toml +++ b/tools/curate-etl/Cargo.toml @@ -7,5 +7,7 @@ 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 fe50b9b4..1b9ab54e 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -1,6 +1,6 @@ # `curate-etl` -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`. +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`). ## Scope & Sign Conventions @@ -158,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`: MongoDB `qmFilings` / `qmEarnings` BSON cursors, `provider_mapping` `listing_id` resolution, Zstd Parquet writing, and M2 `fundamentals_pit` joins. +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`). ## `provider_mapping` Table (`M1.2h`) @@ -192,13 +192,17 @@ 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. - - Deterministic `created_by` metadata so identical inputs produce byte-identical `part.parquet` files. + - **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). 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 }` @@ -453,7 +457,29 @@ 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, end-to-end `curate bars_1d` CLI command, and decoders for other collections (`qmPrices`, `qmSplits`, `qmDividends`, `ceoShorts`, `qmFilings`, `qmEarnings`, `eodIntraday1M`). + - 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. ## Local Benchmarks @@ -669,6 +695,54 @@ 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` + - 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: @@ -841,3 +915,649 @@ 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. + +## 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). + +## 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-*`). diff --git a/tools/curate-etl/src/bench.rs b/tools/curate-etl/src/bench.rs index 02b8bbd7..084869fd 100644 --- a/tools/curate-etl/src/bench.rs +++ b/tools/curate-etl/src/bench.rs @@ -9,14 +9,22 @@ use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; use std::time::Instant; use bson::oid::ObjectId; -use bson::raw::{cstr, RawDocumentBuf}; +use bson::raw::{cstr, RawBsonRef, 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::bson_eod_prices::{decode_eod_price_buffer, BsonEodDecodeStats}; +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::corporate_actions::{ build_corporate_actions, CorporateActionError, CorporateActionKind, CorporateActionsStats, DelistingOutcomeEvent, DividendActionEvent, KnownAtSource, SplitActionEvent, @@ -79,6 +87,9 @@ 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; @@ -104,6 +115,7 @@ 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]; @@ -3144,6 +3156,13 @@ 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(), @@ -3615,28 +3634,7 @@ pub struct BsonEodPricesBenchReport { pub stats: BsonEodDecodeStats, } -/// 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(), - }; - } - +fn build_bson_eod_prices_bench_buffer(rows: usize) -> Vec { const SYMBOL_POOL: usize = 2_000; const EXCHANGES: [&str; 4] = ["NASDAQ", "NYSE", "TSX", "TSXV"]; const PROVIDER_EXCHANGES: [&str; 4] = ["US", "US", "TO", "V"]; @@ -3750,6 +3748,33 @@ pub fn run_bson_eod_prices_benchmark(rows: usize) -> BsonEodPricesBenchReport { 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; @@ -3792,6 +3817,600 @@ 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; @@ -4427,6 +5046,824 @@ 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; @@ -5385,6 +6822,3639 @@ 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) +} + #[cfg(test)] mod tests { use super::*; @@ -6211,6 +11281,140 @@ 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(); @@ -6721,4 +11925,618 @@ 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); + } } diff --git a/tools/curate-etl/src/bson_ceo_shorts.rs b/tools/curate-etl/src/bson_ceo_shorts.rs new file mode 100644 index 00000000..dff169a0 --- /dev/null +++ b/tools/curate-etl/src/bson_ceo_shorts.rs @@ -0,0 +1,627 @@ +//! 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 new file mode 100644 index 00000000..cac3c154 --- /dev/null +++ b/tools/curate-etl/src/bson_ceo_shorts_tests.rs @@ -0,0 +1,732 @@ +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_prices.rs b/tools/curate-etl/src/bson_eod_prices.rs index 9547f250..a7602240 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; -const MILLIS_PER_DAY: i64 = 86_400_000; +pub(crate) 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,6 +235,26 @@ 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] @@ -250,22 +270,20 @@ fn parse_ascii_digits_u32(bytes: &[u8]) -> Option { } #[inline] -fn parse_ymd_strict(s: &str) -> Result { +pub(crate) fn parse_ymd_strict_days(s: &str) -> Option { let bytes = s.as_bytes(); if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' { - return Err(BsonEodPriceError::MalformedDate { field: "date" }); + return None; } - 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" }) + 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" }) } #[inline] @@ -332,6 +350,7 @@ 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 { @@ -344,56 +363,113 @@ fn decode_eod_price_doc_at<'a>( match decode_element_value("eodSearchCode", elem, offset)? { RawBsonRef::String(s) => { if s.trim().is_empty() { - return Err(BsonEodPriceError::EmptyField { - field: "eodSearchCode", - }); + if first_semantic_err.is_none() { + first_semantic_err = Some(BsonEodPriceError::EmptyField { + field: "eodSearchCode", + }); + } + } else { + eod_search_code = Some(s); } - eod_search_code = Some(s); } other => { - return Err(BsonEodPriceError::WrongType { - field: "eodSearchCode", - actual: other.element_type(), - }); + if first_semantic_err.is_none() { + first_semantic_err = Some(BsonEodPriceError::WrongType { + field: "eodSearchCode", + actual: other.element_type(), + }); + } } } } else if key == cstr!("date") { match decode_element_value("date", elem, offset)? { - RawBsonRef::String(s) => { - session_date = Some(parse_ymd_strict(s)?); - } + 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::DateTime(dt) => { let days = dt.timestamp_millis().div_euclid(MILLIS_PER_DAY); - let day_i32 = i32::try_from(days) - .map_err(|_| BsonEodPriceError::MalformedDate { field: "date" })?; - session_date = Some(day_i32); + 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" }); + } + } + } } other => { - return Err(BsonEodPriceError::WrongType { - field: "date", - actual: other.element_type(), - }); + if first_semantic_err.is_none() { + first_semantic_err = Some(BsonEodPriceError::WrongType { + field: "date", + actual: other.element_type(), + }); + } } } } else if key == cstr!("open") { let val = decode_element_value("open", elem, offset)?; - open = Some(decode_non_negative_number("open", val)?); + 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); + } + } + } } else if key == cstr!("high") { let val = decode_element_value("high", elem, offset)?; - high = Some(decode_non_negative_number("high", val)?); + 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); + } + } + } } else if key == cstr!("low") { let val = decode_element_value("low", elem, offset)?; - low = Some(decode_non_negative_number("low", val)?); + 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); + } + } + } } else if key == cstr!("close") { let val = decode_element_value("close", elem, offset)?; - close = Some(decode_non_negative_number("close", val)?); + 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); + } + } + } } else if key == cstr!("volume") { let val = decode_element_value("volume", elem, offset)?; - adj_volume = Some(decode_non_negative_number("volume", val)?); + 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); + } + } + } } // 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", @@ -438,11 +514,7 @@ pub fn decode_eod_price_doc<'a>( decode_eod_price_doc_at(doc, 0) } -/// 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> { +pub(crate) fn parse_single_raw_doc(bytes: &[u8]) -> Result<&RawDocument, BsonEodPriceError> { if bytes.len() < 4 { return Err(BsonEodPriceError::TruncatedDocument { offset: 0, @@ -471,10 +543,18 @@ pub fn decode_eod_price_bytes<'a>( declared_len, }); } - let doc = RawDocument::from_bytes(bytes).map_err(|err| BsonEodPriceError::CorruptBson { + 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 e5a614b5..42def67e 100644 --- a/tools/curate-etl/src/bson_eod_prices_tests.rs +++ b/tools/curate-etl/src/bson_eod_prices_tests.rs @@ -783,3 +783,20 @@ 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 new file mode 100644 index 00000000..210e6d45 --- /dev/null +++ b/tools/curate-etl/src/bson_qm_actions.rs @@ -0,0 +1,863 @@ +//! 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 new file mode 100644 index 00000000..e49a76fe --- /dev/null +++ b/tools/curate-etl/src/bson_qm_actions_tests.rs @@ -0,0 +1,918 @@ +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 new file mode 100644 index 00000000..91b9e597 --- /dev/null +++ b/tools/curate-etl/src/bson_qm_events.rs @@ -0,0 +1,1072 @@ +//! 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 new file mode 100644 index 00000000..01df13f6 --- /dev/null +++ b/tools/curate-etl/src/bson_qm_events_tests.rs @@ -0,0 +1,500 @@ +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_prices.rs b/tools/curate-etl/src/bson_qm_prices.rs new file mode 100644 index 00000000..10c82ee6 --- /dev/null +++ b/tools/curate-etl/src/bson_qm_prices.rs @@ -0,0 +1,458 @@ +//! 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 new file mode 100644 index 00000000..f94f4442 --- /dev/null +++ b/tools/curate-etl/src/bson_qm_prices_tests.rs @@ -0,0 +1,413 @@ +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 new file mode 100644 index 00000000..b8cf17f1 --- /dev/null +++ b/tools/curate-etl/src/bson_stream.rs @@ -0,0 +1,1082 @@ +//! 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_shorts::{ + decode_ceo_shorts_buffer, BsonCeoShortsDecodeStats, BsonCeoShortsError, CeoShortsFieldNames, +}; +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_prices::{ + decode_qm_price_buffer, BsonQmPriceDecodeStats, BsonQmPriceError, RawQmPrice, +}; +use crate::bson_te_market_data::{ + decode_te_market_data_buffer, BsonTeMarketDataDecodeStats, BsonTeMarketDataError, +}; +use crate::fx::FxDailyBar; +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, + } +} + +/// 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) +} + +/// 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) +} + +#[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 new file mode 100644 index 00000000..500300f6 --- /dev/null +++ b/tools/curate-etl/src/bson_stream_tests.rs @@ -0,0 +1,2115 @@ +use std::error::Error as _; +use std::io::{self, Cursor, Read}; + +use bson::raw::{cstr, RawDocumentBuf}; +use bson::DateTime; + +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_prices::{decode_qm_price_buffer, BsonQmPriceError}; +use crate::bson_stream::{ + decode_eod_price_stream, decode_qm_dividend_stream, decode_qm_price_stream, + decode_qm_split_stream, BsonStreamError, BsonStreamOptions, RawBsonChunkReader, + DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES, +}; + +#[derive(Debug, Clone, Copy)] +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_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 { .. })); +} diff --git a/tools/curate-etl/src/bson_te_market_data.rs b/tools/curate-etl/src/bson_te_market_data.rs new file mode 100644 index 00000000..fd9cff97 --- /dev/null +++ b/tools/curate-etl/src/bson_te_market_data.rs @@ -0,0 +1,839 @@ +//! 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 new file mode 100644 index 00000000..69bb354c --- /dev/null +++ b/tools/curate-etl/src/bson_te_market_data_tests.rs @@ -0,0 +1,522 @@ +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 95fc40b6..73f35d58 100644 --- a/tools/curate-etl/src/cli.rs +++ b/tools/curate-etl/src/cli.rs @@ -3,22 +3,69 @@ //! 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_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_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_FX_BENCH_ROWS, + DEFAULT_MONGO_STREAM_BENCH_ROWS, DEFAULT_PARQUET_ADJ_BENCH_ROWS, + DEFAULT_PARQUET_BARS_BENCH_ROWS, DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS, DEFAULT_PARQUET_EVENTS_BENCH_ROWS, DEFAULT_PARQUET_FX_BENCH_ROWS, DEFAULT_PARQUET_SHORTS_BENCH_ROWS, DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS, DEFAULT_SHORTS_BENCH_ROWS, }; +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::curate_adj::AdjPointInTimeFence; +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_corporate_actions::CurateCorporateActionsArgs; +use crate::run_curate_events::{CurateEventsArgs, DEFAULT_EVENTS_MAPPING_SOURCE}; +use crate::run_curate_fx::{is_supported_te_symbol, CurateFx1dArgs, DEFAULT_TE_SYMBOL}; +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, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq)] 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), BenchSplit(usize), BenchAdj(usize), BenchCorporateActions(usize), @@ -34,10 +81,21 @@ 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. @@ -48,6 +106,24 @@ 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} 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\ @@ -63,10 +139,21 @@ 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-fx [rows] Run fixed-seed fx_1d curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_FX_BENCH_ROWS})" + {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})" ) } @@ -76,6 +163,12 @@ 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} bench-split [rows]\n\ {name} bench-adj [events]\n\ {name} bench-corporate-actions [events]\n\ @@ -91,13 +184,1233 @@ 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-fx [rows]" + {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]" ) } +/// 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 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; + } + + 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 { + "--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_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)) +} + /// 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(); @@ -107,6 +1420,12 @@ 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), ["bench-split"] => Ok(CliAction::BenchSplit(DEFAULT_BENCH_ROWS)), ["bench-split", raw] => match raw.parse::() { Ok(n) if n > 0 => Ok(CliAction::BenchSplit(n)), @@ -259,6 +1578,38 @@ 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)), @@ -269,6 +1620,18 @@ 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)) } @@ -281,6 +1644,18 @@ 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)) } @@ -293,6 +1668,18 @@ 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)), @@ -301,6 +1688,62 @@ 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}'")), } } @@ -588,6 +2031,56 @@ 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"); @@ -606,10 +2099,20 @@ 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")); @@ -627,10 +2130,20 @@ 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] @@ -700,4 +2213,1166 @@ 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()); + } } diff --git a/tools/curate-etl/src/curate_adj.rs b/tools/curate-etl/src/curate_adj.rs new file mode 100644 index 00000000..fa22c910 --- /dev/null +++ b/tools/curate-etl/src/curate_adj.rs @@ -0,0 +1,1944 @@ +//! 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 new file mode 100644 index 00000000..b4a4d0b9 --- /dev/null +++ b/tools/curate-etl/src/curate_adj_tests.rs @@ -0,0 +1,2312 @@ +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 515b3f8d..cf2e7fa0 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_corporate_actions.rs b/tools/curate-etl/src/curate_corporate_actions.rs new file mode 100644 index 00000000..07711998 --- /dev/null +++ b/tools/curate-etl/src/curate_corporate_actions.rs @@ -0,0 +1,600 @@ +//! 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 new file mode 100644 index 00000000..ea9aca5e --- /dev/null +++ b/tools/curate-etl/src/curate_corporate_actions_tests.rs @@ -0,0 +1,1658 @@ +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/lib.rs b/tools/curate-etl/src/lib.rs index 0fffc229..023e1f16 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -3,11 +3,19 @@ pub mod adj; pub mod bars; pub mod bench; +pub mod bson_ceo_shorts; pub mod bson_eod_prices; +pub mod bson_qm_actions; +pub mod bson_qm_events; +pub mod bson_qm_prices; +pub mod bson_stream; +pub mod bson_te_market_data; pub mod cli; pub mod corporate_actions; pub mod events; pub mod fx; +pub mod mongo_safety; +pub mod mongo_stream; pub mod parquet_adj; pub mod parquet_bars; pub mod parquet_corporate_actions; @@ -28,10 +36,50 @@ pub use bars::{ build_bars_1d, Bar1dRow, Bars1dBuild, Bars1dStats, BarsError, EodDailyBar, QmRawVolume, VolumeMismatchSample, MAX_MISMATCH_SAMPLES, }; +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_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_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_shorts_chunks, decode_ceo_shorts_stream, decode_eod_price_chunks, + decode_eod_price_stream, decode_qm_dividend_chunks, decode_qm_dividend_stream, + decode_qm_earnings_chunks, decode_qm_earnings_stream, decode_qm_filings_chunks, + decode_qm_filings_stream, decode_qm_price_chunks, decode_qm_price_stream, + decode_qm_split_chunks, decode_qm_split_stream, decode_te_market_data_chunks, + decode_te_market_data_stream, BsonCeoShortsStreamError, BsonQmEventsStreamError, + BsonStreamError, BsonStreamOptions, RawBsonChunk, RawBsonChunkReader, + DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES, +}; +pub use bson_te_market_data::{ + 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, @@ -49,14 +97,27 @@ 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 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, write_bars_1d_dataset, Bars1dParquetRow, Bars1dWriteOptions, - Bars1dWriteStats, ParquetBarsError, RollbackFailure, DEFAULT_ROW_GROUP_ROWS, - DEFAULT_ZSTD_LEVEL, MAX_PARQUET_YEAR, MIN_PARQUET_YEAR, + 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, }; pub use parquet_corporate_actions::{ corporate_actions_parquet_schema, write_corporate_actions_dataset, CorporateActionsParquetRow, @@ -121,3 +182,71 @@ pub use curate_fx::{ 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 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_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_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 tsv_fixture_tests; diff --git a/tools/curate-etl/src/main.rs b/tools/curate-etl/src/main.rs index fc5eca9e..e54fba0a 100644 --- a/tools/curate-etl/src/main.rs +++ b/tools/curate-etl/src/main.rs @@ -5,13 +5,33 @@ use std::process::ExitCode; use curate_etl::bench::{ 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, + run_bson_qm_actions_benchmark, run_bson_stream_benchmark, run_corporate_actions_benchmark, + run_curate_adj_benchmark, run_curate_adj_cmd_benchmark, run_curate_bars_benchmark, + run_curate_bars_cmd_benchmark, run_curate_corporate_actions_benchmark, + run_curate_corporate_actions_cmd_benchmark, run_curate_events_benchmark, + run_curate_events_cmd_benchmark, run_curate_fx_benchmark, run_curate_fx_cmd_benchmark, + run_curate_shorts_benchmark, run_curate_shorts_command_benchmark, run_events_benchmark, + run_fx_benchmark, run_mongo_stream_benchmark, run_parquet_adj_benchmark, + run_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::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_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_fx::{format_curate_fx_report, run_curate_fx_1d}; +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"); @@ -28,6 +48,154 @@ 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::BenchSplit(rows)) => { let report = match run_split_benchmark(rows) { Ok(report) => report, @@ -503,6 +671,118 @@ 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, @@ -572,6 +852,104 @@ 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, @@ -694,6 +1072,74 @@ 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, @@ -758,6 +1204,407 @@ 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 new file mode 100644 index 00000000..32ead4fc --- /dev/null +++ b/tools/curate-etl/src/mongo_safety.rs @@ -0,0 +1,1068 @@ +//! 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 new file mode 100644 index 00000000..dbc12fe8 --- /dev/null +++ b/tools/curate-etl/src/mongo_safety_tests.rs @@ -0,0 +1,2580 @@ +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 new file mode 100644 index 00000000..35564c58 --- /dev/null +++ b/tools/curate-etl/src/mongo_stream.rs @@ -0,0 +1,1237 @@ +//! 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 new file mode 100644 index 00000000..41fa6da4 --- /dev/null +++ b/tools/curate-etl/src/mongo_stream_tests.rs @@ -0,0 +1,1941 @@ +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 5367748e..ebfa4643 100644 --- a/tools/curate-etl/src/parquet_bars.rs +++ b/tools/curate-etl/src/parquet_bars.rs @@ -16,6 +16,7 @@ //! 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; @@ -23,8 +24,10 @@ 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; +use std::sync::{Arc, Mutex}; use std::time::Duration; use parquet::basic::{Compression, LogicalType, Repetition, TimeUnit, Type as PhysicalType, ZstdLevel}; @@ -33,6 +36,7 @@ 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, @@ -49,6 +53,18 @@ 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 { @@ -71,6 +87,7 @@ pub struct Bars1dParquetRow { pub struct Bars1dWriteOptions { pub row_group_rows: usize, pub zstd_level: i32, + pub threads: usize, } impl Default for Bars1dWriteOptions { @@ -78,6 +95,7 @@ impl Default for Bars1dWriteOptions { Self { row_group_rows: DEFAULT_ROW_GROUP_ROWS, zstd_level: DEFAULT_ZSTD_LEVEL, + threads: DEFAULT_WRITE_THREADS, } } } @@ -99,6 +117,15 @@ 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, @@ -143,6 +170,16 @@ 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, @@ -391,6 +428,22 @@ 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(), @@ -398,7 +451,7 @@ impl YearWriter { })?; let (tmp_path, file) = create_exclusive_tmp_file(&year_dir, run_id)?; - owned_tmp_paths.push(tmp_path.clone()); + record_tmp(tmp_path.clone()); let final_path = year_dir.join("part.parquet"); let buf_writer = BufWriter::with_capacity(FILE_BUF_CAPACITY_BYTES, file); @@ -587,17 +640,52 @@ 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 { @@ -608,6 +696,9 @@ 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 { @@ -648,86 +739,229 @@ 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 write_result: Result, ParquetBarsError> = (|| { - let mut prev_key: Option<(i32, i32)> = None; + 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); - 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, - }); + 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 => {} } - 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)); + 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, + 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, - &run_id, - &schema, - &props, - &mut owned_tmp_paths, - )?; - entry.insert(opened) + min_year: MIN_PARQUET_YEAR, + max_year: MAX_PARQUET_YEAR, + }); } - }; - yw.buf.push(row); - if yw.buf.len() == options.row_group_rows { - yw.flush_row_group(&mut scratch)?; + 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()); } } - 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) - })(); + // 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 synced_files = match write_result { - Ok(files) => files, - Err(err) => { - // Drop all open writers before unlinking temporary files owned by this run. - drop(writers); + 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), + }) + }); + (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); + } + } + } + } + if let Some(err) = first_err { cleanup_owned_files(&owned_tmp_paths); return Err(err); } + (synced, owned_tmp_paths) }; let mut stats = Bars1dWriteStats::default(); @@ -1262,6 +1496,7 @@ 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); @@ -1342,6 +1577,7 @@ mod tests { Bars1dWriteOptions { row_group_rows: 0, zstd_level: DEFAULT_ZSTD_LEVEL, + ..Bars1dWriteOptions::default() }, ) .unwrap_err(); @@ -1356,6 +1592,7 @@ mod tests { Bars1dWriteOptions { row_group_rows: 100, zstd_level: 99, + ..Bars1dWriteOptions::default() }, ) .unwrap_err(); @@ -1466,6 +1703,7 @@ 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 53c42789..84ad961d 100644 --- a/tools/curate-etl/src/parquet_bars_tests.rs +++ b/tools/curate-etl/src/parquet_bars_tests.rs @@ -1,5 +1,7 @@ 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; @@ -9,9 +11,10 @@ use super::tests::{ assert_no_transient_files, assert_row_bitwise_eq, make_row, read_parquet_rows, TempDirGuard, }; use super::{ - write_bars_1d_dataset, write_bars_1d_dataset_with_hooks, Bars1dParquetRow, Bars1dWriteOptions, - ParquetBarsError, MAX_PARQUET_YEAR, MIN_PARQUET_YEAR, + write_bars_1d_dataset, write_bars_1d_dataset_internal, 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] @@ -884,3 +887,406 @@ 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 b5abbb7a..84e6def3 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)] -mod tests { +pub(crate) mod tests { use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; use parquet::basic::ConvertedType; @@ -1306,7 +1306,7 @@ mod tests { } } - pub(super) fn read_parquet_rows(path: &Path) -> Vec { + pub(crate) 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 @@ mod tests { assert_eq!(actual.map(f64::to_bits), expected.map(f64::to_bits)); } - pub(super) fn assert_row_bitwise_eq( + pub(crate) fn assert_row_bitwise_eq( actual: &CorporateActionsParquetRow, expected: &CorporateActionsParquetRow, ) { @@ -1501,7 +1501,7 @@ mod tests { assert_eq!(actual.known_at_source, expected.known_at_source); } - pub(super) fn assert_no_transient_files(dir: &Path) { + pub(crate) fn assert_no_transient_files(dir: &Path) { if !dir.exists() { return; } diff --git a/tools/curate-etl/src/run_curate_adj.rs b/tools/curate-etl/src/run_curate_adj.rs new file mode 100644 index 00000000..7e0f5ef4 --- /dev/null +++ b/tools/curate-etl/src/run_curate_adj.rs @@ -0,0 +1,1151 @@ +//! 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 new file mode 100644 index 00000000..a448a673 --- /dev/null +++ b/tools/curate-etl/src/run_curate_adj_tests.rs @@ -0,0 +1,1044 @@ +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 new file mode 100644 index 00000000..00283b63 --- /dev/null +++ b/tools/curate-etl/src/run_curate_bars.rs @@ -0,0 +1,1395 @@ +//! 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, +} + +struct EodListingRange { + valid_from: i32, + valid_to: Option, + key: Arc, +} + +#[inline] +fn valid_to_sort_key(valid_to: Option) -> (u8, i32) { + match valid_to { + Some(to) => (0, to), + None => (1, i32::MAX), + } +} + +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)?; + + // Build interned `"eod"` key set and reverse `listing_id -> [eod source_id]` index once. + // When `--qm-prices` is provided, also build 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. + let mut eod_keys: HashSet> = HashSet::new(); + let mut eod_by_listing: HashMap>> = HashMap::new(); + let mut eod_ranges_by_listing: HashMap> = HashMap::new(); + let track_eod_ranges = qm_prices_path.is_some(); + 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)) + }); + } + + 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 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)` before fanning out to `"eod"` keys. + let (compacted_splits, splits_collision_collapsed) = + compact_mapped_qm_splits(qm_splits_path, mapped_splits)?; + split_rekey.splits_collision_collapsed = splits_collision_collapsed; + + 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, + } + })?; + + // 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_tests.rs b/tools/curate-etl/src/run_curate_bars_tests.rs new file mode 100644 index 00000000..7faf57f2 --- /dev/null +++ b/tools/curate-etl/src/run_curate_bars_tests.rs @@ -0,0 +1,1775 @@ +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 new file mode 100644 index 00000000..df9f8f05 --- /dev/null +++ b/tools/curate-etl/src/run_curate_corporate_actions.rs @@ -0,0 +1,923 @@ +//! 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 new file mode 100644 index 00000000..359c1023 --- /dev/null +++ b/tools/curate-etl/src/run_curate_corporate_actions_tests.rs @@ -0,0 +1,1558 @@ +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 new file mode 100644 index 00000000..0e069c07 --- /dev/null +++ b/tools/curate-etl/src/run_curate_events.rs @@ -0,0 +1,970 @@ +//! 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 new file mode 100644 index 00000000..3429d6bb --- /dev/null +++ b/tools/curate-etl/src/run_curate_events_tests.rs @@ -0,0 +1,773 @@ +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_fx.rs b/tools/curate-etl/src/run_curate_fx.rs new file mode 100644 index 00000000..f85b2712 --- /dev/null +++ b/tools/curate-etl/src/run_curate_fx.rs @@ -0,0 +1,708 @@ +//! 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_tests.rs b/tools/curate-etl/src/run_curate_fx_tests.rs new file mode 100644 index 00000000..319f0dd5 --- /dev/null +++ b/tools/curate-etl/src/run_curate_fx_tests.rs @@ -0,0 +1,986 @@ +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_shorts.rs b/tools/curate-etl/src/run_curate_shorts.rs new file mode 100644 index 00000000..b5726115 --- /dev/null +++ b/tools/curate-etl/src/run_curate_shorts.rs @@ -0,0 +1,589 @@ +//! 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 new file mode 100644 index 00000000..02b46574 --- /dev/null +++ b/tools/curate-etl/src/run_curate_shorts_tests.rs @@ -0,0 +1,395 @@ +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 new file mode 100644 index 00000000..b36af63e --- /dev/null +++ b/tools/curate-etl/src/run_mongo.rs @@ -0,0 +1,503 @@ +//! 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/tsv_fixture_tests.rs b/tools/curate-etl/src/tsv_fixture_tests.rs new file mode 100644 index 00000000..8512761d --- /dev/null +++ b/tools/curate-etl/src/tsv_fixture_tests.rs @@ -0,0 +1,359 @@ +//! 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/bson_qm_actions_contract.rs b/tools/curate-etl/tests/bson_qm_actions_contract.rs new file mode 100644 index 00000000..85c15861 --- /dev/null +++ b/tools/curate-etl/tests/bson_qm_actions_contract.rs @@ -0,0 +1,209 @@ +//! 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 new file mode 100644 index 00000000..b95b7152 --- /dev/null +++ b/tools/curate-etl/tests/bson_qm_actions_qa_contract.rs @@ -0,0 +1,526 @@ +//! 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 new file mode 100644 index 00000000..63532041 --- /dev/null +++ b/tools/curate-etl/tests/bson_stream_qa_contract.rs @@ -0,0 +1,273 @@ +//! 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 109e9e42..055232fc 100644 --- a/tools/curate-etl/tests/cli.rs +++ b/tools/curate-etl/tests/cli.rs @@ -1,6 +1,12 @@ //! 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")) @@ -24,6 +30,21 @@ 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-corporate-actions"), "{args:?}: {text}"); assert!(text.contains("bench-fx"), "{args:?}: {text}"); @@ -238,3 +259,1454 @@ 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=")); } + +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=")); +} diff --git a/tools/curate-etl/tests/curate_adj_qa_contract.rs b/tools/curate-etl/tests/curate_adj_qa_contract.rs new file mode 100644 index 00000000..de5164d4 --- /dev/null +++ b/tools/curate-etl/tests/curate_adj_qa_contract.rs @@ -0,0 +1,418 @@ +//! 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_shorts.rs b/tools/curate-etl/tests/curate_shorts.rs new file mode 100644 index 00000000..5b2eeca8 --- /dev/null +++ b/tools/curate-etl/tests/curate_shorts.rs @@ -0,0 +1,538 @@ +//! 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 new file mode 100644 index 00000000..cbf74348 --- /dev/null +++ b/tools/curate-etl/tests/fixtures/curate-inputs/delistings.tsv @@ -0,0 +1,3 @@ +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 new file mode 100644 index 00000000..b52375e1 --- /dev/null +++ b/tools/curate-etl/tests/fixtures/curate-inputs/listing_currencies.tsv @@ -0,0 +1,8 @@ +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 new file mode 100644 index 00000000..480fde57 --- /dev/null +++ b/tools/curate-etl/tests/fixtures/curate-inputs/provider_mapping.tsv @@ -0,0 +1,16 @@ +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/mongo_driver_cli_contract.rs b/tools/curate-etl/tests/mongo_driver_cli_contract.rs new file mode 100644 index 00000000..891c9bac --- /dev/null +++ b/tools/curate-etl/tests/mongo_driver_cli_contract.rs @@ -0,0 +1,407 @@ +//! 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 new file mode 100644 index 00000000..507a3271 --- /dev/null +++ b/tools/curate-etl/tests/mongo_stream_qa_contract.rs @@ -0,0 +1,322 @@ +//! 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/run_curate_adj_qa_contract.rs b/tools/curate-etl/tests/run_curate_adj_qa_contract.rs new file mode 100644 index 00000000..0a96ca02 --- /dev/null +++ b/tools/curate-etl/tests/run_curate_adj_qa_contract.rs @@ -0,0 +1,526 @@ +//! 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 new file mode 100644 index 00000000..a01708c8 --- /dev/null +++ b/tools/curate-etl/tests/run_curate_bars_merge_qa.rs @@ -0,0 +1,300 @@ +//! 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 new file mode 100644 index 00000000..1e146458 --- /dev/null +++ b/tools/curate-etl/tests/run_curate_bars_qa_contract.rs @@ -0,0 +1,957 @@ +//! 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 new file mode 100644 index 00000000..a0e37954 --- /dev/null +++ b/tools/curate-etl/tests/run_curate_bars_qm_qa_contract.rs @@ -0,0 +1,814 @@ +//! 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 new file mode 100644 index 00000000..7a0c1c2a --- /dev/null +++ b/tools/curate-etl/tests/run_curate_corporate_actions_qa_contract.rs @@ -0,0 +1,610 @@ +//! 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 new file mode 100644 index 00000000..a376eb0f --- /dev/null +++ b/tools/curate-etl/tests/run_curate_events_qa_contract.rs @@ -0,0 +1,666 @@ +//! 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 new file mode 100644 index 00000000..3ac417b8 --- /dev/null +++ b/tools/curate-etl/tests/run_curate_fx_qa_contract.rs @@ -0,0 +1,416 @@ +//! 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 new file mode 100644 index 00000000..987d30ba --- /dev/null +++ b/tools/curate-etl/tests/run_curate_shorts_qa_contract.rs @@ -0,0 +1,555 @@ +//! 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"); +}