From d9fcd8cf8b0b65e3d846cb99a41ceaef396129f6 Mon Sep 17 00:00:00 2001 From: Studio Date: Sat, 28 Nov 2026 17:28:28 -0500 Subject: [PATCH] =?UTF-8?q?T-99:=20M1.2q=20=E2=80=94=20`tools/curate-etl`:?= =?UTF-8?q?=20keep=20pre-2008=20daily=20bars=20=E2=80=94=20`16:00=20ET`=20?= =?UTF-8?q?session-close=20timestamps=20for=201976=E2=80=932030=20(pre-200?= =?UTF-8?q?7=20DST=20rules)=20with=20tests=20and=20benchmark=20re-run=20(n?= =?UTF-8?q?o=20new=20crates)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/README.md | 38 ++- tools/curate-etl/src/bench.rs | 81 +++-- tools/curate-etl/src/curate_bars.rs | 33 +- tools/curate-etl/src/curate_bars_tests.rs | 70 +++- tools/curate-etl/src/lib.rs | 6 + tools/curate-etl/src/main.rs | 3 +- tools/curate-etl/src/session_close.rs | 310 ++++++++++++++++++ .../tests/curate_bars_qa_contract.rs | 51 ++- 8 files changed, 512 insertions(+), 80 deletions(-) create mode 100644 tools/curate-etl/src/session_close.rs diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index 8929ac57..3a62a968 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -643,44 +643,48 @@ This crate currently depends only on `parquet` (Zstd-only, no Arrow/async) so al - `rayon` parallel sharding across symbol/date partitions - QuestDB ILP v2 writer for time-series ingestion -## `bars_1d` Curation Stage (`M1.2p`) +## `bars_1d` Curation Stage (`M1.2p` / `M1.2q`) -`curate_bars_1d` and `curate_and_write_bars_1d` (`src/curate_bars.rs`) join `build_bars_1d`, `ProviderMappingTable`, listing currency metadata, and `write_bars_1d_dataset` into contract `Bars1dParquetRow` records sorted and unique by `(listing_id, session_date)`. +`curate_bars_1d` and `curate_and_write_bars_1d` (`src/curate_bars.rs`) join `build_bars_1d`, `ProviderMappingTable`, listing currency metadata, `session_close::et_session_close_utc_micros`, and `write_bars_1d_dataset` into contract `Bars1dParquetRow` records sorted and unique by `(listing_id, session_date)`. 1. **Field rules:** - Calls `build_bars_1d` unchanged (raw OHLC passed through bit-for-bit, `volume = adj_volume / factor` via `SplitTable`, read-only `qmPrices.sharevolume` cross-check with `Bars1dStats` and `mismatch_samples` carried through untouched). - Resolves `(mapping_source, source_id, session_date) -> listing_id` via `ProviderMappingTable::cursor_for` / `ProviderMappingCursor::resolve` (one cursor per contiguous `key` run, caching the last `(listing_id, currency)` lookup per run). - - Stamps `ts_micros = known_at_micros = 16:00:00 America/New_York` (`16:00 ET`) converted to UTC microseconds via `shorts::et_to_utc_micros` (`21:00 UTC` in EST, `20:00 UTC` in EDT; `America/Toronto` and `America/New_York` share identical post-2007 DST rules). Early-close half days still use `16:00 ET` (strictly later than the real close, so never look-ahead). + - Stamps `ts_micros = known_at_micros = 16:00:00 America/New_York` (`16:00 ET`) converted to UTC microseconds via `session_close::et_session_close_utc_micros` (`21:00 UTC` in EST, `20:00 UTC` in EDT). Across `1976-01-01..=2030-12-31`, `America/New_York` and `America/Toronto` share identical DST rules across all three eras: + - `1976..=1986`: last Sunday of April → last Sunday of October. + - `1987..=2006`: first Sunday of April → last Sunday of October. + - `2007..=2030`: second Sunday of March → first Sunday of November. + Early-close half days still use `16:00 ET` (strictly later than the real close, so never look-ahead). - Sets `vwap = None` and `source = "eod_unadj"` (`BARS_1D_SOURCE_EOD`). 2. **Drop & collision policy (never panics or aborts on bad rows):** - Strict drop priority per built row: 1. `dropped_unmapped`: no `provider_mapping` range covers `(mapping_source, source_id, session_date)`. 2. `dropped_missing_currency`: `listing_id` absent from `listing_currencies` or maps to a blank string. - 3. `dropped_ts_out_of_range`: `session_date` falls outside `shorts::et_to_utc_micros`'s `2008-01-01..=2030-12-31` calendar window (pre-2008 historical `eodPrices` bars drop here rather than guessing pre-2007 DST rules). + 3. `dropped_ts_out_of_range`: `session_date` falls outside `session_close::et_session_close_utc_micros`'s `1976-01-01..=2030-12-31` window. The lower bound is deliberately `1976-01-01` because US emergency DST in `1974–1975` diverged from Toronto, so earlier dates drop here rather than guessing. - After re-sorting in place by `(listing_id, session_date)`, cross-`source_id` collisions on the same `(listing_id, session_date)` collapse to one row when OHLCV is bitwise identical (`listing_collision_collapsed += g - 1`) and drop the entire group when any OHLCV field differs (`listing_collision_dropped += g`). - Exact conservation invariant in `CurateBars1dStats`: `rows_in == builder.rows_out` and `rows_in == rows_out + dropped_unmapped + dropped_missing_currency + dropped_ts_out_of_range + listing_collision_collapsed + listing_collision_dropped`. - Typed caller errors: `CurateBarsError` (`Bars(BarsError)`, `EmptyMappingSource`) and `CurateBarsWriteError` (`Curate(CurateBarsError)`, `Parquet(ParquetBarsError)`). ### `bench-curate-bars` -Fixed-seed (`std`-only SplitMix64) benchmark over `2,000,000` source-keyed `eodPrices` bars across `2,000` `String` keys per `2,000,000`-row block (`2008..=2025` with unique per-key coprime-stride `(source_id, session_date)` pairs guarded against cursor wrap, plus explicitly injected builder duplicates, pre-2008, date-ranged ticker-reuse/unmapped, missing-currency, and cross-`source_id` collision slices, `2,000` splits per block, and ~50% `qmPrices` partners), separately timing in-memory `curate_bars_1d` and Zstd Parquet `write_bars_1d_dataset` into a temp directory with footer row-count verification and cleanup: +Fixed-seed (`std`-only SplitMix64) benchmark over `2,000,000` source-keyed `eodPrices` bars across `2,000` `String` keys per `2,000,000`-row block (`2008..=2025` with unique per-key coprime-stride `(source_id, session_date)` pairs guarded against cursor wrap, plus in-range `1990..=2007`, pre-1976 out-of-range, explicitly injected builder duplicates, date-ranged ticker-reuse/unmapped, missing-currency, and cross-`source_id` collision slices, `2,000` splits per block, and ~50% `qmPrices` partners), separately timing in-memory `curate_bars_1d` and Zstd Parquet `write_bars_1d_dataset` into a temp directory with footer row-count verification and cleanup: ```bash cargo run --release -p curate-etl --offline -- bench-curate-bars [rows] ``` -Command (`2026-11-28`, two back-to-back runs with identical checksum `0x883cab901cdb0ebb`): `cargo run --release -p curate-etl --offline -- bench-curate-bars` +Command (`2026-11-28`, two back-to-back runs with identical checksum `0x098ac03b74d9899a`): `cargo run --release -p curate-etl --offline -- bench-curate-bars` -- Input: `rows=2000000`, `qm_rows=995510`, `splits=2000`, `keys=2000` -- Builder: `rows_out=1994011`, `invalid_ohlc=0`, `inconsistent_ohlc=0`, `invalid_vol=0`, `dup_collapsed=1933`, `dup_conflict_dropped=4056` -- Output: `rows_out=1947803` (`97.39%` retained), `listings_out=2000`, `files=18`, `row_groups=18`, `bytes=52802340`, `read_back_rows=1947803` -- Curation stats: `unmapped=17929`, `missing_curr=15152`, `ts_oor=3950`, `coll_collapsed=3083`, `coll_dropped=6094`, `mismatch_samples=100` -- Note: 846M-row single-core figures below are linear projections from the measured `2,000,000`-row batch at `97.39%` retention. +- Input: `rows=2000000`, `qm_rows=995681`, `splits=2000`, `keys=2000` +- Builder: `rows_out=1994014`, `invalid_ohlc=0`, `inconsistent_ohlc=0`, `invalid_vol=0`, `dup_collapsed=1930`, `dup_conflict_dropped=4056` +- Output: `rows_out=1947916` (`97.40%` retained), `listings_out=2000`, `files=36`, `row_groups=36`, `bytes=53241768`, `read_back_rows=1947916` +- Curation stats: `unmapped=17873`, `missing_curr=15129`, `ts_oor=3946`, `pre_2008_rows=39257`, `coll_collapsed=3066`, `coll_dropped=6084`, `mismatch_samples=100` +- Note: 846M-row single-core figures below are linear projections from the measured `2,000,000`-row batch at `97.40%` retention. - Run 1: - - Stage (in-memory): `elapsed=1225.30 ms`, `throughput=1632248 rows/s`, `latency=612.65 ns/row`, single-core 846M projection `518.3 s` (`8.64 min`), `checksum=0x883cab901cdb0ebb` - - Parquet write: `elapsed=609.48 ms`, `throughput=3195857 rows/s` - - Combined (stage → Parquet): `elapsed=1834.78 ms`, `throughput=1090048 rows/s`, single-core 846M projection `776.1 s` (`12.94 min`, projected at batch=`2000000` and `97.39%` retention) + - Stage (in-memory): `elapsed=1164.89 ms`, `throughput=1716906 rows/s`, `latency=582.44 ns/row`, single-core 846M projection `492.7 s` (`8.21 min`), `checksum=0x098ac03b74d9899a` + - Parquet write: `elapsed=698.34 ms`, `throughput=2789371 rows/s` + - Combined (stage → Parquet): `elapsed=1863.22 ms`, `throughput=1073410 rows/s`, single-core 846M projection `788.1 s` (`13.14 min`, projected at batch=`2000000` and `97.40%` retention) - Run 2: - - Stage (in-memory): `elapsed=1207.46 ms`, `throughput=1656374 rows/s`, `latency=603.73 ns/row`, single-core 846M projection `510.8 s` (`8.51 min`), `checksum=0x883cab901cdb0ebb` - - Parquet write: `elapsed=602.41 ms`, `throughput=3233345 rows/s` - - Combined (stage → Parquet): `elapsed=1809.87 ms`, `throughput=1105053 rows/s`, single-core 846M projection `765.6 s` (`12.76 min`, projected at batch=`2000000` and `97.39%` retention) + - Stage (in-memory): `elapsed=1181.40 ms`, `throughput=1692903 rows/s`, `latency=590.70 ns/row`, single-core 846M projection `499.7 s` (`8.33 min`), `checksum=0x098ac03b74d9899a` + - Parquet write: `elapsed=708.69 ms`, `throughput=2748627 rows/s` + - Combined (stage → Parquet): `elapsed=1890.09 ms`, `throughput=1058151 rows/s`, single-core 846M projection `799.5 s` (`13.33 min`, projected at batch=`2000000` and `97.40%` retention) diff --git a/tools/curate-etl/src/bench.rs b/tools/curate-etl/src/bench.rs index 350cdf72..9681c77b 100644 --- a/tools/curate-etl/src/bench.rs +++ b/tools/curate-etl/src/bench.rs @@ -3672,6 +3672,7 @@ pub struct CurateBarsBenchReport { pub split_event_count: usize, pub qm_rows_in: usize, pub rows_out: usize, + pub pre_2008_rows_out: usize, pub listings_out: usize, pub mismatch_samples_out: usize, pub stage_elapsed_ms: f64, @@ -3728,6 +3729,8 @@ fn build_curate_bars_bench_fixture( ) -> Result { use std::collections::HashMap; + use crate::session_close::SESSION_CLOSE_MIN_SUPPORTED_DATE; + assert!( key_count >= CURATE_BARS_BENCH_KEY_COUNT && key_count % CURATE_BARS_BENCH_KEY_COUNT == 0, "key_count ({key_count}) must be a positive multiple of {CURATE_BARS_BENCH_KEY_COUNT}" @@ -3738,8 +3741,13 @@ fn build_curate_bars_bench_fixture( let max_date = ymd_to_epoch_days(2025, 12, 31).expect("valid end date"); let full_date_span = (max_date - min_date + 1) as u64; let date_span = date_span_limit.map_or(full_date_span, |limit| limit.clamp(1, full_date_span)); - let pre_2008_start = ymd_to_epoch_days(2006, 1, 2).expect("valid pre-2008 start"); - let pre_2008_span = (min_date - pre_2008_start) as u64; + let pre_1976_start = ymd_to_epoch_days(1970, 1, 2).expect("valid pre-1976 start"); + let pre_1976_span = (SESSION_CLOSE_MIN_SUPPORTED_DATE - pre_1976_start) as u64; + let pre_2008_in_range_start = + ymd_to_epoch_days(1990, 1, 2).expect("valid pre-2008 in-range start"); + let pre_2008_in_range_end = + ymd_to_epoch_days(2007, 12, 31).expect("valid pre-2008 in-range end"); + let pre_2008_in_range_span = (pre_2008_in_range_end - pre_2008_in_range_start + 1) as u64; let reuse_end = ymd_to_epoch_days(2016, 12, 31).expect("valid reuse end"); let reuse_resume = ymd_to_epoch_days(2018, 1, 1).expect("valid reuse resume"); @@ -3784,7 +3792,7 @@ fn build_curate_bars_bench_fixture( mapping_rows.push(ProviderMappingRow { source: "eod".to_string(), source_id: key.clone(), - valid_from: pre_2008_start, + valid_from: pre_1976_start, valid_to: None, listing_id: lid, }); @@ -3795,7 +3803,7 @@ fn build_curate_bars_bench_fixture( mapping_rows.push(ProviderMappingRow { source: "eod".to_string(), source_id: key.clone(), - valid_from: pre_2008_start, + valid_from: pre_1976_start, valid_to: Some(reuse_end), listing_id: lid1, }); @@ -3813,7 +3821,7 @@ fn build_curate_bars_bench_fixture( mapping_rows.push(ProviderMappingRow { source: "eod".to_string(), source_id: key.clone(), - valid_from: pre_2008_start, + valid_from: pre_1976_start, valid_to: None, listing_id: alias_lid, }); @@ -3822,7 +3830,7 @@ fn build_curate_bars_bench_fixture( mapping_rows.push(ProviderMappingRow { source: "eod".to_string(), source_id: key.clone(), - valid_from: pre_2008_start, + valid_from: pre_1976_start, valid_to: None, listing_id: lid, }); @@ -3849,21 +3857,26 @@ fn build_curate_bars_bench_fixture( // Per-key coprime-stride cursors with explicit usage guards guarantee unique // (source_id, session_date) pairs for ordinary bars (up to 6,574 dates per key in - // 2008..=2025, 730 in 2006..2008) so all builder duplicates and cross-source_id collisions - // are injected explicitly and a cursor can never wrap silently. + // 2008..=2025, 6,573 in 1990..=2007, and 2,190 in 1970..1976) so all builder duplicates and + // cross-source_id collisions are injected explicitly and a cursor can never wrap silently. const DATE_STRIDE: u64 = 1_571; // prime, coprime to 6,574 = 2 * 19 * 173 - const PRE_2008_STRIDE: u64 = 197; // prime, coprime to 730 = 2 * 5 * 73 + const PRE_1976_STRIDE: u64 = 397; // prime, coprime to 2,190 = 2 * 3 * 5 * 73 + const PRE_2008_IN_RANGE_STRIDE: u64 = 1_571; // prime, coprime to 6,573 = 3 * 7 * 313 let date_stride = if date_span_limit.is_none() { DATE_STRIDE } else { 1 }; let mut date_cursor: Vec = (0..key_count).map(|_| rng.next_u64() % date_span).collect(); - let mut pre_date_cursor: Vec = (0..key_count) - .map(|_| rng.next_u64() % pre_2008_span) + let mut pre_1976_cursor: Vec = (0..key_count) + .map(|_| rng.next_u64() % pre_1976_span) + .collect(); + let mut pre_2008_cursor: Vec = (0..key_count) + .map(|_| rng.next_u64() % pre_2008_in_range_span) .collect(); let mut date_used: Vec = vec![0; key_count]; - let mut pre_date_used: Vec = vec![0; key_count]; + let mut pre_1976_used: Vec = vec![0; key_count]; + let mut pre_2008_used: Vec = vec![0; key_count]; let mut last_alias_pair: Option<(usize, EodDailyBar)> = None; let mut last_ordinary_bar: Option> = None; @@ -3922,19 +3935,33 @@ fn build_curate_bars_bench_fixture( } }; let session_date = if roll == 10 || roll == 11 { - if pre_date_used[key_idx] >= pre_2008_span { + if pre_1976_used[key_idx] >= pre_1976_span { return Err(CurateBarsBenchError::FixtureDatePoolExhausted { rows, key_count, key_idx, - pool: "pre-2008", - capacity: pre_2008_span, + pool: "pre-1976", + capacity: pre_1976_span, }); } - pre_date_used[key_idx] += 1; - let offset = pre_date_cursor[key_idx]; - pre_date_cursor[key_idx] = (offset + PRE_2008_STRIDE) % pre_2008_span; - pre_2008_start + offset as i32 + pre_1976_used[key_idx] += 1; + let offset = pre_1976_cursor[key_idx]; + pre_1976_cursor[key_idx] = (offset + PRE_1976_STRIDE) % pre_1976_span; + pre_1976_start + offset as i32 + } else if (12..32).contains(&roll) { + if pre_2008_used[key_idx] >= pre_2008_in_range_span { + return Err(CurateBarsBenchError::FixtureDatePoolExhausted { + rows, + key_count, + key_idx, + pool: "1990..=2007", + capacity: pre_2008_in_range_span, + }); + } + pre_2008_used[key_idx] += 1; + let offset = pre_2008_cursor[key_idx]; + pre_2008_cursor[key_idx] = (offset + PRE_2008_IN_RANGE_STRIDE) % pre_2008_in_range_span; + pre_2008_in_range_start + offset as i32 } else { if date_used[key_idx] >= date_span { return Err(CurateBarsBenchError::FixtureDatePoolExhausted { @@ -4056,6 +4083,7 @@ fn run_curate_bars_benchmark_tracked( split_event_count: 0, qm_rows_in: 0, rows_out: 0, + pre_2008_rows_out: 0, listings_out: 0, mismatch_samples_out: 0, stage_elapsed_ms: 0.0, @@ -4150,12 +4178,20 @@ fn run_curate_bars_benchmark_tracked( 0.0 }; + let pre_2008_rows_out: usize = write_stats + .rows_by_year + .iter() + .filter(|(&year, _)| year < 2008) + .map(|(_, &count)| count) + .sum(); + let report = CurateBarsBenchReport { rows, key_count: fixture_key_count, split_event_count, qm_rows_in, rows_out: curated.stats.rows_out, + pre_2008_rows_out, listings_out: curated.stats.listings_out, mismatch_samples_out: curated.mismatch_samples.len(), stage_elapsed_ms, @@ -4181,8 +4217,8 @@ fn run_curate_bars_benchmark_tracked( /// Runs the fixed-seed `bars_1d` curation stage + Zstd Parquet write benchmark for `rows` /// source-keyed `eodPrices` bars across `2,000` `String` source keys per `2,000,000`-row block -/// (`2008..=2025` plus small pre-2008, unmapped, missing-currency, and cross-`source_id` -/// collision slices). +/// (`2008..=2025` plus in-range `1990..=2007`, pre-1976 out-of-range, unmapped, missing-currency, +/// and cross-`source_id` collision slices). pub fn run_curate_bars_benchmark(rows: usize) -> Result { let (report, _) = run_curate_bars_benchmark_tracked(rows)?; Ok(report) @@ -5044,6 +5080,8 @@ mod tests { assert!(a.stats.dropped_unmapped > 0); assert!(a.stats.dropped_missing_currency > 0); assert!(a.stats.dropped_ts_out_of_range > 0); + assert!(a.pre_2008_rows_out > 0); + assert_eq!(a.pre_2008_rows_out, b.pre_2008_rows_out); assert!(a.stats.listing_collision_collapsed > 0); assert!(a.stats.listing_collision_dropped > 0); } @@ -5054,6 +5092,7 @@ mod tests { assert!(!dir.exists(), "temp dir {} should be removed", dir.display()); assert_eq!(report.rows, 0); assert_eq!(report.rows_out, 0); + assert_eq!(report.pre_2008_rows_out, 0); assert_eq!(report.read_back_rows, 0); assert_eq!(report.listings_out, 0); assert_eq!(report.files_written, 0); diff --git a/tools/curate-etl/src/curate_bars.rs b/tools/curate-etl/src/curate_bars.rs index 511ea5db..515b3f8d 100644 --- a/tools/curate-etl/src/curate_bars.rs +++ b/tools/curate-etl/src/curate_bars.rs @@ -10,20 +10,20 @@ //! (one cursor per contiguous `key` run, since `build_bars_1d` emits rows sorted by //! `(key, session_date)`). //! - Stamps `ts_micros = known_at_micros = 16:00:00 America/New_York` (`16:00 ET`) converted to -//! UTC microseconds via [`crate::shorts::et_to_utc_micros`] (`design/PLATFORM-PLAN.md`: -//! "`known_at` = session close"). +//! UTC microseconds via [`crate::session_close::et_session_close_utc_micros`] +//! (`design/PLATFORM-PLAN.md`: "`known_at` = session close"). //! - **Early-close half days** (e.g., `13:00 ET` on Christmas Eve or the day after US //! Thanksgiving) still use `16:00 ET`, which is strictly later than the real close and //! therefore never introduces look-ahead bias. -//! - **North American post-2007 DST parity:** `shorts::et_to_utc_micros` applies the -//! `America/Toronto` post-2007 DST schedule (2nd Sunday of March `02:00` → 1st Sunday of -//! November `02:00`, EDT `UTC-4` = `20:00 UTC`, EST `UTC-5` = `21:00 UTC`), which is -//! identical to `America/New_York` for every date in its supported window. -//! - **Calendar window:** `shorts::et_to_utc_micros` covers `2008-01-01..=2030-12-31` -//! ([`crate::shorts::MIN_SUPPORTED_DATE`]..=[`crate::shorts::MAX_SUPPORTED_DATE`]). Pre-2008 -//! historical `eodPrices` bars (or post-2030 dates) are dropped into -//! [`CurateBars1dStats::dropped_ts_out_of_range`] rather than panicking or guessing pre-2007 -//! DST rules. +//! - **North American DST eras (`America/New_York` == `America/Toronto` over `1976..=2030`):** +//! `et_session_close_utc_micros` applies the three identical US/Canada DST eras (`1976..=1986` +//! last Sun Apr → last Sun Oct; `1987..=2006` first Sun Apr → last Sun Oct; `2007..=2030` +//! second Sun Mar → first Sun Nov; EDT `UTC-4` = `20:00 UTC`, EST `UTC-5` = `21:00 UTC`). +//! - **Calendar window:** covers `1976-01-01..=2030-12-31` +//! ([`crate::session_close::SESSION_CLOSE_MIN_SUPPORTED_DATE`]..=[`crate::session_close::SESSION_CLOSE_MAX_SUPPORTED_DATE`]). +//! The lower bound is `1976-01-01` because US emergency DST in `1974–1975` diverged from +//! Toronto; pre-1976 or post-2030 dates are dropped into +//! [`CurateBars1dStats::dropped_ts_out_of_range`] rather than panicking or guessing. //! - Sets `vwap = None` and `source = Cow::Borrowed(BARS_1D_SOURCE_EOD)` (`"eod_unadj"`). //! - Re-sorts mapped rows in place by `(listing_id, session_date)` and compacts cross-`source_id` //! collisions on the same `(listing_id, session_date)`: bitwise-identical OHLCV collapses to one @@ -44,7 +44,7 @@ use crate::parquet_bars::{ write_bars_1d_dataset, Bars1dParquetRow, Bars1dWriteOptions, Bars1dWriteStats, ParquetBarsError, }; use crate::provider_mapping::ProviderMappingTable; -use crate::shorts::et_to_utc_micros; +use crate::session_close::et_session_close_utc_micros; use crate::split::SplitTable; /// Canonical contract `source` provenance label for un-adjusted `eodPrices` daily bars. @@ -189,7 +189,7 @@ fn parquet_row_ohlcv_bit_eq(a: &Bars1dParquetRow, b: &Bars1dParquetRow) -> bool /// 1. No mapping range covers `(mapping_source, source_id, session_date)` → `dropped_unmapped`. /// 2. Resolved `listing_id` is absent from `listing_currencies` or maps to a blank string → /// `dropped_missing_currency`. -/// 3. `et_to_utc_micros(session_date, 16, 0, 0)` fails (date outside `2008-01-01..=2030-12-31`) → +/// 3. `et_session_close_utc_micros(session_date)` fails (date outside `1976-01-01..=2030-12-31`) → /// `dropped_ts_out_of_range`. /// /// After re-sorting in place by `(listing_id, session_date)`, cross-`source_id` collisions on the @@ -267,12 +267,7 @@ where continue; }; - let Ok(ts_micros) = et_to_utc_micros( - bar.session_date, - BARS_1D_SESSION_CLOSE_HOUR_ET, - BARS_1D_SESSION_CLOSE_MINUTE_ET, - BARS_1D_SESSION_CLOSE_SECOND_ET, - ) else { + let Ok(ts_micros) = et_session_close_utc_micros(bar.session_date) else { stats.dropped_ts_out_of_range += 1; continue; }; diff --git a/tools/curate-etl/src/curate_bars_tests.rs b/tools/curate-etl/src/curate_bars_tests.rs index 85e3c1d8..2b23f5cd 100644 --- a/tools/curate-etl/src/curate_bars_tests.rs +++ b/tools/curate-etl/src/curate_bars_tests.rs @@ -11,7 +11,8 @@ use parquet::file::reader::{FileReader, SerializedFileReader}; use super::*; use crate::bars::build_bars_1d; use crate::provider_mapping::ProviderMappingRow; -use crate::shorts::{epoch_days_to_ymd, MAX_SUPPORTED_DATE, MIN_SUPPORTED_DATE}; +use crate::session_close::{SESSION_CLOSE_MAX_SUPPORTED_DATE, SESSION_CLOSE_MIN_SUPPORTED_DATE}; +use crate::shorts::epoch_days_to_ymd; use crate::split::{ymd_to_epoch_days, SplitEvent}; static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0); @@ -395,9 +396,13 @@ fn timestamps_match_1600_et_in_winter_summer_dst_transitions_and_drop_out_of_ran let curr = currencies(&[(1, "USD")]); let splits: SplitTable = SplitTable::default(); - // 2024 DST transitions: spring-forward 2024-03-10, fall-back 2024-11-03. + // Cover pre-2008 eras (1976, 1999, 2006) plus 2024 DST transitions (spring-forward + // 2024-03-10, fall-back 2024-11-03). Keep ascending by date to match sorted output. let cases = [ // (y, m, d, expected_utc_hour) + (1976, 4, 25, 20), // Era 1 spring-forward Sunday (last Sun Apr, EDT -> 20:00 UTC) + (1999, 1, 15, 21), // Era 2 winter EST -> 21:00 UTC + (2006, 6, 15, 20), // Era 2 summer EDT -> 20:00 UTC (2024, 1, 15, 21), // Winter EST (UTC-5) -> 21:00 UTC (2024, 3, 8, 21), // Friday before spring-forward (EST) (2024, 3, 10, 20), // Spring-forward Sunday 16:00 EDT -> 20:00 UTC @@ -412,10 +417,10 @@ fn timestamps_match_1600_et_in_winter_summer_dst_transitions_and_drop_out_of_ran .iter() .map(|&(y, m, d, _)| bar("AAPL.US", day(y, m, d), 100.0, 101.0, 99.0, 100.5, 1_000.0)) .collect(); - // Add out-of-range dates just outside [MIN_SUPPORTED_DATE, MAX_SUPPORTED_DATE]. + // Add out-of-range dates just outside [SESSION_CLOSE_MIN_SUPPORTED_DATE, SESSION_CLOSE_MAX_SUPPORTED_DATE]. input_bars.push(bar( "AAPL.US", - MIN_SUPPORTED_DATE - 1, // 2007-12-31 + SESSION_CLOSE_MIN_SUPPORTED_DATE - 1, // 1975-12-31 100.0, 101.0, 99.0, @@ -424,7 +429,7 @@ fn timestamps_match_1600_et_in_winter_summer_dst_transitions_and_drop_out_of_ran )); input_bars.push(bar( "AAPL.US", - MAX_SUPPORTED_DATE + 1, // 2031-01-01 + SESSION_CLOSE_MAX_SUPPORTED_DATE + 1, // 2031-01-01 100.0, 101.0, 99.0, @@ -458,6 +463,53 @@ fn timestamps_match_1600_et_in_winter_summer_dst_transitions_and_drop_out_of_ran } } +#[test] +fn pre_2008_bars_emit_exact_1600_et_timestamps_and_1975_bar_drops_out_of_range() { + let mapping = + ProviderMappingTable::from_rows([map_row("eod", "IBM.US", i32::MIN, None, 42)]).unwrap(); + let curr = currencies(&[(42, "USD")]); + let splits: SplitTable = SplitTable::default(); + + let d_1975 = day(1975, 6, 16); + let d_1999 = day(1999, 1, 15); + let d_2006 = day(2006, 6, 15); + + let input_bars = vec![ + bar("IBM.US", d_1975, 50.0, 51.0, 49.0, 50.5, 500_000.0), + bar("IBM.US", d_1999, 90.0, 92.0, 89.0, 91.25, 1_200_000.0), + bar("IBM.US", d_2006, 78.0, 79.5, 77.5, 79.0, 2_300_000.0), + ]; + + let out = curate_bars_1d( + input_bars, + &splits, + std::iter::empty::>(), + 0.01, + &mapping, + "eod", + &curr, + ) + .unwrap(); + + assert_conservation_and_order(&out); + assert_eq!(out.stats.dropped_ts_out_of_range, 1); + assert_eq!(out.rows.len(), 2); + + // 1999-01-15 (EST -> 21:00 UTC) + let expected_1999 = utc_micros(1999, 1, 15, 21, 0, 0); + assert_eq!(out.rows[0].listing_id, 42); + assert_eq!(out.rows[0].session_date, d_1999); + assert_eq!(out.rows[0].ts_micros, expected_1999); + assert_eq!(out.rows[0].known_at_micros, expected_1999); + + // 2006-06-15 (EDT -> 20:00 UTC) + let expected_2006 = utc_micros(2006, 6, 15, 20, 0, 0); + assert_eq!(out.rows[1].listing_id, 42); + assert_eq!(out.rows[1].session_date, d_2006); + assert_eq!(out.rows[1].ts_micros, expected_2006); + assert_eq!(out.rows[1].known_at_micros, expected_2006); +} + #[test] fn date_ranged_mapping_routes_ticker_reuse_and_counts_unmapped_and_missing_currency() { // FB.US: Meta (listing 100) 2012-05-18..=2022-06-08, gap, ETF (listing 200) 2025-01-02.. @@ -493,8 +545,8 @@ fn date_ranged_mapping_routes_ticker_reuse_and_counts_unmapped_and_missing_curre bar("FB.US", d_etf_start, 25.0, 26.0, 24.5, 25.2, 600.0), // -> 200 bar("FB.US", d_etf_later, 27.0, 28.0, 26.5, 27.4, 700.0), // -> 200 bar("UNKNOWN.US", d_etf_start, 10.0, 11.0, 9.0, 10.5, 50.0), // unmapped (unknown key) - // Missing currency + pre-2008 date tests priority: missing currency wins over ts_out_of_range - bar("NOCURR.US", MIN_SUPPORTED_DATE - 5, 10.0, 11.0, 9.0, 10.5, 50.0), + // Missing currency + pre-1976 date tests priority: missing currency wins over ts_out_of_range + bar("NOCURR.US", SESSION_CLOSE_MIN_SUPPORTED_DATE - 5, 10.0, 11.0, 9.0, 10.5, 50.0), bar("NOCURR.US", d_etf_start, 10.0, 11.0, 9.0, 10.5, 50.0), bar("BLANKCURR.US", d_etf_start, 10.0, 11.0, 9.0, 10.5, 50.0), ]; @@ -595,7 +647,7 @@ fn mixed_fixture_conservation_passthrough_permutation_invariance_and_empty_input let d1 = day(2024, 2, 1); let d2 = day(2024, 2, 2); let d3 = day(2024, 2, 5); - let d_old = day(2005, 6, 1); + let d_old = day(1975, 6, 16); let splits = SplitTable::from_events([( "S1.US".to_string(), @@ -623,7 +675,7 @@ fn mixed_fixture_conservation_passthrough_permutation_invariance_and_empty_input bar("S1_DUP.US", d2, 10.0, 11.0, 9.5, 10.6, 2_000.0), // Builder invalid OHLC (dropped before curate stage) bar("S1.US", d3, -1.0, 11.0, 9.0, 10.0, 100.0), - // Pre-2008 timestamp out of range + // Pre-1976 timestamp out of range bar("S1.US", d_old, 5.0, 6.0, 4.5, 5.5, 100.0), // Missing currency bar("NOCURR.US", d3, 15.0, 16.0, 14.0, 15.5, 250.0), diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index 3ed215bb..db12225c 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -15,6 +15,7 @@ pub mod parquet_fx; mod parquet_publish; pub mod parquet_shorts; pub mod provider_mapping; +pub mod session_close; pub mod shorts; pub mod split; @@ -73,6 +74,11 @@ pub use provider_mapping::{ MappingRange, ProviderMappingCursor, ProviderMappingError, ProviderMappingRow, ProviderMappingTable, }; +pub use session_close::{ + et_session_close_utc_micros, SessionCloseError, SESSION_CLOSE_MAX_SUPPORTED_DATE, + SESSION_CLOSE_MAX_SUPPORTED_YEAR, SESSION_CLOSE_MIN_SUPPORTED_DATE, + SESSION_CLOSE_MIN_SUPPORTED_YEAR, +}; pub use shorts::{ add_canadian_business_days, build_shorts, epoch_days_to_ymd, et_to_utc_micros, is_canadian_business_day, CeoShortReport, ShortRow, ShortsBuild, ShortsError, ShortsStats, diff --git a/tools/curate-etl/src/main.rs b/tools/curate-etl/src/main.rs index 39b70b8d..7b2be7aa 100644 --- a/tools/curate-etl/src/main.rs +++ b/tools/curate-etl/src/main.rs @@ -535,10 +535,11 @@ fn main() -> ExitCode { retention_pct ); println!( - " curate: unmapped={} missing_curr={} ts_oor={} coll_collapsed={} coll_dropped={} mismatch_samples={}", + " curate: unmapped={} missing_curr={} ts_oor={} pre_2008_rows={} coll_collapsed={} coll_dropped={} mismatch_samples={}", report.stats.dropped_unmapped, report.stats.dropped_missing_currency, report.stats.dropped_ts_out_of_range, + report.pre_2008_rows_out, report.stats.listing_collision_collapsed, report.stats.listing_collision_dropped, report.mismatch_samples_out diff --git a/tools/curate-etl/src/session_close.rs b/tools/curate-etl/src/session_close.rs new file mode 100644 index 00000000..49630836 --- /dev/null +++ b/tools/curate-etl/src/session_close.rs @@ -0,0 +1,310 @@ +//! Pure `std`-only North American Eastern Time (`16:00:00 ET`) session-close timestamp converter +//! covering `1976-01-01..=2030-12-31`. +//! +//! # DST Schedule (`America/New_York` == `America/Toronto` over `1976..=2030`) +//! Across the entire `1976..=2030` window, `America/New_York` and `America/Toronto` observed +//! identical Daylight Saving Time rules across three eras: +//! - **`1976..=1986`**: last Sunday of April → last Sunday of October. +//! - **`1987..=2006`**: first Sunday of April → last Sunday of October. +//! - **`2007..=2030`**: second Sunday of March → first Sunday of November (Energy Policy Act of +//! 2005 / matching Canadian provincial adoption). +//! +//! During EDT (`UTC-4`), `16:00:00 ET` is `20:00:00 UTC`. During EST (`UTC-5`), `16:00:00 ET` is +//! `21:00:00 UTC`. Because `16:00` is strictly after the `02:00` wall-clock transition, the spring +//! transition Sunday is already EDT (`20:00 UTC`) and the fall transition Sunday is already EST +//! (`21:00 UTC`). +//! +//! # Conservative Early-Close & Lower-Bound Policy +//! - **Early-close half days** (e.g., `13:00 ET` on Christmas Eve or the day after US +//! Thanksgiving) still map to `16:00:00 ET`, which is strictly later than the actual close and +//! therefore never introduces look-ahead bias for daily bar `known_at`. +//! - **Why the lower bound is `1976-01-01`**: in `1974–1975` the US Emergency Daylight Saving Time +//! Energy Conservation Act moved US clocks onto winter DST while Ontario/Toronto stayed on +//! standard rules, so `America/New_York` and `America/Toronto` diverged. Earlier dates return +//! [`SessionCloseError::DateOutOfRange`] rather than guessing exchange-specific historical rules. + +use std::error::Error; +use std::fmt; +use std::sync::OnceLock; + +use crate::shorts::epoch_days_to_ymd; +use crate::split::ymd_to_epoch_days; + +/// First Gregorian year covered by [`et_session_close_utc_micros`] (`1976-01-01`). +pub const SESSION_CLOSE_MIN_SUPPORTED_YEAR: i32 = 1976; + +/// Last Gregorian year covered by [`et_session_close_utc_micros`] (`2030-12-31`). +pub const SESSION_CLOSE_MAX_SUPPORTED_YEAR: i32 = 2030; + +/// Epoch day for `1976-01-01` (inclusive lower bound of [`et_session_close_utc_micros`]). +pub const SESSION_CLOSE_MIN_SUPPORTED_DATE: i32 = 2_191; + +/// Epoch day for `2030-12-31` (inclusive upper bound of [`et_session_close_utc_micros`]). +pub const SESSION_CLOSE_MAX_SUPPORTED_DATE: i32 = 22_279; + +const SUPPORTED_YEAR_COUNT: usize = + (SESSION_CLOSE_MAX_SUPPORTED_YEAR - SESSION_CLOSE_MIN_SUPPORTED_YEAR + 1) as usize; + +/// Typed error returned by [`et_session_close_utc_micros`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SessionCloseError { + /// The requested epoch day fell outside `[SESSION_CLOSE_MIN_SUPPORTED_DATE, SESSION_CLOSE_MAX_SUPPORTED_DATE]`. + DateOutOfRange { + epoch_day: i32, + min_supported: i32, + max_supported: i32, + }, +} + +impl fmt::Display for SessionCloseError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + Self::DateOutOfRange { + epoch_day, + min_supported, + max_supported, + } => write!( + f, + "epoch day {epoch_day} is outside supported session-close range [{min_supported}, {max_supported}] ({SESSION_CLOSE_MIN_SUPPORTED_YEAR}-01-01..={SESSION_CLOSE_MAX_SUPPORTED_YEAR}-12-31)" + ), + } + } +} + +impl Error for SessionCloseError {} + +/// ISO-8601 weekday for an epoch day: `1 = Monday`, ..., `6 = Saturday`, `7 = Sunday`. +#[inline] +fn iso_weekday(epoch_day: i32) -> u8 { + // 1970-01-01 (epoch_day == 0) was Thursday (ISO 4). + ((i64::from(epoch_day) + 3).rem_euclid(7) + 1) as u8 +} + +/// Returns the epoch day of the `nth` Sunday (`1`-indexed) in `(year, month)`. +fn nth_sunday_of_month(year: i32, month: u32, nth: u32) -> i32 { + let first = ymd_to_epoch_days(year, month, 1).expect("valid first of month"); + let first_wd = iso_weekday(first); + let delta = (7 - i32::from(first_wd)).rem_euclid(7); + first + delta + (nth as i32 - 1) * 7 +} + +/// Returns the epoch day of the last Sunday in `(year, month)`. +fn last_sunday_of_month(year: i32, month: u32) -> i32 { + let (next_year, next_month) = if month == 12 { + (year + 1, 1) + } else { + (year, month + 1) + }; + let last = ymd_to_epoch_days(next_year, next_month, 1).expect("valid first of next month") - 1; + let last_wd = iso_weekday(last); + last - (i32::from(last_wd) % 7) +} + +fn build_dst_bounds() -> [(i32, i32); SUPPORTED_YEAR_COUNT] { + let mut table = [(0i32, 0i32); SUPPORTED_YEAR_COUNT]; + for year in SESSION_CLOSE_MIN_SUPPORTED_YEAR..=SESSION_CLOSE_MAX_SUPPORTED_YEAR { + let (dst_start, dst_end) = match year { + 1976..=1986 => ( + last_sunday_of_month(year, 4), + last_sunday_of_month(year, 10), + ), + 1987..=2006 => ( + nth_sunday_of_month(year, 4, 1), + last_sunday_of_month(year, 10), + ), + 2007..=2030 => ( + nth_sunday_of_month(year, 3, 2), + nth_sunday_of_month(year, 11, 1), + ), + _ => unreachable!("year is bounded by supported range"), + }; + table[(year - SESSION_CLOSE_MIN_SUPPORTED_YEAR) as usize] = (dst_start, dst_end); + } + table +} + +#[inline] +fn dst_bounds() -> &'static [(i32, i32); SUPPORTED_YEAR_COUNT] { + static TABLE: OnceLock<[(i32, i32); SUPPORTED_YEAR_COUNT]> = OnceLock::new(); + TABLE.get_or_init(build_dst_bounds) +} + +/// Converts `epoch_day` at `16:00:00` Eastern wall-clock (`America/New_York` / `America/Toronto`) +/// to UTC microseconds since the Unix epoch. +/// +/// Covers `1976-01-01..=2030-12-31` across all three North American DST eras (`1976–1986`, +/// `1987–2006`, `2007–2030`). Returns [`SessionCloseError::DateOutOfRange`] for any date outside +/// `[SESSION_CLOSE_MIN_SUPPORTED_DATE, SESSION_CLOSE_MAX_SUPPORTED_DATE]`. +#[inline] +pub fn et_session_close_utc_micros(epoch_day: i32) -> Result { + if !(SESSION_CLOSE_MIN_SUPPORTED_DATE..=SESSION_CLOSE_MAX_SUPPORTED_DATE).contains(&epoch_day) { + return Err(SessionCloseError::DateOutOfRange { + epoch_day, + min_supported: SESSION_CLOSE_MIN_SUPPORTED_DATE, + max_supported: SESSION_CLOSE_MAX_SUPPORTED_DATE, + }); + } + + let (year, _, _) = epoch_days_to_ymd(epoch_day); + let (dst_start, dst_end) = dst_bounds()[(year - SESSION_CLOSE_MIN_SUPPORTED_YEAR) as usize]; + let is_edt = epoch_day >= dst_start && epoch_day < dst_end; + let utc_hour_secs: i64 = if is_edt { 20 * 3_600 } else { 21 * 3_600 }; + Ok((i64::from(epoch_day) * 86_400 + utc_hour_secs) * 1_000_000) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::shorts::{et_to_utc_micros, MAX_SUPPORTED_DATE, MIN_SUPPORTED_DATE}; + + fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid date") + } + + fn expected_utc_micros(epoch_day: i32, utc_hour: i64) -> i64 { + (i64::from(epoch_day) * 86_400 + utc_hour * 3_600) * 1_000_000 + } + + #[test] + fn supported_date_constants_match_ymd_to_epoch_days() { + assert_eq!(SESSION_CLOSE_MIN_SUPPORTED_DATE, day(1976, 1, 1)); + assert_eq!(SESSION_CLOSE_MAX_SUPPORTED_DATE, day(2030, 12, 31)); + assert_eq!(SUPPORTED_YEAR_COUNT, 55); + } + + #[test] + fn known_vectors_cover_all_three_dst_eras_and_transitions() { + let cases = [ + // Era 1 (1976..=1986): last Sunday of April -> last Sunday of October + (1976, 4, 24, 21), // Saturday before spring-forward (EST) + (1976, 4, 25, 20), // Last Sunday of April (EDT) + (1976, 10, 30, 20), // Saturday before fall-back (EDT) + (1976, 10, 31, 21), // Last Sunday of October (EST) + (1980, 1, 15, 21), // Era 1 mid-winter (EST) + (1980, 7, 15, 20), // Era 1 mid-summer (EDT) + (1986, 4, 26, 21), // Saturday before spring-forward (EST) + (1986, 4, 27, 20), // Last Sunday of April (EDT) + // Era 2 (1987..=2006): first Sunday of April -> last Sunday of October + (1987, 4, 4, 21), // Saturday before spring-forward (EST) + (1987, 4, 5, 20), // First Sunday of April (EDT) + (1987, 10, 24, 20), // Saturday before fall-back (EDT) + (1987, 10, 25, 21), // Last Sunday of October (EST) + (1999, 1, 15, 21), // Era 2 mid-winter (EST) + (1999, 7, 15, 20), // Era 2 mid-summer (EDT) + (2006, 4, 1, 21), // Saturday before spring-forward (EST) + (2006, 4, 2, 20), // First Sunday of April (EDT) + (2006, 10, 28, 20), // Saturday before fall-back (EDT) + (2006, 10, 29, 21), // Last Sunday of October (EST) + // Era 3 (2007..=2030): second Sunday of March -> first Sunday of November + (2007, 3, 10, 21), // Saturday before spring-forward (EST) + (2007, 3, 11, 20), // Second Sunday of March (EDT) + (2007, 11, 3, 20), // Saturday before fall-back (EDT) + (2007, 11, 4, 21), // First Sunday of November (EST) + (2024, 1, 15, 21), // Era 3 mid-winter (EST) + (2024, 7, 15, 20), // Era 3 mid-summer (EDT) + ]; + + for (y, m, d, expected_hour) in cases { + let epoch_day = day(y, m, d); + let actual = et_session_close_utc_micros(epoch_day).expect("in-range date"); + let expected = expected_utc_micros(epoch_day, expected_hour); + assert_eq!( + actual, expected, + "micros mismatch on {y:04}-{m:02}-{d:02} (expected {expected_hour}:00 UTC)" + ); + let hour_of_day = (actual / 1_000_000 - i64::from(epoch_day) * 86_400) / 3_600; + assert_eq!( + hour_of_day, expected_hour, + "UTC hour mismatch on {y:04}-{m:02}-{d:02}" + ); + } + } + + #[test] + fn bit_exact_parity_with_shorts_et_to_utc_micros_for_2008_to_2030() { + for d in MIN_SUPPORTED_DATE..=MAX_SUPPORTED_DATE { + let expected = et_to_utc_micros(d, 16, 0, 0).expect("shorts 2008..=2030 date"); + let actual = et_session_close_utc_micros(d).expect("session_close 2008..=2030 date"); + assert_eq!( + actual, expected, + "parity mismatch against shorts::et_to_utc_micros on epoch_day={d}" + ); + } + } + + #[test] + fn full_window_sweep_has_only_20_or_21_utc_and_two_sunday_flips_per_year() { + let mut spring_flips_by_year = [0u32; SUPPORTED_YEAR_COUNT]; + let mut fall_flips_by_year = [0u32; SUPPORTED_YEAR_COUNT]; + + let mut prev_hour: Option = None; + for d in SESSION_CLOSE_MIN_SUPPORTED_DATE..=SESSION_CLOSE_MAX_SUPPORTED_DATE { + let micros = et_session_close_utc_micros(d).expect("in-range date"); + let offset_micros = micros - i64::from(d) * 86_400 * 1_000_000; + let utc_hour = match offset_micros { + 72_000_000_000 => 20, // 20 * 3600 * 1e6 + 75_600_000_000 => 21, // 21 * 3600 * 1e6 + other => panic!( + "unexpected UTC offset micros {other} on epoch_day={d} (expected 20h or 21h)" + ), + }; + + if let Some(prev) = prev_hour { + if prev != utc_hour { + assert_eq!( + iso_weekday(d), + 7, + "DST flip on epoch_day={d} must occur on a Sunday" + ); + let (year, _, _) = epoch_days_to_ymd(d); + let idx = (year - SESSION_CLOSE_MIN_SUPPORTED_YEAR) as usize; + match (prev, utc_hour) { + (21, 20) => spring_flips_by_year[idx] += 1, + (20, 21) => fall_flips_by_year[idx] += 1, + _ => unreachable!(), + } + } + } + prev_hour = Some(utc_hour); + } + + for year in SESSION_CLOSE_MIN_SUPPORTED_YEAR..=SESSION_CLOSE_MAX_SUPPORTED_YEAR { + let idx = (year - SESSION_CLOSE_MIN_SUPPORTED_YEAR) as usize; + assert_eq!( + spring_flips_by_year[idx], 1, + "year {year} must have exactly one EST->EDT flip" + ); + assert_eq!( + fall_flips_by_year[idx], 1, + "year {year} must have exactly one EDT->EST flip" + ); + } + } + + #[test] + fn out_of_range_dates_return_typed_error_without_panicking() { + let bad_days = [ + day(1975, 12, 31), + day(2031, 1, 1), + i32::MIN, + i32::MAX, + ]; + for bad_day in bad_days { + let err = et_session_close_utc_micros(bad_day).unwrap_err(); + assert_eq!( + err, + SessionCloseError::DateOutOfRange { + epoch_day: bad_day, + min_supported: SESSION_CLOSE_MIN_SUPPORTED_DATE, + max_supported: SESSION_CLOSE_MAX_SUPPORTED_DATE, + } + ); + assert!(err.source().is_none()); + let msg = err.to_string(); + assert!( + msg.contains(&bad_day.to_string()) && msg.contains("1976-01-01..=2030-12-31"), + "unexpected Display message: {msg}" + ); + } + } +} diff --git a/tools/curate-etl/tests/curate_bars_qa_contract.rs b/tools/curate-etl/tests/curate_bars_qa_contract.rs index 467457fc..4407c877 100644 --- a/tools/curate-etl/tests/curate_bars_qa_contract.rs +++ b/tools/curate-etl/tests/curate_bars_qa_contract.rs @@ -1,9 +1,9 @@ -//! QA contract tests for the public `bars_1d` curation stage (T-98 / M1.2p). +//! QA contract tests for the public `bars_1d` curation stage (T-98 / M1.2p, T-99 / M1.2q). //! //! Covers gaps left by the in-crate `curate_bars_tests.rs`, checking against independent //! references rather than the stage's own logic: -//! - session-close timestamps for every calendar day in `2008-01-01..=2030-12-31` against a -//! hand-written US/Canada DST rule (no look-ahead, never earlier than 16:00 ET); +//! - session-close timestamps for every calendar day in `1976-01-01..=2030-12-31` against a +//! hand-written 3-era US/Canada DST rule (no look-ahead, never earlier than 16:00 ET); //! - seeded randomized differential test against a naive reference (non-cursor mapping lookup, //! `BTreeMap` grouping) plus permutation invariance; //! - `mapping_source` isolation, split-on-one-alias collisions, builder-vs-stage duplicate @@ -19,7 +19,7 @@ use curate_etl::{ build_bars_1d, curate_and_write_bars_1d, curate_bars_1d, Bars1dParquetRow, Bars1dWriteOptions, CurateBars1dOutput, EodDailyBar, ProviderMappingRow, ProviderMappingTable, QmRawVolume, SplitEvent, SplitTable, BARS_1D_SOURCE_EOD, - MAX_SUPPORTED_DATE, MIN_SUPPORTED_DATE, + SESSION_CLOSE_MAX_SUPPORTED_DATE, SESSION_CLOSE_MIN_SUPPORTED_DATE, }; const MICROS_PER_HOUR: i64 = 3_600_000_000; @@ -80,11 +80,28 @@ fn nth_sunday(year: i32, month: u32, n: i32) -> i32 { first + to_sunday + 7 * (n - 1) } -/// Independent reference: 16:00 ET in UTC micros using the post-2007 US/Canada rule -/// (EDT from the 2nd Sunday of March to the day before the 1st Sunday of November, at 16:00). +fn last_sunday(year: i32, month: u32) -> i32 { + let last = if month == 12 { + day(year + 1, 1, 1) - 1 + } else { + day(year, month + 1, 1) - 1 + }; + last - weekday(last) +} + +/// Independent reference: 16:00 ET in UTC micros across all three US/Canada DST eras +/// (`1976..=1986` last Sun Apr -> last Sun Oct; `1987..=2006` 1st Sun Apr -> last Sun Oct; +/// `2007..=2030` 2nd Sun Mar -> 1st Sun Nov). fn reference_close_utc(epoch_day: i32) -> i64 { let (y, _, _) = curate_etl::epoch_days_to_ymd(epoch_day); - let edt = epoch_day >= nth_sunday(y, 3, 2) && epoch_day < nth_sunday(y, 11, 1); + let (start, end) = if y <= 1986 { + (last_sunday(y, 4), last_sunday(y, 10)) + } else if y <= 2006 { + (nth_sunday(y, 4, 1), last_sunday(y, 10)) + } else { + (nth_sunday(y, 3, 2), nth_sunday(y, 11, 1)) + }; + let edt = epoch_day >= start && epoch_day < end; let utc_hour = if edt { 20 } else { 21 }; i64::from(epoch_day) * MICROS_PER_DAY + utc_hour * MICROS_PER_HOUR } @@ -163,7 +180,7 @@ fn every_supported_day_closes_at_1600_et_per_independent_dst_rule_and_never_earl // one day on each side. let mapping = ProviderMappingTable::from_rows([map_row("eod", "SPY.US", i32::MIN, None, 1)]).unwrap(); - let bars: Vec<_> = (MIN_SUPPORTED_DATE - 1..=MAX_SUPPORTED_DATE + 1) + let bars: Vec<_> = (SESSION_CLOSE_MIN_SUPPORTED_DATE - 1..=SESSION_CLOSE_MAX_SUPPORTED_DATE + 1) .map(|d| bar("SPY.US", d, 10.0, 11.0, 9.0, 10.5, 100.0)) .collect(); let total = bars.len(); @@ -182,8 +199,14 @@ fn every_supported_day_closes_at_1600_et_per_independent_dst_rule_and_never_earl assert_conservation(&out); assert_eq!(out.stats.dropped_ts_out_of_range, 2); assert_eq!(out.rows.len(), total - 2); - assert_eq!(out.rows.first().unwrap().session_date, MIN_SUPPORTED_DATE); - assert_eq!(out.rows.last().unwrap().session_date, MAX_SUPPORTED_DATE); + assert_eq!( + out.rows.first().unwrap().session_date, + SESSION_CLOSE_MIN_SUPPORTED_DATE + ); + assert_eq!( + out.rows.last().unwrap().session_date, + SESSION_CLOSE_MAX_SUPPORTED_DATE + ); for r in &out.rows { let expected = reference_close_utc(r.session_date); @@ -221,7 +244,9 @@ fn reference_curate( no_curr += 1; continue; }; - if b.session_date < MIN_SUPPORTED_DATE || b.session_date > MAX_SUPPORTED_DATE { + if b.session_date < SESSION_CLOSE_MIN_SUPPORTED_DATE + || b.session_date > SESSION_CLOSE_MAX_SUPPORTED_DATE + { oor += 1; continue; } @@ -265,8 +290,8 @@ fn seeded_random_fixtures_match_naive_reference_and_are_permutation_invariant() for seed in 0..12u64 { let mut rng = Rng(0xC0FF_EE00 ^ seed.wrapping_mul(0x9E37_79B9)); let keys: Vec = (0..8).map(|i| format!("K{i}.US")).collect(); - let base = day(2007, 11, 1); - let span = 120u64; // straddles 2008-01-01 so some bars are out of range + let base = day(1975, 11, 1); + let span = 120u64; // straddles 1976-01-01 so some bars are out of range // Mapping: K0..K5 date-ranged (with gaps) onto listings 1..=4 so several ids alias the // same listing; K6 maps to listing 9 (no currency); K7 is unmapped. A decoy source