Skip to content

fix(c_abi): fix #276 Windows DriverManager teardown crash (keep foreign threads out of the runtime + pin the module) - #277

Merged
vikrantpuppala merged 2 commits into
mainfrom
fix/276-c-abi-block-on-foreign-thread
Aug 21, 2026
Merged

vikrantpuppala merged 2 commits into
mainfrom
fix/276-c-abi-block-on-foreign-thread

Conversation

@vikrantpuppala

@vikrantpuppala vikrantpuppala commented Aug 20, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Fixes #276 — on Windows/MSVC, C-ABI entry points driven through the ODBC DriverManager crash during teardown with tokio's EnterGuard values dropped out of order panic / System allocator may not use TLS with destructors abort (and an intermittent hang).

The bug has two independent halves, and both are needed for a full fix:

  1. The foreign caller thread entering the runtime. block_on_ffi called Runtime::block_on on the caller thread, which enters the process-wide runtime and registers tokio's runtime-context TLS there. A foreign OS thread the kernel doesn't own (e.g. the ODBC driver's result-prefetch thread) that is later torn down on Windows drops that context guard out of order during TLS teardown → panic/abort.
    Fix: block_on_ffi now rt.spawns the future onto the runtime's worker threads and blocks the caller on a std::sync::mpsc channel — the caller thread never enters the runtime. (Adds Fut: Send + T: Send; the metadata entry points marshal their C-string args on the caller thread so !Send raw pointers don't cross to workers; a lifetime-extend transmute on the spawned task is sound because the caller blocks until completion.)

  2. The kernel's own worker threads outliving a DLL unload. The process-wide multi-thread runtime is leaked (never shut down) and leaves detached kernel-c-abi OS worker threads alive. The ODBC DriverManager loads and unloads the driver DLL across connections; when FreeLibrary unmaps the DLL while those workers are still alive, they execute freed code (Access Violation) and their tokio context-guard TLS is destroyed out of order (the panic). The in-flight block_on_ffi task then never completes and the caller deadlocks on its result channel — the intermittent hang.
    Fix: at runtime init, pin the kernel's containing module on Windows via GetModuleHandleExW(FROM_ADDRESS | PIN), so the DriverManager's FreeLibrary can never unmap the DLL while its worker threads live. Windows-only; the kernel32 import is declared inline to avoid a new windows-sys dependency and its cargo-deny review.

Root-cause evidence

Reproduced and diagnosed in the databricks-odbc Windows driver-manager e2e (which had skipped paramset_status_test/rowcount_test citing #276). A cdb-symbolicated native stack from CI showed, with only fix (1) applied: the main thread parked in c_abi::block_on_ffi → mpsc::Receiver::recv → Thread::park; a kernel-c-abi worker thread at an Access Violation (c0000005); the tokio current.rs:82 "EnterGuard dropped out of order" panic; and the driver DLL mapped at two different base addresses in one process (proof of DriverManager load/unload). With fix (2) added, the same driver-manager tests go from exit=137 (hang) to exit=0, 6/6 passing, with zero crash indicators in the log.

Test plan

  • cargo test — all kernel tests pass, including the portable regression guard c_abi::tests::block_on_ffi_runs_future_off_the_caller_thread (fails under the old block_on, passes with spawn) and the reentrancy-rejection test.
  • End-to-end: databricks-odbc Windows driver-manager e2e with the driver's kernel pin bumped to this branch — rowcount_test and paramset_status_test pass (previously hung / crashed). Un-skipping those in the ODBC repo is the follow-up gate.

Closes #276.

…ows TLS-teardown corruption

`block_on_ffi` called `Runtime::block_on` on the calling thread. `block_on`
*enters* the process-wide runtime on that thread, registering tokio's
runtime-context thread-local on it. When the caller is a native OS thread the
kernel does not own — the intended ODBC / Go usage, e.g. the ODBC driver's
result-prefetch thread — and that thread is later torn down on Windows/MSVC,
tokio's context guard and the `LAST_ERROR` `CString` thread-local are dropped
during TLS teardown in an order that trips tokio's "EnterGuard dropped out of
order" panic or the "System allocator may not use TLS with destructors" abort
(#276).

Instead, spawn the future onto the runtime's own worker threads and block the
caller on a plain `std` channel. The caller thread never enters the runtime, so
no runtime-context TLS is ever registered on it and there is nothing to corrupt
at teardown. The `Handle::try_current()` reentrancy guard stays: it only reads
(empty-initialises) the caller's context, never enters the runtime.

Because the future now runs on worker threads it must be `Send` (and its output
`Send`). The metadata entry points previously marshalled their raw C-string
pointers inside the spawned async block; move that marshalling onto the caller
thread (before the async block) so only `Send` borrows cross onto the workers,
never the `!Send` raw pointers.

Closes #276

Co-authored-by: Isaac
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.

…d can't dangle its worker threads (#276)

The spawn-not-block_on change alone is insufficient: it keeps the foreign
caller thread out of the runtime, but the process-wide multi-thread runtime
still leaves detached `kernel-c-abi` worker threads alive across the ODBC
DriverManager's load/unload of the driver DLL. When FreeLibrary unmaps the
DLL while those workers run, they execute freed code (Access Violation) and
tokio's per-thread context guard is dropped after its thread-local CONTEXT is
gone -> "EnterGuard values dropped out of order" panic; the in-flight
block_on_ffi task never completes and the caller deadlocks (confirmed via a
cdb-symbolicated Windows CI repro).

Pin the containing module (GetModuleHandleExW FROM_ADDRESS|PIN) at runtime
init so the DLL is never unloaded while its worker threads live. Windows-only;
inline kernel32 decl to avoid a new windows-sys dependency + deny review.

Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
@vikrantpuppala vikrantpuppala changed the title fix(c_abi): drive futures off the foreign caller thread to avoid Windows TLS-teardown corruption fix(c_abi): fix #276 Windows DriverManager teardown crash (keep foreign threads out of the runtime + pin the module) Aug 21, 2026

@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 — solid, well-reasoned fix for #276. Verified: futures is already a dependency, thread-local error propagation still works (errors return by value and are stored on the caller thread), the !Send marshalling is compiler-enforced by the new Fut: Send bound, and the lifetime-extend transmute is sound because the caller blocks on rx.recv() until the future (and its borrows) are dropped. One low-severity note: the Windows module-pin ignores its return value, so a pin failure would silently reintroduce the crash.

Comment thread src/c_abi/mod.rs
pin_containing_module as usize as *const u16,
&mut module,
);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Low — The GetModuleHandleExW return value is discarded. GetModuleHandleExW returns nonzero on success and 0 on failure; on failure module stays null and the PIN silently does not happen. Since this pin is the load-bearing half-2 of the #276 fix (keeping the DLL from being unmapped under its own worker threads), a silent failure would let the teardown crash recur on Windows with no signal pointing back at the pin — exactly the hard-to-diagnose class of bug this PR is fixing.

Consider checking the result and emitting a tracing::warn! (with GetLastError if cheap) so a pin failure is observable rather than invisible. This is best-effort by nature, so low severity — but a one-line log would materially aid future diagnosis.

@vikrantpuppala
vikrantpuppala added this pull request to the merge queue Aug 21, 2026
Merged via the queue into main with commit be4b868 Aug 21, 2026
20 checks passed

This branch was previously deployed

1 inactive deployment
azure-prod — b617d5ff Deployed Aug 21, 2026 by oss-reviewer-bot[bot] via followup #915
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant