diff --git a/tools/curate-etl/tests/bson_eod_intraday_qa_contract.rs b/tools/curate-etl/tests/bson_eod_intraday_qa_contract.rs new file mode 100644 index 00000000..5fe00412 --- /dev/null +++ b/tools/curate-etl/tests/bson_eod_intraday_qa_contract.rs @@ -0,0 +1,438 @@ +//! QA contract tests for the public `eodIntraday1M` raw BSON decoder (T-141 / M2.3d). +//! +//! Covers gaps left by the in-crate `bson_eod_intraday_tests.rs`, using only the public API: +//! - field-order independence, case-sensitive keys, nested look-alike keys ignored; +//! - error precedence: corrupt skipped payload beats an earlier semantic error, and the first +//! semantic error in document order wins over later ones; +//! - timestamp edge values (`i32::MAX`, subnormal / half-second / huge doubles); +//! - `Display` names the offending field; empty buffer; `i32::MAX` declared length; +//! - seeded byte-mutation fuzz: never panics, conservation always holds, every buffer row equals +//! the single-document decode of the same frame, and the stream decode reproduces the buffer +//! rows, per-document errors, and terminal framing offset; +//! - stream: empty input, `max_doc_bytes` overflow, and invalid options; +//! - UTC bar-start micros map to the right `build_bars_1m` session date across the UTC midnight. + +use std::io::{self, Cursor, Read}; + +use bson::raw::{cstr, RawBsonRef, RawDocumentBuf}; +use curate_etl::{ + build_bars_1m, decode_eod_intraday_buffer, decode_eod_intraday_bytes, + decode_eod_intraday_doc, decode_eod_intraday_stream, iter_raw_bson_docs, ymd_to_epoch_days, + BsonEodIntradayDecodeStats, BsonEodIntradayError, BsonStreamError, BsonStreamOptions, + RawEodIntradayBar, SplitTable, +}; + +const TS: i64 = 1_717_767_000; + +struct SplitMix64(u64); + +impl SplitMix64 { + 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) + } +} + +/// Reader returning seeded pseudo-random short reads of 1..=61 bytes. +struct JitterReader<'a> { + data: &'a [u8], + pos: usize, + rng: SplitMix64, +} + +impl Read for JitterReader<'_> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + let remaining = self.data.len() - self.pos; + if remaining == 0 { + return Ok(0); + } + let step = (self.rng.next_u64() % 61) as usize + 1; + let take = remaining.min(step).min(buf.len()); + buf[..take].copy_from_slice(&self.data[self.pos..self.pos + take]); + self.pos += take; + Ok(take) + } +} + +fn valid_doc(code: &str, ts: i64, close: f64, volume: f64) -> RawDocumentBuf { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("symbol"), "X"); + doc.append(cstr!("eodSearchCode"), code); + doc.append(cstr!("datetime"), "2024-06-07 13:30:00"); + doc.append(cstr!("timestamp"), ts); + doc.append(cstr!("gmtoffset"), 0_i32); + doc.append(cstr!("open"), close - 0.25); + doc.append(cstr!("high"), close + 0.5); + doc.append(cstr!("low"), close - 0.5); + doc.append(cstr!("close"), close); + doc.append(cstr!("volume"), volume); + doc +} + +fn with_timestamp(ts: RawBsonRef<'_>) -> RawDocumentBuf { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), "NVDA.US"); + doc.append(cstr!("timestamp"), ts); + doc.append(cstr!("open"), 10.0_f64); + doc.append(cstr!("high"), 11.0_f64); + doc.append(cstr!("low"), 9.0_f64); + doc.append(cstr!("close"), 10.5_f64); + doc.append(cstr!("volume"), 1.0_f64); + doc +} + +type Row = (String, i64, [u64; 5]); + +fn row(b: RawEodIntradayBar<'_>) -> Row { + ( + b.eod_search_code.to_owned(), + b.ts, + [ + b.open.to_bits(), + b.high.to_bits(), + b.low.to_bits(), + b.close.to_bits(), + b.volume.to_bits(), + ], + ) +} + +#[test] +fn field_order_does_not_change_the_decoded_bar() { + let forward = valid_doc("NVDA.US", TS, 120.5, 1_000.0); + let mut reversed = RawDocumentBuf::new(); + reversed.append(cstr!("volume"), 1_000.0_f64); + reversed.append(cstr!("close"), 120.5_f64); + reversed.append(cstr!("low"), 120.0_f64); + reversed.append(cstr!("high"), 121.0_f64); + reversed.append(cstr!("open"), 120.25_f64); + reversed.append(cstr!("timestamp"), TS); + reversed.append(cstr!("eodSearchCode"), "NVDA.US"); + + assert_eq!( + decode_eod_intraday_doc(&forward).unwrap(), + decode_eod_intraday_doc(&reversed).unwrap() + ); +} + +#[test] +fn keys_are_case_sensitive_and_nested_look_alikes_are_ignored() { + // `Timestamp` (capital T) is not `timestamp`; a nested `timestamp` must not satisfy it either. + let mut nested = RawDocumentBuf::new(); + nested.append(cstr!("timestamp"), TS); + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), "NVDA.US"); + doc.append(cstr!("Timestamp"), TS); + doc.append(cstr!("meta"), RawBsonRef::Document(nested.as_ref())); + doc.append(cstr!("open"), 10.0_f64); + doc.append(cstr!("high"), 11.0_f64); + doc.append(cstr!("low"), 9.0_f64); + doc.append(cstr!("close"), 10.5_f64); + doc.append(cstr!("volume"), 1.0_f64); + + assert_eq!( + decode_eod_intraday_doc(&doc), + Err(BsonEodIntradayError::MissingField { field: "timestamp" }) + ); +} + +#[test] +fn eod_search_code_is_borrowed_verbatim_without_trimming() { + let doc = valid_doc(" NVDA.US ", TS, 10.0, 1.0); + let bar = decode_eod_intraday_bytes(doc.as_bytes()).unwrap(); + assert_eq!(bar.eod_search_code, " NVDA.US "); +} + +#[test] +fn first_semantic_error_in_document_order_wins() { + // close is invalid before eodSearchCode is blank: close error must be reported. + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("close"), -1.0_f64); + doc.append(cstr!("eodSearchCode"), ""); + doc.append(cstr!("timestamp"), -5_i64); + doc.append(cstr!("open"), 10.0_f64); + doc.append(cstr!("high"), 11.0_f64); + doc.append(cstr!("low"), 9.0_f64); + doc.append(cstr!("volume"), 1.0_f64); + + match decode_eod_intraday_doc(&doc) { + Err(BsonEodIntradayError::InvalidNumber { field: "close", value }) => { + assert_eq!(value, -1.0) + } + other => panic!("expected InvalidNumber(close), got {other:?}"), + } + + // A semantic error plus a missing field: the semantic error wins over MissingField. + let mut doc2 = RawDocumentBuf::new(); + doc2.append(cstr!("eodSearchCode"), "NVDA.US"); + doc2.append(cstr!("timestamp"), RawBsonRef::Null); + assert!(matches!( + decode_eod_intraday_doc(&doc2), + Err(BsonEodIntradayError::WrongType { field: "timestamp", .. }) + )); +} + +#[test] +fn corrupt_skipped_payload_after_semantic_error_is_reported_as_corrupt_bson() { + // Blank key (semantic) first, then a later `datetime` string with invalid UTF-8. + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), " "); + doc.append(cstr!("timestamp"), TS); + doc.append(cstr!("open"), 10.0_f64); + doc.append(cstr!("high"), 11.0_f64); + doc.append(cstr!("low"), 9.0_f64); + doc.append(cstr!("close"), 10.5_f64); + doc.append(cstr!("volume"), 1.0_f64); + doc.append(cstr!("datetime"), "ZZZZ"); + let mut bytes = doc.into_bytes(); + let pos = bytes.windows(4).position(|w| w == b"ZZZZ").unwrap(); + bytes[pos + 1] = 0xFF; + + let mut stats = BsonEodIntradayDecodeStats::default(); + let mut errs = Vec::new(); + let s = decode_eod_intraday_buffer(&bytes, |_| panic!("no row"), |o, e| errs.push((o, e))); + stats.merge(&s); + assert_eq!(errs.len(), 1); + assert!(matches!(errs[0], (0, BsonEodIntradayError::CorruptBson { offset: 0, .. }))); + assert_eq!(stats.rejected_corrupt_document, 1); + assert_eq!(stats.rejected_empty_field, 0); + assert_eq!(stats.rejected_total(), 1); +} + +#[test] +fn timestamp_edge_values_are_accepted_or_rejected_exactly() { + // i32::MAX seconds (2038-01-19) is valid in Int32 form. + let bar_doc = with_timestamp(RawBsonRef::Int32(i32::MAX)); + let bar = decode_eod_intraday_doc(&bar_doc).unwrap(); + assert_eq!(bar.ts, i64::from(i32::MAX) * 1_000_000); + + let max_secs = i64::MAX / 1_000_000; + for bad in [ + RawBsonRef::Double(f64::MIN_POSITIVE), + RawBsonRef::Double(5e-324), + RawBsonRef::Double(max_secs as f64 + 0.5), + RawBsonRef::Double(1e300), + RawBsonRef::Double(f64::MAX), + RawBsonRef::Int32(i32::MIN), + RawBsonRef::Int64(i64::MIN), + ] { + let doc = with_timestamp(bad); + assert_eq!( + decode_eod_intraday_doc(&doc), + Err(BsonEodIntradayError::InvalidTimestamp { field: "timestamp" }), + "timestamp {bad:?}" + ); + } +} + +#[test] +fn display_messages_name_the_offending_field_and_offset() { + let cases = [ + (BsonEodIntradayError::MissingField { field: "eodSearchCode" }, "eodSearchCode"), + (BsonEodIntradayError::EmptyField { field: "eodSearchCode" }, "eodSearchCode"), + (BsonEodIntradayError::InvalidTimestamp { field: "timestamp" }, "timestamp"), + (BsonEodIntradayError::InvalidNumber { field: "volume", value: -1.0 }, ">= 0"), + (BsonEodIntradayError::InvalidNumber { field: "close", value: 0.0 }, "> 0"), + ( + BsonEodIntradayError::CorruptBson { offset: 77, detail: "x".into() }, + "77", + ), + ]; + for (err, needle) in cases { + let msg = err.to_string(); + assert!(msg.contains(needle), "{msg:?} should contain {needle:?}"); + } +} + +#[test] +fn empty_buffer_and_huge_declared_length_never_panic() { + let stats = decode_eod_intraday_buffer(&[], |_| panic!(), |_, _| panic!()); + assert_eq!(stats, BsonEodIntradayDecodeStats::default()); + + let mut bytes = valid_doc("NVDA.US", TS, 10.0, 1.0).into_bytes(); + let first_len = bytes.len(); + bytes.extend_from_slice(&i32::MAX.to_le_bytes()); + bytes.extend_from_slice(&[0u8; 8]); + let mut rows = 0usize; + let mut errs = Vec::new(); + let stats = decode_eod_intraday_buffer(&bytes, |_| rows += 1, |o, e| errs.push((o, e))); + assert_eq!(rows, 1); + assert_eq!(stats.docs_seen, 2); + assert_eq!(stats.rejected_corrupt_document, 1); + assert_eq!(errs.len(), 1); + assert_eq!(errs[0].0, first_len); + assert!(matches!( + errs[0].1, + BsonEodIntradayError::TruncatedDocument { declared_len: Some(i32::MAX), .. } + )); +} + +fn is_framing(e: &BsonEodIntradayError) -> bool { + matches!( + e, + BsonEodIntradayError::TruncatedDocument { .. } + | BsonEodIntradayError::CorruptDocumentLength { .. } + ) +} + +#[test] +fn seeded_mutation_fuzz_buffer_and_stream_agree_and_conserve_counts() { + let mut clean = Vec::new(); + for i in 0..20i64 { + let doc = valid_doc(&format!("S{i:02}.US"), TS + 60 * i, 10.0 + i as f64, 100.0 * i as f64); + clean.extend_from_slice(doc.as_bytes()); + } + let mut rng = SplitMix64(0x7141_B50E); + let (mut framing_cases, mut ok_cases, mut rows_seen) = (0usize, 0usize, 0usize); + + for case in 0..400u64 { + let mut bytes = clean.clone(); + for _ in 0..1 + (rng.next_u64() % 4) as usize { + let idx = (rng.next_u64() as usize) % bytes.len(); + bytes[idx] = rng.next_u64() as u8; + } + if rng.next_u64() % 5 == 0 { + let cut = (rng.next_u64() as usize) % bytes.len(); + bytes.truncate(cut); + } + + // Buffer decode: every row must equal the single-frame decode of the same bytes. + let mut frames = Vec::new(); + let mut it = iter_raw_bson_docs(&bytes); + while let Some(item) = it.next_with_offset() { + if let Ok((off, doc)) = item { + frames.push((off, doc.as_bytes().len())); + } + } + let mut exp_rows = Vec::new(); + let mut exp_errs = Vec::new(); + let stats = decode_eod_intraday_buffer( + &bytes, + |b| { + let start = b.eod_search_code.as_ptr() as usize - bytes.as_ptr() as usize; + let &(off, len) = frames + .iter() + .find(|(o, l)| start >= *o && start < o + l) + .expect("row borrows from a framed doc"); + assert_eq!(decode_eod_intraday_bytes(&bytes[off..off + len]).unwrap(), b); + exp_rows.push(row(b)); + }, + |o, e| exp_errs.push((o as u64, e)), + ); + assert_eq!(stats.docs_seen, stats.rows_decoded + stats.rejected_total(), "case={case}"); + assert_eq!(stats.rows_decoded, exp_rows.len()); + assert_eq!(stats.rejected_total(), exp_errs.len()); + rows_seen += exp_rows.len(); + + let exp_framing = match exp_errs.last() { + Some((off, e)) if is_framing(e) => { + let off = *off; + exp_errs.pop(); + Some(off) + } + _ => None, + }; + + let cap = [1usize, 5, 41, 300, 4096][(case % 5) as usize]; + let mut rows = Vec::new(); + let mut errs = Vec::new(); + let result = decode_eod_intraday_stream( + JitterReader { data: &bytes, pos: 0, rng: SplitMix64(case) }, + BsonStreamOptions { chunk_capacity_bytes: cap, max_doc_bytes: 1 << 20 }, + |b| rows.push(row(b)), + |o, e| errs.push((o, e)), + ); + assert_eq!(rows, exp_rows, "case={case} cap={cap}"); + assert_eq!(errs, exp_errs, "case={case} cap={cap}"); + match (exp_framing, result) { + (None, Ok(s)) => { + ok_cases += 1; + assert_eq!(s, stats, "case={case}"); + } + (Some(off), Err(BsonStreamError::CorruptDocumentLength { offset, .. })) + | (Some(off), Err(BsonStreamError::TruncatedDocument { offset, .. })) => { + framing_cases += 1; + assert_eq!(offset, off, "case={case} cap={cap}"); + } + (exp, got) => panic!("case={case}: expected framing={exp:?}, got {got:?}"), + } + } + assert!(framing_cases >= 20, "framing_cases={framing_cases}"); + assert!(ok_cases >= 20, "ok_cases={ok_cases}"); + assert!(rows_seen > 1000, "rows_seen={rows_seen}"); +} + +#[test] +fn stream_handles_empty_input_oversized_docs_and_invalid_options() { + let stats = decode_eod_intraday_stream( + Cursor::new(Vec::::new()), + BsonStreamOptions::default(), + |_| panic!(), + |_, _| panic!(), + ) + .unwrap(); + assert_eq!(stats, BsonEodIntradayDecodeStats::default()); + + let first = valid_doc("NVDA.US", TS, 10.0, 1.0).into_bytes(); + let mut big = valid_doc("BIG.US", TS, 10.0, 1.0); + big.append(cstr!("pad"), "p".repeat(256).as_str()); + let mut input = first.clone(); + input.extend_from_slice(big.as_bytes()); + + let mut rows = Vec::new(); + let err = decode_eod_intraday_stream( + Cursor::new(&input), + BsonStreamOptions { chunk_capacity_bytes: 16, max_doc_bytes: 200 }, + |b| rows.push(row(b)), + |_, e| panic!("unexpected per-doc error {e:?}"), + ) + .unwrap_err(); + assert_eq!(rows.len(), 1); + assert!(matches!( + err, + BsonStreamError::CorruptDocumentLength { offset, max_doc_bytes: 200, .. } + if offset == first.len() as u64 + )); + + for (opts, want_cap) in [ + (BsonStreamOptions { chunk_capacity_bytes: 0, max_doc_bytes: 4096 }, true), + (BsonStreamOptions { chunk_capacity_bytes: 16, max_doc_bytes: 4 }, false), + ] { + let err = decode_eod_intraday_stream(Cursor::new(&input), opts, |_| {}, |_, _| {}) + .unwrap_err(); + if want_cap { + assert!(matches!(err, BsonStreamError::InvalidChunkCapacity)); + } else { + assert!(matches!(err, BsonStreamError::InvalidMaxDocBytes)); + } + } +} + +#[test] +fn utc_bar_start_micros_assign_late_et_bars_to_the_correct_session_date() { + // 2024-06-07 19:59 EDT = 2024-06-07 23:59 UTC (same UTC date) and + // 2024-06-07 20:00 EDT = 2024-06-08 00:00 UTC (next UTC date) both belong to the 06-07 + // US session; a seconds/micros unit slip would push them to 1970 or far future dates. + let late = 1_717_804_740_i64; // 2024-06-07T23:59:00Z + let after_midnight = 1_717_804_800_i64; // 2024-06-08T00:00:00Z + let mut buf = Vec::new(); + buf.extend_from_slice(valid_doc("NVDA.US", late, 120.0, 10.0).as_bytes()); + buf.extend_from_slice(valid_doc("NVDA.US", after_midnight, 120.1, 10.0).as_bytes()); + + let mut bars = Vec::new(); + decode_eod_intraday_buffer( + &buf, + |b| bars.push(b.into_eod_intraday_bar(|c, _| c.to_owned())), + |_, e| panic!("{e:?}"), + ); + let built = build_bars_1m(bars, &SplitTable::::default()); + let june7 = ymd_to_epoch_days(2024, 6, 7).unwrap(); + let dates: Vec = built.rows.iter().map(|r| r.session_date).collect(); + assert_eq!(built.rows.len(), 2); + assert_eq!(dates, vec![june7, june7]); + assert_eq!(built.rows[0].ts, late * 1_000_000); + assert_eq!(built.rows[1].ts, after_midnight * 1_000_000); +}