Skip to content

Add ProcessWait for async child process waiting - #339

Merged
lalinsky merged 4 commits into
mainfrom
process-wait
Mar 11, 2026
Merged

lalinsky merged 4 commits into
mainfrom
process-wait

Conversation

@lalinsky

Copy link
Copy Markdown
Owner

Summary

  • Add ProcessWait completion type for asynchronously waiting on child process exit
  • Support all backends: io_uring, epoll, kqueue, iocp, poll
  • Use pidfd on Linux (io_uring/epoll), EVFILT_PROC on kqueue, thread pool on Windows/poll

Test plan

  • Tests pass on all platforms (Linux, macOS, FreeBSD, NetBSD, Windows)
  • Tests cover exit code 0, exit code 1, and signal termination

@coderabbitai

coderabbitai Bot commented Mar 10, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Rate limit exceeded

@claude[bot] has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 7 minutes and 46 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 912cf0fe-3710-4643-82e0-4ca3e9d1eee5

📥 Commits

Reviewing files that changed from the base of the PR and between f1bd9fb and 7db967b.

📒 Files selected for processing (1)
  • src/ev/backends/iocp.zig
📝 Walkthrough

Walkthrough

Adds a new ProcessWait operation and cross-platform process-wait handling across backends, wiring it into the loop, blocking/thread-pool, public API, OS bindings, and tests to observe child exit codes or termination signals.

Changes

Cohort / File(s) Summary
Core types & exports
src/ev/completion.zig, src/ev/root.zig
Add ProcessWait op/type, ExitStatus, ProcessHandle, and process_wait capability; export ProcessWait from root.
Common blocking/work helpers
src/ev/backends/common.zig, src/ev/blocking.zig
Add handleProcessWait (cross-platform wait logic) and processWaitWork; wire executeBlocking to call common.handleProcessWait for .process_wait.
Event loop integration
src/ev/loop.zig
Map .process_wait to common.processWaitWork in op dispatch so loop invokes the work path for process waits.
Backends: epoll & io_uring
src/ev/backends/epoll.zig, src/ev/backends/io_uring.zig
Enable .process_wait capability; add ProcessWaitData (pidfd / siginfo), submit & poll/SQE paths, decode exit vs signal, and cleanup pidfd.
Backends: kqueue
src/ev/backends/kqueue.zig
Add .process_wait via PROC kevent NOTE.EXIT, submit/kevent wiring, and waitpid-based result decoding.
Backends: iocp & poll
src/ev/backends/iocp.zig, src/ev/backends/poll.zig
IOCP: add Windows process-wait submit/callback/register logic and ProcessWaitData; Poll: mark .process_wait routed to thread-pool (unreachable in poll switch).
Event backend glue & capabilities
src/ev/backends/common.zig, src/ev/backends/...
Propagate process_wait capability across backend capability structs and related getHandle/submit/checkCompletion flows.
Tests
src/ev/test/process_wait.zig, src/ev/tests.zig
Add tests that spawn children and assert exit code 0/1 and signal-terminated behavior; register the test in suite.
Platform layer
src/os/windows.zig, src/os/root.zig
Add Windows wait APIs (WaitForSingleObject, GetExitCodeProcess, registration/unregistration functions and constants); change exported timespec binding to posix.timespec.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

🐣 A child process whispers, then folds,
The loop listens in cross‑platform holds,
Signals, codes, a tiny reported state,
Work queued, wait handled, completion innate,
One small op nailed — the event loop hums.

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Add ProcessWait for async child process waiting' directly and clearly describes the main change—a new ProcessWait completion type for asynchronous child process waiting, which aligns with the core objective across all file modifications.
Description check ✅ Passed The description is directly relevant, outlining the ProcessWait feature addition, backend support strategy, and test coverage across platforms, matching the actual changeset scope and objectives.
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 process-wait

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

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/ev/backends/common.zig`:
- Around line 694-695: The current blocking waits (Windows WaitForSingleObject
with INFINITE and POSIX waitid/waitpid) prevent the Work cancellation from being
observed; change the blocking calls in the thread-pool fallback (the code paths
around WaitForSingleObject/WAIT_OBJECT_0 and the POSIX waitid/waitpid blocks
referenced) to use a finite timeout loop (e.g., short-timeout
WaitForSingleObject or repeated waitpid(..., WNOHANG) / waitid with brief
sleeps) so the loop can periodically check the Work cancellation flag and retry
on EINTR; implement a small timeout/sleep interval, re-check cancellation each
iteration, and only break when the child has actually exited or the Work is
cancelled.

In `@src/ev/backends/kqueue.zig`:
- Around line 698-719: The process_wait branch currently treats any waitpid
error as error.Unexpected; modify the waitpid error handling (around
posix.system.waitpid in the .process_wait case handling ProcessWait) to inspect
the platform errno (posix.errno) and map ECHILD to error.ProcessNotFound,
otherwise call comp.setError(error.Unexpected) as before so kqueue matches the
epoll/io_uring semantics; keep the rest of the success path that decodes status
and calls comp.setResult(.process_wait, ...) unchanged.

In `@src/os/root.zig`:
- Line 20: The public alias change made in root.zig (pub const timespec =
posix.timespec) breaks nominal typing because syscalls use
posix.system.timespec; either revert the alias to posix.system.timespec or
update all syscall signatures and callers to use os.timespec consistently.
Concretely, restore pub const timespec = posix.system.timespec in
src/os/root.zig OR update every syscall prototype and users (examples: functions
in src/os/time.zig and src/os/fs.zig that reference posix.system.timespec, and
the public APIs exported from src/time.zig) to accept os.timespec and fix all
call sites to pass the new type. Ensure the chosen approach is applied across
syscall declarations and their callers in the same patch to keep types
consistent.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 1783b320-56b7-4a72-84ff-70d111269f0a

📥 Commits

Reviewing files that changed from the base of the PR and between d946751 and 7edc210.

📒 Files selected for processing (14)
  • src/ev/backends/common.zig
  • src/ev/backends/epoll.zig
  • src/ev/backends/io_uring.zig
  • src/ev/backends/iocp.zig
  • src/ev/backends/kqueue.zig
  • src/ev/backends/poll.zig
  • src/ev/blocking.zig
  • src/ev/completion.zig
  • src/ev/loop.zig
  • src/ev/root.zig
  • src/ev/test/process_wait.zig
  • src/ev/tests.zig
  • src/os/root.zig
  • src/os/windows.zig

Comment thread src/ev/backends/common.zig Resolved
Comment thread src/ev/backends/kqueue.zig Resolved
Comment thread src/os/root.zig Resolved
@lalinsky

Copy link
Copy Markdown
Owner Author

@claude we need to change the IOCP backend to use callback based approach, use wine to test it

@claude

claude Bot commented Mar 11, 2026 •

Copy link
Copy Markdown

Claude finished @lalinsky's task in 7m 19s —— View job


Implemented callback-based IOCP process_wait

  • Gather context
  • Read IOCP backend and related files
  • Understand current Windows API support
  • Add Windows APIs (RegisterWaitForSingleObject, UnregisterWaitEx, PostQueuedCompletionStatus) to windows.zig
  • Add ProcessWaitData struct and processWaitCallback to iocp.zig
  • Implement submitProcessWait in iocp.zig
  • Update submit and processCompletion switches in iocp.zig
  • Set process_wait = true in IOCP capabilities
  • Compiled successfully for x86_64-windows (Wine not available in environment)
  • Linux tests pass (10/10)
  • Pushed changes

Summary

The IOCP backend now uses a fully callback-based approach for process_wait:

  1. RegisterWaitForSingleObject registers a Windows thread-pool callback on the process HANDLE with WT_EXECUTEONLYONCE. No thread is blocked.
  2. When the process exits, Windows fires processWaitCallback from a thread-pool thread, which calls PostQueuedCompletionStatus to inject an IOCP completion packet using the completion's overlapped pointer.
  3. The IOCP event loop picks up the packet in processCompletion, calls UnregisterWaitEx to clean up the registration, and then GetExitCodeProcess to get the exit code.

New ProcessWaitData struct added to iocp.zig holds:

  • wait_handle — the registration handle (used for cleanup)
  • iocp — copy of the IOCP port handle (needed by the callback)

The process_wait capability is now true for the IOCP backend, so it goes through Backend.submit directly rather than the thread pool.
| Branch: process-wait

@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.

🧹 Nitpick comments (1)
src/ev/backends/kqueue.zig (1)

711-718: Exit status decoding differs from epoll when process is signaled.

When a process is terminated by a signal, there's no meaningful exit code. The epoll backend (from src/ev/backends/epoll.zig:786-789) explicitly sets .code = 0 in this case:

.code = if (si_code == CLD_EXITED) `@intCast`(si_status) else 0,

For consistent cross-platform behavior, kqueue should do the same:

Proposed fix for consistent exit status
             // Decode wait status (WEXITSTATUS and WTERMSIG equivalent)
             const ustatus: u32 = `@bitCast`(status);
             const exit_code: u8 = `@intCast`((ustatus >> 8) & 0xff);
             const signal_num: u8 = `@intCast`(ustatus & 0x7f);
             comp.setResult(.process_wait, .{
-                .code = exit_code,
+                .code = if (signal_num != 0) 0 else exit_code,
                 .signal = if (signal_num != 0) signal_num else null,
             });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/ev/backends/kqueue.zig` around lines 711 - 718, The kqueue exit-status
decoding currently sets .code to exit_code even when the process was signaled;
change the logic in the block that computes ustatus/exit_code/signal_num and
calls comp.setResult(.process_wait) so that .code is 0 when the process was
terminated by a signal (i.e., when signal_num != 0) and only uses exit_code when
not signaled, and preserve .signal as null when there is no signal; update the
comp.setResult call (the .process_wait result construction) to mirror the epoll
behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/ev/backends/kqueue.zig`:
- Around line 711-718: The kqueue exit-status decoding currently sets .code to
exit_code even when the process was signaled; change the logic in the block that
computes ustatus/exit_code/signal_num and calls comp.setResult(.process_wait) so
that .code is 0 when the process was terminated by a signal (i.e., when
signal_num != 0) and only uses exit_code when not signaled, and preserve .signal
as null when there is no signal; update the comp.setResult call (the
.process_wait result construction) to mirror the epoll behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 0b3573cf-3e9c-46ab-8f6b-d2a96d37b893

📥 Commits

Reviewing files that changed from the base of the PR and between 7edc210 and 36e1217.

📒 Files selected for processing (1)
  • src/ev/backends/kqueue.zig

Use RegisterWaitForSingleObject to register a Windows thread-pool
callback on the process handle. When the process exits, the callback
calls PostQueuedCompletionStatus to notify the IOCP event loop,
which then retrieves the exit code via GetExitCodeProcess.

This avoids blocking a thread pool thread for the duration of the
process lifetime, and integrates cleanly with the existing IOCP
completion dispatch path.

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

Copy link
Copy Markdown
Owner Author

@claude the IOCP process waiter should be cancelable, can we make it so?

@claude

claude Bot commented Mar 11, 2026 •

Copy link
Copy Markdown

Claude finished @lalinsky's task in 4m 56s —— View job


Making IOCP process_wait cancelable

  • Gather context
  • Read IOCP backend and cancellation-related code
  • Implement cancellation support in iocp.zig
  • Compiled successfully for x86_64-windows
  • Linux tests pass (10/10)
  • Commit and push

Summary

The IOCP process_wait operation is now cancelable. The key challenge was avoiding a race between the Windows thread-pool callback and the cancel path — both could try to post a completion to IOCP.

Changes to src/ev/backends/iocp.zig:

  1. ProcessWaitData — added posted: std.atomic.Value(bool) to coordinate which path wins the race to post to IOCP.

  2. processWaitCallback — uses cmpxchgStrong(false, true) before PostQueuedCompletionStatus, so if cancel() gets there first the callback becomes a no-op.

  3. submitProcessWait — resets posted to false on each submission (supports resubmission).

  4. cancel() — new .process_wait branch:

    • Calls UnregisterWaitEx(handle, INVALID_HANDLE_VALUE) — this blocks until any in-flight callback finishes, eliminating the race window
    • Then races via CAS: if callback hasn't posted yet, cancel() posts the completion itself
  5. processCompletion — checks c.cancel_state.load(.acquire).requested; if true, sets error.Canceled instead of calling GetExitCodeProcess.
    | Branch: process-wait

Add cancellation support for process_wait in the IOCP backend:

- Add atomic 'posted' flag to ProcessWaitData to prevent double-posting
  when both the callback and cancel() race to post an IOCP completion
- Make processWaitCallback use CAS before posting so the cancel path can
  win the race if it gets there first
- Handle .process_wait in cancel(): call UnregisterWaitEx with
  INVALID_HANDLE_VALUE to wait for any in-flight callback, then post the
  completion ourselves if the callback didn't already do so
- In processCompletion, check cancel_state.requested and set
  error.Canceled instead of calling GetExitCodeProcess
- Reset the posted flag in submitProcessWait to support resubmission

Co-authored-by: Lukáš Lalinský <[email protected]>
@lalinsky
lalinsky merged commit 3ba644f into main Mar 11, 2026
28 checks passed
@lalinsky
lalinsky deleted the process-wait branch March 11, 2026 06:52
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