Repository navigation
Add CompactWaitQueue - 8-byte space-optimized wait queue - #146
Conversation
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
WalkthroughThe PR adds a new Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes
Possibly related PRs
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches🧪 Generate unit tests (beta)
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: 0
🧹 Nitpick comments (3)
src/utils/wait_queue.zig (3)
541-597: popOrTransition docs don’t match implementation anymoreThe 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 solidThe 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/prevanduserdataare guarded byacquireMutationLock()and published with a.releasestore/fetchAnd, mirroring WaitQueue’s ordering guarantees. That keeps the non‑atomic tail inuserdatasafe.pushInternalcorrectly handles the “first waiter” case by making the node self‑point as tail, and the multi‑waiter case by deriving tail fromhead.userdata, appending, then updatinghead.userdatato the new tail.pop,remove, andpopOrTransitionall preserve the invariant “if head is a pointer,head.userdatapoints to the tail”:
- pop/popOrTransition transfer
old_head.userdatatonext.userdatawhen there is a successor.- remove head hands
head.userdatato the new head, remove tail updateshead.userdatato the new tail, and middle removals leave it untouched.- Single-element cases transition to a sentinel and never read
userdatain 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) *Tandfn tailPtr(head: *T) *Tto 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 cancellationThe extended WaitQueue tests exercise:
- Basic state transitions and
.emptyinit.- Double-remove behaviour using pointer-based membership checks rather than
in_list.- Concurrent push/pop and concurrent remove during modifications.
popOrTransitionunder 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
📒 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 casesThe new SimpleWaitQueue tests hit the basics (empty, FIFO push/pop), targeted remove behaviour (middle/head/tail, double remove), and
.emptyinitialization. That matches the implementation’s pointer-based membership checks andin_listdebug 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 trackingThe 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.userdatais updated to the new tail, and removing the last tail folds back to self.- Head removal tests check that
userdatais 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 coverageThe 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
sentinel1and 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 appropriateThe heavy-contention stress test where each thread pushes its own items and then interleaves pops and removes against a shared
CompactWaitQueueis a nice mirror of the WaitQueue stress test:
- Per-thread atomic counters avoid data races when aggregating results.
- The total
popped + removed + remainingequalstotal_itemsassertion checks for both lost and double-processed nodes.- Final state check against
Queue.State.sentinel0confirms the queue is quiescent.No issues here; this should reliably shake out lock-handling bugs.
Summary
Implements CompactWaitQueue, a space-efficient variant of WaitQueue that uses only 8 bytes by storing the tail pointer in the head node's
userdatafield.This is designed for implementing
std.Thread.Mutexandstd.Thread.Condinterfaces that only provide 64 bits of state.Key Features
.acquire/.releaseproperly synchronizedTechnical Details
The implementation maintains the invariant: when
headis a pointer (queue non-empty),head_node.userdatacontains the tail pointer.Critical operations:
item.userdata = @intFromPtr(item), subsequent appends updatehead.userdatanext.userdata = old_head.userdatahead.userdatawhen removing tail, transfers tail when removing headAll modifications to
userdataand the doubly-linked list happen under the mutation lock, ensuring proper synchronization.Test Coverage
Added 11 comprehensive tests matching WaitQueue's coverage:
All 169 tests pass (existing + new tests).
Test Plan
./check.sh- all tests pass