rivet/source/mongo/mod.rs
1//! **Layer: Execution** — MongoDB source engine (document store).
2//!
3//! Unlike the three SQL engines (PostgreSQL / MySQL / SQL Server), MongoDB has
4//! no SQL, no fixed per-collection schema, and no `information_schema`. So the
5//! SQL-shaped read seam — chunked/keyset planning, incremental predicate
6//! building, catalog introspection — does **not** apply. This adapter is the
7//! **OSS JSON-blob model**: every document exports as exactly two columns —
8//! `_id` (`Utf8`, the document key stringified: ObjectId → hex, etc.) and
9//! `document` (`Utf8` + the `arrow.json` extension type, the whole BSON
10//! document rendered as relaxed extended JSON).
11//!
12//! Per-field typing is punted downstream (`PARSE_JSON` in the warehouse). Schema
13//! inference / auto-discovery is deliberately **out of scope for OSS** (it is the
14//! paid-tier `discover` mechanism); the user gets a lossless blob, not a guessed
15//! columnar schema. A future `columns:` projection can carve typed columns out of
16//! the blob without changing this default.
17//!
18//! ## Sync bridge (ADR-0011)
19//!
20//! The `mongodb` driver is async (tokio); the [`Source`] trait is sync
21//! `&mut self`. Like the MSSQL/tiberius engine, each [`MongoSource`] owns a tokio
22//! runtime and `block_on`s every driver call — no async leaks into the runner.
23//!
24//! ## Scope
25//!
26//! `mode: full` only (incremental / chunked / time-window are SQL-runner concepts
27//! and are refused with an actionable error). Within full mode, `source.mongo.
28//! page_size` opts into **keyset (seek) paging** on `_id` — bounded query time,
29//! per-page parts, optional cross-run **resume** (`resume: true`, typed BSON
30//! checkpoint), and `parallel: N` **`_id`-range fan-out** (any BSON `_id`). CDC
31//! (change streams) rides the canonical `ChangeStream` seam and is added
32//! separately.
33
34use std::sync::Arc;
35
36use arrow::array::{ArrayRef, StringBuilder};
37use arrow::datatypes::{Schema, SchemaRef};
38use arrow::record_batch::RecordBatch;
39use futures_util::TryStreamExt;
40use mongodb::Client;
41use mongodb::bson::oid::ObjectId;
42use mongodb::bson::{Bson, Document, doc};
43use mongodb::options::{ClientOptions, CollectionOptions, ReadConcern};
44use tokio::runtime::Runtime;
45
46use crate::config::{MongoConfig, MongoJsonMode, MongoReadConcern, TlsConfig};
47use crate::error::Result;
48use crate::source::{BatchSink, ExportRequest, Source};
49use crate::types::{ColumnOverrides, RivetType, SourceColumn, TypeMapping};
50
51pub(crate) mod cdc;
52
53/// The byte budget at which a document batch flushes. The `document` column is an
54/// Arrow `Utf8` (i32 offsets): a batch accumulating > 2 GiB panics ("byte array
55/// offset overflow"). Large documents (up to 16 MB each) hit that far before the
56/// row cap (~65 K rows), so a row-only limit is unsafe for a document store —
57/// `None` (the default in every tuning profile) MUST NOT mean "unbounded".
58/// Default 256 MiB: bounds RSS (the correct blob knob) and keeps every batch well
59/// under the i32 ceiling (bug-hunt: 2300×1 MB docs panicked on the default).
60fn mongo_batch_byte_cap(max_batch_memory_mb: Option<usize>) -> usize {
61 const DEFAULT: usize = 256 * 1024 * 1024;
62 // Keep the cap STRICTLY below the i32 offset ceiling. `document` is an Arrow
63 // Utf8 (i32 offsets), so a flush threshold >= 2 GiB lets a batch's cumulative
64 // value buffer overflow i32::MAX on `append_value` and panic ("byte array
65 // offset overflow") BEFORE the byte-cap flush check fires — the exact crash
66 // the cap exists to prevent. The default is already sub-2 GiB, but a user
67 // override (`max_batch_memory_mb: 2048`, a plausible "give it 2 GB") had no
68 // upper clamp. Clamp to 1 GiB so a full batch + one more 16 MB doc still fits.
69 const MAX: usize = 1024 * 1024 * 1024;
70 max_batch_memory_mb
71 .map(|mb| mb.saturating_mul(1024 * 1024).min(MAX))
72 .filter(|&b| b > 0)
73 .unwrap_or(DEFAULT)
74}
75
76/// Map rivet's [`TlsConfig`] onto the mongodb driver's `Tls`, mirroring the SQL
77/// engines' posture: `Disable` = plaintext; `Require` = TLS but accept any cert
78/// (sniff-proof, not MITM-proof); `VerifyCa` = verify chain, skip hostname;
79/// `VerifyFull` = verify both. The per-field `accept_invalid_*` flags widen (but
80/// never narrow) the mode. Without this the driver ignored the block entirely.
81fn tls_to_mongo(cfg: &TlsConfig) -> mongodb::options::Tls {
82 use crate::config::TlsMode;
83 use mongodb::options::{Tls, TlsOptions};
84 if matches!(cfg.mode, TlsMode::Disable) {
85 return Tls::Disabled;
86 }
87 // Only `Require` waives certificate verification; `VerifyCa`/`VerifyFull`
88 // both verify the chain. (This driver exposes no hostname-only toggle, so
89 // `VerifyCa` verifies the hostname too — stricter than the SQL engines, never
90 // weaker.) The per-field `accept_invalid_certs` flag widens, never narrows.
91 let mode_invalid_cert = matches!(cfg.mode, TlsMode::Require);
92 let mut o = TlsOptions::default();
93 o.ca_file_path = cfg.ca_file.as_ref().map(std::path::PathBuf::from);
94 o.allow_invalid_certificates = Some(mode_invalid_cert || cfg.accept_invalid_certs);
95 Tls::Enabled(o)
96}
97
98/// A connected MongoDB session: the async client plus the tokio runtime that
99/// drives it, so the sync `Source` trait can `block_on` every driver call
100/// (ADR-0011, mirrors MSSQL/tiberius). This is the **one** place that owns the
101/// async→sync bridge — the SDAM-needs-a-worker-thread runtime, the connect +
102/// ping handshake, the borrow dance — reused by the source, the harm / count
103/// probes, and `rivet init`.
104pub struct MongoSession {
105 rt: Runtime,
106 client: Client,
107 /// Database resolved from the connection URL path (`mongodb://…/<db>`).
108 db: String,
109}
110
111impl MongoSession {
112 /// Connect + `ping`. `gate` applies the shared remote-plaintext TLS refusal
113 /// (`require_tls_or_loopback`, CWE-319); `rivet init` passes `false` (dev
114 /// convenience, like the SQL init helpers), every other caller `true`.
115 pub fn connect(url: &str, tls: Option<&TlsConfig>, gate: bool) -> Result<Self> {
116 if gate {
117 crate::source::require_tls_or_loopback(url, tls)?;
118 }
119 // Small multi-thread runtime (not current-thread): the driver spawns
120 // background SDAM/heartbeat tasks that must make progress independently
121 // of our `block_on` calls, or connection monitoring starves.
122 let rt = tokio::runtime::Builder::new_multi_thread()
123 .worker_threads(2)
124 .enable_all()
125 .build()?;
126 let (client, db) = rt.block_on(async {
127 let mut opts = ClientOptions::parse(url).await?;
128 // Honor the `tls:` block. Without this the driver used only the URL's
129 // `?tls=` — so `tls: { mode: verify-full }` on a URL that didn't opt
130 // in connected in PLAINTEXT, the exact posture the operator asked to
131 // forbid (bug-hunt find). `None` ⇒ leave the URL's own tls setting.
132 if let Some(cfg) = tls {
133 opts.tls = Some(tls_to_mongo(cfg));
134 }
135 let db = opts.default_database.clone().ok_or_else(|| {
136 anyhow::anyhow!(
137 "mongodb url must include a database: mongodb://user:pass@host:port/<db>"
138 )
139 })?;
140 let client = Client::with_options(opts)?;
141 // Round-trip so a bad host/auth fails at connect, not first read.
142 client.database(&db).run_command(doc! { "ping": 1 }).await?;
143 Ok::<_, anyhow::Error>((client, db))
144 })?;
145 Ok(Self { rt, client, db })
146 }
147
148 pub fn client(&self) -> &Client {
149 &self.client
150 }
151 pub fn db(&self) -> &str {
152 &self.db
153 }
154 /// Drive a future to completion on the owned runtime.
155 pub fn block_on<T>(&self, fut: impl std::future::Future<Output = T>) -> T {
156 self.rt.block_on(fut)
157 }
158}
159
160/// MongoDB source over a [`MongoSession`], carrying the resolved `source.mongo:`
161/// read options `export` applies.
162pub struct MongoSource {
163 session: MongoSession,
164 /// Render the `document` column as canonical (type-tagged) extended JSON.
165 canonical_json: bool,
166 /// Scan under `readConcern: snapshot` (point-in-time; 5.0+ replica set).
167 snapshot: bool,
168 /// Set `noCursorTimeout` on the scan cursor.
169 no_cursor_timeout: bool,
170 /// A disjoint `_id` slice `[lo, hi)` for ONE parallel worker. When `Some`,
171 /// every scan (keyset page or full) is bounded to `{_id: {$gte: lo, $lt:
172 /// hi}}` (composed with the keyset `$gt` cursor). Bounds are `Bson` — a slice
173 /// works for ANY `_id` type (ObjectId, integer, string), with `MinKey`/
174 /// `MaxKey` as the outer sentinels. Set per-worker by the parallel runner;
175 /// ranges tile the whole BSON key space so their union is the full collection
176 /// with no overlap. `_id` is immutable ⇒ no doc migrates between ranges.
177 /// `None` ⇒ the whole collection (the normal single reader).
178 id_range: Option<(Bson, Bson)>,
179 /// Collections already vetted by [`Self::ensure_uniform_id_type`] this run —
180 /// the guard runs on the FIRST keyset page of every run, including a
181 /// checkpointed resume (`after_id` present). Gating it on `after_id.is_none()`
182 /// let `resume: true` bypass it forever: an `_id` of a new BSON band inserted
183 /// after run 1 was silently unreachable on every later run (bug-hunt find).
184 id_guard_checked: std::collections::HashSet<String>,
185}
186
187impl MongoSource {
188 /// Connect, resolving the optional `source.mongo:` read options (absent ⇒
189 /// relaxed JSON, server read concern, cursor kept alive). Used by
190 /// `create_source` (with the config block) and the `doctor` / type-report
191 /// probes (with `None`).
192 pub fn connect(url: &str, tls: Option<&TlsConfig>, cfg: Option<&MongoConfig>) -> Result<Self> {
193 let session = MongoSession::connect(url, tls, true)?;
194 let (canonical_json, snapshot, no_cursor_timeout) = match cfg {
195 None => (false, false, true),
196 Some(c) => (
197 matches!(c.json, MongoJsonMode::Canonical),
198 matches!(c.read_concern, MongoReadConcern::Snapshot),
199 c.no_cursor_timeout,
200 ),
201 };
202 Ok(Self {
203 session,
204 canonical_json,
205 snapshot,
206 no_cursor_timeout,
207 id_range: None,
208 id_guard_checked: std::collections::HashSet::new(),
209 })
210 }
211
212 /// Bind this reader to one disjoint `_id` slice `[lo, hi)` (a parallel
213 /// worker). Consuming builder — each worker owns its own `MongoSource`.
214 pub fn with_id_range(mut self, lo: Bson, hi: Bson) -> Self {
215 self.id_range = Some((lo, hi));
216 self
217 }
218
219 /// The min and max `_id` of `collection` by BSON sort order (one index-bound
220 /// `find_one` each), or `None` if the collection is empty. Brackets are
221 /// *contiguous* in BSON sort order, so the endpoints span every bracket
222 /// present — comparing them detects any heterogeneous-`_id` mix. Shared by the
223 /// keyset *refusal* ([`Self::ensure_uniform_id_type`]) and the full-scan
224 /// *warning* ([`Self::warn_if_heterogeneous_id`]).
225 fn id_span(&self, collection: &str) -> Result<Option<(Document, Document)>> {
226 let coll = self
227 .session
228 .client()
229 .database(self.session.db())
230 .collection::<Document>(collection);
231 self.session.block_on(async {
232 let lo = coll.find_one(doc! {}).sort(doc! { "_id": 1 }).await?;
233 let hi = coll.find_one(doc! {}).sort(doc! { "_id": -1 }).await?;
234 Ok::<_, anyhow::Error>(lo.zip(hi))
235 })
236 }
237
238 /// Guard against silent loss on a heterogeneous-`_id` collection. Keyset
239 /// paging seeks with `$gt`/`$lt`, which MongoDB **type-brackets**: a numeric
240 /// cursor never matches a string `_id` even though strings sort after numbers,
241 /// so a collection mixing `_id` types would page only the first bracket and
242 /// silently drop the rest (verified: an int+string collection reads 50%). We
243 /// compare the BSON bracket of the min and max `_id` (a single bracket is a
244 /// contiguous band, so differing endpoints ⟺ a bracket jump exists) and refuse
245 /// keyset/parallel, pointing at the full scan — a single ordered cursor, which
246 /// DOES cross brackets. Numeric types share bracket 0, so a mixed
247 /// Int32/Int64/Double `_id` still keysets fine.
248 pub(crate) fn ensure_uniform_id_type(&self, collection: &str) -> Result<()> {
249 if let Some((lo, hi)) = self.id_span(collection)?
250 && let (Some(lo_id), Some(hi_id)) = (lo.get("_id"), hi.get("_id"))
251 {
252 // NaN never matches $gt/$gte/$lt against a non-NaN operand: a keyset
253 // page boundary landing ON the NaN row drops the whole remaining
254 // collection, and every parallel range excludes it. NaN sorts FIRST
255 // in the numeric band, so the min probe always sees it (the max
256 // probe covers the all-NaN corner).
257 for id in [lo_id, hi_id] {
258 if matches!(id, Bson::Double(f) if f.is_nan()) {
259 anyhow::bail!(
260 "collection '{collection}' has a NaN `_id`: MongoDB range \
261 operators never match NaN, so keyset paging / parallel \
262 ranges would silently skip documents. Remove `page_size` \
263 and `parallel` to use a full ordered scan (a single \
264 cursor reads every document), or fix the `_id`."
265 );
266 }
267 }
268 // Unknown band is refused too (see `id_types_collide`): if we cannot
269 // place the type we cannot promise the seek crosses it — loud beats a
270 // silent gap.
271 if id_types_collide(lo_id, hi_id) {
272 anyhow::bail!(
273 "collection '{collection}' has heterogeneous `_id` types \
274 ({:?} … {:?}): MongoDB keyset paging seeks with `$gt`, which is \
275 BSON-type-bracketed and would silently skip every `_id` type but \
276 one. Remove `page_size` and `parallel` to use a full ordered scan \
277 (a single cursor crosses BSON types), or normalise `_id` to one type.",
278 lo_id.element_type(),
279 hi_id.element_type(),
280 );
281 }
282 }
283 Ok(())
284 }
285
286 /// Advisory sibling of [`Self::ensure_uniform_id_type`] for the **full-scan**
287 /// path (no `page_size`, no `parallel`): a full ordered cursor DOES cross BSON
288 /// brackets, so a heterogeneous-`_id` collection is read completely — no loss.
289 /// But the flat `_id` **display column** stringifies distinct BSON types to
290 /// possibly-colliding text (int `1001` and string `"1001"` both → `"1001"`), so
291 /// a warehouse merge keyed on `_id` would conflate them. Warn once, up front,
292 /// and point at the typed `document._id` (see docs). Best-effort: a probe
293 /// failure is silent (advisory, never a gate).
294 pub(crate) fn warn_if_heterogeneous_id(&self, collection: &str) {
295 let Ok(Some((lo, hi))) = self.id_span(collection) else {
296 return;
297 };
298 if let (Some(lo_id), Some(hi_id)) = (lo.get("_id"), hi.get("_id"))
299 && id_types_collide(lo_id, hi_id)
300 {
301 log::warn!(
302 "collection '{collection}' has heterogeneous `_id` types ({:?} … {:?}): {}",
303 lo_id.element_type(),
304 hi_id.element_type(),
305 hetero_id_guidance()
306 );
307 }
308 }
309
310 /// Split the collection's `_id` space into `n` disjoint, size-balanced
311 /// ranges `[lo, hi)` whose union tiles the whole BSON key space (so the union
312 /// read is the complete collection, no overlap) — for ANY `_id` type, not
313 /// just ObjectId. Boundaries come from a `$sample` of the `_id`s (a
314 /// WiredTiger random cursor — O(sample), NOT a collection scan, unlike
315 /// `$bucketAuto` which examines every doc), then the N−1 quantiles of the
316 /// sorted sample. Outer bounds are `MinKey`/`MaxKey`, which sort before/after
317 /// every value, so the first/last range cannot miss the true extremes.
318 pub fn sample_id_ranges(&self, collection: &str, n: usize) -> Result<Vec<(Bson, Bson)>> {
319 self.ensure_uniform_id_type(collection)?;
320 let n = n.max(1);
321 let full_range = || vec![(Bson::MinKey, Bson::MaxKey)];
322 if n == 1 {
323 return Ok(full_range());
324 }
325 // ~250 samples per target range (min 2000), capped so a huge N stays well
326 // under the 5%-of-collection threshold that flips $sample to a full sort.
327 let sample_size = (n * 250).clamp(2000, 50_000);
328 let coll = self
329 .session
330 .client()
331 .database(self.session.db())
332 .collection::<Document>(collection);
333 let ids: Vec<Bson> = self.session.block_on(async move {
334 let mut cursor = coll
335 .aggregate(vec![
336 doc! { "$sample": { "size": sample_size as i64 } },
337 doc! { "$sort": { "_id": 1 } },
338 doc! { "$project": { "_id": 1 } },
339 ])
340 .await?;
341 let mut ids = Vec::new();
342 while let Some(d) = cursor.try_next().await? {
343 // `$sort` yields the sampled `_id`s in BSON order; any type is fine
344 // (the range filter compares by the same order the server sorts by).
345 if let Some(id) = d.get("_id") {
346 ids.push(id.clone());
347 }
348 }
349 Ok::<_, anyhow::Error>(ids)
350 })?;
351 if ids.len() < 2 {
352 // Too few docs to split meaningfully — one range over everything.
353 return Ok(full_range());
354 }
355 // N−1 interior quantile boundaries → N ranges; MinKey/MaxKey at the ends
356 // sort before/after every value, so the outer slices cover the extremes
357 // for ANY `_id` type.
358 let mut bounds = vec![Bson::MinKey];
359 for i in 1..n {
360 bounds.push(ids[i * ids.len() / n].clone());
361 }
362 bounds.push(Bson::MaxKey);
363 // Adjacent quantiles can land on the same value in a skewed sample; drop
364 // the resulting empty `[x, x)` so a worker never gets a no-op range (the
365 // dropped value is still covered by the next range's `$gte`).
366 Ok(bounds
367 .windows(2)
368 .filter(|w| w[0] != w[1])
369 .map(|w| (w[0].clone(), w[1].clone()))
370 .collect())
371 }
372}
373
374/// The two fixed columns of the JSON-blob model. Used by both the export schema
375/// and `type_mappings`, so `check --type-report` and the export agree.
376fn blob_mappings() -> Vec<TypeMapping> {
377 vec![
378 TypeMapping::from_source(
379 &SourceColumn::simple("_id", "objectid", false),
380 RivetType::String,
381 ),
382 TypeMapping::from_source(
383 // Nullable: a CDC DELETE with no pre-image (pre/post-images not
384 // enabled, or < 6.0) carries only `_id`, so `document` is NULL. A
385 // batch export never writes a null here — nullable is a safe superset.
386 &SourceColumn::simple("document", "document", true),
387 RivetType::Json,
388 ),
389 ]
390}
391
392/// Arrow schema for the JSON-blob model (`_id: Utf8`, `document: Utf8 + json`).
393fn blob_schema() -> SchemaRef {
394 let fields = blob_mappings()
395 .iter()
396 .map(|m| {
397 crate::types::build_arrow_field(m)
398 .expect("blob columns (String/Json) always have an Arrow mapping")
399 })
400 .collect::<Vec<_>>();
401 Arc::new(Schema::new(fields))
402}
403
404/// Stringify a document `_id` for the `_id` column. ObjectId → 24-char hex;
405/// string/number keys → their natural text; anything exotic (binary, compound)
406/// → its relaxed extended JSON, so the column is always populated and never
407/// silently null.
408fn id_to_string(id: Option<&Bson>) -> String {
409 match id {
410 Some(Bson::ObjectId(oid)) => oid.to_hex(),
411 Some(Bson::String(s)) => s.clone(),
412 // Ints, bools, etc. render as their bare relaxed-extjson value (`42`,
413 // `true`); ObjectId/String are special-cased above only to drop the
414 // `{"$oid":…}` wrapper / surrounding quotes.
415 Some(other) => other.clone().into_relaxed_extjson().to_string(),
416 // A document with no `_id` is not possible in MongoDB (the server
417 // always assigns one), but never panic on malformed input.
418 None => String::new(),
419 }
420}
421
422/// Encode a BSON `_id` as a lossless, engine-decodable keyset token: the raw
423/// BSON bytes of `{_id: <value>}`, hex-encoded. Unlike the display `_id` column
424/// (hex/text — type-ambiguous, e.g. integer `1001` vs string `"1001"`), this
425/// preserves the exact BSON type across the string-typed cursor seam, so keyset
426/// paging + resume work for ANY `_id`, not just ObjectId.
427/// The BSON comparison *band* an `_id` falls in for a `$gt`/`$lt` keyset seek.
428/// MongoDB only compares within a band; the server's sort order is
429/// `MinKey < Null < Numbers < String/Symbol < Object < Array < BinData <
430/// ObjectId < Boolean < Date < Timestamp < Regex < MaxKey`. The four numeric
431/// types share one band (a mixed Int32/Int64/Double `_id` keysets fine); every
432/// other band is its own bracket — a former catch-all arm lumped Null, Object,
433/// Array and Regex together, so a `null` + `{…}` collection slipped past the
434/// guard and silently lost a band (bug-hunt find). `None` = a type we cannot
435/// place (MinKey/MaxKey/JS/DbPointer/…) — the caller refuses keyset rather than
436/// guessing. Two `_id`s in different brackets ⟹ un-keyset-able.
437fn id_bracket(v: &Bson) -> Option<u8> {
438 Some(match v {
439 Bson::Double(_) | Bson::Int32(_) | Bson::Int64(_) | Bson::Decimal128(_) => 0,
440 Bson::Null => 1,
441 Bson::String(_) | Bson::Symbol(_) => 2,
442 Bson::Document(_) => 3,
443 Bson::Array(_) => 4,
444 Bson::Binary(_) => 5,
445 Bson::ObjectId(_) => 6,
446 Bson::Boolean(_) => 7,
447 Bson::DateTime(_) => 8,
448 Bson::Timestamp(_) => 9,
449 Bson::RegularExpression(_) => 10,
450 _ => return None,
451 })
452}
453
454/// Whether two `_id` values fall in DIFFERENT keyset brackets — i.e. the
455/// collection mixes BSON `_id` types. An unplaceable type (`id_bracket` = `None`)
456/// counts as colliding: we can neither seek across it (keyset) nor vouch its
457/// display text won't collide (full scan). Pure, so the keyset refusal and the
458/// full-scan warning share one notion of "heterogeneous `_id`".
459fn id_types_collide(lo: &Bson, hi: &Bson) -> bool {
460 match (id_bracket(lo), id_bracket(hi)) {
461 (Some(a), Some(b)) => a != b,
462 _ => true,
463 }
464}
465
466/// The shared downstream-guidance tail of the heterogeneous-`_id` warning (batch
467/// full scan and CDC both emit it). The flat `_id` column renders different BSON
468/// types to possibly-colliding text, so a warehouse merge keyed on `_id` conflates
469/// distinct documents — the typed value is always in `document._id`.
470pub(super) fn hetero_id_guidance() -> &'static str {
471 "the flat `_id` column renders different BSON types to possibly-colliding text \
472 (int 1001 and string \"1001\" both become \"1001\"), so a downstream merge keyed \
473 on `_id` conflates distinct documents — key on the typed `document._id` instead \
474 (see docs/reference/mongodb.md#consuming-in-the-warehouse)"
475}
476
477fn encode_id_cursor(id: &Bson) -> String {
478 let mut buf = Vec::new();
479 doc! { "_id": id.clone() }
480 .to_writer(&mut buf)
481 .expect("a one-field BSON document always serializes");
482 bytes_to_hex(&buf)
483}
484
485/// Lower-case hex of raw bytes — the string half of the BSON-token round-trip
486/// (paired with [`hex_to_bytes`]), used to carry a lossless BSON value across a
487/// string-typed seam (the keyset cursor and the CDC resume token).
488pub(super) fn bytes_to_hex(bytes: &[u8]) -> String {
489 bytes.iter().map(|b| format!("{b:02x}")).collect()
490}
491
492/// Inverse of [`encode_id_cursor`]. Falls back to a bare 24-char ObjectId hex so
493/// a cursor written before the typed token (or a value read from the display
494/// column) still resolves.
495fn decode_id_cursor(token: &str) -> Result<Bson> {
496 if let Ok(bytes) = hex_to_bytes(token)
497 && let Ok(doc) = Document::from_reader(&bytes[..])
498 && let Some(id) = doc.get("_id")
499 {
500 return Ok(id.clone());
501 }
502 ObjectId::parse_str(token).map(Bson::ObjectId).map_err(|_| {
503 anyhow::anyhow!("MongoDB keyset cursor '{token}' is neither a typed token nor ObjectId hex")
504 })
505}
506
507fn hex_to_bytes(s: &str) -> Result<Vec<u8>> {
508 // The 2-byte slices below index by BYTE; a multi-byte char boundary would
509 // panic. A corrupted / foreign token is an error, never a panic.
510 if !s.is_ascii() {
511 anyhow::bail!("invalid hex cursor token (non-ASCII)");
512 }
513 if !s.len().is_multiple_of(2) {
514 anyhow::bail!("odd-length hex cursor token");
515 }
516 (0..s.len())
517 .step_by(2)
518 .map(|i| u8::from_str_radix(&s[i..i + 2], 16).map_err(|e| anyhow::anyhow!(e)))
519 .collect()
520}
521
522/// Render a whole BSON document as an extended-JSON string. `canonical=false`
523/// (relaxed) keeps common scalars native (`42`, `"x"`, `true`, nested
524/// objects/arrays) while still wrapping exotic BSON types losslessly
525/// (`{"$oid":…}`, `{"$date":…}`, `{"$numberDecimal":…}`) — friendliest for a
526/// downstream `PARSE_JSON`. `canonical=true` type-tags every value
527/// (`{"$numberLong":…}`) so Int64/Double survive a double-based JSON-number
528/// parser that would otherwise clamp values beyond 2^53.
529fn document_to_json(doc: &Document, canonical: bool) -> Result<String> {
530 let bson = Bson::Document(doc.clone());
531 let value = if canonical {
532 bson.into_canonical_extjson()
533 } else {
534 bson.into_relaxed_extjson()
535 };
536 Ok(serde_json::to_string(&value)?)
537}
538
539/// Finish the accumulated builders into a `RecordBatch` and hand it to the sink.
540fn flush(
541 schema: &SchemaRef,
542 ids: &mut StringBuilder,
543 docs: &mut StringBuilder,
544 sink: &mut dyn BatchSink,
545) -> Result<()> {
546 let columns: Vec<ArrayRef> = vec![Arc::new(ids.finish()), Arc::new(docs.finish())];
547 let batch = RecordBatch::try_new(schema.clone(), columns)?;
548 sink.on_batch(&batch)?;
549 Ok(())
550}
551
552impl Source for MongoSource {
553 fn export(&mut self, request: &ExportRequest<'_>, sink: &mut dyn BatchSink) -> Result<()> {
554 // The structured read-intent: the bare collection behind the `table:`
555 // shortcut (ADR-0027). `None` ⇒ a hand-written `query:` or a
556 // filtered/wrapped form, which has no MongoDB equivalent.
557 let coll_name = request.base_relation.ok_or_else(|| {
558 anyhow::anyhow!(
559 "MongoDB source supports only `table: <collection>` with `mode: full` — a \
560 hand-written `query:` or a filtered/wrapped form has no MongoDB equivalent. \
561 Got query: {}",
562 request.query
563 )
564 })?;
565 let schema = blob_schema();
566 sink.on_schema(schema.clone())?;
567
568 // `readConcern: snapshot` must ride the collection handle; a plain scan
569 // uses the default handle. The scalar opts are copied into locals so the
570 // async scan closure doesn't borrow `self`.
571 let db = self.session.client().database(self.session.db());
572 let coll = if self.snapshot {
573 db.collection_with_options::<Document>(
574 coll_name,
575 CollectionOptions::builder()
576 .read_concern(ReadConcern::snapshot())
577 .build(),
578 )
579 } else {
580 db.collection::<Document>(coll_name)
581 };
582 let canonical = self.canonical_json;
583 let no_cursor_timeout = self.no_cursor_timeout;
584 let id_range = self.id_range.clone();
585 // Source-side batch = the RSS lever. Two caps, whichever trips first:
586 // • `tuning.batch_size` — a row count (schema-based memory budget for a
587 // document store is unreliable: the `document` column is variable
588 // length, so a row estimate off the Arrow schema misfires);
589 // • `tuning.max_batch_memory_mb` — a hard byte budget on the batch,
590 // the *correct* RSS knob for a JSON blob (flush by accumulated bytes,
591 // independent of how big each document is).
592 let batch_rows = request.tuning.effective_batch_size(Some(&schema)).max(1);
593 let batch_byte_cap = mongo_batch_byte_cap(request.tuning.max_batch_memory_mb);
594
595 // Keyset (seek) pagination: the keyset runner drives the outer loop and
596 // hands us one page's `page_limit` plus the previous page's max `_id`
597 // as a lossless typed token (`set_source_cursor` → `decode_id_cursor`).
598 // We page `find({_id:{$gt:after}}).sort({_id:1}).limit(n)` — a bounded,
599 // index-driven range scan. `page_limit` unset ⇒ one full scan. Because
600 // the token carries the exact BSON type (not a type-ambiguous hex/text
601 // rendering), keyset works for ANY `_id` — ObjectId, integer, string —
602 // and MongoDB's own `$gt`/`sort` provide the ordering.
603 let page_limit = request.page_limit;
604 let after_id: Option<Bson> =
605 match request.cursor.and_then(|c| c.last_cursor_value.as_deref()) {
606 Some(token) => Some(decode_id_cursor(token)?),
607 None => None,
608 };
609
610 // Single-worker keyset, first page of THIS run — including a checkpointed
611 // resume: refuse a heterogeneous-`_id` collection up front. `$gt` is
612 // type-bracketed and would silently drop every `_id` band but the
613 // cursor's; a resume whose cursor predates newly-inserted documents of a
614 // different band would otherwise skip them forever while reporting
615 // success (the guard must NOT be gated on `after_id.is_none()`).
616 // (Parallel checks this in `sample_id_ranges`; a full scan — `page_limit`
617 // unset — is exempt because its single cursor crosses brackets.)
618 if page_limit.is_some() && id_range.is_none() && !self.id_guard_checked.contains(coll_name)
619 {
620 self.ensure_uniform_id_type(coll_name)?;
621 self.id_guard_checked.insert(coll_name.to_string());
622 }
623
624 // Full scan (no page_size, not a parallel worker) is the ONE path that
625 // permits a heterogeneous-`_id` collection — its single cursor crosses BSON
626 // brackets, so the read is complete (keyset/parallel refuse it above). But
627 // the flat `_id` display column can collide across types downstream, so warn
628 // once, up front. Advisory only — never gates the run.
629 if page_limit.is_none() && id_range.is_none() {
630 self.warn_if_heterogeneous_id(coll_name);
631 }
632
633 let total = self.session.block_on(async {
634 // Lower bound: the keyset cursor (`$gt: after`) when resuming a page,
635 // else this worker's range floor (`$gte: lo`). Upper bound: the range
636 // ceiling (`$lt: hi`). A worker with no range and no cursor scans all.
637 let filter = {
638 let mut cond = Document::new();
639 match &after_id {
640 Some(id) => {
641 cond.insert("$gt", id.clone());
642 }
643 None => {
644 if let Some((lo, _)) = &id_range {
645 cond.insert("$gte", lo.clone());
646 }
647 }
648 }
649 if let Some((_, hi)) = &id_range {
650 cond.insert("$lt", hi.clone());
651 }
652 if cond.is_empty() {
653 doc! {}
654 } else {
655 doc! { "_id": cond }
656 }
657 };
658 let mut find = coll.find(filter);
659 if let Some(page) = page_limit {
660 find = find.sort(doc! { "_id": 1 }).limit(page as i64);
661 }
662 if no_cursor_timeout {
663 find = find.no_cursor_timeout(true);
664 }
665 let mut cursor = find.await?;
666 let mut ids = StringBuilder::new();
667 let mut docs = StringBuilder::new();
668 let mut in_batch = 0usize;
669 let mut batch_bytes = 0usize;
670 let mut total = 0usize;
671 // The page's max `_id` (the last row, since keyset sorts `_id` asc).
672 // Reported to the sink as a typed token so the runner advances by the
673 // exact BSON value, not the type-ambiguous display string.
674 let mut max_id: Option<Bson> = None;
675 while let Some(d) = cursor.try_next().await? {
676 let id = id_to_string(d.get("_id"));
677 let json = document_to_json(&d, canonical)?;
678 batch_bytes += id.len() + json.len();
679 ids.append_value(&id);
680 docs.append_value(&json);
681 if page_limit.is_some() {
682 max_id = d.get("_id").cloned();
683 }
684 in_batch += 1;
685 total += 1;
686 if in_batch >= batch_rows || batch_bytes >= batch_byte_cap {
687 flush(&schema, &mut ids, &mut docs, sink)?;
688 in_batch = 0;
689 batch_bytes = 0;
690 }
691 }
692 if in_batch > 0 {
693 flush(&schema, &mut ids, &mut docs, sink)?;
694 }
695 // Keyset only: hand the runner the exact BSON high-water mark.
696 if let Some(id) = &max_id {
697 sink.set_source_cursor(encode_id_cursor(id));
698 }
699 Ok::<usize, anyhow::Error>(total)
700 })?;
701
702 log::info!("total: {total} documents (collection '{coll_name}')");
703 Ok(())
704 }
705
706 /// The JSON-blob model has a fixed two-column schema regardless of the
707 /// query, so `check --type-report` shows it without touching the server.
708 fn type_mappings(
709 &mut self,
710 _query: &str,
711 _column_overrides: &ColumnOverrides,
712 ) -> Result<Vec<TypeMapping>> {
713 Ok(blob_mappings())
714 }
715
716 /// The only scalar rivet asks a `mode: full` source is the reconcile row
717 /// count — `SELECT COUNT(*) FROM (SELECT * FROM <coll>) AS _rivet_reconcile`.
718 /// Recognize that shape and answer it with `countDocuments` so
719 /// `rivet run --reconcile` verifies Mongo exports like the SQL engines. Any
720 /// other SQL scalar (cursor MIN/MAX, etc.) has no Mongo meaning → `None`,
721 /// which callers treat as "unavailable" and skip.
722 fn query_scalar(&mut self, sql: &str) -> Result<Option<String>> {
723 if !sql.to_ascii_lowercase().contains("count(") {
724 return Ok(None);
725 }
726 let Some(coll_name) = last_from_identifier(sql) else {
727 return Ok(None);
728 };
729 let coll = self
730 .session
731 .client()
732 .database(self.session.db())
733 .collection::<Document>(coll_name);
734 let n = self
735 .session
736 .block_on(async move { coll.count_documents(doc! {}).await })?;
737 Ok(Some(n.to_string()))
738 }
739}
740
741/// Pull the collection name out of the innermost `… FROM <ident>` of a SQL
742/// string — the reconcile count wraps the base as
743/// `SELECT COUNT(*) FROM (SELECT * FROM <coll>) AS _rivet_reconcile`, so the
744/// *last* `FROM` names the collection. `None` if no bare identifier follows.
745///
746/// The batch export path no longer un-parses SQL — it reads the structured
747/// `ExportRequest::base_relation` (ADR-0027). This un-parser survives only
748/// because `query_scalar` receives a bare SQL string with no structured
749/// counterpart yet; giving the reconcile count a typed request would delete it
750/// too (the remaining tail of ADR-0027).
751fn last_from_identifier(sql: &str) -> Option<&str> {
752 const MARKER: &str = "from ";
753 let start = sql.to_ascii_lowercase().rfind(MARKER)? + MARKER.len();
754 let ident = sql[start..]
755 .trim_start()
756 .split(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '.'))
757 .next()?;
758 (!ident.is_empty()).then_some(ident)
759}
760
761/// Read a possibly-nested numeric field out of a `serverStatus` document,
762/// coercing Int32 / Int64 / Double to `i64`. `None` if any path segment is
763/// missing or the leaf is not numeric — so a storage engine that omits a
764/// section (e.g. in-memory has no `wiredTiger`) just drops that one metric.
765fn nested_i64(doc: &Document, path: &[&str]) -> Option<i64> {
766 let (leaf, parents) = path.split_last()?;
767 let mut cur = doc;
768 for key in parents {
769 cur = cur.get_document(key).ok()?;
770 }
771 match cur.get(leaf) {
772 Some(Bson::Int64(v)) => Some(*v),
773 Some(Bson::Int32(v)) => Some(*v as i64),
774 Some(Bson::Double(v)) => Some(*v as i64),
775 _ => None,
776 }
777}
778
779/// Pull the source-harm counters out of a `serverStatus` response. Only
780/// **cumulative monotonic** counters are emitted (never gauges), because the
781/// pipeline stores the before→after *delta* — the same contract as the SQL
782/// engines' `sample_harm_counters`.
783fn harm_from_server_status(status: &Document) -> Vec<(String, i64)> {
784 // (metric label, serverStatus path). Chosen as the Mongo analogues of the
785 // PG harm set: docs/keys *scanned* are the read-amplification signal
786 // (≈ `pg_tup_returned`), docs *returned* ≈ `pg_tup_fetched`, `getmore` is
787 // rivet's own streaming footprint (every cursor batch), and WiredTiger
788 // cache bytes-read is the I/O-vs-cache split (≈ `pg_blks_read`).
789 let probes: [(&str, &[&str]); 6] = [
790 (
791 "mongo_docs_scanned",
792 &["metrics", "queryExecutor", "scannedObjects"],
793 ),
794 (
795 "mongo_keys_scanned",
796 &["metrics", "queryExecutor", "scanned"],
797 ),
798 ("mongo_docs_returned", &["metrics", "document", "returned"]),
799 ("mongo_op_query", &["opcounters", "query"]),
800 ("mongo_op_getmore", &["opcounters", "getmore"]),
801 (
802 "mongo_wt_cache_bytes_read",
803 &["wiredTiger", "cache", "bytes read into cache"],
804 ),
805 ];
806 probes
807 .iter()
808 .filter_map(|(name, path)| nested_i64(status, path).map(|v| ((*name).to_string(), v)))
809 .collect()
810}
811
812/// Snapshot MongoDB's source-harm counters via `serverStatus` — the document-
813/// store analogue of the SQL engines' `sample_harm_counters`. Returns
814/// `(metric, cumulative_value)` pairs; the pipeline captures these before and
815/// after the export and stores the per-metric delta in `export_harm`.
816///
817/// These are **server-wide** cumulative counters, so concurrent activity
818/// inflates the delta; on a single-tenant pilot box it is the run's own read
819/// footprint. `serverStatus` needs the `clusterMonitor` role (or the
820/// `serverStatus` privilege) on authenticated deployments — `None` on any
821/// connect / permission / query failure, exactly like the SQL engines:
822/// harm metrics are observability, never a gate.
823pub(crate) fn sample_harm_counters(
824 url: &str,
825 tls: Option<&TlsConfig>,
826) -> Option<Vec<(String, i64)>> {
827 let session = MongoSession::connect(url, tls, true).ok()?;
828 session.block_on(async {
829 let status = session
830 .client()
831 .database(session.db())
832 .run_command(doc! { "serverStatus": 1 })
833 .await
834 .ok()?;
835 Some(harm_from_server_status(&status))
836 })
837}
838
839/// Scan-free document-count estimate for one collection — the preflight
840/// `row_estimate` (the Mongo analogue of PG `reltuples` / MySQL `TABLE_ROWS`).
841/// `estimatedDocumentCount` reads collection metadata, never scans the
842/// collection. `None` on any failure — the diagnostic then shows an unknown
843/// row count, exactly as MySQL does when its estimate is untrustworthy.
844pub(crate) fn estimated_count(url: &str, tls: Option<&TlsConfig>, collection: &str) -> Option<i64> {
845 let session = MongoSession::connect(url, tls, true).ok()?;
846 session.block_on(async {
847 let n = session
848 .client()
849 .database(session.db())
850 .collection::<Document>(collection)
851 .estimated_document_count()
852 .await
853 .ok()?;
854 i64::try_from(n).ok()
855 })
856}
857
858#[cfg(test)]
859mod tests {
860 use super::*;
861 use mongodb::bson::oid::ObjectId;
862
863 // W4: the byte-cap multiplications had no exact-value test — `mb * 1024 *
864 // 1024` mutating to `+` or `/` silently shrinks (or explodes) the flush
865 // budget that keeps document batches under the i32 offset ceiling.
866 #[test]
867 fn batch_byte_cap_is_exact_mib() {
868 assert_eq!(super::mongo_batch_byte_cap(Some(10)), 10 * 1024 * 1024);
869 assert_eq!(super::mongo_batch_byte_cap(None), 256 * 1024 * 1024);
870 // Zero is not a valid budget — falls back to the default.
871 assert_eq!(super::mongo_batch_byte_cap(Some(0)), 256 * 1024 * 1024);
872 }
873
874 #[test]
875 fn batch_byte_cap_is_clamped_below_the_i32_offset_ceiling() {
876 // RED before the clamp: `document` is an Arrow Utf8 (i32 offsets), so a cap
877 // >= 2 GiB let a batch overflow i32::MAX on append and PANIC before the
878 // flush check — the exact crash the cap prevents. A user "give it 2 GB"
879 // (max_batch_memory_mb: 2048) must be clamped, not passed through.
880 let ceiling = i32::MAX as usize;
881 for mb in [2048usize, 4096, 65_536, usize::MAX / (1024 * 1024)] {
882 let cap = super::mongo_batch_byte_cap(Some(mb));
883 assert!(
884 cap < ceiling,
885 "max_batch_memory_mb={mb} yields cap {cap} >= i32::MAX ({ceiling}) — would overflow the Utf8 offset builder"
886 );
887 }
888 // The clamp doesn't shrink a safe sub-ceiling value.
889 assert_eq!(super::mongo_batch_byte_cap(Some(256)), 256 * 1024 * 1024);
890 }
891
892 // ── mutation-W4 gap closure ──────────────────────────────────────────────
893 // Deleting any `id_bracket` arm survived the suite: the type falls to the
894 // `None` catch-all and keyset is (conservatively) refused — a false refusal
895 // no test noticed. The same blindness would pass the DANGEROUS neighbour: a
896 // MERGE regression (two types sharing a band number) makes collide=false
897 // and keysets across a real server band — the silent bracket-loss class the
898 // heterogeneous-`_id` guard exists to prevent. Pin the WHOLE map.
899 #[test]
900 fn id_bracket_map_matches_the_server_sort_bands() {
901 use mongodb::bson::spec::BinarySubtype;
902 use mongodb::bson::{Binary, DateTime, Decimal128, Regex, Timestamp, doc};
903 let b = |v: &Bson| id_bracket(v);
904
905 // The four numeric types share band 0 — a mixed Int32/Int64/Double
906 // `_id` keysets fine by design.
907 assert_eq!(b(&Bson::Int32(1)), Some(0));
908 assert_eq!(b(&Bson::Int64(1)), Some(0));
909 assert_eq!(b(&Bson::Double(1.0)), Some(0));
910 assert_eq!(
911 b(&Bson::Decimal128("1".parse::<Decimal128>().unwrap())),
912 Some(0)
913 );
914 // Every other placeable type is its OWN band, in server sort order.
915 assert_eq!(b(&Bson::Null), Some(1));
916 assert_eq!(b(&Bson::String("s".into())), Some(2));
917 assert_eq!(b(&Bson::Document(doc! {"k": 1})), Some(3));
918 assert_eq!(b(&Bson::Array(vec![Bson::Int32(1)])), Some(4));
919 assert_eq!(
920 b(&Bson::Binary(Binary {
921 subtype: BinarySubtype::Generic,
922 bytes: vec![1],
923 })),
924 Some(5)
925 );
926 assert_eq!(b(&Bson::ObjectId(ObjectId::new())), Some(6));
927 assert_eq!(b(&Bson::Boolean(true)), Some(7));
928 assert_eq!(b(&Bson::DateTime(DateTime::from_millis(0))), Some(8));
929 assert_eq!(
930 b(&Bson::Timestamp(Timestamp {
931 time: 0,
932 increment: 0
933 })),
934 Some(9)
935 );
936 assert_eq!(
937 b(&Bson::RegularExpression(Regex {
938 pattern: "a".into(),
939 options: String::new(),
940 })),
941 Some(10)
942 );
943 // Unplaceable types refuse keyset rather than guess.
944 assert_eq!(b(&Bson::MaxKey), None);
945
946 // The collide relation derives from the map: same band never collides,
947 // different bands always do, unplaceable collides with everything.
948 assert!(!id_types_collide(&Bson::Int32(1), &Bson::Double(2.0)));
949 assert!(id_types_collide(
950 &Bson::Int64(2000),
951 &Bson::String("id-1".into())
952 ));
953 assert!(id_types_collide(&Bson::Null, &Bson::Document(doc! {})));
954 assert!(id_types_collide(&Bson::MaxKey, &Bson::MaxKey));
955 }
956
957 #[test]
958 fn id_string_covers_common_key_types() {
959 let oid = ObjectId::parse_str("64b8f0000000000000000000").unwrap();
960 assert_eq!(
961 id_to_string(Some(&Bson::ObjectId(oid))),
962 "64b8f0000000000000000000"
963 );
964 assert_eq!(id_to_string(Some(&Bson::String("abc".to_string()))), "abc");
965 assert_eq!(id_to_string(Some(&Bson::Int64(42))), "42");
966 assert_eq!(id_to_string(Some(&Bson::Int32(7))), "7");
967 // Never panic / never silently vanish on a missing id.
968 assert_eq!(id_to_string(None), "");
969 }
970
971 #[test]
972 fn heterogeneous_id_detection_is_bracket_based() {
973 let int1001 = Bson::Int32(1001);
974 let str1001 = Bson::String("1001".to_string());
975 let oid = Bson::ObjectId(ObjectId::parse_str("64b8f0000000000000000000").unwrap());
976 // The exact collision the warehouse MERGE guards against: int and string
977 // that stringify to the SAME `_id` text but are distinct documents.
978 assert!(id_types_collide(&int1001, &str1001));
979 // ObjectId vs a string (e.g. its own hex stored as a string _id): cross-bracket.
980 assert!(id_types_collide(&oid, &str1001));
981 // Uniform is NOT flagged — same type, and the four numeric types share
982 // bracket 0 (a mixed Int32/Int64 `_id` is not a display collision).
983 assert!(!id_types_collide(&int1001, &Bson::Int32(2002)));
984 assert!(!id_types_collide(&int1001, &Bson::Int64(9_000_000_000)));
985 assert!(!id_types_collide(&oid, &oid));
986 assert!(!id_types_collide(
987 &str1001,
988 &Bson::String("abc".to_string())
989 ));
990 }
991
992 #[test]
993 fn roast_tls_config_is_honored_not_ignored() {
994 use crate::config::{TlsConfig, TlsMode};
995 use mongodb::options::Tls;
996 let cfg = |mode, ca: Option<&str>| TlsConfig {
997 mode,
998 ca_file: ca.map(String::from),
999 accept_invalid_certs: false,
1000 accept_invalid_hostnames: false,
1001 };
1002 // verify-full: TLS on, verify chain AND hostname, ca wired.
1003 match tls_to_mongo(&cfg(TlsMode::VerifyFull, Some("/ca.pem"))) {
1004 Tls::Enabled(o) => {
1005 assert_eq!(
1006 o.ca_file_path.as_deref(),
1007 Some(std::path::Path::new("/ca.pem"))
1008 );
1009 assert_eq!(o.allow_invalid_certificates, Some(false));
1010 }
1011 Tls::Disabled => panic!("verify-full must ENABLE tls, not ignore it"),
1012 }
1013 // require: TLS on but cert unverified.
1014 match tls_to_mongo(&cfg(TlsMode::Require, None)) {
1015 Tls::Enabled(o) => assert_eq!(o.allow_invalid_certificates, Some(true)),
1016 Tls::Disabled => panic!("require must enable tls"),
1017 }
1018 // disable: explicit plaintext opt-in.
1019 assert!(matches!(
1020 tls_to_mongo(&cfg(TlsMode::Disable, None)),
1021 Tls::Disabled
1022 ));
1023 }
1024
1025 #[test]
1026 fn roast_default_batch_byte_cap_is_bounded_not_unlimited() {
1027 // The whole point of the fix: with no user budget the cap must be a
1028 // finite byte value (≤ the Arrow i32 ceiling), never "unbounded" — an
1029 // unbounded batch of large documents panics ("byte array offset
1030 // overflow"). Verified live at 2300×1 MB before this guard.
1031 let cap = mongo_batch_byte_cap(None);
1032 assert!(
1033 cap > 0 && cap < (i32::MAX as usize),
1034 "cap must be finite + sub-2GiB"
1035 );
1036 // A user budget is honored (MiB → bytes); 0 falls back to the default.
1037 assert_eq!(mongo_batch_byte_cap(Some(64)), 64 * 1024 * 1024);
1038 assert_eq!(mongo_batch_byte_cap(Some(0)), mongo_batch_byte_cap(None));
1039 }
1040
1041 #[test]
1042 fn roast_non_ascii_cursor_token_is_a_clean_error_not_a_panic() {
1043 // A corrupted / foreign checkpoint token must surface as Err — never a
1044 // byte-boundary panic. '€' is 3 bytes: "€€" is 6 bytes (even, so it
1045 // passes the odd-length check) and the 2-byte hex slice at [0..2] cuts
1046 // the char in half — which panicked before hex_to_bytes rejected
1047 // non-ASCII input up front.
1048 assert!(decode_id_cursor("€€").is_err());
1049 }
1050
1051 #[test]
1052 fn id_cursor_token_roundtrips_every_bson_type_losslessly() {
1053 // The whole point of the typed token (A′): the display column can't tell
1054 // integer `1001` from string `"1001"`, but the cursor MUST — otherwise a
1055 // keyset `$gt` on the wrong BSON type mis-pages. Prove the round-trip
1056 // preserves the exact type for each `_id` shape keyset supports.
1057 let oid = Bson::ObjectId(ObjectId::parse_str("64b8f0000000000000000000").unwrap());
1058 for id in [
1059 oid.clone(),
1060 Bson::Int32(1001),
1061 Bson::Int64(9_000_000_000),
1062 Bson::String("1001".to_string()), // same text as Int32(1001) — must NOT collide
1063 Bson::String("sku-00042".to_string()),
1064 ] {
1065 let token = encode_id_cursor(&id);
1066 assert_eq!(
1067 decode_id_cursor(&token).unwrap(),
1068 id,
1069 "typed cursor round-trip lost the type for {id:?}"
1070 );
1071 }
1072 // Int32(1001) and String("1001") encode to DIFFERENT tokens (no ambiguity).
1073 assert_ne!(
1074 encode_id_cursor(&Bson::Int32(1001)),
1075 encode_id_cursor(&Bson::String("1001".to_string()))
1076 );
1077 // Legacy / display fallback: a bare 24-char ObjectId hex still decodes.
1078 assert_eq!(decode_id_cursor("64b8f0000000000000000000").unwrap(), oid);
1079 }
1080
1081 #[test]
1082 fn document_renders_relaxed_and_canonical() {
1083 let d = doc! {
1084 "a": 1i32,
1085 "b": "x",
1086 "big": 9_223_372_036_854_775_807i64,
1087 "nested": doc! { "d": true },
1088 };
1089 // Relaxed: common scalars native, Int64 as a bare JSON number.
1090 let relaxed = document_to_json(&d, false).unwrap();
1091 assert!(relaxed.contains("\"a\":1"), "got: {relaxed}");
1092 assert!(relaxed.contains("\"b\":\"x\""), "got: {relaxed}");
1093 assert!(
1094 relaxed.contains("\"nested\":{\"d\":true}"),
1095 "got: {relaxed}"
1096 );
1097 assert!(
1098 relaxed.contains("\"big\":9223372036854775807"),
1099 "int64 is a bare number in relaxed: {relaxed}"
1100 );
1101 // Canonical: every number type-tagged so a double-based JSON parser can't
1102 // clamp an Int64 beyond 2^53.
1103 let canonical = document_to_json(&d, true).unwrap();
1104 assert!(
1105 canonical.contains("\"$numberLong\":\"9223372036854775807\""),
1106 "int64 is type-tagged in canonical: {canonical}"
1107 );
1108 }
1109
1110 #[test]
1111 fn blob_schema_is_two_columns_id_and_document_json() {
1112 let schema = blob_schema();
1113 let names: Vec<&str> = schema.fields().iter().map(|f| f.name().as_str()).collect();
1114 assert_eq!(names, vec!["_id", "document"]);
1115 // The document column carries the Arrow JSON canonical extension type so
1116 // parquet emits a native JSON column downstream, not a bare string.
1117 let doc_field = schema.field_with_name("document").unwrap();
1118 assert_eq!(
1119 doc_field.metadata().get("ARROW:extension:name"),
1120 Some(&"arrow.json".to_string()),
1121 "document column must carry the arrow.json extension type"
1122 );
1123 }
1124
1125 #[test]
1126 fn harm_counters_extracted_from_server_status() {
1127 let status = doc! {
1128 "metrics": {
1129 "queryExecutor": { "scanned": 10i64, "scannedObjects": 500i64 },
1130 "document": { "returned": 480i64 },
1131 },
1132 "opcounters": { "query": 7i32, "getmore": 12i32 },
1133 "wiredTiger": { "cache": { "bytes read into cache": 1_048_576i64 } },
1134 };
1135 let harm: std::collections::HashMap<String, i64> =
1136 harm_from_server_status(&status).into_iter().collect();
1137 assert_eq!(harm.get("mongo_docs_scanned"), Some(&500));
1138 assert_eq!(harm.get("mongo_keys_scanned"), Some(&10));
1139 assert_eq!(harm.get("mongo_docs_returned"), Some(&480));
1140 assert_eq!(harm.get("mongo_op_query"), Some(&7)); // Int32 coerced to i64
1141 assert_eq!(harm.get("mongo_op_getmore"), Some(&12));
1142 assert_eq!(harm.get("mongo_wt_cache_bytes_read"), Some(&1_048_576));
1143 }
1144
1145 #[test]
1146 fn reconcile_count_query_names_the_collection() {
1147 // The reconcile count wraps the base query; the LAST `FROM` names the
1148 // collection countDocuments runs against.
1149 assert_eq!(
1150 last_from_identifier("SELECT COUNT(*) FROM (SELECT * FROM orders) AS _rivet_reconcile"),
1151 Some("orders")
1152 );
1153 assert_eq!(
1154 last_from_identifier("select count(*) from (select * from shop_events) as _r"),
1155 Some("shop_events")
1156 );
1157 // No bare identifier after a FROM → no count.
1158 assert_eq!(last_from_identifier("SELECT 1"), None);
1159 }
1160
1161 #[test]
1162 fn harm_skips_missing_sections_gracefully() {
1163 // e.g. the in-memory storage engine has no `wiredTiger` section — a
1164 // missing section drops only its own metric, never errors.
1165 let status = doc! { "opcounters": { "query": 3i64 } };
1166 let harm: std::collections::HashMap<String, i64> =
1167 harm_from_server_status(&status).into_iter().collect();
1168 assert_eq!(harm.get("mongo_op_query"), Some(&3));
1169 assert!(!harm.contains_key("mongo_wt_cache_bytes_read"));
1170 assert!(!harm.contains_key("mongo_docs_scanned"));
1171 }
1172}