Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
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
3 changes: 3 additions & 0 deletions NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ 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 returning cleanup errors, even if another stream is unread or partly read; otherwise close still waits for server cleanup.
- After a drained close, same-session attach/status and the owner's result reads wait for background CloseStatement before reading server state; independent sessions may still observe SUCCEEDED until cleanup finishes. Drop cleanup remains fire-and-forget and does not delay observers. After Session::close, async statements no longer send CloseStatement on close or Drop; the server reclaims them with the session.

### Updated

### Fixed
Expand Down
4 changes: 3 additions & 1 deletion include/databricks_kernel.h
Original file line number Diff line number Diff line change
Expand Up @@ -1011,7 +1011,9 @@ 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. After a successful drain, close
* returns without waiting for server cleanup. 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
2 changes: 2 additions & 0 deletions napi/NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ layout, or npm publishing. Pure-kernel changes go in the root

### Changed

- After a drained result, `close()` returns without waiting for server cleanup and does not reject on cleanup failure.

### Updated

### Fixed
Expand Down
5 changes: 4 additions & 1 deletion napi/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -862,7 +862,10 @@ 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. After a successful drain, close returns without waiting
* for server cleanup: cleanup errors are not returned and do not trigger
* a `Drop` retry. `status()` after close rejects with `InvalidStatementHandle`.
*
* Also invalidates the handles `awaitResult()` returned: their
* `fetchNextBatch()` then rejects with `InvalidStatementHandle`,
Expand Down
5 changes: 4 additions & 1 deletion napi/src/async_statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -372,7 +372,10 @@ 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. After a successful drain, close returns without waiting
/// for server cleanup: cleanup errors are not returned and do not trigger
/// a `Drop` retry. `status()` after close rejects with `InvalidStatementHandle`.
///
/// Also invalidates the handles `awaitResult()` returned: their
/// `fetchNextBatch()` then rejects with `InvalidStatementHandle`,
Expand Down
2 changes: 2 additions & 0 deletions pyo3/NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ changes go in the root `NEXT_CHANGELOG.md`.

### Changed

- After a drained result, `close()` returns without waiting for server cleanup and does not raise on cleanup failure.

### Updated

### Fixed
Expand Down
7 changes: 6 additions & 1 deletion pyo3/src/executed_async.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,12 @@ impl ExecutedAsyncStatement {
Ok(())
}

/// Close the statement (server-side `CloseStatement`). Idempotent.
/// Idempotent close: after successful EOF on any stream, best-effort cleanup runs
/// in the background even if another stream is unread or partly read, without
/// returning cleanup errors or retrying them on Drop; otherwise close awaits
/// server cleanup. Same-session attach/status waits for background
/// `CloseStatement` before reading server state (`CLOSED` on success);
/// independent sessions may still observe `SUCCEEDED` until cleanup finishes.
fn close(&mut self, py: Python<'_>) -> PyResult<()> {
let Some(inner) = self.inner.as_mut() else {
return Ok(());
Expand Down
69 changes: 33 additions & 36 deletions src/client/sea.rs
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,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 @@ -1627,43 +1656,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
7 changes: 7 additions & 0 deletions src/client/transport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -436,6 +436,13 @@ 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 without logging failures; the background caller reports them.
/// Implementations should return errors without logging. The default falls back
/// to `close_statement`, which may log failures itself.
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
Loading
Loading