Skip to content

feat(c-abi): expose detached statement canceller for sync execute - #163

Merged
vikrantpuppala merged 7 commits into
mainfrom
mani/c-abi-statement-canceller
Jul 14, 2026
Merged

vikrantpuppala merged 7 commits into
mainfrom
mani/c-abi-statement-canceller

Conversation

@mani-mathur-arch

@mani-mathur-arch mani-mathur-arch commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Expose the kernel's existing StatementCanceller over the C ABI:
kernel_statement_canceller_new / _cancel / _free.

kernel_statement_execute blocks the calling thread for the whole query, so a
C-ABI host cannot cancel it by calling another method on the same statement
handle mid-execute (that would alias the &mut Statement borrow). A detached
canceller — obtained before execute — solves this: it holds only cloned
Arcs (session + inflight statement id), no Statement borrow, so it is safe
to fire from another thread while execute runs.

It is the building block a host driver (e.g. Go database/sql) uses to honor
ctx cancellation over a blocking execute (watcher thread → out-of-band cancel).

Semantics

  • Statement-scoped, not execution-scoped. The canceller tracks whichever
    query is currently in flight on its statement; re-executing retargets it to
    the new query. Use one per execute: obtain before execute, free after it
    returns.
  • _cancel(canceller, dispatched) reports through the dispatched: *mut bool
    out-param whether a cancel RPC was actually sent — true once a server
    statement id has been observed, false if none has yet (nothing executed, or
    still in the initial round-trip). Both return Success; a no-op is not an
    error. dispatched may be null.
  • Single-owner teardown. _cancel blocks on the cancel RPC (which retries
    with backoff on a retryable failure), so a host must quiesce any cancelling
    thread before _free.

What changes

  • src/c_abi/statement.rs — three extern "C" entry points over a boxed
    CancellerHandle wrapping StatementCanceller; the cancel path runs through
    the existing block_on_ffi panic firewall. Purely additive — no existing
    symbol or signature changes.
  • include/databricks_kernel.h — the opaque kernel_statement_canceller_t
    typedef, the three declarations, and the canceller's place in the teardown
    ordering.
  • tests/v0_c_abi_canceller_wiremock.rs — drives the entry points against a
    mock SEA server.

Test plan

  • cargo test — tests/v0_c_abi_canceller_wiremock.rs covers cancel during a
    blocking execute from another thread (status stays RUNNING until the cancel POST
    lands, so the failure is caused by the cancel), the no-op-before-id case, a
    failing cancel RPC, a post-terminal cancel, and re-execute retargeting; plus
    null-guard unit tests for all three entry points.
  • cargo clippy --all-targets -- -D warnings clean
  • cargo +stable fmt --all clean

Additive symbols only; ABI-compatible with the sync path.

kernel_statement_execute blocks the calling thread for the whole query, so a
host cannot cancel it by calling another method on the same statement handle
(that would alias the &mut Statement borrow). Add kernel_statement_canceller_
new/_cancel/_free, exposing the existing StatementCanceller so a host can fire
a cancel from another thread. The canceller clones only the session + inflight-id
Arcs (no Statement borrow), so it is safe to use concurrently with the in-flight
execute; statement-scoped, targeting the specific server statement id observed
for this statement.

This is the sync counterpart to kernel_executed_async_statement_cancel and the
building block for the Go binding's watcher-goroutine cancellation model
(blocking execute + out-of-band cancel).

Add null-guard unit tests for the three entry points; the server-driven cancel
path is covered by the e2e/wiremock suites.

Co-authored-by: Isaac
Signed-off-by: Mani Kaustubh Mathur <mani.mathur@databricks.com>
…ests

Refine the detached statement canceller so a C-ABI host can act on the
result and can't trip a use-after-free:

- kernel_statement_canceller_cancel gains a `dispatched: *mut bool`
  out-param: true when a cancel RPC was sent, false when no server
  statement id has been observed yet (the query's initial round-trip).
  Written on every non-null path so it is always defined.
- Clone the canceller into the async future rather than borrowing it
  through the handle box, so the blocking cancel RPC holds no reference
  into memory a concurrent _free could drop.
- Document the statement-scoped retargeting, session pin, teardown
  ordering, and single-owner _free/_cancel contract in the header and
  rustdoc.

Add tests/v0_c_abi_canceller_wiremock.rs driving the entry points against
a mock SEA server: cancel-during-execute (status stays RUNNING until the
cancel POST lands), no-op-before-id, cancel-RPC-failure, and re-execute
retargeting.

Co-authored-by: Isaac
Signed-off-by: Mani Kaustubh Mathur <mani.mathur@databricks.com>
…l-failure test

Address review follow-ups on the statement canceller:

- kernel_statement_canceller_cancel writes *dispatched=false before the
  null-handle guard, so the out-param is defined on every non-null-pointer
  return path (the guard previously returned before the write, contradicting
  the documented contract).
- Correct the _cancel and _free docs: the cancel call blocks on the RPC,
  which on a retryable server error retries with backoff and can stay in
  flight far longer than one round-trip — so a host must quiesce cancelling
  threads before freeing.
- The cancel-failure test uses a non-retryable 404 instead of 500, avoiding
  the ~60s idempotent-retry ladder.
- Add coverage: null `out` on _new returns InvalidArgument; a cancel after
  the statement is terminal dispatches and reports dispatched=true.

Co-authored-by: Isaac
Signed-off-by: Mani Kaustubh Mathur <mani.mathur@databricks.com>
Trim two over-long comments in kernel_statement_canceller_cancel to the
density of the sibling entry points: drop the single-owner restatement from
the clone comment (it is already in the # Safety block) and collapse the
doubled "written on every path / always defined" phrasing in the dispatched
doc.

Co-authored-by: Isaac
Signed-off-by: Mani Kaustubh Mathur <mani.mathur@databricks.com>
Pull in #162 (C ABI: OAuth U2M, custom headers, session validity, logging
init). No conflicts; both PRs append to include/databricks_kernel.h in
distinct sections and touch disjoint source (this branch: statement.rs
canceller; #162: session.rs / logging.rs / c_abi/session.rs). Build,
clippy -D warnings, canceller + session-close wiremock, and full lib
tests all green on the merged tree.

Co-authored-by: Isaac
Signed-off-by: Mani Kaustubh Mathur <mani.mathur@databricks.com>
Comment thread include/databricks_kernel.h Resolved
Comment thread src/c_abi/statement.rs Resolved
Comment thread tests/v0_c_abi_canceller_wiremock.rs Resolved
Comment thread src/c_abi/statement.rs
/// with backoff and can stay in flight far longer than one round-trip, so join or
/// otherwise quiesce any cancelling thread before freeing.
#[no_mangle]
pub unsafe extern "C" fn kernel_statement_canceller_free(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The single-owner / quiesce-before-free contract is prose-only; kernel_statement_canceller_free unconditionally Box::from_raws with no in-flight guard. A cancel-then-timeout-then-free host pattern (plausible given the ~15-min block in F3) triggers UB. No test exercises concurrent _free during an in-flight _cancel (all tests join the cancelling thread first).

Note: the UAF window is narrow — _cancel clones the canceller (owned) at statement.rs:452 before block_on_ffi, so the borrow into the box is only held during the clone, not across the blocking RPC. The window is .as_ref() → .clone(), not the whole RPC.

  • Fix: either Arc the CancellerHandle so the last drop wins (turning UB into a delayed free), or state in the header that violating single-owner is undefined behavior (memory unsafety), not merely "so quiesce any cancelling thread first" (which reads as a perf suggestion) — plus a Miri/ASan concurrent-free test.

Posted by code-review-squad · /full-review · feedback: #code-review-squad-feedback

Comment thread include/databricks_kernel.h Resolved
@vikrantpuppala

Copy link
Copy Markdown
Collaborator

Code Review Squad — Review

Score: 75/100 — MODERATE RISK

The core canceller mechanism is memory-safe by construction (cloned Arcs, no Statement borrow held across the RPC) and well-tested for the happy path. The issues are contract & documentation gaps at the C boundary that a host driver (Go/ODBC) would trip over: a hard UB constraint omitted from the header (F1, the one to fix before merge), an unquantified worst-case block time, a self-contradictory teardown note, and tests that never exercise the documented cross-lifetime usage. 9/9 reviewers delivered.


Could not post inline comments for: F2, F4, F8 — see body below.

Medium Findings

F2 — src/statement/mutable.rs:L295 — Retained canceller can cancel the PRIOR finished query during re-execute handoff

On re-execute, the shared inflight_id slot still holds the previous query's id and is not cleared until MidExecuteCancelState::new (execute() line 298), which runs after invalidate_prior().await (line 295) and prepare_for_dispatch (line 296). invalidate_prior does not touch inflight_id (verified lines 608-637). In the window between the second execute() call and the slot clear, a concurrent kernel_statement_canceller_cancel reads the stale prior id, POSTs a cancel against the already-finished first query, and returns Success with dispatched=true.

The header advertises (line 209) "a canceller retained across a re-execute cancels the LATER query" — during this handoff that is briefly false, with a positive dispatched=true signal masking the miss. The recommended one-per-execute pattern avoids it, and the canceller_retargets_the_current_execution_on_reuse test only passes because it spins on second_started before firing — deliberately stepping over this window.

  • Suggested fix: clear the inflight_id slot to None at the very entry of execute()/submit()/execute_direct() (before invalidate_prior().await), collapsing the stale window to zero. Alternatively, document that a retained canceller may momentarily target the prior query during the re-execute handoff.

F4 — src/statement/mutable.rs:L752 — Silent dispatched=false no-op emits no log on any path

StatementCanceller::cancel returns Ok(false) from the let Some(id) = id else { return Ok(false) } branch (lines 752-754) before entering the instrumented span, so it emits no tracing event. The transport logs dispatch only at debug!, and the no-op branch never reaches the transport. When a host calls _cancel and it no-ops because no server id has been observed yet (fast query, or still in the initial submit round-trip), the call produces zero log output even at RUST_LOG=databricks_sql_kernel=debug — nothing distinguishes "cancel raced ahead of the id" from "host wired to the wrong handle".

  • Fix: emit one DEBUG event at the cancel decision point — both the no-op branch and the dispatch branch, with the observed id — so both outcomes are attributable in a single log stream. The fix location is pre-existing mutable.rs shared across napi/pyo3/C-ABI bindings, so it benefits all consumers.

F8 — src/statement/mutable.rs:L753 — dispatched=true means an id was in the slot, not that a live query was interrupted

cancel() returns Ok(true) whenever the slot holds any id and the POST does not error (lines 753-758). Because the slot retains the id after a query finishes, a cancel fired post-terminal (or in the F2 re-execute window against a stale id) still reports dispatched=true. The header (lines 393-401) sells dispatched as how a host "tells a dispatched cancel from a no-op", but a dispatch against a finished statement is itself a semantic no-op — so true does not mean "you interrupted a running query". The PR's own cancel_after_terminal_dispatches_and_reports_true test asserts exactly this.

  • Fix: reword the header/docstring: dispatched=true means "a cancel RPC was POSTed for the currently-observed statement id; this does not imply a running query was interrupted (the id may be already-terminal or superseded)".

Address the canceller review findings on this PR:

- Clear the shared inflight-id slot at the entry of execute/submit/
  execute_direct (before the first await), collapsing the re-execute
  handoff window where a retained canceller could fire against the prior
  finished query and report dispatched=true. Single clearing point;
  MidExecuteCancelState::new is now a pure capture. Kept out of
  invalidate_prior (also called by close(), where the slot must survive).
- Log both cancel outcomes (no-op and dispatch) at debug so a silent
  no-op is attributable under RUST_LOG=databricks_sql_kernel=debug.
- Header: state that calling _new concurrently with an in-flight execute
  is UB, quantify the ~15-min cancel-RPC worst case, drop cancellers from
  the ordered RPC-teardown list (freeing drives no RPC), reword
  dispatched=true semantics, and sharpen _free single-owner to UB.
- Add a wiremock test proving a canceller stays usable after statement
  and session close (cloned session Arc keeps the client alive).

Co-authored-by: Isaac
Signed-off-by: Mani Kaustubh Mathur <mani.mathur@databricks.com>
Comment thread tests/v0_c_abi_canceller_wiremock.rs Resolved
Comment thread src/c_abi/statement.rs Resolved
Comment thread src/c_abi/statement.rs Resolved
Comment thread src/c_abi/statement.rs Resolved
Comment thread src/statement/mutable.rs Resolved
Comment thread src/c_abi/statement.rs Resolved
@mani-mathur-arch

Copy link
Copy Markdown
Contributor Author

Code Review Squad — Review

Score: 77/100 — MODERATE RISK

The unsafe/FFI mechanics are sound — three reviewers independently verified the Box round-trip, Arc/Send semantics, no-lock-across-await, block_on reentrancy rejection, and null-guards, and found no UB. The findings are not memory-safety bugs but a documentation contradiction on canceller free-ordering, an over-restrictive &mut Statement borrow in _new, the headline re-execute-race fix having no test that would fail if reverted, and a ≤15-min blocking cancel colliding with the join-before-free contract. None block merge; F2 (doc contradiction) and F4 (untested fix) are the highest-value fixes.


…er docs

Address the second canceller review pass:

- Add retained_canceller_noops_in_the_reexecute_handoff_window: a held
  second-execute POST parks the dispatch in the pre-observer window, so a
  cancel fired there must observe an empty slot (dispatched=false, no POST
  to the prior id). Reverting reset_inflight_slot() now fails a test — the
  prior retarget test passed either way.
- Add tests/v0_statement_canceller_reexecute.rs: direct-Rust-API coverage
  for the reset_inflight_slot() clear on submit()/execute_direct() (async
  submit is not exposed over the C ABI). A failed second dispatch leaves
  the slot cleared with the fix, stale without it.
- Fix the c_abi _new rustdoc: free is order-independent (drives no RPC),
  matching the header and the canceller_outlives test — was contradicting
  both by saying "free before closing the statement".
- Drop the hardcoded "~15 min / 900s / 5" retry figures from the header
  and Rust doc; point at the SEA retry-config defaults so the prose can't
  go stale when they retune.

Co-authored-by: Isaac
Signed-off-by: Mani Kaustubh Mathur <mani.mathur@databricks.com>
@mani-mathur-arch

Copy link
Copy Markdown
Contributor Author

Canceller review — resolution summary

Both review passes have been addressed, across two commits (68ae83c, e0db5fa). Summary below.

Pass 1 (initial review) — all 8 findings fixed in 68ae83c

Header / C-boundary contract

  • _new now states plainly that calling it concurrently with an in-flight execute on the same statement is undefined behavior (the merge-blocker); typedef tightened to "the returned handle is safe to use concurrently."
  • Dropped statement cancellers from the ordered RPC-teardown list — freeing one drives no RPC, so its order is independent.
  • Reworded dispatched=true: it means a cancel was POSTed for the observed id, not that a running query was interrupted.
  • Sharpened _free's single-owner note from a perf-sounding "quiesce" to explicit UB (use-after-free).

Engine (src/statement/mutable.rs)

  • Closed the re-execute stale-id window: the shared inflight_id slot is cleared at dispatch entry (reset_inflight_slot), so a retained canceller can't fire against the prior finished query during the handoff.
  • Both cancel outcomes (no-op and dispatch) now emit a debug event, so a no-op is attributable under RUST_LOG=…=debug.

Tests

  • Added canceller_outlives_statement_and_session_close, exercising the cross-lifetime invariant (cloned session Arc keeps the client alive past kernel_session_close).

Pass 2 (re-review of 68ae83c) — 4 fixed in e0db5fa, 2 deferred by-design

Fixed

  • Aligned the _new rustdoc free-ordering to the header + test (it had contradicted both by saying "free before closing the statement").
  • Added retained_canceller_noops_in_the_reexecute_handoff_window — a test that actually fails if reset_inflight_slot is reverted (the prior retarget test passed either way; verified by reverting all three call sites).
  • Added tests/v0_statement_canceller_reexecute.rs — direct-Rust-API coverage for the slot clear on submit() / execute_direct(), which aren't reachable over the C ABI.
  • De-hardcoded the retry-budget figures (was "~15 min / 900s / 5") to a pointer at the SEA retry defaults, so the docs can't go stale.

Deferred (by-design, not defects)

  • Blocking _cancel vs single-owner _free: the blocking call returns the RPC status a fire-and-forget variant would discard; it's a documented trade-off on a cold path, with the worst-case block time and joinable-thread guidance now in
    the docs. A non-blocking spawn-and-return variant is a deliberate API-shape change to make when a real host needs it.
  • _new's &mut Statement borrow: intentional misuse-prevention (obtain-before-dispatch is the contract, and the header calls out the UB). Dropping the borrow to allow the lazy Go ctx.Done() pattern needs a new Session/Statement
    accessor, best designed with that consumer in hand.

Verification

cargo fmt + clippy -D warnings clean; full cargo test green (including the new guard tests, confirmed to fail when the fix is reverted); Isaac Review (--uncommitted) returned no surviving findings on both commits.

@vikrantpuppala
vikrantpuppala added this pull request to the merge queue Jul 14, 2026
Merged via the queue into main with commit 56b9a6e Jul 14, 2026
15 of 16 checks passed
mani-mathur-arch added a commit that referenced this pull request Jul 14, 2026
Empty commit to fire a fresh synchronize event so the pull_request:[main]
gated workflows (Unit + doc tests) evaluate now that the PR base was
retargeted from mani/c-abi-statement-canceller (landed as #163) to main.
No content change; squashed away at merge.

Co-authored-by: Isaac
Signed-off-by: Mani Kaustubh Mathur <mani.mathur@databricks.com>

This branch was previously deployed

1 inactive deployment
azure-prod — e0db5fa8 Deployed Jul 13, 2026 by mani-mathur-arch via v0 E2E surface #205
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