T-95: tests

This commit is contained in:
Studio 2026-11-28 15:36:29 -05:00
parent 3fe80d95a4
commit 44ef8cda04

View file

@ -0,0 +1,475 @@
//! QA contract tests for the public `adj_factors` Parquet writer (T-95 / M1.2m).
//!
//! Covers gaps left by `parquet_adj_contract.rs` / `parquet_adj_edge_contract.rs`:
//! - streaming proof: a lazy iterator observes flushed row-group bytes in the staging file
//! before it yields the remaining rows (a collect-then-write writer would fail);
//! - `div_currency` null patterns that land exactly on the 4,096-row string batch boundary;
//! - per-row-group interner reset: currencies that change between row groups keep their labels;
//! - seeded randomized round-trip across several `row_group_rows` values, checking bit-exact
//! values, null positions and `ceil(n / row_group_rows)` row groups in stats and footer.
use std::borrow::Cow;
use std::fs::{self, File};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use curate_etl::{
write_adj_factors_dataset, ymd_to_epoch_days, AdjFactorsParquetRow, AdjFactorsWriteOptions,
};
use parquet::column::reader::ColumnReader;
use parquet::file::reader::{FileReader, SerializedFileReader};
const MICROS_PER_DAY: i64 = 86_400_000_000;
/// Mirrors `parquet_publish::STRING_WRITE_BATCH_ROWS` (crate-private).
const STRING_BATCH: usize = 4_096;
static SEQ: AtomicU64 = AtomicU64::new(0);
struct TempDir(PathBuf);
impl TempDir {
fn new(tag: &str) -> Self {
let seq = SEQ.fetch_add(1, Ordering::Relaxed);
let path = std::env::temp_dir().join(format!(
"curate-etl-pq-adj-qa-{tag}-{}-{seq}",
std::process::id()
));
let _ = fs::remove_dir_all(&path);
fs::create_dir_all(&path).expect("create temp dir");
Self(path)
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
/// Deterministic SplitMix64 (fixed seed per test).
struct Rng(u64);
impl Rng {
fn next_u64(&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)
}
/// Uniform in `[1.0, 2.0)` with a random 52-bit mantissa (incompressible).
fn factor(&mut self) -> f64 {
f64::from_bits(0x3FF0_0000_0000_0000 | (self.next_u64() >> 12))
}
}
fn base_day() -> i32 {
ymd_to_epoch_days(1990, 1, 2).expect("valid date")
}
fn part_path(out: &Path) -> PathBuf {
out.join("adj_factors/part.parquet")
}
fn opts(row_group_rows: usize) -> AdjFactorsWriteOptions {
AdjFactorsWriteOptions {
row_group_rows,
..AdjFactorsWriteOptions::default()
}
}
/// Row `i` of a single listing; `currency = None` makes it split-only.
fn row(i: usize, currency: Option<Cow<'static, str>>, rng: &mut Rng) -> AdjFactorsParquetRow {
let ex_date = base_day() + i32::try_from(i).expect("index fits i32");
let (split_factor, div_cash) = match currency {
None => (rng.factor(), 0.0),
Some(_) => (1.0, rng.factor() - 1.0 + 0.01),
};
AdjFactorsParquetRow {
listing_id: 7,
ex_date,
split_factor,
div_cash,
div_currency: currency,
cum_split_factor: rng.factor(),
cum_total_factor: rng.factor(),
known_at_micros: (i64::from(ex_date) - 14) * MICROS_PER_DAY,
}
}
fn read_rows(path: &Path) -> Vec<AdjFactorsParquetRow> {
let reader = SerializedFileReader::new(File::open(path).expect("open")).expect("reader");
let meta = reader.metadata();
let mut out = Vec::new();
for rg in 0..meta.num_row_groups() {
let rg_reader = reader.get_row_group(rg).expect("rg");
let n = meta.row_group(rg).num_rows() as usize;
let i32s = |idx: usize| -> Vec<i32> {
let mut v = Vec::new();
let ColumnReader::Int32ColumnReader(mut r) =
rg_reader.get_column_reader(idx).expect("col")
else {
panic!("expected INT32 at {idx}");
};
r.read_records(n, None, None, &mut v).expect("read");
v
};
let i64s = |idx: usize| -> Vec<i64> {
let mut v = Vec::new();
let ColumnReader::Int64ColumnReader(mut r) =
rg_reader.get_column_reader(idx).expect("col")
else {
panic!("expected INT64 at {idx}");
};
r.read_records(n, None, None, &mut v).expect("read");
v
};
let f64s = |idx: usize| -> Vec<f64> {
let mut v = Vec::new();
let ColumnReader::DoubleColumnReader(mut r) =
rg_reader.get_column_reader(idx).expect("col")
else {
panic!("expected DOUBLE at {idx}");
};
r.read_records(n, None, None, &mut v).expect("read");
v
};
let opt_strs = |idx: usize| -> Vec<Option<String>> {
let mut vals = Vec::new();
let mut defs = Vec::new();
let ColumnReader::ByteArrayColumnReader(mut r) =
rg_reader.get_column_reader(idx).expect("col")
else {
panic!("expected BYTE_ARRAY at {idx}");
};
let (read, _, levels_read) = r
.read_records(n, Some(&mut defs), None, &mut vals)
.expect("read");
assert_eq!(read, n);
assert_eq!(levels_read, n);
let mut vi = 0usize;
let mut res = Vec::with_capacity(n);
for d in defs {
match d {
0 => res.push(None),
1 => {
res.push(Some(
String::from_utf8(vals[vi].data().to_vec()).expect("utf8"),
));
vi += 1;
}
other => panic!("unexpected def level {other}"),
}
}
assert_eq!(vi, vals.len());
res
};
let (lid, ed, sf, dc, dcur, csf, ctf, ka) = (
i32s(0),
i32s(1),
f64s(2),
f64s(3),
opt_strs(4),
f64s(5),
f64s(6),
i64s(7),
);
for i in 0..n {
out.push(AdjFactorsParquetRow {
listing_id: lid[i],
ex_date: ed[i],
split_factor: sf[i],
div_cash: dc[i],
div_currency: dcur[i].clone().map(Cow::Owned),
cum_split_factor: csf[i],
cum_total_factor: ctf[i],
known_at_micros: ka[i],
});
}
}
out
}
fn assert_bitwise(actual: &[AdjFactorsParquetRow], expected: &[AdjFactorsParquetRow]) {
assert_eq!(actual.len(), expected.len(), "row count");
for (i, (a, e)) in actual.iter().zip(expected).enumerate() {
assert_eq!(a.listing_id, e.listing_id, "row {i} listing_id");
assert_eq!(a.ex_date, e.ex_date, "row {i} ex_date");
assert_eq!(
a.split_factor.to_bits(),
e.split_factor.to_bits(),
"row {i} split"
);
assert_eq!(
a.div_cash.to_bits(),
e.div_cash.to_bits(),
"row {i} div_cash"
);
assert_eq!(a.div_currency, e.div_currency, "row {i} div_currency");
assert_eq!(
a.cum_split_factor.to_bits(),
e.cum_split_factor.to_bits(),
"row {i} cum_split"
);
assert_eq!(
a.cum_total_factor.to_bits(),
e.cum_total_factor.to_bits(),
"row {i} cum_total"
);
assert_eq!(a.known_at_micros, e.known_at_micros, "row {i} known_at");
}
}
fn row_group_sizes(path: &Path) -> Vec<i64> {
let reader = SerializedFileReader::new(File::open(path).expect("open")).expect("reader");
reader
.metadata()
.row_groups()
.iter()
.map(|rg| rg.num_rows())
.collect()
}
fn staging_bytes(adj_dir: &Path) -> u64 {
let Ok(entries) = fs::read_dir(adj_dir) else {
return 0;
};
entries
.map(|e| e.expect("dir entry"))
.filter(|e| e.file_name().to_string_lossy().ends_with(".tmp"))
.map(|e| e.metadata().map(|m| m.len()).unwrap_or(0))
.sum()
}
/// Lazy source that records the staging-file size each time a new row group starts.
struct ObservingIter {
adj_dir: PathBuf,
total: usize,
row_group_rows: usize,
next_idx: usize,
rng: Rng,
observed_at_group_start: Vec<u64>,
}
impl Iterator for ObservingIter {
type Item = AdjFactorsParquetRow;
fn next(&mut self) -> Option<Self::Item> {
if self.next_idx >= self.total {
return None;
}
if self.next_idx % self.row_group_rows == 0 {
self.observed_at_group_start
.push(staging_bytes(&self.adj_dir));
}
let currency = if self.next_idx % 3 == 0 {
None
} else {
Some(Cow::Borrowed("USD"))
};
let r = row(self.next_idx, currency, &mut self.rng);
self.next_idx += 1;
Some(r)
}
}
#[test]
fn row_groups_are_flushed_to_staging_before_remaining_rows_are_pulled() {
// Arrange: 3 row groups of 20,000 rows with random-mantissa doubles so each flushed
// group (~4 x 160 KB of DOUBLE pages) exceeds the 64 KiB BufWriter and reaches disk.
let tmp = TempDir::new("streaming");
let row_group_rows = 20_000;
let mut iter = ObservingIter {
adj_dir: tmp.0.join("adj_factors"),
total: 3 * row_group_rows,
row_group_rows,
next_idx: 0,
rng: Rng(0x0A0D_1A55_0000_0001),
observed_at_group_start: Vec::new(),
};
// Act: drive the writer through `&mut` so the observations survive.
let stats = write_adj_factors_dataset(&tmp.0, iter.by_ref(), opts(row_group_rows)).unwrap();
// Assert
assert_eq!(stats.rows_written, 3 * row_group_rows);
assert_eq!(stats.row_groups_written, 3);
let obs = &iter.observed_at_group_start;
assert_eq!(obs.len(), 3, "one observation per row-group start");
assert!(
obs[1] > 100_000,
"row group 1 must be on disk before row group 2 is pulled; staging had {} bytes",
obs[1]
);
assert!(
obs[2] > obs[1] + 100_000,
"row group 2 must be on disk before row group 3 is pulled; observed {obs:?}"
);
assert!(
stats.bytes_written > obs[2],
"final file must contain the last row group and footer"
);
assert_eq!(
row_group_sizes(&part_path(&tmp.0)),
vec![20_000, 20_000, 20_000]
);
}
#[test]
fn null_runs_aligned_to_4096_string_batch_boundary_round_trip() {
// Each case is a null pattern (true = Some) inside a single row group.
let n = STRING_BATCH;
let cases: Vec<(&str, Vec<bool>)> = vec![
("4096-null-then-1-some", (0..=n).map(|i| i == n).collect()),
("1-some-then-4096-null", (0..=n).map(|i| i == 0).collect()),
(
"4096-some-then-4096-null-then-1-some",
(0..=2 * n).map(|i| i < n || i == 2 * n).collect(),
),
("exactly-4096-null", vec![false; n]),
("exactly-8192-some", vec![true; 2 * n]),
(
"null-straddles-boundary",
(0..2 * n).map(|i| !(n - 2..n + 2).contains(&i)).collect(),
),
];
for (label, pattern) in cases {
// Arrange
let tmp = TempDir::new(label);
let mut rng = Rng(0x0A0D_1A55_0000_0002);
let rows: Vec<AdjFactorsParquetRow> = pattern
.iter()
.enumerate()
.map(|(i, &some)| {
let cur = some.then_some(Cow::Borrowed(if i % 2 == 0 { "USD" } else { "CAD" }));
row(i, cur, &mut rng)
})
.collect();
// Act
let stats = write_adj_factors_dataset(&tmp.0, &rows, opts(1_000_000)).unwrap();
// Assert
assert_eq!(stats.rows_written, rows.len(), "{label}");
assert_eq!(stats.row_groups_written, 1, "{label}");
assert_bitwise(&read_rows(&part_path(&tmp.0)), &rows);
}
}
#[test]
fn currency_labels_survive_interner_reset_between_row_groups() {
// Arrange: row group 1 interns [USD, CAD]; row group 2 starts with EUR then CAD then
// GBP, so stale ids from group 1 would surface as the wrong label in group 2.
let tmp = TempDir::new("interner");
let mut rng = Rng(0x0A0D_1A55_0000_0003);
let labels: [Option<&'static str>; 8] = [
Some("USD"),
Some("CAD"),
None,
Some("USD"),
Some("EUR"),
Some("CAD"),
None,
Some("GBP"),
];
let rows: Vec<AdjFactorsParquetRow> = labels
.iter()
.enumerate()
.map(|(i, l)| row(i, l.map(Cow::Borrowed), &mut rng))
.collect();
// Act
let stats = write_adj_factors_dataset(&tmp.0, &rows, opts(4)).unwrap();
// Assert
assert_eq!(stats.row_groups_written, 2);
let back = read_rows(&part_path(&tmp.0));
let back_labels: Vec<Option<&str>> = back.iter().map(|r| r.div_currency.as_deref()).collect();
assert_eq!(back_labels, labels.to_vec());
assert_bitwise(&back, &rows);
}
#[test]
fn seeded_random_streams_round_trip_with_expected_row_group_layout() {
let currencies = ["USD", "CAD", "EUR", "GBP", "CHF"];
for (case, &(total, row_group_rows)) in [
(1usize, 1usize),
(17, 4),
(999, 1000),
(1000, 1000),
(1001, 1000),
(9_000, 4_097),
(12_289, 4_096),
]
.iter()
.enumerate()
{
// Arrange: seeded mix of split-only (None), dividend-only and combined rows across
// multiple listings, strictly ascending by (listing_id, ex_date).
let tmp = TempDir::new(&format!("random-{case}"));
let mut rng = Rng(0x0A0D_1A55_1000_0000 + case as u64);
let mut rows = Vec::with_capacity(total);
let mut listing_id = 1i32;
let mut ex_date = base_day();
for _ in 0..total {
let r = rng.next_u64();
if r % 50 == 0 {
listing_id += 1 + ((r >> 8) % 3) as i32;
ex_date = base_day() + ((r >> 16) % 30) as i32;
} else {
ex_date += 1 + ((r >> 24) % 5) as i32;
}
let kind = (r >> 32) % 10;
let currency = currencies[((r >> 40) as usize) % currencies.len()];
let (split_factor, div_cash, div_currency) = match kind {
0 => (rng.factor(), 0.0, None),
1 => (rng.factor(), rng.factor(), Some(Cow::Borrowed(currency))),
_ => (
1.0,
rng.factor() - 1.0 + 0.01,
Some(Cow::Borrowed(currency)),
),
};
rows.push(AdjFactorsParquetRow {
listing_id,
ex_date,
split_factor,
div_cash,
div_currency,
cum_split_factor: rng.factor(),
cum_total_factor: rng.factor(),
known_at_micros: (i64::from(ex_date) - ((r >> 48) % 30) as i64) * MICROS_PER_DAY,
});
}
// Act
let stats = write_adj_factors_dataset(&tmp.0, rows.iter(), opts(row_group_rows)).unwrap();
// Assert
let expected_groups = total.div_ceil(row_group_rows);
assert_eq!(stats.rows_written, total, "case {case}");
assert_eq!(stats.row_groups_written, expected_groups, "case {case}");
let path = part_path(&tmp.0);
assert_eq!(
fs::metadata(&path).unwrap().len(),
stats.bytes_written,
"case {case}"
);
let sizes = row_group_sizes(&path);
assert_eq!(sizes.len(), expected_groups, "case {case}");
let (last, full) = sizes.split_last().unwrap();
assert!(
full.iter().all(|&s| s == row_group_rows as i64),
"case {case}: {sizes:?}"
);
assert_eq!(
*last as usize,
total - row_group_rows * (expected_groups - 1),
"case {case}"
);
assert_bitwise(&read_rows(&path), &rows);
}
}