Skip to content

runtime: periodic stack pool cleanup and higher default max_unused_stacks - #421

Merged
lalinsky merged 1 commit into
mainfrom
stack-pool-eviction
May 28, 2026
Merged

lalinsky merged 1 commit into
mainfrom
stack-pool-eviction

Conversation

@lalinsky

@lalinsky lalinsky commented May 28, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • Raises default max_unused_stacks from 16 to 1000, so stacks are reused across tasks at typical concurrency levels instead of being freed and reallocated each time
  • Adds StackPool.cleanup(now, limit) — evicts up to limit expired entries from the head of the pool (oldest-first, stops early on the first non-expired entry, frees outside the lock)
  • Adds a 60s ev.Timer per Executor that calls cleanup(loop.now(), 16) and rearms itself, ensuring idle stacks are reclaimed even when task activity is low

The existing release-time eviction (up to 4 per release() call) remains unchanged as a fast path during active periods.

See #415

Test plan

  • ./check.sh passes
  • ./check.sh --backend epoll passes

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

coderabbitai Bot commented May 28, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR implements periodic cleanup of idle stacks in the coroutine stack pool. A new StackPool.cleanup() method scans the free list and evicts stacks older than a configured age, while a 60-second executor timer periodically triggers cleanup. The default pool size increases from 16 to 1000 stacks.

Changes

Periodic stack pool eviction

Layer / File(s) Summary
Stack pool cleanup method
src/coro/stack_pool.zig
StackPool.cleanup(now, limit) evicts up to limit expired stacks by scanning the free list under mutex lock, collecting nodes to free into a temporary list, and freeing stack memory after releasing the lock to minimize hold time.
Executor periodic eviction integration
src/runtime.zig
Default max_unused_stacks increased to 1000. Executor gains an ev.Timer field initialized to 60s, registered during Executor.init, and wired to a stackPoolEvictionCallback that calls runtime.stack_pool.cleanup(loop.now(), 16) and reschedules itself.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • lalinsky/zio#177: Enables the eviction logic by modifying StackPool.release to record timestamps on free stacks.
  • lalinsky/zio#142: Introduces StackPool eviction parameters and stack recycling behavior that this PR extends with periodic cleanup.
  • lalinsky/zio#30: Establishes the foundational stack pool implementation that this PR extends with eviction and runtime wiring.

Poem

A 60-second heartbeat ticks, ⏰
Old stacks fall away from the heap,
One thousand fresh ones waiting—
The pool breathes, life cycles,
Memory dances its endless rhythm.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed Title directly and clearly describes the main changes: adding periodic stack pool cleanup and increasing the default max_unused_stacks value.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description check ✅ Passed The PR description directly aligns with the changeset, detailing the three main modifications: increased max_unused_stacks, the new cleanup method, and the periodic eviction timer.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch stack-pool-eviction

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 (1)
src/coro/stack_pool.zig (1)

173-204: ⚡ Quick win

Add a direct cleanup() regression test.

The current tests only hit age-based eviction through release(), not the new cleanup(now, limit) contract. A small unit test that seeds expired + live entries and asserts both the limit and 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

📥 Commits

Reviewing files that changed from the base of the PR and between 412f154 and 9399f08.

📒 Files selected for processing (2)
  • src/coro/stack_pool.zig
  • src/runtime.zig

Comment thread src/runtime.zig
Comment on lines +334 to +336
// Register periodic stack pool eviction timer
self.stack_pool_eviction_timer.c.callback = stackPoolEvictionCallback;
self.loop.add(&self.stack_pool_eviction_timer.c);

@coderabbitai coderabbitai Bot May 28, 2026 •

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@coderabbitai create separate issue for this

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.

🧩 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).

@lalinsky
lalinsky merged commit db1a707 into main May 28, 2026
30 checks passed
@lalinsky
lalinsky deleted the stack-pool-eviction branch May 28, 2026 07:26
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