Skip to content

coro: slab-allocate coroutine stacks with a decaying demand watermark - #634

Merged
lalinsky merged 9 commits into
mainfrom
stack-slab
Aug 1, 2026
Merged

lalinsky merged 9 commits into
mainfrom
stack-slab

Conversation

@lalinsky

@lalinsky lalinsky commented Aug 1, 2026

Copy link
Copy Markdown
Owner

Closes #436.

What

Coroutine stacks on 64-bit POSIX targets are now carved from slab reservations instead of each getting its own mapping, and the stack pool's retention policy is a decaying demand watermark instead of the old count cap and age limit.

Allocation. A slab is one mmap(PROT_NONE) reservation holding -Dstack-slab-slots slots (build option, default 64; 0 restores the per-stack allocator), with the slab header in the arena's first committed page and NOHUGEPAGE advised once per slab. Each slot has the exact layout of a standalone stack mapping (its first page is never-committed reservation, acting as the guard page), so the SIGSEGV growth handler, overflow detection, valgrind registration, and the pool's FreeNode-in-stack trick all work unchanged. A cold stack costs one mprotect instead of mmap+madvise+mprotect (#436 measured those at ~68ms per 10k tasks); releasing and reusing a stack costs no syscalls on any path.

Retention. max_unused_stacks and max_age are gone (BREAKING for direct StackPool.Config users). The pool keeps a retain target that ratchets up to each epoch's peak in-use count instantly and halves per shrink_interval (default 60s, .zero disables shrinking) on the way down — jemalloc-decay-style rather than a cliff. A periodic pass (driven by the existing per-executor timer; the pool rate-limits itself) frees capacity beyond the target: whole empty slabs first, then individually mapped stacks oldest-first, each pass bounded to half of what is currently there so the worst pass scales with the burst and halves every interval. Slabs keep per-slab freelists and in-use counts, and acquire prefers the first slab with a free slot, so load concentrates and older slabs drain toward empty where one munmap retires 64 slots. stack_pool.prewarm commits N slots at init and floors the watermark.

Burst-then-idle example: a 10k-task burst holds its capacity for one full interval (repeat bursts pay nothing), then drains 10k → 5k → 2.5k → … to the steady-state demand over ~10 minutes; a trickle load keeps one warm slab forever; total silence for an interval releases everything.

Platform matrix

platform allocator
64-bit POSIX (Linux, macOS, FreeBSD, NetBSD, illumos) slab slots
32-bit targets per-stack mmap (slabs can't afford the contiguous VA)
Windows per-stack RtlCreateUserStack (TEB/PAGE_GUARD integration)
OpenBSD per-stack MAP_STACK, fully committed (can't start as PROT_NONE)

The slab path also falls back to per-stack mapping at runtime if a reservation fails. The watermark policy applies uniformly; only the reclamation unit differs.

Deviations from #436's proposal

  • Chained fixed-size slabs instead of one giant N-stack reservation: same syscall economics, but reclaimable piecewise by the watermark instead of all-or-nothing.
  • No MADV_FREE on release: that path was measured too expensive back when stackRecycle was disabled, and it's the motivation for keeping release syscall-free and batching all reclamation into the periodic pass.

Benchmarks

Interleaved A/B vs main (dev box), zio-benchmarks: sleep 10ms x 10k tasks -25% st / -23% mt (the README's known weak case), fan-out light -5% st / -11% mt, spawn -7%, fan-in and ping-pong neutral-to-better. Confirmed after the watermark/decay commits landed. Motivating decomposition: ~75% of the fan-out-vs-Go gap was this fixed per-stack cost, not scheduling.

Testing

Full suite on io_uring, epoll (599/599); arm32 cross-compiles (gate degrades to the per-stack path); watermark semantics pinned by deterministic tests driving shrink() with synthetic timestamps (burst protection for one epoch, halving decay, live-slot pinning, prewarm floor, rate-limit guard). riscv64-under-QEMU has one pre-existing failure (clearTimer racing a firing timer) that reproduces identically on clean main.

lalinsky added 6 commits July 31, 2026 22:43
Each coroutine stack used to cost three syscalls up front (mmap PROT_NONE,
madvise NOHUGEPAGE, mprotect the initial commit) plus a munmap when the
pool let go of it, and the pool capped retained stacks at 16, so any
workload with more than 16 concurrent-then-exiting tasks churned the full
cycle every generation. Measured against Go on the fan-out benchmark, most
of the gap was this fixed cost, not scheduling.

Stacks on 64-bit POSIX targets now come from slab arenas: one PROT_NONE
reservation holds stack-slab-slots slots (build option, default 64), the
slab header lives in the arena's first committed page, and each slot has
the exact layout of a standalone allocation, so stack growth, overflow
detection, and the pool's in-stack FreeNode work unchanged. A cold slot
costs one mprotect; releasing a slot is a pointer push onto a LIFO with no
syscalls (recycling was measured too expensive long ago, so slots are
never decommitted); slabs are unmapped wholesale at pool deinit. The
max_unused_stacks/max_age policy now applies only to individually mapped
stacks, which still serve 32-bit targets, Windows (RtlCreateUserStack),
OpenBSD (MAP_STACK cannot start as PROT_NONE), and reservation failure.

The new stack_pool.prewarm runtime option commits that many slots at init
for spawn-burst workloads.

Benchmarks (dev box, interleaved): sleep 10ms x 10k tasks -28% st / -23%
mt, fan-out light -5% st / -11% mt, spawn -7%, fan-in neutral. riscv64
qemu failure (clearTimer race test) is pre-existing on main.
max_unused_stacks and max_age were the wrong shape for the pool: a count
cap says nothing about what the workload needs, and age eviction frees
stacks one munmap at a time on the release path. Both are gone. The pool
now tracks the peak number of stacks simultaneously in use over each
shrink_interval (default 60s, .zero disables), and a periodic pass frees
whatever committed capacity that watermark says was not needed: whole
slabs whose every slot is idle are unmapped first (slabs keep per-slab
free lists and in-use counts now, and acquire prefers the first slab
with a free slot so load concentrates and older slabs drain toward
empty), then individually mapped stacks, oldest first, bounded per pass.

Releasing a stack never makes a syscall on any path anymore; all
reclamation lives in the timer-driven shrink pass, which rate-limits
itself so every executor's timer may drive it. Prewarmed slots floor the
watermark and are never shrunk away. A burst's memory decays one
interval after it stops repeating; steady load keeps its stacks
indefinitely with no periodic reallocation.

stackRecycle and its MADV_FREE path are unused now; release(timestamp)
lost its parameter.
Resetting the retain watermark to each epoch's peak meant a 10k-stack
burst kept full capacity for one interval and then lost 97% of it in a
single pass: a cliff, and one timer callback stuck with ~150 munmaps.
Other allocators smooth this (jemalloc's dirty_decay purge curve,
tcmalloc's rate-limited background release, Go's paced scavenger), so
the retain target now ratchets up to the epoch peak instantly and halves
per interval on the way down, with whole-slab frees additionally capped
per pass. A burst's capacity drains with a half-life of one
shrink_interval; a repeat burst re-inflates the target immediately; the
prewarm floor still holds.
An absolute cap on slab frees per pass turns the decay's exponential
drain into a linear one as soon as a burst exceeds the cap: a 100k-stack
burst would spend an hour and a half at 16 slabs per pass. Bound each
pass by half of what is currently there instead (slabs and fallback
stacks alike), which matches the decay curve's own shape: the worst pass
scales with the burst and halves every interval after it.
@coderabbitai

coderabbitai Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 5ef34752-61f8-4fbc-8429-fd9e7ad13514

📥 Commits

Reviewing files that changed from the base of the PR and between fe85a87 and 68be24f.

📒 Files selected for processing (2)
  • src/coro/stack.zig
  • src/coro/stack_pool.zig
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/coro/stack_pool.zig

📝 Walkthrough

Walkthrough

The coroutine stack pool now supports POSIX slab allocation with fallback mappings, free-list reuse, demand-based shrinking, and prewarming. Runtime timers and task cleanup use the updated APIs. The changelog documents the breaking configuration changes.

Changes

Coroutine stack allocator

Layer / File(s) Summary
Slab primitives and pool model
src/coro/stack.zig, src/coro/stack_pool.zig
Adds slab reservation, owner-tag handling, guarded slot initialization, and slab configuration state.
Pool allocation and reuse
src/coro/stack_pool.zig
Acquisition and release reuse slab slots, fall back to individual mappings, and reclaim both allocation types during deinitialization.
Watermark shrinking and prewarming
src/coro/stack_pool.zig
Adds demand watermarks, decaying retention, bounded shrinking, prewarming, and tests for slab and fallback reclamation.
Runtime API integration
src/runtime.zig, src/task.zig, docs/changelog.md
Replaces age-based eviction with interval-driven shrinking, removes timestamp arguments from release calls, prewarms during initialization, and documents the breaking changes.

Estimated code review effort: 4 (Complex) | ~60 minutes

Possibly related PRs

  • lalinsky/zio#421: Replaced StackPool.cleanup and max_age eviction with watermark-based shrinking.
  • lalinsky/zio#423: Modified runtime stack-pool maintenance timers.
  • lalinsky/zio#595: Modified coroutine stack cleanup and AnyTask.releaseCoro.

Poem

Slabs hold stacks in ordered rows,
Free lists return what each task throws.
Watermarks fade, old pages depart,
Prewarming keeps a ready start.
One guard below, one pool in flight.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies slab allocation for coroutine stacks and the decaying demand watermark.
Description check ✅ Passed The description directly explains the slab allocator, retention changes, platform behavior, benchmarks, and testing.
Linked Issues check ✅ Passed The PR satisfies issue #436 by adding reusable slab slots while preserving guard pages, freelists, and fallback allocation.
Out of Scope Changes check ✅ Passed The changes remain within the stated slab allocation and stack-pool retention objectives.
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
  • Commit unit tests in branch stack-slab

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.

@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: 3

🧹 Nitpick comments (2)
src/runtime.zig (1)

418-420: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

The 60s literal here duplicates Config.shrink_interval's default and is unreachable.

Executor.init overwrites this field with self.runtime.options.stack_pool.shrink_interval whenever that interval is nonzero, and never adds the timer to the loop when it is zero. So the 60s written here is never the value that runs. If the Config default changes, this literal silently goes stale.

Proposed cleanup
-    // Periodic timer driving the stack pool's watermark shrink pass. The
-    // pool rate-limits itself, so every executor may carry this timer.
-    stack_pool_shrink_timer: ev.Timer = ev.Timer.init(.{ .duration = .fromSeconds(60) }),
+    // Periodic timer driving the stack pool's watermark shrink pass. The
+    // duration is set in init() from the configured shrink_interval; the
+    // pool rate-limits itself, so every executor may carry this timer.
+    stack_pool_shrink_timer: ev.Timer = undefined,
🤖 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 418 - 420, Remove the unreachable 60-second
initializer from stack_pool_shrink_timer and make the field initialization
reflect that Executor.init always assigns the configured interval before use.
Preserve the existing Config.shrink_interval-driven behavior and zero-interval
handling in Executor.init.
src/coro/stack_pool.zig (1)

157-190: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

The free-slot scan is O(number of slabs) on every acquire.

acquire walks the whole slab chain until it finds a slab with a free slot. With many live coroutines the chain grows to live_stacks / slab_slots entries. In the steady state the head slab usually has a free slot, so the walk is short. But a workload that frees only from older slabs makes every acquire traverse the entire chain, and the same chain is walked again by slabOfLocked on every release, so the cost shows up twice per stack lifetime.

If you want this bounded, keep a second intrusive list of slabs that have at least one free slot: release pushes the slab onto it when free goes from null to non-null, acquire pops from its head, and the carve path only touches the main chain. That keeps the "old slabs drain toward empty" property while making both hot paths O(1).

Not a blocker for this PR — the current shape is fine for typical spawn/exit patterns.

🤖 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 157 - 190, Optimize slab free-slot
lookup by adding a separate intrusive list of slabs with available slots,
alongside the main slab chain. Update the release path to enqueue a slab when
its free list transitions from empty, and update acquire to remove a slab from
this availability list when taking a slot instead of scanning self.slabs; keep
carveSlotLocked operating on the main chain and preserve the existing drain
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/coro/stack_pool.zig`:
- Around line 259-274: Update StackPool.shrink around the last_shrink interval
guard to return immediately when now is earlier than last_shrink, before calling
durationTo. Preserve the existing interval check for non-stale timestamps so
shrinking only proceeds after the configured shrink interval has elapsed.
- Around line 588-606: Update the test “StackPool slab: prewarm fills the
freelist and floors the watermark” to derive its prewarm count from the
configured slab_slots value, ensuring the count fits within one slab. Use that
same derived count for the prewarm option and both carved-value assertions,
including the assertion after acquire, while preserving the existing in_use and
no-additional-carving checks.

In `@src/runtime.zig`:
- Around line 1291-1295: Move errdefer self.stack_pool.deinit() before the
self.stack_pool.prewarm() call in the Runtime initialization flow, so partial
prewarm failures clean up all already-reserved slabs while preserving cleanup
for later initialization errors.

---

Nitpick comments:
In `@src/coro/stack_pool.zig`:
- Around line 157-190: Optimize slab free-slot lookup by adding a separate
intrusive list of slabs with available slots, alongside the main slab chain.
Update the release path to enqueue a slab when its free list transitions from
empty, and update acquire to remove a slab from this availability list when
taking a slot instead of scanning self.slabs; keep carveSlotLocked operating on
the main chain and preserve the existing drain behavior.

In `@src/runtime.zig`:
- Around line 418-420: Remove the unreachable 60-second initializer from
stack_pool_shrink_timer and make the field initialization reflect that
Executor.init always assigns the configured interval before use. Preserve the
existing Config.shrink_interval-driven behavior and zero-interval handling in
Executor.init.
🪄 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 Plus

Run ID: 12f4a60a-b408-47d6-9fde-c7929b247d9f

📥 Commits

Reviewing files that changed from the base of the PR and between b22ffc6 and 1b1a0f1.

📒 Files selected for processing (6)
  • build.zig
  • docs/changelog.md
  • src/coro/stack.zig
  • src/coro/stack_pool.zig
  • src/runtime.zig
  • src/task.zig

Comment thread src/coro/stack_pool.zig Resolved
Comment thread src/coro/stack_pool.zig Resolved
Comment thread src/runtime.zig Resolved
The slab-free loops in deinit and shrink were not comptime-gated, so
slabFree (and its munmap) got analyzed on Windows where the slab path is
disabled: lld failed with an undefined munmap symbol. The loops are now
behind the platform gate.

The slot count also moves from a build option to StackPool.Config
(stack_pool.slab_slots, default 64, 0 disables slabs at runtime): nothing
in the slab layout needs the count at comptime, only the platform support
does, so the comptime slab_enabled splits into comptime slab_supported
(platform and pointer width) plus the runtime config check. One knob
instead of two, reachable from RuntimeOptions, and the fallback-path test
now runs on every platform by constructing a pool with slab_slots = 0
instead of being skipped wherever slabs exist.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/coro/stack_pool.zig (1)

385-391: 🚀 Performance & Scalability | 🟠 Major | 🏗️ Heavy lift

Avoid a linear slab-owner lookup on each release.

release calls slabOfLocked for every slab-backed stack. slabOfLocked scans the full slab chain while holding mutex. With N releases across S slabs, this can require O(N*S) locked work. Large bursts can therefore cause quadratic pool contention.

Record slab ownership when carving a slot, or use an address-indexed lookup, so the release path does not scan all slabs.

🤖 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 385 - 391, Replace the full-chain scan
in slabOfLocked, which is used by release, with constant-time slab ownership
tracking. Record the owning Slab when carving each stack slot and make release
retrieve that ownership directly, or maintain an address-indexed lookup updated
with slab allocation and removal; preserve mutex safety and existing ownership
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.

Outside diff comments:
In `@src/coro/stack_pool.zig`:
- Around line 385-391: Replace the full-chain scan in slabOfLocked, which is
used by release, with constant-time slab ownership tracking. Record the owning
Slab when carving each stack slot and make release retrieve that ownership
directly, or maintain an address-indexed lookup updated with slab allocation and
removal; preserve mutex safety and existing ownership behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 4bf2d503-5c77-4076-85a4-973d621d03bf

📥 Commits

Reviewing files that changed from the base of the PR and between 1b1a0f1 and 17b69f7.

📒 Files selected for processing (2)
  • docs/changelog.md
  • src/coro/stack_pool.zig
🚧 Files skipped from review as they are similar to previous changes (1)
  • docs/changelog.md

An errdefer only covers errors raised after it, so a mid-loop
OutOfMemory inside prewarm() leaked the slabs it had already reserved.
Also document that the shrink guard's saturating durationTo makes stale
cross-loop timestamps skip a pass rather than run one early.

Reported by review on #634.
Acquire walked the slab chain looking for a free slot and release walked
it again in slabOfLocked to find the slot's slab: both O(slabs), both
under the pool mutex, and a workload freeing into old slabs paid the
full chain twice per stack lifetime (157 entries at 10k live stacks).

Acquire now pops from a partial list threading exactly the slabs that
have free slots (linked on the release that makes a slab non-full,
unlinked on the acquire that empties it or the shrink pass that unmaps
it). The LIFO order keeps load concentrated on recently active slabs, so
the drain-toward-empty property the shrink pass relies on is preserved.

Release finds the slot's slab through an owner tag: every POSIX stack
reserves 16 bytes above `base` at the very top of its committed region,
written at carve time with the owning slab (0 for an individually
mapped stack) and read back with one load at release. The coroutine's
stack pointer starts at `base` and grows down, so the word survives the
coroutine's lifetime; the initial commit is floored at one page so the
tag always has committed memory. slabOfLocked stays as a debug-build
cross-check and test helper.

Benchmarks hold: sleep 10ms x 10k -28%, spawn -15% vs main.
@lalinsky

lalinsky commented Aug 1, 2026

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@lalinsky
lalinsky merged commit 7f4a4a1 into main Aug 1, 2026
28 checks passed
@lalinsky
lalinsky deleted the stack-slab branch August 1, 2026 06:10
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.

Use slab allocation for coroutine stacks to avoid per-task mmap/munmap overhead

1 participant