T-76: M1.2f — tools/curate-etl: pure shorts builder (ceoShorts → +4 Canadian business-day 17:00 ET known_at) with local benchmark (no new crates)
This commit is contained in:
parent
a3cc5fd007
commit
9e8cc1d3c7
7 changed files with 1829 additions and 6 deletions
|
|
@ -1,6 +1,6 @@
|
|||
# `curate-etl`
|
||||
|
||||
Dedicated zero-dependency Rust crate for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, the `M1.2c` pure `corporate_actions` event-log builder, the `M1.2d` pure `bars_1d` daily bar builder + `qmPrices.sharevolume` cross-check, and the `M1.2e` pure `fx_1d` USD/CAD builder + carry-forward lookup.
|
||||
Dedicated zero-dependency Rust crate for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, the `M1.2c` pure `corporate_actions` event-log builder, the `M1.2d` pure `bars_1d` daily bar builder + `qmPrices.sharevolume` cross-check, the `M1.2e` pure `fx_1d` USD/CAD builder + carry-forward lookup, and the `M1.2f` pure `shorts` (`ceoShorts`) point-in-time builder + Canadian TSX business-day / `America/Toronto` DST calendar.
|
||||
|
||||
## Scope & Sign Conventions
|
||||
|
||||
|
|
@ -94,6 +94,43 @@ Rules:
|
|||
|
||||
Deferred out of `src/fx.rs`: `ts`/`known_at` timestamp derivation (later writer task), `CADUSD.FOREX` inversion, `fx_1m` intraday FX, and wiring FX into `src/adj.rs` cross-currency dividends.
|
||||
|
||||
## `shorts` Builder (`M1.2f`)
|
||||
|
||||
`build_shorts` (`src/shorts.rs`) turns raw `ceoShorts` semi-monthly short-interest report rows (`CeoShortReport<K>`) into sorted, unique per-`(key, report_date)` point-in-time `ShortRow<K>` rows matching `shorts/part.parquet` in `design/DATA-CONTRACTS.md` (`listing_id, report_date, known_at, shares_short, net_change, pct_float, source`).
|
||||
|
||||
Rules:
|
||||
1. **Canadian TSX business-day calendar (`2008-01-01..=2030-12-31`):**
|
||||
- `is_canadian_business_day(epoch_day)` and `add_canadian_business_days(epoch_day, n)` cover `MIN_SUPPORTED_YEAR = 2008` through `MAX_SUPPORTED_YEAR = 2030` (`MIN_SUPPORTED_DATE = 13_879` ..= `MAX_SUPPORTED_DATE = 22_279`), strictly covering the `2017-01-01..=2027-12-31` dataset window plus year-end `+4` business-day rollovers. Dates outside `[MIN_SUPPORTED_DATE, MAX_SUPPORTED_DATE]` (or stepping past `MAX_SUPPORTED_DATE`) return `ShortsError::DateOutOfRange` rather than guessing or panicking.
|
||||
- Non-business days: Saturdays, Sundays, and the 9 TSX market holidays:
|
||||
1. **New Year's Day** (Jan 1; Sat → Mon Jan 3, Sun → Mon Jan 2)
|
||||
2. **Family Day** (3rd Monday of February, TSX holiday since 2008)
|
||||
3. **Good Friday** (computed Gregorian Easter Sunday − 2 days)
|
||||
4. **Victoria Day** (Monday strictly before May 25)
|
||||
5. **Canada Day** (Jul 1; Sat → Mon Jul 3, Sun → Mon Jul 2)
|
||||
6. **Civic Holiday** (1st Monday of August)
|
||||
7. **Labour Day** (1st Monday of September)
|
||||
8. **Thanksgiving** (2nd Monday of October)
|
||||
9. **Christmas Day & Boxing Day** (Mon–Thu → Dec 25/26; Fri → Dec 25 & Mon Dec 28; Sat → Mon Dec 27 & Tue Dec 28; Sun → Mon Dec 26 & Tue Dec 27)
|
||||
- Federal holidays where TSX remains open (National Day for Truth and Reconciliation on Sept 30 and Remembrance Day on Nov 11) are treated as normal TSX business days.
|
||||
- When `report_date` itself falls on a non-business day (e.g. a Saturday month-end), `add_canadian_business_days(report_date, 4)` counts strictly forward so `known_at_date` is the 4th TSX business day strictly after `report_date` (`known_at_date > report_date` always holds).
|
||||
2. **`America/Toronto` ET → UTC DST conversion (`et_to_utc_micros`):**
|
||||
- Applies North American post-2007 DST rules (2nd Sunday of March 02:00 → 1st Sunday of November 02:00 = EDT `UTC-4`, otherwise EST `UTC-5`).
|
||||
- `known_at_utc_micros` is `17:00:00 America/Toronto` on `known_at_date` (`21:00:00 UTC` in EDT, `22:00:00 UTC` in EST).
|
||||
- Rejects out-of-range dates (`DateOutOfRange`), invalid wall-clock components (`InvalidLocalTime`), spring-forward nonexistent times `02:00..03:00` (`NonexistentLocalTime`), and fall-back ambiguous times `01:00..02:00` (`AmbiguousLocalTime`).
|
||||
- Exposed publicly alongside `epoch_days_to_ymd` so the upcoming `events` builder (`16:05 ET` lag) can reuse it directly.
|
||||
3. **Bad-row resilience, sanitization, and deduplication:**
|
||||
- Every input row's `report_date + 4` business days is validated first so out-of-range dates fail deterministically with `ShortsError::DateOutOfRange` regardless of row order or bad numeric fields.
|
||||
- Non-finite or negative `shares_short` rows are dropped and counted in `dropped_invalid_shares_short` (without incrementing optional-field null counters); `-0.0` is normalized to `0.0`.
|
||||
- Non-finite `net_change` and `pct_float` values are sanitized to `None` and counted in `nulled_invalid_net_change` and `nulled_invalid_pct_float`; `-0.0` is normalized to `0.0`.
|
||||
- Bitwise-identical duplicates on `(key, report_date)` collapse (`duplicate_collapsed += n - 1`); conflicting duplicate groups drop entirely (`duplicate_conflict_dropped += n`).
|
||||
- Every emitted row carries `source = "ceo_shorts"`, `known_at_date > report_date`, and is strictly sorted by `(key, report_date)`.
|
||||
4. **Determinism & accounting invariants:**
|
||||
- Any input permutation yields bitwise-identical `rows` and `stats`.
|
||||
- `rows_in == rows_out + dropped_invalid_shares_short + duplicate_collapsed + duplicate_conflict_dropped`.
|
||||
5. **CIRO publication-lag note:** The `+4` Canadian business-day `17:00 ET` rule is the locked contract proxy from `design/DATA-CONTRACTS.md` (not an observed CIRO scrape timestamp). Downstream signal studies should still run `+1` business-day lag stress tests around holidays and month-end boundaries.
|
||||
|
||||
Deferred out of `src/shorts.rs`: MongoDB `ceoShorts` BSON streaming, `provider_mapping` `listing_id` resolution, Zstd Parquet writing, `rayon` sharding, and deriving `pct_float` from shares outstanding (values are passed through as supplied by the caller).
|
||||
|
||||
## Local Benchmarks
|
||||
|
||||
### `bench-split`
|
||||
|
|
@ -166,7 +203,21 @@ Command: `cargo run --release -p curate-etl --offline -- bench-fx`
|
|||
- Lookup: `lookups=1000000`, `hits=999224`, `elapsed=25.68 ms`, `throughput=38946650 lookups/s`, `latency=25.68 ns/lookup`, `checksum=0x21e746bd53f3e7ff` (identical across back-to-back runs)
|
||||
- Stats: `eod_invalid=164`, `eod_inconsistent=170`, `eod_dup_collapsed=165`, `eod_dup_conflict=165`, `te_invalid=21`, `te_inconsistent=23`, `te_dup_collapsed=21`, `te_dup_conflict=34`, `te_superseded=2065`, `overlap_checked=2065`, `within_tol=1954`, `mismatched=111`, `max_overlap_rel=0.025000`
|
||||
|
||||
## Deferred Follow-Ups (`M1.2f+` / `M2`)
|
||||
### `bench-shorts`
|
||||
|
||||
Fixed-seed (`std`-only SplitMix64) benchmark over `700,000` synthetic `ceoShorts` report rows across `12,500` `i32` `listing_id` keys on semi-monthly (15th and month-end) dates spanning `2017-04-15..=2026-04-30` with injected negative/NaN `shares_short`, non-finite optional fields, identical duplicates, and conflicting duplicates, timing only `build_shorts`:
|
||||
|
||||
```bash
|
||||
cargo run --release -p curate-etl --offline -- bench-shorts [rows]
|
||||
```
|
||||
|
||||
Command: `cargo run --release -p curate-etl --offline -- bench-shorts`
|
||||
|
||||
- Input: `rows=700000`, `keys=12500`
|
||||
- Build: `rows_out=528426`, `keys_out=12500`, `elapsed=49.76 ms`, `throughput=14068555 rows/s`, `latency=71.08 ns/row`, `checksum=0x1a99126eaa1a519b` (identical across back-to-back runs)
|
||||
- Stats: `invalid_shares=6915`, `nulled_net_change=3673`, `nulled_pct_float=3500`, `dup_collapsed=5352`, `dup_conflict=159307`
|
||||
|
||||
## Deferred Follow-Ups (`M1.2g+` / `M2`)
|
||||
|
||||
This crate currently uses `std` only so it builds strictly offline. Follow-up tasks (IO wiring and crates.io dependencies) will add:
|
||||
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ use crate::corporate_actions::{
|
|||
DividendActionEvent, SplitActionEvent,
|
||||
};
|
||||
use crate::fx::{build_fx_1d, fx_rate_on_or_before, Fx1dStats, FxDailyBar};
|
||||
use crate::shorts::{build_shorts, CeoShortReport, ShortsError, ShortsStats};
|
||||
use crate::split::{unadjust_volume, ymd_to_epoch_days, SplitError, SplitEvent, SplitTable};
|
||||
|
||||
pub const DEFAULT_BENCH_ROWS: usize = 10_000_000;
|
||||
|
|
@ -18,14 +19,17 @@ 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 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 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).
|
||||
|
|
@ -928,6 +932,189 @@ pub fn run_fx_benchmark(rows: usize) -> FxBenchReport {
|
|||
}
|
||||
}
|
||||
|
||||
/// 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,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
|
@ -1145,4 +1332,39 @@ mod tests {
|
|||
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);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@
|
|||
|
||||
use crate::bench::{
|
||||
DEFAULT_ADJ_BENCH_EVENTS, DEFAULT_BARS_BENCH_ROWS, DEFAULT_BENCH_ROWS,
|
||||
DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS, DEFAULT_FX_BENCH_ROWS,
|
||||
DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS, DEFAULT_FX_BENCH_ROWS, DEFAULT_SHORTS_BENCH_ROWS,
|
||||
};
|
||||
|
||||
/// Parsed CLI command to execute.
|
||||
|
|
@ -18,6 +18,7 @@ pub enum CliAction {
|
|||
BenchCorporateActions(usize),
|
||||
BenchBars(usize),
|
||||
BenchFx(usize),
|
||||
BenchShorts(usize),
|
||||
}
|
||||
|
||||
/// Formats full help text including binary name and version.
|
||||
|
|
@ -32,7 +33,8 @@ pub fn format_usage(name: &str, version: &str) -> String {
|
|||
{name} bench-adj [events] Run fixed-seed adj_factors build benchmark (default: {DEFAULT_ADJ_BENCH_EVENTS})\n\
|
||||
{name} bench-corporate-actions [events] Run fixed-seed corporate_actions build benchmark (default: {DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS})\n\
|
||||
{name} bench-bars [rows] Run fixed-seed bars_1d build + cross-check benchmark (default: {DEFAULT_BARS_BENCH_ROWS})\n\
|
||||
{name} bench-fx [rows] Run fixed-seed fx_1d build + lookup benchmark (default: {DEFAULT_FX_BENCH_ROWS})"
|
||||
{name} bench-fx [rows] Run fixed-seed fx_1d build + lookup benchmark (default: {DEFAULT_FX_BENCH_ROWS})\n\
|
||||
{name} bench-shorts [rows] Run fixed-seed shorts build benchmark (default: {DEFAULT_SHORTS_BENCH_ROWS})"
|
||||
)
|
||||
}
|
||||
|
||||
|
|
@ -46,7 +48,8 @@ pub fn format_usage_stderr(name: &str) -> String {
|
|||
{name} bench-adj [events]\n\
|
||||
{name} bench-corporate-actions [events]\n\
|
||||
{name} bench-bars [rows]\n\
|
||||
{name} bench-fx [rows]"
|
||||
{name} bench-fx [rows]\n\
|
||||
{name} bench-shorts [rows]"
|
||||
)
|
||||
}
|
||||
|
||||
|
|
@ -103,6 +106,14 @@ pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
|||
)),
|
||||
},
|
||||
["bench-fx", _, ..] => Err("too many arguments for bench-fx".to_string()),
|
||||
["bench-shorts"] => Ok(CliAction::BenchShorts(DEFAULT_SHORTS_BENCH_ROWS)),
|
||||
["bench-shorts", raw] => match raw.parse::<usize>() {
|
||||
Ok(n) if n > 0 => Ok(CliAction::BenchShorts(n)),
|
||||
_ => Err(format!(
|
||||
"invalid row count '{raw}' (expected a positive integer)"
|
||||
)),
|
||||
},
|
||||
["bench-shorts", _, ..] => Err("too many arguments for bench-shorts".to_string()),
|
||||
[other, ..] => Err(format!("unknown argument '{other}'")),
|
||||
}
|
||||
}
|
||||
|
|
@ -220,6 +231,22 @@ mod tests {
|
|||
assert!(parse_args(&to_args(&["bench-fx", "10", "20"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_and_validates_bench_shorts_args() {
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&["bench-shorts"])),
|
||||
Ok(CliAction::BenchShorts(DEFAULT_SHORTS_BENCH_ROWS))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&["bench-shorts", "50000"])),
|
||||
Ok(CliAction::BenchShorts(50_000))
|
||||
);
|
||||
assert!(parse_args(&to_args(&["bench-shorts", "0"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-shorts", "-5"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-shorts", "abc"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-shorts", "10", "20"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usage_strings_mention_all_benchmarks() {
|
||||
let full = format_usage("curate-etl", "0.1.0");
|
||||
|
|
@ -228,6 +255,7 @@ mod tests {
|
|||
assert!(full.contains("bench-corporate-actions"));
|
||||
assert!(full.contains("bench-bars"));
|
||||
assert!(full.contains("bench-fx"));
|
||||
assert!(full.contains("bench-shorts"));
|
||||
|
||||
let short = format_usage_stderr("curate-etl");
|
||||
assert!(short.contains("bench-split"));
|
||||
|
|
@ -235,5 +263,6 @@ mod tests {
|
|||
assert!(short.contains("bench-corporate-actions"));
|
||||
assert!(short.contains("bench-bars"));
|
||||
assert!(short.contains("bench-fx"));
|
||||
assert!(short.contains("bench-shorts"));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ pub mod bench;
|
|||
pub mod cli;
|
||||
pub mod corporate_actions;
|
||||
pub mod fx;
|
||||
pub mod shorts;
|
||||
pub mod split;
|
||||
|
||||
pub use adj::{
|
||||
|
|
@ -25,6 +26,13 @@ pub use fx::{
|
|||
build_fx_1d, fx_rate_on_or_before, Fx1dBuild, Fx1dRow, Fx1dStats, FxDailyBar, FxSource,
|
||||
FxSourceStats, FX_OVERLAP_REL_TOLERANCE, FX_PAIR_USDCAD,
|
||||
};
|
||||
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,
|
||||
MAX_SUPPORTED_DATE, MAX_SUPPORTED_YEAR, MIN_SUPPORTED_DATE, MIN_SUPPORTED_YEAR,
|
||||
SHORTS_DISSEMINATION_HOUR_ET, SHORTS_DISSEMINATION_MINUTE_ET, SHORTS_LAG_BUSINESS_DAYS,
|
||||
SHORTS_SOURCE_CEO,
|
||||
};
|
||||
pub use split::{
|
||||
unadjust_ohlcv, unadjust_price, unadjust_volume, ymd_to_epoch_days, OhlcvBar, SplitEntry,
|
||||
SplitError, SplitEvent, SplitTable,
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ use std::process::ExitCode;
|
|||
|
||||
use curate_etl::bench::{
|
||||
run_adj_benchmark, run_bars_benchmark, run_corporate_actions_benchmark, run_fx_benchmark,
|
||||
run_split_benchmark,
|
||||
run_shorts_benchmark, run_split_benchmark,
|
||||
};
|
||||
use curate_etl::cli::{format_usage, format_usage_stderr, parse_args, CliAction};
|
||||
|
||||
|
|
@ -204,6 +204,35 @@ fn main() -> ExitCode {
|
|||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchShorts(rows)) => {
|
||||
let report = match run_shorts_benchmark(rows) {
|
||||
Ok(report) => report,
|
||||
Err(err) => {
|
||||
eprintln!("error: shorts benchmark failed: {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
println!("curate-etl bench-shorts");
|
||||
println!(" input: rows={} keys={}", report.rows, report.key_count);
|
||||
println!(
|
||||
" build: rows_out={} keys_out={} elapsed={:.2} ms throughput={:.0} rows/s latency={:.2} ns/row checksum=0x{:016x}",
|
||||
report.rows_out,
|
||||
report.keys_out,
|
||||
report.build_elapsed_ms,
|
||||
report.rows_per_sec,
|
||||
report.ns_per_row,
|
||||
report.checksum
|
||||
);
|
||||
println!(
|
||||
" stats: invalid_shares={} nulled_net_change={} nulled_pct_float={} dup_collapsed={} dup_conflict={}",
|
||||
report.stats.dropped_invalid_shares_short,
|
||||
report.stats.nulled_invalid_net_change,
|
||||
report.stats.nulled_invalid_pct_float,
|
||||
report.stats.duplicate_collapsed,
|
||||
report.stats.duplicate_conflict_dropped
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(msg) => {
|
||||
eprintln!("error: {msg}");
|
||||
eprintln!("{}", format_usage_stderr(NAME));
|
||||
|
|
|
|||
987
tools/curate-etl/src/shorts.rs
Normal file
987
tools/curate-etl/src/shorts.rs
Normal file
|
|
@ -0,0 +1,987 @@
|
|||
//! Pure, in-memory `shorts` builder (`ceoShorts` → `+4` Canadian TSX business-day `17:00 ET`
|
||||
//! `known_at`).
|
||||
//!
|
||||
//! Produces sorted, unique per-`(key, report_date)` rows matching `shorts/part.parquet` in
|
||||
//! `design/DATA-CONTRACTS.md` (`listing_id, report_date, known_at, shares_short, net_change,
|
||||
//! pct_float, source`).
|
||||
//!
|
||||
//! Also exposes reusable `std`-only Canadian TSX business-day calendar (`2008–2030`) and
|
||||
//! `America/Toronto` ET→UTC DST conversion helpers ([`is_canadian_business_day`],
|
||||
//! [`add_canadian_business_days`], [`et_to_utc_micros`], [`epoch_days_to_ymd`]) for downstream
|
||||
//! builders (e.g., `events` with `16:05 ET` lag).
|
||||
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use crate::split::ymd_to_epoch_days;
|
||||
|
||||
/// Canonical provenance label written to [`ShortRow::source`].
|
||||
pub const SHORTS_SOURCE_CEO: &str = "ceo_shorts";
|
||||
|
||||
/// Locked CIRO dissemination lag in Canadian TSX business days (`design/DATA-CONTRACTS.md` §1).
|
||||
pub const SHORTS_LAG_BUSINESS_DAYS: u32 = 4;
|
||||
|
||||
/// Locked CIRO dissemination wall-clock hour in `America/Toronto` (`17:00 ET`).
|
||||
pub const SHORTS_DISSEMINATION_HOUR_ET: u8 = 17;
|
||||
|
||||
/// Locked CIRO dissemination wall-clock minute in `America/Toronto` (`17:00 ET`).
|
||||
pub const SHORTS_DISSEMINATION_MINUTE_ET: u8 = 0;
|
||||
|
||||
/// First Gregorian year covered by the built-in TSX holiday & DST calendar (Family Day joined TSX
|
||||
/// in 2008; North American 2nd-Sun-Mar / 1st-Sun-Nov DST rules took effect in 2007).
|
||||
pub const MIN_SUPPORTED_YEAR: i32 = 2008;
|
||||
|
||||
/// Last Gregorian year covered by the built-in TSX holiday & DST calendar (strictly covers
|
||||
/// `2017-01-01..=2027-12-31` plus year-end `+4` business-day rollovers).
|
||||
pub const MAX_SUPPORTED_YEAR: i32 = 2030;
|
||||
|
||||
/// Epoch day for `2008-01-01` (inclusive lower bound of the supported calendar range).
|
||||
pub const MIN_SUPPORTED_DATE: i32 = 13_879;
|
||||
|
||||
/// Epoch day for `2030-12-31` (inclusive upper bound of the supported calendar range).
|
||||
pub const MAX_SUPPORTED_DATE: i32 = 22_279;
|
||||
|
||||
const SUPPORTED_DAY_COUNT: usize = (MAX_SUPPORTED_DATE - MIN_SUPPORTED_DATE + 1) as usize;
|
||||
const SUPPORTED_YEAR_COUNT: usize = (MAX_SUPPORTED_YEAR - MIN_SUPPORTED_YEAR + 1) as usize;
|
||||
|
||||
/// Typed errors returned by the Canadian calendar, ET→UTC converter, and [`build_shorts`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ShortsError {
|
||||
/// A date (or a stepped business day) fell outside `[MIN_SUPPORTED_DATE, MAX_SUPPORTED_DATE]`.
|
||||
DateOutOfRange {
|
||||
epoch_day: i32,
|
||||
min_supported: i32,
|
||||
max_supported: i32,
|
||||
},
|
||||
/// Wall-clock `(hour, minute, second)` components were out of range (`0..=23`, `0..=59`, `0..=59`).
|
||||
InvalidLocalTime { hour: u8, minute: u8, second: u8 },
|
||||
/// Local wall-clock time fell in the spring-forward DST gap (`02:00:00..=02:59:59` ET on the
|
||||
/// 2nd Sunday of March).
|
||||
NonexistentLocalTime {
|
||||
epoch_day: i32,
|
||||
hour: u8,
|
||||
minute: u8,
|
||||
second: u8,
|
||||
},
|
||||
/// Local wall-clock time fell in the fall-back DST overlap (`01:00:00..=01:59:59` ET on the
|
||||
/// 1st Sunday of November).
|
||||
AmbiguousLocalTime {
|
||||
epoch_day: i32,
|
||||
hour: u8,
|
||||
minute: u8,
|
||||
second: u8,
|
||||
},
|
||||
}
|
||||
|
||||
impl fmt::Display for ShortsError {
|
||||
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 calendar range [{min_supported}, {max_supported}] ({MIN_SUPPORTED_YEAR}-01-01..={MAX_SUPPORTED_YEAR}-12-31)"
|
||||
),
|
||||
Self::InvalidLocalTime {
|
||||
hour,
|
||||
minute,
|
||||
second,
|
||||
} => write!(
|
||||
f,
|
||||
"invalid local time {hour:02}:{minute:02}:{second:02} (expected 00:00:00..=23:59:59)"
|
||||
),
|
||||
Self::NonexistentLocalTime {
|
||||
epoch_day,
|
||||
hour,
|
||||
minute,
|
||||
second,
|
||||
} => {
|
||||
let (y, m, d) = epoch_days_to_ymd(epoch_day);
|
||||
write!(
|
||||
f,
|
||||
"nonexistent America/Toronto local time {y:04}-{m:02}-{d:02} {hour:02}:{minute:02}:{second:02} (spring-forward DST gap)"
|
||||
)
|
||||
}
|
||||
Self::AmbiguousLocalTime {
|
||||
epoch_day,
|
||||
hour,
|
||||
minute,
|
||||
second,
|
||||
} => {
|
||||
let (y, m, d) = epoch_days_to_ymd(epoch_day);
|
||||
write!(
|
||||
f,
|
||||
"ambiguous America/Toronto local time {y:04}-{m:02}-{d:02} {hour:02}:{minute:02}:{second:02} (fall-back DST overlap)"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for ShortsError {}
|
||||
|
||||
/// Converts signed days since `1970-01-01` (UTC Gregorian) back to `(year, month, day)`.
|
||||
///
|
||||
/// Exact inverse of [`crate::ymd_to_epoch_days`] (Howard Hinnant's `civil_from_days`).
|
||||
#[inline]
|
||||
pub fn epoch_days_to_ymd(epoch_day: i32) -> (i32, u32, u32) {
|
||||
let z = i64::from(epoch_day) + 719_468;
|
||||
let era = z.div_euclid(146_097);
|
||||
let doe = z - era * 146_097; // [0, 146096]
|
||||
let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; // [0, 399]
|
||||
let y = yoe + era * 400;
|
||||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365]
|
||||
let mp = (5 * doy + 2) / 153; // [0, 11]
|
||||
let d = doy - (153 * mp + 2) / 5 + 1; // [1, 31]
|
||||
let m = if mp < 10 { mp + 3 } else { mp - 9 }; // [1, 12]
|
||||
let year = y + i64::from(m <= 2);
|
||||
(year as i32, m as u32, d as u32)
|
||||
}
|
||||
|
||||
/// 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
|
||||
}
|
||||
|
||||
/// Computes the epoch day of the `nth` occurrence (`1`-indexed) of `target_iso_weekday`
|
||||
/// (`1 = Mon ..= 7 = Sun`) in `(year, month)`.
|
||||
fn nth_weekday_of_month(year: i32, month: u32, target_iso_weekday: u8, 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 = (i32::from(target_iso_weekday) - i32::from(first_wd)).rem_euclid(7);
|
||||
first + delta + (nth as i32 - 1) * 7
|
||||
}
|
||||
|
||||
/// Anonymous Gregorian algorithm (Meeus/Jones/Butcher) for Easter Sunday.
|
||||
fn easter_sunday_epoch_day(year: i32) -> i32 {
|
||||
let a = year % 19;
|
||||
let b = year / 100;
|
||||
let c = year % 100;
|
||||
let d = b / 4;
|
||||
let e = b % 4;
|
||||
let f = (b + 8) / 25;
|
||||
let g = (b - f + 1) / 3;
|
||||
let h = (19 * a + b - d - g + 15) % 30;
|
||||
let i = c / 4;
|
||||
let k = c % 4;
|
||||
let l = (32 + 2 * e + 2 * i - h - k) % 7;
|
||||
let m = (a + 11 * h + 22 * l) / 451;
|
||||
let month = (h + l - 7 * m + 114) / 31;
|
||||
let day = ((h + l - 7 * m + 114) % 31) + 1;
|
||||
ymd_to_epoch_days(year, month as u32, day as u32).expect("valid Easter Sunday")
|
||||
}
|
||||
|
||||
/// Observes a fixed-date TSX holiday (New Year's Day / Canada Day): Saturday → Monday (`+2`),
|
||||
/// Sunday → Monday (`+1`), weekday → same day.
|
||||
fn observed_fixed_holiday(epoch_day: i32) -> i32 {
|
||||
match iso_weekday(epoch_day) {
|
||||
6 => epoch_day + 2,
|
||||
7 => epoch_day + 1,
|
||||
_ => epoch_day,
|
||||
}
|
||||
}
|
||||
|
||||
struct CalendarTable {
|
||||
/// `true` iff `MIN_SUPPORTED_DATE + idx` is a Canadian TSX business day.
|
||||
is_business: Vec<bool>,
|
||||
/// Per-year `(dst_start_epoch_day, dst_end_epoch_day)` for `MIN_SUPPORTED_YEAR..=MAX_SUPPORTED_YEAR`.
|
||||
dst_bounds: [(i32, i32); SUPPORTED_YEAR_COUNT],
|
||||
}
|
||||
|
||||
impl CalendarTable {
|
||||
fn build() -> Self {
|
||||
let mut is_business = vec![true; SUPPORTED_DAY_COUNT];
|
||||
for (idx, flag) in is_business.iter_mut().enumerate() {
|
||||
let day = MIN_SUPPORTED_DATE + idx as i32;
|
||||
if iso_weekday(day) >= 6 {
|
||||
*flag = false;
|
||||
}
|
||||
}
|
||||
|
||||
let mut dst_bounds = [(0i32, 0i32); SUPPORTED_YEAR_COUNT];
|
||||
|
||||
for year in MIN_SUPPORTED_YEAR..=MAX_SUPPORTED_YEAR {
|
||||
let mut mark_holiday = |day: i32| {
|
||||
if (MIN_SUPPORTED_DATE..=MAX_SUPPORTED_DATE).contains(&day) {
|
||||
is_business[(day - MIN_SUPPORTED_DATE) as usize] = false;
|
||||
}
|
||||
};
|
||||
|
||||
// 1. New Year's Day (Jan 1; Sat -> Mon Jan 3, Sun -> Mon Jan 2).
|
||||
let jan1 = ymd_to_epoch_days(year, 1, 1).expect("valid Jan 1");
|
||||
mark_holiday(observed_fixed_holiday(jan1));
|
||||
|
||||
// 2. Family Day (3rd Monday of February, observed by TSX since 2008).
|
||||
mark_holiday(nth_weekday_of_month(year, 2, 1, 3));
|
||||
|
||||
// 3. Good Friday (Easter Sunday - 2 days).
|
||||
mark_holiday(easter_sunday_epoch_day(year) - 2);
|
||||
|
||||
// 4. Victoria Day (Monday strictly before May 25).
|
||||
let may24 = ymd_to_epoch_days(year, 5, 24).expect("valid May 24");
|
||||
let victoria = may24 - i32::from(iso_weekday(may24) - 1);
|
||||
mark_holiday(victoria);
|
||||
|
||||
// 5. Canada Day (Jul 1; Sat -> Mon Jul 3, Sun -> Mon Jul 2).
|
||||
let jul1 = ymd_to_epoch_days(year, 7, 1).expect("valid Jul 1");
|
||||
mark_holiday(observed_fixed_holiday(jul1));
|
||||
|
||||
// 6. Civic Holiday (1st Monday of August).
|
||||
mark_holiday(nth_weekday_of_month(year, 8, 1, 1));
|
||||
|
||||
// 7. Labour Day (1st Monday of September).
|
||||
mark_holiday(nth_weekday_of_month(year, 9, 1, 1));
|
||||
|
||||
// 8. Thanksgiving (2nd Monday of October).
|
||||
mark_holiday(nth_weekday_of_month(year, 10, 1, 2));
|
||||
|
||||
// 9. Christmas Day & Boxing Day pair (Dec 25/26 with TSX weekend observance):
|
||||
// Mon–Thu -> Dec 25 & Dec 26
|
||||
// Fri -> Dec 25 (Fri) & Dec 28 (Mon)
|
||||
// Sat -> Dec 27 (Mon) & Dec 28 (Tue)
|
||||
// Sun -> Dec 26 (Mon) & Dec 27 (Tue)
|
||||
let dec25 = ymd_to_epoch_days(year, 12, 25).expect("valid Dec 25");
|
||||
let (xmas_obs, boxing_obs) = match iso_weekday(dec25) {
|
||||
1..=4 => (dec25, dec25 + 1),
|
||||
5 => (dec25, dec25 + 3),
|
||||
6 => (dec25 + 2, dec25 + 3),
|
||||
7 => (dec25 + 1, dec25 + 2),
|
||||
_ => unreachable!("iso_weekday is always in 1..=7"),
|
||||
};
|
||||
mark_holiday(xmas_obs);
|
||||
mark_holiday(boxing_obs);
|
||||
|
||||
// America/Toronto DST: 2nd Sunday of March -> 1st Sunday of November.
|
||||
let dst_start = nth_weekday_of_month(year, 3, 7, 2);
|
||||
let dst_end = nth_weekday_of_month(year, 11, 7, 1);
|
||||
dst_bounds[(year - MIN_SUPPORTED_YEAR) as usize] = (dst_start, dst_end);
|
||||
}
|
||||
|
||||
Self {
|
||||
is_business,
|
||||
dst_bounds,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn calendar_table() -> &'static CalendarTable {
|
||||
static TABLE: OnceLock<CalendarTable> = OnceLock::new();
|
||||
TABLE.get_or_init(CalendarTable::build)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn check_supported_date(epoch_day: i32) -> Result<(), ShortsError> {
|
||||
if (MIN_SUPPORTED_DATE..=MAX_SUPPORTED_DATE).contains(&epoch_day) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ShortsError::DateOutOfRange {
|
||||
epoch_day,
|
||||
min_supported: MIN_SUPPORTED_DATE,
|
||||
max_supported: MAX_SUPPORTED_DATE,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `Ok(true)` iff `epoch_day` is a Canadian TSX business day (weekday and not a TSX
|
||||
/// holiday) within `[MIN_SUPPORTED_DATE, MAX_SUPPORTED_DATE]` (`2008-01-01..=2030-12-31`).
|
||||
///
|
||||
/// Dates outside the supported range return [`ShortsError::DateOutOfRange`].
|
||||
#[inline]
|
||||
pub fn is_canadian_business_day(epoch_day: i32) -> Result<bool, ShortsError> {
|
||||
check_supported_date(epoch_day)?;
|
||||
let table = calendar_table();
|
||||
Ok(table.is_business[(epoch_day - MIN_SUPPORTED_DATE) as usize])
|
||||
}
|
||||
|
||||
/// Advances `epoch_day` strictly forward by `n` Canadian TSX business days.
|
||||
///
|
||||
/// - When `n == 0`, returns `Ok(epoch_day)` if `epoch_day` is within the supported range.
|
||||
/// - When `epoch_day` is itself a weekend or holiday, counts strictly forward from `epoch_day` so
|
||||
/// the returned date is the `n`-th business day strictly after `epoch_day`.
|
||||
/// - Returns [`ShortsError::DateOutOfRange`] if `epoch_day` or any stepped day leaves
|
||||
/// `[MIN_SUPPORTED_DATE, MAX_SUPPORTED_DATE]`.
|
||||
#[inline]
|
||||
pub fn add_canadian_business_days(epoch_day: i32, n: u32) -> Result<i32, ShortsError> {
|
||||
check_supported_date(epoch_day)?;
|
||||
if n == 0 {
|
||||
return Ok(epoch_day);
|
||||
}
|
||||
|
||||
let table = calendar_table();
|
||||
let mut cur = epoch_day;
|
||||
let mut remaining = n;
|
||||
while remaining > 0 {
|
||||
if cur >= MAX_SUPPORTED_DATE {
|
||||
return Err(ShortsError::DateOutOfRange {
|
||||
epoch_day: cur.saturating_add(1),
|
||||
min_supported: MIN_SUPPORTED_DATE,
|
||||
max_supported: MAX_SUPPORTED_DATE,
|
||||
});
|
||||
}
|
||||
cur += 1;
|
||||
if table.is_business[(cur - MIN_SUPPORTED_DATE) as usize] {
|
||||
remaining -= 1;
|
||||
}
|
||||
}
|
||||
Ok(cur)
|
||||
}
|
||||
|
||||
/// Converts an `America/Toronto` local date and wall-clock time `(hour, minute, second)` to UTC
|
||||
/// microseconds since `1970-01-01T00:00:00Z`.
|
||||
///
|
||||
/// Applies North American post-2007 DST rules (2nd Sunday of March 02:00 → 1st Sunday of November
|
||||
/// 02:00 = EDT `UTC-4`, otherwise EST `UTC-5`) over `2008-01-01..=2030-12-31`.
|
||||
///
|
||||
/// Rejects:
|
||||
/// - out-of-range dates ([`ShortsError::DateOutOfRange`]),
|
||||
/// - invalid clock components ([`ShortsError::InvalidLocalTime`]),
|
||||
/// - spring-forward nonexistent times `02:00:00..=02:59:59` ([`ShortsError::NonexistentLocalTime`]),
|
||||
/// - fall-back ambiguous times `01:00:00..=01:59:59` ([`ShortsError::AmbiguousLocalTime`]).
|
||||
#[inline]
|
||||
pub fn et_to_utc_micros(
|
||||
epoch_day: i32,
|
||||
hour: u8,
|
||||
minute: u8,
|
||||
second: u8,
|
||||
) -> Result<i64, ShortsError> {
|
||||
if hour > 23 || minute > 59 || second > 59 {
|
||||
return Err(ShortsError::InvalidLocalTime {
|
||||
hour,
|
||||
minute,
|
||||
second,
|
||||
});
|
||||
}
|
||||
check_supported_date(epoch_day)?;
|
||||
|
||||
let (year, _, _) = epoch_days_to_ymd(epoch_day);
|
||||
let (dst_start, dst_end) = calendar_table().dst_bounds[(year - MIN_SUPPORTED_YEAR) as usize];
|
||||
|
||||
let is_edt = if epoch_day == dst_start {
|
||||
if hour == 2 {
|
||||
return Err(ShortsError::NonexistentLocalTime {
|
||||
epoch_day,
|
||||
hour,
|
||||
minute,
|
||||
second,
|
||||
});
|
||||
}
|
||||
hour >= 3
|
||||
} else if epoch_day == dst_end {
|
||||
if hour == 1 {
|
||||
return Err(ShortsError::AmbiguousLocalTime {
|
||||
epoch_day,
|
||||
hour,
|
||||
minute,
|
||||
second,
|
||||
});
|
||||
}
|
||||
hour == 0
|
||||
} else {
|
||||
epoch_day > dst_start && epoch_day < dst_end
|
||||
};
|
||||
|
||||
let offset_hours: i64 = if is_edt { 4 } else { 5 };
|
||||
let local_secs = i64::from(hour) * 3_600 + i64::from(minute) * 60 + i64::from(second);
|
||||
let utc_secs = i64::from(epoch_day) * 86_400 + local_secs + offset_hours * 3_600;
|
||||
Ok(utc_secs * 1_000_000)
|
||||
}
|
||||
|
||||
/// A single raw `ceoShorts` short-interest report row.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct CeoShortReport<K = String> {
|
||||
pub key: K,
|
||||
/// Report period date (15th or month-end) as days since `1970-01-01` (UTC Gregorian).
|
||||
pub report_date: i32,
|
||||
/// Reported short share count (must be finite and `>= 0.0`).
|
||||
pub shares_short: f64,
|
||||
/// Optional net change vs. prior report (non-finite values are sanitized to `None`).
|
||||
pub net_change: Option<f64>,
|
||||
/// Optional percent of float short passed through from caller (non-finite → `None`).
|
||||
pub pct_float: Option<f64>,
|
||||
}
|
||||
|
||||
/// A single curated `shorts` row, sorted and unique by `(key, report_date)`.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ShortRow<K = String> {
|
||||
pub key: K,
|
||||
pub report_date: i32,
|
||||
/// Point-in-time dissemination date (`report_date + 4` Canadian TSX business days).
|
||||
pub known_at_date: i32,
|
||||
/// Point-in-time UTC microseconds (`17:00:00 America/Toronto` on `known_at_date`).
|
||||
pub known_at_utc_micros: i64,
|
||||
pub shares_short: f64,
|
||||
pub net_change: Option<f64>,
|
||||
pub pct_float: Option<f64>,
|
||||
pub source: &'static str,
|
||||
}
|
||||
|
||||
/// Summary accounting counters produced alongside [`ShortsBuild::rows`].
|
||||
///
|
||||
/// Conservation invariant:
|
||||
/// `rows_in == rows_out + dropped_invalid_shares_short + duplicate_collapsed + duplicate_conflict_dropped`
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct ShortsStats {
|
||||
pub rows_in: usize,
|
||||
pub rows_out: usize,
|
||||
pub keys_out: usize,
|
||||
pub dropped_invalid_shares_short: usize,
|
||||
pub nulled_invalid_net_change: usize,
|
||||
pub nulled_invalid_pct_float: usize,
|
||||
pub duplicate_collapsed: usize,
|
||||
pub duplicate_conflict_dropped: usize,
|
||||
}
|
||||
|
||||
/// Output of [`build_shorts`]: sorted, unique point-in-time `shorts` rows and exact stats.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ShortsBuild<K = String> {
|
||||
pub rows: Vec<ShortRow<K>>,
|
||||
pub stats: ShortsStats,
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn normalize_zero(v: f64) -> f64 {
|
||||
if v == 0.0 {
|
||||
0.0
|
||||
} else {
|
||||
v
|
||||
}
|
||||
}
|
||||
|
||||
struct NormalizedShort<K> {
|
||||
key: K,
|
||||
report_date: i32,
|
||||
known_at_date: i32,
|
||||
shares_short: f64,
|
||||
net_change: Option<f64>,
|
||||
pct_float: Option<f64>,
|
||||
}
|
||||
|
||||
impl<K> NormalizedShort<K> {
|
||||
#[inline]
|
||||
fn values_bit_eq(&self, other: &Self) -> bool {
|
||||
self.shares_short.to_bits() == other.shares_short.to_bits()
|
||||
&& self.net_change.map(f64::to_bits) == other.net_change.map(f64::to_bits)
|
||||
&& self.pct_float.map(f64::to_bits) == other.pct_float.map(f64::to_bits)
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds sorted, unique point-in-time `shorts` rows from raw `ceoShorts` report rows.
|
||||
///
|
||||
/// - Validates `report_date + 4` Canadian TSX business days on every input row first so any
|
||||
/// out-of-range date returns [`ShortsError::DateOutOfRange`] deterministically regardless of row
|
||||
/// order or bad numeric fields.
|
||||
/// - Drops non-finite or negative `shares_short` (`dropped_invalid_shares_short`) without aborting
|
||||
/// and without incrementing optional-field null counters.
|
||||
/// - Sanitizes non-finite `net_change` / `pct_float` to `None` (`nulled_invalid_net_change` /
|
||||
/// `nulled_invalid_pct_float`) and normalizes `-0.0` to `0.0` before deduplication.
|
||||
/// - Collapses bitwise-identical duplicates on `(key, report_date)` (`duplicate_collapsed`) and
|
||||
/// drops conflicting duplicate groups entirely (`duplicate_conflict_dropped`).
|
||||
/// - Stamps `known_at_utc_micros = 17:00 America/Toronto` on `known_at_date` and
|
||||
/// `source = "ceo_shorts"`.
|
||||
/// - Any permutation of `rows` yields bitwise-identical `rows` and `stats`.
|
||||
pub fn build_shorts<K, I>(rows: I) -> Result<ShortsBuild<K>, ShortsError>
|
||||
where
|
||||
K: Ord + Clone,
|
||||
I: IntoIterator<Item = CeoShortReport<K>>,
|
||||
{
|
||||
let iter = rows.into_iter();
|
||||
let (lower, _) = iter.size_hint();
|
||||
let mut stats = ShortsStats::default();
|
||||
let mut valid: Vec<NormalizedShort<K>> = Vec::with_capacity(lower);
|
||||
|
||||
for row in iter {
|
||||
stats.rows_in += 1;
|
||||
|
||||
let known_at_date = add_canadian_business_days(row.report_date, SHORTS_LAG_BUSINESS_DAYS)?;
|
||||
|
||||
if !row.shares_short.is_finite() || row.shares_short < 0.0 {
|
||||
stats.dropped_invalid_shares_short += 1;
|
||||
continue;
|
||||
}
|
||||
let shares_short = normalize_zero(row.shares_short);
|
||||
|
||||
let net_change = match row.net_change {
|
||||
Some(v) if v.is_finite() => Some(normalize_zero(v)),
|
||||
Some(_) => {
|
||||
stats.nulled_invalid_net_change += 1;
|
||||
None
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
|
||||
let pct_float = match row.pct_float {
|
||||
Some(v) if v.is_finite() => Some(normalize_zero(v)),
|
||||
Some(_) => {
|
||||
stats.nulled_invalid_pct_float += 1;
|
||||
None
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
|
||||
valid.push(NormalizedShort {
|
||||
key: row.key,
|
||||
report_date: row.report_date,
|
||||
known_at_date,
|
||||
shares_short,
|
||||
net_change,
|
||||
pct_float,
|
||||
});
|
||||
}
|
||||
|
||||
valid.sort_unstable_by(|a, b| {
|
||||
a.key
|
||||
.cmp(&b.key)
|
||||
.then_with(|| a.report_date.cmp(&b.report_date))
|
||||
});
|
||||
|
||||
let mut out: Vec<ShortRow<K>> = Vec::with_capacity(valid.len());
|
||||
let len = valid.len();
|
||||
let mut read_idx = 0usize;
|
||||
|
||||
while read_idx < len {
|
||||
let mut group_end = read_idx + 1;
|
||||
while group_end < len
|
||||
&& valid[group_end].key == valid[read_idx].key
|
||||
&& valid[group_end].report_date == valid[read_idx].report_date
|
||||
{
|
||||
group_end += 1;
|
||||
}
|
||||
|
||||
let group_len = group_end - read_idx;
|
||||
let first = &valid[read_idx];
|
||||
let all_identical = valid[read_idx + 1..group_end]
|
||||
.iter()
|
||||
.all(|other| first.values_bit_eq(other));
|
||||
|
||||
if all_identical {
|
||||
stats.duplicate_collapsed += group_len - 1;
|
||||
let known_at_utc_micros = et_to_utc_micros(
|
||||
first.known_at_date,
|
||||
SHORTS_DISSEMINATION_HOUR_ET,
|
||||
SHORTS_DISSEMINATION_MINUTE_ET,
|
||||
0,
|
||||
)?;
|
||||
if out.last().is_none_or(|prev| prev.key != first.key) {
|
||||
stats.keys_out += 1;
|
||||
}
|
||||
out.push(ShortRow {
|
||||
key: first.key.clone(),
|
||||
report_date: first.report_date,
|
||||
known_at_date: first.known_at_date,
|
||||
known_at_utc_micros,
|
||||
shares_short: first.shares_short,
|
||||
net_change: first.net_change,
|
||||
pct_float: first.pct_float,
|
||||
source: SHORTS_SOURCE_CEO,
|
||||
});
|
||||
} else {
|
||||
stats.duplicate_conflict_dropped += group_len;
|
||||
}
|
||||
|
||||
read_idx = group_end;
|
||||
}
|
||||
|
||||
stats.rows_out = out.len();
|
||||
|
||||
Ok(ShortsBuild { rows: out, stats })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn day(y: i32, m: u32, d: u32) -> i32 {
|
||||
ymd_to_epoch_days(y, m, d).expect("valid test date")
|
||||
}
|
||||
|
||||
fn utc_micros(y: i32, m: u32, d: u32, hour: u8, minute: u8, second: u8) -> i64 {
|
||||
let epoch_day = day(y, m, d);
|
||||
let secs = i64::from(epoch_day) * 86_400
|
||||
+ i64::from(hour) * 3_600
|
||||
+ i64::from(minute) * 60
|
||||
+ i64::from(second);
|
||||
secs * 1_000_000
|
||||
}
|
||||
|
||||
fn report(
|
||||
key: &str,
|
||||
report_date: i32,
|
||||
shares_short: f64,
|
||||
net_change: Option<f64>,
|
||||
pct_float: Option<f64>,
|
||||
) -> CeoShortReport<String> {
|
||||
CeoShortReport {
|
||||
key: key.to_string(),
|
||||
report_date,
|
||||
shares_short,
|
||||
net_change,
|
||||
pct_float,
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_invariants<K: Ord>(build: &ShortsBuild<K>) {
|
||||
let s = &build.stats;
|
||||
assert_eq!(
|
||||
s.rows_in,
|
||||
s.rows_out
|
||||
+ s.dropped_invalid_shares_short
|
||||
+ s.duplicate_collapsed
|
||||
+ s.duplicate_conflict_dropped,
|
||||
"accounting invariant failed: {s:?}"
|
||||
);
|
||||
assert_eq!(s.rows_out, build.rows.len());
|
||||
for pair in build.rows.windows(2) {
|
||||
assert!(
|
||||
(&pair[0].key, pair[0].report_date) < (&pair[1].key, pair[1].report_date),
|
||||
"rows must be strictly sorted by (key, report_date)"
|
||||
);
|
||||
}
|
||||
for row in &build.rows {
|
||||
assert!(
|
||||
row.known_at_date > row.report_date,
|
||||
"look-ahead violation: known_at_date {} <= report_date {}",
|
||||
row.known_at_date,
|
||||
row.report_date
|
||||
);
|
||||
assert_eq!(row.source, SHORTS_SOURCE_CEO);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn supported_date_bounds_match_calendar_constants() {
|
||||
assert_eq!(day(MIN_SUPPORTED_YEAR, 1, 1), MIN_SUPPORTED_DATE);
|
||||
assert_eq!(day(MAX_SUPPORTED_YEAR, 12, 31), MAX_SUPPORTED_DATE);
|
||||
assert_eq!(epoch_days_to_ymd(MIN_SUPPORTED_DATE), (2008, 1, 1));
|
||||
assert_eq!(epoch_days_to_ymd(MAX_SUPPORTED_DATE), (2030, 12, 31));
|
||||
assert_eq!(epoch_days_to_ymd(0), (1970, 1, 1));
|
||||
assert_eq!(epoch_days_to_ymd(-1), (1969, 12, 31));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn epoch_days_to_ymd_round_trips_every_supported_day() {
|
||||
for d in MIN_SUPPORTED_DATE..=MAX_SUPPORTED_DATE {
|
||||
let (y, m, dom) = epoch_days_to_ymd(d);
|
||||
assert_eq!(ymd_to_epoch_days(y, m, dom).unwrap(), d);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pinned_tsx_holidays_and_observances_are_non_business_days() {
|
||||
let holidays = [
|
||||
// Pinned acceptance criteria dates
|
||||
(2024, 3, 29), // Good Friday
|
||||
(2023, 7, 3), // Canada Day observed (Jul 1 Sat)
|
||||
(2022, 12, 26), // Christmas observed (Dec 25 Sun)
|
||||
(2022, 12, 27), // Boxing Day observed (Dec 25 Sun)
|
||||
(2021, 2, 15), // Family Day
|
||||
(2024, 5, 20), // Victoria Day
|
||||
(2024, 8, 5), // Civic Holiday
|
||||
(2024, 10, 14), // Thanksgiving
|
||||
// New Year's Day weekday + Sat/Sun observances
|
||||
(2024, 1, 1), // Mon
|
||||
(2022, 1, 3), // Jan 1 Sat -> Mon Jan 3
|
||||
(2023, 1, 2), // Jan 1 Sun -> Mon Jan 2
|
||||
// Christmas/Boxing Day Fri and Sat cases
|
||||
(2020, 12, 25), // Fri
|
||||
(2020, 12, 28), // Dec 26 Sat -> Mon Dec 28
|
||||
(2021, 12, 27), // Dec 25 Sat -> Mon Dec 27
|
||||
(2021, 12, 28), // Dec 26 Sun -> Tue Dec 28
|
||||
// Canada Day Sun observance
|
||||
(2018, 7, 2), // Jul 1 Sun -> Mon Jul 2
|
||||
// Labour Day
|
||||
(2024, 9, 2), // 1st Mon of Sep
|
||||
// Weekend
|
||||
(2024, 6, 15), // Saturday
|
||||
(2024, 6, 16), // Sunday
|
||||
];
|
||||
|
||||
for (y, m, d) in holidays {
|
||||
assert_eq!(
|
||||
is_canadian_business_day(day(y, m, d)),
|
||||
Ok(false),
|
||||
"expected {y:04}-{m:02}-{d:02} to be a non-business day"
|
||||
);
|
||||
}
|
||||
|
||||
// Ordinary weekdays + federal holidays where TSX remains open
|
||||
let business_days = [
|
||||
(2024, 6, 12), // Ordinary Wednesday
|
||||
(2023, 10, 2), // National Day for Truth & Reconciliation observed (TSX open)
|
||||
(2024, 9, 30), // National Day for Truth & Reconciliation (TSX open)
|
||||
(2024, 11, 11), // Remembrance Day (TSX open)
|
||||
(2021, 12, 24), // Christmas Eve (Fri before Sat Christmas -> TSX open)
|
||||
(2021, 12, 31), // New Year's Eve (Fri before Sat New Year's -> TSX open)
|
||||
];
|
||||
|
||||
for (y, m, d) in business_days {
|
||||
assert_eq!(
|
||||
is_canadian_business_day(day(y, m, d)),
|
||||
Ok(true),
|
||||
"expected {y:04}-{m:02}-{d:02} to be a TSX business day"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_canadian_business_days_matches_pinned_plus_four_fixtures() {
|
||||
assert_eq!(
|
||||
add_canadian_business_days(day(2024, 3, 15), 4),
|
||||
Ok(day(2024, 3, 21))
|
||||
);
|
||||
assert_eq!(
|
||||
add_canadian_business_days(day(2024, 3, 28), 4),
|
||||
Ok(day(2024, 4, 4))
|
||||
);
|
||||
assert_eq!(
|
||||
add_canadian_business_days(day(2023, 12, 29), 4),
|
||||
Ok(day(2024, 1, 5))
|
||||
);
|
||||
assert_eq!(
|
||||
add_canadian_business_days(day(2023, 9, 30), 4),
|
||||
Ok(day(2023, 10, 5))
|
||||
);
|
||||
// n == 0 returns input unchanged when in range (even on a weekend)
|
||||
assert_eq!(
|
||||
add_canadian_business_days(day(2023, 9, 30), 0),
|
||||
Ok(day(2023, 9, 30))
|
||||
);
|
||||
// Year-end 2027 rollover into Jan 2028 works cleanly
|
||||
assert_eq!(
|
||||
add_canadian_business_days(day(2027, 12, 31), 4),
|
||||
Ok(day(2028, 1, 7))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn out_of_range_dates_return_typed_error_without_panicking() {
|
||||
for bad in [
|
||||
MIN_SUPPORTED_DATE - 1,
|
||||
MAX_SUPPORTED_DATE + 1,
|
||||
day(2007, 12, 31),
|
||||
day(2031, 1, 1),
|
||||
i32::MIN,
|
||||
i32::MAX,
|
||||
] {
|
||||
assert!(matches!(
|
||||
is_canadian_business_day(bad),
|
||||
Err(ShortsError::DateOutOfRange { epoch_day, .. }) if epoch_day == bad
|
||||
));
|
||||
assert!(matches!(
|
||||
add_canadian_business_days(bad, 4),
|
||||
Err(ShortsError::DateOutOfRange { epoch_day, .. }) if epoch_day == bad
|
||||
));
|
||||
assert!(matches!(
|
||||
et_to_utc_micros(bad, 17, 0, 0),
|
||||
Err(ShortsError::DateOutOfRange { epoch_day, .. }) if epoch_day == bad
|
||||
));
|
||||
}
|
||||
|
||||
// Stepping past MAX_SUPPORTED_DATE returns DateOutOfRange
|
||||
assert!(matches!(
|
||||
add_canadian_business_days(day(2030, 12, 30), 4),
|
||||
Err(ShortsError::DateOutOfRange { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn et_to_utc_micros_handles_edt_est_dst_boundaries_and_errors() {
|
||||
// Summer (EDT UTC-4) -> 17:00 ET == 21:00 UTC
|
||||
assert_eq!(
|
||||
et_to_utc_micros(day(2024, 7, 15), 17, 0, 0),
|
||||
Ok(utc_micros(2024, 7, 15, 21, 0, 0))
|
||||
);
|
||||
// Winter (EST UTC-5) -> 17:00 ET == 22:00 UTC
|
||||
assert_eq!(
|
||||
et_to_utc_micros(day(2024, 1, 15), 17, 0, 0),
|
||||
Ok(utc_micros(2024, 1, 15, 22, 0, 0))
|
||||
);
|
||||
|
||||
// Both sides of March 2024 spring-forward (2nd Sun = Mar 10)
|
||||
assert_eq!(
|
||||
et_to_utc_micros(day(2024, 3, 9), 17, 0, 0),
|
||||
Ok(utc_micros(2024, 3, 9, 22, 0, 0))
|
||||
);
|
||||
assert_eq!(
|
||||
et_to_utc_micros(day(2024, 3, 10), 1, 59, 59),
|
||||
Ok(utc_micros(2024, 3, 10, 6, 59, 59))
|
||||
);
|
||||
assert_eq!(
|
||||
et_to_utc_micros(day(2024, 3, 10), 3, 0, 0),
|
||||
Ok(utc_micros(2024, 3, 10, 7, 0, 0))
|
||||
);
|
||||
assert_eq!(
|
||||
et_to_utc_micros(day(2024, 3, 10), 17, 0, 0),
|
||||
Ok(utc_micros(2024, 3, 10, 21, 0, 0))
|
||||
);
|
||||
|
||||
// Both sides of November 2024 fall-back (1st Sun = Nov 3)
|
||||
assert_eq!(
|
||||
et_to_utc_micros(day(2024, 11, 2), 17, 0, 0),
|
||||
Ok(utc_micros(2024, 11, 2, 21, 0, 0))
|
||||
);
|
||||
assert_eq!(
|
||||
et_to_utc_micros(day(2024, 11, 3), 0, 30, 0),
|
||||
Ok(utc_micros(2024, 11, 3, 4, 30, 0))
|
||||
);
|
||||
assert_eq!(
|
||||
et_to_utc_micros(day(2024, 11, 3), 2, 0, 0),
|
||||
Ok(utc_micros(2024, 11, 3, 7, 0, 0))
|
||||
);
|
||||
assert_eq!(
|
||||
et_to_utc_micros(day(2024, 11, 3), 17, 0, 0),
|
||||
Ok(utc_micros(2024, 11, 3, 22, 0, 0))
|
||||
);
|
||||
|
||||
// Reuse check for events 16:05 ET lag
|
||||
assert_eq!(
|
||||
et_to_utc_micros(day(2024, 7, 15), 16, 5, 0),
|
||||
Ok(utc_micros(2024, 7, 15, 20, 5, 0))
|
||||
);
|
||||
assert_eq!(
|
||||
et_to_utc_micros(day(2024, 1, 15), 16, 5, 0),
|
||||
Ok(utc_micros(2024, 1, 15, 21, 5, 0))
|
||||
);
|
||||
|
||||
// Spring-forward nonexistent local time (2026-03-08 02:30)
|
||||
assert_eq!(
|
||||
et_to_utc_micros(day(2026, 3, 8), 2, 30, 0),
|
||||
Err(ShortsError::NonexistentLocalTime {
|
||||
epoch_day: day(2026, 3, 8),
|
||||
hour: 2,
|
||||
minute: 30,
|
||||
second: 0,
|
||||
})
|
||||
);
|
||||
|
||||
// Fall-back ambiguous local time (2026-11-01 01:30)
|
||||
assert_eq!(
|
||||
et_to_utc_micros(day(2026, 11, 1), 1, 30, 0),
|
||||
Err(ShortsError::AmbiguousLocalTime {
|
||||
epoch_day: day(2026, 11, 1),
|
||||
hour: 1,
|
||||
minute: 30,
|
||||
second: 0,
|
||||
})
|
||||
);
|
||||
|
||||
// Invalid clock components
|
||||
assert_eq!(
|
||||
et_to_utc_micros(day(2024, 6, 12), 24, 0, 0),
|
||||
Err(ShortsError::InvalidLocalTime {
|
||||
hour: 24,
|
||||
minute: 0,
|
||||
second: 0,
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
et_to_utc_micros(day(2024, 6, 12), 12, 60, 0),
|
||||
Err(ShortsError::InvalidLocalTime {
|
||||
hour: 12,
|
||||
minute: 60,
|
||||
second: 0,
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
et_to_utc_micros(day(2024, 6, 12), 12, 0, 60),
|
||||
Err(ShortsError::InvalidLocalTime {
|
||||
hour: 12,
|
||||
minute: 0,
|
||||
second: 60,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_shorts_handles_empty_input() {
|
||||
let built = build_shorts::<String, _>(Vec::new()).unwrap();
|
||||
assert!(built.rows.is_empty());
|
||||
assert_eq!(built.stats, ShortsStats::default());
|
||||
assert_invariants(&built);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_shorts_filters_sanitizes_dedups_and_preserves_accounting() {
|
||||
let d1 = day(2024, 3, 15);
|
||||
let d2 = day(2024, 3, 28);
|
||||
let d3 = day(2023, 12, 29);
|
||||
|
||||
let input = vec![
|
||||
// Valid row + bitwise-identical duplicate with -0.0 normalization
|
||||
report("AAA.TO", d1, -0.0, Some(-0.0), Some(-0.0)),
|
||||
report("AAA.TO", d1, 0.0, Some(0.0), Some(0.0)),
|
||||
// Invalid shares_short with NaN optional fields: dropped before optional-field nulling
|
||||
report("AAA.TO", d2, -10.0, Some(f64::NAN), Some(f64::INFINITY)),
|
||||
report("AAA.TO", d2, f64::NAN, Some(1.0), None),
|
||||
report("AAA.TO", d2, f64::INFINITY, None, Some(f64::NEG_INFINITY)),
|
||||
// Valid row with non-finite optional fields -> nulled and counted
|
||||
report(
|
||||
"BBB.TO",
|
||||
d2,
|
||||
125_000.0,
|
||||
Some(f64::NAN),
|
||||
Some(f64::INFINITY),
|
||||
),
|
||||
// Conflicting duplicate group -> dropped entirely
|
||||
report("CCC.TO", d3, 50_000.0, Some(1_000.0), Some(1.5)),
|
||||
report("CCC.TO", d3, 50_001.0, Some(1_000.0), Some(1.5)),
|
||||
];
|
||||
|
||||
let built = build_shorts(input).unwrap();
|
||||
assert_invariants(&built);
|
||||
|
||||
assert_eq!(built.stats.rows_in, 8);
|
||||
assert_eq!(built.stats.rows_out, 2);
|
||||
assert_eq!(built.stats.keys_out, 2);
|
||||
assert_eq!(built.stats.dropped_invalid_shares_short, 3);
|
||||
assert_eq!(built.stats.nulled_invalid_net_change, 1);
|
||||
assert_eq!(built.stats.nulled_invalid_pct_float, 1);
|
||||
assert_eq!(built.stats.duplicate_collapsed, 1);
|
||||
assert_eq!(built.stats.duplicate_conflict_dropped, 2);
|
||||
|
||||
assert_eq!(built.rows[0].key, "AAA.TO");
|
||||
assert_eq!(built.rows[0].report_date, d1);
|
||||
assert_eq!(built.rows[0].known_at_date, day(2024, 3, 21));
|
||||
assert_eq!(
|
||||
built.rows[0].known_at_utc_micros,
|
||||
utc_micros(2024, 3, 21, 21, 0, 0)
|
||||
);
|
||||
assert_eq!(built.rows[0].shares_short.to_bits(), 0.0_f64.to_bits());
|
||||
assert_eq!(
|
||||
built.rows[0].net_change.map(f64::to_bits),
|
||||
Some(0.0_f64.to_bits())
|
||||
);
|
||||
assert_eq!(
|
||||
built.rows[0].pct_float.map(f64::to_bits),
|
||||
Some(0.0_f64.to_bits())
|
||||
);
|
||||
|
||||
assert_eq!(built.rows[1].key, "BBB.TO");
|
||||
assert_eq!(built.rows[1].report_date, d2);
|
||||
assert_eq!(built.rows[1].known_at_date, day(2024, 4, 4));
|
||||
assert_eq!(
|
||||
built.rows[1].known_at_utc_micros,
|
||||
utc_micros(2024, 4, 4, 21, 0, 0)
|
||||
);
|
||||
assert_eq!(built.rows[1].shares_short, 125_000.0);
|
||||
assert_eq!(built.rows[1].net_change, None);
|
||||
assert_eq!(built.rows[1].pct_float, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_shorts_rejects_out_of_range_date_even_on_invalid_shares_row() {
|
||||
let err = build_shorts(vec![report(
|
||||
"AAA.TO",
|
||||
day(2007, 12, 31),
|
||||
-5.0,
|
||||
None,
|
||||
None,
|
||||
)])
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, ShortsError::DateOutOfRange { .. }));
|
||||
}
|
||||
}
|
||||
497
tools/curate-etl/tests/shorts_contract.rs
Normal file
497
tools/curate-etl/tests/shorts_contract.rs
Normal file
|
|
@ -0,0 +1,497 @@
|
|||
//! Contract tests for the public `curate_etl` `shorts` builder API and CLI binary (T-76 / M1.2f).
|
||||
//!
|
||||
//! Uses only the crate's public surface and compiled binary (`CARGO_BIN_EXE_curate-etl`), guarding:
|
||||
//! - Canadian TSX holiday calendar & weekend observance rules (2008–2030),
|
||||
//! - `+4` Canadian business-day lag calculation & out-of-range error handling,
|
||||
//! - `America/Toronto` ET→UTC DST conversion (including spring-gap and fall-overlap rejections),
|
||||
//! - `build_shorts` bad-row resilience, optional-field sanitization, `-0.0` normalization,
|
||||
//! deduplication, accounting invariants, no-look-ahead, and permutation invariance,
|
||||
//! - `bench-shorts` reproducibility and CLI argument validation.
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
use curate_etl::bench::run_shorts_benchmark;
|
||||
use curate_etl::{
|
||||
add_canadian_business_days, build_shorts, epoch_days_to_ymd, et_to_utc_micros,
|
||||
is_canadian_business_day, ymd_to_epoch_days, CeoShortReport, ShortRow, ShortsBuild,
|
||||
ShortsError, ShortsStats, MAX_SUPPORTED_DATE, MAX_SUPPORTED_YEAR, MIN_SUPPORTED_DATE,
|
||||
MIN_SUPPORTED_YEAR, SHORTS_DISSEMINATION_HOUR_ET, SHORTS_DISSEMINATION_MINUTE_ET,
|
||||
SHORTS_LAG_BUSINESS_DAYS, SHORTS_SOURCE_CEO,
|
||||
};
|
||||
|
||||
fn day(y: i32, m: u32, d: u32) -> i32 {
|
||||
ymd_to_epoch_days(y, m, d).expect("valid fixture date")
|
||||
}
|
||||
|
||||
fn utc_micros(y: i32, m: u32, d: u32, hour: u8, minute: u8, second: u8) -> i64 {
|
||||
let epoch_day = day(y, m, d);
|
||||
let secs = i64::from(epoch_day) * 86_400
|
||||
+ i64::from(hour) * 3_600
|
||||
+ i64::from(minute) * 60
|
||||
+ i64::from(second);
|
||||
secs * 1_000_000
|
||||
}
|
||||
|
||||
struct Rng(u64);
|
||||
|
||||
impl Rng {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
|
||||
let mut z = self.0;
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
|
||||
z ^ (z >> 31)
|
||||
}
|
||||
}
|
||||
|
||||
fn shuffle<T>(items: &mut [T], rng: &mut Rng) {
|
||||
for i in (1..items.len()).rev() {
|
||||
let j = (rng.next() % (i as u64 + 1)) as usize;
|
||||
items.swap(i, j);
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_accounting_and_order<K: Ord>(build: &ShortsBuild<K>) {
|
||||
let s = &build.stats;
|
||||
assert_eq!(
|
||||
s.rows_in,
|
||||
s.rows_out
|
||||
+ s.dropped_invalid_shares_short
|
||||
+ s.duplicate_collapsed
|
||||
+ s.duplicate_conflict_dropped,
|
||||
"accounting invariant failed: {s:?}"
|
||||
);
|
||||
assert_eq!(s.rows_out, build.rows.len());
|
||||
|
||||
let mut distinct_keys = 0usize;
|
||||
let mut prev_key: Option<&K> = None;
|
||||
for row in &build.rows {
|
||||
assert!(
|
||||
row.known_at_date > row.report_date,
|
||||
"look-ahead violation: known_at_date {} <= report_date {}",
|
||||
row.known_at_date,
|
||||
row.report_date
|
||||
);
|
||||
assert_eq!(row.source, SHORTS_SOURCE_CEO);
|
||||
assert_eq!(row.source, "ceo_shorts");
|
||||
if prev_key != Some(&row.key) {
|
||||
distinct_keys += 1;
|
||||
prev_key = Some(&row.key);
|
||||
}
|
||||
}
|
||||
assert_eq!(s.keys_out, distinct_keys);
|
||||
|
||||
for pair in build.rows.windows(2) {
|
||||
assert!(
|
||||
(&pair[0].key, pair[0].report_date) < (&pair[1].key, pair[1].report_date),
|
||||
"rows must be strictly sorted by (key, report_date)"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_rows_bit_eq<K: PartialEq + std::fmt::Debug>(a: &[ShortRow<K>], b: &[ShortRow<K>]) {
|
||||
assert_eq!(a.len(), b.len());
|
||||
for (x, y) in a.iter().zip(b) {
|
||||
assert_eq!(x.key, y.key);
|
||||
assert_eq!(x.report_date, y.report_date);
|
||||
assert_eq!(x.known_at_date, y.known_at_date);
|
||||
assert_eq!(x.known_at_utc_micros, y.known_at_utc_micros);
|
||||
assert_eq!(x.shares_short.to_bits(), y.shares_short.to_bits());
|
||||
assert_eq!(
|
||||
x.net_change.map(f64::to_bits),
|
||||
y.net_change.map(f64::to_bits)
|
||||
);
|
||||
assert_eq!(
|
||||
x.pct_float.map(f64::to_bits),
|
||||
y.pct_float.map(f64::to_bits)
|
||||
);
|
||||
assert_eq!(x.source, y.source);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn public_constants_and_calendar_holidays_match_contract() {
|
||||
assert_eq!(SHORTS_SOURCE_CEO, "ceo_shorts");
|
||||
assert_eq!(SHORTS_LAG_BUSINESS_DAYS, 4);
|
||||
assert_eq!(SHORTS_DISSEMINATION_HOUR_ET, 17);
|
||||
assert_eq!(SHORTS_DISSEMINATION_MINUTE_ET, 0);
|
||||
assert_eq!(MIN_SUPPORTED_YEAR, 2008);
|
||||
assert_eq!(MAX_SUPPORTED_YEAR, 2030);
|
||||
assert_eq!(epoch_days_to_ymd(MIN_SUPPORTED_DATE), (2008, 1, 1));
|
||||
assert_eq!(epoch_days_to_ymd(MAX_SUPPORTED_DATE), (2030, 12, 31));
|
||||
|
||||
// Pinned TSX holidays and weekend observances
|
||||
let non_business = [
|
||||
(2024, 3, 29), // Good Friday
|
||||
(2023, 7, 3), // Canada Day observed
|
||||
(2022, 12, 26), // Christmas observed
|
||||
(2022, 12, 27), // Boxing Day observed
|
||||
(2021, 2, 15), // Family Day
|
||||
(2024, 5, 20), // Victoria Day
|
||||
(2024, 8, 5), // Civic Holiday
|
||||
(2024, 10, 14), // Thanksgiving
|
||||
(2022, 1, 3), // New Year's Day observed (Sat Jan 1 -> Mon Jan 3)
|
||||
(2023, 1, 2), // New Year's Day observed (Sun Jan 1 -> Mon Jan 2)
|
||||
(2020, 12, 28), // Boxing Day observed (Fri Dec 25 / Sat Dec 26 -> Mon Dec 28)
|
||||
(2021, 12, 27), // Christmas observed (Sat Dec 25 -> Mon Dec 27)
|
||||
(2021, 12, 28), // Boxing Day observed (Sun Dec 26 -> Tue Dec 28)
|
||||
];
|
||||
for (y, m, d) in non_business {
|
||||
assert_eq!(
|
||||
is_canadian_business_day(day(y, m, d)),
|
||||
Ok(false),
|
||||
"expected {y:04}-{m:02}-{d:02} to be a non-business day"
|
||||
);
|
||||
}
|
||||
|
||||
// Ordinary weekday + federal holidays where TSX trades normally
|
||||
for (y, m, d) in [(2024, 6, 12), (2023, 10, 2), (2024, 11, 11)] {
|
||||
assert_eq!(
|
||||
is_canadian_business_day(day(y, m, d)),
|
||||
Ok(true),
|
||||
"expected {y:04}-{m:02}-{d:02} to be a business day"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plus_four_business_days_and_out_of_range_errors() {
|
||||
assert_eq!(
|
||||
add_canadian_business_days(day(2024, 3, 15), 4),
|
||||
Ok(day(2024, 3, 21))
|
||||
);
|
||||
assert_eq!(
|
||||
add_canadian_business_days(day(2024, 3, 28), 4),
|
||||
Ok(day(2024, 4, 4))
|
||||
);
|
||||
assert_eq!(
|
||||
add_canadian_business_days(day(2023, 12, 29), 4),
|
||||
Ok(day(2024, 1, 5))
|
||||
);
|
||||
assert_eq!(
|
||||
add_canadian_business_days(day(2023, 9, 30), 4),
|
||||
Ok(day(2023, 10, 5))
|
||||
);
|
||||
assert_eq!(
|
||||
add_canadian_business_days(day(2024, 6, 12), 0),
|
||||
Ok(day(2024, 6, 12))
|
||||
);
|
||||
|
||||
// Out-of-range dates return typed ShortsError::DateOutOfRange without panicking
|
||||
for bad in [
|
||||
MIN_SUPPORTED_DATE - 1,
|
||||
MAX_SUPPORTED_DATE + 1,
|
||||
i32::MIN,
|
||||
i32::MAX,
|
||||
] {
|
||||
assert!(matches!(
|
||||
is_canadian_business_day(bad),
|
||||
Err(ShortsError::DateOutOfRange { .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
add_canadian_business_days(bad, 4),
|
||||
Err(ShortsError::DateOutOfRange { .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
et_to_utc_micros(bad, 17, 0, 0),
|
||||
Err(ShortsError::DateOutOfRange { .. })
|
||||
));
|
||||
}
|
||||
assert!(matches!(
|
||||
add_canadian_business_days(day(2030, 12, 30), 4),
|
||||
Err(ShortsError::DateOutOfRange { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn et_to_utc_micros_dst_transitions_and_local_time_validation() {
|
||||
// Summer EDT (21:00Z) vs Winter EST (22:00Z)
|
||||
assert_eq!(
|
||||
et_to_utc_micros(day(2024, 7, 15), 17, 0, 0),
|
||||
Ok(utc_micros(2024, 7, 15, 21, 0, 0))
|
||||
);
|
||||
assert_eq!(
|
||||
et_to_utc_micros(day(2024, 1, 15), 17, 0, 0),
|
||||
Ok(utc_micros(2024, 1, 15, 22, 0, 0))
|
||||
);
|
||||
|
||||
// Both sides of March spring-forward (2024-03-10)
|
||||
assert_eq!(
|
||||
et_to_utc_micros(day(2024, 3, 9), 17, 0, 0),
|
||||
Ok(utc_micros(2024, 3, 9, 22, 0, 0))
|
||||
);
|
||||
assert_eq!(
|
||||
et_to_utc_micros(day(2024, 3, 10), 17, 0, 0),
|
||||
Ok(utc_micros(2024, 3, 10, 21, 0, 0))
|
||||
);
|
||||
|
||||
// Both sides of November fall-back (2024-11-03)
|
||||
assert_eq!(
|
||||
et_to_utc_micros(day(2024, 11, 2), 17, 0, 0),
|
||||
Ok(utc_micros(2024, 11, 2, 21, 0, 0))
|
||||
);
|
||||
assert_eq!(
|
||||
et_to_utc_micros(day(2024, 11, 3), 17, 0, 0),
|
||||
Ok(utc_micros(2024, 11, 3, 22, 0, 0))
|
||||
);
|
||||
|
||||
// Events 16:05 ET reuse
|
||||
assert_eq!(
|
||||
et_to_utc_micros(day(2026, 3, 6), 16, 5, 0),
|
||||
Ok(utc_micros(2026, 3, 6, 21, 5, 0))
|
||||
);
|
||||
assert_eq!(
|
||||
et_to_utc_micros(day(2026, 3, 9), 16, 5, 0),
|
||||
Ok(utc_micros(2026, 3, 9, 20, 5, 0))
|
||||
);
|
||||
|
||||
// Nonexistent, ambiguous, and invalid clock times
|
||||
assert!(matches!(
|
||||
et_to_utc_micros(day(2026, 3, 8), 2, 30, 0),
|
||||
Err(ShortsError::NonexistentLocalTime { .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
et_to_utc_micros(day(2026, 11, 1), 1, 30, 0),
|
||||
Err(ShortsError::AmbiguousLocalTime { .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
et_to_utc_micros(day(2024, 6, 12), 25, 0, 0),
|
||||
Err(ShortsError::InvalidLocalTime { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_shorts_happy_path_bad_rows_dedup_and_empty_input() {
|
||||
let empty = build_shorts::<i32, _>(Vec::new()).unwrap();
|
||||
assert!(empty.rows.is_empty());
|
||||
assert_eq!(empty.stats, ShortsStats::default());
|
||||
assert_accounting_and_order(&empty);
|
||||
|
||||
let d_winter = day(2023, 12, 29); // +4bd -> 2024-01-05 (EST -> 22:00Z)
|
||||
let d_summer = day(2024, 6, 15); // Sat -> +4bd -> 2024-06-20 (EDT -> 21:00Z)
|
||||
let d_easter = day(2024, 3, 28); // Thu before Good Friday -> +4bd -> 2024-04-04 (EDT -> 21:00Z)
|
||||
|
||||
let rows = vec![
|
||||
CeoShortReport {
|
||||
key: 20,
|
||||
report_date: d_summer,
|
||||
shares_short: 250_000.0,
|
||||
net_change: Some(-12_500.0),
|
||||
pct_float: Some(3.25),
|
||||
},
|
||||
// Identical duplicate with -0.0 normalization
|
||||
CeoShortReport {
|
||||
key: 10,
|
||||
report_date: d_winter,
|
||||
shares_short: -0.0,
|
||||
net_change: Some(-0.0),
|
||||
pct_float: Some(-0.0),
|
||||
},
|
||||
CeoShortReport {
|
||||
key: 10,
|
||||
report_date: d_winter,
|
||||
shares_short: 0.0,
|
||||
net_change: Some(0.0),
|
||||
pct_float: Some(0.0),
|
||||
},
|
||||
// Non-finite optional fields nulled and counted
|
||||
CeoShortReport {
|
||||
key: 10,
|
||||
report_date: d_easter,
|
||||
shares_short: 42_000.0,
|
||||
net_change: Some(f64::NEG_INFINITY),
|
||||
pct_float: Some(f64::NAN),
|
||||
},
|
||||
// Invalid shares_short dropped without incrementing optional-field null counters
|
||||
CeoShortReport {
|
||||
key: 30,
|
||||
report_date: d_winter,
|
||||
shares_short: -1.0,
|
||||
net_change: Some(f64::NAN),
|
||||
pct_float: Some(f64::INFINITY),
|
||||
},
|
||||
CeoShortReport {
|
||||
key: 30,
|
||||
report_date: d_summer,
|
||||
shares_short: f64::NAN,
|
||||
net_change: None,
|
||||
pct_float: None,
|
||||
},
|
||||
// Conflicting duplicate group dropped entirely
|
||||
CeoShortReport {
|
||||
key: 40,
|
||||
report_date: d_summer,
|
||||
shares_short: 10_000.0,
|
||||
net_change: Some(500.0),
|
||||
pct_float: None,
|
||||
},
|
||||
CeoShortReport {
|
||||
key: 40,
|
||||
report_date: d_summer,
|
||||
shares_short: 10_000.0,
|
||||
net_change: Some(600.0),
|
||||
pct_float: None,
|
||||
},
|
||||
];
|
||||
|
||||
let built = build_shorts(rows).unwrap();
|
||||
assert_accounting_and_order(&built);
|
||||
assert_eq!(built.stats.rows_in, 8);
|
||||
assert_eq!(built.stats.rows_out, 3);
|
||||
assert_eq!(built.stats.keys_out, 2);
|
||||
assert_eq!(built.stats.dropped_invalid_shares_short, 2);
|
||||
assert_eq!(built.stats.nulled_invalid_net_change, 1);
|
||||
assert_eq!(built.stats.nulled_invalid_pct_float, 1);
|
||||
assert_eq!(built.stats.duplicate_collapsed, 1);
|
||||
assert_eq!(built.stats.duplicate_conflict_dropped, 2);
|
||||
|
||||
assert_eq!(built.rows[0].key, 10);
|
||||
assert_eq!(built.rows[0].known_at_date, day(2024, 1, 5));
|
||||
assert_eq!(
|
||||
built.rows[0].known_at_utc_micros,
|
||||
utc_micros(2024, 1, 5, 22, 0, 0)
|
||||
);
|
||||
assert_eq!(built.rows[0].shares_short.to_bits(), 0.0_f64.to_bits());
|
||||
|
||||
assert_eq!(built.rows[1].key, 10);
|
||||
assert_eq!(built.rows[1].known_at_date, day(2024, 4, 4));
|
||||
assert_eq!(
|
||||
built.rows[1].known_at_utc_micros,
|
||||
utc_micros(2024, 4, 4, 21, 0, 0)
|
||||
);
|
||||
assert_eq!(built.rows[1].net_change, None);
|
||||
assert_eq!(built.rows[1].pct_float, None);
|
||||
|
||||
assert_eq!(built.rows[2].key, 20);
|
||||
assert_eq!(built.rows[2].known_at_date, day(2024, 6, 20));
|
||||
assert_eq!(
|
||||
built.rows[2].known_at_utc_micros,
|
||||
utc_micros(2024, 6, 20, 21, 0, 0)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn permutation_invariance_holds_across_fixed_seed_shuffles() {
|
||||
let dates = [
|
||||
day(2017, 4, 15),
|
||||
day(2020, 12, 31),
|
||||
day(2022, 12, 15),
|
||||
day(2023, 9, 30),
|
||||
day(2024, 3, 15),
|
||||
day(2024, 3, 28),
|
||||
day(2025, 11, 15),
|
||||
day(2026, 4, 30),
|
||||
];
|
||||
|
||||
let mut input = Vec::new();
|
||||
for key in 1..=25_i32 {
|
||||
for (idx, &d) in dates.iter().enumerate() {
|
||||
let base = CeoShortReport {
|
||||
key,
|
||||
report_date: d,
|
||||
shares_short: ((key as usize * 1_000) + idx * 50) as f64,
|
||||
net_change: if idx % 3 == 0 {
|
||||
Some(f64::NAN)
|
||||
} else {
|
||||
Some((idx as f64 - 3.0) * 100.0)
|
||||
},
|
||||
pct_float: if idx % 4 == 0 {
|
||||
Some(f64::INFINITY)
|
||||
} else {
|
||||
Some(0.5 + idx as f64 * 0.25)
|
||||
},
|
||||
};
|
||||
input.push(base.clone());
|
||||
if (key + idx as i32) % 7 == 0 {
|
||||
input.push(base.clone()); // identical duplicate
|
||||
}
|
||||
if (key + idx as i32) % 11 == 0 {
|
||||
let mut conflict = base;
|
||||
conflict.shares_short += 1.0;
|
||||
input.push(conflict); // conflicting duplicate
|
||||
}
|
||||
}
|
||||
if key % 5 == 0 {
|
||||
input.push(CeoShortReport {
|
||||
key,
|
||||
report_date: dates[0],
|
||||
shares_short: -10.0,
|
||||
net_change: Some(f64::NAN),
|
||||
pct_float: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let baseline = build_shorts(input.clone()).unwrap();
|
||||
assert_accounting_and_order(&baseline);
|
||||
assert!(baseline.stats.duplicate_collapsed > 0);
|
||||
assert!(baseline.stats.duplicate_conflict_dropped > 0);
|
||||
assert!(baseline.stats.dropped_invalid_shares_short > 0);
|
||||
assert!(baseline.stats.nulled_invalid_net_change > 0);
|
||||
assert!(baseline.stats.nulled_invalid_pct_float > 0);
|
||||
|
||||
let mut rng = Rng(0x570C_4B07_5404_9999);
|
||||
for _ in 0..16 {
|
||||
let mut perm = input.clone();
|
||||
shuffle(&mut perm, &mut rng);
|
||||
let trial = build_shorts(perm).unwrap();
|
||||
assert_accounting_and_order(&trial);
|
||||
assert_rows_bit_eq(&baseline.rows, &trial.rows);
|
||||
assert_eq!(baseline.stats, trial.stats);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_shorts_benchmark_and_cli_binary_are_reproducible() {
|
||||
let a = run_shorts_benchmark(2_000).unwrap();
|
||||
let b = run_shorts_benchmark(2_000).unwrap();
|
||||
assert_eq!(a.rows, 2_000);
|
||||
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);
|
||||
|
||||
let bin = env!("CARGO_BIN_EXE_curate-etl");
|
||||
let run1 = Command::new(bin)
|
||||
.args(["bench-shorts", "5000"])
|
||||
.output()
|
||||
.expect("run bench-shorts #1");
|
||||
let run2 = Command::new(bin)
|
||||
.args(["bench-shorts", "5000"])
|
||||
.output()
|
||||
.expect("run bench-shorts #2");
|
||||
|
||||
assert!(run1.status.success(), "bench-shorts #1 failed");
|
||||
assert!(run2.status.success(), "bench-shorts #2 failed");
|
||||
|
||||
let out1 = String::from_utf8_lossy(&run1.stdout);
|
||||
let out2 = String::from_utf8_lossy(&run2.stdout);
|
||||
assert!(out1.contains("curate-etl bench-shorts"));
|
||||
assert!(out1.contains("rows/s"));
|
||||
assert!(out1.contains("checksum=0x"));
|
||||
|
||||
let extract_checksum = |s: &str| -> String {
|
||||
s.split("checksum=")
|
||||
.nth(1)
|
||||
.and_then(|rest| rest.split_whitespace().next())
|
||||
.expect("checksum token present")
|
||||
.to_string()
|
||||
};
|
||||
assert_eq!(extract_checksum(&out1), extract_checksum(&out2));
|
||||
|
||||
// Invalid CLI args exit non-zero and mention bench-shorts in usage
|
||||
for bad in [
|
||||
&["bench-shorts", "0"][..],
|
||||
&["bench-shorts", "abc"][..],
|
||||
&["bench-shorts", "10", "20"][..],
|
||||
] {
|
||||
let out = Command::new(bin)
|
||||
.args(bad)
|
||||
.output()
|
||||
.expect("run invalid bench-shorts");
|
||||
assert!(!out.status.success(), "expected failure for {bad:?}");
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(stderr.contains("bench-shorts"));
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue