Skip to content

perf(kernel): cut ~530ms off SELECT 1 — drop wait_timeout, skip redundant CloseStatement - #21

Merged
vikrantpuppala merged 2 commits into
mainfrom
perf/drop-wait-timeout
May 18, 2026
Merged

vikrantpuppala merged 2 commits into
mainfrom
perf/drop-wait-timeout

Conversation

@vikrantpuppala

Copy link
Copy Markdown
Collaborator

Summary

SELECT-1 through the kernel was ~700ms TTFR vs Thrift's ~400ms. This PR removes two avoidable sources of that fixed overhead on the sync-execute path (Statement::execute):

  1. Drop wait_timeout=10s from the request. Direct HTTP probes showed the server's own no-timeout default already waits up to ~10s anyway, but on a trivial query the wait_timeout=10s path returns ~260ms slower (~655ms vs ~397ms) — and more importantly, with wait_timeout set the server returns state=SUCCEEDED (statement still alive), forcing an explicit CloseStatement round-trip. Without it, the server returns state=CLOSED for inline-result fast-path queries and reclaims server-side resources itself.

  2. Skip CancelStatement + CloseStatement when the server already returned state=CLOSED. Plumb server_state through ExecuteResult and share an Arc<AtomicBool> closed flag between Statement and ExecutedStatement. When the server reports CLOSED in its execute response, the flag is pre-set to true; explicit close() on either handle, the lifecycle owner's invalidate_prior cleanup path, and Drop's fire-and-forget cleanup all short-circuit. (The PySQL connector calls Statement.close() after every execute(), so without sharing the flag the savings from Initial import: Databricks ADBC Rust driver as databricks-sql-kernel #1 are immediately undone by an extra round-trip in the lifecycle close.)

Statement::submit still passes wait_timeout=0s explicitly — that path is defined by "return immediately with a PENDING/RUNNING statement_id", so omitting it would change behaviour rather than just speed it up.

Benchmark results

scripts/bench_kernel_vs_thrift.py against Dogfood, median over 5 samples (warm-up dropped).

Before this PR (fix/reader-nested-block-on, the PR #20 baseline this stacks on):

shape thrift TTFR kernel TTFR delta
SELECT 1 397 ms 925 ms +528 ms
range(10k) 1095 ms 1186 ms +91 ms
metadata.catalogs 406 ms 519 ms +113 ms

After this PR:

shape thrift TTFR kernel TTFR delta
SELECT 1 389 ms 395 ms +6 ms
range(10k) 1100 ms 646 ms –454 ms
metadata.catalogs 414 ms 542 ms +128 ms

SELECT 1 is now at parity with Thrift. range(10k) got a much larger lift than expected (kernel now beats Thrift) — same root cause: the server can return inline-result + state=CLOSED on small results, and both round-trips we used to fire are now redundant.

Test plan

  • cargo build && cargo clippy --all-targets -- -D warnings
  • cargo test --lib — 366 passed
  • Re-benched against Dogfood — numbers in the table above
  • Connector e2e (kernel backend) green via bench_kernel_vs_thrift.py (each cell opens a fresh connection, executes, drains, closes — so it exercises the full statement lifecycle including the close path)

Stacked on

This pull request and its description were written by Claude Code.

@vikrantpuppala
vikrantpuppala force-pushed the fix/reader-nested-block-on branch from 7d07dbb to 1b81dc8 Compare May 18, 2026 05:48
…execute

SELECT-1 paid ~530ms of avoidable fixed overhead vs Thrift:

1. The kernel always sent wait_timeout=10s + on_wait_timeout=CONTINUE on
   sync execute. Direct HTTP probes showed the server's own no-timeout
   default already waits up to 10s anyway, but on a trivial query the
   wait_timeout=10s path returns ~260ms slower (~655ms vs ~397ms).
   Dropping the parameter is pure win — same effective behaviour, faster
   completion, and the server now returns state=CLOSED on the inline-result
   fast path, eliminating the second round of overhead below.

2. ExecutedStatement always issued a CloseStatement RPC on explicit close
   or Drop. When the server has already moved the statement to CLOSED in
   its execute response (which it does whenever it can return results in
   the same response, i.e. the common SELECT-1 case), that second RPC is
   redundant. Thread server_state through ExecuteResult and pre-set the
   handle's closed flag from it so both explicit close() and Drop skip
   the extra round-trip.

Statement::submit still passes wait_timeout=0s explicitly — that path is
defined by 'return immediately with a PENDING/RUNNING statement_id', and
omitting wait_timeout there would change behaviour rather than just speed
it up.

Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
@vikrantpuppala
vikrantpuppala changed the base branch from fix/reader-nested-block-on to main May 18, 2026 06:04
@vikrantpuppala
vikrantpuppala force-pushed the perf/drop-wait-timeout branch from 1e3aa70 to 5f9c283 Compare May 18, 2026 06:05
@gopalldb

Copy link
Copy Markdown
Collaborator

Critical (block merge)

C1. cargo +stable fmt --all -- --check fails on mutable.rs:160

let already_closed = matches!(result.server_state, crate::types::sea::StatementState::Closed);

rustfmt wants to split this across four lines (verified locally — Diff in /private/tmp/pr21-check/src/statement/mutable.rs:157). The pr-checks.yml CI gate (per CLAUDE.md) runs cargo +stable fmt --all --
--check and will reject the PR.

Fix: run cargo +stable fmt --all and commit. Or — better, since the matches! form is verbose for a one-variant check — collapse it:
let already_closed =
result.server_state == crate::types::sea::StatementState::Closed;
StatementState derives PartialEq, Eq (verified at types/sea.rs:45), so equality works directly. Saves the macro indirection too.

Or import the type once and shorten the right-hand side:
use crate::types::sea::StatementState;
...
let already_closed = result.server_state == StatementState::Closed;

Any of the three works. I'd take the third — most readable.

Important

I1. Only Closed short-circuits; what about other terminal states the server could return?

mutable.rs:160:
let already_closed = matches!(result.server_state, StatementState::Closed);

StatementState has 6 variants: Pending, Running, Succeeded, Failed, Canceled, Closed. The PR correctly treats only Closed as "server-side cleaned up." But:

  • Failed: server reported the query failed during the execute call (server-side error before the result was returned). Is the statement still alive? Per the SEA spec, Failed means the statement is in a
    terminal failure state; the docs are ambiguous about whether the server keeps it for GetStatementStatus polling. If a query fails inline and we get Failed back, sending CloseStatement is likely needed.
  • Canceled: the server reports the statement was canceled (typically via prior CancelStatement). Already terminal but probably needs close.
  • Succeeded: statement alive, needs explicit close. Current behavior (no short-circuit) is right.

The PR description establishes that omitting wait_timeout typically yields Closed on the inline-result fast path, but doesn't guarantee the server can't return Succeeded on this path (e.g., for results that
exceed inline thresholds, or under server-side configuration changes).

The current code is correct but narrow: only the actually-observed fast path triggers the optimization. If wait_timeout is reintroduced (e.g., by a caller passing Some("5s") to prepare_for_dispatch), the
closed flag stays false and the round-trip fires normally. Defensive.

Suggestion (small): add one comment line at mutable.rs:160:
// Only Closed triggers the short-circuit. Succeeded means the
// server still owns the statement and we must issue CloseStatement.
// Failed / Canceled are terminal but still server-side-tracked
// — also fall through to the standard close path.
let already_closed = result.server_state == StatementState::Closed;

Not blocking. Just makes the design intent explicit.

I2. ExecutedAsyncStatement::new got closed parameter but the submit-path comment in mutable.rs says "the server can't return CLOSED yet"

mutable.rs:202-205:
// submit path always uses wait_timeout=0s, so the server can't
// return CLOSED yet; start the flag false and let later close()
// calls flip it.
let closed = Arc::new(AtomicBool::new(false));

Why not also propagate submit_result.server_state and pre-set the flag if the server did return Closed? Async-submit with a deliberate wait_timeout=0s shouldn't return Closed in practice — but the existing
code in execute() doesn't blindly trust the wait-timeout setting either; it inspects server_state. Being symmetric here is cheap defense:

let already_closed = matches!(response.status.state, StatementState::Closed);
let closed = Arc::new(AtomicBool::new(already_closed));

If the server changes its behavior or some edge case (network hiccup, server-side state machine quirk), the submit path benefits the same way. Symmetric with execute.

Not blocking — the current submit-path comment is honest. Worth thinking about for cleanliness.

I3. ExecutedStatement::close swap is now correct against the share, but does the ExecutedStatement::Drop path also see the pre-set true?

Cross-checking executed.rs:128-145:
async fn close(&self) -> Result<()> {
async {
if self.closed.swap(true, Ordering::AcqRel) {
return Ok(()); // already closed — short-circuit
}
self.session.transport().close_statement(&self.statement_id).await
}...
}

impl Drop for ExecutedStatement {
fn drop(&mut self) {
if self.closed.load(Ordering::Acquire) {
return; // already closed — no fire-and-forget
}
...spawn(close_statement(...))...
}
}

When ExecutedStatement::new is called with closed = Arc::new(AtomicBool::new(true)) (server-pre-closed case), both close() and Drop short-circuit immediately. ✓

When closed is Arc::new(AtomicBool::new(false)) (server returned Succeeded):

  • User calls close() → swap returns false, we issue real CloseStatement, flag flipped to true. ✓
  • User drops without close → Drop sees false, spawns fire-and-forget close. ✓
  • User calls close() then drops → close swaps to true, Drop sees true, skips. ✓

But: what about the executed handle dropped before the parent statement is re-executed, while the close-spawn is still in flight?

Timeline:

  1. execute() returns ExecutedStatement(closed=false). Parent last_closed = Some(Arc::clone(&closed)).
  2. User drops ExecutedStatement. Drop sees closed=false, swaps to... wait — Drop does load(Acquire) then spawn, but does not swap. The flag stays false!
  3. User calls execute() again. invalidate_prior sees last_closed.swap(true, AcqRel) = false → tries to cancel+close again.

So if the user drops the executed handle and immediately re-executes, two close-statement RPCs race (one from the spawned task, one from invalidate_prior). The server is idempotent on close (the doc comment
in executed.rs:130-132 notes this), so functionally it's "right" — just wasteful.

The pre-existing ExecutedStatement::Drop doesn't flip the flag because there's no other reader that cares. But now there's Statement::last_closed watching the same Arc, and Drop should set it so
invalidate_prior skips.

Suggestion: add self.closed.store(true, Ordering::Release); (or swap) at the start of Drop for ExecutedStatement, before the load. The current if self.closed.load(...) { return } becomes if
self.closed.swap(true, Ordering::AcqRel) { return }. Same semantics for Drop (idempotency was never an issue), but now the shared last_closed correctly reflects "Drop is handling it."

Caveat: this is also fine to leave as-is — the server idempotency makes the race harmless. The cost is one wasted CloseStatement on the rare drop-then-reexecute pattern. Worth a follow-up note rather than
blocking.

I4. Arc is now shared between Statement and the executed handle — verify Send + Sync invariant still holds

Statement::last_closed: Option<Arc> — Arc is Send + Sync. ✓ The kernel's lib.rs (per CLAUDE.md) asserts Send + Sync on the public handles; this addition doesn't break those.

Quick sanity: did the lib-level assertion catch this if we'd accidentally used Rc? Yes — the existing assert_send_sync!(Statement) in lib.rs would fail to compile. ✓ Good defense.

@vikrantpuppala
vikrantpuppala requested a review from gopalldb May 18, 2026 06:21
C1 (rustfmt): the inline matches!() on result.server_state failed
cargo +stable fmt --all -- --check. Replace with == against an
imported StatementState (PartialEq + Eq are already derived) — both
shorter and rustfmt-clean.

I1 (clarify intent): only Closed means the server reclaimed the
statement. Succeeded/Failed/Canceled are terminal but still
server-side-tracked and need an explicit CloseStatement. Add a
comment so future readers don't widen the short-circuit by accident.

I3 (close flag race): ExecutedStatement::Drop and
ExecutedAsyncStatement::Drop previously did load(Acquire) then
spawn(close_statement), never flipping the shared closed flag.
After this PR the parent Statement::last_closed holds the same Arc,
so a drop(executed) → execute() again sequence would have
invalidate_prior race a second CloseStatement against the
Drop-spawned one. The server is idempotent so it's harmless, but
the extra RPC is wasted. Change both Drop impls to swap(true,
AcqRel) so invalidate_prior sees the flag and short-circuits.

Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
@vikrantpuppala

Copy link
Copy Markdown
Collaborator Author

Addressed in f75b605:

  • C1 ✅ Switched to use crate::types::sea::StatementState + result.server_state == StatementState::Closed. cargo +stable fmt --all -- --check clean locally.
  • I1 ✅ Added the comment block explaining why only Closed short-circuits and what the other terminal states mean.
  • I3 ✅ Changed both ExecutedStatement::Drop and ExecutedAsyncStatement::Drop from load(Acquire) to swap(true, AcqRel). Now the shared flag reflects "Drop is handling it" and invalidate_prior skips on the next execute.

Skipping I2 on purpose: submit() always sends wait_timeout=0s, so the server structurally can't return Closed on that path — adding a server_state check there would be dead code dressed as defense. Happy to revisit if you disagree.

cargo +stable fmt --all -- --check, cargo clippy --all-targets -- -D warnings, and cargo test --lib (366 passed) all clean.

@vikrantpuppala
vikrantpuppala merged commit aed2efb into main May 18, 2026
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.

2 participants