From ae007b8f0e75745522c6bf8d734a700ef4b518c8 Mon Sep 17 00:00:00 2001 From: Studio Date: Sat, 28 Nov 2026 11:12:41 -0500 Subject: [PATCH 1/6] =?UTF-8?q?T-90:=20M1.2i=20=E2=80=94=20`tools/curate-e?= =?UTF-8?q?tl`:=20Zstd=20Parquet=20writer=20for=20`bars=5F1d`=20(`year=3DY?= =?UTF-8?q?YYY/part.parquet`,=20contract=20schema)=20with=20round-trip=20t?= =?UTF-8?q?ests=20and=20local=20benchmark=20(adds=20the=20`parquet`=20crat?= =?UTF-8?q?e)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cargo.lock | 190 +++- tools/curate-etl/Cargo.toml | 2 + tools/curate-etl/README.md | 54 +- tools/curate-etl/src/bench.rs | 339 ++++++ tools/curate-etl/src/cli.rs | 40 +- tools/curate-etl/src/lib.rs | 6 + tools/curate-etl/src/main.rs | 33 +- tools/curate-etl/src/parquet_bars.rs | 1544 ++++++++++++++++++++++++++ 8 files changed, 2197 insertions(+), 11 deletions(-) create mode 100644 tools/curate-etl/src/parquet_bars.rs diff --git a/Cargo.lock b/Cargo.lock index 4fc5e43f..6d77dd3a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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", +] diff --git a/tools/curate-etl/Cargo.toml b/tools/curate-etl/Cargo.toml index 39a39fe6..f397feb3 100644 --- a/tools/curate-etl/Cargo.toml +++ b/tools/curate-etl/Cargo.toml @@ -6,3 +6,5 @@ authors.workspace = true license.workspace = true [dependencies] +parquet = { version = "=60.2.0", default-features = false, features = ["zstd"] } + diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index e86c25b7..755bf94f 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -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,40 @@ 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` arena indexed by a sorted per-source `HashMap` (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 `/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 & 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. + - Every year partition writes to `part.parquet.tmp`, flushes, and calls `File::sync_all()` before any partition is renamed to `part.parquet`. On any error, all open writers are dropped and all created `part.parquet.tmp` files are removed while leaving pre-existing `part.parquet` files untouched. +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 }` + - `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=1258.64 ms`, `throughput=3972536 rows/s`, `write=175.28 MB/s`, `size=46.27 bytes/row`, `compression=1.82x` + ## Local Benchmarks ### `bench-split` @@ -290,13 +324,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=1258.64 ms`, `throughput=3972536 rows/s`, `write=175.28 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 diff --git a/tools/curate-etl/src/bench.rs b/tools/curate-etl/src/bench.rs index 26371bd4..557059e1 100644 --- a/tools/curate-etl/src/bench.rs +++ b/tools/curate-etl/src/bench.rs @@ -1,8 +1,14 @@ //! 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::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; use std::time::Instant; +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 +17,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 +33,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 +49,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 +1610,292 @@ 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() -> Result { + let seq = BENCH_TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); + let pid = std::process::id(); + let path = std::env::temp_dir().join(format!("curate-etl-bench-pq-bars-{pid}-{seq}")); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).map_err(|source| ParquetBarsError::Io { + path: path.clone(), + source, + })?; + Ok(Self { path }) + } +} + +impl Drop for BenchTempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +struct ParquetBarsBenchIter { + weekdays: Vec, + 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) -> 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 { + 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 { + 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 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::(), + Bars1dWriteOptions::default(), + )?; + let report = ParquetBarsBenchReport { + rows: 0, + read_back_rows: stats.rows_written, + 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; + + let mut read_back_rows = 0usize; + for &year in stats.rows_by_year.keys() { + let path = temp + .path + .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, + } + })?; + read_back_rows += reader.metadata().file_metadata().num_rows() as usize; + } + + 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 { + let (report, _) = run_parquet_bars_benchmark_tracked(rows)?; + Ok(report) +} + #[cfg(test)] mod tests { use super::*; @@ -1931,4 +2230,44 @@ 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); + } } diff --git a/tools/curate-etl/src/cli.rs b/tools/curate-etl/src/cli.rs index 198cfdd8..b03e400c 100644 --- a/tools/curate-etl/src/cli.rs +++ b/tools/curate-etl/src/cli.rs @@ -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 { ["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::() { + 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")); } } diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index 9a2ddd61..a0d19fb7 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -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, DEFAULT_ROW_GROUP_ROWS, DEFAULT_ZSTD_LEVEL, + MAX_PARQUET_YEAR, MIN_PARQUET_YEAR, +}; pub use provider_mapping::{ MappingRange, ProviderMappingCursor, ProviderMappingError, ProviderMappingRow, ProviderMappingTable, diff --git a/tools/curate-etl/src/main.rs b/tools/curate-etl/src/main.rs index 166ce1ed..3441e023 100644 --- a/tools/curate-etl/src/main.rs +++ b/tools/curate-etl/src/main.rs @@ -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)); diff --git a/tools/curate-etl/src/parquet_bars.rs b/tools/curate-etl/src/parquet_bars.rs new file mode 100644 index 00000000..9a5aae37 --- /dev/null +++ b/tools/curate-etl/src/parquet_bars.rs @@ -0,0 +1,1544 @@ +//! Streaming, atomic, year-partitioned Zstd Parquet writer for `bars_1d`. +//! +//! Writes `bars_1d/year=YYYY/part.parquet` files matching the 12-column contract schema in +//! `design/DATA-CONTRACTS.md` (§3A): +//! +//! 1. `listing_id` (`INT32`, `REQUIRED`) +//! 2. `ts` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`) +//! 3. `session_date` (`INT32`, `REQUIRED`, `DATE`) +//! 4. `open` (`DOUBLE`, `REQUIRED`) +//! 5. `high` (`DOUBLE`, `REQUIRED`) +//! 6. `low` (`DOUBLE`, `REQUIRED`) +//! 7. `close` (`DOUBLE`, `REQUIRED`) +//! 8. `volume` (`DOUBLE`, `REQUIRED`) +//! 9. `vwap` (`DOUBLE`, `OPTIONAL`) +//! 10. `currency` (`BYTE_ARRAY`, `REQUIRED`, `STRING`) +//! 11. `source` (`BYTE_ARRAY`, `REQUIRED`, `STRING`) +//! 12. `known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`) + +use std::borrow::{Borrow, Cow}; +use std::cmp::Ordering; +use std::collections::{BTreeMap, HashMap}; +use std::error::Error; +use std::fmt; +use std::fs::{self, File}; +use std::io::{self, BufWriter, Write}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use parquet::basic::{Compression, LogicalType, Repetition, TimeUnit, Type as PhysicalType, ZstdLevel}; +use parquet::column::writer::ColumnWriter; +use parquet::data_type::ByteArray; +use parquet::errors::ParquetError; +use parquet::file::properties::{WriterProperties, WriterPropertiesPtr}; +use parquet::file::writer::SerializedFileWriter; +use parquet::schema::types::{ColumnPath, Type, TypePtr}; + +use crate::shorts::epoch_days_to_ymd; + +/// Default maximum number of rows buffered per Parquet row group. +pub const DEFAULT_ROW_GROUP_ROWS: usize = 1_000_000; + +/// Default Zstd compression level for `bars_1d` Parquet files. +pub const DEFAULT_ZSTD_LEVEL: i32 = 3; + +/// Minimum allowed calendar year for `session_date` partitioning. +pub const MIN_PARQUET_YEAR: i32 = 1900; + +/// Maximum allowed calendar year for `session_date` partitioning. +pub const MAX_PARQUET_YEAR: i32 = 2200; + +const STRING_WRITE_BATCH_ROWS: usize = 4_096; +const FILE_BUF_CAPACITY_BYTES: usize = 64 * 1024; +const LINEAR_INTERN_LIMIT: usize = 8; + +/// Single `bars_1d` row matching the `design/DATA-CONTRACTS.md` Parquet schema. +#[derive(Debug, Clone, PartialEq)] +pub struct Bars1dParquetRow { + pub listing_id: i32, + pub ts_micros: i64, + pub session_date: i32, + pub open: f64, + pub high: f64, + pub low: f64, + pub close: f64, + pub volume: f64, + pub vwap: Option, + pub currency: Cow<'static, str>, + pub source: Cow<'static, str>, + pub known_at_micros: i64, +} + +/// Configuration for [`write_bars_1d_dataset`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Bars1dWriteOptions { + pub row_group_rows: usize, + pub zstd_level: i32, +} + +impl Default for Bars1dWriteOptions { + fn default() -> Self { + Self { + row_group_rows: DEFAULT_ROW_GROUP_ROWS, + zstd_level: DEFAULT_ZSTD_LEVEL, + } + } +} + +/// Accounting summary returned by [`write_bars_1d_dataset`]. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Bars1dWriteStats { + pub rows_written: usize, + pub files_written: usize, + pub row_groups_written: usize, + pub bytes_written: u64, + pub rows_by_year: BTreeMap, +} + +/// Typed error returned by [`write_bars_1d_dataset`]. +#[derive(Debug)] +pub enum ParquetBarsError { + InvalidRowGroupRows, + InvalidZstdLevel { + level: i32, + }, + UnsortedInput { + prev_listing_id: i32, + prev_session_date: i32, + listing_id: i32, + session_date: i32, + }, + DuplicateKey { + listing_id: i32, + session_date: i32, + }, + SessionYearOutOfRange { + listing_id: i32, + session_date: i32, + year: i32, + min_year: i32, + max_year: i32, + }, + Io { + path: PathBuf, + source: io::Error, + }, + Parquet { + path: PathBuf, + source: ParquetError, + }, +} + +impl fmt::Display for ParquetBarsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidRowGroupRows => { + write!(f, "invalid row_group_rows: must be greater than 0") + } + Self::InvalidZstdLevel { level } => { + write!(f, "invalid Zstd compression level: {level}") + } + Self::UnsortedInput { + prev_listing_id, + prev_session_date, + listing_id, + session_date, + } => write!( + f, + "unsorted input: ({listing_id}, {session_date}) follows ({prev_listing_id}, {prev_session_date})" + ), + Self::DuplicateKey { + listing_id, + session_date, + } => write!( + f, + "duplicate (listing_id, session_date) key: ({listing_id}, {session_date})" + ), + Self::SessionYearOutOfRange { + listing_id, + session_date, + year, + min_year, + max_year, + } => write!( + f, + "session_date {session_date} (year {year}) for listing_id {listing_id} is outside allowed range {min_year}..={max_year}" + ), + Self::Io { path, source } => { + write!(f, "I/O error at '{}': {source}", path.display()) + } + Self::Parquet { path, source } => { + write!(f, "Parquet error at '{}': {source}", path.display()) + } + } + } +} + +impl Error for ParquetBarsError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::Io { source, .. } => Some(source), + Self::Parquet { source, .. } => Some(source), + _ => None, + } + } +} + +/// Builds the exact 12-column Parquet schema for `bars_1d` per `design/DATA-CONTRACTS.md`. +pub fn bars_1d_parquet_schema() -> Result { + let fields: Vec = vec![ + Arc::new( + Type::primitive_type_builder("listing_id", PhysicalType::INT32) + .with_repetition(Repetition::REQUIRED) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("ts", PhysicalType::INT64) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::timestamp(true, TimeUnit::MICROS))) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("session_date", PhysicalType::INT32) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::Date)) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("open", PhysicalType::DOUBLE) + .with_repetition(Repetition::REQUIRED) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("high", PhysicalType::DOUBLE) + .with_repetition(Repetition::REQUIRED) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("low", PhysicalType::DOUBLE) + .with_repetition(Repetition::REQUIRED) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("close", PhysicalType::DOUBLE) + .with_repetition(Repetition::REQUIRED) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("volume", PhysicalType::DOUBLE) + .with_repetition(Repetition::REQUIRED) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("vwap", PhysicalType::DOUBLE) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("currency", PhysicalType::BYTE_ARRAY) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::String)) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("source", PhysicalType::BYTE_ARRAY) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::String)) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("known_at", PhysicalType::INT64) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::timestamp(true, TimeUnit::MICROS))) + .build()?, + ), + ]; + + Ok(Arc::new( + Type::group_type_builder("bars_1d") + .with_fields(fields) + .build()?, + )) +} + +fn build_writer_properties(zstd_level: ZstdLevel) -> WriterPropertiesPtr { + Arc::new( + WriterProperties::builder() + .set_compression(Compression::ZSTD(zstd_level)) + .set_column_dictionary_enabled(ColumnPath::from("currency"), true) + .set_column_dictionary_enabled(ColumnPath::from("source"), true) + .set_created_by(format!("curate-etl {}", env!("CARGO_PKG_VERSION"))) + .build(), + ) +} + +#[derive(Default)] +struct StringInterner { + values: Vec, + index: HashMap, +} + +impl StringInterner { + fn intern(&mut self, s: &str) -> u32 { + if self.values.len() <= LINEAR_INTERN_LIMIT { + let bytes = s.as_bytes(); + for (idx, existing) in self.values.iter().enumerate() { + if existing.data() == bytes { + return idx as u32; + } + } + let id = self.values.len() as u32; + self.values.push(ByteArray::from(s)); + if self.values.len() > LINEAR_INTERN_LIMIT { + self.index.reserve(self.values.len()); + for (i, val) in self.values.iter().enumerate() { + if let Ok(text) = std::str::from_utf8(val.data()) { + self.index.insert(text.to_owned(), i as u32); + } + } + } + return id; + } + + if let Some(&id) = self.index.get(s) { + return id; + } + let id = self.values.len() as u32; + self.values.push(ByteArray::from(s)); + self.index.insert(s.to_owned(), id); + id + } + + #[inline] + fn get(&self, id: u32) -> &ByteArray { + &self.values[id as usize] + } + + fn clear(&mut self) { + self.values.clear(); + self.index.clear(); + } +} + +#[derive(Default)] +struct RowGroupBuffer { + listing_id: Vec, + ts_micros: Vec, + session_date: Vec, + open: Vec, + high: Vec, + low: Vec, + close: Vec, + volume: Vec, + vwap_values: Vec, + vwap_def_levels: Vec, + currency_ids: Vec, + currency_interner: StringInterner, + source_ids: Vec, + source_interner: StringInterner, + known_at_micros: Vec, +} + +impl RowGroupBuffer { + #[inline] + fn len(&self) -> usize { + self.listing_id.len() + } + + fn push(&mut self, row: &Bars1dParquetRow) { + self.listing_id.push(row.listing_id); + self.ts_micros.push(row.ts_micros); + self.session_date.push(row.session_date); + self.open.push(row.open); + self.high.push(row.high); + self.low.push(row.low); + self.close.push(row.close); + self.volume.push(row.volume); + match row.vwap { + Some(v) => { + self.vwap_values.push(v); + self.vwap_def_levels.push(1); + } + None => { + self.vwap_def_levels.push(0); + } + } + let currency_id = self.currency_interner.intern(row.currency.as_ref()); + self.currency_ids.push(currency_id); + let source_id = self.source_interner.intern(row.source.as_ref()); + self.source_ids.push(source_id); + self.known_at_micros.push(row.known_at_micros); + } + + fn clear(&mut self) { + self.listing_id.clear(); + self.ts_micros.clear(); + self.session_date.clear(); + self.open.clear(); + self.high.clear(); + self.low.clear(); + self.close.clear(); + self.volume.clear(); + self.vwap_values.clear(); + self.vwap_def_levels.clear(); + self.currency_ids.clear(); + self.currency_interner.clear(); + self.source_ids.clear(); + self.source_interner.clear(); + self.known_at_micros.clear(); + } +} + +struct YearWriter { + tmp_path: PathBuf, + final_path: PathBuf, + writer: SerializedFileWriter>, + buf: RowGroupBuffer, + rows_written: usize, + row_groups_written: usize, +} + +impl YearWriter { + fn open( + bars_dir: &Path, + year: i32, + schema: &TypePtr, + props: &WriterPropertiesPtr, + created_tmp_paths: &mut Vec, + ) -> Result { + let year_dir = bars_dir.join(format!("year={year:04}")); + fs::create_dir_all(&year_dir).map_err(|source| ParquetBarsError::Io { + path: year_dir.clone(), + source, + })?; + + let tmp_path = year_dir.join("part.parquet.tmp"); + let final_path = year_dir.join("part.parquet"); + let file = File::create(&tmp_path).map_err(|source| ParquetBarsError::Io { + path: tmp_path.clone(), + source, + })?; + created_tmp_paths.push(tmp_path.clone()); + + let buf_writer = BufWriter::with_capacity(FILE_BUF_CAPACITY_BYTES, file); + let writer = SerializedFileWriter::new(buf_writer, schema.clone(), props.clone()).map_err( + |source| ParquetBarsError::Parquet { + path: tmp_path.clone(), + source, + }, + )?; + + Ok(Self { + tmp_path, + final_path, + writer, + buf: RowGroupBuffer::default(), + rows_written: 0, + row_groups_written: 0, + }) + } + + fn flush_row_group(&mut self, scratch: &mut Vec) -> Result<(), ParquetBarsError> { + let row_count = self.buf.len(); + if row_count == 0 { + return Ok(()); + } + + let map_pq = |source: ParquetError| ParquetBarsError::Parquet { + path: self.tmp_path.clone(), + source, + }; + + let mut rg_writer = self.writer.next_row_group().map_err(map_pq)?; + + // 1. listing_id (INT32, REQUIRED) + write_i32_col(&mut rg_writer, &self.buf.listing_id, &self.tmp_path)?; + // 2. ts (INT64, REQUIRED) + write_i64_col(&mut rg_writer, &self.buf.ts_micros, &self.tmp_path)?; + // 3. session_date (INT32, REQUIRED) + write_i32_col(&mut rg_writer, &self.buf.session_date, &self.tmp_path)?; + // 4. open (DOUBLE, REQUIRED) + write_f64_col(&mut rg_writer, &self.buf.open, None, &self.tmp_path)?; + // 5. high (DOUBLE, REQUIRED) + write_f64_col(&mut rg_writer, &self.buf.high, None, &self.tmp_path)?; + // 6. low (DOUBLE, REQUIRED) + write_f64_col(&mut rg_writer, &self.buf.low, None, &self.tmp_path)?; + // 7. close (DOUBLE, REQUIRED) + write_f64_col(&mut rg_writer, &self.buf.close, None, &self.tmp_path)?; + // 8. volume (DOUBLE, REQUIRED) + write_f64_col(&mut rg_writer, &self.buf.volume, None, &self.tmp_path)?; + // 9. vwap (DOUBLE, OPTIONAL) + write_f64_col( + &mut rg_writer, + &self.buf.vwap_values, + Some(&self.buf.vwap_def_levels), + &self.tmp_path, + )?; + // 10. currency (BYTE_ARRAY, REQUIRED) + write_interned_str_col( + &mut rg_writer, + &self.buf.currency_ids, + &self.buf.currency_interner, + scratch, + &self.tmp_path, + )?; + // 11. source (BYTE_ARRAY, REQUIRED) + write_interned_str_col( + &mut rg_writer, + &self.buf.source_ids, + &self.buf.source_interner, + scratch, + &self.tmp_path, + )?; + // 12. known_at (INT64, REQUIRED) + write_i64_col(&mut rg_writer, &self.buf.known_at_micros, &self.tmp_path)?; + + rg_writer.close().map_err(map_pq)?; + + self.rows_written += row_count; + self.row_groups_written += 1; + self.buf.clear(); + Ok(()) + } + + fn finish_and_sync(mut self, scratch: &mut Vec) -> Result { + self.flush_row_group(scratch)?; + + let mut buf_writer = self + .writer + .into_inner() + .map_err(|source| ParquetBarsError::Parquet { + path: self.tmp_path.clone(), + source, + })?; + buf_writer.flush().map_err(|source| ParquetBarsError::Io { + path: self.tmp_path.clone(), + source, + })?; + let file = buf_writer + .into_inner() + .map_err(|err| ParquetBarsError::Io { + path: self.tmp_path.clone(), + source: err.into_error(), + })?; + file.sync_all().map_err(|source| ParquetBarsError::Io { + path: self.tmp_path.clone(), + source, + })?; + let bytes = file + .metadata() + .map_err(|source| ParquetBarsError::Io { + path: self.tmp_path.clone(), + source, + })? + .len(); + drop(file); + + Ok(SyncedYearFile { + tmp_path: self.tmp_path, + final_path: self.final_path, + rows_written: self.rows_written, + row_groups_written: self.row_groups_written, + bytes, + }) + } +} + +struct SyncedYearFile { + tmp_path: PathBuf, + final_path: PathBuf, + rows_written: usize, + row_groups_written: usize, + bytes: u64, +} + +fn next_column<'a>( + rg_writer: &'a mut parquet::file::writer::SerializedRowGroupWriter<'_, BufWriter>, + path: &Path, +) -> Result, ParquetBarsError> { + match rg_writer.next_column() { + Ok(Some(col)) => Ok(col), + Ok(None) => Err(ParquetBarsError::Parquet { + path: path.to_path_buf(), + source: ParquetError::General("unexpected end of Parquet schema columns".to_string()), + }), + Err(source) => Err(ParquetBarsError::Parquet { + path: path.to_path_buf(), + source, + }), + } +} + +fn write_i32_col( + rg_writer: &mut parquet::file::writer::SerializedRowGroupWriter<'_, BufWriter>, + values: &[i32], + path: &Path, +) -> Result<(), ParquetBarsError> { + let mut col = next_column(rg_writer, path)?; + match col.untyped() { + ColumnWriter::Int32ColumnWriter(typed) => { + typed + .write_batch(values, None, None) + .map_err(|source| ParquetBarsError::Parquet { + path: path.to_path_buf(), + source, + })?; + } + _ => { + return Err(ParquetBarsError::Parquet { + path: path.to_path_buf(), + source: ParquetError::General("expected INT32 column writer".to_string()), + }); + } + } + col.close().map_err(|source| ParquetBarsError::Parquet { + path: path.to_path_buf(), + source, + }) +} + +fn write_i64_col( + rg_writer: &mut parquet::file::writer::SerializedRowGroupWriter<'_, BufWriter>, + values: &[i64], + path: &Path, +) -> Result<(), ParquetBarsError> { + let mut col = next_column(rg_writer, path)?; + match col.untyped() { + ColumnWriter::Int64ColumnWriter(typed) => { + typed + .write_batch(values, None, None) + .map_err(|source| ParquetBarsError::Parquet { + path: path.to_path_buf(), + source, + })?; + } + _ => { + return Err(ParquetBarsError::Parquet { + path: path.to_path_buf(), + source: ParquetError::General("expected INT64 column writer".to_string()), + }); + } + } + col.close().map_err(|source| ParquetBarsError::Parquet { + path: path.to_path_buf(), + source, + }) +} + +fn write_f64_col( + rg_writer: &mut parquet::file::writer::SerializedRowGroupWriter<'_, BufWriter>, + values: &[f64], + def_levels: Option<&[i16]>, + path: &Path, +) -> Result<(), ParquetBarsError> { + let mut col = next_column(rg_writer, path)?; + match col.untyped() { + ColumnWriter::DoubleColumnWriter(typed) => { + typed + .write_batch(values, def_levels, None) + .map_err(|source| ParquetBarsError::Parquet { + path: path.to_path_buf(), + source, + })?; + } + _ => { + return Err(ParquetBarsError::Parquet { + path: path.to_path_buf(), + source: ParquetError::General("expected DOUBLE column writer".to_string()), + }); + } + } + col.close().map_err(|source| ParquetBarsError::Parquet { + path: path.to_path_buf(), + source, + }) +} + +fn write_interned_str_col( + rg_writer: &mut parquet::file::writer::SerializedRowGroupWriter<'_, BufWriter>, + ids: &[u32], + interner: &StringInterner, + scratch: &mut Vec, + path: &Path, +) -> Result<(), ParquetBarsError> { + let mut col = next_column(rg_writer, path)?; + match col.untyped() { + ColumnWriter::ByteArrayColumnWriter(typed) => { + for chunk in ids.chunks(STRING_WRITE_BATCH_ROWS) { + scratch.clear(); + for &id in chunk { + scratch.push(interner.get(id).clone()); + } + typed + .write_batch(scratch, None, None) + .map_err(|source| ParquetBarsError::Parquet { + path: path.to_path_buf(), + source, + })?; + } + } + _ => { + return Err(ParquetBarsError::Parquet { + path: path.to_path_buf(), + source: ParquetError::General("expected BYTE_ARRAY column writer".to_string()), + }); + } + } + col.close().map_err(|source| ParquetBarsError::Parquet { + path: path.to_path_buf(), + source, + }) +} + +fn cleanup_temp_files(tmp_paths: &[PathBuf]) { + for path in tmp_paths { + let _ = fs::remove_file(path); + } +} + +/// Streams strictly ascending `(listing_id, session_date)` rows into year-partitioned Zstd +/// Parquet files at `/bars_1d/year=YYYY/part.parquet`. +/// +/// # Atomicity +/// Every year partition is written to `part.parquet.tmp`, flushed, and `sync_all`'d before any +/// partition is renamed to `part.parquet`. On any validation, Parquet, or I/O error, all open +/// writers are closed and all created `.tmp` files are removed, leaving pre-existing +/// `part.parquet` files untouched. +pub fn write_bars_1d_dataset( + out_dir: P, + rows: I, + options: Bars1dWriteOptions, +) -> Result +where + P: AsRef, + I: IntoIterator, + R: Borrow, +{ + if options.row_group_rows == 0 { + return Err(ParquetBarsError::InvalidRowGroupRows); + } + let zstd_level = ZstdLevel::try_new(options.zstd_level).map_err(|_| { + ParquetBarsError::InvalidZstdLevel { + level: options.zstd_level, + } + })?; + + let out_dir = out_dir.as_ref(); + let bars_dir = out_dir.join("bars_1d"); + let schema = bars_1d_parquet_schema().map_err(|source| ParquetBarsError::Parquet { + path: bars_dir.clone(), + source, + })?; + let props = build_writer_properties(zstd_level); + + let mut writers: BTreeMap = BTreeMap::new(); + let mut created_tmp_paths: Vec = Vec::new(); + let mut scratch: Vec = Vec::with_capacity(STRING_WRITE_BATCH_ROWS); + + let write_result: Result, ParquetBarsError> = (|| { + let mut prev_key: Option<(i32, i32)> = None; + + for item in rows { + let row = item.borrow(); + if let Some((prev_listing_id, prev_session_date)) = prev_key { + match (row.listing_id, row.session_date).cmp(&(prev_listing_id, prev_session_date)) + { + Ordering::Equal => { + return Err(ParquetBarsError::DuplicateKey { + listing_id: row.listing_id, + session_date: row.session_date, + }); + } + Ordering::Less => { + return Err(ParquetBarsError::UnsortedInput { + prev_listing_id, + prev_session_date, + listing_id: row.listing_id, + session_date: row.session_date, + }); + } + Ordering::Greater => {} + } + } + prev_key = Some((row.listing_id, row.session_date)); + + let (year, _, _) = epoch_days_to_ymd(row.session_date); + if !(MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR).contains(&year) { + return Err(ParquetBarsError::SessionYearOutOfRange { + listing_id: row.listing_id, + session_date: row.session_date, + year, + min_year: MIN_PARQUET_YEAR, + max_year: MAX_PARQUET_YEAR, + }); + } + + let yw = match writers.entry(year) { + std::collections::btree_map::Entry::Occupied(entry) => entry.into_mut(), + std::collections::btree_map::Entry::Vacant(entry) => { + let opened = YearWriter::open( + &bars_dir, + year, + &schema, + &props, + &mut created_tmp_paths, + )?; + entry.insert(opened) + } + }; + + yw.buf.push(row); + if yw.buf.len() == options.row_group_rows { + yw.flush_row_group(&mut scratch)?; + } + } + + let mut synced = Vec::with_capacity(writers.len()); + let drained: Vec<(i32, YearWriter)> = std::mem::take(&mut writers).into_iter().collect(); + for (year, yw) in drained { + let file = yw.finish_and_sync(&mut scratch)?; + synced.push((year, file)); + } + Ok(synced) + })(); + + let synced_files = match write_result { + Ok(files) => files, + Err(err) => { + // Drop all open writers before unlinking temporary files. + drop(writers); + cleanup_temp_files(&created_tmp_paths); + return Err(err); + } + }; + + let mut stats = Bars1dWriteStats::default(); + for (year, file) in synced_files { + if let Err(source) = fs::rename(&file.tmp_path, &file.final_path) { + cleanup_temp_files(&created_tmp_paths); + return Err(ParquetBarsError::Io { + path: file.final_path, + source, + }); + } + stats.rows_written += file.rows_written; + stats.files_written += 1; + stats.row_groups_written += file.row_groups_written; + stats.bytes_written += file.bytes; + stats.rows_by_year.insert(year, file.rows_written); + } + + Ok(stats) +} + +#[cfg(test)] +mod tests { + use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; + + use parquet::basic::ConvertedType; + use parquet::column::reader::ColumnReader; + use parquet::file::reader::{FileReader, SerializedFileReader}; + + use super::*; + use crate::split::ymd_to_epoch_days; + + static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0); + + struct TempDirGuard { + path: PathBuf, + } + + impl TempDirGuard { + fn new(label: &str) -> Self { + let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); + let pid = std::process::id(); + let path = std::env::temp_dir().join(format!("curate-etl-pq-test-{label}-{pid}-{seq}")); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create test temp dir"); + Self { path } + } + + fn path(&self) -> &Path { + &self.path + } + } + + impl Drop for TempDirGuard { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } + } + + fn make_row( + listing_id: i32, + year: i32, + month: u32, + day: u32, + close: f64, + volume: f64, + vwap: Option, + currency: &'static str, + source: &'static str, + ) -> Bars1dParquetRow { + let session_date = ymd_to_epoch_days(year, month, day).expect("valid date"); + 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; + Bars1dParquetRow { + listing_id, + ts_micros, + session_date, + open: close - 0.5, + high: close + 1.25, + low: close - 1.0, + close, + volume, + vwap, + currency: Cow::Borrowed(currency), + source: Cow::Borrowed(source), + known_at_micros, + } + } + + fn read_parquet_rows(path: &Path) -> Vec { + let file = File::open(path).expect("open parquet file"); + let reader = SerializedFileReader::new(file).expect("open parquet reader"); + let metadata = reader.metadata(); + let mut out = Vec::new(); + + for rg_idx in 0..metadata.num_row_groups() { + let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); + let num_rows = metadata.row_group(rg_idx).num_rows() as usize; + + let listing_id = read_i32_col(rg_reader.get_column_reader(0).unwrap(), num_rows); + let ts_micros = read_i64_col(rg_reader.get_column_reader(1).unwrap(), num_rows); + let session_date = read_i32_col(rg_reader.get_column_reader(2).unwrap(), num_rows); + let open = read_req_f64_col(rg_reader.get_column_reader(3).unwrap(), num_rows); + let high = read_req_f64_col(rg_reader.get_column_reader(4).unwrap(), num_rows); + let low = read_req_f64_col(rg_reader.get_column_reader(5).unwrap(), num_rows); + let close = read_req_f64_col(rg_reader.get_column_reader(6).unwrap(), num_rows); + let volume = read_req_f64_col(rg_reader.get_column_reader(7).unwrap(), num_rows); + let vwap = read_opt_f64_col(rg_reader.get_column_reader(8).unwrap(), num_rows); + let currency = read_str_col(rg_reader.get_column_reader(9).unwrap(), num_rows); + let source = read_str_col(rg_reader.get_column_reader(10).unwrap(), num_rows); + let known_at_micros = read_i64_col(rg_reader.get_column_reader(11).unwrap(), num_rows); + + for i in 0..num_rows { + out.push(Bars1dParquetRow { + listing_id: listing_id[i], + ts_micros: ts_micros[i], + session_date: session_date[i], + open: open[i], + high: high[i], + low: low[i], + close: close[i], + volume: volume[i], + vwap: vwap[i], + currency: Cow::Owned(currency[i].clone()), + source: Cow::Owned(source[i].clone()), + known_at_micros: known_at_micros[i], + }); + } + } + out + } + + fn read_i32_col(reader: ColumnReader, expected: usize) -> Vec { + let mut values = Vec::with_capacity(expected); + match reader { + ColumnReader::Int32ColumnReader(mut r) => { + let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap(); + assert_eq!(records, expected); + } + _ => panic!("expected Int32ColumnReader"), + } + values + } + + fn read_i64_col(reader: ColumnReader, expected: usize) -> Vec { + let mut values = Vec::with_capacity(expected); + match reader { + ColumnReader::Int64ColumnReader(mut r) => { + let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap(); + assert_eq!(records, expected); + } + _ => panic!("expected Int64ColumnReader"), + } + values + } + + fn read_req_f64_col(reader: ColumnReader, expected: usize) -> Vec { + let mut values = Vec::with_capacity(expected); + match reader { + ColumnReader::DoubleColumnReader(mut r) => { + let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap(); + assert_eq!(records, expected); + } + _ => panic!("expected DoubleColumnReader"), + } + values + } + + fn read_opt_f64_col(reader: ColumnReader, expected: usize) -> Vec> { + let mut raw_values = Vec::with_capacity(expected); + let mut def_levels = Vec::with_capacity(expected); + match reader { + ColumnReader::DoubleColumnReader(mut r) => { + let (records, _, levels) = r + .read_records(expected, Some(&mut def_levels), None, &mut raw_values) + .unwrap(); + assert_eq!(records, expected); + assert_eq!(levels, expected); + } + _ => panic!("expected DoubleColumnReader"), + } + let mut out = Vec::with_capacity(expected); + let mut val_idx = 0usize; + for lvl in def_levels { + if lvl == 1 { + out.push(Some(raw_values[val_idx])); + val_idx += 1; + } else { + out.push(None); + } + } + assert_eq!(val_idx, raw_values.len()); + out + } + + fn read_str_col(reader: ColumnReader, expected: usize) -> Vec { + let mut values = Vec::with_capacity(expected); + match reader { + ColumnReader::ByteArrayColumnReader(mut r) => { + let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap(); + assert_eq!(records, expected); + } + _ => panic!("expected ByteArrayColumnReader"), + } + values + .into_iter() + .map(|ba| String::from_utf8(ba.data().to_vec()).expect("valid utf8")) + .collect() + } + + fn assert_row_bitwise_eq(actual: &Bars1dParquetRow, expected: &Bars1dParquetRow) { + assert_eq!(actual.listing_id, expected.listing_id); + assert_eq!(actual.ts_micros, expected.ts_micros); + assert_eq!(actual.session_date, expected.session_date); + assert_eq!(actual.open.to_bits(), expected.open.to_bits()); + assert_eq!(actual.high.to_bits(), expected.high.to_bits()); + assert_eq!(actual.low.to_bits(), expected.low.to_bits()); + assert_eq!(actual.close.to_bits(), expected.close.to_bits()); + assert_eq!(actual.volume.to_bits(), expected.volume.to_bits()); + assert_eq!( + actual.vwap.map(f64::to_bits), + expected.vwap.map(f64::to_bits) + ); + assert_eq!(actual.currency, expected.currency); + assert_eq!(actual.source, expected.source); + assert_eq!(actual.known_at_micros, expected.known_at_micros); + } + + #[test] + fn round_trip_three_years_preserves_bitwise_values_and_order() { + let tmp = TempDirGuard::new("round-trip"); + let rows = vec![ + make_row(1, 2022, 6, 15, 100.25, 0.0, None, "USD", "eod_unadj"), + make_row(1, 2023, 3, 10, 112.50, 1_234_567.0, Some(112.42), "USD", "eod_unadj"), + make_row(1, 2024, 11, 1, 145.75, 987_654.0, Some(145.10), "USD", "qm_raw"), + make_row(2, 2022, 12, 30, 12.10, 50_000.0, Some(12.05), "CAD", "eod_unadj"), + make_row(2, 2024, 1, 2, 15.80, 0.0, None, "CAD", "eod_unadj"), + make_row(7, 2023, 7, 4, 42.00, 10_500.0, None, "USD", "ib_live"), + ]; + + let stats = + write_bars_1d_dataset(tmp.path(), &rows, Bars1dWriteOptions::default()).unwrap(); + assert_eq!(stats.rows_written, rows.len()); + assert_eq!(stats.files_written, 3); + assert_eq!(stats.row_groups_written, 3); + assert!(stats.bytes_written > 0); + assert_eq!(stats.rows_by_year.get(&2022), Some(&2)); + assert_eq!(stats.rows_by_year.get(&2023), Some(&2)); + assert_eq!(stats.rows_by_year.get(&2024), Some(&2)); + + for year in [2022, 2023, 2024] { + let path = tmp + .path() + .join(format!("bars_1d/year={year:04}/part.parquet")); + assert!(path.exists(), "expected {}", path.display()); + assert!( + !tmp.path() + .join(format!("bars_1d/year={year:04}/part.parquet.tmp")) + .exists() + ); + + let expected_year_rows: Vec<&Bars1dParquetRow> = rows + .iter() + .filter(|r| epoch_days_to_ymd(r.session_date).0 == year) + .collect(); + let actual_year_rows = read_parquet_rows(&path); + assert_eq!(actual_year_rows.len(), expected_year_rows.len()); + for (actual, expected) in actual_year_rows.iter().zip(expected_year_rows.iter()) { + assert_row_bitwise_eq(actual, expected); + assert!(actual.volume.is_sign_positive()); + assert!(actual.currency.is_ascii()); + assert!(actual.source.is_ascii()); + } + } + } + + #[test] + fn metadata_matches_contract_schema_and_zstd_compression() { + let tmp = TempDirGuard::new("schema"); + let rows = vec![ + make_row(10, 2024, 5, 20, 55.0, 250_000.0, Some(54.8), "USD", "eod_unadj"), + make_row(10, 2024, 5, 21, 56.0, 300_000.0, None, "CAD", "eod_unadj"), + ]; + + write_bars_1d_dataset(tmp.path(), &rows, Bars1dWriteOptions::default()).unwrap(); + + let path = tmp.path().join("bars_1d/year=2024/part.parquet"); + let file = File::open(&path).unwrap(); + let reader = SerializedFileReader::new(file).unwrap(); + let file_meta = reader.metadata().file_metadata(); + let schema = file_meta.schema_descr(); + + assert_eq!(schema.name(), "bars_1d"); + assert_eq!(schema.num_columns(), 12); + + let expected: [(&str, PhysicalType, Repetition, Option, ConvertedType); 12] = [ + ( + "listing_id", + PhysicalType::INT32, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "ts", + PhysicalType::INT64, + Repetition::REQUIRED, + Some(LogicalType::timestamp(true, TimeUnit::MICROS)), + ConvertedType::TIMESTAMP_MICROS, + ), + ( + "session_date", + PhysicalType::INT32, + Repetition::REQUIRED, + Some(LogicalType::Date), + ConvertedType::DATE, + ), + ( + "open", + PhysicalType::DOUBLE, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "high", + PhysicalType::DOUBLE, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "low", + PhysicalType::DOUBLE, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "close", + PhysicalType::DOUBLE, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "volume", + PhysicalType::DOUBLE, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "vwap", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "currency", + PhysicalType::BYTE_ARRAY, + Repetition::REQUIRED, + Some(LogicalType::String), + ConvertedType::UTF8, + ), + ( + "source", + PhysicalType::BYTE_ARRAY, + Repetition::REQUIRED, + Some(LogicalType::String), + ConvertedType::UTF8, + ), + ( + "known_at", + PhysicalType::INT64, + Repetition::REQUIRED, + Some(LogicalType::timestamp(true, TimeUnit::MICROS)), + ConvertedType::TIMESTAMP_MICROS, + ), + ]; + + for (idx, (name, phys, rep, logical, converted)) in expected.iter().enumerate() { + let col = schema.column(idx); + let field = col.self_type(); + assert_eq!(col.name(), *name, "column {idx} name mismatch"); + assert_eq!(col.physical_type(), *phys, "column {name} physical type"); + assert_eq!( + field.get_basic_info().repetition(), + *rep, + "column {name} repetition" + ); + assert_eq!( + field.get_basic_info().logical_type_ref(), + logical.as_ref(), + "column {name} logical type" + ); + assert_eq!( + field.get_basic_info().converted_type(), + *converted, + "column {name} converted type" + ); + } + + assert_eq!(reader.metadata().num_row_groups(), 1); + let rg = reader.metadata().row_group(0); + for col_idx in 0..12 { + let chunk = rg.column(col_idx); + assert!( + matches!(chunk.compression(), Compression::ZSTD(_)), + "column {col_idx} must use ZSTD compression, got {:?}", + chunk.compression() + ); + } + } + + #[test] + fn partitioning_splits_dec31_and_jan01_and_omits_empty_years() { + let tmp = TempDirGuard::new("partition"); + let rows = vec![ + make_row(1, 2020, 12, 31, 10.0, 100.0, None, "USD", "eod_unadj"), + make_row(1, 2021, 1, 1, 10.5, 200.0, None, "USD", "eod_unadj"), + make_row(1, 2023, 6, 1, 12.0, 300.0, None, "USD", "eod_unadj"), + ]; + + let stats = + write_bars_1d_dataset(tmp.path(), &rows, Bars1dWriteOptions::default()).unwrap(); + assert_eq!(stats.files_written, 3); + assert!(tmp.path().join("bars_1d/year=2020/part.parquet").exists()); + assert!(tmp.path().join("bars_1d/year=2021/part.parquet").exists()); + assert!(!tmp.path().join("bars_1d/year=2022").exists()); + assert!(tmp.path().join("bars_1d/year=2023/part.parquet").exists()); + + assert_eq!( + read_parquet_rows(&tmp.path().join("bars_1d/year=2020/part.parquet")).len(), + 1 + ); + assert_eq!( + read_parquet_rows(&tmp.path().join("bars_1d/year=2021/part.parquet")).len(), + 1 + ); + assert_eq!( + read_parquet_rows(&tmp.path().join("bars_1d/year=2023/part.parquet")).len(), + 1 + ); + } + + #[test] + fn row_groups_split_exact_sizes() { + let tmp = TempDirGuard::new("row-groups"); + let base_date = ymd_to_epoch_days(2024, 1, 2).unwrap(); + let mut rows = Vec::with_capacity(2_500); + for listing_id in 1..=25 { + for day_offset in 0..100 { + let session_date = base_date + day_offset; + let ts_micros = i64::from(session_date) * 86_400_000_000; + rows.push(Bars1dParquetRow { + listing_id, + ts_micros, + session_date, + open: 20.0, + high: 21.0, + low: 19.5, + close: 20.5, + volume: 10_000.0, + vwap: Some(20.25), + currency: Cow::Borrowed("USD"), + source: Cow::Borrowed("eod_unadj"), + known_at_micros: ts_micros, + }); + } + } + + let options = Bars1dWriteOptions { + row_group_rows: 1_000, + zstd_level: DEFAULT_ZSTD_LEVEL, + }; + let stats = write_bars_1d_dataset(tmp.path(), &rows, options).unwrap(); + assert_eq!(stats.rows_written, 2_500); + assert_eq!(stats.files_written, 1); + assert_eq!(stats.row_groups_written, 3); + + let file = File::open(tmp.path().join("bars_1d/year=2024/part.parquet")).unwrap(); + let reader = SerializedFileReader::new(file).unwrap(); + assert_eq!(reader.metadata().num_row_groups(), 3); + assert_eq!(reader.metadata().row_group(0).num_rows(), 1_000); + assert_eq!(reader.metadata().row_group(1).num_rows(), 1_000); + assert_eq!(reader.metadata().row_group(2).num_rows(), 500); + } + + #[test] + fn empty_input_returns_zero_stats_and_creates_nothing() { + let tmp = TempDirGuard::new("empty"); + let empty: Vec = Vec::new(); + let stats = + write_bars_1d_dataset(tmp.path(), &empty, Bars1dWriteOptions::default()).unwrap(); + assert_eq!(stats, Bars1dWriteStats::default()); + assert!(!tmp.path().join("bars_1d").exists()); + } + + #[test] + fn writing_same_rows_twice_is_byte_identical() { + let tmp_a = TempDirGuard::new("det-a"); + let tmp_b = TempDirGuard::new("det-b"); + let rows = vec![ + make_row(1, 2023, 2, 1, 10.0, 1_000.0, Some(10.0), "USD", "eod_unadj"), + make_row(1, 2024, 2, 1, 11.0, 2_000.0, None, "USD", "eod_unadj"), + make_row(2, 2023, 2, 1, 20.0, 3_000.0, Some(19.9), "CAD", "qm_raw"), + make_row(2, 2024, 2, 1, 21.0, 4_000.0, None, "CAD", "qm_raw"), + ]; + + let stats_a = + write_bars_1d_dataset(tmp_a.path(), &rows, Bars1dWriteOptions::default()).unwrap(); + let stats_b = + write_bars_1d_dataset(tmp_b.path(), &rows, Bars1dWriteOptions::default()).unwrap(); + assert_eq!(stats_a, stats_b); + + for year in [2023, 2024] { + let bytes_a = + fs::read(tmp_a.path().join(format!("bars_1d/year={year:04}/part.parquet"))) + .unwrap(); + let bytes_b = + fs::read(tmp_b.path().join(format!("bars_1d/year={year:04}/part.parquet"))) + .unwrap(); + assert_eq!(bytes_a, bytes_b, "year {year} parquet bytes must match"); + } + } + + #[test] + fn failure_modes_return_typed_errors_and_preserve_existing_files() { + let tmp = TempDirGuard::new("failures"); + + // Seed a valid existing 2024 partition. + let initial = vec![make_row( + 1, + 2024, + 1, + 2, + 100.0, + 5_000.0, + Some(99.5), + "USD", + "eod_unadj", + )]; + write_bars_1d_dataset(tmp.path(), &initial, Bars1dWriteOptions::default()).unwrap(); + let existing_path = tmp.path().join("bars_1d/year=2024/part.parquet"); + let existing_tmp = tmp.path().join("bars_1d/year=2024/part.parquet.tmp"); + let original_bytes = fs::read(&existing_path).unwrap(); + + // 1. Invalid row_group_rows = 0 + let err = write_bars_1d_dataset( + tmp.path(), + &initial, + Bars1dWriteOptions { + row_group_rows: 0, + zstd_level: DEFAULT_ZSTD_LEVEL, + }, + ) + .unwrap_err(); + assert!(matches!(err, ParquetBarsError::InvalidRowGroupRows)); + assert!(!existing_tmp.exists()); + assert_eq!(fs::read(&existing_path).unwrap(), original_bytes); + + // 2. Invalid Zstd level + let err = write_bars_1d_dataset( + tmp.path(), + &initial, + Bars1dWriteOptions { + row_group_rows: 100, + zstd_level: 99, + }, + ) + .unwrap_err(); + assert!(matches!( + err, + ParquetBarsError::InvalidZstdLevel { level: 99 } + )); + assert!(!existing_tmp.exists()); + assert_eq!(fs::read(&existing_path).unwrap(), original_bytes); + + // 3. Unsorted input (after writing a valid row into 2024) + let unsorted = vec![ + make_row(2, 2024, 5, 1, 50.0, 100.0, None, "USD", "eod_unadj"), + make_row(1, 2024, 5, 2, 51.0, 200.0, None, "USD", "eod_unadj"), + ]; + let err = write_bars_1d_dataset(tmp.path(), &unsorted, Bars1dWriteOptions::default()) + .unwrap_err(); + assert!(matches!( + err, + ParquetBarsError::UnsortedInput { + prev_listing_id: 2, + listing_id: 1, + .. + } + )); + assert!(!existing_tmp.exists()); + assert_eq!(fs::read(&existing_path).unwrap(), original_bytes); + + // 4. Duplicate (listing_id, session_date) + let dup = vec![ + make_row(1, 2024, 6, 3, 50.0, 100.0, None, "USD", "eod_unadj"), + make_row(1, 2024, 6, 3, 50.0, 100.0, None, "USD", "eod_unadj"), + ]; + let err = + write_bars_1d_dataset(tmp.path(), &dup, Bars1dWriteOptions::default()).unwrap_err(); + assert!(matches!( + err, + ParquetBarsError::DuplicateKey { listing_id: 1, .. } + )); + assert!(!existing_tmp.exists()); + assert_eq!(fs::read(&existing_path).unwrap(), original_bytes); + + // 5. Session year out of range (< 1900 and > 2200) + let too_old = vec![ + make_row(1, 2024, 1, 2, 10.0, 100.0, None, "USD", "eod_unadj"), + make_row(2, 1899, 12, 31, 10.0, 100.0, None, "USD", "eod_unadj"), + ]; + let err = write_bars_1d_dataset(tmp.path(), &too_old, Bars1dWriteOptions::default()) + .unwrap_err(); + assert!(matches!( + err, + ParquetBarsError::SessionYearOutOfRange { + listing_id: 2, + year: 1899, + min_year: MIN_PARQUET_YEAR, + max_year: MAX_PARQUET_YEAR, + .. + } + )); + assert!(!existing_tmp.exists()); + assert_eq!(fs::read(&existing_path).unwrap(), original_bytes); + + let too_new = vec![make_row( + 3, + 2201, + 1, + 1, + 10.0, + 100.0, + None, + "USD", + "eod_unadj", + )]; + let err = write_bars_1d_dataset(tmp.path(), &too_new, Bars1dWriteOptions::default()) + .unwrap_err(); + assert!(matches!( + err, + ParquetBarsError::SessionYearOutOfRange { + listing_id: 3, + year: 2201, + .. + } + )); + assert!(!existing_tmp.exists()); + assert_eq!(fs::read(&existing_path).unwrap(), original_bytes); + + // 6. Unwritable out_dir (path is an existing regular file) + let blocker_file = tmp.path().join("not-a-dir"); + fs::write(&blocker_file, b"file-content").unwrap(); + let err = + write_bars_1d_dataset(&blocker_file, &initial, Bars1dWriteOptions::default()) + .unwrap_err(); + assert!(matches!(err, ParquetBarsError::Io { .. })); + assert_eq!(fs::read(&blocker_file).unwrap(), b"file-content"); + assert_eq!(fs::read(&existing_path).unwrap(), original_bytes); + + // 7. Mid-stream failure after flushing a full row group across multiple years + let multi_year_fail = vec![ + make_row(1, 2023, 6, 1, 10.0, 100.0, None, "USD", "eod_unadj"), + make_row(1, 2024, 6, 1, 11.0, 200.0, None, "USD", "eod_unadj"), + make_row(2, 2024, 6, 1, 12.0, 300.0, None, "USD", "eod_unadj"), + // Out-of-order after year=2024 already flushed a 2-row group to part.parquet.tmp + make_row(2, 2023, 6, 1, 13.0, 400.0, None, "USD", "eod_unadj"), + ]; + let err = write_bars_1d_dataset( + tmp.path(), + &multi_year_fail, + Bars1dWriteOptions { + row_group_rows: 2, + zstd_level: DEFAULT_ZSTD_LEVEL, + }, + ) + .unwrap_err(); + assert!(matches!(err, ParquetBarsError::UnsortedInput { .. })); + assert!(!tmp.path().join("bars_1d/year=2023/part.parquet.tmp").exists()); + assert!(!tmp.path().join("bars_1d/year=2023/part.parquet").exists()); + assert!(!existing_tmp.exists()); + assert_eq!(fs::read(&existing_path).unwrap(), original_bytes); + } + + #[test] + fn string_interner_handles_more_than_linear_limit_distinct_values() { + let tmp = TempDirGuard::new("many-strings"); + let currencies = [ + "USD", "CAD", "EUR", "GBP", "JPY", "CHF", "AUD", "NZD", "SEK", "NOK", "HKD", "SGD", + ]; + let mut rows = Vec::with_capacity(currencies.len() * 2); + for (i, &ccy) in currencies.iter().enumerate() { + rows.push(make_row( + (i + 1) as i32, + 2024, + 3, + 1, + 10.0 + i as f64, + 1_000.0, + None, + ccy, + "eod_unadj", + )); + rows.push(make_row( + (i + 1) as i32, + 2024, + 3, + 2, + 11.0 + i as f64, + 2_000.0, + Some(10.5 + i as f64), + ccy, + "qm_raw", + )); + } + + let stats = + write_bars_1d_dataset(tmp.path(), &rows, Bars1dWriteOptions::default()).unwrap(); + assert_eq!(stats.rows_written, rows.len()); + let read_back = read_parquet_rows(&tmp.path().join("bars_1d/year=2024/part.parquet")); + assert_eq!(read_back.len(), rows.len()); + for (actual, expected) in read_back.iter().zip(rows.iter()) { + assert_row_bitwise_eq(actual, expected); + } + } +} From 62f47cf3e898d77b2ffffbd44c8943ddbd19a710 Mon Sep 17 00:00:00 2001 From: Studio Date: Sat, 28 Nov 2026 11:24:10 -0500 Subject: [PATCH 2/6] =?UTF-8?q?T-90:=20M1.2i=20=E2=80=94=20`tools/curate-e?= =?UTF-8?q?tl`:=20Zstd=20Parquet=20writer=20for=20`bars=5F1d`=20(`year=3DY?= =?UTF-8?q?YYY/part.parquet`,=20contract=20schema)=20with=20round-trip=20t?= =?UTF-8?q?ests=20and=20local=20benchmark=20(adds=20the=20`parquet`=20crat?= =?UTF-8?q?e)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/README.md | 8 +- tools/curate-etl/src/bench.rs | 174 +++++++-- tools/curate-etl/src/parquet_bars.rs | 521 +++++++++++++++++++++++++-- 3 files changed, 650 insertions(+), 53 deletions(-) diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index 755bf94f..0c4c0f70 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -193,9 +193,9 @@ Rules: - 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 & atomicity rules:** +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. - - Every year partition writes to `part.parquet.tmp`, flushes, and calls `File::sync_all()` before any partition is renamed to `part.parquet`. On any error, all open writers are dropped and all created `part.parquet.tmp` files are removed while leaving pre-existing `part.parquet` files untouched. + - Concurrent writers targeting the same `/bars_1d` directory are serialized via an in-process per-dataset mutex and an exclusive `.write.lock` file. Every year partition writes to an exclusively created per-run staging file (`part.parquet..tmp`), flushes, and calls `File::sync_all()` before publication. During publication, pre-existing `part.parquet` files are backed up until every partition rename succeeds; on any error, all open writers are dropped, replaced partitions are restored from backup, newly published partitions are removed, and only staging files owned by the current run are unlinked. 4. **Typed errors (`ParquetBarsError`):** - `InvalidRowGroupRows` (`row_group_rows == 0`) - `InvalidZstdLevel { level }` @@ -208,7 +208,7 @@ Rules: - 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=1258.64 ms`, `throughput=3972536 rows/s`, `write=175.28 MB/s`, `size=46.27 bytes/row`, `compression=1.82x` + - Perf: `elapsed=1432.74 ms`, `throughput=3489815 rows/s`, `write=153.98 MB/s`, `size=46.27 bytes/row`, `compression=1.82x` ## Local Benchmarks @@ -336,7 +336,7 @@ Command (`2026-11-28`): `cargo run --release -p curate-etl --offline -- bench-pa - Input: `rows=5000000`, `listings=2000`, `raw_row_bytes=84` - Output: `files=20`, `row_groups=20`, `bytes=231330139`, `read_back_rows=5000000` -- Perf: `elapsed=1258.64 ms`, `throughput=3972536 rows/s`, `write=175.28 MB/s`, `size=46.27 bytes/row`, `compression=1.82x` +- Perf: `elapsed=1432.74 ms`, `throughput=3489815 rows/s`, `write=153.98 MB/s`, `size=46.27 bytes/row`, `compression=1.82x` ## Deferred Follow-Ups (`M1.3+` / `M2`) diff --git a/tools/curate-etl/src/bench.rs b/tools/curate-etl/src/bench.rs index 557059e1..4ab31613 100644 --- a/tools/curate-etl/src/bench.rs +++ b/tools/curate-etl/src/bench.rs @@ -3,10 +3,12 @@ use std::borrow::Cow; use std::fs::{self, File}; use std::hint::black_box; -use std::path::PathBuf; +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}; @@ -1634,16 +1636,30 @@ struct BenchTempDir { } impl BenchTempDir { - fn new() -> Result { - let seq = BENCH_TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); + fn new_in(base: &Path) -> Result { let pid = std::process::id(); - let path = std::env::temp_dir().join(format!("curate-etl-bench-pq-bars-{pid}-{seq}")); - let _ = fs::remove_dir_all(&path); - fs::create_dir_all(&path).map_err(|source| ParquetBarsError::Io { - path: path.clone(), - source, - })?; - Ok(Self { path }) + 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::new_in(&std::env::temp_dir()) } } @@ -1796,6 +1812,53 @@ fn collect_bench_weekdays_2006_2025() -> Vec { days } +fn verify_parquet_bars_row_count( + out_dir: &Path, + years: impl IntoIterator, + expected_rows: usize, +) -> Result { + 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> { @@ -1808,9 +1871,11 @@ fn run_parquet_bars_benchmark_tracked( std::iter::empty::(), 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: stats.rows_written, + read_back_rows, listing_count: 0, files_written: stats.files_written, row_groups_written: stats.row_groups_written, @@ -1835,24 +1900,19 @@ fn run_parquet_bars_benchmark_tracked( let elapsed_secs = start.elapsed().as_secs_f64(); let elapsed_ms = elapsed_secs * 1_000.0; - let mut read_back_rows = 0usize; - for &year in stats.rows_by_year.keys() { - let path = temp - .path - .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, - } - })?; - read_back_rows += reader.metadata().file_metadata().num_rows() as usize; + 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 @@ -2270,4 +2330,64 @@ mod tests { 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"); + } } diff --git a/tools/curate-etl/src/parquet_bars.rs b/tools/curate-etl/src/parquet_bars.rs index 9a5aae37..1530654c 100644 --- a/tools/curate-etl/src/parquet_bars.rs +++ b/tools/curate-etl/src/parquet_bars.rs @@ -21,10 +21,13 @@ use std::cmp::Ordering; use std::collections::{BTreeMap, HashMap}; use std::error::Error; use std::fmt; -use std::fs::{self, File}; +use std::fs::{self, File, OpenOptions}; use std::io::{self, BufWriter, Write}; use std::path::{Path, PathBuf}; -use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; +use std::sync::{Arc, Mutex, OnceLock}; +use std::thread; +use std::time::Duration; use parquet::basic::{Compression, LogicalType, Repetition, TimeUnit, Type as PhysicalType, ZstdLevel}; use parquet::column::writer::ColumnWriter; @@ -389,6 +392,127 @@ impl RowGroupBuffer { } } +static DATASET_LOCKS: OnceLock>>>> = OnceLock::new(); +static WRITE_RUN_SEQ: AtomicU64 = AtomicU64::new(0); + +fn dataset_mutex(bars_dir: &Path) -> Arc> { + let key = fs::canonicalize(bars_dir).unwrap_or_else(|_| bars_dir.to_path_buf()); + let map_mutex = DATASET_LOCKS.get_or_init(|| Mutex::new(HashMap::new())); + let mut map = map_mutex.lock().unwrap_or_else(|err| err.into_inner()); + map.entry(key) + .or_insert_with(|| Arc::new(Mutex::new(()))) + .clone() +} + +struct DatasetFileLock { + path: PathBuf, +} + +impl DatasetFileLock { + fn acquire(bars_dir: &Path) -> Result { + let lock_path = bars_dir.join(".write.lock"); + let mut backoff_ms = 2u64; + loop { + match OpenOptions::new() + .write(true) + .create_new(true) + .open(&lock_path) + { + Ok(mut file) => { + let _ = writeln!(file, "{}", std::process::id()); + let _ = file.sync_all(); + return Ok(Self { path: lock_path }); + } + Err(err) if err.kind() == io::ErrorKind::AlreadyExists => { + thread::sleep(Duration::from_millis(backoff_ms)); + backoff_ms = (backoff_ms * 2).min(25); + } + Err(source) => { + return Err(ParquetBarsError::Io { + path: lock_path, + source, + }); + } + } + } + } +} + +impl Drop for DatasetFileLock { + fn drop(&mut self) { + let _ = fs::remove_file(&self.path); + } +} + +fn next_run_id() -> String { + let seq = WRITE_RUN_SEQ.fetch_add(1, AtomicOrdering::Relaxed); + format!("{}-{seq}", std::process::id()) +} + +fn create_exclusive_tmp_file( + year_dir: &Path, + run_id: &str, +) -> Result<(PathBuf, File), ParquetBarsError> { + for attempt in 0..1024u32 { + let file_name = if attempt == 0 { + format!("part.parquet.{run_id}.tmp") + } else { + format!("part.parquet.{run_id}.{attempt}.tmp") + }; + let tmp_path = year_dir.join(file_name); + match OpenOptions::new() + .write(true) + .create_new(true) + .open(&tmp_path) + { + Ok(file) => return Ok((tmp_path, file)), + Err(err) if err.kind() == io::ErrorKind::AlreadyExists => continue, + Err(source) => { + return Err(ParquetBarsError::Io { + path: tmp_path, + source, + }); + } + } + } + Err(ParquetBarsError::Io { + path: year_dir.join(format!("part.parquet.{run_id}.tmp")), + source: io::Error::new( + io::ErrorKind::AlreadyExists, + "exhausted unique staging file names", + ), + }) +} + +fn choose_unique_backup_path(final_path: &Path, run_id: &str) -> Result { + let parent = final_path.parent().unwrap_or_else(|| Path::new(".")); + for attempt in 0..1024u32 { + let file_name = if attempt == 0 { + format!("part.parquet.{run_id}.bak") + } else { + format!("part.parquet.{run_id}.{attempt}.bak") + }; + let bak_path = parent.join(file_name); + match fs::symlink_metadata(&bak_path) { + Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(bak_path), + Ok(_) => continue, + Err(source) => { + return Err(ParquetBarsError::Io { + path: bak_path, + source, + }); + } + } + } + Err(ParquetBarsError::Io { + path: parent.join(format!("part.parquet.{run_id}.bak")), + source: io::Error::new( + io::ErrorKind::AlreadyExists, + "exhausted unique backup file names", + ), + }) +} + struct YearWriter { tmp_path: PathBuf, final_path: PathBuf, @@ -402,9 +526,10 @@ impl YearWriter { fn open( bars_dir: &Path, year: i32, + run_id: &str, schema: &TypePtr, props: &WriterPropertiesPtr, - created_tmp_paths: &mut Vec, + owned_tmp_paths: &mut Vec, ) -> Result { let year_dir = bars_dir.join(format!("year={year:04}")); fs::create_dir_all(&year_dir).map_err(|source| ParquetBarsError::Io { @@ -412,13 +537,9 @@ impl YearWriter { source, })?; - let tmp_path = year_dir.join("part.parquet.tmp"); + let (tmp_path, file) = create_exclusive_tmp_file(&year_dir, run_id)?; + owned_tmp_paths.push(tmp_path.clone()); let final_path = year_dir.join("part.parquet"); - let file = File::create(&tmp_path).map_err(|source| ParquetBarsError::Io { - path: tmp_path.clone(), - source, - })?; - created_tmp_paths.push(tmp_path.clone()); let buf_writer = BufWriter::with_capacity(FILE_BUF_CAPACITY_BYTES, file); let writer = SerializedFileWriter::new(buf_writer, schema.clone(), props.clone()).map_err( @@ -690,20 +811,41 @@ fn write_interned_str_col( }) } -fn cleanup_temp_files(tmp_paths: &[PathBuf]) { - for path in tmp_paths { +fn cleanup_owned_files(owned_paths: &[PathBuf]) { + for path in owned_paths { let _ = fs::remove_file(path); } } +struct PublishedPartition { + final_path: PathBuf, + backup_path: Option, +} + +fn rollback_published(published: &[PublishedPartition]) { + for part in published.iter().rev() { + match &part.backup_path { + Some(bak) => { + let _ = fs::rename(bak, &part.final_path); + } + None => { + let _ = fs::remove_file(&part.final_path); + } + } + } +} + /// Streams strictly ascending `(listing_id, session_date)` rows into year-partitioned Zstd /// Parquet files at `/bars_1d/year=YYYY/part.parquet`. /// -/// # Atomicity -/// Every year partition is written to `part.parquet.tmp`, flushed, and `sync_all`'d before any -/// partition is renamed to `part.parquet`. On any validation, Parquet, or I/O error, all open -/// writers are closed and all created `.tmp` files are removed, leaving pre-existing -/// `part.parquet` files untouched. +/// # Concurrency & Atomicity +/// Concurrent writers targeting the same `/bars_1d` directory are serialized via an +/// in-process per-dataset mutex and an exclusive `.write.lock` file. Every year partition is +/// written to an exclusively created per-run staging file (`part.parquet..tmp`), flushed, +/// and `sync_all`'d before publication. During publication, pre-existing `part.parquet` files +/// are moved to per-run backups until every partition rename succeeds; on any error, all open +/// writers are dropped, replaced partitions are restored from backup, newly published partitions +/// are removed, and only staging files owned by the current run are unlinked. pub fn write_bars_1d_dataset( out_dir: P, rows: I, @@ -723,6 +865,24 @@ where } })?; + let mut row_iter = rows.into_iter(); + let Some(first_item) = row_iter.next() else { + return Ok(Bars1dWriteStats::default()); + }; + { + let first_row = first_item.borrow(); + let (first_year, _, _) = epoch_days_to_ymd(first_row.session_date); + if !(MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR).contains(&first_year) { + return Err(ParquetBarsError::SessionYearOutOfRange { + listing_id: first_row.listing_id, + session_date: first_row.session_date, + year: first_year, + min_year: MIN_PARQUET_YEAR, + max_year: MAX_PARQUET_YEAR, + }); + } + } + let out_dir = out_dir.as_ref(); let bars_dir = out_dir.join("bars_1d"); let schema = bars_1d_parquet_schema().map_err(|source| ParquetBarsError::Parquet { @@ -731,14 +891,27 @@ where })?; let props = build_writer_properties(zstd_level); + fs::create_dir_all(&bars_dir).map_err(|source| ParquetBarsError::Io { + path: bars_dir.clone(), + source, + })?; + + // Serialize writers targeting the same dataset directory across threads and processes. + // Drop order guarantees `.write.lock` is removed while `_in_process_guard` is still held, + // and only after all staging/publication/rollback work has finished. + let dataset_mu = dataset_mutex(&bars_dir); + let _in_process_guard = dataset_mu.lock().unwrap_or_else(|err| err.into_inner()); + let _file_lock = DatasetFileLock::acquire(&bars_dir)?; + + let run_id = next_run_id(); let mut writers: BTreeMap = BTreeMap::new(); - let mut created_tmp_paths: Vec = Vec::new(); + let mut owned_tmp_paths: Vec = Vec::new(); let mut scratch: Vec = Vec::with_capacity(STRING_WRITE_BATCH_ROWS); let write_result: Result, ParquetBarsError> = (|| { let mut prev_key: Option<(i32, i32)> = None; - for item in rows { + for item in std::iter::once(first_item).chain(row_iter) { let row = item.borrow(); if let Some((prev_listing_id, prev_session_date)) = prev_key { match (row.listing_id, row.session_date).cmp(&(prev_listing_id, prev_session_date)) @@ -779,9 +952,10 @@ where let opened = YearWriter::open( &bars_dir, year, + &run_id, &schema, &props, - &mut created_tmp_paths, + &mut owned_tmp_paths, )?; entry.insert(opened) } @@ -805,22 +979,66 @@ where let synced_files = match write_result { Ok(files) => files, Err(err) => { - // Drop all open writers before unlinking temporary files. + // Drop all open writers before unlinking temporary files owned by this run. drop(writers); - cleanup_temp_files(&created_tmp_paths); + cleanup_owned_files(&owned_tmp_paths); return Err(err); } }; let mut stats = Bars1dWriteStats::default(); + let mut published: Vec = Vec::with_capacity(synced_files.len()); for (year, file) in synced_files { + let backup_path = match fs::symlink_metadata(&file.final_path) { + Ok(meta) if !meta.is_dir() => { + let bak = match choose_unique_backup_path(&file.final_path, &run_id) { + Ok(path) => path, + Err(err) => { + rollback_published(&published); + cleanup_owned_files(&owned_tmp_paths); + return Err(err); + } + }; + if let Err(source) = fs::rename(&file.final_path, &bak) { + rollback_published(&published); + cleanup_owned_files(&owned_tmp_paths); + return Err(ParquetBarsError::Io { + path: file.final_path, + source, + }); + } + Some(bak) + } + // Directory occupying final_path: leave it in place so the rename below fails + // cleanly and triggers rollback of all earlier partitions. + Ok(_) => None, + Err(err) if err.kind() == io::ErrorKind::NotFound => None, + Err(source) => { + rollback_published(&published); + cleanup_owned_files(&owned_tmp_paths); + return Err(ParquetBarsError::Io { + path: file.final_path, + source, + }); + } + }; + if let Err(source) = fs::rename(&file.tmp_path, &file.final_path) { - cleanup_temp_files(&created_tmp_paths); + if let Some(bak) = backup_path { + let _ = fs::rename(&bak, &file.final_path); + } + rollback_published(&published); + cleanup_owned_files(&owned_tmp_paths); return Err(ParquetBarsError::Io { path: file.final_path, source, }); } + + published.push(PublishedPartition { + final_path: file.final_path, + backup_path, + }); stats.rows_written += file.rows_written; stats.files_written += 1; stats.row_groups_written += file.row_groups_written; @@ -828,6 +1046,12 @@ where stats.rows_by_year.insert(year, file.rows_written); } + for part in &published { + if let Some(bak) = &part.backup_path { + let _ = fs::remove_file(bak); + } + } + Ok(stats) } @@ -869,6 +1093,7 @@ mod tests { } } + #[allow(clippy::too_many_arguments)] fn make_row( listing_id: i32, year: i32, @@ -1498,6 +1723,258 @@ mod tests { assert!(!tmp.path().join("bars_1d/year=2023/part.parquet").exists()); assert!(!existing_tmp.exists()); assert_eq!(fs::read(&existing_path).unwrap(), original_bytes); + assert_no_transient_files(&tmp.path().join("bars_1d")); + } + + fn assert_no_transient_files(bars_dir: &Path) { + if !bars_dir.exists() { + return; + } + assert!( + !bars_dir.join(".write.lock").exists(), + "stale .write.lock left in {}", + bars_dir.display() + ); + for entry in fs::read_dir(bars_dir).expect("read bars_dir") { + let entry = entry.expect("bars_dir entry"); + let path = entry.path(); + if path.is_dir() { + for sub in fs::read_dir(&path).expect("read year dir") { + let sub = sub.expect("year dir entry"); + let name = sub.file_name(); + let name_str = name.to_string_lossy(); + assert!( + !name_str.ends_with(".tmp") && !name_str.ends_with(".bak"), + "stale transient file left behind: {}", + sub.path().display() + ); + } + } + } + } + + #[test] + fn publication_rename_failure_rolls_back_replaced_and_new_partitions() { + let tmp = TempDirGuard::new("rename-rollback"); + + // Seed an existing 2023 partition. + let initial_2023 = vec![make_row( + 1, + 2023, + 5, + 10, + 75.0, + 10_000.0, + Some(74.8), + "USD", + "eod_unadj", + )]; + write_bars_1d_dataset(tmp.path(), &initial_2023, Bars1dWriteOptions::default()).unwrap(); + let path_2023 = tmp.path().join("bars_1d/year=2023/part.parquet"); + let original_2023_bytes = fs::read(&path_2023).unwrap(); + + // Occupy 2024's final path with a directory so the third partition's rename fails + // after 2022 (new) and 2023 (replaced) have already been renamed into place. + let blocker_2024 = tmp.path().join("bars_1d/year=2024/part.parquet"); + fs::create_dir_all(&blocker_2024).unwrap(); + + let refresh = vec![ + make_row(1, 2022, 6, 1, 50.0, 1_000.0, None, "USD", "eod_unadj"), + make_row(1, 2023, 6, 1, 99.0, 2_000.0, Some(98.5), "USD", "eod_unadj"), + make_row(1, 2024, 6, 1, 120.0, 3_000.0, None, "USD", "eod_unadj"), + ]; + + let err = write_bars_1d_dataset(tmp.path(), &refresh, Bars1dWriteOptions::default()) + .unwrap_err(); + assert!( + matches!(&err, ParquetBarsError::Io { path, .. } if path == &blocker_2024), + "expected Io error at {}, got {err:?}", + blocker_2024.display() + ); + + // Newly published 2022 partition must be removed on rollback. + assert!( + !tmp.path().join("bars_1d/year=2022/part.parquet").exists(), + "newly published 2022 partition must be rolled back" + ); + // Existing 2023 partition must be restored byte-for-byte from backup. + assert_eq!( + fs::read(&path_2023).unwrap(), + original_2023_bytes, + "existing 2023 partition must be restored byte-identical" + ); + // Occupying directory at 2024 must remain untouched. + assert!(blocker_2024.is_dir()); + assert_no_transient_files(&tmp.path().join("bars_1d")); + } + + #[test] + fn overlapping_writers_serialize_without_corruption_or_mixed_generations() { + use std::sync::mpsc; + + let tmp = TempDirGuard::new("overlap"); + let out_dir = tmp.path().to_path_buf(); + + let rows_a = vec![ + make_row(1, 2023, 3, 1, 100.0, 1_000.0, Some(100.0), "USD", "eod_unadj"), + make_row(1, 2024, 3, 1, 101.0, 1_100.0, Some(101.0), "USD", "eod_unadj"), + make_row(2, 2023, 3, 1, 102.0, 1_200.0, None, "CAD", "eod_unadj"), + make_row(2, 2024, 3, 1, 103.0, 1_300.0, None, "CAD", "eod_unadj"), + ]; + let rows_b = vec![ + make_row(1, 2023, 4, 1, 200.0, 2_000.0, Some(200.0), "USD", "qm_raw"), + make_row(1, 2024, 4, 1, 201.0, 2_100.0, Some(201.0), "USD", "qm_raw"), + make_row(2, 2023, 4, 1, 202.0, 2_200.0, None, "CAD", "qm_raw"), + make_row(2, 2024, 4, 1, 203.0, 2_300.0, None, "CAD", "qm_raw"), + ]; + + struct SignalingIter { + rows: std::vec::IntoIter, + seen: usize, + on_second: Option>, + on_end: Option>, + } + + impl Iterator for SignalingIter { + type Item = Bars1dParquetRow; + fn next(&mut self) -> Option { + self.seen += 1; + if self.seen == 2 { + if let Some(cb) = self.on_second.take() { + cb(); + } + } + let item = self.rows.next(); + if item.is_none() { + if let Some(cb) = self.on_end.take() { + cb(); + } + } + item + } + } + + let events = Arc::new(Mutex::new(Vec::<&'static str>::new())); + let (t1_locked_tx, t1_locked_rx) = mpsc::channel::<()>(); + let (t2_started_tx, t2_started_rx) = mpsc::channel::<()>(); + + let out_dir_1 = out_dir.clone(); + let events_1 = Arc::clone(&events); + let events_1_end = Arc::clone(&events); + let rows_a_clone = rows_a.clone(); + let handle_1 = thread::spawn(move || { + let iter = SignalingIter { + rows: rows_a_clone.into_iter(), + seen: 0, + on_second: Some(Box::new(move || { + events_1.lock().unwrap().push("t1_row2"); + let _ = t1_locked_tx.send(()); + // Wait briefly for thread 2 to enter write_bars_1d_dataset and block on lock. + let _ = t2_started_rx.recv_timeout(Duration::from_secs(2)); + thread::sleep(Duration::from_millis(30)); + })), + on_end: Some(Box::new(move || { + events_1_end.lock().unwrap().push("t1_iter_end"); + })), + }; + write_bars_1d_dataset(&out_dir_1, iter, Bars1dWriteOptions::default()) + }); + + let out_dir_2 = out_dir.clone(); + let events_2 = Arc::clone(&events); + let rows_b_clone = rows_b.clone(); + let handle_2 = thread::spawn(move || { + t1_locked_rx.recv_timeout(Duration::from_secs(2)).unwrap(); + let _ = t2_started_tx.send(()); + let iter = SignalingIter { + rows: rows_b_clone.into_iter(), + seen: 0, + on_second: Some(Box::new(move || { + events_2.lock().unwrap().push("t2_row2"); + })), + on_end: None, + }; + write_bars_1d_dataset(&out_dir_2, iter, Bars1dWriteOptions::default()) + }); + + let stats_1 = handle_1.join().unwrap().unwrap(); + let stats_2 = handle_2.join().unwrap().unwrap(); + assert_eq!(stats_1.rows_written, rows_a.len()); + assert_eq!(stats_2.rows_written, rows_b.len()); + + // Thread 1 must have finished its entire stream before Thread 2 could pull row 2 under the lock. + let recorded = events.lock().unwrap(); + let pos_t1_end = recorded + .iter() + .position(|&e| e == "t1_iter_end") + .expect("t1_iter_end recorded"); + let pos_t2_row2 = recorded + .iter() + .position(|&e| e == "t2_row2") + .expect("t2_row2 recorded"); + assert!( + pos_t1_end < pos_t2_row2, + "expected strict serialization, got events: {recorded:?}" + ); + + // Final on-disk partitions must match Thread 2 across all years (no mixed generations). + for year in [2023, 2024] { + let actual = read_parquet_rows( + &out_dir.join(format!("bars_1d/year={year:04}/part.parquet")), + ); + let expected: Vec<&Bars1dParquetRow> = rows_b + .iter() + .filter(|r| epoch_days_to_ymd(r.session_date).0 == year) + .collect(); + assert_eq!(actual.len(), expected.len()); + for (a, e) in actual.iter().zip(expected.iter()) { + assert_row_bitwise_eq(a, e); + } + } + assert_no_transient_files(&out_dir.join("bars_1d")); + } + + #[test] + fn exclusive_staging_and_cleanup_preserve_unowned_tmp_files() { + let tmp = TempDirGuard::new("unowned-tmp"); + let year_dir = tmp.path().join("bars_1d/year=2024"); + fs::create_dir_all(&year_dir).unwrap(); + + let foreign_tmp_1 = year_dir.join("part.parquet.tmp"); + let foreign_tmp_2 = year_dir.join("part.parquet.foreign.tmp"); + fs::write(&foreign_tmp_1, b"foreign-staging-1").unwrap(); + fs::write(&foreign_tmp_2, b"foreign-staging-2").unwrap(); + + // Failing run must clean up only its own staging file and never touch unowned .tmp files. + let unsorted = vec![ + make_row(2, 2024, 5, 1, 50.0, 100.0, None, "USD", "eod_unadj"), + make_row(1, 2024, 5, 2, 51.0, 200.0, None, "USD", "eod_unadj"), + ]; + let err = write_bars_1d_dataset(tmp.path(), &unsorted, Bars1dWriteOptions::default()) + .unwrap_err(); + assert!(matches!(err, ParquetBarsError::UnsortedInput { .. })); + assert_eq!(fs::read(&foreign_tmp_1).unwrap(), b"foreign-staging-1"); + assert_eq!(fs::read(&foreign_tmp_2).unwrap(), b"foreign-staging-2"); + + // Succeeding run must also preserve unowned .tmp files and leave only part.parquet + foreign files. + let valid = vec![make_row( + 1, + 2024, + 5, + 1, + 50.0, + 100.0, + None, + "USD", + "eod_unadj", + )]; + write_bars_1d_dataset(tmp.path(), &valid, Bars1dWriteOptions::default()).unwrap(); + assert_eq!(fs::read(&foreign_tmp_1).unwrap(), b"foreign-staging-1"); + assert_eq!(fs::read(&foreign_tmp_2).unwrap(), b"foreign-staging-2"); + assert_eq!( + read_parquet_rows(&year_dir.join("part.parquet")).len(), + 1 + ); } #[test] From fd943851b48a7827847ea87b19dbefbb517917aa Mon Sep 17 00:00:00 2001 From: Studio Date: Sat, 28 Nov 2026 11:32:43 -0500 Subject: [PATCH 3/6] =?UTF-8?q?T-90:=20M1.2i=20=E2=80=94=20`tools/curate-e?= =?UTF-8?q?tl`:=20Zstd=20Parquet=20writer=20for=20`bars=5F1d`=20(`year=3DY?= =?UTF-8?q?YYY/part.parquet`,=20contract=20schema)=20with=20round-trip=20t?= =?UTF-8?q?ests=20and=20local=20benchmark=20(adds=20the=20`parquet`=20crat?= =?UTF-8?q?e)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/README.md | 8 +- tools/curate-etl/src/lib.rs | 4 +- tools/curate-etl/src/parquet_bars.rs | 445 ++++++++++++++++++++++++--- 3 files changed, 410 insertions(+), 47 deletions(-) diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index 0c4c0f70..f067bedc 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -195,20 +195,22 @@ Rules: - Deterministic `created_by` metadata so identical inputs produce byte-identical `part.parquet` files. 3. **Sort, concurrency & atomicity rules:** - Input must already be sorted strictly ascending by `(listing_id, session_date)`; within each year file rows remain in `(listing_id, session_date)` order. - - Concurrent writers targeting the same `/bars_1d` directory are serialized via an in-process per-dataset mutex and an exclusive `.write.lock` file. Every year partition writes to an exclusively created per-run staging file (`part.parquet..tmp`), flushes, and calls `File::sync_all()` before publication. During publication, pre-existing `part.parquet` files are backed up until every partition rename succeeds; on any error, all open writers are dropped, replaced partitions are restored from backup, newly published partitions are removed, and only staging files owned by the current run are unlinked. + - Concurrent writers targeting the same `/bars_1d` directory are serialized via an in-process per-dataset mutex and a bounded-wait exclusive `.write.lock` file (30 s default timeout returning `ParquetBarsError::LockTimeout` with the lock path if a crashed process left a stale lock behind). Every year partition writes to an exclusively created per-run staging file (`part.parquet..tmp`), flushes, and calls `File::sync_all()` before publication. During publication, pre-existing `part.parquet` files are backed up in place (hard link with exclusive copy fallback) so the live path remains readable until replaced by a single atomic `rename`; on any error, all open writers are dropped, replaced partitions are restored from backup, newly published partitions are removed (reporting any rollback failures alongside the original error via `RollbackFailed`), and only staging files owned by the current run are unlinked. 4. **Typed errors (`ParquetBarsError`):** - `InvalidRowGroupRows` (`row_group_rows == 0`) - `InvalidZstdLevel { level }` - `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=1432.74 ms`, `throughput=3489815 rows/s`, `write=153.98 MB/s`, `size=46.27 bytes/row`, `compression=1.82x` + - Perf: `elapsed=1422.27 ms`, `throughput=3515517 rows/s`, `write=155.11 MB/s`, `size=46.27 bytes/row`, `compression=1.82x` ## Local Benchmarks @@ -336,7 +338,7 @@ Command (`2026-11-28`): `cargo run --release -p curate-etl --offline -- bench-pa - Input: `rows=5000000`, `listings=2000`, `raw_row_bytes=84` - Output: `files=20`, `row_groups=20`, `bytes=231330139`, `read_back_rows=5000000` -- Perf: `elapsed=1432.74 ms`, `throughput=3489815 rows/s`, `write=153.98 MB/s`, `size=46.27 bytes/row`, `compression=1.82x` +- 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`) diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index a0d19fb7..6efd8878 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -39,8 +39,8 @@ pub use fx::{ }; pub use parquet_bars::{ bars_1d_parquet_schema, write_bars_1d_dataset, Bars1dParquetRow, Bars1dWriteOptions, - Bars1dWriteStats, ParquetBarsError, DEFAULT_ROW_GROUP_ROWS, DEFAULT_ZSTD_LEVEL, - MAX_PARQUET_YEAR, MIN_PARQUET_YEAR, + Bars1dWriteStats, ParquetBarsError, RollbackFailure, DEFAULT_ROW_GROUP_ROWS, + DEFAULT_ZSTD_LEVEL, MAX_PARQUET_YEAR, MIN_PARQUET_YEAR, }; pub use provider_mapping::{ MappingRange, ProviderMappingCursor, ProviderMappingError, ProviderMappingRow, diff --git a/tools/curate-etl/src/parquet_bars.rs b/tools/curate-etl/src/parquet_bars.rs index 1530654c..72c73db3 100644 --- a/tools/curate-etl/src/parquet_bars.rs +++ b/tools/curate-etl/src/parquet_bars.rs @@ -27,7 +27,7 @@ use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; use std::sync::{Arc, Mutex, OnceLock}; use std::thread; -use std::time::Duration; +use std::time::{Duration, Instant}; use parquet::basic::{Compression, LogicalType, Repetition, TimeUnit, Type as PhysicalType, ZstdLevel}; use parquet::column::writer::ColumnWriter; @@ -54,6 +54,7 @@ pub const MAX_PARQUET_YEAR: i32 = 2200; const STRING_WRITE_BATCH_ROWS: usize = 4_096; const FILE_BUF_CAPACITY_BYTES: usize = 64 * 1024; const LINEAR_INTERN_LIMIT: usize = 8; +const DEFAULT_LOCK_TIMEOUT: Duration = Duration::from_secs(30); /// Single `bars_1d` row matching the `design/DATA-CONTRACTS.md` Parquet schema. #[derive(Debug, Clone, PartialEq)] @@ -98,6 +99,34 @@ pub struct Bars1dWriteStats { pub rows_by_year: BTreeMap, } +/// Single failure encountered while rolling back a partial publication. +#[derive(Debug)] +pub struct RollbackFailure { + pub final_path: PathBuf, + pub backup_path: Option, + pub source: io::Error, +} + +impl fmt::Display for RollbackFailure { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match &self.backup_path { + Some(bak) => write!( + f, + "partition '{}' (backup '{}'): {}", + self.final_path.display(), + bak.display(), + self.source + ), + None => write!( + f, + "partition '{}': {}", + self.final_path.display(), + self.source + ), + } + } +} + /// Typed error returned by [`write_bars_1d_dataset`]. #[derive(Debug)] pub enum ParquetBarsError { @@ -122,6 +151,14 @@ pub enum ParquetBarsError { min_year: i32, max_year: i32, }, + LockTimeout { + path: PathBuf, + waited: Duration, + }, + RollbackFailed { + cause: Box, + failures: Vec, + }, Io { path: PathBuf, source: io::Error, @@ -167,6 +204,23 @@ impl fmt::Display for ParquetBarsError { f, "session_date {session_date} (year {year}) for listing_id {listing_id} is outside allowed range {min_year}..={max_year}" ), + Self::LockTimeout { path, waited } => write!( + f, + "timed out after {}ms waiting for dataset write lock '{}' (if no writer is active, remove the stale lock file and retry)", + waited.as_millis(), + path.display() + ), + Self::RollbackFailed { cause, failures } => { + write!( + f, + "publication failed ({cause}) and rollback encountered {} error(s) requiring manual recovery:", + failures.len() + )?; + for failure in failures { + write!(f, " [{failure}]")?; + } + Ok(()) + } Self::Io { path, source } => { write!(f, "I/O error at '{}': {source}", path.display()) } @@ -180,6 +234,7 @@ impl fmt::Display for ParquetBarsError { impl Error for ParquetBarsError { fn source(&self) -> Option<&(dyn Error + 'static)> { match self { + Self::RollbackFailed { cause, .. } => Some(cause.as_ref()), Self::Io { source, .. } => Some(source), Self::Parquet { source, .. } => Some(source), _ => None, @@ -409,8 +464,9 @@ struct DatasetFileLock { } impl DatasetFileLock { - fn acquire(bars_dir: &Path) -> Result { + fn acquire_with_timeout(bars_dir: &Path, timeout: Duration) -> Result { let lock_path = bars_dir.join(".write.lock"); + let start = Instant::now(); let mut backoff_ms = 2u64; loop { match OpenOptions::new() @@ -424,7 +480,15 @@ impl DatasetFileLock { return Ok(Self { path: lock_path }); } Err(err) if err.kind() == io::ErrorKind::AlreadyExists => { - thread::sleep(Duration::from_millis(backoff_ms)); + let elapsed = start.elapsed(); + if elapsed >= timeout { + return Err(ParquetBarsError::LockTimeout { + path: lock_path, + waited: elapsed, + }); + } + let remaining = timeout.saturating_sub(elapsed); + thread::sleep(Duration::from_millis(backoff_ms).min(remaining)); backoff_ms = (backoff_ms * 2).min(25); } Err(source) => { @@ -484,7 +548,36 @@ fn create_exclusive_tmp_file( }) } -fn choose_unique_backup_path(final_path: &Path, run_id: &str) -> Result { +fn is_hard_link_unsupported(err: &io::Error) -> bool { + matches!( + err.kind(), + io::ErrorKind::Unsupported | io::ErrorKind::PermissionDenied + ) +} + +fn copy_to_exclusive_backup(src: &Path, dst: &Path) -> io::Result<()> { + let mut dst_file = OpenOptions::new().write(true).create_new(true).open(dst)?; + let copy_res = (|| -> io::Result<()> { + let mut src_file = File::open(src)?; + io::copy(&mut src_file, &mut dst_file)?; + dst_file.sync_all()?; + Ok(()) + })(); + if let Err(err) = copy_res { + drop(dst_file); + let _ = fs::remove_file(dst); + return Err(err); + } + Ok(()) +} + +/// Creates a per-run rollback backup of `final_path` while keeping `final_path` intact on disk. +/// Uses an atomic hard link in the same directory when supported, falling back to an exclusive +/// file copy so readers never observe a missing `part.parquet` before replacement. +fn create_backup_preserving_live( + final_path: &Path, + run_id: &str, +) -> Result { let parent = final_path.parent().unwrap_or_else(|| Path::new(".")); for attempt in 0..1024u32 { let file_name = if attempt == 0 { @@ -493,9 +586,21 @@ fn choose_unique_backup_path(final_path: &Path, run_id: &str) -> Result return Ok(bak_path), - Ok(_) => continue, + match fs::hard_link(final_path, &bak_path) { + Ok(()) => return Ok(bak_path), + Err(err) if err.kind() == io::ErrorKind::AlreadyExists => continue, + Err(err) if is_hard_link_unsupported(&err) => { + match copy_to_exclusive_backup(final_path, &bak_path) { + Ok(()) => return Ok(bak_path), + Err(copy_err) if copy_err.kind() == io::ErrorKind::AlreadyExists => continue, + Err(source) => { + return Err(ParquetBarsError::Io { + path: bak_path, + source, + }); + } + } + } Err(source) => { return Err(ParquetBarsError::Io { path: bak_path, @@ -822,17 +927,53 @@ struct PublishedPartition { backup_path: Option, } -fn rollback_published(published: &[PublishedPartition]) { +fn rollback_published(published: &[PublishedPartition]) -> Vec { + let mut failures = Vec::new(); for part in published.iter().rev() { match &part.backup_path { Some(bak) => { - let _ = fs::rename(bak, &part.final_path); + if let Err(source) = fs::rename(bak, &part.final_path) { + failures.push(RollbackFailure { + final_path: part.final_path.clone(), + backup_path: Some(bak.clone()), + source, + }); + } } None => { - let _ = fs::remove_file(&part.final_path); + if let Err(source) = fs::remove_file(&part.final_path) { + failures.push(RollbackFailure { + final_path: part.final_path.clone(), + backup_path: None, + source, + }); + } } } } + failures +} + +fn finish_with_rollback( + cause: ParquetBarsError, + published: &[PublishedPartition], + extra_failure: Option, + owned_tmp_paths: &[PathBuf], +) -> ParquetBarsError { + let mut failures = Vec::new(); + if let Some(failure) = extra_failure { + failures.push(failure); + } + failures.extend(rollback_published(published)); + cleanup_owned_files(owned_tmp_paths); + if failures.is_empty() { + cause + } else { + ParquetBarsError::RollbackFailed { + cause: Box::new(cause), + failures, + } + } } /// Streams strictly ascending `(listing_id, session_date)` rows into year-partitioned Zstd @@ -840,12 +981,14 @@ fn rollback_published(published: &[PublishedPartition]) { /// /// # Concurrency & Atomicity /// Concurrent writers targeting the same `/bars_1d` directory are serialized via an -/// in-process per-dataset mutex and an exclusive `.write.lock` file. Every year partition is -/// written to an exclusively created per-run staging file (`part.parquet..tmp`), flushed, -/// and `sync_all`'d before publication. During publication, pre-existing `part.parquet` files -/// are moved to per-run backups until every partition rename succeeds; on any error, all open -/// writers are dropped, replaced partitions are restored from backup, newly published partitions -/// are removed, and only staging files owned by the current run are unlinked. +/// in-process per-dataset mutex and a bounded-wait exclusive `.write.lock` file. Every year +/// partition is written to an exclusively created per-run staging file (`part.parquet..tmp`), +/// flushed, and `sync_all`'d before publication. During publication, pre-existing `part.parquet` +/// files are backed up in place (via hard link, or 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 (with any rollback failures reported alongside the original error), and only staging +/// files owned by the current run are unlinked. pub fn write_bars_1d_dataset( out_dir: P, rows: I, @@ -855,6 +998,28 @@ where P: AsRef, I: IntoIterator, R: Borrow, +{ + write_bars_1d_dataset_with_hooks( + out_dir, + rows, + options, + DEFAULT_LOCK_TIMEOUT, + |_, _, _| {}, + ) +} + +fn write_bars_1d_dataset_with_hooks( + out_dir: P, + rows: I, + options: Bars1dWriteOptions, + lock_timeout: Duration, + mut on_after_backup: F, +) -> Result +where + P: AsRef, + I: IntoIterator, + R: Borrow, + F: FnMut(i32, &Path, Option<&Path>), { if options.row_group_rows == 0 { return Err(ParquetBarsError::InvalidRowGroupRows); @@ -901,7 +1066,7 @@ where // and only after all staging/publication/rollback work has finished. let dataset_mu = dataset_mutex(&bars_dir); let _in_process_guard = dataset_mu.lock().unwrap_or_else(|err| err.into_inner()); - let _file_lock = DatasetFileLock::acquire(&bars_dir)?; + let _file_lock = DatasetFileLock::acquire_with_timeout(&bars_dir, lock_timeout)?; let run_id = next_run_id(); let mut writers: BTreeMap = BTreeMap::new(); @@ -991,48 +1156,48 @@ where for (year, file) in synced_files { let backup_path = match fs::symlink_metadata(&file.final_path) { Ok(meta) if !meta.is_dir() => { - let bak = match choose_unique_backup_path(&file.final_path, &run_id) { - Ok(path) => path, + match create_backup_preserving_live(&file.final_path, &run_id) { + Ok(bak) => Some(bak), Err(err) => { - rollback_published(&published); - cleanup_owned_files(&owned_tmp_paths); - return Err(err); + return Err(finish_with_rollback(err, &published, None, &owned_tmp_paths)); } - }; - if let Err(source) = fs::rename(&file.final_path, &bak) { - rollback_published(&published); - cleanup_owned_files(&owned_tmp_paths); - return Err(ParquetBarsError::Io { - path: file.final_path, - source, - }); } - Some(bak) } // Directory occupying final_path: leave it in place so the rename below fails // cleanly and triggers rollback of all earlier partitions. Ok(_) => None, Err(err) if err.kind() == io::ErrorKind::NotFound => None, Err(source) => { - rollback_published(&published); - cleanup_owned_files(&owned_tmp_paths); - return Err(ParquetBarsError::Io { + let err = ParquetBarsError::Io { path: file.final_path, source, - }); + }; + return Err(finish_with_rollback(err, &published, None, &owned_tmp_paths)); } }; + on_after_backup(year, &file.final_path, backup_path.as_deref()); + if let Err(source) = fs::rename(&file.tmp_path, &file.final_path) { - if let Some(bak) = backup_path { - let _ = fs::rename(&bak, &file.final_path); - } - rollback_published(&published); - cleanup_owned_files(&owned_tmp_paths); - return Err(ParquetBarsError::Io { + // `file.final_path` was never moved during backup creation, so it remains intact; + // only remove the backup created for this partition before rolling back earlier ones. + let extra_failure = backup_path.and_then(|bak| { + fs::remove_file(&bak).err().map(|remove_err| RollbackFailure { + final_path: file.final_path.clone(), + backup_path: Some(bak), + source: remove_err, + }) + }); + let err = ParquetBarsError::Io { path: file.final_path, source, - }); + }; + return Err(finish_with_rollback( + err, + &published, + extra_failure, + &owned_tmp_paths, + )); } published.push(PublishedPartition { @@ -2018,4 +2183,200 @@ mod tests { assert_row_bitwise_eq(actual, expected); } } + + #[test] + fn existing_partition_remains_readable_between_backup_and_replacement() { + let tmp = TempDirGuard::new("live-readable"); + + let initial = vec![make_row( + 1, + 2023, + 5, + 10, + 75.0, + 10_000.0, + Some(74.8), + "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 original_bytes = fs::read(&path_2023).unwrap(); + + let refresh = vec![ + make_row(1, 2023, 6, 1, 99.0, 20_000.0, Some(98.5), "USD", "eod_unadj"), + make_row(2, 2023, 6, 2, 101.0, 30_000.0, None, "CAD", "qm_raw"), + ]; + + let mut observed_mid_publish = false; + let stats = write_bars_1d_dataset_with_hooks( + tmp.path(), + &refresh, + Bars1dWriteOptions::default(), + DEFAULT_LOCK_TIMEOUT, + |year, final_path, backup_path| { + assert_eq!(year, 2023); + let bak = backup_path.expect("backup must be created for existing partition"); + assert!(bak.exists(), "backup must exist before replacement"); + assert!( + final_path.exists(), + "live partition must remain present after backup creation" + ); + assert_eq!( + fs::read(final_path).expect("read live partition before rename"), + original_bytes + ); + let live_rows = read_parquet_rows(final_path); + assert_eq!(live_rows.len(), initial.len()); + assert_row_bitwise_eq(&live_rows[0], &initial[0]); + observed_mid_publish = true; + }, + ) + .unwrap(); + + assert!(observed_mid_publish, "on_after_backup hook must run"); + assert_eq!(stats.rows_written, refresh.len()); + let updated_rows = read_parquet_rows(&path_2023); + assert_eq!(updated_rows.len(), refresh.len()); + for (actual, expected) in updated_rows.iter().zip(refresh.iter()) { + assert_row_bitwise_eq(actual, expected); + } + assert_no_transient_files(&tmp.path().join("bars_1d")); + } + + #[test] + fn abandoned_write_lock_times_out_with_actionable_error() { + let tmp = TempDirGuard::new("abandoned-lock"); + + let initial = vec![make_row( + 1, + 2024, + 1, + 2, + 100.0, + 5_000.0, + Some(99.5), + "USD", + "eod_unadj", + )]; + write_bars_1d_dataset(tmp.path(), &initial, Bars1dWriteOptions::default()).unwrap(); + let existing_path = tmp.path().join("bars_1d/year=2024/part.parquet"); + let original_bytes = fs::read(&existing_path).unwrap(); + + // Simulate a crashed writer that left `.write.lock` behind. + let lock_path = tmp.path().join("bars_1d/.write.lock"); + fs::write(&lock_path, b"999999\n").unwrap(); + + let timeout = Duration::from_millis(40); + let refresh = vec![make_row( + 1, + 2024, + 2, + 1, + 105.0, + 6_000.0, + None, + "USD", + "eod_unadj", + )]; + let err = write_bars_1d_dataset_with_hooks( + tmp.path(), + &refresh, + Bars1dWriteOptions::default(), + timeout, + |_, _, _| {}, + ) + .unwrap_err(); + + match &err { + ParquetBarsError::LockTimeout { path, waited } => { + assert_eq!(path, &lock_path); + assert!(*waited >= timeout); + } + other => panic!("expected LockTimeout, got {other:?}"), + } + let msg = err.to_string(); + assert!( + msg.contains(&lock_path.display().to_string()), + "LockTimeout message must include lock path, got: {msg}" + ); + // Abandoned lock is not unowned-deleted, and existing partition is untouched. + assert_eq!(fs::read(&lock_path).unwrap(), b"999999\n"); + assert_eq!(fs::read(&existing_path).unwrap(), original_bytes); + // Clean up simulated lock so assert_no_transient_files checks for stray .tmp/.bak. + fs::remove_file(&lock_path).unwrap(); + assert_no_transient_files(&tmp.path().join("bars_1d")); + } + + #[test] + fn rollback_failure_reports_original_error_and_partition_backup_paths() { + let tmp = TempDirGuard::new("rollback-failure"); + + let initial_2023 = vec![make_row( + 1, + 2023, + 5, + 10, + 75.0, + 10_000.0, + Some(74.8), + "USD", + "eod_unadj", + )]; + write_bars_1d_dataset(tmp.path(), &initial_2023, Bars1dWriteOptions::default()).unwrap(); + let path_2023 = tmp.path().join("bars_1d/year=2023/part.parquet"); + let original_2023_bytes = fs::read(&path_2023).unwrap(); + + // Block 2024 publication with a directory so 2024 rename fails after 2023 is replaced. + let blocker_2024 = tmp.path().join("bars_1d/year=2024/part.parquet"); + fs::create_dir_all(&blocker_2024).unwrap(); + + let refresh = vec![ + make_row(1, 2023, 6, 1, 99.0, 2_000.0, Some(98.5), "USD", "eod_unadj"), + make_row(1, 2024, 6, 1, 120.0, 3_000.0, None, "USD", "eod_unadj"), + ]; + + let mut captured_2023_backup: Option = None; + let path_2023_for_hook = path_2023.clone(); + let err = write_bars_1d_dataset_with_hooks( + tmp.path(), + &refresh, + Bars1dWriteOptions::default(), + DEFAULT_LOCK_TIMEOUT, + |year, _final_path, backup_path| { + if year == 2023 { + captured_2023_backup = backup_path.map(Path::to_path_buf); + } else if year == 2024 { + // Replace already-published 2023 file with a directory so rollback's + // `fs::rename(bak, path_2023)` deterministically fails. + fs::remove_file(&path_2023_for_hook).unwrap(); + fs::create_dir(&path_2023_for_hook).unwrap(); + } + }, + ) + .unwrap_err(); + + let expected_bak = captured_2023_backup.expect("2023 backup path recorded"); + match &err { + ParquetBarsError::RollbackFailed { cause, failures } => { + assert!( + matches!(cause.as_ref(), ParquetBarsError::Io { path, .. } if path == &blocker_2024), + "expected original cause at {}, got {cause:?}", + blocker_2024.display() + ); + assert_eq!(failures.len(), 1); + assert_eq!(failures[0].final_path, path_2023); + assert_eq!(failures[0].backup_path.as_deref(), Some(expected_bak.as_path())); + } + other => panic!("expected RollbackFailed, got {other:?}"), + } + + let msg = err.to_string(); + assert!(msg.contains(&blocker_2024.display().to_string()), "{msg}"); + assert!(msg.contains(&path_2023.display().to_string()), "{msg}"); + assert!(msg.contains(&expected_bak.display().to_string()), "{msg}"); + assert!(err.source().is_some()); + // Original backup remains intact on disk for operator recovery. + assert_eq!(fs::read(&expected_bak).unwrap(), original_2023_bytes); + } } From 64cb0cb725eee9732d0543b31c68b697e5fcd671 Mon Sep 17 00:00:00 2001 From: Studio Date: Sat, 28 Nov 2026 11:49:39 -0500 Subject: [PATCH 4/6] =?UTF-8?q?T-90:=20M1.2i=20=E2=80=94=20`tools/curate-e?= =?UTF-8?q?tl`:=20Zstd=20Parquet=20writer=20for=20`bars=5F1d`=20(`year=3DY?= =?UTF-8?q?YYY/part.parquet`,=20contract=20schema)=20with=20round-trip=20t?= =?UTF-8?q?ests=20and=20local=20benchmark=20(adds=20the=20`parquet`=20crat?= =?UTF-8?q?e)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/src/parquet_bars.rs | 18 +- tools/curate-etl/src/parquet_bars_tests.rs | 680 +++++++++++++++++++++ 2 files changed, 691 insertions(+), 7 deletions(-) create mode 100644 tools/curate-etl/src/parquet_bars_tests.rs diff --git a/tools/curate-etl/src/parquet_bars.rs b/tools/curate-etl/src/parquet_bars.rs index 72c73db3..16c8833e 100644 --- a/tools/curate-etl/src/parquet_bars.rs +++ b/tools/curate-etl/src/parquet_bars.rs @@ -1233,12 +1233,12 @@ mod tests { static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0); - struct TempDirGuard { + pub(super) struct TempDirGuard { path: PathBuf, } impl TempDirGuard { - fn new(label: &str) -> Self { + pub(super) fn new(label: &str) -> Self { let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); let pid = std::process::id(); let path = std::env::temp_dir().join(format!("curate-etl-pq-test-{label}-{pid}-{seq}")); @@ -1247,7 +1247,7 @@ mod tests { Self { path } } - fn path(&self) -> &Path { + pub(super) fn path(&self) -> &Path { &self.path } } @@ -1259,7 +1259,7 @@ mod tests { } #[allow(clippy::too_many_arguments)] - fn make_row( + pub(super) fn make_row( listing_id: i32, year: i32, month: u32, @@ -1289,7 +1289,7 @@ mod tests { } } - fn read_parquet_rows(path: &Path) -> Vec { + pub(super) fn read_parquet_rows(path: &Path) -> Vec { let file = File::open(path).expect("open parquet file"); let reader = SerializedFileReader::new(file).expect("open parquet reader"); let metadata = reader.metadata(); @@ -1410,7 +1410,7 @@ mod tests { .collect() } - fn assert_row_bitwise_eq(actual: &Bars1dParquetRow, expected: &Bars1dParquetRow) { + pub(super) fn assert_row_bitwise_eq(actual: &Bars1dParquetRow, expected: &Bars1dParquetRow) { assert_eq!(actual.listing_id, expected.listing_id); assert_eq!(actual.ts_micros, expected.ts_micros); assert_eq!(actual.session_date, expected.session_date); @@ -1891,7 +1891,7 @@ mod tests { assert_no_transient_files(&tmp.path().join("bars_1d")); } - fn assert_no_transient_files(bars_dir: &Path) { + pub(super) fn assert_no_transient_files(bars_dir: &Path) { if !bars_dir.exists() { return; } @@ -2380,3 +2380,7 @@ mod tests { assert_eq!(fs::read(&expected_bak).unwrap(), original_2023_bytes); } } + +#[cfg(test)] +#[path = "parquet_bars_tests.rs"] +mod edge_case_tests; diff --git a/tools/curate-etl/src/parquet_bars_tests.rs b/tools/curate-etl/src/parquet_bars_tests.rs new file mode 100644 index 00000000..28fb443e --- /dev/null +++ b/tools/curate-etl/src/parquet_bars_tests.rs @@ -0,0 +1,680 @@ +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 = (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 = (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 = (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 = (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 = 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 = (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 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 = (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::>() + ); + } +} + +#[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::(), + 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 = (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")); +} From 441a98cd058f590f27f6b8ee49a8424c585774bf Mon Sep 17 00:00:00 2001 From: Studio Date: Sat, 28 Nov 2026 11:56:40 -0500 Subject: [PATCH 5/6] =?UTF-8?q?T-90:=20M1.2i=20=E2=80=94=20`tools/curate-e?= =?UTF-8?q?tl`:=20Zstd=20Parquet=20writer=20for=20`bars=5F1d`=20(`year=3DY?= =?UTF-8?q?YYY/part.parquet`,=20contract=20schema)=20with=20round-trip=20t?= =?UTF-8?q?ests=20and=20local=20benchmark=20(adds=20the=20`parquet`=20crat?= =?UTF-8?q?e)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/src/parquet_bars_tests.rs | 206 +++++++++++++++++++++ 1 file changed, 206 insertions(+) diff --git a/tools/curate-etl/src/parquet_bars_tests.rs b/tools/curate-etl/src/parquet_bars_tests.rs index 28fb443e..53c42789 100644 --- a/tools/curate-etl/src/parquet_bars_tests.rs +++ b/tools/curate-etl/src/parquet_bars_tests.rs @@ -678,3 +678,209 @@ fn error_after_30_flushed_row_groups_leaves_no_partial_files() { 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); +} From b907659da2adf69ae3184cd95fd60d775eba3e1a Mon Sep 17 00:00:00 2001 From: Studio Date: Sat, 28 Nov 2026 12:02:49 -0500 Subject: [PATCH 6/6] T-90: tests --- .../curate-etl/tests/parquet_bars_contract.rs | 533 ++++++++++++++++++ 1 file changed, 533 insertions(+) create mode 100644 tools/curate-etl/tests/parquet_bars_contract.rs diff --git a/tools/curate-etl/tests/parquet_bars_contract.rs b/tools/curate-etl/tests/parquet_bars_contract.rs new file mode 100644 index 00000000..81e79314 --- /dev/null +++ b/tools/curate-etl/tests/parquet_bars_contract.rs @@ -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 { + 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 { + 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 { + 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> { + 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 { + 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>| -> Vec { + 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 { + fn walk(root: &Path, dir: &Path, out: &mut Vec) { + 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::>(), + [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 = (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 { + (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 { + 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")); +}