Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 40 additions & 4 deletions napi/src/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String, String>` whose iteration order is
Expand Down Expand Up @@ -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<HashMap<String, String>>,
/// 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<i64>,
/// 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<u32>,
}

/// Closed-state error builder. Mirrors `statement::statement_closed_err`
Expand Down Expand Up @@ -227,6 +239,10 @@ impl Connection {
options: Option<ExecuteOptions>,
) -> napi::Result<Statement> {
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
Expand All @@ -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.
Expand Down Expand Up @@ -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");
Expand All @@ -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();
Expand All @@ -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();
Expand All @@ -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();
Expand All @@ -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();
Expand All @@ -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!(
Expand All @@ -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();
Expand Down
107 changes: 100 additions & 7 deletions src/reader/inline/provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,37 @@ pub struct InlineArrowProvider {
schema: Option<SchemaRef>,
}

/// 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<RecordBatch>,
total_row_count: Option<i64>,
) -> Vec<RecordBatch> {
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.
///
Expand All @@ -46,14 +77,26 @@ 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
///
/// # Errors
/// - If decompression fails
/// - If Arrow IPC parsing fails
pub fn new(attachment: Vec<u8>, compression: CompressionCodec) -> Result<Self> {
pub fn new(
attachment: Vec<u8>,
compression: CompressionCodec,
total_row_count: Option<i64>,
) -> Result<Self> {
if attachment.is_empty() {
tracing::debug!("Empty attachment, creating empty provider");
return Ok(Self {
Expand All @@ -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!(
Expand Down Expand Up @@ -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());
Expand Down Expand Up @@ -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);
Expand All @@ -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();
Expand All @@ -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());
Expand All @@ -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::<usize>(), 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::<usize>(), 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::<usize>(), 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"
);
}
}
16 changes: 12 additions & 4 deletions src/reader/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

Expand Down Expand Up @@ -304,14 +309,17 @@ impl ResultReaderFactory {
&self,
inline_data: &[u8],
compression: CompressionCodec,
total_row_count: Option<i64>,
) -> Result<Box<dyn ResultReader + Send>> {
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)))
}
Expand Down
Loading