From 5442b9cd16f75c7c32070e847042ed585042ce88 Mon Sep 17 00:00:00 2001 From: Studio Date: Sat, 28 Nov 2026 18:47:26 -0500 Subject: [PATCH 1/3] =?UTF-8?q?T-102:=20M1.2t=20=E2=80=94=20`tools/curate-?= =?UTF-8?q?etl`:=20pure=20`fx=5F1d`=20curation=20stage=20(`CAD.FOREX`=20+?= =?UTF-8?q?=20`teMarketData.USDCAD`=20daily=20bars=20=E2=86=92=20`Fx1dParq?= =?UTF-8?q?uetRow`s=20with=20`ts`/`known=5Fat`=20=E2=86=92=20Zstd=20Parque?= =?UTF-8?q?t)=20with=20tests=20and=20local=20benchmark=20(no=20new=20crate?= =?UTF-8?q?s)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/README.md | 39 ++ tools/curate-etl/src/bench.rs | 276 ++++++++++-- tools/curate-etl/src/cli.rs | 44 +- tools/curate-etl/src/curate_fx.rs | 195 ++++++++ tools/curate-etl/src/curate_fx_tests.rs | 572 ++++++++++++++++++++++++ tools/curate-etl/src/lib.rs | 7 + tools/curate-etl/src/main.rs | 74 ++- tools/curate-etl/tests/cli.rs | 39 ++ 8 files changed, 1202 insertions(+), 44 deletions(-) create mode 100644 tools/curate-etl/src/curate_fx.rs create mode 100644 tools/curate-etl/src/curate_fx_tests.rs diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index 9fa5f802..f2b1d5af 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -764,3 +764,42 @@ Command (`2026-11-28`, two back-to-back runs with identical checksum `0xde3b3bd6 - Stage (in-memory): `elapsed=1002.51 ms`, `throughput=1994998 rows/s`, `latency=501.25 ns/row`, `checksum=0xde3b3bd654c65ebe` - Parquet write: `elapsed=228.03 ms`, `throughput=8494083 rows/s` - Combined (stage → Parquet): `elapsed=1230.53 ms`, `throughput=1625311 rows/s` + +## `fx_1d` Curation Stage (`M1.2t`) + +`curate_fx_1d` and `curate_and_write_fx_1d` (`src/curate_fx.rs`) join `build_fx_1d` and `write_fx_1d_dataset` into contract `Fx1dParquetRow` records sorted and unique by `session_date` (no `provider_mapping` lookup is needed because FX rows are keyed by `pair = "USDCAD"`, not `listing_id`). + +1. **Field & timestamp rules:** + - Calls `build_fx_1d` unchanged (`CAD.FOREX` takes precedence on overlapping dates, `teMarketData.USDCAD` fills interior gaps and the post-EOD tail, the read-only 1% overlap cross-check runs untouched, and all `Fx1dStats` counters are carried through unchanged). + - Maps every `Fx1dRow` via `Fx1dParquetRow::from_fx_row` with zero per-row heap allocation (`pair = "USDCAD"` and `source` ∈ `{"eod_cad_forex", "te_usdcad"}` stay `Cow::Borrowed`), preserving the strictly ascending, unique `session_date` order. + - **Conservative no-look-ahead timestamp rule:** stamps every row with `ts_micros = known_at_micros = (session_date + 1) * FX_1D_MICROS_PER_DAY - 1` (`23:59:59.999999 UTC` of `session_date`, offset `FX_1D_TS_OFFSET_MICROS_FROM_DAY_START = 86_399_999_999` from UTC midnight) via `fx_1d_utc_day_end_micros`. Neither `CAD.FOREX` nor `teMarketData.USDCAD` documents its daily FX cutoff, so the last microsecond of the UTC day is the conservative no-look-ahead choice (same-day `16:00 ET` equity close signals resolve to the prior UTC day's bar), satisfies `parquet_fx`'s `TsOutsideSessionDate` and `KnownAtBeforeTs` checks, and requires no DST table for `1971–1975` (outside `session_close.rs`'s `1976–2030` window). +2. **Accounting & error handling:** + - Exact conservation invariant in `CurateFx1dStats`: `rows_in == builder.rows_out == rows_out`, with `stats.builder` bit-identical to calling `build_fx_1d` directly. + - Checked `i64` arithmetic: any `session_date` whose UTC day-end microsecond timestamp overflows `i64` (`session_date >= 106_751_991` or `session_date <= -106_751_993`, including `i32::MAX` / `i32::MIN`) returns `CurateFxError::SessionDateOutOfRange { session_date }` without panicking or wrapping. + - `curate_and_write_fx_1d` runs `curate_fx_1d` before invoking `write_fx_1d_dataset`, so any `CurateFxError` leaves `out_dir` untouched (and surfaces via `CurateFxWriteError::{Curate, Parquet}`). +3. **Still out of scope:** + - Live MongoDB cursor / BSON decoders for `CAD.FOREX` and `teMarketData.USDCAD` documents + - Intraday `fx_1m` curation + +### `bench-curate-fx` + +Fixed-seed (`std`-only SplitMix64) benchmark over `20,000` (default; real dataset is ~15k rows) or `[rows]` daily USD/CAD bars (~80% `CAD.FOREX`, ~20% `teMarketData.USDCAD` with overlap window, interior EOD gaps, post-EOD TE tail, and injected invalid/inconsistent/duplicate rows), separately timing in-memory `curate_fx_1d` and Zstd Parquet `write_fx_1d_dataset` into a temp directory with footer row-count verification and cleanup: + +```bash +cargo run --release -p curate-etl --offline -- bench-curate-fx [rows] +``` + +1. Default run (`2026-11-28`): `cargo run --release -p curate-etl --offline -- bench-curate-fx` + - Input: `rows=20000`, `eod_rows=16000`, `te_rows=4000` + - Builder: `rows_out=17180` (`eod_out=15341`, `te_out=1839`, `eod_invalid=164`, `eod_inconsistent=178`, `eod_dup_collapsed=145`, `eod_dup_conflict=172`, `te_invalid=18`, `te_inconsistent=26`, `te_dup_collapsed=27`, `te_dup_conflict=14`) + - Stage (in-memory): `rows_out=17180` (`85.90%` retained), `elapsed=1.070 ms`, `throughput=18683801 rows/s`, `latency=53.52 ns/row`, `checksum=0x298f47e68cdf7022` + - Parquet write: `files=1`, `row_groups=1`, `bytes=714498`, `read_back_rows=17180`, `elapsed=16.691 ms`, `throughput=1029303 rows/s` + - Combined (stage → Parquet): `elapsed=17.761 ms`, `throughput=1126041 rows/s` + - Overlap: `te_superseded=2076`, `checked=2076`, `within_tol=1979`, `mismatched=97`, `max_overlap_rel=0.025000` +2. 1M-row run (`2026-11-28`): `cargo run --release -p curate-etl --offline -- bench-curate-fx 1000000` + - Input: `rows=1000000`, `eod_rows=800000`, `te_rows=200000` + - Builder: `rows_out=859916` (`eod_out=767923`, `te_out=91993`, `eod_invalid=8245`, `eod_inconsistent=8035`, `eod_dup_collapsed=7794`, `eod_dup_conflict=8003`, `te_invalid=1214`, `te_inconsistent=1198`, `te_dup_collapsed=1213`, `te_dup_conflict=1213`) + - Stage (in-memory): `rows_out=859916` (`85.99%` retained), `elapsed=59.652 ms`, `throughput=16763900 rows/s`, `latency=59.65 ns/row`, `checksum=0x2a2f2665b32d8ae0` + - Parquet write: `files=1`, `row_groups=1`, `bytes=27440094`, `read_back_rows=859916`, `elapsed=215.804 ms`, `throughput=3984706 rows/s` + - Combined (stage → Parquet): `elapsed=275.456 ms`, `throughput=3630342 rows/s` + - Overlap: `te_superseded=103169`, `checked=103169`, `within_tol=97958`, `mismatched=5211`, `max_overlap_rel=0.025000` diff --git a/tools/curate-etl/src/bench.rs b/tools/curate-etl/src/bench.rs index 9a656118..7ced525e 100644 --- a/tools/curate-etl/src/bench.rs +++ b/tools/curate-etl/src/bench.rs @@ -714,37 +714,8 @@ fn next_weekday(date: i32) -> i32 { } } -/// Runs the fixed-seed `build_fx_1d` + [`fx_rate_on_or_before`] benchmark for `rows` total daily -/// FX rows across `CAD.FOREX` (~80%) and `teMarketData.USDCAD` (~20%). -/// -/// Generates deterministic USD/CAD bars with an overlap window, interior EOD gaps, a post-EOD TE -/// tail, small shares of invalid/inconsistent/identical-duplicate/conflicting-duplicate rows, and -/// ~5% intentional overlap mismatches. Shuffles both inputs deterministically, times -/// [`build_fx_1d`], then times [`DEFAULT_FX_BENCH_LOOKUPS`] (`1_000_000`, or `0` when `rows == 0`) -/// zero-allocation [`fx_rate_on_or_before`] lookups. -pub fn run_fx_benchmark(rows: usize) -> FxBenchReport { - if rows == 0 { - let built = build_fx_1d(&[], &[]); - return FxBenchReport { - rows: 0, - eod_rows_in: 0, - te_rows_in: 0, - rows_out: 0, - build_elapsed_ms: 0.0, - build_rows_per_sec: 0.0, - build_ns_per_row: 0.0, - lookups: 0, - lookup_hits: 0, - lookup_elapsed_ms: 0.0, - lookups_per_sec: 0.0, - ns_per_lookup: 0.0, - checksum: 0, - stats: built.stats, - }; - } - +fn generate_fx_bench_inputs(rows: usize, rng: &mut SplitMix64) -> (Vec, Vec) { let base_date = ymd_to_epoch_days(1971, 1, 4).unwrap_or(368); - let mut rng = SplitMix64::new(FX_BENCH_SEED); let te_target = rows / 5; let eod_target = rows - te_target; @@ -938,8 +909,44 @@ pub fn run_fx_benchmark(rows: usize) -> FxBenchReport { }); } - shuffle_slice(&mut eod, &mut rng); - shuffle_slice(&mut te, &mut rng); + shuffle_slice(&mut eod, rng); + shuffle_slice(&mut te, rng); + + (eod, te) +} + +/// Runs the fixed-seed `build_fx_1d` + [`fx_rate_on_or_before`] benchmark for `rows` total daily +/// FX rows across `CAD.FOREX` (~80%) and `teMarketData.USDCAD` (~20%). +/// +/// Generates deterministic USD/CAD bars with an overlap window, interior EOD gaps, a post-EOD TE +/// tail, small shares of invalid/inconsistent/identical-duplicate/conflicting-duplicate rows, and +/// ~5% intentional overlap mismatches. Shuffles both inputs deterministically, times +/// [`build_fx_1d`], then times [`DEFAULT_FX_BENCH_LOOKUPS`] (`1_000_000`, or `0` when `rows == 0`) +/// zero-allocation [`fx_rate_on_or_before`] lookups. +pub fn run_fx_benchmark(rows: usize) -> FxBenchReport { + if rows == 0 { + let built = build_fx_1d(&[], &[]); + return FxBenchReport { + rows: 0, + eod_rows_in: 0, + te_rows_in: 0, + rows_out: 0, + build_elapsed_ms: 0.0, + build_rows_per_sec: 0.0, + build_ns_per_row: 0.0, + lookups: 0, + lookup_hits: 0, + lookup_elapsed_ms: 0.0, + lookups_per_sec: 0.0, + ns_per_lookup: 0.0, + checksum: 0, + stats: built.stats, + }; + } + + let base_date = ymd_to_epoch_days(1971, 1, 4).unwrap_or(368); + let mut rng = SplitMix64::new(FX_BENCH_SEED); + let (eod, te) = generate_fx_bench_inputs(rows, &mut rng); let eod_rows_in = eod.len(); let te_rows_in = te.len(); @@ -4858,6 +4865,145 @@ pub fn run_curate_shorts_benchmark( Ok(report) } +pub const DEFAULT_CURATE_FX_BENCH_ROWS: usize = 20_000; +const CURATE_FX_BENCH_SEED: u64 = 0x570C_4B07_C04A_F81D; + +/// Summary metrics produced by [`run_curate_fx_benchmark`]. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct CurateFxBenchReport { + pub rows: usize, + pub eod_rows_in: usize, + pub te_rows_in: usize, + pub rows_out: usize, + pub stage_elapsed_ms: f64, + pub stage_rows_per_sec: f64, + pub stage_ns_per_row: f64, + pub parquet_elapsed_ms: f64, + pub parquet_rows_per_sec: f64, + pub total_elapsed_ms: f64, + pub total_rows_per_sec: f64, + pub files_written: usize, + pub row_groups_written: usize, + pub bytes_written: u64, + pub read_back_rows: usize, + pub checksum: u64, + pub stats: crate::curate_fx::CurateFx1dStats, +} + +fn run_curate_fx_benchmark_tracked( + rows: usize, +) -> Result<(CurateFxBenchReport, PathBuf), crate::curate_fx::CurateFxWriteError> { + use crate::curate_fx::{curate_fx_1d, CurateFx1dStats, CurateFxWriteError}; + + let temp = BenchTempDir::new_in_with_prefix(&std::env::temp_dir(), "curate-etl-bench-curate-fx") + .map_err(|(path, source)| CurateFxWriteError::Parquet(ParquetFxError::Io { path, source }))?; + let temp_path = temp.path.clone(); + + if rows == 0 { + let curated = curate_fx_1d(&[], &[])?; + let write_stats = + write_fx_1d_dataset(&temp.path, &curated.rows, Fx1dWriteOptions::default())?; + let read_back_rows = verify_parquet_fx_row_count(&temp.path, 0)?; + drop(temp); + return Ok(( + CurateFxBenchReport { + rows: 0, + eod_rows_in: 0, + te_rows_in: 0, + rows_out: 0, + stage_elapsed_ms: 0.0, + stage_rows_per_sec: 0.0, + stage_ns_per_row: 0.0, + parquet_elapsed_ms: 0.0, + parquet_rows_per_sec: 0.0, + total_elapsed_ms: 0.0, + total_rows_per_sec: 0.0, + files_written: write_stats.files_written, + row_groups_written: write_stats.row_groups_written, + bytes_written: write_stats.bytes_written, + read_back_rows, + checksum: 0, + stats: CurateFx1dStats::default(), + }, + temp_path, + )); + } + + let mut rng = SplitMix64::new(CURATE_FX_BENCH_SEED); + let (eod, te) = generate_fx_bench_inputs(rows, &mut rng); + let eod_rows_in = eod.len(); + let te_rows_in = te.len(); + + // 1. Time pure in-memory curation stage. + let stage_start = Instant::now(); + let curated = curate_fx_1d(&eod, &te)?; + let stage_elapsed_secs = stage_start.elapsed().as_secs_f64(); + let stage_elapsed_ms = stage_elapsed_secs * 1_000.0; + + let mut hash = 0u64; + for row in &curated.rows { + hash = mix_str_u64(hash, row.pair.as_ref()); + hash = mix_u64(hash, row.session_date as u64); + hash = mix_u64(hash, row.ts_micros as u64); + hash = mix_u64(hash, row.open.to_bits()); + hash = mix_u64(hash, row.high.to_bits()); + hash = mix_u64(hash, row.low.to_bits()); + hash = mix_u64(hash, row.close.to_bits()); + hash = mix_str_u64(hash, row.source.as_ref()); + hash = mix_u64(hash, row.known_at_micros as u64); + } + let checksum = black_box(hash); + + // 2. Separately time Parquet write to temp dir. + let parquet_start = Instant::now(); + let write_stats = + write_fx_1d_dataset(&temp.path, &curated.rows, Fx1dWriteOptions::default())?; + let parquet_elapsed_secs = parquet_start.elapsed().as_secs_f64(); + let parquet_elapsed_ms = parquet_elapsed_secs * 1_000.0; + + let read_back_rows = verify_parquet_fx_row_count(&temp.path, curated.rows.len())?; + + let (stage_rows_per_sec, stage_ns_per_row) = compute_rates(rows, stage_elapsed_secs); + let (parquet_rows_per_sec, _) = compute_rates(curated.rows.len(), parquet_elapsed_secs); + let total_elapsed_secs = stage_elapsed_secs + parquet_elapsed_secs; + let total_elapsed_ms = total_elapsed_secs * 1_000.0; + let (total_rows_per_sec, _) = compute_rates(rows, total_elapsed_secs); + + let report = CurateFxBenchReport { + rows, + eod_rows_in, + te_rows_in, + rows_out: curated.stats.rows_out, + stage_elapsed_ms, + stage_rows_per_sec, + stage_ns_per_row, + parquet_elapsed_ms, + parquet_rows_per_sec, + total_elapsed_ms, + total_rows_per_sec, + files_written: write_stats.files_written, + row_groups_written: write_stats.row_groups_written, + bytes_written: write_stats.bytes_written, + read_back_rows, + checksum, + stats: curated.stats, + }; + + drop(temp); + Ok((report, temp_path)) +} + +/// Runs the fixed-seed `fx_1d` curation stage + Zstd Parquet write benchmark for `rows` total +/// daily USD/CAD bars across `CAD.FOREX` (~80%) and `teMarketData.USDCAD` (~20%), separately +/// timing in-memory `curate_fx_1d` and Zstd Parquet `write_fx_1d_dataset` into a temp directory +/// removed on drop. +pub fn run_curate_fx_benchmark( + rows: usize, +) -> Result { + let (report, _) = run_curate_fx_benchmark_tracked(rows)?; + Ok(report) +} + #[cfg(test)] mod tests { use super::*; @@ -6062,4 +6208,70 @@ mod tests { ); assert!(curated.stats.rows_out > 25_000 * 90 / 100); } + + #[test] + fn curate_fx_benchmark_small_run_is_deterministic_and_cleans_up() { + let (a, dir_a) = run_curate_fx_benchmark_tracked(2_000).unwrap(); + let (b, dir_b) = run_curate_fx_benchmark_tracked(2_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, 2_000); + assert_eq!(a.eod_rows_in + a.te_rows_in, 2_000); + assert!(a.rows_out > 0); + assert_eq!(a.rows_out, b.rows_out); + assert_eq!(a.read_back_rows, a.rows_out); + assert_eq!(a.stats.rows_in, a.stats.builder.rows_out); + assert_eq!(a.stats.rows_out, a.stats.rows_in); + assert_eq!(a.files_written, 1); + 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.stats, b.stats); + assert_eq!(a.checksum, b.checksum); + assert_ne!(a.checksum, 0); + assert!(a.stage_rows_per_sec.is_finite() && a.stage_rows_per_sec >= 0.0); + assert!(a.stage_ns_per_row.is_finite() && a.stage_ns_per_row >= 0.0); + assert!(a.parquet_rows_per_sec.is_finite() && a.parquet_rows_per_sec >= 0.0); + assert!(a.total_rows_per_sec.is_finite() && a.total_rows_per_sec >= 0.0); + assert!(a.stats.builder.eod.dropped_invalid_ohlc > 0); + assert!(a.stats.builder.eod.dropped_inconsistent_ohlc > 0); + assert!(a.stats.builder.eod.duplicate_collapsed > 0); + assert!(a.stats.builder.eod.duplicate_conflict_dropped > 0); + assert!(a.stats.builder.te_superseded_by_eod > 0); + assert!(a.stats.builder.overlap_within_tolerance > 0); + assert!(a.stats.builder.overlap_mismatched > 0); + assert!(a.stats.builder.te_rows_out > 0); + } + + #[test] + fn curate_fx_benchmark_zero_rows_handles_cleanly() { + let (report, dir) = run_curate_fx_benchmark_tracked(0).unwrap(); + assert!(!dir.exists(), "temp dir {} should be removed", dir.display()); + assert_eq!(report.rows, 0); + assert_eq!(report.eod_rows_in, 0); + assert_eq!(report.te_rows_in, 0); + assert_eq!(report.rows_out, 0); + assert_eq!(report.read_back_rows, 0); + assert_eq!(report.files_written, 0); + assert_eq!(report.row_groups_written, 0); + assert_eq!(report.bytes_written, 0); + assert_eq!(report.checksum, 0); + assert_eq!(report.stage_elapsed_ms, 0.0); + assert_eq!(report.stage_rows_per_sec, 0.0); + assert_eq!(report.stage_ns_per_row, 0.0); + assert_eq!(report.parquet_elapsed_ms, 0.0); + assert_eq!(report.parquet_rows_per_sec, 0.0); + assert_eq!(report.total_elapsed_ms, 0.0); + assert_eq!(report.total_rows_per_sec, 0.0); + assert_eq!(report.stats, crate::curate_fx::CurateFx1dStats::default()); + } } diff --git a/tools/curate-etl/src/cli.rs b/tools/curate-etl/src/cli.rs index 36937be0..90337be8 100644 --- a/tools/curate-etl/src/cli.rs +++ b/tools/curate-etl/src/cli.rs @@ -6,11 +6,12 @@ use crate::bench::{ DEFAULT_ADJ_BENCH_EVENTS, DEFAULT_BARS_BENCH_ROWS, DEFAULT_BENCH_ROWS, DEFAULT_BSON_EOD_PRICES_BENCH_ROWS, DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS, - DEFAULT_CURATE_BARS_BENCH_ROWS, DEFAULT_CURATE_SHORTS_BENCH_ROWS, DEFAULT_EVENTS_BENCH_ROWS, - DEFAULT_FX_BENCH_ROWS, DEFAULT_PARQUET_ADJ_BENCH_ROWS, DEFAULT_PARQUET_BARS_BENCH_ROWS, - DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS, DEFAULT_PARQUET_EVENTS_BENCH_ROWS, - DEFAULT_PARQUET_FX_BENCH_ROWS, DEFAULT_PARQUET_SHORTS_BENCH_ROWS, - DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS, DEFAULT_SHORTS_BENCH_ROWS, + DEFAULT_CURATE_BARS_BENCH_ROWS, DEFAULT_CURATE_FX_BENCH_ROWS, DEFAULT_CURATE_SHORTS_BENCH_ROWS, + DEFAULT_EVENTS_BENCH_ROWS, DEFAULT_FX_BENCH_ROWS, DEFAULT_PARQUET_ADJ_BENCH_ROWS, + DEFAULT_PARQUET_BARS_BENCH_ROWS, DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS, + DEFAULT_PARQUET_EVENTS_BENCH_ROWS, DEFAULT_PARQUET_FX_BENCH_ROWS, + DEFAULT_PARQUET_SHORTS_BENCH_ROWS, DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS, + DEFAULT_SHORTS_BENCH_ROWS, }; /// Parsed CLI command to execute. @@ -35,6 +36,7 @@ pub enum CliAction { BenchBsonEodPrices(usize), BenchCurateBars(usize), BenchCurateShorts(usize), + BenchCurateFx(usize), } /// Formats full help text including binary name and version. @@ -61,7 +63,8 @@ pub fn format_usage(name: &str, version: &str) -> String { {name} bench-parquet-corporate-actions [rows] Run fixed-seed corporate_actions Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS})\n\ {name} bench-bson-eod-prices [rows] Run fixed-seed eodPrices raw BSON zero-copy decode benchmark (default: {DEFAULT_BSON_EOD_PRICES_BENCH_ROWS})\n\ {name} bench-curate-bars [rows] Run fixed-seed bars_1d curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_BARS_BENCH_ROWS})\n\ - {name} bench-curate-shorts [rows] Run fixed-seed shorts curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_SHORTS_BENCH_ROWS})" + {name} bench-curate-shorts [rows] Run fixed-seed shorts curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_SHORTS_BENCH_ROWS})\n\ + {name} bench-curate-fx [rows] Run fixed-seed fx_1d curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_FX_BENCH_ROWS})" ) } @@ -87,7 +90,8 @@ pub fn format_usage_stderr(name: &str) -> String { {name} bench-parquet-corporate-actions [rows]\n\ {name} bench-bson-eod-prices [rows]\n\ {name} bench-curate-bars [rows]\n\ - {name} bench-curate-shorts [rows]" + {name} bench-curate-shorts [rows]\n\ + {name} bench-curate-fx [rows]" ) } @@ -274,6 +278,14 @@ pub fn parse_args(args: &[String]) -> Result { ["bench-curate-shorts", _, ..] => { Err("too many arguments for bench-curate-shorts".to_string()) } + ["bench-curate-fx"] => Ok(CliAction::BenchCurateFx(DEFAULT_CURATE_FX_BENCH_ROWS)), + ["bench-curate-fx", raw] => match raw.parse::() { + Ok(n) if n > 0 => Ok(CliAction::BenchCurateFx(n)), + _ => Err(format!( + "invalid row count '{raw}' (expected a positive integer)" + )), + }, + ["bench-curate-fx", _, ..] => Err("too many arguments for bench-curate-fx".to_string()), [other, ..] => Err(format!("unknown argument '{other}'")), } } @@ -581,6 +593,7 @@ mod tests { assert!(full.contains("bench-bson-eod-prices")); assert!(full.contains("bench-curate-bars")); assert!(full.contains("bench-curate-shorts")); + assert!(full.contains("bench-curate-fx")); let short = format_usage_stderr("curate-etl"); assert!(short.contains("bench-split")); @@ -600,6 +613,7 @@ mod tests { assert!(short.contains("bench-bson-eod-prices")); assert!(short.contains("bench-curate-bars")); assert!(short.contains("bench-curate-shorts")); + assert!(short.contains("bench-curate-fx")); } #[test] @@ -635,4 +649,20 @@ mod tests { assert!(parse_args(&to_args(&["bench-curate-shorts", "abc"])).is_err()); assert!(parse_args(&to_args(&["bench-curate-shorts", "10", "20"])).is_err()); } + + #[test] + fn parses_and_validates_bench_curate_fx_args() { + assert_eq!( + parse_args(&to_args(&["bench-curate-fx"])), + Ok(CliAction::BenchCurateFx(DEFAULT_CURATE_FX_BENCH_ROWS)) + ); + assert_eq!( + parse_args(&to_args(&["bench-curate-fx", "100000"])), + Ok(CliAction::BenchCurateFx(100_000)) + ); + assert!(parse_args(&to_args(&["bench-curate-fx", "0"])).is_err()); + assert!(parse_args(&to_args(&["bench-curate-fx", "-5"])).is_err()); + assert!(parse_args(&to_args(&["bench-curate-fx", "abc"])).is_err()); + assert!(parse_args(&to_args(&["bench-curate-fx", "10", "20"])).is_err()); + } } diff --git a/tools/curate-etl/src/curate_fx.rs b/tools/curate-etl/src/curate_fx.rs new file mode 100644 index 00000000..eb51852a --- /dev/null +++ b/tools/curate-etl/src/curate_fx.rs @@ -0,0 +1,195 @@ +//! Pure, in-memory `fx_1d` curation stage joining [`crate::fx::build_fx_1d`] and +//! [`crate::parquet_fx::write_fx_1d_dataset`] into contract [`Fx1dParquetRow`]s. +//! +//! # Contract & Point-in-Time Rules +//! - Calls [`build_fx_1d`] unchanged: EODHD `CAD.FOREX` takes precedence on overlapping dates, +//! TradingEconomics `teMarketData.USDCAD` fills interior gaps and the post-EOD tail, the +//! read-only 1% overlap cross-check runs untouched, and all [`Fx1dStats`] counters are carried +//! through unchanged. +//! - Maps every [`crate::fx::Fx1dRow`] to [`Fx1dParquetRow`] via [`Fx1dParquetRow::from_fx_row`] +//! with zero per-row heap allocation (`pair` and `source` stay `Cow::Borrowed`), preserving the +//! strictly ascending, unique `session_date` order emitted by [`build_fx_1d`]. +//! - **Conservative no-look-ahead timestamp rule:** stamps every row with +//! `ts_micros = known_at_micros = (session_date + 1) * FX_1D_MICROS_PER_DAY - 1` +//! (i.e. `23:59:59.999999 UTC` of `session_date`, offset +//! [`FX_1D_TS_OFFSET_MICROS_FROM_DAY_START`] from UTC midnight). Neither `CAD.FOREX` nor +//! `teMarketData.USDCAD` documents its daily FX cutoff, so the last microsecond of the UTC day +//! is the conservative no-look-ahead boundary: +//! - Same-day `16:00 ET` equity close signals resolve to the prior UTC day's FX bar rather than +//! peeking at an undocumented same-day cutoff. +//! - Every timestamp lies strictly inside the UTC day `[day_start, day_end)` and has +//! `known_at >= ts`, satisfying `parquet_fx`'s `TsOutsideSessionDate` and `KnownAtBeforeTs` +//! invariants. +//! - Requires no DST table for `1971–1975` (which lies outside `session_close.rs`'s +//! `1976–2030` range). +//! - Uses checked `i64` arithmetic via [`fx_1d_utc_day_end_micros`]; any `session_date` whose +//! UTC day-end microsecond timestamp overflows `i64` returns +//! [`CurateFxError::SessionDateOutOfRange`] without panicking or wrapping. +//! - Accounting invariant on [`CurateFx1dStats`]: `rows_in == builder.rows_out == rows_out`. + +use std::error::Error; +use std::fmt; +use std::path::Path; + +use crate::fx::{build_fx_1d, Fx1dStats, FxDailyBar}; +use crate::parquet_fx::{ + write_fx_1d_dataset, Fx1dParquetRow, Fx1dWriteOptions, Fx1dWriteStats, ParquetFxError, +}; + +/// Number of microseconds in one UTC calendar day (`86_400 * 1_000_000`). +pub const FX_1D_MICROS_PER_DAY: i64 = 86_400_000_000; + +/// Offset in microseconds from `00:00:00.000000 UTC` to `23:59:59.999999 UTC` +/// (`FX_1D_MICROS_PER_DAY - 1`), used as both `ts` and `known_at` for curated `fx_1d` rows. +pub const FX_1D_TS_OFFSET_MICROS_FROM_DAY_START: i64 = FX_1D_MICROS_PER_DAY - 1; + +/// Accounting summary produced alongside [`CurateFx1dOutput::rows`]. +/// +/// Conservation invariant: +/// - `rows_in == builder.rows_out == rows_out` +/// - `builder` independently satisfies all [`Fx1dStats`] conservation invariants. +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub struct CurateFx1dStats { + pub builder: Fx1dStats, + pub rows_in: usize, + pub rows_out: usize, +} + +/// Output of [`curate_fx_1d`]: contract Parquet rows sorted and unique by `session_date` +/// and full stage + builder stats. +#[derive(Debug, Clone, PartialEq)] +pub struct CurateFx1dOutput { + pub rows: Vec, + pub stats: CurateFx1dStats, +} + +/// Typed errors returned by [`curate_fx_1d`] and [`fx_1d_utc_day_end_micros`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CurateFxError { + /// `session_date` cannot be represented as a UTC day-end `i64` microsecond timestamp + /// (`(session_date + 1) * 86_400_000_000 - 1` overflows `i64`). + SessionDateOutOfRange { session_date: i32 }, +} + +impl fmt::Display for CurateFxError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + Self::SessionDateOutOfRange { session_date } => write!( + f, + "fx_1d session_date {session_date} overflows i64 UTC microsecond timestamp" + ), + } + } +} + +impl Error for CurateFxError {} + +/// Combined stats returned by [`curate_and_write_fx_1d`]. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct CurateFx1dWriteReport { + pub curate_stats: CurateFx1dStats, + pub write_stats: Fx1dWriteStats, +} + +/// Typed error returned by [`curate_and_write_fx_1d`]. +#[derive(Debug)] +pub enum CurateFxWriteError { + Curate(CurateFxError), + Parquet(ParquetFxError), +} + +impl fmt::Display for CurateFxWriteError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Curate(err) => write!(f, "fx_1d curation failed: {err}"), + Self::Parquet(err) => write!(f, "fx_1d Parquet write failed: {err}"), + } + } +} + +impl Error for CurateFxWriteError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::Curate(err) => Some(err), + Self::Parquet(err) => Some(err), + } + } +} + +impl From for CurateFxWriteError { + fn from(err: CurateFxError) -> Self { + Self::Curate(err) + } +} + +impl From for CurateFxWriteError { + fn from(err: ParquetFxError) -> Self { + Self::Parquet(err) + } +} + +/// Computes `23:59:59.999999 UTC` of `session_date` (days since `1970-01-01`) in UTC microseconds +/// using checked `i64` arithmetic. +/// +/// Formula: `(session_date + 1) * FX_1D_MICROS_PER_DAY - (FX_1D_MICROS_PER_DAY - FX_1D_TS_OFFSET_MICROS_FROM_DAY_START)`. +#[inline] +pub fn fx_1d_utc_day_end_micros(session_date: i32) -> Result { + let sub_from_next_day = FX_1D_MICROS_PER_DAY - FX_1D_TS_OFFSET_MICROS_FROM_DAY_START; + i64::from(session_date) + .checked_add(1) + .and_then(|next_day| next_day.checked_mul(FX_1D_MICROS_PER_DAY)) + .and_then(|next_day_start| next_day_start.checked_sub(sub_from_next_day)) + .ok_or(CurateFxError::SessionDateOutOfRange { session_date }) +} + +/// Pure `fx_1d` curation stage: merges `CAD.FOREX` (`eod`) and `teMarketData.USDCAD` (`te`) via +/// [`build_fx_1d`] and stamps each row with conservative `23:59:59.999999 UTC` `ts`/`known_at` +/// timestamps via [`fx_1d_utc_day_end_micros`] into contract [`Fx1dParquetRow`]s. +/// +/// Output rows preserve the strictly ascending, unique `session_date` order emitted by +/// [`build_fx_1d`], with `pair` and `source` kept as `Cow::Borrowed` (zero per-row heap +/// allocation). +pub fn curate_fx_1d( + eod: &[FxDailyBar], + te: &[FxDailyBar], +) -> Result { + let built = build_fx_1d(eod, te); + let rows_in = built.rows.len(); + let mut rows = Vec::with_capacity(rows_in); + + for row in &built.rows { + let ts_micros = fx_1d_utc_day_end_micros(row.session_date)?; + rows.push(Fx1dParquetRow::from_fx_row(row, ts_micros, ts_micros)); + } + + let stats = CurateFx1dStats { + builder: built.stats, + rows_in, + rows_out: rows.len(), + }; + + Ok(CurateFx1dOutput { rows, stats }) +} + +/// Thin end-to-end wrapper running [`curate_fx_1d`] and publishing the resulting contract rows +/// via [`write_fx_1d_dataset`] to `/fx_1d/part.parquet`. +/// +/// Any [`CurateFxError`] returns before [`write_fx_1d_dataset`] is invoked, leaving `out_dir` +/// untouched. +pub fn curate_and_write_fx_1d>( + out_dir: P, + eod: &[FxDailyBar], + te: &[FxDailyBar], + options: Fx1dWriteOptions, +) -> Result { + let curated = curate_fx_1d(eod, te)?; + let write_stats = write_fx_1d_dataset(out_dir, &curated.rows, options)?; + Ok(CurateFx1dWriteReport { + curate_stats: curated.stats, + write_stats, + }) +} + +#[cfg(test)] +#[path = "curate_fx_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/curate_fx_tests.rs b/tools/curate-etl/src/curate_fx_tests.rs new file mode 100644 index 00000000..717257c7 --- /dev/null +++ b/tools/curate-etl/src/curate_fx_tests.rs @@ -0,0 +1,572 @@ +use std::borrow::Cow; +use std::error::Error; +use std::fs::{self, File}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; + +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +use super::*; +use crate::fx::{build_fx_1d, FxSource, FX_PAIR_USDCAD}; +use crate::parquet_fx::fx_1d_parquet_schema; +use crate::split::ymd_to_epoch_days; + +static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDirGuard { + path: PathBuf, +} + +impl TempDirGuard { + fn new(label: &str) -> Self { + let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); + let pid = std::process::id(); + let path = std::env::temp_dir().join(format!("curate-etl-curate-fx-{label}-{pid}-{seq}")); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create test temp dir"); + Self { path } + } + + fn path(&self) -> &Path { + &self.path + } +} + +impl Drop for TempDirGuard { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid date") +} + +fn bar(session_date: i32, open: f64, high: f64, low: f64, close: f64) -> FxDailyBar { + FxDailyBar { + session_date, + open, + high, + low, + close, + } +} + +fn flat(session_date: i32, rate: f64) -> FxDailyBar { + bar(session_date, rate, rate, rate, rate) +} + +fn assert_utc_day_end_invariants(row: &Fx1dParquetRow) { + let expected_ts = + (i128::from(row.session_date) + 1) * i128::from(FX_1D_MICROS_PER_DAY) - 1; + let day_start = i128::from(row.session_date) * i128::from(FX_1D_MICROS_PER_DAY); + let day_end = day_start + i128::from(FX_1D_MICROS_PER_DAY); + let ts = i128::from(row.ts_micros); + + assert_eq!(ts, expected_ts, "ts must equal UTC day-end microsecond"); + assert_eq!(row.known_at_micros, row.ts_micros, "known_at must equal ts"); + assert!( + ts >= day_start && ts < day_end, + "ts {ts} must lie inside UTC day [{day_start}, {day_end}) for session_date {}", + row.session_date + ); +} + +fn assert_stage_invariants(out: &CurateFx1dOutput) { + let s = &out.stats; + assert_eq!(s.rows_in, s.builder.rows_out); + assert_eq!(s.rows_out, s.rows_in); + assert_eq!(s.rows_out, out.rows.len()); + + for row in &out.rows { + assert_eq!(row.pair.as_ref(), FX_PAIR_USDCAD); + assert!(matches!(row.pair, Cow::Borrowed(_)), "pair must stay borrowed"); + assert!( + matches!(row.source, Cow::Borrowed(_)), + "source must stay borrowed" + ); + assert!( + row.source.as_ref() == FxSource::EodCadForex.as_str() + || row.source.as_ref() == FxSource::TeUsdCad.as_str() + ); + assert_utc_day_end_invariants(row); + } + + for pair in out.rows.windows(2) { + assert!( + pair[0].session_date < pair[1].session_date, + "rows must be strictly ascending and unique by session_date: {} >= {}", + pair[0].session_date, + pair[1].session_date + ); + } +} + +fn assert_row_bitwise_eq(actual: &Fx1dParquetRow, expected: &Fx1dParquetRow) { + assert_eq!(actual.pair.as_ref(), expected.pair.as_ref()); + assert_eq!(actual.session_date, expected.session_date); + assert_eq!(actual.ts_micros, expected.ts_micros); + assert_eq!(actual.open.to_bits(), expected.open.to_bits()); + assert_eq!(actual.high.to_bits(), expected.high.to_bits()); + assert_eq!(actual.low.to_bits(), expected.low.to_bits()); + assert_eq!(actual.close.to_bits(), expected.close.to_bits()); + assert_eq!(actual.source.as_ref(), expected.source.as_ref()); + assert_eq!(actual.known_at_micros, expected.known_at_micros); +} + +fn read_parquet_fx(path: &Path) -> (usize, Vec) { + let file = File::open(path).expect("open parquet file"); + let reader = SerializedFileReader::new(file).expect("open parquet reader"); + let metadata = reader.metadata(); + let expected_schema = fx_1d_parquet_schema().expect("contract schema"); + assert_eq!( + metadata.file_metadata().schema_descr().root_schema_ptr(), + expected_schema, + "written Parquet schema must equal fx_1d_parquet_schema()" + ); + assert_eq!(metadata.file_metadata().schema_descr().num_columns(), 9); + + let footer_rows = metadata.file_metadata().num_rows() as usize; + let mut out = Vec::with_capacity(footer_rows); + + for rg_idx in 0..metadata.num_row_groups() { + let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); + let num_rows = metadata.row_group(rg_idx).num_rows() as usize; + + let pair = read_str_col(rg_reader.get_column_reader(0).unwrap(), num_rows); + let session_date = read_i32_col(rg_reader.get_column_reader(1).unwrap(), num_rows); + let ts_micros = read_i64_col(rg_reader.get_column_reader(2).unwrap(), num_rows); + let open = read_f64_col(rg_reader.get_column_reader(3).unwrap(), num_rows); + let high = read_f64_col(rg_reader.get_column_reader(4).unwrap(), num_rows); + let low = read_f64_col(rg_reader.get_column_reader(5).unwrap(), num_rows); + let close = read_f64_col(rg_reader.get_column_reader(6).unwrap(), num_rows); + let source = read_str_col(rg_reader.get_column_reader(7).unwrap(), num_rows); + let known_at_micros = read_i64_col(rg_reader.get_column_reader(8).unwrap(), num_rows); + + for i in 0..num_rows { + out.push(Fx1dParquetRow { + pair: Cow::Owned(pair[i].clone()), + session_date: session_date[i], + ts_micros: ts_micros[i], + open: open[i], + high: high[i], + low: low[i], + close: close[i], + source: Cow::Owned(source[i].clone()), + known_at_micros: known_at_micros[i], + }); + } + } + + (footer_rows, out) +} + +fn read_i32_col(reader: ColumnReader, expected: usize) -> Vec { + let mut values = Vec::with_capacity(expected); + match reader { + ColumnReader::Int32ColumnReader(mut r) => { + let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap(); + assert_eq!(records, expected); + } + _ => panic!("expected Int32ColumnReader"), + } + values +} + +fn read_i64_col(reader: ColumnReader, expected: usize) -> Vec { + let mut values = Vec::with_capacity(expected); + match reader { + ColumnReader::Int64ColumnReader(mut r) => { + let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap(); + assert_eq!(records, expected); + } + _ => panic!("expected Int64ColumnReader"), + } + values +} + +fn read_f64_col(reader: ColumnReader, expected: usize) -> Vec { + let mut values = Vec::with_capacity(expected); + match reader { + ColumnReader::DoubleColumnReader(mut r) => { + let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap(); + assert_eq!(records, expected); + } + _ => panic!("expected DoubleColumnReader"), + } + values +} + +fn read_str_col(reader: ColumnReader, expected: usize) -> Vec { + let mut values = Vec::with_capacity(expected); + match reader { + ColumnReader::ByteArrayColumnReader(mut r) => { + let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap(); + assert_eq!(records, expected); + } + _ => panic!("expected ByteArrayColumnReader"), + } + values + .into_iter() + .map(|ba| String::from_utf8(ba.data().to_vec()).expect("valid utf8")) + .collect() +} + +#[test] +fn happy_path_eod_only_te_only_and_merged_overlap_gap_and_tail() { + let d1 = day(2025, 1, 2); + let d2 = day(2025, 1, 3); + let d3 = day(2025, 1, 6); + let d4 = day(2026, 4, 30); + + let eod = [ + bar(d1, 1.4301, 1.4402, 1.4253, 1.4354), + // d2 missing in EOD (interior gap) + bar(d3, 1.4365, 1.4436, 1.4307, 1.4388), + ]; + let te = [ + bar(d1, 1.4311, 1.4412, 1.4263, 1.4364), // overlaps d1 -> EOD wins + bar(d2, 1.4341, 1.4392, 1.4313, 1.4374), // fills interior gap + bar(d4, 1.3801, 1.3902, 1.3753, 1.3854), // fills post-EOD tail + ]; + + // EOD-only + let eod_only = curate_fx_1d(&eod, &[]).unwrap(); + assert_stage_invariants(&eod_only); + assert_eq!(eod_only.rows.len(), 2); + assert!(eod_only.rows.iter().all(|r| r.source.as_ref() == "eod_cad_forex")); + + // TE-only + let te_only = curate_fx_1d(&[], &te).unwrap(); + assert_stage_invariants(&te_only); + assert_eq!(te_only.rows.len(), 3); + assert!(te_only.rows.iter().all(|r| r.source.as_ref() == "te_usdcad")); + + // Merged: EOD wins overlap, TE fills interior gap + tail + let merged = curate_fx_1d(&eod, &te).unwrap(); + assert_stage_invariants(&merged); + assert_eq!(merged.rows.len(), 4); + assert_eq!(merged.stats.builder.eod_rows_out, 2); + assert_eq!(merged.stats.builder.te_rows_out, 2); + assert_eq!(merged.stats.builder.te_superseded_by_eod, 1); + + // d1: EOD wins with bit-exact OHLC + assert_eq!(merged.rows[0].session_date, d1); + assert_eq!(merged.rows[0].source.as_ref(), "eod_cad_forex"); + assert_eq!(merged.rows[0].open.to_bits(), eod[0].open.to_bits()); + assert_eq!(merged.rows[0].high.to_bits(), eod[0].high.to_bits()); + assert_eq!(merged.rows[0].low.to_bits(), eod[0].low.to_bits()); + assert_eq!(merged.rows[0].close.to_bits(), eod[0].close.to_bits()); + + // d2: TE interior gap fill + assert_eq!(merged.rows[1].session_date, d2); + assert_eq!(merged.rows[1].source.as_ref(), "te_usdcad"); + assert_eq!(merged.rows[1].open.to_bits(), te[1].open.to_bits()); + assert_eq!(merged.rows[1].high.to_bits(), te[1].high.to_bits()); + assert_eq!(merged.rows[1].low.to_bits(), te[1].low.to_bits()); + assert_eq!(merged.rows[1].close.to_bits(), te[1].close.to_bits()); + + // d3: EOD only + assert_eq!(merged.rows[2].session_date, d3); + assert_eq!(merged.rows[2].source.as_ref(), "eod_cad_forex"); + assert_eq!(merged.rows[2].close.to_bits(), eod[1].close.to_bits()); + + // d4: TE tail fill + assert_eq!(merged.rows[3].session_date, d4); + assert_eq!(merged.rows[3].source.as_ref(), "te_usdcad"); + assert_eq!(merged.rows[3].close.to_bits(), te[2].close.to_bits()); +} + +#[test] +fn timestamps_match_exact_utc_day_end_for_epoch_1971_pre1970_and_2026() { + let d_1969_01_01 = day(1969, 1, 1); + let d_1969_12_31 = day(1969, 12, 31); + let d_1970_01_01 = day(1970, 1, 1); + let d_1971_01_04 = day(1971, 1, 4); + let d_2026_04_30 = day(2026, 4, 30); + + assert_eq!(d_1969_01_01, -365); + assert_eq!(d_1969_12_31, -1); + assert_eq!(d_1970_01_01, 0); + assert_eq!(d_1971_01_04, 368); + assert_eq!(d_2026_04_30, 20_573); + + let expected = [ + (d_1969_01_01, -31_449_600_000_001_i64), + (d_1969_12_31, -1_i64), + (d_1970_01_01, 86_399_999_999_i64), + (d_1971_01_04, 31_881_599_999_999_i64), + (d_2026_04_30, 1_777_593_599_999_999_i64), + ]; + + let eod: Vec = expected.iter().map(|&(d, _)| flat(d, 1.35)).collect(); + let curated = curate_fx_1d(&eod, &[]).unwrap(); + assert_stage_invariants(&curated); + assert_eq!(curated.rows.len(), expected.len()); + + for (row, &(date, expected_ts)) in curated.rows.iter().zip(expected.iter()) { + assert_eq!(row.session_date, date); + assert_eq!(row.ts_micros, expected_ts); + assert_eq!(row.known_at_micros, expected_ts); + assert_eq!(fx_1d_utc_day_end_micros(date).unwrap(), expected_ts); + } +} + +#[test] +fn stats_invariant_and_builder_stats_match_direct_build_fx_1d_bit_for_bit() { + let base = day(2024, 6, 3); + let eod = [ + // Invalid OHLC + bar(base, f64::NAN, 1.37, 1.35, 1.36), + bar(base + 1, 1.36, 1.37, 0.0, 1.36), + // Inconsistent OHLC + bar(base + 2, 1.36, 1.34, 1.35, 1.36), + // Identical duplicate (collapses) + flat(base + 3, 1.365), + flat(base + 3, 1.365), + // Conflicting duplicate (drops group; TE fills) + flat(base + 4, 1.370), + flat(base + 4, 1.371), + // Clean overlap within 1% + bar(base + 5, 1.360, 1.370, 1.355, 1.362), + // Clean overlap > 1% mismatch (read-only audit) + bar(base + 6, 1.360, 1.370, 1.355, 1.360), + ]; + let te = [ + // Invalid + inconsistent in TE + bar(base, -1.0, 1.37, 1.35, 1.36), + bar(base + 1, 1.36, 1.37, 1.35, 1.38), + // Fills base + 4 where EOD had conflict + flat(base + 4, 1.3705), + // Overlap within tolerance + bar(base + 5, 1.361, 1.371, 1.356, 1.363), + // Overlap mismatched (>1%) + bar(base + 6, 1.390, 1.400, 1.385, 1.395), + // Duplicate collapsed in TE tail + flat(base + 7, 1.380), + flat(base + 7, 1.380), + // Conflicting duplicate in TE tail + flat(base + 8, 1.385), + flat(base + 8, 1.386), + ]; + + let direct = build_fx_1d(&eod, &te); + let curated = curate_fx_1d(&eod, &te).unwrap(); + assert_stage_invariants(&curated); + + assert_eq!(curated.stats.rows_in, curated.stats.builder.rows_out); + assert_eq!(curated.stats.rows_out, curated.stats.builder.rows_out); + assert_eq!(curated.stats.builder, direct.stats); + assert_eq!( + curated.stats.builder.max_overlap_rel.to_bits(), + direct.stats.max_overlap_rel.to_bits() + ); + assert!(curated.stats.builder.eod.dropped_invalid_ohlc > 0); + assert!(curated.stats.builder.eod.dropped_inconsistent_ohlc > 0); + assert!(curated.stats.builder.eod.duplicate_collapsed > 0); + assert!(curated.stats.builder.eod.duplicate_conflict_dropped > 0); + assert!(curated.stats.builder.te.dropped_invalid_ohlc > 0); + assert!(curated.stats.builder.te.dropped_inconsistent_ohlc > 0); + assert!(curated.stats.builder.te.duplicate_collapsed > 0); + assert!(curated.stats.builder.te.duplicate_conflict_dropped > 0); + assert_eq!(curated.stats.builder.overlap_within_tolerance, 1); + assert_eq!(curated.stats.builder.overlap_mismatched, 1); +} + +#[test] +fn permutation_invariance_and_temporal_prefix_stability() { + let base = day(2025, 3, 3); + let eod = vec![ + bar(base, 1.441, 1.448, 1.439, 1.445), + bar(base + 2, 1.446, 1.451, 1.442, 1.449), + bar(base + 3, 1.449, 1.455, 1.444, 1.450), + ]; + let te = vec![ + bar(base, 1.442, 1.449, 1.440, 1.446), + bar(base + 1, 1.444, 1.450, 1.441, 1.447), + bar(base + 4, 1.450, 1.458, 1.447, 1.453), + ]; + + let baseline = curate_fx_1d(&eod, &te).unwrap(); + assert_stage_invariants(&baseline); + + let mut eod_rev = eod.clone(); + let mut te_rev = te.clone(); + eod_rev.reverse(); + te_rev.reverse(); + let permuted = curate_fx_1d(&eod_rev, &te_rev).unwrap(); + assert_eq!(permuted.stats, baseline.stats); + assert_eq!(permuted.rows.len(), baseline.rows.len()); + for (a, b) in permuted.rows.iter().zip(baseline.rows.iter()) { + assert_row_bitwise_eq(a, b); + } + + // Temporal prefix stability: appending future TE tail rows leaves earlier rows bit-identical. + let mut te_extended = te; + te_extended.push(bar(base + 10, 1.420, 1.430, 1.415, 1.425)); + te_extended.push(bar(base + 11, 1.425, 1.432, 1.420, 1.428)); + let extended = curate_fx_1d(&eod, &te_extended).unwrap(); + assert_stage_invariants(&extended); + assert_eq!(extended.rows.len(), baseline.rows.len() + 2); + for (a, b) in extended.rows[..baseline.rows.len()] + .iter() + .zip(baseline.rows.iter()) + { + assert_row_bitwise_eq(a, b); + } +} + +#[test] +fn empty_inputs_return_zero_rows_and_create_no_output_dir() { + let curated = curate_fx_1d(&[], &[]).unwrap(); + assert_stage_invariants(&curated); + assert!(curated.rows.is_empty()); + assert_eq!(curated.stats, CurateFx1dStats::default()); + + let tmp = TempDirGuard::new("empty"); + let report = curate_and_write_fx_1d(tmp.path(), &[], &[], Fx1dWriteOptions::default()).unwrap(); + assert_eq!(report.curate_stats, CurateFx1dStats::default()); + assert_eq!(report.write_stats, Fx1dWriteStats::default()); + assert!( + !tmp.path().join("fx_1d").exists(), + "empty input must not create fx_1d directory" + ); +} + +#[test] +fn session_date_overflow_boundaries_return_typed_error_and_leave_disk_untouched() { + // Tight valid boundaries succeed and satisfy UTC-day containment. + for valid_date in [106_751_990_i32, -106_751_992_i32] { + let curated = curate_fx_1d(&[flat(valid_date, 1.35)], &[]).unwrap(); + assert_stage_invariants(&curated); + assert_eq!(curated.rows.len(), 1); + } + + // Extreme and tight overflow boundaries fail cleanly without panicking. + for bad_date in [i32::MAX, i32::MIN, 106_751_991_i32, -106_751_993_i32] { + let err = curate_fx_1d(&[flat(bad_date, 1.35)], &[]).unwrap_err(); + assert_eq!( + err, + CurateFxError::SessionDateOutOfRange { + session_date: bad_date + } + ); + assert!(err.source().is_none()); + assert!(err.to_string().contains(&bad_date.to_string())); + + // Fresh directory: neither fx_1d/part.parquet nor staging files created. + let fresh = TempDirGuard::new("overflow-fresh"); + let write_err = curate_and_write_fx_1d( + fresh.path(), + &[flat(bad_date, 1.35)], + &[], + Fx1dWriteOptions::default(), + ) + .unwrap_err(); + assert!(matches!( + write_err, + CurateFxWriteError::Curate(CurateFxError::SessionDateOutOfRange { session_date }) + if session_date == bad_date + )); + assert!(write_err.source().is_some()); + assert!(write_err.to_string().contains("fx_1d curation failed")); + assert!(!fresh.path().join("fx_1d").exists()); + } + + // Pre-existing fx_1d/part.parquet remains byte-identical on curate error. + let tmp = TempDirGuard::new("overflow-preserve"); + let valid = [bar(day(2025, 1, 2), 1.430, 1.440, 1.425, 1.435)]; + curate_and_write_fx_1d(tmp.path(), &valid, &[], Fx1dWriteOptions::default()).unwrap(); + let part_path = tmp.path().join("fx_1d/part.parquet"); + let original_bytes = fs::read(&part_path).expect("read original part.parquet"); + + let write_err = curate_and_write_fx_1d( + tmp.path(), + &[flat(i32::MAX, 1.35)], + &[], + Fx1dWriteOptions::default(), + ) + .unwrap_err(); + assert!(matches!( + write_err, + CurateFxWriteError::Curate(CurateFxError::SessionDateOutOfRange { + session_date: i32::MAX + }) + )); + assert_eq!(fs::read(&part_path).unwrap(), original_bytes); +} + +#[test] +fn curate_and_write_fx_1d_round_trips_schema_bits_and_atomic_rerun() { + let tmp = TempDirGuard::new("round-trip"); + let eod = [ + bar(day(1971, 1, 4), 1.0101, 1.0152, 1.0083, 1.0124), + bar(day(2025, 1, 2), 1.4301, 1.4402, 1.4253, 1.4354), + bar(day(2025, 1, 6), 1.4365, 1.4436, 1.4307, 1.4388), + ]; + let te = [ + bar(day(2025, 1, 2), 1.4311, 1.4412, 1.4263, 1.4364), + bar(day(2025, 1, 3), 1.4341, 1.4392, 1.4313, 1.4374), + bar(day(2026, 4, 30), 1.3801, 1.3902, 1.3753, 1.3854), + ]; + + let curated = curate_fx_1d(&eod, &te).unwrap(); + let report1 = + curate_and_write_fx_1d(tmp.path(), &eod, &te, Fx1dWriteOptions::default()).unwrap(); + + assert_eq!(report1.curate_stats, curated.stats); + assert_eq!(report1.write_stats.rows_written, report1.curate_stats.rows_out); + assert_eq!(report1.write_stats.files_written, 1); + assert!(report1.write_stats.bytes_written > 0); + + let fx_dir = tmp.path().join("fx_1d"); + let part_path = fx_dir.join("part.parquet"); + assert!(part_path.exists()); + + // No transient .tmp, .bak, or .write.lock files remain. + for entry in fs::read_dir(&fx_dir).expect("read fx_1d dir") { + let name = entry.unwrap().file_name().to_string_lossy().into_owned(); + assert_eq!(name, "part.parquet", "unexpected transient file '{name}'"); + } + + let (footer_rows, read_back) = read_parquet_fx(&part_path); + assert_eq!(footer_rows, curated.rows.len()); + assert_eq!(read_back.len(), curated.rows.len()); + for (actual, expected) in read_back.iter().zip(curated.rows.iter()) { + assert_row_bitwise_eq(actual, expected); + } + + // Second identical run atomically replaces and yields byte-identical output. + let bytes1 = fs::read(&part_path).expect("read first part.parquet"); + let report2 = + curate_and_write_fx_1d(tmp.path(), &eod, &te, Fx1dWriteOptions::default()).unwrap(); + assert_eq!(report2, report1); + let bytes2 = fs::read(&part_path).expect("read second part.parquet"); + assert_eq!(bytes2, bytes1, "rerun must produce byte-identical part.parquet"); + + for entry in fs::read_dir(&fx_dir).expect("read fx_1d dir after rerun") { + let name = entry.unwrap().file_name().to_string_lossy().into_owned(); + assert_eq!(name, "part.parquet", "unexpected transient file '{name}'"); + } +} + +#[test] +fn writer_error_when_out_dir_is_regular_file_surfaces_as_parquet_error_with_source() { + let tmp = TempDirGuard::new("writer-err"); + let regular_file = tmp.path().join("not_a_dir"); + fs::write(®ular_file, b"occupying path").expect("write regular file"); + + let eod = [bar(day(2025, 1, 2), 1.430, 1.440, 1.425, 1.435)]; + let err = + curate_and_write_fx_1d(®ular_file, &eod, &[], Fx1dWriteOptions::default()).unwrap_err(); + assert!( + matches!(err, CurateFxWriteError::Parquet(ParquetFxError::Io { .. })), + "expected Parquet(Io) error, got {err:?}" + ); + assert!(err.source().is_some(), "Parquet write error must expose source()"); + assert!( + err.to_string().contains("fx_1d Parquet write failed"), + "unexpected Display: {err}" + ); +} diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index c08bccfd..fbf45302 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -108,3 +108,10 @@ pub use curate_shorts::{ curate_and_write_shorts, curate_shorts, CurateShortsError, CurateShortsOutput, CurateShortsStats, CurateShortsWriteError, CurateShortsWriteReport, }; + +pub mod curate_fx; +pub use curate_fx::{ + curate_and_write_fx_1d, curate_fx_1d, fx_1d_utc_day_end_micros, CurateFx1dOutput, + CurateFx1dStats, CurateFx1dWriteReport, CurateFxError, CurateFxWriteError, + FX_1D_MICROS_PER_DAY, FX_1D_TS_OFFSET_MICROS_FROM_DAY_START, +}; diff --git a/tools/curate-etl/src/main.rs b/tools/curate-etl/src/main.rs index b9034cfa..2972bad3 100644 --- a/tools/curate-etl/src/main.rs +++ b/tools/curate-etl/src/main.rs @@ -5,11 +5,11 @@ use std::process::ExitCode; use curate_etl::bench::{ run_adj_benchmark, run_bars_benchmark, run_bson_eod_prices_benchmark, - run_corporate_actions_benchmark, run_curate_bars_benchmark, run_curate_shorts_benchmark, - run_events_benchmark, run_fx_benchmark, run_parquet_adj_benchmark, run_parquet_bars_benchmark, - run_parquet_corporate_actions_benchmark, run_parquet_events_benchmark, - run_parquet_fx_benchmark, run_parquet_shorts_benchmark, run_provider_mapping_benchmark, - run_shorts_benchmark, run_split_benchmark, + run_corporate_actions_benchmark, run_curate_bars_benchmark, run_curate_fx_benchmark, + run_curate_shorts_benchmark, run_events_benchmark, run_fx_benchmark, + run_parquet_adj_benchmark, run_parquet_bars_benchmark, run_parquet_corporate_actions_benchmark, + run_parquet_events_benchmark, run_parquet_fx_benchmark, run_parquet_shorts_benchmark, + run_provider_mapping_benchmark, run_shorts_benchmark, run_split_benchmark, }; use curate_etl::cli::{format_usage, format_usage_stderr, parse_args, CliAction}; @@ -630,6 +630,70 @@ fn main() -> ExitCode { ); ExitCode::SUCCESS } + Ok(CliAction::BenchCurateFx(rows)) => { + let report = match run_curate_fx_benchmark(rows) { + Ok(report) => report, + Err(err) => { + eprintln!("error: curate-fx benchmark failed: {err}"); + return ExitCode::FAILURE; + } + }; + let retention_pct = if report.rows > 0 { + (report.rows_out as f64 / report.rows as f64) * 100.0 + } else { + 0.0 + }; + println!("curate-etl bench-curate-fx"); + println!( + " input: rows={} eod_rows={} te_rows={}", + report.rows, report.eod_rows_in, report.te_rows_in + ); + println!( + " builder: rows_out={} eod_out={} te_out={} eod_invalid={} eod_inconsistent={} eod_dup_collapsed={} eod_dup_conflict={} te_invalid={} te_inconsistent={} te_dup_collapsed={} te_dup_conflict={}", + report.stats.builder.rows_out, + report.stats.builder.eod_rows_out, + report.stats.builder.te_rows_out, + report.stats.builder.eod.dropped_invalid_ohlc, + report.stats.builder.eod.dropped_inconsistent_ohlc, + report.stats.builder.eod.duplicate_collapsed, + report.stats.builder.eod.duplicate_conflict_dropped, + report.stats.builder.te.dropped_invalid_ohlc, + report.stats.builder.te.dropped_inconsistent_ohlc, + report.stats.builder.te.duplicate_collapsed, + report.stats.builder.te.duplicate_conflict_dropped + ); + println!( + " stage: rows_out={} ({:.2}% retained) elapsed={:.3} ms throughput={:.0} rows/s latency={:.2} ns/row checksum=0x{:016x}", + report.rows_out, + retention_pct, + report.stage_elapsed_ms, + report.stage_rows_per_sec, + report.stage_ns_per_row, + report.checksum + ); + println!( + " parquet: files={} row_groups={} bytes={} read_back_rows={} elapsed={:.3} ms throughput={:.0} rows/s", + report.files_written, + report.row_groups_written, + report.bytes_written, + report.read_back_rows, + report.parquet_elapsed_ms, + report.parquet_rows_per_sec + ); + println!( + " total: elapsed={:.3} ms throughput={:.0} rows/s", + report.total_elapsed_ms, report.total_rows_per_sec + ); + println!( + " overlap: te_superseded={} checked={} within_tol={} mismatched={} max_overlap_rel={:.6}", + report.stats.builder.te_superseded_by_eod, + report.stats.builder.overlap_checked, + report.stats.builder.overlap_within_tolerance, + report.stats.builder.overlap_mismatched, + report.stats.builder.max_overlap_rel + ); + ExitCode::SUCCESS + } Err(msg) => { eprintln!("error: {msg}"); eprintln!("{}", format_usage_stderr(NAME)); diff --git a/tools/curate-etl/tests/cli.rs b/tools/curate-etl/tests/cli.rs index 21a9d720..109e9e42 100644 --- a/tools/curate-etl/tests/cli.rs +++ b/tools/curate-etl/tests/cli.rs @@ -28,6 +28,7 @@ fn no_args_and_help_print_usage_and_succeed() { assert!(text.contains("bench-corporate-actions"), "{args:?}: {text}"); assert!(text.contains("bench-fx"), "{args:?}: {text}"); assert!(text.contains("bench-events"), "{args:?}: {text}"); + assert!(text.contains("bench-curate-fx"), "{args:?}: {text}"); } } @@ -64,6 +65,10 @@ fn invalid_invocations_exit_nonzero_with_usage_on_stderr() { &["bench-events", "0"][..], &["bench-events", "-5"][..], &["bench-events", "10", "20"][..], + &["bench-curate-fx", "abc"][..], + &["bench-curate-fx", "0"][..], + &["bench-curate-fx", "-5"][..], + &["bench-curate-fx", "10", "20"][..], &["--unknown"][..], &["export"][..], ] { @@ -199,3 +204,37 @@ fn bench_events_small_run_is_headless_deterministic_and_reports_rates() { assert_eq!(checksum_a, checksum_b); assert_eq!(field(&text_a, "rows_out="), field(&text_b, "rows_out=")); } + +#[test] +fn bench_curate_fx_small_run_is_headless_deterministic_and_reports_rates() { + let a = run(&["bench-curate-fx", "2000"]); + let b = run(&["bench-curate-fx", "2000"]); + assert!(a.status.success(), "{}", stderr(&a)); + assert!(b.status.success(), "{}", stderr(&b)); + assert!(stderr(&a).is_empty(), "unexpected stderr: {}", stderr(&a)); + assert!(stderr(&b).is_empty(), "unexpected stderr: {}", stderr(&b)); + + let text_a = stdout(&a); + let text_b = stdout(&b); + assert!(text_a.contains("curate-etl bench-curate-fx"), "{text_a}"); + assert!(text_a.contains("rows=2000 "), "{text_a}"); + assert!(text_a.contains("stage:"), "{text_a}"); + assert!(text_a.contains("parquet:"), "{text_a}"); + assert!(text_a.contains("total:"), "{text_a}"); + assert!(text_a.contains("overlap:"), "{text_a}"); + assert!(text_a.contains("rows/s"), "{text_a}"); + assert!(text_a.contains("bytes="), "{text_a}"); + assert!(text_a.contains("checksum=0x"), "{text_a}"); + + let field = |s: &str, prefix: &str| { + s.split_whitespace() + .find(|t| t.starts_with(prefix)) + .map(str::to_owned) + }; + let checksum_a = field(&text_a, "checksum="); + let checksum_b = field(&text_b, "checksum="); + assert!(checksum_a.is_some(), "{text_a}"); + assert_eq!(checksum_a, checksum_b); + assert_eq!(field(&text_a, "rows_out="), field(&text_b, "rows_out=")); + assert_eq!(field(&text_a, "bytes="), field(&text_b, "bytes=")); +} From f988094851b3bba74199155127dd6cd0aca117f7 Mon Sep 17 00:00:00 2001 From: Studio Date: Sat, 28 Nov 2026 18:55:18 -0500 Subject: [PATCH 2/3] =?UTF-8?q?T-102:=20M1.2t=20=E2=80=94=20`tools/curate-?= =?UTF-8?q?etl`:=20pure=20`fx=5F1d`=20curation=20stage=20(`CAD.FOREX`=20+?= =?UTF-8?q?=20`teMarketData.USDCAD`=20daily=20bars=20=E2=86=92=20`Fx1dParq?= =?UTF-8?q?uetRow`s=20with=20`ts`/`known=5Fat`=20=E2=86=92=20Zstd=20Parque?= =?UTF-8?q?t)=20with=20tests=20and=20local=20benchmark=20(no=20new=20crate?= =?UTF-8?q?s)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/src/curate_fx_tests.rs | 127 ++++++++++++++++++++++++ 1 file changed, 127 insertions(+) diff --git a/tools/curate-etl/src/curate_fx_tests.rs b/tools/curate-etl/src/curate_fx_tests.rs index 717257c7..f42e24f8 100644 --- a/tools/curate-etl/src/curate_fx_tests.rs +++ b/tools/curate-etl/src/curate_fx_tests.rs @@ -1,6 +1,7 @@ use std::borrow::Cow; use std::error::Error; use std::fs::{self, File}; +use std::io::Read; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; @@ -570,3 +571,129 @@ fn writer_error_when_out_dir_is_regular_file_surfaces_as_parquet_error_with_sour "unexpected Display: {err}" ); } + +#[test] +fn curate_and_write_fx_1d_atomic_replace_preserves_open_handle_on_changed_input() { + let tmp = TempDirGuard::new("atomic-replace"); + let eod_v1 = [ + bar(day(2025, 1, 2), 1.4301, 1.4402, 1.4253, 1.4354), + bar(day(2025, 1, 3), 1.4341, 1.4392, 1.4313, 1.4374), + ]; + let eod_v2 = [ + bar(day(2025, 1, 2), 1.4301, 1.4402, 1.4253, 1.4354), + bar(day(2025, 1, 3), 1.4341, 1.4392, 1.4313, 1.4374), + bar(day(2025, 1, 6), 1.4410, 1.4490, 1.4380, 1.4455), + ]; + + curate_and_write_fx_1d(tmp.path(), &eod_v1, &[], Fx1dWriteOptions::default()).unwrap(); + let fx_dir = tmp.path().join("fx_1d"); + let part_path = fx_dir.join("part.parquet"); + let original_bytes = fs::read(&part_path).expect("read v1 part.parquet"); + + // Hold an open handle to v1 while publishing changed input v2. + let mut old_handle = File::open(&part_path).expect("open handle to v1 part.parquet"); + + let expected_v2 = curate_fx_1d(&eod_v2, &[]).unwrap(); + let report_v2 = + curate_and_write_fx_1d(tmp.path(), &eod_v2, &[], Fx1dWriteOptions::default()).unwrap(); + assert_eq!(report_v2.write_stats.rows_written, expected_v2.rows.len()); + + // An atomic rename replaces the directory entry without mutating the unlinked v1 inode. + let mut old_handle_bytes = Vec::new(); + old_handle + .read_to_end(&mut old_handle_bytes) + .expect("read v1 bytes from open handle"); + assert_eq!( + old_handle_bytes, original_bytes, + "open handle to previous part.parquet must still read original bytes" + ); + + // Opening the path now resolves to the newly published v2 rows. + let (footer_rows, read_back_v2) = read_parquet_fx(&part_path); + assert_eq!(footer_rows, expected_v2.rows.len()); + assert_eq!(read_back_v2.len(), expected_v2.rows.len()); + for (actual, expected) in read_back_v2.iter().zip(expected_v2.rows.iter()) { + assert_row_bitwise_eq(actual, expected); + } + + for entry in fs::read_dir(&fx_dir).expect("read fx_1d dir after v2 publish") { + let name = entry.unwrap().file_name().to_string_lossy().into_owned(); + assert_eq!(name, "part.parquet", "unexpected transient file '{name}'"); + } +} + +#[test] +fn overflowing_session_date_mixed_with_valid_rows_fails_whole_stage_without_writing() { + let tmp = TempDirGuard::new("mixed-overflow"); + let eod = [ + bar(day(2025, 1, 2), 1.430, 1.440, 1.425, 1.435), + flat(106_751_991, 1.35), + ]; + let te = [bar(day(2025, 1, 3), 1.434, 1.439, 1.431, 1.437)]; + + let err = + curate_and_write_fx_1d(tmp.path(), &eod, &te, Fx1dWriteOptions::default()).unwrap_err(); + assert!(matches!( + err, + CurateFxWriteError::Curate(CurateFxError::SessionDateOutOfRange { + session_date: 106_751_991 + }) + )); + assert!(!tmp.path().join("fx_1d").exists()); +} + +#[test] +fn invalid_bar_with_overflowing_session_date_is_dropped_by_builder_before_timestamping() { + let eod = [ + bar(day(2025, 1, 2), 1.430, 1.440, 1.425, 1.435), + bar(i32::MAX, 1.35, 1.36, 1.34, 0.0), + ]; + let out = curate_fx_1d(&eod, &[]).expect("invalid overflowing bar should be dropped"); + assert_stage_invariants(&out); + assert_eq!(out.stats.builder.eod.dropped_invalid_ohlc, 1); + assert_eq!(out.rows.len(), 1); + assert_eq!(out.rows[0].session_date, day(2025, 1, 2)); +} + +#[test] +fn fx_1d_utc_day_end_micros_matches_i128_reference_across_seeded_sweep() { + let mut state: u64 = 0x517c_c1b7_2722_0a95; + let mut next_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) + }; + + let boundaries = [ + i32::MIN, + -106_751_994, + -106_751_993, + -106_751_992, + -1, + 0, + 1, + 106_751_990, + 106_751_991, + 106_751_992, + i32::MAX, + ]; + + let mut dates = Vec::with_capacity(boundaries.len() + 10_000); + dates.extend_from_slice(&boundaries); + for _ in 0..10_000 { + dates.push(next_u64() as i32); + } + + for session_date in dates { + let wide = (i128::from(session_date) + 1) * i128::from(FX_1D_MICROS_PER_DAY) - 1; + let expected = i64::try_from(wide) + .map_err(|_| CurateFxError::SessionDateOutOfRange { session_date }); + assert_eq!( + fx_1d_utc_day_end_micros(session_date), + expected, + "mismatch for session_date={session_date}" + ); + } +} From 48bbf01eefebf16bdcf44dee74c1ed5be8d6bfc1 Mon Sep 17 00:00:00 2001 From: Studio Date: Sat, 28 Nov 2026 19:01:36 -0500 Subject: [PATCH 3/3] T-102: tests --- .../curate-etl/tests/curate_fx_qa_contract.rs | 407 ++++++++++++++++++ 1 file changed, 407 insertions(+) create mode 100644 tools/curate-etl/tests/curate_fx_qa_contract.rs diff --git a/tools/curate-etl/tests/curate_fx_qa_contract.rs b/tools/curate-etl/tests/curate_fx_qa_contract.rs new file mode 100644 index 00000000..52b9c56b --- /dev/null +++ b/tools/curate-etl/tests/curate_fx_qa_contract.rs @@ -0,0 +1,407 @@ +//! QA contract tests for the public `fx_1d` curation stage (T-102 / M1.2t). +//! +//! Covers gaps left by the in-crate `curate_fx_tests.rs`, checking against independent +//! references rather than the stage's own logic: +//! - seeded differential test against a naive `BTreeMap` merge (EOD wins, TE fills) on clean, +//! shuffled inputs, with `ts`/`known_at` recomputed in `i128`; +//! - point-in-time join: an as-of lookup by `known_at <= t` at a `16:00 ET` equity close on day +//! `d` (both DST regimes) resolves to day `d-1`'s bar, never day `d`'s; +//! - poison look-ahead: appending absurd future EOD/TE rows leaves every earlier row bit-identical; +//! - multi-row-group round trip and re-publish replacing a larger `part.parquet` with a smaller one; +//! - `bench-curate-fx` binary run: checksum and bytes pinned to the README values, temp dir cleaned. + +use std::borrow::Cow; +use std::collections::BTreeMap; +use std::fs::{self, File}; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::atomic::{AtomicU64, Ordering}; + +use curate_etl::{ + curate_and_write_fx_1d, curate_fx_1d, fx_1d_parquet_schema, ymd_to_epoch_days, Fx1dParquetRow, + Fx1dWriteOptions, FxDailyBar, FX_PAIR_USDCAD, +}; +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +const MICROS_PER_HOUR: i64 = 3_600_000_000; +const MICROS_PER_DAY: i64 = 86_400_000_000; + +static SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDir(PathBuf); + +impl TempDir { + fn new(tag: &str) -> Self { + let seq = SEQ.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!( + "curate-etl-curate-fx-qa-{tag}-{}-{seq}", + std::process::id() + )); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create temp dir"); + Self(path) + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +/// Deterministic SplitMix64 (fixed seed per test). +struct Rng(u64); + +impl Rng { + fn next_u64(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } + + fn below(&mut self, n: u64) -> u64 { + self.next_u64() % n + } + + fn unit(&mut self) -> f64 { + (self.next_u64() >> 11) as f64 / (1u64 << 53) as f64 + } +} + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid date") +} + +fn bar(session_date: i32, open: f64, high: f64, low: f64, close: f64) -> FxDailyBar { + FxDailyBar { + session_date, + open, + high, + low, + close, + } +} + +/// Clean OHLC bar (`low <= open, close <= high`, all positive and finite). +fn clean_bar(rng: &mut Rng, session_date: i32) -> FxDailyBar { + let mid = 0.9 + rng.unit() * 0.7; + let open = mid * (1.0 + (rng.unit() - 0.5) * 0.004); + let close = mid * (1.0 + (rng.unit() - 0.5) * 0.004); + let high = open.max(close) * (1.0 + rng.unit() * 0.003); + let low = open.min(close) * (1.0 - rng.unit() * 0.003); + bar(session_date, open, high, low, close) +} + +fn shuffle(v: &mut [T], rng: &mut Rng) { + for i in (1..v.len()).rev() { + let j = rng.below(i as u64 + 1) as usize; + v.swap(i, j); + } +} + +fn day_end_reference(session_date: i32) -> i64 { + let wide = (i128::from(session_date) + 1) * i128::from(MICROS_PER_DAY) - 1; + i64::try_from(wide).expect("test dates fit in i64 micros") +} + +fn assert_row_bits(actual: &Fx1dParquetRow, expected: &Fx1dParquetRow) { + assert_eq!(actual.pair.as_ref(), expected.pair.as_ref()); + assert_eq!(actual.session_date, expected.session_date); + assert_eq!(actual.ts_micros, expected.ts_micros); + assert_eq!(actual.open.to_bits(), expected.open.to_bits()); + assert_eq!(actual.high.to_bits(), expected.high.to_bits()); + assert_eq!(actual.low.to_bits(), expected.low.to_bits()); + assert_eq!(actual.close.to_bits(), expected.close.to_bits()); + assert_eq!(actual.source.as_ref(), expected.source.as_ref()); + assert_eq!(actual.known_at_micros, expected.known_at_micros); +} + +fn read_back(path: &Path) -> (usize, Vec) { + let reader = SerializedFileReader::new(File::open(path).expect("open")).expect("reader"); + let meta = reader.metadata(); + assert_eq!( + meta.file_metadata().schema_descr().root_schema_ptr(), + fx_1d_parquet_schema().expect("schema") + ); + let mut out = Vec::new(); + for rg in 0..meta.num_row_groups() { + let rgr = reader.get_row_group(rg).expect("row group"); + let n = meta.row_group(rg).num_rows() as usize; + let strs = |i: usize| -> Vec { + let mut v = Vec::new(); + match rgr.get_column_reader(i).unwrap() { + ColumnReader::ByteArrayColumnReader(mut r) => { + r.read_records(n, None, None, &mut v).unwrap(); + } + _ => panic!("expected byte array column {i}"), + } + v.into_iter() + .map(|b| String::from_utf8(b.data().to_vec()).unwrap()) + .collect() + }; + let i64s = |i: usize| -> Vec { + let mut v = Vec::new(); + match rgr.get_column_reader(i).unwrap() { + ColumnReader::Int64ColumnReader(mut r) => { + r.read_records(n, None, None, &mut v).unwrap(); + } + _ => panic!("expected i64 column {i}"), + } + v + }; + let f64s = |i: usize| -> Vec { + let mut v = Vec::new(); + match rgr.get_column_reader(i).unwrap() { + ColumnReader::DoubleColumnReader(mut r) => { + r.read_records(n, None, None, &mut v).unwrap(); + } + _ => panic!("expected f64 column {i}"), + } + v + }; + let mut dates = Vec::new(); + match rgr.get_column_reader(1).unwrap() { + ColumnReader::Int32ColumnReader(mut r) => { + r.read_records(n, None, None, &mut dates).unwrap(); + } + _ => panic!("expected i32 session_date"), + } + let (pair, ts, o, h, l, c, src, ka) = ( + strs(0), + i64s(2), + f64s(3), + f64s(4), + f64s(5), + f64s(6), + strs(7), + i64s(8), + ); + assert_eq!(dates.len(), n); + for i in 0..n { + out.push(Fx1dParquetRow { + pair: Cow::Owned(pair[i].clone()), + session_date: dates[i], + ts_micros: ts[i], + open: o[i], + high: h[i], + low: l[i], + close: c[i], + source: Cow::Owned(src[i].clone()), + known_at_micros: ka[i], + }); + } + } + (meta.file_metadata().num_rows() as usize, out) +} + +#[test] +fn seeded_differential_matches_naive_eod_precedence_union_merge() { + for seed in [0x1u64, 0xF00D, 0xC0FF_EE11, 0x5EED_0102_0304] { + let mut rng = Rng(seed); + let start = day(1969, 6, 2); + let span = 4_000; + let mut eod = Vec::new(); + let mut te = Vec::new(); + for d in start..start + span { + // ~70% EOD, ~45% TE, independent: gives overlap, interior gaps, head and tail. + if rng.below(100) < 70 && d < start + span - 300 { + eod.push(clean_bar(&mut rng, d)); + } + if rng.below(100) < 45 { + te.push(clean_bar(&mut rng, d)); + } + } + shuffle(&mut eod, &mut rng); + shuffle(&mut te, &mut rng); + + let mut reference: BTreeMap = BTreeMap::new(); + for b in &te { + reference.insert(b.session_date, (*b, "te_usdcad")); + } + for b in &eod { + reference.insert(b.session_date, (*b, "eod_cad_forex")); + } + + let out = curate_fx_1d(&eod, &te).expect("clean input curates"); + assert_eq!(out.rows.len(), reference.len(), "seed {seed:#x}"); + assert_eq!(out.stats.rows_in, out.stats.builder.rows_out); + assert_eq!(out.stats.rows_out, out.rows.len()); + assert_eq!( + out.stats.builder.eod_rows_out + out.stats.builder.te_rows_out, + out.rows.len() + ); + + for (row, (date, (b, src))) in out.rows.iter().zip(reference.iter()) { + let ts = day_end_reference(*date); + let expected = Fx1dParquetRow { + pair: Cow::Borrowed(FX_PAIR_USDCAD), + session_date: *date, + ts_micros: ts, + open: b.open, + high: b.high, + low: b.low, + close: b.close, + source: Cow::Borrowed(src), + known_at_micros: ts, + }; + assert_row_bits(row, &expected); + } + } +} + +#[test] +fn as_of_join_at_same_day_equity_close_never_sees_that_days_fx_bar() { + // 16:00 America/Toronto = 21:00 UTC in EST and 20:00 UTC in EDT. + let cases = [ + (day(2025, 1, 15), 21), // EST + (day(2025, 7, 15), 20), // EDT + (day(1972, 2, 15), 21), // pre-session_close.rs range, EST + (day(1969, 12, 31), 21), // negative session_date + ]; + for (d, close_hour_utc) in cases { + let eod = [ + bar(d - 1, 1.30, 1.31, 1.29, 1.305), + bar(d, 1.40, 1.41, 1.39, 1.405), + bar(d + 1, 1.50, 1.51, 1.49, 1.505), + ]; + let out = curate_fx_1d(&eod, &[]).unwrap(); + let close_ts = i64::from(d) * MICROS_PER_DAY + close_hour_utc * MICROS_PER_HOUR; + + let visible: Vec<&Fx1dParquetRow> = out + .rows + .iter() + .filter(|r| r.known_at_micros <= close_ts) + .collect(); + let latest = visible.last().expect("prior day bar is visible"); + assert_eq!(latest.session_date, d - 1, "date {d}"); + assert_eq!(latest.close.to_bits(), 1.305f64.to_bits()); + + // Day d's bar becomes visible exactly at its last UTC microsecond, not one before. + let row_d = out.rows.iter().find(|r| r.session_date == d).unwrap(); + let next_midnight = (i64::from(d) + 1) * MICROS_PER_DAY; + assert_eq!(row_d.known_at_micros, next_midnight - 1); + assert!(row_d.known_at_micros > close_ts); + } +} + +#[test] +fn poison_future_rows_leave_every_earlier_row_bit_identical() { + let mut rng = Rng(0xBAD_F00D); + let base = day(2024, 1, 1); + let eod: Vec = (0..200).map(|i| clean_bar(&mut rng, base + i)).collect(); + let te: Vec = (150..260).map(|i| clean_bar(&mut rng, base + i)).collect(); + let baseline = curate_fx_1d(&eod, &te).unwrap(); + + for cutoff in [base + 50, base + 199, base + 259] { + let mut eod_p = eod.clone(); + let mut te_p = te.clone(); + // Absurd but valid future rows after the cutoff, including overlap conflicts. + eod_p.push(bar(cutoff + 1, 99.0, 100.0, 98.0, 99.5)); + te_p.push(bar(cutoff + 1, 0.01, 0.02, 0.005, 0.015)); + te_p.push(bar(cutoff + 400, 50.0, 51.0, 49.0, 50.5)); + eod_p.reverse(); + let poisoned = curate_fx_1d(&eod_p, &te_p).unwrap(); + + let keep = baseline + .rows + .iter() + .take_while(|r| r.session_date <= cutoff) + .count(); + assert!(keep > 0); + for (a, b) in poisoned.rows[..keep].iter().zip(&baseline.rows[..keep]) { + assert_row_bits(a, b); + } + } +} + +#[test] +fn multi_row_group_round_trip_and_republish_smaller_dataset() { + let tmp = TempDir::new("multi-rg"); + let mut rng = Rng(0x0123_4567); + let base = day(1971, 1, 4); + let eod: Vec = (0..1_000).map(|i| clean_bar(&mut rng, base + i)).collect(); + let te: Vec = (900..1_037) + .map(|i| clean_bar(&mut rng, base + i)) + .collect(); + let options = Fx1dWriteOptions { + row_group_rows: 128, + ..Fx1dWriteOptions::default() + }; + + let expected = curate_fx_1d(&eod, &te).unwrap(); + let report = curate_and_write_fx_1d(&tmp.0, &eod, &te, options).unwrap(); + assert_eq!(report.write_stats.rows_written, 1_037); + assert_eq!( + report.write_stats.row_groups_written, + 1_037usize.div_ceil(128) + ); + let part = tmp.0.join("fx_1d/part.parquet"); + let (footer, rows) = read_back(&part); + assert_eq!(footer, expected.rows.len()); + assert_eq!(rows.len(), expected.rows.len()); + for (a, b) in rows.iter().zip(&expected.rows) { + assert_row_bits(a, b); + } + let large_len = fs::metadata(&part).unwrap().len(); + + // Re-publish a much smaller dataset: no stale tail rows from the larger file survive. + let small = [bar(base + 5_000, 1.2, 1.25, 1.18, 1.22)]; + let report2 = curate_and_write_fx_1d(&tmp.0, &small, &[], options).unwrap(); + assert_eq!(report2.write_stats.rows_written, 1); + assert!(fs::metadata(&part).unwrap().len() < large_len); + let (footer2, rows2) = read_back(&part); + assert_eq!(footer2, 1); + assert_eq!(rows2[0].session_date, base + 5_000); + assert_eq!(rows2[0].ts_micros, day_end_reference(base + 5_000)); + assert_eq!(rows2[0].source.as_ref(), "eod_cad_forex"); + let names: Vec = fs::read_dir(tmp.0.join("fx_1d")) + .unwrap() + .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + assert_eq!(names, vec!["part.parquet".to_string()]); +} + +fn field<'a>(text: &'a str, prefix: &str) -> Option<&'a str> { + text.split_whitespace() + .find(|t| t.starts_with(prefix)) + .map(|t| &t[prefix.len()..]) +} + +#[test] +fn bench_curate_fx_default_run_matches_readme_checksum_and_cleans_temp_dir() { + let tmp = TempDir::new("bench-tmpdir"); + let output = Command::new(env!("CARGO_BIN_EXE_curate-etl")) + .arg("bench-curate-fx") + .env("TMPDIR", &tmp.0) + .output() + .expect("run curate-etl"); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success(), + "stderr: {}", + String::from_utf8_lossy(&output.stderr) + ); + + // Values recorded in tools/curate-etl/README.md (`bench-curate-fx`, default 20,000 rows). + assert_eq!(field(&stdout, "rows="), Some("20000"), "{stdout}"); + assert_eq!( + field(&stdout, "checksum="), + Some("0x298f47e68cdf7022"), + "{stdout}" + ); + assert_eq!(field(&stdout, "bytes="), Some("714498"), "{stdout}"); + assert_eq!(field(&stdout, "read_back_rows="), Some("17180"), "{stdout}"); + assert_eq!(field(&stdout, "rows_out="), Some("17180"), "{stdout}"); + + let leftovers: Vec<_> = fs::read_dir(&tmp.0) + .unwrap() + .map(|e| e.unwrap().file_name()) + .collect(); + assert!( + leftovers.is_empty(), + "bench left temp entries: {leftovers:?}" + ); +}