stock-bot/tools/curate-etl/tests/events_reference.rs
2026-11-27 22:51:48 -05:00

595 lines
21 KiB
Rust
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! 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-date poison-row stability (appending filings and earnings on later dates never alters
//! emitted rows from earlier dates), plus an explicit fixture showing that a same-date evening
//! filing replaces the `16:05 ET` fallback (which is intended for T+1 open use, not same-day
//! intraday cutoffs).
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, KNOWN_AT_SOURCE_STATUTORY_LAG,
};
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_date_poison_filings_and_earnings_never_alters_prior_dates() {
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 same_date_late_filing_replaces_1605_fallback_across_intraday_cutoff() {
// The 16:05 ET fallback (`statutory_lag_estimate`) is intended for T+1 open use, not same-day
// intraday cutoffs: if a same-date qualifying filing arrives at 21:30 ET, link precedence
// moves the earnings timestamp from 16:05 ET (before a 17:00 ET intraday cutoff) to 21:30 ET
// (after that cutoff).
let report_date = day(2025, 2, 10);
let intraday_cutoff_utc = oracle_utc_micros(2025, 2, 10, 17, 0, 0, 5); // 17:00 EST = 22:00Z
let fallback_1605_utc = oracle_utc_micros(2025, 2, 10, 16, 5, 0, 5); // 16:05 EST = 21:05Z
let late_filing_utc = oracle_utc_micros(2025, 2, 10, 21, 30, 0, 5); // 21:30 EST = 02:30Z Feb 11
let earning = QmEarning {
key: 2_i32,
report_date,
announce_time: "AMC".to_string(),
fiscal_period_end: Some(day(2024, 12, 31)),
actual_eps: Some(2.2),
revenue: Some(80_000.0),
};
let without_filing = build_events(Vec::<QmFiling<i32>>::new(), vec![earning.clone()]);
assert_eq!(without_filing.rows.len(), 1);
let fallback_row = &without_filing.rows[0];
assert_eq!(fallback_row.known_at_micros, fallback_1605_utc);
assert_eq!(fallback_row.known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG);
assert!(fallback_row.known_at_micros < intraday_cutoff_utc);
let with_late_filing = build_events(
vec![QmFiling {
key: 2_i32,
timefiled: "2025-02-10T21:30:00 EST".to_string(),
form_type: "8-K".to_string(),
filing_id: Some("f-late-8k".to_string()),
url: None,
}],
vec![earning],
);
let linked_row = with_late_filing
.rows
.iter()
.find(|r| r.kind == EVENT_KIND_EARNINGS)
.expect("earnings row present");
assert_eq!(linked_row.known_at_micros, late_filing_utc);
assert_eq!(linked_row.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP);
assert!(linked_row.known_at_micros > intraday_cutoff_utc);
}
#[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);
}
// ---------------------------------------------------------------------------------------------
// QA additions (T-77): robustness, PIT truncation, link eligibility and boundary edge cases.
// ---------------------------------------------------------------------------------------------
struct QaRng(u64);
impl QaRng {
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 filing(key: i32, timefiled: &str, form_type: &str, id: Option<&str>) -> QmFiling<i32> {
QmFiling {
key,
timefiled: timefiled.to_string(),
form_type: form_type.to_string(),
filing_id: id.map(str::to_string),
url: None,
}
}
fn earning(key: i32, report_date: i32, announce_time: &str, eps: f64) -> QmEarning<i32> {
QmEarning {
key,
report_date,
announce_time: announce_time.to_string(),
fiscal_period_end: None,
actual_eps: Some(eps),
revenue: None,
}
}
#[test]
fn qa_non_ascii_and_seeded_garbage_timefiled_never_panics_and_is_counted() {
// Multibyte characters at structural offsets must not cause byte-slice panics.
let fixed = [
"2025-01-31T06:01:27 ÉST",
"2025-01-31T06:01:27 EST",
"2025é01-31T06:01:27 EST",
"2025-01-31T06:01:2é EST",
"2025-01-31T06:01:27\u{00a0}EST",
"2025-01-31T06:01:27.123 EST",
"+025-01-31T06:01:27 EST",
"2025-01-31T06:01:27 EST\0",
];
for raw in fixed {
assert!(parse_filing_timefiled(raw).is_err(), "must reject {raw:?}");
}
let alphabet: Vec<char> = "0123456789-T: ESTDZé\u{00a0}2/".chars().collect();
let template: Vec<char> = "2025-01-31T06:01:27 EST".chars().collect();
let mut rng = QaRng(0x0A11_7E57_0000_0077);
let mut inputs = Vec::new();
for i in 0..5_000 {
let mut chars = template.clone();
let mutations = 1 + (rng.next() % 3) as usize;
for _ in 0..mutations {
let pos = (rng.next() as usize) % chars.len();
chars[pos] = alphabet[(rng.next() as usize) % alphabet.len()];
}
if rng.next() % 5 == 0 {
let cut = (rng.next() as usize) % chars.len();
chars.truncate(cut);
}
let raw: String = chars.into_iter().collect();
let _ = parse_filing_timefiled(&raw); // must not panic
inputs.push(filing(i % 7, &raw, "8-K", Some(&format!("g{i}"))));
}
let built = build_events(inputs, Vec::<QmEarning<i32>>::new());
let s = built.stats;
assert_eq!(s.filings_in, 5_000);
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
);
assert_eq!(s.rows_out, built.rows.len());
// Every emitted row came from a string that parses successfully on its own.
for row in &built.rows {
assert_eq!(row.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP);
assert_eq!(row.ts_micros, row.known_at_micros);
}
}
#[test]
fn qa_skipped_or_non_qualifying_same_day_filings_never_anchor_earnings() {
let report = day(2025, 1, 31);
let filings = vec![
// Same key, same ET date, qualifying form, but each row is unparseable → must not link.
filing(1, "2025-01-31T07:00:00 PST", "8-K", Some("bad-zone")),
filing(
1,
"2025-01-31T25:00:00 EST",
"News release",
Some("bad-time"),
),
filing(1, "2025-01-31 07:00:00 EST", "8-K/A", Some("bad-format")),
// Valid but non-qualifying forms on the same day.
filing(1, "2025-01-31T06:00:00 EST", "10-Q", Some("q")),
filing(1, "2025-01-31T06:30:00 EST", "NT 10-K", Some("nt")),
filing(1, "2025-01-31T06:45:00 EST", "MD&A", Some("mda")),
];
let built = build_events(filings, vec![earning(1, report, "BTO", 1.0)]);
let e: Vec<_> = built
.rows
.iter()
.filter(|r| r.kind == EVENT_KIND_EARNINGS)
.collect();
assert_eq!(e.len(), 1);
assert_eq!(e[0].known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG);
// 2025-01-31 is EST → 16:05 ET == 21:05Z.
assert_eq!(
e[0].known_at_micros,
oracle_utc_micros(2025, 1, 31, 21, 5, 0, 0)
);
assert!(e[0].payload_json.contains("\"linked_filing_id\":null"));
assert_eq!(built.stats.earnings_linked_to_filing, 0);
assert_eq!(built.stats.earnings_lagged_1605, 1);
assert_eq!(built.stats.filings_skipped_unknown_zone, 1);
assert_eq!(built.stats.filings_skipped_invalid_date_time, 1);
assert_eq!(built.stats.filings_skipped_malformed_timestamp, 1);
}
#[test]
fn qa_nt_and_variant_edgar_forms_are_not_periodic_reports() {
use curate_etl::{classify_form_type, is_periodic_financial_report, FilingFormGroup};
// A late-filing notice must never be treated as the periodic report itself (PIT join safety).
for raw in [
"NT 10-K", "NT 10-Q", "10-K405", "10-KT", "10-QT", "8-K12B", "40-FR12B",
] {
assert!(
!is_periodic_financial_report(raw),
"{raw:?} must not be periodic"
);
assert_eq!(classify_form_type(raw).0, FilingFormGroup::Other, "{raw:?}");
}
// `/A` with internal whitespace still keeps the base group.
assert_eq!(
classify_form_type("10-K /A"),
(FilingFormGroup::Form10K, true)
);
assert_eq!(classify_form_type("8-k/a"), (FilingFormGroup::Form8K, true));
}
#[test]
fn qa_earnings_duplicates_normalize_announce_time_and_conflicting_times_drop_group() {
let d = day(2025, 7, 15);
let earnings = vec![
// Same normalized announce time ("bto") → collapse.
earning(1, d, "BTO", 2.0),
earning(1, d, " bto ", 2.0),
// "N/A" vs "other code" both normalize to "unknown" → collapse.
earning(2, d, "N/A", 3.0),
earning(2, d, "TBD", 3.0),
// BTO vs AMC for the same (key, report_date) → conflict, whole group dropped.
earning(3, d, "BTO", 4.0),
earning(3, d, "AMC", 4.0),
earning(3, d, "AMC", 4.0),
];
let built = build_events(Vec::<QmFiling<i32>>::new(), earnings);
let s = built.stats;
assert_eq!(s.earnings_in, 7);
assert_eq!(s.earnings_out, 2);
assert_eq!(s.earnings_duplicate_collapsed, 2);
assert_eq!(s.earnings_duplicate_conflict_dropped, 3);
assert!(built.rows.iter().all(|r| r.key != 3));
let subtypes: Vec<_> = built
.rows
.iter()
.map(|r| (r.key, r.subtype.as_str()))
.collect();
assert_eq!(subtypes, vec![(1, "bto"), (2, "unknown")]);
// 2025-07-15 is EDT → 16:05 ET == 20:05Z.
for row in &built.rows {
assert_eq!(
row.known_at_micros,
oracle_utc_micros(2025, 7, 15, 20, 5, 0, 0)
);
}
}
#[test]
fn qa_supported_range_boundaries_are_inclusive_for_unlinked_earnings() {
use curate_etl::{MAX_SUPPORTED_DATE, MIN_SUPPORTED_DATE};
let earnings = vec![
earning(1, MIN_SUPPORTED_DATE, "AMC", 1.0),
earning(2, MAX_SUPPORTED_DATE, "AMC", 1.0),
earning(3, MIN_SUPPORTED_DATE - 1, "AMC", 1.0),
earning(4, MAX_SUPPORTED_DATE + 1, "AMC", 1.0),
earning(5, i32::MIN, "AMC", 1.0),
earning(6, i32::MAX, "AMC", 1.0),
];
let built = build_events(Vec::<QmFiling<i32>>::new(), earnings);
assert_eq!(built.stats.earnings_out, 2);
assert_eq!(built.stats.earnings_skipped_out_of_range, 4);
// 2008-01-01 (EST) → 21:05Z; 2030-12-31 (EST) → 21:05Z.
assert_eq!(
built.rows[0].known_at_micros,
oracle_utc_micros(2008, 1, 1, 21, 5, 0, 0)
);
assert_eq!(
built.rows[1].known_at_micros,
oracle_utc_micros(2030, 12, 31, 21, 5, 0, 0)
);
}
/// Extracts the `"report_date":"YYYY-MM-DD"` field from an earnings payload.
fn payload_report_date(payload: &str) -> String {
let marker = "\"report_date\":\"";
let start = payload.find(marker).expect("report_date present") + marker.len();
payload[start..start + 10].to_string()
}
#[test]
fn qa_seeded_truncation_rebuild_matches_full_build_for_every_cutoff() {
// Lens truncation test: deleting everything dated at/after ET date D and rebuilding must
// reproduce exactly the full build's rows dated before D (no future-dependent output).
let mut rng = QaRng(0x7A0C_A710_0000_0077);
let forms = [
"8-K",
"News release",
"4",
"10-Q",
"8-K/A",
"Annual financial statements",
];
let start = day(2024, 1, 1);
let span = 120u64;
let mut filings = Vec::new();
for i in 0..3_000 {
let key = (rng.next() % 40) as i32;
let d = start + (rng.next() % span) as i32;
let (y, m, dd) = epoch_ymd(d);
// Include late-evening ET times that cross into the next UTC day; EST only so the
// ET-date cutoff maps to a single UTC instant.
let hour = [6, 9, 12, 16, 17, 21, 23][(rng.next() % 7) as usize];
let ts = format!(
"{y:04}-{m:02}-{dd:02}T{hour:02}:{:02}:{:02} EST",
rng.next() % 60,
rng.next() % 60
);
filings.push((
d,
filing(
key,
&ts,
forms[(rng.next() % 6) as usize],
Some(&format!("t{i}")),
),
));
}
let mut earnings = Vec::new();
for _ in 0..600 {
let key = (rng.next() % 40) as i32;
let d = start + (rng.next() % span) as i32;
let at = ["BTO", "AMC", "N/A"][(rng.next() % 3) as usize];
earnings.push((d, earning(key, d, at, (rng.next() % 500) as f64 / 100.0)));
}
let full = build_events(
filings.iter().map(|(_, f)| f.clone()),
earnings.iter().map(|(_, e)| e.clone()),
);
for offset in [1, 17, 45, 60, 89, 119] {
let cutoff = start + offset;
let (cy, cm, cd) = epoch_ymd(cutoff);
let cutoff_str = format!("{cy:04}-{cm:02}-{cd:02}");
let cutoff_utc = i64::from(cutoff) * MICROS_PER_DAY + 5 * MICROS_PER_HOUR;
let truncated = build_events(
filings
.iter()
.filter(|(d, _)| *d < cutoff)
.map(|(_, f)| f.clone()),
earnings
.iter()
.filter(|(d, _)| *d < cutoff)
.map(|(_, e)| e.clone()),
);
let expected: Vec<_> = full
.rows
.iter()
.filter(|r| {
if r.kind == EVENT_KIND_EARNINGS {
payload_report_date(&r.payload_json) < cutoff_str
} else {
r.ts_micros < cutoff_utc
}
})
.cloned()
.collect();
assert_eq!(
truncated.rows, expected,
"truncation mismatch at cutoff {cutoff_str}"
);
}
}
fn epoch_ymd(epoch_day: i32) -> (i32, u32, u32) {
curate_etl::shorts::epoch_days_to_ymd(epoch_day)
}