T-130: edits made in the worktree

This commit is contained in:
Studio 2026-11-30 23:29:51 -05:00
parent 58658ff163
commit 3c949d532b
3 changed files with 450 additions and 142 deletions

View file

@ -163,6 +163,44 @@ pub struct DailySessionClose<K = String> {
/// Session date as days since `1970-01-01` (Eastern / trading calendar date).
pub session_date: i32,
pub close: f64,
/// Optional exclusive Eastern Time session-close cutoff in UTC microseconds.
///
/// When `Some(cutoff_ts)`, only [`IntradaySession::Rth`] bars with `ts < cutoff_ts` are
/// eligible as the session's closing bar (for example, `13:00:00 ET` on an early-close half
/// day so post-close prints between `13:00` and `15:59 ET` do not displace the `12:59 ET`
/// closing bar while [`Bar1mRow::session`] retains the fixed `PRE`/`RTH`/`POST` tags).
/// When `None`, defaults to the standard `16:00:00 ET` RTH boundary.
pub session_close_ts: Option<i64>,
}
impl<K> DailySessionClose<K> {
/// Creates a daily close reference using the standard `16:00:00 ET` RTH cutoff.
#[inline]
pub const fn new(key: K, session_date: i32, close: f64) -> Self {
Self {
key,
session_date,
close,
session_close_ts: None,
}
}
/// Creates a daily close reference with an explicit exclusive UTC microsecond session-close
/// cutoff (for example, `13:00:00 ET` on a half-day early close).
#[inline]
pub const fn with_close_cutoff(
key: K,
session_date: i32,
close: f64,
session_close_ts: i64,
) -> Self {
Self {
key,
session_date,
close,
session_close_ts: Some(session_close_ts),
}
}
}
impl<K> From<Bar1dRow<K>> for DailySessionClose<K> {
@ -172,6 +210,7 @@ impl<K> From<Bar1dRow<K>> for DailySessionClose<K> {
key: row.key,
session_date: row.session_date,
close: row.close,
session_close_ts: None,
}
}
}
@ -183,6 +222,7 @@ impl<K: Clone> From<&Bar1dRow<K>> for DailySessionClose<K> {
key: row.key.clone(),
session_date: row.session_date,
close: row.close,
session_close_ts: None,
}
}
}
@ -393,7 +433,10 @@ where
stats.dropped_inconsistent_ohlc += 1;
continue;
}
if !unadj.volume.is_finite() || unadj.volume < 0.0 {
if !unadj.volume.is_finite()
|| unadj.volume < 0.0
|| (first.volume > 0.0 && unadj.volume == 0.0)
{
stats.dropped_invalid_volume += 1;
continue;
}
@ -472,9 +515,96 @@ struct LastRthBar<'a, K> {
session_date: i32,
ts: i64,
close: f64,
/// `true` when multiple eligible `Rth` bars shared the maximum `ts` with differing closes.
conflicting_last_ts: bool,
}
fn collect_last_rth_bars<K: Ord>(rows_1m: &[Bar1mRow<K>]) -> Vec<LastRthBar<'_, K>> {
fn select_last_rth_bars<'a, K, I>(
rth_sorted: I,
valid_daily: &[DailySessionClose<K>],
) -> Vec<LastRthBar<'a, K>>
where
K: Ord + 'a,
I: IntoIterator<Item = (&'a K, i32, i64, f64)>,
{
let mut result: Vec<LastRthBar<'a, K>> = Vec::new();
let mut daily_idx = 0usize;
let mut cur_group: Option<(&'a K, i32, Option<i64>)> = None;
let mut cur_best: Option<LastRthBar<'a, K>> = None;
for (key, session_date, ts, close) in rth_sorted {
let cutoff = match cur_group {
Some((gk, gd, cutoff)) if gk == key && gd == session_date => cutoff,
_ => {
if let Some(best) = cur_best.take() {
result.push(best);
}
while daily_idx < valid_daily.len() {
match valid_daily[daily_idx]
.key
.cmp(key)
.then_with(|| valid_daily[daily_idx].session_date.cmp(&session_date))
{
Ordering::Less => daily_idx += 1,
Ordering::Equal | Ordering::Greater => break,
}
}
let cutoff = if daily_idx < valid_daily.len()
&& &valid_daily[daily_idx].key == key
&& valid_daily[daily_idx].session_date == session_date
{
valid_daily[daily_idx].session_close_ts
} else {
None
};
cur_group = Some((key, session_date, cutoff));
cutoff
}
};
if let Some(cutoff_ts) = cutoff {
if ts >= cutoff_ts {
continue;
}
}
match &mut cur_best {
Some(best) => match ts.cmp(&best.ts) {
Ordering::Greater => {
best.ts = ts;
best.close = close;
best.conflicting_last_ts = false;
}
Ordering::Equal => {
if close.to_bits() != best.close.to_bits() {
best.conflicting_last_ts = true;
}
}
Ordering::Less => {}
},
None => {
cur_best = Some(LastRthBar {
key,
session_date,
ts,
close,
conflicting_last_ts: false,
});
}
}
}
if let Some(best) = cur_best {
result.push(best);
}
result
}
fn collect_last_rth_bars<'a, K: Ord>(
rows_1m: &'a [Bar1mRow<K>],
valid_daily: &[DailySessionClose<K>],
) -> Vec<LastRthBar<'a, K>> {
let is_sorted = rows_1m.windows(2).all(|w| {
w[0].key
.cmp(&w[1].key)
@ -484,77 +614,46 @@ fn collect_last_rth_bars<K: Ord>(rows_1m: &[Bar1mRow<K>]) -> Vec<LastRthBar<'_,
});
if is_sorted {
let mut last_rth: Vec<LastRthBar<'_, K>> = Vec::new();
for row in rows_1m {
if row.session != IntradaySession::Rth {
continue;
}
if let Some(prev) = last_rth.last_mut() {
if prev.key == &row.key && prev.session_date == row.session_date {
prev.ts = row.ts;
prev.close = row.close;
continue;
}
}
last_rth.push(LastRthBar {
key: &row.key,
session_date: row.session_date,
ts: row.ts,
close: row.close,
});
}
return last_rth;
return select_last_rth_bars(
rows_1m
.iter()
.filter(|row| row.session == IntradaySession::Rth)
.map(|row| (&row.key, row.session_date, row.ts, row.close)),
valid_daily,
);
}
let mut rth_rows: Vec<LastRthBar<'_, K>> = rows_1m
let mut rth_rows: Vec<(&'a K, i32, i64, f64)> = rows_1m
.iter()
.filter(|row| row.session == IntradaySession::Rth)
.map(|row| LastRthBar {
key: &row.key,
session_date: row.session_date,
ts: row.ts,
close: row.close,
})
.map(|row| (&row.key, row.session_date, row.ts, row.close))
.collect();
rth_rows.sort_by(|a, b| {
a.key
.cmp(b.key)
.then_with(|| a.session_date.cmp(&b.session_date))
.then_with(|| a.ts.cmp(&b.ts))
rth_rows.sort_unstable_by(|a, b| {
a.0.cmp(b.0)
.then_with(|| a.1.cmp(&b.1))
.then_with(|| a.2.cmp(&b.2))
});
let mut write_idx = 0usize;
let mut read_idx = 0usize;
while read_idx < rth_rows.len() {
let mut group_end = read_idx + 1;
while group_end < rth_rows.len()
&& rth_rows[group_end].key == rth_rows[read_idx].key
&& rth_rows[group_end].session_date == rth_rows[read_idx].session_date
{
group_end += 1;
}
let last_idx = group_end - 1;
if write_idx != last_idx {
rth_rows.swap(write_idx, last_idx);
}
write_idx += 1;
read_idx = group_end;
}
rth_rows.truncate(write_idx);
rth_rows
select_last_rth_bars(rth_rows, valid_daily)
}
/// Cross-checks the close of the last [`IntradaySession::Rth`] 1-minute bar per
/// `(key, session_date)` against raw daily `bars_1d` closes.
///
/// - Returns [`Bars1mError::InvalidTolerance`] if `rel_tolerance` is non-finite or `< 0.0`.
/// - Selects the last `RTH` bar by max `ts` per `(key, session_date)` (handling early-close half
/// days cleanly while ignoring `PRE`/`POST` bars and excluding `PRE`/`POST`-only sessions).
/// - Selects the last `RTH` bar by max `ts` per `(key, session_date)` strictly before the
/// partner's optional [`DailySessionClose::session_close_ts`] cutoff (defaulting to the
/// standard `16:00:00 ET` boundary when `None`), ignoring `PRE`/`POST` bars and excluding
/// sessions with no eligible `RTH` bar before their cutoff.
/// - If a caller supplies multiple eligible `RTH` bars sharing the session's maximum `ts` with
/// differing `close` values, the session is deterministically counted as `unchecked` regardless
/// of input order.
/// - Uses an `O(N)` single-pass scan when `rows_1m` is already sorted by `(key, session_date, ts)`
/// and falls back to a deterministic sort otherwise.
/// - Filters invalid (`<= 0`, non-finite), collapses bitwise-identical duplicate, and drops
/// conflicting duplicate `bars_1d_closes` partners.
/// conflicting duplicate `bars_1d_closes` partners (comparing both `close` and
/// `session_close_ts`).
/// - Retains up to [`MAX_MISMATCH_SAMPLES`] worst mismatches ordered by
/// `(rel DESC, key ASC, session_date ASC)`.
pub fn check_session_closes<K, D, I>(
@ -572,8 +671,6 @@ where
}
let mut stats = SessionCloseStats::default();
let last_rth = collect_last_rth_bars(rows_1m);
stats.rth_sessions = last_rth.len();
let daily_iter = bars_1d_closes.into_iter();
let mut valid_daily: Vec<DailySessionClose<K>> = Vec::with_capacity(daily_iter.size_hint().0);
@ -606,9 +703,10 @@ where
}
let group_len = group_end - read_idx;
let first_bits = valid_daily[read_idx].close.to_bits();
let all_identical = valid_daily[read_idx + 1..group_end]
.iter()
.all(|other| other.close.to_bits() == first_bits);
let first_cutoff = valid_daily[read_idx].session_close_ts;
let all_identical = valid_daily[read_idx + 1..group_end].iter().all(|other| {
other.close.to_bits() == first_bits && other.session_close_ts == first_cutoff
});
if all_identical {
stats.daily_duplicate_collapsed += group_len - 1;
@ -624,11 +722,19 @@ where
valid_daily.truncate(write_idx);
stats.daily_unique_partners = valid_daily.len();
let last_rth = collect_last_rth_bars(rows_1m, &valid_daily);
stats.rth_sessions = last_rth.len();
let mut daily_idx = 0usize;
let mut heap: BinaryHeap<HeapSessionCloseMismatch<K>> =
BinaryHeap::with_capacity(MAX_MISMATCH_SAMPLES + 1);
for rth in &last_rth {
if rth.conflicting_last_ts {
stats.unchecked += 1;
continue;
}
while daily_idx < valid_daily.len() {
match valid_daily[daily_idx]
.key

View file

@ -489,6 +489,8 @@ fn drops_bad_rows_by_priority_handles_post_unadjust_overflow_underflow_and_dupli
bar_1m(1, i64::MAX, 8.0, 10.0, 5.0, 8.0, 10.0),
// Post-unadjust volume overflow (1e200 / 1e-200 -> Inf) -> dropped_invalid_volume
bar_1m(1, base_ts + 12 * minute, 8.0, 10.0, 5.0, 8.0, 1e200),
// Post-unadjust positive volume underflow (1e-200 / 1e200 -> 0.0) -> dropped_invalid_volume
bar_1m(2, base_ts + 15 * minute, 8.0, 10.0, 5.0, 8.0, 1e-200),
// Post-unadjust price underflow (1e-200 * 1e-200 -> 0.0) -> dropped_invalid_ohlc
bar_1m(1, base_ts + 13 * minute, 1e-200, 1e-200, 1e-200, 1e-200, 10.0),
// Post-unadjust price overflow (1e200 * 1e200 -> Inf) -> dropped_invalid_ohlc
@ -505,10 +507,10 @@ fn drops_bad_rows_by_priority_handles_post_unadjust_overflow_underflow_and_dupli
);
assert_bars_1m_invariants(&built.stats);
assert_eq!(built.stats.bars_in, 24);
assert_eq!(built.stats.bars_in, 25);
assert_eq!(built.stats.dropped_invalid_ohlc, 6); // 4 input + 1 underflow + 1 overflow
assert_eq!(built.stats.dropped_inconsistent_ohlc, 5);
assert_eq!(built.stats.dropped_invalid_volume, 4); // 3 input + 1 volume overflow
assert_eq!(built.stats.dropped_invalid_volume, 5); // 3 input + 1 overflow + 1 positive underflow
assert_eq!(built.stats.dropped_ts_out_of_range, 4);
assert_eq!(built.stats.duplicate_collapsed, 2);
assert_eq!(built.stats.duplicate_conflict_dropped, 2);
@ -533,39 +535,46 @@ fn check_session_closes_handles_early_close_pre_post_only_unsorted_hygiene_cap_a
assert!(err.to_string().contains("invalid relative tolerance"));
}
// 2. Half-day early close (last RTH bar 12:59 ET, later POST bar ignored) + PRE/POST-only session.
let half_day = day(2024, 11, 29); // Day after US Thanksgiving
// 2. Half-day early close (Friday after US Thanksgiving, 13:00 ET close):
// - build_bars_1m preserves the fixed PRE/RTH/POST tags (13:00 and 13:15 still carry RTH).
// - check_session_closes applies the listing's 13:00 ET session_close_ts cutoff so 12:59 ET
// is selected and 13:00 / 13:15 / 16:15 prints do not displace the closing bar.
let half_day = day(2024, 11, 29); // Friday after US Thanksgiving
let post_only_day = day(2024, 12, 2);
let ts_1259 = et_ts(2024, 11, 29, 12, 59);
let ts_1300 = et_ts(2024, 11, 29, 13, 0);
let ts_1315 = et_ts(2024, 11, 29, 13, 15);
let splits: SplitTable<i32> = SplitTable::default();
let built = build_bars_1m(
[
bar_1m(1, et_ts(2024, 11, 29, 9, 30), 100.0, 101.0, 99.5, 100.5, 500.0),
bar_1m(1, et_ts(2024, 11, 29, 12, 59), 101.0, 101.5, 100.8, 101.25, 800.0),
// Later POST bar with a very different close must NOT be selected as RTH close.
bar_1m(1, et_ts(2024, 11, 29, 16, 15), 105.0, 106.0, 104.5, 105.5, 100.0),
bar_1m(1, ts_1259, 101.0, 101.5, 100.8, 101.25, 800.0),
// Exact 13:00 ET boundary and 13:15 ET after-hours print (>4% away):
// fixed tags stay RTH, but the 13:00 ET cutoff must exclude both from the close check.
bar_1m(1, ts_1300, 103.5, 104.2, 103.2, 104.0, 120.0),
bar_1m(1, ts_1315, 105.0, 106.0, 104.5, 105.5, 100.0),
bar_1m(1, et_ts(2024, 11, 29, 16, 15), 105.5, 106.5, 105.0, 106.0, 80.0),
// PRE/POST-only session must be excluded from rth_sessions.
bar_1m(1, et_ts(2024, 12, 2, 8, 0), 102.0, 103.0, 101.5, 102.5, 50.0),
bar_1m(1, et_ts(2024, 12, 2, 17, 0), 103.0, 104.0, 102.5, 103.5, 50.0),
],
&splits,
);
// Output tags strictly follow fixed 09:30..16:00 ET bounds.
assert_eq!(built.rows[0].session, IntradaySession::Rth);
assert_eq!(built.rows[1].session, IntradaySession::Rth);
assert_eq!(built.rows[2].session, IntradaySession::Rth);
assert_eq!(built.rows[3].session, IntradaySession::Rth);
assert_eq!(built.rows[4].session, IntradaySession::Post);
// Reverse rows_1m to exercise the unsorted fallback path in check_session_closes.
let mut reversed_rows = built.rows.clone();
reversed_rows.reverse();
let daily = [
DailySessionClose {
key: 1,
session_date: half_day,
close: 101.25,
},
DailySessionClose {
key: 1,
session_date: post_only_day,
close: 103.5,
},
DailySessionClose::with_close_cutoff(1, half_day, 101.25, ts_1300),
DailySessionClose::new(1, post_only_day, 103.5),
];
let sorted_check = check_session_closes(&built.rows, daily.clone(), 0.005).unwrap();
let unsorted_check = check_session_closes(&reversed_rows, daily, 0.005).unwrap();
@ -575,6 +584,45 @@ fn check_session_closes_handles_early_close_pre_post_only_unsorted_hygiene_cap_a
assert_eq!(sorted_check.stats.checked, 1);
assert_eq!(sorted_check.stats.within_tolerance, 1);
assert_eq!(sorted_check.stats.mismatched, 0);
assert_eq!(sorted_check.stats.max_rel_diff, 0.0);
// Prove 12:59 ET (101.25) was actually selected under the 13:00 ET cutoff:
// comparing against the 13:15 ET price (105.5) must report a mismatch at ts_1259.
let prove_1259 = check_session_closes(
&built.rows,
[DailySessionClose::with_close_cutoff(1, half_day, 105.5, ts_1300)],
0.005,
)
.unwrap();
assert_eq!(prove_1259.stats.mismatched, 1);
assert_eq!(prove_1259.mismatch_samples[0].last_rth_ts, ts_1259);
assert_eq!(prove_1259.mismatch_samples[0].close_1m, 101.25);
// Without the early-close cutoff, the fixed 16:00 ET window picks 13:15 ET (105.5) and mismatches.
let without_cutoff = check_session_closes(
&built.rows,
[DailySessionClose::new(1, half_day, 101.25)],
0.005,
)
.unwrap();
assert_eq!(without_cutoff.stats.mismatched, 1);
assert_eq!(without_cutoff.mismatch_samples[0].last_rth_ts, ts_1315);
assert_eq!(without_cutoff.mismatch_samples[0].close_1m, 105.5);
// A half-day session whose only RTH bars are at/after the cutoff has no eligible RTH bar.
let post_cutoff_only = build_bars_1m(
[bar_1m(9, ts_1315, 105.0, 106.0, 104.5, 105.5, 100.0)],
&splits,
);
let post_cutoff_check = check_session_closes(
&post_cutoff_only.rows,
[DailySessionClose::with_close_cutoff(9, half_day, 101.25, ts_1300)],
0.005,
)
.unwrap();
assert_close_check_invariants(&post_cutoff_check.stats);
assert_eq!(post_cutoff_check.stats.rth_sessions, 0);
assert_eq!(post_cutoff_check.stats.checked, 0);
// 3. Daily close hygiene (invalid, identical dup, conflicting dup) + >100 mismatch sample cap.
let base_day = day(2024, 1, 2);
@ -583,18 +631,28 @@ fn check_session_closes_handles_early_close_pre_post_only_unsorted_hygiene_cap_a
// Session 0: exact match with identical daily duplicate -> collapses to 1
rows_1m_in.push(bar_1m(1, et_ts(2024, 1, 2, 15, 59), 10.0, 10.5, 9.5, 10.0, 100.0));
daily_in.push(DailySessionClose { key: 1, session_date: base_day, close: 10.0 });
daily_in.push(DailySessionClose { key: 1, session_date: base_day, close: 10.0 });
daily_in.push(DailySessionClose::new(1, base_day, 10.0));
daily_in.push(DailySessionClose::new(1, base_day, 10.0));
// Session 1: conflicting daily duplicate -> dropped -> unchecked
rows_1m_in.push(bar_1m(1, et_ts(2024, 1, 3, 15, 59), 10.0, 10.5, 9.5, 10.0, 100.0));
daily_in.push(DailySessionClose { key: 1, session_date: base_day + 1, close: 10.0 });
daily_in.push(DailySessionClose { key: 1, session_date: base_day + 1, close: 10.5 });
daily_in.push(DailySessionClose::new(1, base_day + 1, 10.0));
daily_in.push(DailySessionClose::new(1, base_day + 1, 10.5));
// Session 2: invalid daily closes (NaN, <=0) -> dropped -> unchecked
rows_1m_in.push(bar_1m(1, et_ts(2024, 1, 4, 15, 59), 10.0, 10.5, 9.5, 10.0, 100.0));
daily_in.push(DailySessionClose { key: 1, session_date: base_day + 2, close: f64::NAN });
daily_in.push(DailySessionClose { key: 1, session_date: base_day + 2, close: 0.0 });
daily_in.push(DailySessionClose::new(1, base_day + 2, f64::NAN));
daily_in.push(DailySessionClose::new(1, base_day + 2, 0.0));
// Session 3: same daily close but conflicting session_close_ts -> dropped -> unchecked
rows_1m_in.push(bar_1m(1, et_ts(2024, 1, 5, 15, 59), 10.0, 10.5, 9.5, 10.0, 100.0));
daily_in.push(DailySessionClose::new(1, base_day + 3, 10.0));
daily_in.push(DailySessionClose::with_close_cutoff(
1,
base_day + 3,
10.0,
et_ts(2024, 1, 5, 13, 0),
));
// 110 mismatches across distinct days on key=2 (plus a tie on key=3 to verify tie-break order).
let start_day = day(2024, 2, 1);
@ -603,29 +661,21 @@ fn check_session_closes_handles_early_close_pre_post_only_unsorted_hygiene_cap_a
let ts = et_to_utc_micros(d, 15, 59, 0).unwrap();
let close_1m = 100.0 + (i + 2) as f64; // rel = (i + 2) / 100 >= 0.02 > 0.005
rows_1m_in.push(bar_1m(2, ts, close_1m, close_1m, close_1m, close_1m, 100.0));
daily_in.push(DailySessionClose {
key: 2,
session_date: d,
close: 100.0,
});
daily_in.push(DailySessionClose::new(2, d, 100.0));
}
// Tie with highest rel (1.11) on key=3 vs key=2 -> key=2 must sort before key=3.
let tie_d = start_day + 109;
let tie_ts = et_to_utc_micros(tie_d, 15, 59, 0).unwrap();
rows_1m_in.push(bar_1m(3, tie_ts, 211.0, 211.0, 211.0, 211.0, 100.0));
daily_in.push(DailySessionClose {
key: 3,
session_date: tie_d,
close: 100.0,
});
daily_in.push(DailySessionClose::new(3, tie_d, 100.0));
let built_many = build_bars_1m(rows_1m_in, &splits);
let check_many = check_session_closes(&built_many.rows, daily_in, 0.005).unwrap();
assert_close_check_invariants(&check_many.stats);
assert_eq!(check_many.stats.daily_invalid_close_dropped, 2);
assert_eq!(check_many.stats.daily_duplicate_collapsed, 1);
assert_eq!(check_many.stats.daily_duplicate_conflict_dropped, 2);
assert_eq!(check_many.stats.unchecked, 2);
assert_eq!(check_many.stats.daily_duplicate_conflict_dropped, 4);
assert_eq!(check_many.stats.unchecked, 3);
assert_eq!(check_many.stats.mismatched, 111);
assert_eq!(check_many.mismatch_samples.len(), MAX_MISMATCH_SAMPLES);
@ -685,3 +735,90 @@ fn output_is_sorted_unique_and_deterministic_across_input_permutations() {
assert_eq!(ord, Ordering::Less, "output not strictly sorted/unique");
}
}
#[test]
fn check_session_closes_handles_conflicting_latest_rth_timestamps_deterministically() {
let d1 = day(2024, 6, 10);
let d2 = day(2024, 6, 11);
let d3 = day(2024, 6, 12);
let mk_row = |key: i32, session_date: i32, ts: i64, close: f64| Bar1mRow {
key,
session_date,
ts,
open: close,
high: close,
low: close,
close,
volume: 100.0,
session: IntradaySession::Rth,
source: BARS_1M_SOURCE_EOD,
};
// d1: conflicting closes at the latest RTH timestamp (one matches 100.0, one is 105.0).
let ts_d1_last = et_ts(2024, 6, 10, 15, 59);
let d1_match = mk_row(1, d1, ts_d1_last, 100.0);
let d1_mismatch = mk_row(1, d1, ts_d1_last, 105.0);
// d2: identical duplicate closes at the latest RTH timestamp -> checked and matched.
let ts_d2_last = et_ts(2024, 6, 11, 15, 59);
let d2_a = mk_row(1, d2, ts_d2_last, 50.0);
let d2_b = mk_row(1, d2, ts_d2_last, 50.0);
// d3: conflicting closes at an earlier timestamp (10:00) followed by a unique latest bar (15:59)
// -> latest bar is unambiguous, so d3 is checked and matched.
let ts_d3_early = et_ts(2024, 6, 12, 10, 0);
let ts_d3_last = et_ts(2024, 6, 12, 15, 59);
let d3_early_a = mk_row(1, d3, ts_d3_early, 20.0);
let d3_early_b = mk_row(1, d3, ts_d3_early, 25.0);
let d3_last = mk_row(1, d3, ts_d3_last, 22.0);
let daily = [
DailySessionClose::new(1, d1, 100.0),
DailySessionClose::new(1, d2, 50.0),
DailySessionClose::new(1, d3, 22.0),
];
// Order A (sorted): matching bar before mismatching bar on d1.
let order_a = vec![
d1_match.clone(),
d1_mismatch.clone(),
d2_a.clone(),
d2_b.clone(),
d3_early_a.clone(),
d3_early_b.clone(),
d3_last.clone(),
];
// Order B (sorted): mismatching bar before matching bar on d1.
let order_b = vec![
d1_mismatch.clone(),
d1_match.clone(),
d2_b.clone(),
d2_a.clone(),
d3_early_b.clone(),
d3_early_a.clone(),
d3_last.clone(),
];
// Order C (unsorted fallback): reversed order_a.
let mut order_c = order_a.clone();
order_c.reverse();
// Order D (unsorted fallback): reversed order_b.
let mut order_d = order_b.clone();
order_d.reverse();
let check_a = check_session_closes(&order_a, daily.clone(), 0.005).unwrap();
let check_b = check_session_closes(&order_b, daily.clone(), 0.005).unwrap();
let check_c = check_session_closes(&order_c, daily.clone(), 0.005).unwrap();
let check_d = check_session_closes(&order_d, daily, 0.005).unwrap();
assert_eq!(check_a, check_b);
assert_eq!(check_a, check_c);
assert_eq!(check_a, check_d);
assert_close_check_invariants(&check_a.stats);
assert_eq!(check_a.stats.rth_sessions, 3);
assert_eq!(check_a.stats.checked, 2);
assert_eq!(check_a.stats.within_tolerance, 2);
assert_eq!(check_a.stats.mismatched, 0);
assert_eq!(check_a.stats.unchecked, 1);
assert!(check_a.mismatch_samples.is_empty());
}

View file

@ -837,26 +837,10 @@ fn verify_bars_1m_bench_self_check() -> Result<(), Bars1mError> {
assert_eq!(built.rows[6].session, IntradaySession::Post);
let daily = [
DailySessionClose {
key: "NEXM.V",
session_date: nexm_ex - 1,
close: 1.2145,
},
DailySessionClose {
key: "NEXM.V",
session_date: nexm_ex,
close: 24.30,
},
DailySessionClose {
key: "NVDA.US",
session_date: nvda_ex - 3,
close: 1_208.88,
},
DailySessionClose {
key: "NVDA.US",
session_date: nvda_ex,
close: 121.79,
},
DailySessionClose::new("NEXM.V", nexm_ex - 1, 1.2145),
DailySessionClose::new("NEXM.V", nexm_ex, 24.30),
DailySessionClose::new("NVDA.US", nvda_ex - 3, 1_208.88),
DailySessionClose::new("NVDA.US", nvda_ex, 121.79),
];
let check = check_session_closes(&built.rows, daily, 0.005)?;
assert_eq!(check.stats.checked, 4, "self-check expected 4 checked sessions");
@ -869,9 +853,10 @@ fn verify_bars_1m_bench_self_check() -> Result<(), Bars1mError> {
/// Executes a pre-timing correctness self-check (NEXM.V 1:20 reverse split, NVDA.US 10:1 forward
/// split, EST/EDT session tagging, and `check_session_closes`), then generates `rows` deterministic
/// multi-session EST/EDT 1m bars across `2_000` `i32` keys with forward/reverse splits, a small
/// share of invalid/inconsistent/out-of-range/duplicate bars, and daily close cross-check partners.
/// Times [`build_bars_1m`] and [`check_session_closes`] and returns throughput plus a deterministic
/// `u64` checksum.
/// share of invalid/inconsistent/out-of-range/duplicate bars, and one daily close reference per
/// sampled synthetic session derived from its expected last valid RTH minute (with deliberate
/// mismatches and duplicate conflicts injected separately). Times [`build_bars_1m`] and
/// [`check_session_closes`] and returns throughput plus a deterministic `u64` checksum.
pub fn run_bars_1m_benchmark(rows: usize) -> Result<Bars1mBenchReport, Bars1mError> {
verify_bars_1m_bench_self_check()?;
@ -892,21 +877,30 @@ pub fn run_bars_1m_benchmark(rows: usize) -> Result<Bars1mBenchReport, Bars1mErr
let split_event_count = splits.event_count();
let mut bars: Vec<EodIntradayBar<i32>> = Vec::with_capacity(rows);
let mut daily_closes: Vec<DailySessionClose<i32>> = Vec::with_capacity(rows / 20 + 64);
// Track every valid RTH candidate `(key, session_date, ts, close)` (including exact/conflicting
// duplicates) so we can derive each session's exact expected last valid RTH bar before timing.
let mut valid_rth_candidates: Vec<(i32, i32, i64, f64)> = Vec::with_capacity(rows / 2 + 64);
let mut last_valid: Option<EodIntradayBar<i32>> = None;
let mut last_valid: Option<(EodIntradayBar<i32>, i32, bool)> = None;
for _ in 0..rows {
let roll = rng.next_u64() % 1_000;
if roll < 5 {
if let Some(prev) = last_valid.clone() {
if let Some((prev, prev_date, prev_is_rth)) = last_valid.clone() {
if prev_is_rth {
valid_rth_candidates.push((prev.key, prev_date, prev.ts, prev.close));
}
bars.push(prev);
continue;
}
} else if roll < 7 {
if let Some(mut prev) = last_valid.clone() {
if let Some((mut prev, prev_date, prev_is_rth)) = last_valid.clone() {
let orig_close_bits = prev.close.to_bits();
prev.close = (prev.close + 0.05).min(prev.high);
if prev.close.to_bits() == last_valid.as_ref().map_or(0, |b| b.close.to_bits()) {
prev.volume += 1.0;
if prev.close.to_bits() == orig_close_bits {
prev.close = (prev.close - 0.05).max(prev.low);
}
if prev_is_rth {
valid_rth_candidates.push((prev.key, prev_date, prev.ts, prev.close));
}
bars.push(prev);
continue;
@ -917,6 +911,7 @@ pub fn run_bars_1m_benchmark(rows: usize) -> Result<Bars1mBenchReport, Bars1mErr
let session_date = min_date + (rng.next_u64() % date_span) as i32;
// 08:00..=19:59 ET (minutes 480..1200) -> spans PRE, RTH, and POST on both EST and EDT.
let et_minute = 480 + (rng.next_u64() % 720) as i64;
let is_rth = (570..960).contains(&et_minute);
let close_1600_utc = et_session_close_utc_micros(session_date).unwrap_or(0);
let ts = close_1600_utc + (et_minute - 960) * 60_000_000;
@ -974,7 +969,10 @@ pub fn run_bars_1m_benchmark(rows: usize) -> Result<Bars1mBenchReport, Bars1mErr
close,
volume: 0.0,
};
last_valid = Some(b.clone());
if is_rth {
valid_rth_candidates.push((key, session_date, ts, close));
}
last_valid = Some((b.clone(), session_date, is_rth));
b
}
_ => {
@ -987,29 +985,96 @@ pub fn run_bars_1m_benchmark(rows: usize) -> Result<Bars1mBenchReport, Bars1mErr
close,
volume,
};
last_valid = Some(b.clone());
if (570..960).contains(&et_minute) && (rng.next_u64() % 16) == 0 {
let factor = splits.cum_factor_after(&key, session_date);
let raw_close = close * factor;
let mismatch_roll = rng.next_u64() % 100;
let daily_close = if mismatch_roll == 0 {
raw_close * 1.05
} else {
let jitter_bp = (rng.next_u64() % 41) as f64 - 20.0; // -0.20%..+0.20%
raw_close * (1.0 + jitter_bp * 0.0001)
};
daily_closes.push(DailySessionClose {
key,
session_date,
close: daily_close,
});
if is_rth {
valid_rth_candidates.push((key, session_date, ts, close));
}
last_valid = Some((b.clone(), session_date, is_rth));
b
}
};
bars.push(bar);
}
// Derive one daily reference close per sampled synthetic session from its expected last
// surviving valid RTH bar, then inject deliberate mismatches and conflicts separately.
valid_rth_candidates.sort_unstable_by(|a, b| {
a.0.cmp(&b.0)
.then_with(|| a.1.cmp(&b.1))
.then_with(|| a.2.cmp(&b.2))
});
let mut daily_closes: Vec<DailySessionClose<i32>> =
Vec::with_capacity(valid_rth_candidates.len() / 4 + 64);
let mut idx = 0usize;
while idx < valid_rth_candidates.len() {
let key = valid_rth_candidates[idx].0;
let session_date = valid_rth_candidates[idx].1;
let mut session_end = idx + 1;
while session_end < valid_rth_candidates.len()
&& valid_rth_candidates[session_end].0 == key
&& valid_rth_candidates[session_end].1 == session_date
{
session_end += 1;
}
// Find the last non-conflicted `(key, ts)` subgroup within this `(key, session_date)`.
let mut expected_last_close: Option<f64> = None;
let mut g = idx;
while g < session_end {
let ts = valid_rth_candidates[g].2;
let mut g_end = g + 1;
while g_end < session_end && valid_rth_candidates[g_end].2 == ts {
g_end += 1;
}
let first_bits = valid_rth_candidates[g].3.to_bits();
let all_same = valid_rth_candidates[g + 1..g_end]
.iter()
.all(|c| c.3.to_bits() == first_bits);
if all_same {
expected_last_close = Some(valid_rth_candidates[g].3);
}
g = g_end;
}
idx = session_end;
let Some(adj_close) = expected_last_close else {
continue;
};
if (rng.next_u64() % 4) != 0 {
continue;
}
let factor = splits.cum_factor_after(&key, session_date);
let raw_close = adj_close * factor;
let case_roll = rng.next_u64() % 200;
match case_roll {
0..=1 => {
// Deliberate 5% mismatch (> 0.5% tolerance).
daily_closes.push(DailySessionClose::new(key, session_date, raw_close * 1.05));
}
2 => {
// Deliberate conflicting duplicate daily reference.
daily_closes.push(DailySessionClose::new(key, session_date, raw_close));
daily_closes.push(DailySessionClose::new(key, session_date, raw_close * 1.03));
}
3 => {
// Deliberate identical duplicate daily reference.
daily_closes.push(DailySessionClose::new(key, session_date, raw_close));
daily_closes.push(DailySessionClose::new(key, session_date, raw_close));
}
_ => {
// Within-tolerance reference (-0.20%..+0.20%).
let jitter_bp = (rng.next_u64() % 41) as f64 - 20.0;
daily_closes.push(DailySessionClose::new(
key,
session_date,
raw_close * (1.0 + jitter_bp * 0.0001),
));
}
}
}
drop(valid_rth_candidates);
let daily_rows_in = daily_closes.len();
let build_start = Instant::now();