stock-bot/tools/curate-etl/src/bench.rs

1665 lines
59 KiB
Rust

//! Fixed-seed, std-only benchmark for the split-factor lookup and un-adjustment hot loop.
use std::hint::black_box;
use std::time::Instant;
use crate::adj::{build_adj_factors, AdjBuildStats, AdjError, DividendEvent};
use crate::bars::{build_bars_1d, Bars1dStats, BarsError, EodDailyBar, QmRawVolume};
use crate::corporate_actions::{
build_corporate_actions, CorporateActionError, CorporateActionsStats, DelistingOutcomeEvent,
DividendActionEvent, SplitActionEvent,
};
use crate::events::{build_events, EventsStats, QmEarning, QmFiling};
use crate::fx::{build_fx_1d, fx_rate_on_or_before, Fx1dStats, FxDailyBar};
use crate::shorts::{build_shorts, epoch_days_to_ymd, CeoShortReport, ShortsError, ShortsStats};
use crate::split::{unadjust_volume, ymd_to_epoch_days, SplitError, SplitEvent, SplitTable};
pub const DEFAULT_BENCH_ROWS: usize = 10_000_000;
pub const DEFAULT_ADJ_BENCH_EVENTS: usize = 1_000_000;
pub const DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS: usize = 1_000_000;
pub const DEFAULT_BARS_BENCH_ROWS: usize = 10_000_000;
pub const DEFAULT_FX_BENCH_ROWS: usize = 20_000;
pub const DEFAULT_FX_BENCH_LOOKUPS: usize = 1_000_000;
pub const DEFAULT_SHORTS_BENCH_ROWS: usize = 700_000;
pub const DEFAULT_EVENTS_BENCH_ROWS: usize = 500_000;
pub const BENCH_KEY_COUNT: usize = 20_000;
pub const BENCH_EVENT_COUNT: usize = 19_000;
const SHORTS_BENCH_KEY_COUNT: usize = 12_500;
const BENCH_SEED: u64 = 0x570C_4B07_5171_7E57;
const ADJ_BENCH_SEED: u64 = 0x570C_4B07_AD7F_AC70;
const CORPORATE_ACTIONS_BENCH_SEED: u64 = 0x570C_4B07_C049_AC71;
const BARS_BENCH_SEED: u64 = 0x570C_4B07_BA45_1D00;
const FX_BENCH_SEED: u64 = 0x570C_4B07_F81D_CADE;
const SHORTS_BENCH_SEED: u64 = 0x570C_4B07_5404_7500;
const EVENTS_BENCH_SEED: u64 = 0x570C_4B07_E7E4_7500;
const SAMPLE_RATIOS: [f64; 9] = [2.0, 3.0, 4.0, 5.0, 10.0, 0.5, 0.25, 0.1, 0.05];
/// Deterministic SplitMix64 generator (zero external dependencies).
#[derive(Debug, Clone, Copy)]
struct SplitMix64 {
state: u64,
}
impl SplitMix64 {
#[inline]
fn new(seed: u64) -> Self {
Self { state: seed }
}
#[inline]
fn next_u64(&mut self) -> u64 {
self.state = self.state.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = self.state;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
}
}
/// Summary metrics produced by [`run_split_benchmark`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct BenchReport {
pub rows: usize,
pub key_count: usize,
pub table_keys_with_splits: usize,
pub table_event_count: usize,
pub build_elapsed_ms: f64,
pub elapsed_ms: f64,
pub rows_per_sec: f64,
pub ns_per_row: f64,
pub checksum: f64,
}
#[inline]
fn compute_rates(rows: usize, elapsed_secs: f64) -> (f64, f64) {
if rows == 0 || elapsed_secs <= 0.0 || !elapsed_secs.is_finite() {
(0.0, 0.0)
} else {
(rows as f64 / elapsed_secs, elapsed_secs * 1e9 / rows as f64)
}
}
/// Runs the fixed-seed split lookup + `unadjust_volume` benchmark for `rows` bars.
///
/// Builds a [`SplitTable<String>`] with `20_000` symbol keys and `19_000` deterministic forward
/// and reverse splits spanning `1990-01-01..=2025-12-31`, then executes `rows` zero-allocation
/// lookups and volume un-adjustments.
pub fn run_split_benchmark(rows: usize) -> Result<BenchReport, SplitError> {
let min_date = ymd_to_epoch_days(1990, 1, 1)?;
let max_date = ymd_to_epoch_days(2025, 12, 31)?;
let date_span = (max_date - min_date + 1) as u64;
let keys: Vec<String> = (0..BENCH_KEY_COUNT)
.map(|i| format!("SYM{i:05}.US"))
.collect();
let mut rng = SplitMix64::new(BENCH_SEED);
let mut events = Vec::with_capacity(BENCH_EVENT_COUNT);
for _ in 0..BENCH_EVENT_COUNT {
let key_idx = (rng.next_u64() as usize) % keys.len();
let ex_date = min_date + (rng.next_u64() % date_span) as i32;
let ratio = SAMPLE_RATIOS[(rng.next_u64() as usize) % SAMPLE_RATIOS.len()];
events.push((keys[key_idx].clone(), SplitEvent { ex_date, ratio }));
}
let build_start = Instant::now();
let table = SplitTable::from_events(events)?;
let build_elapsed_ms = build_start.elapsed().as_secs_f64() * 1_000.0;
let key_count = keys.len();
let mut acc = 0.0_f64;
let loop_start = Instant::now();
for _ in 0..rows {
let key_idx = (rng.next_u64() as usize) % key_count;
let bar_date = min_date + (rng.next_u64() % date_span) as i32;
let adj_volume = ((rng.next_u64() % 10_000_000) + 100) as f64;
let factor = table.cum_factor_after(keys[key_idx].as_str(), bar_date);
let raw_volume = unadjust_volume(adj_volume, factor);
acc += raw_volume;
}
let checksum = black_box(acc);
let elapsed = loop_start.elapsed();
let elapsed_secs = elapsed.as_secs_f64();
let elapsed_ms = elapsed_secs * 1_000.0;
let (rows_per_sec, ns_per_row) = compute_rates(rows, elapsed_secs);
Ok(BenchReport {
rows,
key_count,
table_keys_with_splits: table.len(),
table_event_count: table.event_count(),
build_elapsed_ms,
elapsed_ms,
rows_per_sec,
ns_per_row,
checksum,
})
}
/// Summary metrics produced by [`run_adj_benchmark`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct AdjBenchReport {
pub events: usize,
pub split_events_in: usize,
pub dividend_events_in: usize,
pub key_count: usize,
pub rows_out: usize,
pub keys_out: usize,
pub build_elapsed_ms: f64,
pub events_per_sec: f64,
pub ns_per_event: f64,
pub checksum: f64,
pub stats: AdjBuildStats,
}
/// Runs the fixed-seed `build_adj_factors` benchmark for `events` mixed split and dividend events.
///
/// Generates `events` deterministic events across `20_000` `i32` `listing_id` keys spanning
/// `1990-01-01..=2025-12-31` (~4% splits including occasional `1.0` no-ops, ~96% dividends with
/// realistic USD/CAD home currencies and small fallback fractions), times only
/// [`build_adj_factors`], and returns throughput plus a deterministic checksum.
pub fn run_adj_benchmark(events: usize) -> Result<AdjBenchReport, AdjError> {
let min_date = ymd_to_epoch_days(1990, 1, 1).unwrap_or(7_305);
let max_date = ymd_to_epoch_days(2025, 12, 31).unwrap_or(20_453);
let date_span = (max_date - min_date + 1) as u64;
let mut rng = SplitMix64::new(ADJ_BENCH_SEED);
let mut splits: Vec<(i32, SplitEvent)> = Vec::with_capacity(events / 20);
let mut dividends: Vec<(i32, DividendEvent)> = Vec::with_capacity(events);
for _ in 0..events {
let key = ((rng.next_u64() as usize) % BENCH_KEY_COUNT) as i32 + 1;
let ex_date = min_date + (rng.next_u64() % date_span) as i32;
let kind_roll = rng.next_u64() % 100;
if kind_roll < 4 {
let ratio_roll = rng.next_u64() % 20;
let ratio = if ratio_roll == 0 {
1.0
} else {
SAMPLE_RATIOS[(rng.next_u64() as usize) % SAMPLE_RATIOS.len()]
};
splits.push((key, SplitEvent { ex_date, ratio }));
} else {
let (home_curr, alt_curr) = if key % 5 == 0 {
("CAD", "USD")
} else {
("USD", "CAD")
};
let fallback_roll = rng.next_u64() % 100;
let cash = if fallback_roll == 5 {
0.0
} else {
((rng.next_u64() % 150) + 5) as f64 * 0.01
};
let (prev_close, prev_close_currency) = match fallback_roll {
0 | 1 => (None, Some(home_curr.to_string())),
2 | 3 => (
Some(20.0 + (rng.next_u64() % 200) as f64),
Some(alt_curr.to_string()),
),
4 => (Some(cash * 0.5), Some(home_curr.to_string())),
_ => (
Some(20.0 + (rng.next_u64() % 200) as f64),
Some(home_curr.to_string()),
),
};
dividends.push((
key,
DividendEvent {
ex_date,
cash,
currency: home_curr.to_string(),
prev_close,
prev_close_currency,
},
));
}
}
let split_events_in = splits.len();
let dividend_events_in = dividends.len();
let build_start = Instant::now();
let built = build_adj_factors(splits, dividends)?;
let build_elapsed = build_start.elapsed();
let build_elapsed_secs = build_elapsed.as_secs_f64();
let build_elapsed_ms = build_elapsed_secs * 1_000.0;
let mut acc = 0.0_f64;
for row in &built.rows {
acc += row.cum_split_factor + row.cum_total_factor + row.div_cash;
}
let checksum = black_box(acc);
let (events_per_sec, ns_per_event) = compute_rates(events, build_elapsed_secs);
Ok(AdjBenchReport {
events,
split_events_in,
dividend_events_in,
key_count: BENCH_KEY_COUNT,
rows_out: built.stats.rows_out,
keys_out: built.stats.keys_out,
build_elapsed_ms,
events_per_sec,
ns_per_event,
checksum,
stats: built.stats,
})
}
/// Summary metrics produced by [`run_corporate_actions_benchmark`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct CorporateActionsBenchReport {
pub events: usize,
pub splits_in: usize,
pub dividends_in: usize,
pub delistings_in: usize,
pub key_count: usize,
pub rows_out: usize,
pub keys_out: usize,
pub build_elapsed_ms: f64,
pub events_per_sec: f64,
pub ns_per_event: f64,
pub checksum: u64,
pub stats: CorporateActionsStats,
}
#[inline]
fn mix_u64(state: u64, value: u64) -> u64 {
let mut x = state ^ value.wrapping_mul(0x9E37_79B9_7F4A_7C15);
x = x.rotate_left(27).wrapping_mul(0xBF58_476D_1CE4_E5B9);
x ^ (x >> 31)
}
/// Runs the fixed-seed `build_corporate_actions` benchmark for `events` mixed split, dividend,
/// and delisting events.
///
/// Generates `events` deterministic events across `20_000` `i32` `listing_id` keys spanning
/// `1990-01-01..=2025-12-31` (~4% splits with `1.0` no-ops and declared/missing/late dates,
/// ~92% USD/CAD dividends with `0.0` drops and declared/missing/late dates, ~4% delistings with
/// OTC transfers, `-0.3`/`-1.0` terminal returns, and no-outcome drops), times only
/// [`build_corporate_actions`], and returns throughput plus a deterministic `u64` checksum.
pub fn run_corporate_actions_benchmark(
events: usize,
) -> Result<CorporateActionsBenchReport, CorporateActionError> {
let min_date = ymd_to_epoch_days(1990, 1, 1).unwrap_or(7_305);
let max_date = ymd_to_epoch_days(2025, 12, 31).unwrap_or(20_453);
let date_span = (max_date - min_date + 1) as u64;
let mut rng = SplitMix64::new(CORPORATE_ACTIONS_BENCH_SEED);
let mut splits: Vec<(i32, SplitActionEvent)> = Vec::with_capacity(events / 20);
let mut dividends: Vec<(i32, DividendActionEvent)> = Vec::with_capacity(events);
let mut delistings: Vec<(i32, DelistingOutcomeEvent<i32>)> = Vec::with_capacity(events / 20);
for _ in 0..events {
let key = (rng.next_u64() % (BENCH_KEY_COUNT as u64)) as i32 + 1;
let ex_date = min_date + (rng.next_u64() % date_span) as i32;
let kind_roll = rng.next_u64() % 100;
if kind_roll < 4 {
let ratio_roll = rng.next_u64() % 20;
let ratio = if ratio_roll == 0 {
1.0
} else {
SAMPLE_RATIOS[(rng.next_u64() % (SAMPLE_RATIOS.len() as u64)) as usize]
};
let decl_roll = rng.next_u64() % 100;
let declared_date = if decl_roll < 30 {
Some(ex_date - 14)
} else if decl_roll < 32 {
Some(ex_date + 3)
} else {
None
};
splits.push((
key,
SplitActionEvent {
ex_date,
ratio,
declared_date,
},
));
} else if kind_roll < 96 {
let curr = if key % 5 == 0 { "CAD" } else { "USD" };
let cash_roll = rng.next_u64() % 100;
let cash = if cash_roll == 0 {
0.0
} else {
((rng.next_u64() % 150) + 5) as f64 * 0.01
};
let decl_roll = rng.next_u64() % 100;
let declared_date = if decl_roll < 82 {
Some(ex_date - 21)
} else if decl_roll < 84 {
Some(ex_date + 2)
} else {
None
};
dividends.push((
key,
DividendActionEvent {
ex_date,
cash,
currency: curr.to_string(),
declared_date,
},
));
} else {
let outcome_roll = rng.next_u64() % 10;
let (successor_key, terminal_return) = match outcome_roll {
0..=2 => (Some(key + BENCH_KEY_COUNT as i32), None),
3..=5 => (None, Some(-0.3)),
6..=7 => (None, Some(-1.0)),
_ => (None, None),
};
delistings.push((
key,
DelistingOutcomeEvent {
delist_date: ex_date,
successor_key,
terminal_return,
},
));
}
}
let splits_in = splits.len();
let dividends_in = dividends.len();
let delistings_in = delistings.len();
let build_start = Instant::now();
let built = build_corporate_actions(splits, dividends, delistings)?;
let build_elapsed = build_start.elapsed();
let build_elapsed_secs = build_elapsed.as_secs_f64();
let build_elapsed_ms = build_elapsed_secs * 1_000.0;
let mut hash = 0u64;
for row in &built.rows {
hash = mix_u64(hash, row.key as u64);
hash = mix_u64(hash, row.ex_date as u64);
hash = mix_u64(hash, row.declared_date.map_or(u64::MAX, |d| d as u64));
hash = mix_u64(hash, row.kind as u64);
hash = mix_u64(hash, row.ratio.map_or(0, f64::to_bits));
hash = mix_u64(hash, row.cash_amount.map_or(0, f64::to_bits));
let curr_bits = row.currency.as_deref().map_or(0u64, |c| {
c.bytes()
.fold(0u64, |acc, b| acc.wrapping_shl(8) | u64::from(b))
});
hash = mix_u64(hash, curr_bits);
hash = mix_u64(hash, row.successor_key.map_or(u64::MAX, |k| k as u64));
hash = mix_u64(hash, row.terminal_return.map_or(0, f64::to_bits));
hash = mix_u64(hash, row.known_at_date as u64);
hash = mix_u64(hash, row.known_at_source as u64);
}
let checksum = black_box(hash);
let (events_per_sec, ns_per_event) = compute_rates(events, build_elapsed_secs);
Ok(CorporateActionsBenchReport {
events,
splits_in,
dividends_in,
delistings_in,
key_count: BENCH_KEY_COUNT,
rows_out: built.stats.rows_out,
keys_out: built.stats.keys_out,
build_elapsed_ms,
events_per_sec,
ns_per_event,
checksum,
stats: built.stats,
})
}
/// Summary metrics produced by [`run_bars_benchmark`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct BarsBenchReport {
pub rows: usize,
pub key_count: usize,
pub split_event_count: usize,
pub qm_rows_in: usize,
pub rows_out: usize,
pub keys_out: usize,
pub mismatch_samples_out: usize,
pub build_elapsed_ms: f64,
pub rows_per_sec: f64,
pub ns_per_row: f64,
pub checksum: u64,
pub stats: Bars1dStats,
}
/// Runs the fixed-seed `build_bars_1d` benchmark for `rows` daily bars.
///
/// Generates `rows` deterministic daily bars across `20_000` `i32` `listing_id` keys spanning
/// `1990-01-01..=2025-12-31` with `19_000` forward/reverse splits, a small share of invalid,
/// zero-volume, identical-duplicate, and conflicting-duplicate bars, and ~50% `qmPrices` raw-volume
/// cross-check partners (mostly within 1% plus ~1% intentional mismatches). Times only
/// [`build_bars_1d`] and returns throughput plus a deterministic `u64` checksum.
pub fn run_bars_benchmark(rows: usize) -> Result<BarsBenchReport, BarsError> {
let min_date = ymd_to_epoch_days(1990, 1, 1).unwrap_or(7_305);
let max_date = ymd_to_epoch_days(2025, 12, 31).unwrap_or(20_453);
let date_span = (max_date - min_date + 1) as u64;
let mut rng = SplitMix64::new(BARS_BENCH_SEED);
let mut split_events = Vec::with_capacity(BENCH_EVENT_COUNT);
for _ in 0..BENCH_EVENT_COUNT {
let key = (rng.next_u64() % (BENCH_KEY_COUNT as u64)) as i32 + 1;
let ex_date = min_date + (rng.next_u64() % date_span) as i32;
let ratio = SAMPLE_RATIOS[(rng.next_u64() % (SAMPLE_RATIOS.len() as u64)) as usize];
split_events.push((key, SplitEvent { ex_date, ratio }));
}
let splits = SplitTable::from_events(split_events).unwrap_or_default();
let split_event_count = splits.event_count();
let mut bars: Vec<EodDailyBar<i32>> = Vec::with_capacity(rows);
let mut qm_volumes: Vec<QmRawVolume<i32>> = Vec::with_capacity(rows / 2 + 64);
let mut last_valid: Option<EodDailyBar<i32>> = None;
for _ in 0..rows {
let roll = rng.next_u64() % 1_000;
if roll < 5 {
if let Some(prev) = last_valid.clone() {
bars.push(prev);
continue;
}
} else if roll < 7 {
if let Some(mut prev) = last_valid.clone() {
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.adj_volume += 1.0;
}
bars.push(prev);
continue;
}
}
let key = (rng.next_u64() % (BENCH_KEY_COUNT as u64)) as i32 + 1;
let session_date = min_date + (rng.next_u64() % date_span) as i32;
let low = ((rng.next_u64() % 40_000) + 100) as f64 * 0.01;
let spread = ((rng.next_u64() % 500) + 10) as f64 * 0.01;
let high = low + spread;
let open = low + spread * ((rng.next_u64() % 100) as f64 * 0.01);
let close = low + spread * ((rng.next_u64() % 100) as f64 * 0.01);
let adj_volume = ((rng.next_u64() % 10_000_000) + 100) as f64;
let bar = match roll {
7..=8 => EodDailyBar {
key,
session_date,
open: -1.0,
high,
low,
close,
adj_volume,
},
9..=10 => EodDailyBar {
key,
session_date,
open,
high: low - 0.5,
low,
close,
adj_volume,
},
11..=12 => EodDailyBar {
key,
session_date,
open,
high,
low,
close,
adj_volume: -10.0,
},
13..=16 => {
let b = EodDailyBar {
key,
session_date,
open,
high,
low,
close,
adj_volume: 0.0,
};
last_valid = Some(b.clone());
b
}
_ => {
let b = EodDailyBar {
key,
session_date,
open,
high,
low,
close,
adj_volume,
};
last_valid = Some(b.clone());
if rng.next_u64() & 1 == 0 {
let factor = splits.cum_factor_after(&key, session_date);
let raw = unadjust_volume(adj_volume, factor);
let mismatch_roll = rng.next_u64() % 100;
let share_volume = if mismatch_roll == 0 {
raw * 1.15
} else {
let jitter_bp = (rng.next_u64() % 101) as f64 - 50.0; // -0.50%..+0.50%
raw * (1.0 + jitter_bp * 0.0001)
};
qm_volumes.push(QmRawVolume {
key,
session_date,
share_volume,
});
}
b
}
};
bars.push(bar);
}
let qm_rows_in = qm_volumes.len();
let build_start = Instant::now();
let built = build_bars_1d(bars, &splits, qm_volumes, 0.01)?;
let build_elapsed = build_start.elapsed();
let build_elapsed_secs = build_elapsed.as_secs_f64();
let build_elapsed_ms = build_elapsed_secs * 1_000.0;
let mut hash = 0u64;
for row in &built.rows {
hash = mix_u64(hash, row.key as u64);
hash = mix_u64(hash, row.session_date 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_u64(hash, row.volume.to_bits());
}
for sample in &built.mismatch_samples {
hash = mix_u64(hash, sample.key as u64);
hash = mix_u64(hash, sample.session_date as u64);
hash = mix_u64(hash, sample.volume.to_bits());
hash = mix_u64(hash, sample.share_volume.to_bits());
hash = mix_u64(hash, sample.rel.to_bits());
}
let checksum = black_box(hash);
let (rows_per_sec, ns_per_row) = compute_rates(rows, build_elapsed_secs);
Ok(BarsBenchReport {
rows,
key_count: BENCH_KEY_COUNT,
split_event_count,
qm_rows_in,
rows_out: built.stats.rows_out,
keys_out: built.stats.keys_out,
mismatch_samples_out: built.mismatch_samples.len(),
build_elapsed_ms,
rows_per_sec,
ns_per_row,
checksum,
stats: built.stats,
})
}
/// Summary metrics produced by [`run_fx_benchmark`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FxBenchReport {
pub rows: usize,
pub eod_rows_in: usize,
pub te_rows_in: usize,
pub rows_out: usize,
pub build_elapsed_ms: f64,
pub build_rows_per_sec: f64,
pub build_ns_per_row: f64,
pub lookups: usize,
pub lookup_hits: usize,
pub lookup_elapsed_ms: f64,
pub lookups_per_sec: f64,
pub ns_per_lookup: f64,
pub checksum: u64,
pub stats: Fx1dStats,
}
fn shuffle_slice<T>(items: &mut [T], rng: &mut SplitMix64) {
for i in (1..items.len()).rev() {
let j = (rng.next_u64() % (i as u64 + 1)) as usize;
items.swap(i, j);
}
}
#[inline]
fn next_weekday(date: i32) -> i32 {
let next = date + 1;
// 1970-01-01 was Thursday (0=Thu, 1=Fri, 2=Sat, 3=Sun, 4=Mon).
match next.rem_euclid(7) {
2 => next + 2,
3 => next + 1,
_ => next,
}
}
/// 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 te_target = rows / 5;
let eod_target = rows - te_target;
let mut eod: Vec<FxDailyBar> = Vec::with_capacity(eod_target);
let mut eod_valid_history: Vec<FxDailyBar> = Vec::with_capacity(eod_target);
let mut interior_gap_dates: Vec<i32> = Vec::new();
let mut cur_date = base_date;
let mut rate = 1.01_f64;
for _ in 0..eod_target {
let roll = rng.next_u64() % 1_000;
if roll < 10 {
if let Some(&prev) = eod_valid_history.last() {
eod.push(prev);
continue;
}
} else if roll < 15 {
if let Some(&prev) = eod_valid_history.last() {
let mut conflicting = prev;
conflicting.close = (conflicting.close + 0.002).min(conflicting.high);
if conflicting.close.to_bits() == prev.close.to_bits() {
conflicting.high += 0.002;
conflicting.close += 0.001;
}
eod.push(conflicting);
continue;
}
}
// Advance calendar date, skipping weekends and occasional interior gaps.
cur_date = next_weekday(cur_date);
if rng.next_u64() % 20 == 0 {
interior_gap_dates.push(cur_date);
cur_date = next_weekday(cur_date);
}
let step = ((rng.next_u64() % 201) as f64 - 100.0) * 0.0001;
rate = (rate + step).clamp(0.92, 1.60);
let half_spread = ((rng.next_u64() % 80) + 10) as f64 * 0.0001;
let low = (rate - half_spread).max(0.50);
let high = rate + half_spread;
let open = low + (high - low) * ((rng.next_u64() % 100) as f64 * 0.01);
let close = rate;
let bar = match roll {
15..=24 => FxDailyBar {
session_date: cur_date,
open: -1.0,
high,
low,
close,
},
25..=34 => FxDailyBar {
session_date: cur_date,
open,
high: low - 0.01,
low,
close,
},
_ => {
let b = FxDailyBar {
session_date: cur_date,
open,
high,
low,
close,
};
eod_valid_history.push(b);
b
}
};
eod.push(bar);
}
let last_eod_date = cur_date;
let mut te: Vec<FxDailyBar> = Vec::with_capacity(te_target);
let mut te_last_valid: Option<FxDailyBar> = None;
// ~60% of TE rows overlap EOD's recent window + interior gaps; ~40% extend past EOD's tail.
let te_overlap_target = (te_target * 3) / 5;
let te_tail_target = te_target - te_overlap_target;
let overlap_start = eod_valid_history.len().saturating_sub(te_overlap_target);
for idx in 0..te_overlap_target {
let roll = rng.next_u64() % 1_000;
if roll < 10 {
if let Some(prev) = te_last_valid {
te.push(prev);
continue;
}
} else if roll < 15 {
if let Some(mut prev) = te_last_valid {
prev.close = (prev.close + 0.002).min(prev.high);
if prev.close.to_bits() == te_last_valid.map_or(0, |b| b.close.to_bits()) {
prev.high += 0.002;
prev.close += 0.001;
}
te.push(prev);
continue;
}
}
// Fill some interior EOD gaps, otherwise overlap EOD dates.
let (session_date, base_bar) = if idx % 10 == 0 && !interior_gap_dates.is_empty() {
let gap_date = interior_gap_dates[(idx / 10) % interior_gap_dates.len()];
let ref_bar = eod_valid_history
.get(overlap_start + idx)
.copied()
.unwrap_or(FxDailyBar {
session_date: gap_date,
open: 1.35,
high: 1.36,
low: 1.34,
close: 1.35,
});
(gap_date, ref_bar)
} else if let Some(&ref_bar) = eod_valid_history.get(overlap_start + idx) {
(ref_bar.session_date, ref_bar)
} else {
(
last_eod_date + 1 + idx as i32,
FxDailyBar {
session_date: last_eod_date + 1 + idx as i32,
open: 1.35,
high: 1.36,
low: 1.34,
close: 1.35,
},
)
};
// ~5% intentional overlap mismatches (+2.5%), ~95% within 1% (±0.30%).
let factor = if rng.next_u64() % 20 == 0 {
1.025
} else {
let jitter_bp = (rng.next_u64() % 61) as f64 - 30.0;
1.0 + jitter_bp * 0.0001
};
let open = base_bar.open * factor;
let high = base_bar.high * factor;
let low = base_bar.low * factor;
let close = base_bar.close * factor;
let bar = match roll {
15..=24 => FxDailyBar {
session_date,
open: f64::NAN,
high,
low,
close,
},
25..=34 => FxDailyBar {
session_date,
open,
high: low - 0.01,
low,
close,
},
_ => {
let b = FxDailyBar {
session_date,
open,
high,
low,
close,
};
te_last_valid = Some(b);
b
}
};
te.push(bar);
}
let mut tail_date = last_eod_date;
let mut tail_rate = rate;
for _ in 0..te_tail_target {
tail_date = next_weekday(tail_date);
let step = ((rng.next_u64() % 201) as f64 - 100.0) * 0.0001;
tail_rate = (tail_rate + step).clamp(0.92, 1.60);
let half_spread = ((rng.next_u64() % 80) + 10) as f64 * 0.0001;
let low = (tail_rate - half_spread).max(0.50);
let high = tail_rate + half_spread;
let open = low + (high - low) * ((rng.next_u64() % 100) as f64 * 0.01);
te.push(FxDailyBar {
session_date: tail_date,
open,
high,
low,
close: tail_rate,
});
}
shuffle_slice(&mut eod, &mut rng);
shuffle_slice(&mut te, &mut rng);
let eod_rows_in = eod.len();
let te_rows_in = te.len();
let build_start = Instant::now();
let built = build_fx_1d(&eod, &te);
let build_elapsed_secs = build_start.elapsed().as_secs_f64();
let build_elapsed_ms = build_elapsed_secs * 1_000.0;
let (build_rows_per_sec, build_ns_per_row) = compute_rates(rows, build_elapsed_secs);
let mut rows_hash = 0u64;
for row in &built.rows {
rows_hash = mix_u64(rows_hash, row.session_date as u64);
rows_hash = mix_u64(rows_hash, row.open.to_bits());
rows_hash = mix_u64(rows_hash, row.high.to_bits());
rows_hash = mix_u64(rows_hash, row.low.to_bits());
rows_hash = mix_u64(rows_hash, row.close.to_bits());
rows_hash = mix_u64(rows_hash, row.source as u64);
}
let lookups = DEFAULT_FX_BENCH_LOOKUPS;
let (query_min, query_span) = match (built.rows.first(), built.rows.last()) {
(Some(first), Some(last)) => {
let min_q = first.session_date - 10;
let max_q = last.session_date + 10;
(min_q, (i64::from(max_q) - i64::from(min_q) + 1) as u64)
}
_ => (base_date, 100u64),
};
let mut lookup_hash = 0u64;
let mut lookup_hits = 0usize;
let lookup_start = Instant::now();
for _ in 0..lookups {
let query_date = query_min + (rng.next_u64() % query_span) as i32;
if let Some(row) = fx_rate_on_or_before(&built.rows, query_date, 4) {
lookup_hits += 1;
lookup_hash = mix_u64(lookup_hash, row.close.to_bits());
} else {
lookup_hash = mix_u64(lookup_hash, 0xDEAD_BEEF_u64);
}
}
let lookup_hash = black_box(lookup_hash);
let lookup_elapsed_secs = lookup_start.elapsed().as_secs_f64();
let lookup_elapsed_ms = lookup_elapsed_secs * 1_000.0;
let (lookups_per_sec, ns_per_lookup) = compute_rates(lookups, lookup_elapsed_secs);
let checksum = black_box(mix_u64(rows_hash, lookup_hash));
FxBenchReport {
rows,
eod_rows_in,
te_rows_in,
rows_out: built.stats.rows_out,
build_elapsed_ms,
build_rows_per_sec,
build_ns_per_row,
lookups,
lookup_hits,
lookup_elapsed_ms,
lookups_per_sec,
ns_per_lookup,
checksum,
stats: built.stats,
}
}
/// Summary metrics produced by [`run_shorts_benchmark`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ShortsBenchReport {
pub rows: usize,
pub key_count: usize,
pub rows_out: usize,
pub keys_out: usize,
pub build_elapsed_ms: f64,
pub rows_per_sec: f64,
pub ns_per_row: f64,
pub checksum: u64,
pub stats: ShortsStats,
}
fn semi_monthly_report_dates() -> Vec<i32> {
let mut dates = Vec::with_capacity(220);
let mut year = 2017_i32;
let mut month = 4_u32;
while year < 2026 || (year == 2026 && month <= 4) {
let mid = ymd_to_epoch_days(year, month, 15).expect("valid 15th");
let (next_y, next_m) = if month == 12 {
(year + 1, 1)
} else {
(year, month + 1)
};
let month_end = ymd_to_epoch_days(next_y, next_m, 1).expect("valid next month") - 1;
dates.push(mid);
dates.push(month_end);
year = next_y;
month = next_m;
}
dates
}
/// Runs the fixed-seed `build_shorts` benchmark for `rows` synthetic `ceoShorts` rows.
///
/// Generates `rows` deterministic reports across `12_500` `i32` `listing_id` keys on semi-monthly
/// (15th and month-end) dates spanning `2017-04-15..=2026-04-30` with small shares of negative/NaN
/// `shares_short`, non-finite optional fields, identical duplicates, and conflicting duplicates,
/// shuffles deterministically, times only [`build_shorts`], and returns throughput plus a
/// deterministic `u64` checksum.
pub fn run_shorts_benchmark(rows: usize) -> Result<ShortsBenchReport, ShortsError> {
if rows == 0 {
let built = build_shorts::<i32, _>(Vec::new())?;
return Ok(ShortsBenchReport {
rows: 0,
key_count: SHORTS_BENCH_KEY_COUNT,
rows_out: 0,
keys_out: 0,
build_elapsed_ms: 0.0,
rows_per_sec: 0.0,
ns_per_row: 0.0,
checksum: 0,
stats: built.stats,
});
}
let report_dates = semi_monthly_report_dates();
let mut rng = SplitMix64::new(SHORTS_BENCH_SEED);
let mut reports: Vec<CeoShortReport<i32>> = Vec::with_capacity(rows);
let mut last_valid: Option<CeoShortReport<i32>> = None;
for _ in 0..rows {
let roll = rng.next_u64() % 1_000;
if roll < 10 {
if let Some(prev) = last_valid.clone() {
reports.push(prev);
continue;
}
} else if roll < 15 {
if let Some(mut prev) = last_valid.clone() {
prev.shares_short += 100.0;
reports.push(prev);
continue;
}
}
let key = (rng.next_u64() % (SHORTS_BENCH_KEY_COUNT as u64)) as i32 + 1;
let report_date = report_dates[(rng.next_u64() as usize) % report_dates.len()];
let shares = ((rng.next_u64() % 5_000_000) + 100) as f64;
let net_raw = ((rng.next_u64() % 200_000) as f64) - 100_000.0;
let pct_raw = ((rng.next_u64() % 1_500) as f64) * 0.01;
let row = match roll {
15..=19 => CeoShortReport {
key,
report_date,
shares_short: -50.0,
net_change: Some(net_raw),
pct_float: Some(pct_raw),
},
20..=24 => CeoShortReport {
key,
report_date,
shares_short: f64::NAN,
net_change: Some(net_raw),
pct_float: Some(pct_raw),
},
25..=29 => {
let r = CeoShortReport {
key,
report_date,
shares_short: shares,
net_change: Some(f64::NAN),
pct_float: Some(pct_raw),
};
last_valid = Some(r.clone());
r
}
30..=34 => {
let r = CeoShortReport {
key,
report_date,
shares_short: shares,
net_change: Some(net_raw),
pct_float: Some(f64::INFINITY),
};
last_valid = Some(r.clone());
r
}
_ => {
let net_change = if rng.next_u64() % 10 == 0 {
None
} else {
Some(net_raw)
};
let pct_float = if rng.next_u64() % 4 == 0 {
None
} else {
Some(pct_raw)
};
let r = CeoShortReport {
key,
report_date,
shares_short: shares,
net_change,
pct_float,
};
last_valid = Some(r.clone());
r
}
};
reports.push(row);
}
shuffle_slice(&mut reports, &mut rng);
let build_start = Instant::now();
let built = build_shorts(reports)?;
let build_elapsed_secs = build_start.elapsed().as_secs_f64();
let build_elapsed_ms = build_elapsed_secs * 1_000.0;
let (rows_per_sec, ns_per_row) = compute_rates(rows, build_elapsed_secs);
let mut hash = 0u64;
for row in &built.rows {
hash = mix_u64(hash, row.key as u64);
hash = mix_u64(hash, row.report_date as u64);
hash = mix_u64(hash, row.known_at_date as u64);
hash = mix_u64(hash, row.known_at_utc_micros as u64);
hash = mix_u64(hash, row.shares_short.to_bits());
hash = mix_u64(hash, row.net_change.map_or(u64::MAX, f64::to_bits));
hash = mix_u64(hash, row.pct_float.map_or(u64::MAX, f64::to_bits));
let source_bits = row
.source
.bytes()
.fold(0u64, |acc, b| acc.wrapping_shl(8) | u64::from(b));
hash = mix_u64(hash, source_bits);
}
let checksum = black_box(hash);
Ok(ShortsBenchReport {
rows,
key_count: SHORTS_BENCH_KEY_COUNT,
rows_out: built.stats.rows_out,
keys_out: built.stats.keys_out,
build_elapsed_ms,
rows_per_sec,
ns_per_row,
checksum,
stats: built.stats,
})
}
/// Summary metrics produced by [`run_events_benchmark`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct EventsBenchReport {
pub rows: usize,
pub filings_in: usize,
pub earnings_in: usize,
pub key_count: usize,
pub rows_out: usize,
pub keys_out: usize,
pub build_elapsed_ms: f64,
pub rows_per_sec: f64,
pub ns_per_row: f64,
pub checksum: u64,
pub stats: EventsStats,
}
const BENCH_FORM_TYPES: &[&str] = &[
"8-K",
"News release",
"4",
"10-Q",
"10-K",
"10-K/A",
"144",
"40-F",
"Interim financial statements/report",
"Annual financial statements",
"MD&A",
"52-109",
"NI 43-101",
"45-106F1",
"424B5",
"8-K/A",
];
const BENCH_ANNOUNCE_TIMES: &[&str] = &["N/A", "AMC", "BTO"];
fn mix_bytes(mut hash: u64, bytes: &[u8]) -> u64 {
let mut chunks = bytes.chunks_exact(8);
for chunk in &mut chunks {
let mut buf = [0u8; 8];
buf.copy_from_slice(chunk);
hash = mix_u64(hash, u64::from_le_bytes(buf));
}
let rem = chunks.remainder();
if !rem.is_empty() {
let mut buf = [0u8; 8];
buf[..rem.len()].copy_from_slice(rem);
hash = mix_u64(hash, u64::from_le_bytes(buf));
}
mix_u64(hash, bytes.len() as u64)
}
/// Runs the fixed-seed `build_events` benchmark for `rows` total synthetic `qmFilings` (~98.5%)
/// and `qmEarnings` (~1.5%) rows across `20_000` `i32` `listing_id` keys.
///
/// Mirrors the empirical `30.52M` filings / `444.9k` earnings ratio with EST/EDT/pre-2008/
/// late-evening timestamps, all EDGAR and SEDAR+ form groups, linked + unlinked earnings, and
/// small shares of malformed/skipped/duplicate/conflicting rows. Shuffles both inputs
/// deterministically, times only [`build_events`], and returns throughput plus a deterministic
/// `u64` checksum.
pub fn run_events_benchmark(rows: usize) -> EventsBenchReport {
if rows == 0 {
let built = build_events::<i32, _, _>(Vec::new(), Vec::new());
return EventsBenchReport {
rows: 0,
filings_in: 0,
earnings_in: 0,
key_count: BENCH_KEY_COUNT,
rows_out: 0,
keys_out: 0,
build_elapsed_ms: 0.0,
rows_per_sec: 0.0,
ns_per_row: 0.0,
checksum: 0,
stats: built.stats,
};
}
let min_filing_date = ymd_to_epoch_days(2003, 1, 1).unwrap_or(12_053);
let max_filing_date = ymd_to_epoch_days(2026, 4, 30).unwrap_or(20_573);
let filing_span = (max_filing_date - min_filing_date + 1) as u64;
let min_earning_date = ymd_to_epoch_days(2008, 1, 1).unwrap_or(13_879);
let max_earning_date = ymd_to_epoch_days(2026, 4, 30).unwrap_or(20_573);
let earning_span = (max_earning_date - min_earning_date + 1) as u64;
let earnings_target = (rows * 15) / 1_000;
let filings_target = rows - earnings_target;
let mut rng = SplitMix64::new(EVENTS_BENCH_SEED);
let mut filings: Vec<QmFiling<i32>> = Vec::with_capacity(filings_target);
let mut link_pool: Vec<(i32, i32)> = Vec::with_capacity(earnings_target.min(16_384));
let mut last_valid_filing: Option<QmFiling<i32>> = None;
for idx in 0..filings_target {
let roll = rng.next_u64() % 1_000;
if roll < 5 {
if let Some(prev) = last_valid_filing.clone() {
filings.push(prev);
continue;
}
}
let key = (rng.next_u64() % (BENCH_KEY_COUNT as u64)) as i32 + 1;
let epoch_day = min_filing_date + (rng.next_u64() % filing_span) as i32;
let (y, m, d) = epoch_days_to_ymd(epoch_day);
let form_idx = (rng.next_u64() as usize) % BENCH_FORM_TYPES.len();
let form_type = BENCH_FORM_TYPES[form_idx].to_string();
let filing_id = if rng.next_u64() % 10 == 0 {
None
} else {
Some(format!("F{idx:08}"))
};
let url = if rng.next_u64() % 4 == 0 {
None
} else {
Some(format!("https://filings.example/{key}/{idx}"))
};
let timefiled = match roll {
5..=7 => "bad-timestamp".to_string(),
8..=10 => format!("{y:04}-{m:02}-{d:02}T12:00:00 PST"),
11..=13 => format!("{y:04}-02-30T12:00:00 EST"),
14..=15 => format!("{y:04}-{m:02}-{d:02}T25:00:00 EST"),
_ => {
// Mix morning, midday, and late-evening ET (crossing into next UTC day).
let hour = if roll < 60 {
21 + (rng.next_u64() % 3) as u32
} else {
6 + (rng.next_u64() % 13) as u32
};
let minute = (rng.next_u64() % 60) as u32;
let second = (rng.next_u64() % 60) as u32;
let zone = if (4..=10).contains(&m) { "EDT" } else { "EST" };
let ts = format!("{y:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02} {zone}");
if matches!(form_idx, 0 | 1 | 15) && link_pool.len() < 16_384 {
link_pool.push((key, epoch_day));
}
ts
}
};
let row = QmFiling {
key,
timefiled,
form_type,
filing_id,
url,
};
if roll >= 16 {
last_valid_filing = Some(row.clone());
}
filings.push(row);
}
let mut earnings: Vec<QmEarning<i32>> = Vec::with_capacity(earnings_target);
let mut last_valid_earning: Option<QmEarning<i32>> = None;
for _ in 0..earnings_target {
let roll = rng.next_u64() % 1_000;
if roll < 15 {
if let Some(prev) = last_valid_earning.clone() {
earnings.push(prev);
continue;
}
} else if roll < 25 {
if let Some(mut prev) = last_valid_earning.clone() {
prev.actual_eps = Some(prev.actual_eps.unwrap_or(0.0) + 0.10);
earnings.push(prev);
continue;
}
}
let (key, report_date) = if roll < 30 && !link_pool.is_empty() {
// Out-of-range unlinked date (< 2008-01-01)
let k = (rng.next_u64() % (BENCH_KEY_COUNT as u64)) as i32 + 1;
let d = ymd_to_epoch_days(2005, 6, 15).unwrap_or(12_949);
(k, d)
} else if roll < 450 && !link_pool.is_empty() {
let pick = (rng.next_u64() as usize) % link_pool.len();
link_pool[pick]
} else {
let k = (rng.next_u64() % (BENCH_KEY_COUNT as u64)) as i32 + 1;
let d = min_earning_date + (rng.next_u64() % earning_span) as i32;
(k, d)
};
let announce_time =
BENCH_ANNOUNCE_TIMES[(rng.next_u64() as usize) % BENCH_ANNOUNCE_TIMES.len()]
.to_string();
let actual_eps = if roll % 50 == 0 {
Some(f64::NAN)
} else {
Some((((rng.next_u64() % 1_000) as f64) - 200.0) * 0.01)
};
let revenue = Some(((rng.next_u64() % 5_000_000) + 10_000) as f64);
let row = QmEarning {
key,
report_date,
announce_time,
fiscal_period_end: Some(report_date - 35),
actual_eps,
revenue,
};
if roll >= 30 {
last_valid_earning = Some(row.clone());
}
earnings.push(row);
}
shuffle_slice(&mut filings, &mut rng);
shuffle_slice(&mut earnings, &mut rng);
let filings_in = filings.len();
let earnings_in = earnings.len();
let build_start = Instant::now();
let built = build_events(filings, earnings);
let build_elapsed_secs = build_start.elapsed().as_secs_f64();
let build_elapsed_ms = build_elapsed_secs * 1_000.0;
let (rows_per_sec, ns_per_row) = compute_rates(rows, build_elapsed_secs);
let mut hash = 0u64;
for row in &built.rows {
hash = mix_u64(hash, row.key as u64);
hash = mix_u64(hash, row.ts_micros as u64);
hash = mix_u64(hash, row.known_at_micros as u64);
hash = mix_bytes(hash, row.known_at_source.as_bytes());
hash = mix_bytes(hash, row.kind.as_bytes());
hash = mix_bytes(hash, row.subtype.as_bytes());
hash = mix_bytes(hash, row.payload_json.as_bytes());
}
let checksum = black_box(hash);
EventsBenchReport {
rows,
filings_in,
earnings_in,
key_count: BENCH_KEY_COUNT,
rows_out: built.stats.rows_out,
keys_out: built.stats.keys_out,
build_elapsed_ms,
rows_per_sec,
ns_per_row,
checksum,
stats: built.stats,
}
}
#[cfg(test)]
mod tests {
use super::*;
const EXPECTED_KEYS_WITH_SPLITS: usize = 12_153;
const EXPECTED_EVENT_COUNT: usize = 18_999;
#[test]
fn benchmark_small_run_is_deterministic() {
let a = run_split_benchmark(1_000).unwrap();
let b = run_split_benchmark(1_000).unwrap();
assert_eq!(a.rows, 1_000);
assert_eq!(a.key_count, BENCH_KEY_COUNT);
assert_eq!(a.table_keys_with_splits, EXPECTED_KEYS_WITH_SPLITS);
assert_eq!(a.table_event_count, EXPECTED_EVENT_COUNT);
assert_eq!(a.table_keys_with_splits, b.table_keys_with_splits);
assert_eq!(a.table_event_count, b.table_event_count);
assert_eq!(a.checksum.to_bits(), b.checksum.to_bits());
assert!(a.checksum.is_finite() && a.checksum > 0.0);
assert!(a.rows_per_sec.is_finite() && a.rows_per_sec >= 0.0);
assert!(a.ns_per_row.is_finite() && a.ns_per_row >= 0.0);
}
#[test]
fn compute_rates_uses_fixed_duration() {
let (rows_per_sec, ns_per_row) = compute_rates(1_000, 0.5);
assert_eq!(rows_per_sec, 2_000.0);
assert_eq!(ns_per_row, 500_000.0);
assert_eq!(compute_rates(0, 0.5), (0.0, 0.0));
assert_eq!(compute_rates(1_000, 0.0), (0.0, 0.0));
assert_eq!(compute_rates(1_000, -1.0), (0.0, 0.0));
}
#[test]
fn benchmark_zero_rows_handles_cleanly() {
let report = run_split_benchmark(0).unwrap();
assert_eq!(report.rows, 0);
assert_eq!(report.key_count, BENCH_KEY_COUNT);
assert_eq!(report.table_keys_with_splits, EXPECTED_KEYS_WITH_SPLITS);
assert_eq!(report.table_event_count, EXPECTED_EVENT_COUNT);
assert_eq!(report.checksum, 0.0);
assert_eq!(report.rows_per_sec, 0.0);
assert_eq!(report.ns_per_row, 0.0);
}
#[test]
fn adj_benchmark_small_run_is_deterministic() {
let a = run_adj_benchmark(5_000).unwrap();
let b = run_adj_benchmark(5_000).unwrap();
assert_eq!(a.events, 5_000);
assert_eq!(a.split_events_in + a.dividend_events_in, 5_000);
assert_eq!(a.key_count, BENCH_KEY_COUNT);
assert_eq!(a.rows_out, b.rows_out);
assert_eq!(a.keys_out, b.keys_out);
assert_eq!(a.stats, b.stats);
assert_eq!(a.checksum.to_bits(), b.checksum.to_bits());
assert!(a.checksum.is_finite() && a.checksum > 0.0);
assert!(a.events_per_sec.is_finite() && a.events_per_sec >= 0.0);
assert!(a.ns_per_event.is_finite() && a.ns_per_event >= 0.0);
assert!(a.stats.dividends_missing_prev_close > 0);
assert!(a.stats.dividends_currency_mismatch > 0);
assert!(a.stats.dividends_not_below_prev_close > 0);
}
#[test]
fn adj_benchmark_zero_events_handles_cleanly() {
let report = run_adj_benchmark(0).unwrap();
assert_eq!(report.events, 0);
assert_eq!(report.split_events_in, 0);
assert_eq!(report.dividend_events_in, 0);
assert_eq!(report.rows_out, 0);
assert_eq!(report.keys_out, 0);
assert_eq!(report.stats, AdjBuildStats::default());
assert_eq!(report.checksum, 0.0);
assert_eq!(report.events_per_sec, 0.0);
assert_eq!(report.ns_per_event, 0.0);
}
#[test]
fn corporate_actions_benchmark_small_run_is_deterministic() {
let a = run_corporate_actions_benchmark(5_000).unwrap();
let b = run_corporate_actions_benchmark(5_000).unwrap();
assert_eq!(a.events, 5_000);
assert_eq!(a.splits_in + a.dividends_in + a.delistings_in, 5_000);
assert_eq!(a.key_count, BENCH_KEY_COUNT);
assert_eq!(a.rows_out, b.rows_out);
assert_eq!(a.keys_out, b.keys_out);
assert_eq!(a.stats, b.stats);
assert_eq!(a.checksum, b.checksum);
assert_ne!(a.checksum, 0);
assert!(a.events_per_sec.is_finite() && a.events_per_sec >= 0.0);
assert!(a.ns_per_event.is_finite() && a.ns_per_event >= 0.0);
assert!(a.stats.splits_out > 0);
assert!(a.stats.dividends_out > 0);
assert!(a.stats.otc_delist_transfers_out > 0);
assert!(a.stats.delistings_out > 0);
assert!(a.stats.delist_without_outcome > 0);
assert!(a.stats.declared_after_ex_date > 0);
}
#[test]
fn corporate_actions_benchmark_zero_events_handles_cleanly() {
let report = run_corporate_actions_benchmark(0).unwrap();
assert_eq!(report.events, 0);
assert_eq!(report.splits_in, 0);
assert_eq!(report.dividends_in, 0);
assert_eq!(report.delistings_in, 0);
assert_eq!(report.rows_out, 0);
assert_eq!(report.keys_out, 0);
assert_eq!(report.stats, CorporateActionsStats::default());
assert_eq!(report.checksum, 0);
assert_eq!(report.events_per_sec, 0.0);
assert_eq!(report.ns_per_event, 0.0);
}
#[test]
fn bars_benchmark_small_run_is_deterministic() {
let a = run_bars_benchmark(20_000).unwrap();
let b = run_bars_benchmark(20_000).unwrap();
assert_eq!(a.rows, 20_000);
assert_eq!(a.stats.bars_in, 20_000);
assert_eq!(a.key_count, BENCH_KEY_COUNT);
assert_eq!(a.rows_out, b.rows_out);
assert_eq!(a.keys_out, b.keys_out);
assert_eq!(a.mismatch_samples_out, b.mismatch_samples_out);
assert_eq!(a.stats, b.stats);
assert_eq!(a.checksum, b.checksum);
assert_ne!(a.checksum, 0);
assert!(a.rows_per_sec.is_finite() && a.rows_per_sec >= 0.0);
assert!(a.ns_per_row.is_finite() && a.ns_per_row >= 0.0);
assert!(a.stats.dropped_invalid_ohlc > 0);
assert!(a.stats.dropped_inconsistent_ohlc > 0);
assert!(a.stats.dropped_invalid_volume > 0);
assert!(a.stats.duplicate_collapsed > 0);
assert!(a.stats.duplicate_conflict_dropped > 0);
assert!(a.stats.volume_within_tolerance > 0);
assert!(a.stats.volume_mismatched > 0);
assert!(a.stats.volume_unchecked > 0);
}
#[test]
fn bars_benchmark_zero_rows_handles_cleanly() {
let report = run_bars_benchmark(0).unwrap();
assert_eq!(report.rows, 0);
assert_eq!(report.qm_rows_in, 0);
assert_eq!(report.rows_out, 0);
assert_eq!(report.keys_out, 0);
assert_eq!(report.mismatch_samples_out, 0);
assert_eq!(report.stats, Bars1dStats::default());
assert_eq!(report.checksum, 0);
assert_eq!(report.rows_per_sec, 0.0);
assert_eq!(report.ns_per_row, 0.0);
}
#[test]
fn fx_benchmark_small_run_is_deterministic() {
let a = run_fx_benchmark(2_000);
let b = run_fx_benchmark(2_000);
assert_eq!(a.rows, 2_000);
assert_eq!(a.eod_rows_in + a.te_rows_in, 2_000);
assert_eq!(a.rows_out, b.rows_out);
assert_eq!(a.lookups, DEFAULT_FX_BENCH_LOOKUPS);
assert_eq!(a.lookup_hits, b.lookup_hits);
assert!(a.lookup_hits > 0 && a.lookup_hits < a.lookups);
assert_eq!(a.stats, b.stats);
assert_eq!(a.checksum, b.checksum);
assert_ne!(a.checksum, 0);
assert!(a.build_rows_per_sec.is_finite() && a.build_rows_per_sec >= 0.0);
assert!(a.build_ns_per_row.is_finite() && a.build_ns_per_row >= 0.0);
assert!(a.lookups_per_sec.is_finite() && a.lookups_per_sec >= 0.0);
assert!(a.ns_per_lookup.is_finite() && a.ns_per_lookup >= 0.0);
assert!(a.stats.eod.dropped_invalid_ohlc > 0);
assert!(a.stats.eod.dropped_inconsistent_ohlc > 0);
assert!(a.stats.eod.duplicate_collapsed > 0);
assert!(a.stats.eod.duplicate_conflict_dropped > 0);
assert!(a.stats.te_superseded_by_eod > 0);
assert!(a.stats.overlap_within_tolerance > 0);
assert!(a.stats.overlap_mismatched > 0);
assert!(a.stats.te_rows_out > 0);
}
#[test]
fn fx_benchmark_zero_rows_handles_cleanly() {
let report = run_fx_benchmark(0);
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.lookups, 0);
assert_eq!(report.lookup_hits, 0);
assert_eq!(report.stats, Fx1dStats::default());
assert_eq!(report.checksum, 0);
assert_eq!(report.build_rows_per_sec, 0.0);
assert_eq!(report.build_ns_per_row, 0.0);
assert_eq!(report.lookups_per_sec, 0.0);
assert_eq!(report.ns_per_lookup, 0.0);
}
#[test]
fn next_weekday_skips_saturdays_and_sundays() {
let thu = ymd_to_epoch_days(2025, 1, 2).unwrap();
let fri = ymd_to_epoch_days(2025, 1, 3).unwrap();
let sat = ymd_to_epoch_days(2025, 1, 4).unwrap();
let sun = ymd_to_epoch_days(2025, 1, 5).unwrap();
let mon = ymd_to_epoch_days(2025, 1, 6).unwrap();
assert_eq!(next_weekday(thu), fri);
assert_eq!(next_weekday(fri), mon);
assert_eq!(next_weekday(sat), mon);
assert_eq!(next_weekday(sun), mon);
}
#[test]
fn shorts_benchmark_small_run_is_deterministic() {
let a = run_shorts_benchmark(5_000).unwrap();
let b = run_shorts_benchmark(5_000).unwrap();
assert_eq!(a.rows, 5_000);
assert_eq!(a.stats.rows_in, 5_000);
assert_eq!(a.key_count, SHORTS_BENCH_KEY_COUNT);
assert_eq!(a.rows_out, b.rows_out);
assert_eq!(a.keys_out, b.keys_out);
assert_eq!(a.stats, b.stats);
assert_eq!(a.checksum, b.checksum);
assert_ne!(a.checksum, 0);
assert!(a.rows_per_sec.is_finite() && a.rows_per_sec >= 0.0);
assert!(a.ns_per_row.is_finite() && a.ns_per_row >= 0.0);
assert!(a.stats.dropped_invalid_shares_short > 0);
assert!(a.stats.nulled_invalid_net_change > 0);
assert!(a.stats.nulled_invalid_pct_float > 0);
assert!(a.stats.duplicate_collapsed > 0);
assert!(a.stats.duplicate_conflict_dropped > 0);
}
#[test]
fn shorts_benchmark_zero_rows_handles_cleanly() {
let report = run_shorts_benchmark(0).unwrap();
assert_eq!(report.rows, 0);
assert_eq!(report.key_count, SHORTS_BENCH_KEY_COUNT);
assert_eq!(report.rows_out, 0);
assert_eq!(report.keys_out, 0);
assert_eq!(report.stats, ShortsStats::default());
assert_eq!(report.checksum, 0);
assert_eq!(report.rows_per_sec, 0.0);
assert_eq!(report.ns_per_row, 0.0);
}
#[test]
fn events_benchmark_small_run_is_deterministic() {
let a = run_events_benchmark(20_000);
let b = run_events_benchmark(20_000);
assert_eq!(a.rows, 20_000);
assert_eq!(a.filings_in + a.earnings_in, 20_000);
assert_eq!(a.stats.filings_in, a.filings_in);
assert_eq!(a.stats.earnings_in, a.earnings_in);
assert_eq!(a.key_count, BENCH_KEY_COUNT);
assert_eq!(a.rows_out, b.rows_out);
assert_eq!(a.keys_out, b.keys_out);
assert_eq!(a.stats, b.stats);
assert_eq!(a.checksum, b.checksum);
assert_ne!(a.checksum, 0);
assert!(a.rows_per_sec.is_finite() && a.rows_per_sec >= 0.0);
assert!(a.ns_per_row.is_finite() && a.ns_per_row >= 0.0);
assert!(a.stats.filings_out > 0);
assert!(a.stats.filings_skipped_malformed_timestamp > 0);
assert!(a.stats.filings_skipped_unknown_zone > 0);
assert!(a.stats.filings_skipped_invalid_date_time > 0);
assert!(a.stats.filings_duplicate_collapsed > 0);
assert!(a.stats.earnings_linked_to_filing > 0);
assert!(a.stats.earnings_lagged_1605 > 0);
}
#[test]
fn events_benchmark_zero_rows_handles_cleanly() {
let report = run_events_benchmark(0);
assert_eq!(report.rows, 0);
assert_eq!(report.filings_in, 0);
assert_eq!(report.earnings_in, 0);
assert_eq!(report.key_count, BENCH_KEY_COUNT);
assert_eq!(report.rows_out, 0);
assert_eq!(report.keys_out, 0);
assert_eq!(report.stats, EventsStats::default());
assert_eq!(report.checksum, 0);
assert_eq!(report.rows_per_sec, 0.0);
assert_eq!(report.ns_per_row, 0.0);
}
}