Repository navigation
Use StackPool from coro.zig with standardized 8MB stacks - #142
Conversation
Replace the old bucket-based stack pool with the new StackPool from coro.zig. This brings several improvements: - Thread-safe StackPool shared across all executors (not per-executor) - Automatic stack growth via signal handlers (SIGSEGV/SIGBUS on POSIX) - LRU eviction with configurable max unused stacks (default: 16) - Time-based expiration for unused stacks (default: 60s) - Stack memory recycling (MADV_FREE on POSIX, VirtualAlloc on Windows) Stack configuration is now standardized: - 8MB reserved virtual address space per stack - 64KB initial committed physical memory - Removed per-task stack_size option from SpawnOptions Signal handlers for stack growth are installed in: - Runtime.init() for the main thread - Executor.run() for each worker thread
WalkthroughStack management architecture refactored to centralize ownership. Removed per-task stack_size option from SpawnOptions and TaskCreateOptions. Runtime now owns and manages the stack pool directly, with tasks acquiring stacks from context.stack_info. Updated coro dependency to a new commit. Removed standalone stack_pool module. Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes
Possibly related PRs
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches🧪 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
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
build.zig.zon(1 hunks)examples/tls_demo.zig(1 hunks)src/core/task.zig(3 hunks)src/runtime.zig(9 hunks)src/stack_pool.zig(0 hunks)
💤 Files with no reviewable changes (1)
- src/stack_pool.zig
🧰 Additional context used
🧠 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-11-04T10:29:56.949Z
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.
Applied to files:
src/core/task.zigexamples/tls_demo.zigsrc/runtime.zig
📚 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/task.zigexamples/tls_demo.zigsrc/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). (5)
- GitHub Check: test (ubuntu-latest, riscv64-linux, qemu-riscv64-static, epoll)
- GitHub Check: test (ubuntu-latest, x86_64-linux)
- GitHub Check: test (windows-latest, native)
- GitHub Check: test (macos-latest, native)
- GitHub Check: test (ubuntu-latest, aarch64-linux, qemu-aarch64-static, epoll)
🔇 Additional comments (4)
examples/tls_demo.zig (1)
73-73: Spawn call correctly switches to default stack configUsing
.{}forSpawnOptionsmatches the new API (nostack_size) and keeps this example aligned with the runtime’s standardized 8MB stack pool. Nothing to fix here.src/runtime.zig (1)
70-75: Stack pool ownership and stack release look consistentThe new
RuntimeOptions.stack_pooldefaults andRuntime.stack_pool: StackPoolownership tie together cleanly:
Runtime.initconstructs a singleStackPoolfromoptions.stack_pool, andRuntime.deinitcallsself.stack_pool.deinit()after all executors and awaitables have been drained, so the pool outlives all tasks.AnyTask.create(insrc/core/task.zig) acquires a stack once per coroutine;Executor.runreleasescurrent_coro.context.stack_infowhen a coroutine finishes and zeroesallocation_len(lines 682–685), andAnyTask.destroyFnreleases any leftover stack if it wasn’t already released.- That gives you a single shared pool with balanced acquire/release and no obvious double-free path, assuming
StackPool.releaseis happy with value semantics.From a runtime perspective this is solid and matches the PR’s goal of a central, thread‑safe stack pool.
Also applies to: 682-685, 906-907, 969-970, 1006-1007
src/core/task.zig (1)
11-11: Stack pool usage from tasks is balanced and guarded against double releaseThe coroutine stack lifecycle here looks sane:
AnyTask.createacquires a stack fromexecutor.runtime.stack_pooland stores it inself.coro.context.stack_info, with anerrdeferrelease if anything after that fails.- When a coroutine finishes normally,
Executor.runreleasesstack_infoand zeroesallocation_len, so the task no longer owns a stack at that point.AnyTask.destroyFnconditionally releasesself.coro.context.stack_infoonly whenallocation_len > 0, which covers:
- Tasks that never ran or died early and still hold a stack.
- Tasks that didn’t go through the normal “finished in executor loop” path for whatever reason.
- While avoiding double‐releasing stacks already freed in the executor loop.
Given that
Runtime.deinitdrains awaitables before deinitializingstack_pool, this wiring is coherent and doesn’t leave obvious leaks or double frees.Also applies to: 285-287, 340-343
build.zig.zon (1)
18-19: Verify coro.zig commit and hash pairingYou bumped the coro.zig dependency to a new commit and hash. That’s the right place for this change, but it’s worth double‑checking that:
- The commit
7228ad40…actually exists and matches the intended version of coro.zig withStackPool/stack-growth APIs you’re using.- The
hash = "coro-0.4.0-…"matches whatzig fetchreports for that URL.If those two line up on your machine, this change is good to go.
| const StackPool = @import("coro").StackPool; | ||
| const StackPoolConfig = @import("coro").StackPoolConfig; | ||
| const StackInfo = @import("coro").StackInfo; | ||
| const setupStackGrowth = @import("coro").setupStackGrowth; | ||
| const cleanupStackGrowth = @import("coro").cleanupStackGrowth; |
There was a problem hiding this comment.
Stack-growth handlers: avoid double install/cleanup on main thread and handle init failures
Right now the main thread hits setupStackGrowth() twice and cleanupStackGrowth() twice:
Runtime.initcallssetupStackGrowth()on the calling thread (the future main executor).- Later,
Runtime.runcallsexecutors.items[0].run()on the same thread, andExecutor.rununconditionally doestry setupStackGrowth(); defer cleanupStackGrowth();. - After the run loop exits,
Executor.run’sdefer cleanupStackGrowth()runs once, and thenRuntime.deinitcallscleanupStackGrowth()again.
On top of that, if Runtime.init fails after calling setupStackGrowth() (e.g., allocator or thread-pool failure), there’s no corresponding cleanup; the process keeps the handler installed even though no Runtime instance was created.
If setupStackGrowth/cleanupStackGrowth are strictly idempotent this is just wasted work; if they assume a single install/uninstall pair per thread, this can turn into real bugs.
I’d tighten this up like so:
- Treat stack-growth setup in
Runtime.initas for the main executor only, and only invoke it there. - In
Executor.run, install handlers only for worker threads (non-zero executors). - Add an
errdefer cleanupStackGrowth();after thesetupStackGrowth()call inRuntime.initso init failures don’t leak the handler.
Something along these lines:
pub fn init(allocator: Allocator, options: RuntimeOptions) !*Runtime {
- // Setup stack growth signal handlers for this thread
- try setupStackGrowth();
+ // Setup stack growth signal handlers for the main executor thread
+ try setupStackGrowth();
+ errdefer cleanupStackGrowth();
// ...
}
pub fn run(self: *Executor) !void {
- // Setup stack growth signal handlers for this thread
- try setupStackGrowth();
- defer cleanupStackGrowth();
+ // Worker executors install their own stack growth handlers
+ if (self.id != 0) {
+ try setupStackGrowth();
+ defer cleanupStackGrowth();
+ }
// Initialize loop on this thread
// ...
}Runtime.deinit can keep its cleanupStackGrowth() to tear down the main thread’s handler.
Also applies to: 634-637, 919-921, 1009-1011
🤖 Prompt for AI Agents
In src/runtime.zig around lines 17-21 (and also review uses at 634-637, 919-921,
1009-1011): the stack-growth handlers are being installed/cleaned up multiple
times on the main thread and can leak on init failure. Change Runtime.init to
call setupStackGrowth() only for the main executor, immediately follow that call
with errdefer cleanupStackGrowth(); so a failed init will undo the install, and
keep Runtime.deinit calling cleanupStackGrowth() to remove the main handler. In
Executor.run, only call setupStackGrowth()/defer cleanupStackGrowth() for worker
threads (e.g., executor index != 0) so the main thread doesn’t install twice.
Apply the same single-install, conditional-install, and errdefer pattern to the
other referenced locations.
There was a problem hiding this comment.
It's fine, the code can handle it.
There was a problem hiding this comment.
@lalinsky, understood! If setupStackGrowth and cleanupStackGrowth are idempotent and handle multiple calls gracefully, then the current approach is fine.
🧠 Learnings used
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.
Learnt from: lalinsky
Repo: lalinsky/zio PR: 47
File: src/sync/Mutex.zig:237-237
Timestamp: 2025-10-15T19:38:44.659Z
Learning: In the `unlock` method of `src/sync/Mutex.zig`, the `runtime` parameter is intentionally retained (marked with `_ = runtime;`) for API consistency and future-proofing, even though it's not currently used in the implementation.
Summary
Replace the old bucket-based stack pool with the new StackPool from coro.zig. This brings several improvements and simplifications.
Changes
Standardized Stack Configuration
All tasks now use the same stack configuration:
stack_sizeoption fromSpawnOptionsandCreateOptionsSignal Handler Setup
Stack growth signal handlers are installed in:
Runtime.init()for the main threadExecutor.run()for each worker threadRuntime.deinit()and when executors exitTesting
All 162 tests pass ✅