Skip to content

Fix wait_node double-list bug in sync primitives - #182

Merged
lalinsky merged 2 commits into
mainfrom
fix-waiter-pattern
Jan 8, 2026
Merged

lalinsky merged 2 commits into
mainfrom
fix-waiter-pattern

Conversation

@lalinsky

@lalinsky lalinsky commented Jan 8, 2026

Copy link
Copy Markdown
Owner

Summary

  • Fix bug where a task's wait_node could be in two lists simultaneously when cancelled/timed out while waiting on a sync primitive
  • Introduce stack-allocated Waiter struct that separates operation wait nodes from task wait nodes
  • Change in_list debug checks to use std.debug.runtime_safety for coverage in ReleaseSafe builds

Problem

When a task waits on a sync primitive (Mutex, Condition, ResetEvent, etc.), its wait_node is added to the primitive's queue. If the task is cancelled or times out, the runtime tries to schedule the task by pushing its wait_node to the ready queue - but it's still in the sync primitive's queue, causing an assertion failure.

Solution

Introduce a Waiter struct in src/sync/common.zig that wraps a separate WaitNode. The Waiter's wait_node goes into the sync primitive's queue, while the task's own wait_node remains free for runtime scheduling.

Files Changed

  • src/sync/common.zig (NEW) - Waiter struct definition
  • src/sync/Condition.zig - Use Waiter in wait/timedWait
  • src/sync/ResetEvent.zig - Use Waiter in wait/timedWait
  • src/sync/Notify.zig - Use Waiter in wait/timedWait
  • src/sync/Mutex.zig - Use Waiter in lock
  • src/sync/channel.zig - Use Waiter in send/receive
  • src/sync/broadcast_channel.zig - Use Waiter in receive
  • src/signal.zig - Use Waiter in wait/timedWait
  • Various utils files - Change to std.debug.runtime_safety

Test plan

  • All 254 existing tests pass
  • Specific cancellation test added: ResetEvent: cancel waiting task

When a task waits on a sync primitive, its wait_node is added to the
primitive's queue. If the task is cancelled or times out, the runtime
tries to schedule the task by pushing its wait_node to the ready queue,
but it's still in the sync primitive's queue - causing an assertion
failure (node can't be in two lists at once).

Fix by introducing a stack-allocated Waiter struct that wraps a separate
WaitNode for sync primitive queues. The Waiter's wait_node goes into
the sync primitive's queue, while the task's own wait_node remains free
for runtime scheduling.

Also change in_list debug checks from builtin.mode == .Debug to
std.debug.runtime_safety for coverage in ReleaseSafe builds.
@coderabbitai

coderabbitai Bot commented Jan 8, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

The PR refactors synchronization primitives to use per-operation Waiters, migrates debug safety checks from compile-time build modes to runtime safety flags, adds debug assertions in task scheduling, and introduces a custom test runner with enhanced logging and diagnostics.

Changes

Cohort / File(s) Summary
Test Infrastructure
build.zig, test_runner.zig
Adds custom Zig test runner with test log capture, per-test timing tracking, slow-test identification, colorized output, memory leak detection, and panic handling integration (399 new lines in test_runner). Test configuration updated to reference the new runner.
Runtime Safety Condition Migration
src/runtime/WaitNode.zig, src/runtime/awaitable.zig, src/runtime/group.zig, src/utils/simple_queue.zig, src/utils/simple_stack.zig, src/utils/wait_queue.zig
Replaces compile-time builtin.mode == .Debug guards with runtime std.debug.runtime_safety checks. In wait_queue.zig: adds tail-pointer initialization in CompactWaitQueue and adjusts pointer-tracking semantics.
Runtime Scheduling
src/runtime.zig
Adds debug-only assertions in scheduleTaskLocal and scheduleTaskRemote to verify wait_node is not already in a list before enqueuing.
Waiter Infrastructure
src/sync/common.zig
New public Waiter type with embedded WaitNode and Awaitable pointer; provides init() constructor and vtable for task resumption on wake.
Synchronization Primitives
src/signal.zig, src/sync/Condition.zig, src/sync/Mutex.zig, src/sync/Notify.zig, src/sync/ResetEvent.zig, src/sync/broadcast_channel.zig, src/sync/channel.zig
Introduces stack-allocated Waiter per wait operation, replaces direct task.awaitable.wait_node with waiter.wait_node in queue operations, updates cancellation paths to remove waiter.wait_node, removes prior in-list debug assertions after wake events. ResetEvent adds new cancellation test.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Possibly related PRs

Poem

🧵 Per-op waiters dance their own line,
No shared nodes, each waiter's spine,
Debug checks now heed runtime's call,
Test logs flow, slow tests fall,
Safety nets woven tighter still. 🎭

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the primary change: fixing a bug where wait_node could be in multiple lists simultaneously when sync primitives are cancelled or timed out.
Description check ✅ Passed The description is directly related to the changeset, explaining the bug, solution approach with the Waiter struct, affected files, and test coverage.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix-waiter-pattern

📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 15d8a8c and ca9c876.

📒 Files selected for processing (17)
  • build.zig
  • src/runtime.zig
  • src/runtime/WaitNode.zig
  • src/runtime/awaitable.zig
  • src/runtime/group.zig
  • src/signal.zig
  • src/sync/Condition.zig
  • src/sync/Mutex.zig
  • src/sync/Notify.zig
  • src/sync/ResetEvent.zig
  • src/sync/broadcast_channel.zig
  • src/sync/channel.zig
  • src/sync/common.zig
  • src/utils/simple_queue.zig
  • src/utils/simple_stack.zig
  • src/utils/wait_queue.zig
  • test_runner.zig
🧰 Additional context used
🧠 Learnings (11)
📓 Common learnings
Learnt from: lalinsky
Repo: lalinsky/zio PR: 48
File: src/core/ConcurrentAwaitableList.zig:254-269
Timestamp: 2025-10-16T14:33:19.718Z
Learning: In the zio repository's `src/core/ConcurrentAwaitableList.zig` and `src/core/Awaitable.zig`, the `in_list` field should remain debug-only (conditional compilation with `builtin.mode == .Debug`). Double-removal detection in `ConcurrentAwaitableList.remove()` uses pointer-based checks (comparing `prev`/`next` against `head`/`tail`) rather than relying on a regular `in_list` field.
📚 Learning: 2025-10-21T10:00:56.962Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 62
File: src/utils/queue.zig:141-147
Timestamp: 2025-10-21T10:00:56.962Z
Learning: In work-stealing queues implemented in src/utils/queue.zig, stealers only modify the victim's head position, never the tail. The tail is exclusively owned by the owner thread, so no atomic acquire operations are needed when the owner reads its own tail.

Applied to files:

  • src/signal.zig
  • src/sync/Mutex.zig
  • src/utils/simple_queue.zig
  • src/sync/Notify.zig
  • src/sync/ResetEvent.zig
  • src/utils/wait_queue.zig
  • src/sync/Condition.zig
📚 Learning: 2025-10-16T14:33:19.718Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 48
File: src/core/ConcurrentAwaitableList.zig:254-269
Timestamp: 2025-10-16T14:33:19.718Z
Learning: In the zio repository's `src/core/ConcurrentAwaitableList.zig` and `src/core/Awaitable.zig`, the `in_list` field should remain debug-only (conditional compilation with `builtin.mode == .Debug`). Double-removal detection in `ConcurrentAwaitableList.remove()` uses pointer-based checks (comparing `prev`/`next` against `head`/`tail`) rather than relying on a regular `in_list` field.

Applied to files:

  • src/signal.zig
  • src/utils/simple_stack.zig
  • src/utils/simple_queue.zig
  • src/runtime/awaitable.zig
  • src/sync/Notify.zig
  • src/sync/ResetEvent.zig
  • src/runtime.zig
  • src/runtime/group.zig
  • src/utils/wait_queue.zig
  • src/sync/Condition.zig
  • src/runtime/WaitNode.zig
📚 Learning: 2026-01-07T13:15:48.677Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 179
File: src/os/windows.zig:424-424
Timestamp: 2026-01-07T13:15:48.677Z
Learning: In `src/os/windows.zig`, WSABUF must be re-exported from `std.os.windows.ws2_32.WSABUF` rather than defined locally because it needs to satisfy `std.Io.Reader` compatibility requirements.

Applied to files:

  • src/signal.zig
  • src/sync/Notify.zig
📚 Learning: 2025-10-15T19:38:44.659Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 47
File: src/sync/Mutex.zig:237-237
Timestamp: 2025-10-15T19:38:44.659Z
Learning: In the `unlock` method of `src/sync/Mutex.zig`, the `runtime` parameter is intentionally retained (marked with `_ = runtime;`) for API consistency and future-proofing, even though it's not currently used in the implementation.

Applied to files:

  • src/sync/Mutex.zig
  • src/utils/simple_stack.zig
  • src/utils/simple_queue.zig
  • src/runtime.zig
  • src/utils/wait_queue.zig
📚 Learning: 2025-11-04T10:29:56.949Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 118
File: src/core/task.zig:33-115
Timestamp: 2025-11-04T10:29:56.949Z
Learning: In zio's task implementation (src/core/task.zig), the Closure struct intentionally caps result_len and context_len at 4096 bytes (using u12 fields) and alignment at 16 bytes (using u4 padding fields). This is a deliberate design decision to avoid bloating task structures. Users needing larger result or context storage should heap-allocate and pass pointers instead. These limits are more generous than std lib's fixed storage (64 bytes for results, 1024 bytes for args).
<!-- [add_learning]
The task storage limits in zio (4 KiB for result/context, 16-byte alignment) are intentional design constraints to prevent task bloat, not correctness issues. The maintainer's position is that larger data should be heap-allocated.

Applied to files:

  • src/sync/Mutex.zig
📚 Learning: 2025-10-03T11:09:46.846Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 18
File: src/net.zig:18-25
Timestamp: 2025-10-03T11:09:46.846Z
Learning: In zio's `Runtime.BlockingTask`, calling `deinit()` on a blocking task only frees the task wrapper (TaskData) itself, not the result returned by the blocking function. The result remains valid and owned by the caller, who is responsible for its cleanup. This is the intended design for async blocking tasks.

Applied to files:

  • src/sync/Mutex.zig
  • src/sync/Notify.zig
  • src/sync/broadcast_channel.zig
📚 Learning: 2026-01-08T09:59:37.757Z
Learnt from: CR
Repo: lalinsky/zio PR: 0
File: CLAUDE.md:0-0
Timestamp: 2026-01-08T09:59:37.757Z
Learning: Applies to build.zig.zon : Update version in build.zig.zon during release process

Applied to files:

  • build.zig
📚 Learning: 2025-10-21T10:07:03.593Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 62
File: src/utils/queue.zig:109-126
Timestamp: 2025-10-21T10:07:03.593Z
Learning: In src/utils/queue.zig WorkStealingQueue implementation, the owner thread can safely use `.raw` to read its own `tail` atomic value since the owner is always a single thread and only it modifies tail. No ordering is needed when reading your own writes within the same thread.

Applied to files:

  • src/sync/ResetEvent.zig
  • src/utils/wait_queue.zig
  • src/sync/Condition.zig
📚 Learning: 2025-10-23T16:17:53.575Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 70
File: src/select.zig:145-153
Timestamp: 2025-10-23T16:17:53.575Z
Learning: In src/select.zig, the select() function is designed to accept futures either as copyable wrappers (e.g., JoinHandle(T)) by value, or as pointers (e.g., &reset_event) for value-owned types. This is intentional, and users are expected to pass the appropriate form based on the future type.

Applied to files:

  • src/sync/ResetEvent.zig
  • src/sync/broadcast_channel.zig
📚 Learning: 2025-10-10T05:59:17.087Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 41
File: src/udp.zig:79-82
Timestamp: 2025-10-10T05:59:17.087Z
Learning: In UDP socket operations (src/udp.zig), error.Canceled from result_data.result represents OS/IO-level cancellation (e.g., io_uring), not user-requested cancellation. User cancellation is handled by waitForXevCompletion() via try. OS-level error.Canceled should be mapped to error.Unexpected as it represents an unexpected system event.

Applied to files:

  • src/sync/ResetEvent.zig
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: cubic · AI code reviewer
  • GitHub Check: test (windows-latest)
🔇 Additional comments (33)
src/runtime.zig (1)

743-745: Good defensive assertions for catching double-enqueue.

These checks will fire if a task's wait_node is already in a queue when scheduling is attempted, which is exactly the bug this PR addresses. Placing them before any push operation is the right spot.

The std.debug.runtime_safety guard means these assertions also run in ReleaseSafe builds, not just Debug - a sensible choice for catching this class of bug.

Also applies to: 767-769

test_runner.zig (4)

22-58: LogCapture: mutex usage looks correct for thread-safety.

The mutex protects access to capture_writer and ensures log output is serialized. The lock-then-write pattern is appropriate.

One thing to note: when capture_writer is null (line 42-43), you call std.debug.print which has its own internal locking, so the mutex is technically redundant in that path, but it doesn't hurt and keeps the code symmetric.


74-92: Test harness setup looks solid.

The GPA, environment parsing, slow-test tracker, and log buffer are all properly initialized with corresponding defers. The log capture buffer using std.Io.Writer.Allocating will grow as needed and get freed on exit.


376-383: Custom panic handler for test context.

Using std.debug.FullPanic with a wrapper that prints the current test name before calling defaultPanic is useful for debugging - when a test panics, you'll immediately know which one without having to scroll up through output.


178-184: Zig version compatibility for dumpStackTrace API.

The API changed in 0.16 from taking the StackTrace by-value to taking a pointer; the code correctly passes the dereferenced value for <0.16 and the pointer directly for 0.16+.

build.zig (1)

108-112: Custom test runner integration.

The .mode = .simple setting means your test_runner.zig gets builtin.test_functions directly and handles execution itself. This pairs correctly with the test_runner.zig implementation that iterates over builtin.test_functions.

src/utils/simple_queue.zig (1)

33-36: Runtime safety for in_list tracking - consistent change.

Switching from builtin.mode == .Debug to std.debug.runtime_safety means these assertions will also fire in ReleaseSafe builds. For a single-threaded queue, that's useful - you get safety checks in optimized builds without the full Debug overhead.

The doc comment at line 13 still says "Required in debug mode" but now it's "required when runtime_safety is enabled". Minor doc drift, but not blocking.

Also applies to: 51-53, 93-95

src/utils/simple_stack.zig (1)

31-34: Consistent with the simple_queue.zig changes.

Same runtime_safety guard pattern applied to the stack. No issues here.

Also applies to: 41-43

src/sync/broadcast_channel.zig (2)

164-166: Stack-allocated Waiter correctly separates concerns.

The Waiter is declared outside the loop, so it persists through potential loop iterations (e.g., when woken but another consumer grabbed the message first). The .init(&task.awaitable) ties the waiter's wake callback back to the task.

This is the fix for the double-list bug: waiter.wait_node goes into the channel's queue, while task.awaitable.wait_node remains available for the runtime scheduler.


196-203: Enqueue and cancellation cleanup use the waiter's node.

Line 196 pushes waiter.wait_node (not task.awaitable.wait_node), and line 203 removes it on cancellation. The symmetry is correct.

src/sync/Mutex.zig (2)

81-89: Waiter pattern applied to Mutex.lock slow path.

The waiter is created before calling pushOrTransition, ensuring the stack-allocated waiter.wait_node is valid for the entire operation. If the mutex transitions to unlocked (line 90-93), we bail out early and never actually use the waiter for waiting - that's fine, the node was never enqueued.


98-105: Cancellation cleanup uses waiter.wait_node.

On error.Canceled, we attempt to remove waiter.wait_node from the queue. If removal fails (we already inherited the lock), we unlock. The logic is sound.

src/sync/ResetEvent.zig (2)

128-130: Waiter pattern correctly applied.

The stack-allocated Waiter cleanly separates the operation's wait node from the task's wait node. The wait_node is pushed/removed from the queue correctly, preventing the double-list assertion failure.

Also applies to: 136-136, 146-146


375-406: Good test coverage for the cancel-while-waiting scenario.

This test directly exercises the bug being fixed. One note: the waiter_task.cancel(runtime) call on line 403 is redundant since defer waiter_task.cancel(runtime) on line 393 will execute regardless. Not a bug, just slightly duplicative.

src/sync/channel.zig (2)

106-108: Waiter pattern applied correctly to receive path.

The stack-allocated waiter decouples the channel's wait queue from the task's scheduling. Cancellation handling properly removes waiter.wait_node and forwards the wake to another receiver when necessary.

Also applies to: 135-135, 142-142


201-203: Waiter pattern applied correctly to send path.

Same pattern as receive - local Waiter with proper queue removal and wake forwarding on cancellation.

Also applies to: 229-229, 236-236

src/runtime/awaitable.zig (1)

56-56: Runtime safety check expansion is intentional.

The switch from builtin.mode == .Debug to std.debug.runtime_safety enables this debug field in ReleaseSafe builds. Based on learnings, the in_list field historically used compile-time Debug mode. This change broadens coverage - verify this aligns with the project's safety guarantees expectations for ReleaseSafe builds.

src/runtime/WaitNode.zig (1)

4-4: Consistent with awaitable.zig change.

The std import is now required for std.debug.runtime_safety. Same rationale as awaitable.zig - broadens in_list debug field availability to ReleaseSafe builds.

Also applies to: 13-13

src/sync/Notify.zig (2)

113-115: Waiter pattern with proper wake forwarding.

The implementation correctly forwards the wake to another waiter when cancellation removes a node that was already popped by signal(). This prevents signal loss - good attention to the stateless nature of Notify.

Also applies to: 120-120, 126-136


155-157: timedWait follows the same pattern.

Consistent with wait() - creates local Waiter and handles cancellation with proper wake forwarding.

Also applies to: 167-167, 173-185

src/signal.zig (2)

285-287: Waiter pattern applied correctly.

Signal's cancellation path just removes from queue without forwarding wake - this is correct because signalHandlerUnix/consoleCtrlHandlerWindows broadcast to all matching handlers. No signal loss risk here.

Also applies to: 292-292, 298-298


328-330: timedWait follows the same pattern.

Consistent application - local Waiter with queue operations on waiter.wait_node.

Also applies to: 335-335, 346-346

src/sync/common.zig (1)

26-45: Clean abstraction for the double-list bug fix.

The Waiter struct is minimal and does exactly what's needed: holds a separate WaitNode that delegates wake to the parent task's awaitable. The use of .maybe_remote in resumeTask is correct since the wake can originate from signal handlers or other threads.

The @fieldParentPtr pattern is idiomatic Zig for intrusive data structures.

src/sync/Condition.zig (3)

63-63: LGTM!

Clean import of the new Waiter type from the sync common module.


95-102: Solid fix for the double-list bug.

Stack-allocated Waiter with its own wait_node keeps the operation's queue membership separate from the task's runtime scheduling. The waiter lives on the stack for the duration of the blocking call, so lifetime is correct.


168-174: Consistent with wait() implementation.

Same stack-allocated waiter pattern applied to the timed variant. The timeout logic remains intact, just operating on the decoupled wait node.

src/utils/wait_queue.zig (6)

70-73: Runtime safety gating now covers ReleaseSafe builds.

This changes from builtin.mode == .Debug to std.debug.runtime_safety, meaning these assertions fire in both Debug and ReleaseSafe modes. This aligns with the PR's stated goal. Note: this deviates from a past learning that suggested keeping in_list debug-only, but the PR explicitly updates this behavior for broader coverage. Based on learnings, you may want to confirm this is the intended direction.


93-96: Consistent safety check pattern.

Same std.debug.runtime_safety gating applied to pop operation.


346-349: WaitQueue follows the same pattern.

All WaitQueue operations (pushInternal, pop, remove, popOrTransition) now use std.debug.runtime_safety for in_list tracking. Consistent with SimpleWaitQueue changes.


775-778: CompactWaitQueue completes the pattern.

Same std.debug.runtime_safety gating applied across all CompactWaitQueue operations. All three queue implementations are now consistent.


783-788: Tail self-reference for single-item queue is correct.

When the queue transitions from empty to one item, storing the item's own pointer in userdata correctly establishes it as both head and tail. Good use of the comment to clarify intent.


861-864: Pop operation safety checks are consistent.

Standard pattern: assert item is in list, then mark as removed.

src/runtime/group.zig (1)

170-170: GroupNode aligns with updated queue safety checks.

The in_list field now uses std.debug.runtime_safety gating, consistent with the changes in wait_queue.zig. Since GroupNode is used with CompactWaitQueue, this ensures the field types match the queue's expectations in all build modes.


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.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

No issues found across 17 files

@lalinsky
lalinsky merged commit c9661a3 into main Jan 8, 2026
@lalinsky
lalinsky deleted the fix-waiter-pattern branch January 8, 2026 16:17
This was referenced Jan 9, 2026
@coderabbitai coderabbitai Bot mentioned this pull request Apr 17, 2026
1 of 4 tasks
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