T-109: M1.2y — tools/curate-etl: bounded-memory streaming reader for concatenated raw BSON (impl Read → whole-document chunks → existing eodPrices / qmSplits / qmDividends decoders) with tests and local benchmark (no new crates, no MongoDB connection)

This commit is contained in:
Studio 2026-11-28 23:54:58 -05:00
parent 5131c2525f
commit c57ca3201c
2 changed files with 190 additions and 43 deletions

View file

@ -39,7 +39,7 @@ pub const MIN_BSON_DOC_BYTES: usize = 5;
/// Configuration options for [`RawBsonChunkReader`] and the `decode_*_stream` helpers.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BsonStreamOptions {
/// Initial reusable buffer size in bytes. Must be `> 0`.
/// Initial reusable buffer size in bytes (capped at `max_doc_bytes`). Must be `> 0`.
pub chunk_capacity_bytes: usize,
/// Hard upper bound on any single BSON document's declared byte length. Must be `>= 5`.
pub max_doc_bytes: usize,
@ -224,8 +224,9 @@ fn read_i32_le(bytes: &[u8]) -> i32 {
/// Bounded-memory chunked reader for concatenated length-prefixed raw BSON documents.
///
/// Reuses a single internal byte buffer across all calls to [`Self::next_chunk`], carrying any
/// trailing partial document to the front of the buffer before the next fill. The buffer grows
/// only when a single document exceeds the current buffer length (or to 4 bytes when
/// trailing partial document to the front of the buffer before the next fill. The initial
/// allocation is capped at `min(options.chunk_capacity_bytes, options.max_doc_bytes)`; the buffer
/// grows only when a single document exceeds the current buffer length (or to 4 bytes when
/// `chunk_capacity_bytes < 4`), and never beyond `options.max_doc_bytes`.
pub struct RawBsonChunkReader<R: io::Read> {
reader: R,
@ -245,10 +246,11 @@ impl<R: io::Read> RawBsonChunkReader<R> {
/// Creates a new chunk reader with [`BsonStreamOptions::default`].
pub fn new(reader: R) -> Self {
let options = BsonStreamOptions::default();
let initial_cap = options.chunk_capacity_bytes.min(options.max_doc_bytes);
Self {
reader,
options,
buf: vec![0u8; options.chunk_capacity_bytes],
buf: vec![0u8; initial_cap],
filled: 0,
consumed: 0,
buf_start_offset: 0,
@ -263,10 +265,11 @@ impl<R: io::Read> RawBsonChunkReader<R> {
/// Creates a new chunk reader with explicit [`BsonStreamOptions`], validating them up front.
pub fn with_options(reader: R, options: BsonStreamOptions) -> Result<Self, BsonStreamError> {
options.validate()?;
let initial_cap = options.chunk_capacity_bytes.min(options.max_doc_bytes);
Ok(Self {
reader,
options,
buf: vec![0u8; options.chunk_capacity_bytes],
buf: vec![0u8; initial_cap],
filled: 0,
consumed: 0,
buf_start_offset: 0,
@ -340,32 +343,47 @@ impl<R: io::Read> RawBsonChunkReader<R> {
self.consumed = 0;
}
let mut first_doc_len_checked = false;
let mut chunk_end = 0usize;
let mut chunk_docs = 0u64;
loop {
// Inspect the leading 4-byte length prefix as soon as it is buffered so an already-
// buffered corrupt length fails immediately without extra I/O, and oversized single
// documents grow the buffer before filling.
if !first_doc_len_checked && self.filled >= 4 {
let declared_len = read_i32_le(&self.buf[0..4]);
// Incrementally frame complete documents as bytes arrive so a corrupt length prefix
// stops the fill loop immediately without issuing further reads.
let mut saw_corrupt_len = false;
while self.filled - chunk_end >= 4 {
let declared_len = read_i32_le(&self.buf[chunk_end..chunk_end + 4]);
if declared_len < MIN_BSON_DOC_BYTES as i32
|| (declared_len as usize) > self.options.max_doc_bytes
{
let err = StickyError::CorruptDocumentLength {
offset: self.buf_start_offset,
declared_len,
max_doc_bytes: self.options.max_doc_bytes,
};
self.terminal = TerminalState::Failed(err.clone());
return Err(err.to_error());
if chunk_end == 0 {
let err = StickyError::CorruptDocumentLength {
offset: self.buf_start_offset,
declared_len,
max_doc_bytes: self.options.max_doc_bytes,
};
self.terminal = TerminalState::Failed(err.clone());
return Err(err.to_error());
}
// Yield any complete preceding documents first; the next call will compact
// this corrupt header to index 0 and surface `CorruptDocumentLength`.
saw_corrupt_len = true;
break;
}
let doc_len = declared_len as usize;
if doc_len > self.buf.len() {
if chunk_end == 0
&& doc_len > self.buf.len()
&& !self.eof_reached
&& self.pending_io_err.is_none()
{
self.grow_buf_exact(doc_len);
}
first_doc_len_checked = true;
if doc_len > self.filled - chunk_end {
break;
}
chunk_end += doc_len;
chunk_docs += 1;
}
if self.eof_reached || self.pending_io_err.is_some() {
if saw_corrupt_len || self.eof_reached || self.pending_io_err.is_some() {
break;
}
@ -374,8 +392,8 @@ impl<R: io::Read> RawBsonChunkReader<R> {
// `chunk_capacity_bytes` was in `1..=3`; grow to 4 bytes (always <= max_doc_bytes).
self.grow_buf_exact(4);
} else {
// Buffer is full and `first_doc_len <= self.buf.len() == self.filled`, so at
// least one complete document is ready to yield.
// Buffer is full and the leading document fit in `self.buf.len()`, so at least
// one complete document is ready to yield.
break;
}
}
@ -397,26 +415,6 @@ impl<R: io::Read> RawBsonChunkReader<R> {
}
}
// Frame as many complete length-prefixed documents as are buffered.
let mut chunk_end = 0usize;
let mut chunk_docs = 0u64;
while self.filled - chunk_end >= 4 {
let declared_len = read_i32_le(&self.buf[chunk_end..chunk_end + 4]);
if declared_len < MIN_BSON_DOC_BYTES as i32
|| (declared_len as usize) > self.options.max_doc_bytes
{
// Yield any complete preceding documents first; the next call will compact this
// corrupt header to index 0 and surface `CorruptDocumentLength`.
break;
}
let doc_len = declared_len as usize;
if doc_len > self.filled - chunk_end {
break;
}
chunk_end += doc_len;
chunk_docs += 1;
}
if chunk_end > 0 {
self.consumed = chunk_end;
self.docs_framed += chunk_docs;

View file

@ -1103,3 +1103,152 @@ fn stats_merge_and_add_assign_sum_all_fields() {
assert_eq!(q_acc.rejected_total(), 12);
assert_eq!(q_acc.decoded + q_acc.rejected_total(), q_acc.docs_in);
}
#[test]
fn initial_allocation_is_capped_at_max_doc_bytes() {
let max_doc = 1024 * 1024;
let empty_reader = RawBsonChunkReader::with_options(
Cursor::new(&[][..]),
BsonStreamOptions {
chunk_capacity_bytes: DEFAULT_CHUNK_CAPACITY_BYTES,
max_doc_bytes: max_doc,
},
)
.expect("chunk_capacity_bytes > max_doc_bytes must succeed with capped buffer");
assert!(
empty_reader.buffer_capacity() <= max_doc,
"initial capacity {} exceeded max_doc_bytes {max_doc}",
empty_reader.buffer_capacity()
);
assert_eq!(empty_reader.buffer_capacity(), max_doc);
// Also verify streaming valid docs when chunk_capacity_bytes > max_doc_bytes.
let doc = make_eod_doc("CAP.US", "2024-06-10", 10.0, 11.0, 9.0, 10.5, 100);
let mut input = Vec::new();
for _ in 0..8 {
input.extend_from_slice(&doc);
}
let small_max = 256usize;
assert!(doc.len() < small_max);
let mut reader = RawBsonChunkReader::with_options(
FixedStepReader::new(&input, 37),
BsonStreamOptions {
chunk_capacity_bytes: 4096,
max_doc_bytes: small_max,
},
)
.unwrap();
assert_eq!(reader.buffer_capacity(), small_max);
let mut reconstructed = Vec::new();
while let Some(chunk) = reader.next_chunk().unwrap() {
reconstructed.extend_from_slice(chunk.bytes);
assert!(reader.buffer_capacity() <= small_max);
}
assert_eq!(reconstructed, input);
assert_eq!(reader.docs_framed(), 8);
assert!(reader.buffer_capacity() <= small_max);
}
#[test]
fn corrupt_header_after_valid_doc_stops_fill_without_extra_read() {
struct ScriptedReader {
chunks: Vec<Vec<u8>>,
idx: usize,
read_calls: usize,
}
impl Read for ScriptedReader {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.read_calls += 1;
if self.idx >= self.chunks.len() {
panic!(
"unexpected extra read #{} after supplying scripted chunks",
self.read_calls
);
}
let src = &self.chunks[self.idx];
assert!(
src.len() <= buf.len(),
"scripted chunk ({}) exceeds caller buffer ({})",
src.len(),
buf.len()
);
buf[..src.len()].copy_from_slice(src);
self.idx += 1;
Ok(src.len())
}
}
let valid_doc = make_eod_doc("PIPE.US", "2024-06-10", 10.0, 11.0, 9.0, 10.5, 100);
let prefix_len = valid_doc.len() as u64;
let bad_len = 0_i32;
// Case 1: single short read supplies both the valid doc and the corrupt 4-byte header.
let mut single_packet = valid_doc.clone();
single_packet.extend_from_slice(&bad_len.to_le_bytes());
let mut reader = RawBsonChunkReader::with_options(
ScriptedReader {
chunks: vec![single_packet],
idx: 0,
read_calls: 0,
},
BsonStreamOptions {
chunk_capacity_bytes: 4096,
max_doc_bytes: 4096,
},
)
.unwrap();
let chunk = reader
.next_chunk()
.expect("valid prefix must be yielded immediately")
.expect("expected valid prefix chunk");
assert_eq!(chunk.start_offset, 0);
assert_eq!(chunk.bytes, valid_doc.as_slice());
let err = reader.next_chunk().unwrap_err();
assert!(matches!(
err,
BsonStreamError::CorruptDocumentLength {
offset,
declared_len,
max_doc_bytes: 4096,
} if offset == prefix_len && declared_len == bad_len
));
assert_eq!(reader.into_inner().read_calls, 1);
// Case 2: corrupt header split across two short reads; stops immediately once 4 bytes arrive.
let mut part1 = valid_doc.clone();
let bad_bytes = (-42_i32).to_le_bytes();
part1.extend_from_slice(&bad_bytes[..2]);
let part2 = bad_bytes[2..].to_vec();
let mut split_reader = RawBsonChunkReader::with_options(
ScriptedReader {
chunks: vec![part1, part2],
idx: 0,
read_calls: 0,
},
BsonStreamOptions {
chunk_capacity_bytes: 4096,
max_doc_bytes: 4096,
},
)
.unwrap();
let chunk = split_reader.next_chunk().unwrap().unwrap();
assert_eq!(chunk.bytes, valid_doc.as_slice());
let err = split_reader.next_chunk().unwrap_err();
assert!(matches!(
err,
BsonStreamError::CorruptDocumentLength {
offset,
declared_len: -42,
max_doc_bytes: 4096,
} if offset == prefix_len
));
assert_eq!(split_reader.into_inner().read_calls, 2);
}