Repository navigation
Replace DoublyLinkedList with simple singly-linked AnyTaskList - #5
Conversation
- Replace std.DoublyLinkedList(AnyTask) with custom singly-linked list - Add next field to AnyTask for direct linking - Update Task<T> to work directly with *AnyTask instead of *AnyTaskList.Node - Implement push, pop, append, concatByMoving, and remove methods - Simplify task management by removing Node wrapper indirection
WalkthroughRefactors task management to use a direct AnyTask singly-linked structure with a Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor Caller
participant Runtime
participant ReadyList as AnyTaskList
participant AnyTask
participant Coro as Coroutine
Caller->>Runtime: spawn(f)
Runtime->>AnyTask: allocate + init(id, coro, ref_count, next=null)
Runtime->>ReadyList: push(task)
Runtime-->>Caller: returns Task{ task: *AnyTask }
loop scheduler tick
Runtime->>ReadyList: pop()
alt task exists
Runtime->>Coro: resume(task.coro)
opt task finished
Coro-->>Runtime: completed
Runtime->>AnyTask: wake waiting_list (append woken tasks)
Runtime->>ReadyList: push appended tasks
Runtime->>AnyTask: dealloc if ref_count==0
end
else
Runtime-->>Runtime: idle/wait
end
end
sequenceDiagram
autonumber
actor Joiner
participant TaskT as Task(T)
participant AnyTask
participant Runtime
participant Coro as Coroutine
Joiner->>TaskT: join()/result()
TaskT->>AnyTask: check task.coro status
alt not completed
TaskT->>Runtime: wait(current_coro)
Runtime->>AnyTask: append current task to waiting_list
Note right of AnyTask: uses direct fields (id, coro, next)
else completed
AnyTask-->>TaskT: provide result via task.coro
end
participant Waker as External
Waker->>Runtime: markReady(coro*)
Runtime->>ReadyList: push(task from taskPtrFromCoroPtr(coro*))
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches🧪 Generate unit tests
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (5)
src/runtime.zig (5)
140-149: Add a debug guard to prevent accidental double-enqueue.With a single
nextfield, enqueuing a task already in any list corrupts lists. Add an assertion to catch double-enqueue in debug builds.Apply this diff:
pub fn push(self: *AnyTaskList, task: *AnyTask) void { - task.next = null; + assert(task.next == null); // not already enqueued anywhere + task.next = null; if (self.tail) |tail| { tail.next = task; self.tail = task; } else { self.head = task; self.tail = task; } }
379-387: Guard against waiting on self to avoid deadlock.Calling
wait/joinon the current task deadlocks. Add a fast check.Apply this diff:
pub fn wait(self: *Runtime, task_id: u64) void { const task = self.tasks.get(task_id) orelse return; if (task.coro.result != .pending) { return; } const current_coro = coroutines.getCurrent() orelse std.debug.panic("not in coroutine", .{}); - task.waiting_list.append(taskPtrFromCoroPtr(current_coro)); + const current_task = taskPtrFromCoroPtr(current_coro); + if (current_task == task) { + std.debug.panic("a task cannot wait on itself", .{}); + } + task.waiting_list.append(current_task); current_coro.waitForReady(); }
54-54: Single next pointer implies single-list membership invariant.Using one
nextacross ready/cleanup/waiting lists requires tasks to be in at most one list at a time. Current flow appears to honor this; keep it documented and enforced with assertions (see push() guard).
135-210: AnyTaskList implementation is correct and minimal.push/pop/concat/remove look sound. Consider keeping these operations O(1)/move-only as you do now; the added assert prevents subtle corruption.
239-241: Deinit is assertive, which is acceptable for runtime teardown.You free tasks regardless of outstanding handles. Document that handles must not outlive Runtime or use after deinit. Optional: in debug, warn if
ref_count.value > 1.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/runtime.zig(10 hunks)
🔇 Additional comments (2)
src/runtime.zig (2)
66-124: Task wrapper changes look good.Direct
*AnyTaskusage and ref_count handling inside the wrapper are consistent. Once spawn’s runtime ref_count increment is added, join/result/detach semantics align.
367-377: Pointer derivation and readiness signaling look correct.
taskPtrFromCoroPtrandmarkReadymatch the new layout and enforce.waitingstate to avoid duplicate enqueues.
- Add in_list field to AnyTask (bool in debug, void in release) - Add assertions in push() to prevent adding task already in a list - Mark tasks as not in list when popped or removed - Guard against waiting on self to avoid deadlock
There was a problem hiding this comment.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/runtime.zig (1)
251-257: Major: Runtime.deinit frees tasks regardless of outstanding handles.If a Task(T) handle still exists, deinit will destroy the task, causing UAF when the handle later calls detach/deinit. Enforce correct lifecycle with a debug assertion to catch misuse.
Apply:
pub fn deinit(self: *Runtime) void { - var iter = self.tasks.iterator(); + if (builtin.mode == .Debug) { + // Deinitializing with live tasks breaks ref-count ownership. + std.debug.assert(self.tasks.size == 0); + } + var iter = self.tasks.iterator(); while (iter.next()) |entry| { const task = entry.value_ptr.*; task.coro.deinit(self.allocator); self.allocator.destroy(task); }
🧹 Nitpick comments (6)
src/runtime.zig (6)
95-106: Consider adding joinAndDetach() for ergonomics.Most callers want to reclaim the handle after join; a small helper avoids leaks from forgotten detach().
Example addition inside Task(T):
pub fn joinAndDetach(self: *Self) T { const val = self.join(); self.detach(); return val; }
108-125: Optional: return a typed result instead of panicking.result() currently panics on .pending and on .failure for non-error-union T. Consider exposing resultOrNull(): ?T or returning CoroutineResult(T) to avoid panics in library code.
188-226: remove() is correct; add early-exit micro‑opt if you want.Current linear scan is fine. You might tighten the loop to stop once curr.next is null.
263-290: Unify handle construction to one path.spawn currently increments the ref_count and then returns a struct literal; prefer using Task(T).init() to keep the policy in one place.
Apply:
- self.ready_queue.append(task); - - task.ref_count.incr(); - return .{ .task = task, .runtime = self }; + self.ready_queue.append(task); + return Task(ReturnType(func)).init(task, self);Note: Task.init already increments the handle ref; keep the initial RefCounter.init() = 1 for runtime ownership. Based on learnings.
332-339: Assert removal from tasks during cleanup.If a task isn’t in the map, something went wrong; assert in Debug to catch invariants early.
Apply:
- _ = self.tasks.remove(task.id); + const removed = self.tasks.remove(task.id); + if (builtin.mode == .Debug) std.debug.assert(removed);
388-394: Use a debug assert instead of a hard panic in markReady.External callbacks firing slightly out of phase can trip this; prefer assertions in Debug to avoid panicking in release builds.
Apply:
- if (coro.state != .waiting) std.debug.panic("coroutine is not waiting", .{}); + if (builtin.mode == .Debug) std.debug.assert(coro.state == .waiting);
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/runtime.zig(9 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-09-27T04:41:48.623Z
Learnt from: lalinsky
PR: lalinsky/zio#5
File: src/runtime.zig:257-273
Timestamp: 2025-09-27T04:41:48.623Z
Learning: RefCounter.init() starts with an initial count of 1, not 0. When a task is created in spawn(), the initial count represents the runtime's ownership when stored in self.tasks, and an additional incr() is called for the returned Task(T) handle.
Applied to files:
src/runtime.zig
🔇 Additional comments (7)
src/runtime.zig (7)
54-60: Good: direct next pointer and debug-only membership flag.Sane move to embed linkage in AnyTask. The in_list guard is correctly compiled out in non-Debug builds.
71-74: Ref-count semantics in Task.init look correct.Init taking a counted reference for the handle aligns with the runtime owning the initial ref. Based on learnings.
84-93: Detach deallocates only on last reference.This matches the runtime’s ownership model and prevents double frees. Based on learnings.
136-172: AnyTaskList.push/pop look correct; invariant maintained.next is reset, tail/head updates are correct, and debug in_list toggling prevents multi-list membership.
Please ensure all list insertions go through push/append (no raw next manipulation). If any direct mutations exist, they may violate the debug invariant.
173-187: concatByMoving is O(1) and correctly clears other.One nit: no invariant change needed since in_list tracks “in some list,” not which list, so this is fine.
344-362: Scheduler transitions look sound..state handling and waiting_list draining correctly move waiters to ready.
395-407: wait() correctly guards against self-wait and pending check.Membership and state transitions are consistent with the new list.
* Automatic stack growth on POSIX via SIGSEGV handler * Fix macOS/BSD builds * Use SIGSTKSZ for alternate signal stack allocation Replace hardcoded 8KB with platform-recommended SIGSTKSZ constant to ensure proper signal stack size across different architectures and operating systems. * Attempt * Fix * Skip stack growth on macos * Add diagnostic logging for stack growth debugging Add comprehensive logging to: - setupStackGrowth: Track altstack allocation and signal handler setup - sigsegvHandler: Trace handler execution path - Stack growth test: Monitor test progress and coroutine execution Remove macOS skip to enable debugging on that platform. * Add environment variable for test log capture * Revert aarch64 context switching optimization This reverts the changes from commit 1025c55, which optimized aarch64 context switching by storing lr in the Context struct. Reverting to the previous implementation that marks lr as clobbered and sets x30=0 explicitly. * Run tests under lldb on macOS CI for better crash debugging * Fix CI: run tests without lldb to allow signal handlers to work Running tests under lldb was preventing SIGSEGV signal handlers from working because lldb intercepts signals by default. Now tests run normally, and crash reports are shown only if tests fail on macOS. * More logging * Add more log * Add macOS stack growth PoC and skip test on macOS - Created clean standalone PoC to test SIGSEGV-based stack growth on macOS - Added PoC to CI to verify if the mechanism works - Skip the stack growth test on macOS (it has never worked there) The test crashes with SIGILL on macOS, needs investigation. The PoC will help determine if the issue is with the test itself or the stack growth mechanism. * Improve macOS PoC to actually trigger SIGSEGV Add explicit test that writes to uncommitted (PROT_NONE) memory to verify the SIGSEGV handler is actually invoked. Previous version was optimized away by the compiler and didn't actually test stack growth. * Fix stack growth on macOS: handle SIGBUS instead of SIGSEGV macOS sends SIGBUS when accessing PROT_NONE memory, not SIGSEGV. This is why stack growth has never worked on macOS. Changes: - Register both SIGSEGV and SIGBUS handlers on macOS - Update PoC to test both signals - Add proper cleanup for SIGBUS handler on Darwin This should fix the SIGILL crashes we were seeing - they were actually SIGBUS crashes that weren't being caught. * Re-enable stack growth test on macOS Now that we handle SIGBUS, the test should work on macOS. * Clean up signal handler naming and remove PoC Changes: - Rename sigsegvHandler -> stackFaultHandler (more accurate) - Update all log messages: "SIGSEGV:" -> "Stack fault:" - Rename test: "automatic growth via SIGSEGV" -> "automatic growth" - Update comments to reflect both SIGSEGV and SIGBUS handling - Remove macOS PoC (no longer needed, test works now) - Remove PoC from CI workflow The PoC served its purpose - it helped us discover that macOS uses SIGBUS instead of SIGSEGV for PROT_NONE access. Now that the actual test works, the PoC is no longer needed. * Fix * W * Revert "Revert aarch64 context switching optimization" This reverts commit 9e617e32974cafe4f62d96a515213bc9a9b7db82. * . * Remove debug logging from stack growth implementation Clean up debugging artifacts added during development: - Remove test log capture and crash report inspection from CI - Remove verbose logging from setupStackGrowth() and signal handler - Remove test case logging statements - Keep error logging for OutOfMemory conditions * Save and restore previous SIGBUS handler on cleanup Previously only the SIGSEGV handler was saved and restored. On macOS, we also install a SIGBUS handler (since macOS sends SIGBUS for PROT_NONE access), but we were just restoring the default handler instead of the previous one. Now we properly save and restore both handlers. * Propagate faults to previous signal handler instead of aborting When a SIGSEGV/SIGBUS fault is not from coroutine stack growth, properly chain to the previous signal handler instead of unconditionally aborting. This allows other signal handlers (e.g., debuggers, crash reporters) to work correctly. The handler will: - Call previous sigaction/handler if one was installed - Restore and re-raise for SIG.DFL/SIG.IGN - Abort as fallback if handler returns or raise fails * Fix switch on untagged union and remove SA_NODEFER - Fix compilation error: can't switch on untagged union, check SA_SIGINFO flag instead to determine handler type - Remove SA_NODEFER flag as it's not needed for our use case * Fix signal handler context parameter types - Change ctx parameter from ?*const anyopaque to ?*anyopaque in both stackFaultHandler and invokePreviousHandler - The context pointer points to mutable CPU state, not const - Handle optional handler fields on FreeBSD - Add missing cast for posix.raise() * Enable automatic growth test on Windows The test now runs on both POSIX and Windows. setupStackGrowth() and cleanupStackGrowth() are already no-ops on Windows, so we can call them unconditionally. Stack growth is verified on both platforms: - POSIX: via SIGSEGV/SIGBUS handler - Windows: via RtlCreateUserStack's automatic PAGE_GUARD mechanism * Fix setupStackGrowth/cleanStackGrowth
…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]>
Summary
This PR replaces the
std.DoublyLinkedList(AnyTask)implementation with a custom singly-linked list for better performance and simpler memory management.Changes Made
nextpointer for linking, eliminating the need for wrapper Node structures*AnyTaskinstead of*AnyTaskList.Node, simplifying the APIpush,pop,append,concatByMoving, andremovemethods to AnyTaskListBenefits
.dataindirectionTest plan
Summary by CodeRabbit
Breaking Changes
New Features
Improvements
Stability