Skip to content

Add CompactWaitQueue - 8-byte space-optimized wait queue - #146

Merged
lalinsky merged 1 commit into
mainfrom
compact-wait-queue
Nov 16, 2025
Merged

lalinsky merged 1 commit into
mainfrom
compact-wait-queue

Conversation

@lalinsky

Copy link
Copy Markdown
Owner

Summary

Implements CompactWaitQueue, a space-efficient variant of WaitQueue that uses only 8 bytes by storing the tail pointer in the head node's userdata field.

This is designed for implementing std.Thread.Mutex and std.Thread.Cond interfaces that only provide 64 bits of state.

Key Features

  • 8 bytes total: Single atomic head pointer, tail stored in head_node.userdata
  • Same semantics as WaitQueue: Tagged pointers with sentinel states + mutation lock
  • O(1) operations: push, pop, remove all constant time
  • Thread-safe: Full concurrent access via mutation spinlock
  • Sound memory ordering: .acquire/.release properly synchronized

Technical Details

The implementation maintains the invariant: when head is a pointer (queue non-empty), head_node.userdata contains the tail pointer.

Critical operations:

  • push: First item sets item.userdata = @intFromPtr(item), subsequent appends update head.userdata
  • pop: Transfers tail pointer from old head to new head: next.userdata = old_head.userdata
  • remove: Updates head.userdata when removing tail, transfers tail when removing head

All modifications to userdata and the doubly-linked list happen under the mutation lock, ensuring proper synchronization.

Test Coverage

Added 11 comprehensive tests matching WaitQueue's coverage:

  • ✅ Basic operations (push/pop/remove)
  • ✅ State transitions
  • ✅ Tail tracking verification
  • ✅ Double-remove prevention
  • ✅ Concurrent push and pop (4 threads × 100 items)
  • ✅ Concurrent modifications (3 threads racing)
  • ✅ popOrTransition with concurrent removals (500 items)
  • ✅ Heavy contention stress test (8 threads × 200 items)

All 169 tests pass (existing + new tests).

Test Plan

  • Run ./check.sh - all tests pass
  • Verify thread-safety with concurrent stress tests
  • Verify tail tracking correctness in all edge cases
  • Verify double-remove prevention works correctly

Implements a space-efficient variant of WaitQueue that uses only 8 bytes
by storing the tail pointer in the head node's userdata field. This is
designed for implementing std.Thread.Mutex and std.Thread.Cond interfaces
that only provide 64 bits of state.

Key features:
- Single atomic head pointer (8 bytes total)
- Tail stored in head_node.userdata when queue is non-empty
- Same tagged pointer scheme as WaitQueue (sentinels + mutation lock)
- O(1) push, pop, and remove operations
- Full thread-safety with mutation spinlock

Memory ordering is carefully maintained:
- acquireMutationLock() uses .acquire to synchronize with prior releases
- All modifications to userdata and doubly-linked list happen under lock
- Tail pointer transfers correctly during head removal and tail removal

Includes comprehensive test coverage:
- Basic operations (push/pop/remove)
- State transitions
- Tail tracking verification
- Double-remove prevention
- Concurrent operations (push/pop/remove with multiple threads)
- Heavy contention stress testing
@coderabbitai

coderabbitai Bot commented Nov 16, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

The PR adds a new CompactWaitQueue(T) type—an 8-byte wait queue variant that stores the tail pointer in the head node's userdata field. Includes state machine logic, atomic operations for initialization, state transitions, mutation locking, and queue operations (push, pop, remove). Tests cover the new variant and concurrent scenarios.

Changes

Cohort / File(s) Summary
CompactWaitQueue implementation
src/utils/wait_queue.zig
Introduces new public CompactWaitQueue(T) type with 8-byte footprint. Adds state machine with sentinel and pointer encodings, atomic state transitions, mutation locking (acquire/release), and core queue operations (push, pushUnless, pushOrTransition, pop, remove, popOrTransition). Tail pointer stored in head.userdata. Updates documentation and extends test coverage for concurrent operations and state machine transitions.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • State machine logic: Verify correctness of sentinel-based state encodings and atomic transitions—particularly edge cases during concurrent push/pop operations.
  • Tail pointer management via userdata: Ensure head.userdata correctly tracks tail across all queue operations and handles the compact 8-byte encoding without data loss.
  • Atomic operations and synchronization: Confirm acquire/release semantics in mutation locking and state transitions prevent race conditions.
  • New public API surface: Review all 15+ public methods for consistent behavior, proper error handling in pushUnless and popOrTransition variants, and alignment with existing queue semantics.

Possibly related PRs

Poem

🧵 Eight bytes packed tight, a tail in disguise,
Queue operations dance without compromise,
Atomic transitions waltz through the state,
Compact and clever—efficiency awaits. ✨

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title directly and clearly summarizes the main change—adding a new 8-byte space-optimized wait queue variant named CompactWaitQueue.
Description check ✅ Passed The description is comprehensive and directly related to the changeset, explaining the CompactWaitQueue implementation, design rationale, technical details, and test coverage.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch compact-wait-queue

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: 0

🧹 Nitpick comments (3)
src/utils/wait_queue.zig (3)

541-597: popOrTransition docs don’t match implementation anymore

The comment says “retrying until success or queue is empty” and mentions a loop, but the implementation executes a single pop/transition attempt per call. Behaviour is fine and your tests match the current semantics, but the doc should be tightened to describe the single-shot behaviour (or the function should actually loop, if that’s still the intent).


601-990: CompactWaitQueue core design and concurrency semantics look solid

The 8‑byte variant cleanly reuses the WaitQueue state machine and mutation lock, while routing all tail management through head_node.userdata. A few notes:

  • All writes to next/prev and userdata are guarded by acquireMutationLock() and published with a .release store/fetchAnd, mirroring WaitQueue’s ordering guarantees. That keeps the non‑atomic tail in userdata safe.
  • pushInternal correctly handles the “first waiter” case by making the node self‑point as tail, and the multi‑waiter case by deriving tail from head.userdata, appending, then updating head.userdata to the new tail.
  • pop, remove, and popOrTransition all preserve the invariant “if head is a pointer, head.userdata points to the tail”:
    • pop/popOrTransition transfer old_head.userdata to next.userdata when there is a successor.
    • remove head hands head.userdata to the new head, remove tail updates head.userdata to the new tail, and middle removals leave it untouched.
    • Single-element cases transition to a sentinel and never read userdata in empty states.
  • Lock release paths are complete: empty/sentinel paths use releaseMutationLock(), all pointer paths drop the mutation bit via .store(.release) in the same way as WaitQueue.

If you want to go one step further, you could factor small helpers like fn headPtr(state: State) *T and fn tailPtr(head: *T) *T to centralize the pointer/int casts and make future tweaks to the encoding less error‑prone, but the current code is readable and correct as is.


1136-1569: WaitQueue test suite is in good shape, especially around contention and cancellation

The extended WaitQueue tests exercise:

  • Basic state transitions and .empty init.
  • Double-remove behaviour using pointer-based membership checks rather than in_list.
  • Concurrent push/pop and concurrent remove during modifications.
  • popOrTransition under concurrent removals.
  • A stress test where all threads both push and race pop/remove under heavy contention.

These align with the internal design (mutation spinlock, non-atomic tail) and should make regressions in the state machine or lock handling obvious. Only nit is the popOrTransition doc mismatch mentioned earlier; the tests themselves look appropriate.

📜 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 dc6a76c and 647c3ef.

📒 Files selected for processing (1)
  • src/utils/wait_queue.zig (7 hunks)
🧰 Additional context used
🧠 Learnings (3)
📚 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/utils/wait_queue.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/utils/wait_queue.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/utils/wait_queue.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). (1)
  • GitHub Check: test (windows-latest)
🔇 Additional comments (4)
src/utils/wait_queue.zig (4)

992-1134: SimpleWaitQueue tests cover the right edge cases

The new SimpleWaitQueue tests hit the basics (empty, FIFO push/pop), targeted remove behaviour (middle/head/tail, double remove), and .empty initialization. That matches the implementation’s pointer-based membership checks and in_list debug semantics, and should catch the usual off‑by‑one or head/tail mishandling bugs.


1571-1811: CompactWaitQueue basic/tail/remove tests validate the userdata-based tail tracking

The basic, state-transition, .empty, tail-tracking, and remove tests for CompactWaitQueue do a good job of pinning the new invariants:

  • They confirm the single-element “head.userdata points to itself” rule, and that adding/removing elements correctly updates or transfers userdata.
  • Tail removal tests verify head.userdata is updated to the new tail, and removing the last tail folds back to self.
  • Head removal tests check that userdata is transferred to the new head.
  • The double-remove test matches the pointer-based membership semantics from WaitQueue.

This gives strong coverage for the new encoding, especially the subtle cases where head or tail moves.


1813-2018: Concurrent and popOrTransition tests for CompactWaitQueue mirror WaitQueue’s coverage

The concurrent push/pop, concurrent remove during modifications, and popOrTransition-with-removals tests for CompactWaitQueue closely mirror the WaitQueue variants:

  • Multiple producers pushing into a single consumer drain.
  • Three-thread scenario (producer, popper, remover) that verifies every item is either popped, removed, or drained, and that the queue ends in sentinel0.
  • popOrTransition under concurrent removals that checks the final sentinel is sentinel1 and that all nodes are accounted for.

Given the implementation shares the same locking/state pattern, this is exactly the sort of concurrency coverage you want for the new variant.


2020-2116: Heavy-contention stress test for CompactWaitQueue is appropriate

The heavy-contention stress test where each thread pushes its own items and then interleaves pops and removes against a shared CompactWaitQueue is a nice mirror of the WaitQueue stress test:

  • Per-thread atomic counters avoid data races when aggregating results.
  • The total popped + removed + remaining equals total_items assertion checks for both lost and double-processed nodes.
  • Final state check against Queue.State.sentinel0 confirms the queue is quiescent.

No issues here; this should reliably shake out lock-handling bugs.

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