Skip to content

Auto-reap group tasks on completion - #164

Merged
lalinsky merged 1 commit into
mainfrom
auto-reap-group-tasks
Dec 17, 2025
Merged

lalinsky merged 1 commit into
mainfrom
auto-reap-group-tasks

Conversation

@lalinsky

Copy link
Copy Markdown
Owner

Problem

Long-running groups accumulate task allocations because completed tasks are only reaped when group.wait() or group.cancel() is called. While stacks are released immediately, the task structs remain allocated (~200 bytes + context size per task).

For groups that run indefinitely or for long periods, this causes unbounded memory growth.

Solution

When a group task completes, it is now immediately removed from the group's task list and the group's reference is released. This prevents memory accumulation while maintaining all existing functionality.

Implementation

The changes are minimal and focused:

  1. Regular tasks (src/runtime.zig): After marking a task complete in the scheduler loop, remove it from the group list and release the group's reference
  2. Blocking tasks (src/core/blocking_task.zig): Same logic in the completion callback which runs on the aio event loop thread

Thread Safety

The implementation handles concurrent access correctly:

  • Both remove() and pop() on CompactWaitQueue are protected by atomic mutex
  • When a task completes and removes itself, pop() in cleanup won't see it
  • When cleanup pops a node, subsequent remove() returns false
  • By checking the return value of remove(), we ensure exactly one release happens

Testing

All existing tests pass without modification (168/168), including the group-specific tests:

  • Group: spawn
  • Group: wait for multiple tasks
  • Group: cancellation while waiting

Behavior

User-visible: None - groups work exactly the same way from user perspective

Internal: Long-running groups no longer accumulate completed task allocations. Memory is released immediately after each task completes.

Previously, group tasks accumulated in memory until group.wait() or
group.cancel() was called. For long-running groups, this could cause
unbounded memory growth.

Now, when a group task completes, it is immediately removed from the
group's task list and the group's reference is released. This prevents
memory accumulation while maintaining all existing functionality.

The implementation is thread-safe: both regular tasks (completed on
executor threads) and blocking tasks (completed on aio event loop
thread) are handled correctly, with proper synchronization to ensure
exactly one release happens even if groupCancel races with completion.
@coderabbitai

coderabbitai Bot commented Dec 17, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds group-aware cleanup during awaitable completion across two runtime contexts. When an awaitable finishes, the code now checks if it belongs to a group, removes it from the group's task list if present, and releases the group's reference without shutdown semantics to prevent improper double-release.

Changes

Cohort / File(s) Summary
Group-aware awaitable cleanup
src/core/blocking_task.zig, src/runtime.zig
Adds conditional removal of awaitables from their group's task list upon completion. After marking complete, checks for group association, removes group_node from task list, and releases group reference with non-shutdown hint if removal succeeds. Prevents conflicts when groupCancel has already removed the node.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Reference counting semantics: Verify the non-shutdown release path properly avoids double-release and handles edge cases where groupCancel pre-removes the node.
  • Execution context differences: Both blocking_task.zig and runtime.zig implement similar logic in different control flows—ensure both paths handle the group_node state consistently.
  • Group lifecycle: Confirm that releasing with done = false vs. done = true maintains correct group reference accounting across the awaitable lifecycle.

Possibly related PRs

  • PR #15: Introduces the Awaitable abstraction and releaseAwaitable semantics that this PR depends on.
  • PR #152: Adds the Group and Awaitable.group_node structures that this cleanup logic now operates on.
  • PR #154: Modifies GroupNode linkage and group task list manipulation that directly parallels these changes.

Poem

Tasks complete, from groups they flee 🚀
No double-release, reference free,
Group_node removed, the cleanup's done,
Awaitable life cycle—cleanly run ✨

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title directly matches the main change: completing group tasks now triggers immediate removal from the group's task list.
Description check ✅ Passed The description is comprehensive and directly related to the changeset, detailing the problem, solution, implementation across both files, thread safety considerations, and test results.
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 auto-reap-group-tasks

📜 Recent 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 1e427e6 and 8ba30d8.

📒 Files selected for processing (2)
  • src/core/blocking_task.zig (1 hunks)
  • src/runtime.zig (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.zig

📄 CodeRabbit inference engine (CLAUDE.md)

Use zig env to get the path to the Zig standard library when needed

Files:

  • src/core/blocking_task.zig
  • src/runtime.zig
🧠 Learnings (3)
📓 Common learnings
Learnt from: lalinsky
Repo: lalinsky/zio PR: 118
File: src/core/task.zig:33-115
Timestamp: 2025-11-04T10:29:56.949Z
Learning: In zio's task implementation (src/core/task.zig), the Closure struct intentionally caps result_len and context_len at 4096 bytes (using u12 fields) and alignment at 16 bytes (using u4 padding fields). This is a deliberate design decision to avoid bloating task structures. Users needing larger result or context storage should heap-allocate and pass pointers instead. These limits are more generous than std lib's fixed storage (64 bytes for results, 1024 bytes for args).
<!-- [add_learning]
The task storage limits in zio (4 KiB for result/context, 16-byte alignment) are intentional design constraints to prevent task bloat, not correctness issues. The maintainer's position is that larger data should be heap-allocated.
📚 Learning: 2025-10-03T11:09:46.846Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 18
File: src/net.zig:18-25
Timestamp: 2025-10-03T11:09:46.846Z
Learning: In zio's `Runtime.BlockingTask`, calling `deinit()` on a blocking task only frees the task wrapper (TaskData) itself, not the result returned by the blocking function. The result remains valid and owned by the caller, who is responsible for its cleanup. This is the intended design for async blocking tasks.

Applied to files:

  • src/core/blocking_task.zig
  • src/runtime.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/core/blocking_task.zig
  • src/runtime.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 (2)
src/core/blocking_task.zig (1)

96-103: Group cleanup logic looks solid.

The pattern is correct: check for group presence, attempt removal from the group's task list, and release the group's reference only if removal succeeded. The done = false parameter ensures this release doesn't trigger task list removal or shutdown checks—those happen in the subsequent releaseAwaitable call at line 107 with done = true.

The race condition between task completion and groupCancel is properly handled by checking remove()'s return value.

src/runtime.zig (1)

558-564: Consistent group cleanup implementation.

This mirrors the blocking task cleanup logic exactly, which is good for maintainability. The placement is correct: after markComplete() wakes all waiters but before the final reference release. The two-stage release (group reference with done = false, then runtime reference with done = true) properly separates concerns—the first removes the task from the group without touching the global task list, the second handles the runtime's bookkeeping and potential shutdown wake.


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.

@lalinsky
lalinsky merged commit bbe8748 into main Dec 17, 2025
@lalinsky
lalinsky deleted the auto-reap-group-tasks branch December 17, 2025 06:50
This was referenced Jan 10, 2026
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