T-109: tests

This commit is contained in:
Studio 2026-11-29 00:07:42 -05:00
parent 000847f458
commit 38cab8b4ca

View file

@ -0,0 +1,273 @@
//! QA contract tests for the public `bson_stream` API (T-109 / M1.2y).
//!
//! Covers gaps left by `src/bson_stream_tests.rs`, using only the public crate API:
//! - seeded byte-mutation fuzz: for every mutated `eodPrices` stream the streamed decode never
//! panics, yields exactly the buffer decoder's rows and per-document errors in order, and a
//! buffer framing error maps to a stream `Err` at the same absolute offset;
//! - `RawBsonChunkReader::new` (default options) frames a multi-document stream end to end;
//! - `decode_*_chunks` resumed on a reader that already failed returns the sticky error at once;
//! - `BsonStreamError` `Display` names the offset and `source()` exposes the original I/O error;
//! - `bench-bson-stream` binary: completes on a small row count with a ratio and peak buffer
//! line, identical checksum across two runs, invalid args exit non-zero.
use std::error::Error as _;
use std::io::{self, Cursor, Read};
use std::process::{Command, Output};
use bson::raw::{cstr, RawDocumentBuf};
use curate_etl::{
decode_eod_price_buffer, decode_eod_price_chunks, decode_eod_price_stream,
decode_qm_split_chunks, BsonEodPriceError, BsonStreamError, BsonStreamOptions,
RawBsonChunkReader, DEFAULT_CHUNK_CAPACITY_BYTES,
};
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..=97 bytes.
struct JitterReader<'a> {
data: &'a [u8],
pos: usize,
rng: SplitMix64,
}
impl Read for JitterReader<'_> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let remaining = self.data.len() - self.pos;
if remaining == 0 {
return Ok(0);
}
let step = (self.rng.next_u64() % 97) 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)
}
}
/// Reader that yields its data once and then fails every subsequent read.
struct FailAfterData {
data: Vec<u8>,
pos: usize,
reads_after_fail: usize,
}
impl Read for FailAfterData {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
if self.pos == self.data.len() {
self.reads_after_fail += 1;
return Err(io::Error::new(io::ErrorKind::ConnectionReset, "cursor dropped"));
}
let take = (self.data.len() - self.pos).min(buf.len());
buf[..take].copy_from_slice(&self.data[self.pos..self.pos + take]);
self.pos += take;
Ok(take)
}
}
fn eod_doc(code: &str, day: u32, close: f64) -> Vec<u8> {
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("eodSearchCode"), code);
doc.append(cstr!("date"), format!("2024-06-{day:02}"));
doc.append(cstr!("open"), close - 0.5);
doc.append(cstr!("high"), close + 1.0);
doc.append(cstr!("low"), close - 1.0);
doc.append(cstr!("close"), close);
doc.append(cstr!("volume"), 1_000_i64 + day as i64);
doc.append(cstr!("exchange"), "TSX");
doc.into_bytes()
}
fn eod_fixture(count: usize) -> Vec<u8> {
let mut out = Vec::new();
for i in 0..count {
out.extend_from_slice(&eod_doc(&format!("Q{i:03}.TO"), 1 + (i % 28) as u32, 10.0 + i as f64));
}
out
}
type Row = (String, i32, u64, u64);
fn buffer_decode(bytes: &[u8]) -> (Vec<Row>, Vec<(u64, String)>) {
let mut rows = Vec::new();
let mut errs = Vec::new();
decode_eod_price_buffer(
bytes,
|b| rows.push((b.eod_search_code.to_owned(), b.session_date, b.close.to_bits(), b.adj_volume.to_bits())),
|off, e| errs.push((off as u64, format!("{e:?}"))),
);
(rows, errs)
}
fn is_framing_error(debug: &str) -> bool {
debug.starts_with("CorruptDocumentLength") || debug.starts_with("TruncatedDocument")
}
#[test]
fn seeded_mutation_fuzz_stream_matches_buffer_rows_errors_and_framing_offset() {
let clean = eod_fixture(24);
let mut rng = SplitMix64(0x5EED_B50E);
let mut framing_cases = 0usize;
let mut ok_cases = 0usize;
for case in 0..400u64 {
let mut bytes = clean.clone();
let flips = 1 + (rng.next_u64() % 4) as usize;
for _ in 0..flips {
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);
}
let (exp_rows, mut exp_errs) = buffer_decode(&bytes);
let exp_framing = match exp_errs.last() {
Some((off, dbg)) if is_framing_error(dbg) => {
let off = *off;
exp_errs.pop();
Some(off)
}
_ => None,
};
let cap = [1usize, 4, 37, 256, 4096][(case % 5) as usize];
let mut rows = Vec::new();
let mut errs = Vec::new();
let result = decode_eod_price_stream(
JitterReader { data: &bytes, pos: 0, rng: SplitMix64(case) },
BsonStreamOptions { chunk_capacity_bytes: cap, max_doc_bytes: 1 << 20 },
|b| rows.push((b.eod_search_code.to_owned(), b.session_date, b.close.to_bits(), b.adj_volume.to_bits())),
|off, e: BsonEodPriceError| errs.push((off, format!("{e:?}"))),
);
assert_eq!(rows, exp_rows, "case={case} cap={cap}: rows diverge");
assert_eq!(errs, exp_errs, "case={case} cap={cap}: per-doc errors diverge");
match (exp_framing, result) {
(None, Ok(stats)) => {
ok_cases += 1;
assert_eq!(stats.decoded, exp_rows.len(), "case={case}");
assert_eq!(stats.decoded + stats.rejected_total(), stats.docs_in, "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}: framing offset");
}
(exp, got) => panic!("case={case} cap={cap}: expected framing={exp:?}, got {got:?}"),
}
}
// The sweep must exercise both outcomes, or it proves nothing.
assert!(framing_cases >= 20, "framing_cases={framing_cases}");
assert!(ok_cases >= 20, "ok_cases={ok_cases}");
}
#[test]
fn default_reader_frames_whole_stream_with_default_capacity() {
let input = eod_fixture(50);
let mut reader = RawBsonChunkReader::new(JitterReader { data: &input, pos: 0, rng: SplitMix64(7) });
let mut joined = Vec::new();
while let Some(chunk) = reader.next_chunk().expect("valid stream") {
assert_eq!(chunk.start_offset, joined.len() as u64);
joined.extend_from_slice(chunk.bytes);
}
assert_eq!(joined, input);
assert_eq!(reader.docs_framed(), 50);
assert_eq!(reader.bytes_read(), input.len() as u64);
assert_eq!(reader.buffer_capacity(), DEFAULT_CHUNK_CAPACITY_BYTES);
}
#[test]
fn chunk_helpers_on_failed_reader_return_sticky_error_without_rereading() {
let input = eod_fixture(3);
let len = input.len() as u64;
let mut reader = RawBsonChunkReader::with_options(
FailAfterData { data: input, pos: 0, reads_after_fail: 0 },
BsonStreamOptions { chunk_capacity_bytes: 64, max_doc_bytes: 4096 },
)
.unwrap();
let mut bars = 0usize;
let err = decode_eod_price_chunks(&mut reader, |_| bars += 1, |_, _| panic!("no per-doc errors"))
.expect_err("I/O failure must surface");
assert_eq!(bars, 3, "all complete docs delivered before the I/O error");
let BsonStreamError::Io { offset, ref source } = err else { panic!("expected Io, got {err:?}") };
assert_eq!(offset, len);
assert_eq!(source.kind(), io::ErrorKind::ConnectionReset);
// A different helper resumed on the same failed reader must fail immediately.
let again = decode_qm_split_chunks(&mut reader, |_| panic!("no rows"), |_, _| panic!("no errors"))
.expect_err("sticky error");
assert!(matches!(again, BsonStreamError::Io { offset, .. } if offset == len));
assert_eq!(reader.into_inner().reads_after_fail, 1, "source read exactly once after data");
}
#[test]
fn error_display_names_offset_and_io_source_is_exposed() {
let mut bytes = eod_doc("A.TO", 3, 5.0);
let first_len = bytes.len();
bytes.extend_from_slice(&2_i32.to_le_bytes());
let err = decode_eod_price_stream(Cursor::new(bytes), BsonStreamOptions::default(), |_| {}, |_, _| {})
.expect_err("corrupt length");
assert!(err.source().is_none());
let text = err.to_string();
assert!(text.contains(&format!("offset {first_len}")), "{text}");
assert!(text.contains("length 2"), "{text}");
let io_err = decode_eod_price_stream(
FailAfterData { data: Vec::new(), pos: 0, reads_after_fail: 0 },
BsonStreamOptions::default(),
|_| {},
|_, _| {},
)
.expect_err("io");
let src = io_err.source().expect("Io exposes source");
assert!(src.to_string().contains("cursor dropped"), "{src}");
assert!(io_err.to_string().contains("offset 0"), "{io_err}");
assert!(BsonStreamError::InvalidChunkCapacity.to_string().contains("chunk_capacity_bytes"));
assert!(BsonStreamError::InvalidMaxDocBytes.to_string().contains("max_doc_bytes"));
}
fn run_bin(args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_curate-etl"))
.args(args)
.output()
.expect("spawn curate-etl binary")
}
fn checksum_of(out: &Output) -> String {
let text = String::from_utf8_lossy(&out.stdout);
text.split_whitespace()
.find(|t| t.starts_with("checksum=0x"))
.unwrap_or_else(|| panic!("no checksum in output: {text}"))
.to_owned()
}
#[test]
fn bench_bson_stream_binary_is_deterministic_and_rejects_bad_args() {
let a = run_bin(&["bench-bson-stream", "5000"]);
let b = run_bin(&["bench-bson-stream", "5000"]);
assert!(a.status.success(), "stderr: {}", String::from_utf8_lossy(&a.stderr));
assert!(b.status.success());
assert_eq!(checksum_of(&a), checksum_of(&b));
let text = String::from_utf8_lossy(&a.stdout).to_lowercase();
assert!(text.contains("rows=5000"), "{text}");
assert!(text.contains("ratio"), "{text}");
assert!(text.contains("peak_buffer_capacity"), "{text}");
for bad in [&["bench-bson-stream", "abc"][..], &["bench-bson-stream", "1", "2"][..]] {
let out = run_bin(bad);
assert!(!out.status.success(), "args {bad:?} must fail");
}
}