T-77: M1.2g — tools/curate-etl: pure events builder (qmFilings timefiled → UTC + form groups; qmEarnings linked to same-day filing or lagged to 16:05 ET) with local benchmark (no new crates)
This commit is contained in:
parent
9bd77a6869
commit
3100ec65b1
9 changed files with 2644 additions and 8 deletions
|
|
@ -1,6 +1,6 @@
|
|||
# `curate-etl`
|
||||
|
||||
Dedicated zero-dependency Rust crate for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, the `M1.2c` pure `corporate_actions` event-log builder, the `M1.2d` pure `bars_1d` daily bar builder + `qmPrices.sharevolume` cross-check, 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<K>`) and `qmEarnings` (`QmEarning<K>`) streams into deterministically sorted point-in-time `EventRow<K>` 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:
|
||||
|
||||
|
|
|
|||
|
|
@ -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<ShortsBenchReport, ShortsErro
|
|||
})
|
||||
}
|
||||
|
||||
/// Summary metrics produced by [`run_events_benchmark`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct EventsBenchReport {
|
||||
pub rows: usize,
|
||||
pub filings_in: usize,
|
||||
pub earnings_in: usize,
|
||||
pub key_count: usize,
|
||||
pub rows_out: usize,
|
||||
pub keys_out: usize,
|
||||
pub build_elapsed_ms: f64,
|
||||
pub rows_per_sec: f64,
|
||||
pub ns_per_row: f64,
|
||||
pub checksum: u64,
|
||||
pub stats: EventsStats,
|
||||
}
|
||||
|
||||
const BENCH_FORM_TYPES: &[&str] = &[
|
||||
"8-K",
|
||||
"News release",
|
||||
"4",
|
||||
"10-Q",
|
||||
"10-K",
|
||||
"10-K/A",
|
||||
"144",
|
||||
"40-F",
|
||||
"Interim financial statements/report",
|
||||
"Annual financial statements",
|
||||
"MD&A",
|
||||
"52-109",
|
||||
"NI 43-101",
|
||||
"45-106F1",
|
||||
"424B5",
|
||||
"8-K/A",
|
||||
];
|
||||
|
||||
const BENCH_ANNOUNCE_TIMES: &[&str] = &["N/A", "AMC", "BTO"];
|
||||
|
||||
fn mix_bytes(mut hash: u64, bytes: &[u8]) -> u64 {
|
||||
let mut chunks = bytes.chunks_exact(8);
|
||||
for chunk in &mut chunks {
|
||||
let mut buf = [0u8; 8];
|
||||
buf.copy_from_slice(chunk);
|
||||
hash = mix_u64(hash, u64::from_le_bytes(buf));
|
||||
}
|
||||
let rem = chunks.remainder();
|
||||
if !rem.is_empty() {
|
||||
let mut buf = [0u8; 8];
|
||||
buf[..rem.len()].copy_from_slice(rem);
|
||||
hash = mix_u64(hash, u64::from_le_bytes(buf));
|
||||
}
|
||||
mix_u64(hash, bytes.len() as u64)
|
||||
}
|
||||
|
||||
/// Runs the fixed-seed `build_events` benchmark for `rows` total synthetic `qmFilings` (~98.5%)
|
||||
/// and `qmEarnings` (~1.5%) rows across `20_000` `i32` `listing_id` keys.
|
||||
///
|
||||
/// Mirrors the empirical `30.52M` filings / `444.9k` earnings ratio with EST/EDT/pre-2008/
|
||||
/// late-evening timestamps, all EDGAR and SEDAR+ form groups, linked + unlinked earnings, and
|
||||
/// small shares of malformed/skipped/duplicate/conflicting rows. Shuffles both inputs
|
||||
/// deterministically, times only [`build_events`], and returns throughput plus a deterministic
|
||||
/// `u64` checksum.
|
||||
pub fn run_events_benchmark(rows: usize) -> EventsBenchReport {
|
||||
if rows == 0 {
|
||||
let built = build_events::<i32, _, _>(Vec::new(), Vec::new());
|
||||
return EventsBenchReport {
|
||||
rows: 0,
|
||||
filings_in: 0,
|
||||
earnings_in: 0,
|
||||
key_count: BENCH_KEY_COUNT,
|
||||
rows_out: 0,
|
||||
keys_out: 0,
|
||||
build_elapsed_ms: 0.0,
|
||||
rows_per_sec: 0.0,
|
||||
ns_per_row: 0.0,
|
||||
checksum: 0,
|
||||
stats: built.stats,
|
||||
};
|
||||
}
|
||||
|
||||
let min_filing_date = ymd_to_epoch_days(2003, 1, 1).unwrap_or(12_053);
|
||||
let max_filing_date = ymd_to_epoch_days(2026, 4, 30).unwrap_or(20_573);
|
||||
let filing_span = (max_filing_date - min_filing_date + 1) as u64;
|
||||
|
||||
let min_earning_date = ymd_to_epoch_days(2008, 1, 1).unwrap_or(13_879);
|
||||
let max_earning_date = ymd_to_epoch_days(2026, 4, 30).unwrap_or(20_573);
|
||||
let earning_span = (max_earning_date - min_earning_date + 1) as u64;
|
||||
|
||||
let earnings_target = (rows * 15) / 1_000;
|
||||
let filings_target = rows - earnings_target;
|
||||
|
||||
let mut rng = SplitMix64::new(EVENTS_BENCH_SEED);
|
||||
let mut filings: Vec<QmFiling<i32>> = Vec::with_capacity(filings_target);
|
||||
let mut link_pool: Vec<(i32, i32)> = Vec::with_capacity(earnings_target.min(16_384));
|
||||
let mut last_valid_filing: Option<QmFiling<i32>> = None;
|
||||
|
||||
for idx in 0..filings_target {
|
||||
let roll = rng.next_u64() % 1_000;
|
||||
if roll < 5 {
|
||||
if let Some(prev) = last_valid_filing.clone() {
|
||||
filings.push(prev);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
let key = (rng.next_u64() % (BENCH_KEY_COUNT as u64)) as i32 + 1;
|
||||
let epoch_day = min_filing_date + (rng.next_u64() % filing_span) as i32;
|
||||
let (y, m, d) = epoch_days_to_ymd(epoch_day);
|
||||
let form_idx = (rng.next_u64() as usize) % BENCH_FORM_TYPES.len();
|
||||
let form_type = BENCH_FORM_TYPES[form_idx].to_string();
|
||||
let filing_id = if rng.next_u64() % 10 == 0 {
|
||||
None
|
||||
} else {
|
||||
Some(format!("F{idx:08}"))
|
||||
};
|
||||
let url = if rng.next_u64() % 4 == 0 {
|
||||
None
|
||||
} else {
|
||||
Some(format!("https://filings.example/{key}/{idx}"))
|
||||
};
|
||||
|
||||
let timefiled = match roll {
|
||||
5..=7 => "bad-timestamp".to_string(),
|
||||
8..=10 => format!("{y:04}-{m:02}-{d:02}T12:00:00 PST"),
|
||||
11..=13 => format!("{y:04}-02-30T12:00:00 EST"),
|
||||
14..=15 => format!("{y:04}-{m:02}-{d:02}T25:00:00 EST"),
|
||||
_ => {
|
||||
// Mix morning, midday, and late-evening ET (crossing into next UTC day).
|
||||
let hour = if roll < 60 {
|
||||
21 + (rng.next_u64() % 3) as u32
|
||||
} else {
|
||||
6 + (rng.next_u64() % 13) as u32
|
||||
};
|
||||
let minute = (rng.next_u64() % 60) as u32;
|
||||
let second = (rng.next_u64() % 60) as u32;
|
||||
let zone = if (4..=10).contains(&m) { "EDT" } else { "EST" };
|
||||
let ts = format!("{y:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02} {zone}");
|
||||
if matches!(form_idx, 0 | 1 | 15) && link_pool.len() < 16_384 {
|
||||
link_pool.push((key, epoch_day));
|
||||
}
|
||||
ts
|
||||
}
|
||||
};
|
||||
|
||||
let row = QmFiling {
|
||||
key,
|
||||
timefiled,
|
||||
form_type,
|
||||
filing_id,
|
||||
url,
|
||||
};
|
||||
if roll >= 16 {
|
||||
last_valid_filing = Some(row.clone());
|
||||
}
|
||||
filings.push(row);
|
||||
}
|
||||
|
||||
let mut earnings: Vec<QmEarning<i32>> = Vec::with_capacity(earnings_target);
|
||||
let mut last_valid_earning: Option<QmEarning<i32>> = None;
|
||||
|
||||
for _ in 0..earnings_target {
|
||||
let roll = rng.next_u64() % 1_000;
|
||||
if roll < 15 {
|
||||
if let Some(prev) = last_valid_earning.clone() {
|
||||
earnings.push(prev);
|
||||
continue;
|
||||
}
|
||||
} else if roll < 25 {
|
||||
if let Some(mut prev) = last_valid_earning.clone() {
|
||||
prev.actual_eps = Some(prev.actual_eps.unwrap_or(0.0) + 0.10);
|
||||
earnings.push(prev);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
let (key, report_date) = if roll < 30 && !link_pool.is_empty() {
|
||||
// Out-of-range unlinked date (< 2008-01-01)
|
||||
let k = (rng.next_u64() % (BENCH_KEY_COUNT as u64)) as i32 + 1;
|
||||
let d = ymd_to_epoch_days(2005, 6, 15).unwrap_or(12_949);
|
||||
(k, d)
|
||||
} else if roll < 450 && !link_pool.is_empty() {
|
||||
let pick = (rng.next_u64() as usize) % link_pool.len();
|
||||
link_pool[pick]
|
||||
} else {
|
||||
let k = (rng.next_u64() % (BENCH_KEY_COUNT as u64)) as i32 + 1;
|
||||
let d = min_earning_date + (rng.next_u64() % earning_span) as i32;
|
||||
(k, d)
|
||||
};
|
||||
|
||||
let announce_time =
|
||||
BENCH_ANNOUNCE_TIMES[(rng.next_u64() as usize) % BENCH_ANNOUNCE_TIMES.len()]
|
||||
.to_string();
|
||||
let actual_eps = if roll % 50 == 0 {
|
||||
Some(f64::NAN)
|
||||
} else {
|
||||
Some((((rng.next_u64() % 1_000) as f64) - 200.0) * 0.01)
|
||||
};
|
||||
let revenue = Some(((rng.next_u64() % 5_000_000) + 10_000) as f64);
|
||||
|
||||
let row = QmEarning {
|
||||
key,
|
||||
report_date,
|
||||
announce_time,
|
||||
fiscal_period_end: Some(report_date - 35),
|
||||
actual_eps,
|
||||
revenue,
|
||||
};
|
||||
if roll >= 30 {
|
||||
last_valid_earning = Some(row.clone());
|
||||
}
|
||||
earnings.push(row);
|
||||
}
|
||||
|
||||
shuffle_slice(&mut filings, &mut rng);
|
||||
shuffle_slice(&mut earnings, &mut rng);
|
||||
|
||||
let filings_in = filings.len();
|
||||
let earnings_in = earnings.len();
|
||||
|
||||
let build_start = Instant::now();
|
||||
let built = build_events(filings, earnings);
|
||||
let build_elapsed_secs = build_start.elapsed().as_secs_f64();
|
||||
let build_elapsed_ms = build_elapsed_secs * 1_000.0;
|
||||
let (rows_per_sec, ns_per_row) = compute_rates(rows, build_elapsed_secs);
|
||||
|
||||
let mut hash = 0u64;
|
||||
for row in &built.rows {
|
||||
hash = mix_u64(hash, row.key as u64);
|
||||
hash = mix_u64(hash, row.ts_micros as u64);
|
||||
hash = mix_u64(hash, row.known_at_micros as u64);
|
||||
hash = mix_bytes(hash, row.known_at_source.as_bytes());
|
||||
hash = mix_bytes(hash, row.kind.as_bytes());
|
||||
hash = mix_bytes(hash, row.subtype.as_bytes());
|
||||
hash = mix_bytes(hash, row.payload_json.as_bytes());
|
||||
}
|
||||
let checksum = black_box(hash);
|
||||
|
||||
EventsBenchReport {
|
||||
rows,
|
||||
filings_in,
|
||||
earnings_in,
|
||||
key_count: BENCH_KEY_COUNT,
|
||||
rows_out: built.stats.rows_out,
|
||||
keys_out: built.stats.keys_out,
|
||||
build_elapsed_ms,
|
||||
rows_per_sec,
|
||||
ns_per_row,
|
||||
checksum,
|
||||
stats: built.stats,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<CliAction, String> {
|
|||
)),
|
||||
},
|
||||
["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::<usize>() {
|
||||
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"));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
1071
tools/curate-etl/src/events.rs
Normal file
1071
tools/curate-etl/src/events.rs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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));
|
||||
|
|
|
|||
|
|
@ -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="));
|
||||
}
|
||||
|
|
|
|||
887
tools/curate-etl/tests/events_contract.rs
Normal file
887
tools/curate-etl/tests/events_contract.rs
Normal file
|
|
@ -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<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-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<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"));
|
||||
}
|
||||
}
|
||||
232
tools/curate-etl/tests/events_reference.rs
Normal file
232
tools/curate-etl/tests/events_reference.rs
Normal file
|
|
@ -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);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue