From ae007b8f0e75745522c6bf8d734a700ef4b518c8 Mon Sep 17 00:00:00 2001 From: Studio Date: Sat, 28 Nov 2026 11:12:41 -0500 Subject: [PATCH] =?UTF-8?q?T-90:=20M1.2i=20=E2=80=94=20`tools/curate-etl`:?= =?UTF-8?q?=20Zstd=20Parquet=20writer=20for=20`bars=5F1d`=20(`year=3DYYYY/?= =?UTF-8?q?part.parquet`,=20contract=20schema)=20with=20round-trip=20tests?= =?UTF-8?q?=20and=20local=20benchmark=20(adds=20the=20`parquet`=20crate)?= 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); + } + } +}