Skip to content

fix(statement): close synchronously on drain to stop racing the next request (#170) - #224

Closed
vikrantpuppala wants to merge 1 commit into
mainfrom
fix/170-sync-close-on-drain
Closed

vikrantpuppala wants to merge 1 commit into
mainfrom
fix/170-sync-close-on-drain

Conversation

@vikrantpuppala

Copy link
Copy Markdown
Collaborator

Summary

The kernel's auto-close-on-drain path spawned a detached fire-and-forget CloseStatement (runtime.spawn(async move { transport.close_statement(...).await })) once a result stream reached end-of-stream. Because the spawned DELETE /api/2.0/sql/statements/<id> runs whenever the runtime schedules it, it races the caller's next request on the same session — non-deterministic wire ordering. The databricks-driver-test proxy suite replays the identical recording fail / pass / pass across back-to-back strict-ordering runs (the DELETE sometimes lands before, sometimes after, the next ExecuteStatement).

C# ADBC (CloseStatementAsync(...).GetAwaiter().GetResult()) and databricks-jdbc (apiClient.execute(req) inline) both close synchronously at result-set close, so the DELETE never races a later request. This PR 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 (src/statement/executed.rs): 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, src/result_stream.rs): 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 / non-goals

  • Explicit close() was already synchronous — unchanged.
  • Statement::invalidate_prior is untouched — it still spawns fire-and-forget, so PR perf(statement): skip cancel + fire-and-forget close in invalidate_prior #85's re-execute-loop perf win (Cancel + Close off the critical path, ~10-14% on large-result QRC loops) is preserved for the not-fully-drained case. When a caller does fully drain, the sync close fires and flips closed, so a subsequent re-execute's invalidate_prior sees closed=true and skips — no double work, and the close lands at the natural between-statements point.
  • Async ExecutedAsyncStatement needs no change: its result stream has no drain-auto-close (close_guard = None; its own close() is already synchronous), and its Drop / await_result drop-cancel are the legitimate can't-await fallbacks Fire-and-forget (async spawned) CloseStatement on drain/Drop races the session's next request — non-deterministic wire ordering #170 says to keep spawned.
  • A drain-close wire failure is logged and swallowed (the result is already fully delivered; the server reclaims the handle at session expiry) rather than surfaced as a spurious end-of-stream error. The closed flag is still flipped so Drop doesn't re-fire.

Relationship to #168

#168 (redundant close when state=CLOSED) and this issue are complementary: #168 removes the close entirely for CLOSED statements (so there's nothing to race there), while #170 orders the close that genuinely must fire (SUCCEEDED / large CloudFetch). The drain_of_closed_statement_fires_no_close_even_when_synchronous test confirms this PR does not resurrect the #168 redundant DELETE.

Test plan

All three new tests are verified tripwires (fail against the pre-fix spawned close, pass after):

  • v0_execute_wiremock::drain_closes_statement_synchronously_before_returning — SUCCEEDED drain → the DELETE must already be on the wire when next_batch() returns None (asserted with no sleep).

  • v0_execute_wiremock::drain_of_closed_statement_fires_no_close_even_when_synchronous — SEA metadata queries emit a redundant CloseStatement DELETE on a statement already returned state=CLOSED #168 CLOSED-skip preserved.

  • v0_metadata_wiremock::metadata_drain_closes_statement_synchronously — same guarantee on the metadata path.

  • cargo test — 738 lib tests + all integration suites, 0 failures

  • cargo clippy --all-targets -- -D warnings — clean

  • cargo +stable fmt --all

Closes #170

This pull request and its description were written by Isaac.

…request (#170)

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/<id>` 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 <vikrant.puppala@databricks.com>

@oss-reviewer-bot oss-reviewer-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Verdict: 1 Low

Solid, well-documented fix that aligns the drain-close path with C# ADBC / JDBC synchronous close ordering, with good tripwire tests on both the execute and metadata paths. The closed-flag / mem::take guards correctly prevent double-close across drain / explicit close() / Drop, and the metadata close_now disarming the Drop backstop is correct. One low-severity note on a cancellation-safety edge introduced by moving the close inline.

Comment thread src/statement/executed.rs
.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.

@vikrantpuppala

Copy link
Copy Markdown
Collaborator Author

Closing this without merging. On review, the synchronous-close approach here fixes a non-problem at a real production-latency cost:

  • Not a correctness bug. The close targets a specific, already-terminal statement_id (DELETE /statements/stmt-A). The next request creates an independent statement (POST /statements → stmt-B). The DELETE cannot affect stmt-B, the session, or anything else — the two are independent server operations, and wire ordering between them has no correctness consequence. (Session close doesn't coordinate with pending statement closes either; the server reclaims everything on delete_session.)
  • The only thing the async close breaks is strict-ordering replay tooling (the databricks-driver-test proxy harness), which already has the correct fix on its side (per-connection recording).
  • Blocking the drain re-introduces serially what PR perf(statement): skip cancel + fire-and-forget close in invalidate_prior #85 deliberately moved off the critical path — a +1 CloseStatement RTT at end-of-stream for SUCCEEDED / large-CloudFetch statements, undoing that measured re-execute-loop win. (CLOSED statements are unaffected thanks to SEA metadata queries emit a redundant CloseStatement DELETE on a statement already returned state=CLOSED #168, but the open-statement hot path regresses.)

Trading production latency for proxy-replay tidiness is the wrong call. See #170 for the full rationale and recommendation.

This branch was previously deployed

1 inactive deployment
azure-prod — a097454e Deployed Aug 10, 2026 by oss-reviewer-bot[bot] via followup #228
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Fire-and-forget (async spawned) CloseStatement on drain/Drop races the session's next request — non-deterministic wire ordering

1 participant