Skip to content

masked timeout fix - #270

Merged
coot merged 20 commits into
mainfrom
coot/masked-timeout-fix
Nov 20, 2026
Merged

coot merged 20 commits into
mainfrom
coot/masked-timeout-fix

Conversation

@coot

@coot coot commented Oct 29, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes a race in IOSim and IOSimPOR that could raise a timeout exception after timeout returned (#269). Both simulators now restore masking state after asynchronous exceptions and cancel a blocked throwTo when its caller is interrupted. Regression tests cover these cases.

IOSimPOR now explores races between throwTo and target wake-ups and checks independent schedules in parallel without duplicate evaluation. Previously recorded schedules may replay differently or fail to replay.

@coot
coot requested a review from a team as a code owner October 29, 2026 14:36
@coot coot self-assigned this Oct 29, 2026
@coot coot changed the title coot/masked timeout fix masked timeout fix Oct 29, 2026
coot added 3 commits November 6, 2026 14:41
use `macos-15`, `macos-latest` (Xcode 27) has SDK .tbd stub file using
architecture token that GHC's linker rejects.
I think it's more readable to have
```hs
  MaskedInterruptible -> isThreadBlocked thread
```
rather than the equivalent
```hs
  MaskedInterruptible
    | isThreadBlocked thread -> True
    | otherwise              -> False
```
use `\case` to suppress an hlint warning
@coot
coot force-pushed the coot/masked-timeout-fix branch 2 times, most recently from e908f97 to 745d240 Compare November 10, 2026 15:17
When a timeout fires, its assassin takes the lock of the `TimeoutFrame`,
and then throws the `TimeoutException`.  It could still throw after the
timed thread had left the frame:

* if the action returned after the assassin had taken the lock, but
  before it threw: the thread took the assassin's id with
  `atomically (takeTMVar lock)` before killing it, and committing
  a transaction yields;
* if an exception unwound the frame: its lock was left open, so an
  assassin which was already forked could still take it, and throw.

Now `closeTimeoutLock` closes the lock in `ST`, while leaving the frame,
without yielding.  It fills a free lock, so that the assassin never
takes it.  Otherwise it returns the assassin which holds the lock, and
the thread kills it as its next action, before the assassin can run
again.  `unwindControlStack` returns the locks of all the
`TimeoutFrame`s it unwinds, and they are closed the same way before the
exception handler runs.  Fixed in both `IOSim` and `IOSimPOR`.

This doesn't cover an assassin which has already thrown to a masked
thread: its exception stays pending after it is killed.  That's fixed by
"Cancel a blocked `throwTo` when its thread is interrupted".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@coot
coot force-pushed the coot/masked-timeout-fix branch 6 times, most recently from f82badc to 5710ea5 Compare November 17, 2026 13:12
@coot
coot enabled auto-merge November 17, 2026 14:15
@coot
coot disabled auto-merge November 17, 2026 14:15
@coot
coot force-pushed the coot/masked-timeout-fix branch from 5710ea5 to 071d1a8 Compare November 17, 2026 16:19
coot and others added 10 commits November 18, 2026 10:51
When handling `Throw` after successful unwinding of the control stack,
we run cleanups of unwound TimeoutFrames.  We must wrap them in
`uninterruptibleMask_` but only if it matters, so they are uninterrupted
and pending async exceptions are delivered when `uninterruptibleMask_`
unmasks.  The latter makes sure that continuation after a timeout is not
run before delivery of a pending async exception (the counterexample in
the tests catches that case).

We do the wrapping in `uninterruptibleMask_` conditionally, for
performance reasons and to avoid extra steps in IOSimPOR.
A thread blocked in `throwTo` (its target has async exceptions masked) can
be interrupted: by another thread's `throwTo` (e.g. `killThread`), or by one
of its own pending async exceptions, since `throwTo` is an interruptible
point.  Its exception stayed in the target's `threadThrowTo` and was raised
when the target unmasked: the target received an exception from a `throwTo`
which had already been interrupted, and the scheduler woke the original
thrower, even out of an unrelated block.  In GHC the `throwTo` is cancelled.

`ThrowTo` has two cases:
1. blocking case (`willBlock = True`):
   if the thread is not `MaskedUninterruptible` and there are pending async
   exceptions one of them is raised (since `throwTo` is a blocking call
   in this case). Only otherwise we can add the async exception from
   `throwTo` to the target thread.
2. non-blocking case (`willBlock = False`): the exception is thrown to the
   target, and if the target is blocked in `throwTo`, its exception is
   dropped from the pending async exceptions of its own target (exactly one
   thread, possibly the current one).

The IOSimPOR fix follows the same logic, with a few differences:
* ad 1. the step keeps its `throwToEffect`: whether `e` is thrown depends on
  the masking state of the target.
* ad 2. the exception is dropped only from the thread which holds it in
  its own `threadThrowTo`. IOSim applies `dropThrowToFrom tid'` to all
  threads, which is a no-op for the others, IOSimPOR applies
  `dropThrowToFrom tid'` and modifies effects (see next point).
* ad 2. the current step records a `throwToEffect` for these threads
  (there might be just one such thread), since its pending async
  exceptions change, so that IOSimPOR can find races between this step
  and its steps.
* ad 2. target thread's vector clock is joined with the current one, so
  IOSimPOR knows its later steps depend on this step, and doesn't move them
  before it in a modified schedule (`propExploration` failed with
  "Thread ... not runnable" without it).

`unit_async_10` and `unit_async_11` relied on the old behaviour: child 1 now
survives, as in GHC.
This patch fixes a simple bug where `throwTo tid e1 >> throwTo tid e2`
delivers only `e2`, while `e1` is lost when the first `throwTo` is
non-blocking.

To avoid subsequent `throwTo` overwrite the delivered async exception we
make the target thread interruptible masked.  Then the latter `throwTo`
will land in the `willBlock = True` branch, and the exception will not
be overwritten.  The thread masking state is restored when we unwind the
control stack to find an exception handler - thus any exception handler
will run in the right masking state.

GHC is using the same mechanism to avoid this bug.

`prop_stacked_timeouts` is adjusted, it now agrees with how GHC does
things.  On a tie, the outer timeout now wins.
This eliminates a bug where timeout assassin threads were not marked
as racy; `setRacyThread` is removed.
since `io-sim-por: childThreadId take racy flag` now explores more
races, the `stacked timeout` test needed to be updated.  IOSim test was
only refactored to mach the same style as the IOSimPOR test.
IOSim already does that.  This should be done, because `StartTimeout`
creates a timeout lock.
A `throwTo` to a masked thread, which is blocked in STM, races with
a write which wakes the thread up: if the exception is thrown first, it
interrupts the transaction; if the write is first, the exception is
pending until the thread unmasks, after the transaction committed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
coot added 6 commits November 18, 2026 10:51
As in `IOSim` when cancelling a timeout we should only unblock threads
that were blocked on STM, not any other threads.  `NewTimeout` creates
a `TVar s Bool` to which `CaneclTimeout` writes, thus they might be
unblocked now.  There's no reason to unblock threads that are blocked
for other reasons.
`conjoinSpeculate` is a custom version of `conjoin` from `QuickCheck`.
This patch fixes a performance bug in it.  When a conjunct failed
(`ok result == Just False`), we returned the conjunct itself rather than
its result.  Since `conj` is written in the `Rose` monad, the bind ran
it again, unlike `QuickCheck`'s `conjoin`, which returns the already
reduced rose.

The same happened when a conjunct was discarded (`ok result ==
Nothing`): we returned `rest`, the conjunction of the remaining
conjuncts, instead of its result, so `rest` was evaluated twice.

`exploreSimTrace` nests two conjunctions (`.&&|` and `conjoinPar`) per
level of race reversals, so a failure at depth L was re-evaluated in the
order of `4^L` times; each discarded conjunct on the way doubled it
again.
`conjoinPar` wasn't effective in starting sparks, since the property in
`exploreSimTrace` was wrapping a property inside `counterexample` and
`tabulate` which add `IORose` on top of the property.  We need to run
the `IO` part (using `unsafePerformIO`) and then use `par` to evaluate
the simulation result in parallel using sparks.

This patch gives 2x elapsed time improvement on one o
`cardano-diffusion` tests, with `MUT time / elapsed time` ratio raised
from around 1 to almost 12.
Since `QuickCheck-2.15`, `res { abort = False }` is not needed - since
`2.15` that's the default, so we can drop `againNoCatch`.

We can use `.&&.` instead of our custom `.&&|` since now `conjoinPar`
can now evaluate `IORose`, and `.&&.` is already sequential.
@coot
coot force-pushed the coot/masked-timeout-fix branch from 071d1a8 to 91d156b Compare November 18, 2026 09:52

@karknu karknu left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM

@coot
coot enabled auto-merge November 20, 2026 09:59
@coot
coot disabled auto-merge November 20, 2026 11:29
@coot
coot added this pull request to the merge queue Nov 20, 2026
@github-project-automation github-project-automation Bot moved this to In Progress in Ouroboros Network Nov 20, 2026
Merged via the queue into main with commit 79ff5db Nov 20, 2026
32 checks passed
@coot
coot deleted the coot/masked-timeout-fix branch November 20, 2026 11:47
@github-project-automation github-project-automation Bot moved this from In Progress to Done in Ouroboros Network Nov 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

timeout under mask_: a cancelled assassin's exception is delivered after the frame

2 participants