Skip to content

Cancelable delegated file ops on kqueue/poll backends - #539

Merged
lalinsky merged 8 commits into
mainfrom
cancel-blocking-fileops
Jul 5, 2026
Merged

lalinsky merged 8 commits into
mainfrom
cancel-blocking-fileops

Conversation

@lalinsky

@lalinsky lalinsky commented Jul 4, 2026 •

Copy link
Copy Markdown
Owner

Stacked on #514 (cancel-blocking). Extends the SIGURG syscall-cancellation mechanism from that PR to the file/dir operations that fall back to the thread pool on backends without native async file I/O (kqueue, poll, ...).

A task blocked in open()/stat()/unlink()/... on a hung mount, or read()/write() on a stalled network filesystem, can now be canceled instead of waiting the syscall out.

Mechanism

  • DelegatedWork shared struct — used as the internal payload of every delegated file/dir op. Bundles the pool Work, loop linkage, allocator slot, the cancellation Token, and an intrusive link for the loop's resend list. linked_context.linked back-points to the owning Completion, so the loop reaches a DelegatedWork from a completion generically — nothing is added to the hot Completion struct.

  • Bracketed fs wrappers — the delegated syscall wrappers are wrapped in a Syscall.begin() / defer finish() / checkCancel()-on-EINTR region. The worker binds the token around work.func, so a SIGURG turns the blocking syscall into EINTR → error.Canceled. Off a cancelable worker the token is null and the brackets are no-ops (verified: all normal file I/O still passes). Now covered: openat, createat, preadv, pwritev, readv, writev, getdents/dirRead, dirOpen, read, write, fileSync, renameat, dirDeleteFile/Dir, mkdirat, fileSize, fstat, fstatat, fileSetSize/Permissions/Owner/Timestamps, dirSetFilePermissions/Owner/Timestamps, dirSymLink, dirReadLink, dirHardLink, dirAccess, dirRealPath (~30 wrappers).

  • Loop-driven resend — cancelLocal sends the first signal and, if the worker is blocked-and-canceling, adds the work to Loop.cancel_resend. Each tick re-sends SIGURG to cover a first signal lost in the begin()→sleep window, dropping entries once the worker acknowledges. This is not driven by the canceling coroutine — loop.cancel runs on the loop thread too (e.g. groupCallback canceling race-group siblings), so resend had to be non-blocking and loop-owned. The entry is removed as the completion is finalized in the work_completions drain, before its waiter is signaled, so the sweep never dereferences a token whose op is being freed. All list access is on the owning loop's thread; no lock.

  • Syscall API simplified — finish() is now idempotent, so every call site uses one idiom (const sc = try begin(); defer sc.finish(); with plain returns) instead of an explicit success-finish() + a per-error-arm fail(). Syscall.fail is removed; getrandom and the two cancel tests were converted along with the wrappers. The surface is now begin / checkCancel / finish (+ checkCanceled for the getaddrinfo-style pre-check).

The nesting constraint

begin() forbids nesting (a bracketed wrapper must not call another bracketed wrapper while its region is open — that would hit unreachable, a runtime panic, not a compile error). Every internal cross-call was audited; the transformed wrappers are all leaves. Three functions that call other now-cancelable wrappers — dirRealPathFile, fileHardLink, renameatPreserve — are deliberately left unbracketed (their constituent syscalls are still cancelable via the wrappers they call); making them cancelable needs block-scoped regions, a follow-up.

Testing

  • New fs test: canceling a blocking FIFO open (writerless O_RDONLY blocks in the worker's openat, since POSIX opens are unconditionally blocking) on the poll backend → error.Canceled. Passes; stress-clean (dozens of runs), no hangs.
  • Full suite green on poll (509) and io_uring (510); base cancel tests (syscall_cancel, blockInPlace, random) pass; cross-compiles clean on macOS/kqueue, FreeBSD/kqueue, and Windows.

Scope / notes

  • read/write bracketing uses the identical path but has no CI-testable interrupt: pool reads only ever get seekable regular files (pipes route to the backend poll path; positional reads on pipes are ESPIPE), and regular-file I/O blocks in TASK_UNINTERRUPTIBLE locally. So their cancellation bites only on network filesystems. The FIFO-open test validates the shared machinery end-to-end; the metadata/path ops that block only on hung mounts are likewise validated by the shared mechanism, not a dedicated interrupt test.
  • Not bracketed: ioctlPosix/process_wait (not cancelable file ops), and the three nesting functions above (dirRealPathFile/fileHardLink/renameatPreserve), which need block-scoped regions. All delegated ops carry the token via DelegatedWork, so each remaining wrapper is a one-spot follow-up.

Extends the SIGURG syscall-cancellation mechanism to the file/dir operations
that fall back to the thread pool on backends without native async file I/O
(kqueue, poll, ...). A task blocked in, e.g., open() on a hung mount or a
read()/write() on a stalled network filesystem can now be canceled instead of
waiting for the syscall to return on its own.

Mechanism:

  - A shared `DelegatedWork` struct is used as the `internal` payload of every
    delegated file/dir op. It bundles the pool `Work`, the loop linkage, an
    allocator slot, the cancellation `Token`, and an intrusive link for the
    loop's resend list. `linked_context.linked` back-points to the owning
    completion, so the loop finds a `DelegatedWork` from a completion generically
    (no per-op-type switch, nothing added to the hot `Completion`).

  - The worker binds the token around `work.func`; the delegated fs syscall
    wrappers (openat/createat/preadv/pwritev/readv/writev) are bracketed with
    `Syscall.begin()/checkCancel()/finish()`, so a SIGURG turns the blocking
    syscall into EINTR -> `error.Canceled`. Off a cancelable worker the token is
    null and the brackets are no-ops.

  - Cancellation (`cancelLocal`) sends the first signal and, if the worker is
    blocked-and-canceling, adds the work to `Loop.cancel_resend`. Each `tick`
    re-sends SIGURG to cover a first signal lost in the begin()->sleep window,
    dropping entries once the worker acknowledges. The entry is removed as the
    completion is finalized in the `work_completions` drain, before its waiter is
    signaled, so the sweep never touches a token whose op is being freed. All
    list access is on the owning loop's thread; no lock.

Tested with a FIFO-open cancellation test on the poll backend (a writerless
O_RDONLY FIFO blocks in the worker's openat, since POSIX opens are always
blocking). read/write bracketing uses the identical path; note that pool reads
only ever get seekable regular files, which are uninterruptible on local disk,
so their cancellation bites only on network filesystems.
@coderabbitai

coderabbitai Bot commented Jul 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: e0628e3a-df1a-4c99-a0ef-9df97d07652d

📥 Commits

Reviewing files that changed from the base of the PR and between 28f9f72 and b41e854.

📒 Files selected for processing (4)
  • src/common.zig
  • src/ev/completion.zig
  • src/ev/loop.zig
  • src/ev/thread_pool.zig
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/ev/loop.zig

📝 Walkthrough

Walkthrough

This PR adds cancellation resend handling for delegated blocking work, makes syscall cancellation helpers idempotent, updates POSIX syscall wrappers to check cancellation on EINTR, and adds a FIFO cancellation regression test.

Changes

Cancellation-aware delegated file work

Layer / File(s) Summary
Delegated payloads and cancel state
src/ev/completion.zig, src/ev/thread_pool.zig
Adds DelegatedWork, moves resend linkage onto Work, switches non-native operation fallbacks to the shared payload, and changes token-bearing thread-pool cancellation.
Syscall cancel helpers and region cleanup
src/os/syscall_cancel.zig, src/common.zig, src/os/posix.zig
Adds Token.isCanceling(), makes Syscall.finish() idempotent, updates the cancelable syscall test to defer finish(), and changes Linux getrandom cleanup to use defer sc.finish().
Loop resend tracking and polling
src/ev/loop.zig
Adds resend tracking, registration, completion cleanup, token wiring, and resend-aware tick polling for canceled delegated work.
Cancel-aware filesystem syscalls
src/os/fs.zig
Wraps POSIX filesystem syscalls in cancelable regions and checks cancellation on EINTR across open, read/write, sync, rename, delete, mkdir, stat, permission, ownership, timestamp, link, access, readdir, and realpath paths.
Blocking open cancellation test
src/fs.zig
Adds mkfifo and a test that cancels a blocking FIFO open and expects error.Canceled.

Estimated code review effort: 4 (Complex) | ~60 minutes

Possibly related PRs

  • lalinsky/zio#41: Shares the same cancellation machinery area, including syscall-cancel tokens and delegated work handling.
  • lalinsky/zio#454: Touches the same DirRenamePreserve operation path updated here through delegated completion and loop cancellation plumbing.

Poem

A blocked syscall heard the cue,
SIGURG came back, not just once but twice or two.
finish() now exits when the region is done,
and FIFO tests prove the cancel path works as one.
Plain syscalls, but now they know
how to stop, retry, and go.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly matches the PR’s main change: cancelable delegated file operations on kqueue/poll backends.
Description check ✅ Passed The description is directly about extending SIGURG cancellation to delegated file and directory operations.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch cancel-blocking-fileops

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot 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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/os/fs.zig (1)

804-817: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Wrap dirReadPosix with syscall_cancel dirOpen already has the cancelable wrapper, but dirReadPosix still retries getdents64/getdirentries without checking the token, so canceling a blocked directory read stays a no-op on the delegated worker path.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/os/fs.zig` around lines 804 - 817, `dirReadPosix` still loops on
`getdents64`/`getdirentries` without honoring cancellation, so make it use the
same `syscall_cancel` pattern already used by `dirOpen`. Update the
`dirReadPosix` path in `src/os/fs.zig` to pass the cancellation token through
the delegated worker/syscall wrapper, and ensure the retry loop checks for
cancellation before reissuing the read so blocked directory reads can be
interrupted cleanly.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@src/os/fs.zig`:
- Around line 804-817: `dirReadPosix` still loops on
`getdents64`/`getdirentries` without honoring cancellation, so make it use the
same `syscall_cancel` pattern already used by `dirOpen`. Update the
`dirReadPosix` path in `src/os/fs.zig` to pass the cancellation token through
the delegated worker/syscall wrapper, and ensure the retry loop checks for
cancellation before reissuing the read so blocked directory reads can be
interrupted cleanly.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: b4e7f200-8c17-4e64-ad0a-9e8b3a317186

📥 Commits

Reviewing files that changed from the base of the PR and between 7e237df and d35a790.

📒 Files selected for processing (5)
  • src/ev/completion.zig
  • src/ev/loop.zig
  • src/fs.zig
  • src/os/fs.zig
  • src/os/syscall_cancel.zig

Bracket dirReadPosix's getdents64/getdirentries loop with the syscall
cancellation region, like the read/write/open wrappers. dir_read is already
delegated via DelegatedWork, so this makes reading a directory on a hung/slow
mount cancelable as well.
Base automatically changed from cancel-blocking to main July 5, 2026 06:04
lalinsky added 2 commits July 5, 2026 08:25
Bracket the rest of the thread-pool-delegated fs wrappers with the syscall
cancellation region, so a task blocked on a hung/slow mount doing any of them
can be canceled: dirOpen, read, write, fileSync, renameat, dirDeleteFile,
dirDeleteDir, mkdirat, fileSize, fstat, fstatat, fileSetSize/Permissions/Owner/
Timestamps, dirSetFilePermissions/Owner/Timestamps, dirSymLink, dirReadLink,
dirHardLink, dirAccess, dirRealPath.

To keep the per-wrapper change to two lines, `Syscall.finish()` is now
idempotent (closing an already-closed region is a no-op), so each wrapper just
needs `const sc = try Syscall.begin(); defer sc.finish();` plus a
`try sc.checkCancel()` on the EINTR arm — no per-arm finish/fail bookkeeping.

Left for a follow-up: dirRealPathFile, fileHardLink, and renameatPreserve call
*other* now-cancelable wrappers, so a function-scoped region would nest inside
those calls (begin() forbids nesting). They need block-scoped regions around
their individual loops; their constituent syscalls are already cancelable via
the wrappers they call. Also unbracketed: openat2/resolve_beneath, and
ioctlPosix/process_wait (not cancelable file ops).
Now that finish() is idempotent, every cancelable-syscall site can use a single
`const sc = try begin(); defer sc.finish();` with plain returns, instead of an
explicit finish() on the success arm and a fail() wrapper on each error arm.

Convert the remaining explicit-style sites — the openat/createat/preadv/pwritev/
readv/writev/dirRead wrappers, getrandom, and the two cancel tests — to the
defer form, and remove the now-unused Syscall.fail helper. Pure refactor, no
behavior change (verified: syscall_cancel/blockInPlace/random tests, poll +
io_uring full suites, and the open-cancel stress all pass).

@coderabbitai coderabbitai Bot 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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/os/fs.zig (2)

660-696: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Move the openat2 loops into the cancelable region

The Linux openat2 paths in src/os/fs.zig still sit before Syscall.begin(), so .INTR, .AGAIN => continue never gets translated into Canceled. That leaves resolve_beneath opens uncancelable in openat, dirOpen, and createat on a hung mount.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/os/fs.zig` around lines 660 - 696, The Linux openat2 handling in the
file-open path is still outside the cancelable syscall region, so interruptions
are not converted into cancellation. Move the openat2 retry loop in the
resolve_beneath branch of the fs open logic so it runs after
syscall_cancel.Syscall.begin() and before defer sc.finish(), and make sure the
.INTR and .AGAIN cases flow through the existing cancellation handling used by
openat, dirOpen, and createat.

1401-1426: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Add cancel checks to the remaining EINTR retry loops renameatPreserve, fileHardLink, and dirRealPathFile still spin on EINTR without sc.checkCancel(), so a cancelable worker can get stuck in those paths. Mirror the cancel handling used in the other syscall wrappers.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/os/fs.zig` around lines 1401 - 1426, Add cancel handling to the remaining
EINTR retry loops in renameatPreserve, fileHardLink, and dirRealPathFile so a
cancelable worker can’t spin forever. In each loop that currently retries on
.INTR, call sc.checkCancel() before continuing, matching the pattern already
used in the other syscall wrappers, and keep the existing errno-to-error mapping
unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@src/os/fs.zig`:
- Around line 660-696: The Linux openat2 handling in the file-open path is still
outside the cancelable syscall region, so interruptions are not converted into
cancellation. Move the openat2 retry loop in the resolve_beneath branch of the
fs open logic so it runs after syscall_cancel.Syscall.begin() and before defer
sc.finish(), and make sure the .INTR and .AGAIN cases flow through the existing
cancellation handling used by openat, dirOpen, and createat.
- Around line 1401-1426: Add cancel handling to the remaining EINTR retry loops
in renameatPreserve, fileHardLink, and dirRealPathFile so a cancelable worker
can’t spin forever. In each loop that currently retries on .INTR, call
sc.checkCancel() before continuing, matching the pattern already used in the
other syscall wrappers, and keep the existing errno-to-error mapping unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: ba3cde96-1152-417f-8221-f7808b586cf6

📥 Commits

Reviewing files that changed from the base of the PR and between 4951122 and dffcfd5.

📒 Files selected for processing (4)
  • src/common.zig
  • src/os/fs.zig
  • src/os/posix.zig
  • src/os/syscall_cancel.zig
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/os/syscall_cancel.zig

lalinsky added 2 commits July 5, 2026 08:48
The Linux openat2 paths in openat, createat, and dirOpen ran their retry loop
*before* Syscall.begin(), so their `.INTR, .AGAIN => continue` never became
`Canceled` — leaving resolve_beneath opens uncancelable on a hung mount.

Move `begin()`/`defer finish()` above the resolve_beneath branch so the one
region covers both the openat2 loop and the plain openat loop, and split the
openat2 arm into `.INTR => checkCancel()` (cancellation) vs `.AGAIN => continue`
(a real retry, not a cancel).
blockInPlace kept ctx/work/waiter on its own stack and used a custom
completion_fn that signaled the waiter directly from the worker thread.
The cancel path returned as soon as it observed a `done` flag that
completion_fn set *before* its trailing waiter.signal(), so the task
could return and reclaim the frame while the worker was still inside
signal() — a use-after-free that read the freed Waiter (its union tag
decoded as .select, taking cmpxchgStrong on a garbage pointer and
segfaulting at 0x0). It reproduced regularly on powerpc64le under QEMU
in CI, where the resend-backoff timer reliably fired in the tiny window
between the store and the signal.

Fix: submit the work through the event loop and wait via waitForIo, so
the loop owns completion delivery — it finalizes work.c and signals the
waiter on the loop thread as the last step, and waitForIo waits for that
before returning. Nothing touches the stack frame after we may return,
so the UAF window is gone by construction. This deletes the custom
completion_fn, the `done` flag, and the whole manual token/resend loop.

To make this correct and cover the first-signal-lost case generically:

- Generalize the loop's SIGURG cancel-resend list to key on any
  Work.cancel_token, not just DelegatedWork. The intrusive link moves
  from DelegatedWork to Work (resend_next/resend_key); resend_key is the
  public completion whose finalization drops the entry, so both a plain
  .work op (key == &work.c) and a delegated file op (key == the owning
  op completion) are handled uniformly. The generic .work cancel path
  now registers for resend too.

- ThreadPool.cancel never drops token-bearing work: its func always runs
  so the result is always valid (a still-queued syscall aborts at
  begin(), a running one is interrupted via SIGURG). This preserves
  blockInPlace's "workFn always runs" invariant and matches the delegated
  ops (which report Canceled from the op func either way).

A canceled blockInPlace now also re-arms the task's pending cancellation
(via waitForIo's recancel), so the task stays canceled afterward.
lalinsky added 2 commits July 5, 2026 11:02
waitForIo only returns error.Canceled when the completion carries a
Canceled result, which only happens on the drop path where workFn never
runs and ctx.result is undefined. Token-bearing work is never dropped, so
that is unreachable here; assert it with `catch unreachable` rather than
swallowing it, so a broken invariant crashes loudly instead of returning
uninitialized ctx.result.
Fix blockInPlace cancellation UAF by waiting through the event loop
@lalinsky
lalinsky merged commit 120ada0 into main Jul 5, 2026
26 checks passed
@lalinsky
lalinsky deleted the cancel-blocking-fileops branch July 5, 2026 11:46
dimenus pushed a commit to dimenus/zio that referenced this pull request Nov 14, 2026
…ds the four completion defects of the two outside reviews

## Problem

Two rounds of outside review found three serious defects, and one more, that
about 150 hand-written mutants and tests had missed: round 1 finding 1 (an
empty datagram moved the byte ring's head), round 1 finding 2 (an op woken
by a close ran against the socket that reused its fd number), round 2 F1 (a
batch entry completed twice after a group callback cancelled it) and round 2
F2 (a woken pipe receive reported end of file). All are in how ops are
completed, woken, cancelled and closed, or in rare shapes. The two model
tests in `sim.zig` check storage only. Nothing checked ops against a model.

## Changes

- New `src/sim_op_model_test.zig`, two tests:
  - `sim: op model: datagram sockets and a pipe under random sends,
    receives, polls, cancels, race groups, close and reopen` (the parent),
    which runs the same name `, in a child process`.
  - One sim run per seed with a bare `ev.Loop` (no runtime), four datagram
    sockets and one pipe. 14 step kinds: ev send, layer send, ev receive
    (parks when empty), layer receive, layer poll, ev poll (read or write),
    pipe send, pipe receive, cancel (an op or a whole group), race group of
    2 or 3 members (deferred and not), close (layer or ev), open (reuses the
    fd number), SO_RCVBUF, and clock (one poll, or polls until the clock
    has moved by 0.2 to 10 ms).
  - A group callback that runs inside a poll submits new ops into the slots
    it just freed ("follow-ups"), mostly of the same type, so a new op sits
    at the address of a member that may still be in the harvest's batch.
    This is item 4 of the brief (report 15's gap).
  - The model is byte strings, queues, ports and pending ops. It shares no
    helper with the sim. The header comment has what it checks, the rules
    the generator keeps so the model has one answer, and what it does not
    reach.
  - The child prints `op model: seed S step K` before each step, so a crash
    anywhere names the seed and step; the parent prints the last one.
    `ZIO_OP_MODEL_SEED` replays one seed, `ZIO_OP_MODEL_STEPS` sets the
    length (default 8 seeds x 5000 steps).
  - It fails when any step kind or any of 16 case counters is zero: a case
    that never ran is a hole, not a pass.
- `src/sim.zig`: `testPipeBuffered` (test only) so the test compares each
  pipe end's level with the model after every step; the child-process
  helpers (`death_child_env`, `isDeathChild`, `noCoreDump`, `childDone`,
  `checkDoneMarkers`) are `pub`; the new file is imported in the test block.
  No change to a build without sim: all of it is test code.

## The four defects, with each fix reverted (ran)

Each in a scratch clone of this tree with only the fix's code reverted (the
tests that came with it stay). 7c0c22e reverts cleanly with `git revert`;
the other three conflict in `sim.zig` tests added later, so their code
hunks were reverted by hand: 3727c95 the old `ring_head` line; 1b2d7ce the
harvest's `buf[i].closed` check and the close's `dgram_closed` wake; 794ce5d
the `isLive` skip and the old `takeOpId(c) orelse buf[i].id`. The default
run (8 seeds x 5000 steps), then the failing seed alone, 3 runs each:

| fix reverted | found at | what it printed |
|---|---|---|
| 3727c95, round 1 finding 1 | seed 3, step 772 | `d_recv op lalinsky#539: buffer 0 holds other bytes than the model's (721 bytes from offset 0)` |
| 1b2d7ce, round 1 finding 2 | seed 1, step 1927 | `d_recv op #1223 was due before poll 844 and has not completed` |
| 794ce5d, round 2 F1 | seed 1, step 21 | `panic: reached unreachable code` (the child's last step line names it) |
| 7c0c22e, round 2 F2 | seed 1, step 133 | `p_recv op lalinsky#30 (waited) completed .{ .n = 0 } on an open pipe with nothing buffered` |

Each seed alone failed at the same step in 3 of 3 runs.

Finding 1 needs seven events in order on one socket (only empty datagrams
left after a receive, a datagram with bytes lands, the empty one is
received, another lands, ...). A first version did not find it: 1886 of
3003 datagrams went to ports with no socket, and the op slots were full in
7164 steps because one poll moves the clock only to the next due op. The
test now aims 7 of 8 sends at an open socket and has the clock step that
moves a fixed time. Counters `only_empty_left` (283) and
`landed_behind_empty` (107) show the start of that shape is reached.

## Mutants (ran, T/mut/run.py, all on this test)

- PO1, `isLive` compares the pointer only: KILLED, `sim: op 34 completed
  but not live`.
- PO2, `isLive` and `endOp` compare the pointer only: KILLED, `sim: 9 ops
  due but only 8 live`.
- Control: PO1 and PO2 with the follow-ups turned off. Both pass every
  model check over all 8 seeds and fail only on the test's own guard,
  `followups_into_canceled_due` is 0. So the follow-ups are what kill them.
- No live check in the harvest: KILLED. A drain that wakes no sender, a
  copy that wakes no receiver: KILLED at the end check ("still waits with
  nothing to wait for"). A cancel that leaves a datagram op parked: KILLED
  (`two ev ops parked`). A close that wakes nothing: KILLED. A receive that
  reports the full length: KILLED. No byte limit: KILLED.
- No packet limit: SURVIVED, as expected: queues here stay far below 1024.
  The datagram queue model test is the instrument for it (next commit).

## Counts of a passing run (8 seeds x 5000 steps, about 0.15 s)

- Steps by kind: ev_send 4063, layer_send 1293, ev_recv 3696, layer_recv
  1306, layer_poll 942, ev_poll 1643, pipe_send 3356, pipe_recv 3351,
  cancel 2137, group 3204, close 1059, open 1049, rcvbuf 997, clock 8373.
- Skipped because the rules forbade it then: ev_send 557, ev_recv 784,
  layer_send 578, open 445 (no socket closed), the rest under 300. Skips for
  a full slot pool: 0.
- ops 25509, parked 3121, canceled 983, closed_hit 261, reused_number_ops
  16506, closed_then_reused 28, groups 2824, f1_shape_groups 1086,
  followups 1611, followups_into_canceled_due 475, f2_shape 181.
- datagrams 7550 (2157 empty), truncated 1355, scatter receives 3745,
  dropped for the limits 409, no socket 1389, discarded at close 1090,
  landed in a socket opened after the send 114, pipe sends parked 411.

## Benefits

- The first instrument that checks ops, not storage: every completion is
  checked against a model, once, with its bytes; and every wait must have a
  reason at the end, which catches a lost wake.
- A crash is reported with its seed and step, and replays alone.

## Alternatives rejected, and what this depends on

- **Drive ops from tasks with `waitForIo`.** It hides the harvest: a task's
  wait makes members deferred, so F1 cannot happen, and the test cannot
  cancel or submit inside a harvest.
- **A model that accepts any order of actions in one poll.** Possible, but
  a lenient oracle is how a model passes a defect. Instead the generator
  keeps the order knowable: a pipe op that will wait is never deferred, one
  source per destination per instant, distinct fds in a group.
- **In-process only, with the step in a global the panic prints.** The F1
  crash is `unreachable` in `enterCompleted`, which never reaches a sim
  hook. A child process sees every crash, and a hang hits its 600 s limit.
- **Settle the end by a count of polls.** Tried first: a send woken at
  25.26 ms was due at 30.26 ms, 40 polls ended near 28 ms, and the end check
  called a legal wait a lost wake. The end now settles 20 ms of clock time.
- Depends on: the sim lands datagrams only inside a harvest, and the clock
  moves only inside a poll, so between polls the model and the sim have
  landed the same datagrams (`syncLand`); and a pipe op's delay is at most
  5 ms (the liveness check allows 10).

## Statistics

- `src/sim_op_model_test.zig`: new, 1485 lines (`zig fmt`).
- `src/sim.zig`: +14 -5 (one test accessor, five `pub`, one import).
- Sim tests (`-Dtest-filter="sim: "`): 213 of 213 passed, 2 skipped (211
  before, plus the two new tests; both listed by name in the verbose run).

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.

1 participant