Skip to content

fix(napi): release the session when an AsyncStatement closes - #462

Merged
vuanhphung merged 10 commits into
mainfrom
fix/napi-release-session-at-close
Nov 16, 2026
Merged

vuanhphung merged 10 commits into
mainfrom
fix/napi-release-session-at-close

Conversation

@vuanhphung

@vuanhphung vuanhphung commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Bug: On Node, a closed AsyncStatement keeps the kernel session alive until JS garbage collection. close() left the detached canceller in place, and the AsyncResultHandle from awaitResult() kept its ResultStream until Drop. Both hold Arc<SessionInner>, so the host's shared telemetry lease (src/telemetry/manager.rs:98-124) never reached zero. A later session on the same host then reused that client and ignored its own telemetryBatchSize / telemetryFlushIntervalMs. The Node driver hits this on runAsync: true, and on the default path whenever the direct POST isn't terminal. Found by the driver-test TELEMETRY-015 test.

Change: close() drops the canceller and empties the result slot of every AsyncResultHandle it returned, whether or not the close RPC succeeds. It skips a slot that an in-flight fetchNextBatch() holds (try_lock), so close never waits for a fetch; that stream stays referenced until the handle is collected, as before. Fetching from a released handle returns InvalidStatementHandle. CancellableExecution keeps a canceller the same way, but the Node driver doesn't call executeStatementCancellable (lib/kernel/KernelSessionBackend.ts), so it isn't touched here.

Size: 62 added and 12 removed non-test lines, about 38 of them code; previously 158 and 34. close() and fetchNextBatch() (and index.d.ts) document the handle invalidation. The hardening below was removed to keep the fix minimal.

Follow-ups, not in this PR:

  • Release a stream that is mid-fetch when close() runs, once that fetch returns. An earlier revision did this with a closed flag plus a spawned release; a flag-only handoff misses under Release/Acquire ordering, so it needs the spawned release.
  • Release on a panicking close RPC (a drop guard).
  • Release the result slots from AsyncStatement's Drop task too, for a statement collected without close().
  • Prune dead Weaks when one statement calls awaitResult() repeatedly.

Testing:

  • napi wiremock tests, each checked against a mutant: the canceller and result-handle lease tests fail without their release (the second session exports at once), close_does_not_wait_for_an_in_flight_fetch times out if close() awaits the slot lock, and close_releases_session_when_the_close_rpc_fails fails if close() returns early on the RPC error.
  • In napi, cargo fmt --all -- --check, cargo clippy --all-targets --locked -- -D warnings and cargo test --locked --features dyn-symbols pass (91 tests).
  • Live Node on SEA, databricks-sql-nodejs f436057 with a binding built from 4c4d4de: the TELEMETRY-015 tripwire in databricks-driver-test#2069 throws XPASS in 2/2 runs. It reports xfail with the pinned kernel 0b5d0ed. The Node path closes after fetching, so the trim doesn't change it; the earlier revision 06e4048 also passed TELEMETRY-015 3/3 in driver-test main's telemetry file.
Cell Before After
TELEMETRY-015 nodejs sea (#2069 tripwire) xfail XPASS

This reaches Node through a KERNEL_REV bump.

This pull request and its description were written by Isaac.

AsyncStatement.close() left its detached canceller in place and never
released the result streams of the AsyncResultHandles it returned. Both
hold the kernel session, so the host's shared telemetry client stayed
alive until JS garbage collection. A later session on the same host then
reused it and ignored its own batch size and flush interval.

close() now drops the canceller and empties every result slot it handed
out, even if the close RPC fails. Fetching from an AsyncResultHandle after
its statement is closed returns InvalidStatementHandle.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Vu Anh Phung <vu.phung@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 release-on-close logic is sound: the slot is registered while inner is held, so a queued close() always sees it, and resources are released even when the close RPC fails. Each wiremock test opens its own mock server, so their hosts don't collide. One low-severity concern: close() now waits behind any in-flight fetchNextBatch().

Comment thread napi/src/async_statement.rs Resolved
fetchNextBatch() holds the result slot's mutex for the whole batch fetch,
so awaiting that mutex in close() held the close promise until the fetch
finished. close() now marks each slot closed and takes the stream only if
the slot is free. A fetch that holds the slot drops the stream when it
returns.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Vu Anh Phung <vu.phung@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: 2 Low

Looks good, with 2 low-severity notes. The close/fetch handoff is sound: close() sets closed and then calls try_lock, and a fetch checks the flag again after dropping its guard, so no interleaving leaves the stream held. One remaining case is out of scope: when the statement is dropped without an explicit close(), Drop does not release live result handles. That matches the previous behaviour.

Comment thread napi/src/async_statement.rs Resolved
Comment thread napi/src/async_statement.rs Resolved
close() set the slot's closed flag and then tried the lock, while a
finishing fetch released the lock and then read the flag. With
Release/Acquire ordering both sides can miss each other, so neither drops
the stream and the session stays alive until JS GC. A same-primitive
litmus run hit this 181 times in 3M iterations.

When the slot is busy, close() now spawns a task that waits for the lock
and drops the stream, so the release no longer depends on the fetch
noticing. Also prune dead result slots when registering a new one, and
test that a failed close RPC still releases the canceller and stream.

Signed-off-by: Vu Anh Phung <vu.phung@databricks.com>
Co-authored-by: Isaac <no-reply@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: 2 Low

Looks good overall, with two low-severity concerns: if the close RPC panics, the canceller and result slots are never released, and the user-facing docs were not updated for the new fetch-after-close contract. The try_lock/spawn release design, registering the slot while inner is held, and the wiremock coverage all look sound.

Comment thread napi/src/async_statement.rs Resolved
Comment thread napi/src/async_statement.rs Resolved
A panic in the close RPC skipped the release of the canceller and result
streams, and a retried close() returns early, so the session leaked again.
The release now lives in a drop guard created before the RPC, so it runs on
return and on unwind.

Document on AsyncStatement.close() and AsyncResultHandle.fetchNextBatch()
that closing the statement invalidates the handles awaitResult() returned,
and mirror it in index.d.ts.

Signed-off-by: Vu Anh Phung <vu.phung@databricks.com>
Co-authored-by: Isaac <no-reply@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.

…l fix

Keep only what TELEMETRY-015 needs and what avoids a regression: close()
drops the canceller and empties every idle result slot, and skips a slot
an in-flight fetch holds, so close never waits for a fetch.

Drop the hardening that came after: the closed flag, the spawned release
of a busy slot and its runtime-handle fallback, the drop guard for a
panicking close RPC, dead-Weak pruning, and the doc and index.d.ts
additions, along with the tests that only covered them.

Signed-off-by: Vu Anh Phung <vu.phung@databricks.com>
Co-authored-by: Isaac <no-reply@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 High · 2 Medium · 1 Low

The fix covers the common path, but a slot that a fetch holds during close() is never released, and the release is skipped if the close RPC panics. The code here also doesn't match the PR description: there is no spawned release task, no drop guard, and the listed tests and doc updates are missing.

Comment thread napi/src/async_statement.rs Resolved
// rather than firing a wire cancel on a closing statement.
closed.store(true, Ordering::Release);
ExecutedAsyncStatement::close(&mut inner_state.executed_async)
let outcome = ExecutedAsyncStatement::close(&mut inner_state.executed_async)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium — The release only runs if ExecutedAsyncStatement::close(...).await returns. If the close path panics, guarded's catch_unwind turns the panic into an error and skips the release block. The future can also be dropped mid-RPC (for example on runtime shutdown). In both cases inner has already been taken and closed is already set, so a retried close() returns Ok(()) at L389 and never releases the canceller or result slots. The PR description says the release runs from a drop guard so it also covers panics. Put the canceller/results release in a guard struct whose Drop does it, created before the RPC await, or at least run the release before awaiting the RPC.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Also deliberate scope. Before this PR, a panic in the close RPC (or the future being dropped at runtime shutdown) likewise left the canceller and streams to GC, so this is not a regression the PR introduces. No test can drive a panic through the kernel close RPC from the binding. The release runs inline after the RPC returns, so it still covers an RPC error (close_releases_session_when_the_close_rpc_fails). I kept it after the RPC rather than before so the kernel finalizes statement telemetry first. The drop guard is listed as a follow-up in the PR body.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Fair point: this isn't a regression. Before this PR a panic or a dropped future also left these resources for GC to clean up, and putting the release after the RPC so the kernel finalizes telemetry first makes sense. The gap is still in the code at L398, though. Once inner is taken and closed is set, a panic or a dropped future means a retried close() returns Ok(()) without ever releasing the canceller or result slots. I'm leaving this thread open so the drop-guard follow-up stays visible, rather than resolving it on deferred scope. If you'd rather not build the full guard now, a small Drop struct that does only the release and gets disarmed after the inline release would keep your telemetry ordering and close the gap. Otherwise, linking the follow-up issue here would be enough for a human to resolve this thread.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Leaving this for the user, as you suggest. The drop guard is in the PR's follow-ups list. I can't file the tracking issue myself; I have flagged it for the user, who can link it here.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Thanks, flagging it for the user is the right move. The code at L398 hasn't changed: the canceller and result-slot release still only runs after the RPC returns. So the gap is still there if the close panics or its future is dropped, and I'm leaving this thread open. A human can resolve it once the follow-up issue for the drop guard is linked here, or once the guard is added.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The follow-ups (drop guard for a panicking close, release of a busy slot after its fetch, release from the Drop path) are listed in the PR body, and the maintainer will track them.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Thanks. Having the follow-ups in the PR body for the maintainer to track works for me. The code at L398 still runs the canceller and result-slot release only after the close RPC returns, so I'm leaving this thread open as the visible marker until the drop guard lands or a human resolves it with the tracking link.

Comment thread napi/src/async_statement.rs Resolved
Comment thread napi/src/async_statement.rs Resolved
@vuanhphung

Copy link
Copy Markdown
Collaborator Author

Scope trim in 4c4d4de: the PR is now the minimal fix (50 added / 12 removed non-test lines, previously 158 / 34). close() drops the canceller and empties idle result slots; it skips a slot an in-flight fetch holds (try_lock), so it never waits for a fetch. The closed flag, spawned busy-slot release and runtime fallback, panic drop guard, dead-Weak pruning, and the doc/index.d.ts additions discussed in earlier threads are removed and listed as follow-ups in the PR body.

State the user-facing change on close() and fetchNextBatch(), and mirror
it in index.d.ts. A handle that was mid-fetch at close is left as before.

Signed-off-by: Vu Anh Phung <vu.phung@databricks.com>
Co-authored-by: Isaac <no-reply@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: 2 Low

Looks good: the canceller and result slots are released correctly on both the success and error paths of the close RPC, and I found no correctness issues in the locking. I have two low-severity notes: the same session leak is still reachable through Drop when JS never calls close(), and the in-flight-fetch test doesn't assert the documented state after close.

Comment thread napi/src/async_statement.rs Resolved
Comment thread napi/src/async_statement.rs Resolved

This branch was previously deployed

1 inactive deployment
azure-prod — 24032253 Deployed Nov 16, 2026 by oss-reviewer-bot[bot] via followup #3368
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