Skip to content

Simplify runIo and consolidate IO utilities - #220

Merged
lalinsky merged 4 commits into
mainfrom
simplify-runio
Jan 21, 2026
Merged

lalinsky merged 4 commits into
mainfrom
simplify-runio

Conversation

@lalinsky

Copy link
Copy Markdown
Owner

Summary

  • Refactor runIo to use a single loop with canceling flag instead of separate cancelIo/waitForIo functions
  • Add Completion.isCompleted() method that checks both cancel_state.completed and state == .dead
  • Fix race condition by setting preparing_to_wait before loop.add()
  • Handle edge case where IO completes during cancellation by calling task.recancel() to preserve the cancel for the next checkpoint
  • Handle IO completing successfully despite cancel request by checking c.err
  • Move fillBuf helper to src/utils/writer.zig
  • Move runIo to common.zig and delete io.zig
  • Remove unused functions: cancelIo, waitForIo, runIoMulti, timedWaitForIo

Test plan

  • All 294 existing tests pass

- Refactor runIo to use a single loop with canceling flag instead of
  separate cancelIo/waitForIo functions
- Add Completion.isCompleted() method that checks both cancel_state.completed
  and state == .dead
- Fix race condition by setting preparing_to_wait before loop.add()
- Handle edge case where IO completes during cancellation by calling
  task.recancel() to preserve the cancel for the next checkpoint
- Use beginShield/endShield while waiting for cancel to complete
- Remove unused functions: cancelIo, waitForIo, runIoMulti, timedWaitForIo,
  MultiIoContext, multiIoCallback
- Remove unused imports: Executor, meta, Timeoutable, Duration, AutoCancel
- Inline genericCallback as anonymous struct function
- Update imports in fs.zig, net.zig, runtime.zig
- Delete now-empty io.zig
@coderabbitai

coderabbitai Bot commented Jan 21, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This PR reorganizes I/O orchestration by moving runIo from io.zig to common.zig with a new implementation using completion contexts and cancellation coordination. In parallel, fillBuf moves to utils/writer.zig. The entire io.zig module is deleted, with import statements updated across the codebase accordingly.

Changes

Cohort / File(s) Summary
Core I/O relocation
src/common.zig
Adds new runIo(rt, c) function (+69 lines) implementing runtime-assisted I/O orchestration with completion callbacks, atomic completion flags, cancellation shielding, and task coordination via rt.getCurrentTask(), task.recancel(), and task.wake(). Includes logic for shield regions guarding cancellation during I/O waits and error handling for Canceled states.
I/O module removal
src/io.zig
Entire module deleted (-337 lines). Removes public functions genericCallback, cancelIo, waitForIo, runIo, runIoMulti, timedWaitForIo, fillBuf, and MultiIoContext struct, along with associated tests and helper logic.
Buffer utility extraction
src/utils/writer.zig
New fillBuf function (+158 lines) that constructs iovec-like buffers with header, data slices, and splatting patterns. Handles zero/single/multi-byte splat cases with branching logic for pattern repetition across multiple iovecs. Includes comprehensive unit tests for edge cases and large splat behavior.
Import path updates
src/fs.zig, src/net.zig, src/runtime.zig
Each file updates module imports: runIo from io.zig → common.zig (+1/-1 line per file), and in fs/net, fillBuf from io.zig → utils/writer.zig (+1/-1 additional). No logic changes.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

I/O danced from io.zig's walls,
Now common.zig answers the calls,
Splat buffers leap to writer's hall,
Shield and cancel, one and all— 🛡️✨
Old bonds severed, new paths rise tall.

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main refactoring: simplifying runIo and consolidating IO utilities into fewer files.
Description check ✅ Passed The description directly relates to the changeset, detailing specific refactoring steps including moving runIo to common.zig, moving fillBuf to utils/writer.zig, removing io.zig, and handling race conditions.
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 simplify-runio

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

🤖 Fix all issues with AI agents
In `@src/ev/completion.zig`:
- Around line 298-300: isCompleted currently does an acquire load of
Completion.cancel_state and then reads Completion.state non-atomically, which
can see cancel_state.completed=true before state is updated to .dead (race
between finishCompletion's .acq_rel cmpxchg and the later write to state). Fix
by making state an atomic (e.g., atomic enum/int) and use matching ordering
(acquire in isCompleted, release in finishCompletion when writing .dead), or
reorder finishCompletion so state = .dead is written before performing the
.acq_rel cmpxchg that sets completed=true; update references to
Completion.state, finishCompletion, and cancel_state/cmpxchg accordingly.
🧹 Nitpick comments (1)
src/utils/writer.zig (1)

17-83: Optional: guard the single‑byte splat path when splat_buffer is empty.

If a caller ever passes a zero‑length buffer, the single‑byte path can emit zero‑length slices and stall progress. A small fallback keeps it robust.

Suggested guard for empty splat_buffer
-            1 => {
-                const memset_len = `@min`(splat_buffer.len, splat);
-                const buf = splat_buffer[0..memset_len];
-                `@memset`(buf, pattern[0]);
-                if (len < max_len) {
-                    out[len] = buf;
-                    len += 1;
-                }
-                var remaining_splat = splat - buf.len;
-                while (remaining_splat > splat_buffer.len and len < max_len) {
-                    out[len] = splat_buffer;
-                    len += 1;
-                    remaining_splat -= splat_buffer.len;
-                }
-                if (remaining_splat > 0 and len < max_len) {
-                    out[len] = splat_buffer[0..remaining_splat];
-                    len += 1;
-                }
-            },
+            1 => {
+                if (splat_buffer.len == 0) {
+                    var i: usize = 0;
+                    while (i < splat and len < max_len) : (i += 1) {
+                        out[len] = pattern;
+                        len += 1;
+                    }
+                } else {
+                    const memset_len = `@min`(splat_buffer.len, splat);
+                    const buf = splat_buffer[0..memset_len];
+                    `@memset`(buf, pattern[0]);
+                    if (len < max_len) {
+                        out[len] = buf;
+                        len += 1;
+                    }
+                    var remaining_splat = splat - buf.len;
+                    while (remaining_splat > splat_buffer.len and len < max_len) {
+                        out[len] = splat_buffer;
+                        len += 1;
+                        remaining_splat -= splat_buffer.len;
+                    }
+                    if (remaining_splat > 0 and len < max_len) {
+                        out[len] = splat_buffer[0..remaining_splat];
+                        len += 1;
+                    }
+                }
+            },

Comment thread src/ev/completion.zig Resolved
Replace racy Completion.isCompleted() with local atomic bool in runIo.
The callback sets the bool before waking the task, giving us a
race-free way to check if our callback ran.
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