From a097454e5f1aba9edb6119f7807a388c1ad6e187 Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Mon, 10 Aug 2026 06:22:43 +0000 Subject: [PATCH] fix(statement): close synchronously on drain to stop racing the next request (#170) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The auto-close-on-drain path spawned a detached fire-and-forget `CloseStatement` (`runtime.spawn`) once a result stream reached end-of-stream. Because the spawned `DELETE /statements/` runs whenever the runtime schedules it, it raced the caller's next request on the same session — non-deterministic wire ordering that breaks ordered replay/proxy tooling (the databricks-driver-test proxy suite replays the identical recording fail/pass/pass across back-to-back runs). C# ADBC and databricks-jdbc both close synchronously at result-set close, so the DELETE never races a later request. This aligns the kernel's drain path with them. Fix — close synchronously (await) at the two drain sites that have an `.await` to hang it on, keep fire-and-forget only for the true `Drop`-without-drain GC fallback (Drop can't `.await`): - `ExecutedStatement::next_batch` end-of-stream: new async `close_if_open` awaits the `CloseStatement` before returning `Ok(None)`. `Drop` still uses `spawn_close_if_open`. The shared `closed` flag makes whichever of drain / explicit `close()` / `Drop` fires first win. - Metadata `ResultStream` (`StatementCloseGuard`): new `close_now` awaits the close from `ResultStream::next_batch`'s end-of-stream arm and empties the id to disarm the `Drop` backstop. Scope preserved: the explicit `close()` path was already synchronous, and `Statement::invalidate_prior` is untouched — it still spawns fire-and-forget, so PR #85's re-execute-loop perf win (Cancel+Close off the critical path) is kept for the not-fully-drained case. A drain-close wire failure is logged and swallowed (the result is already delivered; the server reclaims at session expiry) rather than surfaced as a spurious end-of-stream error. The async `ExecutedAsyncStatement` needs no change: its result stream has no drain-auto-close (its own `close()` is already synchronous), and its Drop / await_result drop-cancel are the legitimate can't-await fallbacks. Tests (verified tripwires — fail before, pass after): - v0_execute_wiremock: `drain_closes_statement_synchronously_before_returning` (SUCCEEDED drain → DELETE already on the wire, no sleep) + `drain_of_closed_statement_fires_no_close_even_when_synchronous` (issue #168 CLOSED-skip preserved). - v0_metadata_wiremock: `metadata_drain_closes_statement_synchronously`. Co-authored-by: Isaac Signed-off-by: Vikrant Puppala --- src/result_stream.rs | 46 +++++++++++++++-- src/statement/executed.rs | 72 +++++++++++++++++++++++---- tests/v0_execute_wiremock.rs | 93 +++++++++++++++++++++++++++++++++++ tests/v0_metadata_wiremock.rs | 54 ++++++++++++++++++++ 4 files changed, 253 insertions(+), 12 deletions(-) diff --git a/src/result_stream.rs b/src/result_stream.rs index 79249879..673d8ba6 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -486,14 +486,44 @@ pub struct ResultStream { close_guard: Option, } -/// 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/` 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, 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()); @@ -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) } } diff --git a/src/statement/executed.rs b/src/statement/executed.rs index b8717e75..c7d3a452 100644 --- a/src/statement/executed.rs +++ b/src/statement/executed.rs @@ -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/` 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 @@ -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> { @@ -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 + { + 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; diff --git a/tests/v0_execute_wiremock.rs b/tests/v0_execute_wiremock.rs index 5756c1ed..d0fbf372 100644 --- a/tests/v0_execute_wiremock.rs +++ b/tests/v0_execute_wiremock.rs @@ -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/` 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"); +} diff --git a/tests/v0_metadata_wiremock.rs b/tests/v0_metadata_wiremock.rs index 1668c5f3..2776a899 100644 --- a/tests/v0_metadata_wiremock.rs +++ b/tests/v0_metadata_wiremock.rs @@ -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/` 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)" + ); +}