T-90: M1.2i — tools/curate-etl: Zstd Parquet writer for bars_1d (year=YYYY/part.parquet, contract schema) with round-trip tests and local benchmark (adds the parquet crate)

This commit is contained in:
Studio 2026-11-28 11:12:41 -05:00
parent 94791648c6
commit ae007b8f0e
8 changed files with 2197 additions and 11 deletions

190
Cargo.lock generated
View file

@ -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",
]

View file

@ -6,3 +6,5 @@ authors.workspace = true
license.workspace = true
[dependencies]
parquet = { version = "=60.2.0", default-features = false, features = ["zstd"] }

View file

@ -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<MappingRange>` arena indexed by a sorted per-source `HashMap<String, (usize, usize)>` (linear scan for `<= 8` sources, binary search otherwise) plus binary search over the key's ranges.
- `ProviderMappingCursor` (via `cursor_for(source, source_id)` or `ProviderMappingCursor::new(ranges)`) resolves ascending `bar_date` streams for a single key in amortised O(1), automatically falling back to binary search on out-of-order probes so its output always matches `ProviderMappingTable::resolve` identically.
## `bars_1d` Parquet Writer (`M1.2i`)
`write_bars_1d_dataset` (`src/parquet_bars.rs`) streams strictly ascending `(listing_id, session_date)` `Bars1dParquetRow` records into Zstd-compressed, year-partitioned Parquet files matching `design/DATA-CONTRACTS.md` (§3A).
1. **Exact 12-column contract schema (`bars_1d_parquet_schema`):**
- `listing_id` (`INT32`, `REQUIRED`)
- `ts` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`)
- `session_date` (`INT32`, `REQUIRED`, `DATE`)
- `open`, `high`, `low`, `close`, `volume` (`DOUBLE`, `REQUIRED`)
- `vwap` (`DOUBLE`, `OPTIONAL`)
- `currency`, `source` (`BYTE_ARRAY`, `REQUIRED`, `STRING`, dictionary-encoded)
- `known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`)
2. **Partition layout & compression:**
- Writes `<out_dir>/bars_1d/year=YYYY/part.parquet` lazily per observed `session_date` calendar year (`1900..=2200`); empty input and empty years create no directories or files.
- Zstd compression on every column chunk (`DEFAULT_ZSTD_LEVEL = 3`, configurable via `Bars1dWriteOptions::zstd_level`).
- Bounded streaming buffers (`DEFAULT_ROW_GROUP_ROWS = 1_000_000`, configurable via `Bars1dWriteOptions::row_group_rows`): each active year buffers at most one row group of columnar data (with string interning for `currency`/`source`), flushing and clearing buffers on every row-group boundary.
- Deterministic `created_by` metadata so identical inputs produce byte-identical `part.parquet` files.
3. **Sort & 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

View file

@ -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<Self, ParquetBarsError> {
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<i32>,
listing_count: usize,
base_per_listing: usize,
rem_listings: usize,
cur_listing: usize,
cur_day_idx: usize,
cur_listing_rows: usize,
cur_close: f64,
rng: SplitMix64,
}
impl ParquetBarsBenchIter {
fn new(rows: usize, weekdays: Vec<i32>) -> Self {
let min_listings = if rows == 0 {
PARQUET_BARS_BENCH_BASE_LISTINGS
} else {
rows.div_ceil(weekdays.len())
.max(PARQUET_BARS_BENCH_BASE_LISTINGS)
};
let active_listings = rows.min(min_listings);
let base_per_listing = if active_listings == 0 {
0
} else {
rows / active_listings
};
let rem_listings = if active_listings == 0 {
0
} else {
rows % active_listings
};
let mut iter = Self {
weekdays,
listing_count: active_listings,
base_per_listing,
rem_listings,
cur_listing: 0,
cur_day_idx: 0,
cur_listing_rows: 0,
cur_close: 50.0,
rng: SplitMix64::new(PARQUET_BARS_BENCH_SEED),
};
if active_listings > 0 {
iter.setup_listing(0);
}
iter
}
fn setup_listing(&mut self, listing_idx: usize) {
self.cur_listing = listing_idx;
self.cur_day_idx = 0;
self.cur_listing_rows =
self.base_per_listing + usize::from(listing_idx < self.rem_listings);
self.cur_close = 5.0 + ((self.rng.next_u64() % 25_000) as f64) * 0.01;
}
}
impl Iterator for ParquetBarsBenchIter {
type Item = Bars1dParquetRow;
fn next(&mut self) -> Option<Self::Item> {
if self.cur_listing >= self.listing_count {
return None;
}
if self.cur_day_idx >= self.cur_listing_rows {
let next_listing = self.cur_listing + 1;
if next_listing >= self.listing_count {
self.cur_listing = next_listing;
return None;
}
self.setup_listing(next_listing);
}
let listing_id = (self.cur_listing + 1) as i32;
let w = self.weekdays.len();
let n = self.cur_listing_rows;
let date_pos = if n == 1 {
(self.cur_listing.wrapping_mul(257)) % w
} else {
(self.cur_day_idx * w) / n
};
let session_date = self.weekdays[date_pos];
self.cur_day_idx += 1;
let r1 = self.rng.next_u64();
let r2 = self.rng.next_u64();
// Small realistic random walk in cents.
let delta_bps = ((r1 & 0xFF) as i64) - 128;
let next_close = (self.cur_close * (1.0 + (delta_bps as f64) * 0.0002)).clamp(0.5, 5_000.0);
let open = self.cur_close;
let spread = 0.005 + (((r1 >> 8) & 0x3F) as f64) * 0.0005;
let high = open.max(next_close) * (1.0 + spread);
let low = (open.min(next_close) * (1.0 - spread)).max(0.01);
self.cur_close = next_close;
let volume = ((r2 & 0x3F_FFFF) + 100) as f64;
let vwap = if (r2 >> 22) & 0x3 == 0 {
None
} else {
Some((open + high + low + next_close) * 0.25)
};
let currency = if listing_id % 5 == 0 {
Cow::Borrowed("CAD")
} else {
Cow::Borrowed("USD")
};
let source = Cow::Borrowed("eod_unadj");
let ts_micros = i64::from(session_date) * 86_400_000_000 + 21 * 3_600_000_000;
let known_at_micros = ts_micros + 900_000_000;
Some(Bars1dParquetRow {
listing_id,
ts_micros,
session_date,
open,
high,
low,
close: next_close,
volume,
vwap,
currency,
source,
known_at_micros,
})
}
}
fn collect_bench_weekdays_2006_2025() -> Vec<i32> {
let start = ymd_to_epoch_days(2006, 1, 2).expect("valid start date");
let end = ymd_to_epoch_days(2025, 12, 31).expect("valid end date");
let mut days = Vec::with_capacity(5_300);
let mut d = start;
while d <= end {
let dow = (d + 4).rem_euclid(7);
if (1..=5).contains(&dow) {
days.push(d);
}
d += 1;
}
days
}
fn run_parquet_bars_benchmark_tracked(
rows: usize,
) -> Result<(ParquetBarsBenchReport, PathBuf), ParquetBarsError> {
let temp = BenchTempDir::new()?;
let temp_path = temp.path.clone();
if rows == 0 {
let stats = write_bars_1d_dataset(
&temp.path,
std::iter::empty::<Bars1dParquetRow>(),
Bars1dWriteOptions::default(),
)?;
let 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<ParquetBarsBenchReport, ParquetBarsError> {
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);
}
}

View file

@ -6,7 +6,8 @@
use crate::bench::{
DEFAULT_ADJ_BENCH_EVENTS, DEFAULT_BARS_BENCH_ROWS, DEFAULT_BENCH_ROWS,
DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS, DEFAULT_EVENTS_BENCH_ROWS, DEFAULT_FX_BENCH_ROWS,
DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS, DEFAULT_SHORTS_BENCH_ROWS,
DEFAULT_PARQUET_BARS_BENCH_ROWS, DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS,
DEFAULT_SHORTS_BENCH_ROWS,
};
/// Parsed CLI command to execute.
@ -22,6 +23,7 @@ pub enum CliAction {
BenchShorts(usize),
BenchEvents(usize),
BenchProviderMapping(usize),
BenchParquetBars(usize),
}
/// Formats full help text including binary name and version.
@ -39,7 +41,8 @@ pub fn format_usage(name: &str, version: &str) -> String {
{name} bench-fx [rows] Run fixed-seed fx_1d build + lookup benchmark (default: {DEFAULT_FX_BENCH_ROWS})\n\
{name} bench-shorts [rows] Run fixed-seed shorts build benchmark (default: {DEFAULT_SHORTS_BENCH_ROWS})\n\
{name} bench-events [rows] Run fixed-seed events build benchmark (default: {DEFAULT_EVENTS_BENCH_ROWS})\n\
{name} bench-provider-mapping [lookups] Run fixed-seed provider_mapping build + lookup benchmark (default: {DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS})"
{name} bench-provider-mapping [lookups] Run fixed-seed provider_mapping build + lookup benchmark (default: {DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS})\n\
{name} bench-parquet-bars [rows] Run fixed-seed bars_1d Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_BARS_BENCH_ROWS})"
)
}
@ -56,7 +59,8 @@ pub fn format_usage_stderr(name: &str) -> String {
{name} bench-fx [rows]\n\
{name} bench-shorts [rows]\n\
{name} bench-events [rows]\n\
{name} bench-provider-mapping [lookups]"
{name} bench-provider-mapping [lookups]\n\
{name} bench-parquet-bars [rows]"
)
}
@ -141,6 +145,18 @@ pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
["bench-provider-mapping", _, ..] => {
Err("too many arguments for bench-provider-mapping".to_string())
}
["bench-parquet-bars"] => Ok(CliAction::BenchParquetBars(
DEFAULT_PARQUET_BARS_BENCH_ROWS,
)),
["bench-parquet-bars", raw] => match raw.parse::<usize>() {
Ok(n) if n > 0 => Ok(CliAction::BenchParquetBars(n)),
_ => Err(format!(
"invalid row count '{raw}' (expected a positive integer)"
)),
},
["bench-parquet-bars", _, ..] => {
Err("too many arguments for bench-parquet-bars".to_string())
}
[other, ..] => Err(format!("unknown argument '{other}'")),
}
}
@ -308,6 +324,22 @@ mod tests {
assert!(parse_args(&to_args(&["bench-provider-mapping", "10", "20"])).is_err());
}
#[test]
fn parses_and_validates_bench_parquet_bars_args() {
assert_eq!(
parse_args(&to_args(&["bench-parquet-bars"])),
Ok(CliAction::BenchParquetBars(DEFAULT_PARQUET_BARS_BENCH_ROWS))
);
assert_eq!(
parse_args(&to_args(&["bench-parquet-bars", "250000"])),
Ok(CliAction::BenchParquetBars(250_000))
);
assert!(parse_args(&to_args(&["bench-parquet-bars", "0"])).is_err());
assert!(parse_args(&to_args(&["bench-parquet-bars", "-5"])).is_err());
assert!(parse_args(&to_args(&["bench-parquet-bars", "abc"])).is_err());
assert!(parse_args(&to_args(&["bench-parquet-bars", "10", "20"])).is_err());
}
#[test]
fn usage_strings_mention_all_benchmarks() {
let full = format_usage("curate-etl", "0.1.0");
@ -319,6 +351,7 @@ mod tests {
assert!(full.contains("bench-shorts"));
assert!(full.contains("bench-events"));
assert!(full.contains("bench-provider-mapping"));
assert!(full.contains("bench-parquet-bars"));
let short = format_usage_stderr("curate-etl");
assert!(short.contains("bench-split"));
@ -329,5 +362,6 @@ mod tests {
assert!(short.contains("bench-shorts"));
assert!(short.contains("bench-events"));
assert!(short.contains("bench-provider-mapping"));
assert!(short.contains("bench-parquet-bars"));
}
}

View file

@ -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,

View file

@ -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));

File diff suppressed because it is too large Load diff