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
46 changes: 43 additions & 3 deletions src/result_stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -486,14 +486,44 @@ pub struct ResultStream {
close_guard: Option<StatementCloseGuard>,
}

/// Fire-and-forget `CloseStatement`-on-Drop for a server statement that
/// no other handle owns (the metadata path). Mirrors the
/// `ExecutedStatement` Drop cleanup, scoped to the bare-stream case.
/// `CloseStatement` cleanup for a server statement that no other handle
/// owns (the metadata path). Mirrors the `ExecutedStatement` cleanup,
/// scoped to the bare-stream case.
///
/// Preferred path: the owning [`ResultStream`] calls
/// [`close_now`](Self::close_now) **synchronously** when its `next_batch`
/// drains to end-of-stream, so the `DELETE /statements/<id>` is ordered
/// before the caller's next request (issue #170). `close_now` empties
/// `statement_id`, which disarms the `Drop` backstop below. The `Drop`
/// stays fire-and-forget for the not-fully-drained case (abandoned
/// metadata stream), where there is no `.await` to hang the close on.
struct StatementCloseGuard {
session: Arc<SessionInner>,
statement_id: String,
}

impl StatementCloseGuard {
/// Synchronously close the statement and disarm the `Drop` backstop.
/// A wire failure is logged and swallowed — the metadata result is
/// already delivered and the server reclaims the handle at session
/// expiry. Idempotent: a second call (or a `Drop` after this) sees an
/// empty id and no-ops.
async fn close_now(&mut self) {
let stmt_id = std::mem::take(&mut self.statement_id);
if stmt_id.is_empty() {
return;
}
if let Err(e) = self.session.transport().close_statement(&stmt_id).await {
crate::klog::warn!(
"synchronous close_statement for metadata stream {} failed: {} \
(server reclaims on session close)",
stmt_id,
e
);
}
}
}

impl Drop for StatementCloseGuard {
fn drop(&mut self) {
let transport = Arc::clone(self.session.transport());
Expand Down Expand Up @@ -617,6 +647,16 @@ impl ResultStream {
self.current = None;
self.current_row_idx = 0;
self.exhausted = true;
// Metadata path (`close_guard` is `Some`): close the
// server statement synchronously now that the stream is
// drained, so the `DELETE` is ordered before the caller's
// next request rather than racing it on a spawned task
// (issue #170). The data path leaves `close_guard` `None`
// — there the owning `ExecutedStatement` handles the
// close. `close_now` disarms the `Drop` backstop.
if let Some(guard) = self.close_guard.as_mut() {
guard.close_now().await;
}
Ok(None)
}
}
Expand Down
72 changes: 63 additions & 9 deletions src/statement/executed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,11 +115,24 @@ impl ExecutedStatement {
/// when the stream is exhausted**.
///
/// Identical to `result_stream_mut().next_batch()` except that the
/// first time it observes end-of-stream (`Ok(None)`), it spawns a
/// fire-and-forget `CloseStatement` (guarded by the shared `closed`
/// flag, so `Drop` / explicit `close()` never double-fire).
/// first time it observes end-of-stream (`Ok(None)`), it closes the
/// server statement **synchronously** — awaiting the `CloseStatement`
/// before returning `Ok(None)` — guarded by the shared `closed` flag
/// so `Drop` / explicit `close()` never double-fire.
///
/// Why this matters: for a large CloudFetch result whose chunk
/// Why synchronous (issue #170): a detached fire-and-forget close
/// (`runtime.spawn`) is not ordered w.r.t. the caller's next request
/// on the same session, so the `DELETE /statements/<id>` races the
/// next `ExecuteStatement` — non-deterministic wire ordering that
/// breaks ordered replay/proxy tooling. Awaiting here lands the
/// close on the wire before the drain returns, so the next request
/// the caller issues is naturally ordered after it (matching C# ADBC
/// and databricks-jdbc, which close synchronously at result-set
/// close). The true `Drop`-without-drain fallback stays
/// fire-and-forget ([`Self::spawn_close_if_open`]) — `Drop` can't
/// `.await`.
///
/// Why close here at all: for a large CloudFetch result whose chunk
/// *links* are paginated (`all_fetched=false`), the reader fetches
/// later links lazily via `get_result_chunks` against the live
/// server statement *during consumption*. Closing the statement
Expand All @@ -130,6 +143,14 @@ impl ExecutedStatement {
/// always safe, and the connector no longer needs to close the
/// statement on the sync path at all.
///
/// A close failure at drain is intentionally swallowed (logged, not
/// returned): the drained result is already fully delivered, the
/// server reclaims the handle at session expiry, and surfacing a
/// cleanup error as an end-of-stream error would be a spurious
/// failure on an otherwise-successful fetch. The `closed` flag is
/// still flipped (see [`Self::close_if_open`]), so `Drop` does not
/// re-attempt.
///
/// Bindings should call this instead of
/// `result_stream_mut().next_batch()` so the auto-close fires.
pub async fn next_batch(&mut self) -> Result<Option<&ResultBatch>> {
Expand All @@ -146,15 +167,48 @@ impl ExecutedStatement {
return Ok(self.result_stream.current());
}
// End-of-stream: every lazy link fetch has completed, so the
// server statement is safe to close.
self.spawn_close_if_open();
// server statement is safe to close. Await it so the DELETE is
// ordered before the caller's next request (issue #170).
self.close_if_open().await;
Ok(None)
}

/// Close the server statement **synchronously** (awaiting the
/// `CloseStatement`) unless it is already closed (`closed` flag).
/// The auto-close-on-drain path ([`Self::next_batch`]) uses this so
/// the DELETE is ordered w.r.t. the caller's next request. The
/// `swap` claims the close so `Drop` / explicit `close()` skip it.
///
/// A wire failure is logged and swallowed (not returned): the drain
/// has already delivered the full result, and the server reclaims
/// the handle at session expiry. The `closed` flag stays set so
/// `Drop` does not re-fire — accepting a rare leaked handle over a
/// duplicate close on every drain.
async fn close_if_open(&self) {
if self.closed.swap(true, Ordering::AcqRel) {
return;
}
if let Err(e) = self
.session
.transport()
.close_statement(&self.statement_id)
.await

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Low — Cancellation of next_batch at the drain-close await now leaks the handle, where the old fire-and-forget path did not.

close_if_open flips closed to true (the swap) before awaiting close_statement. If the next_batch future is dropped at that await point (e.g. the caller wraps drain in a tokio::select! / timeout), the DELETE never lands, yet Drop's spawn_close_if_open observes closed=true and skips — so the server statement leaks until session expiry.

Before this PR, next_batch called the synchronous spawn_close_if_open() and returned immediately; the spawned close ran on the runtime independently of the next_batch future, so cancelling the drain did not abandon the close. Awaiting inline reintroduces that coupling.

This is consistent with the PR's documented "accept a rare leaked handle over a duplicate close" tradeoff for wire failures, and cancellation mid-drain is uncommon — hence low. But it is a real behavior regression from the prior fire-and-forget path that the doc-comment's failure rationale doesn't cover (cancellation is not a wire failure). Worth a sentence in the close_if_open doc noting that a cancelled drain-close leaks, or leaving the swap until after a successful close so Drop can still retry on cancellation.

{
warn!(
statement_id = %self.statement_id,
error = %e,
"auto-close on drain failed; server-side resource reclaimed \
when the session closes"
);
}
}

/// Spawn a fire-and-forget `CloseStatement` unless the statement is
/// already closed (`closed` flag). Shared by [`Self::next_batch`]'s
/// auto-close-on-drain and `Drop`. The `swap` makes whichever fires
/// first win; the other observes `closed=true` and skips.
/// already closed (`closed` flag). Used **only** by `Drop`, which
/// can't `.await` — the drain path closes synchronously via
/// [`Self::close_if_open`]. The `swap` makes whichever of `Drop` /
/// drain / explicit `close()` fires first win; the others observe
/// `closed=true` and skip.
fn spawn_close_if_open(&self) {
if self.closed.swap(true, Ordering::AcqRel) {
return;
Expand Down
93 changes: 93 additions & 0 deletions tests/v0_execute_wiremock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1161,3 +1161,96 @@ async fn execute_succeeded_inline_still_closes_statement() {
);
// `_close` also verifies expect(1) when it drops at end of scope.
}

// ─── Synchronous close ordering on drain (issue #170) ───

/// Regression for issue #170: the auto-close-on-drain path must close the
/// server statement **synchronously** — the `DELETE /statements/<id>` must
/// already be on the wire by the time `ExecutedStatement::next_batch()`
/// returns `Ok(None)` (end of stream). A detached fire-and-forget close
/// (`runtime.spawn`) is NOT ordered w.r.t. the caller's next request on the
/// same session, which is the non-deterministic wire ordering #170 reports.
///
/// The assertion reads `received_requests()` **immediately** after drain,
/// with no sleep: only a synchronous, awaited close guarantees the DELETE
/// is already recorded at that point. A spawned close may or may not have
/// run yet, so this reliably fails against the fire-and-forget drain path
/// and passes once the drain awaits the close.
#[tokio::test]
async fn drain_closes_statement_synchronously_before_returning() {
let server = MockServer::start().await;
mount_create_session(&server).await;
mount_delete_session(&server).await;

let batch = int64_batch("n", vec![1]);
// SUCCEEDED (not CLOSED) so a close genuinely must fire — the server
// still owns the statement.
mount_execute(&server, succeeded_inline_body("stmt-sync", &batch)).await;
mount_close_any_statement(&server).await;

let session = open_session(&server).await;
let mut stmt = session.statement();
stmt.spec().sql("SELECT 1 AS n");
let mut exec = stmt.execute().await.expect("execute");

// Drain to end-of-stream via next_batch(), which fires the auto-close.
// The final call returns Ok(None) only after the drain-close completes
// when it is synchronous.
while exec.next_batch().await.expect("next_batch").is_some() {}

// No sleep: assert the DELETE is ALREADY on the wire. This is the
// synchronous-ordering guarantee — a fire-and-forget spawn need not have
// executed yet at this point.
let delete_path = "/api/2.0/sql/statements/stmt-sync";
let deletes = server
.received_requests()
.await
.expect("received_requests")
.iter()
.filter(|r| r.method == wiremock::http::Method::DELETE && r.url.path() == delete_path)
.count();
assert_eq!(
deletes, 1,
"drain must close the statement synchronously — the DELETE must be on \
the wire before next_batch() returns None (issue #170)"
);
}

/// Companion to [`drain_closes_statement_synchronously_before_returning`]:
/// when the statement already reported `state=CLOSED`, drain must STILL fire
/// no close at all (issue #168 guarantee preserved by the #170 sync-close
/// change — a synchronous close must not resurrect the redundant DELETE the
/// CLOSED short-circuit suppresses).
#[tokio::test]
async fn drain_of_closed_statement_fires_no_close_even_when_synchronous() {
let server = MockServer::start().await;
mount_create_session(&server).await;
mount_delete_session(&server).await;

let batch = int64_batch("n", vec![1]);
mount_execute(&server, closed_inline_body("stmt-sync-closed", &batch)).await;

let _no_close = Mock::given(method("DELETE"))
.and(path("/api/2.0/sql/statements/stmt-sync-closed"))
.respond_with(ResponseTemplate::new(200).set_body_string("{}"))
.expect(0)
.mount_as_scoped(&server)
.await;

let session = open_session(&server).await;
{
let mut stmt = session.statement();
stmt.spec().sql("SELECT 1 AS n");
let mut exec = stmt.execute().await.expect("execute");
while exec.next_batch().await.expect("next_batch").is_some() {}
}

let closes = wait_for_close_delete(
&server,
"stmt-sync-closed",
0,
std::time::Duration::from_millis(500),
)
.await;
assert_eq!(closes, 0, "CLOSED statement must never fire CloseStatement");
}
54 changes: 54 additions & 0 deletions tests/v0_metadata_wiremock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1435,3 +1435,57 @@ async fn metadata_closed_response_skips_close_on_wildcard_fanout() {
}
// `_no_close` also verifies expect(0) when it drops at end of scope.
}

// ─── Synchronous close ordering on drain (issue #170) ───

/// Regression for issue #170 on the metadata path: draining a metadata
/// `ResultStream` to end-of-stream must close the server statement
/// **synchronously** — the `DELETE /statements/<id>` must already be on
/// the wire by the time `next_batch()` returns `None`, not raced on a
/// detached `runtime.spawn`. Asserted with no sleep: only a synchronous,
/// awaited close guarantees the DELETE is recorded at that point.
///
/// Uses a SUCCEEDED response so a close genuinely fires (the CLOSED path
/// is already covered by `metadata_closed_response_skips_close_statement`).
#[tokio::test]
async fn metadata_drain_closes_statement_synchronously() {
let server = MockServer::start().await;
mount_create_session(&server).await;
mount_delete_session(&server).await;

let raw = string_batch(vec![("catalog", vec![Some("main")])]);
mount_execute(&server, succeeded_inline_response_body(&raw)).await;
// Stub the DELETE so it doesn't 404 (kept unscoped; the assertion
// reads received_requests directly).
Mock::given(method("DELETE"))
.and(path("/api/2.0/sql/statements/stmt-test"))
.respond_with(ResponseTemplate::new(200).set_body_string("{}"))
.mount(&server)
.await;

let session = open_session(&server).await;
let mut stream = session
.metadata()
.list_catalogs()
.await
.expect("list_catalogs");
// Drain to end-of-stream. The final next_batch() returning None must
// have already awaited the CloseStatement (issue #170).
let _ = drain_stream(&mut stream).await;

// No sleep: the DELETE must ALREADY be on the wire.
let deletes = server
.received_requests()
.await
.expect("received_requests")
.iter()
.filter(|r| {
r.method.as_str() == "DELETE" && r.url.path() == "/api/2.0/sql/statements/stmt-test"
})
.count();
assert_eq!(
deletes, 1,
"metadata drain must close the statement synchronously — the DELETE \
must be on the wire before next_batch() returns None (issue #170)"
);
}
Loading