T-97: M1.2o — tools/curate-etl: zero-copy raw BSON decoder for eodPrices documents → EodDailyBar (adds the bson crate only; no MongoDB connection) with fixture tests and local benchmark
This commit is contained in:
commit
e9fd202515
10 changed files with 2450 additions and 19 deletions
224
Cargo.lock
generated
224
Cargo.lock
generated
|
|
@ -10,9 +10,9 @@ checksum = "3019c0b8d883a8a17df3129e417ef463c087807d245e8881a31d583dee1c0519"
|
|||
dependencies = [
|
||||
"cfg-if",
|
||||
"const-random",
|
||||
"getrandom 0.3.4",
|
||||
"getrandom 0.4.3",
|
||||
"once_cell",
|
||||
"serde",
|
||||
"version_check",
|
||||
"zerocopy",
|
||||
]
|
||||
|
|
@ -73,12 +73,51 @@ version = "1.5.1"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
||||
|
||||
[[package]]
|
||||
name = "base64"
|
||||
version = "0.22.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||
|
||||
[[package]]
|
||||
name = "bitvec"
|
||||
version = "1.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ddcec3d12c579d40898fe0a9a358a803c23e9c52ca3c425707f81c9436211837"
|
||||
dependencies = [
|
||||
"funty",
|
||||
"radium",
|
||||
"tap",
|
||||
"wyz",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bson"
|
||||
version = "3.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b3f109694c4f45353972af96bf97d8a057f82e2d6e496457f4d135b9867a518c"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"base64",
|
||||
"bitvec",
|
||||
"getrandom 0.3.4",
|
||||
"hex",
|
||||
"indexmap",
|
||||
"js-sys",
|
||||
"rand 0.9.5",
|
||||
"serde_bytes",
|
||||
"simdutf8",
|
||||
"thiserror 2.0.21",
|
||||
"time",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bumpalo"
|
||||
version = "3.20.4"
|
||||
|
|
@ -239,6 +278,7 @@ dependencies = [
|
|||
name = "curate-etl"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bson",
|
||||
"parquet",
|
||||
]
|
||||
|
||||
|
|
@ -255,6 +295,12 @@ dependencies = [
|
|||
"parking_lot_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "deranged"
|
||||
version = "0.5.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e"
|
||||
|
||||
[[package]]
|
||||
name = "engine"
|
||||
version = "0.1.0"
|
||||
|
|
@ -272,19 +318,25 @@ dependencies = [
|
|||
"num-rational",
|
||||
"num-traits",
|
||||
"parking_lot",
|
||||
"rand",
|
||||
"rand 0.8.8",
|
||||
"rand_distr",
|
||||
"rust_decimal",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"statrs",
|
||||
"thiserror",
|
||||
"thiserror 1.0.69",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "equivalent"
|
||||
version = "1.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
|
||||
|
||||
[[package]]
|
||||
name = "errno"
|
||||
version = "0.3.15"
|
||||
|
|
@ -301,6 +353,12 @@ version = "0.1.15"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
|
||||
|
||||
[[package]]
|
||||
name = "funty"
|
||||
version = "2.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c"
|
||||
|
||||
[[package]]
|
||||
name = "futures-core"
|
||||
version = "0.3.34"
|
||||
|
|
@ -343,9 +401,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||
checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"js-sys",
|
||||
"libc",
|
||||
"r-efi 5.3.0",
|
||||
"wasip2",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
@ -385,6 +445,12 @@ version = "0.17.2"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc"
|
||||
|
||||
[[package]]
|
||||
name = "hex"
|
||||
version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
|
||||
|
||||
[[package]]
|
||||
name = "iana-time-zone"
|
||||
version = "0.1.65"
|
||||
|
|
@ -409,6 +475,16 @@ dependencies = [
|
|||
"cc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "indexmap"
|
||||
version = "2.14.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
|
||||
dependencies = [
|
||||
"equivalent",
|
||||
"hashbrown 0.17.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.19"
|
||||
|
|
@ -518,7 +594,7 @@ dependencies = [
|
|||
"num-complex",
|
||||
"num-rational",
|
||||
"num-traits",
|
||||
"rand",
|
||||
"rand 0.8.8",
|
||||
"rand_distr",
|
||||
"simba 0.6.0",
|
||||
"typenum",
|
||||
|
|
@ -661,6 +737,12 @@ dependencies = [
|
|||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-conv"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
|
||||
|
||||
[[package]]
|
||||
name = "num-integer"
|
||||
version = "0.1.47"
|
||||
|
|
@ -757,6 +839,12 @@ version = "0.3.34"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
|
||||
|
||||
[[package]]
|
||||
name = "powerfmt"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958"
|
||||
|
||||
[[package]]
|
||||
name = "ppv-lite86"
|
||||
version = "0.2.21"
|
||||
|
|
@ -796,6 +884,12 @@ version = "6.0.0"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
|
||||
|
||||
[[package]]
|
||||
name = "radium"
|
||||
version = "0.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09"
|
||||
|
||||
[[package]]
|
||||
name = "rand"
|
||||
version = "0.8.8"
|
||||
|
|
@ -803,8 +897,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||
checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"rand_chacha",
|
||||
"rand_core",
|
||||
"rand_chacha 0.3.1",
|
||||
"rand_core 0.6.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"
|
||||
dependencies = [
|
||||
"rand_chacha 0.9.0",
|
||||
"rand_core 0.9.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
@ -814,7 +918,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
|
||||
dependencies = [
|
||||
"ppv-lite86",
|
||||
"rand_core",
|
||||
"rand_core 0.6.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_chacha"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
|
||||
dependencies = [
|
||||
"ppv-lite86",
|
||||
"rand_core 0.9.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
@ -826,6 +940,15 @@ dependencies = [
|
|||
"getrandom 0.2.17",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_core"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
|
||||
dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_distr"
|
||||
version = "0.4.3"
|
||||
|
|
@ -833,7 +956,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||
checksum = "32cb0b9bc82b0a0876c2dd994a7e7a2683d3e7390ca40e6886785ef0c7e3ee31"
|
||||
dependencies = [
|
||||
"num-traits",
|
||||
"rand",
|
||||
"rand 0.8.8",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
@ -933,6 +1056,16 @@ dependencies = [
|
|||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_bytes"
|
||||
version = "0.11.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_core"
|
||||
version = "1.0.229"
|
||||
|
|
@ -1017,6 +1150,12 @@ dependencies = [
|
|||
"wide",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "simdutf8"
|
||||
version = "0.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"
|
||||
|
||||
[[package]]
|
||||
name = "slab"
|
||||
version = "0.4.12"
|
||||
|
|
@ -1049,7 +1188,7 @@ dependencies = [
|
|||
"lazy_static",
|
||||
"nalgebra 0.29.0",
|
||||
"num-traits",
|
||||
"rand",
|
||||
"rand 0.8.8",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
@ -1085,13 +1224,28 @@ dependencies = [
|
|||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tap"
|
||||
version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369"
|
||||
|
||||
[[package]]
|
||||
name = "thiserror"
|
||||
version = "1.0.69"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"
|
||||
dependencies = [
|
||||
"thiserror-impl",
|
||||
"thiserror-impl 1.0.69",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror"
|
||||
version = "2.0.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
|
||||
dependencies = [
|
||||
"thiserror-impl 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
@ -1105,6 +1259,17 @@ dependencies = [
|
|||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror-impl"
|
||||
version = "2.0.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thread_local"
|
||||
version = "1.1.10"
|
||||
|
|
@ -1114,6 +1279,36 @@ dependencies = [
|
|||
"cfg-if",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "time"
|
||||
version = "0.3.55"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134"
|
||||
dependencies = [
|
||||
"deranged",
|
||||
"num-conv",
|
||||
"powerfmt",
|
||||
"serde_core",
|
||||
"time-core",
|
||||
"time-macros",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "time-core"
|
||||
version = "0.1.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"
|
||||
|
||||
[[package]]
|
||||
name = "time-macros"
|
||||
version = "0.2.32"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85"
|
||||
dependencies = [
|
||||
"num-conv",
|
||||
"time-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tiny-keccak"
|
||||
version = "2.0.2"
|
||||
|
|
@ -1399,6 +1594,15 @@ version = "0.57.1"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
|
||||
|
||||
[[package]]
|
||||
name = "wyz"
|
||||
version = "0.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed"
|
||||
dependencies = [
|
||||
"tap",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy"
|
||||
version = "0.8.66"
|
||||
|
|
|
|||
|
|
@ -6,5 +6,6 @@ authors.workspace = true
|
|||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
bson = { version = "=3.1.0", default-features = false, features = ["compat-3-0-0"] }
|
||||
parquet = { version = "=60.2.0", default-features = false, features = ["zstd"] }
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# `curate-etl`
|
||||
|
||||
Dedicated Rust crate (single direct dependency: `parquet` with `default-features = false, features = ["zstd"]`) for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, the `M1.2c` pure `corporate_actions` event-log builder, the `M1.2d` pure `bars_1d` daily bar builder + `qmPrices.sharevolume` cross-check, the `M1.2e` pure `fx_1d` USD/CAD builder + carry-forward lookup, the `M1.2f` pure `shorts` (`ceoShorts`) point-in-time builder + Canadian TSX business-day / `America/Toronto` DST calendar, the `M1.2g` pure `events` (`qmFilings` + `qmEarnings`) point-in-time builder, the `M1.2h` pure in-RAM `provider_mapping` `(source, source_id, bar_date) -> listing_id` lookup table, 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`, and the `M1.2n` streaming Zstd Parquet writer for `corporate_actions`.
|
||||
Dedicated Rust crate (two exact-pinned direct dependencies: `bson` `=3.1.0` with `default-features = false, features = ["compat-3-0-0"]` and `parquet` `=60.2.0` with `default-features = false, features = ["zstd"]`) for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, the `M1.2c` pure `corporate_actions` event-log builder, the `M1.2d` pure `bars_1d` daily bar builder + `qmPrices.sharevolume` cross-check, the `M1.2e` pure `fx_1d` USD/CAD builder + carry-forward lookup, the `M1.2f` pure `shorts` (`ceoShorts`) point-in-time builder + Canadian TSX business-day / `America/Toronto` DST calendar, the `M1.2g` pure `events` (`qmFilings` + `qmEarnings`) point-in-time builder, the `M1.2h` pure in-RAM `provider_mapping` `(source, source_id, bar_date) -> listing_id` lookup table, the `M1.2i` streaming Zstd Parquet writer for `bars_1d`, the `M1.2j` streaming Zstd Parquet writer for `shorts`, the `M1.2k` streaming Zstd Parquet writer for `events`, the `M1.2l` streaming Zstd Parquet writer for `fx_1d`, the `M1.2m` streaming Zstd Parquet writer for `adj_factors`, the `M1.2n` streaming Zstd Parquet writer for `corporate_actions`, and the `M1.2o` zero-copy raw BSON decoder for `eodPrices`.
|
||||
|
||||
## Scope & Sign Conventions
|
||||
|
||||
|
|
@ -433,6 +433,28 @@ Rules:
|
|||
- Output: `files=1`, `row_groups=1`, `bytes=4041339`, `read_back_rows=1000000`
|
||||
- Perf: `elapsed=153.96 ms`, `throughput=6495345 rows/s`, `write=25.03 MB/s`, `size=4.04 bytes/row`, `compression=17.82x`
|
||||
|
||||
## `eodPrices` Raw BSON Decoder (`M1.2o`)
|
||||
|
||||
`decode_eod_price_doc`, `decode_eod_price_bytes`, `iter_raw_bson_docs`, and `decode_eod_price_buffer` (`src/bson_eod_prices.rs`) decode raw MongoDB `eodPrices` BSON documents in a single forward pass over `RawDocument::iter_elements()` without allocating a `String` or `bson::Document` per row.
|
||||
|
||||
1. **Pinned dependency & driver compatibility:**
|
||||
- Adds `bson = { version = "=3.1.0", default-features = false, features = ["compat-3-0-0"] }` (MSRV `1.81+`, tested against workspace `rustc 1.88.0`, no `serde` derive).
|
||||
- Paired with the official `mongodb` `3.x` Rust driver using `features = ["bson-3"]` so the upcoming MongoDB cursor task reuses the same `bson` 3.x crate without pulling in a duplicate `bson` major version.
|
||||
2. **Empirical field contract & cited sources:**
|
||||
- Grounded in `apps/stock/data-ingestion/src/handlers/eod/shared/price-storage.ts:4-56`, `apps/stock/data-ingestion/src/handlers/eod/actions/prices.ts:105-157`, `apps/stock/data-pipeline/src/normalization/bar-spans.ts:12-18`, and `design/DATA-CONTRACTS.md` §1 (line 13).
|
||||
- `eodSearchCode`: BSON UTF-8 `String` (borrowed verbatim as `&str`; empty or whitespace-only is rejected).
|
||||
- `date`: strict 10-byte ASCII `YYYY-MM-DD` BSON `String` (validated via `split::ymd_to_epoch_days`) or BSON `DateTime` (converted to UTC epoch days via `timestamp_millis().div_euclid(86_400_000)` with `i32` bounds check so pre-1970 timestamps map accurately).
|
||||
- `open`, `high`, `low`, `close`, `volume`: every BSON numeric representation MongoDB can store for a JS number (`Double`, `Int32`, `Int64`); must be finite and `>= 0.0` (`-0.0` normalized to `+0.0`). Per `design/DATA-CONTRACTS.md` §1, OHLC is raw and `volume` is retroactively split-adjusted, mapping directly to `EodDailyBar::adj_volume`.
|
||||
- Unknown extra fields (`_id`, `symbol`, `exchange`, `providerExchange`, `source`, `adjustedClose`, `adjusted_close`, `created_at`, `updated_at`, nested objects/arrays, etc.) are skipped without decoding their values.
|
||||
3. **Zero-allocation key mapping:**
|
||||
- Decodes into borrowed `RawEodDailyBar<'a>` and converts to `EodDailyBar<K>` via `into_eod_daily_bar(|code, date| ...)` or `try_into_eod_daily_bar(|code, date| mapping.resolve("eod", code, date))`, avoiding per-row `String` allocations across 846M documents.
|
||||
4. **Typed errors & stream skip/accounting policy:**
|
||||
- Never panics on untrusted input. `BsonEodPriceError` names the offending field on every field-level error: `MissingField`, `EmptyField`, `WrongType`, `MalformedDate`, `InvalidNumber`, `TruncatedDocument`, `CorruptDocumentLength`, and `CorruptBson`.
|
||||
- `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`).
|
||||
|
||||
## Local Benchmarks
|
||||
|
||||
### `bench-split`
|
||||
|
|
@ -631,9 +653,25 @@ Command (`2026-11-28`): `cargo run --release -p curate-etl --offline -- bench-pa
|
|||
- Output: `files=1`, `row_groups=1`, `bytes=4041339`, `read_back_rows=1000000`
|
||||
- Perf: `elapsed=153.96 ms`, `throughput=6495345 rows/s`, `write=25.03 MB/s`, `size=4.04 bytes/row`, `compression=17.82x`
|
||||
|
||||
### `bench-bson-eod-prices`
|
||||
|
||||
Fixed-seed (`std`-only SplitMix64) zero-copy raw BSON decode benchmark over `1,000,000` realistic synthetic `eodPrices` documents (including `_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) pre-encoded into one contiguous length-prefixed buffer up front, timing decode-only via `decode_eod_price_buffer`:
|
||||
|
||||
```bash
|
||||
cargo run --release -p curate-etl --offline -- bench-bson-eod-prices [rows]
|
||||
```
|
||||
|
||||
Command (`2026-11-28`, two back-to-back runs with identical checksum `0x05af9d2746d1b5e3`): `cargo run --release -p curate-etl --offline -- bench-bson-eod-prices`
|
||||
|
||||
- Input: `rows=1000000`, `bytes=285639152` (~272.4 MiB, ~285.6 bytes/doc)
|
||||
- Decode: `decoded=995008`, `rejected=4992` (`missing=1985`, `empty=0`, `wrong_type=986`, `malformed_date=1027`, `invalid_number=994`, `corrupt=0`)
|
||||
- Run 1: `elapsed=221.82 ms`, `throughput=4508210 rows/s`, `scan=1228.07 MB/s`, `latency=221.82 ns/row`, `checksum=0x05af9d2746d1b5e3`
|
||||
- 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`).
|
||||
|
||||
## Deferred Follow-Ups (`M1.3+` / `M2`)
|
||||
|
||||
This crate currently depends only on `parquet` (Zstd-only, no Arrow/async) so all tests and benchmarks run strictly offline once the Cargo cache is populated. Follow-up tasks will add:
|
||||
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:
|
||||
|
||||
- `bars_1d` and `fx_1d` schema metadata columns (`ts`, `known_at`, `currency`, `source`, `vwap`) requiring exchange session/timezone and listing metadata
|
||||
- `CADUSD.FOREX` inversion, `fx_1m` intraday FX, and wiring `fx_1d` into `src/adj.rs` cross-currency dividends
|
||||
|
|
|
|||
|
|
@ -8,11 +8,15 @@ use std::path::{Path, PathBuf};
|
|||
use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering};
|
||||
use std::time::Instant;
|
||||
|
||||
use bson::oid::ObjectId;
|
||||
use bson::raw::{cstr, RawDocumentBuf};
|
||||
use bson::DateTime;
|
||||
use parquet::errors::ParquetError;
|
||||
use parquet::file::reader::{FileReader, SerializedFileReader};
|
||||
|
||||
use crate::adj::{build_adj_factors, AdjBuildStats, AdjError, DividendEvent};
|
||||
use crate::bars::{build_bars_1d, Bars1dStats, BarsError, EodDailyBar, QmRawVolume};
|
||||
use crate::bson_eod_prices::{decode_eod_price_buffer, BsonEodDecodeStats};
|
||||
use crate::corporate_actions::{
|
||||
build_corporate_actions, CorporateActionError, CorporateActionKind, CorporateActionsStats,
|
||||
DelistingOutcomeEvent, DividendActionEvent, KnownAtSource, SplitActionEvent,
|
||||
|
|
@ -74,6 +78,7 @@ pub const DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS: usize = 1_000_000;
|
|||
/// + `cash_amount` (8) + `currency` (3) + `successor_listing_id` (4) + `terminal_return` (8)
|
||||
/// + `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 BENCH_KEY_COUNT: usize = 20_000;
|
||||
pub const BENCH_EVENT_COUNT: usize = 19_000;
|
||||
pub const PROVIDER_MAPPING_BENCH_KEY_COUNT: usize = 60_000;
|
||||
|
|
@ -98,6 +103,7 @@ const PARQUET_SHORTS_BENCH_SEED: u64 = 0x570C_4B07_9A49_5404;
|
|||
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 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];
|
||||
|
||||
|
|
@ -3589,6 +3595,196 @@ pub fn run_parquet_corporate_actions_benchmark(
|
|||
Ok(report)
|
||||
}
|
||||
|
||||
/// Summary metrics produced by [`run_bson_eod_prices_benchmark`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct BsonEodPricesBenchReport {
|
||||
pub rows: usize,
|
||||
pub bytes: usize,
|
||||
pub elapsed_ms: f64,
|
||||
pub rows_per_sec: f64,
|
||||
pub mb_per_sec: f64,
|
||||
pub ns_per_row: f64,
|
||||
pub checksum: u64,
|
||||
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<u8>` buffer up front, then times decode-only via [`decode_eod_price_buffer`].
|
||||
pub fn run_bson_eod_prices_benchmark(rows: usize) -> BsonEodPricesBenchReport {
|
||||
if rows == 0 {
|
||||
return BsonEodPricesBenchReport {
|
||||
rows: 0,
|
||||
bytes: 0,
|
||||
elapsed_ms: 0.0,
|
||||
rows_per_sec: 0.0,
|
||||
mb_per_sec: 0.0,
|
||||
ns_per_row: 0.0,
|
||||
checksum: 0,
|
||||
stats: BsonEodDecodeStats::default(),
|
||||
};
|
||||
}
|
||||
|
||||
const SYMBOL_POOL: usize = 2_000;
|
||||
const EXCHANGES: [&str; 4] = ["NASDAQ", "NYSE", "TSX", "TSXV"];
|
||||
const PROVIDER_EXCHANGES: [&str; 4] = ["US", "US", "TO", "V"];
|
||||
const MILLIS_PER_DAY: i64 = 86_400_000;
|
||||
|
||||
let min_date = ymd_to_epoch_days(2010, 1, 4).unwrap_or(14_613);
|
||||
let max_date = ymd_to_epoch_days(2025, 12, 31).unwrap_or(20_453);
|
||||
let mut date_days: Vec<i32> = Vec::with_capacity(4_200);
|
||||
let mut date_strings: Vec<String> = Vec::with_capacity(4_200);
|
||||
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!("SYM{i:04}");
|
||||
let prov = PROVIDER_EXCHANGES[ex_idx];
|
||||
let code = format!("{sym}.{prov}");
|
||||
(sym, code, EXCHANGES[ex_idx], prov)
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut rng = SplitMix64::new(BSON_EOD_PRICES_BENCH_SEED);
|
||||
// ~240 bytes per realistic eodPrices document with extra metadata fields.
|
||||
let mut buffer: Vec<u8> = Vec::with_capacity(rows.saturating_mul(256));
|
||||
|
||||
for i in 0..rows {
|
||||
let sym_idx = (rng.next_u64() as usize) % symbols.len();
|
||||
let (ref symbol, ref code, exchange, provider_exchange) = 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 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;
|
||||
|
||||
let mut oid_bytes = [0u8; 12];
|
||||
let seq = (i as u64).to_be_bytes();
|
||||
oid_bytes[4..12].copy_from_slice(&seq);
|
||||
|
||||
let created_ms = i64::from(epoch_day) * MILLIS_PER_DAY + 79_200_000;
|
||||
let updated_ms = created_ms + 60_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!("providerExchange"), provider_exchange);
|
||||
doc.append(cstr!("source"), "eod");
|
||||
|
||||
// Inject ~0.5% deterministic rejected rows across 4 distinct error categories.
|
||||
let bad_roll = rng.next_u64() % 1_000;
|
||||
doc.append(cstr!("eodSearchCode"), code.as_str());
|
||||
if bad_roll == 0 {
|
||||
// Malformed date string.
|
||||
doc.append(cstr!("date"), "2023-02-29");
|
||||
} else if rng.next_u64() % 20 == 0 {
|
||||
// ~5% BSON DateTime dates.
|
||||
doc.append(
|
||||
cstr!("date"),
|
||||
DateTime::from_millis(i64::from(epoch_day) * MILLIS_PER_DAY),
|
||||
);
|
||||
} else {
|
||||
doc.append(cstr!("date"), date_str.as_str());
|
||||
}
|
||||
|
||||
if bad_roll == 1 {
|
||||
// Wrong BSON type on open.
|
||||
doc.append(cstr!("open"), "bad");
|
||||
} else if i % 10 == 0 {
|
||||
doc.append(cstr!("open"), (base_cents / 100) as i32);
|
||||
} else {
|
||||
doc.append(cstr!("open"), open);
|
||||
}
|
||||
|
||||
if bad_roll == 2 {
|
||||
// Negative price on high.
|
||||
doc.append(cstr!("high"), -1.0_f64);
|
||||
} else {
|
||||
doc.append(cstr!("high"), high);
|
||||
}
|
||||
|
||||
doc.append(cstr!("low"), low);
|
||||
doc.append(cstr!("close"), close);
|
||||
doc.append(cstr!("adjustedClose"), close * 0.95);
|
||||
|
||||
if bad_roll != 3 && bad_roll != 4 {
|
||||
match i % 3 {
|
||||
0 => doc.append(cstr!("volume"), volume_i64),
|
||||
1 => doc.append(cstr!("volume"), (volume_i64 as i32).abs()),
|
||||
_ => doc.append(cstr!("volume"), volume_i64 as f64),
|
||||
}
|
||||
}
|
||||
// When bad_roll is 3 or 4, omit `volume` to exercise MissingField.
|
||||
|
||||
doc.append(cstr!("created_at"), DateTime::from_millis(created_ms));
|
||||
doc.append(cstr!("updated_at"), DateTime::from_millis(updated_ms));
|
||||
|
||||
buffer.extend_from_slice(doc.as_bytes());
|
||||
}
|
||||
|
||||
let bytes = buffer.len();
|
||||
let mut hash = 0u64;
|
||||
let mut err_hash = 0u64;
|
||||
|
||||
let start = Instant::now();
|
||||
let stats = decode_eod_price_buffer(
|
||||
&buffer,
|
||||
|bar| {
|
||||
hash = mix_bytes(hash, bar.eod_search_code.as_bytes());
|
||||
hash = mix_u64(hash, bar.session_date as u64);
|
||||
hash = mix_u64(hash, bar.open.to_bits());
|
||||
hash = mix_u64(hash, bar.high.to_bits());
|
||||
hash = mix_u64(hash, bar.low.to_bits());
|
||||
hash = mix_u64(hash, bar.close.to_bits());
|
||||
hash = mix_u64(hash, bar.adj_volume.to_bits());
|
||||
},
|
||||
|offset, _err| {
|
||||
err_hash = mix_u64(err_hash, offset as u64 ^ 0xDEAD_BEEF_CAFE_BABEu64);
|
||||
},
|
||||
);
|
||||
let elapsed_secs = start.elapsed().as_secs_f64();
|
||||
let elapsed_ms = elapsed_secs * 1_000.0;
|
||||
let (rows_per_sec, ns_per_row) = compute_rates(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);
|
||||
|
||||
BsonEodPricesBenchReport {
|
||||
rows,
|
||||
bytes,
|
||||
elapsed_ms,
|
||||
rows_per_sec,
|
||||
mb_per_sec,
|
||||
ns_per_row,
|
||||
checksum,
|
||||
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;
|
||||
|
|
@ -5456,6 +5652,38 @@ mod tests {
|
|||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bson_eod_prices_benchmark_small_run_is_deterministic() {
|
||||
let a = run_bson_eod_prices_benchmark(20_000);
|
||||
let b = run_bson_eod_prices_benchmark(20_000);
|
||||
|
||||
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!(a.stats.decoded > 19_000);
|
||||
assert!(a.stats.rejected_total() > 0);
|
||||
assert!(a.rows_per_sec.is_finite() && a.rows_per_sec >= 0.0);
|
||||
assert!(a.mb_per_sec.is_finite() && a.mb_per_sec >= 0.0);
|
||||
assert!(a.ns_per_row.is_finite() && a.ns_per_row >= 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bson_eod_prices_benchmark_zero_rows_handles_cleanly() {
|
||||
let report = run_bson_eod_prices_benchmark(0);
|
||||
assert_eq!(report.rows, 0);
|
||||
assert_eq!(report.bytes, 0);
|
||||
assert_eq!(report.elapsed_ms, 0.0);
|
||||
assert_eq!(report.rows_per_sec, 0.0);
|
||||
assert_eq!(report.mb_per_sec, 0.0);
|
||||
assert_eq!(report.ns_per_row, 0.0);
|
||||
assert_eq!(report.checksum, 0);
|
||||
assert_eq!(report.stats, BsonEodDecodeStats::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();
|
||||
|
|
|
|||
633
tools/curate-etl/src/bson_eod_prices.rs
Normal file
633
tools/curate-etl/src/bson_eod_prices.rs
Normal file
|
|
@ -0,0 +1,633 @@
|
|||
//! Zero-copy raw BSON decoder for MongoDB `eodPrices` documents (`M1.2o`).
|
||||
//!
|
||||
//! Decodes `&bson::RawDocument` slices in a single forward pass over `iter_elements()` into
|
||||
//! borrowed [`RawEodDailyBar`] views without allocating a `String` or `bson::Document` per row.
|
||||
//! Callers convert borrowed views into [`crate::bars::EodDailyBar<K>`] via a caller-supplied key
|
||||
//! mapper (for example [`crate::provider_mapping::ProviderMappingTable::resolve`] or an interned
|
||||
//! integer symbol ID), keeping the 846M-document path free of per-row `String` allocations.
|
||||
//!
|
||||
//! # Empirical Field Contract
|
||||
//!
|
||||
//! Field names and semantics are grounded in the repository's ingestion writer, pipeline reader,
|
||||
//! and empirical data contract:
|
||||
//! - `apps/stock/data-ingestion/src/handlers/eod/shared/price-storage.ts:4-56` (`persistEodPrices`
|
||||
//! writes `eodSearchCode`, `date`, `open`, `high`, `low`, `close`, `volume`, plus metadata fields
|
||||
//! `symbol`, `exchange`, `providerExchange`, `source`, and optional `adjustedClose`)
|
||||
//! - `apps/stock/data-ingestion/src/handlers/eod/actions/prices.ts:105-157` (calls
|
||||
//! `persistEodPrices` with `{ symbol, exchange, eodSearchCode }` and EODHD JSON OHLCV records)
|
||||
//! - `apps/stock/data-pipeline/src/normalization/bar-spans.ts:12-18` (`eodPrices` keyed by
|
||||
//! `eodSearchCode` and `date`)
|
||||
//! - `design/DATA-CONTRACTS.md` §1 (line 13): `eodPrices` (~845.7M docs) stores **raw**
|
||||
//! `open`/`high`/`low`/`close`, while `volume` is **retroactively split-adjusted** and therefore
|
||||
//! maps directly to [`EodDailyBar::adj_volume`].
|
||||
//!
|
||||
//! Accepted BSON field representations:
|
||||
//! - `eodSearchCode`: BSON UTF-8 `String` (stored 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).
|
||||
//! - `open`, `high`, `low`, `close`, `volume`: BSON `Double`, `Int32`, or `Int64` (every numeric
|
||||
//! representation MongoDB can store for a JS number); must be finite and `>= 0.0` (`-0.0` is
|
||||
//! normalized to `+0.0`).
|
||||
//! - Unknown extra fields (`_id`, `symbol`, `exchange`, `providerExchange`, `source`,
|
||||
//! `adjustedClose`, `adjusted_close`, `created_at`, `updated_at`, nested objects/arrays, etc.)
|
||||
//! are skipped without decoding their values.
|
||||
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
|
||||
use bson::raw::{cstr, RawBsonRef, RawDocument, RawElement};
|
||||
use bson::spec::ElementType;
|
||||
|
||||
use crate::bars::EodDailyBar;
|
||||
use crate::split::ymd_to_epoch_days;
|
||||
|
||||
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.
|
||||
///
|
||||
/// Borrows `eod_search_code` directly from the underlying `&RawDocument` byte slice.
|
||||
/// Per `design/DATA-CONTRACTS.md` §1, `open`/`high`/`low`/`close` are raw and `adj_volume` holds
|
||||
/// the retroactively split-adjusted `eodPrices.volume`.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct RawEodDailyBar<'a> {
|
||||
pub eod_search_code: &'a str,
|
||||
/// Session date as days since `1970-01-01` (UTC Gregorian).
|
||||
pub session_date: i32,
|
||||
pub open: f64,
|
||||
pub high: f64,
|
||||
pub low: f64,
|
||||
pub close: f64,
|
||||
/// Retroactively split-adjusted `eodPrices.volume`.
|
||||
pub adj_volume: f64,
|
||||
}
|
||||
|
||||
impl<'a> RawEodDailyBar<'a> {
|
||||
/// Converts this borrowed view into an [`EodDailyBar<K>`] using a caller-supplied key mapper.
|
||||
///
|
||||
/// `map_key` receives `(eod_search_code, session_date)` so callers can resolve an integer
|
||||
/// `listing_id` or interned key without allocating a per-row `String`.
|
||||
#[inline]
|
||||
pub fn into_eod_daily_bar<K, F>(self, map_key: F) -> EodDailyBar<K>
|
||||
where
|
||||
F: FnOnce(&'a str, i32) -> K,
|
||||
{
|
||||
EodDailyBar {
|
||||
key: map_key(self.eod_search_code, self.session_date),
|
||||
session_date: self.session_date,
|
||||
open: self.open,
|
||||
high: self.high,
|
||||
low: self.low,
|
||||
close: self.close,
|
||||
adj_volume: self.adj_volume,
|
||||
}
|
||||
}
|
||||
|
||||
/// Fallible conversion into [`EodDailyBar<K>`] using a caller-supplied key resolver
|
||||
/// (for example `|code, date| mapping.resolve("eod", code, date)`).
|
||||
#[inline]
|
||||
pub fn try_into_eod_daily_bar<K, F>(self, map_key: F) -> Option<EodDailyBar<K>>
|
||||
where
|
||||
F: FnOnce(&'a str, i32) -> Option<K>,
|
||||
{
|
||||
let key = map_key(self.eod_search_code, self.session_date)?;
|
||||
Some(EodDailyBar {
|
||||
key,
|
||||
session_date: self.session_date,
|
||||
open: self.open,
|
||||
high: self.high,
|
||||
low: self.low,
|
||||
close: self.close,
|
||||
adj_volume: self.adj_volume,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Typed errors returned while decoding raw `eodPrices` 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 BsonEodPriceError {
|
||||
/// 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 date or BSON `DateTime`
|
||||
/// overflowed `i32` epoch days.
|
||||
MalformedDate { field: &'static str },
|
||||
/// A numeric OHLC or `volume` field was non-finite (`NaN`, `±inf`) or `< 0.0`.
|
||||
InvalidNumber { field: &'static str, value: f64 },
|
||||
/// Buffer ended before a complete 4-byte length prefix or declared document body.
|
||||
TruncatedDocument {
|
||||
offset: usize,
|
||||
remaining: usize,
|
||||
declared_len: Option<i32>,
|
||||
},
|
||||
/// 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 BsonEodPriceError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::MissingField { field } => {
|
||||
write!(f, "eodPrices BSON missing required field '{field}'")
|
||||
}
|
||||
Self::EmptyField { field } => {
|
||||
write!(f, "eodPrices BSON field '{field}' must not be empty or blank")
|
||||
}
|
||||
Self::WrongType { field, actual } => {
|
||||
write!(
|
||||
f,
|
||||
"eodPrices BSON field '{field}' has unexpected BSON type {actual:?}"
|
||||
)
|
||||
}
|
||||
Self::MalformedDate { field } => {
|
||||
write!(
|
||||
f,
|
||||
"eodPrices BSON field '{field}' is not a valid YYYY-MM-DD date or in-range DateTime"
|
||||
)
|
||||
}
|
||||
Self::InvalidNumber { field, value } => {
|
||||
write!(
|
||||
f,
|
||||
"eodPrices BSON field '{field}' has invalid numeric value {value}: must be finite and >= 0"
|
||||
)
|
||||
}
|
||||
Self::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len,
|
||||
} => match declared_len {
|
||||
Some(len) => write!(
|
||||
f,
|
||||
"truncated BSON document at byte offset {offset}: declared length {len} exceeds remaining {remaining} bytes"
|
||||
),
|
||||
None => write!(
|
||||
f,
|
||||
"truncated BSON document header at byte offset {offset}: only {remaining} bytes remaining"
|
||||
),
|
||||
},
|
||||
Self::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
} => write!(
|
||||
f,
|
||||
"corrupt BSON document length {declared_len} at byte offset {offset}"
|
||||
),
|
||||
Self::CorruptBson { offset, detail } => {
|
||||
write!(f, "corrupt BSON bytes at byte offset {offset}: {detail}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for BsonEodPriceError {}
|
||||
|
||||
/// Per-batch decode and rejection accounting for [`decode_eod_price_buffer`].
|
||||
///
|
||||
/// Conservation invariant: `decoded + rejected_total() == docs_in`.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct BsonEodDecodeStats {
|
||||
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_invalid_number: usize,
|
||||
pub rejected_corrupt_document: usize,
|
||||
}
|
||||
|
||||
impl BsonEodDecodeStats {
|
||||
/// 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: &BsonEodPriceError) {
|
||||
match err {
|
||||
BsonEodPriceError::MissingField { .. } => self.rejected_missing_field += 1,
|
||||
BsonEodPriceError::EmptyField { .. } => self.rejected_empty_field += 1,
|
||||
BsonEodPriceError::WrongType { .. } => self.rejected_wrong_type += 1,
|
||||
BsonEodPriceError::MalformedDate { .. } => self.rejected_malformed_date += 1,
|
||||
BsonEodPriceError::InvalidNumber { .. } => self.rejected_invalid_number += 1,
|
||||
BsonEodPriceError::TruncatedDocument { .. }
|
||||
| BsonEodPriceError::CorruptDocumentLength { .. }
|
||||
| BsonEodPriceError::CorruptBson { .. } => self.rejected_corrupt_document += 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn parse_ascii_digits_u32(bytes: &[u8]) -> Option<u32> {
|
||||
let mut acc: u32 = 0;
|
||||
for &b in bytes {
|
||||
if !b.is_ascii_digit() {
|
||||
return None;
|
||||
}
|
||||
acc = acc * 10 + u32::from(b - b'0');
|
||||
}
|
||||
Some(acc)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn parse_ymd_strict(s: &str) -> Result<i32, BsonEodPriceError> {
|
||||
let bytes = s.as_bytes();
|
||||
if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' {
|
||||
return Err(BsonEodPriceError::MalformedDate { field: "date" });
|
||||
}
|
||||
let Some(year_u32) = parse_ascii_digits_u32(&bytes[0..4]) else {
|
||||
return Err(BsonEodPriceError::MalformedDate { field: "date" });
|
||||
};
|
||||
let Some(month) = parse_ascii_digits_u32(&bytes[5..7]) else {
|
||||
return Err(BsonEodPriceError::MalformedDate { field: "date" });
|
||||
};
|
||||
let Some(day) = parse_ascii_digits_u32(&bytes[8..10]) else {
|
||||
return Err(BsonEodPriceError::MalformedDate { field: "date" });
|
||||
};
|
||||
ymd_to_epoch_days(year_u32 as i32, month, day)
|
||||
.map_err(|_| BsonEodPriceError::MalformedDate { field: "date" })
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_element_value<'a>(
|
||||
field: &'static str,
|
||||
elem: RawElement<'a>,
|
||||
offset: usize,
|
||||
) -> Result<RawBsonRef<'a>, BsonEodPriceError> {
|
||||
elem.value().map_err(|err| BsonEodPriceError::CorruptBson {
|
||||
offset,
|
||||
detail: format!("field '{field}': {err}"),
|
||||
})
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_non_negative_number(
|
||||
field: &'static str,
|
||||
val: RawBsonRef<'_>,
|
||||
) -> Result<f64, BsonEodPriceError> {
|
||||
match val {
|
||||
RawBsonRef::Double(v) => {
|
||||
if !v.is_finite() || v < 0.0 {
|
||||
return Err(BsonEodPriceError::InvalidNumber { field, value: v });
|
||||
}
|
||||
if v == 0.0 {
|
||||
Ok(0.0)
|
||||
} else {
|
||||
Ok(v)
|
||||
}
|
||||
}
|
||||
RawBsonRef::Int32(v) => {
|
||||
if v < 0 {
|
||||
return Err(BsonEodPriceError::InvalidNumber {
|
||||
field,
|
||||
value: f64::from(v),
|
||||
});
|
||||
}
|
||||
Ok(f64::from(v))
|
||||
}
|
||||
RawBsonRef::Int64(v) => {
|
||||
if v < 0 {
|
||||
return Err(BsonEodPriceError::InvalidNumber {
|
||||
field,
|
||||
value: v as f64,
|
||||
});
|
||||
}
|
||||
Ok(v as f64)
|
||||
}
|
||||
other => Err(BsonEodPriceError::WrongType {
|
||||
field,
|
||||
actual: other.element_type(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_eod_price_doc_at<'a>(
|
||||
doc: &'a RawDocument,
|
||||
offset: usize,
|
||||
) -> Result<RawEodDailyBar<'a>, BsonEodPriceError> {
|
||||
let mut eod_search_code: Option<&'a str> = None;
|
||||
let mut session_date: Option<i32> = None;
|
||||
let mut open: Option<f64> = None;
|
||||
let mut high: Option<f64> = None;
|
||||
let mut low: Option<f64> = None;
|
||||
let mut close: Option<f64> = None;
|
||||
let mut adj_volume: Option<f64> = None;
|
||||
|
||||
for elem_res in doc.iter_elements() {
|
||||
let elem = elem_res.map_err(|err| BsonEodPriceError::CorruptBson {
|
||||
offset,
|
||||
detail: err.to_string(),
|
||||
})?;
|
||||
let key = elem.key();
|
||||
|
||||
if key == cstr!("eodSearchCode") {
|
||||
match decode_element_value("eodSearchCode", elem, offset)? {
|
||||
RawBsonRef::String(s) => {
|
||||
if s.trim().is_empty() {
|
||||
return Err(BsonEodPriceError::EmptyField {
|
||||
field: "eodSearchCode",
|
||||
});
|
||||
}
|
||||
eod_search_code = Some(s);
|
||||
}
|
||||
other => {
|
||||
return Err(BsonEodPriceError::WrongType {
|
||||
field: "eodSearchCode",
|
||||
actual: other.element_type(),
|
||||
});
|
||||
}
|
||||
}
|
||||
} else if key == cstr!("date") {
|
||||
match decode_element_value("date", elem, offset)? {
|
||||
RawBsonRef::String(s) => {
|
||||
session_date = Some(parse_ymd_strict(s)?);
|
||||
}
|
||||
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);
|
||||
}
|
||||
other => {
|
||||
return Err(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)?);
|
||||
} else if key == cstr!("high") {
|
||||
let val = decode_element_value("high", elem, offset)?;
|
||||
high = Some(decode_non_negative_number("high", val)?);
|
||||
} else if key == cstr!("low") {
|
||||
let val = decode_element_value("low", elem, offset)?;
|
||||
low = Some(decode_non_negative_number("low", val)?);
|
||||
} else if key == cstr!("close") {
|
||||
let val = decode_element_value("close", elem, offset)?;
|
||||
close = Some(decode_non_negative_number("close", val)?);
|
||||
} else if key == cstr!("volume") {
|
||||
let val = decode_element_value("volume", elem, offset)?;
|
||||
adj_volume = Some(decode_non_negative_number("volume", val)?);
|
||||
}
|
||||
// Unknown extra fields are skipped without calling `elem.value()`.
|
||||
}
|
||||
|
||||
let Some(eod_search_code) = eod_search_code else {
|
||||
return Err(BsonEodPriceError::MissingField {
|
||||
field: "eodSearchCode",
|
||||
});
|
||||
};
|
||||
let Some(session_date) = session_date else {
|
||||
return Err(BsonEodPriceError::MissingField { field: "date" });
|
||||
};
|
||||
let Some(open) = open else {
|
||||
return Err(BsonEodPriceError::MissingField { field: "open" });
|
||||
};
|
||||
let Some(high) = high else {
|
||||
return Err(BsonEodPriceError::MissingField { field: "high" });
|
||||
};
|
||||
let Some(low) = low else {
|
||||
return Err(BsonEodPriceError::MissingField { field: "low" });
|
||||
};
|
||||
let Some(close) = close else {
|
||||
return Err(BsonEodPriceError::MissingField { field: "close" });
|
||||
};
|
||||
let Some(adj_volume) = adj_volume else {
|
||||
return Err(BsonEodPriceError::MissingField { field: "volume" });
|
||||
};
|
||||
|
||||
Ok(RawEodDailyBar {
|
||||
eod_search_code,
|
||||
session_date,
|
||||
open,
|
||||
high,
|
||||
low,
|
||||
close,
|
||||
adj_volume,
|
||||
})
|
||||
}
|
||||
|
||||
/// Decodes a single `&RawDocument` representing an `eodPrices` MongoDB document in one forward pass
|
||||
/// without allocating a `String` or owned `bson::Document`.
|
||||
#[inline]
|
||||
pub fn decode_eod_price_doc<'a>(
|
||||
doc: &'a RawDocument,
|
||||
) -> Result<RawEodDailyBar<'a>, BsonEodPriceError> {
|
||||
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<RawEodDailyBar<'a>, BsonEodPriceError> {
|
||||
if bytes.len() < 4 {
|
||||
return Err(BsonEodPriceError::TruncatedDocument {
|
||||
offset: 0,
|
||||
remaining: bytes.len(),
|
||||
declared_len: None,
|
||||
});
|
||||
}
|
||||
let declared_len = i32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
|
||||
if declared_len < MIN_BSON_DOC_LEN {
|
||||
return Err(BsonEodPriceError::CorruptDocumentLength {
|
||||
offset: 0,
|
||||
declared_len,
|
||||
});
|
||||
}
|
||||
let len_usize = declared_len as usize;
|
||||
if len_usize > bytes.len() {
|
||||
return Err(BsonEodPriceError::TruncatedDocument {
|
||||
offset: 0,
|
||||
remaining: bytes.len(),
|
||||
declared_len: Some(declared_len),
|
||||
});
|
||||
}
|
||||
if len_usize < bytes.len() {
|
||||
return Err(BsonEodPriceError::CorruptDocumentLength {
|
||||
offset: 0,
|
||||
declared_len,
|
||||
});
|
||||
}
|
||||
let doc = RawDocument::from_bytes(bytes).map_err(|err| BsonEodPriceError::CorruptBson {
|
||||
offset: 0,
|
||||
detail: err.to_string(),
|
||||
})?;
|
||||
decode_eod_price_doc_at(doc, 0)
|
||||
}
|
||||
|
||||
/// Zero-copy iterator over concatenated length-prefixed BSON documents (wire / `mongodump` layout).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RawBsonDocIter<'a> {
|
||||
buf: &'a [u8],
|
||||
offset: usize,
|
||||
terminated: bool,
|
||||
}
|
||||
|
||||
/// Item returned by [`RawBsonDocIter::next_with_offset`].
|
||||
pub type RawBsonDocWithOffset<'a> = Result<(usize, &'a RawDocument), (usize, BsonEodPriceError)>;
|
||||
|
||||
impl<'a> RawBsonDocIter<'a> {
|
||||
/// Creates a new iterator starting at byte offset `0`.
|
||||
#[inline]
|
||||
pub fn new(buf: &'a [u8]) -> Self {
|
||||
Self {
|
||||
buf,
|
||||
offset: 0,
|
||||
terminated: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the next framed `&RawDocument` along with its starting byte offset in the buffer.
|
||||
///
|
||||
/// Unrecoverable framing errors (`TruncatedDocument`, `CorruptDocumentLength`) terminate the
|
||||
/// iterator cleanly so iteration never loops infinitely or slices out of bounds. A validly
|
||||
/// length-framed document with invalid BSON framing bytes returns `CorruptBson` and advances
|
||||
/// past the framed document so subsequent documents can still be read.
|
||||
pub fn next_with_offset(&mut self) -> Option<RawBsonDocWithOffset<'a>> {
|
||||
if self.terminated || self.offset >= self.buf.len() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let offset = self.offset;
|
||||
let remaining = self.buf.len() - offset;
|
||||
if remaining < 4 {
|
||||
self.terminated = true;
|
||||
return Some(Err((
|
||||
offset,
|
||||
BsonEodPriceError::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len: None,
|
||||
},
|
||||
)));
|
||||
}
|
||||
|
||||
let declared_len = i32::from_le_bytes([
|
||||
self.buf[offset],
|
||||
self.buf[offset + 1],
|
||||
self.buf[offset + 2],
|
||||
self.buf[offset + 3],
|
||||
]);
|
||||
if declared_len < MIN_BSON_DOC_LEN {
|
||||
self.terminated = true;
|
||||
return Some(Err((
|
||||
offset,
|
||||
BsonEodPriceError::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
},
|
||||
)));
|
||||
}
|
||||
|
||||
let doc_len = declared_len as usize;
|
||||
if doc_len > remaining {
|
||||
self.terminated = true;
|
||||
return Some(Err((
|
||||
offset,
|
||||
BsonEodPriceError::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len: Some(declared_len),
|
||||
},
|
||||
)));
|
||||
}
|
||||
|
||||
let slice = &self.buf[offset..offset + doc_len];
|
||||
self.offset += doc_len;
|
||||
|
||||
match RawDocument::from_bytes(slice) {
|
||||
Ok(doc) => Some(Ok((offset, doc))),
|
||||
Err(err) => Some(Err((
|
||||
offset,
|
||||
BsonEodPriceError::CorruptBson {
|
||||
offset,
|
||||
detail: err.to_string(),
|
||||
},
|
||||
))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Iterator for RawBsonDocIter<'a> {
|
||||
type Item = Result<&'a RawDocument, BsonEodPriceError>;
|
||||
|
||||
#[inline]
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
self.next_with_offset()
|
||||
.map(|res| res.map(|(_, doc)| doc).map_err(|(_, err)| err))
|
||||
}
|
||||
}
|
||||
|
||||
/// Walks a contiguous byte buffer of concatenated length-prefixed BSON documents, yielding
|
||||
/// zero-copy `&RawDocument` slices.
|
||||
#[inline]
|
||||
pub fn iter_raw_bson_docs<'a>(buf: &'a [u8]) -> RawBsonDocIter<'a> {
|
||||
RawBsonDocIter::new(buf)
|
||||
}
|
||||
|
||||
/// Streams a concatenated length-prefixed BSON buffer through [`decode_eod_price_doc`], invoking
|
||||
/// `on_bar` for every valid document and `on_error(byte_offset, err)` for every rejected document
|
||||
/// without aborting the stream on per-document errors.
|
||||
///
|
||||
/// Always maintains `stats.decoded + stats.rejected_total() == stats.docs_in`.
|
||||
pub fn decode_eod_price_buffer<'a, F, E>(
|
||||
buf: &'a [u8],
|
||||
mut on_bar: F,
|
||||
mut on_error: E,
|
||||
) -> BsonEodDecodeStats
|
||||
where
|
||||
F: FnMut(RawEodDailyBar<'a>),
|
||||
E: FnMut(usize, BsonEodPriceError),
|
||||
{
|
||||
let mut stats = BsonEodDecodeStats::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_eod_price_doc_at(doc, doc_offset) {
|
||||
Ok(bar) => {
|
||||
stats.decoded += 1;
|
||||
on_bar(bar);
|
||||
}
|
||||
Err(err) => {
|
||||
stats.record_error(&err);
|
||||
on_error(doc_offset, err);
|
||||
}
|
||||
},
|
||||
Err((doc_offset, err)) => {
|
||||
stats.record_error(&err);
|
||||
on_error(doc_offset, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stats
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "bson_eod_prices_tests.rs"]
|
||||
mod tests;
|
||||
785
tools/curate-etl/src/bson_eod_prices_tests.rs
Normal file
785
tools/curate-etl/src/bson_eod_prices_tests.rs
Normal file
|
|
@ -0,0 +1,785 @@
|
|||
use bson::oid::ObjectId;
|
||||
use bson::raw::{cstr, RawArrayBuf, RawBsonRef, RawDocumentBuf};
|
||||
use bson::spec::ElementType;
|
||||
use bson::DateTime;
|
||||
|
||||
use super::*;
|
||||
use crate::bars::{build_bars_1d, QmRawVolume};
|
||||
use crate::provider_mapping::{ProviderMappingRow, ProviderMappingTable};
|
||||
use crate::split::{ymd_to_epoch_days, SplitEvent, SplitTable};
|
||||
|
||||
fn day(y: i32, m: u32, d: u32) -> i32 {
|
||||
ymd_to_epoch_days(y, m, d).unwrap()
|
||||
}
|
||||
|
||||
fn make_valid_doc(
|
||||
code: &str,
|
||||
date: &str,
|
||||
open: f64,
|
||||
high: f64,
|
||||
low: f64,
|
||||
close: f64,
|
||||
volume: f64,
|
||||
) -> RawDocumentBuf {
|
||||
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
|
||||
}
|
||||
|
||||
fn assert_rel_eq(actual: f64, expected: f64, rel_tol: f64) {
|
||||
let diff = (actual - expected).abs();
|
||||
let scale = expected.abs().max(1.0);
|
||||
assert!(
|
||||
diff <= rel_tol * scale,
|
||||
"actual={actual} expected={expected} diff={diff} rel_tol={rel_tol}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_realistic_eod_price_doc_and_ignores_extra_fields() {
|
||||
let mut nested = RawDocumentBuf::new();
|
||||
nested.append(cstr!("provider"), "eodhd");
|
||||
nested.append(cstr!("version"), 2_i32);
|
||||
|
||||
let mut tags = RawArrayBuf::new();
|
||||
tags.push("us");
|
||||
tags.push("equity");
|
||||
|
||||
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!("providerExchange"), "US");
|
||||
doc.append(cstr!("source"), "eod");
|
||||
doc.append(cstr!("eodSearchCode"), "NVDA.US");
|
||||
doc.append(cstr!("date"), "2024-06-07");
|
||||
doc.append(cstr!("open"), 1197.70_f64);
|
||||
doc.append(cstr!("high"), 1216.92_f64);
|
||||
doc.append(cstr!("low"), 1180.22_f64);
|
||||
doc.append(cstr!("close"), 1208.88_f64);
|
||||
doc.append(cstr!("adjustedClose"), 120.888_f64);
|
||||
doc.append(cstr!("adjusted_close"), 120.888_f64);
|
||||
doc.append(cstr!("volume"), 412_390_000_i64);
|
||||
doc.append(cstr!("created_at"), DateTime::from_millis(1_717_804_800_000));
|
||||
doc.append(cstr!("updated_at"), DateTime::from_millis(1_717_891_200_000));
|
||||
doc.append(cstr!("meta"), RawBsonRef::Document(nested.as_ref()));
|
||||
doc.append(cstr!("tags"), RawBsonRef::Array(tags.as_ref()));
|
||||
|
||||
let bar = decode_eod_price_doc(&doc).unwrap();
|
||||
assert_eq!(bar.eod_search_code, "NVDA.US");
|
||||
assert_eq!(bar.session_date, day(2024, 6, 7));
|
||||
assert_eq!(bar.open.to_bits(), 1197.70_f64.to_bits());
|
||||
assert_eq!(bar.high.to_bits(), 1216.92_f64.to_bits());
|
||||
assert_eq!(bar.low.to_bits(), 1180.22_f64.to_bits());
|
||||
assert_eq!(bar.close.to_bits(), 1208.88_f64.to_bits());
|
||||
assert_eq!(bar.adj_volume.to_bits(), 412_390_000.0_f64.to_bits());
|
||||
|
||||
// Verify decode_eod_price_bytes matches decode_eod_price_doc bit-for-bit.
|
||||
let from_bytes = decode_eod_price_bytes(doc.as_bytes()).unwrap();
|
||||
assert_eq!(from_bytes, bar);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_double_int32_int64_numerics_and_zero_volume_normalization() {
|
||||
// Mixed Int32, Int64, and Double across OHLC and volume.
|
||||
let mut mixed = RawDocumentBuf::new();
|
||||
mixed.append(cstr!("eodSearchCode"), "SHOP.TO");
|
||||
mixed.append(cstr!("date"), "2024-02-29");
|
||||
mixed.append(cstr!("open"), 100_i32);
|
||||
mixed.append(cstr!("high"), 105_i64);
|
||||
mixed.append(cstr!("low"), 99.5_f64);
|
||||
mixed.append(cstr!("close"), 104_i32);
|
||||
mixed.append(cstr!("volume"), 5_000_000_000_i64);
|
||||
|
||||
let bar = decode_eod_price_doc(&mixed).unwrap();
|
||||
assert_eq!(bar.eod_search_code, "SHOP.TO");
|
||||
assert_eq!(bar.session_date, day(2024, 2, 29));
|
||||
assert_eq!(bar.open.to_bits(), 100.0_f64.to_bits());
|
||||
assert_eq!(bar.high.to_bits(), 105.0_f64.to_bits());
|
||||
assert_eq!(bar.low.to_bits(), 99.5_f64.to_bits());
|
||||
assert_eq!(bar.close.to_bits(), 104.0_f64.to_bits());
|
||||
assert_eq!(bar.adj_volume.to_bits(), 5_000_000_000.0_f64.to_bits());
|
||||
|
||||
// Zero volume in Double (+0.0, -0.0), Int32 (0), Int64 (0) all normalize to +0.0.
|
||||
let zero_cases: [RawBsonRef<'_>; 4] = [
|
||||
RawBsonRef::Double(0.0),
|
||||
RawBsonRef::Double(-0.0),
|
||||
RawBsonRef::Int32(0),
|
||||
RawBsonRef::Int64(0),
|
||||
];
|
||||
for zero_val in zero_cases {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("eodSearchCode"), "ZERO.US");
|
||||
doc.append(cstr!("date"), "2024-06-07");
|
||||
doc.append(cstr!("open"), -0.0_f64);
|
||||
doc.append(cstr!("high"), 10_i32);
|
||||
doc.append(cstr!("low"), 0_i64);
|
||||
doc.append(cstr!("close"), 5.5_f64);
|
||||
doc.append(cstr!("volume"), zero_val);
|
||||
|
||||
let decoded = decode_eod_price_doc(&doc).unwrap();
|
||||
assert_eq!(decoded.open.to_bits(), 0.0_f64.to_bits());
|
||||
assert_eq!(decoded.low.to_bits(), 0.0_f64.to_bits());
|
||||
assert_eq!(decoded.adj_volume.to_bits(), 0.0_f64.to_bits());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_ymd_string_and_bson_datetime_to_identical_epoch_days() {
|
||||
let cases = [
|
||||
("1969-12-31", day(1969, 12, 31)),
|
||||
("1970-01-01", day(1970, 1, 1)),
|
||||
("2024-02-29", day(2024, 2, 29)),
|
||||
("2024-06-07", day(2024, 6, 7)),
|
||||
];
|
||||
|
||||
for (date_str, expected_day) in cases {
|
||||
let str_doc = make_valid_doc("TEST.US", date_str, 10.0, 11.0, 9.5, 10.5, 1000.0);
|
||||
let decoded_str = decode_eod_price_doc(&str_doc).unwrap();
|
||||
assert_eq!(decoded_str.session_date, expected_day);
|
||||
|
||||
// Midnight UTC DateTime.
|
||||
let midnight_ms = i64::from(expected_day) * MILLIS_PER_DAY;
|
||||
let mut dt_mid = RawDocumentBuf::new();
|
||||
dt_mid.append(cstr!("eodSearchCode"), "TEST.US");
|
||||
dt_mid.append(cstr!("date"), DateTime::from_millis(midnight_ms));
|
||||
dt_mid.append(cstr!("open"), 10.0_f64);
|
||||
dt_mid.append(cstr!("high"), 11.0_f64);
|
||||
dt_mid.append(cstr!("low"), 9.5_f64);
|
||||
dt_mid.append(cstr!("close"), 10.5_f64);
|
||||
dt_mid.append(cstr!("volume"), 1000.0_f64);
|
||||
assert_eq!(
|
||||
decode_eod_price_doc(&dt_mid).unwrap().session_date,
|
||||
expected_day
|
||||
);
|
||||
|
||||
// Mid-day UTC DateTime (12:34:56.789 UTC) — critically tests pre-1970 Euclidean division
|
||||
// (`1969-12-31T12:34:56.789Z` must be -1, NOT 0).
|
||||
let midday_ms = midnight_ms + (12 * 3_600 + 34 * 60 + 56) * 1_000 + 789;
|
||||
let mut dt_midday = RawDocumentBuf::new();
|
||||
dt_midday.append(cstr!("eodSearchCode"), "TEST.US");
|
||||
dt_midday.append(cstr!("date"), DateTime::from_millis(midday_ms));
|
||||
dt_midday.append(cstr!("open"), 10.0_f64);
|
||||
dt_midday.append(cstr!("high"), 11.0_f64);
|
||||
dt_midday.append(cstr!("low"), 9.5_f64);
|
||||
dt_midday.append(cstr!("close"), 10.5_f64);
|
||||
dt_midday.append(cstr!("volume"), 1000.0_f64);
|
||||
assert_eq!(
|
||||
decode_eod_price_doc(&dt_midday).unwrap().session_date,
|
||||
expected_day
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_each_required_field_returns_typed_error_naming_field() {
|
||||
let required = [
|
||||
"eodSearchCode",
|
||||
"date",
|
||||
"open",
|
||||
"high",
|
||||
"low",
|
||||
"close",
|
||||
"volume",
|
||||
];
|
||||
|
||||
for omit in required {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
if omit != "eodSearchCode" {
|
||||
doc.append(cstr!("eodSearchCode"), "AAPL.US");
|
||||
}
|
||||
if omit != "date" {
|
||||
doc.append(cstr!("date"), "2024-06-07");
|
||||
}
|
||||
if omit != "open" {
|
||||
doc.append(cstr!("open"), 190.0_f64);
|
||||
}
|
||||
if omit != "high" {
|
||||
doc.append(cstr!("high"), 195.0_f64);
|
||||
}
|
||||
if omit != "low" {
|
||||
doc.append(cstr!("low"), 189.0_f64);
|
||||
}
|
||||
if omit != "close" {
|
||||
doc.append(cstr!("close"), 194.5_f64);
|
||||
}
|
||||
if omit != "volume" {
|
||||
doc.append(cstr!("volume"), 50_000_000_i64);
|
||||
}
|
||||
|
||||
let err = decode_eod_price_doc(&doc).unwrap_err();
|
||||
assert_eq!(err, BsonEodPriceError::MissingField { field: omit });
|
||||
assert!(
|
||||
err.to_string().contains(omit),
|
||||
"error message should name '{omit}', got: {err}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_or_whitespace_eod_search_code_returns_empty_field_error() {
|
||||
for blank in ["", " ", "\t\n"] {
|
||||
let doc = make_valid_doc(blank, "2024-06-07", 10.0, 11.0, 9.0, 10.5, 100.0);
|
||||
let err = decode_eod_price_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonEodPriceError::EmptyField {
|
||||
field: "eodSearchCode"
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains("eodSearchCode"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrong_bson_types_return_typed_error_naming_field() {
|
||||
let oid = ObjectId::from_bytes([0xAA; 12]);
|
||||
let mut arr = RawArrayBuf::new();
|
||||
arr.push(1_i32);
|
||||
|
||||
// Wrong types for eodSearchCode.
|
||||
for (bad_val, expected_ty) in [
|
||||
(RawBsonRef::Int32(42), ElementType::Int32),
|
||||
(RawBsonRef::Boolean(true), ElementType::Boolean),
|
||||
(RawBsonRef::Null, ElementType::Null),
|
||||
(RawBsonRef::ObjectId(oid), ElementType::ObjectId),
|
||||
(RawBsonRef::Array(arr.as_ref()), ElementType::Array),
|
||||
] {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("eodSearchCode"), bad_val);
|
||||
doc.append(cstr!("date"), "2024-06-07");
|
||||
doc.append(cstr!("open"), 10.0_f64);
|
||||
doc.append(cstr!("high"), 11.0_f64);
|
||||
doc.append(cstr!("low"), 9.0_f64);
|
||||
doc.append(cstr!("close"), 10.5_f64);
|
||||
doc.append(cstr!("volume"), 100_i32);
|
||||
|
||||
let err = decode_eod_price_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonEodPriceError::WrongType {
|
||||
field: "eodSearchCode",
|
||||
actual: expected_ty,
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains("eodSearchCode"));
|
||||
}
|
||||
|
||||
// Wrong types for date.
|
||||
for (bad_val, expected_ty) in [
|
||||
(RawBsonRef::Int64(20240607), ElementType::Int64),
|
||||
(RawBsonRef::Boolean(false), ElementType::Boolean),
|
||||
(RawBsonRef::Null, ElementType::Null),
|
||||
(RawBsonRef::ObjectId(oid), ElementType::ObjectId),
|
||||
(RawBsonRef::Array(arr.as_ref()), ElementType::Array),
|
||||
] {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("eodSearchCode"), "AAPL.US");
|
||||
doc.append(cstr!("date"), bad_val);
|
||||
doc.append(cstr!("open"), 10.0_f64);
|
||||
doc.append(cstr!("high"), 11.0_f64);
|
||||
doc.append(cstr!("low"), 9.0_f64);
|
||||
doc.append(cstr!("close"), 10.5_f64);
|
||||
doc.append(cstr!("volume"), 100_i32);
|
||||
|
||||
let err = decode_eod_price_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonEodPriceError::WrongType {
|
||||
field: "date",
|
||||
actual: expected_ty,
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains("date"));
|
||||
}
|
||||
|
||||
// Wrong types for each numeric field (open, high, low, close, volume).
|
||||
let numeric_fields = ["open", "high", "low", "close", "volume"];
|
||||
for target in numeric_fields {
|
||||
for (bad_val, expected_ty) in [
|
||||
(RawBsonRef::String("10.5"), ElementType::String),
|
||||
(RawBsonRef::Boolean(true), ElementType::Boolean),
|
||||
(RawBsonRef::Null, ElementType::Null),
|
||||
(RawBsonRef::ObjectId(oid), ElementType::ObjectId),
|
||||
(RawBsonRef::Array(arr.as_ref()), ElementType::Array),
|
||||
] {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("eodSearchCode"), "AAPL.US");
|
||||
doc.append(cstr!("date"), "2024-06-07");
|
||||
for &field in &numeric_fields {
|
||||
let key = match field {
|
||||
"open" => cstr!("open"),
|
||||
"high" => cstr!("high"),
|
||||
"low" => cstr!("low"),
|
||||
"close" => cstr!("close"),
|
||||
_ => cstr!("volume"),
|
||||
};
|
||||
if field == target {
|
||||
doc.append(key, bad_val);
|
||||
} else {
|
||||
doc.append(key, 10.0_f64);
|
||||
}
|
||||
}
|
||||
|
||||
let err = decode_eod_price_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonEodPriceError::WrongType {
|
||||
field: target,
|
||||
actual: expected_ty,
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(target));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_dates_and_out_of_range_datetimes_return_malformed_date_error() {
|
||||
for bad_date in [
|
||||
"2023-02-29",
|
||||
"1900-02-29",
|
||||
"2024-6-7",
|
||||
"2024-06-07T00:00:00Z",
|
||||
"2024-13-01",
|
||||
"2024-00-10",
|
||||
"2024-04-31",
|
||||
"",
|
||||
" 2024-06-07",
|
||||
"2024/06/07",
|
||||
"abcd-ef-gh",
|
||||
] {
|
||||
let doc = make_valid_doc("BAD.US", bad_date, 10.0, 11.0, 9.0, 10.5, 100.0);
|
||||
let err = decode_eod_price_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonEodPriceError::MalformedDate { field: "date" },
|
||||
"expected MalformedDate for '{bad_date}'"
|
||||
);
|
||||
assert!(err.to_string().contains("date"));
|
||||
}
|
||||
|
||||
for extreme_ms in [i64::MAX, i64::MIN] {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("eodSearchCode"), "BAD.US");
|
||||
doc.append(cstr!("date"), DateTime::from_millis(extreme_ms));
|
||||
doc.append(cstr!("open"), 10.0_f64);
|
||||
doc.append(cstr!("high"), 11.0_f64);
|
||||
doc.append(cstr!("low"), 9.0_f64);
|
||||
doc.append(cstr!("close"), 10.5_f64);
|
||||
doc.append(cstr!("volume"), 100_i32);
|
||||
|
||||
let err = decode_eod_price_doc(&doc).unwrap_err();
|
||||
assert_eq!(err, BsonEodPriceError::MalformedDate { field: "date" });
|
||||
assert!(err.to_string().contains("date"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_finite_and_negative_prices_or_volume_return_invalid_number_error() {
|
||||
let fields = ["open", "high", "low", "close", "volume"];
|
||||
let bad_values: [RawBsonRef<'_>; 6] = [
|
||||
RawBsonRef::Double(f64::NAN),
|
||||
RawBsonRef::Double(f64::INFINITY),
|
||||
RawBsonRef::Double(f64::NEG_INFINITY),
|
||||
RawBsonRef::Double(-0.01),
|
||||
RawBsonRef::Int32(-1),
|
||||
RawBsonRef::Int64(-100),
|
||||
];
|
||||
|
||||
for target in fields {
|
||||
for bad_val in bad_values {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("eodSearchCode"), "NUM.US");
|
||||
doc.append(cstr!("date"), "2024-06-07");
|
||||
for &field in &fields {
|
||||
let key = match field {
|
||||
"open" => cstr!("open"),
|
||||
"high" => cstr!("high"),
|
||||
"low" => cstr!("low"),
|
||||
"close" => cstr!("close"),
|
||||
_ => cstr!("volume"),
|
||||
};
|
||||
if field == target {
|
||||
doc.append(key, bad_val);
|
||||
} else {
|
||||
doc.append(key, 10.0_f64);
|
||||
}
|
||||
}
|
||||
|
||||
let err = decode_eod_price_doc(&doc).unwrap_err();
|
||||
assert!(
|
||||
matches!(err, BsonEodPriceError::InvalidNumber { field, .. } if field == target),
|
||||
"expected InvalidNumber for {target} with {bad_val:?}, got {err:?}"
|
||||
);
|
||||
assert!(err.to_string().contains(target));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncated_and_corrupt_length_prefixed_buffers_return_typed_errors_without_panicking() {
|
||||
// 1. Truncated header (< 4 bytes).
|
||||
let err = decode_eod_price_bytes(&[0x05, 0x00, 0x00]).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonEodPriceError::TruncatedDocument {
|
||||
offset: 0,
|
||||
remaining: 3,
|
||||
declared_len: None,
|
||||
}
|
||||
);
|
||||
|
||||
// 2. Declared length < 5 (0, 4, negative).
|
||||
for bad_len in [0_i32, 4_i32, -12_i32] {
|
||||
let mut buf = Vec::from(bad_len.to_le_bytes());
|
||||
buf.push(0);
|
||||
let err = decode_eod_price_bytes(&buf).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonEodPriceError::CorruptDocumentLength {
|
||||
offset: 0,
|
||||
declared_len: bad_len,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
// 3. Truncated body (declared_len > remaining).
|
||||
let valid = make_valid_doc("NVDA.US", "2024-06-07", 10.0, 11.0, 9.0, 10.5, 100.0);
|
||||
let full_bytes = valid.as_bytes();
|
||||
let truncated = &full_bytes[..full_bytes.len() - 5];
|
||||
let err = decode_eod_price_bytes(truncated).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonEodPriceError::TruncatedDocument {
|
||||
offset: 0,
|
||||
remaining: truncated.len(),
|
||||
declared_len: Some(full_bytes.len() as i32),
|
||||
}
|
||||
);
|
||||
|
||||
// 4. Corrupt trailing terminator (last byte != 0x00).
|
||||
let mut bad_term = full_bytes.to_vec();
|
||||
*bad_term.last_mut().unwrap() = 0xFF;
|
||||
let err = decode_eod_price_bytes(&bad_term).unwrap_err();
|
||||
assert!(
|
||||
matches!(err, BsonEodPriceError::CorruptBson { offset: 0, .. }),
|
||||
"expected CorruptBson for bad terminator, got {err:?}"
|
||||
);
|
||||
|
||||
// 5. Corrupt element framing inside a length-valid document (bad element type byte 0x7F).
|
||||
let mut bad_elem: Vec<u8> = Vec::new();
|
||||
let declared: i32 = 10;
|
||||
bad_elem.extend_from_slice(&declared.to_le_bytes());
|
||||
bad_elem.extend_from_slice(&[0x7F, b'a', 0x00, 0x01, 0x02, 0x00]);
|
||||
let err = decode_eod_price_bytes(&bad_elem).unwrap_err();
|
||||
assert!(
|
||||
matches!(err, BsonEodPriceError::CorruptBson { offset: 0, .. }),
|
||||
"expected CorruptBson for corrupt element framing, got {err:?}"
|
||||
);
|
||||
|
||||
// 6. Iterator terminates cleanly on framing errors without looping.
|
||||
let mut iter = iter_raw_bson_docs(truncated);
|
||||
assert!(matches!(
|
||||
iter.next(),
|
||||
Some(Err(BsonEodPriceError::TruncatedDocument { .. }))
|
||||
));
|
||||
assert!(iter.next().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_document_buffer_skips_bad_docs_and_reconciles_per_reason_stats() {
|
||||
let good_1 = make_valid_doc("AAPL.US", "2024-06-05", 194.0, 196.9, 193.5, 195.87, 54_000_000.0);
|
||||
|
||||
// Bad 1: missing field (`volume`).
|
||||
let mut bad_missing = RawDocumentBuf::new();
|
||||
bad_missing.append(cstr!("eodSearchCode"), "MISS.US");
|
||||
bad_missing.append(cstr!("date"), "2024-06-05");
|
||||
bad_missing.append(cstr!("open"), 10.0_f64);
|
||||
bad_missing.append(cstr!("high"), 11.0_f64);
|
||||
bad_missing.append(cstr!("low"), 9.0_f64);
|
||||
bad_missing.append(cstr!("close"), 10.5_f64);
|
||||
|
||||
// Bad 2: empty `eodSearchCode`.
|
||||
let bad_empty = make_valid_doc(" ", "2024-06-05", 10.0, 11.0, 9.0, 10.5, 100.0);
|
||||
|
||||
// Bad 3: wrong BSON type (`open` is string).
|
||||
let mut bad_type = RawDocumentBuf::new();
|
||||
bad_type.append(cstr!("eodSearchCode"), "TYPE.US");
|
||||
bad_type.append(cstr!("date"), "2024-06-05");
|
||||
bad_type.append(cstr!("open"), "not-a-number");
|
||||
bad_type.append(cstr!("high"), 11.0_f64);
|
||||
bad_type.append(cstr!("low"), 9.0_f64);
|
||||
bad_type.append(cstr!("close"), 10.5_f64);
|
||||
bad_type.append(cstr!("volume"), 100_i32);
|
||||
|
||||
// Bad 4: malformed date.
|
||||
let bad_date = make_valid_doc("DATE.US", "2023-02-29", 10.0, 11.0, 9.0, 10.5, 100.0);
|
||||
|
||||
// Bad 5: negative price.
|
||||
let bad_price = make_valid_doc("NEG.US", "2024-06-05", -1.0, 11.0, 9.0, 10.5, 100.0);
|
||||
|
||||
// Bad 6: NaN volume.
|
||||
let bad_vol = make_valid_doc("NAN.US", "2024-06-05", 10.0, 11.0, 9.0, 10.5, f64::NAN);
|
||||
|
||||
// Bad 7: length-valid document with corrupt trailing null byte (stream still continues past it).
|
||||
let mut bad_corrupt = make_valid_doc("COR.US", "2024-06-05", 10.0, 11.0, 9.0, 10.5, 100.0)
|
||||
.as_bytes()
|
||||
.to_vec();
|
||||
*bad_corrupt.last_mut().unwrap() = 0xEE;
|
||||
|
||||
let good_2 = make_valid_doc("MSFT.US", "2024-06-06", 423.0, 425.3, 420.5, 424.52, 14_800_000.0);
|
||||
|
||||
let mut buffer = Vec::new();
|
||||
buffer.extend_from_slice(good_1.as_bytes());
|
||||
buffer.extend_from_slice(bad_missing.as_bytes());
|
||||
buffer.extend_from_slice(bad_empty.as_bytes());
|
||||
buffer.extend_from_slice(bad_type.as_bytes());
|
||||
buffer.extend_from_slice(bad_date.as_bytes());
|
||||
buffer.extend_from_slice(bad_price.as_bytes());
|
||||
buffer.extend_from_slice(bad_vol.as_bytes());
|
||||
buffer.extend_from_slice(&bad_corrupt);
|
||||
buffer.extend_from_slice(good_2.as_bytes());
|
||||
|
||||
let mut decoded_codes: Vec<String> = Vec::new();
|
||||
let mut errors: Vec<(usize, BsonEodPriceError)> = Vec::new();
|
||||
|
||||
let stats = decode_eod_price_buffer(
|
||||
&buffer,
|
||||
|bar| decoded_codes.push(bar.eod_search_code.to_string()),
|
||||
|offset, err| errors.push((offset, err)),
|
||||
);
|
||||
|
||||
assert_eq!(decoded_codes, vec!["AAPL.US", "MSFT.US"]);
|
||||
assert_eq!(stats.docs_in, 9);
|
||||
assert_eq!(stats.decoded, 2);
|
||||
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_invalid_number, 2);
|
||||
assert_eq!(stats.rejected_corrupt_document, 1);
|
||||
assert_eq!(stats.rejected_total(), 7);
|
||||
assert_eq!(stats.decoded + stats.rejected_total(), stats.docs_in);
|
||||
assert_eq!(errors.len(), 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decoded_nvda_split_buffer_feeds_build_bars_1d_with_non_string_key_mapper() {
|
||||
let pre_split = day(2024, 6, 7);
|
||||
let ex_date = day(2024, 6, 10);
|
||||
let post_split = day(2024, 6, 11);
|
||||
const NVDA_LISTING_ID: i32 = 42;
|
||||
|
||||
// Encode NVDA 10:1 split fixture with mixed Int64 / Int32 / Double volume representations.
|
||||
let mut doc_pre = RawDocumentBuf::new();
|
||||
doc_pre.append(cstr!("eodSearchCode"), "NVDA.US");
|
||||
doc_pre.append(cstr!("date"), "2024-06-07");
|
||||
doc_pre.append(cstr!("open"), 1197.70_f64);
|
||||
doc_pre.append(cstr!("high"), 1216.92_f64);
|
||||
doc_pre.append(cstr!("low"), 1180.22_f64);
|
||||
doc_pre.append(cstr!("close"), 1208.88_f64);
|
||||
doc_pre.append(cstr!("volume"), 412_390_000_i64);
|
||||
|
||||
let mut doc_ex = RawDocumentBuf::new();
|
||||
doc_ex.append(cstr!("eodSearchCode"), "NVDA.US");
|
||||
doc_ex.append(cstr!("date"), "2024-06-10");
|
||||
doc_ex.append(cstr!("open"), 120.37_f64);
|
||||
doc_ex.append(cstr!("high"), 123.10_f64);
|
||||
doc_ex.append(cstr!("low"), 117.01_f64);
|
||||
doc_ex.append(cstr!("close"), 121.79_f64);
|
||||
doc_ex.append(cstr!("volume"), 314_162_700_i32);
|
||||
|
||||
let mut doc_post = RawDocumentBuf::new();
|
||||
doc_post.append(cstr!("eodSearchCode"), "NVDA.US");
|
||||
doc_post.append(
|
||||
cstr!("date"),
|
||||
DateTime::from_millis(i64::from(post_split) * MILLIS_PER_DAY),
|
||||
);
|
||||
doc_post.append(cstr!("open"), 121.77_f64);
|
||||
doc_post.append(cstr!("high"), 122.87_f64);
|
||||
doc_post.append(cstr!("low"), 118.74_f64);
|
||||
doc_post.append(cstr!("close"), 120.91_f64);
|
||||
doc_post.append(cstr!("volume"), 222_551_200.0_f64);
|
||||
|
||||
// Include an unmapped symbol to prove try_into_eod_daily_bar filters unmapped keys cleanly.
|
||||
let doc_unmapped = make_valid_doc("UNKNOWN.US", "2024-06-10", 10.0, 11.0, 9.0, 10.5, 1_000.0);
|
||||
|
||||
let mut buf = Vec::new();
|
||||
buf.extend_from_slice(doc_pre.as_bytes());
|
||||
buf.extend_from_slice(doc_ex.as_bytes());
|
||||
buf.extend_from_slice(doc_post.as_bytes());
|
||||
buf.extend_from_slice(doc_unmapped.as_bytes());
|
||||
|
||||
let mapping = ProviderMappingTable::from_rows([ProviderMappingRow {
|
||||
source: "eod".to_string(),
|
||||
source_id: "NVDA.US".to_string(),
|
||||
valid_from: day(1999, 1, 22),
|
||||
valid_to: None,
|
||||
listing_id: NVDA_LISTING_ID,
|
||||
}])
|
||||
.unwrap();
|
||||
|
||||
let mut bars: Vec<EodDailyBar<i32>> = Vec::new();
|
||||
let stats = decode_eod_price_buffer(
|
||||
&buf,
|
||||
|raw| {
|
||||
if let Some(bar) =
|
||||
raw.try_into_eod_daily_bar(|code, dt| mapping.resolve("eod", code, dt))
|
||||
{
|
||||
bars.push(bar);
|
||||
}
|
||||
},
|
||||
|offset, err| panic!("unexpected decode error at offset {offset}: {err}"),
|
||||
);
|
||||
|
||||
assert_eq!(stats.docs_in, 4);
|
||||
assert_eq!(stats.decoded, 4);
|
||||
assert_eq!(stats.rejected_total(), 0);
|
||||
assert_eq!(bars.len(), 3);
|
||||
|
||||
let splits: SplitTable<i32> = SplitTable::from_events([(
|
||||
NVDA_LISTING_ID,
|
||||
SplitEvent {
|
||||
ex_date,
|
||||
ratio: 10.0,
|
||||
},
|
||||
)])
|
||||
.unwrap();
|
||||
|
||||
let built =
|
||||
build_bars_1d(bars, &splits, std::iter::empty::<QmRawVolume<i32>>(), 0.01).unwrap();
|
||||
assert_eq!(built.rows.len(), 3);
|
||||
|
||||
// Pre-split 2024-06-07: raw OHLC preserved bit-for-bit, volume un-adjusted by / 10.
|
||||
let r0 = &built.rows[0];
|
||||
assert_eq!(r0.key, NVDA_LISTING_ID);
|
||||
assert_eq!(r0.session_date, pre_split);
|
||||
assert_eq!(r0.open.to_bits(), 1197.70_f64.to_bits());
|
||||
assert_eq!(r0.high.to_bits(), 1216.92_f64.to_bits());
|
||||
assert_eq!(r0.low.to_bits(), 1180.22_f64.to_bits());
|
||||
assert_eq!(r0.close.to_bits(), 1208.88_f64.to_bits());
|
||||
assert_rel_eq(r0.volume, 41_239_000.0, 1e-12);
|
||||
|
||||
// Ex-date 2024-06-10: factor = 1.0, volume unchanged.
|
||||
let r1 = &built.rows[1];
|
||||
assert_eq!(r1.session_date, ex_date);
|
||||
assert_eq!(r1.close.to_bits(), 121.79_f64.to_bits());
|
||||
assert_eq!(r1.volume.to_bits(), 314_162_700.0_f64.to_bits());
|
||||
|
||||
// Post-split 2024-06-11: factor = 1.0, volume unchanged.
|
||||
let r2 = &built.rows[2];
|
||||
assert_eq!(r2.session_date, post_split);
|
||||
assert_eq!(r2.close.to_bits(), 120.91_f64.to_bits());
|
||||
assert_eq!(r2.volume.to_bits(), 222_551_200.0_f64.to_bits());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_utf8_in_known_field_names_field_and_stream_continues() {
|
||||
let good_1 = make_valid_doc("AAPL.US", "2024-06-05", 194.0, 196.9, 193.5, 195.87, 54_000_000.0);
|
||||
let good_2 = make_valid_doc("MSFT.US", "2024-06-06", 423.0, 425.3, 420.5, 424.52, 14_800_000.0);
|
||||
|
||||
// Build a length-valid document and corrupt a byte inside the `eodSearchCode` string value
|
||||
// to invalid UTF-8 (`0xFF`) while leaving all framing and null terminators intact.
|
||||
let mut bad_utf8 = make_valid_doc("BADX.US", "2024-06-05", 10.0, 11.0, 9.0, 10.5, 100.0)
|
||||
.as_bytes()
|
||||
.to_vec();
|
||||
let needle = b"BADX.US";
|
||||
let pos = bad_utf8
|
||||
.windows(needle.len())
|
||||
.position(|w| w == needle)
|
||||
.expect("fixture should contain sentinel eodSearchCode bytes");
|
||||
bad_utf8[pos] = 0xFF;
|
||||
|
||||
// Single-document decode reports CorruptBson naming the field.
|
||||
let err = decode_eod_price_bytes(&bad_utf8).unwrap_err();
|
||||
match &err {
|
||||
BsonEodPriceError::CorruptBson { offset, detail } => {
|
||||
assert_eq!(*offset, 0);
|
||||
assert!(
|
||||
detail.contains("eodSearchCode"),
|
||||
"CorruptBson detail should name 'eodSearchCode', got: {detail}"
|
||||
);
|
||||
}
|
||||
other => panic!("expected CorruptBson for invalid UTF-8, got {other:?}"),
|
||||
}
|
||||
assert!(
|
||||
err.to_string().contains("eodSearchCode"),
|
||||
"Display output should name 'eodSearchCode', got: {err}"
|
||||
);
|
||||
|
||||
// Stream continues past the invalid-UTF-8 document and decodes the following document.
|
||||
let mut buffer = Vec::new();
|
||||
buffer.extend_from_slice(good_1.as_bytes());
|
||||
let bad_offset = buffer.len();
|
||||
buffer.extend_from_slice(&bad_utf8);
|
||||
buffer.extend_from_slice(good_2.as_bytes());
|
||||
|
||||
let mut decoded_codes: Vec<String> = Vec::new();
|
||||
let mut errors: Vec<(usize, BsonEodPriceError)> = Vec::new();
|
||||
let stats = decode_eod_price_buffer(
|
||||
&buffer,
|
||||
|bar| decoded_codes.push(bar.eod_search_code.to_string()),
|
||||
|offset, err| errors.push((offset, err)),
|
||||
);
|
||||
|
||||
assert_eq!(decoded_codes, vec!["AAPL.US", "MSFT.US"]);
|
||||
assert_eq!(stats.docs_in, 3);
|
||||
assert_eq!(stats.decoded, 2);
|
||||
assert_eq!(stats.rejected_corrupt_document, 1);
|
||||
assert_eq!(stats.rejected_total(), 1);
|
||||
assert_eq!(stats.decoded + stats.rejected_total(), stats.docs_in);
|
||||
assert_eq!(errors.len(), 1);
|
||||
assert_eq!(errors[0].0, bad_offset);
|
||||
assert!(
|
||||
errors[0].1.to_string().contains("eodSearchCode"),
|
||||
"stream error should name 'eodSearchCode', got: {}",
|
||||
errors[0].1
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corrupt_length_prefix_in_middle_stops_stream_cleanly() {
|
||||
let good_1 = make_valid_doc("AAPL.US", "2024-06-05", 194.0, 196.9, 193.5, 195.87, 54_000_000.0);
|
||||
let good_2 = make_valid_doc("MSFT.US", "2024-06-06", 423.0, 425.3, 420.5, 424.52, 14_800_000.0);
|
||||
|
||||
let mut buffer = Vec::new();
|
||||
buffer.extend_from_slice(good_1.as_bytes());
|
||||
let bad_offset = buffer.len();
|
||||
buffer.extend_from_slice(&2_i32.to_le_bytes());
|
||||
buffer.extend_from_slice(good_2.as_bytes());
|
||||
|
||||
let mut decoded_codes: Vec<String> = Vec::new();
|
||||
let mut errors: Vec<(usize, BsonEodPriceError)> = Vec::new();
|
||||
let stats = decode_eod_price_buffer(
|
||||
&buffer,
|
||||
|bar| decoded_codes.push(bar.eod_search_code.to_string()),
|
||||
|offset, err| errors.push((offset, err)),
|
||||
);
|
||||
|
||||
assert_eq!(decoded_codes, vec!["AAPL.US"]);
|
||||
assert_eq!(stats.docs_in, 2);
|
||||
assert_eq!(stats.decoded, 1);
|
||||
assert_eq!(stats.rejected_corrupt_document, 1);
|
||||
assert_eq!(stats.rejected_total(), 1);
|
||||
assert_eq!(stats.decoded + stats.rejected_total(), stats.docs_in);
|
||||
assert_eq!(
|
||||
errors,
|
||||
vec![(
|
||||
bad_offset,
|
||||
BsonEodPriceError::CorruptDocumentLength {
|
||||
offset: bad_offset,
|
||||
declared_len: 2,
|
||||
}
|
||||
)]
|
||||
);
|
||||
}
|
||||
|
|
@ -5,12 +5,12 @@
|
|||
|
||||
use crate::bench::{
|
||||
DEFAULT_ADJ_BENCH_EVENTS, DEFAULT_BARS_BENCH_ROWS, DEFAULT_BENCH_ROWS,
|
||||
DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS, 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_CORPORATE_ACTIONS_BENCH_EVENTS,
|
||||
DEFAULT_CURATE_BARS_BENCH_ROWS, DEFAULT_CURATE_SHORTS_BENCH_ROWS, DEFAULT_EVENTS_BENCH_ROWS,
|
||||
DEFAULT_FX_BENCH_ROWS, DEFAULT_PARQUET_ADJ_BENCH_ROWS, DEFAULT_PARQUET_BARS_BENCH_ROWS,
|
||||
DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS, DEFAULT_PARQUET_EVENTS_BENCH_ROWS,
|
||||
DEFAULT_PARQUET_FX_BENCH_ROWS, DEFAULT_PARQUET_SHORTS_BENCH_ROWS,
|
||||
DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS, DEFAULT_SHORTS_BENCH_ROWS,
|
||||
DEFAULT_CURATE_BARS_BENCH_ROWS, DEFAULT_CURATE_SHORTS_BENCH_ROWS,
|
||||
};
|
||||
|
||||
/// Parsed CLI command to execute.
|
||||
|
|
@ -32,6 +32,7 @@ pub enum CliAction {
|
|||
BenchParquetFx(usize),
|
||||
BenchParquetAdj(usize),
|
||||
BenchParquetCorporateActions(usize),
|
||||
BenchBsonEodPrices(usize),
|
||||
BenchCurateBars(usize),
|
||||
BenchCurateShorts(usize),
|
||||
}
|
||||
|
|
@ -58,6 +59,7 @@ pub fn format_usage(name: &str, version: &str) -> String {
|
|||
{name} bench-parquet-fx [rows] Run fixed-seed fx_1d Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_FX_BENCH_ROWS})\n\
|
||||
{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-curate-bars [rows] Run fixed-seed bars_1d curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_BARS_BENCH_ROWS})\n\
|
||||
{name} bench-curate-shorts [rows] Run fixed-seed shorts curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_SHORTS_BENCH_ROWS})"
|
||||
)
|
||||
|
|
@ -83,6 +85,7 @@ pub fn format_usage_stderr(name: &str) -> String {
|
|||
{name} bench-parquet-fx [rows]\n\
|
||||
{name} bench-parquet-adj [rows]\n\
|
||||
{name} bench-parquet-corporate-actions [rows]\n\
|
||||
{name} bench-bson-eod-prices [rows]\n\
|
||||
{name} bench-curate-bars [rows]\n\
|
||||
{name} bench-curate-shorts [rows]"
|
||||
)
|
||||
|
|
@ -237,6 +240,18 @@ pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
|||
["bench-parquet-corporate-actions", _, ..] => {
|
||||
Err("too many arguments for bench-parquet-corporate-actions".to_string())
|
||||
}
|
||||
["bench-bson-eod-prices"] => Ok(CliAction::BenchBsonEodPrices(
|
||||
DEFAULT_BSON_EOD_PRICES_BENCH_ROWS,
|
||||
)),
|
||||
["bench-bson-eod-prices", raw] => match raw.parse::<usize>() {
|
||||
Ok(n) if n > 0 => Ok(CliAction::BenchBsonEodPrices(n)),
|
||||
_ => Err(format!(
|
||||
"invalid row count '{raw}' (expected a positive integer)"
|
||||
)),
|
||||
},
|
||||
["bench-bson-eod-prices", _, ..] => {
|
||||
Err("too many arguments for bench-bson-eod-prices".to_string())
|
||||
}
|
||||
["bench-curate-bars"] => Ok(CliAction::BenchCurateBars(DEFAULT_CURATE_BARS_BENCH_ROWS)),
|
||||
["bench-curate-bars", raw] => match raw.parse::<usize>() {
|
||||
Ok(n) if n > 0 => Ok(CliAction::BenchCurateBars(n)),
|
||||
|
|
@ -528,6 +543,24 @@ mod tests {
|
|||
assert!(parse_args(&to_args(&["bench-parquet-corporate-actions", "10", "20"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_and_validates_bench_bson_eod_prices_args() {
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&["bench-bson-eod-prices"])),
|
||||
Ok(CliAction::BenchBsonEodPrices(
|
||||
DEFAULT_BSON_EOD_PRICES_BENCH_ROWS
|
||||
))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&["bench-bson-eod-prices", "250000"])),
|
||||
Ok(CliAction::BenchBsonEodPrices(250_000))
|
||||
);
|
||||
assert!(parse_args(&to_args(&["bench-bson-eod-prices", "0"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-bson-eod-prices", "-5"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-bson-eod-prices", "abc"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-bson-eod-prices", "10", "20"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usage_strings_mention_all_benchmarks() {
|
||||
let full = format_usage("curate-etl", "0.1.0");
|
||||
|
|
@ -545,6 +578,7 @@ mod tests {
|
|||
assert!(full.contains("bench-parquet-fx"));
|
||||
assert!(full.contains("bench-parquet-adj"));
|
||||
assert!(full.contains("bench-parquet-corporate-actions"));
|
||||
assert!(full.contains("bench-bson-eod-prices"));
|
||||
assert!(full.contains("bench-curate-bars"));
|
||||
assert!(full.contains("bench-curate-shorts"));
|
||||
|
||||
|
|
@ -563,6 +597,7 @@ mod tests {
|
|||
assert!(short.contains("bench-parquet-fx"));
|
||||
assert!(short.contains("bench-parquet-adj"));
|
||||
assert!(short.contains("bench-parquet-corporate-actions"));
|
||||
assert!(short.contains("bench-bson-eod-prices"));
|
||||
assert!(short.contains("bench-curate-bars"));
|
||||
assert!(short.contains("bench-curate-shorts"));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@
|
|||
pub mod adj;
|
||||
pub mod bars;
|
||||
pub mod bench;
|
||||
pub mod bson_eod_prices;
|
||||
pub mod cli;
|
||||
pub mod corporate_actions;
|
||||
pub mod events;
|
||||
|
|
@ -27,6 +28,10 @@ pub use bars::{
|
|||
build_bars_1d, Bar1dRow, Bars1dBuild, Bars1dStats, BarsError, EodDailyBar, QmRawVolume,
|
||||
VolumeMismatchSample, MAX_MISMATCH_SAMPLES,
|
||||
};
|
||||
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 corporate_actions::{
|
||||
build_corporate_actions, CorporateActionError, CorporateActionKind, CorporateActionRow,
|
||||
CorporateActionsBuild, CorporateActionsStats, DelistingOutcomeEvent, DividendActionEvent,
|
||||
|
|
|
|||
|
|
@ -4,12 +4,12 @@ use std::env;
|
|||
use std::process::ExitCode;
|
||||
|
||||
use curate_etl::bench::{
|
||||
run_adj_benchmark, run_bars_benchmark, run_corporate_actions_benchmark, run_events_benchmark,
|
||||
run_fx_benchmark, run_parquet_adj_benchmark, run_parquet_bars_benchmark,
|
||||
run_adj_benchmark, run_bars_benchmark, run_bson_eod_prices_benchmark,
|
||||
run_corporate_actions_benchmark, run_curate_bars_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_curate_bars_benchmark,
|
||||
run_curate_shorts_benchmark,
|
||||
run_shorts_benchmark, run_split_benchmark,
|
||||
};
|
||||
use curate_etl::cli::{format_usage, format_usage_stderr, parse_args, CliAction};
|
||||
|
||||
|
|
@ -478,6 +478,31 @@ fn main() -> ExitCode {
|
|||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchBsonEodPrices(rows)) => {
|
||||
let report = run_bson_eod_prices_benchmark(rows);
|
||||
println!("curate-etl bench-bson-eod-prices");
|
||||
println!(" input: rows={} bytes={}", report.rows, report.bytes);
|
||||
println!(
|
||||
" decode: decoded={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={})",
|
||||
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
|
||||
);
|
||||
println!(
|
||||
" perf: elapsed={:.2} ms throughput={:.0} rows/s scan={:.2} MB/s latency={:.2} ns/row checksum=0x{:016x}",
|
||||
report.elapsed_ms,
|
||||
report.rows_per_sec,
|
||||
report.mb_per_sec,
|
||||
report.ns_per_row,
|
||||
report.checksum
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchCurateBars(rows)) => {
|
||||
let report = match run_curate_bars_benchmark(rows) {
|
||||
Ok(report) => report,
|
||||
|
|
|
|||
477
tools/curate-etl/tests/bson_eod_prices_qa_contract.rs
Normal file
477
tools/curate-etl/tests/bson_eod_prices_qa_contract.rs
Normal file
|
|
@ -0,0 +1,477 @@
|
|||
//! QA contract tests for the public `eodPrices` raw BSON decoder (T-97 / M1.2o).
|
||||
//!
|
||||
//! Covers gaps left by the in-crate `bson_eod_prices_tests.rs`, using only the public API:
|
||||
//! - zero-copy: decoded `eod_search_code` borrows from the input buffer;
|
||||
//! - field-order independence, case-sensitive keys, nested look-alike keys ignored;
|
||||
//! - `DateTime` day boundaries (last ms of a day, -1 ms before epoch);
|
||||
//! - error callbacks receive the exact byte offset of the rejected document;
|
||||
//! - empty buffer, truncated tail after good docs, `i32::MAX` declared length, trailing bytes;
|
||||
//! - seeded byte-mutation fuzz: never panics and `decoded + rejected == docs_in` always holds,
|
||||
//! and every decoded bar is identical to the single-document decode of the same bytes;
|
||||
//! - `bench-bson-eod-prices` 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::{
|
||||
decode_eod_price_buffer, decode_eod_price_bytes, decode_eod_price_doc, iter_raw_bson_docs,
|
||||
ymd_to_epoch_days, BsonEodPriceError, RawEodDailyBar,
|
||||
};
|
||||
|
||||
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 valid_doc(code: &str, date: &str, close: f64, volume: i64) -> RawDocumentBuf {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("_id"), "ignored");
|
||||
doc.append(cstr!("eodSearchCode"), code);
|
||||
doc.append(cstr!("date"), date);
|
||||
doc.append(cstr!("open"), close - 1.0);
|
||||
doc.append(cstr!("high"), close + 1.0);
|
||||
doc.append(cstr!("low"), close - 2.0);
|
||||
doc.append(cstr!("close"), close);
|
||||
doc.append(cstr!("volume"), volume);
|
||||
doc
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decoded_search_code_borrows_from_input_buffer_without_copying() {
|
||||
let doc = valid_doc("RY.TO", "2024-06-07", 130.0, 1_000);
|
||||
let bytes = doc.as_bytes();
|
||||
let bar = decode_eod_price_bytes(bytes).unwrap();
|
||||
|
||||
let start = bytes.as_ptr() as usize;
|
||||
let end = start + bytes.len();
|
||||
let code_ptr = bar.eod_search_code.as_ptr() as usize;
|
||||
assert!(
|
||||
code_ptr >= start && code_ptr + bar.eod_search_code.len() <= end,
|
||||
"eod_search_code must point into the input bytes"
|
||||
);
|
||||
assert_eq!(bar.eod_search_code, "RY.TO");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn field_order_does_not_change_the_decoded_bar() {
|
||||
let mut reversed = RawDocumentBuf::new();
|
||||
reversed.append(cstr!("volume"), 1_000_i64);
|
||||
reversed.append(cstr!("close"), 130.0_f64);
|
||||
reversed.append(cstr!("low"), 128.0_f64);
|
||||
reversed.append(cstr!("high"), 131.0_f64);
|
||||
reversed.append(cstr!("open"), 129.0_f64);
|
||||
reversed.append(cstr!("date"), "2024-06-07");
|
||||
reversed.append(cstr!("eodSearchCode"), "RY.TO");
|
||||
|
||||
let forward = valid_doc("RY.TO", "2024-06-07", 130.0, 1_000);
|
||||
assert_eq!(
|
||||
decode_eod_price_doc(&reversed).unwrap(),
|
||||
decode_eod_price_doc(&forward).unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keys_are_case_sensitive_and_nested_lookalikes_are_ignored() {
|
||||
// `Volume` (capitalised) and a nested `volume` must not satisfy the top-level field.
|
||||
let mut nested = RawDocumentBuf::new();
|
||||
nested.append(cstr!("volume"), 5_i64);
|
||||
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("eodSearchCode"), "RY.TO");
|
||||
doc.append(cstr!("date"), "2024-06-07");
|
||||
doc.append(cstr!("open"), 1.0_f64);
|
||||
doc.append(cstr!("high"), 1.0_f64);
|
||||
doc.append(cstr!("low"), 1.0_f64);
|
||||
doc.append(cstr!("close"), 1.0_f64);
|
||||
doc.append(cstr!("Volume"), 5_i64);
|
||||
doc.append(cstr!("meta"), RawBsonRef::Document(nested.as_ref()));
|
||||
|
||||
assert_eq!(
|
||||
decode_eod_price_doc(&doc).unwrap_err(),
|
||||
BsonEodPriceError::MissingField { field: "volume" }
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_fields_with_unusual_types_are_ignored() {
|
||||
// Only known keys are type-checked; the writer's optional `adjustedClose` may be null.
|
||||
let mut doc = valid_doc("RY.TO", "2024-06-07", 130.0, 1_000);
|
||||
doc.append(cstr!("adjustedClose"), RawBsonRef::Null);
|
||||
doc.append(cstr!("adjusted_close"), "n/a");
|
||||
doc.append(cstr!("updated_at"), true);
|
||||
|
||||
let bar = decode_eod_price_bytes(doc.as_bytes()).unwrap();
|
||||
assert_eq!(bar.close, 130.0);
|
||||
assert_eq!(bar.adj_volume, 1_000.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn datetime_maps_to_utc_calendar_day_at_both_boundaries() {
|
||||
let d = day(2024, 6, 7);
|
||||
let cases = [
|
||||
(i64::from(d) * MILLIS_PER_DAY, d),
|
||||
(i64::from(d) * MILLIS_PER_DAY + MILLIS_PER_DAY - 1, d),
|
||||
(i64::from(d + 1) * MILLIS_PER_DAY, d + 1),
|
||||
(-1, -1),
|
||||
(0, 0),
|
||||
];
|
||||
for (ms, expected) in cases {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("eodSearchCode"), "RY.TO");
|
||||
doc.append(cstr!("date"), DateTime::from_millis(ms));
|
||||
doc.append(cstr!("open"), 1.0_f64);
|
||||
doc.append(cstr!("high"), 1.0_f64);
|
||||
doc.append(cstr!("low"), 1.0_f64);
|
||||
doc.append(cstr!("close"), 1.0_f64);
|
||||
doc.append(cstr!("volume"), 1_i32);
|
||||
assert_eq!(
|
||||
decode_eod_price_doc(&doc).unwrap().session_date,
|
||||
expected,
|
||||
"ms={ms}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn key_mapper_receives_search_code_and_session_date() {
|
||||
let doc = valid_doc("RY.TO", "2024-06-07", 130.0, 1_000);
|
||||
let raw: RawEodDailyBar<'_> = decode_eod_price_doc(&doc).unwrap();
|
||||
|
||||
let mut seen = None;
|
||||
let bar = raw.into_eod_daily_bar(|code, date| {
|
||||
seen = Some((code.len(), date));
|
||||
7_u32
|
||||
});
|
||||
assert_eq!(seen, Some((5, day(2024, 6, 7))));
|
||||
assert_eq!(bar.key, 7);
|
||||
assert_eq!(bar.session_date, day(2024, 6, 7));
|
||||
assert_eq!(bar.adj_volume, 1_000.0);
|
||||
|
||||
assert!(raw.try_into_eod_daily_bar(|_, _| None::<u32>).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_callback_reports_exact_byte_offset_of_each_rejected_doc() {
|
||||
let good = valid_doc("A.US", "2024-06-07", 10.0, 1);
|
||||
let bad_date = valid_doc("B.US", "2024-02-30", 10.0, 1);
|
||||
let bad_vol = valid_doc("C.US", "2024-06-07", 10.0, -1);
|
||||
|
||||
let mut buf = Vec::new();
|
||||
buf.extend_from_slice(good.as_bytes());
|
||||
let off_bad_date = buf.len();
|
||||
buf.extend_from_slice(bad_date.as_bytes());
|
||||
buf.extend_from_slice(good.as_bytes());
|
||||
let off_bad_vol = buf.len();
|
||||
buf.extend_from_slice(bad_vol.as_bytes());
|
||||
|
||||
let mut errors = Vec::new();
|
||||
let mut decoded = 0;
|
||||
let stats = decode_eod_price_buffer(&buf, |_| decoded += 1, |o, e| errors.push((o, e)));
|
||||
|
||||
assert_eq!(decoded, 2);
|
||||
assert_eq!(
|
||||
errors,
|
||||
vec![
|
||||
(
|
||||
off_bad_date,
|
||||
BsonEodPriceError::MalformedDate { field: "date" }
|
||||
),
|
||||
(
|
||||
off_bad_vol,
|
||||
BsonEodPriceError::InvalidNumber {
|
||||
field: "volume",
|
||||
value: -1.0
|
||||
}
|
||||
),
|
||||
]
|
||||
);
|
||||
assert_eq!(stats.docs_in, 4);
|
||||
assert_eq!(stats.decoded + stats.rejected_total(), stats.docs_in);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_buffer_yields_no_docs_and_no_callbacks() {
|
||||
let stats = decode_eod_price_buffer(
|
||||
&[],
|
||||
|_| panic!("no bar expected"),
|
||||
|_, _| panic!("no error expected"),
|
||||
);
|
||||
assert_eq!(stats.docs_in, 0);
|
||||
assert_eq!(stats.rejected_total(), 0);
|
||||
assert!(iter_raw_bson_docs(&[]).next().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncated_tail_after_good_docs_counts_one_corrupt_reject() {
|
||||
let good = valid_doc("A.US", "2024-06-07", 10.0, 1);
|
||||
let mut buf = Vec::new();
|
||||
buf.extend_from_slice(good.as_bytes());
|
||||
buf.extend_from_slice(good.as_bytes());
|
||||
let tail_offset = buf.len();
|
||||
buf.extend_from_slice(&good.as_bytes()[..10]);
|
||||
|
||||
let mut errors = Vec::new();
|
||||
let stats = decode_eod_price_buffer(&buf, |_| {}, |o, e| errors.push((o, e)));
|
||||
|
||||
assert_eq!(stats.docs_in, 3);
|
||||
assert_eq!(stats.decoded, 2);
|
||||
assert_eq!(stats.rejected_corrupt_document, 1);
|
||||
assert_eq!(errors.len(), 1);
|
||||
assert_eq!(errors[0].0, tail_offset);
|
||||
assert!(matches!(
|
||||
errors[0].1,
|
||||
BsonEodPriceError::TruncatedDocument {
|
||||
remaining: 10,
|
||||
declared_len: Some(_),
|
||||
..
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn huge_declared_length_is_truncation_not_a_panic() {
|
||||
let mut buf = i32::MAX.to_le_bytes().to_vec();
|
||||
buf.extend_from_slice(&[0u8; 16]);
|
||||
assert_eq!(
|
||||
decode_eod_price_bytes(&buf).unwrap_err(),
|
||||
BsonEodPriceError::TruncatedDocument {
|
||||
offset: 0,
|
||||
remaining: 20,
|
||||
declared_len: Some(i32::MAX),
|
||||
}
|
||||
);
|
||||
let stats = decode_eod_price_buffer(&buf, |_| {}, |_, _| {});
|
||||
assert_eq!(stats.docs_in, 1);
|
||||
assert_eq!(stats.rejected_corrupt_document, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_doc_decode_rejects_trailing_bytes() {
|
||||
let mut bytes = valid_doc("A.US", "2024-06-07", 10.0, 1).as_bytes().to_vec();
|
||||
let declared = bytes.len() as i32;
|
||||
bytes.push(0);
|
||||
assert_eq!(
|
||||
decode_eod_price_bytes(&bytes).unwrap_err(),
|
||||
BsonEodPriceError::CorruptDocumentLength {
|
||||
offset: 0,
|
||||
declared_len: declared,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/// `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)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seeded_byte_mutation_fuzz_never_panics_and_always_reconciles() {
|
||||
let mut base = Vec::new();
|
||||
for i in 0..8 {
|
||||
let code = format!("S{i}.US");
|
||||
base.extend_from_slice(valid_doc(&code, "2024-06-07", 10.0 + i as f64, 100).as_bytes());
|
||||
}
|
||||
|
||||
let mut rng = SplitMix64(0x0B50_7E57_F022_0097);
|
||||
for _ in 0..3_000 {
|
||||
let mut buf = base.clone();
|
||||
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);
|
||||
}
|
||||
|
||||
// Every bar emitted by the stream must equal the single-doc decode of its framed bytes.
|
||||
let mut offsets = Vec::new();
|
||||
let mut iter = iter_raw_bson_docs(&buf);
|
||||
while let Some(item) = iter.next_with_offset() {
|
||||
if let Ok((off, doc)) = item {
|
||||
offsets.push((off, doc.as_bytes().len()));
|
||||
}
|
||||
}
|
||||
|
||||
let mut bars = Vec::new();
|
||||
let stats = decode_eod_price_buffer(&buf, |b| bars.push(b), |_, _| {});
|
||||
assert_eq!(stats.decoded + stats.rejected_total(), stats.docs_in);
|
||||
assert_eq!(stats.decoded, bars.len());
|
||||
|
||||
let mut expected = Vec::new();
|
||||
for (off, len) in offsets {
|
||||
if let Ok(b) = decode_eod_price_bytes(&buf[off..off + len]) {
|
||||
expected.push(b);
|
||||
}
|
||||
}
|
||||
// Compare bit patterns so a NaN can never hide a mismatch (decoder rejects NaN anyway).
|
||||
let key = |b: &RawEodDailyBar<'_>| {
|
||||
(
|
||||
b.eod_search_code.to_string(),
|
||||
b.session_date,
|
||||
[b.open, b.high, b.low, b.close, b.adj_volume].map(f64::to_bits),
|
||||
)
|
||||
};
|
||||
assert_eq!(
|
||||
bars.iter().map(key).collect::<Vec<_>>(),
|
||||
expected.iter().map(key).collect::<Vec<_>>()
|
||||
);
|
||||
for b in &bars {
|
||||
for v in [b.open, b.high, b.low, b.close, b.adj_volume] {
|
||||
assert!(v.is_finite() && v >= 0.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run_bin(args: &[&str]) -> Output {
|
||||
Command::new(env!("CARGO_BIN_EXE_curate-etl"))
|
||||
.args(args)
|
||||
.output()
|
||||
.expect("spawn curate-etl binary")
|
||||
}
|
||||
|
||||
fn checksum_line(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 decode = text
|
||||
.lines()
|
||||
.find(|l| l.trim_start().starts_with("decode:"))
|
||||
.unwrap_or_else(|| panic!("no decode line in output: {text}"));
|
||||
format!("{checksum} {}", decode.trim())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bench_binary_prints_identical_checksum_across_runs() {
|
||||
let a = run_bin(&["bench-bson-eod-prices", "5000"]);
|
||||
let b = run_bin(&["bench-bson-eod-prices", "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=", "rows/s", "MB/s", "checksum=0x"] {
|
||||
assert!(text.contains(needle), "missing {needle}: {text}");
|
||||
}
|
||||
assert_eq!(checksum_line(&a), checksum_line(&b));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bench_binary_rejects_invalid_row_counts() {
|
||||
for args in [
|
||||
&["bench-bson-eod-prices", "0"][..],
|
||||
&["bench-bson-eod-prices", "-5"][..],
|
||||
&["bench-bson-eod-prices", "abc"][..],
|
||||
&["bench-bson-eod-prices", "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");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn binary_usage_lists_bson_bench_alongside_merged_curate_benches() {
|
||||
let out = run_bin(&["--help"]);
|
||||
assert!(
|
||||
out.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
let text = String::from_utf8_lossy(&out.stdout);
|
||||
for needle in [
|
||||
"bench-bson-eod-prices",
|
||||
"bench-curate-bars",
|
||||
"bench-curate-shorts",
|
||||
] {
|
||||
assert!(text.contains(needle), "usage missing {needle}: {text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reused_search_code_resolves_listing_by_decoded_session_date() {
|
||||
use curate_etl::{ProviderMappingRow, ProviderMappingTable};
|
||||
|
||||
// Arrange: one ticker reused by two listings with a one-day gap between them.
|
||||
let mapping = ProviderMappingTable::from_rows([
|
||||
ProviderMappingRow {
|
||||
source: "eod".to_string(),
|
||||
source_id: "REUSE.US".to_string(),
|
||||
valid_from: day(2015, 1, 2),
|
||||
valid_to: Some(day(2020, 1, 30)),
|
||||
listing_id: 1,
|
||||
},
|
||||
ProviderMappingRow {
|
||||
source: "eod".to_string(),
|
||||
source_id: "REUSE.US".to_string(),
|
||||
valid_from: day(2020, 2, 1),
|
||||
valid_to: None,
|
||||
listing_id: 2,
|
||||
},
|
||||
])
|
||||
.unwrap();
|
||||
|
||||
let mut buf = Vec::new();
|
||||
buf.extend_from_slice(valid_doc("REUSE.US", "2020-01-30", 10.0, 100).as_bytes());
|
||||
buf.extend_from_slice(valid_doc("REUSE.US", "2020-01-31", 10.0, 100).as_bytes());
|
||||
// First day of the successor listing, stored as a mid-day BSON DateTime.
|
||||
let mut dt_doc = RawDocumentBuf::new();
|
||||
dt_doc.append(cstr!("eodSearchCode"), "REUSE.US");
|
||||
dt_doc.append(
|
||||
cstr!("date"),
|
||||
DateTime::from_millis(i64::from(day(2020, 2, 1)) * MILLIS_PER_DAY + 43_200_000),
|
||||
);
|
||||
dt_doc.append(cstr!("open"), 9.0);
|
||||
dt_doc.append(cstr!("high"), 11.0);
|
||||
dt_doc.append(cstr!("low"), 8.0);
|
||||
dt_doc.append(cstr!("close"), 10.0);
|
||||
dt_doc.append(cstr!("volume"), 100_i32);
|
||||
buf.extend_from_slice(dt_doc.as_bytes());
|
||||
|
||||
// Act
|
||||
let mut resolved: Vec<(i32, Option<i32>)> = Vec::new();
|
||||
let stats = decode_eod_price_buffer(
|
||||
&buf,
|
||||
|raw| {
|
||||
let key = raw
|
||||
.try_into_eod_daily_bar(|code, d| mapping.resolve("eod", code, d))
|
||||
.map(|b| b.key);
|
||||
resolved.push((raw.session_date, key));
|
||||
},
|
||||
|offset, err| panic!("unexpected reject at {offset}: {err}"),
|
||||
);
|
||||
|
||||
// Assert: each bar maps to the listing valid on its own date; the gap day maps to none.
|
||||
assert_eq!(stats.decoded, 3);
|
||||
assert_eq!(
|
||||
resolved,
|
||||
vec![
|
||||
(day(2020, 1, 30), Some(1)),
|
||||
(day(2020, 1, 31), None),
|
||||
(day(2020, 2, 1), Some(2)),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn int64_volume_beyond_i32_range_decodes_exactly() {
|
||||
let doc = valid_doc("BIG.US", "2024-06-07", 10.0, 3_000_000_123);
|
||||
let bar = decode_eod_price_doc(&doc).unwrap();
|
||||
assert_eq!(bar.adj_volume.to_bits(), 3_000_000_123.0_f64.to_bits());
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue