Repository navigation
coro: slab-allocate coroutine stacks with a decaying demand watermark - #634
Conversation
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.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughThe 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. ChangesCoroutine stack allocator
Estimated code review effort: 4 (Complex) | ~60 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 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: 3
🧹 Nitpick comments (2)
src/runtime.zig (1)
418-420: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueThe 60s literal here duplicates
Config.shrink_interval's default and is unreachable.
Executor.initoverwrites this field withself.runtime.options.stack_pool.shrink_intervalwhenever that interval is nonzero, and never adds the timer to the loop when it is zero. So the60swritten here is never the value that runs. If theConfigdefault 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 winThe free-slot scan is O(number of slabs) on every acquire.
acquirewalks the whole slab chain until it finds a slab with a free slot. With many live coroutines the chain grows tolive_stacks / slab_slotsentries. 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 byslabOfLockedon 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:
releasepushes the slab onto it whenfreegoes from null to non-null,acquirepops 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
📒 Files selected for processing (6)
build.zigdocs/changelog.mdsrc/coro/stack.zigsrc/coro/stack_pool.zigsrc/runtime.zigsrc/task.zig
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.
There was a problem hiding this comment.
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 liftAvoid a linear slab-owner lookup on each release.
releasecallsslabOfLockedfor every slab-backed stack.slabOfLockedscans the full slab chain while holdingmutex. WithNreleases acrossSslabs, 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
📒 Files selected for processing (2)
docs/changelog.mdsrc/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.
|
@coderabbitai review |
✅ Action performedReview finished.
|
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-slotsslots (build option, default 64; 0 restores the per-stack allocator), with the slab header in the arena's first committed page andNOHUGEPAGEadvised 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 onemprotectinstead 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_stacksandmax_ageare gone (BREAKING for directStackPool.Configusers). The pool keeps a retain target that ratchets up to each epoch's peak in-use count instantly and halves pershrink_interval(default 60s,.zerodisables 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.prewarmcommits 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
RtlCreateUserStack(TEB/PAGE_GUARD integration)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
MADV_FREEon release: that path was measured too expensive back whenstackRecyclewas 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.