Repository navigation
Add stack pool for coroutine stack reuse - #30
Conversation
- Remove result_ptr field from Coroutine struct to reduce struct size - Add result_ptr to CoroutineData for better encapsulation of execution data - Improve type safety: result_ptr is now strongly typed as *FutureResult(Result) - Simplify result setting: eliminate optional checks and casting - All coroutine execution data is now in one place This refactoring maintains the same API while improving the internal design.
- Add parent_context_ptr parameter to Coroutine.init() for complete initialization - Remove parent_context_ptr parameter from switchTo() - now uses stored value - Add Runtime.fromCoroutine() and Runtime.getCurrent() static methods - Remove redundant runtime field from AnyTask (8 bytes saved per task) - Add Task.runtime() utility method using Runtime.fromCoroutine() - Update all runtime access to use new utility methods These changes provide safer coroutine initialization and reduce memory overhead while maintaining clean API design with @fieldParentPtr optimization.
WalkthroughReplaces Coroutine.init with a void setup API and moves coroutine data onto the coroutine stack; introduces a multi-bucket StackPool and integrates it into Runtime for stack acquire/release and periodic cleanup; runtime lookup helpers (fromCoroutine/getCurrent) and Task lifecycle adjusted accordingly. (48 words) Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant App as Application
participant RT as Runtime
participant SP as StackPool
participant T as TypedTask
participant C as Coroutine
App->>RT: spawn(func, args)
RT->>SP: acquire(requested_stack)
SP-->>RT: Stack
RT->>T: allocate TypedTask
RT->>C: setup(Result, func, args, result_ptr)\nassign stack & parent_context
RT-->>App: AnyTask
App->>RT: run()
loop event loop
RT->>C: coro.switchTo()
C-->>RT: yield/complete
RT->>SP: cleanup() (periodic)
end
sequenceDiagram
autonumber
participant C as Coroutine
participant Timer as Timeout
participant RT as Runtime
Note over C,Timer: timedWaitForReadyWithCallback
C->>Timer: start(timeout_ms)
Timer-->>C: timeout
C->>RT: Runtime.fromCoroutine(&coro)
RT->>C: markReady(&coro)
C-->>RT: resume via run loop
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 |
Implements a power-of-2 size-class based stack pool to reduce allocation overhead for coroutines. Key features: - 8 buckets: 64KB, 128KB, 256KB, 512KB, 1MB, 2MB, 4MB, 8MB - Power-of-2 rounding with size calculated via bit shift - Intrusive LIFO free list (zero allocation overhead) - Page-aligned stack allocations - Time-based cleanup (configurable retention and interval) - Default stack size reduced from 4MB to 1MB Stacks are automatically pooled on Task destruction and reused on spawn, with periodic cleanup of stacks idle longer than the retention period (default 60s, cleaned every 10s).
Co-authored-by: Lukáš Lalinský <[email protected]>
Stacks are now returned to the pool as soon as a coroutine completes execution, rather than waiting for the task to be destroyed. This reduces memory pressure and improves stack reuse when JoinHandles are held.
|
@coderabbitai full review |
✅ Actions performedFull review triggered. |
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (3)
src/stack_pool.zig (1)
130-133: Consider handling edge cases in roundToPowerOf2.While unlikely in practice,
std.math.ceilPowerOfTwocan fail ifsizewould overflow when rounded (e.g., size > 2^63 on 64-bit systems). Thecatch unreachablecould panic in these extreme cases.Consider adding a defensive assertion:
fn roundToPowerOf2(size: usize) usize { if (size <= MIN_STACK_SIZE) return MIN_STACK_SIZE; + assert(size <= MAX_POOLED_SIZE * 2); // Reasonable upper bound return std.math.ceilPowerOfTwo(usize, size) catch unreachable; }src/coroutines.zig (1)
303-341: LGTM: Well-structured setup function with one suggestion.The
setupfunction cleanly replacesinitby operating on a pre-allocated stack. The stack layout calculation (Lines 326-337) and context initialization (Line 340) are correct.Consider adding a defensive assertion before unwrapping
self.stackon Line 326:+ assert(self.stack != null); // Ensured by caller (Runtime.spawn) const stack = self.stack.?; // Stack must be non-null during setupsrc/runtime.zig (1)
461-471: Add debug-mode assertion in fromCoroutine (src/runtime.zig:462)
All coroutine initializations setparent_context_ptr = &self.main_context, but this assumption is fragile; guard it by asserting in Debug mode:if (builtin.mode == .Debug) assert(coro.parent_context_ptr == &rt.main_context);
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
src/coroutines.zig(2 hunks)src/runtime.zig(13 hunks)src/stack_pool.zig(1 hunks)
🔇 Additional comments (14)
src/stack_pool.zig (5)
9-19: LGTM: Well-defined bucket configuration.The power-of-two size classes (64KB to 8MB) with page alignment provide good memory efficiency and reduce fragmentation. The bit-shift calculation in
bucketSizeis clean and correct.
21-39: LGTM: Efficient intrusive free list design.Storing the free list nodes directly in unused stack memory avoids extra allocations and leverages cache locality. The timestamp tracking enables time-based cleanup.
148-159: LGTM: Clean acquire logic with proper fallback.The implementation correctly:
- Rounds up to power-of-two bucket size
- Uses pooled stacks when available
- Falls back to direct allocation for oversized stacks (>8MB)
- Maintains page alignment for all allocations
161-170: LGTM: Symmetric release logic.The release path correctly mirrors the acquire logic by returning pooled stacks to buckets and directly freeing oversized stacks.
172-177: LGTM: Time-based cleanup with warm pool.The cleanup logic balances memory reclamation with warm pool performance by respecting
min_warm_countandretention_msthresholds.src/runtime.zig (6)
15-27: LGTM: Clean integration of stack pool configuration.The
stack_poolfield inRuntimeOptionsfollows the existing pattern forthread_pooland properly exposes the pool's configuration options.
183-191: LGTM: Defensive double-free prevention.The check on Line 187 defensively guards against double-release, even though the stack should already be released when the coroutine becomes dead (see Lines 703-707). This defensive programming is good practice.
499-500: LGTM: Proper stack pool lifecycle management.The stack pool is correctly initialized in
Runtime.init(Line 499) with the provided options and cleaned up inRuntime.deinit(Line 532), ensuring no leaks.Also applies to: 531-532
557-577: LGTM: Robust stack acquisition with proper error handling.The spawn logic correctly:
- Acquires a stack from the pool with the requested size (Line 558)
- Releases the stack on error via
errdefer(Line 559)- Initializes the coroutine with the acquired stack (Line 569)
- Calls the new
setupAPI (Line 577)
671-676: LGTM: Time-based periodic cleanup.The cleanup logic runs every
cleanup_interval_ms(default 10s) to reclaim idle stacks based onretention_ms(default 60s). This prevents unbounded memory growth while maintaining a warm pool for performance.
703-707: LGTM: Immediate stack release on coroutine death.Releasing the stack as soon as the coroutine becomes dead (Line 705) and nulling the pointer (Line 706) minimizes memory footprint and enables the defensive check in
destroyFn(Lines 186-189).src/coroutines.zig (3)
298-301: LGTM: Clean API evolution to external stack management.The changes enable external stack management by the pool:
contexthas a default value since it's initialized insetupstackis optional since it's managed by the caller- The state machine remains unchanged
343-349: LGTM: Simplified switchTo signature.Removing the
parent_context_ptrparameter (Line 343) simplifies the API sinceparent_context_ptris now always set during coroutine initialization.
19-19: Verify default coroutine stack size adequacyDefault stack size reduced from 4 MB to 1 MB (2 MB on Windows); this may overflow deep-call or large-frame coroutines. Confirm existing workloads run safely under the new default or mandate explicit
stack_sizeoverrides.
…ds the four completion defects of the two outside reviews
## Problem
Two rounds of outside review found three serious defects, and one more, that
about 150 hand-written mutants and tests had missed: round 1 finding 1 (an
empty datagram moved the byte ring's head), round 1 finding 2 (an op woken
by a close ran against the socket that reused its fd number), round 2 F1 (a
batch entry completed twice after a group callback cancelled it) and round 2
F2 (a woken pipe receive reported end of file). All are in how ops are
completed, woken, cancelled and closed, or in rare shapes. The two model
tests in `sim.zig` check storage only. Nothing checked ops against a model.
## Changes
- New `src/sim_op_model_test.zig`, two tests:
- `sim: op model: datagram sockets and a pipe under random sends,
receives, polls, cancels, race groups, close and reopen` (the parent),
which runs the same name `, in a child process`.
- One sim run per seed with a bare `ev.Loop` (no runtime), four datagram
sockets and one pipe. 14 step kinds: ev send, layer send, ev receive
(parks when empty), layer receive, layer poll, ev poll (read or write),
pipe send, pipe receive, cancel (an op or a whole group), race group of
2 or 3 members (deferred and not), close (layer or ev), open (reuses the
fd number), SO_RCVBUF, and clock (one poll, or polls until the clock
has moved by 0.2 to 10 ms).
- A group callback that runs inside a poll submits new ops into the slots
it just freed ("follow-ups"), mostly of the same type, so a new op sits
at the address of a member that may still be in the harvest's batch.
This is item 4 of the brief (report 15's gap).
- The model is byte strings, queues, ports and pending ops. It shares no
helper with the sim. The header comment has what it checks, the rules
the generator keeps so the model has one answer, and what it does not
reach.
- The child prints `op model: seed S step K` before each step, so a crash
anywhere names the seed and step; the parent prints the last one.
`ZIO_OP_MODEL_SEED` replays one seed, `ZIO_OP_MODEL_STEPS` sets the
length (default 8 seeds x 5000 steps).
- It fails when any step kind or any of 16 case counters is zero: a case
that never ran is a hole, not a pass.
- `src/sim.zig`: `testPipeBuffered` (test only) so the test compares each
pipe end's level with the model after every step; the child-process
helpers (`death_child_env`, `isDeathChild`, `noCoreDump`, `childDone`,
`checkDoneMarkers`) are `pub`; the new file is imported in the test block.
No change to a build without sim: all of it is test code.
## The four defects, with each fix reverted (ran)
Each in a scratch clone of this tree with only the fix's code reverted (the
tests that came with it stay). 7c0c22e reverts cleanly with `git revert`;
the other three conflict in `sim.zig` tests added later, so their code
hunks were reverted by hand: 3727c95 the old `ring_head` line; 1b2d7ce the
harvest's `buf[i].closed` check and the close's `dgram_closed` wake; 794ce5d
the `isLive` skip and the old `takeOpId(c) orelse buf[i].id`. The default
run (8 seeds x 5000 steps), then the failing seed alone, 3 runs each:
| fix reverted | found at | what it printed |
|---|---|---|
| 3727c95, round 1 finding 1 | seed 3, step 772 | `d_recv op lalinsky#539: buffer 0 holds other bytes than the model's (721 bytes from offset 0)` |
| 1b2d7ce, round 1 finding 2 | seed 1, step 1927 | `d_recv op #1223 was due before poll 844 and has not completed` |
| 794ce5d, round 2 F1 | seed 1, step 21 | `panic: reached unreachable code` (the child's last step line names it) |
| 7c0c22e, round 2 F2 | seed 1, step 133 | `p_recv op lalinsky#30 (waited) completed .{ .n = 0 } on an open pipe with nothing buffered` |
Each seed alone failed at the same step in 3 of 3 runs.
Finding 1 needs seven events in order on one socket (only empty datagrams
left after a receive, a datagram with bytes lands, the empty one is
received, another lands, ...). A first version did not find it: 1886 of
3003 datagrams went to ports with no socket, and the op slots were full in
7164 steps because one poll moves the clock only to the next due op. The
test now aims 7 of 8 sends at an open socket and has the clock step that
moves a fixed time. Counters `only_empty_left` (283) and
`landed_behind_empty` (107) show the start of that shape is reached.
## Mutants (ran, T/mut/run.py, all on this test)
- PO1, `isLive` compares the pointer only: KILLED, `sim: op 34 completed
but not live`.
- PO2, `isLive` and `endOp` compare the pointer only: KILLED, `sim: 9 ops
due but only 8 live`.
- Control: PO1 and PO2 with the follow-ups turned off. Both pass every
model check over all 8 seeds and fail only on the test's own guard,
`followups_into_canceled_due` is 0. So the follow-ups are what kill them.
- No live check in the harvest: KILLED. A drain that wakes no sender, a
copy that wakes no receiver: KILLED at the end check ("still waits with
nothing to wait for"). A cancel that leaves a datagram op parked: KILLED
(`two ev ops parked`). A close that wakes nothing: KILLED. A receive that
reports the full length: KILLED. No byte limit: KILLED.
- No packet limit: SURVIVED, as expected: queues here stay far below 1024.
The datagram queue model test is the instrument for it (next commit).
## Counts of a passing run (8 seeds x 5000 steps, about 0.15 s)
- Steps by kind: ev_send 4063, layer_send 1293, ev_recv 3696, layer_recv
1306, layer_poll 942, ev_poll 1643, pipe_send 3356, pipe_recv 3351,
cancel 2137, group 3204, close 1059, open 1049, rcvbuf 997, clock 8373.
- Skipped because the rules forbade it then: ev_send 557, ev_recv 784,
layer_send 578, open 445 (no socket closed), the rest under 300. Skips for
a full slot pool: 0.
- ops 25509, parked 3121, canceled 983, closed_hit 261, reused_number_ops
16506, closed_then_reused 28, groups 2824, f1_shape_groups 1086,
followups 1611, followups_into_canceled_due 475, f2_shape 181.
- datagrams 7550 (2157 empty), truncated 1355, scatter receives 3745,
dropped for the limits 409, no socket 1389, discarded at close 1090,
landed in a socket opened after the send 114, pipe sends parked 411.
## Benefits
- The first instrument that checks ops, not storage: every completion is
checked against a model, once, with its bytes; and every wait must have a
reason at the end, which catches a lost wake.
- A crash is reported with its seed and step, and replays alone.
## Alternatives rejected, and what this depends on
- **Drive ops from tasks with `waitForIo`.** It hides the harvest: a task's
wait makes members deferred, so F1 cannot happen, and the test cannot
cancel or submit inside a harvest.
- **A model that accepts any order of actions in one poll.** Possible, but
a lenient oracle is how a model passes a defect. Instead the generator
keeps the order knowable: a pipe op that will wait is never deferred, one
source per destination per instant, distinct fds in a group.
- **In-process only, with the step in a global the panic prints.** The F1
crash is `unreachable` in `enterCompleted`, which never reaches a sim
hook. A child process sees every crash, and a hang hits its 600 s limit.
- **Settle the end by a count of polls.** Tried first: a send woken at
25.26 ms was due at 30.26 ms, 40 polls ended near 28 ms, and the end check
called a legal wait a lost wake. The end now settles 20 ms of clock time.
- Depends on: the sim lands datagrams only inside a harvest, and the clock
moves only inside a poll, so between polls the model and the sim have
landed the same datagrams (`syncLand`); and a pipe op's delay is at most
5 ms (the liveness check allows 10).
## Statistics
- `src/sim_op_model_test.zig`: new, 1485 lines (`zig fmt`).
- `src/sim.zig`: +14 -5 (one test accessor, five `pub`, one import).
- Sim tests (`-Dtest-filter="sim: "`): 213 of 213 passed, 2 skipped (211
before, plus the two new tests; both listed by name in the verbose run).
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
Implements a power-of-2 size-class based stack pool to reduce allocation overhead for coroutines.
Implementation Details
Stack Pool (
src/stack_pool.zig):MIN_STACK_SIZE << bucket_indexRuntime Integration:
Runtime.spawn()acquires stacks from poolTask.destroyFn()returns stacks to poolRuntime.run()performs time-based cleanup every 10sRuntimeOptions.stack_poolBenefits
Test Plan
Summary by CodeRabbit
New Features
Refactor
Chores