442 lines
16 KiB
Rust
442 lines
16 KiB
Rust
//! QA differential and validation-oracle tests for `ProviderMappingTable` /
|
|
//! `ProviderMappingCursor` (T-81 / M1.2h).
|
|
//!
|
|
//! Compares the optimized table (source-partitioned `HashMap` index + contiguous range arena +
|
|
//! binary search) against a naive linear scan over the raw rows, and `from_rows` validation
|
|
//! against a brute-force validator written only from the documented rules. Every generator is
|
|
//! seeded, so failures reproduce from the printed seed.
|
|
|
|
use std::collections::BTreeMap;
|
|
|
|
use curate_etl::bench::{run_provider_mapping_benchmark, PROVIDER_MAPPING_BENCH_KEY_COUNT};
|
|
use curate_etl::{
|
|
MappingRange, ProviderMappingCursor, ProviderMappingError, ProviderMappingRow,
|
|
ProviderMappingTable,
|
|
};
|
|
|
|
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 below(&mut self, n: u64) -> u64 {
|
|
self.next() % n
|
|
}
|
|
|
|
fn shuffle<T>(&mut self, items: &mut [T]) {
|
|
for i in (1..items.len()).rev() {
|
|
let j = self.below(i as u64 + 1) as usize;
|
|
items.swap(i, j);
|
|
}
|
|
}
|
|
}
|
|
|
|
fn row(
|
|
source: &str,
|
|
source_id: &str,
|
|
valid_from: i32,
|
|
valid_to: Option<i32>,
|
|
listing_id: i32,
|
|
) -> ProviderMappingRow {
|
|
ProviderMappingRow {
|
|
source: source.to_string(),
|
|
source_id: source_id.to_string(),
|
|
valid_from,
|
|
valid_to,
|
|
listing_id,
|
|
}
|
|
}
|
|
|
|
/// Linear-scan oracle over raw (already valid, non-overlapping) rows.
|
|
fn naive_resolve(
|
|
rows: &[ProviderMappingRow],
|
|
source: &str,
|
|
source_id: &str,
|
|
d: i32,
|
|
) -> Option<i32> {
|
|
rows.iter()
|
|
.find(|r| {
|
|
r.source == source
|
|
&& r.source_id == source_id
|
|
&& d >= r.valid_from
|
|
&& r.valid_to.is_none_or(|to| d <= to)
|
|
})
|
|
.map(|r| r.listing_id)
|
|
}
|
|
|
|
/// Variant-only classification of a validation outcome.
|
|
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
|
|
enum Outcome {
|
|
Ok,
|
|
EmptySource,
|
|
EmptySourceId,
|
|
InvalidListingId,
|
|
InvalidRange,
|
|
DuplicateValidFrom,
|
|
OverlappingRanges,
|
|
}
|
|
|
|
fn classify(result: &Result<ProviderMappingTable, ProviderMappingError>) -> Outcome {
|
|
match result {
|
|
Ok(_) => Outcome::Ok,
|
|
Err(ProviderMappingError::EmptySource) => Outcome::EmptySource,
|
|
Err(ProviderMappingError::EmptySourceId { .. }) => Outcome::EmptySourceId,
|
|
Err(ProviderMappingError::InvalidListingId { .. }) => Outcome::InvalidListingId,
|
|
Err(ProviderMappingError::InvalidRange { .. }) => Outcome::InvalidRange,
|
|
Err(ProviderMappingError::DuplicateValidFrom { .. }) => Outcome::DuplicateValidFrom,
|
|
Err(ProviderMappingError::OverlappingRanges { .. }) => Outcome::OverlappingRanges,
|
|
}
|
|
}
|
|
|
|
/// Brute-force validator from the documented rules: row-level errors take precedence (ranked
|
|
/// EmptySource < EmptySourceId < InvalidListingId < InvalidRange); otherwise the first key in
|
|
/// `(source, source_id)` order with a same-`valid_from` pair reports a duplicate, or with any
|
|
/// pairwise-intersecting inclusive ranges reports an overlap.
|
|
fn oracle_validate(rows: &[ProviderMappingRow]) -> Outcome {
|
|
let mut best: Option<Outcome> = None;
|
|
let rank = |o: Outcome| o as u8;
|
|
for r in rows {
|
|
let o = if r.source.trim().is_empty() {
|
|
Outcome::EmptySource
|
|
} else if r.source_id.trim().is_empty() {
|
|
Outcome::EmptySourceId
|
|
} else if r.listing_id <= 0 {
|
|
Outcome::InvalidListingId
|
|
} else if r.valid_to.is_some_and(|to| to < r.valid_from) {
|
|
Outcome::InvalidRange
|
|
} else {
|
|
continue;
|
|
};
|
|
if best.is_none_or(|b| rank(o) < rank(b)) {
|
|
best = Some(o);
|
|
}
|
|
}
|
|
if let Some(b) = best {
|
|
return b;
|
|
}
|
|
|
|
let mut by_key: BTreeMap<(&str, &str), Vec<&ProviderMappingRow>> = BTreeMap::new();
|
|
for r in rows {
|
|
by_key
|
|
.entry((r.source.as_str(), r.source_id.as_str()))
|
|
.or_default()
|
|
.push(r);
|
|
}
|
|
for key_rows in by_key.values() {
|
|
let mut dup = false;
|
|
let mut overlap = false;
|
|
for (i, a) in key_rows.iter().enumerate() {
|
|
for b in &key_rows[i + 1..] {
|
|
if a.valid_from == b.valid_from {
|
|
dup = true;
|
|
}
|
|
let a_to = a.valid_to.map_or(i64::MAX, i64::from);
|
|
let b_to = b.valid_to.map_or(i64::MAX, i64::from);
|
|
let lo = i64::from(a.valid_from.max(b.valid_from));
|
|
if lo <= a_to.min(b_to) {
|
|
overlap = true;
|
|
}
|
|
}
|
|
}
|
|
// Same valid_from always overlaps too; the first sorted violating pair decides which
|
|
// error is reported, so only assert that one of them is.
|
|
if dup || overlap {
|
|
return if dup && !overlap_without_dup(key_rows) {
|
|
Outcome::DuplicateValidFrom
|
|
} else {
|
|
Outcome::OverlappingRanges
|
|
};
|
|
}
|
|
}
|
|
Outcome::Ok
|
|
}
|
|
|
|
/// For a key with duplicates, decides which error the documented sorted-adjacent scan reports
|
|
/// first: walk rows sorted by `(valid_from, valid_to)` and return `true` if an overlap between
|
|
/// distinct `valid_from`s is met before any same-`valid_from` pair.
|
|
fn overlap_without_dup(key_rows: &[&ProviderMappingRow]) -> bool {
|
|
let mut sorted: Vec<&ProviderMappingRow> = key_rows.to_vec();
|
|
sorted.sort_by_key(|r| {
|
|
(
|
|
r.valid_from,
|
|
r.valid_to.map_or(i64::MAX, i64::from),
|
|
r.listing_id,
|
|
)
|
|
});
|
|
for pair in sorted.windows(2) {
|
|
if pair[0].valid_from == pair[1].valid_from {
|
|
return false;
|
|
}
|
|
let overlaps = pair[0].valid_to.is_none_or(|to| to >= pair[1].valid_from);
|
|
if overlaps {
|
|
return true;
|
|
}
|
|
}
|
|
false
|
|
}
|
|
|
|
/// Generates a valid table: `n_sources` sources, single-day / adjacent / gapped / open-ended
|
|
/// ranges. Returns rows plus every `(source, source_id)` key (and a few absent probes).
|
|
fn gen_valid(rng: &mut Rng, n_sources: usize) -> (Vec<ProviderMappingRow>, Vec<(String, String)>) {
|
|
let mut rows = Vec::new();
|
|
let mut keys = Vec::new();
|
|
let mut listing = 1i32;
|
|
for s in 0..n_sources {
|
|
let source = format!("src{s:02}");
|
|
let n_keys = 1 + rng.below(6) as usize;
|
|
for k in 0..n_keys {
|
|
let id = format!("ID{k}");
|
|
keys.push((source.clone(), id.clone()));
|
|
let n_ranges = 1 + rng.below(4) as usize;
|
|
let mut start = 1_000 + rng.below(50) as i32;
|
|
for r in 0..n_ranges {
|
|
let is_last = r + 1 == n_ranges;
|
|
let len = match rng.below(3) {
|
|
0 => 0, // single-day range
|
|
_ => rng.below(30) as i32,
|
|
};
|
|
let valid_to = if is_last && rng.below(2) == 0 {
|
|
None
|
|
} else {
|
|
Some(start + len)
|
|
};
|
|
rows.push(row(&source, &id, start, valid_to, listing));
|
|
listing += 1;
|
|
let gap = if rng.below(2) == 0 {
|
|
1
|
|
} else {
|
|
2 + rng.below(15) as i32
|
|
};
|
|
start += len + gap;
|
|
}
|
|
}
|
|
}
|
|
keys.push(("src00".to_string(), "MISSING".to_string()));
|
|
keys.push(("nosrc".to_string(), "ID0".to_string()));
|
|
(rows, keys)
|
|
}
|
|
|
|
#[test]
|
|
fn resolve_and_cursor_match_linear_scan_oracle_across_seeds_and_source_counts() {
|
|
for seed in 0..60u64 {
|
|
let mut rng = Rng(0x0A11_CE00_0000_0000 ^ seed);
|
|
// Alternate between the linear source scan (<= 8) and binary search (> 8) paths.
|
|
let n_sources = if seed % 2 == 0 {
|
|
1 + rng.below(8) as usize
|
|
} else {
|
|
9 + rng.below(6) as usize
|
|
};
|
|
let (mut rows, keys) = gen_valid(&mut rng, n_sources);
|
|
let oracle_rows = rows.clone();
|
|
rng.shuffle(&mut rows);
|
|
let table =
|
|
ProviderMappingTable::from_rows(rows).unwrap_or_else(|e| panic!("seed {seed}: {e}"));
|
|
|
|
assert_eq!(table.range_count(), oracle_rows.len(), "seed {seed}");
|
|
assert_eq!(table.len(), keys.len() - 2, "seed {seed}");
|
|
|
|
for (src, id) in &keys {
|
|
let mut ascending = ProviderMappingCursor::new(table.ranges_for(src, id));
|
|
for d in 990..=1_300 {
|
|
let expected = naive_resolve(&oracle_rows, src, id, d);
|
|
assert_eq!(
|
|
table.resolve(src, id, d),
|
|
expected,
|
|
"seed {seed} ({src},{id},{d})"
|
|
);
|
|
assert_eq!(
|
|
ascending.resolve(d),
|
|
expected,
|
|
"seed {seed} cursor ({src},{id},{d})"
|
|
);
|
|
}
|
|
for d in [i32::MIN, i32::MIN + 1, -1, 0, i32::MAX - 1, i32::MAX] {
|
|
let expected = naive_resolve(&oracle_rows, src, id, d);
|
|
assert_eq!(
|
|
table.resolve(src, id, d),
|
|
expected,
|
|
"seed {seed} extreme {d}"
|
|
);
|
|
}
|
|
|
|
// Random-order probes through one cursor must still equal resolve.
|
|
let mut random = table.cursor_for(src, id);
|
|
for _ in 0..200 {
|
|
let d = 990 + rng.below(320) as i32;
|
|
assert_eq!(
|
|
random.resolve(d),
|
|
table.resolve(src, id, d),
|
|
"seed {seed} random ({src},{id},{d})"
|
|
);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn from_rows_accepts_exactly_what_brute_force_validator_accepts_and_is_permutation_invariant() {
|
|
let sources = ["eod", "qm", " ", "ib"];
|
|
let ids = ["A", "B", "", " A", "\t"];
|
|
let mut seen: Vec<Outcome> = Vec::new();
|
|
for seed in 0..400u64 {
|
|
let mut rng = Rng(0xBADD_A7A0_0000_0000 ^ seed);
|
|
let n = 1 + rng.below(7) as usize;
|
|
let mut rows = Vec::with_capacity(n);
|
|
for _ in 0..n {
|
|
// Mostly well-formed rows so key-level errors and Ok outcomes are common.
|
|
let source = if rng.below(12) == 0 {
|
|
sources[2]
|
|
} else {
|
|
sources[[0, 1, 3][rng.below(3) as usize]]
|
|
};
|
|
let source_id = if rng.below(10) == 0 {
|
|
ids[[2, 4][rng.below(2) as usize]]
|
|
} else {
|
|
ids[[0, 1, 3][rng.below(3) as usize]]
|
|
};
|
|
let from = rng.below(20) as i32;
|
|
let to = match rng.below(4) {
|
|
0 => None,
|
|
1 if rng.below(5) == 0 => Some(from - 1 - rng.below(3) as i32),
|
|
_ => Some(from + rng.below(6) as i32),
|
|
};
|
|
let listing_id = if rng.below(15) == 0 {
|
|
-(rng.below(2) as i32)
|
|
} else {
|
|
1 + rng.below(50) as i32
|
|
};
|
|
rows.push(row(source, source_id, from, to, listing_id));
|
|
}
|
|
|
|
let baseline = ProviderMappingTable::from_rows(rows.clone());
|
|
assert_eq!(
|
|
classify(&baseline),
|
|
oracle_validate(&rows),
|
|
"seed {seed}: {rows:?}"
|
|
);
|
|
if !seen.contains(&classify(&baseline)) {
|
|
seen.push(classify(&baseline));
|
|
}
|
|
|
|
for _ in 0..4 {
|
|
let mut shuffled = rows.clone();
|
|
rng.shuffle(&mut shuffled);
|
|
let candidate = ProviderMappingTable::from_rows(shuffled);
|
|
match (&baseline, &candidate) {
|
|
(Err(a), Err(b)) => {
|
|
assert_eq!(a, b, "seed {seed}: error changed under permutation")
|
|
}
|
|
(Ok(a), Ok(b)) => {
|
|
assert_eq!(a.len(), b.len());
|
|
assert_eq!(a.range_count(), b.range_count());
|
|
for r in &rows {
|
|
assert_eq!(
|
|
a.ranges_for(&r.source, &r.source_id),
|
|
b.ranges_for(&r.source, &r.source_id)
|
|
);
|
|
for d in -5..30 {
|
|
assert_eq!(
|
|
a.resolve(&r.source, &r.source_id, d),
|
|
b.resolve(&r.source, &r.source_id, d)
|
|
);
|
|
}
|
|
}
|
|
}
|
|
_ => panic!("seed {seed}: Ok/Err outcome changed under permutation"),
|
|
}
|
|
}
|
|
}
|
|
// Guard against a generator that never exercises some outcome.
|
|
assert_eq!(seen.len(), 7, "outcomes exercised: {seen:?}");
|
|
}
|
|
|
|
#[test]
|
|
fn matching_is_case_sensitive_and_unicode_whitespace_only_ids_are_rejected() {
|
|
let table = ProviderMappingTable::from_rows([
|
|
row("eod", "FB.US", 100, None, 1),
|
|
row("eod", "\u{00A0}FB.US", 100, None, 2),
|
|
])
|
|
.unwrap();
|
|
assert_eq!(table.resolve("eod", "FB.US", 100), Some(1));
|
|
assert_eq!(table.resolve("eod", "\u{00A0}FB.US", 100), Some(2));
|
|
assert_eq!(table.resolve("eod", "fb.us", 100), None);
|
|
assert_eq!(table.resolve("EOD", "FB.US", 100), None);
|
|
assert_eq!(table.resolve("eod", "", 100), None);
|
|
assert_eq!(table.resolve("", "FB.US", 100), None);
|
|
|
|
for blank in ["\u{3000}", "\u{00A0}\u{2003}", "\u{2028}"] {
|
|
assert_eq!(
|
|
ProviderMappingTable::from_rows([row("eod", blank, 100, None, 1)]).unwrap_err(),
|
|
ProviderMappingError::EmptySourceId {
|
|
source: "eod".to_string()
|
|
},
|
|
"{blank:?}"
|
|
);
|
|
assert_eq!(
|
|
ProviderMappingTable::from_rows([row(blank, "FB.US", 100, None, 1)]).unwrap_err(),
|
|
ProviderMappingError::EmptySource,
|
|
"{blank:?}"
|
|
);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn ranges_for_returns_sorted_canonical_slice_and_cursor_reset_restarts() {
|
|
let table = ProviderMappingTable::from_rows([
|
|
row("ib", "107113386", 50, None, 3),
|
|
row("ib", "107113386", 10, Some(19), 1),
|
|
row("ib", "107113386", 20, Some(30), 2),
|
|
])
|
|
.unwrap();
|
|
let expected = [
|
|
MappingRange {
|
|
valid_from: 10,
|
|
valid_to: Some(19),
|
|
listing_id: 1,
|
|
},
|
|
MappingRange {
|
|
valid_from: 20,
|
|
valid_to: Some(30),
|
|
listing_id: 2,
|
|
},
|
|
MappingRange {
|
|
valid_from: 50,
|
|
valid_to: None,
|
|
listing_id: 3,
|
|
},
|
|
];
|
|
assert_eq!(table.ranges_for("ib", "107113386"), &expected);
|
|
assert!(expected[0].contains(10) && expected[0].contains(19) && !expected[0].contains(20));
|
|
assert!(expected[2].contains(i32::MAX) && !expected[2].contains(49));
|
|
|
|
let mut cursor = table.cursor_for("ib", "107113386");
|
|
assert_eq!(cursor.resolve(i32::MIN), None);
|
|
assert_eq!(cursor.resolve(i32::MAX), Some(3));
|
|
cursor.reset();
|
|
assert_eq!(cursor.resolve(15), Some(1));
|
|
assert_eq!(cursor.resolve(31), None);
|
|
assert_eq!(cursor.resolve(20), Some(2)); // backwards probe after a gap miss
|
|
}
|
|
|
|
#[test]
|
|
fn benchmark_workload_matches_spec_shape_and_miss_rate() {
|
|
let report = run_provider_mapping_benchmark(200_000).unwrap();
|
|
assert_eq!(report.key_count, PROVIDER_MAPPING_BENCH_KEY_COUNT);
|
|
assert_eq!(report.key_count, 60_000);
|
|
assert_eq!(report.range_count, 68_000);
|
|
assert_eq!(report.multi_range_keys, 6_000);
|
|
assert_eq!(report.hits + report.misses, 200_000);
|
|
let miss_rate = report.misses as f64 / report.lookups as f64;
|
|
// ~5% designed misses plus any random probes that land in interior gaps.
|
|
assert!((0.04..0.07).contains(&miss_rate), "miss rate {miss_rate}");
|
|
|
|
let again = run_provider_mapping_benchmark(200_000).unwrap();
|
|
assert_eq!(report.checksum, again.checksum);
|
|
assert_eq!(report.hits, again.hits);
|
|
}
|