T-90: M1.2i — tools/curate-etl: Zstd Parquet writer for bars_1d (year=YYYY/part.parquet, contract schema) with round-trip tests and local benchmark (adds the parquet crate)
This commit is contained in:
commit
fe9ec15199
10 changed files with 4580 additions and 11 deletions
190
Cargo.lock
generated
190
Cargo.lock
generated
|
|
@ -2,6 +2,21 @@
|
|||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "ahash"
|
||||
version = "0.8.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3019c0b8d883a8a17df3129e417ef463c087807d245e8881a31d583dee1c0519"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"const-random",
|
||||
"getrandom 0.3.4",
|
||||
"getrandom 0.4.3",
|
||||
"once_cell",
|
||||
"version_check",
|
||||
"zerocopy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "aho-corasick"
|
||||
version = "1.1.5"
|
||||
|
|
@ -89,6 +104,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||
checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69"
|
||||
dependencies = [
|
||||
"find-msvc-tools",
|
||||
"jobserver",
|
||||
"libc",
|
||||
"shlex",
|
||||
]
|
||||
|
||||
|
|
@ -112,6 +129,25 @@ dependencies = [
|
|||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "const-random"
|
||||
version = "0.1.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d38d4bb3e79c716fd0330d8da84171b0135e59e01076e99f22b75a64c56e952c"
|
||||
dependencies = [
|
||||
"const-random-macro",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "const-random-macro"
|
||||
version = "0.1.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d66bb491e9fc48cb3fed9d57df886880a751d540d645ebc86b6d9d35b8fa8457"
|
||||
dependencies = [
|
||||
"getrandom 0.4.3",
|
||||
"tiny-keccak",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "convert_case"
|
||||
version = "0.6.0"
|
||||
|
|
@ -183,6 +219,12 @@ version = "0.8.23"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
|
||||
|
||||
[[package]]
|
||||
name = "crunchy"
|
||||
version = "0.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
|
||||
|
||||
[[package]]
|
||||
name = "ctor"
|
||||
version = "0.2.9"
|
||||
|
|
@ -196,6 +238,9 @@ dependencies = [
|
|||
[[package]]
|
||||
name = "curate-etl"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"parquet",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dashmap"
|
||||
|
|
@ -204,7 +249,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||
checksum = "978747c1d849a7d2ee5e8adc0159961c48fb7e5db2f06af6723b80123bb53856"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"hashbrown",
|
||||
"hashbrown 0.14.5",
|
||||
"lock_api",
|
||||
"once_cell",
|
||||
"parking_lot_core",
|
||||
|
|
@ -223,7 +268,7 @@ dependencies = [
|
|||
"napi",
|
||||
"napi-build",
|
||||
"napi-derive",
|
||||
"num-bigint",
|
||||
"num-bigint 0.4.6",
|
||||
"num-rational",
|
||||
"num-traits",
|
||||
"parking_lot",
|
||||
|
|
@ -299,16 +344,47 @@ checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
|
|||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"r-efi",
|
||||
"r-efi 5.3.0",
|
||||
"wasip2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"js-sys",
|
||||
"libc",
|
||||
"r-efi 6.0.0",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "half"
|
||||
version = "2.7.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"crunchy",
|
||||
"num-traits",
|
||||
"zerocopy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.14.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.17.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc"
|
||||
|
||||
[[package]]
|
||||
name = "iana-time-zone"
|
||||
version = "0.1.65"
|
||||
|
|
@ -339,6 +415,16 @@ version = "1.0.19"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
|
||||
|
||||
[[package]]
|
||||
name = "jobserver"
|
||||
version = "0.1.35"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"
|
||||
dependencies = [
|
||||
"getrandom 0.4.3",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "js-sys"
|
||||
version = "0.3.107"
|
||||
|
|
@ -556,6 +642,16 @@ dependencies = [
|
|||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-bigint"
|
||||
version = "0.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "93e7820bc0a80a0238e650327316f929ba18d5be054b647490a3a6a339f3e7c0"
|
||||
dependencies = [
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-complex"
|
||||
version = "0.4.6"
|
||||
|
|
@ -580,7 +676,7 @@ version = "0.4.2"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
|
||||
dependencies = [
|
||||
"num-bigint",
|
||||
"num-bigint 0.4.6",
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
]
|
||||
|
|
@ -624,6 +720,25 @@ dependencies = [
|
|||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "parquet"
|
||||
version = "60.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6701f0dd63f5ee23a0f1f2865ff76825c301759d6ab649e3e5686cc32d066957"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytes",
|
||||
"chrono",
|
||||
"half",
|
||||
"hashbrown 0.17.2",
|
||||
"num-bigint 0.5.1",
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
"seq-macro",
|
||||
"twox-hash",
|
||||
"zstd",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "paste"
|
||||
version = "1.0.15"
|
||||
|
|
@ -636,6 +751,12 @@ version = "0.2.18"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752"
|
||||
|
||||
[[package]]
|
||||
name = "pkg-config"
|
||||
version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
|
||||
|
||||
[[package]]
|
||||
name = "ppv-lite86"
|
||||
version = "0.2.21"
|
||||
|
|
@ -669,6 +790,12 @@ version = "5.3.0"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
|
||||
|
||||
[[package]]
|
||||
name = "r-efi"
|
||||
version = "6.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
|
||||
|
||||
[[package]]
|
||||
name = "rand"
|
||||
version = "0.8.8"
|
||||
|
|
@ -790,6 +917,12 @@ version = "1.0.28"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
|
||||
|
||||
[[package]]
|
||||
name = "seq-macro"
|
||||
version = "0.3.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1bc711410fbe7399f390ca1c3b60ad0f53f80e95c5eb935e52268a0e2cd49acc"
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.229"
|
||||
|
|
@ -981,6 +1114,15 @@ dependencies = [
|
|||
"cfg-if",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tiny-keccak"
|
||||
version = "2.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237"
|
||||
dependencies = [
|
||||
"crunchy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tokio"
|
||||
version = "1.54.1"
|
||||
|
|
@ -1066,6 +1208,12 @@ dependencies = [
|
|||
"tracing-log",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "twox-hash"
|
||||
version = "2.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "86a801b3cea342a06d468c8710662aa29e5e05e4f5c0d62f00bbb7f2ad7941c2"
|
||||
|
||||
[[package]]
|
||||
name = "typenum"
|
||||
version = "1.20.1"
|
||||
|
|
@ -1102,6 +1250,12 @@ version = "0.1.1"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
|
||||
|
||||
[[package]]
|
||||
name = "version_check"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
||||
|
||||
[[package]]
|
||||
name = "wasi"
|
||||
version = "0.11.1+wasi-snapshot-preview1"
|
||||
|
|
@ -1270,3 +1424,31 @@ name = "zmij"
|
|||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
||||
|
||||
[[package]]
|
||||
name = "zstd"
|
||||
version = "0.14.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "465cb081cac3a28a84ef547702dba1fe0f4a9f22e4e57a0b675ceee028c2af80"
|
||||
dependencies = [
|
||||
"zstd-safe",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zstd-safe"
|
||||
version = "8.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9b09bddd92c53b91833f4df03e0ea07e02d8367cfcd15a3b9acda94fc273f793"
|
||||
dependencies = [
|
||||
"zstd-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zstd-sys"
|
||||
version = "2.2.0+zstd.1.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c3f4089cda6dda4dc43c43dd9f8964140064fd2f752f3da46c3a483c3c175160"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"pkg-config",
|
||||
]
|
||||
|
|
|
|||
|
|
@ -6,3 +6,5 @@ authors.workspace = true
|
|||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
parquet = { version = "=60.2.0", default-features = false, features = ["zstd"] }
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# `curate-etl`
|
||||
|
||||
Dedicated zero-dependency Rust crate for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, the `M1.2c` pure `corporate_actions` event-log builder, 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, and the `M1.2h` pure in-RAM `provider_mapping` `(source, source_id, bar_date) -> listing_id` lookup table.
|
||||
Dedicated Rust crate (single direct dependency: `parquet` with `default-features = false, features = ["zstd"]`) for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, the `M1.2c` pure `corporate_actions` event-log builder, the `M1.2d` pure `bars_1d` daily bar builder + `qmPrices.sharevolume` cross-check, the `M1.2e` pure `fx_1d` USD/CAD builder + carry-forward lookup, the `M1.2f` pure `shorts` (`ceoShorts`) point-in-time builder + Canadian TSX business-day / `America/Toronto` DST calendar, the `M1.2g` pure `events` (`qmFilings` + `qmEarnings`) point-in-time builder, the `M1.2h` pure in-RAM `provider_mapping` `(source, source_id, bar_date) -> listing_id` lookup table, and the `M1.2i` streaming Zstd Parquet writer for `bars_1d`.
|
||||
|
||||
## Scope & Sign Conventions
|
||||
|
||||
|
|
@ -176,6 +176,42 @@ Rules:
|
|||
- `resolve(source, source_id, bar_date)` and `ranges_for(source, source_id)` perform zero heap allocations: all `MappingRange`s live in a single contiguous `Vec<MappingRange>` arena indexed by a sorted per-source `HashMap<String, (usize, usize)>` (linear scan for `<= 8` sources, binary search otherwise) plus binary search over the key's ranges.
|
||||
- `ProviderMappingCursor` (via `cursor_for(source, source_id)` or `ProviderMappingCursor::new(ranges)`) resolves ascending `bar_date` streams for a single key in amortised O(1), automatically falling back to binary search on out-of-order probes so its output always matches `ProviderMappingTable::resolve` identically.
|
||||
|
||||
## `bars_1d` Parquet Writer (`M1.2i`)
|
||||
|
||||
`write_bars_1d_dataset` (`src/parquet_bars.rs`) streams strictly ascending `(listing_id, session_date)` `Bars1dParquetRow` records into Zstd-compressed, year-partitioned Parquet files matching `design/DATA-CONTRACTS.md` (§3A).
|
||||
|
||||
1. **Exact 12-column contract schema (`bars_1d_parquet_schema`):**
|
||||
- `listing_id` (`INT32`, `REQUIRED`)
|
||||
- `ts` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`)
|
||||
- `session_date` (`INT32`, `REQUIRED`, `DATE`)
|
||||
- `open`, `high`, `low`, `close`, `volume` (`DOUBLE`, `REQUIRED`)
|
||||
- `vwap` (`DOUBLE`, `OPTIONAL`)
|
||||
- `currency`, `source` (`BYTE_ARRAY`, `REQUIRED`, `STRING`, dictionary-encoded)
|
||||
- `known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`)
|
||||
2. **Partition layout & compression:**
|
||||
- Writes `<out_dir>/bars_1d/year=YYYY/part.parquet` lazily per observed `session_date` calendar year (`1900..=2200`); empty input and empty years create no directories or files.
|
||||
- Zstd compression on every column chunk (`DEFAULT_ZSTD_LEVEL = 3`, configurable via `Bars1dWriteOptions::zstd_level`).
|
||||
- Bounded streaming buffers (`DEFAULT_ROW_GROUP_ROWS = 1_000_000`, configurable via `Bars1dWriteOptions::row_group_rows`): each active year buffers at most one row group of columnar data (with string interning for `currency`/`source`), flushing and clearing buffers on every row-group boundary.
|
||||
- Deterministic `created_by` metadata so identical inputs produce byte-identical `part.parquet` files.
|
||||
3. **Sort, concurrency & atomicity rules:**
|
||||
- Input must already be sorted strictly ascending by `(listing_id, session_date)`; within each year file rows remain in `(listing_id, session_date)` order.
|
||||
- Concurrent writers targeting the same `<out_dir>/bars_1d` directory are serialized via an in-process per-dataset mutex and a bounded-wait exclusive `.write.lock` file (30 s default timeout returning `ParquetBarsError::LockTimeout` with the lock path if a crashed process left a stale lock behind). Every year partition writes to an exclusively created per-run staging file (`part.parquet.<run>.tmp`), flushes, and calls `File::sync_all()` before publication. During publication, pre-existing `part.parquet` files are backed up in place (hard link with exclusive copy fallback) so the live path remains readable until replaced by a single atomic `rename`; on any error, all open writers are dropped, replaced partitions are restored from backup, newly published partitions are removed (reporting any rollback failures alongside the original error via `RollbackFailed`), and only staging files owned by the current run are unlinked.
|
||||
4. **Typed errors (`ParquetBarsError`):**
|
||||
- `InvalidRowGroupRows` (`row_group_rows == 0`)
|
||||
- `InvalidZstdLevel { level }`
|
||||
- `UnsortedInput { prev_listing_id, prev_session_date, listing_id, session_date }`
|
||||
- `DuplicateKey { listing_id, session_date }`
|
||||
- `SessionYearOutOfRange { listing_id, session_date, year, min_year, max_year }`
|
||||
- `LockTimeout { path, waited }`
|
||||
- `RollbackFailed { cause, failures }`
|
||||
- `Io { path, source }`
|
||||
- `Parquet { path, source }`
|
||||
5. **Measured baseline (`2026-11-28`):**
|
||||
- Command: `cargo run --release -p curate-etl --offline -- bench-parquet-bars`
|
||||
- Input: `rows=5000000`, `listings=2000`, `raw_row_bytes=84` (20 years `2006..=2025`)
|
||||
- Output: `files=20`, `row_groups=20`, `bytes=231330139`, `read_back_rows=5000000`
|
||||
- Perf: `elapsed=1422.27 ms`, `throughput=3515517 rows/s`, `write=155.11 MB/s`, `size=46.27 bytes/row`, `compression=1.82x`
|
||||
|
||||
## Local Benchmarks
|
||||
|
||||
### `bench-split`
|
||||
|
|
@ -290,13 +326,27 @@ Command: `cargo run --release -p curate-etl --offline -- bench-provider-mapping`
|
|||
- Table: `keys=60000`, `ranges=68000`, `multi_range_keys=6000`, `build=17.45 ms`, `throughput=3896541 rows/s`
|
||||
- Lookup: `lookups=10000000`, `hits=9443294`, `misses=556706`, `elapsed=447.14 ms`, `throughput=22364140 lookups/s`, `latency=44.71 ns/lookup`, `checksum=0xad8536129cafb697` (identical across back-to-back runs)
|
||||
|
||||
### `bench-parquet-bars`
|
||||
|
||||
Fixed-seed (`std`-only SplitMix64) streaming Zstd Parquet write benchmark over `5,000,000` sorted `Bars1dParquetRow` rows across `2,000` listings and 20 years (`2006..=2025`), writing `bars_1d/year=YYYY/part.parquet` into a fresh temp directory under `std::env::temp_dir()`, verifying Parquet footer row counts across all 20 files, and deleting the temp directory:
|
||||
|
||||
```bash
|
||||
cargo run --release -p curate-etl --offline -- bench-parquet-bars [rows]
|
||||
```
|
||||
|
||||
Command (`2026-11-28`): `cargo run --release -p curate-etl --offline -- bench-parquet-bars`
|
||||
|
||||
- Input: `rows=5000000`, `listings=2000`, `raw_row_bytes=84`
|
||||
- Output: `files=20`, `row_groups=20`, `bytes=231330139`, `read_back_rows=5000000`
|
||||
- Perf: `elapsed=1422.27 ms`, `throughput=3515517 rows/s`, `write=155.11 MB/s`, `size=46.27 bytes/row`, `compression=1.82x`
|
||||
|
||||
## Deferred Follow-Ups (`M1.3+` / `M2`)
|
||||
|
||||
This crate currently uses `std` only so it builds strictly offline. Follow-up tasks (IO wiring and crates.io dependencies) will add:
|
||||
This crate currently depends only on `parquet` (Zstd-only, no Arrow/async) so all tests and benchmarks run strictly offline once the Cargo cache is populated. Follow-up tasks will add:
|
||||
|
||||
- `bars_1d` and `fx_1d` schema metadata columns (`ts`, `known_at`, `currency`, `source`, `vwap`) requiring exchange session/timezone and listing metadata
|
||||
- `CADUSD.FOREX` inversion, `fx_1m` intraday FX, and wiring `fx_1d` into `src/adj.rs` cross-currency dividends
|
||||
- `year=YYYY` partitioning, Zstd-compressed Parquet writer for curated daily/intraday datasets, and `qmPrices` OHLC cross-check
|
||||
- Zstd Parquet writers for the remaining curated tables (`adj_factors`, `corporate_actions`, `fx_1d`, `events`, `shorts`) and `qmPrices` OHLC cross-check
|
||||
- Read-only MongoDB `RawDocumentBuf` streaming cursors (`eodPrices`, `eodIntraday1M`, `qmSplits`)
|
||||
- PostgreSQL I/O preload into `ProviderMappingTable` and rewiring the builders to resolve `(source, source_id, bar_date) -> listing_id: i32`
|
||||
- `rayon` parallel sharding across symbol/date partitions
|
||||
|
|
|
|||
|
|
@ -1,8 +1,16 @@
|
|||
//! Fixed-seed, std-only benchmark for the split-factor lookup and un-adjustment hot loop.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::fs::{self, File};
|
||||
use std::hint::black_box;
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering};
|
||||
use std::time::Instant;
|
||||
|
||||
use parquet::errors::ParquetError;
|
||||
use parquet::file::reader::{FileReader, SerializedFileReader};
|
||||
|
||||
use crate::adj::{build_adj_factors, AdjBuildStats, AdjError, DividendEvent};
|
||||
use crate::bars::{build_bars_1d, Bars1dStats, BarsError, EodDailyBar, QmRawVolume};
|
||||
use crate::corporate_actions::{
|
||||
|
|
@ -11,6 +19,9 @@ use crate::corporate_actions::{
|
|||
};
|
||||
use crate::events::{build_events, EventsStats, QmEarning, QmFiling};
|
||||
use crate::fx::{build_fx_1d, fx_rate_on_or_before, Fx1dStats, FxDailyBar};
|
||||
use crate::parquet_bars::{
|
||||
write_bars_1d_dataset, Bars1dParquetRow, Bars1dWriteOptions, ParquetBarsError,
|
||||
};
|
||||
use crate::provider_mapping::{ProviderMappingError, ProviderMappingRow, ProviderMappingTable};
|
||||
use crate::shorts::{build_shorts, epoch_days_to_ymd, CeoShortReport, ShortsError, ShortsStats};
|
||||
use crate::split::{unadjust_volume, ymd_to_epoch_days, SplitError, SplitEvent, SplitTable};
|
||||
|
|
@ -24,10 +35,13 @@ pub const DEFAULT_FX_BENCH_LOOKUPS: usize = 1_000_000;
|
|||
pub const DEFAULT_SHORTS_BENCH_ROWS: usize = 700_000;
|
||||
pub const DEFAULT_EVENTS_BENCH_ROWS: usize = 500_000;
|
||||
pub const DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS: usize = 10_000_000;
|
||||
pub const DEFAULT_PARQUET_BARS_BENCH_ROWS: usize = 5_000_000;
|
||||
pub const PARQUET_BARS_RAW_ROW_BYTES: usize = 84;
|
||||
pub const BENCH_KEY_COUNT: usize = 20_000;
|
||||
pub const BENCH_EVENT_COUNT: usize = 19_000;
|
||||
pub const PROVIDER_MAPPING_BENCH_KEY_COUNT: usize = 60_000;
|
||||
const SHORTS_BENCH_KEY_COUNT: usize = 12_500;
|
||||
const PARQUET_BARS_BENCH_BASE_LISTINGS: usize = 2_000;
|
||||
|
||||
const BENCH_SEED: u64 = 0x570C_4B07_5171_7E57;
|
||||
const ADJ_BENCH_SEED: u64 = 0x570C_4B07_AD7F_AC70;
|
||||
|
|
@ -37,6 +51,7 @@ const FX_BENCH_SEED: u64 = 0x570C_4B07_F81D_CADE;
|
|||
const SHORTS_BENCH_SEED: u64 = 0x570C_4B07_5404_7500;
|
||||
const EVENTS_BENCH_SEED: u64 = 0x570C_4B07_E7E4_7500;
|
||||
const PROVIDER_MAPPING_BENCH_SEED: u64 = 0x570C_4B07_9407_1D00;
|
||||
const PARQUET_BARS_BENCH_SEED: u64 = 0x570C_4B07_9A49_BA45;
|
||||
const SAMPLE_RATIOS: [f64; 9] = [2.0, 3.0, 4.0, 5.0, 10.0, 0.5, 0.25, 0.1, 0.05];
|
||||
|
||||
/// Deterministic SplitMix64 generator (zero external dependencies).
|
||||
|
|
@ -1597,6 +1612,350 @@ pub fn run_provider_mapping_benchmark(
|
|||
})
|
||||
}
|
||||
|
||||
/// Summary metrics produced by [`run_parquet_bars_benchmark`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct ParquetBarsBenchReport {
|
||||
pub rows: usize,
|
||||
pub read_back_rows: usize,
|
||||
pub listing_count: usize,
|
||||
pub files_written: usize,
|
||||
pub row_groups_written: usize,
|
||||
pub bytes_written: u64,
|
||||
pub raw_row_bytes: usize,
|
||||
pub elapsed_ms: f64,
|
||||
pub rows_per_sec: f64,
|
||||
pub mb_per_sec: f64,
|
||||
pub bytes_per_row: f64,
|
||||
pub compression_ratio: f64,
|
||||
}
|
||||
|
||||
static BENCH_TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
struct BenchTempDir {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl BenchTempDir {
|
||||
fn new_in(base: &Path) -> Result<Self, ParquetBarsError> {
|
||||
let pid = std::process::id();
|
||||
for _ in 0..1024 {
|
||||
let seq = BENCH_TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed);
|
||||
let path = base.join(format!("curate-etl-bench-pq-bars-{pid}-{seq}"));
|
||||
match fs::create_dir(&path) {
|
||||
Ok(()) => return Ok(Self { path }),
|
||||
Err(err) if err.kind() == io::ErrorKind::AlreadyExists => continue,
|
||||
Err(source) => {
|
||||
return Err(ParquetBarsError::Io { path, source });
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(ParquetBarsError::Io {
|
||||
path: base.to_path_buf(),
|
||||
source: io::Error::new(
|
||||
io::ErrorKind::AlreadyExists,
|
||||
"exhausted unique benchmark temp directory names",
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
fn new() -> Result<Self, ParquetBarsError> {
|
||||
Self::new_in(&std::env::temp_dir())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for BenchTempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
struct ParquetBarsBenchIter {
|
||||
weekdays: Vec<i32>,
|
||||
listing_count: usize,
|
||||
base_per_listing: usize,
|
||||
rem_listings: usize,
|
||||
cur_listing: usize,
|
||||
cur_day_idx: usize,
|
||||
cur_listing_rows: usize,
|
||||
cur_close: f64,
|
||||
rng: SplitMix64,
|
||||
}
|
||||
|
||||
impl ParquetBarsBenchIter {
|
||||
fn new(rows: usize, weekdays: Vec<i32>) -> Self {
|
||||
let min_listings = if rows == 0 {
|
||||
PARQUET_BARS_BENCH_BASE_LISTINGS
|
||||
} else {
|
||||
rows.div_ceil(weekdays.len())
|
||||
.max(PARQUET_BARS_BENCH_BASE_LISTINGS)
|
||||
};
|
||||
let active_listings = rows.min(min_listings);
|
||||
let base_per_listing = if active_listings == 0 {
|
||||
0
|
||||
} else {
|
||||
rows / active_listings
|
||||
};
|
||||
let rem_listings = if active_listings == 0 {
|
||||
0
|
||||
} else {
|
||||
rows % active_listings
|
||||
};
|
||||
let mut iter = Self {
|
||||
weekdays,
|
||||
listing_count: active_listings,
|
||||
base_per_listing,
|
||||
rem_listings,
|
||||
cur_listing: 0,
|
||||
cur_day_idx: 0,
|
||||
cur_listing_rows: 0,
|
||||
cur_close: 50.0,
|
||||
rng: SplitMix64::new(PARQUET_BARS_BENCH_SEED),
|
||||
};
|
||||
if active_listings > 0 {
|
||||
iter.setup_listing(0);
|
||||
}
|
||||
iter
|
||||
}
|
||||
|
||||
fn setup_listing(&mut self, listing_idx: usize) {
|
||||
self.cur_listing = listing_idx;
|
||||
self.cur_day_idx = 0;
|
||||
self.cur_listing_rows =
|
||||
self.base_per_listing + usize::from(listing_idx < self.rem_listings);
|
||||
self.cur_close = 5.0 + ((self.rng.next_u64() % 25_000) as f64) * 0.01;
|
||||
}
|
||||
}
|
||||
|
||||
impl Iterator for ParquetBarsBenchIter {
|
||||
type Item = Bars1dParquetRow;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
if self.cur_listing >= self.listing_count {
|
||||
return None;
|
||||
}
|
||||
if self.cur_day_idx >= self.cur_listing_rows {
|
||||
let next_listing = self.cur_listing + 1;
|
||||
if next_listing >= self.listing_count {
|
||||
self.cur_listing = next_listing;
|
||||
return None;
|
||||
}
|
||||
self.setup_listing(next_listing);
|
||||
}
|
||||
|
||||
let listing_id = (self.cur_listing + 1) as i32;
|
||||
let w = self.weekdays.len();
|
||||
let n = self.cur_listing_rows;
|
||||
let date_pos = if n == 1 {
|
||||
(self.cur_listing.wrapping_mul(257)) % w
|
||||
} else {
|
||||
(self.cur_day_idx * w) / n
|
||||
};
|
||||
let session_date = self.weekdays[date_pos];
|
||||
self.cur_day_idx += 1;
|
||||
|
||||
let r1 = self.rng.next_u64();
|
||||
let r2 = self.rng.next_u64();
|
||||
|
||||
// Small realistic random walk in cents.
|
||||
let delta_bps = ((r1 & 0xFF) as i64) - 128;
|
||||
let next_close = (self.cur_close * (1.0 + (delta_bps as f64) * 0.0002)).clamp(0.5, 5_000.0);
|
||||
let open = self.cur_close;
|
||||
let spread = 0.005 + (((r1 >> 8) & 0x3F) as f64) * 0.0005;
|
||||
let high = open.max(next_close) * (1.0 + spread);
|
||||
let low = (open.min(next_close) * (1.0 - spread)).max(0.01);
|
||||
self.cur_close = next_close;
|
||||
|
||||
let volume = ((r2 & 0x3F_FFFF) + 100) as f64;
|
||||
let vwap = if (r2 >> 22) & 0x3 == 0 {
|
||||
None
|
||||
} else {
|
||||
Some((open + high + low + next_close) * 0.25)
|
||||
};
|
||||
let currency = if listing_id % 5 == 0 {
|
||||
Cow::Borrowed("CAD")
|
||||
} else {
|
||||
Cow::Borrowed("USD")
|
||||
};
|
||||
let source = Cow::Borrowed("eod_unadj");
|
||||
let ts_micros = i64::from(session_date) * 86_400_000_000 + 21 * 3_600_000_000;
|
||||
let known_at_micros = ts_micros + 900_000_000;
|
||||
|
||||
Some(Bars1dParquetRow {
|
||||
listing_id,
|
||||
ts_micros,
|
||||
session_date,
|
||||
open,
|
||||
high,
|
||||
low,
|
||||
close: next_close,
|
||||
volume,
|
||||
vwap,
|
||||
currency,
|
||||
source,
|
||||
known_at_micros,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_bench_weekdays_2006_2025() -> Vec<i32> {
|
||||
let start = ymd_to_epoch_days(2006, 1, 2).expect("valid start date");
|
||||
let end = ymd_to_epoch_days(2025, 12, 31).expect("valid end date");
|
||||
let mut days = Vec::with_capacity(5_300);
|
||||
let mut d = start;
|
||||
while d <= end {
|
||||
let dow = (d + 4).rem_euclid(7);
|
||||
if (1..=5).contains(&dow) {
|
||||
days.push(d);
|
||||
}
|
||||
d += 1;
|
||||
}
|
||||
days
|
||||
}
|
||||
|
||||
fn verify_parquet_bars_row_count(
|
||||
out_dir: &Path,
|
||||
years: impl IntoIterator<Item = i32>,
|
||||
expected_rows: usize,
|
||||
) -> Result<usize, ParquetBarsError> {
|
||||
let mut read_back_rows = 0usize;
|
||||
for year in years {
|
||||
let path = out_dir.join(format!("bars_1d/year={year:04}/part.parquet"));
|
||||
let file = File::open(&path).map_err(|source| ParquetBarsError::Io {
|
||||
path: path.clone(),
|
||||
source,
|
||||
})?;
|
||||
let reader = SerializedFileReader::new(file).map_err(|source| {
|
||||
ParquetBarsError::Parquet {
|
||||
path: path.clone(),
|
||||
source,
|
||||
}
|
||||
})?;
|
||||
let file_rows = usize::try_from(reader.metadata().file_metadata().num_rows()).map_err(
|
||||
|_| ParquetBarsError::Parquet {
|
||||
path: path.clone(),
|
||||
source: ParquetError::General(format!(
|
||||
"negative or overflowing Parquet footer row count: {}",
|
||||
reader.metadata().file_metadata().num_rows()
|
||||
)),
|
||||
},
|
||||
)?;
|
||||
read_back_rows = read_back_rows.checked_add(file_rows).ok_or_else(|| {
|
||||
ParquetBarsError::Parquet {
|
||||
path: path.clone(),
|
||||
source: ParquetError::General("read-back row count overflow".to_string()),
|
||||
}
|
||||
})?;
|
||||
}
|
||||
|
||||
if read_back_rows != expected_rows {
|
||||
return Err(ParquetBarsError::Parquet {
|
||||
path: out_dir.join("bars_1d"),
|
||||
source: ParquetError::General(format!(
|
||||
"parquet row count mismatch: expected {expected_rows}, read back {read_back_rows}"
|
||||
)),
|
||||
});
|
||||
}
|
||||
|
||||
Ok(read_back_rows)
|
||||
}
|
||||
|
||||
fn run_parquet_bars_benchmark_tracked(
|
||||
rows: usize,
|
||||
) -> Result<(ParquetBarsBenchReport, PathBuf), ParquetBarsError> {
|
||||
let temp = BenchTempDir::new()?;
|
||||
let temp_path = temp.path.clone();
|
||||
|
||||
if rows == 0 {
|
||||
let stats = write_bars_1d_dataset(
|
||||
&temp.path,
|
||||
std::iter::empty::<Bars1dParquetRow>(),
|
||||
Bars1dWriteOptions::default(),
|
||||
)?;
|
||||
let read_back_rows =
|
||||
verify_parquet_bars_row_count(&temp.path, stats.rows_by_year.keys().copied(), 0)?;
|
||||
let report = ParquetBarsBenchReport {
|
||||
rows: 0,
|
||||
read_back_rows,
|
||||
listing_count: 0,
|
||||
files_written: stats.files_written,
|
||||
row_groups_written: stats.row_groups_written,
|
||||
bytes_written: stats.bytes_written,
|
||||
raw_row_bytes: PARQUET_BARS_RAW_ROW_BYTES,
|
||||
elapsed_ms: 0.0,
|
||||
rows_per_sec: 0.0,
|
||||
mb_per_sec: 0.0,
|
||||
bytes_per_row: 0.0,
|
||||
compression_ratio: 0.0,
|
||||
};
|
||||
drop(temp);
|
||||
return Ok((report, temp_path));
|
||||
}
|
||||
|
||||
let weekdays = collect_bench_weekdays_2006_2025();
|
||||
let iter = ParquetBarsBenchIter::new(rows, weekdays);
|
||||
let listing_count = iter.listing_count;
|
||||
|
||||
let start = Instant::now();
|
||||
let stats = write_bars_1d_dataset(&temp.path, iter, Bars1dWriteOptions::default())?;
|
||||
let elapsed_secs = start.elapsed().as_secs_f64();
|
||||
let elapsed_ms = elapsed_secs * 1_000.0;
|
||||
|
||||
if stats.rows_written != rows {
|
||||
return Err(ParquetBarsError::Parquet {
|
||||
path: temp.path.join("bars_1d"),
|
||||
source: ParquetError::General(format!(
|
||||
"writer row count mismatch: expected {rows}, stats reported {}",
|
||||
stats.rows_written
|
||||
)),
|
||||
});
|
||||
}
|
||||
|
||||
let read_back_rows =
|
||||
verify_parquet_bars_row_count(&temp.path, stats.rows_by_year.keys().copied(), rows)?;
|
||||
|
||||
let (rows_per_sec, _) = compute_rates(rows, elapsed_secs);
|
||||
let mb_per_sec = if elapsed_secs > 0.0 && elapsed_secs.is_finite() {
|
||||
(stats.bytes_written as f64 / (1024.0 * 1024.0)) / elapsed_secs
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let bytes_per_row = stats.bytes_written as f64 / rows as f64;
|
||||
let raw_bytes = (rows as f64) * (PARQUET_BARS_RAW_ROW_BYTES as f64);
|
||||
let compression_ratio = if stats.bytes_written > 0 {
|
||||
raw_bytes / (stats.bytes_written as f64)
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
drop(temp);
|
||||
|
||||
Ok((
|
||||
ParquetBarsBenchReport {
|
||||
rows,
|
||||
read_back_rows,
|
||||
listing_count,
|
||||
files_written: stats.files_written,
|
||||
row_groups_written: stats.row_groups_written,
|
||||
bytes_written: stats.bytes_written,
|
||||
raw_row_bytes: PARQUET_BARS_RAW_ROW_BYTES,
|
||||
elapsed_ms,
|
||||
rows_per_sec,
|
||||
mb_per_sec,
|
||||
bytes_per_row,
|
||||
compression_ratio,
|
||||
},
|
||||
temp_path,
|
||||
))
|
||||
}
|
||||
|
||||
/// Runs the fixed-seed Zstd Parquet `bars_1d` writer benchmark for `rows` sorted daily bars
|
||||
/// spanning `2006..=2025` across `>= 2,000` listings, reads back Parquet footer row counts,
|
||||
/// and deletes its temporary output directory.
|
||||
pub fn run_parquet_bars_benchmark(rows: usize) -> Result<ParquetBarsBenchReport, ParquetBarsError> {
|
||||
let (report, _) = run_parquet_bars_benchmark_tracked(rows)?;
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
|
@ -1931,4 +2290,104 @@ mod tests {
|
|||
assert_eq!(report.ns_per_lookup, 0.0);
|
||||
assert_eq!(report.checksum, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parquet_bars_benchmark_small_run_is_deterministic_and_cleans_up() {
|
||||
let (a, dir_a) = run_parquet_bars_benchmark_tracked(10_000).unwrap();
|
||||
let (b, dir_b) = run_parquet_bars_benchmark_tracked(10_000).unwrap();
|
||||
|
||||
assert!(!dir_a.exists(), "temp dir {} should be removed", dir_a.display());
|
||||
assert!(!dir_b.exists(), "temp dir {} should be removed", dir_b.display());
|
||||
assert_eq!(a.rows, 10_000);
|
||||
assert_eq!(a.read_back_rows, 10_000);
|
||||
assert_eq!(a.listing_count, PARQUET_BARS_BENCH_BASE_LISTINGS);
|
||||
assert_eq!(a.files_written, b.files_written);
|
||||
assert!(a.files_written >= 2);
|
||||
assert_eq!(a.row_groups_written, b.row_groups_written);
|
||||
assert_eq!(a.bytes_written, b.bytes_written);
|
||||
assert!(a.bytes_written > 0);
|
||||
assert_eq!(a.raw_row_bytes, PARQUET_BARS_RAW_ROW_BYTES);
|
||||
assert!(a.rows_per_sec.is_finite() && a.rows_per_sec >= 0.0);
|
||||
assert!(a.mb_per_sec.is_finite() && a.mb_per_sec >= 0.0);
|
||||
assert!(a.bytes_per_row.is_finite() && a.bytes_per_row > 0.0);
|
||||
assert!(a.compression_ratio.is_finite() && a.compression_ratio > 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parquet_bars_benchmark_zero_rows_handles_cleanly() {
|
||||
let (report, dir) = run_parquet_bars_benchmark_tracked(0).unwrap();
|
||||
assert!(!dir.exists(), "temp dir {} should be removed", dir.display());
|
||||
assert_eq!(report.rows, 0);
|
||||
assert_eq!(report.read_back_rows, 0);
|
||||
assert_eq!(report.listing_count, 0);
|
||||
assert_eq!(report.files_written, 0);
|
||||
assert_eq!(report.row_groups_written, 0);
|
||||
assert_eq!(report.bytes_written, 0);
|
||||
assert_eq!(report.raw_row_bytes, PARQUET_BARS_RAW_ROW_BYTES);
|
||||
assert_eq!(report.elapsed_ms, 0.0);
|
||||
assert_eq!(report.rows_per_sec, 0.0);
|
||||
assert_eq!(report.mb_per_sec, 0.0);
|
||||
assert_eq!(report.bytes_per_row, 0.0);
|
||||
assert_eq!(report.compression_ratio, 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verify_parquet_bars_row_count_returns_error_on_mismatch() {
|
||||
let temp = BenchTempDir::new().unwrap();
|
||||
let weekdays = collect_bench_weekdays_2006_2025();
|
||||
let iter = ParquetBarsBenchIter::new(250, weekdays);
|
||||
let stats =
|
||||
write_bars_1d_dataset(&temp.path, iter, Bars1dWriteOptions::default()).unwrap();
|
||||
|
||||
let matched =
|
||||
verify_parquet_bars_row_count(&temp.path, stats.rows_by_year.keys().copied(), 250)
|
||||
.unwrap();
|
||||
assert_eq!(matched, 250);
|
||||
|
||||
let err =
|
||||
verify_parquet_bars_row_count(&temp.path, stats.rows_by_year.keys().copied(), 255)
|
||||
.unwrap_err();
|
||||
let msg = err.to_string();
|
||||
assert!(
|
||||
matches!(err, ParquetBarsError::Parquet { .. }),
|
||||
"expected Parquet error, got {err:?}"
|
||||
);
|
||||
assert!(
|
||||
msg.contains("255") && msg.contains("250"),
|
||||
"error must report expected (255) and actual (250) row counts, got: {msg}"
|
||||
);
|
||||
|
||||
let err_zero = verify_parquet_bars_row_count(&temp.path, std::iter::empty(), 10)
|
||||
.unwrap_err();
|
||||
let msg_zero = err_zero.to_string();
|
||||
assert!(
|
||||
msg_zero.contains("10") && msg_zero.contains('0'),
|
||||
"error must report expected (10) and actual (0) row counts, got: {msg_zero}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bench_temp_dir_retries_on_collision_and_preserves_existing_dir() {
|
||||
let root = BenchTempDir::new().unwrap();
|
||||
let pid = std::process::id();
|
||||
let next_seq = BENCH_TEMP_DIR_SEQ.load(AtomicOrdering::Relaxed);
|
||||
let colliding = root
|
||||
.path
|
||||
.join(format!("curate-etl-bench-pq-bars-{pid}-{next_seq}"));
|
||||
fs::create_dir(&colliding).unwrap();
|
||||
let sentinel = colliding.join("keep.txt");
|
||||
fs::write(&sentinel, b"do-not-delete").unwrap();
|
||||
|
||||
let created_path = {
|
||||
let dir = BenchTempDir::new_in(&root.path).unwrap();
|
||||
assert_ne!(dir.path, colliding);
|
||||
assert!(dir.path.is_dir());
|
||||
assert_eq!(fs::read(&sentinel).unwrap(), b"do-not-delete");
|
||||
dir.path.clone()
|
||||
};
|
||||
|
||||
assert!(!created_path.exists());
|
||||
assert!(colliding.is_dir());
|
||||
assert_eq!(fs::read(&sentinel).unwrap(), b"do-not-delete");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,7 +6,8 @@
|
|||
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_PROVIDER_MAPPING_BENCH_LOOKUPS, DEFAULT_SHORTS_BENCH_ROWS,
|
||||
DEFAULT_PARQUET_BARS_BENCH_ROWS, DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS,
|
||||
DEFAULT_SHORTS_BENCH_ROWS,
|
||||
};
|
||||
|
||||
/// Parsed CLI command to execute.
|
||||
|
|
@ -22,6 +23,7 @@ pub enum CliAction {
|
|||
BenchShorts(usize),
|
||||
BenchEvents(usize),
|
||||
BenchProviderMapping(usize),
|
||||
BenchParquetBars(usize),
|
||||
}
|
||||
|
||||
/// Formats full help text including binary name and version.
|
||||
|
|
@ -39,7 +41,8 @@ pub fn format_usage(name: &str, version: &str) -> String {
|
|||
{name} bench-fx [rows] Run fixed-seed fx_1d build + lookup benchmark (default: {DEFAULT_FX_BENCH_ROWS})\n\
|
||||
{name} bench-shorts [rows] Run fixed-seed shorts build benchmark (default: {DEFAULT_SHORTS_BENCH_ROWS})\n\
|
||||
{name} bench-events [rows] Run fixed-seed events build benchmark (default: {DEFAULT_EVENTS_BENCH_ROWS})\n\
|
||||
{name} bench-provider-mapping [lookups] Run fixed-seed provider_mapping build + lookup benchmark (default: {DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS})"
|
||||
{name} bench-provider-mapping [lookups] Run fixed-seed provider_mapping build + lookup benchmark (default: {DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS})\n\
|
||||
{name} bench-parquet-bars [rows] Run fixed-seed bars_1d Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_BARS_BENCH_ROWS})"
|
||||
)
|
||||
}
|
||||
|
||||
|
|
@ -56,7 +59,8 @@ pub fn format_usage_stderr(name: &str) -> String {
|
|||
{name} bench-fx [rows]\n\
|
||||
{name} bench-shorts [rows]\n\
|
||||
{name} bench-events [rows]\n\
|
||||
{name} bench-provider-mapping [lookups]"
|
||||
{name} bench-provider-mapping [lookups]\n\
|
||||
{name} bench-parquet-bars [rows]"
|
||||
)
|
||||
}
|
||||
|
||||
|
|
@ -141,6 +145,18 @@ pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
|||
["bench-provider-mapping", _, ..] => {
|
||||
Err("too many arguments for bench-provider-mapping".to_string())
|
||||
}
|
||||
["bench-parquet-bars"] => Ok(CliAction::BenchParquetBars(
|
||||
DEFAULT_PARQUET_BARS_BENCH_ROWS,
|
||||
)),
|
||||
["bench-parquet-bars", raw] => match raw.parse::<usize>() {
|
||||
Ok(n) if n > 0 => Ok(CliAction::BenchParquetBars(n)),
|
||||
_ => Err(format!(
|
||||
"invalid row count '{raw}' (expected a positive integer)"
|
||||
)),
|
||||
},
|
||||
["bench-parquet-bars", _, ..] => {
|
||||
Err("too many arguments for bench-parquet-bars".to_string())
|
||||
}
|
||||
[other, ..] => Err(format!("unknown argument '{other}'")),
|
||||
}
|
||||
}
|
||||
|
|
@ -308,6 +324,22 @@ mod tests {
|
|||
assert!(parse_args(&to_args(&["bench-provider-mapping", "10", "20"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_and_validates_bench_parquet_bars_args() {
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&["bench-parquet-bars"])),
|
||||
Ok(CliAction::BenchParquetBars(DEFAULT_PARQUET_BARS_BENCH_ROWS))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&["bench-parquet-bars", "250000"])),
|
||||
Ok(CliAction::BenchParquetBars(250_000))
|
||||
);
|
||||
assert!(parse_args(&to_args(&["bench-parquet-bars", "0"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-parquet-bars", "-5"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-parquet-bars", "abc"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-parquet-bars", "10", "20"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usage_strings_mention_all_benchmarks() {
|
||||
let full = format_usage("curate-etl", "0.1.0");
|
||||
|
|
@ -319,6 +351,7 @@ mod tests {
|
|||
assert!(full.contains("bench-shorts"));
|
||||
assert!(full.contains("bench-events"));
|
||||
assert!(full.contains("bench-provider-mapping"));
|
||||
assert!(full.contains("bench-parquet-bars"));
|
||||
|
||||
let short = format_usage_stderr("curate-etl");
|
||||
assert!(short.contains("bench-split"));
|
||||
|
|
@ -329,5 +362,6 @@ mod tests {
|
|||
assert!(short.contains("bench-shorts"));
|
||||
assert!(short.contains("bench-events"));
|
||||
assert!(short.contains("bench-provider-mapping"));
|
||||
assert!(short.contains("bench-parquet-bars"));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ pub mod cli;
|
|||
pub mod corporate_actions;
|
||||
pub mod events;
|
||||
pub mod fx;
|
||||
pub mod parquet_bars;
|
||||
pub mod provider_mapping;
|
||||
pub mod shorts;
|
||||
pub mod split;
|
||||
|
|
@ -36,6 +37,11 @@ pub use fx::{
|
|||
build_fx_1d, fx_rate_on_or_before, Fx1dBuild, Fx1dRow, Fx1dStats, FxDailyBar, FxSource,
|
||||
FxSourceStats, FX_OVERLAP_REL_TOLERANCE, FX_PAIR_USDCAD,
|
||||
};
|
||||
pub use parquet_bars::{
|
||||
bars_1d_parquet_schema, write_bars_1d_dataset, Bars1dParquetRow, Bars1dWriteOptions,
|
||||
Bars1dWriteStats, ParquetBarsError, RollbackFailure, DEFAULT_ROW_GROUP_ROWS,
|
||||
DEFAULT_ZSTD_LEVEL, MAX_PARQUET_YEAR, MIN_PARQUET_YEAR,
|
||||
};
|
||||
pub use provider_mapping::{
|
||||
MappingRange, ProviderMappingCursor, ProviderMappingError, ProviderMappingRow,
|
||||
ProviderMappingTable,
|
||||
|
|
|
|||
|
|
@ -5,7 +5,8 @@ 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_provider_mapping_benchmark, run_shorts_benchmark, run_split_benchmark,
|
||||
run_fx_benchmark, run_parquet_bars_benchmark, run_provider_mapping_benchmark,
|
||||
run_shorts_benchmark, run_split_benchmark,
|
||||
};
|
||||
use curate_etl::cli::{format_usage, format_usage_stderr, parse_args, CliAction};
|
||||
|
||||
|
|
@ -294,6 +295,36 @@ fn main() -> ExitCode {
|
|||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchParquetBars(rows)) => {
|
||||
let report = match run_parquet_bars_benchmark(rows) {
|
||||
Ok(report) => report,
|
||||
Err(err) => {
|
||||
eprintln!("error: parquet bars benchmark failed: {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
println!("curate-etl bench-parquet-bars");
|
||||
println!(
|
||||
" input: rows={} listings={} raw_row_bytes={}",
|
||||
report.rows, report.listing_count, report.raw_row_bytes
|
||||
);
|
||||
println!(
|
||||
" output: files={} row_groups={} bytes={} read_back_rows={}",
|
||||
report.files_written,
|
||||
report.row_groups_written,
|
||||
report.bytes_written,
|
||||
report.read_back_rows
|
||||
);
|
||||
println!(
|
||||
" perf: elapsed={:.2} ms throughput={:.0} rows/s write={:.2} MB/s size={:.2} bytes/row compression={:.2}x",
|
||||
report.elapsed_ms,
|
||||
report.rows_per_sec,
|
||||
report.mb_per_sec,
|
||||
report.bytes_per_row,
|
||||
report.compression_ratio
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(msg) => {
|
||||
eprintln!("error: {msg}");
|
||||
eprintln!("{}", format_usage_stderr(NAME));
|
||||
|
|
|
|||
2386
tools/curate-etl/src/parquet_bars.rs
Normal file
2386
tools/curate-etl/src/parquet_bars.rs
Normal file
File diff suppressed because it is too large
Load diff
886
tools/curate-etl/src/parquet_bars_tests.rs
Normal file
886
tools/curate-etl/src/parquet_bars_tests.rs
Normal file
|
|
@ -0,0 +1,886 @@
|
|||
use std::borrow::Cow;
|
||||
use std::fs::{self, File};
|
||||
use std::time::Duration;
|
||||
|
||||
use parquet::basic::Encoding;
|
||||
use parquet::file::reader::{FileReader, SerializedFileReader};
|
||||
|
||||
use super::tests::{
|
||||
assert_no_transient_files, assert_row_bitwise_eq, make_row, read_parquet_rows, TempDirGuard,
|
||||
};
|
||||
use super::{
|
||||
write_bars_1d_dataset, write_bars_1d_dataset_with_hooks, Bars1dParquetRow, Bars1dWriteOptions,
|
||||
ParquetBarsError, MAX_PARQUET_YEAR, MIN_PARQUET_YEAR,
|
||||
};
|
||||
use crate::split::ymd_to_epoch_days;
|
||||
|
||||
#[test]
|
||||
fn year_bounds_accept_1900_pre_1970_and_2200_bitwise() {
|
||||
let tmp = TempDirGuard::new("year-bounds-ok");
|
||||
let rows = vec![
|
||||
make_row(1, 1900, 1, 1, 10.5, 100.0, Some(10.25), "USD", "eod_unadj"),
|
||||
make_row(1, 1969, 12, 31, 20.0, 200.0, None, "USD", "eod_unadj"),
|
||||
make_row(1, 2200, 12, 31, 30.75, 300.0, Some(30.5), "CAD", "eod_unadj"),
|
||||
];
|
||||
assert!(rows[0].session_date < 0);
|
||||
assert!(rows[1].session_date < 0);
|
||||
|
||||
let stats =
|
||||
write_bars_1d_dataset(tmp.path(), &rows, Bars1dWriteOptions::default()).unwrap();
|
||||
assert_eq!(stats.rows_written, 3);
|
||||
assert_eq!(stats.files_written, 3);
|
||||
|
||||
for (year, expected) in [(1900, &rows[0]), (1969, &rows[1]), (2200, &rows[2])] {
|
||||
let path = tmp.path().join(format!("bars_1d/year={year}/part.parquet"));
|
||||
let actual = read_parquet_rows(&path);
|
||||
assert_eq!(actual.len(), 1);
|
||||
assert_row_bitwise_eq(&actual[0], expected);
|
||||
}
|
||||
assert_no_transient_files(&tmp.path().join("bars_1d"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_row_year_1899_rejected_before_creating_partition_files() {
|
||||
let tmp = TempDirGuard::new("year-1899-reject");
|
||||
let rows = vec![make_row(
|
||||
1,
|
||||
1899,
|
||||
12,
|
||||
31,
|
||||
10.0,
|
||||
100.0,
|
||||
None,
|
||||
"USD",
|
||||
"eod_unadj",
|
||||
)];
|
||||
|
||||
let err =
|
||||
write_bars_1d_dataset(tmp.path(), &rows, Bars1dWriteOptions::default()).unwrap_err();
|
||||
assert!(
|
||||
matches!(
|
||||
err,
|
||||
ParquetBarsError::SessionYearOutOfRange {
|
||||
listing_id: 1,
|
||||
year: 1899,
|
||||
min_year: MIN_PARQUET_YEAR,
|
||||
max_year: MAX_PARQUET_YEAR,
|
||||
..
|
||||
}
|
||||
),
|
||||
"expected SessionYearOutOfRange for 1899, got {err:?}"
|
||||
);
|
||||
|
||||
let bars_dir = tmp.path().join("bars_1d");
|
||||
assert!(!bars_dir.join("year=1899").exists());
|
||||
assert_no_transient_files(&bars_dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zstd_level_boundaries_accept_1_and_22_and_reject_23_without_disk_writes() {
|
||||
let tmp = TempDirGuard::new("zstd-bounds");
|
||||
let rows = vec![make_row(
|
||||
1,
|
||||
2024,
|
||||
3,
|
||||
15,
|
||||
100.0,
|
||||
5_000.0,
|
||||
Some(99.75),
|
||||
"USD",
|
||||
"eod_unadj",
|
||||
)];
|
||||
|
||||
let out_bad = tmp.path().join("bad-23");
|
||||
let err = write_bars_1d_dataset(
|
||||
&out_bad,
|
||||
&rows,
|
||||
Bars1dWriteOptions {
|
||||
zstd_level: 23,
|
||||
..Bars1dWriteOptions::default()
|
||||
},
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, ParquetBarsError::InvalidZstdLevel { level: 23 }));
|
||||
assert!(!out_bad.exists(), "invalid option must not create output dir");
|
||||
|
||||
for level in [1, 22] {
|
||||
let out_ok = tmp.path().join(format!("lvl-{level}"));
|
||||
let stats = write_bars_1d_dataset(
|
||||
&out_ok,
|
||||
&rows,
|
||||
Bars1dWriteOptions {
|
||||
zstd_level: level,
|
||||
..Bars1dWriteOptions::default()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(stats.rows_written, 1);
|
||||
let actual = read_parquet_rows(&out_ok.join("bars_1d/year=2024/part.parquet"));
|
||||
assert_eq!(actual.len(), 1);
|
||||
assert_row_bitwise_eq(&actual[0], &rows[0]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn different_zstd_levels_change_file_bytes_but_preserve_values() {
|
||||
let tmp = TempDirGuard::new("zstd-diff-levels");
|
||||
let mut rows = Vec::with_capacity(200);
|
||||
let base_day = ymd_to_epoch_days(2024, 1, 2).unwrap();
|
||||
for i in 0..200_i32 {
|
||||
let session_date = base_day + i;
|
||||
let ts_micros = i64::from(session_date) * 86_400_000_000;
|
||||
let close = 50.0 + f64::from(i) * 0.13;
|
||||
rows.push(Bars1dParquetRow {
|
||||
listing_id: 1,
|
||||
ts_micros,
|
||||
session_date,
|
||||
open: close - 0.25,
|
||||
high: close + 0.5,
|
||||
low: close - 0.5,
|
||||
close,
|
||||
volume: 10_000.0 + f64::from(i) * 37.0,
|
||||
vwap: if i % 3 == 0 { None } else { Some(close - 0.05) },
|
||||
currency: Cow::Borrowed("USD"),
|
||||
source: Cow::Borrowed("eod_unadj"),
|
||||
known_at_micros: ts_micros + 900_000_000,
|
||||
});
|
||||
}
|
||||
|
||||
let out_low = tmp.path().join("lvl-1");
|
||||
let out_high = tmp.path().join("lvl-19");
|
||||
write_bars_1d_dataset(
|
||||
&out_low,
|
||||
&rows,
|
||||
Bars1dWriteOptions {
|
||||
zstd_level: 1,
|
||||
..Bars1dWriteOptions::default()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
write_bars_1d_dataset(
|
||||
&out_high,
|
||||
&rows,
|
||||
Bars1dWriteOptions {
|
||||
zstd_level: 19,
|
||||
..Bars1dWriteOptions::default()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let p_low = out_low.join("bars_1d/year=2024/part.parquet");
|
||||
let p_high = out_high.join("bars_1d/year=2024/part.parquet");
|
||||
assert_ne!(fs::read(&p_low).unwrap(), fs::read(&p_high).unwrap());
|
||||
|
||||
let actual_low = read_parquet_rows(&p_low);
|
||||
let actual_high = read_parquet_rows(&p_high);
|
||||
assert_eq!(actual_low.len(), rows.len());
|
||||
assert_eq!(actual_high.len(), rows.len());
|
||||
for i in 0..rows.len() {
|
||||
assert_row_bitwise_eq(&actual_low[i], &rows[i]);
|
||||
assert_row_bitwise_eq(&actual_high[i], &rows[i]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_multiple_row_groups_and_row_group_size_one_leave_no_empty_groups() {
|
||||
let tmp = TempDirGuard::new("rg-exact-and-one");
|
||||
let base_day = ymd_to_epoch_days(2024, 1, 2).unwrap();
|
||||
let rows: Vec<Bars1dParquetRow> = (0..12_i32)
|
||||
.map(|i| {
|
||||
let session_date = base_day + i;
|
||||
let ts_micros = i64::from(session_date) * 86_400_000_000;
|
||||
Bars1dParquetRow {
|
||||
listing_id: 1,
|
||||
ts_micros,
|
||||
session_date,
|
||||
open: 10.0,
|
||||
high: 11.0,
|
||||
low: 9.0,
|
||||
close: 10.5 + f64::from(i),
|
||||
volume: 100.0,
|
||||
vwap: Some(10.25),
|
||||
currency: Cow::Borrowed("USD"),
|
||||
source: Cow::Borrowed("eod_unadj"),
|
||||
known_at_micros: ts_micros + 1_000,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Exact multiple: 12 rows / 4 per row group => 3 groups of 4, no trailing empty group.
|
||||
let out_mult = tmp.path().join("mult");
|
||||
let stats_mult = write_bars_1d_dataset(
|
||||
&out_mult,
|
||||
&rows,
|
||||
Bars1dWriteOptions {
|
||||
row_group_rows: 4,
|
||||
..Bars1dWriteOptions::default()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(stats_mult.row_groups_written, 3);
|
||||
let reader = SerializedFileReader::new(
|
||||
File::open(out_mult.join("bars_1d/year=2024/part.parquet")).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let rg_sizes: Vec<i64> = (0..reader.metadata().num_row_groups())
|
||||
.map(|i| reader.metadata().row_group(i).num_rows())
|
||||
.collect();
|
||||
assert_eq!(rg_sizes, vec![4, 4, 4]);
|
||||
|
||||
// Minimum row group size: 1 row per group.
|
||||
let out_one = tmp.path().join("one");
|
||||
let stats_one = write_bars_1d_dataset(
|
||||
&out_one,
|
||||
&rows[..5],
|
||||
Bars1dWriteOptions {
|
||||
row_group_rows: 1,
|
||||
..Bars1dWriteOptions::default()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(stats_one.row_groups_written, 5);
|
||||
let p_one = out_one.join("bars_1d/year=2024/part.parquet");
|
||||
let reader_one = SerializedFileReader::new(File::open(&p_one).unwrap()).unwrap();
|
||||
let rg_one_sizes: Vec<i64> = (0..reader_one.metadata().num_row_groups())
|
||||
.map(|i| reader_one.metadata().row_group(i).num_rows())
|
||||
.collect();
|
||||
assert_eq!(rg_one_sizes, vec![1, 1, 1, 1, 1]);
|
||||
let actual_one = read_parquet_rows(&p_one);
|
||||
for (a, e) in actual_one.iter().zip(&rows[..5]) {
|
||||
assert_row_bitwise_eq(a, e);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interleaved_years_across_listings_maintain_independent_row_group_buffers() {
|
||||
let tmp = TempDirGuard::new("interleaved-years");
|
||||
// 5 listings each with a 2023 row and a 2024 row (strictly ascending by (listing_id, session_date)).
|
||||
let mut rows = Vec::new();
|
||||
for listing_id in 1..=5_i32 {
|
||||
rows.push(make_row(
|
||||
listing_id,
|
||||
2023,
|
||||
6,
|
||||
15,
|
||||
100.0 + f64::from(listing_id),
|
||||
1_000.0,
|
||||
Some(100.0),
|
||||
"USD",
|
||||
"eod_unadj",
|
||||
));
|
||||
rows.push(make_row(
|
||||
listing_id,
|
||||
2024,
|
||||
6,
|
||||
15,
|
||||
200.0 + f64::from(listing_id),
|
||||
2_000.0,
|
||||
None,
|
||||
"CAD",
|
||||
"qm_raw",
|
||||
));
|
||||
}
|
||||
|
||||
let stats = write_bars_1d_dataset(
|
||||
tmp.path(),
|
||||
&rows,
|
||||
Bars1dWriteOptions {
|
||||
row_group_rows: 2,
|
||||
..Bars1dWriteOptions::default()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
// 5 rows per year with row_group_rows=2 => 3 row groups per year (2, 2, 1) => 6 total.
|
||||
assert_eq!(stats.files_written, 2);
|
||||
assert_eq!(stats.row_groups_written, 6);
|
||||
|
||||
for year in [2023, 2024] {
|
||||
let path = tmp.path().join(format!("bars_1d/year={year}/part.parquet"));
|
||||
let reader = SerializedFileReader::new(File::open(&path).unwrap()).unwrap();
|
||||
let sizes: Vec<i64> = (0..reader.metadata().num_row_groups())
|
||||
.map(|i| reader.metadata().row_group(i).num_rows())
|
||||
.collect();
|
||||
assert_eq!(sizes, vec![2, 2, 1]);
|
||||
let actual = read_parquet_rows(&path);
|
||||
let expected_ids: Vec<i32> = actual.iter().map(|r| r.listing_id).collect();
|
||||
assert_eq!(expected_ids, vec![1, 2, 3, 4, 5]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backwards_date_within_same_listing_returns_unsorted_input_naming_both_rows() {
|
||||
let tmp = TempDirGuard::new("backwards-date");
|
||||
let first = make_row(7, 2024, 5, 10, 50.0, 100.0, None, "USD", "eod_unadj");
|
||||
let second = make_row(7, 2024, 5, 9, 49.0, 100.0, None, "USD", "eod_unadj");
|
||||
let d1 = first.session_date;
|
||||
let d2 = second.session_date;
|
||||
|
||||
let err = write_bars_1d_dataset(tmp.path(), &[first, second], Bars1dWriteOptions::default())
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
matches!(
|
||||
err,
|
||||
ParquetBarsError::UnsortedInput {
|
||||
prev_listing_id: 7,
|
||||
prev_session_date,
|
||||
listing_id: 7,
|
||||
session_date,
|
||||
} if prev_session_date == d1 && session_date == d2
|
||||
),
|
||||
"expected UnsortedInput naming both rows, got {err:?}"
|
||||
);
|
||||
assert_no_transient_files(&tmp.path().join("bars_1d"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn negative_listing_ids_sort_and_round_trip_correctly() {
|
||||
let tmp = TempDirGuard::new("negative-listings");
|
||||
let rows = vec![
|
||||
make_row(-100, 2024, 1, 2, 10.0, 50.0, None, "USD", "eod_unadj"),
|
||||
make_row(-1, 2024, 1, 2, 20.0, 60.0, Some(19.9), "USD", "eod_unadj"),
|
||||
make_row(0, 2024, 1, 2, 30.0, 70.0, None, "USD", "eod_unadj"),
|
||||
make_row(1, 2024, 1, 2, 40.0, 80.0, Some(39.8), "USD", "eod_unadj"),
|
||||
];
|
||||
|
||||
let stats =
|
||||
write_bars_1d_dataset(tmp.path(), &rows, Bars1dWriteOptions::default()).unwrap();
|
||||
assert_eq!(stats.rows_written, 4);
|
||||
let actual = read_parquet_rows(&tmp.path().join("bars_1d/year=2024/part.parquet"));
|
||||
assert_eq!(actual.len(), rows.len());
|
||||
for (a, e) in actual.iter().zip(&rows) {
|
||||
assert_row_bitwise_eq(a, e);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn special_ieee754_floats_and_all_none_or_all_some_vwap_round_trip_bitwise() {
|
||||
let tmp = TempDirGuard::new("special-floats");
|
||||
let base_day = ymd_to_epoch_days(2024, 2, 1).unwrap();
|
||||
let payload_nan = f64::from_bits(0x7ff8_0000_0000_0042);
|
||||
let subnormal = f64::MIN_POSITIVE / 2.0;
|
||||
assert!(subnormal.is_subnormal());
|
||||
|
||||
// Row group 1 (2 rows): all-None vwap, special IEEE-754 bit patterns.
|
||||
// Row group 2 (2 rows): all-Some vwap, including payload NaN and -0.0.
|
||||
let rows = vec![
|
||||
Bars1dParquetRow {
|
||||
listing_id: 1,
|
||||
ts_micros: i64::from(base_day) * 86_400_000_000,
|
||||
session_date: base_day,
|
||||
open: -0.0,
|
||||
high: f64::INFINITY,
|
||||
low: f64::NEG_INFINITY,
|
||||
close: subnormal,
|
||||
volume: -0.0,
|
||||
vwap: None,
|
||||
currency: Cow::Borrowed("USD"),
|
||||
source: Cow::Borrowed("eod_unadj"),
|
||||
known_at_micros: i64::from(base_day) * 86_400_000_000 + 1,
|
||||
},
|
||||
Bars1dParquetRow {
|
||||
listing_id: 1,
|
||||
ts_micros: i64::from(base_day + 1) * 86_400_000_000,
|
||||
session_date: base_day + 1,
|
||||
open: payload_nan,
|
||||
high: -subnormal,
|
||||
low: 0.0,
|
||||
close: 1.0,
|
||||
volume: subnormal,
|
||||
vwap: None,
|
||||
currency: Cow::Borrowed("USD"),
|
||||
source: Cow::Borrowed("eod_unadj"),
|
||||
known_at_micros: i64::from(base_day + 1) * 86_400_000_000 + 1,
|
||||
},
|
||||
Bars1dParquetRow {
|
||||
listing_id: 1,
|
||||
ts_micros: i64::from(base_day + 2) * 86_400_000_000,
|
||||
session_date: base_day + 2,
|
||||
open: 10.0,
|
||||
high: 11.0,
|
||||
low: 9.0,
|
||||
close: 10.5,
|
||||
volume: 100.0,
|
||||
vwap: Some(payload_nan),
|
||||
currency: Cow::Borrowed("USD"),
|
||||
source: Cow::Borrowed("eod_unadj"),
|
||||
known_at_micros: i64::from(base_day + 2) * 86_400_000_000 + 1,
|
||||
},
|
||||
Bars1dParquetRow {
|
||||
listing_id: 1,
|
||||
ts_micros: i64::from(base_day + 3) * 86_400_000_000,
|
||||
session_date: base_day + 3,
|
||||
open: 10.0,
|
||||
high: 11.0,
|
||||
low: 9.0,
|
||||
close: 10.5,
|
||||
volume: 100.0,
|
||||
vwap: Some(-0.0),
|
||||
currency: Cow::Borrowed("USD"),
|
||||
source: Cow::Borrowed("eod_unadj"),
|
||||
known_at_micros: i64::from(base_day + 3) * 86_400_000_000 + 1,
|
||||
},
|
||||
];
|
||||
|
||||
write_bars_1d_dataset(
|
||||
tmp.path(),
|
||||
&rows,
|
||||
Bars1dWriteOptions {
|
||||
row_group_rows: 2,
|
||||
..Bars1dWriteOptions::default()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let actual = read_parquet_rows(&tmp.path().join("bars_1d/year=2024/part.parquet"));
|
||||
assert_eq!(actual.len(), rows.len());
|
||||
for (a, e) in actual.iter().zip(&rows) {
|
||||
assert_row_bitwise_eq(a, e);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn owned_empty_and_many_distinct_strings_round_trip_when_passed_by_value() {
|
||||
let tmp = TempDirGuard::new("owned-strings-by-value");
|
||||
let base_day = ymd_to_epoch_days(2024, 4, 1).unwrap();
|
||||
let expected: Vec<Bars1dParquetRow> = (0..12_i32)
|
||||
.map(|i| {
|
||||
let session_date = base_day + i;
|
||||
let ts_micros = i64::from(session_date) * 86_400_000_000;
|
||||
let currency = if i == 0 {
|
||||
Cow::Owned(String::new())
|
||||
} else {
|
||||
Cow::Owned(format!("CUR{i:02}"))
|
||||
};
|
||||
let source = if i == 1 {
|
||||
Cow::Owned(String::new())
|
||||
} else {
|
||||
Cow::Owned(format!("src_{i:02}"))
|
||||
};
|
||||
Bars1dParquetRow {
|
||||
listing_id: 1,
|
||||
ts_micros,
|
||||
session_date,
|
||||
open: 10.0,
|
||||
high: 11.0,
|
||||
low: 9.0,
|
||||
close: 10.5,
|
||||
volume: 500.0,
|
||||
vwap: Some(10.25),
|
||||
currency,
|
||||
source,
|
||||
known_at_micros: ts_micros + 60_000_000,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Pass owned Vec<Bars1dParquetRow> by value (not &[...]).
|
||||
let stats = write_bars_1d_dataset(
|
||||
tmp.path(),
|
||||
expected.clone(),
|
||||
Bars1dWriteOptions::default(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(stats.rows_written, expected.len());
|
||||
|
||||
let actual = read_parquet_rows(&tmp.path().join("bars_1d/year=2024/part.parquet"));
|
||||
assert_eq!(actual.len(), expected.len());
|
||||
for (a, e) in actual.iter().zip(&expected) {
|
||||
assert_row_bitwise_eq(a, e);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn currency_and_source_columns_use_dictionary_encoding() {
|
||||
let tmp = TempDirGuard::new("dict-encoding");
|
||||
let base_day = ymd_to_epoch_days(2024, 1, 2).unwrap();
|
||||
let rows: Vec<Bars1dParquetRow> = (0..100_i32)
|
||||
.map(|i| {
|
||||
let session_date = base_day + i;
|
||||
let ts_micros = i64::from(session_date) * 86_400_000_000;
|
||||
Bars1dParquetRow {
|
||||
listing_id: 1,
|
||||
ts_micros,
|
||||
session_date,
|
||||
open: 10.0,
|
||||
high: 11.0,
|
||||
low: 9.0,
|
||||
close: 10.5,
|
||||
volume: 1_000.0,
|
||||
vwap: None,
|
||||
currency: Cow::Borrowed(if i % 2 == 0 { "USD" } else { "CAD" }),
|
||||
source: Cow::Borrowed(if i % 3 == 0 { "eod_unadj" } else { "qm_raw" }),
|
||||
known_at_micros: ts_micros + 900_000_000,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
write_bars_1d_dataset(tmp.path(), &rows, Bars1dWriteOptions::default()).unwrap();
|
||||
let path = tmp.path().join("bars_1d/year=2024/part.parquet");
|
||||
let reader = SerializedFileReader::new(File::open(&path).unwrap()).unwrap();
|
||||
let rg = reader.metadata().row_group(0);
|
||||
|
||||
for (col_idx, name) in [(9, "currency"), (10, "source")] {
|
||||
let col = rg.column(col_idx);
|
||||
assert_eq!(col.column_descr().name(), name);
|
||||
assert!(
|
||||
col.dictionary_page_offset().is_some(),
|
||||
"expected dictionary page for column {name}"
|
||||
);
|
||||
let has_dict_encoding = col
|
||||
.encodings()
|
||||
.any(|enc| matches!(enc, Encoding::RLE_DICTIONARY | Encoding::PLAIN_DICTIONARY));
|
||||
assert!(
|
||||
has_dict_encoding,
|
||||
"expected dictionary encoding on column {name}, got {:?}",
|
||||
col.encodings().collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stats_bytes_written_and_rows_by_year_match_disk_files_and_footers() {
|
||||
let tmp = TempDirGuard::new("stats-match-disk");
|
||||
let rows = vec![
|
||||
make_row(1, 2022, 3, 1, 10.0, 100.0, None, "USD", "eod_unadj"),
|
||||
make_row(1, 2023, 3, 1, 20.0, 200.0, Some(19.5), "USD", "eod_unadj"),
|
||||
make_row(1, 2023, 3, 2, 21.0, 210.0, Some(20.5), "USD", "eod_unadj"),
|
||||
make_row(2, 2024, 7, 1, 30.0, 300.0, None, "CAD", "qm_raw"),
|
||||
make_row(2, 2024, 7, 2, 31.0, 310.0, None, "CAD", "qm_raw"),
|
||||
make_row(2, 2024, 7, 3, 32.0, 320.0, None, "CAD", "qm_raw"),
|
||||
];
|
||||
|
||||
let stats =
|
||||
write_bars_1d_dataset(tmp.path(), &rows, Bars1dWriteOptions::default()).unwrap();
|
||||
assert_eq!(stats.rows_written, rows.len());
|
||||
assert_eq!(
|
||||
stats.rows_by_year.values().copied().sum::<usize>(),
|
||||
stats.rows_written
|
||||
);
|
||||
|
||||
let mut disk_bytes = 0_u64;
|
||||
for (&year, &expected_count) in &stats.rows_by_year {
|
||||
let path = tmp.path().join(format!("bars_1d/year={year}/part.parquet"));
|
||||
disk_bytes += fs::metadata(&path).unwrap().len();
|
||||
let reader = SerializedFileReader::new(File::open(&path).unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
reader.metadata().file_metadata().num_rows() as usize,
|
||||
expected_count
|
||||
);
|
||||
}
|
||||
assert_eq!(stats.bytes_written, disk_bytes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewriting_single_year_replaces_target_leaves_other_years_untouched_and_cleans_transients() {
|
||||
let tmp = TempDirGuard::new("rewrite-single-year");
|
||||
let initial = vec![
|
||||
make_row(1, 2023, 4, 1, 50.0, 1_000.0, Some(49.9), "USD", "eod_unadj"),
|
||||
make_row(1, 2024, 4, 1, 60.0, 2_000.0, None, "USD", "eod_unadj"),
|
||||
];
|
||||
write_bars_1d_dataset(tmp.path(), &initial, Bars1dWriteOptions::default()).unwrap();
|
||||
|
||||
let path_2023 = tmp.path().join("bars_1d/year=2023/part.parquet");
|
||||
let path_2024 = tmp.path().join("bars_1d/year=2024/part.parquet");
|
||||
let orig_2023_bytes = fs::read(&path_2023).unwrap();
|
||||
|
||||
// Rewrite only 2024 with new data.
|
||||
let updated_2024 = vec![
|
||||
make_row(1, 2024, 4, 1, 65.0, 3_000.0, Some(64.5), "USD", "eod_unadj"),
|
||||
make_row(1, 2024, 4, 2, 66.0, 3_500.0, Some(65.5), "USD", "eod_unadj"),
|
||||
];
|
||||
let stats =
|
||||
write_bars_1d_dataset(tmp.path(), &updated_2024, Bars1dWriteOptions::default()).unwrap();
|
||||
assert_eq!(stats.files_written, 1);
|
||||
assert_eq!(stats.rows_written, 2);
|
||||
|
||||
assert_eq!(fs::read(&path_2023).unwrap(), orig_2023_bytes);
|
||||
let actual_2024 = read_parquet_rows(&path_2024);
|
||||
assert_eq!(actual_2024.len(), updated_2024.len());
|
||||
for (a, e) in actual_2024.iter().zip(&updated_2024) {
|
||||
assert_row_bitwise_eq(a, e);
|
||||
}
|
||||
assert_no_transient_files(&tmp.path().join("bars_1d"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_run_releases_write_lock_so_next_run_succeeds_within_50ms() {
|
||||
let tmp = TempDirGuard::new("lock-release-after-err");
|
||||
let bad_rows = vec![
|
||||
make_row(2, 2024, 1, 2, 10.0, 100.0, None, "USD", "eod_unadj"),
|
||||
make_row(1, 2024, 1, 2, 10.0, 100.0, None, "USD", "eod_unadj"),
|
||||
];
|
||||
let err =
|
||||
write_bars_1d_dataset(tmp.path(), &bad_rows, Bars1dWriteOptions::default()).unwrap_err();
|
||||
assert!(matches!(err, ParquetBarsError::UnsortedInput { .. }));
|
||||
|
||||
let good_rows = vec![make_row(
|
||||
1,
|
||||
2024,
|
||||
1,
|
||||
2,
|
||||
10.0,
|
||||
100.0,
|
||||
None,
|
||||
"USD",
|
||||
"eod_unadj",
|
||||
)];
|
||||
let stats = write_bars_1d_dataset_with_hooks(
|
||||
tmp.path(),
|
||||
&good_rows,
|
||||
Bars1dWriteOptions::default(),
|
||||
Duration::from_millis(50),
|
||||
|_, _, _| {},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(stats.rows_written, 1);
|
||||
assert_no_transient_files(&tmp.path().join("bars_1d"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_after_30_flushed_row_groups_leaves_no_partial_files() {
|
||||
let tmp = TempDirGuard::new("err-after-30-rgs");
|
||||
let base_day = ymd_to_epoch_days(2024, 1, 2).unwrap();
|
||||
let mut rows: Vec<Bars1dParquetRow> = (0..60_i32)
|
||||
.map(|i| {
|
||||
let session_date = base_day + i;
|
||||
let ts_micros = i64::from(session_date) * 86_400_000_000;
|
||||
Bars1dParquetRow {
|
||||
listing_id: 1,
|
||||
ts_micros,
|
||||
session_date,
|
||||
open: 10.0,
|
||||
high: 11.0,
|
||||
low: 9.0,
|
||||
close: 10.5,
|
||||
volume: 100.0,
|
||||
vwap: None,
|
||||
currency: Cow::Borrowed("USD"),
|
||||
source: Cow::Borrowed("eod_unadj"),
|
||||
known_at_micros: ts_micros + 1_000,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
// 60 rows with row_group_rows=2 flushes 30 row groups before hitting this duplicate key.
|
||||
rows.push(rows[59].clone());
|
||||
|
||||
let err = write_bars_1d_dataset(
|
||||
tmp.path(),
|
||||
&rows,
|
||||
Bars1dWriteOptions {
|
||||
row_group_rows: 2,
|
||||
..Bars1dWriteOptions::default()
|
||||
},
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, ParquetBarsError::DuplicateKey { listing_id: 1, .. }));
|
||||
|
||||
let final_path = tmp.path().join("bars_1d/year=2024/part.parquet");
|
||||
assert!(!final_path.exists(), "partial part.parquet must not be published");
|
||||
assert_no_transient_files(&tmp.path().join("bars_1d"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bars_1d_path_occupied_by_regular_file_returns_io_error_and_leaves_file_untouched() {
|
||||
let tmp = TempDirGuard::new("bars-1d-is-file");
|
||||
let bars_path = tmp.path().join("bars_1d");
|
||||
let sentinel = b"not-a-directory";
|
||||
fs::write(&bars_path, sentinel).unwrap();
|
||||
|
||||
let rows = vec![make_row(
|
||||
1,
|
||||
2024,
|
||||
1,
|
||||
2,
|
||||
10.0,
|
||||
100.0,
|
||||
Some(10.0),
|
||||
"USD",
|
||||
"eod_unadj",
|
||||
)];
|
||||
let err =
|
||||
write_bars_1d_dataset(tmp.path(), &rows, Bars1dWriteOptions::default()).unwrap_err();
|
||||
assert!(
|
||||
matches!(err, ParquetBarsError::Io { ref path, .. } if path == &bars_path),
|
||||
"expected Io error for bars_1d path, got {err:?}"
|
||||
);
|
||||
assert!(bars_path.is_file());
|
||||
assert_eq!(fs::read(&bars_path).unwrap(), sentinel);
|
||||
let entries: Vec<_> = fs::read_dir(tmp.path())
|
||||
.unwrap()
|
||||
.map(|e| e.unwrap().file_name())
|
||||
.collect();
|
||||
assert_eq!(entries, vec![std::ffi::OsString::from("bars_1d")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocked_year_dir_partway_through_preserves_prior_year_cleans_staging_and_releases_lock() {
|
||||
let tmp = TempDirGuard::new("blocked-year-dir");
|
||||
let initial = vec![make_row(
|
||||
1,
|
||||
2024,
|
||||
6,
|
||||
15,
|
||||
100.0,
|
||||
1_000.0,
|
||||
Some(99.5),
|
||||
"USD",
|
||||
"eod_unadj",
|
||||
)];
|
||||
write_bars_1d_dataset(tmp.path(), &initial, Bars1dWriteOptions::default()).unwrap();
|
||||
|
||||
let path_2024 = tmp.path().join("bars_1d/year=2024/part.parquet");
|
||||
let orig_2024_bytes = fs::read(&path_2024).unwrap();
|
||||
|
||||
// Block year=2025 with a regular file so staging fails partway through after 2024 opens.
|
||||
let blocked_2025 = tmp.path().join("bars_1d/year=2025");
|
||||
fs::write(&blocked_2025, b"blocker").unwrap();
|
||||
|
||||
let refresh = vec![
|
||||
make_row(1, 2024, 6, 15, 110.0, 2_000.0, Some(109.5), "USD", "eod_unadj"),
|
||||
make_row(1, 2025, 1, 2, 120.0, 3_000.0, Some(119.5), "USD", "eod_unadj"),
|
||||
];
|
||||
let err =
|
||||
write_bars_1d_dataset(tmp.path(), &refresh, Bars1dWriteOptions::default()).unwrap_err();
|
||||
assert!(
|
||||
matches!(err, ParquetBarsError::Io { ref path, .. } if path == &blocked_2025),
|
||||
"expected Io error naming year=2025, got {err:?}"
|
||||
);
|
||||
|
||||
assert_eq!(fs::read(&path_2024).unwrap(), orig_2024_bytes);
|
||||
assert_no_transient_files(&tmp.path().join("bars_1d"));
|
||||
|
||||
// Lock must be released so a subsequent valid write succeeds immediately.
|
||||
let follow_up = vec![make_row(
|
||||
1,
|
||||
2024,
|
||||
6,
|
||||
16,
|
||||
111.0,
|
||||
2_100.0,
|
||||
None,
|
||||
"USD",
|
||||
"eod_unadj",
|
||||
)];
|
||||
let stats = write_bars_1d_dataset_with_hooks(
|
||||
tmp.path(),
|
||||
&follow_up,
|
||||
Bars1dWriteOptions::default(),
|
||||
Duration::from_millis(50),
|
||||
|_, _, _| {},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(stats.rows_written, 1);
|
||||
assert_no_transient_files(&tmp.path().join("bars_1d"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_year_refresh_replaces_existing_adds_new_preserves_untouched_and_leaves_only_part_parquet() {
|
||||
let tmp = TempDirGuard::new("multi-year-refresh");
|
||||
let initial = vec![
|
||||
make_row(1, 2022, 5, 1, 10.0, 100.0, None, "USD", "eod_unadj"),
|
||||
make_row(1, 2023, 5, 1, 20.0, 200.0, Some(19.9), "USD", "eod_unadj"),
|
||||
make_row(1, 2024, 5, 1, 30.0, 300.0, None, "USD", "eod_unadj"),
|
||||
];
|
||||
write_bars_1d_dataset(tmp.path(), &initial, Bars1dWriteOptions::default()).unwrap();
|
||||
|
||||
let path_2022 = tmp.path().join("bars_1d/year=2022/part.parquet");
|
||||
let orig_2022_bytes = fs::read(&path_2022).unwrap();
|
||||
|
||||
let refresh = vec![
|
||||
make_row(1, 2023, 5, 1, 25.0, 250.0, Some(24.5), "USD", "eod_unadj"),
|
||||
make_row(1, 2023, 5, 2, 26.0, 260.0, Some(25.5), "USD", "eod_unadj"),
|
||||
make_row(1, 2024, 5, 1, 35.0, 350.0, Some(34.5), "CAD", "qm_raw"),
|
||||
make_row(1, 2025, 1, 2, 40.0, 400.0, None, "USD", "eod_unadj"),
|
||||
make_row(2, 2025, 1, 2, 41.0, 410.0, Some(40.5), "USD", "eod_unadj"),
|
||||
make_row(3, 2025, 1, 2, 42.0, 420.0, None, "CAD", "qm_raw"),
|
||||
];
|
||||
let stats =
|
||||
write_bars_1d_dataset(tmp.path(), &refresh, Bars1dWriteOptions::default()).unwrap();
|
||||
assert_eq!(stats.files_written, 3);
|
||||
assert_eq!(stats.rows_written, 6);
|
||||
assert_eq!(stats.rows_by_year.get(&2023), Some(&2));
|
||||
assert_eq!(stats.rows_by_year.get(&2024), Some(&1));
|
||||
assert_eq!(stats.rows_by_year.get(&2025), Some(&3));
|
||||
assert_eq!(stats.rows_by_year.get(&2022), None);
|
||||
|
||||
assert_eq!(fs::read(&path_2022).unwrap(), orig_2022_bytes);
|
||||
assert_eq!(
|
||||
read_parquet_rows(&tmp.path().join("bars_1d/year=2023/part.parquet")).len(),
|
||||
2
|
||||
);
|
||||
assert_eq!(
|
||||
read_parquet_rows(&tmp.path().join("bars_1d/year=2024/part.parquet")).len(),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
read_parquet_rows(&tmp.path().join("bars_1d/year=2025/part.parquet")).len(),
|
||||
3
|
||||
);
|
||||
|
||||
let bars_dir = tmp.path().join("bars_1d");
|
||||
assert_no_transient_files(&bars_dir);
|
||||
for year in [2022, 2023, 2024, 2025] {
|
||||
let year_dir = bars_dir.join(format!("year={year}"));
|
||||
let entries: Vec<_> = fs::read_dir(&year_dir)
|
||||
.unwrap()
|
||||
.map(|e| e.unwrap().file_name())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
entries,
|
||||
vec![std::ffi::OsString::from("part.parquet")],
|
||||
"year={year} should contain only part.parquet"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn active_external_write_lock_times_out_without_deleting_lock_or_modifying_existing_partition() {
|
||||
let tmp = TempDirGuard::new("external-lock-held");
|
||||
let initial = vec![make_row(
|
||||
1,
|
||||
2024,
|
||||
3,
|
||||
10,
|
||||
50.0,
|
||||
500.0,
|
||||
Some(49.5),
|
||||
"USD",
|
||||
"eod_unadj",
|
||||
)];
|
||||
write_bars_1d_dataset(tmp.path(), &initial, Bars1dWriteOptions::default()).unwrap();
|
||||
|
||||
let path_2024 = tmp.path().join("bars_1d/year=2024/part.parquet");
|
||||
let orig_2024_bytes = fs::read(&path_2024).unwrap();
|
||||
|
||||
let lock_path = tmp.path().join("bars_1d/.write.lock");
|
||||
let lock_contents = b"pid=999999\n";
|
||||
fs::write(&lock_path, lock_contents).unwrap();
|
||||
|
||||
let updated = vec![make_row(
|
||||
1,
|
||||
2024,
|
||||
3,
|
||||
10,
|
||||
99.0,
|
||||
999.0,
|
||||
Some(98.5),
|
||||
"USD",
|
||||
"eod_unadj",
|
||||
)];
|
||||
let err = write_bars_1d_dataset_with_hooks(
|
||||
tmp.path(),
|
||||
&updated,
|
||||
Bars1dWriteOptions::default(),
|
||||
Duration::from_millis(60),
|
||||
|_, _, _| {},
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
matches!(err, ParquetBarsError::LockTimeout { ref path, .. } if path == &lock_path),
|
||||
"expected LockTimeout naming lock path, got {err:?}"
|
||||
);
|
||||
|
||||
assert!(lock_path.exists(), "must not delete another writer's lock");
|
||||
assert_eq!(fs::read(&lock_path).unwrap(), lock_contents);
|
||||
assert_eq!(fs::read(&path_2024).unwrap(), orig_2024_bytes);
|
||||
}
|
||||
533
tools/curate-etl/tests/parquet_bars_contract.rs
Normal file
533
tools/curate-etl/tests/parquet_bars_contract.rs
Normal file
|
|
@ -0,0 +1,533 @@
|
|||
//! QA contract tests for the public `bars_1d` Parquet writer API (T-90 / M1.2i).
|
||||
//!
|
||||
//! Uses only the crate's public surface (`write_bars_1d_dataset`, `bars_1d_parquet_schema`, the
|
||||
//! `curate-etl` binary) plus an independent Parquet column reader, guarding the
|
||||
//! `design/DATA-CONTRACTS.md` §3A `bars_1d/year=YYYY/part.parquet` layout, refresh semantics,
|
||||
//! string-interning row-group boundaries, in-process writer serialization and the
|
||||
//! `bench-parquet-bars` CLI contract.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::fs::{self, File};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Barrier};
|
||||
use std::thread;
|
||||
|
||||
use curate_etl::{
|
||||
bars_1d_parquet_schema, write_bars_1d_dataset, ymd_to_epoch_days, Bars1dParquetRow,
|
||||
Bars1dWriteOptions, ParquetBarsError,
|
||||
};
|
||||
use parquet::basic::Compression;
|
||||
use parquet::column::reader::ColumnReader;
|
||||
use parquet::file::reader::{FileReader, SerializedFileReader};
|
||||
|
||||
static SEQ: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// Unique, self-cleaning temp dir under `std::env::temp_dir()`.
|
||||
struct TempDir(PathBuf);
|
||||
|
||||
impl TempDir {
|
||||
fn new(tag: &str) -> Self {
|
||||
let seq = SEQ.fetch_add(1, Ordering::Relaxed);
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"curate-etl-pq-contract-{tag}-{}-{seq}",
|
||||
std::process::id()
|
||||
));
|
||||
let _ = fs::remove_dir_all(&path);
|
||||
fs::create_dir_all(&path).expect("create temp dir");
|
||||
Self(path)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn day(y: i32, m: u32, d: u32) -> i32 {
|
||||
ymd_to_epoch_days(y, m, d).expect("valid fixture date")
|
||||
}
|
||||
|
||||
fn row(listing_id: i32, session_date: i32, close: f64, currency: &str) -> Bars1dParquetRow {
|
||||
let ts = i64::from(session_date) * 86_400_000_000 + 20 * 3_600_000_000;
|
||||
Bars1dParquetRow {
|
||||
listing_id,
|
||||
ts_micros: ts,
|
||||
session_date,
|
||||
open: close - 0.25,
|
||||
high: close + 1.0,
|
||||
low: close - 1.0,
|
||||
close,
|
||||
volume: 1_000.0 + f64::from(listing_id),
|
||||
vwap: if listing_id % 2 == 0 {
|
||||
None
|
||||
} else {
|
||||
Some(close + 0.125)
|
||||
},
|
||||
currency: Cow::Owned(currency.to_string()),
|
||||
source: Cow::Borrowed("eod_unadj"),
|
||||
known_at_micros: ts + 900_000_000,
|
||||
}
|
||||
}
|
||||
|
||||
fn part_path(out: &Path, year: i32) -> PathBuf {
|
||||
out.join(format!("bars_1d/year={year:04}/part.parquet"))
|
||||
}
|
||||
|
||||
fn read_rows(path: &Path) -> Vec<Bars1dParquetRow> {
|
||||
let reader = SerializedFileReader::new(File::open(path).expect("open")).expect("reader");
|
||||
let meta = reader.metadata();
|
||||
let mut out = Vec::new();
|
||||
for rg in 0..meta.num_row_groups() {
|
||||
let n = meta.row_group(rg).num_rows() as usize;
|
||||
let g = reader.get_row_group(rg).expect("row group");
|
||||
let col = |i: usize| g.get_column_reader(i).expect("column reader");
|
||||
let i32s = |c: ColumnReader| -> Vec<i32> {
|
||||
let mut v = Vec::new();
|
||||
match c {
|
||||
ColumnReader::Int32ColumnReader(mut r) => {
|
||||
assert_eq!(r.read_records(n, None, None, &mut v).unwrap().0, n);
|
||||
}
|
||||
_ => panic!("expected INT32"),
|
||||
}
|
||||
v
|
||||
};
|
||||
let i64s = |c: ColumnReader| -> Vec<i64> {
|
||||
let mut v = Vec::new();
|
||||
match c {
|
||||
ColumnReader::Int64ColumnReader(mut r) => {
|
||||
assert_eq!(r.read_records(n, None, None, &mut v).unwrap().0, n);
|
||||
}
|
||||
_ => panic!("expected INT64"),
|
||||
}
|
||||
v
|
||||
};
|
||||
let f64s = |c: ColumnReader| -> Vec<Option<f64>> {
|
||||
let mut v = Vec::new();
|
||||
let mut defs = Vec::new();
|
||||
match c {
|
||||
ColumnReader::DoubleColumnReader(mut r) => {
|
||||
assert_eq!(
|
||||
r.read_records(n, Some(&mut defs), None, &mut v).unwrap().0,
|
||||
n
|
||||
);
|
||||
}
|
||||
_ => panic!("expected DOUBLE"),
|
||||
}
|
||||
if defs.is_empty() {
|
||||
return v.into_iter().map(Some).collect();
|
||||
}
|
||||
let mut it = v.into_iter();
|
||||
defs.iter()
|
||||
.map(|&d| if d == 1 { it.next() } else { None })
|
||||
.collect()
|
||||
};
|
||||
let strs = |c: ColumnReader| -> Vec<String> {
|
||||
let mut v = Vec::new();
|
||||
match c {
|
||||
ColumnReader::ByteArrayColumnReader(mut r) => {
|
||||
assert_eq!(r.read_records(n, None, None, &mut v).unwrap().0, n);
|
||||
}
|
||||
_ => panic!("expected BYTE_ARRAY"),
|
||||
}
|
||||
v.iter()
|
||||
.map(|b| std::str::from_utf8(b.data()).expect("utf8").to_string())
|
||||
.collect()
|
||||
};
|
||||
let req = |v: Vec<Option<f64>>| -> Vec<f64> {
|
||||
v.into_iter().map(|x| x.expect("required double")).collect()
|
||||
};
|
||||
let lid = i32s(col(0));
|
||||
let ts = i64s(col(1));
|
||||
let sd = i32s(col(2));
|
||||
let open = req(f64s(col(3)));
|
||||
let high = req(f64s(col(4)));
|
||||
let low = req(f64s(col(5)));
|
||||
let close = req(f64s(col(6)));
|
||||
let volume = req(f64s(col(7)));
|
||||
let vwap = f64s(col(8));
|
||||
let cur = strs(col(9));
|
||||
let src = strs(col(10));
|
||||
let ka = i64s(col(11));
|
||||
for i in 0..n {
|
||||
out.push(Bars1dParquetRow {
|
||||
listing_id: lid[i],
|
||||
ts_micros: ts[i],
|
||||
session_date: sd[i],
|
||||
open: open[i],
|
||||
high: high[i],
|
||||
low: low[i],
|
||||
close: close[i],
|
||||
volume: volume[i],
|
||||
vwap: vwap[i],
|
||||
currency: Cow::Owned(cur[i].clone()),
|
||||
source: Cow::Owned(src[i].clone()),
|
||||
known_at_micros: ka[i],
|
||||
});
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn assert_rows_bitwise(actual: &[Bars1dParquetRow], expected: &[Bars1dParquetRow]) {
|
||||
assert_eq!(actual.len(), expected.len(), "row count");
|
||||
for (i, (a, e)) in actual.iter().zip(expected).enumerate() {
|
||||
assert_eq!(a.listing_id, e.listing_id, "row {i} listing_id");
|
||||
assert_eq!(a.ts_micros, e.ts_micros, "row {i} ts");
|
||||
assert_eq!(a.session_date, e.session_date, "row {i} session_date");
|
||||
for (name, x, y) in [
|
||||
("open", a.open, e.open),
|
||||
("high", a.high, e.high),
|
||||
("low", a.low, e.low),
|
||||
("close", a.close, e.close),
|
||||
("volume", a.volume, e.volume),
|
||||
] {
|
||||
assert_eq!(x.to_bits(), y.to_bits(), "row {i} {name}");
|
||||
}
|
||||
assert_eq!(
|
||||
a.vwap.map(f64::to_bits),
|
||||
e.vwap.map(f64::to_bits),
|
||||
"row {i} vwap"
|
||||
);
|
||||
assert_eq!(a.currency, e.currency, "row {i} currency");
|
||||
assert_eq!(a.source, e.source, "row {i} source");
|
||||
assert_eq!(a.known_at_micros, e.known_at_micros, "row {i} known_at");
|
||||
}
|
||||
}
|
||||
|
||||
/// Lists every file under `dir` (recursively), relative to `dir`, sorted.
|
||||
fn list_files(dir: &Path) -> Vec<String> {
|
||||
fn walk(root: &Path, dir: &Path, out: &mut Vec<String>) {
|
||||
let Ok(entries) = fs::read_dir(dir) else {
|
||||
return;
|
||||
};
|
||||
for entry in entries {
|
||||
let path = entry.expect("dir entry").path();
|
||||
if path.is_dir() {
|
||||
walk(root, &path, out);
|
||||
} else {
|
||||
out.push(path.strip_prefix(root).unwrap().display().to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
walk(dir, dir, &mut out);
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_schema_equals_public_schema_and_contract_column_order() {
|
||||
let tmp = TempDir::new("schema");
|
||||
let rows = vec![row(1, day(2024, 3, 1), 10.0, "USD")];
|
||||
write_bars_1d_dataset(&tmp.0, &rows, Bars1dWriteOptions::default()).unwrap();
|
||||
|
||||
let reader = SerializedFileReader::new(File::open(part_path(&tmp.0, 2024)).unwrap()).unwrap();
|
||||
let meta = reader.metadata();
|
||||
let file_schema = meta.file_metadata().schema();
|
||||
let public_schema = bars_1d_parquet_schema().unwrap();
|
||||
assert_eq!(
|
||||
file_schema,
|
||||
public_schema.as_ref(),
|
||||
"on-disk schema == public schema"
|
||||
);
|
||||
|
||||
let names: Vec<&str> = file_schema.get_fields().iter().map(|f| f.name()).collect();
|
||||
assert_eq!(
|
||||
names,
|
||||
[
|
||||
"listing_id",
|
||||
"ts",
|
||||
"session_date",
|
||||
"open",
|
||||
"high",
|
||||
"low",
|
||||
"close",
|
||||
"volume",
|
||||
"vwap",
|
||||
"currency",
|
||||
"source",
|
||||
"known_at"
|
||||
]
|
||||
);
|
||||
for rg in meta.row_groups() {
|
||||
for c in rg.columns() {
|
||||
assert!(
|
||||
matches!(c.compression(), Compression::ZSTD(_)),
|
||||
"{} not ZSTD",
|
||||
c.column_path()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_year_refresh_publishes_new_values_bitwise_not_stale_rows() {
|
||||
// Reviewer gap: old and new partitions have equal row counts, so only a value check proves
|
||||
// the refresh actually replaced the stale bar.
|
||||
let tmp = TempDir::new("refresh");
|
||||
let old = vec![
|
||||
row(1, day(2023, 6, 1), 10.0, "USD"),
|
||||
row(1, day(2024, 6, 3), 20.0, "USD"),
|
||||
row(2, day(2022, 6, 1), 30.0, "CAD"),
|
||||
];
|
||||
write_bars_1d_dataset(&tmp.0, &old, Bars1dWriteOptions::default()).unwrap();
|
||||
let untouched_2022 = fs::read(part_path(&tmp.0, 2022)).unwrap();
|
||||
|
||||
let new = vec![
|
||||
row(1, day(2023, 6, 1), 11.5, "USD"),
|
||||
row(1, day(2024, 6, 3), 21.5, "CAD"),
|
||||
row(1, day(2025, 1, 2), 31.5, "USD"),
|
||||
];
|
||||
let stats = write_bars_1d_dataset(&tmp.0, &new, Bars1dWriteOptions::default()).unwrap();
|
||||
assert_eq!(stats.rows_written, 3);
|
||||
assert_eq!(stats.files_written, 3);
|
||||
|
||||
assert_rows_bitwise(&read_rows(&part_path(&tmp.0, 2023)), &new[0..1]);
|
||||
assert_rows_bitwise(&read_rows(&part_path(&tmp.0, 2024)), &new[1..2]);
|
||||
assert_rows_bitwise(&read_rows(&part_path(&tmp.0, 2025)), &new[2..3]);
|
||||
assert_eq!(fs::read(part_path(&tmp.0, 2022)).unwrap(), untouched_2022);
|
||||
assert_eq!(
|
||||
list_files(&tmp.0.join("bars_1d")),
|
||||
[
|
||||
"year=2022/part.parquet",
|
||||
"year=2023/part.parquet",
|
||||
"year=2024/part.parquet",
|
||||
"year=2025/part.parquet"
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rows_interleaved_across_years_keep_listing_then_date_order_per_file() {
|
||||
let tmp = TempDir::new("order");
|
||||
let rows = vec![
|
||||
row(1, day(2023, 12, 29), 1.0, "USD"),
|
||||
row(1, day(2024, 1, 2), 2.0, "USD"),
|
||||
row(1, day(2024, 2, 29), 3.0, "USD"),
|
||||
row(7, day(2023, 12, 31), 4.0, "CAD"),
|
||||
row(7, day(2024, 1, 1), 5.0, "CAD"),
|
||||
row(9, day(2024, 12, 31), 6.0, "USD"),
|
||||
];
|
||||
let stats = write_bars_1d_dataset(&tmp.0, &rows, Bars1dWriteOptions::default()).unwrap();
|
||||
|
||||
assert_eq!(stats.rows_by_year.get(&2023), Some(&2));
|
||||
assert_eq!(stats.rows_by_year.get(&2024), Some(&4));
|
||||
let y23: Vec<_> = vec![rows[0].clone(), rows[3].clone()];
|
||||
let y24: Vec<_> = vec![
|
||||
rows[1].clone(),
|
||||
rows[2].clone(),
|
||||
rows[4].clone(),
|
||||
rows[5].clone(),
|
||||
];
|
||||
assert_rows_bitwise(&read_rows(&part_path(&tmp.0, 2023)), &y23);
|
||||
assert_rows_bitwise(&read_rows(&part_path(&tmp.0, 2024)), &y24);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_date_days_since_epoch_round_trip_including_pre_epoch_and_leap_day() {
|
||||
let tmp = TempDir::new("dates");
|
||||
let rows = vec![
|
||||
row(1, day(1969, 12, 31), 1.0, "USD"),
|
||||
row(1, day(1970, 1, 1), 2.0, "USD"),
|
||||
row(1, day(2000, 2, 29), 3.0, "USD"),
|
||||
];
|
||||
assert_eq!(rows[0].session_date, -1);
|
||||
assert_eq!(rows[1].session_date, 0);
|
||||
let stats = write_bars_1d_dataset(&tmp.0, &rows, Bars1dWriteOptions::default()).unwrap();
|
||||
assert_eq!(
|
||||
stats.rows_by_year.keys().copied().collect::<Vec<_>>(),
|
||||
[1969, 1970, 2000]
|
||||
);
|
||||
assert_rows_bitwise(&read_rows(&part_path(&tmp.0, 1969)), &rows[0..1]);
|
||||
assert_rows_bitwise(&read_rows(&part_path(&tmp.0, 1970)), &rows[1..2]);
|
||||
assert_rows_bitwise(&read_rows(&part_path(&tmp.0, 2000)), &rows[2..3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn string_interner_crossing_linear_limit_and_row_group_resets_round_trip() {
|
||||
// 12 distinct currencies (crosses the writer's small linear-intern threshold mid-group),
|
||||
// revisiting earlier values after the threshold, across 3 row groups so per-group
|
||||
// interner resets are exercised.
|
||||
let tmp = TempDir::new("intern");
|
||||
let currencies: Vec<String> = (0..12).map(|i| format!("C{i:02}")).collect();
|
||||
let mut rows = Vec::new();
|
||||
let base = day(2021, 1, 4);
|
||||
for i in 0..30i32 {
|
||||
let idx = ((i * 7) % 12) as usize;
|
||||
let mut r = row(1, base + i, 100.0 + f64::from(i), ¤cies[idx]);
|
||||
r.source = Cow::Owned(format!("src{}", (i * 5) % 11));
|
||||
rows.push(r);
|
||||
}
|
||||
let opts = Bars1dWriteOptions {
|
||||
row_group_rows: 11,
|
||||
..Bars1dWriteOptions::default()
|
||||
};
|
||||
let stats = write_bars_1d_dataset(&tmp.0, &rows, opts).unwrap();
|
||||
assert_eq!(stats.row_groups_written, 3);
|
||||
assert_rows_bitwise(&read_rows(&part_path(&tmp.0, 2021)), &rows);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concurrent_in_process_writers_publish_one_complete_generation_and_no_transients() {
|
||||
let tmp = TempDir::new("concurrent");
|
||||
let out = Arc::new(tmp.0.clone());
|
||||
let make = |close_base: f64, cur: &'static str| -> Vec<Bars1dParquetRow> {
|
||||
(0..2_000)
|
||||
.map(|i| {
|
||||
row(
|
||||
1 + i / 400,
|
||||
day(2020, 1, 1) + (i % 400),
|
||||
close_base + f64::from(i),
|
||||
cur,
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let gens = Arc::new([make(1_000.0, "USD"), make(5_000.0, "CAD")]);
|
||||
let barrier = Arc::new(Barrier::new(2));
|
||||
let handles: Vec<_> = (0..2)
|
||||
.map(|g| {
|
||||
let (out, gens, barrier) = (out.clone(), gens.clone(), barrier.clone());
|
||||
thread::spawn(move || {
|
||||
barrier.wait();
|
||||
let opts = Bars1dWriteOptions {
|
||||
row_group_rows: 97,
|
||||
..Bars1dWriteOptions::default()
|
||||
};
|
||||
write_bars_1d_dataset(out.as_path(), &gens[g], opts)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
for h in handles {
|
||||
let stats = h.join().expect("writer thread").expect("writer result");
|
||||
assert_eq!(stats.rows_written, 2_000);
|
||||
}
|
||||
|
||||
// Every year file must come entirely from one generation (no mixed / truncated output).
|
||||
for year in [2020, 2021] {
|
||||
let got = read_rows(&part_path(&tmp.0, year));
|
||||
let from = |g: usize| -> Vec<Bars1dParquetRow> {
|
||||
let (lo, hi) = (day(year, 1, 1), day(year + 1, 1, 1));
|
||||
gens[g]
|
||||
.iter()
|
||||
.filter(|r| r.session_date >= lo && r.session_date < hi)
|
||||
.cloned()
|
||||
.collect()
|
||||
};
|
||||
let g = if got.first().map(|r| r.currency.as_ref()) == Some("USD") {
|
||||
0
|
||||
} else {
|
||||
1
|
||||
};
|
||||
assert_rows_bitwise(&got, &from(g));
|
||||
}
|
||||
assert_eq!(
|
||||
list_files(&tmp.0.join("bars_1d")),
|
||||
["year=2020/part.parquet", "year=2021/part.parquet"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsorted_row_after_several_years_opened_keeps_existing_partitions_and_leaves_no_files() {
|
||||
let tmp = TempDir::new("midfail");
|
||||
let seed = vec![
|
||||
row(1, day(2019, 5, 1), 9.0, "USD"),
|
||||
row(1, day(2020, 5, 1), 9.5, "USD"),
|
||||
];
|
||||
write_bars_1d_dataset(&tmp.0, &seed, Bars1dWriteOptions::default()).unwrap();
|
||||
let before_2019 = fs::read(part_path(&tmp.0, 2019)).unwrap();
|
||||
let before_2020 = fs::read(part_path(&tmp.0, 2020)).unwrap();
|
||||
|
||||
let bad = vec![
|
||||
row(1, day(2019, 5, 1), 1.0, "USD"),
|
||||
row(1, day(2020, 5, 1), 2.0, "USD"),
|
||||
row(1, day(2021, 5, 3), 3.0, "USD"),
|
||||
row(1, day(2021, 5, 2), 4.0, "USD"), // goes backwards
|
||||
row(2, day(2022, 5, 2), 5.0, "USD"),
|
||||
];
|
||||
let err = write_bars_1d_dataset(&tmp.0, &bad, Bars1dWriteOptions::default()).unwrap_err();
|
||||
match &err {
|
||||
ParquetBarsError::UnsortedInput {
|
||||
prev_listing_id,
|
||||
prev_session_date,
|
||||
listing_id,
|
||||
session_date,
|
||||
} => {
|
||||
assert_eq!((*prev_listing_id, *prev_session_date), (1, day(2021, 5, 3)));
|
||||
assert_eq!((*listing_id, *session_date), (1, day(2021, 5, 2)));
|
||||
}
|
||||
other => panic!("expected UnsortedInput, got {other:?}"),
|
||||
}
|
||||
let msg = err.to_string();
|
||||
assert!(
|
||||
msg.contains(&day(2021, 5, 3).to_string()) && msg.contains(&day(2021, 5, 2).to_string())
|
||||
);
|
||||
|
||||
assert_eq!(fs::read(part_path(&tmp.0, 2019)).unwrap(), before_2019);
|
||||
assert_eq!(fs::read(part_path(&tmp.0, 2020)).unwrap(), before_2020);
|
||||
assert_eq!(
|
||||
list_files(&tmp.0.join("bars_1d")),
|
||||
["year=2019/part.parquet", "year=2020/part.parquet"],
|
||||
"no staging, backup, lock or new partition files may remain"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn io_error_exposes_source_chain_and_path() {
|
||||
let tmp = TempDir::new("ioerr");
|
||||
let file_as_out = tmp.0.join("not-a-dir");
|
||||
fs::write(&file_as_out, b"x").unwrap();
|
||||
let err = write_bars_1d_dataset(
|
||||
&file_as_out,
|
||||
&[row(1, day(2024, 1, 2), 1.0, "USD")],
|
||||
Bars1dWriteOptions::default(),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, ParquetBarsError::Io { .. }), "got {err:?}");
|
||||
assert!(std::error::Error::source(&err).is_some());
|
||||
assert!(err.to_string().contains("not-a-dir"));
|
||||
assert_eq!(fs::read(&file_as_out).unwrap(), b"x");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bench_parquet_bars_cli_prints_metrics_and_removes_its_temp_dir() {
|
||||
let tmp = TempDir::new("cli");
|
||||
let out = Command::new(env!("CARGO_BIN_EXE_curate-etl"))
|
||||
.args(["bench-parquet-bars", "20000"])
|
||||
.env("TMPDIR", &tmp.0)
|
||||
.output()
|
||||
.expect("spawn curate-etl");
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
assert!(
|
||||
out.status.success(),
|
||||
"stderr: {}",
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
for needle in [
|
||||
"curate-etl bench-parquet-bars",
|
||||
"rows=20000",
|
||||
"read_back_rows=20000",
|
||||
"rows/s",
|
||||
"MB/s",
|
||||
"bytes/row",
|
||||
"compression=",
|
||||
] {
|
||||
assert!(stdout.contains(needle), "missing '{needle}' in:\n{stdout}");
|
||||
}
|
||||
let leftovers: Vec<_> = fs::read_dir(&tmp.0).unwrap().collect();
|
||||
assert!(
|
||||
leftovers.is_empty(),
|
||||
"benchmark left files in TMPDIR: {leftovers:?}"
|
||||
);
|
||||
|
||||
let bad = Command::new(env!("CARGO_BIN_EXE_curate-etl"))
|
||||
.args(["bench-parquet-bars", "0"])
|
||||
.env("TMPDIR", &tmp.0)
|
||||
.output()
|
||||
.expect("spawn curate-etl");
|
||||
assert!(!bad.status.success());
|
||||
assert!(String::from_utf8_lossy(&bad.stderr).contains("bench-parquet-bars"));
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue