Skip to content

t-1166: DST sim runtime (clock, mux, I/O identity) - #1

Merged
dimenus merged 50 commits into
mainfrom
sim/dst-m1
Aug 27, 2026
Merged

dimenus merged 50 commits into
mainfrom
sim/dst-m1

Conversation

@dimenus

@dimenus dimenus commented Aug 27, 2026

Copy link
Copy Markdown
Owner

Summary

  • Deterministic sim path for DST: clock/futex seams, one Loop.poll wait, deposit conservation, submit-time I/O ids through park/wake/cancel/complete.
  • Terminal sim submit errors complete (no send-after-close deadlock). Production suite 667/667. Fast-forward-clean onto main.
  • Pin for starh2 tools/zio-dst: 913ffda. Sol Extra High approved. Do not merge until Ryan says.

Test plan

  • zig build test on this pin (667/667 locally)
  • starh2 harness D1–D5 + fixtures on the matching starh2 PR
  • Confirm no leftover harness-only debug in production paths

lalinsky and others added 30 commits August 20, 2026 08:28
The no-task (foreign/pool-thread) `Waiter` park went straight to a futex
wait and only ever returned on completion — a `.allow_cancel` wait was
silently uncancelable. Cancellation (SIGURG on the worker's bound token)
was absorbed as a spurious wakeup and the thread re-parked.

Wrap the `.allow_cancel` futex park in a `syscall_cancel.Syscall` region:
SIGURG interrupts the futex with EINTR, and `checkCancel` turns a pending
cancel into `error.Canceled`. The token is reached through the threadlocal
that `Token.enter` binds, so nothing has to be threaded through the Waiter.

When no token is bound (a foreign thread with no cancellation source),
`begin()` yields a null-token no-op and the park behaves exactly as before,
so existing callers are unaffected. `.no_cancel` always takes the plain
path. Enables cancellation of blocking-thread parking (sleep/await/futex on
a pool worker) for the blocking std.Io direction (issue lalinsky#567).
…sky#570)

`AnyBlockingTask.cancel()` was a stale flag with a TODO. Wire it to the
SIGURG cancellation machinery so a canceled blocking task's worker is
actually interrupted at any cancelable point inside the task's function.

Launch stays pool-direct (spawnBlocking remains callable from any thread);
only cancellation touches a loop:

- AnyBlockingTask gets an embedded `token`, bound by the pool worker via
  `work.cancel_token`, so a cancelable syscall inside the function is
  interruptible by SIGURG.
- cancel() cancels the pool work (first SIGURG) and, on the canceling
  coroutine's current loop, arms the loop's resend if the worker is blocked.
  It takes a keep-alive ref so the work (and its token) can't be freed while
  it may sit on the resend list — this replaces the loop-managed-completion
  removal guarantee that pool-direct work doesn't have.
- The ref is dropped via a new per-Work `resend_release` hook, fired by
  sweepResend when it unlinks the entry on ack (or inline when no resend was
  armed). Since the hook runs on the loop thread after the entry is removed,
  the work can never be freed while still on the list.
- Loop.cancelWork(work) exposes the arm-and-resend step for pool-direct work.
- Off a loop thread (foreign caller), cancel() falls back to a best-effort
  single signal with no resend.

Groundwork for the blocking std.Io direction (issue lalinsky#567). Cancelable
syscalls inside the task are interrupted now; making a Waiter park (sleep/
await/futex) inside the task cancelable additionally needs the cancelable
Waiter-park change, tracked separately.
* io: add Runtime.blockingIo() for blocking std.Io dispatch

Tag the low bit of the std.Io userdata pointer to select between
coroutine-based (spawnTask) and thread-pool-based (spawnBlockingTask)
dispatch in the concurrent/async/group vtable methods. Everything else
in the vtable is shared.

awaitOrCancel now uses Awaitable.getResultSlice() to copy results
generically instead of hardcoding AnyTask, so it works for both task
kinds without a second vtable.

Groundwork for issue lalinsky#567 (blocking std.Io implementation).

* group: fix groupSpawnBlockingTask to use the group closure variant

groupSpawnBlockingTask was using .regular (fn(ctx, result) void) with
result_len=0, which is the wrong Closure.Start variant for group tasks.
Switch to .group (fn(ctx) void) to match groupSpawnTask.

* io: use groupSpawnBlockingTask in vtable group impls

The .threaded branches in groupAsyncImpl and groupConcurrentImpl were
calling spawnBlockingTask directly instead of going through the helper,
unlike the .evented branches which already used groupSpawnTask.

* io: rename Mode variants to regular/blocking

* blocking_task: reserve a thread for std.Io concurrent dispatch

The std.Io concurrent contract guarantees the task will actually run
concurrently. Set reserve_thread on blocking tasks spawned through the
vtable so the pool spins up an extra worker when saturated, preventing
deadlock when a caller waits on a future queued behind itself.

Only the std.Io vtable paths set this; zio's own Runtime.spawnBlocking
and Group.spawnBlocking are called from coroutines on the event loop
and don't hold pool slots.
…e parked (lalinsky#691)

Rewrite ConditionFutex to track waiter and signal counts in a packed u32
state word, matching the design from std.Io.Condition. signal() and
broadcast() now return early when no threads are parked, avoiding
unnecessary futex syscalls.

Also move thread_pool's condition signal outside the queue mutex to
eliminate immediate lock contention from woken workers.
…alinsky#692)

zio.checkCancel() was a silent no-op on thread pool workers because
there is no executor or AnyTask on those threads. Fall through to
syscall_cancel.checkCanceled() when no task context exists, so blocking
tasks can observe cancellation through the same public API.
Cleanup that a cancellation can skip leaves the file or directory behind
for good, with nothing left to retry it. deleteFileUncancelable and
deleteDirUncancelable run the unlink through waitForIoUncancelable, like
close() does, and deleteTreeUncancelable walks the tree under a
cancellation shield so a canceled task cannot abandon it half done.

Each comes with an error set that has no Canceled in it, which is the
point: a deinit handling error.Canceled from a delete either writes a
branch that cannot be taken, or quietly reports a cancellation as a
failed delete. DeleteTreeError is now that set plus Cancelable.

The temporary file and directory cleanup paths were already doing this by
hand, so removeTempTree is gone and removeTempFile is down to the log
call it wraps; AtomicFile.deinit goes through the same helper.
FileReader, FileWriter and Mode were pub in fs.zig, but fs.zig itself is
not exported from zio.zig, so none of them could be named from outside
the package. That left File.preferred_mode unusable and the reader/writer
types reachable only through @typeof.

Alias Reader and Writer inside File and nest the Mode enum there, matching
std.Io.File and zio's own net.Stream, which already nests its Reader and
Writer.
Re-arming a cancellation that a cancellation point already reported was
only reachable through getCurrentTask().recancel(), i.e. through an
internal API. Expose it as zio.recancel(), mirroring std.Io.recancel and
the checkCancel/beginShield/endShield wrappers: a no-op outside a task
context, where a blocking task's cancellation is never consumed and so
needs no re-arming.

AnyTask.recancel() asserted user_canceled, which is stricter than
std.Io.recancel's "error.Canceled was returned from a prior cancelation
point" and does not fit a public API: a task canceled by withTimeout has
auto_canceled set instead. Assert the task is under a cancellation of
either kind. That also covers waitForIo, which re-arms when an operation
completes successfully despite a cancel request and could reach the
assert from an auto-cancel.
## Problem

A task canceled while parked in `select()` returned `error.Canceled`
even when a queuing future had already COMMITTED a result to it. For a
channel branch, the sender's `tryClaim` on the select waiter succeeds
any time no winner is set — including while the cancel is landing — and
the claim copies the item into the select's stack context. The cleanup
absorbed the in-flight signal and then discarded the result, so the
item vanished: it was neither in the channel nor delivered. An item
that carries ownership (starh2's write acks carry accounting releases)
leaked on every teardown race; the starh2 suite hit the deinit
accounting assert in roughly 2 of 9 runs.

`Channel.receive` already keeps the conservation promise for the same
race: on cancellation it absorbs the in-flight signal and returns the
item instead of `error.Canceled`. `select` violated its own protocol
comment ("false: ... The future has committed to waking this waiter").

## Change

The cancel path now runs its own epilogue instead of falling through
the shared defer:

1. Cancel every registered branch. `asyncCancelWait` returning false is
   the commitment signal — and a claim can land DURING this loop, which
   is why the winner decision must come after it, not before.
2. Absorb every in-flight signal (`waiter.wait(expected, .no_cancel)`).
   This is also what orders the claimed result's copy before the read.
3. If a branch won, return its result; the task's cancellation stays
   pending and re-fires at the next cancelable operation (the same
   semantics `Channel.receive` has). Otherwise return `error.Canceled`.

A `cleanup_done` flag keeps the normal-path defer from double-canceling
and double-counting after the epilogue ran.

## Test

`select: canceled select delivers a claimed channel item` races a
`trySend` against `cancel()` of a parked select, 2000 iterations, and
asserts the conservation law: the item is either still in the channel
or was returned. Against the unpatched select it fails at iteration 0.
The existing `select: with cancellation` test (no queuing branch, no
committed result) still expects `error.Canceled` and still passes.

## Known same-class gap, not fixed here

`selectAwaitables` (the `std.Io.selectImpl` path) has the same cleanup
shape, but it returns only an index and result extraction belongs to
the caller, so the fix belongs in that caller's layer.

Co-Authored-By: Claude Fable 5 <[email protected]>
(cherry picked from commit 84bb04c)
`select()`'s registration loop trusted a boolean `asyncWait`: false meant
"already complete", and select then did a BLIND `winner.store(i)`. Branches
registered earlier in the same pass were already claimable, so a concurrent
producer could claim one (winner CAS, item copied into the select's stack
context, signal sent) and the store overwrote the claim: select returned
the later branch, the claimed item died on the dead frame, and cleanup's
signal accounting undercounted (a signal could land on a dead stack
waiter). In starh2 this dropped inbound wire chunks and write acks at a
measured 8-in-30 full-suite runs (diagnostic CAS panic in the fast path);
the visible tail was a 34-byte outbound-accounting leak at connection
teardown.

An independent cross-vendor review (GPT 5.4, 2026-08-20, recorded in
starh2 captures/select-clobber-review-answer.txt) confirmed the race from
source and rejected a naive claim-before-consume patch: a boolean protocol
cannot express "lost, nothing registered", and a prefix registration count
breaks once a lost branch can sit between two queued ones.

- `common.AsyncWaitState`: `asyncWait` now returns `.ready | .queued |
  .lost`. `.ready` means the future WON the select (called
  `waiter.tryClaim()`) BEFORE any consuming side effect; `.lost` means
  another branch already won and the future consumed and registered
  nothing. Direct waiters always claim successfully, so non-select paths
  treat `.lost` as unreachable.
- `select()` / `selectAwaitables()`: per-branch state (`untouched |
  queued | lost`) replaces the prefix `registered_count`; cleanup cancels
  exactly the queued set and counts expected signals per branch. A pass
  that observes `.lost` absorbs the winner's in-flight signal and delivers
  its result.
- Implementations updated to claim-before-consume: channel
  receive/send (buffered take, peer handoff, closed), broadcast channel
  (lagged/available/closed arms), CompletionQueue ready path, ResetEvent,
  Future, Awaitable, JoinHandle, Group, Signal (claim before the consuming
  counter swap), Notify and Timeout (always `.queued`).
- The protocol doc in select.zig carries the new contract.

An unbuffered select-vs-select rendezvous (a select-send racing a
select-receive with no buffer) can win a select and then find every peer
lost. That composition is unsupported in this fork and panics with a
named message instead of stranding the select. Every consumer here uses
direct senders (`send`/`trySend`), whose claims cannot fail.

- zio suite: 634/634 before and after.
- starh2 repro `tools/select-cancel-repro` (cancel-path conservation):
  clean 200k iterations.
- starh2 repro `select-clobber-repro`: clean 2M iterations.
- The in-situ gate is the starh2 suite soak on this commit; the previous
  rate was 8-in-30 diagnostic panics and ~1-in-8 accounting-leak crashes.

Co-Authored-By: Claude Fable 5 <[email protected]>
(cherry picked from commit b4fabaa)
A seven-branch select (starh2's connection actor) exceeded the default
1000 backwards-branch quota inside the WaitContext plumbing and failed to
compile. Quota raised in select(); selectAwaitables is runtime-shaped and
unaffected.

Co-Authored-By: Claude Fable 5 <[email protected]>
(cherry picked from commit 3025548)
* sync: remove Notify

Notify is edge-triggered with no persistent state, so it cannot
express committable readiness for the select/future protocol.
Dropped ahead of the select protocol rework rather than giving
it permit semantics.

* docs: name the removed API as zio.Notify in the changelog

* docs: reflow the changelog entry

* docs: drop the changelog entry
Replace the boolean asyncWait protocol with a five-state one (ready,
ready_signaled, queued, requeued, decided) built on one rule: an arm's
consuming side effect happens only after the arm has secured the
select's winner word. Fixes lalinsky#700, lalinsky#701 and the select-over-rendezvous
deadlock family without the global two-phase prepare/commit/rollback
rework of PR lalinsky#708.

- Sources claim the winner CAS before consuming (or make the consume
  revertible, like Signal's counter). The registration fast path can no
  longer clobber an earlier arm's claim (lalinsky#701): select() never stores
  the winner itself.
- The winner word gains a COMMITTING fence state used only by channel
  commits that pair a peer waiter (rendezvous, delivery to a parked
  receiver): claim the peer, then decide self, with the fence making the
  second step unlosable. This is what PR lalinsky#702's claim-before-consume
  could not express and had to panic on.
- Channel peers that observe the fence skip the waiter in place and
  bump a generation counter on the fenced select, which re-polls its
  arms before parking; asyncWait is now idempotent under re-poll. This
  un-deadlocks a select over two rendezvous channels racing select
  senders, which main hangs on deterministically.
- Non-channel producers keep their pop-claim-signal shape; a claim that
  hits the fence behaves like a lost one, and the woken select recovers
  the standing readiness by re-polling. The requeued/ready_signaled
  states keep the signal accounting exact.
- The cancellation path runs its own epilogue: cancel every registered
  arm, absorb in-flight signals, then deliver a claimed winner's result
  instead of dropping it (lalinsky#700). The cancellation request stays pending,
  matching Channel.receive.
- Direct (non-select) channel operations keep the fused single-lock
  check-and-consume shape; measured at parity with main, while the
  two-phase branch regressed 30-52% across the board.
- Group/CompletionQueue: a wake consumed for a dequeued registration was
  lost when the arm's claim then lost (.decided reported nothing and
  asyncCancelWait claimed no signal was owed), letting cleanup return
  while the wake was still in flight to the frame. Track it as
  ctx.pending_signal and keep reporting it via asyncCancelWait until the
  caller has accounted for it.
- waitOnFlagQueue had the mirror bug: the ready path unhooked the node
  before claiming, so a lost claim reported .decided with the node gone
  and no signal ever coming, while asyncCancelWait's failed remove made
  the caller expect one. Claim before touching the registration, and in
  the register-vs-completion race window hand the unhooked
  registration's owed signal to ourselves.
- Both winning canceled paths (select and selectAwaitables) now re-arm
  the consumed cancellation request via task.recancel() before
  delivering the claimed result, matching waitForIo and the documented
  Channel.receive semantics; a null task binding (thread-blocked wait)
  stays a no-op.
- admitSender no longer admits a parked sender after close: a sender
  still queued at close was fence-skipped and must re-poll into
  error.Closed rather than have its send succeed on a closed channel.
Same rule admitSender already follows: a sender still queued after close
was fence-skipped by close() and must re-poll into error.Closed. Letting
tryReceive complete its send made the fence window observable (an
identical sender that was not fenced fails with error.Closed) and left
tryReceive as the only receive path still pairing post-close.
Every source's asyncWait opens by unhooking any prior registration so a
select's re-poll never double-registers. A direct (non-select) waiter is
called exactly once and never re-polled, so it can never have a prior
registration; the remove() is guaranteed to find nothing and only costs a
list-membership check (a WaitQueue mutation lock for the flag-queue
sources) inside the hottest critical section in the system.

Gate it on a new Waiter.isDirect() so direct send/receive skips it. On the
native channel ping-pong and worker-pool benchmarks this recovers roughly
the single-threaded half of the regression the claim protocol introduced
over main (for example unbuffered ping-pong st +9% -> +4%, worker-pool
fan_in st +6% -> +4%); the multi-threaded cases are dominated by
cross-thread wake cost and are unchanged.
Blocking send/receive went through AsyncSendImpl/AsyncReceiveImpl.asyncWait,
the same entry point select() drives, so every direct send/receive paid for
the claim/commit-fence machinery (tryClaim on self, beginCommit/claimWaiter/
finishCommit for a peer pairing) even though a direct waiter has no winner
word, no sibling arms, and cannot lose a race to itself.

A direct op needs none of that: under the channel mutex, checking for a peer
or buffer space and consuming is already atomic, exactly as trySend/tryReceive
do it. Rewrite blocking send/receive as that fused check-and-consume, falling
back to parking a direct waiter (byte-identical node/ctx setup to before) only
when nothing is available. asyncWait is untouched but now select-only.

Recovers the regression the claim protocol introduced over main on the native
channel benchmarks: 5-way interleaved A/B (25 rounds, ReleaseFast) puts the
direct path at parity with main (avg -0.1%, median +0.9%) where the protocol
branch was +5.7%, including the multi-threaded ping-pong rows (+8.7%/+6.1% ->
+2.0%/+0.4%). All tests pass.
Now that blocking send/receive have their own fused fast path, the channel's
asyncWait is reached by a direct waiter only through zio.wait(ch.asyncReceive()),
an uncommon path not worth optimizing. Skipping the re-poll unhook there saved
nothing that matters and left asyncWait with a special case for a caller that
no longer exists on the hot path, so handle every waiter uniformly again: the
unconditional remove() is a harmless no-op for a direct waiter and the required
idempotency for a select re-poll.

Waiter.isDirect() stays; it still gates the unhook for the common direct waits
on Future/ResetEvent/Awaitable/Signal in common.waitOnFlagQueue and signal.zig.
Every send path tried a direct handoff to a queued receiver before touching
the buffer. That is correct while the usual invariant holds (a receiver is
only queued when the buffer is empty), but a busy (fenced) select receiver
breaks it: a send skips the receiver, buffers behind it, and leaves it queued,
so the next send finds it claimable and hands over an item that overtakes the
buffered one. The receiver then observes the newer item first, violating the
FIFO ordering Channel documents.

Hand off only while the buffer is empty, in trySend, the fused send fast path
and AsyncSendImpl.asyncWait alike; otherwise append, so the item queues behind
the older ones. The skipped receiver is already owed a re-poll (the claim that
found it busy bumped the select's generation), and that re-poll takes the
oldest buffered item. The rule is written down once as handoffOrder.

Costs nothing measurable: A/B over the native channel benchmarks puts the
fixed build within noise of the unfixed one on every case.
…fence

A notification whose winner CAS observed COMMITTING was discarded, and the
select recovered by re-polling its arms. That assumes the readiness the
notification reported is still standing, which holds for level sources but
not for every one: a drained Group can take new tasks and a set ResetEvent
can be reset (its set() pops every waiter, so the reset is legal), and both
then report themselves unready. The event was lost and the select waited on
something that had already happened, where a direct wait on the same source
would have returned. Timeout already carried a private `fired` latch for
exactly this reason.

Record the arm in a new pending_winner word instead, published before the
signal, and have select() promote it into the winner word after every point
where the fence may have come down and again after each wake. The second
site is what covers a bounce that lands just as the fence is released.
Promotion delivers the arm without re-polling its source, which is the whole
point: the notification is proof the arm completed.

Only the first bounce of a fence window is kept; later ones would have lost
the winner word anyway, and they consumed nothing, so nothing is stranded.
A promoted winner goes through the settle cancel loop like a loser, because
only its source can say whether its signal is still owed: an intervening
re-poll may already have re-registered the arm and counted that signal as
.requeued.

Channels keep the generation counter for .busy queued peers, which is
unaffected: those never signal, so there is no identity to preserve.
When a peer claims a parked direct sender or receiver just before the task is
canceled, the cancelable wait reports the cancellation while the item is
already committed. Both paths then deliver the result instead of the
cancellation, but the wait had already consumed the request, so it was lost
and the next cancelable operation never saw it.

Re-arm it via task.recancel() before returning the result, as waitForIo does
for an I/O that completes despite a cancel, and as both select paths already
do for a claimed winner. A null task binding means the wait blocked the
thread and consumed nothing, so it stays a no-op.

Inherited from main rather than introduced by the fused fast path, which
copied this epilogue unchanged.
Records dimenus's claim-before-consume work in this branch's ancestry. The
content is deliberately not taken: this branch implements the same rule
(an arm's consuming side effect happens only after it secures the winner
word) with a commit fence that lets a select-send pair a select-receive,
which is what lalinsky#702 could not express and had to panic on. Keeping the
commits here credits that work and lets lalinsky#702 close as merged rather than
abandoned.

Tree is unchanged by this merge.
select: claim-before-consume protocol with a commit fence confined to channels
…alinsky#711)

* Refresh the cached awake snapshot after the backend poll, not at scan top

## Problem

The awake `now` snapshot refreshed in `checkTimers`, at the top of
`poll` — BEFORE the backend poll. When the backend poll slept a long
time and woke on I/O, everything that ran before the next `poll` —
completion callbacks, and the task batch the runtime runs after a wake —
computed `.duration` timer deadlines in `armTimer` from a snapshot as
old as the sleep, up to `max_wait` (60 s).

A duration timer armed there was backdated by the full sleep: a 5 s
timeout armed right after a 10 s idle poll had a deadline already 5 s in
the past and fired on the next scan instead of 5 s later.

Observed in the wild by an HTTP/2 server on this runtime: h2spec case
http2/5.1/12 runs directly after two cases that each hold the server
idle for 10 s. The next accepted connection armed its 5 s preface
timeout through `zio.select`, the timer fired instantly, and the server
closed the fresh connection 0 ms after accept. An arm-site detector
measured `late_ms=5002 dur_ms=5000` exactly once per full h2spec run,
at exactly that suite position, in 3 of 3 runs.

Yield-based remedies do not close this: a yield moves the task to the
back of the run queue the executor is currently draining, and the
executor does not poll between batch items. Measured on main with the
detector, three full h2spec runs per variant: `maybeYield()` at select
entry left 1 of 3 runs backdated, direct `yield()` 3 of 3, a forced
`.reschedule` yield 1 of 3.

## Change

- The snapshot refresh MOVES from the top of `checkTimers` to `poll`,
  right after the backend poll, unconditional. That puts the fresh value
  where it is consumed: the completion callbacks and the caller's task
  batch that run before the next poll. A CPU-bound caller polling with
  `.zero` refreshes each pass too. Cost is unchanged: the same one clock
  read per poll that `checkTimers` paid, relocated. `armTimer` keeps the
  cached read, preserving the per-scan "same tick = same now" base for
  timers armed within one tick.
- Regression test: a pipe-read completion wakes a 1.2 s backend sleep,
  then a 500 ms duration timer is armed after `poll` returns, where the
  runtime runs task code. Before this change the timer fires in ~0 ms;
  the test asserts it fires no earlier than 450 ms. The wake must be an
  I/O completion delivered by the sleeping poll itself: an async notify
  wakes one poll and completes on the next, so that shape cannot
  reproduce the bug.

## Alternatives considered

- Fresh clock read per `.duration` arm in `armTimer`: fixes the arm
  site unconditionally but adds a clock read per armed timer and cuts
  against the per-scan cache design.
- Refresh gated on "the backend poll could have waited": rejected in
  review — the gate saves nothing measurable and leaves the
  zero-timeout corridor stale.

## Verification

- `zig build test`: 653 of 653 pass.
- The regression test fails on the previous code (timer fires early)
  and passes with this change — checked both ways.
- The HTTP/2 server's conformance case failed 8 of 11 full-suite runs
  before and passes 4 of 4 on this fix (revalidated on this shape).


* ev: refresh the awake snapshot on both sides of the backend poll

checkTimers no longer takes the tick; poll owns it and opens one before
the pre-poll scan and one after the backend poll returns.

The post-poll refresh is the fix: the backend poll is the only place the
loop sleeps, so everything running until the next poll (completion
callbacks, and the caller's task batch) armed .duration deadlines from a
snapshot stale by the whole sleep, up to max_wait. A timeout armed there
was backdated and fired at once.

The pre-poll refresh keeps the scan that decides the poll timeout on a
fresh clock, so a timer expiring during a task batch is not delayed by
the length of that batch.

Executor tick accounting reads the cached snapshot for its batch window
now that it is fresh: every path into that read ends in a loop.poll,
which refreshes on return. The other two clock reads stay fresh on
purpose, since the cache does not advance inside a batch.

---------

Co-authored-by: Ryan Saunderson <[email protected]>
Co-authored-by: Lukas Lalinsky <[email protected]>
## Problem

Under `select`, a CompletionQueue arm can win with the queue EMPTY and
OPEN, with exactly one task driving the queue. `ownerCallback` publishes
to `completed` and wakes in two non-atomic halves; in the gap the
driver's other arm wins the select, the CQ arm deregisters cleanly (no
in-flight signal to count — correctly, nothing was dispatched yet), the
driver pops the published item with `next()`, and the next select
registers a fresh waiter on the same futex word. The stale wake then
dequeues the new waiter and claims the new select's CQ arm with nothing
to take: `getResult` hits `std.debug.assert(drained)`.

## Change

- `examples/cq_spurious_select_repro.zig`: ~200 lines, no server code,
  one driver task per queue by construction (select arm, `next()` pops
  between selects, documented close/cancelAll(.keep)/drain teardown).
  Exit 0 = clean, exit 2 = spurious win detected on a tolerant build,
  abort = the getResult assert fired.
- `build.zig`: register the example
  (`zig build examples -Dexample=cq-spurious-select-repro`).

## Verification

At this commit's parent the repro aborts at the `getResult` assert
within about a second on macOS/kqueue and Linux/io_uring, Debug and
ReleaseSafe, with 8 workers; 1-2 workers run clean (the window needs
runtime-wide scheduler pressure; each queue still has exactly one
driver).

Co-Authored-By: Claude Fable 5 <[email protected]>
…fore signaling

## Problem

The future protocol parked select registrations on the `signal` futex
word, and `ownerCallback` published in two non-atomic halves: push to
`completed` under the mutex, then `fetchAdd` + `Futex.wake` after
unlocking. A wake dispatched in that gap is not tied to any
registration, so it can outlive the select that was parked when it was
dispatched. The interleaving (one driver task throughout):

1. `ownerCallback` pushes to `completed`, unlocks, and is preempted
   before the wake.
2. Another arm wins the select; the CQ arm deregisters cleanly (the
   wake has not dequeued anything, so there is no in-flight signal to
   count -- correctly, at that moment).
3. The driver pops the published item with `next()` and resubmits.
4. The next select registers a fresh waiter on the same futex word.
5. The old wake fires, dequeues the new waiter, and claims the new
   select's CQ arm with the queue empty and open. `getResult` hits
   `std.debug.assert(drained)`: a crash in ReleaseSafe, an undefined
   `error.Closed` return in ReleaseFast.

`examples/cq_spurious_select_repro.zig` (previous commit) reproduces
this within a second on macOS/kqueue and Linux/io_uring.

## Change

The producer now claims a specific completion to a specific waiter
before signaling, so a wake always carries an item nobody else can
take:

- The queue holds the future-protocol registration itself, in a `reg`
  slot guarded by the queue mutex. `WaitContext` loses its
  `FutexWaiter` and `pending_signal`; it gains the deposit fields
  `claimed`/`drained`.
- `asyncWait` checks readiness and registers in one critical section,
  so the check-then-park window is gone and no post-registration
  double-check is needed. A winning claim (its own, or a re-polled
  producer deposit) always carries its result in the context.
- `ownerCallback` and the draining `close` claim the registered waiter
  under the mutex (`claimToRegistered`): on a won claim they pop the
  completion (or latch the drained state) into the registered context,
  clear the slot, and send exactly one signal after unlocking. On
  `.busy` the select's own generation bump re-polls the owner; on
  `.lost` the losing select's settle phase cleans up. Either way
  nothing is consumed without a won claim.
- `asyncCancelWait` deregisters under the same mutex, so removal and
  claim are mutually exclusive: removed means no signal was or will be
  sent; claimed means the deposit is in hand and one signal is
  accounted. A canceled generic `wait` restores an unconsumed deposit
  to the queue; a select delivers its claimed winner even when
  canceled (lalinsky#700).
- `getResult` consumes the deposit and keeps the truth-telling assert:
  a won arm with no deposit is a protocol violation again, not a
  survivable race.
- The blocking paths (`wait`, `timedWait`, `cancel`, `cancelAll`) stay
  on the futex word; they re-check the queues on every wake and never
  interpret a wake as a claim.
- The single-driver rule is now enforced: the registration slot makes
  a second driver visible, and the driver-only entry points panic on
  it instead of corrupting the claim accounting (`getResult` asserting
  far from the cause). Two tasks selecting over one queue panics at
  the second registration.
- Teardown quiescence: `ownerCallback`'s `fetchAdd` moved inside the
  critical section, so once a teardown drain observes `pending` empty
  the callback never touches the queue's memory again (`Futex.wake`
  takes only the address and does not dereference it). Previously the
  documented `defer cq.cancelAll(.discard)` stack teardown could free
  the queue under a live callback's `fetchAdd`.

## Benefits

- The spurious select win is closed by construction: a signal without
  a deposit cannot exist, so no wake can cross select generations.
- Misuse (two drivers) fails loudly at the point of misuse, in every
  optimize mode, instead of corrupting a later select.
- One fewer futex bucket round-trip per delivered completion on the
  select path (the claim replaces prepareWait/wake/cancelWait).

## Alternatives considered

- Tolerating the empty win in `getResult` (`error.Closed` + driver
  re-poll): mutes an assertion that catches real misuse, and every
  driver has to know the re-poll rule (rejected on review of lalinsky#712).
- Counting the wake into `signal` under the same mutex acquisition as
  the `completed` push, keeping futex parking: closes the published
  gap but keeps consuming wakes that carry no item, so the accounting
  stays load-bearing across generations; producer-claims removes the
  class.
- A global lock around publish+wake+claim: closes the race and
  serializes every completion against the driver; rejected for the
  select hot path.

## Verification

- `zig build test`: 653/653 pass, no existing test changed.
- `cq-spurious-select-repro 8 20000 64`: 10 consecutive clean runs in
  Debug and ReleaseSafe on macOS/kqueue (at the parent commit the same
  invocation aborts at the `getResult` assert within a second, 3/3).

Co-Authored-By: Claude Fable 5 <[email protected]>
## Problem

`isEmpty`/`hasPending`/`hasCompleted` answer three partial questions,
but the state a driver actually stops on -- closed, nothing in flight,
nothing left to take -- had no predicate. `isClosed` would be the wrong
stop predicate: a `close` raced in with operations still in flight
reads closed while `ownerCallback` will still deliver their
completions, and a driver stopping there leaks them.

## Change

- `isDrained()`: one mutex-protected check of
  `closed and pending empty and completed empty`, the terminal state
  that `wait` and a select's queue arm report as `error.Closed`.
- A test pinning its three cases: open-and-empty is not drained,
  closed-with-inflight is not drained, closed-and-taken is drained.

Split out of the lalinsky#712 discussion at the maintainer's suggestion: under
the claims protocol the queue arm's `error.Closed` already implies the
terminal state, but drivers that consume through `next()` or observe a
queue another task closes still need the predicate.

Co-Authored-By: Claude Fable 5 <[email protected]>
…er death example

## Problem

The claims protocol moved the race-prone edges: claim vs close, claim
vs cancelAll's drain, claim vs a canceled select, and callback
quiescence at teardown. None of them had a test, and the misuse the
maintainer's lalinsky#712 walk demonstrated (two tasks selecting over one
queue) had no witness at all.

## Change

New tests in src/completion_queue.zig:

- close claims the drained state to a parked select: the deterministic
  producer-close path (nothing pending, close is what drains).
- a close racing the claim delivers the completion, then error.Closed:
  50 rounds of a thread-safe close landing at varying points against an
  in-flight completion; asserts exactly-once delivery and terminal
  order.
- callbacks racing cancelAll(.keep) conserve every completion: 64
  operations spread so the drain races live callbacks; every one comes
  out exactly once.
- a claim landing on a canceled select is delivered, never dropped: 200
  rounds of cancel vs notify; the select reports error.Canceled with
  the completion still takeable, or delivers it (lalinsky#700), never both and
  never neither.
- teardown drain leaves the queue memory quiescent: poisons the queue
  struct the moment cancelAll(.discard) returns and watches it while
  canceled completions land as a burst across four loops (parallel
  submitter tasks put each batch on its own loop; with one loop the
  wake that releases the drain is always the last callback's own, and
  the interleaving cannot exist). Instrument validation: with the
  pre-claims gap (signal-word write after unlock) widened to 50us the
  watch fails every run, the flip being the write's +1 on a poison
  byte; a write-side probe confirms the drain does return inside
  another loop's callback gap in this shape. At the real gap's width
  (two instructions) a black-box watch needs a preemption exactly
  there, so a pass is one clean sample and a failure is definitive;
  the enforced protection is the code shape (the write sits inside the
  critical section the drain synchronizes on).

New example (a death test driven externally, since the test runner
cannot expect a panic):

- examples/cq_two_driver_misuse.zig: two tasks selecting over one
  queue in the maintainer's lalinsky#712 shape. Expected outcome: abort with
  "CompletionQueue: selected from two tasks; one task must drive the
  queue". Exit 0 means the misuse was silently accepted.

## Verification

- zig build test: 659/659 pass (653 upstream + isDrained + these five).
- The misuse example aborts with the panic above in Debug and
  ReleaseFast (rc=134 both).

Co-Authored-By: Claude Fable 5 <[email protected]>
Three review findings, all real, plus a deadlock the first version of
one fix introduced:

- cq_spurious_select_repro: the flooder's feed descriptor was an atomic
  value, which does not protect the descriptor's lifetime. The flooder
  could load the old descriptor, the driver could close it, and the OS
  could reuse the number before the write landed. The descriptor now
  shares one mutex with its teardown: the flooder's load-and-write is
  one mutex hold, and the driver clears the descriptor under the mutex
  BEFORE closing it after unlock. A write therefore finishes before the
  clear can start, and any later hold sees -1, so no write can reach a
  closed descriptor.

  The close must stay OUTSIDE the mutex. A first version closed under
  the hold and deadlocked about one run in ten on macOS: the close sat
  in __close_nocancel for 50+ minutes (uninterruptible), the worker's
  flooder was parked on the mutex, and that executor slept in kevent
  with an infinite cap. The userspace legs of the cycle are on the
  captured stacks (mutex -> close -> sleeping kevent -> parked flooder
  -> mutex); the kernel leg (a socket close waiting on a kqueue that
  still holds the socket's knote) is inferred, not proven. Moving the
  close after the unlock breaks the cycle at the mutex edge either way.

- cq_two_driver_misuse: the undetected-misuse path exited 0, so only a
  harness that inverts the exit code read it as a failure. It exits 3
  now, and the header documents the contract: the expected outcome is
  the abort, 3 means the check failed, anything else means the example
  itself failed to run.

- build.zig: the reproducer uses socketpair and fcntl, which do not
  exist for the Windows target, so `zig build examples` broke there. A
  `posix_only` flag now skips it on Windows, and selecting it directly
  fails with a clear message. Verified both ways for x86_64-windows:
  the full examples build succeeds, and direct selection reports the
  reason.

Verification: the edited reproducer still aborts at the getResult
assert on main (3/3 on macOS/kqueue and Linux/io_uring), and stays
clean on this branch: 30 consecutive runs in macOS Debug (the deadlock
showed at roughly 1 in 10 there), 10 in macOS ReleaseSafe, 10 each in
Linux Debug and ReleaseSafe, every leg under a hard timeout so a hang
cannot pass silently. zig build test 659/659; ./check.sh --full clean.

Co-Authored-By: Claude Fable 5 <[email protected]>
## Problem

Two layered problems around the reviewed descriptor-lifetime fix:

1. The previous commit (0c9271c) says it moved the descriptor close out
   of the feed mutex, but its tree does not contain that change: the
   edit script asserted the OLD text was present and then wrote the
   buffer back WITHOUT applying the replacement, so it reported success
   while changing nothing. The review bot caught the mismatch. Every
   verification run before this commit therefore exercised the
   close-under-mutex code; the "did test this change" sentence in
   0c9271c's message is wrong.
2. Applied for real, the mutex approach fails on its own terms. Runs
   slow from ~10 s to 100-300 s (the flooder parks on the mutex instead
   of spinning, and the fixture's cadence collapses), and the
   uninterruptible close wedge SURVIVES the close being outside the
   hold: a run that outlived its timeout took SIGTERM and sat in exit
   for 10+ minutes with a thread in __close_nocancel. So the earlier
   mutex-cycle explanation was incomplete, and both mutex shapes (close
   under the hold, close after it) are wrong for this fixture.

## Change

Remove the shared descriptor instead of synchronizing it. The flooder
only floods the channel arm. The driver primes and feeds its own
socket between selects and closes it in plain defers. The descriptor
has exactly one owner for its whole life, so the reviewed reuse race
cannot be expressed, and there is no mutex to slow or wedge anything.

## Verification

- The instrument still fires: on main the reworked reproducer aborts
  at the getResult assert in 0.4-4.4 s, 3/3 on macOS/kqueue and 3/3 on
  Linux/io_uring.
- On this branch: 15 consecutive clean runs in macOS Debug (~7 s each,
  faster than the original fixture), 5 in macOS ReleaseSafe, 10 each in
  Linux Debug and ReleaseSafe, every run under a hard timeout.
- zig fmt clean; suite unchanged (the file is an example).
- Acceptance for THIS commit was read back from HEAD, not from the
  editor's output.

Co-Authored-By: Claude Fable 5 <[email protected]>
rsaunderson-i3v and others added 20 commits August 26, 2026 06:39
Requested in review: the tip does not ship the two examples. They stay
in this branch's earlier commits for reference (the reproducer's final
shape is in the previous commit; the getResult-assert baseline runs are
recorded against the first commit of the branch). build.zig returns to
its upstream shape; the posix_only machinery existed only for the
reproducer.

Co-Authored-By: Claude Fable 5 <[email protected]>
…leted`

## Problem

`checkSingleDriverLocked()` was a convention: every driver-side consumer
of `completed` had to remember to call it after taking the mutex. It was
omitted three separate times (the CodeRabbit review of PR 713 caught the
class; finding F11 in the starh2 review-recall oracle), and two
omissions were still live at this branch tip: the `timedWait` timeout
re-check popped without it, and `drainPending`'s discard pass popped
without it. A convention that has been omitted three times is not a
convention; it is a defect generator. Measured context: 48 blinded
agent-review runs across four vendors reproduced many findings on these
commits, and none of them caught this class - only a structural rule
does.

## Changes

- One dispatcher, `consumeAsDriver(op)`, now owns the whole driver-side
  critical section: lock, `checkSingleDriverLocked()`, the operation,
  unlock. Ops: `take_head` (pop plus the drained computation),
  `take_specific` (unlink one node, or classify it as pending/absent),
  `drain` (read `pending` emptiness first, then for `.discard` drop
  every completed result in the same critical section).
- `wait`, `timedWait` (both its ordinary check and the timeout
  re-check), `next`, `cancel` (both its fast path and its wait loop) and
  `drainPending` route through the dispatcher. The timeout branch and
  the drain pass thereby gain the single-driver check they lacked.
- `cancel`'s wait loop now distinguishes `pending` from `absent` and
  asserts `absent` unreachable after the initial classification, which
  is sound because `ownerCallback` moves a node from `pending` to
  `completed` inside one critical section.
- The select side stays outside the dispatcher on purpose: `asyncWait`
  and `claimToRegistered` consume while managing `reg` themselves - the
  parked select IS the driver, so the driver check would be wrong there.
- A source-invariant test embeds this file and holds the consumer list
  closed: `completed.pop()` in exactly {consumeAsDriver, asyncWait,
  claimToRegistered} (4 sites), `unlink(&completed, ...)` only in
  consumeAsDriver (1 site), no `completed.remove`, and
  `checkSingleDriverLocked()` present in exactly {consumeAsDriver,
  requestCancelAll} (2 sites). Counts are exact in both directions, so
  a drifted needle fails loudly instead of going blind. The needles are
  split string literals so the scan cannot match its own source.

## Verification

- `zig build test`: 660 of 660 tests passed.
- Mutation-proven, both directions: a bare `completed.pop()` added to
  `isEmpty` fails the invariant test with `ForbiddenConsumer` naming the
  function; deleting `checkSingleDriverLocked()` from the dispatcher
  fails the exact-count pin (expected 2, found 1).

## Alternatives considered and rejected

- A cross-file proof-token type (`DriverProof` constructible only beside
  the lock+check): rejected on a cross-vendor design review (GPT-5.6
  Sol; brief and answer in starh2 captures/cq-token-design/). Zig
  struct fields are always public, so a separate file does not make the
  storage opaque - the claimed compiler enforcement did not hold - and
  the token added two new conventions (stale-proof reuse after unlock,
  an unforced `end()`), more than the one it removed.
- Asserting `mutex.held` inside a `takeCompletedLocked` helper: Zig's
  std mutex exposes no held-by-me query, and a helper that trusts its
  caller to hold the lock re-creates the omission class one level up.
- A general Zig analyzer for the pattern: the measured evidence from the
  sibling dotnet effort is that synthesized semantic detectors collapse
  out of sample; a repo-local exact-count source test is rung 3 with
  none of that risk.

## Statistics

One file, +147/-62. Two omission sites closed, one new test, two
mutations proven fatal.

Co-Authored-By: Claude Fable 5 <[email protected]>
### Problem

starh2 t-1166 needs a deterministic simulation of the CQ / select / timer
core. The pin-gate is probabilistic. All five historical bugs lived in
that core, not in file I/O or io_uring.

### Changes

- Add `zio_options.sim` (default false) and `sim-mutant`.
- Add `src/sim.zig`: logical clock, seed RNG, event-trace hash, deadlock.
- Route `os.time.now` to the sim clock when `sim` is on.
- Skip `backend.poll` in `Loop.poll`. Advance the sim clock by the
  timeout the real poll would have slept.
- Panic on kernel futex wait/wake in sim mode (D4).
- Use no-op mutex and condition in sim (one thread).
- Pick the next ready task with the seed RNG when two or more are ready.
- Emit `task_switch`, `wake`, `timer_fire`, and `cq_pop` into a Wyhash.
  The hash does not include the RNG stream.
- Panic in `armTimer` if a duration deadline is behind true now + duration.
- Mutant `arm_timer_stale` computes duration deadlines from epoch 0.
- Mutant `omit_timeout_recheck` skips the `timedWait` timeout re-check.

### Benefits

A later grader can re-run from printed seeds. Production builds keep
`sim=false` and do not pay for this path.

### Alternatives considered

- A new `sim` `BackendType`: more code for the same intercept. Rejected
  for M1. M2 can still add it for I/O completions.
- Copy TigerBeetle VOPR into the tree: rejected. Different I/O model.
- Pattern-match known bugs in the harness: forbidden by t-1166.

### Verification

`tools/zio-dst` in starh2: D1 20 seeds x 2, D2 251 distinct traces in
1000 seeds, D4 both arms fire, D5 SCOPE names unsimulated sources.
`--arm-mutant` with `arm_timer_stale` fires on SEED=1 and replays (D3).
`omit_timeout_recheck` does not fire on one thread: both timer callbacks
run in one `processCompletions` before the driver resumes, and
`Waiter.timedWaitClock` prefers a signal over a timeout. That is a
finding for M3, not a silent pass.

### Statistics

- 9 files changed, about 220 insertions
## Problem

`AutoCancel` always armed on `.awake`. Every layer beneath it already
understood clocks: `ev.Timer` carries a `clock` field with an `initClock`
constructor, `Loop` keeps one timer heap per wall clock and resolves
durations against the matching `now` in `armTimer`, and `Timeout.fromStd`
is deliberately clockless because "the clock itself travels separately on
the `ev.Timer`". `Clock.fromStdTimeout` exists to carry that other half.

`AutoCancel.set` never assigned `self.timer.clock`, so it kept the
`.awake` default from `.init`, and those two `fromStd` helpers had no
caller able to use both halves.

A `std.Io`-facing wrapper therefore cannot pass an absolute deadline
through. dusty exposes `Request.setTimeout(std.Io.Timeout)`, so a handler
can hand it a `.real` deadline; on the zio path it has to flatten that
with `toDurationFromNow` into a relative monotonic duration measured at
arm time, and a settable clock stops being settable the moment it is
armed.

## Change

`setClock(timeout, clock)` assigns `timer.clock` alongside the `userdata`
and `callback` that `set` already writes. `set(timeout)` becomes
`setClock(timeout, .awake)`, so existing behavior is unchanged.

The clock is written after the `clear()` that opens the function, and
only because of it: `disarmTimer` removes from `timers[clockIndex(
timer.clock)]`, so moving the clock under an armed timer would take it
out of the wrong heap. The `clear` is already there for the
cross-executor re-arm and the in-flight-callback race; this relies on it.

Also exports `zio.Clock`, which was missing next to `Duration`,
`Timestamp` and `Timeout` and was reachable only as `zio.time.Clock`.

## Tests

The absolute-deadline test is the one that needs the feature: a `.real`
timestamp is ~1.7e18 ns against an awake epoch of ~1e13 ns, so on the
monotonic heap it reads as far-future and never fires. Swapping its
`.real` for `.awake` fails the test.

The clock-switch test covers the ordering constraint above by re-arming a
still-live real-clock timer onto `.awake`.

Closes lalinsky#716
### Problem

upstream `5de2c44` (`AutoCancel.setClock`, lalinsky#717) puts a timer on the
`.real` heap. M1 treated every wall clock as one logical counter starting
at 0. A `.real` deadline then looks like a monotonic deadline, so a
missing `setClock` (clock stays `.awake`) still fires. That hides the
lalinsky#717 defect under DST.

### Change

- `now(.real)` is logical ns plus 1.7e18 (the unix-scale offset lalinsky#717 names).
- `.awake` / `.boot` stay on the logical counter (`boot==awake` is still
  unsimulated).
- The armTimer backdate mutant uses that clock's epoch, not raw 0.

### Alternatives

Keep one epoch and only test duration-on-`.real`: a duration uses
`nowFor` of the timer's clock, so it fires even when `clock` is wrong.
Rejected. The absolute-deadline case is the one that needs `setClock`.
### Problem

M1 never delivered net completions. `Loop.pollSim` skipped `backend.poll`
but `add` still had no path for recv/send, so a grader cannot exercise CQ
over I/O. `kqueue` still opened a real fd at `Loop.init`.

### Change

- In-memory bidirectional pipe (`sim.pipePair`). No kernel fd.
- `Loop.add` routes `net_recv` / `net_send` / `net_close` to the pipe.
- `pollSim` harvests due I/O (shuffled when two or more) then
  `markCompleted`. Same ownerCallback path as a timer.
- Skip `kqueue` create in sim. `backend.poll` panics (`sim: real
  backend.poll`).
- D5: `net_pipe` is simulated. `file_io` and `connect_accept` stay
  unsimulated.

### Alternatives

- Complete I/O inline in `submit`: no harvest, no race with timers.
  Rejected.
- Real `socketpair` plus sim scheduling: still a kernel syscall. Rejected.
### Problem

M1/M2 ran one executor. Remote submit was the same OS thread and the
same loop. The F11 timeout re-check never ran with a completion in
`completed`: both timer callbacks finished in one `processCompletions`
before the driver resumed, and `Waiter.timedWaitClock` prefers a signal.

### Change

- Sim allows `executors=2` and inits the second executor on this thread.
  No OS worker thread.
- `Executor.run` multiplexes: pick a ready executor, or poll every loop
  at `.zero`, or advance the sim clock to the earliest timer.
- `ownerCallback` yields to the other logical executor after the push
  and before `Futex.wake`. That is the two-thread window, made sayable
  on one thread.
- `Loop.bindThread` / `peekNextTimeout` for the mux.

### Alternatives

- Real worker threads: wall clock and kernel futex. Rejected for DST.
- Rebase onto lalinsky/zio main: drops `consumeAsDriver`. Rejected.
### Problem

`pollSim` was a second poll loop. It called `updateNow` after `advanceNs`
on its own. A production regression in the post-wait snapshot refresh
(lalinsky#711) could not fire in sim. The mux idle path also advanced the clock
and then called `poll(.zero)`, so the wait never ran inside `poll`.

### Change

- `Loop.poll` is one function for production and sim. `waitForEvents`
  is `backend.poll` or sim `advanceNs`. The post-wait `updateNow` is
  one statement.
- Mux idle calls `poll(min_t)` on the loop that owns the next timer.
  Other loops then `poll(.zero)`.

### Benefits

A missing post-wait `updateNow` in production is a missing refresh in
sim. The lalinsky#711 class can fire under DST.

### Alternatives

- Keep `pollSim` and share a helper for `updateNow` only. Rejected.
  A second loop can still skip the helper.
- Advance in the mux and `poll(.zero)`. Rejected. That wait is not
  the production wait.

### Verification

- `zig build test`: 666 of 666 pass. The lalinsky#711 timer test is in that
  suite.
- DST harness D1 PASS, D2 DISTINCT_HASHES=250 SEEDS=1000, D4 PASS,
  D5 PASS. Both constructed mutants fire at SEED=1.
### Problem

DST still had two silent windows:

- `waitForEvents` either did not sleep or slept the full timeout and
  returned `timed_out=true`. I/O that lands during a sleep (kevent
  returns `timed_out=false`) could not happen. Immediate due I/O is a
  zero-timeout poll, not that window.
- The select registration sweep ran as one atomic step. A producer
  could not claim an arm between registrations.

A task that resumed on the other loop after a clock advance also armed
duration timers from a stale snapshot (`armTimer backdated`).

### Change

- Each sim I/O completion has a future `due_at` (1 ms or 5 ms).
  `waitForEvents` advances only to that time and returns
  `timed_out=false`. Mux idle treats the next due I/O as a wake time.
- After each queued arm in the select sweep, `simCoopYield` (same
  idea as `ownerCallback`).
- `simRunOneTask` calls `updateNow` before it steps, so a duration
  timer armed after a clock advance on the other loop is not
  backdated.

### Alternatives

- Zero I/O delay, and only harvest already-due completions. Rejected.
  That is the zero-timeout path the grader named as not the window.
- Yield only after the whole sweep. Rejected. A mid-sweep claim
  cannot interleave.

### Verification

- `zig build test`: 666 of 666 pass.
- DST D1 PASS, D2 DISTINCT_HASHES=250 SEEDS=1000, D4 PASS, D5 PASS.
  Both constructed mutants fire at SEED=1.
### Problem

A claimed CQ deposit could leave the select frame without getResult
and without a restore. getResult already panics on a win with no
deposit. The other direction was silent: a loser with a deposit, or
a canceled return that still held ctx.claimed.

Several `updateNow` sites covered every fixture consumer of the
snapshot. Reverting the post-wait refresh (lalinsky#711) was inert.

### Change

- `asyncCancelWait`: a select waiter whose ctx holds a deposit while
  the winner word does not hold this arm panics.
- `select` return: a frame exit that still holds `ctx.claimed` panics.
  getResult consumes the winner first.
- `simRunOneTask` refreshes only on the coop-yield path (the other
  loop advanced the sim clock inside poll). After poll returns, the
  post-wait `updateNow` is the only refresh the next task batch sees.

### Alternatives

- Restore a losing select deposit into `completed`. Rejected. That
  hides the protocol break.
- Refresh on every `simRunOneTask`. Rejected. The post-poll task
  batch would stay fresh after a revert of the lalinsky#711 site.

### Verification

- `zig build test`: 666 of 666 pass (includes the lalinsky#711 timer test).
- DST D1 PASS, D2 DISTINCT_HASHES=250 SEEDS=1000, D4 PASS, D5 PASS.
  Both constructed mutants fire at SEED=1.
### Problem

CQ deposit conservation checked `ctx.claimed` only. A channel deposit
lives in `result_set` / `succeeded`. A losing or canceled arm could
drop it silently.

The mux ran every ready task before any `poll`. A canceled select
always deregistered before poll could fire a claim into it.

### Change

- Channel `asyncCancelWait`: a select waiter with `result_set` or
  `succeeded` whose winner word does not hold this arm panics.
- `getResult` consumes those flags so a delivered winner does not
  trip the frame-exit check. `select` walks `impl_ctx` for the same
  leftover-deposit panic as CQ.
- Mux: half the ready steps harvest `poll(.zero)` first, so a due
  timer or I/O can claim a parked select before the ready canceler
  runs.

### Alternatives

- Restore a losing channel deposit into the buffer. Rejected. That
  hides the protocol break.
- Always sleep (`poll(min_t)`) while ready tasks wait. Rejected.
  That would serialize `same_tick_race` through the timer heap.

### Verification

- `zig build test`: 666 of 666 pass.
- DST D1 PASS, D2 DISTINCT_HASHES=252 SEEDS=1000, D4 PASS, D5 PASS.
  Both constructed mutants fire at SEED=1.
### Problem

`Waiter.wait` checks the signal before the cancellable yield. A
canceled select with a claimed winner needs the producer to commit
BETWEEN the Canceled raise and settle's deregistration. That region
had no yield, so one cooperative thread could never run inside it.

### Change

- After `canceled` is set, before the cancel loop, `simCoopYield`.
  The other logical executor can claim a parked arm (channel send
  racing `JoinHandle.cancel`) before deregistration.
- The same yield is in `selectAwaitables`.

### Alternatives

- Yield inside `asyncCancelWait` before the dequeue. That also
  opens the window, but only for the source that yields. The settle
  site covers every arm.

### Verification

- `zig build test`: 666 of 666 pass.
- DST D1 PASS, D2 DISTINCT_HASHES=252 SEEDS=1000, D4 PASS, D5 PASS.
### Problem

CQ claims are delivered only in `ownerCallback`, which runs inside
`poll`. The cancel-settle `simCoopYield` ran one ready task and did
not harvest. A due zero-duration timer could not claim a parked
select between Canceled and deregistration. Mux harvests between
ready steps, not inside a task's settle.

### Change

When `simCoopYield` is called from a task (`current_task != null`),
it `poll(.zero)` on every loop first. That is the settle path and
the select-sweep path. When called from poll (`current_task` is
null), it still only runs a ready task on the other executor, so it
does not re-enter poll.

### Alternatives

- Nested `poll` on the loop already inside `ownerCallback`. Rejected.
  Re-entrant poll on the same loop is unsafe.
- Harvest only at the settle call site. That also closes the hole.
  Doing it in `simCoopYield` covers every task-side coop point.

### Verification

- `zig build test`: 666 of 666 pass.
- DST D1 PASS, D2 DISTINCT_HASHES=252 SEEDS=1000, D4 PASS, D5 PASS.
  D1 hashes for `same_tick_race` are unchanged (that path yields
  from poll, not from a task).
### Problem

Task-side `poll(.zero)` was always-on. Every sweep and settle yield
delivered due claims at once, and wait prefers a landed signal over
a pending cancel. `canceled=true` never ran. A park-catch probe in
`select_task_cancel` went silent.

Settle yield was [poll, then one task]. A producer that submitted in
the task phase got no poll afterwards, so its claim still could not
land in that settle.

### Change

- First harvest is `pickIndex(2)`, same idea as the mux harvest.
  Explored space has early-claim and late-claim.
- After the coop task runs, a second seeded harvest. A submit in the
  task phase can still claim in this settle.
- From poll (`current_task` is null) there is still no harvest.

### Verification

- `zig build test`: 666 of 666 pass.
- DST D1 PASS (same_tick hashes unchanged), D2 DISTINCT_HASHES=252
  SEEDS=1000, D4 PASS, D5 PASS.
- `select_task_cancel` PARK_CATCH fired on 3 of 30 seeds (2, 9, 29).
### Problem

An independent merge review found sim still entered real backends on
Linux, delegated wall timers to a backend it never polls, ignored
`dont_wait`, overflowed the armTimer check, omitted drained from the
timeout recheck, inferred deposits from field names, hashed a thin
state digest, checked the wrong pipe end for backpressure, and let
`spawnBlocking` escape onto real threads.

### Change

- Every backend `init`/`poll`/`deinit` skips or panics in sim. Linux
  does not open io_uring or epoll. `native_wall_timers` is false in
  sim, so real/boot deadlines join the logical poll timeout.
- `RecvFlags.dont_wait` matches main. Empty sim recv returns
  WouldBlock instead of parking.
- armTimer backdate check uses saturating add. Timeout recheck panics
  on drained as well as queued. WaitContext implements `holdsDeposit`;
  select frame-exit uses that, not field names.
- stateDigest includes the trace hash and sim I/O. Mutant panics print
  TRACE_HASH.
- Recv wakes the peer's parked send. Close wakes the peer's send.
- `spawnBlocking` panics in sim. SCOPE no longer claims io_uring is
  never entered.

### Verification

- `zig build test`: 666 of 666 pass.
- DST D1 PASS, D2 DISTINCT_HASHES=252 SEEDS=1000, D4 PASS, D5 PASS.
  Mutant D3 prints and matches TRACE_HASH. setclock_real clock_ns=30ms
  for three 10 ms AutoCancels.
### Problem

A parked send that a recv wakes still completed as BrokenPipe. That
error is only valid for a closed peer. A 500 ms oversleep of the
wrong timer still passed the setclock oracle. Conservation panics
used `@panic` and skipped TRACE_HASH. stateDigest hashed buffer
lengths and due times, so equal-length payloads collided. RecvFlags
docs did not match main. Broadcast recv had no holdsDeposit.

### Change

- harvestSimIo retries a capacity-woken send through harvestSend.
  That copies into the peer buffer and does not re-queue the
  completion. BrokenPipe remains only for eof.
- stateDigest hashes buffered bytes and each due kind.
- Conservation panics call sim.protocolPanic so TRACE_HASH prints.
  Broadcast recv implements holdsDeposit and consumes the deposit
  in getResult. select rejects a WaitContext that stores a deposit
  without holdsDeposit.
- RecvFlags.dont_wait docs and flag order match origin/main tryRead.
- Darwin sim Loop.init does not open a kqueue fd and does not
  allocate an event buffer.

### Verification

- `zig build test`: 666 of 666 pass.
- DST D1-D5 and mutant arms run after the origin/main merge.
Bring d0c4d79 (non-parking tryRead) onto sim/dst-m1 so the branch
merges cleanly into dimenus/zio main. RecvFlags.dont_wait docs
already match. consumeAsDriver stays on this branch.
### Problem

Deposit checking still inferred ownership from field names. A CQ
WaitContext that stored its claim in `claimed` and `drained` could
drop `holdsDeposit()` and still compile. `getResult` did not consume
`drained`, so a drained claim slipped past frame-exit. Several
protocol failures used `@panic` or `std.debug.assert` and printed no
TRACE_HASH. The due-list digest hashed deadline and kind, so two
same-kind ops due at the same tick collided.

### Change

- Every non-void WaitContext implements `holdsDeposit()`. Missing it
  is a compile error. Timeout, Group, and the select fence test
  return false. CQ `holdsDeposit` includes `drained`; `getResult`
  consumes it.
- Protocol failures go through `sim.protocolPanic` / `sim.panic`,
  which print TRACE_HASH. That includes CQ winner-without-deposit,
  channel/broadcast winner-without-result, select with no winner
  and no cancel, sim capacity panics, and unsimulated I/O.
- Each due I/O gets a stable id at submit. The digest hashes that
  id. `io_complete` emits it. Due kind is `DueKind`.
- Darwin SCOPE names the kqueue fd skip only on Darwin.

### Verification

- `zig build test`: 667 of 667 pass.
- DST D1 PASS, D2 DISTINCT_HASHES=252 SEEDS=1000, D4 PASS, D5 PASS.
  Mutant D3 replays the same panic line and TRACE_HASH.
  setclock_real clock_ns=30000000 (exact 10 ms per case).
### Problem

`pushDueKind` allocated the due-I/O id when an op joined the due
list, not when it was submitted. A parked recv stored only a
pointer. A later wake assigned a new id. Two parked recvs woken
in opposite order produced the same digest and the same
`io_complete` ids. A harvest that re-parked a send also dropped
the old id.

### Change

- `allocOpId` runs at submit (`sendBytes`, `recvInto`, `closeFd`).
- Parked state stores `{c, id}`. Wake, re-park, cancel, and
  complete reuse that id. `pushDueKind` does not allocate.
- `stateDigest` hashes parked ids and `next_io_id`, so a canceled
  due op still changes the digest.
- `runWakeOrderProbe` parks recv A then B and wakes in either
  order. The two orders must hash differently.

### Verification

- `zig build test`: 667 of 667 pass (the probe test skips without
  `-Dsim=true`).
- DST D1 PASS, D2 DISTINCT_HASHES=252 SEEDS=1000, D4 PASS, D5 PASS.
  `io_id_identity` seed 7: wake order A vs B changes TRACE_HASH
  and STATE_DIGEST.
### Problem

`cancelIo` returned only a bool. `cancelSimIo` set Canceled and
completed without the submit-time id. Two same-kind cancels left
the same `next_io_id` and no identity-bearing `io_complete`.
`.bad_fd` and send `.eof` called `setError` without a due entry
or `markCompleted`. A send after peer close could wait forever.

### Change

- A live-op table stores `{c, id}` at `allocOpId`. `cancelIo`
  returns that id. `cancelSimIo` emits `io_complete` with it.
- Terminal submit errors (eof, bad_fd) push a due entry. Harvest
  completes them with the submit-time id. Would-block emits on
  the immediate complete path.
- `runCancelOrderProbe` parks recv A then B and cancels in
  either order. The two orders must hash differently.

### Verification

- `zig build test`: 667 of 667 pass.
- DST D1 PASS, D2 DISTINCT_HASHES=252 SEEDS=1000, D4 PASS, D5 PASS.
  `io_cancel_identity` seed 7: cancel orders differ.
  `io_send_after_close` returns BrokenPipe (no deadlock).
  `io_cancel_parked` returns Canceled.
@dimenus
dimenus merged commit cd0d5fc into main Aug 27, 2026
dimenus pushed a commit that referenced this pull request Nov 14, 2026
…a race sibling's cancel cannot hide a lost one (round 4, finding 2)

## Problem

Round 4 of the outside review (of 0c0b061), finding 2. The op model's end
gave every waiting op its readiness at once. In a race group with
receives R1 and R2, if R1's registration was lost, R2 completed, the race
cancelled R1, and R1's `Canceled` was accepted as a sibling's cancel. The
proof was also counted when given, not when it worked, and the end's
settle still ran the random in-poll actions (closes, cancels,
follow-ups).

## Measured (ran)

Mutant RM2, "a race member's park does not register": in `submitSimDgram`
the second parked member of a group skips `dgramPark` (the first keeps
its registration, as in the review's sequence). RM, which strands every
member, is killed mid-run by the wake obligation already (seed 1, step
101), so it never reaches the end.

| run | old end (all at once) | new end (one at a time) |
|---|---|---|
| default length (8 seeds x 5000) | KILLED mid-run, seed 1 step 1800 | KILLED mid-run, seed 1 step 1800 |
| the end alone (`ZIO_OP_MODEL_STEPS=0`), 3 runs | SURVIVED, 3 of 3 | KILLED, 3 of 3: `seed 1 step 0: d_recv op #1 still waits on a socket with 1 datagrams queued` |

The "old end" here is the old procedure with the end groups below added,
so both columns prove the same ops.

## Changes (src/sim_op_model_test.zig)

- **End groups:** the end empties the queues (each a checked layer
  receive), then submits race groups of two waiting receives on sockets
  with nothing queued or waiting, so the proof has race members to prove
  (`end_groups`, required non-zero; 10 at the default length).
- **One at a time:** one waiting op is given what it waits for, and the
  clock settles before the next. A proof counts only when that op
  completes from it; a proving op that ends `Canceled` fails. The proof is
  recorded by the op's own completion, because its slot can be freed and
  reused by the time the settle ends.
- **No random actions during the proof:** `inBatch` and the group
  callback's follow-ups are off.
- A replay with `ZIO_OP_MODEL_STEPS` is a diagnostic: the counter floors
  and the probes are skipped (as for `ZIO_OP_MODEL_SEED`).

Two test bugs on the way, fixed above: the first version read the proven
op through its slot after a follow-up had reused it ("op lalinsky#5 ... group
null still waits", where op lalinsky#2 had been given and completed); follow-ups
are now off in the proof, and the proof is recorded at completion.

## Benefits

- A lost registration of a race member is found when that member is the
  one given readiness; a cancelled sibling is no longer counted as proven.

## Alternatives rejected, and what this depends on

- **Prove every member of a race group.** Once one completes, the race
  cancels the rest by design; the one-at-a-time order proves the member
  chosen, and the others are only cancelled.
- **A sim accessor that lists registered ops.** It would check the sim
  against itself; readiness checks behaviour.
- Depends on: a race member that completes cancels its siblings at once
  (`Group.groupCallback`), so the next waiting op chosen is never a member
  of a group already proven.

## Statistics

- src/sim_op_model_test.zig: about +90 -30.
- Sim tests (`-Dtest-filter="sim: "`): 224 of 224 passed, 2 skipped (with
  the next commit's test).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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