Skip to content

docs(258): design note for pooled VM cgroups, with the decision it needs - #318

Merged
pdettori merged 1 commit into
rossoctl:mainfrom
pdettori:docs/258-pooled-vm-cgroups
Sep 22, 2026
Merged

pdettori merged 1 commit into
rossoctl:mainfrom
pdettori:docs/258-pooled-vm-cgroups

Conversation

@pdettori

Copy link
Copy Markdown
Member

Design note only — no code. Part of #258.

Proposes replacing per-VM cgroup create/destroy with a free list of long-lived cgroups, and
puts one question to a reviewer before any implementation.

Why this and not something cheaper

Task 3.1's decomposition made the cgroup rmdir the largest single cost in an Exec: 195.52 ms of
a 253 ms Destroy at 64 slots
, growing 91x across a 16x concurrency range because cgroup removal
is kernel-serialised. Two cheaper fixes were built, measured, and both failed:

  • deferring the rmdir conserves the time into Acquire (16 slots: −14.76 Destroy, +14.41
    Acquire) and makes 64 slots worse (−79/+101, net +24 ms);
  • reclaiming charges before rmdir works (dying cgroups −64/rung vs +64..73) but costs ~1.2 s
    of synchronous writeback per VM
    and hung worker startup.

The same churn also parks 12,400+ dying cgroups, which degraded this host ~24% at 64 slots
over a single session. Not creating the cgroups addresses the latency and the degradation together,
with no reclaim work — a cgroup that never dies cannot accumulate.

The decision this needs

A reused cgroup inherits its predecessor's page-cache charges, and CgroupMemoryMaxBytes is
PerVMBytes — per D1, "the SAME figure admission control charges per VM".

Confirmed directly: re-reading the golden snapshot from inside a fresh cgroup charged it 0 MiB,
because those pages were already resident and charged to whichever cgroup first faulted them. The
snapshot rootfs alone is 403 MiB against a 288 MiB per-VM limit. So reuse and a per-VM
memory.max are incompatible.

§4 lays out three options with what each costs. A — drop memory.max on pooled cgroups and
rely on admitLocked's MaxCommittedBytes gate — is my recommendation, because the bound is not
lost, only its second enforcement point.

§4 also asks a question I could not settle by reading, and whose answer changes what option A gives
up: is that per-VM limit doing useful work today, or already causing reclaim of guest memory?
The guest's RAM is a MAP_SHARED mapping of the snapshot memory file — page cache, charged to the
cgroup — and the 1.2 s writeback measured on a dying VM cgroup shows these accumulate substantial
dirty cache inside that limit. If it is routinely hit, option A removes a cost rather than a
protection.

Two things reviewers should push on

  • §5 inverts an invariant. Today a vm-N cgroup present at startup is an orphan to be
    removed. With pooled cgroups the directory is expected to persist; what must not persist is a dead
    VMM inside one. isPoolVMCgroupDirName is already "the single authority" on the name and handles
    two arms, so a third form is a small explicit change — but the sweep's meaning changes.
  • §3 deliberately does not size a pool. There is no slot concept in vmpool to size one from
    (nextIDLocked mints from a monotonic counter; concurrency is bounded by admitLocked), so a
    free list lets the high-water mark be the peak concurrent VM count without anything predicting it.

What it does not change

The jail and its id-collision guard, execGate and the spec §4.3 mount constraint, and Destroy's
kill+cmd.Wait floor of ~34 ms — a SIGKILLed Firecracker holding a 256 MiB MAP_SHARED mapping
must have that address space torn down before it is reaped. This change does not approach that
floor, and §6 says so explicitly so the expected gain is not overstated.

🤖 Generated with Claude Code

@pdettori

Copy link
Copy Markdown
Member Author

Housekeeping

The branch carries the reclaim-flag feat and its revert ahead of the docs commit. Net diff is just the note, so I'll squash-merge (or rebase to the single f1e862e if you'd rather keep it clean on your side). Either way the revert's findings are preserved in the note.

§4 decision: A, with B underneath it

  • No memory.max on pooled cgroups. admitLocked remains the bound. I'm comfortable giving up the per-VM kernel ceiling because it isn't protecting against a runaway guest — guest RAM is capped by the Firecracker config at 256 MiB regardless. It only guards against a runaway VMM process, which is a narrow failure mode, and the note's own numbers (256 MiB guest as charged page cache, 288 MiB limit, 617 MiB dirty on a dying cgroup) suggest the limit is probably being hit today and reclaiming the guest's own working set.
  • Keep a kernel ceiling where it matters: memory.max on the parent slice. Size it to MaxCommittedBytes plus headroom for the shared snapshot page cache (~1.1 GiB for rootfs + memory file). Slice-level reclaim under pressure would evict exactly the pages every restore reads, so don't set it tight to the budget. This gives A's throughput with B's aggregate backstop.

Precondition before code: settle the open question by measurement

The "is memory.max already doing harm" question is cheap to answer: read memory.events (max, high, oom) on live vm-N cgroups during a c=64 rung. Non-zero max confirms the limit is being hit today. Please run that once and record the result in the note before the implementation PR — it turns the justification for A from an argument into a fact.

Two things to check while you're there

  1. The "incompatible" claim may be stronger than needed. Shared read-only snapshot pages are charged to whichever cgroup first faults them — once, to one cgroup — not to every pooled cgroup. If the worker pre-reads the golden snapshot at startup from its own cgroup, no pooled cgroup ever owns those charges. What a pooled cgroup would inherit is per-VM dirty cache of files that outlive the VM (the workspace disk, per spec §4.3, is the obvious candidate). Worth confirming which of these actually pins the 12k dying cgroups. If it's the shared pages, pre-warming + per-cgroup memory.max becomes a viable option D that keeps D1 intact. That wouldn't change the decision above on its own, but it changes what we're giving up and belongs in the note.
  2. Free-list guard. Before pushing a cgroup back to the free list, check cgroup.procs is empty. kill + cmd.Wait reaps the jailer, but a stray child would otherwise be handed to the next tenant. If non-empty: don't reuse, leak it, log it, count it.

Agreed as written

pool-<n> naming rather than vm-<n>; the SweepOrphans inversion (kill members, tolerate the directory); the ~34 ms kill+wait floor explicitly not being claimed; and the §7 verification plan, especially nr_dying_descendants flat across rungs and the cheapest rung repeated last.

…surement

Proposes replacing per-VM cgroup create/destroy with a free list of long-lived cgroups.
Single commit off main; the reclaim experiment's feat+revert this branch previously carried
are preserved on feat/258-reclaim-before-rmdir and summarised in §1.

WHY HERE. Task 3.1 made the cgroup rmdir the largest single cost in an Exec -- 195.52 ms of
a 253 ms Destroy at 64 slots, growing 91x across a 16x concurrency range because cgroup
removal is kernel-serialised. Two cheaper fixes were built, measured and rejected:
deferring conserves the time into Acquire and makes 64 slots worse; reclaiming charges
before rmdir hung worker startup. The same churn also parks 12,400+ dying cgroups, which
degraded this host ~24% at 64 slots over one session.

SECTION 4 WAS A DECISION AND IS NOW A MEASUREMENT. The note previously claimed reuse and a
per-VM memory.max were incompatible, because a reused cgroup would inherit the snapshot's
page cache, and asked for a choice between dropping the per-VM ceiling, moving it to the
parent slice, or abandoning reuse. Review asked for the premise to be tested first by
reading memory.events on live vm-N cgroups. It does not hold:

  memory.events max/high/oom/oom_kill   non-zero in 0 of 306 samples (40 cgroups)
  memory.current                        mean 0.9 MiB, max 2 MiB, against a 288 MiB limit
  memory.stat file/anon/dirty           all ~0

The per-VM limit has never come near engaging, and a reused cgroup would inherit ~1 MiB
rather than ~400 MiB. The reason is structural, not luck: memfile is mlocked by the WORKER
at startup (PinMemoryFile) and the snapshot is hardlinked so it stays "a single page-cache
object shared across every VM", so a guest's MAP_SHARED mapping of already-resident pages
charges nothing to the VM. The review's own check-1 hypothesis -- that a startup pre-read
from the worker's cgroup would keep pooled cgroups clean -- already exists in the code.

So the decision is option D: keep CgroupMemoryMaxBytes = PerVMBytes on pooled cgroups. D1
is preserved exactly and no ceiling has to be given up. My earlier speculation that the
limit might already be forcing reclaim of the guest's working set is also false.

TWO CORRECTIONS THIS FORCED. The reclaim experiment's hang was attributed to ~1.2 s of
writeback per VM, measured on a synthetic cgroup deliberately charged with 617 MiB of dirty
cache. A real VM cgroup holds ~1 MiB, so that mechanism does not transfer: the failure is
reproducible (two ON rungs failed, two OFF passed) but its cause is now open, and sections 1
and 4 say so rather than leaving a wrong explanation in the record. And if each cgroup holds
~1 MiB, what pins 12-13k of them dying is not obvious -- recorded as the one loose end,
which pooling makes moot by not creating them.

ALSO FROM REVIEW: the free list must check cgroup.procs is empty before reuse. kill +
cmd.Wait reaps the jailer, but a stray child that escaped the process group would otherwise
be handed to the next tenant, inside its memory bound. Non-empty means do not reuse: leak
it, log it, count it. Leaking one cgroup is the old behaviour; handing a live stranger's
process to the next VM is not.

Unchanged from the reviewed version, and agreed there: pool-<n> naming rather than vm-<n>,
the SweepOrphans inversion (kill members, tolerate the directory), the ~34 ms kill+wait
floor explicitly not claimed, and section 7's verification plan with nr_dying_descendants
flat across rungs and the cheapest rung repeated last.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
@pdettori
pdettori force-pushed the docs/258-pooled-vm-cgroups branch from f1e862e to 3d184d6 Compare September 22, 2026 13:38
@pdettori

Copy link
Copy Markdown
Member Author

Ran the precondition. The premise of §4 does not hold — so the decision is moot and D1 survives.

Thanks for insisting on measuring before coding; the measurement inverts the section.

Sampled live vm-N cgroups during a c=64 rung — 306 samples across 40 distinct cgroups:

signal result
memory.events max non-zero in 0 of 306
high / oom / oom_kill 0 of 306
memory.current mean 0.9 MiB, p50 1, max 2 MiB (limit is 288 MiB)
memory.stat file / anon / file_dirty / file_writeback all ~0

The per-VM limit is never approached, and a VM cgroup charges about 1 MiB. So:

  • Your check 1 was right, and the data goes further than "charged once, to one cgroup": those
    pages are charged to the worker. PinMemoryFile mlocks memfile at worker startup
    (cmd/microvm-worker/main.go), and the snapshot is hardlinked into each jail precisely so it
    stays "a single page-cache object shared across every VM restored from this snapshot" (spec
    §7.3 / Task 14). A guest's MAP_SHARED mapping of already-resident, already-charged pages
    charges nothing to the VM. The startup pre-read you proposed as option D's precondition already
    exists in the code.
  • So a reused cgroup inherits ~1 MiB, not ~400 MiB. Reuse and per-VM memory.max are
    compatible
    , and I have taken option D: keep CgroupMemoryMaxBytes = PerVMBytes. No ceiling
    given up, D1 intact, and neither A nor B is needed.
  • My speculation that the limit might already be forcing reclaim of the guest's working set is
    false — nothing hit, nothing reclaimed, no OOM.

Your reasoning for A-with-B-underneath was sound on the premise as I had written it. It just turned
out the premise was mine, not the system's.

Two corrections this forced, both now in the note

  1. The reclaim experiment's stated mechanism is withdrawn. I attributed the startup hang to
    ~1.2 s of writeback per VM — measured on a synthetic cgroup I had deliberately charged with
    617 MiB of dirty cache. A real VM cgroup holds ~1 MiB, so that does not transfer. The failure
    is reproducible (two ON rungs failed, two OFF passed) but its cause is now open, and §1 and
    §4 say so rather than leaving a plausible-but-unsupported explanation in the record.
  2. A new loose end: if each cgroup holds ~1 MiB, what pins 12–13k of them as dying is not
    obvious. Recorded in §4. Pooling makes it moot by not creating them, so it does not block this.

Also done

  • Free-list guard added to §3, with your reasoning: check cgroup.procs is empty before reuse;
    non-empty means leak it, log it, count it. Leaking one cgroup is the old behaviour, handing a live
    stranger's process to the next tenant inside its memory bound is not.
  • Branch collapsed to a single commit off main (3d184d6), since you offered. The reclaim
    feat+revert stay on feat/258-reclaim-before-rmdir with their findings, and §1 summarises them.

One note on merging: gh pr merge is denied to me by this session's permission config, so the merge
itself needs your hand. I am proceeding to the implementation on the strength of §4 being resolved —
say the word if you would rather I wait for the merge first.

@pdettori
pdettori merged commit 4883355 into rossoctl:main Sep 22, 2026
13 checks passed
@pdettori
pdettori deleted the docs/258-pooled-vm-cgroups branch September 22, 2026 13:42
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.

1 participant