Skip to content

Add CompactConcurrentQueue (8-byte variant) with benchmarks - #58

Merged
lalinsky merged 2 commits into
mainfrom
claude/issue-57-20251019-0756
Oct 19, 2025
Merged

lalinsky merged 2 commits into
mainfrom
claude/issue-57-20251019-0756

Conversation

@lalinsky

@lalinsky lalinsky commented Oct 19, 2025 •

Copy link
Copy Markdown
Owner

Summary

Implements a space-optimized version of ConcurrentQueue that fits in 8 bytes for compatibility with std.Io.Mutex and Condition 64-bit state.

Key features:

  • Queue structure: 8 bytes (only atomic head pointer)
  • Tail pointer stored in head node's tail field
  • Same O(1) operations as standard ConcurrentQueue
  • Comprehensive tests and benchmark suite

Trade-offs:

  • ✅ Fits in 64-bit atomic word
  • ✅ Maintains all functionality
  • ❌ Each node 8 bytes larger (tail field)
  • ❌ Slightly more complex operations

Closes #57


Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Introduced CompactConcurrentQueue — an 8-byte, memory-efficient concurrent queue.
    • Added comprehensive benchmark suite with single- and multi-threaded performance tests.
  • Updates

    • Synchronization primitives (mutexes/conditions) now use the compact queue to reduce per-waiter memory overhead.
  • Chores

    • Exposed ConcurrentQueue and CompactConcurrentQueue in the public API.

Implements a space-optimized version of ConcurrentQueue that fits in
8 bytes by storing only the head pointer. The tail pointer is stored
in the head node itself, rather than as a separate field.

Key features:
- Queue structure: 8 bytes (only atomic head pointer)
- Compatible with std.Io.Mutex/Condition 64-bit state
- Same O(1) operations as standard ConcurrentQueue
- Nodes require additional 'tail' field (8 bytes per node)

Trade-offs:
+ Fits in 64-bit atomic word
+ Maintains all functionality of standard queue
- Each node 8 bytes larger (tail field mostly unused)
- Slightly more complex operations (tail copying on updates)

Includes comprehensive tests and benchmark suite comparing both
implementations for single-threaded and concurrent scenarios.

Co-authored-by: Lukáš Lalinský <[email protected]>
@coderabbitai

coderabbitai Bot commented Oct 19, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds an 8-byte CompactConcurrentQueue implementation, updates sync primitives to use it (and adds a tail field to WaitNode), exposes it via the public zio API, and adds a benchmark suite and build entry to compare ConcurrentQueue vs CompactConcurrentQueue in single- and multi-threaded scenarios.

Changes

Cohort / File(s) Summary
New Benchmark Suite
benchmarks/concurrent_queue_bench.zig
Adds benchmarks measuring single-threaded and multi-threaded performance for ConcurrentQueue and CompactConcurrentQueue, plus formatting and orchestration helpers and a pub fn main() entry for the bench.
Build Configuration
build.zig
Registers the new benchmark: { .name = "concurrent-queue", .file = "benchmarks/concurrent_queue_bench.zig" }.
Compact Queue Implementation
src/utils/concurrent_queue.zig
Introduces CompactConcurrentQueue(comptime T: type) (8-byte header) with sentinel state encoding, mutation-lock bit semantics, push/pop/remove/popOrTransition logic, state transition helpers, and extensive concurrent and stress tests.
Public API Export
src/zio.zig
Re-exports ConcurrentQueue and new CompactConcurrentQueue from utils/concurrent_queue.zig as public bindings.
Sync primitives & WaitNode
src/core/WaitNode.zig, src/sync/Condition.zig, src/sync/Mutex.zig
Adds tail: ?*WaitNode to WaitNode; replaces internal uses of ConcurrentQueue(WaitNode) with CompactConcurrentQueue(WaitNode) and updates associated state/type aliases and fields.

Sequence Diagram(s)

sequenceDiagram
    participant Caller as Caller (bench/test)
    participant Q as CompactConcurrentQueue
    participant Worker as Worker Thread
    participant Head as Head Node Memory

    Note over Caller,Q: Setup
    Caller->>Q: initWithState(.sentinel1)

    Note over Worker,Q: Concurrent push phase (many threads)
    par
      Worker->>Q: acquireMutationLock()    %% spin and CAS head pointer with mutation bit
      Worker->>Head: append item to head.tail list
      Worker->>Q: releaseMutationLock()
    and
      Worker->>Q: push(item)  %% high-level
    end

    Note over Caller,Q: Pop/Drain phase (single thread)
    Caller->>Q: pop()
    Q->>Head: read head + next
    Q->>Q: possibly transition sentinel states / carry tail
    Q-->>Caller: return item / null
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

🐰
A tiny queue, eight bytes tight,
Tail tucked in the head’s small room,
Threads hop in from left and right,
Benchmarks hum — no sign of gloom,
I nibble code and bounce with zoom!

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title "Add CompactConcurrentQueue (8-byte variant) with benchmarks" directly and accurately summarizes the primary change in the changeset. It is specific and clear, identifying exactly what is being added (the CompactConcurrentQueue), its key distinguishing feature (8-byte variant), and that benchmarks are included. The title is concise and avoids vague terms, making it easy for teammates to understand the core modification from a quick scan of the history.
Linked Issues Check ✅ Passed The PR fully addresses all coding requirements from issue #57. It implements CompactConcurrentQueue with an 8-byte header (storing only the head pointer as an atomic usize), embeds the tail pointer in the first node's tail field (adding the field to WaitNode), maintains O(1) operations with proper state management, and integrates the variant into Mutex and Condition as requested. Comprehensive tests and benchmarks are included. All primary objectives for creating a 64-bit-compatible queue variant are successfully delivered.
Out of Scope Changes Check ✅ Passed All changes are directly in scope and necessary for implementing the CompactConcurrentQueue variant and achieving the objectives outlined in issue #57. The changes include the core implementation, required field additions to support the compact design, public API exports, benchmarks (explicitly mentioned in the PR title), and integration into Mutex and Condition (per the collaborator's request). No unrelated modifications or tangential changes are present.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch claude/issue-57-20251019-0756

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 418c747 and 3f8b55a.

📒 Files selected for processing (3)
  • src/core/WaitNode.zig (1 hunks)
  • src/sync/Condition.zig (2 hunks)
  • src/sync/Mutex.zig (1 hunks)
⏰ 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 (7)
src/core/WaitNode.zig (1)

10-10: LGTM! The tail field enables the 8-byte queue header.

The addition of the tail field is a straightforward change that enables CompactConcurrentQueue to store the tail pointer in the head node rather than in the queue header. This increases every WaitNode by 8 bytes, which is the documented trade-off to achieve an 8-byte queue header for std.Io compatibility.

src/sync/Condition.zig (3)

57-57: Import updated correctly.

The import change to CompactConcurrentQueue aligns with the PR objective to use the 8-byte variant for std.Io compatibility.


60-60: Queue type updated with appropriate initialization.

The field type correctly switches to CompactConcurrentQueue(WaitNode) with .empty initialization, which is appropriate for a condition variable's wait queue (starts empty with no special sentinel state needed).


127-127: TimeoutContext type correctly updated.

The internal TimeoutContext struct's field type is properly updated to match the new queue type, maintaining consistency throughout the timeout handling logic.

src/sync/Mutex.zig (3)

31-31: Import updated correctly.

The import change to CompactConcurrentQueue is consistent with the PR's goal to adopt the 8-byte queue variant.


39-39: Queue field correctly migrated with sentinel state preserved.

The queue field is properly updated to CompactConcurrentQueue(WaitNode) while preserving the .initWithState(.sentinel1) initialization pattern. This maintains the unlocked initial state and the sentinel-based encoding that distinguishes locked/unlocked states from pointer-based wait queues.


41-41: State alias updated appropriately.

The State type alias is correctly updated to reference CompactConcurrentQueue(WaitNode).State, maintaining type consistency for the sentinel constants and state operations used throughout the mutex implementation.


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 (4)
src/utils/concurrent_queue.zig (3)

823-872: Add compile-time validation for T’s fields and alignment

Enforce presence of next/prev/tail and require at least 4‑byte alignment to guarantee two tag bits. Prevents UB in release builds.

 pub fn CompactConcurrentQueue(comptime T: type) type {
     return struct {
         const Self = @This();
+        const meta = std.meta;
+        comptime {
+            // Require structural fields
+            if (meta.fieldIndex(T, "next") == null or
+                meta.fieldIndex(T, "prev") == null or
+                meta.fieldIndex(T, "tail") == null)
+            {
+                @compileError("CompactConcurrentQueue(T) requires fields: next, prev, tail");
+            }
+            // Require at least 2 tag bits => 4-byte alignment
+            if (@alignOf(T) < 4) {
+                @compileError("CompactConcurrentQueue(T) requires @alignOf(T) >= 4 (two tag bits).");
+            }
+        }

992-1052: Optional: strengthen debug invariants in remove()

Consider asserting item.in_list in Debug to catch accidental double-removals earlier (tests already cover behavior). Purely debug-time.

-            if (builtin.mode == .Debug) {
-                item.in_list = false;
-            }
+            if (builtin.mode == .Debug) {
+                std.debug.assert(item.in_list);
+                item.in_list = false;
+            }

1147-1149: Make size assertion portable across 32/64-bit targets

On 32‑bit, the queue will be 4 bytes. Gate by pointer size.

-    // The whole point: verify it's only 8 bytes!
-    try testing.expectEqual(8, @sizeOf(Queue));
+    if (@sizeOf(usize) == 8) {
+        try testing.expectEqual(8, @sizeOf(Queue));
+    } else {
+        try testing.expectEqual(@sizeOf(usize), @sizeOf(Queue));
+    }
benchmarks/concurrent_queue_bench.zig (1)

278-286: Optional: scale threads with CPU count and allow overrides

Improves portability and out-of-the-box relevance.

-    const num_threads = 4;
+    const num_threads = std.math.max(1, std.Thread.getCpuCount() orelse 4);
     const ops_per_thread = 2_500;
-    const concurrent_iterations = 50;
+    const concurrent_iterations = 50;
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 94bbd99 and 418c747.

📒 Files selected for processing (4)
  • benchmarks/concurrent_queue_bench.zig (1 hunks)
  • build.zig (1 hunks)
  • src/utils/concurrent_queue.zig (1 hunks)
  • src/zio.zig (1 hunks)
🔇 Additional comments (4)
src/utils/concurrent_queue.zig (1)

924-955: push path looks correct with lock handoff via store(.release)

Initialization, tail carry, and unlock semantics are sound. Nice.

build.zig (1)

48-48: LGTM: benchmark wired into build graph

Entry is correct; integrates with existing loop and zio import.

src/zio.zig (1)

37-41: LGTM: clean re-exports

Public surface exposes both variants without breaking existing imports.

benchmarks/concurrent_queue_bench.zig (1)

1-86: Bench logic and accounting look solid

Push/pop counts validated; timing aggregation is reasonable.

Also applies to: 88-186, 198-251

Comment thread src/utils/concurrent_queue.zig Resolved
@lalinsky

Copy link
Copy Markdown
Owner Author

@claude use this variant in mutex and condition

@claude

claude Bot commented Oct 19, 2025 •

Copy link
Copy Markdown

Claude finished @lalinsky's task —— View job


Completed: Integrated CompactConcurrentQueue into Mutex and Condition

Changes Made

  • Updated src/sync/Mutex.zig:31 to use CompactConcurrentQueue(WaitNode)
  • Updated src/sync/Condition.zig:57,127 to use CompactConcurrentQueue(WaitNode)
  • Added tail field to src/core/WaitNode.zig:10 for CompactConcurrentQueue compatibility

Both Mutex and Condition primitives now use the 8-byte CompactConcurrentQueue variant, fitting within the 64-bit state requirement for std.Io.Mutex and Condition compatibility as intended.

Test Results

All 108 tests passed successfully ✓

Commit

Pushed commit 3f8b55a with the integration changes.


Branch: claude/issue-57-20251019-0756

- Replace ConcurrentQueue with CompactConcurrentQueue in Mutex and Condition
- Add tail field to WaitNode for CompactConcurrentQueue compatibility
- Both primitives now fit within 64-bit state requirement

Co-authored-by: Lukáš Lalinský <[email protected]>
@lalinsky
lalinsky merged commit 382bbd0 into main Oct 19, 2025
@lalinsky
lalinsky deleted the claude/issue-57-20251019-0756 branch December 16, 2025 19:16
lalinsky added a commit that referenced this pull request Jan 6, 2026
* Add file_stat operation

Add FileStat and FileStatPath operations for retrieving file metadata:
- FileStat: stat by file descriptor (fd-based)
- FileStatPath: stat by path relative to directory

Returns FileStatInfo struct with fields: inode, size, mode, kind,
atime, mtime, ctime (timestamps in nanoseconds).

io_uring backend uses native statx() syscall; other backends use
thread pool fallback with blocking fstat()/fstatat().

* Fix macOS build: use atime/mtime/ctime methods for cross-platform Stat access

* Use statx on Linux for file stat operations

* Fix Windows build: bitcast inode to i64

* Use statx on Linux for fsize as well

* Merge FileStat and FileStatPath into single operation

Consolidate the two stat operations into one by making the path parameter
optional (null = stat fd itself, non-null = stat path relative to fd).

API changes:
- FileStat.init(fd) -> FileStat.init(fd, null)
- FileStatPath.init(dir, path) -> FileStat.init(dir, path)
- FileStatPath type removed

* Fix memory leak when stat path is empty string
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.

8 byte large concurrent queue

1 participant