T-106: tests
This commit is contained in:
parent
c8a2301527
commit
50a9968e84
1 changed files with 418 additions and 0 deletions
418
tools/curate-etl/tests/curate_adj_qa_contract.rs
Normal file
418
tools/curate-etl/tests/curate_adj_qa_contract.rs
Normal file
|
|
@ -0,0 +1,418 @@
|
|||
//! QA contract tests for the public `adj_factors` curation stage (T-106 / M1.2v).
|
||||
//!
|
||||
//! Complements the in-crate `curate_adj_tests.rs` with checks against independent references
|
||||
//! built only from the public API:
|
||||
//! - seeded differential test: per-bar split factors across ticker renames, ticker reuse and
|
||||
//! unmapped gaps equal a naive per-listing product of later split ratios;
|
||||
//! - fenced publish → separate reopen equals the naive reference over only the events whose
|
||||
//! conservative `16:00 ET` known_at is `<= as_of`, and every reopened row honours the fence;
|
||||
//! - re-publishing a smaller fenced snapshot over a larger retrospective one leaves exactly one
|
||||
//! `part.parquet` whose footer carries the `stock_bot.adj_factors.*` keys and contract schema;
|
||||
//! - `bench-curate-adj` binary run: checksum/bytes/rows pinned to the README values, temp dir
|
||||
//! cleaned.
|
||||
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::fs::{self, File};
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use curate_etl::{
|
||||
adj_factors_for_bar, adj_factors_parquet_schema, curate_adj_factors,
|
||||
curate_and_write_adj_factors, curate_and_write_adj_factors_as_of, et_session_close_utc_micros,
|
||||
read_adj_factors_dataset, read_adj_factors_dataset_as_of, ymd_to_epoch_days,
|
||||
AdjFactorsWriteOptions, AdjPointInTimeFence, AdjSnapshotKind, CurateAdjReadError,
|
||||
DividendEvent, ProviderMappingRow, ProviderMappingTable, SplitEvent,
|
||||
};
|
||||
use parquet::file::reader::{FileReader, SerializedFileReader};
|
||||
|
||||
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-curate-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);
|
||||
}
|
||||
}
|
||||
|
||||
struct SplitMix64(u64);
|
||||
|
||||
impl SplitMix64 {
|
||||
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 below(&mut self, n: u64) -> u64 {
|
||||
self.next() % n
|
||||
}
|
||||
}
|
||||
|
||||
fn day(y: i32, m: u32, d: u32) -> i32 {
|
||||
ymd_to_epoch_days(y, m, d).expect("valid date")
|
||||
}
|
||||
|
||||
fn map_row(key: &str, from: i32, to: Option<i32>, listing_id: i32) -> ProviderMappingRow {
|
||||
ProviderMappingRow {
|
||||
source: "qm".to_string(),
|
||||
source_id: key.to_string(),
|
||||
valid_from: from,
|
||||
valid_to: to,
|
||||
listing_id,
|
||||
}
|
||||
}
|
||||
|
||||
/// Exactly representable ratios so the naive product is order-independent.
|
||||
const RATIOS: [f64; 6] = [2.0, 0.5, 4.0, 0.25, 3.0, 1.0];
|
||||
|
||||
struct Fixture {
|
||||
mapping: ProviderMappingTable,
|
||||
splits: Vec<(String, SplitEvent)>,
|
||||
/// Naive reference: listing_id -> (ex_date -> ratio) for every mapped split (incl. 1:1).
|
||||
reference: BTreeMap<i32, BTreeMap<i32, f64>>,
|
||||
min: i32,
|
||||
max: i32,
|
||||
}
|
||||
|
||||
/// Layout per listing group `g` (deterministic):
|
||||
/// - listing `3g+1`: single key `S{g}` for the whole span;
|
||||
/// - listing `3g+2`: key `OLD{g}` until 2012-12-31, renamed to `NEW{g}` from 2013-01-01;
|
||||
/// - key `RE{g}` maps to listing `3g+3` until 2015-06-30, unmapped through 2015, then to listing
|
||||
/// `100_000 + g` from 2016-01-01 (ticker reuse with a gap).
|
||||
fn seeded_fixture(seed: u64, groups: i32, events: usize) -> Fixture {
|
||||
let min = day(2000, 1, 1);
|
||||
let max = day(2025, 12, 31);
|
||||
let rename = day(2012, 12, 31);
|
||||
let reuse_old_end = day(2015, 6, 30);
|
||||
let reuse_new_start = day(2016, 1, 1);
|
||||
|
||||
let mut rows = Vec::new();
|
||||
for g in 0..groups {
|
||||
rows.push(map_row(&format!("S{g}"), min, None, 3 * g + 1));
|
||||
rows.push(map_row(&format!("OLD{g}"), min, Some(rename), 3 * g + 2));
|
||||
rows.push(map_row(&format!("NEW{g}"), rename + 1, None, 3 * g + 2));
|
||||
rows.push(map_row(
|
||||
&format!("RE{g}"),
|
||||
min,
|
||||
Some(reuse_old_end),
|
||||
3 * g + 3,
|
||||
));
|
||||
rows.push(map_row(
|
||||
&format!("RE{g}"),
|
||||
reuse_new_start,
|
||||
None,
|
||||
100_000 + g,
|
||||
));
|
||||
}
|
||||
let mapping = ProviderMappingTable::from_rows(rows).expect("valid mapping");
|
||||
|
||||
let mut rng = SplitMix64(seed);
|
||||
let mut seen: HashSet<(String, i32)> = HashSet::new();
|
||||
let mut splits = Vec::new();
|
||||
let mut reference: BTreeMap<i32, BTreeMap<i32, f64>> = BTreeMap::new();
|
||||
while splits.len() < events {
|
||||
let g = rng.below(groups as u64) as i32;
|
||||
let ex_date = min + rng.below((max - min + 1) as u64) as i32;
|
||||
let (key, listing) = match rng.below(4) {
|
||||
0 => (format!("S{g}"), Some(3 * g + 1)),
|
||||
1 if ex_date <= rename => (format!("OLD{g}"), Some(3 * g + 2)),
|
||||
1 => (format!("NEW{g}"), Some(3 * g + 2)),
|
||||
2 if ex_date <= reuse_old_end => (format!("RE{g}"), Some(3 * g + 3)),
|
||||
2 if ex_date < reuse_new_start => (format!("RE{g}"), None),
|
||||
2 => (format!("RE{g}"), Some(100_000 + g)),
|
||||
_ => (format!("UNMAPPED{g}"), None),
|
||||
};
|
||||
// One event per (key, ex_date): same-key same-day multiplication is the builder's own
|
||||
// contract and is covered in-crate.
|
||||
if !seen.insert((key.clone(), ex_date)) {
|
||||
continue;
|
||||
}
|
||||
let ratio = RATIOS[rng.below(RATIOS.len() as u64) as usize];
|
||||
if let Some(listing_id) = listing {
|
||||
reference
|
||||
.entry(listing_id)
|
||||
.or_default()
|
||||
.insert(ex_date, ratio);
|
||||
}
|
||||
splits.push((key, SplitEvent { ex_date, ratio }));
|
||||
}
|
||||
Fixture {
|
||||
mapping,
|
||||
splits,
|
||||
reference,
|
||||
min,
|
||||
max,
|
||||
}
|
||||
}
|
||||
|
||||
/// Product of every reference split ratio with `ex_date > bar_date` for `listing_id`.
|
||||
fn naive_factor(
|
||||
reference: &BTreeMap<i32, BTreeMap<i32, f64>>,
|
||||
listing_id: i32,
|
||||
bar_date: i32,
|
||||
admit: impl Fn(i32) -> bool,
|
||||
) -> f64 {
|
||||
reference.get(&listing_id).map_or(1.0, |events| {
|
||||
events
|
||||
.range(bar_date + 1..)
|
||||
.filter(|(ex, _)| admit(**ex))
|
||||
.map(|(_, r)| *r)
|
||||
.product()
|
||||
})
|
||||
}
|
||||
|
||||
const NO_DIVIDENDS: [(String, DividendEvent); 0] = [];
|
||||
|
||||
#[test]
|
||||
fn seeded_split_factors_match_naive_per_listing_reference_across_rename_reuse_and_gaps() {
|
||||
let fx = seeded_fixture(0xAD0A_115E_ED00, 40, 3_000);
|
||||
let out =
|
||||
curate_adj_factors(&fx.mapping, "qm", fx.splits.clone(), NO_DIVIDENDS).expect("curate");
|
||||
|
||||
assert_eq!(out.snapshot_kind, AdjSnapshotKind::RetrospectiveSnapshot);
|
||||
let mapped: usize = fx.reference.values().map(BTreeMap::len).sum();
|
||||
assert_eq!(out.stats.splits_in, fx.splits.len());
|
||||
assert_eq!(
|
||||
out.stats.splits_dropped_unmapped,
|
||||
fx.splits.len() - mapped,
|
||||
"unmapped count must equal events with no covering range"
|
||||
);
|
||||
assert_eq!(out.stats.splits_collision_collapsed, 0);
|
||||
assert_eq!(out.stats.builder.split_events_in, mapped);
|
||||
let noops = fx
|
||||
.reference
|
||||
.values()
|
||||
.flat_map(BTreeMap::values)
|
||||
.filter(|r| **r == 1.0)
|
||||
.count();
|
||||
assert_eq!(out.stats.builder.split_noops_dropped, noops);
|
||||
assert_eq!(out.stats.rows_out, mapped - noops);
|
||||
assert!(out.stats.splits_dropped_unmapped > 0 && noops > 0);
|
||||
|
||||
let mut rng = SplitMix64(0x0B5E_55ED);
|
||||
let listings: Vec<i32> = fx.reference.keys().copied().collect();
|
||||
for _ in 0..5_000 {
|
||||
let listing_id = listings[rng.below(listings.len() as u64) as usize];
|
||||
let bar = fx.min - 5 + rng.below((fx.max - fx.min + 10) as u64) as i32;
|
||||
let expected = naive_factor(&fx.reference, listing_id, bar, |_| true);
|
||||
let (split, _total) = adj_factors_for_bar(&out.rows, listing_id, bar);
|
||||
assert_eq!(
|
||||
split.to_bits(),
|
||||
expected.to_bits(),
|
||||
"listing {listing_id} bar {bar}: got {split}, expected {expected}"
|
||||
);
|
||||
}
|
||||
// Unknown listing never picks up another listing's chain.
|
||||
assert_eq!(adj_factors_for_bar(&out.rows, 99_999, fx.min), (1.0, 1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fenced_publish_then_separate_reopen_matches_naive_filtered_reference() {
|
||||
let fx = seeded_fixture(0xFE11_CE00, 25, 2_000);
|
||||
let tmp = TempDir::new("fenced-reopen");
|
||||
// As of 2018-03-14 12:00 UTC: an ex-date of 2018-03-14 (close 20:00 UTC) is still unknown.
|
||||
let as_of = et_session_close_utc_micros(day(2018, 3, 14)).unwrap() - 8 * 3_600_000_000;
|
||||
let fence = AdjPointInTimeFence::as_of(as_of);
|
||||
|
||||
let report = curate_and_write_adj_factors_as_of(
|
||||
&tmp.0,
|
||||
&fx.mapping,
|
||||
"qm",
|
||||
fx.splits.clone(),
|
||||
NO_DIVIDENDS,
|
||||
fence,
|
||||
AdjFactorsWriteOptions {
|
||||
row_group_rows: 11,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.expect("fenced publish");
|
||||
assert_eq!(
|
||||
report.snapshot_kind,
|
||||
AdjSnapshotKind::PointInTimeFenced(fence)
|
||||
);
|
||||
assert!(report.curate_stats.splits_dropped_fenced > 0);
|
||||
|
||||
// Separate read step: only the published artifact is consulted.
|
||||
let snap = read_adj_factors_dataset_as_of(&tmp.0, fence).expect("reopen");
|
||||
assert_eq!(
|
||||
snap.snapshot_kind,
|
||||
AdjSnapshotKind::PointInTimeFenced(fence)
|
||||
);
|
||||
assert_eq!(snap.rows.len(), report.write_stats.rows_written);
|
||||
for row in &snap.rows {
|
||||
assert!(row.known_at_micros <= as_of, "row beyond as_of: {row:?}");
|
||||
}
|
||||
for w in snap.rows.windows(2) {
|
||||
assert!((w[0].listing_id, w[0].ex_date) < (w[1].listing_id, w[1].ex_date));
|
||||
}
|
||||
|
||||
let admitted = |ex: i32| et_session_close_utc_micros(ex).unwrap() <= as_of;
|
||||
let mut rng = SplitMix64(0xA5_0F);
|
||||
let listings: Vec<i32> = fx.reference.keys().copied().collect();
|
||||
for _ in 0..3_000 {
|
||||
let listing_id = listings[rng.below(listings.len() as u64) as usize];
|
||||
let bar = fx.min + rng.below((day(2018, 3, 14) - fx.min) as u64) as i32;
|
||||
let expected = naive_factor(&fx.reference, listing_id, bar, admitted);
|
||||
let (split, _) = snap.factors_for_bar(listing_id, bar);
|
||||
assert_eq!(
|
||||
split.to_bits(),
|
||||
expected.to_bits(),
|
||||
"listing {listing_id} bar {bar} as_of {as_of}"
|
||||
);
|
||||
}
|
||||
|
||||
// A neighbouring fence one microsecond later is a different artifact and must be refused.
|
||||
let other = AdjPointInTimeFence::as_of(as_of + 1);
|
||||
assert!(matches!(
|
||||
read_adj_factors_dataset_as_of(&tmp.0, other),
|
||||
Err(CurateAdjReadError::IncompatibleFence { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smaller_fenced_republish_supersedes_larger_retrospective_snapshot_in_one_file() {
|
||||
let fx = seeded_fixture(0x5_0BE5, 30, 2_500);
|
||||
let tmp = TempDir::new("republish");
|
||||
|
||||
let retro = curate_and_write_adj_factors(
|
||||
&tmp.0,
|
||||
&fx.mapping,
|
||||
"qm",
|
||||
fx.splits.clone(),
|
||||
NO_DIVIDENDS,
|
||||
AdjFactorsWriteOptions::default(),
|
||||
)
|
||||
.expect("retrospective publish");
|
||||
let fence = AdjPointInTimeFence::as_of_with_vault_cutoff(
|
||||
et_session_close_utc_micros(day(2024, 6, 28)).unwrap(),
|
||||
et_session_close_utc_micros(day(2005, 1, 3)).unwrap(),
|
||||
);
|
||||
assert!(matches!(
|
||||
read_adj_factors_dataset_as_of(&tmp.0, fence),
|
||||
Err(CurateAdjReadError::RetrospectiveSnapshotRejected { .. })
|
||||
));
|
||||
|
||||
let fenced = curate_and_write_adj_factors_as_of(
|
||||
&tmp.0,
|
||||
&fx.mapping,
|
||||
"qm",
|
||||
fx.splits.clone(),
|
||||
NO_DIVIDENDS,
|
||||
fence,
|
||||
AdjFactorsWriteOptions::default(),
|
||||
)
|
||||
.expect("fenced publish");
|
||||
assert!(fenced.write_stats.rows_written < retro.write_stats.rows_written);
|
||||
|
||||
let names: Vec<String> = fs::read_dir(tmp.0.join("adj_factors"))
|
||||
.unwrap()
|
||||
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
|
||||
.collect();
|
||||
assert_eq!(names, vec!["part.parquet".to_string()]);
|
||||
|
||||
// Vault cutoff wins over the later as_of: every row is strictly before the vault boundary.
|
||||
let snap = read_adj_factors_dataset(&tmp.0).expect("reopen");
|
||||
assert_eq!(
|
||||
snap.snapshot_kind,
|
||||
AdjSnapshotKind::PointInTimeFenced(fence)
|
||||
);
|
||||
assert_eq!(snap.rows.len(), fenced.write_stats.rows_written);
|
||||
let vault = fence.vault_cutoff_micros.unwrap();
|
||||
assert!(snap.rows.iter().all(|r| r.known_at_micros < vault));
|
||||
|
||||
// A generic Parquet reader sees the contract schema and the bound footer keys.
|
||||
let path = tmp.0.join("adj_factors").join("part.parquet");
|
||||
let reader = SerializedFileReader::new(File::open(&path).unwrap()).unwrap();
|
||||
let file_meta = reader.metadata().file_metadata();
|
||||
assert_eq!(
|
||||
file_meta.schema(),
|
||||
adj_factors_parquet_schema().unwrap().as_ref()
|
||||
);
|
||||
assert_eq!(file_meta.num_rows() as usize, snap.rows.len());
|
||||
let kv: BTreeMap<String, Option<String>> = file_meta
|
||||
.key_value_metadata()
|
||||
.expect("footer key_value_metadata")
|
||||
.iter()
|
||||
.map(|kv| (kv.key.clone(), kv.value.clone()))
|
||||
.filter(|(k, _)| k.starts_with("stock_bot.adj_factors."))
|
||||
.collect();
|
||||
let get = |k: &str| kv[&format!("stock_bot.adj_factors.{k}")].as_deref();
|
||||
assert_eq!(kv.len(), 6, "{kv:?}");
|
||||
assert_eq!(get("format_version"), Some("1"));
|
||||
assert_eq!(get("snapshot_kind"), Some("point_in_time_fenced"));
|
||||
assert_eq!(
|
||||
get("as_of_micros"),
|
||||
Some(fence.as_of_micros.unwrap().to_string().as_str())
|
||||
);
|
||||
assert_eq!(get("vault_cutoff_micros"), Some(vault.to_string().as_str()));
|
||||
assert_eq!(
|
||||
get("rows_written"),
|
||||
Some(snap.rows.len().to_string().as_str())
|
||||
);
|
||||
}
|
||||
|
||||
fn field<'a>(text: &'a str, prefix: &str) -> Option<&'a str> {
|
||||
text.split_whitespace()
|
||||
.find(|t| t.starts_with(prefix))
|
||||
.map(|t| &t[prefix.len()..])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bench_curate_adj_default_run_matches_readme_values_and_cleans_temp_dir() {
|
||||
let tmp = TempDir::new("bench-tmpdir");
|
||||
let output = Command::new(env!("CARGO_BIN_EXE_curate-etl"))
|
||||
.arg("bench-curate-adj")
|
||||
.env("TMPDIR", &tmp.0)
|
||||
.output()
|
||||
.expect("run curate-etl");
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"stderr: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
|
||||
// Values recorded in tools/curate-etl/README.md (`bench-curate-adj`, default 1,000,000).
|
||||
assert_eq!(field(&stdout, "events="), Some("1000000"), "{stdout}");
|
||||
assert_eq!(field(&stdout, "splits="), Some("40221"), "{stdout}");
|
||||
assert_eq!(field(&stdout, "dividends="), Some("959779"), "{stdout}");
|
||||
assert_eq!(
|
||||
field(&stdout, "checksum="),
|
||||
Some("0x024ec73a1afe7e6b"),
|
||||
"{stdout}"
|
||||
);
|
||||
assert_eq!(field(&stdout, "bytes="), Some("11872037"), "{stdout}");
|
||||
assert_eq!(
|
||||
field(&stdout, "read_back_rows="),
|
||||
Some("946414"),
|
||||
"{stdout}"
|
||||
);
|
||||
assert_eq!(field(&stdout, "rows_out="), Some("946414"), "{stdout}");
|
||||
assert_eq!(field(&stdout, "coll_collapsed="), Some("4930"), "{stdout}");
|
||||
|
||||
let leftovers: Vec<_> = fs::read_dir(&tmp.0)
|
||||
.unwrap()
|
||||
.map(|e| e.unwrap().file_name())
|
||||
.collect();
|
||||
assert!(
|
||||
leftovers.is_empty(),
|
||||
"bench left temp entries: {leftovers:?}"
|
||||
);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue