Skip to content

Use StackPool from coro.zig with standardized 8MB stacks - #142

Merged
lalinsky merged 1 commit into
mainfrom
use-stack-pool-from-coro-zig
Nov 14, 2025
Merged

lalinsky merged 1 commit into
mainfrom
use-stack-pool-from-coro-zig

Conversation

@lalinsky

Copy link
Copy Markdown
Owner

Summary

Replace the old bucket-based stack pool with the new StackPool from coro.zig. This brings several improvements and simplifications.

Changes

  • Thread-safe StackPool: One shared StackPool per Runtime (instead of per-Executor)
  • Automatic stack growth: Signal handlers (SIGSEGV/SIGBUS on POSIX) handle stack expansion on-demand
  • LRU eviction: Configurable max unused stacks (default: 16)
  • Time-based expiration: Unused stacks freed after 60 seconds
  • Stack recycling: Uses MADV_FREE on POSIX, VirtualAlloc on Windows to release memory

Standardized Stack Configuration

All tasks now use the same stack configuration:

  • 8MB reserved virtual address space
  • 64KB initial committed physical memory
  • Removed stack_size option from SpawnOptions and CreateOptions

Signal Handler Setup

Stack growth signal handlers are installed in:

  • Runtime.init() for the main thread
  • Executor.run() for each worker thread
  • Cleaned up in Runtime.deinit() and when executors exit

Testing

All 162 tests pass ✅

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

coderabbitai Bot commented Nov 14, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Stack 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

Cohort / File(s) Change Summary
Dependency Update
build.zig.zon
Updated coro dependency from commit d22571c to 7228ad4 with corresponding hash change
Runtime & Task Architecture
src/runtime.zig, src/core/task.zig
Removed stack_size field from SpawnOptions and TaskCreateOptions. Centralized stack_pool ownership to Runtime (moved from per-Executor). Changed RuntimeOptions.stack_pool type from StackPoolOptions to StackPoolConfig with concrete defaults (max 8MB, 64KB committed, 16 unused stacks, 60s max age). Tasks now acquire stacks via runtime.stack_pool and store in coro.context.stack_info. Updated task creation/destruction paths accordingly
Example Updates
examples/tls_demo.zig
Removed explicit .stack_size = 4 * 1024 * 1024 from spawn call; now uses default stack allocation
Stack Pool Module Deletion
src/stack_pool.zig
Entire file removed (previously implemented bucketed pool with FIFO acquisition, age-based cleanup, and page-aligned allocation)

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

  • Stack pool ownership transition: Verify all lifecycle paths (init/deinit) correctly moved from per-Executor to Runtime. Check that Executor still accesses stack_pool through runtime reference without redundant management.
  • Context.stack_info integration: Confirm tasks properly acquire from rt.stack_pool and release via stack_info in both normal and error paths. Look for deferred release correctness in task creation.
  • Runtime/Executor initialization sequences: Trace through setupStackGrowth/cleanupStackGrowth calls to ensure stack growth is wired per-thread without gaps.
  • Coro dependency compatibility: Verify new coro commit supports the stack_info usage patterns in coroutine context.
  • TLS demo example: Confirm default stack sizing meets the example's needs (removed explicit 4MB request).

Possibly related PRs

Poem

Stacks once scattered, now they gather close,
Runtime tends the pool with ordered prose,
No per-task sizing clutters up the frame,
Tasks acquire freely—simple, lean, less strain,
Architecture breathes, constraints unwind,
Cleaner patterns flourish in the grind! 🏗️

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: replacing the stack pool implementation with coro.zig's StackPool and standardizing to 8MB stacks across the codebase.
Description check ✅ Passed The description clearly relates to the changeset, detailing the stack pool replacement, signal handler setup, and the standardized 8MB stack configuration implemented across multiple files.
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 use-stack-pool-from-coro-zig

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

📜 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 026aae3 and ce13aed.

📒 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.zig
  • examples/tls_demo.zig
  • src/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.zig
  • examples/tls_demo.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). (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 config

Using .{} for SpawnOptions matches the new API (no stack_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 consistent

The new RuntimeOptions.stack_pool defaults and Runtime.stack_pool: StackPool ownership tie together cleanly:

  • Runtime.init constructs a single StackPool from options.stack_pool, and Runtime.deinit calls self.stack_pool.deinit() after all executors and awaitables have been drained, so the pool outlives all tasks.
  • AnyTask.create (in src/core/task.zig) acquires a stack once per coroutine; Executor.run releases current_coro.context.stack_info when a coroutine finishes and zeroes allocation_len (lines 682–685), and AnyTask.destroyFn releases 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.release is 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 release

The coroutine stack lifecycle here looks sane:

  • AnyTask.create acquires a stack from executor.runtime.stack_pool and stores it in self.coro.context.stack_info, with an errdefer release if anything after that fails.
  • When a coroutine finishes normally, Executor.run releases stack_info and zeroes allocation_len, so the task no longer owns a stack at that point.
  • AnyTask.destroyFn conditionally releases self.coro.context.stack_info only when allocation_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.deinit drains awaitables before deinitializing stack_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 pairing

You 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 with StackPool/stack-growth APIs you’re using.
  • The hash = "coro-0.4.0-…" matches what zig fetch reports for that URL.

If those two line up on your machine, this change is good to go.

Comment thread src/runtime.zig
Comment on lines +17 to +21
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;

@coderabbitai coderabbitai Bot Nov 14, 2025 •

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

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.init calls setupStackGrowth() on the calling thread (the future main executor).
  • Later, Runtime.run calls executors.items[0].run() on the same thread, and Executor.run unconditionally does try setupStackGrowth(); defer cleanupStackGrowth();.
  • After the run loop exits, Executor.run’s defer cleanupStackGrowth() runs once, and then Runtime.deinit calls cleanupStackGrowth() 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.init as 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 the setupStackGrowth() call in Runtime.init so 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.

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.

It's fine, the code can handle it.

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.

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

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