T-143: tests

This commit is contained in:
Studio 2026-12-01 22:05:43 -05:00
parent 288fdec14d
commit 065af2eade

View file

@ -1263,3 +1263,615 @@ fn publish_failure_on_later_year_rolls_back_replaced_and_new_partitions() {
assert!(part_2025.is_dir());
assert_no_transient_files(&tmp.path().join("fundamentals_pit"));
}
// ---------------------------------------------------------------------------------------------
// QA additions (T-143): full-row round-trip equality, builder estimated-lag provenance,
// partial-rewrite semantics, deterministic bytes, and remaining typed validation errors.
// ---------------------------------------------------------------------------------------------
/// Expected decoded form of a row: what the reader must see after a write/read round trip.
fn expected_decoded(row: &FundamentalsPitParquetRow) -> DecodedFundamentalsPitRow {
let latest = row
.latest_period()
.expect("expected row must have a latest period");
let ttm = row.ttm.as_ref();
DecodedFundamentalsPitRow {
listing_id: row.listing_id,
effective_known_at: row.effective_known_at_micros,
known_at_source: row.known_at_source.to_string(),
has_estimated_lag: row.has_estimated_lag,
period_end: latest.period_end,
fiscal_period: latest.fiscal_period.to_string(),
currency: latest.currency.clone(),
period_known_at: latest.period_known_at_micros,
revenue: latest.fields.revenue,
net_income: latest.fields.net_income,
operating_cash_flow: latest.fields.operating_cash_flow,
total_assets: latest.fields.total_assets,
total_equity: latest.fields.total_equity,
shares_outstanding: latest.fields.shares_outstanding,
ttm_period_end: ttm.map(|t| t.ending_period_end),
ttm_currency: ttm.map(|t| t.currency.clone()),
ttm_revenue: ttm.and_then(|t| t.flows.revenue),
ttm_net_income: ttm.and_then(|t| t.flows.net_income),
ttm_operating_cash_flow: ttm.and_then(|t| t.flows.operating_cash_flow),
ttm_has_estimated_lag: ttm.map(|t| t.has_estimated_lag),
}
}
fn read_year(out_dir: &Path, year: i32) -> Vec<DecodedFundamentalsPitRow> {
read_parquet_rows(&out_dir.join(format!("fundamentals_pit/year={year}/part.parquet")))
}
fn list_year_dirs(out_dir: &Path) -> Vec<String> {
let mut names: Vec<String> = fs::read_dir(out_dir.join("fundamentals_pit"))
.expect("read dataset dir")
.map(|e| e.expect("entry").file_name().to_string_lossy().into_owned())
.filter(|n| n.starts_with("year="))
.collect();
names.sort();
names
}
/// Deterministic LCG so fixtures are reproducible without an RNG crate.
struct Lcg(u64);
impl Lcg {
fn next_u32(&mut self) -> u32 {
self.0 = self
.0
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
(self.0 >> 33) as u32
}
fn chance(&mut self, pct: u32) -> bool {
self.next_u32() % 100 < pct
}
fn opt(&mut self, pct_null: u32, v: f64) -> Option<f64> {
if self.chance(pct_null) {
None
} else {
Some(v)
}
}
}
#[test]
fn partition_files_contain_exact_expected_row_sequence_per_year() {
let tmp = TempDirGuard::new("qa-partition-exact");
let ttm = |end: i32, rev: f64| FundamentalsTtm {
ending_period_end: end,
currency: "USD".to_string(),
flows: TtmFlowFields {
revenue: Some(rev),
net_income: None,
operating_cash_flow: Some(rev / 2.0),
},
has_estimated_lag: false,
};
let ts_2023_end = utc_micros(2023, 12, 31, 23, 59, 59, 999_999);
let ts_2024_start = utc_micros(2024, 1, 1, 0, 0, 0, 0);
let rows = vec![
make_row(
1,
utc_micros(2023, 5, 1, 14, 0, 0, 0),
day(2023, 3, 31),
Some(10.0),
None,
),
make_row(
1,
ts_2023_end,
day(2023, 9, 30),
Some(11.0),
Some(ttm(day(2023, 9, 30), 40.0)),
),
make_row(
1,
ts_2024_start,
day(2023, 12, 31),
Some(12.0),
Some(ttm(day(2023, 12, 31), 44.0)),
),
make_row(
2,
utc_micros(2023, 8, 1, 14, 0, 0, 0),
day(2023, 6, 30),
None,
None,
),
make_row(
2,
utc_micros(2024, 2, 1, 14, 0, 0, 0),
day(2023, 12, 31),
Some(21.0),
None,
),
make_row(
3,
utc_micros(2023, 11, 1, 14, 0, 0, 0),
day(2023, 9, 30),
Some(30.0),
None,
),
make_row(
3,
utc_micros(2024, 5, 1, 14, 0, 0, 0),
day(2024, 3, 31),
Some(31.0),
Some(ttm(day(2024, 3, 31), 120.0)),
),
];
write_fundamentals_pit_dataset(
tmp.path(),
&rows,
FundamentalsPitWriteOptions {
row_group_rows: 2,
zstd_level: DEFAULT_ZSTD_LEVEL,
},
)
.expect("write");
let expected_2023: Vec<_> = [0, 1, 3, 5]
.iter()
.map(|&i| expected_decoded(&rows[i]))
.collect();
let expected_2024: Vec<_> = [2, 4, 6]
.iter()
.map(|&i| expected_decoded(&rows[i]))
.collect();
assert_eq!(list_year_dirs(tmp.path()), vec!["year=2023", "year=2024"]);
assert_eq!(read_year(tmp.path(), 2023), expected_2023);
assert_eq!(read_year(tmp.path(), 2024), expected_2024);
}
#[test]
fn seeded_mixed_null_patterns_round_trip_across_many_row_groups() {
let tmp = TempDirGuard::new("qa-seeded");
let mut rng = Lcg(0x5EED_1430);
let mut rows = Vec::new();
for listing_id in 1..=9_i32 {
for q in 0..12_i32 {
// One quarter apart; spans 2021..=2023 so multiple partitions get interleaved.
let ts = utc_micros(
2021 + q / 4,
(q % 4) as u32 * 3 + 2,
10,
20,
30,
0,
i64::from(listing_id),
);
let period_end = day(2021 + q / 4, (q % 4) as u32 * 3 + 1, 1);
let base = f64::from(listing_id * 1000 + q);
let estimated = rng.chance(30);
let currency = if rng.chance(20) { "CAD" } else { "USD" };
let ttm = if rng.chance(40) {
None
} else {
Some(FundamentalsTtm {
ending_period_end: period_end,
currency: currency.to_string(),
flows: TtmFlowFields {
revenue: rng.opt(25, base * 4.0),
net_income: rng.opt(25, -base * 0.25),
operating_cash_flow: rng.opt(25, 0.0),
},
has_estimated_lag: rng.chance(50),
})
};
rows.push(FundamentalsPitParquetRow::new(
listing_id,
ts,
Cow::Borrowed(if estimated {
KNOWN_AT_SOURCE_STATUTORY_LAG
} else {
KNOWN_AT_SOURCE_FILING_TIMESTAMP
}),
estimated,
FundamentalsPitLatestPeriod {
period_end,
fiscal_period: Cow::Borrowed(if q % 4 == 3 { "FY" } else { "Q" }),
currency: currency.to_string(),
period_known_at_micros: ts - 1,
fields: FundamentalsFields {
revenue: rng.opt(20, base),
net_income: rng.opt(20, -base / 10.0),
operating_cash_flow: rng.opt(20, base / 7.0),
total_assets: rng.opt(20, base * 5.0),
total_equity: rng.opt(20, base * 2.0),
shares_outstanding: rng.opt(20, 1.0e9),
},
},
ttm,
));
}
}
// Sanity: the fixture really exercises all-null and all-present TTM in the same file.
assert!(rows.iter().any(|r| r.ttm.is_none()));
assert!(rows
.iter()
.any(|r| r.ttm.as_ref().is_some_and(|t| t.flows.revenue.is_none())));
let stats = write_fundamentals_pit_dataset(
tmp.path(),
&rows,
FundamentalsPitWriteOptions {
row_group_rows: 5,
zstd_level: 1,
},
)
.expect("write seeded dataset");
assert_eq!(stats.rows_written, rows.len());
assert_eq!(
stats.rows_by_year,
BTreeMap::from([(2021, 36), (2022, 36), (2023, 36)])
);
// 36 rows per year at 5 rows per group -> 8 groups per year.
assert_eq!(stats.row_groups_written, 24);
for year in 2021..=2023 {
let expected: Vec<_> = rows
.iter()
.filter(|r| partition_year_utc(r.effective_known_at_micros) == year)
.map(expected_decoded)
.collect();
assert_eq!(read_year(tmp.path(), year), expected, "year {year}");
}
assert_no_transient_files(&tmp.path().join("fundamentals_pit"));
}
#[test]
fn builder_statutory_lag_snapshots_keep_estimated_provenance_on_disk() {
// Listing 7 (TSXV/CSE venue) files Q1 via a 10-Q; Q2 has no filing and no report date,
// so its known_at falls back to period_end + 60d at 16:05 America/Toronto.
let listing_id = 7_i32;
let venues = BTreeMap::from([(listing_id, StatutoryLagVenue::TsxvCse)]);
let p_q1 = day(2024, 3, 31);
let p_q2 = day(2024, 6, 30);
let fields = |rev: f64| FundamentalsFields {
revenue: Some(rev),
net_income: Some(rev / 10.0),
operating_cash_flow: None,
total_assets: Some(900.0),
total_equity: Some(400.0),
shares_outstanding: Some(50.0),
};
let observations = vec![
obs(
listing_id,
p_q1,
FiscalPeriod::Quarterly,
"CAD",
None,
fields(100.0),
),
obs(
listing_id,
p_q2,
FiscalPeriod::Quarterly,
"CAD",
None,
fields(130.0),
),
];
let filings = vec![filing(listing_id, "2024-05-10T16:30:00 EDT", "10-Q")];
let build = build_fundamentals_rows(observations, filings, &venues);
let snaps = build_fundamentals_snapshots(&build.rows, 4).expect("snapshots");
assert_eq!(snaps.len(), 2);
let rows: Vec<FundamentalsPitParquetRow> =
snaps.iter().map(FundamentalsPitParquetRow::from).collect();
let tmp = TempDirGuard::new("qa-estimated");
write_fundamentals_pit_dataset(tmp.path(), &rows, FundamentalsPitWriteOptions::default())
.expect("write");
let decoded = read_year(tmp.path(), 2024);
assert_eq!(
decoded,
rows.iter().map(expected_decoded).collect::<Vec<_>>()
);
// Q1: filing-backed, at the 10-Q's UTC timestamp.
let ts_q1 = utc_micros(2024, 5, 10, 20, 30, 0, 0);
assert_eq!(decoded[0].effective_known_at, ts_q1);
assert_eq!(decoded[0].known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP);
assert!(!decoded[0].has_estimated_lag);
assert_eq!(decoded[0].period_end, p_q1);
assert_eq!(decoded[0].period_known_at, ts_q1);
assert_eq!(decoded[0].currency, "CAD");
// Q2: estimated, 2024-06-30 + 60d = 2024-08-29 16:05 EDT = 20:05 UTC.
let ts_q2_est = utc_micros(2024, 8, 29, 20, 5, 0, 0);
assert_eq!(decoded[1].effective_known_at, ts_q2_est);
assert_eq!(decoded[1].known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG);
assert!(decoded[1].has_estimated_lag);
assert_eq!(decoded[1].period_end, p_q2);
assert_eq!(decoded[1].period_known_at, ts_q2_est);
assert_eq!(decoded[1].revenue, Some(130.0));
assert_eq!(decoded[1].operating_cash_flow, None);
// Only two quarters exist, so TTM is unavailable and every ttm_* column is null.
for r in &decoded {
assert_eq!(r.ttm_period_end, None);
assert_eq!(r.ttm_currency, None);
assert_eq!(r.ttm_revenue, None);
assert_eq!(r.ttm_net_income, None);
assert_eq!(r.ttm_operating_cash_flow, None);
assert_eq!(r.ttm_has_estimated_lag, None);
}
}
#[test]
fn rewrite_replaces_only_years_present_in_new_input() {
let tmp = TempDirGuard::new("qa-rewrite");
let first = vec![
make_row(
1,
utc_micros(2023, 5, 1, 14, 0, 0, 0),
day(2023, 3, 31),
Some(10.0),
None,
),
make_row(
1,
utc_micros(2024, 5, 1, 14, 0, 0, 0),
day(2024, 3, 31),
Some(20.0),
None,
),
];
write_fundamentals_pit_dataset(tmp.path(), &first, FundamentalsPitWriteOptions::default())
.expect("first write");
let part_2023 = tmp.path().join("fundamentals_pit/year=2023/part.parquet");
let bytes_2023 = fs::read(&part_2023).expect("read 2023");
let second = vec![
make_row(
5,
utc_micros(2024, 2, 1, 14, 0, 0, 0),
day(2023, 12, 31),
Some(55.0),
None,
),
make_row(
5,
utc_micros(2024, 6, 1, 14, 0, 0, 0),
day(2024, 3, 31),
Some(56.0),
None,
),
];
let stats =
write_fundamentals_pit_dataset(tmp.path(), &second, FundamentalsPitWriteOptions::default())
.expect("second write");
assert_eq!(stats.rows_by_year, BTreeMap::from([(2024, 2)]));
// 2024 is fully replaced (no merge with old rows); 2023 is untouched byte for byte.
assert_eq!(
read_year(tmp.path(), 2024),
second.iter().map(expected_decoded).collect::<Vec<_>>()
);
assert_eq!(fs::read(&part_2023).expect("reread 2023"), bytes_2023);
assert_no_transient_files(&tmp.path().join("fundamentals_pit"));
}
#[test]
fn identical_input_produces_byte_identical_partitions() {
let rows = vec![
make_row(
1,
utc_micros(2023, 5, 1, 14, 0, 0, 0),
day(2023, 3, 31),
Some(10.0),
None,
),
make_row(
2,
utc_micros(2024, 5, 1, 14, 0, 0, 0),
day(2024, 3, 31),
None,
None,
),
];
let a = TempDirGuard::new("qa-determinism-a");
let b = TempDirGuard::new("qa-determinism-b");
let opts = FundamentalsPitWriteOptions {
row_group_rows: 1,
zstd_level: DEFAULT_ZSTD_LEVEL,
};
write_fundamentals_pit_dataset(a.path(), &rows, opts).expect("write a");
write_fundamentals_pit_dataset(b.path(), &rows, opts).expect("write b");
for year in [2023, 2024] {
let rel = format!("fundamentals_pit/year={year}/part.parquet");
assert_eq!(
fs::read(a.path().join(&rel)).expect("read a"),
fs::read(b.path().join(&rel)).expect("read b"),
"year {year} bytes differ between identical runs"
);
}
}
#[test]
fn remaining_validation_errors_are_typed_and_publish_nothing() {
let ts = utc_micros(2024, 5, 1, 20, 0, 0, 0);
let valid = make_row(1, ts - 1, day(2024, 3, 31), Some(1.0), None);
let defaults = FundamentalsPitWriteOptions::default();
let run = |label: &str, bad: FundamentalsPitParquetRow, opts: FundamentalsPitWriteOptions| {
let tmp = TempDirGuard::new(label);
let err = write_fundamentals_pit_dataset(tmp.path(), [valid.clone(), bad], opts)
.expect_err("invalid input must fail");
let year_dir = tmp.path().join("fundamentals_pit/year=2024");
assert!(
!year_dir.join("part.parquet").exists(),
"{label}: partial file published"
);
assert_no_transient_files(&tmp.path().join("fundamentals_pit"));
err
};
let mut nan_row = make_row(1, ts, day(2024, 3, 31), Some(f64::NAN), None);
nan_row.has_estimated_lag = true;
let err = run("qa-nan", nan_row, defaults);
assert!(
matches!(
err,
ParquetFundamentalsError::NonFiniteValue {
row_index: 1,
field: "revenue",
..
}
),
"got {err:?}"
);
let inf_ttm = make_row(
1,
ts,
day(2024, 3, 31),
Some(1.0),
Some(FundamentalsTtm {
ending_period_end: day(2024, 3, 31),
currency: "USD".to_string(),
flows: TtmFlowFields {
revenue: Some(1.0),
net_income: None,
operating_cash_flow: Some(f64::INFINITY),
},
has_estimated_lag: false,
}),
);
let err = run("qa-inf-ttm", inf_ttm, defaults);
assert!(
matches!(
err,
ParquetFundamentalsError::NonFiniteValue {
field: "ttm_operating_cash_flow",
..
}
),
"got {err:?}"
);
let mut blank_source = make_row(1, ts, day(2024, 3, 31), Some(1.0), None);
blank_source.known_at_source = Cow::Borrowed(" ");
let err = run("qa-blank-source", blank_source, defaults);
assert!(
matches!(
err,
ParquetFundamentalsError::EmptyKnownAtSource { row_index: 1, .. }
),
"got {err:?}"
);
let blank_ttm_currency = make_row(
1,
ts,
day(2024, 3, 31),
Some(1.0),
Some(FundamentalsTtm {
ending_period_end: day(2024, 3, 31),
currency: String::new(),
flows: TtmFlowFields {
revenue: None,
net_income: None,
operating_cash_flow: None,
},
has_estimated_lag: false,
}),
);
let err = run("qa-blank-ttm-ccy", blank_ttm_currency, defaults);
assert!(
matches!(
err,
ParquetFundamentalsError::EmptyTtmCurrency { row_index: 1, .. }
),
"got {err:?}"
);
let blank_currency = FundamentalsPitParquetRow::new(
1,
ts,
Cow::Borrowed(KNOWN_AT_SOURCE_FILING_TIMESTAMP),
false,
FundamentalsPitLatestPeriod {
period_end: day(2024, 3, 31),
fiscal_period: Cow::Borrowed("Q"),
currency: String::new(),
period_known_at_micros: ts,
fields: FundamentalsFields {
revenue: None,
net_income: None,
operating_cash_flow: None,
total_assets: None,
total_equity: None,
shares_outstanding: None,
},
},
None,
);
let err = run("qa-blank-ccy", blank_currency, defaults);
assert!(
matches!(
err,
ParquetFundamentalsError::EmptyCurrency { row_index: 1, .. }
),
"got {err:?}"
);
// Year 2201 is above MAX_PARQUET_YEAR (2200).
let far_future = make_row(
1,
utc_micros(2201, 1, 1, 0, 0, 0, 0),
day(2024, 3, 31),
Some(1.0),
None,
);
let err = run("qa-year-range", far_future, defaults);
assert!(
matches!(
err,
ParquetFundamentalsError::PartitionYearOutOfRange {
row_index: 1,
year: 2201,
..
}
),
"got {err:?}"
);
// Option validation happens before any filesystem side effects.
let tmp = TempDirGuard::new("qa-bad-options");
let err = write_fundamentals_pit_dataset(
tmp.path(),
[valid.clone()],
FundamentalsPitWriteOptions {
row_group_rows: 0,
zstd_level: DEFAULT_ZSTD_LEVEL,
},
)
.unwrap_err();
assert!(
matches!(err, ParquetFundamentalsError::InvalidRowGroupRows),
"got {err:?}"
);
let err = write_fundamentals_pit_dataset(
tmp.path(),
[valid],
FundamentalsPitWriteOptions {
row_group_rows: 1,
zstd_level: 99,
},
)
.unwrap_err();
assert!(
matches!(
err,
ParquetFundamentalsError::InvalidZstdLevel { level: 99 }
),
"got {err:?}"
);
assert!(!tmp.path().join("fundamentals_pit").exists());
}