diff --git a/napi/src/connection.rs b/napi/src/connection.rs index 4a20f490..c5c9de52 100644 --- a/napi/src/connection.rs +++ b/napi/src/connection.rs @@ -51,10 +51,11 @@ use crate::util::guarded; /// produces (`lib/utils/queryTags.ts`). Backslashes in keys are /// doubled; backslash/colon/comma in values are backslash-escaped. /// -/// Positional parameters, named parameters, row limit, and wait -/// timeout are deferred: they require either a non-trivial JS↔napi -/// `TypedValue` mapping (params) or a kernel-side `StatementSpec` -/// extension (`row_limit`/`wait_timeout`). Both land in follow-on PRs. +/// `rowLimit` (SEA `row_limit`) and `queryTimeoutSecs` (the per-statement +/// server wait timeout) are exposed here and threaded onto the kernel +/// `StatementSpec`. Positional and named parameters remain deferred: they +/// require a non-trivial JS↔napi `TypedValue` mapping and land in a +/// follow-on PR. /// /// **Tag-order caveat (M4 parity note).** The napi `queryTags` field /// is a Rust `HashMap` whose iteration order is @@ -90,6 +91,17 @@ pub struct ExecuteOptions { /// HashMap-iteration-order vs `Object.keys`-iteration-order /// divergence and the byte-identical-Thrift-parity workaround. pub query_tags: Option>, + /// Server-side cap on the number of rows this statement returns + /// (SEA `row_limit`), independent of any SQL `LIMIT`. Maps to + /// `StatementSpec.row_limit`. Omitted ⇒ no driver-imposed cap. + pub row_limit: Option, + /// Per-statement server wait timeout in whole seconds. Bounds how + /// long the server waits before cancelling the statement + /// (`on_wait_timeout = CANCEL`), surfacing as a timeout — the + /// server statement timeout (JDBC `setQueryTimeout`). Maps to + /// `StatementSpec.query_timeout_secs`. Distinct from the + /// connection-level transport timeout. The SEA wire caps it at 50s. + pub query_timeout_secs: Option, } /// Closed-state error builder. Mirrors `statement::statement_closed_err` @@ -227,6 +239,10 @@ impl Connection { options: Option, ) -> napi::Result { let inner = Arc::clone(&self.inner); + // Pull the scalar knobs out before `build_merged_statement_conf` + // consumes `options` (both `i64`/`u32` are `Copy`). + let row_limit = options.as_ref().and_then(|o| o.row_limit); + let query_timeout_secs = options.as_ref().and_then(|o| o.query_timeout_secs); // Merge `query_tags` into `statement_conf` at the napi boundary // so the kernel sees a single conf map. Serialise the tag // map to the comma-separated `key:value` wire shape NodeJS @@ -242,6 +258,12 @@ impl Connection { if let Some(conf) = merged_conf { stmt.spec().statement_conf(conf); } + // `None` leaves the kernel's omit-the-field default in place, + // so threading unconditionally is safe and keeps the spec the + // single source of truth. + stmt.spec() + .row_limit(row_limit) + .query_timeout_secs(query_timeout_secs); let executed = stmt.execute().await.map_err(napi_err_from_kernel)?; // Pass the parent kernel `Statement` into the JS wrapper. @@ -375,6 +397,8 @@ mod tests { let result = build_merged_statement_conf(Some(ExecuteOptions { statement_conf: Some(HashMap::new()), query_tags: Some(HashMap::new()), + row_limit: None, + query_timeout_secs: None, })) .unwrap(); assert!(result.is_none(), "empty maps → no statement_conf"); @@ -387,6 +411,8 @@ mod tests { let result = build_merged_statement_conf(Some(ExecuteOptions { statement_conf: Some(conf), query_tags: None, + row_limit: None, + query_timeout_secs: None, })) .unwrap() .unwrap(); @@ -400,6 +426,8 @@ mod tests { let result = build_merged_statement_conf(Some(ExecuteOptions { statement_conf: None, query_tags: Some(tags), + row_limit: None, + query_timeout_secs: None, })) .unwrap() .unwrap(); @@ -417,6 +445,8 @@ mod tests { let result = build_merged_statement_conf(Some(ExecuteOptions { statement_conf: None, query_tags: Some(tags), + row_limit: None, + query_timeout_secs: None, })) .unwrap() .unwrap(); @@ -433,6 +463,8 @@ mod tests { let result = build_merged_statement_conf(Some(ExecuteOptions { statement_conf: None, query_tags: Some(tags), + row_limit: None, + query_timeout_secs: None, })) .unwrap() .unwrap(); @@ -451,6 +483,8 @@ mod tests { let err = build_merged_statement_conf(Some(ExecuteOptions { statement_conf: Some(conf), query_tags: Some(tags), + row_limit: None, + query_timeout_secs: None, })) .expect_err("must reject when both are set"); assert!( @@ -472,6 +506,8 @@ mod tests { let result = build_merged_statement_conf(Some(ExecuteOptions { statement_conf: Some(conf), query_tags: Some(HashMap::new()), + row_limit: None, + query_timeout_secs: None, })) .unwrap() .unwrap(); diff --git a/src/reader/inline/provider.rs b/src/reader/inline/provider.rs index 5a135dcf..4449a290 100644 --- a/src/reader/inline/provider.rs +++ b/src/reader/inline/provider.rs @@ -38,6 +38,37 @@ pub struct InlineArrowProvider { schema: Option, } +/// Clamp a sequence of record batches to an authoritative logical row +/// count (`manifest.total_row_count`), slicing the batch that crosses the +/// boundary and dropping any rows past it. `None` (or a negative count) +/// leaves the batches untouched. Pure so the boundary arithmetic is +/// unit-testable. See [`InlineArrowProvider::new`] for why the manifest +/// count, not the raw Arrow row count, is authoritative. +fn clamp_to_total_rows( + batches: Vec, + total_row_count: Option, +) -> Vec { + let Some(limit) = total_row_count.filter(|n| *n >= 0).map(|n| n as usize) else { + return batches; + }; + let mut out = Vec::with_capacity(batches.len()); + let mut remaining = limit; + for batch in batches { + if remaining == 0 { + break; + } + if batch.num_rows() <= remaining { + remaining -= batch.num_rows(); + out.push(batch); + } else { + // This batch crosses the boundary — keep only `remaining` rows. + out.push(batch.slice(0, remaining)); + remaining = 0; + } + } + out +} + impl InlineArrowProvider { /// Create a new provider from raw Arrow IPC bytes. /// @@ -46,6 +77,14 @@ impl InlineArrowProvider { /// # Arguments /// * `attachment` - Raw Arrow IPC bytes (decoded from base64) /// * `compression` - Compression codec used (from manifest.result_compression) + /// * `total_row_count` - Authoritative logical row count from + /// `manifest.total_row_count`. When `Some`, the decoded batches are + /// clamped to this count: with a `row_limit` applied the SEA server + /// returns one extra look-ahead Arrow row beyond the logical count + /// (`manifest.truncated = true`), and the manifest count — not the + /// raw Arrow row count — is the result size. Mirrors the Python SEA + /// connector, which bounds its `ArrowQueue` by `total_row_count`. + /// `None` leaves the batches unclamped. /// /// # Returns /// A new provider with parsed batches ready for iteration @@ -53,7 +92,11 @@ impl InlineArrowProvider { /// # Errors /// - If decompression fails /// - If Arrow IPC parsing fails - pub fn new(attachment: Vec, compression: CompressionCodec) -> Result { + pub fn new( + attachment: Vec, + compression: CompressionCodec, + total_row_count: Option, + ) -> Result { if attachment.is_empty() { tracing::debug!("Empty attachment, creating empty provider"); return Ok(Self { @@ -69,10 +112,12 @@ impl InlineArrowProvider { ); // Reuse the shared Arrow IPC parser (same format as CloudFetch) - let batches = parse_arrow_ipc(&attachment, compression).map_err(|e| { + let parsed = parse_arrow_ipc(&attachment, compression).map_err(|e| { Error::io().message(format!("Failed to parse inline Arrow data: {}", e)) })?; + let batches = clamp_to_total_rows(parsed, total_row_count); + let schema = batches.first().map(|b| b.schema()); tracing::debug!( @@ -156,7 +201,8 @@ mod tests { let batch = create_test_batch(100); let ipc_data = create_test_arrow_ipc(&[batch]); - let mut provider = InlineArrowProvider::new(ipc_data, CompressionCodec::None).unwrap(); + let mut provider = + InlineArrowProvider::new(ipc_data, CompressionCodec::None, None).unwrap(); // Check schema assert!(provider.schema().is_some()); @@ -189,7 +235,7 @@ mod tests { } let mut provider = - InlineArrowProvider::new(compressed, CompressionCodec::Lz4Frame).unwrap(); + InlineArrowProvider::new(compressed, CompressionCodec::Lz4Frame, None).unwrap(); let batch = provider.next_batch().unwrap().unwrap(); assert_eq!(batch.num_rows(), 100); @@ -201,7 +247,8 @@ mod tests { let batch2 = create_test_batch(30); let ipc_data = create_test_arrow_ipc(&[batch1, batch2]); - let mut provider = InlineArrowProvider::new(ipc_data, CompressionCodec::None).unwrap(); + let mut provider = + InlineArrowProvider::new(ipc_data, CompressionCodec::None, None).unwrap(); // First batch let batch = provider.next_batch().unwrap().unwrap(); @@ -217,7 +264,7 @@ mod tests { #[test] fn test_inline_provider_with_empty_data() { - let provider = InlineArrowProvider::new(vec![], CompressionCodec::None).unwrap(); + let provider = InlineArrowProvider::new(vec![], CompressionCodec::None, None).unwrap(); assert!(provider.schema().is_none()); assert!(!provider.has_more()); @@ -227,7 +274,53 @@ mod tests { fn test_inline_provider_with_invalid_data() { let invalid_data = b"this is not valid arrow ipc data".to_vec(); - let result = InlineArrowProvider::new(invalid_data, CompressionCodec::None); + let result = InlineArrowProvider::new(invalid_data, CompressionCodec::None, None); assert!(result.is_err()); } + + #[test] + fn clamp_none_is_passthrough() { + let batches = vec![create_test_batch(10)]; + let out = clamp_to_total_rows(batches, None); + assert_eq!(out.iter().map(|b| b.num_rows()).sum::(), 10); + } + + #[test] + fn clamp_slices_across_batches() { + // 4 + 4 + 4 = 12 rows; clamp to 10 -> 4 + 4 + 2. + let batches = vec![ + create_test_batch(4), + create_test_batch(4), + create_test_batch(4), + ]; + let out = clamp_to_total_rows(batches, Some(10)); + assert_eq!(out.iter().map(|b| b.num_rows()).sum::(), 10); + assert_eq!(out.len(), 3); + assert_eq!(out[2].num_rows(), 2); + } + + #[test] + fn clamp_above_actual_is_noop() { + let batches = vec![create_test_batch(5)]; + let out = clamp_to_total_rows(batches, Some(1000)); + assert_eq!(out.iter().map(|b| b.num_rows()).sum::(), 5); + } + + #[test] + fn inline_provider_clamps_look_ahead_row_to_manifest_count() { + // Reproduces the row_limit=N -> N+1 server look-ahead: an 11-row + // Arrow attachment with manifest.total_row_count = 10 must surface + // exactly 10 rows (parity with Python use_sea and Thrift). + let batch = create_test_batch(11); + let ipc = create_test_arrow_ipc(&[batch]); + let mut provider = InlineArrowProvider::new(ipc, CompressionCodec::None, Some(10)).unwrap(); + let mut total = 0; + while let Some(b) = provider.next_batch().unwrap() { + total += b.num_rows(); + } + assert_eq!( + total, 10, + "must clamp the +1 look-ahead row to the manifest count" + ); + } } diff --git a/src/reader/mod.rs b/src/reader/mod.rs index 607cefd6..7fd4dc64 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -177,7 +177,12 @@ impl ResultReaderFactory { inline_data.len() ); - return self.create_inline_reader(inline_data, compression); + // Pass the manifest's authoritative row count so the + // inline provider clamps off any look-ahead row the SEA + // server appends when a row_limit truncates the result. + let total_row_count = + response.manifest.as_ref().and_then(|m| m.total_row_count); + return self.create_inline_reader(inline_data, compression, total_row_count); } } @@ -304,14 +309,17 @@ impl ResultReaderFactory { &self, inline_data: &[u8], compression: CompressionCodec, + total_row_count: Option, ) -> Result> { tracing::debug!( - "Creating inline Arrow reader: {} bytes, compression={:?}", + "Creating inline Arrow reader: {} bytes, compression={:?}, total_row_count={:?}", inline_data.len(), - compression + compression, + total_row_count ); - let provider = InlineArrowProvider::new(inline_data.to_vec(), compression)?; + let provider = + InlineArrowProvider::new(inline_data.to_vec(), compression, total_row_count)?; Ok(Box::new(InlineArrowReader::new(provider))) } diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index cb48b5c6..a6fe47f6 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -66,6 +66,31 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use tracing::{warn, Instrument}; +/// Resolve the SEA `(wait_timeout, on_wait_timeout)` pair for an execute / +/// submit dispatch. Pure so the precedence rules are unit-testable without +/// a live `Session`. +/// +/// - `caller_wait_secs = Some(s)` — the caller pinned the wait shape +/// (e.g. `submit` passes `"0s"` for async). Respected verbatim with +/// `CONTINUE`; overriding it would make async submit block. +/// - `caller_wait_secs = None` — the sync `execute` path. A per-statement +/// `spec_query_timeout_secs` then bounds the server wait and `CANCEL`s +/// the statement on elapse (JDBC `setQueryTimeout` / Python `use_sea`'s +/// `wait_timeout` semantics). With no spec timeout, both are omitted so +/// the server applies its default (~10s wait + auto-close on success). +fn resolve_wait_timeout( + caller_wait_secs: Option<&str>, + spec_query_timeout_secs: Option, +) -> (Option, Option) { + match caller_wait_secs { + Some(s) => (Some(s.to_string()), Some("CONTINUE".to_string())), + None => match spec_query_timeout_secs { + Some(secs) => (Some(format!("{secs}s")), Some("CANCEL".to_string())), + None => (None, None), + }, + } +} + /// Lifecycle owner for a single statement spec. /// /// Mutable, reusable. Mutate the spec in place via [`Statement::spec`], @@ -300,13 +325,12 @@ impl Statement { if self.spec.result_format != ResultFormat::Arrow { return Err(Error::invalid_argument().message("v0 supports ResultFormat::Arrow only")); } - // `wait_timeout = None` means "omit the field"; the server - // applies its default (~10s wait + auto-close on success). - // `on_wait_timeout` only matters when wait_timeout is set, - // so mirror the presence. + let (wait_timeout, on_wait_timeout) = + resolve_wait_timeout(wait_timeout_secs, self.spec.query_timeout_secs); let mut exec_params = ExecuteParams { - wait_timeout: wait_timeout_secs.map(|s| s.to_string()), - on_wait_timeout: wait_timeout_secs.map(|_| "CONTINUE".to_string()), + wait_timeout, + on_wait_timeout, + row_limit: self.spec.row_limit, ..ExecuteParams::default() }; for (i, value) in self.spec.positional_params.iter().enumerate() { @@ -456,3 +480,35 @@ impl Drop for Statement { // remaining cleanup obligation here. } } + +#[cfg(test)] +mod tests { + use super::resolve_wait_timeout; + + #[test] + fn async_submit_caller_value_is_respected_verbatim() { + // submit() pins "0s" for async; never overridden, even if a spec + // query_timeout is set (overriding would make submit block). + let (wait, on_wait) = resolve_wait_timeout(Some("0s"), Some(30)); + assert_eq!(wait.as_deref(), Some("0s")); + assert_eq!(on_wait.as_deref(), Some("CONTINUE")); + } + + #[test] + fn sync_with_query_timeout_cancels_on_elapse() { + // execute() passes None; a spec query_timeout bounds the wait and + // CANCELs the statement on elapse (server statement-timeout). + let (wait, on_wait) = resolve_wait_timeout(None, Some(30)); + assert_eq!(wait.as_deref(), Some("30s")); + assert_eq!(on_wait.as_deref(), Some("CANCEL")); + } + + #[test] + fn sync_without_query_timeout_omits_field() { + // No caller pin and no spec timeout: omit both so the server uses + // its default (~10s wait + auto-close on success). + let (wait, on_wait) = resolve_wait_timeout(None, None); + assert_eq!(wait, None); + assert_eq!(on_wait, None); + } +} diff --git a/src/statement/spec.rs b/src/statement/spec.rs index 656467d3..e4d708a4 100644 --- a/src/statement/spec.rs +++ b/src/statement/spec.rs @@ -139,6 +139,25 @@ pub struct StatementSpec { /// `session_conf` at execute time; this map wins on key collisions. pub statement_conf: HashMap, + /// Server-side cap on the number of rows returned by this statement, + /// independent of SQL `LIMIT`. Maps directly to the SEA + /// `ExecuteStatement.row_limit` wire field (Python `use_sea`'s + /// `row_limit=` kwarg is the canonical cross-driver surface). `None` + /// omits the field, so the server applies no driver-imposed cap. + pub row_limit: Option, + + /// Server-side statement wait timeout, in whole seconds. Bounds how + /// long the server waits for the statement to reach a terminal state + /// before the wait elapses; on elapse the statement is cancelled + /// (`on_wait_timeout = CANCEL`), surfacing as a timeout to the caller. + /// This is the per-statement server timeout (JDBC `setQueryTimeout` / + /// Python `use_sea`'s `wait_timeout=`), distinct from the transport + /// `overall_timeout`. `None` lets the kernel pick its sync/async + /// default (see `Statement::execute` / `submit`). The SEA wire caps + /// the value at 50s; the kernel forwards the requested value verbatim + /// and lets the server clamp. + pub query_timeout_secs: Option, + /// Result wire format. pub result_format: ResultFormat, } @@ -206,6 +225,20 @@ impl StatementSpec { self } + /// Set the server-side row cap (SEA `row_limit`). `None` clears it. + pub fn row_limit(&mut self, row_limit: Option) -> &mut Self { + self.row_limit = row_limit; + self + } + + /// Set the per-statement server wait timeout in whole seconds. `None` + /// clears it (kernel default applies). See the field docs for the + /// `CANCEL`-on-elapse semantics and the 50s server cap. + pub fn query_timeout_secs(&mut self, secs: Option) -> &mut Self { + self.query_timeout_secs = secs; + self + } + /// Set the result wire format. pub fn result_format(&mut self, fmt: ResultFormat) -> &mut Self { self.result_format = fmt; @@ -224,9 +257,25 @@ mod tests { assert!(s.positional_params.is_empty()); assert!(s.named_params.is_empty()); assert!(s.statement_conf.is_empty()); + // row_limit / query_timeout default to "omit the field" so the + // server applies no driver-imposed cap and its own wait default. + assert!(s.row_limit.is_none()); + assert!(s.query_timeout_secs.is_none()); assert_eq!(s.result_format, ResultFormat::Arrow); } + #[test] + fn row_limit_and_query_timeout_setters() { + let mut s = StatementSpec::new(); + s.row_limit(Some(100)).query_timeout_secs(Some(30)); + assert_eq!(s.row_limit, Some(100)); + assert_eq!(s.query_timeout_secs, Some(30)); + // `None` clears back to the omit-the-field default. + s.row_limit(None).query_timeout_secs(None); + assert!(s.row_limit.is_none()); + assert!(s.query_timeout_secs.is_none()); + } + #[test] fn fluent_setters_compose() -> Result<()> { let mut s = StatementSpec::new();