Skip to content

perf(vmpool): reuse per-VM cgroups from a pool instead of creating one per VM (#258) - #319

Merged
pdettori merged 3 commits into
rossoctl:mainfrom
pdettori:feat/258-pooled-vm-cgroups
Sep 22, 2026
Merged

pdettori merged 3 commits into
rossoctl:mainfrom
pdettori:feat/258-pooled-vm-cgroups

Conversation

@pdettori

Copy link
Copy Markdown
Member

Implements the design merged in #318, on top of #317's sub-phase instrumentation. Part of #258.

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

before after
throughput 182.50 593.11 Exec/s 3.25x
Destroy 253.02 ms 60.25 ms 0.24x
cgroup work inside it 195.52 ms 0.047 ms the release is a slice append
p95 487 ms 141 ms
Acquire 69.97 ms 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 — which is the distinction that made
deferral fail and this succeed.

Acquire collapsing and the cold rate falling to 0.139 also means replenishment now keeps up, so
the "replenishment ceiling" framing dissolves once the churn is gone.

Scope of those figures

Each Exec includes two host-initiated vsock connections, both inside the measured phases: one in
Resume (mounting /workspace, 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 here.

Why this, and not something cheaper

#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 built, measured and rejected first (both on #258):

  • deferring the rmdir — time conserved into Acquire (16 slots: −14.76/+14.41), and 64 slots got
    worse (−79/+101, net +24 ms);
  • reclaiming charges before rmdir — reliably hung worker startup.

The churn also parked 12,400+ dying cgroups, which degraded the rig ~24% at 64 slots over a session.

Design points worth reviewing

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

D1's bound is kept (#318 §4, option D). memory.max = PerVMBytes moves from jailer to the pool.
Safe because a live VM cgroup charges ~1 MiB against a 288 MiB limit (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 invariant is pinned by the same test as before, rewritten rather than deleted,
and that test now also asserts --cgroup is absent — the thing that would silently restore the
churn.

Two guards, both failing closed:

  1. release refuses to reuse a cgroup whose cgroup.procs is non-empty (your review point). 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.
  2. 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 hitting it.

SweepOrphans inversion. It recognises pool-<n> as a third form, so a dead VMM left inside one
by a crashed worker is still killed. The code states the inversion explicitly: a vm-<n> cgroup at
startup is an orphan, a pool-<n> one is normal.

Removals, and what happened to their tests

vmCgroupDirFor and firecrackerVM.cgroupDir are production-dead once the pool owns placement,
so they are gone. Three tests existed only to exercise them; their invariants — reuse, ENOENT
tolerance, the bound, the leak guard — now live in cgroup_pool_test.go where the behaviour actually
is. Keeping a tested-but-unreachable path would imply per-VM cgroups still exist.

Both tests from your #317 review (a68688b) are preserved. TestDestroyEmitsNothingWithout- DiagPhases 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.

Verification

check result
go test ./... -count=1 9 packages, exit 0
-race clean on the pool and the Destroy paths
go vet / gofmt / make lint clean
metal, c=64 / 16 / 4 table above; c=4 repeated last came in 1% from first, so the host stayed stable within the session

One caveat on the headline number. It was measured with ~14,000 dying cgroups still present from
earlier work, so 593 is a floor rather than a clean-host figure. Those are page-cache-pinned and
clear with sync; echo 3 > /proc/sys/vm/drop_caches (14,024 → 51 in ~3 s) — no reboot needed, which
matters because a reboot would silently re-enable swap and reset the CPU governor on this rig, and
the driver refuses to run with swap on.

🤖 Generated with Claude Code

…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]>

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

Mamma mia, what a piece of work — 3.25x and the rationale to back it.

The measurement discipline is the best part of this PR. Two cheaper fixes built, measured and rejected before this one, and the "unlike the deferral attempt, the time did not reappear elsewhere" check is exactly what makes 593 Exec/s believable rather than merely hoped-for. --parent-cgroup without --cgroup is the right lever, and asserting the absence of --cgroup in the test is what keeps it that way — bellissimo, that is the assertion that stops this regressing silently in six months.

Three findings, all in acquire's error and reuse paths rather than in the design. One is a blocker with a one-line fix:

  1. must-fix — cgroup_pool.go:89: the minted-- rollback can hand the same pool-<n> to two live VMs under concurrency, which breaks the one-VM-per-bound invariant this whole change rests on.
  2. suggestion — cgroup_pool.go:76: acquire pops a free entry without checking it still exists. cgroup.go:221 asserts that it "re-creates on miss"; it does not.
  3. suggestion — cgroup_pool.go:95: a writeMemoryMax failure strands a created, unbounded cgroup without counting it — the silent accumulation this PR exists to eliminate, on the error path.

Plus two documentation nits inline.

One more, with no anchor line in a hunk: removing vmCgroupDirFor takes away vmCgroupPath's last production caller — cgroup.go:95 is now reached only from cgroup_test.go. By this PR's own standard ("keeping a tested-but-unreachable path would imply per-VM cgroups still exist"), vmCgroupPath and TestVMCgroupPathIsUnderTheParentSlice are now in that same category. Worth either removing them in this PR or saying why the name helper is different from the placement helper.

For what it is worth, I checked whether ParentCgroup set with CgroupMemoryMaxBytes == 0 would now turn a previously-unbounded-but-working config into a hard failure of every restore, since writeMemoryMax rejects <= 0 where firecrackerCgroupArgs used to just omit the flag. validate() already refuses that combination at construction, so there is no regression — perfetto, the guard was already in the right place.

Everything else checks out: readCgroupProcs really does report a missing path as (nil, nil), so guard 2's premise is accurate; every cleanup() call site precedes the firecrackerVM literal, so there is no double-release; and the destroyed early-return keeps Destroy from releasing twice. All 13 CI checks green, single commit, DCO signed.

dir := p.abs(rel)
if err := mkdirAllCgroup(dir); err != nil {
p.mu.Lock()
p.minted-- // not created, so do not claim the name

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.

must-fix — this rollback is correct single-threaded and wrong concurrently. It can hand the same pool-<n> to two live VMs:

A: seq=5, minted -> 6
B: seq=6, minted -> 7, mkdir pool-6 OK   <- B now holds pool-6
A: mkdir pool-5 FAILS -> minted-- -> 6
C: seq=6, minted -> 7
C: mkdirAllCgroup(pool-6) returns nil (it already exists, and is a dir)
C: writeMemoryMax, returns pool-6      <- C now holds pool-6 too

B and C are then two VMMs inside one cgroup sharing one memory.max = PerVMBytes. That is D1 inverted: admission control charged 2 x 288 MiB while the kernel enforces one 288 MiB bound over both, so a ballooning command in B can OOM C's VMM — the outcome spec section 6 mitigation #3 exists to prevent. The fallout is also mis-recorded: whichever destroys first spins 200 ms in waitForCgroupEmpty on the other's pid, then release sees len(pids) > 0 and counts a leak; the second destroy finds it empty and pushes the same rel back onto free, so the cgroup ends up both leaked-counted and reusable.

Reachable, not theoretical. mkdirAllCgroup fails when the parent slice is gone — an operator clearing the slice by hand is step 3a of your own metal runbook — or on EACCES, or when cgroupfs hits a limit, which is likelier on precisely the host carrying 12,400 dying cgroups. Under 64 slots concurrent acquires are the steady state, and if the slice is briefly absent every concurrent mint fails, minted walks backwards several steps, and ids restart low against live holders.

Simplest fix is to delete the rollback entirely: an int counter is free, the name is not, and "do not claim the name" is the part that cannot be made safe without holding mu across the mkdir (which would serialise the very syscall this PR is trying to keep off the critical path). mintedCount() then counts attempts rather than successes — no test in this PR depends on the difference, since none of them exercises a failing mkdir. If the distinction is worth keeping for diagnostics, a second never-decrementing issued counter for name allocation would do it.

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.

Confirmed, and your trace is exactly right — the load-bearing step is that MkdirAll returns nil on an existing directory, so C doesn't fail on B's cgroup, it silently succeeds into it. Fixed in 4a04d86 by deleting the rollback.

Renamed to issued and documented as a name allocator that never goes backwards, with your reasoning in the comment: an int is free, a name is not, and making the rollback safe would mean holding mu across the mkdir — serialising the syscall this change exists to keep off the critical path.

mintedCount() now reports names allocated rather than cgroups created. You were right that nothing depended on the difference; I checked each caller. I did not add the separate issued diagnostic counter you offered, since nothing reads it yet.

On the test: I agree the collision needs concurrency to stage, so I pinned the invariant that prevents it instead. TestCgroupPoolNeverReclaimsANameAfterAFailedMint puts a file where pool-0's directory would go, so the first mint fails and the second must come back as pool-1. With the rollback the second acquire retries pool-0 and fails identically — verified by re-introducing it, which fails the test on "the failed name was reclaimed".

I had also mis-recorded the consequence in my own PR body by calling the two guards "both failing closed". This path wasn't failing closed at all; it was failing into an aliased bound.

func (p *cgroupPool) acquire() (string, error) {
p.mu.Lock()
if n := len(p.free); n > 0 {
rel := p.free[n-1]

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.

suggestion — the pop path has no existence check, which leaves the guard asymmetric: release is careful that the directory must still BE there, but acquire trusts a rel that may have vanished while it sat idle on the free list.

And the idle entries are the ones most exposed to the very scenario guard 2 cites. An idle pooled cgroup is empty, so rmdir on it succeeds; a live VM's cgroup is EBUSY and survives. So an operator clearing the slice by hand (runbook step 3a) removes precisely what is in free and leaves the live ones alone — the guard is watching the half of that event that is less likely to happen.

It does self-heal: acquire hands out a stale rel, the restore fails, cleanup() calls release, the stat fails and the entry is dropped. But that is one failed restore per stale entry, and at 64 slots the free list can hold ~100 of them, so the cost is a burst of failed replenishes rather than none.

cgroup.go:221 also states the property this is missing. "the sweep removing the directory too is harmless because acquire re-creates on miss" is the behaviour I would expect from reading that comment, but mkdirAllCgroup only runs on the mint path, never on a pop.

A stat on the popped rel — fall through to the mint path on miss — costs microseconds against a 60 ms Destroy and would make both the guard symmetric and that comment true.

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.

Confirmed and fixed. The part I had missed is the one you spelled out: idle entries are the most exposed, because an idle pooled cgroup is empty so rmdir succeeds on it while a live VM's is EBUSY and survives. So clearing the slice by hand removes precisely what's in free and leaves the live ones — my release-side guard was watching the less likely half of that event.

acquire now stats the popped rel and, on a miss, rebuilds it under the same name (nothing else can hold it, since it was on the free list). Creation is shared with the mint path in one create helper so both produce a bounded cgroup rather than one that is merely present.

That also makes the cgroup.go claim true. You were right that "acquire re-creates on miss" described behaviour that didn't exist — I'd written the comment describing what I intended rather than what I'd implemented, which is worse than no comment.

TestCgroupPoolRecreatesAPoppedCgroupThatVanished removes the directory while idle and asserts the next acquire hands out something that exists and is bounded.

}
// The bound jailer's --cgroup used to write. Kept here so D1's figure still applies to every
// VM (design note §4): the same PerVMBytes admission control charges.
if err := writeMemoryMax(dir, p.memMax); err != nil {

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.

suggestion — if mkdirAllCgroup succeeded and this fails, the directory exists, is unbounded (no memory.max written), never reaches the free list, is never removed, and is not counted in leaked. The next acquire mints pool-<seq+1>, so pool-<seq> is stranded for the life of the worker.

That is the silent, accumulating dying-cgroup population this PR exists to eliminate, reappearing on the error path — and it sits oddly against the two paths either side of it: the mkdir branch above rolls back deliberately, and release is meticulous that "a leak is counted so it cannot be silent." Here nothing is counted, so the one case that produces an unbounded cgroup is also the one case with no signal.

Either leaked.Add(1) plus a log before returning (matching release's posture — something exists that we are not reusing), or removeCgroupDir(dir) on the way out since nothing has been placed in it yet and the rmdir cost is irrelevant on a path that is already failing. The first is more consistent with the rest of the file.

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.

Confirmed. Took your first option — leaked.Add(1) plus a log — for the consistency reason you gave: release is explicit that a leak must not be silent, and this was the one path that could produce an unbounded cgroup with no signal at all.

I did not also removeCgroupDir it. Rationale: the counter plus log is the part that matters, and an rmdir here would be the only place in the pool that removes a directory, which cuts against the whole design. If it accumulates in practice the count will say so.

TestCgroupPoolCountsALeakWhenTheBoundCannotBeWritten stages it by making memory.max a directory, so the cgroup mkdir succeeds and the write into it cannot — asserting both leaks() == 1 and that it never reaches the free list.

// instead of a host-level OOM lottery whose size-ranked favourites include
// microvm-worker itself. cgroup v2's memory.max accepts a bare byte count (no unit
// suffix), which is what gets written here.
// mkdirAllCgroup creates a cgroup directory. Separated so cgroupPool reads as intent rather than

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 new function landed between writeMemoryMax's doc comment and writeMemoryMax itself, so godoc now reads the whole block above as mkdirAllCgroup's documentation. Net effect: mkdirAllCgroup (a one-line os.MkdirAll) is documented with spec section 6's third mitigation and the host-level-OOM-lottery rationale, and writeMemoryMax — the function that actually implements that mitigation, and the one this PR makes more load-bearing by moving the write out of jailer and into our own code — is left with no doc comment at all.

A blank line before line 333 fixes it. In a file this carefully commented it is worth the one line, since the misattributed paragraph is also the clearest statement anywhere of why the bound exists.

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.

Confirmed — and this is the second time I've done it: #315's vmCgroupDirFor landed between firecrackerCgroupArgs' doc and its declaration in the same way. Worth me treating "inserting a helper above a documented function" as a thing to check rather than a coincidence.

Fixed in 4a04d86 by moving mkdirAllCgroup above the block rather than adding a blank line, so each comment sits on the function it describes. Verified with go doc -u: mkdirAllCgroup now documents itself, and writeMemoryMax has spec §6's mitigation back — which, as you say, is the clearest statement anywhere of why the bound exists, and it belongs on the function that now implements it.

// production path.
cgroupRoot string

// CgroupMemoryMaxBytes is the per-VM cgroup memory.max jailer is told to write via

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 — this doc is now describing the mechanism the PR just removed: memory.max jailer is told to write via --cgroup, and further down on its own ParentCgroup produces no per-VM memory.max at all. After this change jailer is never told to write it and never creates a per-VM cgroup at all; cgroupPool.acquire writes it.

validate()'s error text at line 138 has drifted the same way — "jailer would move the VM into the slice without creating a per-VM cgroup or memory.max." The check is still exactly right (the pool needs memMax > 0 or writeMemoryMax rejects it, which would now fail every restore instead of silently omitting a flag — so the guard matters more than before, not less), but an operator who trips it gets an explanation of jailer behaviour that no longer happens.

Both are the same one-line-each edit, and worth doing in this PR: these two blocks are where the next reader goes to find out who owns the bound, and right now they name jailer.

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.

Confirmed, both updated. CgroupMemoryMaxBytes' doc now says the pool writes the bound and that jailer is never told to create a per-VM cgroup, while keeping the part that hasn't changed: the figure is still PerVMBytes(cfg), the same one admission control charges, so the kernel ceiling and the software gate still agree.

validate()'s text now describes the real failure — "the cgroup pool could not write a memory.max for the VMs it creates, so every restore would fail" — instead of jailer behaviour that no longer happens. And it records your point that the guard matters more now, not less: writeMemoryMax rejects <= 0, so a zero is a hard failure of every restore rather than a silently omitted flag.

Thanks for checking that combination for a regression, incidentally — that's the one I'd have been most likely to ship.

…bounded case (rossoctl#319 review)

Six findings. All reproduced before changing anything; the first is a correctness bug
that only appears concurrently.

MUST-FIX: the mkdir rollback could alias a live holder. acquire rolled `minted` back
when mkdir failed, which is correct single-threaded and wrong concurrently:

  A: seq=5, minted -> 6
  B: seq=6, minted -> 7, mkdir pool-6 OK      <- B holds pool-6
  A: mkdir pool-5 FAILS -> minted-- -> 6
  C: seq=6 -> mkdirAllCgroup(pool-6) returns NIL (it exists, and is a dir)
  C: writeMemoryMax, returns pool-6           <- C holds pool-6 too

Two VMMs then share one memory.max. That is D1 inverted -- admission control charged
2 x PerVMBytes while the kernel enforces a single bound over both -- so a ballooning
command in one can OOM the other's VMM, which is the outcome spec section 6 mitigation
rossoctl#3 exists to prevent. The fallout is mis-recorded as well: whichever destroys first
spins in waitForCgroupEmpty on the other's pid and counts a leak, then the second finds
it empty and pushes the SAME rel back onto free, leaving it both leak-counted and
reusable.

Reachable rather than theoretical: mkdirAllCgroup fails when the parent slice is gone,
which clearing the slice by hand does (metal runbook step 3a), and at 64 slots
concurrent acquires are the steady state.

Fixed by deleting the rollback. The counter is renamed `issued` and documented as a NAME
ALLOCATOR that never goes backwards -- an int is free, a name is not. Making the rollback
safe would mean holding mu across the mkdir, serialising the syscall this change exists
to keep off the critical path. mintedCount() now reports names allocated, which after a
failed mint exceeds the number of cgroups; no test depended on the difference.

Pinned by TestCgroupPoolNeverReclaimsANameAfterAFailedMint. The collision itself needs
concurrency to stage, so the test pins the invariant that prevents it -- a name used by a
failed mint is never handed out again. Re-introducing the rollback fails it.

SUGGESTION: acquire now verifies a popped entry and rebuilds it under the same name if it
vanished. The guard was asymmetric -- release insisted the directory still be there,
acquire trusted a rel that may have disappeared while idle -- and the review pointed out
that idle entries are the MOST exposed: an idle pooled cgroup is empty so rmdir succeeds,
while a live VM's is EBUSY and survives, so clearing the slice removes precisely what is
in `free`. It self-healed at a cost of one failed restore per stale entry, and `free` can
hold ~100 at 64 slots. This also makes isPoolVMCgroupDirName's claim that acquire
"re-creates on miss" true, which it was not.

SUGGESTION: a writeMemoryMax failure now counts a leak and logs. The directory existed,
was UNBOUNDED, never reached the free list and was never removed or counted -- the silent
accumulation this whole change removes, reappearing on the error path, and inconsistent
with release's "a leak is counted so it cannot be silent". Creation is shared by the mint
and rebuild paths in one `create` helper so both produce a BOUNDED cgroup, never one that
is merely present.

NIT: mkdirAllCgroup had landed between writeMemoryMax's doc comment and writeMemoryMax,
so godoc attributed spec section 6's mitigation to a one-line MkdirAll and left the
function that implements it undocumented. Moved above the block. (Same mistake as rossoctl#315's
vmCgroupDirFor placement -- worth noticing as a pattern when inserting helpers.)

NIT: two places still described jailer writing memory.max and creating the per-VM cgroup.
CgroupMemoryMaxBytes' doc and validate()'s error text now say the pool writes it. The
check is unchanged and matters more than before: writeMemoryMax rejects <= 0, so a zero
fails every restore rather than silently omitting a flag.

Also removed, from the no-anchor finding: vmCgroupPath and
TestVMCgroupPathIsUnderTheParentSlice. vmCgroupDirFor was its last production caller, so
by this PR's own standard -- "keeping a tested-but-unreachable path would imply per-VM
cgroups still exist" -- the name helper is in the same category as the placement helper.

Verified: go test ./... -count=1, 9 packages exit 0; -race clean on the pool; go vet,
gofmt and make lint clean; godoc attribution checked with `go doc -u` on both functions.

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

Copy link
Copy Markdown
Member Author

All six addressed in 4a04d86

finding disposition
must-fix — minted-- can alias a live holder fixed, rollback deleted, invariant pinned by a test that fails if it returns
acquire doesn't verify a popped entry fixed — stat, and rebuild under the same name on a miss
writeMemoryMax failure strands an unbounded cgroup fixed — counted and logged, matching release's posture
mkdirAllCgroup doc placement fixed — moved above the block, verified with go doc -u
CgroupMemoryMaxBytes doc + validate() text name jailer fixed — both now say the pool writes it
no-anchor: vmCgroupPath is production-dead removed, with its test

On the blocker

Your trace was right, and the step that makes it bite is that MkdirAll returns nil on an
existing directory — so C doesn't collide loudly, it succeeds silently into B's cgroup. Two VMMs
under one memory.max, with the leak accounting confused on top exactly as you describe.

I'd also mis-recorded it in my own PR body: I called the two guards "both failing closed". This path
wasn't failing closed, it was failing into an aliased bound.

The collision needs concurrency to stage, so the test pins the invariant that prevents it — a name
used by a failed mint is never reissued. Re-introducing the rollback fails it on "the failed name
was reclaimed".

On the asymmetric guard

The observation I'd missed is the one that makes it matter: idle entries are the most exposed,
because an idle pooled cgroup is empty so rmdir succeeds on it while a live VM's is EBUSY and
survives. Clearing the slice removes precisely what's in free. My release-side guard was watching
the less likely half.

And you were right that cgroup.go's "acquire re-creates on miss" described behaviour that didn't
exist. I'd written the comment for what I intended rather than what I'd implemented, which is worse
than having no comment — it's now true.

On vmCgroupPath

Removed, with TestVMCgroupPathIsUnderTheParentSlice. You're right that the standard I applied to
the placement helper applies to the name helper: vmCgroupDirFor was its last production caller,
and leaving a tested-but-unreachable path would imply per-VM cgroups still exist.

Not done, with reasoning

I did not add removeCgroupDir to the writeMemoryMax failure path alongside the count. The
counter plus log is the part that matters, and an rmdir there would be the only place in the pool
that removes a directory — which cuts against the design. If it accumulates, the count will say so.

I also did not add the separate issued diagnostic counter you offered, since nothing reads it yet.

Verification

go test ./... -count=1 9 packages exit 0; -race clean on the pool; go vet, gofmt, make lint clean. Each of the three new tests was confirmed to fail before its fix, and the blocker's fix
was mutation-checked by re-adding the rollback.

The metal numbers in the PR body are unaffected — none of these paths is on the measured happy path.

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

Perfetto — all six addressed, and I checked each one against 4a04d86 rather than taking the commit message's word for it.

finding fix verified
1 must-fix, minted-- aliasing rollback deleted, field renamed issued and documented as a monotonic name allocator create() returns the mkdir error without touching the counter — the alias is gone at the source, not guarded against
2 unchecked pop acquire stats the popped rel and rebuilds under the same name on a miss the rebuild goes through the shared create(), so a recreated cgroup is bounded, never merely present
3 stranded unbounded cgroup leaked.Add(1) + log on a writeMemoryMax failure and the mkdir-failure branch correctly does not count one, since nothing was created
4 nit, godoc mkdirAllCgroup moved above the block attribution correct on both functions now
5 nit, stale docs CgroupMemoryMaxBytes doc and validate()'s text rewritten
6 vmCgroupPath removed with its test nothing newly orphaned: ParentCgroupPath still has a production caller in cmd/microvm-worker/main.go, and fakeSlice is still used by two test files

Extracting creation into one create() shared by the mint and rebuild paths is a better shape than what I suggested — I was thinking of the two paths as separate fixes, and folding them means "a cgroup this pool hands out is bounded" is now enforced in one place instead of asserted twice.

The three new tests are the part I want to single out, because they stage real failures instead of mocking: a file where pool-0's directory goes, so MkdirAll gets ENOTDIR, and memory.max as a directory, so the mkdir succeeds and only the write can fail. That second one is a genuinely elegant way to reach a branch that otherwise needs a full disk. And TestCgroupPoolNeverReclaimsANameAfterAFailedMint is double-guarded — restore the rollback and the second acquire both errors and returns the wrong name — which is what you want from a test pinning an invariant whose real failure mode needs concurrency to stage.

I also take the point about #315's vmCgroupDirFor landing the same way. Two instances of "helper inserted between a doc comment and its function" is a pattern, and go doc -u on the touched functions is a cheap check for it.

One nit inline, which I missed in round 1 and which does not block anything. Bellissimo work — 3.25x with the isolation invariant tightened rather than traded away.

All 13 checks green, both commits signed off, Assisted-By correctly used.

// monotonic (a live VMM holding a jail id is what the collision guard refuses on), so a pooled
// cgroup named vm-3 would not correspond to VM vm-3 and the two namespaces would silently diverge.
// isPoolVMCgroupDirName recognises this form so SweepOrphans still sees a dead VMM inside one.
const pooledCgroupPrefix = "pool-"

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, and one I should have caught in round 1 rather than now.

cgroup.go:89 introduces its const block as "the single authority on what a VM's cgroup DIRECTORY is called under the parent slice", and gives the reason they sit together: "they live together, in the file that has to recognise them, because H1 was a false premise about exactly this." pooledCgroupPrefix is now a fourth name in that category — it names a directory under the same parent slice, and isPoolVMCgroupDirName in that very file has to recognise it — but it lives here instead.

Your doc above already acknowledges the relationship ("Kept beside isPoolVMID and isPoolVMCgroupDirName, which that file documents as..."), so this is not an oversight. The asymmetry is just that the acknowledgment lives in the file that isn't the stated authority, so a reader who goes to cgroup.go:89 for the complete list still gets three names and no pointer to the fourth.

Either direction resolves it: move the const into that block, or add a line to the block's comment saying the pool's own prefix is deliberately separate and why. The second is probably truer to the design, since the reason this name is not vm-<n> — jailer's --id must stay monotonic, so the two namespaces would silently diverge — is itself worth having recorded where the authority is claimed.

Entirely take-or-leave; H1 is the kind of bug that came from names drifting apart, which is the only reason I mention it at all.

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.

Taken, and your reasoning for the pointer is what convinced me to move it instead. Fixed in c1ebaf6.

The argument that decided it is the one you made: the reason this name is not vm-<n> deserves recording where the authority is claimed. Putting the const there records it in the same place and makes "single authority" literally true rather than a claim plus a cross-reference — which matters more than usual for a block whose whole justification is H1.

Moving it surfaced that the asymmetry went one level deeper. isPooledCgroupDirName — the code that recognises the fourth name — also lived beside the pool, while the other two recognisers are in cgroup.go. A name and the code that recognises it are exactly the pair H1 got wrong, so both are now in the authority file. cgroup_pool.go keeps lifecycle only: acquire, release, the free list.

The block header now says four and names cgroupPool as the fourth consumer beside pool.nextIDLocked and launcher_chv.go's Restore. Two things that were only in the pool's own doc are now recorded at the authority:

  • why it is not vmIDPrefix — jailer's --id must stay monotonic, so a reused cgroup named vm-3 would stop corresponding to VM vm-3 and the namespaces would drift silently. That is this block's own failure mode, in a form that reads as correct.
  • that pool-<n> inverts the invariant the other names carry — a vm-<n> cgroup at startup is an orphan to sweep, a pool-<n> one is normal, and what must not survive a restart is a process inside one rather than the directory.

No behaviour change: same names, same recognition, same tests. And you were right that this belonged in round 1 — I wrote that acknowledgment in cgroup_pool.go ("Kept beside isPoolVMID and isPoolVMCgroupDirName, which that file documents as...") which shows I saw the relationship and then documented it in the wrong file, which is the more annoying version of the mistake.

…he naming authority (rossoctl#319 review)

cgroup.go's const block calls itself "the single authority on what a VM's cgroup
DIRECTORY is called under the parent slice", and explains why the names live together:
"in the file that has to recognise them, because H1 was a false premise about exactly
this". pooledCgroupPrefix was a fourth name in that category living in cgroup_pool.go,
so a reader who went to the stated authority for the complete list got three names and
no pointer to the fourth.

Review offered two fixes -- move the const in, or leave it and add a pointer -- and
leaned toward the pointer, on the grounds that the reason this name is not vm-<n>
deserves recording where the authority is claimed. That reasoning is what persuaded me
to move it instead: putting the const there records the rationale in the same place AND
makes "single authority" literally true rather than a claim plus a cross-reference.

Moving it also surfaced that the asymmetry went one level deeper. isPooledCgroupDirName
-- the code that RECOGNISES the fourth name -- also lived beside the pool, while the
other two recognisers sit in cgroup.go. A name and the code that recognises it are
precisely the pair H1 got wrong, so both are now in the authority file and the comment
says why. cgroup_pool.go keeps lifecycle: acquire, release, the free list.

The block's header now says four rather than three and names cgroupPool as the fourth
consumer, alongside pool.nextIDLocked and launcher_chv.go's Restore.

Two things recorded at the authority that were only in the pool's own doc before:

  - why the name is not vmIDPrefix -- jailer's --id must stay monotonic, because a live
    VMM holding a jail id is what the collision guard refuses on, so a reused cgroup
    named vm-3 would stop corresponding to VM vm-3 and the namespaces would drift
    silently. That is the failure mode this block exists to prevent, in a form that
    reads as correct.
  - that pool-<n> INVERTS the invariant the other names carry: a vm-<n> cgroup present
    at startup is an orphan to sweep, a pool-<n> one is normal, and what must not
    survive a restart is a process inside one rather than the directory.

No behaviour change: same names, same recognition, same tests.

Verified: go test ./... -count=1, 9 packages exit 0; go vet, gofmt and make lint clean.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
@pdettori
pdettori merged commit 61bd8a6 into rossoctl:main Sep 22, 2026
13 checks passed
@pdettori
pdettori deleted the feat/258-pooled-vm-cgroups branch September 22, 2026 15:39
pdettori added a commit to pdettori/moca that referenced this pull request Sep 22, 2026
…call site

Review on rossoctl#330 found the first version fixed one copy of the stale claim and then
pointed at another. It deferred to firecrackerCgroupArgs' doc comment, which was
byte-identical to base and still asserted the function returns "--cgroup
memory.max=<bytes> (D1: the flag that actually creates the per-VM cgroup at all)" --
the exact claim the PR exists to remove. The contradiction moved one hop and gained an
explicit pointer aimed at the stale side.

So the correction now lands on the function, where godoc renders it and where a reader
following any pointer arrives:

- firecrackerCgroupArgs' doc comment: says what it returns (two flags), that it creates
  and bounds nothing, that rossoctl#319 removed --cgroup, and how D1's bound survives via
  cgroupPool. Three clauses were stale, not one: "create and bound this VM's own
  cgroup", the --cgroup description, and "so a test can assert the memory bound" -- that
  test asserts the bound off the pool and asserts flags-only about this function.
- The call site shrinks to a bare pointer. Most of what it carried belongs on the
  function, and describing what a previous version of the comment claimed left the next
  reader two dead states to carry instead of one; git blame already holds that.
- launcher_chv.go: dropped the "like firecrackerCgroupArgs" analogy, which inherited the
  pre-rossoctl#319 property. CHV's -p MemoryMax= still carries a bound; the function it compared
  itself to no longer does. Replaced with the asymmetry stated explicitly, so neither arm
  is read off the other.
- cgroup.go: three more of the same class, found by sweeping the package rather than the
  diff. The header's arm-agnostic paragraph pointed at firecrackerCgroupArgs while
  asserting jailer makes the cgroup; the slice tree diagram showed only the pre-rossoctl#319
  vm-<n> form; and vmIDPrefix claimed "The Firecracker arm's cgroup directory IS that
  id", contradicted by pooledCgroupPrefix 28 lines below in the same const block, which
  says a vm-<n> cgroup at startup is an orphan.

Attribution corrected throughout: rossoctl#258 is the measurement issue that produced the
195.52 ms figure, rossoctl#319 is the PR that dropped the flag.

Comment-only: every changed line in the diff is a comment, checked mechanically.
gofmt clean, go build and go vet clean, full vmpool suite passes with -count=1 (the
cgroup-filtered run matched 32 tests, counted rather than trusting a bare ok), all 9
remote-worker packages pass, make lint passes.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
pdettori added a commit that referenced this pull request Sep 22, 2026
#319 follow-up)

The comment above the firecrackerCgroupArgs call still described the flag set
as "--cgroup-version/--parent-cgroup/--cgroup" and called --cgroup "the
load-bearing one of three". That was accurate until #258/#319, which removed
--cgroup deliberately: creating a cgroup per VM cost 195.52 ms of a 253 ms
Destroy at 64 slots plus an unbounded dying-cgroup population.

So the caller's comment contradicted the callee's, which opens with "NO
--cgroup (#258)". Whichever a reader saw first, the other looked like a bug —
and the plausible reaction to the stale one is to "restore" the flag and
reintroduce a 3.25x regression.

Corrected, and says why D1's per-VM memory bound still holds without it:
cgroupPool writes memory.max = PerVMBytes on the pooled cgroup the jailer
relocates into, rather than jailer writing it on a fresh one.

Comment only; no behaviour change. `go build ./...` clean, and the full vmpool
suite passes (44 cgroup-matching tests, verified non-vacuous).

Refs #258 #319

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