Skip to content
Open
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
2 changes: 2 additions & 0 deletions NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ changes go in their respective binding's NEXT_CHANGELOG.

### Added

- `ResultStream::try_next_ready_batch()` advances the stream when a batch is ready without blocking. Errors and end-of-stream remain deferred until a normal fetch observes them.

### Changed

### Updated
Expand Down
2 changes: 2 additions & 0 deletions napi/NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ layout, or npm publishing. Pure-kernel changes go in the root

### Changed

- Result fetches pack already-buffered Arrow batches into IPC payloads capped at 16,384 rows, 1MiB of sliced Arrow data (excluding IPC framing), and 16 messages, without waiting for another download. Single oversized batches and schemas containing dictionaries retain one batch per payload.

### Updated

### Fixed
Expand Down
16 changes: 8 additions & 8 deletions napi/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -721,13 +721,13 @@ export interface RawParameterInput {
value?: string
}
/**
* A single Arrow IPC stream payload encoding one record batch (plus
* A single Arrow IPC stream payload encoding one or more record batches (plus
* the schema header so the JS-side reader is stateless).
*/
export interface ArrowBatch {
/**
* Arrow IPC stream payload (schema header + 1 record-batch
* message). Decode with `apache-arrow`'s `RecordBatchReader`.
* Arrow IPC stream payload (schema header + record-batch messages).
* Decode with `apache-arrow`'s `RecordBatchReader`.
*/
ipcBytes: Buffer
}
Expand Down Expand Up @@ -887,10 +887,10 @@ export declare class AsyncResultHandle {
/**
* Pull the next batch of results. Returns `null` when the
* stream is exhausted. The returned `ArrowBatch.ipcBytes` is a
* complete Arrow IPC stream (schema header + 1 record-batch
* message), suitable for handing to `apache-arrow`'s
* `RecordBatchReader`. Byte-identical to the sync
* `Statement.fetchNextBatch()` payload for the same query.
* complete Arrow IPC stream (schema header + one or more record-batch
* messages), suitable for handing to `apache-arrow`'s
* `RecordBatchReader`. Uses the same bounded packing as
* `Statement.fetchNextBatch()`.
* Rejects with `KernelError(InvalidStatementHandle)` after the
* parent `AsyncStatement` is closed (see `AsyncStatement.close()`).
*/
Expand Down Expand Up @@ -1225,7 +1225,7 @@ export declare class Statement {
/**
* Pull the next batch of results. Returns `null` when the stream
* is exhausted. The returned `ArrowBatch.ipcBytes` is a complete
* Arrow IPC stream (schema header + 1 record-batch message)
* Arrow IPC stream (schema header + one or more record-batch messages)
* suitable for handing to `apache-arrow`'s `RecordBatchReader`.
*
* On `Err`, the stream is in an unspecified state — call
Expand Down
34 changes: 10 additions & 24 deletions napi/src/async_statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,11 +60,11 @@ use tokio::sync::Mutex;
use arrow_schema::SchemaRef;
use databricks_sql_kernel::{
AsyncStatementCanceller, Error as KernelError, ExecutedAsyncStatement, ExecutedStatementHandle,
ResultBatch, ResultStream, Statement as KernelStatement,
ResultStream, Statement as KernelStatement,
};

use crate::error::napi_err_from_kernel;
use crate::result::{encode_ipc_stream, ArrowBatch, ArrowSchema};
use crate::result::{encode_ipc_stream, ArrowBatch, ArrowSchema, IpcStream};
use crate::runtime;
use crate::util::guarded;

Expand All @@ -89,7 +89,7 @@ fn closed_err(what: &str) -> napi::Error {
// ───────────────────────── AsyncStatement ─────────────────────────

/// An `AsyncResultHandle`'s stream, shared with its parent `AsyncStatement`.
type ResultSlot = Mutex<Option<ResultStream>>;
type ResultSlot = Mutex<Option<IpcStream<ResultStream>>>;

/// Inner state for the JS-visible `AsyncStatement` wrapper. Same
/// shape rationale as `StatementInner` in `statement.rs`: we hold
Expand Down Expand Up @@ -320,7 +320,7 @@ impl AsyncStatement {
.map_err(napi_err_from_kernel)?;
let statement_id = inner_state.executed_async.statement_id().to_owned();
let schema = stream.schema();
let stream = Arc::new(Mutex::new(Some(stream)));
let stream = Arc::new(Mutex::new(Some(IpcStream::new(stream))));
// Registered while `inner` is held, so a queued `close()` sees it.
results
.lock()
Expand Down Expand Up @@ -473,10 +473,10 @@ impl AsyncResultHandle {

/// Pull the next batch of results. Returns `null` when the
/// stream is exhausted. The returned `ArrowBatch.ipcBytes` is a
/// complete Arrow IPC stream (schema header + 1 record-batch
/// message), suitable for handing to `apache-arrow`'s
/// `RecordBatchReader`. Byte-identical to the sync
/// `Statement.fetchNextBatch()` payload for the same query.
/// complete Arrow IPC stream (schema header + one or more record-batch
/// messages), suitable for handing to `apache-arrow`'s
/// `RecordBatchReader`. Uses the same bounded packing as
/// `Statement.fetchNextBatch()`.
/// Rejects with `KernelError(InvalidStatementHandle)` after the
/// parent `AsyncStatement` is closed (see `AsyncStatement.close()`).
#[napi]
Expand All @@ -488,24 +488,10 @@ impl AsyncResultHandle {
let stream = guard
.as_mut()
.ok_or_else(|| closed_err("AsyncResultHandle"))?;
let maybe_batch = stream.next_batch().await.map_err(napi_err_from_kernel)?;
let Some(batch) = maybe_batch else {
let maybe_bytes = stream.next(&schema, "databricks-sea-native").await?;
let Some(bytes) = maybe_bytes else {
return Ok(None);
};
let record_batch = match batch {
ResultBatch::Arrow(rb) => rb,
_ => {
return Err(napi_err_from_kernel(
KernelError::invalid_argument().message(format!(
"non-Arrow ResultBatch variant from kernel — \
databricks-sea-native v{} cannot decode this batch \
shape, upgrade the binding",
env!("CARGO_PKG_VERSION"),
)),
));
}
};
let bytes = encode_ipc_stream(&schema, Some(record_batch))?;
Ok(Some(ArrowBatch {
ipc_bytes: bytes.into(),
}))
Expand Down
237 changes: 237 additions & 0 deletions napi/src/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -702,6 +702,243 @@ mod tests {
assert_eq!(conn.session_id(), "session-survives-close");
}

async fn packed_statement_observations(server: &MockServer) -> (usize, Vec<serde_json::Value>) {
let requests = server.received_requests().await.unwrap();
let closes = requests
.iter()
.filter(|request| {
request.method.as_str() == "DELETE"
&& request.url.path() == "/api/2.0/sql/statements/stmt-packed-eof"
})
.count();
let events = requests
.iter()
.filter(|request| request.url.path() == "/telemetry-ext")
.flat_map(|request| {
let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap();
body["protoLogs"]
.as_array()
.unwrap()
.iter()
.map(|log| {
serde_json::from_str::<serde_json::Value>(log.as_str().unwrap()).unwrap()
})
.filter(|log| {
log["entry"]["sql_driver_log"]["sql_statement_id"] == "stmt-packed-eof"
})
.collect::<Vec<_>>()
})
.collect();
(closes, events)
}

#[tokio::test]
async fn packed_executed_path_defers_close_and_telemetry_until_consumed() {
use arrow_array::{ArrayRef, Int64Array, RecordBatch};
use arrow_ipc::{reader::StreamReader, writer::StreamWriter};
use databricks_sql_kernel::TelemetryConfig;
use std::time::Duration;

for (early_close, failed_download) in [(false, false), (true, false), (false, true)] {
let server = MockServer::start().await;
let batch = RecordBatch::try_from_iter([(
"n",
Arc::new(Int64Array::from(vec![Some(13), None, Some(-7)])) as ArrayRef,
)])
.unwrap();
let mut ipc = Vec::new();
{
let mut writer = StreamWriter::try_new(&mut ipc, &batch.schema()).unwrap();
for _ in 0..3 {
writer.write(&batch).unwrap();
}
writer.finish().unwrap();
}
Mock::given(method("POST"))
.and(path("/api/2.0/sql/warehouses/test_wh/sessions"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"session_id": "sess-packed-eof"
})))
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path("/chunk"))
.respond_with(ResponseTemplate::new(200).set_body_bytes(ipc.clone()))
.expect(1)
.mount(&server)
.await;
if failed_download {
Mock::given(method("GET"))
.and(path("/failed-chunk"))
.respond_with(
ResponseTemplate::new(500).set_body_string("fixture download failure"),
)
.expect(5)
.mount(&server)
.await;
}
let mut links = vec![json!({
"external_link": format!("{}/chunk", server.uri()),
"expiration": "2099-01-01T00:00:00Z",
"chunk_index": 0, "row_offset": 0, "row_count": 9, "byte_count": ipc.len()
})];
if failed_download {
links.push(json!({
"external_link": format!("{}/failed-chunk", server.uri()),
"expiration": "2099-01-01T00:00:00Z",
"chunk_index": 1, "row_offset": 9, "row_count": 3, "byte_count": ipc.len()
}));
}
Mock::given(method("POST"))
.and(path("/api/2.0/sql/statements"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"statement_id": "stmt-packed-eof",
"status": { "state": "SUCCEEDED" },
"manifest": {
"format": "ARROW_STREAM",
"schema": { "column_count": 1, "columns": [{
"name": "n", "type_name": "BIGINT", "type_text": "BIGINT", "position": 0
}] },
"total_chunk_count": links.len(), "total_row_count": if failed_download { 12 } else { 9 },
"total_byte_count": ipc.len(), "truncated": false
},
"result": { "external_links": links }
})))
.mount(&server)
.await;
for endpoint in [
"/api/2.0/sql/statements/stmt-packed-eof",
"/api/2.0/sql/sessions/sess-packed-eof",
] {
Mock::given(method("DELETE"))
.and(path(endpoint))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({})))
.expect(1)
.mount(&server)
.await;
}
Mock::given(method("POST"))
.and(path("/telemetry-ext"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({})))
.mount(&server)
.await;
let mut telemetry = TelemetryConfig::default();
telemetry.set_enabled(true);
telemetry.batch_size = 1;
telemetry.flush_interval = Duration::from_millis(10);
let mut http = databricks_sql_kernel::HttpConfig::default();
http.retry_max_retries = 0;
let session = Session::builder()
.http_path(server.uri(), "/sql/1.0/warehouses/test_wh")
.auth(AuthConfig::Pat {
token: "test-token".into(),
identity_federation_client_id: None,
})
.telemetry(telemetry)
.http(http)
.open()
.await
.unwrap();
let connection = Connection {
session_id: session.session_id().to_owned(),
inner: Arc::new(Mutex::new(Some(session))),
};
let statement = connection
.execute_statement("SELECT n".into(), None)
.await
.unwrap();
let payload = statement.fetch_next_batch().await.unwrap().unwrap();
let batches: Vec<_> = StreamReader::try_new(payload.ipc_bytes.as_ref(), None)
.unwrap()
.collect::<Result<_, _>>()
.unwrap();
assert_eq!(batches.len(), 3);
assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::<usize>(), 9);
for actual in &batches {
assert_eq!(
actual
.column(0)
.as_any()
.downcast_ref::<Int64Array>()
.unwrap(),
batch
.column(0)
.as_any()
.downcast_ref::<Int64Array>()
.unwrap()
);
}
// The fetch mutex is the completion barrier. Inspect synchronous EOF
// state so a queued-but-not-yet-sent DELETE cannot hide an early close.
assert!(statement.has_current_batch_for_test().await);
let (closes, events) = packed_statement_observations(&server).await;
assert_eq!(closes, 0, "lookahead must not close before the null fetch");
assert!(
events.is_empty(),
"lookahead must not finalize statement telemetry"
);

let mut delivered_error_code = None;
if failed_download {
let error =
tokio::time::timeout(Duration::from_secs(15), statement.fetch_next_batch())
.await
.expect("bounded retry failure")
.err()
.expect("second fetch must deliver the failed download");
assert!(
error.reason.contains("NetworkError") || error.reason.contains("Internal"),
"{}",
error.reason
);
let envelope: serde_json::Value = serde_json::from_str(
error
.reason
.strip_prefix(crate::error::ERROR_SENTINEL)
.unwrap(),
)
.unwrap();
delivered_error_code = Some(envelope["code"].as_str().unwrap().to_owned());
assert_eq!(
packed_statement_observations(&server).await.0,
0,
"a delivered download error must not auto-close"
);
statement.close().await.unwrap();
} else if early_close {
statement.close().await.unwrap();
} else {
assert!(statement.fetch_next_batch().await.unwrap().is_none());
}
let completed = tokio::time::timeout(Duration::from_secs(2), async {
loop {
let (closes, events) = packed_statement_observations(&server).await;
if closes == 1 && events.len() == 1 {
let latency = &events[0]["entry"]["sql_driver_log"]["sql_operation"]
["result_latency"]["result_set_consumption_latency_millis"];
assert_eq!(latency.is_null(), early_close);
let error_name =
&events[0]["entry"]["sql_driver_log"]["error_info"]["error_name"];
assert_eq!(error_name.as_str(), delivered_error_code.as_deref());
break;
}
tokio::time::sleep(Duration::from_millis(5)).await;
}
})
.await;
assert!(
completed.is_ok(),
"completion early_close={early_close} failed_download={failed_download}: {:?}",
packed_statement_observations(&server).await
);
statement.close().await.unwrap();
connection.close().await.unwrap();
let (closes, events) = packed_statement_observations(&server).await;
assert_eq!(closes, 1);
assert_eq!(events.len(), 1, "close must not duplicate error telemetry");
}
}

#[tokio::test]
async fn build_statement_forwards_raw_params_and_rejects_mixed_binding() {
let server = MockServer::start().await;
Expand Down
Loading
Loading