Repository navigation
runtime: periodic stack pool cleanup and higher default max_unused_stacks - #421
Conversation
…acks Add a periodic eviction timer (60s interval) to each Executor that calls StackPool.cleanup() to free up to 16 expired stacks per firing. This complements the existing release-time eviction (which is limited to 4 per call) by ensuring idle stacks are reclaimed even when activity is low. Also raise the default max_unused_stacks from 16 to 1000 so that stacks are reused across tasks at typical concurrency levels rather than being freed and reallocated on every task.
📝 WalkthroughWalkthroughThis PR implements periodic cleanup of idle stacks in the coroutine stack pool. A new ChangesPeriodic stack pool eviction
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 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: 1
🧹 Nitpick comments (1)
src/coro/stack_pool.zig (1)
173-204: ⚡ Quick winAdd a direct
cleanup()regression test.The current tests only hit age-based eviction through
release(), not the newcleanup(now, limit)contract. A small unit test that seeds expired + live entries and asserts both thelimitand the “stop on first non-expired entry” behavior would pin down the tricky part of this change.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/coro/stack_pool.zig` around lines 173 - 204, Add a focused unit test that directly exercises StackPool.cleanup(now, limit): construct a StackPool, insert several FreeNode entries with controlled timestamps (some older than config.max_age and one newer), call cleanup with a specific limit, and assert that at most `limit` expired nodes were freed (mock/spy stack.stackFree) and that cleanup stops when it encounters the first non-expired node (i.e., later nodes remain in the pool); use StackPool methods used in the diff (e.g., removeNode, head, FreeNode.timestamp) and the pool's mutex to set up state safely so the test pins both the limit behavior and the "stop on first non-expired entry" behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/runtime.zig`:
- Around line 334-336: The eviction timer is being armed unconditionally,
causing unnecessary wakeups when stack_pool.max_age is zero; change the logic
around self.stack_pool_eviction_timer.c.callback,
self.loop.add(&self.stack_pool_eviction_timer.c) and the rearming inside
stackPoolEvictionCallback so they only register/rearm when
self.runtime.options.stack_pool.max_age.value > 0 (i.e., gate the initial
loop.add(...) and any subsequent re-add in stackPoolEvictionCallback on that
condition), ensuring cleanup() runs without scheduling the periodic timer when
max_age is zero.
---
Nitpick comments:
In `@src/coro/stack_pool.zig`:
- Around line 173-204: Add a focused unit test that directly exercises
StackPool.cleanup(now, limit): construct a StackPool, insert several FreeNode
entries with controlled timestamps (some older than config.max_age and one
newer), call cleanup with a specific limit, and assert that at most `limit`
expired nodes were freed (mock/spy stack.stackFree) and that cleanup stops when
it encounters the first non-expired node (i.e., later nodes remain in the pool);
use StackPool methods used in the diff (e.g., removeNode, head,
FreeNode.timestamp) and the pool's mutex to set up state safely so the test pins
both the limit behavior and the "stop on first non-expired entry" behavior.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 5092b1c5-1d77-478e-8fb9-84a977c88de9
📒 Files selected for processing (2)
src/coro/stack_pool.zigsrc/runtime.zig
| // Register periodic stack pool eviction timer | ||
| self.stack_pool_eviction_timer.c.callback = stackPoolEvictionCallback; | ||
| self.loop.add(&self.stack_pool_eviction_timer.c); |
There was a problem hiding this comment.
Don’t arm the eviction timer when age-based eviction is disabled.
With stack_pool.max_age = .zero, every executor still wakes once a minute just to return from cleanup() immediately. That turns a disabled feature into permanent background work on idle runtimes. Gate both the initial loop.add(...) and the callback rearm on self.runtime.options.stack_pool.max_age.value > 0.
Also applies to: 356-360
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/runtime.zig` around lines 334 - 336, The eviction timer is being armed
unconditionally, causing unnecessary wakeups when stack_pool.max_age is zero;
change the logic around self.stack_pool_eviction_timer.c.callback,
self.loop.add(&self.stack_pool_eviction_timer.c) and the rearming inside
stackPoolEvictionCallback so they only register/rearm when
self.runtime.options.stack_pool.max_age.value > 0 (i.e., gate the initial
loop.add(...) and any subsequent re-add in stackPoolEvictionCallback on that
condition), ensuring cleanup() runs without scheduling the periodic timer when
max_age is zero.
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
gh issue create \
--repo lalinsky/zio \
--title "runtime: skip eviction timer when stack_pool.max_age is zero" \
--assignee lalinsky \
--body "## Problem
When \`RuntimeOptions.stack_pool.max_age\` is set to \`.zero\` (i.e., age-based eviction disabled), every \`Executor\` still registers and rearms a 60-second \`ev.Timer\`. On each tick the timer fires, \`stackPoolEvictionCallback\` calls \`cleanup()\` which returns immediately because \`max_age == .zero\`, then immediately rearms the timer. This is unnecessary background work on idle runtimes that have opted out of age-based eviction.
## Expected behavior
When \`stack_pool.max_age.value == 0\`, neither the initial \`loop.add(&self.stack_pool_eviction_timer.c)\` in \`Executor.init\` nor the \`loop.add(c)\` rearm inside \`stackPoolEvictionCallback\` should run.
## References
- PR: https://github.com/lalinsky/zio/pull/421
- Review comment: https://github.com/lalinsky/zio/pull/421#discussion_r3316021338
Reported by `@lalinsky`"Length of output: 1089
@lalinsky Created #422 to track this.
🧠 Learnings used
Learnt from: lalinsky
Repo: lalinsky/zio PR: 184
File: src/runtime/blocking_task.zig:117-146
Timestamp: 2026-01-10T13:55:00.163Z
Learning: In Zig files, do not reference libxev for async I/O. The project uses a custom event loop implementation under src/ev/ and a callback-based async I/O loop similar to libuv/libxev. Reviewers should ensure code relies on the src/ev event loop and that there are no libxev usage patterns; prefer the central event loop in src/ev/ for all asynchronous operations.
Learnt from: lalinsky
Repo: lalinsky/zio PR: 184
File: src/stdio.zig:117-129
Timestamp: 2026-01-10T14:08:37.019Z
Learning: In Zig files implementing swap-like semantics (e.g., old = swap(new); defer swap(old)), ensure the return value is an opaque restoration token rather than a direct reflection of internal state. Rely on the contract to perform increment/decrement logic internally (e.g., shield_count) and not expose internal state through the token. This makes behavior predictable, supports refactoring, and avoids leaking internal state across calls. Apply this pattern broadly to Zig code that uses a paired-swap or restoration-token mechanism.
Learnt from: lalinsky
Repo: lalinsky/zio PR: 250
File: src/utils/simple_stack.zig:10-14
Timestamp: 2026-01-29T05:49:09.119Z
Learning: In Zig sources (example: src/utils/simple_stack.zig, src/utils/simple_queue.zig, src/runtime/awaitable.zig), define the in_list field condition using std.debug.runtime_safety instead of checking builtin.mode == .Debug. This ensures the field exists in both Debug and ReleaseSafe builds (where runtime safety checks are active) and is void only in ReleaseFast and ReleaseSmall builds. When reviewing, verify the conditional type uses std.debug.runtime_safety to gate in_list, and that ReleaseFast/ReleaseSmall properly omit it.
Learnt from: lalinsky
Repo: lalinsky/zio PR: 267
File: examples/hello_world.zig:4-10
Timestamp: 2026-01-31T10:27:14.848Z
Learning: In Zig code reading the zio repository, Runtime.init(allocator, options) returns a *Runtime (a pointer) rather than a Runtime value. Therefore, when passing the result to functions that expect *Runtime, do not apply & to take its address. Use the pointer directly (e.g., let rt = Runtime.init(...); someFunc(rt);) to avoid taking the address of a pointer. This guideline applies to all Zig files that interact with Runtime.init and similar APIs returning *Runtime.
Learnt from: lalinsky
Repo: lalinsky/zio PR: 346
File: src/coro/stack.zig:17-24
Timestamp: 2026-03-13T11:45:53.013Z
Learning: In Zig code reviews, do not flag module-level or file-scope declarations that reference POSIX-only types as Windows build issues if all code paths referencing those declarations return early on Windows (e.g., if (builtin.os.tag == .windows) return;). These declarations are lazily analyzed and only compiled when reachable. Treat this as a general pattern: POSIX-type references that are gated by Windows guards should not be considered build failures. Applicable to Zig source files across the repo (any .zig file).
Summary
max_unused_stacksfrom 16 to 1000, so stacks are reused across tasks at typical concurrency levels instead of being freed and reallocated each timeStackPool.cleanup(now, limit)— evicts up tolimitexpired entries from the head of the pool (oldest-first, stops early on the first non-expired entry, frees outside the lock)ev.TimerperExecutorthat callscleanup(loop.now(), 16)and rearms itself, ensuring idle stacks are reclaimed even when task activity is lowThe existing release-time eviction (up to 4 per
release()call) remains unchanged as a fast path during active periods.See #415
Test plan
./check.shpasses./check.sh --backend epollpasses