diff --git a/tools/curate-etl/tests/bson_eod_prices_qa_contract.rs b/tools/curate-etl/tests/bson_eod_prices_qa_contract.rs new file mode 100644 index 00000000..529940a8 --- /dev/null +++ b/tools/curate-etl/tests/bson_eod_prices_qa_contract.rs @@ -0,0 +1,387 @@ +//! QA contract tests for the public `eodPrices` raw BSON decoder (T-97 / M1.2o). +//! +//! Covers gaps left by the in-crate `bson_eod_prices_tests.rs`, using only the public API: +//! - zero-copy: decoded `eod_search_code` borrows from the input buffer; +//! - field-order independence, case-sensitive keys, nested look-alike keys ignored; +//! - `DateTime` day boundaries (last ms of a day, -1 ms before epoch); +//! - error callbacks receive the exact byte offset of the rejected document; +//! - empty buffer, truncated tail after good docs, `i32::MAX` declared length, trailing bytes; +//! - seeded byte-mutation fuzz: never panics and `decoded + rejected == docs_in` always holds, +//! and every decoded bar is identical to the single-document decode of the same bytes; +//! - `bench-bson-eod-prices` 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::{ + decode_eod_price_buffer, decode_eod_price_bytes, decode_eod_price_doc, iter_raw_bson_docs, + ymd_to_epoch_days, BsonEodPriceError, RawEodDailyBar, +}; + +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 valid_doc(code: &str, date: &str, close: f64, volume: i64) -> RawDocumentBuf { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("_id"), "ignored"); + doc.append(cstr!("eodSearchCode"), code); + doc.append(cstr!("date"), date); + doc.append(cstr!("open"), close - 1.0); + doc.append(cstr!("high"), close + 1.0); + doc.append(cstr!("low"), close - 2.0); + doc.append(cstr!("close"), close); + doc.append(cstr!("volume"), volume); + doc +} + +#[test] +fn decoded_search_code_borrows_from_input_buffer_without_copying() { + let doc = valid_doc("RY.TO", "2024-06-07", 130.0, 1_000); + let bytes = doc.as_bytes(); + let bar = decode_eod_price_bytes(bytes).unwrap(); + + let start = bytes.as_ptr() as usize; + let end = start + bytes.len(); + let code_ptr = bar.eod_search_code.as_ptr() as usize; + assert!( + code_ptr >= start && code_ptr + bar.eod_search_code.len() <= end, + "eod_search_code must point into the input bytes" + ); + assert_eq!(bar.eod_search_code, "RY.TO"); +} + +#[test] +fn field_order_does_not_change_the_decoded_bar() { + let mut reversed = RawDocumentBuf::new(); + reversed.append(cstr!("volume"), 1_000_i64); + reversed.append(cstr!("close"), 130.0_f64); + reversed.append(cstr!("low"), 128.0_f64); + reversed.append(cstr!("high"), 131.0_f64); + reversed.append(cstr!("open"), 129.0_f64); + reversed.append(cstr!("date"), "2024-06-07"); + reversed.append(cstr!("eodSearchCode"), "RY.TO"); + + let forward = valid_doc("RY.TO", "2024-06-07", 130.0, 1_000); + assert_eq!( + decode_eod_price_doc(&reversed).unwrap(), + decode_eod_price_doc(&forward).unwrap() + ); +} + +#[test] +fn keys_are_case_sensitive_and_nested_lookalikes_are_ignored() { + // `Volume` (capitalised) and a nested `volume` must not satisfy the top-level field. + let mut nested = RawDocumentBuf::new(); + nested.append(cstr!("volume"), 5_i64); + + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), "RY.TO"); + doc.append(cstr!("date"), "2024-06-07"); + doc.append(cstr!("open"), 1.0_f64); + doc.append(cstr!("high"), 1.0_f64); + doc.append(cstr!("low"), 1.0_f64); + doc.append(cstr!("close"), 1.0_f64); + doc.append(cstr!("Volume"), 5_i64); + doc.append(cstr!("meta"), RawBsonRef::Document(nested.as_ref())); + + assert_eq!( + decode_eod_price_doc(&doc).unwrap_err(), + BsonEodPriceError::MissingField { field: "volume" } + ); +} + +#[test] +fn unknown_fields_with_unusual_types_are_ignored() { + // Only known keys are type-checked; the writer's optional `adjustedClose` may be null. + let mut doc = valid_doc("RY.TO", "2024-06-07", 130.0, 1_000); + doc.append(cstr!("adjustedClose"), RawBsonRef::Null); + doc.append(cstr!("adjusted_close"), "n/a"); + doc.append(cstr!("updated_at"), true); + + let bar = decode_eod_price_bytes(doc.as_bytes()).unwrap(); + assert_eq!(bar.close, 130.0); + assert_eq!(bar.adj_volume, 1_000.0); +} + +#[test] +fn datetime_maps_to_utc_calendar_day_at_both_boundaries() { + let d = day(2024, 6, 7); + let cases = [ + (i64::from(d) * MILLIS_PER_DAY, d), + (i64::from(d) * MILLIS_PER_DAY + MILLIS_PER_DAY - 1, d), + (i64::from(d + 1) * MILLIS_PER_DAY, d + 1), + (-1, -1), + (0, 0), + ]; + for (ms, expected) in cases { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), "RY.TO"); + doc.append(cstr!("date"), DateTime::from_millis(ms)); + doc.append(cstr!("open"), 1.0_f64); + doc.append(cstr!("high"), 1.0_f64); + doc.append(cstr!("low"), 1.0_f64); + doc.append(cstr!("close"), 1.0_f64); + doc.append(cstr!("volume"), 1_i32); + assert_eq!( + decode_eod_price_doc(&doc).unwrap().session_date, + expected, + "ms={ms}" + ); + } +} + +#[test] +fn key_mapper_receives_search_code_and_session_date() { + let doc = valid_doc("RY.TO", "2024-06-07", 130.0, 1_000); + let raw: RawEodDailyBar<'_> = decode_eod_price_doc(&doc).unwrap(); + + let mut seen = None; + let bar = raw.into_eod_daily_bar(|code, date| { + seen = Some((code.len(), date)); + 7_u32 + }); + assert_eq!(seen, Some((5, day(2024, 6, 7)))); + assert_eq!(bar.key, 7); + assert_eq!(bar.session_date, day(2024, 6, 7)); + assert_eq!(bar.adj_volume, 1_000.0); + + assert!(raw.try_into_eod_daily_bar(|_, _| None::).is_none()); +} + +#[test] +fn error_callback_reports_exact_byte_offset_of_each_rejected_doc() { + let good = valid_doc("A.US", "2024-06-07", 10.0, 1); + let bad_date = valid_doc("B.US", "2024-02-30", 10.0, 1); + let bad_vol = valid_doc("C.US", "2024-06-07", 10.0, -1); + + let mut buf = Vec::new(); + buf.extend_from_slice(good.as_bytes()); + let off_bad_date = buf.len(); + buf.extend_from_slice(bad_date.as_bytes()); + buf.extend_from_slice(good.as_bytes()); + let off_bad_vol = buf.len(); + buf.extend_from_slice(bad_vol.as_bytes()); + + let mut errors = Vec::new(); + let mut decoded = 0; + let stats = decode_eod_price_buffer(&buf, |_| decoded += 1, |o, e| errors.push((o, e))); + + assert_eq!(decoded, 2); + assert_eq!( + errors, + vec![ + ( + off_bad_date, + BsonEodPriceError::MalformedDate { field: "date" } + ), + ( + off_bad_vol, + BsonEodPriceError::InvalidNumber { + field: "volume", + value: -1.0 + } + ), + ] + ); + assert_eq!(stats.docs_in, 4); + assert_eq!(stats.decoded + stats.rejected_total(), stats.docs_in); +} + +#[test] +fn empty_buffer_yields_no_docs_and_no_callbacks() { + let stats = decode_eod_price_buffer( + &[], + |_| panic!("no bar expected"), + |_, _| panic!("no error expected"), + ); + assert_eq!(stats.docs_in, 0); + assert_eq!(stats.rejected_total(), 0); + assert!(iter_raw_bson_docs(&[]).next().is_none()); +} + +#[test] +fn truncated_tail_after_good_docs_counts_one_corrupt_reject() { + let good = valid_doc("A.US", "2024-06-07", 10.0, 1); + let mut buf = Vec::new(); + buf.extend_from_slice(good.as_bytes()); + buf.extend_from_slice(good.as_bytes()); + let tail_offset = buf.len(); + buf.extend_from_slice(&good.as_bytes()[..10]); + + let mut errors = Vec::new(); + let stats = decode_eod_price_buffer(&buf, |_| {}, |o, e| errors.push((o, e))); + + assert_eq!(stats.docs_in, 3); + assert_eq!(stats.decoded, 2); + assert_eq!(stats.rejected_corrupt_document, 1); + assert_eq!(errors.len(), 1); + assert_eq!(errors[0].0, tail_offset); + assert!(matches!( + errors[0].1, + BsonEodPriceError::TruncatedDocument { + remaining: 10, + declared_len: Some(_), + .. + } + )); +} + +#[test] +fn huge_declared_length_is_truncation_not_a_panic() { + let mut buf = i32::MAX.to_le_bytes().to_vec(); + buf.extend_from_slice(&[0u8; 16]); + assert_eq!( + decode_eod_price_bytes(&buf).unwrap_err(), + BsonEodPriceError::TruncatedDocument { + offset: 0, + remaining: 20, + declared_len: Some(i32::MAX), + } + ); + let stats = decode_eod_price_buffer(&buf, |_| {}, |_, _| {}); + assert_eq!(stats.docs_in, 1); + assert_eq!(stats.rejected_corrupt_document, 1); +} + +#[test] +fn single_doc_decode_rejects_trailing_bytes() { + let mut bytes = valid_doc("A.US", "2024-06-07", 10.0, 1).as_bytes().to_vec(); + let declared = bytes.len() as i32; + bytes.push(0); + assert_eq!( + decode_eod_price_bytes(&bytes).unwrap_err(), + BsonEodPriceError::CorruptDocumentLength { + offset: 0, + declared_len: declared, + } + ); +} + +/// `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) + } +} + +#[test] +fn seeded_byte_mutation_fuzz_never_panics_and_always_reconciles() { + let mut base = Vec::new(); + for i in 0..8 { + let code = format!("S{i}.US"); + base.extend_from_slice(valid_doc(&code, "2024-06-07", 10.0 + i as f64, 100).as_bytes()); + } + + let mut rng = SplitMix64(0x0B50_7E57_F022_0097); + for _ in 0..3_000 { + let mut buf = base.clone(); + 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); + } + + // Every bar emitted by the stream must equal the single-doc decode of its framed bytes. + let mut offsets = Vec::new(); + let mut iter = iter_raw_bson_docs(&buf); + while let Some(item) = iter.next_with_offset() { + if let Ok((off, doc)) = item { + offsets.push((off, doc.as_bytes().len())); + } + } + + let mut bars = Vec::new(); + let stats = decode_eod_price_buffer(&buf, |b| bars.push(b), |_, _| {}); + assert_eq!(stats.decoded + stats.rejected_total(), stats.docs_in); + assert_eq!(stats.decoded, bars.len()); + + let mut expected = Vec::new(); + for (off, len) in offsets { + if let Ok(b) = decode_eod_price_bytes(&buf[off..off + len]) { + expected.push(b); + } + } + // Compare bit patterns so a NaN can never hide a mismatch (decoder rejects NaN anyway). + let key = |b: &RawEodDailyBar<'_>| { + ( + b.eod_search_code.to_string(), + b.session_date, + [b.open, b.high, b.low, b.close, b.adj_volume].map(f64::to_bits), + ) + }; + assert_eq!( + bars.iter().map(key).collect::>(), + expected.iter().map(key).collect::>() + ); + for b in &bars { + for v in [b.open, b.high, b.low, b.close, b.adj_volume] { + assert!(v.is_finite() && v >= 0.0); + } + } + } +} + +fn run_bin(args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_curate-etl")) + .args(args) + .output() + .expect("spawn curate-etl binary") +} + +fn checksum_line(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 decode = text + .lines() + .find(|l| l.trim_start().starts_with("decode:")) + .unwrap_or_else(|| panic!("no decode line in output: {text}")); + format!("{checksum} {}", decode.trim()) +} + +#[test] +fn bench_binary_prints_identical_checksum_across_runs() { + let a = run_bin(&["bench-bson-eod-prices", "5000"]); + let b = run_bin(&["bench-bson-eod-prices", "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=", "rows/s", "MB/s", "checksum=0x"] { + assert!(text.contains(needle), "missing {needle}: {text}"); + } + assert_eq!(checksum_line(&a), checksum_line(&b)); +} + +#[test] +fn bench_binary_rejects_invalid_row_counts() { + for args in [ + &["bench-bson-eod-prices", "0"][..], + &["bench-bson-eod-prices", "-5"][..], + &["bench-bson-eod-prices", "abc"][..], + &["bench-bson-eod-prices", "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"); + } +}