Skip to content

feat(vmpool): time Destroy's sub-phases behind SH_DIAG_PHASES (#258) - #317

Merged
pdettori merged 2 commits into
rossoctl:mainfrom
pdettori:feat/258-destroy-subphases
Sep 22, 2026
Merged

pdettori merged 2 commits into
rossoctl:mainfrom
pdettori:feat/258-destroy-subphases

Conversation

@pdettori

Copy link
Copy Markdown
Member

Part of #258, Task 3.1. Instrumentation only — no behaviour change, nothing formatted when
phaseLog is nil.

Destroy is the largest phase of an Exec and was the only one with no internal visibility. Task
1.3's re-run measured it at 36.77 ms (c=4), 65.06 ms (c=16) and 164.27 ms (c=64) — growing 4.5x
across a 16x concurrency range while Resume stayed at ~24-28 ms and Run at ~4-5 ms. Since
throughput = slots / per-Exec total predicts every measured point within 3-4%, this phase is
directly on the throughput path.

Adds kill_us, wait_us, removeall_us, cgroupwait_us, cgrouprmdir_us and a total, in the
same shape and behind the same gate as the existing restore phases so aggregate tooling parses
both identically. Field names are asserted by a test, because they are parsed downstream and a
silently renamed field reads there as a missing phase rather than as an error.

What it found (full data on #258)

slots kill wait removeall cgroupwait cgrouprmdir total
4 0.01 33.91 1.08 0.04 2.15 37.19
16 0.01 48.30 1.47 0.05 15.53 65.36
64 0.03 55.65 1.75 0.07 195.52 253.02

The sub-phases sum to the total exactly at every point — no unmeasured residue.

wait_us is the fixed cost and barely scales (1.6x across 16x concurrency), consistent with a
SIGKILLed Firecracker needing its 256 MiB MAP_SHARED address space torn down before it can be
reaped. cgrouprmdir_us grows 91x and is 77% of Destroy at 64 slots.

Why the cgroup split earned its place: it exposed that nr_dying_descendants under the VM
slice is 12,399 with zero live children. Those are directories #255's fix already rmdir'd
whose kernel structures are pinned by memory charges (jailer gets --cgroup memory.max= per VM).
So #255 fixed the directory leak but a kernel-side accumulation with the same shape of
consequence remains, rmdir alone does not reclaim it, and cgroup cost therefore depends on
cumulative VMs since boot. That is already visible: c=64 measured 0.78x here running last
versus first in the earlier sweep, with 0 stale directories both times.

cgroupwait_us came out at 0.04-0.07 ms, confirming waitForCgroupEmpty's fixed 10 ms sleep
never fires — cmd.Wait has already reaped the VMM. That was worth measuring rather than
assuming, since the equivalent assumption about waitForUnixSocket was wrong (#315).

Verification

go test ./... 9 packages exit 0; go vet, gofmt, make lint clean. Two tests: the phase line
carries every field and the id, and nothing is emitted with SH_DIAG_PHASES unset.

The prediction was recorded in the commit message before measuring. It was right about wait_us
dominating and about kill/removeall/cgroupwait, and wrong about the cgroup cost — predicted
~4.5 ms flat, measured up to 195.52 ms and scaling. That error is the useful part of the result.

🤖 Generated with Claude Code

…tl#258)

Destroy is the largest phase of an Exec and was the only one with no internal
visibility. Task 1.3's re-run measured it at 36.77 ms (c=4), 65.06 ms (c=16) and
164.27 ms (c=64) -- growing 4.5x across a 16x concurrency range while Resume stayed
at ~24-28 ms and Run at ~4-5 ms. Since `throughput = slots / per-Exec total` predicts
every measured point within 3-4%, this phase is directly on the throughput path.

Adds `kill_us`, `wait_us`, `removeall_us`, `cgroupwait_us`, `cgrouprmdir_us` and a
total, emitted as one line per Destroy behind SH_DIAG_PHASES -- the same shape and the
same gate as the existing restore phases, so a run's aggregate tooling parses both the
same way. Field names are asserted by a test, because they are parsed downstream and a
silently renamed field reads there as a missing phase rather than as an error.

The cgroup work is split into wait and rmdir deliberately. `waitForCgroupEmpty` sleeps
a FIXED 10 ms between reads -- the same pattern rossoctl#304 removed from `waitForUnixSocket`
-- and it should never fire here, because `cmd.Wait` has already reaped the VMM so
`cgroup.procs` should be empty on the first read. That is exactly the kind of
assumption that turned out to be wrong for `waitForUnixSocket` (rossoctl#315), so it is
measured rather than asserted.

No behaviour change: instrumentation only, and nothing is formatted when phaseLog is
nil.

Prediction recorded before measuring, so the result can disagree with it:

  wait_us       50-60 ms, dominant -- a SIGKILLed Firecracker holding a 256 MiB
                MAP_SHARED guest mapping must have that address space torn down by
                the kernel before the process is reaped
  cgroup*_us    ~4.5 ms combined, inferred from the c=4 regression after rossoctl#314
                added it (32.28 -> 36.77 ms)
  removeall_us  < 1 ms -- a 12-op jail-lifecycle microbenchmark ran at 13,961 ops/s
                (~0.07 ms), ~500x too fast to explain the total
  kill_us       negligible -- one signal to a process group

If `removeall_us` dominates instead, the cause is the workspace ext4 image: the guest
wrote to a host file through a MAP_SHARED mapping, and unlinking it may force a flush.

Verified: `go test ./...` 9 packages exit 0; `go vet`, `gofmt`, `make lint` clean.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>

@mrsabath mrsabath left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

Instrumentation-only change, tightly scoped (30 lines of production code), and it earns its keep — the decomposition it enables is what found cgrouprmdir_us growing 91x and the 12,399 nr_dying_descendants with zero live children, which is a materially different finding than #255's directory leak.

Shape and gate match the existing restore phases line exactly, so aggregate tooling parses both identically. Sub-phases are contiguous and phaseStart is set before the cmd != nil branch, so the parts-sum-to-total claim in the description holds structurally, not just empirically. I particularly value that the prediction was committed before measuring and that the description leads with the part it got wrong.

No must-fix issues. Two non-blocking comments inline.

Note on commit history (not inline — this is about commits, not a line)

The branch carries cb7c50d (deferred cgroup reaper) and ea6e1ad (its exact revert — verified: 0+/232- reversing 232+/0-, all three files). The net diff is the instrumentation alone, which is exactly what the PR describes, so this is not a correctness concern. Flagging only so the merge is squashed or the pair is dropped by a rebase: landing both into main leaves a feature and its revert in history for a change that ships neither.


Areas reviewed: Go (vmpool launcher), tests, commit conventions
Commits: 3 commits, all signed off; includes one commit and its exact revert
CI status: passing (13/13)

// Sub-phase timing (#258 Task 3.1). Destroy is the largest phase of an Exec -- 36.77 ms
// at c=4, 65.06 ms at c=16, 164.27 ms at c=64, growing 4.5x across the sweep while Resume
// and Run stay flat -- and it was the only phase with no internal visibility. Behind
// SH_DIAG_PHASES like the restore phases, so the cost when off is one nil check.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: "the cost when off is one nil check" understates it slightly — the six time.Now() calls below are unconditional, so the cost when off is one nil check plus six time.Now().

The restore path's equivalent comment is precise about exactly this distinction:

The five time.Now() calls are ~100ns against a restore measured in tens of MILLISECONDS, so they are unconditional and only the log line is gated.

That framing is both accurate and makes the same point (the cost is negligible against a phase measured in tens of ms). Worth matching it here rather than the stronger claim, since the two comments will be read side by side.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 9aaa9ac. Reworded to match the restore path's framing verbatim in structure:

Behind SH_DIAG_PHASES like the restore phases: the six time.Now() calls are ~100ns against a Destroy measured in tens of MILLISECONDS, so they are unconditional and only the log line is gated.

Six is right — phaseStart, killStart, waitStart, removeAllStart, cgWaitStart, cgRmStart.

vm := &firecrackerVM{id: "vm-78", key: "run-1", jailRoot: jailRoot}
if err := vm.Destroy(); err != nil {
t.Fatalf("Destroy: %v", err)
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TestDestroyEmitsNothingWithoutDiagPhases asserts only that Destroy returns no error — it never checks that nothing was emitted.

It is a genuine guard (a Destroy that formatted unconditionally would nil-deref here), and the comment's reasoning about the hot path is right. But the name promises an assertion the body does not make: if a later change emitted the line via log.Printf directly instead of through phaseLog, this test would still pass while the thing it is named for had broken.

Cheapest fix keeps the name honest — a counting stub rather than nil:

calls := 0
phaseLog = func(string, ...any) { calls++ }
// ... after Destroy:
if calls != 0 {
    t.Errorf("Destroy emitted %d phase lines with SH_DIAG_PHASES unset, want 0", calls)
}

Though that no longer exercises the nil path, which is the one that would actually panic — so ideally both: keep this test as-is but rename it to say it guards the nil path, and add the counting variant for the "emits nothing" claim.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The diagnosis is right and the split is in 9aaa9ac, but the counting stub can't work here — worth writing down why, since it's a property of the gate rather than of the test.

phaseLog is the gate. diag.go sets it once, in init(), and only when SH_DIAG_PHASES=1:

var phaseLog func(format string, args ...any)

func init() {
	if os.Getenv("SH_DIAG_PHASES") == "1" {
		phaseLog = log.Printf
	}
}

So a non-nil phaseLog is diagnostics being on. phaseLog = func(string, ...any) { calls++ } would satisfy if phaseLog != nil, Destroy would emit as designed, and calls would be 1 — the assertion would be counting the enabled path and requiring it to stay silent.

Took your "ideally both", with the second test asserting against the destination instead:

  • TestDestroyToleratesANilPhaseLog — the old body, renamed to say what it guards.
  • TestDestroyEmitsNothingWithoutDiagPhases — phaseLog nil, standard logger captured via log.SetOutput, asserts the buffer is empty. That's where phaseLog points when the env var is set, so it's the right surface, and it keeps the nil path exercised.

It also catches the specific regression you named, which is the part I checked rather than assumed. Replacing the gate with an unconditional log.Printf:

--- PASS: TestDestroyToleratesANilPhaseLog (0.00s)
=== RUN   TestDestroyEmitsNothingWithoutDiagPhases
    launcher_firecracker_test.go:515: Destroy logged "vmpool: destroy phases id=vm-79 kill_us=0
    wait_us=0 removeall_us=49 cgroupwait_us=139 cgrouprmdir_us=190 total_us=379\n" with
    SH_DIAG_PHASES unset, want nothing
--- FAIL: TestDestroyEmitsNothingWithoutDiagPhases (0.00s)

The nil-path test passes through that regression, which is the gap you described, now covered. The new test sets cgroupDir so every sub-phase runs, including the branch that emits. log.SetOutput/SetFlags are restored in t.Cleanup; nothing in the package uses t.Parallel, so swapping the default logger is safe.

pdettori added a commit to pdettori/moca that referenced this pull request Sep 22, 2026
…soctl#317 review)

Two review comments, both about the accuracy of claims rather than behaviour. No production
logic changes.

The Destroy sub-phase comment said the cost when diagnostics are off is "one nil check". It is
one nil check plus six unconditional `time.Now()` calls. Reworded to the framing the restore
path already uses, since the two comments sit in the same file and get read together: the calls
are ~100ns against a phase measured in tens of milliseconds, so they are unconditional and only
the log line is gated.

`TestDestroyEmitsNothingWithoutDiagPhases` asserted only that Destroy returned no error -- the
name promised an assertion the body never made. Split in two:

  - `TestDestroyToleratesANilPhaseLog` keeps the old body under a name that says what it
    guards. A nil phaseLog is the path every production Exec takes and the one that would
    nil-deref, so it is worth a test of its own.
  - `TestDestroyEmitsNothingWithoutDiagPhases` now captures the standard logger and asserts it
    stays empty.

The review suggested a counting `phaseLog` stub for the second. That cannot work here: a
non-nil `phaseLog` IS diagnostics being on (diag.go sets it once, in init, from
SH_DIAG_PHASES), so a stub would be counting the enabled path and asserting it stays silent.
Asserting against the destination instead -- the standard logger, which is where `phaseLog`
points when the env var is set -- tests the same claim and additionally catches the regression
the reviewer named and a stub would miss: a later change emitting via `log.Printf` directly,
bypassing the gate.

That was verified rather than assumed. Temporarily replacing the gate with an unconditional
`log.Printf` fails the new test on the emitted line and leaves the nil-path test passing, which
is exactly the gap the review described.

Verified: `go test ./...` 9 packages exit 0; `go vet`, `gofmt`, `make lint` clean.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…soctl#317 review)

Two review comments, both about the accuracy of claims rather than behaviour. No production
logic changes.

The Destroy sub-phase comment said the cost when diagnostics are off is "one nil check". It is
one nil check plus six unconditional `time.Now()` calls. Reworded to the framing the restore
path already uses, since the two comments sit in the same file and get read together: the calls
are ~100ns against a phase measured in tens of milliseconds, so they are unconditional and only
the log line is gated.

`TestDestroyEmitsNothingWithoutDiagPhases` asserted only that Destroy returned no error -- the
name promised an assertion the body never made. Split in two:

  - `TestDestroyToleratesANilPhaseLog` keeps the old body under a name that says what it
    guards. A nil phaseLog is the path every production Exec takes and the one that would
    nil-deref, so it is worth a test of its own.
  - `TestDestroyEmitsNothingWithoutDiagPhases` now captures the standard logger and asserts it
    stays empty.

The review suggested a counting `phaseLog` stub for the second. That cannot work here: a
non-nil `phaseLog` IS diagnostics being on (diag.go sets it once, in init, from
SH_DIAG_PHASES), so a stub would be counting the enabled path and asserting it stays silent.
Asserting against the destination instead -- the standard logger, which is where `phaseLog`
points when the env var is set -- tests the same claim and additionally catches the regression
the reviewer named and a stub would miss: a later change emitting via `log.Printf` directly,
bypassing the gate.

That was verified rather than assumed. Temporarily replacing the gate with an unconditional
`log.Printf` fails the new test on the emitted line and leaves the nil-path test passing, which
is exactly the gap the review described.

Verified: `go test ./...` 9 packages exit 0; `go vet`, `gofmt`, `make lint` clean.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
@pdettori
pdettori force-pushed the feat/258-destroy-subphases branch from 9aaa9ac to a68688b Compare September 22, 2026 14:11
@pdettori

Copy link
Copy Markdown
Member Author

Both inline comments are addressed in a68688b, and the revert pair is dropped.

Commit history: rebased rather than relying on a squash, because this repo merges PRs with merge commits (#312, #313, #314, #315 are all merge commits), so the pair would have landed in main as-is. cb7c50d and ea6e1ad are gone; the branch is now 4cb406c + the review-fix commit. The tree is byte-identical to the pre-rebase head — git diff between them is empty — and go test ./... is 9 packages exit 0 after the rebase. Keeping 4cb406c as its own commit preserves the prediction recorded in its message before measuring, which a squash body would have flattened.

Comment wording: now matches the restore path's framing, and says six time.Now() calls rather than "one nil check".

Test: split into TestDestroyToleratesANilPhaseLog (old body, honest name) and a rewritten TestDestroyEmitsNothingWithoutDiagPhases that captures the standard logger and asserts it stays empty. The counting-stub form couldn't work — a non-nil phaseLog is diagnostics being on, so it would have counted the enabled path — details in the thread. The new test does fail on the log.Printf-bypassing-the-gate regression you named; I checked that by introducing it rather than assuming.

Verified: go test ./... 9 packages exit 0; go vet, gofmt, make lint all clean.

@pdettori
pdettori merged commit 0148a17 into rossoctl:main Sep 22, 2026
13 checks passed
@pdettori
pdettori deleted the feat/258-destroy-subphases branch September 22, 2026 14:19
pdettori added a commit to pdettori/moca that referenced this pull request Sep 22, 2026
…e per VM (rossoctl#258)

Implements the design merged in rossoctl#318, on top of rossoctl#317's sub-phase instrumentation.
jailer is given only --parent-cgroup, pointing at a cgroup the pool created and
bounded; --cgroup, the flag that CREATES a per-VM cgroup, is no longer passed.

MEASURED ON METAL, c=64, 400 iters/slot:

  throughput   182.50 -> 593.11 Exec/s   3.25x
  Destroy      253.02 -> 60.25 ms        0.24x
  cgroup work  195.52 -> 0.047 ms        the release is a slice append
  p95          487 -> 141 ms
  Acquire      69.97 -> 3.96 ms          cold rate 0.508 -> 0.139
  host CPU     16.9% -> 67.4%            the work now reaches the cores

Unlike the deferral attempt, the time did NOT reappear elsewhere: per-Exec total went
342.93 -> 102.64 ms. The work is gone rather than relocated.

SCOPE OF THOSE FIGURES. Each Exec includes TWO host-initiated vsock connections, both
inside the measured phases: one in Resume (mounting /workspace and carrying the
wall-clock correction) and one in Run (the command). Neither is amortised, and neither
can be -- Firecracker closes ESTABLISHED vsock connections on resume, so a connection
carried across a restore is "a connection to nowhere" (guestconn.go). Direction is
host->guest only: the host dials uds_path and sends CONNECT <port> while the guest agent
listens on 1024, so no guest->host listener and no outbound-from-guest setup appears in
these numbers.

WHY. rossoctl#317's decomposition made the per-VM cgroup rmdir the largest single cost in an
Exec -- 2.15 / 15.53 / 195.52 ms at 4 / 16 / 64 slots, 91x growth, 77% of Destroy at the
top, because cgroup removal is kernel-serialised. Two cheaper fixes were measured and
rejected first: deferring the rmdir conserves the time into Acquire and makes 64 slots
worse, and reclaiming charges before rmdir hangs worker startup. The churn also parked
12,400+ dying cgroups, which degraded the rig ~24% at 64 slots over a session.

A FREE LIST, NOT A SIZED POOL. acquire pops or mints, release pushes back, so the
high-water mark is the peak concurrent VM count without anything predicting it. Observed
182 / 48 / 12 dirs at 64 / 16 / 4 slots -- i.e. slots x (1 + StandbyDepth), which
corrects the design note's estimate -- against ~26,000 create/destroy cycles per rung.

D1's BOUND IS KEPT (rossoctl#318 section 4, option D). memory.max = PerVMBytes moves from
jailer's --cgroup to the pool, so the figure admission control charges still applies to
every VM. Safe because a live VM cgroup charges ~1 MiB against a 288 MiB limit --
measured, 0 of 306 samples near it -- since the snapshot's memfile is mlocked by the
WORKER and hardlinked to stay one shared page-cache object. The relocated invariant is
pinned by the same test that pinned it before, rewritten rather than deleted, and that
test now also asserts --cgroup is ABSENT, which is what would silently restore the churn.

TWO GUARDS, both failing closed:

  - release refuses to reuse a cgroup whose cgroup.procs is non-empty (raised in rossoctl#318
    review). A stray child that escaped the process group would otherwise be handed to
    the next tenant, inside its memory bound. It leaks, logs and counts instead.
  - release also DROPS a cgroup whose directory has vanished. readCgroupProcs reports a
    missing path as (nil, nil), indistinguishable from "empty", so without this a
    disappeared cgroup would return to the free list and acquire would hand jailer a
    --parent-cgroup that does not exist. Reachable: clearing the slice by hand is step 3a
    of the metal runbook. Found by reading readCgroupProcs, not by a failure.

SweepOrphans recognises pool-<n> as a third form beside vm-<n> and the CHV scope, so a
dead VMM left inside one by a crashed worker is still killed. This INVERTS the invariant
for the new form and the code says so: a vm-<n> cgroup at startup is an orphan, a
pool-<n> one is normal. Named pool-<n> deliberately -- jailer's --id must stay monotonic,
so reusing that namespace would make a cgroup named vm-3 not correspond to VM vm-3.

REMOVED as production-dead: vmCgroupDirFor and firecrackerVM.cgroupDir. Nothing sets them
once the pool owns placement. Three tests that existed only to exercise them are gone and
their invariants now live in cgroup_pool_test.go, where the behaviour is; the rest are
adapted. Keeping a tested-but-unreachable path would imply per-VM cgroups still exist.

Both tests from rossoctl#317's own review (a68688b) are preserved. TestDestroyEmitsNothing-
WithoutDiagPhases now runs against a real pooled cgroup, which makes it strictly
stronger: it would also catch a release that logged on its happy path, i.e. once per Exec.

Verified: go test ./... -count=1, 9 packages exit 0; -race clean on the pool and the
Destroy paths; go vet, gofmt and make lint clean.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
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.

2 participants