Skip to content
Merged
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
11 changes: 4 additions & 7 deletions napi/src/async_statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,8 @@
//! wrapper applied to every entry here covers the
//! V8-panic-across-boundary case on top of both.
//!
//! `close()` routes through the `ExecutedStatementHandle` trait the
//! kernel implements for both `ExecutedStatement` and
//! `ExecutedAsyncStatement`, holding `inner.lock()` like the sync path.
//! `close()` routes through the kernel's concrete async handle close,
//! holding `inner.lock()` like the sync path.
//! `cancel()` is the one method that does *not* take the lock — it
//! fires through a detached `AsyncStatementCanceller` (session +
//! statement_id) so it can interrupt an in-flight `awaitResult()`
Expand Down Expand Up @@ -362,16 +361,14 @@ impl AsyncStatement {
let mut guard = inner.lock().await;
guard.take()
};
let Some(inner_state) = taken else {
let Some(mut inner_state) = taken else {
return Ok(());
};
// Flip the lock-free flag once we own the close so a racing
// lock-free `cancel()` short-circuits to InvalidStatementHandle
// rather than firing a wire cancel on a closing statement.
closed.store(true, Ordering::Release);
inner_state
.executed_async
.close()
ExecutedAsyncStatement::close(&mut inner_state.executed_async)
.await
.map_err(napi_err_from_kernel)
})
Expand Down
2 changes: 1 addition & 1 deletion pyo3/src/executed_async.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ impl ExecutedAsyncStatement {
return Ok(());
};
let runtime = inner.runtime.clone();
let res = run_kernel!(py, runtime, inner.exec.close());
let res = run_kernel!(py, runtime, KExecutedAsyncStatement::close(&mut inner.exec));
self.inner = None;
res.map(|_| ())
}
Expand Down
49 changes: 49 additions & 0 deletions src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2424,6 +2424,55 @@ mod is_open_tests {
);
}

#[tokio::test]
async fn async_statement_close_finalizes_partial_result_telemetry() {
let server = MockServer::start().await;
mount_session_create_delete(&server, "sess-telemetry-async-partial-close").await;
mount_close_any_statement(&server).await;
mount_execute(&server, running_body("stmt-telemetry-async-partial-close")).await;
mount_status(
&server,
"stmt-telemetry-async-partial-close",
succeeded_inline_body(
"stmt-telemetry-async-partial-close",
&int64_batch("n", vec![1]),
),
)
.await;
let exporter = CapturingTelemetryExporter::default();
let telemetry = TelemetryConfig {
enabled: true,
..Default::default()
}
.with_exporter(std::sync::Arc::new(exporter.clone()));
let session =
telemetry_test_session(&server, "sess-telemetry-async-partial-close", telemetry).await;

let mut stmt = session.statement();
stmt.spec().sql("SELECT 1 AS n");
let mut async_exec = stmt.submit().await.expect("submit succeeds");
let mut stream = async_exec.await_result().await.expect("await succeeds");
assert!(stream.next_batch().await.expect("first batch").is_some());

async_exec.close().await.expect("close succeeds");
session.close().await.expect("close succeeds");

let async_statement_logs = exported_logs(&exporter)
.into_iter()
.filter(|log| operation_type(log) == Some("EXECUTE_STATEMENT_ASYNC"))
.collect::<Vec<_>>();
assert_eq!(
async_statement_logs.len(),
1,
"partial async result close should finalize telemetry once even while \
the result stream is still live"
);
assert_eq!(
async_statement_logs[0]["entry"]["sql_driver_log"]["sql_statement_id"],
"stmt-telemetry-async-partial-close"
);
}

#[tokio::test]
async fn async_statement_status_failure_exports_error_telemetry() {
let server = MockServer::start().await;
Expand Down
21 changes: 19 additions & 2 deletions src/statement/executed_async.rs
Original file line number Diff line number Diff line change
Expand Up @@ -731,6 +731,25 @@ impl ExecutedStatementHandle for ExecutedAsyncStatement {
}

async fn close(&self) -> Result<()> {
self.close_server_statement().await
}
}

impl ExecutedAsyncStatement {
/// Explicit close for concrete async statements.
///
/// Once [`await_result`](Self::await_result) / [`fetch_result`](Self::fetch_result)
/// returns a [`ResultStream`], that stream owns success finalization so full
/// result consumption can include result metrics. Explicitly closing the owning
/// async statement is the binding-visible lifecycle boundary, though, so finalize
/// here as a deterministic backstop for partial-fetch callers that keep the stream
/// alive past session close.
pub async fn close(&mut self) -> Result<()> {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium — The new finalizing close(&mut self) is only reached via UFCS or when the ExecutedStatementHandle trait is out of scope — otherwise the non-finalizing trait close(&self) silently wins, reintroducing the RCA-29 telemetry gap for those callers.

Rust method resolution tries the &self receiver candidate before &mut self. When ExecutedStatementHandle is in scope, exec.close() finds the trait's close(&self) at the &Self step and selects it (server-close only, no finalize) — the inherent &mut self method is never considered. The napi and pyo3 bindings dodge this correctly with UFCS (ExecutedAsyncStatement::close(&mut …)), and the new session.rs test works only because that test module keeps the trait out of scope and binds mut. But:

  • A direct Rust consumer that does use databricks_sql_kernel::ExecutedStatementHandle; (needed for cancel()) and then calls exec.close() gets the non-finalizing close — the exact partial-fetch telemetry loss this PR sets out to fix.
  • The C ABI closes through Box<dyn ExecutedStatementHandle> (per src/statement/handle.rs:32), which can only dispatch to close(&self), so async statements closed via the trait object never hit the new backstop.

In those paths telemetry still eventually flushes when the ResultStream drops, so this is a determinism regression rather than guaranteed loss, and it mirrors the pre-existing sync pattern. Worth a doc note on the inherent method ("trait-object / trait-in-scope callers get the non-finalizing close; use UFCS") so the guarantee isn't silently lost by a future caller.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's okay for now, all 3 drivers pass the telemetry emitted on statement closure test. How they work may not be the same but it's good for now for PuPr.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed the tests passing across all three drivers is a reasonable bar for PuPr, and this was always flagged as a determinism regression rather than guaranteed loss — not a blocker. The reason I'm keeping it open is that "how they work may not be the same" is exactly the trap: the trait-in-scope and Box<dyn ExecutedStatementHandle> paths still resolve to the non-finalizing close(&self), and nothing in the current code records that. A one-line doc note on the inherent close(&mut self) ("trait-object / trait-in-scope callers get the non-finalizing close; use UFCS to finalize") would preserve the guarantee for the next caller at effectively zero cost. Happy to leave it as a post-PuPr follow-up rather than a merge gate.

self.statement_telemetry.finalize(None);
self.close_server_statement().await
}

async fn close_server_statement(&self) -> Result<()> {
// Idempotent on success: a prior successful close sets
// `closed=true` and subsequent calls short-circuit.
//
Expand Down Expand Up @@ -767,9 +786,7 @@ impl ExecutedStatementHandle for ExecutedAsyncStatement {
.instrument(self.session.log_span().clone())
.await
}
}

impl ExecutedAsyncStatement {
/// Produce a detached [`AsyncStatementCanceller`] that can fire a
/// server-side cancel for this statement *without borrowing the
/// handle*.
Expand Down
Loading