diff --git a/Cargo.lock b/Cargo.lock index 11d01203..20159235 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -280,6 +280,7 @@ version = "0.1.0" dependencies = [ "bson", "parquet", + "rayon", ] [[package]] @@ -301,6 +302,12 @@ version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + [[package]] name = "engine" version = "0.1.0" @@ -965,6 +972,26 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3" +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + [[package]] name = "redox_syscall" version = "0.5.18" diff --git a/tools/curate-etl/Cargo.toml b/tools/curate-etl/Cargo.toml index 2f81cd3a..646f30a8 100644 --- a/tools/curate-etl/Cargo.toml +++ b/tools/curate-etl/Cargo.toml @@ -8,4 +8,5 @@ license.workspace = true [dependencies] bson = { version = "=3.1.0", default-features = false, features = ["compat-3-0-0"] } parquet = { version = "=60.2.0", default-features = false, features = ["zstd"] } +rayon = "=1.12.0" diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index 5baf09e1..cec33908 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -1,6 +1,6 @@ # `curate-etl` -Dedicated Rust crate (two exact-pinned direct dependencies: `bson` `=3.1.0` with `default-features = false, features = ["compat-3-0-0"]` and `parquet` `=60.2.0` with `default-features = false, features = ["zstd"]`) for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, the `M1.2c` pure `corporate_actions` event-log builder, the `M1.2d` pure `bars_1d` daily bar builder + `qmPrices.sharevolume` cross-check, the `M1.2e` pure `fx_1d` USD/CAD builder + carry-forward lookup, the `M1.2f` pure `shorts` (`ceoShorts`) point-in-time builder + Canadian TSX business-day / `America/Toronto` DST calendar, the `M1.2g` pure `events` (`qmFilings` + `qmEarnings`) point-in-time builder, the `M1.2h` pure in-RAM `provider_mapping` `(source, source_id, bar_date) -> listing_id` lookup table, the `M1.2i` streaming Zstd Parquet writer for `bars_1d`, the `M1.2j` streaming Zstd Parquet writer for `shorts`, the `M1.2k` streaming Zstd Parquet writer for `events`, the `M1.2l` streaming Zstd Parquet writer for `fx_1d`, the `M1.2m` streaming Zstd Parquet writer for `adj_factors`, the `M1.2n` streaming Zstd Parquet writer for `corporate_actions`, the `M1.2o` zero-copy raw BSON decoder for `eodPrices`, the `M1.2w` zero-copy raw BSON decoders for `qmSplits` and `qmDividends`, the `M1.2y` bounded-memory streaming reader for concatenated raw BSON (`bson_stream`), the `M1.2ad` `ceoShorts` decoder + `curate-shorts` command, the `M1.2ae` `qmFilings` / `qmEarnings` decoders + `curate-events` command, and the `M1.2ah` zero-copy `qmPrices` decoder + optional `--qm-prices` volume cross-check in `curate-bars-1d`. +Dedicated Rust crate (three exact-pinned direct dependencies: `bson` `=3.1.0` with `default-features = false, features = ["compat-3-0-0"]`, `parquet` `=60.2.0` with `default-features = false, features = ["zstd"]`, and `rayon` `=1.12.0`) for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, the `M1.2c` pure `corporate_actions` event-log builder, the `M1.2d` pure `bars_1d` daily bar builder + `qmPrices.sharevolume` cross-check, the `M1.2e` pure `fx_1d` USD/CAD builder + carry-forward lookup, the `M1.2f` pure `shorts` (`ceoShorts`) point-in-time builder + Canadian TSX business-day / `America/Toronto` DST calendar, the `M1.2g` pure `events` (`qmFilings` + `qmEarnings`) point-in-time builder, the `M1.2h` pure in-RAM `provider_mapping` `(source, source_id, bar_date) -> listing_id` lookup table, the `M1.2i` streaming Zstd Parquet writer for `bars_1d`, the `M1.2j` streaming Zstd Parquet writer for `shorts`, the `M1.2k` streaming Zstd Parquet writer for `events`, the `M1.2l` streaming Zstd Parquet writer for `fx_1d`, the `M1.2m` streaming Zstd Parquet writer for `adj_factors`, the `M1.2n` streaming Zstd Parquet writer for `corporate_actions`, the `M1.2o` zero-copy raw BSON decoder for `eodPrices`, the `M1.2w` zero-copy raw BSON decoders for `qmSplits` and `qmDividends`, the `M1.2y` bounded-memory streaming reader for concatenated raw BSON (`bson_stream`), the `M1.2ad` `ceoShorts` decoder + `curate-shorts` command, the `M1.2ae` `qmFilings` / `qmEarnings` decoders + `curate-events` command, the `M1.2ah` zero-copy `qmPrices` decoder + optional `--qm-prices` volume cross-check in `curate-bars-1d`, and the `M1.2ai` `rayon` year-sharded parallel Zstd Parquet writer (`--threads`) for `curate-bars-1d`. ## Scope & Sign Conventions @@ -192,13 +192,17 @@ Rules: - 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. + - **Year-sharded `rayon` parallel write (`M1.2ai`):** configurable via `Bars1dWriteOptions::threads` (`DEFAULT_WRITE_THREADS = 1` in `Bars1dWriteOptions::default()` to keep bounded streaming memory for library callers; `default_parallel_threads()` returns `std::thread::available_parallelism()`, falling back to `1`). When `threads == 1`, runs the unchanged single-pass streaming path. When `threads > 1`, runs one sequential validation + order-preserving year-bucketing pass, encodes and Zstd-compresses each `year=YYYY` staging file on a local `rayon::ThreadPool` sized to `threads.min(years).max(1)` (never the global pool), catches worker panics (`WorkerPanicked`), sorts outcomes by ascending year (returning the lowest failing year's error deterministically on failure after unlinking only this run's staging files), and publishes sequentially in ascending year order. + - **Byte-identical determinism guarantee:** identical inputs produce byte-for-byte identical `bars_1d/year=YYYY/part.parquet` files regardless of `threads` (same row order per year, same `row_group_rows` flush boundaries, same schema, dictionary interning order, and `created_by` metadata). 3. **Sort, concurrency & atomicity rules:** - Input must already be sorted strictly ascending by `(listing_id, session_date)`; within each year file rows remain in `(listing_id, session_date)` order. - Concurrent writers targeting the same `/bars_1d` directory are serialized via an in-process per-dataset mutex and a bounded-wait exclusive `.write.lock` file (30 s default timeout returning `ParquetBarsError::LockTimeout` with the lock path if a crashed process left a stale lock behind). Every year partition writes to an exclusively created per-run staging file (`part.parquet..tmp`), flushes, and calls `File::sync_all()` before publication. During publication, pre-existing `part.parquet` files are backed up in place (hard link with exclusive copy fallback) so the live path remains readable until replaced by a single atomic `rename`; on any error, all open writers are dropped, replaced partitions are restored from backup, newly published partitions are removed (reporting any rollback failures alongside the original error via `RollbackFailed`), and only staging files owned by the current run are unlinked. 4. **Typed errors (`ParquetBarsError`):** - `InvalidRowGroupRows` (`row_group_rows == 0`) - `InvalidZstdLevel { level }` + - `InvalidThreads` (`threads == 0`) + - `ThreadPoolBuild { threads, detail }` + - `WorkerPanicked { year, detail }` - `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 }` @@ -1012,9 +1016,9 @@ Command (`2026-11-28`, two back-to-back runs with identical checksum `0x0c22a1a1 - Parquet write: `elapsed=87.57 ms`, `throughput=5647404 rows/s` - Combined (stage → Parquet): `elapsed=371.89 ms`, `throughput=1398252 events/s` -## `curate-bars-1d` Command (`M1.2z` / `M1.2ah`) +## `curate-bars-1d` Command (`M1.2z` / `M1.2ah` / `M1.2ai`) -End-to-end file-to-Parquet CLI command (`src/run_curate_bars.rs`) wiring `RawBsonChunkReader`, `decode_eod_price_chunks`, `decode_qm_split_chunks`, optional `decode_qm_price_chunks` (`src/bson_qm_prices.rs`), `ProviderMappingTable`, `SplitTable`, and `curate_and_write_bars_1d` into `/bars_1d/year=YYYY/part.parquet` with zero extra crates and no database connections. +End-to-end file-to-Parquet CLI command (`src/run_curate_bars.rs`) wiring `RawBsonChunkReader`, `decode_eod_price_chunks`, `decode_qm_split_chunks`, optional `decode_qm_price_chunks` (`src/bson_qm_prices.rs`), `ProviderMappingTable`, `SplitTable`, and `curate_and_write_bars_1d` (with `rayon` year-sharded parallel Zstd Parquet encoding) into `/bars_1d/year=YYYY/part.parquet` with no database connections. ### Invocation @@ -1026,6 +1030,7 @@ curate-etl curate-bars-1d \ --curate-inputs # exporter output dir (pins /current once before opening TSVs) --out # dataset root -> bars_1d/year=YYYY/part.parquet [--rel-tolerance ] # default: 0.01 + [--threads ] # default: available_parallelism() (1 = bounded-RAM sequential write) ``` Instead of `--curate-inputs `, standalone TSV files may be passed directly with `--provider-mapping --listing-currencies ` (mutually exclusive with `--curate-inputs`). When reading from a live exporter output directory, always prefer `--curate-inputs ` so `curate-bars-1d` pins `/current` once before opening either TSV and cannot mix generations across a concurrent refresh. @@ -1060,7 +1065,7 @@ Both `--flag value` and `--flag=value` forms are accepted (in the separated `--f ### Report Counters & Conservation Invariants -On success, `curate-bars-1d` prints deterministic `key=value` lines to stdout (`eod_bson`, `splits_bson`, `splits`, `filter`, `builder`, `curate`, `write`, ascending `years`, `qm_check: qm_prices=absent` when `--qm-prices` is omitted or `qm_bson` / `qm_rekey` / `qm_check` + up to `100` `qm_mismatch` lines when supplied, and `timing`): +On success, `curate-bars-1d` prints deterministic `key=value` lines to stdout (`eod_bson`, `splits_bson`, `splits`, `filter`, `builder`, `curate`, `write`, ascending `years`, `qm_check: qm_prices=absent` when `--qm-prices` is omitted or `qm_bson` / `qm_rekey` / `qm_check` + up to `100` `qm_mismatch` lines when supplied, `config: threads=`, and `timing`): - `splits_in == splits_applied + splits_collision_collapsed + splits_unmapped_qm + splits_no_eod_partner + splits_noop_dropped + splits_bson.rejected` - `eod_bson.docs_framed == eod_bson.docs_in == eod_bson.decoded + eod_bson.rejected` @@ -1074,13 +1079,13 @@ On success, `curate-bars-1d` prints deterministic `key=value` lines to stdout (` ### `bench-curate-bars-cmd` -Fixed-seed (`std`-only SplitMix64) end-to-end file→Parquet benchmark synthesizing `eodPrices.bson`, `qmSplits.bson`, `qmPrices.bson` (matching `Double`/`Int32`/`Int64` `sharevolume` partners, unmapped QM keys, QM keys with no EOD partner, wrong-typed `sharevolume` rejects, and exact injected >1% divergences), `provider_mapping.tsv`, and `listing_currencies.tsv` into a temp dir, timing decode / qm decode+rekey / curate / write splits separately, verifying Parquet footer row counts, and cleaning up on drop: +Fixed-seed (`std`-only SplitMix64) end-to-end file→Parquet benchmark synthesizing `eodPrices.bson`, `qmSplits.bson`, `qmPrices.bson` (matching `Double`/`Int32`/`Int64` `sharevolume` partners, unmapped QM keys, QM keys with no EOD partner, wrong-typed `sharevolume` rejects, and exact injected >1% divergences), `provider_mapping.tsv`, and `listing_currencies.tsv` into a temp dir, timing decode / qm decode+rekey / curate / sequential (`threads=1`, `write_1`) vs parallel (`threads=available_parallelism()`, `write` + `speedup`) Parquet writes on the exact same curated rows, verifying Parquet footer row counts for both outputs, and cleaning up on drop: ```bash cargo run -p curate-etl --release --offline -- bench-curate-bars-cmd [rows] ``` -Measured locally (`2026-11-29`): +Single-threaded baseline measured locally (`2026-11-29`, prior to `rayon` parallel write; multi-thread `write_1` vs `write` numbers pending first unsandboxed release run after `rayon = "=1.12.0"` is fetched): 1. **1,000,000 rows** (`cargo run -p curate-etl --release --offline -- bench-curate-bars-cmd 1000000`): - Input: `rows=1000000`, `eod_bytes=161690000` (154.2 MiB), `splits_docs=2040`, `splits_bytes=188080`, `qm_docs=227439`, `qm_bytes=20815907` (19.9 MiB), `keys=2000` @@ -1099,8 +1104,8 @@ Measured locally (`2026-11-29`): ### Known Limits -- **Full in-RAM buffering of mapped bars (and optional QM volumes):** `curate-bars-1d` buffers every mapped bar in `Vec>>` before sorting (`64 B/bar` struct size; measured `68.5–109.6 B/bar` including `Vec` geometric growth headroom, plus ~200 B/row peak during `curate_bars_1d` while `built.rows` and `Bars1dParquetRow` briefly coexist), plus `32 B/row` for mapped `QmRawVolume>` when `--qm-prices` is supplied (~1.6 GiB worst case if all 51.5M QM rows map). For the US+CA subset (~100–150M rows of the 846M-row `eodPrices` collection), this implies roughly **20–30 GiB peak RAM** (viable on a 64 GiB workstation, tight on 32 GiB); running all 846M global rows unsharded would exceed 160 GiB. -- **No `rayon` sharding or direct MongoDB cursors yet:** single-threaded file-to-file execution only; hash/key-sharded `rayon` streaming and direct MongoDB cursors are deferred to a follow-up. +- **Full in-RAM buffering of mapped bars (and optional QM volumes) + parallel year-bucketing RAM:** `curate-bars-1d` buffers every mapped bar in `Vec>>` before sorting (`64 B/bar` struct size; measured `68.5–109.6 B/bar` including `Vec` geometric growth headroom, plus ~200 B/row peak during `curate_bars_1d` while `built.rows` and `Bars1dParquetRow` briefly coexist), plus `32 B/row` for mapped `QmRawVolume>` when `--qm-prices` is supplied (~1.6 GiB worst case if all 51.5M QM rows map). When `--threads > 1`, Pass 1 of `write_bars_1d_dataset` buckets validated `Bars1dParquetRow`s by year (`~136 B/row` struct size plus `Vec` growth slack, `~180–200 B/row` transient overhead before the caller's `curated.rows` vector drops) and holds up to `min(threads, years)` concurrent `RowGroupBuffer`s during parallel Zstd encoding (each year's bucket drops as soon as its worker finishes). Pass `--threads 1` to use the bounded-RAM single-pass streaming writer. For the US+CA subset (~100–150M rows of the 846M-row `eodPrices` collection), this implies roughly **20–30 GiB peak RAM** (viable on a 64 GiB workstation, tight on 32 GiB); running all 846M global rows unsharded would exceed 160 GiB. +- **Parallelism scope & direct MongoDB cursors:** `rayon` year-sharded parallelism currently covers the `curate-bars-1d` Parquet write stage (`--threads`); parallel BSON decode, parallel curate/sort, other `curate-*` commands, and direct MongoDB cursors remain deferred to follow-up tasks. - **Ticker-reuse split keying caveat:** because `curate_bars_1d` takes `SplitTable` keyed by `eodSearchCode` rather than `listing_id`, attaching a split to every `"eod"` `source_id` pointing at a `listing_id` means a later split on a reused `eodSearchCode` could affect an earlier listing that previously held that same `eodSearchCode`. - **Partition-level replacement on `--out` reuse:** `write_bars_1d_dataset` atomically replaces only the `bars_1d/year=YYYY/part.parquet` partitions emitted by the current run. Reusing an existing `--out` directory for a narrower year range leaves older year partitions intact on disk; use a fresh `--out` directory for a complete rebuild. diff --git a/tools/curate-etl/src/bench.rs b/tools/curate-etl/src/bench.rs index 9a482634..0ea4c1b0 100644 --- a/tools/curate-etl/src/bench.rs +++ b/tools/curate-etl/src/bench.rs @@ -4955,6 +4955,8 @@ pub struct CurateBarsCmdBenchReport { pub files_written: usize, pub row_groups_written: usize, pub bytes_written: u64, + pub parallel_threads: usize, + pub read_back_rows_seq: usize, pub read_back_rows: usize, pub decode_elapsed_ms: f64, pub decode_rows_per_sec: f64, @@ -4964,9 +4966,13 @@ pub struct CurateBarsCmdBenchReport { pub qm_input_mb_per_sec: f64, pub curate_elapsed_ms: f64, pub curate_rows_per_sec: f64, + pub write_seq_elapsed_ms: f64, + pub write_seq_rows_per_sec: f64, + pub write_seq_mb_per_sec: f64, pub write_elapsed_ms: f64, pub write_rows_per_sec: f64, pub write_mb_per_sec: f64, + pub write_speedup: f64, pub total_elapsed_ms: f64, pub total_rows_per_sec: f64, pub total_mb_per_sec: f64, @@ -5034,8 +5040,9 @@ fn run_curate_bars_cmd_benchmark_tracked( use std::io::{BufWriter, Write}; use crate::bson_eod_prices::MILLIS_PER_DAY; + use crate::parquet_bars::default_parallel_threads; use crate::run_curate_bars::{ - run_curate_bars_1d_timed, CurateBars1dArgs, DEFAULT_CURATE_BARS_REL_TOLERANCE, + run_curate_bars_1d_timed_compare, CurateBars1dArgs, DEFAULT_CURATE_BARS_REL_TOLERANCE, }; const MIB: f64 = 1_048_576.0; @@ -5052,7 +5059,8 @@ fn run_curate_bars_cmd_benchmark_tracked( let qm_prices_path = temp.path.join("qmPrices.bson"); let mapping_path = temp.path.join("provider_mapping.tsv"); let currencies_path = temp.path.join("listing_currencies.tsv"); - let out_dir = temp.path.join("out"); + let out_dir_seq = temp.path.join("out_seq"); + let out_dir_par = temp.path.join("out_par"); let key_count = curate_bars_bench_key_count(rows.max(1)); @@ -5547,20 +5555,30 @@ fn run_curate_bars_cmd_benchmark_tracked( })?; } - // 4. Run the full command path file -> Parquet with decode / curate / write timing. + // 4. Run the full command path file -> Parquet with decode / curate / seq+par write timing. + let parallel_threads = default_parallel_threads(); let args = CurateBars1dArgs { eod_prices: eod_path, qm_splits: splits_path, qm_prices: Some(qm_prices_path), provider_mapping: mapping_path, listing_currencies: currencies_path, - out_dir: out_dir.clone(), + out_dir: out_dir_par.clone(), rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, + threads: parallel_threads, }; - let timed = run_curate_bars_1d_timed(&args).map_err(CurateBarsCmdBenchError::Run)?; + let timed = run_curate_bars_1d_timed_compare(&args, &out_dir_seq, &out_dir_par, parallel_threads) + .map_err(CurateBarsCmdBenchError::Run)?; + + let read_back_rows_seq = verify_parquet_bars_row_count( + &out_dir_seq, + timed.write_stats_seq.rows_by_year.keys().copied(), + timed.write_stats_seq.rows_written, + ) + .map_err(CurateBarsCmdBenchError::Verify)?; let read_back_rows = verify_parquet_bars_row_count( - &out_dir, + &out_dir_par, timed.report.write_stats.rows_by_year.keys().copied(), timed.report.write_stats.rows_written, ) @@ -5569,9 +5587,10 @@ fn run_curate_bars_cmd_benchmark_tracked( let decode_elapsed_ms = timed.decode_elapsed_secs * 1_000.0; let qm_decode_rekey_elapsed_ms = timed.qm_decode_rekey_elapsed_secs * 1_000.0; let curate_elapsed_ms = timed.curate_elapsed_secs * 1_000.0; - let write_elapsed_ms = timed.write_elapsed_secs * 1_000.0; + let write_seq_elapsed_ms = timed.write_seq_elapsed_secs * 1_000.0; + let write_elapsed_ms = timed.write_par_elapsed_secs * 1_000.0; let total_elapsed_secs = - timed.decode_elapsed_secs + timed.curate_elapsed_secs + timed.write_elapsed_secs; + timed.decode_elapsed_secs + timed.curate_elapsed_secs + timed.write_par_elapsed_secs; let total_elapsed_ms = total_elapsed_secs * 1_000.0; let (decode_rows_per_sec, _) = compute_rates(rows, timed.decode_elapsed_secs); @@ -5581,8 +5600,14 @@ fn run_curate_bars_cmd_benchmark_tracked( ); let (curate_rows_per_sec, _) = compute_rates(timed.report.buffered_bars, timed.curate_elapsed_secs); - let (write_rows_per_sec, _) = - compute_rates(timed.report.write_stats.rows_written, timed.write_elapsed_secs); + let (write_seq_rows_per_sec, _) = compute_rates( + timed.write_stats_seq.rows_written, + timed.write_seq_elapsed_secs, + ); + let (write_rows_per_sec, _) = compute_rates( + timed.report.write_stats.rows_written, + timed.write_par_elapsed_secs, + ); let (total_rows_per_sec, _) = compute_rates(rows, total_elapsed_secs); let total_input_bytes = timed.report.eod_bytes_read @@ -5598,11 +5623,21 @@ fn run_curate_bars_cmd_benchmark_tracked( } else { 0.0 }; - let write_mb_per_sec = if timed.write_elapsed_secs > 0.0 { - (timed.report.write_stats.bytes_written as f64 / MIB) / timed.write_elapsed_secs + let write_seq_mb_per_sec = if timed.write_seq_elapsed_secs > 0.0 { + (timed.write_stats_seq.bytes_written as f64 / MIB) / timed.write_seq_elapsed_secs } else { 0.0 }; + let write_mb_per_sec = if timed.write_par_elapsed_secs > 0.0 { + (timed.report.write_stats.bytes_written as f64 / MIB) / timed.write_par_elapsed_secs + } else { + 0.0 + }; + let write_speedup = if timed.write_par_elapsed_secs > 0.0 && timed.write_seq_elapsed_secs > 0.0 { + timed.write_seq_elapsed_secs / timed.write_par_elapsed_secs + } else { + 1.0 + }; let total_mb_per_sec = if total_elapsed_secs > 0.0 { (total_input_bytes as f64 / MIB) / total_elapsed_secs } else { @@ -5632,6 +5667,8 @@ fn run_curate_bars_cmd_benchmark_tracked( files_written: timed.report.write_stats.files_written, row_groups_written: timed.report.write_stats.row_groups_written, bytes_written: timed.report.write_stats.bytes_written, + parallel_threads, + read_back_rows_seq, read_back_rows, decode_elapsed_ms, decode_rows_per_sec, @@ -5641,9 +5678,13 @@ fn run_curate_bars_cmd_benchmark_tracked( qm_input_mb_per_sec, curate_elapsed_ms, curate_rows_per_sec, + write_seq_elapsed_ms, + write_seq_rows_per_sec, + write_seq_mb_per_sec, write_elapsed_ms, write_rows_per_sec, write_mb_per_sec, + write_speedup, total_elapsed_ms, total_rows_per_sec, total_mb_per_sec, @@ -11893,7 +11934,10 @@ mod tests { ); assert!(report.bars_unmapped_source_dropped > 0); assert!(report.rows_out > 0); + assert_eq!(report.read_back_rows_seq, report.rows_out); assert_eq!(report.read_back_rows, report.rows_out); + assert!(report.parallel_threads >= 1); + assert!(report.write_speedup.is_finite() && report.write_speedup > 0.0); assert!(report.bytes_per_buffered_bar >= 64.0); assert_eq!( report.split_rekey.splits_in, @@ -11961,6 +12005,10 @@ mod tests { let (report, dir) = run_curate_bars_cmd_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_seq, 0); + assert_eq!(report.read_back_rows, 0); + assert!(report.parallel_threads >= 1); + assert!(report.write_speedup.is_finite() && report.write_speedup > 0.0); assert_eq!(report.eod_docs_framed, 0); assert_eq!(report.qm_docs_framed, 0); assert_eq!(report.qm_matched_us, 0); diff --git a/tools/curate-etl/src/cli.rs b/tools/curate-etl/src/cli.rs index 428cdd66..a99a68d1 100644 --- a/tools/curate-etl/src/cli.rs +++ b/tools/curate-etl/src/cli.rs @@ -29,7 +29,9 @@ use crate::bson_qm_events::{ DEFAULT_EARNINGS_REPORT_DATE_FIELD, DEFAULT_FILINGS_KEY_FIELD, DEFAULT_FILINGS_TIMEFILED_FIELD, }; use crate::run_curate_adj::CurateAdjFactorsArgs; -use crate::run_curate_bars::{CurateBars1dArgs, DEFAULT_CURATE_BARS_REL_TOLERANCE}; +use crate::run_curate_bars::{ + default_curate_bars_threads, CurateBars1dArgs, DEFAULT_CURATE_BARS_REL_TOLERANCE, +}; use crate::run_curate_corporate_actions::CurateCorporateActionsArgs; use crate::run_curate_events::{CurateEventsArgs, DEFAULT_EVENTS_MAPPING_SOURCE}; use crate::run_curate_fx::{is_supported_te_symbol, CurateFx1dArgs, DEFAULT_TE_SYMBOL}; @@ -85,8 +87,8 @@ pub fn format_usage(name: &str, version: &str) -> String { Usage:\n\ {name} [--help | -h]\n\ {name} [--version | -V]\n\ - {name} curate-bars-1d --eod-prices --qm-splits [--qm-prices ] (--curate-inputs | --provider-mapping --listing-currencies ) --out [--rel-tolerance ]\n\ - Curate daily bars from BSON + TSV files into bars_1d/year=YYYY/part.parquet (default --rel-tolerance: {DEFAULT_CURATE_BARS_REL_TOLERANCE})\n\ + {name} curate-bars-1d --eod-prices --qm-splits [--qm-prices ] (--curate-inputs | --provider-mapping --listing-currencies ) --out [--rel-tolerance ] [--threads ]\n\ + Curate daily bars from BSON + TSV files into bars_1d/year=YYYY/part.parquet (default --rel-tolerance: {DEFAULT_CURATE_BARS_REL_TOLERANCE}, --threads: available parallelism)\n\ {name} curate-adj-factors --qm-splits --qm-dividends --provider-mapping --bars-1d --out \n\ Curate retrospective adj_factors from BSON + TSV + bars_1d Parquet into adj_factors/part.parquet\n\ {name} curate-corporate-actions --qm-splits --qm-dividends (--curate-inputs | --provider-mapping [--delistings ]) --out \n\ @@ -135,7 +137,7 @@ pub fn format_usage_stderr(name: &str) -> String { "Usage:\n\ {name} [--help | -h]\n\ {name} [--version | -V]\n\ - {name} curate-bars-1d --eod-prices --qm-splits [--qm-prices ] (--curate-inputs | --provider-mapping --listing-currencies ) --out [--rel-tolerance ]\n\ + {name} curate-bars-1d --eod-prices --qm-splits [--qm-prices ] (--curate-inputs | --provider-mapping --listing-currencies ) --out [--rel-tolerance ] [--threads ]\n\ {name} curate-adj-factors --qm-splits --qm-dividends --provider-mapping --bars-1d --out \n\ {name} curate-corporate-actions --qm-splits --qm-dividends (--curate-inputs | --provider-mapping [--delistings ]) --out \n\ {name} curate-fx-1d --eod-prices --te-market-data [--te-symbol ] --out \n\ @@ -222,6 +224,7 @@ fn parse_curate_bars_1d_args(args: &[&str]) -> Result let mut listing_currencies: Option = None; let mut out_dir: Option = None; let mut rel_tolerance: Option = None; + let mut threads: Option = None; let mut i = 0usize; while i < args.len() { @@ -284,6 +287,25 @@ fn parse_curate_bars_1d_args(args: &[&str]) -> Result let normalized = if parsed == 0.0 { 0.0 } else { parsed }; rel_tolerance = Some(normalized); } + "--threads" => { + if threads.is_some() { + return Err("duplicate flag '--threads'".to_string()); + } + if value.is_empty() || !value.bytes().all(|b| b.is_ascii_digit()) { + return Err(format!( + "invalid --threads '{value}' (expected a positive integer >= 1)" + )); + } + let parsed = value.parse::().map_err(|_| { + format!("invalid --threads '{value}' (expected a positive integer >= 1)") + })?; + if parsed == 0 { + return Err(format!( + "invalid --threads '{value}' (expected a positive integer >= 1)" + )); + } + threads = Some(parsed); + } other => return Err(format!("unknown flag '{other}' for curate-bars-1d")), } } @@ -322,6 +344,7 @@ fn parse_curate_bars_1d_args(args: &[&str]) -> Result listing_currencies, out_dir, rel_tolerance: rel_tolerance.unwrap_or(DEFAULT_CURATE_BARS_REL_TOLERANCE), + threads: threads.unwrap_or_else(default_curate_bars_threads), }) } @@ -1700,6 +1723,7 @@ mod tests { listing_currencies: PathBuf::from("/tmp/listing_currencies.tsv"), out_dir: PathBuf::from("/tmp/out"), rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, + threads: default_curate_bars_threads(), }) ); @@ -1729,6 +1753,7 @@ mod tests { listing_currencies: PathBuf::from("/tmp/listing_currencies.tsv"), out_dir: PathBuf::from("/tmp/out"), rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, + threads: default_curate_bars_threads(), }) ); @@ -1812,6 +1837,44 @@ mod tests { let err = parse_args(&to_args(&missing_qm)).unwrap_err(); assert!(err.contains("missing value for flag '--qm-prices'"), "{err}"); + // Valid --threads forms (separated and equals) and default. + let mut with_threads = full.to_vec(); + with_threads.extend(["--threads", "4"]); + match parse_args(&to_args(&with_threads)).expect("valid --threads 4") { + CliAction::CurateBars1d(a) => assert_eq!(a.threads, 4), + other => panic!("unexpected action: {other:?}"), + } + let mut with_threads_eq = full.to_vec(); + with_threads_eq.push("--threads=8"); + match parse_args(&to_args(&with_threads_eq)).expect("valid --threads=8") { + CliAction::CurateBars1d(a) => assert_eq!(a.threads, 8), + other => panic!("unexpected action: {other:?}"), + } + + // Invalid --threads values: 0, non-integer, negative, empty, missing, duplicate. + for bad in ["0", "abc", "-1", "+2", "1.5", ""] { + let mut args_eq = full.to_vec(); + let flag = format!("--threads={bad}"); + args_eq.push(&flag); + let err = parse_args(&to_args(&args_eq)).unwrap_err(); + assert!( + err.contains("invalid --threads"), + "expected invalid --threads for '{bad}', got: {err}" + ); + } + let mut missing_threads = full.to_vec(); + missing_threads.push("--threads"); + let err = parse_args(&to_args(&missing_threads)).unwrap_err(); + assert!(err.contains("missing value for flag '--threads'"), "{err}"); + + let mut dup_threads = full.to_vec(); + dup_threads.extend(["--threads", "2", "--threads=4"]); + let err = parse_args(&to_args(&dup_threads)).unwrap_err(); + assert!(err.contains("duplicate flag '--threads'"), "{err}"); + + assert!(format_usage("curate-etl", "0.1.0").contains("[--threads ]")); + assert!(format_usage_stderr("curate-etl").contains("[--threads ]")); + // Unknown flag. let mut unk = full.to_vec(); unk.extend(["--bogus", "1"]); diff --git a/tools/curate-etl/src/curate_bars.rs b/tools/curate-etl/src/curate_bars.rs index 515b3f8d..cf2e7fa0 100644 --- a/tools/curate-etl/src/curate_bars.rs +++ b/tools/curate-etl/src/curate_bars.rs @@ -386,7 +386,7 @@ where mapping_source, listing_currencies, )?; - let write_stats = write_bars_1d_dataset(out_dir, &curated.rows, options)?; + let write_stats = write_bars_1d_dataset(out_dir, curated.rows, options)?; Ok(CurateBars1dWriteReport { curate_stats: curated.stats, write_stats, diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index 29fcfcd8..ab444317 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -100,9 +100,10 @@ pub use parquet_adj::{ AdjFactorsWriteOptions, AdjFactorsWriteStats, ParquetAdjError, }; pub use parquet_bars::{ - bars_1d_parquet_schema, write_bars_1d_dataset, Bars1dParquetRow, Bars1dWriteOptions, - Bars1dWriteStats, ParquetBarsError, RollbackFailure, DEFAULT_ROW_GROUP_ROWS, - DEFAULT_ZSTD_LEVEL, MAX_PARQUET_YEAR, MIN_PARQUET_YEAR, + bars_1d_parquet_schema, default_parallel_threads, write_bars_1d_dataset, Bars1dParquetRow, + Bars1dWriteOptions, Bars1dWriteStats, ParquetBarsError, RollbackFailure, + DEFAULT_ROW_GROUP_ROWS, DEFAULT_WRITE_THREADS, DEFAULT_ZSTD_LEVEL, MAX_PARQUET_YEAR, + MIN_PARQUET_YEAR, }; pub use parquet_corporate_actions::{ corporate_actions_parquet_schema, write_corporate_actions_dataset, CorporateActionsParquetRow, @@ -186,9 +187,9 @@ pub use curate_corporate_actions::{ pub mod run_curate_bars; pub use run_curate_bars::{ - format_curate_bars_report, load_listing_currencies_tsv, load_provider_mapping_tsv, - run_curate_bars_1d, CurateBars1dArgs, CurateBars1dRunReport, QmVolumeRekeyStats, - RunCurateBarsError, SplitRekeyStats, DEFAULT_CURATE_BARS_REL_TOLERANCE, + default_curate_bars_threads, format_curate_bars_report, load_listing_currencies_tsv, + load_provider_mapping_tsv, run_curate_bars_1d, CurateBars1dArgs, CurateBars1dRunReport, + QmVolumeRekeyStats, RunCurateBarsError, SplitRekeyStats, DEFAULT_CURATE_BARS_REL_TOLERANCE, }; pub mod run_curate_adj; diff --git a/tools/curate-etl/src/main.rs b/tools/curate-etl/src/main.rs index 606ae9e7..e60629d7 100644 --- a/tools/curate-etl/src/main.rs +++ b/tools/curate-etl/src/main.rs @@ -789,10 +789,22 @@ fn main() -> ExitCode { report.curate_stats.listing_collision_dropped ); println!( - " write: elapsed={:.2} ms throughput={:.0} rows/s write={:.2} MB/s files={} row_groups={} bytes={} read_back_rows={}", + " write_1: threads=1 elapsed={:.2} ms throughput={:.0} rows/s write={:.2} MB/s files={} row_groups={} bytes={} read_back_rows={}", + report.write_seq_elapsed_ms, + report.write_seq_rows_per_sec, + report.write_seq_mb_per_sec, + report.files_written, + report.row_groups_written, + report.bytes_written, + report.read_back_rows_seq + ); + println!( + " write: threads={} elapsed={:.2} ms throughput={:.0} rows/s write={:.2} MB/s speedup={:.2}x files={} row_groups={} bytes={} read_back_rows={}", + report.parallel_threads, report.write_elapsed_ms, report.write_rows_per_sec, report.write_mb_per_sec, + report.write_speedup, report.files_written, report.row_groups_written, report.bytes_written, diff --git a/tools/curate-etl/src/parquet_bars.rs b/tools/curate-etl/src/parquet_bars.rs index 5367748e..ebfa4643 100644 --- a/tools/curate-etl/src/parquet_bars.rs +++ b/tools/curate-etl/src/parquet_bars.rs @@ -16,6 +16,7 @@ //! 11. `source` (`BYTE_ARRAY`, `REQUIRED`, `STRING`) //! 12. `known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`) +use std::any::Any; use std::borrow::{Borrow, Cow}; use std::cmp::Ordering; use std::collections::BTreeMap; @@ -23,8 +24,10 @@ use std::error::Error; use std::fmt; use std::fs::{self, File}; use std::io::{self, BufWriter, Write}; +use std::num::NonZeroUsize; +use std::panic::{catch_unwind, AssertUnwindSafe}; use std::path::{Path, PathBuf}; -use std::sync::Arc; +use std::sync::{Arc, Mutex}; use std::time::Duration; use parquet::basic::{Compression, LogicalType, Repetition, TimeUnit, Type as PhysicalType, ZstdLevel}; @@ -33,6 +36,7 @@ use parquet::errors::ParquetError; use parquet::file::properties::{WriterProperties, WriterPropertiesPtr}; use parquet::file::writer::SerializedFileWriter; use parquet::schema::types::{ColumnPath, Type, TypePtr}; +use rayon::prelude::*; use crate::parquet_publish::{ cleanup_owned_files, create_backup_preserving_live, create_exclusive_tmp_file, dataset_mutex, @@ -49,6 +53,18 @@ pub const MIN_PARQUET_YEAR: i32 = 1900; /// Maximum allowed calendar year for `session_date` partitioning. pub const MAX_PARQUET_YEAR: i32 = 2200; +/// Default worker thread count for [`Bars1dWriteOptions::default`] (`1` keeps bounded streaming +/// memory for library callers). +pub const DEFAULT_WRITE_THREADS: usize = 1; + +/// Default parallel worker thread count (`std::thread::available_parallelism()`, falling back to +/// `1` if unavailable). +pub fn default_parallel_threads() -> usize { + std::thread::available_parallelism() + .map(NonZeroUsize::get) + .unwrap_or(1) +} + /// Single `bars_1d` row matching the `design/DATA-CONTRACTS.md` Parquet schema. #[derive(Debug, Clone, PartialEq)] pub struct Bars1dParquetRow { @@ -71,6 +87,7 @@ pub struct Bars1dParquetRow { pub struct Bars1dWriteOptions { pub row_group_rows: usize, pub zstd_level: i32, + pub threads: usize, } impl Default for Bars1dWriteOptions { @@ -78,6 +95,7 @@ impl Default for Bars1dWriteOptions { Self { row_group_rows: DEFAULT_ROW_GROUP_ROWS, zstd_level: DEFAULT_ZSTD_LEVEL, + threads: DEFAULT_WRITE_THREADS, } } } @@ -99,6 +117,15 @@ pub enum ParquetBarsError { InvalidZstdLevel { level: i32, }, + InvalidThreads, + ThreadPoolBuild { + threads: usize, + detail: String, + }, + WorkerPanicked { + year: i32, + detail: String, + }, UnsortedInput { prev_listing_id: i32, prev_session_date: i32, @@ -143,6 +170,16 @@ impl fmt::Display for ParquetBarsError { Self::InvalidZstdLevel { level } => { write!(f, "invalid Zstd compression level: {level}") } + Self::InvalidThreads => { + write!(f, "invalid threads: must be greater than 0") + } + Self::ThreadPoolBuild { threads, detail } => write!( + f, + "failed to build rayon thread pool with {threads} thread(s): {detail}" + ), + Self::WorkerPanicked { year, detail } => { + write!(f, "worker panicked while encoding year={year:04}: {detail}") + } Self::UnsortedInput { prev_listing_id, prev_session_date, @@ -391,6 +428,22 @@ impl YearWriter { props: &WriterPropertiesPtr, owned_tmp_paths: &mut Vec, ) -> Result { + Self::open_with_tmp_recorder(bars_dir, year, run_id, schema, props, |tmp_path| { + owned_tmp_paths.push(tmp_path); + }) + } + + fn open_with_tmp_recorder( + bars_dir: &Path, + year: i32, + run_id: &str, + schema: &TypePtr, + props: &WriterPropertiesPtr, + mut record_tmp: F, + ) -> Result + where + F: FnMut(PathBuf), + { 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(), @@ -398,7 +451,7 @@ impl YearWriter { })?; let (tmp_path, file) = create_exclusive_tmp_file(&year_dir, run_id)?; - owned_tmp_paths.push(tmp_path.clone()); + record_tmp(tmp_path.clone()); let final_path = year_dir.join("part.parquet"); let buf_writer = BufWriter::with_capacity(FILE_BUF_CAPACITY_BYTES, file); @@ -587,17 +640,52 @@ where ) } +fn format_panic_payload(payload: Box) -> String { + if let Some(s) = payload.downcast_ref::<&str>() { + (*s).to_string() + } else if let Some(s) = payload.downcast_ref::() { + s.clone() + } else { + "unknown panic payload".to_string() + } +} + fn write_bars_1d_dataset_with_hooks( out_dir: P, rows: I, options: Bars1dWriteOptions, lock_timeout: Duration, + on_after_backup: F, +) -> Result +where + P: AsRef, + I: IntoIterator, + R: Borrow, + F: FnMut(i32, &Path, Option<&Path>), +{ + write_bars_1d_dataset_internal( + out_dir, + rows, + options, + lock_timeout, + |_, _| Ok(()), + on_after_backup, + ) +} + +fn write_bars_1d_dataset_internal( + out_dir: P, + rows: I, + options: Bars1dWriteOptions, + lock_timeout: Duration, + on_stage_year: S, mut on_after_backup: F, ) -> Result where P: AsRef, I: IntoIterator, R: Borrow, + S: Fn(i32, &Path) -> Result<(), ParquetBarsError> + Sync, F: FnMut(i32, &Path, Option<&Path>), { if options.row_group_rows == 0 { @@ -608,6 +696,9 @@ where level: options.zstd_level, } })?; + if options.threads == 0 { + return Err(ParquetBarsError::InvalidThreads); + } let mut row_iter = rows.into_iter(); let Some(first_item) = row_iter.next() else { @@ -648,86 +739,229 @@ where let _file_lock = DatasetFileLock::acquire_with_timeout(&bars_dir, lock_timeout)?; let run_id = next_run_id(); - let mut writers: BTreeMap = BTreeMap::new(); - let mut owned_tmp_paths: Vec = Vec::new(); - let mut scratch: Vec = Vec::with_capacity(STRING_WRITE_BATCH_ROWS); - let write_result: Result, ParquetBarsError> = (|| { - let mut prev_key: Option<(i32, i32)> = None; + let (synced_files, owned_tmp_paths) = if options.threads == 1 { + let mut owned_tmp_paths: Vec = Vec::new(); + let mut writers: BTreeMap = BTreeMap::new(); + let mut scratch: Vec = Vec::with_capacity(STRING_WRITE_BATCH_ROWS); - for item in std::iter::once(first_item).chain(row_iter) { - let row = item.borrow(); - if let Some((prev_listing_id, prev_session_date)) = prev_key { - match (row.listing_id, row.session_date).cmp(&(prev_listing_id, prev_session_date)) - { - Ordering::Equal => { - return Err(ParquetBarsError::DuplicateKey { - listing_id: row.listing_id, - session_date: row.session_date, - }); + let write_result: Result, ParquetBarsError> = (|| { + let mut prev_key: Option<(i32, i32)> = None; + + for item in std::iter::once(first_item).chain(row_iter) { + let row = item.borrow(); + if let Some((prev_listing_id, prev_session_date)) = prev_key { + match (row.listing_id, row.session_date) + .cmp(&(prev_listing_id, prev_session_date)) + { + 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 => {} } - 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)); + 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, + 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, - &run_id, - &schema, - &props, - &mut owned_tmp_paths, - )?; - entry.insert(opened) + min_year: MIN_PARQUET_YEAR, + max_year: MAX_PARQUET_YEAR, + }); } - }; - yw.buf.push(row); - if yw.buf.len() == options.row_group_rows { - yw.flush_row_group(&mut scratch)?; + 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, + &run_id, + &schema, + &props, + &mut owned_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 { + on_stage_year(year, &yw.tmp_path)?; + let file = yw.finish_and_sync(&mut scratch)?; + synced.push((year, file)); + } + Ok(synced) + })(); + + match write_result { + Ok(files) => (files, owned_tmp_paths), + Err(err) => { + // Drop all open writers before unlinking temporary files owned by this run. + drop(writers); + cleanup_owned_files(&owned_tmp_paths); + return Err(err); + } + } + } else { + // Pass 1: single sequential global validation pass enforcing exact error precedence while + // bucketing rows by year in preserved order. + let mut buckets: BTreeMap> = BTreeMap::new(); + { + let mut prev_key: Option<(i32, i32)> = None; + for item in std::iter::once(first_item).chain(row_iter) { + let row = item.borrow(); + if let Some((prev_listing_id, prev_session_date)) = prev_key { + match (row.listing_id, row.session_date) + .cmp(&(prev_listing_id, prev_session_date)) + { + 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, + }); + } + + buckets.entry(year).or_default().push(row.clone()); } } - 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) - })(); + // Schedule largest years first for load balance; tie-break by ascending year. + let mut work_items: Vec<(i32, Vec)> = buckets.into_iter().collect(); + work_items.sort_unstable_by(|(year_a, rows_a), (year_b, rows_b)| { + rows_b.len().cmp(&rows_a.len()).then_with(|| year_a.cmp(year_b)) + }); - let synced_files = match write_result { - Ok(files) => files, - Err(err) => { - // Drop all open writers before unlinking temporary files owned by this run. - drop(writers); + let pool_threads = options.threads.clamp(1, work_items.len().max(1)); + let pool = rayon::ThreadPoolBuilder::new() + .num_threads(pool_threads) + .build() + .map_err(|err| ParquetBarsError::ThreadPoolBuild { + threads: pool_threads, + detail: err.to_string(), + })?; + + let shared_tmp_paths: Mutex> = Mutex::new(Vec::with_capacity(work_items.len())); + let bars_dir_ref = bars_dir.as_path(); + let run_id_ref = run_id.as_str(); + let schema_ref = &schema; + let props_ref = &props; + let on_stage_ref = &on_stage_year; + let shared_tmp_ref = &shared_tmp_paths; + let row_group_rows = options.row_group_rows; + + let mut outcomes: Vec<(i32, Result)> = + pool.install(|| { + work_items + .into_par_iter() + .map(|(year, year_rows)| { + let res = catch_unwind(AssertUnwindSafe(|| { + let mut yw = YearWriter::open_with_tmp_recorder( + bars_dir_ref, + year, + run_id_ref, + schema_ref, + props_ref, + |tmp_path| { + shared_tmp_ref + .lock() + .unwrap_or_else(|err| err.into_inner()) + .push(tmp_path); + }, + )?; + let mut scratch: Vec = + Vec::with_capacity(STRING_WRITE_BATCH_ROWS); + for row in &year_rows { + yw.buf.push(row); + if yw.buf.len() == row_group_rows { + yw.flush_row_group(&mut scratch)?; + } + } + drop(year_rows); + on_stage_ref(year, &yw.tmp_path)?; + yw.finish_and_sync(&mut scratch) + })) + .unwrap_or_else(|payload| { + Err(ParquetBarsError::WorkerPanicked { + year, + detail: format_panic_payload(payload), + }) + }); + (year, res) + }) + .collect() + }); + + let owned_tmp_paths = shared_tmp_paths + .into_inner() + .unwrap_or_else(|err| err.into_inner()); + outcomes.sort_unstable_by_key(|(year, _)| *year); + + let mut synced = Vec::with_capacity(outcomes.len()); + let mut first_err: Option = None; + for (year, res) in outcomes { + match res { + Ok(file) => { + if first_err.is_none() { + synced.push((year, file)); + } + } + Err(err) => { + if first_err.is_none() { + first_err = Some(err); + } + } + } + } + if let Some(err) = first_err { cleanup_owned_files(&owned_tmp_paths); return Err(err); } + (synced, owned_tmp_paths) }; let mut stats = Bars1dWriteStats::default(); @@ -1262,6 +1496,7 @@ mod tests { let options = Bars1dWriteOptions { row_group_rows: 1_000, zstd_level: DEFAULT_ZSTD_LEVEL, + ..Bars1dWriteOptions::default() }; let stats = write_bars_1d_dataset(tmp.path(), &rows, options).unwrap(); assert_eq!(stats.rows_written, 2_500); @@ -1342,6 +1577,7 @@ mod tests { Bars1dWriteOptions { row_group_rows: 0, zstd_level: DEFAULT_ZSTD_LEVEL, + ..Bars1dWriteOptions::default() }, ) .unwrap_err(); @@ -1356,6 +1592,7 @@ mod tests { Bars1dWriteOptions { row_group_rows: 100, zstd_level: 99, + ..Bars1dWriteOptions::default() }, ) .unwrap_err(); @@ -1466,6 +1703,7 @@ mod tests { Bars1dWriteOptions { row_group_rows: 2, zstd_level: DEFAULT_ZSTD_LEVEL, + ..Bars1dWriteOptions::default() }, ) .unwrap_err(); diff --git a/tools/curate-etl/src/parquet_bars_tests.rs b/tools/curate-etl/src/parquet_bars_tests.rs index 53c42789..84ad961d 100644 --- a/tools/curate-etl/src/parquet_bars_tests.rs +++ b/tools/curate-etl/src/parquet_bars_tests.rs @@ -1,5 +1,7 @@ use std::borrow::Cow; +use std::error::Error as _; use std::fs::{self, File}; +use std::io; use std::time::Duration; use parquet::basic::Encoding; @@ -9,9 +11,10 @@ use super::tests::{ assert_no_transient_files, assert_row_bitwise_eq, make_row, read_parquet_rows, TempDirGuard, }; use super::{ - write_bars_1d_dataset, write_bars_1d_dataset_with_hooks, Bars1dParquetRow, Bars1dWriteOptions, - ParquetBarsError, MAX_PARQUET_YEAR, MIN_PARQUET_YEAR, + write_bars_1d_dataset, write_bars_1d_dataset_internal, write_bars_1d_dataset_with_hooks, + Bars1dParquetRow, Bars1dWriteOptions, ParquetBarsError, MAX_PARQUET_YEAR, MIN_PARQUET_YEAR, }; +use crate::parquet_publish::DEFAULT_LOCK_TIMEOUT; use crate::split::ymd_to_epoch_days; #[test] @@ -884,3 +887,406 @@ fn active_external_write_lock_times_out_without_deleting_lock_or_modifying_exist assert_eq!(fs::read(&lock_path).unwrap(), lock_contents); assert_eq!(fs::read(&path_2024).unwrap(), orig_2024_bytes); } + +fn splitmix64_next(state: &mut u64) -> u64 { + *state = state.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = *state; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) +} + +#[test] +fn parallel_write_multi_year_200k_rows_is_byte_identical_across_thread_counts() { + // 20 years (2006..=2025) x 100 listings x 100 sessions/year = 200,000 rows. + // row_group_rows = 3_500 -> 3 row groups per year (60 row groups total). + let mut rng: u64 = 0x570C_4B07_0012_0001; + let mut rows = Vec::with_capacity(200_000); + for listing_id in 1..=100_i32 { + let currency = if listing_id % 3 == 0 { "CAD" } else { "USD" }; + for year in 2006..=2025_i32 { + let jan1 = ymd_to_epoch_days(year, 1, 1).unwrap(); + for offset in 0..100_i32 { + let session_date = jan1 + offset * 3; + let r = splitmix64_next(&mut rng); + let close = 5.0 + ((r & 0xFFFF) as f64) * 0.01; + let volume = 1_000.0 + (((r >> 16) & 0xFFFF) as f64) * 10.0; + let vwap = if (r >> 32) & 3 == 0 { + None + } else { + Some(close - 0.125) + }; + let ts_micros = i64::from(session_date) * 86_400_000_000 + 21 * 3_600_000_000; + rows.push(Bars1dParquetRow { + listing_id, + ts_micros, + session_date, + open: close - 0.5, + high: close + 1.0, + low: close - 0.75, + close, + volume, + vwap, + currency: Cow::Borrowed(currency), + source: Cow::Borrowed("eod_unadj"), + known_at_micros: ts_micros, + }); + } + } + } + assert_eq!(rows.len(), 200_000); + + let dir_1 = TempDirGuard::new("par-parity-t1"); + let dir_2 = TempDirGuard::new("par-parity-t2"); + let dir_8 = TempDirGuard::new("par-parity-t8"); + + let opts = |threads| Bars1dWriteOptions { + row_group_rows: 3_500, + threads, + ..Bars1dWriteOptions::default() + }; + + let stats_1 = write_bars_1d_dataset(dir_1.path(), &rows, opts(1)).unwrap(); + let stats_2 = write_bars_1d_dataset(dir_2.path(), &rows, opts(2)).unwrap(); + let stats_8 = write_bars_1d_dataset(dir_8.path(), &rows, opts(8)).unwrap(); + + assert_eq!(stats_1.rows_written, 200_000); + assert_eq!(stats_1.files_written, 20); + assert_eq!(stats_1.row_groups_written, 60); + assert_eq!(stats_1, stats_2); + assert_eq!(stats_1, stats_8); + + for year in 2006..=2025_i32 { + let rel = format!("bars_1d/year={year:04}/part.parquet"); + let b1 = fs::read(dir_1.path().join(&rel)).unwrap(); + let b2 = fs::read(dir_2.path().join(&rel)).unwrap(); + let b8 = fs::read(dir_8.path().join(&rel)).unwrap(); + assert_eq!(b1, b2, "threads=1 vs threads=2 diverged for {rel}"); + assert_eq!(b1, b8, "threads=1 vs threads=8 diverged for {rel}"); + } + + assert_no_transient_files(&dir_1.path().join("bars_1d")); + assert_no_transient_files(&dir_2.path().join("bars_1d")); + assert_no_transient_files(&dir_8.path().join("bars_1d")); +} + +fn assert_no_parquet_or_tmp_under(root: &std::path::Path) { + if !root.exists() { + return; + } + let mut stack = vec![root.to_path_buf()]; + while let Some(dir) = stack.pop() { + for entry in fs::read_dir(&dir).unwrap() { + let entry = entry.unwrap(); + let path = entry.path(); + if path.is_dir() { + stack.push(path); + } else { + let name = entry.file_name().to_string_lossy().into_owned(); + assert!( + name != "part.parquet" + && !name.ends_with(".tmp") + && !name.ends_with(".bak") + && name != ".write.lock", + "unexpected leftover file '{}'", + path.display() + ); + } + } + } +} + +#[test] +fn parallel_write_error_parity_and_clean_directory() { + let valid_row = make_row(1, 2024, 1, 2, 10.0, 100.0, None, "USD", "eod_unadj"); + let opts_par = |row_group_rows, zstd_level, threads| Bars1dWriteOptions { + row_group_rows, + zstd_level, + threads, + }; + + // 1. InvalidRowGroupRows + { + let d_seq = TempDirGuard::new("par-err-rg-seq"); + let d_par = TempDirGuard::new("par-err-rg-par"); + let e1 = write_bars_1d_dataset( + d_seq.path(), + std::slice::from_ref(&valid_row), + opts_par(0, 3, 1), + ) + .unwrap_err(); + let e4 = write_bars_1d_dataset( + d_par.path(), + std::slice::from_ref(&valid_row), + opts_par(0, 3, 4), + ) + .unwrap_err(); + assert!(matches!(e1, ParquetBarsError::InvalidRowGroupRows)); + assert!(matches!(e4, ParquetBarsError::InvalidRowGroupRows)); + assert_no_parquet_or_tmp_under(d_par.path()); + } + + // 2. InvalidZstdLevel + { + let d_seq = TempDirGuard::new("par-err-zstd-seq"); + let d_par = TempDirGuard::new("par-err-zstd-par"); + let e1 = write_bars_1d_dataset( + d_seq.path(), + std::slice::from_ref(&valid_row), + opts_par(100, 99, 1), + ) + .unwrap_err(); + let e4 = write_bars_1d_dataset( + d_par.path(), + std::slice::from_ref(&valid_row), + opts_par(100, 99, 4), + ) + .unwrap_err(); + assert!(matches!( + e1, + ParquetBarsError::InvalidZstdLevel { level: 99 } + )); + assert!(matches!( + e4, + ParquetBarsError::InvalidZstdLevel { level: 99 } + )); + assert_no_parquet_or_tmp_under(d_par.path()); + } + + // 3. InvalidThreads (threads = 0) + { + let d_zero = TempDirGuard::new("par-err-threads-0"); + let err = write_bars_1d_dataset( + d_zero.path(), + std::slice::from_ref(&valid_row), + opts_par(100, 3, 0), + ) + .unwrap_err(); + assert!(matches!(err, ParquetBarsError::InvalidThreads)); + assert!(err.to_string().contains("threads")); + assert!(err.source().is_none()); + assert_no_parquet_or_tmp_under(d_zero.path()); + } + + // 4. UnsortedInput + { + let rows = vec![ + make_row(1, 2024, 1, 5, 10.0, 100.0, None, "USD", "eod_unadj"), + make_row(1, 2024, 1, 4, 10.0, 100.0, None, "USD", "eod_unadj"), + ]; + let d_seq = TempDirGuard::new("par-err-unsorted-seq"); + let d_par = TempDirGuard::new("par-err-unsorted-par"); + let e1 = write_bars_1d_dataset(d_seq.path(), &rows, opts_par(100, 3, 1)).unwrap_err(); + let e4 = write_bars_1d_dataset(d_par.path(), &rows, opts_par(100, 3, 4)).unwrap_err(); + assert_eq!(e1.to_string(), e4.to_string()); + assert!(matches!(e4, ParquetBarsError::UnsortedInput { .. })); + assert_no_parquet_or_tmp_under(d_par.path()); + } + + // 5. DuplicateKey + { + let rows = vec![ + make_row(1, 2024, 1, 5, 10.0, 100.0, None, "USD", "eod_unadj"), + make_row(1, 2024, 1, 5, 11.0, 200.0, None, "USD", "eod_unadj"), + ]; + let d_seq = TempDirGuard::new("par-err-dup-seq"); + let d_par = TempDirGuard::new("par-err-dup-par"); + let e1 = write_bars_1d_dataset(d_seq.path(), &rows, opts_par(100, 3, 1)).unwrap_err(); + let e4 = write_bars_1d_dataset(d_par.path(), &rows, opts_par(100, 3, 4)).unwrap_err(); + assert_eq!(e1.to_string(), e4.to_string()); + assert!(matches!(e4, ParquetBarsError::DuplicateKey { .. })); + assert_no_parquet_or_tmp_under(d_par.path()); + } + + // 6. SessionYearOutOfRange (later row) + { + let rows = vec![ + make_row(1, 2024, 1, 5, 10.0, 100.0, None, "USD", "eod_unadj"), + make_row( + 1, + MAX_PARQUET_YEAR + 1, + 1, + 2, + 10.0, + 100.0, + None, + "USD", + "eod_unadj", + ), + ]; + let d_seq = TempDirGuard::new("par-err-year-seq"); + let d_par = TempDirGuard::new("par-err-year-par"); + let e1 = write_bars_1d_dataset(d_seq.path(), &rows, opts_par(100, 3, 1)).unwrap_err(); + let e4 = write_bars_1d_dataset(d_par.path(), &rows, opts_par(100, 3, 4)).unwrap_err(); + assert_eq!(e1.to_string(), e4.to_string()); + assert!(matches!( + e4, + ParquetBarsError::SessionYearOutOfRange { year, .. } if year == MAX_PARQUET_YEAR + 1 + )); + assert_no_parquet_or_tmp_under(d_par.path()); + } +} + +#[test] +fn parallel_injected_single_year_failure_preserves_existing_and_cleans_staging() { + let tmp = TempDirGuard::new("par-single-year-fail"); + let seed = vec![ + make_row(1, 2023, 6, 15, 20.0, 200.0, None, "USD", "eod_unadj"), + make_row(1, 2024, 6, 15, 30.0, 300.0, None, "USD", "eod_unadj"), + ]; + write_bars_1d_dataset(tmp.path(), &seed, Bars1dWriteOptions::default()).unwrap(); + + let p2023 = tmp.path().join("bars_1d/year=2023/part.parquet"); + let p2024 = tmp.path().join("bars_1d/year=2024/part.parquet"); + let orig_2023 = fs::read(&p2023).unwrap(); + let orig_2024 = fs::read(&p2024).unwrap(); + + // Unowned foreign temp file must not be removed by our cleanup. + let foreign_tmp = tmp + .path() + .join("bars_1d/year=2024/part.parquet.foreign.tmp"); + fs::write(&foreign_tmp, b"foreign-tmp").unwrap(); + + let refresh = vec![ + make_row(1, 2022, 6, 15, 15.0, 150.0, None, "USD", "eod_unadj"), + make_row(1, 2023, 6, 15, 25.0, 250.0, None, "USD", "eod_unadj"), + make_row(1, 2024, 6, 15, 35.0, 350.0, None, "USD", "eod_unadj"), + make_row(1, 2025, 6, 15, 45.0, 450.0, None, "USD", "eod_unadj"), + ]; + + let err = write_bars_1d_dataset_internal( + tmp.path(), + &refresh, + Bars1dWriteOptions { + threads: 4, + ..Bars1dWriteOptions::default() + }, + DEFAULT_LOCK_TIMEOUT, + |year, tmp_path| { + if year == 2024 { + Err(ParquetBarsError::Io { + path: tmp_path.to_path_buf(), + source: io::Error::other("injected-year-2024"), + }) + } else { + Ok(()) + } + }, + |_, _, _| {}, + ) + .unwrap_err(); + + assert!( + matches!(err, ParquetBarsError::Io { .. }) + && err.to_string().contains("injected-year-2024"), + "unexpected error: {err:?}" + ); + assert_eq!(fs::read(&p2023).unwrap(), orig_2023); + assert_eq!(fs::read(&p2024).unwrap(), orig_2024); + assert!(!tmp.path().join("bars_1d/year=2022/part.parquet").exists()); + assert!(!tmp.path().join("bars_1d/year=2025/part.parquet").exists()); + assert!(!tmp.path().join("bars_1d/.write.lock").exists()); + assert_eq!(fs::read(&foreign_tmp).unwrap(), b"foreign-tmp"); + + // Remove the intentional foreign tmp, then confirm zero transient files remain. + fs::remove_file(&foreign_tmp).unwrap(); + assert_no_transient_files(&tmp.path().join("bars_1d")); +} + +#[test] +fn parallel_multi_year_failures_return_lowest_year_error_deterministically() { + let rows = vec![ + make_row(1, 2021, 5, 1, 10.0, 100.0, None, "USD", "eod_unadj"), + make_row(1, 2022, 5, 1, 20.0, 200.0, None, "USD", "eod_unadj"), + make_row(1, 2023, 5, 1, 30.0, 300.0, None, "USD", "eod_unadj"), + make_row(1, 2024, 5, 1, 40.0, 400.0, None, "USD", "eod_unadj"), + make_row(1, 2025, 5, 1, 50.0, 500.0, None, "USD", "eod_unadj"), + ]; + + for iter in 0..5 { + let tmp = TempDirGuard::new(&format!("par-multi-fail-{iter}")); + let err = write_bars_1d_dataset_internal( + tmp.path(), + &rows, + Bars1dWriteOptions { + threads: 4, + ..Bars1dWriteOptions::default() + }, + DEFAULT_LOCK_TIMEOUT, + |year, tmp_path| { + if year == 2022 || year == 2024 { + Err(ParquetBarsError::Io { + path: tmp_path.to_path_buf(), + source: io::Error::other(format!("injected-year-{year}")), + }) + } else { + Ok(()) + } + }, + |_, _, _| {}, + ) + .unwrap_err(); + + assert!( + err.to_string().contains("injected-year-2022"), + "iteration {iter}: expected lowest failing year 2022 error, got {err}" + ); + assert_no_parquet_or_tmp_under(tmp.path()); + } +} + +#[test] +fn parallel_worker_panic_returns_typed_error_cleans_up_and_does_not_poison_lock() { + let tmp = TempDirGuard::new("par-worker-panic"); + let rows = vec![ + make_row(1, 2022, 5, 1, 10.0, 100.0, None, "USD", "eod_unadj"), + make_row(1, 2023, 5, 1, 20.0, 200.0, None, "USD", "eod_unadj"), + make_row(1, 2024, 5, 1, 30.0, 300.0, None, "USD", "eod_unadj"), + make_row(1, 2025, 5, 1, 40.0, 400.0, None, "USD", "eod_unadj"), + ]; + + let err = write_bars_1d_dataset_internal( + tmp.path(), + &rows, + Bars1dWriteOptions { + threads: 4, + ..Bars1dWriteOptions::default() + }, + DEFAULT_LOCK_TIMEOUT, + |year, _| { + if year == 2023 { + panic!("boom-2023"); + } + Ok(()) + }, + |_, _, _| {}, + ) + .unwrap_err(); + + match &err { + ParquetBarsError::WorkerPanicked { year, detail } => { + assert_eq!(*year, 2023); + assert!(detail.contains("boom-2023"), "unexpected detail: {detail}"); + } + other => panic!("expected WorkerPanicked, got {other:?}"), + } + assert!(err.to_string().contains("2023")); + assert!(err.source().is_none()); + assert_no_parquet_or_tmp_under(tmp.path()); + + // Subsequent write to the same directory must succeed without lock poisoning or timeout. + let stats = write_bars_1d_dataset_with_hooks( + tmp.path(), + &rows, + Bars1dWriteOptions { + threads: 4, + ..Bars1dWriteOptions::default() + }, + Duration::from_millis(50), + |_, _, _| {}, + ) + .unwrap(); + assert_eq!(stats.rows_written, 4); + assert_eq!(stats.files_written, 4); + assert_no_transient_files(&tmp.path().join("bars_1d")); +} diff --git a/tools/curate-etl/src/run_curate_bars.rs b/tools/curate-etl/src/run_curate_bars.rs index fe8e113c..85cee9fb 100644 --- a/tools/curate-etl/src/run_curate_bars.rs +++ b/tools/curate-etl/src/run_curate_bars.rs @@ -40,7 +40,10 @@ use crate::bson_stream::{ use crate::curate_bars::{ curate_and_write_bars_1d, curate_bars_1d, CurateBars1dStats, CurateBarsWriteError, }; -use crate::parquet_bars::{write_bars_1d_dataset, Bars1dWriteOptions, Bars1dWriteStats}; +use crate::parquet_bars::{ + default_parallel_threads, write_bars_1d_dataset, Bars1dWriteOptions, Bars1dWriteStats, + ParquetBarsError, +}; use crate::provider_mapping::{ProviderMappingError, ProviderMappingRow, ProviderMappingTable}; use crate::shorts::epoch_days_to_ymd; use crate::split::{SplitError, SplitEvent, SplitTable}; @@ -48,6 +51,12 @@ use crate::split::{SplitError, SplitEvent, SplitTable}; /// Default relative volume tolerance passed to `curate_bars_1d` (matches `bench-curate-bars`). pub const DEFAULT_CURATE_BARS_REL_TOLERANCE: f64 = 0.01; +/// Default Parquet writer thread count for `curate-bars-1d` (`std::thread::available_parallelism()`, +/// falling back to `1`). +pub fn default_curate_bars_threads() -> usize { + default_parallel_threads() +} + /// Parsed arguments for the `curate-bars-1d` CLI command. #[derive(Debug, Clone, PartialEq)] pub struct CurateBars1dArgs { @@ -58,6 +67,7 @@ pub struct CurateBars1dArgs { pub listing_currencies: PathBuf, pub out_dir: PathBuf, pub rel_tolerance: f64, + pub threads: usize, } /// Accounting counters for re-keying `qmSplits` (`qmSearchCode` -> `listing_id` -> `eodSearchCode`). @@ -129,6 +139,7 @@ pub struct CurateBars1dRunReport { pub curate_stats: CurateBars1dStats, pub write_stats: Bars1dWriteStats, pub mismatch_samples: Vec>>, + pub threads: usize, pub elapsed_secs: f64, } @@ -142,6 +153,19 @@ pub(crate) struct CurateBars1dTimedRun { pub write_elapsed_secs: f64, } +/// Stage-timed run output comparing sequential (`threads=1`) vs parallel (`threads=par_threads`) +/// Parquet writes on the same curated rows for `bench-curate-bars-cmd`. +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct CurateBars1dTimedCompareRun { + pub report: CurateBars1dRunReport, + pub decode_elapsed_secs: f64, + pub qm_decode_rekey_elapsed_secs: f64, + pub curate_elapsed_secs: f64, + pub write_seq_elapsed_secs: f64, + pub write_par_elapsed_secs: f64, + pub write_stats_seq: Bars1dWriteStats, +} + /// Typed errors returned by [`run_curate_bars_1d`] and its TSV loaders. /// /// Every variant's `Display` output is a single line naming the offending path (and 1-based line @@ -892,6 +916,12 @@ fn load_and_decode_inputs( pub fn run_curate_bars_1d( args: &CurateBars1dArgs, ) -> Result { + if args.threads == 0 { + return Err(RunCurateBarsError::CurateWrite { + out_dir: args.out_dir.clone(), + source: CurateBarsWriteError::Parquet(ParquetBarsError::InvalidThreads), + }); + } let start = Instant::now(); let loaded = load_and_decode_inputs(args)?; @@ -904,7 +934,10 @@ pub fn run_curate_bars_1d( &loaded.mapping, "eod", &loaded.currencies, - Bars1dWriteOptions::default(), + Bars1dWriteOptions { + threads: args.threads, + ..Bars1dWriteOptions::default() + }, ) .map_err(|source| RunCurateBarsError::CurateWrite { out_dir: args.out_dir.clone(), @@ -931,15 +964,22 @@ pub fn run_curate_bars_1d( curate_stats: write_report.curate_stats, write_stats: write_report.write_stats, mismatch_samples: write_report.mismatch_samples, + threads: args.threads, elapsed_secs: start.elapsed().as_secs_f64(), }) } /// Stage-timed variant of [`run_curate_bars_1d`] sharing [`load_and_decode_inputs`] and calling -/// [`curate_bars_1d`] + [`write_bars_1d_dataset`] separately for `bench-curate-bars-cmd`. +/// [`curate_bars_1d`] + [`write_bars_1d_dataset`] separately. pub(crate) fn run_curate_bars_1d_timed( args: &CurateBars1dArgs, ) -> Result { + if args.threads == 0 { + return Err(RunCurateBarsError::CurateWrite { + out_dir: args.out_dir.clone(), + source: CurateBarsWriteError::Parquet(ParquetBarsError::InvalidThreads), + }); + } let total_start = Instant::now(); let decode_start = Instant::now(); @@ -963,12 +1003,18 @@ pub(crate) fn run_curate_bars_1d_timed( let curate_elapsed_secs = curate_start.elapsed().as_secs_f64(); let write_start = Instant::now(); - let write_stats = - write_bars_1d_dataset(&args.out_dir, &curated.rows, Bars1dWriteOptions::default()) - .map_err(|source| RunCurateBarsError::CurateWrite { - out_dir: args.out_dir.clone(), - source: CurateBarsWriteError::Parquet(source), - })?; + let write_stats = write_bars_1d_dataset( + &args.out_dir, + curated.rows, + Bars1dWriteOptions { + threads: args.threads, + ..Bars1dWriteOptions::default() + }, + ) + .map_err(|source| RunCurateBarsError::CurateWrite { + out_dir: args.out_dir.clone(), + source: CurateBarsWriteError::Parquet(source), + })?; let write_elapsed_secs = write_start.elapsed().as_secs_f64(); let report = CurateBars1dRunReport { @@ -991,6 +1037,7 @@ pub(crate) fn run_curate_bars_1d_timed( curate_stats: curated.stats, write_stats, mismatch_samples: curated.mismatch_samples, + threads: args.threads, elapsed_secs: total_start.elapsed().as_secs_f64(), }; @@ -1003,6 +1050,115 @@ pub(crate) fn run_curate_bars_1d_timed( }) } +/// Stage-timed variant for `bench-curate-bars-cmd`: decodes and curates once, then times +/// `write_bars_1d_dataset` on the exact same curated rows at `threads = 1` (into `seq_out_dir`) +/// and `threads = par_threads` (into `par_out_dir`). +pub(crate) fn run_curate_bars_1d_timed_compare( + args: &CurateBars1dArgs, + seq_out_dir: &Path, + par_out_dir: &Path, + par_threads: usize, +) -> Result { + if par_threads == 0 { + return Err(RunCurateBarsError::CurateWrite { + out_dir: par_out_dir.to_path_buf(), + source: CurateBarsWriteError::Parquet(ParquetBarsError::InvalidThreads), + }); + } + validate_out_dir(seq_out_dir)?; + validate_out_dir(par_out_dir)?; + let total_start = Instant::now(); + + let decode_start = Instant::now(); + let loaded = load_and_decode_inputs(args)?; + let decode_elapsed_secs = decode_start.elapsed().as_secs_f64(); + + let curate_start = Instant::now(); + let curated = curate_bars_1d( + loaded.bars, + &loaded.splits, + loaded.qm_volumes, + args.rel_tolerance, + &loaded.mapping, + "eod", + &loaded.currencies, + ) + .map_err(|source| RunCurateBarsError::CurateWrite { + out_dir: par_out_dir.to_path_buf(), + source: CurateBarsWriteError::Curate(source), + })?; + let curate_elapsed_secs = curate_start.elapsed().as_secs_f64(); + + let write_seq_start = Instant::now(); + let write_stats_seq = write_bars_1d_dataset( + seq_out_dir, + &curated.rows, + Bars1dWriteOptions { + threads: 1, + ..Bars1dWriteOptions::default() + }, + ) + .map_err(|source| RunCurateBarsError::CurateWrite { + out_dir: seq_out_dir.to_path_buf(), + source: CurateBarsWriteError::Parquet(source), + })?; + let write_seq_elapsed_secs = write_seq_start.elapsed().as_secs_f64(); + + let write_par_start = Instant::now(); + let write_stats_par = write_bars_1d_dataset( + par_out_dir, + &curated.rows, + Bars1dWriteOptions { + threads: par_threads, + ..Bars1dWriteOptions::default() + }, + ) + .map_err(|source| RunCurateBarsError::CurateWrite { + out_dir: par_out_dir.to_path_buf(), + source: CurateBarsWriteError::Parquet(source), + })?; + let write_par_elapsed_secs = write_par_start.elapsed().as_secs_f64(); + + assert_eq!( + write_stats_seq, write_stats_par, + "sequential and parallel write_bars_1d_dataset stats must match identically" + ); + + let report = CurateBars1dRunReport { + eod_docs_framed: loaded.eod_docs_framed, + eod_bytes_read: loaded.eod_bytes_read, + eod_decode: loaded.eod_decode, + splits_docs_framed: loaded.splits_docs_framed, + splits_bytes_read: loaded.splits_bytes_read, + splits_decode: loaded.splits_decode, + split_rekey: loaded.split_rekey, + qm_prices_present: loaded.qm_prices_present, + qm_prices_docs_framed: loaded.qm_prices_docs_framed, + qm_prices_bytes_read: loaded.qm_prices_bytes_read, + qm_prices_decode: loaded.qm_prices_decode, + qm_rekey: loaded.qm_rekey, + buffered_qm_bytes: loaded.buffered_qm_bytes, + bars_unmapped_source_dropped: loaded.bars_unmapped_source_dropped, + buffered_bars: loaded.buffered_bars, + buffered_bar_bytes: loaded.buffered_bar_bytes, + curate_stats: curated.stats, + write_stats: write_stats_par, + mismatch_samples: curated.mismatch_samples, + threads: par_threads, + elapsed_secs: total_start.elapsed().as_secs_f64(), + }; + + Ok(CurateBars1dTimedCompareRun { + report, + decode_elapsed_secs, + qm_decode_rekey_elapsed_secs: loaded.qm_decode_rekey_elapsed_secs, + curate_elapsed_secs, + write_seq_elapsed_secs, + write_par_elapsed_secs, + write_stats_seq, + }) +} + /// Formats [`CurateBars1dRunReport`] into a deterministic machine-readable `key=value` summary. /// /// Only the final `timing:` line contains wall-clock time (`elapsed_secs`). @@ -1139,6 +1295,7 @@ pub fn format_curate_bars_report(report: &CurateBars1dRunReport) -> String { out.push_str(" qm_check: qm_prices=absent\n"); } + let _ = writeln!(out, " config: threads={}", report.threads); let _ = write!(out, " timing: elapsed_secs={:.6}", report.elapsed_secs); out } diff --git a/tools/curate-etl/src/run_curate_bars_tests.rs b/tools/curate-etl/src/run_curate_bars_tests.rs index 5b0bafd2..8d7e2e47 100644 --- a/tools/curate-etl/src/run_curate_bars_tests.rs +++ b/tools/curate-etl/src/run_curate_bars_tests.rs @@ -199,6 +199,7 @@ fn end_to_end_happy_path_nvda_cross_provider_split() { listing_currencies: curr_path, out_dir: out_dir.clone(), rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, + threads: 1, }; let report = run_curate_bars_1d(&args).expect("curate-bars-1d happy path"); @@ -313,6 +314,7 @@ fn split_rekey_edge_cases_and_conservation_invariants() { listing_currencies: curr_path, out_dir: out_dir.clone(), rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, + threads: 1, }; let report = run_curate_bars_1d(&args).expect("split rekey test"); @@ -416,6 +418,7 @@ fn qm_alias_splits_collapse_identical_and_reject_conflicting_with_parquet_readba listing_currencies: curr_path.clone(), out_dir: out_ok.clone(), rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, + threads: 1, }) .expect("identical QM alias splits should collapse cleanly"); @@ -464,6 +467,7 @@ fn qm_alias_splits_collapse_identical_and_reject_conflicting_with_parquet_readba listing_currencies: curr_path, out_dir: out_conflict.clone(), rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, + threads: 1, }) .unwrap_err(); match &err { @@ -535,6 +539,7 @@ fn early_filter_missing_currency_and_full_bar_accounting() { listing_currencies: curr_path, out_dir: out_dir.clone(), rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, + threads: 1, }; let report = run_curate_bars_1d(&args).expect("accounting run"); @@ -666,6 +671,7 @@ fn failure_modes_return_typed_errors_and_leave_no_partial_dataset() { listing_currencies: valid_curr.clone(), out_dir: out1.clone(), rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, + threads: 1, }) .unwrap_err(); assert!(matches!(err, RunCurateBarsError::OpenInput { .. })); @@ -685,6 +691,7 @@ fn failure_modes_return_typed_errors_and_leave_no_partial_dataset() { listing_currencies: valid_curr.clone(), out_dir: out2.clone(), rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, + threads: 1, }) .unwrap_err(); assert!(matches!( @@ -711,6 +718,7 @@ fn failure_modes_return_typed_errors_and_leave_no_partial_dataset() { listing_currencies: valid_curr.clone(), out_dir: out3.clone(), rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, + threads: 1, }) .unwrap_err(); assert!(matches!( @@ -737,6 +745,7 @@ fn failure_modes_return_typed_errors_and_leave_no_partial_dataset() { listing_currencies: valid_curr.clone(), out_dir: out4.clone(), rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, + threads: 1, }) .unwrap_err(); assert!(matches!(err, RunCurateBarsError::TsvParse { line: 2, .. })); @@ -759,6 +768,7 @@ fn failure_modes_return_typed_errors_and_leave_no_partial_dataset() { listing_currencies: valid_curr.clone(), out_dir: out5.clone(), rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, + threads: 1, }) .unwrap_err(); assert!(matches!( @@ -781,6 +791,7 @@ fn failure_modes_return_typed_errors_and_leave_no_partial_dataset() { listing_currencies: valid_curr.clone(), out_dir: out_file.clone(), rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, + threads: 1, }) .unwrap_err(); assert!(matches!(err, RunCurateBarsError::InvalidOutDir { .. })); @@ -800,6 +811,7 @@ fn failure_modes_return_typed_errors_and_leave_no_partial_dataset() { listing_currencies: valid_curr, out_dir: out_obstructed.clone(), rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, + threads: 1, }) .unwrap_err(); assert!(matches!( @@ -873,6 +885,7 @@ fn deterministic_parquet_and_report_across_runs_and_shuffled_inputs_and_timed_pa listing_currencies: curr_path.clone(), out_dir: out1.clone(), rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, + threads: 1, }) .unwrap(); let r2 = run_curate_bars_1d(&CurateBars1dArgs { @@ -883,6 +896,7 @@ fn deterministic_parquet_and_report_across_runs_and_shuffled_inputs_and_timed_pa listing_currencies: curr_path.clone(), out_dir: out2.clone(), rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, + threads: 1, }) .unwrap(); let r3 = run_curate_bars_1d(&CurateBars1dArgs { @@ -893,6 +907,7 @@ fn deterministic_parquet_and_report_across_runs_and_shuffled_inputs_and_timed_pa listing_currencies: curr_path.clone(), out_dir: out3.clone(), rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, + threads: 1, }) .unwrap(); let rt = run_curate_bars_1d_timed(&CurateBars1dArgs { @@ -903,6 +918,7 @@ fn deterministic_parquet_and_report_across_runs_and_shuffled_inputs_and_timed_pa listing_currencies: curr_path, out_dir: out_timed.clone(), rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, + threads: 1, }) .unwrap(); @@ -953,6 +969,7 @@ fn rerun_with_narrower_year_range_replaces_emitted_year_and_leaves_older_year_un listing_currencies: curr_path.clone(), out_dir: out_dir.clone(), rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, + threads: 1, }) .expect("initial 2023+2024 run"); assert_eq!(r1.write_stats.rows_by_year.get(&2023), Some(&1)); @@ -975,6 +992,7 @@ fn rerun_with_narrower_year_range_replaces_emitted_year_and_leaves_older_year_un listing_currencies: curr_path, out_dir: out_dir.clone(), rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, + threads: 1, }) .expect("narrower 2024-only rerun"); assert_eq!(r2.write_stats.rows_by_year.len(), 1); @@ -1018,6 +1036,7 @@ fn failed_rerun_over_existing_dataset_leaves_published_partitions_byte_identical listing_currencies: valid_curr.clone(), out_dir: out_dir.clone(), rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, + threads: 1, }) .expect("seed existing dataset"); @@ -1048,6 +1067,7 @@ fn failed_rerun_over_existing_dataset_leaves_published_partitions_byte_identical listing_currencies: valid_curr.clone(), out_dir: out_dir.clone(), rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, + threads: 1, }) .is_err()); assert_unchanged_and_clean(); @@ -1066,6 +1086,7 @@ fn failed_rerun_over_existing_dataset_leaves_published_partitions_byte_identical listing_currencies: valid_curr.clone(), out_dir: out_dir.clone(), rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, + threads: 1, }) .is_err()); assert_unchanged_and_clean(); @@ -1081,6 +1102,7 @@ fn failed_rerun_over_existing_dataset_leaves_published_partitions_byte_identical listing_currencies: bad_curr, out_dir: out_dir.clone(), rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, + threads: 1, }) .is_err()); assert_unchanged_and_clean(); @@ -1107,6 +1129,7 @@ fn empty_and_all_unmapped_inputs_publish_nothing_and_account_cleanly() { listing_currencies: empty_curr, out_dir: out_empty.clone(), rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, + threads: 1, }) .expect("zero-byte inputs succeed"); assert_eq!(report_empty.eod_docs_framed, 0); @@ -1136,6 +1159,7 @@ fn empty_and_all_unmapped_inputs_publish_nothing_and_account_cleanly() { listing_currencies: curr_path, out_dir: out_unmapped.clone(), rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, + threads: 1, }) .expect("all-unmapped inputs succeed"); assert_eq!(report_unmapped.eod_docs_framed, 2); @@ -1188,6 +1212,7 @@ fn multi_forward_and_reverse_split_math_preserves_ohlc() { listing_currencies: curr_path, out_dir: out_dir.clone(), rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, + threads: 1, }) .expect("multi-split math"); assert_eq!(report.write_stats.rows_written, 5); @@ -1283,6 +1308,7 @@ fn tsv_loaders_reject_strict_edge_cases_and_accept_no_trailing_newline() { listing_currencies: no_nl_curr, out_dir: dir.path().join("out_inv_range"), rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, + threads: 1, }) .unwrap_err(); assert!(matches!( @@ -1432,6 +1458,7 @@ fn qm_prices_nvda_split_cross_check_mismatch_samples_and_readonly_parquet_invari listing_currencies: curr_path.clone(), out_dir: out_without.clone(), rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, + threads: 1, }) .unwrap(); @@ -1443,6 +1470,7 @@ fn qm_prices_nvda_split_cross_check_mismatch_samples_and_readonly_parquet_invari listing_currencies: curr_path.clone(), out_dir: out_with.clone(), rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, + threads: 1, }) .unwrap(); @@ -1454,6 +1482,7 @@ fn qm_prices_nvda_split_cross_check_mismatch_samples_and_readonly_parquet_invari listing_currencies: curr_path.clone(), out_dir: out_shuf.clone(), rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, + threads: 1, }) .unwrap(); @@ -1465,6 +1494,7 @@ fn qm_prices_nvda_split_cross_check_mismatch_samples_and_readonly_parquet_invari listing_currencies: curr_path, out_dir: out_timed.clone(), rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, + threads: 1, }) .unwrap(); @@ -1609,6 +1639,7 @@ fn qm_prices_date_aware_rekey_reused_ticker_rename_alias_fanout_and_unmapped_cou listing_currencies: curr_path, out_dir: dir.path().join("out"), rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, + threads: 1, }) .unwrap(); @@ -1626,3 +1657,113 @@ fn qm_prices_date_aware_rekey_reused_ticker_rename_alias_fanout_and_unmapped_cou assert_eq!(b.volume_mismatched, 0); assert_eq!(b.volume_unchecked, 0); } + +#[test] +fn run_curate_bars_1d_threads_1_and_4_produce_byte_identical_parquet_and_matching_report() { + let dir = TestTempDir::new("threads-parity"); + let map_path = dir.path().join("provider_mapping.tsv"); + let curr_path = dir.path().join("listing_currencies.tsv"); + let splits_path = dir.path().join("qmSplits.bson"); + let eod_path = dir.path().join("eodPrices.bson"); + + write_bytes( + &map_path, + b"eod\tAAA.US\t2020-01-01\t\t10\n\ + eod\tBBB.TO\t2020-01-01\t\t20\n\ + qm\tAAA:US\t2020-01-01\t\t10\n", + ); + write_bytes(&curr_path, b"10\tUSD\n20\tCAD\n"); + write_bytes(&splits_path, &split_doc("AAA:US", "2023-06-01", 2.0)); + + let eod_docs = [ + eod_doc("AAA.US", "2021-03-10", 10.0, 11.0, 9.5, 10.5, 2000.0), + eod_doc("AAA.US", "2022-04-12", 12.0, 13.0, 11.5, 12.5, 2400.0), + eod_doc("AAA.US", "2023-07-14", 14.0, 15.0, 13.5, 14.5, 1500.0), + eod_doc("BBB.TO", "2022-05-02", 20.0, 21.0, 19.5, 20.5, 3000.0), + eod_doc("BBB.TO", "2024-08-08", 22.0, 23.0, 21.5, 22.5, 3200.0), + ]; + write_bytes(&eod_path, &eod_docs.concat()); + + let out_1 = dir.path().join("out_t1"); + let out_4 = dir.path().join("out_t4"); + + let r1 = run_curate_bars_1d(&CurateBars1dArgs { + eod_prices: eod_path.clone(), + qm_splits: splits_path.clone(), + qm_prices: None, + provider_mapping: map_path.clone(), + listing_currencies: curr_path.clone(), + out_dir: out_1.clone(), + rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, + threads: 1, + }) + .unwrap(); + let r4 = run_curate_bars_1d(&CurateBars1dArgs { + eod_prices: eod_path.clone(), + qm_splits: splits_path.clone(), + qm_prices: None, + provider_mapping: map_path.clone(), + listing_currencies: curr_path.clone(), + out_dir: out_4.clone(), + rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, + threads: 4, + }) + .unwrap(); + + assert_eq!(r1.threads, 1); + assert_eq!(r4.threads, 4); + assert_eq!(r1.write_stats, r4.write_stats); + assert_eq!(r1.curate_stats, r4.curate_stats); + + for year in [2021_i32, 2022, 2023, 2024] { + let rel = format!("bars_1d/year={year:04}/part.parquet"); + assert_eq!( + fs::read(out_1.join(&rel)).unwrap(), + fs::read(out_4.join(&rel)).unwrap(), + "byte mismatch for {rel}" + ); + } + + let strip_config_and_timing = |text: &str| -> String { + text.lines() + .filter(|line| { + let t = line.trim_start(); + !t.starts_with("config:") && !t.starts_with("timing:") + }) + .collect::>() + .join("\n") + }; + let rep1 = format_curate_bars_report(&r1); + let rep4 = format_curate_bars_report(&r4); + assert!(rep1.contains(" config: threads=1\n"), "{rep1}"); + assert!(rep4.contains(" config: threads=4\n"), "{rep4}"); + assert_eq!( + strip_config_and_timing(&rep1), + strip_config_and_timing(&rep4) + ); + + // Zero threads fails closed before touching --out. + let out_0 = dir.path().join("out_t0"); + let err = run_curate_bars_1d(&CurateBars1dArgs { + eod_prices: eod_path, + qm_splits: splits_path, + qm_prices: None, + provider_mapping: map_path, + listing_currencies: curr_path, + out_dir: out_0.clone(), + rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, + threads: 0, + }) + .unwrap_err(); + assert!( + matches!( + err, + RunCurateBarsError::CurateWrite { + source: CurateBarsWriteError::Parquet(crate::parquet_bars::ParquetBarsError::InvalidThreads), + .. + } + ), + "unexpected error: {err:?}" + ); + assert!(!out_0.exists()); +} diff --git a/tools/curate-etl/tests/cli.rs b/tools/curate-etl/tests/cli.rs index 1cff1cd1..4e841adb 100644 --- a/tools/curate-etl/tests/cli.rs +++ b/tools/curate-etl/tests/cli.rs @@ -456,6 +456,135 @@ fn curate_bars_1d_cli_happy_path_and_determinism_with_shuffled_bson() { assert!(text_a.contains("qm_check: qm_prices=absent"), "{text_a}"); } +#[test] +fn curate_bars_1d_cli_threads_flag_parity_and_validation() { + let dir = CliTempDir::new("bars-threads-cli"); + let map_path = dir.path.join("provider_mapping.tsv"); + let curr_path = dir.path.join("listing_currencies.tsv"); + let eod_path = dir.path.join("eod.bson"); + let splits_path = dir.path.join("splits.bson"); + + fs::write( + &map_path, + "eod\tAAPL.US\t2020-01-01\t\t10\neod\tSHOP.TO\t2020-01-01\t\t20\nqm\tAAPL:US\t2020-01-01\t\t10\n", + ) + .unwrap(); + fs::write(&curr_path, "10\tUSD\n20\tCAD\n").unwrap(); + + let mut eod_bytes = Vec::new(); + eod_bytes.extend_from_slice(&make_eod_doc("AAPL.US", "2022-05-03", 150.0, 2_000.0)); + eod_bytes.extend_from_slice(&make_eod_doc("AAPL.US", "2023-06-05", 170.0, 1_500.0)); + eod_bytes.extend_from_slice(&make_eod_doc("SHOP.TO", "2024-07-08", 80.0, 3_000.0)); + eod_bytes.extend_from_slice(&make_eod_doc("SHOP.TO", "2025-02-10", 90.0, 2_500.0)); + fs::write(&eod_path, &eod_bytes).unwrap(); + fs::write(&splits_path, make_split_doc("AAPL:US", "2023-01-10", 2.0)).unwrap(); + + let out_t1 = dir.path.join("out_t1"); + let out_t4 = dir.path.join("out_t4"); + + let run_1 = run(&[ + "curate-bars-1d", + "--eod-prices", + eod_path.to_str().unwrap(), + "--qm-splits", + splits_path.to_str().unwrap(), + "--provider-mapping", + map_path.to_str().unwrap(), + "--listing-currencies", + curr_path.to_str().unwrap(), + "--out", + out_t1.to_str().unwrap(), + "--threads", + "1", + ]); + assert!(run_1.status.success(), "{}", stderr(&run_1)); + assert!(stderr(&run_1).is_empty(), "{}", stderr(&run_1)); + + let run_4 = run(&[ + "curate-bars-1d", + "--eod-prices", + eod_path.to_str().unwrap(), + "--qm-splits", + splits_path.to_str().unwrap(), + "--provider-mapping", + map_path.to_str().unwrap(), + "--listing-currencies", + curr_path.to_str().unwrap(), + "--out", + out_t4.to_str().unwrap(), + "--threads", + "4", + ]); + assert!(run_4.status.success(), "{}", stderr(&run_4)); + assert!(stderr(&run_4).is_empty(), "{}", stderr(&run_4)); + + let text_1 = stdout(&run_1); + let text_4 = stdout(&run_4); + assert!(text_1.contains(" config: threads=1\n"), "{text_1}"); + assert!(text_4.contains(" config: threads=4\n"), "{text_4}"); + + let strip_threads_and_timing = |s: &str| { + s.lines() + .filter(|l| { + let t = l.trim_start(); + !t.starts_with("config:") && !t.starts_with("timing:") + }) + .collect::>() + .join("\n") + }; + assert_eq!( + strip_threads_and_timing(&text_1), + strip_threads_and_timing(&text_4) + ); + + for year in [2022_i32, 2023, 2024, 2025] { + let rel = format!("bars_1d/year={year:04}/part.parquet"); + assert_eq!( + fs::read(out_t1.join(&rel)).unwrap(), + fs::read(out_t4.join(&rel)).unwrap(), + "CLI --threads 1 vs --threads 4 diverged on {rel}" + ); + } + + // Invalid --threads invocations must exit non-zero, print usage on stderr, and write nothing. + for (label, extra) in [ + ("zero", vec!["--threads", "0"]), + ("alpha", vec!["--threads", "abc"]), + ("neg", vec!["--threads=-1"]), + ("missing", vec!["--threads"]), + ("dup", vec!["--threads", "2", "--threads", "4"]), + ] { + let bad_out = dir.path.join(format!("out_bad_{label}")); + let mut argv = vec![ + "curate-bars-1d", + "--eod-prices", + eod_path.to_str().unwrap(), + "--qm-splits", + splits_path.to_str().unwrap(), + "--provider-mapping", + map_path.to_str().unwrap(), + "--listing-currencies", + curr_path.to_str().unwrap(), + "--out", + bad_out.to_str().unwrap(), + ]; + argv.extend(extra); + let res = run(&argv); + assert!( + !res.status.success(), + "{label}: expected non-zero exit, stdout={}", + stdout(&res) + ); + let err_text = stderr(&res); + assert!(err_text.contains("Usage:"), "{label}: missing usage in {err_text}"); + assert!( + !bad_out.exists(), + "{label}: invalid --threads must not create '{}'", + bad_out.display() + ); + } +} + fn make_qm_price_doc(code: &str, date: &str, share_volume: f64) -> Vec { let mut doc = RawDocumentBuf::new(); doc.append(cstr!("qmSearchCode"), code); @@ -930,7 +1059,9 @@ fn bench_curate_bars_cmd_small_run_succeeds_and_reports_splits() { assert!(text.contains("qm:"), "{text}"); assert!(text.contains("injected="), "{text}"); assert!(text.contains("curate:"), "{text}"); + assert!(text.contains("write_1: threads=1 "), "{text}"); assert!(text.contains("write:"), "{text}"); + assert!(text.contains("speedup="), "{text}"); assert!(text.contains("total:"), "{text}"); assert!(text.contains("bytes/bar"), "{text}"); } diff --git a/tools/curate-etl/tests/run_curate_bars_merge_qa.rs b/tools/curate-etl/tests/run_curate_bars_merge_qa.rs index a7a5f877..22de7314 100644 --- a/tools/curate-etl/tests/run_curate_bars_merge_qa.rs +++ b/tools/curate-etl/tests/run_curate_bars_merge_qa.rs @@ -85,6 +85,7 @@ fn args_for(dir: &TempDir, out: &str, rel_tolerance: f64) -> CurateBars1dArgs { listing_currencies: dir.join("listing_currencies.tsv"), out_dir: dir.join(out), rel_tolerance, + threads: 1, } } diff --git a/tools/curate-etl/tests/run_curate_bars_qa_contract.rs b/tools/curate-etl/tests/run_curate_bars_qa_contract.rs index 9f763424..bdc3c593 100644 --- a/tools/curate-etl/tests/run_curate_bars_qa_contract.rs +++ b/tools/curate-etl/tests/run_curate_bars_qa_contract.rs @@ -136,6 +136,7 @@ fn args_for(dir: &TempDir, out: &str) -> CurateBars1dArgs { listing_currencies: dir.join("listing_currencies.tsv"), out_dir: dir.join(out), rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, + threads: 1, } } diff --git a/tools/curate-etl/tests/run_curate_bars_qm_qa_contract.rs b/tools/curate-etl/tests/run_curate_bars_qm_qa_contract.rs index a1ca5027..15a0b952 100644 --- a/tools/curate-etl/tests/run_curate_bars_qm_qa_contract.rs +++ b/tools/curate-etl/tests/run_curate_bars_qm_qa_contract.rs @@ -169,6 +169,7 @@ fn args_for(dir: &TempDir, out: &str, qm: Option<&str>) -> CurateBars1dArgs { listing_currencies: dir.join("listing_currencies.tsv"), out_dir: dir.join(out), rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE, + threads: 1, } }