T-126: M1.2al — tools/curate-etl: sealed read-only MongoDB raw-BSON cursor adapter (mongo_stream.rs: ValidatedReadOnlyMongoUri → allowlisted find → impl io::Read feeding the existing bson_stream decoders) with offline tests and local benchmark (adds the mongodb crate only; no live MongoDB in tests)

This commit is contained in:
Studio 2026-11-30 02:22:06 -05:00
parent 97fad30fd0
commit be144d874a
5 changed files with 259 additions and 34 deletions

View file

@ -1531,9 +1531,9 @@ Library-only, driver-independent read-only MongoDB raw-BSON cursor seam (`src/mo
### Public API & Sealing Guarantees
- **Closed collection allowlist (`SourceCollection`):** 8 variants matching `RAW_BSON_EXPORT_COLLECTIONS` in `apps/stock/data-pipeline/src/security-master/export-raw-bson.ts` in exact order (`eodPrices`, `qmSplits`, `qmDividends`, `qmPrices`, `teMarketData`, `ceoShorts`, `qmFilings`, `qmEarnings`). No API accepts a free-form collection name string.
- **Typed read spec (`MongoReadSpec`, `MongoDateRange`, `FilterDateValue`, `build_filter_document`):** validates `batch_size` (`1..=100_000`, default `4_096`), `limit` (`1..=i64::MAX`), `max_doc_bytes` (`>= 5`, default `16 MiB + 16 KiB`), non-blank `key_eq`, and half-open `[gte, lt)` `date_range` (rejected on `teMarketData`), building `bson::Document` via `Document::from_iter(...)`.
- **Typed read spec (`MongoReadSpec`, `MongoDateRange`, `FilterDateValue`, `build_filter_document`):** validates `batch_size` (`1..=100_000`, default `4_096`), `limit` (`1..=i64::MAX`), `max_doc_bytes` (`>= 5`, default `16 MiB + 16 KiB`), non-blank `key_eq`, and half-open `[gte, lt)` `date_range` (rejected on `teMarketData`; `qmFilings.timefiled` bounds require Eastern Time `YYYY-MM-DDTHH:MM:SS EST|EDT` strings validated via `parse_filing_timefiled` so UTC bounds cannot silently miss late-evening ET filings), building `bson::Document` via `Document::from_iter(...)`.
- **Driver-independent seam (`RawDocumentSource`, `SliceRawDocumentSource`, `VecRawDocumentSource`) + bounded-memory `io::Read` adapter (`RawBsonCursorReader<S>`):** validates every raw BSON frame (`len >= 5`, `len <= max_doc_bytes`, 4-byte LE length prefix `== len`, trailing `0x00`), copies directly into the caller's buffer when it fits, spills only the unread tail of a single current document into a reused `pending` buffer, tracks `docs_read()` / `bytes_read()` / `pending_capacity()`, and surfaces mid-stream errors as sticky `io::Error`s carrying `MongoStreamError`.
- **Error redaction (`MongoStreamError`, `MongoStreamError::redacted_source`):** never stores raw URIs or passwords; sanitizes raw URI, raw password, percent-decoded password, and embedded `mongodb://` / `mongodb+srv://` userinfo passwords to `[REDACTED]` (reusing `mongo_safety::redact_mongo_uri_password`).
- **Error redaction (`MongoStreamError`, `MongoStreamError::redacted_source`):** never stores raw URIs or passwords; sanitizes raw URI, raw password, percent-decoded password, and embedded `mongodb://` / `mongodb+srv://` userinfo passwords (including passwords containing punctuation such as `,`, `;`, quotes, brackets, or `@`) to `[REDACTED]` (reusing `mongo_safety::redact_mongo_uri_password`).
### `bench-mongo-stream`
@ -1545,8 +1545,8 @@ cargo run -p curate-etl --release --offline -- bench-mongo-stream 1000000
Measured locally (`2026-11-30`, two back-to-back offline runs on the final code with identical stats `decoded=995008`, `rejected=4992`, and checksum `0x05af9d2746d1b5e3`):
- **Run 1:** plain `273.98 ms` (`3,649,838 docs/s`, `994.24 MB/s`) vs. `RawBsonCursorReader` `275.41 ms` (`3,630,978 docs/s`, `989.10 MB/s`, ratio `0.995x`, `peak_pending_capacity=271 bytes`)
- **Run 2:** plain `265.00 ms` (`3,773,617 docs/s`, `1,027.96 MB/s`) vs. `RawBsonCursorReader` `270.05 ms` (`3,703,016 docs/s`, `1,008.73 MB/s`, ratio `0.981x`, `peak_pending_capacity=271 bytes`)
- **Run 1:** plain `264.49 ms` (`3,780,816 docs/s`, `1,029.92 MiB/s`) vs. `RawBsonCursorReader` `263.32 ms` (`3,797,634 docs/s`, `1,034.50 MiB/s`, ratio `1.004x`, `peak_pending_capacity=271 bytes`)
- **Run 2:** plain `281.99 ms` (`3,546,241 docs/s`, `966.02 MiB/s`) vs. `RawBsonCursorReader` `270.90 ms` (`3,691,390 docs/s`, `1,005.56 MiB/s`, ratio `1.041x`, `peak_pending_capacity=271 bytes`)
### Not Done / Not Verified

View file

@ -4002,10 +4002,10 @@ pub struct MongoStreamBenchReport {
pub bytes: usize,
pub plain_elapsed_ms: f64,
pub plain_docs_per_sec: f64,
pub plain_mb_per_sec: f64,
pub plain_mib_per_sec: f64,
pub cursor_elapsed_ms: f64,
pub cursor_docs_per_sec: f64,
pub cursor_mb_per_sec: f64,
pub cursor_mib_per_sec: f64,
pub cursor_to_plain_ratio: f64,
pub peak_pending_capacity: usize,
pub checksum: u64,
@ -4021,10 +4021,10 @@ pub fn run_mongo_stream_benchmark(rows: usize) -> Result<MongoStreamBenchReport,
bytes: 0,
plain_elapsed_ms: 0.0,
plain_docs_per_sec: 0.0,
plain_mb_per_sec: 0.0,
plain_mib_per_sec: 0.0,
cursor_elapsed_ms: 0.0,
cursor_docs_per_sec: 0.0,
cursor_mb_per_sec: 0.0,
cursor_mib_per_sec: 0.0,
cursor_to_plain_ratio: 0.0,
peak_pending_capacity: 0,
checksum: 0,
@ -4103,7 +4103,7 @@ pub fn run_mongo_stream_benchmark(rows: usize) -> Result<MongoStreamBenchReport,
let plain_elapsed_ms = plain_elapsed_secs * 1_000.0;
let (plain_docs_per_sec, _) = compute_rates(rows, plain_elapsed_secs);
let plain_mb_per_sec = if plain_elapsed_secs > 0.0 && plain_elapsed_secs.is_finite() {
let plain_mib_per_sec = if plain_elapsed_secs > 0.0 && plain_elapsed_secs.is_finite() {
(bytes as f64 / (1024.0 * 1024.0)) / plain_elapsed_secs
} else {
0.0
@ -4111,7 +4111,7 @@ pub fn run_mongo_stream_benchmark(rows: usize) -> Result<MongoStreamBenchReport,
let cursor_elapsed_ms = cursor_elapsed_secs * 1_000.0;
let (cursor_docs_per_sec, _) = compute_rates(rows, cursor_elapsed_secs);
let cursor_mb_per_sec = if cursor_elapsed_secs > 0.0 && cursor_elapsed_secs.is_finite() {
let cursor_mib_per_sec = if cursor_elapsed_secs > 0.0 && cursor_elapsed_secs.is_finite() {
(bytes as f64 / (1024.0 * 1024.0)) / cursor_elapsed_secs
} else {
0.0
@ -4128,10 +4128,10 @@ pub fn run_mongo_stream_benchmark(rows: usize) -> Result<MongoStreamBenchReport,
bytes,
plain_elapsed_ms,
plain_docs_per_sec,
plain_mb_per_sec,
plain_mib_per_sec,
cursor_elapsed_ms,
cursor_docs_per_sec,
cursor_mb_per_sec,
cursor_mib_per_sec,
cursor_to_plain_ratio,
peak_pending_capacity,
checksum: cursor_checksum,

View file

@ -680,14 +680,14 @@ fn main() -> ExitCode {
report.checksum
);
println!(
" plain: elapsed={:.2} ms throughput={:.0} docs/s scan={:.2} MB/s",
report.plain_elapsed_ms, report.plain_docs_per_sec, report.plain_mb_per_sec
" plain: elapsed={:.2} ms throughput={:.0} docs/s scan={:.2} MiB/s",
report.plain_elapsed_ms, report.plain_docs_per_sec, report.plain_mib_per_sec
);
println!(
" cursor: elapsed={:.2} ms throughput={:.0} docs/s scan={:.2} MB/s ratio={:.3}x peak_pending_capacity={} bytes",
" cursor: elapsed={:.2} ms throughput={:.0} docs/s scan={:.2} MiB/s ratio={:.3}x peak_pending_capacity={} bytes",
report.cursor_elapsed_ms,
report.cursor_docs_per_sec,
report.cursor_mb_per_sec,
report.cursor_mib_per_sec,
report.cursor_to_plain_ratio,
report.peak_pending_capacity
);

View file

@ -23,6 +23,7 @@ use std::io;
use bson::{Bson, DateTime, Document};
use crate::bson_stream::{DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES};
use crate::events::parse_filing_timefiled;
use crate::mongo_safety::{redact_mongo_uri_password, ValidatedReadOnlyMongoUri};
/// Default MongoDB cursor batch size (matches `DEFAULT_RAW_BSON_BATCH_SIZE`).
@ -213,6 +214,63 @@ impl MongoReadSpec {
});
}
}
if collection == SourceCollection::QmFilings {
let gte_parsed = match &range.gte {
Some(FilterDateValue::IsoString(s)) => {
Some(parse_filing_timefiled(s).map_err(|err| {
MongoStreamError::InvalidDateRange {
collection,
detail: format!(
"qmFilings.timefiled gte must be an Eastern Time timestamp \
(YYYY-MM-DDTHH:MM:SS EST|EDT): {err}"
),
}
})?)
}
Some(FilterDateValue::BsonDateTimeMillis(_)) => {
return Err(MongoStreamError::InvalidDateRange {
collection,
detail: "qmFilings.timefiled is stored as an Eastern Time string \
(YYYY-MM-DDTHH:MM:SS EST|EDT); BsonDateTimeMillis bounds \
are not supported"
.to_owned(),
});
}
None => None,
};
let lt_parsed = match &range.lt {
Some(FilterDateValue::IsoString(s)) => {
Some(parse_filing_timefiled(s).map_err(|err| {
MongoStreamError::InvalidDateRange {
collection,
detail: format!(
"qmFilings.timefiled lt must be an Eastern Time timestamp \
(YYYY-MM-DDTHH:MM:SS EST|EDT): {err}"
),
}
})?)
}
Some(FilterDateValue::BsonDateTimeMillis(_)) => {
return Err(MongoStreamError::InvalidDateRange {
collection,
detail: "qmFilings.timefiled is stored as an Eastern Time string \
(YYYY-MM-DDTHH:MM:SS EST|EDT); BsonDateTimeMillis bounds \
are not supported"
.to_owned(),
});
}
None => None,
};
if let (Some(a), Some(b)) = (gte_parsed, lt_parsed) {
if a.utc_micros >= b.utc_micros {
return Err(MongoStreamError::InvalidDateRange {
collection,
detail: "qmFilings.timefiled gte must precede lt in UTC time"
.to_owned(),
});
}
}
}
if let (Some(gte), Some(lt)) = (&range.gte, &range.lt) {
match (gte, lt) {
(FilterDateValue::IsoString(a), FilterDateValue::IsoString(b)) => {
@ -681,15 +739,17 @@ fn redact_embedded_mongo_uris(text: &str) -> String {
while cursor < text.len() {
let rem = &lower[cursor..];
let next_std = rem.find("mongodb://");
let next_srv = rem.find("mongodb+srv://");
let next_std = rem.find("mongodb://").map(|i| (i, "mongodb://".len()));
let next_srv = rem
.find("mongodb+srv://")
.map(|i| (i, "mongodb+srv://".len()));
let next = match (next_std, next_srv) {
(Some(a), Some(b)) => Some(a.min(b)),
(Some(a), Some(b)) => Some(if a.0 <= b.0 { a } else { b }),
(Some(a), None) => Some(a),
(None, Some(b)) => Some(b),
(None, None) => None,
};
let Some(rel_start) = next else {
let Some((rel_start, scheme_len)) = next else {
result.push_str(&text[cursor..]);
break;
};
@ -698,14 +758,33 @@ fn redact_embedded_mongo_uris(text: &str) -> String {
result.push_str(&text[cursor..start]);
let tail = &text[start..];
let uri_len = tail
.find(|c: char| {
c.is_whitespace() || matches!(c, '"' | '\'' | ')' | ']' | '}' | ',' | ';')
})
.unwrap_or(tail.len());
let candidate = &tail[..uri_len];
result.push_str(&redact_mongo_uri_password(candidate));
cursor = start + uri_len;
let after_scheme = &tail[scheme_len..];
// Authority ends at `/`, `?`, or whitespace. Do not stop on punctuation
// such as `,`, `;`, `)`, `]`, `}`, `"`, `'` before locating `@`, because
// embedded passwords (or replica-set host lists) may contain them.
let authority_end = after_scheme
.find(|c: char| c.is_whitespace() || matches!(c, '/' | '?'))
.unwrap_or(after_scheme.len());
let authority_region = &after_scheme[..authority_end];
if let Some(at_idx) = authority_region.rfind('@') {
let userinfo = &authority_region[..at_idx];
if let Some(colon_idx) = userinfo.find(':') {
let prefix_with_at = &tail[..scheme_len + at_idx + 1];
if !userinfo.contains('@') {
result.push_str(&redact_mongo_uri_password(prefix_with_at));
} else {
result.push_str(&tail[..scheme_len + colon_idx + 1]);
result.push_str("[REDACTED]@");
}
cursor = start + scheme_len + at_idx + 1;
continue;
}
}
let advance = scheme_len + authority_end;
result.push_str(&tail[..advance]);
cursor = start + advance;
}
result

View file

@ -48,7 +48,7 @@ fn build_qm_split_doc(code: &str, date: &str, ratio: f64) -> Vec<u8> {
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("qmSearchCode"), code);
doc.append(cstr!("date"), date);
doc.append(cstr!("splitRatio"), ratio);
doc.append(cstr!("splitratio"), ratio);
doc.into_bytes()
}
@ -56,7 +56,7 @@ fn build_qm_split_reject_doc(code: &str) -> Vec<u8> {
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("qmSearchCode"), code);
doc.append(cstr!("date"), "2024-06-10");
doc.append(cstr!("splitRatio"), "bad-type");
doc.append(cstr!("splitratio"), "bad-type");
doc.into_bytes()
}
@ -64,8 +64,8 @@ fn build_qm_dividend_doc(code: &str, date: &str, cash: f64, currency: &str) -> V
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("qmSearchCode"), code);
doc.append(cstr!("date"), date);
doc.append(cstr!("dividendCash"), cash);
doc.append(cstr!("dividendCurrency"), currency);
doc.append(cstr!("amount"), cash);
doc.append(cstr!("currency"), currency);
doc.into_bytes()
}
@ -73,8 +73,8 @@ fn build_qm_dividend_reject_doc(code: &str) -> Vec<u8> {
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("qmSearchCode"), code);
doc.append(cstr!("date"), "2024-06-10");
doc.append(cstr!("dividendCash"), -1.0);
doc.append(cstr!("dividendCurrency"), "USD");
doc.append(cstr!("amount"), -1.0);
doc.append(cstr!("currency"), "USD");
doc.into_bytes()
}
@ -270,6 +270,10 @@ fn parity_eod_prices_stream_across_default_and_odd_buffers() {
|offset, err| expected_errs.push((offset, err)),
)
.expect("baseline cursor decode must succeed");
assert_eq!(expected_rows.len(), 3, "baseline eodPrices must decode 3 valid rows");
assert_eq!(expected_errs.len(), 1, "baseline eodPrices must reject 1 invalid doc");
assert_eq!(expected_stats.decoded, 3);
assert_eq!(expected_stats.rejected_total(), 1);
for step in [usize::MAX, 1, 3, 7, 13, 37] {
let mut cursor_reader = RawBsonCursorReader::new(VecRawDocumentSource::new(docs.clone()));
@ -346,6 +350,10 @@ fn parity_qm_splits_stream_across_default_and_odd_buffers() {
|offset, err| expected_errs.push((offset, err)),
)
.expect("baseline qmSplits decode must succeed");
assert_eq!(expected_rows.len(), 2, "baseline qmSplits must decode 2 valid rows");
assert_eq!(expected_errs.len(), 1, "baseline qmSplits must reject 1 invalid doc");
assert_eq!(expected_stats.decoded, 2);
assert_eq!(expected_stats.rejected_total(), 1);
for step in [usize::MAX, 1, 3, 7, 13, 37] {
let mut cursor_reader = RawBsonCursorReader::new(VecRawDocumentSource::new(docs.clone()));
@ -417,6 +425,10 @@ fn parity_qm_dividends_stream_across_default_and_odd_buffers() {
|offset, err| expected_errs.push((offset, err)),
)
.expect("baseline qmDividends decode must succeed");
assert_eq!(expected_rows.len(), 2, "baseline qmDividends must decode 2 valid rows");
assert_eq!(expected_errs.len(), 1, "baseline qmDividends must reject 1 invalid doc");
assert_eq!(expected_stats.decoded, 2);
assert_eq!(expected_stats.rejected_total(), 1);
for step in [usize::MAX, 1, 3, 7, 13, 37] {
let mut cursor_reader = RawBsonCursorReader::new(VecRawDocumentSource::new(docs.clone()));
@ -496,6 +508,9 @@ fn parity_qm_filings_stream_across_default_and_odd_buffers() {
},
)
.expect("baseline qmFilings decode must succeed");
assert_eq!(expected_rows.len(), 2, "baseline qmFilings must decode 2 valid rows");
assert_eq!(expected_stats.rows_out, 2);
assert_eq!(expected_stats.skipped_total(), 1);
for step in [usize::MAX, 1, 3, 7, 13, 37] {
let mut cursor_reader = RawBsonCursorReader::new(VecRawDocumentSource::new(docs.clone()));
@ -932,6 +947,89 @@ fn build_filter_document_and_spec_validation() {
));
}
#[test]
fn qm_filings_date_range_requires_eastern_time_and_handles_et_utc_date_boundary() {
// UTC ISO string must be rejected: a filing stored as "2024-12-31T21:30:00 EST"
// (= 2025-01-01T02:30:00Z) would lexicographically sort before "2025-01-01T00:00:00Z".
assert!(matches!(
build_filter_document(
SourceCollection::QmFilings,
&MongoReadSpec {
date_range: Some(MongoDateRange {
gte: Some(FilterDateValue::IsoString("2025-01-01T00:00:00Z".to_owned())),
lt: Some(FilterDateValue::IsoString("2025-01-02T00:00:00Z".to_owned())),
}),
..MongoReadSpec::default()
}
),
Err(MongoStreamError::InvalidDateRange {
collection: SourceCollection::QmFilings,
..
})
));
// Bare YYYY-MM-DD and BsonDateTimeMillis bounds must also be rejected for qmFilings.
assert!(matches!(
build_filter_document(
SourceCollection::QmFilings,
&MongoReadSpec {
date_range: Some(MongoDateRange {
gte: Some(FilterDateValue::IsoString("2025-01-01".to_owned())),
lt: None,
}),
..MongoReadSpec::default()
}
),
Err(MongoStreamError::InvalidDateRange {
collection: SourceCollection::QmFilings,
..
})
));
assert!(matches!(
build_filter_document(
SourceCollection::QmFilings,
&MongoReadSpec {
date_range: Some(MongoDateRange {
gte: Some(FilterDateValue::BsonDateTimeMillis(1_735_689_600_000)),
lt: None,
}),
..MongoReadSpec::default()
}
),
Err(MongoStreamError::InvalidDateRange {
collection: SourceCollection::QmFilings,
..
})
));
// Valid Eastern Time bounds spanning the UTC 2025-01-01 midnight boundary:
// 2025-01-01T00:00:00Z == 2024-12-31T19:00:00 EST.
let gte_et = "2024-12-31T19:00:00 EST";
let lt_et = "2025-01-01T19:00:00 EST";
let filing_across_boundary = "2024-12-31T21:30:00 EST"; // 2025-01-01T02:30:00Z
let filter = build_filter_document(
SourceCollection::QmFilings,
&MongoReadSpec {
date_range: Some(MongoDateRange {
gte: Some(FilterDateValue::IsoString(gte_et.to_owned())),
lt: Some(FilterDateValue::IsoString(lt_et.to_owned())),
}),
..MongoReadSpec::default()
},
)
.expect("valid Eastern Time bounds for qmFilings must succeed");
let tf = filter
.get_document("timefiled")
.expect("timefiled range subdocument must exist");
assert_eq!(tf.get("$gte"), Some(&Bson::String(gte_et.to_owned())));
assert_eq!(tf.get("$lt"), Some(&Bson::String(lt_et.to_owned())));
assert!(
filing_across_boundary >= gte_et && filing_across_boundary < lt_et,
"filing {filing_across_boundary} must fall inside [{gte_et}, {lt_et})"
);
}
// ---------------------------------------------------------------------------
// 5. Password redaction (plain and percent-encoded sentinel passwords)
// ---------------------------------------------------------------------------
@ -992,6 +1090,54 @@ fn error_display_and_debug_never_leak_plain_or_percent_encoded_passwords() {
assert!(enc_display.contains("[REDACTED]"));
}
#[test]
fn error_redaction_covers_distinct_secondary_uri_passwords_with_punctuation() {
let primary_uri = validate_uri(
"mongodb://studio_stock_bot_read:PRIMARY_PASS_111@localhost:27017/stock?authSource=stock",
);
let secondary_pass_comma = "SEC_ALPHA,BETA;GAMMA)DELTA";
let secondary_pass_srv = "SRV_PASS\"QUOTE]BRACKET@AT";
let diagnostic = format!(
"primary timed out; fallback mongodb://secondary:{secondary_pass_comma}@10.0.0.51:27017,10.0.0.52:27017/stock, \
and srv \"mongodb+srv://reader:{secondary_pass_srv}@cluster.internal/stock?retryReads=true\""
);
let err = MongoStreamError::redacted_source(&diagnostic, &primary_uri);
let display_out = format!("{err}");
let debug_out = format!("{err:?}");
for secret in [
"PRIMARY_PASS_111",
secondary_pass_comma,
"SEC_ALPHA",
"BETA",
"GAMMA",
"DELTA",
secondary_pass_srv,
"SRV_PASS",
"QUOTE",
"BRACKET",
] {
assert!(
!display_out.contains(secret),
"Display leaked secondary password fragment `{secret}`: {display_out}"
);
assert!(
!debug_out.contains(secret),
"Debug leaked secondary password fragment `{secret}`: {debug_out}"
);
}
assert!(
display_out.contains("mongodb://secondary:[REDACTED]@10.0.0.51:27017,10.0.0.52:27017/stock"),
"unexpected redacted secondary URI in Display: {display_out}"
);
assert!(
display_out.contains("mongodb+srv://reader:[REDACTED]@cluster.internal/stock?retryReads=true"),
"unexpected redacted srv URI in Display: {display_out}"
);
}
// ---------------------------------------------------------------------------
// 6. Sealed-surface source scan (zero driver paths or mutating calls)
// ---------------------------------------------------------------------------