Skip to content

feat(c-abi): result-stream canceller to interrupt an in-flight next_batch (odbc#355) - #312

Merged
vikrantpuppala merged 4 commits into
mainfrom
feat/355-stream-abort
Sep 3, 2026
Merged

vikrantpuppala merged 4 commits into
mainfrom
feat/355-stream-abort

Conversation

@vikrantpuppala

Copy link
Copy Markdown
Collaborator

Summary

Adds a detached result-stream canceller to the kernel C ABI so a host driver can interrupt an in-flight kernel_result_stream_next_batch — the kernel prerequisite for databricks-odbc#355 part B (cancelling a prefetch thread blocked inside a batch fetch) and, transitively, its bounded-teardown story.

kernel_result_stream_next_batch blocks the calling C thread on a batch fetch that, for a CloudFetch-linked result, can take as long as the underlying request's own timeout. A host fetching on a background thread (the ODBC prefetch thread) had no way to interrupt it, so SQLCancel / SQLCloseCursor / statement or connection teardown could wait for that request instead of returning promptly.

What changed

New C ABI (mirrors the statement canceller's clonable-Arc ownership, but backed by a client-side tokio-util CancellationToken — no server RPC):

  • kernel_result_stream_canceller_new(stream, out) — clones the stream's cancellation token into a detached handle. Borrows none of the stream's mutable state, so it is safe to obtain while a next_batch is in flight and to fire concurrently with next_batch/close on the owning thread.
  • kernel_result_stream_canceller_cancel(canceller) — flips the token (non-blocking, idempotent). next_batch drives each fetch inside a tokio::select! (biased toward the fetch) against the token, so a cancel fired mid-fetch unwinds it and next_batch returns KernelStatusCode_Cancelled promptly. Once fired, the stream is permanently aborted (every later next_batch returns Cancelled rather than re-driving a reader left at an indeterminate position).
  • kernel_result_stream_canceller_free(canceller) — drops the box (no RPC); free order relative to kernel_result_stream_close is unconstrained.

databricks_kernel.h updated to match.

Test plan

  • cargo test --lib c_abi::result — 6 pass, including:
    • cancel_interrupts_an_in_flight_next_batch — headline: parks next_batch inside a blocking reader and interrupts it from another thread; asserts Cancelled returns before the (never-fired) release.
    • cancel_before_next_batch_returns_cancelled, canceller_outlives_stream_close, canceller_null_guards_return_invalid_argument.
  • cargo test --test v0_c_abi_result_stream_canceller_wiremock — proves the exported symbols link and abort a live stream over a real session + wiremock transport.
  • cargo fmt --check + cargo clippy --lib clean.

Notes

Part C of odbc#355 (bounded connection-close teardown) needs no kernel ABI: an abandoned execute's statement handle holds its own Arc<SessionInner>, so the ODBC reaper can detach it and close the session without a use-after-free. That bound is implemented on the ODBC side.

This pull request and its description were written by Isaac.

…atch (odbc#355-B)

kernel_result_stream_next_batch blocks the calling C thread on a batch
fetch that, for a CloudFetch-linked result, can take as long as the
underlying request's own timeout. A host driver fetching on a background
thread (the ODBC prefetch thread) then had no way to interrupt it, so
SQLCancel / SQLCloseCursor / statement or connection teardown could wait
for that request rather than returning promptly (databricks-odbc#355-B).

Add a detached result-stream canceller mirroring the statement canceller's
clonable-Arc ownership, but backed by a client-side tokio-util
CancellationToken instead of a server RPC:

  * kernel_result_stream_canceller_new clones the stream's token into a
    detached handle. It borrows none of the stream's mutable state and
    issues no RPC, so — unlike the statement canceller — it is safe to
    obtain WHILE a next_batch is in flight and to fire concurrently with
    next_batch/close on the owning thread.
  * kernel_result_stream_canceller_cancel flips the token (non-blocking,
    idempotent). next_batch drives each fetch inside a tokio::select!
    (biased toward the fetch) against the token, so a cancel fired mid-fetch
    unwinds it and next_batch returns KernelStatusCode_Cancelled promptly.
  * Once fired the stream is permanently aborted: every later next_batch
    returns Cancelled rather than re-driving a reader left at an
    indeterminate position (the fetch future was dropped mid-await).
  * kernel_result_stream_canceller_free drops the box (no RPC); its order
    relative to kernel_result_stream_close is unconstrained.

Tests: a crate-internal unit test parks next_batch inside a blocking reader
and interrupts it from another thread (the headline in-flight case), plus
pre-fire, permanence, outlives-close, and null-guard cases; an integration
test proves the exported symbols work over a real session + wiremock
transport. Header updated to match.

Part C (bounded connection-close teardown) needs no kernel ABI: an
abandoned execute's statement handle holds its own Arc<SessionInner>, so
the ODBC reaper can detach it and close the session without a
use-after-free; that bound lives on the ODBC side.

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 Medium

Solid, well-documented feature with good test coverage; the _cancel/token design (separate Sync CancellationToken box) is sound and correctly interruptible. One medium concern: canceller_new forms a whole-struct &ResultStreamInner while next_batch holds a &mut to the same struct on another thread — the exact concurrent use the safety docs sanction — which is an aliasing/UB violation even though the accessed fields are disjoint.

Comment thread src/c_abi/result.rs Resolved
@vikrantpuppala

Copy link
Copy Markdown
Collaborator Author

Consumed by databricks-odbc#362 (issue databricks-odbc#355, parts B & C). The ODBC driver's result-set teardown fires kernel_result_stream_canceller_cancel before joining its prefetch thread, so a SQLCancel / SQLCloseCursor / connection close no longer waits out an in-flight batch fetch. That PR pins the kernel at this branch's head for now and will re-pin to this PR's squash-merge commit once it lands.

…_new sound during next_batch (odbc#355 review F1)

kernel_result_stream_canceller_new and next_batch both formed a reference
over the WHOLE ResultStreamInner (.as_ref() / .as_mut()). The API docs
bless calling canceller_new while a next_batch is in flight on another
thread — but a whole-struct &mut carries a noalias guarantee over the
entire allocation, so a &ResultStreamInner (canceller_new) overlapping a
live &mut ResultStreamInner (next_batch, held across the fetch) is UB at
the reference level even though each side only touches a different field.

Fix: split ResultStreamInner into its two fields at the access site via
raw-pointer projection. next_batch and get_schema now take &mut only of
(*p).shape (addr_of_mut!) and clone (*p).cancel through addr_of!;
canceller_new reads only (*p).cancel through addr_of!. The fetch's live
borrow therefore covers only `shape`, and a concurrent canceller_new's
read covers only `cancel` (a Sync atomic) — disjoint fields, never an
overlapping whole-struct reference, so the documented concurrent-obtain
contract is now actually sound.

The headline in-flight test now obtains the canceller AFTER the fetch
thread has parked inside next_batch (rather than before spawning it), so
it exercises the concurrent canceller_new-during-next_batch path the docs
bless and the fix protects — run under miri / ThreadSanitizer to check the
aliasing at the reference level.

cargo test c_abi::result (6) + the canceller wiremock integration test
pass; clippy + fmt clean.

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 Medium

Solid, carefully-reasoned addition — the disjoint-field raw-pointer projection correctly avoids the whole-struct &mut noalias hazard against a concurrent canceller_new, and the biased select! + pre-check give clean permanent-abort semantics. One medium concern: the in-flight cancellation tests all cover only the Owned (metadata) shape, leaving the Executed (sync-execute) path — the actual ODBC consumer path this feature targets — untested. Nit: the header/doc phrase "CloudFetch-link" (databricks_kernel.h and result.rs comments) reads better as "CloudFetch-linked".

Comment thread src/c_abi/result.rs Resolved

@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 Medium · 1 Low

Solid, well-documented addition — the raw-pointer field-projection soundness argument (disjoint cancel vs shape, Sync token) holds, dependency tokio-util is already declared, and the null-guard/error conventions match the existing statement canceller. Two calibration notes: the Executed (sync-execute) stream shape — the path odbc#355-B actually targets — has no cancel test (only the Owned/metadata shape is exercised), and the "batch fetch is abandoned" wording understates that the underlying CloudFetch download continues detached after a cancel.

Comment thread src/c_abi/result.rs Resolved
Comment thread src/c_abi/result.rs Resolved
…hapes; clarify client-side scope (odbc#355 review)

Two review follow-ups on #312:

- F1 (Executed-arm cancel logic untested): the Owned and Executed shapes had
  duplicated tokio::select! + Arrow-variant-mapping blocks, so the reviewer
  correctly noted the Executed arm's cancellation path was never exercised (all
  tests build Owned streams). Extract one shared async wrapper, select_next_batch,
  that both arms route their next_batch future through — generic over
  Borrow<ResultBatch> so it takes the owned arm's Option<ResultBatch> and the
  executed arm's Option<&ResultBatch> alike. The cancellation/select logic is now
  a SINGLE code path, so the mid-fetch-cancel unit test covers the exact select!
  the Executed arm uses; the arms differ only in how they produce the batch
  future and the Executed arm's executed_ref stale-handle guard.

- F2 (client-side scope): document on ResultStreamInner that firing the token
  bounds the CALLER'S wait (drops the next_batch future) but does NOT abort the
  underlying CloudFetch download — the provider's spawned download task keeps a
  worker + connection busy until it finishes/times out. A host wanting bounded
  teardown gets a bounded caller-return, not immediate reclamation; close the
  stream to release the download on its own completion.

cargo test c_abi::result (6) + clippy + fmt clean.

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

Looks good — the C ABI additions are careful and well-documented. The central soundness claim (disjoint-field raw-pointer projection so a concurrent canceller_new reading cancel never aliases next_batch's &mut shape) holds, the biased select + pre-check + permanent-abort semantics are correct, and the header matches the implementation. One low-severity consistency note about a missing panic guard.

Comment thread src/c_abi/result.rs Resolved
… (odbc#355 review)

Its two siblings (_cancel, _free) guard their bodies with catch_ffi so a panic
cannot unwind across the extern "C" boundary (UB); _new did not, despite doing
strictly more work (Box allocation + ptr::write). Wrap it too for panic-safety
and uniformity. catch_ffi also clears the thread-local error up front, replacing
the explicit clear_error(). No behavior change on the success/null-guard paths.

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.

✅ No issues identified by the review bot.

@vikrantpuppala
vikrantpuppala added this pull request to the merge queue Sep 3, 2026
@vikrantpuppala
vikrantpuppala removed this pull request from the merge queue due to a manual request Sep 3, 2026
@vikrantpuppala
vikrantpuppala added this pull request to the merge queue Sep 3, 2026
Merged via the queue into main with commit 1c6cdda Sep 3, 2026
21 of 22 checks passed

This branch was previously deployed

1 inactive deployment
azure-prod — 5b4efa35 Deployed Sep 3, 2026 by oss-reviewer-bot[bot] via followup #1274
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.

1 participant