Repository navigation
feat(c-abi): expose detached statement canceller for sync execute - #163
Conversation
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>
| /// 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( |
There was a problem hiding this comment.
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
CancellerHandleso 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
Code Review Squad — ReviewScore: 75/100 — MODERATE RISK The core canceller mechanism is memory-safe by construction (cloned Arcs, no Could not post inline comments for: F2, F4, F8 — see body below. Medium FindingsF2 —
|
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>
Code Review Squad — ReviewScore: 77/100 — MODERATE RISK The unsafe/FFI mechanics are sound — three reviewers independently verified the |
…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>
Canceller review — resolution summaryBoth review passes have been addressed, across two commits (68ae83c, e0db5fa). Summary below. Pass 1 (initial review) — all 8 findings fixed in 68ae83cHeader / C-boundary contract
Engine (
Tests
Pass 2 (re-review of
|
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>
Summary
Expose the kernel's existing
StatementCancellerover the C ABI:kernel_statement_canceller_new/_cancel/_free.kernel_statement_executeblocks the calling thread for the whole query, so aC-ABI host cannot cancel it by calling another method on the same statement
handle mid-execute (that would alias the
&mut Statementborrow). A detachedcanceller — obtained before
execute— solves this: it holds only clonedArcs (session + inflight statement id), noStatementborrow, so it is safeto fire from another thread while
executeruns.It is the building block a host driver (e.g. Go
database/sql) uses to honorctxcancellation over a blocking execute (watcher thread → out-of-band cancel).Semantics
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 itreturns.
_cancel(canceller, dispatched)reports through thedispatched: *mut boolout-param whether a cancel RPC was actually sent —
trueonce a serverstatement id has been observed,
falseif none has yet (nothing executed, orstill in the initial round-trip). Both return
Success; a no-op is not anerror.
dispatchedmay be null._cancelblocks on the cancel RPC (which retrieswith backoff on a retryable failure), so a host must quiesce any cancelling
thread before
_free.What changes
src/c_abi/statement.rs— threeextern "C"entry points over a boxedCancellerHandlewrappingStatementCanceller; the cancel path runs throughthe existing
block_on_ffipanic firewall. Purely additive — no existingsymbol or signature changes.
include/databricks_kernel.h— the opaquekernel_statement_canceller_ttypedef, the three declarations, and the canceller's place in the teardown
ordering.
tests/v0_c_abi_canceller_wiremock.rs— drives the entry points against amock SEA server.
Test plan
cargo test—tests/v0_c_abi_canceller_wiremock.rscovers cancel during ablocking 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 warningscleancargo +stable fmt --allcleanAdditive symbols only; ABI-compatible with the sync path.