diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index ce931eda..968f64c1 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -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, 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. +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, the `M1.2f` pure `shorts` (`ceoShorts`) point-in-time builder + Canadian TSX business-day / `America/Toronto` DST calendar, and the `M1.2g` pure `events` (`qmFilings` + `qmEarnings`) point-in-time builder. ## Scope & Sign Conventions @@ -131,6 +131,35 @@ Rules: 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). +## `events` Builder (`M1.2g`) + +`build_events` (`src/events.rs`) turns raw `qmFilings` (`QmFiling`) and `qmEarnings` (`QmEarning`) streams into deterministically sorted point-in-time `EventRow` records matching `events/year=YYYY/part.parquet` in `design/DATA-CONTRACTS.md` (`listing_id, ts, known_at, known_at_source, kind, subtype, payload_json`), plus `partition_year_utc` / `EventRow::partition_year` for UTC `year=YYYY` partitioning. + +Rules: +1. **Filing timestamps (`kind = "filing"`):** + - `parse_filing_timefiled` strictly parses `YYYY-MM-DDTHH:MM:SS EST` (`UTC-5`) and `YYYY-MM-DDTHH:MM:SS EDT` (`UTC-4`). Using the explicit abbreviation's fixed offset avoids DST calendar range limits so pre-2008 filings convert cleanly. + - Emits `ts_micros = known_at_micros = UTC(timefiled)` and `known_at_source = "filing_timestamp"`. + - Malformed strings (`filings_skipped_malformed_timestamp`), missing/unknown zones such as `PST`/`UTC`/`Z` (`filings_skipped_unknown_zone`), and invalid calendar dates or wall-clock times (`filings_skipped_invalid_date_time`) are skipped and counted without panicking. + - *Provenance caveat:* EDGAR filings accepted after `17:30 ET` are converted directly to UTC without next-business-day shifting (per the M1.2g contract); downstream intraday studies should apply exchange-session routing and post-`17:30 ET` visibility rules on top of `known_at_micros`. +2. **Table-driven form groups & periodic-report predicate (`classify_form_type`, `is_periodic_financial_report`):** + - Exact EDGAR codes (checked after stripping optional `/A` amendment suffix so `"4"` never matches `"40-F"`, `"424B5"`, or `"45-106F1"`): `10-K` (`"10-k"`), `10-Q` (`"10-q"`), `8-K` (`"8-k"`), `4` (`"4"`), `144` (`"144"`), `40-F` (`"40-f"`). + - SEDAR+ substring rules in fixed priority order: `Interim financial statements/report` (`"interim_financial_statements"`), `Annual financial statements` (`"annual_financial_statements"`), `MD&A` (`"mda"`), `52-109` (`"52-109"`), `NI 43-101` (`"ni_43_101"`), `45-106F1` (`"45-106f1"`), `News release` (`"news_release"`). Everything else maps to `"other"`. + - Amendments (`/A` or `"amended"`) map to the same group with `is_amendment: true` and the raw `form_type` preserved in `payload_json`. + - `is_periodic_financial_report` is `true` only for `10-K`, `10-Q`, `40-F`, `Interim financial statements`, and `Annual financial statements` (for the M2 `fundamentals_pit` filing join). +3. **Earnings linking & conservative `16:05 ET` lag (`kind = "earnings"`):** + - Precedence: + 1. If the same `key` has a qualifying filing (`8-K` or `News release`, including amendments) whose local ET calendar date matches `report_date` (including late-evening ET filings whose UTC date is the next day), `known_at_micros` = earliest such filing's UTC timestamp (`known_at_source = "filing_timestamp"`, deterministic tie-break on `(filing_id, form_type, url)`). + 2. Otherwise `known_at_micros = report_date 16:05:00 America/Toronto` via `shorts::et_to_utc_micros` (`known_at_source = "statutory_lag_estimate"`, conservative T+1 open). This applies to `N/A`, `BTO`, and `AMC` alike whenever no linked filing provides a real timestamp—unlinked `BTO`/`AMC` rows are never stamped earlier than `16:05 ET`. + 3. Unlinked `report_date` values outside `[MIN_SUPPORTED_DATE, MAX_SUPPORTED_DATE]` (`2008-01-01..=2030-12-31`) are skipped and counted in `earnings_skipped_out_of_range` (pre-2008 dates with a linked same-day filing still succeed). + - `ts_micros = known_at_micros`; `subtype` = normalized announce time (`"bto"` / `"amc"` / `"unknown"`). + - Post-hoc overwritten `consensusEps` is deliberately omitted from `QmEarning` and `payload_json` per `design/DATA-CONTRACTS.md` §1. +4. **Payload JSON, deduplication, sorting & accounting:** + - Hand-written `std`-only RFC 8259 JSON encoder with strict string escaping, non-ASCII UTF-8 passthrough, stable key order, `-0.0` normalized to `0`, and non-finite `f64` (`NaN`/`±inf`) emitted as `null`. + - Exact duplicate filings collapse (`filings_duplicate_collapsed`); identical normalized `(key, report_date)` earnings collapse (`earnings_duplicate_collapsed`) and conflicting `(key, report_date)` groups drop entirely (`earnings_duplicate_conflict_dropped`). + - Output rows are sorted deterministically by `(key, ts_micros, kind, subtype, payload_json, known_at_micros, known_at_source)` and `EventsStats` reconciles exactly per kind (`filings_in == filings_out + skips + dup`, `earnings_in == earnings_out + oor + dup + conflict`, `earnings_out == linked + lagged`, `rows_out == filings_out + earnings_out`). + +Deferred out of `src/events.rs`: MongoDB `qmFilings` / `qmEarnings` BSON cursors, `provider_mapping` `listing_id` resolution, Zstd Parquet writing, and M2 `fundamentals_pit` joins. + ## Local Benchmarks ### `bench-split` @@ -217,7 +246,22 @@ Command: `cargo run --release -p curate-etl --offline -- bench-shorts` - 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`) +### `bench-events` + +Fixed-seed (`std`-only SplitMix64) benchmark over `500,000` synthetic rows (~98.5% `qmFilings`, ~1.5% `qmEarnings`, mirroring `30.52M` filings / `444.9k` earnings) across `20,000` `i32` `listing_id` keys with EST/EDT/pre-2008/late-evening timestamps, all EDGAR/SEDAR+ form groups, linked + unlinked earnings, and injected malformed/skipped/duplicate/conflicting rows, timing only `build_events`: + +```bash +cargo run --release -p curate-etl --offline -- bench-events [rows] +``` + +Command: `cargo run --release -p curate-etl --offline -- bench-events` + +- Input: `rows=500000`, `filings=492500`, `earnings=7500`, `keys=20000` +- Build: `rows_out=491190`, `filings_out=484531`, `earnings_out=6659`, `keys_out=20000`, `elapsed=268.55 ms`, `throughput=1861871 rows/s`, `latency=537.09 ns/row`, `checksum=0xbf74cd745a2646c6` (identical across back-to-back runs) +- Stats: `malformed_ts=1525`, `unknown_zone=1496`, `invalid_dt=2476`, `filing_dup=2472`, `linked=2569`, `lagged_1605=4090`, `earnings_oor=37`, `earnings_dup=98`, `earnings_conflict=706` +- Extrapolation to full `30.52M` `qmFilings` + `444.9k` `qmEarnings` (`30,964,900` rows): ~`16.6 s` single-threaded CPU time (excluding MongoDB BSON streaming and Zstd Parquet I/O). + +## Deferred Follow-Ups (`M1.3+` / `M2`) This crate currently uses `std` only so it builds strictly offline. Follow-up tasks (IO wiring and crates.io dependencies) will add: diff --git a/tools/curate-etl/src/bench.rs b/tools/curate-etl/src/bench.rs index 189b9895..5674eb69 100644 --- a/tools/curate-etl/src/bench.rs +++ b/tools/curate-etl/src/bench.rs @@ -9,8 +9,9 @@ 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, CeoShortReport, ShortsError, ShortsStats}; +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; @@ -20,6 +21,7 @@ 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; @@ -30,6 +32,7 @@ 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). @@ -1115,6 +1118,257 @@ pub fn run_shorts_benchmark(rows: usize) -> Result 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::(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> = 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> = 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> = Vec::with_capacity(earnings_target); + let mut last_valid_earning: Option> = 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::*; @@ -1367,4 +1621,45 @@ mod tests { 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); + } } diff --git a/tools/curate-etl/src/cli.rs b/tools/curate-etl/src/cli.rs index 70dfa3fe..22cbe685 100644 --- a/tools/curate-etl/src/cli.rs +++ b/tools/curate-etl/src/cli.rs @@ -5,7 +5,8 @@ use crate::bench::{ DEFAULT_ADJ_BENCH_EVENTS, DEFAULT_BARS_BENCH_ROWS, DEFAULT_BENCH_ROWS, - DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS, DEFAULT_FX_BENCH_ROWS, DEFAULT_SHORTS_BENCH_ROWS, + DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS, DEFAULT_EVENTS_BENCH_ROWS, DEFAULT_FX_BENCH_ROWS, + DEFAULT_SHORTS_BENCH_ROWS, }; /// Parsed CLI command to execute. @@ -19,6 +20,7 @@ pub enum CliAction { BenchBars(usize), BenchFx(usize), BenchShorts(usize), + BenchEvents(usize), } /// Formats full help text including binary name and version. @@ -34,7 +36,8 @@ pub fn format_usage(name: &str, version: &str) -> String { {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})\n\ - {name} bench-shorts [rows] Run fixed-seed shorts build benchmark (default: {DEFAULT_SHORTS_BENCH_ROWS})" + {name} bench-shorts [rows] Run fixed-seed shorts build benchmark (default: {DEFAULT_SHORTS_BENCH_ROWS})\n\ + {name} bench-events [rows] Run fixed-seed events build benchmark (default: {DEFAULT_EVENTS_BENCH_ROWS})" ) } @@ -49,7 +52,8 @@ pub fn format_usage_stderr(name: &str) -> String { {name} bench-corporate-actions [events]\n\ {name} bench-bars [rows]\n\ {name} bench-fx [rows]\n\ - {name} bench-shorts [rows]" + {name} bench-shorts [rows]\n\ + {name} bench-events [rows]" ) } @@ -114,6 +118,14 @@ pub fn parse_args(args: &[String]) -> Result { )), }, ["bench-shorts", _, ..] => Err("too many arguments for bench-shorts".to_string()), + ["bench-events"] => Ok(CliAction::BenchEvents(DEFAULT_EVENTS_BENCH_ROWS)), + ["bench-events", raw] => match raw.parse::() { + Ok(n) if n > 0 => Ok(CliAction::BenchEvents(n)), + _ => Err(format!( + "invalid row count '{raw}' (expected a positive integer)" + )), + }, + ["bench-events", _, ..] => Err("too many arguments for bench-events".to_string()), [other, ..] => Err(format!("unknown argument '{other}'")), } } @@ -247,6 +259,22 @@ mod tests { assert!(parse_args(&to_args(&["bench-shorts", "10", "20"])).is_err()); } + #[test] + fn parses_and_validates_bench_events_args() { + assert_eq!( + parse_args(&to_args(&["bench-events"])), + Ok(CliAction::BenchEvents(DEFAULT_EVENTS_BENCH_ROWS)) + ); + assert_eq!( + parse_args(&to_args(&["bench-events", "50000"])), + Ok(CliAction::BenchEvents(50_000)) + ); + assert!(parse_args(&to_args(&["bench-events", "0"])).is_err()); + assert!(parse_args(&to_args(&["bench-events", "-5"])).is_err()); + assert!(parse_args(&to_args(&["bench-events", "abc"])).is_err()); + assert!(parse_args(&to_args(&["bench-events", "10", "20"])).is_err()); + } + #[test] fn usage_strings_mention_all_benchmarks() { let full = format_usage("curate-etl", "0.1.0"); @@ -256,6 +284,7 @@ mod tests { assert!(full.contains("bench-bars")); assert!(full.contains("bench-fx")); assert!(full.contains("bench-shorts")); + assert!(full.contains("bench-events")); let short = format_usage_stderr("curate-etl"); assert!(short.contains("bench-split")); @@ -264,5 +293,6 @@ mod tests { assert!(short.contains("bench-bars")); assert!(short.contains("bench-fx")); assert!(short.contains("bench-shorts")); + assert!(short.contains("bench-events")); } } diff --git a/tools/curate-etl/src/events.rs b/tools/curate-etl/src/events.rs new file mode 100644 index 00000000..d585a6de --- /dev/null +++ b/tools/curate-etl/src/events.rs @@ -0,0 +1,1071 @@ +//! Pure, in-memory `events` builder (`qmFilings` `timefiled` → UTC + form groups; `qmEarnings` +//! linked to same-day `8-K` / `News release` filing or conservatively lagged to `16:05 ET`). +//! +//! Produces deterministically sorted [`EventRow`] records matching `events/year=YYYY/part.parquet` +//! in `design/DATA-CONTRACTS.md` (`listing_id, ts, known_at, known_at_source, kind, subtype, +//! payload_json`), plus [`partition_year_utc`] / [`EventRow::partition_year`] for `year=YYYY` +//! partitioning. +//! +//! ## Point-in-time & Provenance Rules +//! - **Filings (`kind = "filing"`):** `timefiled` is parsed strictly as `YYYY-MM-DDTHH:MM:SS EST` +//! (`UTC-5`) or `YYYY-MM-DDTHH:MM:SS EDT` (`UTC-4`). Using the explicit zone abbreviation's +//! fixed offset avoids DST calendar range limits so pre-2008 filings convert cleanly. +//! `ts_micros = known_at_micros = UTC(timefiled)` with `known_at_source = "filing_timestamp"`. +//! *Caveat:* EDGAR filings accepted after `17:30 ET` are not shifted to the next business day +//! here (per the M1.2g contract); downstream intraday studies should apply exchange-session +//! routing / post-`17:30 ET` visibility rules on top of `known_at_micros`. +//! - **Earnings (`kind = "earnings"`):** +//! 1. If the same `key` has a qualifying filing (`8-K` or `News release`, including amendments) +//! whose local ET calendar date matches `report_date`, `known_at_micros` is the earliest such +//! filing's UTC timestamp (`known_at_source = "filing_timestamp"`). +//! 2. Otherwise `known_at_micros = report_date 16:05:00 America/Toronto` via +//! [`crate::shorts::et_to_utc_micros`] (`known_at_source = "statutory_lag_estimate"`, +//! tradable T+1 open). This conservative fallback applies to `N/A`, `BTO`, and `AMC` rows +//! alike whenever no linked filing provides a verified timestamp—unlinked `BTO`/`AMC` rows +//! are never stamped earlier than `16:05 ET`. +//! 3. Unlinked `report_date` values outside `[MIN_SUPPORTED_DATE, MAX_SUPPORTED_DATE]` +//! (`2008-01-01..=2030-12-31`) are skipped and counted (`earnings_skipped_out_of_range`). +//! 4. Post-hoc overwritten `consensusEps` is deliberately omitted from [`QmEarning`] and +//! earnings `payload_json` per `design/DATA-CONTRACTS.md` §1. + +use std::error::Error; +use std::fmt::{self, Write as _}; + +use crate::shorts::{epoch_days_to_ymd, et_to_utc_micros}; +use crate::split::ymd_to_epoch_days; + +/// Canonical `kind` label for `qmFilings` rows. +pub const EVENT_KIND_FILING: &str = "filing"; + +/// Canonical `kind` label for `qmEarnings` rows. +pub const EVENT_KIND_EARNINGS: &str = "earnings"; + +/// Provenance label when `known_at_micros` comes directly from a parsed `qmFilings.timefiled`. +pub const KNOWN_AT_SOURCE_FILING_TIMESTAMP: &str = "filing_timestamp"; + +/// Provenance label when an unlinked earnings row falls back to `report_date 16:05 ET`. +pub const KNOWN_AT_SOURCE_STATUTORY_LAG: &str = "statutory_lag_estimate"; + +/// Conservative fallback hour (`16:05 America/Toronto`) for unlinked earnings rows. +pub const EARNINGS_FALLBACK_HOUR_ET: u8 = 16; + +/// Conservative fallback minute (`16:05 America/Toronto`) for unlinked earnings rows. +pub const EARNINGS_FALLBACK_MINUTE_ET: u8 = 5; + +const MICROS_PER_DAY: i64 = 86_400_000_000; + +/// Returns the UTC Gregorian calendar year for `ts_micros` (microseconds since +/// `1970-01-01T00:00:00Z`), used for `events/year=YYYY/part.parquet` partitioning. +#[inline] +pub fn partition_year_utc(ts_micros: i64) -> i32 { + let epoch_day = ts_micros.div_euclid(MICROS_PER_DAY) as i32; + epoch_days_to_ymd(epoch_day).0 +} + +/// Typed parse errors returned by [`parse_filing_timefiled`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FilingTimeError { + /// Input did not match the exact 19-byte ASCII `YYYY-MM-DDTHH:MM:SS` prefix structure. + MalformedFormat, + /// Input had a valid timestamp prefix but was missing a zone or used a zone other than + /// `" EST"` or `" EDT"`. + UnknownZone, + /// Calendar date components were not a valid Gregorian date (e.g., `2025-02-30`). + InvalidDate, + /// Clock components were outside `00:00:00..=23:59:59`. + InvalidTime, +} + +impl fmt::Display for FilingTimeError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + Self::MalformedFormat => { + write!(f, "malformed filing timestamp (expected YYYY-MM-DDTHH:MM:SS EST|EDT)") + } + Self::UnknownZone => { + write!(f, "missing or unsupported filing time zone (expected ' EST' or ' EDT')") + } + Self::InvalidDate => write!(f, "invalid Gregorian calendar date in filing timestamp"), + Self::InvalidTime => { + write!(f, "invalid wall-clock time in filing timestamp (expected 00:00:00..=23:59:59)") + } + } + } +} + +impl Error for FilingTimeError {} + +/// Parsed `qmFilings.timefiled` carrying both the UTC instant and the local ET calendar date. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ParsedFilingTime { + /// UTC timestamp in microseconds since `1970-01-01T00:00:00Z`. + pub utc_micros: i64, + /// Local Eastern Time calendar date as days since `1970-01-01` (used for same-day earnings + /// linking even when late-evening ET crosses into the next UTC calendar day). + pub et_date: i32, +} + +#[inline] +fn parse_2_digits(bytes: &[u8], offset: usize) -> Option { + let a = bytes[offset]; + let b = bytes[offset + 1]; + if a.is_ascii_digit() && b.is_ascii_digit() { + Some(u32::from(a - b'0') * 10 + u32::from(b - b'0')) + } else { + None + } +} + +#[inline] +fn parse_4_digits(bytes: &[u8], offset: usize) -> Option { + let hi = parse_2_digits(bytes, offset)?; + let lo = parse_2_digits(bytes, offset + 2)?; + Some((hi * 100 + lo) as i32) +} + +/// Strictly parses a `qmFilings.timefiled` string of the form `YYYY-MM-DDTHH:MM:SS EST` or +/// `YYYY-MM-DDTHH:MM:SS EDT`. +/// +/// Uses the explicit zone abbreviation's fixed offset (`EST = UTC-5`, `EDT = UTC-4`) so historical +/// pre-2008 filings convert without DST table range restrictions. Never panics and never guesses +/// on malformed strings, unknown zones, or invalid calendar dates/times. +pub fn parse_filing_timefiled(raw: &str) -> Result { + let bytes = raw.as_bytes(); + if bytes.len() < 19 + || bytes[4] != b'-' + || bytes[7] != b'-' + || bytes[10] != b'T' + || bytes[13] != b':' + || bytes[16] != b':' + { + return Err(FilingTimeError::MalformedFormat); + } + + let year = parse_4_digits(bytes, 0).ok_or(FilingTimeError::MalformedFormat)?; + let month = parse_2_digits(bytes, 5).ok_or(FilingTimeError::MalformedFormat)?; + let day = parse_2_digits(bytes, 8).ok_or(FilingTimeError::MalformedFormat)?; + let hour = parse_2_digits(bytes, 11).ok_or(FilingTimeError::MalformedFormat)?; + let minute = parse_2_digits(bytes, 14).ok_or(FilingTimeError::MalformedFormat)?; + let second = parse_2_digits(bytes, 17).ok_or(FilingTimeError::MalformedFormat)?; + + let offset_hours: i64 = match &bytes[19..] { + b" EST" => 5, + b" EDT" => 4, + _ => return Err(FilingTimeError::UnknownZone), + }; + + let et_date = ymd_to_epoch_days(year, month, day).map_err(|_| FilingTimeError::InvalidDate)?; + if hour > 23 || minute > 59 || second > 59 { + return Err(FilingTimeError::InvalidTime); + } + + let local_secs = i64::from(hour) * 3_600 + i64::from(minute) * 60 + i64::from(second); + let utc_secs = i64::from(et_date) * 86_400 + local_secs + offset_hours * 3_600; + Ok(ParsedFilingTime { + utc_micros: utc_secs * 1_000_000, + et_date, + }) +} + +/// Canonical form-group classification for US EDGAR and Canadian SEDAR+ filings. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum FilingFormGroup { + Form10K, + Form10Q, + Form8K, + Form4, + Form144, + Form40F, + InterimFinancials, + AnnualFinancials, + Mda, + Form52109, + Ni43101, + Form45106F1, + NewsRelease, + Other, +} + +impl FilingFormGroup { + /// Canonical lowercase `subtype` string written to [`EventRow::subtype`]. + #[inline] + pub const fn as_str(self) -> &'static str { + match self { + Self::Form10K => "10-k", + Self::Form10Q => "10-q", + Self::Form8K => "8-k", + Self::Form4 => "4", + Self::Form144 => "144", + Self::Form40F => "40-f", + Self::InterimFinancials => "interim_financial_statements", + Self::AnnualFinancials => "annual_financial_statements", + Self::Mda => "mda", + Self::Form52109 => "52-109", + Self::Ni43101 => "ni_43_101", + Self::Form45106F1 => "45-106f1", + Self::NewsRelease => "news_release", + Self::Other => "other", + } + } + + /// Returns `true` iff this form group is a periodic financial report eligible for the M2 + /// `fundamentals_pit` filing join (`10-K`, `10-Q`, `40-F`, `Interim financial statements`, + /// `Annual financial statements`). + #[inline] + pub const fn is_periodic_financial_report(self) -> bool { + matches!( + self, + Self::Form10K + | Self::Form10Q + | Self::Form40F + | Self::InterimFinancials + | Self::AnnualFinancials + ) + } + + /// Returns `true` iff this form group may anchor a same-day `qmEarnings` announcement time + /// (`8-K` or `News release`). + #[inline] + pub const fn is_earnings_link_candidate(self) -> bool { + matches!(self, Self::Form8K | Self::NewsRelease) + } +} + +/// Exact-match EDGAR form table (checked after stripping optional `/A` amendment suffix). +/// Keeping EDGAR codes exact prevents `"4"` from falsely matching `"40-F"`, `"424B5"`, or +/// `"45-106F1"`. +const EXACT_EDGAR_FORM_RULES: &[(&str, FilingFormGroup)] = &[ + ("10-K", FilingFormGroup::Form10K), + ("10-Q", FilingFormGroup::Form10Q), + ("8-K", FilingFormGroup::Form8K), + ("4", FilingFormGroup::Form4), + ("144", FilingFormGroup::Form144), + ("40-F", FilingFormGroup::Form40F), +]; + +/// Fixed-priority substring rules for Canadian SEDAR+ filing descriptions. +const SEDAR_SUBSTRING_RULES: &[(&str, FilingFormGroup)] = &[ + ("INTERIM FINANCIAL STATEMENTS", FilingFormGroup::InterimFinancials), + ("INTERIM FINANCIAL REPORT", FilingFormGroup::InterimFinancials), + ("ANNUAL FINANCIAL STATEMENTS", FilingFormGroup::AnnualFinancials), + ("MD&A", FilingFormGroup::Mda), + ("MANAGEMENT'S DISCUSSION AND ANALYSIS", FilingFormGroup::Mda), + ("52-109", FilingFormGroup::Form52109), + ("43-101", FilingFormGroup::Ni43101), + ("45-106F1", FilingFormGroup::Form45106F1), + ("NEWS RELEASE", FilingFormGroup::NewsRelease), +]; + +/// Classifies a raw `qmFilings.form_type` into `(FilingFormGroup, is_amendment)`. +/// +/// - Trims ASCII whitespace and compares case-insensitively. +/// - Detects `/A` suffixes (e.g. `10-K/A`, `8-K/A`, `40-F/A`) and `"amended"` markers while +/// mapping amendments to the same underlying [`FilingFormGroup`]. +/// - Checks exact EDGAR codes first, then SEDAR+ substring rules in fixed priority order, +/// defaulting to [`FilingFormGroup::Other`]. +pub fn classify_form_type(form_type: &str) -> (FilingFormGroup, bool) { + let trimmed = form_type.trim(); + if trimmed.is_empty() { + return (FilingFormGroup::Other, false); + } + + let upper = trimmed.to_ascii_uppercase(); + let (base, has_slash_a) = match upper.strip_suffix("/A") { + Some(prefix) => (prefix.trim_end(), true), + None => (upper.as_str(), false), + }; + let is_amendment = has_slash_a || upper.contains("AMENDED"); + + for &(code, group) in EXACT_EDGAR_FORM_RULES { + if base == code { + return (group, is_amendment); + } + } + + for &(needle, group) in SEDAR_SUBSTRING_RULES { + if base.contains(needle) { + return (group, is_amendment); + } + } + + (FilingFormGroup::Other, is_amendment) +} + +/// Convenience predicate returning `true` iff `form_type` classifies as a periodic financial +/// report (`10-K`, `10-Q`, `40-F`, `Interim financial statements`, `Annual financial statements`, +/// including amendments). +#[inline] +pub fn is_periodic_financial_report(form_type: &str) -> bool { + classify_form_type(form_type) + .0 + .is_periodic_financial_report() +} + +/// Normalizes `qmEarnings.announceTime` into `"bto"`, `"amc"`, or `"unknown"`. +#[inline] +pub fn normalize_announce_time(raw: &str) -> &'static str { + let trimmed = raw.trim(); + if trimmed.eq_ignore_ascii_case("bto") { + "bto" + } else if trimmed.eq_ignore_ascii_case("amc") { + "amc" + } else { + "unknown" + } +} + +/// A single raw `qmFilings` input record. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct QmFiling { + pub key: K, + /// Raw Eastern timestamp string, e.g. `"2025-01-31T06:01:27 EST"`. + pub timefiled: String, + /// Raw EDGAR or SEDAR+ form type string, e.g. `"10-K/A"` or `"News release"`. + pub form_type: String, + /// Optional provider filing / accession identifier included in `payload_json`. + pub filing_id: Option, + /// Optional filing document URL included in `payload_json`. + pub url: Option, +} + +/// A single raw `qmEarnings` input record. +/// +/// Deliberately omits `consensusEps`, which is overwritten post-hoc in `qmEarnings` per +/// `design/DATA-CONTRACTS.md` §1 and is not point-in-time safe. +#[derive(Debug, Clone, PartialEq)] +pub struct QmEarning { + pub key: K, + /// Earnings report calendar date (ET) as days since `1970-01-01` (UTC Gregorian). + pub report_date: i32, + /// Raw provider announce-time code (`"BTO"`, `"AMC"`, `"N/A"`, etc.). + pub announce_time: String, + /// Optional fiscal period end date as days since `1970-01-01`. + pub fiscal_period_end: Option, + /// Optional reported actual EPS (non-finite values emit as `null` in `payload_json`). + pub actual_eps: Option, + /// Optional reported revenue (non-finite values emit as `null` in `payload_json`). + pub revenue: Option, +} + +/// A single curated `events` row matching `events/year=YYYY/part.parquet`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EventRow { + pub key: K, + /// Event timestamp in UTC microseconds since `1970-01-01T00:00:00Z`. + pub ts_micros: i64, + /// Point-in-time availability timestamp in UTC microseconds since `1970-01-01T00:00:00Z`. + pub known_at_micros: i64, + /// Provenance of `known_at_micros` (`"filing_timestamp"` or `"statutory_lag_estimate"`). + pub known_at_source: &'static str, + /// Event category (`"filing"` or `"earnings"`). + pub kind: &'static str, + /// Normalized form group (filings) or announce time (`"bto"` / `"amc"` / `"unknown"`, earnings). + pub subtype: String, + /// Compact RFC 8259 JSON object with stable key ordering. + pub payload_json: String, +} + +impl EventRow { + /// Returns the UTC Gregorian partition year of [`Self::ts_micros`] (`year=YYYY`). + #[inline] + pub fn partition_year(&self) -> i32 { + partition_year_utc(self.ts_micros) + } +} + +/// Exact per-kind accounting counters produced alongside [`EventsBuild::rows`]. +/// +/// Conservation invariants: +/// - `filings_in == filings_out + filings_skipped_malformed_timestamp + filings_skipped_unknown_zone + filings_skipped_invalid_date_time + filings_duplicate_collapsed` +/// - `earnings_in == earnings_out + earnings_skipped_out_of_range + earnings_duplicate_collapsed + earnings_duplicate_conflict_dropped` +/// - `earnings_out == earnings_linked_to_filing + earnings_lagged_1605` +/// - `rows_out == filings_out + earnings_out` +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct EventsStats { + pub filings_in: usize, + pub filings_out: usize, + pub filings_skipped_malformed_timestamp: usize, + pub filings_skipped_unknown_zone: usize, + pub filings_skipped_invalid_date_time: usize, + pub filings_duplicate_collapsed: usize, + pub earnings_in: usize, + pub earnings_out: usize, + pub earnings_linked_to_filing: usize, + pub earnings_lagged_1605: usize, + pub earnings_skipped_out_of_range: usize, + pub earnings_duplicate_collapsed: usize, + pub earnings_duplicate_conflict_dropped: usize, + pub rows_out: usize, + pub keys_out: usize, +} + +/// Output of [`build_events`]: deterministically sorted `events` rows and reconciling stats. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EventsBuild { + pub rows: Vec>, + pub stats: EventsStats, +} + +#[inline] +fn sanitize_opt_f64(value: Option) -> Option { + match value { + Some(v) if v.is_finite() => Some(if v == 0.0 { 0.0 } else { v }), + _ => None, + } +} + +const HEX_LOWER: &[u8; 16] = b"0123456789abcdef"; + +fn push_json_str(out: &mut String, s: &str) { + out.push('"'); + let bytes = s.as_bytes(); + let mut start = 0usize; + for (idx, &b) in bytes.iter().enumerate() { + let escaped = match b { + b'"' => Some("\\\""), + b'\\' => Some("\\\\"), + 0x08 => Some("\\b"), + 0x0C => Some("\\f"), + b'\n' => Some("\\n"), + b'\r' => Some("\\r"), + b'\t' => Some("\\t"), + 0x00..=0x1F => { + if start < idx { + out.push_str(&s[start..idx]); + } + out.push_str("\\u00"); + out.push(HEX_LOWER[(b >> 4) as usize] as char); + out.push(HEX_LOWER[(b & 0x0F) as usize] as char); + start = idx + 1; + continue; + } + _ => None, + }; + if let Some(esc) = escaped { + if start < idx { + out.push_str(&s[start..idx]); + } + out.push_str(esc); + start = idx + 1; + } + } + if start < bytes.len() { + out.push_str(&s[start..]); + } + out.push('"'); +} + +#[inline] +fn push_json_opt_str(out: &mut String, s: Option<&str>) { + match s { + Some(v) => push_json_str(out, v), + None => out.push_str("null"), + } +} + +#[inline] +fn push_json_opt_f64(out: &mut String, v: Option) { + match sanitize_opt_f64(v) { + Some(x) => { + let _ = write!(out, "{x}"); + } + None => out.push_str("null"), + } +} + +#[inline] +fn push_json_date(out: &mut String, epoch_day: i32) { + let (y, m, d) = epoch_days_to_ymd(epoch_day); + let _ = write!(out, "\"{y:04}-{m:02}-{d:02}\""); +} + +#[inline] +fn push_json_opt_date(out: &mut String, epoch_day: Option) { + match epoch_day { + Some(d) => push_json_date(out, d), + None => out.push_str("null"), + } +} + +/// Encodes a filing event's `payload_json` as a compact RFC 8259 JSON object with stable key +/// ordering: `{"filing_id":...,"form_type":...,"is_amendment":...,"url":...}`. +pub fn encode_filing_payload_json( + filing_id: Option<&str>, + form_type: &str, + is_amendment: bool, + url: Option<&str>, +) -> String { + let cap = 56 + + filing_id.map_or(4, str::len) + + form_type.len() + + url.map_or(4, str::len); + let mut out = String::with_capacity(cap); + out.push_str("{\"filing_id\":"); + push_json_opt_str(&mut out, filing_id); + out.push_str(",\"form_type\":"); + push_json_str(&mut out, form_type); + out.push_str(",\"is_amendment\":"); + out.push_str(if is_amendment { "true" } else { "false" }); + out.push_str(",\"url\":"); + push_json_opt_str(&mut out, url); + out.push('}'); + out +} + +/// Encodes an earnings event's `payload_json` as a compact RFC 8259 JSON object with stable key +/// ordering: +/// `{"actual_eps":...,"announce_time":...,"fiscal_period_end":...,"linked_filing_id":...,"report_date":"YYYY-MM-DD","revenue":...}`. +/// +/// Non-finite numeric values emit as `null`, `-0.0` normalizes to `0.0`, and `consensusEps` is +/// deliberately omitted. +pub fn encode_earnings_payload_json( + actual_eps: Option, + announce_time: &str, + fiscal_period_end: Option, + linked_filing_id: Option<&str>, + report_date: i32, + revenue: Option, +) -> String { + let cap = 112 + announce_time.len() + linked_filing_id.map_or(4, str::len); + let mut out = String::with_capacity(cap); + out.push_str("{\"actual_eps\":"); + push_json_opt_f64(&mut out, actual_eps); + out.push_str(",\"announce_time\":"); + push_json_str(&mut out, announce_time); + out.push_str(",\"fiscal_period_end\":"); + push_json_opt_date(&mut out, fiscal_period_end); + out.push_str(",\"linked_filing_id\":"); + push_json_opt_str(&mut out, linked_filing_id); + out.push_str(",\"report_date\":"); + push_json_date(&mut out, report_date); + out.push_str(",\"revenue\":"); + push_json_opt_f64(&mut out, revenue); + out.push('}'); + out +} + +struct QualifyingLink { + key: K, + et_date: i32, + utc_micros: i64, + filing_id: Option, + form_type: String, + url: Option, +} + +struct NormalizedEarning { + key: K, + report_date: i32, + ts_micros: i64, + known_at_source: &'static str, + is_linked: bool, + link_idx: Option, + subtype: &'static str, + fiscal_period_end: Option, + actual_eps: Option, + revenue: Option, +} + +impl NormalizedEarning { + #[inline] + fn values_bit_eq(&self, other: &Self) -> bool { + self.subtype == other.subtype + && self.fiscal_period_end == other.fiscal_period_end + && self.actual_eps.map(f64::to_bits) == other.actual_eps.map(f64::to_bits) + && self.revenue.map(f64::to_bits) == other.revenue.map(f64::to_bits) + } +} + +/// Builds deterministically sorted point-in-time `events` rows from raw `qmFilings` and +/// `qmEarnings` streams. +/// +/// Infallible: malformed timestamps, unknown zones, invalid dates/times, and out-of-range +/// unlinked earnings dates are counted in [`EventsStats`] and skipped without panicking. +/// Any permutation of `filings` and `earnings` produces identical `rows` and `stats`. +pub fn build_events(filings: IF, earnings: IE) -> EventsBuild +where + K: Ord + Clone, + IF: IntoIterator>, + IE: IntoIterator>, +{ + let filings_iter = filings.into_iter(); + let (filings_lower, _) = filings_iter.size_hint(); + let mut stats = EventsStats::default(); + let mut rows: Vec> = Vec::with_capacity(filings_lower); + let mut links: Vec> = Vec::new(); + + for filing in filings_iter { + stats.filings_in += 1; + + let parsed = match parse_filing_timefiled(&filing.timefiled) { + Ok(p) => p, + Err(FilingTimeError::MalformedFormat) => { + stats.filings_skipped_malformed_timestamp += 1; + continue; + } + Err(FilingTimeError::UnknownZone) => { + stats.filings_skipped_unknown_zone += 1; + continue; + } + Err(FilingTimeError::InvalidDate | FilingTimeError::InvalidTime) => { + stats.filings_skipped_invalid_date_time += 1; + continue; + } + }; + + let (group, is_amendment) = classify_form_type(&filing.form_type); + let payload_json = encode_filing_payload_json( + filing.filing_id.as_deref(), + &filing.form_type, + is_amendment, + filing.url.as_deref(), + ); + + if group.is_earnings_link_candidate() { + links.push(QualifyingLink { + key: filing.key.clone(), + et_date: parsed.et_date, + utc_micros: parsed.utc_micros, + filing_id: filing.filing_id, + form_type: filing.form_type, + url: filing.url, + }); + } + + rows.push(EventRow { + key: filing.key, + ts_micros: parsed.utc_micros, + known_at_micros: parsed.utc_micros, + known_at_source: KNOWN_AT_SOURCE_FILING_TIMESTAMP, + kind: EVENT_KIND_FILING, + subtype: group.as_str().to_string(), + payload_json, + }); + } + + // Retain the strictly earliest deterministic qualifying filing per (key, et_date). + links.sort_unstable_by(|a, b| { + a.key + .cmp(&b.key) + .then_with(|| a.et_date.cmp(&b.et_date)) + .then_with(|| a.utc_micros.cmp(&b.utc_micros)) + .then_with(|| a.filing_id.cmp(&b.filing_id)) + .then_with(|| a.form_type.cmp(&b.form_type)) + .then_with(|| a.url.cmp(&b.url)) + }); + links.dedup_by(|later, earlier| earlier.key == later.key && earlier.et_date == later.et_date); + + // Collapse exact duplicate filing rows. + rows.sort_unstable_by(|a, b| { + a.key + .cmp(&b.key) + .then_with(|| a.ts_micros.cmp(&b.ts_micros)) + .then_with(|| a.subtype.cmp(&b.subtype)) + .then_with(|| a.payload_json.cmp(&b.payload_json)) + }); + let filings_before_dedup = rows.len(); + rows.dedup_by(|b, a| { + a.key == b.key + && a.ts_micros == b.ts_micros + && a.subtype == b.subtype + && a.payload_json == b.payload_json + }); + stats.filings_duplicate_collapsed = filings_before_dedup - rows.len(); + stats.filings_out = rows.len(); + + // Scan and resolve earnings rows against qualifying links or 16:05 ET fallback. + let earnings_iter = earnings.into_iter(); + let (earnings_lower, _) = earnings_iter.size_hint(); + let mut norm_earnings: Vec> = Vec::with_capacity(earnings_lower); + + for earning in earnings_iter { + stats.earnings_in += 1; + + let link_lookup = links.binary_search_by(|l| { + l.key + .cmp(&earning.key) + .then_with(|| l.et_date.cmp(&earning.report_date)) + }); + + let (ts_micros, known_at_source, is_linked, link_idx) = match link_lookup { + Ok(idx) => ( + links[idx].utc_micros, + KNOWN_AT_SOURCE_FILING_TIMESTAMP, + true, + Some(idx), + ), + Err(_) => match et_to_utc_micros( + earning.report_date, + EARNINGS_FALLBACK_HOUR_ET, + EARNINGS_FALLBACK_MINUTE_ET, + 0, + ) { + Ok(utc) => (utc, KNOWN_AT_SOURCE_STATUTORY_LAG, false, None), + Err(_) => { + stats.earnings_skipped_out_of_range += 1; + continue; + } + }, + }; + + norm_earnings.push(NormalizedEarning { + key: earning.key, + report_date: earning.report_date, + ts_micros, + known_at_source, + is_linked, + link_idx, + subtype: normalize_announce_time(&earning.announce_time), + fiscal_period_end: earning.fiscal_period_end, + actual_eps: sanitize_opt_f64(earning.actual_eps), + revenue: sanitize_opt_f64(earning.revenue), + }); + } + + norm_earnings.sort_unstable_by(|a, b| { + a.key + .cmp(&b.key) + .then_with(|| a.report_date.cmp(&b.report_date)) + }); + + rows.reserve(norm_earnings.len()); + let len = norm_earnings.len(); + let mut read_idx = 0usize; + while read_idx < len { + let mut group_end = read_idx + 1; + while group_end < len + && norm_earnings[group_end].key == norm_earnings[read_idx].key + && norm_earnings[group_end].report_date == norm_earnings[read_idx].report_date + { + group_end += 1; + } + + let group_len = group_end - read_idx; + let first = &norm_earnings[read_idx]; + let all_identical = norm_earnings[read_idx + 1..group_end] + .iter() + .all(|other| first.values_bit_eq(other)); + + if all_identical { + stats.earnings_duplicate_collapsed += group_len - 1; + if first.is_linked { + stats.earnings_linked_to_filing += 1; + } else { + stats.earnings_lagged_1605 += 1; + } + + let linked_filing_id = first + .link_idx + .and_then(|idx| links[idx].filing_id.as_deref()); + let payload_json = encode_earnings_payload_json( + first.actual_eps, + first.subtype, + first.fiscal_period_end, + linked_filing_id, + first.report_date, + first.revenue, + ); + rows.push(EventRow { + key: first.key.clone(), + ts_micros: first.ts_micros, + known_at_micros: first.ts_micros, + known_at_source: first.known_at_source, + kind: EVENT_KIND_EARNINGS, + subtype: first.subtype.to_string(), + payload_json, + }); + } else { + stats.earnings_duplicate_conflict_dropped += group_len; + } + + read_idx = group_end; + } + + stats.earnings_out = stats.earnings_linked_to_filing + stats.earnings_lagged_1605; + + rows.sort_unstable_by(|a, b| { + a.key + .cmp(&b.key) + .then_with(|| a.ts_micros.cmp(&b.ts_micros)) + .then_with(|| a.kind.cmp(b.kind)) + .then_with(|| a.subtype.cmp(&b.subtype)) + .then_with(|| a.payload_json.cmp(&b.payload_json)) + .then_with(|| a.known_at_micros.cmp(&b.known_at_micros)) + .then_with(|| a.known_at_source.cmp(b.known_at_source)) + }); + + stats.rows_out = rows.len(); + let mut keys_out = 0usize; + let mut prev_key: Option<&K> = None; + for row in &rows { + if prev_key != Some(&row.key) { + keys_out += 1; + prev_key = Some(&row.key); + } + } + stats.keys_out = keys_out; + + EventsBuild { rows, 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 assert_invariants(build: &EventsBuild) { + let s = &build.stats; + assert_eq!( + s.filings_in, + s.filings_out + + s.filings_skipped_malformed_timestamp + + s.filings_skipped_unknown_zone + + s.filings_skipped_invalid_date_time + + s.filings_duplicate_collapsed, + "filing accounting mismatch: {s:?}" + ); + assert_eq!( + s.earnings_in, + s.earnings_out + + s.earnings_skipped_out_of_range + + s.earnings_duplicate_collapsed + + s.earnings_duplicate_conflict_dropped, + "earnings accounting mismatch: {s:?}" + ); + assert_eq!( + s.earnings_out, + s.earnings_linked_to_filing + s.earnings_lagged_1605 + ); + assert_eq!(s.rows_out, s.filings_out + s.earnings_out); + assert_eq!(s.rows_out, build.rows.len()); + + for pair in build.rows.windows(2) { + assert!( + ( + &pair[0].key, + pair[0].ts_micros, + pair[0].kind, + &pair[0].subtype, + &pair[0].payload_json + ) <= ( + &pair[1].key, + pair[1].ts_micros, + pair[1].kind, + &pair[1].subtype, + &pair[1].payload_json + ), + "rows must be deterministically sorted" + ); + } + } + + #[test] + fn parse_filing_timefiled_converts_est_edt_leap_and_pre_2008_exact_to_microsecond() { + let est = parse_filing_timefiled("2025-01-31T06:01:27 EST").unwrap(); + assert_eq!(est.utc_micros, utc_micros(2025, 1, 31, 11, 1, 27)); + assert_eq!(est.et_date, day(2025, 1, 31)); + + let edt = parse_filing_timefiled("2025-07-15T16:30:45 EDT").unwrap(); + assert_eq!(edt.utc_micros, utc_micros(2025, 7, 15, 20, 30, 45)); + assert_eq!(edt.et_date, day(2025, 7, 15)); + + let pre_2008 = parse_filing_timefiled("2003-07-15T14:30:00 EDT").unwrap(); + assert_eq!(pre_2008.utc_micros, utc_micros(2003, 7, 15, 18, 30, 0)); + assert_eq!(pre_2008.et_date, day(2003, 7, 15)); + + let leap = parse_filing_timefiled("2024-02-29T23:45:10 EST").unwrap(); + assert_eq!(leap.utc_micros, utc_micros(2024, 3, 1, 4, 45, 10)); + assert_eq!(leap.et_date, day(2024, 2, 29)); + } + + #[test] + fn parse_filing_timefiled_rejects_malformed_unknown_zone_and_invalid_dates_times() { + for bad in [ + "", + "2025-01-31 06:01:27 EST", + "2025/01/31T06:01:27 EST", + "2025-1-31T06:01:27 EST", + "not-a-timestamp", + ] { + assert_eq!( + parse_filing_timefiled(bad), + Err(FilingTimeError::MalformedFormat), + "expected MalformedFormat for {bad:?}" + ); + } + + for bad_zone in [ + "2025-01-31T06:01:27", + "2025-01-31T06:01:27 PST", + "2025-01-31T06:01:27 UTC", + "2025-01-31T06:01:27Z", + "2025-01-31T06:01:27 est", + "2025-01-31T06:01:27 EST ", + ] { + assert_eq!( + parse_filing_timefiled(bad_zone), + Err(FilingTimeError::UnknownZone), + "expected UnknownZone for {bad_zone:?}" + ); + } + + for bad_date in [ + "2025-02-30T06:01:27 EST", + "2025-02-29T06:01:27 EST", + "2025-13-01T06:01:27 EST", + "2025-00-10T06:01:27 EST", + ] { + assert_eq!( + parse_filing_timefiled(bad_date), + Err(FilingTimeError::InvalidDate), + "expected InvalidDate for {bad_date:?}" + ); + } + + for bad_time in [ + "2025-01-31T24:00:00 EST", + "2025-01-31T25:00:00 EST", + "2025-01-31T12:60:00 EST", + "2025-01-31T12:00:60 EST", + ] { + assert_eq!( + parse_filing_timefiled(bad_time), + Err(FilingTimeError::InvalidTime), + "expected InvalidTime for {bad_time:?}" + ); + } + } + + #[test] + fn classify_form_type_covers_all_edgar_sedar_amendments_and_negative_cases() { + let cases = [ + ("10-K", FilingFormGroup::Form10K, false, true, false), + ("10-K/A", FilingFormGroup::Form10K, true, true, false), + (" 10-q ", FilingFormGroup::Form10Q, false, true, false), + ("10-Q/A", FilingFormGroup::Form10Q, true, true, false), + ("8-K", FilingFormGroup::Form8K, false, false, true), + ("8-K/A", FilingFormGroup::Form8K, true, false, true), + ("4", FilingFormGroup::Form4, false, false, false), + ("4/A", FilingFormGroup::Form4, true, false, false), + ("144", FilingFormGroup::Form144, false, false, false), + ("40-F", FilingFormGroup::Form40F, false, true, false), + ("40-F/A", FilingFormGroup::Form40F, true, true, false), + ( + "Interim financial statements/report", + FilingFormGroup::InterimFinancials, + false, + true, + false, + ), + ( + "Amended interim financial statements/report", + FilingFormGroup::InterimFinancials, + true, + true, + false, + ), + ( + "Annual financial statements", + FilingFormGroup::AnnualFinancials, + false, + true, + false, + ), + ("MD&A", FilingFormGroup::Mda, false, false, false), + ("52-109", FilingFormGroup::Form52109, false, false, false), + ("NI 43-101", FilingFormGroup::Ni43101, false, false, false), + ("45-106F1", FilingFormGroup::Form45106F1, false, false, false), + ( + "News release", + FilingFormGroup::NewsRelease, + false, + false, + true, + ), + ("424B5", FilingFormGroup::Other, false, false, false), + ("S-3", FilingFormGroup::Other, false, false, false), + ("DEF 14A", FilingFormGroup::Other, false, false, false), + ("", FilingFormGroup::Other, false, false, false), + ]; + + for (raw, expected_group, expected_amend, expected_periodic, expected_link) in cases { + let (group, is_amend) = classify_form_type(raw); + assert_eq!(group, expected_group, "group mismatch for {raw:?}"); + assert_eq!(is_amend, expected_amend, "amendment mismatch for {raw:?}"); + assert_eq!( + group.is_periodic_financial_report(), + expected_periodic, + "periodic mismatch for {raw:?}" + ); + assert_eq!( + is_periodic_financial_report(raw), + expected_periodic, + "free predicate mismatch for {raw:?}" + ); + assert_eq!( + group.is_earnings_link_candidate(), + expected_link, + "link candidate mismatch for {raw:?}" + ); + } + } + + #[test] + fn json_encoding_escapes_special_chars_and_handles_non_finite_numbers() { + let filing_json = encode_filing_payload_json( + Some("acc-\"1\"\\x\n\t\x00\x1f"), + "10-K/A", + true, + Some("https://example.com/café"), + ); + assert_eq!( + filing_json, + "{\"filing_id\":\"acc-\\\"1\\\"\\\\x\\n\\t\\u0000\\u001f\",\"form_type\":\"10-K/A\",\"is_amendment\":true,\"url\":\"https://example.com/café\"}" + ); + + let earnings_json = encode_earnings_payload_json( + Some(f64::NAN), + "unknown", + Some(day(2024, 12, 31)), + None, + day(2025, 1, 31), + Some(-0.0), + ); + assert_eq!( + earnings_json, + "{\"actual_eps\":null,\"announce_time\":\"unknown\",\"fiscal_period_end\":\"2024-12-31\",\"linked_filing_id\":null,\"report_date\":\"2025-01-31\",\"revenue\":0}" + ); + assert!(!earnings_json.contains("consensusEps")); + assert!(!earnings_json.contains("consensus_eps")); + } + + #[test] + fn partition_year_utc_tracks_utc_year_across_year_end_et_rollover() { + let late_dec31 = parse_filing_timefiled("2024-12-31T21:30:00 EST").unwrap(); + assert_eq!(late_dec31.et_date, day(2024, 12, 31)); + assert_eq!(partition_year_utc(late_dec31.utc_micros), 2025); + + let mid_dec31 = parse_filing_timefiled("2024-12-31T16:00:00 EST").unwrap(); + assert_eq!(partition_year_utc(mid_dec31.utc_micros), 2024); + } + + #[test] + fn build_events_empty_and_basic_reconciliation() { + let empty = build_events::(Vec::new(), Vec::new()); + assert!(empty.rows.is_empty()); + assert_eq!(empty.stats, EventsStats::default()); + assert_invariants(&empty); + } +} diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index f27db413..1d1d577c 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -5,6 +5,7 @@ pub mod bars; pub mod bench; pub mod cli; pub mod corporate_actions; +pub mod events; pub mod fx; pub mod shorts; pub mod split; @@ -22,6 +23,14 @@ pub use corporate_actions::{ CorporateActionsBuild, CorporateActionsStats, DelistingOutcomeEvent, DividendActionEvent, KnownAtSource, SplitActionEvent, }; +pub use events::{ + build_events, classify_form_type, encode_earnings_payload_json, encode_filing_payload_json, + is_periodic_financial_report, normalize_announce_time, parse_filing_timefiled, + partition_year_utc, EventRow, EventsBuild, EventsStats, FilingFormGroup, FilingTimeError, + ParsedFilingTime, QmEarning, QmFiling, EARNINGS_FALLBACK_HOUR_ET, EARNINGS_FALLBACK_MINUTE_ET, + EVENT_KIND_EARNINGS, EVENT_KIND_FILING, KNOWN_AT_SOURCE_FILING_TIMESTAMP, + KNOWN_AT_SOURCE_STATUTORY_LAG, +}; pub use fx::{ build_fx_1d, fx_rate_on_or_before, Fx1dBuild, Fx1dRow, Fx1dStats, FxDailyBar, FxSource, FxSourceStats, FX_OVERLAP_REL_TOLERANCE, FX_PAIR_USDCAD, diff --git a/tools/curate-etl/src/main.rs b/tools/curate-etl/src/main.rs index 3834c301..8647d5ec 100644 --- a/tools/curate-etl/src/main.rs +++ b/tools/curate-etl/src/main.rs @@ -4,8 +4,8 @@ use std::env; use std::process::ExitCode; use curate_etl::bench::{ - run_adj_benchmark, run_bars_benchmark, run_corporate_actions_benchmark, run_fx_benchmark, - run_shorts_benchmark, run_split_benchmark, + run_adj_benchmark, run_bars_benchmark, run_corporate_actions_benchmark, run_events_benchmark, + run_fx_benchmark, run_shorts_benchmark, run_split_benchmark, }; use curate_etl::cli::{format_usage, format_usage_stderr, parse_args, CliAction}; @@ -233,6 +233,38 @@ fn main() -> ExitCode { ); ExitCode::SUCCESS } + Ok(CliAction::BenchEvents(rows)) => { + let report = run_events_benchmark(rows); + println!("curate-etl bench-events"); + println!( + " input: rows={} filings={} earnings={} keys={}", + report.rows, report.filings_in, report.earnings_in, report.key_count + ); + println!( + " build: rows_out={} filings_out={} earnings_out={} keys_out={} elapsed={:.2} ms throughput={:.0} rows/s latency={:.2} ns/row checksum=0x{:016x}", + report.rows_out, + report.stats.filings_out, + report.stats.earnings_out, + report.keys_out, + report.build_elapsed_ms, + report.rows_per_sec, + report.ns_per_row, + report.checksum + ); + println!( + " stats: malformed_ts={} unknown_zone={} invalid_dt={} filing_dup={} linked={} lagged_1605={} earnings_oor={} earnings_dup={} earnings_conflict={}", + report.stats.filings_skipped_malformed_timestamp, + report.stats.filings_skipped_unknown_zone, + report.stats.filings_skipped_invalid_date_time, + report.stats.filings_duplicate_collapsed, + report.stats.earnings_linked_to_filing, + report.stats.earnings_lagged_1605, + report.stats.earnings_skipped_out_of_range, + report.stats.earnings_duplicate_collapsed, + report.stats.earnings_duplicate_conflict_dropped + ); + ExitCode::SUCCESS + } Err(msg) => { eprintln!("error: {msg}"); eprintln!("{}", format_usage_stderr(NAME)); diff --git a/tools/curate-etl/tests/cli.rs b/tools/curate-etl/tests/cli.rs index b4bbf94e..21a9d720 100644 --- a/tools/curate-etl/tests/cli.rs +++ b/tools/curate-etl/tests/cli.rs @@ -27,6 +27,7 @@ fn no_args_and_help_print_usage_and_succeed() { assert!(text.contains("bench-split"), "{args:?}: {text}"); assert!(text.contains("bench-corporate-actions"), "{args:?}: {text}"); assert!(text.contains("bench-fx"), "{args:?}: {text}"); + assert!(text.contains("bench-events"), "{args:?}: {text}"); } } @@ -59,6 +60,10 @@ fn invalid_invocations_exit_nonzero_with_usage_on_stderr() { &["bench-fx", "0"][..], &["bench-fx", "-5"][..], &["bench-fx", "10", "20"][..], + &["bench-events", "abc"][..], + &["bench-events", "0"][..], + &["bench-events", "-5"][..], + &["bench-events", "10", "20"][..], &["--unknown"][..], &["export"][..], ] { @@ -163,3 +168,34 @@ fn bench_fx_small_run_is_headless_deterministic_and_reports_rates() { assert_eq!(checksum_a, checksum_b); assert_eq!(field(&text_a, "rows_out="), field(&text_b, "rows_out=")); } + +#[test] +fn bench_events_small_run_is_headless_deterministic_and_reports_rates() { + let a = run(&["bench-events", "1000"]); + let b = run(&["bench-events", "1000"]); + assert!(a.status.success(), "{}", stderr(&a)); + assert!(b.status.success(), "{}", stderr(&b)); + assert!(stderr(&a).is_empty(), "unexpected stderr: {}", stderr(&a)); + assert!(stderr(&b).is_empty(), "unexpected stderr: {}", stderr(&b)); + + let text_a = stdout(&a); + let text_b = stdout(&b); + assert!(text_a.contains("curate-etl bench-events"), "{text_a}"); + assert!(text_a.contains("rows=1000 "), "{text_a}"); + assert!(text_a.contains("rows_out="), "{text_a}"); + assert!(text_a.contains("rows/s"), "{text_a}"); + assert!(text_a.contains("ns/row"), "{text_a}"); + assert!(text_a.contains("checksum=0x"), "{text_a}"); + assert!(text_a.contains("stats: malformed_ts="), "{text_a}"); + + let field = |s: &str, prefix: &str| { + s.split_whitespace() + .find(|t| t.starts_with(prefix)) + .map(str::to_owned) + }; + let checksum_a = field(&text_a, "checksum="); + let checksum_b = field(&text_b, "checksum="); + assert!(checksum_a.is_some(), "{text_a}"); + assert_eq!(checksum_a, checksum_b); + assert_eq!(field(&text_a, "rows_out="), field(&text_b, "rows_out=")); +} diff --git a/tools/curate-etl/tests/events_contract.rs b/tools/curate-etl/tests/events_contract.rs new file mode 100644 index 00000000..62ee0ea6 --- /dev/null +++ b/tools/curate-etl/tests/events_contract.rs @@ -0,0 +1,887 @@ +//! Contract tests for the public `curate_etl` `events` builder API and CLI binary (T-77 / M1.2g). +//! +//! Uses only the crate's public surface and compiled binary (`CARGO_BIN_EXE_curate-etl`), guarding: +//! - Strict `qmFilings.timefiled` EST/EDT → UTC conversion (including pre-2008 & bad-row skips), +//! - EDGAR & SEDAR+ form-group classification, amendment handling, and periodic-report predicate, +//! - `qmEarnings` linking to same-day `8-K`/`News release` vs. conservative `16:05 ET` fallback, +//! - Strict RFC 8259 JSON payload round-trip, stable key ordering, and `consensusEps` omission, +//! - Deterministic sorting, deduplication, conflict dropping, accounting invariants, and +//! permutation invariance, +//! - `bench-events` reproducibility and CLI argument validation. + +use std::process::Command; + +use curate_etl::bench::run_events_benchmark; +use curate_etl::{ + build_events, classify_form_type, encode_earnings_payload_json, encode_filing_payload_json, + is_periodic_financial_report, normalize_announce_time, parse_filing_timefiled, + partition_year_utc, ymd_to_epoch_days, EventRow, EventsBuild, EventsStats, FilingFormGroup, + FilingTimeError, QmEarning, QmFiling, EARNINGS_FALLBACK_HOUR_ET, EARNINGS_FALLBACK_MINUTE_ET, + EVENT_KIND_EARNINGS, EVENT_KIND_FILING, KNOWN_AT_SOURCE_FILING_TIMESTAMP, + KNOWN_AT_SOURCE_STATUTORY_LAG, MAX_SUPPORTED_DATE, MIN_SUPPORTED_DATE, +}; + +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(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); + } +} + +/// Minimal strict `std`-only RFC 8259 JSON value for contract round-trip validation. +#[derive(Debug, PartialEq)] +enum JsonVal { + Null, + Bool(bool), + Num(f64), + Str(String), + Obj(Vec<(String, JsonVal)>), +} + +struct JsonParser<'a> { + bytes: &'a [u8], + pos: usize, +} + +impl<'a> JsonParser<'a> { + fn new(src: &'a str) -> Self { + Self { + bytes: src.as_bytes(), + pos: 0, + } + } + + fn peek(&self) -> Option { + self.bytes.get(self.pos).copied() + } + + fn parse_value(&mut self) -> Result { + match self.peek() { + Some(b'{') => self.parse_object(), + Some(b'"') => self.parse_string().map(JsonVal::Str), + Some(b't') => self.expect_lit(b"true", JsonVal::Bool(true)), + Some(b'f') => self.expect_lit(b"false", JsonVal::Bool(false)), + Some(b'n') => self.expect_lit(b"null", JsonVal::Null), + Some(b'-' | b'0'..=b'9') => self.parse_number(), + other => Err(format!("unexpected byte {other:?} at {}", self.pos)), + } + } + + fn expect_lit(&mut self, lit: &[u8], val: JsonVal) -> Result { + if self.bytes[self.pos..].starts_with(lit) { + self.pos += lit.len(); + Ok(val) + } else { + Err(format!("expected {:?} at {}", lit, self.pos)) + } + } + + fn parse_object(&mut self) -> Result { + self.pos += 1; // '{' + let mut fields = Vec::new(); + if self.peek() == Some(b'}') { + self.pos += 1; + return Ok(JsonVal::Obj(fields)); + } + loop { + let key = self.parse_string()?; + if self.peek() != Some(b':') { + return Err(format!("expected ':' at {}", self.pos)); + } + self.pos += 1; + let val = self.parse_value()?; + fields.push((key, val)); + match self.peek() { + Some(b',') => self.pos += 1, + Some(b'}') => { + self.pos += 1; + return Ok(JsonVal::Obj(fields)); + } + other => return Err(format!("expected ',' or '}}', got {other:?} at {}", self.pos)), + } + } + } + + fn parse_string(&mut self) -> Result { + if self.peek() != Some(b'"') { + return Err(format!("expected '\"' at {}", self.pos)); + } + self.pos += 1; + let mut out = String::new(); + while self.pos < self.bytes.len() { + let b = self.bytes[self.pos]; + if b == b'"' { + self.pos += 1; + return Ok(out); + } + if b < 0x20 { + return Err(format!("unescaped control byte 0x{b:02x} at {}", self.pos)); + } + if b == b'\\' { + self.pos += 1; + let esc = self.peek().ok_or("unterminated escape")?; + self.pos += 1; + match esc { + b'"' => out.push('"'), + b'\\' => out.push('\\'), + b'/' => out.push('/'), + b'b' => out.push('\x08'), + b'f' => out.push('\x0C'), + b'n' => out.push('\n'), + b'r' => out.push('\r'), + b't' => out.push('\t'), + b'u' => { + if self.pos + 4 > self.bytes.len() { + return Err("truncated \\u escape".to_string()); + } + let hex = std::str::from_utf8(&self.bytes[self.pos..self.pos + 4]) + .map_err(|_| "invalid utf-8 in \\u")?; + let code = u32::from_str_radix(hex, 16) + .map_err(|_| format!("invalid hex {hex}"))?; + self.pos += 4; + let ch = char::from_u32(code).ok_or("invalid scalar")?; + out.push(ch); + } + other => return Err(format!("invalid escape \\{}", other as char)), + } + } else { + let rest = std::str::from_utf8(&self.bytes[self.pos..]) + .map_err(|_| "invalid utf-8 in string")?; + let ch = rest.chars().next().ok_or("unexpected EOF")?; + out.push(ch); + self.pos += ch.len_utf8(); + } + } + Err("unterminated string".to_string()) + } + + fn parse_number(&mut self) -> Result { + let start = self.pos; + if self.peek() == Some(b'-') { + self.pos += 1; + } + match self.peek() { + Some(b'0') => self.pos += 1, + Some(b'1'..=b'9') => { + while matches!(self.peek(), Some(b'0'..=b'9')) { + self.pos += 1; + } + } + _ => return Err(format!("invalid number start at {}", self.pos)), + } + if self.peek() == Some(b'.') { + self.pos += 1; + if !matches!(self.peek(), Some(b'0'..=b'9')) { + return Err(format!("expected digit after '.' at {}", self.pos)); + } + while matches!(self.peek(), Some(b'0'..=b'9')) { + self.pos += 1; + } + } + if matches!(self.peek(), Some(b'e' | b'E')) { + self.pos += 1; + if matches!(self.peek(), Some(b'+' | b'-')) { + self.pos += 1; + } + if !matches!(self.peek(), Some(b'0'..=b'9')) { + return Err(format!("expected exponent digit at {}", self.pos)); + } + while matches!(self.peek(), Some(b'0'..=b'9')) { + self.pos += 1; + } + } + let slice = std::str::from_utf8(&self.bytes[start..self.pos]).unwrap(); + let num = slice + .parse::() + .map_err(|_| format!("invalid float {slice}"))?; + if !num.is_finite() { + return Err(format!("non-finite JSON number {slice}")); + } + Ok(JsonVal::Num(num)) + } +} + +fn parse_json_object(src: &str) -> Vec<(String, JsonVal)> { + let mut parser = JsonParser::new(src); + let val = parser + .parse_value() + .unwrap_or_else(|e| panic!("invalid JSON {src:?}: {e}")); + assert_eq!(parser.pos, src.len(), "trailing bytes in JSON: {src:?}"); + match val { + JsonVal::Obj(fields) => fields, + other => panic!("expected JSON object, got {other:?}"), + } +} + +fn assert_accounting_and_order(build: &EventsBuild) { + let s = &build.stats; + assert_eq!( + s.filings_in, + s.filings_out + + s.filings_skipped_malformed_timestamp + + s.filings_skipped_unknown_zone + + s.filings_skipped_invalid_date_time + + s.filings_duplicate_collapsed, + "filing conservation failed: {s:?}" + ); + assert_eq!( + s.earnings_in, + s.earnings_out + + s.earnings_skipped_out_of_range + + s.earnings_duplicate_collapsed + + s.earnings_duplicate_conflict_dropped, + "earnings conservation failed: {s:?}" + ); + assert_eq!( + s.earnings_out, + s.earnings_linked_to_filing + s.earnings_lagged_1605 + ); + assert_eq!(s.rows_out, s.filings_out + s.earnings_out); + 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_eq!(row.ts_micros, row.known_at_micros); + assert_eq!(row.partition_year(), partition_year_utc(row.ts_micros)); + let fields = parse_json_object(&row.payload_json); + let keys: Vec<&str> = fields.iter().map(|(k, _)| k.as_str()).collect(); + if row.kind == EVENT_KIND_FILING { + assert_eq!(keys, vec!["filing_id", "form_type", "is_amendment", "url"]); + assert_eq!(row.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); + } else { + assert_eq!(row.kind, EVENT_KIND_EARNINGS); + assert_eq!( + keys, + vec![ + "actual_eps", + "announce_time", + "fiscal_period_end", + "linked_filing_id", + "report_date", + "revenue", + ] + ); + assert!(!keys.contains(&"consensusEps")); + assert!(!keys.contains(&"consensus_eps")); + } + 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) { + let lhs = ( + &pair[0].key, + pair[0].ts_micros, + pair[0].kind, + &pair[0].subtype, + &pair[0].payload_json, + ); + let rhs = ( + &pair[1].key, + pair[1].ts_micros, + pair[1].kind, + &pair[1].subtype, + &pair[1].payload_json, + ); + assert!(lhs <= rhs, "rows must be sorted deterministically"); + } +} + +#[test] +fn public_constants_and_filing_timestamps_match_contract() { + assert_eq!(EVENT_KIND_FILING, "filing"); + assert_eq!(EVENT_KIND_EARNINGS, "earnings"); + assert_eq!(KNOWN_AT_SOURCE_FILING_TIMESTAMP, "filing_timestamp"); + assert_eq!(KNOWN_AT_SOURCE_STATUTORY_LAG, "statutory_lag_estimate"); + assert_eq!(EARNINGS_FALLBACK_HOUR_ET, 16); + assert_eq!(EARNINGS_FALLBACK_MINUTE_ET, 5); + + let est = parse_filing_timefiled("2025-01-31T06:01:27 EST").unwrap(); + assert_eq!(est.utc_micros, utc_micros(2025, 1, 31, 11, 1, 27)); + assert_eq!(est.et_date, day(2025, 1, 31)); + + let edt = parse_filing_timefiled("2025-07-04T09:15:00 EDT").unwrap(); + assert_eq!(edt.utc_micros, utc_micros(2025, 7, 4, 13, 15, 0)); + assert_eq!(edt.et_date, day(2025, 7, 4)); + + let pre2008 = parse_filing_timefiled("2003-07-15T14:30:00 EDT").unwrap(); + assert_eq!(pre2008.utc_micros, utc_micros(2003, 7, 15, 18, 30, 0)); + assert_eq!(pre2008.et_date, day(2003, 7, 15)); + + assert_eq!( + parse_filing_timefiled("bad"), + Err(FilingTimeError::MalformedFormat) + ); + assert_eq!( + parse_filing_timefiled("2025-01-31T06:01:27 PST"), + Err(FilingTimeError::UnknownZone) + ); + assert_eq!( + parse_filing_timefiled("2025-01-31T06:01:27"), + Err(FilingTimeError::UnknownZone) + ); + assert_eq!( + parse_filing_timefiled("2025-02-30T06:01:27 EST"), + Err(FilingTimeError::InvalidDate) + ); + assert_eq!( + parse_filing_timefiled("2025-01-31T25:00:00 EST"), + Err(FilingTimeError::InvalidTime) + ); + assert_eq!( + parse_filing_timefiled("2025-01-31T12:60:00 EST"), + Err(FilingTimeError::InvalidTime) + ); +} + +#[test] +fn form_groups_and_periodic_predicate_cover_all_contract_forms() { + let cases = [ + ("10-K", FilingFormGroup::Form10K, "10-k", false, true), + ("10-K/A", FilingFormGroup::Form10K, "10-k", true, true), + ("10-Q", FilingFormGroup::Form10Q, "10-q", false, true), + ("10-Q/A", FilingFormGroup::Form10Q, "10-q", true, true), + ("8-K", FilingFormGroup::Form8K, "8-k", false, false), + ("8-K/A", FilingFormGroup::Form8K, "8-k", true, false), + ("4", FilingFormGroup::Form4, "4", false, false), + ("144", FilingFormGroup::Form144, "144", false, false), + ("40-F", FilingFormGroup::Form40F, "40-f", false, true), + ( + "Interim financial statements/report", + FilingFormGroup::InterimFinancials, + "interim_financial_statements", + false, + true, + ), + ( + "Annual financial statements", + FilingFormGroup::AnnualFinancials, + "annual_financial_statements", + false, + true, + ), + ("MD&A", FilingFormGroup::Mda, "mda", false, false), + ("52-109", FilingFormGroup::Form52109, "52-109", false, false), + ( + "NI 43-101", + FilingFormGroup::Ni43101, + "ni_43_101", + false, + false, + ), + ( + "45-106F1", + FilingFormGroup::Form45106F1, + "45-106f1", + false, + false, + ), + ( + "News release", + FilingFormGroup::NewsRelease, + "news_release", + false, + false, + ), + ("424B5", FilingFormGroup::Other, "other", false, false), + ("S-3", FilingFormGroup::Other, "other", false, false), + ("DEF 14A", FilingFormGroup::Other, "other", false, false), + ]; + + for (raw, group, subtype, amend, periodic) in cases { + let (got_group, got_amend) = classify_form_type(raw); + assert_eq!(got_group, group, "raw={raw:?}"); + assert_eq!(got_group.as_str(), subtype, "raw={raw:?}"); + assert_eq!(got_amend, amend, "raw={raw:?}"); + assert_eq!(got_group.is_periodic_financial_report(), periodic); + assert_eq!(is_periodic_financial_report(raw), periodic); + } + + assert_eq!(normalize_announce_time("BTO"), "bto"); + assert_eq!(normalize_announce_time(" amc "), "amc"); + assert_eq!(normalize_announce_time("N/A"), "unknown"); + assert_eq!(normalize_announce_time(""), "unknown"); +} + +#[test] +fn earnings_linking_lagging_cross_midnight_and_out_of_range_rules() { + let d_est = day(2025, 1, 31); // EST + let d_edt = day(2025, 7, 15); // EDT + let d_other = day(2025, 2, 3); + let d_pre2008 = day(2003, 7, 15); + + let filings = vec![ + // (a) Same-day 8-K for key=1 + QmFiling { + key: 1, + timefiled: "2025-01-31T16:10:00 EST".to_string(), + form_type: "8-K".to_string(), + filing_id: Some("k1-8k".to_string()), + url: None, + }, + // (b) Multiple same-day 8-K + News release for key=2 -> earliest wins + QmFiling { + key: 2, + timefiled: "2025-01-31T17:00:00 EST".to_string(), + form_type: "8-K".to_string(), + filing_id: Some("k2-late".to_string()), + url: None, + }, + QmFiling { + key: 2, + timefiled: "2025-01-31T07:30:00 EST".to_string(), + form_type: "News release".to_string(), + filing_id: Some("k2-early".to_string()), + url: None, + }, + // (b2) Exact timestamp tie for key=20 -> deterministic smallest filing_id wins + QmFiling { + key: 20, + timefiled: "2025-01-31T08:00:00 EST".to_string(), + form_type: "8-K".to_string(), + filing_id: Some("b-id".to_string()), + url: None, + }, + QmFiling { + key: 20, + timefiled: "2025-01-31T08:00:00 EST".to_string(), + form_type: "8-K".to_string(), + filing_id: Some("a-id".to_string()), + url: None, + }, + // (c) Non-qualifying Form 4 on same day for key=3 + qualifying 8-K on different date + QmFiling { + key: 3, + timefiled: "2025-01-31T08:00:00 EST".to_string(), + form_type: "4".to_string(), + filing_id: Some("k3-form4".to_string()), + url: None, + }, + QmFiling { + key: 3, + timefiled: "2025-02-03T08:00:00 EST".to_string(), + form_type: "8-K".to_string(), + filing_id: Some("k3-other-day".to_string()), + url: None, + }, + // (f) Pre-2008 qualifying 8-K for key=6 -> allows pre-2008 earnings to link! + QmFiling { + key: 6, + timefiled: "2003-07-15T16:15:00 EDT".to_string(), + form_type: "8-K".to_string(), + filing_id: Some("k6-2003".to_string()), + url: None, + }, + // (g) Late-evening ET filing crossing into next UTC calendar day (2025-02-01T02:30:00Z) + QmFiling { + key: 7, + timefiled: "2025-01-31T21:30:00 EST".to_string(), + form_type: "8-K".to_string(), + filing_id: Some("k7-late-et".to_string()), + url: None, + }, + ]; + + let earnings = vec![ + // (a) N/A linked to same-day 8-K + QmEarning { + key: 1, + report_date: d_est, + announce_time: "N/A".to_string(), + fiscal_period_end: Some(day(2024, 12, 31)), + actual_eps: Some(1.25), + revenue: Some(100_000.0), + }, + // (b) Linked to earliest (News release 07:30 EST) + QmEarning { + key: 2, + report_date: d_est, + announce_time: "N/A".to_string(), + fiscal_period_end: None, + actual_eps: Some(0.5), + revenue: None, + }, + // (b2) Tie-break picks "a-id" + QmEarning { + key: 20, + report_date: d_est, + announce_time: "BTO".to_string(), + fiscal_period_end: None, + actual_eps: None, + revenue: None, + }, + // (c)+(d) Unlinked EST (Form 4 doesn't qualify; 8-K is different date) -> 21:05Z + QmEarning { + key: 3, + report_date: d_est, + announce_time: "N/A".to_string(), + fiscal_period_end: None, + actual_eps: None, + revenue: None, + }, + // (d)+(e) Unlinked EDT + BTO -> 20:05Z (never earlier than 16:05 ET) + QmEarning { + key: 4, + report_date: d_edt, + announce_time: "BTO".to_string(), + fiscal_period_end: None, + actual_eps: None, + revenue: None, + }, + // (e) Unlinked EST + AMC -> 21:05Z + QmEarning { + key: 5, + report_date: d_other, + announce_time: "AMC".to_string(), + fiscal_period_end: None, + actual_eps: None, + revenue: None, + }, + // (f1) Pre-2008 WITH linked filing -> succeeds via filing_timestamp + QmEarning { + key: 6, + report_date: d_pre2008, + announce_time: "AMC".to_string(), + fiscal_period_end: None, + actual_eps: None, + revenue: None, + }, + // (f2) Pre-2008 WITHOUT linked filing -> skipped (out of range) + QmEarning { + key: 60, + report_date: MIN_SUPPORTED_DATE - 1, + announce_time: "N/A".to_string(), + fiscal_period_end: None, + actual_eps: None, + revenue: None, + }, + // (f3) Post-2030 WITHOUT linked filing -> skipped (out of range) + QmEarning { + key: 61, + report_date: MAX_SUPPORTED_DATE + 1, + announce_time: "N/A".to_string(), + fiscal_period_end: None, + actual_eps: None, + revenue: None, + }, + // (g) Late-evening ET filing links by ET calendar date (2025-01-31) + QmEarning { + key: 7, + report_date: d_est, + announce_time: "AMC".to_string(), + fiscal_period_end: None, + actual_eps: Some(2.0), + revenue: None, + }, + ]; + + let built = build_events(filings, earnings); + assert_accounting_and_order(&built); + assert_eq!(built.stats.earnings_in, 10); + assert_eq!(built.stats.earnings_out, 8); + assert_eq!(built.stats.earnings_linked_to_filing, 5); + assert_eq!(built.stats.earnings_lagged_1605, 3); + assert_eq!(built.stats.earnings_skipped_out_of_range, 2); + + let find_earning = |key: i32| -> &EventRow { + built + .rows + .iter() + .find(|r| r.key == key && r.kind == EVENT_KIND_EARNINGS) + .unwrap_or_else(|| panic!("missing earning for key {key}")) + }; + + let e1 = find_earning(1); + assert_eq!(e1.known_at_micros, utc_micros(2025, 1, 31, 21, 10, 0)); + assert_eq!(e1.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); + assert_eq!(e1.subtype, "unknown"); + + let e2 = find_earning(2); + assert_eq!(e2.known_at_micros, utc_micros(2025, 1, 31, 12, 30, 0)); + assert_eq!(e2.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); + assert!(e2.payload_json.contains("\"linked_filing_id\":\"k2-early\"")); + + let e20 = find_earning(20); + assert!(e20.payload_json.contains("\"linked_filing_id\":\"a-id\"")); + + let e3 = find_earning(3); + assert_eq!(e3.known_at_micros, utc_micros(2025, 1, 31, 21, 5, 0)); + assert_eq!(e3.known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); + assert_eq!(e3.subtype, "unknown"); + + let e4 = find_earning(4); + assert_eq!(e4.known_at_micros, utc_micros(2025, 7, 15, 20, 5, 0)); + assert_eq!(e4.known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); + assert_eq!(e4.subtype, "bto"); + + let e5 = find_earning(5); + assert_eq!(e5.known_at_micros, utc_micros(2025, 2, 3, 21, 5, 0)); + assert_eq!(e5.known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); + assert_eq!(e5.subtype, "amc"); + + let e6 = find_earning(6); + assert_eq!(e6.known_at_micros, utc_micros(2003, 7, 15, 20, 15, 0)); + assert_eq!(e6.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); + + let e7 = find_earning(7); + assert_eq!(e7.known_at_micros, utc_micros(2025, 2, 1, 2, 30, 0)); + assert_eq!(e7.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); + assert!(e7 + .payload_json + .contains("\"linked_filing_id\":\"k7-late-et\"")); +} + +#[test] +fn payload_json_round_trips_escapes_unicode_and_non_finite_numbers() { + let tricky_id = "id-\"quote\"\\slash\x08\x0c\n\r\t\x00\x1f-日本語-café"; + let tricky_form = "10-K/A \"amended\""; + let tricky_url = "https://sec.gov/Archives/a\\b?q=\"1\"&x=αβγ"; + + let raw = encode_filing_payload_json(Some(tricky_id), tricky_form, true, Some(tricky_url)); + let parsed = parse_json_object(&raw); + assert_eq!( + parsed, + vec![ + ("filing_id".to_string(), JsonVal::Str(tricky_id.to_string())), + ( + "form_type".to_string(), + JsonVal::Str(tricky_form.to_string()) + ), + ("is_amendment".to_string(), JsonVal::Bool(true)), + ("url".to_string(), JsonVal::Str(tricky_url.to_string())), + ] + ); + + let e_raw = encode_earnings_payload_json( + Some(f64::NAN), + "bto", + Some(day(2024, 9, 30)), + Some("acc\"1"), + day(2024, 10, 31), + Some(f64::INFINITY), + ); + let e_parsed = parse_json_object(&e_raw); + assert_eq!( + e_parsed, + vec![ + ("actual_eps".to_string(), JsonVal::Null), + ("announce_time".to_string(), JsonVal::Str("bto".to_string())), + ( + "fiscal_period_end".to_string(), + JsonVal::Str("2024-09-30".to_string()) + ), + ( + "linked_filing_id".to_string(), + JsonVal::Str("acc\"1".to_string()) + ), + ( + "report_date".to_string(), + JsonVal::Str("2024-10-31".to_string()) + ), + ("revenue".to_string(), JsonVal::Null), + ] + ); +} + +#[test] +fn deduplication_conflicts_zero_nan_normalization_and_permutation_invariance() { + let d1 = day(2025, 1, 31); + let d2 = day(2025, 7, 15); + + let filings = vec![ + QmFiling { + key: 1, + timefiled: "2025-01-31T06:01:27 EST".to_string(), + form_type: "8-K".to_string(), + filing_id: Some("f1".to_string()), + url: None, + }, + // Exact duplicate filing -> collapsed + QmFiling { + key: 1, + timefiled: "2025-01-31T06:01:27 EST".to_string(), + form_type: "8-K".to_string(), + filing_id: Some("f1".to_string()), + url: None, + }, + // Bad filings -> skipped and counted + QmFiling { + key: 1, + timefiled: "not-a-date".to_string(), + form_type: "10-K".to_string(), + filing_id: None, + url: None, + }, + QmFiling { + key: 1, + timefiled: "2025-01-31T06:01:27 PST".to_string(), + form_type: "10-K".to_string(), + filing_id: None, + url: None, + }, + QmFiling { + key: 1, + timefiled: "2025-02-30T06:01:27 EST".to_string(), + form_type: "10-K".to_string(), + filing_id: None, + url: None, + }, + QmFiling { + key: 1, + timefiled: "2025-01-31T25:00:00 EST".to_string(), + form_type: "10-K".to_string(), + filing_id: None, + url: None, + }, + ]; + + let earnings = vec![ + // Identical after -0.0 and distinct NaN normalization -> collapsed (no conflict) + QmEarning { + key: 1, + report_date: d1, + announce_time: "N/A".to_string(), + fiscal_period_end: None, + actual_eps: Some(-0.0), + revenue: Some(f64::NAN), + }, + QmEarning { + key: 1, + report_date: d1, + announce_time: " ".to_string(), + fiscal_period_end: None, + actual_eps: Some(0.0), + revenue: Some(f64::from_bits(0x7ff8_0000_0000_0001)), + }, + // Conflicting duplicate group -> dropped entirely + QmEarning { + key: 2, + report_date: d2, + announce_time: "AMC".to_string(), + fiscal_period_end: None, + actual_eps: Some(1.0), + revenue: None, + }, + QmEarning { + key: 2, + report_date: d2, + announce_time: "AMC".to_string(), + fiscal_period_end: None, + actual_eps: Some(2.0), + revenue: None, + }, + ]; + + let baseline = build_events(filings.clone(), earnings.clone()); + assert_accounting_and_order(&baseline); + assert_eq!(baseline.stats.filings_in, 6); + assert_eq!(baseline.stats.filings_out, 1); + assert_eq!(baseline.stats.filings_duplicate_collapsed, 1); + assert_eq!(baseline.stats.filings_skipped_malformed_timestamp, 1); + assert_eq!(baseline.stats.filings_skipped_unknown_zone, 1); + assert_eq!(baseline.stats.filings_skipped_invalid_date_time, 2); + assert_eq!(baseline.stats.earnings_in, 4); + assert_eq!(baseline.stats.earnings_out, 1); + assert_eq!(baseline.stats.earnings_duplicate_collapsed, 1); + assert_eq!(baseline.stats.earnings_duplicate_conflict_dropped, 2); + + let mut rng = Rng(0x570C_4B07_E7E4_9999); + for _ in 0..16 { + let mut f_perm = filings.clone(); + let mut e_perm = earnings.clone(); + shuffle(&mut f_perm, &mut rng); + shuffle(&mut e_perm, &mut rng); + let trial = build_events(f_perm, e_perm); + assert_accounting_and_order(&trial); + assert_eq!(trial.rows, baseline.rows); + assert_eq!(trial.stats, baseline.stats); + } + + let empty = build_events::(Vec::new(), Vec::new()); + assert_eq!(empty.stats, EventsStats::default()); + assert_accounting_and_order(&empty); +} + +#[test] +fn run_events_benchmark_and_cli_binary_are_reproducible() { + let a = run_events_benchmark(5_000); + let b = run_events_benchmark(5_000); + assert_eq!(a.rows, 5_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-events", "5000"]) + .output() + .expect("run bench-events #1"); + let run2 = Command::new(bin) + .args(["bench-events", "5000"]) + .output() + .expect("run bench-events #2"); + + assert!(run1.status.success(), "bench-events #1 failed"); + assert!(run2.status.success(), "bench-events #2 failed"); + + let out1 = String::from_utf8_lossy(&run1.stdout); + let out2 = String::from_utf8_lossy(&run2.stdout); + assert!(out1.contains("curate-etl bench-events")); + 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)); + + for bad in [ + &["bench-events", "0"][..], + &["bench-events", "-5"][..], + &["bench-events", "abc"][..], + &["bench-events", "10", "20"][..], + ] { + let out = Command::new(bin) + .args(bad) + .output() + .expect("run invalid bench-events"); + assert!(!out.status.success(), "expected failure for {bad:?}"); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(stderr.contains("bench-events")); + } +} diff --git a/tools/curate-etl/tests/events_reference.rs b/tools/curate-etl/tests/events_reference.rs new file mode 100644 index 00000000..8789893b --- /dev/null +++ b/tools/curate-etl/tests/events_reference.rs @@ -0,0 +1,232 @@ +//! Independent reference / point-in-time QA tests for the `events` builder (T-77 / M1.2g). +//! +//! Verifies: +//! - Independent EST (+5h) / EDT (+4h) UTC math oracle across pre-2008, leap-day, and +//! year-end cross-midnight filings, +//! - Cross-midnight ET calendar-date linking (`2024-12-31T21:30:00 EST` links to `2024-12-31` +//! while partitioning into UTC `year=2025`), +//! - Future poison-row no-look-ahead invariance (appending future filings, earnings, bad rows, +//! and conflicting duplicates never alters any earlier emitted row). + +use curate_etl::bench::{run_events_benchmark, DEFAULT_EVENTS_BENCH_ROWS}; +use curate_etl::{ + build_events, parse_filing_timefiled, partition_year_utc, ymd_to_epoch_days, QmEarning, + QmFiling, EVENT_KIND_EARNINGS, KNOWN_AT_SOURCE_FILING_TIMESTAMP, +}; + +const MICROS_PER_SEC: i64 = 1_000_000; +const MICROS_PER_HOUR: i64 = 3_600 * MICROS_PER_SEC; +const MICROS_PER_DAY: i64 = 24 * MICROS_PER_HOUR; + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid fixture date") +} + +fn oracle_utc_micros( + year: i32, + month: u32, + dom: u32, + hour: u32, + minute: u32, + second: u32, + offset_hours: i64, +) -> i64 { + let d = i64::from(day(year, month, dom)); + d * MICROS_PER_DAY + + (i64::from(hour) + offset_hours) * MICROS_PER_HOUR + + i64::from(minute) * 60 * MICROS_PER_SEC + + i64::from(second) * MICROS_PER_SEC +} + +#[test] +fn est_and_edt_conversions_match_independent_oracle_across_decades() { + let cases = [ + (1999, 12, 31, 23, 59, 59, "EST", 5), + (2000, 2, 29, 16, 30, 0, "EST", 5), + (2003, 7, 15, 14, 30, 0, "EDT", 4), + (2007, 11, 4, 0, 15, 10, "EDT", 4), + (2024, 12, 31, 21, 30, 0, "EST", 5), + (2025, 1, 31, 6, 1, 27, "EST", 5), + (2026, 3, 6, 17, 0, 0, "EST", 5), + (2026, 3, 9, 17, 0, 0, "EDT", 4), + ]; + + for (y, m, d, hh, mm, ss, zone, offset) in cases { + let raw = format!("{y:04}-{m:02}-{d:02}T{hh:02}:{mm:02}:{ss:02} {zone}"); + let parsed = parse_filing_timefiled(&raw).expect("valid oracle fixture"); + assert_eq!(parsed.et_date, day(y, m, d), "et_date mismatch for {raw}"); + assert_eq!( + parsed.utc_micros, + oracle_utc_micros(y, m, d, hh, mm, ss, offset), + "utc_micros mismatch for {raw}" + ); + } +} + +#[test] +fn year_end_late_et_filing_links_by_et_date_and_partitions_by_utc_year() { + let dec31 = day(2024, 12, 31); + let built = build_events( + vec![QmFiling { + key: 42_i32, + timefiled: "2024-12-31T21:30:00 EST".to_string(), + form_type: "News release".to_string(), + filing_id: Some("nye-nr".to_string()), + url: None, + }], + vec![QmEarning { + key: 42_i32, + report_date: dec31, + announce_time: "N/A".to_string(), + fiscal_period_end: Some(day(2024, 10, 31)), + actual_eps: Some(0.42), + revenue: None, + }], + ); + + assert_eq!(built.rows.len(), 2); + let expected_utc = oracle_utc_micros(2025, 1, 1, 2, 30, 0, 0); + assert_eq!(partition_year_utc(expected_utc), 2025); + + for row in &built.rows { + assert_eq!(row.ts_micros, expected_utc); + assert_eq!(row.known_at_micros, expected_utc); + assert_eq!(row.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); + assert_eq!(row.partition_year(), 2025); + } + + let earning = built + .rows + .iter() + .find(|r| r.kind == EVENT_KIND_EARNINGS) + .expect("earnings row present"); + assert!(earning + .payload_json + .contains("\"linked_filing_id\":\"nye-nr\"")); +} + +#[test] +fn appending_future_poison_filings_and_earnings_never_alters_earlier_rows() { + let cutoff_utc = oracle_utc_micros(2025, 3, 1, 0, 0, 0, 0); + + let base_filings = vec![ + QmFiling { + key: 1_i32, + timefiled: "2025-01-31T08:00:00 EST".to_string(), + form_type: "8-K".to_string(), + filing_id: Some("f-jan".to_string()), + url: None, + }, + QmFiling { + key: 2_i32, + timefiled: "2025-02-10T16:30:00 EST".to_string(), + form_type: "10-K".to_string(), + filing_id: Some("f-feb".to_string()), + url: None, + }, + ]; + let base_earnings = vec![ + QmEarning { + key: 1_i32, + report_date: day(2025, 1, 31), + announce_time: "BTO".to_string(), + fiscal_period_end: Some(day(2024, 12, 31)), + actual_eps: Some(1.1), + revenue: Some(50_000.0), + }, + QmEarning { + key: 2_i32, + report_date: day(2025, 2, 10), + announce_time: "AMC".to_string(), + fiscal_period_end: Some(day(2024, 12, 31)), + actual_eps: Some(2.2), + revenue: Some(80_000.0), + }, + ]; + + let before = build_events(base_filings.clone(), base_earnings.clone()); + + let mut poisoned_filings = base_filings; + poisoned_filings.push(QmFiling { + key: 1, + timefiled: "2025-05-01T07:00:00 EDT".to_string(), + form_type: "8-K".to_string(), + filing_id: Some("f-may-poison".to_string()), + url: None, + }); + poisoned_filings.push(QmFiling { + key: 2, + timefiled: "2025-02-11T07:00:00 EST".to_string(), + form_type: "8-K".to_string(), + filing_id: Some("f-next-day".to_string()), + url: None, + }); + poisoned_filings.push(QmFiling { + key: 1, + timefiled: "malformed".to_string(), + form_type: "8-K".to_string(), + filing_id: None, + url: None, + }); + + let mut poisoned_earnings = base_earnings; + poisoned_earnings.push(QmEarning { + key: 1, + report_date: day(2025, 5, 1), + announce_time: "N/A".to_string(), + fiscal_period_end: None, + actual_eps: Some(999.0), + revenue: None, + }); + poisoned_earnings.push(QmEarning { + key: 2, + report_date: day(2025, 6, 1), + announce_time: "AMC".to_string(), + fiscal_period_end: None, + actual_eps: Some(1.0), + revenue: None, + }); + poisoned_earnings.push(QmEarning { + key: 2, + report_date: day(2025, 6, 1), + announce_time: "AMC".to_string(), + fiscal_period_end: None, + actual_eps: Some(2.0), + revenue: None, + }); + + let after = build_events(poisoned_filings, poisoned_earnings); + let earlier: Vec<_> = after + .rows + .iter() + .filter(|r| r.ts_micros < cutoff_utc && r.known_at_micros < cutoff_utc) + .filter(|r| !(r.key == 2 && r.payload_json.contains("f-next-day"))) + .cloned() + .collect(); + assert_eq!(earlier, before.rows); +} + +#[test] +fn default_bench_events_matches_readme_recorded_output() { + // README records rows_out=491190, filings_out=484531, earnings_out=6659, keys_out=20000, + // checksum 0xbf74cd745a2646c6 and the stats line below for + // `cargo run --release -p curate-etl --offline -- bench-events`. + let report = run_events_benchmark(DEFAULT_EVENTS_BENCH_ROWS); + assert_eq!(DEFAULT_EVENTS_BENCH_ROWS, 500_000); + assert_eq!(report.filings_in, 492_500); + assert_eq!(report.earnings_in, 7_500); + assert_eq!(report.rows_out, 491_190); + assert_eq!(report.stats.filings_out, 484_531); + assert_eq!(report.stats.earnings_out, 6_659); + assert_eq!(report.keys_out, 20_000); + assert_eq!(report.stats.filings_skipped_malformed_timestamp, 1_525); + assert_eq!(report.stats.filings_skipped_unknown_zone, 1_496); + assert_eq!(report.stats.filings_skipped_invalid_date_time, 2_476); + assert_eq!(report.stats.filings_duplicate_collapsed, 2_472); + assert_eq!(report.stats.earnings_linked_to_filing, 2_569); + assert_eq!(report.stats.earnings_lagged_1605, 4_090); + assert_eq!(report.stats.earnings_skipped_out_of_range, 37); + assert_eq!(report.stats.earnings_duplicate_collapsed, 98); + assert_eq!(report.stats.earnings_duplicate_conflict_dropped, 706); + assert_eq!(report.checksum, 0xbf74_cd74_5a26_46c6); +}