Skip to content

Replace DoublyLinkedList with simple singly-linked AnyTaskList - #5

Merged
lalinsky merged 2 commits into
mainfrom
anytasklist-feature
Sep 27, 2025
Merged

lalinsky merged 2 commits into
mainfrom
anytasklist-feature

Conversation

@lalinsky

@lalinsky lalinsky commented Sep 26, 2025 •

Copy link
Copy Markdown
Owner

Summary

This PR replaces the std.DoublyLinkedList(AnyTask) implementation with a custom singly-linked list for better performance and simpler memory management.

Changes Made

  • Replace std.DoublyLinkedList: Removed dependency on standard library's doubly-linked list in favor of a simpler custom implementation
  • Add next field to AnyTask: Tasks now directly contain a next pointer for linking, eliminating the need for wrapper Node structures
  • Update Task interface: Now works directly with *AnyTask instead of *AnyTaskList.Node, simplifying the API
  • Implement core list operations: Added push, pop, append, concatByMoving, and remove methods to AnyTaskList
  • Remove Node indirection: Eliminated the wrapper Node structure, making task management more direct and efficient

Benefits

  • Performance: Singly-linked list with direct task pointers reduces memory overhead and improves cache locality
  • Simplicity: Removes abstraction layers and makes the code more straightforward
  • Memory efficiency: Eliminates Node wrapper allocations
  • API clarity: Direct access to task fields without .data indirection

Test plan

  • Code compiles successfully
  • All tests pass
  • Verify task scheduling and cleanup still work correctly

Summary by CodeRabbit

  • Breaking Changes

    • Public task and runtime APIs changed (handle types, initialization, and list semantics). Upstream integrations may need updates.
  • New Features

    • mark-ready exposed as a public runtime method.
    • Task handles gained an explicit deinit method.
  • Improvements

    • Scheduler rewritten to use a simpler task list and direct task references, reducing scheduling overhead and clarifying lifecycle flows.
  • Stability

    • Improved task cleanup, waiting/joining behavior, and memory management.

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

coderabbitai Bot commented Sep 26, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Refactors task management to use a direct AnyTask singly-linked structure with a next pointer, replaces std.DoublyLinkedList with a custom AnyTaskList, updates Task(T) to hold *AnyTask, changes runtime task map to *AnyTask, and adjusts spawn/wait/join/result/deinit/markReady flows in src/runtime.zig.

Changes

Cohort / File(s) Summary
AnyTask structure and linkage
src/runtime.zig
Added AnyTask.next: ?*AnyTask = null; replaced references from data.*/node wrapper to direct fields (id, coro, ref_count, waiting_list, next).
Task(T) wrapper API
src/runtime.zig
Task now stores *AnyTask (was *AnyTaskList.Node); init signature updated; added pub fn deinit; detach/join/result use task.coro and task.ref_count.
AnyTaskList implementation
src/runtime.zig
Replaced std.DoublyLinkedList with a custom AnyTaskList { head, tail } and methods: push, pop, append, concatByMoving, remove; operations use AnyTask.next and include debug in_list checks.
Runtime mappings and loops
src/runtime.zig
tasks map now std.AutoHashMapUnmanaged(u64, *AnyTask); spawn/wait/loop/ready logic updated to operate on *AnyTask; iterations, dealloc, and state transitions reference task.coro, task.next, and waiting_list.
Public utilities & helpers
src/runtime.zig
pub inline fn taskPtrFromCoroPtr(coro: *Coroutine) *AnyTask now returns *AnyTask; markReady promoted to pub fn markReady(self: *Runtime, coro: *Coroutine) void.
Creation and destruction paths
src/runtime.zig
Spawn allocates/initializes AnyTask directly (task.* = .{ ... }); deinit/destroy paths updated to use task.coro, task.next, and task.ref_count; removed node-based deallocation paths.

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
Loading
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*))
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

I nibbled the nodes to a single bright thread,
Next links hop lightly where doubly once led.
Tasks map to hearts, coro beats in sync,
Ready lists rustle—pop, push, and blink.
A gentle wake—markReady!—I cheer,
Then join for the harvest: results nibble-near. 🥕

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title accurately and succinctly describes the primary change—replacing the standard DoublyLinkedList with a custom singly-linked AnyTaskList—without extraneous detail or vague language.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch anytasklist-feature

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 and usage tips.

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

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 next field, 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/join on 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 next across 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

📥 Commits

Reviewing files that changed from the base of the PR and between 65f8ad2 and 8a64fee.

📒 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 *AnyTask usage 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.

taskPtrFromCoroPtr and markReady match the new layout and enforce .waiting state to avoid duplicate enqueues.

Comment thread src/runtime.zig Resolved
- 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
@lalinsky
lalinsky merged commit dc4ec48 into main Sep 27, 2025
@lalinsky
lalinsky deleted the anytasklist-feature branch September 27, 2025 05:04

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

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8a64fee and f4368e4.

📒 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.

lalinsky added a commit that referenced this pull request Jan 6, 2026
* 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
This was referenced Jan 10, 2026
dimenus pushed a commit to dimenus/zio 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.

1 participant