Skip to content

BLAS: revert the foreign-call cancellation handler from the level-3 wrappers - #1835

Open
vtjnash wants to merge 1 commit into
masterfrom
jn/revert-cancel-unsafe
Open

vtjnash wants to merge 1 commit into
masterfrom
jn/revert-cancel-unsafe

Conversation

@vtjnash

@vtjnash vtjnash commented Nov 2, 2026

Copy link
Copy Markdown
Member

gemm!, symm! and hemm! were annotated @ccall cancel_handler=... with a Julia @cfunction as the handler, so that cancelling the calling task would run _cancel_handler on the thread blocked in the BLAS call, which set the cancel bit of that thread's OpenBLAS token slot. This implementation was unsound in several ways, and relanding can take a much simpler approach still using the changes to libopenblas, so those stay in the binaries.

The handler ran like a signal handler: on Unix inside the SIGUSR2 handler, on macOS and Windows on the frozen thread's stack after a context rewrite. The option's contract was that the handler is async-signal-safe. _cancel_handler itself is integer-only code, but the wrapper Julia emits for any @cfunction compares the global world counter with the world cached in its cfuncdata on every call and, on a mismatch, re-resolves the target through jl_get_abi_converter: method lookup, possibly inference and compilation, locks, malloc. The world counter moves on every method definition in the process, so after any package load or REPL definition the first delivery took that path inside a signal handler, on a thread interrupted at an arbitrary instruction of OpenBLAS, which allocates its own buffers. The wrapper also pushes a GC frame and rewrites the task's world age from the handler. No Julia function can meet the contract, however small its body.

The signal was never needed for what the handler did. openblas_cancel takes the token slot explicitly and performs an atomic store, and the slot is the calling thread's, so the cancelling thread could have set the bit itself. Running on the victim thread only bought passing C_NULL as the state and looking the slot up from the current thread inside the handler, at the cost of all of the above.

Remove the handler, the extension detection in _cancel_detect and its reset in lbt_forward, and the per-call _cancel_prepare and @cancel_check pair around the three calls, which were unconditional and charged every small gemm! for a feature gated on large ones. The calls go back to plain @ccalls. Cancellation of a long BLAS call now waits for the call to return, as it did before the annotation; a cooperative check at a call site belongs to callers that know their work is long.

A reland should drive the cancellation from the cancelling thread, without signals or handlers. The protocol the OpenBLAS patch already provides needs one adjustment: the generation of the slot should be advanced by the caller before the call, not by the driver at entry, so the wrapper can learn it. The wrapper then obtains its thread's slot with openblas_cancel_token() and the fresh generation on the calling thread, publishes the pair in a task field for the duration of the call, and clears it afterwards. cancel! reads the pair from the task on its own thread and calls openblas_cancel(slot, gen), whose compare-and-set on the generation makes a late sender a no-op: a slot that has moved on to another operation, possibly another task's, is never touched. The post-call check then unwinds a genuinely cancelled call before its output escapes, exactly as the wrappers did here, and a cancellation that arrives before the call starts is observed by the pre-call check. That design has no victim-thread execution, no contract on the handler, and no cross-task hazard, and it costs the same handful of stores this annotation did.

Assisted-by: Claude Code (Fable 5.1)

@vtjnash
vtjnash requested review from Keno and KristofferC November 2, 2026 19:54
@codecov

codecov Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.58%. Comparing base (ae5f7dd) to head (56f7246).

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1835      +/-   ##
==========================================
- Coverage   99.58%   99.58%   -0.01%     
==========================================
  Files          35       35              
  Lines       18712    18674      -38     
==========================================
- Hits        18634    18596      -38     
  Misses         78       78              

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@Keno Keno left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This was a deliberate design choice. The PR text hand-waives at an alternative, but does not work it out. The corner cases are a bit nasty.

@vtjnash vtjnash left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Being deliberate in calling a @cfunction from a signal handler doesn't make the implementation seem any less unsound. I don't know the specifics either, just that we can't introduce new regressions when we introduce new features.

@vtjnash

vtjnash commented Nov 6, 2026

Copy link
Copy Markdown
Member Author

Windows runs a new thread (in our terms, a task) to handle signals to avoid the unix design issue where hijacking the state of an existing thread makes it almost unusable for mere mortals. Would that work for you -- sending cancellation runs a new thread/task so that it inherits neither the caller nor callee's unknown state when handling a signal?

@Keno

Keno commented Nov 6, 2026

Copy link
Copy Markdown
Member

That might work, we should survey other libraries and see. Are we comfortable that we can always spin up a new thread even when threading might otherwise not be enabled?

@topolarity

Copy link
Copy Markdown
Member

This was a deliberate design choice.

Deliberate or not, do you agree w.r.t. the problems?

Naively, seems extremely buggy to me for us to try to do cfunction inside signal handlers, since almost nothing is async-signal safe and Julia just doesn't try to respect those constraints as a language. What's the argument that it's OK here?

…rappers

`gemm!`, `symm!` and `hemm!` were annotated `@ccall cancel_handler=...`
with a Julia `@cfunction` as the handler, so that cancelling the calling
task would run `_cancel_handler` on the thread blocked in the BLAS call,
which set the cancel bit of that thread's OpenBLAS token slot. This
implementation was unsound in several ways, and relanding can take a
much simpler approach still using the changes to libopenblas, so those
stay in the binaries.

The handler ran like a signal handler: on Unix inside the SIGUSR2
handler, on macOS and Windows on the frozen thread's stack after a
context rewrite. The option's contract was that the handler is
async-signal-safe. `_cancel_handler` itself is integer-only code, but
the wrapper Julia emits for any `@cfunction` compares the global world
counter with the world cached in its `cfuncdata` on every call and, on a
mismatch, re-resolves the target through `jl_get_abi_converter`: method
lookup, possibly inference and compilation, locks, malloc. The world
counter moves on every method definition in the process, so after any
package load or REPL definition the first delivery took that path inside
a signal handler, on a thread interrupted at an arbitrary instruction of
OpenBLAS, which allocates its own buffers. The wrapper also pushes a GC
frame and rewrites the task's world age from the handler. No Julia
function can meet the contract, however small its body.

The signal was never needed for what the handler did. `openblas_cancel`
takes the token slot explicitly and performs an atomic store, and the
slot is the calling thread's, so the cancelling thread could have set
the bit itself. Running on the victim thread only bought passing
`C_NULL` as the state and looking the slot up from the current thread
inside the handler, at the cost of all of the above.

Remove the handler, the extension detection in `_cancel_detect` and its
reset in `lbt_forward`, and the per-call `_cancel_prepare` and
`@cancel_check` pair around the three calls, which were unconditional
and charged every small `gemm!` for a feature gated on large ones. The
calls go back to plain `@ccall`s. Cancellation of a long BLAS call now
waits for the call to return, as it did before the annotation; a
cooperative check at a call site belongs to callers that know their work
is long.

A reland should drive the cancellation from the cancelling thread,
without signals or handlers. The protocol the OpenBLAS patch already
provides needs one adjustment: the generation of the slot should be
advanced by the caller before the call, not by the driver at entry, so
the wrapper can learn it. The wrapper then obtains its thread's slot
with `openblas_cancel_token()` and the fresh generation on the calling
thread, publishes the pair in a task field for the duration of the call,
and clears it afterwards. `cancel!` reads the pair from the task on its
own thread and calls `openblas_cancel(slot, gen)`, whose compare-and-set
on the generation makes a late sender a no-op: a slot that has moved on
to another operation, possibly another task's, is never touched. The
post-call check then unwinds a genuinely cancelled call before its
output escapes, exactly as the wrappers did here, and a cancellation
that arrives before the call starts is observed by the pre-call check.
That design has no victim-thread execution, no contract on the handler,
and no cross-task hazard, and it costs the same handful of stores this
annotation did.

Assisted-by: Claude Code (Fable 5.1)
@vtjnash
vtjnash force-pushed the jn/revert-cancel-unsafe branch from 83763d7 to 56f7246 Compare December 3, 2026 18:16
@vtjnash
vtjnash added this pull request to stack #2009 December 3, 2026 18:37

This branch has not been deployed

No deployments
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.

3 participants