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 @@ -13,6 +13,8 @@ changes go in their respective binding's NEXT_CHANGELOG.

### Changed

Once any result stream of an asynchronous execution reaches successful EOF, closing the execution releases ownership immediately and cleans up the server statement in the background, without reporting cleanup errors. This also applies when another stream of that execution is unread or partly read; otherwise close still waits for server cleanup.

### Updated

### Fixed
Expand Down
5 changes: 4 additions & 1 deletion include/databricks_kernel.h
Original file line number Diff line number Diff line change
Expand Up @@ -954,7 +954,10 @@ KernelStatusCode kernel_executed_async_statement_canceller_free(
kernel_executed_async_statement_canceller_t* canceller);

/* Close the server operation and consume the async handle. The handle is
* consumed even when close returns an error. */
* consumed even when close returns an error. Once any result stream of this
* execution reaches successful EOF, cleanup runs in the background, even if
* another stream is unread or partly read. Background cleanup errors are not
* returned and do not trigger a Drop retry. */
KernelStatusCode kernel_executed_async_statement_close(
kernel_executed_async_statement_t* exec);

Expand Down
6 changes: 5 additions & 1 deletion napi/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -852,7 +852,11 @@ export declare class AsyncStatement {
* inner is already `None`, so a JS-side retry sees the
* closed-handle short-circuit and returns `Ok(())` without
* re-attempting the wire call. The kernel's own `Drop`
* fire-and-forget retry runs once in the background.
* fire-and-forget retry runs once in the background after an awaited
* close fails. Once any stream of this execution reaches successful
* EOF, close schedules background cleanup instead: cleanup errors are
* not returned and do not trigger a `Drop` retry, even if another
* stream is unread or partly read.
*
* Also invalidates the handles `awaitResult()` returned: their
* `fetchNextBatch()` then rejects with `InvalidStatementHandle`,
Expand Down
6 changes: 5 additions & 1 deletion napi/src/async_statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -372,7 +372,11 @@ impl AsyncStatement {
/// inner is already `None`, so a JS-side retry sees the
/// closed-handle short-circuit and returns `Ok(())` without
/// re-attempting the wire call. The kernel's own `Drop`
/// fire-and-forget retry runs once in the background.
/// fire-and-forget retry runs once in the background after an awaited
/// close fails. Once any stream of this execution reaches successful
/// EOF, close schedules background cleanup instead: cleanup errors are
/// not returned and do not trigger a `Drop` retry, even if another
/// stream is unread or partly read.
///
/// Also invalidates the handles `awaitResult()` returned: their
/// `fetchNextBatch()` then rejects with `InvalidStatementHandle`,
Expand Down
69 changes: 33 additions & 36 deletions src/client/sea.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,35 @@ impl SeaRestTransport {
}
}

async fn close_statement_impl(&self, statement_id: &str, report_failure: bool) -> Result<()> {
let url = format!("{}/statements/{}", self.base_url(), statement_id);
debug!("Closing statement at {}", url);
let request = self
.http_client
.inner()
.request(Method::DELETE, &url)
.build()
.map_err(|error| {
Error::invalid_argument().message(format!("Failed to build request: {error}"))
})?;
if let Err(error) = self
.http_client
.execute(request, RequestType::CloseStatement)
.await
{
if report_failure {
crate::klog::warn!(
statement_id = %statement_id,
error = %error,
"close_statement failed after HTTP retries; surfacing to caller (Drop fallback close will run)"
);
}
return Err(error);
}
debug!("Closed statement: {}", statement_id);
Ok(())
}

/// Set the reader factory and runtime handle. Must be called once after wrapping in `Arc`.
pub fn set_reader_factory(
&self,
Expand Down Expand Up @@ -1596,43 +1625,11 @@ impl Transport for SeaRestTransport {
}

async fn close_statement(&self, statement_id: &str) -> Result<()> {
let url = format!("{}/statements/{}", self.base_url(), statement_id);

debug!("Closing statement at {}", url);

let request = self
.http_client
.inner()
.request(Method::DELETE, &url)
.build()
.map_err(|e| {
Error::invalid_argument().message(format!("Failed to build request: {e}"))
})?;

// Surface the wire error so the caller's retry-on-failure path can
// run — `ExecutedStatement::close` / `ExecutedAsyncStatement::close`
// only flip their `closed` flag on success, so a swallowed error here
// would make their store-on-success semantics dead code (and a failed
// explicit close would look like it succeeded). The HTTP client has
// already applied the SEA retry policy, so callers see only the
// post-retry result; the `Drop` fire-and-forget fallback close still
// runs on the kernel side if the explicit close errored.
if let Err(e) = self
.http_client
.execute(request, RequestType::CloseStatement)
.await
{
crate::klog::warn!(
statement_id = %statement_id,
error = %e,
"close_statement failed after HTTP retries; surfacing to caller (Drop fallback close will run)"
);
return Err(e);
}

debug!("Closed statement: {}", statement_id);
self.close_statement_impl(statement_id, true).await
}

Ok(())
async fn close_statement_in_background(&self, statement_id: &str) -> Result<()> {
self.close_statement_impl(statement_id, false).await
}

// --- Metadata ---
Expand Down
5 changes: 5 additions & 0 deletions src/client/transport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -418,6 +418,11 @@ pub(crate) trait Transport: Send + Sync + std::fmt::Debug {
/// Close/cleanup a statement (release server resources).
async fn close_statement(&self, statement_id: &str) -> Result<()>;

/// Close a statement whose background caller reports cleanup failures.
async fn close_statement_in_background(&self, statement_id: &str) -> Result<()> {
self.close_statement(statement_id).await
}

// --- Metadata ---

/// List all catalogs.
Expand Down
129 changes: 127 additions & 2 deletions src/result_stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ use arrow_array::types::{
use arrow_array::{Array, RecordBatch};
use arrow_schema::{DataType, Schema, TimeUnit};
use chrono::{NaiveDate, NaiveDateTime};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;

/// Cheap-clone reference to a result schema. The kernel hands one
Expand Down Expand Up @@ -493,6 +494,7 @@ pub struct ResultStream {
close_guard: Option<StatementCloseGuard>,

telemetry: Option<ResultStreamTelemetry>,
drained: Option<Arc<AtomicBool>>,
}

struct ResultStreamTelemetry {
Expand Down Expand Up @@ -607,6 +609,7 @@ impl ResultStream {
current_row_idx: 0,
exhausted: false,
close_guard: None,
drained: None,
telemetry: None,
})
}
Expand Down Expand Up @@ -642,6 +645,10 @@ impl ResultStream {
self.telemetry = Some(ResultStreamTelemetry::new(telemetry));
}

pub(crate) fn attach_drain_signal(&mut self, drained: Arc<AtomicBool>) {
self.drained = Some(drained);
}

fn reader_metrics(&self) -> Option<ResultReaderMetrics> {
self.reader.as_ref().and_then(|reader| reader.metrics())
}
Expand All @@ -665,10 +672,18 @@ impl ResultStream {
/// `consumed = false` so an abandoned stream doesn't report
/// think-time as consumption latency.
fn finalize_telemetry(&mut self, error: Option<&Error>) {
if error.is_some() {
self.drained = None;
}
let metrics = self.reader_metrics();
if let Some(telemetry) = &mut self.telemetry {
telemetry.finish(metrics, error, true);
}
if self.exhausted && error.is_none() {
if let Some(drained) = self.drained.take() {
drained.store(true, Ordering::Release);
}
}
}

/// Install `batch` as the current batch: buffer it, reset the row
Expand Down Expand Up @@ -714,7 +729,11 @@ impl ResultStream {
// A batch buffered by `peek_first_batch` is replayed here first,
// so a non-consuming peek doesn't steal it from the caller.
if let Some(batch) = self.prefetched.take() {
self.set_current_batch(batch.map_err(|error| *error)?);
let batch = batch.map_err(|error| {
self.drained = None;
*error
})?;
self.set_current_batch(batch);
return Ok(self.current.as_ref());
}
if self.exhausted {
Expand Down Expand Up @@ -748,7 +767,11 @@ impl ResultStream {
/// network or background-prefetch progress.
pub fn try_next_batch(&mut self) -> Result<TryNextBatch<'_>> {
if let Some(batch) = self.prefetched.take() {
self.set_current_batch(batch.map_err(|error| *error)?);
let batch = batch.map_err(|error| {
self.drained = None;
*error
})?;
self.set_current_batch(batch);
return Ok(TryNextBatch::Ready(
self.current.as_ref().expect("batch was just installed"),
));
Expand Down Expand Up @@ -930,6 +953,7 @@ impl ResultStream {
.expect("ResultStream reader is present until into_owned_batches consumes it"),
prefetched,
telemetry: self.telemetry.take(),
drained: self.drained.take(),
done: false,
}
}
Expand Down Expand Up @@ -959,6 +983,7 @@ pub struct OwnedBatchIter {
reader: Box<dyn ResultReader>,
prefetched: Prefetched<RecordBatch>,
telemetry: Option<ResultStreamTelemetry>,
drained: Option<Arc<AtomicBool>>,
done: bool,
}

Expand Down Expand Up @@ -1004,6 +1029,9 @@ impl Iterator for OwnedBatchIter {
if let Some(telemetry) = &mut self.telemetry {
telemetry.finish(self.reader.metrics(), None, true);
}
if let Some(drained) = self.drained.take() {
drained.store(true, Ordering::Release);
}
None
}
Err(e) => {
Expand Down Expand Up @@ -1415,6 +1443,103 @@ mod tests {
assert!(iter.next().is_none(), "still None on subsequent calls");
}

#[tokio::test]
async fn drain_signal_requires_successful_exhaustion() {
for mode in [
"next",
"try",
"owned",
"drop",
"error",
"try-error",
"peek-error-next",
"peek-error-try",
"peek-empty",
"finalize-undrained",
] {
let signal = Arc::new(AtomicBool::new(false));
let batch = RecordBatch::try_new(
schema_for(vec![Field::new("n", DataType::Int64, true)]),
vec![Arc::new(Int64Array::from(vec![Some(71), None, Some(-19)]))],
)
.unwrap();
let mut stream = if mode.contains("error") {
stream_with_one_shot_error().await
} else if mode == "peek-empty" {
ResultStream::from_reader(Box::new(InMemoryReader::new(batch.schema(), vec![])))
.await
.unwrap()
} else {
stream_with(batch.clone()).await
};
stream.attach_drain_signal(Arc::clone(&signal));
assert!(!signal.load(Ordering::Acquire));
match mode {
"next" => {
assert!(stream.next_batch().await.unwrap().is_some());
assert!(!signal.load(Ordering::Acquire));
assert!(stream.next_batch().await.unwrap().is_none());
}
"try" => {
assert!(matches!(
stream.try_next_batch().unwrap(),
TryNextBatch::Ready(_)
));
assert!(!signal.load(Ordering::Acquire));
assert!(matches!(
stream.try_next_batch().unwrap(),
TryNextBatch::End
));
}
"owned" => {
let mut batches = stream.into_owned_batches();
assert_eq!(batches.next().unwrap().unwrap(), batch);
assert!(!signal.load(Ordering::Acquire));
assert!(batches.next().is_none());
}
"peek-empty" => {
assert!(stream.peek_first_batch().await.unwrap().is_none());
assert!(!signal.load(Ordering::Acquire));
assert!(stream.next_batch().await.unwrap().is_none());
}
"finalize-undrained" => stream.finalize_telemetry(None),
"error" => {
assert!(stream.next_batch().await.is_err());
assert!(stream.next_batch().await.unwrap().is_none());
assert!(matches!(
stream.try_next_batch().unwrap(),
TryNextBatch::End
));
}
"try-error" => {
assert!(stream.try_next_batch().is_err());
assert!(matches!(
stream.try_next_batch().unwrap(),
TryNextBatch::End
));
assert!(stream.next_batch().await.unwrap().is_none());
}
"peek-error-next" | "peek-error-try" => {
assert!(stream.peek_first_batch().await.is_err());
stream.attach_drain_signal(Arc::clone(&signal));
if mode == "peek-error-next" {
assert!(stream.next_batch().await.is_err());
} else {
assert!(stream.try_next_batch().is_err());
}
assert!(stream.next_batch().await.unwrap().is_none());
}
"drop" => drop(stream),
_ => unreachable!(),
}
assert_eq!(
signal.load(Ordering::Acquire),
!matches!(mode, "drop" | "finalize-undrained") && !mode.contains("error"),
"{mode}"
);
}
}

#[tokio::test]
async fn into_owned_batches_stops_after_error() {
// ErrorReader yields one Err then would yield None; iterator
Expand Down
8 changes: 6 additions & 2 deletions src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ pub(crate) struct SessionInner {
/// `false`, so [`Drop`] retries via its fire-and-forget path —
/// transient `delete_session` failures don't leak the server-
/// side session.
closed: std::sync::atomic::AtomicBool,
closed: Arc<std::sync::atomic::AtomicBool>,

/// Client-tracked autocommit state. `true` (the default) means every
/// statement auto-commits at the server; `false` means statements run
Expand Down Expand Up @@ -170,6 +170,10 @@ impl SessionInner {
&self.session_id
}

pub(crate) fn closed_flag(&self) -> Arc<std::sync::atomic::AtomicBool> {
Arc::clone(&self.closed)
}

/// Typed feature-flag reader for kernel-internal consumers such as
/// statements and result handling. Reads use the process-wide cache.
// This accessor intentionally precedes its first kernel-owned consumer.
Expand Down Expand Up @@ -479,7 +483,7 @@ impl Session {
log_span,
telemetry,
feature_flags,
closed: std::sync::atomic::AtomicBool::new(false),
closed: Arc::new(std::sync::atomic::AtomicBool::new(false)),
// Autocommit defaults to on (every statement commits); a
// caller opts into explicit transactions via set_autocommit.
autocommit: std::sync::atomic::AtomicBool::new(true),
Expand Down
Loading
Loading