922 lines
32 KiB
Rust
922 lines
32 KiB
Rust
//! 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<T>(items: &mut [T], rng: &mut Rng) {
|
|
for i in (1..items.len()).rev() {
|
|
let j = (rng.next() % (i as u64 + 1)) as usize;
|
|
items.swap(i, j);
|
|
}
|
|
}
|
|
|
|
/// 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<u8> {
|
|
self.bytes.get(self.pos).copied()
|
|
}
|
|
|
|
fn parse_value(&mut self) -> Result<JsonVal, String> {
|
|
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<JsonVal, String> {
|
|
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<JsonVal, String> {
|
|
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<String, String> {
|
|
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<JsonVal, String> {
|
|
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::<f64>()
|
|
.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<K: Ord>(build: &EventsBuild<K>) {
|
|
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-K (Amended)", FilingFormGroup::Form10K, "10-k", true, true),
|
|
("10-Q", FilingFormGroup::Form10Q, "10-q", false, true),
|
|
("10-Q/A", FilingFormGroup::Form10Q, "10-q", true, true),
|
|
("10-Q - Amended", FilingFormGroup::Form10Q, "10-q", true, true),
|
|
("8-K", FilingFormGroup::Form8K, "8-k", false, false),
|
|
("8-K/A", FilingFormGroup::Form8K, "8-k", true, false),
|
|
("8-K (Amended)", 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),
|
|
("Amended 40-F", FilingFormGroup::Form40F, "40-f", true, 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");
|
|
|
|
// Regression: `10-K (Amended)` retains subtype `"10-k"` while preserving the raw label in JSON.
|
|
let amended_build = build_events(
|
|
vec![QmFiling {
|
|
key: 7_i32,
|
|
timefiled: "2025-03-03T16:15:00 EST".to_string(),
|
|
form_type: "10-K (Amended)".to_string(),
|
|
filing_id: Some("f-10k-amended".to_string()),
|
|
url: None,
|
|
}],
|
|
Vec::<QmEarning<i32>>::new(),
|
|
);
|
|
assert_accounting_and_order(&amended_build);
|
|
assert_eq!(amended_build.rows.len(), 1);
|
|
assert_eq!(amended_build.rows[0].subtype, "10-k");
|
|
let fields = parse_json_object(&amended_build.rows[0].payload_json);
|
|
assert_eq!(
|
|
fields,
|
|
vec![
|
|
(
|
|
"filing_id".to_string(),
|
|
JsonVal::Str("f-10k-amended".to_string())
|
|
),
|
|
(
|
|
"form_type".to_string(),
|
|
JsonVal::Str("10-K (Amended)".to_string())
|
|
),
|
|
("is_amendment".to_string(), JsonVal::Bool(true)),
|
|
("url".to_string(), JsonVal::Null),
|
|
]
|
|
);
|
|
}
|
|
|
|
#[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<i32> {
|
|
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::<i32, _, _>(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"));
|
|
}
|
|
}
|