Repository navigation
fix(statement): close synchronously on drain to stop racing the next request (#170) - #224
vikrantpuppala wants to merge 1 commit into
Conversation
…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>
There was a problem hiding this comment.
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.
| .session | ||
| .transport() | ||
| .close_statement(&self.statement_id) | ||
| .await |
There was a problem hiding this comment.
🔵 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.
|
Closing this without merging. On review, the synchronous-close approach here fixes a non-problem at a real production-latency cost:
Trading production latency for proxy-replay tidiness is the wrong call. See #170 for the full rationale and recommendation. |
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 spawnedDELETE /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 nextExecuteStatement).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
.awaitto hang it on; keep fire-and-forget only for the trueDrop-without-drain GC fallback (Dropcan't.await):ExecutedStatement::next_batchend-of-stream (src/statement/executed.rs): new asyncclose_if_openawaits theCloseStatementbefore returningOk(None).Dropstill usesspawn_close_if_open. The sharedclosedflag makes whichever of drain / explicitclose()/Dropfires first win.ResultStream(StatementCloseGuard,src/result_stream.rs): newclose_nowawaits the close fromResultStream::next_batch's end-of-stream arm and empties the id to disarm theDropbackstop.Scope / non-goals
close()was already synchronous — unchanged.Statement::invalidate_prioris 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 + Closeoff 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 flipsclosed, so a subsequent re-execute'sinvalidate_priorseesclosed=trueand skips — no double work, and the close lands at the natural between-statements point.ExecutedAsyncStatementneeds no change: its result stream has no drain-auto-close (close_guard = None; its ownclose()is already synchronous), and itsDrop/await_resultdrop-cancel are the legitimate can't-awaitfallbacks Fire-and-forget (async spawned) CloseStatement on drain/Drop races the session's next request — non-deterministic wire ordering #170 says to keep spawned.closedflag is still flipped soDropdoesn'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). Thedrain_of_closed_statement_fires_no_close_even_when_synchronoustest 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 whennext_batch()returnsNone(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 failurescargo clippy --all-targets -- -D warnings— cleancargo +stable fmt --allCloses #170
This pull request and its description were written by Isaac.