diff --git a/tools/curate-etl/tests/bson_qm_actions_qa_contract.rs b/tools/curate-etl/tests/bson_qm_actions_qa_contract.rs new file mode 100644 index 00000000..471f281f --- /dev/null +++ b/tools/curate-etl/tests/bson_qm_actions_qa_contract.rs @@ -0,0 +1,520 @@ +//! QA contract tests for the public `qmSplits` / `qmDividends` raw BSON decoders (T-107 / M1.2w). +//! +//! Covers gaps left by `src/bson_qm_actions_tests.rs` and `tests/bson_qm_actions_contract.rs`, +//! using only the public API: +//! - zero-copy: `qm_search_code` / `currency` borrow from the input buffer; +//! - field-order independence, case-sensitive keys, nested look-alike keys ignored; +//! - `usdFxRate` / unknown fields with corrupt payloads are skipped without decoding, while the +//! same corruption inside a known field is a typed `CorruptBson` naming that field; +//! - `DateTime` day boundaries (last ms of a day, -1 ms before epoch); +//! - `split_noop_ratio_one` counts exactly `1.0`, not near-one ratios; +//! - error callbacks receive the exact byte offset of the rejected document; empty buffer, +//! truncated tail after good docs, `i32::MAX` declared length; +//! - seeded byte-mutation fuzz for both collections: never panics, always reconciles, and every +//! streamed row equals the single-document decode of the same bytes; +//! - benchmark guard: synthetic docs actually decode (rejections stay near the injected ~0.5%), +//! so a field-constant change cannot silently turn the benchmark into a rejection-path timing; +//! - `bench-bson-qm-actions` binary: identical checksum across two runs, invalid args exit 1. + +use std::process::{Command, Output}; + +use bson::raw::{cstr, RawBsonRef, RawDocumentBuf}; +use bson::DateTime; +use curate_etl::bench::run_bson_qm_actions_benchmark; +use curate_etl::{ + decode_qm_dividend_buffer, decode_qm_dividend_bytes, decode_qm_dividend_doc, + decode_qm_split_buffer, decode_qm_split_bytes, decode_qm_split_doc, iter_raw_bson_docs, + ymd_to_epoch_days, BsonQmActionError, RawQmDividend, RawQmSplit, FIELD_DIVIDEND_CASH, + FIELD_DIVIDEND_CURRENCY, FIELD_QM_SEARCH_CODE, FIELD_SPLIT_RATIO, +}; + +const MILLIS_PER_DAY: i64 = 86_400_000; + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).unwrap() +} + +fn split_doc(code: &str, date: &str, ratio: f64) -> RawDocumentBuf { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("_id"), "ignored"); + doc.append(cstr!("qmSearchCode"), code); + doc.append(cstr!("date"), date); + doc.append(cstr!("splitratio"), ratio); + doc.append(cstr!("usdFxRate"), 1_i32); + doc +} + +fn dividend_doc(code: &str, date: &str, cash: f64, currency: &str) -> RawDocumentBuf { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("_id"), "ignored"); + doc.append(cstr!("qmSearchCode"), code); + doc.append(cstr!("date"), date); + doc.append(cstr!("declared"), "2024-05-01"); + doc.append(cstr!("amount"), cash); + doc.append(cstr!("currency"), currency); + doc.append(cstr!("usdFxRate"), 1_i32); + doc +} + +fn ptr_within(s: &str, buf: &[u8]) -> bool { + let range = buf.as_ptr_range(); + let p = s.as_ptr(); + range.contains(&p) && (p as usize + s.len()) <= range.end as usize +} + +/// Overwrites the first occurrence of `needle` in `bytes` with `replacement` (same length). +fn patch(bytes: &mut [u8], needle: &[u8], replacement: &[u8]) { + assert_eq!(needle.len(), replacement.len()); + let pos = bytes + .windows(needle.len()) + .position(|w| w == needle) + .expect("needle present"); + bytes[pos..pos + needle.len()].copy_from_slice(replacement); +} + +#[test] +fn decoded_strings_borrow_directly_from_the_input_buffer() { + let s = split_doc("NVDA", "2024-06-10", 10.0); + let split = decode_qm_split_bytes(s.as_bytes()).unwrap(); + assert!(ptr_within(split.qm_search_code, s.as_bytes())); + + let d = dividend_doc("RY:CA", "2024-11-15", 1.42, "CAD"); + let mut buf = Vec::new(); + buf.extend_from_slice(d.as_bytes()); + let mut seen = Vec::new(); + decode_qm_dividend_buffer(&buf, |div| seen.push(div), |_, e| panic!("{e}")); + assert_eq!(seen.len(), 1); + assert!(ptr_within(seen[0].qm_search_code, &buf)); + assert!(ptr_within(seen[0].currency, &buf)); +} + +#[test] +fn field_order_is_irrelevant_keys_are_case_sensitive_and_nested_lookalikes_are_ignored() { + // Reverse field order decodes identically. + let mut rev = RawDocumentBuf::new(); + rev.append(cstr!("usdFxRate"), 1.0_f64); + rev.append(cstr!("currency"), "CAD"); + rev.append(cstr!("amount"), 1.42_f64); + rev.append(cstr!("declared"), "2024-05-01"); + rev.append(cstr!("date"), "2024-11-15"); + rev.append(cstr!("qmSearchCode"), "RY:CA"); + let fwd = dividend_doc("RY:CA", "2024-11-15", 1.42, "CAD"); + assert_eq!( + decode_qm_dividend_doc(&rev).unwrap(), + decode_qm_dividend_doc(&fwd).unwrap() + ); + + // Differently-cased keys are unknown fields, so the required field is missing. + let mut cased = RawDocumentBuf::new(); + cased.append(cstr!("QmSearchCode"), "NVDA"); + cased.append(cstr!("date"), "2024-06-10"); + cased.append(cstr!("splitratio"), 10.0_f64); + assert_eq!( + decode_qm_split_doc(&cased).unwrap_err(), + BsonQmActionError::MissingField { + field: FIELD_QM_SEARCH_CODE + } + ); + let mut cased_ratio = RawDocumentBuf::new(); + cased_ratio.append(cstr!("qmSearchCode"), "NVDA"); + cased_ratio.append(cstr!("date"), "2024-06-10"); + cased_ratio.append(cstr!("splitRatio"), 10.0_f64); + assert_eq!( + decode_qm_split_doc(&cased_ratio).unwrap_err(), + BsonQmActionError::MissingField { + field: FIELD_SPLIT_RATIO + } + ); + + // A nested sub-document carrying look-alike keys must neither satisfy nor poison the decode. + let mut nested = RawDocumentBuf::new(); + nested.append(cstr!("splitratio"), -99.0_f64); + nested.append(cstr!("amount"), "bad"); + nested.append(cstr!("currency"), 7_i32); + nested.append(cstr!("date"), "not-a-date"); + let mut outer = split_doc("NVDA", "2024-06-10", 10.0); + outer.append(cstr!("raw"), RawBsonRef::Document(nested.as_ref())); + let split = decode_qm_split_doc(&outer).unwrap(); + assert_eq!(split.ratio, 10.0); + + let mut outer_div = dividend_doc("RY:CA", "2024-11-15", 1.42, "CAD"); + outer_div.append(cstr!("raw"), RawBsonRef::Document(nested.as_ref())); + let div = decode_qm_dividend_doc(&outer_div).unwrap(); + assert_eq!((div.cash, div.currency), (1.42, "CAD")); + + let mut only_nested = RawDocumentBuf::new(); + only_nested.append(cstr!("qmSearchCode"), "NVDA"); + only_nested.append(cstr!("date"), "2024-06-10"); + only_nested.append(cstr!("raw"), RawBsonRef::Document(nested.as_ref())); + assert_eq!( + decode_qm_split_doc(&only_nested).unwrap_err(), + BsonQmActionError::MissingField { + field: FIELD_SPLIT_RATIO + } + ); +} + +#[test] +fn corrupt_payload_in_ignored_field_is_skipped_but_in_known_field_names_that_field() { + // Unknown field / `usdFxRate` with invalid UTF-8 string bytes: framing is valid, payload is + // never decoded. + let mut d = dividend_doc("RY:CA", "2024-11-15", 1.42, "CAD"); + d.append(cstr!("zzExtra"), "XYZW"); + let mut bytes = d.as_bytes().to_vec(); + patch(&mut bytes, b"XYZW", &[0xFF, 0xFE, 0xFD, 0xFC]); + let div = decode_qm_dividend_bytes(&bytes).unwrap(); + assert_eq!(div.currency, "CAD"); + + let mut s = split_doc("NVDA", "2024-06-10", 10.0); + s.append(cstr!("usdFxRate"), "QQQQ"); + let mut bytes = s.as_bytes().to_vec(); + patch(&mut bytes, b"QQQQ", &[0xC3, 0x28, 0xA0, 0xA1]); + assert_eq!(decode_qm_split_bytes(&bytes).unwrap().ratio, 10.0); + + // Same corruption inside `currency` is a typed CorruptBson naming the field (no panic). + let d = dividend_doc("RY:CA", "2024-11-15", 1.42, "QQQ"); + let mut bytes = d.as_bytes().to_vec(); + patch(&mut bytes, b"QQQ", &[0xFF, 0xFE, 0xFD]); + match decode_qm_dividend_bytes(&bytes).unwrap_err() { + BsonQmActionError::CorruptBson { offset, detail } => { + assert_eq!(offset, 0); + assert!(detail.contains(FIELD_DIVIDEND_CURRENCY), "{detail}"); + } + other => panic!("expected CorruptBson, got {other:?}"), + } +} + +#[test] +fn datetime_dates_floor_to_utc_day_at_boundaries() { + let cases = [ + (-1_i64, -1_i32), + (0, 0), + (-MILLIS_PER_DAY, -1), + (-MILLIS_PER_DAY - 1, -2), + ( + i64::from(day(2024, 6, 10)) * MILLIS_PER_DAY + MILLIS_PER_DAY - 1, + day(2024, 6, 10), + ), + ( + i64::from(day(2024, 6, 11)) * MILLIS_PER_DAY, + day(2024, 6, 11), + ), + ]; + for (ms, expected) in cases { + let mut s = RawDocumentBuf::new(); + s.append(cstr!("qmSearchCode"), "IBM"); + s.append(cstr!("date"), DateTime::from_millis(ms)); + s.append(cstr!("declared"), DateTime::from_millis(ms)); + s.append(cstr!("splitratio"), 2_i64); + let split = decode_qm_split_doc(&s).unwrap(); + assert_eq!(split.ex_date, expected, "ms={ms}"); + assert_eq!(split.declared_date, Some(expected), "ms={ms}"); + + let mut d = RawDocumentBuf::new(); + d.append(cstr!("qmSearchCode"), "IBM"); + d.append(cstr!("date"), DateTime::from_millis(ms)); + d.append(cstr!("amount"), 1_i32); + d.append(cstr!("currency"), "USD"); + assert_eq!( + decode_qm_dividend_doc(&d).unwrap().ex_date, + expected, + "ms={ms}" + ); + } +} + +#[test] +fn noop_counter_counts_only_exact_ratio_one() { + let mut buf = Vec::new(); + for ratio in [1.0, 1.000_000_000_1, 0.999_999_999_9, 1.0, 2.0] { + buf.extend_from_slice(split_doc("X", "2024-03-15", ratio).as_bytes()); + } + let mut n = 0; + let stats = decode_qm_split_buffer(&buf, |_| n += 1, |_, e| panic!("{e}")); + assert_eq!(n, 5); + assert_eq!(stats.decoded, 5); + assert_eq!(stats.split_noop_ratio_one, 2); + assert_eq!(stats.rejected_total(), 0); + + // Dividends never touch the split no-op counter. + let d = dividend_doc("X", "2024-03-15", 1.0, "USD"); + let stats = decode_qm_dividend_buffer(d.as_bytes(), |_| {}, |_, e| panic!("{e}")); + assert_eq!(stats.split_noop_ratio_one, 0); +} + +#[test] +fn error_callbacks_report_exact_offsets_and_framing_failures_stop_cleanly() { + // Empty buffer: nothing in, nothing out. + let stats = decode_qm_split_buffer(&[], |_| panic!(), |_, _| panic!()); + assert_eq!(stats, Default::default()); + let stats = decode_qm_dividend_buffer(&[], |_| panic!(), |_, _| panic!()); + assert_eq!(stats, Default::default()); + + let good = dividend_doc("A", "2024-06-10", 0.5, "USD"); + let bad_cash = dividend_doc("B", "2024-06-10", -0.5, "USD"); + let bad_date = dividend_doc("C", "2024-13-01", 0.5, "USD"); + let mut buf = Vec::new(); + let mut expected_err_offsets = Vec::new(); + buf.extend_from_slice(good.as_bytes()); + expected_err_offsets.push(buf.len()); + buf.extend_from_slice(bad_cash.as_bytes()); + expected_err_offsets.push(buf.len()); + buf.extend_from_slice(bad_date.as_bytes()); + buf.extend_from_slice(good.as_bytes()); + // Truncated tail: declares a full doc but only half is present. + expected_err_offsets.push(buf.len()); + let tail_start = buf.len(); + buf.extend_from_slice(&good.as_bytes()[..good.as_bytes().len() / 2]); + + let mut errs = Vec::new(); + let mut codes = Vec::new(); + let stats = decode_qm_dividend_buffer( + &buf, + |d: RawQmDividend<'_>| codes.push(d.qm_search_code), + |off, e| errs.push((off, e)), + ); + assert_eq!(codes, vec!["A", "A"]); + assert_eq!( + errs.iter().map(|(o, _)| *o).collect::>(), + expected_err_offsets + ); + assert!(matches!( + errs[0].1, + BsonQmActionError::InvalidNumber { + field: FIELD_DIVIDEND_CASH, + .. + } + )); + assert!(matches!( + errs[2].1, + BsonQmActionError::TruncatedDocument { + offset, + declared_len: Some(_), + .. + } if offset == tail_start + )); + assert_eq!(stats.docs_in, 5); + assert_eq!(stats.decoded, 2); + assert_eq!(stats.rejected_corrupt_document, 1); + assert_eq!(stats.decoded + stats.rejected_total(), stats.docs_in); + + // i32::MAX declared length after a good split doc terminates without panicking. + let mut buf = split_doc("S", "2024-06-10", 2.0).as_bytes().to_vec(); + let bad_at = buf.len(); + buf.extend_from_slice(&i32::MAX.to_le_bytes()); + buf.extend_from_slice(&[0u8; 8]); + let mut errs = Vec::new(); + let stats = decode_qm_split_buffer(&buf, |_| {}, |off, e| errs.push((off, e))); + assert_eq!(stats.docs_in, 2); + assert_eq!(stats.decoded, 1); + assert_eq!(errs.len(), 1); + assert_eq!(errs[0].0, bad_at); + assert!(matches!( + errs[0].1, + BsonQmActionError::TruncatedDocument { .. } + )); + + // Single-doc decoder: trailing bytes are rejected as a length mismatch, not silently ignored. + let mut trailing = split_doc("S", "2024-06-10", 2.0).as_bytes().to_vec(); + trailing.push(0); + assert!(matches!( + decode_qm_split_bytes(&trailing).unwrap_err(), + BsonQmActionError::CorruptDocumentLength { .. } + )); +} + +/// `std`-only SplitMix64 so the fuzz corpus is fixed across runs. +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 mutate(rng: &mut SplitMix64, base: &[u8]) -> Vec { + let mut buf = base.to_vec(); + let flips = 1 + (rng.next() % 4) as usize; + for _ in 0..flips { + let pos = (rng.next() as usize) % buf.len(); + buf[pos] = rng.next() as u8; + } + if rng.next() % 4 == 0 { + let cut = (rng.next() as usize) % buf.len(); + buf.truncate(cut); + } + buf +} + +fn framed_slices(buf: &[u8]) -> Vec<(usize, usize)> { + let mut out = Vec::new(); + let mut iter = iter_raw_bson_docs(buf); + while let Some(item) = iter.next_with_offset() { + if let Ok((off, doc)) = item { + out.push((off, doc.as_bytes().len())); + } + } + out +} + +#[test] +fn seeded_byte_mutation_fuzz_never_panics_and_always_reconciles_for_both_collections() { + let mut split_base = Vec::new(); + let mut div_base = Vec::new(); + for i in 0..8 { + let code = format!("Q{i}:CA"); + split_base.extend_from_slice(split_doc(&code, "2024-06-07", 1.0 + i as f64).as_bytes()); + div_base + .extend_from_slice(dividend_doc(&code, "2024-06-07", 0.1 * i as f64, "CAD").as_bytes()); + } + + let split_key = |s: &RawQmSplit<'_>| { + ( + s.qm_search_code.to_string(), + s.ex_date, + s.ratio.to_bits(), + s.declared_date, + ) + }; + let div_key = |d: &RawQmDividend<'_>| { + ( + d.qm_search_code.to_string(), + d.ex_date, + d.cash.to_bits(), + d.currency.to_string(), + d.declared_date, + ) + }; + + let mut rng = SplitMix64(0x0B50_7E57_0A11_0107); + for _ in 0..2_000 { + let buf = mutate(&mut rng, &split_base); + let mut rows = Vec::new(); + let stats = decode_qm_split_buffer(&buf, |s| rows.push(s), |_, _| {}); + assert_eq!(stats.decoded + stats.rejected_total(), stats.docs_in); + assert_eq!(stats.decoded, rows.len()); + assert_eq!( + stats.split_noop_ratio_one, + rows.iter().filter(|s| s.ratio == 1.0).count() + ); + let expected: Vec<_> = framed_slices(&buf) + .into_iter() + .filter_map(|(o, l)| decode_qm_split_bytes(&buf[o..o + l]).ok()) + .collect(); + assert_eq!( + rows.iter().map(split_key).collect::>(), + expected.iter().map(split_key).collect::>() + ); + for s in &rows { + assert!(s.ratio.is_finite() && s.ratio > 0.0); + assert!(!s.qm_search_code.trim().is_empty()); + } + + let buf = mutate(&mut rng, &div_base); + let mut rows = Vec::new(); + let stats = decode_qm_dividend_buffer(&buf, |d| rows.push(d), |_, _| {}); + assert_eq!(stats.decoded + stats.rejected_total(), stats.docs_in); + assert_eq!(stats.decoded, rows.len()); + assert_eq!(stats.split_noop_ratio_one, 0); + let expected: Vec<_> = framed_slices(&buf) + .into_iter() + .filter_map(|(o, l)| decode_qm_dividend_bytes(&buf[o..o + l]).ok()) + .collect(); + assert_eq!( + rows.iter().map(div_key).collect::>(), + expected.iter().map(div_key).collect::>() + ); + for d in &rows { + assert!(d.cash.is_finite() && d.cash >= 0.0 && !d.cash.is_sign_negative()); + assert!(!d.currency.trim().is_empty()); + } + } +} + +#[test] +fn benchmark_corpus_mostly_decodes_so_it_times_the_happy_path() { + let report = run_bson_qm_actions_benchmark(20_000); + let s = report.split_stats; + let d = report.dividend_stats; + assert_eq!(s.docs_in + d.docs_in, 20_000); + // Injected errors are ~0.5% per collection; allow generous headroom but fail if a renamed + // field constant makes the corpus reject en masse. + assert!( + s.rejected_total() * 50 < s.docs_in, + "split rejections too high: {s:?}" + ); + assert!( + d.rejected_total() * 50 < d.docs_in, + "dividend rejections too high: {d:?}" + ); + assert_eq!(s.rejected_corrupt_document + d.rejected_corrupt_document, 0); +} + +fn run_bin(args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_curate-etl")) + .args(args) + .output() + .expect("spawn curate-etl binary") +} + +fn stable_output(out: &Output) -> String { + let text = String::from_utf8_lossy(&out.stdout); + let checksum = text + .split_whitespace() + .find(|t| t.starts_with("checksum=0x")) + .unwrap_or_else(|| panic!("no checksum in output: {text}")); + let stats: Vec<&str> = text + .lines() + .map(str::trim_start) + .filter(|l| { + l.starts_with("input:") || l.starts_with("splits:") || l.starts_with("dividends:") + }) + .collect(); + assert_eq!(stats.len(), 3, "missing stats lines: {text}"); + format!("{checksum} {}", stats.join(" | ")) +} + +#[test] +fn bench_binary_prints_identical_checksum_and_stats_across_runs() { + let a = run_bin(&["bench-bson-qm-actions", "5000"]); + let b = run_bin(&["bench-bson-qm-actions", "5000"]); + assert!(a.status.success(), "{}", String::from_utf8_lossy(&a.stderr)); + assert!(b.status.success(), "{}", String::from_utf8_lossy(&b.stderr)); + + let text = String::from_utf8_lossy(&a.stdout); + assert!(text.contains("rows=5000"), "{text}"); + for needle in [ + "elapsed=", + "docs/s", + "MB/s", + "noop_ratio_one=", + "checksum=0x", + ] { + assert!(text.contains(needle), "missing {needle}: {text}"); + } + assert_eq!(stable_output(&a), stable_output(&b)); +} + +#[test] +fn bench_binary_rejects_invalid_row_counts_and_is_listed_in_usage() { + for args in [ + &["bench-bson-qm-actions", "0"][..], + &["bench-bson-qm-actions", "-5"][..], + &["bench-bson-qm-actions", "abc"][..], + &["bench-bson-qm-actions", "10", "20"][..], + ] { + let out = run_bin(args); + assert_eq!(out.status.code(), Some(1), "{args:?}"); + let err = String::from_utf8_lossy(&out.stderr); + assert!(err.contains("error:"), "{args:?}: {err}"); + assert!(out.stdout.is_empty(), "{args:?} wrote to stdout"); + } + + let out = run_bin(&["--help"]); + assert!(out.status.success()); + assert!(String::from_utf8_lossy(&out.stdout).contains("bench-bson-qm-actions")); +}